sonarium 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +271 -0
  3. package/dist/index.d.ts +1000 -0
  4. package/dist/index.js +2716 -0
  5. package/dist/index.js.map +1 -0
  6. package/dist/sonarium.iife.js +236 -0
  7. package/dist/sonarium.iife.js.map +1 -0
  8. package/package.json +63 -0
  9. package/src/core/engine.ts +468 -0
  10. package/src/core/listener.ts +61 -0
  11. package/src/core/matter-voice.ts +240 -0
  12. package/src/core/profile.ts +313 -0
  13. package/src/core/room.ts +135 -0
  14. package/src/core/scanner.ts +176 -0
  15. package/src/core/voices.ts +222 -0
  16. package/src/index.ts +74 -0
  17. package/src/interact/activate.ts +56 -0
  18. package/src/interact/drag.ts +52 -0
  19. package/src/interact/keyboard.ts +48 -0
  20. package/src/interact/midi.ts +40 -0
  21. package/src/interact/motion.ts +61 -0
  22. package/src/interact/pointer.ts +65 -0
  23. package/src/interact/scroll.ts +43 -0
  24. package/src/math/chroma.ts +111 -0
  25. package/src/math/mapping.ts +100 -0
  26. package/src/math/matter.ts +201 -0
  27. package/src/math/modular.ts +99 -0
  28. package/src/math/pulse.ts +64 -0
  29. package/src/math/scales.ts +90 -0
  30. package/src/math/util.ts +16 -0
  31. package/src/spatial/backend.ts +166 -0
  32. package/src/spatial/bus.ts +114 -0
  33. package/src/spatial/decoder.ts +63 -0
  34. package/src/spatial/encoder.ts +54 -0
  35. package/src/spatial/field.ts +75 -0
  36. package/src/spatial/perceptual.ts +43 -0
  37. package/src/spatial/room-foa.ts +81 -0
  38. package/src/spatial/rotation.ts +73 -0
  39. package/src/spatial/sh.ts +38 -0
  40. package/src/spatial/sphere.ts +36 -0
  41. package/src/themes/index.ts +60 -0
  42. package/src/types.ts +157 -0
  43. package/src/ui/gate.ts +65 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../node_modules/@babel/runtime/helpers/arrayWithHoles.js","../node_modules/@babel/runtime/helpers/iterableToArrayLimit.js","../node_modules/@babel/runtime/helpers/arrayLikeToArray.js","../node_modules/@babel/runtime/helpers/unsupportedIterableToArray.js","../node_modules/@babel/runtime/helpers/nonIterableRest.js","../node_modules/@babel/runtime/helpers/slicedToArray.js","../node_modules/@babel/runtime/helpers/classCallCheck.js","../node_modules/@babel/runtime/helpers/typeof.js","../node_modules/@babel/runtime/helpers/toPrimitive.js","../node_modules/@babel/runtime/helpers/toPropertyKey.js","../node_modules/@babel/runtime/helpers/createClass.js","../node_modules/automation-events/build/es5/bundle.js","../src/index.ts","../node_modules/tone/Tone/version.ts","../node_modules/standardized-audio-context/src/module.ts","../node_modules/standardized-audio-context/src/factories/abort-error.ts","../node_modules/standardized-audio-context/src/factories/add-active-input-connection-to-audio-node.ts","../node_modules/standardized-audio-context/src/factories/add-audio-node-connections.ts","../node_modules/standardized-audio-context/src/factories/add-audio-param-connections.ts","../node_modules/standardized-audio-context/src/globals.ts","../node_modules/standardized-audio-context/src/helpers/is-constructible.ts","../node_modules/standardized-audio-context/src/helpers/split-import-statements.ts","../node_modules/standardized-audio-context/src/factories/add-audio-worklet-module.ts","../node_modules/standardized-audio-context/src/helpers/get-value-for-key.ts","../node_modules/standardized-audio-context/src/helpers/pick-element-from-set.ts","../node_modules/standardized-audio-context/src/helpers/delete-passive-input-connection-to-audio-node.ts","../node_modules/standardized-audio-context/src/helpers/get-event-listeners-of-audio-node.ts","../node_modules/standardized-audio-context/src/helpers/set-internal-state-to-active.ts","../node_modules/standardized-audio-context/src/guards/audio-worklet-node.ts","../node_modules/standardized-audio-context/src/helpers/set-internal-state-to-passive.ts","../node_modules/standardized-audio-context/src/helpers/set-internal-state-to-passive-when-necessary.ts","../node_modules/standardized-audio-context/src/factories/add-connection-to-audio-node.ts","../node_modules/standardized-audio-context/src/factories/add-passive-input-connection-to-audio-node.ts","../node_modules/standardized-audio-context/src/factories/add-silent-connection.ts","../node_modules/standardized-audio-context/src/factories/add-unrendered-audio-worklet-node.ts","../node_modules/standardized-audio-context/src/factories/analyser-node-constructor.ts","../node_modules/standardized-audio-context/src/helpers/is-owned-by-context.ts","../node_modules/standardized-audio-context/src/factories/analyser-node-renderer-factory.ts","../node_modules/standardized-audio-context/src/helpers/test-audio-buffer-copy-channel-methods-out-of-bounds-support.ts","../node_modules/standardized-audio-context/src/factories/index-size-error.ts","../node_modules/standardized-audio-context/src/helpers/wrap-audio-buffer-get-channel-data-method.ts","../node_modules/standardized-audio-context/src/factories/audio-buffer-constructor.ts","../node_modules/standardized-audio-context/src/constants.ts","../node_modules/standardized-audio-context/src/helpers/is-active-audio-node.ts","../node_modules/standardized-audio-context/src/factories/audio-buffer-source-node-constructor.ts","../node_modules/standardized-audio-context/src/factories/audio-buffer-source-node-renderer-factory.ts","../node_modules/standardized-audio-context/src/guards/audio-buffer-source-node.ts","../node_modules/standardized-audio-context/src/guards/biquad-filter-node.ts","../node_modules/standardized-audio-context/src/guards/constant-source-node.ts","../node_modules/standardized-audio-context/src/guards/gain-node.ts","../node_modules/standardized-audio-context/src/guards/oscillator-node.ts","../node_modules/standardized-audio-context/src/guards/stereo-panner-node.ts","../node_modules/standardized-audio-context/src/helpers/get-audio-node-connections.ts","../node_modules/standardized-audio-context/src/helpers/get-audio-param-connections.ts","../node_modules/standardized-audio-context/src/helpers/deactivate-active-audio-node-input-connections.ts","../node_modules/standardized-audio-context/src/helpers/deactivate-audio-graph.ts","../node_modules/standardized-audio-context/src/helpers/is-valid-latency-hint.ts","../node_modules/standardized-audio-context/src/factories/audio-context-constructor.ts","../node_modules/standardized-audio-context/src/factories/audio-destination-node-constructor.ts","../node_modules/standardized-audio-context/src/factories/audio-destination-node-renderer-factory.ts","../node_modules/standardized-audio-context/src/factories/audio-listener-factory.ts","../node_modules/standardized-audio-context/src/guards/audio-node.ts","../node_modules/standardized-audio-context/src/guards/audio-node-output-connection.ts","../node_modules/standardized-audio-context/src/helpers/insert-element-in-set.ts","../node_modules/standardized-audio-context/src/helpers/add-active-input-connection-to-audio-param.ts","../node_modules/standardized-audio-context/src/helpers/add-passive-input-connection-to-audio-param.ts","../node_modules/standardized-audio-context/src/guards/native-audio-node-faker.ts","../node_modules/standardized-audio-context/src/helpers/connect-native-audio-node-to-native-audio-node.ts","../node_modules/standardized-audio-context/src/helpers/delete-active-input-connection.ts","../node_modules/standardized-audio-context/src/helpers/delete-active-input-connection-to-audio-param.ts","../node_modules/standardized-audio-context/src/helpers/delete-event-listeners-of-audio-node.ts","../node_modules/standardized-audio-context/src/helpers/delete-passive-input-connection-to-audio-param.ts","../node_modules/standardized-audio-context/src/helpers/disconnect-native-audio-node-from-native-audio-node.ts","../node_modules/standardized-audio-context/src/helpers/get-native-audio-node.ts","../node_modules/standardized-audio-context/src/helpers/get-native-audio-param.ts","../node_modules/standardized-audio-context/src/helpers/is-part-of-a-cycle.ts","../node_modules/standardized-audio-context/src/helpers/is-passive-audio-node.ts","../node_modules/standardized-audio-context/src/helpers/test-audio-node-disconnect-method-support.ts","../node_modules/standardized-audio-context/src/helpers/visit-each-audio-node-once.ts","../node_modules/standardized-audio-context/src/guards/native-audio-node.ts","../node_modules/standardized-audio-context/src/helpers/wrap-audio-node-disconnect-method.ts","../node_modules/standardized-audio-context/src/factories/audio-node-constructor.ts","../node_modules/standardized-audio-context/src/factories/audio-param-factory.ts","../node_modules/standardized-audio-context/src/factories/audio-param-renderer.ts","../node_modules/standardized-audio-context/src/read-only-map.ts","../node_modules/standardized-audio-context/src/factories/audio-worklet-node-constructor.ts","../node_modules/standardized-audio-context/src/helpers/copy-from-channel.ts","../node_modules/standardized-audio-context/src/helpers/copy-to-channel.ts","../node_modules/standardized-audio-context/src/helpers/create-nested-arrays.ts","../node_modules/standardized-audio-context/src/helpers/get-audio-worklet-processor.ts","../node_modules/standardized-audio-context/src/factories/audio-worklet-node-renderer-factory.ts","../node_modules/standardized-audio-context/src/factories/base-audio-context-constructor.ts","../node_modules/standardized-audio-context/src/factories/biquad-filter-node-constructor.ts","../node_modules/standardized-audio-context/src/factories/biquad-filter-node-renderer-factory.ts","../node_modules/standardized-audio-context/src/factories/cache-test-result.ts","../node_modules/standardized-audio-context/src/factories/channel-merger-node-constructor.ts","../node_modules/standardized-audio-context/src/factories/channel-merger-node-renderer-factory.ts","../node_modules/standardized-audio-context/src/factories/channel-splitter-node-constructor.ts","../node_modules/standardized-audio-context/src/factories/channel-splitter-node-renderer-factory.ts","../node_modules/standardized-audio-context/src/factories/connect-audio-param.ts","../node_modules/standardized-audio-context/src/factories/connect-multiple-outputs.ts","../node_modules/standardized-audio-context/src/factories/connected-native-audio-buffer-source-node-factory.ts","../node_modules/standardized-audio-context/src/factories/constant-source-node-constructor.ts","../node_modules/standardized-audio-context/src/factories/constant-source-node-renderer-factory.ts","../node_modules/standardized-audio-context/src/factories/convert-number-to-unsigned-long.ts","../node_modules/standardized-audio-context/src/factories/convolver-node-constructor.ts","../node_modules/standardized-audio-context/src/factories/convolver-node-renderer-factory.ts","../node_modules/standardized-audio-context/src/factories/create-native-offline-audio-context.ts","../node_modules/standardized-audio-context/src/factories/data-clone-error.ts","../node_modules/standardized-audio-context/src/helpers/detach-array-buffer.ts","../node_modules/standardized-audio-context/src/factories/decode-audio-data.ts","../node_modules/standardized-audio-context/src/factories/decrement-cycle-counter.ts","../node_modules/standardized-audio-context/src/factories/delay-node-constructor.ts","../node_modules/standardized-audio-context/src/factories/delay-node-renderer-factory.ts","../node_modules/standardized-audio-context/src/factories/delete-active-input-connection-to-audio-node.ts","../node_modules/standardized-audio-context/src/factories/delete-unrendered-audio-worklet-node.ts","../node_modules/standardized-audio-context/src/guards/delay-node.ts","../node_modules/standardized-audio-context/src/factories/detect-cycles.ts","../node_modules/standardized-audio-context/src/factories/disconnect-multiple-outputs.ts","../node_modules/standardized-audio-context/src/factories/dynamics-compressor-node-constructor.ts","../node_modules/standardized-audio-context/src/factories/dynamics-compressor-node-renderer-factory.ts","../node_modules/standardized-audio-context/src/factories/encoding-error.ts","../node_modules/standardized-audio-context/src/factories/evaluate-source.ts","../node_modules/standardized-audio-context/src/factories/event-target-constructor.ts","../node_modules/standardized-audio-context/src/factories/expose-current-frame-and-current-time.ts","../node_modules/standardized-audio-context/src/factories/fetch-source.ts","../node_modules/standardized-audio-context/src/factories/gain-node-constructor.ts","../node_modules/standardized-audio-context/src/factories/gain-node-renderer-factory.ts","../node_modules/standardized-audio-context/src/factories/get-active-audio-worklet-node-inputs.ts","../node_modules/standardized-audio-context/src/factories/get-audio-node-renderer.ts","../node_modules/standardized-audio-context/src/factories/get-audio-node-tail-time.ts","../node_modules/standardized-audio-context/src/factories/get-audio-param-renderer.ts","../node_modules/standardized-audio-context/src/factories/get-backup-offline-audio-context.ts","../node_modules/standardized-audio-context/src/factories/invalid-state-error.ts","../node_modules/standardized-audio-context/src/factories/get-native-context.ts","../node_modules/standardized-audio-context/src/factories/get-or-create-backup-offline-audio-context.ts","../node_modules/standardized-audio-context/src/factories/get-unrendered-audio-worklet-nodes.ts","../node_modules/standardized-audio-context/src/factories/invalid-access-error.ts","../node_modules/standardized-audio-context/src/helpers/wrap-iir-filter-node-get-frequency-response-method.ts","../node_modules/standardized-audio-context/src/factories/iir-filter-node-constructor.ts","../node_modules/standardized-audio-context/src/helpers/filter-buffer.ts","../node_modules/standardized-audio-context/src/factories/iir-filter-node-renderer-factory.ts","../node_modules/standardized-audio-context/src/factories/increment-cycle-counter-factory.ts","../node_modules/standardized-audio-context/src/factories/is-any-audio-context.ts","../node_modules/standardized-audio-context/src/factories/is-any-audio-node.ts","../node_modules/standardized-audio-context/src/factories/is-any-audio-param.ts","../node_modules/standardized-audio-context/src/factories/is-any-offline-audio-context.ts","../node_modules/standardized-audio-context/src/factories/is-native-audio-context.ts","../node_modules/standardized-audio-context/src/factories/is-native-audio-node.ts","../node_modules/standardized-audio-context/src/factories/is-native-audio-param.ts","../node_modules/standardized-audio-context/src/factories/is-native-context.ts","../node_modules/standardized-audio-context/src/factories/is-native-offline-audio-context.ts","../node_modules/standardized-audio-context/src/factories/is-secure-context.ts","../node_modules/standardized-audio-context/src/factories/media-element-audio-source-node-constructor.ts","../node_modules/standardized-audio-context/src/factories/media-stream-audio-destination-node-constructor.ts","../node_modules/standardized-audio-context/src/factories/media-stream-audio-source-node-constructor.ts","../node_modules/standardized-audio-context/src/factories/media-stream-track-audio-source-node-constructor.ts","../node_modules/standardized-audio-context/src/factories/minimal-audio-context-constructor.ts","../node_modules/standardized-audio-context/src/factories/minimal-base-audio-context-constructor.ts","../node_modules/standardized-audio-context/src/helpers/test-promise-support.ts","../node_modules/standardized-audio-context/src/factories/minimal-offline-audio-context-constructor.ts","../node_modules/standardized-audio-context/src/factories/monitor-connections.ts","../node_modules/standardized-audio-context/src/helpers/assign-native-audio-node-option.ts","../node_modules/standardized-audio-context/src/helpers/assign-native-audio-node-options.ts","../node_modules/standardized-audio-context/src/helpers/test-analyser-node-get-float-time-domain-data-method-support.ts","../node_modules/standardized-audio-context/src/helpers/wrap-analyser-node-get-float-time-domain-data-method.ts","../node_modules/standardized-audio-context/src/factories/native-analyser-node-factory.ts","../node_modules/standardized-audio-context/src/factories/native-audio-buffer-constructor.ts","../node_modules/standardized-audio-context/src/helpers/assign-native-audio-node-audio-param-value.ts","../node_modules/standardized-audio-context/src/helpers/wrap-audio-buffer-source-node-start-method-consecutive-calls.ts","../node_modules/standardized-audio-context/src/helpers/wrap-audio-scheduled-source-node-start-method-negative-parameters.ts","../node_modules/standardized-audio-context/src/helpers/wrap-audio-scheduled-source-node-stop-method-negative-parameters.ts","../node_modules/standardized-audio-context/src/factories/native-audio-buffer-source-node-factory.ts","../node_modules/standardized-audio-context/src/factories/native-audio-context-constructor.ts","../node_modules/standardized-audio-context/src/factories/native-audio-destination-node.ts","../node_modules/standardized-audio-context/src/factories/native-audio-worklet-node-constructor.ts","../node_modules/standardized-audio-context/src/helpers/test-clonability-of-audio-worklet-node-options.ts","../node_modules/standardized-audio-context/src/factories/native-audio-worklet-node-factory.ts","../node_modules/standardized-audio-context/src/helpers/compute-buffer-size.ts","../node_modules/standardized-audio-context/src/helpers/clone-audio-worklet-node-options.ts","../node_modules/standardized-audio-context/src/helpers/create-audio-worklet-processor-promise.ts","../node_modules/standardized-audio-context/src/helpers/create-audio-worklet-processor.ts","../node_modules/standardized-audio-context/src/factories/native-audio-worklet-node-faker-factory.ts","../node_modules/standardized-audio-context/src/factories/native-biquad-filter-node.ts","../node_modules/standardized-audio-context/src/factories/native-channel-merger-node-factory.ts","../node_modules/standardized-audio-context/src/helpers/wrap-channel-splitter-node.ts","../node_modules/standardized-audio-context/src/factories/native-channel-splitter-node.ts","../node_modules/standardized-audio-context/src/factories/native-constant-source-node-factory.ts","../node_modules/standardized-audio-context/src/helpers/intercept-connections.ts","../node_modules/standardized-audio-context/src/factories/native-constant-source-node-faker-factory.ts","../node_modules/standardized-audio-context/src/factories/native-convolver-node-factory.ts","../node_modules/standardized-audio-context/src/factories/native-delay-node.ts","../node_modules/standardized-audio-context/src/factories/native-dynamics-compressor-node-factory.ts","../node_modules/standardized-audio-context/src/factories/native-gain-node.ts","../node_modules/standardized-audio-context/src/factories/native-iir-filter-node-factory.ts","../node_modules/standardized-audio-context/src/factories/native-iir-filter-node-faker-factory.ts","../node_modules/standardized-audio-context/src/factories/native-media-element-audio-source-node.ts","../node_modules/standardized-audio-context/src/factories/native-media-stream-audio-destination-node.ts","../node_modules/standardized-audio-context/src/factories/native-media-stream-audio-source-node.ts","../node_modules/standardized-audio-context/src/factories/native-media-stream-track-audio-source-node-factory.ts","../node_modules/standardized-audio-context/src/factories/native-offline-audio-context-constructor.ts","../node_modules/standardized-audio-context/src/factories/native-oscillator-node-factory.ts","../node_modules/standardized-audio-context/src/factories/native-panner-node-factory.ts","../node_modules/standardized-audio-context/src/factories/native-panner-node-faker-factory.ts","../node_modules/standardized-audio-context/src/factories/native-periodic-wave-factory.ts","../node_modules/standardized-audio-context/src/factories/native-script-processor-node.ts","../node_modules/standardized-audio-context/src/factories/native-stereo-panner-node-factory.ts","../node_modules/standardized-audio-context/src/factories/native-stereo-panner-node-faker-factory.ts","../node_modules/standardized-audio-context/src/factories/native-wave-shaper-node-factory.ts","../node_modules/standardized-audio-context/src/factories/native-wave-shaper-node-faker-factory.ts","../node_modules/standardized-audio-context/src/factories/not-supported-error.ts","../node_modules/standardized-audio-context/src/factories/offline-audio-context-constructor.ts","../node_modules/standardized-audio-context/src/factories/oscillator-node-constructor.ts","../node_modules/standardized-audio-context/src/factories/oscillator-node-renderer-factory.ts","../node_modules/standardized-audio-context/src/factories/panner-node-constructor.ts","../node_modules/standardized-audio-context/src/factories/panner-node-renderer-factory.ts","../node_modules/standardized-audio-context/src/factories/periodic-wave-constructor.ts","../node_modules/standardized-audio-context/src/factories/render-automation.ts","../node_modules/standardized-audio-context/src/factories/render-inputs-of-audio-node.ts","../node_modules/standardized-audio-context/src/factories/render-inputs-of-audio-param.ts","../node_modules/standardized-audio-context/src/factories/render-native-offline-audio-context.ts","../node_modules/standardized-audio-context/src/factories/set-active-audio-worklet-node-inputs.ts","../node_modules/standardized-audio-context/src/factories/set-audio-node-tail-time.ts","../node_modules/standardized-audio-context/src/factories/start-rendering.ts","../node_modules/standardized-audio-context/src/factories/stereo-panner-node-constructor.ts","../node_modules/standardized-audio-context/src/factories/stereo-panner-node-renderer-factory.ts","../node_modules/standardized-audio-context/src/factories/test-audio-buffer-constructor-support.ts","../node_modules/standardized-audio-context/src/factories/test-audio-worklet-processor-post-message-support.ts","../node_modules/standardized-audio-context/src/factories/test-offline-audio-context-current-time-support.ts","../node_modules/standardized-audio-context/src/factories/unknown-error.ts","../node_modules/standardized-audio-context/src/factories/wave-shaper-node-constructor.ts","../node_modules/standardized-audio-context/src/factories/wave-shaper-node-renderer-factory.ts","../node_modules/standardized-audio-context/src/factories/window.ts","../node_modules/standardized-audio-context/src/factories/wrap-audio-buffer-copy-channel-methods.ts","../node_modules/standardized-audio-context/src/factories/wrap-audio-buffer-copy-channel-methods-out-of-bounds.ts","../node_modules/standardized-audio-context/src/factories/wrap-audio-buffer-source-node-stop-method-nullified-buffer.ts","../node_modules/standardized-audio-context/src/factories/wrap-channel-merger-node.ts","../node_modules/standardized-audio-context/src/helpers/get-first-sample.ts","../node_modules/standardized-audio-context/src/helpers/is-dc-curve.ts","../node_modules/standardized-audio-context/src/helpers/overwrite-accessors.ts","../node_modules/standardized-audio-context/src/helpers/sanitize-audio-worklet-node-options.ts","../node_modules/standardized-audio-context/src/helpers/sanitize-channel-splitter-options.ts","../node_modules/standardized-audio-context/src/helpers/sanitize-periodic-wave-options.ts","../node_modules/standardized-audio-context/src/helpers/set-value-at-time-until-possible.ts","../node_modules/standardized-audio-context/src/helpers/test-audio-buffer-source-node-start-method-consecutive-calls-support.ts","../node_modules/standardized-audio-context/src/helpers/test-audio-buffer-source-node-start-method-offset-clamping-support.ts","../node_modules/standardized-audio-context/src/helpers/test-audio-buffer-source-node-stop-method-nullified-buffer-support.ts","../node_modules/standardized-audio-context/src/helpers/test-audio-scheduled-source-node-start-method-negative-parameters-support.ts","../node_modules/standardized-audio-context/src/helpers/test-audio-scheduled-source-node-stop-method-consecutive-calls-support.ts","../node_modules/standardized-audio-context/src/helpers/test-audio-scheduled-source-node-stop-method-negative-parameters-support.ts","../node_modules/standardized-audio-context/src/helpers/test-audio-worklet-node-options-clonability.ts","../node_modules/standardized-audio-context/src/helpers/wrap-audio-buffer-source-node-start-method-offset-clamping.ts","../node_modules/standardized-audio-context/src/helpers/wrap-audio-scheduled-source-node-stop-method-consecutive-calls.ts","../node_modules/standardized-audio-context/src/helpers/wrap-event-listener.ts","../node_modules/tone/Tone/core/util/TypeCheck.ts","../node_modules/tone/Tone/core/util/Debug.ts","../node_modules/tone/Tone/core/context/AudioContext.ts","../node_modules/tslib/tslib.es6.mjs","../node_modules/tone/Tone/core/clock/Ticker.ts","../node_modules/tone/Tone/core/util/AdvancedTypeCheck.ts","../node_modules/tone/Tone/core/util/Defaults.ts","../node_modules/tone/Tone/core/Tone.ts","../node_modules/tone/Tone/core/util/Math.ts","../node_modules/tone/Tone/core/util/Timeline.ts","../node_modules/tone/Tone/core/context/ContextInitialization.ts","../node_modules/tone/Tone/core/util/Emitter.ts","../node_modules/tone/Tone/core/context/BaseContext.ts","../node_modules/tone/Tone/core/context/Context.ts","../node_modules/tone/Tone/core/context/DummyContext.ts","../node_modules/tone/Tone/core/util/Interface.ts","../node_modules/tone/Tone/core/context/ToneAudioBuffer.ts","../node_modules/tone/Tone/core/context/OfflineContext.ts","../node_modules/tone/Tone/core/Global.ts","../node_modules/tone/Tone/core/type/Conversions.ts","../node_modules/tone/Tone/core/type/TimeBase.ts","../node_modules/tone/Tone/core/type/Time.ts","../node_modules/tone/Tone/core/type/Frequency.ts","../node_modules/tone/Tone/core/type/TransportTime.ts","../node_modules/tone/Tone/core/context/ToneWithContext.ts","../node_modules/tone/Tone/core/util/StateTimeline.ts","../node_modules/tone/Tone/core/context/Param.ts","../node_modules/tone/Tone/core/context/ToneAudioNode.ts","../node_modules/tone/Tone/core/context/Gain.ts","../node_modules/tone/Tone/source/OneShotSource.ts","../node_modules/tone/Tone/signal/ToneConstantSource.ts","../node_modules/tone/Tone/signal/Signal.ts","../node_modules/tone/Tone/core/clock/TickParam.ts","../node_modules/tone/Tone/core/clock/TickSignal.ts","../node_modules/tone/Tone/core/clock/TickSource.ts","../node_modules/tone/Tone/core/clock/Clock.ts","../node_modules/tone/Tone/core/context/Delay.ts","../node_modules/tone/Tone/component/channel/Volume.ts","../node_modules/tone/Tone/core/context/Destination.ts","../node_modules/tone/Tone/core/context/Listener.ts","../node_modules/tone/Tone/core/context/ToneAudioBuffers.ts","../node_modules/tone/Tone/core/type/Ticks.ts","../node_modules/tone/Tone/core/util/Draw.ts","../node_modules/tone/Tone/core/util/IntervalTimeline.ts","../node_modules/tone/Tone/core/util/TimelineValue.ts","../node_modules/tone/Tone/signal/SignalOperator.ts","../node_modules/tone/Tone/signal/WaveShaper.ts","../node_modules/tone/Tone/signal/Pow.ts","../node_modules/tone/Tone/core/clock/TransportEvent.ts","../node_modules/tone/Tone/core/clock/TransportRepeatEvent.ts","../node_modules/tone/Tone/core/clock/Transport.ts","../node_modules/tone/Tone/source/Source.ts","../node_modules/tone/Tone/source/buffer/ToneBufferSource.ts","../node_modules/tone/Tone/source/Noise.ts","../node_modules/tone/Tone/source/oscillator/OscillatorInterface.ts","../node_modules/tone/Tone/source/oscillator/ToneOscillatorNode.ts","../node_modules/tone/Tone/source/oscillator/Oscillator.ts","../node_modules/tone/Tone/signal/AudioToGain.ts","../node_modules/tone/Tone/signal/Multiply.ts","../node_modules/tone/Tone/source/oscillator/AMOscillator.ts","../node_modules/tone/Tone/source/oscillator/FMOscillator.ts","../node_modules/tone/Tone/source/oscillator/PulseOscillator.ts","../node_modules/tone/Tone/source/oscillator/FatOscillator.ts","../node_modules/tone/Tone/source/oscillator/PWMOscillator.ts","../node_modules/tone/Tone/source/oscillator/OmniOscillator.ts","../node_modules/tone/Tone/signal/Add.ts","../node_modules/tone/Tone/signal/Scale.ts","../node_modules/tone/Tone/signal/Zero.ts","../node_modules/tone/Tone/source/oscillator/LFO.ts","../node_modules/tone/Tone/core/util/Decorator.ts","../node_modules/tone/Tone/source/buffer/Player.ts","../node_modules/tone/Tone/signal/GainToAudio.ts","../node_modules/tone/Tone/component/envelope/Envelope.ts","../node_modules/tone/Tone/instrument/Instrument.ts","../node_modules/tone/Tone/instrument/Monophonic.ts","../node_modules/tone/Tone/component/envelope/AmplitudeEnvelope.ts","../node_modules/tone/Tone/instrument/Synth.ts","../node_modules/tone/Tone/instrument/ModulationSynth.ts","../node_modules/tone/Tone/component/filter/BiquadFilter.ts","../node_modules/tone/Tone/component/filter/Filter.ts","../node_modules/tone/Tone/instrument/FMSynth.ts","../node_modules/tone/Tone/instrument/MembraneSynth.ts","../node_modules/tone/Tone/instrument/NoiseSynth.ts","../node_modules/tone/Tone/core/worklet/WorkletGlobalScope.ts","../node_modules/tone/Tone/core/worklet/ToneAudioWorklet.ts","../node_modules/tone/Tone/core/worklet/ToneAudioWorkletProcessor.worklet.ts","../node_modules/tone/Tone/core/worklet/SingleIOProcessor.worklet.ts","../node_modules/tone/Tone/core/worklet/DelayLine.worklet.ts","../node_modules/tone/Tone/component/filter/FeedbackCombFilter.worklet.ts","../node_modules/tone/Tone/component/filter/FeedbackCombFilter.ts","../node_modules/tone/Tone/component/filter/OnePoleFilter.ts","../node_modules/tone/Tone/component/filter/LowpassCombFilter.ts","../node_modules/tone/Tone/instrument/PluckSynth.ts","../node_modules/tone/Tone/instrument/Sampler.ts","../node_modules/tone/Tone/event/ToneEvent.ts","../node_modules/tone/Tone/event/Loop.ts","../node_modules/tone/Tone/component/channel/CrossFade.ts","../node_modules/tone/Tone/effect/Effect.ts","../node_modules/tone/Tone/component/channel/Panner.ts","../node_modules/tone/Tone/effect/BitCrusher.worklet.ts","../node_modules/tone/Tone/component/channel/Split.ts","../node_modules/tone/Tone/component/channel/Merge.ts","../node_modules/tone/Tone/effect/Freeverb.ts","../node_modules/tone/Tone/effect/JCReverb.ts","../node_modules/tone/Tone/effect/Reverb.ts","../node_modules/tone/Tone/component/channel/Solo.ts","../node_modules/tone/Tone/component/channel/PanVol.ts","../node_modules/tone/Tone/component/channel/Channel.ts","../node_modules/tone/Tone/component/channel/Panner3D.ts","../node_modules/tone/Tone/component/dynamics/Compressor.ts","../node_modules/tone/Tone/component/dynamics/Limiter.ts","../node_modules/tone/Tone/index.ts","../src/math/util.ts","../src/math/scales.ts","../src/math/modular.ts","../src/math/chroma.ts","../src/math/pulse.ts","../src/themes/index.ts","../src/ui/gate.ts","../src/spatial/sh.ts","../src/spatial/decoder.ts","../src/spatial/rotation.ts","../src/spatial/bus.ts","../src/spatial/encoder.ts","../src/spatial/sphere.ts","../src/spatial/perceptual.ts","../src/spatial/room-foa.ts","../src/spatial/backend.ts","../src/spatial/field.ts","../src/math/mapping.ts","../src/core/listener.ts","../src/core/room.ts","../src/math/matter.ts","../src/core/profile.ts","../src/core/scanner.ts","../src/core/matter-voice.ts","../src/core/voices.ts","../src/interact/pointer.ts","../src/interact/activate.ts","../src/interact/keyboard.ts","../src/interact/scroll.ts","../src/interact/motion.ts","../src/interact/drag.ts","../src/interact/midi.ts","../src/core/engine.ts"],"sourcesContent":["function _arrayWithHoles(r) {\n if (Array.isArray(r)) return r;\n}\nmodule.exports = _arrayWithHoles, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","function _iterableToArrayLimit(r, l) {\n var t = null == r ? null : \"undefined\" != typeof Symbol && r[Symbol.iterator] || r[\"@@iterator\"];\n if (null != t) {\n var e,\n n,\n i,\n u,\n a = [],\n f = !0,\n o = !1;\n try {\n if (i = (t = t.call(r)).next, 0 === l) {\n if (Object(t) !== t) return;\n f = !1;\n } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);\n } catch (r) {\n o = !0, n = r;\n } finally {\n try {\n if (!f && null != t[\"return\"] && (u = t[\"return\"](), Object(u) !== u)) return;\n } finally {\n if (o) throw n;\n }\n }\n return a;\n }\n}\nmodule.exports = _iterableToArrayLimit, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","function _arrayLikeToArray(r, a) {\n (null == a || a > r.length) && (a = r.length);\n for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];\n return n;\n}\nmodule.exports = _arrayLikeToArray, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","var arrayLikeToArray = require(\"./arrayLikeToArray.js\");\nfunction _unsupportedIterableToArray(r, a) {\n if (r) {\n if (\"string\" == typeof r) return arrayLikeToArray(r, a);\n var t = {}.toString.call(r).slice(8, -1);\n return \"Object\" === t && r.constructor && (t = r.constructor.name), \"Map\" === t || \"Set\" === t ? Array.from(r) : \"Arguments\" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? arrayLikeToArray(r, a) : void 0;\n }\n}\nmodule.exports = _unsupportedIterableToArray, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","function _nonIterableRest() {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\nmodule.exports = _nonIterableRest, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","var arrayWithHoles = require(\"./arrayWithHoles.js\");\nvar iterableToArrayLimit = require(\"./iterableToArrayLimit.js\");\nvar unsupportedIterableToArray = require(\"./unsupportedIterableToArray.js\");\nvar nonIterableRest = require(\"./nonIterableRest.js\");\nfunction _slicedToArray(r, e) {\n return arrayWithHoles(r) || iterableToArrayLimit(r, e) || unsupportedIterableToArray(r, e) || nonIterableRest();\n}\nmodule.exports = _slicedToArray, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","function _classCallCheck(a, n) {\n if (!(a instanceof n)) throw new TypeError(\"Cannot call a class as a function\");\n}\nmodule.exports = _classCallCheck, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","function _typeof(o) {\n \"@babel/helpers - typeof\";\n\n return module.exports = _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) {\n return typeof o;\n } : function (o) {\n return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o;\n }, module.exports.__esModule = true, module.exports[\"default\"] = module.exports, _typeof(o);\n}\nmodule.exports = _typeof, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","var _typeof = require(\"./typeof.js\")[\"default\"];\nfunction toPrimitive(t, r) {\n if (\"object\" != _typeof(t) || !t) return t;\n var e = t[Symbol.toPrimitive];\n if (void 0 !== e) {\n var i = e.call(t, r || \"default\");\n if (\"object\" != _typeof(i)) return i;\n throw new TypeError(\"@@toPrimitive must return a primitive value.\");\n }\n return (\"string\" === r ? String : Number)(t);\n}\nmodule.exports = toPrimitive, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","var _typeof = require(\"./typeof.js\")[\"default\"];\nvar toPrimitive = require(\"./toPrimitive.js\");\nfunction toPropertyKey(t) {\n var i = toPrimitive(t, \"string\");\n return \"symbol\" == _typeof(i) ? i : i + \"\";\n}\nmodule.exports = toPropertyKey, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","var toPropertyKey = require(\"./toPropertyKey.js\");\nfunction _defineProperties(e, r) {\n for (var t = 0; t < r.length; t++) {\n var o = r[t];\n o.enumerable = o.enumerable || !1, o.configurable = !0, \"value\" in o && (o.writable = !0), Object.defineProperty(e, toPropertyKey(o.key), o);\n }\n}\nfunction _createClass(e, r, t) {\n return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, \"prototype\", {\n writable: !1\n }), e;\n}\nmodule.exports = _createClass, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@babel/runtime/helpers/slicedToArray'), require('@babel/runtime/helpers/classCallCheck'), require('@babel/runtime/helpers/createClass')) :\n typeof define === 'function' && define.amd ? define(['exports', '@babel/runtime/helpers/slicedToArray', '@babel/runtime/helpers/classCallCheck', '@babel/runtime/helpers/createClass'], factory) :\n (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.automationEvents = {}, global._slicedToArray, global._classCallCheck, global._createClass));\n})(this, (function (exports, _slicedToArray, _classCallCheck, _createClass) { 'use strict';\n\n var createExtendedExponentialRampToValueAutomationEvent = function createExtendedExponentialRampToValueAutomationEvent(value, endTime, insertTime) {\n return {\n endTime: endTime,\n insertTime: insertTime,\n type: 'exponentialRampToValue',\n value: value\n };\n };\n\n var createExtendedLinearRampToValueAutomationEvent = function createExtendedLinearRampToValueAutomationEvent(value, endTime, insertTime) {\n return {\n endTime: endTime,\n insertTime: insertTime,\n type: 'linearRampToValue',\n value: value\n };\n };\n\n var createSetValueAutomationEvent = function createSetValueAutomationEvent(value, startTime) {\n return {\n startTime: startTime,\n type: 'setValue',\n value: value\n };\n };\n\n var createSetValueCurveAutomationEvent = function createSetValueCurveAutomationEvent(values, startTime, duration) {\n return {\n duration: duration,\n startTime: startTime,\n type: 'setValueCurve',\n values: values\n };\n };\n\n var getTargetValueAtTime = function getTargetValueAtTime(time, valueAtStartTime, _ref) {\n var startTime = _ref.startTime,\n target = _ref.target,\n timeConstant = _ref.timeConstant;\n return target + (valueAtStartTime - target) * Math.exp((startTime - time) / timeConstant);\n };\n\n var isExponentialRampToValueAutomationEvent = function isExponentialRampToValueAutomationEvent(automationEvent) {\n return automationEvent.type === 'exponentialRampToValue';\n };\n\n var isLinearRampToValueAutomationEvent = function isLinearRampToValueAutomationEvent(automationEvent) {\n return automationEvent.type === 'linearRampToValue';\n };\n\n var isAnyRampToValueAutomationEvent = function isAnyRampToValueAutomationEvent(automationEvent) {\n return isExponentialRampToValueAutomationEvent(automationEvent) || isLinearRampToValueAutomationEvent(automationEvent);\n };\n\n var isSetValueAutomationEvent = function isSetValueAutomationEvent(automationEvent) {\n return automationEvent.type === 'setValue';\n };\n\n var isSetValueCurveAutomationEvent = function isSetValueCurveAutomationEvent(automationEvent) {\n return automationEvent.type === 'setValueCurve';\n };\n\n var _getValueOfAutomationEventAtIndexAtTime = function getValueOfAutomationEventAtIndexAtTime(automationEvents, index, time, defaultValue) {\n var automationEvent = automationEvents[index];\n return automationEvent === undefined ? defaultValue : isAnyRampToValueAutomationEvent(automationEvent) || isSetValueAutomationEvent(automationEvent) ? automationEvent.value : isSetValueCurveAutomationEvent(automationEvent) ? automationEvent.values[automationEvent.values.length - 1] : getTargetValueAtTime(time, _getValueOfAutomationEventAtIndexAtTime(automationEvents, index - 1, automationEvent.startTime, defaultValue), automationEvent);\n };\n\n var getEndTimeAndValueOfPreviousAutomationEvent = function getEndTimeAndValueOfPreviousAutomationEvent(automationEvents, index, currentAutomationEvent, nextAutomationEvent, defaultValue) {\n return currentAutomationEvent === undefined ? [nextAutomationEvent.insertTime, defaultValue] : isAnyRampToValueAutomationEvent(currentAutomationEvent) ? [currentAutomationEvent.endTime, currentAutomationEvent.value] : isSetValueAutomationEvent(currentAutomationEvent) ? [currentAutomationEvent.startTime, currentAutomationEvent.value] : isSetValueCurveAutomationEvent(currentAutomationEvent) ? [currentAutomationEvent.startTime + currentAutomationEvent.duration, currentAutomationEvent.values[currentAutomationEvent.values.length - 1]] : [currentAutomationEvent.startTime, _getValueOfAutomationEventAtIndexAtTime(automationEvents, index - 1, currentAutomationEvent.startTime, defaultValue)];\n };\n\n var isCancelAndHoldAutomationEvent = function isCancelAndHoldAutomationEvent(automationEvent) {\n return automationEvent.type === 'cancelAndHold';\n };\n\n var isCancelScheduledValuesAutomationEvent = function isCancelScheduledValuesAutomationEvent(automationEvent) {\n return automationEvent.type === 'cancelScheduledValues';\n };\n\n var getEventTime = function getEventTime(automationEvent) {\n if (isCancelAndHoldAutomationEvent(automationEvent) || isCancelScheduledValuesAutomationEvent(automationEvent)) {\n return automationEvent.cancelTime;\n }\n if (isExponentialRampToValueAutomationEvent(automationEvent) || isLinearRampToValueAutomationEvent(automationEvent)) {\n return automationEvent.endTime;\n }\n return automationEvent.startTime;\n };\n\n var getExponentialRampValueAtTime = function getExponentialRampValueAtTime(time, startTime, valueAtStartTime, _ref) {\n var endTime = _ref.endTime,\n value = _ref.value;\n if (valueAtStartTime === value) {\n return value;\n }\n if (0 < valueAtStartTime && 0 < value || valueAtStartTime < 0 && value < 0) {\n return valueAtStartTime * Math.pow(value / valueAtStartTime, (time - startTime) / (endTime - startTime));\n }\n return time < endTime ? valueAtStartTime : value;\n };\n\n var getLinearRampValueAtTime = function getLinearRampValueAtTime(time, startTime, valueAtStartTime, _ref) {\n var endTime = _ref.endTime,\n value = _ref.value;\n return valueAtStartTime + (time - startTime) / (endTime - startTime) * (value - valueAtStartTime);\n };\n\n var interpolateValue = function interpolateValue(values, theoreticIndex) {\n var lowerIndex = Math.floor(theoreticIndex);\n if (lowerIndex === theoreticIndex) {\n return values[lowerIndex];\n }\n var upperIndex = Math.ceil(theoreticIndex);\n return (1 - (theoreticIndex - lowerIndex)) * values[lowerIndex] + (1 - (upperIndex - theoreticIndex)) * values[upperIndex];\n };\n\n var getValueCurveValueAtTime = function getValueCurveValueAtTime(time, _ref) {\n var duration = _ref.duration,\n startTime = _ref.startTime,\n values = _ref.values;\n var theoreticIndex = (time - startTime) / duration * (values.length - 1);\n return interpolateValue(values, theoreticIndex);\n };\n\n var truncateValueCurve = function truncateValueCurve(values, originalDuration, targetDuration) {\n var length = values.length;\n var truncatedLength = Math.max(1, Math.floor(targetDuration / originalDuration * length)) + 1;\n var truncatedValues = values instanceof Float32Array ? new Float32Array(truncatedLength) : values.slice(0, truncatedLength);\n for (var i = 0; i < truncatedLength; i += 1) {\n var time = i / (truncatedLength - 1) * targetDuration;\n var theoreticIndex = time / originalDuration * (length - 1);\n truncatedValues[i] = interpolateValue(values, theoreticIndex);\n }\n return truncatedValues;\n };\n\n var isSetTargetAutomationEvent = function isSetTargetAutomationEvent(automationEvent) {\n return automationEvent.type === 'setTarget';\n };\n\n var AutomationEventList = /*#__PURE__*/function () {\n function AutomationEventList(defaultValue) {\n _classCallCheck(this, AutomationEventList);\n this._automationEvents = [];\n this._currenTime = 0;\n this._defaultValue = defaultValue;\n }\n return _createClass(AutomationEventList, [{\n key: Symbol.iterator,\n value: function value() {\n return this._automationEvents[Symbol.iterator]();\n }\n }, {\n key: \"add\",\n value: function add(automationEvent) {\n var eventTime = getEventTime(automationEvent);\n if (isCancelAndHoldAutomationEvent(automationEvent) || isCancelScheduledValuesAutomationEvent(automationEvent)) {\n var index = this._automationEvents.findIndex(function (currentAutomationEvent) {\n if (isCancelScheduledValuesAutomationEvent(automationEvent) && isSetValueCurveAutomationEvent(currentAutomationEvent)) {\n return currentAutomationEvent.startTime + currentAutomationEvent.duration >= eventTime;\n }\n return getEventTime(currentAutomationEvent) >= eventTime;\n });\n var removedAutomationEvent = this._automationEvents[index];\n if (index !== -1) {\n this._automationEvents = this._automationEvents.slice(0, index);\n }\n if (isCancelAndHoldAutomationEvent(automationEvent)) {\n var lastAutomationEvent = this._automationEvents[this._automationEvents.length - 1];\n if (removedAutomationEvent !== undefined && isAnyRampToValueAutomationEvent(removedAutomationEvent)) {\n if (lastAutomationEvent !== undefined && isSetTargetAutomationEvent(lastAutomationEvent)) {\n throw new Error('The internal list is malformed.');\n }\n var startTime = lastAutomationEvent === undefined ? removedAutomationEvent.insertTime : isSetValueCurveAutomationEvent(lastAutomationEvent) ? lastAutomationEvent.startTime + lastAutomationEvent.duration : getEventTime(lastAutomationEvent);\n var startValue = lastAutomationEvent === undefined ? this._defaultValue : isSetValueCurveAutomationEvent(lastAutomationEvent) ? lastAutomationEvent.values[lastAutomationEvent.values.length - 1] : lastAutomationEvent.value;\n var value = isExponentialRampToValueAutomationEvent(removedAutomationEvent) ? getExponentialRampValueAtTime(eventTime, startTime, startValue, removedAutomationEvent) : getLinearRampValueAtTime(eventTime, startTime, startValue, removedAutomationEvent);\n var truncatedAutomationEvent = isExponentialRampToValueAutomationEvent(removedAutomationEvent) ? createExtendedExponentialRampToValueAutomationEvent(value, eventTime, this._currenTime) : createExtendedLinearRampToValueAutomationEvent(value, eventTime, this._currenTime);\n this._automationEvents.push(truncatedAutomationEvent);\n }\n if (lastAutomationEvent !== undefined && isSetTargetAutomationEvent(lastAutomationEvent)) {\n this._automationEvents.push(createSetValueAutomationEvent(this.getValue(eventTime), eventTime));\n }\n if (lastAutomationEvent !== undefined && isSetValueCurveAutomationEvent(lastAutomationEvent) && lastAutomationEvent.startTime + lastAutomationEvent.duration > eventTime) {\n var duration = eventTime - lastAutomationEvent.startTime;\n this._automationEvents[this._automationEvents.length - 1] = createSetValueCurveAutomationEvent(truncateValueCurve(lastAutomationEvent.values, lastAutomationEvent.duration, duration), lastAutomationEvent.startTime, duration);\n }\n }\n } else {\n var _index = this._automationEvents.findIndex(function (currentAutomationEvent) {\n return getEventTime(currentAutomationEvent) > eventTime;\n });\n var previousAutomationEvent = _index === -1 ? this._automationEvents[this._automationEvents.length - 1] : this._automationEvents[_index - 1];\n if (previousAutomationEvent !== undefined && isSetValueCurveAutomationEvent(previousAutomationEvent) && getEventTime(previousAutomationEvent) + previousAutomationEvent.duration > eventTime) {\n return false;\n }\n var persistentAutomationEvent = isExponentialRampToValueAutomationEvent(automationEvent) ? createExtendedExponentialRampToValueAutomationEvent(automationEvent.value, automationEvent.endTime, this._currenTime) : isLinearRampToValueAutomationEvent(automationEvent) ? createExtendedLinearRampToValueAutomationEvent(automationEvent.value, eventTime, this._currenTime) : automationEvent;\n if (_index === -1) {\n this._automationEvents.push(persistentAutomationEvent);\n } else {\n if (isSetValueCurveAutomationEvent(automationEvent) && eventTime + automationEvent.duration > getEventTime(this._automationEvents[_index])) {\n return false;\n }\n this._automationEvents.splice(_index, 0, persistentAutomationEvent);\n }\n }\n return true;\n }\n }, {\n key: \"flush\",\n value: function flush(time) {\n var index = this._automationEvents.findIndex(function (currentAutomationEvent) {\n return getEventTime(currentAutomationEvent) > time;\n });\n if (index > 1) {\n var remainingAutomationEvents = this._automationEvents.slice(index - 1);\n var firstRemainingAutomationEvent = remainingAutomationEvents[0];\n if (isSetTargetAutomationEvent(firstRemainingAutomationEvent)) {\n remainingAutomationEvents.unshift(createSetValueAutomationEvent(_getValueOfAutomationEventAtIndexAtTime(this._automationEvents, index - 2, firstRemainingAutomationEvent.startTime, this._defaultValue), firstRemainingAutomationEvent.startTime));\n }\n this._automationEvents = remainingAutomationEvents;\n }\n }\n }, {\n key: \"getValue\",\n value: function getValue(time) {\n if (this._automationEvents.length === 0) {\n return this._defaultValue;\n }\n var indexOfNextEvent = this._automationEvents.findIndex(function (automationEvent) {\n return getEventTime(automationEvent) > time;\n });\n var nextAutomationEvent = this._automationEvents[indexOfNextEvent];\n var indexOfCurrentEvent = (indexOfNextEvent === -1 ? this._automationEvents.length : indexOfNextEvent) - 1;\n var currentAutomationEvent = this._automationEvents[indexOfCurrentEvent];\n if (currentAutomationEvent !== undefined && isSetTargetAutomationEvent(currentAutomationEvent) && (nextAutomationEvent === undefined || !isAnyRampToValueAutomationEvent(nextAutomationEvent) || nextAutomationEvent.insertTime > time)) {\n return getTargetValueAtTime(time, _getValueOfAutomationEventAtIndexAtTime(this._automationEvents, indexOfCurrentEvent - 1, currentAutomationEvent.startTime, this._defaultValue), currentAutomationEvent);\n }\n if (currentAutomationEvent !== undefined && isSetValueAutomationEvent(currentAutomationEvent) && (nextAutomationEvent === undefined || !isAnyRampToValueAutomationEvent(nextAutomationEvent))) {\n return currentAutomationEvent.value;\n }\n if (currentAutomationEvent !== undefined && isSetValueCurveAutomationEvent(currentAutomationEvent) && (nextAutomationEvent === undefined || !isAnyRampToValueAutomationEvent(nextAutomationEvent) || currentAutomationEvent.startTime + currentAutomationEvent.duration > time)) {\n if (time < currentAutomationEvent.startTime + currentAutomationEvent.duration) {\n return getValueCurveValueAtTime(time, currentAutomationEvent);\n }\n return currentAutomationEvent.values[currentAutomationEvent.values.length - 1];\n }\n if (currentAutomationEvent !== undefined && isAnyRampToValueAutomationEvent(currentAutomationEvent) && (nextAutomationEvent === undefined || !isAnyRampToValueAutomationEvent(nextAutomationEvent))) {\n return currentAutomationEvent.value;\n }\n if (nextAutomationEvent !== undefined && isExponentialRampToValueAutomationEvent(nextAutomationEvent)) {\n var _getEndTimeAndValueOf = getEndTimeAndValueOfPreviousAutomationEvent(this._automationEvents, indexOfCurrentEvent, currentAutomationEvent, nextAutomationEvent, this._defaultValue),\n _getEndTimeAndValueOf2 = _slicedToArray(_getEndTimeAndValueOf, 2),\n startTime = _getEndTimeAndValueOf2[0],\n value = _getEndTimeAndValueOf2[1];\n return getExponentialRampValueAtTime(time, startTime, value, nextAutomationEvent);\n }\n if (nextAutomationEvent !== undefined && isLinearRampToValueAutomationEvent(nextAutomationEvent)) {\n var _getEndTimeAndValueOf3 = getEndTimeAndValueOfPreviousAutomationEvent(this._automationEvents, indexOfCurrentEvent, currentAutomationEvent, nextAutomationEvent, this._defaultValue),\n _getEndTimeAndValueOf4 = _slicedToArray(_getEndTimeAndValueOf3, 2),\n _startTime = _getEndTimeAndValueOf4[0],\n _value = _getEndTimeAndValueOf4[1];\n return getLinearRampValueAtTime(time, _startTime, _value, nextAutomationEvent);\n }\n return this._defaultValue;\n }\n }]);\n }();\n\n var createCancelAndHoldAutomationEvent = function createCancelAndHoldAutomationEvent(cancelTime) {\n return {\n cancelTime: cancelTime,\n type: 'cancelAndHold'\n };\n };\n\n var createCancelScheduledValuesAutomationEvent = function createCancelScheduledValuesAutomationEvent(cancelTime) {\n return {\n cancelTime: cancelTime,\n type: 'cancelScheduledValues'\n };\n };\n\n var createExponentialRampToValueAutomationEvent = function createExponentialRampToValueAutomationEvent(value, endTime) {\n return {\n endTime: endTime,\n type: 'exponentialRampToValue',\n value: value\n };\n };\n\n var createLinearRampToValueAutomationEvent = function createLinearRampToValueAutomationEvent(value, endTime) {\n return {\n endTime: endTime,\n type: 'linearRampToValue',\n value: value\n };\n };\n\n var createSetTargetAutomationEvent = function createSetTargetAutomationEvent(target, startTime, timeConstant) {\n return {\n startTime: startTime,\n target: target,\n timeConstant: timeConstant,\n type: 'setTarget'\n };\n };\n\n exports.AutomationEventList = AutomationEventList;\n exports.createCancelAndHoldAutomationEvent = createCancelAndHoldAutomationEvent;\n exports.createCancelScheduledValuesAutomationEvent = createCancelScheduledValuesAutomationEvent;\n exports.createExponentialRampToValueAutomationEvent = createExponentialRampToValueAutomationEvent;\n exports.createLinearRampToValueAutomationEvent = createLinearRampToValueAutomationEvent;\n exports.createSetTargetAutomationEvent = createSetTargetAutomationEvent;\n exports.createSetValueAutomationEvent = createSetValueAutomationEvent;\n exports.createSetValueCurveAutomationEvent = createSetValueCurveAutomationEvent;\n\n}));\n","/**\n * Sonarium — drop-in acoustic UX.\n * One script tag turns any webpage into a spatial sound field: layout becomes a stereo stage,\n * geometry becomes timbre (Kiki/Bouba), the DOM tree becomes depth and harmony, the viewport\n * becomes a room, and your cursor becomes your ears.\n *\n * import { create } from 'sonarium' // ESM\n * const space = create({ theme: 'aurora' })\n *\n * <script src=\".../sonarium.iife.js\" data-auto></script> // zero-code\n *\n * Docs: https://github.com/frank890417/sonarium — start with docs/PLAN.md.\n */\nimport { Engine } from './core/engine'\nimport type { SonariumOptions } from './types'\n\nexport const version = '0.6.0'\n\nexport type {\n SonariumOptions, SonicProfile, Theme, VoiceRecipe, Role, Wave, SynthKind,\n Articulation, TriggerDetail, SonariumEvent, SphereProps, PerceptualFactors,\n} from './types'\nexport { THEMES } from './themes/index'\nexport { siteKey, parseKey, degreeToMidi, midiToFreq, midiToNoteName, stepInScale, SCALES } from './math/scales'\nexport * as mapping from './math/mapping'\nexport * as matter from './math/matter'\nexport * as chroma from './math/chroma'\nexport * as pulse from './math/pulse'\nexport * as modular from './math/modular'\n// The pure spatial layer (SPATIAL.md) — reusable beyond the DOM.\nexport { foaGains, unitVector, DEG } from './spatial/sh'\nexport { rotationMatrix, lookMatrix, applyMat3 } from './spatial/rotation'\nexport { CUBE_LAYOUT, decodeMatrix, decodeGains } from './spatial/decoder'\nexport * as sphereMapping from './spatial/sphere'\nexport { DEFAULT_FACTORS } from './spatial/perceptual'\nexport type { Engine }\n\n/**\n * Create a Sonarium instance. Safe to call before any user gesture: audio arms itself and\n * starts on the first pointer/key interaction (browser autoplay policy treated as a feature).\n */\nexport function create(options: SonariumOptions = {}): Engine {\n return new Engine(options)\n}\n\n// ---------------------------------------------------------------------------- auto-init\n// <script src=\"sonarium.iife.js\" data-auto data-theme=\"paper\" data-ambient=\"0.2\"></script>\nfunction autoInit(): void {\n if (typeof document === 'undefined') return\n const script = document.currentScript as HTMLScriptElement | null\n if (!script || script.dataset.auto === undefined) return\n const opts: SonariumOptions = {}\n if (script.dataset.theme) opts.theme = script.dataset.theme as SonariumOptions['theme']\n if (script.dataset.key) opts.key = script.dataset.key\n if (script.dataset.ambient) opts.ambient = parseFloat(script.dataset.ambient)\n if (script.dataset.listener) opts.listener = script.dataset.listener as SonariumOptions['listener']\n if (script.dataset.volume) opts.volume = parseFloat(script.dataset.volume)\n if (script.dataset.panning) opts.panning = script.dataset.panning as SonariumOptions['panning']\n const boot = () => {\n try {\n const engine = create(opts)\n ;(window as unknown as Record<string, unknown>).sonarium = engine\n } catch (err) {\n console.warn('[sonarium] auto-init failed', err)\n }\n }\n if (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', boot, { once: true })\n } else {\n boot()\n }\n}\n\nautoInit()\n","export const version: string = \"15.1.22\";\n","import {\n createCancelAndHoldAutomationEvent,\n createCancelScheduledValuesAutomationEvent,\n createExponentialRampToValueAutomationEvent,\n createLinearRampToValueAutomationEvent,\n createSetTargetAutomationEvent,\n createSetValueAutomationEvent,\n createSetValueCurveAutomationEvent\n} from 'automation-events';\nimport { createAbortError } from './factories/abort-error';\nimport { createAddActiveInputConnectionToAudioNode } from './factories/add-active-input-connection-to-audio-node';\nimport { createAddAudioNodeConnections } from './factories/add-audio-node-connections';\nimport { createAddAudioParamConnections } from './factories/add-audio-param-connections';\nimport { createAddAudioWorkletModule } from './factories/add-audio-worklet-module';\nimport { createAddConnectionToAudioNode } from './factories/add-connection-to-audio-node';\nimport { createAddPassiveInputConnectionToAudioNode } from './factories/add-passive-input-connection-to-audio-node';\nimport { createAddSilentConnection } from './factories/add-silent-connection';\nimport { createAddUnrenderedAudioWorkletNode } from './factories/add-unrendered-audio-worklet-node';\nimport { createAnalyserNodeConstructor } from './factories/analyser-node-constructor';\nimport { createAnalyserNodeRendererFactory } from './factories/analyser-node-renderer-factory';\nimport { createAudioBufferConstructor } from './factories/audio-buffer-constructor';\nimport { createAudioBufferSourceNodeConstructor } from './factories/audio-buffer-source-node-constructor';\nimport { createAudioBufferSourceNodeRendererFactory } from './factories/audio-buffer-source-node-renderer-factory';\nimport { createAudioContextConstructor } from './factories/audio-context-constructor';\nimport { createAudioDestinationNodeConstructor } from './factories/audio-destination-node-constructor';\nimport { createAudioDestinationNodeRenderer } from './factories/audio-destination-node-renderer-factory';\nimport { createAudioListenerFactory } from './factories/audio-listener-factory';\nimport { createAudioNodeConstructor } from './factories/audio-node-constructor';\nimport { createAudioParamFactory } from './factories/audio-param-factory';\nimport { createAudioParamRenderer } from './factories/audio-param-renderer';\nimport { createAudioWorkletNodeConstructor } from './factories/audio-worklet-node-constructor';\nimport { createAudioWorkletNodeRendererFactory } from './factories/audio-worklet-node-renderer-factory';\nimport { createBaseAudioContextConstructor } from './factories/base-audio-context-constructor';\nimport { createBiquadFilterNodeConstructor } from './factories/biquad-filter-node-constructor';\nimport { createBiquadFilterNodeRendererFactory } from './factories/biquad-filter-node-renderer-factory';\nimport { createCacheTestResult } from './factories/cache-test-result';\nimport { createChannelMergerNodeConstructor } from './factories/channel-merger-node-constructor';\nimport { createChannelMergerNodeRendererFactory } from './factories/channel-merger-node-renderer-factory';\nimport { createChannelSplitterNodeConstructor } from './factories/channel-splitter-node-constructor';\nimport { createChannelSplitterNodeRendererFactory } from './factories/channel-splitter-node-renderer-factory';\nimport { createConnectAudioParam } from './factories/connect-audio-param';\nimport { createConnectMultipleOutputs } from './factories/connect-multiple-outputs';\nimport { createConnectedNativeAudioBufferSourceNodeFactory } from './factories/connected-native-audio-buffer-source-node-factory';\nimport { createConstantSourceNodeConstructor } from './factories/constant-source-node-constructor';\nimport { createConstantSourceNodeRendererFactory } from './factories/constant-source-node-renderer-factory';\nimport { createConvertNumberToUnsignedLong } from './factories/convert-number-to-unsigned-long';\nimport { createConvolverNodeConstructor } from './factories/convolver-node-constructor';\nimport { createConvolverNodeRendererFactory } from './factories/convolver-node-renderer-factory';\nimport { createCreateNativeOfflineAudioContext } from './factories/create-native-offline-audio-context';\nimport { createDataCloneError } from './factories/data-clone-error';\nimport { createDecodeAudioData } from './factories/decode-audio-data';\nimport { createDecrementCycleCounter } from './factories/decrement-cycle-counter';\nimport { createDelayNodeConstructor } from './factories/delay-node-constructor';\nimport { createDelayNodeRendererFactory } from './factories/delay-node-renderer-factory';\nimport { createDeleteActiveInputConnectionToAudioNode } from './factories/delete-active-input-connection-to-audio-node';\nimport { createDeleteUnrenderedAudioWorkletNode } from './factories/delete-unrendered-audio-worklet-node';\nimport { createDetectCycles } from './factories/detect-cycles';\nimport { createDisconnectMultipleOutputs } from './factories/disconnect-multiple-outputs';\nimport { createDynamicsCompressorNodeConstructor } from './factories/dynamics-compressor-node-constructor';\nimport { createDynamicsCompressorNodeRendererFactory } from './factories/dynamics-compressor-node-renderer-factory';\nimport { createEncodingError } from './factories/encoding-error';\nimport { createEvaluateSource } from './factories/evaluate-source';\nimport { createEventTargetConstructor } from './factories/event-target-constructor';\nimport { createExposeCurrentFrameAndCurrentTime } from './factories/expose-current-frame-and-current-time';\nimport { createFetchSource } from './factories/fetch-source';\nimport { createGainNodeConstructor } from './factories/gain-node-constructor';\nimport { createGainNodeRendererFactory } from './factories/gain-node-renderer-factory';\nimport { createGetActiveAudioWorkletNodeInputs } from './factories/get-active-audio-worklet-node-inputs';\nimport { createGetAudioNodeRenderer } from './factories/get-audio-node-renderer';\nimport { createGetAudioNodeTailTime } from './factories/get-audio-node-tail-time';\nimport { createGetAudioParamRenderer } from './factories/get-audio-param-renderer';\nimport { createGetBackupOfflineAudioContext } from './factories/get-backup-offline-audio-context';\nimport { createGetNativeContext } from './factories/get-native-context';\nimport { createGetOrCreateBackupOfflineAudioContext } from './factories/get-or-create-backup-offline-audio-context';\nimport { createGetUnrenderedAudioWorkletNodes } from './factories/get-unrendered-audio-worklet-nodes';\nimport { createIIRFilterNodeConstructor } from './factories/iir-filter-node-constructor';\nimport { createIIRFilterNodeRendererFactory } from './factories/iir-filter-node-renderer-factory';\nimport { createIncrementCycleCounterFactory } from './factories/increment-cycle-counter-factory';\nimport { createIndexSizeError } from './factories/index-size-error';\nimport { createInvalidAccessError } from './factories/invalid-access-error';\nimport { createInvalidStateError } from './factories/invalid-state-error';\nimport { createIsAnyAudioContext } from './factories/is-any-audio-context';\nimport { createIsAnyAudioNode } from './factories/is-any-audio-node';\nimport { createIsAnyAudioParam } from './factories/is-any-audio-param';\nimport { createIsAnyOfflineAudioContext } from './factories/is-any-offline-audio-context';\nimport { createIsNativeAudioContext } from './factories/is-native-audio-context';\nimport { createIsNativeAudioNode } from './factories/is-native-audio-node';\nimport { createIsNativeAudioParam } from './factories/is-native-audio-param';\nimport { createIsNativeContext } from './factories/is-native-context';\nimport { createIsNativeOfflineAudioContext } from './factories/is-native-offline-audio-context';\nimport { createIsSecureContext } from './factories/is-secure-context';\nimport { createIsSupportedPromise } from './factories/is-supported-promise';\nimport { createMediaElementAudioSourceNodeConstructor } from './factories/media-element-audio-source-node-constructor';\nimport { createMediaStreamAudioDestinationNodeConstructor } from './factories/media-stream-audio-destination-node-constructor';\nimport { createMediaStreamAudioSourceNodeConstructor } from './factories/media-stream-audio-source-node-constructor';\nimport { createMediaStreamTrackAudioSourceNodeConstructor } from './factories/media-stream-track-audio-source-node-constructor';\nimport { createMinimalAudioContextConstructor } from './factories/minimal-audio-context-constructor';\nimport { createMinimalBaseAudioContextConstructor } from './factories/minimal-base-audio-context-constructor';\nimport { createMinimalOfflineAudioContextConstructor } from './factories/minimal-offline-audio-context-constructor';\nimport { createMonitorConnections } from './factories/monitor-connections';\nimport { createNativeAnalyserNodeFactory } from './factories/native-analyser-node-factory';\nimport { createNativeAudioBufferConstructor } from './factories/native-audio-buffer-constructor';\nimport { createNativeAudioBufferSourceNodeFactory } from './factories/native-audio-buffer-source-node-factory';\nimport { createNativeAudioContextConstructor } from './factories/native-audio-context-constructor';\nimport { createNativeAudioDestinationNodeFactory } from './factories/native-audio-destination-node';\nimport { createNativeAudioWorkletNodeConstructor } from './factories/native-audio-worklet-node-constructor';\nimport { createNativeAudioWorkletNodeFactory } from './factories/native-audio-worklet-node-factory';\nimport { createNativeAudioWorkletNodeFakerFactory } from './factories/native-audio-worklet-node-faker-factory';\nimport { createNativeBiquadFilterNode } from './factories/native-biquad-filter-node';\nimport { createNativeChannelMergerNodeFactory } from './factories/native-channel-merger-node-factory';\nimport { createNativeChannelSplitterNode } from './factories/native-channel-splitter-node';\nimport { createNativeConstantSourceNodeFactory } from './factories/native-constant-source-node-factory';\nimport { createNativeConstantSourceNodeFakerFactory } from './factories/native-constant-source-node-faker-factory';\nimport { createNativeConvolverNodeFactory } from './factories/native-convolver-node-factory';\nimport { createNativeDelayNode } from './factories/native-delay-node';\nimport { createNativeDynamicsCompressorNodeFactory } from './factories/native-dynamics-compressor-node-factory';\nimport { createNativeGainNode } from './factories/native-gain-node';\nimport { createNativeIIRFilterNodeFactory } from './factories/native-iir-filter-node-factory';\nimport { createNativeIIRFilterNodeFakerFactory } from './factories/native-iir-filter-node-faker-factory';\nimport { createNativeMediaElementAudioSourceNode } from './factories/native-media-element-audio-source-node';\nimport { createNativeMediaStreamAudioDestinationNode } from './factories/native-media-stream-audio-destination-node';\nimport { createNativeMediaStreamAudioSourceNode } from './factories/native-media-stream-audio-source-node';\nimport { createNativeMediaStreamTrackAudioSourceNodeFactory } from './factories/native-media-stream-track-audio-source-node-factory';\nimport { createNativeOfflineAudioContextConstructor } from './factories/native-offline-audio-context-constructor';\nimport { createNativeOscillatorNodeFactory } from './factories/native-oscillator-node-factory';\nimport { createNativePannerNodeFactory } from './factories/native-panner-node-factory';\nimport { createNativePannerNodeFakerFactory } from './factories/native-panner-node-faker-factory';\nimport { createNativePeriodicWaveFactory } from './factories/native-periodic-wave-factory';\nimport { createNativeScriptProcessorNode } from './factories/native-script-processor-node';\nimport { createNativeStereoPannerNodeFactory } from './factories/native-stereo-panner-node-factory';\nimport { createNativeStereoPannerNodeFakerFactory } from './factories/native-stereo-panner-node-faker-factory';\nimport { createNativeWaveShaperNodeFactory } from './factories/native-wave-shaper-node-factory';\nimport { createNativeWaveShaperNodeFakerFactory } from './factories/native-wave-shaper-node-faker-factory';\nimport { createNotSupportedError } from './factories/not-supported-error';\nimport { createOfflineAudioContextConstructor } from './factories/offline-audio-context-constructor';\nimport { createOscillatorNodeConstructor } from './factories/oscillator-node-constructor';\nimport { createOscillatorNodeRendererFactory } from './factories/oscillator-node-renderer-factory';\nimport { createPannerNodeConstructor } from './factories/panner-node-constructor';\nimport { createPannerNodeRendererFactory } from './factories/panner-node-renderer-factory';\nimport { createPeriodicWaveConstructor } from './factories/periodic-wave-constructor';\nimport { createRenderAutomation } from './factories/render-automation';\nimport { createRenderInputsOfAudioNode } from './factories/render-inputs-of-audio-node';\nimport { createRenderInputsOfAudioParam } from './factories/render-inputs-of-audio-param';\nimport { createRenderNativeOfflineAudioContext } from './factories/render-native-offline-audio-context';\nimport { createSetActiveAudioWorkletNodeInputs } from './factories/set-active-audio-worklet-node-inputs';\nimport { createSetAudioNodeTailTime } from './factories/set-audio-node-tail-time';\nimport { createStartRendering } from './factories/start-rendering';\nimport { createStereoPannerNodeConstructor } from './factories/stereo-panner-node-constructor';\nimport { createStereoPannerNodeRendererFactory } from './factories/stereo-panner-node-renderer-factory';\nimport { createTestAudioBufferConstructorSupport } from './factories/test-audio-buffer-constructor-support';\nimport { createTestAudioBufferCopyChannelMethodsSubarraySupport } from './factories/test-audio-buffer-copy-channel-methods-subarray-support';\nimport { createTestAudioContextCloseMethodSupport } from './factories/test-audio-context-close-method-support';\nimport { createTestAudioContextDecodeAudioDataMethodTypeErrorSupport } from './factories/test-audio-context-decode-audio-data-method-type-error-support';\nimport { createTestAudioContextOptionsSupport } from './factories/test-audio-context-options-support';\nimport { createTestAudioNodeConnectMethodSupport } from './factories/test-audio-node-connect-method-support';\nimport { createTestAudioWorkletProcessorNoOutputsSupport } from './factories/test-audio-worklet-processor-no-outputs-support';\nimport { createTestAudioWorkletProcessorPostMessageSupport } from './factories/test-audio-worklet-processor-post-message-support';\nimport { createTestChannelMergerNodeChannelCountSupport } from './factories/test-channel-merger-node-channel-count-support';\nimport { createTestConstantSourceNodeAccurateSchedulingSupport } from './factories/test-constant-source-node-accurate-scheduling-support';\nimport { createTestConvolverNodeBufferReassignabilitySupport } from './factories/test-convolver-node-buffer-reassignability-support';\nimport { createTestConvolverNodeChannelCountSupport } from './factories/test-convolver-node-channel-count-support';\nimport { createTestIsSecureContextSupport } from './factories/test-is-secure-context-support';\nimport { createTestMediaStreamAudioSourceNodeMediaStreamWithoutAudioTrackSupport } from './factories/test-media-stream-audio-source-node-media-stream-without-audio-track-support';\nimport { createTestOfflineAudioContextCurrentTimeSupport } from './factories/test-offline-audio-context-current-time-support';\nimport { createTestStereoPannerNodeDefaultValueSupport } from './factories/test-stereo-panner-node-default-value-support';\nimport { createUnknownError } from './factories/unknown-error';\nimport { createWaveShaperNodeConstructor } from './factories/wave-shaper-node-constructor';\nimport { createWaveShaperNodeRendererFactory } from './factories/wave-shaper-node-renderer-factory';\nimport { createWindow } from './factories/window';\nimport { createWrapAudioBufferCopyChannelMethods } from './factories/wrap-audio-buffer-copy-channel-methods';\nimport { createWrapAudioBufferCopyChannelMethodsOutOfBounds } from './factories/wrap-audio-buffer-copy-channel-methods-out-of-bounds';\nimport { createWrapAudioBufferSourceNodeStopMethodNullifiedBuffer } from './factories/wrap-audio-buffer-source-node-stop-method-nullified-buffer';\nimport { createWrapChannelMergerNode } from './factories/wrap-channel-merger-node';\nimport {\n AUDIO_NODE_CONNECTIONS_STORE,\n AUDIO_NODE_STORE,\n AUDIO_PARAM_CONNECTIONS_STORE,\n AUDIO_PARAM_STORE,\n CONTEXT_STORE,\n CYCLE_COUNTERS\n} from './globals';\nimport { connectNativeAudioNodeToNativeAudioNode } from './helpers/connect-native-audio-node-to-native-audio-node';\nimport { disconnectNativeAudioNodeFromNativeAudioNode } from './helpers/disconnect-native-audio-node-from-native-audio-node';\nimport { getAudioNodeConnections } from './helpers/get-audio-node-connections';\nimport { getAudioParamConnections } from './helpers/get-audio-param-connections';\nimport { getEventListenersOfAudioNode } from './helpers/get-event-listeners-of-audio-node';\nimport { getFirstSample } from './helpers/get-first-sample';\nimport { getNativeAudioNode } from './helpers/get-native-audio-node';\nimport { getNativeAudioParam } from './helpers/get-native-audio-param';\nimport { getValueForKey } from './helpers/get-value-for-key';\nimport { insertElementInSet } from './helpers/insert-element-in-set';\nimport { isActiveAudioNode } from './helpers/is-active-audio-node';\nimport { isDCCurve } from './helpers/is-dc-curve';\nimport { isPartOfACycle } from './helpers/is-part-of-a-cycle';\nimport { isPassiveAudioNode } from './helpers/is-passive-audio-node';\nimport { overwriteAccessors } from './helpers/overwrite-accessors';\nimport { pickElementFromSet } from './helpers/pick-element-from-set';\nimport { sanitizeAudioWorkletNodeOptions } from './helpers/sanitize-audio-worklet-node-options';\nimport { sanitizeChannelSplitterOptions } from './helpers/sanitize-channel-splitter-options';\nimport { sanitizePeriodicWaveOptions } from './helpers/sanitize-periodic-wave-options';\nimport { setValueAtTimeUntilPossible } from './helpers/set-value-at-time-until-possible';\nimport { testAudioBufferCopyChannelMethodsOutOfBoundsSupport } from './helpers/test-audio-buffer-copy-channel-methods-out-of-bounds-support';\nimport { testAudioBufferSourceNodeStartMethodConsecutiveCallsSupport } from './helpers/test-audio-buffer-source-node-start-method-consecutive-calls-support';\nimport { testAudioBufferSourceNodeStartMethodOffsetClampingSupport } from './helpers/test-audio-buffer-source-node-start-method-offset-clamping-support';\nimport { testAudioBufferSourceNodeStopMethodNullifiedBufferSupport } from './helpers/test-audio-buffer-source-node-stop-method-nullified-buffer-support';\nimport { testAudioScheduledSourceNodeStartMethodNegativeParametersSupport } from './helpers/test-audio-scheduled-source-node-start-method-negative-parameters-support';\nimport { testAudioScheduledSourceNodeStopMethodConsecutiveCallsSupport } from './helpers/test-audio-scheduled-source-node-stop-method-consecutive-calls-support';\nimport { testAudioScheduledSourceNodeStopMethodNegativeParametersSupport } from './helpers/test-audio-scheduled-source-node-stop-method-negative-parameters-support';\nimport { testAudioWorkletNodeOptionsClonability } from './helpers/test-audio-worklet-node-options-clonability';\nimport { testDomExceptionConstructorSupport } from './helpers/test-dom-exception-constructor-support';\nimport { testPromiseSupport } from './helpers/test-promise-support';\nimport { testTransferablesSupport } from './helpers/test-transferables-support';\nimport { wrapAudioBufferSourceNodeStartMethodOffsetClamping } from './helpers/wrap-audio-buffer-source-node-start-method-offset-clamping';\nimport { wrapAudioScheduledSourceNodeStopMethodConsecutiveCalls } from './helpers/wrap-audio-scheduled-source-node-stop-method-consecutive-calls';\nimport { wrapEventListener } from './helpers/wrap-event-listener';\nimport {\n IAnalyserNode,\n IAudioBuffer,\n IAudioBufferSourceNode,\n IAudioContext,\n IAudioNode,\n IAudioWorkletNode,\n IBiquadFilterNode,\n IConstantSourceNode,\n IConvolverNode,\n IDelayNode,\n IDynamicsCompressorNode,\n IGainNode,\n IIIRFilterNode,\n IMediaElementAudioSourceNode,\n IMediaStreamAudioDestinationNode,\n IMediaStreamAudioSourceNode,\n IMediaStreamTrackAudioSourceNode,\n IMinimalAudioContext,\n IMinimalOfflineAudioContext,\n IOfflineAudioContext,\n IOfflineAudioContextConstructor,\n IOscillatorNode,\n IPannerNode,\n IPeriodicWave,\n IStereoPannerNode,\n IWaveShaperNode\n} from './interfaces';\nimport {\n TActiveAudioWorkletNodeInputsStore,\n TAddAudioWorkletModuleFunction,\n TAnalyserNodeConstructor,\n TAudioBufferConstructor,\n TAudioBufferSourceNodeConstructor,\n TAudioBufferStore,\n TAudioContextConstructor,\n TAudioParamAudioNodeStore,\n TAudioWorkletNodeConstructor,\n TBackupOfflineAudioContextStore,\n TBiquadFilterNodeConstructor,\n TChannelMergerNodeConstructor,\n TChannelSplitterNodeConstructor,\n TConstantSourceNodeConstructor,\n TContext,\n TConvolverNodeConstructor,\n TDecodeAudioDataFunction,\n TDelayNodeConstructor,\n TDynamicsCompressorNodeConstructor,\n TGainNodeConstructor,\n TIIRFilterNodeConstructor,\n TMediaElementAudioSourceNodeConstructor,\n TMediaStreamAudioDestinationNodeConstructor,\n TMediaStreamAudioSourceNodeConstructor,\n TMediaStreamTrackAudioSourceNodeConstructor,\n TMinimalAudioContextConstructor,\n TMinimalOfflineAudioContextConstructor,\n TOscillatorNodeConstructor,\n TPannerNodeConstructor,\n TPeriodicWaveConstructor,\n TStereoPannerNodeConstructor,\n TUnrenderedAudioWorkletNodeStore,\n TWaveShaperNodeConstructor\n} from './types';\n\n/*\n * @todo Explicitly referencing the barrel file seems to be necessary when enabling the\n * isolatedModules compiler option.\n */\nexport * from './interfaces/index';\nexport * from './types/index';\n\nconst addActiveInputConnectionToAudioNode = createAddActiveInputConnectionToAudioNode(insertElementInSet);\nconst addPassiveInputConnectionToAudioNode = createAddPassiveInputConnectionToAudioNode(insertElementInSet);\nconst deleteActiveInputConnectionToAudioNode = createDeleteActiveInputConnectionToAudioNode(pickElementFromSet);\nconst audioNodeTailTimeStore = new WeakMap();\nconst getAudioNodeTailTime = createGetAudioNodeTailTime(audioNodeTailTimeStore);\nconst cacheTestResult = createCacheTestResult(new Map(), new WeakMap());\nconst window = createWindow();\nconst createNativeAnalyserNode = createNativeAnalyserNodeFactory(cacheTestResult, createIndexSizeError);\nconst getAudioNodeRenderer = createGetAudioNodeRenderer(getAudioNodeConnections);\nconst renderInputsOfAudioNode = createRenderInputsOfAudioNode(getAudioNodeConnections, getAudioNodeRenderer, isPartOfACycle);\nconst createAnalyserNodeRenderer = createAnalyserNodeRendererFactory(createNativeAnalyserNode, getNativeAudioNode, renderInputsOfAudioNode);\nconst getNativeContext = createGetNativeContext(CONTEXT_STORE);\nconst nativeOfflineAudioContextConstructor = createNativeOfflineAudioContextConstructor(window);\nconst isNativeOfflineAudioContext = createIsNativeOfflineAudioContext(nativeOfflineAudioContextConstructor);\nconst audioParamAudioNodeStore: TAudioParamAudioNodeStore = new WeakMap();\nconst eventTargetConstructor = createEventTargetConstructor(wrapEventListener);\nconst nativeAudioContextConstructor = createNativeAudioContextConstructor(window);\nconst isNativeAudioContext = createIsNativeAudioContext(nativeAudioContextConstructor);\nconst isNativeAudioNode = createIsNativeAudioNode(window);\nconst isNativeAudioParam = createIsNativeAudioParam(window);\nconst nativeAudioWorkletNodeConstructor = createNativeAudioWorkletNodeConstructor(window);\nconst audioNodeConstructor = createAudioNodeConstructor(\n createAddAudioNodeConnections(AUDIO_NODE_CONNECTIONS_STORE),\n createAddConnectionToAudioNode(\n addActiveInputConnectionToAudioNode,\n addPassiveInputConnectionToAudioNode,\n connectNativeAudioNodeToNativeAudioNode,\n deleteActiveInputConnectionToAudioNode,\n disconnectNativeAudioNodeFromNativeAudioNode,\n getAudioNodeConnections,\n getAudioNodeTailTime,\n getEventListenersOfAudioNode,\n getNativeAudioNode,\n insertElementInSet,\n isActiveAudioNode,\n isPartOfACycle,\n isPassiveAudioNode\n ),\n cacheTestResult,\n createIncrementCycleCounterFactory(\n CYCLE_COUNTERS,\n disconnectNativeAudioNodeFromNativeAudioNode,\n getAudioNodeConnections,\n getNativeAudioNode,\n getNativeAudioParam,\n isActiveAudioNode\n ),\n createIndexSizeError,\n createInvalidAccessError,\n createNotSupportedError,\n createDecrementCycleCounter(\n connectNativeAudioNodeToNativeAudioNode,\n CYCLE_COUNTERS,\n getAudioNodeConnections,\n getNativeAudioNode,\n getNativeAudioParam,\n getNativeContext,\n isActiveAudioNode,\n isNativeOfflineAudioContext\n ),\n createDetectCycles(audioParamAudioNodeStore, getAudioNodeConnections, getValueForKey),\n eventTargetConstructor,\n getNativeContext,\n isNativeAudioContext,\n isNativeAudioNode,\n isNativeAudioParam,\n isNativeOfflineAudioContext,\n nativeAudioWorkletNodeConstructor\n);\nconst analyserNodeConstructor: TAnalyserNodeConstructor = createAnalyserNodeConstructor(\n audioNodeConstructor,\n createAnalyserNodeRenderer,\n createIndexSizeError,\n createNativeAnalyserNode,\n getNativeContext,\n isNativeOfflineAudioContext\n);\n\ntype analyserNodeConstructor<T extends TContext> = IAnalyserNode<T>;\n\nexport { analyserNodeConstructor as AnalyserNode };\n\nconst audioBufferStore: TAudioBufferStore = new WeakSet();\nconst nativeAudioBufferConstructor = createNativeAudioBufferConstructor(window);\nconst convertNumberToUnsignedLong = createConvertNumberToUnsignedLong(new Uint32Array(1));\nconst wrapAudioBufferCopyChannelMethods = createWrapAudioBufferCopyChannelMethods(convertNumberToUnsignedLong, createIndexSizeError);\nconst wrapAudioBufferCopyChannelMethodsOutOfBounds = createWrapAudioBufferCopyChannelMethodsOutOfBounds(convertNumberToUnsignedLong);\nconst audioBufferConstructor: TAudioBufferConstructor = createAudioBufferConstructor(\n audioBufferStore,\n cacheTestResult,\n createNotSupportedError,\n nativeAudioBufferConstructor,\n nativeOfflineAudioContextConstructor,\n createTestAudioBufferConstructorSupport(nativeAudioBufferConstructor),\n wrapAudioBufferCopyChannelMethods,\n wrapAudioBufferCopyChannelMethodsOutOfBounds\n);\n\ntype audioBufferConstructor = IAudioBuffer;\n\nexport { audioBufferConstructor as AudioBuffer };\n\nconst addSilentConnection = createAddSilentConnection(createNativeGainNode);\nconst renderInputsOfAudioParam = createRenderInputsOfAudioParam(getAudioNodeRenderer, getAudioParamConnections, isPartOfACycle);\nconst connectAudioParam = createConnectAudioParam(renderInputsOfAudioParam);\nconst createNativeAudioBufferSourceNode = createNativeAudioBufferSourceNodeFactory(\n addSilentConnection,\n cacheTestResult,\n testAudioBufferSourceNodeStartMethodConsecutiveCallsSupport,\n testAudioBufferSourceNodeStartMethodOffsetClampingSupport,\n testAudioBufferSourceNodeStopMethodNullifiedBufferSupport,\n testAudioScheduledSourceNodeStartMethodNegativeParametersSupport,\n testAudioScheduledSourceNodeStopMethodConsecutiveCallsSupport,\n testAudioScheduledSourceNodeStopMethodNegativeParametersSupport,\n wrapAudioBufferSourceNodeStartMethodOffsetClamping,\n createWrapAudioBufferSourceNodeStopMethodNullifiedBuffer(overwriteAccessors),\n wrapAudioScheduledSourceNodeStopMethodConsecutiveCalls\n);\nconst renderAutomation = createRenderAutomation(createGetAudioParamRenderer(getAudioParamConnections), renderInputsOfAudioParam);\nconst createAudioBufferSourceNodeRenderer = createAudioBufferSourceNodeRendererFactory(\n connectAudioParam,\n createNativeAudioBufferSourceNode,\n getNativeAudioNode,\n renderAutomation,\n renderInputsOfAudioNode\n);\nconst createAudioParam = createAudioParamFactory(\n createAddAudioParamConnections(AUDIO_PARAM_CONNECTIONS_STORE),\n audioParamAudioNodeStore,\n AUDIO_PARAM_STORE,\n createAudioParamRenderer,\n createCancelAndHoldAutomationEvent,\n createCancelScheduledValuesAutomationEvent,\n createExponentialRampToValueAutomationEvent,\n createLinearRampToValueAutomationEvent,\n createSetTargetAutomationEvent,\n createSetValueAutomationEvent,\n createSetValueCurveAutomationEvent,\n nativeAudioContextConstructor,\n setValueAtTimeUntilPossible\n);\nconst audioBufferSourceNodeConstructor: TAudioBufferSourceNodeConstructor = createAudioBufferSourceNodeConstructor(\n audioNodeConstructor,\n createAudioBufferSourceNodeRenderer,\n createAudioParam,\n createInvalidStateError,\n createNativeAudioBufferSourceNode,\n getNativeContext,\n isNativeOfflineAudioContext,\n wrapEventListener\n);\n\ntype audioBufferSourceNodeConstructor<T extends TContext> = IAudioBufferSourceNode<T>;\n\nexport { audioBufferSourceNodeConstructor as AudioBufferSourceNode };\n\nconst audioDestinationNodeConstructor = createAudioDestinationNodeConstructor(\n audioNodeConstructor,\n createAudioDestinationNodeRenderer,\n createIndexSizeError,\n createInvalidStateError,\n createNativeAudioDestinationNodeFactory(createNativeGainNode, overwriteAccessors),\n getNativeContext,\n isNativeOfflineAudioContext,\n renderInputsOfAudioNode\n);\nconst createBiquadFilterNodeRenderer = createBiquadFilterNodeRendererFactory(\n connectAudioParam,\n createNativeBiquadFilterNode,\n getNativeAudioNode,\n renderAutomation,\n renderInputsOfAudioNode\n);\nconst setAudioNodeTailTime = createSetAudioNodeTailTime(audioNodeTailTimeStore);\nconst biquadFilterNodeConstructor: TBiquadFilterNodeConstructor = createBiquadFilterNodeConstructor(\n audioNodeConstructor,\n createAudioParam,\n createBiquadFilterNodeRenderer,\n createInvalidAccessError,\n createNativeBiquadFilterNode,\n getNativeContext,\n isNativeOfflineAudioContext,\n setAudioNodeTailTime\n);\nconst monitorConnections = createMonitorConnections(insertElementInSet, isNativeAudioNode);\nconst wrapChannelMergerNode = createWrapChannelMergerNode(createInvalidStateError, monitorConnections);\nconst createNativeChannelMergerNode = createNativeChannelMergerNodeFactory(nativeAudioContextConstructor, wrapChannelMergerNode);\nconst createChannelMergerNodeRenderer = createChannelMergerNodeRendererFactory(\n createNativeChannelMergerNode,\n getNativeAudioNode,\n renderInputsOfAudioNode\n);\nconst channelMergerNodeConstructor: TChannelMergerNodeConstructor = createChannelMergerNodeConstructor(\n audioNodeConstructor,\n createChannelMergerNodeRenderer,\n createNativeChannelMergerNode,\n getNativeContext,\n isNativeOfflineAudioContext\n);\nconst createChannelSplitterNodeRenderer = createChannelSplitterNodeRendererFactory(\n createNativeChannelSplitterNode,\n getNativeAudioNode,\n renderInputsOfAudioNode\n);\nconst channelSplitterNodeConstructor: TChannelSplitterNodeConstructor = createChannelSplitterNodeConstructor(\n audioNodeConstructor,\n createChannelSplitterNodeRenderer,\n createNativeChannelSplitterNode,\n getNativeContext,\n isNativeOfflineAudioContext,\n sanitizeChannelSplitterOptions\n);\nconst createNativeConstantSourceNodeFaker = createNativeConstantSourceNodeFakerFactory(\n addSilentConnection,\n createNativeAudioBufferSourceNode,\n createNativeGainNode,\n monitorConnections\n);\nconst createNativeConstantSourceNode = createNativeConstantSourceNodeFactory(\n addSilentConnection,\n cacheTestResult,\n createNativeConstantSourceNodeFaker,\n testAudioScheduledSourceNodeStartMethodNegativeParametersSupport,\n testAudioScheduledSourceNodeStopMethodNegativeParametersSupport\n);\nconst createConstantSourceNodeRenderer = createConstantSourceNodeRendererFactory(\n connectAudioParam,\n createNativeConstantSourceNode,\n getNativeAudioNode,\n renderAutomation,\n renderInputsOfAudioNode\n);\nconst constantSourceNodeConstructor: TConstantSourceNodeConstructor = createConstantSourceNodeConstructor(\n audioNodeConstructor,\n createAudioParam,\n createConstantSourceNodeRenderer,\n createNativeConstantSourceNode,\n getNativeContext,\n isNativeOfflineAudioContext,\n wrapEventListener\n);\nconst createNativeConvolverNode = createNativeConvolverNodeFactory(createNotSupportedError, overwriteAccessors);\nconst createConvolverNodeRenderer = createConvolverNodeRendererFactory(\n createNativeConvolverNode,\n getNativeAudioNode,\n renderInputsOfAudioNode\n);\nconst convolverNodeConstructor: TConvolverNodeConstructor = createConvolverNodeConstructor(\n audioNodeConstructor,\n createConvolverNodeRenderer,\n createNativeConvolverNode,\n getNativeContext,\n isNativeOfflineAudioContext,\n setAudioNodeTailTime\n);\nconst createDelayNodeRenderer = createDelayNodeRendererFactory(\n connectAudioParam,\n createNativeDelayNode,\n getNativeAudioNode,\n renderAutomation,\n renderInputsOfAudioNode\n);\nconst delayNodeConstructor: TDelayNodeConstructor = createDelayNodeConstructor(\n audioNodeConstructor,\n createAudioParam,\n createDelayNodeRenderer,\n createNativeDelayNode,\n getNativeContext,\n isNativeOfflineAudioContext,\n setAudioNodeTailTime\n);\nconst createNativeDynamicsCompressorNode = createNativeDynamicsCompressorNodeFactory(createNotSupportedError);\nconst createDynamicsCompressorNodeRenderer = createDynamicsCompressorNodeRendererFactory(\n connectAudioParam,\n createNativeDynamicsCompressorNode,\n getNativeAudioNode,\n renderAutomation,\n renderInputsOfAudioNode\n);\nconst dynamicsCompressorNodeConstructor: TDynamicsCompressorNodeConstructor = createDynamicsCompressorNodeConstructor(\n audioNodeConstructor,\n createAudioParam,\n createDynamicsCompressorNodeRenderer,\n createNativeDynamicsCompressorNode,\n createNotSupportedError,\n getNativeContext,\n isNativeOfflineAudioContext,\n setAudioNodeTailTime\n);\nconst createGainNodeRenderer = createGainNodeRendererFactory(\n connectAudioParam,\n createNativeGainNode,\n getNativeAudioNode,\n renderAutomation,\n renderInputsOfAudioNode\n);\nconst gainNodeConstructor: TGainNodeConstructor = createGainNodeConstructor(\n audioNodeConstructor,\n createAudioParam,\n createGainNodeRenderer,\n createNativeGainNode,\n getNativeContext,\n isNativeOfflineAudioContext\n);\nconst createNativeIIRFilterNodeFaker = createNativeIIRFilterNodeFakerFactory(\n createInvalidAccessError,\n createInvalidStateError,\n createNativeScriptProcessorNode,\n createNotSupportedError\n);\nconst renderNativeOfflineAudioContext = createRenderNativeOfflineAudioContext(\n cacheTestResult,\n createNativeGainNode,\n createNativeScriptProcessorNode,\n createTestOfflineAudioContextCurrentTimeSupport(createNativeGainNode, nativeOfflineAudioContextConstructor)\n);\nconst createIIRFilterNodeRenderer = createIIRFilterNodeRendererFactory(\n createNativeAudioBufferSourceNode,\n getNativeAudioNode,\n nativeOfflineAudioContextConstructor,\n renderInputsOfAudioNode,\n renderNativeOfflineAudioContext\n);\nconst createNativeIIRFilterNode = createNativeIIRFilterNodeFactory(createNativeIIRFilterNodeFaker);\nconst iIRFilterNodeConstructor: TIIRFilterNodeConstructor = createIIRFilterNodeConstructor(\n audioNodeConstructor,\n createNativeIIRFilterNode,\n createIIRFilterNodeRenderer,\n getNativeContext,\n isNativeOfflineAudioContext,\n setAudioNodeTailTime\n);\nconst createAudioListener = createAudioListenerFactory(\n createAudioParam,\n createNativeChannelMergerNode,\n createNativeConstantSourceNode,\n createNativeScriptProcessorNode,\n createNotSupportedError,\n getFirstSample,\n isNativeOfflineAudioContext,\n overwriteAccessors\n);\nconst unrenderedAudioWorkletNodeStore: TUnrenderedAudioWorkletNodeStore = new WeakMap();\nconst minimalBaseAudioContextConstructor = createMinimalBaseAudioContextConstructor(\n audioDestinationNodeConstructor,\n createAudioListener,\n eventTargetConstructor,\n isNativeOfflineAudioContext,\n unrenderedAudioWorkletNodeStore,\n wrapEventListener\n);\nconst createNativeOscillatorNode = createNativeOscillatorNodeFactory(\n addSilentConnection,\n cacheTestResult,\n testAudioScheduledSourceNodeStartMethodNegativeParametersSupport,\n testAudioScheduledSourceNodeStopMethodConsecutiveCallsSupport,\n testAudioScheduledSourceNodeStopMethodNegativeParametersSupport,\n wrapAudioScheduledSourceNodeStopMethodConsecutiveCalls\n);\nconst createOscillatorNodeRenderer = createOscillatorNodeRendererFactory(\n connectAudioParam,\n createNativeOscillatorNode,\n getNativeAudioNode,\n renderAutomation,\n renderInputsOfAudioNode\n);\nconst oscillatorNodeConstructor: TOscillatorNodeConstructor = createOscillatorNodeConstructor(\n audioNodeConstructor,\n createAudioParam,\n createNativeOscillatorNode,\n createOscillatorNodeRenderer,\n getNativeContext,\n isNativeOfflineAudioContext,\n wrapEventListener\n);\nconst createConnectedNativeAudioBufferSourceNode = createConnectedNativeAudioBufferSourceNodeFactory(createNativeAudioBufferSourceNode);\nconst createNativeWaveShaperNodeFaker = createNativeWaveShaperNodeFakerFactory(\n createConnectedNativeAudioBufferSourceNode,\n createInvalidStateError,\n createNativeGainNode,\n isDCCurve,\n monitorConnections\n);\nconst createNativeWaveShaperNode = createNativeWaveShaperNodeFactory(\n createConnectedNativeAudioBufferSourceNode,\n createInvalidStateError,\n createNativeWaveShaperNodeFaker,\n isDCCurve,\n monitorConnections,\n nativeAudioContextConstructor,\n overwriteAccessors\n);\nconst createNativePannerNodeFaker = createNativePannerNodeFakerFactory(\n connectNativeAudioNodeToNativeAudioNode,\n createInvalidStateError,\n createNativeChannelMergerNode,\n createNativeGainNode,\n createNativeScriptProcessorNode,\n createNativeWaveShaperNode,\n createNotSupportedError,\n disconnectNativeAudioNodeFromNativeAudioNode,\n getFirstSample,\n monitorConnections\n);\nconst createNativePannerNode = createNativePannerNodeFactory(createNativePannerNodeFaker);\nconst createPannerNodeRenderer = createPannerNodeRendererFactory(\n connectAudioParam,\n createNativeChannelMergerNode,\n createNativeConstantSourceNode,\n createNativeGainNode,\n createNativePannerNode,\n getNativeAudioNode,\n nativeOfflineAudioContextConstructor,\n renderAutomation,\n renderInputsOfAudioNode,\n renderNativeOfflineAudioContext\n);\nconst pannerNodeConstructor: TPannerNodeConstructor = createPannerNodeConstructor(\n audioNodeConstructor,\n createAudioParam,\n createNativePannerNode,\n createPannerNodeRenderer,\n getNativeContext,\n isNativeOfflineAudioContext,\n setAudioNodeTailTime\n);\nconst createNativePeriodicWave = createNativePeriodicWaveFactory(createIndexSizeError);\nconst periodicWaveConstructor: TPeriodicWaveConstructor = createPeriodicWaveConstructor(\n createNativePeriodicWave,\n getNativeContext,\n new WeakSet(),\n sanitizePeriodicWaveOptions\n);\nconst nativeStereoPannerNodeFakerFactory = createNativeStereoPannerNodeFakerFactory(\n createNativeChannelMergerNode,\n createNativeChannelSplitterNode,\n createNativeGainNode,\n createNativeWaveShaperNode,\n createNotSupportedError,\n monitorConnections\n);\nconst createNativeStereoPannerNode = createNativeStereoPannerNodeFactory(nativeStereoPannerNodeFakerFactory, createNotSupportedError);\nconst createStereoPannerNodeRenderer = createStereoPannerNodeRendererFactory(\n connectAudioParam,\n createNativeStereoPannerNode,\n getNativeAudioNode,\n renderAutomation,\n renderInputsOfAudioNode\n);\nconst stereoPannerNodeConstructor: TStereoPannerNodeConstructor = createStereoPannerNodeConstructor(\n audioNodeConstructor,\n createAudioParam,\n createNativeStereoPannerNode,\n createStereoPannerNodeRenderer,\n getNativeContext,\n isNativeOfflineAudioContext\n);\nconst createWaveShaperNodeRenderer = createWaveShaperNodeRendererFactory(\n createNativeWaveShaperNode,\n getNativeAudioNode,\n renderInputsOfAudioNode\n);\nconst waveShaperNodeConstructor: TWaveShaperNodeConstructor = createWaveShaperNodeConstructor(\n audioNodeConstructor,\n createInvalidStateError,\n createNativeWaveShaperNode,\n createWaveShaperNodeRenderer,\n getNativeContext,\n isNativeOfflineAudioContext,\n setAudioNodeTailTime\n);\nconst isSecureContext = createIsSecureContext(window);\nconst exposeCurrentFrameAndCurrentTime = createExposeCurrentFrameAndCurrentTime(window);\nconst backupOfflineAudioContextStore: TBackupOfflineAudioContextStore = new WeakMap();\nconst getOrCreateBackupOfflineAudioContext = createGetOrCreateBackupOfflineAudioContext(\n backupOfflineAudioContextStore,\n nativeOfflineAudioContextConstructor\n);\n\n// The addAudioWorkletModule() function is only available in a SecureContext.\nexport const addAudioWorkletModule: undefined | TAddAudioWorkletModuleFunction = isSecureContext\n ? createAddAudioWorkletModule(\n cacheTestResult,\n createNotSupportedError,\n createEvaluateSource(window),\n exposeCurrentFrameAndCurrentTime,\n createFetchSource(createAbortError),\n getNativeContext,\n getOrCreateBackupOfflineAudioContext,\n isNativeOfflineAudioContext,\n nativeAudioWorkletNodeConstructor,\n new WeakMap(),\n new WeakMap(),\n createTestAudioWorkletProcessorPostMessageSupport(nativeAudioWorkletNodeConstructor, nativeOfflineAudioContextConstructor),\n // @todo window is guaranteed to be defined because isSecureContext checks that as well.\n <NonNullable<typeof window>>window\n )\n : undefined;\n\nconst isNativeContext = createIsNativeContext(isNativeAudioContext, isNativeOfflineAudioContext);\n\nexport const decodeAudioData: TDecodeAudioDataFunction = createDecodeAudioData(\n audioBufferStore,\n cacheTestResult,\n createDataCloneError,\n createEncodingError,\n new WeakSet(),\n getNativeContext,\n isNativeContext,\n testAudioBufferCopyChannelMethodsOutOfBoundsSupport,\n testPromiseSupport,\n wrapAudioBufferCopyChannelMethods,\n wrapAudioBufferCopyChannelMethodsOutOfBounds\n);\n\nconst baseAudioContextConstructor = createBaseAudioContextConstructor(\n addAudioWorkletModule,\n analyserNodeConstructor,\n audioBufferConstructor,\n audioBufferSourceNodeConstructor,\n biquadFilterNodeConstructor,\n channelMergerNodeConstructor,\n channelSplitterNodeConstructor,\n constantSourceNodeConstructor,\n convolverNodeConstructor,\n decodeAudioData,\n delayNodeConstructor,\n dynamicsCompressorNodeConstructor,\n gainNodeConstructor,\n iIRFilterNodeConstructor,\n minimalBaseAudioContextConstructor,\n oscillatorNodeConstructor,\n pannerNodeConstructor,\n periodicWaveConstructor,\n stereoPannerNodeConstructor,\n waveShaperNodeConstructor\n);\nconst mediaElementAudioSourceNodeConstructor: TMediaElementAudioSourceNodeConstructor = createMediaElementAudioSourceNodeConstructor(\n audioNodeConstructor,\n createNativeMediaElementAudioSourceNode,\n getNativeContext,\n isNativeOfflineAudioContext\n);\nconst mediaStreamAudioDestinationNodeConstructor: TMediaStreamAudioDestinationNodeConstructor =\n createMediaStreamAudioDestinationNodeConstructor(\n audioNodeConstructor,\n createNativeMediaStreamAudioDestinationNode,\n getNativeContext,\n isNativeOfflineAudioContext\n );\nconst mediaStreamAudioSourceNodeConstructor: TMediaStreamAudioSourceNodeConstructor = createMediaStreamAudioSourceNodeConstructor(\n audioNodeConstructor,\n createNativeMediaStreamAudioSourceNode,\n getNativeContext,\n isNativeOfflineAudioContext\n);\nconst createNativeMediaStreamTrackAudioSourceNode = createNativeMediaStreamTrackAudioSourceNodeFactory(\n createInvalidStateError,\n isNativeOfflineAudioContext\n);\nconst mediaStreamTrackAudioSourceNodeConstructor: TMediaStreamTrackAudioSourceNodeConstructor =\n createMediaStreamTrackAudioSourceNodeConstructor(audioNodeConstructor, createNativeMediaStreamTrackAudioSourceNode, getNativeContext);\nconst audioContextConstructor: TAudioContextConstructor = createAudioContextConstructor(\n baseAudioContextConstructor,\n createInvalidStateError,\n createNotSupportedError,\n createUnknownError,\n mediaElementAudioSourceNodeConstructor,\n mediaStreamAudioDestinationNodeConstructor,\n mediaStreamAudioSourceNodeConstructor,\n mediaStreamTrackAudioSourceNodeConstructor,\n nativeAudioContextConstructor\n);\n\ntype audioContextConstructor = IAudioContext;\n\nexport { audioContextConstructor as AudioContext };\n\nconst getUnrenderedAudioWorkletNodes = createGetUnrenderedAudioWorkletNodes(unrenderedAudioWorkletNodeStore);\nconst addUnrenderedAudioWorkletNode = createAddUnrenderedAudioWorkletNode(getUnrenderedAudioWorkletNodes);\nconst connectMultipleOutputs = createConnectMultipleOutputs(createIndexSizeError);\nconst deleteUnrenderedAudioWorkletNode = createDeleteUnrenderedAudioWorkletNode(getUnrenderedAudioWorkletNodes);\nconst disconnectMultipleOutputs = createDisconnectMultipleOutputs(createIndexSizeError);\nconst activeAudioWorkletNodeInputsStore: TActiveAudioWorkletNodeInputsStore = new WeakMap();\nconst getActiveAudioWorkletNodeInputs = createGetActiveAudioWorkletNodeInputs(activeAudioWorkletNodeInputsStore, getValueForKey);\nconst createNativeAudioWorkletNodeFaker = createNativeAudioWorkletNodeFakerFactory(\n connectMultipleOutputs,\n createIndexSizeError,\n createInvalidStateError,\n createNativeChannelMergerNode,\n createNativeChannelSplitterNode,\n createNativeConstantSourceNode,\n createNativeGainNode,\n createNativeScriptProcessorNode,\n createNotSupportedError,\n disconnectMultipleOutputs,\n exposeCurrentFrameAndCurrentTime,\n getActiveAudioWorkletNodeInputs,\n monitorConnections\n);\nconst createNativeAudioWorkletNode = createNativeAudioWorkletNodeFactory(\n createInvalidStateError,\n createNativeAudioWorkletNodeFaker,\n createNativeGainNode,\n createNotSupportedError,\n monitorConnections\n);\nconst createAudioWorkletNodeRenderer = createAudioWorkletNodeRendererFactory(\n connectAudioParam,\n connectMultipleOutputs,\n createNativeAudioBufferSourceNode,\n createNativeChannelMergerNode,\n createNativeChannelSplitterNode,\n createNativeConstantSourceNode,\n createNativeGainNode,\n deleteUnrenderedAudioWorkletNode,\n disconnectMultipleOutputs,\n exposeCurrentFrameAndCurrentTime,\n getNativeAudioNode,\n nativeAudioWorkletNodeConstructor,\n nativeOfflineAudioContextConstructor,\n renderAutomation,\n renderInputsOfAudioNode,\n renderNativeOfflineAudioContext\n);\nconst getBackupOfflineAudioContext = createGetBackupOfflineAudioContext(backupOfflineAudioContextStore);\nconst setActiveAudioWorkletNodeInputs = createSetActiveAudioWorkletNodeInputs(activeAudioWorkletNodeInputsStore);\n\n// The AudioWorkletNode constructor is only available in a SecureContext.\nconst audioWorkletNodeConstructor: undefined | TAudioWorkletNodeConstructor = isSecureContext\n ? createAudioWorkletNodeConstructor(\n addUnrenderedAudioWorkletNode,\n audioNodeConstructor,\n createAudioParam,\n createAudioWorkletNodeRenderer,\n createNativeAudioWorkletNode,\n getAudioNodeConnections,\n getBackupOfflineAudioContext,\n getNativeContext,\n isNativeOfflineAudioContext,\n nativeAudioWorkletNodeConstructor,\n sanitizeAudioWorkletNodeOptions,\n setActiveAudioWorkletNodeInputs,\n testAudioWorkletNodeOptionsClonability,\n wrapEventListener\n )\n : undefined;\n\ntype audioWorkletNodeConstructor<T extends TContext> = undefined | IAudioWorkletNode<T>;\n\nexport { audioWorkletNodeConstructor as AudioWorkletNode };\n\ntype biquadFilterNodeConstructor<T extends TContext> = IBiquadFilterNode<T>;\n\nexport { biquadFilterNodeConstructor as BiquadFilterNode };\n\ntype channelMergerNodeConstructor<T extends TContext> = IAudioNode<T>;\n\nexport { channelMergerNodeConstructor as ChannelMergerNode };\n\ntype channelSplitterNodeConstructor<T extends TContext> = IAudioNode<T>;\n\nexport { channelSplitterNodeConstructor as ChannelSplitterNode };\n\ntype constantSourceNodeConstructor<T extends TContext> = IConstantSourceNode<T>;\n\nexport { convolverNodeConstructor as ConvolverNode };\n\ntype convolverNodeConstructor<T extends TContext> = IConvolverNode<T>;\n\nexport { constantSourceNodeConstructor as ConstantSourceNode };\n\ntype delayNodeConstructor<T extends TContext> = IDelayNode<T>;\n\nexport { delayNodeConstructor as DelayNode };\n\ntype dynamicsCompressorNodeConstructor<T extends TContext> = IDynamicsCompressorNode<T>;\n\nexport { dynamicsCompressorNodeConstructor as DynamicsCompressorNode };\n\ntype gainNodeConstructor<T extends TContext> = IGainNode<T>;\n\nexport { gainNodeConstructor as GainNode };\n\ntype iIRFilterNodeConstructor<T extends TContext> = IIIRFilterNode<T>;\n\nexport { iIRFilterNodeConstructor as IIRFilterNode };\n\ntype mediaElementAudioSourceNodeConstructor<T extends IAudioContext | IMinimalAudioContext> = IMediaElementAudioSourceNode<T>;\n\nexport { mediaElementAudioSourceNodeConstructor as MediaElementAudioSourceNode };\n\ntype mediaStreamAudioDestinationNodeConstructor<T extends IAudioContext | IMinimalAudioContext> = IMediaStreamAudioDestinationNode<T>;\n\nexport { mediaStreamAudioDestinationNodeConstructor as MediaStreamAudioDestinationNode };\n\ntype mediaStreamAudioSourceNodeConstructor<T extends IAudioContext | IMinimalAudioContext> = IMediaStreamAudioSourceNode<T>;\n\nexport { mediaStreamAudioSourceNodeConstructor as MediaStreamAudioSourceNode };\n\ntype mediaStreamTrackAudioSourceNodeConstructor<T extends IAudioContext | IMinimalAudioContext> = IMediaStreamTrackAudioSourceNode<T>;\n\nexport { mediaStreamTrackAudioSourceNodeConstructor as MediaStreamTrackAudioSourceNode };\n\nconst minimalAudioContextConstructor: TMinimalAudioContextConstructor = createMinimalAudioContextConstructor(\n createInvalidStateError,\n createNotSupportedError,\n createUnknownError,\n minimalBaseAudioContextConstructor,\n nativeAudioContextConstructor\n);\n\ntype minimalAudioContextConstructor = IMinimalAudioContext;\n\nexport { minimalAudioContextConstructor as MinimalAudioContext };\n\nconst createNativeOfflineAudioContext = createCreateNativeOfflineAudioContext(\n createNotSupportedError,\n nativeOfflineAudioContextConstructor\n);\nconst startRendering = createStartRendering(\n audioBufferStore,\n cacheTestResult,\n getAudioNodeRenderer,\n getUnrenderedAudioWorkletNodes,\n renderNativeOfflineAudioContext,\n testAudioBufferCopyChannelMethodsOutOfBoundsSupport,\n wrapAudioBufferCopyChannelMethods,\n wrapAudioBufferCopyChannelMethodsOutOfBounds\n);\nconst minimalOfflineAudioContextConstructor: TMinimalOfflineAudioContextConstructor = createMinimalOfflineAudioContextConstructor(\n cacheTestResult,\n createInvalidStateError,\n createNativeOfflineAudioContext,\n minimalBaseAudioContextConstructor,\n startRendering\n);\n\ntype minimalOfflineAudioContextConstructor = IMinimalOfflineAudioContext;\n\nexport { minimalOfflineAudioContextConstructor as MinimalOfflineAudioContext };\n\nconst offlineAudioContextConstructor: IOfflineAudioContextConstructor = createOfflineAudioContextConstructor(\n baseAudioContextConstructor,\n cacheTestResult,\n createInvalidStateError,\n createNativeOfflineAudioContext,\n startRendering\n);\n\ntype offlineAudioContextConstructor = IOfflineAudioContext;\n\nexport { offlineAudioContextConstructor as OfflineAudioContext };\n\ntype oscillatorNodeConstructor<T extends TContext> = IOscillatorNode<T>;\n\nexport { oscillatorNodeConstructor as OscillatorNode };\n\ntype pannerNodeConstructor<T extends TContext> = IPannerNode<T>;\n\nexport { pannerNodeConstructor as PannerNode };\n\ntype periodicWaveConstructor = IPeriodicWave;\n\nexport { periodicWaveConstructor as PeriodicWave };\n\ntype stereoPannerNodeConstructor<T extends TContext> = IStereoPannerNode<T>;\n\nexport { stereoPannerNodeConstructor as StereoPannerNode };\n\ntype waveShaperNodeConstructor<T extends TContext> = IWaveShaperNode<T>;\n\nexport { waveShaperNodeConstructor as WaveShaperNode };\n\nexport const isAnyAudioContext = createIsAnyAudioContext(CONTEXT_STORE, isNativeAudioContext);\n\nexport const isAnyAudioNode = createIsAnyAudioNode(AUDIO_NODE_STORE, isNativeAudioNode);\n\nexport const isAnyAudioParam = createIsAnyAudioParam(AUDIO_PARAM_STORE, isNativeAudioParam);\n\nexport const isAnyOfflineAudioContext = createIsAnyOfflineAudioContext(CONTEXT_STORE, isNativeOfflineAudioContext);\n\nexport const isSupported = () =>\n createIsSupportedPromise(\n cacheTestResult,\n createTestAudioBufferCopyChannelMethodsSubarraySupport(nativeOfflineAudioContextConstructor),\n createTestAudioContextCloseMethodSupport(nativeAudioContextConstructor),\n createTestAudioContextDecodeAudioDataMethodTypeErrorSupport(nativeOfflineAudioContextConstructor),\n createTestAudioContextOptionsSupport(nativeAudioContextConstructor),\n createTestAudioNodeConnectMethodSupport(nativeOfflineAudioContextConstructor),\n createTestAudioWorkletProcessorNoOutputsSupport(nativeAudioWorkletNodeConstructor, nativeOfflineAudioContextConstructor),\n createTestChannelMergerNodeChannelCountSupport(nativeOfflineAudioContextConstructor),\n createTestConstantSourceNodeAccurateSchedulingSupport(nativeOfflineAudioContextConstructor),\n createTestConvolverNodeBufferReassignabilitySupport(nativeOfflineAudioContextConstructor),\n createTestConvolverNodeChannelCountSupport(nativeOfflineAudioContextConstructor),\n testDomExceptionConstructorSupport,\n createTestIsSecureContextSupport(window),\n createTestMediaStreamAudioSourceNodeMediaStreamWithoutAudioTrackSupport(nativeAudioContextConstructor),\n createTestStereoPannerNodeDefaultValueSupport(nativeOfflineAudioContextConstructor),\n testTransferablesSupport\n );\n","import { TAbortErrorFactory } from '../types';\n\nexport const createAbortError: TAbortErrorFactory = () => new DOMException('', 'AbortError');\n","import { TAddActiveInputConnectionToAudioNodeFactory } from '../types/add-active-input-connection-to-audio-node-factory';\n\nexport const createAddActiveInputConnectionToAudioNode: TAddActiveInputConnectionToAudioNodeFactory = (insertElementInSet) => {\n return (activeInputs, source, [output, input, eventListener], ignoreDuplicates) => {\n insertElementInSet(\n activeInputs[input],\n [source, output, eventListener],\n (activeInputConnection) => activeInputConnection[0] === source && activeInputConnection[1] === output,\n ignoreDuplicates\n );\n };\n};\n","import { IAudioNode, IAudioNodeRenderer, IMinimalOfflineAudioContext, IOfflineAudioContext } from '../interfaces';\nimport { TActiveInputConnection, TAddAudioNodeConnectionsFactory, TContext, TNativeAudioNode } from '../types';\n\nexport const createAddAudioNodeConnections: TAddAudioNodeConnectionsFactory = (audioNodeConnectionsStore) => {\n return <T extends TContext>(\n audioNode: IAudioNode<T>,\n audioNodeRenderer: T extends IMinimalOfflineAudioContext | IOfflineAudioContext ? IAudioNodeRenderer<T, IAudioNode<T>> : null,\n nativeAudioNode: TNativeAudioNode\n ) => {\n const activeInputs = [];\n\n for (let i = 0; i < nativeAudioNode.numberOfInputs; i += 1) {\n activeInputs.push(new Set<TActiveInputConnection<T>>());\n }\n\n audioNodeConnectionsStore.set(audioNode, {\n activeInputs,\n outputs: new Set(),\n passiveInputs: new WeakMap(),\n renderer: audioNodeRenderer\n });\n };\n};\n","import { IAudioParam, IAudioParamRenderer, IMinimalOfflineAudioContext, IOfflineAudioContext } from '../interfaces';\nimport { TAddAudioParamConnectionsFactory, TContext } from '../types';\n\nexport const createAddAudioParamConnections: TAddAudioParamConnectionsFactory = (audioParamConnectionsStore) => {\n return <T extends TContext>(\n audioParam: IAudioParam,\n audioParamRenderer: T extends IMinimalOfflineAudioContext | IOfflineAudioContext ? IAudioParamRenderer : null\n ) => {\n audioParamConnectionsStore.set(audioParam, { activeInputs: new Set(), passiveInputs: new WeakMap(), renderer: audioParamRenderer });\n };\n};\n","import { IAudioNode, IAudioWorkletProcessor, IAudioWorkletProcessorConstructor } from './interfaces';\nimport {\n TAudioNodeConnectionsStore,\n TAudioNodeStore,\n TAudioParamConnectionsStore,\n TAudioParamStore,\n TContext,\n TContextStore,\n TCycleCounters,\n TInternalStateEventListener,\n TNativeAudioWorkletNode,\n TNativeContext\n} from './types';\n\nexport const ACTIVE_AUDIO_NODE_STORE: WeakSet<IAudioNode<TContext>> = new WeakSet();\n\nexport const AUDIO_NODE_CONNECTIONS_STORE: TAudioNodeConnectionsStore = new WeakMap();\n\nexport const AUDIO_NODE_STORE: TAudioNodeStore = new WeakMap();\n\nexport const AUDIO_PARAM_CONNECTIONS_STORE: TAudioParamConnectionsStore = new WeakMap();\n\nexport const AUDIO_PARAM_STORE: TAudioParamStore = new WeakMap();\n\nexport const CONTEXT_STORE: TContextStore = new WeakMap();\n\nexport const EVENT_LISTENERS: WeakMap<IAudioNode<TContext>, Set<TInternalStateEventListener>> = new WeakMap();\n\nexport const CYCLE_COUNTERS: TCycleCounters = new WeakMap();\n\n// This clunky name is borrowed from the spec. :-)\nexport const NODE_NAME_TO_PROCESSOR_CONSTRUCTOR_MAPS: WeakMap<\n TNativeContext,\n Map<string, IAudioWorkletProcessorConstructor>\n> = new WeakMap();\n\nexport const NODE_TO_PROCESSOR_MAPS: WeakMap<\n TNativeContext,\n WeakMap<TNativeAudioWorkletNode, Promise<IAudioWorkletProcessor>>\n> = new WeakMap();\n","import { TConstructor } from '../types';\n\nconst handler = {\n construct(): any {\n return handler;\n }\n};\n\nexport const isConstructible = (constructible: TConstructor): boolean => {\n try {\n const proxy = new Proxy(constructible, handler);\n\n new proxy(); // tslint:disable-line:no-unused-expression\n } catch {\n return false;\n }\n\n return true;\n};\n","/*\n * This massive regex tries to cover all the following cases.\n *\n * import './path';\n * import defaultImport from './path';\n * import { namedImport } from './path';\n * import { namedImport as renamendImport } from './path';\n * import * as namespaceImport from './path';\n * import defaultImport, { namedImport } from './path';\n * import defaultImport, { namedImport as renamendImport } from './path';\n * import defaultImport, * as namespaceImport from './path';\n */\nconst IMPORT_STATEMENT_REGEX = /^import(?:(?:[\\s]+[\\w]+|(?:[\\s]+[\\w]+[\\s]*,)?[\\s]*\\{[\\s]*[\\w]+(?:[\\s]+as[\\s]+[\\w]+)?(?:[\\s]*,[\\s]*[\\w]+(?:[\\s]+as[\\s]+[\\w]+)?)*[\\s]*}|(?:[\\s]+[\\w]+[\\s]*,)?[\\s]*\\*[\\s]+as[\\s]+[\\w]+)[\\s]+from)?(?:[\\s]*)(\"([^\"\\\\]|\\\\.)+\"|'([^'\\\\]|\\\\.)+')(?:[\\s]*);?/; // tslint:disable-line:max-line-length\n\nexport const splitImportStatements = (source: string, url: string): [string, string] => {\n const importStatements = [];\n\n let sourceWithoutImportStatements = source.replace(/^[\\s]+/, '');\n let result = sourceWithoutImportStatements.match(IMPORT_STATEMENT_REGEX);\n\n while (result !== null) {\n const unresolvedUrl = result[1].slice(1, -1);\n\n const importStatementWithResolvedUrl = result[0]\n .replace(/([\\s]+)?;?$/, '')\n .replace(unresolvedUrl, new URL(unresolvedUrl, url).toString());\n importStatements.push(importStatementWithResolvedUrl);\n\n sourceWithoutImportStatements = sourceWithoutImportStatements.slice(result[0].length).replace(/^[\\s]+/, '');\n result = sourceWithoutImportStatements.match(IMPORT_STATEMENT_REGEX);\n }\n\n return [importStatements.join(';'), sourceWithoutImportStatements];\n};\n","import { NODE_NAME_TO_PROCESSOR_CONSTRUCTOR_MAPS } from '../globals';\nimport { isConstructible } from '../helpers/is-constructible';\nimport { splitImportStatements } from '../helpers/split-import-statements';\nimport { IAudioWorkletProcessorConstructor } from '../interfaces';\nimport { TAddAudioWorkletModuleFactory, TEvaluateAudioWorkletGlobalScopeFunction } from '../types';\n\nconst verifyParameterDescriptors = (parameterDescriptors: IAudioWorkletProcessorConstructor['parameterDescriptors']) => {\n if (parameterDescriptors !== undefined && !Array.isArray(parameterDescriptors)) {\n throw new TypeError('The parameterDescriptors property of given value for processorCtor is not an array.');\n }\n};\n\nconst verifyProcessorCtor = <T extends IAudioWorkletProcessorConstructor>(processorCtor: T) => {\n if (!isConstructible(processorCtor)) {\n throw new TypeError('The given value for processorCtor should be a constructor.');\n }\n\n if (processorCtor.prototype === null || typeof processorCtor.prototype !== 'object') {\n throw new TypeError('The given value for processorCtor should have a prototype.');\n }\n};\n\nexport const createAddAudioWorkletModule: TAddAudioWorkletModuleFactory = (\n cacheTestResult,\n createNotSupportedError,\n evaluateSource,\n exposeCurrentFrameAndCurrentTime,\n fetchSource,\n getNativeContext,\n getOrCreateBackupOfflineAudioContext,\n isNativeOfflineAudioContext,\n nativeAudioWorkletNodeConstructor,\n ongoingRequests,\n resolvedRequests,\n testAudioWorkletProcessorPostMessageSupport,\n window\n) => {\n let index = 0;\n\n return (context, moduleURL, options = { credentials: 'omit' }) => {\n const resolvedRequestsOfContext = resolvedRequests.get(context);\n\n if (resolvedRequestsOfContext !== undefined && resolvedRequestsOfContext.has(moduleURL)) {\n return Promise.resolve();\n }\n\n const ongoingRequestsOfContext = ongoingRequests.get(context);\n\n if (ongoingRequestsOfContext !== undefined) {\n const promiseOfOngoingRequest = ongoingRequestsOfContext.get(moduleURL);\n\n if (promiseOfOngoingRequest !== undefined) {\n return promiseOfOngoingRequest;\n }\n }\n\n const nativeContext = getNativeContext(context);\n\n // Bug #59: Safari does not implement the audioWorklet property.\n const promise =\n nativeContext.audioWorklet === undefined\n ? fetchSource(moduleURL)\n .then(([source, absoluteUrl]) => {\n const [importStatements, sourceWithoutImportStatements] = splitImportStatements(source, absoluteUrl);\n\n /*\n * This is the unminified version of the code used below:\n *\n * ```js\n * ${ importStatements };\n * ((a, b) => {\n * (a[b] = a[b] || [ ]).push(\n * (AudioWorkletProcessor, global, registerProcessor, sampleRate, self, window) => {\n * ${ sourceWithoutImportStatements }\n * }\n * );\n * })(window, '_AWGS');\n * ```\n */\n // tslint:disable-next-line:max-line-length\n const wrappedSource = `${importStatements};((a,b)=>{(a[b]=a[b]||[]).push((AudioWorkletProcessor,global,registerProcessor,sampleRate,self,window)=>{${sourceWithoutImportStatements}\n})})(window,'_AWGS')`;\n\n // @todo Evaluating the given source code is a possible security problem.\n return evaluateSource(wrappedSource);\n })\n .then(() => {\n const evaluateAudioWorkletGlobalScope = (<TEvaluateAudioWorkletGlobalScopeFunction[]>(<any>window)._AWGS).pop();\n\n if (evaluateAudioWorkletGlobalScope === undefined) {\n // Bug #182 Chrome and Edge do throw an instance of a SyntaxError instead of a DOMException.\n throw new SyntaxError();\n }\n\n exposeCurrentFrameAndCurrentTime(nativeContext.currentTime, nativeContext.sampleRate, () =>\n evaluateAudioWorkletGlobalScope(\n class AudioWorkletProcessor {},\n undefined,\n (name, processorCtor) => {\n if (name.trim() === '') {\n throw createNotSupportedError();\n }\n\n const nodeNameToProcessorConstructorMap = NODE_NAME_TO_PROCESSOR_CONSTRUCTOR_MAPS.get(nativeContext);\n\n if (nodeNameToProcessorConstructorMap !== undefined) {\n if (nodeNameToProcessorConstructorMap.has(name)) {\n throw createNotSupportedError();\n }\n\n verifyProcessorCtor(processorCtor);\n verifyParameterDescriptors(processorCtor.parameterDescriptors);\n\n nodeNameToProcessorConstructorMap.set(name, processorCtor);\n } else {\n verifyProcessorCtor(processorCtor);\n verifyParameterDescriptors(processorCtor.parameterDescriptors);\n\n NODE_NAME_TO_PROCESSOR_CONSTRUCTOR_MAPS.set(nativeContext, new Map([[name, processorCtor]]));\n }\n },\n nativeContext.sampleRate,\n undefined,\n undefined\n )\n );\n })\n : Promise.all([\n fetchSource(moduleURL),\n Promise.resolve(\n cacheTestResult(testAudioWorkletProcessorPostMessageSupport, testAudioWorkletProcessorPostMessageSupport)\n )\n ]).then(([[source, absoluteUrl], isSupportingPostMessage]) => {\n const currentIndex = index + 1;\n\n index = currentIndex;\n\n const [importStatements, sourceWithoutImportStatements] = splitImportStatements(source, absoluteUrl);\n /*\n * Bug #179: Firefox does not allow to transfer any buffer which has been passed to the process() method as an argument.\n *\n * This is the unminified version of the code used below.\n *\n * ```js\n * class extends AudioWorkletProcessor {\n *\n * __buffers = new WeakSet();\n *\n * constructor () {\n * super();\n *\n * this.port.postMessage = ((postMessage) => {\n * return (message, transferables) => {\n * const filteredTransferables = (transferables)\n * ? transferables.filter((transferable) => !this.__buffers.has(transferable))\n * : transferables;\n *\n * return postMessage.call(this.port, message, filteredTransferables);\n * };\n * })(this.port.postMessage);\n * }\n * }\n * ```\n */\n const patchedAudioWorkletProcessor = isSupportingPostMessage\n ? 'AudioWorkletProcessor'\n : 'class extends AudioWorkletProcessor {__b=new WeakSet();constructor(){super();(p=>p.postMessage=(q=>(m,t)=>q.call(p,m,t?t.filter(u=>!this.__b.has(u)):t))(p.postMessage))(this.port)}}';\n /*\n * Bug #170: Chrome and Edge do call process() with an array with empty channelData for each input if no input is connected.\n *\n * Bug #179: Firefox does not allow to transfer any buffer which has been passed to the process() method as an argument.\n *\n * Bug #190: Safari doesn't throw an error when loading an unparsable module.\n *\n * This is the unminified version of the code used below:\n *\n * ```js\n * `${ importStatements };\n * ((AudioWorkletProcessor, registerProcessor) => {${ sourceWithoutImportStatements }\n * })(\n * ${ patchedAudioWorkletProcessor },\n * (name, processorCtor) => registerProcessor(name, class extends processorCtor {\n *\n * __collectBuffers = (array) => {\n * array.forEach((element) => this.__buffers.add(element.buffer));\n * };\n *\n * process (inputs, outputs, parameters) {\n * inputs.forEach(this.__collectBuffers);\n * outputs.forEach(this.__collectBuffers);\n * this.__collectBuffers(Object.values(parameters));\n *\n * return super.process(\n * (inputs.map((input) => input.some((channelData) => channelData.length === 0)) ? [ ] : input),\n * outputs,\n * parameters\n * );\n * }\n *\n * })\n * );\n *\n * registerProcessor(`__sac${currentIndex}`, class extends AudioWorkletProcessor{\n *\n * process () {\n * return false;\n * }\n *\n * })`\n * ```\n */\n const memberDefinition = isSupportingPostMessage ? '' : '__c = (a) => a.forEach(e=>this.__b.add(e.buffer));';\n const bufferRegistration = isSupportingPostMessage\n ? ''\n : 'i.forEach(this.__c);o.forEach(this.__c);this.__c(Object.values(p));';\n const wrappedSource = `${importStatements};((AudioWorkletProcessor,registerProcessor)=>{${sourceWithoutImportStatements}\n})(${patchedAudioWorkletProcessor},(n,p)=>registerProcessor(n,class extends p{${memberDefinition}process(i,o,p){${bufferRegistration}return super.process(i.map(j=>j.some(k=>k.length===0)?[]:j),o,p)}}));registerProcessor('__sac${currentIndex}',class extends AudioWorkletProcessor{process(){return !1}})`;\n const blob = new Blob([wrappedSource], { type: 'application/javascript; charset=utf-8' });\n const url = URL.createObjectURL(blob);\n\n return nativeContext.audioWorklet\n .addModule(url, options)\n .then(() => {\n if (isNativeOfflineAudioContext(nativeContext)) {\n return nativeContext;\n }\n\n // Bug #186: Chrome and Edge do not allow to create an AudioWorkletNode on a closed AudioContext.\n const backupOfflineAudioContext = getOrCreateBackupOfflineAudioContext(nativeContext);\n\n return backupOfflineAudioContext.audioWorklet.addModule(url, options).then(() => backupOfflineAudioContext);\n })\n .then((nativeContextOrBackupOfflineAudioContext) => {\n if (nativeAudioWorkletNodeConstructor === null) {\n throw new SyntaxError();\n }\n\n try {\n // Bug #190: Safari doesn't throw an error when loading an unparsable module.\n new nativeAudioWorkletNodeConstructor(nativeContextOrBackupOfflineAudioContext, `__sac${currentIndex}`); // tslint:disable-line:no-unused-expression\n } catch {\n throw new SyntaxError();\n }\n })\n .finally(() => URL.revokeObjectURL(url));\n });\n\n if (ongoingRequestsOfContext === undefined) {\n ongoingRequests.set(context, new Map([[moduleURL, promise]]));\n } else {\n ongoingRequestsOfContext.set(moduleURL, promise);\n }\n\n promise\n .then(() => {\n const updatedResolvedRequestsOfContext = resolvedRequests.get(context);\n\n if (updatedResolvedRequestsOfContext === undefined) {\n resolvedRequests.set(context, new Set([moduleURL]));\n } else {\n updatedResolvedRequestsOfContext.add(moduleURL);\n }\n })\n .finally(() => {\n const updatedOngoingRequestsOfContext = ongoingRequests.get(context);\n\n if (updatedOngoingRequestsOfContext !== undefined) {\n updatedOngoingRequestsOfContext.delete(moduleURL);\n }\n });\n\n return promise;\n };\n};\n","import { TGetValueForKeyFunction } from '../types';\n\nexport const getValueForKey: TGetValueForKeyFunction = (map, key) => {\n const value = map.get(key);\n\n if (value === undefined) {\n throw new Error('A value with the given key could not be found.');\n }\n\n return value;\n};\n","import { TPickElementFromSetFunction } from '../types';\n\nexport const pickElementFromSet: TPickElementFromSetFunction = (set, predicate) => {\n const matchingElements = Array.from(set).filter(predicate);\n\n if (matchingElements.length > 1) {\n throw Error('More than one element was found.');\n }\n\n if (matchingElements.length === 0) {\n throw Error('No element was found.');\n }\n\n const [matchingElement] = matchingElements;\n\n set.delete(matchingElement);\n\n return matchingElement;\n};\n","import { IAudioNode } from '../interfaces';\nimport { TContext, TPassiveAudioNodeInputConnection } from '../types';\nimport { getValueForKey } from './get-value-for-key';\nimport { pickElementFromSet } from './pick-element-from-set';\n\nexport const deletePassiveInputConnectionToAudioNode = <T extends TContext>(\n passiveInputs: WeakMap<IAudioNode<T>, Set<TPassiveAudioNodeInputConnection>>,\n source: IAudioNode<T>,\n output: number,\n input: number\n) => {\n const passiveInputConnections = getValueForKey(passiveInputs, source);\n const matchingConnection = pickElementFromSet(\n passiveInputConnections,\n (passiveInputConnection) => passiveInputConnection[0] === output && passiveInputConnection[1] === input\n );\n\n if (passiveInputConnections.size === 0) {\n passiveInputs.delete(source);\n }\n\n return matchingConnection;\n};\n","import { EVENT_LISTENERS } from '../globals';\nimport { TGetEventListenersOfAudioNodeFunction } from '../types';\nimport { getValueForKey } from './get-value-for-key';\n\nexport const getEventListenersOfAudioNode: TGetEventListenersOfAudioNodeFunction = (audioNode) => {\n return getValueForKey(EVENT_LISTENERS, audioNode);\n};\n","import { ACTIVE_AUDIO_NODE_STORE } from '../globals';\nimport { IAudioNode } from '../interfaces';\nimport { TContext } from '../types';\nimport { getEventListenersOfAudioNode } from './get-event-listeners-of-audio-node';\n\nexport const setInternalStateToActive = <T extends TContext>(audioNode: IAudioNode<T>) => {\n if (ACTIVE_AUDIO_NODE_STORE.has(audioNode)) {\n throw new Error('The AudioNode is already stored.');\n }\n\n ACTIVE_AUDIO_NODE_STORE.add(audioNode);\n\n getEventListenersOfAudioNode(audioNode).forEach((eventListener) => eventListener(true));\n};\n","import { IAudioNode, IAudioWorkletNode } from '../interfaces';\nimport { TContext } from '../types';\n\nexport const isAudioWorkletNode = <T extends TContext>(audioNode: IAudioNode<T>): audioNode is IAudioWorkletNode<T> => {\n return 'port' in audioNode;\n};\n","import { ACTIVE_AUDIO_NODE_STORE } from '../globals';\nimport { IAudioNode } from '../interfaces';\nimport { TContext } from '../types';\nimport { getEventListenersOfAudioNode } from './get-event-listeners-of-audio-node';\n\nexport const setInternalStateToPassive = <T extends TContext>(audioNode: IAudioNode<T>) => {\n if (!ACTIVE_AUDIO_NODE_STORE.has(audioNode)) {\n throw new Error('The AudioNode is not stored.');\n }\n\n ACTIVE_AUDIO_NODE_STORE.delete(audioNode);\n\n getEventListenersOfAudioNode(audioNode).forEach((eventListener) => eventListener(false));\n};\n","import { isAudioWorkletNode } from '../guards/audio-worklet-node';\nimport { IAudioNode } from '../interfaces';\nimport { TActiveInputConnection, TContext } from '../types';\nimport { setInternalStateToPassive } from './set-internal-state-to-passive';\n\n// Set the internalState of the audioNode to 'passive' if it is not an AudioWorkletNode and if it has no 'active' input connections.\nexport const setInternalStateToPassiveWhenNecessary = <T extends TContext>(\n audioNode: IAudioNode<T>,\n activeInputs: Set<TActiveInputConnection<T>>[]\n) => {\n if (!isAudioWorkletNode(audioNode) && activeInputs.every((connections) => connections.size === 0)) {\n setInternalStateToPassive(audioNode);\n }\n};\n","import { deletePassiveInputConnectionToAudioNode } from '../helpers/delete-passive-input-connection-to-audio-node';\nimport { setInternalStateToActive } from '../helpers/set-internal-state-to-active';\nimport { setInternalStateToPassiveWhenNecessary } from '../helpers/set-internal-state-to-passive-when-necessary';\nimport { IAudioNode } from '../interfaces';\nimport { TAddConnectionToAudioNodeFactory, TContext, TInternalStateEventListener } from '../types';\n\nexport const createAddConnectionToAudioNode: TAddConnectionToAudioNodeFactory = (\n addActiveInputConnectionToAudioNode,\n addPassiveInputConnectionToAudioNode,\n connectNativeAudioNodeToNativeAudioNode,\n deleteActiveInputConnectionToAudioNode,\n disconnectNativeAudioNodeFromNativeAudioNode,\n getAudioNodeConnections,\n getAudioNodeTailTime,\n getEventListenersOfAudioNode,\n getNativeAudioNode,\n insertElementInSet,\n isActiveAudioNode,\n isPartOfACycle,\n isPassiveAudioNode\n) => {\n const tailTimeTimeoutIds = new WeakMap<IAudioNode<TContext>, number>();\n\n return (source, destination, output, input, isOffline) => {\n const { activeInputs, passiveInputs } = getAudioNodeConnections(destination);\n const { outputs } = getAudioNodeConnections(source);\n const eventListeners = getEventListenersOfAudioNode(source);\n\n const eventListener: TInternalStateEventListener = (isActive) => {\n const nativeDestinationAudioNode = getNativeAudioNode(destination);\n const nativeSourceAudioNode = getNativeAudioNode(source);\n\n if (isActive) {\n const partialConnection = deletePassiveInputConnectionToAudioNode(passiveInputs, source, output, input);\n\n addActiveInputConnectionToAudioNode(activeInputs, source, partialConnection, false);\n\n if (!isOffline && !isPartOfACycle(source)) {\n connectNativeAudioNodeToNativeAudioNode(nativeSourceAudioNode, nativeDestinationAudioNode, output, input);\n }\n\n if (isPassiveAudioNode(destination)) {\n setInternalStateToActive(destination);\n }\n } else {\n const partialConnection = deleteActiveInputConnectionToAudioNode(activeInputs, source, output, input);\n\n addPassiveInputConnectionToAudioNode(passiveInputs, input, partialConnection, false);\n\n if (!isOffline && !isPartOfACycle(source)) {\n disconnectNativeAudioNodeFromNativeAudioNode(nativeSourceAudioNode, nativeDestinationAudioNode, output, input);\n }\n\n const tailTime = getAudioNodeTailTime(destination);\n\n if (tailTime === 0) {\n if (isActiveAudioNode(destination)) {\n setInternalStateToPassiveWhenNecessary(destination, activeInputs);\n }\n } else {\n const tailTimeTimeoutId = tailTimeTimeoutIds.get(destination);\n\n if (tailTimeTimeoutId !== undefined) {\n clearTimeout(tailTimeTimeoutId);\n }\n\n tailTimeTimeoutIds.set(\n destination,\n setTimeout(() => {\n if (isActiveAudioNode(destination)) {\n setInternalStateToPassiveWhenNecessary(destination, activeInputs);\n }\n }, tailTime * 1000)\n );\n }\n }\n };\n\n if (\n insertElementInSet(\n outputs,\n [destination, output, input],\n (outputConnection) =>\n outputConnection[0] === destination && outputConnection[1] === output && outputConnection[2] === input,\n true\n )\n ) {\n eventListeners.add(eventListener);\n\n if (isActiveAudioNode(source)) {\n addActiveInputConnectionToAudioNode(activeInputs, source, [output, input, eventListener], true);\n } else {\n addPassiveInputConnectionToAudioNode(passiveInputs, input, [source, output, eventListener], true);\n }\n\n return true;\n }\n\n return false;\n };\n};\n","import { TAddPassiveInputConnectionToAudioNodeFactory } from '../types';\n\nexport const createAddPassiveInputConnectionToAudioNode: TAddPassiveInputConnectionToAudioNodeFactory = (insertElementInSet) => {\n return (passiveInputs, input, [source, output, eventListener], ignoreDuplicates) => {\n const passiveInputConnections = passiveInputs.get(source);\n\n if (passiveInputConnections === undefined) {\n passiveInputs.set(source, new Set([[output, input, eventListener]]));\n } else {\n insertElementInSet(\n passiveInputConnections,\n [output, input, eventListener],\n (passiveInputConnection) => passiveInputConnection[0] === output && passiveInputConnection[1] === input,\n ignoreDuplicates\n );\n }\n };\n};\n","import { TAddSilentConnectionFactory } from '../types';\n\nexport const createAddSilentConnection: TAddSilentConnectionFactory = (createNativeGainNode) => {\n return (nativeContext, nativeAudioScheduledSourceNode) => {\n const nativeGainNode = createNativeGainNode(nativeContext, {\n channelCount: 1,\n channelCountMode: 'explicit',\n channelInterpretation: 'discrete',\n gain: 0\n });\n\n nativeAudioScheduledSourceNode.connect(nativeGainNode).connect(nativeContext.destination);\n\n const disconnect = () => {\n nativeAudioScheduledSourceNode.removeEventListener('ended', disconnect);\n nativeAudioScheduledSourceNode.disconnect(nativeGainNode);\n nativeGainNode.disconnect();\n };\n\n nativeAudioScheduledSourceNode.addEventListener('ended', disconnect);\n };\n};\n","import { TAddUnrenderedAudioWorkletNodeFactory } from '../types';\n\nexport const createAddUnrenderedAudioWorkletNode: TAddUnrenderedAudioWorkletNodeFactory = (getUnrenderedAudioWorkletNodes) => {\n return (nativeContext, audioWorkletNode) => {\n getUnrenderedAudioWorkletNodes(nativeContext).add(audioWorkletNode);\n };\n};\n","import { IAnalyserNode, IAnalyserOptions } from '../interfaces';\nimport { TAnalyserNodeConstructorFactory, TAudioNodeRenderer, TContext, TNativeAnalyserNode } from '../types';\n\nconst DEFAULT_OPTIONS = {\n channelCount: 2,\n channelCountMode: 'max',\n channelInterpretation: 'speakers',\n fftSize: 2048,\n maxDecibels: -30,\n minDecibels: -100,\n smoothingTimeConstant: 0.8\n} as const;\n\nexport const createAnalyserNodeConstructor: TAnalyserNodeConstructorFactory = (\n audionNodeConstructor,\n createAnalyserNodeRenderer,\n createIndexSizeError,\n createNativeAnalyserNode,\n getNativeContext,\n isNativeOfflineAudioContext\n) => {\n return class AnalyserNode<T extends TContext> extends audionNodeConstructor<T> implements IAnalyserNode<T> {\n private _nativeAnalyserNode: TNativeAnalyserNode;\n\n constructor(context: T, options?: Partial<IAnalyserOptions>) {\n const nativeContext = getNativeContext(context);\n const mergedOptions = { ...DEFAULT_OPTIONS, ...options };\n const nativeAnalyserNode = createNativeAnalyserNode(nativeContext, mergedOptions);\n const analyserNodeRenderer = <TAudioNodeRenderer<T, this>>(\n (isNativeOfflineAudioContext(nativeContext) ? createAnalyserNodeRenderer() : null)\n );\n\n super(context, false, nativeAnalyserNode, analyserNodeRenderer);\n\n this._nativeAnalyserNode = nativeAnalyserNode;\n }\n\n get fftSize(): number {\n return this._nativeAnalyserNode.fftSize;\n }\n\n set fftSize(value) {\n this._nativeAnalyserNode.fftSize = value;\n }\n\n get frequencyBinCount(): number {\n return this._nativeAnalyserNode.frequencyBinCount;\n }\n\n get maxDecibels(): number {\n return this._nativeAnalyserNode.maxDecibels;\n }\n\n set maxDecibels(value) {\n // Bug #118: Safari does not throw an error if maxDecibels is not more than minDecibels.\n const maxDecibels = this._nativeAnalyserNode.maxDecibels;\n\n this._nativeAnalyserNode.maxDecibels = value;\n\n if (!(value > this._nativeAnalyserNode.minDecibels)) {\n this._nativeAnalyserNode.maxDecibels = maxDecibels;\n\n throw createIndexSizeError();\n }\n }\n\n get minDecibels(): number {\n return this._nativeAnalyserNode.minDecibels;\n }\n\n set minDecibels(value) {\n // Bug #118: Safari does not throw an error if maxDecibels is not more than minDecibels.\n const minDecibels = this._nativeAnalyserNode.minDecibels;\n\n this._nativeAnalyserNode.minDecibels = value;\n\n if (!(this._nativeAnalyserNode.maxDecibels > value)) {\n this._nativeAnalyserNode.minDecibels = minDecibels;\n\n throw createIndexSizeError();\n }\n }\n\n get smoothingTimeConstant(): number {\n return this._nativeAnalyserNode.smoothingTimeConstant;\n }\n\n set smoothingTimeConstant(value) {\n this._nativeAnalyserNode.smoothingTimeConstant = value;\n }\n\n public getByteFrequencyData(array: Uint8Array): void {\n this._nativeAnalyserNode.getByteFrequencyData(array);\n }\n\n public getByteTimeDomainData(array: Uint8Array): void {\n this._nativeAnalyserNode.getByteTimeDomainData(array);\n }\n\n public getFloatFrequencyData(array: Float32Array): void {\n this._nativeAnalyserNode.getFloatFrequencyData(array);\n }\n\n public getFloatTimeDomainData(array: Float32Array): void {\n this._nativeAnalyserNode.getFloatTimeDomainData(array);\n }\n };\n};\n","import { TNativeAudioNode, TNativeContext } from '../types';\n\nexport const isOwnedByContext = (nativeAudioNode: TNativeAudioNode, nativeContext: TNativeContext): boolean => {\n return nativeAudioNode.context === nativeContext;\n};\n","import { isOwnedByContext } from '../helpers/is-owned-by-context';\nimport { IAnalyserNode, IMinimalOfflineAudioContext, IOfflineAudioContext } from '../interfaces';\nimport { TAnalyserNodeRendererFactoryFactory, TNativeAnalyserNode, TNativeOfflineAudioContext } from '../types';\n\nexport const createAnalyserNodeRendererFactory: TAnalyserNodeRendererFactoryFactory = (\n createNativeAnalyserNode,\n getNativeAudioNode,\n renderInputsOfAudioNode\n) => {\n return <T extends IMinimalOfflineAudioContext | IOfflineAudioContext>() => {\n const renderedNativeAnalyserNodes = new WeakMap<TNativeOfflineAudioContext, TNativeAnalyserNode>();\n\n const createAnalyserNode = async (proxy: IAnalyserNode<T>, nativeOfflineAudioContext: TNativeOfflineAudioContext) => {\n let nativeAnalyserNode = getNativeAudioNode<T, TNativeAnalyserNode>(proxy);\n\n // If the initially used nativeAnalyserNode was not constructed on the same OfflineAudioContext it needs to be created again.\n const nativeAnalyserNodeIsOwnedByContext = isOwnedByContext(nativeAnalyserNode, nativeOfflineAudioContext);\n\n if (!nativeAnalyserNodeIsOwnedByContext) {\n const options = {\n channelCount: nativeAnalyserNode.channelCount,\n channelCountMode: nativeAnalyserNode.channelCountMode,\n channelInterpretation: nativeAnalyserNode.channelInterpretation,\n fftSize: nativeAnalyserNode.fftSize,\n maxDecibels: nativeAnalyserNode.maxDecibels,\n minDecibels: nativeAnalyserNode.minDecibels,\n smoothingTimeConstant: nativeAnalyserNode.smoothingTimeConstant\n };\n\n nativeAnalyserNode = createNativeAnalyserNode(nativeOfflineAudioContext, options);\n }\n\n renderedNativeAnalyserNodes.set(nativeOfflineAudioContext, nativeAnalyserNode);\n\n await renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeAnalyserNode);\n\n return nativeAnalyserNode;\n };\n\n return {\n render(proxy: IAnalyserNode<T>, nativeOfflineAudioContext: TNativeOfflineAudioContext): Promise<TNativeAnalyserNode> {\n const renderedNativeAnalyserNode = renderedNativeAnalyserNodes.get(nativeOfflineAudioContext);\n\n if (renderedNativeAnalyserNode !== undefined) {\n return Promise.resolve(renderedNativeAnalyserNode);\n }\n\n return createAnalyserNode(proxy, nativeOfflineAudioContext);\n }\n };\n };\n};\n","import { TNativeAudioBuffer } from '../types';\n\nexport const testAudioBufferCopyChannelMethodsOutOfBoundsSupport = (nativeAudioBuffer: TNativeAudioBuffer): boolean => {\n try {\n nativeAudioBuffer.copyToChannel(new Float32Array(1), 0, -1);\n } catch {\n return false;\n }\n\n return true;\n};\n","import { TIndexSizeErrorFactory } from '../types';\n\nexport const createIndexSizeError: TIndexSizeErrorFactory = () => new DOMException('', 'IndexSizeError');\n","import { createIndexSizeError } from '../factories/index-size-error';\nimport { TNativeAudioBuffer } from '../types';\n\nexport const wrapAudioBufferGetChannelDataMethod = (audioBuffer: TNativeAudioBuffer): void => {\n audioBuffer.getChannelData = ((getChannelData) => {\n return (channel: number) => {\n try {\n return getChannelData.call(audioBuffer, channel);\n } catch (err) {\n if (err.code === 12) {\n throw createIndexSizeError();\n }\n\n throw err;\n }\n };\n })(audioBuffer.getChannelData);\n};\n","import { testAudioBufferCopyChannelMethodsOutOfBoundsSupport } from '../helpers/test-audio-buffer-copy-channel-methods-out-of-bounds-support';\nimport { wrapAudioBufferGetChannelDataMethod } from '../helpers/wrap-audio-buffer-get-channel-data-method';\nimport { IAudioBuffer, IAudioBufferOptions } from '../interfaces';\nimport { TAudioBufferConstructorFactory, TNativeOfflineAudioContext } from '../types';\n\nconst DEFAULT_OPTIONS = {\n numberOfChannels: 1\n} as const;\n\nexport const createAudioBufferConstructor: TAudioBufferConstructorFactory = (\n audioBufferStore,\n cacheTestResult,\n createNotSupportedError,\n nativeAudioBufferConstructor,\n nativeOfflineAudioContextConstructor,\n testNativeAudioBufferConstructorSupport,\n wrapAudioBufferCopyChannelMethods,\n wrapAudioBufferCopyChannelMethodsOutOfBounds\n) => {\n let nativeOfflineAudioContext: null | TNativeOfflineAudioContext = null;\n\n return class AudioBuffer implements IAudioBuffer {\n // This field needs to be defined to convince TypeScript that the IAudioBuffer will be implemented.\n public copyFromChannel!: (destination: Float32Array, channelNumber: number, bufferOffset?: number) => void;\n\n // This field needs to be defined to convince TypeScript that the IAudioBuffer will be implemented.\n public copyToChannel!: (source: Float32Array, channelNumber: number, bufferOffset?: number) => void;\n\n // This field needs to be defined to convince TypeScript that the IAudioBuffer will be implemented.\n public duration!: number;\n\n // This field needs to be defined to convince TypeScript that the IAudioBuffer will be implemented.\n public getChannelData!: (channel: number) => Float32Array;\n\n // This field needs to be defined to convince TypeScript that the IAudioBuffer will be implemented.\n public length!: number;\n\n // This field needs to be defined to convince TypeScript that the IAudioBuffer will be implemented.\n public numberOfChannels!: number;\n\n // This field needs to be defined to convince TypeScript that the IAudioBuffer will be implemented.\n public sampleRate!: number;\n\n constructor(options: IAudioBufferOptions) {\n if (nativeOfflineAudioContextConstructor === null) {\n throw new Error('Missing the native OfflineAudioContext constructor.');\n }\n\n const { length, numberOfChannels, sampleRate } = { ...DEFAULT_OPTIONS, ...options };\n\n if (nativeOfflineAudioContext === null) {\n nativeOfflineAudioContext = new nativeOfflineAudioContextConstructor(1, 1, 44100);\n }\n\n /*\n * Bug #99: Firefox does not throw a NotSupportedError when the numberOfChannels is zero. But it only does it when using the\n * factory function. But since Firefox also supports the constructor everything should be fine.\n */\n const audioBuffer =\n nativeAudioBufferConstructor !== null &&\n cacheTestResult(testNativeAudioBufferConstructorSupport, testNativeAudioBufferConstructorSupport)\n ? new nativeAudioBufferConstructor({ length, numberOfChannels, sampleRate })\n : nativeOfflineAudioContext.createBuffer(numberOfChannels, length, sampleRate);\n\n // Bug #99: Safari does not throw an error when the numberOfChannels is zero.\n if (audioBuffer.numberOfChannels === 0) {\n throw createNotSupportedError();\n }\n\n // Bug #5: Safari does not support copyFromChannel() and copyToChannel().\n // Bug #100: Safari does throw a wrong error when calling getChannelData() with an out-of-bounds value.\n if (typeof audioBuffer.copyFromChannel !== 'function') {\n wrapAudioBufferCopyChannelMethods(audioBuffer);\n wrapAudioBufferGetChannelDataMethod(audioBuffer);\n // Bug #157: Firefox does not allow the bufferOffset to be out-of-bounds.\n } else if (\n !cacheTestResult(testAudioBufferCopyChannelMethodsOutOfBoundsSupport, () =>\n testAudioBufferCopyChannelMethodsOutOfBoundsSupport(audioBuffer)\n )\n ) {\n wrapAudioBufferCopyChannelMethodsOutOfBounds(audioBuffer);\n }\n\n audioBufferStore.add(audioBuffer);\n\n /*\n * This does violate all good pratices but it is necessary to allow this AudioBuffer to be used with native\n * (Offline)AudioContexts.\n */\n return audioBuffer;\n }\n\n public static [Symbol.hasInstance](instance: unknown): boolean {\n return (\n (instance !== null && typeof instance === 'object' && Object.getPrototypeOf(instance) === AudioBuffer.prototype) ||\n audioBufferStore.has(<any>instance)\n );\n }\n };\n};\n","export const MOST_NEGATIVE_SINGLE_FLOAT = -3.4028234663852886e38;\n\nexport const MOST_POSITIVE_SINGLE_FLOAT = -MOST_NEGATIVE_SINGLE_FLOAT;\n","import { ACTIVE_AUDIO_NODE_STORE } from '../globals';\nimport { TIsActiveAudioNodeFunction } from '../types';\n\nexport const isActiveAudioNode: TIsActiveAudioNodeFunction = (audioNode) => ACTIVE_AUDIO_NODE_STORE.has(audioNode);\n","import { MOST_NEGATIVE_SINGLE_FLOAT, MOST_POSITIVE_SINGLE_FLOAT } from '../constants';\nimport { isActiveAudioNode } from '../helpers/is-active-audio-node';\nimport { setInternalStateToActive } from '../helpers/set-internal-state-to-active';\nimport { setInternalStateToPassive } from '../helpers/set-internal-state-to-passive';\nimport { IAudioBufferSourceNode, IAudioBufferSourceOptions, IAudioParam, IAudioScheduledSourceNodeEventMap } from '../interfaces';\nimport {\n TAnyAudioBuffer,\n TAudioBufferSourceNodeConstructorFactory,\n TAudioBufferSourceNodeRenderer,\n TContext,\n TEventHandler,\n TNativeAudioBufferSourceNode\n} from '../types';\n\nconst DEFAULT_OPTIONS = {\n buffer: null,\n channelCount: 2,\n channelCountMode: 'max',\n channelInterpretation: 'speakers',\n // Bug #149: Safari does not yet support the detune AudioParam.\n loop: false,\n loopEnd: 0,\n loopStart: 0,\n playbackRate: 1\n} as const;\n\nexport const createAudioBufferSourceNodeConstructor: TAudioBufferSourceNodeConstructorFactory = (\n audioNodeConstructor,\n createAudioBufferSourceNodeRenderer,\n createAudioParam,\n createInvalidStateError,\n createNativeAudioBufferSourceNode,\n getNativeContext,\n isNativeOfflineAudioContext,\n wrapEventListener\n) => {\n return class AudioBufferSourceNode<T extends TContext>\n extends audioNodeConstructor<T, IAudioScheduledSourceNodeEventMap>\n implements IAudioBufferSourceNode<T>\n {\n private _audioBufferSourceNodeRenderer: TAudioBufferSourceNodeRenderer<T>;\n\n private _isBufferNullified: boolean;\n\n private _isBufferSet: boolean;\n\n private _nativeAudioBufferSourceNode: TNativeAudioBufferSourceNode;\n\n private _onended: null | TEventHandler<this>;\n\n private _playbackRate: IAudioParam;\n\n constructor(context: T, options?: Partial<IAudioBufferSourceOptions>) {\n const nativeContext = getNativeContext(context);\n const mergedOptions = { ...DEFAULT_OPTIONS, ...options };\n const nativeAudioBufferSourceNode = createNativeAudioBufferSourceNode(nativeContext, mergedOptions);\n const isOffline = isNativeOfflineAudioContext(nativeContext);\n const audioBufferSourceNodeRenderer = <TAudioBufferSourceNodeRenderer<T>>(\n (isOffline ? createAudioBufferSourceNodeRenderer() : null)\n );\n\n super(context, false, nativeAudioBufferSourceNode, audioBufferSourceNodeRenderer);\n\n this._audioBufferSourceNodeRenderer = audioBufferSourceNodeRenderer;\n this._isBufferNullified = false;\n this._isBufferSet = mergedOptions.buffer !== null;\n this._nativeAudioBufferSourceNode = nativeAudioBufferSourceNode;\n this._onended = null;\n // Bug #73: Safari does not export the correct values for maxValue and minValue.\n this._playbackRate = createAudioParam(\n this,\n isOffline,\n nativeAudioBufferSourceNode.playbackRate,\n MOST_POSITIVE_SINGLE_FLOAT,\n MOST_NEGATIVE_SINGLE_FLOAT\n );\n }\n\n get buffer(): null | TAnyAudioBuffer {\n if (this._isBufferNullified) {\n return null;\n }\n\n return this._nativeAudioBufferSourceNode.buffer;\n }\n\n set buffer(value) {\n this._nativeAudioBufferSourceNode.buffer = value;\n\n // Bug #72: Only Chrome & Edge do not allow to reassign the buffer yet.\n if (value !== null) {\n if (this._isBufferSet) {\n throw createInvalidStateError();\n }\n\n this._isBufferSet = true;\n }\n }\n\n get loop(): boolean {\n return this._nativeAudioBufferSourceNode.loop;\n }\n\n set loop(value) {\n this._nativeAudioBufferSourceNode.loop = value;\n }\n\n get loopEnd(): number {\n return this._nativeAudioBufferSourceNode.loopEnd;\n }\n\n set loopEnd(value) {\n this._nativeAudioBufferSourceNode.loopEnd = value;\n }\n\n get loopStart(): number {\n return this._nativeAudioBufferSourceNode.loopStart;\n }\n\n set loopStart(value) {\n this._nativeAudioBufferSourceNode.loopStart = value;\n }\n\n get onended(): null | TEventHandler<this> {\n return this._onended;\n }\n\n set onended(value) {\n const wrappedListener = typeof value === 'function' ? wrapEventListener(this, value) : null;\n\n this._nativeAudioBufferSourceNode.onended = wrappedListener;\n\n const nativeOnEnded = this._nativeAudioBufferSourceNode.onended;\n\n this._onended = nativeOnEnded !== null && nativeOnEnded === wrappedListener ? value : nativeOnEnded;\n }\n\n get playbackRate(): IAudioParam {\n return this._playbackRate;\n }\n\n public start(when = 0, offset = 0, duration?: number): void {\n this._nativeAudioBufferSourceNode.start(when, offset, duration);\n\n if (this._audioBufferSourceNodeRenderer !== null) {\n this._audioBufferSourceNodeRenderer.start = duration === undefined ? [when, offset] : [when, offset, duration];\n }\n\n if (this.context.state !== 'closed') {\n setInternalStateToActive(this);\n\n const resetInternalStateToPassive = () => {\n this._nativeAudioBufferSourceNode.removeEventListener('ended', resetInternalStateToPassive);\n\n if (isActiveAudioNode(this)) {\n setInternalStateToPassive(this);\n }\n };\n\n this._nativeAudioBufferSourceNode.addEventListener('ended', resetInternalStateToPassive);\n }\n }\n\n public stop(when = 0): void {\n this._nativeAudioBufferSourceNode.stop(when);\n\n if (this._audioBufferSourceNodeRenderer !== null) {\n this._audioBufferSourceNodeRenderer.stop = when;\n }\n }\n };\n};\n","import { isOwnedByContext } from '../helpers/is-owned-by-context';\nimport { IAudioBufferSourceNode, IMinimalOfflineAudioContext, IOfflineAudioContext } from '../interfaces';\nimport { TAudioBufferSourceNodeRendererFactoryFactory, TNativeAudioBufferSourceNode, TNativeOfflineAudioContext } from '../types';\n\nexport const createAudioBufferSourceNodeRendererFactory: TAudioBufferSourceNodeRendererFactoryFactory = (\n connectAudioParam,\n createNativeAudioBufferSourceNode,\n getNativeAudioNode,\n renderAutomation,\n renderInputsOfAudioNode\n) => {\n return <T extends IMinimalOfflineAudioContext | IOfflineAudioContext>() => {\n const renderedNativeAudioBufferSourceNodes = new WeakMap<TNativeOfflineAudioContext, TNativeAudioBufferSourceNode>();\n\n let start: null | [number, number] | [number, number, number] = null;\n let stop: null | number = null;\n\n const createAudioBufferSourceNode = async (\n proxy: IAudioBufferSourceNode<T>,\n nativeOfflineAudioContext: TNativeOfflineAudioContext\n ) => {\n let nativeAudioBufferSourceNode = getNativeAudioNode<T, TNativeAudioBufferSourceNode>(proxy);\n\n /*\n * If the initially used nativeAudioBufferSourceNode was not constructed on the same OfflineAudioContext it needs to be created\n * again.\n */\n const nativeAudioBufferSourceNodeIsOwnedByContext = isOwnedByContext(nativeAudioBufferSourceNode, nativeOfflineAudioContext);\n\n if (!nativeAudioBufferSourceNodeIsOwnedByContext) {\n const options = {\n buffer: nativeAudioBufferSourceNode.buffer,\n channelCount: nativeAudioBufferSourceNode.channelCount,\n channelCountMode: nativeAudioBufferSourceNode.channelCountMode,\n channelInterpretation: nativeAudioBufferSourceNode.channelInterpretation,\n // Bug #149: Safari does not yet support the detune AudioParam.\n loop: nativeAudioBufferSourceNode.loop,\n loopEnd: nativeAudioBufferSourceNode.loopEnd,\n loopStart: nativeAudioBufferSourceNode.loopStart,\n playbackRate: nativeAudioBufferSourceNode.playbackRate.value\n };\n\n nativeAudioBufferSourceNode = createNativeAudioBufferSourceNode(nativeOfflineAudioContext, options);\n\n if (start !== null) {\n nativeAudioBufferSourceNode.start(...start);\n }\n\n if (stop !== null) {\n nativeAudioBufferSourceNode.stop(stop);\n }\n }\n\n renderedNativeAudioBufferSourceNodes.set(nativeOfflineAudioContext, nativeAudioBufferSourceNode);\n\n if (!nativeAudioBufferSourceNodeIsOwnedByContext) {\n // Bug #149: Safari does not yet support the detune AudioParam.\n await renderAutomation(nativeOfflineAudioContext, proxy.playbackRate, nativeAudioBufferSourceNode.playbackRate);\n } else {\n // Bug #149: Safari does not yet support the detune AudioParam.\n await connectAudioParam(nativeOfflineAudioContext, proxy.playbackRate, nativeAudioBufferSourceNode.playbackRate);\n }\n\n await renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeAudioBufferSourceNode);\n\n return nativeAudioBufferSourceNode;\n };\n\n return {\n set start(value: [number, number] | [number, number, number]) {\n start = value;\n },\n set stop(value: number) {\n stop = value;\n },\n render(\n proxy: IAudioBufferSourceNode<T>,\n nativeOfflineAudioContext: TNativeOfflineAudioContext\n ): Promise<TNativeAudioBufferSourceNode> {\n const renderedNativeAudioBufferSourceNode = renderedNativeAudioBufferSourceNodes.get(nativeOfflineAudioContext);\n\n if (renderedNativeAudioBufferSourceNode !== undefined) {\n return Promise.resolve(renderedNativeAudioBufferSourceNode);\n }\n\n return createAudioBufferSourceNode(proxy, nativeOfflineAudioContext);\n }\n };\n };\n};\n","import { IAudioBufferSourceNode, IAudioNode } from '../interfaces';\nimport { TContext } from '../types';\n\nexport const isAudioBufferSourceNode = <T extends TContext>(audioNode: IAudioNode<T>): audioNode is IAudioBufferSourceNode<T> => {\n return 'playbackRate' in audioNode;\n};\n","import { IAudioNode, IBiquadFilterNode } from '../interfaces';\nimport { TContext } from '../types';\n\nexport const isBiquadFilterNode = <T extends TContext>(audioNode: IAudioNode<T>): audioNode is IBiquadFilterNode<T> => {\n return 'frequency' in audioNode && 'gain' in audioNode;\n};\n","import { IAudioNode, IConstantSourceNode } from '../interfaces';\nimport { TContext } from '../types';\n\nexport const isConstantSourceNode = <T extends TContext>(audioNode: IAudioNode<T>): audioNode is IConstantSourceNode<T> => {\n return 'offset' in audioNode;\n};\n","import { IAudioNode, IGainNode } from '../interfaces';\nimport { TContext } from '../types';\n\nexport const isGainNode = <T extends TContext>(audioNode: IAudioNode<T>): audioNode is IGainNode<T> => {\n return !('frequency' in audioNode) && 'gain' in audioNode;\n};\n","import { IAudioNode, IOscillatorNode } from '../interfaces';\nimport { TContext } from '../types';\n\nexport const isOscillatorNode = <T extends TContext>(audioNode: IAudioNode<T>): audioNode is IOscillatorNode<T> => {\n return 'detune' in audioNode && 'frequency' in audioNode && !('gain' in audioNode);\n};\n","import { IAudioNode, IStereoPannerNode } from '../interfaces';\nimport { TContext } from '../types';\n\nexport const isStereoPannerNode = <T extends TContext>(audioNode: IAudioNode<T>): audioNode is IStereoPannerNode<T> => {\n return 'pan' in audioNode;\n};\n","import { AUDIO_NODE_CONNECTIONS_STORE } from '../globals';\nimport { IAudioNode } from '../interfaces';\nimport { TAudioNodeConnections, TContext, TGetAudioNodeConnectionsFunction } from '../types';\nimport { getValueForKey } from './get-value-for-key';\n\nexport const getAudioNodeConnections: TGetAudioNodeConnectionsFunction = <T extends TContext>(\n audioNode: IAudioNode<T>\n): TAudioNodeConnections<T> => {\n return <TAudioNodeConnections<T>>getValueForKey(AUDIO_NODE_CONNECTIONS_STORE, audioNode);\n};\n","import { AUDIO_PARAM_CONNECTIONS_STORE } from '../globals';\nimport { IAudioParam } from '../interfaces';\nimport { TAudioParamConnections, TContext, TGetAudioParamConnectionsFunction } from '../types';\nimport { getValueForKey } from './get-value-for-key';\n\nexport const getAudioParamConnections: TGetAudioParamConnectionsFunction = <T extends TContext>(\n audioParam: IAudioParam\n): TAudioParamConnections<T> => {\n return <TAudioParamConnections<T>>getValueForKey(AUDIO_PARAM_CONNECTIONS_STORE, audioParam);\n};\n","import { isAudioBufferSourceNode } from '../guards/audio-buffer-source-node';\nimport { isAudioWorkletNode } from '../guards/audio-worklet-node';\nimport { isBiquadFilterNode } from '../guards/biquad-filter-node';\nimport { isConstantSourceNode } from '../guards/constant-source-node';\nimport { isGainNode } from '../guards/gain-node';\nimport { isOscillatorNode } from '../guards/oscillator-node';\nimport { isStereoPannerNode } from '../guards/stereo-panner-node';\nimport { IAudioNode } from '../interfaces';\nimport { TContext } from '../types';\nimport { getAudioNodeConnections } from './get-audio-node-connections';\nimport { getAudioParamConnections } from './get-audio-param-connections';\nimport { isActiveAudioNode } from './is-active-audio-node';\nimport { setInternalStateToPassive } from './set-internal-state-to-passive';\n\nexport const deactivateActiveAudioNodeInputConnections = <T extends TContext>(\n audioNode: IAudioNode<T>,\n trace: readonly IAudioNode<T>[]\n) => {\n const { activeInputs } = getAudioNodeConnections(audioNode);\n\n activeInputs.forEach((connections) =>\n connections.forEach(([source]) => {\n if (!trace.includes(audioNode)) {\n deactivateActiveAudioNodeInputConnections(source, [...trace, audioNode]);\n }\n })\n );\n\n const audioParams = isAudioBufferSourceNode(audioNode)\n ? [\n // Bug #149: Safari does not yet support the detune AudioParam.\n audioNode.playbackRate\n ]\n : isAudioWorkletNode(audioNode)\n ? Array.from(audioNode.parameters.values())\n : isBiquadFilterNode(audioNode)\n ? [audioNode.Q, audioNode.detune, audioNode.frequency, audioNode.gain]\n : isConstantSourceNode(audioNode)\n ? [audioNode.offset]\n : isGainNode(audioNode)\n ? [audioNode.gain]\n : isOscillatorNode(audioNode)\n ? [audioNode.detune, audioNode.frequency]\n : isStereoPannerNode(audioNode)\n ? [audioNode.pan]\n : [];\n\n for (const audioParam of audioParams) {\n const audioParamConnections = getAudioParamConnections<T>(audioParam);\n\n if (audioParamConnections !== undefined) {\n audioParamConnections.activeInputs.forEach(([source]) => deactivateActiveAudioNodeInputConnections(source, trace));\n }\n }\n\n if (isActiveAudioNode(audioNode)) {\n setInternalStateToPassive(audioNode);\n }\n};\n","import { IAudioDestinationNode } from '../interfaces';\nimport { TContext } from '../types';\nimport { deactivateActiveAudioNodeInputConnections } from './deactivate-active-audio-node-input-connections';\n\nexport const deactivateAudioGraph = <T extends TContext>(context: T): void => {\n deactivateActiveAudioNodeInputConnections(<IAudioDestinationNode<T>>context.destination, []);\n};\n","import { IAudioContextOptions } from '../interfaces';\n\nexport const isValidLatencyHint = (latencyHint: IAudioContextOptions['latencyHint']) => {\n return (\n latencyHint === undefined ||\n typeof latencyHint === 'number' ||\n (typeof latencyHint === 'string' && (latencyHint === 'balanced' || latencyHint === 'interactive' || latencyHint === 'playback'))\n );\n};\n","import { deactivateAudioGraph } from '../helpers/deactivate-audio-graph';\nimport { isValidLatencyHint } from '../helpers/is-valid-latency-hint';\nimport {\n IAudioContext,\n IAudioContextOptions,\n IMediaElementAudioSourceNode,\n IMediaStreamAudioDestinationNode,\n IMediaStreamAudioSourceNode,\n IMediaStreamTrackAudioSourceNode\n} from '../interfaces';\nimport { TAudioContextConstructorFactory, TAudioContextState, TNativeAudioContext, TNativeGainNode, TNativeOscillatorNode } from '../types';\n\nexport const createAudioContextConstructor: TAudioContextConstructorFactory = (\n baseAudioContextConstructor,\n createInvalidStateError,\n createNotSupportedError,\n createUnknownError,\n mediaElementAudioSourceNodeConstructor,\n mediaStreamAudioDestinationNodeConstructor,\n mediaStreamAudioSourceNodeConstructor,\n mediaStreamTrackAudioSourceNodeConstructor,\n nativeAudioContextConstructor\n) => {\n return class AudioContext extends baseAudioContextConstructor<IAudioContext> implements IAudioContext {\n private _baseLatency: number;\n\n private _nativeAudioContext: TNativeAudioContext;\n\n private _nativeGainNode: null | TNativeGainNode;\n\n private _nativeOscillatorNode: null | TNativeOscillatorNode;\n\n private _state: null | 'suspended';\n\n constructor(options: IAudioContextOptions = {}) {\n if (nativeAudioContextConstructor === null) {\n throw new Error('Missing the native AudioContext constructor.');\n }\n\n let nativeAudioContext: TNativeAudioContext;\n\n try {\n nativeAudioContext = new nativeAudioContextConstructor(options);\n } catch (err) {\n // Bug #192 Safari does throw a SyntaxError if the sampleRate is not supported.\n if (err.code === 12 && err.message === 'sampleRate is not in range') {\n throw createNotSupportedError();\n }\n\n throw err;\n }\n\n // Bug #131 Safari returns null when there are four other AudioContexts running already.\n if (nativeAudioContext === null) {\n throw createUnknownError();\n }\n\n // Bug #51 Only Chrome and Edge throw an error if the given latencyHint is invalid.\n if (!isValidLatencyHint(options.latencyHint)) {\n throw new TypeError(\n `The provided value '${options.latencyHint}' is not a valid enum value of type AudioContextLatencyCategory.`\n );\n }\n\n // Bug #150 Safari does not support setting the sampleRate.\n if (options.sampleRate !== undefined && nativeAudioContext.sampleRate !== options.sampleRate) {\n throw createNotSupportedError();\n }\n\n super(nativeAudioContext, 2);\n\n const { latencyHint } = options;\n const { sampleRate } = nativeAudioContext;\n\n // @todo The values for 'balanced', 'interactive' and 'playback' are just copied from Chrome's implementation.\n this._baseLatency =\n typeof nativeAudioContext.baseLatency === 'number'\n ? nativeAudioContext.baseLatency\n : latencyHint === 'balanced'\n ? 512 / sampleRate\n : latencyHint === 'interactive' || latencyHint === undefined\n ? 256 / sampleRate\n : latencyHint === 'playback'\n ? 1024 / sampleRate\n : /*\n * @todo The min (256) and max (16384) values are taken from the allowed bufferSize values of a\n * ScriptProcessorNode.\n */\n (Math.max(2, Math.min(128, Math.round((latencyHint * sampleRate) / 128))) * 128) / sampleRate;\n this._nativeAudioContext = nativeAudioContext;\n\n // Bug #188: Safari will set the context's state to 'interrupted' in case the user switches tabs.\n if (nativeAudioContextConstructor.name === 'webkitAudioContext') {\n this._nativeGainNode = nativeAudioContext.createGain();\n this._nativeOscillatorNode = nativeAudioContext.createOscillator();\n\n this._nativeGainNode.gain.value = 1e-37;\n\n this._nativeOscillatorNode.connect(this._nativeGainNode).connect(nativeAudioContext.destination);\n this._nativeOscillatorNode.start();\n } else {\n this._nativeGainNode = null;\n this._nativeOscillatorNode = null;\n }\n\n this._state = null;\n\n /*\n * Bug #34: Chrome and Edge pretend to be running right away, but fire an onstatechange event when the state actually changes\n * to 'running'.\n */\n if (nativeAudioContext.state === 'running') {\n this._state = 'suspended';\n\n const revokeState = () => {\n if (this._state === 'suspended') {\n this._state = null;\n }\n\n nativeAudioContext.removeEventListener('statechange', revokeState);\n };\n\n nativeAudioContext.addEventListener('statechange', revokeState);\n }\n }\n\n get baseLatency(): number {\n return this._baseLatency;\n }\n\n get state(): TAudioContextState {\n return this._state !== null ? this._state : this._nativeAudioContext.state;\n }\n\n public close(): Promise<void> {\n // Bug #35: Firefox does not throw an error if the AudioContext was closed before.\n if (this.state === 'closed') {\n return this._nativeAudioContext.close().then(() => {\n throw createInvalidStateError();\n });\n }\n\n // Bug #34: If the state was set to suspended before it should be revoked now.\n if (this._state === 'suspended') {\n this._state = null;\n }\n\n return this._nativeAudioContext.close().then(() => {\n if (this._nativeGainNode !== null && this._nativeOscillatorNode !== null) {\n this._nativeOscillatorNode.stop();\n\n this._nativeGainNode.disconnect();\n this._nativeOscillatorNode.disconnect();\n }\n\n deactivateAudioGraph(this);\n });\n }\n\n public createMediaElementSource(mediaElement: HTMLMediaElement): IMediaElementAudioSourceNode<this> {\n return new mediaElementAudioSourceNodeConstructor(this, { mediaElement });\n }\n\n public createMediaStreamDestination(): IMediaStreamAudioDestinationNode<this> {\n return new mediaStreamAudioDestinationNodeConstructor(this);\n }\n\n public createMediaStreamSource(mediaStream: MediaStream): IMediaStreamAudioSourceNode<this> {\n return new mediaStreamAudioSourceNodeConstructor(this, { mediaStream });\n }\n\n public createMediaStreamTrackSource(mediaStreamTrack: MediaStreamTrack): IMediaStreamTrackAudioSourceNode<this> {\n return new mediaStreamTrackAudioSourceNodeConstructor(this, { mediaStreamTrack });\n }\n\n public resume(): Promise<void> {\n if (this._state === 'suspended') {\n return new Promise((resolve, reject) => {\n const resolvePromise = () => {\n this._nativeAudioContext.removeEventListener('statechange', resolvePromise);\n\n if (this._nativeAudioContext.state === 'running') {\n resolve();\n } else {\n this.resume().then(resolve, reject);\n }\n };\n\n this._nativeAudioContext.addEventListener('statechange', resolvePromise);\n });\n }\n\n return this._nativeAudioContext.resume().catch((err) => {\n // Bug #55: Chrome and Edge do throw an InvalidAccessError instead of an InvalidStateError.\n // Bug #56: Safari invokes the catch handler but without an error.\n if (err === undefined || err.code === 15) {\n throw createInvalidStateError();\n }\n\n throw err;\n });\n }\n\n public suspend(): Promise<void> {\n return this._nativeAudioContext.suspend().catch((err) => {\n // Bug #56: Safari invokes the catch handler but without an error.\n if (err === undefined) {\n throw createInvalidStateError();\n }\n\n throw err;\n });\n }\n };\n};\n","import { IAudioDestinationNode } from '../interfaces';\nimport {\n TAudioDestinationNodeConstructorFactory,\n TAudioNodeRenderer,\n TChannelCountMode,\n TContext,\n TNativeAudioDestinationNode\n} from '../types';\n\nexport const createAudioDestinationNodeConstructor: TAudioDestinationNodeConstructorFactory = (\n audioNodeConstructor,\n createAudioDestinationNodeRenderer,\n createIndexSizeError,\n createInvalidStateError,\n createNativeAudioDestinationNode,\n getNativeContext,\n isNativeOfflineAudioContext,\n renderInputsOfAudioNode\n) => {\n return class AudioDestinationNode<T extends TContext> extends audioNodeConstructor<T> implements IAudioDestinationNode<T> {\n private _isNodeOfNativeOfflineAudioContext: boolean;\n\n private _nativeAudioDestinationNode: TNativeAudioDestinationNode;\n\n constructor(context: T, channelCount: number) {\n const nativeContext = getNativeContext(context);\n const isOffline = isNativeOfflineAudioContext(nativeContext);\n const nativeAudioDestinationNode = createNativeAudioDestinationNode(nativeContext, channelCount, isOffline);\n const audioDestinationNodeRenderer = <TAudioNodeRenderer<T, this>>(\n (isOffline ? createAudioDestinationNodeRenderer(renderInputsOfAudioNode) : null)\n );\n\n super(context, false, nativeAudioDestinationNode, audioDestinationNodeRenderer);\n\n this._isNodeOfNativeOfflineAudioContext = isOffline;\n this._nativeAudioDestinationNode = nativeAudioDestinationNode;\n }\n\n get channelCount(): number {\n return this._nativeAudioDestinationNode.channelCount;\n }\n\n set channelCount(value) {\n // Bug #52: Chrome, Edge & Safari do not throw an exception at all.\n // Bug #54: Firefox does throw an IndexSizeError.\n if (this._isNodeOfNativeOfflineAudioContext) {\n throw createInvalidStateError();\n }\n\n // Bug #47: The AudioDestinationNode in Safari does not initialize the maxChannelCount property correctly.\n if (value > this._nativeAudioDestinationNode.maxChannelCount) {\n throw createIndexSizeError();\n }\n\n this._nativeAudioDestinationNode.channelCount = value;\n }\n\n get channelCountMode(): TChannelCountMode {\n return this._nativeAudioDestinationNode.channelCountMode;\n }\n\n set channelCountMode(value) {\n // Bug #53: No browser does throw an exception yet.\n if (this._isNodeOfNativeOfflineAudioContext) {\n throw createInvalidStateError();\n }\n\n this._nativeAudioDestinationNode.channelCountMode = value;\n }\n\n get maxChannelCount(): number {\n return this._nativeAudioDestinationNode.maxChannelCount;\n }\n };\n};\n","import { IAudioDestinationNode, IMinimalOfflineAudioContext, IOfflineAudioContext } from '../interfaces';\nimport {\n TAudioDestinationNodeRendererFactory,\n TNativeAudioDestinationNode,\n TNativeOfflineAudioContext,\n TRenderInputsOfAudioNodeFunction\n} from '../types';\n\nexport const createAudioDestinationNodeRenderer: TAudioDestinationNodeRendererFactory = <\n T extends IMinimalOfflineAudioContext | IOfflineAudioContext\n>(\n renderInputsOfAudioNode: TRenderInputsOfAudioNodeFunction\n) => {\n const renderedNativeAudioDestinationNodes = new WeakMap<TNativeOfflineAudioContext, TNativeAudioDestinationNode>();\n\n const createAudioDestinationNode = async (proxy: IAudioDestinationNode<T>, nativeOfflineAudioContext: TNativeOfflineAudioContext) => {\n const nativeAudioDestinationNode = nativeOfflineAudioContext.destination;\n\n renderedNativeAudioDestinationNodes.set(nativeOfflineAudioContext, nativeAudioDestinationNode);\n\n await renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeAudioDestinationNode);\n\n return nativeAudioDestinationNode;\n };\n\n return {\n render(\n proxy: IAudioDestinationNode<T>,\n nativeOfflineAudioContext: TNativeOfflineAudioContext\n ): Promise<TNativeAudioDestinationNode> {\n const renderedNativeAudioDestinationNode = renderedNativeAudioDestinationNodes.get(nativeOfflineAudioContext);\n\n if (renderedNativeAudioDestinationNode !== undefined) {\n return Promise.resolve(renderedNativeAudioDestinationNode);\n }\n\n return createAudioDestinationNode(proxy, nativeOfflineAudioContext);\n }\n };\n};\n","import { MOST_NEGATIVE_SINGLE_FLOAT, MOST_POSITIVE_SINGLE_FLOAT } from '../constants';\nimport { IAudioParam } from '../interfaces';\nimport { TAudioListenerFactoryFactory } from '../types';\n\nexport const createAudioListenerFactory: TAudioListenerFactoryFactory = (\n createAudioParam,\n createNativeChannelMergerNode,\n createNativeConstantSourceNode,\n createNativeScriptProcessorNode,\n createNotSupportedError,\n getFirstSample,\n isNativeOfflineAudioContext,\n overwriteAccessors\n) => {\n return (context, nativeContext) => {\n const nativeListener = nativeContext.listener;\n\n // Bug #117: Only Chrome & Edge support the new interface already.\n const createFakeAudioParams = () => {\n const buffer = new Float32Array(1);\n const channelMergerNode = createNativeChannelMergerNode(nativeContext, {\n channelCount: 1,\n channelCountMode: 'explicit',\n channelInterpretation: 'speakers',\n numberOfInputs: 9\n });\n const isOffline = isNativeOfflineAudioContext(nativeContext);\n\n let isScriptProcessorNodeCreated = false;\n let lastOrientation: [number, number, number, number, number, number] = [0, 0, -1, 0, 1, 0];\n let lastPosition: [number, number, number] = [0, 0, 0];\n\n const createScriptProcessorNode = () => {\n if (isScriptProcessorNodeCreated) {\n return;\n }\n\n isScriptProcessorNodeCreated = true;\n\n const scriptProcessorNode = createNativeScriptProcessorNode(nativeContext, 256, 9, 0);\n\n // tslint:disable-next-line:deprecation\n scriptProcessorNode.onaudioprocess = ({ inputBuffer }) => {\n const orientation: [number, number, number, number, number, number] = [\n getFirstSample(inputBuffer, buffer, 0),\n getFirstSample(inputBuffer, buffer, 1),\n getFirstSample(inputBuffer, buffer, 2),\n getFirstSample(inputBuffer, buffer, 3),\n getFirstSample(inputBuffer, buffer, 4),\n getFirstSample(inputBuffer, buffer, 5)\n ];\n\n if (orientation.some((value, index) => value !== lastOrientation[index])) {\n nativeListener.setOrientation(...orientation); // tslint:disable-line:deprecation\n\n lastOrientation = orientation;\n }\n\n const positon: [number, number, number] = [\n getFirstSample(inputBuffer, buffer, 6),\n getFirstSample(inputBuffer, buffer, 7),\n getFirstSample(inputBuffer, buffer, 8)\n ];\n\n if (positon.some((value, index) => value !== lastPosition[index])) {\n nativeListener.setPosition(...positon); // tslint:disable-line:deprecation\n\n lastPosition = positon;\n }\n };\n\n channelMergerNode.connect(scriptProcessorNode);\n };\n const createSetOrientation = (index: number) => (value: number) => {\n if (value !== lastOrientation[index]) {\n lastOrientation[index] = value;\n\n nativeListener.setOrientation(...lastOrientation); // tslint:disable-line:deprecation\n }\n };\n const createSetPosition = (index: number) => (value: number) => {\n if (value !== lastPosition[index]) {\n lastPosition[index] = value;\n\n nativeListener.setPosition(...lastPosition); // tslint:disable-line:deprecation\n }\n };\n const createFakeAudioParam = (input: number, initialValue: number, setValue: (value: number) => void) => {\n const constantSourceNode = createNativeConstantSourceNode(nativeContext, {\n channelCount: 1,\n channelCountMode: 'explicit',\n channelInterpretation: 'discrete',\n offset: initialValue\n });\n\n constantSourceNode.connect(channelMergerNode, 0, input);\n\n // @todo This should be stopped when the context is closed.\n constantSourceNode.start();\n\n Object.defineProperty(constantSourceNode.offset, 'defaultValue', {\n get(): number {\n return initialValue;\n }\n });\n\n /*\n * Bug #62 & #74: Safari does not support ConstantSourceNodes and does not export the correct values for maxValue and\n * minValue for GainNodes.\n */\n const audioParam = createAudioParam(\n <any>{ context },\n isOffline,\n constantSourceNode.offset,\n MOST_POSITIVE_SINGLE_FLOAT,\n MOST_NEGATIVE_SINGLE_FLOAT\n );\n\n overwriteAccessors(\n audioParam,\n 'value',\n (get) => () => get.call(audioParam),\n (set) => (value) => {\n try {\n set.call(audioParam, value);\n } catch (err) {\n if (err.code !== 9) {\n throw err;\n }\n }\n\n createScriptProcessorNode();\n\n if (isOffline) {\n // Bug #117: Using setOrientation() and setPosition() doesn't work with an OfflineAudioContext.\n setValue(value);\n }\n }\n );\n\n audioParam.cancelAndHoldAtTime = ((cancelAndHoldAtTime) => {\n if (isOffline) {\n return () => {\n throw createNotSupportedError();\n };\n }\n\n return (...args: Parameters<IAudioParam['cancelAndHoldAtTime']>) => {\n const value = cancelAndHoldAtTime.apply(audioParam, args);\n\n createScriptProcessorNode();\n\n return value;\n };\n })(audioParam.cancelAndHoldAtTime);\n audioParam.cancelScheduledValues = ((cancelScheduledValues) => {\n if (isOffline) {\n return () => {\n throw createNotSupportedError();\n };\n }\n\n return (...args: Parameters<IAudioParam['cancelScheduledValues']>) => {\n const value = cancelScheduledValues.apply(audioParam, args);\n\n createScriptProcessorNode();\n\n return value;\n };\n })(audioParam.cancelScheduledValues);\n audioParam.exponentialRampToValueAtTime = ((exponentialRampToValueAtTime) => {\n if (isOffline) {\n return () => {\n throw createNotSupportedError();\n };\n }\n\n return (...args: Parameters<IAudioParam['exponentialRampToValueAtTime']>) => {\n const value = exponentialRampToValueAtTime.apply(audioParam, args);\n\n createScriptProcessorNode();\n\n return value;\n };\n })(audioParam.exponentialRampToValueAtTime);\n audioParam.linearRampToValueAtTime = ((linearRampToValueAtTime) => {\n if (isOffline) {\n return () => {\n throw createNotSupportedError();\n };\n }\n\n return (...args: Parameters<IAudioParam['linearRampToValueAtTime']>) => {\n const value = linearRampToValueAtTime.apply(audioParam, args);\n\n createScriptProcessorNode();\n\n return value;\n };\n })(audioParam.linearRampToValueAtTime);\n audioParam.setTargetAtTime = ((setTargetAtTime) => {\n if (isOffline) {\n return () => {\n throw createNotSupportedError();\n };\n }\n\n return (...args: Parameters<IAudioParam['setTargetAtTime']>) => {\n const value = setTargetAtTime.apply(audioParam, args);\n\n createScriptProcessorNode();\n\n return value;\n };\n })(audioParam.setTargetAtTime);\n audioParam.setValueAtTime = ((setValueAtTime) => {\n if (isOffline) {\n return () => {\n throw createNotSupportedError();\n };\n }\n\n return (...args: Parameters<IAudioParam['setValueAtTime']>) => {\n const value = setValueAtTime.apply(audioParam, args);\n\n createScriptProcessorNode();\n\n return value;\n };\n })(audioParam.setValueAtTime);\n audioParam.setValueCurveAtTime = ((setValueCurveAtTime) => {\n if (isOffline) {\n return () => {\n throw createNotSupportedError();\n };\n }\n\n return (...args: Parameters<IAudioParam['setValueCurveAtTime']>) => {\n const value = setValueCurveAtTime.apply(audioParam, args);\n\n createScriptProcessorNode();\n\n return value;\n };\n })(audioParam.setValueCurveAtTime);\n\n return audioParam;\n };\n\n return {\n forwardX: createFakeAudioParam(0, 0, createSetOrientation(0)),\n forwardY: createFakeAudioParam(1, 0, createSetOrientation(1)),\n forwardZ: createFakeAudioParam(2, -1, createSetOrientation(2)),\n positionX: createFakeAudioParam(6, 0, createSetPosition(0)),\n positionY: createFakeAudioParam(7, 0, createSetPosition(1)),\n positionZ: createFakeAudioParam(8, 0, createSetPosition(2)),\n upX: createFakeAudioParam(3, 0, createSetOrientation(3)),\n upY: createFakeAudioParam(4, 1, createSetOrientation(4)),\n upZ: createFakeAudioParam(5, 0, createSetOrientation(5))\n };\n };\n\n const { forwardX, forwardY, forwardZ, positionX, positionY, positionZ, upX, upY, upZ } =\n nativeListener.forwardX === undefined ? createFakeAudioParams() : nativeListener;\n\n return {\n get forwardX(): IAudioParam {\n return forwardX;\n },\n get forwardY(): IAudioParam {\n return forwardY;\n },\n get forwardZ(): IAudioParam {\n return forwardZ;\n },\n get positionX(): IAudioParam {\n return positionX;\n },\n get positionY(): IAudioParam {\n return positionY;\n },\n get positionZ(): IAudioParam {\n return positionZ;\n },\n get upX(): IAudioParam {\n return upX;\n },\n get upY(): IAudioParam {\n return upY;\n },\n get upZ(): IAudioParam {\n return upZ;\n }\n };\n };\n};\n","import { IAudioNode, IAudioParam } from '../interfaces';\nimport { TContext } from '../types';\n\nexport const isAudioNode = <T extends TContext>(\n audioNodeOrAudioParam: IAudioNode<T> | IAudioParam\n): audioNodeOrAudioParam is IAudioNode<T> => {\n return 'context' in audioNodeOrAudioParam;\n};\n","import { TAudioNodeOutputConnection, TContext, TOutputConnection } from '../types';\nimport { isAudioNode } from './audio-node';\n\nexport const isAudioNodeOutputConnection = <T extends TContext>(\n outputConnection: TOutputConnection<T>\n): outputConnection is TAudioNodeOutputConnection<T> => {\n return isAudioNode(outputConnection[0]);\n};\n","import { TInsertElementInSetFunction } from '../types';\n\nexport const insertElementInSet: TInsertElementInSetFunction = (set, element, predicate, ignoreDuplicates) => {\n for (const lmnt of set) {\n if (predicate(lmnt)) {\n if (ignoreDuplicates) {\n return false;\n }\n\n throw Error('The set contains at least one similar element.');\n }\n }\n\n set.add(element);\n\n return true;\n};\n","import { IAudioNode } from '../interfaces';\nimport { TActiveInputConnection, TContext, TPassiveAudioParamInputConnection } from '../types';\nimport { insertElementInSet } from './insert-element-in-set';\n\nexport const addActiveInputConnectionToAudioParam = <T extends TContext>(\n activeInputs: Set<TActiveInputConnection<T>>,\n source: IAudioNode<T>,\n [output, eventListener]: TPassiveAudioParamInputConnection,\n ignoreDuplicates: boolean\n) => {\n insertElementInSet(\n activeInputs,\n [source, output, eventListener],\n (activeInputConnection) => activeInputConnection[0] === source && activeInputConnection[1] === output,\n ignoreDuplicates\n );\n};\n","import { IAudioNode } from '../interfaces';\nimport { TActiveInputConnection, TContext, TPassiveAudioParamInputConnection } from '../types';\nimport { insertElementInSet } from './insert-element-in-set';\n\nexport const addPassiveInputConnectionToAudioParam = <T extends TContext>(\n passiveInputs: WeakMap<IAudioNode<T>, Set<TPassiveAudioParamInputConnection>>,\n [source, output, eventListener]: TActiveInputConnection<T>,\n ignoreDuplicates: boolean\n) => {\n const passiveInputConnections = passiveInputs.get(source);\n\n if (passiveInputConnections === undefined) {\n passiveInputs.set(source, new Set([[output, eventListener]]));\n } else {\n insertElementInSet(\n passiveInputConnections,\n [output, eventListener],\n (passiveInputConnection) => passiveInputConnection[0] === output,\n ignoreDuplicates\n );\n }\n};\n","import { INativeAudioNodeFaker } from '../interfaces';\nimport { TNativeAudioNode } from '../types';\n\nexport const isNativeAudioNodeFaker = (\n nativeAudioNodeOrNativeAudioNodeFaker: TNativeAudioNode | INativeAudioNodeFaker\n): nativeAudioNodeOrNativeAudioNodeFaker is INativeAudioNodeFaker => {\n return 'inputs' in nativeAudioNodeOrNativeAudioNodeFaker;\n};\n","import { isNativeAudioNodeFaker } from '../guards/native-audio-node-faker';\nimport { INativeAudioNodeFaker } from '../interfaces';\nimport { TConnectNativeAudioNodeToNativeAudioNodeFunction, TNativeAudioNode } from '../types';\n\nexport const connectNativeAudioNodeToNativeAudioNode: TConnectNativeAudioNodeToNativeAudioNodeFunction = (\n nativeSourceAudioNode: INativeAudioNodeFaker | TNativeAudioNode,\n nativeDestinationAudioNode: INativeAudioNodeFaker | TNativeAudioNode,\n output: number,\n input: number\n): [TNativeAudioNode, number, number] => {\n if (isNativeAudioNodeFaker(nativeDestinationAudioNode)) {\n const fakeNativeDestinationAudioNode = nativeDestinationAudioNode.inputs[input];\n\n nativeSourceAudioNode.connect(fakeNativeDestinationAudioNode, output, 0);\n\n return [fakeNativeDestinationAudioNode, output, 0];\n }\n\n nativeSourceAudioNode.connect(nativeDestinationAudioNode, output, input);\n\n return [nativeDestinationAudioNode, output, input];\n};\n","import { IAudioNode } from '../interfaces';\nimport { TActiveInputConnection, TContext } from '../types';\n\nexport const deleteActiveInputConnection = <T extends TContext>(\n activeInputConnections: Set<TActiveInputConnection<T>>,\n source: IAudioNode<T>,\n output: number\n): null | TActiveInputConnection<T> => {\n for (const activeInputConnection of activeInputConnections) {\n if (activeInputConnection[0] === source && activeInputConnection[1] === output) {\n activeInputConnections.delete(activeInputConnection);\n\n return activeInputConnection;\n }\n }\n\n return null;\n};\n","import { IAudioNode } from '../interfaces';\nimport { TActiveInputConnection, TContext } from '../types';\nimport { pickElementFromSet } from './pick-element-from-set';\n\nexport const deleteActiveInputConnectionToAudioParam = <T extends TContext>(\n activeInputs: Set<TActiveInputConnection<T>>,\n source: IAudioNode<T>,\n output: number\n) => {\n return pickElementFromSet(\n activeInputs,\n (activeInputConnection) => activeInputConnection[0] === source && activeInputConnection[1] === output\n );\n};\n","import { IAudioNode } from '../interfaces';\nimport { TContext, TInternalStateEventListener } from '../types';\nimport { getEventListenersOfAudioNode } from './get-event-listeners-of-audio-node';\n\nexport const deleteEventListenerOfAudioNode = <T extends TContext>(\n audioNode: IAudioNode<T>,\n eventListener: TInternalStateEventListener\n) => {\n const eventListeners = getEventListenersOfAudioNode(audioNode);\n\n if (!eventListeners.delete(eventListener)) {\n throw new Error('Missing the expected event listener.');\n }\n};\n","import { IAudioNode } from '../interfaces';\nimport { TContext, TPassiveAudioParamInputConnection } from '../types';\nimport { getValueForKey } from './get-value-for-key';\nimport { pickElementFromSet } from './pick-element-from-set';\n\nexport const deletePassiveInputConnectionToAudioParam = <T extends TContext>(\n passiveInputs: WeakMap<IAudioNode<T>, Set<TPassiveAudioParamInputConnection>>,\n source: IAudioNode<T>,\n output: number\n) => {\n const passiveInputConnections = getValueForKey(passiveInputs, source);\n const matchingConnection = pickElementFromSet(\n passiveInputConnections,\n (passiveInputConnection) => passiveInputConnection[0] === output\n );\n\n if (passiveInputConnections.size === 0) {\n passiveInputs.delete(source);\n }\n\n return matchingConnection;\n};\n","import { isNativeAudioNodeFaker } from '../guards/native-audio-node-faker';\nimport { TDisconnectNativeAudioNodeFromNativeAudioNodeFunction } from '../types';\n\nexport const disconnectNativeAudioNodeFromNativeAudioNode: TDisconnectNativeAudioNodeFromNativeAudioNodeFunction = (\n nativeSourceAudioNode,\n nativeDestinationAudioNode,\n output,\n input\n) => {\n if (isNativeAudioNodeFaker(nativeDestinationAudioNode)) {\n nativeSourceAudioNode.disconnect(nativeDestinationAudioNode.inputs[input], output, 0);\n } else {\n nativeSourceAudioNode.disconnect(nativeDestinationAudioNode, output, input);\n }\n};\n","import { AUDIO_NODE_STORE } from '../globals';\nimport { IAudioNode, INativeAudioNodeFaker } from '../interfaces';\nimport { TContext, TGetNativeAudioNodeFunction, TNativeAudioNode } from '../types';\nimport { getValueForKey } from './get-value-for-key';\n\nexport const getNativeAudioNode: TGetNativeAudioNodeFunction = <T extends TContext, U extends TNativeAudioNode | INativeAudioNodeFaker>(\n audioNode: IAudioNode<T>\n): U => {\n return <U>getValueForKey(AUDIO_NODE_STORE, audioNode);\n};\n","import { AUDIO_PARAM_STORE } from '../globals';\nimport { IAudioParam } from '../interfaces';\nimport { TNativeAudioParam } from '../types';\nimport { getValueForKey } from './get-value-for-key';\n\nexport const getNativeAudioParam = (audioParam: IAudioParam): TNativeAudioParam => {\n return getValueForKey(AUDIO_PARAM_STORE, audioParam);\n};\n","import { CYCLE_COUNTERS } from '../globals';\nimport { TIsPartOfACycleFunction } from '../types';\n\nexport const isPartOfACycle: TIsPartOfACycleFunction = (audioNode) => {\n return CYCLE_COUNTERS.has(audioNode);\n};\n","import { ACTIVE_AUDIO_NODE_STORE } from '../globals';\nimport { TIsPassiveAudioNodeFunction } from '../types';\n\nexport const isPassiveAudioNode: TIsPassiveAudioNodeFunction = (audioNode) => {\n return !ACTIVE_AUDIO_NODE_STORE.has(audioNode);\n};\n","import { TNativeAudioContext, TNativeAudioWorkletNodeConstructor } from '../types';\n\nexport const testAudioNodeDisconnectMethodSupport = (\n nativeAudioContext: TNativeAudioContext,\n nativeAudioWorkletNodeConstructor: null | TNativeAudioWorkletNodeConstructor\n): Promise<boolean> => {\n return new Promise((resolve) => {\n /*\n * This bug existed in Safari up until v14.0.2. Since AudioWorklets were not supported in Safari until v14.1 the presence of the\n * constructor for an AudioWorkletNode can be used here to skip the test.\n */\n if (nativeAudioWorkletNodeConstructor !== null) {\n resolve(true);\n } else {\n const analyzer = nativeAudioContext.createScriptProcessor(256, 1, 1); // tslint:disable-line deprecation\n const dummy = nativeAudioContext.createGain();\n // Bug #95: Safari does not play one sample buffers.\n const ones = nativeAudioContext.createBuffer(1, 2, 44100);\n const channelData = ones.getChannelData(0);\n\n channelData[0] = 1;\n channelData[1] = 1;\n\n const source = nativeAudioContext.createBufferSource();\n\n source.buffer = ones;\n source.loop = true;\n\n source.connect(analyzer).connect(nativeAudioContext.destination);\n source.connect(dummy);\n source.disconnect(dummy);\n\n // tslint:disable-next-line:deprecation\n analyzer.onaudioprocess = (event) => {\n const chnnlDt = event.inputBuffer.getChannelData(0); // tslint:disable-line deprecation\n\n if (Array.prototype.some.call(chnnlDt, (sample: number) => sample === 1)) {\n resolve(true);\n } else {\n resolve(false);\n }\n\n source.stop();\n\n analyzer.onaudioprocess = null; // tslint:disable-line:deprecation\n\n source.disconnect(analyzer);\n analyzer.disconnect(nativeAudioContext.destination);\n };\n\n source.start();\n }\n });\n};\n","import { IAudioNode } from '../interfaces';\nimport { TContext } from '../types';\n\nexport const visitEachAudioNodeOnce = <T extends TContext>(\n cycles: IAudioNode<T>[][],\n visitor: (audioNode: IAudioNode<T>, count: number) => void\n): void => {\n const counts = new Map<IAudioNode<T>, number>();\n\n for (const cycle of cycles) {\n for (const audioNode of cycle) {\n const count = counts.get(audioNode);\n\n counts.set(audioNode, count === undefined ? 1 : count + 1);\n }\n }\n\n counts.forEach((count, audioNode) => visitor(audioNode, count));\n};\n","import { TNativeAudioNode, TNativeAudioParam } from '../types';\n\nexport const isNativeAudioNode = (\n nativeAudioNodeOrAudioParam: TNativeAudioNode | TNativeAudioParam\n): nativeAudioNodeOrAudioParam is TNativeAudioNode => {\n return 'context' in nativeAudioNodeOrAudioParam;\n};\n","import { isNativeAudioNode } from '../guards/native-audio-node';\nimport { TNativeAudioNode, TNativeAudioParam } from '../types';\n\nexport const wrapAudioNodeDisconnectMethod = (nativeAudioNode: TNativeAudioNode): void => {\n const connections = new Map<TNativeAudioNode | TNativeAudioParam, { input: number; output: number }[]>();\n\n nativeAudioNode.connect = <TNativeAudioNode['connect']>((connect) => {\n // tslint:disable-next-line:invalid-void no-inferrable-types\n return (destination: TNativeAudioNode | TNativeAudioParam, output = 0, input: number = 0): void | TNativeAudioNode => {\n const returnValue = isNativeAudioNode(destination) ? connect(destination, output, input) : connect(destination, output);\n\n // Save the new connection only if the calls to connect above didn't throw an error.\n const connectionsToDestination = connections.get(destination);\n\n if (connectionsToDestination === undefined) {\n connections.set(destination, [{ input, output }]);\n } else {\n if (connectionsToDestination.every((connection) => connection.input !== input || connection.output !== output)) {\n connectionsToDestination.push({ input, output });\n }\n }\n\n return returnValue;\n };\n })(nativeAudioNode.connect.bind(nativeAudioNode));\n\n nativeAudioNode.disconnect = ((disconnect) => {\n return (destinationOrOutput?: number | TNativeAudioNode | TNativeAudioParam, output?: number, input?: number): void => {\n disconnect.apply(nativeAudioNode);\n\n if (destinationOrOutput === undefined) {\n connections.clear();\n } else if (typeof destinationOrOutput === 'number') {\n for (const [destination, connectionsToDestination] of connections) {\n const filteredConnections = connectionsToDestination.filter((connection) => connection.output !== destinationOrOutput);\n\n if (filteredConnections.length === 0) {\n connections.delete(destination);\n } else {\n connections.set(destination, filteredConnections);\n }\n }\n } else if (connections.has(destinationOrOutput)) {\n if (output === undefined) {\n connections.delete(destinationOrOutput);\n } else {\n const connectionsToDestination = connections.get(destinationOrOutput);\n\n if (connectionsToDestination !== undefined) {\n const filteredConnections = connectionsToDestination.filter(\n (connection) => connection.output !== output && (connection.input !== input || input === undefined)\n );\n\n if (filteredConnections.length === 0) {\n connections.delete(destinationOrOutput);\n } else {\n connections.set(destinationOrOutput, filteredConnections);\n }\n }\n }\n }\n\n for (const [destination, connectionsToDestination] of connections) {\n connectionsToDestination.forEach((connection) => {\n if (isNativeAudioNode(destination)) {\n nativeAudioNode.connect(destination, connection.output, connection.input);\n } else {\n nativeAudioNode.connect(destination, connection.output);\n }\n });\n }\n };\n })(nativeAudioNode.disconnect);\n};\n","import { AUDIO_NODE_STORE, EVENT_LISTENERS } from '../globals';\nimport { isAudioNode } from '../guards/audio-node';\nimport { isAudioNodeOutputConnection } from '../guards/audio-node-output-connection';\nimport { addActiveInputConnectionToAudioParam } from '../helpers/add-active-input-connection-to-audio-param';\nimport { addPassiveInputConnectionToAudioParam } from '../helpers/add-passive-input-connection-to-audio-param';\nimport { connectNativeAudioNodeToNativeAudioNode } from '../helpers/connect-native-audio-node-to-native-audio-node';\nimport { deleteActiveInputConnection } from '../helpers/delete-active-input-connection';\nimport { deleteActiveInputConnectionToAudioParam } from '../helpers/delete-active-input-connection-to-audio-param';\nimport { deleteEventListenerOfAudioNode } from '../helpers/delete-event-listeners-of-audio-node';\nimport { deletePassiveInputConnectionToAudioNode } from '../helpers/delete-passive-input-connection-to-audio-node';\nimport { deletePassiveInputConnectionToAudioParam } from '../helpers/delete-passive-input-connection-to-audio-param';\nimport { disconnectNativeAudioNodeFromNativeAudioNode } from '../helpers/disconnect-native-audio-node-from-native-audio-node';\nimport { getAudioNodeConnections } from '../helpers/get-audio-node-connections';\nimport { getAudioParamConnections } from '../helpers/get-audio-param-connections';\nimport { getEventListenersOfAudioNode } from '../helpers/get-event-listeners-of-audio-node';\nimport { getNativeAudioNode } from '../helpers/get-native-audio-node';\nimport { getNativeAudioParam } from '../helpers/get-native-audio-param';\nimport { insertElementInSet } from '../helpers/insert-element-in-set';\nimport { isActiveAudioNode } from '../helpers/is-active-audio-node';\nimport { isPartOfACycle } from '../helpers/is-part-of-a-cycle';\nimport { isPassiveAudioNode } from '../helpers/is-passive-audio-node';\nimport { setInternalStateToActive } from '../helpers/set-internal-state-to-active';\nimport { setInternalStateToPassiveWhenNecessary } from '../helpers/set-internal-state-to-passive-when-necessary';\nimport { testAudioNodeDisconnectMethodSupport } from '../helpers/test-audio-node-disconnect-method-support';\nimport { visitEachAudioNodeOnce } from '../helpers/visit-each-audio-node-once';\nimport { wrapAudioNodeDisconnectMethod } from '../helpers/wrap-audio-node-disconnect-method';\nimport {\n IAudioNode,\n IAudioNodeRenderer,\n IAudioParam,\n IMinimalOfflineAudioContext,\n INativeAudioNodeFaker,\n IOfflineAudioContext\n} from '../interfaces';\nimport {\n TAudioNodeConstructorFactory,\n TChannelCountMode,\n TChannelInterpretation,\n TContext,\n TInternalStateEventListener,\n TNativeAudioNode,\n TNativeAudioParam\n} from '../types';\n\nconst addConnectionToAudioParamOfAudioContext = <T extends TContext>(\n source: IAudioNode<T>,\n destination: IAudioParam,\n output: number,\n isOffline: boolean\n): boolean => {\n const { activeInputs, passiveInputs } = getAudioParamConnections<T>(destination);\n const { outputs } = getAudioNodeConnections(source);\n const eventListeners = getEventListenersOfAudioNode(source);\n\n const eventListener: TInternalStateEventListener = (isActive) => {\n const nativeAudioNode = getNativeAudioNode(source);\n const nativeAudioParam = getNativeAudioParam(destination);\n\n if (isActive) {\n const partialConnection = deletePassiveInputConnectionToAudioParam(passiveInputs, source, output);\n\n addActiveInputConnectionToAudioParam(activeInputs, source, partialConnection, false);\n\n if (!isOffline && !isPartOfACycle(source)) {\n nativeAudioNode.connect(nativeAudioParam, output);\n }\n } else {\n const partialConnection = deleteActiveInputConnectionToAudioParam(activeInputs, source, output);\n\n addPassiveInputConnectionToAudioParam(passiveInputs, partialConnection, false);\n\n if (!isOffline && !isPartOfACycle(source)) {\n nativeAudioNode.disconnect(nativeAudioParam, output);\n }\n }\n };\n\n if (\n insertElementInSet(\n outputs,\n [destination, output],\n (outputConnection) => outputConnection[0] === destination && outputConnection[1] === output,\n true\n )\n ) {\n eventListeners.add(eventListener);\n\n if (isActiveAudioNode(source)) {\n addActiveInputConnectionToAudioParam(activeInputs, source, [output, eventListener], true);\n } else {\n addPassiveInputConnectionToAudioParam(passiveInputs, [source, output, eventListener], true);\n }\n\n return true;\n }\n\n return false;\n};\n\nconst deleteInputConnectionOfAudioNode = <T extends TContext>(\n source: IAudioNode<T>,\n destination: IAudioNode<T>,\n output: number,\n input: number\n): [null | TInternalStateEventListener, boolean] => {\n const { activeInputs, passiveInputs } = getAudioNodeConnections(destination);\n\n const activeInputConnection = deleteActiveInputConnection(activeInputs[input], source, output);\n\n if (activeInputConnection === null) {\n const passiveInputConnection = deletePassiveInputConnectionToAudioNode(passiveInputs, source, output, input);\n\n return [passiveInputConnection[2], false];\n }\n\n return [activeInputConnection[2], true];\n};\n\nconst deleteInputConnectionOfAudioParam = <T extends TContext>(\n source: IAudioNode<T>,\n destination: IAudioParam,\n output: number\n): [null | TInternalStateEventListener, boolean] => {\n const { activeInputs, passiveInputs } = getAudioParamConnections<T>(destination);\n\n const activeInputConnection = deleteActiveInputConnection(activeInputs, source, output);\n\n if (activeInputConnection === null) {\n const passiveInputConnection = deletePassiveInputConnectionToAudioParam(passiveInputs, source, output);\n\n return [passiveInputConnection[1], false];\n }\n\n return [activeInputConnection[2], true];\n};\n\nconst deleteInputsOfAudioNode = <T extends TContext>(\n source: IAudioNode<T>,\n isOffline: boolean,\n destination: IAudioNode<T>,\n output: number,\n input: number\n) => {\n const [listener, isActive] = deleteInputConnectionOfAudioNode(source, destination, output, input);\n\n if (listener !== null) {\n deleteEventListenerOfAudioNode(source, listener);\n\n if (isActive && !isOffline && !isPartOfACycle(source)) {\n disconnectNativeAudioNodeFromNativeAudioNode(getNativeAudioNode(source), getNativeAudioNode(destination), output, input);\n }\n }\n\n if (isActiveAudioNode(destination)) {\n const { activeInputs } = getAudioNodeConnections(destination);\n\n setInternalStateToPassiveWhenNecessary(destination, activeInputs);\n }\n};\n\nconst deleteInputsOfAudioParam = <T extends TContext>(\n source: IAudioNode<T>,\n isOffline: boolean,\n destination: IAudioParam,\n output: number\n) => {\n const [listener, isActive] = deleteInputConnectionOfAudioParam(source, destination, output);\n\n if (listener !== null) {\n deleteEventListenerOfAudioNode(source, listener);\n\n if (isActive && !isOffline && !isPartOfACycle(source)) {\n getNativeAudioNode(source).disconnect(getNativeAudioParam(destination), output);\n }\n }\n};\n\nconst deleteAnyConnection = <T extends TContext>(source: IAudioNode<T>, isOffline: boolean): (IAudioNode<T> | IAudioParam)[] => {\n const audioNodeConnectionsOfSource = getAudioNodeConnections(source);\n const destinations = [];\n\n for (const outputConnection of audioNodeConnectionsOfSource.outputs) {\n if (isAudioNodeOutputConnection(outputConnection)) {\n deleteInputsOfAudioNode(source, isOffline, ...outputConnection);\n } else {\n deleteInputsOfAudioParam(source, isOffline, ...outputConnection);\n }\n\n destinations.push(outputConnection[0]);\n }\n\n audioNodeConnectionsOfSource.outputs.clear();\n\n return destinations;\n};\n\nconst deleteConnectionAtOutput = <T extends TContext>(\n source: IAudioNode<T>,\n isOffline: boolean,\n output: number\n): (IAudioNode<T> | IAudioParam)[] => {\n const audioNodeConnectionsOfSource = getAudioNodeConnections(source);\n const destinations = [];\n\n for (const outputConnection of audioNodeConnectionsOfSource.outputs) {\n if (outputConnection[1] === output) {\n if (isAudioNodeOutputConnection(outputConnection)) {\n deleteInputsOfAudioNode(source, isOffline, ...outputConnection);\n } else {\n deleteInputsOfAudioParam(source, isOffline, ...outputConnection);\n }\n\n destinations.push(outputConnection[0]);\n audioNodeConnectionsOfSource.outputs.delete(outputConnection);\n }\n }\n\n return destinations;\n};\n\nconst deleteConnectionToDestination = <T extends TContext, U extends TContext>(\n source: IAudioNode<T>,\n isOffline: boolean,\n destination: IAudioNode<U> | IAudioParam,\n output?: number,\n input?: number\n): (IAudioNode<T> | IAudioParam)[] => {\n const audioNodeConnectionsOfSource = getAudioNodeConnections(source);\n\n return Array.from(audioNodeConnectionsOfSource.outputs)\n .filter(\n (outputConnection) =>\n outputConnection[0] === destination &&\n (output === undefined || outputConnection[1] === output) &&\n (input === undefined || outputConnection[2] === input)\n )\n .map((outputConnection) => {\n if (isAudioNodeOutputConnection(outputConnection)) {\n deleteInputsOfAudioNode(source, isOffline, ...outputConnection);\n } else {\n deleteInputsOfAudioParam(source, isOffline, ...outputConnection);\n }\n\n audioNodeConnectionsOfSource.outputs.delete(outputConnection);\n\n return outputConnection[0];\n });\n};\n\nexport const createAudioNodeConstructor: TAudioNodeConstructorFactory = (\n addAudioNodeConnections,\n addConnectionToAudioNode,\n cacheTestResult,\n createIncrementCycleCounter,\n createIndexSizeError,\n createInvalidAccessError,\n createNotSupportedError,\n decrementCycleCounter,\n detectCycles,\n eventTargetConstructor,\n getNativeContext,\n isNativeAudioContext,\n isNativeAudioNode,\n isNativeAudioParam,\n isNativeOfflineAudioContext,\n nativeAudioWorkletNodeConstructor\n) => {\n return class AudioNode<T extends TContext, EventMap extends Record<string, Event> = {}>\n extends eventTargetConstructor<EventMap>\n implements IAudioNode<T, EventMap>\n {\n private _context: T;\n\n private _nativeAudioNode: INativeAudioNodeFaker | TNativeAudioNode;\n\n constructor(\n context: T,\n isActive: boolean,\n nativeAudioNode: INativeAudioNodeFaker | TNativeAudioNode,\n audioNodeRenderer: T extends IMinimalOfflineAudioContext | IOfflineAudioContext ? IAudioNodeRenderer<T, IAudioNode<T>> : null\n ) {\n super(nativeAudioNode);\n\n this._context = context;\n this._nativeAudioNode = nativeAudioNode;\n\n const nativeContext = getNativeContext(context);\n\n // Bug #12: Safari does not support to disconnect a specific destination.\n if (\n isNativeAudioContext(nativeContext) &&\n true !==\n cacheTestResult(testAudioNodeDisconnectMethodSupport, () => {\n return testAudioNodeDisconnectMethodSupport(nativeContext, nativeAudioWorkletNodeConstructor);\n })\n ) {\n wrapAudioNodeDisconnectMethod(nativeAudioNode);\n }\n\n AUDIO_NODE_STORE.set(this, nativeAudioNode);\n EVENT_LISTENERS.set(this, new Set());\n\n if (context.state !== 'closed' && isActive) {\n setInternalStateToActive(this);\n }\n\n addAudioNodeConnections(this, audioNodeRenderer, nativeAudioNode);\n }\n\n get channelCount(): number {\n return this._nativeAudioNode.channelCount;\n }\n\n set channelCount(value) {\n this._nativeAudioNode.channelCount = value;\n }\n\n get channelCountMode(): TChannelCountMode {\n return this._nativeAudioNode.channelCountMode;\n }\n\n set channelCountMode(value) {\n this._nativeAudioNode.channelCountMode = value;\n }\n\n get channelInterpretation(): TChannelInterpretation {\n return this._nativeAudioNode.channelInterpretation;\n }\n\n set channelInterpretation(value) {\n this._nativeAudioNode.channelInterpretation = value;\n }\n\n get context(): T {\n return this._context;\n }\n\n get numberOfInputs(): number {\n return this._nativeAudioNode.numberOfInputs;\n }\n\n get numberOfOutputs(): number {\n return this._nativeAudioNode.numberOfOutputs;\n }\n\n public connect<U extends TContext, V extends IAudioNode<U>>(destinationNode: V, output?: number, input?: number): V;\n public connect(destinationParam: IAudioParam, output?: number): void;\n // tslint:disable-next-line:invalid-void\n public connect<U extends TContext, V extends IAudioNode<U>>(destination: V | IAudioParam, output = 0, input = 0): void | V {\n // Bug #174: Safari does expose a wrong numberOfOutputs for MediaStreamAudioDestinationNodes.\n if (output < 0 || output >= this._nativeAudioNode.numberOfOutputs) {\n throw createIndexSizeError();\n }\n\n const nativeContext = getNativeContext(this._context);\n const isOffline = isNativeOfflineAudioContext(nativeContext);\n\n if (isNativeAudioNode(destination) || isNativeAudioParam(destination)) {\n throw createInvalidAccessError();\n }\n\n if (isAudioNode(destination)) {\n const nativeDestinationAudioNode = getNativeAudioNode(destination);\n\n try {\n const connection = connectNativeAudioNodeToNativeAudioNode(\n this._nativeAudioNode,\n nativeDestinationAudioNode,\n output,\n input\n );\n\n const isPassive = isPassiveAudioNode(this);\n\n if (isOffline || isPassive) {\n this._nativeAudioNode.disconnect(...connection);\n }\n\n if (this.context.state !== 'closed' && !isPassive && isPassiveAudioNode(destination)) {\n setInternalStateToActive(destination);\n }\n } catch (err) {\n // Bug #41: Safari does not throw the correct exception so far.\n if (err.code === 12) {\n throw createInvalidAccessError();\n }\n\n throw err;\n }\n\n const isNewConnectionToAudioNode = addConnectionToAudioNode(\n this,\n <IAudioNode<TContext>>destination,\n output,\n input,\n isOffline\n );\n\n // Bug #164: Only Firefox detects cycles so far.\n if (isNewConnectionToAudioNode) {\n const cycles = detectCycles([this], <IAudioNode<T>>(<unknown>destination));\n\n visitEachAudioNodeOnce(cycles, createIncrementCycleCounter(isOffline));\n }\n\n return destination;\n }\n\n const nativeAudioParam = getNativeAudioParam(destination);\n\n /*\n * Bug #73, #147 & #153: Safari does not support to connect an input signal to the playbackRate AudioParam of an\n * AudioBufferSourceNode. This can't be easily detected and that's why the outdated name property is used here to identify\n * Safari. In addition to that the maxValue property is used to only detect the affected versions below v14.0.2.\n */\n if ((<TNativeAudioParam & { name: string }>nativeAudioParam).name === 'playbackRate' && nativeAudioParam.maxValue === 1024) {\n throw createNotSupportedError();\n }\n\n try {\n this._nativeAudioNode.connect(nativeAudioParam, output);\n\n if (isOffline || isPassiveAudioNode(this)) {\n this._nativeAudioNode.disconnect(nativeAudioParam, output);\n }\n } catch (err) {\n // Bug #58: Safari doesn't throw an InvalidAccessError yet.\n if (err.code === 12) {\n throw createInvalidAccessError();\n }\n\n throw err;\n }\n\n const isNewConnectionToAudioParam = addConnectionToAudioParamOfAudioContext(this, destination, output, isOffline);\n\n // Bug #164: Only Firefox detects cycles so far.\n if (isNewConnectionToAudioParam) {\n const cycles = detectCycles([this], destination);\n\n visitEachAudioNodeOnce(cycles, createIncrementCycleCounter(isOffline));\n }\n }\n\n public disconnect(output?: number): void;\n public disconnect<U extends TContext>(destinationNode: IAudioNode<U>, output?: number, input?: number): void;\n public disconnect(destinationParam: IAudioParam, output?: number): void;\n public disconnect<U extends TContext>(\n destinationOrOutput?: number | IAudioNode<U> | IAudioParam,\n output?: number,\n input?: number\n ): void {\n let destinations: (IAudioNode<T> | IAudioParam)[];\n\n const nativeContext = getNativeContext(this._context);\n const isOffline = isNativeOfflineAudioContext(nativeContext);\n\n if (destinationOrOutput === undefined) {\n destinations = deleteAnyConnection(this, isOffline);\n } else if (typeof destinationOrOutput === 'number') {\n if (destinationOrOutput < 0 || destinationOrOutput >= this.numberOfOutputs) {\n throw createIndexSizeError();\n }\n\n destinations = deleteConnectionAtOutput(this, isOffline, destinationOrOutput);\n } else {\n if (output !== undefined && (output < 0 || output >= this.numberOfOutputs)) {\n throw createIndexSizeError();\n }\n\n if (isAudioNode(destinationOrOutput) && input !== undefined && (input < 0 || input >= destinationOrOutput.numberOfInputs)) {\n throw createIndexSizeError();\n }\n\n destinations = deleteConnectionToDestination(this, isOffline, destinationOrOutput, output, input);\n\n if (destinations.length === 0) {\n throw createInvalidAccessError();\n }\n }\n\n // Bug #164: Only Firefox detects cycles so far.\n for (const destination of destinations) {\n const cycles = detectCycles([this], destination);\n\n visitEachAudioNodeOnce(cycles, decrementCycleCounter);\n }\n }\n };\n};\n","import { AutomationEventList } from 'automation-events';\nimport { IAudioNode, IAudioParam, IAudioParamRenderer, IMinimalOfflineAudioContext, IOfflineAudioContext } from '../interfaces';\nimport { TAudioParamFactoryFactory, TContext, TNativeAudioParam } from '../types';\n\nexport const createAudioParamFactory: TAudioParamFactoryFactory = (\n addAudioParamConnections,\n audioParamAudioNodeStore,\n audioParamStore,\n createAudioParamRenderer,\n createCancelAndHoldAutomationEvent,\n createCancelScheduledValuesAutomationEvent,\n createExponentialRampToValueAutomationEvent,\n createLinearRampToValueAutomationEvent,\n createSetTargetAutomationEvent,\n createSetValueAutomationEvent,\n createSetValueCurveAutomationEvent,\n nativeAudioContextConstructor,\n setValueAtTimeUntilPossible\n) => {\n return <T extends TContext>(\n audioNode: IAudioNode<T>,\n isAudioParamOfOfflineAudioContext: boolean,\n nativeAudioParam: TNativeAudioParam,\n maxValue: null | number = null,\n minValue: null | number = null\n ): IAudioParam => {\n // Bug #196 Only Safari sets the defaultValue to the initial value.\n const defaultValue = nativeAudioParam.value;\n const automationEventList = new AutomationEventList(defaultValue);\n const audioParamRenderer = isAudioParamOfOfflineAudioContext ? createAudioParamRenderer(automationEventList) : null;\n const audioParam = {\n get defaultValue(): number {\n return defaultValue;\n },\n get maxValue(): number {\n return maxValue === null ? nativeAudioParam.maxValue : maxValue;\n },\n get minValue(): number {\n return minValue === null ? nativeAudioParam.minValue : minValue;\n },\n get value(): number {\n return nativeAudioParam.value;\n },\n set value(value) {\n nativeAudioParam.value = value;\n\n // Bug #98: Firefox & Safari do not yet treat the value setter like a call to setValueAtTime().\n audioParam.setValueAtTime(value, audioNode.context.currentTime);\n },\n cancelAndHoldAtTime(cancelTime: number): IAudioParam {\n // Bug #28: Firefox & Safari do not yet implement cancelAndHoldAtTime().\n if (typeof nativeAudioParam.cancelAndHoldAtTime === 'function') {\n if (audioParamRenderer === null) {\n automationEventList.flush(audioNode.context.currentTime);\n }\n\n automationEventList.add(createCancelAndHoldAutomationEvent(cancelTime));\n nativeAudioParam.cancelAndHoldAtTime(cancelTime);\n } else {\n const previousLastEvent = Array.from(automationEventList).pop();\n\n if (audioParamRenderer === null) {\n automationEventList.flush(audioNode.context.currentTime);\n }\n\n automationEventList.add(createCancelAndHoldAutomationEvent(cancelTime));\n\n const currentLastEvent = Array.from(automationEventList).pop();\n\n nativeAudioParam.cancelScheduledValues(cancelTime);\n\n if (previousLastEvent !== currentLastEvent && currentLastEvent !== undefined) {\n if (currentLastEvent.type === 'exponentialRampToValue') {\n nativeAudioParam.exponentialRampToValueAtTime(currentLastEvent.value, currentLastEvent.endTime);\n } else if (currentLastEvent.type === 'linearRampToValue') {\n nativeAudioParam.linearRampToValueAtTime(currentLastEvent.value, currentLastEvent.endTime);\n } else if (currentLastEvent.type === 'setValue') {\n nativeAudioParam.setValueAtTime(currentLastEvent.value, currentLastEvent.startTime);\n } else if (currentLastEvent.type === 'setValueCurve') {\n nativeAudioParam.setValueCurveAtTime(\n currentLastEvent.values,\n currentLastEvent.startTime,\n currentLastEvent.duration\n );\n }\n }\n }\n\n return audioParam;\n },\n cancelScheduledValues(cancelTime: number): IAudioParam {\n if (audioParamRenderer === null) {\n automationEventList.flush(audioNode.context.currentTime);\n }\n\n automationEventList.add(createCancelScheduledValuesAutomationEvent(cancelTime));\n nativeAudioParam.cancelScheduledValues(cancelTime);\n\n return audioParam;\n },\n exponentialRampToValueAtTime(value: number, endTime: number): IAudioParam {\n // Bug #45: Safari does not throw an error yet.\n if (value === 0) {\n throw new RangeError();\n }\n\n // Bug #187: Safari does not throw an error yet.\n if (!Number.isFinite(endTime) || endTime < 0) {\n throw new RangeError();\n }\n\n const currentTime = audioNode.context.currentTime;\n\n if (audioParamRenderer === null) {\n automationEventList.flush(currentTime);\n }\n\n // Bug #194: Firefox does not implicitly call setValueAtTime() if there is no previous event.\n if (Array.from(automationEventList).length === 0) {\n automationEventList.add(createSetValueAutomationEvent(defaultValue, currentTime));\n nativeAudioParam.setValueAtTime(defaultValue, currentTime);\n }\n\n automationEventList.add(createExponentialRampToValueAutomationEvent(value, endTime));\n nativeAudioParam.exponentialRampToValueAtTime(value, endTime);\n\n return audioParam;\n },\n linearRampToValueAtTime(value: number, endTime: number): IAudioParam {\n const currentTime = audioNode.context.currentTime;\n\n if (audioParamRenderer === null) {\n automationEventList.flush(currentTime);\n }\n\n // Bug #195: Firefox does not implicitly call setValueAtTime() if there is no previous event.\n if (Array.from(automationEventList).length === 0) {\n automationEventList.add(createSetValueAutomationEvent(defaultValue, currentTime));\n nativeAudioParam.setValueAtTime(defaultValue, currentTime);\n }\n\n automationEventList.add(createLinearRampToValueAutomationEvent(value, endTime));\n nativeAudioParam.linearRampToValueAtTime(value, endTime);\n\n return audioParam;\n },\n setTargetAtTime(target: number, startTime: number, timeConstant: number): IAudioParam {\n if (audioParamRenderer === null) {\n automationEventList.flush(audioNode.context.currentTime);\n }\n\n automationEventList.add(createSetTargetAutomationEvent(target, startTime, timeConstant));\n nativeAudioParam.setTargetAtTime(target, startTime, timeConstant);\n\n return audioParam;\n },\n setValueAtTime(value: number, startTime: number): IAudioParam {\n if (audioParamRenderer === null) {\n automationEventList.flush(audioNode.context.currentTime);\n }\n\n automationEventList.add(createSetValueAutomationEvent(value, startTime));\n nativeAudioParam.setValueAtTime(value, startTime);\n\n return audioParam;\n },\n setValueCurveAtTime(values: Iterable<number>, startTime: number, duration: number): IAudioParam {\n // Bug 183: Safari only accepts a Float32Array.\n const convertedValues = values instanceof Float32Array ? values : new Float32Array(values);\n /*\n * Bug #152: Safari does not correctly interpolate the values of the curve.\n * @todo Unfortunately there is no way to test for this behavior in a synchronous fashion which is why testing for the\n * existence of the webkitAudioContext is used as a workaround here.\n */\n if (nativeAudioContextConstructor !== null && nativeAudioContextConstructor.name === 'webkitAudioContext') {\n const endTime = startTime + duration;\n const sampleRate = audioNode.context.sampleRate;\n const firstSample = Math.ceil(startTime * sampleRate);\n const lastSample = Math.floor(endTime * sampleRate);\n const numberOfInterpolatedValues = lastSample - firstSample;\n const interpolatedValues = new Float32Array(numberOfInterpolatedValues);\n\n for (let i = 0; i < numberOfInterpolatedValues; i += 1) {\n const theoreticIndex = ((convertedValues.length - 1) / duration) * ((firstSample + i) / sampleRate - startTime);\n const lowerIndex = Math.floor(theoreticIndex);\n const upperIndex = Math.ceil(theoreticIndex);\n\n interpolatedValues[i] =\n lowerIndex === upperIndex\n ? convertedValues[lowerIndex]\n : (1 - (theoreticIndex - lowerIndex)) * convertedValues[lowerIndex] +\n (1 - (upperIndex - theoreticIndex)) * convertedValues[upperIndex];\n }\n\n if (audioParamRenderer === null) {\n automationEventList.flush(audioNode.context.currentTime);\n }\n\n automationEventList.add(createSetValueCurveAutomationEvent(interpolatedValues, startTime, duration));\n nativeAudioParam.setValueCurveAtTime(interpolatedValues, startTime, duration);\n\n const timeOfLastSample = lastSample / sampleRate;\n\n if (timeOfLastSample < endTime) {\n setValueAtTimeUntilPossible(audioParam, interpolatedValues[interpolatedValues.length - 1], timeOfLastSample);\n }\n\n setValueAtTimeUntilPossible(audioParam, convertedValues[convertedValues.length - 1], endTime);\n } else {\n if (audioParamRenderer === null) {\n automationEventList.flush(audioNode.context.currentTime);\n }\n\n automationEventList.add(createSetValueCurveAutomationEvent(convertedValues, startTime, duration));\n nativeAudioParam.setValueCurveAtTime(convertedValues, startTime, duration);\n }\n\n return audioParam;\n }\n };\n\n audioParamStore.set(audioParam, nativeAudioParam);\n audioParamAudioNodeStore.set(audioParam, audioNode);\n\n addAudioParamConnections(\n audioParam,\n <T extends IMinimalOfflineAudioContext | IOfflineAudioContext ? IAudioParamRenderer : null>audioParamRenderer\n );\n\n return audioParam;\n };\n};\n","import { TAudioParamRendererFactory, TNativeAudioParam } from '../types';\n\nexport const createAudioParamRenderer: TAudioParamRendererFactory = (automationEventList) => {\n return {\n replay(audioParam: TNativeAudioParam): void {\n for (const automationEvent of automationEventList) {\n if (automationEvent.type === 'exponentialRampToValue') {\n const { endTime, value } = automationEvent;\n\n audioParam.exponentialRampToValueAtTime(value, endTime);\n } else if (automationEvent.type === 'linearRampToValue') {\n const { endTime, value } = automationEvent;\n\n audioParam.linearRampToValueAtTime(value, endTime);\n } else if (automationEvent.type === 'setTarget') {\n const { startTime, target, timeConstant } = automationEvent;\n\n audioParam.setTargetAtTime(target, startTime, timeConstant);\n } else if (automationEvent.type === 'setValue') {\n const { startTime, value } = automationEvent;\n\n audioParam.setValueAtTime(value, startTime);\n } else if (automationEvent.type === 'setValueCurve') {\n const { duration, startTime, values } = automationEvent;\n\n audioParam.setValueCurveAtTime(values, startTime, duration);\n } else {\n throw new Error(\"Can't apply an unknown automation.\");\n }\n }\n }\n };\n};\n","import { IReadOnlyMap } from './interfaces';\n\nexport class ReadOnlyMap<T, U> implements IReadOnlyMap<T, U> {\n private _map: Map<T, U>;\n\n constructor(parameters: [T, U][]) {\n this._map = new Map(parameters);\n }\n\n get size(): number {\n return this._map.size;\n }\n\n public entries(): IterableIterator<[T, U]> {\n return this._map.entries();\n }\n\n public forEach(callback: (audioParam: U, name: T, map: ReadOnlyMap<T, U>) => void, thisArg: any = null): void {\n return this._map.forEach((value: U, key: T) => callback.call(thisArg, value, key, this));\n }\n\n public get(name: T): undefined | U {\n return this._map.get(name);\n }\n\n public has(name: T): boolean {\n return this._map.has(name);\n }\n\n public keys(): IterableIterator<T> {\n return this._map.keys();\n }\n\n public values(): IterableIterator<U> {\n return this._map.values();\n }\n}\n","import { NODE_NAME_TO_PROCESSOR_CONSTRUCTOR_MAPS } from '../globals';\nimport {\n IAudioParam,\n IAudioWorkletNode,\n IAudioWorkletNodeEventMap,\n IAudioWorkletNodeOptions,\n IMinimalAudioContext,\n IMinimalOfflineAudioContext,\n IOfflineAudioContext,\n IReadOnlyMap\n} from '../interfaces';\nimport { ReadOnlyMap } from '../read-only-map';\nimport {\n TAudioNodeRenderer,\n TAudioParamMap,\n TAudioWorkletNodeConstructorFactory,\n TContext,\n TErrorEventHandler,\n TNativeAudioContext,\n TNativeAudioParam,\n TNativeAudioWorkletNode\n} from '../types';\n\nconst DEFAULT_OPTIONS = {\n channelCount: 2,\n // Bug #61: The channelCountMode should be 'max' according to the spec but is set to 'explicit' to achieve consistent behavior.\n channelCountMode: 'explicit',\n channelInterpretation: 'speakers',\n numberOfInputs: 1,\n numberOfOutputs: 1,\n parameterData: {},\n processorOptions: {}\n} as const;\n\nexport const createAudioWorkletNodeConstructor: TAudioWorkletNodeConstructorFactory = (\n addUnrenderedAudioWorkletNode,\n audioNodeConstructor,\n createAudioParam,\n createAudioWorkletNodeRenderer,\n createNativeAudioWorkletNode,\n getAudioNodeConnections,\n getBackupOfflineAudioContext,\n getNativeContext,\n isNativeOfflineAudioContext,\n nativeAudioWorkletNodeConstructor,\n sanitizeAudioWorkletNodeOptions,\n setActiveAudioWorkletNodeInputs,\n testAudioWorkletNodeOptionsClonability,\n wrapEventListener\n) => {\n return class AudioWorkletNode<T extends TContext>\n extends audioNodeConstructor<T, IAudioWorkletNodeEventMap>\n implements IAudioWorkletNode<T>\n {\n private _nativeAudioWorkletNode: TNativeAudioWorkletNode;\n\n private _onprocessorerror: null | TErrorEventHandler<this>;\n\n private _parameters: null | TAudioParamMap;\n\n constructor(context: T, name: string, options?: Partial<IAudioWorkletNodeOptions>) {\n const nativeContext = getNativeContext(context);\n const isOffline = isNativeOfflineAudioContext(nativeContext);\n const mergedOptions = sanitizeAudioWorkletNodeOptions({ ...DEFAULT_OPTIONS, ...options });\n\n // Bug #191: Safari doesn't throw an error if the options aren't clonable.\n testAudioWorkletNodeOptionsClonability(mergedOptions);\n\n const nodeNameToProcessorConstructorMap = NODE_NAME_TO_PROCESSOR_CONSTRUCTOR_MAPS.get(nativeContext);\n const processorConstructor = nodeNameToProcessorConstructorMap?.get(name);\n // Bug #186: Chrome and Edge do not allow to create an AudioWorkletNode on a closed AudioContext.\n const nativeContextOrBackupOfflineAudioContext =\n isOffline || nativeContext.state !== 'closed'\n ? nativeContext\n : getBackupOfflineAudioContext(<TNativeAudioContext>nativeContext) ?? nativeContext;\n const nativeAudioWorkletNode = createNativeAudioWorkletNode(\n nativeContextOrBackupOfflineAudioContext,\n isOffline ? null : (<IMinimalAudioContext>(<any>context)).baseLatency,\n nativeAudioWorkletNodeConstructor,\n name,\n processorConstructor,\n mergedOptions\n );\n const audioWorkletNodeRenderer = <TAudioNodeRenderer<T, this>>(\n (isOffline ? createAudioWorkletNodeRenderer(name, mergedOptions, processorConstructor) : null)\n );\n\n /*\n * @todo Add a mechanism to switch an AudioWorkletNode to passive once the process() function of the AudioWorkletProcessor\n * returns false.\n */\n super(context, true, nativeAudioWorkletNode, audioWorkletNodeRenderer);\n\n const parameters: [string, IAudioParam][] = [];\n\n nativeAudioWorkletNode.parameters.forEach((nativeAudioParam, nm) => {\n const audioParam = createAudioParam(this, isOffline, nativeAudioParam);\n\n parameters.push([nm, audioParam]);\n });\n\n this._nativeAudioWorkletNode = nativeAudioWorkletNode;\n this._onprocessorerror = null;\n this._parameters = new ReadOnlyMap(parameters);\n\n /*\n * Bug #86 & #87: Invoking the renderer of an AudioWorkletNode might be necessary if it has no direct or indirect connection to\n * the destination.\n */\n if (isOffline) {\n addUnrenderedAudioWorkletNode(nativeContext, <IAudioWorkletNode<IMinimalOfflineAudioContext | IOfflineAudioContext>>this);\n }\n\n const { activeInputs } = getAudioNodeConnections(this);\n\n setActiveAudioWorkletNodeInputs(nativeAudioWorkletNode, activeInputs);\n }\n\n get onprocessorerror(): null | TErrorEventHandler<this> {\n return this._onprocessorerror;\n }\n\n set onprocessorerror(value) {\n const wrappedListener = typeof value === 'function' ? wrapEventListener(this, <EventListenerOrEventListenerObject>value) : null;\n\n this._nativeAudioWorkletNode.onprocessorerror = wrappedListener;\n\n const nativeOnProcessorError = this._nativeAudioWorkletNode.onprocessorerror;\n\n this._onprocessorerror =\n nativeOnProcessorError !== null && nativeOnProcessorError === wrappedListener\n ? value\n : <null | TErrorEventHandler<this>>nativeOnProcessorError;\n }\n\n get parameters(): TAudioParamMap {\n if (this._parameters === null) {\n // @todo The definition that TypeScript uses of the AudioParamMap is lacking many methods.\n return <IReadOnlyMap<string, TNativeAudioParam>>this._nativeAudioWorkletNode.parameters;\n }\n\n return this._parameters;\n }\n\n get port(): MessagePort {\n return this._nativeAudioWorkletNode.port;\n }\n };\n};\n","import { TNativeAudioBuffer } from '../types';\n\nexport function copyFromChannel(\n audioBuffer: TNativeAudioBuffer,\n parent: { [key: number]: Float32Array },\n key: number,\n channelNumber: number,\n bufferOffset: number\n): void;\nexport function copyFromChannel(\n audioBuffer: TNativeAudioBuffer,\n parent: { [key: string]: Float32Array },\n key: string,\n channelNumber: number,\n bufferOffset: number\n): void;\nexport function copyFromChannel(\n audioBuffer: TNativeAudioBuffer,\n // @todo There is currently no way to define something like { [ key: number | string ]: Float32Array }\n parent: any,\n key: number | string,\n channelNumber: number,\n bufferOffset: number\n): void {\n if (typeof audioBuffer.copyFromChannel === 'function') {\n // The byteLength will be 0 when the ArrayBuffer was transferred.\n if (parent[key].byteLength === 0) {\n parent[key] = new Float32Array(128);\n }\n\n audioBuffer.copyFromChannel(parent[key], channelNumber, bufferOffset);\n\n // Bug #5: Safari does not support copyFromChannel().\n } else {\n const channelData = audioBuffer.getChannelData(channelNumber);\n\n // The byteLength will be 0 when the ArrayBuffer was transferred.\n if (parent[key].byteLength === 0) {\n parent[key] = channelData.slice(bufferOffset, bufferOffset + 128);\n } else {\n const slicedInput = new Float32Array(channelData.buffer, bufferOffset * Float32Array.BYTES_PER_ELEMENT, 128);\n\n parent[key].set(slicedInput);\n }\n }\n}\n","import { TNativeAudioBuffer } from '../types';\n\nexport const copyToChannel = (\n audioBuffer: TNativeAudioBuffer,\n parent: { [key: number]: Float32Array },\n key: number,\n channelNumber: number,\n bufferOffset: number\n): void => {\n if (typeof audioBuffer.copyToChannel === 'function') {\n // The byteLength will be 0 when the ArrayBuffer was transferred.\n if (parent[key].byteLength !== 0) {\n audioBuffer.copyToChannel(parent[key], channelNumber, bufferOffset);\n }\n\n // Bug #5: Safari does not support copyToChannel().\n } else {\n // The byteLength will be 0 when the ArrayBuffer was transferred.\n if (parent[key].byteLength !== 0) {\n audioBuffer.getChannelData(channelNumber).set(parent[key], bufferOffset);\n }\n }\n};\n","export const createNestedArrays = (x: number, y: number | number[]): Float32Array[][] => {\n const arrays: Float32Array[][] = [];\n\n for (let i = 0; i < x; i += 1) {\n const array = [];\n\n const length = typeof y === 'number' ? y : y[i];\n\n for (let j = 0; j < length; j += 1) {\n array.push(new Float32Array(128));\n }\n\n arrays.push(array);\n }\n\n return arrays;\n};\n","import { NODE_TO_PROCESSOR_MAPS } from '../globals';\nimport { IAudioNode, IAudioWorkletProcessor } from '../interfaces';\nimport { TContext, TNativeAudioWorkletNode, TNativeOfflineAudioContext } from '../types';\nimport { getNativeAudioNode } from './get-native-audio-node';\nimport { getValueForKey } from './get-value-for-key';\n\nexport const getAudioWorkletProcessor = <T extends TContext>(\n nativeOfflineAudioContext: TNativeOfflineAudioContext,\n proxy: IAudioNode<T>\n): Promise<IAudioWorkletProcessor> => {\n const nodeToProcessorMap = getValueForKey(NODE_TO_PROCESSOR_MAPS, nativeOfflineAudioContext);\n const nativeAudioWorkletNode = getNativeAudioNode<T, TNativeAudioWorkletNode>(proxy);\n\n return getValueForKey(nodeToProcessorMap, nativeAudioWorkletNode);\n};\n","import { copyFromChannel } from '../helpers/copy-from-channel';\nimport { copyToChannel } from '../helpers/copy-to-channel';\nimport { createNestedArrays } from '../helpers/create-nested-arrays';\nimport { getAudioNodeConnections } from '../helpers/get-audio-node-connections';\nimport { getAudioWorkletProcessor } from '../helpers/get-audio-worklet-processor';\nimport { isOwnedByContext } from '../helpers/is-owned-by-context';\nimport {\n IAudioWorkletNode,\n IAudioWorkletNodeOptions,\n IAudioWorkletProcessorConstructor,\n IMinimalOfflineAudioContext,\n IOfflineAudioContext,\n IReadOnlyMap\n} from '../interfaces';\nimport {\n TAudioWorkletNodeRendererFactoryFactory,\n TExposeCurrentFrameAndCurrentTimeFunction,\n TNativeAudioBuffer,\n TNativeAudioNode,\n TNativeAudioParam,\n TNativeAudioWorkletNode,\n TNativeChannelMergerNode,\n TNativeChannelSplitterNode,\n TNativeGainNode,\n TNativeOfflineAudioContext\n} from '../types';\n\nconst processBuffer = async <T extends IMinimalOfflineAudioContext | IOfflineAudioContext>(\n proxy: IAudioWorkletNode<T>,\n renderedBuffer: null | TNativeAudioBuffer,\n nativeOfflineAudioContext: TNativeOfflineAudioContext,\n options: IAudioWorkletNodeOptions,\n outputChannelCount: number[],\n processorConstructor: undefined | IAudioWorkletProcessorConstructor,\n exposeCurrentFrameAndCurrentTime: TExposeCurrentFrameAndCurrentTimeFunction\n): Promise<null | TNativeAudioBuffer> => {\n // Ceil the length to the next full render quantum.\n // Bug #17: Safari does not yet expose the length.\n const length = renderedBuffer === null ? Math.ceil(proxy.context.length / 128) * 128 : renderedBuffer.length;\n const numberOfInputChannels = options.channelCount * options.numberOfInputs;\n const numberOfOutputChannels = outputChannelCount.reduce((sum, value) => sum + value, 0);\n const processedBuffer =\n numberOfOutputChannels === 0\n ? null\n : nativeOfflineAudioContext.createBuffer(numberOfOutputChannels, length, nativeOfflineAudioContext.sampleRate);\n\n if (processorConstructor === undefined) {\n throw new Error('Missing the processor constructor.');\n }\n\n const audioNodeConnections = getAudioNodeConnections(proxy);\n const audioWorkletProcessor = await getAudioWorkletProcessor(nativeOfflineAudioContext, proxy);\n const inputs = createNestedArrays(options.numberOfInputs, options.channelCount);\n const outputs = createNestedArrays(options.numberOfOutputs, outputChannelCount);\n const parameters: { [name: string]: Float32Array } = Array.from(proxy.parameters.keys()).reduce(\n (prmtrs, name) => ({ ...prmtrs, [name]: new Float32Array(128) }),\n {}\n );\n\n for (let i = 0; i < length; i += 128) {\n if (options.numberOfInputs > 0 && renderedBuffer !== null) {\n for (let j = 0; j < options.numberOfInputs; j += 1) {\n for (let k = 0; k < options.channelCount; k += 1) {\n copyFromChannel(renderedBuffer, inputs[j], k, k, i);\n }\n }\n }\n\n if (processorConstructor.parameterDescriptors !== undefined && renderedBuffer !== null) {\n processorConstructor.parameterDescriptors.forEach(({ name }, index) => {\n copyFromChannel(renderedBuffer, parameters, name, numberOfInputChannels + index, i);\n });\n }\n\n for (let j = 0; j < options.numberOfInputs; j += 1) {\n for (let k = 0; k < outputChannelCount[j]; k += 1) {\n // The byteLength will be 0 when the ArrayBuffer was transferred.\n if (outputs[j][k].byteLength === 0) {\n outputs[j][k] = new Float32Array(128);\n }\n }\n }\n\n try {\n const potentiallyEmptyInputs = inputs.map((input, index) => {\n if (audioNodeConnections.activeInputs[index].size === 0) {\n return [];\n }\n\n return input;\n });\n const activeSourceFlag = exposeCurrentFrameAndCurrentTime(\n i / nativeOfflineAudioContext.sampleRate,\n nativeOfflineAudioContext.sampleRate,\n () => audioWorkletProcessor.process(potentiallyEmptyInputs, outputs, parameters)\n );\n\n if (processedBuffer !== null) {\n for (let j = 0, outputChannelSplitterNodeOutput = 0; j < options.numberOfOutputs; j += 1) {\n for (let k = 0; k < outputChannelCount[j]; k += 1) {\n copyToChannel(processedBuffer, outputs[j], k, outputChannelSplitterNodeOutput + k, i);\n }\n\n outputChannelSplitterNodeOutput += outputChannelCount[j];\n }\n }\n\n if (!activeSourceFlag) {\n break;\n }\n } catch (error) {\n proxy.dispatchEvent(\n new ErrorEvent('processorerror', {\n colno: error.colno,\n filename: error.filename,\n lineno: error.lineno,\n message: error.message\n })\n );\n\n break;\n }\n }\n\n return processedBuffer;\n};\n\nexport const createAudioWorkletNodeRendererFactory: TAudioWorkletNodeRendererFactoryFactory = (\n connectAudioParam,\n connectMultipleOutputs,\n createNativeAudioBufferSourceNode,\n createNativeChannelMergerNode,\n createNativeChannelSplitterNode,\n createNativeConstantSourceNode,\n createNativeGainNode,\n deleteUnrenderedAudioWorkletNode,\n disconnectMultipleOutputs,\n exposeCurrentFrameAndCurrentTime,\n getNativeAudioNode,\n nativeAudioWorkletNodeConstructor,\n nativeOfflineAudioContextConstructor,\n renderAutomation,\n renderInputsOfAudioNode,\n renderNativeOfflineAudioContext\n) => {\n return <T extends IMinimalOfflineAudioContext | IOfflineAudioContext>(\n name: string,\n options: IAudioWorkletNodeOptions,\n processorConstructor: undefined | IAudioWorkletProcessorConstructor\n ) => {\n const renderedNativeAudioNodes = new WeakMap<TNativeOfflineAudioContext, TNativeAudioWorkletNode | TNativeGainNode>();\n\n let processedBufferPromise: null | Promise<null | TNativeAudioBuffer> = null;\n\n const createAudioNode = async (proxy: IAudioWorkletNode<T>, nativeOfflineAudioContext: TNativeOfflineAudioContext) => {\n let nativeAudioWorkletNode = getNativeAudioNode<T, TNativeAudioWorkletNode>(proxy);\n let nativeOutputNodes: null | [TNativeChannelSplitterNode, TNativeChannelMergerNode[], TNativeGainNode] = null;\n\n const nativeAudioWorkletNodeIsOwnedByContext = isOwnedByContext(nativeAudioWorkletNode, nativeOfflineAudioContext);\n const outputChannelCount = Array.isArray(options.outputChannelCount)\n ? options.outputChannelCount\n : Array.from(options.outputChannelCount);\n\n // Bug #61: Only Chrome, Edge & Firefox have an implementation of the AudioWorkletNode yet.\n if (nativeAudioWorkletNodeConstructor === null) {\n const numberOfOutputChannels = outputChannelCount.reduce((sum, value) => sum + value, 0);\n const outputChannelSplitterNode = createNativeChannelSplitterNode(nativeOfflineAudioContext, {\n channelCount: Math.max(1, numberOfOutputChannels),\n channelCountMode: 'explicit',\n channelInterpretation: 'discrete',\n numberOfOutputs: Math.max(1, numberOfOutputChannels)\n });\n const outputChannelMergerNodes: TNativeChannelMergerNode[] = [];\n\n for (let i = 0; i < proxy.numberOfOutputs; i += 1) {\n outputChannelMergerNodes.push(\n createNativeChannelMergerNode(nativeOfflineAudioContext, {\n channelCount: 1,\n channelCountMode: 'explicit',\n channelInterpretation: 'speakers',\n numberOfInputs: outputChannelCount[i]\n })\n );\n }\n\n const outputGainNode = createNativeGainNode(nativeOfflineAudioContext, {\n channelCount: options.channelCount,\n channelCountMode: options.channelCountMode,\n channelInterpretation: options.channelInterpretation,\n gain: 1\n });\n\n outputGainNode.connect = <TNativeAudioNode['connect']>connectMultipleOutputs.bind(null, outputChannelMergerNodes);\n outputGainNode.disconnect = <TNativeAudioNode['disconnect']>disconnectMultipleOutputs.bind(null, outputChannelMergerNodes);\n\n nativeOutputNodes = [outputChannelSplitterNode, outputChannelMergerNodes, outputGainNode];\n } else if (!nativeAudioWorkletNodeIsOwnedByContext) {\n nativeAudioWorkletNode = new nativeAudioWorkletNodeConstructor(nativeOfflineAudioContext, name);\n }\n\n renderedNativeAudioNodes.set(\n nativeOfflineAudioContext,\n nativeOutputNodes === null ? nativeAudioWorkletNode : nativeOutputNodes[2]\n );\n\n if (nativeOutputNodes !== null) {\n if (processedBufferPromise === null) {\n if (processorConstructor === undefined) {\n throw new Error('Missing the processor constructor.');\n }\n\n if (nativeOfflineAudioContextConstructor === null) {\n throw new Error('Missing the native OfflineAudioContext constructor.');\n }\n\n // Bug #47: The AudioDestinationNode in Safari gets not initialized correctly.\n const numberOfInputChannels = proxy.channelCount * proxy.numberOfInputs;\n const numberOfParameters =\n processorConstructor.parameterDescriptors === undefined ? 0 : processorConstructor.parameterDescriptors.length;\n const numberOfChannels = numberOfInputChannels + numberOfParameters;\n\n const renderBuffer = async () => {\n const partialOfflineAudioContext = new nativeOfflineAudioContextConstructor(\n numberOfChannels,\n // Ceil the length to the next full render quantum.\n // Bug #17: Safari does not yet expose the length.\n Math.ceil(proxy.context.length / 128) * 128,\n nativeOfflineAudioContext.sampleRate\n );\n const gainNodes: TNativeGainNode[] = [];\n const inputChannelSplitterNodes = [];\n\n for (let i = 0; i < options.numberOfInputs; i += 1) {\n gainNodes.push(\n createNativeGainNode(partialOfflineAudioContext, {\n channelCount: options.channelCount,\n channelCountMode: options.channelCountMode,\n channelInterpretation: options.channelInterpretation,\n gain: 1\n })\n );\n inputChannelSplitterNodes.push(\n createNativeChannelSplitterNode(partialOfflineAudioContext, {\n channelCount: options.channelCount,\n channelCountMode: 'explicit',\n channelInterpretation: 'discrete',\n numberOfOutputs: options.channelCount\n })\n );\n }\n\n const constantSourceNodes = await Promise.all(\n Array.from(proxy.parameters.values()).map(async (audioParam) => {\n const constantSourceNode = createNativeConstantSourceNode(partialOfflineAudioContext, {\n channelCount: 1,\n channelCountMode: 'explicit',\n channelInterpretation: 'discrete',\n offset: audioParam.value\n });\n\n await renderAutomation(partialOfflineAudioContext, audioParam, constantSourceNode.offset);\n\n return constantSourceNode;\n })\n );\n\n const inputChannelMergerNode = createNativeChannelMergerNode(partialOfflineAudioContext, {\n channelCount: 1,\n channelCountMode: 'explicit',\n channelInterpretation: 'speakers',\n numberOfInputs: Math.max(1, numberOfInputChannels + numberOfParameters)\n });\n\n for (let i = 0; i < options.numberOfInputs; i += 1) {\n gainNodes[i].connect(inputChannelSplitterNodes[i]);\n\n for (let j = 0; j < options.channelCount; j += 1) {\n inputChannelSplitterNodes[i].connect(inputChannelMergerNode, j, i * options.channelCount + j);\n }\n }\n\n for (const [index, constantSourceNode] of constantSourceNodes.entries()) {\n constantSourceNode.connect(inputChannelMergerNode, 0, numberOfInputChannels + index);\n constantSourceNode.start(0);\n }\n\n inputChannelMergerNode.connect(partialOfflineAudioContext.destination);\n\n await Promise.all(\n gainNodes.map((gainNode) => renderInputsOfAudioNode(proxy, partialOfflineAudioContext, gainNode))\n );\n\n return renderNativeOfflineAudioContext(partialOfflineAudioContext);\n };\n\n processedBufferPromise = processBuffer(\n proxy,\n numberOfChannels === 0 ? null : await renderBuffer(),\n nativeOfflineAudioContext,\n options,\n outputChannelCount,\n processorConstructor,\n exposeCurrentFrameAndCurrentTime\n );\n }\n\n const processedBuffer = await processedBufferPromise;\n const audioBufferSourceNode = createNativeAudioBufferSourceNode(nativeOfflineAudioContext, {\n buffer: null,\n channelCount: 2,\n channelCountMode: 'max',\n channelInterpretation: 'speakers',\n loop: false,\n loopEnd: 0,\n loopStart: 0,\n playbackRate: 1\n });\n const [outputChannelSplitterNode, outputChannelMergerNodes, outputGainNode] = nativeOutputNodes;\n\n if (processedBuffer !== null) {\n audioBufferSourceNode.buffer = processedBuffer;\n audioBufferSourceNode.start(0);\n }\n\n audioBufferSourceNode.connect(outputChannelSplitterNode);\n\n for (let i = 0, outputChannelSplitterNodeOutput = 0; i < proxy.numberOfOutputs; i += 1) {\n const outputChannelMergerNode = outputChannelMergerNodes[i];\n\n for (let j = 0; j < outputChannelCount[i]; j += 1) {\n outputChannelSplitterNode.connect(outputChannelMergerNode, outputChannelSplitterNodeOutput + j, j);\n }\n\n outputChannelSplitterNodeOutput += outputChannelCount[i];\n }\n\n return outputGainNode;\n }\n\n if (!nativeAudioWorkletNodeIsOwnedByContext) {\n for (const [nm, audioParam] of proxy.parameters.entries()) {\n await renderAutomation(\n nativeOfflineAudioContext,\n audioParam,\n // @todo The definition that TypeScript uses of the AudioParamMap is lacking many methods.\n <TNativeAudioParam>(<IReadOnlyMap<string, TNativeAudioParam>>nativeAudioWorkletNode.parameters).get(nm)\n );\n }\n } else {\n for (const [nm, audioParam] of proxy.parameters.entries()) {\n await connectAudioParam(\n nativeOfflineAudioContext,\n audioParam,\n // @todo The definition that TypeScript uses of the AudioParamMap is lacking many methods.\n <TNativeAudioParam>(<IReadOnlyMap<string, TNativeAudioParam>>nativeAudioWorkletNode.parameters).get(nm)\n );\n }\n }\n\n await renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeAudioWorkletNode);\n\n return nativeAudioWorkletNode;\n };\n\n return {\n render(\n proxy: IAudioWorkletNode<T>,\n nativeOfflineAudioContext: TNativeOfflineAudioContext\n ): Promise<TNativeAudioWorkletNode | TNativeGainNode> {\n deleteUnrenderedAudioWorkletNode(nativeOfflineAudioContext, proxy);\n\n const renderedNativeAudioWorkletNodeOrGainNode = renderedNativeAudioNodes.get(nativeOfflineAudioContext);\n\n if (renderedNativeAudioWorkletNodeOrGainNode !== undefined) {\n return Promise.resolve(renderedNativeAudioWorkletNodeOrGainNode);\n }\n\n return createAudioNode(proxy, nativeOfflineAudioContext);\n }\n };\n };\n};\n","import {\n IAnalyserNode,\n IAudioBuffer,\n IAudioBufferSourceNode,\n IAudioNode,\n IAudioWorklet,\n IBaseAudioContext,\n IBiquadFilterNode,\n IConstantSourceNode,\n IConvolverNode,\n IDelayNode,\n IDynamicsCompressorNode,\n IGainNode,\n IIIRFilterNode,\n IOscillatorNode,\n IPannerNode,\n IPeriodicWave,\n IPeriodicWaveConstraints,\n IStereoPannerNode,\n IWaveShaperNode,\n IWorkletOptions\n} from '../interfaces';\nimport { TBaseAudioContextConstructorFactory, TContext, TDecodeErrorCallback, TDecodeSuccessCallback, TNativeContext } from '../types';\n\nexport const createBaseAudioContextConstructor: TBaseAudioContextConstructorFactory = (\n addAudioWorkletModule,\n analyserNodeConstructor,\n audioBufferConstructor,\n audioBufferSourceNodeConstructor,\n biquadFilterNodeConstructor,\n channelMergerNodeConstructor,\n channelSplitterNodeConstructor,\n constantSourceNodeConstructor,\n convolverNodeConstructor,\n decodeAudioData,\n delayNodeConstructor,\n dynamicsCompressorNodeConstructor,\n gainNodeConstructor,\n iIRFilterNodeConstructor,\n minimalBaseAudioContextConstructor,\n oscillatorNodeConstructor,\n pannerNodeConstructor,\n periodicWaveConstructor,\n stereoPannerNodeConstructor,\n waveShaperNodeConstructor\n) => {\n return class BaseAudioContext<T extends TContext> extends minimalBaseAudioContextConstructor<T> implements IBaseAudioContext<T> {\n private _audioWorklet: undefined | IAudioWorklet;\n\n constructor(private _nativeContext: TNativeContext, numberOfChannels: number) {\n super(_nativeContext, numberOfChannels);\n\n this._audioWorklet =\n addAudioWorkletModule === undefined\n ? undefined\n : {\n addModule: (moduleURL: string, options?: IWorkletOptions) => {\n return addAudioWorkletModule(<T>(<unknown>this), moduleURL, options);\n }\n };\n }\n\n get audioWorklet(): undefined | IAudioWorklet {\n return this._audioWorklet;\n }\n\n public createAnalyser(): IAnalyserNode<T> {\n return new analyserNodeConstructor(<T>(<unknown>this));\n }\n\n public createBiquadFilter(): IBiquadFilterNode<T> {\n return new biquadFilterNodeConstructor(<T>(<unknown>this));\n }\n\n public createBuffer(numberOfChannels: number, length: number, sampleRate: number): IAudioBuffer {\n return new audioBufferConstructor({ length, numberOfChannels, sampleRate });\n }\n\n public createBufferSource(): IAudioBufferSourceNode<T> {\n return new audioBufferSourceNodeConstructor(<T>(<unknown>this));\n }\n\n public createChannelMerger(numberOfInputs = 6): IAudioNode<T> {\n return new channelMergerNodeConstructor(<T>(<unknown>this), { numberOfInputs });\n }\n\n public createChannelSplitter(numberOfOutputs = 6): IAudioNode<T> {\n return new channelSplitterNodeConstructor(<T>(<unknown>this), { numberOfOutputs });\n }\n\n public createConstantSource(): IConstantSourceNode<T> {\n return new constantSourceNodeConstructor(<T>(<unknown>this));\n }\n\n public createConvolver(): IConvolverNode<T> {\n return new convolverNodeConstructor(<T>(<unknown>this));\n }\n\n public createDelay(maxDelayTime = 1): IDelayNode<T> {\n return new delayNodeConstructor(<T>(<unknown>this), { maxDelayTime });\n }\n\n public createDynamicsCompressor(): IDynamicsCompressorNode<T> {\n return new dynamicsCompressorNodeConstructor(<T>(<unknown>this));\n }\n\n public createGain(): IGainNode<T> {\n return new gainNodeConstructor(<T>(<unknown>this));\n }\n\n public createIIRFilter(feedforward: Iterable<number>, feedback: Iterable<number>): IIIRFilterNode<T> {\n return new iIRFilterNodeConstructor(<T>(<unknown>this), { feedback, feedforward });\n }\n\n public createOscillator(): IOscillatorNode<T> {\n return new oscillatorNodeConstructor(<T>(<unknown>this));\n }\n\n public createPanner(): IPannerNode<T> {\n return new pannerNodeConstructor(<T>(<unknown>this));\n }\n\n public createPeriodicWave(\n real: Iterable<number>,\n imag: Iterable<number>,\n constraints: Partial<IPeriodicWaveConstraints> = { disableNormalization: false }\n ): IPeriodicWave {\n return new periodicWaveConstructor(<T>(<unknown>this), { ...constraints, imag, real });\n }\n\n public createStereoPanner(): IStereoPannerNode<T> {\n return new stereoPannerNodeConstructor(<T>(<unknown>this));\n }\n\n public createWaveShaper(): IWaveShaperNode<T> {\n return new waveShaperNodeConstructor(<T>(<unknown>this));\n }\n\n public decodeAudioData(\n audioData: ArrayBuffer,\n successCallback?: TDecodeSuccessCallback,\n errorCallback?: TDecodeErrorCallback\n ): Promise<IAudioBuffer> {\n return decodeAudioData(this._nativeContext, audioData).then(\n (audioBuffer) => {\n if (typeof successCallback === 'function') {\n successCallback(audioBuffer);\n }\n\n return audioBuffer;\n },\n (err) => {\n if (typeof errorCallback === 'function') {\n errorCallback(err);\n }\n\n throw err;\n }\n );\n }\n };\n};\n","import { MOST_NEGATIVE_SINGLE_FLOAT, MOST_POSITIVE_SINGLE_FLOAT } from '../constants';\nimport { IAudioParam, IBiquadFilterNode, IBiquadFilterOptions } from '../interfaces';\nimport { TAudioNodeRenderer, TBiquadFilterNodeConstructorFactory, TBiquadFilterType, TContext, TNativeBiquadFilterNode } from '../types';\n\nconst DEFAULT_OPTIONS = {\n Q: 1,\n channelCount: 2,\n channelCountMode: 'max',\n channelInterpretation: 'speakers',\n detune: 0,\n frequency: 350,\n gain: 0,\n type: 'lowpass'\n} as const;\n\nexport const createBiquadFilterNodeConstructor: TBiquadFilterNodeConstructorFactory = (\n audioNodeConstructor,\n createAudioParam,\n createBiquadFilterNodeRenderer,\n createInvalidAccessError,\n createNativeBiquadFilterNode,\n getNativeContext,\n isNativeOfflineAudioContext,\n setAudioNodeTailTime\n) => {\n return class BiquadFilterNode<T extends TContext> extends audioNodeConstructor<T> implements IBiquadFilterNode<T> {\n private _detune: IAudioParam;\n\n private _frequency: IAudioParam;\n\n private _gain: IAudioParam;\n\n private _nativeBiquadFilterNode: TNativeBiquadFilterNode;\n\n private _Q: IAudioParam;\n\n constructor(context: T, options?: Partial<IBiquadFilterOptions>) {\n const nativeContext = getNativeContext(context);\n const mergedOptions = { ...DEFAULT_OPTIONS, ...options };\n const nativeBiquadFilterNode = createNativeBiquadFilterNode(nativeContext, mergedOptions);\n const isOffline = isNativeOfflineAudioContext(nativeContext);\n const biquadFilterNodeRenderer = <TAudioNodeRenderer<T, this>>(isOffline ? createBiquadFilterNodeRenderer() : null);\n\n super(context, false, nativeBiquadFilterNode, biquadFilterNodeRenderer);\n\n // Bug #80: Safari does not export the correct values for maxValue and minValue.\n this._Q = createAudioParam(this, isOffline, nativeBiquadFilterNode.Q, MOST_POSITIVE_SINGLE_FLOAT, MOST_NEGATIVE_SINGLE_FLOAT);\n // Bug #78: Firefox & Safari do not export the correct values for maxValue and minValue.\n this._detune = createAudioParam(\n this,\n isOffline,\n nativeBiquadFilterNode.detune,\n 1200 * Math.log2(MOST_POSITIVE_SINGLE_FLOAT),\n -1200 * Math.log2(MOST_POSITIVE_SINGLE_FLOAT)\n );\n // Bug #77: Firefox & Safari do not export the correct value for minValue.\n this._frequency = createAudioParam(this, isOffline, nativeBiquadFilterNode.frequency, context.sampleRate / 2, 0);\n // Bug #79: Firefox & Safari do not export the correct values for maxValue and minValue.\n this._gain = createAudioParam(\n this,\n isOffline,\n nativeBiquadFilterNode.gain,\n 40 * Math.log10(MOST_POSITIVE_SINGLE_FLOAT),\n MOST_NEGATIVE_SINGLE_FLOAT\n );\n this._nativeBiquadFilterNode = nativeBiquadFilterNode;\n\n // @todo Determine a meaningful tail-time instead of just using one second.\n setAudioNodeTailTime(this, 1);\n }\n\n get detune(): IAudioParam {\n return this._detune;\n }\n\n get frequency(): IAudioParam {\n return this._frequency;\n }\n\n get gain(): IAudioParam {\n return this._gain;\n }\n\n get Q(): IAudioParam {\n return this._Q;\n }\n\n get type(): TBiquadFilterType {\n return this._nativeBiquadFilterNode.type;\n }\n\n set type(value) {\n this._nativeBiquadFilterNode.type = value;\n }\n\n public getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void {\n // Bug #189: Safari does throw an InvalidStateError.\n try {\n this._nativeBiquadFilterNode.getFrequencyResponse(frequencyHz, magResponse, phaseResponse);\n } catch (err) {\n if (err.code === 11) {\n throw createInvalidAccessError();\n }\n\n throw err;\n }\n\n // Bug #68: Safari does not throw an error if the parameters differ in their length.\n if (frequencyHz.length !== magResponse.length || magResponse.length !== phaseResponse.length) {\n throw createInvalidAccessError();\n }\n }\n };\n};\n","import { isOwnedByContext } from '../helpers/is-owned-by-context';\nimport { IBiquadFilterNode, IMinimalOfflineAudioContext, IOfflineAudioContext } from '../interfaces';\nimport { TBiquadFilterNodeRendererFactoryFactory, TNativeBiquadFilterNode, TNativeOfflineAudioContext } from '../types';\n\nexport const createBiquadFilterNodeRendererFactory: TBiquadFilterNodeRendererFactoryFactory = (\n connectAudioParam,\n createNativeBiquadFilterNode,\n getNativeAudioNode,\n renderAutomation,\n renderInputsOfAudioNode\n) => {\n return <T extends IMinimalOfflineAudioContext | IOfflineAudioContext>() => {\n const renderedNativeBiquadFilterNodes = new WeakMap<TNativeOfflineAudioContext, TNativeBiquadFilterNode>();\n\n const createBiquadFilterNode = async (proxy: IBiquadFilterNode<T>, nativeOfflineAudioContext: TNativeOfflineAudioContext) => {\n let nativeBiquadFilterNode = getNativeAudioNode<T, TNativeBiquadFilterNode>(proxy);\n\n /*\n * If the initially used nativeBiquadFilterNode was not constructed on the same OfflineAudioContext it needs to be created\n * again.\n */\n const nativeBiquadFilterNodeIsOwnedByContext = isOwnedByContext(nativeBiquadFilterNode, nativeOfflineAudioContext);\n\n if (!nativeBiquadFilterNodeIsOwnedByContext) {\n const options = {\n Q: nativeBiquadFilterNode.Q.value,\n channelCount: nativeBiquadFilterNode.channelCount,\n channelCountMode: nativeBiquadFilterNode.channelCountMode,\n channelInterpretation: nativeBiquadFilterNode.channelInterpretation,\n detune: nativeBiquadFilterNode.detune.value,\n frequency: nativeBiquadFilterNode.frequency.value,\n gain: nativeBiquadFilterNode.gain.value,\n type: nativeBiquadFilterNode.type\n };\n\n nativeBiquadFilterNode = createNativeBiquadFilterNode(nativeOfflineAudioContext, options);\n }\n\n renderedNativeBiquadFilterNodes.set(nativeOfflineAudioContext, nativeBiquadFilterNode);\n\n if (!nativeBiquadFilterNodeIsOwnedByContext) {\n await renderAutomation(nativeOfflineAudioContext, proxy.Q, nativeBiquadFilterNode.Q);\n await renderAutomation(nativeOfflineAudioContext, proxy.detune, nativeBiquadFilterNode.detune);\n await renderAutomation(nativeOfflineAudioContext, proxy.frequency, nativeBiquadFilterNode.frequency);\n await renderAutomation(nativeOfflineAudioContext, proxy.gain, nativeBiquadFilterNode.gain);\n } else {\n await connectAudioParam(nativeOfflineAudioContext, proxy.Q, nativeBiquadFilterNode.Q);\n await connectAudioParam(nativeOfflineAudioContext, proxy.detune, nativeBiquadFilterNode.detune);\n await connectAudioParam(nativeOfflineAudioContext, proxy.frequency, nativeBiquadFilterNode.frequency);\n await connectAudioParam(nativeOfflineAudioContext, proxy.gain, nativeBiquadFilterNode.gain);\n }\n\n await renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeBiquadFilterNode);\n\n return nativeBiquadFilterNode;\n };\n\n return {\n render(proxy: IBiquadFilterNode<T>, nativeOfflineAudioContext: TNativeOfflineAudioContext): Promise<TNativeBiquadFilterNode> {\n const renderedNativeBiquadFilterNode = renderedNativeBiquadFilterNodes.get(nativeOfflineAudioContext);\n\n if (renderedNativeBiquadFilterNode !== undefined) {\n return Promise.resolve(renderedNativeBiquadFilterNode);\n }\n\n return createBiquadFilterNode(proxy, nativeOfflineAudioContext);\n }\n };\n };\n};\n","import { TCacheTestResultFactory } from '../types';\n\nexport const createCacheTestResult: TCacheTestResultFactory = (ongoingTests, testResults) => {\n return (tester, test) => {\n const cachedTestResult = testResults.get(tester);\n\n if (cachedTestResult !== undefined) {\n return cachedTestResult;\n }\n\n const ongoingTest = ongoingTests.get(tester);\n\n if (ongoingTest !== undefined) {\n return ongoingTest;\n }\n\n try {\n const synchronousTestResult = test();\n\n if (synchronousTestResult instanceof Promise) {\n ongoingTests.set(tester, synchronousTestResult);\n\n return synchronousTestResult\n .catch(() => false)\n .then((finalTestResult) => {\n ongoingTests.delete(tester);\n testResults.set(tester, finalTestResult);\n\n return finalTestResult;\n });\n }\n\n testResults.set(tester, synchronousTestResult);\n\n return synchronousTestResult;\n } catch {\n testResults.set(tester, false);\n\n return false;\n }\n };\n};\n","import { IChannelMergerOptions } from '../interfaces';\nimport { TAudioNodeRenderer, TChannelMergerNodeConstructorFactory, TContext } from '../types';\n\nconst DEFAULT_OPTIONS = {\n channelCount: 1,\n channelCountMode: 'explicit',\n channelInterpretation: 'speakers',\n numberOfInputs: 6\n} as const;\n\nexport const createChannelMergerNodeConstructor: TChannelMergerNodeConstructorFactory = (\n audioNodeConstructor,\n createChannelMergerNodeRenderer,\n createNativeChannelMergerNode,\n getNativeContext,\n isNativeOfflineAudioContext\n) => {\n return class ChannelMergerNode<T extends TContext> extends audioNodeConstructor<T> {\n constructor(context: T, options?: Partial<IChannelMergerOptions>) {\n const nativeContext = getNativeContext(context);\n const mergedOptions = { ...DEFAULT_OPTIONS, ...options };\n const nativeChannelMergerNode = createNativeChannelMergerNode(nativeContext, mergedOptions);\n const channelMergerNodeRenderer = <TAudioNodeRenderer<T, this>>(\n (isNativeOfflineAudioContext(nativeContext) ? createChannelMergerNodeRenderer() : null)\n );\n\n super(context, false, nativeChannelMergerNode, channelMergerNodeRenderer);\n }\n };\n};\n","import { isOwnedByContext } from '../helpers/is-owned-by-context';\nimport { IAudioNode, IMinimalOfflineAudioContext, IOfflineAudioContext } from '../interfaces';\nimport { TChannelMergerNodeRendererFactoryFactory, TNativeAudioNode, TNativeOfflineAudioContext } from '../types';\n\nexport const createChannelMergerNodeRendererFactory: TChannelMergerNodeRendererFactoryFactory = (\n createNativeChannelMergerNode,\n getNativeAudioNode,\n renderInputsOfAudioNode\n) => {\n return <T extends IMinimalOfflineAudioContext | IOfflineAudioContext>() => {\n const renderedNativeAudioNodes = new WeakMap<TNativeOfflineAudioContext, TNativeAudioNode>();\n\n const createAudioNode = async (proxy: IAudioNode<T>, nativeOfflineAudioContext: TNativeOfflineAudioContext) => {\n let nativeAudioNode = getNativeAudioNode<T, TNativeAudioNode>(proxy);\n\n // If the initially used nativeAudioNode was not constructed on the same OfflineAudioContext it needs to be created again.\n const nativeAudioNodeIsOwnedByContext = isOwnedByContext(nativeAudioNode, nativeOfflineAudioContext);\n\n if (!nativeAudioNodeIsOwnedByContext) {\n const options = {\n channelCount: nativeAudioNode.channelCount,\n channelCountMode: nativeAudioNode.channelCountMode,\n channelInterpretation: nativeAudioNode.channelInterpretation,\n numberOfInputs: nativeAudioNode.numberOfInputs\n };\n\n nativeAudioNode = createNativeChannelMergerNode(nativeOfflineAudioContext, options);\n }\n\n renderedNativeAudioNodes.set(nativeOfflineAudioContext, nativeAudioNode);\n\n await renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeAudioNode);\n\n return nativeAudioNode;\n };\n\n return {\n render(proxy: IAudioNode<T>, nativeOfflineAudioContext: TNativeOfflineAudioContext): Promise<TNativeAudioNode> {\n const renderedNativeAudioNode = renderedNativeAudioNodes.get(nativeOfflineAudioContext);\n\n if (renderedNativeAudioNode !== undefined) {\n return Promise.resolve(renderedNativeAudioNode);\n }\n\n return createAudioNode(proxy, nativeOfflineAudioContext);\n }\n };\n };\n};\n","import { IChannelSplitterOptions } from '../interfaces';\nimport { TAudioNodeRenderer, TChannelSplitterNodeConstructorFactory, TContext } from '../types';\n\nconst DEFAULT_OPTIONS = {\n channelCount: 6,\n channelCountMode: 'explicit',\n channelInterpretation: 'discrete',\n numberOfOutputs: 6\n} as const;\n\nexport const createChannelSplitterNodeConstructor: TChannelSplitterNodeConstructorFactory = (\n audioNodeConstructor,\n createChannelSplitterNodeRenderer,\n createNativeChannelSplitterNode,\n getNativeContext,\n isNativeOfflineAudioContext,\n sanitizeChannelSplitterOptions\n) => {\n return class ChannelSplitterNode<T extends TContext> extends audioNodeConstructor<T> {\n constructor(context: T, options?: Partial<IChannelSplitterOptions>) {\n const nativeContext = getNativeContext(context);\n const mergedOptions = sanitizeChannelSplitterOptions({ ...DEFAULT_OPTIONS, ...options });\n const nativeChannelSplitterNode = createNativeChannelSplitterNode(nativeContext, mergedOptions);\n const channelSplitterNodeRenderer = <TAudioNodeRenderer<T, this>>(\n (isNativeOfflineAudioContext(nativeContext) ? createChannelSplitterNodeRenderer() : null)\n );\n\n super(context, false, nativeChannelSplitterNode, channelSplitterNodeRenderer);\n }\n };\n};\n","import { isOwnedByContext } from '../helpers/is-owned-by-context';\nimport { IAudioNode, IMinimalOfflineAudioContext, IOfflineAudioContext } from '../interfaces';\nimport { TChannelSplitterNodeRendererFactoryFactory, TNativeAudioNode, TNativeOfflineAudioContext } from '../types';\n\nexport const createChannelSplitterNodeRendererFactory: TChannelSplitterNodeRendererFactoryFactory = (\n createNativeChannelSplitterNode,\n getNativeAudioNode,\n renderInputsOfAudioNode\n) => {\n return <T extends IMinimalOfflineAudioContext | IOfflineAudioContext>() => {\n const renderedNativeAudioNodes = new WeakMap<TNativeOfflineAudioContext, TNativeAudioNode>();\n\n const createAudioNode = async (proxy: IAudioNode<T>, nativeOfflineAudioContext: TNativeOfflineAudioContext) => {\n let nativeAudioNode = getNativeAudioNode<T, TNativeAudioNode>(proxy);\n\n // If the initially used nativeAudioNode was not constructed on the same OfflineAudioContext it needs to be created again.\n const nativeAudioNodeIsOwnedByContext = isOwnedByContext(nativeAudioNode, nativeOfflineAudioContext);\n\n if (!nativeAudioNodeIsOwnedByContext) {\n const options = {\n channelCount: nativeAudioNode.channelCount,\n channelCountMode: nativeAudioNode.channelCountMode,\n channelInterpretation: nativeAudioNode.channelInterpretation,\n numberOfOutputs: nativeAudioNode.numberOfOutputs\n };\n\n nativeAudioNode = createNativeChannelSplitterNode(nativeOfflineAudioContext, options);\n }\n\n renderedNativeAudioNodes.set(nativeOfflineAudioContext, nativeAudioNode);\n\n await renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeAudioNode);\n\n return nativeAudioNode;\n };\n\n return {\n render(proxy: IAudioNode<T>, nativeOfflineAudioContext: TNativeOfflineAudioContext): Promise<TNativeAudioNode> {\n const renderedNativeAudioNode = renderedNativeAudioNodes.get(nativeOfflineAudioContext);\n\n if (renderedNativeAudioNode !== undefined) {\n return Promise.resolve(renderedNativeAudioNode);\n }\n\n return createAudioNode(proxy, nativeOfflineAudioContext);\n }\n };\n };\n};\n","import { TConnectAudioParamFactory } from '../types';\n\nexport const createConnectAudioParam: TConnectAudioParamFactory = (renderInputsOfAudioParam) => {\n return (nativeOfflineAudioContext, audioParam, nativeAudioParam) => {\n return renderInputsOfAudioParam(audioParam, nativeOfflineAudioContext, nativeAudioParam);\n };\n};\n","import { isNativeAudioNode } from '../guards/native-audio-node';\nimport { TConnectMultipleOutputsFactory } from '../types';\n\nexport const createConnectMultipleOutputs: TConnectMultipleOutputsFactory = (createIndexSizeError) => {\n return (outputAudioNodes, destination, output = 0, input = 0) => {\n const outputAudioNode = outputAudioNodes[output];\n\n if (outputAudioNode === undefined) {\n throw createIndexSizeError();\n }\n\n if (isNativeAudioNode(destination)) {\n return outputAudioNode.connect(destination, 0, input);\n }\n\n return outputAudioNode.connect(destination, 0);\n };\n};\n","import { TConnectedNativeAudioBufferSourceNodeFactoryFactory } from '../types';\n\nexport const createConnectedNativeAudioBufferSourceNodeFactory: TConnectedNativeAudioBufferSourceNodeFactoryFactory = (\n createNativeAudioBufferSourceNode\n) => {\n return (nativeContext, nativeAudioNode) => {\n const nativeAudioBufferSourceNode = createNativeAudioBufferSourceNode(nativeContext, {\n buffer: null,\n channelCount: 2,\n channelCountMode: 'max',\n channelInterpretation: 'speakers',\n loop: false,\n loopEnd: 0,\n loopStart: 0,\n playbackRate: 1\n });\n const nativeAudioBuffer = nativeContext.createBuffer(1, 2, 44100);\n\n nativeAudioBufferSourceNode.buffer = nativeAudioBuffer;\n nativeAudioBufferSourceNode.loop = true;\n\n nativeAudioBufferSourceNode.connect(nativeAudioNode);\n nativeAudioBufferSourceNode.start();\n\n return () => {\n nativeAudioBufferSourceNode.stop();\n nativeAudioBufferSourceNode.disconnect(nativeAudioNode);\n };\n };\n};\n","import { MOST_NEGATIVE_SINGLE_FLOAT, MOST_POSITIVE_SINGLE_FLOAT } from '../constants';\nimport { isActiveAudioNode } from '../helpers/is-active-audio-node';\nimport { setInternalStateToActive } from '../helpers/set-internal-state-to-active';\nimport { setInternalStateToPassive } from '../helpers/set-internal-state-to-passive';\nimport { IAudioParam, IAudioScheduledSourceNodeEventMap, IConstantSourceNode, IConstantSourceOptions } from '../interfaces';\nimport {\n TConstantSourceNodeConstructorFactory,\n TConstantSourceNodeRenderer,\n TContext,\n TEventHandler,\n TNativeConstantSourceNode\n} from '../types';\n\nconst DEFAULT_OPTIONS = {\n channelCount: 2,\n channelCountMode: 'max',\n channelInterpretation: 'speakers',\n offset: 1\n} as const;\n\nexport const createConstantSourceNodeConstructor: TConstantSourceNodeConstructorFactory = (\n audioNodeConstructor,\n createAudioParam,\n createConstantSourceNodeRendererFactory,\n createNativeConstantSourceNode,\n getNativeContext,\n isNativeOfflineAudioContext,\n wrapEventListener\n) => {\n return class ConstantSourceNode<T extends TContext>\n extends audioNodeConstructor<T, IAudioScheduledSourceNodeEventMap>\n implements IConstantSourceNode<T>\n {\n private _constantSourceNodeRenderer: TConstantSourceNodeRenderer<T>;\n\n private _nativeConstantSourceNode: TNativeConstantSourceNode;\n\n private _offset: IAudioParam;\n\n private _onended: null | TEventHandler<this>;\n\n constructor(context: T, options?: Partial<IConstantSourceOptions>) {\n const nativeContext = getNativeContext(context);\n const mergedOptions = { ...DEFAULT_OPTIONS, ...options };\n const nativeConstantSourceNode = createNativeConstantSourceNode(nativeContext, mergedOptions);\n const isOffline = isNativeOfflineAudioContext(nativeContext);\n const constantSourceNodeRenderer = <TConstantSourceNodeRenderer<T>>(\n (isOffline ? createConstantSourceNodeRendererFactory() : null)\n );\n\n super(context, false, nativeConstantSourceNode, constantSourceNodeRenderer);\n\n this._constantSourceNodeRenderer = constantSourceNodeRenderer;\n this._nativeConstantSourceNode = nativeConstantSourceNode;\n /*\n * Bug #62 & #74: Safari does not support ConstantSourceNodes and does not export the correct values for maxValue and minValue\n * for GainNodes.\n */\n this._offset = createAudioParam(\n this,\n isOffline,\n nativeConstantSourceNode.offset,\n MOST_POSITIVE_SINGLE_FLOAT,\n MOST_NEGATIVE_SINGLE_FLOAT\n );\n this._onended = null;\n }\n\n get offset(): IAudioParam {\n return this._offset;\n }\n\n get onended(): null | TEventHandler<this> {\n return this._onended;\n }\n\n set onended(value) {\n const wrappedListener = typeof value === 'function' ? wrapEventListener(this, value) : null;\n\n this._nativeConstantSourceNode.onended = wrappedListener;\n\n const nativeOnEnded = this._nativeConstantSourceNode.onended;\n\n this._onended = nativeOnEnded !== null && nativeOnEnded === wrappedListener ? value : nativeOnEnded;\n }\n\n public start(when = 0): void {\n this._nativeConstantSourceNode.start(when);\n\n if (this._constantSourceNodeRenderer !== null) {\n this._constantSourceNodeRenderer.start = when;\n }\n\n if (this.context.state !== 'closed') {\n setInternalStateToActive(this);\n\n const resetInternalStateToPassive = () => {\n this._nativeConstantSourceNode.removeEventListener('ended', resetInternalStateToPassive);\n\n if (isActiveAudioNode(this)) {\n setInternalStateToPassive(this);\n }\n };\n\n this._nativeConstantSourceNode.addEventListener('ended', resetInternalStateToPassive);\n }\n }\n\n public stop(when = 0): void {\n this._nativeConstantSourceNode.stop(when);\n\n if (this._constantSourceNodeRenderer !== null) {\n this._constantSourceNodeRenderer.stop = when;\n }\n }\n };\n};\n","import { isOwnedByContext } from '../helpers/is-owned-by-context';\nimport { IConstantSourceNode, IMinimalOfflineAudioContext, IOfflineAudioContext } from '../interfaces';\nimport { TConstantSourceNodeRendererFactoryFactory, TNativeConstantSourceNode, TNativeOfflineAudioContext } from '../types';\n\nexport const createConstantSourceNodeRendererFactory: TConstantSourceNodeRendererFactoryFactory = (\n connectAudioParam,\n createNativeConstantSourceNode,\n getNativeAudioNode,\n renderAutomation,\n renderInputsOfAudioNode\n) => {\n return <T extends IMinimalOfflineAudioContext | IOfflineAudioContext>() => {\n const renderedNativeConstantSourceNodes = new WeakMap<TNativeOfflineAudioContext, TNativeConstantSourceNode>();\n\n let start: null | number = null;\n let stop: null | number = null;\n\n const createConstantSourceNode = async (proxy: IConstantSourceNode<T>, nativeOfflineAudioContext: TNativeOfflineAudioContext) => {\n let nativeConstantSourceNode = getNativeAudioNode<T, TNativeConstantSourceNode>(proxy);\n\n /*\n * If the initially used nativeConstantSourceNode was not constructed on the same OfflineAudioContext it needs to be created\n * again.\n */\n const nativeConstantSourceNodeIsOwnedByContext = isOwnedByContext(nativeConstantSourceNode, nativeOfflineAudioContext);\n\n if (!nativeConstantSourceNodeIsOwnedByContext) {\n const options = {\n channelCount: nativeConstantSourceNode.channelCount,\n channelCountMode: nativeConstantSourceNode.channelCountMode,\n channelInterpretation: nativeConstantSourceNode.channelInterpretation,\n offset: nativeConstantSourceNode.offset.value\n };\n\n nativeConstantSourceNode = createNativeConstantSourceNode(nativeOfflineAudioContext, options);\n\n if (start !== null) {\n nativeConstantSourceNode.start(start);\n }\n\n if (stop !== null) {\n nativeConstantSourceNode.stop(stop);\n }\n }\n\n renderedNativeConstantSourceNodes.set(nativeOfflineAudioContext, nativeConstantSourceNode);\n\n if (!nativeConstantSourceNodeIsOwnedByContext) {\n await renderAutomation(nativeOfflineAudioContext, proxy.offset, nativeConstantSourceNode.offset);\n } else {\n await connectAudioParam(nativeOfflineAudioContext, proxy.offset, nativeConstantSourceNode.offset);\n }\n\n await renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeConstantSourceNode);\n\n return nativeConstantSourceNode;\n };\n\n return {\n set start(value: number) {\n start = value;\n },\n set stop(value: number) {\n stop = value;\n },\n render(\n proxy: IConstantSourceNode<T>,\n nativeOfflineAudioContext: TNativeOfflineAudioContext\n ): Promise<TNativeConstantSourceNode> {\n const renderedNativeConstantSourceNode = renderedNativeConstantSourceNodes.get(nativeOfflineAudioContext);\n\n if (renderedNativeConstantSourceNode !== undefined) {\n return Promise.resolve(renderedNativeConstantSourceNode);\n }\n\n return createConstantSourceNode(proxy, nativeOfflineAudioContext);\n }\n };\n };\n};\n","import { TConvertNumberToUnsignedLongFactory } from '../types';\n\nexport const createConvertNumberToUnsignedLong: TConvertNumberToUnsignedLongFactory = (unit32Array) => {\n return (value) => {\n unit32Array[0] = value;\n\n return unit32Array[0];\n };\n};\n","import { IConvolverNode, IConvolverOptions } from '../interfaces';\nimport { TAnyAudioBuffer, TAudioNodeRenderer, TContext, TConvolverNodeConstructorFactory, TNativeConvolverNode } from '../types';\n\nconst DEFAULT_OPTIONS = {\n buffer: null,\n channelCount: 2,\n channelCountMode: 'clamped-max',\n channelInterpretation: 'speakers',\n disableNormalization: false\n} as const;\n\nexport const createConvolverNodeConstructor: TConvolverNodeConstructorFactory = (\n audioNodeConstructor,\n createConvolverNodeRenderer,\n createNativeConvolverNode,\n getNativeContext,\n isNativeOfflineAudioContext,\n setAudioNodeTailTime\n) => {\n return class ConvolverNode<T extends TContext> extends audioNodeConstructor<T> implements IConvolverNode<T> {\n private _isBufferNullified: boolean;\n\n private _nativeConvolverNode: TNativeConvolverNode;\n\n constructor(context: T, options?: Partial<IConvolverOptions>) {\n const nativeContext = getNativeContext(context);\n const mergedOptions = { ...DEFAULT_OPTIONS, ...options };\n const nativeConvolverNode = createNativeConvolverNode(nativeContext, mergedOptions);\n const isOffline = isNativeOfflineAudioContext(nativeContext);\n const convolverNodeRenderer = <TAudioNodeRenderer<T, this>>(isOffline ? createConvolverNodeRenderer() : null);\n\n super(context, false, nativeConvolverNode, convolverNodeRenderer);\n\n this._isBufferNullified = false;\n this._nativeConvolverNode = nativeConvolverNode;\n\n if (mergedOptions.buffer !== null) {\n setAudioNodeTailTime(this, mergedOptions.buffer.duration);\n }\n }\n\n get buffer(): null | TAnyAudioBuffer {\n if (this._isBufferNullified) {\n return null;\n }\n\n return this._nativeConvolverNode.buffer;\n }\n\n set buffer(value) {\n this._nativeConvolverNode.buffer = value;\n\n // Bug #115: Safari does not allow to set the buffer to null.\n if (value === null && this._nativeConvolverNode.buffer !== null) {\n const nativeContext = this._nativeConvolverNode.context;\n\n this._nativeConvolverNode.buffer = nativeContext.createBuffer(1, 1, nativeContext.sampleRate);\n this._isBufferNullified = true;\n\n setAudioNodeTailTime(this, 0);\n } else {\n this._isBufferNullified = false;\n\n setAudioNodeTailTime(this, this._nativeConvolverNode.buffer === null ? 0 : this._nativeConvolverNode.buffer.duration);\n }\n }\n\n get normalize(): boolean {\n return this._nativeConvolverNode.normalize;\n }\n\n set normalize(value) {\n this._nativeConvolverNode.normalize = value;\n }\n };\n};\n","import { isNativeAudioNodeFaker } from '../guards/native-audio-node-faker';\nimport { isOwnedByContext } from '../helpers/is-owned-by-context';\nimport { IConvolverNode, IMinimalOfflineAudioContext, IOfflineAudioContext } from '../interfaces';\nimport { TConvolverNodeRendererFactoryFactory, TNativeConvolverNode, TNativeOfflineAudioContext } from '../types';\n\nexport const createConvolverNodeRendererFactory: TConvolverNodeRendererFactoryFactory = (\n createNativeConvolverNode,\n getNativeAudioNode,\n renderInputsOfAudioNode\n) => {\n return <T extends IMinimalOfflineAudioContext | IOfflineAudioContext>() => {\n const renderedNativeConvolverNodes = new WeakMap<TNativeOfflineAudioContext, TNativeConvolverNode>();\n\n const createConvolverNode = async (proxy: IConvolverNode<T>, nativeOfflineAudioContext: TNativeOfflineAudioContext) => {\n let nativeConvolverNode = getNativeAudioNode<T, TNativeConvolverNode>(proxy);\n\n // If the initially used nativeConvolverNode was not constructed on the same OfflineAudioContext it needs to be created again.\n const nativeConvolverNodeIsOwnedByContext = isOwnedByContext(nativeConvolverNode, nativeOfflineAudioContext);\n\n if (!nativeConvolverNodeIsOwnedByContext) {\n const options = {\n buffer: nativeConvolverNode.buffer,\n channelCount: nativeConvolverNode.channelCount,\n channelCountMode: nativeConvolverNode.channelCountMode,\n channelInterpretation: nativeConvolverNode.channelInterpretation,\n disableNormalization: !nativeConvolverNode.normalize\n };\n\n nativeConvolverNode = createNativeConvolverNode(nativeOfflineAudioContext, options);\n }\n\n renderedNativeConvolverNodes.set(nativeOfflineAudioContext, nativeConvolverNode);\n\n if (isNativeAudioNodeFaker(nativeConvolverNode)) {\n await renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeConvolverNode.inputs[0]);\n } else {\n await renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeConvolverNode);\n }\n\n return nativeConvolverNode;\n };\n\n return {\n render(proxy: IConvolverNode<T>, nativeOfflineAudioContext: TNativeOfflineAudioContext): Promise<TNativeConvolverNode> {\n const renderedNativeConvolverNode = renderedNativeConvolverNodes.get(nativeOfflineAudioContext);\n\n if (renderedNativeConvolverNode !== undefined) {\n return Promise.resolve(renderedNativeConvolverNode);\n }\n\n return createConvolverNode(proxy, nativeOfflineAudioContext);\n }\n };\n };\n};\n","import { TCreateNativeOfflineAudioContextFactory } from '../types';\n\nexport const createCreateNativeOfflineAudioContext: TCreateNativeOfflineAudioContextFactory = (\n createNotSupportedError,\n nativeOfflineAudioContextConstructor\n) => {\n return (numberOfChannels, length, sampleRate) => {\n if (nativeOfflineAudioContextConstructor === null) {\n throw new Error('Missing the native OfflineAudioContext constructor.');\n }\n\n try {\n return new nativeOfflineAudioContextConstructor(numberOfChannels, length, sampleRate);\n } catch (err) {\n // Bug #143, #144 & #146: Safari throws a SyntaxError when numberOfChannels, length or sampleRate are invalid.\n if (err.name === 'SyntaxError') {\n throw createNotSupportedError();\n }\n\n throw err;\n }\n };\n};\n","import { TDataCloneErrorFactory } from '../types';\n\nexport const createDataCloneError: TDataCloneErrorFactory = () => new DOMException('', 'DataCloneError');\n","export const detachArrayBuffer = (arrayBuffer: ArrayBuffer): Promise<void> => {\n const { port1, port2 } = new MessageChannel();\n\n return new Promise((resolve) => {\n const closeAndResolve = () => {\n port2.onmessage = null;\n\n port1.close();\n port2.close();\n\n resolve();\n };\n\n port2.onmessage = () => closeAndResolve();\n\n try {\n port1.postMessage(arrayBuffer, [arrayBuffer]);\n } catch {\n // Ignore errors.\n } finally {\n closeAndResolve();\n }\n });\n};\n","import { detachArrayBuffer } from '../helpers/detach-array-buffer';\nimport { wrapAudioBufferGetChannelDataMethod } from '../helpers/wrap-audio-buffer-get-channel-data-method';\nimport { TDecodeAudioDataFactory } from '../types';\n\nexport const createDecodeAudioData: TDecodeAudioDataFactory = (\n audioBufferStore,\n cacheTestResult,\n createDataCloneError,\n createEncodingError,\n detachedArrayBuffers,\n getNativeContext,\n isNativeContext,\n testAudioBufferCopyChannelMethodsOutOfBoundsSupport,\n testPromiseSupport,\n wrapAudioBufferCopyChannelMethods,\n wrapAudioBufferCopyChannelMethodsOutOfBounds\n) => {\n return (anyContext, audioData) => {\n const nativeContext = isNativeContext(anyContext) ? anyContext : getNativeContext(anyContext);\n\n // Bug #43: Only Chrome and Edge do throw a DataCloneError.\n if (detachedArrayBuffers.has(audioData)) {\n const err = createDataCloneError();\n\n return Promise.reject(err);\n }\n\n // The audioData parameter maybe of a type which can't be added to a WeakSet.\n try {\n detachedArrayBuffers.add(audioData);\n } catch {\n // Ignore errors.\n }\n\n // Bug #21: Safari does not support promises yet.\n if (cacheTestResult(testPromiseSupport, () => testPromiseSupport(nativeContext))) {\n return nativeContext.decodeAudioData(audioData).then((audioBuffer) => {\n // Bug #133: Safari does neuter the ArrayBuffer.\n detachArrayBuffer(audioData).catch(() => {\n // Ignore errors.\n });\n\n // Bug #157: Firefox does not allow the bufferOffset to be out-of-bounds.\n if (\n !cacheTestResult(testAudioBufferCopyChannelMethodsOutOfBoundsSupport, () =>\n testAudioBufferCopyChannelMethodsOutOfBoundsSupport(audioBuffer)\n )\n ) {\n wrapAudioBufferCopyChannelMethodsOutOfBounds(audioBuffer);\n }\n\n audioBufferStore.add(audioBuffer);\n\n return audioBuffer;\n });\n }\n\n // Bug #21: Safari does not return a Promise yet.\n return new Promise((resolve, reject) => {\n const complete = async () => {\n // Bug #133: Safari does neuter the ArrayBuffer.\n try {\n await detachArrayBuffer(audioData);\n } catch {\n // Ignore errors.\n }\n };\n\n const fail = (err: DOMException | Error) => {\n reject(err);\n complete();\n };\n\n // Bug #26: Safari throws a synchronous error.\n try {\n // Bug #1: Safari requires a successCallback.\n nativeContext.decodeAudioData(\n audioData,\n (audioBuffer) => {\n // Bug #5: Safari does not support copyFromChannel() and copyToChannel().\n // Bug #100: Safari does throw a wrong error when calling getChannelData() with an out-of-bounds value.\n if (typeof audioBuffer.copyFromChannel !== 'function') {\n wrapAudioBufferCopyChannelMethods(audioBuffer);\n wrapAudioBufferGetChannelDataMethod(audioBuffer);\n }\n\n audioBufferStore.add(audioBuffer);\n\n complete().then(() => resolve(audioBuffer));\n },\n (err: DOMException | Error) => {\n // Bug #4: Safari returns null instead of an error.\n if (err === null) {\n fail(createEncodingError());\n } else {\n fail(err);\n }\n }\n );\n } catch (err) {\n fail(err);\n }\n });\n };\n};\n","import { isAudioNodeOutputConnection } from '../guards/audio-node-output-connection';\nimport { TDecrementCycleCounterFactory } from '../types';\n\nexport const createDecrementCycleCounter: TDecrementCycleCounterFactory = (\n connectNativeAudioNodeToNativeAudioNode,\n cycleCounters,\n getAudioNodeConnections,\n getNativeAudioNode,\n getNativeAudioParam,\n getNativeContext,\n isActiveAudioNode,\n isNativeOfflineAudioContext\n) => {\n return (audioNode, count) => {\n const cycleCounter = cycleCounters.get(audioNode);\n\n if (cycleCounter === undefined) {\n throw new Error('Missing the expected cycle count.');\n }\n\n const nativeContext = getNativeContext(audioNode.context);\n const isOffline = isNativeOfflineAudioContext(nativeContext);\n\n if (cycleCounter === count) {\n cycleCounters.delete(audioNode);\n\n if (!isOffline && isActiveAudioNode(audioNode)) {\n const nativeSourceAudioNode = getNativeAudioNode(audioNode);\n const { outputs } = getAudioNodeConnections(audioNode);\n\n for (const output of outputs) {\n if (isAudioNodeOutputConnection(output)) {\n const nativeDestinationAudioNode = getNativeAudioNode(output[0]);\n\n connectNativeAudioNodeToNativeAudioNode(nativeSourceAudioNode, nativeDestinationAudioNode, output[1], output[2]);\n } else {\n const nativeDestinationAudioParam = getNativeAudioParam(output[0]);\n\n nativeSourceAudioNode.connect(nativeDestinationAudioParam, output[1]);\n }\n }\n }\n } else {\n cycleCounters.set(audioNode, cycleCounter - count);\n }\n };\n};\n","import { IAudioParam, IDelayNode, IDelayOptions } from '../interfaces';\nimport { TAudioNodeRenderer, TContext, TDelayNodeConstructorFactory } from '../types';\n\nconst DEFAULT_OPTIONS = {\n channelCount: 2,\n channelCountMode: 'max',\n channelInterpretation: 'speakers',\n delayTime: 0,\n maxDelayTime: 1\n} as const;\n\nexport const createDelayNodeConstructor: TDelayNodeConstructorFactory = (\n audioNodeConstructor,\n createAudioParam,\n createDelayNodeRenderer,\n createNativeDelayNode,\n getNativeContext,\n isNativeOfflineAudioContext,\n setAudioNodeTailTime\n) => {\n return class DelayNode<T extends TContext> extends audioNodeConstructor<T> implements IDelayNode<T> {\n private _delayTime: IAudioParam;\n\n constructor(context: T, options?: Partial<IDelayOptions>) {\n const nativeContext = getNativeContext(context);\n const mergedOptions = { ...DEFAULT_OPTIONS, ...options };\n const nativeDelayNode = createNativeDelayNode(nativeContext, mergedOptions);\n const isOffline = isNativeOfflineAudioContext(nativeContext);\n const delayNodeRenderer = <TAudioNodeRenderer<T, this>>(isOffline ? createDelayNodeRenderer(mergedOptions.maxDelayTime) : null);\n\n super(context, false, nativeDelayNode, delayNodeRenderer);\n\n this._delayTime = createAudioParam(this, isOffline, nativeDelayNode.delayTime);\n\n setAudioNodeTailTime(this, mergedOptions.maxDelayTime);\n }\n\n get delayTime(): IAudioParam {\n return this._delayTime;\n }\n };\n};\n","import { isOwnedByContext } from '../helpers/is-owned-by-context';\nimport { IDelayNode, IMinimalOfflineAudioContext, IOfflineAudioContext } from '../interfaces';\nimport { TDelayNodeRendererFactoryFactory, TNativeDelayNode, TNativeOfflineAudioContext } from '../types';\n\nexport const createDelayNodeRendererFactory: TDelayNodeRendererFactoryFactory = (\n connectAudioParam,\n createNativeDelayNode,\n getNativeAudioNode,\n renderAutomation,\n renderInputsOfAudioNode\n) => {\n return <T extends IMinimalOfflineAudioContext | IOfflineAudioContext>(maxDelayTime: number) => {\n const renderedNativeDelayNodes = new WeakMap<TNativeOfflineAudioContext, TNativeDelayNode>();\n\n const createDelayNode = async (proxy: IDelayNode<T>, nativeOfflineAudioContext: TNativeOfflineAudioContext) => {\n let nativeDelayNode = getNativeAudioNode<T, TNativeDelayNode>(proxy);\n\n // If the initially used nativeDelayNode was not constructed on the same OfflineAudioContext it needs to be created again.\n const nativeDelayNodeIsOwnedByContext = isOwnedByContext(nativeDelayNode, nativeOfflineAudioContext);\n\n if (!nativeDelayNodeIsOwnedByContext) {\n const options = {\n channelCount: nativeDelayNode.channelCount,\n channelCountMode: nativeDelayNode.channelCountMode,\n channelInterpretation: nativeDelayNode.channelInterpretation,\n delayTime: nativeDelayNode.delayTime.value,\n maxDelayTime\n };\n\n nativeDelayNode = createNativeDelayNode(nativeOfflineAudioContext, options);\n }\n\n renderedNativeDelayNodes.set(nativeOfflineAudioContext, nativeDelayNode);\n\n if (!nativeDelayNodeIsOwnedByContext) {\n await renderAutomation(nativeOfflineAudioContext, proxy.delayTime, nativeDelayNode.delayTime);\n } else {\n await connectAudioParam(nativeOfflineAudioContext, proxy.delayTime, nativeDelayNode.delayTime);\n }\n\n await renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeDelayNode);\n\n return nativeDelayNode;\n };\n\n return {\n render(proxy: IDelayNode<T>, nativeOfflineAudioContext: TNativeOfflineAudioContext): Promise<TNativeDelayNode> {\n const renderedNativeDelayNode = renderedNativeDelayNodes.get(nativeOfflineAudioContext);\n\n if (renderedNativeDelayNode !== undefined) {\n return Promise.resolve(renderedNativeDelayNode);\n }\n\n return createDelayNode(proxy, nativeOfflineAudioContext);\n }\n };\n };\n};\n","import { TDeleteActiveInputConnectionToAudioNodeFactory } from '../types';\n\nexport const createDeleteActiveInputConnectionToAudioNode: TDeleteActiveInputConnectionToAudioNodeFactory = (pickElementFromSet) => {\n return (activeInputs, source, output, input) => {\n return pickElementFromSet(\n activeInputs[input],\n (activeInputConnection) => activeInputConnection[0] === source && activeInputConnection[1] === output\n );\n };\n};\n","import { TDeleteUnrenderedAudioWorkletNodeFactory } from '../types';\n\nexport const createDeleteUnrenderedAudioWorkletNode: TDeleteUnrenderedAudioWorkletNodeFactory = (getUnrenderedAudioWorkletNodes) => {\n return (nativeContext, audioWorkletNode) => {\n getUnrenderedAudioWorkletNodes(nativeContext).delete(audioWorkletNode);\n };\n};\n","import { IAudioNode, IDelayNode } from '../interfaces';\nimport { TContext } from '../types';\n\nexport const isDelayNode = <T extends TContext>(audioNode: IAudioNode<T>): audioNode is IDelayNode<T> => {\n return 'delayTime' in audioNode;\n};\n","import { isAudioNode } from '../guards/audio-node';\nimport { isDelayNode } from '../guards/delay-node';\nimport { IAudioNode, IAudioParam } from '../interfaces';\nimport { TContext, TDetectCyclesFactory } from '../types';\n\nexport const createDetectCycles: TDetectCyclesFactory = (audioParamAudioNodeStore, getAudioNodeConnections, getValueForKey) => {\n return function detectCycles<T extends TContext>(chain: IAudioNode<T>[], nextLink: IAudioNode<T> | IAudioParam): IAudioNode<T>[][] {\n const audioNode = isAudioNode(nextLink) ? nextLink : <IAudioNode<T>>getValueForKey(audioParamAudioNodeStore, nextLink);\n\n if (isDelayNode(audioNode)) {\n return [];\n }\n\n if (chain[0] === audioNode) {\n return [chain];\n }\n\n if (chain.includes(audioNode)) {\n return [];\n }\n\n const { outputs } = getAudioNodeConnections(audioNode);\n\n return Array.from(outputs)\n .map((outputConnection) => detectCycles([...chain, audioNode], outputConnection[0]))\n .reduce((mergedCycles, nestedCycles) => mergedCycles.concat(nestedCycles), []);\n };\n};\n","import { isNativeAudioNode } from '../guards/native-audio-node';\nimport { TDisconnectMultipleOutputsFactory, TIndexSizeErrorFactory, TNativeAudioNode } from '../types';\n\nconst getOutputAudioNodeAtIndex = (\n createIndexSizeError: TIndexSizeErrorFactory,\n outputAudioNodes: TNativeAudioNode[],\n output: number\n): TNativeAudioNode => {\n const outputAudioNode = outputAudioNodes[output];\n\n if (outputAudioNode === undefined) {\n throw createIndexSizeError();\n }\n\n return outputAudioNode;\n};\n\nexport const createDisconnectMultipleOutputs: TDisconnectMultipleOutputsFactory = (createIndexSizeError) => {\n return (outputAudioNodes, destinationOrOutput = undefined, output = undefined, input = 0) => {\n if (destinationOrOutput === undefined) {\n return outputAudioNodes.forEach((outputAudioNode) => outputAudioNode.disconnect());\n }\n\n if (typeof destinationOrOutput === 'number') {\n return getOutputAudioNodeAtIndex(createIndexSizeError, outputAudioNodes, destinationOrOutput).disconnect();\n }\n\n if (isNativeAudioNode(destinationOrOutput)) {\n if (output === undefined) {\n return outputAudioNodes.forEach((outputAudioNode) => outputAudioNode.disconnect(destinationOrOutput));\n }\n\n if (input === undefined) {\n return getOutputAudioNodeAtIndex(createIndexSizeError, outputAudioNodes, output).disconnect(destinationOrOutput, 0);\n }\n\n return getOutputAudioNodeAtIndex(createIndexSizeError, outputAudioNodes, output).disconnect(destinationOrOutput, 0, input);\n }\n\n if (output === undefined) {\n return outputAudioNodes.forEach((outputAudioNode) => outputAudioNode.disconnect(destinationOrOutput));\n }\n\n return getOutputAudioNodeAtIndex(createIndexSizeError, outputAudioNodes, output).disconnect(destinationOrOutput, 0);\n };\n};\n","import { IAudioParam, IDynamicsCompressorNode, IDynamicsCompressorOptions } from '../interfaces';\nimport {\n TAudioNodeRenderer,\n TChannelCountMode,\n TContext,\n TDynamicsCompressorNodeConstructorFactory,\n TNativeAudioParam,\n TNativeDynamicsCompressorNode\n} from '../types';\n\nconst DEFAULT_OPTIONS = {\n attack: 0.003,\n channelCount: 2,\n channelCountMode: 'clamped-max',\n channelInterpretation: 'speakers',\n knee: 30,\n ratio: 12,\n release: 0.25,\n threshold: -24\n} as const;\n\nexport const createDynamicsCompressorNodeConstructor: TDynamicsCompressorNodeConstructorFactory = (\n audioNodeConstructor,\n createAudioParam,\n createDynamicsCompressorNodeRenderer,\n createNativeDynamicsCompressorNode,\n createNotSupportedError,\n getNativeContext,\n isNativeOfflineAudioContext,\n setAudioNodeTailTime\n) => {\n return class DynamicsCompressorNode<T extends TContext> extends audioNodeConstructor<T> implements IDynamicsCompressorNode<T> {\n private _attack: IAudioParam;\n\n private _knee: IAudioParam;\n\n private _nativeDynamicsCompressorNode: TNativeDynamicsCompressorNode;\n\n private _ratio: IAudioParam;\n\n private _release: IAudioParam;\n\n private _threshold: IAudioParam;\n\n constructor(context: T, options?: Partial<IDynamicsCompressorOptions>) {\n const nativeContext = getNativeContext(context);\n const mergedOptions = { ...DEFAULT_OPTIONS, ...options };\n const nativeDynamicsCompressorNode = createNativeDynamicsCompressorNode(nativeContext, mergedOptions);\n const isOffline = isNativeOfflineAudioContext(nativeContext);\n const dynamicsCompressorNodeRenderer = <TAudioNodeRenderer<T, this>>(isOffline ? createDynamicsCompressorNodeRenderer() : null);\n\n super(context, false, nativeDynamicsCompressorNode, dynamicsCompressorNodeRenderer);\n\n this._attack = createAudioParam(this, isOffline, nativeDynamicsCompressorNode.attack);\n this._knee = createAudioParam(this, isOffline, nativeDynamicsCompressorNode.knee);\n this._nativeDynamicsCompressorNode = nativeDynamicsCompressorNode;\n this._ratio = createAudioParam(this, isOffline, nativeDynamicsCompressorNode.ratio);\n this._release = createAudioParam(this, isOffline, nativeDynamicsCompressorNode.release);\n this._threshold = createAudioParam(this, isOffline, nativeDynamicsCompressorNode.threshold);\n\n setAudioNodeTailTime(this, 0.006);\n }\n\n get attack(): IAudioParam {\n return this._attack;\n }\n\n // Bug #108: Safari allows a channelCount of three and above which is why the getter and setter needs to be overwritten here.\n get channelCount(): number {\n return this._nativeDynamicsCompressorNode.channelCount;\n }\n\n set channelCount(value) {\n const previousChannelCount = this._nativeDynamicsCompressorNode.channelCount;\n\n this._nativeDynamicsCompressorNode.channelCount = value;\n\n if (value > 2) {\n this._nativeDynamicsCompressorNode.channelCount = previousChannelCount;\n\n throw createNotSupportedError();\n }\n }\n\n /*\n * Bug #109: Only Chrome and Firefox disallow a channelCountMode of 'max' yet which is why the getter and setter needs to be\n * overwritten here.\n */\n get channelCountMode(): TChannelCountMode {\n return this._nativeDynamicsCompressorNode.channelCountMode;\n }\n\n set channelCountMode(value) {\n const previousChannelCount = this._nativeDynamicsCompressorNode.channelCountMode;\n\n this._nativeDynamicsCompressorNode.channelCountMode = value;\n\n if (value === 'max') {\n this._nativeDynamicsCompressorNode.channelCountMode = previousChannelCount;\n\n throw createNotSupportedError();\n }\n }\n\n get knee(): IAudioParam {\n return this._knee;\n }\n\n get ratio(): IAudioParam {\n return this._ratio;\n }\n\n get reduction(): number {\n // Bug #111: Safari returns an AudioParam instead of a number.\n if (typeof (<TNativeAudioParam>(<any>this._nativeDynamicsCompressorNode.reduction)).value === 'number') {\n return (<TNativeAudioParam>(<any>this._nativeDynamicsCompressorNode.reduction)).value;\n }\n\n return this._nativeDynamicsCompressorNode.reduction;\n }\n\n get release(): IAudioParam {\n return this._release;\n }\n\n get threshold(): IAudioParam {\n return this._threshold;\n }\n };\n};\n","import { isOwnedByContext } from '../helpers/is-owned-by-context';\nimport { IDynamicsCompressorNode, IMinimalOfflineAudioContext, IOfflineAudioContext } from '../interfaces';\nimport { TDynamicsCompressorNodeRendererFactoryFactory, TNativeDynamicsCompressorNode, TNativeOfflineAudioContext } from '../types';\n\nexport const createDynamicsCompressorNodeRendererFactory: TDynamicsCompressorNodeRendererFactoryFactory = (\n connectAudioParam,\n createNativeDynamicsCompressorNode,\n getNativeAudioNode,\n renderAutomation,\n renderInputsOfAudioNode\n) => {\n return <T extends IMinimalOfflineAudioContext | IOfflineAudioContext>() => {\n const renderedNativeDynamicsCompressorNodes = new WeakMap<TNativeOfflineAudioContext, TNativeDynamicsCompressorNode>();\n\n const createDynamicsCompressorNode = async (\n proxy: IDynamicsCompressorNode<T>,\n nativeOfflineAudioContext: TNativeOfflineAudioContext\n ) => {\n let nativeDynamicsCompressorNode = getNativeAudioNode<T, TNativeDynamicsCompressorNode>(proxy);\n\n /*\n * If the initially used nativeDynamicsCompressorNode was not constructed on the same OfflineAudioContext it needs to be\n * created again.\n */\n const nativeDynamicsCompressorNodeIsOwnedByContext = isOwnedByContext(nativeDynamicsCompressorNode, nativeOfflineAudioContext);\n\n if (!nativeDynamicsCompressorNodeIsOwnedByContext) {\n const options = {\n attack: nativeDynamicsCompressorNode.attack.value,\n channelCount: nativeDynamicsCompressorNode.channelCount,\n channelCountMode: nativeDynamicsCompressorNode.channelCountMode,\n channelInterpretation: nativeDynamicsCompressorNode.channelInterpretation,\n knee: nativeDynamicsCompressorNode.knee.value,\n ratio: nativeDynamicsCompressorNode.ratio.value,\n release: nativeDynamicsCompressorNode.release.value,\n threshold: nativeDynamicsCompressorNode.threshold.value\n };\n\n nativeDynamicsCompressorNode = createNativeDynamicsCompressorNode(nativeOfflineAudioContext, options);\n }\n\n renderedNativeDynamicsCompressorNodes.set(nativeOfflineAudioContext, nativeDynamicsCompressorNode);\n\n if (!nativeDynamicsCompressorNodeIsOwnedByContext) {\n await renderAutomation(nativeOfflineAudioContext, proxy.attack, nativeDynamicsCompressorNode.attack);\n await renderAutomation(nativeOfflineAudioContext, proxy.knee, nativeDynamicsCompressorNode.knee);\n await renderAutomation(nativeOfflineAudioContext, proxy.ratio, nativeDynamicsCompressorNode.ratio);\n await renderAutomation(nativeOfflineAudioContext, proxy.release, nativeDynamicsCompressorNode.release);\n await renderAutomation(nativeOfflineAudioContext, proxy.threshold, nativeDynamicsCompressorNode.threshold);\n } else {\n await connectAudioParam(nativeOfflineAudioContext, proxy.attack, nativeDynamicsCompressorNode.attack);\n await connectAudioParam(nativeOfflineAudioContext, proxy.knee, nativeDynamicsCompressorNode.knee);\n await connectAudioParam(nativeOfflineAudioContext, proxy.ratio, nativeDynamicsCompressorNode.ratio);\n await connectAudioParam(nativeOfflineAudioContext, proxy.release, nativeDynamicsCompressorNode.release);\n await connectAudioParam(nativeOfflineAudioContext, proxy.threshold, nativeDynamicsCompressorNode.threshold);\n }\n\n await renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeDynamicsCompressorNode);\n\n return nativeDynamicsCompressorNode;\n };\n\n return {\n render(\n proxy: IDynamicsCompressorNode<T>,\n nativeOfflineAudioContext: TNativeOfflineAudioContext\n ): Promise<TNativeDynamicsCompressorNode> {\n const renderedNativeDynamicsCompressorNode = renderedNativeDynamicsCompressorNodes.get(nativeOfflineAudioContext);\n\n if (renderedNativeDynamicsCompressorNode !== undefined) {\n return Promise.resolve(renderedNativeDynamicsCompressorNode);\n }\n\n return createDynamicsCompressorNode(proxy, nativeOfflineAudioContext);\n }\n };\n };\n};\n","import { TEncodingErrorFactory } from '../types';\n\nexport const createEncodingError: TEncodingErrorFactory = () => new DOMException('', 'EncodingError');\n","import { TEvaluateSourceFactory } from '../types';\n\nexport const createEvaluateSource: TEvaluateSourceFactory = (window) => {\n return (source) =>\n new Promise((resolve, reject) => {\n if (window === null) {\n // Bug #182 Chrome and Edge do throw an instance of a SyntaxError instead of a DOMException.\n reject(new SyntaxError());\n\n return;\n }\n\n const head = window.document.head;\n\n if (head === null) {\n // Bug #182 Chrome and Edge do throw an instance of a SyntaxError instead of a DOMException.\n reject(new SyntaxError());\n } else {\n const script = window.document.createElement('script');\n // @todo Safari doesn't like URLs with a type of 'application/javascript; charset=utf-8'.\n const blob = new Blob([source], { type: 'application/javascript' });\n const url = URL.createObjectURL(blob);\n\n const originalOnErrorHandler = window.onerror;\n\n const removeErrorEventListenerAndRevokeUrl = () => {\n window.onerror = originalOnErrorHandler;\n\n URL.revokeObjectURL(url);\n };\n\n window.onerror = (message, src, lineno, colno, error) => {\n // @todo Edge thinks the source is the one of the html document.\n if (src === url || (src === window.location.href && lineno === 1 && colno === 1)) {\n removeErrorEventListenerAndRevokeUrl();\n reject(error);\n\n return false;\n }\n\n if (originalOnErrorHandler !== null) {\n return originalOnErrorHandler(message, src, lineno, colno, error);\n }\n };\n\n script.onerror = () => {\n removeErrorEventListenerAndRevokeUrl();\n // Bug #182 Chrome and Edge do throw an instance of a SyntaxError instead of a DOMException.\n reject(new SyntaxError());\n };\n script.onload = () => {\n removeErrorEventListenerAndRevokeUrl();\n resolve();\n };\n script.src = url;\n script.type = 'module';\n\n head.appendChild(script);\n }\n });\n};\n","import { IEventTarget } from '../interfaces';\nimport { TEventHandler, TEventTargetConstructorFactory, TNativeEventTarget } from '../types';\n\nexport const createEventTargetConstructor: TEventTargetConstructorFactory = (wrapEventListener) => {\n return class EventTarget<EventMap extends Record<string, Event>> implements IEventTarget<EventMap> {\n private _listeners: WeakMap<EventListenerOrEventListenerObject, EventListenerOrEventListenerObject>;\n\n constructor(private _nativeEventTarget: TNativeEventTarget) {\n this._listeners = new WeakMap();\n }\n\n public addEventListener(\n type: string,\n listener: null | TEventHandler<this> | EventListenerOrEventListenerObject,\n options?: boolean | AddEventListenerOptions\n ): void {\n if (listener !== null) {\n let wrappedEventListener = this._listeners.get(listener);\n\n if (wrappedEventListener === undefined) {\n wrappedEventListener = wrapEventListener(this, listener);\n\n if (typeof listener === 'function') {\n this._listeners.set(listener, wrappedEventListener);\n }\n }\n\n this._nativeEventTarget.addEventListener(type, wrappedEventListener, options);\n }\n }\n\n public dispatchEvent(event: Event): boolean {\n return this._nativeEventTarget.dispatchEvent(event);\n }\n\n public removeEventListener(\n type: string,\n listener: null | TEventHandler<this> | EventListenerOrEventListenerObject,\n options?: boolean | EventListenerOptions\n ): void {\n const wrappedEventListener = listener === null ? undefined : this._listeners.get(listener);\n\n this._nativeEventTarget.removeEventListener(type, wrappedEventListener === undefined ? null : wrappedEventListener, options);\n }\n };\n};\n","import { TExposeCurrentFrameAndCurrentTimeFactory } from '../types';\n\nexport const createExposeCurrentFrameAndCurrentTime: TExposeCurrentFrameAndCurrentTimeFactory = (window) => {\n return (currentTime, sampleRate, fn) => {\n Object.defineProperties(window, {\n currentFrame: {\n configurable: true,\n get(): number {\n return Math.round(currentTime * sampleRate);\n }\n },\n currentTime: {\n configurable: true,\n get(): number {\n return currentTime;\n }\n }\n });\n\n try {\n return fn();\n } finally {\n if (window !== null) {\n delete (<any>window).currentFrame;\n delete (<any>window).currentTime;\n }\n }\n };\n};\n","import { TFetchSourceFactory } from '../types';\n\nexport const createFetchSource: TFetchSourceFactory = (createAbortError) => {\n return async (url) => {\n try {\n const response = await fetch(url);\n\n if (response.ok) {\n return [await response.text(), response.url];\n }\n } catch {\n // Ignore errors.\n } // tslint:disable-line:no-empty\n\n throw createAbortError();\n };\n};\n","import { MOST_NEGATIVE_SINGLE_FLOAT, MOST_POSITIVE_SINGLE_FLOAT } from '../constants';\nimport { IAudioParam, IGainNode, IGainOptions } from '../interfaces';\nimport { TAudioNodeRenderer, TContext, TGainNodeConstructorFactory } from '../types';\n\nconst DEFAULT_OPTIONS = {\n channelCount: 2,\n channelCountMode: 'max',\n channelInterpretation: 'speakers',\n gain: 1\n} as const;\n\nexport const createGainNodeConstructor: TGainNodeConstructorFactory = (\n audioNodeConstructor,\n createAudioParam,\n createGainNodeRenderer,\n createNativeGainNode,\n getNativeContext,\n isNativeOfflineAudioContext\n) => {\n return class GainNode<T extends TContext> extends audioNodeConstructor<T> implements IGainNode<T> {\n private _gain: IAudioParam;\n\n constructor(context: T, options?: Partial<IGainOptions>) {\n const nativeContext = getNativeContext(context);\n const mergedOptions = { ...DEFAULT_OPTIONS, ...options };\n const nativeGainNode = createNativeGainNode(nativeContext, mergedOptions);\n const isOffline = isNativeOfflineAudioContext(nativeContext);\n const gainNodeRenderer = <TAudioNodeRenderer<T, this>>(isOffline ? createGainNodeRenderer() : null);\n\n super(context, false, nativeGainNode, gainNodeRenderer);\n\n // Bug #74: Safari does not export the correct values for maxValue and minValue.\n this._gain = createAudioParam(this, isOffline, nativeGainNode.gain, MOST_POSITIVE_SINGLE_FLOAT, MOST_NEGATIVE_SINGLE_FLOAT);\n }\n\n get gain(): IAudioParam {\n return this._gain;\n }\n };\n};\n","import { isOwnedByContext } from '../helpers/is-owned-by-context';\nimport { IGainNode, IMinimalOfflineAudioContext, IOfflineAudioContext } from '../interfaces';\nimport { TGainNodeRendererFactoryFactory, TNativeGainNode, TNativeOfflineAudioContext } from '../types';\n\nexport const createGainNodeRendererFactory: TGainNodeRendererFactoryFactory = (\n connectAudioParam,\n createNativeGainNode,\n getNativeAudioNode,\n renderAutomation,\n renderInputsOfAudioNode\n) => {\n return <T extends IMinimalOfflineAudioContext | IOfflineAudioContext>() => {\n const renderedNativeGainNodes = new WeakMap<TNativeOfflineAudioContext, TNativeGainNode>();\n\n const createGainNode = async (proxy: IGainNode<T>, nativeOfflineAudioContext: TNativeOfflineAudioContext) => {\n let nativeGainNode = getNativeAudioNode<T, TNativeGainNode>(proxy);\n\n // If the initially used nativeGainNode was not constructed on the same OfflineAudioContext it needs to be created again.\n const nativeGainNodeIsOwnedByContext = isOwnedByContext(nativeGainNode, nativeOfflineAudioContext);\n\n if (!nativeGainNodeIsOwnedByContext) {\n const options = {\n channelCount: nativeGainNode.channelCount,\n channelCountMode: nativeGainNode.channelCountMode,\n channelInterpretation: nativeGainNode.channelInterpretation,\n gain: nativeGainNode.gain.value\n };\n\n nativeGainNode = createNativeGainNode(nativeOfflineAudioContext, options);\n }\n\n renderedNativeGainNodes.set(nativeOfflineAudioContext, nativeGainNode);\n\n if (!nativeGainNodeIsOwnedByContext) {\n await renderAutomation(nativeOfflineAudioContext, proxy.gain, nativeGainNode.gain);\n } else {\n await connectAudioParam(nativeOfflineAudioContext, proxy.gain, nativeGainNode.gain);\n }\n\n await renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeGainNode);\n\n return nativeGainNode;\n };\n\n return {\n render(proxy: IGainNode<T>, nativeOfflineAudioContext: TNativeOfflineAudioContext): Promise<TNativeGainNode> {\n const renderedNativeGainNode = renderedNativeGainNodes.get(nativeOfflineAudioContext);\n\n if (renderedNativeGainNode !== undefined) {\n return Promise.resolve(renderedNativeGainNode);\n }\n\n return createGainNode(proxy, nativeOfflineAudioContext);\n }\n };\n };\n};\n","import { TActiveInputConnection, TContext, TGetActiveAudioWorkletNodeInputsFactory, TNativeAudioWorkletNode } from '../types';\n\nexport const createGetActiveAudioWorkletNodeInputs: TGetActiveAudioWorkletNodeInputsFactory = (\n activeAudioWorkletNodeInputsStore,\n getValueForKey\n) => {\n return <T extends TContext>(nativeAudioWorkletNode: TNativeAudioWorkletNode) =>\n <Set<TActiveInputConnection<T>>[]>getValueForKey(activeAudioWorkletNodeInputsStore, nativeAudioWorkletNode);\n};\n","import { IAudioNode, IAudioNodeRenderer, IMinimalOfflineAudioContext, IOfflineAudioContext } from '../interfaces';\nimport { TGetAudioNodeRendererFactory } from '../types';\n\nexport const createGetAudioNodeRenderer: TGetAudioNodeRendererFactory = (getAudioNodeConnections) => {\n return <T extends IMinimalOfflineAudioContext | IOfflineAudioContext>(\n audioNode: IAudioNode<T>\n ): IAudioNodeRenderer<T, IAudioNode<T>> => {\n const audioNodeConnections = getAudioNodeConnections(audioNode);\n\n if (audioNodeConnections.renderer === null) {\n throw new Error('Missing the renderer of the given AudioNode in the audio graph.');\n }\n\n return <IAudioNodeRenderer<T, IAudioNode<T>>>audioNodeConnections.renderer;\n };\n};\n","import { TGetAudioNodeTailTimeFactory } from '../types';\n\nexport const createGetAudioNodeTailTime: TGetAudioNodeTailTimeFactory = (audioNodeTailTimeStore) => {\n return (audioNode) => audioNodeTailTimeStore.get(audioNode) ?? 0;\n};\n","import { IMinimalOfflineAudioContext } from '../interfaces';\nimport { TGetAudioParamRendererFactory } from '../types';\n\nexport const createGetAudioParamRenderer: TGetAudioParamRendererFactory = (getAudioParamConnections) => {\n return (audioParam) => {\n const audioParamConnections = getAudioParamConnections<IMinimalOfflineAudioContext>(audioParam);\n\n if (audioParamConnections.renderer === null) {\n throw new Error('Missing the renderer of the given AudioParam in the audio graph.');\n }\n\n return audioParamConnections.renderer;\n };\n};\n","import { TGetBackupOfflineAudioContextFactory } from '../types';\n\nexport const createGetBackupOfflineAudioContext: TGetBackupOfflineAudioContextFactory = (backupOfflineAudioContextStore) => {\n return (nativeContext) => {\n return backupOfflineAudioContextStore.get(nativeContext);\n };\n};\n","import { TInvalidStateErrorFactory } from '../types';\n\nexport const createInvalidStateError: TInvalidStateErrorFactory = () => new DOMException('', 'InvalidStateError');\n","import { IMinimalOfflineAudioContext, IOfflineAudioContext } from '../interfaces';\nimport { TContext, TGetNativeContextFactory, TNativeAudioContext, TNativeOfflineAudioContext } from '../types';\nimport { createInvalidStateError } from './invalid-state-error';\n\nexport const createGetNativeContext: TGetNativeContextFactory = (contextStore) => {\n return <T extends TContext>(\n context: T\n ): T extends IMinimalOfflineAudioContext | IOfflineAudioContext ? TNativeOfflineAudioContext : TNativeAudioContext => {\n const nativeContext = contextStore.get(context);\n\n if (nativeContext === undefined) {\n throw createInvalidStateError();\n }\n\n return <T extends IMinimalOfflineAudioContext | IOfflineAudioContext ? TNativeOfflineAudioContext : TNativeAudioContext>(\n nativeContext\n );\n };\n};\n","import { TGetOrCreateBackupOfflineAudioContextFactory } from '../types';\n\nexport const createGetOrCreateBackupOfflineAudioContext: TGetOrCreateBackupOfflineAudioContextFactory = (\n backupOfflineAudioContextStore,\n nativeOfflineAudioContextConstructor\n) => {\n return (nativeContext) => {\n let backupOfflineAudioContext = backupOfflineAudioContextStore.get(nativeContext);\n\n if (backupOfflineAudioContext !== undefined) {\n return backupOfflineAudioContext;\n }\n\n if (nativeOfflineAudioContextConstructor === null) {\n throw new Error('Missing the native OfflineAudioContext constructor.');\n }\n\n // Bug #141: Safari does not support creating an OfflineAudioContext with less than 44100 Hz.\n backupOfflineAudioContext = new nativeOfflineAudioContextConstructor(1, 1, 44100);\n\n backupOfflineAudioContextStore.set(nativeContext, backupOfflineAudioContext);\n\n return backupOfflineAudioContext;\n };\n};\n","import { TGetUnrenderedAudioWorkletNodesFactory } from '../types';\n\nexport const createGetUnrenderedAudioWorkletNodes: TGetUnrenderedAudioWorkletNodesFactory = (unrenderedAudioWorkletNodeStore) => {\n return (nativeContext) => {\n const unrenderedAudioWorkletNodes = unrenderedAudioWorkletNodeStore.get(nativeContext);\n\n if (unrenderedAudioWorkletNodes === undefined) {\n throw new Error('The context has no set of AudioWorkletNodes.');\n }\n\n return unrenderedAudioWorkletNodes;\n };\n};\n","import { TInvalidAccessErrorFactory } from '../types';\n\nexport const createInvalidAccessError: TInvalidAccessErrorFactory = () => new DOMException('', 'InvalidAccessError');\n","import { createInvalidAccessError } from '../factories/invalid-access-error';\nimport { TNativeIIRFilterNode } from '../types';\n\nexport const wrapIIRFilterNodeGetFrequencyResponseMethod = (nativeIIRFilterNode: TNativeIIRFilterNode): void => {\n nativeIIRFilterNode.getFrequencyResponse = ((getFrequencyResponse) => {\n return (frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array) => {\n if (frequencyHz.length !== magResponse.length || magResponse.length !== phaseResponse.length) {\n throw createInvalidAccessError();\n }\n\n return getFrequencyResponse.call(nativeIIRFilterNode, frequencyHz, magResponse, phaseResponse);\n };\n })(nativeIIRFilterNode.getFrequencyResponse);\n};\n","import { wrapIIRFilterNodeGetFrequencyResponseMethod } from '../helpers/wrap-iir-filter-node-get-frequency-response-method';\nimport { IIIRFilterNode, IIIRFilterOptions, IMinimalAudioContext } from '../interfaces';\nimport { TAudioNodeRenderer, TContext, TIIRFilterNodeConstructorFactory, TNativeIIRFilterNode } from '../types';\n\nconst DEFAULT_OPTIONS = {\n channelCount: 2,\n channelCountMode: 'max',\n channelInterpretation: 'speakers'\n} as const;\n\nexport const createIIRFilterNodeConstructor: TIIRFilterNodeConstructorFactory = (\n audioNodeConstructor,\n createNativeIIRFilterNode,\n createIIRFilterNodeRenderer,\n getNativeContext,\n isNativeOfflineAudioContext,\n setAudioNodeTailTime\n) => {\n return class IIRFilterNode<T extends TContext> extends audioNodeConstructor<T> implements IIIRFilterNode<T> {\n private _nativeIIRFilterNode: TNativeIIRFilterNode;\n\n constructor(\n context: T,\n options: { feedback: IIIRFilterOptions['feedback']; feedforward: IIIRFilterOptions['feedforward'] } & Partial<IIIRFilterOptions>\n ) {\n const nativeContext = getNativeContext(context);\n const isOffline = isNativeOfflineAudioContext(nativeContext);\n const mergedOptions = { ...DEFAULT_OPTIONS, ...options };\n const nativeIIRFilterNode = createNativeIIRFilterNode(\n nativeContext,\n isOffline ? null : (<IMinimalAudioContext>(<any>context)).baseLatency,\n mergedOptions\n );\n const iirFilterNodeRenderer = <TAudioNodeRenderer<T, this>>(\n (isOffline ? createIIRFilterNodeRenderer(mergedOptions.feedback, mergedOptions.feedforward) : null)\n );\n\n super(context, false, nativeIIRFilterNode, iirFilterNodeRenderer);\n\n // Bug #23 & #24: FirefoxDeveloper does not throw an InvalidAccessError.\n // @todo Write a test which allows other browsers to remain unpatched.\n wrapIIRFilterNodeGetFrequencyResponseMethod(nativeIIRFilterNode);\n\n this._nativeIIRFilterNode = nativeIIRFilterNode;\n\n // @todo Determine a meaningful tail-time instead of just using one second.\n setAudioNodeTailTime(this, 1);\n }\n\n public getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void {\n return this._nativeIIRFilterNode.getFrequencyResponse(frequencyHz, magResponse, phaseResponse);\n }\n };\n};\n","// This implementation as shamelessly inspired by source code of\n// tslint:disable-next-line:max-line-length\n// {@link https://chromium.googlesource.com/chromium/src.git/+/master/third_party/WebKit/Source/platform/audio/IIRFilter.cpp|Chromium's IIRFilter}.\nexport const filterBuffer = (\n feedback: Float64Array,\n feedbackLength: number,\n feedforward: Float64Array,\n feedforwardLength: number,\n minLength: number,\n xBuffer: Float32Array,\n yBuffer: Float32Array,\n bufferIndex: number,\n bufferLength: number,\n input: Float32Array,\n output: Float32Array\n) => {\n const inputLength = input.length;\n\n let i = bufferIndex;\n\n for (let j = 0; j < inputLength; j += 1) {\n let y = feedforward[0] * input[j];\n\n for (let k = 1; k < minLength; k += 1) {\n const x = (i - k) & (bufferLength - 1); // tslint:disable-line:no-bitwise\n\n y += feedforward[k] * xBuffer[x];\n y -= feedback[k] * yBuffer[x];\n }\n\n for (let k = minLength; k < feedforwardLength; k += 1) {\n y += feedforward[k] * xBuffer[(i - k) & (bufferLength - 1)]; // tslint:disable-line:no-bitwise\n }\n\n for (let k = minLength; k < feedbackLength; k += 1) {\n y -= feedback[k] * yBuffer[(i - k) & (bufferLength - 1)]; // tslint:disable-line:no-bitwise\n }\n\n xBuffer[i] = input[j];\n yBuffer[i] = y;\n\n i = (i + 1) & (bufferLength - 1); // tslint:disable-line:no-bitwise\n\n output[j] = y;\n }\n\n return i;\n};\n","import { filterBuffer } from '../helpers/filter-buffer';\nimport { isOwnedByContext } from '../helpers/is-owned-by-context';\nimport { IIIRFilterNode, IMinimalOfflineAudioContext, IOfflineAudioContext } from '../interfaces';\nimport {\n TIIRFilterNodeRendererFactoryFactory,\n TNativeAudioBuffer,\n TNativeAudioBufferSourceNode,\n TNativeIIRFilterNode,\n TNativeOfflineAudioContext\n} from '../types';\n\nconst filterFullBuffer = (\n renderedBuffer: TNativeAudioBuffer,\n nativeOfflineAudioContext: TNativeOfflineAudioContext,\n feedback: Iterable<number>,\n feedforward: Iterable<number>\n) => {\n const convertedFeedback = feedback instanceof Float64Array ? feedback : new Float64Array(feedback);\n const convertedFeedforward = feedforward instanceof Float64Array ? feedforward : new Float64Array(feedforward);\n const feedbackLength = convertedFeedback.length;\n const feedforwardLength = convertedFeedforward.length;\n const minLength = Math.min(feedbackLength, feedforwardLength);\n\n if (convertedFeedback[0] !== 1) {\n for (let i = 0; i < feedbackLength; i += 1) {\n convertedFeedforward[i] /= convertedFeedback[0];\n }\n\n for (let i = 1; i < feedforwardLength; i += 1) {\n convertedFeedback[i] /= convertedFeedback[0];\n }\n }\n\n const bufferLength = 32;\n const xBuffer = new Float32Array(bufferLength);\n const yBuffer = new Float32Array(bufferLength);\n\n const filteredBuffer = nativeOfflineAudioContext.createBuffer(\n renderedBuffer.numberOfChannels,\n renderedBuffer.length,\n renderedBuffer.sampleRate\n );\n\n const numberOfChannels = renderedBuffer.numberOfChannels;\n\n for (let i = 0; i < numberOfChannels; i += 1) {\n const input = renderedBuffer.getChannelData(i);\n const output = filteredBuffer.getChannelData(i);\n\n xBuffer.fill(0);\n yBuffer.fill(0);\n\n filterBuffer(\n convertedFeedback,\n feedbackLength,\n convertedFeedforward,\n feedforwardLength,\n minLength,\n xBuffer,\n yBuffer,\n 0,\n bufferLength,\n input,\n output\n );\n }\n\n return filteredBuffer;\n};\n\nexport const createIIRFilterNodeRendererFactory: TIIRFilterNodeRendererFactoryFactory = (\n createNativeAudioBufferSourceNode,\n getNativeAudioNode,\n nativeOfflineAudioContextConstructor,\n renderInputsOfAudioNode,\n renderNativeOfflineAudioContext\n) => {\n return <T extends IMinimalOfflineAudioContext | IOfflineAudioContext>(feedback: Iterable<number>, feedforward: Iterable<number>) => {\n const renderedNativeAudioNodes = new WeakMap<TNativeOfflineAudioContext, TNativeAudioBufferSourceNode | TNativeIIRFilterNode>();\n\n let filteredBufferPromise: null | Promise<null | TNativeAudioBuffer> = null;\n\n const createAudioNode = async (proxy: IIIRFilterNode<T>, nativeOfflineAudioContext: TNativeOfflineAudioContext) => {\n let nativeAudioBufferSourceNode: null | TNativeAudioBufferSourceNode = null;\n let nativeIIRFilterNode = getNativeAudioNode<T, TNativeIIRFilterNode>(proxy);\n\n // If the initially used nativeIIRFilterNode was not constructed on the same OfflineAudioContext it needs to be created again.\n const nativeIIRFilterNodeIsOwnedByContext = isOwnedByContext(nativeIIRFilterNode, nativeOfflineAudioContext);\n\n // Bug #9: Safari does not support IIRFilterNodes.\n if (nativeOfflineAudioContext.createIIRFilter === undefined) {\n nativeAudioBufferSourceNode = createNativeAudioBufferSourceNode(nativeOfflineAudioContext, {\n buffer: null,\n channelCount: 2,\n channelCountMode: 'max',\n channelInterpretation: 'speakers',\n loop: false,\n loopEnd: 0,\n loopStart: 0,\n playbackRate: 1\n });\n } else if (!nativeIIRFilterNodeIsOwnedByContext) {\n // @todo TypeScript defines the parameters of createIIRFilter() as arrays of numbers.\n nativeIIRFilterNode = nativeOfflineAudioContext.createIIRFilter(<number[]>feedforward, <number[]>feedback);\n }\n\n renderedNativeAudioNodes.set(\n nativeOfflineAudioContext,\n nativeAudioBufferSourceNode === null ? nativeIIRFilterNode : nativeAudioBufferSourceNode\n );\n\n if (nativeAudioBufferSourceNode !== null) {\n if (filteredBufferPromise === null) {\n if (nativeOfflineAudioContextConstructor === null) {\n throw new Error('Missing the native OfflineAudioContext constructor.');\n }\n\n const partialOfflineAudioContext = new nativeOfflineAudioContextConstructor(\n // Bug #47: The AudioDestinationNode in Safari gets not initialized correctly.\n proxy.context.destination.channelCount,\n // Bug #17: Safari does not yet expose the length.\n proxy.context.length,\n nativeOfflineAudioContext.sampleRate\n );\n\n filteredBufferPromise = (async () => {\n await renderInputsOfAudioNode(proxy, partialOfflineAudioContext, partialOfflineAudioContext.destination);\n\n const renderedBuffer = await renderNativeOfflineAudioContext(partialOfflineAudioContext);\n\n return filterFullBuffer(renderedBuffer, nativeOfflineAudioContext, feedback, feedforward);\n })();\n }\n\n const filteredBuffer = await filteredBufferPromise;\n\n nativeAudioBufferSourceNode.buffer = filteredBuffer;\n nativeAudioBufferSourceNode.start(0);\n\n return nativeAudioBufferSourceNode;\n }\n\n await renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeIIRFilterNode);\n\n return nativeIIRFilterNode;\n };\n\n return {\n render(\n proxy: IIIRFilterNode<T>,\n nativeOfflineAudioContext: TNativeOfflineAudioContext\n ): Promise<TNativeAudioBufferSourceNode | TNativeIIRFilterNode> {\n const renderedNativeAudioNode = renderedNativeAudioNodes.get(nativeOfflineAudioContext);\n\n if (renderedNativeAudioNode !== undefined) {\n return Promise.resolve(renderedNativeAudioNode);\n }\n\n return createAudioNode(proxy, nativeOfflineAudioContext);\n }\n };\n };\n};\n","import { isAudioNodeOutputConnection } from '../guards/audio-node-output-connection';\nimport { TIncrementCycleCounterFactoryFactory } from '../types';\n\nexport const createIncrementCycleCounterFactory: TIncrementCycleCounterFactoryFactory = (\n cycleCounters,\n disconnectNativeAudioNodeFromNativeAudioNode,\n getAudioNodeConnections,\n getNativeAudioNode,\n getNativeAudioParam,\n isActiveAudioNode\n) => {\n return (isOffline) => {\n return (audioNode, count) => {\n const cycleCounter = cycleCounters.get(audioNode);\n\n if (cycleCounter === undefined) {\n if (!isOffline && isActiveAudioNode(audioNode)) {\n const nativeSourceAudioNode = getNativeAudioNode(audioNode);\n const { outputs } = getAudioNodeConnections(audioNode);\n\n for (const output of outputs) {\n if (isAudioNodeOutputConnection(output)) {\n const nativeDestinationAudioNode = getNativeAudioNode(output[0]);\n\n disconnectNativeAudioNodeFromNativeAudioNode(\n nativeSourceAudioNode,\n nativeDestinationAudioNode,\n output[1],\n output[2]\n );\n } else {\n const nativeDestinationAudioParam = getNativeAudioParam(output[0]);\n\n nativeSourceAudioNode.disconnect(nativeDestinationAudioParam, output[1]);\n }\n }\n }\n\n cycleCounters.set(audioNode, count);\n } else {\n cycleCounters.set(audioNode, cycleCounter + count);\n }\n };\n };\n};\n","import { IAudioContext, IMinimalAudioContext } from '../interfaces';\nimport { TIsAnyAudioContextFactory, TNativeAudioContext } from '../types';\n\nexport const createIsAnyAudioContext: TIsAnyAudioContextFactory = (contextStore, isNativeAudioContext) => {\n return (anything): anything is IAudioContext | IMinimalAudioContext | TNativeAudioContext => {\n const nativeContext = contextStore.get(<any>anything);\n\n return isNativeAudioContext(nativeContext) || isNativeAudioContext(anything);\n };\n};\n","import { IAudioNode } from '../interfaces';\nimport { TIsAnyAudioNodeFactory, TNativeAudioNode } from '../types';\n\nexport const createIsAnyAudioNode: TIsAnyAudioNodeFactory = (audioNodeStore, isNativeAudioNode) => {\n return (anything): anything is IAudioNode<any> | TNativeAudioNode => audioNodeStore.has(<any>anything) || isNativeAudioNode(anything);\n};\n","import { IAudioParam } from '../interfaces';\nimport { TIsAnyAudioParamFactory, TNativeAudioParam } from '../types';\n\nexport const createIsAnyAudioParam: TIsAnyAudioParamFactory = (audioParamStore, isNativeAudioParam) => {\n return (anything): anything is IAudioParam | TNativeAudioParam => audioParamStore.has(<any>anything) || isNativeAudioParam(anything);\n};\n","import { IMinimalOfflineAudioContext, IOfflineAudioContext } from '../interfaces';\nimport { TIsAnyOfflineAudioContextFactory, TNativeOfflineAudioContext } from '../types';\n\nexport const createIsAnyOfflineAudioContext: TIsAnyOfflineAudioContextFactory = (contextStore, isNativeOfflineAudioContext) => {\n return (anything): anything is IMinimalOfflineAudioContext | IOfflineAudioContext | TNativeOfflineAudioContext => {\n const nativeContext = contextStore.get(<any>anything);\n\n return isNativeOfflineAudioContext(nativeContext) || isNativeOfflineAudioContext(anything);\n };\n};\n","import { TIsNativeAudioContextFactory, TNativeAudioContext } from '../types';\n\nexport const createIsNativeAudioContext: TIsNativeAudioContextFactory = (nativeAudioContextConstructor) => {\n return (anything): anything is TNativeAudioContext => {\n return nativeAudioContextConstructor !== null && anything instanceof nativeAudioContextConstructor;\n };\n};\n","import { TIsNativeAudioNodeFactory, TNativeAudioNode } from '../types';\n\nexport const createIsNativeAudioNode: TIsNativeAudioNodeFactory = (window) => {\n return (anything): anything is TNativeAudioNode => {\n return window !== null && typeof window.AudioNode === 'function' && anything instanceof window.AudioNode;\n };\n};\n","import { TIsNativeAudioParamFactory, TNativeAudioParam } from '../types';\n\nexport const createIsNativeAudioParam: TIsNativeAudioParamFactory = (window) => {\n return (anything): anything is TNativeAudioParam => {\n return window !== null && typeof window.AudioParam === 'function' && anything instanceof window.AudioParam;\n };\n};\n","import { TIsNativeContextFactory, TNativeAudioContext } from '../types';\n\nexport const createIsNativeContext: TIsNativeContextFactory = (isNativeAudioContext, isNativeOfflineAudioContext) => {\n return (anything): anything is TNativeAudioContext => {\n return isNativeAudioContext(anything) || isNativeOfflineAudioContext(anything);\n };\n};\n","import { TIsNativeOfflineAudioContextFactory, TNativeOfflineAudioContext } from '../types';\n\nexport const createIsNativeOfflineAudioContext: TIsNativeOfflineAudioContextFactory = (nativeOfflineAudioContextConstructor) => {\n return (anything): anything is TNativeOfflineAudioContext => {\n return nativeOfflineAudioContextConstructor !== null && anything instanceof nativeOfflineAudioContextConstructor;\n };\n};\n","import { TIsSecureContextFactory } from '../types';\n\nexport const createIsSecureContext: TIsSecureContextFactory = (window) => window !== null && window.isSecureContext;\n","import { IAudioContext, IMediaElementAudioSourceNode, IMediaElementAudioSourceOptions, IMinimalAudioContext } from '../interfaces';\nimport { TAudioNodeRenderer, TMediaElementAudioSourceNodeConstructorFactory, TNativeMediaElementAudioSourceNode } from '../types';\n\nexport const createMediaElementAudioSourceNodeConstructor: TMediaElementAudioSourceNodeConstructorFactory = (\n audioNodeConstructor,\n createNativeMediaElementAudioSourceNode,\n getNativeContext,\n isNativeOfflineAudioContext\n) => {\n return class MediaElementAudioSourceNode<T extends IAudioContext | IMinimalAudioContext> extends audioNodeConstructor<T>\n implements IMediaElementAudioSourceNode<T> {\n private _nativeMediaElementAudioSourceNode: TNativeMediaElementAudioSourceNode;\n\n constructor(context: T, options: IMediaElementAudioSourceOptions) {\n const nativeContext = getNativeContext(context);\n const nativeMediaElementAudioSourceNode = createNativeMediaElementAudioSourceNode(nativeContext, options);\n\n // Bug #171: Safari allows to create a MediaElementAudioSourceNode with an OfflineAudioContext.\n if (isNativeOfflineAudioContext(nativeContext)) {\n throw TypeError();\n }\n\n super(context, true, nativeMediaElementAudioSourceNode, <TAudioNodeRenderer<T>>null);\n\n this._nativeMediaElementAudioSourceNode = nativeMediaElementAudioSourceNode;\n }\n\n get mediaElement(): HTMLMediaElement {\n return this._nativeMediaElementAudioSourceNode.mediaElement;\n }\n };\n};\n","import { IAudioContext, IAudioNodeOptions, IMediaStreamAudioDestinationNode, IMinimalAudioContext } from '../interfaces';\nimport { TAudioNodeRenderer, TMediaStreamAudioDestinationNodeConstructorFactory, TNativeMediaStreamAudioDestinationNode } from '../types';\n\nconst DEFAULT_OPTIONS = {\n channelCount: 2,\n channelCountMode: 'explicit',\n channelInterpretation: 'speakers'\n} as const;\n\nexport const createMediaStreamAudioDestinationNodeConstructor: TMediaStreamAudioDestinationNodeConstructorFactory = (\n audioNodeConstructor,\n createNativeMediaStreamAudioDestinationNode,\n getNativeContext,\n isNativeOfflineAudioContext\n) => {\n return class MediaStreamAudioDestinationNode<T extends IAudioContext | IMinimalAudioContext> extends audioNodeConstructor<T>\n implements IMediaStreamAudioDestinationNode<T> {\n private _nativeMediaStreamAudioDestinationNode: TNativeMediaStreamAudioDestinationNode;\n\n constructor(context: T, options?: Partial<IAudioNodeOptions>) {\n const nativeContext = getNativeContext(context);\n\n // Bug #173: Safari allows to create a MediaStreamAudioDestinationNode with an OfflineAudioContext.\n if (isNativeOfflineAudioContext(nativeContext)) {\n throw new TypeError();\n }\n\n const mergedOptions = { ...DEFAULT_OPTIONS, ...options };\n const nativeMediaStreamAudioDestinationNode = createNativeMediaStreamAudioDestinationNode(nativeContext, mergedOptions);\n\n super(context, false, nativeMediaStreamAudioDestinationNode, <TAudioNodeRenderer<T>>null);\n\n this._nativeMediaStreamAudioDestinationNode = nativeMediaStreamAudioDestinationNode;\n }\n\n get stream(): MediaStream {\n return this._nativeMediaStreamAudioDestinationNode.stream;\n }\n };\n};\n","import { IAudioContext, IMediaStreamAudioSourceNode, IMediaStreamAudioSourceOptions, IMinimalAudioContext } from '../interfaces';\nimport { TAudioNodeRenderer, TMediaStreamAudioSourceNodeConstructorFactory, TNativeMediaStreamAudioSourceNode } from '../types';\n\nexport const createMediaStreamAudioSourceNodeConstructor: TMediaStreamAudioSourceNodeConstructorFactory = (\n audioNodeConstructor,\n createNativeMediaStreamAudioSourceNode,\n getNativeContext,\n isNativeOfflineAudioContext\n) => {\n return class MediaStreamAudioSourceNode<T extends IAudioContext | IMinimalAudioContext> extends audioNodeConstructor<T>\n implements IMediaStreamAudioSourceNode<T> {\n private _nativeMediaStreamAudioSourceNode: TNativeMediaStreamAudioSourceNode;\n\n constructor(context: T, options: IMediaStreamAudioSourceOptions) {\n const nativeContext = getNativeContext(context);\n const nativeMediaStreamAudioSourceNode = createNativeMediaStreamAudioSourceNode(nativeContext, options);\n\n // Bug #172: Safari allows to create a MediaStreamAudioSourceNode with an OfflineAudioContext.\n if (isNativeOfflineAudioContext(nativeContext)) {\n throw new TypeError();\n }\n\n super(context, true, nativeMediaStreamAudioSourceNode, <TAudioNodeRenderer<T>>null);\n\n this._nativeMediaStreamAudioSourceNode = nativeMediaStreamAudioSourceNode;\n }\n\n get mediaStream(): MediaStream {\n return this._nativeMediaStreamAudioSourceNode.mediaStream;\n }\n };\n};\n","import { IAudioContext, IMediaStreamTrackAudioSourceNode, IMediaStreamTrackAudioSourceOptions, IMinimalAudioContext } from '../interfaces';\nimport { TAudioNodeRenderer, TMediaStreamTrackAudioSourceNodeConstructorFactory } from '../types';\n\nexport const createMediaStreamTrackAudioSourceNodeConstructor: TMediaStreamTrackAudioSourceNodeConstructorFactory = (\n audioNodeConstructor,\n createNativeMediaStreamTrackAudioSourceNode,\n getNativeContext\n) => {\n return class MediaStreamTrackAudioSourceNode<T extends IAudioContext | IMinimalAudioContext> extends audioNodeConstructor<T>\n implements IMediaStreamTrackAudioSourceNode<T> {\n constructor(context: T, options: IMediaStreamTrackAudioSourceOptions) {\n const nativeContext = getNativeContext(context);\n const nativeMediaStreamTrackAudioSourceNode = createNativeMediaStreamTrackAudioSourceNode(nativeContext, options);\n\n super(context, true, nativeMediaStreamTrackAudioSourceNode, <TAudioNodeRenderer<T>>null);\n }\n };\n};\n","import { deactivateAudioGraph } from '../helpers/deactivate-audio-graph';\nimport { isValidLatencyHint } from '../helpers/is-valid-latency-hint';\nimport { IAudioContextOptions, IMinimalAudioContext } from '../interfaces';\nimport {\n TAudioContextState,\n TMinimalAudioContextConstructorFactory,\n TNativeAudioContext,\n TNativeGainNode,\n TNativeOscillatorNode\n} from '../types';\n\nexport const createMinimalAudioContextConstructor: TMinimalAudioContextConstructorFactory = (\n createInvalidStateError,\n createNotSupportedError,\n createUnknownError,\n minimalBaseAudioContextConstructor,\n nativeAudioContextConstructor\n) => {\n return class MinimalAudioContext extends minimalBaseAudioContextConstructor<IMinimalAudioContext> implements IMinimalAudioContext {\n private _baseLatency: number;\n\n private _nativeAudioContext: TNativeAudioContext;\n\n private _nativeGainNode: null | TNativeGainNode;\n\n private _nativeOscillatorNode: null | TNativeOscillatorNode;\n\n private _state: null | 'suspended';\n\n constructor(options: IAudioContextOptions = {}) {\n if (nativeAudioContextConstructor === null) {\n throw new Error('Missing the native AudioContext constructor.');\n }\n\n let nativeAudioContext: TNativeAudioContext;\n\n try {\n nativeAudioContext = new nativeAudioContextConstructor(options);\n } catch (err) {\n // Bug #192 Safari does throw a SyntaxError if the sampleRate is not supported.\n if (err.code === 12 && err.message === 'sampleRate is not in range') {\n throw createNotSupportedError();\n }\n\n throw err;\n }\n\n // Bug #131 Safari returns null when there are four other AudioContexts running already.\n if (nativeAudioContext === null) {\n throw createUnknownError();\n }\n\n // Bug #51 Only Chrome and Edge throw an error if the given latencyHint is invalid.\n if (!isValidLatencyHint(options.latencyHint)) {\n throw new TypeError(\n `The provided value '${options.latencyHint}' is not a valid enum value of type AudioContextLatencyCategory.`\n );\n }\n\n // Bug #150 Safari does not support setting the sampleRate.\n if (options.sampleRate !== undefined && nativeAudioContext.sampleRate !== options.sampleRate) {\n throw createNotSupportedError();\n }\n\n super(nativeAudioContext, 2);\n\n const { latencyHint } = options;\n const { sampleRate } = nativeAudioContext;\n\n // @todo The values for 'balanced', 'interactive' and 'playback' are just copied from Chrome's implementation.\n this._baseLatency =\n typeof nativeAudioContext.baseLatency === 'number'\n ? nativeAudioContext.baseLatency\n : latencyHint === 'balanced'\n ? 512 / sampleRate\n : latencyHint === 'interactive' || latencyHint === undefined\n ? 256 / sampleRate\n : latencyHint === 'playback'\n ? 1024 / sampleRate\n : /*\n * @todo The min (256) and max (16384) values are taken from the allowed bufferSize values of a\n * ScriptProcessorNode.\n */\n (Math.max(2, Math.min(128, Math.round((latencyHint * sampleRate) / 128))) * 128) / sampleRate;\n this._nativeAudioContext = nativeAudioContext;\n\n // Bug #188: Safari will set the context's state to 'interrupted' in case the user switches tabs.\n if (nativeAudioContextConstructor.name === 'webkitAudioContext') {\n this._nativeGainNode = nativeAudioContext.createGain();\n this._nativeOscillatorNode = nativeAudioContext.createOscillator();\n\n this._nativeGainNode.gain.value = 1e-37;\n\n this._nativeOscillatorNode.connect(this._nativeGainNode).connect(nativeAudioContext.destination);\n this._nativeOscillatorNode.start();\n } else {\n this._nativeGainNode = null;\n this._nativeOscillatorNode = null;\n }\n\n this._state = null;\n\n /*\n * Bug #34: Chrome and Edge pretend to be running right away, but fire an onstatechange event when the state actually changes\n * to 'running'.\n */\n if (nativeAudioContext.state === 'running') {\n this._state = 'suspended';\n\n const revokeState = () => {\n if (this._state === 'suspended') {\n this._state = null;\n }\n\n nativeAudioContext.removeEventListener('statechange', revokeState);\n };\n\n nativeAudioContext.addEventListener('statechange', revokeState);\n }\n }\n\n get baseLatency(): number {\n return this._baseLatency;\n }\n\n get state(): TAudioContextState {\n return this._state !== null ? this._state : this._nativeAudioContext.state;\n }\n\n public close(): Promise<void> {\n // Bug #35: Firefox does not throw an error if the AudioContext was closed before.\n if (this.state === 'closed') {\n return this._nativeAudioContext.close().then(() => {\n throw createInvalidStateError();\n });\n }\n\n // Bug #34: If the state was set to suspended before it should be revoked now.\n if (this._state === 'suspended') {\n this._state = null;\n }\n\n return this._nativeAudioContext.close().then(() => {\n if (this._nativeGainNode !== null && this._nativeOscillatorNode !== null) {\n this._nativeOscillatorNode.stop();\n\n this._nativeGainNode.disconnect();\n this._nativeOscillatorNode.disconnect();\n }\n\n deactivateAudioGraph(this);\n });\n }\n\n public resume(): Promise<void> {\n if (this._state === 'suspended') {\n return new Promise((resolve, reject) => {\n const resolvePromise = () => {\n this._nativeAudioContext.removeEventListener('statechange', resolvePromise);\n\n if (this._nativeAudioContext.state === 'running') {\n resolve();\n } else {\n this.resume().then(resolve, reject);\n }\n };\n\n this._nativeAudioContext.addEventListener('statechange', resolvePromise);\n });\n }\n\n return this._nativeAudioContext.resume().catch((err) => {\n // Bug #55: Chrome and Edge do throw an InvalidAccessError instead of an InvalidStateError.\n // Bug #56: Safari invokes the catch handler but without an error.\n if (err === undefined || err.code === 15) {\n throw createInvalidStateError();\n }\n\n throw err;\n });\n }\n\n public suspend(): Promise<void> {\n return this._nativeAudioContext.suspend().catch((err) => {\n // Bug #56: Safari invokes the catch handler but without an error.\n if (err === undefined) {\n throw createInvalidStateError();\n }\n\n throw err;\n });\n }\n };\n};\n","import { CONTEXT_STORE } from '../globals';\nimport { IAudioDestinationNode, IAudioListener, IMinimalBaseAudioContext, IMinimalBaseAudioContextEventMap } from '../interfaces';\nimport { TAudioContextState, TContext, TEventHandler, TMinimalBaseAudioContextConstructorFactory, TNativeContext } from '../types';\n\nexport const createMinimalBaseAudioContextConstructor: TMinimalBaseAudioContextConstructorFactory = (\n audioDestinationNodeConstructor,\n createAudioListener,\n eventTargetConstructor,\n isNativeOfflineAudioContext,\n unrenderedAudioWorkletNodeStore,\n wrapEventListener\n) => {\n return class MinimalBaseAudioContext<T extends TContext>\n extends eventTargetConstructor<IMinimalBaseAudioContextEventMap>\n implements IMinimalBaseAudioContext<T>\n {\n private _destination: IAudioDestinationNode<T>;\n\n private _listener: IAudioListener;\n\n private _onstatechange: null | TEventHandler<T>;\n\n constructor(private _nativeContext: TNativeContext, numberOfChannels: number) {\n super(_nativeContext);\n\n CONTEXT_STORE.set(<T>(<unknown>this), _nativeContext);\n\n if (isNativeOfflineAudioContext(_nativeContext)) {\n unrenderedAudioWorkletNodeStore.set(_nativeContext, new Set());\n }\n\n this._destination = new audioDestinationNodeConstructor(<T>(<unknown>this), numberOfChannels);\n this._listener = createAudioListener(<T>(<unknown>this), _nativeContext);\n this._onstatechange = null;\n }\n\n get currentTime(): number {\n return this._nativeContext.currentTime;\n }\n\n get destination(): IAudioDestinationNode<T> {\n return this._destination;\n }\n\n get listener(): IAudioListener {\n return this._listener;\n }\n\n get onstatechange(): null | TEventHandler<T> {\n return this._onstatechange;\n }\n\n set onstatechange(value) {\n const wrappedListener = typeof value === 'function' ? wrapEventListener(this, value) : null;\n\n this._nativeContext.onstatechange = wrappedListener;\n\n const nativeOnStateChange = this._nativeContext.onstatechange;\n\n this._onstatechange = nativeOnStateChange !== null && nativeOnStateChange === wrappedListener ? value : nativeOnStateChange;\n }\n\n get sampleRate(): number {\n return this._nativeContext.sampleRate;\n }\n\n get state(): TAudioContextState {\n return this._nativeContext.state;\n }\n };\n};\n","import { TNativeContext } from '../types';\n\nexport const testPromiseSupport = (nativeContext: TNativeContext): boolean => {\n // This 12 numbers represent the 48 bytes of an empty WAVE file with a single sample.\n const uint32Array = new Uint32Array([1179011410, 40, 1163280727, 544501094, 16, 131073, 44100, 176400, 1048580, 1635017060, 4, 0]);\n\n try {\n // Bug #1: Safari requires a successCallback.\n const promise = nativeContext.decodeAudioData(<ArrayBuffer>uint32Array.buffer, () => {\n // Ignore the success callback.\n });\n\n if (promise === undefined) {\n return false;\n }\n\n promise.catch(() => {\n // Ignore rejected errors.\n });\n\n return true;\n } catch {\n // Ignore errors.\n }\n\n return false;\n};\n","import { deactivateAudioGraph } from '../helpers/deactivate-audio-graph';\nimport { testPromiseSupport } from '../helpers/test-promise-support';\nimport { IAudioBuffer, IMinimalOfflineAudioContext, IOfflineAudioContextOptions } from '../interfaces';\nimport { TAudioContextState, TMinimalOfflineAudioContextConstructorFactory, TNativeOfflineAudioContext } from '../types';\n\nconst DEFAULT_OPTIONS = {\n numberOfChannels: 1\n} as const;\n\nexport const createMinimalOfflineAudioContextConstructor: TMinimalOfflineAudioContextConstructorFactory = (\n cacheTestResult,\n createInvalidStateError,\n createNativeOfflineAudioContext,\n minimalBaseAudioContextConstructor,\n startRendering\n) => {\n return class MinimalOfflineAudioContext extends minimalBaseAudioContextConstructor<IMinimalOfflineAudioContext>\n implements IMinimalOfflineAudioContext {\n private _length: number;\n\n private _nativeOfflineAudioContext: TNativeOfflineAudioContext;\n\n private _state: null | TAudioContextState;\n\n constructor(options: IOfflineAudioContextOptions) {\n const { length, numberOfChannels, sampleRate } = { ...DEFAULT_OPTIONS, ...options };\n\n const nativeOfflineAudioContext = createNativeOfflineAudioContext(numberOfChannels, length, sampleRate);\n\n // #21 Safari does not support promises and therefore would fire the statechange event before the promise can be resolved.\n if (!cacheTestResult(testPromiseSupport, () => testPromiseSupport(nativeOfflineAudioContext))) {\n nativeOfflineAudioContext.addEventListener(\n 'statechange',\n (() => {\n let i = 0;\n\n const delayStateChangeEvent = (event: Event) => {\n if (this._state === 'running') {\n if (i > 0) {\n nativeOfflineAudioContext.removeEventListener('statechange', delayStateChangeEvent);\n event.stopImmediatePropagation();\n\n this._waitForThePromiseToSettle(event);\n } else {\n i += 1;\n }\n }\n };\n\n return delayStateChangeEvent;\n })()\n );\n }\n\n super(nativeOfflineAudioContext, numberOfChannels);\n\n this._length = length;\n this._nativeOfflineAudioContext = nativeOfflineAudioContext;\n this._state = null;\n }\n\n get length(): number {\n // Bug #17: Safari does not yet expose the length.\n if (this._nativeOfflineAudioContext.length === undefined) {\n return this._length;\n }\n\n return this._nativeOfflineAudioContext.length;\n }\n\n get state(): TAudioContextState {\n return this._state === null ? this._nativeOfflineAudioContext.state : this._state;\n }\n\n public startRendering(): Promise<IAudioBuffer> {\n /*\n * Bug #9 & #59: It is theoretically possible that startRendering() will first render a partialOfflineAudioContext. Therefore\n * the state of the nativeOfflineAudioContext might no transition to running immediately.\n */\n if (this._state === 'running') {\n return Promise.reject(createInvalidStateError());\n }\n\n this._state = 'running';\n\n return startRendering(this.destination, this._nativeOfflineAudioContext).finally(() => {\n this._state = null;\n\n deactivateAudioGraph(this);\n });\n }\n\n private _waitForThePromiseToSettle(event: Event): void {\n if (this._state === null) {\n this._nativeOfflineAudioContext.dispatchEvent(event);\n } else {\n setTimeout(() => this._waitForThePromiseToSettle(event));\n }\n }\n };\n};\n","import { TMonitorConnectionsFactory, TNativeAudioNode, TNativeAudioParam } from '../types';\n\nexport const createMonitorConnections: TMonitorConnectionsFactory = (insertElementInSet, isNativeAudioNode) => {\n return (nativeAudioNode, whenConnected, whenDisconnected) => {\n const connections = new Set<[TNativeAudioNode, number, number] | [TNativeAudioParam, number]>();\n\n nativeAudioNode.connect = <TNativeAudioNode['connect']>((connect) => {\n // tslint:disable-next-line:invalid-void no-inferrable-types\n return (destination: TNativeAudioNode | TNativeAudioParam, output = 0, input: number = 0): void | TNativeAudioNode => {\n const wasDisconnected = connections.size === 0;\n\n if (isNativeAudioNode(destination)) {\n // @todo TypeScript cannot infer the overloaded signature with 3 arguments yet.\n (<(destination: TNativeAudioNode, output?: number, input?: number) => TNativeAudioNode>connect).call(\n nativeAudioNode,\n destination,\n output,\n input\n );\n\n insertElementInSet(\n connections,\n [destination, output, input],\n (connection) => connection[0] === destination && connection[1] === output && connection[2] === input,\n true\n );\n\n if (wasDisconnected) {\n whenConnected();\n }\n\n return destination;\n }\n\n connect.call(nativeAudioNode, destination, output);\n\n insertElementInSet(\n connections,\n [destination, output],\n (connection) => connection[0] === destination && connection[1] === output,\n true\n );\n\n if (wasDisconnected) {\n whenConnected();\n }\n\n return;\n };\n })(nativeAudioNode.connect);\n\n nativeAudioNode.disconnect = ((disconnect) => {\n return (destinationOrOutput?: number | TNativeAudioNode | TNativeAudioParam, output?: number, input?: number): void => {\n const wasConnected = connections.size > 0;\n\n if (destinationOrOutput === undefined) {\n disconnect.apply(nativeAudioNode);\n\n connections.clear();\n } else if (typeof destinationOrOutput === 'number') {\n // @todo TypeScript cannot infer the overloaded signature with 1 argument yet.\n (<(output: number) => void>disconnect).call(nativeAudioNode, destinationOrOutput);\n\n for (const connection of connections) {\n if (connection[1] === destinationOrOutput) {\n connections.delete(connection);\n }\n }\n } else {\n if (isNativeAudioNode(destinationOrOutput)) {\n // @todo TypeScript cannot infer the overloaded signature with 3 arguments yet.\n (<(destination: TNativeAudioNode, output?: number, input?: number) => void>disconnect).call(\n nativeAudioNode,\n destinationOrOutput,\n output,\n input\n );\n } else {\n // @todo TypeScript cannot infer the overloaded signature with 2 arguments yet.\n (<(destination: TNativeAudioParam, output?: number) => void>disconnect).call(\n nativeAudioNode,\n destinationOrOutput,\n output\n );\n }\n\n for (const connection of connections) {\n if (\n connection[0] === destinationOrOutput &&\n (output === undefined || connection[1] === output) &&\n (input === undefined || connection[2] === input)\n ) {\n connections.delete(connection);\n }\n }\n }\n\n const isDisconnected = connections.size === 0;\n\n if (wasConnected && isDisconnected) {\n whenDisconnected();\n }\n };\n })(nativeAudioNode.disconnect);\n\n return nativeAudioNode;\n };\n};\n","export const assignNativeAudioNodeOption = <T extends keyof any, U extends any>(\n nativeAudioNode: Record<T, U>,\n options: Record<T, U>,\n option: T\n) => {\n const value = options[option];\n\n if (value !== undefined && value !== nativeAudioNode[option]) {\n nativeAudioNode[option] = value;\n }\n};\n","import { IAudioNodeOptions } from '../interfaces';\nimport { TNativeAudioNode } from '../types';\nimport { assignNativeAudioNodeOption } from './assign-native-audio-node-option';\n\nexport const assignNativeAudioNodeOptions = (nativeAudioNode: TNativeAudioNode, options: IAudioNodeOptions): void => {\n assignNativeAudioNodeOption(nativeAudioNode, options, 'channelCount');\n assignNativeAudioNodeOption(nativeAudioNode, options, 'channelCountMode');\n assignNativeAudioNodeOption(nativeAudioNode, options, 'channelInterpretation');\n};\n","import { TNativeAnalyserNode } from '../types';\n\nexport const testAnalyserNodeGetFloatTimeDomainDataMethodSupport = (nativeAnalyserNode: TNativeAnalyserNode): boolean => {\n return typeof nativeAnalyserNode.getFloatTimeDomainData === 'function';\n};\n","import { TNativeAnalyserNode } from '../types';\n\nexport const wrapAnalyserNodeGetFloatTimeDomainDataMethod = (nativeAnalyserNode: TNativeAnalyserNode): void => {\n nativeAnalyserNode.getFloatTimeDomainData = (array: Float32Array) => {\n const byteTimeDomainData = new Uint8Array(array.length);\n\n nativeAnalyserNode.getByteTimeDomainData(byteTimeDomainData);\n\n const length = Math.max(byteTimeDomainData.length, nativeAnalyserNode.fftSize);\n\n for (let i = 0; i < length; i += 1) {\n array[i] = (byteTimeDomainData[i] - 128) * 0.0078125;\n }\n\n return array;\n };\n};\n","import { assignNativeAudioNodeOption } from '../helpers/assign-native-audio-node-option';\nimport { assignNativeAudioNodeOptions } from '../helpers/assign-native-audio-node-options';\nimport { testAnalyserNodeGetFloatTimeDomainDataMethodSupport } from '../helpers/test-analyser-node-get-float-time-domain-data-method-support';\nimport { wrapAnalyserNodeGetFloatTimeDomainDataMethod } from '../helpers/wrap-analyser-node-get-float-time-domain-data-method';\nimport { TNativeAnalyserNodeFactoryFactory } from '../types';\n\nexport const createNativeAnalyserNodeFactory: TNativeAnalyserNodeFactoryFactory = (cacheTestResult, createIndexSizeError) => {\n return (nativeContext, options) => {\n const nativeAnalyserNode = nativeContext.createAnalyser();\n\n // Bug #37: Firefox does not create an AnalyserNode with the default properties.\n assignNativeAudioNodeOptions(nativeAnalyserNode, options);\n\n // Bug #118: Safari does not throw an error if maxDecibels is not more than minDecibels.\n if (!(options.maxDecibels > options.minDecibels)) {\n throw createIndexSizeError();\n }\n\n assignNativeAudioNodeOption(nativeAnalyserNode, options, 'fftSize');\n assignNativeAudioNodeOption(nativeAnalyserNode, options, 'maxDecibels');\n assignNativeAudioNodeOption(nativeAnalyserNode, options, 'minDecibels');\n assignNativeAudioNodeOption(nativeAnalyserNode, options, 'smoothingTimeConstant');\n\n // Bug #36: Safari does not support getFloatTimeDomainData() yet.\n if (\n !cacheTestResult(testAnalyserNodeGetFloatTimeDomainDataMethodSupport, () =>\n testAnalyserNodeGetFloatTimeDomainDataMethodSupport(nativeAnalyserNode)\n )\n ) {\n wrapAnalyserNodeGetFloatTimeDomainDataMethod(nativeAnalyserNode);\n }\n\n return nativeAnalyserNode;\n };\n};\n","import { TNativeAudioBufferConstructorFactory } from '../types';\n\nexport const createNativeAudioBufferConstructor: TNativeAudioBufferConstructorFactory = (window) => {\n if (window === null) {\n return null;\n }\n\n if (window.hasOwnProperty('AudioBuffer')) {\n return window.AudioBuffer;\n }\n\n return null;\n};\n","export const assignNativeAudioNodeAudioParamValue = <T extends { [key: string]: any }, U extends { [key: string]: any }>(\n nativeAudioNode: T,\n options: U,\n audioParam: keyof T & keyof U\n) => {\n const value = options[audioParam];\n\n if (value !== undefined && value !== nativeAudioNode[audioParam].value) {\n nativeAudioNode[audioParam].value = value;\n }\n};\n","import { createInvalidStateError } from '../factories/invalid-state-error';\nimport { TNativeAudioBufferSourceNode } from '../types';\n\nexport const wrapAudioBufferSourceNodeStartMethodConsecutiveCalls = (nativeAudioBufferSourceNode: TNativeAudioBufferSourceNode): void => {\n nativeAudioBufferSourceNode.start = ((start) => {\n let isScheduled = false;\n\n return (when = 0, offset = 0, duration?: number) => {\n if (isScheduled) {\n throw createInvalidStateError();\n }\n\n start.call(nativeAudioBufferSourceNode, when, offset, duration);\n\n isScheduled = true;\n };\n })(nativeAudioBufferSourceNode.start);\n};\n","import { TNativeAudioBufferSourceNode, TNativeConstantSourceNode, TNativeOscillatorNode } from '../types';\n\nexport const wrapAudioScheduledSourceNodeStartMethodNegativeParameters = (\n nativeAudioScheduledSourceNode: TNativeAudioBufferSourceNode | TNativeConstantSourceNode | TNativeOscillatorNode\n): void => {\n nativeAudioScheduledSourceNode.start = ((start) => {\n return (when = 0, offset = 0, duration?: number) => {\n if ((typeof duration === 'number' && duration < 0) || offset < 0 || when < 0) {\n throw new RangeError(\"The parameters can't be negative.\");\n }\n\n // @todo TypeScript cannot infer the overloaded signature with 3 arguments yet.\n (<(when: number, offset: number, duration?: number) => void>start).call(nativeAudioScheduledSourceNode, when, offset, duration);\n };\n })(nativeAudioScheduledSourceNode.start);\n};\n","import { TNativeAudioBufferSourceNode, TNativeConstantSourceNode, TNativeOscillatorNode } from '../types';\n\nexport const wrapAudioScheduledSourceNodeStopMethodNegativeParameters = (\n nativeAudioScheduledSourceNode: TNativeAudioBufferSourceNode | TNativeConstantSourceNode | TNativeOscillatorNode\n): void => {\n nativeAudioScheduledSourceNode.stop = ((stop) => {\n return (when = 0) => {\n if (when < 0) {\n throw new RangeError(\"The parameter can't be negative.\");\n }\n\n stop.call(nativeAudioScheduledSourceNode, when);\n };\n })(nativeAudioScheduledSourceNode.stop);\n};\n","import { assignNativeAudioNodeAudioParamValue } from '../helpers/assign-native-audio-node-audio-param-value';\nimport { assignNativeAudioNodeOption } from '../helpers/assign-native-audio-node-option';\nimport { assignNativeAudioNodeOptions } from '../helpers/assign-native-audio-node-options';\nimport { wrapAudioBufferSourceNodeStartMethodConsecutiveCalls } from '../helpers/wrap-audio-buffer-source-node-start-method-consecutive-calls';\nimport { wrapAudioScheduledSourceNodeStartMethodNegativeParameters } from '../helpers/wrap-audio-scheduled-source-node-start-method-negative-parameters';\nimport { wrapAudioScheduledSourceNodeStopMethodNegativeParameters } from '../helpers/wrap-audio-scheduled-source-node-stop-method-negative-parameters';\nimport { TNativeAudioBufferSourceNodeFactoryFactory } from '../types';\n\nexport const createNativeAudioBufferSourceNodeFactory: TNativeAudioBufferSourceNodeFactoryFactory = (\n addSilentConnection,\n cacheTestResult,\n testAudioBufferSourceNodeStartMethodConsecutiveCallsSupport,\n testAudioBufferSourceNodeStartMethodOffsetClampingSupport,\n testAudioBufferSourceNodeStopMethodNullifiedBufferSupport,\n testAudioScheduledSourceNodeStartMethodNegativeParametersSupport,\n testAudioScheduledSourceNodeStopMethodConsecutiveCallsSupport,\n testAudioScheduledSourceNodeStopMethodNegativeParametersSupport,\n wrapAudioBufferSourceNodeStartMethodOffsetClampling,\n wrapAudioBufferSourceNodeStopMethodNullifiedBuffer,\n wrapAudioScheduledSourceNodeStopMethodConsecutiveCalls\n) => {\n return (nativeContext, options) => {\n const nativeAudioBufferSourceNode = nativeContext.createBufferSource();\n\n assignNativeAudioNodeOptions(nativeAudioBufferSourceNode, options);\n\n assignNativeAudioNodeAudioParamValue(nativeAudioBufferSourceNode, options, 'playbackRate');\n\n assignNativeAudioNodeOption(nativeAudioBufferSourceNode, options, 'buffer');\n\n // Bug #149: Safari does not yet support the detune AudioParam.\n\n assignNativeAudioNodeOption(nativeAudioBufferSourceNode, options, 'loop');\n assignNativeAudioNodeOption(nativeAudioBufferSourceNode, options, 'loopEnd');\n assignNativeAudioNodeOption(nativeAudioBufferSourceNode, options, 'loopStart');\n\n // Bug #69: Safari does allow calls to start() of an already scheduled AudioBufferSourceNode.\n if (\n !cacheTestResult(testAudioBufferSourceNodeStartMethodConsecutiveCallsSupport, () =>\n testAudioBufferSourceNodeStartMethodConsecutiveCallsSupport(nativeContext)\n )\n ) {\n wrapAudioBufferSourceNodeStartMethodConsecutiveCalls(nativeAudioBufferSourceNode);\n }\n\n // Bug #154 & #155: Safari does not handle offsets which are equal to or greater than the duration of the buffer.\n if (\n !cacheTestResult(testAudioBufferSourceNodeStartMethodOffsetClampingSupport, () =>\n testAudioBufferSourceNodeStartMethodOffsetClampingSupport(nativeContext)\n )\n ) {\n wrapAudioBufferSourceNodeStartMethodOffsetClampling(nativeAudioBufferSourceNode);\n }\n\n // Bug #162: Safari does throw an error when stop() is called on an AudioBufferSourceNode which has no buffer assigned to it.\n if (\n !cacheTestResult(testAudioBufferSourceNodeStopMethodNullifiedBufferSupport, () =>\n testAudioBufferSourceNodeStopMethodNullifiedBufferSupport(nativeContext)\n )\n ) {\n wrapAudioBufferSourceNodeStopMethodNullifiedBuffer(nativeAudioBufferSourceNode, nativeContext);\n }\n\n // Bug #44: Safari does not throw a RangeError yet.\n if (\n !cacheTestResult(testAudioScheduledSourceNodeStartMethodNegativeParametersSupport, () =>\n testAudioScheduledSourceNodeStartMethodNegativeParametersSupport(nativeContext)\n )\n ) {\n wrapAudioScheduledSourceNodeStartMethodNegativeParameters(nativeAudioBufferSourceNode);\n }\n\n // Bug #19: Safari does not ignore calls to stop() of an already stopped AudioBufferSourceNode.\n if (\n !cacheTestResult(testAudioScheduledSourceNodeStopMethodConsecutiveCallsSupport, () =>\n testAudioScheduledSourceNodeStopMethodConsecutiveCallsSupport(nativeContext)\n )\n ) {\n wrapAudioScheduledSourceNodeStopMethodConsecutiveCalls(nativeAudioBufferSourceNode, nativeContext);\n }\n\n // Bug #44: Only Firefox does not throw a RangeError yet.\n if (\n !cacheTestResult(testAudioScheduledSourceNodeStopMethodNegativeParametersSupport, () =>\n testAudioScheduledSourceNodeStopMethodNegativeParametersSupport(nativeContext)\n )\n ) {\n wrapAudioScheduledSourceNodeStopMethodNegativeParameters(nativeAudioBufferSourceNode);\n }\n\n // Bug #175: Safari will not fire an ended event if the AudioBufferSourceNode is unconnected.\n addSilentConnection(nativeContext, nativeAudioBufferSourceNode);\n\n return nativeAudioBufferSourceNode;\n };\n};\n","import { TNativeAudioContextConstructorFactory } from '../types';\n\nexport const createNativeAudioContextConstructor: TNativeAudioContextConstructorFactory = (window) => {\n if (window === null) {\n return null;\n }\n\n if (window.hasOwnProperty('AudioContext')) {\n return window.AudioContext;\n }\n\n return window.hasOwnProperty('webkitAudioContext') ? (<any>window).webkitAudioContext : null;\n};\n","import { TNativeAudioDestinationNode, TNativeAudioDestinationNodeFactoryFactory, TNativeGainNode } from '../types';\n\nexport const createNativeAudioDestinationNodeFactory: TNativeAudioDestinationNodeFactoryFactory = (\n createNativeGainNode,\n overwriteAccessors\n) => {\n return (nativeContext, channelCount, isNodeOfNativeOfflineAudioContext) => {\n const nativeAudioDestinationNode = nativeContext.destination;\n\n // Bug #132: Safari does not have the correct channelCount.\n if (nativeAudioDestinationNode.channelCount !== channelCount) {\n try {\n nativeAudioDestinationNode.channelCount = channelCount;\n } catch {\n // Bug #169: Safari throws an error on each attempt to change the channelCount.\n }\n }\n\n // Bug #83: Safari does not have the correct channelCountMode.\n if (isNodeOfNativeOfflineAudioContext && nativeAudioDestinationNode.channelCountMode !== 'explicit') {\n nativeAudioDestinationNode.channelCountMode = 'explicit';\n }\n\n // Bug #47: The AudioDestinationNode in Safari does not initialize the maxChannelCount property correctly.\n if (nativeAudioDestinationNode.maxChannelCount === 0) {\n Object.defineProperty(nativeAudioDestinationNode, 'maxChannelCount', {\n value: channelCount\n });\n }\n\n // Bug #168: No browser does yet have an AudioDestinationNode with an output.\n const gainNode = createNativeGainNode(nativeContext, {\n channelCount,\n channelCountMode: nativeAudioDestinationNode.channelCountMode,\n channelInterpretation: nativeAudioDestinationNode.channelInterpretation,\n gain: 1\n });\n\n overwriteAccessors(\n gainNode,\n 'channelCount',\n (get) => () => get.call(gainNode),\n (set) => (value) => {\n set.call(gainNode, value);\n\n try {\n nativeAudioDestinationNode.channelCount = value;\n } catch (err) {\n // Bug #169: Safari throws an error on each attempt to change the channelCount.\n if (value > nativeAudioDestinationNode.maxChannelCount) {\n throw err;\n }\n }\n }\n );\n\n overwriteAccessors(\n gainNode,\n 'channelCountMode',\n (get) => () => get.call(gainNode),\n (set) => (value) => {\n set.call(gainNode, value);\n nativeAudioDestinationNode.channelCountMode = value;\n }\n );\n\n overwriteAccessors(\n gainNode,\n 'channelInterpretation',\n (get) => () => get.call(gainNode),\n (set) => (value) => {\n set.call(gainNode, value);\n nativeAudioDestinationNode.channelInterpretation = value;\n }\n );\n\n Object.defineProperty(gainNode, 'maxChannelCount', {\n get: () => nativeAudioDestinationNode.maxChannelCount\n });\n\n // @todo This should be disconnected when the context is closed.\n gainNode.connect(nativeAudioDestinationNode);\n\n return <{ maxChannelCount: TNativeAudioDestinationNode['maxChannelCount'] } & TNativeGainNode>gainNode;\n };\n};\n","import { TNativeAudioWorkletNodeConstructorFactory } from '../types';\n\nexport const createNativeAudioWorkletNodeConstructor: TNativeAudioWorkletNodeConstructorFactory = (window) => {\n if (window === null) {\n return null;\n }\n\n return window.hasOwnProperty('AudioWorkletNode') ? window.AudioWorkletNode : null;\n};\n","import { IAudioWorkletNodeOptions } from '../interfaces';\n\nexport const testClonabilityOfAudioWorkletNodeOptions = (audioWorkletNodeOptions: IAudioWorkletNodeOptions): void => {\n const { port1 } = new MessageChannel();\n\n try {\n // This will throw an error if the audioWorkletNodeOptions are not clonable.\n port1.postMessage(audioWorkletNodeOptions);\n } finally {\n port1.close();\n }\n};\n","import { testClonabilityOfAudioWorkletNodeOptions } from '../helpers/test-clonability-of-audio-worklet-node-options';\nimport { TNativeAudioWorkletNode, TNativeAudioWorkletNodeFactoryFactory, TNativeAudioWorkletNodeOptions } from '../types';\n\nexport const createNativeAudioWorkletNodeFactory: TNativeAudioWorkletNodeFactoryFactory = (\n createInvalidStateError,\n createNativeAudioWorkletNodeFaker,\n createNativeGainNode,\n createNotSupportedError,\n monitorConnections\n) => {\n return (nativeContext, baseLatency, nativeAudioWorkletNodeConstructor, name, processorConstructor, options) => {\n if (nativeAudioWorkletNodeConstructor !== null) {\n try {\n const nativeAudioWorkletNode = new nativeAudioWorkletNodeConstructor(\n nativeContext,\n name,\n <TNativeAudioWorkletNodeOptions>options\n );\n const patchedEventListeners: Map<\n EventListenerOrEventListenerObject,\n NonNullable<TNativeAudioWorkletNode['onprocessorerror']>\n > = new Map();\n\n let onprocessorerror: TNativeAudioWorkletNode['onprocessorerror'] = null;\n\n Object.defineProperties(nativeAudioWorkletNode, {\n /*\n * Bug #61: Overwriting the property accessors for channelCount and channelCountMode is necessary as long as some\n * browsers have no native implementation to achieve a consistent behavior.\n */\n channelCount: {\n get: () => options.channelCount,\n set: () => {\n throw createInvalidStateError();\n }\n },\n channelCountMode: {\n get: () => 'explicit',\n set: () => {\n throw createInvalidStateError();\n }\n },\n // Bug #156: Chrome and Edge do not yet fire an ErrorEvent.\n onprocessorerror: {\n get: () => onprocessorerror,\n set: (value) => {\n if (typeof onprocessorerror === 'function') {\n nativeAudioWorkletNode.removeEventListener('processorerror', onprocessorerror);\n }\n\n onprocessorerror = typeof value === 'function' ? value : null;\n\n if (typeof onprocessorerror === 'function') {\n nativeAudioWorkletNode.addEventListener('processorerror', onprocessorerror);\n }\n }\n }\n });\n\n nativeAudioWorkletNode.addEventListener = ((addEventListener) => {\n return (...args: [string, EventListenerOrEventListenerObject, (boolean | AddEventListenerOptions)?]): void => {\n if (args[0] === 'processorerror') {\n const unpatchedEventListener =\n typeof args[1] === 'function'\n ? args[1]\n : typeof args[1] === 'object' && args[1] !== null && typeof args[1].handleEvent === 'function'\n ? args[1].handleEvent\n : null;\n\n if (unpatchedEventListener !== null) {\n const patchedEventListener = patchedEventListeners.get(args[1]);\n\n if (patchedEventListener !== undefined) {\n args[1] = patchedEventListener;\n } else {\n args[1] = (event: Event) => {\n // Bug #178: Chrome and Edge do fire an event of type error.\n if (event.type === 'error') {\n Object.defineProperties(event, {\n type: { value: 'processorerror' }\n });\n\n unpatchedEventListener(event);\n } else {\n unpatchedEventListener(new ErrorEvent(args[0], { ...event }));\n }\n };\n\n patchedEventListeners.set(unpatchedEventListener, args[1]);\n }\n }\n }\n\n // Bug #178: Chrome and Edge do fire an event of type error.\n addEventListener.call(nativeAudioWorkletNode, 'error', args[1], args[2]);\n\n return addEventListener.call(nativeAudioWorkletNode, ...args);\n };\n })(nativeAudioWorkletNode.addEventListener);\n\n nativeAudioWorkletNode.removeEventListener = ((removeEventListener) => {\n return (...args: any[]): void => {\n if (args[0] === 'processorerror') {\n const patchedEventListener = patchedEventListeners.get(args[1]);\n\n if (patchedEventListener !== undefined) {\n patchedEventListeners.delete(args[1]);\n\n args[1] = patchedEventListener;\n }\n }\n\n // Bug #178: Chrome and Edge do fire an event of type error.\n removeEventListener.call(nativeAudioWorkletNode, 'error', args[1], args[2]);\n\n return removeEventListener.call(nativeAudioWorkletNode, args[0], args[1], args[2]);\n };\n })(nativeAudioWorkletNode.removeEventListener);\n\n /*\n * Bug #86: Chrome and Edge do not invoke the process() function if the corresponding AudioWorkletNode is unconnected but\n * has an output.\n */\n if (options.numberOfOutputs !== 0) {\n const nativeGainNode = createNativeGainNode(nativeContext, {\n channelCount: 1,\n channelCountMode: 'explicit',\n channelInterpretation: 'discrete',\n gain: 0\n });\n\n nativeAudioWorkletNode.connect(nativeGainNode).connect(nativeContext.destination);\n\n const whenConnected = () => nativeGainNode.disconnect();\n const whenDisconnected = () => nativeGainNode.connect(nativeContext.destination);\n\n // @todo Disconnect the connection when the process() function of the AudioWorkletNode returns false.\n return monitorConnections(nativeAudioWorkletNode, whenConnected, whenDisconnected);\n }\n\n return nativeAudioWorkletNode;\n } catch (err) {\n // Bug #60: Chrome & Edge throw an InvalidStateError instead of a NotSupportedError.\n if (err.code === 11) {\n throw createNotSupportedError();\n }\n\n throw err;\n }\n }\n\n // Bug #61: Only Chrome & Edge have an implementation of the AudioWorkletNode yet.\n if (processorConstructor === undefined) {\n throw createNotSupportedError();\n }\n\n testClonabilityOfAudioWorkletNodeOptions(options);\n\n return createNativeAudioWorkletNodeFaker(nativeContext, baseLatency, processorConstructor, options);\n };\n};\n","export const computeBufferSize = (baseLatency: null | number, sampleRate: number) => {\n if (baseLatency === null) {\n return 512;\n }\n\n return Math.max(512, Math.min(16384, Math.pow(2, Math.round(Math.log2(baseLatency * sampleRate)))));\n};\n","import { IAudioWorkletNodeOptions } from '../interfaces';\n\nexport const cloneAudioWorkletNodeOptions = (audioWorkletNodeOptions: IAudioWorkletNodeOptions): Promise<IAudioWorkletNodeOptions> => {\n return new Promise((resolve, reject) => {\n const { port1, port2 } = new MessageChannel();\n\n port1.onmessage = ({ data }) => {\n port1.close();\n port2.close();\n\n resolve(data);\n };\n port1.onmessageerror = ({ data }) => {\n port1.close();\n port2.close();\n\n reject(data);\n };\n\n // This will throw an error if the audioWorkletNodeOptions are not clonable.\n port2.postMessage(audioWorkletNodeOptions);\n });\n};\n","import { IAudioWorkletNodeOptions, IAudioWorkletProcessor, IAudioWorkletProcessorConstructor } from '../interfaces';\nimport { cloneAudioWorkletNodeOptions } from './clone-audio-worklet-node-options';\n\nexport const createAudioWorkletProcessorPromise = async (\n processorConstructor: IAudioWorkletProcessorConstructor,\n audioWorkletNodeOptions: IAudioWorkletNodeOptions\n): Promise<IAudioWorkletProcessor> => {\n const clonedAudioWorkletNodeOptions = await cloneAudioWorkletNodeOptions(audioWorkletNodeOptions);\n\n return new processorConstructor(clonedAudioWorkletNodeOptions);\n};\n","import { NODE_TO_PROCESSOR_MAPS } from '../globals';\nimport { IAudioWorkletNodeOptions, IAudioWorkletProcessor, IAudioWorkletProcessorConstructor } from '../interfaces';\nimport { TNativeAudioWorkletNode, TNativeContext } from '../types';\nimport { createAudioWorkletProcessorPromise } from './create-audio-worklet-processor-promise';\n\nexport const createAudioWorkletProcessor = (\n nativeContext: TNativeContext,\n nativeAudioWorkletNode: TNativeAudioWorkletNode,\n processorConstructor: IAudioWorkletProcessorConstructor,\n audioWorkletNodeOptions: IAudioWorkletNodeOptions\n): Promise<IAudioWorkletProcessor> => {\n let nodeToProcessorMap = NODE_TO_PROCESSOR_MAPS.get(nativeContext);\n\n if (nodeToProcessorMap === undefined) {\n nodeToProcessorMap = new WeakMap();\n\n NODE_TO_PROCESSOR_MAPS.set(nativeContext, nodeToProcessorMap);\n }\n\n const audioWorkletProcessorPromise = createAudioWorkletProcessorPromise(processorConstructor, audioWorkletNodeOptions);\n\n nodeToProcessorMap.set(nativeAudioWorkletNode, audioWorkletProcessorPromise);\n\n return audioWorkletProcessorPromise;\n};\n","import { MOST_NEGATIVE_SINGLE_FLOAT, MOST_POSITIVE_SINGLE_FLOAT } from '../constants';\nimport { computeBufferSize } from '../helpers/compute-buffer-size';\nimport { copyFromChannel } from '../helpers/copy-from-channel';\nimport { copyToChannel } from '../helpers/copy-to-channel';\nimport { createAudioWorkletProcessor } from '../helpers/create-audio-worklet-processor';\nimport { createNestedArrays } from '../helpers/create-nested-arrays';\nimport { IAudioWorkletProcessor } from '../interfaces';\nimport { ReadOnlyMap } from '../read-only-map';\nimport {\n TNativeAudioNode,\n TNativeAudioParam,\n TNativeAudioWorkletNode,\n TNativeAudioWorkletNodeFakerFactoryFactory,\n TNativeChannelMergerNode,\n TNativeChannelSplitterNode,\n TNativeConstantSourceNode,\n TNativeGainNode\n} from '../types';\n\nexport const createNativeAudioWorkletNodeFakerFactory: TNativeAudioWorkletNodeFakerFactoryFactory = (\n connectMultipleOutputs,\n createIndexSizeError,\n createInvalidStateError,\n createNativeChannelMergerNode,\n createNativeChannelSplitterNode,\n createNativeConstantSourceNode,\n createNativeGainNode,\n createNativeScriptProcessorNode,\n createNotSupportedError,\n disconnectMultipleOutputs,\n exposeCurrentFrameAndCurrentTime,\n getActiveAudioWorkletNodeInputs,\n monitorConnections\n) => {\n return (nativeContext, baseLatency, processorConstructor, options) => {\n if (options.numberOfInputs === 0 && options.numberOfOutputs === 0) {\n throw createNotSupportedError();\n }\n\n const outputChannelCount = Array.isArray(options.outputChannelCount)\n ? options.outputChannelCount\n : Array.from(options.outputChannelCount);\n\n // @todo Check if any of the channelCount values is greater than the implementation's maximum number of channels.\n if (outputChannelCount.some((channelCount) => channelCount < 1)) {\n throw createNotSupportedError();\n }\n\n if (outputChannelCount.length !== options.numberOfOutputs) {\n throw createIndexSizeError();\n }\n\n // Bug #61: This is not part of the standard but required for the faker to work.\n if (options.channelCountMode !== 'explicit') {\n throw createNotSupportedError();\n }\n\n const numberOfInputChannels = options.channelCount * options.numberOfInputs;\n const numberOfOutputChannels = outputChannelCount.reduce((sum, value) => sum + value, 0);\n const numberOfParameters =\n processorConstructor.parameterDescriptors === undefined ? 0 : processorConstructor.parameterDescriptors.length;\n\n // Bug #61: This is not part of the standard but required for the faker to work.\n if (numberOfInputChannels + numberOfParameters > 6 || numberOfOutputChannels > 6) {\n throw createNotSupportedError();\n }\n\n const messageChannel = new MessageChannel();\n const gainNodes: TNativeGainNode[] = [];\n const inputChannelSplitterNodes: TNativeChannelSplitterNode[] = [];\n\n for (let i = 0; i < options.numberOfInputs; i += 1) {\n gainNodes.push(\n createNativeGainNode(nativeContext, {\n channelCount: options.channelCount,\n channelCountMode: options.channelCountMode,\n channelInterpretation: options.channelInterpretation,\n gain: 1\n })\n );\n inputChannelSplitterNodes.push(\n createNativeChannelSplitterNode(nativeContext, {\n channelCount: options.channelCount,\n channelCountMode: 'explicit',\n channelInterpretation: 'discrete',\n numberOfOutputs: options.channelCount\n })\n );\n }\n\n const constantSourceNodes: TNativeConstantSourceNode[] = [];\n\n if (processorConstructor.parameterDescriptors !== undefined) {\n for (const { defaultValue, maxValue, minValue, name } of processorConstructor.parameterDescriptors) {\n const constantSourceNode = createNativeConstantSourceNode(nativeContext, {\n channelCount: 1,\n channelCountMode: 'explicit',\n channelInterpretation: 'discrete',\n offset:\n options.parameterData[name] !== undefined\n ? options.parameterData[name]\n : defaultValue === undefined\n ? 0\n : defaultValue\n });\n\n Object.defineProperties(constantSourceNode.offset, {\n defaultValue: {\n get: () => (defaultValue === undefined ? 0 : defaultValue)\n },\n maxValue: {\n get: () => (maxValue === undefined ? MOST_POSITIVE_SINGLE_FLOAT : maxValue)\n },\n minValue: {\n get: () => (minValue === undefined ? MOST_NEGATIVE_SINGLE_FLOAT : minValue)\n }\n });\n\n constantSourceNodes.push(constantSourceNode);\n }\n }\n\n const inputChannelMergerNode = createNativeChannelMergerNode(nativeContext, {\n channelCount: 1,\n channelCountMode: 'explicit',\n channelInterpretation: 'speakers',\n numberOfInputs: Math.max(1, numberOfInputChannels + numberOfParameters)\n });\n const bufferSize = computeBufferSize(baseLatency, nativeContext.sampleRate);\n const scriptProcessorNode = createNativeScriptProcessorNode(\n nativeContext,\n bufferSize,\n numberOfInputChannels + numberOfParameters,\n // Bug #87: Only Firefox will fire an AudioProcessingEvent if there is no connected output.\n Math.max(1, numberOfOutputChannels)\n );\n const outputChannelSplitterNode = createNativeChannelSplitterNode(nativeContext, {\n channelCount: Math.max(1, numberOfOutputChannels),\n channelCountMode: 'explicit',\n channelInterpretation: 'discrete',\n numberOfOutputs: Math.max(1, numberOfOutputChannels)\n });\n const outputChannelMergerNodes: TNativeChannelMergerNode[] = [];\n\n for (let i = 0; i < options.numberOfOutputs; i += 1) {\n outputChannelMergerNodes.push(\n createNativeChannelMergerNode(nativeContext, {\n channelCount: 1,\n channelCountMode: 'explicit',\n channelInterpretation: 'speakers',\n numberOfInputs: outputChannelCount[i]\n })\n );\n }\n\n for (let i = 0; i < options.numberOfInputs; i += 1) {\n gainNodes[i].connect(inputChannelSplitterNodes[i]);\n\n for (let j = 0; j < options.channelCount; j += 1) {\n inputChannelSplitterNodes[i].connect(inputChannelMergerNode, j, i * options.channelCount + j);\n }\n }\n\n const parameterMap = new ReadOnlyMap(\n processorConstructor.parameterDescriptors === undefined\n ? []\n : processorConstructor.parameterDescriptors.map(({ name }, index) => {\n const constantSourceNode = constantSourceNodes[index];\n\n constantSourceNode.connect(inputChannelMergerNode, 0, numberOfInputChannels + index);\n constantSourceNode.start(0);\n\n return <[string, TNativeAudioParam]>[name, constantSourceNode.offset];\n })\n );\n\n inputChannelMergerNode.connect(scriptProcessorNode);\n\n let channelInterpretation = options.channelInterpretation;\n let onprocessorerror: TNativeAudioWorkletNode['onprocessorerror'] = null;\n\n // Bug #87: Expose at least one output to make this node connectable.\n const outputAudioNodes = options.numberOfOutputs === 0 ? [scriptProcessorNode] : outputChannelMergerNodes;\n const nativeAudioWorkletNodeFaker = {\n get bufferSize(): number {\n return bufferSize;\n },\n get channelCount(): number {\n return options.channelCount;\n },\n set channelCount(_) {\n // Bug #61: This is not part of the standard but required for the faker to work.\n throw createInvalidStateError();\n },\n get channelCountMode(): TNativeAudioWorkletNode['channelCountMode'] {\n return options.channelCountMode;\n },\n set channelCountMode(_) {\n // Bug #61: This is not part of the standard but required for the faker to work.\n throw createInvalidStateError();\n },\n get channelInterpretation(): TNativeAudioWorkletNode['channelInterpretation'] {\n return channelInterpretation;\n },\n set channelInterpretation(value) {\n for (const gainNode of gainNodes) {\n gainNode.channelInterpretation = value;\n }\n\n channelInterpretation = value;\n },\n get context(): TNativeAudioWorkletNode['context'] {\n return scriptProcessorNode.context;\n },\n get inputs(): TNativeAudioNode[] {\n return gainNodes;\n },\n get numberOfInputs(): number {\n return options.numberOfInputs;\n },\n get numberOfOutputs(): number {\n return options.numberOfOutputs;\n },\n get onprocessorerror(): TNativeAudioWorkletNode['onprocessorerror'] {\n return onprocessorerror;\n },\n set onprocessorerror(value) {\n if (typeof onprocessorerror === 'function') {\n nativeAudioWorkletNodeFaker.removeEventListener('processorerror', onprocessorerror);\n }\n\n onprocessorerror = typeof value === 'function' ? value : null;\n\n if (typeof onprocessorerror === 'function') {\n nativeAudioWorkletNodeFaker.addEventListener('processorerror', onprocessorerror);\n }\n },\n get parameters(): TNativeAudioWorkletNode['parameters'] {\n return parameterMap;\n },\n get port(): TNativeAudioWorkletNode['port'] {\n return messageChannel.port2;\n },\n addEventListener(...args: any[]): void {\n return scriptProcessorNode.addEventListener(args[0], args[1], args[2]);\n },\n connect: <TNativeAudioNode['connect']>connectMultipleOutputs.bind(null, outputAudioNodes),\n disconnect: <TNativeAudioNode['disconnect']>disconnectMultipleOutputs.bind(null, outputAudioNodes),\n dispatchEvent(...args: any[]): boolean {\n return scriptProcessorNode.dispatchEvent(args[0]);\n },\n removeEventListener(...args: any[]): void {\n return scriptProcessorNode.removeEventListener(args[0], args[1], args[2]);\n }\n };\n\n const patchedEventListeners: Map<EventListenerOrEventListenerObject, NonNullable<MessagePort['onmessage']>> = new Map();\n\n messageChannel.port1.addEventListener = ((addEventListener) => {\n return (...args: [string, EventListenerOrEventListenerObject, (boolean | AddEventListenerOptions)?]): void => {\n if (args[0] === 'message') {\n const unpatchedEventListener =\n typeof args[1] === 'function'\n ? args[1]\n : typeof args[1] === 'object' && args[1] !== null && typeof args[1].handleEvent === 'function'\n ? args[1].handleEvent\n : null;\n\n if (unpatchedEventListener !== null) {\n const patchedEventListener = patchedEventListeners.get(args[1]);\n\n if (patchedEventListener !== undefined) {\n args[1] = <EventListenerOrEventListenerObject>patchedEventListener;\n } else {\n args[1] = (event: Event) => {\n exposeCurrentFrameAndCurrentTime(nativeContext.currentTime, nativeContext.sampleRate, () =>\n unpatchedEventListener(event)\n );\n };\n\n patchedEventListeners.set(unpatchedEventListener, args[1]);\n }\n }\n }\n\n return addEventListener.call(messageChannel.port1, args[0], args[1], args[2]);\n };\n })(messageChannel.port1.addEventListener);\n\n messageChannel.port1.removeEventListener = ((removeEventListener) => {\n return (...args: any[]): void => {\n if (args[0] === 'message') {\n const patchedEventListener = patchedEventListeners.get(args[1]);\n\n if (patchedEventListener !== undefined) {\n patchedEventListeners.delete(args[1]);\n\n args[1] = patchedEventListener;\n }\n }\n\n return removeEventListener.call(messageChannel.port1, args[0], args[1], args[2]);\n };\n })(messageChannel.port1.removeEventListener);\n\n let onmessage: MessagePort['onmessage'] = null;\n\n Object.defineProperty(messageChannel.port1, 'onmessage', {\n get: () => onmessage,\n set: (value) => {\n if (typeof onmessage === 'function') {\n messageChannel.port1.removeEventListener('message', onmessage);\n }\n\n onmessage = typeof value === 'function' ? value : null;\n\n if (typeof onmessage === 'function') {\n messageChannel.port1.addEventListener('message', onmessage);\n messageChannel.port1.start();\n }\n }\n });\n\n processorConstructor.prototype.port = messageChannel.port1;\n\n let audioWorkletProcessor: null | IAudioWorkletProcessor = null;\n\n const audioWorkletProcessorPromise = createAudioWorkletProcessor(\n nativeContext,\n nativeAudioWorkletNodeFaker,\n processorConstructor,\n options\n );\n\n audioWorkletProcessorPromise.then((dWrkltPrcssr) => (audioWorkletProcessor = dWrkltPrcssr));\n\n const inputs = createNestedArrays(options.numberOfInputs, options.channelCount);\n const outputs = createNestedArrays(options.numberOfOutputs, outputChannelCount);\n const parameters: { [name: string]: Float32Array } =\n processorConstructor.parameterDescriptors === undefined\n ? []\n : processorConstructor.parameterDescriptors.reduce(\n (prmtrs, { name }) => ({ ...prmtrs, [name]: new Float32Array(128) }),\n {}\n );\n\n let isActive = true;\n\n const disconnectOutputsGraph = () => {\n if (options.numberOfOutputs > 0) {\n scriptProcessorNode.disconnect(outputChannelSplitterNode);\n }\n\n for (let i = 0, outputChannelSplitterNodeOutput = 0; i < options.numberOfOutputs; i += 1) {\n const outputChannelMergerNode = outputChannelMergerNodes[i];\n\n for (let j = 0; j < outputChannelCount[i]; j += 1) {\n outputChannelSplitterNode.disconnect(outputChannelMergerNode, outputChannelSplitterNodeOutput + j, j);\n }\n\n outputChannelSplitterNodeOutput += outputChannelCount[i];\n }\n };\n\n const activeInputIndexes = new Map<number, number>();\n\n // tslint:disable-next-line:deprecation\n scriptProcessorNode.onaudioprocess = ({ inputBuffer, outputBuffer }: AudioProcessingEvent) => {\n if (audioWorkletProcessor !== null) {\n const activeInputs = getActiveAudioWorkletNodeInputs(nativeAudioWorkletNodeFaker);\n\n for (let i = 0; i < bufferSize; i += 128) {\n for (let j = 0; j < options.numberOfInputs; j += 1) {\n for (let k = 0; k < options.channelCount; k += 1) {\n copyFromChannel(inputBuffer, inputs[j], k, k, i);\n }\n }\n\n if (processorConstructor.parameterDescriptors !== undefined) {\n processorConstructor.parameterDescriptors.forEach(({ name }, index) => {\n copyFromChannel(inputBuffer, parameters, name, numberOfInputChannels + index, i);\n });\n }\n\n for (let j = 0; j < options.numberOfInputs; j += 1) {\n for (let k = 0; k < outputChannelCount[j]; k += 1) {\n // The byteLength will be 0 when the ArrayBuffer was transferred.\n if (outputs[j][k].byteLength === 0) {\n outputs[j][k] = new Float32Array(128);\n }\n }\n }\n\n try {\n const potentiallyEmptyInputs = inputs.map((input, index) => {\n const activeInput = activeInputs[index];\n\n if (activeInput.size > 0) {\n activeInputIndexes.set(index, bufferSize / 128);\n\n return input;\n }\n\n const count = activeInputIndexes.get(index);\n\n if (count === undefined) {\n return [];\n }\n\n if (input.every((channelData) => channelData.every((sample) => sample === 0))) {\n if (count === 1) {\n activeInputIndexes.delete(index);\n } else {\n activeInputIndexes.set(index, count - 1);\n }\n }\n\n return input;\n });\n\n const activeSourceFlag = exposeCurrentFrameAndCurrentTime(\n nativeContext.currentTime + i / nativeContext.sampleRate,\n nativeContext.sampleRate,\n () => (<IAudioWorkletProcessor>audioWorkletProcessor).process(potentiallyEmptyInputs, outputs, parameters)\n );\n\n isActive = activeSourceFlag;\n\n for (let j = 0, outputChannelSplitterNodeOutput = 0; j < options.numberOfOutputs; j += 1) {\n for (let k = 0; k < outputChannelCount[j]; k += 1) {\n copyToChannel(outputBuffer, outputs[j], k, outputChannelSplitterNodeOutput + k, i);\n }\n\n outputChannelSplitterNodeOutput += outputChannelCount[j];\n }\n } catch (error) {\n isActive = false;\n\n nativeAudioWorkletNodeFaker.dispatchEvent(\n new ErrorEvent('processorerror', {\n colno: error.colno,\n filename: error.filename,\n lineno: error.lineno,\n message: error.message\n })\n );\n }\n\n if (!isActive) {\n for (let j = 0; j < options.numberOfInputs; j += 1) {\n gainNodes[j].disconnect(inputChannelSplitterNodes[j]);\n\n for (let k = 0; k < options.channelCount; k += 1) {\n inputChannelSplitterNodes[i].disconnect(inputChannelMergerNode, k, j * options.channelCount + k);\n }\n }\n\n if (processorConstructor.parameterDescriptors !== undefined) {\n const length = processorConstructor.parameterDescriptors.length;\n\n for (let j = 0; j < length; j += 1) {\n const constantSourceNode = constantSourceNodes[j];\n\n constantSourceNode.disconnect(inputChannelMergerNode, 0, numberOfInputChannels + j);\n constantSourceNode.stop();\n }\n }\n\n inputChannelMergerNode.disconnect(scriptProcessorNode);\n\n scriptProcessorNode.onaudioprocess = null; // tslint:disable-line:deprecation\n\n if (isConnected) {\n disconnectOutputsGraph();\n } else {\n disconnectFakeGraph();\n }\n\n break;\n }\n }\n }\n };\n\n let isConnected = false;\n\n // Bug #87: Only Firefox will fire an AudioProcessingEvent if there is no connected output.\n const nativeGainNode = createNativeGainNode(nativeContext, {\n channelCount: 1,\n channelCountMode: 'explicit',\n channelInterpretation: 'discrete',\n gain: 0\n });\n\n const connectFakeGraph = () => scriptProcessorNode.connect(nativeGainNode).connect(nativeContext.destination);\n const disconnectFakeGraph = () => {\n scriptProcessorNode.disconnect(nativeGainNode);\n nativeGainNode.disconnect();\n };\n const whenConnected = () => {\n if (isActive) {\n disconnectFakeGraph();\n\n if (options.numberOfOutputs > 0) {\n scriptProcessorNode.connect(outputChannelSplitterNode);\n }\n\n for (let i = 0, outputChannelSplitterNodeOutput = 0; i < options.numberOfOutputs; i += 1) {\n const outputChannelMergerNode = outputChannelMergerNodes[i];\n\n for (let j = 0; j < outputChannelCount[i]; j += 1) {\n outputChannelSplitterNode.connect(outputChannelMergerNode, outputChannelSplitterNodeOutput + j, j);\n }\n\n outputChannelSplitterNodeOutput += outputChannelCount[i];\n }\n }\n\n isConnected = true;\n };\n const whenDisconnected = () => {\n if (isActive) {\n connectFakeGraph();\n disconnectOutputsGraph();\n }\n\n isConnected = false;\n };\n\n connectFakeGraph();\n\n return monitorConnections(nativeAudioWorkletNodeFaker, whenConnected, whenDisconnected);\n };\n};\n","import { assignNativeAudioNodeAudioParamValue } from '../helpers/assign-native-audio-node-audio-param-value';\nimport { assignNativeAudioNodeOption } from '../helpers/assign-native-audio-node-option';\nimport { assignNativeAudioNodeOptions } from '../helpers/assign-native-audio-node-options';\nimport { TNativeBiquadFilterNodeFactory } from '../types';\n\nexport const createNativeBiquadFilterNode: TNativeBiquadFilterNodeFactory = (nativeContext, options) => {\n const nativeBiquadFilterNode = nativeContext.createBiquadFilter();\n\n assignNativeAudioNodeOptions(nativeBiquadFilterNode, options);\n\n assignNativeAudioNodeAudioParamValue(nativeBiquadFilterNode, options, 'Q');\n assignNativeAudioNodeAudioParamValue(nativeBiquadFilterNode, options, 'detune');\n assignNativeAudioNodeAudioParamValue(nativeBiquadFilterNode, options, 'frequency');\n assignNativeAudioNodeAudioParamValue(nativeBiquadFilterNode, options, 'gain');\n\n assignNativeAudioNodeOption(nativeBiquadFilterNode, options, 'type');\n\n return nativeBiquadFilterNode;\n};\n","import { assignNativeAudioNodeOptions } from '../helpers/assign-native-audio-node-options';\nimport { TNativeChannelMergerNodeFactoryFactory } from '../types';\n\nexport const createNativeChannelMergerNodeFactory: TNativeChannelMergerNodeFactoryFactory = (\n nativeAudioContextConstructor,\n wrapChannelMergerNode\n) => {\n return (nativeContext, options) => {\n const nativeChannelMergerNode = nativeContext.createChannelMerger(options.numberOfInputs);\n\n /*\n * Bug #20: Safari requires a connection of any kind to treat the input signal correctly.\n * @todo Unfortunately there is no way to test for this behavior in a synchronous fashion which is why testing for the existence of\n * the webkitAudioContext is used as a workaround here.\n */\n if (nativeAudioContextConstructor !== null && nativeAudioContextConstructor.name === 'webkitAudioContext') {\n wrapChannelMergerNode(nativeContext, nativeChannelMergerNode);\n }\n\n assignNativeAudioNodeOptions(nativeChannelMergerNode, options);\n\n return nativeChannelMergerNode;\n };\n};\n","import { createInvalidStateError } from '../factories/invalid-state-error';\nimport { TNativeChannelSplitterNode } from '../types';\n\nexport const wrapChannelSplitterNode = (channelSplitterNode: TNativeChannelSplitterNode): void => {\n const channelCount = channelSplitterNode.numberOfOutputs;\n\n // Bug #97: Safari does not throw an error when attempting to change the channelCount to something other than its initial value.\n Object.defineProperty(channelSplitterNode, 'channelCount', {\n get: () => channelCount,\n set: (value) => {\n if (value !== channelCount) {\n throw createInvalidStateError();\n }\n }\n });\n\n // Bug #30: Safari does not throw an error when attempting to change the channelCountMode to something other than explicit.\n Object.defineProperty(channelSplitterNode, 'channelCountMode', {\n get: () => 'explicit',\n set: (value) => {\n if (value !== 'explicit') {\n throw createInvalidStateError();\n }\n }\n });\n\n // Bug #32: Safari does not throw an error when attempting to change the channelInterpretation to something other than discrete.\n Object.defineProperty(channelSplitterNode, 'channelInterpretation', {\n get: () => 'discrete',\n set: (value) => {\n if (value !== 'discrete') {\n throw createInvalidStateError();\n }\n }\n });\n};\n","import { assignNativeAudioNodeOptions } from '../helpers/assign-native-audio-node-options';\nimport { wrapChannelSplitterNode } from '../helpers/wrap-channel-splitter-node';\nimport { TNativeChannelSplitterNodeFactory } from '../types';\n\nexport const createNativeChannelSplitterNode: TNativeChannelSplitterNodeFactory = (nativeContext, options) => {\n const nativeChannelSplitterNode = nativeContext.createChannelSplitter(options.numberOfOutputs);\n\n // Bug #96: Safari does not have the correct channelCount.\n // Bug #29: Safari does not have the correct channelCountMode.\n // Bug #31: Safari does not have the correct channelInterpretation.\n assignNativeAudioNodeOptions(nativeChannelSplitterNode, options);\n\n // Bug #29, #30, #31, #32, #96 & #97: Only Chrome, Edge & Firefox partially support the spec yet.\n wrapChannelSplitterNode(nativeChannelSplitterNode);\n\n return nativeChannelSplitterNode;\n};\n","import { assignNativeAudioNodeAudioParamValue } from '../helpers/assign-native-audio-node-audio-param-value';\nimport { assignNativeAudioNodeOptions } from '../helpers/assign-native-audio-node-options';\nimport { wrapAudioScheduledSourceNodeStartMethodNegativeParameters } from '../helpers/wrap-audio-scheduled-source-node-start-method-negative-parameters';\nimport { wrapAudioScheduledSourceNodeStopMethodNegativeParameters } from '../helpers/wrap-audio-scheduled-source-node-stop-method-negative-parameters';\nimport { TNativeConstantSourceNodeFactoryFactory } from '../types';\n\nexport const createNativeConstantSourceNodeFactory: TNativeConstantSourceNodeFactoryFactory = (\n addSilentConnection,\n cacheTestResult,\n createNativeConstantSourceNodeFaker,\n testAudioScheduledSourceNodeStartMethodNegativeParametersSupport,\n testAudioScheduledSourceNodeStopMethodNegativeParametersSupport\n) => {\n return (nativeContext, options) => {\n // Bug #62: Safari does not support ConstantSourceNodes.\n if (nativeContext.createConstantSource === undefined) {\n return createNativeConstantSourceNodeFaker(nativeContext, options);\n }\n\n const nativeConstantSourceNode = nativeContext.createConstantSource();\n\n assignNativeAudioNodeOptions(nativeConstantSourceNode, options);\n\n assignNativeAudioNodeAudioParamValue(nativeConstantSourceNode, options, 'offset');\n\n // Bug #44: Safari does not throw a RangeError yet.\n if (\n !cacheTestResult(testAudioScheduledSourceNodeStartMethodNegativeParametersSupport, () =>\n testAudioScheduledSourceNodeStartMethodNegativeParametersSupport(nativeContext)\n )\n ) {\n wrapAudioScheduledSourceNodeStartMethodNegativeParameters(nativeConstantSourceNode);\n }\n\n // Bug #44: Only Firefox does not throw a RangeError yet.\n if (\n !cacheTestResult(testAudioScheduledSourceNodeStopMethodNegativeParametersSupport, () =>\n testAudioScheduledSourceNodeStopMethodNegativeParametersSupport(nativeContext)\n )\n ) {\n wrapAudioScheduledSourceNodeStopMethodNegativeParameters(nativeConstantSourceNode);\n }\n\n // Bug #175: Safari will not fire an ended event if the ConstantSourceNode is unconnected.\n addSilentConnection(nativeContext, nativeConstantSourceNode);\n\n return nativeConstantSourceNode;\n };\n};\n","import { TNativeAudioNode } from '../types';\n\nexport const interceptConnections = <T extends object>(\n original: T,\n interceptor: TNativeAudioNode\n): T & { connect: TNativeAudioNode['connect']; disconnect: TNativeAudioNode['disconnect'] } => {\n (<T & { connect: TNativeAudioNode['connect'] }>original).connect = interceptor.connect.bind(interceptor);\n\n (<T & { disconnect: TNativeAudioNode['disconnect'] }>original).disconnect = interceptor.disconnect.bind(interceptor);\n\n return <T & { connect: TNativeAudioNode['connect']; disconnect: TNativeAudioNode['disconnect'] }>original;\n};\n","import { interceptConnections } from '../helpers/intercept-connections';\nimport {\n TNativeAudioBufferSourceNode,\n TNativeAudioNode,\n TNativeConstantSourceNode,\n TNativeConstantSourceNodeFakerFactoryFactory\n} from '../types';\n\nexport const createNativeConstantSourceNodeFakerFactory: TNativeConstantSourceNodeFakerFactoryFactory = (\n addSilentConnection,\n createNativeAudioBufferSourceNode,\n createNativeGainNode,\n monitorConnections\n) => {\n return (nativeContext, { offset, ...audioNodeOptions }) => {\n const audioBuffer = nativeContext.createBuffer(1, 2, 44100);\n const audioBufferSourceNode = createNativeAudioBufferSourceNode(nativeContext, {\n buffer: null,\n channelCount: 2,\n channelCountMode: 'max',\n channelInterpretation: 'speakers',\n loop: false,\n loopEnd: 0,\n loopStart: 0,\n playbackRate: 1\n });\n const gainNode = createNativeGainNode(nativeContext, { ...audioNodeOptions, gain: offset });\n\n // Bug #5: Safari does not support copyFromChannel() and copyToChannel().\n const channelData = audioBuffer.getChannelData(0);\n\n // Bug #95: Safari does not play or loop one sample buffers.\n channelData[0] = 1;\n channelData[1] = 1;\n\n audioBufferSourceNode.buffer = audioBuffer;\n audioBufferSourceNode.loop = true;\n\n const nativeConstantSourceNodeFaker = {\n get bufferSize(): undefined {\n return undefined;\n },\n get channelCount(): number {\n return gainNode.channelCount;\n },\n set channelCount(value) {\n gainNode.channelCount = value;\n },\n get channelCountMode(): TNativeConstantSourceNode['channelCountMode'] {\n return gainNode.channelCountMode;\n },\n set channelCountMode(value) {\n gainNode.channelCountMode = value;\n },\n get channelInterpretation(): TNativeConstantSourceNode['channelInterpretation'] {\n return gainNode.channelInterpretation;\n },\n set channelInterpretation(value) {\n gainNode.channelInterpretation = value;\n },\n get context(): TNativeConstantSourceNode['context'] {\n return gainNode.context;\n },\n get inputs(): TNativeAudioNode[] {\n return [];\n },\n get numberOfInputs(): number {\n return audioBufferSourceNode.numberOfInputs;\n },\n get numberOfOutputs(): number {\n return gainNode.numberOfOutputs;\n },\n get offset(): TNativeConstantSourceNode['offset'] {\n return gainNode.gain;\n },\n get onended(): TNativeConstantSourceNode['onended'] {\n return audioBufferSourceNode.onended;\n },\n set onended(value) {\n audioBufferSourceNode.onended = <TNativeAudioBufferSourceNode['onended']>value;\n },\n addEventListener(...args: any[]): void {\n return audioBufferSourceNode.addEventListener(args[0], args[1], args[2]);\n },\n dispatchEvent(...args: any[]): boolean {\n return audioBufferSourceNode.dispatchEvent(args[0]);\n },\n removeEventListener(...args: any[]): void {\n return audioBufferSourceNode.removeEventListener(args[0], args[1], args[2]);\n },\n start(when = 0): void {\n audioBufferSourceNode.start.call(audioBufferSourceNode, when);\n },\n stop(when = 0): void {\n audioBufferSourceNode.stop.call(audioBufferSourceNode, when);\n }\n };\n\n const whenConnected = () => audioBufferSourceNode.connect(gainNode);\n const whenDisconnected = () => audioBufferSourceNode.disconnect(gainNode);\n\n // Bug #175: Safari will not fire an ended event if the AudioBufferSourceNode is unconnected.\n addSilentConnection(nativeContext, audioBufferSourceNode);\n\n return monitorConnections(interceptConnections(nativeConstantSourceNodeFaker, gainNode), whenConnected, whenDisconnected);\n };\n};\n","import { assignNativeAudioNodeOption } from '../helpers/assign-native-audio-node-option';\nimport { assignNativeAudioNodeOptions } from '../helpers/assign-native-audio-node-options';\nimport { TNativeConvolverNodeFactoryFactory } from '../types';\n\nexport const createNativeConvolverNodeFactory: TNativeConvolverNodeFactoryFactory = (createNotSupportedError, overwriteAccessors) => {\n return (nativeContext, options) => {\n const nativeConvolverNode = nativeContext.createConvolver();\n\n assignNativeAudioNodeOptions(nativeConvolverNode, options);\n\n // The normalize property needs to be set before setting the buffer.\n if (options.disableNormalization === nativeConvolverNode.normalize) {\n nativeConvolverNode.normalize = !options.disableNormalization;\n }\n\n assignNativeAudioNodeOption(nativeConvolverNode, options, 'buffer');\n\n // Bug #113: Safari does allow to set the channelCount to a value larger than 2.\n if (options.channelCount > 2) {\n throw createNotSupportedError();\n }\n\n overwriteAccessors(\n nativeConvolverNode,\n 'channelCount',\n (get) => () => get.call(nativeConvolverNode),\n (set) => (value) => {\n if (value > 2) {\n throw createNotSupportedError();\n }\n\n return set.call(nativeConvolverNode, value);\n }\n );\n\n // Bug #114: Safari allows to set the channelCountMode to 'max'.\n if (options.channelCountMode === 'max') {\n throw createNotSupportedError();\n }\n\n overwriteAccessors(\n nativeConvolverNode,\n 'channelCountMode',\n (get) => () => get.call(nativeConvolverNode),\n (set) => (value) => {\n if (value === 'max') {\n throw createNotSupportedError();\n }\n\n return set.call(nativeConvolverNode, value);\n }\n );\n\n return nativeConvolverNode;\n };\n};\n","import { assignNativeAudioNodeAudioParamValue } from '../helpers/assign-native-audio-node-audio-param-value';\nimport { assignNativeAudioNodeOptions } from '../helpers/assign-native-audio-node-options';\nimport { TNativeDelayNodeFactory } from '../types';\n\nexport const createNativeDelayNode: TNativeDelayNodeFactory = (nativeContext, options) => {\n const nativeDelayNode = nativeContext.createDelay(options.maxDelayTime);\n\n assignNativeAudioNodeOptions(nativeDelayNode, options);\n\n assignNativeAudioNodeAudioParamValue(nativeDelayNode, options, 'delayTime');\n\n return nativeDelayNode;\n};\n","import { assignNativeAudioNodeAudioParamValue } from '../helpers/assign-native-audio-node-audio-param-value';\nimport { assignNativeAudioNodeOptions } from '../helpers/assign-native-audio-node-options';\nimport { TNativeDynamicsCompressorNodeFactoryFactory } from '../types';\n\nexport const createNativeDynamicsCompressorNodeFactory: TNativeDynamicsCompressorNodeFactoryFactory = (createNotSupportedError) => {\n return (nativeContext, options) => {\n const nativeDynamicsCompressorNode = nativeContext.createDynamicsCompressor();\n\n assignNativeAudioNodeOptions(nativeDynamicsCompressorNode, options);\n\n // Bug #108: Safari allows a channelCount of three and above.\n if (options.channelCount > 2) {\n throw createNotSupportedError();\n }\n\n // Bug #109: Only Chrome and Firefox disallow a channelCountMode of 'max'.\n if (options.channelCountMode === 'max') {\n throw createNotSupportedError();\n }\n\n assignNativeAudioNodeAudioParamValue(nativeDynamicsCompressorNode, options, 'attack');\n assignNativeAudioNodeAudioParamValue(nativeDynamicsCompressorNode, options, 'knee');\n assignNativeAudioNodeAudioParamValue(nativeDynamicsCompressorNode, options, 'ratio');\n assignNativeAudioNodeAudioParamValue(nativeDynamicsCompressorNode, options, 'release');\n assignNativeAudioNodeAudioParamValue(nativeDynamicsCompressorNode, options, 'threshold');\n\n return nativeDynamicsCompressorNode;\n };\n};\n","import { assignNativeAudioNodeAudioParamValue } from '../helpers/assign-native-audio-node-audio-param-value';\nimport { assignNativeAudioNodeOptions } from '../helpers/assign-native-audio-node-options';\nimport { TNativeGainNodeFactory } from '../types';\n\nexport const createNativeGainNode: TNativeGainNodeFactory = (nativeContext, options) => {\n const nativeGainNode = nativeContext.createGain();\n\n assignNativeAudioNodeOptions(nativeGainNode, options);\n\n assignNativeAudioNodeAudioParamValue(nativeGainNode, options, 'gain');\n\n return nativeGainNode;\n};\n","import { assignNativeAudioNodeOptions } from '../helpers/assign-native-audio-node-options';\nimport { TNativeIIRFilterNodeFactoryFactory } from '../types';\n\nexport const createNativeIIRFilterNodeFactory: TNativeIIRFilterNodeFactoryFactory = (createNativeIIRFilterNodeFaker) => {\n return (nativeContext, baseLatency, options) => {\n // Bug #9: Safari does not support IIRFilterNodes.\n if (nativeContext.createIIRFilter === undefined) {\n return createNativeIIRFilterNodeFaker(nativeContext, baseLatency, options);\n }\n\n // @todo TypeScript defines the parameters of createIIRFilter() as arrays of numbers.\n const nativeIIRFilterNode = nativeContext.createIIRFilter(<number[]>options.feedforward, <number[]>options.feedback);\n\n assignNativeAudioNodeOptions(nativeIIRFilterNode, options);\n\n return nativeIIRFilterNode;\n };\n};\n","import { computeBufferSize } from '../helpers/compute-buffer-size';\nimport { filterBuffer } from '../helpers/filter-buffer';\nimport { interceptConnections } from '../helpers/intercept-connections';\nimport { TNativeAudioNode, TNativeIIRFilterNode, TNativeIIRFilterNodeFakerFactoryFactory } from '../types';\n\nfunction divide(a: [number, number], b: [number, number]): [number, number] {\n const denominator = b[0] * b[0] + b[1] * b[1];\n\n return [(a[0] * b[0] + a[1] * b[1]) / denominator, (a[1] * b[0] - a[0] * b[1]) / denominator];\n}\n\nfunction multiply(a: [number, number], b: [number, number]): [number, number] {\n return [a[0] * b[0] - a[1] * b[1], a[0] * b[1] + a[1] * b[0]];\n}\n\nfunction evaluatePolynomial(coefficient: Float64Array, z: [number, number]): [number, number] {\n let result: [number, number] = [0, 0];\n\n for (let i = coefficient.length - 1; i >= 0; i -= 1) {\n result = multiply(result, z);\n\n result[0] += coefficient[i];\n }\n\n return result;\n}\n\nexport const createNativeIIRFilterNodeFakerFactory: TNativeIIRFilterNodeFakerFactoryFactory = (\n createInvalidAccessError,\n createInvalidStateError,\n createNativeScriptProcessorNode,\n createNotSupportedError\n) => {\n return (nativeContext, baseLatency, { channelCount, channelCountMode, channelInterpretation, feedback, feedforward }) => {\n const bufferSize = computeBufferSize(baseLatency, nativeContext.sampleRate);\n const convertedFeedback = feedback instanceof Float64Array ? feedback : new Float64Array(feedback);\n const convertedFeedforward = feedforward instanceof Float64Array ? feedforward : new Float64Array(feedforward);\n const feedbackLength = convertedFeedback.length;\n const feedforwardLength = convertedFeedforward.length;\n const minLength = Math.min(feedbackLength, feedforwardLength);\n\n if (feedbackLength === 0 || feedbackLength > 20) {\n throw createNotSupportedError();\n }\n\n if (convertedFeedback[0] === 0) {\n throw createInvalidStateError();\n }\n\n if (feedforwardLength === 0 || feedforwardLength > 20) {\n throw createNotSupportedError();\n }\n\n if (convertedFeedforward[0] === 0) {\n throw createInvalidStateError();\n }\n\n if (convertedFeedback[0] !== 1) {\n for (let i = 0; i < feedforwardLength; i += 1) {\n convertedFeedforward[i] /= convertedFeedback[0];\n }\n\n for (let i = 1; i < feedbackLength; i += 1) {\n convertedFeedback[i] /= convertedFeedback[0];\n }\n }\n\n const scriptProcessorNode = createNativeScriptProcessorNode(nativeContext, bufferSize, channelCount, channelCount);\n\n scriptProcessorNode.channelCount = channelCount;\n scriptProcessorNode.channelCountMode = channelCountMode;\n scriptProcessorNode.channelInterpretation = channelInterpretation;\n\n const bufferLength = 32;\n const bufferIndexes: number[] = [];\n const xBuffers: Float32Array[] = [];\n const yBuffers: Float32Array[] = [];\n\n for (let i = 0; i < channelCount; i += 1) {\n bufferIndexes.push(0);\n\n const xBuffer = new Float32Array(bufferLength);\n const yBuffer = new Float32Array(bufferLength);\n\n xBuffer.fill(0);\n yBuffer.fill(0);\n\n xBuffers.push(xBuffer);\n yBuffers.push(yBuffer);\n }\n\n // tslint:disable-next-line:deprecation\n scriptProcessorNode.onaudioprocess = (event: AudioProcessingEvent) => {\n const inputBuffer = event.inputBuffer;\n const outputBuffer = event.outputBuffer;\n\n const numberOfChannels = inputBuffer.numberOfChannels;\n\n for (let i = 0; i < numberOfChannels; i += 1) {\n const input = inputBuffer.getChannelData(i);\n const output = outputBuffer.getChannelData(i);\n\n bufferIndexes[i] = filterBuffer(\n convertedFeedback,\n feedbackLength,\n convertedFeedforward,\n feedforwardLength,\n minLength,\n xBuffers[i],\n yBuffers[i],\n bufferIndexes[i],\n bufferLength,\n input,\n output\n );\n }\n };\n\n const nyquist = nativeContext.sampleRate / 2;\n\n const nativeIIRFilterNodeFaker = {\n get bufferSize(): number {\n return bufferSize;\n },\n get channelCount(): number {\n return scriptProcessorNode.channelCount;\n },\n set channelCount(value) {\n scriptProcessorNode.channelCount = value;\n },\n get channelCountMode(): TNativeIIRFilterNode['channelCountMode'] {\n return scriptProcessorNode.channelCountMode;\n },\n set channelCountMode(value) {\n scriptProcessorNode.channelCountMode = value;\n },\n get channelInterpretation(): TNativeIIRFilterNode['channelInterpretation'] {\n return scriptProcessorNode.channelInterpretation;\n },\n set channelInterpretation(value) {\n scriptProcessorNode.channelInterpretation = value;\n },\n get context(): TNativeIIRFilterNode['context'] {\n return scriptProcessorNode.context;\n },\n get inputs(): TNativeAudioNode[] {\n return [scriptProcessorNode];\n },\n get numberOfInputs(): number {\n return scriptProcessorNode.numberOfInputs;\n },\n get numberOfOutputs(): number {\n return scriptProcessorNode.numberOfOutputs;\n },\n addEventListener(...args: any[]): void {\n // @todo Dissallow adding an audioprocess listener.\n return scriptProcessorNode.addEventListener(args[0], args[1], args[2]);\n },\n dispatchEvent(...args: any[]): boolean {\n return scriptProcessorNode.dispatchEvent(args[0]);\n },\n getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void {\n if (frequencyHz.length !== magResponse.length || magResponse.length !== phaseResponse.length) {\n throw createInvalidAccessError();\n }\n\n const length = frequencyHz.length;\n\n for (let i = 0; i < length; i += 1) {\n const omega = -Math.PI * (frequencyHz[i] / nyquist);\n const z: [number, number] = [Math.cos(omega), Math.sin(omega)];\n const numerator = evaluatePolynomial(convertedFeedforward, z);\n const denominator = evaluatePolynomial(convertedFeedback, z);\n const response = divide(numerator, denominator);\n\n magResponse[i] = Math.sqrt(response[0] * response[0] + response[1] * response[1]);\n phaseResponse[i] = Math.atan2(response[1], response[0]);\n }\n },\n removeEventListener(...args: any[]): void {\n return scriptProcessorNode.removeEventListener(args[0], args[1], args[2]);\n }\n };\n\n return interceptConnections(nativeIIRFilterNodeFaker, scriptProcessorNode);\n };\n};\n","import { TNativeMediaElementAudioSourceNodeFactory } from '../types';\n\nexport const createNativeMediaElementAudioSourceNode: TNativeMediaElementAudioSourceNodeFactory = (nativeAudioContext, options) => {\n return nativeAudioContext.createMediaElementSource(options.mediaElement);\n};\n","import { assignNativeAudioNodeOptions } from '../helpers/assign-native-audio-node-options';\nimport { TNativeMediaStreamAudioDestinationNodeFactory } from '../types';\n\nexport const createNativeMediaStreamAudioDestinationNode: TNativeMediaStreamAudioDestinationNodeFactory = (nativeAudioContext, options) => {\n const nativeMediaStreamAudioDestinationNode = nativeAudioContext.createMediaStreamDestination();\n\n assignNativeAudioNodeOptions(nativeMediaStreamAudioDestinationNode, options);\n\n // Bug #174: Safari does expose a wrong numberOfOutputs.\n if (nativeMediaStreamAudioDestinationNode.numberOfOutputs === 1) {\n Object.defineProperty(nativeMediaStreamAudioDestinationNode, 'numberOfOutputs', { get: () => 0 });\n }\n\n return nativeMediaStreamAudioDestinationNode;\n};\n","import { TNativeMediaStreamAudioSourceNodeFactory } from '../types';\n\nexport const createNativeMediaStreamAudioSourceNode: TNativeMediaStreamAudioSourceNodeFactory = (nativeAudioContext, { mediaStream }) => {\n const audioStreamTracks = mediaStream.getAudioTracks();\n /*\n * Bug #151: Safari does not use the audio track as input anymore if it gets removed from the mediaStream after construction.\n * Bug #159: Safari picks the first audio track if the MediaStream has more than one audio track.\n */\n audioStreamTracks.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));\n\n const filteredAudioStreamTracks = audioStreamTracks.slice(0, 1);\n\n const nativeMediaStreamAudioSourceNode = nativeAudioContext.createMediaStreamSource(new MediaStream(filteredAudioStreamTracks));\n\n /*\n * Bug #151 & #159: The given mediaStream gets reconstructed before it gets passed to the native node which is why the accessor needs\n * to be overwritten as it would otherwise expose the reconstructed version.\n */\n Object.defineProperty(nativeMediaStreamAudioSourceNode, 'mediaStream', { value: mediaStream });\n\n return nativeMediaStreamAudioSourceNode;\n};\n","import { TNativeMediaStreamTrackAudioSourceNodeFactoryFactory } from '../types';\n\nexport const createNativeMediaStreamTrackAudioSourceNodeFactory: TNativeMediaStreamTrackAudioSourceNodeFactoryFactory = (\n createInvalidStateError,\n isNativeOfflineAudioContext\n) => {\n return (nativeAudioContext, { mediaStreamTrack }) => {\n // Bug #121: Only Firefox does yet support the MediaStreamTrackAudioSourceNode.\n if (typeof nativeAudioContext.createMediaStreamTrackSource === 'function') {\n return nativeAudioContext.createMediaStreamTrackSource(mediaStreamTrack);\n }\n\n const mediaStream = new MediaStream([mediaStreamTrack]);\n const nativeMediaStreamAudioSourceNode = nativeAudioContext.createMediaStreamSource(mediaStream);\n\n // Bug #120: Firefox does not throw an error if the mediaStream has no audio track.\n if (mediaStreamTrack.kind !== 'audio') {\n throw createInvalidStateError();\n }\n\n // Bug #172: Safari allows to create a MediaStreamAudioSourceNode with an OfflineAudioContext.\n if (isNativeOfflineAudioContext(nativeAudioContext)) {\n throw new TypeError();\n }\n\n return nativeMediaStreamAudioSourceNode;\n };\n};\n","import { TNativeOfflineAudioContextConstructorFactory } from '../types';\n\nexport const createNativeOfflineAudioContextConstructor: TNativeOfflineAudioContextConstructorFactory = (window) => {\n if (window === null) {\n return null;\n }\n\n if (window.hasOwnProperty('OfflineAudioContext')) {\n return window.OfflineAudioContext;\n }\n\n return window.hasOwnProperty('webkitOfflineAudioContext') ? (<any>window).webkitOfflineAudioContext : null;\n};\n","import { assignNativeAudioNodeAudioParamValue } from '../helpers/assign-native-audio-node-audio-param-value';\nimport { assignNativeAudioNodeOption } from '../helpers/assign-native-audio-node-option';\nimport { assignNativeAudioNodeOptions } from '../helpers/assign-native-audio-node-options';\nimport { wrapAudioScheduledSourceNodeStartMethodNegativeParameters } from '../helpers/wrap-audio-scheduled-source-node-start-method-negative-parameters';\nimport { wrapAudioScheduledSourceNodeStopMethodNegativeParameters } from '../helpers/wrap-audio-scheduled-source-node-stop-method-negative-parameters';\nimport { TNativeOscillatorNodeFactoryFactory } from '../types';\n\nexport const createNativeOscillatorNodeFactory: TNativeOscillatorNodeFactoryFactory = (\n addSilentConnection,\n cacheTestResult,\n testAudioScheduledSourceNodeStartMethodNegativeParametersSupport,\n testAudioScheduledSourceNodeStopMethodConsecutiveCallsSupport,\n testAudioScheduledSourceNodeStopMethodNegativeParametersSupport,\n wrapAudioScheduledSourceNodeStopMethodConsecutiveCalls\n) => {\n return (nativeContext, options) => {\n const nativeOscillatorNode = nativeContext.createOscillator();\n\n assignNativeAudioNodeOptions(nativeOscillatorNode, options);\n\n assignNativeAudioNodeAudioParamValue(nativeOscillatorNode, options, 'detune');\n assignNativeAudioNodeAudioParamValue(nativeOscillatorNode, options, 'frequency');\n\n if (options.periodicWave !== undefined) {\n nativeOscillatorNode.setPeriodicWave(options.periodicWave);\n } else {\n assignNativeAudioNodeOption(nativeOscillatorNode, options, 'type');\n }\n\n // Bug #44: Only Chrome & Edge throw a RangeError yet.\n if (\n !cacheTestResult(testAudioScheduledSourceNodeStartMethodNegativeParametersSupport, () =>\n testAudioScheduledSourceNodeStartMethodNegativeParametersSupport(nativeContext)\n )\n ) {\n wrapAudioScheduledSourceNodeStartMethodNegativeParameters(nativeOscillatorNode);\n }\n\n // Bug #19: Safari does not ignore calls to stop() of an already stopped AudioBufferSourceNode.\n if (\n !cacheTestResult(testAudioScheduledSourceNodeStopMethodConsecutiveCallsSupport, () =>\n testAudioScheduledSourceNodeStopMethodConsecutiveCallsSupport(nativeContext)\n )\n ) {\n wrapAudioScheduledSourceNodeStopMethodConsecutiveCalls(nativeOscillatorNode, nativeContext);\n }\n\n // Bug #44: Only Firefox does not throw a RangeError yet.\n if (\n !cacheTestResult(testAudioScheduledSourceNodeStopMethodNegativeParametersSupport, () =>\n testAudioScheduledSourceNodeStopMethodNegativeParametersSupport(nativeContext)\n )\n ) {\n wrapAudioScheduledSourceNodeStopMethodNegativeParameters(nativeOscillatorNode);\n }\n\n // Bug #175: Safari will not fire an ended event if the OscillatorNode is unconnected.\n addSilentConnection(nativeContext, nativeOscillatorNode);\n\n return nativeOscillatorNode;\n };\n};\n","import { assignNativeAudioNodeAudioParamValue } from '../helpers/assign-native-audio-node-audio-param-value';\nimport { assignNativeAudioNodeOption } from '../helpers/assign-native-audio-node-option';\nimport { assignNativeAudioNodeOptions } from '../helpers/assign-native-audio-node-options';\nimport { TNativePannerNodeFactoryFactory } from '../types';\n\nexport const createNativePannerNodeFactory: TNativePannerNodeFactoryFactory = (createNativePannerNodeFaker) => {\n return (nativeContext, options) => {\n const nativePannerNode = nativeContext.createPanner();\n\n // Bug #124: Safari does not support modifying the orientation and the position with AudioParams.\n if (nativePannerNode.orientationX === undefined) {\n return createNativePannerNodeFaker(nativeContext, options);\n }\n\n assignNativeAudioNodeOptions(nativePannerNode, options);\n\n assignNativeAudioNodeAudioParamValue(nativePannerNode, options, 'orientationX');\n assignNativeAudioNodeAudioParamValue(nativePannerNode, options, 'orientationY');\n assignNativeAudioNodeAudioParamValue(nativePannerNode, options, 'orientationZ');\n assignNativeAudioNodeAudioParamValue(nativePannerNode, options, 'positionX');\n assignNativeAudioNodeAudioParamValue(nativePannerNode, options, 'positionY');\n assignNativeAudioNodeAudioParamValue(nativePannerNode, options, 'positionZ');\n\n assignNativeAudioNodeOption(nativePannerNode, options, 'coneInnerAngle');\n assignNativeAudioNodeOption(nativePannerNode, options, 'coneOuterAngle');\n assignNativeAudioNodeOption(nativePannerNode, options, 'coneOuterGain');\n assignNativeAudioNodeOption(nativePannerNode, options, 'distanceModel');\n assignNativeAudioNodeOption(nativePannerNode, options, 'maxDistance');\n assignNativeAudioNodeOption(nativePannerNode, options, 'panningModel');\n assignNativeAudioNodeOption(nativePannerNode, options, 'refDistance');\n assignNativeAudioNodeOption(nativePannerNode, options, 'rolloffFactor');\n\n return nativePannerNode;\n };\n};\n","import { assignNativeAudioNodeOptions } from '../helpers/assign-native-audio-node-options';\nimport { interceptConnections } from '../helpers/intercept-connections';\nimport { TNativeAudioNode, TNativePannerNode, TNativePannerNodeFakerFactoryFactory } from '../types';\n\nexport const createNativePannerNodeFakerFactory: TNativePannerNodeFakerFactoryFactory = (\n connectNativeAudioNodeToNativeAudioNode,\n createInvalidStateError,\n createNativeChannelMergerNode,\n createNativeGainNode,\n createNativeScriptProcessorNode,\n createNativeWaveShaperNode,\n createNotSupportedError,\n disconnectNativeAudioNodeFromNativeAudioNode,\n getFirstSample,\n monitorConnections\n) => {\n return (\n nativeContext,\n {\n coneInnerAngle,\n coneOuterAngle,\n coneOuterGain,\n distanceModel,\n maxDistance,\n orientationX,\n orientationY,\n orientationZ,\n panningModel,\n positionX,\n positionY,\n positionZ,\n refDistance,\n rolloffFactor,\n ...audioNodeOptions\n }\n ) => {\n const pannerNode = nativeContext.createPanner();\n\n // Bug #125: Safari does not throw an error yet.\n if (audioNodeOptions.channelCount > 2) {\n throw createNotSupportedError();\n }\n\n // Bug #126: Safari does not throw an error yet.\n if (audioNodeOptions.channelCountMode === 'max') {\n throw createNotSupportedError();\n }\n\n assignNativeAudioNodeOptions(pannerNode, audioNodeOptions);\n\n const SINGLE_CHANNEL_OPTIONS = {\n channelCount: 1,\n channelCountMode: 'explicit',\n channelInterpretation: 'discrete'\n } as const;\n\n const channelMergerNode = createNativeChannelMergerNode(nativeContext, {\n ...SINGLE_CHANNEL_OPTIONS,\n channelInterpretation: 'speakers',\n numberOfInputs: 6\n });\n const inputGainNode = createNativeGainNode(nativeContext, { ...audioNodeOptions, gain: 1 });\n const orientationXGainNode = createNativeGainNode(nativeContext, { ...SINGLE_CHANNEL_OPTIONS, gain: 1 });\n const orientationYGainNode = createNativeGainNode(nativeContext, { ...SINGLE_CHANNEL_OPTIONS, gain: 0 });\n const orientationZGainNode = createNativeGainNode(nativeContext, { ...SINGLE_CHANNEL_OPTIONS, gain: 0 });\n const positionXGainNode = createNativeGainNode(nativeContext, { ...SINGLE_CHANNEL_OPTIONS, gain: 0 });\n const positionYGainNode = createNativeGainNode(nativeContext, { ...SINGLE_CHANNEL_OPTIONS, gain: 0 });\n const positionZGainNode = createNativeGainNode(nativeContext, { ...SINGLE_CHANNEL_OPTIONS, gain: 0 });\n const scriptProcessorNode = createNativeScriptProcessorNode(nativeContext, 256, 6, 1);\n const waveShaperNode = createNativeWaveShaperNode(nativeContext, {\n ...SINGLE_CHANNEL_OPTIONS,\n curve: new Float32Array([1, 1]),\n oversample: 'none'\n });\n\n let lastOrientation: [number, number, number] = [orientationX, orientationY, orientationZ];\n let lastPosition: [number, number, number] = [positionX, positionY, positionZ];\n\n const buffer = new Float32Array(1);\n\n // tslint:disable-next-line:deprecation\n scriptProcessorNode.onaudioprocess = ({ inputBuffer }) => {\n const orientation: [number, number, number] = [\n getFirstSample(inputBuffer, buffer, 0),\n getFirstSample(inputBuffer, buffer, 1),\n getFirstSample(inputBuffer, buffer, 2)\n ];\n\n if (orientation.some((value, index) => value !== lastOrientation[index])) {\n pannerNode.setOrientation(...orientation); // tslint:disable-line:deprecation\n\n lastOrientation = orientation;\n }\n\n const positon: [number, number, number] = [\n getFirstSample(inputBuffer, buffer, 3),\n getFirstSample(inputBuffer, buffer, 4),\n getFirstSample(inputBuffer, buffer, 5)\n ];\n\n if (positon.some((value, index) => value !== lastPosition[index])) {\n pannerNode.setPosition(...positon); // tslint:disable-line:deprecation\n\n lastPosition = positon;\n }\n };\n\n Object.defineProperty(orientationYGainNode.gain, 'defaultValue', { get: () => 0 });\n Object.defineProperty(orientationZGainNode.gain, 'defaultValue', { get: () => 0 });\n Object.defineProperty(positionXGainNode.gain, 'defaultValue', { get: () => 0 });\n Object.defineProperty(positionYGainNode.gain, 'defaultValue', { get: () => 0 });\n Object.defineProperty(positionZGainNode.gain, 'defaultValue', { get: () => 0 });\n\n const nativePannerNodeFaker = {\n get bufferSize(): undefined {\n return undefined;\n },\n get channelCount(): number {\n return pannerNode.channelCount;\n },\n set channelCount(value) {\n // Bug #125: Safari does not throw an error yet.\n if (value > 2) {\n throw createNotSupportedError();\n }\n\n inputGainNode.channelCount = value;\n pannerNode.channelCount = value;\n },\n get channelCountMode(): TNativePannerNode['channelCountMode'] {\n return pannerNode.channelCountMode;\n },\n set channelCountMode(value) {\n // Bug #126: Safari does not throw an error yet.\n if (value === 'max') {\n throw createNotSupportedError();\n }\n\n inputGainNode.channelCountMode = value;\n pannerNode.channelCountMode = value;\n },\n get channelInterpretation(): TNativePannerNode['channelInterpretation'] {\n return pannerNode.channelInterpretation;\n },\n set channelInterpretation(value) {\n inputGainNode.channelInterpretation = value;\n pannerNode.channelInterpretation = value;\n },\n get coneInnerAngle(): TNativePannerNode['coneInnerAngle'] {\n return pannerNode.coneInnerAngle;\n },\n set coneInnerAngle(value) {\n pannerNode.coneInnerAngle = value;\n },\n get coneOuterAngle(): TNativePannerNode['coneOuterAngle'] {\n return pannerNode.coneOuterAngle;\n },\n set coneOuterAngle(value) {\n pannerNode.coneOuterAngle = value;\n },\n get coneOuterGain(): TNativePannerNode['coneOuterGain'] {\n return pannerNode.coneOuterGain;\n },\n set coneOuterGain(value) {\n // Bug #127: Safari does not throw an InvalidStateError yet.\n if (value < 0 || value > 1) {\n throw createInvalidStateError();\n }\n\n pannerNode.coneOuterGain = value;\n },\n get context(): TNativePannerNode['context'] {\n return pannerNode.context;\n },\n get distanceModel(): TNativePannerNode['distanceModel'] {\n return pannerNode.distanceModel;\n },\n set distanceModel(value) {\n pannerNode.distanceModel = value;\n },\n get inputs(): TNativeAudioNode[] {\n return [inputGainNode];\n },\n get maxDistance(): TNativePannerNode['maxDistance'] {\n return pannerNode.maxDistance;\n },\n set maxDistance(value) {\n // Bug #128: Safari does not throw an error yet.\n if (value < 0) {\n throw new RangeError();\n }\n\n pannerNode.maxDistance = value;\n },\n get numberOfInputs(): number {\n return pannerNode.numberOfInputs;\n },\n get numberOfOutputs(): number {\n return pannerNode.numberOfOutputs;\n },\n get orientationX(): TNativePannerNode['orientationX'] {\n return orientationXGainNode.gain;\n },\n get orientationY(): TNativePannerNode['orientationY'] {\n return orientationYGainNode.gain;\n },\n get orientationZ(): TNativePannerNode['orientationZ'] {\n return orientationZGainNode.gain;\n },\n get panningModel(): TNativePannerNode['panningModel'] {\n return pannerNode.panningModel;\n },\n set panningModel(value) {\n pannerNode.panningModel = value;\n },\n get positionX(): TNativePannerNode['positionX'] {\n return positionXGainNode.gain;\n },\n get positionY(): TNativePannerNode['positionY'] {\n return positionYGainNode.gain;\n },\n get positionZ(): TNativePannerNode['positionZ'] {\n return positionZGainNode.gain;\n },\n get refDistance(): TNativePannerNode['refDistance'] {\n return pannerNode.refDistance;\n },\n set refDistance(value) {\n // Bug #129: Safari does not throw an error yet.\n if (value < 0) {\n throw new RangeError();\n }\n\n pannerNode.refDistance = value;\n },\n get rolloffFactor(): TNativePannerNode['rolloffFactor'] {\n return pannerNode.rolloffFactor;\n },\n set rolloffFactor(value) {\n // Bug #130: Safari does not throw an error yet.\n if (value < 0) {\n throw new RangeError();\n }\n\n pannerNode.rolloffFactor = value;\n },\n addEventListener(...args: any[]): void {\n return inputGainNode.addEventListener(args[0], args[1], args[2]);\n },\n dispatchEvent(...args: any[]): boolean {\n return inputGainNode.dispatchEvent(args[0]);\n },\n removeEventListener(...args: any[]): void {\n return inputGainNode.removeEventListener(args[0], args[1], args[2]);\n }\n };\n\n if (coneInnerAngle !== nativePannerNodeFaker.coneInnerAngle) {\n nativePannerNodeFaker.coneInnerAngle = coneInnerAngle;\n }\n\n if (coneOuterAngle !== nativePannerNodeFaker.coneOuterAngle) {\n nativePannerNodeFaker.coneOuterAngle = coneOuterAngle;\n }\n\n if (coneOuterGain !== nativePannerNodeFaker.coneOuterGain) {\n nativePannerNodeFaker.coneOuterGain = coneOuterGain;\n }\n\n if (distanceModel !== nativePannerNodeFaker.distanceModel) {\n nativePannerNodeFaker.distanceModel = distanceModel;\n }\n\n if (maxDistance !== nativePannerNodeFaker.maxDistance) {\n nativePannerNodeFaker.maxDistance = maxDistance;\n }\n\n if (orientationX !== nativePannerNodeFaker.orientationX.value) {\n nativePannerNodeFaker.orientationX.value = orientationX;\n }\n\n if (orientationY !== nativePannerNodeFaker.orientationY.value) {\n nativePannerNodeFaker.orientationY.value = orientationY;\n }\n\n if (orientationZ !== nativePannerNodeFaker.orientationZ.value) {\n nativePannerNodeFaker.orientationZ.value = orientationZ;\n }\n\n if (panningModel !== nativePannerNodeFaker.panningModel) {\n nativePannerNodeFaker.panningModel = panningModel;\n }\n\n if (positionX !== nativePannerNodeFaker.positionX.value) {\n nativePannerNodeFaker.positionX.value = positionX;\n }\n\n if (positionY !== nativePannerNodeFaker.positionY.value) {\n nativePannerNodeFaker.positionY.value = positionY;\n }\n\n if (positionZ !== nativePannerNodeFaker.positionZ.value) {\n nativePannerNodeFaker.positionZ.value = positionZ;\n }\n\n if (refDistance !== nativePannerNodeFaker.refDistance) {\n nativePannerNodeFaker.refDistance = refDistance;\n }\n\n if (rolloffFactor !== nativePannerNodeFaker.rolloffFactor) {\n nativePannerNodeFaker.rolloffFactor = rolloffFactor;\n }\n\n if (lastOrientation[0] !== 1 || lastOrientation[1] !== 0 || lastOrientation[2] !== 0) {\n pannerNode.setOrientation(...lastOrientation); // tslint:disable-line:deprecation\n }\n\n if (lastPosition[0] !== 0 || lastPosition[1] !== 0 || lastPosition[2] !== 0) {\n pannerNode.setPosition(...lastPosition); // tslint:disable-line:deprecation\n }\n\n const whenConnected = () => {\n inputGainNode.connect(pannerNode);\n\n // Bug #119: Safari does not fully support the WaveShaperNode.\n connectNativeAudioNodeToNativeAudioNode(inputGainNode, waveShaperNode, 0, 0);\n\n waveShaperNode.connect(orientationXGainNode).connect(channelMergerNode, 0, 0);\n waveShaperNode.connect(orientationYGainNode).connect(channelMergerNode, 0, 1);\n waveShaperNode.connect(orientationZGainNode).connect(channelMergerNode, 0, 2);\n waveShaperNode.connect(positionXGainNode).connect(channelMergerNode, 0, 3);\n waveShaperNode.connect(positionYGainNode).connect(channelMergerNode, 0, 4);\n waveShaperNode.connect(positionZGainNode).connect(channelMergerNode, 0, 5);\n\n channelMergerNode.connect(scriptProcessorNode).connect(nativeContext.destination);\n };\n const whenDisconnected = () => {\n inputGainNode.disconnect(pannerNode);\n\n // Bug #119: Safari does not fully support the WaveShaperNode.\n disconnectNativeAudioNodeFromNativeAudioNode(inputGainNode, waveShaperNode, 0, 0);\n\n waveShaperNode.disconnect(orientationXGainNode);\n orientationXGainNode.disconnect(channelMergerNode);\n waveShaperNode.disconnect(orientationYGainNode);\n orientationYGainNode.disconnect(channelMergerNode);\n waveShaperNode.disconnect(orientationZGainNode);\n orientationZGainNode.disconnect(channelMergerNode);\n waveShaperNode.disconnect(positionXGainNode);\n positionXGainNode.disconnect(channelMergerNode);\n waveShaperNode.disconnect(positionYGainNode);\n positionYGainNode.disconnect(channelMergerNode);\n waveShaperNode.disconnect(positionZGainNode);\n positionZGainNode.disconnect(channelMergerNode);\n\n channelMergerNode.disconnect(scriptProcessorNode);\n scriptProcessorNode.disconnect(nativeContext.destination);\n };\n\n return monitorConnections(interceptConnections(nativePannerNodeFaker, pannerNode), whenConnected, whenDisconnected);\n };\n};\n","import { TNativePeriodicWaveFactoryFactory } from '../types';\n\nexport const createNativePeriodicWaveFactory: TNativePeriodicWaveFactoryFactory = (createIndexSizeError) => {\n return (nativeContext, { disableNormalization, imag, real }) => {\n // Bug #180: Safari does not allow to use ordinary arrays.\n const convertedImag = imag instanceof Float32Array ? imag : new Float32Array(imag);\n const convertedReal = real instanceof Float32Array ? real : new Float32Array(real);\n\n const nativePeriodicWave = nativeContext.createPeriodicWave(convertedReal, convertedImag, { disableNormalization });\n\n // Bug #181: Safari does not throw an IndexSizeError so far if the given arrays have less than two values.\n if (Array.from(imag).length < 2) {\n throw createIndexSizeError();\n }\n\n return nativePeriodicWave;\n };\n};\n","import { TNativeScriptProcessorNodeFactory } from '../types';\n\nexport const createNativeScriptProcessorNode: TNativeScriptProcessorNodeFactory = (\n nativeContext,\n bufferSize,\n numberOfInputChannels,\n numberOfOutputChannels\n) => {\n return nativeContext.createScriptProcessor(bufferSize, numberOfInputChannels, numberOfOutputChannels); // tslint:disable-line deprecation\n};\n","import { assignNativeAudioNodeAudioParamValue } from '../helpers/assign-native-audio-node-audio-param-value';\nimport { assignNativeAudioNodeOptions } from '../helpers/assign-native-audio-node-options';\nimport { TNativeStereoPannerNodeFactoryFactory } from '../types';\n\nexport const createNativeStereoPannerNodeFactory: TNativeStereoPannerNodeFactoryFactory = (\n createNativeStereoPannerNodeFaker,\n createNotSupportedError\n) => {\n return (nativeContext, options) => {\n const channelCountMode = options.channelCountMode;\n\n /*\n * Bug #105: The channelCountMode of 'clamped-max' should be supported. However it is not possible to write a polyfill for Safari\n * which supports it and therefore it can't be supported at all.\n */\n if (channelCountMode === 'clamped-max') {\n throw createNotSupportedError();\n }\n\n // Bug #105: Safari does not support the StereoPannerNode.\n if (nativeContext.createStereoPanner === undefined) {\n return createNativeStereoPannerNodeFaker(nativeContext, options);\n }\n\n const nativeStereoPannerNode = nativeContext.createStereoPanner();\n\n assignNativeAudioNodeOptions(nativeStereoPannerNode, options);\n\n assignNativeAudioNodeAudioParamValue(nativeStereoPannerNode, options, 'pan');\n\n /*\n * Bug #105: The channelCountMode of 'clamped-max' should be supported. However it is not possible to write a polyfill for Safari\n * which supports it and therefore it can't be supported at all.\n */\n Object.defineProperty(nativeStereoPannerNode, 'channelCountMode', {\n get: () => channelCountMode,\n set: (value) => {\n if (value !== channelCountMode) {\n throw createNotSupportedError();\n }\n }\n });\n\n return nativeStereoPannerNode;\n };\n};\n","import { interceptConnections } from '../helpers/intercept-connections';\nimport { INativeWaveShaperNodeFaker } from '../interfaces';\nimport {\n TNativeAudioNode,\n TNativeChannelMergerNode,\n TNativeContext,\n TNativeGainNode,\n TNativeStereoPannerNode,\n TNativeStereoPannerNodeFakerFactoryFactory\n} from '../types';\n\nexport const createNativeStereoPannerNodeFakerFactory: TNativeStereoPannerNodeFakerFactoryFactory = (\n createNativeChannelMergerNode,\n createNativeChannelSplitterNode,\n createNativeGainNode,\n createNativeWaveShaperNode,\n createNotSupportedError,\n monitorConnections\n) => {\n // The curve has a size of 14bit plus 1 value to have an exact representation for zero. This value has been determined experimentally.\n const CURVE_SIZE = 16385;\n const DC_CURVE = new Float32Array([1, 1]);\n const HALF_PI = Math.PI / 2;\n const SINGLE_CHANNEL_OPTIONS = { channelCount: 1, channelCountMode: 'explicit', channelInterpretation: 'discrete' } as const;\n const SINGLE_CHANNEL_WAVE_SHAPER_OPTIONS = { ...SINGLE_CHANNEL_OPTIONS, oversample: 'none' } as const;\n\n const buildInternalGraphForMono = (\n nativeContext: TNativeContext,\n inputGainNode: TNativeGainNode,\n panGainNode: TNativeGainNode,\n channelMergerNode: TNativeChannelMergerNode\n ) => {\n const leftWaveShaperCurve = new Float32Array(CURVE_SIZE);\n const rightWaveShaperCurve = new Float32Array(CURVE_SIZE);\n\n for (let i = 0; i < CURVE_SIZE; i += 1) {\n const x = (i / (CURVE_SIZE - 1)) * HALF_PI;\n\n leftWaveShaperCurve[i] = Math.cos(x);\n rightWaveShaperCurve[i] = Math.sin(x);\n }\n\n const leftGainNode = createNativeGainNode(nativeContext, { ...SINGLE_CHANNEL_OPTIONS, gain: 0 });\n // Bug #119: Safari does not fully support the WaveShaperNode.\n const leftWaveShaperNode = <INativeWaveShaperNodeFaker>(\n createNativeWaveShaperNode(nativeContext, { ...SINGLE_CHANNEL_WAVE_SHAPER_OPTIONS, curve: leftWaveShaperCurve })\n );\n // Bug #119: Safari does not fully support the WaveShaperNode.\n const panWaveShaperNode = <INativeWaveShaperNodeFaker>(\n createNativeWaveShaperNode(nativeContext, { ...SINGLE_CHANNEL_WAVE_SHAPER_OPTIONS, curve: DC_CURVE })\n );\n const rightGainNode = createNativeGainNode(nativeContext, { ...SINGLE_CHANNEL_OPTIONS, gain: 0 });\n // Bug #119: Safari does not fully support the WaveShaperNode.\n const rightWaveShaperNode = <INativeWaveShaperNodeFaker>(\n createNativeWaveShaperNode(nativeContext, { ...SINGLE_CHANNEL_WAVE_SHAPER_OPTIONS, curve: rightWaveShaperCurve })\n );\n\n return {\n connectGraph(): void {\n inputGainNode.connect(leftGainNode);\n inputGainNode.connect(panWaveShaperNode.inputs === undefined ? panWaveShaperNode : panWaveShaperNode.inputs[0]);\n inputGainNode.connect(rightGainNode);\n\n panWaveShaperNode.connect(panGainNode);\n\n panGainNode.connect(leftWaveShaperNode.inputs === undefined ? leftWaveShaperNode : leftWaveShaperNode.inputs[0]);\n panGainNode.connect(rightWaveShaperNode.inputs === undefined ? rightWaveShaperNode : rightWaveShaperNode.inputs[0]);\n\n leftWaveShaperNode.connect(leftGainNode.gain);\n rightWaveShaperNode.connect(rightGainNode.gain);\n\n leftGainNode.connect(channelMergerNode, 0, 0);\n rightGainNode.connect(channelMergerNode, 0, 1);\n },\n disconnectGraph(): void {\n inputGainNode.disconnect(leftGainNode);\n inputGainNode.disconnect(panWaveShaperNode.inputs === undefined ? panWaveShaperNode : panWaveShaperNode.inputs[0]);\n inputGainNode.disconnect(rightGainNode);\n\n panWaveShaperNode.disconnect(panGainNode);\n\n panGainNode.disconnect(leftWaveShaperNode.inputs === undefined ? leftWaveShaperNode : leftWaveShaperNode.inputs[0]);\n panGainNode.disconnect(rightWaveShaperNode.inputs === undefined ? rightWaveShaperNode : rightWaveShaperNode.inputs[0]);\n\n leftWaveShaperNode.disconnect(leftGainNode.gain);\n rightWaveShaperNode.disconnect(rightGainNode.gain);\n\n leftGainNode.disconnect(channelMergerNode, 0, 0);\n rightGainNode.disconnect(channelMergerNode, 0, 1);\n }\n };\n };\n\n const buildInternalGraphForStereo = (\n nativeContext: TNativeContext,\n inputGainNode: TNativeGainNode,\n panGainNode: TNativeGainNode,\n channelMergerNode: TNativeChannelMergerNode\n ) => {\n const leftInputForLeftOutputWaveShaperCurve = new Float32Array(CURVE_SIZE);\n const leftInputForRightOutputWaveShaperCurve = new Float32Array(CURVE_SIZE);\n const rightInputForLeftOutputWaveShaperCurve = new Float32Array(CURVE_SIZE);\n const rightInputForRightOutputWaveShaperCurve = new Float32Array(CURVE_SIZE);\n\n const centerIndex = Math.floor(CURVE_SIZE / 2);\n\n for (let i = 0; i < CURVE_SIZE; i += 1) {\n if (i > centerIndex) {\n const x = ((i - centerIndex) / (CURVE_SIZE - 1 - centerIndex)) * HALF_PI;\n\n leftInputForLeftOutputWaveShaperCurve[i] = Math.cos(x);\n leftInputForRightOutputWaveShaperCurve[i] = Math.sin(x);\n rightInputForLeftOutputWaveShaperCurve[i] = 0;\n rightInputForRightOutputWaveShaperCurve[i] = 1;\n } else {\n const x = (i / (CURVE_SIZE - 1 - centerIndex)) * HALF_PI;\n\n leftInputForLeftOutputWaveShaperCurve[i] = 1;\n leftInputForRightOutputWaveShaperCurve[i] = 0;\n rightInputForLeftOutputWaveShaperCurve[i] = Math.cos(x);\n rightInputForRightOutputWaveShaperCurve[i] = Math.sin(x);\n }\n }\n\n const channelSplitterNode = createNativeChannelSplitterNode(nativeContext, {\n channelCount: 2,\n channelCountMode: 'explicit',\n channelInterpretation: 'discrete',\n numberOfOutputs: 2\n });\n const leftInputForLeftOutputGainNode = createNativeGainNode(nativeContext, { ...SINGLE_CHANNEL_OPTIONS, gain: 0 });\n // Bug #119: Safari does not fully support the WaveShaperNode.\n const leftInputForLeftOutputWaveShaperNode = <INativeWaveShaperNodeFaker>createNativeWaveShaperNode(nativeContext, {\n ...SINGLE_CHANNEL_WAVE_SHAPER_OPTIONS,\n curve: leftInputForLeftOutputWaveShaperCurve\n });\n const leftInputForRightOutputGainNode = createNativeGainNode(nativeContext, { ...SINGLE_CHANNEL_OPTIONS, gain: 0 });\n // Bug #119: Safari does not fully support the WaveShaperNode.\n const leftInputForRightOutputWaveShaperNode = <INativeWaveShaperNodeFaker>createNativeWaveShaperNode(nativeContext, {\n ...SINGLE_CHANNEL_WAVE_SHAPER_OPTIONS,\n curve: leftInputForRightOutputWaveShaperCurve\n });\n // Bug #119: Safari does not fully support the WaveShaperNode.\n const panWaveShaperNode = <INativeWaveShaperNodeFaker>(\n createNativeWaveShaperNode(nativeContext, { ...SINGLE_CHANNEL_WAVE_SHAPER_OPTIONS, curve: DC_CURVE })\n );\n const rightInputForLeftOutputGainNode = createNativeGainNode(nativeContext, { ...SINGLE_CHANNEL_OPTIONS, gain: 0 });\n // Bug #119: Safari does not fully support the WaveShaperNode.\n const rightInputForLeftOutputWaveShaperNode = <INativeWaveShaperNodeFaker>createNativeWaveShaperNode(nativeContext, {\n ...SINGLE_CHANNEL_WAVE_SHAPER_OPTIONS,\n curve: rightInputForLeftOutputWaveShaperCurve\n });\n const rightInputForRightOutputGainNode = createNativeGainNode(nativeContext, { ...SINGLE_CHANNEL_OPTIONS, gain: 0 });\n // Bug #119: Safari does not fully support the WaveShaperNode.\n const rightInputForRightOutputWaveShaperNode = <INativeWaveShaperNodeFaker>createNativeWaveShaperNode(nativeContext, {\n ...SINGLE_CHANNEL_WAVE_SHAPER_OPTIONS,\n curve: rightInputForRightOutputWaveShaperCurve\n });\n\n return {\n connectGraph(): void {\n inputGainNode.connect(channelSplitterNode);\n inputGainNode.connect(panWaveShaperNode.inputs === undefined ? panWaveShaperNode : panWaveShaperNode.inputs[0]);\n\n channelSplitterNode.connect(leftInputForLeftOutputGainNode, 0);\n channelSplitterNode.connect(leftInputForRightOutputGainNode, 0);\n channelSplitterNode.connect(rightInputForLeftOutputGainNode, 1);\n channelSplitterNode.connect(rightInputForRightOutputGainNode, 1);\n\n panWaveShaperNode.connect(panGainNode);\n\n panGainNode.connect(\n leftInputForLeftOutputWaveShaperNode.inputs === undefined\n ? leftInputForLeftOutputWaveShaperNode\n : leftInputForLeftOutputWaveShaperNode.inputs[0]\n );\n panGainNode.connect(\n leftInputForRightOutputWaveShaperNode.inputs === undefined\n ? leftInputForRightOutputWaveShaperNode\n : leftInputForRightOutputWaveShaperNode.inputs[0]\n );\n panGainNode.connect(\n rightInputForLeftOutputWaveShaperNode.inputs === undefined\n ? rightInputForLeftOutputWaveShaperNode\n : rightInputForLeftOutputWaveShaperNode.inputs[0]\n );\n panGainNode.connect(\n rightInputForRightOutputWaveShaperNode.inputs === undefined\n ? rightInputForRightOutputWaveShaperNode\n : rightInputForRightOutputWaveShaperNode.inputs[0]\n );\n\n leftInputForLeftOutputWaveShaperNode.connect(leftInputForLeftOutputGainNode.gain);\n leftInputForRightOutputWaveShaperNode.connect(leftInputForRightOutputGainNode.gain);\n rightInputForLeftOutputWaveShaperNode.connect(rightInputForLeftOutputGainNode.gain);\n rightInputForRightOutputWaveShaperNode.connect(rightInputForRightOutputGainNode.gain);\n\n leftInputForLeftOutputGainNode.connect(channelMergerNode, 0, 0);\n rightInputForLeftOutputGainNode.connect(channelMergerNode, 0, 0);\n\n leftInputForRightOutputGainNode.connect(channelMergerNode, 0, 1);\n rightInputForRightOutputGainNode.connect(channelMergerNode, 0, 1);\n },\n disconnectGraph(): void {\n inputGainNode.disconnect(channelSplitterNode);\n inputGainNode.disconnect(panWaveShaperNode.inputs === undefined ? panWaveShaperNode : panWaveShaperNode.inputs[0]);\n\n channelSplitterNode.disconnect(leftInputForLeftOutputGainNode, 0);\n channelSplitterNode.disconnect(leftInputForRightOutputGainNode, 0);\n channelSplitterNode.disconnect(rightInputForLeftOutputGainNode, 1);\n channelSplitterNode.disconnect(rightInputForRightOutputGainNode, 1);\n\n panWaveShaperNode.disconnect(panGainNode);\n\n panGainNode.disconnect(\n leftInputForLeftOutputWaveShaperNode.inputs === undefined\n ? leftInputForLeftOutputWaveShaperNode\n : leftInputForLeftOutputWaveShaperNode.inputs[0]\n );\n panGainNode.disconnect(\n leftInputForRightOutputWaveShaperNode.inputs === undefined\n ? leftInputForRightOutputWaveShaperNode\n : leftInputForRightOutputWaveShaperNode.inputs[0]\n );\n panGainNode.disconnect(\n rightInputForLeftOutputWaveShaperNode.inputs === undefined\n ? rightInputForLeftOutputWaveShaperNode\n : rightInputForLeftOutputWaveShaperNode.inputs[0]\n );\n panGainNode.disconnect(\n rightInputForRightOutputWaveShaperNode.inputs === undefined\n ? rightInputForRightOutputWaveShaperNode\n : rightInputForRightOutputWaveShaperNode.inputs[0]\n );\n\n leftInputForLeftOutputWaveShaperNode.disconnect(leftInputForLeftOutputGainNode.gain);\n leftInputForRightOutputWaveShaperNode.disconnect(leftInputForRightOutputGainNode.gain);\n rightInputForLeftOutputWaveShaperNode.disconnect(rightInputForLeftOutputGainNode.gain);\n rightInputForRightOutputWaveShaperNode.disconnect(rightInputForRightOutputGainNode.gain);\n\n leftInputForLeftOutputGainNode.disconnect(channelMergerNode, 0, 0);\n rightInputForLeftOutputGainNode.disconnect(channelMergerNode, 0, 0);\n\n leftInputForRightOutputGainNode.disconnect(channelMergerNode, 0, 1);\n rightInputForRightOutputGainNode.disconnect(channelMergerNode, 0, 1);\n }\n };\n };\n\n const buildInternalGraph = (\n nativeContext: TNativeContext,\n channelCount: number,\n inputGainNode: TNativeGainNode,\n panGainNode: TNativeGainNode,\n channelMergerNode: TNativeChannelMergerNode\n ) => {\n if (channelCount === 1) {\n return buildInternalGraphForMono(nativeContext, inputGainNode, panGainNode, channelMergerNode);\n }\n\n if (channelCount === 2) {\n return buildInternalGraphForStereo(nativeContext, inputGainNode, panGainNode, channelMergerNode);\n }\n\n throw createNotSupportedError();\n };\n\n return (nativeContext, { channelCount, channelCountMode, pan, ...audioNodeOptions }) => {\n if (channelCountMode === 'max') {\n throw createNotSupportedError();\n }\n\n const channelMergerNode = createNativeChannelMergerNode(nativeContext, {\n ...audioNodeOptions,\n channelCount: 1,\n channelCountMode,\n numberOfInputs: 2\n });\n const inputGainNode = createNativeGainNode(nativeContext, { ...audioNodeOptions, channelCount, channelCountMode, gain: 1 });\n const panGainNode = createNativeGainNode(nativeContext, {\n channelCount: 1,\n channelCountMode: 'explicit',\n channelInterpretation: 'discrete',\n gain: pan\n });\n\n let { connectGraph, disconnectGraph } = buildInternalGraph(\n nativeContext,\n channelCount,\n inputGainNode,\n panGainNode,\n channelMergerNode\n );\n\n Object.defineProperty(panGainNode.gain, 'defaultValue', { get: () => 0 });\n Object.defineProperty(panGainNode.gain, 'maxValue', { get: () => 1 });\n Object.defineProperty(panGainNode.gain, 'minValue', { get: () => -1 });\n\n const nativeStereoPannerNodeFakerFactory = {\n get bufferSize(): undefined {\n return undefined;\n },\n get channelCount(): number {\n return inputGainNode.channelCount;\n },\n set channelCount(value) {\n if (inputGainNode.channelCount !== value) {\n if (isConnected) {\n disconnectGraph();\n }\n\n ({ connectGraph, disconnectGraph } = buildInternalGraph(\n nativeContext,\n value,\n inputGainNode,\n panGainNode,\n channelMergerNode\n ));\n\n if (isConnected) {\n connectGraph();\n }\n }\n\n inputGainNode.channelCount = value;\n },\n get channelCountMode(): TNativeStereoPannerNode['channelCountMode'] {\n return inputGainNode.channelCountMode;\n },\n set channelCountMode(value) {\n if (value === 'clamped-max' || value === 'max') {\n throw createNotSupportedError();\n }\n\n inputGainNode.channelCountMode = value;\n },\n get channelInterpretation(): TNativeStereoPannerNode['channelInterpretation'] {\n return inputGainNode.channelInterpretation;\n },\n set channelInterpretation(value) {\n inputGainNode.channelInterpretation = value;\n },\n get context(): TNativeStereoPannerNode['context'] {\n return inputGainNode.context;\n },\n get inputs(): TNativeAudioNode[] {\n return [inputGainNode];\n },\n get numberOfInputs(): number {\n return inputGainNode.numberOfInputs;\n },\n get numberOfOutputs(): number {\n return inputGainNode.numberOfOutputs;\n },\n get pan(): TNativeStereoPannerNode['pan'] {\n return panGainNode.gain;\n },\n addEventListener(...args: any[]): void {\n return inputGainNode.addEventListener(args[0], args[1], args[2]);\n },\n dispatchEvent(...args: any[]): boolean {\n return inputGainNode.dispatchEvent(args[0]);\n },\n removeEventListener(...args: any[]): void {\n return inputGainNode.removeEventListener(args[0], args[1], args[2]);\n }\n };\n\n let isConnected = false;\n\n const whenConnected = () => {\n connectGraph();\n\n isConnected = true;\n };\n const whenDisconnected = () => {\n disconnectGraph();\n\n isConnected = false;\n };\n\n return monitorConnections(\n interceptConnections(nativeStereoPannerNodeFakerFactory, channelMergerNode),\n whenConnected,\n whenDisconnected\n );\n };\n};\n","import { assignNativeAudioNodeOption } from '../helpers/assign-native-audio-node-option';\nimport { assignNativeAudioNodeOptions } from '../helpers/assign-native-audio-node-options';\nimport { TNativeWaveShaperNodeFactoryFactory } from '../types';\n\nexport const createNativeWaveShaperNodeFactory: TNativeWaveShaperNodeFactoryFactory = (\n createConnectedNativeAudioBufferSourceNode,\n createInvalidStateError,\n createNativeWaveShaperNodeFaker,\n isDCCurve,\n monitorConnections,\n nativeAudioContextConstructor,\n overwriteAccessors\n) => {\n return (nativeContext, options) => {\n const nativeWaveShaperNode = nativeContext.createWaveShaper();\n\n /*\n * Bug #119: Safari does not correctly map the values.\n * @todo Unfortunately there is no way to test for this behavior in a synchronous fashion which is why testing for the existence of\n * the webkitAudioContext is used as a workaround here. Testing for the automationRate property is necessary because this workaround\n * isn't necessary anymore since v14.0.2 of Safari.\n */\n if (\n nativeAudioContextConstructor !== null &&\n nativeAudioContextConstructor.name === 'webkitAudioContext' &&\n nativeContext.createGain().gain.automationRate === undefined\n ) {\n return createNativeWaveShaperNodeFaker(nativeContext, options);\n }\n\n assignNativeAudioNodeOptions(nativeWaveShaperNode, options);\n\n const curve = options.curve === null || options.curve instanceof Float32Array ? options.curve : new Float32Array(options.curve);\n\n // Bug #104: Chrome and Edge will throw an InvalidAccessError when the curve has less than two samples.\n if (curve !== null && curve.length < 2) {\n throw createInvalidStateError();\n }\n\n // Only values of type Float32Array can be assigned to the curve property.\n assignNativeAudioNodeOption(nativeWaveShaperNode, { curve }, 'curve');\n assignNativeAudioNodeOption(nativeWaveShaperNode, options, 'oversample');\n\n let disconnectNativeAudioBufferSourceNode: null | (() => void) = null;\n let isConnected = false;\n\n overwriteAccessors(\n nativeWaveShaperNode,\n 'curve',\n (get) => () => get.call(nativeWaveShaperNode),\n (set) => (value) => {\n set.call(nativeWaveShaperNode, value);\n\n if (isConnected) {\n if (isDCCurve(value) && disconnectNativeAudioBufferSourceNode === null) {\n disconnectNativeAudioBufferSourceNode = createConnectedNativeAudioBufferSourceNode(\n nativeContext,\n nativeWaveShaperNode\n );\n } else if (!isDCCurve(value) && disconnectNativeAudioBufferSourceNode !== null) {\n disconnectNativeAudioBufferSourceNode();\n disconnectNativeAudioBufferSourceNode = null;\n }\n }\n\n return value;\n }\n );\n\n const whenConnected = () => {\n isConnected = true;\n\n if (isDCCurve(nativeWaveShaperNode.curve)) {\n disconnectNativeAudioBufferSourceNode = createConnectedNativeAudioBufferSourceNode(nativeContext, nativeWaveShaperNode);\n }\n };\n const whenDisconnected = () => {\n isConnected = false;\n\n if (disconnectNativeAudioBufferSourceNode !== null) {\n disconnectNativeAudioBufferSourceNode();\n disconnectNativeAudioBufferSourceNode = null;\n }\n };\n\n return monitorConnections(nativeWaveShaperNode, whenConnected, whenDisconnected);\n };\n};\n","import { assignNativeAudioNodeOptions } from '../helpers/assign-native-audio-node-options';\nimport { interceptConnections } from '../helpers/intercept-connections';\nimport { TNativeAudioNode, TNativeWaveShaperNode, TNativeWaveShaperNodeFakerFactoryFactory } from '../types';\n\nexport const createNativeWaveShaperNodeFakerFactory: TNativeWaveShaperNodeFakerFactoryFactory = (\n createConnectedNativeAudioBufferSourceNode,\n createInvalidStateError,\n createNativeGainNode,\n isDCCurve,\n monitorConnections\n) => {\n return (nativeContext, { curve, oversample, ...audioNodeOptions }) => {\n const negativeWaveShaperNode = nativeContext.createWaveShaper();\n const positiveWaveShaperNode = nativeContext.createWaveShaper();\n\n assignNativeAudioNodeOptions(negativeWaveShaperNode, audioNodeOptions);\n assignNativeAudioNodeOptions(positiveWaveShaperNode, audioNodeOptions);\n\n const inputGainNode = createNativeGainNode(nativeContext, { ...audioNodeOptions, gain: 1 });\n const invertGainNode = createNativeGainNode(nativeContext, { ...audioNodeOptions, gain: -1 });\n const outputGainNode = createNativeGainNode(nativeContext, { ...audioNodeOptions, gain: 1 });\n const revertGainNode = createNativeGainNode(nativeContext, { ...audioNodeOptions, gain: -1 });\n\n let disconnectNativeAudioBufferSourceNode: null | (() => void) = null;\n let isConnected = false;\n let unmodifiedCurve: null | TNativeWaveShaperNode['curve'] = null;\n\n const nativeWaveShaperNodeFaker = {\n get bufferSize(): undefined {\n return undefined;\n },\n get channelCount(): number {\n return negativeWaveShaperNode.channelCount;\n },\n set channelCount(value) {\n inputGainNode.channelCount = value;\n invertGainNode.channelCount = value;\n negativeWaveShaperNode.channelCount = value;\n outputGainNode.channelCount = value;\n positiveWaveShaperNode.channelCount = value;\n revertGainNode.channelCount = value;\n },\n get channelCountMode(): TNativeWaveShaperNode['channelCountMode'] {\n return negativeWaveShaperNode.channelCountMode;\n },\n set channelCountMode(value) {\n inputGainNode.channelCountMode = value;\n invertGainNode.channelCountMode = value;\n negativeWaveShaperNode.channelCountMode = value;\n outputGainNode.channelCountMode = value;\n positiveWaveShaperNode.channelCountMode = value;\n revertGainNode.channelCountMode = value;\n },\n get channelInterpretation(): TNativeWaveShaperNode['channelInterpretation'] {\n return negativeWaveShaperNode.channelInterpretation;\n },\n set channelInterpretation(value) {\n inputGainNode.channelInterpretation = value;\n invertGainNode.channelInterpretation = value;\n negativeWaveShaperNode.channelInterpretation = value;\n outputGainNode.channelInterpretation = value;\n positiveWaveShaperNode.channelInterpretation = value;\n revertGainNode.channelInterpretation = value;\n },\n get context(): TNativeWaveShaperNode['context'] {\n return negativeWaveShaperNode.context;\n },\n get curve(): TNativeWaveShaperNode['curve'] {\n return unmodifiedCurve;\n },\n set curve(value) {\n // Bug #102: Safari does not throw an InvalidStateError when the curve has less than two samples.\n if (value !== null && value.length < 2) {\n throw createInvalidStateError();\n }\n\n if (value === null) {\n negativeWaveShaperNode.curve = value;\n positiveWaveShaperNode.curve = value;\n } else {\n const curveLength = value.length;\n\n const negativeCurve = new Float32Array(curveLength + 2 - (curveLength % 2));\n const positiveCurve = new Float32Array(curveLength + 2 - (curveLength % 2));\n\n negativeCurve[0] = value[0];\n positiveCurve[0] = -value[curveLength - 1];\n\n const length = Math.ceil((curveLength + 1) / 2);\n const centerIndex = (curveLength + 1) / 2 - 1;\n\n for (let i = 1; i < length; i += 1) {\n const theoreticIndex = (i / length) * centerIndex;\n\n const lowerIndex = Math.floor(theoreticIndex);\n const upperIndex = Math.ceil(theoreticIndex);\n\n negativeCurve[i] =\n lowerIndex === upperIndex\n ? value[lowerIndex]\n : (1 - (theoreticIndex - lowerIndex)) * value[lowerIndex] +\n (1 - (upperIndex - theoreticIndex)) * value[upperIndex];\n positiveCurve[i] =\n lowerIndex === upperIndex\n ? -value[curveLength - 1 - lowerIndex]\n : -((1 - (theoreticIndex - lowerIndex)) * value[curveLength - 1 - lowerIndex]) -\n (1 - (upperIndex - theoreticIndex)) * value[curveLength - 1 - upperIndex];\n }\n\n negativeCurve[length] = curveLength % 2 === 1 ? value[length - 1] : (value[length - 2] + value[length - 1]) / 2;\n\n negativeWaveShaperNode.curve = negativeCurve;\n positiveWaveShaperNode.curve = positiveCurve;\n }\n\n unmodifiedCurve = value;\n\n if (isConnected) {\n if (isDCCurve(unmodifiedCurve) && disconnectNativeAudioBufferSourceNode === null) {\n disconnectNativeAudioBufferSourceNode = createConnectedNativeAudioBufferSourceNode(nativeContext, inputGainNode);\n } else if (disconnectNativeAudioBufferSourceNode !== null) {\n disconnectNativeAudioBufferSourceNode();\n disconnectNativeAudioBufferSourceNode = null;\n }\n }\n },\n get inputs(): TNativeAudioNode[] {\n return [inputGainNode];\n },\n get numberOfInputs(): number {\n return negativeWaveShaperNode.numberOfInputs;\n },\n get numberOfOutputs(): number {\n return negativeWaveShaperNode.numberOfOutputs;\n },\n get oversample(): TNativeWaveShaperNode['oversample'] {\n return negativeWaveShaperNode.oversample;\n },\n set oversample(value) {\n negativeWaveShaperNode.oversample = value;\n positiveWaveShaperNode.oversample = value;\n },\n addEventListener(...args: any[]): void {\n return inputGainNode.addEventListener(args[0], args[1], args[2]);\n },\n dispatchEvent(...args: any[]): boolean {\n return inputGainNode.dispatchEvent(args[0]);\n },\n removeEventListener(...args: any[]): void {\n return inputGainNode.removeEventListener(args[0], args[1], args[2]);\n }\n };\n\n if (curve !== null) {\n // Only values of type Float32Array can be assigned to the curve property.\n nativeWaveShaperNodeFaker.curve = curve instanceof Float32Array ? curve : new Float32Array(curve);\n }\n\n if (oversample !== nativeWaveShaperNodeFaker.oversample) {\n nativeWaveShaperNodeFaker.oversample = oversample;\n }\n\n const whenConnected = () => {\n inputGainNode.connect(negativeWaveShaperNode).connect(outputGainNode);\n\n inputGainNode.connect(invertGainNode).connect(positiveWaveShaperNode).connect(revertGainNode).connect(outputGainNode);\n\n isConnected = true;\n\n if (isDCCurve(unmodifiedCurve)) {\n disconnectNativeAudioBufferSourceNode = createConnectedNativeAudioBufferSourceNode(nativeContext, inputGainNode);\n }\n };\n const whenDisconnected = () => {\n inputGainNode.disconnect(negativeWaveShaperNode);\n negativeWaveShaperNode.disconnect(outputGainNode);\n\n inputGainNode.disconnect(invertGainNode);\n invertGainNode.disconnect(positiveWaveShaperNode);\n positiveWaveShaperNode.disconnect(revertGainNode);\n revertGainNode.disconnect(outputGainNode);\n\n isConnected = false;\n\n if (disconnectNativeAudioBufferSourceNode !== null) {\n disconnectNativeAudioBufferSourceNode();\n disconnectNativeAudioBufferSourceNode = null;\n }\n };\n\n return monitorConnections(interceptConnections(nativeWaveShaperNodeFaker, outputGainNode), whenConnected, whenDisconnected);\n };\n};\n","import { TNotSupportedErrorFactory } from '../types';\n\nexport const createNotSupportedError: TNotSupportedErrorFactory = () => new DOMException('', 'NotSupportedError');\n","import { deactivateAudioGraph } from '../helpers/deactivate-audio-graph';\nimport { testPromiseSupport } from '../helpers/test-promise-support';\nimport { IAudioBuffer, IOfflineAudioContext, IOfflineAudioContextOptions } from '../interfaces';\nimport { TAudioContextState, TNativeOfflineAudioContext, TOfflineAudioContextConstructorFactory } from '../types';\n\nconst DEFAULT_OPTIONS = {\n numberOfChannels: 1\n} as const;\n\nexport const createOfflineAudioContextConstructor: TOfflineAudioContextConstructorFactory = (\n baseAudioContextConstructor,\n cacheTestResult,\n createInvalidStateError,\n createNativeOfflineAudioContext,\n startRendering\n) => {\n return class OfflineAudioContext extends baseAudioContextConstructor<IOfflineAudioContext> implements IOfflineAudioContext {\n private _length: number;\n\n private _nativeOfflineAudioContext: TNativeOfflineAudioContext;\n\n private _state: null | TAudioContextState;\n\n constructor(options: IOfflineAudioContextOptions);\n constructor(numberOfChannels: number, length: number, sampleRate: number);\n constructor(a: number | IOfflineAudioContextOptions, b?: number, c?: number) {\n let options: IOfflineAudioContextOptions;\n\n if (typeof a === 'number' && b !== undefined && c !== undefined) {\n options = { length: b, numberOfChannels: a, sampleRate: c };\n } else if (typeof a === 'object') {\n options = a;\n } else {\n throw new Error('The given parameters are not valid.');\n }\n\n const { length, numberOfChannels, sampleRate } = { ...DEFAULT_OPTIONS, ...options };\n\n const nativeOfflineAudioContext = createNativeOfflineAudioContext(numberOfChannels, length, sampleRate);\n\n // #21 Safari does not support promises and therefore would fire the statechange event before the promise can be resolved.\n if (!cacheTestResult(testPromiseSupport, () => testPromiseSupport(nativeOfflineAudioContext))) {\n nativeOfflineAudioContext.addEventListener(\n 'statechange',\n (() => {\n let i = 0;\n\n const delayStateChangeEvent = (event: Event) => {\n if (this._state === 'running') {\n if (i > 0) {\n nativeOfflineAudioContext.removeEventListener('statechange', delayStateChangeEvent);\n event.stopImmediatePropagation();\n\n this._waitForThePromiseToSettle(event);\n } else {\n i += 1;\n }\n }\n };\n\n return delayStateChangeEvent;\n })()\n );\n }\n\n super(nativeOfflineAudioContext, numberOfChannels);\n\n this._length = length;\n this._nativeOfflineAudioContext = nativeOfflineAudioContext;\n this._state = null;\n }\n\n get length(): number {\n // Bug #17: Safari does not yet expose the length.\n if (this._nativeOfflineAudioContext.length === undefined) {\n return this._length;\n }\n\n return this._nativeOfflineAudioContext.length;\n }\n\n get state(): TAudioContextState {\n return this._state === null ? this._nativeOfflineAudioContext.state : this._state;\n }\n\n public startRendering(): Promise<IAudioBuffer> {\n /*\n * Bug #9 & #59: It is theoretically possible that startRendering() will first render a partialOfflineAudioContext. Therefore\n * the state of the nativeOfflineAudioContext might no transition to running immediately.\n */\n if (this._state === 'running') {\n return Promise.reject(createInvalidStateError());\n }\n\n this._state = 'running';\n\n return startRendering(this.destination, this._nativeOfflineAudioContext).finally(() => {\n this._state = null;\n\n deactivateAudioGraph(this);\n });\n }\n\n private _waitForThePromiseToSettle(event: Event): void {\n if (this._state === null) {\n this._nativeOfflineAudioContext.dispatchEvent(event);\n } else {\n setTimeout(() => this._waitForThePromiseToSettle(event));\n }\n }\n };\n};\n","import { isActiveAudioNode } from '../helpers/is-active-audio-node';\nimport { setInternalStateToActive } from '../helpers/set-internal-state-to-active';\nimport { setInternalStateToPassive } from '../helpers/set-internal-state-to-passive';\nimport {\n IAudioParam,\n IAudioScheduledSourceNodeEventMap,\n IMinimalOfflineAudioContext,\n IOscillatorNode,\n IOscillatorNodeRenderer,\n IOscillatorOptions\n} from '../interfaces';\nimport {\n TContext,\n TEventHandler,\n TNativeOscillatorNode,\n TOscillatorNodeConstructorFactory,\n TOscillatorNodeRenderer,\n TOscillatorType\n} from '../types';\n\nconst DEFAULT_OPTIONS = {\n channelCount: 2,\n channelCountMode: 'max', // This attribute has no effect for nodes with no inputs.\n channelInterpretation: 'speakers', // This attribute has no effect for nodes with no inputs.\n detune: 0,\n frequency: 440,\n periodicWave: undefined,\n type: 'sine'\n} as const;\n\nexport const createOscillatorNodeConstructor: TOscillatorNodeConstructorFactory = (\n audioNodeConstructor,\n createAudioParam,\n createNativeOscillatorNode,\n createOscillatorNodeRenderer,\n getNativeContext,\n isNativeOfflineAudioContext,\n wrapEventListener\n) => {\n return class OscillatorNode<T extends TContext>\n extends audioNodeConstructor<T, IAudioScheduledSourceNodeEventMap>\n implements IOscillatorNode<T>\n {\n private _detune: IAudioParam;\n\n private _frequency: IAudioParam;\n\n private _nativeOscillatorNode: TNativeOscillatorNode;\n\n private _onended: null | TEventHandler<this>;\n\n private _oscillatorNodeRenderer: TOscillatorNodeRenderer<T>;\n\n constructor(context: T, options?: Partial<IOscillatorOptions>) {\n const nativeContext = getNativeContext(context);\n const mergedOptions = { ...DEFAULT_OPTIONS, ...options };\n const nativeOscillatorNode = createNativeOscillatorNode(nativeContext, mergedOptions);\n const isOffline = isNativeOfflineAudioContext(nativeContext);\n const oscillatorNodeRenderer = <TOscillatorNodeRenderer<T>>(isOffline ? createOscillatorNodeRenderer() : null);\n const nyquist = context.sampleRate / 2;\n\n super(context, false, nativeOscillatorNode, oscillatorNodeRenderer);\n\n // Bug #81: Firefox & Safari do not export the correct values for maxValue and minValue.\n this._detune = createAudioParam(this, isOffline, nativeOscillatorNode.detune, 153600, -153600);\n // Bug #76: Safari does not export the correct values for maxValue and minValue.\n this._frequency = createAudioParam(this, isOffline, nativeOscillatorNode.frequency, nyquist, -nyquist);\n this._nativeOscillatorNode = nativeOscillatorNode;\n this._onended = null;\n this._oscillatorNodeRenderer = oscillatorNodeRenderer;\n\n if (this._oscillatorNodeRenderer !== null && mergedOptions.periodicWave !== undefined) {\n (<IOscillatorNodeRenderer<IMinimalOfflineAudioContext>>this._oscillatorNodeRenderer).periodicWave =\n mergedOptions.periodicWave;\n }\n }\n\n get detune(): IAudioParam {\n return this._detune;\n }\n\n get frequency(): IAudioParam {\n return this._frequency;\n }\n\n get onended(): null | TEventHandler<this> {\n return this._onended;\n }\n\n set onended(value) {\n const wrappedListener = typeof value === 'function' ? wrapEventListener(this, value) : null;\n\n this._nativeOscillatorNode.onended = wrappedListener;\n\n const nativeOnEnded = this._nativeOscillatorNode.onended;\n\n this._onended = nativeOnEnded !== null && nativeOnEnded === wrappedListener ? value : nativeOnEnded;\n }\n\n get type(): TOscillatorType {\n return this._nativeOscillatorNode.type;\n }\n\n set type(value) {\n this._nativeOscillatorNode.type = value;\n\n if (this._oscillatorNodeRenderer !== null) {\n this._oscillatorNodeRenderer.periodicWave = null;\n }\n }\n\n public setPeriodicWave(periodicWave: PeriodicWave): void {\n this._nativeOscillatorNode.setPeriodicWave(periodicWave);\n\n if (this._oscillatorNodeRenderer !== null) {\n this._oscillatorNodeRenderer.periodicWave = periodicWave;\n }\n }\n\n public start(when = 0): void {\n this._nativeOscillatorNode.start(when);\n\n if (this._oscillatorNodeRenderer !== null) {\n this._oscillatorNodeRenderer.start = when;\n }\n\n if (this.context.state !== 'closed') {\n setInternalStateToActive(this);\n\n const resetInternalStateToPassive = () => {\n this._nativeOscillatorNode.removeEventListener('ended', resetInternalStateToPassive);\n\n if (isActiveAudioNode(this)) {\n setInternalStateToPassive(this);\n }\n };\n\n this._nativeOscillatorNode.addEventListener('ended', resetInternalStateToPassive);\n }\n }\n\n public stop(when = 0): void {\n this._nativeOscillatorNode.stop(when);\n\n if (this._oscillatorNodeRenderer !== null) {\n this._oscillatorNodeRenderer.stop = when;\n }\n }\n };\n};\n","import { isOwnedByContext } from '../helpers/is-owned-by-context';\nimport { IMinimalOfflineAudioContext, IOfflineAudioContext, IOscillatorNode, IPeriodicWave } from '../interfaces';\nimport { TNativeOfflineAudioContext, TNativeOscillatorNode, TOscillatorNodeRendererFactoryFactory } from '../types';\n\nexport const createOscillatorNodeRendererFactory: TOscillatorNodeRendererFactoryFactory = (\n connectAudioParam,\n createNativeOscillatorNode,\n getNativeAudioNode,\n renderAutomation,\n renderInputsOfAudioNode\n) => {\n return <T extends IMinimalOfflineAudioContext | IOfflineAudioContext>() => {\n const renderedNativeOscillatorNodes = new WeakMap<TNativeOfflineAudioContext, TNativeOscillatorNode>();\n\n let periodicWave: null | IPeriodicWave = null;\n let start: null | number = null;\n let stop: null | number = null;\n\n const createOscillatorNode = async (proxy: IOscillatorNode<T>, nativeOfflineAudioContext: TNativeOfflineAudioContext) => {\n let nativeOscillatorNode = getNativeAudioNode<T, TNativeOscillatorNode>(proxy);\n\n // If the initially used nativeOscillatorNode was not constructed on the same OfflineAudioContext it needs to be created again.\n const nativeOscillatorNodeIsOwnedByContext = isOwnedByContext(nativeOscillatorNode, nativeOfflineAudioContext);\n\n if (!nativeOscillatorNodeIsOwnedByContext) {\n const options = {\n channelCount: nativeOscillatorNode.channelCount,\n channelCountMode: nativeOscillatorNode.channelCountMode,\n channelInterpretation: nativeOscillatorNode.channelInterpretation,\n detune: nativeOscillatorNode.detune.value,\n frequency: nativeOscillatorNode.frequency.value,\n periodicWave: periodicWave === null ? undefined : periodicWave,\n type: nativeOscillatorNode.type\n };\n\n nativeOscillatorNode = createNativeOscillatorNode(nativeOfflineAudioContext, options);\n\n if (start !== null) {\n nativeOscillatorNode.start(start);\n }\n\n if (stop !== null) {\n nativeOscillatorNode.stop(stop);\n }\n }\n\n renderedNativeOscillatorNodes.set(nativeOfflineAudioContext, nativeOscillatorNode);\n\n if (!nativeOscillatorNodeIsOwnedByContext) {\n await renderAutomation(nativeOfflineAudioContext, proxy.detune, nativeOscillatorNode.detune);\n await renderAutomation(nativeOfflineAudioContext, proxy.frequency, nativeOscillatorNode.frequency);\n } else {\n await connectAudioParam(nativeOfflineAudioContext, proxy.detune, nativeOscillatorNode.detune);\n await connectAudioParam(nativeOfflineAudioContext, proxy.frequency, nativeOscillatorNode.frequency);\n }\n\n await renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeOscillatorNode);\n\n return nativeOscillatorNode;\n };\n\n return {\n set periodicWave(value: null | IPeriodicWave) {\n periodicWave = value;\n },\n set start(value: number) {\n start = value;\n },\n set stop(value: number) {\n stop = value;\n },\n render(proxy: IOscillatorNode<T>, nativeOfflineAudioContext: TNativeOfflineAudioContext): Promise<TNativeOscillatorNode> {\n const renderedNativeOscillatorNode = renderedNativeOscillatorNodes.get(nativeOfflineAudioContext);\n\n if (renderedNativeOscillatorNode !== undefined) {\n return Promise.resolve(renderedNativeOscillatorNode);\n }\n\n return createOscillatorNode(proxy, nativeOfflineAudioContext);\n }\n };\n };\n};\n","import { MOST_NEGATIVE_SINGLE_FLOAT, MOST_POSITIVE_SINGLE_FLOAT } from '../constants';\nimport { IAudioParam, IPannerNode, IPannerOptions } from '../interfaces';\nimport {\n TAudioNodeRenderer,\n TContext,\n TDistanceModelType,\n TNativePannerNode,\n TPannerNodeConstructorFactory,\n TPanningModelType\n} from '../types';\n\nconst DEFAULT_OPTIONS = {\n channelCount: 2,\n channelCountMode: 'clamped-max',\n channelInterpretation: 'speakers',\n coneInnerAngle: 360,\n coneOuterAngle: 360,\n coneOuterGain: 0,\n distanceModel: 'inverse',\n maxDistance: 10000,\n orientationX: 1,\n orientationY: 0,\n orientationZ: 0,\n panningModel: 'equalpower',\n positionX: 0,\n positionY: 0,\n positionZ: 0,\n refDistance: 1,\n rolloffFactor: 1\n} as const;\n\nexport const createPannerNodeConstructor: TPannerNodeConstructorFactory = (\n audioNodeConstructor,\n createAudioParam,\n createNativePannerNode,\n createPannerNodeRenderer,\n getNativeContext,\n isNativeOfflineAudioContext,\n setAudioNodeTailTime\n) => {\n return class PannerNode<T extends TContext> extends audioNodeConstructor<T> implements IPannerNode<T> {\n private _nativePannerNode: TNativePannerNode;\n\n private _orientationX: IAudioParam;\n\n private _orientationY: IAudioParam;\n\n private _orientationZ: IAudioParam;\n\n private _positionX: IAudioParam;\n\n private _positionY: IAudioParam;\n\n private _positionZ: IAudioParam;\n\n constructor(context: T, options?: Partial<IPannerOptions>) {\n const nativeContext = getNativeContext(context);\n const mergedOptions = { ...DEFAULT_OPTIONS, ...options };\n const nativePannerNode = createNativePannerNode(nativeContext, mergedOptions);\n const isOffline = isNativeOfflineAudioContext(nativeContext);\n const pannerNodeRenderer = <TAudioNodeRenderer<T, this>>(isOffline ? createPannerNodeRenderer() : null);\n\n super(context, false, nativePannerNode, pannerNodeRenderer);\n\n this._nativePannerNode = nativePannerNode;\n // Bug #74: Safari does not export the correct values for maxValue and minValue.\n this._orientationX = createAudioParam(\n this,\n isOffline,\n nativePannerNode.orientationX,\n MOST_POSITIVE_SINGLE_FLOAT,\n MOST_NEGATIVE_SINGLE_FLOAT\n );\n this._orientationY = createAudioParam(\n this,\n isOffline,\n nativePannerNode.orientationY,\n MOST_POSITIVE_SINGLE_FLOAT,\n MOST_NEGATIVE_SINGLE_FLOAT\n );\n this._orientationZ = createAudioParam(\n this,\n isOffline,\n nativePannerNode.orientationZ,\n MOST_POSITIVE_SINGLE_FLOAT,\n MOST_NEGATIVE_SINGLE_FLOAT\n );\n this._positionX = createAudioParam(\n this,\n isOffline,\n nativePannerNode.positionX,\n MOST_POSITIVE_SINGLE_FLOAT,\n MOST_NEGATIVE_SINGLE_FLOAT\n );\n this._positionY = createAudioParam(\n this,\n isOffline,\n nativePannerNode.positionY,\n MOST_POSITIVE_SINGLE_FLOAT,\n MOST_NEGATIVE_SINGLE_FLOAT\n );\n this._positionZ = createAudioParam(\n this,\n isOffline,\n nativePannerNode.positionZ,\n MOST_POSITIVE_SINGLE_FLOAT,\n MOST_NEGATIVE_SINGLE_FLOAT\n );\n\n // @todo Determine a meaningful tail-time instead of just using one second.\n setAudioNodeTailTime(this, 1);\n }\n\n get coneInnerAngle(): number {\n return this._nativePannerNode.coneInnerAngle;\n }\n\n set coneInnerAngle(value) {\n this._nativePannerNode.coneInnerAngle = value;\n }\n\n get coneOuterAngle(): number {\n return this._nativePannerNode.coneOuterAngle;\n }\n\n set coneOuterAngle(value) {\n this._nativePannerNode.coneOuterAngle = value;\n }\n\n get coneOuterGain(): number {\n return this._nativePannerNode.coneOuterGain;\n }\n\n set coneOuterGain(value) {\n this._nativePannerNode.coneOuterGain = value;\n }\n\n get distanceModel(): TDistanceModelType {\n return this._nativePannerNode.distanceModel;\n }\n\n set distanceModel(value) {\n this._nativePannerNode.distanceModel = value;\n }\n\n get maxDistance(): number {\n return this._nativePannerNode.maxDistance;\n }\n\n set maxDistance(value) {\n this._nativePannerNode.maxDistance = value;\n }\n\n get orientationX(): IAudioParam {\n return this._orientationX;\n }\n\n get orientationY(): IAudioParam {\n return this._orientationY;\n }\n\n get orientationZ(): IAudioParam {\n return this._orientationZ;\n }\n\n get panningModel(): TPanningModelType {\n return this._nativePannerNode.panningModel;\n }\n\n set panningModel(value) {\n this._nativePannerNode.panningModel = value;\n }\n\n get positionX(): IAudioParam {\n return this._positionX;\n }\n\n get positionY(): IAudioParam {\n return this._positionY;\n }\n\n get positionZ(): IAudioParam {\n return this._positionZ;\n }\n\n get refDistance(): number {\n return this._nativePannerNode.refDistance;\n }\n\n set refDistance(value) {\n this._nativePannerNode.refDistance = value;\n }\n\n get rolloffFactor(): number {\n return this._nativePannerNode.rolloffFactor;\n }\n\n set rolloffFactor(value) {\n this._nativePannerNode.rolloffFactor = value;\n }\n };\n};\n","import { isNativeAudioNodeFaker } from '../guards/native-audio-node-faker';\nimport { isOwnedByContext } from '../helpers/is-owned-by-context';\nimport { IMinimalOfflineAudioContext, INativePannerNodeFaker, IOfflineAudioContext, IPannerNode } from '../interfaces';\nimport {\n TNativeAudioBuffer,\n TNativeGainNode,\n TNativeOfflineAudioContext,\n TNativePannerNode,\n TPannerNodeRendererFactoryFactory\n} from '../types';\n\nexport const createPannerNodeRendererFactory: TPannerNodeRendererFactoryFactory = (\n connectAudioParam,\n createNativeChannelMergerNode,\n createNativeConstantSourceNode,\n createNativeGainNode,\n createNativePannerNode,\n getNativeAudioNode,\n nativeOfflineAudioContextConstructor,\n renderAutomation,\n renderInputsOfAudioNode,\n renderNativeOfflineAudioContext\n) => {\n return <T extends IMinimalOfflineAudioContext | IOfflineAudioContext>() => {\n const renderedNativeAudioNodes = new WeakMap<TNativeOfflineAudioContext, TNativeGainNode | TNativePannerNode>();\n\n let renderedBufferPromise: null | Promise<TNativeAudioBuffer> = null;\n\n const createAudioNode = async (proxy: IPannerNode<T>, nativeOfflineAudioContext: TNativeOfflineAudioContext) => {\n let nativeGainNode: null | TNativeGainNode = null;\n let nativePannerNode = getNativeAudioNode<T, TNativePannerNode>(proxy);\n\n const commonAudioNodeOptions = {\n channelCount: nativePannerNode.channelCount,\n channelCountMode: nativePannerNode.channelCountMode,\n channelInterpretation: nativePannerNode.channelInterpretation\n };\n const commonNativePannerNodeOptions = {\n ...commonAudioNodeOptions,\n coneInnerAngle: nativePannerNode.coneInnerAngle,\n coneOuterAngle: nativePannerNode.coneOuterAngle,\n coneOuterGain: nativePannerNode.coneOuterGain,\n distanceModel: nativePannerNode.distanceModel,\n maxDistance: nativePannerNode.maxDistance,\n panningModel: nativePannerNode.panningModel,\n refDistance: nativePannerNode.refDistance,\n rolloffFactor: nativePannerNode.rolloffFactor\n };\n\n // If the initially used nativePannerNode was not constructed on the same OfflineAudioContext it needs to be created again.\n const nativePannerNodeIsOwnedByContext = isOwnedByContext(nativePannerNode, nativeOfflineAudioContext);\n\n // Bug #124: Safari does not support modifying the orientation and the position with AudioParams.\n if ('bufferSize' in nativePannerNode) {\n nativeGainNode = createNativeGainNode(nativeOfflineAudioContext, { ...commonAudioNodeOptions, gain: 1 });\n } else if (!nativePannerNodeIsOwnedByContext) {\n const options = {\n ...commonNativePannerNodeOptions,\n orientationX: nativePannerNode.orientationX.value,\n orientationY: nativePannerNode.orientationY.value,\n orientationZ: nativePannerNode.orientationZ.value,\n positionX: nativePannerNode.positionX.value,\n positionY: nativePannerNode.positionY.value,\n positionZ: nativePannerNode.positionZ.value\n };\n\n nativePannerNode = createNativePannerNode(nativeOfflineAudioContext, options);\n }\n\n renderedNativeAudioNodes.set(nativeOfflineAudioContext, nativeGainNode === null ? nativePannerNode : nativeGainNode);\n\n if (nativeGainNode !== null) {\n if (renderedBufferPromise === null) {\n if (nativeOfflineAudioContextConstructor === null) {\n throw new Error('Missing the native OfflineAudioContext constructor.');\n }\n\n const partialOfflineAudioContext = new nativeOfflineAudioContextConstructor(\n 6,\n // Bug #17: Safari does not yet expose the length.\n proxy.context.length,\n nativeOfflineAudioContext.sampleRate\n );\n const nativeChannelMergerNode = createNativeChannelMergerNode(partialOfflineAudioContext, {\n channelCount: 1,\n channelCountMode: 'explicit',\n channelInterpretation: 'speakers',\n numberOfInputs: 6\n });\n nativeChannelMergerNode.connect(partialOfflineAudioContext.destination);\n\n renderedBufferPromise = (async () => {\n const nativeConstantSourceNodes = await Promise.all(\n [\n proxy.orientationX,\n proxy.orientationY,\n proxy.orientationZ,\n proxy.positionX,\n proxy.positionY,\n proxy.positionZ\n ].map(async (audioParam, index) => {\n const nativeConstantSourceNode = createNativeConstantSourceNode(partialOfflineAudioContext, {\n channelCount: 1,\n channelCountMode: 'explicit',\n channelInterpretation: 'discrete',\n offset: index === 0 ? 1 : 0\n });\n\n await renderAutomation(partialOfflineAudioContext, audioParam, nativeConstantSourceNode.offset);\n\n return nativeConstantSourceNode;\n })\n );\n\n for (let i = 0; i < 6; i += 1) {\n nativeConstantSourceNodes[i].connect(nativeChannelMergerNode, 0, i);\n nativeConstantSourceNodes[i].start(0);\n }\n\n return renderNativeOfflineAudioContext(partialOfflineAudioContext);\n })();\n }\n\n const renderedBuffer = await renderedBufferPromise;\n const inputGainNode = createNativeGainNode(nativeOfflineAudioContext, { ...commonAudioNodeOptions, gain: 1 });\n\n await renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, inputGainNode);\n\n const channelDatas: Float32Array[] = [];\n\n for (let i = 0; i < renderedBuffer.numberOfChannels; i += 1) {\n channelDatas.push(renderedBuffer.getChannelData(i));\n }\n\n let lastOrientation = [channelDatas[0][0], channelDatas[1][0], channelDatas[2][0]];\n let lastPosition = [channelDatas[3][0], channelDatas[4][0], channelDatas[5][0]];\n let gateGainNode = createNativeGainNode(nativeOfflineAudioContext, { ...commonAudioNodeOptions, gain: 1 });\n let partialPannerNode = createNativePannerNode(nativeOfflineAudioContext, {\n ...commonNativePannerNodeOptions,\n orientationX: lastOrientation[0],\n orientationY: lastOrientation[1],\n orientationZ: lastOrientation[2],\n positionX: lastPosition[0],\n positionY: lastPosition[1],\n positionZ: lastPosition[2]\n });\n\n inputGainNode.connect(gateGainNode).connect((<INativePannerNodeFaker>partialPannerNode).inputs[0]);\n partialPannerNode.connect(nativeGainNode);\n\n for (let i = 128; i < renderedBuffer.length; i += 128) {\n const orientation: [number, number, number] = [channelDatas[0][i], channelDatas[1][i], channelDatas[2][i]];\n const positon: [number, number, number] = [channelDatas[3][i], channelDatas[4][i], channelDatas[5][i]];\n\n if (\n orientation.some((value, index) => value !== lastOrientation[index]) ||\n positon.some((value, index) => value !== lastPosition[index])\n ) {\n lastOrientation = orientation;\n lastPosition = positon;\n\n const currentTime = i / nativeOfflineAudioContext.sampleRate;\n\n gateGainNode.gain.setValueAtTime(0, currentTime);\n\n gateGainNode = createNativeGainNode(nativeOfflineAudioContext, { ...commonAudioNodeOptions, gain: 0 });\n partialPannerNode = createNativePannerNode(nativeOfflineAudioContext, {\n ...commonNativePannerNodeOptions,\n orientationX: lastOrientation[0],\n orientationY: lastOrientation[1],\n orientationZ: lastOrientation[2],\n positionX: lastPosition[0],\n positionY: lastPosition[1],\n positionZ: lastPosition[2]\n });\n\n gateGainNode.gain.setValueAtTime(1, currentTime);\n\n inputGainNode.connect(gateGainNode).connect((<INativePannerNodeFaker>partialPannerNode).inputs[0]);\n partialPannerNode.connect(nativeGainNode);\n }\n }\n\n return nativeGainNode;\n }\n\n if (!nativePannerNodeIsOwnedByContext) {\n await renderAutomation(nativeOfflineAudioContext, proxy.orientationX, nativePannerNode.orientationX);\n await renderAutomation(nativeOfflineAudioContext, proxy.orientationY, nativePannerNode.orientationY);\n await renderAutomation(nativeOfflineAudioContext, proxy.orientationZ, nativePannerNode.orientationZ);\n await renderAutomation(nativeOfflineAudioContext, proxy.positionX, nativePannerNode.positionX);\n await renderAutomation(nativeOfflineAudioContext, proxy.positionY, nativePannerNode.positionY);\n await renderAutomation(nativeOfflineAudioContext, proxy.positionZ, nativePannerNode.positionZ);\n } else {\n await connectAudioParam(nativeOfflineAudioContext, proxy.orientationX, nativePannerNode.orientationX);\n await connectAudioParam(nativeOfflineAudioContext, proxy.orientationY, nativePannerNode.orientationY);\n await connectAudioParam(nativeOfflineAudioContext, proxy.orientationZ, nativePannerNode.orientationZ);\n await connectAudioParam(nativeOfflineAudioContext, proxy.positionX, nativePannerNode.positionX);\n await connectAudioParam(nativeOfflineAudioContext, proxy.positionY, nativePannerNode.positionY);\n await connectAudioParam(nativeOfflineAudioContext, proxy.positionZ, nativePannerNode.positionZ);\n }\n\n if (isNativeAudioNodeFaker(nativePannerNode)) {\n await renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativePannerNode.inputs[0]);\n } else {\n await renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativePannerNode);\n }\n\n return nativePannerNode;\n };\n\n return {\n render(\n proxy: IPannerNode<T>,\n nativeOfflineAudioContext: TNativeOfflineAudioContext\n ): Promise<TNativeGainNode | TNativePannerNode> {\n const renderedNativeGainNodeOrNativePannerNode = renderedNativeAudioNodes.get(nativeOfflineAudioContext);\n\n if (renderedNativeGainNodeOrNativePannerNode !== undefined) {\n return Promise.resolve(renderedNativeGainNodeOrNativePannerNode);\n }\n\n return createAudioNode(proxy, nativeOfflineAudioContext);\n }\n };\n };\n};\n","import { IPeriodicWave, IPeriodicWaveOptions } from '../interfaces';\nimport { TContext, TPeriodicWaveConstructorFactory } from '../types';\n\nconst DEFAULT_OPTIONS = {\n disableNormalization: false\n} as const;\n\nexport const createPeriodicWaveConstructor: TPeriodicWaveConstructorFactory = (\n createNativePeriodicWave,\n getNativeContext,\n periodicWaveStore,\n sanitizePeriodicWaveOptions\n) => {\n return class PeriodicWave<T extends TContext> implements IPeriodicWave {\n constructor(context: T, options?: Partial<IPeriodicWaveOptions>) {\n const nativeContext = getNativeContext(context);\n const mergedOptions = sanitizePeriodicWaveOptions({ ...DEFAULT_OPTIONS, ...options });\n const periodicWave = createNativePeriodicWave(nativeContext, mergedOptions);\n\n periodicWaveStore.add(periodicWave);\n\n // This does violate all good pratices but it is used here to simplify the handling of periodic waves.\n return periodicWave;\n }\n\n public static [Symbol.hasInstance](instance: unknown): boolean {\n return (\n (instance !== null && typeof instance === 'object' && Object.getPrototypeOf(instance) === PeriodicWave.prototype) ||\n periodicWaveStore.has(<any>instance)\n );\n }\n };\n};\n","import { TRenderAutomationFactory } from '../types';\n\nexport const createRenderAutomation: TRenderAutomationFactory = (getAudioParamRenderer, renderInputsOfAudioParam) => {\n return (nativeOfflineAudioContext, audioParam, nativeAudioParam) => {\n const audioParamRenderer = getAudioParamRenderer(audioParam);\n\n audioParamRenderer.replay(nativeAudioParam);\n\n return renderInputsOfAudioParam(audioParam, nativeOfflineAudioContext, nativeAudioParam);\n };\n};\n","import { IAudioDestinationNode } from '../interfaces';\nimport { TRenderInputsOfAudioNodeFactory } from '../types';\n\nexport const createRenderInputsOfAudioNode: TRenderInputsOfAudioNodeFactory = (\n getAudioNodeConnections,\n getAudioNodeRenderer,\n isPartOfACycle\n) => {\n return async (audioNode, nativeOfflineAudioContext, nativeAudioNode) => {\n const audioNodeConnections = getAudioNodeConnections(audioNode);\n\n await Promise.all(\n audioNodeConnections.activeInputs\n .map((connections, input) =>\n Array.from(connections).map(async ([source, output]) => {\n const audioNodeRenderer = getAudioNodeRenderer(source);\n const renderedNativeAudioNode = await audioNodeRenderer.render(source, nativeOfflineAudioContext);\n const destination = <IAudioDestinationNode<typeof audioNode.context>>audioNode.context.destination;\n\n if (!isPartOfACycle(source) && (audioNode !== destination || !isPartOfACycle(audioNode))) {\n renderedNativeAudioNode.connect(nativeAudioNode, output, input);\n }\n })\n )\n .reduce((allRenderingPromises, renderingPromises) => [...allRenderingPromises, ...renderingPromises], [])\n );\n };\n};\n","import { IAudioParam, IMinimalOfflineAudioContext, IOfflineAudioContext } from '../interfaces';\nimport { TNativeAudioParam, TNativeOfflineAudioContext, TRenderInputsOfAudioParamFactory } from '../types';\n\nexport const createRenderInputsOfAudioParam: TRenderInputsOfAudioParamFactory = (\n getAudioNodeRenderer,\n getAudioParamConnections,\n isPartOfACycle\n) => {\n return async <T extends IMinimalOfflineAudioContext | IOfflineAudioContext>(\n audioParam: IAudioParam,\n nativeOfflineAudioContext: TNativeOfflineAudioContext,\n nativeAudioParam: TNativeAudioParam\n ): Promise<void> => {\n const audioParamConnections = getAudioParamConnections<T>(audioParam);\n\n await Promise.all(\n Array.from(audioParamConnections.activeInputs).map(async ([source, output]) => {\n const audioNodeRenderer = getAudioNodeRenderer(source);\n const renderedNativeAudioNode = await audioNodeRenderer.render(source, nativeOfflineAudioContext);\n\n if (!isPartOfACycle(source)) {\n renderedNativeAudioNode.connect(nativeAudioParam, output);\n }\n })\n );\n };\n};\n","import { testPromiseSupport } from '../helpers/test-promise-support';\nimport { IOfflineAudioCompletionEvent } from '../interfaces';\nimport { TNativeAudioBuffer, TRenderNativeOfflineAudioContextFactory } from '../types';\n\nexport const createRenderNativeOfflineAudioContext: TRenderNativeOfflineAudioContextFactory = (\n cacheTestResult,\n createNativeGainNode,\n createNativeScriptProcessorNode,\n testOfflineAudioContextCurrentTimeSupport\n) => {\n return (nativeOfflineAudioContext) => {\n // Bug #21: Safari does not support promises yet.\n if (cacheTestResult(testPromiseSupport, () => testPromiseSupport(nativeOfflineAudioContext))) {\n // Bug #158: Chrome and Edge do not advance currentTime if it is not accessed while rendering the audio.\n return Promise.resolve(\n cacheTestResult(testOfflineAudioContextCurrentTimeSupport, testOfflineAudioContextCurrentTimeSupport)\n ).then((isOfflineAudioContextCurrentTimeSupported) => {\n if (!isOfflineAudioContextCurrentTimeSupported) {\n const scriptProcessorNode = createNativeScriptProcessorNode(nativeOfflineAudioContext, 512, 0, 1);\n\n nativeOfflineAudioContext.oncomplete = () => {\n scriptProcessorNode.onaudioprocess = null; // tslint:disable-line:deprecation\n scriptProcessorNode.disconnect();\n };\n scriptProcessorNode.onaudioprocess = () => nativeOfflineAudioContext.currentTime; // tslint:disable-line:deprecation\n\n scriptProcessorNode.connect(nativeOfflineAudioContext.destination);\n }\n\n return nativeOfflineAudioContext.startRendering();\n });\n }\n\n return new Promise<TNativeAudioBuffer>((resolve) => {\n // Bug #48: Safari does not render an OfflineAudioContext without any connected node.\n const gainNode = createNativeGainNode(nativeOfflineAudioContext, {\n channelCount: 1,\n channelCountMode: 'explicit',\n channelInterpretation: 'discrete',\n gain: 0\n });\n\n nativeOfflineAudioContext.oncomplete = (event: IOfflineAudioCompletionEvent) => {\n gainNode.disconnect();\n\n resolve(event.renderedBuffer);\n };\n\n gainNode.connect(nativeOfflineAudioContext.destination);\n\n nativeOfflineAudioContext.startRendering();\n });\n };\n};\n","import { TSetActiveAudioWorkletNodeInputsFactory } from '../types';\n\nexport const createSetActiveAudioWorkletNodeInputs: TSetActiveAudioWorkletNodeInputsFactory = (activeAudioWorkletNodeInputsStore) => {\n return (nativeAudioWorkletNode, activeInputs) => {\n activeAudioWorkletNodeInputsStore.set(nativeAudioWorkletNode, activeInputs);\n };\n};\n","import { TSetAudioNodeTailTimeFactory } from '../types';\n\nexport const createSetAudioNodeTailTime: TSetAudioNodeTailTimeFactory = (audioNodeTailTimeStore) => {\n return (audioNode, tailTime) => audioNodeTailTimeStore.set(audioNode, tailTime);\n};\n","import { wrapAudioBufferGetChannelDataMethod } from '../helpers/wrap-audio-buffer-get-channel-data-method';\nimport { TStartRenderingFactory } from '../types';\n\nexport const createStartRendering: TStartRenderingFactory = (\n audioBufferStore,\n cacheTestResult,\n getAudioNodeRenderer,\n getUnrenderedAudioWorkletNodes,\n renderNativeOfflineAudioContext,\n testAudioBufferCopyChannelMethodsOutOfBoundsSupport,\n wrapAudioBufferCopyChannelMethods,\n wrapAudioBufferCopyChannelMethodsOutOfBounds\n) => {\n return (destination, nativeOfflineAudioContext) =>\n getAudioNodeRenderer(destination)\n .render(destination, nativeOfflineAudioContext)\n /*\n * Bug #86 & #87: Invoking the renderer of an AudioWorkletNode might be necessary if it has no direct or indirect connection to the\n * destination.\n */\n .then(() =>\n Promise.all(\n Array.from(getUnrenderedAudioWorkletNodes(nativeOfflineAudioContext)).map((audioWorkletNode) =>\n getAudioNodeRenderer(audioWorkletNode).render(audioWorkletNode, nativeOfflineAudioContext)\n )\n )\n )\n .then(() => renderNativeOfflineAudioContext(nativeOfflineAudioContext))\n .then((audioBuffer) => {\n // Bug #5: Safari does not support copyFromChannel() and copyToChannel().\n // Bug #100: Safari does throw a wrong error when calling getChannelData() with an out-of-bounds value.\n if (typeof audioBuffer.copyFromChannel !== 'function') {\n wrapAudioBufferCopyChannelMethods(audioBuffer);\n wrapAudioBufferGetChannelDataMethod(audioBuffer);\n // Bug #157: Firefox does not allow the bufferOffset to be out-of-bounds.\n } else if (\n !cacheTestResult(testAudioBufferCopyChannelMethodsOutOfBoundsSupport, () =>\n testAudioBufferCopyChannelMethodsOutOfBoundsSupport(audioBuffer)\n )\n ) {\n wrapAudioBufferCopyChannelMethodsOutOfBounds(audioBuffer);\n }\n\n audioBufferStore.add(audioBuffer);\n\n return audioBuffer;\n });\n};\n","import { IAudioParam, IStereoPannerNode, IStereoPannerOptions } from '../interfaces';\nimport { TAudioNodeRenderer, TContext, TStereoPannerNodeConstructorFactory } from '../types';\n\nconst DEFAULT_OPTIONS = {\n channelCount: 2,\n /*\n * Bug #105: The channelCountMode should be 'clamped-max' according to the spec but is set to 'explicit' to achieve consistent\n * behavior.\n */\n channelCountMode: 'explicit',\n channelInterpretation: 'speakers',\n pan: 0\n} as const;\n\nexport const createStereoPannerNodeConstructor: TStereoPannerNodeConstructorFactory = (\n audioNodeConstructor,\n createAudioParam,\n createNativeStereoPannerNode,\n createStereoPannerNodeRenderer,\n getNativeContext,\n isNativeOfflineAudioContext\n) => {\n return class StereoPannerNode<T extends TContext> extends audioNodeConstructor<T> implements IStereoPannerNode<T> {\n private _pan: IAudioParam;\n\n constructor(context: T, options?: Partial<IStereoPannerOptions>) {\n const nativeContext = getNativeContext(context);\n const mergedOptions = { ...DEFAULT_OPTIONS, ...options };\n const nativeStereoPannerNode = createNativeStereoPannerNode(nativeContext, mergedOptions);\n const isOffline = isNativeOfflineAudioContext(nativeContext);\n const stereoPannerNodeRenderer = <TAudioNodeRenderer<T, this>>(isOffline ? createStereoPannerNodeRenderer() : null);\n\n super(context, false, nativeStereoPannerNode, stereoPannerNodeRenderer);\n\n this._pan = createAudioParam(this, isOffline, nativeStereoPannerNode.pan);\n }\n\n get pan(): IAudioParam {\n return this._pan;\n }\n };\n};\n","import { isNativeAudioNodeFaker } from '../guards/native-audio-node-faker';\nimport { isOwnedByContext } from '../helpers/is-owned-by-context';\nimport { IMinimalOfflineAudioContext, IOfflineAudioContext, IStereoPannerNode } from '../interfaces';\nimport { TNativeOfflineAudioContext, TNativeStereoPannerNode, TStereoPannerNodeRendererFactoryFactory } from '../types';\n\nexport const createStereoPannerNodeRendererFactory: TStereoPannerNodeRendererFactoryFactory = (\n connectAudioParam,\n createNativeStereoPannerNode,\n getNativeAudioNode,\n renderAutomation,\n renderInputsOfAudioNode\n) => {\n return <T extends IMinimalOfflineAudioContext | IOfflineAudioContext>() => {\n const renderedNativeStereoPannerNodes = new WeakMap<TNativeOfflineAudioContext, TNativeStereoPannerNode>();\n\n const createStereoPannerNode = async (proxy: IStereoPannerNode<T>, nativeOfflineAudioContext: TNativeOfflineAudioContext) => {\n let nativeStereoPannerNode = getNativeAudioNode<T, TNativeStereoPannerNode>(proxy);\n\n /*\n * If the initially used nativeStereoPannerNode was not constructed on the same OfflineAudioContext it needs to be created\n * again.\n */\n const nativeStereoPannerNodeIsOwnedByContext = isOwnedByContext(nativeStereoPannerNode, nativeOfflineAudioContext);\n\n if (!nativeStereoPannerNodeIsOwnedByContext) {\n const options = {\n channelCount: nativeStereoPannerNode.channelCount,\n channelCountMode: nativeStereoPannerNode.channelCountMode,\n channelInterpretation: nativeStereoPannerNode.channelInterpretation,\n pan: nativeStereoPannerNode.pan.value\n };\n\n nativeStereoPannerNode = createNativeStereoPannerNode(nativeOfflineAudioContext, options);\n }\n\n renderedNativeStereoPannerNodes.set(nativeOfflineAudioContext, nativeStereoPannerNode);\n\n if (!nativeStereoPannerNodeIsOwnedByContext) {\n await renderAutomation(nativeOfflineAudioContext, proxy.pan, nativeStereoPannerNode.pan);\n } else {\n await connectAudioParam(nativeOfflineAudioContext, proxy.pan, nativeStereoPannerNode.pan);\n }\n\n if (isNativeAudioNodeFaker(nativeStereoPannerNode)) {\n await renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeStereoPannerNode.inputs[0]);\n } else {\n await renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeStereoPannerNode);\n }\n\n return nativeStereoPannerNode;\n };\n\n return {\n render(proxy: IStereoPannerNode<T>, nativeOfflineAudioContext: TNativeOfflineAudioContext): Promise<TNativeStereoPannerNode> {\n const renderedNativeStereoPannerNode = renderedNativeStereoPannerNodes.get(nativeOfflineAudioContext);\n\n if (renderedNativeStereoPannerNode !== undefined) {\n return Promise.resolve(renderedNativeStereoPannerNode);\n }\n\n return createStereoPannerNode(proxy, nativeOfflineAudioContext);\n }\n };\n };\n};\n","import { TTestAudioBufferConstructorSupportFactory } from '../types';\n\n// Bug #33: Safari exposes an AudioBuffer but it can't be used as a constructor.\nexport const createTestAudioBufferConstructorSupport: TTestAudioBufferConstructorSupportFactory = (nativeAudioBufferConstructor) => {\n return () => {\n if (nativeAudioBufferConstructor === null) {\n return false;\n }\n\n try {\n new nativeAudioBufferConstructor({ length: 1, sampleRate: 44100 }); // tslint:disable-line:no-unused-expression\n } catch {\n return false;\n }\n\n return true;\n };\n};\n","import { TTestAudioWorkletProcessorPostMessageSupportFactory } from '../types';\n\n// Bug #179: Firefox does not allow to transfer any buffer which has been passed to the process() method as an argument.\nexport const createTestAudioWorkletProcessorPostMessageSupport: TTestAudioWorkletProcessorPostMessageSupportFactory = (\n nativeAudioWorkletNodeConstructor,\n nativeOfflineAudioContextConstructor\n) => {\n return async () => {\n // Bug #61: If there is no native AudioWorkletNode it gets faked and therefore it is no problem if the it doesn't exist.\n if (nativeAudioWorkletNodeConstructor === null) {\n return true;\n }\n\n if (nativeOfflineAudioContextConstructor === null) {\n return false;\n }\n\n const blob = new Blob(\n ['class A extends AudioWorkletProcessor{process(i){this.port.postMessage(i,[i[0][0].buffer])}}registerProcessor(\"a\",A)'],\n {\n type: 'application/javascript; charset=utf-8'\n }\n );\n // Bug #141: Safari does not support creating an OfflineAudioContext with less than 44100 Hz.\n const offlineAudioContext = new nativeOfflineAudioContextConstructor(1, 128, 44100);\n const url = URL.createObjectURL(blob);\n\n let isEmittingMessageEvents = false;\n let isEmittingProcessorErrorEvents = false;\n\n try {\n await offlineAudioContext.audioWorklet.addModule(url);\n\n const audioWorkletNode = new nativeAudioWorkletNodeConstructor(offlineAudioContext, 'a', { numberOfOutputs: 0 });\n const oscillator = offlineAudioContext.createOscillator();\n\n audioWorkletNode.port.onmessage = () => (isEmittingMessageEvents = true);\n audioWorkletNode.onprocessorerror = () => (isEmittingProcessorErrorEvents = true);\n\n oscillator.connect(audioWorkletNode);\n oscillator.start(0);\n\n await offlineAudioContext.startRendering();\n\n // Bug #197: Safari does not deliver the messages before the promise returned by startRendering() resolves.\n await new Promise((resolve) => setTimeout(resolve));\n } catch {\n // Ignore errors.\n } finally {\n URL.revokeObjectURL(url);\n }\n\n return isEmittingMessageEvents && !isEmittingProcessorErrorEvents;\n };\n};\n","import { TTestOfflineAudioContextCurrentTimeSupportFactory } from '../types';\n\nexport const createTestOfflineAudioContextCurrentTimeSupport: TTestOfflineAudioContextCurrentTimeSupportFactory = (\n createNativeGainNode,\n nativeOfflineAudioContextConstructor\n) => {\n return () => {\n if (nativeOfflineAudioContextConstructor === null) {\n return Promise.resolve(false);\n }\n\n const nativeOfflineAudioContext = new nativeOfflineAudioContextConstructor(1, 1, 44100);\n\n // Bug #48: Safari does not render an OfflineAudioContext without any connected node.\n const gainNode = createNativeGainNode(nativeOfflineAudioContext, {\n channelCount: 1,\n channelCountMode: 'explicit',\n channelInterpretation: 'discrete',\n gain: 0\n });\n\n // Bug #21: Safari does not support promises yet.\n return new Promise((resolve) => {\n nativeOfflineAudioContext.oncomplete = () => {\n gainNode.disconnect();\n\n resolve(nativeOfflineAudioContext.currentTime !== 0);\n };\n nativeOfflineAudioContext.startRendering();\n });\n };\n};\n","import { TUnknownErrorFactory } from '../types';\n\nexport const createUnknownError: TUnknownErrorFactory = () => new DOMException('', 'UnknownError');\n","import { IWaveShaperNode, IWaveShaperOptions } from '../interfaces';\nimport { TAudioNodeRenderer, TContext, TNativeWaveShaperNode, TOverSampleType, TWaveShaperNodeConstructorFactory } from '../types';\n\nconst DEFAULT_OPTIONS = {\n channelCount: 2,\n channelCountMode: 'max',\n channelInterpretation: 'speakers',\n curve: null,\n oversample: 'none'\n} as const;\n\nexport const createWaveShaperNodeConstructor: TWaveShaperNodeConstructorFactory = (\n audioNodeConstructor,\n createInvalidStateError,\n createNativeWaveShaperNode,\n createWaveShaperNodeRenderer,\n getNativeContext,\n isNativeOfflineAudioContext,\n setAudioNodeTailTime\n) => {\n return class WaveShaperNode<T extends TContext> extends audioNodeConstructor<T> implements IWaveShaperNode<T> {\n private _isCurveNullified: boolean;\n\n private _nativeWaveShaperNode: TNativeWaveShaperNode;\n\n constructor(context: T, options?: Partial<IWaveShaperOptions>) {\n const nativeContext = getNativeContext(context);\n const mergedOptions = { ...DEFAULT_OPTIONS, ...options };\n const nativeWaveShaperNode = createNativeWaveShaperNode(nativeContext, mergedOptions);\n const isOffline = isNativeOfflineAudioContext(nativeContext);\n const waveShaperNodeRenderer = <TAudioNodeRenderer<T, this>>(isOffline ? createWaveShaperNodeRenderer() : null);\n\n // @todo Add a mechanism to only switch a WaveShaperNode to active while it is connected.\n super(context, true, nativeWaveShaperNode, waveShaperNodeRenderer);\n\n this._isCurveNullified = false;\n this._nativeWaveShaperNode = nativeWaveShaperNode;\n\n // @todo Determine a meaningful tail-time instead of just using one second.\n setAudioNodeTailTime(this, 1);\n }\n\n get curve(): null | Float32Array {\n if (this._isCurveNullified) {\n return null;\n }\n\n return this._nativeWaveShaperNode.curve;\n }\n\n set curve(value) {\n // Bug #103: Safari does not allow to set the curve to null.\n if (value === null) {\n this._isCurveNullified = true;\n this._nativeWaveShaperNode.curve = new Float32Array([0, 0]);\n } else {\n // Bug #102: Safari does not throw an InvalidStateError when the curve has less than two samples.\n // Bug #104: Chrome and Edge will throw an InvalidAccessError when the curve has less than two samples.\n if (value.length < 2) {\n throw createInvalidStateError();\n }\n\n this._isCurveNullified = false;\n this._nativeWaveShaperNode.curve = value;\n }\n }\n\n get oversample(): TOverSampleType {\n return this._nativeWaveShaperNode.oversample;\n }\n\n set oversample(value) {\n this._nativeWaveShaperNode.oversample = value;\n }\n };\n};\n","import { isNativeAudioNodeFaker } from '../guards/native-audio-node-faker';\nimport { isOwnedByContext } from '../helpers/is-owned-by-context';\nimport { IMinimalOfflineAudioContext, IOfflineAudioContext, IWaveShaperNode } from '../interfaces';\nimport { TNativeOfflineAudioContext, TNativeWaveShaperNode, TWaveShaperNodeRendererFactoryFactory } from '../types';\n\nexport const createWaveShaperNodeRendererFactory: TWaveShaperNodeRendererFactoryFactory = (\n createNativeWaveShaperNode,\n getNativeAudioNode,\n renderInputsOfAudioNode\n) => {\n return <T extends IMinimalOfflineAudioContext | IOfflineAudioContext>() => {\n const renderedNativeWaveShaperNodes = new WeakMap<TNativeOfflineAudioContext, TNativeWaveShaperNode>();\n\n const createWaveShaperNode = async (proxy: IWaveShaperNode<T>, nativeOfflineAudioContext: TNativeOfflineAudioContext) => {\n let nativeWaveShaperNode = getNativeAudioNode<T, TNativeWaveShaperNode>(proxy);\n\n // If the initially used nativeWaveShaperNode was not constructed on the same OfflineAudioContext it needs to be created again.\n const nativeWaveShaperNodeIsOwnedByContext = isOwnedByContext(nativeWaveShaperNode, nativeOfflineAudioContext);\n\n if (!nativeWaveShaperNodeIsOwnedByContext) {\n const options = {\n channelCount: nativeWaveShaperNode.channelCount,\n channelCountMode: nativeWaveShaperNode.channelCountMode,\n channelInterpretation: nativeWaveShaperNode.channelInterpretation,\n curve: nativeWaveShaperNode.curve,\n oversample: nativeWaveShaperNode.oversample\n };\n\n nativeWaveShaperNode = createNativeWaveShaperNode(nativeOfflineAudioContext, options);\n }\n\n renderedNativeWaveShaperNodes.set(nativeOfflineAudioContext, nativeWaveShaperNode);\n\n if (isNativeAudioNodeFaker(nativeWaveShaperNode)) {\n await renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeWaveShaperNode.inputs[0]);\n } else {\n await renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeWaveShaperNode);\n }\n\n return nativeWaveShaperNode;\n };\n\n return {\n render(proxy: IWaveShaperNode<T>, nativeOfflineAudioContext: TNativeOfflineAudioContext): Promise<TNativeWaveShaperNode> {\n const renderedNativeWaveShaperNode = renderedNativeWaveShaperNodes.get(nativeOfflineAudioContext);\n\n if (renderedNativeWaveShaperNode !== undefined) {\n return Promise.resolve(renderedNativeWaveShaperNode);\n }\n\n return createWaveShaperNode(proxy, nativeOfflineAudioContext);\n }\n };\n };\n};\n","import { TWindow, TWindowFactory } from '../types';\n\nexport const createWindow: TWindowFactory = () => (typeof window === 'undefined' ? null : <TWindow>window);\n","import { TNativeAudioBuffer, TWrapAudioBufferCopyChannelMethodsFactory } from '../types';\n\nexport const createWrapAudioBufferCopyChannelMethods: TWrapAudioBufferCopyChannelMethodsFactory = (\n convertNumberToUnsignedLong,\n createIndexSizeError\n) => {\n return (audioBuffer: TNativeAudioBuffer): void => {\n audioBuffer.copyFromChannel = (destination, channelNumberAsNumber, bufferOffsetAsNumber = 0) => {\n const bufferOffset = convertNumberToUnsignedLong(bufferOffsetAsNumber);\n const channelNumber = convertNumberToUnsignedLong(channelNumberAsNumber);\n\n if (channelNumber >= audioBuffer.numberOfChannels) {\n throw createIndexSizeError();\n }\n\n const audioBufferLength = audioBuffer.length;\n const channelData = audioBuffer.getChannelData(channelNumber);\n const destinationLength = destination.length;\n\n for (let i = bufferOffset < 0 ? -bufferOffset : 0; i + bufferOffset < audioBufferLength && i < destinationLength; i += 1) {\n destination[i] = channelData[i + bufferOffset];\n }\n };\n\n audioBuffer.copyToChannel = (source, channelNumberAsNumber, bufferOffsetAsNumber = 0) => {\n const bufferOffset = convertNumberToUnsignedLong(bufferOffsetAsNumber);\n const channelNumber = convertNumberToUnsignedLong(channelNumberAsNumber);\n\n if (channelNumber >= audioBuffer.numberOfChannels) {\n throw createIndexSizeError();\n }\n\n const audioBufferLength = audioBuffer.length;\n const channelData = audioBuffer.getChannelData(channelNumber);\n const sourceLength = source.length;\n\n for (let i = bufferOffset < 0 ? -bufferOffset : 0; i + bufferOffset < audioBufferLength && i < sourceLength; i += 1) {\n channelData[i + bufferOffset] = source[i];\n }\n };\n };\n};\n","import { TNativeAudioBuffer, TWrapAudioBufferCopyChannelMethodsOutOfBoundsFactory } from '../types';\n\nexport const createWrapAudioBufferCopyChannelMethodsOutOfBounds: TWrapAudioBufferCopyChannelMethodsOutOfBoundsFactory = (\n convertNumberToUnsignedLong\n) => {\n return (audioBuffer: TNativeAudioBuffer): void => {\n audioBuffer.copyFromChannel = ((copyFromChannel) => {\n return (destination: Float32Array, channelNumberAsNumber: number, bufferOffsetAsNumber = 0) => {\n const bufferOffset = convertNumberToUnsignedLong(bufferOffsetAsNumber);\n const channelNumber = convertNumberToUnsignedLong(channelNumberAsNumber);\n\n if (bufferOffset < audioBuffer.length) {\n return copyFromChannel.call(audioBuffer, destination, channelNumber, bufferOffset);\n }\n };\n })(audioBuffer.copyFromChannel);\n\n audioBuffer.copyToChannel = ((copyToChannel) => {\n return (source: Float32Array, channelNumberAsNumber: number, bufferOffsetAsNumber = 0) => {\n const bufferOffset = convertNumberToUnsignedLong(bufferOffsetAsNumber);\n const channelNumber = convertNumberToUnsignedLong(channelNumberAsNumber);\n\n if (bufferOffset < audioBuffer.length) {\n return copyToChannel.call(audioBuffer, source, channelNumber, bufferOffset);\n }\n };\n })(audioBuffer.copyToChannel);\n };\n};\n","import { TWrapAudioBufferSourceNodeStopMethodNullifiedBufferFactory } from '../types';\n\nexport const createWrapAudioBufferSourceNodeStopMethodNullifiedBuffer: TWrapAudioBufferSourceNodeStopMethodNullifiedBufferFactory = (\n overwriteAccessors\n) => {\n return (nativeAudioBufferSourceNode, nativeContext) => {\n const nullifiedBuffer = nativeContext.createBuffer(1, 1, 44100);\n\n if (nativeAudioBufferSourceNode.buffer === null) {\n nativeAudioBufferSourceNode.buffer = nullifiedBuffer;\n }\n\n overwriteAccessors(\n nativeAudioBufferSourceNode,\n 'buffer',\n (get) => () => {\n const value = get.call(nativeAudioBufferSourceNode);\n\n return value === nullifiedBuffer ? null : value;\n },\n (set) => (value) => {\n return set.call(nativeAudioBufferSourceNode, value === null ? nullifiedBuffer : value);\n }\n );\n };\n};\n","import { TWrapChannelMergerNodeFactory } from '../types';\n\nexport const createWrapChannelMergerNode: TWrapChannelMergerNodeFactory = (createInvalidStateError, monitorConnections) => {\n return (nativeContext, channelMergerNode) => {\n // Bug #15: Safari does not return the default properties.\n channelMergerNode.channelCount = 1;\n channelMergerNode.channelCountMode = 'explicit';\n\n // Bug #16: Safari does not throw an error when setting a different channelCount or channelCountMode.\n Object.defineProperty(channelMergerNode, 'channelCount', {\n get: () => 1,\n set: () => {\n throw createInvalidStateError();\n }\n });\n\n Object.defineProperty(channelMergerNode, 'channelCountMode', {\n get: () => 'explicit',\n set: () => {\n throw createInvalidStateError();\n }\n });\n\n // Bug #20: Safari requires a connection of any kind to treat the input signal correctly.\n const audioBufferSourceNode = nativeContext.createBufferSource();\n\n const whenConnected = () => {\n const length = channelMergerNode.numberOfInputs;\n\n for (let i = 0; i < length; i += 1) {\n audioBufferSourceNode.connect(channelMergerNode, 0, i);\n }\n };\n const whenDisconnected = () => audioBufferSourceNode.disconnect(channelMergerNode);\n\n monitorConnections(channelMergerNode, whenConnected, whenDisconnected);\n };\n};\n","import { TGetFirstSampleFunction } from '../types';\n\nexport const getFirstSample: TGetFirstSampleFunction = (audioBuffer, buffer, channelNumber) => {\n // Bug #5: Safari does not support copyFromChannel() and copyToChannel().\n if (audioBuffer.copyFromChannel === undefined) {\n return audioBuffer.getChannelData(channelNumber)[0];\n }\n\n audioBuffer.copyFromChannel(buffer, channelNumber);\n\n return buffer[0];\n};\n","import { TIsDCCurveFunction } from '../types';\n\nexport const isDCCurve: TIsDCCurveFunction = (curve) => {\n if (curve === null) {\n return false;\n }\n\n const length = curve.length;\n\n if (length % 2 !== 0) {\n return curve[Math.floor(length / 2)] !== 0;\n }\n\n return curve[length / 2 - 1] + curve[length / 2] !== 0;\n};\n","import { TOverwriteAccessorsFunction } from '../types';\n\nexport const overwriteAccessors: TOverwriteAccessorsFunction = (object, property, createGetter, createSetter) => {\n let prototype = object;\n\n while (!prototype.hasOwnProperty(property)) {\n prototype = Object.getPrototypeOf(prototype);\n }\n\n const { get, set } = <Required<PropertyDescriptor>>Object.getOwnPropertyDescriptor(prototype, property);\n\n Object.defineProperty(object, property, { get: createGetter(get), set: createSetter(set) });\n};\n","import { TSanitizeAudioWorkletNodeOptionsFunction } from '../types';\n\nexport const sanitizeAudioWorkletNodeOptions: TSanitizeAudioWorkletNodeOptionsFunction = (options) => {\n return {\n ...options,\n outputChannelCount:\n options.outputChannelCount !== undefined\n ? options.outputChannelCount\n : options.numberOfInputs === 1 && options.numberOfOutputs === 1\n ? /*\n * Bug #61: This should be the computedNumberOfChannels, but unfortunately that is almost impossible to fake. That's why\n * the channelCountMode is required to be 'explicit' as long as there is not a native implementation in every browser. That\n * makes sure the computedNumberOfChannels is equivilant to the channelCount which makes it much easier to compute.\n */\n [options.channelCount]\n : Array.from({ length: options.numberOfOutputs }, () => 1)\n };\n};\n","import { TSanitizeChannelSplitterOptionsFunction } from '../types';\n\nexport const sanitizeChannelSplitterOptions: TSanitizeChannelSplitterOptionsFunction = (options) => {\n return { ...options, channelCount: options.numberOfOutputs };\n};\n","import { TSanitizePeriodicWaveOptionsFunction } from '../types';\n\nexport const sanitizePeriodicWaveOptions: TSanitizePeriodicWaveOptionsFunction = (options) => {\n const { imag, real } = options;\n\n if (imag === undefined) {\n if (real === undefined) {\n return { ...options, imag: [0, 0], real: [0, 0] };\n }\n\n return { ...options, imag: Array.from(real, () => 0), real };\n }\n\n if (real === undefined) {\n return { ...options, imag, real: Array.from(imag, () => 0) };\n }\n\n return { ...options, imag, real };\n};\n","import { TSetValueAtTimeUntilPossibleFunction } from '../types';\n\nexport const setValueAtTimeUntilPossible: TSetValueAtTimeUntilPossibleFunction = (audioParam, value, startTime) => {\n try {\n audioParam.setValueAtTime(value, startTime);\n } catch (err) {\n if (err.code !== 9) {\n throw err;\n }\n\n setValueAtTimeUntilPossible(audioParam, value, startTime + 1e-7);\n }\n};\n","import { TNativeContext } from '../types';\n\nexport const testAudioBufferSourceNodeStartMethodConsecutiveCallsSupport = (nativeContext: TNativeContext) => {\n const nativeAudioBufferSourceNode = nativeContext.createBufferSource();\n\n nativeAudioBufferSourceNode.start();\n\n try {\n nativeAudioBufferSourceNode.start();\n } catch {\n return true;\n }\n\n return false;\n};\n","import { TNativeContext } from '../types';\n\nexport const testAudioBufferSourceNodeStartMethodOffsetClampingSupport = (nativeContext: TNativeContext) => {\n const nativeAudioBufferSourceNode = nativeContext.createBufferSource();\n const nativeAudioBuffer = nativeContext.createBuffer(1, 1, 44100);\n\n nativeAudioBufferSourceNode.buffer = nativeAudioBuffer;\n\n try {\n nativeAudioBufferSourceNode.start(0, 1);\n } catch {\n return false;\n }\n\n return true;\n};\n","import { TNativeContext } from '../types';\n\nexport const testAudioBufferSourceNodeStopMethodNullifiedBufferSupport = (nativeContext: TNativeContext) => {\n const nativeAudioBufferSourceNode = nativeContext.createBufferSource();\n\n nativeAudioBufferSourceNode.start();\n\n try {\n nativeAudioBufferSourceNode.stop();\n } catch {\n return false;\n }\n\n return true;\n};\n","import { TNativeContext } from '../types';\n\nexport const testAudioScheduledSourceNodeStartMethodNegativeParametersSupport = (nativeContext: TNativeContext) => {\n const nativeAudioBufferSourceNode = nativeContext.createOscillator();\n\n try {\n nativeAudioBufferSourceNode.start(-1);\n } catch (err) {\n return err instanceof RangeError;\n }\n\n return false;\n};\n","import { TNativeContext } from '../types';\n\nexport const testAudioScheduledSourceNodeStopMethodConsecutiveCallsSupport = (nativeContext: TNativeContext) => {\n const nativeAudioBuffer = nativeContext.createBuffer(1, 1, 44100);\n const nativeAudioBufferSourceNode = nativeContext.createBufferSource();\n\n nativeAudioBufferSourceNode.buffer = nativeAudioBuffer;\n nativeAudioBufferSourceNode.start();\n nativeAudioBufferSourceNode.stop();\n\n try {\n nativeAudioBufferSourceNode.stop();\n\n return true;\n } catch {\n return false;\n }\n};\n","import { TNativeContext } from '../types';\n\nexport const testAudioScheduledSourceNodeStopMethodNegativeParametersSupport = (nativeContext: TNativeContext) => {\n const nativeAudioBufferSourceNode = nativeContext.createOscillator();\n\n try {\n nativeAudioBufferSourceNode.stop(-1);\n } catch (err) {\n return err instanceof RangeError;\n }\n\n return false;\n};\n","import { TTestAudioWorkletNodeOptionsClonabilityFunction } from '../types';\n\nexport const testAudioWorkletNodeOptionsClonability: TTestAudioWorkletNodeOptionsClonabilityFunction = (audioWorkletNodeOptions) => {\n const { port1, port2 } = new MessageChannel();\n\n try {\n // This will throw an error if the audioWorkletNodeOptions are not clonable.\n port1.postMessage(audioWorkletNodeOptions);\n } finally {\n port1.close();\n port2.close();\n }\n};\n","import { TNativeAudioBufferSourceNode } from '../types';\n\nexport const wrapAudioBufferSourceNodeStartMethodOffsetClamping = (nativeAudioBufferSourceNode: TNativeAudioBufferSourceNode): void => {\n nativeAudioBufferSourceNode.start = ((start) => {\n return (when = 0, offset = 0, duration?: number) => {\n const buffer = nativeAudioBufferSourceNode.buffer;\n // Bug #154: Safari does not clamp the offset if it is equal to or greater than the duration of the buffer.\n const clampedOffset = buffer === null ? offset : Math.min(buffer.duration, offset);\n\n // Bug #155: Safari does not handle the offset correctly if it would cause the buffer to be not be played at all.\n if (buffer !== null && clampedOffset > buffer.duration - 0.5 / nativeAudioBufferSourceNode.context.sampleRate) {\n start.call(nativeAudioBufferSourceNode, when, 0, 0);\n } else {\n start.call(nativeAudioBufferSourceNode, when, clampedOffset, duration);\n }\n };\n })(nativeAudioBufferSourceNode.start);\n};\n","import { TNativeAudioNode, TWrapAudioScheduledSourceNodeStopMethodConsecutiveCallsFunction } from '../types';\nimport { interceptConnections } from './intercept-connections';\n\nexport const wrapAudioScheduledSourceNodeStopMethodConsecutiveCalls: TWrapAudioScheduledSourceNodeStopMethodConsecutiveCallsFunction = (\n nativeAudioScheduledSourceNode,\n nativeContext\n) => {\n const nativeGainNode = nativeContext.createGain();\n\n nativeAudioScheduledSourceNode.connect(nativeGainNode);\n\n const disconnectGainNode = ((disconnect) => {\n return () => {\n // @todo TypeScript cannot infer the overloaded signature with 1 argument yet.\n (<(destinaton: TNativeAudioNode) => void>disconnect).call(nativeAudioScheduledSourceNode, nativeGainNode);\n nativeAudioScheduledSourceNode.removeEventListener('ended', disconnectGainNode);\n };\n })(nativeAudioScheduledSourceNode.disconnect);\n\n nativeAudioScheduledSourceNode.addEventListener('ended', disconnectGainNode);\n\n interceptConnections(nativeAudioScheduledSourceNode, nativeGainNode);\n\n nativeAudioScheduledSourceNode.stop = ((stop) => {\n let isStopped = false;\n\n return (when = 0) => {\n if (isStopped) {\n try {\n stop.call(nativeAudioScheduledSourceNode, when);\n } catch {\n nativeGainNode.gain.setValueAtTime(0, when);\n }\n } else {\n stop.call(nativeAudioScheduledSourceNode, when);\n\n isStopped = true;\n }\n };\n })(nativeAudioScheduledSourceNode.stop);\n};\n","import { TWrapEventListenerFunction } from '../types';\n\nexport const wrapEventListener: TWrapEventListenerFunction = (target, eventListener) => {\n return (event) => {\n const descriptor = { value: target };\n\n Object.defineProperties(event, {\n currentTarget: descriptor,\n target: descriptor\n });\n\n if (typeof eventListener === 'function') {\n return eventListener.call(target, event);\n }\n\n return eventListener.handleEvent.call(target, event);\n };\n};\n","import { Note } from \"../type/Units.js\";\n\n/**\n * Test if the arg is undefined\n */\nexport function isUndef(arg: any): arg is undefined {\n\treturn arg === undefined;\n}\n\n/**\n * Test if the arg is not undefined\n */\nexport function isDefined<T>(arg: T | undefined): arg is T {\n\treturn arg !== undefined;\n}\n\n/**\n * Test if the arg is a function\n */\nexport function isFunction(arg: any): arg is (a: any) => any {\n\treturn typeof arg === \"function\";\n}\n\n/**\n * Test if the argument is a number.\n */\nexport function isNumber(arg: any): arg is number {\n\treturn typeof arg === \"number\";\n}\n\n/**\n * Test if the given argument is an object literal (i.e. `{}`);\n */\nexport function isObject(arg: any): arg is object {\n\treturn (\n\t\tObject.prototype.toString.call(arg) === \"[object Object]\" &&\n\t\targ.constructor === Object\n\t);\n}\n\n/**\n * Test if the argument is a boolean.\n */\nexport function isBoolean(arg: any): arg is boolean {\n\treturn typeof arg === \"boolean\";\n}\n\n/**\n * Test if the argument is an Array\n */\nexport function isArray(arg: any): arg is any[] {\n\treturn Array.isArray(arg);\n}\n\n/**\n * Test if the argument is a string.\n */\nexport function isString(arg: any): arg is string {\n\treturn typeof arg === \"string\";\n}\n\n/**\n * Test if the argument is in the form of a note in scientific pitch notation.\n * e.g. \"C4\"\n */\nexport function isNote(arg: any): arg is Note {\n\treturn isString(arg) && /^([a-g]{1}(?:b|#|x|bb)?)(-?[0-9]+)/i.test(arg);\n}\n","import { isUndef } from \"./TypeCheck.js\";\nimport type { BaseContext } from \"../context/BaseContext.js\";\nimport type { Time } from \"../type/Units.js\";\n\n/**\n * Assert that the statement is true, otherwise invoke the error.\n * @param statement\n * @param error The message which is passed into an Error\n */\nexport function assert(statement: boolean, error: string): asserts statement {\n\tif (!statement) {\n\t\tthrow new Error(error);\n\t}\n}\n\n/**\n * Make sure that the given value is within the range\n */\nexport function assertRange(value: number, gte: number, lte = Infinity): void {\n\tif (!(gte <= value && value <= lte)) {\n\t\tthrow new RangeError(\n\t\t\t`Value must be within [${gte}, ${lte}], got: ${value}`\n\t\t);\n\t}\n}\n\n/**\n * Warn if the context is not running.\n */\nexport function assertContextRunning(context: BaseContext): void {\n\t// add a warning if the context is not started\n\tif (!context.isOffline && context.state !== \"running\") {\n\t\twarn(\n\t\t\t'The AudioContext is \"suspended\". Invoke Tone.start() from a user action to start the audio.'\n\t\t);\n\t}\n}\n\n/**\n * If it is currently inside a scheduled callback\n */\nlet isInsideScheduledCallback = false;\nlet printedScheduledWarning = false;\n\n/**\n * Notify that the following block of code is occurring inside a Transport callback.\n */\nexport function enterScheduledCallback(insideCallback: boolean): void {\n\tisInsideScheduledCallback = insideCallback;\n}\n\n/**\n * Make sure that a time was passed into\n */\nexport function assertUsedScheduleTime(time?: Time): void {\n\tif (\n\t\tisUndef(time) &&\n\t\tisInsideScheduledCallback &&\n\t\t!printedScheduledWarning\n\t) {\n\t\tprintedScheduledWarning = true;\n\t\twarn(\n\t\t\t\"Events scheduled inside of scheduled callbacks should use the passed in scheduling time. See https://github.com/Tonejs/Tone.js/wiki/Accurate-Timing\"\n\t\t);\n\t}\n}\n\n/**\n * A basic logging interface\n */\ninterface Logger {\n\tlog: (args?: any[]) => void;\n\twarn: (args?: any[]) => void;\n}\n\n/**\n * The default logger is the console\n */\nlet defaultLogger: Logger = console;\n\n/**\n * Set the logging interface\n */\nexport function setLogger(logger: Logger): void {\n\tdefaultLogger = logger;\n}\n\n/**\n * Log anything\n */\nexport function log(...args: any[]): void {\n\tdefaultLogger.log(...args);\n}\n\n/**\n * Warn anything\n */\nexport function warn(...args: any[]): void {\n\tdefaultLogger.warn(...args);\n}\n","import {\n\tAudioContext as stdAudioContext,\n\tAudioWorkletNode as stdAudioWorkletNode,\n\tOfflineAudioContext as stdOfflineAudioContext,\n} from \"standardized-audio-context\";\nimport { assert } from \"../util/Debug.js\";\nimport { isDefined } from \"../util/TypeCheck.js\";\n\n/**\n * Create a new AudioContext\n */\nexport function createAudioContext(\n\toptions?: AudioContextOptions\n): AudioContext {\n\treturn new stdAudioContext(options) as unknown as AudioContext;\n}\n\n/**\n * Create a new OfflineAudioContext\n */\nexport function createOfflineAudioContext(\n\tchannels: number,\n\tlength: number,\n\tsampleRate: number\n): OfflineAudioContext {\n\treturn new stdOfflineAudioContext(\n\t\tchannels,\n\t\tlength,\n\t\tsampleRate\n\t) as unknown as OfflineAudioContext;\n}\n\n/**\n * Either the online or offline audio context\n */\nexport type AnyAudioContext = AudioContext | OfflineAudioContext;\n\n/**\n * Interface for things that Tone.js adds to the window\n */\ninterface ToneWindow extends Window {\n\tTONE_SILENCE_LOGGING?: boolean;\n\tTONE_DEBUG_CLASS?: string;\n\tBaseAudioContext: any;\n\tAudioWorkletNode: any;\n}\n\n/**\n * A reference to the window object\n * @hidden\n */\nexport const theWindow: ToneWindow | null =\n\ttypeof self === \"object\" ? self : null;\n\n/**\n * If the browser has a window object which has an AudioContext\n * @hidden\n */\nexport const hasAudioContext =\n\ttheWindow &&\n\t(theWindow.hasOwnProperty(\"AudioContext\") ||\n\t\ttheWindow.hasOwnProperty(\"webkitAudioContext\"));\n\nexport function createAudioWorkletNode(\n\tcontext: AnyAudioContext,\n\tname: string,\n\toptions?: Partial<AudioWorkletNodeOptions>\n): AudioWorkletNode {\n\tassert(\n\t\tisDefined(stdAudioWorkletNode),\n\t\t\"AudioWorkletNode only works in a secure context (https or localhost)\"\n\t);\n\treturn new (\n\t\tcontext instanceof theWindow?.BaseAudioContext\n\t\t\t? theWindow?.AudioWorkletNode\n\t\t\t: stdAudioWorkletNode\n\t)(context, name, options);\n}\n\n/**\n * This promise resolves to a boolean which indicates if the\n * functionality is supported within the currently used browse.\n * Taken from [standardized-audio-context](https://github.com/chrisguttandin/standardized-audio-context#issupported)\n */\nexport { isSupported as supported } from \"standardized-audio-context\";\n","/******************************************************************************\nCopyright (c) Microsoft Corporation.\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n***************************************************************************** */\n/* global Reflect, Promise, SuppressedError, Symbol, Iterator */\n\nvar extendStatics = function(d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n return extendStatics(d, b);\n};\n\nexport function __extends(d, b) {\n if (typeof b !== \"function\" && b !== null)\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n}\n\nexport var __assign = function() {\n __assign = Object.assign || function __assign(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\n }\n return t;\n }\n return __assign.apply(this, arguments);\n}\n\nexport function __rest(s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n}\n\nexport function __decorate(decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n}\n\nexport function __param(paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n}\n\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\n var _, done = false;\n for (var i = decorators.length - 1; i >= 0; i--) {\n var context = {};\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\n if (kind === \"accessor\") {\n if (result === void 0) continue;\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\n if (_ = accept(result.get)) descriptor.get = _;\n if (_ = accept(result.set)) descriptor.set = _;\n if (_ = accept(result.init)) initializers.unshift(_);\n }\n else if (_ = accept(result)) {\n if (kind === \"field\") initializers.unshift(_);\n else descriptor[key] = _;\n }\n }\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\n done = true;\n};\n\nexport function __runInitializers(thisArg, initializers, value) {\n var useValue = arguments.length > 2;\n for (var i = 0; i < initializers.length; i++) {\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\n }\n return useValue ? value : void 0;\n};\n\nexport function __propKey(x) {\n return typeof x === \"symbol\" ? x : \"\".concat(x);\n};\n\nexport function __setFunctionName(f, name, prefix) {\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\n};\n\nexport function __metadata(metadataKey, metadataValue) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\n}\n\nexport function __awaiter(thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n}\n\nexport function __generator(thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === \"function\" ? Iterator : Object).prototype);\n return g.next = verb(0), g[\"throw\"] = verb(1), g[\"return\"] = verb(2), typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n}\n\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n});\n\nexport function __exportStar(m, o) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\n}\n\nexport function __values(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n}\n\nexport function __read(o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n}\n\n/** @deprecated */\nexport function __spread() {\n for (var ar = [], i = 0; i < arguments.length; i++)\n ar = ar.concat(__read(arguments[i]));\n return ar;\n}\n\n/** @deprecated */\nexport function __spreadArrays() {\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\n r[k] = a[j];\n return r;\n}\n\nexport function __spreadArray(to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n}\n\nexport function __await(v) {\n return this instanceof __await ? (this.v = v, this) : new __await(v);\n}\n\nexport function __asyncGenerator(thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = Object.create((typeof AsyncIterator === \"function\" ? AsyncIterator : Object).prototype), verb(\"next\"), verb(\"throw\"), verb(\"return\", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;\n function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }\n function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n}\n\nexport function __asyncDelegator(o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\n}\n\nexport function __asyncValues(o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n}\n\nexport function __makeTemplateObject(cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n};\n\nvar __setModuleDefault = Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n};\n\nvar ownKeys = function(o) {\n ownKeys = Object.getOwnPropertyNames || function (o) {\n var ar = [];\n for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;\n return ar;\n };\n return ownKeys(o);\n};\n\nexport function __importStar(mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== \"default\") __createBinding(result, mod, k[i]);\n __setModuleDefault(result, mod);\n return result;\n}\n\nexport function __importDefault(mod) {\n return (mod && mod.__esModule) ? mod : { default: mod };\n}\n\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n}\n\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n}\n\nexport function __classPrivateFieldIn(state, receiver) {\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\n}\n\nexport function __addDisposableResource(env, value, async) {\n if (value !== null && value !== void 0) {\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\n var dispose, inner;\n if (async) {\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\n dispose = value[Symbol.asyncDispose];\n }\n if (dispose === void 0) {\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\n dispose = value[Symbol.dispose];\n if (async) inner = dispose;\n }\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\n if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };\n env.stack.push({ value: value, dispose: dispose, async: async });\n }\n else if (async) {\n env.stack.push({ async: true });\n }\n return value;\n}\n\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\n var e = new Error(message);\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\n};\n\nexport function __disposeResources(env) {\n function fail(e) {\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\n env.hasError = true;\n }\n var r, s = 0;\n function next() {\n while (r = env.stack.pop()) {\n try {\n if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);\n if (r.dispose) {\n var result = r.dispose.call(r.value);\n if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\n }\n else s |= 1;\n }\n catch (e) {\n fail(e);\n }\n }\n if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();\n if (env.hasError) throw env.error;\n }\n return next();\n}\n\nexport function __rewriteRelativeImportExtension(path, preserveJsx) {\n if (typeof path === \"string\" && /^\\.\\.?\\//.test(path)) {\n return path.replace(/\\.(tsx)$|((?:\\.d)?)((?:\\.[^./]+?)?)\\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {\n return tsx ? preserveJsx ? \".jsx\" : \".js\" : d && (!ext || !cm) ? m : (d + ext + \".\" + cm.toLowerCase() + \"js\");\n });\n }\n return path;\n}\n\nexport default {\n __extends,\n __assign,\n __rest,\n __decorate,\n __param,\n __esDecorate,\n __runInitializers,\n __propKey,\n __setFunctionName,\n __metadata,\n __awaiter,\n __generator,\n __createBinding,\n __exportStar,\n __values,\n __read,\n __spread,\n __spreadArrays,\n __spreadArray,\n __await,\n __asyncGenerator,\n __asyncDelegator,\n __asyncValues,\n __makeTemplateObject,\n __importStar,\n __importDefault,\n __classPrivateFieldGet,\n __classPrivateFieldSet,\n __classPrivateFieldIn,\n __addDisposableResource,\n __disposeResources,\n __rewriteRelativeImportExtension,\n};\n","import { Seconds } from \"../type/Units.js\";\n\nexport type TickerClockSource = \"worker\" | \"timeout\" | \"offline\";\n\n/**\n * A class which provides a reliable callback using either\n * a Web Worker, or if that isn't supported, falls back to setTimeout.\n */\nexport class Ticker {\n\t/**\n\t * Either \"worker\" or \"timeout\" or \"offline\"\n\t */\n\tprivate _type: TickerClockSource;\n\n\t/**\n\t * The update interval of the worker\n\t */\n\tprivate _updateInterval!: Seconds;\n\n\t/**\n\t * The lowest allowable interval, preferably calculated from context sampleRate\n\t */\n\tprivate _minimumUpdateInterval: Seconds;\n\n\t/**\n\t * The callback to invoke at regular intervals\n\t */\n\tprivate _callback: () => void;\n\n\t/**\n\t * track the callback interval\n\t */\n\tprivate _timeout!: ReturnType<typeof setTimeout>;\n\n\t/**\n\t * private reference to the worker\n\t */\n\tprivate _worker!: Worker;\n\n\tconstructor(\n\t\tcallback: () => void,\n\t\ttype: TickerClockSource,\n\t\tupdateInterval: Seconds,\n\t\tcontextSampleRate?: number\n\t) {\n\t\tthis._callback = callback;\n\t\tthis._type = type;\n\t\tthis._minimumUpdateInterval = Math.max(\n\t\t\t128 / (contextSampleRate || 44100),\n\t\t\t0.001\n\t\t);\n\t\tthis.updateInterval = updateInterval;\n\n\t\t// create the clock source for the first time\n\t\tthis._createClock();\n\t}\n\n\t/**\n\t * Generate a web worker\n\t */\n\tprivate _createWorker(): void {\n\t\tconst blob = new Blob(\n\t\t\t[\n\t\t\t\t/* javascript */ `\n\t\t\t// the initial timeout time\n\t\t\tlet timeoutTime = ${(this._updateInterval * 1000).toFixed(1)};\n\t\t\t// onmessage callback\n\t\t\tself.onmessage = function(msg){\n\t\t\t\ttimeoutTime = parseInt(msg.data);\n\t\t\t};\n\t\t\t// the tick function which posts a message\n\t\t\t// and schedules a new tick\n\t\t\tfunction tick(){\n\t\t\t\tsetTimeout(tick, timeoutTime);\n\t\t\t\tself.postMessage('tick');\n\t\t\t}\n\t\t\t// call tick initially\n\t\t\ttick();\n\t\t\t`,\n\t\t\t],\n\t\t\t{ type: \"text/javascript\" }\n\t\t);\n\t\tconst blobUrl = URL.createObjectURL(blob);\n\t\tconst worker = new Worker(blobUrl);\n\n\t\tworker.onmessage = this._callback.bind(this);\n\n\t\tthis._worker = worker;\n\t}\n\n\t/**\n\t * Create a timeout loop\n\t */\n\tprivate _createTimeout(): void {\n\t\tthis._timeout = setTimeout(() => {\n\t\t\tthis._createTimeout();\n\t\t\tthis._callback();\n\t\t}, this._updateInterval * 1000);\n\t}\n\n\t/**\n\t * Create the clock source.\n\t */\n\tprivate _createClock(): void {\n\t\tif (this._type === \"worker\") {\n\t\t\ttry {\n\t\t\t\tthis._createWorker();\n\t\t\t} catch (e) {\n\t\t\t\t// workers not supported, fallback to timeout\n\t\t\t\tthis._type = \"timeout\";\n\t\t\t\tthis._createClock();\n\t\t\t}\n\t\t} else if (this._type === \"timeout\") {\n\t\t\tthis._createTimeout();\n\t\t}\n\t}\n\n\t/**\n\t * Clean up the current clock source\n\t */\n\tprivate _disposeClock(): void {\n\t\tif (this._timeout) {\n\t\t\tclearTimeout(this._timeout);\n\t\t}\n\t\tif (this._worker) {\n\t\t\tthis._worker.terminate();\n\t\t\tthis._worker.onmessage = null;\n\t\t}\n\t}\n\n\t/**\n\t * The rate in seconds the ticker will update\n\t */\n\tget updateInterval(): Seconds {\n\t\treturn this._updateInterval;\n\t}\n\tset updateInterval(interval: Seconds) {\n\t\tthis._updateInterval = Math.max(interval, this._minimumUpdateInterval);\n\t\tif (this._type === \"worker\") {\n\t\t\tthis._worker?.postMessage(this._updateInterval * 1000);\n\t\t}\n\t}\n\n\t/**\n\t * The type of the ticker, either a worker or a timeout\n\t */\n\tget type(): TickerClockSource {\n\t\treturn this._type;\n\t}\n\tset type(type: TickerClockSource) {\n\t\tthis._disposeClock();\n\t\tthis._type = type;\n\t\tthis._createClock();\n\t}\n\n\t/**\n\t * Clean up\n\t */\n\tdispose(): void {\n\t\tthis._disposeClock();\n\t}\n}\n","import {\n\tAudioBuffer,\n\tisAnyAudioContext,\n\tisAnyAudioNode,\n\tisAnyAudioParam,\n\tisAnyOfflineAudioContext,\n} from \"standardized-audio-context\";\n\n/**\n * Test if the given value is an instanceof AudioParam\n */\nexport function isAudioParam(arg: any): arg is AudioParam {\n\treturn isAnyAudioParam(arg);\n}\n\n/**\n * Test if the given value is an instanceof AudioNode\n */\nexport function isAudioNode(arg: any): arg is AudioNode {\n\treturn isAnyAudioNode(arg);\n}\n\n/**\n * Test if the arg is instanceof an OfflineAudioContext\n */\nexport function isOfflineAudioContext(arg: any): arg is OfflineAudioContext {\n\treturn isAnyOfflineAudioContext(arg);\n}\n\n/**\n * Test if the arg is an instanceof AudioContext\n */\nexport function isAudioContext(arg: any): arg is AudioContext {\n\treturn isAnyAudioContext(arg);\n}\n\n/**\n * Test if the arg is instanceof an AudioBuffer\n */\nexport function isAudioBuffer(arg: any): arg is AudioBuffer {\n\treturn arg instanceof AudioBuffer;\n}\n","import {\n\tisAudioBuffer,\n\tisAudioNode,\n\tisAudioParam,\n} from \"./AdvancedTypeCheck.js\";\nimport { isDefined, isObject, isUndef } from \"./TypeCheck.js\";\nimport type { BaseToneOptions } from \"../Tone.js\";\n\n/**\n * Some objects should not be merged\n */\nfunction noCopy(key: string, arg: any): boolean {\n\treturn (\n\t\tkey === \"value\" ||\n\t\tisAudioParam(arg) ||\n\t\tisAudioNode(arg) ||\n\t\tisAudioBuffer(arg)\n\t);\n}\n\nexport function deepMerge<T>(target: T): T;\nexport function deepMerge<T, U>(target: T, source1: U): T & U;\nexport function deepMerge<T, U, V>(\n\ttarget: T,\n\tsource1: U,\n\tsource2: V\n): T & U & V;\nexport function deepMerge<T, U, V, W>(\n\ttarget: T,\n\tsource1: U,\n\tsource2: V,\n\tsource3: W\n): T & U & V & W;\n/**\n * Recursively merge an object\n * @param target the object to merge into\n * @param sources the source objects to merge\n */\nexport function deepMerge(target: any, ...sources: any[]): any {\n\tif (!sources.length) {\n\t\treturn target;\n\t}\n\tconst source = sources.shift();\n\n\tif (isObject(target) && isObject(source)) {\n\t\tfor (const key in source) {\n\t\t\tif (noCopy(key, source[key])) {\n\t\t\t\ttarget[key] = source[key];\n\t\t\t} else if (isObject(source[key])) {\n\t\t\t\tif (!target[key]) {\n\t\t\t\t\tObject.assign(target, { [key]: {} });\n\t\t\t\t}\n\t\t\t\tdeepMerge(target[key], source[key] as any);\n\t\t\t} else {\n\t\t\t\tObject.assign(target, { [key]: source[key] as any });\n\t\t\t}\n\t\t}\n\t}\n\t// @ts-ignore\n\treturn deepMerge(target, ...sources);\n}\n\n/**\n * Returns true if the two arrays have the same value for each of the elements\n */\nexport function deepEquals<T>(arrayA: T[], arrayB: T[]): boolean {\n\treturn (\n\t\tarrayA.length === arrayB.length &&\n\t\tarrayA.every((element, index) => arrayB[index] === element)\n\t);\n}\n\n/**\n * Convert an args array into an object.\n * @internal\n */\nexport function optionsFromArguments<T extends object>(\n\tdefaults: T,\n\targsArray: IArguments,\n\tkeys: Array<keyof T> = [],\n\tobjKey?: keyof T\n): T {\n\tconst opts: Partial<T> = {};\n\tconst args = Array.from(argsArray);\n\t// if the first argument is an object and has an object key\n\tif (isObject(args[0]) && objKey && !Reflect.has(args[0], objKey)) {\n\t\t// if it's not part of the defaults\n\t\tconst partOfDefaults = Object.keys(args[0]).some((key) =>\n\t\t\tReflect.has(defaults, key)\n\t\t);\n\t\tif (!partOfDefaults) {\n\t\t\t// merge that key\n\t\t\tdeepMerge(opts, { [objKey]: args[0] });\n\t\t\t// remove the obj key from the keys\n\t\t\tkeys.splice(keys.indexOf(objKey), 1);\n\t\t\t// shift the first argument off\n\t\t\targs.shift();\n\t\t}\n\t}\n\tif (args.length === 1 && isObject(args[0])) {\n\t\tdeepMerge(opts, args[0]);\n\t} else {\n\t\tfor (let i = 0; i < keys.length; i++) {\n\t\t\tif (isDefined(args[i])) {\n\t\t\t\topts[keys[i]] = args[i];\n\t\t\t}\n\t\t}\n\t}\n\treturn deepMerge(defaults, opts);\n}\n\n/**\n * Return this instances default values by calling Constructor.getDefaults()\n */\nexport function getDefaultsFromInstance<T>(instance: T): BaseToneOptions {\n\ttype ToneClass = {\n\t\tconstructor: ToneClass;\n\t\tgetDefaults: () => BaseToneOptions;\n\t} & T;\n\n\treturn (instance as ToneClass).constructor.getDefaults();\n}\n\n/**\n * Returns the fallback if the given object is undefined.\n * Take an array of arguments and return a formatted options object.\n * @internal\n */\nexport function defaultArg<T>(given: T, fallback: T): T {\n\tif (isUndef(given)) {\n\t\treturn fallback;\n\t} else {\n\t\treturn given;\n\t}\n}\n\n/**\n * Remove all of the properties belonging to omit from obj.\n */\nexport function omitFromObject<T extends object, O extends string[]>(\n\tobj: T,\n\tomit: O\n): Omit<T, keyof O> {\n\tomit.forEach((prop) => {\n\t\tif (Reflect.has(obj, prop)) {\n\t\t\tdelete obj[prop];\n\t\t}\n\t});\n\treturn obj;\n}\n","/**\n * Tone.js\n * @author Yotam Mann\n * @license http://opensource.org/licenses/MIT MIT License\n * @copyright 2014-2024 Yotam Mann\n */\nimport { version } from \"../version.js\";\nimport { theWindow } from \"./context/AudioContext.js\";\nimport { log } from \"./util/Debug.js\";\n\n//-------------------------------------\n// \tTONE\n//-------------------------------------\n\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface BaseToneOptions {}\n\n/**\n * Tone is the base class of all other classes.\n *\n * @category Core\n * @constructor\n */\nexport abstract class Tone {\n\t/**\n\t * The version number semver\n\t */\n\tstatic version: string = version;\n\n\t/**\n\t * The name of the class\n\t */\n\tprotected abstract name: string;\n\n\t/**\n\t * Returns all of the default options belonging to the class.\n\t */\n\tstatic getDefaults(): BaseToneOptions {\n\t\treturn {};\n\t}\n\n\t//-------------------------------------\n\t// \tDEBUGGING\n\t//-------------------------------------\n\n\t/**\n\t * Set this debug flag to log all events that happen in this class.\n\t */\n\tdebug = false;\n\n\t/**\n\t * Prints the outputs to the console log for debugging purposes.\n\t * Prints the contents only if either the object has a property\n\t * called `debug` set to true, or a variable called TONE_DEBUG_CLASS\n\t * is set to the name of the class.\n\t * @example\n\t * const osc = new Tone.Oscillator();\n\t * // prints all logs originating from this oscillator\n\t * osc.debug = true;\n\t * // calls to start/stop will print in the console\n\t * osc.start();\n\t */\n\tprotected log(...args: any[]): void {\n\t\t// if the object is either set to debug = true\n\t\t// or if there is a string on the Tone.global.with the class name\n\t\tif (\n\t\t\tthis.debug ||\n\t\t\t(theWindow && this.toString() === theWindow.TONE_DEBUG_CLASS)\n\t\t) {\n\t\t\tlog(this, ...args);\n\t\t}\n\t}\n\n\t//-------------------------------------\n\t// \tDISPOSING\n\t//-------------------------------------\n\n\t/**\n\t * Indicates if the instance was disposed\n\t */\n\tprivate _wasDisposed = false;\n\n\t/**\n\t * disconnect and dispose.\n\t */\n\tdispose(): this {\n\t\tthis._wasDisposed = true;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Indicates if the instance was disposed. 'Disposing' an\n\t * instance means that all of the Web Audio nodes that were\n\t * created for the instance are disconnected and freed for garbage collection.\n\t */\n\tget disposed(): boolean {\n\t\treturn this._wasDisposed;\n\t}\n\n\t/**\n\t * Convert the class to a string\n\t * @example\n\t * const osc = new Tone.Oscillator();\n\t * console.log(osc.toString());\n\t */\n\ttoString(): string {\n\t\treturn this.name;\n\t}\n}\n","/**\n * The threshold for correctness for operators. Less than one sample even\n * at very high sampling rates (e.g. `1e-6 < 1 / 192000`).\n */\nconst EPSILON = 1e-6;\n\n/**\n * Test if A is greater than B\n */\nexport function GT(a: number, b: number): boolean {\n\treturn a > b + EPSILON;\n}\n\n/**\n * Test if A is greater than or equal to B\n */\nexport function GTE(a: number, b: number): boolean {\n\treturn GT(a, b) || EQ(a, b);\n}\n\n/**\n * Test if A is less than B\n */\nexport function LT(a: number, b: number): boolean {\n\treturn a + EPSILON < b;\n}\n\n/**\n * Test if A is less than B\n */\nexport function EQ(a: number, b: number): boolean {\n\treturn Math.abs(a - b) < EPSILON;\n}\n\n/**\n * Clamp the value within the given range\n */\nexport function clamp(value: number, min: number, max: number): number {\n\treturn Math.max(Math.min(value, max), min);\n}\n","import { Tone } from \"../Tone.js\";\nimport { Seconds } from \"../type/Units.js\";\nimport { optionsFromArguments } from \"./Defaults.js\";\nimport { assert } from \"./Debug.js\";\nimport { EQ, GT, GTE, LT } from \"./Math.js\";\n\ntype TimelineSearchParam = \"ticks\" | \"time\";\n\n/**\n * The options object for Timeline\n */\ninterface TimelineOptions {\n\tmemory: number;\n\tincreasing: boolean;\n}\n\n/**\n * An event must have a time number\n */\nexport interface TimelineEvent {\n\ttime: number;\n}\n\n/**\n * A Timeline class for scheduling and maintaining state\n * along a timeline. All events must have a \"time\" property.\n * Internally, events are stored in time order for fast\n * retrieval.\n * @internal\n */\nexport class Timeline<GenericEvent extends TimelineEvent> extends Tone {\n\treadonly name: string = \"Timeline\";\n\n\t/**\n\t * The memory of the timeline, i.e.\n\t * how many events in the past it will retain\n\t */\n\tmemory: number;\n\n\t/**\n\t * The array of scheduled timeline events\n\t */\n\tprotected _timeline: GenericEvent[] = [];\n\n\t/**\n\t * If the time value must always be greater than or equal to the last\n\t * element on the list.\n\t */\n\tincreasing: boolean;\n\n\t/**\n\t * @param memory The number of previous events that are retained.\n\t */\n\tconstructor(memory?: number);\n\tconstructor(options?: Partial<TimelineOptions>);\n\tconstructor() {\n\t\tsuper();\n\t\tconst options = optionsFromArguments(\n\t\t\tTimeline.getDefaults(),\n\t\t\targuments,\n\t\t\t[\"memory\"]\n\t\t);\n\n\t\tthis.memory = options.memory;\n\t\tthis.increasing = options.increasing;\n\t}\n\n\tstatic getDefaults(): TimelineOptions {\n\t\treturn {\n\t\t\tmemory: Infinity,\n\t\t\tincreasing: false,\n\t\t};\n\t}\n\n\t/**\n\t * The number of items in the timeline.\n\t */\n\tget length(): number {\n\t\treturn this._timeline.length;\n\t}\n\n\t/**\n\t * Insert an event object onto the timeline. Events must have a \"time\" attribute.\n\t * @param event The event object to insert into the timeline.\n\t */\n\tadd(event: GenericEvent): this {\n\t\t// the event needs to have a time attribute\n\t\tassert(\n\t\t\tReflect.has(event, \"time\"),\n\t\t\t\"Timeline: events must have a time attribute\"\n\t\t);\n\t\tevent.time = event.time.valueOf();\n\t\tif (this.increasing && this.length) {\n\t\t\tconst lastValue = this._timeline[this.length - 1] as GenericEvent;\n\t\t\tassert(\n\t\t\t\tGTE(event.time, lastValue.time),\n\t\t\t\t\"The time must be greater than or equal to the last scheduled time\"\n\t\t\t);\n\t\t\tthis._timeline.push(event);\n\t\t} else {\n\t\t\tconst index = this._search(event.time);\n\t\t\tthis._timeline.splice(index + 1, 0, event);\n\t\t}\n\t\t// if the length is more than the memory, remove the previous ones\n\t\tif (this.length > this.memory) {\n\t\t\tconst diff = this.length - this.memory;\n\t\t\tthis._timeline.splice(0, diff);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Remove an event from the timeline.\n\t * @param {Object} event The event object to remove from the list.\n\t * @returns {Timeline} this\n\t */\n\tremove(event: GenericEvent): this {\n\t\tconst index = this._timeline.indexOf(event);\n\t\tif (index !== -1) {\n\t\t\tthis._timeline.splice(index, 1);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Get the nearest event whose time is less than or equal to the given time.\n\t * @param time The time to query.\n\t */\n\tget(\n\t\ttime: number,\n\t\tparam: TimelineSearchParam = \"time\"\n\t): GenericEvent | null {\n\t\tconst index = this._search(time, param);\n\t\tif (index !== -1) {\n\t\t\treturn this._timeline[index];\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * Return the first event in the timeline without removing it\n\t * @returns {Object} The first event object\n\t * @deprecated\n\t */\n\tpeek(): GenericEvent | undefined {\n\t\treturn this._timeline[0];\n\t}\n\n\t/**\n\t * Return the first event in the timeline and remove it\n\t * @deprecated\n\t */\n\tshift(): GenericEvent | undefined {\n\t\treturn this._timeline.shift();\n\t}\n\n\t/**\n\t * Get the event which is scheduled after the given time.\n\t * @param time The time to query.\n\t */\n\tgetAfter(\n\t\ttime: number,\n\t\tparam: TimelineSearchParam = \"time\"\n\t): GenericEvent | null {\n\t\tconst index = this._search(time, param);\n\t\tif (index + 1 < this._timeline.length) {\n\t\t\treturn this._timeline[index + 1];\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * Get the event before the event at the given time.\n\t * @param time The time to query.\n\t */\n\tgetBefore(time: number): GenericEvent | null {\n\t\tconst len = this._timeline.length;\n\t\t// if it's after the last item, return the last item\n\t\tif (len > 0 && this._timeline[len - 1].time < time) {\n\t\t\treturn this._timeline[len - 1];\n\t\t}\n\t\tconst index = this._search(time);\n\t\tif (index - 1 >= 0) {\n\t\t\treturn this._timeline[index - 1];\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * Cancel events at and after the given time\n\t * @param after The time to query.\n\t */\n\tcancel(after: number): this {\n\t\tif (this._timeline.length > 1) {\n\t\t\tlet index = this._search(after);\n\t\t\tif (index >= 0) {\n\t\t\t\tif (EQ(this._timeline[index].time, after)) {\n\t\t\t\t\t// get the first item with that time\n\t\t\t\t\tfor (let i = index; i >= 0; i--) {\n\t\t\t\t\t\tif (EQ(this._timeline[i].time, after)) {\n\t\t\t\t\t\t\tindex = i;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tthis._timeline = this._timeline.slice(0, index);\n\t\t\t\t} else {\n\t\t\t\t\tthis._timeline = this._timeline.slice(0, index + 1);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthis._timeline = [];\n\t\t\t}\n\t\t} else if (this._timeline.length === 1) {\n\t\t\t// the first item's time\n\t\t\tif (GTE(this._timeline[0].time, after)) {\n\t\t\t\tthis._timeline = [];\n\t\t\t}\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Cancel events before or equal to the given time.\n\t * @param time The time to cancel before.\n\t */\n\tcancelBefore(time: number): this {\n\t\tconst index = this._search(time);\n\t\tif (index >= 0) {\n\t\t\tthis._timeline = this._timeline.slice(index + 1);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Returns the previous event if there is one. null otherwise\n\t * @param event The event to find the previous one of\n\t * @return The event right before the given event\n\t */\n\tpreviousEvent(event: GenericEvent): GenericEvent | null {\n\t\tconst index = this._timeline.indexOf(event);\n\t\tif (index > 0) {\n\t\t\treturn this._timeline[index - 1];\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * Does a binary search on the timeline array and returns the\n\t * nearest event index whose time is after or equal to the given time.\n\t * If a time is searched before the first index in the timeline, -1 is returned.\n\t * If the time is after the end, the index of the last item is returned.\n\t */\n\tprotected _search(\n\t\ttime: number,\n\t\tparam: TimelineSearchParam = \"time\"\n\t): number {\n\t\tif (this._timeline.length === 0) {\n\t\t\treturn -1;\n\t\t}\n\t\tlet beginning = 0;\n\t\tconst len = this._timeline.length;\n\t\tlet end = len;\n\t\tif (len > 0 && this._timeline[len - 1][param] <= time) {\n\t\t\treturn len - 1;\n\t\t}\n\t\twhile (beginning < end) {\n\t\t\t// calculate the midpoint for roughly equal partition\n\t\t\tlet midPoint = Math.floor(beginning + (end - beginning) / 2);\n\t\t\tconst event = this._timeline[midPoint];\n\t\t\tconst nextEvent = this._timeline[midPoint + 1];\n\t\t\tif (EQ(event[param], time)) {\n\t\t\t\t// choose the last one that has the same time\n\t\t\t\tfor (let i = midPoint; i < this._timeline.length; i++) {\n\t\t\t\t\tconst testEvent = this._timeline[i];\n\t\t\t\t\tif (EQ(testEvent[param], time)) {\n\t\t\t\t\t\tmidPoint = i;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn midPoint;\n\t\t\t} else if (LT(event[param], time) && GT(nextEvent[param], time)) {\n\t\t\t\treturn midPoint;\n\t\t\t} else if (GT(event[param], time)) {\n\t\t\t\t// search lower\n\t\t\t\tend = midPoint;\n\t\t\t} else {\n\t\t\t\t// search upper\n\t\t\t\tbeginning = midPoint + 1;\n\t\t\t}\n\t\t}\n\t\treturn -1;\n\t}\n\n\t/**\n\t * Internal iterator. Applies extra safety checks for\n\t * removing items from the array.\n\t */\n\tprivate _iterate(\n\t\tcallback: (event: GenericEvent) => void,\n\t\tlowerBound = 0,\n\t\tupperBound = this._timeline.length - 1\n\t): void {\n\t\tthis._timeline.slice(lowerBound, upperBound + 1).forEach(callback);\n\t}\n\n\t/**\n\t * Iterate over everything in the array\n\t * @param callback The callback to invoke with every item\n\t */\n\tforEach(callback: (event: GenericEvent) => void): this {\n\t\tthis._iterate(callback);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Iterate over everything in the array at or before the given time.\n\t * @param time The time to check if items are before\n\t * @param callback The callback to invoke with every item\n\t */\n\tforEachBefore(\n\t\ttime: Seconds,\n\t\tcallback: (event: GenericEvent) => void\n\t): this {\n\t\t// iterate over the items in reverse so that removing an item doesn't break things\n\t\tconst upperBound = this._search(time);\n\t\tif (upperBound !== -1) {\n\t\t\tthis._iterate(callback, 0, upperBound);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Iterate over everything in the array after the given time.\n\t * @param time The time to check if items are before\n\t * @param callback The callback to invoke with every item\n\t */\n\tforEachAfter(time: Seconds, callback: (event: GenericEvent) => void): this {\n\t\t// iterate over the items in reverse so that removing an item doesn't break things\n\t\tconst lowerBound = this._search(time);\n\t\tthis._iterate(callback, lowerBound + 1);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Iterate over everything in the array between the startTime and endTime.\n\t * The timerange is inclusive of the startTime, but exclusive of the endTime.\n\t * range = [startTime, endTime).\n\t * @param startTime The time to check if items are before\n\t * @param endTime The end of the test interval.\n\t * @param callback The callback to invoke with every item\n\t */\n\tforEachBetween(\n\t\tstartTime: number,\n\t\tendTime: number,\n\t\tcallback: (event: GenericEvent) => void\n\t): this {\n\t\tlet lowerBound = this._search(startTime);\n\t\tlet upperBound = this._search(endTime);\n\t\tif (lowerBound !== -1 && upperBound !== -1) {\n\t\t\tif (this._timeline[lowerBound].time !== startTime) {\n\t\t\t\tlowerBound += 1;\n\t\t\t}\n\t\t\t// exclusive of the end time\n\t\t\tif (this._timeline[upperBound].time === endTime) {\n\t\t\t\tupperBound -= 1;\n\t\t\t}\n\t\t\tthis._iterate(callback, lowerBound, upperBound);\n\t\t} else if (lowerBound === -1) {\n\t\t\tthis._iterate(callback, 0, upperBound);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Iterate over everything in the array at or after the given time. Similar to\n\t * forEachAfter, but includes the item(s) at the given time.\n\t * @param time The time to check if items are before\n\t * @param callback The callback to invoke with every item\n\t */\n\tforEachFrom(time: number, callback: (event: GenericEvent) => void): this {\n\t\t// iterate over the items in reverse so that removing an item doesn't break things\n\t\tlet lowerBound = this._search(time);\n\t\t// work backwards until the event time is less than time\n\t\twhile (lowerBound >= 0 && this._timeline[lowerBound].time >= time) {\n\t\t\tlowerBound--;\n\t\t}\n\t\tthis._iterate(callback, lowerBound + 1);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Iterate over everything in the array at the given time\n\t * @param time The time to check if items are before\n\t * @param callback The callback to invoke with every item\n\t */\n\tforEachAtTime(time: number, callback: (event: GenericEvent) => void): this {\n\t\t// iterate over the items in reverse so that removing an item doesn't break things\n\t\tconst upperBound = this._search(time);\n\t\tif (upperBound !== -1 && EQ(this._timeline[upperBound].time, time)) {\n\t\t\tlet lowerBound = upperBound;\n\t\t\tfor (let i = upperBound; i >= 0; i--) {\n\t\t\t\tif (EQ(this._timeline[i].time, time)) {\n\t\t\t\t\tlowerBound = i;\n\t\t\t\t} else {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis._iterate(\n\t\t\t\t(event) => {\n\t\t\t\t\tcallback(event);\n\t\t\t\t},\n\t\t\t\tlowerBound,\n\t\t\t\tupperBound\n\t\t\t);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Clean up.\n\t */\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis._timeline = [];\n\t\treturn this;\n\t}\n}\n","//-------------------------------------\n// INITIALIZING NEW CONTEXT\n//-------------------------------------\nimport type { Context } from \"./Context.js\";\n\n/**\n * Array of callbacks to invoke when a new context is created\n */\nconst notifyNewContext: Array<(ctx: Context) => void> = [];\n\n/**\n * Used internally to setup a new Context\n */\nexport function onContextInit(cb: (ctx: Context) => void): void {\n\tnotifyNewContext.push(cb);\n}\n\n/**\n * Invoke any classes which need to also be initialized when a new context is created.\n */\nexport function initializeContext(ctx: Context): void {\n\t// add any additional modules\n\tnotifyNewContext.forEach((cb) => cb(ctx));\n}\n\n/**\n * Array of callbacks to invoke when a new context is closed\n */\nconst notifyCloseContext: Array<(ctx: Context) => void> = [];\n\n/**\n * Used internally to tear down a Context\n */\nexport function onContextClose(cb: (ctx: Context) => void): void {\n\tnotifyCloseContext.push(cb);\n}\n\nexport function closeContext(ctx: Context): void {\n\t// remove any additional modules\n\tnotifyCloseContext.forEach((cb) => cb(ctx));\n}\n","import { Tone } from \"../Tone.js\";\nimport { isUndef } from \"./TypeCheck.js\";\n\nexport interface EmitterEventObject {\n\t[event: string]: Array<(...args: any[]) => void>;\n}\n\n/**\n * Emitter gives classes which extend it\n * the ability to listen for and emit events.\n * Inspiration and reference from Jerome Etienne's [MicroEvent](https://github.com/jeromeetienne/microevent.js).\n * MIT (c) 2011 Jerome Etienne.\n * @category Core\n */\nexport class Emitter<EventType extends string = string> extends Tone {\n\treadonly name: string = \"Emitter\";\n\n\t/**\n\t * Private container for the events\n\t */\n\tprivate _events?: EmitterEventObject;\n\n\t/**\n\t * Bind a callback to a specific event.\n\t * @param event The name of the event to listen for.\n\t * @param callback The callback to invoke when the event is emitted\n\t */\n\ton(event: EventType, callback: (...args: any[]) => void): this {\n\t\t// split the event\n\t\tconst events = event.split(/\\W+/);\n\t\tevents.forEach((eventName) => {\n\t\t\tif (isUndef(this._events)) {\n\t\t\t\tthis._events = {};\n\t\t\t}\n\t\t\tif (!this._events.hasOwnProperty(eventName)) {\n\t\t\t\tthis._events[eventName] = [];\n\t\t\t}\n\t\t\tthis._events[eventName].push(callback);\n\t\t});\n\t\treturn this;\n\t}\n\n\t/**\n\t * Bind a callback which is only invoked once\n\t * @param event The name of the event to listen for.\n\t * @param callback The callback to invoke when the event is emitted\n\t */\n\tonce(event: EventType, callback: (...args: any[]) => void): this {\n\t\tconst boundCallback = (...args: any[]) => {\n\t\t\t// invoke the callback\n\t\t\tcallback(...args);\n\t\t\t// remove the event\n\t\t\tthis.off(event, boundCallback);\n\t\t};\n\t\tthis.on(event, boundCallback);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Remove the event listener.\n\t * @param event The event to stop listening to.\n\t * @param callback The callback which was bound to the event with Emitter.on.\n\t * If no callback is given, all callbacks events are removed.\n\t */\n\toff(event: EventType, callback?: (...args: any[]) => void): this {\n\t\tconst events = event.split(/\\W+/);\n\t\tevents.forEach((eventName) => {\n\t\t\tif (isUndef(this._events)) {\n\t\t\t\tthis._events = {};\n\t\t\t}\n\t\t\tif (this._events.hasOwnProperty(eventName)) {\n\t\t\t\tif (isUndef(callback)) {\n\t\t\t\t\tthis._events[eventName] = [];\n\t\t\t\t} else {\n\t\t\t\t\tconst eventList = this._events[eventName];\n\t\t\t\t\tfor (let i = eventList.length - 1; i >= 0; i--) {\n\t\t\t\t\t\tif (eventList[i] === callback) {\n\t\t\t\t\t\t\teventList.splice(i, 1);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\treturn this;\n\t}\n\n\t/**\n\t * Invoke all of the callbacks bound to the event\n\t * with any arguments passed in.\n\t * @param event The name of the event.\n\t * @param args The arguments to pass to the functions listening.\n\t */\n\temit(event: EventType, ...args: any[]): this {\n\t\tif (this._events) {\n\t\t\tif (this._events.hasOwnProperty(event)) {\n\t\t\t\tconst eventList = this._events[event].slice(0);\n\t\t\t\tfor (let i = 0, len = eventList.length; i < len; i++) {\n\t\t\t\t\teventList[i].apply(this, args);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Add Emitter functions (on/off/emit) to the object\n\t */\n\tstatic mixin(constr: any): void {\n\t\t// instance._events = {};\n\t\t[\"on\", \"once\", \"off\", \"emit\"].forEach((name) => {\n\t\t\tconst property = Object.getOwnPropertyDescriptor(\n\t\t\t\tEmitter.prototype,\n\t\t\t\tname\n\t\t\t) as PropertyDescriptor;\n\t\t\tObject.defineProperty(constr.prototype, name, property);\n\t\t});\n\t}\n\n\t/**\n\t * Clean up\n\t */\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis._events = undefined;\n\t\treturn this;\n\t}\n}\n","import { Seconds } from \"../type/Units.js\";\nimport { Emitter } from \"../util/Emitter.js\";\nimport { AnyAudioContext } from \"./AudioContext.js\";\nimport type { DrawClass as Draw } from \"../util/Draw.js\";\nimport type { DestinationClass as Destination } from \"./Destination.js\";\nimport type { TransportClass as Transport } from \"../clock/Transport.js\";\nimport type { ListenerClass as Listener } from \"./Listener.js\";\n\n// these are either not used in Tone.js or deprecated and not implemented.\nexport type ExcludedFromBaseAudioContext =\n\t| \"onstatechange\"\n\t| \"addEventListener\"\n\t| \"removeEventListener\"\n\t| \"listener\"\n\t| \"dispatchEvent\"\n\t| \"audioWorklet\"\n\t| \"destination\"\n\t| \"createScriptProcessor\";\n\n// the subset of the BaseAudioContext which Tone.Context implements.\nexport type BaseAudioContextSubset = Omit<\n\tBaseAudioContext,\n\tExcludedFromBaseAudioContext\n>;\n\nexport type ContextLatencyHint = AudioContextLatencyCategory;\n\nexport abstract class BaseContext\n\textends Emitter<\"statechange\" | \"tick\">\n\timplements BaseAudioContextSubset\n{\n\t//---------------------------\n\t// BASE AUDIO CONTEXT METHODS\n\t//---------------------------\n\tabstract createAnalyser(): AnalyserNode;\n\n\tabstract createOscillator(): OscillatorNode;\n\n\tabstract createBufferSource(): AudioBufferSourceNode;\n\n\tabstract createBiquadFilter(): BiquadFilterNode;\n\n\tabstract createBuffer(\n\t\t_numberOfChannels: number,\n\t\t_length: number,\n\t\t_sampleRate: number\n\t): AudioBuffer;\n\n\tabstract createChannelMerger(\n\t\t_numberOfInputs?: number | undefined\n\t): ChannelMergerNode;\n\n\tabstract createChannelSplitter(\n\t\t_numberOfOutputs?: number | undefined\n\t): ChannelSplitterNode;\n\n\tabstract createConstantSource(): ConstantSourceNode;\n\n\tabstract createConvolver(): ConvolverNode;\n\n\tabstract createDelay(_maxDelayTime?: number | undefined): DelayNode;\n\n\tabstract createDynamicsCompressor(): DynamicsCompressorNode;\n\n\tabstract createGain(): GainNode;\n\n\tabstract createIIRFilter(\n\t\t_feedForward: number[] | Float32Array,\n\t\t_feedback: number[] | Float32Array\n\t): IIRFilterNode;\n\n\tabstract createPanner(): PannerNode;\n\n\tabstract createPeriodicWave(\n\t\t_real: number[] | Float32Array,\n\t\t_imag: number[] | Float32Array,\n\t\t_constraints?: PeriodicWaveConstraints | undefined\n\t): PeriodicWave;\n\n\tabstract createStereoPanner(): StereoPannerNode;\n\n\tabstract createWaveShaper(): WaveShaperNode;\n\n\tabstract createMediaStreamSource(\n\t\t_stream: MediaStream\n\t): MediaStreamAudioSourceNode;\n\n\tabstract createMediaElementSource(\n\t\t_element: HTMLMediaElement\n\t): MediaElementAudioSourceNode;\n\n\tabstract createMediaStreamDestination(): MediaStreamAudioDestinationNode;\n\n\tabstract decodeAudioData(_audioData: ArrayBuffer): Promise<AudioBuffer>;\n\n\t//---------------------------\n\t// TONE AUDIO CONTEXT METHODS\n\t//---------------------------\n\n\tabstract createAudioWorkletNode(\n\t\t_name: string,\n\t\t_options?: Partial<AudioWorkletNodeOptions>\n\t): AudioWorkletNode;\n\n\tabstract get rawContext(): AnyAudioContext;\n\n\tabstract addAudioWorkletModule(_url: string): Promise<void>;\n\n\tabstract lookAhead: number;\n\n\tabstract latencyHint: ContextLatencyHint | Seconds;\n\n\tabstract resume(): Promise<void>;\n\n\tabstract setTimeout(\n\t\t_fn: (...args: any[]) => void,\n\t\t_timeout: Seconds\n\t): number;\n\n\tabstract clearTimeout(_id: number): this;\n\n\tabstract setInterval(\n\t\t_fn: (...args: any[]) => void,\n\t\t_interval: Seconds\n\t): number;\n\n\tabstract clearInterval(_id: number): this;\n\n\tabstract getConstant(_val: number): AudioBufferSourceNode;\n\n\tabstract get currentTime(): Seconds;\n\n\tabstract get state(): AudioContextState;\n\n\tabstract get sampleRate(): number;\n\n\tabstract get listener(): Listener;\n\n\tabstract get transport(): Transport;\n\n\tabstract get draw(): Draw;\n\n\tabstract get destination(): Destination;\n\n\tabstract now(): Seconds;\n\n\tabstract immediate(): Seconds;\n\n\t/*\n\t * This is a placeholder so that JSON.stringify does not throw an error\n\t * This matches what JSON.stringify(audioContext) returns on a native\n\t * audioContext instance.\n\t */\n\ttoJSON(): Record<string, any> {\n\t\treturn {};\n\t}\n\n\treadonly isOffline: boolean = false;\n}\n","import { Ticker, TickerClockSource } from \"../clock/Ticker.js\";\nimport { Seconds } from \"../type/Units.js\";\nimport { isAudioContext } from \"../util/AdvancedTypeCheck.js\";\nimport { optionsFromArguments } from \"../util/Defaults.js\";\nimport { Timeline } from \"../util/Timeline.js\";\nimport { isDefined } from \"../util/TypeCheck.js\";\nimport {\n\tAnyAudioContext,\n\tcreateAudioContext,\n\tcreateAudioWorkletNode,\n} from \"./AudioContext.js\";\nimport { closeContext, initializeContext } from \"./ContextInitialization.js\";\nimport { BaseContext, ContextLatencyHint } from \"./BaseContext.js\";\nimport { assert } from \"../util/Debug.js\";\nimport type { DrawClass as Draw } from \"../util/Draw.js\";\nimport type { DestinationClass as Destination } from \"./Destination.js\";\nimport type { TransportClass as Transport } from \"../clock/Transport.js\";\nimport type { ListenerClass as Listener } from \"./Listener.js\";\n\nexport interface ContextOptions {\n\tclockSource: TickerClockSource;\n\tlatencyHint: ContextLatencyHint;\n\tlookAhead: Seconds;\n\tupdateInterval: Seconds;\n\tcontext: AnyAudioContext;\n}\n\nexport interface ContextTimeoutEvent {\n\tcallback: (...args: any[]) => void;\n\tid: number;\n\ttime: Seconds;\n}\n\n/**\n * Wrapper around the native AudioContext.\n * @category Core\n */\nexport class Context extends BaseContext {\n\treadonly name: string = \"Context\";\n\n\t/**\n\t * private reference to the BaseAudioContext\n\t */\n\tprotected readonly _context: AnyAudioContext;\n\n\t/**\n\t * A reliable callback method\n\t */\n\tprivate readonly _ticker: Ticker;\n\n\t/**\n\t * The default latency hint\n\t */\n\tprivate _latencyHint!: ContextLatencyHint | Seconds;\n\n\t/**\n\t * An object containing all of the constants AudioBufferSourceNodes\n\t */\n\tprivate _constants = new Map<number, AudioBufferSourceNode>();\n\n\t/**\n\t * All of the setTimeout events.\n\t */\n\tprivate _timeouts: Timeline<ContextTimeoutEvent> = new Timeline();\n\n\t/**\n\t * The timeout id counter\n\t */\n\tprivate _timeoutIds = 0;\n\n\t/**\n\t * A reference the Transport singleton belonging to this context\n\t */\n\tprivate _transport!: Transport;\n\n\t/**\n\t * A reference the Listener singleton belonging to this context\n\t */\n\tprivate _listener!: Listener;\n\n\t/**\n\t * A reference the Destination singleton belonging to this context\n\t */\n\tprivate _destination!: Destination;\n\n\t/**\n\t * A reference the Transport singleton belonging to this context\n\t */\n\tprivate _draw!: Draw;\n\n\t/**\n\t * Private indicator if the context has been initialized\n\t */\n\tprivate _initialized = false;\n\n\t/**\n\t * Private indicator if a close() has been called on the context, since close is async\n\t */\n\tprivate _closeStarted = false;\n\n\t/**\n\t * Indicates if the context is an OfflineAudioContext or an AudioContext\n\t */\n\treadonly isOffline: boolean = false;\n\n\tconstructor(context?: AnyAudioContext);\n\tconstructor(options?: Partial<ContextOptions>);\n\tconstructor() {\n\t\tsuper();\n\t\tconst options = optionsFromArguments(Context.getDefaults(), arguments, [\n\t\t\t\"context\",\n\t\t]);\n\n\t\tif (options.context) {\n\t\t\tthis._context = options.context;\n\t\t\t// custom context provided, latencyHint unknown (unless explicitly provided in options)\n\t\t\tthis._latencyHint = arguments[0]?.latencyHint || \"\";\n\t\t} else {\n\t\t\tthis._context = createAudioContext({\n\t\t\t\tlatencyHint: options.latencyHint,\n\t\t\t});\n\t\t\tthis._latencyHint = options.latencyHint;\n\t\t}\n\n\t\tthis._ticker = new Ticker(\n\t\t\tthis.emit.bind(this, \"tick\"),\n\t\t\toptions.clockSource,\n\t\t\toptions.updateInterval,\n\t\t\tthis._context.sampleRate\n\t\t);\n\t\tthis.on(\"tick\", this._timeoutLoop.bind(this));\n\n\t\t// fwd events from the context\n\t\tthis._context.onstatechange = () => {\n\t\t\tthis.emit(\"statechange\", this.state);\n\t\t};\n\n\t\t// if no custom updateInterval provided, updateInterval will be derived by lookAhead setter\n\t\tthis[\n\t\t\targuments[0]?.hasOwnProperty(\"updateInterval\")\n\t\t\t\t? \"_lookAhead\"\n\t\t\t\t: \"lookAhead\"\n\t\t] = options.lookAhead;\n\t}\n\n\tstatic getDefaults(): ContextOptions {\n\t\treturn {\n\t\t\tclockSource: \"worker\",\n\t\t\tlatencyHint: \"interactive\",\n\t\t\tlookAhead: 0.1,\n\t\t\tupdateInterval: 0.05,\n\t\t} as ContextOptions;\n\t}\n\n\t/**\n\t * Finish setting up the context. **You usually do not need to do this manually.**\n\t */\n\tprivate initialize(): this {\n\t\tif (!this._initialized) {\n\t\t\t// add any additional modules\n\t\t\tinitializeContext(this);\n\t\t\tthis._initialized = true;\n\t\t}\n\t\treturn this;\n\t}\n\n\t//---------------------------\n\t// BASE AUDIO CONTEXT METHODS\n\t//---------------------------\n\n\tcreateAnalyser(): AnalyserNode {\n\t\treturn this._context.createAnalyser();\n\t}\n\tcreateOscillator(): OscillatorNode {\n\t\treturn this._context.createOscillator();\n\t}\n\tcreateBufferSource(): AudioBufferSourceNode {\n\t\treturn this._context.createBufferSource();\n\t}\n\tcreateBiquadFilter(): BiquadFilterNode {\n\t\treturn this._context.createBiquadFilter();\n\t}\n\tcreateBuffer(\n\t\tnumberOfChannels: number,\n\t\tlength: number,\n\t\tsampleRate: number\n\t): AudioBuffer {\n\t\treturn this._context.createBuffer(numberOfChannels, length, sampleRate);\n\t}\n\tcreateChannelMerger(\n\t\tnumberOfInputs?: number | undefined\n\t): ChannelMergerNode {\n\t\treturn this._context.createChannelMerger(numberOfInputs);\n\t}\n\tcreateChannelSplitter(\n\t\tnumberOfOutputs?: number | undefined\n\t): ChannelSplitterNode {\n\t\treturn this._context.createChannelSplitter(numberOfOutputs);\n\t}\n\tcreateConstantSource(): ConstantSourceNode {\n\t\treturn this._context.createConstantSource();\n\t}\n\tcreateConvolver(): ConvolverNode {\n\t\treturn this._context.createConvolver();\n\t}\n\tcreateDelay(maxDelayTime?: number | undefined): DelayNode {\n\t\treturn this._context.createDelay(maxDelayTime);\n\t}\n\tcreateDynamicsCompressor(): DynamicsCompressorNode {\n\t\treturn this._context.createDynamicsCompressor();\n\t}\n\tcreateGain(): GainNode {\n\t\treturn this._context.createGain();\n\t}\n\tcreateIIRFilter(\n\t\tfeedForward: number[] | Float32Array,\n\t\tfeedback: number[] | Float32Array\n\t): IIRFilterNode {\n\t\t// @ts-ignore\n\t\treturn this._context.createIIRFilter(feedForward, feedback);\n\t}\n\tcreatePanner(): PannerNode {\n\t\treturn this._context.createPanner();\n\t}\n\tcreatePeriodicWave(\n\t\treal: number[] | Float32Array,\n\t\timag: number[] | Float32Array,\n\t\tconstraints?: PeriodicWaveConstraints | undefined\n\t): PeriodicWave {\n\t\treturn this._context.createPeriodicWave(real, imag, constraints);\n\t}\n\tcreateStereoPanner(): StereoPannerNode {\n\t\treturn this._context.createStereoPanner();\n\t}\n\tcreateWaveShaper(): WaveShaperNode {\n\t\treturn this._context.createWaveShaper();\n\t}\n\tcreateMediaStreamSource(stream: MediaStream): MediaStreamAudioSourceNode {\n\t\tassert(\n\t\t\tisAudioContext(this._context),\n\t\t\t\"Not available if OfflineAudioContext\"\n\t\t);\n\t\tconst context = this._context as AudioContext;\n\t\treturn context.createMediaStreamSource(stream);\n\t}\n\tcreateMediaElementSource(\n\t\telement: HTMLMediaElement\n\t): MediaElementAudioSourceNode {\n\t\tassert(\n\t\t\tisAudioContext(this._context),\n\t\t\t\"Not available if OfflineAudioContext\"\n\t\t);\n\t\tconst context = this._context as AudioContext;\n\t\treturn context.createMediaElementSource(element);\n\t}\n\tcreateMediaStreamDestination(): MediaStreamAudioDestinationNode {\n\t\tassert(\n\t\t\tisAudioContext(this._context),\n\t\t\t\"Not available if OfflineAudioContext\"\n\t\t);\n\t\tconst context = this._context as AudioContext;\n\t\treturn context.createMediaStreamDestination();\n\t}\n\tdecodeAudioData(audioData: ArrayBuffer): Promise<AudioBuffer> {\n\t\treturn this._context.decodeAudioData(audioData);\n\t}\n\n\t/**\n\t * The current time in seconds of the AudioContext.\n\t */\n\tget currentTime(): Seconds {\n\t\treturn this._context.currentTime;\n\t}\n\t/**\n\t * The current time in seconds of the AudioContext.\n\t */\n\tget state(): AudioContextState {\n\t\treturn this._context.state;\n\t}\n\t/**\n\t * The current time in seconds of the AudioContext.\n\t */\n\tget sampleRate(): number {\n\t\treturn this._context.sampleRate;\n\t}\n\n\t/**\n\t * The listener\n\t */\n\tget listener(): Listener {\n\t\tthis.initialize();\n\t\treturn this._listener;\n\t}\n\tset listener(l) {\n\t\tassert(\n\t\t\t!this._initialized,\n\t\t\t\"The listener cannot be set after initialization.\"\n\t\t);\n\t\tthis._listener = l;\n\t}\n\n\t/**\n\t * There is only one Transport per Context. It is created on initialization.\n\t */\n\tget transport(): Transport {\n\t\tthis.initialize();\n\t\treturn this._transport;\n\t}\n\tset transport(t: Transport) {\n\t\tassert(\n\t\t\t!this._initialized,\n\t\t\t\"The transport cannot be set after initialization.\"\n\t\t);\n\t\tthis._transport = t;\n\t}\n\n\t/**\n\t * This is the Draw object for the context which is useful for synchronizing the draw frame with the Tone.js clock.\n\t */\n\tget draw(): Draw {\n\t\tthis.initialize();\n\t\treturn this._draw;\n\t}\n\tset draw(d) {\n\t\tassert(!this._initialized, \"Draw cannot be set after initialization.\");\n\t\tthis._draw = d;\n\t}\n\n\t/**\n\t * A reference to the Context's destination node.\n\t */\n\tget destination(): Destination {\n\t\tthis.initialize();\n\t\treturn this._destination;\n\t}\n\tset destination(d: Destination) {\n\t\tassert(\n\t\t\t!this._initialized,\n\t\t\t\"The destination cannot be set after initialization.\"\n\t\t);\n\t\tthis._destination = d;\n\t}\n\n\t//--------------------------------------------\n\t// AUDIO WORKLET\n\t//--------------------------------------------\n\n\t/**\n\t * Maps a module name to promise of the addModule method\n\t */\n\tprivate _workletPromise: null | Promise<void> = null;\n\n\t/**\n\t * Create an audio worklet node from a name and options. The module\n\t * must first be loaded using {@link addAudioWorkletModule}.\n\t */\n\tcreateAudioWorkletNode(\n\t\tname: string,\n\t\toptions?: Partial<AudioWorkletNodeOptions>\n\t): AudioWorkletNode {\n\t\treturn createAudioWorkletNode(this.rawContext, name, options);\n\t}\n\n\t/**\n\t * Add an AudioWorkletProcessor module\n\t * @param url The url of the module\n\t */\n\tasync addAudioWorkletModule(url: string): Promise<void> {\n\t\tassert(\n\t\t\tisDefined(this.rawContext.audioWorklet),\n\t\t\t\"AudioWorkletNode is only available in a secure context (https or localhost)\"\n\t\t);\n\t\tif (!this._workletPromise) {\n\t\t\tthis._workletPromise = this.rawContext.audioWorklet.addModule(url);\n\t\t}\n\t\tawait this._workletPromise;\n\t}\n\n\t/**\n\t * Returns a promise which resolves when all of the worklets have been loaded on this context\n\t */\n\tprotected async workletsAreReady(): Promise<void> {\n\t\t(await this._workletPromise) ? this._workletPromise : Promise.resolve();\n\t}\n\n\t//---------------------------\n\t// TICKER\n\t//---------------------------\n\n\t/**\n\t * How often the interval callback is invoked.\n\t * This number corresponds to how responsive the scheduling\n\t * can be. Setting to 0 will result in the lowest practial interval\n\t * based on context properties. context.updateInterval + context.lookAhead\n\t * gives you the total latency between scheduling an event and hearing it.\n\t */\n\tget updateInterval(): Seconds {\n\t\treturn this._ticker.updateInterval;\n\t}\n\tset updateInterval(interval: Seconds) {\n\t\tthis._ticker.updateInterval = interval;\n\t}\n\n\t/**\n\t * What the source of the clock is, either \"worker\" (default),\n\t * \"timeout\", or \"offline\" (none).\n\t */\n\tget clockSource(): TickerClockSource {\n\t\treturn this._ticker.type;\n\t}\n\tset clockSource(type: TickerClockSource) {\n\t\tthis._ticker.type = type;\n\t}\n\n\t/**\n\t * The amount of time into the future events are scheduled. Giving Web Audio\n\t * a short amount of time into the future to schedule events can reduce clicks and\n\t * improve performance. This value can be set to 0 to get the lowest latency.\n\t * Adjusting this value also affects the {@link updateInterval}.\n\t */\n\tget lookAhead(): Seconds {\n\t\treturn this._lookAhead;\n\t}\n\tset lookAhead(time: Seconds) {\n\t\tthis._lookAhead = time;\n\t\t// if lookAhead is 0, default to .01 updateInterval\n\t\tthis.updateInterval = time ? time / 2 : 0.01;\n\t}\n\tprivate _lookAhead!: Seconds;\n\n\t/**\n\t * The type of playback, which affects tradeoffs between audio\n\t * output latency and responsiveness.\n\t * In addition to setting the value in seconds, the latencyHint also\n\t * accepts the strings \"interactive\" (prioritizes low latency),\n\t * \"playback\" (prioritizes sustained playback), \"balanced\" (balances\n\t * latency and performance).\n\t * @example\n\t * // prioritize sustained playback\n\t * const context = new Tone.Context({ latencyHint: \"playback\" });\n\t * // set this context as the global Context\n\t * Tone.setContext(context);\n\t * // the global context is gettable with Tone.getContext()\n\t * console.log(Tone.getContext().latencyHint);\n\t */\n\tget latencyHint(): ContextLatencyHint | Seconds {\n\t\treturn this._latencyHint;\n\t}\n\n\t/**\n\t * The unwrapped AudioContext or OfflineAudioContext\n\t */\n\tget rawContext(): AnyAudioContext {\n\t\treturn this._context;\n\t}\n\n\t/**\n\t * The current audio context time plus a short {@link lookAhead}.\n\t * @example\n\t * setInterval(() => {\n\t * \tconsole.log(\"now\", Tone.now());\n\t * }, 100);\n\t */\n\tnow(): Seconds {\n\t\treturn this._context.currentTime + this._lookAhead;\n\t}\n\n\t/**\n\t * The current audio context time without the {@link lookAhead}.\n\t * In most cases it is better to use {@link now} instead of {@link immediate} since\n\t * with {@link now} the {@link lookAhead} is applied equally to _all_ components including internal components,\n\t * to making sure that everything is scheduled in sync. Mixing {@link now} and {@link immediate}\n\t * can cause some timing issues. If no lookAhead is desired, you can set the {@link lookAhead} to `0`.\n\t */\n\timmediate(): Seconds {\n\t\treturn this._context.currentTime;\n\t}\n\n\t/**\n\t * Starts the audio context from a suspended state. This is required\n\t * to initially start the AudioContext.\n\t * @see {@link start}\n\t */\n\tresume(): Promise<void> {\n\t\tif (isAudioContext(this._context)) {\n\t\t\treturn this._context.resume();\n\t\t} else {\n\t\t\treturn Promise.resolve();\n\t\t}\n\t}\n\n\t/**\n\t * Close the context. Once closed, the context can no longer be used and\n\t * any AudioNodes created from the context will be silent.\n\t */\n\tasync close(): Promise<void> {\n\t\tif (\n\t\t\tisAudioContext(this._context) &&\n\t\t\tthis.state !== \"closed\" &&\n\t\t\t!this._closeStarted\n\t\t) {\n\t\t\tthis._closeStarted = true;\n\t\t\tawait this._context.close();\n\t\t}\n\t\tif (this._initialized) {\n\t\t\tcloseContext(this);\n\t\t}\n\t}\n\n\t/**\n\t * **Internal** Generate a looped buffer at some constant value.\n\t */\n\tgetConstant(val: number): AudioBufferSourceNode {\n\t\tif (this._constants.has(val)) {\n\t\t\treturn this._constants.get(val) as AudioBufferSourceNode;\n\t\t} else {\n\t\t\tconst buffer = this._context.createBuffer(\n\t\t\t\t1,\n\t\t\t\t128,\n\t\t\t\tthis._context.sampleRate\n\t\t\t);\n\t\t\tconst arr = buffer.getChannelData(0);\n\t\t\tfor (let i = 0; i < arr.length; i++) {\n\t\t\t\tarr[i] = val;\n\t\t\t}\n\t\t\tconst constant = this._context.createBufferSource();\n\t\t\tconstant.channelCount = 1;\n\t\t\tconstant.channelCountMode = \"explicit\";\n\t\t\tconstant.buffer = buffer;\n\t\t\tconstant.loop = true;\n\t\t\tconstant.start(0);\n\t\t\tthis._constants.set(val, constant);\n\t\t\treturn constant;\n\t\t}\n\t}\n\n\t/**\n\t * Clean up. Also closes the audio context.\n\t */\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis._ticker.dispose();\n\t\tthis._timeouts.dispose();\n\t\tObject.keys(this._constants).map((val) =>\n\t\t\tthis._constants[val].disconnect()\n\t\t);\n\t\tthis.close();\n\t\treturn this;\n\t}\n\n\t//---------------------------\n\t// TIMEOUTS\n\t//---------------------------\n\n\t/**\n\t * The private loop which keeps track of the context scheduled timeouts\n\t * Is invoked from the clock source\n\t */\n\tprivate _timeoutLoop(): void {\n\t\tconst now = this.now();\n\t\tthis._timeouts.forEachBefore(now, (event) => {\n\t\t\t// invoke the callback\n\t\t\tevent.callback();\n\t\t\tthis._timeouts.remove(event);\n\t\t});\n\t}\n\n\t/**\n\t * A setTimeout which is guaranteed by the clock source.\n\t * Also runs in the offline context.\n\t * @param fn The callback to invoke\n\t * @param timeout The timeout in seconds\n\t * @returns ID to use when invoking Context.clearTimeout\n\t */\n\tsetTimeout(fn: (...args: any[]) => void, timeout: Seconds): number {\n\t\tthis._timeoutIds++;\n\t\tconst now = this.now();\n\t\tthis._timeouts.add({\n\t\t\tcallback: fn,\n\t\t\tid: this._timeoutIds,\n\t\t\ttime: now + timeout,\n\t\t});\n\t\treturn this._timeoutIds;\n\t}\n\n\t/**\n\t * Clears a previously scheduled timeout with Tone.context.setTimeout\n\t * @param id The ID returned from setTimeout\n\t */\n\tclearTimeout(id: number): this {\n\t\tthis._timeouts.forEach((event) => {\n\t\t\tif (event.id === id) {\n\t\t\t\tthis._timeouts.remove(event);\n\t\t\t}\n\t\t});\n\t\treturn this;\n\t}\n\n\t/**\n\t * Clear the function scheduled by {@link setInterval}\n\t */\n\tclearInterval(id: number): this {\n\t\treturn this.clearTimeout(id);\n\t}\n\n\t/**\n\t * Adds a repeating event to the context's callback clock\n\t */\n\tsetInterval(fn: (...args: any[]) => void, interval: Seconds): number {\n\t\tconst id = ++this._timeoutIds;\n\t\tconst intervalFn = () => {\n\t\t\tconst now = this.now();\n\t\t\tthis._timeouts.add({\n\t\t\t\tcallback: () => {\n\t\t\t\t\t// invoke the callback\n\t\t\t\t\tfn();\n\t\t\t\t\t// invoke the event to repeat it\n\t\t\t\t\tintervalFn();\n\t\t\t\t},\n\t\t\t\tid,\n\t\t\t\ttime: now + interval,\n\t\t\t});\n\t\t};\n\t\t// kick it off\n\t\tintervalFn();\n\t\treturn id;\n\t}\n}\n","import { BaseContext } from \"./BaseContext.js\";\nimport { Seconds } from \"../type/Units.js\";\nimport { AnyAudioContext } from \"./AudioContext.js\";\nimport type { DrawClass as Draw } from \"../util/Draw.js\";\nimport type { DestinationClass as Destination } from \"./Destination.js\";\nimport type { TransportClass as Transport } from \"../clock/Transport.js\";\nimport type { ListenerClass as Listener } from \"./Listener.js\";\n\nexport class DummyContext extends BaseContext {\n\t//---------------------------\n\t// BASE AUDIO CONTEXT METHODS\n\t//---------------------------\n\tcreateAnalyser(): AnalyserNode {\n\t\treturn {} as AnalyserNode;\n\t}\n\n\tcreateOscillator(): OscillatorNode {\n\t\treturn {} as OscillatorNode;\n\t}\n\n\tcreateBufferSource() {\n\t\treturn {} as AudioBufferSourceNode;\n\t}\n\n\tcreateBiquadFilter(): BiquadFilterNode {\n\t\treturn {} as BiquadFilterNode;\n\t}\n\n\tcreateBuffer(\n\t\t_numberOfChannels: number,\n\t\t_length: number,\n\t\t_sampleRate: number\n\t): AudioBuffer {\n\t\treturn {} as AudioBuffer;\n\t}\n\n\tcreateChannelMerger(\n\t\t_numberOfInputs?: number | undefined\n\t): ChannelMergerNode {\n\t\treturn {} as ChannelMergerNode;\n\t}\n\n\tcreateChannelSplitter(\n\t\t_numberOfOutputs?: number | undefined\n\t): ChannelSplitterNode {\n\t\treturn {} as ChannelSplitterNode;\n\t}\n\n\tcreateConstantSource(): ConstantSourceNode {\n\t\treturn {} as ConstantSourceNode;\n\t}\n\n\tcreateConvolver(): ConvolverNode {\n\t\treturn {} as ConvolverNode;\n\t}\n\n\tcreateDelay(_maxDelayTime?: number | undefined): DelayNode {\n\t\treturn {} as DelayNode;\n\t}\n\n\tcreateDynamicsCompressor(): DynamicsCompressorNode {\n\t\treturn {} as DynamicsCompressorNode;\n\t}\n\n\tcreateGain(): GainNode {\n\t\treturn {} as GainNode;\n\t}\n\n\tcreateIIRFilter(\n\t\t_feedForward: number[] | Float32Array,\n\t\t_feedback: number[] | Float32Array\n\t): IIRFilterNode {\n\t\treturn {} as IIRFilterNode;\n\t}\n\n\tcreatePanner(): PannerNode {\n\t\treturn {} as PannerNode;\n\t}\n\n\tcreatePeriodicWave(\n\t\t_real: number[] | Float32Array,\n\t\t_imag: number[] | Float32Array,\n\t\t_constraints?: PeriodicWaveConstraints | undefined\n\t): PeriodicWave {\n\t\treturn {} as PeriodicWave;\n\t}\n\n\tcreateStereoPanner(): StereoPannerNode {\n\t\treturn {} as StereoPannerNode;\n\t}\n\n\tcreateWaveShaper(): WaveShaperNode {\n\t\treturn {} as WaveShaperNode;\n\t}\n\n\tcreateMediaStreamSource(_stream: MediaStream): MediaStreamAudioSourceNode {\n\t\treturn {} as MediaStreamAudioSourceNode;\n\t}\n\n\tcreateMediaElementSource(\n\t\t_element: HTMLMediaElement\n\t): MediaElementAudioSourceNode {\n\t\treturn {} as MediaElementAudioSourceNode;\n\t}\n\n\tcreateMediaStreamDestination(): MediaStreamAudioDestinationNode {\n\t\treturn {} as MediaStreamAudioDestinationNode;\n\t}\n\n\tdecodeAudioData(_audioData: ArrayBuffer): Promise<AudioBuffer> {\n\t\treturn Promise.resolve({} as AudioBuffer);\n\t}\n\n\t//---------------------------\n\t// TONE AUDIO CONTEXT METHODS\n\t//---------------------------\n\n\tcreateAudioWorkletNode(\n\t\t_name: string,\n\t\t_options?: Partial<AudioWorkletNodeOptions>\n\t): AudioWorkletNode {\n\t\treturn {} as AudioWorkletNode;\n\t}\n\n\tget rawContext(): AnyAudioContext {\n\t\treturn {} as AnyAudioContext;\n\t}\n\n\tasync addAudioWorkletModule(_url: string): Promise<void> {\n\t\treturn Promise.resolve();\n\t}\n\n\tlookAhead = 0;\n\n\tlatencyHint = 0;\n\n\tresume(): Promise<void> {\n\t\treturn Promise.resolve();\n\t}\n\n\tsetTimeout(_fn: (...args: any[]) => void, _timeout: Seconds): number {\n\t\treturn 0;\n\t}\n\n\tclearTimeout(_id: number): this {\n\t\treturn this;\n\t}\n\n\tsetInterval(_fn: (...args: any[]) => void, _interval: Seconds): number {\n\t\treturn 0;\n\t}\n\n\tclearInterval(_id: number): this {\n\t\treturn this;\n\t}\n\n\tgetConstant(_val: number): AudioBufferSourceNode {\n\t\treturn {} as AudioBufferSourceNode;\n\t}\n\n\tget currentTime(): Seconds {\n\t\treturn 0;\n\t}\n\n\tget state(): AudioContextState {\n\t\treturn {} as AudioContextState;\n\t}\n\n\tget sampleRate(): number {\n\t\treturn 0;\n\t}\n\n\tget listener(): Listener {\n\t\treturn {} as Listener;\n\t}\n\n\tget transport(): Transport {\n\t\treturn {} as Transport;\n\t}\n\n\tget draw(): Draw {\n\t\treturn {} as Draw;\n\t}\n\tset draw(_d) {}\n\n\tget destination(): Destination {\n\t\treturn {} as Destination;\n\t}\n\tset destination(_d: Destination) {}\n\n\tnow() {\n\t\treturn 0;\n\t}\n\n\timmediate() {\n\t\treturn 0;\n\t}\n\n\treadonly isOffline: boolean = false;\n}\n","import { isArray } from \"./TypeCheck.js\";\n\n// return an interface which excludes certain keys\nexport type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;\n\n/**\n * Make the property not writable using `defineProperty`. Internal use only.\n */\nexport function readOnly(target: object, property: string | string[]): void {\n\tif (isArray(property)) {\n\t\tproperty.forEach((str) => readOnly(target, str));\n\t} else {\n\t\tObject.defineProperty(target, property, {\n\t\t\tenumerable: true,\n\t\t\twritable: false,\n\t\t});\n\t}\n}\n\n/**\n * Make an attribute writeable. Internal use only.\n */\nexport function writable(target: object, property: string | string[]): void {\n\tif (isArray(property)) {\n\t\tproperty.forEach((str) => writable(target, str));\n\t} else {\n\t\tObject.defineProperty(target, property, {\n\t\t\twritable: true,\n\t\t});\n\t}\n}\n\nexport const noOp: (...args: any[]) => any = () => {\n\t// no operation here!\n};\n\n/**\n * Recursive Partial taken from here: https://stackoverflow.com/a/51365037\n */\nexport type RecursivePartial<T> = {\n\t[P in keyof T]?: T[P] extends Array<infer U>\n\t\t? Array<RecursivePartial<U>>\n\t\t: T[P] extends object\n\t\t\t? RecursivePartial<T[P]>\n\t\t\t: T[P];\n};\n","import { getContext } from \"../Global.js\";\nimport { Tone } from \"../Tone.js\";\nimport { Samples, Seconds } from \"../type/Units.js\";\nimport { optionsFromArguments } from \"../util/Defaults.js\";\nimport { noOp } from \"../util/Interface.js\";\nimport { isArray, isNumber, isString } from \"../util/TypeCheck.js\";\nimport { assert } from \"../util/Debug.js\";\n\ninterface ToneAudioBufferOptions {\n\turl?: string | AudioBuffer | ToneAudioBuffer;\n\treverse: boolean;\n\tonload: (buffer?: ToneAudioBuffer) => void;\n\tonerror: (error: Error) => void;\n}\n\n/**\n * AudioBuffer loading and storage. ToneAudioBuffer is used internally by all\n * classes that make requests for audio files such as Tone.Player,\n * Tone.Sampler and Tone.Convolver.\n * @example\n * const buffer = new Tone.ToneAudioBuffer(\"https://tonejs.github.io/audio/casio/A1.mp3\", () => {\n * \tconsole.log(\"loaded\");\n * });\n * @category Core\n */\nexport class ToneAudioBuffer extends Tone {\n\treadonly name: string = \"ToneAudioBuffer\";\n\n\t/**\n\t * stores the loaded AudioBuffer\n\t */\n\tprivate _buffer?: AudioBuffer;\n\n\t/**\n\t * indicates if the buffer should be reversed or not\n\t */\n\tprivate _reversed!: boolean;\n\n\t/**\n\t * Callback when the buffer is loaded.\n\t */\n\tonload: (buffer: ToneAudioBuffer) => void = noOp;\n\n\t/**\n\t *\n\t * @param url The url to load, or the audio buffer to set.\n\t * @param onload A callback which is invoked after the buffer is loaded.\n\t * It's recommended to use `ToneAudioBuffer.on('load', callback)` instead\n\t * since it will give you a callback when _all_ buffers are loaded.\n\t * @param onerror The callback to invoke if there is an error\n\t */\n\tconstructor(\n\t\turl?: string | ToneAudioBuffer | AudioBuffer,\n\t\tonload?: (buffer: ToneAudioBuffer) => void,\n\t\tonerror?: (error: Error) => void\n\t);\n\tconstructor(options?: Partial<ToneAudioBufferOptions>);\n\tconstructor() {\n\t\tsuper();\n\n\t\tconst options = optionsFromArguments(\n\t\t\tToneAudioBuffer.getDefaults(),\n\t\t\targuments,\n\t\t\t[\"url\", \"onload\", \"onerror\"]\n\t\t);\n\n\t\tthis.reverse = options.reverse;\n\t\tthis.onload = options.onload;\n\n\t\tif (isString(options.url)) {\n\t\t\t// initiate the download\n\t\t\tthis.load(options.url).catch(options.onerror);\n\t\t} else if (options.url) {\n\t\t\tthis.set(options.url);\n\t\t}\n\t}\n\n\tstatic getDefaults(): ToneAudioBufferOptions {\n\t\treturn {\n\t\t\tonerror: noOp,\n\t\t\tonload: noOp,\n\t\t\treverse: false,\n\t\t};\n\t}\n\n\t/**\n\t * The sample rate of the AudioBuffer\n\t */\n\tget sampleRate(): number {\n\t\tif (this._buffer) {\n\t\t\treturn this._buffer.sampleRate;\n\t\t} else {\n\t\t\treturn getContext().sampleRate;\n\t\t}\n\t}\n\n\t/**\n\t * Pass in an AudioBuffer or ToneAudioBuffer to set the value of this buffer.\n\t */\n\tset(buffer: AudioBuffer | ToneAudioBuffer): this {\n\t\tif (buffer instanceof ToneAudioBuffer) {\n\t\t\t// if it's loaded, set it\n\t\t\tif (buffer.loaded) {\n\t\t\t\tthis._buffer = buffer.get();\n\t\t\t} else {\n\t\t\t\t// otherwise when it's loaded, invoke it's callback\n\t\t\t\tbuffer.onload = () => {\n\t\t\t\t\tthis.set(buffer);\n\t\t\t\t\tthis.onload(this);\n\t\t\t\t};\n\t\t\t}\n\t\t} else {\n\t\t\tthis._buffer = buffer;\n\t\t}\n\t\t// reverse it initially\n\t\tif (this._reversed) {\n\t\t\tthis._reverse();\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * The audio buffer stored in the object.\n\t */\n\tget(): AudioBuffer | undefined {\n\t\treturn this._buffer;\n\t}\n\n\t/**\n\t * Makes an fetch request for the selected url then decodes the file as an audio buffer.\n\t * Invokes the callback once the audio buffer loads.\n\t * @param url The url of the buffer to load. filetype support depends on the browser.\n\t * @returns A Promise which resolves with this ToneAudioBuffer\n\t */\n\tasync load(url: string): Promise<this> {\n\t\tconst doneLoading: Promise<void> = ToneAudioBuffer.load(url).then(\n\t\t\t(audioBuffer) => {\n\t\t\t\tthis.set(audioBuffer);\n\t\t\t\t// invoke the onload method\n\t\t\t\tthis.onload(this);\n\t\t\t}\n\t\t);\n\t\tToneAudioBuffer.downloads.push(doneLoading);\n\t\ttry {\n\t\t\tawait doneLoading;\n\t\t} finally {\n\t\t\t// remove the downloaded file\n\t\t\tconst index = ToneAudioBuffer.downloads.indexOf(doneLoading);\n\t\t\tToneAudioBuffer.downloads.splice(index, 1);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * clean up\n\t */\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis._buffer = undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Set the audio buffer from the array.\n\t * To create a multichannel AudioBuffer, pass in a multidimensional array.\n\t * @param array The array to fill the audio buffer\n\t */\n\tfromArray(array: Float32Array | Float32Array[]): this {\n\t\tconst isMultidimensional = isArray(array) && array[0].length > 0;\n\t\tconst channels = isMultidimensional ? array.length : 1;\n\t\tconst len = isMultidimensional\n\t\t\t? (array[0] as Float32Array).length\n\t\t\t: array.length;\n\t\tconst context = getContext();\n\t\tconst buffer = context.createBuffer(channels, len, context.sampleRate);\n\t\tconst multiChannelArray: Float32Array[] =\n\t\t\t!isMultidimensional && channels === 1\n\t\t\t\t? [array as Float32Array]\n\t\t\t\t: (array as Float32Array[]);\n\n\t\tfor (let c = 0; c < channels; c++) {\n\t\t\tbuffer.copyToChannel(multiChannelArray[c], c);\n\t\t}\n\t\tthis._buffer = buffer;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sums multiple channels into 1 channel\n\t * @param chanNum Optionally only copy a single channel from the array.\n\t */\n\ttoMono(chanNum?: number): this {\n\t\tif (isNumber(chanNum)) {\n\t\t\tthis.fromArray(this.toArray(chanNum));\n\t\t} else {\n\t\t\tlet outputArray = new Float32Array(this.length as number);\n\t\t\tconst numChannels = this.numberOfChannels;\n\t\t\tfor (let channel = 0; channel < numChannels; channel++) {\n\t\t\t\tconst channelArray = this.toArray(channel) as Float32Array;\n\t\t\t\tfor (let i = 0; i < channelArray.length; i++) {\n\t\t\t\t\toutputArray[i] += channelArray[i];\n\t\t\t\t}\n\t\t\t}\n\t\t\t// divide by the number of channels\n\t\t\toutputArray = outputArray.map((sample) => sample / numChannels);\n\t\t\tthis.fromArray(outputArray);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Get the buffer as an array. Single channel buffers will return a 1-dimensional\n\t * Float32Array, and multichannel buffers will return multidimensional arrays.\n\t * @param channel Optionally only copy a single channel from the array.\n\t */\n\ttoArray(channel?: number): Float32Array | Float32Array[] {\n\t\tif (isNumber(channel)) {\n\t\t\treturn this.getChannelData(channel);\n\t\t} else if (this.numberOfChannels === 1) {\n\t\t\treturn this.toArray(0);\n\t\t} else {\n\t\t\tconst ret: Float32Array[] = [];\n\t\t\tfor (let c = 0; c < this.numberOfChannels; c++) {\n\t\t\t\tret[c] = this.getChannelData(c);\n\t\t\t}\n\t\t\treturn ret;\n\t\t}\n\t}\n\n\t/**\n\t * Returns the Float32Array representing the PCM audio data for the specific channel.\n\t * @param channel The channel number to return\n\t * @return The audio as a TypedArray\n\t */\n\tgetChannelData(channel: number): Float32Array {\n\t\tif (this._buffer) {\n\t\t\treturn this._buffer.getChannelData(channel);\n\t\t} else {\n\t\t\treturn new Float32Array(0);\n\t\t}\n\t}\n\n\t/**\n\t * Cut a subsection of the array and return a buffer of the\n\t * subsection. Does not modify the original buffer\n\t * @param start The time to start the slice\n\t * @param end The end time to slice. If none is given will default to the end of the buffer\n\t */\n\tslice(start: Seconds, end: Seconds = this.duration): ToneAudioBuffer {\n\t\tassert(this.loaded, \"Buffer is not loaded\");\n\t\tconst startSamples = Math.floor(start * this.sampleRate);\n\t\tconst endSamples = Math.floor(end * this.sampleRate);\n\t\tassert(\n\t\t\tstartSamples < endSamples,\n\t\t\t\"The start time must be less than the end time\"\n\t\t);\n\t\tconst length = endSamples - startSamples;\n\t\tconst retBuffer = getContext().createBuffer(\n\t\t\tthis.numberOfChannels,\n\t\t\tlength,\n\t\t\tthis.sampleRate\n\t\t);\n\t\tfor (let channel = 0; channel < this.numberOfChannels; channel++) {\n\t\t\tretBuffer.copyToChannel(\n\t\t\t\tthis.getChannelData(channel).subarray(startSamples, endSamples),\n\t\t\t\tchannel\n\t\t\t);\n\t\t}\n\t\treturn new ToneAudioBuffer(retBuffer);\n\t}\n\n\t/**\n\t * Reverse the buffer.\n\t */\n\tprivate _reverse(): this {\n\t\tif (this.loaded) {\n\t\t\tfor (let i = 0; i < this.numberOfChannels; i++) {\n\t\t\t\tthis.getChannelData(i).reverse();\n\t\t\t}\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * If the buffer is loaded or not\n\t */\n\tget loaded(): boolean {\n\t\treturn this.length > 0;\n\t}\n\n\t/**\n\t * The duration of the buffer in seconds.\n\t */\n\tget duration(): Seconds {\n\t\tif (this._buffer) {\n\t\t\treturn this._buffer.duration;\n\t\t} else {\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\t/**\n\t * The length of the buffer in samples\n\t */\n\tget length(): Samples {\n\t\tif (this._buffer) {\n\t\t\treturn this._buffer.length;\n\t\t} else {\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\t/**\n\t * The number of discrete audio channels. Returns 0 if no buffer is loaded.\n\t */\n\tget numberOfChannels(): number {\n\t\tif (this._buffer) {\n\t\t\treturn this._buffer.numberOfChannels;\n\t\t} else {\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\t/**\n\t * Reverse the buffer.\n\t */\n\tget reverse(): boolean {\n\t\treturn this._reversed;\n\t}\n\tset reverse(rev: boolean) {\n\t\tif (this._reversed !== rev) {\n\t\t\tthis._reversed = rev;\n\t\t\tthis._reverse();\n\t\t}\n\t}\n\n\t//-------------------------------------\n\t// STATIC METHODS\n\t//-------------------------------------\n\n\t/**\n\t * A path which is prefixed before every url.\n\t */\n\tstatic baseUrl = \"\";\n\n\t/**\n\t * Create a ToneAudioBuffer from the array. To create a multichannel AudioBuffer,\n\t * pass in a multidimensional array.\n\t * @param array The array to fill the audio buffer\n\t * @return A ToneAudioBuffer created from the array\n\t */\n\tstatic fromArray(array: Float32Array | Float32Array[]): ToneAudioBuffer {\n\t\treturn new ToneAudioBuffer().fromArray(array);\n\t}\n\n\t/**\n\t * Creates a ToneAudioBuffer from a URL, returns a promise which resolves to a ToneAudioBuffer\n\t * @param url The url to load.\n\t * @return A promise which resolves to a ToneAudioBuffer\n\t */\n\tstatic async fromUrl(url: string): Promise<ToneAudioBuffer> {\n\t\tconst buffer = new ToneAudioBuffer();\n\t\treturn await buffer.load(url);\n\t}\n\n\t/**\n\t * All of the downloads\n\t */\n\tstatic downloads: Array<Promise<void>> = [];\n\n\t/**\n\t * Loads a url using fetch and returns the AudioBuffer.\n\t */\n\tstatic async load(url: string): Promise<AudioBuffer> {\n\t\t// make sure there is a slash between the baseUrl and the url\n\t\tconst baseUrl =\n\t\t\tToneAudioBuffer.baseUrl === \"\" ||\n\t\t\tToneAudioBuffer.baseUrl.endsWith(\"/\")\n\t\t\t\t? ToneAudioBuffer.baseUrl\n\t\t\t\t: ToneAudioBuffer.baseUrl + \"/\";\n\n\t\tconst response = await fetch(baseUrl + url);\n\t\tif (!response.ok) {\n\t\t\tthrow new Error(`could not load url: ${url}`);\n\t\t}\n\t\tconst arrayBuffer = await response.arrayBuffer();\n\n\t\tconst audioBuffer = await getContext().decodeAudioData(arrayBuffer);\n\n\t\treturn audioBuffer;\n\t}\n\n\t/**\n\t * Checks a url's extension to see if the current browser can play that file type.\n\t * @param url The url/extension to test\n\t * @return If the file extension can be played\n\t * @static\n\t * @example\n\t * Tone.ToneAudioBuffer.supportsType(\"wav\"); // returns true\n\t * Tone.ToneAudioBuffer.supportsType(\"path/to/file.wav\"); // returns true\n\t */\n\tstatic supportsType(url: string): boolean {\n\t\tconst extensions = url.split(\".\");\n\t\tconst extension = extensions[extensions.length - 1];\n\t\tconst response = document\n\t\t\t.createElement(\"audio\")\n\t\t\t.canPlayType(\"audio/\" + extension);\n\t\treturn response !== \"\";\n\t}\n\n\t/**\n\t * Returns a Promise which resolves when all of the buffers have loaded\n\t */\n\tstatic async loaded(): Promise<void> {\n\t\t// this makes sure that the function is always async\n\t\tawait Promise.resolve();\n\t\twhile (ToneAudioBuffer.downloads.length) {\n\t\t\tawait ToneAudioBuffer.downloads[0];\n\t\t}\n\t}\n}\n","import { createOfflineAudioContext } from \"../context/AudioContext.js\";\nimport { Context } from \"../context/Context.js\";\nimport { Seconds } from \"../type/Units.js\";\nimport { isOfflineAudioContext } from \"../util/AdvancedTypeCheck.js\";\nimport { ToneAudioBuffer } from \"./ToneAudioBuffer.js\";\n\n/**\n * Wrapper around the OfflineAudioContext\n * @category Core\n * @example\n * // generate a single channel, 0.5 second buffer\n * const context = new Tone.OfflineContext(1, 0.5, 44100);\n * const osc = new Tone.Oscillator({ context });\n * context.render().then(buffer => {\n * \tconsole.log(buffer.numberOfChannels, buffer.duration);\n * });\n */\nexport class OfflineContext extends Context {\n\treadonly name: string = \"OfflineContext\";\n\n\t/**\n\t * A private reference to the duration\n\t */\n\tprivate readonly _duration: Seconds;\n\n\t/**\n\t * An artificial clock source\n\t */\n\tprivate _currentTime: Seconds = 0;\n\n\t/**\n\t * Private reference to the OfflineAudioContext.\n\t */\n\tprotected _context!: OfflineAudioContext;\n\n\treadonly isOffline: boolean = true;\n\n\t/**\n\t * @param channels The number of channels to render\n\t * @param duration The duration to render in seconds\n\t * @param sampleRate the sample rate to render at\n\t */\n\tconstructor(channels: number, duration: Seconds, sampleRate: number);\n\tconstructor(context: OfflineAudioContext);\n\tconstructor() {\n\t\tsuper({\n\t\t\tclockSource: \"offline\",\n\t\t\tcontext: isOfflineAudioContext(arguments[0])\n\t\t\t\t? arguments[0]\n\t\t\t\t: createOfflineAudioContext(\n\t\t\t\t\t\targuments[0],\n\t\t\t\t\t\targuments[1] * arguments[2],\n\t\t\t\t\t\targuments[2]\n\t\t\t\t\t),\n\t\t\tlookAhead: 0,\n\t\t\tupdateInterval: isOfflineAudioContext(arguments[0])\n\t\t\t\t? 128 / arguments[0].sampleRate\n\t\t\t\t: 128 / arguments[2],\n\t\t});\n\n\t\tthis._duration = isOfflineAudioContext(arguments[0])\n\t\t\t? arguments[0].length / arguments[0].sampleRate\n\t\t\t: arguments[1];\n\t}\n\n\t/**\n\t * Override the now method to point to the internal clock time\n\t */\n\tnow(): Seconds {\n\t\treturn this._currentTime;\n\t}\n\n\t/**\n\t * Same as this.now()\n\t */\n\tget currentTime(): Seconds {\n\t\treturn this._currentTime;\n\t}\n\n\t/**\n\t * Render just the clock portion of the audio context.\n\t */\n\tprivate async _renderClock(asynchronous: boolean): Promise<void> {\n\t\tlet index = 0;\n\t\twhile (this._duration - this._currentTime >= 0) {\n\t\t\t// invoke all the callbacks on that time\n\t\t\tthis.emit(\"tick\");\n\n\t\t\t// increment the clock in block-sized chunks\n\t\t\tthis._currentTime += 128 / this.sampleRate;\n\n\t\t\t// yield once a second of audio\n\t\t\tindex++;\n\t\t\tconst yieldEvery = Math.floor(this.sampleRate / 128);\n\t\t\tif (asynchronous && index % yieldEvery === 0) {\n\t\t\t\tawait new Promise((done) => setTimeout(done, 1));\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Render the output of the OfflineContext\n\t * @param asynchronous If the clock should be rendered asynchronously, which will not block the main thread, but be slightly slower.\n\t */\n\tasync render(asynchronous = true): Promise<ToneAudioBuffer> {\n\t\tawait this.workletsAreReady();\n\t\tawait this._renderClock(asynchronous);\n\t\tconst buffer = await this._context.startRendering();\n\t\treturn new ToneAudioBuffer(buffer);\n\t}\n\n\t/**\n\t * Close the context\n\t */\n\tclose(): Promise<void> {\n\t\treturn Promise.resolve();\n\t}\n}\n","import { version } from \"../version.js\";\nimport {\n\tAnyAudioContext,\n\thasAudioContext,\n\ttheWindow,\n} from \"./context/AudioContext.js\";\nimport { Context } from \"./context/Context.js\";\nimport { DummyContext } from \"./context/DummyContext.js\";\nimport { BaseContext } from \"./context/BaseContext.js\";\nimport { OfflineContext } from \"./context/OfflineContext.js\";\nimport {\n\tisAudioContext,\n\tisOfflineAudioContext,\n} from \"./util/AdvancedTypeCheck.js\";\n\n/**\n * This dummy context is used to avoid throwing immediate errors when importing in Node.js\n */\nconst dummyContext = new DummyContext();\n\n/**\n * The global audio context which is getable and assignable through\n * getContext and setContext\n */\nlet globalContext: BaseContext = dummyContext;\n\n/**\n * Returns the default system-wide {@link Context}\n * @category Core\n */\nexport function getContext(): BaseContext {\n\tif (globalContext === dummyContext && hasAudioContext) {\n\t\tsetContext(new Context());\n\t}\n\treturn globalContext;\n}\n\n/**\n * Set the default audio context\n * @param context\n * @param disposeOld Pass `true` if you don't need the old context to dispose it.\n * @category Core\n */\nexport function setContext(\n\tcontext: BaseContext | AnyAudioContext,\n\tdisposeOld = false\n): void {\n\tif (disposeOld) {\n\t\tglobalContext.dispose();\n\t}\n\n\tif (isAudioContext(context)) {\n\t\tglobalContext = new Context(context);\n\t} else if (isOfflineAudioContext(context)) {\n\t\tglobalContext = new OfflineContext(context);\n\t} else {\n\t\tglobalContext = context;\n\t}\n}\n\n/**\n * Most browsers will not play _any_ audio until a user\n * clicks something (like a play button). Invoke this method\n * on a click or keypress event handler to start the audio context.\n * More about the Autoplay policy\n * [here](https://developers.google.com/web/updates/2017/09/autoplay-policy-changes#webaudio)\n * @example\n * document.querySelector(\"button\").addEventListener(\"click\", async () => {\n * \tawait Tone.start();\n * \tconsole.log(\"context started\");\n * });\n * @category Core\n */\nexport function start(): Promise<void> {\n\treturn globalContext.resume();\n}\n\n/**\n * Log Tone.js + version in the console.\n */\nif (theWindow && !theWindow.TONE_SILENCE_LOGGING) {\n\tlet prefix = \"v\";\n\tif (version === \"dev\") {\n\t\tprefix = \"\";\n\t}\n\tconst printString = ` * Tone.js ${prefix}${version} * `;\n\t// eslint-disable-next-line no-console\n\tconsole.log(`%c${printString}`, \"background: #000; color: #fff\");\n}\n","import {\n\tDecibels,\n\tGainFactor,\n\tHertz,\n\tInterval,\n\tMidiNote,\n\tNormalRange,\n} from \"./Units.js\";\n\n/**\n * Equal power gain scale. Good for cross-fading.\n * @param percent (0-1)\n */\nexport function equalPowerScale(percent: NormalRange): number {\n\tconst piFactor = 0.5 * Math.PI;\n\treturn Math.sin(percent * piFactor);\n}\n\n/**\n * Convert decibels into gain.\n */\nexport function dbToGain(db: Decibels): GainFactor {\n\treturn Math.pow(10, db / 20);\n}\n\n/**\n * Convert gain to decibels.\n */\nexport function gainToDb(gain: GainFactor): Decibels {\n\treturn 20 * (Math.log(gain) / Math.LN10);\n}\n\n/**\n * Convert an interval (in semitones) to a frequency ratio.\n * @param interval the number of semitones above the base note\n * @example\n * Tone.intervalToFrequencyRatio(0); // 1\n * Tone.intervalToFrequencyRatio(12); // 2\n * Tone.intervalToFrequencyRatio(-12); // 0.5\n */\nexport function intervalToFrequencyRatio(interval: Interval): number {\n\treturn Math.pow(2, interval / 12);\n}\n\n/**\n * The Global [concert tuning pitch](https://en.wikipedia.org/wiki/Concert_pitch) which is used\n * to generate all the other pitch values from notes. A4's values in Hertz.\n */\nlet A4: Hertz = 440;\n\nexport function getA4(): Hertz {\n\treturn A4;\n}\n\nexport function setA4(freq: Hertz): void {\n\tA4 = freq;\n}\n\n/**\n * Convert a frequency value to a MIDI note.\n * @param frequency The value to frequency value to convert.\n * @example\n * Tone.ftom(440); // returns 69\n */\nexport function ftom(frequency: Hertz): MidiNote {\n\treturn Math.round(ftomf(frequency)) as MidiNote;\n}\n\n/**\n * Convert a frequency to a floating point midi value\n */\nexport function ftomf(frequency: Hertz): number {\n\treturn 69 + 12 * Math.log2(frequency / A4);\n}\n\n/**\n * Convert a MIDI note to frequency value.\n * @param midi The midi number to convert.\n * @return The corresponding frequency value\n * @example\n * Tone.mtof(69); // 440\n */\nexport function mtof(midi: MidiNote): Hertz {\n\treturn A4 * Math.pow(2, (midi - 69) / 12);\n}\n","import { BaseContext } from \"../context/BaseContext.js\";\nimport { Tone } from \"../Tone.js\";\nimport { isDefined, isObject, isString, isUndef } from \"../util/TypeCheck.js\";\nimport {\n\tBPM,\n\tHertz,\n\tMidiNote,\n\tMilliseconds,\n\tSamples,\n\tSeconds,\n\tTicks,\n\tTime,\n} from \"./Units.js\";\n\nexport type TimeValue = Time | TimeBaseClass<any, any>;\n\n/**\n * The units that the TimeBase can accept. extended by other classes\n */\nexport type TimeBaseUnit =\n\t| \"s\"\n\t| \"n\"\n\t| \"t\"\n\t| \"m\"\n\t| \"i\"\n\t| \"hz\"\n\t| \"tr\"\n\t| \"samples\"\n\t| \"number\";\n\nexport interface TypeFunction {\n\tregexp: RegExp;\n\tmethod: (value: string, ...args: string[]) => number;\n}\n\nexport interface TimeExpression<Type extends number> {\n\t[key: string]: {\n\t\tregexp: RegExp;\n\t\tmethod: (value: string, ...args: string[]) => Type;\n\t};\n}\n\n/**\n * TimeBase is a flexible encoding of time which can be evaluated to and from a string.\n */\nexport abstract class TimeBaseClass<\n\tType extends number,\n\tUnit extends string,\n> extends Tone {\n\treadonly context: BaseContext;\n\n\t/**\n\t * The value of the units\n\t */\n\tprotected _val?: TimeValue;\n\n\t/**\n\t * The units of time\n\t */\n\tprotected _units?: Unit;\n\n\t/**\n\t * All of the conversion expressions\n\t */\n\tprotected _expressions: TimeExpression<Type>;\n\n\t/**\n\t * The default units\n\t */\n\treadonly defaultUnits: Unit = \"s\" as Unit;\n\n\t/**\n\t * @param context The context associated with the time value. Used to compute\n\t * Transport and context-relative timing.\n\t * @param value The time value as a number, string or object\n\t * @param units Unit values\n\t */\n\tconstructor(context: BaseContext, value?: TimeValue, units?: Unit) {\n\t\tsuper();\n\n\t\tthis._val = value;\n\t\tthis._units = units;\n\t\tthis.context = context;\n\t\tthis._expressions = this._getExpressions();\n\t}\n\n\t/**\n\t * All of the time encoding expressions\n\t */\n\tprotected _getExpressions(): TimeExpression<Type> {\n\t\treturn {\n\t\t\thz: {\n\t\t\t\tmethod: (value) => {\n\t\t\t\t\treturn this._frequencyToUnits(parseFloat(value));\n\t\t\t\t},\n\t\t\t\tregexp: /^(\\d+(?:\\.\\d+)?)hz$/i,\n\t\t\t},\n\t\t\ti: {\n\t\t\t\tmethod: (value) => {\n\t\t\t\t\treturn this._ticksToUnits(parseInt(value, 10));\n\t\t\t\t},\n\t\t\t\tregexp: /^(\\d+)i$/i,\n\t\t\t},\n\t\t\tm: {\n\t\t\t\tmethod: (value) => {\n\t\t\t\t\treturn this._beatsToUnits(\n\t\t\t\t\t\tparseInt(value, 10) * this._getTimeSignature()\n\t\t\t\t\t);\n\t\t\t\t},\n\t\t\t\tregexp: /^(\\d+)m$/i,\n\t\t\t},\n\t\t\tn: {\n\t\t\t\tmethod: (value, dot) => {\n\t\t\t\t\tconst numericValue = parseInt(value, 10);\n\t\t\t\t\tconst scalar = dot === \".\" ? 1.5 : 1;\n\t\t\t\t\tif (numericValue === 1) {\n\t\t\t\t\t\treturn (this._beatsToUnits(this._getTimeSignature()) *\n\t\t\t\t\t\t\tscalar) as Type;\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn (this._beatsToUnits(4 / numericValue) *\n\t\t\t\t\t\t\tscalar) as Type;\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tregexp: /^(\\d+)n(\\.?)$/i,\n\t\t\t},\n\t\t\tnumber: {\n\t\t\t\tmethod: (value) => {\n\t\t\t\t\treturn this._expressions[this.defaultUnits].method.call(\n\t\t\t\t\t\tthis,\n\t\t\t\t\t\tvalue\n\t\t\t\t\t);\n\t\t\t\t},\n\t\t\t\tregexp: /^(\\d+(?:\\.\\d+)?)$/,\n\t\t\t},\n\t\t\ts: {\n\t\t\t\tmethod: (value): Type => {\n\t\t\t\t\treturn this._secondsToUnits(parseFloat(value));\n\t\t\t\t},\n\t\t\t\tregexp: /^(\\d+(?:\\.\\d+)?)s$/,\n\t\t\t},\n\t\t\tsamples: {\n\t\t\t\tmethod: (value) => {\n\t\t\t\t\treturn (parseInt(value, 10) /\n\t\t\t\t\t\tthis.context.sampleRate) as Type;\n\t\t\t\t},\n\t\t\t\tregexp: /^(\\d+)samples$/,\n\t\t\t},\n\t\t\tt: {\n\t\t\t\tmethod: (value) => {\n\t\t\t\t\tconst numericValue = parseInt(value, 10);\n\t\t\t\t\treturn this._beatsToUnits(\n\t\t\t\t\t\t8 / (Math.floor(numericValue) * 3)\n\t\t\t\t\t);\n\t\t\t\t},\n\t\t\t\tregexp: /^(\\d+)t$/i,\n\t\t\t},\n\t\t\ttr: {\n\t\t\t\tmethod: (m, q, s) => {\n\t\t\t\t\tlet total = 0;\n\t\t\t\t\tif (m && m !== \"0\") {\n\t\t\t\t\t\ttotal += this._beatsToUnits(\n\t\t\t\t\t\t\tthis._getTimeSignature() * parseFloat(m)\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tif (q && q !== \"0\") {\n\t\t\t\t\t\ttotal += this._beatsToUnits(parseFloat(q));\n\t\t\t\t\t}\n\t\t\t\t\tif (s && s !== \"0\") {\n\t\t\t\t\t\ttotal += this._beatsToUnits(parseFloat(s) / 4);\n\t\t\t\t\t}\n\t\t\t\t\treturn total as Type;\n\t\t\t\t},\n\t\t\t\tregexp: /^(\\d+(?:\\.\\d+)?):(\\d+(?:\\.\\d+)?):?(\\d+(?:\\.\\d+)?)?$/,\n\t\t\t},\n\t\t};\n\t}\n\n\t//-------------------------------------\n\t// \tVALUE OF\n\t//-------------------------------------\n\n\t/**\n\t * Evaluate the time value. Returns the time in seconds.\n\t */\n\tvalueOf(): Type {\n\t\tif (this._val instanceof TimeBaseClass) {\n\t\t\tthis.fromType(this._val);\n\t\t}\n\t\tif (isUndef(this._val)) {\n\t\t\treturn this._noArg();\n\t\t} else if (isString(this._val) && isUndef(this._units)) {\n\t\t\tfor (const units in this._expressions) {\n\t\t\t\tif (this._expressions[units].regexp.test(this._val.trim())) {\n\t\t\t\t\tthis._units = units as Unit;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (isObject(this._val)) {\n\t\t\tlet total = 0;\n\t\t\tfor (const typeName in this._val) {\n\t\t\t\tif (isDefined(this._val[typeName])) {\n\t\t\t\t\tconst quantity = this._val[typeName];\n\t\t\t\t\tconst time =\n\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\tnew this.constructor(this.context, typeName).valueOf() *\n\t\t\t\t\t\tquantity;\n\t\t\t\t\ttotal += time;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn total as Type;\n\t\t}\n\t\tif (isDefined(this._units)) {\n\t\t\tconst expr = this._expressions[this._units];\n\t\t\tconst matching = this._val.toString().trim().match(expr.regexp);\n\t\t\tif (matching) {\n\t\t\t\treturn expr.method.apply(this, matching.slice(1));\n\t\t\t} else {\n\t\t\t\treturn expr.method.call(this, this._val);\n\t\t\t}\n\t\t} else if (isString(this._val)) {\n\t\t\treturn parseFloat(this._val) as Type;\n\t\t} else {\n\t\t\treturn this._val as Type;\n\t\t}\n\t}\n\n\t//-------------------------------------\n\t// \tUNIT CONVERSIONS\n\t//-------------------------------------\n\n\t/**\n\t * Returns the value of a frequency in the current units\n\t */\n\tprotected _frequencyToUnits(freq: Hertz): Type {\n\t\treturn (1 / freq) as Type;\n\t}\n\n\t/**\n\t * Return the value of the beats in the current units\n\t */\n\tprotected _beatsToUnits(beats: number): Type {\n\t\treturn ((60 / this._getBpm()) * beats) as Type;\n\t}\n\n\t/**\n\t * Returns the value of a second in the current units\n\t */\n\tprotected _secondsToUnits(seconds: Seconds): Type {\n\t\treturn seconds as Type;\n\t}\n\n\t/**\n\t * Returns the value of a tick in the current time units\n\t */\n\tprotected _ticksToUnits(ticks: Ticks): Type {\n\t\treturn ((ticks * this._beatsToUnits(1)) / this._getPPQ()) as Type;\n\t}\n\n\t/**\n\t * With no arguments, return 'now'\n\t */\n\tprotected _noArg(): Type {\n\t\treturn this._now();\n\t}\n\n\t//-------------------------------------\n\t// \tTEMPO CONVERSIONS\n\t//-------------------------------------\n\n\t/**\n\t * Return the bpm\n\t */\n\tprotected _getBpm(): BPM {\n\t\treturn this.context.transport.bpm.value;\n\t}\n\n\t/**\n\t * Return the timeSignature\n\t */\n\tprotected _getTimeSignature(): number {\n\t\treturn this.context.transport.timeSignature as number;\n\t}\n\n\t/**\n\t * Return the PPQ or 192 if Transport is not available\n\t */\n\tprotected _getPPQ(): number {\n\t\treturn this.context.transport.PPQ;\n\t}\n\n\t/**\n\t * Return the current time in whichever context is relevant\n\t */\n\tprotected abstract _now(): Type;\n\n\t//-------------------------------------\n\t// \tCONVERSION INTERFACE\n\t//-------------------------------------\n\n\t/**\n\t * Coerce a time type into this units type.\n\t * @param type Any time type units\n\t */\n\tfromType(type: TimeBaseClass<any, any>): this {\n\t\tthis._units = undefined;\n\t\tswitch (this.defaultUnits) {\n\t\t\tcase \"s\":\n\t\t\t\tthis._val = type.toSeconds();\n\t\t\t\tbreak;\n\t\t\tcase \"i\":\n\t\t\t\tthis._val = type.toTicks();\n\t\t\t\tbreak;\n\t\t\tcase \"hz\":\n\t\t\t\tthis._val = type.toFrequency();\n\t\t\t\tbreak;\n\t\t\tcase \"midi\":\n\t\t\t\tthis._val = type.toMidi();\n\t\t\t\tbreak;\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Return the value in seconds\n\t */\n\tabstract toSeconds(): Seconds;\n\n\t/**\n\t * Return the value as a Midi note\n\t */\n\tabstract toMidi(): MidiNote;\n\n\t/**\n\t * Convert the value into ticks\n\t */\n\tabstract toTicks(): Ticks;\n\n\t/**\n\t * Return the value in hertz\n\t */\n\ttoFrequency(): Hertz {\n\t\treturn 1 / this.toSeconds();\n\t}\n\n\t/**\n\t * Return the time in samples\n\t */\n\ttoSamples(): Samples {\n\t\treturn this.toSeconds() * this.context.sampleRate;\n\t}\n\n\t/**\n\t * Return the time in milliseconds.\n\t */\n\ttoMilliseconds(): Milliseconds {\n\t\treturn this.toSeconds() * 1000;\n\t}\n}\n","import { getContext } from \"../Global.js\";\nimport { ftom } from \"./Conversions.js\";\nimport {\n\tTimeBaseClass,\n\tTimeBaseUnit,\n\tTimeExpression,\n\tTimeValue,\n} from \"./TimeBase.js\";\nimport {\n\tBarsBeatsSixteenths,\n\tMidiNote,\n\tSeconds,\n\tSubdivision,\n\tTicks,\n\tTime,\n} from \"./Units.js\";\n\n/**\n * TimeClass is a primitive type for encoding and decoding Time values.\n * TimeClass can be passed into the parameter of any method which takes time as an argument.\n * @param val The time value.\n * @param units The units of the value.\n * @example\n * const time = Tone.Time(\"4n\"); // a quarter note\n * @category Unit\n */\nexport class TimeClass<\n\tType extends Seconds | Ticks = Seconds,\n\tUnit extends string = TimeBaseUnit,\n> extends TimeBaseClass<Type, Unit> {\n\treadonly name: string = \"TimeClass\";\n\n\tprotected _getExpressions(): TimeExpression<Type> {\n\t\treturn Object.assign(super._getExpressions(), {\n\t\t\tnow: {\n\t\t\t\tmethod: (capture: string): Type => {\n\t\t\t\t\treturn (this._now() +\n\t\t\t\t\t\tnew (this.constructor as typeof TimeClass)(\n\t\t\t\t\t\t\tthis.context,\n\t\t\t\t\t\t\tcapture\n\t\t\t\t\t\t).valueOf()) as Type;\n\t\t\t\t},\n\t\t\t\tregexp: /^\\+(.+)/,\n\t\t\t},\n\t\t\tquantize: {\n\t\t\t\tmethod: (capture: string): Type => {\n\t\t\t\t\tconst quantTo = new TimeClass(\n\t\t\t\t\t\tthis.context,\n\t\t\t\t\t\tcapture\n\t\t\t\t\t).valueOf();\n\t\t\t\t\treturn this._secondsToUnits(\n\t\t\t\t\t\tthis.context.transport.nextSubdivision(quantTo)\n\t\t\t\t\t);\n\t\t\t\t},\n\t\t\t\tregexp: /^@(.+)/,\n\t\t\t},\n\t\t});\n\t}\n\n\t/**\n\t * Quantize the time by the given subdivision. Optionally add a\n\t * percentage which will move the time value towards the ideal\n\t * quantized value by that percentage.\n\t * @param subdiv The subdivision to quantize to\n\t * @param percent Move the time value towards the quantized value by a percentage.\n\t * @example\n\t * Tone.Time(21).quantize(2); // returns 22\n\t * Tone.Time(0.6).quantize(\"4n\", 0.5); // returns 0.55\n\t */\n\tquantize(subdiv: Time, percent = 1): Type {\n\t\tconst subdivision = new (this.constructor as typeof TimeClass)(\n\t\t\tthis.context,\n\t\t\tsubdiv\n\t\t).valueOf();\n\t\tconst value = this.valueOf();\n\t\tconst multiple = Math.round(value / subdivision);\n\t\tconst ideal = multiple * subdivision;\n\t\tconst diff = ideal - value;\n\t\treturn (value + diff * percent) as Type;\n\t}\n\n\t//-------------------------------------\n\t// CONVERSIONS\n\t//-------------------------------------\n\t/**\n\t * Convert a Time to Notation. The notation values are will be the\n\t * closest representation between 1m to 128th note.\n\t * @return {Notation}\n\t * @example\n\t * // if the Transport is at 120bpm:\n\t * Tone.Time(2).toNotation(); // returns \"1m\"\n\t */\n\ttoNotation(): Subdivision {\n\t\tconst time = this.toSeconds();\n\t\tconst testNotations: Subdivision[] = [\"1m\"];\n\t\tfor (let power = 1; power < 9; power++) {\n\t\t\tconst subdiv = Math.pow(2, power);\n\t\t\ttestNotations.push((subdiv + \"n.\") as Subdivision);\n\t\t\ttestNotations.push((subdiv + \"n\") as Subdivision);\n\t\t\ttestNotations.push((subdiv + \"t\") as Subdivision);\n\t\t}\n\t\ttestNotations.push(\"0\");\n\t\t// find the closets notation representation\n\t\tlet closest = testNotations[0];\n\t\tlet closestSeconds = new TimeClass(\n\t\t\tthis.context,\n\t\t\ttestNotations[0]\n\t\t).toSeconds();\n\t\ttestNotations.forEach((notation) => {\n\t\t\tconst notationSeconds = new TimeClass(\n\t\t\t\tthis.context,\n\t\t\t\tnotation\n\t\t\t).toSeconds();\n\t\t\tif (\n\t\t\t\tMath.abs(notationSeconds - time) <\n\t\t\t\tMath.abs(closestSeconds - time)\n\t\t\t) {\n\t\t\t\tclosest = notation;\n\t\t\t\tclosestSeconds = notationSeconds;\n\t\t\t}\n\t\t});\n\t\treturn closest;\n\t}\n\n\t/**\n\t * Return the time encoded as Bars:Beats:Sixteenths.\n\t */\n\ttoBarsBeatsSixteenths(): BarsBeatsSixteenths {\n\t\tconst quarterTime = this._beatsToUnits(1);\n\t\tlet quarters = this.valueOf() / quarterTime;\n\t\tquarters = parseFloat(quarters.toFixed(4));\n\t\tconst measures = Math.floor(quarters / this._getTimeSignature());\n\t\tlet sixteenths = (quarters % 1) * 4;\n\t\tquarters = Math.floor(quarters) % this._getTimeSignature();\n\t\tconst sixteenthString = sixteenths.toString();\n\t\tif (sixteenthString.length > 3) {\n\t\t\t// the additional parseFloat removes insignificant trailing zeroes\n\t\t\tsixteenths = parseFloat(parseFloat(sixteenthString).toFixed(3));\n\t\t}\n\t\tconst progress = [measures, quarters, sixteenths];\n\t\treturn progress.join(\":\") as BarsBeatsSixteenths;\n\t}\n\n\t/**\n\t * Return the time in ticks.\n\t */\n\ttoTicks(): Ticks {\n\t\tconst quarterTime = this._beatsToUnits(1);\n\t\tconst quarters = this.valueOf() / quarterTime;\n\t\treturn quarters * this._getPPQ();\n\t}\n\n\t/**\n\t * Return the time in seconds.\n\t */\n\ttoSeconds(): Seconds {\n\t\treturn this.valueOf();\n\t}\n\n\t/**\n\t * Return the value as a midi note.\n\t */\n\ttoMidi(): MidiNote {\n\t\treturn ftom(this.toFrequency());\n\t}\n\n\tprotected _now(): Type {\n\t\treturn this.context.now() as Type;\n\t}\n}\n\n/**\n * Create a TimeClass from a time string or number. The time is computed against the\n * global Tone.Context. To use a specific context, use {@link TimeClass}\n * @param value A value which represents time\n * @param units The value's units if they can't be inferred by the value.\n * @category Unit\n * @example\n * const time = Tone.Time(\"4n\").toSeconds();\n * console.log(time);\n * @example\n * const note = Tone.Time(1).toNotation();\n * console.log(note);\n * @example\n * const freq = Tone.Time(0.5).toFrequency();\n * console.log(freq);\n */\nexport function Time(\n\tvalue?: TimeValue,\n\tunits?: TimeBaseUnit\n): TimeClass<Seconds> {\n\treturn new TimeClass(getContext(), value, units);\n}\n","/* eslint-disable key-spacing */\nimport { getContext } from \"../Global.js\";\nimport { intervalToFrequencyRatio, mtof } from \"./Conversions.js\";\nimport { ftom, getA4, setA4 } from \"./Conversions.js\";\nimport { TimeClass } from \"./Time.js\";\nimport { TimeBaseUnit, TimeExpression, TimeValue } from \"./TimeBase.js\";\nimport {\n\tFrequency,\n\tHertz,\n\tInterval,\n\tMidiNote,\n\tNote,\n\tSeconds,\n\tTicks,\n} from \"./Units.js\";\n\nexport type FrequencyUnit = TimeBaseUnit | \"midi\";\n\n/**\n * Frequency is a primitive type for encoding Frequency values.\n * Eventually all time values are evaluated to hertz using the `valueOf` method.\n * @example\n * Tone.Frequency(\"C3\"); // 261\n * Tone.Frequency(38, \"midi\");\n * Tone.Frequency(\"C3\").transpose(4);\n * @category Unit\n */\nexport class FrequencyClass<Type extends number = Hertz> extends TimeClass<\n\tType,\n\tFrequencyUnit\n> {\n\treadonly name: string = \"Frequency\";\n\n\treadonly defaultUnits: FrequencyUnit = \"hz\";\n\n\t/**\n\t * The [concert tuning pitch](https://en.wikipedia.org/wiki/Concert_pitch) which is used\n\t * to generate all the other pitch values from notes. A4's values in Hertz.\n\t */\n\tstatic get A4(): Hertz {\n\t\treturn getA4();\n\t}\n\tstatic set A4(freq: Hertz) {\n\t\tsetA4(freq);\n\t}\n\n\t//-------------------------------------\n\t// \tAUGMENT BASE EXPRESSIONS\n\t//-------------------------------------\n\n\tprotected _getExpressions(): TimeExpression<Type> {\n\t\treturn Object.assign({}, super._getExpressions(), {\n\t\t\tmidi: {\n\t\t\t\tregexp: /^(\\d+(?:\\.\\d+)?midi)/,\n\t\t\t\tmethod(value): number {\n\t\t\t\t\tif (this.defaultUnits === \"midi\") {\n\t\t\t\t\t\treturn value;\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn FrequencyClass.mtof(value);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t},\n\t\t\tnote: {\n\t\t\t\tregexp: /^([a-g]{1}(?:b|#|##|x|bb|###|#x|x#|bbb)?)(-?[0-9]+)/i,\n\t\t\t\tmethod(pitch, octave): number {\n\t\t\t\t\tconst index = noteToScaleIndex[pitch.toLowerCase()];\n\t\t\t\t\tconst noteNumber = index + (parseInt(octave, 10) + 1) * 12;\n\t\t\t\t\tif (this.defaultUnits === \"midi\") {\n\t\t\t\t\t\treturn noteNumber;\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn FrequencyClass.mtof(noteNumber);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t},\n\t\t\ttr: {\n\t\t\t\tregexp: /^(\\d+(?:\\.\\d+)?):(\\d+(?:\\.\\d+)?):?(\\d+(?:\\.\\d+)?)?/,\n\t\t\t\tmethod(m, q, s): number {\n\t\t\t\t\tlet total = 1;\n\t\t\t\t\tif (m && m !== \"0\") {\n\t\t\t\t\t\ttotal *= this._beatsToUnits(\n\t\t\t\t\t\t\tthis._getTimeSignature() * parseFloat(m)\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tif (q && q !== \"0\") {\n\t\t\t\t\t\ttotal *= this._beatsToUnits(parseFloat(q));\n\t\t\t\t\t}\n\t\t\t\t\tif (s && s !== \"0\") {\n\t\t\t\t\t\ttotal *= this._beatsToUnits(parseFloat(s) / 4);\n\t\t\t\t\t}\n\t\t\t\t\treturn total;\n\t\t\t\t},\n\t\t\t},\n\t\t});\n\t}\n\n\t//-------------------------------------\n\t// \tEXPRESSIONS\n\t//-------------------------------------\n\n\t/**\n\t * Transposes the frequency by the given number of semitones.\n\t * @return A new transposed frequency\n\t * @example\n\t * Tone.Frequency(\"A4\").transpose(3); // \"C5\"\n\t */\n\ttranspose(interval: Interval): FrequencyClass {\n\t\treturn new FrequencyClass(\n\t\t\tthis.context,\n\t\t\tthis.valueOf() * intervalToFrequencyRatio(interval)\n\t\t);\n\t}\n\n\t/**\n\t * Takes an array of semitone intervals and returns\n\t * an array of frequencies transposed by those intervals.\n\t * @return Returns an array of Frequencies\n\t * @example\n\t * Tone.Frequency(\"A4\").harmonize([0, 3, 7]); // [\"A4\", \"C5\", \"E5\"]\n\t */\n\tharmonize(intervals: Interval[]): FrequencyClass[] {\n\t\treturn intervals.map((interval) => {\n\t\t\treturn this.transpose(interval);\n\t\t});\n\t}\n\n\t//-------------------------------------\n\t// \tUNIT CONVERSIONS\n\t//-------------------------------------\n\n\t/**\n\t * Return the value of the frequency as a MIDI note\n\t * @example\n\t * Tone.Frequency(\"C4\").toMidi(); // 60\n\t */\n\ttoMidi(): MidiNote {\n\t\treturn ftom(this.valueOf());\n\t}\n\n\t/**\n\t * Return the value of the frequency in Scientific Pitch Notation\n\t * @example\n\t * Tone.Frequency(69, \"midi\").toNote(); // \"A4\"\n\t */\n\ttoNote(): Note {\n\t\tconst freq = this.toFrequency();\n\t\tconst log = Math.log2(freq / FrequencyClass.A4);\n\t\tlet noteNumber = Math.round(12 * log) + 57;\n\t\tconst octave = Math.floor(noteNumber / 12);\n\t\tif (octave < 0) {\n\t\t\tnoteNumber += -12 * octave;\n\t\t}\n\t\tconst noteName = scaleIndexToNote[noteNumber % 12];\n\t\treturn (noteName + octave.toString()) as Note;\n\t}\n\n\t/**\n\t * Return the duration of one cycle in seconds.\n\t */\n\ttoSeconds(): Seconds {\n\t\treturn 1 / super.toSeconds();\n\t}\n\n\t/**\n\t * Return the duration of one cycle in ticks\n\t */\n\ttoTicks(): Ticks {\n\t\tconst quarterTime = this._beatsToUnits(1);\n\t\tconst quarters = this.valueOf() / quarterTime;\n\t\treturn Math.floor(quarters * this._getPPQ());\n\t}\n\n\t//-------------------------------------\n\t// \tUNIT CONVERSIONS HELPERS\n\t//-------------------------------------\n\n\t/**\n\t * With no arguments, return 0\n\t */\n\tprotected _noArg(): Type {\n\t\treturn 0 as Type;\n\t}\n\n\t/**\n\t * Returns the value of a frequency in the current units\n\t */\n\tprotected _frequencyToUnits(freq: Hertz): Type {\n\t\treturn freq as Type;\n\t}\n\n\t/**\n\t * Returns the value of a tick in the current time units\n\t */\n\tprotected _ticksToUnits(ticks: Ticks): Type {\n\t\treturn (1 / ((ticks * 60) / (this._getBpm() * this._getPPQ()))) as Type;\n\t}\n\n\t/**\n\t * Return the value of the beats in the current units\n\t */\n\tprotected _beatsToUnits(beats: number): Type {\n\t\treturn (1 / super._beatsToUnits(beats)) as Type;\n\t}\n\n\t/**\n\t * Returns the value of a second in the current units\n\t */\n\tprotected _secondsToUnits(seconds: Seconds): Type {\n\t\treturn (1 / seconds) as Type;\n\t}\n\n\t/**\n\t * Convert a MIDI note to frequency value.\n\t * @param midi The midi number to convert.\n\t * @return The corresponding frequency value\n\t */\n\tstatic mtof(midi: MidiNote): Hertz {\n\t\treturn mtof(midi);\n\t}\n\n\t/**\n\t * Convert a frequency value to a MIDI note.\n\t * @param frequency The value to frequency value to convert.\n\t */\n\tstatic ftom(frequency: Hertz): MidiNote {\n\t\treturn ftom(frequency);\n\t}\n}\n\n//-------------------------------------\n// \tFREQUENCY CONVERSIONS\n//-------------------------------------\n\n/**\n * Note to scale index.\n * @hidden\n */\nconst noteToScaleIndex = {\n\tcbbb: -3,\n\tcbb: -2,\n\tcb: -1,\n\tc: 0,\n\t\"c#\": 1,\n\tcx: 2,\n\t\"c##\": 2,\n\t\"c###\": 3,\n\t\"cx#\": 3,\n\t\"c#x\": 3,\n\tdbbb: -1,\n\tdbb: 0,\n\tdb: 1,\n\td: 2,\n\t\"d#\": 3,\n\tdx: 4,\n\t\"d##\": 4,\n\t\"d###\": 5,\n\t\"dx#\": 5,\n\t\"d#x\": 5,\n\tebbb: 1,\n\tebb: 2,\n\teb: 3,\n\te: 4,\n\t\"e#\": 5,\n\tex: 6,\n\t\"e##\": 6,\n\t\"e###\": 7,\n\t\"ex#\": 7,\n\t\"e#x\": 7,\n\tfbbb: 2,\n\tfbb: 3,\n\tfb: 4,\n\tf: 5,\n\t\"f#\": 6,\n\tfx: 7,\n\t\"f##\": 7,\n\t\"f###\": 8,\n\t\"fx#\": 8,\n\t\"f#x\": 8,\n\tgbbb: 4,\n\tgbb: 5,\n\tgb: 6,\n\tg: 7,\n\t\"g#\": 8,\n\tgx: 9,\n\t\"g##\": 9,\n\t\"g###\": 10,\n\t\"gx#\": 10,\n\t\"g#x\": 10,\n\tabbb: 6,\n\tabb: 7,\n\tab: 8,\n\ta: 9,\n\t\"a#\": 10,\n\tax: 11,\n\t\"a##\": 11,\n\t\"a###\": 12,\n\t\"ax#\": 12,\n\t\"a#x\": 12,\n\tbbbb: 8,\n\tbbb: 9,\n\tbb: 10,\n\tb: 11,\n\t\"b#\": 12,\n\tbx: 13,\n\t\"b##\": 13,\n\t\"b###\": 14,\n\t\"bx#\": 14,\n\t\"b#x\": 14,\n};\n\n/**\n * scale index to note (sharps)\n * @hidden\n */\nconst scaleIndexToNote = [\n\t\"C\",\n\t\"C#\",\n\t\"D\",\n\t\"D#\",\n\t\"E\",\n\t\"F\",\n\t\"F#\",\n\t\"G\",\n\t\"G#\",\n\t\"A\",\n\t\"A#\",\n\t\"B\",\n];\n\n/**\n * Convert a value into a FrequencyClass object.\n * @category Unit\n * @example\n * const midi = Tone.Frequency(\"C3\").toMidi();\n * console.log(midi);\n * @example\n * const hertz = Tone.Frequency(38, \"midi\").toFrequency();\n * console.log(hertz);\n */\nexport function Frequency(\n\tvalue?: TimeValue | Frequency,\n\tunits?: FrequencyUnit\n): FrequencyClass {\n\treturn new FrequencyClass(getContext(), value, units);\n}\n","import { getContext } from \"../Global.js\";\nimport { Seconds, Ticks } from \"../type/Units.js\";\nimport { TimeClass } from \"./Time.js\";\nimport { TimeBaseUnit, TimeValue } from \"./TimeBase.js\";\n\n/**\n * TransportTime is a time along the Transport's\n * timeline. It is similar to Tone.Time, but instead of evaluating\n * against the AudioContext's clock, it is evaluated against\n * the Transport's position. See [TransportTime wiki](https://github.com/Tonejs/Tone.js/wiki/TransportTime).\n * @category Unit\n */\nexport class TransportTimeClass<\n\tType extends Seconds | Ticks = Seconds,\n> extends TimeClass<Type> {\n\treadonly name: string = \"TransportTime\";\n\n\t/**\n\t * Return the current time in whichever context is relevant\n\t */\n\tprotected _now(): Type {\n\t\treturn this.context.transport.seconds as Type;\n\t}\n}\n\n/**\n * TransportTime is a time along the Transport's\n * timeline. It is similar to Tone.Time, but instead of evaluating\n * against the AudioContext's clock, it is evaluated against\n * the Transport's position. See [TransportTime wiki](https://github.com/Tonejs/Tone.js/wiki/TransportTime).\n * @category Unit\n */\nexport function TransportTime(\n\tvalue?: TimeValue,\n\tunits?: TimeBaseUnit\n): TransportTimeClass {\n\treturn new TransportTimeClass(getContext(), value, units);\n}\n","import { getContext } from \"../Global.js\";\nimport { Tone } from \"../Tone.js\";\nimport { FrequencyClass } from \"../type/Frequency.js\";\nimport { TimeClass } from \"../type/Time.js\";\nimport { TransportTimeClass } from \"../type/TransportTime.js\";\nimport { Frequency, Hertz, Seconds, Ticks, Time } from \"../type/Units.js\";\nimport { assertUsedScheduleTime } from \"../util/Debug.js\";\nimport {\n\tgetDefaultsFromInstance,\n\toptionsFromArguments,\n} from \"../util/Defaults.js\";\nimport { RecursivePartial } from \"../util/Interface.js\";\nimport {\n\tisArray,\n\tisBoolean,\n\tisDefined,\n\tisNumber,\n\tisString,\n\tisUndef,\n} from \"../util/TypeCheck.js\";\nimport { BaseContext } from \"./BaseContext.js\";\nimport type { TransportClass } from \"../clock/Transport.js\";\n\n/**\n * A unit which process audio\n */\nexport interface ToneWithContextOptions {\n\tcontext: BaseContext;\n}\n\n/**\n * The Base class for all nodes that have an AudioContext.\n */\nexport abstract class ToneWithContext<\n\tOptions extends ToneWithContextOptions,\n> extends Tone {\n\t/**\n\t * The context belonging to the node.\n\t */\n\treadonly context: BaseContext;\n\n\t/**\n\t * The default context to use if no AudioContext is passed in to the constructor.\n\t * Probably should not be set manually. Used internally.\n\t * @hidden\n\t */\n\treadonly defaultContext?: BaseContext;\n\n\t/**\n\t * Pass in a constructor as the first argument\n\t */\n\tconstructor(context?: BaseContext);\n\tconstructor(options?: Partial<ToneWithContextOptions>);\n\tconstructor() {\n\t\tsuper();\n\t\tconst options = optionsFromArguments(\n\t\t\tToneWithContext.getDefaults(),\n\t\t\targuments,\n\t\t\t[\"context\"]\n\t\t);\n\t\tif (this.defaultContext) {\n\t\t\tthis.context = this.defaultContext;\n\t\t} else {\n\t\t\tthis.context = options.context;\n\t\t}\n\t}\n\n\tstatic getDefaults(): ToneWithContextOptions {\n\t\treturn {\n\t\t\tcontext: getContext(),\n\t\t};\n\t}\n\n\t/**\n\t * Return the current time of the Context clock plus the lookAhead.\n\t * @example\n\t * setInterval(() => {\n\t * \tconsole.log(Tone.now());\n\t * }, 100);\n\t */\n\tnow(): Seconds {\n\t\treturn this.context.currentTime + this.context.lookAhead;\n\t}\n\n\t/**\n\t * Return the current time of the Context clock without any lookAhead.\n\t * @example\n\t * setInterval(() => {\n\t * \tconsole.log(Tone.immediate());\n\t * }, 100);\n\t */\n\timmediate(): Seconds {\n\t\treturn this.context.currentTime;\n\t}\n\n\t/**\n\t * The duration in seconds of one sample.\n\t */\n\tget sampleTime(): Seconds {\n\t\treturn 1 / this.context.sampleRate;\n\t}\n\n\t/**\n\t * The number of seconds of 1 processing block (128 samples)\n\t * @example\n\t * console.log(Tone.Destination.blockTime);\n\t */\n\tget blockTime(): Seconds {\n\t\treturn 128 / this.context.sampleRate;\n\t}\n\n\t/**\n\t * Convert the incoming time to seconds.\n\t * This is calculated against the current {@link TransportClass} bpm\n\t * @example\n\t * const gain = new Tone.Gain();\n\t * setInterval(() => console.log(gain.toSeconds(\"4n\")), 100);\n\t * // ramp the tempo to 60 bpm over 30 seconds\n\t * Tone.getTransport().bpm.rampTo(60, 30);\n\t */\n\ttoSeconds(time?: Time): Seconds {\n\t\tassertUsedScheduleTime(time);\n\t\treturn new TimeClass(this.context, time).toSeconds();\n\t}\n\n\t/**\n\t * Convert the input to a frequency number\n\t * @example\n\t * const gain = new Tone.Gain();\n\t * console.log(gain.toFrequency(\"4n\"));\n\t */\n\ttoFrequency(freq: Frequency): Hertz {\n\t\treturn new FrequencyClass(this.context, freq).toFrequency();\n\t}\n\n\t/**\n\t * Convert the input time into ticks\n\t * @example\n\t * const gain = new Tone.Gain();\n\t * console.log(gain.toTicks(\"4n\"));\n\t */\n\ttoTicks(time?: Time | TimeClass): Ticks {\n\t\treturn new TransportTimeClass(this.context, time).toTicks();\n\t}\n\n\t//-------------------------------------\n\t// \tGET/SET\n\t//-------------------------------------\n\n\t/**\n\t * Get a subset of the properties which are in the partial props\n\t */\n\tprotected _getPartialProperties(props: Options): Partial<Options> {\n\t\tconst options = this.get();\n\t\t// remove attributes from the prop that are not in the partial\n\t\tObject.keys(options).forEach((name) => {\n\t\t\tif (isUndef(props[name])) {\n\t\t\t\tdelete options[name];\n\t\t\t}\n\t\t});\n\t\treturn options;\n\t}\n\n\t/**\n\t * Get the object's attributes.\n\t * @example\n\t * const osc = new Tone.Oscillator();\n\t * console.log(osc.get());\n\t */\n\tget(): Options {\n\t\tconst defaults = getDefaultsFromInstance(this) as Options;\n\t\tObject.keys(defaults).forEach((attribute) => {\n\t\t\tif (Reflect.has(this, attribute)) {\n\t\t\t\tconst member = this[attribute];\n\t\t\t\tif (\n\t\t\t\t\tisDefined(member) &&\n\t\t\t\t\tisDefined(member.value) &&\n\t\t\t\t\tisDefined(member.setValueAtTime)\n\t\t\t\t) {\n\t\t\t\t\tdefaults[attribute] = member.value;\n\t\t\t\t} else if (member instanceof ToneWithContext) {\n\t\t\t\t\tdefaults[attribute] = member._getPartialProperties(\n\t\t\t\t\t\tdefaults[attribute]\n\t\t\t\t\t);\n\t\t\t\t\t// otherwise make sure it's a serializable type\n\t\t\t\t} else if (\n\t\t\t\t\tisArray(member) ||\n\t\t\t\t\tisNumber(member) ||\n\t\t\t\t\tisString(member) ||\n\t\t\t\t\tisBoolean(member)\n\t\t\t\t) {\n\t\t\t\t\tdefaults[attribute] = member;\n\t\t\t\t} else {\n\t\t\t\t\t// remove all undefined and unserializable attributes\n\t\t\t\t\tdelete defaults[attribute];\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\treturn defaults;\n\t}\n\n\t/**\n\t * Set multiple properties at once with an object.\n\t * @example\n\t * const filter = new Tone.Filter().toDestination();\n\t * // set values using an object\n\t * filter.set({\n\t * \tfrequency: \"C6\",\n\t * \ttype: \"highpass\"\n\t * });\n\t * const player = new Tone.Player(\"https://tonejs.github.io/audio/berklee/Analogsynth_octaves_highmid.mp3\").connect(filter);\n\t * player.autostart = true;\n\t */\n\tset(props: RecursivePartial<Options>): this {\n\t\tObject.keys(props).forEach((attribute) => {\n\t\t\tif (Reflect.has(this, attribute) && isDefined(this[attribute])) {\n\t\t\t\tif (\n\t\t\t\t\tthis[attribute] &&\n\t\t\t\t\tisDefined(this[attribute].value) &&\n\t\t\t\t\tisDefined(this[attribute].setValueAtTime)\n\t\t\t\t) {\n\t\t\t\t\t// small optimization\n\t\t\t\t\tif (this[attribute].value !== props[attribute]) {\n\t\t\t\t\t\tthis[attribute].value = props[attribute];\n\t\t\t\t\t}\n\t\t\t\t} else if (this[attribute] instanceof ToneWithContext) {\n\t\t\t\t\tthis[attribute].set(props[attribute]);\n\t\t\t\t} else {\n\t\t\t\t\tthis[attribute] = props[attribute];\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\treturn this;\n\t}\n}\n","import { Seconds } from \"../type/Units.js\";\nimport { Timeline, TimelineEvent } from \"./Timeline.js\";\nimport { assertRange } from \"./Debug.js\";\n\nexport type BasicPlaybackState = \"started\" | \"stopped\";\nexport type PlaybackState = BasicPlaybackState | \"paused\";\n\nexport interface StateTimelineEvent extends TimelineEvent {\n\tstate: PlaybackState;\n}\n\n/**\n * A Timeline State. Provides the methods: `setStateAtTime(\"state\", time)` and `getValueAtTime(time)`\n * @param initial The initial state of the StateTimeline. Defaults to `undefined`\n * @internal\n */\nexport class StateTimeline<\n\tAdditionalOptions extends Record<string, any> = Record<string, any>,\n> extends Timeline<StateTimelineEvent & AdditionalOptions> {\n\treadonly name: string = \"StateTimeline\";\n\n\t/**\n\t * The initial state\n\t */\n\tprivate _initial: PlaybackState;\n\n\tconstructor(initial: PlaybackState = \"stopped\") {\n\t\tsuper();\n\t\tthis._initial = initial;\n\t\tthis.setStateAtTime(this._initial, 0);\n\t}\n\n\t/**\n\t * Returns the scheduled state scheduled before or at\n\t * the given time.\n\t * @param time The time to query.\n\t * @return The name of the state input in setStateAtTime.\n\t */\n\tgetValueAtTime(time: Seconds): PlaybackState {\n\t\tconst event = this.get(time);\n\t\tif (event !== null) {\n\t\t\treturn event.state;\n\t\t} else {\n\t\t\treturn this._initial;\n\t\t}\n\t}\n\n\t/**\n\t * Add a state to the timeline.\n\t * @param state The name of the state to set.\n\t * @param time The time to query.\n\t * @param options Any additional options that are needed in the timeline.\n\t */\n\tsetStateAtTime(\n\t\tstate: PlaybackState,\n\t\ttime: Seconds,\n\t\toptions?: AdditionalOptions\n\t): this {\n\t\tassertRange(time, 0);\n\t\tthis.add(\n\t\t\tObject.assign({}, options, {\n\t\t\t\tstate,\n\t\t\t\ttime,\n\t\t\t})\n\t\t);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Return the event before the time with the given state\n\t * @param state The state to look for\n\t * @param time When to check before\n\t * @return The event with the given state before the time\n\t */\n\tgetLastState(\n\t\tstate: PlaybackState,\n\t\ttime: number\n\t): (StateTimelineEvent & AdditionalOptions) | undefined {\n\t\t// time = this.toSeconds(time);\n\t\tconst index = this._search(time);\n\t\tfor (let i = index; i >= 0; i--) {\n\t\t\tconst event = this._timeline[i];\n\t\t\tif (event.state === state) {\n\t\t\t\treturn event;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Return the event after the time with the given state\n\t * @param state The state to look for\n\t * @param time When to check from\n\t * @return The event with the given state after the time\n\t */\n\tgetNextState(\n\t\tstate: PlaybackState,\n\t\ttime: number\n\t): (StateTimelineEvent & AdditionalOptions) | undefined {\n\t\t// time = this.toSeconds(time);\n\t\tconst index = this._search(time);\n\t\tif (index !== -1) {\n\t\t\tfor (let i = index; i < this._timeline.length; i++) {\n\t\t\t\tconst event = this._timeline[i];\n\t\t\t\tif (event.state === state) {\n\t\t\t\t\treturn event;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n","import { AbstractParam } from \"../context/AbstractParam.js\";\nimport { dbToGain, gainToDb } from \"../type/Conversions.js\";\nimport {\n\tDecibels,\n\tFrequency,\n\tPositive,\n\tTime,\n\tUnitMap,\n\tUnitName,\n} from \"../type/Units.js\";\nimport { isAudioParam } from \"../util/AdvancedTypeCheck.js\";\nimport { optionsFromArguments } from \"../util/Defaults.js\";\nimport { Timeline } from \"../util/Timeline.js\";\nimport { isDefined } from \"../util/TypeCheck.js\";\nimport { ToneWithContext, ToneWithContextOptions } from \"./ToneWithContext.js\";\nimport { EQ } from \"../util/Math.js\";\nimport { assert, assertRange } from \"../util/Debug.js\";\n\nexport interface ParamOptions<TypeName extends UnitName>\n\textends ToneWithContextOptions {\n\tunits: TypeName;\n\tvalue?: UnitMap[TypeName];\n\tparam: AudioParam | Param<TypeName>;\n\tconvert: boolean;\n\tminValue?: number;\n\tmaxValue?: number;\n\tswappable?: boolean;\n}\n\n/**\n * the possible automation types\n */\ntype AutomationType =\n\t| \"linearRampToValueAtTime\"\n\t| \"exponentialRampToValueAtTime\"\n\t| \"setValueAtTime\"\n\t| \"setTargetAtTime\"\n\t| \"cancelScheduledValues\";\n\ninterface TargetAutomationEvent {\n\ttype: \"setTargetAtTime\";\n\ttime: number;\n\tvalue: number;\n\tconstant: number;\n}\n\ninterface NormalAutomationEvent {\n\ttype: Exclude<AutomationType, \"setTargetAtTime\">;\n\ttime: number;\n\tvalue: number;\n}\n/**\n * The events on the automation\n */\nexport type AutomationEvent = NormalAutomationEvent | TargetAutomationEvent;\n\n/**\n * Param wraps the native Web Audio's AudioParam to provide\n * additional unit conversion functionality. It also\n * serves as a base-class for classes which have a single,\n * automatable parameter.\n * @category Core\n */\nexport class Param<TypeName extends UnitName = \"number\">\n\textends ToneWithContext<ParamOptions<TypeName>>\n\timplements AbstractParam<TypeName>\n{\n\treadonly name: string = \"Param\";\n\n\treadonly input: GainNode | AudioParam;\n\n\treadonly units: UnitName;\n\tconvert: boolean;\n\toverridden = false;\n\n\t/**\n\t * The timeline which tracks all of the automations.\n\t */\n\tprotected _events: Timeline<AutomationEvent>;\n\n\t/**\n\t * The native parameter to control\n\t */\n\tprotected _param: AudioParam;\n\n\t/**\n\t * The default value before anything is assigned\n\t */\n\tprotected _initialValue: number;\n\n\t/**\n\t * The minimum output value\n\t */\n\tprivate _minOutput = 1e-7;\n\n\t/**\n\t * Private reference to the min and max values if passed into the constructor\n\t */\n\tprivate readonly _minValue?: number;\n\tprivate readonly _maxValue?: number;\n\n\t/**\n\t * If the underlying AudioParam can be swapped out\n\t * using the setParam method.\n\t */\n\tprotected readonly _swappable: boolean;\n\n\t/**\n\t * @param param The AudioParam to wrap\n\t * @param units The unit name\n\t * @param convert Whether or not to convert the value to the target units\n\t */\n\tconstructor(param: AudioParam, units?: TypeName, convert?: boolean);\n\tconstructor(options: Partial<ParamOptions<TypeName>>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(Param.getDefaults(), arguments, [\n\t\t\t\"param\",\n\t\t\t\"units\",\n\t\t\t\"convert\",\n\t\t]);\n\t\tsuper(options);\n\n\t\tassert(\n\t\t\tisDefined(options.param) &&\n\t\t\t\t(isAudioParam(options.param) || options.param instanceof Param),\n\t\t\t\"param must be an AudioParam\"\n\t\t);\n\n\t\twhile (!isAudioParam(options.param)) {\n\t\t\toptions.param = options.param._param;\n\t\t}\n\n\t\tthis._swappable = isDefined(options.swappable)\n\t\t\t? options.swappable\n\t\t\t: false;\n\t\tif (this._swappable) {\n\t\t\tthis.input = this.context.createGain();\n\t\t\t// initialize\n\t\t\tthis._param = options.param;\n\t\t\tthis.input.connect(this._param);\n\t\t} else {\n\t\t\tthis._param = this.input = options.param;\n\t\t}\n\t\tthis._events = new Timeline<AutomationEvent>(1000);\n\t\tthis._initialValue = this._param.defaultValue;\n\t\tthis.units = options.units;\n\t\tthis.convert = options.convert;\n\t\tthis._minValue = options.minValue;\n\t\tthis._maxValue = options.maxValue;\n\n\t\t// if the value is defined, set it immediately\n\t\tif (\n\t\t\tisDefined(options.value) &&\n\t\t\toptions.value !== this._toType(this._initialValue)\n\t\t) {\n\t\t\tthis.setValueAtTime(options.value, 0);\n\t\t}\n\t}\n\n\tstatic getDefaults(): ParamOptions<any> {\n\t\treturn Object.assign(ToneWithContext.getDefaults(), {\n\t\t\tconvert: true,\n\t\t\tunits: \"number\" as UnitName,\n\t\t} as ParamOptions<any>);\n\t}\n\n\tget value(): UnitMap[TypeName] {\n\t\tconst now = this.now();\n\t\treturn this.getValueAtTime(now);\n\t}\n\tset value(value) {\n\t\tthis.cancelScheduledValues(this.now());\n\t\tthis.setValueAtTime(value, this.now());\n\t}\n\n\tget minValue(): number {\n\t\t// if it's not the default minValue, return it\n\t\tif (isDefined(this._minValue)) {\n\t\t\treturn this._minValue;\n\t\t} else if (\n\t\t\tthis.units === \"time\" ||\n\t\t\tthis.units === \"frequency\" ||\n\t\t\tthis.units === \"normalRange\" ||\n\t\t\tthis.units === \"positive\" ||\n\t\t\tthis.units === \"transportTime\" ||\n\t\t\tthis.units === \"ticks\" ||\n\t\t\tthis.units === \"bpm\" ||\n\t\t\tthis.units === \"hertz\" ||\n\t\t\tthis.units === \"samples\"\n\t\t) {\n\t\t\treturn 0;\n\t\t} else if (this.units === \"audioRange\") {\n\t\t\treturn -1;\n\t\t} else if (this.units === \"decibels\") {\n\t\t\treturn -Infinity;\n\t\t} else {\n\t\t\treturn this._param.minValue;\n\t\t}\n\t}\n\n\tget maxValue(): number {\n\t\tif (isDefined(this._maxValue)) {\n\t\t\treturn this._maxValue;\n\t\t} else if (\n\t\t\tthis.units === \"normalRange\" ||\n\t\t\tthis.units === \"audioRange\"\n\t\t) {\n\t\t\treturn 1;\n\t\t} else {\n\t\t\treturn this._param.maxValue;\n\t\t}\n\t}\n\n\t/**\n\t * Type guard based on the unit name\n\t */\n\tprivate _is<T>(arg: any, type: UnitName): arg is T {\n\t\treturn this.units === type;\n\t}\n\n\t/**\n\t * Make sure the value is always in the defined range\n\t */\n\tprivate _assertRange(value: number): number {\n\t\tif (isDefined(this.maxValue) && isDefined(this.minValue)) {\n\t\t\tassertRange(\n\t\t\t\tvalue,\n\t\t\t\tthis._fromType(this.minValue),\n\t\t\t\tthis._fromType(this.maxValue)\n\t\t\t);\n\t\t}\n\t\treturn value;\n\t}\n\n\t/**\n\t * Convert the given value from the type specified by Param.units\n\t * into the destination value (such as Gain or Frequency).\n\t */\n\tprotected _fromType(val: UnitMap[TypeName]): number {\n\t\tif (this.convert && !this.overridden) {\n\t\t\tif (this._is<Time>(val, \"time\")) {\n\t\t\t\treturn this.toSeconds(val);\n\t\t\t} else if (this._is<Decibels>(val, \"decibels\")) {\n\t\t\t\treturn dbToGain(val);\n\t\t\t} else if (this._is<Frequency>(val, \"frequency\")) {\n\t\t\t\treturn this.toFrequency(val);\n\t\t\t} else {\n\t\t\t\treturn val as number;\n\t\t\t}\n\t\t} else if (this.overridden) {\n\t\t\t// if it's overridden, should only schedule 0s\n\t\t\treturn 0;\n\t\t} else {\n\t\t\treturn val as number;\n\t\t}\n\t}\n\n\t/**\n\t * Convert the parameters value into the units specified by Param.units.\n\t */\n\tprotected _toType(val: number): UnitMap[TypeName] {\n\t\tif (this.convert && this.units === \"decibels\") {\n\t\t\treturn gainToDb(val) as UnitMap[TypeName];\n\t\t} else {\n\t\t\treturn val as UnitMap[TypeName];\n\t\t}\n\t}\n\n\t//-------------------------------------\n\t// ABSTRACT PARAM INTERFACE\n\t// all docs are generated from ParamInterface.ts\n\t//-------------------------------------\n\n\tsetValueAtTime(value: UnitMap[TypeName], time: Time): this {\n\t\tconst computedTime = this.toSeconds(time);\n\t\tconst numericValue = this._fromType(value);\n\t\tassert(\n\t\t\tisFinite(numericValue) && isFinite(computedTime),\n\t\t\t`Invalid argument(s) to setValueAtTime: ${JSON.stringify(value)}, ${JSON.stringify(time)}`\n\t\t);\n\t\tthis._assertRange(numericValue);\n\t\tthis.log(this.units, \"setValueAtTime\", value, computedTime);\n\t\tthis._events.add({\n\t\t\ttime: computedTime,\n\t\t\ttype: \"setValueAtTime\",\n\t\t\tvalue: numericValue,\n\t\t});\n\t\tthis._param.setValueAtTime(numericValue, computedTime);\n\t\treturn this;\n\t}\n\n\tgetValueAtTime(time: Time): UnitMap[TypeName] {\n\t\tconst computedTime = Math.max(this.toSeconds(time), 0);\n\t\tconst after = this._events.getAfter(computedTime);\n\t\tconst before = this._events.get(computedTime);\n\t\tlet value = this._initialValue;\n\t\t// if it was set by\n\t\tif (before === null) {\n\t\t\tvalue = this._initialValue;\n\t\t} else if (\n\t\t\tbefore.type === \"setTargetAtTime\" &&\n\t\t\t(after === null || after.type === \"setValueAtTime\")\n\t\t) {\n\t\t\tconst previous = this._events.getBefore(before.time);\n\t\t\tlet previousVal;\n\t\t\tif (previous === null) {\n\t\t\t\tpreviousVal = this._initialValue;\n\t\t\t} else {\n\t\t\t\tpreviousVal = previous.value;\n\t\t\t}\n\t\t\tif (before.type === \"setTargetAtTime\") {\n\t\t\t\tvalue = this._exponentialApproach(\n\t\t\t\t\tbefore.time,\n\t\t\t\t\tpreviousVal,\n\t\t\t\t\tbefore.value,\n\t\t\t\t\tbefore.constant,\n\t\t\t\t\tcomputedTime\n\t\t\t\t);\n\t\t\t}\n\t\t} else if (after === null) {\n\t\t\tvalue = before.value;\n\t\t} else if (\n\t\t\tafter.type === \"linearRampToValueAtTime\" ||\n\t\t\tafter.type === \"exponentialRampToValueAtTime\"\n\t\t) {\n\t\t\tlet beforeValue = before.value;\n\t\t\tif (before.type === \"setTargetAtTime\") {\n\t\t\t\tconst previous = this._events.getBefore(before.time);\n\t\t\t\tif (previous === null) {\n\t\t\t\t\tbeforeValue = this._initialValue;\n\t\t\t\t} else {\n\t\t\t\t\tbeforeValue = previous.value;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (after.type === \"linearRampToValueAtTime\") {\n\t\t\t\tvalue = this._linearInterpolate(\n\t\t\t\t\tbefore.time,\n\t\t\t\t\tbeforeValue,\n\t\t\t\t\tafter.time,\n\t\t\t\t\tafter.value,\n\t\t\t\t\tcomputedTime\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tvalue = this._exponentialInterpolate(\n\t\t\t\t\tbefore.time,\n\t\t\t\t\tbeforeValue,\n\t\t\t\t\tafter.time,\n\t\t\t\t\tafter.value,\n\t\t\t\t\tcomputedTime\n\t\t\t\t);\n\t\t\t}\n\t\t} else {\n\t\t\tvalue = before.value;\n\t\t}\n\t\treturn this._toType(value);\n\t}\n\n\tsetRampPoint(time: Time): this {\n\t\ttime = this.toSeconds(time);\n\t\tlet currentVal = this.getValueAtTime(time);\n\t\tthis.cancelAndHoldAtTime(time);\n\t\tif (this._fromType(currentVal) === 0) {\n\t\t\tcurrentVal = this._toType(this._minOutput);\n\t\t}\n\t\tthis.setValueAtTime(currentVal, time);\n\t\treturn this;\n\t}\n\n\tlinearRampToValueAtTime(value: UnitMap[TypeName], endTime: Time): this {\n\t\tconst numericValue = this._fromType(value);\n\t\tconst computedTime = this.toSeconds(endTime);\n\t\tassert(\n\t\t\tisFinite(numericValue) && isFinite(computedTime),\n\t\t\t`Invalid argument(s) to linearRampToValueAtTime: ${JSON.stringify(value)}, ${JSON.stringify(endTime)}`\n\t\t);\n\t\tthis._assertRange(numericValue);\n\t\tthis._events.add({\n\t\t\ttime: computedTime,\n\t\t\ttype: \"linearRampToValueAtTime\",\n\t\t\tvalue: numericValue,\n\t\t});\n\t\tthis.log(this.units, \"linearRampToValueAtTime\", value, computedTime);\n\t\tthis._param.linearRampToValueAtTime(numericValue, computedTime);\n\t\treturn this;\n\t}\n\n\texponentialRampToValueAtTime(\n\t\tvalue: UnitMap[TypeName],\n\t\tendTime: Time\n\t): this {\n\t\tlet numericValue = this._fromType(value);\n\t\t// the value can't be 0\n\t\tnumericValue = EQ(numericValue, 0) ? this._minOutput : numericValue;\n\t\tthis._assertRange(numericValue);\n\t\tconst computedTime = this.toSeconds(endTime);\n\t\tassert(\n\t\t\tisFinite(numericValue) && isFinite(computedTime),\n\t\t\t`Invalid argument(s) to exponentialRampToValueAtTime: ${JSON.stringify(value)}, ${JSON.stringify(endTime)}`\n\t\t);\n\t\t// store the event\n\t\tthis._events.add({\n\t\t\ttime: computedTime,\n\t\t\ttype: \"exponentialRampToValueAtTime\",\n\t\t\tvalue: numericValue,\n\t\t});\n\t\tthis.log(\n\t\t\tthis.units,\n\t\t\t\"exponentialRampToValueAtTime\",\n\t\t\tvalue,\n\t\t\tcomputedTime\n\t\t);\n\t\tthis._param.exponentialRampToValueAtTime(numericValue, computedTime);\n\t\treturn this;\n\t}\n\n\texponentialRampTo(\n\t\tvalue: UnitMap[TypeName],\n\t\trampTime: Time,\n\t\tstartTime?: Time\n\t): this {\n\t\tstartTime = this.toSeconds(startTime);\n\t\tthis.setRampPoint(startTime);\n\t\tthis.exponentialRampToValueAtTime(\n\t\t\tvalue,\n\t\t\tstartTime + this.toSeconds(rampTime)\n\t\t);\n\t\treturn this;\n\t}\n\n\tlinearRampTo(\n\t\tvalue: UnitMap[TypeName],\n\t\trampTime: Time,\n\t\tstartTime?: Time\n\t): this {\n\t\tstartTime = this.toSeconds(startTime);\n\t\tthis.setRampPoint(startTime);\n\t\tthis.linearRampToValueAtTime(\n\t\t\tvalue,\n\t\t\tstartTime + this.toSeconds(rampTime)\n\t\t);\n\t\treturn this;\n\t}\n\n\ttargetRampTo(\n\t\tvalue: UnitMap[TypeName],\n\t\trampTime: Time,\n\t\tstartTime?: Time\n\t): this {\n\t\tstartTime = this.toSeconds(startTime);\n\t\tthis.setRampPoint(startTime);\n\t\tthis.exponentialApproachValueAtTime(value, startTime, rampTime);\n\t\treturn this;\n\t}\n\n\texponentialApproachValueAtTime(\n\t\tvalue: UnitMap[TypeName],\n\t\ttime: Time,\n\t\trampTime: Time\n\t): this {\n\t\ttime = this.toSeconds(time);\n\t\trampTime = this.toSeconds(rampTime);\n\t\tconst timeConstant = Math.log(rampTime + 1) / Math.log(200);\n\t\tthis.setTargetAtTime(value, time, timeConstant);\n\t\t// at 90% start a linear ramp to the final value\n\t\tthis.cancelAndHoldAtTime(time + rampTime * 0.9);\n\t\tthis.linearRampToValueAtTime(value, time + rampTime);\n\t\treturn this;\n\t}\n\n\tsetTargetAtTime(\n\t\tvalue: UnitMap[TypeName],\n\t\tstartTime: Time,\n\t\ttimeConstant: Positive\n\t): this {\n\t\tconst numericValue = this._fromType(value);\n\t\t// The value will never be able to approach without timeConstant > 0.\n\t\tassert(\n\t\t\tisFinite(timeConstant) && timeConstant > 0,\n\t\t\t\"timeConstant must be a number greater than 0\"\n\t\t);\n\t\tconst computedTime = this.toSeconds(startTime);\n\t\tthis._assertRange(numericValue);\n\t\tassert(\n\t\t\tisFinite(numericValue) && isFinite(computedTime),\n\t\t\t`Invalid argument(s) to setTargetAtTime: ${JSON.stringify(value)}, ${JSON.stringify(startTime)}`\n\t\t);\n\t\tthis._events.add({\n\t\t\tconstant: timeConstant,\n\t\t\ttime: computedTime,\n\t\t\ttype: \"setTargetAtTime\",\n\t\t\tvalue: numericValue,\n\t\t});\n\t\tthis.log(\n\t\t\tthis.units,\n\t\t\t\"setTargetAtTime\",\n\t\t\tvalue,\n\t\t\tcomputedTime,\n\t\t\ttimeConstant\n\t\t);\n\t\tthis._param.setTargetAtTime(numericValue, computedTime, timeConstant);\n\t\treturn this;\n\t}\n\n\tsetValueCurveAtTime(\n\t\tvalues: UnitMap[TypeName][],\n\t\tstartTime: Time,\n\t\tduration: Time,\n\t\tscaling = 1\n\t): this {\n\t\tduration = this.toSeconds(duration);\n\t\tstartTime = this.toSeconds(startTime);\n\t\tconst startingValue = this._fromType(values[0]) * scaling;\n\t\tthis.setValueAtTime(this._toType(startingValue), startTime);\n\t\tconst segTime = duration / (values.length - 1);\n\t\tfor (let i = 1; i < values.length; i++) {\n\t\t\tconst numericValue = this._fromType(values[i]) * scaling;\n\t\t\tthis.linearRampToValueAtTime(\n\t\t\t\tthis._toType(numericValue),\n\t\t\t\tstartTime + i * segTime\n\t\t\t);\n\t\t}\n\t\treturn this;\n\t}\n\n\tcancelScheduledValues(time: Time): this {\n\t\tconst computedTime = this.toSeconds(time);\n\t\tassert(\n\t\t\tisFinite(computedTime),\n\t\t\t`Invalid argument to cancelScheduledValues: ${JSON.stringify(time)}`\n\t\t);\n\t\tthis._events.cancel(computedTime);\n\t\tthis._param.cancelScheduledValues(computedTime);\n\t\tthis.log(this.units, \"cancelScheduledValues\", computedTime);\n\t\treturn this;\n\t}\n\n\tcancelAndHoldAtTime(time: Time): this {\n\t\tconst computedTime = this.toSeconds(time);\n\t\tconst valueAtTime = this._fromType(this.getValueAtTime(computedTime));\n\t\t// remove the schedule events\n\t\tassert(\n\t\t\tisFinite(computedTime),\n\t\t\t`Invalid argument to cancelAndHoldAtTime: ${JSON.stringify(time)}`\n\t\t);\n\n\t\tthis.log(\n\t\t\tthis.units,\n\t\t\t\"cancelAndHoldAtTime\",\n\t\t\tcomputedTime,\n\t\t\t\"value=\" + valueAtTime\n\t\t);\n\n\t\t// if there is an event at the given computedTime\n\t\t// and that even is not a \"set\"\n\t\tconst before = this._events.get(computedTime);\n\t\tconst after = this._events.getAfter(computedTime);\n\t\tif (before && EQ(before.time, computedTime)) {\n\t\t\t// remove everything after\n\t\t\tif (after) {\n\t\t\t\tthis._param.cancelScheduledValues(after.time);\n\t\t\t\tthis._events.cancel(after.time);\n\t\t\t} else {\n\t\t\t\tthis._param.cancelAndHoldAtTime(computedTime);\n\t\t\t\tthis._events.cancel(computedTime + this.sampleTime);\n\t\t\t}\n\t\t} else if (after) {\n\t\t\tthis._param.cancelScheduledValues(after.time);\n\t\t\t// cancel the next event(s)\n\t\t\tthis._events.cancel(after.time);\n\t\t\tif (after.type === \"linearRampToValueAtTime\") {\n\t\t\t\tthis.linearRampToValueAtTime(\n\t\t\t\t\tthis._toType(valueAtTime),\n\t\t\t\t\tcomputedTime\n\t\t\t\t);\n\t\t\t} else if (after.type === \"exponentialRampToValueAtTime\") {\n\t\t\t\tthis.exponentialRampToValueAtTime(\n\t\t\t\t\tthis._toType(valueAtTime),\n\t\t\t\t\tcomputedTime\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// set the value at the given time\n\t\tthis._events.add({\n\t\t\ttime: computedTime,\n\t\t\ttype: \"setValueAtTime\",\n\t\t\tvalue: valueAtTime,\n\t\t});\n\t\tthis._param.setValueAtTime(valueAtTime, computedTime);\n\t\treturn this;\n\t}\n\n\trampTo(\n\t\tvalue: UnitMap[TypeName],\n\t\trampTime: Time = 0.1,\n\t\tstartTime?: Time\n\t): this {\n\t\tif (\n\t\t\tthis.units === \"frequency\" ||\n\t\t\tthis.units === \"bpm\" ||\n\t\t\tthis.units === \"decibels\"\n\t\t) {\n\t\t\tthis.exponentialRampTo(value, rampTime, startTime);\n\t\t} else {\n\t\t\tthis.linearRampTo(value, rampTime, startTime);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Apply all of the previously scheduled events to the passed in Param or AudioParam.\n\t * The applied values will start at the context's current time and schedule\n\t * all of the events which are scheduled on this Param onto the passed in param.\n\t */\n\tapply(param: Param | AudioParam): this {\n\t\tconst now = this.context.currentTime;\n\t\t// set the param's value at the current time and schedule everything else\n\t\tparam.setValueAtTime(this.getValueAtTime(now) as number, now);\n\t\t// if the previous event was a curve, then set the rest of it\n\t\tconst previousEvent = this._events.get(now);\n\t\tif (previousEvent && previousEvent.type === \"setTargetAtTime\") {\n\t\t\t// approx it until the next event with linear ramps\n\t\t\tconst nextEvent = this._events.getAfter(previousEvent.time);\n\t\t\t// or for 2 seconds if there is no event\n\t\t\tconst endTime = nextEvent ? nextEvent.time : now + 2;\n\t\t\tconst subdivisions = (endTime - now) / 10;\n\t\t\tfor (let i = now; i < endTime; i += subdivisions) {\n\t\t\t\tparam.linearRampToValueAtTime(\n\t\t\t\t\tthis.getValueAtTime(i) as number,\n\t\t\t\t\ti\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tthis._events.forEachAfter(this.context.currentTime, (event) => {\n\t\t\tif (event.type === \"cancelScheduledValues\") {\n\t\t\t\tparam.cancelScheduledValues(event.time);\n\t\t\t} else if (event.type === \"setTargetAtTime\") {\n\t\t\t\tparam.setTargetAtTime(event.value, event.time, event.constant);\n\t\t\t} else {\n\t\t\t\tparam[event.type](event.value, event.time);\n\t\t\t}\n\t\t});\n\t\treturn this;\n\t}\n\n\t/**\n\t * Replace the Param's internal AudioParam. Will apply scheduled curves\n\t * onto the parameter and replace the connections.\n\t */\n\tsetParam(param: AudioParam): this {\n\t\tassert(\n\t\t\tthis._swappable,\n\t\t\t\"The Param must be assigned as 'swappable' in the constructor\"\n\t\t);\n\t\tconst input = this.input as GainNode;\n\t\tinput.disconnect(this._param);\n\t\tthis.apply(param);\n\t\tthis._param = param;\n\t\tinput.connect(this._param);\n\t\treturn this;\n\t}\n\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis._events.dispose();\n\t\treturn this;\n\t}\n\n\tget defaultValue(): UnitMap[TypeName] {\n\t\treturn this._toType(this._param.defaultValue);\n\t}\n\n\t//-------------------------------------\n\t// \tAUTOMATION CURVE CALCULATIONS\n\t// \tMIT License, copyright (c) 2014 Jordan Santell\n\t//-------------------------------------\n\n\t// Calculates the the value along the curve produced by setTargetAtTime\n\tprotected _exponentialApproach(\n\t\tt0: number,\n\t\tv0: number,\n\t\tv1: number,\n\t\ttimeConstant: number,\n\t\tt: number\n\t): number {\n\t\treturn v1 + (v0 - v1) * Math.exp(-(t - t0) / timeConstant);\n\t}\n\n\t// Calculates the the value along the curve produced by linearRampToValueAtTime\n\tprotected _linearInterpolate(\n\t\tt0: number,\n\t\tv0: number,\n\t\tt1: number,\n\t\tv1: number,\n\t\tt: number\n\t): number {\n\t\treturn v0 + (v1 - v0) * ((t - t0) / (t1 - t0));\n\t}\n\n\t// Calculates the the value along the curve produced by exponentialRampToValueAtTime\n\tprotected _exponentialInterpolate(\n\t\tt0: number,\n\t\tv0: number,\n\t\tt1: number,\n\t\tv1: number,\n\t\tt: number\n\t): number {\n\t\treturn v0 * Math.pow(v1 / v0, (t - t0) / (t1 - t0));\n\t}\n}\n","import { isAudioNode, isAudioParam } from \"../util/AdvancedTypeCheck.js\";\nimport { isDefined } from \"../util/TypeCheck.js\";\nimport { Param } from \"./Param.js\";\nimport { ToneWithContext, ToneWithContextOptions } from \"./ToneWithContext.js\";\nimport { assert, warn } from \"../util/Debug.js\";\n\nexport type InputNode = ToneAudioNode | AudioNode | Param<any> | AudioParam;\nexport type OutputNode = ToneAudioNode | AudioNode;\n\ninterface ChannelProperties {\n\tchannelCount: number;\n\tchannelCountMode: ChannelCountMode;\n\tchannelInterpretation: ChannelInterpretation;\n}\n\n/**\n * The possible options for this node\n */\nexport type ToneAudioNodeOptions = ToneWithContextOptions;\n\n/**\n * ToneAudioNode is the base class for classes which process audio.\n * @category Core\n */\nexport abstract class ToneAudioNode<\n\tOptions extends ToneAudioNodeOptions = ToneAudioNodeOptions,\n> extends ToneWithContext<Options> {\n\t/**\n\t * The name of the class\n\t */\n\tabstract readonly name: string;\n\n\t/**\n\t * The input node or nodes. If the object is a source,\n\t * it does not have any input and this.input is undefined.\n\t */\n\tabstract input: InputNode | undefined;\n\n\t/**\n\t * The output nodes. If the object is a sink,\n\t * it does not have any output and this.output is undefined.\n\t */\n\tabstract output: OutputNode | undefined;\n\n\t/**\n\t * The number of inputs feeding into the AudioNode.\n\t * For source nodes, this will be 0.\n\t * @example\n\t * const node = new Tone.Gain();\n\t * console.log(node.numberOfInputs);\n\t */\n\tget numberOfInputs(): number {\n\t\tif (isDefined(this.input)) {\n\t\t\tif (isAudioParam(this.input) || this.input instanceof Param) {\n\t\t\t\treturn 1;\n\t\t\t} else {\n\t\t\t\treturn this.input.numberOfInputs;\n\t\t\t}\n\t\t} else {\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\t/**\n\t * The number of outputs of the AudioNode.\n\t * @example\n\t * const node = new Tone.Gain();\n\t * console.log(node.numberOfOutputs);\n\t */\n\tget numberOfOutputs(): number {\n\t\tif (isDefined(this.output)) {\n\t\t\treturn this.output.numberOfOutputs;\n\t\t} else {\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\t/**\n\t * List all of the node that must be set to match the ChannelProperties\n\t */\n\tprotected _internalChannels: OutputNode[] = [];\n\n\t//-------------------------------------\n\t// AUDIO PROPERTIES\n\t//-------------------------------------\n\n\t/**\n\t * Used to decide which nodes to get/set properties on\n\t */\n\tprivate _isAudioNode(node: any): node is AudioNode | ToneAudioNode {\n\t\treturn (\n\t\t\tisDefined(node) &&\n\t\t\t(node instanceof ToneAudioNode || isAudioNode(node))\n\t\t);\n\t}\n\n\t/**\n\t * Get all of the audio nodes (either internal or input/output) which together\n\t * make up how the class node responds to channel input/output\n\t */\n\tprivate _getInternalNodes(): OutputNode[] {\n\t\tconst nodeList = this._internalChannels.slice(0);\n\t\tif (this._isAudioNode(this.input)) {\n\t\t\tnodeList.push(this.input);\n\t\t}\n\t\tif (this._isAudioNode(this.output)) {\n\t\t\tif (this.input !== this.output) {\n\t\t\t\tnodeList.push(this.output);\n\t\t\t}\n\t\t}\n\t\treturn nodeList;\n\t}\n\n\t/**\n\t * Set the audio options for this node such as channelInterpretation\n\t * channelCount, etc.\n\t * @param options\n\t */\n\tprivate _setChannelProperties(options: ChannelProperties): void {\n\t\tconst nodeList = this._getInternalNodes();\n\t\tnodeList.forEach((node) => {\n\t\t\tnode.channelCount = options.channelCount;\n\t\t\tnode.channelCountMode = options.channelCountMode;\n\t\t\tnode.channelInterpretation = options.channelInterpretation;\n\t\t});\n\t}\n\n\t/**\n\t * Get the current audio options for this node such as channelInterpretation\n\t * channelCount, etc.\n\t */\n\tprivate _getChannelProperties(): ChannelProperties {\n\t\tconst nodeList = this._getInternalNodes();\n\t\tassert(\n\t\t\tnodeList.length > 0,\n\t\t\t\"ToneAudioNode does not have any internal nodes\"\n\t\t);\n\t\t// use the first node to get properties\n\t\t// they should all be the same\n\t\tconst node = nodeList[0];\n\t\treturn {\n\t\t\tchannelCount: node.channelCount,\n\t\t\tchannelCountMode: node.channelCountMode,\n\t\t\tchannelInterpretation: node.channelInterpretation,\n\t\t};\n\t}\n\n\t/**\n\t * channelCount is the number of channels used when up-mixing and down-mixing\n\t * connections to any inputs to the node. The default value is 2 except for\n\t * specific nodes where its value is specially determined.\n\t */\n\tget channelCount(): number {\n\t\treturn this._getChannelProperties().channelCount;\n\t}\n\tset channelCount(channelCount) {\n\t\tconst props = this._getChannelProperties();\n\t\t// merge it with the other properties\n\t\tthis._setChannelProperties(Object.assign(props, { channelCount }));\n\t}\n\n\t/**\n\t * channelCountMode determines how channels will be counted when up-mixing and\n\t * down-mixing connections to any inputs to the node.\n\t * The default value is \"max\". This attribute has no effect for nodes with no inputs.\n\t * * \"max\" - computedNumberOfChannels is the maximum of the number of channels of all connections to an input. In this mode channelCount is ignored.\n\t * * \"clamped-max\" - computedNumberOfChannels is determined as for \"max\" and then clamped to a maximum value of the given channelCount.\n\t * * \"explicit\" - computedNumberOfChannels is the exact value as specified by the channelCount.\n\t */\n\tget channelCountMode(): ChannelCountMode {\n\t\treturn this._getChannelProperties().channelCountMode;\n\t}\n\tset channelCountMode(channelCountMode) {\n\t\tconst props = this._getChannelProperties();\n\t\t// merge it with the other properties\n\t\tthis._setChannelProperties(Object.assign(props, { channelCountMode }));\n\t}\n\n\t/**\n\t * channelInterpretation determines how individual channels will be treated\n\t * when up-mixing and down-mixing connections to any inputs to the node.\n\t * The default value is \"speakers\".\n\t */\n\tget channelInterpretation(): ChannelInterpretation {\n\t\treturn this._getChannelProperties().channelInterpretation;\n\t}\n\tset channelInterpretation(channelInterpretation) {\n\t\tconst props = this._getChannelProperties();\n\t\t// merge it with the other properties\n\t\tthis._setChannelProperties(\n\t\t\tObject.assign(props, { channelInterpretation })\n\t\t);\n\t}\n\n\t//-------------------------------------\n\t// CONNECTIONS\n\t//-------------------------------------\n\n\t/**\n\t * connect the output of a ToneAudioNode to an AudioParam, AudioNode, or ToneAudioNode\n\t * @param destination The output to connect to\n\t * @param outputNum The output to connect from\n\t * @param inputNum The input to connect to\n\t */\n\tconnect(destination: InputNode, outputNum = 0, inputNum = 0): this {\n\t\tconnect(this, destination, outputNum, inputNum);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Connect the output to the context's destination node.\n\t * @example\n\t * const osc = new Tone.Oscillator(\"C2\").start();\n\t * osc.toDestination();\n\t */\n\ttoDestination(): this {\n\t\tthis.connect(this.context.destination);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Connect the output to the context's destination node.\n\t * @see {@link toDestination}\n\t * @deprecated\n\t */\n\ttoMaster(): this {\n\t\twarn(\"toMaster() has been renamed toDestination()\");\n\t\treturn this.toDestination();\n\t}\n\n\t/**\n\t * disconnect the output\n\t */\n\tdisconnect(destination?: InputNode, outputNum = 0, inputNum = 0): this {\n\t\tdisconnect(this, destination, outputNum, inputNum);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Connect the output of this node to the rest of the nodes in series.\n\t * @example\n\t * const player = new Tone.Player(\"https://tonejs.github.io/audio/drum-samples/handdrum-loop.mp3\");\n\t * player.autostart = true;\n\t * const filter = new Tone.AutoFilter(4).start();\n\t * const distortion = new Tone.Distortion(0.5);\n\t * // connect the player to the filter, distortion and then to the master output\n\t * player.chain(filter, distortion, Tone.Destination);\n\t */\n\tchain(...nodes: InputNode[]): this {\n\t\tconnectSeries(this, ...nodes);\n\t\treturn this;\n\t}\n\n\t/**\n\t * connect the output of this node to the rest of the nodes in parallel.\n\t * @example\n\t * const player = new Tone.Player(\"https://tonejs.github.io/audio/drum-samples/conga-rhythm.mp3\");\n\t * player.autostart = true;\n\t * const pitchShift = new Tone.PitchShift(4).toDestination();\n\t * const filter = new Tone.Filter(\"G5\").toDestination();\n\t * // connect a node to the pitch shift and filter in parallel\n\t * player.fan(pitchShift, filter);\n\t */\n\tfan(...nodes: InputNode[]): this {\n\t\tnodes.forEach((node) => this.connect(node));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Dispose and disconnect\n\t */\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tif (isDefined(this.input)) {\n\t\t\tif (this.input instanceof ToneAudioNode) {\n\t\t\t\tthis.input.dispose();\n\t\t\t} else if (isAudioNode(this.input)) {\n\t\t\t\tthis.input.disconnect();\n\t\t\t}\n\t\t}\n\t\tif (isDefined(this.output)) {\n\t\t\tif (this.output instanceof ToneAudioNode) {\n\t\t\t\tthis.output.dispose();\n\t\t\t} else if (isAudioNode(this.output)) {\n\t\t\t\tthis.output.disconnect();\n\t\t\t}\n\t\t}\n\t\tthis._internalChannels = [];\n\t\treturn this;\n\t}\n}\n\n//-------------------------------------\n// CONNECTIONS\n//-------------------------------------\n\n/**\n * connect together all of the arguments in series\n * @param nodes\n */\nexport function connectSeries(...nodes: InputNode[]): void {\n\tconst first = nodes.shift();\n\tnodes.reduce((prev, current) => {\n\t\tif (prev instanceof ToneAudioNode) {\n\t\t\tprev.connect(current);\n\t\t} else if (isAudioNode(prev)) {\n\t\t\tconnect(prev, current);\n\t\t}\n\t\treturn current;\n\t}, first);\n}\n\n/**\n * Connect two nodes together so that signal flows from the\n * first node to the second. Optionally specify the input and output channels.\n * @param srcNode The source node\n * @param dstNode The destination node\n * @param outputNumber The output channel of the srcNode\n * @param inputNumber The input channel of the dstNode\n */\nexport function connect(\n\tsrcNode: OutputNode,\n\tdstNode: InputNode,\n\toutputNumber = 0,\n\tinputNumber = 0\n): void {\n\tassert(isDefined(srcNode), \"Cannot connect from undefined node\");\n\tassert(isDefined(dstNode), \"Cannot connect to undefined node\");\n\n\tif (dstNode instanceof ToneAudioNode || isAudioNode(dstNode)) {\n\t\tassert(\n\t\t\tdstNode.numberOfInputs > 0,\n\t\t\t\"Cannot connect to node with no inputs\"\n\t\t);\n\t}\n\tassert(\n\t\tsrcNode.numberOfOutputs > 0,\n\t\t\"Cannot connect from node with no outputs\"\n\t);\n\n\t// resolve the input of the dstNode\n\twhile (dstNode instanceof ToneAudioNode || dstNode instanceof Param) {\n\t\tif (isDefined(dstNode.input)) {\n\t\t\tdstNode = dstNode.input;\n\t\t}\n\t}\n\n\twhile (srcNode instanceof ToneAudioNode) {\n\t\tif (isDefined(srcNode.output)) {\n\t\t\tsrcNode = srcNode.output;\n\t\t}\n\t}\n\n\t// make the connection\n\tif (isAudioParam(dstNode)) {\n\t\tsrcNode.connect(dstNode as AudioParam, outputNumber);\n\t} else {\n\t\tsrcNode.connect(dstNode, outputNumber, inputNumber);\n\t}\n}\n\n/**\n * Disconnect a node from all nodes or optionally include a destination node and input/output channels.\n * @param srcNode The source node\n * @param dstNode The destination node\n * @param outputNumber The output channel of the srcNode\n * @param inputNumber The input channel of the dstNode\n */\nexport function disconnect(\n\tsrcNode: OutputNode,\n\tdstNode?: InputNode,\n\toutputNumber = 0,\n\tinputNumber = 0\n): void {\n\t// resolve the destination node\n\tif (isDefined(dstNode)) {\n\t\twhile (dstNode instanceof ToneAudioNode) {\n\t\t\tdstNode = dstNode.input;\n\t\t}\n\t}\n\n\t// resolve the src node\n\twhile (!isAudioNode(srcNode)) {\n\t\tif (isDefined(srcNode.output)) {\n\t\t\tsrcNode = srcNode.output;\n\t\t}\n\t}\n\n\tif (isAudioParam(dstNode)) {\n\t\tsrcNode.disconnect(dstNode, outputNumber);\n\t} else if (isAudioNode(dstNode)) {\n\t\tsrcNode.disconnect(dstNode, outputNumber, inputNumber);\n\t} else {\n\t\tsrcNode.disconnect();\n\t}\n}\n\n/**\n * Connect the output of one or more source nodes to a single destination node\n * @param nodes One or more source nodes followed by one destination node\n * @example\n * const player = new Tone.Player(\"https://tonejs.github.io/audio/drum-samples/conga-rhythm.mp3\");\n * const player1 = new Tone.Player(\"https://tonejs.github.io/audio/drum-samples/conga-rhythm.mp3\");\n * const filter = new Tone.Filter(\"G5\").toDestination();\n * // connect nodes to a common destination\n * Tone.fanIn(player, player1, filter);\n */\nexport function fanIn(...nodes: OutputNode[]): void {\n\tconst dstNode = nodes.pop();\n\n\tif (isDefined(dstNode)) {\n\t\tnodes.forEach((node) => connect(node, dstNode));\n\t}\n}\n","import { Param } from \"../context/Param.js\";\nimport { UnitMap, UnitName } from \"../type/Units.js\";\nimport { optionsFromArguments } from \"../util/Defaults.js\";\nimport { readOnly } from \"../util/Interface.js\";\nimport { ToneAudioNode, ToneAudioNodeOptions } from \"./ToneAudioNode.js\";\n\ninterface GainOptions<TypeName extends UnitName> extends ToneAudioNodeOptions {\n\tgain: UnitMap[TypeName];\n\tunits: TypeName;\n\tconvert: boolean;\n\tminValue?: number;\n\tmaxValue?: number;\n}\n\n/**\n * A thin wrapper around the Native Web Audio GainNode.\n * The GainNode is a basic building block of the Web Audio\n * API and is useful for routing audio and adjusting gains.\n * @category Core\n * @example\n * return Tone.Offline(() => {\n * \tconst gainNode = new Tone.Gain(0).toDestination();\n * \tconst osc = new Tone.Oscillator(30).connect(gainNode).start();\n * \tgainNode.gain.rampTo(1, 0.1);\n * \tgainNode.gain.rampTo(0, 0.4, 0.2);\n * }, 0.7, 1);\n */\nexport class Gain<\n\tTypeName extends \"gain\" | \"decibels\" | \"normalRange\" = \"gain\",\n> extends ToneAudioNode<GainOptions<TypeName>> {\n\treadonly name: string = \"Gain\";\n\n\t/**\n\t * The gain parameter of the gain node.\n\t * @example\n\t * const gainNode = new Tone.Gain(0).toDestination();\n\t * const osc = new Tone.Oscillator().connect(gainNode).start();\n\t * gainNode.gain.rampTo(1, 0.1);\n\t * gainNode.gain.rampTo(0, 2, \"+0.5\");\n\t */\n\treadonly gain: Param<TypeName>;\n\n\t/**\n\t * The wrapped GainNode.\n\t */\n\tprivate _gainNode: GainNode = this.context.createGain();\n\n\t// input = output\n\treadonly input: GainNode = this._gainNode;\n\treadonly output: GainNode = this._gainNode;\n\n\t/**\n\t * @param gain The initial gain of the GainNode\n\t * @param units The units of the gain parameter.\n\t */\n\tconstructor(gain?: UnitMap[TypeName], units?: TypeName);\n\tconstructor(options?: Partial<GainOptions<TypeName>>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(Gain.getDefaults(), arguments, [\n\t\t\t\"gain\",\n\t\t\t\"units\",\n\t\t]);\n\t\tsuper(options);\n\n\t\tthis.gain = new Param({\n\t\t\tcontext: this.context,\n\t\t\tconvert: options.convert,\n\t\t\tparam: this._gainNode.gain,\n\t\t\tunits: options.units,\n\t\t\tvalue: options.gain,\n\t\t\tminValue: options.minValue,\n\t\t\tmaxValue: options.maxValue,\n\t\t});\n\t\treadOnly(this, \"gain\");\n\t}\n\n\tstatic getDefaults(): GainOptions<any> {\n\t\treturn Object.assign(ToneAudioNode.getDefaults(), {\n\t\t\tconvert: true,\n\t\t\tgain: 1,\n\t\t\tunits: \"gain\",\n\t\t});\n\t}\n\n\t/**\n\t * Clean up.\n\t */\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis._gainNode.disconnect();\n\t\tthis.gain.dispose();\n\t\treturn this;\n\t}\n}\n","import { Gain } from \"../core/context/Gain.js\";\nimport {\n\tToneAudioNode,\n\tToneAudioNodeOptions,\n} from \"../core/context/ToneAudioNode.js\";\nimport { GainFactor, Seconds, Time } from \"../core/type/Units.js\";\nimport { noOp } from \"../core/util/Interface.js\";\nimport { assert } from \"../core/util/Debug.js\";\nimport { BasicPlaybackState } from \"../core/util/StateTimeline.js\";\n\nexport type OneShotSourceCurve = \"linear\" | \"exponential\";\n\ntype onEndedCallback = (source: OneShotSource<any>) => void;\n\nexport interface OneShotSourceOptions extends ToneAudioNodeOptions {\n\tonended: onEndedCallback;\n\tfadeIn: Time;\n\tfadeOut: Time;\n\tcurve: OneShotSourceCurve;\n}\n\n/**\n * Base class for fire-and-forget nodes\n */\nexport abstract class OneShotSource<\n\tOptions extends ToneAudioNodeOptions,\n> extends ToneAudioNode<Options> {\n\t/**\n\t * The callback to invoke after the\n\t * source is done playing.\n\t */\n\tonended: onEndedCallback = noOp;\n\n\t/**\n\t * Sources do not have input nodes\n\t */\n\tinput: undefined;\n\n\t/**\n\t * The start time\n\t */\n\tprotected _startTime = -1;\n\n\t/**\n\t * The stop time\n\t */\n\tprotected _stopTime = -1;\n\n\t/**\n\t * The id of the timeout\n\t */\n\tprivate _timeout = -1;\n\n\t/**\n\t * The public output node\n\t */\n\toutput: Gain = new Gain({\n\t\tcontext: this.context,\n\t\tgain: 0,\n\t});\n\n\t/**\n\t * The output gain node.\n\t */\n\tprotected _gainNode = this.output;\n\n\t/**\n\t * The fadeIn time of the amplitude envelope.\n\t */\n\tprotected _fadeIn: Time;\n\n\t/**\n\t * The fadeOut time of the amplitude envelope.\n\t */\n\tprotected _fadeOut: Time;\n\n\t/**\n\t * The curve applied to the fades, either \"linear\" or \"exponential\"\n\t */\n\tprotected _curve: OneShotSourceCurve;\n\n\tconstructor(options: OneShotSourceOptions) {\n\t\tsuper(options);\n\n\t\tthis._fadeIn = options.fadeIn;\n\t\tthis._fadeOut = options.fadeOut;\n\t\tthis._curve = options.curve;\n\t\tthis.onended = options.onended;\n\t}\n\n\tstatic getDefaults(): OneShotSourceOptions {\n\t\treturn Object.assign(ToneAudioNode.getDefaults(), {\n\t\t\tcurve: \"linear\" as OneShotSourceCurve,\n\t\t\tfadeIn: 0,\n\t\t\tfadeOut: 0,\n\t\t\tonended: noOp,\n\t\t});\n\t}\n\n\t/**\n\t * Stop the source node\n\t */\n\tprotected abstract _stopSource(time: Seconds): void;\n\n\t/**\n\t * Start the source node at the given time\n\t * @param time When to start the node\n\t */\n\tprotected abstract start(time?: Time): this;\n\t/**\n\t * Start the source at the given time\n\t * @param time When to start the source\n\t */\n\tprotected _startGain(time: Seconds, gain: GainFactor = 1): this {\n\t\tassert(\n\t\t\tthis._startTime === -1,\n\t\t\t\"Source cannot be started more than once\"\n\t\t);\n\t\t// apply a fade in envelope\n\t\tconst fadeInTime = this.toSeconds(this._fadeIn);\n\n\t\t// record the start time\n\t\tthis._startTime = time + fadeInTime;\n\t\tthis._startTime = Math.max(this._startTime, this.context.currentTime);\n\n\t\t// schedule the envelope\n\t\tif (fadeInTime > 0) {\n\t\t\tthis._gainNode.gain.setValueAtTime(0, time);\n\t\t\tif (this._curve === \"linear\") {\n\t\t\t\tthis._gainNode.gain.linearRampToValueAtTime(\n\t\t\t\t\tgain,\n\t\t\t\t\ttime + fadeInTime\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tthis._gainNode.gain.exponentialApproachValueAtTime(\n\t\t\t\t\tgain,\n\t\t\t\t\ttime,\n\t\t\t\t\tfadeInTime\n\t\t\t\t);\n\t\t\t}\n\t\t} else {\n\t\t\tthis._gainNode.gain.setValueAtTime(gain, time);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Stop the source node at the given time.\n\t * @param time When to stop the source\n\t */\n\tstop(time?: Time): this {\n\t\tthis.log(\"stop\", time);\n\t\tthis._stopGain(this.toSeconds(time));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Stop the source at the given time\n\t * @param time When to stop the source\n\t */\n\tprotected _stopGain(time: Seconds): this {\n\t\tassert(this._startTime !== -1, \"'start' must be called before 'stop'\");\n\t\t// cancel the previous stop\n\t\tthis.cancelStop();\n\n\t\t// the fadeOut time\n\t\tconst fadeOutTime = this.toSeconds(this._fadeOut);\n\n\t\t// schedule the stop callback\n\t\tthis._stopTime = this.toSeconds(time) + fadeOutTime;\n\t\tthis._stopTime = Math.max(this._stopTime, this.now());\n\t\tif (fadeOutTime > 0) {\n\t\t\t// start the fade out curve at the given time\n\t\t\tif (this._curve === \"linear\") {\n\t\t\t\tthis._gainNode.gain.linearRampTo(0, fadeOutTime, time);\n\t\t\t} else {\n\t\t\t\tthis._gainNode.gain.targetRampTo(0, fadeOutTime, time);\n\t\t\t}\n\t\t} else {\n\t\t\t// stop any ongoing ramps, and set the value to 0\n\t\t\tthis._gainNode.gain.cancelAndHoldAtTime(time);\n\t\t\tthis._gainNode.gain.setValueAtTime(0, time);\n\t\t}\n\t\tthis.context.clearTimeout(this._timeout);\n\t\tthis._timeout = this.context.setTimeout(() => {\n\t\t\t// allow additional time for the exponential curve to fully decay\n\t\t\tconst additionalTail =\n\t\t\t\tthis._curve === \"exponential\" ? fadeOutTime * 2 : 0;\n\t\t\tthis._stopSource(this.now() + additionalTail);\n\t\t\tthis._onended();\n\t\t}, this._stopTime - this.context.currentTime);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Invoke the onended callback\n\t */\n\tprotected _onended(): void {\n\t\tif (this.onended === noOp) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.onended(this);\n\t\t// overwrite onended to make sure it only is called once\n\t\tthis.onended = noOp;\n\t\t// dispose when it's ended to free up for garbage collection only in the online context\n\t\tif (!this.context.isOffline) {\n\t\t\tconst disposeCallback = () => this.dispose();\n\t\t\tif (typeof requestIdleCallback !== \"undefined\") {\n\t\t\t\trequestIdleCallback(disposeCallback);\n\t\t\t} else {\n\t\t\t\tsetTimeout(disposeCallback, 10);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Get the playback state at the given time\n\t */\n\tgetStateAtTime = function (time: Time): BasicPlaybackState {\n\t\tconst computedTime = this.toSeconds(time);\n\t\tif (\n\t\t\tthis._startTime !== -1 &&\n\t\t\tcomputedTime >= this._startTime &&\n\t\t\t(this._stopTime === -1 || computedTime <= this._stopTime)\n\t\t) {\n\t\t\treturn \"started\";\n\t\t} else {\n\t\t\treturn \"stopped\";\n\t\t}\n\t};\n\n\t/**\n\t * Get the playback state at the current time\n\t */\n\tget state(): BasicPlaybackState {\n\t\treturn this.getStateAtTime(this.now());\n\t}\n\n\t/**\n\t * Cancel a scheduled stop event\n\t */\n\tcancelStop(): this {\n\t\tthis.log(\"cancelStop\");\n\t\tassert(this._startTime !== -1, \"Source is not started\");\n\t\t// cancel the stop envelope\n\t\tthis._gainNode.gain.cancelScheduledValues(\n\t\t\tthis._startTime + this.sampleTime\n\t\t);\n\t\tthis.context.clearTimeout(this._timeout);\n\t\tthis._stopTime = -1;\n\t\treturn this;\n\t}\n\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis._gainNode.dispose();\n\t\tthis.onended = noOp;\n\t\treturn this;\n\t}\n}\n","import { connect } from \"../core/context/ToneAudioNode.js\";\nimport { Param } from \"../core/context/Param.js\";\nimport { Seconds, Time, UnitMap, UnitName } from \"../core/type/Units.js\";\nimport { optionsFromArguments } from \"../core/util/Defaults.js\";\nimport {\n\tOneShotSource,\n\tOneShotSourceOptions,\n} from \"../source/OneShotSource.js\";\n\nexport interface ToneConstantSourceOptions<TypeName extends UnitName>\n\textends OneShotSourceOptions {\n\tconvert: boolean;\n\toffset: UnitMap[TypeName];\n\tunits: TypeName;\n\tminValue?: number;\n\tmaxValue?: number;\n}\n\n/**\n * Wrapper around the native fire-and-forget ConstantSource.\n * Adds the ability to reschedule the stop method.\n * @category Signal\n */\nexport class ToneConstantSource<\n\tTypeName extends UnitName = \"number\",\n> extends OneShotSource<ToneConstantSourceOptions<TypeName>> {\n\treadonly name: string = \"ToneConstantSource\";\n\n\t/**\n\t * The signal generator\n\t */\n\tprivate _source = this.context.createConstantSource();\n\n\t/**\n\t * The offset of the signal generator\n\t */\n\treadonly offset: Param<TypeName>;\n\n\t/**\n\t * @param offset The offset value\n\t */\n\tconstructor(offset: UnitMap[TypeName]);\n\tconstructor(options?: Partial<ToneConstantSourceOptions<TypeName>>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(\n\t\t\tToneConstantSource.getDefaults(),\n\t\t\targuments,\n\t\t\t[\"offset\"]\n\t\t);\n\t\tsuper(options);\n\n\t\tconnect(this._source, this._gainNode);\n\n\t\tthis.offset = new Param({\n\t\t\tcontext: this.context,\n\t\t\tconvert: options.convert,\n\t\t\tparam: this._source.offset,\n\t\t\tunits: options.units,\n\t\t\tvalue: options.offset,\n\t\t\tminValue: options.minValue,\n\t\t\tmaxValue: options.maxValue,\n\t\t});\n\t}\n\n\tstatic getDefaults(): ToneConstantSourceOptions<any> {\n\t\treturn Object.assign(OneShotSource.getDefaults(), {\n\t\t\tconvert: true,\n\t\t\toffset: 1,\n\t\t\tunits: \"number\" as UnitName,\n\t\t});\n\t}\n\n\t/**\n\t * Start the source node at the given time\n\t * @param time When to start the source\n\t */\n\tstart(time?: Time): this {\n\t\tconst computedTime = this.toSeconds(time);\n\t\tthis.log(\"start\", computedTime);\n\t\tthis._startGain(computedTime);\n\t\tthis._source.start(computedTime);\n\t\treturn this;\n\t}\n\n\tprotected _stopSource(time?: Seconds): void {\n\t\tthis._source.stop(time);\n\t}\n\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tif (this.state === \"started\") {\n\t\t\tthis.stop();\n\t\t}\n\t\tthis._source.disconnect();\n\t\tthis.offset.dispose();\n\t\treturn this;\n\t}\n}\n","import { AbstractParam } from \"../core/context/AbstractParam.js\";\nimport { Param } from \"../core/context/Param.js\";\nimport {\n\tInputNode,\n\tOutputNode,\n\tToneAudioNode,\n\tToneAudioNodeOptions,\n} from \"../core/context/ToneAudioNode.js\";\nimport { connect } from \"../core/context/ToneAudioNode.js\";\nimport { Time, UnitMap, UnitName } from \"../core/type/Units.js\";\nimport { isAudioParam } from \"../core/util/AdvancedTypeCheck.js\";\nimport { optionsFromArguments } from \"../core/util/Defaults.js\";\nimport { ToneConstantSource } from \"./ToneConstantSource.js\";\n\nexport interface SignalOptions<TypeName extends UnitName>\n\textends ToneAudioNodeOptions {\n\tvalue: UnitMap[TypeName];\n\tunits: TypeName;\n\tconvert: boolean;\n\tminValue?: number;\n\tmaxValue?: number;\n}\n\n/**\n * A signal is an audio-rate value. Tone.Signal is a core component of the library.\n * Unlike a number, Signals can be scheduled with sample-level accuracy. Tone.Signal\n * has all of the methods available to native Web Audio\n * [AudioParam](http://webaudio.github.io/web-audio-api/#the-audioparam-interface)\n * as well as additional conveniences. Read more about working with signals\n * [here](https://github.com/Tonejs/Tone.js/wiki/Signals).\n *\n * @example\n * const osc = new Tone.Oscillator().toDestination().start();\n * // a scheduleable signal which can be connected to control an AudioParam or another Signal\n * const signal = new Tone.Signal({\n * \tvalue: \"C4\",\n * \tunits: \"frequency\"\n * }).connect(osc.frequency);\n * // the scheduled ramp controls the connected signal\n * signal.rampTo(\"C2\", 4, \"+0.5\");\n * @category Signal\n */\nexport class Signal<TypeName extends UnitName = \"number\">\n\textends ToneAudioNode<SignalOptions<any>>\n\timplements AbstractParam<TypeName>\n{\n\treadonly name: string = \"Signal\";\n\n\t/**\n\t * Indicates if the value should be overridden on connection.\n\t */\n\treadonly override: boolean = true;\n\n\t/**\n\t * The constant source node which generates the signal\n\t */\n\tprotected _constantSource: ToneConstantSource<TypeName>;\n\treadonly output: OutputNode;\n\tprotected _param: Param<TypeName>;\n\treadonly input: InputNode;\n\n\t/**\n\t * @param value Initial value of the signal\n\t * @param units The unit name, e.g. \"frequency\"\n\t */\n\tconstructor(value?: UnitMap[TypeName], units?: TypeName);\n\tconstructor(options?: Partial<SignalOptions<TypeName>>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(Signal.getDefaults(), arguments, [\n\t\t\t\"value\",\n\t\t\t\"units\",\n\t\t]) as SignalOptions<TypeName>;\n\t\tsuper(options);\n\n\t\tthis.output = this._constantSource = new ToneConstantSource({\n\t\t\tcontext: this.context,\n\t\t\tconvert: options.convert,\n\t\t\toffset: options.value,\n\t\t\tunits: options.units,\n\t\t\tminValue: options.minValue,\n\t\t\tmaxValue: options.maxValue,\n\t\t});\n\t\tthis._constantSource.start(0);\n\t\tthis.input = this._param = this._constantSource.offset;\n\t}\n\n\tstatic getDefaults(): SignalOptions<any> {\n\t\treturn Object.assign(ToneAudioNode.getDefaults(), {\n\t\t\tconvert: true,\n\t\t\tunits: \"number\" as UnitName,\n\t\t\tvalue: 0,\n\t\t});\n\t}\n\n\tconnect(destination: InputNode, outputNum = 0, inputNum = 0): this {\n\t\t// start it only when connected to something\n\t\tconnectSignal(this, destination, outputNum, inputNum);\n\t\treturn this;\n\t}\n\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis._param.dispose();\n\t\tthis._constantSource.dispose();\n\t\treturn this;\n\t}\n\n\t//-------------------------------------\n\t// ABSTRACT PARAM INTERFACE\n\t// just a proxy for the ConstantSourceNode's offset AudioParam\n\t// all docs are generated from AbstractParam.ts\n\t//-------------------------------------\n\n\tsetValueAtTime(value: UnitMap[TypeName], time: Time): this {\n\t\tthis._param.setValueAtTime(value, time);\n\t\treturn this;\n\t}\n\tgetValueAtTime(time: Time): UnitMap[TypeName] {\n\t\treturn this._param.getValueAtTime(time);\n\t}\n\tsetRampPoint(time: Time): this {\n\t\tthis._param.setRampPoint(time);\n\t\treturn this;\n\t}\n\tlinearRampToValueAtTime(value: UnitMap[TypeName], time: Time): this {\n\t\tthis._param.linearRampToValueAtTime(value, time);\n\t\treturn this;\n\t}\n\texponentialRampToValueAtTime(value: UnitMap[TypeName], time: Time): this {\n\t\tthis._param.exponentialRampToValueAtTime(value, time);\n\t\treturn this;\n\t}\n\texponentialRampTo(\n\t\tvalue: UnitMap[TypeName],\n\t\trampTime: Time,\n\t\tstartTime?: Time\n\t): this {\n\t\tthis._param.exponentialRampTo(value, rampTime, startTime);\n\t\treturn this;\n\t}\n\tlinearRampTo(\n\t\tvalue: UnitMap[TypeName],\n\t\trampTime: Time,\n\t\tstartTime?: Time\n\t): this {\n\t\tthis._param.linearRampTo(value, rampTime, startTime);\n\t\treturn this;\n\t}\n\ttargetRampTo(\n\t\tvalue: UnitMap[TypeName],\n\t\trampTime: Time,\n\t\tstartTime?: Time\n\t): this {\n\t\tthis._param.targetRampTo(value, rampTime, startTime);\n\t\treturn this;\n\t}\n\texponentialApproachValueAtTime(\n\t\tvalue: UnitMap[TypeName],\n\t\ttime: Time,\n\t\trampTime: Time\n\t): this {\n\t\tthis._param.exponentialApproachValueAtTime(value, time, rampTime);\n\t\treturn this;\n\t}\n\tsetTargetAtTime(\n\t\tvalue: UnitMap[TypeName],\n\t\tstartTime: Time,\n\t\ttimeConstant: number\n\t): this {\n\t\tthis._param.setTargetAtTime(value, startTime, timeConstant);\n\t\treturn this;\n\t}\n\tsetValueCurveAtTime(\n\t\tvalues: UnitMap[TypeName][],\n\t\tstartTime: Time,\n\t\tduration: Time,\n\t\tscaling?: number\n\t): this {\n\t\tthis._param.setValueCurveAtTime(values, startTime, duration, scaling);\n\t\treturn this;\n\t}\n\tcancelScheduledValues(time: Time): this {\n\t\tthis._param.cancelScheduledValues(time);\n\t\treturn this;\n\t}\n\tcancelAndHoldAtTime(time: Time): this {\n\t\tthis._param.cancelAndHoldAtTime(time);\n\t\treturn this;\n\t}\n\trampTo(value: UnitMap[TypeName], rampTime: Time, startTime?: Time): this {\n\t\tthis._param.rampTo(value, rampTime, startTime);\n\t\treturn this;\n\t}\n\n\tget value(): UnitMap[TypeName] {\n\t\treturn this._param.value;\n\t}\n\tset value(value: UnitMap[TypeName]) {\n\t\tthis._param.value = value;\n\t}\n\n\tget convert(): boolean {\n\t\treturn this._param.convert;\n\t}\n\tset convert(convert: boolean) {\n\t\tthis._param.convert = convert;\n\t}\n\n\tget units(): UnitName {\n\t\treturn this._param.units;\n\t}\n\n\tget overridden(): boolean {\n\t\treturn this._param.overridden;\n\t}\n\tset overridden(overridden: boolean) {\n\t\tthis._param.overridden = overridden;\n\t}\n\n\tget maxValue(): number {\n\t\treturn this._param.maxValue;\n\t}\n\tget minValue(): number {\n\t\treturn this._param.minValue;\n\t}\n\n\t/**\n\t * @see {@link Param.apply}.\n\t */\n\tapply(param: Param | AudioParam): this {\n\t\tthis._param.apply(param);\n\t\treturn this;\n\t}\n}\n\n/**\n * When connecting from a signal, it's necessary to zero out the node destination\n * node if that node is also a signal. If the destination is not 0, then the values\n * will be summed. This method insures that the output of the destination signal will\n * be the same as the source signal, making the destination signal a pass through node.\n * @param signal The output signal to connect from\n * @param destination the destination to connect to\n * @param outputNum the optional output number\n * @param inputNum the input number\n */\nexport function connectSignal(\n\tsignal: OutputNode,\n\tdestination: InputNode,\n\toutputNum?: number,\n\tinputNum?: number\n): void {\n\tif (\n\t\tdestination instanceof Param ||\n\t\tisAudioParam(destination) ||\n\t\t(destination instanceof Signal && destination.override)\n\t) {\n\t\t// cancel changes\n\t\tdestination.cancelScheduledValues(0);\n\t\t// reset the value\n\t\tdestination.setValueAtTime(0, 0);\n\t\t// mark the value as overridden\n\t\tif (destination instanceof Signal) {\n\t\t\tdestination.overridden = true;\n\t\t}\n\t}\n\tconnect(signal, destination, outputNum, inputNum);\n}\n","import { AutomationEvent, Param, ParamOptions } from \"../context/Param.js\";\nimport { Seconds, Ticks, Time, UnitMap, UnitName } from \"../type/Units.js\";\nimport { optionsFromArguments } from \"../util/Defaults.js\";\nimport { Timeline } from \"../util/Timeline.js\";\nimport { isUndef } from \"../util/TypeCheck.js\";\n\ntype TickAutomationEvent = AutomationEvent & {\n\tticks: number;\n};\n\ninterface TickParamOptions<TypeName extends UnitName>\n\textends ParamOptions<TypeName> {\n\tmultiplier: number;\n}\n\n/**\n * A Param class just for computing ticks. Similar to the {@link Param} class,\n * but offers conversion to BPM values as well as ability to compute tick\n * duration and elapsed ticks\n */\nexport class TickParam<\n\tTypeName extends \"hertz\" | \"bpm\",\n> extends Param<TypeName> {\n\treadonly name: string = \"TickParam\";\n\n\t/**\n\t * The timeline which tracks all of the automations.\n\t */\n\tprotected _events: Timeline<TickAutomationEvent> = new Timeline(Infinity);\n\n\t/**\n\t * The internal holder for the multiplier value\n\t */\n\tprivate _multiplier = 1;\n\n\t/**\n\t * @param param The AudioParam to wrap\n\t * @param units The unit name\n\t * @param convert Whether or not to convert the value to the target units\n\t */\n\t/**\n\t * @param value The initial value of the signal\n\t */\n\tconstructor(value?: number);\n\tconstructor(options: Partial<TickParamOptions<TypeName>>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(\n\t\t\tTickParam.getDefaults(),\n\t\t\targuments,\n\t\t\t[\"value\"]\n\t\t);\n\t\tsuper(options);\n\n\t\t// set the multiplier\n\t\tthis._multiplier = options.multiplier;\n\n\t\t// clear the ticks from the beginning\n\t\tthis._events.cancel(0);\n\t\t// set an initial event\n\t\tthis._events.add({\n\t\t\tticks: 0,\n\t\t\ttime: 0,\n\t\t\ttype: \"setValueAtTime\",\n\t\t\tvalue: this._fromType(options.value),\n\t\t});\n\t\tthis.setValueAtTime(options.value, 0);\n\t}\n\n\tstatic getDefaults(): TickParamOptions<any> {\n\t\treturn Object.assign(Param.getDefaults(), {\n\t\t\tmultiplier: 1,\n\t\t\tunits: \"hertz\",\n\t\t\tvalue: 1,\n\t\t});\n\t}\n\n\tsetTargetAtTime(\n\t\tvalue: UnitMap[TypeName],\n\t\ttime: Time,\n\t\tconstant: number\n\t): this {\n\t\t// approximate it with multiple linear ramps\n\t\ttime = this.toSeconds(time);\n\t\tthis.setRampPoint(time);\n\t\tconst computedValue = this._fromType(value);\n\n\t\t// start from previously scheduled value\n\t\tconst prevEvent = this._events.get(time) as TickAutomationEvent;\n\t\tconst segments = Math.round(Math.max(1 / constant, 1));\n\t\tfor (let i = 0; i <= segments; i++) {\n\t\t\tconst segTime = constant * i + time;\n\t\t\tconst rampVal = this._exponentialApproach(\n\t\t\t\tprevEvent.time,\n\t\t\t\tprevEvent.value,\n\t\t\t\tcomputedValue,\n\t\t\t\tconstant,\n\t\t\t\tsegTime\n\t\t\t);\n\t\t\tthis.linearRampToValueAtTime(this._toType(rampVal), segTime);\n\t\t}\n\t\treturn this;\n\t}\n\n\tsetValueAtTime(value: UnitMap[TypeName], time: Time): this {\n\t\tconst computedTime = this.toSeconds(time);\n\t\tsuper.setValueAtTime(value, time);\n\t\tconst event = this._events.get(computedTime) as TickAutomationEvent;\n\t\tconst previousEvent = this._events.previousEvent(event);\n\t\tconst ticksUntilTime = this._getTicksUntilEvent(\n\t\t\tpreviousEvent,\n\t\t\tcomputedTime\n\t\t);\n\t\tevent.ticks = Math.max(ticksUntilTime, 0);\n\t\treturn this;\n\t}\n\n\tlinearRampToValueAtTime(value: UnitMap[TypeName], time: Time): this {\n\t\tconst computedTime = this.toSeconds(time);\n\t\tsuper.linearRampToValueAtTime(value, time);\n\t\tconst event = this._events.get(computedTime) as TickAutomationEvent;\n\t\tconst previousEvent = this._events.previousEvent(event);\n\t\tconst ticksUntilTime = this._getTicksUntilEvent(\n\t\t\tpreviousEvent,\n\t\t\tcomputedTime\n\t\t);\n\t\tevent.ticks = Math.max(ticksUntilTime, 0);\n\t\treturn this;\n\t}\n\n\texponentialRampToValueAtTime(value: UnitMap[TypeName], time: Time): this {\n\t\t// aproximate it with multiple linear ramps\n\t\ttime = this.toSeconds(time);\n\t\tconst computedVal = this._fromType(value);\n\n\t\t// start from previously scheduled value\n\t\tconst prevEvent = this._events.get(time) as TickAutomationEvent;\n\t\t// approx 10 segments per second\n\t\tconst segments = Math.round(Math.max((time - prevEvent.time) * 10, 1));\n\t\tconst segmentDur = (time - prevEvent.time) / segments;\n\t\tfor (let i = 0; i <= segments; i++) {\n\t\t\tconst segTime = segmentDur * i + prevEvent.time;\n\t\t\tconst rampVal = this._exponentialInterpolate(\n\t\t\t\tprevEvent.time,\n\t\t\t\tprevEvent.value,\n\t\t\t\ttime,\n\t\t\t\tcomputedVal,\n\t\t\t\tsegTime\n\t\t\t);\n\t\t\tthis.linearRampToValueAtTime(this._toType(rampVal), segTime);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Returns the tick value at the time. Takes into account\n\t * any automation curves scheduled on the signal.\n\t * @param event The time to get the tick count at\n\t * @return The number of ticks which have elapsed at the time given any automations.\n\t */\n\tprivate _getTicksUntilEvent(\n\t\tevent: TickAutomationEvent | null,\n\t\ttime: number\n\t): Ticks {\n\t\tif (event === null) {\n\t\t\tevent = {\n\t\t\t\tticks: 0,\n\t\t\t\ttime: 0,\n\t\t\t\ttype: \"setValueAtTime\",\n\t\t\t\tvalue: 0,\n\t\t\t};\n\t\t} else if (isUndef(event.ticks)) {\n\t\t\tconst previousEvent = this._events.previousEvent(event);\n\t\t\tevent.ticks = this._getTicksUntilEvent(previousEvent, event.time);\n\t\t}\n\t\tconst val0 = this._fromType(this.getValueAtTime(event.time));\n\t\tlet val1 = this._fromType(this.getValueAtTime(time));\n\t\t// if it's right on the line, take the previous value\n\t\tconst onTheLineEvent = this._events.get(time);\n\t\tif (\n\t\t\tonTheLineEvent &&\n\t\t\tonTheLineEvent.time === time &&\n\t\t\tonTheLineEvent.type === \"setValueAtTime\"\n\t\t) {\n\t\t\tval1 = this._fromType(this.getValueAtTime(time - this.sampleTime));\n\t\t}\n\t\treturn 0.5 * (time - event.time) * (val0 + val1) + event.ticks;\n\t}\n\n\t/**\n\t * Returns the tick value at the time. Takes into account\n\t * any automation curves scheduled on the signal.\n\t * @param time The time to get the tick count at\n\t * @return The number of ticks which have elapsed at the time given any automations.\n\t */\n\tgetTicksAtTime(time: Time): Ticks {\n\t\tconst computedTime = this.toSeconds(time);\n\t\tconst event = this._events.get(computedTime);\n\t\treturn Math.max(this._getTicksUntilEvent(event, computedTime), 0);\n\t}\n\n\t/**\n\t * Return the elapsed time of the number of ticks from the given time\n\t * @param ticks The number of ticks to calculate\n\t * @param time The time to get the next tick from\n\t * @return The duration of the number of ticks from the given time in seconds\n\t */\n\tgetDurationOfTicks(ticks: Ticks, time: Time): Seconds {\n\t\tconst computedTime = this.toSeconds(time);\n\t\tconst currentTick = this.getTicksAtTime(time);\n\t\treturn this.getTimeOfTick(currentTick + ticks) - computedTime;\n\t}\n\n\t/**\n\t * Given a tick, returns the time that tick occurs at.\n\t * @return The time that the tick occurs.\n\t */\n\tgetTimeOfTick(tick: Ticks): Seconds {\n\t\tconst before = this._events.get(tick, \"ticks\");\n\t\tconst after = this._events.getAfter(tick, \"ticks\");\n\t\tif (before && before.ticks === tick) {\n\t\t\treturn before.time;\n\t\t} else if (\n\t\t\tbefore &&\n\t\t\tafter &&\n\t\t\tafter.type === \"linearRampToValueAtTime\" &&\n\t\t\tbefore.value !== after.value\n\t\t) {\n\t\t\tconst val0 = this._fromType(this.getValueAtTime(before.time));\n\t\t\tconst val1 = this._fromType(this.getValueAtTime(after.time));\n\t\t\tconst delta = (val1 - val0) / (after.time - before.time);\n\t\t\tconst k = Math.sqrt(\n\t\t\t\tMath.pow(val0, 2) - 2 * delta * (before.ticks - tick)\n\t\t\t);\n\t\t\tconst sol1 = (-val0 + k) / delta;\n\t\t\tconst sol2 = (-val0 - k) / delta;\n\t\t\treturn (sol1 > 0 ? sol1 : sol2) + before.time;\n\t\t} else if (before) {\n\t\t\tif (before.value === 0) {\n\t\t\t\treturn Infinity;\n\t\t\t} else {\n\t\t\t\treturn before.time + (tick - before.ticks) / before.value;\n\t\t\t}\n\t\t} else {\n\t\t\treturn tick / this._initialValue;\n\t\t}\n\t}\n\n\t/**\n\t * Convert some number of ticks their the duration in seconds accounting\n\t * for any automation curves starting at the given time.\n\t * @param ticks The number of ticks to convert to seconds.\n\t * @param when When along the automation timeline to convert the ticks.\n\t * @return The duration in seconds of the ticks.\n\t */\n\tticksToTime(ticks: Ticks, when: Time): Seconds {\n\t\treturn this.getDurationOfTicks(ticks, when);\n\t}\n\n\t/**\n\t * The inverse of {@link ticksToTime}. Convert a duration in\n\t * seconds to the corresponding number of ticks accounting for any\n\t * automation curves starting at the given time.\n\t * @param duration The time interval to convert to ticks.\n\t * @param when When along the automation timeline to convert the ticks.\n\t * @return The duration in ticks.\n\t */\n\ttimeToTicks(duration: Time, when: Time): Ticks {\n\t\tconst computedTime = this.toSeconds(when);\n\t\tconst computedDuration = this.toSeconds(duration);\n\t\tconst startTicks = this.getTicksAtTime(computedTime);\n\t\tconst endTicks = this.getTicksAtTime(computedTime + computedDuration);\n\t\treturn endTicks - startTicks;\n\t}\n\n\t/**\n\t * Convert from the type when the unit value is BPM\n\t */\n\tprotected _fromType(val: UnitMap[TypeName]): number {\n\t\tif (this.units === \"bpm\" && this.multiplier) {\n\t\t\treturn 1 / (60 / val / this.multiplier);\n\t\t} else {\n\t\t\treturn super._fromType(val);\n\t\t}\n\t}\n\n\t/**\n\t * Special case of type conversion where the units === \"bpm\"\n\t */\n\tprotected _toType(val: number): UnitMap[TypeName] {\n\t\tif (this.units === \"bpm\" && this.multiplier) {\n\t\t\treturn ((val / this.multiplier) * 60) as UnitMap[TypeName];\n\t\t} else {\n\t\t\treturn super._toType(val);\n\t\t}\n\t}\n\t/**\n\t * A multiplier on the bpm value. Useful for setting a PPQ relative to the base frequency value.\n\t */\n\tget multiplier(): number {\n\t\treturn this._multiplier;\n\t}\n\tset multiplier(m: number) {\n\t\t// get and reset the current value with the new multiplier\n\t\t// might be necessary to clear all the previous values\n\t\tconst currentVal = this.value;\n\t\tthis._multiplier = m;\n\t\tthis.cancelScheduledValues(0);\n\t\tthis.setValueAtTime(currentVal, 0);\n\t}\n}\n","import { Signal, SignalOptions } from \"../../signal/Signal.js\";\nimport { InputNode } from \"../context/ToneAudioNode.js\";\nimport { Seconds, Ticks, Time, UnitMap, UnitName } from \"../type/Units.js\";\nimport { optionsFromArguments } from \"../util/Defaults.js\";\nimport { TickParam } from \"./TickParam.js\";\n\ninterface TickSignalOptions<TypeName extends UnitName>\n\textends SignalOptions<TypeName> {\n\tvalue: UnitMap[TypeName];\n\tmultiplier: number;\n}\n\n/**\n * TickSignal extends Tone.Signal, but adds the capability\n * to calculate the number of elapsed ticks. exponential and target curves\n * are approximated with multiple linear ramps.\n *\n * Thank you Bruno Dias, H. Sofia Pinto, and David M. Matos,\n * for your [WAC paper](https://smartech.gatech.edu/bitstream/handle/1853/54588/WAC2016-49.pdf)\n * describing integrating timing functions for tempo calculations.\n */\nexport class TickSignal<\n\tTypeName extends \"hertz\" | \"bpm\",\n> extends Signal<TypeName> {\n\treadonly name: string = \"TickSignal\";\n\n\t/**\n\t * The param which controls the output signal value\n\t */\n\tprotected _param: TickParam<TypeName>;\n\treadonly input: InputNode;\n\n\t/**\n\t * @param value The initial value of the signal\n\t */\n\tconstructor(value?: UnitMap[TypeName]);\n\tconstructor(options: Partial<TickSignalOptions<TypeName>>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(\n\t\t\tTickSignal.getDefaults(),\n\t\t\targuments,\n\t\t\t[\"value\"]\n\t\t);\n\t\tsuper(options);\n\n\t\tthis.input = this._param = new TickParam({\n\t\t\tcontext: this.context,\n\t\t\tconvert: options.convert,\n\t\t\tmultiplier: options.multiplier,\n\t\t\tparam: this._constantSource.offset,\n\t\t\tunits: options.units,\n\t\t\tvalue: options.value,\n\t\t});\n\t}\n\n\tstatic getDefaults(): TickSignalOptions<any> {\n\t\treturn Object.assign(Signal.getDefaults(), {\n\t\t\tmultiplier: 1,\n\t\t\tunits: \"hertz\",\n\t\t\tvalue: 1,\n\t\t});\n\t}\n\n\tticksToTime(ticks: Ticks, when: Time): Seconds {\n\t\treturn this._param.ticksToTime(ticks, when);\n\t}\n\n\ttimeToTicks(duration: Time, when: Time): Ticks {\n\t\treturn this._param.timeToTicks(duration, when);\n\t}\n\n\tgetTimeOfTick(tick: Ticks): Seconds {\n\t\treturn this._param.getTimeOfTick(tick);\n\t}\n\n\tgetDurationOfTicks(ticks: Ticks, time: Time): Seconds {\n\t\treturn this._param.getDurationOfTicks(ticks, time);\n\t}\n\n\tgetTicksAtTime(time: Time): Ticks {\n\t\treturn this._param.getTicksAtTime(time);\n\t}\n\n\t/**\n\t * A multiplier on the bpm value. Useful for setting a PPQ relative to the base frequency value.\n\t */\n\tget multiplier(): number {\n\t\treturn this._param.multiplier;\n\t}\n\tset multiplier(m: number) {\n\t\tthis._param.multiplier = m;\n\t}\n\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis._param.dispose();\n\t\treturn this;\n\t}\n}\n","import {\n\tToneWithContext,\n\tToneWithContextOptions,\n} from \"../context/ToneWithContext.js\";\nimport { Seconds, Ticks, Time } from \"../type/Units.js\";\nimport { optionsFromArguments } from \"../util/Defaults.js\";\nimport { readOnly } from \"../util/Interface.js\";\nimport {\n\tPlaybackState,\n\tStateTimeline,\n\tStateTimelineEvent,\n} from \"../util/StateTimeline.js\";\nimport { Timeline, TimelineEvent } from \"../util/Timeline.js\";\nimport { isDefined } from \"../util/TypeCheck.js\";\nimport { TickSignal } from \"./TickSignal.js\";\nimport { EQ } from \"../util/Math.js\";\n\ninterface TickSourceOptions extends ToneWithContextOptions {\n\tfrequency: number;\n\tunits: \"bpm\" | \"hertz\";\n}\n\ninterface TickSourceOffsetEvent extends TimelineEvent {\n\tticks: number;\n\ttime: number;\n\tseconds: number;\n}\n\ninterface TickSourceTicksAtTimeEvent extends TimelineEvent {\n\tstate: PlaybackState;\n\ttime: number;\n\tticks: number;\n}\n\ninterface TickSourceSecondsAtTimeEvent extends TimelineEvent {\n\tstate: PlaybackState;\n\ttime: number;\n\tseconds: number;\n}\n\n/**\n * Uses [TickSignal](TickSignal) to track elapsed ticks with complex automation curves.\n */\nexport class TickSource<\n\tTypeName extends \"bpm\" | \"hertz\",\n> extends ToneWithContext<TickSourceOptions> {\n\treadonly name: string = \"TickSource\";\n\n\t/**\n\t * The frequency the callback function should be invoked.\n\t */\n\treadonly frequency: TickSignal<TypeName>;\n\n\t/**\n\t * The state timeline\n\t */\n\tprivate _state: StateTimeline = new StateTimeline();\n\n\t/**\n\t * The offset values of the ticks\n\t */\n\tprivate _tickOffset: Timeline<TickSourceOffsetEvent> = new Timeline();\n\n\t/**\n\t * Memoized values of getTicksAtTime at events with state other than \"started\"\n\t */\n\tprivate _ticksAtTime: Timeline<TickSourceTicksAtTimeEvent> =\n\t\tnew Timeline<TickSourceTicksAtTimeEvent>();\n\n\t/**\n\t * Memoized values of getSecondsAtTime at events with state other than \"started\"\n\t */\n\tprivate _secondsAtTime: Timeline<TickSourceSecondsAtTimeEvent> =\n\t\tnew Timeline<TickSourceSecondsAtTimeEvent>();\n\n\t/**\n\t * @param frequency The initial frequency that the signal ticks at\n\t */\n\tconstructor(frequency?: number);\n\tconstructor(options?: Partial<TickSourceOptions>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(\n\t\t\tTickSource.getDefaults(),\n\t\t\targuments,\n\t\t\t[\"frequency\"]\n\t\t);\n\t\tsuper(options);\n\n\t\tthis.frequency = new TickSignal({\n\t\t\tcontext: this.context,\n\t\t\tunits: options.units as TypeName,\n\t\t\tvalue: options.frequency,\n\t\t});\n\t\treadOnly(this, \"frequency\");\n\n\t\t// set the initial state\n\t\tthis._state.setStateAtTime(\"stopped\", 0);\n\t\t// add the first event\n\t\tthis.setTicksAtTime(0, 0);\n\t}\n\n\tstatic getDefaults(): TickSourceOptions {\n\t\treturn Object.assign(\n\t\t\t{\n\t\t\t\tfrequency: 1,\n\t\t\t\tunits: \"hertz\" as const,\n\t\t\t},\n\t\t\tToneWithContext.getDefaults()\n\t\t);\n\t}\n\n\t/**\n\t * Returns the playback state of the source, either \"started\", \"stopped\" or \"paused\".\n\t */\n\tget state(): PlaybackState {\n\t\treturn this.getStateAtTime(this.now());\n\t}\n\n\t/**\n\t * Start the clock at the given time. Optionally pass in an offset\n\t * of where to start the tick counter from.\n\t * @param time The time the clock should start\n\t * @param offset The number of ticks to start the source at\n\t */\n\tstart(time: Time, offset?: Ticks): this {\n\t\tconst computedTime = this.toSeconds(time);\n\t\tif (this._state.getValueAtTime(computedTime) !== \"started\") {\n\t\t\tthis._state.setStateAtTime(\"started\", computedTime);\n\t\t\tif (isDefined(offset)) {\n\t\t\t\tthis.setTicksAtTime(offset, computedTime);\n\t\t\t}\n\t\t\tthis._ticksAtTime.cancel(computedTime);\n\t\t\tthis._secondsAtTime.cancel(computedTime);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Stop the clock. Stopping the clock resets the tick counter to 0.\n\t * @param time The time when the clock should stop.\n\t */\n\tstop(time: Time): this {\n\t\tconst computedTime = this.toSeconds(time);\n\t\t// cancel the previous stop\n\t\tif (this._state.getValueAtTime(computedTime) === \"stopped\") {\n\t\t\tconst event = this._state.get(computedTime);\n\t\t\tif (event && event.time > 0) {\n\t\t\t\tthis._tickOffset.cancel(event.time);\n\t\t\t\tthis._state.cancel(event.time);\n\t\t\t}\n\t\t}\n\t\tthis._state.cancel(computedTime);\n\t\tthis._state.setStateAtTime(\"stopped\", computedTime);\n\t\tthis.setTicksAtTime(0, computedTime);\n\t\tthis._ticksAtTime.cancel(computedTime);\n\t\tthis._secondsAtTime.cancel(computedTime);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Pause the clock. Pausing does not reset the tick counter.\n\t * @param time The time when the clock should stop.\n\t */\n\tpause(time: Time): this {\n\t\tconst computedTime = this.toSeconds(time);\n\t\tif (this._state.getValueAtTime(computedTime) === \"started\") {\n\t\t\tthis._state.setStateAtTime(\"paused\", computedTime);\n\t\t\tthis._ticksAtTime.cancel(computedTime);\n\t\t\tthis._secondsAtTime.cancel(computedTime);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Cancel start/stop/pause and setTickAtTime events scheduled after the given time.\n\t * @param time When to clear the events after\n\t */\n\tcancel(time: Time): this {\n\t\ttime = this.toSeconds(time);\n\t\tthis._state.cancel(time);\n\t\tthis._tickOffset.cancel(time);\n\t\tthis._ticksAtTime.cancel(time);\n\t\tthis._secondsAtTime.cancel(time);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Get the elapsed ticks at the given time\n\t * @param time When to get the tick value\n\t * @return The number of ticks\n\t */\n\tgetTicksAtTime(time?: Time): Ticks {\n\t\tconst computedTime = this.toSeconds(time);\n\t\tconst stopEvent = this._state.getLastState(\n\t\t\t\"stopped\",\n\t\t\tcomputedTime\n\t\t) as StateTimelineEvent;\n\n\t\t// get previously memoized ticks if available\n\t\tconst memoizedEvent = this._ticksAtTime.get(computedTime);\n\n\t\t// this event allows forEachBetween to iterate until the current time\n\t\tconst tmpEvent: StateTimelineEvent = {\n\t\t\tstate: \"paused\",\n\t\t\ttime: computedTime,\n\t\t};\n\t\tthis._state.add(tmpEvent);\n\n\t\t// keep track of the previous offset event\n\t\tlet lastState = memoizedEvent ? memoizedEvent : stopEvent;\n\t\tlet elapsedTicks = memoizedEvent ? memoizedEvent.ticks : 0;\n\t\tlet eventToMemoize: TickSourceTicksAtTimeEvent | null = null;\n\n\t\t// iterate through all the events since the last stop\n\t\tthis._state.forEachBetween(\n\t\t\tlastState.time,\n\t\t\tcomputedTime + this.sampleTime,\n\t\t\t(e) => {\n\t\t\t\tlet periodStartTime = lastState.time;\n\t\t\t\t// if there is an offset event in this period use that\n\t\t\t\tconst offsetEvent = this._tickOffset.get(e.time);\n\t\t\t\tif (offsetEvent && offsetEvent.time >= lastState.time) {\n\t\t\t\t\telapsedTicks = offsetEvent.ticks;\n\t\t\t\t\tperiodStartTime = offsetEvent.time;\n\t\t\t\t}\n\t\t\t\tif (lastState.state === \"started\" && e.state !== \"started\") {\n\t\t\t\t\telapsedTicks +=\n\t\t\t\t\t\tthis.frequency.getTicksAtTime(e.time) -\n\t\t\t\t\t\tthis.frequency.getTicksAtTime(periodStartTime);\n\t\t\t\t\t// do not memoize the temporary event\n\t\t\t\t\tif (e.time !== tmpEvent.time) {\n\t\t\t\t\t\teventToMemoize = {\n\t\t\t\t\t\t\tstate: e.state,\n\t\t\t\t\t\t\ttime: e.time,\n\t\t\t\t\t\t\tticks: elapsedTicks,\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tlastState = e;\n\t\t\t}\n\t\t);\n\n\t\t// remove the temporary event\n\t\tthis._state.remove(tmpEvent);\n\n\t\t// memoize the ticks at the most recent event with state other than \"started\"\n\t\tif (eventToMemoize) {\n\t\t\tthis._ticksAtTime.add(eventToMemoize);\n\t\t}\n\n\t\t// return the ticks\n\t\treturn elapsedTicks;\n\t}\n\n\t/**\n\t * The number of times the callback was invoked. Starts counting at 0\n\t * and increments after the callback was invoked. Returns -1 when stopped.\n\t */\n\tget ticks(): Ticks {\n\t\treturn this.getTicksAtTime(this.now());\n\t}\n\tset ticks(t: Ticks) {\n\t\tthis.setTicksAtTime(t, this.now());\n\t}\n\n\t/**\n\t * The time since ticks=0 that the TickSource has been running. Accounts\n\t * for tempo curves\n\t */\n\tget seconds(): Seconds {\n\t\treturn this.getSecondsAtTime(this.now());\n\t}\n\tset seconds(s: Seconds) {\n\t\tconst now = this.now();\n\t\tconst ticks = this.frequency.timeToTicks(s, now);\n\t\tthis.setTicksAtTime(ticks, now);\n\t}\n\n\t/**\n\t * Return the elapsed seconds at the given time.\n\t * @param time When to get the elapsed seconds\n\t * @return The number of elapsed seconds\n\t */\n\tgetSecondsAtTime(time: Time): Seconds {\n\t\ttime = this.toSeconds(time);\n\t\tconst stopEvent = this._state.getLastState(\n\t\t\t\"stopped\",\n\t\t\ttime\n\t\t) as StateTimelineEvent;\n\t\t// this event allows forEachBetween to iterate until the current time\n\t\tconst tmpEvent: StateTimelineEvent = { state: \"paused\", time };\n\t\tthis._state.add(tmpEvent);\n\n\t\t// get previously memoized seconds if available\n\t\tconst memoizedEvent = this._secondsAtTime.get(time);\n\n\t\t// keep track of the previous offset event\n\t\tlet lastState = memoizedEvent ? memoizedEvent : stopEvent;\n\t\tlet elapsedSeconds = memoizedEvent ? memoizedEvent.seconds : 0;\n\t\tlet eventToMemoize: TickSourceSecondsAtTimeEvent | null = null;\n\n\t\t// iterate through all the events since the last stop\n\t\tthis._state.forEachBetween(\n\t\t\tlastState.time,\n\t\t\ttime + this.sampleTime,\n\t\t\t(e) => {\n\t\t\t\tlet periodStartTime = lastState.time;\n\t\t\t\t// if there is an offset event in this period use that\n\t\t\t\tconst offsetEvent = this._tickOffset.get(e.time);\n\t\t\t\tif (offsetEvent && offsetEvent.time >= lastState.time) {\n\t\t\t\t\telapsedSeconds = offsetEvent.seconds;\n\t\t\t\t\tperiodStartTime = offsetEvent.time;\n\t\t\t\t}\n\t\t\t\tif (lastState.state === \"started\" && e.state !== \"started\") {\n\t\t\t\t\telapsedSeconds += e.time - periodStartTime;\n\t\t\t\t\t// do not memoize the temporary event\n\t\t\t\t\tif (e.time !== tmpEvent.time) {\n\t\t\t\t\t\teventToMemoize = {\n\t\t\t\t\t\t\tstate: e.state,\n\t\t\t\t\t\t\ttime: e.time,\n\t\t\t\t\t\t\tseconds: elapsedSeconds,\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tlastState = e;\n\t\t\t}\n\t\t);\n\n\t\t// remove the temporary event\n\t\tthis._state.remove(tmpEvent);\n\n\t\t// memoize the seconds at the most recent event with state other than \"started\"\n\t\tif (eventToMemoize) {\n\t\t\tthis._secondsAtTime.add(eventToMemoize);\n\t\t}\n\n\t\t// return the seconds\n\t\treturn elapsedSeconds;\n\t}\n\n\t/**\n\t * Set the clock's ticks at the given time.\n\t * @param ticks The tick value to set\n\t * @param time When to set the tick value\n\t */\n\tsetTicksAtTime(ticks: Ticks, time: Time): this {\n\t\ttime = this.toSeconds(time);\n\t\tthis._tickOffset.cancel(time);\n\t\tthis._tickOffset.add({\n\t\t\tseconds: this.frequency.getDurationOfTicks(ticks, time),\n\t\t\tticks,\n\t\t\ttime,\n\t\t});\n\t\tthis._ticksAtTime.cancel(time);\n\t\tthis._secondsAtTime.cancel(time);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Returns the scheduled state at the given time.\n\t * @param time The time to query.\n\t */\n\tgetStateAtTime(time: Time): PlaybackState {\n\t\ttime = this.toSeconds(time);\n\t\treturn this._state.getValueAtTime(time);\n\t}\n\n\t/**\n\t * Get the time of the given tick. The second argument\n\t * is when to test before. Since ticks can be set (with setTicksAtTime)\n\t * there may be multiple times for a given tick value.\n\t * @param tick The tick number.\n\t * @param before When to measure the tick value from.\n\t * @return The time of the tick\n\t */\n\tgetTimeOfTick(tick: Ticks, before = this.now()): Seconds {\n\t\tconst offset = this._tickOffset.get(before) as TickSourceOffsetEvent;\n\t\tconst event = this._state.get(before) as StateTimelineEvent;\n\t\tconst startTime = Math.max(offset.time, event.time);\n\t\tconst absoluteTicks =\n\t\t\tthis.frequency.getTicksAtTime(startTime) + tick - offset.ticks;\n\t\treturn this.frequency.getTimeOfTick(absoluteTicks);\n\t}\n\n\t/**\n\t * Invoke the callback event at all scheduled ticks between the\n\t * start time and the end time\n\t * @param startTime The beginning of the search range\n\t * @param endTime The end of the search range\n\t * @param callback The callback to invoke with each tick\n\t */\n\tforEachTickBetween(\n\t\tstartTime: number,\n\t\tendTime: number,\n\t\tcallback: (when: Seconds, ticks: Ticks) => void\n\t): this {\n\t\t// only iterate through the sections where it is \"started\"\n\t\tlet lastStateEvent = this._state.get(startTime);\n\t\tthis._state.forEachBetween(startTime, endTime, (event) => {\n\t\t\tif (\n\t\t\t\tlastStateEvent &&\n\t\t\t\tlastStateEvent.state === \"started\" &&\n\t\t\t\tevent.state !== \"started\"\n\t\t\t) {\n\t\t\t\tthis.forEachTickBetween(\n\t\t\t\t\tMath.max(lastStateEvent.time, startTime),\n\t\t\t\t\tevent.time - this.sampleTime,\n\t\t\t\t\tcallback\n\t\t\t\t);\n\t\t\t}\n\t\t\tlastStateEvent = event;\n\t\t});\n\n\t\tlet error: Error | null = null;\n\n\t\tif (lastStateEvent && lastStateEvent.state === \"started\") {\n\t\t\tconst maxStartTime = Math.max(lastStateEvent.time, startTime);\n\t\t\t// figure out the difference between the frequency ticks and the\n\t\t\tconst startTicks = this.frequency.getTicksAtTime(maxStartTime);\n\t\t\tconst ticksAtStart = this.frequency.getTicksAtTime(\n\t\t\t\tlastStateEvent.time\n\t\t\t);\n\t\t\tconst diff = startTicks - ticksAtStart;\n\t\t\tlet offset = Math.ceil(diff) - diff;\n\t\t\t// guard against floating point issues\n\t\t\toffset = EQ(offset, 1) ? 0 : offset;\n\t\t\tlet nextTickTime = this.frequency.getTimeOfTick(\n\t\t\t\tstartTicks + offset\n\t\t\t);\n\t\t\twhile (nextTickTime < endTime) {\n\t\t\t\ttry {\n\t\t\t\t\tcallback(\n\t\t\t\t\t\tnextTickTime,\n\t\t\t\t\t\tMath.round(this.getTicksAtTime(nextTickTime))\n\t\t\t\t\t);\n\t\t\t\t} catch (e) {\n\t\t\t\t\terror = e;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tnextTickTime += this.frequency.getDurationOfTicks(\n\t\t\t\t\t1,\n\t\t\t\t\tnextTickTime\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tif (error) {\n\t\t\tthrow error;\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Clean up\n\t */\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis._state.dispose();\n\t\tthis._tickOffset.dispose();\n\t\tthis._ticksAtTime.dispose();\n\t\tthis._secondsAtTime.dispose();\n\t\tthis.frequency.dispose();\n\t\treturn this;\n\t}\n}\n","import {\n\tToneWithContext,\n\tToneWithContextOptions,\n} from \"../context/ToneWithContext.js\";\nimport { Frequency, Hertz, Seconds, Ticks, Time } from \"../type/Units.js\";\nimport { optionsFromArguments } from \"../util/Defaults.js\";\nimport { Emitter } from \"../util/Emitter.js\";\nimport { noOp, readOnly } from \"../util/Interface.js\";\nimport { PlaybackState, StateTimeline } from \"../util/StateTimeline.js\";\nimport { TickSignal } from \"./TickSignal.js\";\nimport { TickSource } from \"./TickSource.js\";\nimport { assertContextRunning } from \"../util/Debug.js\";\n\ntype ClockCallback = (time: Seconds, ticks?: Ticks) => void;\n\ninterface ClockOptions extends ToneWithContextOptions {\n\tfrequency: Hertz;\n\tcallback: ClockCallback;\n\tunits: \"hertz\" | \"bpm\";\n}\n\ntype ClockEvent = \"start\" | \"stop\" | \"pause\";\n\n/**\n * A sample accurate clock which provides a callback at the given rate.\n * While the callback is not sample-accurate (it is still susceptible to\n * loose JS timing), the time passed in as the argument to the callback\n * is precise. For most applications, it is better to use Tone.Transport\n * instead of the Clock by itself since you can synchronize multiple callbacks.\n * @example\n * // the callback will be invoked approximately once a second\n * // and will print the time exactly once a second apart.\n * const clock = new Tone.Clock(time => {\n * \tconsole.log(time);\n * }, 1);\n * clock.start();\n * @category Core\n */\nexport class Clock<TypeName extends \"bpm\" | \"hertz\" = \"hertz\">\n\textends ToneWithContext<ClockOptions>\n\timplements Emitter<ClockEvent>\n{\n\treadonly name: string = \"Clock\";\n\n\t/**\n\t * The callback function to invoke at the scheduled tick.\n\t */\n\tcallback: ClockCallback = noOp;\n\n\t/**\n\t * The tick counter\n\t */\n\tprivate _tickSource: TickSource<TypeName>;\n\n\t/**\n\t * The last time the loop callback was invoked\n\t */\n\tprivate _lastUpdate = 0;\n\n\t/**\n\t * Keep track of the playback state\n\t */\n\tprivate _state: StateTimeline = new StateTimeline(\"stopped\");\n\n\t/**\n\t * Context bound reference to the _loop method\n\t * This is necessary to remove the event in the end.\n\t */\n\tprivate _boundLoop: () => void = this._loop.bind(this);\n\n\t/**\n\t * The rate the callback function should be invoked.\n\t */\n\tfrequency: TickSignal<TypeName>;\n\n\t/**\n\t * @param callback The callback to be invoked with the time of the audio event\n\t * @param frequency The rate of the callback\n\t */\n\tconstructor(callback?: ClockCallback, frequency?: Frequency);\n\tconstructor(options: Partial<ClockOptions>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(Clock.getDefaults(), arguments, [\n\t\t\t\"callback\",\n\t\t\t\"frequency\",\n\t\t]);\n\t\tsuper(options);\n\n\t\tthis.callback = options.callback;\n\t\tthis._tickSource = new TickSource({\n\t\t\tcontext: this.context,\n\t\t\tfrequency: options.frequency,\n\t\t\tunits: options.units,\n\t\t});\n\t\tthis._lastUpdate = 0;\n\t\tthis.frequency = this._tickSource.frequency;\n\t\treadOnly(this, \"frequency\");\n\n\t\t// add an initial state\n\t\tthis._state.setStateAtTime(\"stopped\", 0);\n\n\t\t// bind a callback to the worker thread\n\t\tthis.context.on(\"tick\", this._boundLoop);\n\t}\n\n\tstatic getDefaults(): ClockOptions {\n\t\treturn Object.assign(ToneWithContext.getDefaults(), {\n\t\t\tcallback: noOp as ClockCallback,\n\t\t\tfrequency: 1,\n\t\t\tunits: \"hertz\",\n\t\t}) as ClockOptions;\n\t}\n\n\t/**\n\t * Returns the playback state of the source, either \"started\", \"stopped\" or \"paused\".\n\t */\n\tget state(): PlaybackState {\n\t\treturn this._state.getValueAtTime(this.now());\n\t}\n\n\t/**\n\t * Start the clock at the given time. Optionally pass in an offset\n\t * of where to start the tick counter from.\n\t * @param time The time the clock should start\n\t * @param offset Where the tick counter starts counting from.\n\t */\n\tstart(time?: Time, offset?: Ticks): this {\n\t\t// make sure the context is running\n\t\tassertContextRunning(this.context);\n\t\t// start the loop\n\t\tconst computedTime = this.toSeconds(time);\n\t\tthis.log(\"start\", computedTime);\n\t\tif (this._state.getValueAtTime(computedTime) !== \"started\") {\n\t\t\tthis._state.setStateAtTime(\"started\", computedTime);\n\t\t\tthis._tickSource.start(computedTime, offset);\n\t\t\tif (computedTime < this._lastUpdate) {\n\t\t\t\tthis.emit(\"start\", computedTime, offset);\n\t\t\t}\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Stop the clock. Stopping the clock resets the tick counter to 0.\n\t * @param time The time when the clock should stop.\n\t * @example\n\t * const clock = new Tone.Clock(time => {\n\t * \tconsole.log(time);\n\t * }, 1);\n\t * clock.start();\n\t * // stop the clock after 10 seconds\n\t * clock.stop(\"+10\");\n\t */\n\tstop(time?: Time): this {\n\t\tconst computedTime = this.toSeconds(time);\n\t\tthis.log(\"stop\", computedTime);\n\t\tthis._state.cancel(computedTime);\n\t\tthis._state.setStateAtTime(\"stopped\", computedTime);\n\t\tthis._tickSource.stop(computedTime);\n\t\tif (computedTime < this._lastUpdate) {\n\t\t\tthis.emit(\"stop\", computedTime);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Pause the clock. Pausing does not reset the tick counter.\n\t * @param time The time when the clock should stop.\n\t */\n\tpause(time?: Time): this {\n\t\tconst computedTime = this.toSeconds(time);\n\t\tif (this._state.getValueAtTime(computedTime) === \"started\") {\n\t\t\tthis._state.setStateAtTime(\"paused\", computedTime);\n\t\t\tthis._tickSource.pause(computedTime);\n\t\t\tif (computedTime < this._lastUpdate) {\n\t\t\t\tthis.emit(\"pause\", computedTime);\n\t\t\t}\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * The number of times the callback was invoked. Starts counting at 0\n\t * and increments after the callback was invoked.\n\t */\n\tget ticks(): Ticks {\n\t\treturn Math.ceil(this.getTicksAtTime(this.now()));\n\t}\n\tset ticks(t: Ticks) {\n\t\tthis._tickSource.ticks = t;\n\t}\n\n\t/**\n\t * The time since ticks=0 that the Clock has been running. Accounts for tempo curves\n\t */\n\tget seconds(): Seconds {\n\t\treturn this._tickSource.seconds;\n\t}\n\tset seconds(s: Seconds) {\n\t\tthis._tickSource.seconds = s;\n\t}\n\n\t/**\n\t * Return the elapsed seconds at the given time.\n\t * @param time When to get the elapsed seconds\n\t * @return The number of elapsed seconds\n\t */\n\tgetSecondsAtTime(time: Time): Seconds {\n\t\treturn this._tickSource.getSecondsAtTime(time);\n\t}\n\n\t/**\n\t * Set the clock's ticks at the given time.\n\t * @param ticks The tick value to set\n\t * @param time When to set the tick value\n\t */\n\tsetTicksAtTime(ticks: Ticks, time: Time): this {\n\t\tthis._tickSource.setTicksAtTime(ticks, time);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Get the time of the given tick. The second argument\n\t * is when to test before. Since ticks can be set (with setTicksAtTime)\n\t * there may be multiple times for a given tick value.\n\t * @param tick The tick number.\n\t * @param before When to measure the tick value from.\n\t * @return The time of the tick\n\t */\n\tgetTimeOfTick(tick: Ticks, before = this.now()): Seconds {\n\t\treturn this._tickSource.getTimeOfTick(tick, before);\n\t}\n\n\t/**\n\t * Get the clock's ticks at the given time.\n\t * @param time When to get the tick value\n\t * @return The tick value at the given time.\n\t */\n\tgetTicksAtTime(time?: Time): Ticks {\n\t\treturn this._tickSource.getTicksAtTime(time);\n\t}\n\n\t/**\n\t * Get the time of the next tick\n\t * @param offset The tick number.\n\t */\n\tnextTickTime(offset: Ticks, when: Time): Seconds {\n\t\tconst computedTime = this.toSeconds(when);\n\t\tconst currentTick = this.getTicksAtTime(computedTime);\n\t\treturn this._tickSource.getTimeOfTick(\n\t\t\tcurrentTick + offset,\n\t\t\tcomputedTime\n\t\t);\n\t}\n\n\t/**\n\t * The scheduling loop.\n\t */\n\tprivate _loop(): void {\n\t\tconst startTime = this._lastUpdate;\n\t\tconst endTime = this.now();\n\t\tthis._lastUpdate = endTime;\n\t\tthis.log(\"loop\", startTime, endTime);\n\n\t\tif (startTime !== endTime) {\n\t\t\t// the state change events\n\t\t\tthis._state.forEachBetween(startTime, endTime, (e) => {\n\t\t\t\tswitch (e.state) {\n\t\t\t\t\tcase \"started\":\n\t\t\t\t\t\tconst offset = this._tickSource.getTicksAtTime(e.time);\n\t\t\t\t\t\tthis.emit(\"start\", e.time, offset);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"stopped\":\n\t\t\t\t\t\tif (e.time !== 0) {\n\t\t\t\t\t\t\tthis.emit(\"stop\", e.time);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"paused\":\n\t\t\t\t\t\tthis.emit(\"pause\", e.time);\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t});\n\t\t\t// the tick callbacks\n\t\t\tthis._tickSource.forEachTickBetween(\n\t\t\t\tstartTime,\n\t\t\t\tendTime,\n\t\t\t\t(time, ticks) => {\n\t\t\t\t\tthis.callback(time, ticks);\n\t\t\t\t}\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Returns the scheduled state at the given time.\n\t * @param time The time to query.\n\t * @return The name of the state input in setStateAtTime.\n\t * @example\n\t * const clock = new Tone.Clock();\n\t * clock.start(\"+0.1\");\n\t * clock.getStateAtTime(\"+0.1\"); // returns \"started\"\n\t */\n\tgetStateAtTime(time: Time): PlaybackState {\n\t\tconst computedTime = this.toSeconds(time);\n\t\treturn this._state.getValueAtTime(computedTime);\n\t}\n\n\t/**\n\t * Clean up\n\t */\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis.context.off(\"tick\", this._boundLoop);\n\t\tthis._tickSource.dispose();\n\t\tthis._state.dispose();\n\t\treturn this;\n\t}\n\n\t//-------------------------------------\n\t// EMITTER MIXIN TO SATISFY COMPILER\n\t//-------------------------------------\n\n\ton!: (event: ClockEvent, callback: (...args: any[]) => void) => this;\n\tonce!: (event: ClockEvent, callback: (...args: any[]) => void) => this;\n\toff!: (\n\t\tevent: ClockEvent,\n\t\tcallback?: ((...args: any[]) => void) | undefined\n\t) => this;\n\temit!: (event: any, ...args: any[]) => this;\n}\n\nEmitter.mixin(Clock);\n","import { Param } from \"../context/Param.js\";\nimport { Seconds, Time } from \"../type/Units.js\";\nimport { optionsFromArguments } from \"../util/Defaults.js\";\nimport { readOnly } from \"../util/Interface.js\";\nimport { ToneAudioNode, ToneAudioNodeOptions } from \"./ToneAudioNode.js\";\n\nexport interface DelayOptions extends ToneAudioNodeOptions {\n\tdelayTime: Time;\n\tmaxDelay: Time;\n}\n\n/**\n * Wrapper around Web Audio's native [DelayNode](http://webaudio.github.io/web-audio-api/#the-delaynode-interface).\n * @category Core\n * @example\n * return Tone.Offline(() => {\n * \tconst delay = new Tone.Delay(0.1).toDestination();\n * \t// connect the signal to both the delay and the destination\n * \tconst pulse = new Tone.PulseOscillator().connect(delay).toDestination();\n * \t// start and stop the pulse\n * \tpulse.start(0).stop(0.01);\n * }, 0.5, 1);\n */\nexport class Delay extends ToneAudioNode<DelayOptions> {\n\treadonly name: string = \"Delay\";\n\n\t/**\n\t * Private holder of the max delay time\n\t */\n\tprivate _maxDelay: Seconds;\n\n\t/**\n\t * The amount of time the incoming signal is delayed.\n\t * @example\n\t * const delay = new Tone.Delay().toDestination();\n\t * // modulate the delayTime between 0.1 and 1 seconds\n\t * const delayLFO = new Tone.LFO(0.5, 0.1, 1).start().connect(delay.delayTime);\n\t * const pulse = new Tone.PulseOscillator().connect(delay).start();\n\t * // the change in delayTime causes the pitch to go up and down\n\t */\n\treadonly delayTime: Param<\"time\">;\n\n\t/**\n\t * Private reference to the internal DelayNode\n\t */\n\tprivate _delayNode: DelayNode;\n\treadonly input: DelayNode;\n\treadonly output: DelayNode;\n\n\t/**\n\t * @param delayTime The delay applied to the incoming signal.\n\t * @param maxDelay The maximum delay time.\n\t */\n\tconstructor(delayTime?: Time, maxDelay?: Time);\n\tconstructor(options?: Partial<DelayOptions>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(Delay.getDefaults(), arguments, [\n\t\t\t\"delayTime\",\n\t\t\t\"maxDelay\",\n\t\t]);\n\t\tsuper(options);\n\n\t\tconst maxDelayInSeconds = this.toSeconds(options.maxDelay);\n\t\tthis._maxDelay = Math.max(\n\t\t\tmaxDelayInSeconds,\n\t\t\tthis.toSeconds(options.delayTime)\n\t\t);\n\n\t\tthis._delayNode =\n\t\t\tthis.input =\n\t\t\tthis.output =\n\t\t\t\tthis.context.createDelay(maxDelayInSeconds);\n\n\t\tthis.delayTime = new Param({\n\t\t\tcontext: this.context,\n\t\t\tparam: this._delayNode.delayTime,\n\t\t\tunits: \"time\",\n\t\t\tvalue: options.delayTime,\n\t\t\tminValue: 0,\n\t\t\tmaxValue: this.maxDelay,\n\t\t});\n\n\t\treadOnly(this, \"delayTime\");\n\t}\n\n\tstatic getDefaults(): DelayOptions {\n\t\treturn Object.assign(ToneAudioNode.getDefaults(), {\n\t\t\tdelayTime: 0,\n\t\t\tmaxDelay: 1,\n\t\t});\n\t}\n\n\t/**\n\t * The maximum delay time. This cannot be changed after\n\t * the value is passed into the constructor.\n\t */\n\tget maxDelay(): Seconds {\n\t\treturn this._maxDelay;\n\t}\n\n\t/**\n\t * Clean up.\n\t */\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis._delayNode.disconnect();\n\t\tthis.delayTime.dispose();\n\t\treturn this;\n\t}\n}\n","import { Gain } from \"../../core/context/Gain.js\";\nimport { Param } from \"../../core/context/Param.js\";\nimport {\n\tToneAudioNode,\n\tToneAudioNodeOptions,\n} from \"../../core/context/ToneAudioNode.js\";\nimport { Decibels } from \"../../core/type/Units.js\";\nimport { optionsFromArguments } from \"../../core/util/Defaults.js\";\nimport { readOnly } from \"../../core/util/Interface.js\";\n\ninterface VolumeOptions extends ToneAudioNodeOptions {\n\tvolume: Decibels;\n\tmute: boolean;\n}\n\n/**\n * Volume is a simple volume node, useful for creating a volume fader.\n *\n * @example\n * const vol = new Tone.Volume(-12).toDestination();\n * const osc = new Tone.Oscillator().connect(vol).start();\n * @category Component\n */\nexport class Volume extends ToneAudioNode<VolumeOptions> {\n\treadonly name: string = \"Volume\";\n\n\t/**\n\t * the output node\n\t */\n\toutput: Gain<\"decibels\">;\n\n\t/**\n\t * Input and output are the same\n\t */\n\tinput: Gain<\"decibels\">;\n\n\t/**\n\t * The unmuted volume\n\t */\n\tprivate _unmutedVolume: Decibels;\n\n\t/**\n\t * The volume control in decibels.\n\t * @example\n\t * const vol = new Tone.Volume().toDestination();\n\t * const osc = new Tone.Oscillator().connect(vol).start();\n\t * vol.volume.value = -20;\n\t */\n\tvolume: Param<\"decibels\">;\n\n\t/**\n\t * @param volume the initial volume in decibels\n\t */\n\tconstructor(volume?: Decibels);\n\tconstructor(options?: Partial<VolumeOptions>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(Volume.getDefaults(), arguments, [\n\t\t\t\"volume\",\n\t\t]);\n\t\tsuper(options);\n\n\t\tthis.input = this.output = new Gain({\n\t\t\tcontext: this.context,\n\t\t\tgain: options.volume,\n\t\t\tunits: \"decibels\",\n\t\t});\n\t\tthis.volume = this.output.gain;\n\t\treadOnly(this, \"volume\");\n\t\tthis._unmutedVolume = options.volume;\n\n\t\t// set the mute initially\n\t\tthis.mute = options.mute;\n\t}\n\n\tstatic getDefaults(): VolumeOptions {\n\t\treturn Object.assign(ToneAudioNode.getDefaults(), {\n\t\t\tmute: false,\n\t\t\tvolume: 0,\n\t\t});\n\t}\n\n\t/**\n\t * Mute the output.\n\t * @example\n\t * const vol = new Tone.Volume(-12).toDestination();\n\t * const osc = new Tone.Oscillator().connect(vol).start();\n\t * // mute the output\n\t * vol.mute = true;\n\t */\n\tget mute(): boolean {\n\t\treturn this.volume.value === -Infinity;\n\t}\n\tset mute(mute: boolean) {\n\t\tif (!this.mute && mute) {\n\t\t\tthis._unmutedVolume = this.volume.value;\n\t\t\t// maybe it should ramp here?\n\t\t\tthis.volume.value = -Infinity;\n\t\t} else if (this.mute && !mute) {\n\t\t\tthis.volume.value = this._unmutedVolume;\n\t\t}\n\t}\n\n\t/**\n\t * clean up\n\t */\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis.input.dispose();\n\t\tthis.volume.dispose();\n\t\treturn this;\n\t}\n}\n","import { Volume } from \"../../component/channel/Volume.js\";\nimport { Decibels } from \"../type/Units.js\";\nimport { optionsFromArguments } from \"../util/Defaults.js\";\nimport { onContextClose, onContextInit } from \"./ContextInitialization.js\";\nimport { Gain } from \"./Gain.js\";\nimport { Param } from \"./Param.js\";\nimport {\n\tconnectSeries,\n\tToneAudioNode,\n\tToneAudioNodeOptions,\n} from \"./ToneAudioNode.js\";\n\ninterface DestinationOptions extends ToneAudioNodeOptions {\n\tvolume: Decibels;\n\tmute: boolean;\n}\n\n/**\n * A single master output which is connected to the\n * AudioDestinationNode (aka your speakers).\n * It provides useful conveniences such as the ability\n * to set the volume and mute the entire application.\n * It also gives you the ability to apply master effects to your application.\n *\n * @example\n * const oscillator = new Tone.Oscillator().start();\n * // the audio will go from the oscillator to the speakers\n * oscillator.connect(Tone.getDestination());\n * // a convenience for connecting to the master output is also provided:\n * oscillator.toDestination();\n * @category Core\n */\nexport class DestinationClass extends ToneAudioNode<DestinationOptions> {\n\treadonly name: string = \"Destination\";\n\n\tinput: Volume = new Volume({ context: this.context });\n\toutput: Gain = new Gain({ context: this.context });\n\n\t/**\n\t * The volume of the master output in decibels. -Infinity is silent, and 0 is no change.\n\t * @example\n\t * const osc = new Tone.Oscillator().toDestination();\n\t * osc.start();\n\t * // ramp the volume down to silent over 10 seconds\n\t * Tone.getDestination().volume.rampTo(-Infinity, 10);\n\t */\n\tvolume: Param<\"decibels\"> = this.input.volume;\n\n\tconstructor(options: Partial<DestinationOptions>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(\n\t\t\tDestinationClass.getDefaults(),\n\t\t\targuments\n\t\t);\n\t\tsuper(options);\n\n\t\tconnectSeries(\n\t\t\tthis.input,\n\t\t\tthis.output,\n\t\t\tthis.context.rawContext.destination\n\t\t);\n\n\t\tthis.mute = options.mute;\n\t\tthis._internalChannels = [\n\t\t\tthis.input,\n\t\t\tthis.context.rawContext.destination,\n\t\t\tthis.output,\n\t\t];\n\t}\n\n\tstatic getDefaults(): DestinationOptions {\n\t\treturn Object.assign(ToneAudioNode.getDefaults(), {\n\t\t\tmute: false,\n\t\t\tvolume: 0,\n\t\t});\n\t}\n\n\t/**\n\t * Mute the output.\n\t * @example\n\t * const oscillator = new Tone.Oscillator().start().toDestination();\n\t * setTimeout(() => {\n\t * \t// mute the output\n\t * \tTone.Destination.mute = true;\n\t * }, 1000);\n\t */\n\tget mute(): boolean {\n\t\treturn this.input.mute;\n\t}\n\tset mute(mute: boolean) {\n\t\tthis.input.mute = mute;\n\t}\n\n\t/**\n\t * Add a master effects chain. NOTE: this will disconnect any nodes which were previously\n\t * chained in the master effects chain.\n\t * @param args All arguments will be connected in a row and the Master will be routed through it.\n\t * @example\n\t * // route all audio through a filter and compressor\n\t * const lowpass = new Tone.Filter(800, \"lowpass\");\n\t * const compressor = new Tone.Compressor(-18);\n\t * Tone.Destination.chain(lowpass, compressor);\n\t */\n\tchain(...args: Array<AudioNode | ToneAudioNode>): this {\n\t\tthis.input.disconnect();\n\t\targs.unshift(this.input);\n\t\targs.push(this.output);\n\t\tconnectSeries(...args);\n\t\treturn this;\n\t}\n\n\t/**\n\t * The maximum number of channels the system can output\n\t * @example\n\t * console.log(Tone.Destination.maxChannelCount);\n\t */\n\tget maxChannelCount(): number {\n\t\treturn this.context.rawContext.destination.maxChannelCount;\n\t}\n\n\t/**\n\t * Clean up\n\t */\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis.volume.dispose();\n\t\treturn this;\n\t}\n}\n\n//-------------------------------------\n// \tINITIALIZATION\n//-------------------------------------\n\nonContextInit((context) => {\n\tcontext.destination = new DestinationClass({ context });\n});\n\nonContextClose((context) => {\n\tcontext.destination.dispose();\n});\n","import { ToneAudioNode, ToneAudioNodeOptions } from \"./ToneAudioNode.js\";\nimport { Param } from \"./Param.js\";\nimport { onContextClose, onContextInit } from \"./ContextInitialization.js\";\n\nexport interface ListenerOptions extends ToneAudioNodeOptions {\n\tpositionX: number;\n\tpositionY: number;\n\tpositionZ: number;\n\tforwardX: number;\n\tforwardY: number;\n\tforwardZ: number;\n\tupX: number;\n\tupY: number;\n\tupZ: number;\n}\n\n/**\n * Tone.Listener is a thin wrapper around the AudioListener. Listener combined\n * with {@link Panner3D} makes up the Web Audio API's 3D panning system. Panner3D allows you\n * to place sounds in 3D and Listener allows you to navigate the 3D sound environment from\n * a first-person perspective. There is only one listener per audio context.\n */\nexport class ListenerClass extends ToneAudioNode<ListenerOptions> {\n\treadonly name: string = \"Listener\";\n\n\t/**\n\t * The listener has no inputs or outputs.\n\t */\n\toutput: undefined;\n\tinput: undefined;\n\n\treadonly positionX: Param = new Param({\n\t\tcontext: this.context,\n\t\tparam: this.context.rawContext.listener.positionX,\n\t});\n\n\treadonly positionY: Param = new Param({\n\t\tcontext: this.context,\n\t\tparam: this.context.rawContext.listener.positionY,\n\t});\n\n\treadonly positionZ: Param = new Param({\n\t\tcontext: this.context,\n\t\tparam: this.context.rawContext.listener.positionZ,\n\t});\n\n\treadonly forwardX: Param = new Param({\n\t\tcontext: this.context,\n\t\tparam: this.context.rawContext.listener.forwardX,\n\t});\n\n\treadonly forwardY: Param = new Param({\n\t\tcontext: this.context,\n\t\tparam: this.context.rawContext.listener.forwardY,\n\t});\n\n\treadonly forwardZ: Param = new Param({\n\t\tcontext: this.context,\n\t\tparam: this.context.rawContext.listener.forwardZ,\n\t});\n\n\treadonly upX: Param = new Param({\n\t\tcontext: this.context,\n\t\tparam: this.context.rawContext.listener.upX,\n\t});\n\n\treadonly upY: Param = new Param({\n\t\tcontext: this.context,\n\t\tparam: this.context.rawContext.listener.upY,\n\t});\n\n\treadonly upZ: Param = new Param({\n\t\tcontext: this.context,\n\t\tparam: this.context.rawContext.listener.upZ,\n\t});\n\n\tstatic getDefaults(): ListenerOptions {\n\t\treturn Object.assign(ToneAudioNode.getDefaults(), {\n\t\t\tpositionX: 0,\n\t\t\tpositionY: 0,\n\t\t\tpositionZ: 0,\n\t\t\tforwardX: 0,\n\t\t\tforwardY: 0,\n\t\t\tforwardZ: -1,\n\t\t\tupX: 0,\n\t\t\tupY: 1,\n\t\t\tupZ: 0,\n\t\t});\n\t}\n\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis.positionX.dispose();\n\t\tthis.positionY.dispose();\n\t\tthis.positionZ.dispose();\n\t\tthis.forwardX.dispose();\n\t\tthis.forwardY.dispose();\n\t\tthis.forwardZ.dispose();\n\t\tthis.upX.dispose();\n\t\tthis.upY.dispose();\n\t\tthis.upZ.dispose();\n\t\treturn this;\n\t}\n}\n\n//-------------------------------------\n// \tINITIALIZATION\n//-------------------------------------\n\nonContextInit((context) => {\n\tcontext.listener = new ListenerClass({ context });\n});\n\nonContextClose((context) => {\n\tcontext.listener.dispose();\n});\n","import { Tone } from \"../Tone.js\";\nimport { optionsFromArguments } from \"../util/Defaults.js\";\nimport { noOp } from \"../util/Interface.js\";\nimport { isString } from \"../util/TypeCheck.js\";\nimport { ToneAudioBuffer } from \"./ToneAudioBuffer.js\";\nimport { assert } from \"../util/Debug.js\";\n\nexport interface ToneAudioBuffersUrlMap {\n\t[name: string]: string | AudioBuffer | ToneAudioBuffer;\n\t[name: number]: string | AudioBuffer | ToneAudioBuffer;\n}\n\ninterface ToneAudioBuffersOptions {\n\turls: ToneAudioBuffersUrlMap;\n\tonload: () => void;\n\tonerror?: (error: Error) => void;\n\tbaseUrl: string;\n}\n\n/**\n * A data structure for holding multiple buffers in a Map-like datastructure.\n *\n * @example\n * const pianoSamples = new Tone.ToneAudioBuffers({\n * \tA1: \"https://tonejs.github.io/audio/casio/A1.mp3\",\n * \tA2: \"https://tonejs.github.io/audio/casio/A2.mp3\",\n * }, () => {\n * \tconst player = new Tone.Player().toDestination();\n * \t// play one of the samples when they all load\n * \tplayer.buffer = pianoSamples.get(\"A2\");\n * \tplayer.start();\n * });\n * @example\n * // To pass in additional parameters in the second parameter\n * const buffers = new Tone.ToneAudioBuffers({\n * \t urls: {\n * \t\t A1: \"A1.mp3\",\n * \t\t A2: \"A2.mp3\",\n * \t },\n * \t onload: () => console.log(\"loaded\"),\n * \t baseUrl: \"https://tonejs.github.io/audio/casio/\"\n * });\n * @category Core\n */\nexport class ToneAudioBuffers extends Tone {\n\treadonly name: string = \"ToneAudioBuffers\";\n\n\t/**\n\t * All of the buffers\n\t */\n\tprivate _buffers: Map<string, ToneAudioBuffer> = new Map();\n\n\t/**\n\t * A path which is prefixed before every url.\n\t */\n\tbaseUrl: string;\n\n\t/**\n\t * Keep track of the number of loaded buffers\n\t */\n\tprivate _loadingCount = 0;\n\n\t/**\n\t * @param urls An object literal or array of urls to load.\n\t * @param onload The callback to invoke when the buffers are loaded.\n\t * @param baseUrl A prefix url to add before all the urls\n\t */\n\tconstructor(\n\t\turls?: ToneAudioBuffersUrlMap,\n\t\tonload?: () => void,\n\t\tbaseUrl?: string\n\t);\n\tconstructor(options?: Partial<ToneAudioBuffersOptions>);\n\tconstructor() {\n\t\tsuper();\n\t\tconst options = optionsFromArguments(\n\t\t\tToneAudioBuffers.getDefaults(),\n\t\t\targuments,\n\t\t\t[\"urls\", \"onload\", \"baseUrl\"],\n\t\t\t\"urls\"\n\t\t);\n\n\t\tthis.baseUrl = options.baseUrl;\n\t\t// add each one\n\t\tObject.keys(options.urls).forEach((name) => {\n\t\t\tthis._loadingCount++;\n\t\t\tconst url = options.urls[name];\n\t\t\tthis.add(\n\t\t\t\tname,\n\t\t\t\turl,\n\t\t\t\tthis._bufferLoaded.bind(this, options.onload),\n\t\t\t\toptions.onerror\n\t\t\t);\n\t\t});\n\t}\n\n\tstatic getDefaults(): ToneAudioBuffersOptions {\n\t\treturn {\n\t\t\tbaseUrl: \"\",\n\t\t\tonerror: noOp,\n\t\t\tonload: noOp,\n\t\t\turls: {},\n\t\t};\n\t}\n\n\t/**\n\t * True if the buffers object has a buffer by that name.\n\t * @param name The key or index of the buffer.\n\t */\n\thas(name: string | number): boolean {\n\t\treturn this._buffers.has(name.toString());\n\t}\n\n\t/**\n\t * Get a buffer by name. If an array was loaded,\n\t * then use the array index.\n\t * @param name The key or index of the buffer.\n\t */\n\tget(name: string | number): ToneAudioBuffer {\n\t\tassert(this.has(name), `ToneAudioBuffers has no buffer named: ${name}`);\n\t\treturn this._buffers.get(name.toString()) as ToneAudioBuffer;\n\t}\n\n\t/**\n\t * A buffer was loaded. decrement the counter.\n\t */\n\tprivate _bufferLoaded(callback: () => void): void {\n\t\tthis._loadingCount--;\n\t\tif (this._loadingCount === 0 && callback) {\n\t\t\tcallback();\n\t\t}\n\t}\n\n\t/**\n\t * If the buffers are loaded or not\n\t */\n\tget loaded(): boolean {\n\t\treturn Array.from(this._buffers).every(([_, buffer]) => buffer.loaded);\n\t}\n\n\t/**\n\t * Add a buffer by name and url to the Buffers\n\t * @param name A unique name to give the buffer\n\t * @param url Either the url of the bufer, or a buffer which will be added with the given name.\n\t * @param callback The callback to invoke when the url is loaded.\n\t * @param onerror Invoked if the buffer can't be loaded\n\t */\n\tadd(\n\t\tname: string | number,\n\t\turl: string | AudioBuffer | ToneAudioBuffer,\n\t\tcallback: () => void = noOp,\n\t\tonerror: (e: Error) => void = noOp\n\t): this {\n\t\tif (isString(url)) {\n\t\t\t// don't include the baseUrl if the url is a base64 encoded sound\n\t\t\tif (\n\t\t\t\tthis.baseUrl &&\n\t\t\t\turl.trim().substring(0, 11).toLowerCase() === \"data:audio/\"\n\t\t\t) {\n\t\t\t\tthis.baseUrl = \"\";\n\t\t\t}\n\t\t\tthis._buffers.set(\n\t\t\t\tname.toString(),\n\t\t\t\tnew ToneAudioBuffer(this.baseUrl + url, callback, onerror)\n\t\t\t);\n\t\t} else {\n\t\t\tthis._buffers.set(\n\t\t\t\tname.toString(),\n\t\t\t\tnew ToneAudioBuffer(url, callback, onerror)\n\t\t\t);\n\t\t}\n\t\treturn this;\n\t}\n\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis._buffers.forEach((buffer) => buffer.dispose());\n\t\tthis._buffers.clear();\n\t\treturn this;\n\t}\n}\n","import { getContext } from \"../Global.js\";\nimport { TimeBaseUnit, TimeValue } from \"./TimeBase.js\";\nimport { TransportTimeClass } from \"./TransportTime.js\";\nimport { Seconds, Ticks } from \"./Units.js\";\n\n/**\n * Ticks is a primitive type for encoding Time values.\n * Ticks can be constructed with or without the `new` keyword. Ticks can be passed\n * into the parameter of any method which takes time as an argument.\n * @example\n * const t = Tone.Ticks(\"4n\"); // a quarter note as ticks\n * @category Unit\n */\nexport class TicksClass extends TransportTimeClass<Ticks> {\n\treadonly name: string = \"Ticks\";\n\n\treadonly defaultUnits: TimeBaseUnit = \"i\";\n\n\t/**\n\t * Get the current time in the given units\n\t */\n\tprotected _now(): Ticks {\n\t\treturn this.context.transport.ticks;\n\t}\n\n\t/**\n\t * Return the value of the beats in the current units\n\t */\n\tprotected _beatsToUnits(beats: number): Ticks {\n\t\treturn this._getPPQ() * beats;\n\t}\n\n\t/**\n\t * Returns the value of a second in the current units\n\t */\n\tprotected _secondsToUnits(seconds: Seconds): Ticks {\n\t\treturn Math.floor((seconds / (60 / this._getBpm())) * this._getPPQ());\n\t}\n\n\t/**\n\t * Returns the value of a tick in the current time units\n\t */\n\tprotected _ticksToUnits(ticks: Ticks): Ticks {\n\t\treturn ticks;\n\t}\n\n\t/**\n\t * Return the time in ticks\n\t */\n\ttoTicks(): Ticks {\n\t\treturn this.valueOf() as Ticks;\n\t}\n\n\t/**\n\t * Return the time in seconds\n\t */\n\ttoSeconds(): Seconds {\n\t\treturn (this.valueOf() / this._getPPQ()) * (60 / this._getBpm());\n\t}\n}\n\n/**\n * Convert a time representation to ticks\n * @category Unit\n */\nexport function Ticks(value?: TimeValue, units?: TimeBaseUnit): TicksClass {\n\treturn new TicksClass(getContext(), value, units);\n}\n","import {\n\tToneWithContext,\n\tToneWithContextOptions,\n} from \"../context/ToneWithContext.js\";\nimport { Seconds, Time } from \"../type/Units.js\";\nimport { Timeline, TimelineEvent } from \"./Timeline.js\";\nimport {\n\tonContextClose,\n\tonContextInit,\n} from \"../context/ContextInitialization.js\";\n\ninterface DrawEvent extends TimelineEvent {\n\tcallback: () => void;\n}\n\n/**\n * Draw is useful for synchronizing visuals and audio events.\n * Callbacks from Tone.Transport or any of the Tone.Event classes\n * always happen _before_ the scheduled time and are not synchronized\n * to the animation frame so they are not good for triggering tightly\n * synchronized visuals and sound. Draw makes it easy to schedule\n * callbacks using the AudioContext time and uses requestAnimationFrame.\n * @example\n * Tone.Transport.schedule((time) => {\n * \t// use the time argument to schedule a callback with Draw\n * \tTone.Draw.schedule(() => {\n * \t\t// do drawing or DOM manipulation here\n * \t\tconsole.log(time);\n * \t}, time);\n * }, \"+0.5\");\n * Tone.Transport.start();\n * @category Core\n */\nexport class DrawClass extends ToneWithContext<ToneWithContextOptions> {\n\treadonly name: string = \"Draw\";\n\n\t/**\n\t * The duration after which events are not invoked.\n\t */\n\texpiration: Seconds = 0.25;\n\n\t/**\n\t * The amount of time before the scheduled time\n\t * that the callback can be invoked. Default is\n\t * half the time of an animation frame (0.008 seconds).\n\t */\n\tanticipation: Seconds = 0.008;\n\n\t/**\n\t * All of the events.\n\t */\n\tprivate _events: Timeline<DrawEvent> = new Timeline();\n\n\t/**\n\t * The draw loop\n\t */\n\tprivate _boundDrawLoop = this._drawLoop.bind(this);\n\n\t/**\n\t * The animation frame id\n\t */\n\tprivate _animationFrame = -1;\n\n\t/**\n\t * Schedule a function at the given time to be invoked\n\t * on the nearest animation frame.\n\t * @param callback Callback is invoked at the given time.\n\t * @param time The time relative to the AudioContext time to invoke the callback.\n\t * @example\n\t * Tone.Transport.scheduleRepeat(time => {\n\t * \tTone.Draw.schedule(() => console.log(time), time);\n\t * }, 1);\n\t * Tone.Transport.start();\n\t */\n\tschedule(callback: () => void, time: Time): this {\n\t\tthis._events.add({\n\t\t\tcallback,\n\t\t\ttime: this.toSeconds(time),\n\t\t});\n\t\t// start the draw loop on the first event\n\t\tif (this._events.length === 1) {\n\t\t\tthis._animationFrame = requestAnimationFrame(this._boundDrawLoop);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Cancel events scheduled after the given time\n\t * @param after Time after which scheduled events will be removed from the scheduling timeline.\n\t */\n\tcancel(after?: Time): this {\n\t\tthis._events.cancel(this.toSeconds(after));\n\t\treturn this;\n\t}\n\n\t/**\n\t * The draw loop\n\t */\n\tprivate _drawLoop(): void {\n\t\tconst now = this.context.currentTime;\n\t\tthis._events.forEachBefore(now + this.anticipation, (event) => {\n\t\t\tif (now - event.time <= this.expiration) {\n\t\t\t\tevent.callback();\n\t\t\t}\n\t\t\tthis._events.remove(event);\n\t\t});\n\t\tif (this._events.length > 0) {\n\t\t\tthis._animationFrame = requestAnimationFrame(this._boundDrawLoop);\n\t\t}\n\t}\n\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis._events.dispose();\n\t\tcancelAnimationFrame(this._animationFrame);\n\t\treturn this;\n\t}\n}\n\n//-------------------------------------\n// \tINITIALIZATION\n//-------------------------------------\n\nonContextInit((context) => {\n\tcontext.draw = new DrawClass({ context });\n});\n\nonContextClose((context) => {\n\tcontext.draw.dispose();\n});\n","import { Tone } from \"../Tone.js\";\nimport { isDefined } from \"./TypeCheck.js\";\nimport { assert } from \"./Debug.js\";\n\n/**\n * An IntervalTimeline event must have a time and duration\n */\nexport interface IntervalTimelineEvent {\n\ttime: number;\n\tduration: number;\n\t[propName: string]: any;\n}\n\ntype IteratorCallback = (event: IntervalTimelineEvent) => void;\n\n/**\n * Similar to Tone.Timeline, but all events represent\n * intervals with both \"time\" and \"duration\" times. The\n * events are placed in a tree structure optimized\n * for querying an intersection point with the timeline\n * events. Internally uses an [Interval Tree](https://en.wikipedia.org/wiki/Interval_tree)\n * to represent the data.\n * @internal\n */\nexport class IntervalTimeline extends Tone {\n\treadonly name: string = \"IntervalTimeline\";\n\n\t/**\n\t * The root node of the inteval tree\n\t */\n\tprivate _root: IntervalNode | null = null;\n\n\t/**\n\t * Keep track of the length of the timeline.\n\t */\n\tprivate _length = 0;\n\n\t/**\n\t * The event to add to the timeline. All events must\n\t * have a time and duration value\n\t * @param event The event to add to the timeline\n\t */\n\tadd(event: IntervalTimelineEvent): this {\n\t\tassert(isDefined(event.time), \"Events must have a time property\");\n\t\tassert(\n\t\t\tisDefined(event.duration),\n\t\t\t\"Events must have a duration parameter\"\n\t\t);\n\n\t\tevent.time = event.time.valueOf();\n\t\tlet node: IntervalNode | null = new IntervalNode(\n\t\t\tevent.time,\n\t\t\tevent.time + event.duration,\n\t\t\tevent\n\t\t);\n\t\tif (this._root === null) {\n\t\t\tthis._root = node;\n\t\t} else {\n\t\t\tthis._root.insert(node);\n\t\t}\n\t\tthis._length++;\n\t\t// Restructure tree to be balanced\n\t\twhile (node !== null) {\n\t\t\tnode.updateHeight();\n\t\t\tnode.updateMax();\n\t\t\tthis._rebalance(node);\n\t\t\tnode = node.parent;\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Remove an event from the timeline.\n\t * @param event The event to remove from the timeline\n\t */\n\tremove(event: IntervalTimelineEvent): this {\n\t\tif (this._root !== null) {\n\t\t\tconst results: IntervalNode[] = [];\n\t\t\tthis._root.search(event.time, results);\n\t\t\tfor (const node of results) {\n\t\t\t\tif (node.event === event) {\n\t\t\t\t\tthis._removeNode(node);\n\t\t\t\t\tthis._length--;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * The number of items in the timeline.\n\t * @readOnly\n\t */\n\tget length(): number {\n\t\treturn this._length;\n\t}\n\n\t/**\n\t * Remove events whose time time is after the given time\n\t * @param after The time to query.\n\t */\n\tcancel(after: number): this {\n\t\tthis.forEachFrom(after, (event) => this.remove(event));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Set the root node as the given node\n\t */\n\tprivate _setRoot(node: IntervalNode | null): void {\n\t\tthis._root = node;\n\t\tif (this._root !== null) {\n\t\t\tthis._root.parent = null;\n\t\t}\n\t}\n\n\t/**\n\t * Replace the references to the node in the node's parent\n\t * with the replacement node.\n\t */\n\tprivate _replaceNodeInParent(\n\t\tnode: IntervalNode,\n\t\treplacement: IntervalNode | null\n\t): void {\n\t\tif (node.parent !== null) {\n\t\t\tif (node.isLeftChild()) {\n\t\t\t\tnode.parent.left = replacement;\n\t\t\t} else {\n\t\t\t\tnode.parent.right = replacement;\n\t\t\t}\n\t\t\tthis._rebalance(node.parent);\n\t\t} else {\n\t\t\tthis._setRoot(replacement);\n\t\t}\n\t}\n\n\t/**\n\t * Remove the node from the tree and replace it with\n\t * a successor which follows the schema.\n\t */\n\tprivate _removeNode(node: IntervalNode): void {\n\t\tif (node.left === null && node.right === null) {\n\t\t\tthis._replaceNodeInParent(node, null);\n\t\t} else if (node.right === null) {\n\t\t\tthis._replaceNodeInParent(node, node.left);\n\t\t} else if (node.left === null) {\n\t\t\tthis._replaceNodeInParent(node, node.right);\n\t\t} else {\n\t\t\tconst balance = node.getBalance();\n\t\t\tlet replacement: IntervalNode;\n\t\t\tlet temp: IntervalNode | null = null;\n\t\t\tif (balance > 0) {\n\t\t\t\tif (node.left.right === null) {\n\t\t\t\t\treplacement = node.left;\n\t\t\t\t\treplacement.right = node.right;\n\t\t\t\t\ttemp = replacement;\n\t\t\t\t} else {\n\t\t\t\t\treplacement = node.left.right;\n\t\t\t\t\twhile (replacement.right !== null) {\n\t\t\t\t\t\treplacement = replacement.right;\n\t\t\t\t\t}\n\t\t\t\t\tif (replacement.parent) {\n\t\t\t\t\t\treplacement.parent.right = replacement.left;\n\t\t\t\t\t\ttemp = replacement.parent;\n\t\t\t\t\t\treplacement.left = node.left;\n\t\t\t\t\t\treplacement.right = node.right;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (node.right.left === null) {\n\t\t\t\treplacement = node.right;\n\t\t\t\treplacement.left = node.left;\n\t\t\t\ttemp = replacement;\n\t\t\t} else {\n\t\t\t\treplacement = node.right.left;\n\t\t\t\twhile (replacement.left !== null) {\n\t\t\t\t\treplacement = replacement.left;\n\t\t\t\t}\n\t\t\t\tif (replacement.parent) {\n\t\t\t\t\treplacement.parent.left = replacement.right;\n\t\t\t\t\ttemp = replacement.parent;\n\t\t\t\t\treplacement.left = node.left;\n\t\t\t\t\treplacement.right = node.right;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (node.parent !== null) {\n\t\t\t\tif (node.isLeftChild()) {\n\t\t\t\t\tnode.parent.left = replacement;\n\t\t\t\t} else {\n\t\t\t\t\tnode.parent.right = replacement;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthis._setRoot(replacement);\n\t\t\t}\n\t\t\tif (temp) {\n\t\t\t\tthis._rebalance(temp);\n\t\t\t}\n\t\t}\n\t\tnode.dispose();\n\t}\n\n\t/**\n\t * Rotate the tree to the left\n\t */\n\tprivate _rotateLeft(node: IntervalNode): void {\n\t\tconst parent = node.parent;\n\t\tconst isLeftChild = node.isLeftChild();\n\n\t\t// Make node.right the new root of this sub tree (instead of node)\n\t\tconst pivotNode = node.right;\n\t\tif (pivotNode) {\n\t\t\tnode.right = pivotNode.left;\n\t\t\tpivotNode.left = node;\n\t\t}\n\n\t\tif (parent !== null) {\n\t\t\tif (isLeftChild) {\n\t\t\t\tparent.left = pivotNode;\n\t\t\t} else {\n\t\t\t\tparent.right = pivotNode;\n\t\t\t}\n\t\t} else {\n\t\t\tthis._setRoot(pivotNode);\n\t\t}\n\t}\n\n\t/**\n\t * Rotate the tree to the right\n\t */\n\tprivate _rotateRight(node: IntervalNode): void {\n\t\tconst parent = node.parent;\n\t\tconst isLeftChild = node.isLeftChild();\n\n\t\t// Make node.left the new root of this sub tree (instead of node)\n\t\tconst pivotNode = node.left;\n\t\tif (pivotNode) {\n\t\t\tnode.left = pivotNode.right;\n\t\t\tpivotNode.right = node;\n\t\t}\n\n\t\tif (parent !== null) {\n\t\t\tif (isLeftChild) {\n\t\t\t\tparent.left = pivotNode;\n\t\t\t} else {\n\t\t\t\tparent.right = pivotNode;\n\t\t\t}\n\t\t} else {\n\t\t\tthis._setRoot(pivotNode);\n\t\t}\n\t}\n\n\t/**\n\t * Balance the BST\n\t */\n\tprivate _rebalance(node: IntervalNode): void {\n\t\tconst balance = node.getBalance();\n\t\tif (balance > 1 && node.left) {\n\t\t\tif (node.left.getBalance() < 0) {\n\t\t\t\tthis._rotateLeft(node.left);\n\t\t\t} else {\n\t\t\t\tthis._rotateRight(node);\n\t\t\t}\n\t\t} else if (balance < -1 && node.right) {\n\t\t\tif (node.right.getBalance() > 0) {\n\t\t\t\tthis._rotateRight(node.right);\n\t\t\t} else {\n\t\t\t\tthis._rotateLeft(node);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Get an event whose time and duration span the give time. Will\n\t * return the match whose \"time\" value is closest to the given time.\n\t * @return The event which spans the desired time\n\t */\n\tget(time: number): IntervalTimelineEvent | null {\n\t\tif (this._root !== null) {\n\t\t\tconst results: IntervalNode[] = [];\n\t\t\tthis._root.search(time, results);\n\t\t\tif (results.length > 0) {\n\t\t\t\tlet max = results[0];\n\t\t\t\tfor (let i = 1; i < results.length; i++) {\n\t\t\t\t\tif (results[i].low > max.low) {\n\t\t\t\t\t\tmax = results[i];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn max.event;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\t/**\n\t * Iterate over everything in the timeline.\n\t * @param callback The callback to invoke with every item\n\t */\n\tforEach(callback: IteratorCallback): this {\n\t\tif (this._root !== null) {\n\t\t\tconst allNodes: IntervalNode[] = [];\n\t\t\tthis._root.traverse((node) => allNodes.push(node));\n\t\t\tallNodes.forEach((node) => {\n\t\t\t\tif (node.event) {\n\t\t\t\t\tcallback(node.event);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Iterate over everything in the array in which the given time\n\t * overlaps with the time and duration time of the event.\n\t * @param time The time to check if items are overlapping\n\t * @param callback The callback to invoke with every item\n\t */\n\tforEachAtTime(time: number, callback: IteratorCallback): this {\n\t\tif (this._root !== null) {\n\t\t\tconst results: IntervalNode[] = [];\n\t\t\tthis._root.search(time, results);\n\t\t\tresults.forEach((node) => {\n\t\t\t\tif (node.event) {\n\t\t\t\t\tcallback(node.event);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Iterate over everything in the array in which the time is greater\n\t * than or equal to the given time.\n\t * @param time The time to check if items are before\n\t * @param callback The callback to invoke with every item\n\t */\n\tforEachFrom(time: number, callback: IteratorCallback): this {\n\t\tif (this._root !== null) {\n\t\t\tconst results: IntervalNode[] = [];\n\t\t\tthis._root.searchAfter(time, results);\n\t\t\tresults.forEach((node) => {\n\t\t\t\tif (node.event) {\n\t\t\t\t\tcallback(node.event);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Clean up\n\t */\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tif (this._root !== null) {\n\t\t\tthis._root.traverse((node) => node.dispose());\n\t\t}\n\t\tthis._root = null;\n\t\treturn this;\n\t}\n}\n\n//-------------------------------------\n// \tINTERVAL NODE HELPER\n//-------------------------------------\n\n/**\n * Represents a node in the binary search tree, with the addition\n * of a \"high\" value which keeps track of the highest value of\n * its children.\n * References:\n * https://brooknovak.wordpress.com/2013/12/07/augmented-interval-tree-in-c/\n * http://www.mif.vu.lt/~valdas/ALGORITMAI/LITERATURA/Cormen/Cormen.pdf\n * @param low\n * @param high\n */\nclass IntervalNode {\n\t// the event container\n\tevent: IntervalTimelineEvent | null;\n\t// the low value\n\tlow: number;\n\t// the high value\n\thigh: number;\n\t// the high value for this and all child nodes\n\tmax: number;\n\t// the nodes to the left\n\tprivate _left: IntervalNode | null = null;\n\t// the nodes to the right\n\tprivate _right: IntervalNode | null = null;\n\t// the parent node\n\tparent: IntervalNode | null = null;\n\t// the number of child nodes\n\theight = 0;\n\n\tconstructor(low: number, high: number, event: IntervalTimelineEvent) {\n\t\tthis.event = event;\n\t\t// the low value\n\t\tthis.low = low;\n\t\t// the high value\n\t\tthis.high = high;\n\t\t// the high value for this and all child nodes\n\t\tthis.max = this.high;\n\t}\n\n\t/**\n\t * Insert a node into the correct spot in the tree\n\t */\n\tinsert(node: IntervalNode): void {\n\t\tif (node.low <= this.low) {\n\t\t\tif (this.left === null) {\n\t\t\t\tthis.left = node;\n\t\t\t} else {\n\t\t\t\tthis.left.insert(node);\n\t\t\t}\n\t\t} else if (this.right === null) {\n\t\t\tthis.right = node;\n\t\t} else {\n\t\t\tthis.right.insert(node);\n\t\t}\n\t}\n\n\t/**\n\t * Search the tree for nodes which overlap\n\t * with the given point\n\t * @param point The point to query\n\t * @param results The array to put the results\n\t */\n\tsearch(point: number, results: IntervalNode[]): void {\n\t\t// If p is to the right of the rightmost point of any interval\n\t\t// in this node and all children, there won't be any matches.\n\t\tif (point > this.max) {\n\t\t\treturn;\n\t\t}\n\t\t// Search left children\n\t\tif (this.left !== null) {\n\t\t\tthis.left.search(point, results);\n\t\t}\n\t\t// Check this node\n\t\tif (this.low <= point && this.high > point) {\n\t\t\tresults.push(this);\n\t\t}\n\t\t// If p is to the left of the time of this interval,\n\t\t// then it can't be in any child to the right.\n\t\tif (this.low > point) {\n\t\t\treturn;\n\t\t}\n\t\t// Search right children\n\t\tif (this.right !== null) {\n\t\t\tthis.right.search(point, results);\n\t\t}\n\t}\n\n\t/**\n\t * Search the tree for nodes which are less\n\t * than the given point\n\t * @param point The point to query\n\t * @param results The array to put the results\n\t */\n\tsearchAfter(point: number, results: IntervalNode[]): void {\n\t\t// Check this node\n\t\tif (this.low >= point) {\n\t\t\tresults.push(this);\n\t\t\tif (this.left !== null) {\n\t\t\t\tthis.left.searchAfter(point, results);\n\t\t\t}\n\t\t}\n\t\t// search the right side\n\t\tif (this.right !== null) {\n\t\t\tthis.right.searchAfter(point, results);\n\t\t}\n\t}\n\n\t/**\n\t * Invoke the callback on this element and both it's branches\n\t * @param {Function} callback\n\t */\n\ttraverse(callback: (self: IntervalNode) => void): void {\n\t\tcallback(this);\n\t\tif (this.left !== null) {\n\t\t\tthis.left.traverse(callback);\n\t\t}\n\t\tif (this.right !== null) {\n\t\t\tthis.right.traverse(callback);\n\t\t}\n\t}\n\n\t/**\n\t * Update the height of the node\n\t */\n\tupdateHeight(): void {\n\t\tif (this.left !== null && this.right !== null) {\n\t\t\tthis.height = Math.max(this.left.height, this.right.height) + 1;\n\t\t} else if (this.right !== null) {\n\t\t\tthis.height = this.right.height + 1;\n\t\t} else if (this.left !== null) {\n\t\t\tthis.height = this.left.height + 1;\n\t\t} else {\n\t\t\tthis.height = 0;\n\t\t}\n\t}\n\n\t/**\n\t * Update the height of the node\n\t */\n\tupdateMax(): void {\n\t\tthis.max = this.high;\n\t\tif (this.left !== null) {\n\t\t\tthis.max = Math.max(this.max, this.left.max);\n\t\t}\n\t\tif (this.right !== null) {\n\t\t\tthis.max = Math.max(this.max, this.right.max);\n\t\t}\n\t}\n\n\t/**\n\t * The balance is how the leafs are distributed on the node\n\t * @return Negative numbers are balanced to the right\n\t */\n\tgetBalance(): number {\n\t\tlet balance = 0;\n\t\tif (this.left !== null && this.right !== null) {\n\t\t\tbalance = this.left.height - this.right.height;\n\t\t} else if (this.left !== null) {\n\t\t\tbalance = this.left.height + 1;\n\t\t} else if (this.right !== null) {\n\t\t\tbalance = -(this.right.height + 1);\n\t\t}\n\t\treturn balance;\n\t}\n\n\t/**\n\t * @returns true if this node is the left child of its parent\n\t */\n\tisLeftChild(): boolean {\n\t\treturn this.parent !== null && this.parent.left === this;\n\t}\n\n\t/**\n\t * get/set the left node\n\t */\n\tget left(): IntervalNode | null {\n\t\treturn this._left;\n\t}\n\n\tset left(node: IntervalNode | null) {\n\t\tthis._left = node;\n\t\tif (node !== null) {\n\t\t\tnode.parent = this;\n\t\t}\n\t\tthis.updateHeight();\n\t\tthis.updateMax();\n\t}\n\n\t/**\n\t * get/set the right node\n\t */\n\tget right(): IntervalNode | null {\n\t\treturn this._right;\n\t}\n\n\tset right(node: IntervalNode | null) {\n\t\tthis._right = node;\n\t\tif (node !== null) {\n\t\t\tnode.parent = this;\n\t\t}\n\t\tthis.updateHeight();\n\t\tthis.updateMax();\n\t}\n\n\t/**\n\t * null out references.\n\t */\n\tdispose(): void {\n\t\tthis.parent = null;\n\t\tthis._left = null;\n\t\tthis._right = null;\n\t\tthis.event = null;\n\t}\n}\n","import { Timeline, TimelineEvent } from \"./Timeline.js\";\nimport { Tone } from \"../Tone.js\";\nimport { Seconds } from \"../type/Units.js\";\n\ninterface TimelineValueEvent<T> extends TimelineEvent {\n\tvalue: T;\n}\n\n/**\n * Represents a single value which is gettable and settable in a timed way\n */\nexport class TimelineValue<Type> extends Tone {\n\treadonly name: string = \"TimelineValue\";\n\n\t/**\n\t * The timeline which stores the values\n\t */\n\tprivate _timeline: Timeline<TimelineValueEvent<Type>> = new Timeline({\n\t\tmemory: 10,\n\t});\n\n\t/**\n\t * Hold the value to return if there is no scheduled values\n\t */\n\tprivate _initialValue: Type;\n\n\t/**\n\t * @param initialValue The value to return if there is no scheduled values\n\t */\n\tconstructor(initialValue: Type) {\n\t\tsuper();\n\t\tthis._initialValue = initialValue;\n\t}\n\n\t/**\n\t * Set the value at the given time\n\t */\n\tset(value: Type, time: Seconds): this {\n\t\tthis._timeline.add({\n\t\t\tvalue,\n\t\t\ttime,\n\t\t});\n\t\treturn this;\n\t}\n\n\t/**\n\t * Get the value at the given time\n\t */\n\tget(time: Seconds): Type {\n\t\tconst event = this._timeline.get(time);\n\t\tif (event) {\n\t\t\treturn event.value;\n\t\t} else {\n\t\t\treturn this._initialValue;\n\t\t}\n\t}\n}\n","import { optionsFromArguments } from \"../core/util/Defaults.js\";\nimport {\n\tInputNode,\n\tToneAudioNode,\n\tToneAudioNodeOptions,\n} from \"../core/context/ToneAudioNode.js\";\nimport { connectSignal } from \"./Signal.js\";\n\nexport type SignalOperatorOptions = ToneAudioNodeOptions;\n\n/**\n * A signal operator has an input and output and modifies the signal.\n */\nexport abstract class SignalOperator<\n\tOptions extends SignalOperatorOptions,\n> extends ToneAudioNode<Options> {\n\tconstructor(options?: Partial<Options>);\n\tconstructor() {\n\t\tsuper(\n\t\t\toptionsFromArguments(SignalOperator.getDefaults(), arguments, [\n\t\t\t\t\"context\",\n\t\t\t])\n\t\t);\n\t}\n\n\tconnect(destination: InputNode, outputNum = 0, inputNum = 0): this {\n\t\tconnectSignal(this, destination, outputNum, inputNum);\n\t\treturn this;\n\t}\n}\n","import { ToneAudioNodeOptions } from \"../core/context/ToneAudioNode.js\";\nimport { optionsFromArguments } from \"../core/util/Defaults.js\";\nimport { isArray, isFunction } from \"../core/util/TypeCheck.js\";\nimport { assert } from \"../core/util/Debug.js\";\nimport { Signal } from \"./Signal.js\";\nimport { SignalOperator } from \"./SignalOperator.js\";\n\nexport type WaveShaperMappingFn = (value: number, index?: number) => number;\n\ntype WaveShaperMapping = WaveShaperMappingFn | number[] | Float32Array;\n\ninterface WaveShaperOptions extends ToneAudioNodeOptions {\n\tmapping?: WaveShaperMapping;\n\tlength: number;\n\tcurve?: number[] | Float32Array;\n}\n\n/**\n * Wraps the native Web Audio API\n * [WaveShaperNode](http://webaudio.github.io/web-audio-api/#the-waveshapernode-interface).\n *\n * @example\n * const osc = new Tone.Oscillator().toDestination().start();\n * // multiply the output of the signal by 2 using the waveshaper's function\n * const timesTwo = new Tone.WaveShaper((val) => val * 2, 2048).connect(osc.frequency);\n * const signal = new Tone.Signal(440).connect(timesTwo);\n * @category Signal\n */\nexport class WaveShaper extends SignalOperator<WaveShaperOptions> {\n\treadonly name: string = \"WaveShaper\";\n\n\t/**\n\t * the waveshaper node\n\t */\n\tprivate _shaper: WaveShaperNode = this.context.createWaveShaper();\n\n\t/**\n\t * The input to the waveshaper node.\n\t */\n\tinput = this._shaper;\n\n\t/**\n\t * The output from the waveshaper node\n\t */\n\toutput = this._shaper;\n\n\t/**\n\t * @param mapping The function used to define the values.\n\t * The mapping function should take two arguments:\n\t * the first is the value at the current position\n\t * and the second is the array position.\n\t * If the argument is an array, that array will be\n\t * set as the wave shaping function. The input\n\t * signal is an AudioRange [-1, 1] value and the output\n\t * signal can take on any numerical values.\n\t *\n\t * @param length The length of the WaveShaperNode buffer.\n\t */\n\tconstructor(mapping?: WaveShaperMapping, length?: number);\n\tconstructor(options?: Partial<WaveShaperOptions>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(\n\t\t\tWaveShaper.getDefaults(),\n\t\t\targuments,\n\t\t\t[\"mapping\", \"length\"]\n\t\t);\n\t\tsuper(options);\n\n\t\tif (\n\t\t\tisArray(options.mapping) ||\n\t\t\toptions.mapping instanceof Float32Array\n\t\t) {\n\t\t\tthis.curve = Float32Array.from(options.mapping);\n\t\t} else if (isFunction(options.mapping)) {\n\t\t\tthis.setMap(options.mapping, options.length);\n\t\t}\n\t}\n\n\tstatic getDefaults(): WaveShaperOptions {\n\t\treturn Object.assign(Signal.getDefaults(), {\n\t\t\tlength: 1024,\n\t\t});\n\t}\n\n\t/**\n\t * Uses a mapping function to set the value of the curve.\n\t * @param mapping The function used to define the values.\n\t * The mapping function take two arguments:\n\t * the first is the value at the current position\n\t * which goes from -1 to 1 over the number of elements\n\t * in the curve array. The second argument is the array position.\n\t * @example\n\t * const shaper = new Tone.WaveShaper();\n\t * // map the input signal from [-1, 1] to [0, 10]\n\t * shaper.setMap((val, index) => (val + 1) * 5);\n\t */\n\tsetMap(mapping: WaveShaperMappingFn, length = 1024): this {\n\t\tconst array = new Float32Array(length);\n\t\tfor (let i = 0, len = length; i < len; i++) {\n\t\t\tconst normalized = (i / (len - 1)) * 2 - 1;\n\t\t\tarray[i] = mapping(normalized, i);\n\t\t}\n\t\tthis.curve = array;\n\t\treturn this;\n\t}\n\n\t/**\n\t * The array to set as the waveshaper curve. For linear curves\n\t * array length does not make much difference, but for complex curves\n\t * longer arrays will provide smoother interpolation.\n\t */\n\tget curve(): Float32Array | null {\n\t\treturn this._shaper.curve;\n\t}\n\n\tset curve(mapping: Float32Array | null) {\n\t\tthis._shaper.curve = mapping;\n\t}\n\n\t/**\n\t * Specifies what type of oversampling (if any) should be used when\n\t * applying the shaping curve. Can either be \"none\", \"2x\" or \"4x\".\n\t */\n\tget oversample(): OverSampleType {\n\t\treturn this._shaper.oversample;\n\t}\n\n\tset oversample(oversampling: OverSampleType) {\n\t\tconst isOverSampleType = [\"none\", \"2x\", \"4x\"].some((str) =>\n\t\t\tstr.includes(oversampling)\n\t\t);\n\t\tassert(\n\t\t\tisOverSampleType,\n\t\t\t\"oversampling must be either 'none', '2x', or '4x'\"\n\t\t);\n\t\tthis._shaper.oversample = oversampling;\n\t}\n\n\t/**\n\t * Clean up.\n\t */\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis._shaper.disconnect();\n\t\treturn this;\n\t}\n}\n","import { WaveShaper, WaveShaperMappingFn } from \"./WaveShaper.js\";\nimport { optionsFromArguments } from \"../core/util/Defaults.js\";\nimport { SignalOperator } from \"./SignalOperator.js\";\nimport { ToneAudioNodeOptions } from \"../core/context/ToneAudioNode.js\";\n\nexport interface PowOptions extends ToneAudioNodeOptions {\n\tvalue: number;\n}\n\n/**\n * Pow applies an exponent to the incoming signal. The incoming signal must be AudioRange [-1, 1]\n *\n * @example\n * const pow = new Tone.Pow(2);\n * const sig = new Tone.Signal(0.5).connect(pow);\n * // output of pow is 0.25.\n * @category Signal\n */\nexport class Pow extends SignalOperator<PowOptions> {\n\treadonly name: string = \"Pow\";\n\n\tprivate _exponent: number;\n\n\tprivate _exponentScaler: WaveShaper;\n\n\tinput: WaveShaper;\n\n\toutput: WaveShaper;\n\n\t/**\n\t * @param value Constant exponent value to use\n\t */\n\tconstructor(value?: number);\n\tconstructor(options?: Partial<PowOptions>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(Pow.getDefaults(), arguments, [\n\t\t\t\"value\",\n\t\t]);\n\t\tsuper(options);\n\n\t\tthis._exponentScaler =\n\t\t\tthis.input =\n\t\t\tthis.output =\n\t\t\t\tnew WaveShaper({\n\t\t\t\t\tcontext: this.context,\n\t\t\t\t\tmapping: this._expFunc(options.value),\n\t\t\t\t\tlength: 8192,\n\t\t\t\t});\n\n\t\tthis._exponent = options.value;\n\t}\n\n\tstatic getDefaults(): PowOptions {\n\t\treturn Object.assign(SignalOperator.getDefaults(), {\n\t\t\tvalue: 1,\n\t\t});\n\t}\n\n\t/**\n\t * the function which maps the waveshaper\n\t * @param exponent exponent value\n\t */\n\tprivate _expFunc(exponent: number): WaveShaperMappingFn {\n\t\treturn (val: number) => {\n\t\t\treturn Math.pow(Math.abs(val), exponent);\n\t\t};\n\t}\n\n\t/**\n\t * The value of the exponent.\n\t */\n\tget value(): number {\n\t\treturn this._exponent;\n\t}\n\tset value(exponent: number) {\n\t\tthis._exponent = exponent;\n\t\tthis._exponentScaler.setMap(this._expFunc(this._exponent));\n\t}\n\n\t/**\n\t * Clean up.\n\t */\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis._exponentScaler.dispose();\n\t\treturn this;\n\t}\n}\n","import { Seconds, Ticks } from \"../type/Units.js\";\nimport { noOp } from \"../util/Interface.js\";\nimport type { TransportClass as Transport } from \"./Transport.js\";\n\nexport interface TransportEventOptions {\n\tcallback: (time: number) => void;\n\tonce: boolean;\n\ttime: Ticks;\n}\n\n/**\n * TransportEvent is an internal class used by {@link TransportClass}\n * to schedule events. Do no invoke this class directly, it is\n * handled from within Tone.Transport.\n */\nexport class TransportEvent {\n\t/**\n\t * Reference to the Transport that created it\n\t */\n\tprotected transport: Transport;\n\n\t/**\n\t * The unique id of the event\n\t */\n\tid: number = TransportEvent._eventId++;\n\n\t/**\n\t * The time the event starts\n\t */\n\ttime: Ticks;\n\n\t/**\n\t * The callback to invoke\n\t */\n\tprivate callback?: (time: Seconds) => void;\n\n\t/**\n\t * If the event should be removed after being invoked.\n\t */\n\tprivate _once: boolean;\n\n\t/**\n\t * The remaining value between the passed in time, and Math.floor(time).\n\t * This value is later added back when scheduling to get sub-tick precision.\n\t */\n\tprotected _remainderTime = 0;\n\n\t/**\n\t * @param transport The transport object which the event belongs to\n\t */\n\tconstructor(transport: Transport, opts: Partial<TransportEventOptions>) {\n\t\tconst options: TransportEventOptions = Object.assign(\n\t\t\tTransportEvent.getDefaults(),\n\t\t\topts\n\t\t);\n\n\t\tthis.transport = transport;\n\t\tthis.callback = options.callback;\n\t\tthis._once = options.once;\n\t\tthis.time = Math.floor(options.time);\n\t\tthis._remainderTime = options.time - this.time;\n\t}\n\n\tstatic getDefaults(): TransportEventOptions {\n\t\treturn {\n\t\t\tcallback: noOp,\n\t\t\tonce: false,\n\t\t\ttime: 0,\n\t\t};\n\t}\n\n\t/**\n\t * Current ID counter\n\t */\n\tprivate static _eventId = 0;\n\n\t/**\n\t * Get the time and remainder time.\n\t */\n\tprotected get floatTime(): number {\n\t\treturn this.time + this._remainderTime;\n\t}\n\n\t/**\n\t * Invoke the event callback.\n\t * @param time The AudioContext time in seconds of the event\n\t */\n\tinvoke(time: Seconds): void {\n\t\tif (this.callback) {\n\t\t\tconst tickDuration = this.transport.bpm.getDurationOfTicks(1, time);\n\t\t\tthis.callback(time + this._remainderTime * tickDuration);\n\t\t\tif (this._once) {\n\t\t\t\tthis.transport.clear(this.id);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Clean up\n\t */\n\tdispose(): this {\n\t\tthis.callback = undefined;\n\t\treturn this;\n\t}\n}\n","import { BaseContext } from \"../context/BaseContext.js\";\nimport { TicksClass } from \"../type/Ticks.js\";\nimport { Seconds, Ticks, Time } from \"../type/Units.js\";\nimport { TransportEvent, TransportEventOptions } from \"./TransportEvent.js\";\nimport { GT, LT } from \"../util/Math.js\";\nimport type { TransportClass as Transport } from \"./Transport.js\";\n\ninterface TransportRepeatEventOptions extends TransportEventOptions {\n\tinterval: Ticks;\n\tduration: Ticks;\n}\n\n/**\n * TransportRepeatEvent is an internal class used by Tone.Transport\n * to schedule repeat events. This class should not be instantiated directly.\n */\nexport class TransportRepeatEvent extends TransportEvent {\n\t/**\n\t * When the event should stop repeating\n\t */\n\tprivate duration: Ticks;\n\n\t/**\n\t * The interval of the repeated event\n\t */\n\tprivate _interval: Ticks;\n\n\t/**\n\t * The ID of the current timeline event\n\t */\n\tprivate _currentId = -1;\n\n\t/**\n\t * The ID of the next timeline event\n\t */\n\tprivate _nextId = -1;\n\n\t/**\n\t * The time of the next event\n\t */\n\tprivate _nextTick = this.time;\n\n\t/**\n\t * a reference to the bound start method\n\t */\n\tprivate _boundRestart = this._restart.bind(this);\n\n\t/**\n\t * The audio context belonging to this event\n\t */\n\tprotected context: BaseContext;\n\n\t/**\n\t * @param transport The transport object which the event belongs to\n\t */\n\tconstructor(\n\t\ttransport: Transport,\n\t\topts: Partial<TransportRepeatEventOptions>\n\t) {\n\t\tsuper(transport, opts);\n\n\t\tconst options = Object.assign(TransportRepeatEvent.getDefaults(), opts);\n\n\t\tthis.duration = options.duration;\n\t\tthis._interval = options.interval;\n\t\tthis._nextTick = options.time;\n\t\tthis.transport.on(\"start\", this._boundRestart);\n\t\tthis.transport.on(\"loopStart\", this._boundRestart);\n\t\tthis.transport.on(\"ticks\", this._boundRestart);\n\t\tthis.context = this.transport.context;\n\t\tthis._restart();\n\t}\n\n\tstatic getDefaults(): TransportRepeatEventOptions {\n\t\treturn Object.assign({}, TransportEvent.getDefaults(), {\n\t\t\tduration: Infinity,\n\t\t\tinterval: 1,\n\t\t\tonce: false,\n\t\t});\n\t}\n\n\t/**\n\t * Invoke the callback. Returns the tick time which\n\t * the next event should be scheduled at.\n\t * @param time The AudioContext time in seconds of the event\n\t */\n\tinvoke(time: Seconds): void {\n\t\t// create more events if necessary\n\t\tthis._createEvents(time);\n\t\t// call the super class\n\t\tsuper.invoke(time);\n\t}\n\n\t/**\n\t * Create an event on the transport on the nextTick\n\t */\n\tprivate _createEvent(): number {\n\t\tif (LT(this._nextTick, this.floatTime + this.duration)) {\n\t\t\treturn this.transport.scheduleOnce(\n\t\t\t\tthis.invoke.bind(this),\n\t\t\t\tnew TicksClass(this.context, this._nextTick).toSeconds()\n\t\t\t);\n\t\t}\n\t\treturn -1;\n\t}\n\n\t/**\n\t * Push more events onto the timeline to keep up with the position of the timeline\n\t */\n\tprivate _createEvents(time: Seconds): void {\n\t\t// schedule the next event\n\t\t// const ticks = this.transport.getTicksAtTime(time);\n\t\t// if the next tick is within the bounds set by \"duration\"\n\t\tif (\n\t\t\tLT(this._nextTick + this._interval, this.floatTime + this.duration)\n\t\t) {\n\t\t\tthis._nextTick += this._interval;\n\t\t\tthis._currentId = this._nextId;\n\t\t\tthis._nextId = this.transport.scheduleOnce(\n\t\t\t\tthis.invoke.bind(this),\n\t\t\t\tnew TicksClass(this.context, this._nextTick).toSeconds()\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Re-compute the events when the transport time has changed from a start/ticks/loopStart event\n\t */\n\tprivate _restart(time?: Time): void {\n\t\tthis.transport.clear(this._currentId);\n\t\tthis.transport.clear(this._nextId);\n\t\t// start at the first event\n\t\tthis._nextTick = this.floatTime;\n\t\tconst ticks = this.transport.getTicksAtTime(time);\n\t\tif (GT(ticks, this.time)) {\n\t\t\t// the event is not being scheduled from the beginning and should be offset\n\t\t\tthis._nextTick =\n\t\t\t\tthis.floatTime +\n\t\t\t\tMath.ceil((ticks - this.floatTime) / this._interval) *\n\t\t\t\t\tthis._interval;\n\t\t}\n\t\tthis._currentId = this._createEvent();\n\t\tthis._nextTick += this._interval;\n\t\tthis._nextId = this._createEvent();\n\t}\n\n\t/**\n\t * Clean up\n\t */\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis.transport.clear(this._currentId);\n\t\tthis.transport.clear(this._nextId);\n\t\tthis.transport.off(\"start\", this._boundRestart);\n\t\tthis.transport.off(\"loopStart\", this._boundRestart);\n\t\tthis.transport.off(\"ticks\", this._boundRestart);\n\t\treturn this;\n\t}\n}\n","import { TimeClass } from \"../../core/type/Time.js\";\nimport { PlaybackState } from \"../../core/util/StateTimeline.js\";\nimport { TimelineValue } from \"../../core/util/TimelineValue.js\";\nimport { ToneAudioNode } from \"../../core/context/ToneAudioNode.js\";\nimport { Pow } from \"../../signal/Pow.js\";\nimport { Signal } from \"../../signal/Signal.js\";\nimport {\n\tonContextClose,\n\tonContextInit,\n} from \"../context/ContextInitialization.js\";\nimport { Gain } from \"../context/Gain.js\";\nimport {\n\tToneWithContext,\n\tToneWithContextOptions,\n} from \"../context/ToneWithContext.js\";\nimport { TicksClass } from \"../type/Ticks.js\";\nimport { TransportTimeClass } from \"../type/TransportTime.js\";\nimport {\n\tBarsBeatsSixteenths,\n\tBPM,\n\tNormalRange,\n\tSeconds,\n\tSubdivision,\n\tTicks,\n\tTime,\n\tTimeSignature,\n\tTransportTime,\n} from \"../type/Units.js\";\nimport { enterScheduledCallback } from \"../util/Debug.js\";\nimport { optionsFromArguments } from \"../util/Defaults.js\";\nimport { Emitter } from \"../util/Emitter.js\";\nimport { readOnly, writable } from \"../util/Interface.js\";\nimport { IntervalTimeline } from \"../util/IntervalTimeline.js\";\nimport { Timeline } from \"../util/Timeline.js\";\nimport { isArray, isDefined } from \"../util/TypeCheck.js\";\nimport { Clock } from \"./Clock.js\";\nimport { TickParam } from \"./TickParam.js\";\nimport { TransportEvent } from \"./TransportEvent.js\";\nimport { TransportRepeatEvent } from \"./TransportRepeatEvent.js\";\n\ninterface TransportOptions extends ToneWithContextOptions {\n\tbpm: BPM;\n\tswing: NormalRange;\n\tswingSubdivision: Subdivision;\n\ttimeSignature: number;\n\tloopStart: Time;\n\tloopEnd: Time;\n\tppq: number;\n}\n\ntype TransportEventNames =\n\t| \"start\"\n\t| \"stop\"\n\t| \"pause\"\n\t| \"loop\"\n\t| \"loopEnd\"\n\t| \"loopStart\"\n\t| \"ticks\";\n\ninterface SyncedSignalEvent {\n\tsignal: Signal;\n\tinitial: number;\n\tnodes: ToneAudioNode<any>[];\n}\n\ntype TransportCallback = (time: Seconds) => void;\n\n/**\n * Transport for timing musical events.\n * Supports tempo curves and time changes. Unlike browser-based timing (setInterval, requestAnimationFrame)\n * Transport timing events pass in the exact time of the scheduled event\n * in the argument of the callback function. Pass that time value to the object\n * you're scheduling. <br><br>\n * A single transport is created for you when the library is initialized.\n * <br><br>\n * The transport emits the events: \"start\", \"stop\", \"pause\", and \"loop\" which are\n * called with the time of that event as the argument.\n *\n * @example\n * const osc = new Tone.Oscillator().toDestination();\n * // repeated event every 8th note\n * Tone.getTransport().scheduleRepeat((time) => {\n * \t// use the callback time to schedule events\n * \tosc.start(time).stop(time + 0.1);\n * }, \"8n\");\n * // transport must be started before it starts invoking events\n * Tone.getTransport().start();\n * @category Core\n */\nexport class TransportClass\n\textends ToneWithContext<TransportOptions>\n\timplements Emitter<TransportEventNames>\n{\n\treadonly name: string = \"Transport\";\n\n\t//-------------------------------------\n\t// \tLOOPING\n\t//-------------------------------------\n\n\t/**\n\t * If the transport loops or not.\n\t */\n\tprivate _loop: TimelineValue<boolean> = new TimelineValue(false);\n\n\t/**\n\t * The loop start position in ticks\n\t */\n\tprivate _loopStart: Ticks = 0;\n\n\t/**\n\t * The loop end position in ticks\n\t */\n\tprivate _loopEnd: Ticks = 0;\n\n\t//-------------------------------------\n\t// \tCLOCK/TEMPO\n\t//-------------------------------------\n\n\t/**\n\t * Pulses per quarter is the number of ticks per quarter note.\n\t */\n\tprivate _ppq: number;\n\n\t/**\n\t * watches the main oscillator for timing ticks\n\t * initially starts at 120bpm\n\t */\n\tprivate _clock: Clock<\"bpm\">;\n\n\t/**\n\t * The Beats Per Minute of the Transport.\n\t * @example\n\t * const osc = new Tone.Oscillator().toDestination();\n\t * Tone.getTransport().bpm.value = 80;\n\t * // start/stop the oscillator every quarter note\n\t * Tone.getTransport().scheduleRepeat(time => {\n\t * \tosc.start(time).stop(time + 0.1);\n\t * }, \"4n\");\n\t * Tone.getTransport().start();\n\t * // ramp the bpm to 120 over 10 seconds\n\t * Tone.getTransport().bpm.rampTo(120, 10);\n\t */\n\tbpm: TickParam<\"bpm\">;\n\n\t/**\n\t * The time signature, or more accurately the numerator\n\t * of the time signature over a denominator of 4.\n\t */\n\tprivate _timeSignature: number;\n\n\t//-------------------------------------\n\t// \tTIMELINE EVENTS\n\t//-------------------------------------\n\n\t/**\n\t * All the events in an object to keep track by ID\n\t */\n\tprivate _scheduledEvents = {};\n\n\t/**\n\t * The scheduled events.\n\t */\n\tprivate _timeline: Timeline<TransportEvent> = new Timeline();\n\n\t/**\n\t * Repeated events\n\t */\n\tprivate _repeatedEvents: IntervalTimeline = new IntervalTimeline();\n\n\t/**\n\t * All of the synced Signals\n\t */\n\tprivate _syncedSignals: SyncedSignalEvent[] = [];\n\n\t//-------------------------------------\n\t// \tSWING\n\t//-------------------------------------\n\n\t/**\n\t * The subdivision of the swing\n\t */\n\tprivate _swingTicks: Ticks;\n\n\t/**\n\t * The swing amount\n\t */\n\tprivate _swingAmount: NormalRange = 0;\n\n\tconstructor(options?: Partial<TransportOptions>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(\n\t\t\tTransportClass.getDefaults(),\n\t\t\targuments\n\t\t);\n\t\tsuper(options);\n\n\t\t// CLOCK/TEMPO\n\t\tthis._ppq = options.ppq;\n\t\tthis._clock = new Clock({\n\t\t\tcallback: this._processTick.bind(this),\n\t\t\tcontext: this.context,\n\t\t\tfrequency: 0,\n\t\t\tunits: \"bpm\",\n\t\t});\n\t\tthis._bindClockEvents();\n\t\tthis.bpm = this._clock.frequency as unknown as TickParam<\"bpm\">;\n\t\tthis._clock.frequency.multiplier = options.ppq;\n\t\tthis.bpm.setValueAtTime(options.bpm, 0);\n\t\treadOnly(this, \"bpm\");\n\t\tthis._timeSignature = options.timeSignature;\n\n\t\t// SWING\n\t\tthis._swingTicks = options.ppq / 2; // 8n\n\t}\n\n\tstatic getDefaults(): TransportOptions {\n\t\treturn Object.assign(ToneWithContext.getDefaults(), {\n\t\t\tbpm: 120,\n\t\t\tloopEnd: \"4m\" as Subdivision,\n\t\t\tloopStart: 0,\n\t\t\tppq: 192,\n\t\t\tswing: 0,\n\t\t\tswingSubdivision: \"8n\" as Subdivision,\n\t\t\ttimeSignature: 4,\n\t\t});\n\t}\n\n\t//-------------------------------------\n\t// \tTICKS\n\t//-------------------------------------\n\n\t/**\n\t * called on every tick\n\t * @param tickTime clock relative tick time\n\t */\n\tprivate _processTick(tickTime: Seconds, ticks: Ticks): void {\n\t\t// do the loop test\n\t\tif (this._loop.get(tickTime)) {\n\t\t\tif (ticks >= this._loopEnd) {\n\t\t\t\tthis.emit(\"loopEnd\", tickTime);\n\t\t\t\tthis._clock.setTicksAtTime(this._loopStart, tickTime);\n\t\t\t\tticks = this._loopStart;\n\t\t\t\tthis.emit(\n\t\t\t\t\t\"loopStart\",\n\t\t\t\t\ttickTime,\n\t\t\t\t\tthis._clock.getSecondsAtTime(tickTime)\n\t\t\t\t);\n\t\t\t\tthis.emit(\"loop\", tickTime);\n\t\t\t}\n\t\t}\n\t\t// handle swing\n\t\tif (\n\t\t\tthis._swingAmount > 0 &&\n\t\t\tticks % this._ppq !== 0 && // not on a downbeat\n\t\t\tticks % (this._swingTicks * 2) !== 0\n\t\t) {\n\t\t\t// add some swing\n\t\t\tconst progress =\n\t\t\t\t(ticks % (this._swingTicks * 2)) / (this._swingTicks * 2);\n\t\t\tconst amount = Math.sin(progress * Math.PI) * this._swingAmount;\n\t\t\ttickTime +=\n\t\t\t\tnew TicksClass(\n\t\t\t\t\tthis.context,\n\t\t\t\t\t(this._swingTicks * 2) / 3\n\t\t\t\t).toSeconds() * amount;\n\t\t}\n\t\t// invoke the timeline events scheduled on this tick\n\t\tenterScheduledCallback(true);\n\t\tthis._timeline.forEachAtTime(ticks, (event) => event.invoke(tickTime));\n\t\tenterScheduledCallback(false);\n\t}\n\n\t//-------------------------------------\n\t// \tSCHEDULABLE EVENTS\n\t//-------------------------------------\n\n\t/**\n\t * Schedule an event along the timeline.\n\t * @param callback The callback to be invoked at the time.\n\t * @param time The time to invoke the callback at.\n\t * @return The id of the event which can be used for canceling the event.\n\t * @example\n\t * // schedule an event on the 16th measure\n\t * Tone.getTransport().schedule((time) => {\n\t * \t// invoked on measure 16\n\t * \tconsole.log(\"measure 16!\");\n\t * }, \"16:0:0\");\n\t */\n\tschedule(\n\t\tcallback: TransportCallback,\n\t\ttime: TransportTime | TransportTimeClass\n\t): number {\n\t\tconst event = new TransportEvent(this, {\n\t\t\tcallback,\n\t\t\ttime: new TransportTimeClass(this.context, time).toTicks(),\n\t\t});\n\t\treturn this._addEvent(event, this._timeline);\n\t}\n\n\t/**\n\t * Schedule a repeated event along the timeline. The event will fire\n\t * at the `interval` starting at the `startTime` and for the specified\n\t * `duration`.\n\t * @param callback The callback to invoke.\n\t * @param interval The duration between successive callbacks. Must be a positive number.\n\t * @param startTime When along the timeline the events should start being invoked.\n\t * @param duration How long the event should repeat.\n\t * @return The ID of the scheduled event. Use this to cancel the event.\n\t * @example\n\t * const osc = new Tone.Oscillator().toDestination().start();\n\t * // a callback invoked every eighth note after the first measure\n\t * Tone.getTransport().scheduleRepeat((time) => {\n\t * \tosc.start(time).stop(time + 0.1);\n\t * }, \"8n\", \"1m\");\n\t */\n\tscheduleRepeat(\n\t\tcallback: TransportCallback,\n\t\tinterval: Time | TimeClass,\n\t\tstartTime?: TransportTime | TransportTimeClass,\n\t\tduration: Time = Infinity\n\t): number {\n\t\tconst event = new TransportRepeatEvent(this, {\n\t\t\tcallback,\n\t\t\tduration: new TimeClass(this.context, duration).toTicks(),\n\t\t\tinterval: new TimeClass(this.context, interval).toTicks(),\n\t\t\ttime: new TransportTimeClass(this.context, startTime).toTicks(),\n\t\t});\n\t\t// kick it off if the Transport is started\n\t\t// @ts-ignore\n\t\treturn this._addEvent(event, this._repeatedEvents);\n\t}\n\n\t/**\n\t * Schedule an event that will be removed after it is invoked.\n\t * @param callback The callback to invoke once.\n\t * @param time The time the callback should be invoked.\n\t * @returns The ID of the scheduled event.\n\t */\n\tscheduleOnce(\n\t\tcallback: TransportCallback,\n\t\ttime: TransportTime | TransportTimeClass\n\t): number {\n\t\tconst event = new TransportEvent(this, {\n\t\t\tcallback,\n\t\t\tonce: true,\n\t\t\ttime: new TransportTimeClass(this.context, time).toTicks(),\n\t\t});\n\t\treturn this._addEvent(event, this._timeline);\n\t}\n\n\t/**\n\t * Clear the passed in event id from the timeline\n\t * @param eventId The id of the event.\n\t */\n\tclear(eventId: number): this {\n\t\tif (this._scheduledEvents.hasOwnProperty(eventId)) {\n\t\t\tconst item = this._scheduledEvents[eventId.toString()];\n\t\t\titem.timeline.remove(item.event);\n\t\t\titem.event.dispose();\n\t\t\tdelete this._scheduledEvents[eventId.toString()];\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Add an event to the correct timeline. Keep track of the\n\t * timeline it was added to.\n\t * @returns the event id which was just added\n\t */\n\tprivate _addEvent(\n\t\tevent: TransportEvent,\n\t\ttimeline: Timeline<TransportEvent>\n\t): number {\n\t\tthis._scheduledEvents[event.id.toString()] = {\n\t\t\tevent,\n\t\t\ttimeline,\n\t\t};\n\t\ttimeline.add(event);\n\t\treturn event.id;\n\t}\n\n\t/**\n\t * Remove scheduled events from the timeline after\n\t * the given time. Repeated events will be removed\n\t * if their startTime is after the given time\n\t * @param after Clear all events after this time.\n\t */\n\tcancel(after: TransportTime = 0): this {\n\t\tconst computedAfter = this.toTicks(after);\n\t\tthis._timeline.forEachFrom(computedAfter, (event) =>\n\t\t\tthis.clear(event.id)\n\t\t);\n\t\tthis._repeatedEvents.forEachFrom(computedAfter, (event) =>\n\t\t\tthis.clear(event.id)\n\t\t);\n\t\treturn this;\n\t}\n\n\t//-------------------------------------\n\t// \tSTART/STOP/PAUSE\n\t//-------------------------------------\n\n\t/**\n\t * Bind start/stop/pause events from the clock and emit them.\n\t */\n\tprivate _bindClockEvents(): void {\n\t\tthis._clock.on(\"start\", (time, offset) => {\n\t\t\toffset = new TicksClass(this.context, offset).toSeconds();\n\t\t\tthis.emit(\"start\", time, offset);\n\t\t});\n\n\t\tthis._clock.on(\"stop\", (time) => {\n\t\t\tthis.emit(\"stop\", time);\n\t\t});\n\n\t\tthis._clock.on(\"pause\", (time) => {\n\t\t\tthis.emit(\"pause\", time);\n\t\t});\n\t}\n\n\t/**\n\t * Returns the playback state of the source, either \"started\", \"stopped\", or \"paused\"\n\t */\n\tget state(): PlaybackState {\n\t\treturn this._clock.getStateAtTime(this.now());\n\t}\n\n\t/**\n\t * Start the transport and all sources synced to the transport.\n\t * @param time The time when the transport should start.\n\t * @param offset The timeline offset to start the transport.\n\t * @example\n\t * // start the transport in one second starting at beginning of the 5th measure.\n\t * Tone.getTransport().start(\"+1\", \"4:0:0\");\n\t */\n\tstart(time?: Time, offset?: TransportTime): this {\n\t\t// start the context\n\t\tthis.context.resume();\n\t\tlet offsetTicks;\n\t\tif (isDefined(offset)) {\n\t\t\toffsetTicks = this.toTicks(offset);\n\t\t}\n\t\t// start the clock\n\t\tthis._clock.start(time, offsetTicks);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Stop the transport and all sources synced to the transport.\n\t * @param time The time when the transport should stop.\n\t * @example\n\t * Tone.getTransport().stop();\n\t */\n\tstop(time?: Time): this {\n\t\tthis._clock.stop(time);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Pause the transport and all sources synced to the transport.\n\t */\n\tpause(time?: Time): this {\n\t\tthis._clock.pause(time);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Toggle the current state of the transport. If it is\n\t * started, it will stop it, otherwise it will start the Transport.\n\t * @param time The time of the event\n\t */\n\ttoggle(time?: Time): this {\n\t\ttime = this.toSeconds(time);\n\t\tif (this._clock.getStateAtTime(time) !== \"started\") {\n\t\t\tthis.start(time);\n\t\t} else {\n\t\t\tthis.stop(time);\n\t\t}\n\t\treturn this;\n\t}\n\n\t//-------------------------------------\n\t// \tSETTERS/GETTERS\n\t//-------------------------------------\n\n\t/**\n\t * The time signature as just the numerator over 4.\n\t * For example 4/4 would be just 4 and 6/8 would be 3.\n\t * @example\n\t * // common time\n\t * Tone.getTransport().timeSignature = 4;\n\t * // 7/8\n\t * Tone.getTransport().timeSignature = [7, 8];\n\t * // this will be reduced to a single number\n\t * Tone.getTransport().timeSignature; // returns 3.5\n\t */\n\tget timeSignature(): TimeSignature {\n\t\treturn this._timeSignature;\n\t}\n\tset timeSignature(timeSig: TimeSignature) {\n\t\tif (isArray(timeSig)) {\n\t\t\ttimeSig = (timeSig[0] / timeSig[1]) * 4;\n\t\t}\n\t\tthis._timeSignature = timeSig;\n\t}\n\n\t/**\n\t * When the Transport.loop = true, this is the starting position of the loop.\n\t */\n\tget loopStart(): Time {\n\t\treturn new TimeClass(this.context, this._loopStart, \"i\").toSeconds();\n\t}\n\tset loopStart(startPosition: Time) {\n\t\tthis._loopStart = this.toTicks(startPosition);\n\t}\n\n\t/**\n\t * When the Transport.loop = true, this is the ending position of the loop.\n\t */\n\tget loopEnd(): Time {\n\t\treturn new TimeClass(this.context, this._loopEnd, \"i\").toSeconds();\n\t}\n\tset loopEnd(endPosition: Time) {\n\t\tthis._loopEnd = this.toTicks(endPosition);\n\t}\n\n\t/**\n\t * If the transport loops or not.\n\t */\n\tget loop(): boolean {\n\t\treturn this._loop.get(this.now());\n\t}\n\tset loop(loop) {\n\t\tthis._loop.set(loop, this.now());\n\t}\n\n\t/**\n\t * Set the loop start and stop at the same time.\n\t * @example\n\t * // loop over the first measure\n\t * Tone.getTransport().setLoopPoints(0, \"1m\");\n\t * Tone.getTransport().loop = true;\n\t */\n\tsetLoopPoints(\n\t\tstartPosition: TransportTime,\n\t\tendPosition: TransportTime\n\t): this {\n\t\tthis.loopStart = startPosition;\n\t\tthis.loopEnd = endPosition;\n\t\treturn this;\n\t}\n\n\t/**\n\t * The swing value. Between 0-1 where 1 equal to the note + half the subdivision.\n\t */\n\tget swing(): NormalRange {\n\t\treturn this._swingAmount;\n\t}\n\tset swing(amount: NormalRange) {\n\t\t// scale the values to a normal range\n\t\tthis._swingAmount = amount;\n\t}\n\n\t/**\n\t * Set the subdivision which the swing will be applied to.\n\t * The default value is an 8th note. Value must be less\n\t * than a quarter note.\n\t */\n\tget swingSubdivision(): Subdivision {\n\t\treturn new TicksClass(this.context, this._swingTicks).toNotation();\n\t}\n\tset swingSubdivision(subdivision: Subdivision) {\n\t\tthis._swingTicks = this.toTicks(subdivision);\n\t}\n\n\t/**\n\t * The Transport's position in Bars:Beats:Sixteenths.\n\t * Setting the value will jump to that position right away.\n\t */\n\tget position(): BarsBeatsSixteenths | Time {\n\t\tconst now = this.now();\n\t\tconst ticks = this._clock.getTicksAtTime(now);\n\t\treturn new TicksClass(this.context, ticks).toBarsBeatsSixteenths();\n\t}\n\tset position(progress: Time) {\n\t\tconst ticks = this.toTicks(progress);\n\t\tthis.ticks = ticks;\n\t}\n\n\t/**\n\t * The Transport's position in seconds.\n\t * Setting the value will jump to that position right away.\n\t */\n\tget seconds(): Seconds {\n\t\treturn this._clock.seconds;\n\t}\n\tset seconds(s: Seconds) {\n\t\tconst now = this.now();\n\t\tconst ticks = this._clock.frequency.timeToTicks(s, now);\n\t\tthis.ticks = ticks;\n\t}\n\n\t/**\n\t * The Transport's loop position as a normalized value. Always\n\t * returns 0 if the Transport.loop = false.\n\t */\n\tget progress(): NormalRange {\n\t\tif (this.loop) {\n\t\t\tconst now = this.now();\n\t\t\tconst ticks = this._clock.getTicksAtTime(now);\n\t\t\treturn (\n\t\t\t\t(ticks - this._loopStart) / (this._loopEnd - this._loopStart)\n\t\t\t);\n\t\t} else {\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\t/**\n\t * The Transport's current tick position.\n\t */\n\tget ticks(): Ticks {\n\t\treturn this._clock.ticks;\n\t}\n\tset ticks(t: Ticks) {\n\t\tif (this._clock.ticks !== t) {\n\t\t\tconst now = this.now();\n\t\t\t// stop everything synced to the transport\n\t\t\tif (this.state === \"started\") {\n\t\t\t\tconst ticks = this._clock.getTicksAtTime(now);\n\t\t\t\t// schedule to start on the next tick, #573\n\t\t\t\tconst remainingTick = this._clock.frequency.getDurationOfTicks(\n\t\t\t\t\tMath.ceil(ticks) - ticks,\n\t\t\t\t\tnow\n\t\t\t\t);\n\t\t\t\tconst time = now + remainingTick;\n\t\t\t\tthis.emit(\"stop\", time);\n\t\t\t\tthis._clock.setTicksAtTime(t, time);\n\t\t\t\t// restart it with the new time\n\t\t\t\tthis.emit(\"start\", time, this._clock.getSecondsAtTime(time));\n\t\t\t} else {\n\t\t\t\tthis.emit(\"ticks\", now);\n\t\t\t\tthis._clock.setTicksAtTime(t, now);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Get the clock's ticks at the given time.\n\t * @param time When to get the tick value\n\t * @return The tick value at the given time.\n\t */\n\tgetTicksAtTime(time?: Time): Ticks {\n\t\treturn this._clock.getTicksAtTime(time);\n\t}\n\n\t/**\n\t * Return the elapsed seconds at the given time.\n\t * @param time When to get the elapsed seconds\n\t * @return The number of elapsed seconds\n\t */\n\tgetSecondsAtTime(time: Time): Seconds {\n\t\treturn this._clock.getSecondsAtTime(time);\n\t}\n\n\t/**\n\t * Pulses Per Quarter note. This is the smallest resolution\n\t * the Transport timing supports. This should be set once\n\t * on initialization and not set again. Changing this value\n\t * after other objects have been created can cause problems.\n\t */\n\tget PPQ(): number {\n\t\treturn this._clock.frequency.multiplier;\n\t}\n\tset PPQ(ppq: number) {\n\t\tthis._clock.frequency.multiplier = ppq;\n\t}\n\n\t//-------------------------------------\n\t// \tSYNCING\n\t//-------------------------------------\n\n\t/**\n\t * Returns the time aligned to the next subdivision\n\t * of the Transport. If the Transport is not started,\n\t * it will return 0.\n\t * Note: this will not work precisely during tempo ramps.\n\t * @param subdivision The subdivision to quantize to\n\t * @return The context time of the next subdivision.\n\t * @example\n\t * // the transport must be started, otherwise returns 0\n\t * Tone.getTransport().start();\n\t * Tone.getTransport().nextSubdivision(\"4n\");\n\t */\n\tnextSubdivision(subdivision?: Time): Seconds {\n\t\tsubdivision = this.toTicks(subdivision);\n\t\tif (this.state !== \"started\") {\n\t\t\t// if the transport's not started, return 0\n\t\t\treturn 0;\n\t\t} else {\n\t\t\tconst now = this.now();\n\t\t\t// the remainder of the current ticks and the subdivision\n\t\t\tconst transportPos = this.getTicksAtTime(now);\n\t\t\tconst remainingTicks = subdivision - (transportPos % subdivision);\n\t\t\treturn this._clock.nextTickTime(remainingTicks, now);\n\t\t}\n\t}\n\n\t/**\n\t * Attaches the signal to the tempo control signal so that\n\t * any changes in the tempo will change the signal in the same\n\t * ratio.\n\t *\n\t * @param signal\n\t * @param ratio Optionally pass in the ratio between the two signals.\n\t * \t\t\tOtherwise it will be computed based on their current values.\n\t */\n\tsyncSignal(signal: Signal<any>, ratio?: number): this {\n\t\tconst now = this.now();\n\t\tlet source: TickParam<\"bpm\"> | ToneAudioNode<any> = this.bpm;\n\t\tlet sourceValue = 1 / (60 / source.getValueAtTime(now) / this.PPQ);\n\t\tlet nodes: ToneAudioNode<any>[] = [];\n\t\t// If the signal is in the time domain, sync it to the reciprocal of\n\t\t// the tempo instead of the tempo.\n\t\tif (signal.units === \"time\") {\n\t\t\t// The input to Pow should be in the range [1 / 4096, 1], where\n\t\t\t// where 4096 is half of the buffer size of Pow's waveshaper.\n\t\t\t// Pick a scaling factor based on the initial tempo that ensures\n\t\t\t// that the initial input is in this range, while leaving room for\n\t\t\t// tempo changes.\n\t\t\tconst scaleFactor = 1 / 64 / sourceValue;\n\t\t\tconst scaleBefore = new Gain(scaleFactor);\n\t\t\tconst reciprocal = new Pow(-1);\n\t\t\tconst scaleAfter = new Gain(scaleFactor);\n\t\t\t// @ts-ignore\n\t\t\tsource.chain(scaleBefore, reciprocal, scaleAfter);\n\t\t\tsource = scaleAfter;\n\t\t\tsourceValue = 1 / sourceValue;\n\t\t\tnodes = [scaleBefore, reciprocal, scaleAfter];\n\t\t}\n\t\tif (!ratio) {\n\t\t\t// get the sync ratio\n\t\t\tif (signal.getValueAtTime(now) !== 0) {\n\t\t\t\tratio = signal.getValueAtTime(now) / sourceValue;\n\t\t\t} else {\n\t\t\t\tratio = 0;\n\t\t\t}\n\t\t}\n\t\tconst ratioSignal = new Gain(ratio);\n\t\t// @ts-ignore\n\t\tsource.connect(ratioSignal);\n\t\t// @ts-ignore\n\t\tratioSignal.connect(signal._param);\n\t\tnodes.push(ratioSignal);\n\t\tthis._syncedSignals.push({\n\t\t\tinitial: signal.value,\n\t\t\tnodes: nodes,\n\t\t\tsignal,\n\t\t});\n\t\tsignal.value = 0;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Unsyncs a previously synced signal from the transport's control.\n\t * @see {@link syncSignal}.\n\t */\n\tunsyncSignal(signal: Signal<any>): this {\n\t\tfor (let i = this._syncedSignals.length - 1; i >= 0; i--) {\n\t\t\tconst syncedSignal = this._syncedSignals[i];\n\t\t\tif (syncedSignal.signal === signal) {\n\t\t\t\tsyncedSignal.nodes.forEach((node) => node.dispose());\n\t\t\t\tsyncedSignal.signal.value = syncedSignal.initial;\n\t\t\t\tthis._syncedSignals.splice(i, 1);\n\t\t\t}\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Clean up.\n\t */\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis._clock.dispose();\n\t\twritable(this, \"bpm\");\n\t\tthis._timeline.dispose();\n\t\tthis._repeatedEvents.dispose();\n\t\treturn this;\n\t}\n\n\t//-------------------------------------\n\t// EMITTER MIXIN TO SATISFY COMPILER\n\t//-------------------------------------\n\n\ton!: (\n\t\tevent: TransportEventNames,\n\t\tcallback: (...args: any[]) => void\n\t) => this;\n\tonce!: (\n\t\tevent: TransportEventNames,\n\t\tcallback: (...args: any[]) => void\n\t) => this;\n\toff!: (\n\t\tevent: TransportEventNames,\n\t\tcallback?: ((...args: any[]) => void) | undefined\n\t) => this;\n\temit!: (event: any, ...args: any[]) => this;\n}\n\nEmitter.mixin(TransportClass);\n\n//-------------------------------------\n// \tINITIALIZATION\n//-------------------------------------\n\nonContextInit((context) => {\n\tcontext.transport = new TransportClass({ context });\n});\n\nonContextClose((context) => {\n\tcontext.transport.dispose();\n});\n","import { Volume } from \"../component/channel/Volume.js\";\nimport \"../core/context/Destination.js\";\nimport \"../core/clock/Transport.js\";\nimport { Param } from \"../core/context/Param.js\";\nimport {\n\tOutputNode,\n\tToneAudioNode,\n\tToneAudioNodeOptions,\n} from \"../core/context/ToneAudioNode.js\";\nimport { Decibels, Seconds, Time } from \"../core/type/Units.js\";\nimport { defaultArg } from \"../core/util/Defaults.js\";\nimport { noOp, readOnly } from \"../core/util/Interface.js\";\nimport {\n\tBasicPlaybackState,\n\tStateTimeline,\n\tStateTimelineEvent,\n} from \"../core/util/StateTimeline.js\";\nimport { isDefined, isUndef } from \"../core/util/TypeCheck.js\";\nimport { assert, assertContextRunning } from \"../core/util/Debug.js\";\nimport { GT } from \"../core/util/Math.js\";\n\ntype onStopCallback = (source: Source<any>) => void;\n\nexport interface SourceOptions extends ToneAudioNodeOptions {\n\tvolume: Decibels;\n\tmute: boolean;\n\tonstop: onStopCallback;\n}\n\n/**\n * Base class for sources.\n * start/stop of this.context.transport.\n *\n * ```\n * // Multiple state change events can be chained together,\n * // but must be set in the correct order and with ascending times\n * // OK\n * state.start().stop(\"+0.2\");\n * // OK\n * state.start().stop(\"+0.2\").start(\"+0.4\").stop(\"+0.7\")\n * // BAD\n * state.stop(\"+0.2\").start();\n * // BAD\n * state.start(\"+0.3\").stop(\"+0.2\");\n * ```\n */\nexport abstract class Source<\n\tOptions extends SourceOptions,\n> extends ToneAudioNode<Options> {\n\t/**\n\t * The output volume node\n\t */\n\tprivate _volume: Volume;\n\n\t/**\n\t * The output node\n\t */\n\toutput: OutputNode;\n\n\t/**\n\t * Sources have no inputs\n\t */\n\tinput = undefined;\n\n\t/**\n\t * The volume of the output in decibels.\n\t * @example\n\t * const source = new Tone.PWMOscillator().toDestination();\n\t * source.volume.value = -6;\n\t */\n\tvolume: Param<\"decibels\">;\n\n\t/**\n\t * The callback to invoke when the source is stopped.\n\t */\n\tonstop: onStopCallback;\n\n\t/**\n\t * Keep track of the scheduled state.\n\t */\n\tprotected _state: StateTimeline<{\n\t\tduration?: Seconds;\n\t\toffset?: Seconds;\n\t\t/**\n\t\t * Either the buffer is explicitly scheduled to end using the stop method,\n\t\t * or it's implicitly ended when the buffer is over.\n\t\t */\n\t\timplicitEnd?: boolean;\n\t}> = new StateTimeline(\"stopped\");\n\n\t/**\n\t * The synced `start` callback function from the transport\n\t */\n\tprotected _synced = false;\n\n\t/**\n\t * Keep track of all of the scheduled event ids\n\t */\n\tprivate _scheduled: number[] = [];\n\n\t/**\n\t * Placeholder functions for syncing/unsyncing to transport\n\t */\n\tprivate _syncedStart: (time: Seconds, offset: Seconds) => void = noOp;\n\tprivate _syncedStop: (time: Seconds) => void = noOp;\n\n\tconstructor(options: SourceOptions) {\n\t\tsuper(options);\n\t\tthis._state.memory = 100;\n\t\tthis._state.increasing = true;\n\n\t\tthis._volume = this.output = new Volume({\n\t\t\tcontext: this.context,\n\t\t\tmute: options.mute,\n\t\t\tvolume: options.volume,\n\t\t});\n\t\tthis.volume = this._volume.volume;\n\t\treadOnly(this, \"volume\");\n\t\tthis.onstop = options.onstop;\n\t}\n\n\tstatic getDefaults(): SourceOptions {\n\t\treturn Object.assign(ToneAudioNode.getDefaults(), {\n\t\t\tmute: false,\n\t\t\tonstop: noOp,\n\t\t\tvolume: 0,\n\t\t});\n\t}\n\n\t/**\n\t * Returns the playback state of the source, either \"started\" or \"stopped\".\n\t * @example\n\t * const player = new Tone.Player(\"https://tonejs.github.io/audio/berklee/ahntone_c3.mp3\", () => {\n\t * \tplayer.start();\n\t * \tconsole.log(player.state);\n\t * }).toDestination();\n\t */\n\tget state(): BasicPlaybackState {\n\t\tif (this._synced) {\n\t\t\tif (this.context.transport.state === \"started\") {\n\t\t\t\treturn this._state.getValueAtTime(\n\t\t\t\t\tthis.context.transport.seconds\n\t\t\t\t) as BasicPlaybackState;\n\t\t\t} else {\n\t\t\t\treturn \"stopped\";\n\t\t\t}\n\t\t} else {\n\t\t\treturn this._state.getValueAtTime(this.now()) as BasicPlaybackState;\n\t\t}\n\t}\n\n\t/**\n\t * Mute the output.\n\t * @example\n\t * const osc = new Tone.Oscillator().toDestination().start();\n\t * // mute the output\n\t * osc.mute = true;\n\t */\n\tget mute(): boolean {\n\t\treturn this._volume.mute;\n\t}\n\tset mute(mute: boolean) {\n\t\tthis._volume.mute = mute;\n\t}\n\n\t// overwrite these functions\n\tprotected abstract _start(time: Time, offset?: Time, duration?: Time): void;\n\tprotected abstract _stop(time: Time): void;\n\tprotected abstract _restart(\n\t\ttime: Seconds,\n\t\toffset?: Time,\n\t\tduration?: Time\n\t): void;\n\n\t/**\n\t * Ensure that the scheduled time is not before the current time.\n\t * Should only be used when scheduled unsynced.\n\t */\n\tprivate _clampToCurrentTime(time: Seconds): Seconds {\n\t\tif (this._synced) {\n\t\t\treturn time;\n\t\t} else {\n\t\t\treturn Math.max(time, this.context.currentTime);\n\t\t}\n\t}\n\n\t/**\n\t * Start the source at the specified time. If no time is given,\n\t * start the source now.\n\t * @param time When the source should be started.\n\t * @example\n\t * const source = new Tone.Oscillator().toDestination();\n\t * source.start(\"+0.5\"); // starts the source 0.5 seconds from now\n\t */\n\tstart(time?: Time, offset?: Time, duration?: Time): this {\n\t\tlet computedTime =\n\t\t\tisUndef(time) && this._synced\n\t\t\t\t? this.context.transport.seconds\n\t\t\t\t: this.toSeconds(time);\n\t\tcomputedTime = this._clampToCurrentTime(computedTime);\n\t\t// if it's started, stop it and restart it\n\t\tif (\n\t\t\t!this._synced &&\n\t\t\tthis._state.getValueAtTime(computedTime) === \"started\"\n\t\t) {\n\t\t\t// time should be strictly greater than the previous start time\n\t\t\tassert(\n\t\t\t\tGT(\n\t\t\t\t\tcomputedTime,\n\t\t\t\t\t(this._state.get(computedTime) as StateTimelineEvent).time\n\t\t\t\t),\n\t\t\t\t\"Start time must be strictly greater than previous start time\"\n\t\t\t);\n\t\t\tthis._state.cancel(computedTime);\n\t\t\tthis._state.setStateAtTime(\"started\", computedTime);\n\t\t\tthis.log(\"restart\", computedTime);\n\t\t\tthis.restart(computedTime, offset, duration);\n\t\t} else {\n\t\t\tthis.log(\"start\", computedTime);\n\t\t\tthis._state.setStateAtTime(\"started\", computedTime);\n\t\t\tif (this._synced) {\n\t\t\t\t// add the offset time to the event\n\t\t\t\tconst event = this._state.get(computedTime);\n\t\t\t\tif (event) {\n\t\t\t\t\tevent.offset = this.toSeconds(defaultArg(offset, 0));\n\t\t\t\t\tevent.duration = duration\n\t\t\t\t\t\t? this.toSeconds(duration)\n\t\t\t\t\t\t: undefined;\n\t\t\t\t}\n\t\t\t\tconst sched = this.context.transport.schedule((t) => {\n\t\t\t\t\tthis._start(t, offset, duration);\n\t\t\t\t}, computedTime);\n\t\t\t\tthis._scheduled.push(sched);\n\n\t\t\t\t// if the transport is already started\n\t\t\t\t// and the time is greater than where the transport is\n\t\t\t\tif (\n\t\t\t\t\tthis.context.transport.state === \"started\" &&\n\t\t\t\t\tthis.context.transport.getSecondsAtTime(this.immediate()) >\n\t\t\t\t\t\tcomputedTime\n\t\t\t\t) {\n\t\t\t\t\tthis._syncedStart(\n\t\t\t\t\t\tthis.now(),\n\t\t\t\t\t\tthis.context.transport.seconds\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tassertContextRunning(this.context);\n\t\t\t\tthis._start(computedTime, offset, duration);\n\t\t\t}\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Stop the source at the specified time. If no time is given,\n\t * stop the source now.\n\t * @param time When the source should be stopped.\n\t * @example\n\t * const source = new Tone.Oscillator().toDestination();\n\t * source.start();\n\t * source.stop(\"+0.5\"); // stops the source 0.5 seconds from now\n\t */\n\tstop(time?: Time): this {\n\t\tlet computedTime =\n\t\t\tisUndef(time) && this._synced\n\t\t\t\t? this.context.transport.seconds\n\t\t\t\t: this.toSeconds(time);\n\t\tcomputedTime = this._clampToCurrentTime(computedTime);\n\t\tif (\n\t\t\tthis._state.getValueAtTime(computedTime) === \"started\" ||\n\t\t\tisDefined(this._state.getNextState(\"started\", computedTime))\n\t\t) {\n\t\t\tthis.log(\"stop\", computedTime);\n\t\t\tif (!this._synced) {\n\t\t\t\tthis._stop(computedTime);\n\t\t\t} else {\n\t\t\t\tconst sched = this.context.transport.schedule(\n\t\t\t\t\tthis._stop.bind(this),\n\t\t\t\t\tcomputedTime\n\t\t\t\t);\n\t\t\t\tthis._scheduled.push(sched);\n\t\t\t}\n\t\t\tthis._state.cancel(computedTime);\n\t\t\tthis._state.setStateAtTime(\"stopped\", computedTime);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Restart the source.\n\t */\n\trestart(time?: Time, offset?: Time, duration?: Time): this {\n\t\ttime = this.toSeconds(time);\n\t\tif (this._state.getValueAtTime(time) === \"started\") {\n\t\t\tthis._state.cancel(time);\n\t\t\tthis._restart(time, offset, duration);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sync the source to the Transport so that all subsequent\n\t * calls to `start` and `stop` are synced to the TransportTime\n\t * instead of the AudioContext time.\n\t *\n\t * @example\n\t * const osc = new Tone.Oscillator().toDestination();\n\t * // sync the source so that it plays between 0 and 0.3 on the Transport's timeline\n\t * osc.sync().start(0).stop(0.3);\n\t * // start the transport.\n\t * Tone.Transport.start();\n\t * // set it to loop once a second\n\t * Tone.Transport.loop = true;\n\t * Tone.Transport.loopEnd = 1;\n\t */\n\tsync(): this {\n\t\tif (!this._synced) {\n\t\t\tthis._synced = true;\n\t\t\tthis._syncedStart = (time, offset) => {\n\t\t\t\tif (GT(offset, 0)) {\n\t\t\t\t\t// get the playback state at that time\n\t\t\t\t\tconst stateEvent = this._state.get(offset);\n\t\t\t\t\t// listen for start events which may occur in the middle of the sync'ed time\n\t\t\t\t\tif (\n\t\t\t\t\t\tstateEvent &&\n\t\t\t\t\t\tstateEvent.state === \"started\" &&\n\t\t\t\t\t\tstateEvent.time !== offset\n\t\t\t\t\t) {\n\t\t\t\t\t\t// get the offset\n\t\t\t\t\t\tconst startOffset =\n\t\t\t\t\t\t\toffset - this.toSeconds(stateEvent.time);\n\t\t\t\t\t\tlet duration: number | undefined;\n\t\t\t\t\t\tif (stateEvent.duration) {\n\t\t\t\t\t\t\tduration =\n\t\t\t\t\t\t\t\tthis.toSeconds(stateEvent.duration) -\n\t\t\t\t\t\t\t\tstartOffset;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis._start(\n\t\t\t\t\t\t\ttime,\n\t\t\t\t\t\t\tthis.toSeconds(stateEvent.offset) + startOffset,\n\t\t\t\t\t\t\tduration\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\t\t\tthis._syncedStop = (time) => {\n\t\t\t\tconst seconds = this.context.transport.getSecondsAtTime(\n\t\t\t\t\tMath.max(time - this.sampleTime, 0)\n\t\t\t\t);\n\t\t\t\tif (this._state.getValueAtTime(seconds) === \"started\") {\n\t\t\t\t\tthis._stop(time);\n\t\t\t\t}\n\t\t\t};\n\t\t\tthis.context.transport.on(\"start\", this._syncedStart);\n\t\t\tthis.context.transport.on(\"loopStart\", this._syncedStart);\n\t\t\tthis.context.transport.on(\"stop\", this._syncedStop);\n\t\t\tthis.context.transport.on(\"pause\", this._syncedStop);\n\t\t\tthis.context.transport.on(\"loopEnd\", this._syncedStop);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Unsync the source to the Transport.\n\t * @see {@link sync}\n\t */\n\tunsync(): this {\n\t\tif (this._synced) {\n\t\t\tthis.context.transport.off(\"stop\", this._syncedStop);\n\t\t\tthis.context.transport.off(\"pause\", this._syncedStop);\n\t\t\tthis.context.transport.off(\"loopEnd\", this._syncedStop);\n\t\t\tthis.context.transport.off(\"start\", this._syncedStart);\n\t\t\tthis.context.transport.off(\"loopStart\", this._syncedStart);\n\t\t}\n\t\tthis._synced = false;\n\t\t// clear all of the scheduled ids\n\t\tthis._scheduled.forEach((id) => this.context.transport.clear(id));\n\t\tthis._scheduled = [];\n\t\tthis._state.cancel(0);\n\t\t// stop it also\n\t\tthis._stop(0);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Clean up.\n\t */\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis.onstop = noOp;\n\t\tthis.unsync();\n\t\tthis._volume.dispose();\n\t\tthis._state.dispose();\n\t\treturn this;\n\t}\n}\n","import { connect } from \"../../core/context/ToneAudioNode.js\";\nimport { Param } from \"../../core/context/Param.js\";\nimport { ToneAudioBuffer } from \"../../core/context/ToneAudioBuffer.js\";\nimport { GainFactor, Positive, Seconds, Time } from \"../../core/type/Units.js\";\nimport { defaultArg, optionsFromArguments } from \"../../core/util/Defaults.js\";\nimport { noOp } from \"../../core/util/Interface.js\";\nimport { isDefined } from \"../../core/util/TypeCheck.js\";\nimport { assert } from \"../../core/util/Debug.js\";\nimport {\n\tOneShotSource,\n\tOneShotSourceCurve,\n\tOneShotSourceOptions,\n} from \"../OneShotSource.js\";\nimport { EQ, GTE, LT } from \"../../core/util/Math.js\";\n\nexport type ToneBufferSourceCurve = OneShotSourceCurve;\n\nexport interface ToneBufferSourceOptions extends OneShotSourceOptions {\n\turl: string | AudioBuffer | ToneAudioBuffer;\n\tcurve: ToneBufferSourceCurve;\n\tplaybackRate: Positive;\n\tfadeIn: Time;\n\tfadeOut: Time;\n\tloopStart: Time;\n\tloopEnd: Time;\n\tloop: boolean;\n\tonload: () => void;\n\tonerror: (error: Error) => void;\n}\n\n/**\n * Wrapper around the native BufferSourceNode.\n * @category Source\n */\nexport class ToneBufferSource extends OneShotSource<ToneBufferSourceOptions> {\n\treadonly name: string = \"ToneBufferSource\";\n\n\t/**\n\t * The oscillator\n\t */\n\tprivate _source = this.context.createBufferSource();\n\tprotected _internalChannels = [this._source];\n\n\t/**\n\t * The frequency of the oscillator\n\t */\n\treadonly playbackRate: Param<\"positive\">;\n\n\t/**\n\t * The private instance of the buffer object\n\t */\n\tprivate _buffer: ToneAudioBuffer;\n\n\t/**\n\t * indicators if the source has started/stopped\n\t */\n\tprivate _sourceStarted = false;\n\tprivate _sourceStopped = false;\n\n\t/**\n\t * @param url The buffer to play or url to load\n\t * @param onload The callback to invoke when the buffer is done playing.\n\t */\n\tconstructor(\n\t\turl?: ToneAudioBuffer | AudioBuffer | string,\n\t\tonload?: () => void\n\t);\n\tconstructor(options?: Partial<ToneBufferSourceOptions>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(\n\t\t\tToneBufferSource.getDefaults(),\n\t\t\targuments,\n\t\t\t[\"url\", \"onload\"]\n\t\t);\n\t\tsuper(options);\n\n\t\tconnect(this._source, this._gainNode);\n\t\tthis._source.onended = () => this._stopSource();\n\n\t\t/**\n\t\t * The playbackRate of the buffer\n\t\t */\n\t\tthis.playbackRate = new Param({\n\t\t\tcontext: this.context,\n\t\t\tparam: this._source.playbackRate,\n\t\t\tunits: \"positive\",\n\t\t\tvalue: options.playbackRate,\n\t\t});\n\n\t\t// set some values initially\n\t\tthis.loop = options.loop;\n\t\tthis.loopStart = options.loopStart;\n\t\tthis.loopEnd = options.loopEnd;\n\t\tthis._buffer = new ToneAudioBuffer(\n\t\t\toptions.url,\n\t\t\toptions.onload,\n\t\t\toptions.onerror\n\t\t);\n\n\t\tthis._internalChannels.push(this._source);\n\t}\n\n\tstatic getDefaults(): ToneBufferSourceOptions {\n\t\treturn Object.assign(OneShotSource.getDefaults(), {\n\t\t\turl: new ToneAudioBuffer(),\n\t\t\tloop: false,\n\t\t\tloopEnd: 0,\n\t\t\tloopStart: 0,\n\t\t\tonload: noOp,\n\t\t\tonerror: noOp,\n\t\t\tplaybackRate: 1,\n\t\t});\n\t}\n\n\t/**\n\t * The fadeIn time of the amplitude envelope.\n\t */\n\tget fadeIn(): Time {\n\t\treturn this._fadeIn;\n\t}\n\tset fadeIn(t: Time) {\n\t\tthis._fadeIn = t;\n\t}\n\n\t/**\n\t * The fadeOut time of the amplitude envelope.\n\t */\n\tget fadeOut(): Time {\n\t\treturn this._fadeOut;\n\t}\n\tset fadeOut(t: Time) {\n\t\tthis._fadeOut = t;\n\t}\n\n\t/**\n\t * The curve applied to the fades, either \"linear\" or \"exponential\"\n\t */\n\tget curve(): ToneBufferSourceCurve {\n\t\treturn this._curve;\n\t}\n\tset curve(t) {\n\t\tthis._curve = t;\n\t}\n\n\t/**\n\t * Start the buffer\n\t * @param time When the player should start.\n\t * @param offset The offset from the beginning of the sample to start at.\n\t * @param duration How long the sample should play. If no duration is given, it will default to the full length of the sample (minus any offset)\n\t * @param gain The gain to play the buffer back at.\n\t */\n\tstart(\n\t\ttime?: Time,\n\t\toffset?: Time,\n\t\tduration?: Time,\n\t\tgain: GainFactor = 1\n\t): this {\n\t\tassert(this.buffer.loaded, \"buffer is either not set or not loaded\");\n\t\tconst computedTime = this.toSeconds(time);\n\n\t\t// apply the gain envelope\n\t\tthis._startGain(computedTime, gain);\n\n\t\t// if it's a loop the default offset is the loopstart point\n\t\tif (this.loop) {\n\t\t\toffset = defaultArg(offset, this.loopStart);\n\t\t} else {\n\t\t\t// otherwise the default offset is 0\n\t\t\toffset = defaultArg(offset, 0);\n\t\t}\n\t\t// make sure the offset is not less than 0\n\t\tlet computedOffset = Math.max(this.toSeconds(offset), 0);\n\n\t\t// start the buffer source\n\t\tif (this.loop) {\n\t\t\t// modify the offset if it's greater than the loop time\n\t\t\tconst loopEnd =\n\t\t\t\tthis.toSeconds(this.loopEnd) || this.buffer.duration;\n\t\t\tconst loopStart = this.toSeconds(this.loopStart);\n\t\t\tconst loopDuration = loopEnd - loopStart;\n\t\t\t// move the offset back\n\t\t\tif (GTE(computedOffset, loopEnd)) {\n\t\t\t\tcomputedOffset =\n\t\t\t\t\t((computedOffset - loopStart) % loopDuration) + loopStart;\n\t\t\t}\n\t\t\t// when the offset is very close to the duration, set it to 0\n\t\t\tif (EQ(computedOffset, this.buffer.duration)) {\n\t\t\t\tcomputedOffset = 0;\n\t\t\t}\n\t\t}\n\n\t\t// this.buffer.loaded would have return false if the AudioBuffer was undefined\n\t\tthis._source.buffer = this.buffer.get() as AudioBuffer;\n\t\tthis._source.loopEnd =\n\t\t\tthis.toSeconds(this.loopEnd) || this.buffer.duration;\n\t\tif (LT(computedOffset, this.buffer.duration)) {\n\t\t\tthis._sourceStarted = true;\n\t\t\tthis._source.start(computedTime, computedOffset);\n\t\t}\n\n\t\t// if a duration is given, schedule a stop\n\t\tif (isDefined(duration)) {\n\t\t\tlet computedDur = this.toSeconds(duration);\n\t\t\t// make sure it's never negative\n\t\t\tcomputedDur = Math.max(computedDur, 0);\n\t\t\tthis.stop(computedTime + computedDur);\n\t\t}\n\n\t\treturn this;\n\t}\n\n\tprotected _stopSource(time?: Seconds): void {\n\t\tif (!this._sourceStopped && this._sourceStarted) {\n\t\t\tthis._sourceStopped = true;\n\t\t\tthis._source.stop(this.toSeconds(time));\n\t\t\tthis._onended();\n\t\t}\n\t}\n\n\t/**\n\t * If loop is true, the loop will start at this position.\n\t */\n\tget loopStart(): Time {\n\t\treturn this._source.loopStart;\n\t}\n\tset loopStart(loopStart: Time) {\n\t\tthis._source.loopStart = this.toSeconds(loopStart);\n\t}\n\n\t/**\n\t * If loop is true, the loop will end at this position.\n\t */\n\tget loopEnd(): Time {\n\t\treturn this._source.loopEnd;\n\t}\n\tset loopEnd(loopEnd: Time) {\n\t\tthis._source.loopEnd = this.toSeconds(loopEnd);\n\t}\n\n\t/**\n\t * The audio buffer belonging to the player.\n\t */\n\tget buffer(): ToneAudioBuffer {\n\t\treturn this._buffer;\n\t}\n\tset buffer(buffer: ToneAudioBuffer) {\n\t\tthis._buffer.set(buffer);\n\t}\n\n\t/**\n\t * If the buffer should loop once it's over.\n\t */\n\tget loop(): boolean {\n\t\treturn this._source.loop;\n\t}\n\tset loop(loop: boolean) {\n\t\tthis._source.loop = loop;\n\t\tif (this._sourceStarted) {\n\t\t\tthis.cancelStop();\n\t\t}\n\t}\n\n\t/**\n\t * Clean up.\n\t */\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis._source.onended = null;\n\t\tthis._source.disconnect();\n\t\tthis._buffer.dispose();\n\t\tthis.playbackRate.dispose();\n\t\treturn this;\n\t}\n}\n","import { ToneAudioBuffer } from \"../core/context/ToneAudioBuffer.js\";\nimport { Positive, Time } from \"../core/type/Units.js\";\nimport { optionsFromArguments } from \"../core/util/Defaults.js\";\nimport { assert } from \"../core/util/Debug.js\";\nimport { Source, SourceOptions } from \"../source/Source.js\";\nimport { ToneBufferSource } from \"./buffer/ToneBufferSource.js\";\n\nexport type NoiseType = \"white\" | \"brown\" | \"pink\";\n\nexport interface NoiseOptions extends SourceOptions {\n\ttype: NoiseType;\n\tplaybackRate: Positive;\n\tfadeIn: Time;\n\tfadeOut: Time;\n}\n\n/**\n * Noise is a noise generator. It uses looped noise buffers to save on performance.\n * Noise supports the noise types: \"pink\", \"white\", and \"brown\". Read more about\n * colors of noise on [Wikipedia](https://en.wikipedia.org/wiki/Colors_of_noise).\n *\n * @example\n * // initialize the noise and start\n * const noise = new Tone.Noise(\"pink\").start();\n * // make an autofilter to shape the noise\n * const autoFilter = new Tone.AutoFilter({\n * \tfrequency: \"8n\",\n * \tbaseFrequency: 200,\n * \toctaves: 8\n * }).toDestination().start();\n * // connect the noise\n * noise.connect(autoFilter);\n * // start the autofilter LFO\n * autoFilter.start();\n * @category Source\n */\nexport class Noise extends Source<NoiseOptions> {\n\treadonly name: string = \"Noise\";\n\n\t/**\n\t * Private reference to the source\n\t */\n\tprivate _source: ToneBufferSource | null = null;\n\n\t/**\n\t * private reference to the type\n\t */\n\tprivate _type!: NoiseType;\n\n\t/**\n\t * The playback rate of the noise. Affects\n\t * the \"frequency\" of the noise.\n\t */\n\tprivate _playbackRate: Positive;\n\n\t/**\n\t * The fadeIn time of the amplitude envelope.\n\t */\n\tprotected _fadeIn: Time;\n\n\t/**\n\t * The fadeOut time of the amplitude envelope.\n\t */\n\tprotected _fadeOut: Time;\n\n\t/**\n\t * @param type the noise type (white|pink|brown)\n\t */\n\tconstructor(type?: NoiseType);\n\tconstructor(options?: Partial<NoiseOptions>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(Noise.getDefaults(), arguments, [\n\t\t\t\"type\",\n\t\t]);\n\t\tsuper(options);\n\n\t\tthis._playbackRate = options.playbackRate;\n\t\tthis.type = options.type;\n\t\tthis._fadeIn = options.fadeIn;\n\t\tthis._fadeOut = options.fadeOut;\n\t}\n\n\tstatic getDefaults(): NoiseOptions {\n\t\treturn Object.assign(Source.getDefaults(), {\n\t\t\tfadeIn: 0,\n\t\t\tfadeOut: 0,\n\t\t\tplaybackRate: 1,\n\t\t\ttype: \"white\" as NoiseType,\n\t\t});\n\t}\n\n\t/**\n\t * The type of the noise. Can be \"white\", \"brown\", or \"pink\".\n\t * @example\n\t * const noise = new Tone.Noise().toDestination().start();\n\t * noise.type = \"brown\";\n\t */\n\tget type(): NoiseType {\n\t\treturn this._type;\n\t}\n\tset type(type: NoiseType) {\n\t\tassert(type in _noiseBuffers, \"Noise: invalid type: \" + type);\n\t\tif (this._type !== type) {\n\t\t\tthis._type = type;\n\t\t\t// if it's playing, stop and restart it\n\t\t\tif (this.state === \"started\") {\n\t\t\t\tconst now = this.now();\n\t\t\t\tthis._stop(now);\n\t\t\t\tthis._start(now);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * The playback rate of the noise. Affects\n\t * the \"frequency\" of the noise.\n\t */\n\tget playbackRate(): Positive {\n\t\treturn this._playbackRate;\n\t}\n\tset playbackRate(rate: Positive) {\n\t\tthis._playbackRate = rate;\n\t\tif (this._source) {\n\t\t\tthis._source.playbackRate.value = rate;\n\t\t}\n\t}\n\n\t/**\n\t * internal start method\n\t */\n\tprotected _start(time?: Time): void {\n\t\tconst buffer = _noiseBuffers[this._type];\n\t\tthis._source = new ToneBufferSource({\n\t\t\turl: buffer,\n\t\t\tcontext: this.context,\n\t\t\tfadeIn: this._fadeIn,\n\t\t\tfadeOut: this._fadeOut,\n\t\t\tloop: true,\n\t\t\tonended: () => this.onstop(this),\n\t\t\tplaybackRate: this._playbackRate,\n\t\t}).connect(this.output);\n\t\tthis._source.start(\n\t\t\tthis.toSeconds(time),\n\t\t\tMath.random() * (buffer.duration - 0.001)\n\t\t);\n\t}\n\n\t/**\n\t * internal stop method\n\t */\n\tprotected _stop(time?: Time): void {\n\t\tif (this._source) {\n\t\t\tthis._source.stop(this.toSeconds(time));\n\t\t\tthis._source = null;\n\t\t}\n\t}\n\n\t/**\n\t * The fadeIn time of the amplitude envelope.\n\t */\n\tget fadeIn(): Time {\n\t\treturn this._fadeIn;\n\t}\n\tset fadeIn(time) {\n\t\tthis._fadeIn = time;\n\t\tif (this._source) {\n\t\t\tthis._source.fadeIn = this._fadeIn;\n\t\t}\n\t}\n\n\t/**\n\t * The fadeOut time of the amplitude envelope.\n\t */\n\tget fadeOut(): Time {\n\t\treturn this._fadeOut;\n\t}\n\tset fadeOut(time) {\n\t\tthis._fadeOut = time;\n\t\tif (this._source) {\n\t\t\tthis._source.fadeOut = this._fadeOut;\n\t\t}\n\t}\n\n\tprotected _restart(time?: Time): void {\n\t\t// TODO could be optimized by cancelling the buffer source 'stop'\n\t\tthis._stop(time);\n\t\tthis._start(time);\n\t}\n\n\t/**\n\t * Clean up.\n\t */\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tif (this._source) {\n\t\t\tthis._source.disconnect();\n\t\t}\n\t\treturn this;\n\t}\n}\n\n//--------------------\n// THE NOISE BUFFERS\n//--------------------\n\n// Noise buffer stats\nconst BUFFER_LENGTH = 44100 * 5;\nconst NUM_CHANNELS = 2;\n\n/**\n * The cached noise buffers\n */\ninterface NoiseCache {\n\t[key: string]: ToneAudioBuffer | null;\n}\n\n/**\n * Cache the noise buffers\n */\nconst _noiseCache: NoiseCache = {\n\tbrown: null,\n\tpink: null,\n\twhite: null,\n};\n\n/**\n * The noise arrays. Generated on initialization.\n * borrowed heavily from https://github.com/zacharydenton/noise.js\n * (c) 2013 Zach Denton (MIT)\n */\nconst _noiseBuffers = {\n\tget brown(): ToneAudioBuffer {\n\t\tif (!_noiseCache.brown) {\n\t\t\tconst buffer: Float32Array[] = [];\n\t\t\tfor (let channelNum = 0; channelNum < NUM_CHANNELS; channelNum++) {\n\t\t\t\tconst channel = new Float32Array(BUFFER_LENGTH);\n\t\t\t\tbuffer[channelNum] = channel;\n\t\t\t\tlet lastOut = 0.0;\n\t\t\t\tfor (let i = 0; i < BUFFER_LENGTH; i++) {\n\t\t\t\t\tconst white = Math.random() * 2 - 1;\n\t\t\t\t\tchannel[i] = (lastOut + 0.02 * white) / 1.02;\n\t\t\t\t\tlastOut = channel[i];\n\t\t\t\t\tchannel[i] *= 3.5; // (roughly) compensate for gain\n\t\t\t\t}\n\t\t\t}\n\t\t\t_noiseCache.brown = new ToneAudioBuffer().fromArray(buffer);\n\t\t}\n\t\treturn _noiseCache.brown;\n\t},\n\n\tget pink(): ToneAudioBuffer {\n\t\tif (!_noiseCache.pink) {\n\t\t\tconst buffer: Float32Array[] = [];\n\t\t\tfor (let channelNum = 0; channelNum < NUM_CHANNELS; channelNum++) {\n\t\t\t\tconst channel = new Float32Array(BUFFER_LENGTH);\n\t\t\t\tbuffer[channelNum] = channel;\n\t\t\t\tlet b0, b1, b2, b3, b4, b5, b6;\n\t\t\t\tb0 = b1 = b2 = b3 = b4 = b5 = b6 = 0.0;\n\t\t\t\tfor (let i = 0; i < BUFFER_LENGTH; i++) {\n\t\t\t\t\tconst white = Math.random() * 2 - 1;\n\t\t\t\t\tb0 = 0.99886 * b0 + white * 0.0555179;\n\t\t\t\t\tb1 = 0.99332 * b1 + white * 0.0750759;\n\t\t\t\t\tb2 = 0.969 * b2 + white * 0.153852;\n\t\t\t\t\tb3 = 0.8665 * b3 + white * 0.3104856;\n\t\t\t\t\tb4 = 0.55 * b4 + white * 0.5329522;\n\t\t\t\t\tb5 = -0.7616 * b5 - white * 0.016898;\n\t\t\t\t\tchannel[i] =\n\t\t\t\t\t\tb0 + b1 + b2 + b3 + b4 + b5 + b6 + white * 0.5362;\n\t\t\t\t\tchannel[i] *= 0.11; // (roughly) compensate for gain\n\t\t\t\t\tb6 = white * 0.115926;\n\t\t\t\t}\n\t\t\t}\n\t\t\t_noiseCache.pink = new ToneAudioBuffer().fromArray(buffer);\n\t\t}\n\t\treturn _noiseCache.pink;\n\t},\n\n\tget white(): ToneAudioBuffer {\n\t\tif (!_noiseCache.white) {\n\t\t\tconst buffer: Float32Array[] = [];\n\t\t\tfor (let channelNum = 0; channelNum < NUM_CHANNELS; channelNum++) {\n\t\t\t\tconst channel = new Float32Array(BUFFER_LENGTH);\n\t\t\t\tbuffer[channelNum] = channel;\n\t\t\t\tfor (let i = 0; i < BUFFER_LENGTH; i++) {\n\t\t\t\t\tchannel[i] = Math.random() * 2 - 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\t_noiseCache.white = new ToneAudioBuffer().fromArray(buffer);\n\t\t}\n\t\treturn _noiseCache.white;\n\t},\n};\n","import {\n\tAudioRange,\n\tCents,\n\tDegrees,\n\tFrequency,\n\tPositive,\n} from \"../../core/type/Units.js\";\nimport { Omit } from \"../../core/util/Interface.js\";\nimport { Signal } from \"../../signal/Signal.js\";\nimport { SourceOptions } from \"../Source.js\";\nimport { OfflineContext } from \"../../core/context/OfflineContext.js\";\n\n/**\n * The common interface of all Oscillators\n */\nexport interface ToneOscillatorInterface {\n\t/**\n\t * The oscillator type without the partialsCount appended to the end\n\t * @example\n\t * const osc = new Tone.Oscillator();\n\t * osc.type = \"sine2\";\n\t * console.log(osc.baseType); // \"sine\"\n\t */\n\tbaseType: OscillatorType | \"pulse\" | \"pwm\";\n\n\t/**\n\t * The oscillator's type. Also capable of setting the first x number of partials of the oscillator.\n\t * For example: \"sine4\" would set be the first 4 partials of the sine wave and \"triangle8\" would\n\t * set the first 8 partials of the triangle wave.\n\t * @example\n\t * return Tone.Offline(() => {\n\t * \tconst osc = new Tone.Oscillator().toDestination().start();\n\t * \tosc.type = \"sine2\";\n\t * }, 0.1, 1);\n\t */\n\ttype: ExtendedToneOscillatorType;\n\n\t/**\n\t * The frequency value of the oscillator\n\t * @example\n\t * const osc = new Tone.FMOscillator(\"Bb4\").toDestination().start();\n\t * osc.frequency.rampTo(\"D2\", 3);\n\t */\n\treadonly frequency: Signal<\"frequency\">;\n\n\t/**\n\t * The detune value in cents (100th of a semitone).\n\t * @example\n\t * const osc = new Tone.PulseOscillator(\"F3\").toDestination().start();\n\t * // pitch it 1 octave = 12 semitones = 1200 cents\n\t * osc.detune.setValueAtTime(-1200, Tone.now());\n\t * osc.detune.setValueAtTime(1200, Tone.now() + 0.5);\n\t * osc.detune.linearRampToValueAtTime(0, Tone.now() + 1);\n\t * osc.stop(Tone.now() + 1.5);\n\t */\n\treadonly detune: Signal<\"cents\">;\n\n\t/**\n\t * The phase is the starting position within the oscillator's cycle. For example\n\t * a phase of 180 would start halfway through the oscillator's cycle.\n\t * @example\n\t * return Tone.Offline(() => {\n\t * \tconst osc = new Tone.Oscillator({\n\t * \t\tfrequency: 20,\n\t * \t\tphase: 90\n\t * \t}).toDestination().start();\n\t * }, 0.1, 1);\n\t */\n\tphase: Degrees;\n\n\t/**\n\t * The partials describes the relative amplitude of each of the harmonics of the oscillator.\n\t * The first value in the array is the first harmonic (i.e. the fundamental frequency), the\n\t * second harmonic is an octave up, the third harmonic is an octave and a fifth, etc. The resulting\n\t * oscillator output is composed of a sine tone at the relative amplitude at each of the harmonic intervals.\n\t *\n\t * Setting this value will automatically set the type to \"custom\".\n\t * The value is an empty array when the type is not \"custom\".\n\t * @example\n\t * const osc = new Tone.Oscillator(\"F3\").toDestination().start();\n\t * setInterval(() => {\n\t * \t// generate 8 random partials\n\t * \tosc.partials = new Array(8).fill(0).map(() => Math.random());\n\t * }, 1000);\n\t */\n\tpartials: number[];\n\n\t/**\n\t * 'partialCount' offers an alternative way to set the number of used partials.\n\t * When partialCount is 0, the maximum number of partials are used when representing\n\t * the waveform using the periodicWave. When 'partials' is set, this value is\n\t * not settable, but equals the length of the partials array. A square wave wave\n\t * is composed of only odd harmonics up through the harmonic series. Partial count\n\t * can limit the number of harmonics which are used to generate the waveform.\n\t * @example\n\t * const osc = new Tone.Oscillator(\"C3\", \"square\").toDestination().start();\n\t * osc.partialCount = 1;\n\t * setInterval(() => {\n\t * \tosc.partialCount++;\n\t * \tconsole.log(osc.partialCount);\n\t * }, 500);\n\t */\n\tpartialCount?: number;\n\n\t/**\n\t * Returns an array of values which represents the waveform.\n\t * @param length The length of the waveform to return\n\t */\n\tasArray(length: number): Promise<Float32Array>;\n}\n\n/**\n * Render a segment of the oscillator to an offline context and return the results as an array\n */\nexport async function generateWaveform(\n\tinstance: any,\n\tlength: number\n): Promise<Float32Array> {\n\tconst duration = length / instance.context.sampleRate;\n\tconst context = new OfflineContext(\n\t\t1,\n\t\tduration,\n\t\tinstance.context.sampleRate\n\t);\n\tconst clone = new instance.constructor(\n\t\tObject.assign(instance.get(), {\n\t\t\t// should do 2 iterations\n\t\t\tfrequency: 2 / duration,\n\t\t\t// zero out the detune\n\t\t\tdetune: 0,\n\t\t\tcontext,\n\t\t})\n\t).toDestination();\n\tclone.start(0);\n\tconst buffer = await context.render();\n\treturn buffer.getChannelData(0);\n}\n\n/**\n * The supported number of partials\n */\ntype PartialsRange =\n\t| 1\n\t| 2\n\t| 3\n\t| 4\n\t| 5\n\t| 6\n\t| 7\n\t| 8\n\t| 9\n\t| 10\n\t| 11\n\t| 12\n\t| 13\n\t| 14\n\t| 15\n\t| 16\n\t| 17\n\t| 18\n\t| 19\n\t| 20\n\t| 21\n\t| 22\n\t| 23\n\t| 24\n\t| 25\n\t| 26\n\t| 27\n\t| 28\n\t| 29\n\t| 30\n\t| 31\n\t| 32;\n\n/**\n * Oscillators with partials\n */\ntype SineWithPartials = `sine${PartialsRange}`;\n\ntype SquareWithPartials = `square${PartialsRange}`;\n\ntype SawtoothWithPartials = `sawtooth${PartialsRange}`;\n\ntype TriangleWithPartials = `triangle${PartialsRange}`;\n\ntype TypeWithPartials =\n\t| SineWithPartials\n\t| SquareWithPartials\n\t| TriangleWithPartials\n\t| SawtoothWithPartials;\n\ninterface BaseOscillatorOptions extends SourceOptions {\n\tfrequency: Frequency;\n\tdetune: Cents;\n\tphase: Degrees;\n}\n\nexport type NonCustomOscillatorType = Exclude<OscillatorType, \"custom\">;\n\ntype AllNonCustomOscillatorType = NonCustomOscillatorType | TypeWithPartials;\n\nexport type ToneOscillatorType = AllNonCustomOscillatorType | \"custom\";\n\nexport type ExtendedToneOscillatorType = ToneOscillatorType | \"pwm\" | \"pulse\";\n\n/**\n * Oscillator Interfaces\n */\ninterface ToneCustomOscillatorOptions extends BaseOscillatorOptions {\n\ttype: \"custom\";\n\tpartials: number[];\n}\n\ninterface ToneTypeOscillatorOptions extends BaseOscillatorOptions {\n\ttype: NonCustomOscillatorType;\n\tpartialCount?: number;\n}\n\ninterface TonePartialOscillatorOptions extends BaseOscillatorOptions {\n\ttype: TypeWithPartials;\n}\n\nexport type ToneOscillatorConstructorOptions =\n\t| ToneCustomOscillatorOptions\n\t| ToneTypeOscillatorOptions\n\t| TonePartialOscillatorOptions;\n\nexport interface ToneOscillatorOptions extends BaseOscillatorOptions {\n\ttype: ToneOscillatorType;\n\tpartialCount: number;\n\tpartials: number[];\n}\n\n/**\n * FMOscillator Interface\n */\ninterface FMBaseOscillatorOptions extends BaseOscillatorOptions {\n\tharmonicity: Positive;\n\tmodulationIndex: Positive;\n\tmodulationType: AllNonCustomOscillatorType;\n}\n\ninterface FMCustomOscillatorOptions extends FMBaseOscillatorOptions {\n\ttype: \"custom\";\n\tpartials: number[];\n}\n\ninterface FMTypeOscillatorOptions extends FMBaseOscillatorOptions {\n\ttype: NonCustomOscillatorType;\n\tpartialsCount?: number;\n}\n\ninterface FMPartialsOscillatorOptions extends FMBaseOscillatorOptions {\n\ttype: TypeWithPartials;\n}\n\nexport type FMConstructorOptions =\n\t| FMTypeOscillatorOptions\n\t| FMCustomOscillatorOptions\n\t| FMPartialsOscillatorOptions;\n\nexport interface FMOscillatorOptions extends ToneOscillatorOptions {\n\tharmonicity: Positive;\n\tmodulationIndex: Positive;\n\tmodulationType: AllNonCustomOscillatorType;\n}\n\n/**\n * AMOscillator Interface\n */\ninterface AMBaseOscillatorOptions extends BaseOscillatorOptions {\n\tharmonicity: Positive;\n\tmodulationType: AllNonCustomOscillatorType;\n}\n\ninterface AMCustomOscillatorOptions extends AMBaseOscillatorOptions {\n\ttype: \"custom\";\n\tpartials: number[];\n}\n\ninterface AMTypeOscillatorOptions extends AMBaseOscillatorOptions {\n\ttype: NonCustomOscillatorType;\n\tpartialsCount?: number;\n}\n\ninterface AMPartialsOscillatorOptions extends AMBaseOscillatorOptions {\n\ttype: TypeWithPartials;\n}\n\nexport type AMConstructorOptions =\n\t| AMCustomOscillatorOptions\n\t| AMTypeOscillatorOptions\n\t| AMPartialsOscillatorOptions;\n\nexport interface AMOscillatorOptions extends ToneOscillatorOptions {\n\tharmonicity: Positive;\n\tmodulationType: AllNonCustomOscillatorType;\n}\n/**\n * FatOscillator\n */\ninterface FatBaseOscillatorOptions extends BaseOscillatorOptions {\n\tspread: Cents;\n\tcount: Positive;\n}\n\ninterface FatCustomOscillatorOptions extends FatBaseOscillatorOptions {\n\ttype: \"custom\";\n\tpartials: number[];\n}\n\ninterface FatTypeOscillatorOptions extends FatBaseOscillatorOptions {\n\ttype: NonCustomOscillatorType;\n\tpartialCount?: number;\n}\n\ninterface FatPartialsOscillatorOptions extends FatBaseOscillatorOptions {\n\ttype: TypeWithPartials;\n}\n\nexport type FatConstructorOptions =\n\t| FatCustomOscillatorOptions\n\t| FatTypeOscillatorOptions\n\t| FatPartialsOscillatorOptions;\n\nexport interface FatOscillatorOptions extends ToneOscillatorOptions {\n\tspread: Cents;\n\tcount: Positive;\n}\n\n/**\n * Pulse Oscillator\n */\nexport interface PulseOscillatorOptions extends BaseOscillatorOptions {\n\ttype: \"pulse\";\n\twidth: AudioRange;\n}\n\n/**\n * PWM Oscillator\n */\nexport interface PWMOscillatorOptions extends BaseOscillatorOptions {\n\ttype: \"pwm\";\n\tmodulationFrequency: Frequency;\n}\n\n/**\n * OMNI OSCILLATOR\n */\n\n/**\n * FM Oscillators with partials\n */\ntype FMSineWithPartials = `fmsine${PartialsRange}`;\n\ntype FMSquareWithPartials = `fmsquare${PartialsRange}`;\n\ntype FMSawtoothWithPartials = `fmsawtooth${PartialsRange}`;\n\ntype FMTriangleWithPartials = `fmtriangle${PartialsRange}`;\n\ntype FMTypeWithPartials =\n\t| FMSineWithPartials\n\t| FMSquareWithPartials\n\t| FMSawtoothWithPartials\n\t| FMTriangleWithPartials;\n\n/**\n * AM Oscillators with partials\n */\ntype AMSineWithPartials = `amsine${PartialsRange}`;\n\ntype AMSquareWithPartials = `amsquare${PartialsRange}`;\n\ntype AMSawtoothWithPartials = `amsawtooth${PartialsRange}`;\n\ntype AMTriangleWithPartials = `amtriangle${PartialsRange}`;\n\ntype AMTypeWithPartials =\n\t| AMSineWithPartials\n\t| AMSquareWithPartials\n\t| AMSawtoothWithPartials\n\t| AMTriangleWithPartials;\n\n/**\n * Fat Oscillators with partials\n */\ntype FatSineWithPartials = `fatsine${PartialsRange}`;\n\ntype FatSquareWithPartials = `fatsquare${PartialsRange}`;\n\ntype FatSawtoothWithPartials = `fatsawtooth${PartialsRange}`;\n\ntype FatTriangleWithPartials = `fattriangle${PartialsRange}`;\n\ntype FatTypeWithPartials =\n\t| FatSineWithPartials\n\t| FatSquareWithPartials\n\t| FatSawtoothWithPartials\n\t| FatTriangleWithPartials;\n\n/**\n * Omni FM\n */\ninterface OmniFMCustomOscillatorOptions extends FMBaseOscillatorOptions {\n\ttype: \"fmcustom\";\n\tpartials: number[];\n}\n\ninterface OmniFMTypeOscillatorOptions extends FMBaseOscillatorOptions {\n\ttype: \"fmsine\" | \"fmsquare\" | \"fmsawtooth\" | \"fmtriangle\";\n\tpartialsCount?: number;\n}\n\ninterface OmniFMPartialsOscillatorOptions extends FMBaseOscillatorOptions {\n\ttype: FMTypeWithPartials;\n}\n\n/**\n * Omni AM\n */\ninterface OmniAMCustomOscillatorOptions extends AMBaseOscillatorOptions {\n\ttype: \"amcustom\";\n\tpartials: number[];\n}\n\ninterface OmniAMTypeOscillatorOptions extends AMBaseOscillatorOptions {\n\ttype: \"amsine\" | \"amsquare\" | \"amsawtooth\" | \"amtriangle\";\n\tpartialsCount?: number;\n}\n\ninterface OmniAMPartialsOscillatorOptions extends AMBaseOscillatorOptions {\n\ttype: AMTypeWithPartials;\n}\n\n/**\n * Omni Fat\n */\ninterface OmniFatCustomOscillatorOptions extends FatBaseOscillatorOptions {\n\ttype: \"fatcustom\";\n\tpartials: number[];\n}\n\ninterface OmniFatTypeOscillatorOptions extends FatBaseOscillatorOptions {\n\ttype: \"fatsine\" | \"fatsquare\" | \"fatsawtooth\" | \"fattriangle\";\n\tpartialsCount?: number;\n}\n\ninterface OmniFatPartialsOscillatorOptions extends FatBaseOscillatorOptions {\n\ttype: FatTypeWithPartials;\n}\n\nexport type OmniOscillatorType =\n\t| \"fatsine\"\n\t| \"fatsquare\"\n\t| \"fatsawtooth\"\n\t| \"fattriangle\"\n\t| \"fatcustom\"\n\t| FatTypeWithPartials\n\t| \"fmsine\"\n\t| \"fmsquare\"\n\t| \"fmsawtooth\"\n\t| \"fmtriangle\"\n\t| \"fmcustom\"\n\t| FMTypeWithPartials\n\t| \"amsine\"\n\t| \"amsquare\"\n\t| \"amsawtooth\"\n\t| \"amtriangle\"\n\t| \"amcustom\"\n\t| AMTypeWithPartials\n\t| TypeWithPartials\n\t| OscillatorType\n\t| \"pulse\"\n\t| \"pwm\";\n\nexport type OmniOscillatorOptions =\n\t| PulseOscillatorOptions\n\t| PWMOscillatorOptions\n\t| OmniFatCustomOscillatorOptions\n\t| OmniFatTypeOscillatorOptions\n\t| OmniFatPartialsOscillatorOptions\n\t| OmniFMCustomOscillatorOptions\n\t| OmniFMTypeOscillatorOptions\n\t| OmniFMPartialsOscillatorOptions\n\t| OmniAMCustomOscillatorOptions\n\t| OmniAMTypeOscillatorOptions\n\t| OmniAMPartialsOscillatorOptions\n\t| ToneOscillatorConstructorOptions;\n\ntype OmitSourceOptions<T extends BaseOscillatorOptions> = Omit<\n\tT,\n\t\"frequency\" | \"detune\" | \"context\"\n>;\n\n/**\n * The settable options for the omni oscillator inside of the source which excludes certain attributes that are defined by the parent class\n */\nexport type OmniOscillatorSynthOptions =\n\t| OmitSourceOptions<PulseOscillatorOptions>\n\t| OmitSourceOptions<PWMOscillatorOptions>\n\t| OmitSourceOptions<OmniFatCustomOscillatorOptions>\n\t| OmitSourceOptions<OmniFatTypeOscillatorOptions>\n\t| OmitSourceOptions<OmniFatPartialsOscillatorOptions>\n\t| OmitSourceOptions<OmniFMCustomOscillatorOptions>\n\t| OmitSourceOptions<OmniFMTypeOscillatorOptions>\n\t| OmitSourceOptions<OmniFMPartialsOscillatorOptions>\n\t| OmitSourceOptions<OmniAMCustomOscillatorOptions>\n\t| OmitSourceOptions<OmniAMTypeOscillatorOptions>\n\t| OmitSourceOptions<OmniAMPartialsOscillatorOptions>\n\t| OmitSourceOptions<ToneCustomOscillatorOptions>\n\t| OmitSourceOptions<ToneTypeOscillatorOptions>\n\t| OmitSourceOptions<TonePartialOscillatorOptions>;\n","import { connect } from \"../../core/context/ToneAudioNode.js\";\nimport { Param } from \"../../core/context/Param.js\";\nimport { Cents, Frequency, Seconds, Time } from \"../../core/type/Units.js\";\nimport { optionsFromArguments } from \"../../core/util/Defaults.js\";\nimport { OneShotSource, OneShotSourceOptions } from \"../OneShotSource.js\";\nimport { readOnly } from \"../../core/util/Interface.js\";\n\nexport interface ToneOscillatorNodeOptions extends OneShotSourceOptions {\n\tfrequency: Frequency;\n\tdetune: Cents;\n\ttype: OscillatorType;\n}\n\n/**\n * Wrapper around the native fire-and-forget OscillatorNode.\n * Adds the ability to reschedule the stop method.\n * ***{@link Oscillator} is better for most use-cases***\n * @category Source\n */\nexport class ToneOscillatorNode extends OneShotSource<ToneOscillatorNodeOptions> {\n\treadonly name: string = \"ToneOscillatorNode\";\n\n\t/**\n\t * The oscillator\n\t */\n\tprivate _oscillator = this.context.createOscillator();\n\tprotected _internalChannels = [this._oscillator];\n\n\t/**\n\t * The frequency of the oscillator\n\t */\n\treadonly frequency: Param<\"frequency\">;\n\n\t/**\n\t * The detune of the oscillator\n\t */\n\treadonly detune: Param<\"cents\">;\n\n\t/**\n\t * @param frequency The frequency value\n\t * @param type The basic oscillator type\n\t */\n\tconstructor(frequency: Frequency, type: OscillatorType);\n\tconstructor(options?: Partial<ToneOscillatorNodeOptions>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(\n\t\t\tToneOscillatorNode.getDefaults(),\n\t\t\targuments,\n\t\t\t[\"frequency\", \"type\"]\n\t\t);\n\t\tsuper(options);\n\n\t\tconnect(this._oscillator, this._gainNode);\n\n\t\tthis.type = options.type;\n\n\t\tthis.frequency = new Param({\n\t\t\tcontext: this.context,\n\t\t\tparam: this._oscillator.frequency,\n\t\t\tunits: \"frequency\",\n\t\t\tvalue: options.frequency,\n\t\t});\n\n\t\tthis.detune = new Param({\n\t\t\tcontext: this.context,\n\t\t\tparam: this._oscillator.detune,\n\t\t\tunits: \"cents\",\n\t\t\tvalue: options.detune,\n\t\t});\n\n\t\treadOnly(this, [\"frequency\", \"detune\"]);\n\t}\n\n\tstatic getDefaults(): ToneOscillatorNodeOptions {\n\t\treturn Object.assign(OneShotSource.getDefaults(), {\n\t\t\tdetune: 0,\n\t\t\tfrequency: 440,\n\t\t\ttype: \"sine\" as OscillatorType,\n\t\t});\n\t}\n\n\t/**\n\t * Start the oscillator node at the given time\n\t * @param time When to start the oscillator\n\t */\n\tstart(time?: Time): this {\n\t\tconst computedTime = this.toSeconds(time);\n\t\tthis.log(\"start\", computedTime);\n\t\tthis._startGain(computedTime);\n\t\tthis._oscillator.start(computedTime);\n\t\treturn this;\n\t}\n\n\tprotected _stopSource(time?: Seconds): void {\n\t\tthis._oscillator.stop(time);\n\t}\n\n\t/**\n\t * Sets an arbitrary custom periodic waveform given a PeriodicWave.\n\t * @param periodicWave PeriodicWave should be created with context.createPeriodicWave\n\t */\n\tsetPeriodicWave(periodicWave: PeriodicWave): this {\n\t\tthis._oscillator.setPeriodicWave(periodicWave);\n\t\treturn this;\n\t}\n\n\t/**\n\t * The oscillator type. Either 'sine', 'sawtooth', 'square', or 'triangle'\n\t */\n\tget type(): OscillatorType {\n\t\treturn this._oscillator.type;\n\t}\n\tset type(type: OscillatorType) {\n\t\tthis._oscillator.type = type;\n\t}\n\n\t/**\n\t * Clean up.\n\t */\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tif (this.state === \"started\") {\n\t\t\tthis.stop();\n\t\t}\n\t\tthis._oscillator.disconnect();\n\t\tthis.frequency.dispose();\n\t\tthis.detune.dispose();\n\t\treturn this;\n\t}\n}\n","import {\n\tAudioRange,\n\tDegrees,\n\tFrequency,\n\tRadians,\n\tTime,\n} from \"../../core/type/Units.js\";\nimport { deepEquals, optionsFromArguments } from \"../../core/util/Defaults.js\";\nimport { readOnly } from \"../../core/util/Interface.js\";\nimport { isDefined } from \"../../core/util/TypeCheck.js\";\nimport { Signal } from \"../../signal/Signal.js\";\nimport { Source } from \"../Source.js\";\nimport {\n\tgenerateWaveform,\n\tToneOscillatorConstructorOptions,\n\tToneOscillatorInterface,\n\tToneOscillatorOptions,\n\tToneOscillatorType,\n} from \"./OscillatorInterface.js\";\nimport { ToneOscillatorNode } from \"./ToneOscillatorNode.js\";\nimport { assertRange } from \"../../core/util/Debug.js\";\nimport { clamp } from \"../../core/util/Math.js\";\nexport {\n\tToneOscillatorOptions,\n\tToneOscillatorType,\n} from \"./OscillatorInterface.js\";\n/**\n * Oscillator supports a number of features including\n * phase rotation, multiple oscillator types (see Oscillator.type),\n * and Transport syncing (see Oscillator.syncFrequency).\n *\n * @example\n * // make and start a 440hz sine tone\n * const osc = new Tone.Oscillator(440, \"sine\").toDestination().start();\n * @category Source\n */\nexport class Oscillator\n\textends Source<ToneOscillatorOptions>\n\timplements ToneOscillatorInterface\n{\n\treadonly name: string = \"Oscillator\";\n\n\t/**\n\t * the main oscillator\n\t */\n\tprivate _oscillator: ToneOscillatorNode | null = null;\n\n\t/**\n\t * The frequency control.\n\t */\n\tfrequency: Signal<\"frequency\">;\n\n\t/**\n\t * The detune control signal.\n\t */\n\tdetune: Signal<\"cents\">;\n\n\t/**\n\t * the periodic wave\n\t */\n\tprivate _wave?: PeriodicWave;\n\n\t/**\n\t * The partials of the oscillator\n\t */\n\tprivate _partials: number[];\n\n\t/**\n\t * The number of partials to limit or extend the periodic wave by\n\t */\n\tprivate _partialCount: number;\n\n\t/**\n\t * the phase of the oscillator between 0 - 360\n\t */\n\tprivate _phase!: Radians;\n\n\t/**\n\t * the type of the oscillator\n\t */\n\tprivate _type: ToneOscillatorType;\n\n\t/**\n\t * @param frequency Starting frequency\n\t * @param type The oscillator type. Read more about type below.\n\t */\n\tconstructor(frequency?: Frequency, type?: ToneOscillatorType);\n\tconstructor(options?: Partial<ToneOscillatorConstructorOptions>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(\n\t\t\tOscillator.getDefaults(),\n\t\t\targuments,\n\t\t\t[\"frequency\", \"type\"]\n\t\t);\n\t\tsuper(options);\n\n\t\tthis.frequency = new Signal<\"frequency\">({\n\t\t\tcontext: this.context,\n\t\t\tunits: \"frequency\",\n\t\t\tvalue: options.frequency,\n\t\t});\n\t\treadOnly(this, \"frequency\");\n\n\t\tthis.detune = new Signal<\"cents\">({\n\t\t\tcontext: this.context,\n\t\t\tunits: \"cents\",\n\t\t\tvalue: options.detune,\n\t\t});\n\t\treadOnly(this, \"detune\");\n\n\t\tthis._partials = options.partials;\n\t\tthis._partialCount = options.partialCount;\n\t\tthis._type = options.type;\n\n\t\tif (options.partialCount && options.type !== \"custom\") {\n\t\t\tthis._type = (this.baseType +\n\t\t\t\toptions.partialCount.toString()) as ToneOscillatorType;\n\t\t}\n\t\tthis.phase = options.phase;\n\t}\n\n\tstatic getDefaults(): ToneOscillatorOptions {\n\t\treturn Object.assign(Source.getDefaults(), {\n\t\t\tdetune: 0,\n\t\t\tfrequency: 440,\n\t\t\tpartialCount: 0,\n\t\t\tpartials: [],\n\t\t\tphase: 0,\n\t\t\ttype: \"sine\" as const,\n\t\t});\n\t}\n\n\t/**\n\t * start the oscillator\n\t */\n\tprotected _start(time?: Time): void {\n\t\tconst computedTime = this.toSeconds(time);\n\t\t// new oscillator with previous values\n\t\tconst oscillator = new ToneOscillatorNode({\n\t\t\tcontext: this.context,\n\t\t\tonended: () => this.onstop(this),\n\t\t});\n\t\tthis._oscillator = oscillator;\n\t\tif (this._wave) {\n\t\t\tthis._oscillator.setPeriodicWave(this._wave);\n\t\t} else {\n\t\t\tthis._oscillator.type = this._type as OscillatorType;\n\t\t}\n\t\t// connect the control signal to the oscillator frequency & detune\n\t\tthis._oscillator.connect(this.output);\n\t\tthis.frequency.connect(this._oscillator.frequency);\n\t\tthis.detune.connect(this._oscillator.detune);\n\n\t\t// start the oscillator\n\t\tthis._oscillator.start(computedTime);\n\t}\n\n\t/**\n\t * stop the oscillator\n\t */\n\tprotected _stop(time?: Time): void {\n\t\tconst computedTime = this.toSeconds(time);\n\t\tif (this._oscillator) {\n\t\t\tthis._oscillator.stop(computedTime);\n\t\t}\n\t}\n\n\t/**\n\t * Restart the oscillator. Does not stop the oscillator, but instead\n\t * just cancels any scheduled 'stop' from being invoked.\n\t */\n\tprotected _restart(time?: Time): this {\n\t\tconst computedTime = this.toSeconds(time);\n\t\tthis.log(\"restart\", computedTime);\n\t\tif (this._oscillator) {\n\t\t\tthis._oscillator.cancelStop();\n\t\t}\n\t\tthis._state.cancel(computedTime);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sync the signal to the Transport's bpm. Any changes to the transports bpm,\n\t * will also affect the oscillators frequency.\n\t * @example\n\t * const osc = new Tone.Oscillator().toDestination().start();\n\t * osc.frequency.value = 440;\n\t * // the ratio between the bpm and the frequency will be maintained\n\t * osc.syncFrequency();\n\t * // double the tempo\n\t * Tone.Transport.bpm.value *= 2;\n\t * // the frequency of the oscillator is doubled to 880\n\t */\n\tsyncFrequency(): this {\n\t\tthis.context.transport.syncSignal(this.frequency);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Unsync the oscillator's frequency from the Transport.\n\t * @see {@link syncFrequency}\n\t */\n\tunsyncFrequency(): this {\n\t\tthis.context.transport.unsyncSignal(this.frequency);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Cache the periodic waves to avoid having to redo computations\n\t */\n\tprivate static _periodicWaveCache: Array<{\n\t\tpartials: number[];\n\t\tphase: number;\n\t\ttype: string;\n\t\tpartialCount: number;\n\t\treal: Float32Array;\n\t\timag: Float32Array;\n\t\twave: PeriodicWave;\n\t}> = [];\n\n\t/**\n\t * Get a cached periodic wave. Avoids having to recompute\n\t * the oscillator values when they have already been computed\n\t * with the same values.\n\t */\n\tprivate _getCachedPeriodicWave():\n\t\t| {\n\t\t\t\treal: Float32Array;\n\t\t\t\timag: Float32Array;\n\t\t\t\tpartials: number[];\n\t\t\t\twave: PeriodicWave;\n\t\t }\n\t\t| undefined {\n\t\tif (this._type === \"custom\") {\n\t\t\tconst oscProps = Oscillator._periodicWaveCache.find(\n\t\t\t\t(description) => {\n\t\t\t\t\treturn (\n\t\t\t\t\t\tdescription.phase === this._phase &&\n\t\t\t\t\t\tdeepEquals(description.partials, this._partials)\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t);\n\t\t\treturn oscProps;\n\t\t} else {\n\t\t\tconst oscProps = Oscillator._periodicWaveCache.find(\n\t\t\t\t(description) => {\n\t\t\t\t\treturn (\n\t\t\t\t\t\tdescription.type === this._type &&\n\t\t\t\t\t\tdescription.phase === this._phase\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t);\n\t\t\tthis._partialCount = oscProps\n\t\t\t\t? oscProps.partialCount\n\t\t\t\t: this._partialCount;\n\t\t\treturn oscProps;\n\t\t}\n\t}\n\n\tget type(): ToneOscillatorType {\n\t\treturn this._type;\n\t}\n\tset type(type) {\n\t\tthis._type = type;\n\t\tconst isBasicType =\n\t\t\t[\"sine\", \"square\", \"sawtooth\", \"triangle\"].indexOf(type) !== -1;\n\t\tif (this._phase === 0 && isBasicType) {\n\t\t\tthis._wave = undefined;\n\t\t\tthis._partialCount = 0;\n\t\t\t// just go with the basic approach\n\t\t\tif (this._oscillator !== null) {\n\t\t\t\t// already tested that it's a basic type\n\t\t\t\tthis._oscillator.type = type as OscillatorType;\n\t\t\t}\n\t\t} else {\n\t\t\t// first check if the value is cached\n\t\t\tconst cache = this._getCachedPeriodicWave();\n\t\t\tif (isDefined(cache)) {\n\t\t\t\tconst { partials, wave } = cache;\n\t\t\t\tthis._wave = wave;\n\t\t\t\tthis._partials = partials;\n\t\t\t\tif (this._oscillator !== null) {\n\t\t\t\t\tthis._oscillator.setPeriodicWave(this._wave);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tconst [real, imag] = this._getRealImaginary(type, this._phase);\n\t\t\t\tconst periodicWave = this.context.createPeriodicWave(\n\t\t\t\t\treal,\n\t\t\t\t\timag\n\t\t\t\t);\n\t\t\t\tthis._wave = periodicWave;\n\t\t\t\tif (this._oscillator !== null) {\n\t\t\t\t\tthis._oscillator.setPeriodicWave(this._wave);\n\t\t\t\t}\n\t\t\t\t// set the cache\n\t\t\t\tOscillator._periodicWaveCache.push({\n\t\t\t\t\timag,\n\t\t\t\t\tpartialCount: this._partialCount,\n\t\t\t\t\tpartials: this._partials,\n\t\t\t\t\tphase: this._phase,\n\t\t\t\t\treal,\n\t\t\t\t\ttype: this._type,\n\t\t\t\t\twave: this._wave,\n\t\t\t\t});\n\t\t\t\tif (Oscillator._periodicWaveCache.length > 100) {\n\t\t\t\t\tOscillator._periodicWaveCache.shift();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tget baseType(): OscillatorType {\n\t\treturn (this._type as string).replace(\n\t\t\tthis.partialCount.toString(),\n\t\t\t\"\"\n\t\t) as OscillatorType;\n\t}\n\tset baseType(baseType) {\n\t\tif (\n\t\t\tthis.partialCount &&\n\t\t\tthis._type !== \"custom\" &&\n\t\t\tbaseType !== \"custom\"\n\t\t) {\n\t\t\tthis.type = (baseType + this.partialCount) as ToneOscillatorType;\n\t\t} else {\n\t\t\tthis.type = baseType;\n\t\t}\n\t}\n\n\tget partialCount(): number {\n\t\treturn this._partialCount;\n\t}\n\tset partialCount(p) {\n\t\tassertRange(p, 0);\n\t\tlet type = this._type;\n\t\tconst partial = /^(sine|triangle|square|sawtooth)(\\d+)$/.exec(\n\t\t\tthis._type\n\t\t);\n\t\tif (partial) {\n\t\t\ttype = partial[1] as OscillatorType;\n\t\t}\n\t\tif (this._type !== \"custom\") {\n\t\t\tif (p === 0) {\n\t\t\t\tthis.type = type;\n\t\t\t} else {\n\t\t\t\tthis.type = (type + p.toString()) as ToneOscillatorType;\n\t\t\t}\n\t\t} else {\n\t\t\t// extend or shorten the partials array\n\t\t\tconst fullPartials = new Float32Array(p);\n\t\t\t// copy over the partials array\n\t\t\tthis._partials.forEach((v, i) => (fullPartials[i] = v));\n\t\t\tthis._partials = Array.from(fullPartials);\n\t\t\tthis.type = this._type;\n\t\t}\n\t}\n\n\t/**\n\t * Returns the real and imaginary components based\n\t * on the oscillator type.\n\t * @returns [real: Float32Array, imaginary: Float32Array]\n\t */\n\tprivate _getRealImaginary(\n\t\ttype: ToneOscillatorType,\n\t\tphase: Radians\n\t): Float32Array[] {\n\t\tconst fftSize = 4096;\n\t\tlet periodicWaveSize = fftSize / 2;\n\n\t\tconst real = new Float32Array(periodicWaveSize);\n\t\tconst imag = new Float32Array(periodicWaveSize);\n\n\t\tlet partialCount = 1;\n\t\tif (type === \"custom\") {\n\t\t\tpartialCount = this._partials.length + 1;\n\t\t\tthis._partialCount = this._partials.length;\n\t\t\tperiodicWaveSize = partialCount;\n\t\t\t// if the partial count is 0, don't bother doing any computation\n\t\t\tif (this._partials.length === 0) {\n\t\t\t\treturn [real, imag];\n\t\t\t}\n\t\t} else {\n\t\t\tconst partial = /^(sine|triangle|square|sawtooth)(\\d+)$/.exec(type);\n\t\t\tif (partial) {\n\t\t\t\tpartialCount = parseInt(partial[2], 10) + 1;\n\t\t\t\tthis._partialCount = parseInt(partial[2], 10);\n\t\t\t\ttype = partial[1] as ToneOscillatorType;\n\t\t\t\tpartialCount = Math.max(partialCount, 2);\n\t\t\t\tperiodicWaveSize = partialCount;\n\t\t\t} else {\n\t\t\t\tthis._partialCount = 0;\n\t\t\t}\n\t\t\tthis._partials = [];\n\t\t}\n\n\t\tfor (let n = 1; n < periodicWaveSize; ++n) {\n\t\t\tconst piFactor = 2 / (n * Math.PI);\n\t\t\tlet b;\n\t\t\tswitch (type) {\n\t\t\t\tcase \"sine\":\n\t\t\t\t\tb = n <= partialCount ? 1 : 0;\n\t\t\t\t\tthis._partials[n - 1] = b;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"square\":\n\t\t\t\t\tb = n & 1 ? 2 * piFactor : 0;\n\t\t\t\t\tthis._partials[n - 1] = b;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"sawtooth\":\n\t\t\t\t\tb = piFactor * (n & 1 ? 1 : -1);\n\t\t\t\t\tthis._partials[n - 1] = b;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"triangle\":\n\t\t\t\t\tif (n & 1) {\n\t\t\t\t\t\tb =\n\t\t\t\t\t\t\t2 *\n\t\t\t\t\t\t\t(piFactor * piFactor) *\n\t\t\t\t\t\t\t(((n - 1) >> 1) & 1 ? -1 : 1);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tb = 0;\n\t\t\t\t\t}\n\t\t\t\t\tthis._partials[n - 1] = b;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"custom\":\n\t\t\t\t\tb = this._partials[n - 1];\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new TypeError(\"Oscillator: invalid type: \" + type);\n\t\t\t}\n\t\t\tif (b !== 0) {\n\t\t\t\treal[n] = -b * Math.sin(phase * n);\n\t\t\t\timag[n] = b * Math.cos(phase * n);\n\t\t\t} else {\n\t\t\t\treal[n] = 0;\n\t\t\t\timag[n] = 0;\n\t\t\t}\n\t\t}\n\t\treturn [real, imag];\n\t}\n\n\t/**\n\t * Compute the inverse FFT for a given phase.\n\t */\n\tprivate _inverseFFT(\n\t\treal: Float32Array,\n\t\timag: Float32Array,\n\t\tphase: Radians\n\t): number {\n\t\tlet sum = 0;\n\t\tconst len = real.length;\n\t\tfor (let i = 0; i < len; i++) {\n\t\t\tsum +=\n\t\t\t\treal[i] * Math.cos(i * phase) + imag[i] * Math.sin(i * phase);\n\t\t}\n\t\treturn sum;\n\t}\n\n\t/**\n\t * Returns the initial value of the oscillator when stopped.\n\t * E.g. a \"sine\" oscillator with phase = 90 would return an initial value of -1.\n\t */\n\tgetInitialValue(): AudioRange {\n\t\tconst [real, imag] = this._getRealImaginary(this._type, 0);\n\t\tlet maxValue = 0;\n\t\tconst twoPi = Math.PI * 2;\n\t\tconst testPositions = 32;\n\t\t// check for peaks in 16 places\n\t\tfor (let i = 0; i < testPositions; i++) {\n\t\t\tmaxValue = Math.max(\n\t\t\t\tthis._inverseFFT(real, imag, (i / testPositions) * twoPi),\n\t\t\t\tmaxValue\n\t\t\t);\n\t\t}\n\t\treturn clamp(\n\t\t\t-this._inverseFFT(real, imag, this._phase) / maxValue,\n\t\t\t-1,\n\t\t\t1\n\t\t);\n\t}\n\n\tget partials(): number[] {\n\t\treturn this._partials.slice(0, this.partialCount);\n\t}\n\tset partials(partials) {\n\t\tthis._partials = partials;\n\t\tthis._partialCount = this._partials.length;\n\t\tif (partials.length) {\n\t\t\tthis.type = \"custom\";\n\t\t}\n\t}\n\n\tget phase(): Degrees {\n\t\treturn this._phase * (180 / Math.PI);\n\t}\n\tset phase(phase) {\n\t\tthis._phase = (phase * Math.PI) / 180;\n\t\t// reset the type\n\t\tthis.type = this._type;\n\t}\n\n\tasync asArray(length = 1024): Promise<Float32Array> {\n\t\treturn generateWaveform(this, length);\n\t}\n\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tif (this._oscillator !== null) {\n\t\t\tthis._oscillator.dispose();\n\t\t}\n\t\tthis._wave = undefined;\n\t\tthis.frequency.dispose();\n\t\tthis.detune.dispose();\n\t\treturn this;\n\t}\n}\n","import { ToneAudioNodeOptions } from \"../core/context/ToneAudioNode.js\";\nimport { SignalOperator } from \"./SignalOperator.js\";\nimport { WaveShaper } from \"./WaveShaper.js\";\n\n/**\n * AudioToGain converts an input in AudioRange [-1,1] to NormalRange [0,1].\n * @see {@link GainToAudio}.\n * @category Signal\n */\nexport class AudioToGain extends SignalOperator<ToneAudioNodeOptions> {\n\treadonly name: string = \"AudioToGain\";\n\n\t/**\n\t * The node which converts the audio ranges\n\t */\n\tprivate _norm = new WaveShaper({\n\t\tcontext: this.context,\n\t\tmapping: (x) => (x + 1) / 2,\n\t});\n\n\t/**\n\t * The AudioRange input [-1, 1]\n\t */\n\tinput = this._norm;\n\n\t/**\n\t * The GainRange output [0, 1]\n\t */\n\toutput = this._norm;\n\n\t/**\n\t * clean up\n\t */\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis._norm.dispose();\n\t\treturn this;\n\t}\n}\n","import { Gain } from \"../core/context/Gain.js\";\nimport { Param } from \"../core/context/Param.js\";\nimport { optionsFromArguments } from \"../core/util/Defaults.js\";\nimport { Signal, SignalOptions } from \"./Signal.js\";\nimport { InputNode, OutputNode } from \"../core/context/ToneAudioNode.js\";\n\n/**\n * Multiply two incoming signals. Or, if a number is given in the constructor,\n * multiplies the incoming signal by that value.\n *\n * @example\n * // multiply two signals\n * const mult = new Tone.Multiply();\n * const sigA = new Tone.Signal(3);\n * const sigB = new Tone.Signal(4);\n * sigA.connect(mult);\n * sigB.connect(mult.factor);\n * // output of mult is 12.\n * @example\n * // multiply a signal and a number\n * const mult = new Tone.Multiply(10);\n * const sig = new Tone.Signal(2).connect(mult);\n * // the output of mult is 20.\n * @category Signal\n */\nexport class Multiply<\n\tTypeName extends \"number\" | \"positive\" = \"number\",\n> extends Signal<TypeName> {\n\treadonly name: string = \"Multiply\";\n\n\t/**\n\t * Indicates if the value should be overridden on connection\n\t */\n\treadonly override = false;\n\n\t/**\n\t * the input gain node\n\t */\n\tprivate _mult: Gain;\n\n\t/**\n\t * The multiplicand input.\n\t */\n\tinput: InputNode;\n\n\t/**\n\t * The product of the input and {@link factor}\n\t */\n\toutput: OutputNode;\n\n\t/**\n\t * The multiplication factor. Can be set directly or a signal can be connected to it.\n\t */\n\tfactor: Param<TypeName>;\n\n\t/**\n\t * @param value Constant value to multiple\n\t */\n\tconstructor(value?: number);\n\tconstructor(options?: Partial<SignalOptions<TypeName>>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(\n\t\t\tMultiply.getDefaults(),\n\t\t\targuments,\n\t\t\t[\"value\"]\n\t\t);\n\t\tsuper(options);\n\n\t\tthis._mult =\n\t\t\tthis.input =\n\t\t\tthis.output =\n\t\t\t\tnew Gain({\n\t\t\t\t\tcontext: this.context,\n\t\t\t\t\tminValue: options.minValue,\n\t\t\t\t\tmaxValue: options.maxValue,\n\t\t\t\t});\n\n\t\tthis.factor = this._param = this._mult\n\t\t\t.gain as unknown as Param<TypeName>;\n\t\tthis.factor.setValueAtTime(options.value, 0);\n\t}\n\n\tstatic getDefaults(): SignalOptions<any> {\n\t\treturn Object.assign(Signal.getDefaults(), {\n\t\t\tvalue: 0,\n\t\t});\n\t}\n\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis._mult.dispose();\n\t\treturn this;\n\t}\n}\n","import { Gain } from \"../../core/context/Gain.js\";\nimport { Degrees, Frequency, Seconds } from \"../../core/type/Units.js\";\nimport { optionsFromArguments } from \"../../core/util/Defaults.js\";\nimport { readOnly } from \"../../core/util/Interface.js\";\nimport { AudioToGain } from \"../../signal/AudioToGain.js\";\nimport { Multiply } from \"../../signal/Multiply.js\";\nimport { Signal } from \"../../signal/Signal.js\";\nimport { Source } from \"../Source.js\";\nimport { Oscillator } from \"./Oscillator.js\";\nimport {\n\tAMConstructorOptions,\n\tAMOscillatorOptions,\n\tgenerateWaveform,\n\tNonCustomOscillatorType,\n\tToneOscillatorInterface,\n\tToneOscillatorType,\n} from \"./OscillatorInterface.js\";\n\nexport { AMOscillatorOptions } from \"./OscillatorInterface.js\";\n\n/**\n * An amplitude modulated oscillator node. It is implemented with\n * two oscillators, one which modulators the other's amplitude\n * through a gain node.\n * ```\n * +-------------+ +----------+\n * | Carrier Osc +>------> GainNode |\n * +-------------+ | +--->Output\n * +---> gain |\n * +---------------+ | +----------+\n * | Modulator Osc +>---+\n * +---------------+\n * ```\n * @example\n * return Tone.Offline(() => {\n * \tconst amOsc = new Tone.AMOscillator(30, \"sine\", \"square\").toDestination().start();\n * }, 0.2, 1);\n * @category Source\n */\nexport class AMOscillator\n\textends Source<AMOscillatorOptions>\n\timplements ToneOscillatorInterface\n{\n\treadonly name: string = \"AMOscillator\";\n\n\t/**\n\t * The carrier oscillator\n\t */\n\tprivate _carrier: Oscillator;\n\n\treadonly frequency: Signal<\"frequency\">;\n\treadonly detune: Signal<\"cents\">;\n\n\t/**\n\t * The modulating oscillator\n\t */\n\tprivate _modulator: Oscillator;\n\n\t/**\n\t * convert the -1,1 output to 0,1\n\t */\n\tprivate _modulationScale = new AudioToGain({ context: this.context });\n\n\t/**\n\t * Harmonicity is the frequency ratio between the carrier and the modulator oscillators.\n\t * A harmonicity of 1 gives both oscillators the same frequency.\n\t * Harmonicity = 2 means a change of an octave.\n\t * @example\n\t * const amOsc = new Tone.AMOscillator(\"D2\").toDestination().start();\n\t * Tone.Transport.scheduleRepeat(time => {\n\t * \tamOsc.harmonicity.setValueAtTime(1, time);\n\t * \tamOsc.harmonicity.setValueAtTime(0.5, time + 0.5);\n\t * \tamOsc.harmonicity.setValueAtTime(1.5, time + 1);\n\t * \tamOsc.harmonicity.setValueAtTime(1, time + 2);\n\t * \tamOsc.harmonicity.linearRampToValueAtTime(2, time + 4);\n\t * }, 4);\n\t * Tone.Transport.start();\n\t */\n\treadonly harmonicity: Signal<\"positive\">;\n\n\t/**\n\t * the node where the modulation happens\n\t */\n\tprivate _modulationNode = new Gain({\n\t\tcontext: this.context,\n\t});\n\n\t/**\n\t * @param frequency The starting frequency of the oscillator.\n\t * @param type The type of the carrier oscillator.\n\t * @param modulationType The type of the modulator oscillator.\n\t */\n\tconstructor(\n\t\tfrequency?: Frequency,\n\t\ttype?: ToneOscillatorType,\n\t\tmodulationType?: ToneOscillatorType\n\t);\n\tconstructor(options?: Partial<AMConstructorOptions>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(\n\t\t\tAMOscillator.getDefaults(),\n\t\t\targuments,\n\t\t\t[\"frequency\", \"type\", \"modulationType\"]\n\t\t);\n\t\tsuper(options);\n\n\t\tthis._carrier = new Oscillator({\n\t\t\tcontext: this.context,\n\t\t\tdetune: options.detune,\n\t\t\tfrequency: options.frequency,\n\t\t\tonstop: () => this.onstop(this),\n\t\t\tphase: options.phase,\n\t\t\ttype: options.type,\n\t\t} as OscillatorOptions);\n\t\t(this.frequency = this._carrier.frequency),\n\t\t\t(this.detune = this._carrier.detune);\n\n\t\tthis._modulator = new Oscillator({\n\t\t\tcontext: this.context,\n\t\t\tphase: options.phase,\n\t\t\ttype: options.modulationType,\n\t\t} as OscillatorOptions);\n\n\t\tthis.harmonicity = new Multiply({\n\t\t\tcontext: this.context,\n\t\t\tunits: \"positive\",\n\t\t\tvalue: options.harmonicity,\n\t\t});\n\n\t\t// connections\n\t\tthis.frequency.chain(this.harmonicity, this._modulator.frequency);\n\t\tthis._modulator.chain(this._modulationScale, this._modulationNode.gain);\n\t\tthis._carrier.chain(this._modulationNode, this.output);\n\n\t\treadOnly(this, [\"frequency\", \"detune\", \"harmonicity\"]);\n\t}\n\n\tstatic getDefaults(): AMOscillatorOptions {\n\t\treturn Object.assign(Oscillator.getDefaults(), {\n\t\t\tharmonicity: 1,\n\t\t\tmodulationType: \"square\" as NonCustomOscillatorType,\n\t\t});\n\t}\n\n\t/**\n\t * start the oscillator\n\t */\n\tprotected _start(time: Seconds): void {\n\t\tthis._modulator.start(time);\n\t\tthis._carrier.start(time);\n\t}\n\n\t/**\n\t * stop the oscillator\n\t */\n\tprotected _stop(time: Seconds): void {\n\t\tthis._modulator.stop(time);\n\t\tthis._carrier.stop(time);\n\t}\n\n\tprotected _restart(time: Seconds): void {\n\t\tthis._modulator.restart(time);\n\t\tthis._carrier.restart(time);\n\t}\n\n\t/**\n\t * The type of the carrier oscillator\n\t */\n\tget type(): ToneOscillatorType {\n\t\treturn this._carrier.type;\n\t}\n\tset type(type: ToneOscillatorType) {\n\t\tthis._carrier.type = type;\n\t}\n\n\tget baseType(): OscillatorType {\n\t\treturn this._carrier.baseType;\n\t}\n\tset baseType(baseType: OscillatorType) {\n\t\tthis._carrier.baseType = baseType;\n\t}\n\n\tget partialCount(): number {\n\t\treturn this._carrier.partialCount;\n\t}\n\tset partialCount(partialCount: number) {\n\t\tthis._carrier.partialCount = partialCount;\n\t}\n\n\t/**\n\t * The type of the modulator oscillator\n\t */\n\tget modulationType(): ToneOscillatorType {\n\t\treturn this._modulator.type;\n\t}\n\tset modulationType(type: ToneOscillatorType) {\n\t\tthis._modulator.type = type;\n\t}\n\n\tget phase(): Degrees {\n\t\treturn this._carrier.phase;\n\t}\n\tset phase(phase: Degrees) {\n\t\tthis._carrier.phase = phase;\n\t\tthis._modulator.phase = phase;\n\t}\n\n\tget partials(): number[] {\n\t\treturn this._carrier.partials;\n\t}\n\tset partials(partials: number[]) {\n\t\tthis._carrier.partials = partials;\n\t}\n\n\tasync asArray(length = 1024): Promise<Float32Array> {\n\t\treturn generateWaveform(this, length);\n\t}\n\n\t/**\n\t * Clean up.\n\t */\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis.frequency.dispose();\n\t\tthis.detune.dispose();\n\t\tthis.harmonicity.dispose();\n\t\tthis._carrier.dispose();\n\t\tthis._modulator.dispose();\n\t\tthis._modulationNode.dispose();\n\t\tthis._modulationScale.dispose();\n\t\treturn this;\n\t}\n}\n","import { Gain } from \"../../core/context/Gain.js\";\nimport { Degrees, Frequency, Seconds, Time } from \"../../core/type/Units.js\";\nimport { optionsFromArguments } from \"../../core/util/Defaults.js\";\nimport { readOnly } from \"../../core/util/Interface.js\";\nimport { Multiply } from \"../../signal/Multiply.js\";\nimport { Signal } from \"../../signal/Signal.js\";\nimport { Source } from \"../Source.js\";\nimport { Oscillator } from \"./Oscillator.js\";\nimport {\n\tFMConstructorOptions,\n\tFMOscillatorOptions,\n\tgenerateWaveform,\n\tNonCustomOscillatorType,\n\tToneOscillatorInterface,\n\tToneOscillatorType,\n} from \"./OscillatorInterface.js\";\n\nexport { FMOscillatorOptions } from \"./OscillatorInterface.js\";\n/**\n * FMOscillator implements a frequency modulation synthesis\n * ```\n * +-------------+\n * +---------------+ +-------------+ | Carrier Osc |\n * | Modulator Osc +>-------> GainNode | | +--->Output\n * +---------------+ | +>----> frequency |\n * +--> gain | +-------------+\n * | +-------------+\n * +-----------------+ |\n * | modulationIndex +>--+\n * +-----------------+\n * ```\n *\n * @example\n * return Tone.Offline(() => {\n * \tconst fmOsc = new Tone.FMOscillator({\n * \t\tfrequency: 200,\n * \t\ttype: \"square\",\n * \t\tmodulationType: \"triangle\",\n * \t\tharmonicity: 0.2,\n * \t\tmodulationIndex: 3\n * \t}).toDestination().start();\n * }, 0.1, 1);\n * @category Source\n */\nexport class FMOscillator\n\textends Source<FMOscillatorOptions>\n\timplements ToneOscillatorInterface\n{\n\treadonly name: string = \"FMOscillator\";\n\n\t/**\n\t * The carrier oscillator\n\t */\n\tprivate _carrier: Oscillator;\n\n\treadonly frequency: Signal<\"frequency\">;\n\treadonly detune: Signal<\"cents\">;\n\n\t/**\n\t * The modulating oscillator\n\t */\n\tprivate _modulator: Oscillator;\n\n\t/**\n\t * Harmonicity is the frequency ratio between the carrier and the modulator oscillators.\n\t * A harmonicity of 1 gives both oscillators the same frequency.\n\t * Harmonicity = 2 means a change of an octave.\n\t * @example\n\t * const fmOsc = new Tone.FMOscillator(\"D2\").toDestination().start();\n\t * // pitch the modulator an octave below carrier\n\t * fmOsc.harmonicity.value = 0.5;\n\t */\n\treadonly harmonicity: Signal<\"positive\">;\n\n\t/**\n\t * The modulation index which is in essence the depth or amount of the modulation. In other terms it is the\n\t * ratio of the frequency of the modulating signal (mf) to the amplitude of the\n\t * modulating signal (ma) -- as in ma/mf.\n\t */\n\treadonly modulationIndex: Signal<\"positive\">;\n\n\t/**\n\t * the node where the modulation happens\n\t */\n\tprivate _modulationNode: Gain = new Gain({\n\t\tcontext: this.context,\n\t\tgain: 0,\n\t});\n\n\t/**\n\t * @param frequency The starting frequency of the oscillator.\n\t * @param type The type of the carrier oscillator.\n\t * @param modulationType The type of the modulator oscillator.\n\t */\n\tconstructor(\n\t\tfrequency?: Frequency,\n\t\ttype?: ToneOscillatorType,\n\t\tmodulationType?: ToneOscillatorType\n\t);\n\tconstructor(options?: Partial<FMConstructorOptions>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(\n\t\t\tFMOscillator.getDefaults(),\n\t\t\targuments,\n\t\t\t[\"frequency\", \"type\", \"modulationType\"]\n\t\t);\n\t\tsuper(options);\n\n\t\tthis._carrier = new Oscillator({\n\t\t\tcontext: this.context,\n\t\t\tdetune: options.detune,\n\t\t\tfrequency: 0,\n\t\t\tonstop: () => this.onstop(this),\n\t\t\tphase: options.phase,\n\t\t\ttype: options.type,\n\t\t} as OscillatorOptions);\n\n\t\tthis.detune = this._carrier.detune;\n\n\t\tthis.frequency = new Signal({\n\t\t\tcontext: this.context,\n\t\t\tunits: \"frequency\",\n\t\t\tvalue: options.frequency,\n\t\t});\n\n\t\tthis._modulator = new Oscillator({\n\t\t\tcontext: this.context,\n\t\t\tphase: options.phase,\n\t\t\ttype: options.modulationType,\n\t\t} as OscillatorOptions);\n\n\t\tthis.harmonicity = new Multiply({\n\t\t\tcontext: this.context,\n\t\t\tunits: \"positive\",\n\t\t\tvalue: options.harmonicity,\n\t\t});\n\n\t\tthis.modulationIndex = new Multiply({\n\t\t\tcontext: this.context,\n\t\t\tunits: \"positive\",\n\t\t\tvalue: options.modulationIndex,\n\t\t});\n\n\t\t// connections\n\t\tthis.frequency.connect(this._carrier.frequency);\n\t\tthis.frequency.chain(this.harmonicity, this._modulator.frequency);\n\t\tthis.frequency.chain(this.modulationIndex, this._modulationNode);\n\t\tthis._modulator.connect(this._modulationNode.gain);\n\t\tthis._modulationNode.connect(this._carrier.frequency);\n\t\tthis._carrier.connect(this.output);\n\t\tthis.detune.connect(this._modulator.detune);\n\n\t\treadOnly(this, [\n\t\t\t\"modulationIndex\",\n\t\t\t\"frequency\",\n\t\t\t\"detune\",\n\t\t\t\"harmonicity\",\n\t\t]);\n\t}\n\n\tstatic getDefaults(): FMOscillatorOptions {\n\t\treturn Object.assign(Oscillator.getDefaults(), {\n\t\t\tharmonicity: 1,\n\t\t\tmodulationIndex: 2,\n\t\t\tmodulationType: \"square\" as NonCustomOscillatorType,\n\t\t});\n\t}\n\n\t/**\n\t * start the oscillator\n\t */\n\tprotected _start(time: Time): void {\n\t\tthis._modulator.start(time);\n\t\tthis._carrier.start(time);\n\t}\n\n\t/**\n\t * stop the oscillator\n\t */\n\tprotected _stop(time: Time): void {\n\t\tthis._modulator.stop(time);\n\t\tthis._carrier.stop(time);\n\t}\n\n\tprotected _restart(time: Seconds): this {\n\t\tthis._modulator.restart(time);\n\t\tthis._carrier.restart(time);\n\t\treturn this;\n\t}\n\n\tget type(): ToneOscillatorType {\n\t\treturn this._carrier.type;\n\t}\n\tset type(type: ToneOscillatorType) {\n\t\tthis._carrier.type = type;\n\t}\n\n\tget baseType(): OscillatorType {\n\t\treturn this._carrier.baseType;\n\t}\n\tset baseType(baseType: OscillatorType) {\n\t\tthis._carrier.baseType = baseType;\n\t}\n\n\tget partialCount(): number {\n\t\treturn this._carrier.partialCount;\n\t}\n\tset partialCount(partialCount: number) {\n\t\tthis._carrier.partialCount = partialCount;\n\t}\n\n\t/**\n\t * The type of the modulator oscillator\n\t */\n\tget modulationType(): ToneOscillatorType {\n\t\treturn this._modulator.type;\n\t}\n\tset modulationType(type: ToneOscillatorType) {\n\t\tthis._modulator.type = type;\n\t}\n\n\tget phase(): Degrees {\n\t\treturn this._carrier.phase;\n\t}\n\tset phase(phase: Degrees) {\n\t\tthis._carrier.phase = phase;\n\t\tthis._modulator.phase = phase;\n\t}\n\n\tget partials(): number[] {\n\t\treturn this._carrier.partials;\n\t}\n\tset partials(partials: number[]) {\n\t\tthis._carrier.partials = partials;\n\t}\n\n\tasync asArray(length = 1024): Promise<Float32Array> {\n\t\treturn generateWaveform(this, length);\n\t}\n\n\t/**\n\t * Clean up.\n\t */\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis.frequency.dispose();\n\t\tthis.harmonicity.dispose();\n\t\tthis._carrier.dispose();\n\t\tthis._modulator.dispose();\n\t\tthis._modulationNode.dispose();\n\t\tthis.modulationIndex.dispose();\n\t\treturn this;\n\t}\n}\n","import { Gain } from \"../../core/context/Gain.js\";\nimport {\n\tAudioRange,\n\tDegrees,\n\tFrequency,\n\tSeconds,\n\tTime,\n} from \"../../core/type/Units.js\";\nimport { optionsFromArguments } from \"../../core/util/Defaults.js\";\nimport { readOnly } from \"../../core/util/Interface.js\";\nimport { Signal } from \"../../signal/Signal.js\";\nimport { WaveShaper } from \"../../signal/WaveShaper.js\";\nimport { Source } from \"../Source.js\";\nimport { Oscillator } from \"./Oscillator.js\";\nimport {\n\tgenerateWaveform,\n\tPulseOscillatorOptions,\n\tToneOscillatorInterface,\n} from \"./OscillatorInterface.js\";\n\nexport { PulseOscillatorOptions } from \"./OscillatorInterface.js\";\n\n/**\n * PulseOscillator is an oscillator with control over pulse width,\n * also known as the duty cycle. At 50% duty cycle (width = 0) the wave is\n * a square wave.\n * [Read more](https://wigglewave.wordpress.com/2014/08/16/pulse-waveforms-and-harmonics/).\n * ```\n * width = -0.25 width = 0.0 width = 0.25\n *\n * +-----+ +-------+ + +-------+ +-+\n * | | | | | | |\n * | | | | | | |\n * +-+ +-------+ + +-------+ +-----+\n *\n *\n * width = -0.5 width = 0.5\n *\n * +---+ +-------+ +---+\n * | | | |\n * | | | |\n * +---+ +-------+ +---+\n *\n *\n * width = -0.75 width = 0.75\n *\n * +-+ +-------+ +-----+\n * | | | |\n * | | | |\n * +-----+ +-------+ +-+\n * ```\n * @example\n * return Tone.Offline(() => {\n * \tconst pulse = new Tone.PulseOscillator(50, 0.4).toDestination().start();\n * }, 0.1, 1);\n * @category Source\n */\nexport class PulseOscillator\n\textends Source<PulseOscillatorOptions>\n\timplements ToneOscillatorInterface\n{\n\treadonly name: string = \"PulseOscillator\";\n\n\t/**\n\t * The width of the pulse.\n\t * @example\n\t * return Tone.Offline(() => {\n\t * \tconst pulse = new Tone.PulseOscillator(20, 0.8).toDestination().start();\n\t * }, 0.1, 1);\n\t */\n\treadonly width: Signal<\"audioRange\">;\n\n\t/**\n\t * gate the width amount\n\t */\n\tprivate _widthGate: Gain = new Gain({\n\t\tcontext: this.context,\n\t\tgain: 0,\n\t});\n\n\t/**\n\t * the sawtooth oscillator\n\t */\n\tprivate _triangle: Oscillator;\n\n\t/**\n\t * The frequency control.\n\t */\n\treadonly frequency: Signal<\"frequency\">;\n\n\t/**\n\t * The detune in cents.\n\t */\n\treadonly detune: Signal<\"cents\">;\n\n\t/**\n\t * Threshold the signal to turn it into a square\n\t */\n\tprivate _thresh = new WaveShaper({\n\t\tcontext: this.context,\n\t\tmapping: (val) => (val <= 0 ? -1 : 1),\n\t});\n\n\t/**\n\t * @param frequency The frequency of the oscillator\n\t * @param width The width of the pulse\n\t */\n\tconstructor(frequency?: Frequency, width?: AudioRange);\n\tconstructor(options?: Partial<PulseOscillatorOptions>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(\n\t\t\tPulseOscillator.getDefaults(),\n\t\t\targuments,\n\t\t\t[\"frequency\", \"width\"]\n\t\t);\n\t\tsuper(options);\n\n\t\tthis.width = new Signal({\n\t\t\tcontext: this.context,\n\t\t\tunits: \"audioRange\",\n\t\t\tvalue: options.width,\n\t\t});\n\n\t\tthis._triangle = new Oscillator({\n\t\t\tcontext: this.context,\n\t\t\tdetune: options.detune,\n\t\t\tfrequency: options.frequency,\n\t\t\tonstop: () => this.onstop(this),\n\t\t\tphase: options.phase,\n\t\t\ttype: \"triangle\",\n\t\t});\n\t\tthis.frequency = this._triangle.frequency;\n\t\tthis.detune = this._triangle.detune;\n\n\t\t// connections\n\t\tthis._triangle.chain(this._thresh, this.output);\n\t\tthis.width.chain(this._widthGate, this._thresh);\n\t\treadOnly(this, [\"width\", \"frequency\", \"detune\"]);\n\t}\n\n\tstatic getDefaults(): PulseOscillatorOptions {\n\t\treturn Object.assign(Source.getDefaults(), {\n\t\t\tdetune: 0,\n\t\t\tfrequency: 440,\n\t\t\tphase: 0,\n\t\t\ttype: \"pulse\" as const,\n\t\t\twidth: 0.2,\n\t\t});\n\t}\n\n\t/**\n\t * start the oscillator\n\t */\n\tprotected _start(time: Time): void {\n\t\ttime = this.toSeconds(time);\n\t\tthis._triangle.start(time);\n\t\tthis._widthGate.gain.setValueAtTime(1, time);\n\t}\n\n\t/**\n\t * stop the oscillator\n\t */\n\tprotected _stop(time: Time): void {\n\t\ttime = this.toSeconds(time);\n\t\tthis._triangle.stop(time);\n\t\t// the width is still connected to the output.\n\t\t// that needs to be stopped also\n\t\tthis._widthGate.gain.cancelScheduledValues(time);\n\t\tthis._widthGate.gain.setValueAtTime(0, time);\n\t}\n\n\tprotected _restart(time: Seconds): void {\n\t\tthis._triangle.restart(time);\n\t\tthis._widthGate.gain.cancelScheduledValues(time);\n\t\tthis._widthGate.gain.setValueAtTime(1, time);\n\t}\n\n\t/**\n\t * The phase of the oscillator in degrees.\n\t */\n\tget phase(): Degrees {\n\t\treturn this._triangle.phase;\n\t}\n\tset phase(phase: Degrees) {\n\t\tthis._triangle.phase = phase;\n\t}\n\n\t/**\n\t * The type of the oscillator. Always returns \"pulse\".\n\t */\n\tget type(): \"pulse\" {\n\t\treturn \"pulse\";\n\t}\n\n\t/**\n\t * The baseType of the oscillator. Always returns \"pulse\".\n\t */\n\tget baseType(): \"pulse\" {\n\t\treturn \"pulse\";\n\t}\n\n\t/**\n\t * The partials of the waveform. Cannot set partials for this waveform type\n\t */\n\tget partials(): number[] {\n\t\treturn [];\n\t}\n\n\t/**\n\t * No partials for this waveform type.\n\t */\n\tget partialCount(): number {\n\t\treturn 0;\n\t}\n\n\t/**\n\t * *Internal use* The carrier oscillator type is fed through the\n\t * waveshaper node to create the pulse. Using different carrier oscillators\n\t * changes oscillator's behavior.\n\t */\n\tset carrierType(type: \"triangle\" | \"sine\") {\n\t\tthis._triangle.type = type;\n\t}\n\n\tasync asArray(length = 1024): Promise<Float32Array> {\n\t\treturn generateWaveform(this, length);\n\t}\n\n\t/**\n\t * Clean up method.\n\t */\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis._triangle.dispose();\n\t\tthis.width.dispose();\n\t\tthis._widthGate.dispose();\n\t\tthis._thresh.dispose();\n\t\treturn this;\n\t}\n}\n","import {\n\tCents,\n\tDegrees,\n\tFrequency,\n\tSeconds,\n\tTime,\n} from \"../../core/type/Units.js\";\nimport { optionsFromArguments } from \"../../core/util/Defaults.js\";\nimport { noOp, readOnly } from \"../../core/util/Interface.js\";\nimport { Signal } from \"../../signal/Signal.js\";\nimport { Source } from \"../Source.js\";\nimport { Oscillator } from \"./Oscillator.js\";\nimport {\n\tFatConstructorOptions,\n\tFatOscillatorOptions,\n\tgenerateWaveform,\n\tNonCustomOscillatorType,\n\tToneOscillatorInterface,\n\tToneOscillatorType,\n} from \"./OscillatorInterface.js\";\nimport { assertRange } from \"../../core/util/Debug.js\";\n\nexport { FatOscillatorOptions } from \"./OscillatorInterface.js\";\n\n/**\n * FatOscillator is an array of oscillators with detune spread between the oscillators\n * @example\n * const fatOsc = new Tone.FatOscillator(\"Ab3\", \"sawtooth\", 40).toDestination().start();\n * @category Source\n */\nexport class FatOscillator\n\textends Source<FatOscillatorOptions>\n\timplements ToneOscillatorInterface\n{\n\treadonly name: string = \"FatOscillator\";\n\n\treadonly frequency: Signal<\"frequency\">;\n\treadonly detune: Signal<\"cents\">;\n\n\t/**\n\t * The array of oscillators\n\t */\n\tprivate _oscillators: Oscillator[] = [];\n\n\t/**\n\t * The total spread of the oscillators\n\t */\n\tprivate _spread: Cents;\n\n\t/**\n\t * The type of the oscillator\n\t */\n\tprivate _type: ToneOscillatorType;\n\n\t/**\n\t * The phase of the oscillators\n\t */\n\tprivate _phase: Degrees;\n\n\t/**\n\t * The partials array\n\t */\n\tprivate _partials: number[];\n\n\t/**\n\t * The number of partials to use\n\t */\n\tprivate _partialCount: number;\n\n\t/**\n\t * @param frequency The oscillator's frequency.\n\t * @param type The type of the oscillator.\n\t * @param spread The detune spread between the oscillators.\n\t */\n\tconstructor(\n\t\tfrequency?: Frequency,\n\t\ttype?: ToneOscillatorType,\n\t\tspread?: Cents\n\t);\n\tconstructor(options?: Partial<FatConstructorOptions>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(\n\t\t\tFatOscillator.getDefaults(),\n\t\t\targuments,\n\t\t\t[\"frequency\", \"type\", \"spread\"]\n\t\t);\n\t\tsuper(options);\n\n\t\tthis.frequency = new Signal({\n\t\t\tcontext: this.context,\n\t\t\tunits: \"frequency\",\n\t\t\tvalue: options.frequency,\n\t\t});\n\t\tthis.detune = new Signal({\n\t\t\tcontext: this.context,\n\t\t\tunits: \"cents\",\n\t\t\tvalue: options.detune,\n\t\t});\n\n\t\tthis._spread = options.spread;\n\t\tthis._type = options.type;\n\t\tthis._phase = options.phase;\n\t\tthis._partials = options.partials;\n\t\tthis._partialCount = options.partialCount;\n\n\t\t// set the count initially\n\t\tthis.count = options.count;\n\n\t\treadOnly(this, [\"frequency\", \"detune\"]);\n\t}\n\n\tstatic getDefaults(): FatOscillatorOptions {\n\t\treturn Object.assign(Oscillator.getDefaults(), {\n\t\t\tcount: 3,\n\t\t\tspread: 20,\n\t\t\ttype: \"sawtooth\",\n\t\t});\n\t}\n\n\t/**\n\t * start the oscillator\n\t */\n\tprotected _start(time: Time): void {\n\t\ttime = this.toSeconds(time);\n\t\tthis._forEach((osc) => osc.start(time));\n\t}\n\n\t/**\n\t * stop the oscillator\n\t */\n\tprotected _stop(time: Time): void {\n\t\ttime = this.toSeconds(time);\n\t\tthis._forEach((osc) => osc.stop(time));\n\t}\n\n\tprotected _restart(time: Seconds): void {\n\t\tthis._forEach((osc) => osc.restart(time));\n\t}\n\n\t/**\n\t * Iterate over all of the oscillators\n\t */\n\tprivate _forEach(iterator: (osc: Oscillator, index: number) => void): void {\n\t\tfor (let i = 0; i < this._oscillators.length; i++) {\n\t\t\titerator(this._oscillators[i], i);\n\t\t}\n\t}\n\n\t/**\n\t * The type of the oscillator\n\t */\n\tget type(): ToneOscillatorType {\n\t\treturn this._type;\n\t}\n\tset type(type: ToneOscillatorType) {\n\t\tthis._type = type;\n\t\tthis._forEach((osc) => (osc.type = type));\n\t}\n\n\t/**\n\t * The detune spread between the oscillators. If \"count\" is\n\t * set to 3 oscillators and the \"spread\" is set to 40,\n\t * the three oscillators would be detuned like this: [-20, 0, 20]\n\t * for a total detune spread of 40 cents.\n\t * @example\n\t * const fatOsc = new Tone.FatOscillator().toDestination().start();\n\t * fatOsc.spread = 70;\n\t */\n\tget spread(): Cents {\n\t\treturn this._spread;\n\t}\n\tset spread(spread: Cents) {\n\t\tthis._spread = spread;\n\t\tif (this._oscillators.length > 1) {\n\t\t\tconst start = -spread / 2;\n\t\t\tconst step = spread / (this._oscillators.length - 1);\n\t\t\tthis._forEach((osc, i) => (osc.detune.value = start + step * i));\n\t\t}\n\t}\n\n\t/**\n\t * The number of detuned oscillators. Must be an integer greater than 1.\n\t * @example\n\t * const fatOsc = new Tone.FatOscillator(\"C#3\", \"sawtooth\").toDestination().start();\n\t * // use 4 sawtooth oscillators\n\t * fatOsc.count = 4;\n\t */\n\tget count(): number {\n\t\treturn this._oscillators.length;\n\t}\n\tset count(count: number) {\n\t\tassertRange(count, 1);\n\t\tif (this._oscillators.length !== count) {\n\t\t\t// dispose the previous oscillators\n\t\t\tthis._forEach((osc) => osc.dispose());\n\t\t\tthis._oscillators = [];\n\t\t\tfor (let i = 0; i < count; i++) {\n\t\t\t\tconst osc = new Oscillator({\n\t\t\t\t\tcontext: this.context,\n\t\t\t\t\tvolume: -6 - count * 1.1,\n\t\t\t\t\ttype: this._type as NonCustomOscillatorType,\n\t\t\t\t\tphase: this._phase + (i / count) * 360,\n\t\t\t\t\tpartialCount: this._partialCount,\n\t\t\t\t\tonstop: i === 0 ? () => this.onstop(this) : noOp,\n\t\t\t\t});\n\t\t\t\tif (this.type === \"custom\") {\n\t\t\t\t\tosc.partials = this._partials;\n\t\t\t\t}\n\t\t\t\tthis.frequency.connect(osc.frequency);\n\t\t\t\tthis.detune.connect(osc.detune);\n\t\t\t\tosc.detune.overridden = false;\n\t\t\t\tosc.connect(this.output);\n\t\t\t\tthis._oscillators[i] = osc;\n\t\t\t}\n\t\t\t// set the spread\n\t\t\tthis.spread = this._spread;\n\t\t\tif (this.state === \"started\") {\n\t\t\t\tthis._forEach((osc) => osc.start());\n\t\t\t}\n\t\t}\n\t}\n\n\tget phase(): Degrees {\n\t\treturn this._phase;\n\t}\n\tset phase(phase: Degrees) {\n\t\tthis._phase = phase;\n\t\tthis._forEach(\n\t\t\t(osc, i) => (osc.phase = this._phase + (i / this.count) * 360)\n\t\t);\n\t}\n\n\tget baseType(): OscillatorType {\n\t\treturn this._oscillators[0].baseType;\n\t}\n\tset baseType(baseType: OscillatorType) {\n\t\tthis._forEach((osc) => (osc.baseType = baseType));\n\t\tthis._type = this._oscillators[0].type;\n\t}\n\n\tget partials(): number[] {\n\t\treturn this._oscillators[0].partials;\n\t}\n\tset partials(partials: number[]) {\n\t\tthis._partials = partials;\n\t\tthis._partialCount = this._partials.length;\n\t\tif (partials.length) {\n\t\t\tthis._type = \"custom\";\n\t\t\tthis._forEach((osc) => (osc.partials = partials));\n\t\t}\n\t}\n\n\tget partialCount(): number {\n\t\treturn this._oscillators[0].partialCount;\n\t}\n\tset partialCount(partialCount: number) {\n\t\tthis._partialCount = partialCount;\n\t\tthis._forEach((osc) => (osc.partialCount = partialCount));\n\t\tthis._type = this._oscillators[0].type;\n\t}\n\n\tasync asArray(length = 1024): Promise<Float32Array> {\n\t\treturn generateWaveform(this, length);\n\t}\n\n\t/**\n\t * Clean up.\n\t */\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis.frequency.dispose();\n\t\tthis.detune.dispose();\n\t\tthis._forEach((osc) => osc.dispose());\n\t\treturn this;\n\t}\n}\n","import { Degrees, Frequency, Seconds, Time } from \"../../core/type/Units.js\";\nimport { optionsFromArguments } from \"../../core/util/Defaults.js\";\nimport { readOnly } from \"../../core/util/Interface.js\";\nimport { Multiply } from \"../../signal/Multiply.js\";\nimport { Signal } from \"../../signal/Signal.js\";\nimport { Source } from \"../Source.js\";\nimport { Oscillator } from \"./Oscillator.js\";\nimport {\n\tgenerateWaveform,\n\tPWMOscillatorOptions,\n\tToneOscillatorInterface,\n} from \"./OscillatorInterface.js\";\nimport { PulseOscillator } from \"./PulseOscillator.js\";\n\nexport { PWMOscillatorOptions } from \"./OscillatorInterface.js\";\n\n/**\n * PWMOscillator modulates the width of a Tone.PulseOscillator\n * at the modulationFrequency. This has the effect of continuously\n * changing the timbre of the oscillator by altering the harmonics\n * generated.\n * @example\n * return Tone.Offline(() => {\n * \tconst pwm = new Tone.PWMOscillator(60, 0.3).toDestination().start();\n * }, 0.1, 1);\n * @category Source\n */\nexport class PWMOscillator\n\textends Source<PWMOscillatorOptions>\n\timplements ToneOscillatorInterface\n{\n\treadonly name: string = \"PWMOscillator\";\n\n\treadonly sourceType = \"pwm\";\n\n\t/**\n\t * the pulse oscillator\n\t */\n\tprivate _pulse: PulseOscillator;\n\t/**\n\t * the modulator\n\t */\n\tprivate _modulator: Oscillator;\n\n\t/**\n\t * Scale the oscillator so it doesn't go silent\n\t * at the extreme values.\n\t */\n\tprivate _scale: Multiply = new Multiply({\n\t\tcontext: this.context,\n\t\tvalue: 2,\n\t});\n\n\t/**\n\t * The frequency control.\n\t */\n\treadonly frequency: Signal<\"frequency\">;\n\n\t/**\n\t * The detune of the oscillator.\n\t */\n\treadonly detune: Signal<\"cents\">;\n\n\t/**\n\t * The width modulation rate of the oscillator.\n\t * @example\n\t * return Tone.Offline(() => {\n\t * \tconst osc = new Tone.PWMOscillator(20, 2).toDestination().start();\n\t * }, 0.1, 1);\n\t */\n\treadonly modulationFrequency: Signal<\"frequency\">;\n\n\t/**\n\t * @param {Frequency} frequency The starting frequency of the oscillator.\n\t * @param {Frequency} modulationFrequency The modulation frequency of the width of the pulse.\n\t */\n\tconstructor(frequency?: Frequency, modulationFrequency?: Frequency);\n\tconstructor(options?: Partial<PWMOscillatorOptions>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(\n\t\t\tPWMOscillator.getDefaults(),\n\t\t\targuments,\n\t\t\t[\"frequency\", \"modulationFrequency\"]\n\t\t);\n\t\tsuper(options);\n\n\t\tthis._pulse = new PulseOscillator({\n\t\t\tcontext: this.context,\n\t\t\tfrequency: options.modulationFrequency,\n\t\t});\n\t\t// change the pulse oscillator type\n\t\tthis._pulse.carrierType = \"sine\";\n\n\t\tthis.modulationFrequency = this._pulse.frequency;\n\n\t\tthis._modulator = new Oscillator({\n\t\t\tcontext: this.context,\n\t\t\tdetune: options.detune,\n\t\t\tfrequency: options.frequency,\n\t\t\tonstop: () => this.onstop(this),\n\t\t\tphase: options.phase,\n\t\t});\n\n\t\tthis.frequency = this._modulator.frequency;\n\t\tthis.detune = this._modulator.detune;\n\n\t\t// connections\n\t\tthis._modulator.chain(this._scale, this._pulse.width);\n\t\tthis._pulse.connect(this.output);\n\t\treadOnly(this, [\"modulationFrequency\", \"frequency\", \"detune\"]);\n\t}\n\n\tstatic getDefaults(): PWMOscillatorOptions {\n\t\treturn Object.assign(Source.getDefaults(), {\n\t\t\tdetune: 0,\n\t\t\tfrequency: 440,\n\t\t\tmodulationFrequency: 0.4,\n\t\t\tphase: 0,\n\t\t\ttype: \"pwm\" as const,\n\t\t});\n\t}\n\t/**\n\t * start the oscillator\n\t */\n\tprotected _start(time: Time): void {\n\t\ttime = this.toSeconds(time);\n\t\tthis._modulator.start(time);\n\t\tthis._pulse.start(time);\n\t}\n\n\t/**\n\t * stop the oscillator\n\t */\n\tprotected _stop(time: Time): void {\n\t\ttime = this.toSeconds(time);\n\t\tthis._modulator.stop(time);\n\t\tthis._pulse.stop(time);\n\t}\n\n\t/**\n\t * restart the oscillator\n\t */\n\tprotected _restart(time: Seconds): void {\n\t\tthis._modulator.restart(time);\n\t\tthis._pulse.restart(time);\n\t}\n\n\t/**\n\t * The type of the oscillator. Always returns \"pwm\".\n\t */\n\tget type(): \"pwm\" {\n\t\treturn \"pwm\";\n\t}\n\n\t/**\n\t * The baseType of the oscillator. Always returns \"pwm\".\n\t */\n\tget baseType(): \"pwm\" {\n\t\treturn \"pwm\";\n\t}\n\n\t/**\n\t * The partials of the waveform. Cannot set partials for this waveform type\n\t */\n\tget partials(): number[] {\n\t\treturn [];\n\t}\n\n\t/**\n\t * No partials for this waveform type.\n\t */\n\tget partialCount(): number {\n\t\treturn 0;\n\t}\n\n\t/**\n\t * The phase of the oscillator in degrees.\n\t */\n\tget phase(): Degrees {\n\t\treturn this._modulator.phase;\n\t}\n\tset phase(phase: Degrees) {\n\t\tthis._modulator.phase = phase;\n\t}\n\n\tasync asArray(length = 1024): Promise<Float32Array> {\n\t\treturn generateWaveform(this, length);\n\t}\n\n\t/**\n\t * Clean up.\n\t */\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis._pulse.dispose();\n\t\tthis._scale.dispose();\n\t\tthis._modulator.dispose();\n\t\treturn this;\n\t}\n}\n","import {\n\tCents,\n\tDegrees,\n\tFrequency,\n\tSeconds,\n\tTime,\n} from \"../../core/type/Units.js\";\nimport { optionsFromArguments } from \"../../core/util/Defaults.js\";\nimport { readOnly } from \"../../core/util/Interface.js\";\nimport { isNumber, isString } from \"../../core/util/TypeCheck.js\";\nimport { Signal } from \"../../signal/Signal.js\";\nimport { Source } from \"../Source.js\";\nimport { AMOscillator } from \"./AMOscillator.js\";\nimport { FatOscillator } from \"./FatOscillator.js\";\nimport { FMOscillator } from \"./FMOscillator.js\";\nimport { Oscillator } from \"./Oscillator.js\";\nimport {\n\tgenerateWaveform,\n\tOmniOscillatorOptions,\n\tOmniOscillatorType,\n\tToneOscillatorInterface,\n\tToneOscillatorType,\n} from \"./OscillatorInterface.js\";\nimport { PulseOscillator } from \"./PulseOscillator.js\";\nimport { PWMOscillator } from \"./PWMOscillator.js\";\n\nexport { OmniOscillatorOptions } from \"./OscillatorInterface.js\";\n\n/**\n * All of the oscillator types that OmniOscillator can take on\n */\ntype AnyOscillator =\n\t| Oscillator\n\t| PWMOscillator\n\t| PulseOscillator\n\t| FatOscillator\n\t| AMOscillator\n\t| FMOscillator;\n\n/**\n * All of the Oscillator constructor types mapped to their name.\n */\ninterface OmniOscillatorSource {\n\tfm: FMOscillator;\n\tam: AMOscillator;\n\tpwm: PWMOscillator;\n\tpulse: PulseOscillator;\n\toscillator: Oscillator;\n\tfat: FatOscillator;\n}\n\n/**\n * The available oscillator types.\n */\nexport type OmniOscSourceType = keyof OmniOscillatorSource;\n\n// Conditional Types\ntype IsAmOrFmOscillator<Osc, Ret> = Osc extends AMOscillator\n\t? Ret\n\t: Osc extends FMOscillator\n\t\t? Ret\n\t\t: undefined;\ntype IsFatOscillator<Osc, Ret> = Osc extends FatOscillator ? Ret : undefined;\ntype IsPWMOscillator<Osc, Ret> = Osc extends PWMOscillator ? Ret : undefined;\ntype IsPulseOscillator<Osc, Ret> = Osc extends PulseOscillator\n\t? Ret\n\t: undefined;\ntype IsFMOscillator<Osc, Ret> = Osc extends FMOscillator ? Ret : undefined;\n\ntype AnyOscillatorConstructor = new (...args: any[]) => AnyOscillator;\n\nconst OmniOscillatorSourceMap: {\n\t[key in OmniOscSourceType]: AnyOscillatorConstructor;\n} = {\n\tam: AMOscillator,\n\tfat: FatOscillator,\n\tfm: FMOscillator,\n\toscillator: Oscillator,\n\tpulse: PulseOscillator,\n\tpwm: PWMOscillator,\n};\n\n/**\n * OmniOscillator aggregates all of the oscillator types into one.\n * @example\n * return Tone.Offline(() => {\n * \tconst omniOsc = new Tone.OmniOscillator(\"C#4\", \"pwm\").toDestination().start();\n * }, 0.1, 1);\n * @category Source\n */\nexport class OmniOscillator<OscType extends AnyOscillator>\n\textends Source<OmniOscillatorOptions>\n\timplements Omit<ToneOscillatorInterface, \"type\">\n{\n\treadonly name: string = \"OmniOscillator\";\n\n\treadonly frequency: Signal<\"frequency\">;\n\treadonly detune: Signal<\"cents\">;\n\n\t/**\n\t * The oscillator that can switch types\n\t */\n\tprivate _oscillator!: AnyOscillator;\n\n\t/**\n\t * the type of the oscillator source\n\t */\n\tprivate _sourceType!: OmniOscSourceType;\n\n\t/**\n\t * @param frequency The initial frequency of the oscillator.\n\t * @param type The type of the oscillator.\n\t */\n\tconstructor(frequency?: Frequency, type?: OmniOscillatorType);\n\tconstructor(options?: Partial<OmniOscillatorOptions>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(\n\t\t\tOmniOscillator.getDefaults(),\n\t\t\targuments,\n\t\t\t[\"frequency\", \"type\"]\n\t\t);\n\t\tsuper(options);\n\n\t\tthis.frequency = new Signal({\n\t\t\tcontext: this.context,\n\t\t\tunits: \"frequency\",\n\t\t\tvalue: options.frequency,\n\t\t});\n\t\tthis.detune = new Signal({\n\t\t\tcontext: this.context,\n\t\t\tunits: \"cents\",\n\t\t\tvalue: options.detune,\n\t\t});\n\t\treadOnly(this, [\"frequency\", \"detune\"]);\n\n\t\t// set the options\n\t\tthis.set(options);\n\t}\n\n\tstatic getDefaults(): OmniOscillatorOptions {\n\t\treturn Object.assign(\n\t\t\tOscillator.getDefaults(),\n\t\t\tFMOscillator.getDefaults(),\n\t\t\tAMOscillator.getDefaults(),\n\t\t\tFatOscillator.getDefaults(),\n\t\t\tPulseOscillator.getDefaults(),\n\t\t\tPWMOscillator.getDefaults()\n\t\t);\n\t}\n\n\t/**\n\t * start the oscillator\n\t */\n\tprotected _start(time: Time): void {\n\t\tthis._oscillator.start(time);\n\t}\n\n\t/**\n\t * start the oscillator\n\t */\n\tprotected _stop(time: Time): void {\n\t\tthis._oscillator.stop(time);\n\t}\n\n\tprotected _restart(time: Seconds): this {\n\t\tthis._oscillator.restart(time);\n\t\treturn this;\n\t}\n\n\t/**\n\t * The type of the oscillator. Can be any of the basic types: sine, square, triangle, sawtooth. Or\n\t * prefix the basic types with \"fm\", \"am\", or \"fat\" to use the FMOscillator, AMOscillator or FatOscillator\n\t * types. The oscillator could also be set to \"pwm\" or \"pulse\". All of the parameters of the\n\t * oscillator's class are accessible when the oscillator is set to that type, but throws an error\n\t * when it's not.\n\t * @example\n\t * const omniOsc = new Tone.OmniOscillator().toDestination().start();\n\t * omniOsc.type = \"pwm\";\n\t * // modulationFrequency is parameter which is available\n\t * // only when the type is \"pwm\".\n\t * omniOsc.modulationFrequency.value = 0.5;\n\t */\n\tget type(): OmniOscillatorType {\n\t\tlet prefix = \"\";\n\t\tif ([\"am\", \"fm\", \"fat\"].some((p) => this._sourceType === p)) {\n\t\t\tprefix = this._sourceType;\n\t\t}\n\t\treturn (prefix + this._oscillator.type) as OmniOscillatorType;\n\t}\n\tset type(type) {\n\t\tif (type.substr(0, 2) === \"fm\") {\n\t\t\tthis._createNewOscillator(\"fm\");\n\t\t\tthis._oscillator = this._oscillator as FMOscillator;\n\t\t\tthis._oscillator.type = type.substr(2) as ToneOscillatorType;\n\t\t} else if (type.substr(0, 2) === \"am\") {\n\t\t\tthis._createNewOscillator(\"am\");\n\t\t\tthis._oscillator = this._oscillator as AMOscillator;\n\t\t\tthis._oscillator.type = type.substr(2) as ToneOscillatorType;\n\t\t} else if (type.substr(0, 3) === \"fat\") {\n\t\t\tthis._createNewOscillator(\"fat\");\n\t\t\tthis._oscillator = this._oscillator as FatOscillator;\n\t\t\tthis._oscillator.type = type.substr(3) as ToneOscillatorType;\n\t\t} else if (type === \"pwm\") {\n\t\t\tthis._createNewOscillator(\"pwm\");\n\t\t\tthis._oscillator = this._oscillator as PWMOscillator;\n\t\t} else if (type === \"pulse\") {\n\t\t\tthis._createNewOscillator(\"pulse\");\n\t\t} else {\n\t\t\tthis._createNewOscillator(\"oscillator\");\n\t\t\tthis._oscillator = this._oscillator as Oscillator;\n\t\t\tthis._oscillator.type = type as ToneOscillatorType;\n\t\t}\n\t}\n\n\t/**\n\t * The value is an empty array when the type is not \"custom\".\n\t * This is not available on \"pwm\" and \"pulse\" oscillator types.\n\t * @see {@link Oscillator.partials}\n\t */\n\tget partials(): number[] {\n\t\treturn this._oscillator.partials;\n\t}\n\tset partials(partials) {\n\t\tif (\n\t\t\t!this._getOscType(this._oscillator, \"pulse\") &&\n\t\t\t!this._getOscType(this._oscillator, \"pwm\")\n\t\t) {\n\t\t\tthis._oscillator.partials = partials;\n\t\t}\n\t}\n\n\tget partialCount(): number {\n\t\treturn this._oscillator.partialCount;\n\t}\n\tset partialCount(partialCount) {\n\t\tif (\n\t\t\t!this._getOscType(this._oscillator, \"pulse\") &&\n\t\t\t!this._getOscType(this._oscillator, \"pwm\")\n\t\t) {\n\t\t\tthis._oscillator.partialCount = partialCount;\n\t\t}\n\t}\n\n\tset(props: Partial<OmniOscillatorOptions>): this {\n\t\t// make sure the type is set first\n\t\tif (Reflect.has(props, \"type\") && props.type) {\n\t\t\tthis.type = props.type;\n\t\t}\n\t\t// then set the rest\n\t\tsuper.set(props);\n\t\treturn this;\n\t}\n\n\t/**\n\t * connect the oscillator to the frequency and detune signals\n\t */\n\tprivate _createNewOscillator(oscType: OmniOscSourceType): void {\n\t\tif (oscType !== this._sourceType) {\n\t\t\tthis._sourceType = oscType;\n\t\t\tconst OscConstructor = OmniOscillatorSourceMap[oscType];\n\t\t\t// short delay to avoid clicks on the change\n\t\t\tconst now = this.now();\n\t\t\tif (this._oscillator) {\n\t\t\t\tconst oldOsc = this._oscillator;\n\t\t\t\toldOsc.stop(now);\n\t\t\t\t// dispose the old one\n\t\t\t\tthis.context.setTimeout(() => oldOsc.dispose(), this.blockTime);\n\t\t\t}\n\t\t\tthis._oscillator = new OscConstructor({\n\t\t\t\tcontext: this.context,\n\t\t\t});\n\t\t\tthis.frequency.connect(this._oscillator.frequency);\n\t\t\tthis.detune.connect(this._oscillator.detune);\n\t\t\tthis._oscillator.connect(this.output);\n\t\t\tthis._oscillator.onstop = () => this.onstop(this);\n\t\t\tif (this.state === \"started\") {\n\t\t\t\tthis._oscillator.start(now);\n\t\t\t}\n\t\t}\n\t}\n\n\tget phase(): Degrees {\n\t\treturn this._oscillator.phase;\n\t}\n\tset phase(phase) {\n\t\tthis._oscillator.phase = phase;\n\t}\n\n\t/**\n\t * The source type of the oscillator.\n\t * @example\n\t * const omniOsc = new Tone.OmniOscillator(440, \"fmsquare\");\n\t * console.log(omniOsc.sourceType); // 'fm'\n\t */\n\tget sourceType(): OmniOscSourceType {\n\t\treturn this._sourceType;\n\t}\n\tset sourceType(sType) {\n\t\t// the basetype defaults to sine\n\t\tlet baseType = \"sine\";\n\t\tif (\n\t\t\tthis._oscillator.type !== \"pwm\" &&\n\t\t\tthis._oscillator.type !== \"pulse\"\n\t\t) {\n\t\t\tbaseType = this._oscillator.type;\n\t\t}\n\n\t\t// set the type\n\t\tif (sType === \"fm\") {\n\t\t\tthis.type = (\"fm\" + baseType) as OmniOscillatorType;\n\t\t} else if (sType === \"am\") {\n\t\t\tthis.type = (\"am\" + baseType) as OmniOscillatorType;\n\t\t} else if (sType === \"fat\") {\n\t\t\tthis.type = (\"fat\" + baseType) as OmniOscillatorType;\n\t\t} else if (sType === \"oscillator\") {\n\t\t\tthis.type = baseType as OmniOscillatorType;\n\t\t} else if (sType === \"pulse\") {\n\t\t\tthis.type = \"pulse\";\n\t\t} else if (sType === \"pwm\") {\n\t\t\tthis.type = \"pwm\";\n\t\t}\n\t}\n\n\tprivate _getOscType<SourceType extends OmniOscSourceType>(\n\t\tosc: AnyOscillator,\n\t\tsourceType: SourceType\n\t): osc is OmniOscillatorSource[SourceType] {\n\t\treturn osc instanceof OmniOscillatorSourceMap[sourceType];\n\t}\n\n\t/**\n\t * The base type of the oscillator.\n\t * @see {@link Oscillator.baseType}\n\t * @example\n\t * const omniOsc = new Tone.OmniOscillator(440, \"fmsquare4\");\n\t * console.log(omniOsc.sourceType, omniOsc.baseType, omniOsc.partialCount);\n\t */\n\tget baseType(): OscillatorType | \"pwm\" | \"pulse\" {\n\t\treturn this._oscillator.baseType;\n\t}\n\tset baseType(baseType) {\n\t\tif (\n\t\t\t!this._getOscType(this._oscillator, \"pulse\") &&\n\t\t\t!this._getOscType(this._oscillator, \"pwm\") &&\n\t\t\tbaseType !== \"pulse\" &&\n\t\t\tbaseType !== \"pwm\"\n\t\t) {\n\t\t\tthis._oscillator.baseType = baseType;\n\t\t}\n\t}\n\n\t/**\n\t * The width of the oscillator when sourceType === \"pulse\".\n\t * @see {@link PWMOscillator}\n\t */\n\tget width(): IsPulseOscillator<OscType, Signal<\"audioRange\">> {\n\t\tif (this._getOscType(this._oscillator, \"pulse\")) {\n\t\t\treturn this._oscillator.width as IsPulseOscillator<\n\t\t\t\tOscType,\n\t\t\t\tSignal<\"audioRange\">\n\t\t\t>;\n\t\t} else {\n\t\t\treturn undefined as IsPulseOscillator<\n\t\t\t\tOscType,\n\t\t\t\tSignal<\"audioRange\">\n\t\t\t>;\n\t\t}\n\t}\n\n\t/**\n\t * The number of detuned oscillators when sourceType === \"fat\".\n\t * @see {@link FatOscillator.count}\n\t */\n\tget count(): IsFatOscillator<OscType, number> {\n\t\tif (this._getOscType(this._oscillator, \"fat\")) {\n\t\t\treturn this._oscillator.count as IsFatOscillator<OscType, number>;\n\t\t} else {\n\t\t\treturn undefined as IsFatOscillator<OscType, number>;\n\t\t}\n\t}\n\tset count(count) {\n\t\tif (this._getOscType(this._oscillator, \"fat\") && isNumber(count)) {\n\t\t\tthis._oscillator.count = count;\n\t\t}\n\t}\n\n\t/**\n\t * The detune spread between the oscillators when sourceType === \"fat\".\n\t * @see {@link FatOscillator.count}\n\t */\n\tget spread(): IsFatOscillator<OscType, Cents> {\n\t\tif (this._getOscType(this._oscillator, \"fat\")) {\n\t\t\treturn this._oscillator.spread as IsFatOscillator<OscType, Cents>;\n\t\t} else {\n\t\t\treturn undefined as IsFatOscillator<OscType, Cents>;\n\t\t}\n\t}\n\tset spread(spread) {\n\t\tif (this._getOscType(this._oscillator, \"fat\") && isNumber(spread)) {\n\t\t\tthis._oscillator.spread = spread;\n\t\t}\n\t}\n\n\t/**\n\t * The type of the modulator oscillator. Only if the oscillator is set to \"am\" or \"fm\" types.\n\t * @see {@link AMOscillator} or {@link FMOscillator}\n\t */\n\tget modulationType(): IsAmOrFmOscillator<OscType, ToneOscillatorType> {\n\t\tif (\n\t\t\tthis._getOscType(this._oscillator, \"fm\") ||\n\t\t\tthis._getOscType(this._oscillator, \"am\")\n\t\t) {\n\t\t\treturn this._oscillator.modulationType as IsAmOrFmOscillator<\n\t\t\t\tOscType,\n\t\t\t\tToneOscillatorType\n\t\t\t>;\n\t\t} else {\n\t\t\treturn undefined as IsAmOrFmOscillator<OscType, ToneOscillatorType>;\n\t\t}\n\t}\n\tset modulationType(mType) {\n\t\tif (\n\t\t\t(this._getOscType(this._oscillator, \"fm\") ||\n\t\t\t\tthis._getOscType(this._oscillator, \"am\")) &&\n\t\t\tisString(mType)\n\t\t) {\n\t\t\tthis._oscillator.modulationType = mType;\n\t\t}\n\t}\n\n\t/**\n\t * The modulation index when the sourceType === \"fm\"\n\t * @see {@link FMOscillator}.\n\t */\n\tget modulationIndex(): IsFMOscillator<OscType, Signal<\"positive\">> {\n\t\tif (this._getOscType(this._oscillator, \"fm\")) {\n\t\t\treturn this._oscillator.modulationIndex as IsFMOscillator<\n\t\t\t\tOscType,\n\t\t\t\tSignal<\"positive\">\n\t\t\t>;\n\t\t} else {\n\t\t\treturn undefined as IsFMOscillator<OscType, Signal<\"positive\">>;\n\t\t}\n\t}\n\n\t/**\n\t * Harmonicity is the frequency ratio between the carrier and the modulator oscillators.\n\t * @see {@link AMOscillator} or {@link FMOscillator}\n\t */\n\tget harmonicity(): IsAmOrFmOscillator<OscType, Signal<\"positive\">> {\n\t\tif (\n\t\t\tthis._getOscType(this._oscillator, \"fm\") ||\n\t\t\tthis._getOscType(this._oscillator, \"am\")\n\t\t) {\n\t\t\treturn this._oscillator.harmonicity as IsAmOrFmOscillator<\n\t\t\t\tOscType,\n\t\t\t\tSignal<\"positive\">\n\t\t\t>;\n\t\t} else {\n\t\t\treturn undefined as IsAmOrFmOscillator<OscType, Signal<\"positive\">>;\n\t\t}\n\t}\n\n\t/**\n\t * The modulationFrequency Signal of the oscillator when sourceType === \"pwm\"\n\t * see {@link PWMOscillator}\n\t * @min 0.1\n\t * @max 5\n\t */\n\tget modulationFrequency(): IsPWMOscillator<OscType, Signal<\"frequency\">> {\n\t\tif (this._getOscType(this._oscillator, \"pwm\")) {\n\t\t\treturn this._oscillator.modulationFrequency as IsPWMOscillator<\n\t\t\t\tOscType,\n\t\t\t\tSignal<\"frequency\">\n\t\t\t>;\n\t\t} else {\n\t\t\treturn undefined as IsPWMOscillator<OscType, Signal<\"frequency\">>;\n\t\t}\n\t}\n\n\tasync asArray(length = 1024): Promise<Float32Array> {\n\t\treturn generateWaveform(this, length);\n\t}\n\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis.detune.dispose();\n\t\tthis.frequency.dispose();\n\t\tthis._oscillator.dispose();\n\t\treturn this;\n\t}\n}\n","import { connectSeries } from \"../core/context/ToneAudioNode.js\";\nimport { Gain } from \"../core/context/Gain.js\";\nimport { Param } from \"../core/context/Param.js\";\nimport { optionsFromArguments } from \"../core/util/Defaults.js\";\nimport { Signal, SignalOptions } from \"./Signal.js\";\n\n/**\n * Add a signal and a number or two signals. When no value is\n * passed into the constructor, Tone.Add will sum input and `addend`\n * If a value is passed into the constructor, the it will be added to the input.\n *\n * @example\n * return Tone.Offline(() => {\n * \tconst add = new Tone.Add(2).toDestination();\n * \tadd.addend.setValueAtTime(1, 0.2);\n * \tconst signal = new Tone.Signal(2);\n * \t// add a signal and a scalar\n * \tsignal.connect(add);\n * \tsignal.setValueAtTime(1, 0.1);\n * }, 0.5, 1);\n * @category Signal\n */\nexport class Add extends Signal {\n\toverride = false;\n\n\treadonly name: string = \"Add\";\n\n\t/**\n\t * the summing node\n\t */\n\tprivate _sum: Gain = new Gain({ context: this.context });\n\treadonly input = this._sum;\n\treadonly output = this._sum;\n\n\t/**\n\t * The value which is added to the input signal\n\t */\n\treadonly addend: Param<\"number\"> = this._param;\n\n\t/**\n\t * @param value If no value is provided, will sum the input and {@link addend}.\n\t */\n\tconstructor(value?: number);\n\tconstructor(options?: Partial<SignalOptions<\"number\">>);\n\tconstructor() {\n\t\tsuper(optionsFromArguments(Add.getDefaults(), arguments, [\"value\"]));\n\n\t\tconnectSeries(this._constantSource, this._sum);\n\t}\n\n\tstatic getDefaults(): SignalOptions<\"number\"> {\n\t\treturn Object.assign(Signal.getDefaults(), {\n\t\t\tvalue: 0,\n\t\t});\n\t}\n\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis._sum.dispose();\n\t\treturn this;\n\t}\n}\n","import {\n\tInputNode,\n\tOutputNode,\n\tToneAudioNodeOptions,\n} from \"../core/context/ToneAudioNode.js\";\nimport { optionsFromArguments } from \"../core/util/Defaults.js\";\nimport { Add } from \"./Add.js\";\nimport { Multiply } from \"./Multiply.js\";\nimport { SignalOperator } from \"./SignalOperator.js\";\n\nexport interface ScaleOptions extends ToneAudioNodeOptions {\n\tmin: number;\n\tmax: number;\n}\n\n/**\n * Performs a linear scaling on an input signal.\n * Scales a NormalRange input to between\n * outputMin and outputMax.\n *\n * @example\n * const scale = new Tone.Scale(50, 100);\n * const signal = new Tone.Signal(0.5).connect(scale);\n * // the output of scale equals 75\n * @category Signal\n */\nexport class Scale<\n\tOptions extends ScaleOptions = ScaleOptions,\n> extends SignalOperator<Options> {\n\treadonly name: string = \"Scale\";\n\n\tinput: InputNode;\n\toutput: OutputNode;\n\n\t/**\n\t * Hold the multiple\n\t */\n\tprotected _mult: Multiply;\n\n\t/**\n\t * Hold the adder\n\t */\n\tprotected _add: Add;\n\n\t/**\n\t * Private reference to the min value\n\t */\n\tprivate _min: number;\n\n\t/**\n\t * Private reference to the max value\n\t */\n\tprivate _max: number;\n\n\t/**\n\t * @param min The output value when the input is 0.\n\t * @param max The output value when the input is 1.\n\t */\n\tconstructor(min?: number, max?: number);\n\tconstructor(options?: Partial<ScaleOptions>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(Scale.getDefaults(), arguments, [\n\t\t\t\"min\",\n\t\t\t\"max\",\n\t\t]);\n\t\tsuper(options as Options);\n\n\t\tthis._mult = this.input = new Multiply({\n\t\t\tcontext: this.context,\n\t\t\tvalue: options.max - options.min,\n\t\t});\n\n\t\tthis._add = this.output = new Add({\n\t\t\tcontext: this.context,\n\t\t\tvalue: options.min,\n\t\t});\n\n\t\tthis._min = options.min;\n\t\tthis._max = options.max;\n\n\t\tthis.input.connect(this.output);\n\t}\n\n\tstatic getDefaults(): ScaleOptions {\n\t\treturn Object.assign(SignalOperator.getDefaults(), {\n\t\t\tmax: 1,\n\t\t\tmin: 0,\n\t\t});\n\t}\n\n\t/**\n\t * The minimum output value. This number is output when the value input value is 0.\n\t */\n\tget min(): number {\n\t\treturn this._min;\n\t}\n\tset min(min) {\n\t\tthis._min = min;\n\t\tthis._setRange();\n\t}\n\n\t/**\n\t * The maximum output value. This number is output when the value input value is 1.\n\t */\n\tget max(): number {\n\t\treturn this._max;\n\t}\n\tset max(max) {\n\t\tthis._max = max;\n\t\tthis._setRange();\n\t}\n\n\t/**\n\t * set the values\n\t */\n\tprivate _setRange(): void {\n\t\tthis._add.value = this._min;\n\t\tthis._mult.value = this._max - this._min;\n\t}\n\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis._add.dispose();\n\t\tthis._mult.dispose();\n\t\treturn this;\n\t}\n}\n","import { Gain } from \"../core/context/Gain.js\";\nimport {\n\tconnect,\n\tdisconnect,\n\tToneAudioNodeOptions,\n} from \"../core/context/ToneAudioNode.js\";\nimport { optionsFromArguments } from \"../core/util/Defaults.js\";\nimport { SignalOperator } from \"./SignalOperator.js\";\n\n/**\n * Tone.Zero outputs 0's at audio-rate. The reason this has to be\n * it's own class is that many browsers optimize out Tone.Signal\n * with a value of 0 and will not process nodes further down the graph.\n * @category Signal\n */\nexport class Zero extends SignalOperator<ToneAudioNodeOptions> {\n\treadonly name: string = \"Zero\";\n\n\t/**\n\t * The gain node which connects the constant source to the output\n\t */\n\tprivate _gain = new Gain({ context: this.context });\n\n\t/**\n\t * Only outputs 0\n\t */\n\toutput = this._gain;\n\n\t/**\n\t * no input node\n\t */\n\tinput = undefined;\n\n\tconstructor(options?: Partial<ToneAudioNodeOptions>);\n\tconstructor() {\n\t\tsuper(optionsFromArguments(Zero.getDefaults(), arguments));\n\t\tconnect(this.context.getConstant(0), this._gain);\n\t}\n\n\t/**\n\t * clean up\n\t */\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tdisconnect(this.context.getConstant(0), this._gain);\n\t\treturn this;\n\t}\n}\n","import { Gain } from \"../../core/context/Gain.js\";\nimport { Param } from \"../../core/context/Param.js\";\nimport {\n\tInputNode,\n\tOutputNode,\n\tToneAudioNode,\n} from \"../../core/context/ToneAudioNode.js\";\nimport {\n\tDegrees,\n\tFrequency,\n\tNormalRange,\n\tTime,\n\tUnitName,\n} from \"../../core/type/Units.js\";\nimport { optionsFromArguments } from \"../../core/util/Defaults.js\";\nimport { readOnly } from \"../../core/util/Interface.js\";\nimport { BasicPlaybackState } from \"../../core/util/StateTimeline.js\";\nimport { AudioToGain } from \"../../signal/AudioToGain.js\";\nimport { Scale } from \"../../signal/Scale.js\";\nimport { connectSignal, Signal } from \"../../signal/Signal.js\";\nimport { Zero } from \"../../signal/Zero.js\";\nimport { Oscillator, ToneOscillatorType } from \"./Oscillator.js\";\nimport {\n\tToneOscillatorConstructorOptions,\n\tToneOscillatorOptions,\n} from \"./OscillatorInterface.js\";\n\nexport type LFOOptions = {\n\tmin: number;\n\tmax: number;\n\tamplitude: NormalRange;\n\tunits: UnitName;\n} & ToneOscillatorOptions;\n\n/**\n * LFO stands for low frequency oscillator. LFO produces an output signal\n * which can be attached to an AudioParam or Tone.Signal\n * in order to modulate that parameter with an oscillator. The LFO can\n * also be synced to the transport to start/stop and change when the tempo changes.\n * @example\n * return Tone.Offline(() => {\n * \tconst lfo = new Tone.LFO(\"4n\", 400, 4000).start().toDestination();\n * }, 0.5, 1);\n * @category Source\n */\nexport class LFO extends ToneAudioNode<LFOOptions> {\n\treadonly name: string = \"LFO\";\n\n\t/**\n\t * The oscillator.\n\t */\n\tprivate _oscillator: Oscillator;\n\n\t/**\n\t * The gain of the output\n\t */\n\tprivate _amplitudeGain: Gain<\"normalRange\">;\n\n\t/**\n\t * The amplitude of the LFO, which controls the output range between\n\t * the min and max output. For example if the min is -10 and the max\n\t * is 10, setting the amplitude to 0.5 would make the LFO modulate\n\t * between -5 and 5.\n\t */\n\treadonly amplitude: Param<\"normalRange\">;\n\n\t/**\n\t * The signal which is output when the LFO is stopped\n\t */\n\tprivate _stoppedSignal: Signal<\"audioRange\">;\n\n\t/**\n\t * Just outputs zeros. This is used so that scaled signal is not\n\t * optimized to silence.\n\t */\n\tprivate _zeros: Zero;\n\n\t/**\n\t * The value that the LFO outputs when it's stopped\n\t */\n\tprivate _stoppedValue = 0;\n\n\t/**\n\t * Convert the oscillators audio range to an output between 0-1 so it can be scaled\n\t */\n\tprivate _a2g: AudioToGain;\n\n\t/**\n\t * Scales the final output to the min and max value\n\t */\n\tprivate _scaler: Scale;\n\n\t/**\n\t * The output of the LFO\n\t */\n\treadonly output: OutputNode;\n\n\t/**\n\t * There is no input node\n\t */\n\treadonly input: undefined;\n\n\t/**\n\t * A private placeholder for the units\n\t */\n\tprivate _units: UnitName = \"number\";\n\n\t/**\n\t * If the input value is converted using the {@link units}\n\t */\n\tconvert = true;\n\n\t/**\n\t * The frequency value of the LFO\n\t */\n\treadonly frequency: Signal<\"frequency\">;\n\n\t/**\n\t * @param frequency The frequency of the oscillation.\n\t * Typically, LFOs will be in the frequency range of 0.1 to 10 hertz.\n\t * @param min The minimum output value of the LFO.\n\t * @param max The maximum value of the LFO.\n\t */\n\tconstructor(frequency?: Frequency, min?: number, max?: number);\n\tconstructor(options?: Partial<LFOOptions>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(LFO.getDefaults(), arguments, [\n\t\t\t\"frequency\",\n\t\t\t\"min\",\n\t\t\t\"max\",\n\t\t]);\n\t\tsuper(options);\n\n\t\tthis._oscillator = new Oscillator(\n\t\t\toptions as ToneOscillatorConstructorOptions\n\t\t);\n\n\t\tthis.frequency = this._oscillator.frequency;\n\n\t\tthis._amplitudeGain = new Gain({\n\t\t\tcontext: this.context,\n\t\t\tgain: options.amplitude,\n\t\t\tunits: \"normalRange\",\n\t\t});\n\t\tthis.amplitude = this._amplitudeGain.gain;\n\t\tthis._stoppedSignal = new Signal({\n\t\t\tcontext: this.context,\n\t\t\tunits: \"audioRange\",\n\t\t\tvalue: 0,\n\t\t});\n\t\tthis._zeros = new Zero({ context: this.context });\n\t\tthis._a2g = new AudioToGain({ context: this.context });\n\t\tthis._scaler = this.output = new Scale({\n\t\t\tcontext: this.context,\n\t\t\tmax: options.max,\n\t\t\tmin: options.min,\n\t\t});\n\n\t\tthis.units = options.units;\n\t\tthis.min = options.min;\n\t\tthis.max = options.max;\n\n\t\t// connect it up\n\t\tthis._oscillator.chain(this._amplitudeGain, this._a2g, this._scaler);\n\t\tthis._zeros.connect(this._a2g);\n\t\tthis._stoppedSignal.connect(this._a2g);\n\t\treadOnly(this, [\"amplitude\", \"frequency\"]);\n\t\tthis.phase = options.phase;\n\t}\n\n\tstatic getDefaults(): LFOOptions {\n\t\treturn Object.assign(Oscillator.getDefaults(), {\n\t\t\tamplitude: 1,\n\t\t\tfrequency: \"4n\",\n\t\t\tmax: 1,\n\t\t\tmin: 0,\n\t\t\ttype: \"sine\",\n\t\t\tunits: \"number\" as UnitName,\n\t\t});\n\t}\n\n\t/**\n\t * Start the LFO.\n\t * @param time The time the LFO will start\n\t */\n\tstart(time?: Time): this {\n\t\ttime = this.toSeconds(time);\n\t\tthis._stoppedSignal.setValueAtTime(0, time);\n\t\tthis._oscillator.start(time);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Stop the LFO.\n\t * @param time The time the LFO will stop\n\t */\n\tstop(time?: Time): this {\n\t\ttime = this.toSeconds(time);\n\t\tthis._stoppedSignal.setValueAtTime(this._stoppedValue, time);\n\t\tthis._oscillator.stop(time);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sync the start/stop/pause to the transport\n\t * and the frequency to the bpm of the transport\n\t * @example\n\t * const lfo = new Tone.LFO(\"8n\");\n\t * lfo.sync().start(0);\n\t * // the rate of the LFO will always be an eighth note, even as the tempo changes\n\t */\n\tsync(): this {\n\t\tthis._oscillator.sync();\n\t\tthis._oscillator.syncFrequency();\n\t\treturn this;\n\t}\n\n\t/**\n\t * unsync the LFO from transport control\n\t */\n\tunsync(): this {\n\t\tthis._oscillator.unsync();\n\t\tthis._oscillator.unsyncFrequency();\n\t\treturn this;\n\t}\n\n\t/**\n\t * After the oscillator waveform is updated, reset the `_stoppedSignal` value to match the updated waveform\n\t */\n\tprivate _setStoppedValue() {\n\t\tthis._stoppedValue = this._oscillator.getInitialValue();\n\t\tthis._stoppedSignal.value = this._stoppedValue;\n\t}\n\n\t/**\n\t * The minimum output of the LFO.\n\t */\n\tget min(): number {\n\t\treturn this._toType(this._scaler.min);\n\t}\n\tset min(min) {\n\t\tmin = this._fromType(min);\n\t\tthis._scaler.min = min;\n\t}\n\n\t/**\n\t * The maximum output of the LFO.\n\t */\n\tget max(): number {\n\t\treturn this._toType(this._scaler.max);\n\t}\n\tset max(max) {\n\t\tmax = this._fromType(max);\n\t\tthis._scaler.max = max;\n\t}\n\n\t/**\n\t * The type of the oscillator.\n\t * @see {@link Oscillator.type}\n\t */\n\tget type(): ToneOscillatorType {\n\t\treturn this._oscillator.type;\n\t}\n\tset type(type) {\n\t\tthis._oscillator.type = type;\n\t\tthis._setStoppedValue();\n\t}\n\n\t/**\n\t * The oscillator's partials array.\n\t * @see {@link Oscillator.partials}\n\t */\n\tget partials(): number[] {\n\t\treturn this._oscillator.partials;\n\t}\n\tset partials(partials) {\n\t\tthis._oscillator.partials = partials;\n\t\tthis._setStoppedValue();\n\t}\n\n\t/**\n\t * The phase of the LFO.\n\t */\n\tget phase(): Degrees {\n\t\treturn this._oscillator.phase;\n\t}\n\tset phase(phase) {\n\t\tthis._oscillator.phase = phase;\n\t\tthis._setStoppedValue();\n\t}\n\n\t/**\n\t * The output units of the LFO.\n\t */\n\tget units(): UnitName {\n\t\treturn this._units;\n\t}\n\tset units(val) {\n\t\tconst currentMin = this.min;\n\t\tconst currentMax = this.max;\n\t\t// convert the min and the max\n\t\tthis._units = val;\n\t\tthis.min = currentMin;\n\t\tthis.max = currentMax;\n\t}\n\n\t/**\n\t * Returns the playback state of the source, either \"started\" or \"stopped\".\n\t */\n\tget state(): BasicPlaybackState {\n\t\treturn this._oscillator.state;\n\t}\n\n\t/**\n\t * @param node the destination to connect to\n\t * @param outputNum the optional output number\n\t * @param inputNum the input number\n\t */\n\tconnect(node: InputNode, outputNum?: number, inputNum?: number): this {\n\t\tif (node instanceof Param || node instanceof Signal) {\n\t\t\tthis.convert = node.convert;\n\t\t\tthis.units = node.units;\n\t\t}\n\t\tconnectSignal(this, node, outputNum, inputNum);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Private methods borrowed from Param\n\t */\n\t// @ts-ignore\n\tprivate _fromType = Param.prototype._fromType;\n\t// @ts-ignore\n\tprivate _toType = Param.prototype._toType;\n\t// @ts-ignore\n\tprivate _is = Param.prototype._is;\n\t// @ts-ignore\n\tprivate _clampValue = Param.prototype._clampValue;\n\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis._oscillator.dispose();\n\t\tthis._stoppedSignal.dispose();\n\t\tthis._zeros.dispose();\n\t\tthis._scaler.dispose();\n\t\tthis._a2g.dispose();\n\t\tthis._amplitudeGain.dispose();\n\t\tthis.amplitude.dispose();\n\t\treturn this;\n\t}\n}\n","import { assertRange } from \"./Debug.js\";\nimport { Time } from \"../type/Units.js\";\n\n/**\n * Assert that the number is in the given range.\n */\nexport function range(min: number, max = Infinity) {\n\tconst valueMap: WeakMap<any, number> = new WeakMap();\n\treturn function (target: any, propertyKey: string | symbol) {\n\t\tReflect.defineProperty(target, propertyKey, {\n\t\t\tconfigurable: true,\n\t\t\tenumerable: true,\n\t\t\tget: function () {\n\t\t\t\treturn valueMap.get(this);\n\t\t\t},\n\t\t\tset: function (newValue: number) {\n\t\t\t\tassertRange(newValue, min, max);\n\t\t\t\tvalueMap.set(this, newValue);\n\t\t\t},\n\t\t});\n\t};\n}\n\n/**\n * Convert the time to seconds and assert that the time is in between the two\n * values when being set.\n */\nexport function timeRange(min: number, max = Infinity) {\n\tconst valueMap: WeakMap<any, Time> = new WeakMap();\n\treturn function (target: any, propertyKey: string) {\n\t\tReflect.defineProperty(target, propertyKey, {\n\t\t\tconfigurable: true,\n\t\t\tenumerable: true,\n\t\t\tget: function () {\n\t\t\t\treturn valueMap.get(this);\n\t\t\t},\n\t\t\tset: function (newValue: Time) {\n\t\t\t\tassertRange(this.toSeconds(newValue), min, max);\n\t\t\t\tvalueMap.set(this, newValue);\n\t\t\t},\n\t\t});\n\t};\n}\n","import { ToneAudioBuffer } from \"../../core/context/ToneAudioBuffer.js\";\nimport { Positive, Seconds, Time } from \"../../core/type/Units.js\";\nimport { defaultArg, optionsFromArguments } from \"../../core/util/Defaults.js\";\nimport { noOp } from \"../../core/util/Interface.js\";\nimport { isUndef } from \"../../core/util/TypeCheck.js\";\nimport { Source, SourceOptions } from \"../Source.js\";\nimport { ToneBufferSource } from \"./ToneBufferSource.js\";\nimport { assertRange } from \"../../core/util/Debug.js\";\nimport { timeRange } from \"../../core/util/Decorator.js\";\n\nexport interface PlayerOptions extends SourceOptions {\n\tonload: () => void;\n\tonerror: (error: Error) => void;\n\tplaybackRate: Positive;\n\tloop: boolean;\n\tautostart: boolean;\n\tloopStart: Time;\n\tloopEnd: Time;\n\treverse: boolean;\n\tfadeIn: Time;\n\tfadeOut: Time;\n\turl?: ToneAudioBuffer | string | AudioBuffer;\n}\n\n/**\n * Player is an audio file player with start, loop, and stop functions.\n * @example\n * const player = new Tone.Player(\"https://tonejs.github.io/audio/berklee/gong_1.mp3\").toDestination();\n * // play as soon as the buffer is loaded\n * player.autostart = true;\n * @category Source\n */\nexport class Player extends Source<PlayerOptions> {\n\treadonly name: string = \"Player\";\n\n\t/**\n\t * If the file should play as soon\n\t * as the buffer is loaded.\n\t */\n\tautostart: boolean;\n\n\t/**\n\t * The buffer\n\t */\n\tprivate _buffer: ToneAudioBuffer;\n\n\t/**\n\t * if the buffer should loop once it's over\n\t */\n\tprivate _loop: boolean;\n\n\t/**\n\t * if 'loop' is true, the loop will start at this position\n\t */\n\tprivate _loopStart: Time;\n\n\t/**\n\t * if 'loop' is true, the loop will end at this position\n\t */\n\tprivate _loopEnd: Time;\n\n\t/**\n\t * the playback rate\n\t */\n\tprivate _playbackRate: Positive;\n\n\t/**\n\t * All of the active buffer source nodes\n\t */\n\tprivate _activeSources: Set<ToneBufferSource> = new Set();\n\n\t/**\n\t * The fadeIn time of the amplitude envelope.\n\t */\n\t@timeRange(0)\n\tfadeIn: Time;\n\n\t/**\n\t * The fadeOut time of the amplitude envelope.\n\t */\n\t@timeRange(0)\n\tfadeOut: Time;\n\n\t/**\n\t * @param url Either the AudioBuffer or the url from which to load the AudioBuffer\n\t * @param onload The function to invoke when the buffer is loaded.\n\t */\n\tconstructor(\n\t\turl?: string | AudioBuffer | ToneAudioBuffer,\n\t\tonload?: () => void\n\t);\n\tconstructor(options?: Partial<PlayerOptions>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(Player.getDefaults(), arguments, [\n\t\t\t\"url\",\n\t\t\t\"onload\",\n\t\t]);\n\t\tsuper(options);\n\n\t\tthis._buffer = new ToneAudioBuffer({\n\t\t\tonload: this._onload.bind(this, options.onload),\n\t\t\tonerror: options.onerror,\n\t\t\treverse: options.reverse,\n\t\t\turl: options.url,\n\t\t});\n\t\tthis.autostart = options.autostart;\n\t\tthis._loop = options.loop;\n\t\tthis._loopStart = options.loopStart;\n\t\tthis._loopEnd = options.loopEnd;\n\t\tthis._playbackRate = options.playbackRate;\n\t\tthis.fadeIn = options.fadeIn;\n\t\tthis.fadeOut = options.fadeOut;\n\t}\n\n\tstatic getDefaults(): PlayerOptions {\n\t\treturn Object.assign(Source.getDefaults(), {\n\t\t\tautostart: false,\n\t\t\tfadeIn: 0,\n\t\t\tfadeOut: 0,\n\t\t\tloop: false,\n\t\t\tloopEnd: 0,\n\t\t\tloopStart: 0,\n\t\t\tonload: noOp,\n\t\t\tonerror: noOp,\n\t\t\tplaybackRate: 1,\n\t\t\treverse: false,\n\t\t});\n\t}\n\n\t/**\n\t * Load the audio file as an audio buffer.\n\t * Decodes the audio asynchronously and invokes\n\t * the callback once the audio buffer loads.\n\t * Note: this does not need to be called if a url\n\t * was passed in to the constructor. Only use this\n\t * if you want to manually load a new url.\n\t * @param url The url of the buffer to load. Filetype support depends on the browser.\n\t */\n\tasync load(url: string): Promise<this> {\n\t\tawait this._buffer.load(url);\n\t\tthis._onload();\n\t\treturn this;\n\t}\n\n\t/**\n\t * Internal callback when the buffer is loaded.\n\t */\n\tprivate _onload(callback: () => void = noOp): void {\n\t\tcallback();\n\t\tif (this.autostart) {\n\t\t\tthis.start();\n\t\t}\n\t}\n\n\t/**\n\t * Internal callback when the buffer is done playing.\n\t */\n\tprivate _onSourceEnd(source: ToneBufferSource): void {\n\t\t// invoke the onstop function\n\t\tthis.onstop(this);\n\n\t\t// delete the source from the active sources\n\t\tthis._activeSources.delete(source);\n\t\tif (\n\t\t\tthis._activeSources.size === 0 &&\n\t\t\t!this._synced &&\n\t\t\tthis._state.getValueAtTime(this.now()) === \"started\"\n\t\t) {\n\t\t\t// remove the 'implicitEnd' event and replace with an explicit end\n\t\t\tthis._state.cancel(this.now());\n\t\t\tthis._state.setStateAtTime(\"stopped\", this.now());\n\t\t}\n\t}\n\n\t/**\n\t * Play the buffer at the given startTime. Optionally add an offset\n\t * and/or duration which will play the buffer from a position\n\t * within the buffer for the given duration.\n\t *\n\t * @param time When the player should start.\n\t * @param offset The offset from the beginning of the sample to start at.\n\t * @param duration How long the sample should play. If no duration is given, it will default to the full length of the sample (minus any offset)\n\t */\n\tstart(time?: Time, offset?: Time, duration?: Time): this {\n\t\tsuper.start(time, offset, duration);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Internal start method\n\t */\n\tprotected _start(startTime?: Time, offset?: Time, duration?: Time): void {\n\t\t// if it's a loop the default offset is the loopStart point\n\t\tif (this._loop) {\n\t\t\toffset = defaultArg(offset, this._loopStart);\n\t\t} else {\n\t\t\t// otherwise the default offset is 0\n\t\t\toffset = defaultArg(offset, 0);\n\t\t}\n\n\t\t// compute the values in seconds\n\t\tconst computedOffset = this.toSeconds(offset);\n\n\t\t// compute the duration which is either the passed in duration of the buffer.duration - offset\n\t\tconst origDuration = duration;\n\t\tduration = defaultArg(\n\t\t\tduration,\n\t\t\tMath.max(this._buffer.duration - computedOffset, 0)\n\t\t);\n\t\tlet computedDuration = this.toSeconds(duration);\n\n\t\t// scale it by the playback rate\n\t\tcomputedDuration = computedDuration / this._playbackRate;\n\n\t\t// get the start time\n\t\tstartTime = this.toSeconds(startTime);\n\n\t\t// make the source\n\t\tconst source = new ToneBufferSource({\n\t\t\turl: this._buffer,\n\t\t\tcontext: this.context,\n\t\t\tfadeIn: this.fadeIn,\n\t\t\tfadeOut: this.fadeOut,\n\t\t\tloop: this._loop,\n\t\t\tloopEnd: this._loopEnd,\n\t\t\tloopStart: this._loopStart,\n\t\t\tonended: this._onSourceEnd.bind(this),\n\t\t\tplaybackRate: this._playbackRate,\n\t\t}).connect(this.output);\n\n\t\t// set the looping properties\n\t\tif (!this._loop && !this._synced) {\n\t\t\t// cancel the previous stop\n\t\t\tthis._state.cancel(startTime + computedDuration);\n\t\t\t// if it's not looping, set the state change at the end of the sample\n\t\t\tthis._state.setStateAtTime(\n\t\t\t\t\"stopped\",\n\t\t\t\tstartTime + computedDuration,\n\t\t\t\t{\n\t\t\t\t\timplicitEnd: true,\n\t\t\t\t}\n\t\t\t);\n\t\t}\n\n\t\t// add it to the array of active sources\n\t\tthis._activeSources.add(source);\n\n\t\t// start it\n\t\tif (this._loop && isUndef(origDuration)) {\n\t\t\tsource.start(startTime, computedOffset);\n\t\t} else {\n\t\t\t// subtract the fade out time\n\t\t\tsource.start(\n\t\t\t\tstartTime,\n\t\t\t\tcomputedOffset,\n\t\t\t\tcomputedDuration - this.toSeconds(this.fadeOut)\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Stop playback.\n\t */\n\tprotected _stop(time?: Time): void {\n\t\tconst computedTime = this.toSeconds(time);\n\t\tthis._activeSources.forEach((source) => source.stop(computedTime));\n\t}\n\n\t/**\n\t * Stop and then restart the player from the beginning (or offset)\n\t * @param time When the player should start.\n\t * @param offset The offset from the beginning of the sample to start at.\n\t * @param duration How long the sample should play. If no duration is given,\n\t * \t\t\t\t\tit will default to the full length of the sample (minus any offset)\n\t */\n\trestart(time?: Seconds, offset?: Time, duration?: Time): this {\n\t\tsuper.restart(time, offset, duration);\n\t\treturn this;\n\t}\n\n\tprotected _restart(time?: Seconds, offset?: Time, duration?: Time): void {\n\t\t[...this._activeSources].pop()?.stop(time); // explicitly stop only the most recently created source, to avoid edge case when > 1 source exists and _stop() erroneously sets all stop times past original end offset\n\t\tthis._start(time, offset, duration);\n\t}\n\n\t/**\n\t * Seek to a specific time in the player's buffer. If the\n\t * source is no longer playing at that time, it will stop.\n\t * @param offset The time to seek to.\n\t * @param when The time for the seek event to occur.\n\t * @example\n\t * const player = new Tone.Player(\"https://tonejs.github.io/audio/berklee/gurgling_theremin_1.mp3\", () => {\n\t * \tplayer.start();\n\t * \t// seek to the offset in 1 second from now\n\t * \tplayer.seek(0.4, \"+1\");\n\t * }).toDestination();\n\t */\n\tseek(offset: Time, when?: Time): this {\n\t\tconst computedTime = this.toSeconds(when);\n\t\tif (this._state.getValueAtTime(computedTime) === \"started\") {\n\t\t\tconst computedOffset = this.toSeconds(offset);\n\t\t\t// if it's currently playing, stop it\n\t\t\tthis._stop(computedTime);\n\t\t\t// restart it at the given time\n\t\t\tthis._start(computedTime, computedOffset);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Set the loop start and end. Will only loop if loop is set to true.\n\t * @param loopStart The loop start time\n\t * @param loopEnd The loop end time\n\t * @example\n\t * const player = new Tone.Player(\"https://tonejs.github.io/audio/berklee/malevoices_aa2_F3.mp3\").toDestination();\n\t * // loop between the given points\n\t * player.setLoopPoints(0.2, 0.3);\n\t * player.loop = true;\n\t * player.autostart = true;\n\t */\n\tsetLoopPoints(loopStart: Time, loopEnd: Time): this {\n\t\tthis.loopStart = loopStart;\n\t\tthis.loopEnd = loopEnd;\n\t\treturn this;\n\t}\n\n\t/**\n\t * If loop is true, the loop will start at this position.\n\t */\n\tget loopStart(): Time {\n\t\treturn this._loopStart;\n\t}\n\tset loopStart(loopStart) {\n\t\tthis._loopStart = loopStart;\n\t\tif (this.buffer.loaded) {\n\t\t\tassertRange(this.toSeconds(loopStart), 0, this.buffer.duration);\n\t\t}\n\t\t// get the current source\n\t\tthis._activeSources.forEach((source) => {\n\t\t\tsource.loopStart = loopStart;\n\t\t});\n\t}\n\n\t/**\n\t * If loop is true, the loop will end at this position.\n\t */\n\tget loopEnd(): Time {\n\t\treturn this._loopEnd;\n\t}\n\tset loopEnd(loopEnd) {\n\t\tthis._loopEnd = loopEnd;\n\t\tif (this.buffer.loaded) {\n\t\t\tassertRange(this.toSeconds(loopEnd), 0, this.buffer.duration);\n\t\t}\n\t\t// get the current source\n\t\tthis._activeSources.forEach((source) => {\n\t\t\tsource.loopEnd = loopEnd;\n\t\t});\n\t}\n\n\t/**\n\t * The audio buffer belonging to the player.\n\t */\n\tget buffer(): ToneAudioBuffer {\n\t\treturn this._buffer;\n\t}\n\tset buffer(buffer) {\n\t\tthis._buffer.set(buffer);\n\t}\n\n\t/**\n\t * If the buffer should loop once it's over.\n\t * @example\n\t * const player = new Tone.Player(\"https://tonejs.github.io/audio/drum-samples/breakbeat.mp3\").toDestination();\n\t * player.loop = true;\n\t * player.autostart = true;\n\t */\n\tget loop(): boolean {\n\t\treturn this._loop;\n\t}\n\tset loop(loop) {\n\t\t// if no change, do nothing\n\t\tif (this._loop === loop) {\n\t\t\treturn;\n\t\t}\n\t\tthis._loop = loop;\n\t\t// set the loop of all of the sources\n\t\tthis._activeSources.forEach((source) => {\n\t\t\tsource.loop = loop;\n\t\t});\n\t\tif (loop) {\n\t\t\t// remove the next stopEvent\n\t\t\tconst stopEvent = this._state.getNextState(\"stopped\", this.now());\n\t\t\tif (stopEvent) {\n\t\t\t\tthis._state.cancel(stopEvent.time);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Normal speed is 1. The pitch will change with the playback rate.\n\t * @example\n\t * const player = new Tone.Player(\"https://tonejs.github.io/audio/berklee/femalevoices_aa2_A5.mp3\").toDestination();\n\t * // play at 1/4 speed\n\t * player.playbackRate = 0.25;\n\t * // play as soon as the buffer is loaded\n\t * player.autostart = true;\n\t */\n\tget playbackRate(): Positive {\n\t\treturn this._playbackRate;\n\t}\n\tset playbackRate(rate) {\n\t\tthis._playbackRate = rate;\n\t\tconst now = this.now();\n\n\t\t// cancel the stop event since it's at a different time now\n\t\tconst stopEvent = this._state.getNextState(\"stopped\", now);\n\t\tif (stopEvent && stopEvent.implicitEnd) {\n\t\t\tthis._state.cancel(stopEvent.time);\n\t\t\tthis._activeSources.forEach((source) => source.cancelStop());\n\t\t}\n\n\t\t// set all the sources\n\t\tthis._activeSources.forEach((source) => {\n\t\t\tsource.playbackRate.setValueAtTime(rate, now);\n\t\t});\n\t}\n\n\t/**\n\t * If the buffer should be reversed. Note that this sets the underlying {@link ToneAudioBuffer.reverse}, so\n\t * if multiple players are pointing at the same ToneAudioBuffer, they will all be reversed.\n\t * @example\n\t * const player = new Tone.Player(\"https://tonejs.github.io/audio/berklee/chime_1.mp3\").toDestination();\n\t * player.autostart = true;\n\t * player.reverse = true;\n\t */\n\tget reverse(): boolean {\n\t\treturn this._buffer.reverse;\n\t}\n\tset reverse(rev) {\n\t\tthis._buffer.reverse = rev;\n\t}\n\n\t/**\n\t * If the buffer is loaded\n\t */\n\tget loaded(): boolean {\n\t\treturn this._buffer.loaded;\n\t}\n\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\t// disconnect all of the players\n\t\tthis._activeSources.forEach((source) => source.dispose());\n\t\tthis._activeSources.clear();\n\t\tthis._buffer.dispose();\n\t\treturn this;\n\t}\n}\n","import { ToneAudioNodeOptions } from \"../core/context/ToneAudioNode.js\";\nimport { SignalOperator } from \"./SignalOperator.js\";\nimport { WaveShaper } from \"./WaveShaper.js\";\n\n/**\n * GainToAudio converts an input in NormalRange [0,1] to AudioRange [-1,1].\n * @see {@link AudioToGain}.\n * @category Signal\n */\nexport class GainToAudio extends SignalOperator<ToneAudioNodeOptions> {\n\treadonly name: string = \"GainToAudio\";\n\n\t/**\n\t * The node which converts the audio ranges\n\t */\n\tprivate _norm = new WaveShaper({\n\t\tcontext: this.context,\n\t\tmapping: (x) => Math.abs(x) * 2 - 1,\n\t});\n\n\t/**\n\t * The NormalRange input [0, 1]\n\t */\n\tinput = this._norm;\n\n\t/**\n\t * The AudioRange output [-1, 1]\n\t */\n\toutput = this._norm;\n\n\t/**\n\t * clean up\n\t */\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis._norm.dispose();\n\t\treturn this;\n\t}\n}\n","import { InputNode, OutputNode } from \"../../core/context/ToneAudioNode.js\";\nimport {\n\tToneAudioNode,\n\tToneAudioNodeOptions,\n} from \"../../core/context/ToneAudioNode.js\";\nimport { NormalRange, Time } from \"../../core/type/Units.js\";\nimport { optionsFromArguments } from \"../../core/util/Defaults.js\";\nimport { isArray, isObject, isString } from \"../../core/util/TypeCheck.js\";\nimport { connectSignal, Signal } from \"../../signal/Signal.js\";\nimport { OfflineContext } from \"../../core/context/OfflineContext.js\";\nimport { assert } from \"../../core/util/Debug.js\";\nimport { range, timeRange } from \"../../core/util/Decorator.js\";\n\ntype BasicEnvelopeCurve = \"linear\" | \"exponential\";\ntype InternalEnvelopeCurve = BasicEnvelopeCurve | number[];\nexport type EnvelopeCurve = EnvelopeCurveName | number[];\n\nexport interface EnvelopeOptions extends ToneAudioNodeOptions {\n\tattack: Time;\n\tdecay: Time;\n\tsustain: NormalRange;\n\trelease: Time;\n\tattackCurve: EnvelopeCurve;\n\treleaseCurve: EnvelopeCurve;\n\tdecayCurve: BasicEnvelopeCurve;\n}\n\n/**\n * Envelope is an [ADSR](https://en.wikipedia.org/wiki/Synthesizer#ADSR_envelope)\n * envelope generator. Envelope outputs a signal which\n * can be connected to an AudioParam or Tone.Signal.\n * ```\n * /\\\n * / \\\n * / \\\n * / \\\n * / \\___________\n * / \\\n * / \\\n * / \\\n * / \\\n * ```\n * @example\n * return Tone.Offline(() => {\n * \tconst env = new Tone.Envelope({\n * \t\tattack: 0.1,\n * \t\tdecay: 0.2,\n * \t\tsustain: 0.5,\n * \t\trelease: 0.8,\n * \t}).toDestination();\n * \tenv.triggerAttackRelease(0.5);\n * }, 1.5, 1);\n * @category Component\n */\nexport class Envelope extends ToneAudioNode<EnvelopeOptions> {\n\treadonly name: string = \"Envelope\";\n\n\t/**\n\t * When triggerAttack is called, the attack time is the amount of\n\t * time it takes for the envelope to reach it's maximum value.\n\t * ```\n\t * /\\\n\t * /X \\\n\t * /XX \\\n\t * /XXX \\\n\t * /XXXX \\___________\n\t * /XXXXX \\\n\t * /XXXXXX \\\n\t * /XXXXXXX \\\n\t * /XXXXXXXX \\\n\t * ```\n\t * @min 0\n\t * @max 2\n\t */\n\t@timeRange(0)\n\tattack: Time;\n\n\t/**\n\t * After the attack portion of the envelope, the value will fall\n\t * over the duration of the decay time to it's sustain value.\n\t * ```\n\t * /\\\n\t * / X\\\n\t * / XX\\\n\t * / XXX\\\n\t * / XXXX\\___________\n\t * / XXXXX \\\n\t * / XXXXX \\\n\t * / XXXXX \\\n\t * / XXXXX \\\n\t * ```\n\t * @min 0\n\t * @max 2\n\t */\n\t@timeRange(0)\n\tdecay: Time;\n\n\t/**\n\t * The sustain value is the value\n\t * which the envelope rests at after triggerAttack is\n\t * called, but before triggerRelease is invoked.\n\t * ```\n\t * /\\\n\t * / \\\n\t * / \\\n\t * / \\\n\t * / \\___________\n\t * / XXXXXXXXXXX\\\n\t * / XXXXXXXXXXX \\\n\t * / XXXXXXXXXXX \\\n\t * / XXXXXXXXXXX \\\n\t * ```\n\t */\n\t@range(0, 1)\n\tsustain: NormalRange;\n\n\t/**\n\t * After triggerRelease is called, the envelope's\n\t * value will fall to it's miminum value over the\n\t * duration of the release time.\n\t * ```\n\t * /\\\n\t * / \\\n\t * / \\\n\t * / \\\n\t * / \\___________\n\t * / X\\\n\t * / XX\\\n\t * / XXX\\\n\t * / XXXX\\\n\t * ```\n\t * @min 0\n\t * @max 5\n\t */\n\t@timeRange(0)\n\trelease: Time;\n\n\t/**\n\t * The automation curve type for the attack\n\t */\n\tprivate _attackCurve!: InternalEnvelopeCurve;\n\n\t/**\n\t * The automation curve type for the decay\n\t */\n\tprivate _decayCurve!: InternalEnvelopeCurve;\n\n\t/**\n\t * The automation curve type for the release\n\t */\n\tprivate _releaseCurve!: InternalEnvelopeCurve;\n\n\t/**\n\t * the signal which is output.\n\t */\n\tprotected _sig: Signal<\"normalRange\"> = new Signal({\n\t\tcontext: this.context,\n\t\tvalue: 0,\n\t});\n\n\t/**\n\t * The output signal of the envelope\n\t */\n\toutput: OutputNode = this._sig;\n\n\t/**\n\t * Envelope has no input\n\t */\n\tinput: InputNode | undefined = undefined;\n\n\t/**\n\t * @param attack The amount of time it takes for the envelope to go from\n\t * 0 to it's maximum value.\n\t * @param decay\tThe period of time after the attack that it takes for the envelope\n\t * \tto fall to the sustain value. Value must be greater than 0.\n\t * @param sustain\tThe percent of the maximum value that the envelope rests at until\n\t * \tthe release is triggered.\n\t * @param release\tThe amount of time after the release is triggered it takes to reach 0.\n\t * \tValue must be greater than 0.\n\t */\n\tconstructor(\n\t\tattack?: Time,\n\t\tdecay?: Time,\n\t\tsustain?: NormalRange,\n\t\trelease?: Time\n\t);\n\tconstructor(options?: Partial<EnvelopeOptions>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(\n\t\t\tEnvelope.getDefaults(),\n\t\t\targuments,\n\t\t\t[\"attack\", \"decay\", \"sustain\", \"release\"]\n\t\t);\n\t\tsuper(options);\n\n\t\tthis.attack = options.attack;\n\t\tthis.decay = options.decay;\n\t\tthis.sustain = options.sustain;\n\t\tthis.release = options.release;\n\t\tthis.attackCurve = options.attackCurve;\n\t\tthis.releaseCurve = options.releaseCurve;\n\t\tthis.decayCurve = options.decayCurve;\n\t}\n\n\tstatic getDefaults(): EnvelopeOptions {\n\t\treturn Object.assign(ToneAudioNode.getDefaults(), {\n\t\t\tattack: 0.01,\n\t\t\tattackCurve: \"linear\" as EnvelopeCurveName,\n\t\t\tdecay: 0.1,\n\t\t\tdecayCurve: \"exponential\" as BasicEnvelopeCurve,\n\t\t\trelease: 1,\n\t\t\treleaseCurve: \"exponential\" as EnvelopeCurveName,\n\t\t\tsustain: 0.5,\n\t\t});\n\t}\n\n\t/**\n\t * Read the current value of the envelope. Useful for\n\t * synchronizing visual output to the envelope.\n\t */\n\tget value(): NormalRange {\n\t\treturn this.getValueAtTime(this.now());\n\t}\n\n\t/**\n\t * Get the curve\n\t * @param curve\n\t * @param direction In/Out\n\t * @return The curve name\n\t */\n\tprivate _getCurve(\n\t\tcurve: InternalEnvelopeCurve,\n\t\tdirection: EnvelopeDirection\n\t): EnvelopeCurve {\n\t\tif (isString(curve)) {\n\t\t\treturn curve;\n\t\t} else {\n\t\t\t// look up the name in the curves array\n\t\t\tlet curveName: EnvelopeCurveName;\n\t\t\tfor (curveName in EnvelopeCurves) {\n\t\t\t\tif (EnvelopeCurves[curveName][direction] === curve) {\n\t\t\t\t\treturn curveName;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// return the custom curve\n\t\t\treturn curve;\n\t\t}\n\t}\n\n\t/**\n\t * Assign a the curve to the given name using the direction\n\t * @param name\n\t * @param direction In/Out\n\t * @param curve\n\t */\n\tprivate _setCurve(\n\t\tname: \"_attackCurve\" | \"_decayCurve\" | \"_releaseCurve\",\n\t\tdirection: EnvelopeDirection,\n\t\tcurve: EnvelopeCurve\n\t): void {\n\t\t// check if it's a valid type\n\t\tif (isString(curve) && Reflect.has(EnvelopeCurves, curve)) {\n\t\t\tconst curveDef = EnvelopeCurves[curve];\n\t\t\tif (isObject(curveDef)) {\n\t\t\t\tif (name !== \"_decayCurve\") {\n\t\t\t\t\tthis[name] = curveDef[direction];\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthis[name] = curveDef;\n\t\t\t}\n\t\t} else if (isArray(curve) && name !== \"_decayCurve\") {\n\t\t\tthis[name] = curve;\n\t\t} else {\n\t\t\tthrow new Error(\"Envelope: invalid curve: \" + curve);\n\t\t}\n\t}\n\n\t/**\n\t * The shape of the attack.\n\t * Can be any of these strings:\n\t * * \"linear\"\n\t * * \"exponential\"\n\t * * \"sine\"\n\t * * \"cosine\"\n\t * * \"bounce\"\n\t * * \"ripple\"\n\t * * \"step\"\n\t *\n\t * Can also be an array which describes the curve. Values\n\t * in the array are evenly subdivided and linearly\n\t * interpolated over the duration of the attack.\n\t * @example\n\t * return Tone.Offline(() => {\n\t * \tconst env = new Tone.Envelope(0.4).toDestination();\n\t * \tenv.attackCurve = \"linear\";\n\t * \tenv.triggerAttack();\n\t * }, 1, 1);\n\t */\n\tget attackCurve(): EnvelopeCurve {\n\t\treturn this._getCurve(this._attackCurve, \"In\");\n\t}\n\tset attackCurve(curve) {\n\t\tthis._setCurve(\"_attackCurve\", \"In\", curve);\n\t}\n\n\t/**\n\t * The shape of the release. See the attack curve types.\n\t * @example\n\t * return Tone.Offline(() => {\n\t * \tconst env = new Tone.Envelope({\n\t * \t\trelease: 0.8\n\t * \t}).toDestination();\n\t * \tenv.triggerAttack();\n\t * \t// release curve could also be defined by an array\n\t * \tenv.releaseCurve = [1, 0.3, 0.4, 0.2, 0.7, 0];\n\t * \tenv.triggerRelease(0.2);\n\t * }, 1, 1);\n\t */\n\tget releaseCurve(): EnvelopeCurve {\n\t\treturn this._getCurve(this._releaseCurve, \"Out\");\n\t}\n\tset releaseCurve(curve) {\n\t\tthis._setCurve(\"_releaseCurve\", \"Out\", curve);\n\t}\n\n\t/**\n\t * The shape of the decay either \"linear\" or \"exponential\"\n\t * @example\n\t * return Tone.Offline(() => {\n\t * \tconst env = new Tone.Envelope({\n\t * \t\tsustain: 0.1,\n\t * \t\tdecay: 0.5\n\t * \t}).toDestination();\n\t * \tenv.decayCurve = \"linear\";\n\t * \tenv.triggerAttack();\n\t * }, 1, 1);\n\t */\n\tget decayCurve(): EnvelopeCurve {\n\t\treturn this._getCurve(this._decayCurve, \"Out\");\n\t}\n\tset decayCurve(curve) {\n\t\tthis._setCurve(\"_decayCurve\", \"Out\", curve);\n\t}\n\n\t/**\n\t * Trigger the attack/decay portion of the ADSR envelope.\n\t * @param time When the attack should start.\n\t * @param velocity The velocity of the envelope scales the vales.\n\t * number between 0-1\n\t * @example\n\t * const env = new Tone.AmplitudeEnvelope().toDestination();\n\t * const osc = new Tone.Oscillator().connect(env).start();\n\t * // trigger the attack 0.5 seconds from now with a velocity of 0.2\n\t * env.triggerAttack(\"+0.5\", 0.2);\n\t */\n\ttriggerAttack(time?: Time, velocity: NormalRange = 1): this {\n\t\tthis.log(\"triggerAttack\", time, velocity);\n\t\ttime = this.toSeconds(time);\n\t\tconst originalAttack = this.toSeconds(this.attack);\n\t\tlet attack = originalAttack;\n\t\tconst decay = this.toSeconds(this.decay);\n\t\t// check if it's not a complete attack\n\t\tconst currentValue = this.getValueAtTime(time);\n\t\tif (currentValue > 0) {\n\t\t\t// subtract the current value from the attack time\n\t\t\tconst attackRate = 1 / attack;\n\t\t\tconst remainingDistance = 1 - currentValue;\n\t\t\t// the attack is now the remaining time\n\t\t\tattack = remainingDistance / attackRate;\n\t\t}\n\t\t// attack\n\t\tif (attack < this.sampleTime) {\n\t\t\tthis._sig.cancelScheduledValues(time);\n\t\t\t// case where the attack time is 0 should set instantly\n\t\t\tthis._sig.setValueAtTime(velocity, time);\n\t\t} else if (this._attackCurve === \"linear\") {\n\t\t\tthis._sig.linearRampTo(velocity, attack, time);\n\t\t} else if (this._attackCurve === \"exponential\") {\n\t\t\tthis._sig.targetRampTo(velocity, attack, time);\n\t\t} else {\n\t\t\tthis._sig.cancelAndHoldAtTime(time);\n\t\t\tlet curve = this._attackCurve;\n\t\t\t// find the starting position in the curve\n\t\t\tfor (let i = 1; i < curve.length; i++) {\n\t\t\t\t// the starting index is between the two values\n\t\t\t\tif (curve[i - 1] <= currentValue && currentValue <= curve[i]) {\n\t\t\t\t\tcurve = this._attackCurve.slice(i);\n\t\t\t\t\t// the first index is the current value\n\t\t\t\t\tcurve[0] = currentValue;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis._sig.setValueCurveAtTime(curve, time, attack, velocity);\n\t\t}\n\t\t// decay\n\t\tif (decay && this.sustain < 1) {\n\t\t\tconst decayValue = velocity * this.sustain;\n\t\t\tconst decayStart = time + attack;\n\t\t\tthis.log(\"decay\", decayStart);\n\t\t\tif (this._decayCurve === \"linear\") {\n\t\t\t\tthis._sig.linearRampToValueAtTime(\n\t\t\t\t\tdecayValue,\n\t\t\t\t\tdecay + decayStart\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tthis._sig.exponentialApproachValueAtTime(\n\t\t\t\t\tdecayValue,\n\t\t\t\t\tdecayStart,\n\t\t\t\t\tdecay\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Triggers the release of the envelope.\n\t * @param time When the release portion of the envelope should start.\n\t * @example\n\t * const env = new Tone.AmplitudeEnvelope().toDestination();\n\t * const osc = new Tone.Oscillator({\n\t * \ttype: \"sawtooth\"\n\t * }).connect(env).start();\n\t * env.triggerAttack();\n\t * // trigger the release half a second after the attack\n\t * env.triggerRelease(\"+0.5\");\n\t */\n\ttriggerRelease(time?: Time): this {\n\t\tthis.log(\"triggerRelease\", time);\n\t\ttime = this.toSeconds(time);\n\t\tconst currentValue = this.getValueAtTime(time);\n\t\tif (currentValue > 0) {\n\t\t\tconst release = this.toSeconds(this.release);\n\t\t\tif (release < this.sampleTime) {\n\t\t\t\tthis._sig.setValueAtTime(0, time);\n\t\t\t} else if (this._releaseCurve === \"linear\") {\n\t\t\t\tthis._sig.linearRampTo(0, release, time);\n\t\t\t} else if (this._releaseCurve === \"exponential\") {\n\t\t\t\tthis._sig.targetRampTo(0, release, time);\n\t\t\t} else {\n\t\t\t\tassert(\n\t\t\t\t\tisArray(this._releaseCurve),\n\t\t\t\t\t\"releaseCurve must be either 'linear', 'exponential' or an array\"\n\t\t\t\t);\n\t\t\t\tthis._sig.cancelAndHoldAtTime(time);\n\t\t\t\tthis._sig.setValueCurveAtTime(\n\t\t\t\t\tthis._releaseCurve,\n\t\t\t\t\ttime,\n\t\t\t\t\trelease,\n\t\t\t\t\tcurrentValue\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Get the scheduled value at the given time. This will\n\t * return the unconverted (raw) value.\n\t * @example\n\t * const env = new Tone.Envelope(0.5, 1, 0.4, 2);\n\t * env.triggerAttackRelease(2);\n\t * setInterval(() => console.log(env.getValueAtTime(Tone.now())), 100);\n\t */\n\tgetValueAtTime(time: Time): NormalRange {\n\t\treturn this._sig.getValueAtTime(time);\n\t}\n\n\t/**\n\t * triggerAttackRelease is shorthand for triggerAttack, then waiting\n\t * some duration, then triggerRelease.\n\t * @param duration The duration of the sustain.\n\t * @param time When the attack should be triggered.\n\t * @param velocity The velocity of the envelope.\n\t * @example\n\t * const env = new Tone.AmplitudeEnvelope().toDestination();\n\t * const osc = new Tone.Oscillator().connect(env).start();\n\t * // trigger the release 0.5 seconds after the attack\n\t * env.triggerAttackRelease(0.5);\n\t */\n\ttriggerAttackRelease(\n\t\tduration: Time,\n\t\ttime?: Time,\n\t\tvelocity: NormalRange = 1\n\t): this {\n\t\ttime = this.toSeconds(time);\n\t\tthis.triggerAttack(time, velocity);\n\t\tthis.triggerRelease(time + this.toSeconds(duration));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Cancels all scheduled envelope changes after the given time.\n\t */\n\tcancel(after?: Time): this {\n\t\tthis._sig.cancelScheduledValues(this.toSeconds(after));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Connect the envelope to a destination node.\n\t */\n\tconnect(destination: InputNode, outputNumber = 0, inputNumber = 0): this {\n\t\tconnectSignal(this, destination, outputNumber, inputNumber);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Render the envelope curve to an array of the given length.\n\t * Good for visualizing the envelope curve. Rescales the duration of the\n\t * envelope to fit the length.\n\t */\n\tasync asArray(length = 1024): Promise<Float32Array> {\n\t\tconst duration = length / this.context.sampleRate;\n\t\tconst context = new OfflineContext(\n\t\t\t1,\n\t\t\tduration,\n\t\t\tthis.context.sampleRate\n\t\t);\n\t\t// normalize the ADSR for the given duration with 20% sustain time\n\t\tconst attackPortion =\n\t\t\tthis.toSeconds(this.attack) + this.toSeconds(this.decay);\n\t\tconst envelopeDuration = attackPortion + this.toSeconds(this.release);\n\t\tconst sustainTime = envelopeDuration * 0.1;\n\t\tconst totalDuration = envelopeDuration + sustainTime;\n\t\t// @ts-ignore\n\t\tconst clone = new this.constructor(\n\t\t\tObject.assign(this.get(), {\n\t\t\t\tattack:\n\t\t\t\t\t(duration * this.toSeconds(this.attack)) / totalDuration,\n\t\t\t\tdecay: (duration * this.toSeconds(this.decay)) / totalDuration,\n\t\t\t\trelease:\n\t\t\t\t\t(duration * this.toSeconds(this.release)) / totalDuration,\n\t\t\t\tcontext,\n\t\t\t})\n\t\t) as Envelope;\n\t\tclone._sig.toDestination();\n\t\tclone.triggerAttackRelease(\n\t\t\t(duration * (attackPortion + sustainTime)) / totalDuration,\n\t\t\t0\n\t\t);\n\t\tconst buffer = await context.render();\n\t\treturn buffer.getChannelData(0);\n\t}\n\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis._sig.dispose();\n\t\treturn this;\n\t}\n}\n\ninterface EnvelopeCurveObject {\n\tIn: number[];\n\tOut: number[];\n}\n\ntype EnvelopeDirection = keyof EnvelopeCurveObject;\n\ninterface EnvelopeCurveMap {\n\tlinear: \"linear\";\n\texponential: \"exponential\";\n\tbounce: EnvelopeCurveObject;\n\tcosine: EnvelopeCurveObject;\n\tsine: EnvelopeCurveObject;\n\tripple: EnvelopeCurveObject;\n\tstep: EnvelopeCurveObject;\n}\n\ntype EnvelopeCurveName = keyof EnvelopeCurveMap;\n\n/**\n * Generate some complex envelope curves.\n */\nconst EnvelopeCurves: EnvelopeCurveMap = (() => {\n\tconst curveLen = 128;\n\n\tlet i: number;\n\tlet k: number;\n\n\t// cosine curve\n\tconst cosineCurve: number[] = [];\n\tfor (i = 0; i < curveLen; i++) {\n\t\tcosineCurve[i] = Math.sin((i / (curveLen - 1)) * (Math.PI / 2));\n\t}\n\n\t// ripple curve\n\tconst rippleCurve: number[] = [];\n\tconst rippleCurveFreq = 6.4;\n\tfor (i = 0; i < curveLen - 1; i++) {\n\t\tk = i / (curveLen - 1);\n\t\tconst sineWave =\n\t\t\tMath.sin(k * (Math.PI * 2) * rippleCurveFreq - Math.PI / 2) + 1;\n\t\trippleCurve[i] = sineWave / 10 + k * 0.83;\n\t}\n\trippleCurve[curveLen - 1] = 1;\n\n\t// stairs curve\n\tconst stairsCurve: number[] = [];\n\tconst steps = 5;\n\tfor (i = 0; i < curveLen; i++) {\n\t\tstairsCurve[i] = Math.ceil((i / (curveLen - 1)) * steps) / steps;\n\t}\n\n\t// in-out easing curve\n\tconst sineCurve: number[] = [];\n\tfor (i = 0; i < curveLen; i++) {\n\t\tk = i / (curveLen - 1);\n\t\tsineCurve[i] = 0.5 * (1 - Math.cos(Math.PI * k));\n\t}\n\n\t// a bounce curve\n\tconst bounceCurve: number[] = [];\n\tfor (i = 0; i < curveLen; i++) {\n\t\tk = i / (curveLen - 1);\n\t\tconst freq = Math.pow(k, 3) * 4 + 0.2;\n\t\tconst val = Math.cos(freq * Math.PI * 2 * k);\n\t\tbounceCurve[i] = Math.abs(val * (1 - k));\n\t}\n\n\t/**\n\t * Invert a value curve to make it work for the release\n\t */\n\tfunction invertCurve(curve: number[]): number[] {\n\t\tconst out = new Array(curve.length);\n\t\tfor (let j = 0; j < curve.length; j++) {\n\t\t\tout[j] = 1 - curve[j];\n\t\t}\n\t\treturn out;\n\t}\n\n\t/**\n\t * reverse the curve\n\t */\n\tfunction reverseCurve(curve: number[]): number[] {\n\t\treturn curve.slice(0).reverse();\n\t}\n\n\t/**\n\t * attack and release curve arrays\n\t */\n\treturn {\n\t\tbounce: {\n\t\t\tIn: invertCurve(bounceCurve),\n\t\t\tOut: bounceCurve,\n\t\t},\n\t\tcosine: {\n\t\t\tIn: cosineCurve,\n\t\t\tOut: reverseCurve(cosineCurve),\n\t\t},\n\t\texponential: \"exponential\" as const,\n\t\tlinear: \"linear\" as const,\n\t\tripple: {\n\t\t\tIn: rippleCurve,\n\t\t\tOut: invertCurve(rippleCurve),\n\t\t},\n\t\tsine: {\n\t\t\tIn: sineCurve,\n\t\t\tOut: invertCurve(sineCurve),\n\t\t},\n\t\tstep: {\n\t\t\tIn: stairsCurve,\n\t\t\tOut: invertCurve(stairsCurve),\n\t\t},\n\t};\n})();\n","import { Volume } from \"../component/channel/Volume.js\";\nimport { Param } from \"../core/context/Param.js\";\nimport {\n\tOutputNode,\n\tToneAudioNode,\n\tToneAudioNodeOptions,\n} from \"../core/context/ToneAudioNode.js\";\nimport { Decibels, Frequency, NormalRange, Time } from \"../core/type/Units.js\";\nimport { optionsFromArguments } from \"../core/util/Defaults.js\";\nimport { readOnly } from \"../core/util/Interface.js\";\n\nexport interface InstrumentOptions extends ToneAudioNodeOptions {\n\tvolume: Decibels;\n}\n\n/**\n * Base-class for all instruments\n */\nexport abstract class Instrument<\n\tOptions extends InstrumentOptions,\n> extends ToneAudioNode<Options> {\n\t/**\n\t * The output and volume triming node\n\t */\n\tprivate _volume: Volume;\n\toutput: OutputNode;\n\n\t/**\n\t * The instrument only has an output\n\t */\n\tinput: undefined;\n\n\t/**\n\t * The volume of the output in decibels.\n\t * @example\n\t * const amSynth = new Tone.AMSynth().toDestination();\n\t * amSynth.volume.value = -6;\n\t * amSynth.triggerAttackRelease(\"G#3\", 0.2);\n\t */\n\tvolume: Param<\"decibels\">;\n\n\t/**\n\t * Keep track of all events scheduled to the transport\n\t * when the instrument is 'synced'\n\t */\n\tprivate _scheduledEvents: number[] = [];\n\n\t/**\n\t * If the instrument is currently synced\n\t */\n\tprivate _synced = false;\n\n\tconstructor(options?: Partial<InstrumentOptions>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(\n\t\t\tInstrument.getDefaults(),\n\t\t\targuments\n\t\t);\n\t\tsuper(options);\n\n\t\tthis._volume = this.output = new Volume({\n\t\t\tcontext: this.context,\n\t\t\tvolume: options.volume,\n\t\t});\n\t\tthis.volume = this._volume.volume;\n\t\treadOnly(this, \"volume\");\n\t}\n\n\tstatic getDefaults(): InstrumentOptions {\n\t\treturn Object.assign(ToneAudioNode.getDefaults(), {\n\t\t\tvolume: 0,\n\t\t});\n\t}\n\n\t/**\n\t * Sync the instrument to the Transport. All subsequent calls of\n\t * {@link triggerAttack} and {@link triggerRelease} will be scheduled along the transport.\n\t * @example\n\t * const fmSynth = new Tone.FMSynth().toDestination();\n\t * fmSynth.volume.value = -6;\n\t * fmSynth.sync();\n\t * // schedule 3 notes when the transport first starts\n\t * fmSynth.triggerAttackRelease(\"C4\", \"8n\", 0);\n\t * fmSynth.triggerAttackRelease(\"E4\", \"8n\", \"8n\");\n\t * fmSynth.triggerAttackRelease(\"G4\", \"8n\", \"4n\");\n\t * // start the transport to hear the notes\n\t * Tone.Transport.start();\n\t */\n\tsync(): this {\n\t\tif (this._syncState()) {\n\t\t\tthis._syncMethod(\"triggerAttack\", 1);\n\t\t\tthis._syncMethod(\"triggerRelease\", 0);\n\n\t\t\tthis.context.transport.on(\"stop\", this._syncedRelease);\n\t\t\tthis.context.transport.on(\"pause\", this._syncedRelease);\n\t\t\tthis.context.transport.on(\"loopEnd\", this._syncedRelease);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * set _sync\n\t */\n\tprotected _syncState(): boolean {\n\t\tlet changed = false;\n\t\tif (!this._synced) {\n\t\t\tthis._synced = true;\n\t\t\tchanged = true;\n\t\t}\n\t\treturn changed;\n\t}\n\n\t/**\n\t * Wrap the given method so that it can be synchronized\n\t * @param method Which method to wrap and sync\n\t * @param timePosition What position the time argument appears in\n\t */\n\tprotected _syncMethod(method: string, timePosition: number): void {\n\t\tconst originalMethod = (this[\"_original_\" + method] = this[method]);\n\t\tthis[method] = (...args: any[]) => {\n\t\t\tconst time = args[timePosition];\n\t\t\tconst id = this.context.transport.schedule((t) => {\n\t\t\t\targs[timePosition] = t;\n\t\t\t\toriginalMethod.apply(this, args);\n\t\t\t}, time);\n\t\t\tthis._scheduledEvents.push(id);\n\t\t};\n\t}\n\n\t/**\n\t * Unsync the instrument from the Transport\n\t */\n\tunsync(): this {\n\t\tthis._scheduledEvents.forEach((id) => this.context.transport.clear(id));\n\t\tthis._scheduledEvents = [];\n\t\tif (this._synced) {\n\t\t\tthis._synced = false;\n\t\t\tthis.triggerAttack = this._original_triggerAttack;\n\t\t\tthis.triggerRelease = this._original_triggerRelease;\n\n\t\t\tthis.context.transport.off(\"stop\", this._syncedRelease);\n\t\t\tthis.context.transport.off(\"pause\", this._syncedRelease);\n\t\t\tthis.context.transport.off(\"loopEnd\", this._syncedRelease);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Trigger the attack and then the release after the duration.\n\t * @param note The note to trigger.\n\t * @param duration How long the note should be held for before\n\t * triggering the release. This value must be greater than 0.\n\t * @param time When the note should be triggered.\n\t * @param velocity The velocity the note should be triggered at.\n\t * @example\n\t * const synth = new Tone.Synth().toDestination();\n\t * // trigger \"C4\" for the duration of an 8th note\n\t * synth.triggerAttackRelease(\"C4\", \"8n\");\n\t */\n\ttriggerAttackRelease(\n\t\tnote: Frequency,\n\t\tduration: Time,\n\t\ttime?: Time,\n\t\tvelocity?: NormalRange\n\t): this {\n\t\tconst computedTime = this.toSeconds(time);\n\t\tconst computedDuration = this.toSeconds(duration);\n\t\tthis.triggerAttack(note, computedTime, velocity);\n\t\tthis.triggerRelease(computedTime + computedDuration);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Start the instrument's note.\n\t * @param note the note to trigger\n\t * @param time the time to trigger the note\n\t * @param velocity the velocity to trigger the note (between 0-1)\n\t */\n\tabstract triggerAttack(\n\t\tnote: Frequency,\n\t\ttime?: Time,\n\t\tvelocity?: NormalRange\n\t): this;\n\tprivate _original_triggerAttack = this.triggerAttack;\n\n\t/**\n\t * Trigger the release phase of the current note.\n\t * @param time when to trigger the release\n\t */\n\tabstract triggerRelease(...args: any[]): this;\n\tprivate _original_triggerRelease = this.triggerRelease;\n\n\t/**\n\t * The release which is scheduled to the timeline.\n\t */\n\tprotected _syncedRelease = (time: number) =>\n\t\tthis._original_triggerRelease(time);\n\n\t/**\n\t * clean up\n\t * @returns {Instrument} this\n\t */\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis._volume.dispose();\n\t\tthis.unsync();\n\t\tthis._scheduledEvents = [];\n\t\treturn this;\n\t}\n}\n","import { FrequencyClass } from \"../core/type/Frequency.js\";\nimport {\n\tCents,\n\tFrequency,\n\tNormalRange,\n\tSeconds,\n\tTime,\n} from \"../core/type/Units.js\";\nimport { optionsFromArguments } from \"../core/util/Defaults.js\";\nimport { noOp } from \"../core/util/Interface.js\";\nimport { Instrument, InstrumentOptions } from \"../instrument/Instrument.js\";\nimport { Signal } from \"../signal/Signal.js\";\nimport { timeRange } from \"../core/util/Decorator.js\";\n\ntype onSilenceCallback = (instrument: Monophonic<any>) => void;\n\nexport interface MonophonicOptions extends InstrumentOptions {\n\tportamento: Seconds;\n\tonsilence: onSilenceCallback;\n\tdetune: Cents;\n}\n\n/**\n * Abstract base class for other monophonic instruments to extend.\n */\nexport abstract class Monophonic<\n\tOptions extends MonophonicOptions,\n> extends Instrument<Options> {\n\t/**\n\t * The glide time between notes.\n\t */\n\t@timeRange(0)\n\tportamento: Seconds;\n\n\t/**\n\t * Invoked when the release has finished and the output is silent.\n\t */\n\tonsilence: onSilenceCallback;\n\n\t/**\n\t * The instrument's frequency signal.\n\t */\n\tabstract readonly frequency: Signal<\"frequency\">;\n\n\t/**\n\t * The instrument's detune control signal.\n\t */\n\tabstract readonly detune: Signal<\"cents\">;\n\n\tconstructor(options?: Partial<MonophonicOptions>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(\n\t\t\tMonophonic.getDefaults(),\n\t\t\targuments\n\t\t);\n\t\tsuper(options);\n\n\t\tthis.portamento = options.portamento;\n\t\tthis.onsilence = options.onsilence;\n\t}\n\n\tstatic getDefaults(): MonophonicOptions {\n\t\treturn Object.assign(Instrument.getDefaults(), {\n\t\t\tdetune: 0,\n\t\t\tonsilence: noOp,\n\t\t\tportamento: 0,\n\t\t});\n\t}\n\n\t/**\n\t * Trigger the attack of the note optionally with a given velocity.\n\t * @param note The note to trigger.\n\t * @param time When the note should start.\n\t * @param velocity The velocity determines how \"loud\" the note will be.\n\t * @example\n\t * const synth = new Tone.Synth().toDestination();\n\t * // trigger the note a half second from now at half velocity\n\t * synth.triggerAttack(\"C4\", \"+0.5\", 0.5);\n\t */\n\ttriggerAttack(\n\t\tnote: Frequency | FrequencyClass,\n\t\ttime?: Time,\n\t\tvelocity: NormalRange = 1\n\t): this {\n\t\tthis.log(\"triggerAttack\", note, time, velocity);\n\t\tconst seconds = this.toSeconds(time);\n\t\tthis._triggerEnvelopeAttack(seconds, velocity);\n\t\tthis.setNote(note, seconds);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Trigger the release portion of the envelope.\n\t * @param time If no time is given, the release happens immediately.\n\t * @example\n\t * const synth = new Tone.Synth().toDestination();\n\t * synth.triggerAttack(\"C4\");\n\t * // trigger the release a second from now\n\t * synth.triggerRelease(\"+1\");\n\t */\n\ttriggerRelease(time?: Time): this {\n\t\tthis.log(\"triggerRelease\", time);\n\t\tconst seconds = this.toSeconds(time);\n\t\tthis._triggerEnvelopeRelease(seconds);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Internal method which starts the envelope attack\n\t */\n\tprotected abstract _triggerEnvelopeAttack(\n\t\ttime: Seconds,\n\t\tvelocity: NormalRange\n\t): void;\n\n\t/**\n\t * Internal method which starts the envelope release\n\t */\n\tprotected abstract _triggerEnvelopeRelease(time: Seconds): void;\n\n\t/**\n\t * Get the level of the output at the given time. Measures\n\t * the envelope(s) value at the time.\n\t * @param time The time to query the envelope value\n\t * @return The output level between 0-1\n\t */\n\tabstract getLevelAtTime(time: Time): NormalRange;\n\n\t/**\n\t * Set the note at the given time. If no time is given, the note\n\t * will set immediately.\n\t * @param note The note to change to.\n\t * @param time The time when the note should be set.\n\t * @example\n\t * const synth = new Tone.Synth().toDestination();\n\t * synth.triggerAttack(\"C4\");\n\t * // change to F#6 in one quarter note from now.\n\t * synth.setNote(\"F#6\", \"+4n\");\n\t */\n\tsetNote(note: Frequency | FrequencyClass, time?: Time): this {\n\t\tconst computedTime = this.toSeconds(time);\n\t\tconst computedFrequency =\n\t\t\tnote instanceof FrequencyClass ? note.toFrequency() : note;\n\t\tif (this.portamento > 0 && this.getLevelAtTime(computedTime) > 0.05) {\n\t\t\tconst portTime = this.toSeconds(this.portamento);\n\t\t\tthis.frequency.exponentialRampTo(\n\t\t\t\tcomputedFrequency,\n\t\t\t\tportTime,\n\t\t\t\tcomputedTime\n\t\t\t);\n\t\t} else {\n\t\t\tthis.frequency.setValueAtTime(computedFrequency, computedTime);\n\t\t}\n\t\treturn this;\n\t}\n}\n","import { Gain } from \"../../core/context/Gain.js\";\nimport { NormalRange, Time } from \"../../core/type/Units.js\";\nimport { optionsFromArguments } from \"../../core/util/Defaults.js\";\nimport { Envelope, EnvelopeOptions } from \"./Envelope.js\";\n\n/**\n * AmplitudeEnvelope is a Tone.Envelope connected to a gain node.\n * Unlike Tone.Envelope, which outputs the envelope's value, AmplitudeEnvelope accepts\n * an audio signal as the input and will apply the envelope to the amplitude\n * of the signal.\n * Read more about ADSR Envelopes on [Wikipedia](https://en.wikipedia.org/wiki/Synthesizer#ADSR_envelope).\n *\n * @example\n * return Tone.Offline(() => {\n * \tconst ampEnv = new Tone.AmplitudeEnvelope({\n * \t\tattack: 0.1,\n * \t\tdecay: 0.2,\n * \t\tsustain: 1.0,\n * \t\trelease: 0.8\n * \t}).toDestination();\n * \t// create an oscillator and connect it\n * \tconst osc = new Tone.Oscillator().connect(ampEnv).start();\n * \t// trigger the envelopes attack and release \"8t\" apart\n * \tampEnv.triggerAttackRelease(\"8t\");\n * }, 1.5, 1);\n * @category Component\n */\nexport class AmplitudeEnvelope extends Envelope {\n\treadonly name: string = \"AmplitudeEnvelope\";\n\n\tprivate _gainNode: Gain = new Gain({\n\t\tcontext: this.context,\n\t\tgain: 0,\n\t});\n\toutput: Gain = this._gainNode;\n\tinput: Gain = this._gainNode;\n\n\t/**\n\t * @param attack The amount of time it takes for the envelope to go from 0 to it's maximum value.\n\t * @param decay\tThe period of time after the attack that it takes for the envelope\n\t * \tto fall to the sustain value. Value must be greater than 0.\n\t * @param sustain\tThe percent of the maximum value that the envelope rests at until\n\t * \tthe release is triggered.\n\t * @param release\tThe amount of time after the release is triggered it takes to reach 0.\n\t * \tValue must be greater than 0.\n\t */\n\tconstructor(\n\t\tattack?: Time,\n\t\tdecay?: Time,\n\t\tsustain?: NormalRange,\n\t\trelease?: Time\n\t);\n\tconstructor(options?: Partial<EnvelopeOptions>);\n\tconstructor() {\n\t\tsuper(\n\t\t\toptionsFromArguments(AmplitudeEnvelope.getDefaults(), arguments, [\n\t\t\t\t\"attack\",\n\t\t\t\t\"decay\",\n\t\t\t\t\"sustain\",\n\t\t\t\t\"release\",\n\t\t\t])\n\t\t);\n\t\tthis._sig.connect(this._gainNode.gain);\n\t\tthis.output = this._gainNode;\n\t\tthis.input = this._gainNode;\n\t}\n\n\t/**\n\t * Clean up\n\t */\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis._gainNode.dispose();\n\t\treturn this;\n\t}\n}\n","import { AmplitudeEnvelope } from \"../component/envelope/AmplitudeEnvelope.js\";\nimport { Envelope, EnvelopeOptions } from \"../component/envelope/Envelope.js\";\nimport {\n\tToneAudioNode,\n\tToneAudioNodeOptions,\n} from \"../core/context/ToneAudioNode.js\";\nimport { NormalRange, Seconds, Time } from \"../core/type/Units.js\";\nimport { omitFromObject, optionsFromArguments } from \"../core/util/Defaults.js\";\nimport { readOnly } from \"../core/util/Interface.js\";\nimport { RecursivePartial } from \"../core/util/Interface.js\";\nimport { Signal } from \"../signal/Signal.js\";\nimport { OmniOscillator } from \"../source/oscillator/OmniOscillator.js\";\nimport {\n\tOmniOscillatorOptions,\n\tOmniOscillatorSynthOptions,\n} from \"../source/oscillator/OscillatorInterface.js\";\nimport { Source } from \"../source/Source.js\";\nimport { Monophonic, MonophonicOptions } from \"./Monophonic.js\";\n\nexport interface SynthOptions extends MonophonicOptions {\n\toscillator: OmniOscillatorSynthOptions;\n\tenvelope: Omit<EnvelopeOptions, keyof ToneAudioNodeOptions>;\n}\n\n/**\n * Synth is composed simply of a {@link OmniOscillator} routed through an {@link AmplitudeEnvelope}.\n * ```\n * +----------------+ +-------------------+\n * | OmniOscillator +>--> AmplitudeEnvelope +>--> Output\n * +----------------+ +-------------------+\n * ```\n * @example\n * const synth = new Tone.Synth().toDestination();\n * synth.triggerAttackRelease(\"C4\", \"8n\");\n * @category Instrument\n */\nexport class Synth<\n\tOptions extends SynthOptions = SynthOptions,\n> extends Monophonic<Options> {\n\treadonly name: string = \"Synth\";\n\n\t/**\n\t * The oscillator.\n\t */\n\treadonly oscillator: OmniOscillator<any>;\n\n\t/**\n\t * The frequency signal\n\t */\n\treadonly frequency: Signal<\"frequency\">;\n\n\t/**\n\t * The detune signal\n\t */\n\treadonly detune: Signal<\"cents\">;\n\n\t/**\n\t * The envelope\n\t */\n\treadonly envelope: AmplitudeEnvelope;\n\n\t/**\n\t * @param options the options available for the synth.\n\t */\n\tconstructor(options?: RecursivePartial<SynthOptions>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(Synth.getDefaults(), arguments);\n\t\tsuper(options);\n\n\t\tthis.oscillator = new OmniOscillator(\n\t\t\tObject.assign(\n\t\t\t\t{\n\t\t\t\t\tcontext: this.context,\n\t\t\t\t\tdetune: options.detune,\n\t\t\t\t\tonstop: () => this.onsilence(this),\n\t\t\t\t},\n\t\t\t\toptions.oscillator\n\t\t\t)\n\t\t);\n\n\t\tthis.frequency = this.oscillator.frequency;\n\t\tthis.detune = this.oscillator.detune;\n\n\t\tthis.envelope = new AmplitudeEnvelope(\n\t\t\tObject.assign(\n\t\t\t\t{\n\t\t\t\t\tcontext: this.context,\n\t\t\t\t},\n\t\t\t\toptions.envelope\n\t\t\t)\n\t\t);\n\n\t\t// connect the oscillators to the output\n\t\tthis.oscillator.chain(this.envelope, this.output);\n\t\treadOnly(this, [\"oscillator\", \"frequency\", \"detune\", \"envelope\"]);\n\t}\n\n\tstatic getDefaults(): SynthOptions {\n\t\treturn Object.assign(Monophonic.getDefaults(), {\n\t\t\tenvelope: Object.assign(\n\t\t\t\tomitFromObject(\n\t\t\t\t\tEnvelope.getDefaults(),\n\t\t\t\t\tObject.keys(ToneAudioNode.getDefaults())\n\t\t\t\t),\n\t\t\t\t{\n\t\t\t\t\tattack: 0.005,\n\t\t\t\t\tdecay: 0.1,\n\t\t\t\t\trelease: 1,\n\t\t\t\t\tsustain: 0.3,\n\t\t\t\t}\n\t\t\t),\n\t\t\toscillator: Object.assign(\n\t\t\t\tomitFromObject(OmniOscillator.getDefaults(), [\n\t\t\t\t\t...Object.keys(Source.getDefaults()),\n\t\t\t\t\t\"frequency\",\n\t\t\t\t\t\"detune\",\n\t\t\t\t]),\n\t\t\t\t{\n\t\t\t\t\ttype: \"triangle\",\n\t\t\t\t}\n\t\t\t) as OmniOscillatorOptions,\n\t\t});\n\t}\n\n\t/**\n\t * start the attack portion of the envelope\n\t * @param time the time the attack should start\n\t * @param velocity the velocity of the note (0-1)\n\t */\n\tprotected _triggerEnvelopeAttack(time: Seconds, velocity: number): void {\n\t\t// the envelopes\n\t\tthis.envelope.triggerAttack(time, velocity);\n\t\tthis.oscillator.start(time);\n\t\t// if there is no release portion, stop the oscillator\n\t\tif (this.envelope.sustain === 0) {\n\t\t\tconst computedAttack = this.toSeconds(this.envelope.attack);\n\t\t\tconst computedDecay = this.toSeconds(this.envelope.decay);\n\t\t\tthis.oscillator.stop(time + computedAttack + computedDecay);\n\t\t}\n\t}\n\n\t/**\n\t * start the release portion of the envelope\n\t * @param time the time the release should start\n\t */\n\tprotected _triggerEnvelopeRelease(time: Seconds): void {\n\t\tthis.envelope.triggerRelease(time);\n\t\tthis.oscillator.stop(time + this.toSeconds(this.envelope.release));\n\t}\n\n\tgetLevelAtTime(time: Time): NormalRange {\n\t\ttime = this.toSeconds(time);\n\t\treturn this.envelope.getValueAtTime(time);\n\t}\n\n\t/**\n\t * clean up\n\t */\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis.oscillator.dispose();\n\t\tthis.envelope.dispose();\n\t\treturn this;\n\t}\n}\n","import { Signal } from \"../signal/Signal.js\";\nimport { Multiply } from \"../signal/Multiply.js\";\nimport { Gain } from \"../core/context/Gain.js\";\nimport { NormalRange, Positive, Seconds, Time } from \"../core/type/Units.js\";\nimport { Envelope, EnvelopeOptions } from \"../component/envelope/Envelope.js\";\nimport {\n\tToneAudioNode,\n\tToneAudioNodeOptions,\n} from \"../core/context/ToneAudioNode.js\";\nimport { Monophonic } from \"./Monophonic.js\";\nimport { OmniOscillator } from \"../source/oscillator/OmniOscillator.js\";\nimport { OmniOscillatorSynthOptions } from \"../source/oscillator/OscillatorInterface.js\";\nimport { Source } from \"../source/Source.js\";\nimport { Synth, SynthOptions } from \"./Synth.js\";\nimport { AmplitudeEnvelope } from \"../component/envelope/AmplitudeEnvelope.js\";\nimport { readOnly, RecursivePartial } from \"../core/util/Interface.js\";\nimport { omitFromObject, optionsFromArguments } from \"../core/util/Defaults.js\";\n\nexport interface ModulationSynthOptions extends SynthOptions {\n\tharmonicity: Positive;\n\tmodulationEnvelope: Omit<EnvelopeOptions, keyof ToneAudioNodeOptions>;\n\tmodulation: OmniOscillatorSynthOptions;\n}\n/**\n * Base class for both AM and FM synths\n */\nexport abstract class ModulationSynth<\n\tOptions extends ModulationSynthOptions,\n> extends Monophonic<Options> {\n\treadonly name: string = \"ModulationSynth\";\n\n\t/**\n\t * The carrier voice.\n\t */\n\tprotected _carrier: Synth;\n\n\t/**\n\t * The modulator voice.\n\t */\n\n\tprotected _modulator: Synth;\n\n\t/**\n\t * The carrier's oscillator\n\t */\n\treadonly oscillator: OmniOscillator<any>;\n\n\t/**\n\t * The carrier's envelope\n\t */\n\treadonly envelope: AmplitudeEnvelope;\n\n\t/**\n\t * The modulator's oscillator which is applied to the amplitude of the oscillator\n\t */\n\treadonly modulation: OmniOscillator<any>;\n\n\t/**\n\t * The modulator's envelope\n\t */\n\treadonly modulationEnvelope: AmplitudeEnvelope;\n\n\t/**\n\t * The frequency control\n\t */\n\treadonly frequency: Signal<\"frequency\">;\n\n\t/**\n\t * The detune in cents\n\t */\n\treadonly detune: Signal<\"cents\">;\n\n\t/**\n\t * Harmonicity is the ratio between the two voices. A harmonicity of\n\t * 1 is no change. Harmonicity = 2 means a change of an octave.\n\t * @example\n\t * const amSynth = new Tone.AMSynth().toDestination();\n\t * // pitch the modulator an octave below oscillator\n\t * amSynth.harmonicity.value = 0.5;\n\t * amSynth.triggerAttackRelease(\"C5\", \"4n\");\n\t */\n\treadonly harmonicity: Multiply;\n\n\t/**\n\t * The node where the modulation happens\n\t */\n\tprotected _modulationNode: Gain;\n\n\tconstructor(options?: RecursivePartial<ModulationSynthOptions>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(\n\t\t\tModulationSynth.getDefaults(),\n\t\t\targuments\n\t\t);\n\t\tsuper(options);\n\n\t\tthis._carrier = new Synth({\n\t\t\tcontext: this.context,\n\t\t\toscillator: options.oscillator,\n\t\t\tenvelope: options.envelope,\n\t\t\tonsilence: () => this.onsilence(this),\n\t\t\tvolume: -10,\n\t\t});\n\t\tthis._modulator = new Synth({\n\t\t\tcontext: this.context,\n\t\t\toscillator: options.modulation,\n\t\t\tenvelope: options.modulationEnvelope,\n\t\t\tvolume: -10,\n\t\t});\n\n\t\tthis.oscillator = this._carrier.oscillator;\n\t\tthis.envelope = this._carrier.envelope;\n\t\tthis.modulation = this._modulator.oscillator;\n\t\tthis.modulationEnvelope = this._modulator.envelope;\n\n\t\tthis.frequency = new Signal({\n\t\t\tcontext: this.context,\n\t\t\tunits: \"frequency\",\n\t\t});\n\t\tthis.detune = new Signal({\n\t\t\tcontext: this.context,\n\t\t\tvalue: options.detune,\n\t\t\tunits: \"cents\",\n\t\t});\n\t\tthis.harmonicity = new Multiply({\n\t\t\tcontext: this.context,\n\t\t\tvalue: options.harmonicity,\n\t\t\tminValue: 0,\n\t\t});\n\t\tthis._modulationNode = new Gain({\n\t\t\tcontext: this.context,\n\t\t\tgain: 0,\n\t\t});\n\n\t\treadOnly(this, [\n\t\t\t\"frequency\",\n\t\t\t\"harmonicity\",\n\t\t\t\"oscillator\",\n\t\t\t\"envelope\",\n\t\t\t\"modulation\",\n\t\t\t\"modulationEnvelope\",\n\t\t\t\"detune\",\n\t\t]);\n\t}\n\n\tstatic getDefaults(): ModulationSynthOptions {\n\t\treturn Object.assign(Monophonic.getDefaults(), {\n\t\t\tharmonicity: 3,\n\t\t\toscillator: Object.assign(\n\t\t\t\tomitFromObject(OmniOscillator.getDefaults(), [\n\t\t\t\t\t...Object.keys(Source.getDefaults()),\n\t\t\t\t\t\"frequency\",\n\t\t\t\t\t\"detune\",\n\t\t\t\t]),\n\t\t\t\t{\n\t\t\t\t\ttype: \"sine\",\n\t\t\t\t}\n\t\t\t) as OmniOscillatorSynthOptions,\n\t\t\tenvelope: Object.assign(\n\t\t\t\tomitFromObject(\n\t\t\t\t\tEnvelope.getDefaults(),\n\t\t\t\t\tObject.keys(ToneAudioNode.getDefaults())\n\t\t\t\t),\n\t\t\t\t{\n\t\t\t\t\tattack: 0.01,\n\t\t\t\t\tdecay: 0.01,\n\t\t\t\t\tsustain: 1,\n\t\t\t\t\trelease: 0.5,\n\t\t\t\t}\n\t\t\t),\n\t\t\tmodulation: Object.assign(\n\t\t\t\tomitFromObject(OmniOscillator.getDefaults(), [\n\t\t\t\t\t...Object.keys(Source.getDefaults()),\n\t\t\t\t\t\"frequency\",\n\t\t\t\t\t\"detune\",\n\t\t\t\t]),\n\t\t\t\t{\n\t\t\t\t\ttype: \"square\",\n\t\t\t\t}\n\t\t\t) as OmniOscillatorSynthOptions,\n\t\t\tmodulationEnvelope: Object.assign(\n\t\t\t\tomitFromObject(\n\t\t\t\t\tEnvelope.getDefaults(),\n\t\t\t\t\tObject.keys(ToneAudioNode.getDefaults())\n\t\t\t\t),\n\t\t\t\t{\n\t\t\t\t\tattack: 0.5,\n\t\t\t\t\tdecay: 0.0,\n\t\t\t\t\tsustain: 1,\n\t\t\t\t\trelease: 0.5,\n\t\t\t\t}\n\t\t\t),\n\t\t});\n\t}\n\n\t/**\n\t * Trigger the attack portion of the note\n\t */\n\tprotected _triggerEnvelopeAttack(time: Seconds, velocity: number): void {\n\t\t// @ts-ignore\n\t\tthis._carrier._triggerEnvelopeAttack(time, velocity);\n\t\t// @ts-ignore\n\t\tthis._modulator._triggerEnvelopeAttack(time, velocity);\n\t}\n\n\t/**\n\t * Trigger the release portion of the note\n\t */\n\tprotected _triggerEnvelopeRelease(time: Seconds) {\n\t\t// @ts-ignore\n\t\tthis._carrier._triggerEnvelopeRelease(time);\n\t\t// @ts-ignore\n\t\tthis._modulator._triggerEnvelopeRelease(time);\n\t\treturn this;\n\t}\n\n\tgetLevelAtTime(time: Time): NormalRange {\n\t\ttime = this.toSeconds(time);\n\t\treturn this.envelope.getValueAtTime(time);\n\t}\n\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis._carrier.dispose();\n\t\tthis._modulator.dispose();\n\t\tthis.frequency.dispose();\n\t\tthis.detune.dispose();\n\t\tthis.harmonicity.dispose();\n\t\tthis._modulationNode.dispose();\n\t\treturn this;\n\t}\n}\n","import {\n\tToneAudioNode,\n\tToneAudioNodeOptions,\n} from \"../../core/context/ToneAudioNode.js\";\nimport { Cents, Frequency, GainFactor } from \"../../core/type/Units.js\";\nimport { optionsFromArguments } from \"../../core/util/Defaults.js\";\nimport { Param } from \"../../core/context/Param.js\";\nimport { assert } from \"../../core/util/Debug.js\";\n\nexport interface BiquadFilterOptions extends ToneAudioNodeOptions {\n\tfrequency: Frequency;\n\tdetune: Cents;\n\tQ: number;\n\ttype: BiquadFilterType;\n\tgain: GainFactor;\n}\n\n/**\n * Thin wrapper around the native Web Audio [BiquadFilterNode](https://webaudio.github.io/web-audio-api/#biquadfilternode).\n * BiquadFilter is similar to {@link Filter} but doesn't have the option to set the \"rolloff\" value.\n * @category Component\n */\nexport class BiquadFilter extends ToneAudioNode<BiquadFilterOptions> {\n\treadonly name: string = \"BiquadFilter\";\n\n\treadonly input: BiquadFilterNode;\n\treadonly output: BiquadFilterNode;\n\n\t/**\n\t * The frequency of the filter\n\t */\n\treadonly frequency: Param<\"frequency\">;\n\n\t/**\n\t * A detune value, in cents, for the frequency.\n\t */\n\treadonly detune: Param<\"cents\">;\n\n\t/**\n\t * The Q factor of the filter.\n\t * For lowpass and highpass filters the Q value is interpreted to be in dB.\n\t * For these filters the nominal range is [−𝑄𝑙𝑖𝑚,𝑄𝑙𝑖𝑚] where 𝑄𝑙𝑖𝑚 is the largest value for which 10𝑄/20 does not overflow. This is approximately 770.63678.\n\t * For the bandpass, notch, allpass, and peaking filters, this value is a linear value.\n\t * The value is related to the bandwidth of the filter and hence should be a positive value. The nominal range is\n\t * [0,3.4028235𝑒38], the upper limit being the most-positive-single-float.\n\t * This is not used for the lowshelf and highshelf filters.\n\t */\n\treadonly Q: Param<\"number\">;\n\n\t/**\n\t * The gain of the filter. Its value is in dB units. The gain is only used for lowshelf, highshelf, and peaking filters.\n\t */\n\treadonly gain: Param<\"decibels\">;\n\n\tprivate readonly _filter: BiquadFilterNode;\n\n\t/**\n\t * @param frequency The cutoff frequency of the filter.\n\t * @param type The type of filter.\n\t */\n\tconstructor(frequency?: Frequency, type?: BiquadFilterType);\n\tconstructor(options?: Partial<BiquadFilterOptions>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(\n\t\t\tBiquadFilter.getDefaults(),\n\t\t\targuments,\n\t\t\t[\"frequency\", \"type\"]\n\t\t);\n\t\tsuper(options);\n\n\t\tthis._filter = this.context.createBiquadFilter();\n\t\tthis.input = this.output = this._filter;\n\n\t\tthis.Q = new Param({\n\t\t\tcontext: this.context,\n\t\t\tunits: \"number\",\n\t\t\tvalue: options.Q,\n\t\t\tparam: this._filter.Q,\n\t\t});\n\n\t\tthis.frequency = new Param({\n\t\t\tcontext: this.context,\n\t\t\tunits: \"frequency\",\n\t\t\tvalue: options.frequency,\n\t\t\tparam: this._filter.frequency,\n\t\t});\n\n\t\tthis.detune = new Param({\n\t\t\tcontext: this.context,\n\t\t\tunits: \"cents\",\n\t\t\tvalue: options.detune,\n\t\t\tparam: this._filter.detune,\n\t\t});\n\n\t\tthis.gain = new Param({\n\t\t\tcontext: this.context,\n\t\t\tunits: \"decibels\",\n\t\t\tconvert: false,\n\t\t\tvalue: options.gain,\n\t\t\tparam: this._filter.gain,\n\t\t});\n\n\t\tthis.type = options.type;\n\t}\n\n\tstatic getDefaults(): BiquadFilterOptions {\n\t\treturn Object.assign(ToneAudioNode.getDefaults(), {\n\t\t\tQ: 1,\n\t\t\ttype: \"lowpass\" as const,\n\t\t\tfrequency: 350,\n\t\t\tdetune: 0,\n\t\t\tgain: 0,\n\t\t});\n\t}\n\n\t/**\n\t * The type of this BiquadFilterNode. For a complete list of types and their attributes, see the\n\t * [Web Audio API](https://webaudio.github.io/web-audio-api/#dom-biquadfiltertype-lowpass)\n\t */\n\tget type(): BiquadFilterType {\n\t\treturn this._filter.type;\n\t}\n\tset type(type) {\n\t\tconst types: BiquadFilterType[] = [\n\t\t\t\"lowpass\",\n\t\t\t\"highpass\",\n\t\t\t\"bandpass\",\n\t\t\t\"lowshelf\",\n\t\t\t\"highshelf\",\n\t\t\t\"notch\",\n\t\t\t\"allpass\",\n\t\t\t\"peaking\",\n\t\t];\n\t\tassert(types.indexOf(type) !== -1, `Invalid filter type: ${type}`);\n\t\tthis._filter.type = type;\n\t}\n\n\t/**\n\t * Get the frequency response curve. This curve represents how the filter\n\t * responses to frequencies between 20hz-20khz.\n\t * @param len The number of values to return\n\t * @return The frequency response curve between 20-20kHz\n\t */\n\tgetFrequencyResponse(len = 128): Float32Array {\n\t\t// start with all 1s\n\t\tconst freqValues = new Float32Array(len);\n\t\tfor (let i = 0; i < len; i++) {\n\t\t\tconst norm = Math.pow(i / len, 2);\n\t\t\tconst freq = norm * (20000 - 20) + 20;\n\t\t\tfreqValues[i] = freq;\n\t\t}\n\t\tconst magValues = new Float32Array(len);\n\t\tconst phaseValues = new Float32Array(len);\n\t\t// clone the filter to remove any connections which may be changing the value\n\t\tconst filterClone = this.context.createBiquadFilter();\n\t\tfilterClone.type = this.type;\n\t\tfilterClone.Q.value = this.Q.value;\n\t\tfilterClone.frequency.value = this.frequency.value as number;\n\t\tfilterClone.gain.value = this.gain.value as number;\n\t\tfilterClone.getFrequencyResponse(freqValues, magValues, phaseValues);\n\t\treturn magValues;\n\t}\n\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis._filter.disconnect();\n\t\tthis.Q.dispose();\n\t\tthis.frequency.dispose();\n\t\tthis.gain.dispose();\n\t\tthis.detune.dispose();\n\t\treturn this;\n\t}\n}\n","import { Gain } from \"../../core/context/Gain.js\";\nimport {\n\tconnectSeries,\n\tToneAudioNode,\n} from \"../../core/context/ToneAudioNode.js\";\nimport { Frequency } from \"../../core/type/Units.js\";\nimport { optionsFromArguments } from \"../../core/util/Defaults.js\";\nimport { readOnly, writable } from \"../../core/util/Interface.js\";\nimport { isNumber } from \"../../core/util/TypeCheck.js\";\nimport { Signal } from \"../../signal/Signal.js\";\nimport { assert } from \"../../core/util/Debug.js\";\nimport { BiquadFilter, BiquadFilterOptions } from \"./BiquadFilter.js\";\n\nexport type FilterRollOff = -12 | -24 | -48 | -96;\n\nexport type FilterOptions = BiquadFilterOptions & {\n\trolloff: FilterRollOff;\n};\n\n/**\n * Tone.Filter is a filter which allows for all of the same native methods\n * as the [BiquadFilterNode](http://webaudio.github.io/web-audio-api/#the-biquadfilternode-interface).\n * Tone.Filter has the added ability to set the filter rolloff at -12\n * (default), -24 and -48.\n * @example\n * const filter = new Tone.Filter(1500, \"highpass\").toDestination();\n * filter.frequency.rampTo(20000, 10);\n * const noise = new Tone.Noise().connect(filter).start();\n * @category Component\n */\nexport class Filter extends ToneAudioNode<FilterOptions> {\n\treadonly name: string = \"Filter\";\n\n\treadonly input = new Gain({ context: this.context });\n\treadonly output = new Gain({ context: this.context });\n\tprivate _filters: BiquadFilter[] = [];\n\n\t/**\n\t * the rolloff value of the filter\n\t */\n\tprivate _rolloff!: FilterRollOff;\n\tprivate _type: BiquadFilterType;\n\n\t/**\n\t * The Q or Quality of the filter\n\t */\n\treadonly Q: Signal<\"positive\">;\n\n\t/**\n\t * The cutoff frequency of the filter.\n\t */\n\treadonly frequency: Signal<\"frequency\">;\n\n\t/**\n\t * The detune parameter\n\t */\n\treadonly detune: Signal<\"cents\">;\n\n\t/**\n\t * The gain of the filter, only used in certain filter types\n\t */\n\treadonly gain: Signal<\"decibels\">;\n\n\t/**\n\t * @param frequency The cutoff frequency of the filter.\n\t * @param type The type of filter.\n\t * @param rolloff The drop in decibels per octave after the cutoff frequency\n\t */\n\tconstructor(\n\t\tfrequency?: Frequency,\n\t\ttype?: BiquadFilterType,\n\t\trolloff?: FilterRollOff\n\t);\n\tconstructor(options?: Partial<FilterOptions>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(Filter.getDefaults(), arguments, [\n\t\t\t\"frequency\",\n\t\t\t\"type\",\n\t\t\t\"rolloff\",\n\t\t]);\n\t\tsuper(options);\n\n\t\tthis._filters = [];\n\n\t\tthis.Q = new Signal({\n\t\t\tcontext: this.context,\n\t\t\tunits: \"positive\",\n\t\t\tvalue: options.Q,\n\t\t});\n\t\tthis.frequency = new Signal({\n\t\t\tcontext: this.context,\n\t\t\tunits: \"frequency\",\n\t\t\tvalue: options.frequency,\n\t\t});\n\t\tthis.detune = new Signal({\n\t\t\tcontext: this.context,\n\t\t\tunits: \"cents\",\n\t\t\tvalue: options.detune,\n\t\t});\n\t\tthis.gain = new Signal({\n\t\t\tcontext: this.context,\n\t\t\tunits: \"decibels\",\n\t\t\tconvert: false,\n\t\t\tvalue: options.gain,\n\t\t});\n\t\tthis._type = options.type;\n\t\tthis.rolloff = options.rolloff;\n\t\treadOnly(this, [\"detune\", \"frequency\", \"gain\", \"Q\"]);\n\t}\n\n\tstatic getDefaults(): FilterOptions {\n\t\treturn Object.assign(ToneAudioNode.getDefaults(), {\n\t\t\tQ: 1,\n\t\t\tdetune: 0,\n\t\t\tfrequency: 350,\n\t\t\tgain: 0,\n\t\t\trolloff: -12 as FilterRollOff,\n\t\t\ttype: \"lowpass\" as BiquadFilterType,\n\t\t});\n\t}\n\n\t/**\n\t * The type of the filter. Types: \"lowpass\", \"highpass\",\n\t * \"bandpass\", \"lowshelf\", \"highshelf\", \"notch\", \"allpass\", or \"peaking\".\n\t */\n\tget type(): BiquadFilterType {\n\t\treturn this._type;\n\t}\n\tset type(type: BiquadFilterType) {\n\t\tconst types: BiquadFilterType[] = [\n\t\t\t\"lowpass\",\n\t\t\t\"highpass\",\n\t\t\t\"bandpass\",\n\t\t\t\"lowshelf\",\n\t\t\t\"highshelf\",\n\t\t\t\"notch\",\n\t\t\t\"allpass\",\n\t\t\t\"peaking\",\n\t\t];\n\t\tassert(types.indexOf(type) !== -1, `Invalid filter type: ${type}`);\n\t\tthis._type = type;\n\t\tthis._filters.forEach((filter) => (filter.type = type));\n\t}\n\n\t/**\n\t * The rolloff of the filter which is the drop in db\n\t * per octave. Implemented internally by cascading filters.\n\t * Only accepts the values -12, -24, -48 and -96.\n\t */\n\tget rolloff(): FilterRollOff {\n\t\treturn this._rolloff;\n\t}\n\tset rolloff(rolloff) {\n\t\tconst rolloffNum = isNumber(rolloff)\n\t\t\t? rolloff\n\t\t\t: (parseInt(rolloff, 10) as FilterRollOff);\n\t\tconst possibilities = [-12, -24, -48, -96];\n\t\tlet cascadingCount = possibilities.indexOf(rolloffNum);\n\t\t// check the rolloff is valid\n\t\tassert(\n\t\t\tcascadingCount !== -1,\n\t\t\t`rolloff can only be ${possibilities.join(\", \")}`\n\t\t);\n\t\tcascadingCount += 1;\n\n\t\tthis._rolloff = rolloffNum;\n\t\tthis.input.disconnect();\n\t\tthis._filters.forEach((filter) => filter.disconnect());\n\n\t\tthis._filters = new Array(cascadingCount);\n\t\tfor (let count = 0; count < cascadingCount; count++) {\n\t\t\tconst filter = new BiquadFilter({\n\t\t\t\tcontext: this.context,\n\t\t\t});\n\t\t\tfilter.type = this._type;\n\t\t\tthis.frequency.connect(filter.frequency);\n\t\t\tthis.detune.connect(filter.detune);\n\t\t\tthis.Q.connect(filter.Q);\n\t\t\tthis.gain.connect(filter.gain);\n\t\t\tthis._filters[count] = filter;\n\t\t}\n\t\tthis._internalChannels = this._filters;\n\t\tconnectSeries(this.input, ...this._internalChannels, this.output);\n\t}\n\n\t/**\n\t * Get the frequency response curve. This curve represents how the filter\n\t * responses to frequencies between 20hz-20khz.\n\t * @param len The number of values to return\n\t * @return The frequency response curve between 20-20kHz\n\t */\n\tgetFrequencyResponse(len = 128): Float32Array {\n\t\tconst filterClone = new BiquadFilter({\n\t\t\tcontext: this.context,\n\t\t\tfrequency: this.frequency.value,\n\t\t\tgain: this.gain.value,\n\t\t\tQ: this.Q.value,\n\t\t\ttype: this._type,\n\t\t\tdetune: this.detune.value,\n\t\t});\n\t\t// start with all 1s\n\t\tconst totalResponse = new Float32Array(len).map(() => 1);\n\t\tthis._filters.forEach(() => {\n\t\t\tconst response = filterClone.getFrequencyResponse(len);\n\t\t\tresponse.forEach((val, i) => (totalResponse[i] *= val));\n\t\t});\n\t\tfilterClone.dispose();\n\t\treturn totalResponse;\n\t}\n\n\t/**\n\t * Clean up.\n\t */\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis._filters.forEach((filter) => {\n\t\t\tfilter.dispose();\n\t\t});\n\t\twritable(this, [\"detune\", \"frequency\", \"gain\", \"Q\"]);\n\t\tthis.frequency.dispose();\n\t\tthis.Q.dispose();\n\t\tthis.detune.dispose();\n\t\tthis.gain.dispose();\n\t\treturn this;\n\t}\n}\n","import { Positive } from \"../core/type/Units.js\";\nimport { optionsFromArguments } from \"../core/util/Defaults.js\";\nimport { RecursivePartial } from \"../core/util/Interface.js\";\nimport { Multiply } from \"../signal/Multiply.js\";\nimport { ModulationSynth, ModulationSynthOptions } from \"./ModulationSynth.js\";\n\nexport interface FMSynthOptions extends ModulationSynthOptions {\n\tmodulationIndex: Positive;\n}\n\n/**\n * FMSynth is composed of two Tone.Synths where one Tone.Synth modulates\n * the frequency of a second Tone.Synth. A lot of spectral content\n * can be explored using the modulationIndex parameter. Read more about\n * frequency modulation synthesis on Sound On Sound: [Part 1](https://web.archive.org/web/20160403123704/http://www.soundonsound.com/sos/apr00/articles/synthsecrets.htm), [Part 2](https://web.archive.org/web/20160403115835/http://www.soundonsound.com/sos/may00/articles/synth.htm).\n *\n * @example\n * const fmSynth = new Tone.FMSynth().toDestination();\n * fmSynth.triggerAttackRelease(\"C5\", \"4n\");\n *\n * @category Instrument\n */\n\nexport class FMSynth extends ModulationSynth<FMSynthOptions> {\n\treadonly name: string = \"FMSynth\";\n\n\t/**\n\t * The modulation index which essentially the depth or amount of the modulation. It is the\n\t * ratio of the frequency of the modulating signal (mf) to the amplitude of the\n\t * modulating signal (ma) -- as in ma/mf.\n\t */\n\treadonly modulationIndex: Multiply;\n\n\tconstructor(options?: RecursivePartial<FMSynthOptions>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(FMSynth.getDefaults(), arguments);\n\t\tsuper(options);\n\n\t\tthis.modulationIndex = new Multiply({\n\t\t\tcontext: this.context,\n\t\t\tvalue: options.modulationIndex,\n\t\t});\n\n\t\t// control the two voices frequency\n\t\tthis.frequency.connect(this._carrier.frequency);\n\t\tthis.frequency.chain(this.harmonicity, this._modulator.frequency);\n\t\tthis.frequency.chain(this.modulationIndex, this._modulationNode);\n\t\tthis.detune.fan(this._carrier.detune, this._modulator.detune);\n\t\tthis._modulator.connect(this._modulationNode.gain);\n\t\tthis._modulationNode.connect(this._carrier.frequency);\n\t\tthis._carrier.connect(this.output);\n\t}\n\n\tstatic getDefaults(): FMSynthOptions {\n\t\treturn Object.assign(ModulationSynth.getDefaults(), {\n\t\t\tmodulationIndex: 10,\n\t\t});\n\t}\n\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis.modulationIndex.dispose();\n\t\treturn this;\n\t}\n}\n","import { FrequencyClass } from \"../core/type/Frequency.js\";\nimport { Frequency, Positive, Time } from \"../core/type/Units.js\";\nimport { deepMerge, optionsFromArguments } from \"../core/util/Defaults.js\";\nimport { readOnly, RecursivePartial } from \"../core/util/Interface.js\";\nimport { Monophonic } from \"./Monophonic.js\";\nimport { Synth, SynthOptions } from \"./Synth.js\";\nimport { range, timeRange } from \"../core/util/Decorator.js\";\n\nexport interface MembraneSynthOptions extends SynthOptions {\n\tpitchDecay: Time;\n\toctaves: Positive;\n}\n\n/**\n * MembraneSynth makes kick and tom sounds using a single oscillator\n * with an amplitude envelope and frequency ramp. A Tone.OmniOscillator\n * is routed through a Tone.AmplitudeEnvelope to the output. The drum\n * quality of the sound comes from the frequency envelope applied\n * during MembraneSynth.triggerAttack(note). The frequency envelope\n * starts at <code>note * .octaves</code> and ramps to <code>note</code>\n * over the duration of <code>.pitchDecay</code>.\n * @example\n * const synth = new Tone.MembraneSynth().toDestination();\n * synth.triggerAttackRelease(\"C2\", \"8n\");\n * @category Instrument\n */\nexport class MembraneSynth extends Synth<MembraneSynthOptions> {\n\treadonly name: string = \"MembraneSynth\";\n\n\t/**\n\t * The number of octaves the pitch envelope ramps.\n\t * @min 0.5\n\t * @max 8\n\t */\n\t@range(0)\n\toctaves: Positive;\n\n\t/**\n\t * The amount of time the frequency envelope takes.\n\t * @min 0\n\t * @max 0.5\n\t */\n\t@timeRange(0)\n\tpitchDecay: Time;\n\n\t/**\n\t * Portamento is ignored in this synth. use pitch decay instead.\n\t */\n\treadonly portamento = 0;\n\n\t/**\n\t * @param options the options available for the synth see defaults\n\t */\n\tconstructor(options?: RecursivePartial<MembraneSynthOptions>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(\n\t\t\tMembraneSynth.getDefaults(),\n\t\t\targuments\n\t\t);\n\t\tsuper(options);\n\n\t\tthis.pitchDecay = options.pitchDecay;\n\t\tthis.octaves = options.octaves;\n\t\treadOnly(this, [\"oscillator\", \"envelope\"]);\n\t}\n\n\tstatic getDefaults(): MembraneSynthOptions {\n\t\treturn deepMerge(Monophonic.getDefaults(), Synth.getDefaults(), {\n\t\t\tenvelope: {\n\t\t\t\tattack: 0.001,\n\t\t\t\tattackCurve: \"exponential\",\n\t\t\t\tdecay: 0.4,\n\t\t\t\trelease: 1.4,\n\t\t\t\tsustain: 0.01,\n\t\t\t},\n\t\t\toctaves: 10,\n\t\t\toscillator: {\n\t\t\t\ttype: \"sine\",\n\t\t\t},\n\t\t\tpitchDecay: 0.05,\n\t\t});\n\t}\n\n\tsetNote(note: Frequency | FrequencyClass, time?: Time): this {\n\t\tconst seconds = this.toSeconds(time);\n\t\tconst hertz = this.toFrequency(\n\t\t\tnote instanceof FrequencyClass ? note.toFrequency() : note\n\t\t);\n\t\tconst maxNote = hertz * this.octaves;\n\t\tthis.oscillator.frequency.setValueAtTime(maxNote, seconds);\n\t\tthis.oscillator.frequency.exponentialRampToValueAtTime(\n\t\t\thertz,\n\t\t\tseconds + this.toSeconds(this.pitchDecay)\n\t\t);\n\t\treturn this;\n\t}\n\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\treturn this;\n\t}\n}\n","import { AmplitudeEnvelope } from \"../component/envelope/AmplitudeEnvelope.js\";\nimport { NormalRange, Time } from \"../core/type/Units.js\";\nimport { omitFromObject, optionsFromArguments } from \"../core/util/Defaults.js\";\nimport { RecursivePartial } from \"../core/util/Interface.js\";\nimport { Noise, NoiseOptions } from \"../source/Noise.js\";\nimport { Instrument, InstrumentOptions } from \"./Instrument.js\";\nimport {\n\tToneAudioNode,\n\tToneAudioNodeOptions,\n} from \"../core/context/ToneAudioNode.js\";\nimport { Envelope, EnvelopeOptions } from \"../component/envelope/Envelope.js\";\nimport { Source } from \"../source/Source.js\";\n\nexport interface NoiseSynthOptions extends InstrumentOptions {\n\tenvelope: Omit<EnvelopeOptions, keyof ToneAudioNodeOptions>;\n\tnoise: Omit<NoiseOptions, keyof ToneAudioNodeOptions>;\n}\n\n/**\n * Tone.NoiseSynth is composed of {@link Noise} through an {@link AmplitudeEnvelope}.\n * ```\n * +-------+ +-------------------+\n * | Noise +>--> AmplitudeEnvelope +>--> Output\n * +-------+ +-------------------+\n * ```\n * @example\n * const noiseSynth = new Tone.NoiseSynth().toDestination();\n * noiseSynth.triggerAttackRelease(\"8n\", 0.05);\n * @category Instrument\n */\nexport class NoiseSynth extends Instrument<NoiseSynthOptions> {\n\treadonly name = \"NoiseSynth\";\n\n\t/**\n\t * The noise source.\n\t */\n\treadonly noise: Noise;\n\n\t/**\n\t * The amplitude envelope.\n\t */\n\treadonly envelope: AmplitudeEnvelope;\n\n\tconstructor(options?: RecursivePartial<NoiseSynthOptions>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(\n\t\t\tNoiseSynth.getDefaults(),\n\t\t\targuments\n\t\t);\n\t\tsuper(options);\n\n\t\tthis.noise = new Noise(\n\t\t\tObject.assign(\n\t\t\t\t{\n\t\t\t\t\tcontext: this.context,\n\t\t\t\t},\n\t\t\t\toptions.noise\n\t\t\t)\n\t\t);\n\n\t\tthis.envelope = new AmplitudeEnvelope(\n\t\t\tObject.assign(\n\t\t\t\t{\n\t\t\t\t\tcontext: this.context,\n\t\t\t\t},\n\t\t\t\toptions.envelope\n\t\t\t)\n\t\t);\n\n\t\t// connect the noise to the output\n\t\tthis.noise.chain(this.envelope, this.output);\n\t}\n\n\tstatic getDefaults(): NoiseSynthOptions {\n\t\treturn Object.assign(Instrument.getDefaults(), {\n\t\t\tenvelope: Object.assign(\n\t\t\t\tomitFromObject(\n\t\t\t\t\tEnvelope.getDefaults(),\n\t\t\t\t\tObject.keys(ToneAudioNode.getDefaults())\n\t\t\t\t),\n\t\t\t\t{\n\t\t\t\t\tdecay: 0.1,\n\t\t\t\t\tsustain: 0.0,\n\t\t\t\t}\n\t\t\t),\n\t\t\tnoise: Object.assign(\n\t\t\t\tomitFromObject(\n\t\t\t\t\tNoise.getDefaults(),\n\t\t\t\t\tObject.keys(Source.getDefaults())\n\t\t\t\t),\n\t\t\t\t{\n\t\t\t\t\ttype: \"white\",\n\t\t\t\t}\n\t\t\t),\n\t\t});\n\t}\n\n\t/**\n\t * Start the attack portion of the envelopes. Unlike other\n\t * instruments, Tone.NoiseSynth doesn't have a note.\n\t * @example\n\t * const noiseSynth = new Tone.NoiseSynth().toDestination();\n\t * noiseSynth.triggerAttack();\n\t */\n\ttriggerAttack(time?: Time, velocity: NormalRange = 1): this {\n\t\ttime = this.toSeconds(time);\n\t\t// the envelopes\n\t\tthis.envelope.triggerAttack(time, velocity);\n\t\t// start the noise\n\t\tthis.noise.start(time);\n\t\tif (this.envelope.sustain === 0) {\n\t\t\tthis.noise.stop(\n\t\t\t\ttime +\n\t\t\t\t\tthis.toSeconds(this.envelope.attack) +\n\t\t\t\t\tthis.toSeconds(this.envelope.decay)\n\t\t\t);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Start the release portion of the envelopes.\n\t */\n\ttriggerRelease(time?: Time): this {\n\t\ttime = this.toSeconds(time);\n\t\tthis.envelope.triggerRelease(time);\n\t\tthis.noise.stop(time + this.toSeconds(this.envelope.release));\n\t\treturn this;\n\t}\n\n\tsync(): this {\n\t\tif (this._syncState()) {\n\t\t\tthis._syncMethod(\"triggerAttack\", 0);\n\t\t\tthis._syncMethod(\"triggerRelease\", 0);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Trigger the attack and then the release after the duration.\n\t * @param duration The amount of time to hold the note for\n\t * @param time The time the note should start\n\t * @param velocity The volume of the note (0-1)\n\t * @example\n\t * const noiseSynth = new Tone.NoiseSynth().toDestination();\n\t * // hold the note for 0.5 seconds\n\t * noiseSynth.triggerAttackRelease(0.5);\n\t */\n\ttriggerAttackRelease(\n\t\tduration: Time,\n\t\ttime?: Time,\n\t\tvelocity: NormalRange = 1\n\t): this {\n\t\ttime = this.toSeconds(time);\n\t\tduration = this.toSeconds(duration);\n\t\tthis.triggerAttack(time, velocity);\n\t\tthis.triggerRelease(time + duration);\n\t\treturn this;\n\t}\n\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis.noise.dispose();\n\t\tthis.envelope.dispose();\n\t\treturn this;\n\t}\n}\n","/**\n * All of the classes or functions which are loaded into the AudioWorkletGlobalScope\n */\nconst workletContext: Set<string> = new Set();\n\n/**\n * Add a class to the AudioWorkletGlobalScope\n */\nexport function addToWorklet(classOrFunction: string) {\n\tworkletContext.add(classOrFunction);\n}\n\n/**\n * Register a processor in the AudioWorkletGlobalScope with the given name\n */\nexport function registerProcessor(name: string, classDesc: string) {\n\tconst processor = /* javascript */ `registerProcessor(\"${name}\", ${classDesc})`;\n\tworkletContext.add(processor);\n}\n\n/**\n * Get all of the modules which have been registered to the AudioWorkletGlobalScope\n */\nexport function getWorkletGlobalScope(): string {\n\treturn Array.from(workletContext).join(\"\\n\");\n}\n","import {\n\tToneAudioNode,\n\tToneAudioNodeOptions,\n} from \"../context/ToneAudioNode.js\";\nimport { noOp } from \"../util/Interface.js\";\nimport { getWorkletGlobalScope } from \"./WorkletGlobalScope.js\";\n\nexport type ToneAudioWorkletOptions = ToneAudioNodeOptions;\n\nexport abstract class ToneAudioWorklet<\n\tOptions extends ToneAudioWorkletOptions,\n> extends ToneAudioNode<Options> {\n\treadonly name: string = \"ToneAudioWorklet\";\n\n\t/**\n\t * The processing node\n\t */\n\tprotected _worklet!: AudioWorkletNode;\n\n\t/**\n\t * A dummy gain node to create a dummy audio param from\n\t */\n\tprivate _dummyGain: GainNode;\n\n\t/**\n\t * A dummy audio param to use when creating Params\n\t */\n\tprotected _dummyParam: AudioParam;\n\n\t/**\n\t * The constructor options for the node\n\t */\n\tprotected workletOptions: Partial<AudioWorkletNodeOptions> = {};\n\n\t/**\n\t * Get the name of the audio worklet\n\t */\n\tprotected abstract _audioWorkletName(): string;\n\n\t/**\n\t * Invoked when the module is loaded and the node is created\n\t */\n\tprotected abstract onReady(node: AudioWorkletNode): void;\n\n\t/**\n\t * Callback which is invoked when there is an error in the processing\n\t */\n\tonprocessorerror: (e: string) => void = noOp;\n\n\tconstructor(options: Options) {\n\t\tsuper(options);\n\n\t\tconst blobUrl = URL.createObjectURL(\n\t\t\tnew Blob([getWorkletGlobalScope()], { type: \"text/javascript\" })\n\t\t);\n\t\tconst name = this._audioWorkletName();\n\n\t\tthis._dummyGain = this.context.createGain();\n\t\tthis._dummyParam = this._dummyGain.gain;\n\n\t\t// Register the processor\n\t\tthis.context.addAudioWorkletModule(blobUrl).then(() => {\n\t\t\t// create the worklet when it's read\n\t\t\tif (!this.disposed) {\n\t\t\t\tthis._worklet = this.context.createAudioWorkletNode(\n\t\t\t\t\tname,\n\t\t\t\t\tthis.workletOptions\n\t\t\t\t);\n\t\t\t\tthis._worklet.onprocessorerror =\n\t\t\t\t\tthis.onprocessorerror.bind(this);\n\t\t\t\tthis.onReady(this._worklet);\n\t\t\t}\n\t\t});\n\t}\n\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis._dummyGain.disconnect();\n\t\tif (this._worklet) {\n\t\t\tthis._worklet.port.postMessage(\"dispose\");\n\t\t\tthis._worklet.disconnect();\n\t\t}\n\t\treturn this;\n\t}\n}\n","import { addToWorklet } from \"./WorkletGlobalScope.js\";\n\nconst toneAudioWorkletProcessor = /* javascript */ `\n\t/**\n\t * The base AudioWorkletProcessor for use in Tone.js. Works with the {@link ToneAudioWorklet}. \n\t */\n\tclass ToneAudioWorkletProcessor extends AudioWorkletProcessor {\n\n\t\tconstructor(options) {\n\t\t\t\n\t\t\tsuper(options);\n\t\t\t/**\n\t\t\t * If the processor was disposed or not. Keep alive until it's disposed.\n\t\t\t */\n\t\t\tthis.disposed = false;\n\t\t \t/** \n\t\t\t * The number of samples in the processing block\n\t\t\t */\n\t\t\tthis.blockSize = 128;\n\t\t\t/**\n\t\t\t * the sample rate\n\t\t\t */\n\t\t\tthis.sampleRate = sampleRate;\n\n\t\t\tthis.port.onmessage = (event) => {\n\t\t\t\t// when it receives a dispose \n\t\t\t\tif (event.data === \"dispose\") {\n\t\t\t\t\tthis.disposed = true;\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t}\n`;\n\naddToWorklet(toneAudioWorkletProcessor);\n","import \"./ToneAudioWorkletProcessor.worklet.js\";\nimport { addToWorklet } from \"./WorkletGlobalScope.js\";\n\nexport const singleIOProcess = /* javascript */ `\n\t/**\n\t * Abstract class for a single input/output processor. \n\t * has a 'generate' function which processes one sample at a time\n\t */\n\tclass SingleIOProcessor extends ToneAudioWorkletProcessor {\n\n\t\tconstructor(options) {\n\t\t\tsuper(Object.assign(options, {\n\t\t\t\tnumberOfInputs: 1,\n\t\t\t\tnumberOfOutputs: 1\n\t\t\t}));\n\t\t\t/**\n\t\t\t * Holds the name of the parameter and a single value of that\n\t\t\t * parameter at the current sample\n\t\t\t * @type { [name: string]: number }\n\t\t\t */\n\t\t\tthis.params = {}\n\t\t}\n\n\t\t/**\n\t\t * Generate an output sample from the input sample and parameters\n\t\t * @abstract\n\t\t * @param input number\n\t\t * @param channel number\n\t\t * @param parameters { [name: string]: number }\n\t\t * @returns number\n\t\t */\n\t\tgenerate(){}\n\n\t\t/**\n\t\t * Update the private params object with the \n\t\t * values of the parameters at the given index\n\t\t * @param parameters { [name: string]: Float32Array },\n\t\t * @param index number\n\t\t */\n\t\tupdateParams(parameters, index) {\n\t\t\tfor (const paramName in parameters) {\n\t\t\t\tconst param = parameters[paramName];\n\t\t\t\tif (param.length > 1) {\n\t\t\t\t\tthis.params[paramName] = parameters[paramName][index];\n\t\t\t\t} else {\n\t\t\t\t\tthis.params[paramName] = parameters[paramName][0];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Process a single frame of the audio\n\t\t * @param inputs Float32Array[][]\n\t\t * @param outputs Float32Array[][]\n\t\t */\n\t\tprocess(inputs, outputs, parameters) {\n\t\t\tconst input = inputs[0];\n\t\t\tconst output = outputs[0];\n\t\t\t// get the parameter values\n\t\t\tconst channelCount = Math.max(input && input.length || 0, output.length);\n\t\t\tfor (let sample = 0; sample < this.blockSize; sample++) {\n\t\t\t\tthis.updateParams(parameters, sample);\n\t\t\t\tfor (let channel = 0; channel < channelCount; channel++) {\n\t\t\t\t\tconst inputSample = input && input.length ? input[channel][sample] : 0;\n\t\t\t\t\toutput[channel][sample] = this.generate(inputSample, channel, this.params);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn !this.disposed;\n\t\t}\n\t};\n`;\n\naddToWorklet(singleIOProcess);\n","import { addToWorklet } from \"./WorkletGlobalScope.js\";\n\nconst delayLine = /* javascript */ `\n\t/**\n\t * A multichannel buffer for use within an AudioWorkletProcessor as a delay line\n\t */\n\tclass DelayLine {\n\t\t\n\t\tconstructor(size, channels) {\n\t\t\tthis.buffer = [];\n\t\t\tthis.writeHead = []\n\t\t\tthis.size = size;\n\n\t\t\t// create the empty channels\n\t\t\tfor (let i = 0; i < channels; i++) {\n\t\t\t\tthis.buffer[i] = new Float32Array(this.size);\n\t\t\t\tthis.writeHead[i] = 0;\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Push a value onto the end\n\t\t * @param channel number\n\t\t * @param value number\n\t\t */\n\t\tpush(channel, value) {\n\t\t\tthis.writeHead[channel] += 1;\n\t\t\tif (this.writeHead[channel] > this.size) {\n\t\t\t\tthis.writeHead[channel] = 0;\n\t\t\t}\n\t\t\tthis.buffer[channel][this.writeHead[channel]] = value;\n\t\t}\n\n\t\t/**\n\t\t * Get the recorded value of the channel given the delay\n\t\t * @param channel number\n\t\t * @param delay number delay samples\n\t\t */\n\t\tget(channel, delay) {\n\t\t\tlet readHead = this.writeHead[channel] - Math.floor(delay);\n\t\t\tif (readHead < 0) {\n\t\t\t\treadHead += this.size;\n\t\t\t}\n\t\t\treturn this.buffer[channel][readHead];\n\t\t}\n\t}\n`;\n\naddToWorklet(delayLine);\n","import \"../../core/worklet/SingleIOProcessor.worklet.js\";\nimport \"../../core/worklet/DelayLine.worklet.js\";\nimport { registerProcessor } from \"../../core/worklet/WorkletGlobalScope.js\";\n\nexport const workletName = \"feedback-comb-filter\";\n\nconst feedbackCombFilter = /* javascript */ `\n\tclass FeedbackCombFilterWorklet extends SingleIOProcessor {\n\n\t\tconstructor(options) {\n\t\t\tsuper(options);\n\t\t\tthis.delayLine = new DelayLine(this.sampleRate, options.channelCount || 2);\n\t\t}\n\n\t\tstatic get parameterDescriptors() {\n\t\t\treturn [{\n\t\t\t\tname: \"delayTime\",\n\t\t\t\tdefaultValue: 0.1,\n\t\t\t\tminValue: 0,\n\t\t\t\tmaxValue: 1,\n\t\t\t\tautomationRate: \"k-rate\"\n\t\t\t}, {\n\t\t\t\tname: \"feedback\",\n\t\t\t\tdefaultValue: 0.5,\n\t\t\t\tminValue: 0,\n\t\t\t\tmaxValue: 0.9999,\n\t\t\t\tautomationRate: \"k-rate\"\n\t\t\t}];\n\t\t}\n\n\t\tgenerate(input, channel, parameters) {\n\t\t\tconst delayedSample = this.delayLine.get(channel, parameters.delayTime * this.sampleRate);\n\t\t\tthis.delayLine.push(channel, input + delayedSample * parameters.feedback);\n\t\t\treturn delayedSample;\n\t\t}\n\t}\n`;\n\nregisterProcessor(workletName, feedbackCombFilter);\n","import { Gain } from \"../../core/context/Gain.js\";\nimport { Param } from \"../../core/context/Param.js\";\nimport {\n\tconnectSeries,\n\tToneAudioNode,\n\tToneAudioNodeOptions,\n} from \"../../core/context/ToneAudioNode.js\";\nimport { NormalRange, Time } from \"../../core/type/Units.js\";\nimport { optionsFromArguments } from \"../../core/util/Defaults.js\";\nimport { readOnly, RecursivePartial } from \"../../core/util/Interface.js\";\nimport { ToneAudioWorklet } from \"../../core/worklet/ToneAudioWorklet.js\";\nimport { workletName } from \"./FeedbackCombFilter.worklet.js\";\n\nexport interface FeedbackCombFilterOptions extends ToneAudioNodeOptions {\n\tdelayTime: Time;\n\tresonance: NormalRange;\n}\n\n/**\n * Comb filters are basic building blocks for physical modeling. Read more\n * about comb filters on [CCRMA's website](https://ccrma.stanford.edu/~jos/pasp/Feedback_Comb_Filters.html).\n *\n * This comb filter is implemented with the AudioWorkletNode which allows it to have feedback delays less than the\n * Web Audio processing block of 128 samples. There is a polyfill for browsers that don't yet support the\n * AudioWorkletNode, but it will add some latency and have slower performance than the AudioWorkletNode.\n * @category Component\n */\nexport class FeedbackCombFilter extends ToneAudioWorklet<FeedbackCombFilterOptions> {\n\treadonly name = \"FeedbackCombFilter\";\n\n\t/**\n\t * The amount of delay of the comb filter.\n\t */\n\treadonly delayTime: Param<\"time\">;\n\n\t/**\n\t * The amount of feedback of the delayed signal.\n\t */\n\treadonly resonance: Param<\"normalRange\">;\n\n\treadonly input: Gain;\n\treadonly output: Gain;\n\n\t/**\n\t * @param delayTime The delay time of the filter.\n\t * @param resonance The amount of feedback the filter has.\n\t */\n\tconstructor(delayTime?: Time, resonance?: NormalRange);\n\tconstructor(options?: RecursivePartial<FeedbackCombFilterOptions>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(\n\t\t\tFeedbackCombFilter.getDefaults(),\n\t\t\targuments,\n\t\t\t[\"delayTime\", \"resonance\"]\n\t\t);\n\t\tsuper(options);\n\n\t\tthis.input = new Gain({ context: this.context });\n\t\tthis.output = new Gain({ context: this.context });\n\n\t\tthis.delayTime = new Param<\"time\">({\n\t\t\tcontext: this.context,\n\t\t\tvalue: options.delayTime,\n\t\t\tunits: \"time\",\n\t\t\tminValue: 0,\n\t\t\tmaxValue: 1,\n\t\t\tparam: this._dummyParam,\n\t\t\tswappable: true,\n\t\t});\n\n\t\tthis.resonance = new Param<\"normalRange\">({\n\t\t\tcontext: this.context,\n\t\t\tvalue: options.resonance,\n\t\t\tunits: \"normalRange\",\n\t\t\tparam: this._dummyParam,\n\t\t\tswappable: true,\n\t\t});\n\n\t\treadOnly(this, [\"resonance\", \"delayTime\"]);\n\t}\n\n\tprotected _audioWorkletName(): string {\n\t\treturn workletName;\n\t}\n\n\t/**\n\t * The default parameters\n\t */\n\tstatic getDefaults(): FeedbackCombFilterOptions {\n\t\treturn Object.assign(ToneAudioNode.getDefaults(), {\n\t\t\tdelayTime: 0.1,\n\t\t\tresonance: 0.5,\n\t\t});\n\t}\n\n\tonReady(node: AudioWorkletNode) {\n\t\tconnectSeries(this.input, node, this.output);\n\t\tconst delayTime = node.parameters.get(\"delayTime\") as AudioParam;\n\t\tthis.delayTime.setParam(delayTime);\n\t\tconst feedback = node.parameters.get(\"feedback\") as AudioParam;\n\t\tthis.resonance.setParam(feedback);\n\t}\n\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis.input.dispose();\n\t\tthis.output.dispose();\n\t\tthis.delayTime.dispose();\n\t\tthis.resonance.dispose();\n\t\treturn this;\n\t}\n}\n","import {\n\tToneAudioNode,\n\tToneAudioNodeOptions,\n} from \"../../core/context/ToneAudioNode.js\";\nimport { Frequency } from \"../../core/type/Units.js\";\nimport { optionsFromArguments } from \"../../core/util/Defaults.js\";\nimport { Gain } from \"../../core/context/Gain.js\";\n\nexport type OnePoleFilterType = \"highpass\" | \"lowpass\";\n\nexport interface OnePoleFilterOptions extends ToneAudioNodeOptions {\n\tfrequency: Frequency;\n\ttype: OnePoleFilterType;\n}\n\n/**\n * A one pole filter with 6db-per-octave rolloff. Either \"highpass\" or \"lowpass\".\n * Note that changing the type or frequency may result in a discontinuity which\n * can sound like a click or pop.\n * References:\n * * http://www.earlevel.com/main/2012/12/15/a-one-pole-filter/\n * * http://www.dspguide.com/ch19/2.htm\n * * https://github.com/vitaliy-bobrov/js-rocks/blob/master/src/app/audio/effects/one-pole-filters.ts\n * @category Component\n */\nexport class OnePoleFilter extends ToneAudioNode<OnePoleFilterOptions> {\n\treadonly name: string = \"OnePoleFilter\";\n\n\t/**\n\t * Hold the current frequency\n\t */\n\tprivate _frequency: Frequency;\n\n\t/**\n\t * the current one pole type\n\t */\n\tprivate _type: OnePoleFilterType;\n\n\t/**\n\t * the current one pole filter\n\t */\n\tprivate _filter!: IIRFilterNode;\n\n\treadonly input: Gain;\n\treadonly output: Gain;\n\n\t/**\n\t * @param frequency The frequency\n\t * @param type The filter type, either \"lowpass\" or \"highpass\"\n\t */\n\tconstructor(frequency?: Frequency, type?: OnePoleFilterType);\n\tconstructor(options?: Partial<OnePoleFilterOptions>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(\n\t\t\tOnePoleFilter.getDefaults(),\n\t\t\targuments,\n\t\t\t[\"frequency\", \"type\"]\n\t\t);\n\t\tsuper(options);\n\n\t\tthis._frequency = options.frequency;\n\t\tthis._type = options.type;\n\t\tthis.input = new Gain({ context: this.context });\n\t\tthis.output = new Gain({ context: this.context });\n\t\tthis._createFilter();\n\t}\n\n\tstatic getDefaults(): OnePoleFilterOptions {\n\t\treturn Object.assign(ToneAudioNode.getDefaults(), {\n\t\t\tfrequency: 880,\n\t\t\ttype: \"lowpass\" as OnePoleFilterType,\n\t\t});\n\t}\n\n\t/**\n\t * Create a filter and dispose the old one\n\t */\n\tprivate _createFilter() {\n\t\tconst oldFilter = this._filter;\n\t\tconst freq = this.toFrequency(this._frequency);\n\t\tconst t = 1 / (2 * Math.PI * freq);\n\t\tif (this._type === \"lowpass\") {\n\t\t\tconst a0 = 1 / (t * this.context.sampleRate);\n\t\t\tconst b1 = a0 - 1;\n\t\t\tthis._filter = this.context.createIIRFilter([a0, 0], [1, b1]);\n\t\t} else {\n\t\t\tconst b1 = 1 / (t * this.context.sampleRate) - 1;\n\t\t\tthis._filter = this.context.createIIRFilter([1, -1], [1, b1]);\n\t\t}\n\n\t\tthis.input.chain(this._filter, this.output);\n\t\tif (oldFilter) {\n\t\t\t// dispose it on the next block\n\t\t\tthis.context.setTimeout(() => {\n\t\t\t\tif (!this.disposed) {\n\t\t\t\t\tthis.input.disconnect(oldFilter);\n\t\t\t\t\toldFilter.disconnect();\n\t\t\t\t}\n\t\t\t}, this.blockTime);\n\t\t}\n\t}\n\n\t/**\n\t * The frequency value.\n\t */\n\tget frequency(): Frequency {\n\t\treturn this._frequency;\n\t}\n\tset frequency(fq) {\n\t\tthis._frequency = fq;\n\t\tthis._createFilter();\n\t}\n\n\t/**\n\t * The OnePole Filter type, either \"highpass\" or \"lowpass\"\n\t */\n\tget type(): OnePoleFilterType {\n\t\treturn this._type;\n\t}\n\tset type(t) {\n\t\tthis._type = t;\n\t\tthis._createFilter();\n\t}\n\n\t/**\n\t * Get the frequency response curve. This curve represents how the filter\n\t * responses to frequencies between 20hz-20khz.\n\t * @param len The number of values to return\n\t * @return The frequency response curve between 20-20kHz\n\t */\n\tgetFrequencyResponse(len = 128): Float32Array {\n\t\tconst freqValues = new Float32Array(len);\n\t\tfor (let i = 0; i < len; i++) {\n\t\t\tconst norm = Math.pow(i / len, 2);\n\t\t\tconst freq = norm * (20000 - 20) + 20;\n\t\t\tfreqValues[i] = freq;\n\t\t}\n\t\tconst magValues = new Float32Array(len);\n\t\tconst phaseValues = new Float32Array(len);\n\t\tthis._filter.getFrequencyResponse(freqValues, magValues, phaseValues);\n\t\treturn magValues;\n\t}\n\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis.input.dispose();\n\t\tthis.output.dispose();\n\t\tthis._filter.disconnect();\n\t\treturn this;\n\t}\n}\n","import { Param } from \"../../core/context/Param.js\";\nimport {\n\tInputNode,\n\tOutputNode,\n\tToneAudioNode,\n\tToneAudioNodeOptions,\n} from \"../../core/context/ToneAudioNode.js\";\nimport { Frequency, NormalRange, Time } from \"../../core/type/Units.js\";\nimport { optionsFromArguments } from \"../../core/util/Defaults.js\";\nimport { RecursivePartial } from \"../../core/util/Interface.js\";\nimport { FeedbackCombFilter } from \"./FeedbackCombFilter.js\";\nimport { OnePoleFilter } from \"./OnePoleFilter.js\";\n\ninterface LowpassCombFilterOptions extends ToneAudioNodeOptions {\n\tdelayTime: Time;\n\tresonance: NormalRange;\n\tdampening: Frequency;\n}\n\n/**\n * A lowpass feedback comb filter. It is similar to\n * {@link FeedbackCombFilter}, but includes a lowpass filter.\n * @category Component\n */\nexport class LowpassCombFilter extends ToneAudioNode<LowpassCombFilterOptions> {\n\treadonly name = \"LowpassCombFilter\";\n\n\t/**\n\t * The delay node\n\t */\n\tprivate _combFilter: FeedbackCombFilter;\n\n\t/**\n\t * The lowpass filter\n\t */\n\tprivate _lowpass: OnePoleFilter;\n\n\t/**\n\t * The delayTime of the comb filter.\n\t */\n\treadonly delayTime: Param<\"time\">;\n\n\t/**\n\t * The amount of feedback of the delayed signal.\n\t */\n\treadonly resonance: Param<\"normalRange\">;\n\n\treadonly input: InputNode;\n\treadonly output: OutputNode;\n\n\t/**\n\t * @param delayTime The delay time of the comb filter\n\t * @param resonance The resonance (feedback) of the comb filter\n\t * @param dampening The cutoff of the lowpass filter dampens the signal as it is fedback.\n\t */\n\tconstructor(\n\t\tdelayTime?: Time,\n\t\tresonance?: NormalRange,\n\t\tdampening?: Frequency\n\t);\n\tconstructor(options?: RecursivePartial<LowpassCombFilterOptions>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(\n\t\t\tLowpassCombFilter.getDefaults(),\n\t\t\targuments,\n\t\t\t[\"delayTime\", \"resonance\", \"dampening\"]\n\t\t);\n\t\tsuper(options);\n\n\t\tthis._combFilter = this.output = new FeedbackCombFilter({\n\t\t\tcontext: this.context,\n\t\t\tdelayTime: options.delayTime,\n\t\t\tresonance: options.resonance,\n\t\t});\n\t\tthis.delayTime = this._combFilter.delayTime;\n\t\tthis.resonance = this._combFilter.resonance;\n\n\t\tthis._lowpass = this.input = new OnePoleFilter({\n\t\t\tcontext: this.context,\n\t\t\tfrequency: options.dampening,\n\t\t\ttype: \"lowpass\",\n\t\t});\n\n\t\t// connections\n\t\tthis._lowpass.connect(this._combFilter);\n\t}\n\n\tstatic getDefaults(): LowpassCombFilterOptions {\n\t\treturn Object.assign(ToneAudioNode.getDefaults(), {\n\t\t\tdampening: 3000,\n\t\t\tdelayTime: 0.1,\n\t\t\tresonance: 0.5,\n\t\t});\n\t}\n\n\t/**\n\t * The dampening control of the feedback\n\t */\n\tget dampening(): Frequency {\n\t\treturn this._lowpass.frequency;\n\t}\n\tset dampening(fq) {\n\t\tthis._lowpass.frequency = fq;\n\t}\n\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis._combFilter.dispose();\n\t\tthis._lowpass.dispose();\n\t\treturn this;\n\t}\n}\n","import { Frequency, NormalRange, Time } from \"../core/type/Units.js\";\nimport { LowpassCombFilter } from \"../component/filter/LowpassCombFilter.js\";\nimport { deepMerge } from \"../core/util/Defaults.js\";\nimport { optionsFromArguments } from \"../core/util/Defaults.js\";\nimport { RecursivePartial } from \"../core/util/Interface.js\";\nimport { Noise } from \"../source/Noise.js\";\nimport { Instrument, InstrumentOptions } from \"./Instrument.js\";\n\nexport interface PluckSynthOptions extends InstrumentOptions {\n\tattackNoise: number;\n\tdampening: Frequency;\n\tresonance: NormalRange;\n\trelease: Time;\n}\n\n/**\n * Karplus-Strong string synthesis.\n * @example\n * const plucky = new Tone.PluckSynth().toDestination();\n * plucky.triggerAttack(\"C4\", \"+0.5\");\n * plucky.triggerAttack(\"C3\", \"+1\");\n * plucky.triggerAttack(\"C2\", \"+1.5\");\n * plucky.triggerAttack(\"C1\", \"+2\");\n * @category Instrument\n */\nexport class PluckSynth extends Instrument<PluckSynthOptions> {\n\treadonly name = \"PluckSynth\";\n\n\t/**\n\t * Noise burst at the beginning\n\t */\n\tprivate _noise: Noise;\n\tprivate _lfcf: LowpassCombFilter;\n\n\t/**\n\t * The amount of noise at the attack.\n\t * Nominal range of [0.1, 20]\n\t * @min 0.1\n\t * @max 20\n\t */\n\tattackNoise: number;\n\n\t/**\n\t * The amount of resonance of the pluck. Also correlates to the sustain duration.\n\t */\n\tresonance: NormalRange;\n\n\t/**\n\t * The release time which corresponds to a resonance ramp down to 0\n\t */\n\trelease: Time;\n\n\tconstructor(options?: RecursivePartial<PluckSynthOptions>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(\n\t\t\tPluckSynth.getDefaults(),\n\t\t\targuments\n\t\t);\n\t\tsuper(options);\n\n\t\tthis._noise = new Noise({\n\t\t\tcontext: this.context,\n\t\t\ttype: \"pink\",\n\t\t});\n\n\t\tthis.attackNoise = options.attackNoise;\n\n\t\tthis._lfcf = new LowpassCombFilter({\n\t\t\tcontext: this.context,\n\t\t\tdampening: options.dampening,\n\t\t\tresonance: options.resonance,\n\t\t});\n\n\t\tthis.resonance = options.resonance;\n\t\tthis.release = options.release;\n\n\t\tthis._noise.connect(this._lfcf);\n\t\tthis._lfcf.connect(this.output);\n\t}\n\n\tstatic getDefaults(): PluckSynthOptions {\n\t\treturn deepMerge(Instrument.getDefaults(), {\n\t\t\tattackNoise: 1,\n\t\t\tdampening: 4000,\n\t\t\tresonance: 0.7,\n\t\t\trelease: 1,\n\t\t});\n\t}\n\n\t/**\n\t * The dampening control. i.e. the lowpass filter frequency of the comb filter\n\t * @min 0\n\t * @max 7000\n\t */\n\tget dampening(): Frequency {\n\t\treturn this._lfcf.dampening;\n\t}\n\tset dampening(fq) {\n\t\tthis._lfcf.dampening = fq;\n\t}\n\n\ttriggerAttack(note: Frequency, time?: Time): this {\n\t\tconst freq = this.toFrequency(note);\n\t\ttime = this.toSeconds(time);\n\t\tconst delayAmount = 1 / freq;\n\t\tthis._lfcf.delayTime.setValueAtTime(delayAmount, time);\n\t\tthis._noise.start(time);\n\t\tthis._noise.stop(time + delayAmount * this.attackNoise);\n\t\tthis._lfcf.resonance.cancelScheduledValues(time);\n\t\tthis._lfcf.resonance.setValueAtTime(this.resonance, time);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Ramp down the {@link resonance} to 0 over the duration of the release time.\n\t */\n\ttriggerRelease(time?: Time): this {\n\t\tthis._lfcf.resonance.linearRampTo(0, this.release, time);\n\t\treturn this;\n\t}\n\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis._noise.dispose();\n\t\tthis._lfcf.dispose();\n\t\treturn this;\n\t}\n}\n","import { ToneAudioBuffer } from \"../core/context/ToneAudioBuffer.js\";\nimport { ToneAudioBuffers } from \"../core/context/ToneAudioBuffers.js\";\nimport { ftomf, intervalToFrequencyRatio } from \"../core/type/Conversions.js\";\nimport { FrequencyClass } from \"../core/type/Frequency.js\";\nimport {\n\tFrequency,\n\tInterval,\n\tMidiNote,\n\tNormalRange,\n\tNote,\n\tTime,\n} from \"../core/type/Units.js\";\nimport { optionsFromArguments } from \"../core/util/Defaults.js\";\nimport { noOp } from \"../core/util/Interface.js\";\nimport { isArray, isNote, isNumber } from \"../core/util/TypeCheck.js\";\nimport { Instrument, InstrumentOptions } from \"../instrument/Instrument.js\";\nimport {\n\tToneBufferSource,\n\tToneBufferSourceCurve,\n} from \"../source/buffer/ToneBufferSource.js\";\nimport { timeRange } from \"../core/util/Decorator.js\";\nimport { assert } from \"../core/util/Debug.js\";\n\ninterface SamplesMap {\n\t[note: string]: ToneAudioBuffer | AudioBuffer | string;\n\t[midi: number]: ToneAudioBuffer | AudioBuffer | string;\n}\n\nexport interface SamplerOptions extends InstrumentOptions {\n\tattack: Time;\n\trelease: Time;\n\tonload: () => void;\n\tonerror: (error: Error) => void;\n\tbaseUrl: string;\n\tcurve: ToneBufferSourceCurve;\n\turls: SamplesMap;\n}\n\n/**\n * Pass in an object which maps the note's pitch or midi value to the url,\n * then you can trigger the attack and release of that note like other instruments.\n * By automatically repitching the samples, it is possible to play pitches which\n * were not explicitly included which can save loading time.\n *\n * For sample or buffer playback where repitching is not necessary,\n * use {@link Player}.\n * @example\n * const sampler = new Tone.Sampler({\n * \turls: {\n * \t\tA1: \"A1.mp3\",\n * \t\tA2: \"A2.mp3\",\n * \t},\n * \tbaseUrl: \"https://tonejs.github.io/audio/casio/\",\n * \tonload: () => {\n * \t\tsampler.triggerAttackRelease([\"C1\", \"E1\", \"G1\", \"B1\"], 0.5);\n * \t}\n * }).toDestination();\n * @category Instrument\n */\nexport class Sampler extends Instrument<SamplerOptions> {\n\treadonly name: string = \"Sampler\";\n\n\t/**\n\t * The stored and loaded buffers\n\t */\n\tprivate _buffers: ToneAudioBuffers;\n\n\t/**\n\t * The object of all currently playing BufferSources\n\t */\n\tprivate _activeSources: Map<MidiNote, ToneBufferSource[]> = new Map();\n\n\t/**\n\t * The envelope applied to the beginning of the sample.\n\t * @min 0\n\t * @max 1\n\t */\n\t@timeRange(0)\n\tattack: Time;\n\n\t/**\n\t * The envelope applied to the end of the envelope.\n\t * @min 0\n\t * @max 1\n\t */\n\t@timeRange(0)\n\trelease: Time;\n\n\t/**\n\t * The shape of the attack/release curve.\n\t * Either \"linear\" or \"exponential\"\n\t */\n\tcurve: ToneBufferSourceCurve;\n\n\t/**\n\t * @param samples An object of samples mapping either Midi Note Numbers or\n\t * \t\t\tScientific Pitch Notation to the url of that sample.\n\t * @param onload The callback to invoke when all of the samples are loaded.\n\t * @param baseUrl The root URL of all of the samples, which is prepended to all the URLs.\n\t */\n\tconstructor(samples?: SamplesMap, onload?: () => void, baseUrl?: string);\n\t/**\n\t * @param samples An object of samples mapping either Midi Note Numbers or\n\t * \t\t\tScientific Pitch Notation to the url of that sample.\n\t * @param options The remaining options associated with the sampler\n\t */\n\tconstructor(\n\t\tsamples?: SamplesMap,\n\t\toptions?: Partial<Omit<SamplerOptions, \"urls\">>\n\t);\n\tconstructor(options?: Partial<SamplerOptions>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(\n\t\t\tSampler.getDefaults(),\n\t\t\targuments,\n\t\t\t[\"urls\", \"onload\", \"baseUrl\"],\n\t\t\t\"urls\"\n\t\t);\n\t\tsuper(options);\n\n\t\tconst urlMap = {};\n\t\tObject.keys(options.urls).forEach((note) => {\n\t\t\tconst noteNumber = parseInt(note, 10);\n\t\t\tassert(\n\t\t\t\tisNote(note) || (isNumber(noteNumber) && isFinite(noteNumber)),\n\t\t\t\t`url key is neither a note or midi pitch: ${note}`\n\t\t\t);\n\t\t\tif (isNote(note)) {\n\t\t\t\t// convert the note name to MIDI\n\t\t\t\tconst mid = new FrequencyClass(this.context, note).toMidi();\n\t\t\t\turlMap[mid] = options.urls[note];\n\t\t\t} else if (isNumber(noteNumber) && isFinite(noteNumber)) {\n\t\t\t\t// otherwise if it's numbers assume it's midi\n\t\t\t\turlMap[noteNumber] = options.urls[noteNumber];\n\t\t\t}\n\t\t});\n\n\t\tthis._buffers = new ToneAudioBuffers({\n\t\t\turls: urlMap,\n\t\t\tonload: options.onload,\n\t\t\tbaseUrl: options.baseUrl,\n\t\t\tonerror: options.onerror,\n\t\t});\n\t\tthis.attack = options.attack;\n\t\tthis.release = options.release;\n\t\tthis.curve = options.curve;\n\n\t\t// invoke the callback if it's already loaded\n\t\tif (this._buffers.loaded) {\n\t\t\t// invoke onload deferred\n\t\t\tPromise.resolve().then(options.onload);\n\t\t}\n\t}\n\n\tstatic getDefaults(): SamplerOptions {\n\t\treturn Object.assign(Instrument.getDefaults(), {\n\t\t\tattack: 0,\n\t\t\tbaseUrl: \"\",\n\t\t\tcurve: \"exponential\" as const,\n\t\t\tonload: noOp,\n\t\t\tonerror: noOp,\n\t\t\trelease: 0.1,\n\t\t\turls: {},\n\t\t});\n\t}\n\n\t/**\n\t * Returns the difference in steps between the given midi note at the closets sample.\n\t */\n\tprivate _findClosest(midi: MidiNote): Interval {\n\t\t// searches within 8 octaves of the given midi note\n\t\tconst MAX_INTERVAL = 96;\n\t\tlet interval = 0;\n\t\twhile (interval < MAX_INTERVAL) {\n\t\t\t// check above and below\n\t\t\tif (this._buffers.has(midi + interval)) {\n\t\t\t\treturn -interval;\n\t\t\t} else if (this._buffers.has(midi - interval)) {\n\t\t\t\treturn interval;\n\t\t\t}\n\t\t\tinterval++;\n\t\t}\n\t\tthrow new Error(`No available buffers for note: ${midi}`);\n\t}\n\n\t/**\n\t * @param notes\tThe note to play, or an array of notes.\n\t * @param time When to play the note\n\t * @param velocity The velocity to play the sample back.\n\t */\n\ttriggerAttack(\n\t\tnotes: Frequency | Frequency[],\n\t\ttime?: Time,\n\t\tvelocity: NormalRange = 1\n\t): this {\n\t\tthis.log(\"triggerAttack\", notes, time, velocity);\n\t\tif (!Array.isArray(notes)) {\n\t\t\tnotes = [notes];\n\t\t}\n\t\tnotes.forEach((note) => {\n\t\t\tconst midiFloat = ftomf(\n\t\t\t\tnew FrequencyClass(this.context, note).toFrequency()\n\t\t\t);\n\t\t\tconst midi = Math.round(midiFloat) as MidiNote;\n\t\t\tconst remainder = midiFloat - midi;\n\t\t\t// find the closest note pitch\n\t\t\tconst difference = this._findClosest(midi);\n\t\t\tconst closestNote = midi - difference;\n\t\t\tconst buffer = this._buffers.get(closestNote);\n\t\t\tconst playbackRate = intervalToFrequencyRatio(\n\t\t\t\tdifference + remainder\n\t\t\t);\n\t\t\t// play that note\n\t\t\tconst source = new ToneBufferSource({\n\t\t\t\turl: buffer,\n\t\t\t\tcontext: this.context,\n\t\t\t\tcurve: this.curve,\n\t\t\t\tfadeIn: this.attack,\n\t\t\t\tfadeOut: this.release,\n\t\t\t\tplaybackRate,\n\t\t\t}).connect(this.output);\n\t\t\tsource.start(time, 0, buffer.duration / playbackRate, velocity);\n\t\t\t// add it to the active sources\n\t\t\tif (!isArray(this._activeSources.get(midi))) {\n\t\t\t\tthis._activeSources.set(midi, []);\n\t\t\t}\n\t\t\t(this._activeSources.get(midi) as ToneBufferSource[]).push(source);\n\n\t\t\t// remove it when it's done\n\t\t\tsource.onended = () => {\n\t\t\t\tif (this._activeSources && this._activeSources.has(midi)) {\n\t\t\t\t\tconst sources = this._activeSources.get(\n\t\t\t\t\t\tmidi\n\t\t\t\t\t) as ToneBufferSource[];\n\t\t\t\t\tconst index = sources.indexOf(source);\n\t\t\t\t\tif (index !== -1) {\n\t\t\t\t\t\tsources.splice(index, 1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\t\t});\n\t\treturn this;\n\t}\n\n\t/**\n\t * @param notes\tThe note to release, or an array of notes.\n\t * @param time \tWhen to release the note.\n\t */\n\ttriggerRelease(notes: Frequency | Frequency[], time?: Time): this {\n\t\tthis.log(\"triggerRelease\", notes, time);\n\t\tif (!Array.isArray(notes)) {\n\t\t\tnotes = [notes];\n\t\t}\n\t\tnotes.forEach((note) => {\n\t\t\tconst midi = new FrequencyClass(this.context, note).toMidi();\n\t\t\t// find the note\n\t\t\tif (\n\t\t\t\tthis._activeSources.has(midi) &&\n\t\t\t\t(this._activeSources.get(midi) as ToneBufferSource[]).length\n\t\t\t) {\n\t\t\t\tconst sources = this._activeSources.get(\n\t\t\t\t\tmidi\n\t\t\t\t) as ToneBufferSource[];\n\t\t\t\ttime = this.toSeconds(time);\n\t\t\t\tsources.forEach((source) => {\n\t\t\t\t\tsource.stop(time);\n\t\t\t\t});\n\t\t\t\tthis._activeSources.set(midi, []);\n\t\t\t}\n\t\t});\n\t\treturn this;\n\t}\n\n\t/**\n\t * Release all currently active notes.\n\t * @param time \tWhen to release the notes.\n\t */\n\treleaseAll(time?: Time): this {\n\t\tconst computedTime = this.toSeconds(time);\n\t\tthis._activeSources.forEach((sources) => {\n\t\t\twhile (sources.length) {\n\t\t\t\tconst source = sources.shift() as ToneBufferSource;\n\t\t\t\tsource.stop(computedTime);\n\t\t\t}\n\t\t});\n\t\treturn this;\n\t}\n\n\tsync(): this {\n\t\tif (this._syncState()) {\n\t\t\tthis._syncMethod(\"triggerAttack\", 1);\n\t\t\tthis._syncMethod(\"triggerRelease\", 1);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Invoke the attack phase, then after the duration, invoke the release.\n\t * @param notes\tThe note to play and release, or an array of notes.\n\t * @param duration The time the note should be held\n\t * @param time When to start the attack\n\t * @param velocity The velocity of the attack\n\t */\n\ttriggerAttackRelease(\n\t\tnotes: Frequency[] | Frequency,\n\t\tduration: Time | Time[],\n\t\ttime?: Time,\n\t\tvelocity: NormalRange = 1\n\t): this {\n\t\tconst computedTime = this.toSeconds(time);\n\t\tthis.triggerAttack(notes, computedTime, velocity);\n\t\tif (isArray(duration)) {\n\t\t\tassert(\n\t\t\t\tisArray(notes),\n\t\t\t\t\"notes must be an array when duration is array\"\n\t\t\t);\n\t\t\t(notes as Frequency[]).forEach((note, index) => {\n\t\t\t\tconst d = duration[Math.min(index, duration.length - 1)];\n\t\t\t\tthis.triggerRelease(note, computedTime + this.toSeconds(d));\n\t\t\t});\n\t\t} else {\n\t\t\tthis.triggerRelease(notes, computedTime + this.toSeconds(duration));\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Add a note to the sampler.\n\t * @param note The buffer's pitch.\n\t * @param url Either the url of the buffer, or a buffer which will be added with the given name.\n\t * @param callback The callback to invoke when the url is loaded.\n\t */\n\tadd(\n\t\tnote: Note | MidiNote,\n\t\turl: string | ToneAudioBuffer | AudioBuffer,\n\t\tcallback?: () => void\n\t): this {\n\t\tassert(\n\t\t\tisNote(note) || isFinite(note),\n\t\t\t`note must be a pitch or midi: ${note}`\n\t\t);\n\t\tif (isNote(note)) {\n\t\t\t// convert the note name to MIDI\n\t\t\tconst mid = new FrequencyClass(this.context, note).toMidi();\n\t\t\tthis._buffers.add(mid, url, callback);\n\t\t} else {\n\t\t\t// otherwise if it's numbers assume it's midi\n\t\t\tthis._buffers.add(note, url, callback);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * If the buffers are loaded or not\n\t */\n\tget loaded(): boolean {\n\t\treturn this._buffers.loaded;\n\t}\n\n\t/**\n\t * Clean up\n\t */\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis._buffers.dispose();\n\t\tthis._activeSources.forEach((sources) => {\n\t\t\tsources.forEach((source) => source.dispose());\n\t\t});\n\t\tthis._activeSources.clear();\n\t\treturn this;\n\t}\n}\n","import \"../core/clock/Transport.js\";\nimport {\n\tToneWithContext,\n\tToneWithContextOptions,\n} from \"../core/context/ToneWithContext.js\";\nimport { TicksClass } from \"../core/type/Ticks.js\";\nimport { TransportTimeClass } from \"../core/type/TransportTime.js\";\nimport {\n\tNormalRange,\n\tPositive,\n\tSeconds,\n\tTicks,\n\tTime,\n\tTransportTime,\n} from \"../core/type/Units.js\";\nimport { defaultArg, optionsFromArguments } from \"../core/util/Defaults.js\";\nimport { noOp } from \"../core/util/Interface.js\";\nimport {\n\tBasicPlaybackState,\n\tStateTimeline,\n} from \"../core/util/StateTimeline.js\";\nimport { isBoolean, isNumber } from \"../core/util/TypeCheck.js\";\n\nexport type ToneEventCallback<T> = (time: Seconds, value: T) => void;\n\nexport interface ToneEventOptions<T> extends ToneWithContextOptions {\n\tcallback: ToneEventCallback<T>;\n\tloop: boolean | number;\n\tloopEnd: Time;\n\tloopStart: Time;\n\tplaybackRate: Positive;\n\tvalue?: T;\n\tprobability: NormalRange;\n\tmute: boolean;\n\thumanize: boolean | Time;\n}\n\n/**\n * ToneEvent abstracts away this.context.transport.schedule and provides a schedulable\n * callback for a single or repeatable events along the timeline.\n *\n * @example\n * const synth = new Tone.PolySynth().toDestination();\n * const chordEvent = new Tone.ToneEvent(((time, chord) => {\n * \t// the chord as well as the exact time of the event\n * \t// are passed in as arguments to the callback function\n * \tsynth.triggerAttackRelease(chord, 0.5, time);\n * }), [\"D4\", \"E4\", \"F4\"]);\n * // start the chord at the beginning of the transport timeline\n * chordEvent.start();\n * // loop it every measure for 8 measures\n * chordEvent.loop = 8;\n * chordEvent.loopEnd = \"1m\";\n * @category Event\n */\nexport class ToneEvent<ValueType = any> extends ToneWithContext<\n\tToneEventOptions<ValueType>\n> {\n\treadonly name: string = \"ToneEvent\";\n\n\t/**\n\t * Loop value\n\t */\n\tprotected _loop: boolean | number;\n\n\t/**\n\t * The callback to invoke.\n\t */\n\tcallback: ToneEventCallback<ValueType>;\n\n\t/**\n\t * The value which is passed to the\n\t * callback function.\n\t */\n\tvalue: ValueType;\n\n\t/**\n\t * When the note is scheduled to start.\n\t */\n\tprotected _loopStart: Ticks;\n\n\t/**\n\t * When the note is scheduled to start.\n\t */\n\tprotected _loopEnd: Ticks;\n\n\t/**\n\t * Tracks the scheduled events\n\t */\n\tprotected _state: StateTimeline<{\n\t\tid: number;\n\t}> = new StateTimeline(\"stopped\");\n\n\t/**\n\t * The playback speed of the note. A speed of 1\n\t * is no change.\n\t */\n\tprotected _playbackRate: Positive;\n\n\t/**\n\t * A delay time from when the event is scheduled to start\n\t */\n\tprotected _startOffset: Ticks = 0;\n\n\t/**\n\t * private holder of probability value\n\t */\n\tprotected _probability: NormalRange;\n\n\t/**\n\t * the amount of variation from the given time.\n\t */\n\tprotected _humanize: boolean | Time;\n\n\t/**\n\t * If mute is true, the callback won't be invoked.\n\t */\n\tmute: boolean;\n\n\t/**\n\t * @param callback The callback to invoke at the time.\n\t * @param value The value or values which should be passed to the callback function on invocation.\n\t */\n\tconstructor(callback?: ToneEventCallback<ValueType>, value?: ValueType);\n\tconstructor(options?: Partial<ToneEventOptions<ValueType>>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(\n\t\t\tToneEvent.getDefaults(),\n\t\t\targuments,\n\t\t\t[\"callback\", \"value\"]\n\t\t);\n\t\tsuper(options);\n\n\t\tthis._loop = options.loop;\n\t\tthis.callback = options.callback;\n\t\tthis.value = options.value;\n\t\tthis._loopStart = this.toTicks(options.loopStart);\n\t\tthis._loopEnd = this.toTicks(options.loopEnd);\n\t\tthis._playbackRate = options.playbackRate;\n\t\tthis._probability = options.probability;\n\t\tthis._humanize = options.humanize;\n\t\tthis.mute = options.mute;\n\t\tthis._playbackRate = options.playbackRate;\n\t\tthis._state.increasing = true;\n\t\t// schedule the events for the first time\n\t\tthis._rescheduleEvents();\n\t}\n\n\tstatic getDefaults(): ToneEventOptions<any> {\n\t\treturn Object.assign(ToneWithContext.getDefaults(), {\n\t\t\tcallback: noOp,\n\t\t\thumanize: false,\n\t\t\tloop: false,\n\t\t\tloopEnd: \"1m\",\n\t\t\tloopStart: 0,\n\t\t\tmute: false,\n\t\t\tplaybackRate: 1,\n\t\t\tprobability: 1,\n\t\t\tvalue: null,\n\t\t});\n\t}\n\n\t/**\n\t * Reschedule all of the events along the timeline\n\t * with the updated values.\n\t * @param after Only reschedules events after the given time.\n\t */\n\tprivate _rescheduleEvents(after: Ticks = -1): void {\n\t\t// if no argument is given, schedules all of the events\n\t\tthis._state.forEachFrom(after, (event) => {\n\t\t\tlet duration;\n\t\t\tif (event.state === \"started\") {\n\t\t\t\tif (event.id !== -1) {\n\t\t\t\t\tthis.context.transport.clear(event.id);\n\t\t\t\t}\n\t\t\t\tconst startTick =\n\t\t\t\t\tevent.time +\n\t\t\t\t\tMath.round(this.startOffset / this._playbackRate);\n\t\t\t\tif (\n\t\t\t\t\tthis._loop === true ||\n\t\t\t\t\t(isNumber(this._loop) && this._loop > 1)\n\t\t\t\t) {\n\t\t\t\t\tduration = Infinity;\n\t\t\t\t\tif (isNumber(this._loop)) {\n\t\t\t\t\t\tduration = this._loop * this._getLoopDuration();\n\t\t\t\t\t}\n\t\t\t\t\tconst nextEvent = this._state.getAfter(startTick);\n\t\t\t\t\tif (nextEvent !== null) {\n\t\t\t\t\t\tduration = Math.min(\n\t\t\t\t\t\t\tduration,\n\t\t\t\t\t\t\tnextEvent.time - startTick\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tif (duration !== Infinity) {\n\t\t\t\t\t\tduration = new TicksClass(this.context, duration);\n\t\t\t\t\t}\n\t\t\t\t\tconst interval = new TicksClass(\n\t\t\t\t\t\tthis.context,\n\t\t\t\t\t\tthis._getLoopDuration()\n\t\t\t\t\t);\n\t\t\t\t\tevent.id = this.context.transport.scheduleRepeat(\n\t\t\t\t\t\tthis._tick.bind(this),\n\t\t\t\t\t\tinterval,\n\t\t\t\t\t\tnew TicksClass(this.context, startTick),\n\t\t\t\t\t\tduration\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tevent.id = this.context.transport.schedule(\n\t\t\t\t\t\tthis._tick.bind(this),\n\t\t\t\t\t\tnew TicksClass(this.context, startTick)\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\t/**\n\t * Returns the playback state of the note, either \"started\" or \"stopped\".\n\t */\n\tget state(): BasicPlaybackState {\n\t\treturn this._state.getValueAtTime(\n\t\t\tthis.context.transport.ticks\n\t\t) as BasicPlaybackState;\n\t}\n\n\t/**\n\t * The start from the scheduled start time.\n\t */\n\tget startOffset(): Ticks {\n\t\treturn this._startOffset;\n\t}\n\tset startOffset(offset) {\n\t\tthis._startOffset = offset;\n\t}\n\n\t/**\n\t * The probability of the notes being triggered.\n\t */\n\tget probability(): NormalRange {\n\t\treturn this._probability;\n\t}\n\tset probability(prob) {\n\t\tthis._probability = prob;\n\t}\n\n\t/**\n\t * If set to true, will apply small random variation\n\t * to the callback time. If the value is given as a time, it will randomize\n\t * by that amount.\n\t * @example\n\t * const event = new Tone.ToneEvent();\n\t * event.humanize = true;\n\t */\n\tget humanize(): Time | boolean {\n\t\treturn this._humanize;\n\t}\n\n\tset humanize(variation) {\n\t\tthis._humanize = variation;\n\t}\n\n\t/**\n\t * Start the note at the given time.\n\t * @param time When the event should start.\n\t */\n\tstart(time?: TransportTime | TransportTimeClass): this {\n\t\tconst ticks = this.toTicks(time);\n\t\tif (this._state.getValueAtTime(ticks) === \"stopped\") {\n\t\t\tthis._state.add({\n\t\t\t\tid: -1,\n\t\t\t\tstate: \"started\",\n\t\t\t\ttime: ticks,\n\t\t\t});\n\t\t\tthis._rescheduleEvents(ticks);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Stop the Event at the given time.\n\t * @param time When the event should stop.\n\t */\n\tstop(time?: TransportTime | TransportTimeClass): this {\n\t\tthis.cancel(time);\n\t\tconst ticks = this.toTicks(time);\n\t\tif (this._state.getValueAtTime(ticks) === \"started\") {\n\t\t\tthis._state.setStateAtTime(\"stopped\", ticks, { id: -1 });\n\t\t\tconst previousEvent = this._state.getBefore(ticks);\n\t\t\tlet rescheduleTime = ticks;\n\t\t\tif (previousEvent !== null) {\n\t\t\t\trescheduleTime = previousEvent.time;\n\t\t\t}\n\t\t\tthis._rescheduleEvents(rescheduleTime);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Cancel all scheduled events greater than or equal to the given time\n\t * @param time The time after which events will be cancel.\n\t */\n\tcancel(time?: TransportTime | TransportTimeClass): this {\n\t\ttime = defaultArg(time, -Infinity);\n\t\tconst ticks = this.toTicks(time);\n\t\tthis._state.forEachFrom(ticks, (event) => {\n\t\t\tthis.context.transport.clear(event.id);\n\t\t});\n\t\tthis._state.cancel(ticks);\n\t\treturn this;\n\t}\n\n\t/**\n\t * The callback function invoker. Also\n\t * checks if the Event is done playing\n\t * @param time The time of the event in seconds\n\t */\n\tprotected _tick(time: Seconds): void {\n\t\tconst ticks = this.context.transport.getTicksAtTime(time);\n\t\tif (!this.mute && this._state.getValueAtTime(ticks) === \"started\") {\n\t\t\tif (this.probability < 1 && Math.random() > this.probability) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (this.humanize) {\n\t\t\t\tlet variation = 0.02;\n\t\t\t\tif (!isBoolean(this.humanize)) {\n\t\t\t\t\tvariation = this.toSeconds(this.humanize);\n\t\t\t\t}\n\t\t\t\ttime += (Math.random() * 2 - 1) * variation;\n\t\t\t}\n\t\t\tthis.callback(time, this.value);\n\t\t}\n\t}\n\n\t/**\n\t * Get the duration of the loop.\n\t */\n\tprotected _getLoopDuration(): Ticks {\n\t\treturn (this._loopEnd - this._loopStart) / this._playbackRate;\n\t}\n\n\t/**\n\t * If the note should loop or not\n\t * between ToneEvent.loopStart and\n\t * ToneEvent.loopEnd. If set to true,\n\t * the event will loop indefinitely,\n\t * if set to a number greater than 1\n\t * it will play a specific number of\n\t * times, if set to false, 0 or 1, the\n\t * part will only play once.\n\t */\n\tget loop(): boolean | number {\n\t\treturn this._loop;\n\t}\n\tset loop(loop) {\n\t\tthis._loop = loop;\n\t\tthis._rescheduleEvents();\n\t}\n\n\t/**\n\t * The playback rate of the event. Defaults to 1.\n\t * @example\n\t * const note = new Tone.ToneEvent();\n\t * note.loop = true;\n\t * // repeat the note twice as fast\n\t * note.playbackRate = 2;\n\t */\n\tget playbackRate(): Positive {\n\t\treturn this._playbackRate;\n\t}\n\tset playbackRate(rate) {\n\t\tthis._playbackRate = rate;\n\t\tthis._rescheduleEvents();\n\t}\n\n\t/**\n\t * The loopEnd point is the time the event will loop\n\t * if ToneEvent.loop is true.\n\t */\n\tget loopEnd(): Time {\n\t\treturn new TicksClass(this.context, this._loopEnd).toSeconds();\n\t}\n\tset loopEnd(loopEnd) {\n\t\tthis._loopEnd = this.toTicks(loopEnd);\n\t\tif (this._loop) {\n\t\t\tthis._rescheduleEvents();\n\t\t}\n\t}\n\n\t/**\n\t * The time when the loop should start.\n\t */\n\tget loopStart(): Time {\n\t\treturn new TicksClass(this.context, this._loopStart).toSeconds();\n\t}\n\tset loopStart(loopStart) {\n\t\tthis._loopStart = this.toTicks(loopStart);\n\t\tif (this._loop) {\n\t\t\tthis._rescheduleEvents();\n\t\t}\n\t}\n\n\t/**\n\t * The current progress of the loop interval.\n\t * Returns 0 if the event is not started yet or\n\t * it is not set to loop.\n\t */\n\tget progress(): NormalRange {\n\t\tif (this._loop) {\n\t\t\tconst ticks = this.context.transport.ticks;\n\t\t\tconst lastEvent = this._state.get(ticks);\n\t\t\tif (lastEvent !== null && lastEvent.state === \"started\") {\n\t\t\t\tconst loopDuration = this._getLoopDuration();\n\t\t\t\tconst progress = (ticks - lastEvent.time) % loopDuration;\n\t\t\t\treturn progress / loopDuration;\n\t\t\t} else {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t} else {\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis.cancel();\n\t\tthis._state.dispose();\n\t\treturn this;\n\t}\n}\n","import { ToneEvent } from \"./ToneEvent.js\";\nimport {\n\tNormalRange,\n\tPositive,\n\tSeconds,\n\tTime,\n\tTransportTime,\n} from \"../core/type/Units.js\";\nimport {\n\tToneWithContext,\n\tToneWithContextOptions,\n} from \"../core/context/ToneWithContext.js\";\nimport { optionsFromArguments } from \"../core/util/Defaults.js\";\nimport { noOp } from \"../core/util/Interface.js\";\nimport { BasicPlaybackState } from \"../core/util/StateTimeline.js\";\n\nexport interface LoopOptions extends ToneWithContextOptions {\n\tcallback: (time: Seconds) => void;\n\tinterval: Time;\n\tplaybackRate: Positive;\n\titerations: number;\n\tprobability: NormalRange;\n\tmute: boolean;\n\thumanize: boolean | Time;\n}\n\n/**\n * Loop creates a looped callback at the\n * specified interval. The callback can be\n * started, stopped and scheduled along\n * the Transport's timeline.\n * @example\n * const loop = new Tone.Loop((time) => {\n * \t// triggered every eighth note.\n * \tconsole.log(time);\n * }, \"8n\").start(0);\n * Tone.Transport.start();\n * @category Event\n */\nexport class Loop<\n\tOptions extends LoopOptions = LoopOptions,\n> extends ToneWithContext<Options> {\n\treadonly name: string = \"Loop\";\n\n\t/**\n\t * The event which produces the callbacks\n\t */\n\tprivate _event: ToneEvent;\n\n\t/**\n\t * The callback to invoke with the next event in the pattern\n\t */\n\tcallback: (time: Seconds) => void;\n\n\t/**\n\t * @param callback The callback to invoke at the time.\n\t * @param interval The time between successive callback calls.\n\t */\n\tconstructor(callback?: (time: Seconds) => void, interval?: Time);\n\tconstructor(options?: Partial<LoopOptions>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(Loop.getDefaults(), arguments, [\n\t\t\t\"callback\",\n\t\t\t\"interval\",\n\t\t]);\n\t\tsuper(options);\n\n\t\tthis._event = new ToneEvent({\n\t\t\tcontext: this.context,\n\t\t\tcallback: this._tick.bind(this),\n\t\t\tloop: true,\n\t\t\tloopEnd: options.interval,\n\t\t\tplaybackRate: options.playbackRate,\n\t\t\tprobability: options.probability,\n\t\t\thumanize: options.humanize,\n\t\t});\n\n\t\tthis.callback = options.callback;\n\t\t// set the iterations\n\t\tthis.iterations = options.iterations;\n\t}\n\n\tstatic getDefaults(): LoopOptions {\n\t\treturn Object.assign(ToneWithContext.getDefaults(), {\n\t\t\tinterval: \"4n\",\n\t\t\tcallback: noOp,\n\t\t\tplaybackRate: 1,\n\t\t\titerations: Infinity,\n\t\t\tprobability: 1,\n\t\t\tmute: false,\n\t\t\thumanize: false,\n\t\t});\n\t}\n\n\t/**\n\t * Start the loop at the specified time along the Transport's timeline.\n\t * @param time When to start the Loop.\n\t */\n\tstart(time?: TransportTime): this {\n\t\tthis._event.start(time);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Stop the loop at the given time.\n\t * @param time When to stop the Loop.\n\t */\n\tstop(time?: TransportTime): this {\n\t\tthis._event.stop(time);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Cancel all scheduled events greater than or equal to the given time\n\t * @param time The time after which events will be cancel.\n\t */\n\tcancel(time?: TransportTime): this {\n\t\tthis._event.cancel(time);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Internal function called when the notes should be called\n\t * @param time The time the event occurs\n\t */\n\tprotected _tick(time: Seconds): void {\n\t\tthis.callback(time);\n\t}\n\n\t/**\n\t * The state of the Loop, either started or stopped.\n\t */\n\tget state(): BasicPlaybackState {\n\t\treturn this._event.state;\n\t}\n\n\t/**\n\t * The progress of the loop as a value between 0-1. 0, when the loop is stopped or done iterating.\n\t */\n\tget progress(): NormalRange {\n\t\treturn this._event.progress;\n\t}\n\n\t/**\n\t * The time between successive callbacks.\n\t * @example\n\t * const loop = new Tone.Loop();\n\t * loop.interval = \"8n\"; // loop every 8n\n\t */\n\tget interval(): Time {\n\t\treturn this._event.loopEnd;\n\t}\n\tset interval(interval) {\n\t\tthis._event.loopEnd = interval;\n\t}\n\n\t/**\n\t * The playback rate of the loop. The normal playback rate is 1 (no change).\n\t * A `playbackRate` of 2 would be twice as fast.\n\t */\n\tget playbackRate(): Positive {\n\t\treturn this._event.playbackRate;\n\t}\n\tset playbackRate(rate) {\n\t\tthis._event.playbackRate = rate;\n\t}\n\n\t/**\n\t * Random variation +/-0.01s to the scheduled time.\n\t * Or give it a time value which it will randomize by.\n\t */\n\tget humanize(): boolean | Time {\n\t\treturn this._event.humanize;\n\t}\n\tset humanize(variation) {\n\t\tthis._event.humanize = variation;\n\t}\n\n\t/**\n\t * The probably of the callback being invoked.\n\t */\n\tget probability(): NormalRange {\n\t\treturn this._event.probability;\n\t}\n\n\tset probability(prob) {\n\t\tthis._event.probability = prob;\n\t}\n\n\t/**\n\t * Muting the Loop means that no callbacks are invoked.\n\t */\n\tget mute(): boolean {\n\t\treturn this._event.mute;\n\t}\n\n\tset mute(mute) {\n\t\tthis._event.mute = mute;\n\t}\n\n\t/**\n\t * The number of iterations of the loop. The default value is `Infinity` (loop forever).\n\t */\n\tget iterations(): number {\n\t\tif (this._event.loop === true) {\n\t\t\treturn Infinity;\n\t\t} else {\n\t\t\treturn this._event.loop as number;\n\t\t}\n\t}\n\tset iterations(iters) {\n\t\tif (iters === Infinity) {\n\t\t\tthis._event.loop = true;\n\t\t} else {\n\t\t\tthis._event.loop = iters;\n\t\t}\n\t}\n\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis._event.dispose();\n\t\treturn this;\n\t}\n}\n","import { Gain } from \"../../core/context/Gain.js\";\nimport {\n\tconnect,\n\tToneAudioNode,\n\tToneAudioNodeOptions,\n} from \"../../core/context/ToneAudioNode.js\";\nimport { NormalRange } from \"../../core/type/Units.js\";\nimport { optionsFromArguments } from \"../../core/util/Defaults.js\";\nimport { readOnly } from \"../../core/util/Interface.js\";\nimport { GainToAudio } from \"../../signal/GainToAudio.js\";\nimport { Signal } from \"../../signal/Signal.js\";\n\ninterface CrossFadeOptions extends ToneAudioNodeOptions {\n\tfade: NormalRange;\n}\n\n/**\n * Tone.Crossfade provides equal power fading between two inputs.\n * More on crossfading technique [here](https://en.wikipedia.org/wiki/Fade_(audio_engineering)#Crossfading).\n * ```\n * +---------+\n * +> input a +>--+\n * +-----------+ +---------------------+ | | |\n * | 1s signal +>--> stereoPannerNode L +>----> gain | |\n * +-----------+ | | +---------+ |\n * +-> pan R +>-+ | +--------+\n * | +---------------------+ | +---> output +>\n * +------+ | | +---------+ | +--------+\n * | fade +>----+ | +> input b +>--+\n * +------+ | | |\n * +--> gain |\n * +---------+\n * ```\n * @example\n * const crossFade = new Tone.CrossFade().toDestination();\n * // connect two inputs Tone.to a/b\n * const inputA = new Tone.Oscillator(440, \"square\").connect(crossFade.a).start();\n * const inputB = new Tone.Oscillator(440, \"sine\").connect(crossFade.b).start();\n * // use the fade to control the mix between the two\n * crossFade.fade.value = 0.5;\n * @category Component\n */\nexport class CrossFade extends ToneAudioNode<CrossFadeOptions> {\n\treadonly name: string = \"CrossFade\";\n\n\t/**\n\t * The crossfading is done by a StereoPannerNode\n\t */\n\tprivate _panner: StereoPannerNode = this.context.createStereoPanner();\n\n\t/**\n\t * Split the output of the panner node into two values used to control the gains.\n\t */\n\tprivate _split: ChannelSplitterNode = this.context.createChannelSplitter(2);\n\n\t/**\n\t * Convert the fade value into an audio range value so it can be connected\n\t * to the panner.pan AudioParam\n\t */\n\tprivate _g2a: GainToAudio = new GainToAudio({ context: this.context });\n\n\t/**\n\t * The input which is at full level when fade = 0\n\t */\n\treadonly a: Gain = new Gain({\n\t\tcontext: this.context,\n\t\tgain: 0,\n\t});\n\n\t/**\n\t * The input which is at full level when fade = 1\n\t */\n\treadonly b: Gain = new Gain({\n\t\tcontext: this.context,\n\t\tgain: 0,\n\t});\n\n\t/**\n\t * The output is a mix between `a` and `b` at the ratio of `fade`\n\t */\n\treadonly output: Gain = new Gain({ context: this.context });\n\n\t/**\n\t * CrossFade has no input, you must choose either `a` or `b`\n\t */\n\treadonly input: undefined;\n\n\t/**\n\t * The mix between the two inputs. A fade value of 0\n\t * will output 100% crossFade.a and\n\t * a value of 1 will output 100% crossFade.b.\n\t */\n\treadonly fade: Signal<\"normalRange\">;\n\n\tprotected _internalChannels = [this.a, this.b];\n\n\t/**\n\t * @param fade The initial fade value [0, 1].\n\t */\n\tconstructor(fade?: NormalRange);\n\tconstructor(options?: Partial<CrossFadeOptions>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(\n\t\t\tCrossFade.getDefaults(),\n\t\t\targuments,\n\t\t\t[\"fade\"]\n\t\t);\n\t\tsuper(options);\n\n\t\tthis.fade = new Signal({\n\t\t\tcontext: this.context,\n\t\t\tunits: \"normalRange\",\n\t\t\tvalue: options.fade,\n\t\t});\n\t\treadOnly(this, \"fade\");\n\n\t\tthis.context.getConstant(1).connect(this._panner);\n\t\tthis._panner.connect(this._split);\n\t\t// this is necessary for standardized-audio-context\n\t\t// doesn't make any difference for the native AudioContext\n\t\t// https://github.com/chrisguttandin/standardized-audio-context/issues/647\n\t\tthis._panner.channelCount = 1;\n\t\tthis._panner.channelCountMode = \"explicit\";\n\t\tconnect(this._split, this.a.gain, 0);\n\t\tconnect(this._split, this.b.gain, 1);\n\n\t\tthis.fade.chain(this._g2a, this._panner.pan);\n\n\t\tthis.a.connect(this.output);\n\t\tthis.b.connect(this.output);\n\t}\n\n\tstatic getDefaults(): CrossFadeOptions {\n\t\treturn Object.assign(ToneAudioNode.getDefaults(), {\n\t\t\tfade: 0.5,\n\t\t});\n\t}\n\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis.a.dispose();\n\t\tthis.b.dispose();\n\t\tthis.output.dispose();\n\t\tthis.fade.dispose();\n\t\tthis._g2a.dispose();\n\t\tthis._panner.disconnect();\n\t\tthis._split.disconnect();\n\t\treturn this;\n\t}\n}\n","import { CrossFade } from \"../component/channel/CrossFade.js\";\nimport { Gain } from \"../core/context/Gain.js\";\nimport {\n\tToneAudioNode,\n\tToneAudioNodeOptions,\n} from \"../core/context/ToneAudioNode.js\";\nimport { NormalRange } from \"../core/type/Units.js\";\nimport { readOnly } from \"../core/util/Interface.js\";\nimport { Signal } from \"../signal/Signal.js\";\n\nexport interface EffectOptions extends ToneAudioNodeOptions {\n\twet: NormalRange;\n}\n/**\n * Effect is the base class for effects. Connect the effect between\n * the effectSend and effectReturn GainNodes, then control the amount of\n * effect which goes to the output using the wet control.\n */\nexport abstract class Effect<\n\tOptions extends EffectOptions,\n> extends ToneAudioNode<Options> {\n\treadonly name: string = \"Effect\";\n\n\t/**\n\t * the drywet knob to control the amount of effect\n\t */\n\tprivate _dryWet: CrossFade = new CrossFade({ context: this.context });\n\n\t/**\n\t * The wet control is how much of the effected\n\t * will pass through to the output. 1 = 100% effected\n\t * signal, 0 = 100% dry signal.\n\t */\n\twet: Signal<\"normalRange\"> = this._dryWet.fade;\n\n\t/**\n\t * connect the effectSend to the input of hte effect\n\t */\n\tprotected effectSend: Gain = new Gain({ context: this.context });\n\n\t/**\n\t * connect the output of the effect to the effectReturn\n\t */\n\tprotected effectReturn: Gain = new Gain({ context: this.context });\n\n\t/**\n\t * The effect input node\n\t */\n\tinput: Gain = new Gain({ context: this.context });\n\n\t/**\n\t * The effect output\n\t */\n\toutput = this._dryWet;\n\n\tconstructor(options: EffectOptions) {\n\t\tsuper(options);\n\n\t\t// connections\n\t\tthis.input.fan(this._dryWet.a, this.effectSend);\n\t\tthis.effectReturn.connect(this._dryWet.b);\n\t\tthis.wet.setValueAtTime(options.wet, 0);\n\t\tthis._internalChannels = [this.effectReturn, this.effectSend];\n\t\treadOnly(this, \"wet\");\n\t}\n\n\tstatic getDefaults(): EffectOptions {\n\t\treturn Object.assign(ToneAudioNode.getDefaults(), {\n\t\t\twet: 1,\n\t\t});\n\t}\n\n\t/**\n\t * chains the effect in between the effectSend and effectReturn\n\t */\n\tprotected connectEffect(effect: ToneAudioNode | AudioNode): this {\n\t\t// add it to the internal channels\n\t\tthis._internalChannels.push(effect);\n\t\tthis.effectSend.chain(effect, this.effectReturn);\n\t\treturn this;\n\t}\n\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis._dryWet.dispose();\n\t\tthis.effectSend.dispose();\n\t\tthis.effectReturn.dispose();\n\t\tthis.wet.dispose();\n\t\treturn this;\n\t}\n}\n","import { Param } from \"../../core/context/Param.js\";\nimport {\n\tToneAudioNode,\n\tToneAudioNodeOptions,\n} from \"../../core/context/ToneAudioNode.js\";\nimport { AudioRange } from \"../../core/type/Units.js\";\nimport { optionsFromArguments } from \"../../core/util/Defaults.js\";\nimport { readOnly } from \"../../core/util/Interface.js\";\n\ninterface TonePannerOptions extends ToneAudioNodeOptions {\n\tpan: AudioRange;\n\tchannelCount: number;\n}\n\n/**\n * Panner is an equal power Left/Right Panner. It is a wrapper around the StereoPannerNode.\n * @example\n * return Tone.Offline(() => {\n * // move the input signal from right to left\n * \tconst panner = new Tone.Panner(1).toDestination();\n * \tpanner.pan.rampTo(-1, 0.5);\n * \tconst osc = new Tone.Oscillator(100).connect(panner).start();\n * }, 0.5, 2);\n * @category Component\n */\nexport class Panner extends ToneAudioNode<TonePannerOptions> {\n\treadonly name: string = \"Panner\";\n\n\t/**\n\t * the panner node\n\t */\n\tprivate _panner: StereoPannerNode = this.context.createStereoPanner();\n\treadonly input: StereoPannerNode = this._panner;\n\treadonly output: StereoPannerNode = this._panner;\n\n\t/**\n\t * The pan control. -1 = hard left, 1 = hard right.\n\t * @min -1\n\t * @max 1\n\t * @example\n\t * return Tone.Offline(() => {\n\t * \t// pan hard right\n\t * \tconst panner = new Tone.Panner(1).toDestination();\n\t * \t// pan hard left\n\t * \tpanner.pan.setValueAtTime(-1, 0.25);\n\t * \tconst osc = new Tone.Oscillator(50, \"triangle\").connect(panner).start();\n\t * }, 0.5, 2);\n\t */\n\treadonly pan: Param<\"audioRange\">;\n\n\tconstructor(options?: Partial<TonePannerOptions>);\n\t/**\n\t * @param pan The initial panner value (Defaults to 0 = \"center\").\n\t */\n\tconstructor(pan?: AudioRange);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(Panner.getDefaults(), arguments, [\n\t\t\t\"pan\",\n\t\t]);\n\t\tsuper(options);\n\n\t\tthis.pan = new Param({\n\t\t\tcontext: this.context,\n\t\t\tparam: this._panner.pan,\n\t\t\tvalue: options.pan,\n\t\t\tminValue: -1,\n\t\t\tmaxValue: 1,\n\t\t});\n\n\t\t// this is necessary for standardized-audio-context\n\t\t// doesn't make any difference for the native AudioContext\n\t\t// https://github.com/chrisguttandin/standardized-audio-context/issues/647\n\t\tthis._panner.channelCount = options.channelCount;\n\t\tthis._panner.channelCountMode = \"explicit\";\n\n\t\t// initial value\n\t\treadOnly(this, \"pan\");\n\t}\n\n\tstatic getDefaults(): TonePannerOptions {\n\t\treturn Object.assign(ToneAudioNode.getDefaults(), {\n\t\t\tpan: 0,\n\t\t\tchannelCount: 1,\n\t\t});\n\t}\n\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis._panner.disconnect();\n\t\tthis.pan.dispose();\n\t\treturn this;\n\t}\n}\n","import \"../core/worklet/SingleIOProcessor.worklet.js\";\nimport { registerProcessor } from \"../core/worklet/WorkletGlobalScope.js\";\n\nexport const workletName = \"bit-crusher\";\n\nexport const bitCrusherWorklet = /* javascript */ `\n\tclass BitCrusherWorklet extends SingleIOProcessor {\n\n\t\tstatic get parameterDescriptors() {\n\t\t\treturn [{\n\t\t\t\tname: \"bits\",\n\t\t\t\tdefaultValue: 12,\n\t\t\t\tminValue: 1,\n\t\t\t\tmaxValue: 16,\n\t\t\t\tautomationRate: 'k-rate'\n\t\t\t}];\n\t\t}\n\n\t\tgenerate(input, _channel, parameters) {\n\t\t\tconst step = Math.pow(0.5, parameters.bits - 1);\n\t\t\tconst val = step * Math.floor(input / step + 0.5);\n\t\t\treturn val;\n\t\t}\n\t}\n`;\n\nregisterProcessor(workletName, bitCrusherWorklet);\n","import {\n\tToneAudioNode,\n\tToneAudioNodeOptions,\n} from \"../../core/context/ToneAudioNode.js\";\nimport { optionsFromArguments } from \"../../core/util/Defaults.js\";\n\ninterface SplitOptions extends ToneAudioNodeOptions {\n\tchannels: number;\n}\n\n/**\n * Split splits an incoming signal into the number of given channels.\n *\n * @example\n * const split = new Tone.Split();\n * // stereoSignal.connect(split);\n * @category Component\n */\nexport class Split extends ToneAudioNode<SplitOptions> {\n\treadonly name: string = \"Split\";\n\n\t/**\n\t * The splitting node\n\t */\n\tprivate _splitter: ChannelSplitterNode;\n\n\treadonly input: ChannelSplitterNode;\n\treadonly output: ChannelSplitterNode;\n\n\t/**\n\t * @param channels The number of channels to merge.\n\t */\n\tconstructor(channels?: number);\n\tconstructor(options?: Partial<SplitOptions>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(Split.getDefaults(), arguments, [\n\t\t\t\"channels\",\n\t\t]);\n\t\tsuper(options);\n\n\t\tthis._splitter =\n\t\t\tthis.input =\n\t\t\tthis.output =\n\t\t\t\tthis.context.createChannelSplitter(options.channels);\n\t\tthis._internalChannels = [this._splitter];\n\t}\n\n\tstatic getDefaults(): SplitOptions {\n\t\treturn Object.assign(ToneAudioNode.getDefaults(), {\n\t\t\tchannels: 2,\n\t\t});\n\t}\n\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis._splitter.disconnect();\n\t\treturn this;\n\t}\n}\n","import {\n\tToneAudioNode,\n\tToneAudioNodeOptions,\n} from \"../../core/context/ToneAudioNode.js\";\nimport { Positive } from \"../../core/type/Units.js\";\nimport { optionsFromArguments } from \"../../core/util/Defaults.js\";\n\ninterface MergeOptions extends ToneAudioNodeOptions {\n\tchannels: Positive;\n}\n\n/**\n * Merge brings multiple mono input channels into a single multichannel output channel.\n *\n * @example\n * const merge = new Tone.Merge().toDestination();\n * // routing a sine tone in the left channel\n * const osc = new Tone.Oscillator().connect(merge, 0, 0).start();\n * // and noise in the right channel\n * const noise = new Tone.Noise().connect(merge, 0, 1).start();;\n * @category Component\n */\nexport class Merge extends ToneAudioNode<MergeOptions> {\n\treadonly name: string = \"Merge\";\n\n\t/**\n\t * The merger node for the channels.\n\t */\n\tprivate _merger: ChannelMergerNode;\n\n\t/**\n\t * The output is the input channels combined into a single (multichannel) output\n\t */\n\treadonly output: ChannelMergerNode;\n\n\t/**\n\t * Multiple input connections combine into a single output.\n\t */\n\treadonly input: ChannelMergerNode;\n\n\t/**\n\t * @param channels The number of channels to merge.\n\t */\n\tconstructor(channels?: Positive);\n\tconstructor(options?: Partial<MergeOptions>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(Merge.getDefaults(), arguments, [\n\t\t\t\"channels\",\n\t\t]);\n\t\tsuper(options);\n\n\t\tthis._merger =\n\t\t\tthis.output =\n\t\t\tthis.input =\n\t\t\t\tthis.context.createChannelMerger(options.channels);\n\t}\n\n\tstatic getDefaults(): MergeOptions {\n\t\treturn Object.assign(ToneAudioNode.getDefaults(), {\n\t\t\tchannels: 2,\n\t\t});\n\t}\n\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis._merger.disconnect();\n\t\treturn this;\n\t}\n}\n","import { StereoEffect, StereoEffectOptions } from \"./StereoEffect.js\";\nimport { Frequency, NormalRange } from \"../core/type/Units.js\";\nimport { optionsFromArguments } from \"../core/util/Defaults.js\";\nimport { readOnly } from \"../core/util/Interface.js\";\nimport { Signal } from \"../signal/Signal.js\";\nimport { LowpassCombFilter } from \"../component/filter/LowpassCombFilter.js\";\n\nexport interface FreeverbOptions extends StereoEffectOptions {\n\tdampening: Frequency;\n\troomSize: NormalRange;\n}\n\n/**\n * An array of comb filter delay values from Freeverb implementation\n */\nconst combFilterTunings = [\n\t1557 / 44100,\n\t1617 / 44100,\n\t1491 / 44100,\n\t1422 / 44100,\n\t1277 / 44100,\n\t1356 / 44100,\n\t1188 / 44100,\n\t1116 / 44100,\n];\n\n/**\n * An array of allpass filter frequency values from Freeverb implementation\n */\nconst allpassFilterFrequencies = [225, 556, 441, 341];\n\n/**\n * Freeverb is a reverb based on [Freeverb](https://ccrma.stanford.edu/~jos/pasp/Freeverb.html).\n * Read more on reverb on [Sound On Sound](https://web.archive.org/web/20160404083902/http://www.soundonsound.com:80/sos/feb01/articles/synthsecrets.asp).\n * Freeverb is now implemented with an AudioWorkletNode which may result on performance degradation on some platforms. Consider using {@link Reverb}.\n * @example\n * const freeverb = new Tone.Freeverb().toDestination();\n * freeverb.dampening = 1000;\n * // routing synth through the reverb\n * const synth = new Tone.NoiseSynth().connect(freeverb);\n * synth.triggerAttackRelease(0.05);\n * @category Effect\n */\nexport class Freeverb extends StereoEffect<FreeverbOptions> {\n\treadonly name: string = \"Freeverb\";\n\n\t/**\n\t * The roomSize value between 0 and 1. A larger roomSize will result in a longer decay.\n\t */\n\treadonly roomSize: Signal<\"normalRange\">;\n\n\t/**\n\t * the comb filters\n\t */\n\tprivate _combFilters: LowpassCombFilter[] = [];\n\n\t/**\n\t * the allpass filters on the left\n\t */\n\tprivate _allpassFiltersL: BiquadFilterNode[] = [];\n\n\t/**\n\t * the allpass filters on the right\n\t */\n\tprivate _allpassFiltersR: BiquadFilterNode[] = [];\n\n\t/**\n\t * @param roomSize Correlated to the decay time.\n\t * @param dampening The cutoff frequency of a lowpass filter as part of the reverb.\n\t */\n\tconstructor(roomSize?: NormalRange, dampening?: Frequency);\n\tconstructor(options?: Partial<FreeverbOptions>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(\n\t\t\tFreeverb.getDefaults(),\n\t\t\targuments,\n\t\t\t[\"roomSize\", \"dampening\"]\n\t\t);\n\t\tsuper(options);\n\n\t\tthis.roomSize = new Signal({\n\t\t\tcontext: this.context,\n\t\t\tvalue: options.roomSize,\n\t\t\tunits: \"normalRange\",\n\t\t});\n\n\t\t// make the allpass filters on the right\n\t\tthis._allpassFiltersL = allpassFilterFrequencies.map((freq) => {\n\t\t\tconst allpassL = this.context.createBiquadFilter();\n\t\t\tallpassL.type = \"allpass\";\n\t\t\tallpassL.frequency.value = freq;\n\t\t\treturn allpassL;\n\t\t});\n\n\t\t// make the allpass filters on the left\n\t\tthis._allpassFiltersR = allpassFilterFrequencies.map((freq) => {\n\t\t\tconst allpassR = this.context.createBiquadFilter();\n\t\t\tallpassR.type = \"allpass\";\n\t\t\tallpassR.frequency.value = freq;\n\t\t\treturn allpassR;\n\t\t});\n\n\t\t// make the comb filters\n\t\tthis._combFilters = combFilterTunings.map((delayTime, index) => {\n\t\t\tconst lfpf = new LowpassCombFilter({\n\t\t\t\tcontext: this.context,\n\t\t\t\tdampening: options.dampening,\n\t\t\t\tdelayTime,\n\t\t\t});\n\t\t\tif (index < combFilterTunings.length / 2) {\n\t\t\t\tthis.connectEffectLeft(lfpf, ...this._allpassFiltersL);\n\t\t\t} else {\n\t\t\t\tthis.connectEffectRight(lfpf, ...this._allpassFiltersR);\n\t\t\t}\n\t\t\tthis.roomSize.connect(lfpf.resonance);\n\t\t\treturn lfpf;\n\t\t});\n\n\t\treadOnly(this, [\"roomSize\"]);\n\t}\n\n\tstatic getDefaults(): FreeverbOptions {\n\t\treturn Object.assign(StereoEffect.getDefaults(), {\n\t\t\troomSize: 0.7,\n\t\t\tdampening: 3000,\n\t\t});\n\t}\n\n\t/**\n\t * The amount of dampening of the reverberant signal.\n\t */\n\n\tget dampening(): Frequency {\n\t\treturn this._combFilters[0].dampening;\n\t}\n\tset dampening(d) {\n\t\tthis._combFilters.forEach((c) => (c.dampening = d));\n\t}\n\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis._allpassFiltersL.forEach((al) => al.disconnect());\n\t\tthis._allpassFiltersR.forEach((ar) => ar.disconnect());\n\t\tthis._combFilters.forEach((cf) => cf.dispose());\n\t\tthis.roomSize.dispose();\n\t\treturn this;\n\t}\n}\n","import { NormalRange } from \"../core/type/Units.js\";\nimport { StereoEffect, StereoEffectOptions } from \"./StereoEffect.js\";\nimport { optionsFromArguments } from \"../core/util/Defaults.js\";\nimport { Scale } from \"../signal/Scale.js\";\nimport { Signal } from \"../signal/Signal.js\";\nimport { FeedbackCombFilter } from \"../component/filter/FeedbackCombFilter.js\";\nimport { readOnly } from \"../core/util/Interface.js\";\n\nexport interface JCReverbOptions extends StereoEffectOptions {\n\troomSize: NormalRange;\n}\n\n/**\n * an array of the comb filter delay time values\n */\nconst combFilterDelayTimes = [\n\t1687 / 25000,\n\t1601 / 25000,\n\t2053 / 25000,\n\t2251 / 25000,\n];\n\n/**\n * the resonances of each of the comb filters\n */\nconst combFilterResonances = [0.773, 0.802, 0.753, 0.733];\n\n/**\n * the allpass filter frequencies\n */\nconst allpassFilterFreqs = [347, 113, 37];\n\n/**\n * JCReverb is a simple [Schroeder Reverberator](https://ccrma.stanford.edu/~jos/pasp/Schroeder_Reverberators.html)\n * tuned by John Chowning in 1970.\n * It is made up of three allpass filters and four {@link FeedbackCombFilter}.\n * JCReverb is now implemented with an AudioWorkletNode which may result on performance degradation on some platforms. Consider using {@link Reverb}.\n * @example\n * const reverb = new Tone.JCReverb(0.4).toDestination();\n * const delay = new Tone.FeedbackDelay(0.5);\n * // connecting the synth to reverb through delay\n * const synth = new Tone.DuoSynth().chain(delay, reverb);\n * synth.triggerAttackRelease(\"A4\", \"8n\");\n *\n * @category Effect\n */\nexport class JCReverb extends StereoEffect<JCReverbOptions> {\n\treadonly name: string = \"JCReverb\";\n\n\t/**\n\t * Room size control values.\n\t */\n\treadonly roomSize: Signal<\"normalRange\">;\n\n\t/**\n\t * Scale the room size\n\t */\n\tprivate _scaleRoomSize: Scale;\n\n\t/**\n\t * a series of allpass filters\n\t */\n\tprivate _allpassFilters: BiquadFilterNode[] = [];\n\n\t/**\n\t * parallel feedback comb filters\n\t */\n\tprivate _feedbackCombFilters: FeedbackCombFilter[] = [];\n\n\t/**\n\t * @param roomSize Correlated to the decay time.\n\t */\n\tconstructor(roomSize?: NormalRange);\n\tconstructor(options?: Partial<JCReverbOptions>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(\n\t\t\tJCReverb.getDefaults(),\n\t\t\targuments,\n\t\t\t[\"roomSize\"]\n\t\t);\n\t\tsuper(options);\n\n\t\tthis.roomSize = new Signal({\n\t\t\tcontext: this.context,\n\t\t\tvalue: options.roomSize,\n\t\t\tunits: \"normalRange\",\n\t\t});\n\t\tthis._scaleRoomSize = new Scale({\n\t\t\tcontext: this.context,\n\t\t\tmin: -0.733,\n\t\t\tmax: 0.197,\n\t\t});\n\n\t\t// make the allpass filters\n\t\tthis._allpassFilters = allpassFilterFreqs.map((freq) => {\n\t\t\tconst allpass = this.context.createBiquadFilter();\n\t\t\tallpass.type = \"allpass\";\n\t\t\tallpass.frequency.value = freq;\n\t\t\treturn allpass;\n\t\t});\n\n\t\t// and the comb filters\n\t\tthis._feedbackCombFilters = combFilterDelayTimes.map(\n\t\t\t(delayTime, index) => {\n\t\t\t\tconst fbcf = new FeedbackCombFilter({\n\t\t\t\t\tcontext: this.context,\n\t\t\t\t\tdelayTime,\n\t\t\t\t});\n\t\t\t\tthis._scaleRoomSize.connect(fbcf.resonance);\n\t\t\t\tfbcf.resonance.value = combFilterResonances[index];\n\t\t\t\tif (index < combFilterDelayTimes.length / 2) {\n\t\t\t\t\tthis.connectEffectLeft(...this._allpassFilters, fbcf);\n\t\t\t\t} else {\n\t\t\t\t\tthis.connectEffectRight(...this._allpassFilters, fbcf);\n\t\t\t\t}\n\t\t\t\treturn fbcf;\n\t\t\t}\n\t\t);\n\n\t\t// chain the allpass filters together\n\t\tthis.roomSize.connect(this._scaleRoomSize);\n\t\treadOnly(this, [\"roomSize\"]);\n\t}\n\n\tstatic getDefaults(): JCReverbOptions {\n\t\treturn Object.assign(StereoEffect.getDefaults(), {\n\t\t\troomSize: 0.5,\n\t\t});\n\t}\n\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis._allpassFilters.forEach((apf) => apf.disconnect());\n\t\tthis._feedbackCombFilters.forEach((fbcf) => fbcf.dispose());\n\t\tthis.roomSize.dispose();\n\t\tthis._scaleRoomSize.dispose();\n\t\treturn this;\n\t}\n}\n","import { Merge } from \"../component/channel/Merge.js\";\nimport { Gain } from \"../core/context/Gain.js\";\nimport { Seconds, Time } from \"../core/type/Units.js\";\nimport { optionsFromArguments } from \"../core/util/Defaults.js\";\nimport { Noise } from \"../source/Noise.js\";\nimport { Effect, EffectOptions } from \"./Effect.js\";\nimport { OfflineContext } from \"../core/context/OfflineContext.js\";\nimport { noOp } from \"../core/util/Interface.js\";\nimport { assertRange } from \"../core/util/Debug.js\";\n\nexport interface ReverbOptions extends EffectOptions {\n\tdecay: Seconds;\n\tpreDelay: Seconds;\n}\n\n/**\n * Simple convolution created with decaying noise.\n * Generates an Impulse Response Buffer\n * with Tone.Offline then feeds the IR into ConvolverNode.\n * The impulse response generation is async, so you have\n * to wait until {@link ready} resolves before it will make a sound.\n *\n * Inspiration from [ReverbGen](https://github.com/adelespinasse/reverbGen).\n * Copyright (c) 2014 Alan deLespinasse Apache 2.0 License.\n *\n * @category Effect\n */\nexport class Reverb extends Effect<ReverbOptions> {\n\treadonly name: string = \"Reverb\";\n\n\t/**\n\t * Convolver node\n\t */\n\tprivate _convolver: ConvolverNode = this.context.createConvolver();\n\n\t/**\n\t * The duration of the reverb.\n\t */\n\tprivate _decay: Seconds;\n\n\t/**\n\t * The amount of time before the reverb is fully ramped in.\n\t */\n\tprivate _preDelay: Seconds;\n\n\t/**\n\t * Resolves when the reverb buffer is generated. Whenever either {@link decay}\n\t * or {@link preDelay} are set, you have to wait until {@link ready} resolves\n\t * before the IR is generated with the latest values.\n\t */\n\tready: Promise<void> = Promise.resolve();\n\n\t/**\n\t * @param decay The amount of time it will reverberate for.\n\t */\n\tconstructor(decay?: Seconds);\n\tconstructor(options?: Partial<ReverbOptions>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(Reverb.getDefaults(), arguments, [\n\t\t\t\"decay\",\n\t\t]);\n\t\tsuper(options);\n\n\t\tconst decayTime = this.toSeconds(options.decay);\n\t\tassertRange(decayTime, 0.001);\n\t\tthis._decay = decayTime;\n\n\t\tconst preDelayTime = this.toSeconds(options.preDelay);\n\t\tassertRange(preDelayTime, 0);\n\t\tthis._preDelay = preDelayTime;\n\n\t\tthis.generate();\n\n\t\tthis.connectEffect(this._convolver);\n\t}\n\n\tstatic getDefaults(): ReverbOptions {\n\t\treturn Object.assign(Effect.getDefaults(), {\n\t\t\tdecay: 1.5,\n\t\t\tpreDelay: 0.01,\n\t\t});\n\t}\n\n\t/**\n\t * The duration of the reverb.\n\t */\n\tget decay(): Time {\n\t\treturn this._decay;\n\t}\n\tset decay(time) {\n\t\ttime = this.toSeconds(time);\n\t\tassertRange(time, 0.001);\n\t\tthis._decay = time;\n\t\tthis.generate();\n\t}\n\n\t/**\n\t * The amount of time before the reverb is fully ramped in.\n\t */\n\tget preDelay(): Time {\n\t\treturn this._preDelay;\n\t}\n\tset preDelay(time) {\n\t\ttime = this.toSeconds(time);\n\t\tassertRange(time, 0);\n\t\tthis._preDelay = time;\n\t\tthis.generate();\n\t}\n\n\t/**\n\t * Generate the Impulse Response. Returns a promise while the IR is being generated.\n\t * @return Promise which returns this object.\n\t */\n\tasync generate(): Promise<this> {\n\t\tconst previousReady = this.ready;\n\n\t\t// create a noise burst which decays over the duration in each channel\n\t\tconst context = new OfflineContext(\n\t\t\t2,\n\t\t\tthis._decay + this._preDelay,\n\t\t\tthis.context.sampleRate\n\t\t);\n\t\tconst noiseL = new Noise({ context });\n\t\tconst noiseR = new Noise({ context });\n\t\tconst merge = new Merge({ context });\n\t\tnoiseL.connect(merge, 0, 0);\n\t\tnoiseR.connect(merge, 0, 1);\n\t\tconst gainNode = new Gain({ context }).toDestination();\n\t\tmerge.connect(gainNode);\n\t\tnoiseL.start(0);\n\t\tnoiseR.start(0);\n\t\t// predelay\n\t\tgainNode.gain.setValueAtTime(0, 0);\n\t\tgainNode.gain.setValueAtTime(1, this._preDelay);\n\t\t// decay\n\t\tgainNode.gain.exponentialApproachValueAtTime(\n\t\t\t0,\n\t\t\tthis._preDelay,\n\t\t\tthis.decay\n\t\t);\n\n\t\t// render the buffer\n\t\tconst renderPromise = context.render();\n\t\tthis.ready = renderPromise.then(noOp);\n\n\t\t// wait for the previous `ready` to resolve\n\t\tawait previousReady;\n\t\t// set the buffer\n\t\tthis._convolver.buffer = (await renderPromise).get() as AudioBuffer;\n\n\t\treturn this;\n\t}\n\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis._convolver.disconnect();\n\t\treturn this;\n\t}\n}\n","import { BaseContext } from \"../../core/context/BaseContext.js\";\nimport { Gain } from \"../../core/context/Gain.js\";\nimport {\n\tToneAudioNode,\n\tToneAudioNodeOptions,\n} from \"../../core/context/ToneAudioNode.js\";\nimport { optionsFromArguments } from \"../../core/util/Defaults.js\";\n\nexport interface SoloOptions extends ToneAudioNodeOptions {\n\tsolo: boolean;\n}\n\n/**\n * Solo lets you isolate a specific audio stream. When an instance is set to `solo=true`,\n * it will mute all other instances of Solo.\n * @example\n * const soloA = new Tone.Solo().toDestination();\n * const oscA = new Tone.Oscillator(\"C4\", \"sawtooth\").connect(soloA);\n * const soloB = new Tone.Solo().toDestination();\n * const oscB = new Tone.Oscillator(\"E4\", \"square\").connect(soloB);\n * soloA.solo = true;\n * // no audio will pass through soloB\n * @category Component\n */\nexport class Solo extends ToneAudioNode<SoloOptions> {\n\treadonly name: string = \"Solo\";\n\n\treadonly input: Gain;\n\treadonly output: Gain;\n\n\t/**\n\t * @param solo If the connection should be initially solo'ed.\n\t */\n\tconstructor(solo?: boolean);\n\tconstructor(options?: Partial<SoloOptions>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(Solo.getDefaults(), arguments, [\n\t\t\t\"solo\",\n\t\t]);\n\t\tsuper(options);\n\n\t\tthis.input = this.output = new Gain({\n\t\t\tcontext: this.context,\n\t\t});\n\n\t\tif (!Solo._allSolos.has(this.context)) {\n\t\t\tSolo._allSolos.set(this.context, new Set());\n\t\t}\n\t\t(Solo._allSolos.get(this.context) as Set<Solo>).add(this);\n\n\t\t// set initially\n\t\tthis.solo = options.solo;\n\t}\n\n\tstatic getDefaults(): SoloOptions {\n\t\treturn Object.assign(ToneAudioNode.getDefaults(), {\n\t\t\tsolo: false,\n\t\t});\n\t}\n\n\t/**\n\t * Hold all of the solo'ed tracks belonging to a specific context\n\t */\n\tprivate static _allSolos: Map<BaseContext, Set<Solo>> = new Map();\n\n\t/**\n\t * Hold the currently solo'ed instance(s)\n\t */\n\tprivate static _soloed: Map<BaseContext, Set<Solo>> = new Map();\n\n\t/**\n\t * Isolates this instance and mutes all other instances of Solo.\n\t * Only one instance can be soloed at a time. A soloed\n\t * instance will report `solo=false` when another instance is soloed.\n\t */\n\tget solo(): boolean {\n\t\treturn this._isSoloed();\n\t}\n\tset solo(solo) {\n\t\tif (solo) {\n\t\t\tthis._addSolo();\n\t\t} else {\n\t\t\tthis._removeSolo();\n\t\t}\n\t\t(Solo._allSolos.get(this.context) as Set<Solo>).forEach((instance) =>\n\t\t\tinstance._updateSolo()\n\t\t);\n\t}\n\n\t/**\n\t * If the current instance is muted, i.e. another instance is soloed\n\t */\n\tget muted(): boolean {\n\t\treturn this.input.gain.value === 0;\n\t}\n\n\t/**\n\t * Add this to the soloed array\n\t */\n\tprivate _addSolo(): void {\n\t\tif (!Solo._soloed.has(this.context)) {\n\t\t\tSolo._soloed.set(this.context, new Set());\n\t\t}\n\t\t(Solo._soloed.get(this.context) as Set<Solo>).add(this);\n\t}\n\n\t/**\n\t * Remove this from the soloed array\n\t */\n\tprivate _removeSolo(): void {\n\t\tif (Solo._soloed.has(this.context)) {\n\t\t\t(Solo._soloed.get(this.context) as Set<Solo>).delete(this);\n\t\t}\n\t}\n\n\t/**\n\t * Is this on the soloed array\n\t */\n\tprivate _isSoloed(): boolean {\n\t\treturn (\n\t\t\tSolo._soloed.has(this.context) &&\n\t\t\t(Solo._soloed.get(this.context) as Set<Solo>).has(this)\n\t\t);\n\t}\n\n\t/**\n\t * Returns true if no one is soloed\n\t */\n\tprivate _noSolos(): boolean {\n\t\t// either does not have any soloed added\n\t\treturn (\n\t\t\t!Solo._soloed.has(this.context) ||\n\t\t\t// or has a solo set but doesn't include any items\n\t\t\t(Solo._soloed.has(this.context) &&\n\t\t\t\t(Solo._soloed.get(this.context) as Set<Solo>).size === 0)\n\t\t);\n\t}\n\n\t/**\n\t * Solo the current instance and unsolo all other instances.\n\t */\n\tprivate _updateSolo(): void {\n\t\tif (this._isSoloed()) {\n\t\t\tthis.input.gain.value = 1;\n\t\t} else if (this._noSolos()) {\n\t\t\t// no one is soloed\n\t\t\tthis.input.gain.value = 1;\n\t\t} else {\n\t\t\tthis.input.gain.value = 0;\n\t\t}\n\t}\n\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\t(Solo._allSolos.get(this.context) as Set<Solo>).delete(this);\n\t\tthis._removeSolo();\n\t\treturn this;\n\t}\n}\n","import { readOnly } from \"../../core/util/Interface.js\";\nimport { Param } from \"../../core/context/Param.js\";\nimport {\n\tInputNode,\n\tOutputNode,\n\tToneAudioNode,\n\tToneAudioNodeOptions,\n} from \"../../core/context/ToneAudioNode.js\";\nimport { AudioRange, Decibels } from \"../../core/type/Units.js\";\nimport { optionsFromArguments } from \"../../core/util/Defaults.js\";\nimport { Panner } from \"./Panner.js\";\nimport { Volume } from \"./Volume.js\";\n\nexport interface PanVolOptions extends ToneAudioNodeOptions {\n\tpan: AudioRange;\n\tvolume: Decibels;\n\tmute: boolean;\n\tchannelCount: number;\n}\n\n/**\n * PanVol is a Tone.Panner and Tone.Volume in one.\n * @example\n * // pan the incoming signal left and drop the volume\n * const panVol = new Tone.PanVol(-0.25, -12).toDestination();\n * const osc = new Tone.Oscillator().connect(panVol).start();\n * @category Component\n */\nexport class PanVol extends ToneAudioNode<PanVolOptions> {\n\treadonly name: string = \"PanVol\";\n\n\treadonly input: InputNode;\n\treadonly output: OutputNode;\n\n\t/**\n\t * The panning node\n\t */\n\tprivate _panner: Panner;\n\n\t/**\n\t * The L/R panning control. -1 = hard left, 1 = hard right.\n\t * @min -1\n\t * @max 1\n\t */\n\treadonly pan: Param<\"audioRange\">;\n\n\t/**\n\t * The volume node\n\t */\n\tprivate _volume: Volume;\n\n\t/**\n\t * The volume control in decibels.\n\t */\n\treadonly volume: Param<\"decibels\">;\n\n\t/**\n\t * @param pan the initial pan\n\t * @param volume The output volume.\n\t */\n\tconstructor(pan?: AudioRange, volume?: Decibels);\n\tconstructor(options?: Partial<PanVolOptions>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(PanVol.getDefaults(), arguments, [\n\t\t\t\"pan\",\n\t\t\t\"volume\",\n\t\t]);\n\t\tsuper(options);\n\n\t\tthis._panner = this.input = new Panner({\n\t\t\tcontext: this.context,\n\t\t\tpan: options.pan,\n\t\t\tchannelCount: options.channelCount,\n\t\t});\n\t\tthis.pan = this._panner.pan;\n\t\tthis._volume = this.output = new Volume({\n\t\t\tcontext: this.context,\n\t\t\tvolume: options.volume,\n\t\t});\n\t\tthis.volume = this._volume.volume;\n\n\t\t// connections\n\t\tthis._panner.connect(this._volume);\n\t\tthis.mute = options.mute;\n\n\t\treadOnly(this, [\"pan\", \"volume\"]);\n\t}\n\n\tstatic getDefaults(): PanVolOptions {\n\t\treturn Object.assign(ToneAudioNode.getDefaults(), {\n\t\t\tmute: false,\n\t\t\tpan: 0,\n\t\t\tvolume: 0,\n\t\t\tchannelCount: 1,\n\t\t});\n\t}\n\n\t/**\n\t * Mute/unmute the volume\n\t */\n\tget mute(): boolean {\n\t\treturn this._volume.mute;\n\t}\n\tset mute(mute) {\n\t\tthis._volume.mute = mute;\n\t}\n\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis._panner.dispose();\n\t\tthis.pan.dispose();\n\t\tthis._volume.dispose();\n\t\tthis.volume.dispose();\n\t\treturn this;\n\t}\n}\n","import { AudioRange, Decibels } from \"../../core/type/Units.js\";\nimport {\n\tInputNode,\n\tOutputNode,\n\tToneAudioNode,\n\tToneAudioNodeOptions,\n} from \"../../core/context/ToneAudioNode.js\";\nimport { optionsFromArguments } from \"../../core/util/Defaults.js\";\nimport { Solo } from \"./Solo.js\";\nimport { PanVol } from \"./PanVol.js\";\nimport { Param } from \"../../core/context/Param.js\";\nimport { readOnly } from \"../../core/util/Interface.js\";\nimport { Gain } from \"../../core/context/Gain.js\";\n\nexport interface ChannelOptions extends ToneAudioNodeOptions {\n\tpan: AudioRange;\n\tvolume: Decibels;\n\tsolo: boolean;\n\tmute: boolean;\n\tchannelCount: number;\n}\n\n/**\n * Channel provides a channel strip interface with volume, pan, solo and mute controls.\n * @see {@link PanVol} and {@link Solo}\n * @example\n * // pan the incoming signal left and drop the volume 12db\n * const channel = new Tone.Channel(-0.25, -12);\n * @category Component\n */\nexport class Channel extends ToneAudioNode<ChannelOptions> {\n\treadonly name: string = \"Channel\";\n\n\treadonly input: InputNode;\n\treadonly output: OutputNode;\n\n\t/**\n\t * The soloing interface\n\t */\n\tprivate _solo: Solo;\n\n\t/**\n\t * The panning and volume node\n\t */\n\tprivate _panVol: PanVol;\n\n\t/**\n\t * The L/R panning control. -1 = hard left, 1 = hard right.\n\t * @min -1\n\t * @max 1\n\t */\n\treadonly pan: Param<\"audioRange\">;\n\n\t/**\n\t * The volume control in decibels.\n\t */\n\treadonly volume: Param<\"decibels\">;\n\n\t/**\n\t * @param volume The output volume.\n\t * @param pan the initial pan\n\t */\n\tconstructor(volume?: Decibels, pan?: AudioRange);\n\tconstructor(options?: Partial<ChannelOptions>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(Channel.getDefaults(), arguments, [\n\t\t\t\"volume\",\n\t\t\t\"pan\",\n\t\t]);\n\t\tsuper(options);\n\n\t\tthis._solo = this.input = new Solo({\n\t\t\tsolo: options.solo,\n\t\t\tcontext: this.context,\n\t\t});\n\t\tthis._panVol = this.output = new PanVol({\n\t\t\tcontext: this.context,\n\t\t\tpan: options.pan,\n\t\t\tvolume: options.volume,\n\t\t\tmute: options.mute,\n\t\t\tchannelCount: options.channelCount,\n\t\t});\n\t\tthis.pan = this._panVol.pan;\n\t\tthis.volume = this._panVol.volume;\n\n\t\tthis._solo.connect(this._panVol);\n\t\treadOnly(this, [\"pan\", \"volume\"]);\n\t}\n\n\tstatic getDefaults(): ChannelOptions {\n\t\treturn Object.assign(ToneAudioNode.getDefaults(), {\n\t\t\tpan: 0,\n\t\t\tvolume: 0,\n\t\t\tmute: false,\n\t\t\tsolo: false,\n\t\t\tchannelCount: 1,\n\t\t});\n\t}\n\n\t/**\n\t * Solo/unsolo the channel. Soloing is only relative to other {@link Channel}s and {@link Solo} instances\n\t */\n\tget solo(): boolean {\n\t\treturn this._solo.solo;\n\t}\n\tset solo(solo) {\n\t\tthis._solo.solo = solo;\n\t}\n\n\t/**\n\t * If the current instance is muted, i.e. another instance is soloed,\n\t * or the channel is muted\n\t */\n\tget muted(): boolean {\n\t\treturn this._solo.muted || this.mute;\n\t}\n\n\t/**\n\t * Mute/unmute the volume\n\t */\n\tget mute(): boolean {\n\t\treturn this._panVol.mute;\n\t}\n\tset mute(mute) {\n\t\tthis._panVol.mute = mute;\n\t}\n\n\t/**\n\t * Store the send/receive channels by name.\n\t */\n\tprivate static buses: Map<string, Gain> = new Map();\n\n\t/**\n\t * Get the gain node belonging to the bus name. Create it if\n\t * it doesn't exist\n\t * @param name The bus name\n\t */\n\tprivate _getBus(name: string): Gain {\n\t\tif (!Channel.buses.has(name)) {\n\t\t\tChannel.buses.set(name, new Gain({ context: this.context }));\n\t\t}\n\t\treturn Channel.buses.get(name) as Gain;\n\t}\n\n\t/**\n\t * Send audio to another channel using a string. `send` is a lot like\n\t * {@link connect}, except it uses a string instead of an object. This can\n\t * be useful in large applications to decouple sections since {@link send}\n\t * and {@link receive} can be invoked separately in order to connect an object\n\t * @param name The channel name to send the audio\n\t * @param volume The amount of the signal to send.\n\t * \tDefaults to 0db, i.e. send the entire signal\n\t * @returns Returns the gain node of this connection.\n\t */\n\tsend(name: string, volume: Decibels = 0): Gain<\"decibels\"> {\n\t\tconst bus = this._getBus(name);\n\t\tconst sendKnob = new Gain({\n\t\t\tcontext: this.context,\n\t\t\tunits: \"decibels\",\n\t\t\tgain: volume,\n\t\t});\n\t\tthis.connect(sendKnob);\n\t\tsendKnob.connect(bus);\n\t\treturn sendKnob;\n\t}\n\n\t/**\n\t * Receive audio from a channel which was connected with {@link send}.\n\t * @param name The channel name to receive audio from.\n\t */\n\treceive(name: string): this {\n\t\tconst bus = this._getBus(name);\n\t\tbus.connect(this);\n\t\treturn this;\n\t}\n\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis._panVol.dispose();\n\t\tthis.pan.dispose();\n\t\tthis.volume.dispose();\n\t\tthis._solo.dispose();\n\t\treturn this;\n\t}\n}\n","import { Param } from \"../../core/context/Param.js\";\nimport {\n\tToneAudioNode,\n\tToneAudioNodeOptions,\n} from \"../../core/context/ToneAudioNode.js\";\nimport { Degrees, GainFactor } from \"../../core/type/Units.js\";\nimport { optionsFromArguments } from \"../../core/util/Defaults.js\";\nimport \"../../core/context/Listener.js\";\n\nexport interface Panner3DOptions extends ToneAudioNodeOptions {\n\tconeInnerAngle: Degrees;\n\tconeOuterAngle: Degrees;\n\tconeOuterGain: GainFactor;\n\tdistanceModel: DistanceModelType;\n\tmaxDistance: number;\n\torientationX: number;\n\torientationY: number;\n\torientationZ: number;\n\tpanningModel: PanningModelType;\n\tpositionX: number;\n\tpositionY: number;\n\tpositionZ: number;\n\trefDistance: number;\n\trolloffFactor: number;\n}\n\n/**\n * A spatialized panner node which supports equalpower or HRTF panning.\n * @category Component\n */\nexport class Panner3D extends ToneAudioNode<Panner3DOptions> {\n\treadonly name: string = \"Panner3D\";\n\n\t/**\n\t * The panning object\n\t */\n\tprivate _panner: PannerNode;\n\treadonly input: PannerNode;\n\treadonly output: PannerNode;\n\n\treadonly positionX: Param<\"number\">;\n\treadonly positionY: Param<\"number\">;\n\treadonly positionZ: Param<\"number\">;\n\n\treadonly orientationX: Param<\"number\">;\n\treadonly orientationY: Param<\"number\">;\n\treadonly orientationZ: Param<\"number\">;\n\n\t/**\n\t * @param positionX The initial x position.\n\t * @param positionY The initial y position.\n\t * @param positionZ The initial z position.\n\t */\n\tconstructor(positionX: number, positionY: number, positionZ: number);\n\tconstructor(options?: Partial<Panner3DOptions>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(\n\t\t\tPanner3D.getDefaults(),\n\t\t\targuments,\n\t\t\t[\"positionX\", \"positionY\", \"positionZ\"]\n\t\t);\n\t\tsuper(options);\n\n\t\tthis._panner = this.input = this.output = this.context.createPanner();\n\t\t// set some values\n\t\tthis.panningModel = options.panningModel;\n\t\tthis.maxDistance = options.maxDistance;\n\t\tthis.distanceModel = options.distanceModel;\n\t\tthis.coneOuterGain = options.coneOuterGain;\n\t\tthis.coneOuterAngle = options.coneOuterAngle;\n\t\tthis.coneInnerAngle = options.coneInnerAngle;\n\t\tthis.refDistance = options.refDistance;\n\t\tthis.rolloffFactor = options.rolloffFactor;\n\n\t\tthis.positionX = new Param({\n\t\t\tcontext: this.context,\n\t\t\tparam: this._panner.positionX,\n\t\t\tvalue: options.positionX,\n\t\t});\n\t\tthis.positionY = new Param({\n\t\t\tcontext: this.context,\n\t\t\tparam: this._panner.positionY,\n\t\t\tvalue: options.positionY,\n\t\t});\n\t\tthis.positionZ = new Param({\n\t\t\tcontext: this.context,\n\t\t\tparam: this._panner.positionZ,\n\t\t\tvalue: options.positionZ,\n\t\t});\n\t\tthis.orientationX = new Param({\n\t\t\tcontext: this.context,\n\t\t\tparam: this._panner.orientationX,\n\t\t\tvalue: options.orientationX,\n\t\t});\n\t\tthis.orientationY = new Param({\n\t\t\tcontext: this.context,\n\t\t\tparam: this._panner.orientationY,\n\t\t\tvalue: options.orientationY,\n\t\t});\n\t\tthis.orientationZ = new Param({\n\t\t\tcontext: this.context,\n\t\t\tparam: this._panner.orientationZ,\n\t\t\tvalue: options.orientationZ,\n\t\t});\n\t}\n\n\tstatic getDefaults(): Panner3DOptions {\n\t\treturn Object.assign(ToneAudioNode.getDefaults(), {\n\t\t\tconeInnerAngle: 360,\n\t\t\tconeOuterAngle: 360,\n\t\t\tconeOuterGain: 0,\n\t\t\tdistanceModel: \"inverse\" as DistanceModelType,\n\t\t\tmaxDistance: 10000,\n\t\t\torientationX: 0,\n\t\t\torientationY: 0,\n\t\t\torientationZ: 0,\n\t\t\tpanningModel: \"equalpower\" as PanningModelType,\n\t\t\tpositionX: 0,\n\t\t\tpositionY: 0,\n\t\t\tpositionZ: 0,\n\t\t\trefDistance: 1,\n\t\t\trolloffFactor: 1,\n\t\t});\n\t}\n\n\t/**\n\t * Sets the position of the source in 3d space.\n\t */\n\tsetPosition(x: number, y: number, z: number): this {\n\t\tthis.positionX.value = x;\n\t\tthis.positionY.value = y;\n\t\tthis.positionZ.value = z;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the orientation of the source in 3d space.\n\t */\n\tsetOrientation(x: number, y: number, z: number): this {\n\t\tthis.orientationX.value = x;\n\t\tthis.orientationY.value = y;\n\t\tthis.orientationZ.value = z;\n\t\treturn this;\n\t}\n\n\t/**\n\t * The panning model. Either \"equalpower\" or \"HRTF\".\n\t */\n\tget panningModel(): PanningModelType {\n\t\treturn this._panner.panningModel;\n\t}\n\tset panningModel(val) {\n\t\tthis._panner.panningModel = val;\n\t}\n\n\t/**\n\t * A reference distance for reducing volume as source move further from the listener\n\t */\n\tget refDistance(): number {\n\t\treturn this._panner.refDistance;\n\t}\n\tset refDistance(val) {\n\t\tthis._panner.refDistance = val;\n\t}\n\n\t/**\n\t * Describes how quickly the volume is reduced as source moves away from listener.\n\t */\n\tget rolloffFactor(): number {\n\t\treturn this._panner.rolloffFactor;\n\t}\n\tset rolloffFactor(val) {\n\t\tthis._panner.rolloffFactor = val;\n\t}\n\n\t/**\n\t * The distance model used by, \"linear\", \"inverse\", or \"exponential\".\n\t */\n\tget distanceModel(): DistanceModelType {\n\t\treturn this._panner.distanceModel;\n\t}\n\tset distanceModel(val) {\n\t\tthis._panner.distanceModel = val;\n\t}\n\n\t/**\n\t * The angle, in degrees, inside of which there will be no volume reduction\n\t */\n\tget coneInnerAngle(): Degrees {\n\t\treturn this._panner.coneInnerAngle;\n\t}\n\tset coneInnerAngle(val) {\n\t\tthis._panner.coneInnerAngle = val;\n\t}\n\n\t/**\n\t * The angle, in degrees, outside of which the volume will be reduced\n\t * to a constant value of coneOuterGain\n\t */\n\tget coneOuterAngle(): Degrees {\n\t\treturn this._panner.coneOuterAngle;\n\t}\n\tset coneOuterAngle(val) {\n\t\tthis._panner.coneOuterAngle = val;\n\t}\n\n\t/**\n\t * The gain outside of the coneOuterAngle\n\t */\n\tget coneOuterGain(): GainFactor {\n\t\treturn this._panner.coneOuterGain;\n\t}\n\tset coneOuterGain(val) {\n\t\tthis._panner.coneOuterGain = val;\n\t}\n\n\t/**\n\t * The maximum distance between source and listener,\n\t * after which the volume will not be reduced any further.\n\t */\n\tget maxDistance(): number {\n\t\treturn this._panner.maxDistance;\n\t}\n\tset maxDistance(val) {\n\t\tthis._panner.maxDistance = val;\n\t}\n\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis._panner.disconnect();\n\t\tthis.orientationX.dispose();\n\t\tthis.orientationY.dispose();\n\t\tthis.orientationZ.dispose();\n\t\tthis.positionX.dispose();\n\t\tthis.positionY.dispose();\n\t\tthis.positionZ.dispose();\n\t\treturn this;\n\t}\n}\n","import { Param } from \"../../core/context/Param.js\";\nimport {\n\tToneAudioNode,\n\tToneAudioNodeOptions,\n} from \"../../core/context/ToneAudioNode.js\";\nimport { Decibels, Positive, Time } from \"../../core/type/Units.js\";\nimport { optionsFromArguments } from \"../../core/util/Defaults.js\";\nimport { readOnly } from \"../../core/util/Interface.js\";\n\nexport interface CompressorOptions extends ToneAudioNodeOptions {\n\tattack: Time;\n\tknee: Decibels;\n\tratio: Positive;\n\trelease: Time;\n\tthreshold: Decibels;\n}\n\n/**\n * Compressor is a thin wrapper around the Web Audio\n * [DynamicsCompressorNode](http://webaudio.github.io/web-audio-api/#the-dynamicscompressornode-interface).\n * Compression reduces the volume of loud sounds or amplifies quiet sounds\n * by narrowing or \"compressing\" an audio signal's dynamic range.\n * Read more on [Wikipedia](https://en.wikipedia.org/wiki/Dynamic_range_compression).\n * @example\n * const comp = new Tone.Compressor(-30, 3);\n * @category Component\n */\nexport class Compressor extends ToneAudioNode<CompressorOptions> {\n\treadonly name: string = \"Compressor\";\n\n\t/**\n\t * the compressor node\n\t */\n\tprivate _compressor: DynamicsCompressorNode =\n\t\tthis.context.createDynamicsCompressor();\n\treadonly input = this._compressor;\n\treadonly output = this._compressor;\n\n\t/**\n\t * The decibel value above which the compression will start taking effect.\n\t * @min -100\n\t * @max 0\n\t */\n\treadonly threshold: Param<\"decibels\">;\n\n\t/**\n\t * The amount of time (in seconds) to reduce the gain by 10dB.\n\t * @min 0\n\t * @max 1\n\t */\n\treadonly attack: Param<\"time\">;\n\n\t/**\n\t * The amount of time (in seconds) to increase the gain by 10dB.\n\t * @min 0\n\t * @max 1\n\t */\n\treadonly release: Param<\"time\">;\n\n\t/**\n\t * A decibel value representing the range above the threshold where the\n\t * curve smoothly transitions to the \"ratio\" portion.\n\t * @min 0\n\t * @max 40\n\t */\n\treadonly knee: Param<\"decibels\">;\n\n\t/**\n\t * The amount of dB change in input for a 1 dB change in output.\n\t * @min 1\n\t * @max 20\n\t */\n\treadonly ratio: Param<\"positive\">;\n\n\t/**\n\t * @param threshold The value above which the compression starts to be applied.\n\t * @param ratio The gain reduction ratio.\n\t */\n\tconstructor(threshold?: Decibels, ratio?: Positive);\n\tconstructor(options?: Partial<CompressorOptions>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(\n\t\t\tCompressor.getDefaults(),\n\t\t\targuments,\n\t\t\t[\"threshold\", \"ratio\"]\n\t\t);\n\t\tsuper(options);\n\n\t\tthis.threshold = new Param({\n\t\t\tminValue: this._compressor.threshold.minValue,\n\t\t\tmaxValue: this._compressor.threshold.maxValue,\n\t\t\tcontext: this.context,\n\t\t\tconvert: false,\n\t\t\tparam: this._compressor.threshold,\n\t\t\tunits: \"decibels\",\n\t\t\tvalue: options.threshold,\n\t\t});\n\n\t\tthis.attack = new Param({\n\t\t\tminValue: this._compressor.attack.minValue,\n\t\t\tmaxValue: this._compressor.attack.maxValue,\n\t\t\tcontext: this.context,\n\t\t\tparam: this._compressor.attack,\n\t\t\tunits: \"time\",\n\t\t\tvalue: options.attack,\n\t\t});\n\n\t\tthis.release = new Param({\n\t\t\tminValue: this._compressor.release.minValue,\n\t\t\tmaxValue: this._compressor.release.maxValue,\n\t\t\tcontext: this.context,\n\t\t\tparam: this._compressor.release,\n\t\t\tunits: \"time\",\n\t\t\tvalue: options.release,\n\t\t});\n\n\t\tthis.knee = new Param({\n\t\t\tminValue: this._compressor.knee.minValue,\n\t\t\tmaxValue: this._compressor.knee.maxValue,\n\t\t\tcontext: this.context,\n\t\t\tconvert: false,\n\t\t\tparam: this._compressor.knee,\n\t\t\tunits: \"decibels\",\n\t\t\tvalue: options.knee,\n\t\t});\n\n\t\tthis.ratio = new Param({\n\t\t\tminValue: this._compressor.ratio.minValue,\n\t\t\tmaxValue: this._compressor.ratio.maxValue,\n\t\t\tcontext: this.context,\n\t\t\tconvert: false,\n\t\t\tparam: this._compressor.ratio,\n\t\t\tunits: \"positive\",\n\t\t\tvalue: options.ratio,\n\t\t});\n\n\t\t// set the defaults\n\t\treadOnly(this, [\"knee\", \"release\", \"attack\", \"ratio\", \"threshold\"]);\n\t}\n\n\tstatic getDefaults(): CompressorOptions {\n\t\treturn Object.assign(ToneAudioNode.getDefaults(), {\n\t\t\tattack: 0.003,\n\t\t\tknee: 30,\n\t\t\tratio: 12,\n\t\t\trelease: 0.25,\n\t\t\tthreshold: -24,\n\t\t});\n\t}\n\n\t/**\n\t * A read-only decibel value for metering purposes, representing the current amount of gain\n\t * reduction that the compressor is applying to the signal. If fed no signal the value will be 0 (no gain reduction).\n\t */\n\tget reduction(): Decibels {\n\t\treturn this._compressor.reduction;\n\t}\n\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis._compressor.disconnect();\n\t\tthis.attack.dispose();\n\t\tthis.release.dispose();\n\t\tthis.threshold.dispose();\n\t\tthis.ratio.dispose();\n\t\tthis.knee.dispose();\n\t\treturn this;\n\t}\n}\n","import {\n\tInputNode,\n\tOutputNode,\n\tToneAudioNode,\n\tToneAudioNodeOptions,\n} from \"../../core/context/ToneAudioNode.js\";\nimport { Decibels } from \"../../core/type/Units.js\";\nimport { optionsFromArguments } from \"../../core/util/Defaults.js\";\nimport { Compressor } from \"./Compressor.js\";\nimport { Param } from \"../../core/context/Param.js\";\nimport { readOnly } from \"../../core/util/Interface.js\";\n\nexport interface LimiterOptions extends ToneAudioNodeOptions {\n\tthreshold: Decibels;\n}\n\n/**\n * Limiter will limit the loudness of an incoming signal.\n * Under the hood it's composed of a {@link Compressor} with a fast attack\n * and release and max compression ratio.\n *\n * @example\n * const limiter = new Tone.Limiter(-20).toDestination();\n * const oscillator = new Tone.Oscillator().connect(limiter);\n * oscillator.start();\n * @category Component\n */\nexport class Limiter extends ToneAudioNode<LimiterOptions> {\n\treadonly name: string = \"Limiter\";\n\n\treadonly input: InputNode;\n\treadonly output: OutputNode;\n\n\t/**\n\t * The compressor which does the limiting\n\t */\n\tprivate _compressor: Compressor;\n\n\treadonly threshold: Param<\"decibels\">;\n\n\t/**\n\t * @param threshold The threshold above which the gain reduction is applied.\n\t */\n\tconstructor(threshold?: Decibels);\n\tconstructor(options?: Partial<LimiterOptions>);\n\tconstructor() {\n\t\tconst options = optionsFromArguments(Limiter.getDefaults(), arguments, [\n\t\t\t\"threshold\",\n\t\t]);\n\t\tsuper(options);\n\n\t\tthis._compressor =\n\t\t\tthis.input =\n\t\t\tthis.output =\n\t\t\t\tnew Compressor({\n\t\t\t\t\tcontext: this.context,\n\t\t\t\t\tratio: 20,\n\t\t\t\t\tattack: 0.003,\n\t\t\t\t\trelease: 0.01,\n\t\t\t\t\tthreshold: options.threshold,\n\t\t\t\t});\n\n\t\tthis.threshold = this._compressor.threshold;\n\t\treadOnly(this, \"threshold\");\n\t}\n\n\tstatic getDefaults(): LimiterOptions {\n\t\treturn Object.assign(ToneAudioNode.getDefaults(), {\n\t\t\tthreshold: -12,\n\t\t});\n\t}\n\n\t/**\n\t * A read-only decibel value for metering purposes, representing the current amount of gain\n\t * reduction that the compressor is applying to the signal.\n\t */\n\tget reduction(): Decibels {\n\t\treturn this._compressor.reduction;\n\t}\n\n\tdispose(): this {\n\t\tsuper.dispose();\n\t\tthis._compressor.dispose();\n\t\tthis.threshold.dispose();\n\t\treturn this;\n\t}\n}\n","export { getContext, setContext } from \"./core/Global.js\";\nimport { Context } from \"./core/context/Context.js\";\nexport * from \"./classes.js\";\nexport * from \"./version.js\";\nimport { getContext } from \"./core/Global.js\";\nimport { ToneAudioBuffer } from \"./core/context/ToneAudioBuffer.js\";\nexport { start } from \"./core/Global.js\";\nimport { Seconds } from \"./core/type/Units.js\";\nexport { supported } from \"./core/context/AudioContext.js\";\nimport type { TransportClass } from \"./core/clock/Transport.js\";\nimport type { DestinationClass } from \"./core/context/Destination.js\";\nimport type { DrawClass } from \"./core/util/Draw.js\";\nimport type { ListenerClass } from \"./core/context/Listener.js\";\n\n/**\n * The current audio context time of the global {@link BaseContext}.\n * @see {@link Context.now}\n * @category Core\n */\nexport function now(): Seconds {\n\treturn getContext().now();\n}\n\n/**\n * The current audio context time of the global {@link Context} without the {@link Context.lookAhead}\n * @see {@link Context.immediate}\n * @category Core\n */\nexport function immediate(): Seconds {\n\treturn getContext().immediate();\n}\n\n/**\n * The Transport object belonging to the global Tone.js Context.\n * @see {@link TransportClass}\n * @category Core\n * @deprecated Use {@link getTransport} instead\n */\nexport const Transport = getContext().transport;\n\n/**\n * The Transport object belonging to the global Tone.js Context.\n * @see {@link TransportClass}\n * @category Core\n */\nexport function getTransport(): TransportClass {\n\treturn getContext().transport;\n}\n\n/**\n * The Destination (output) belonging to the global Tone.js Context.\n * @see {@link DestinationClass}\n * @category Core\n * @deprecated Use {@link getDestination} instead\n */\nexport const Destination = getContext().destination;\n\n/**\n * @deprecated Use {@link getDestination} instead\n */\nexport const Master = getContext().destination;\n\n/**\n * The Destination (output) belonging to the global Tone.js Context.\n * @see {@link DestinationClass}\n * @category Core\n */\nexport function getDestination(): DestinationClass {\n\treturn getContext().destination;\n}\n\n/**\n * The {@link ListenerClass} belonging to the global Tone.js Context.\n * @category Core\n * @deprecated Use {@link getListener} instead\n */\nexport const Listener = getContext().listener;\n\n/**\n * The {@link ListenerClass} belonging to the global Tone.js Context.\n * @category Core\n */\nexport function getListener(): ListenerClass {\n\treturn getContext().listener;\n}\n\n/**\n * Draw is used to synchronize the draw frame with the Transport's callbacks.\n * @see {@link DrawClass}\n * @category Core\n * @deprecated Use {@link getDraw} instead\n */\nexport const Draw = getContext().draw;\n\n/**\n * Get the singleton attached to the global context.\n * Draw is used to synchronize the draw frame with the Transport's callbacks.\n * @see {@link DrawClass}\n * @category Core\n */\nexport function getDraw(): DrawClass {\n\treturn getContext().draw;\n}\n\n/**\n * A reference to the global context\n * @see {@link Context}\n * @deprecated Use {@link getContext} instead\n */\nexport const context = getContext();\n\n/**\n * Promise which resolves when all of the loading promises are resolved.\n * Alias for static {@link ToneAudioBuffer.loaded} method.\n * @category Core\n */\nexport function loaded() {\n\treturn ToneAudioBuffer.loaded();\n}\n\n// this fills in name changes from 13.x to 14.x\nimport { ToneAudioBuffers } from \"./core/context/ToneAudioBuffers.js\";\nimport { ToneBufferSource } from \"./source/buffer/ToneBufferSource.js\";\n/** @deprecated Use {@link ToneAudioBuffer} */\nexport const Buffer: typeof ToneAudioBuffer = ToneAudioBuffer;\n/** @deprecated Use {@link ToneAudioBuffers} */\nexport const Buffers: typeof ToneAudioBuffers = ToneAudioBuffers;\n/** @deprecated Use {@link ToneBufferSource} */\nexport const BufferSource: typeof ToneBufferSource = ToneBufferSource;\n","export const clamp = (v: number, a: number, b: number): number => Math.min(b, Math.max(a, v))\n\nexport const lerp = (a: number, b: number, t: number): number => a + (b - a) * t\n\n/** Normalized position of v in [a, b], clamped to [0, 1]. */\nexport const norm = (v: number, a: number, b: number): number => clamp((v - a) / (b - a), 0, 1)\n\n/** FNV-1a 32-bit — stable, dependency-free hash for site identity (MAPPING.md §0). */\nexport function fnv1a(str: string): number {\n let h = 0x811c9dc5\n for (let i = 0; i < str.length; i++) {\n h ^= str.charCodeAt(i)\n h = Math.imul(h, 0x01000193)\n }\n return h >>> 0\n}\n","import { clamp, fnv1a } from './util'\n\n/** MAPPING.md §0 — the five scales reachable from a hostname hash. */\nexport const SCALES: Record<string, readonly number[]> = {\n pentMajor: [0, 2, 4, 7, 9],\n pentMinor: [0, 3, 5, 7, 10],\n dorian: [0, 2, 3, 5, 7, 9, 10],\n lydian: [0, 2, 4, 6, 7, 9, 11],\n mixolydian: [0, 2, 4, 5, 7, 9, 10],\n} as const\n\nexport const SCALE_NAMES = Object.keys(SCALES) as (keyof typeof SCALES)[]\n\nexport const OCTAVES = 3\n/** C3 — the bottom of the 3-octave pitch space. */\nexport const BASE_MIDI = 48\n\nconst NOTE_TO_PC: Record<string, number> = {\n C: 0, 'C#': 1, Db: 1, D: 2, 'D#': 3, Eb: 3, E: 4, F: 5, 'F#': 6,\n Gb: 6, G: 7, 'G#': 8, Ab: 8, A: 9, 'A#': 10, Bb: 10, B: 11,\n}\n\nconst PC_TO_NOTE = ['C', 'C#', 'D', 'Eb', 'E', 'F', 'F#', 'G', 'Ab', 'A', 'Bb', 'B'] as const\n\nexport interface SiteKey {\n root: number\n scaleName: string\n scale: readonly number[]\n label: string\n}\n\n/** Deterministic per-domain musical identity (T8 audio branding). Same host → same key, always. */\nexport function siteKey(hostname: string): SiteKey {\n const host = hostname || 'localhost'\n const h = fnv1a(host)\n const root = h % 12\n const scaleName = SCALE_NAMES[(h >>> 4) % SCALE_NAMES.length] as string\n const scale = SCALES[scaleName] as readonly number[]\n return { root, scaleName, scale, label: `${PC_TO_NOTE[root]} ${scaleName}` }\n}\n\n/** Parse \"D dorian\" / \"Eb pentMinor\" → SiteKey. Returns null when unrecognized. */\nexport function parseKey(spec: string): SiteKey | null {\n const m = spec.trim().match(/^([A-Ga-g][#b]?)\\s+(\\w+)$/)\n if (!m) return null\n const note = (m[1] as string).charAt(0).toUpperCase() + (m[1] as string).slice(1)\n const root = NOTE_TO_PC[note]\n const scaleName = m[2] as string\n const scale = SCALES[scaleName]\n if (root === undefined || !scale) return null\n return { root, scaleName, scale, label: `${PC_TO_NOTE[root]} ${scaleName}` }\n}\n\n/**\n * The Musical Quantizer (Invariant #2): degree ∈ [0,1] → MIDI note inside the key,\n * laid across OCTAVES octaves from BASE_MIDI + root. stepOffset shifts by whole scale steps\n * (sibling melodies S4, heading registers S6, kiki nudge G10).\n */\nexport function degreeToMidi(degree: number, key: SiteKey, stepOffset = 0): number {\n const steps = key.scale.length * OCTAVES\n let idx = Math.round(clamp(degree, 0, 1) * (steps - 1)) + Math.round(stepOffset)\n idx = clamp(idx, 0, steps - 1)\n const oct = Math.floor(idx / key.scale.length)\n const pc = key.scale[idx % key.scale.length] as number\n return BASE_MIDI + key.root + oct * 12 + pc\n}\n\nexport const midiToFreq = (m: number): number => 440 * Math.pow(2, (m - 69) / 12)\n\n/**\n * Walk N scale steps up/down from a midi note, staying on the key's pitch classes\n * (the ribbon controller's quantizer — MODULAR.md §3; Invariant #2 holds under drag).\n */\nexport function stepInScale(midi: number, key: SiteKey, steps: number): number {\n if (steps === 0) return midi\n const pcs = key.scale.map((s) => (s + key.root) % 12)\n const dir = steps > 0 ? 1 : -1\n let m = midi\n for (let i = 0; i < Math.abs(steps); i++) {\n do {\n m += dir\n } while (!pcs.includes(((m % 12) + 12) % 12) && m > 12 && m < 120)\n }\n return clamp(m, 12, 120)\n}\n\nexport function midiToNoteName(m: number): string {\n const pc = ((m % 12) + 12) % 12\n return `${PC_TO_NOTE[pc]}${Math.floor(m / 12) - 1}`\n}\n","/**\n * The Modular patch — MODULAR.md made executable. CSS properties plug modulation cables:\n * border-width drives the wavefolder, texture×edge sets FM, mass thickens unison, animation\n * and dashed borders patch the LFO. Pure: no DOM, no Tone.\n */\nimport { clamp } from './util'\n\nexport interface ModularVisuals {\n /** seconds; 0 = no animation */\n animationS: number\n borderStyle: 'solid' | 'dashed' | 'dotted' | 'none'\n borderWidthPx: number\n /** seconds; 0 = no transition */\n transitionS: number\n}\n\nexport interface PatchParams {\n fold: { drive: number; mix: number }\n fm: { index: number }\n unison: { detuneCents: number; mix: number }\n lfo: { rateHz: number; shape: 'sine' | 'square'; vibratoCents: number; tremolo: number; filterDepth: number }\n portamentoS: number\n}\n\n/** M1 — heavy borders saturate: drive ∈ [0,1], mix follows. */\nexport function foldFromBorder(borderWidthPx: number, edge: number): PatchParams['fold'] {\n const drive = clamp(borderWidthPx / 6, 0, 1) * (0.25 + 0.75 * clamp(edge, 0, 1))\n return { drive, mix: drive > 0.01 ? 0.25 + 0.55 * drive : 0 }\n}\n\n/** M2 — rough sharp surfaces ring metallic (audio-rate FM index, × carrier Hz in-voice). */\nexport const fmIndex = (texture: number, edge: number): number =>\n 1.5 * clamp(texture, 0, 1) * clamp(edge, 0, 1)\n\n/** M3 — big elements are thick, not just low. */\nexport function unisonFromMass(mass: number): PatchParams['unison'] {\n const m = clamp(mass, 0, 1)\n return m >= 0.45 ? { detuneCents: 4 + 10 * m, mix: 0.4 } : { detuneCents: 0, mix: 0 }\n}\n\n/** M4/M5 — the LFO patch bay: animation owns it; dashed/dotted borders chop; else idle. */\nexport function lfoFromCss(animationS: number, borderStyle: ModularVisuals['borderStyle']): PatchParams['lfo'] {\n if (animationS > 0.05) {\n return {\n rateHz: clamp(1 / animationS, 0.08, 8),\n shape: borderStyle === 'dashed' || borderStyle === 'dotted' ? 'square' : 'sine',\n vibratoCents: 6,\n tremolo: 0.18,\n filterDepth: 0.25,\n }\n }\n if (borderStyle === 'dashed' || borderStyle === 'dotted') {\n return {\n rateHz: borderStyle === 'dotted' ? 7 : 3.5,\n shape: 'square',\n vibratoCents: 0,\n tremolo: 0.3,\n filterDepth: 0.35,\n }\n }\n return { rateHz: 0, shape: 'sine', vibratoCents: 0, tremolo: 0, filterDepth: 0 }\n}\n\n/** M6 — elements that ease visually ease in pitch. Seconds added to the glide. */\nexport const portamentoFromTransition = (transitionS: number): number =>\n clamp(transitionS / 2, 0, 0.25)\n\n/** M7 — typography enters the weave: bold text carries weight (MASS bonus). */\nexport const massBonusFromFontWeight = (weight: number): number =>\n clamp((weight - 400) / 300, 0, 1) * 0.12\n\nexport function patchFrom(matter: { edge: number; mass: number; texture: number }, visuals: ModularVisuals): PatchParams {\n return {\n fold: foldFromBorder(visuals.borderWidthPx, matter.edge),\n fm: { index: fmIndex(matter.texture, matter.edge) },\n unison: unisonFromMass(matter.mass),\n lfo: lfoFromCss(visuals.animationS, visuals.borderStyle),\n portamentoS: portamentoFromTransition(visuals.transitionS),\n }\n}\n\n/**\n * The wavefolder transfer curve: y = sin(2.5·(π/2)·x). Near-linear for quiet signals,\n * folding for hot ones — the amp envelope sweeps the spectrum through the fold every note.\n */\nexport function foldCurve(samples = 2049): Float32Array {\n const out = new Float32Array(samples)\n for (let i = 0; i < samples; i++) {\n const x = (i / (samples - 1)) * 2 - 1\n out[i] = Math.sin(2.5 * (Math.PI / 2) * x)\n }\n return out\n}\n\n/** Drag-glissando ribbon (MODULAR.md §3): horizontal travel → scale-step offset, ±1 octave. */\nexport function ribbonSteps(dxPx: number, vw: number, scaleLen: number): number {\n const t = clamp(dxPx / (vw * 0.6), -1, 1)\n return Math.round(t * scaleLen)\n}\n","/**\n * The Chroma weave — CHROMA.md made executable. Color tints the Matter voice per element and\n * chooses the musical mode per page. Pure: no DOM, no Tone.\n */\nimport { clamp, lerp } from './util'\n\nexport interface Rgb {\n r: number\n g: number\n b: number\n a: number\n}\n\nexport interface Hsl {\n h: number\n s: number\n l: number\n}\n\nexport interface Chroma {\n /** 0 cool … 1 warm (desaturated colors regress to 0.5) */\n warmth: number\n saturation: number\n luminance: number\n}\n\n/** Computed styles emit rgb()/rgba(). Returns null for anything else (treat as no color). */\nexport function parseCssColor(css: string): Rgb | null {\n const m = css.trim().match(/^rgba?\\(\\s*(\\d+(?:\\.\\d+)?)\\s*,\\s*(\\d+(?:\\.\\d+)?)\\s*,\\s*(\\d+(?:\\.\\d+)?)\\s*(?:,\\s*(\\d*(?:\\.\\d+)?)\\s*)?\\)$/)\n if (!m) return null\n return {\n r: clamp(parseFloat(m[1] as string) / 255, 0, 1),\n g: clamp(parseFloat(m[2] as string) / 255, 0, 1),\n b: clamp(parseFloat(m[3] as string) / 255, 0, 1),\n a: m[4] === undefined ? 1 : clamp(parseFloat(m[4] as string), 0, 1),\n }\n}\n\nexport function rgbToHsl({ r, g, b }: Rgb): Hsl {\n const max = Math.max(r, g, b)\n const min = Math.min(r, g, b)\n const l = (max + min) / 2\n const d = max - min\n if (d < 1e-6) return { h: 0, s: 0, l }\n const s = d / (1 - Math.abs(2 * l - 1))\n let h: number\n if (max === r) h = ((g - b) / d) % 6\n else if (max === g) h = (b - r) / d + 2\n else h = (r - g) / d + 4\n h *= 60\n if (h < 0) h += 360\n return { h, s: clamp(s, 0, 1), l }\n}\n\n/** CHROMA.md §1 — cosine distance of hue from 30° (orange); greys regress to neutral 0.5. */\nexport function warmthFromHue(h: number, s: number): number {\n const raw = 0.5 + 0.5 * Math.cos(((h - 30) * Math.PI) / 180)\n return lerp(0.5, raw, clamp(s * 2, 0, 1))\n}\n\nexport function chromaOf(rgb: Rgb | null): Chroma {\n if (!rgb || rgb.a < 0.05) return { warmth: 0.5, saturation: 0, luminance: 0.5 }\n const { h, s, l } = rgbToHsl(rgb)\n return { warmth: warmthFromHue(h, s), saturation: s, luminance: l }\n}\n\n// ------------------------------------------------------------- element weave (CH1–CH5)\n\n/** CH1 — dark UI sounds dark. */\nexport const brightnessFromLuminance = (l: number): number => lerp(0.78, 1.22, clamp(l, 0, 1))\n\n/** CH2 — bright lifts, gently. */\nexport const velocityFromLuminance = (l: number): number => lerp(0.92, 1.06, clamp(l, 0, 1))\n\n/** CH3 — warm = energetic onset (thesis T5). Multiplier on the woven attack. */\nexport const attackScaleFromWarmth = (w: number): number => lerp(1.18, 0.82, clamp(w, 0, 1))\n\n/** CH4 — warm = full-bodied: bonus on the sub oscillator level (subs only, not shimmer). */\nexport const subBonusFromWarmth = (w: number): number => 0.08 * clamp(w, 0, 1)\n\n/** CH5 — vivid color = vivid spectrum: richness passed to genPartials (rolloff reduction). */\nexport const richnessFromSaturation = (s: number): number => 0.35 * clamp(s, 0, 1)\n\n// ------------------------------------------------------------- page weave (CH6–CH8)\n\nexport type ModeName = 'lydian' | 'mixolydian' | 'dorian' | 'pentMinor' | null\n\n/**\n * CH6 — the palette chooses the mode; null = neutral, keep the hostname-hashed scale\n * (identity unchanged). Root pitch-class always stays hostname-hashed (S9).\n */\nexport function modeFromPalette(pal: Chroma): ModeName {\n if (pal.warmth >= 0.55) return pal.luminance >= 0.5 ? 'lydian' : 'mixolydian'\n if (pal.warmth <= 0.45) return pal.luminance >= 0.5 ? 'dorian' : 'pentMinor'\n return null\n}\n\n/** Visual weight of the page: bg dominates, text tints. */\nexport function pagePalette(bg: Chroma, text: Chroma): Chroma {\n return {\n warmth: bg.warmth * 0.7 + text.warmth * 0.3,\n saturation: bg.saturation * 0.7 + text.saturation * 0.3,\n luminance: bg.luminance * 0.7 + text.luminance * 0.3,\n }\n}\n\n/** CH7 — warm rooms hum warmer. Multiplier on the ambience cutoff. */\nexport const roomToneScaleFromWarmth = (w: number): number => lerp(0.85, 1.25, clamp(w, 0, 1))\n\n/** CH8 — warm pages run slightly faster (consumed by PULSE.md P2). */\nexport const tempoScaleFromWarmth = (w: number): number => lerp(0.94, 1.06, clamp(w, 0, 1))\n","/**\n * The Pulse — PULSE.md made executable: tempo from the layout, grid offsets for echoes,\n * metered strum spacing, and the calm system. Pure: no DOM, no Tone.\n * THE LATENCY INVARIANT (PULSE.md §0): nothing here ever delays a primary hit.\n */\nimport { clamp, lerp } from './util'\n\n/** P1+P2 — layout density × page warmth → bpm, clamped to [56, 116]. */\nexport function tempoFromPage(elementCount: number, warmthScale: number): number {\n const base = lerp(66, 104, clamp(elementCount / 120, 0, 1))\n return Math.round(clamp(base * warmthScale, 56, 116))\n}\n\nexport const secondsPerBeat = (bpm: number): number => 60 / Math.max(1, bpm)\n\n/**\n * P3 — offset (seconds from now) to the next grid boundary of `gridS` seconds that is at\n * least `minAheadS` away. `phaseS` = seconds elapsed since the grid's epoch.\n */\nexport function nextGridOffset(phaseS: number, gridS: number, minAheadS: number): number {\n if (gridS <= 0) return minAheadS\n let offset = gridS - (((phaseS % gridS) + gridS) % gridS)\n while (offset < minAheadS) offset += gridS\n return offset\n}\n\n/** Strums step in 32nd notes — the same gesture, now in the groove. Seconds. */\nexport const strumStepS = (bpm: number): number => secondsPerBeat(bpm) / 8\n\n/** Echoes answer on 8ths, one octave up, quiet (PULSE.md §2). */\nexport const ECHO_TRANSPOSE = 12\nexport const ECHO_VELOCITY_SCALE = 0.22\nexport const ECHO_MIN_AHEAD_S = 0.08\nexport const echoGridS = (bpm: number): number => secondsPerBeat(bpm) / 2\n\n// ------------------------------------------------------------- the calm system (P5)\n\nexport const DUCK_RECOVERY_MS = 2000\n\n/** Activity count decays linearly: fully forgiven after count·2 s of silence. */\nexport const decayCount = (count: number, dtMs: number): number =>\n Math.max(0, count - dtMs / DUCK_RECOVERY_MS)\n\n/** Velocity multiplier: the 6th rapid repeat sits at ~40%, never below. */\nexport const duckFactor = (count: number): number =>\n Math.max(0.4, Math.pow(0.85, Math.max(0, count)))\n\n// ------------------------------------------------------------- phrases (P4)\n\nexport const PHRASE_PROBABILITY = 0.55\nexport const PHRASE_MIN_NOTES = 2\nexport const PHRASE_MAX_NOTES = 4\n\n/** Reading order: rows of ~80 px, then left→right. Sort key for (top, left). */\nexport const readingOrderKey = (top: number, left: number): number =>\n Math.round(top / 80) * 100000 + clamp(left, 0, 99999)\n\n/**\n * Window the score by scroll progress: with n elements and a phrase of len, the playhead\n * starts at `progress·(n − len)`.\n */\nexport function phraseWindow(n: number, len: number, progress: number): number {\n return Math.round(clamp(progress, 0, 1) * Math.max(0, n - len))\n}\n","/**\n * L3 Composition — themes are plain data (MAPPING.md §3). Adding a theme means adding an\n * object here; no engine code may special-case a theme name.\n */\nimport type { Theme } from '../types'\n\n// v0.3: aurora speaks through the woven MatterVoice — geometry IS the instrument\n// (MATTER.md). fm bells (headings) and membrane thuds (media) stay as character voices.\nconst aurora: Theme = {\n name: 'aurora',\n defaults: { synthKind: 'matter', octaveShift: 0, baseVelocity: 0.8, releaseScale: 1 },\n roles: {\n toggle: { synthKind: 'matter', baseVelocity: 0.7, releaseScale: 0.8 },\n button: { synthKind: 'matter', baseVelocity: 0.9 },\n link: { synthKind: 'matter', octaveShift: 1, baseVelocity: 0.6, releaseScale: 0.7 },\n input: { synthKind: 'matter', baseVelocity: 0.55, releaseScale: 1.6 },\n heading: { synthKind: 'fm', octaveShift: 0, baseVelocity: 0.75, releaseScale: 2.2 },\n media: { synthKind: 'membrane', octaveShift: -1, baseVelocity: 0.8 },\n item: { synthKind: 'matter', baseVelocity: 0.6, releaseScale: 0.8 },\n text: { synthKind: 'matter', baseVelocity: 0.35, releaseScale: 1.8 },\n },\n}\n\nconst mono: Theme = {\n name: 'mono',\n defaults: { synthKind: 'synth', octaveShift: 0, baseVelocity: 0.7, releaseScale: 0.5 },\n roles: {\n toggle: { synthKind: 'noise', baseVelocity: 0.6 },\n button: { synthKind: 'synth', pinWave: 'square', baseVelocity: 0.7, releaseScale: 0.4 },\n link: { synthKind: 'noise', baseVelocity: 0.45, releaseScale: 0.3 },\n input: { synthKind: 'synth', pinWave: 'sine', octaveShift: -1, baseVelocity: 0.5 },\n heading: { synthKind: 'synth', pinWave: 'sine', octaveShift: 1, baseVelocity: 0.6 },\n media: { synthKind: 'noise', baseVelocity: 0.55 },\n item: { synthKind: 'noise', baseVelocity: 0.4, releaseScale: 0.3 },\n text: { synthKind: 'synth', pinWave: 'sine', baseVelocity: 0 },\n },\n}\n\nconst paper: Theme = {\n name: 'paper',\n defaults: { synthKind: 'pluck', octaveShift: 0, baseVelocity: 0.8, releaseScale: 1 },\n roles: {\n toggle: { synthKind: 'pluck', baseVelocity: 0.7 },\n button: { synthKind: 'pluck', baseVelocity: 0.9 },\n link: { synthKind: 'pluck', octaveShift: 1, baseVelocity: 0.65 },\n input: { synthKind: 'synth', pinWave: 'triangle', baseVelocity: 0.5, releaseScale: 1.4 },\n heading: { synthKind: 'pluck', octaveShift: -1, baseVelocity: 0.85, releaseScale: 1.6 },\n media: { synthKind: 'membrane', octaveShift: -1, baseVelocity: 0.7 },\n item: { synthKind: 'pluck', baseVelocity: 0.6 },\n text: { synthKind: 'synth', pinWave: 'sine', baseVelocity: 0.3, releaseScale: 1.6 },\n },\n}\n\nexport const THEMES: Record<string, Theme> = { aurora, mono, paper }\n\nexport function resolveTheme(theme: string | Theme | undefined): Theme {\n if (!theme) return aurora\n if (typeof theme === 'string') return THEMES[theme] ?? aurora\n return theme\n}\n","/**\n * The unlock & mute chip — autoplay policy treated as a feature (PLAN.md R2).\n * Shadow DOM so host styles can't break it; ARIA so keyboard/SR users get the same control.\n */\nconst STORAGE_KEY = 'sonarium:muted'\n\nexport const isMutedPersisted = (): boolean => {\n try { return localStorage.getItem(STORAGE_KEY) === '1' } catch { return false }\n}\n\nexport const persistMuted = (muted: boolean): void => {\n try { localStorage.setItem(STORAGE_KEY, muted ? '1' : '0') } catch { /* private mode */ }\n}\n\nexport interface GateHandle {\n setState: (state: 'armed' | 'on' | 'muted') => void\n dispose: () => void\n}\n\nexport function mountGate(onToggle: () => void): GateHandle {\n const host = document.createElement('div')\n host.setAttribute('data-sonic', 'off') // the chip itself must never sound\n const shadow = host.attachShadow({ mode: 'open' })\n shadow.innerHTML = `\n <style>\n button {\n position: fixed; right: 16px; bottom: 16px; z-index: 2147483646;\n width: 44px; height: 44px; border-radius: 50%; border: 1px solid rgba(255,255,255,.25);\n background: rgba(20, 22, 30, .82); color: #fff; font-size: 18px; line-height: 1;\n cursor: pointer; backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px);\n box-shadow: 0 4px 16px rgba(0,0,0,.35); transition: transform .15s ease, opacity .3s ease;\n }\n button:hover { transform: scale(1.08); }\n button:focus-visible { outline: 2px solid #7cd4fd; outline-offset: 2px; }\n button.armed { animation: pulse 1.6s ease-in-out infinite; }\n @keyframes pulse { 0%,100% { box-shadow: 0 4px 16px rgba(0,0,0,.35); } 50% { box-shadow: 0 0 0 10px rgba(124,212,253,.18); } }\n </style>\n <button type=\"button\" class=\"armed\" aria-label=\"Enable sound\" title=\"Sonarium — enable sound\">🔇</button>\n `\n const btn = shadow.querySelector('button') as HTMLButtonElement\n btn.addEventListener('click', (e) => {\n e.stopPropagation()\n onToggle()\n })\n document.body.appendChild(host)\n\n return {\n setState(state) {\n btn.classList.toggle('armed', state === 'armed')\n if (state === 'on') {\n btn.textContent = '🔊'\n btn.setAttribute('aria-label', 'Mute Sonarium')\n } else if (state === 'muted') {\n btn.textContent = '🔇'\n btn.setAttribute('aria-label', 'Unmute Sonarium')\n } else {\n btn.textContent = '🔇'\n btn.setAttribute('aria-label', 'Enable sound')\n }\n },\n dispose() {\n host.remove()\n },\n }\n}\n","/**\n * Pure spherical-harmonic encoding — SPATIAL.md §1–2. AmbiX: ACN order [W, Y, Z, X],\n * SN3D normalization, +x forward, +y left, +z up, +azimuth left. No DOM, no Tone.\n */\n\nexport const DEG = Math.PI / 180\n\n/** ACN channel indices, for readability everywhere else. */\nexport const ACN = { W: 0, Y: 1, Z: 2, X: 3 } as const\n\nexport interface FoaGains {\n w: number\n y: number\n z: number\n x: number\n}\n\n/**\n * First-order encode of a plane wave from (azimuth, elevation), with extent σ blending the\n * directional components into the omni channel (SPATIAL.md §2). Angles in radians.\n */\nexport function foaGains(azimuth: number, elevation: number, extent = 0): FoaGains {\n const s = Math.min(1, Math.max(0, extent))\n const cosEl = Math.cos(elevation)\n const dir = 1 - s\n return {\n w: 1 + 0.41 * s,\n y: dir * Math.sin(azimuth) * cosEl,\n z: dir * Math.sin(elevation),\n x: dir * Math.cos(azimuth) * cosEl,\n }\n}\n\n/** Unit direction vector for (azimuth, elevation) in the AmbiX frame. */\nexport function unitVector(azimuth: number, elevation: number): [number, number, number] {\n const cosEl = Math.cos(elevation)\n return [Math.cos(azimuth) * cosEl, Math.sin(azimuth) * cosEl, Math.sin(elevation)]\n}\n","/**\n * Pure FOA decoding — SPATIAL.md §3.2. Sampling decoder with max-rE weighting over a fixed\n * virtual-speaker layout; each speaker is later rendered by one native HRTF panner.\n */\nimport { unitVector, type FoaGains } from './sh'\n\nexport interface Speaker {\n /** Unit direction in the AmbiX frame. */\n dir: [number, number, number]\n label: string\n}\n\nconst C = 1 / Math.sqrt(3)\n\n/** Cube vertices: full-sphere coverage including elevation, symmetric, M = 8. */\nexport const CUBE_LAYOUT: Speaker[] = [\n { dir: [C, C, C], label: 'front-left-up' },\n { dir: [C, -C, C], label: 'front-right-up' },\n { dir: [C, C, -C], label: 'front-left-down' },\n { dir: [C, -C, -C], label: 'front-right-down' },\n { dir: [-C, C, C], label: 'back-left-up' },\n { dir: [-C, -C, C], label: 'back-right-up' },\n { dir: [-C, C, -C], label: 'back-left-down' },\n { dir: [-C, -C, -C], label: 'back-right-down' },\n]\n\n/** max-rE weights for 3D first order (Zotter & Frank): g0 = 1, g1 = 1/√3. */\nexport const MAXRE_G0 = 1\nexport const MAXRE_G1 = 1 / Math.sqrt(3)\n\nexport interface DecodeRow {\n /** Per-ACN gains [w, y, z, x] for one speaker: s = w·W + y·Y + z·Z + x·X. */\n w: number\n y: number\n z: number\n x: number\n}\n\n/**\n * Sampling decode matrix for SN3D input: sm = (1/M)·[g0·W + 3·g1·(X·xm + Y·ym + Z·zm)].\n * The 3 re-normalizes first-order SN3D to N3D inside the projection.\n */\nexport function decodeMatrix(layout: Speaker[]): DecodeRow[] {\n const M = layout.length\n return layout.map(({ dir }) => ({\n w: (1 / M) * MAXRE_G0,\n x: (3 / M) * MAXRE_G1 * dir[0],\n y: (3 / M) * MAXRE_G1 * dir[1],\n z: (3 / M) * MAXRE_G1 * dir[2],\n }))\n}\n\n/** Decode an encoded source to speaker signals (used by tests and the worklet path later). */\nexport function decodeGains(rows: DecodeRow[], g: FoaGains): number[] {\n return rows.map((r) => r.w * g.w + r.y * g.y + r.z * g.z + r.x * g.x)\n}\n\n/** Total decoded energy for a direction — tests assert flatness across the sphere. */\nexport function decodedEnergy(rows: DecodeRow[], azimuth: number, elevation: number): number {\n const v = unitVector(azimuth, elevation)\n const g: FoaGains = { w: 1, x: v[0], y: v[1], z: v[2] }\n return decodeGains(rows, g).reduce((acc, s) => acc + s * s, 0)\n}\n","/**\n * Pure field rotation — SPATIAL.md §3.1. The 3×3 matrix acts on the (X, Y, Z) channel triple\n * (W is rotation-invariant). Row-major: m[r][c], applied as X' = m00·X + m01·Y + m02·Z, etc.\n * Composition R = Rz(yaw) · Ry(pitch) · Rx(roll). Angles in radians.\n */\n\nexport type Mat3 = [\n [number, number, number],\n [number, number, number],\n [number, number, number],\n]\n\nexport const IDENTITY: Mat3 = [\n [1, 0, 0],\n [0, 1, 0],\n [0, 0, 1],\n]\n\nfunction mul(a: Mat3, b: Mat3): Mat3 {\n const out: Mat3 = [\n [0, 0, 0],\n [0, 0, 0],\n [0, 0, 0],\n ]\n for (let r = 0; r < 3; r++)\n for (let c = 0; c < 3; c++)\n out[r]![c] = a[r]![0]! * b[0]![c]! + a[r]![1]! * b[1]![c]! + a[r]![2]! * b[2]![c]!\n return out\n}\n\n/** Acts on column vectors (X, Y, Z)ᵀ in the AmbiX frame (+x fwd, +y left, +z up). */\nexport function rotationMatrix(yaw: number, pitch: number, roll = 0): Mat3 {\n const cy = Math.cos(yaw), sy = Math.sin(yaw)\n const cp = Math.cos(pitch), sp = Math.sin(pitch)\n const cr = Math.cos(roll), sr = Math.sin(roll)\n const Rz: Mat3 = [\n [cy, -sy, 0],\n [sy, cy, 0],\n [0, 0, 1],\n ]\n const Ry: Mat3 = [\n [cp, 0, sp],\n [0, 1, 0],\n [-sp, 0, cp],\n ]\n const Rx: Mat3 = [\n [1, 0, 0],\n [0, cr, -sr],\n [0, sr, cr],\n ]\n return mul(mul(Rz, Ry), Rx)\n}\n\nexport function applyMat3(m: Mat3, v: [number, number, number]): [number, number, number] {\n return [\n m[0]![0]! * v[0] + m[0]![1]! * v[1] + m[0]![2]! * v[2],\n m[1]![0]! * v[0] + m[1]![1]! * v[1] + m[1]![2]! * v[2],\n m[2]![0]! * v[0] + m[2]![1]! * v[1] + m[2]![2]! * v[2],\n ]\n}\n\n/**\n * Look semantics (SPATIAL.md §3.1): the field rotation is the INVERSE of the head's intrinsic\n * yaw-then-pitch rotation. Looking right by α (head Rz(−α)) and up by β (head Ry(−β)) gives\n * field R = (Rz(−α)·Ry(−β))⁻¹ = Ry(β)·Rz(α). The sign/composition decision lives here and\n * only here, pinned by tests: look right → right-side sources arrive frontward; look up →\n * overhead sources arrive frontward.\n */\nexport function lookMatrix(yawRight: number, pitchUp: number): Mat3 {\n const pitch = rotationMatrix(0, pitchUp, 0) // = Ry(pitchUp)\n const yaw = rotationMatrix(yawRight, 0, 0) // = Rz(yawRight)\n return mul(pitch, yaw)\n}\n","/**\n * AmbisonicBus — the field itself (SPATIAL.md §3): W/Y/Z/X summing buses → live 3×3 rotation\n * (nine GainNodes; W invariant) → binaural decode through fixed virtual speakers, each rendered\n * by one native HRTF PannerNode. Imports Tone only.\n */\nimport * as Tone from 'tone'\nimport { CUBE_LAYOUT, decodeMatrix } from './decoder'\nimport { IDENTITY, type Mat3 } from './rotation'\nimport type { BusInputs } from './encoder'\n\nconst SPEAKER_RADIUS = 2.5\n\nexport class AmbisonicBus {\n readonly inputs: BusInputs\n private rot: Tone.Gain[][] // rot[out][in] over (X, Y, Z) = indices 0,1,2\n private outW: Tone.Gain\n private outXYZ: [Tone.Gain, Tone.Gain, Tone.Gain]\n private nodes: { dispose(): void }[] = []\n\n constructor(destination: Tone.InputNode, decoderKind: 'binaural' | 'stereo') {\n this.inputs = { w: new Tone.Gain(1), y: new Tone.Gain(1), z: new Tone.Gain(1), x: new Tone.Gain(1) }\n this.outW = new Tone.Gain(1)\n this.outXYZ = [new Tone.Gain(1), new Tone.Gain(1), new Tone.Gain(1)]\n this.inputs.w.connect(this.outW)\n\n // Rotation matrix acts on the (X, Y, Z) triple: out = R · in.\n const inXYZ = [this.inputs.x, this.inputs.y, this.inputs.z]\n this.rot = []\n for (let r = 0; r < 3; r++) {\n const row: Tone.Gain[] = []\n for (let c = 0; c < 3; c++) {\n const g = new Tone.Gain(IDENTITY[r]![c]!)\n inXYZ[c]!.connect(g)\n g.connect(this.outXYZ[r]!)\n row.push(g)\n }\n this.rot.push(row)\n }\n\n if (decoderKind === 'stereo') this.buildStereoDecode(destination)\n else this.buildVirtualSpeakerDecode(destination)\n\n this.nodes.push(this.inputs.w, this.inputs.y, this.inputs.z, this.inputs.x, this.outW, ...this.outXYZ, ...this.rot.flat())\n }\n\n /** SPATIAL.md §3.2 — 8 cube speakers, each a static mix of (W, X', Y', Z') into a fixed HRTF panner. */\n private buildVirtualSpeakerDecode(destination: Tone.InputNode): void {\n const rows = decodeMatrix(CUBE_LAYOUT)\n rows.forEach((row, i) => {\n const dir = CUBE_LAYOUT[i]!.dir\n const sum = new Tone.Gain(1)\n const mw = new Tone.Gain(row.w)\n const mx = new Tone.Gain(row.x)\n const my = new Tone.Gain(row.y)\n const mz = new Tone.Gain(row.z)\n this.outW.connect(mw)\n this.outXYZ[0]!.connect(mx)\n this.outXYZ[1]!.connect(my)\n this.outXYZ[2]!.connect(mz)\n mw.connect(sum)\n mx.connect(sum)\n my.connect(sum)\n mz.connect(sum)\n // AmbiX (+x fwd, +y left, +z up) → WebAudio (+x right, +y up, −z fwd).\n const panner = new Tone.Panner3D({\n panningModel: 'HRTF',\n distanceModel: 'inverse',\n refDistance: SPEAKER_RADIUS,\n rolloffFactor: 0, // fixed-radius speakers: direction only, no distance shading\n positionX: -dir[1] * SPEAKER_RADIUS,\n positionY: dir[2] * SPEAKER_RADIUS,\n positionZ: -dir[0] * SPEAKER_RADIUS,\n })\n sum.connect(panner)\n panner.connect(destination)\n this.nodes.push(sum, mw, mx, my, mz, panner)\n })\n }\n\n /** Fallback decode without HRTF: two virtual cardioids at ±90° (SPATIAL.md §3.2). */\n private buildStereoDecode(destination: Tone.InputNode): void {\n const L = new Tone.Gain(1)\n const R = new Tone.Gain(1)\n const wL = new Tone.Gain(0.5)\n const wR = new Tone.Gain(0.5)\n const yL = new Tone.Gain(0.5)\n const yR = new Tone.Gain(-0.5)\n this.outW.connect(wL)\n this.outW.connect(wR)\n this.outXYZ[1]!.connect(yL)\n this.outXYZ[1]!.connect(yR)\n wL.connect(L)\n yL.connect(L)\n wR.connect(R)\n yR.connect(R)\n const merge = new Tone.Merge()\n L.connect(merge, 0, 0)\n R.connect(merge, 0, 1)\n merge.connect(destination)\n this.nodes.push(L, R, wL, wR, yL, yR, merge)\n }\n\n /** Rotate the whole field (FieldRig calls this with lookMatrix output). Ramped, zipper-free. */\n setRotation(m: Mat3, rampS = 0.04): void {\n for (let r = 0; r < 3; r++)\n for (let c = 0; c < 3; c++)\n this.rot[r]![c]!.gain.rampTo(m[r]![c]!, rampS)\n }\n\n dispose(): void {\n for (const n of this.nodes) n.dispose()\n this.nodes = []\n }\n}\n","/**\n * SourceEncoder — one per voice lane: four GainNodes carrying the lane's mono signal into the\n * W/Y/Z/X buses with first-order SH gains (SPATIAL.md §2). Imports Tone only.\n */\nimport * as Tone from 'tone'\nimport type { FoaGains } from './sh'\n\nexport interface BusInputs {\n w: Tone.Gain\n y: Tone.Gain\n z: Tone.Gain\n x: Tone.Gain\n}\n\nexport class SourceEncoder {\n readonly input: Tone.Gain\n private gw: Tone.Gain\n private gy: Tone.Gain\n private gz: Tone.Gain\n private gx: Tone.Gain\n\n constructor(bus: BusInputs) {\n this.input = new Tone.Gain(1)\n this.gw = new Tone.Gain(1)\n this.gy = new Tone.Gain(0)\n this.gz = new Tone.Gain(0)\n this.gx = new Tone.Gain(1)\n this.input.connect(this.gw)\n this.input.connect(this.gy)\n this.input.connect(this.gz)\n this.input.connect(this.gx)\n this.gw.connect(bus.w)\n this.gy.connect(bus.y)\n this.gz.connect(bus.z)\n this.gx.connect(bus.x)\n }\n\n /** Apply SH gains × an overall direct-path gain, ramped to avoid zipper noise. */\n set(g: FoaGains, directGain: number, when?: number, rampS = 0.015): void {\n const t = when ?? Tone.now()\n this.gw.gain.rampTo(g.w * directGain, rampS, t)\n this.gy.gain.rampTo(g.y * directGain, rampS, t)\n this.gz.gain.rampTo(g.z * directGain, rampS, t)\n this.gx.gain.rampTo(g.x * directGain, rampS, t)\n }\n\n dispose(): void {\n this.input.dispose()\n this.gw.dispose()\n this.gy.dispose()\n this.gz.dispose()\n this.gx.dispose()\n }\n}\n","/**\n * Pure sphere mappings — SPATIAL.md §4 (canon rows SP1–SP5). The page is laid on the front\n * hemisphere of a sphere around the listener; geometry becomes spherical source properties.\n * No DOM, no Tone.\n */\nimport { clamp, norm } from '../math/util'\nimport { DEG } from './sh'\nimport type { Rect } from '../types'\n\nexport const AZ_MAX = 70 * DEG\nexport const EL_MAX = 45 * DEG\n\n/** SP1/SP2 — screen position → direction. Screen-right = −azimuth (sign tested). */\nexport function sphereFromRect(rect: Rect, vw: number, vh: number): { azimuth: number; elevation: number } {\n const tx = norm(rect.x + rect.w / 2, 0, vw)\n const ty = norm(rect.y + rect.h / 2, 0, vh)\n return {\n azimuth: -(2 * tx - 1) * AZ_MAX,\n elevation: (1 - 2 * ty) * EL_MAX,\n }\n}\n\n/** SP4 — big elements wrap around the listener (T2 extended into space). */\nexport function extentFromSize(sizeT: number): number {\n return clamp(0.05 + 0.75 * Math.pow(clamp(sizeT, 0, 1), 1.2), 0, 0.95)\n}\n\n/** SP5 — Kiki/Bouba in the spatial domain: sharp beams, round radiates. */\nexport function directivityFromRoundness(roundness: number): number {\n return clamp(1 - roundness, 0, 1)\n}\n\n/** SP6 — early-reflection time scale follows the room (viewport). */\nexport function reflectionScaleFromViewport(vw: number): number {\n return 0.6 + norm(vw, 360, 2200) * 1.0\n}\n","/**\n * Pure perceptual-factor formulas — SPATIAL.md §5. The spat5.oper surface: five factors in\n * [0,1], each mapping monotonically to DSP parameters. Defaults mirror the spec table.\n */\nimport { clamp, lerp } from '../math/util'\nimport type { PerceptualFactors } from '../types'\n\nexport type { PerceptualFactors }\n\nexport const DEFAULT_FACTORS: PerceptualFactors = {\n presence: 0.7,\n roomPresence: 0.5,\n envelopment: 0.55,\n warmth: 0.5,\n brilliance: 0.5,\n}\n\nexport function resolveFactors(partial: Partial<PerceptualFactors> | undefined): PerceptualFactors {\n const f = { ...DEFAULT_FACTORS, ...(partial ?? {}) }\n for (const k of Object.keys(f) as (keyof PerceptualFactors)[]) f[k] = clamp(f[k], 0, 1)\n return f\n}\n\n/** presence → direct-path gain (linear). */\nexport const directGain = (presence: number): number => lerp(0.5, 1.2, clamp(presence, 0, 1))\n\n/** roomPresence → early-reflection + reverb-send master (linear). */\nexport const roomGain = (roomPresence: number): number => lerp(0, 1.6, clamp(roomPresence, 0, 1))\n\n/** envelopment → diffuse-tail extent (σ of the tail encoders) and tail level. */\nexport const tailExtent = (envelopment: number): number => clamp(envelopment, 0, 1)\nexport const tailLevel = (envelopment: number): number => lerp(0.7, 1.25, clamp(envelopment, 0, 1))\n\n/** warmth → low-shelf dB at 250 Hz. */\nexport const warmthDb = (warmth: number): number => lerp(-3, 3, clamp(warmth, 0, 1))\n\n/** brilliance → high-shelf dB at 4 kHz. */\nexport const brillianceDb = (brilliance: number): number => lerp(-4, 3, clamp(brilliance, 0, 1))\n\n/** directivity δ → source presence/brightness/room behaviour (SPATIAL.md §2). */\nexport const directivityDirectGain = (d: number): number => lerp(0.75, 1.1, clamp(d, 0, 1))\nexport const directivitySendScale = (d: number): number => lerp(1.35, 0.8, clamp(d, 0, 1))\nexport const directivityFilterScale = (d: number): number => lerp(0.85, 1.15, clamp(d, 0, 1))\n","/**\n * FoaRoom — the Spat room model in the field (SPATIAL.md §3.3): early reflections encoded at\n * mirror directions + the diffuse tail whose extent IS the envelopment factor. Imports Tone only.\n */\nimport * as Tone from 'tone'\nimport { foaGains, DEG } from './sh'\nimport { reflectionScaleFromViewport } from './sphere'\nimport { roomGain, tailExtent, tailLevel, type PerceptualFactors } from './perceptual'\nimport { SourceEncoder, type BusInputs } from './encoder'\n\nconst ER_BASE_TIMES = [0.013, 0.019, 0.027, 0.034]\nconst ER_TAP_LEVELS = [1, 0.85, 0.7, 0.6]\nconst ER_DIRECTIONS: Array<[number, number]> = [\n [110 * DEG, 30 * DEG],\n [-110 * DEG, 30 * DEG],\n [110 * DEG, -30 * DEG],\n [-110 * DEG, -30 * DEG],\n]\n\nexport class FoaRoom {\n /** Lanes tap their direct signal here (mono sum). */\n readonly erIn: Tone.Gain\n private erMaster: Tone.Gain\n private delays: Tone.Delay[] = []\n private split: Tone.Split\n private tailL: SourceEncoder\n private tailR: SourceEncoder\n private nodes: { dispose(): void }[] = []\n\n constructor(bus: BusInputs, reverb: Tone.Reverb, vw: number, factors: PerceptualFactors) {\n this.erIn = new Tone.Gain(1)\n this.erMaster = new Tone.Gain(0.22 * roomGain(factors.roomPresence))\n this.erIn.connect(this.erMaster)\n\n const scale = reflectionScaleFromViewport(vw)\n ER_BASE_TIMES.forEach((t, i) => {\n const delay = new Tone.Delay({ delayTime: t * scale, maxDelay: 0.12 })\n const tap = new Tone.Gain(ER_TAP_LEVELS[i] as number)\n const enc = new SourceEncoder(bus)\n const [az, el] = ER_DIRECTIONS[i] as [number, number]\n enc.set(foaGains(az, el, 0.35), 1)\n this.erMaster.connect(delay)\n delay.connect(tap)\n tap.connect(enc.input)\n this.delays.push(delay)\n this.nodes.push(delay, tap, enc)\n })\n\n // Diffuse tail: reverb L/R become two wide sources at ±120°; their extent = envelopment.\n this.split = new Tone.Split()\n reverb.connect(this.split)\n this.tailL = new SourceEncoder(bus)\n this.tailR = new SourceEncoder(bus)\n this.split.connect(this.tailL.input, 0)\n this.split.connect(this.tailR.input, 1)\n this.applyTail(factors)\n this.nodes.push(this.erIn, this.erMaster, this.split, this.tailL, this.tailR)\n }\n\n private applyTail(f: PerceptualFactors): void {\n const ext = tailExtent(f.envelopment)\n const level = tailLevel(f.envelopment)\n this.tailL.set(foaGains(120 * DEG, 0, ext), level)\n this.tailR.set(foaGains(-120 * DEG, 0, ext), level)\n }\n\n setFactors(f: PerceptualFactors): void {\n this.erMaster.gain.rampTo(0.22 * roomGain(f.roomPresence), 0.1)\n this.applyTail(f)\n }\n\n setViewport(vw: number): void {\n const scale = reflectionScaleFromViewport(vw)\n this.delays.forEach((d, i) => d.delayTime.rampTo((ER_BASE_TIMES[i] as number) * scale, 0.3))\n }\n\n dispose(): void {\n for (const n of this.nodes) n.dispose()\n this.nodes = []\n }\n}\n","/**\n * SpatialBackend — the seam between the voice pool and the spatial engine (SPATIAL.md §6).\n * 'ambisonic' encodes every lane into the shared FOA field; 'panner' is the v0.1 per-voice\n * HRTF path, kept as option and automatic fallback. Imports Tone only.\n */\nimport * as Tone from 'tone'\nimport { clamp } from '../math/util'\nimport type { SonicProfile } from '../types'\nimport type { Room } from '../core/room'\nimport { AmbisonicBus } from './bus'\nimport { SourceEncoder } from './encoder'\nimport { FoaRoom } from './room-foa'\nimport { foaGains } from './sh'\nimport type { Mat3 } from './rotation'\nimport {\n directGain, directivityDirectGain, directivitySendScale, resolveFactors,\n roomGain, type PerceptualFactors,\n} from './perceptual'\n\nexport interface LaneOutput {\n /** The lane's filter connects here. */\n input: Tone.InputNode\n /** Place the voice in space from its profile (called at trigger time). */\n setPlacement(profile: SonicProfile, when?: number): void\n dispose(): void\n}\n\nexport interface SpatialBackend {\n readonly kind: 'ambisonic' | 'panner'\n createOutput(): LaneOutput\n setFactors(factors: PerceptualFactors): void\n /** Rotate the field (ambisonic) — no-op on the panner backend. */\n setRotation(m: Mat3): void\n onViewport(vw: number): void\n dispose(): void\n}\n\n// ---------------------------------------------------------------------------- ambisonic\n\nexport class AmbisonicBackend implements SpatialBackend {\n readonly kind = 'ambisonic' as const\n private bus: AmbisonicBus\n private foaRoom: FoaRoom\n private factors: PerceptualFactors\n\n constructor(private room: Room, decoderKind: 'binaural' | 'stereo', vw: number, factors?: Partial<PerceptualFactors>) {\n this.factors = resolveFactors(factors)\n this.bus = new AmbisonicBus(room.spatialIn, decoderKind)\n this.foaRoom = new FoaRoom(this.bus.inputs, room.reverb, vw, this.factors)\n }\n\n createOutput(): LaneOutput {\n const enc = new SourceEncoder(this.bus.inputs)\n const send = new Tone.Gain(0.15)\n // MATTER.md reverb weave: dark sources bloom dark — the tail is colored per voice.\n const sendColor = new Tone.Filter({ type: 'lowpass', frequency: 5000, rolloff: -12 })\n enc.input.connect(send)\n send.connect(sendColor)\n sendColor.connect(this.room.reverb)\n enc.input.connect(this.foaRoom.erIn)\n const backend = this\n return {\n input: enc.input,\n setPlacement(profile: SonicProfile, when?: number) {\n const t = when ?? Tone.now()\n const s = profile.sphere\n const w = profile.voice.reverb\n const extent = clamp(s.extent + w.extentBonus, 0, 0.95)\n const g = foaGains(s.azimuth, s.elevation, extent)\n const direct = directGain(backend.factors.presence) * directivityDirectGain(s.directivity)\n enc.set(g, direct, when)\n const wetSend = clamp(\n profile.reverbSend * directivitySendScale(s.directivity) * roomGain(backend.factors.roomPresence),\n 0,\n 1.5,\n )\n sendColor.frequency.rampTo(w.sendCutoffHz, 0.02, t)\n send.gain.cancelScheduledValues(t)\n if (w.bloom > 0.35) {\n // round sources swell into the room over the note; sharp ones arrive dry-then-done\n send.gain.setValueAtTime(wetSend * 0.35, t)\n send.gain.rampTo(wetSend, Math.max(0.08, profile.durationS), t)\n } else {\n send.gain.rampTo(wetSend, 0.02, t)\n }\n },\n dispose() {\n enc.dispose()\n send.dispose()\n sendColor.dispose()\n },\n }\n }\n\n setFactors(factors: PerceptualFactors): void {\n this.factors = factors\n this.foaRoom.setFactors(factors)\n this.room.setFactors(factors)\n }\n\n setRotation(m: Mat3): void {\n this.bus.setRotation(m)\n }\n\n onViewport(vw: number): void {\n this.foaRoom.setViewport(vw)\n }\n\n dispose(): void {\n this.foaRoom.dispose()\n this.bus.dispose()\n }\n}\n\n// ---------------------------------------------------------------------------- panner (v0.1)\n\nexport class PannerBackend implements SpatialBackend {\n readonly kind = 'panner' as const\n\n constructor(private room: Room, private panningModel: 'HRTF' | 'equalpower') {}\n\n createOutput(): LaneOutput {\n const panner = new Tone.Panner3D({\n panningModel: this.panningModel,\n distanceModel: 'inverse',\n refDistance: 1,\n rolloffFactor: 0.4,\n positionX: 0, positionY: 0, positionZ: -2,\n })\n const dry = new Tone.Gain(1)\n const send = new Tone.Gain(0.18)\n const sendColor = new Tone.Filter({ type: 'lowpass', frequency: 5000, rolloff: -12 })\n panner.connect(dry)\n panner.connect(send)\n send.connect(sendColor)\n dry.connect(this.room.buses.dryIn)\n sendColor.connect(this.room.buses.wetIn)\n return {\n input: panner,\n setPlacement(profile: SonicProfile, when?: number) {\n const t = when ?? Tone.now()\n panner.positionX.rampTo(profile.pan.x, 0.02, t)\n panner.positionY.rampTo(profile.pan.y, 0.02, t)\n panner.positionZ.rampTo(profile.pan.z, 0.02, t)\n sendColor.frequency.rampTo(profile.voice.reverb.sendCutoffHz, 0.02, t)\n send.gain.rampTo(clamp(profile.reverbSend, 0, 1), 0.02, t)\n },\n dispose() {\n panner.dispose()\n dry.dispose()\n send.dispose()\n sendColor.dispose()\n },\n }\n }\n\n setFactors(factors: PerceptualFactors): void {\n this.room.setFactors(factors)\n }\n\n setRotation(): void { /* the panner world rotates via Tone.Listener (ListenerRig) */ }\n\n onViewport(): void { /* room resize handled by Room */ }\n\n dispose(): void { /* lane outputs disposed by the pool */ }\n}\n","/**\n * FieldRig — embodiment for the ambisonic backend (SPATIAL.md §3.1): mouse-look on desktop,\n * device attitude on mobile, lerped per frame into one field rotation. Exposes the same\n * pointTo/tiltTo surface as the legacy ListenerRig so L2 drivers don't care which world they\n * live in.\n */\nimport { clamp, lerp } from '../math/util'\nimport { DEG } from './sh'\nimport { lookMatrix } from './rotation'\nimport type { SpatialBackend } from './backend'\n\nconst POINTER_YAW_MAX = 40 * DEG\nconst POINTER_PITCH_MAX = 20 * DEG\nconst TILT_YAW_MAX = 35 * DEG\nconst TILT_PITCH_MAX = 25 * DEG\n\nexport class FieldRig {\n private target = { yaw: 0, pitch: 0 }\n private tilt = { yaw: 0, pitch: 0 }\n private look = { yaw: 0, pitch: 0 }\n private raf = 0\n private running = false\n\n constructor(\n private backend: SpatialBackend,\n private mode: 'pointer' | 'center',\n ) {}\n\n start(): void {\n if (this.running) return\n this.running = true\n const step = () => {\n if (!this.running) return\n const gy = clamp(this.target.yaw + this.tilt.yaw, -Math.PI / 2, Math.PI / 2)\n const gp = clamp(this.target.pitch + this.tilt.pitch, -Math.PI / 3, Math.PI / 3)\n const ny = lerp(this.look.yaw, gy, 0.1)\n const np = lerp(this.look.pitch, gp, 0.1)\n if (Math.abs(ny - this.look.yaw) > 1e-4 || Math.abs(np - this.look.pitch) > 1e-4) {\n this.look.yaw = ny\n this.look.pitch = np\n this.backend.setRotation(lookMatrix(this.look.yaw, this.look.pitch))\n }\n this.raf = requestAnimationFrame(step)\n }\n this.raf = requestAnimationFrame(step)\n }\n\n /** I9 — cursor (viewport-normalized 0..1) becomes look direction: right edge = look right. */\n pointTo(tx: number, ty: number): void {\n if (this.mode !== 'pointer') return\n this.target.yaw = (2 * clamp(tx, 0, 1) - 1) * POINTER_YAW_MAX\n this.target.pitch = (1 - 2 * clamp(ty, 0, 1)) * POINTER_PITCH_MAX\n }\n\n /** I10 — device attitude: γ right-tilt = look right, β beyond ~40° = look up/down. */\n tiltTo(gamma: number, beta: number): void {\n this.tilt.yaw = clamp(gamma / 45, -1, 1) * TILT_YAW_MAX\n this.tilt.pitch = clamp((beta - 40) / 45, -1, 1) * -TILT_PITCH_MAX\n }\n\n /** Public look API (head tracking / WebXR later plugs in here). Radians, right/up positive. */\n lookAt(yawRight: number, pitchUp: number): void {\n this.target.yaw = yawRight\n this.target.pitch = pitchUp\n }\n\n get state(): { yaw: number; pitch: number } {\n return { yaw: this.look.yaw, pitch: this.look.pitch }\n }\n\n dispose(): void {\n this.running = false\n cancelAnimationFrame(this.raf)\n }\n}\n","/**\n * Every formula in MAPPING.md §1–2, one named pure function each.\n * This file is the executable form of the Mapping Canon: no DOM, no Tone, no side effects.\n * Change a formula here ⇄ change MAPPING.md in the same commit (PLAN.md Invariant #3).\n */\nimport { clamp, lerp, norm } from './util'\nimport type { Rect, Wave } from '../types'\n\nexport const ROOM_HALF_W = 8 // meters — G1\nexport const ROOM_HALF_H = 4 // meters — G2\n\n/** G1 — element center x → azimuth (positionX, meters). */\nexport function panX(rect: Rect, vw: number): number {\n return (2 * norm(rect.x + rect.w / 2, 0, vw) - 1) * ROOM_HALF_W\n}\n\n/** G2 — element center y → elevation (positionY, meters; screen-top = up). */\nexport function panY(rect: Rect, vh: number): number {\n return (1 - 2 * norm(rect.y + rect.h / 2, 0, vh)) * ROOM_HALF_H\n}\n\n/** G3 — vertical position → brightness tilt multiplier on the filter cutoff. */\nexport function brightnessTilt(rect: Rect, vh: number): number {\n return lerp(1.45, 0.7, norm(rect.y + rect.h / 2, 0, vh))\n}\n\n/** G4 — log-normalized size 0 (tiny) … 1 (viewport-filling). */\nexport function sizeT(rect: Rect, vw: number, vh: number): number {\n const a = Math.max(1, rect.w * rect.h)\n const A = Math.max(1, vw * vh)\n return norm(Math.log(1 + (100 * a) / A), 0, Math.log(101))\n}\n\n/**\n * G4 — pitch degree, inverted: big elements speak low (T2). Compressed into [0.1, 0.85] so\n * sibling/heading step offsets have melodic headroom instead of clamping at the edges.\n */\nexport const degreeFromSize = (t: number): number => 0.1 + 0.75 * (1 - t)\n\n/** G5 — big elements speak louder (T2). */\nexport const velocityFromSize = (t: number): number => lerp(0.85, 1.25, t)\n\n/** G6 — roundness r ∈ [0,1]: 0 = razor corner (kiki), 1 = pill/circle (bouba). */\nexport function roundness(radiusPx: number, rect: Rect): number {\n const half = Math.min(rect.w, rect.h) / 2\n return half <= 0 ? 0 : clamp(radiusPx / half, 0, 1)\n}\n\n/** G7 — the Kiki/Bouba waveform ladder. */\nexport function waveFromRoundness(r: number): Wave {\n if (r < 0.15) return 'square'\n if (r < 0.45) return 'sawtooth'\n if (r < 0.8) return 'triangle'\n return 'sine'\n}\n\n/** G8 — sharp = plosive onset, round = soft bloom. Seconds. */\nexport const attackFromRoundness = (r: number): number => lerp(0.002, 0.045, r)\n\n/** G9 — sharp edges ring with resonance. */\nexport const qFromRoundness = (r: number): number => lerp(2.4, 0.5, r)\n\n/** G10 — sharper ↔ slightly higher (T1), in whole scale steps. */\nexport const pitchNudgeFromRoundness = (r: number): number => (1 - r) * 1\n\n/** G11 — elongation → duration: long elements sweep, squares tick. Seconds. */\nexport function durationFromElongation(rect: Rect): number {\n const e = Math.max(rect.w, rect.h) / Math.max(1, Math.min(rect.w, rect.h))\n return clamp(0.18 * Math.sqrt(e), 0.12, 1.6)\n}\n\n/** G13 — box-shadow blur lifts the element into the room's reverb. */\nexport const sendFromShadowBlur = (blurPx: number): number => clamp(blurPx / 40, 0, 0.5)\n\n/** S1 — DOM depth → distance behind the sound stage (listener at z=0 facing −z). */\nexport const zFromDepth = (depth: number): number => -(1 + 0.7 * Math.min(depth, 10))\n\n/** S2 — deeper nesting = duller voice. Hz. */\nexport const cutoffFromDepth = (depth: number): number => Math.max(700, 9000 * Math.pow(0.82, depth))\n\n/** S3 — deeper nesting = quieter (distance loudness, Zahorik 2002). */\nexport const velocityFromDepth = (depth: number): number => Math.max(0.55, Math.pow(0.97, depth))\n\n/** S5 — positive z-index pulls the element toward the listener. Meters toward z=0. */\nexport const zBonusFromZIndex = (z: number): number => clamp(z / 50, 0, 1) * 0.8\n\n/** S4 — siblings climb the scale, wrapping each octave (do-re-mi…-do) so long lists stay melodic. */\nexport const stepsFromSiblingIndex = (i: number, scaleLen = 7): number => i % Math.max(1, scaleLen)\n\n/** S6 — headings: h1 lands lowest/grandest. Whole scale steps (negative = down). */\nexport const stepsFromHeadingLevel = (level: number): number => -(7 - clamp(level, 1, 6)) * 2\n\n/** S7/S8 — the viewport is the room. */\nexport function reverbFromViewport(vw: number): { decay: number; wet: number } {\n const t = norm(vw, 360, 2200)\n return { decay: lerp(0.6, 4.5, t), wet: lerp(0.08, 0.32, t) }\n}\n\n/** I13 — room tone color follows room size. Hz. */\nexport const ambienceCutoffFromViewport = (vw: number): number => lerp(400, 1400, norm(vw, 360, 2200))\n","/**\n * L0/L2 bridge — the ListenerRig: where the ears are (ARCHITECTURE.md §2).\n * Pointer/center modes + device-tilt offset, lerped each frame to avoid zipper artifacts.\n */\nimport * as Tone from 'tone'\nimport { ROOM_HALF_H, ROOM_HALF_W } from '../math/mapping'\nimport { clamp, lerp } from '../math/util'\n\nexport class ListenerRig {\n private target = { x: 0, y: 0 }\n private tilt = { x: 0, y: 0 }\n private pos = { x: 0, y: 0 }\n private raf = 0\n private running = false\n\n constructor(private mode: 'pointer' | 'center') {}\n\n start(): void {\n if (this.running) return\n this.running = true\n const listener = Tone.getListener()\n // Listener faces -z (WebAudio default); voices live at negative z (MAPPING.md S1).\n listener.forwardX.value = 0\n listener.forwardY.value = 0\n listener.forwardZ.value = -1\n listener.upY.value = 1\n const step = () => {\n if (!this.running) return\n const gx = clamp(this.target.x + this.tilt.x, -ROOM_HALF_W, ROOM_HALF_W)\n const gy = clamp(this.target.y + this.tilt.y, -ROOM_HALF_H, ROOM_HALF_H)\n this.pos.x = lerp(this.pos.x, gx, 0.12)\n this.pos.y = lerp(this.pos.y, gy, 0.12)\n try {\n listener.positionX.value = this.pos.x\n listener.positionY.value = this.pos.y\n listener.positionZ.value = 0\n } catch { /* context may be closing */ }\n this.raf = requestAnimationFrame(step)\n }\n this.raf = requestAnimationFrame(step)\n }\n\n /** I9 — pointer position (viewport-normalized 0..1) targets the ears. */\n pointTo(tx: number, ty: number): void {\n if (this.mode !== 'pointer') return\n // ×0.8: ears track the cursor but stay slightly behind it, keeping the field stable.\n this.target.x = (2 * clamp(tx, 0, 1) - 1) * ROOM_HALF_W * 0.8\n this.target.y = (1 - 2 * clamp(ty, 0, 1)) * ROOM_HALF_H * 0.8\n }\n\n /** I10 — device tilt offsets the ears (γ → x ±4 m, β → y ±2 m). */\n tiltTo(gamma: number, beta: number): void {\n this.tilt.x = clamp(gamma / 45, -1, 1) * 4\n this.tilt.y = clamp((beta - 40) / 45, -1, 1) * -2\n }\n\n dispose(): void {\n this.running = false\n cancelAnimationFrame(this.raf)\n }\n}\n","/**\n * L0 Acoustic Substrate — the Room: master chain (spatial input → warmth/brilliance shelves →\n * volume → limiter), viewport-sized reverb (S7/S8), ambience (I13), visibility fading (I14),\n * mute. In 'panner' mode it also owns the classic dry/wet routing; in 'ambisonic' mode the\n * AmbisonicBackend consumes `reverb` and `spatialIn` directly (SPATIAL.md §6). Imports Tone only.\n */\nimport * as Tone from 'tone'\nimport { ambienceCutoffFromViewport, reverbFromViewport } from '../math/mapping'\nimport { clamp } from '../math/util'\nimport { brillianceDb, warmthDb, type PerceptualFactors } from '../spatial/perceptual'\nimport type { VoiceBuses } from './voices'\n\nexport interface RoomOptions {\n volumeDb: number\n reverb: 'auto' | number\n ambient: number\n mode: 'panner' | 'ambisonic'\n}\n\nexport class Room {\n /** Classic v0.1 buses — meaningful in 'panner' mode (dryIn = spatialIn, wetIn = reverb). */\n readonly buses: VoiceBuses\n /** Everything audible enters here (gets the perceptual EQ + limiter). */\n readonly spatialIn: Tone.Gain\n readonly reverb: Tone.Reverb\n\n private master: Tone.Volume\n private limiter: Tone.Limiter\n private lowShelf: Tone.Filter\n private highShelf: Tone.Filter\n private wetGain: Tone.Gain | null = null\n private noise: Tone.Noise | null = null\n private noiseFilter: Tone.Filter | null = null\n private noiseGain: Tone.Gain | null = null\n private rushGain: Tone.Gain | null = null\n private resizeTimer: ReturnType<typeof setTimeout> | null = null\n private mutedNow = false\n private toneScale = 1\n\n constructor(private opts: RoomOptions, vw: number, factors: PerceptualFactors) {\n this.limiter = new Tone.Limiter(-1).toDestination()\n this.master = new Tone.Volume(opts.volumeDb).connect(this.limiter)\n this.highShelf = new Tone.Filter({ type: 'highshelf', frequency: 4000, gain: brillianceDb(factors.brilliance) }).connect(this.master)\n this.lowShelf = new Tone.Filter({ type: 'lowshelf', frequency: 250, gain: warmthDb(factors.warmth) }).connect(this.highShelf)\n this.spatialIn = new Tone.Gain(1).connect(this.lowShelf)\n\n const { decay, wet } = this.roomParams(vw)\n this.reverb = new Tone.Reverb({ decay, preDelay: 0.02, wet: 1 })\n if (opts.mode === 'panner') {\n this.wetGain = new Tone.Gain(wet).connect(this.spatialIn)\n this.reverb.connect(this.wetGain)\n }\n this.buses = { dryIn: this.spatialIn, wetIn: this.reverb }\n }\n\n setFactors(f: PerceptualFactors): void {\n this.lowShelf.gain.rampTo(warmthDb(f.warmth), 0.1)\n this.highShelf.gain.rampTo(brillianceDb(f.brilliance), 0.1)\n }\n\n private roomParams(vw: number): { decay: number; wet: number } {\n if (this.opts.reverb !== 'auto') {\n const decay = clamp(Number(this.opts.reverb) || 1.5, 0.1, 12)\n return { decay, wet: 0.25 }\n }\n return reverbFromViewport(vw)\n }\n\n /** Debounced: Tone.Reverb regenerates its impulse response when decay changes. */\n resize(vw: number): void {\n if (this.resizeTimer) clearTimeout(this.resizeTimer)\n this.resizeTimer = setTimeout(() => {\n const { decay, wet } = this.roomParams(vw)\n try {\n this.reverb.decay = decay\n this.wetGain?.gain.rampTo(wet, 0.3)\n this.noiseFilter?.frequency.rampTo(ambienceCutoffFromViewport(vw) * this.toneScale, 0.5)\n } catch (err) {\n console.warn('[sonarium] room resize failed', err)\n }\n }, 400)\n }\n\n /** I13 — room tone (sparkles became the phrase engine, PULSE.md §3). toneScale = CH7 warmth. */\n startAmbience(vw: number, level: number, toneScale = 1): void {\n if (level <= 0) return\n this.toneScale = toneScale\n this.noise = new Tone.Noise('brown')\n this.noiseFilter = new Tone.Filter({ frequency: ambienceCutoffFromViewport(vw) * toneScale, type: 'lowpass' })\n this.noiseGain = new Tone.Gain(Tone.dbToGain(-46) * clamp(level / 0.12, 0, 3))\n this.noise.connect(this.noiseFilter)\n this.noiseFilter.connect(this.noiseGain)\n this.noiseGain.connect(this.spatialIn)\n // Air-rush path (MATTER.md §2.2): scroll velocity swells the same room-tone noise.\n this.rushGain = new Tone.Gain(0)\n this.noiseFilter.connect(this.rushGain)\n this.rushGain.connect(this.spatialIn)\n this.noise.start()\n }\n\n /** MATTER.md §2.2 — moving through the page moves air. Swells fast, decays in ~450 ms. */\n rush(level: number): void {\n if (!this.rushGain || this.mutedNow) return\n const now = Tone.now()\n this.rushGain.gain.cancelScheduledValues(now)\n this.rushGain.gain.rampTo(level, 0.05, now)\n this.rushGain.gain.rampTo(0, 0.45, now + 0.07)\n }\n\n /** I14 — never sound in a background tab. */\n setHidden(hidden: boolean): void {\n if (this.mutedNow) return\n this.master.volume.rampTo(hidden ? -Infinity : this.opts.volumeDb, 0.3)\n }\n\n setMuted(muted: boolean): void {\n this.mutedNow = muted\n this.master.volume.rampTo(muted ? -Infinity : this.opts.volumeDb, 0.15)\n }\n\n dispose(): void {\n if (this.resizeTimer) clearTimeout(this.resizeTimer)\n this.noise?.dispose()\n this.noiseFilter?.dispose()\n this.noiseGain?.dispose()\n this.rushGain?.dispose()\n this.reverb.dispose()\n this.wetGain?.dispose()\n this.spatialIn.dispose()\n this.lowShelf.dispose()\n this.highShelf.dispose()\n this.master.dispose()\n this.limiter.dispose()\n }\n}\n","/**\n * The Matter weave — MATTER.md made executable. Four macro-dimensions condensed from visual\n * properties, each woven into bundles of co-varying synthesis parameters so the ear hears one\n * coherent object (Bregman fusion; Grey/McAdams timbre axes). Pure: no DOM, no Tone.\n * Change a formula here ⇄ change MATTER.md §2 in the same commit (Invariant #3).\n */\nimport { clamp, lerp } from './util'\n\nexport interface Matter {\n /** boundary abruptness, kiki↔bouba: 1 − roundness */\n edge: number\n /** size/weight: log-area sizeT */\n mass: number\n /** surface noisiness/airiness: shadows, translucency, dashed borders, media */\n texture: number\n /** distance into the room: normalized DOM depth */\n air: number\n}\n\nexport interface MatterVisuals {\n roundness: number\n sizeT: number\n depth: number\n shadowBlurPx: number\n opacity: number\n dashedBorder: boolean\n isMedia: boolean\n backdropBlurPx: number\n /** MODULAR.md M7 — typography enters the weave (bold text carries weight). Default 0. */\n massBonus?: number\n}\n\nexport function deriveMatter(v: MatterVisuals): Matter {\n const texture = clamp(\n clamp(v.shadowBlurPx / 40, 0, 0.4) +\n (1 - clamp(v.opacity, 0, 1)) * 0.6 +\n (v.dashedBorder ? 0.15 : 0) +\n (v.isMedia ? 0.35 : 0) +\n clamp(v.backdropBlurPx / 40, 0, 0.2),\n 0,\n 1,\n )\n return {\n edge: clamp(1 - v.roundness, 0, 1),\n mass: clamp(v.sizeT + (v.massBonus ?? 0), 0, 1),\n texture,\n air: clamp(Math.min(v.depth, 10) / 10, 0, 1),\n }\n}\n\n// ------------------------------------------------------------------ spectrum (MATTER.md §2.1)\n\nexport const PARTIAL_COUNT = 24\n\n/**\n * Continuous spectrum: EDGE sets the rolloff (bright↔pure), elongation sets hollowness\n * (long thin elements = pipes = odd harmonics), richness (CHROMA.md CH5: saturation)\n * subtracts from the rolloff exponent — vivid color = vivid spectrum. Normalized to Σa² = 1\n * so the whole continuum sits at equal loudness.\n */\nexport function genPartials(edge: number, elongation: number, richness = 0): Float32Array {\n const p = Math.max(0.8, 1 + 2.6 * (1 - clamp(edge, 0, 1)) - clamp(richness, 0, 0.5))\n const evenness = lerp(1, 0.12, clamp((elongation - 1) / 4, 0, 1))\n const a = new Float32Array(PARTIAL_COUNT)\n let energy = 0\n for (let k = 1; k <= PARTIAL_COUNT; k++) {\n const amp = (k % 2 === 1 ? 1 : evenness) / Math.pow(k, p)\n a[k - 1] = amp\n energy += amp * amp\n }\n const norm = 1 / Math.sqrt(energy || 1)\n for (let i = 0; i < PARTIAL_COUNT; i++) a[i] = (a[i] as number) * norm\n return a\n}\n\n// ------------------------------------------------------------------ noise weaves\n\nexport interface TransientSpec {\n /** noise burst length, seconds */\n lengthS: number\n /** high-pass corner of the burst, Hz */\n hpHz: number\n /** burst level relative to the voice (×velocity) */\n level: number\n}\n\n/** EDGE → the /k/ of kiki: a filtered click at onset. edge 0 → none. */\nexport function transient(edge: number): TransientSpec {\n const e = clamp(edge, 0, 1)\n return {\n lengthS: lerp(0.005, 0.025, e),\n hpHz: 2000 + 4000 * e,\n level: 0.7 * e,\n }\n}\n\nexport interface BreathSpec {\n /** sustained airy layer level (0 = pure tone) */\n level: number\n /** band-pass center as a ratio of the fundamental */\n bpRatio: number\n}\n\n/** TEXTURE → breath: translucent/soft-shadowed things are airy. */\nexport function breath(texture: number): BreathSpec {\n const t = clamp(texture, 0, 1)\n return { level: 0.22 * t, bpRatio: lerp(2.5, 1.2, t) }\n}\n\n/** TEXTURE → detune jitter in cents (rough surfaces are pitch-unstable). */\nexport const detuneJitterCents = (texture: number): number => 6 * clamp(texture, 0, 1)\n\n// ------------------------------------------------------------------ pitch behaviour\n\nexport interface SubShimmerSpec {\n /** semitone offset of osc B: −12 chest sub for massive, +12 sparkle for tiny */\n interval: number\n level: number\n}\n\n/** MASS → the second oscillator: big = chest, tiny = sparkle. */\nexport function subShimmer(mass: number): SubShimmerSpec {\n const m = clamp(mass, 0, 1)\n return {\n interval: m >= 0.45 ? -12 : 12,\n level: lerp(0.1, 0.38, clamp(Math.abs(m - 0.45) * 2, 0, 1)),\n }\n}\n\n/** ROUND → glide: the bouba swoop-in. Returns portamento seconds (0 for sharp). */\nexport const glideS = (edge: number): number => lerp(0.028, 0, clamp(edge, 0, 1))\n\n// ------------------------------------------------------------------ envelope weave\n\nexport interface EnvelopeSpec {\n attackS: number\n decayS: number\n sustain: number\n releaseScale: number\n}\n\n/** EDGE strikes, MASS adds inertia. */\nexport function envelopeWeave(edge: number, mass: number): EnvelopeSpec {\n const e = clamp(edge, 0, 1)\n const m = clamp(mass, 0, 1)\n return {\n attackS: lerp(0.045, 0.002, e) + 0.008 * m,\n decayS: lerp(0.4, 0.12, e),\n sustain: lerp(0.35, 0.15, e),\n releaseScale: lerp(0.8, 1.5, m),\n }\n}\n\n// ------------------------------------------------------------------ filter weave\n\nexport interface FilterWeaveSpec {\n q: number\n /** transient brightness bite: cutoff multiplier at onset, decaying to 1 */\n biteAmount: number\n biteDecayS: number\n}\n\n/** EDGE rings and bites. (Base cutoff itself comes from AIR via S2 + tilt, as before.) */\nexport function filterWeave(edge: number): FilterWeaveSpec {\n const e = clamp(edge, 0, 1)\n return {\n q: lerp(0.5, 2.4, e),\n biteAmount: 1 + 3 * e,\n biteDecayS: lerp(0.15, 0.06, e),\n }\n}\n\n// ------------------------------------------------------------------ reverb weave\n\nexport interface ReverbWeaveSpec {\n /** multiplier on the profile's base send */\n sendScale: number\n /** low-pass on the way into the reverb: dark sources bloom dark. Hz */\n sendCutoffHz: number\n /** 0 = arrive at full send immediately (sharp); 1 = swell from 35% over the note (round) */\n bloom: number\n /** spatial extent bonus from airy texture */\n extentBonus: number\n}\n\nexport function reverbWeave(edge: number, mass: number, texture: number): ReverbWeaveSpec {\n const e = clamp(edge, 0, 1)\n const m = clamp(mass, 0, 1)\n const t = clamp(texture, 0, 1)\n return {\n sendScale: lerp(1.3, 0.7, e) * lerp(0.85, 1.15, m),\n sendCutoffHz: lerp(1200, 7000, e),\n bloom: 1 - e,\n extentBonus: 0.15 * t,\n }\n}\n\n// ------------------------------------------------------------------ interaction weave\n\n/** I8 — scroll velocity (px/ms) → air-rush gain on the room tone, decaying over ~400 ms. */\nexport const airRushGain = (pxPerMs: number): number => clamp(pxPerMs * 0.06, 0, 0.18)\n","/**\n * L1 Page Reading — element → SonicProfile. Imports math + DOM, never Tone\n * (ARCHITECTURE.md §1 dependency rules).\n */\nimport {\n attackFromRoundness, brightnessTilt, cutoffFromDepth, degreeFromSize, durationFromElongation,\n panX, panY, pitchNudgeFromRoundness, qFromRoundness, roundness, sendFromShadowBlur, sizeT,\n stepsFromHeadingLevel, stepsFromSiblingIndex, velocityFromDepth, velocityFromSize,\n waveFromRoundness, zBonusFromZIndex, zFromDepth,\n} from '../math/mapping'\nimport { clamp } from '../math/util'\nimport { degreeToMidi, midiToFreq, midiToNoteName, type SiteKey } from '../math/scales'\nimport {\n breath, deriveMatter, detuneJitterCents, envelopeWeave, filterWeave, genPartials, glideS,\n reverbWeave, subShimmer, transient,\n} from '../math/matter'\nimport {\n attackScaleFromWarmth, brightnessFromLuminance, chromaOf, parseCssColor,\n richnessFromSaturation, subBonusFromWarmth, velocityFromLuminance, type Chroma,\n} from '../math/chroma'\nimport { massBonusFromFontWeight, patchFrom, type ModularVisuals } from '../math/modular'\nimport { directivityFromRoundness, extentFromSize, sphereFromRect } from '../spatial/sphere'\nimport { directivityFilterScale } from '../spatial/perceptual'\nimport { DEG } from '../spatial/sh'\nimport type { MatterVoiceParams, Rect, Role, SonicProfile, SphereProps, Theme, VoiceRecipe, Wave } from '../types'\n\nconst HEADING = /^H[1-6]$/\n\nexport function roleOf(el: Element): Role {\n const aria = (el.getAttribute('role') || '').toLowerCase()\n const override = (el as HTMLElement).dataset?.sonicRole as Role | undefined\n if (override) return override\n const tag = el.tagName\n const type = (el.getAttribute('type') || '').toLowerCase()\n if (tag === 'INPUT' && (type === 'checkbox' || type === 'radio')) return 'toggle'\n if (aria === 'switch' || aria === 'checkbox' || tag === 'SUMMARY') return 'toggle'\n if (tag === 'BUTTON' || aria === 'button' || (tag === 'INPUT' && (type === 'button' || type === 'submit' || type === 'reset'))) return 'button'\n if ((tag === 'A' && el.hasAttribute('href')) || aria === 'link') return 'link'\n if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || (el as HTMLElement).isContentEditable) return 'input'\n if (HEADING.test(tag) || aria === 'heading') return 'heading'\n if (tag === 'IMG' || tag === 'VIDEO' || tag === 'SVG' || tag === 'CANVAS' || tag === 'PICTURE' || tag === 'AUDIO') return 'media'\n if (tag === 'LI' || tag === 'TR' || ['listitem', 'option', 'menuitem', 'tab'].includes(aria)) return 'item'\n if (['NAV', 'SECTION', 'ARTICLE', 'ASIDE', 'FORM', 'FIELDSET', 'HEADER', 'FOOTER', 'MAIN', 'DIALOG'].includes(tag)) return 'container'\n if (['navigation', 'region', 'group', 'list', 'menu', 'tablist', 'dialog'].includes(aria)) return 'container'\n if (tag === 'P' || tag === 'BLOCKQUOTE' || tag === 'LABEL' || tag === 'SPAN') return 'text'\n return 'container'\n}\n\nexport function domDepth(el: Element, root: Element): number {\n let d = 0\n let n: Element | null = el\n while (n && n !== root && d < 32) {\n n = n.parentElement\n d++\n }\n return d\n}\n\nfunction eligibleSiblingIndex(el: Element): number {\n const parent = el.parentElement\n if (!parent) return 0\n let i = 0\n for (const sib of Array.from(parent.children)) {\n if (sib === el) return i\n if (sib.tagName === el.tagName || roleOf(sib) === roleOf(el)) i++\n }\n return 0\n}\n\nfunction recipeFor(role: Role, theme: Theme): VoiceRecipe {\n return { ...theme.defaults, ...(theme.roles[role] ?? {}) }\n}\n\nfunction isQuiet(el: Element): boolean {\n let n: Element | null = el\n while (n) {\n if ((n as HTMLElement).dataset?.sonic === 'quiet') return true\n n = n.parentElement\n }\n return false\n}\n\nconst NOTE_RE = /^([A-Ga-g][#b]?)(-?\\d)$/\nfunction pinnedMidi(spec: string | undefined): number | null {\n if (!spec) return null\n const m = spec.trim().match(NOTE_RE)\n if (!m) return null\n const pcs: Record<string, number> = { C: 0, 'C#': 1, Db: 1, D: 2, 'D#': 3, Eb: 3, E: 4, F: 5, 'F#': 6, Gb: 6, G: 7, 'G#': 8, Ab: 8, A: 9, 'A#': 10, Bb: 10, B: 11 }\n const name = (m[1] as string).charAt(0).toUpperCase() + (m[1] as string).slice(1)\n const pc = pcs[name]\n if (pc === undefined) return null\n return (parseInt(m[2] as string, 10) + 1) * 12 + pc\n}\n\nexport interface ProfileEnv {\n root: Element\n key: SiteKey\n theme: Theme\n vw: number\n vh: number\n}\n\n/** CSS custom property, trimmed; '' when unset. Inherits down the tree (the aural stylesheet). */\nfunction sonicVar(cs: CSSStyleDeclaration, name: string): string {\n return cs.getPropertyValue(name).trim()\n}\n\n/** Compute the full acoustic identity of an element. Pure given (el state, env). */\nexport function profileOf(el: Element, env: ProfileEnv): SonicProfile {\n const { key, theme, vw, vh } = env\n const html = el as HTMLElement\n const reasons: Record<string, string> = {}\n\n const cs = getComputedStyle(el)\n const r = el.getBoundingClientRect()\n const rect: Rect = { x: r.x, y: r.y, w: Math.max(1, r.width), h: Math.max(1, r.height) }\n // Priority: data-sonic-role > --sonic-role > inference (CHROMA.md §4).\n const role = (html.dataset?.sonicRole as Role | undefined)\n || (sonicVar(cs, '--sonic-role') as Role | '')\n || roleOf(el)\n const recipe = recipeFor(role, theme)\n reasons.role = `<${el.tagName.toLowerCase()}> reads as \"${role}\" → ${recipe.synthKind} voice (theme ${theme.name})`\n // border-radius percentages survive into computed style — resolve against the box.\n const radiusRaw = cs.borderTopLeftRadius\n const radiusPx = radiusRaw.endsWith('%')\n ? ((parseFloat(radiusRaw) || 0) / 100) * Math.min(rect.w, rect.h)\n : parseFloat(radiusRaw) || 0\n const opacity = parseFloat(cs.opacity)\n const shadowBlur = parseShadowBlur(cs.boxShadow)\n const zIndex = cs.position !== 'static' ? parseInt(cs.zIndex, 10) || 0 : 0\n\n // Space (G1, G2, S1, S5)\n const depth = domDepth(el, env.root)\n const pan = {\n x: panX(rect, vw),\n y: panY(rect, vh),\n z: zFromDepth(depth) + zBonusFromZIndex(zIndex),\n }\n reasons.position = `center (${Math.round(rect.x + rect.w / 2)}, ${Math.round(rect.y + rect.h / 2)}) px → (${pan.x.toFixed(1)}, ${pan.y.toFixed(1)}) m; depth ${depth} → ${pan.z.toFixed(1)} m away`\n\n // Pitch (G4, S4, S6, G10) through the quantizer\n const st = sizeT(rect, vw, vh)\n const degree = degreeFromSize(st)\n const round = roundness(radiusPx, rect)\n let steps = stepsFromSiblingIndex(eligibleSiblingIndex(el), key.scale.length) + pitchNudgeFromRoundness(round)\n if (role === 'heading') {\n const level = HEADING.test(el.tagName) ? parseInt(el.tagName[1] as string, 10) : 2\n steps += stepsFromHeadingLevel(level)\n }\n steps += recipe.octaveShift * key.scale.length\n const pinned = pinnedMidi(html.dataset?.sonicNote ?? sonicVar(cs, '--sonic-note') ?? undefined)\n const midi = pinned ?? degreeToMidi(degree, key, steps)\n reasons.pitch = pinned !== null\n ? `pinned by data-sonic-note → ${midiToNoteName(midi)}`\n : `area ${(rect.w * rect.h / 1000).toFixed(1)}k px² (size ${st.toFixed(2)}) + sibling/heading offsets → ${midiToNoteName(midi)} in ${key.label}`\n\n // Timbre (G6–G9) — Kiki/Bouba\n const wave: Wave = (html.dataset?.sonicWave as Wave)\n || (sonicVar(cs, '--sonic-wave') as Wave | '')\n || recipe.pinWave\n || waveFromRoundness(round)\n const attack = attackFromRoundness(round)\n reasons.timbre = `roundness ${round.toFixed(2)} (radius ${radiusPx}px) → ${wave} wave, ${(attack * 1000).toFixed(0)} ms attack`\n\n // Duration (G11)\n const durationS = durationFromElongation(rect)\n reasons.duration = `aspect ${(Math.max(rect.w, rect.h) / Math.min(rect.w, rect.h)).toFixed(1)}:1 → ${durationS.toFixed(2)} s`\n\n // Sphere — the 聲球 (SPATIAL.md SP1–SP5)\n const dir = sphereFromRect(rect, vw, vh)\n const extentOverride = parseFloat(html.dataset?.sonicExtent ?? sonicVar(cs, '--sonic-extent'))\n const sphere: SphereProps = {\n azimuth: dir.azimuth,\n elevation: dir.elevation,\n extent: isNaN(extentOverride) ? extentFromSize(st) : clamp(extentOverride, 0, 1),\n directivity: directivityFromRoundness(round),\n }\n reasons.sphere = `az ${(sphere.azimuth / DEG).toFixed(0)}°, el ${(sphere.elevation / DEG).toFixed(0)}°, extent ${sphere.extent.toFixed(2)} (size wraps the listener), directivity ${sphere.directivity.toFixed(2)} (sharp beams, round radiates)`\n\n // The Chroma weave (CHROMA.md §1) — the element's color as mood, extracted once, used below.\n const chroma = elementChroma(el, cs, role)\n\n // Filter (S2 · G3, G9, CH1) — depth, height, directivity and color luminance share the cutoff\n const filterHz = cutoffFromDepth(depth) * brightnessTilt(rect, vh)\n * directivityFilterScale(sphere.directivity) * brightnessFromLuminance(chroma.luminance)\n reasons.filter = `depth ${depth} + vertical position + directivity + luminance → low-pass ${Math.round(filterHz)} Hz`\n\n // Loudness (G5, G12, S3, CH2, quiet via attribute or --sonic custom property)\n let velocityScale = recipe.baseVelocity * velocityFromSize(st) * velocityFromDepth(depth)\n * (isNaN(opacity) ? 1 : opacity) * velocityFromLuminance(chroma.luminance)\n const sonicMode = sonicVar(cs, '--sonic')\n if (isQuiet(el) || sonicMode === 'quiet') velocityScale *= 0.4\n if (sonicMode === 'off') {\n velocityScale = 0\n reasons.silenced = '--sonic: off (aural stylesheet)'\n }\n velocityScale = clamp(velocityScale, 0, 1.5)\n\n // The Matter weave (MATTER.md §2) — one material, many co-varying cues.\n const elongation = Math.max(rect.w, rect.h) / Math.max(1, Math.min(rect.w, rect.h))\n const textish = role === 'text' || role === 'heading' || role === 'link' || role === 'button'\n const fontWeight = textish ? parseInt(cs.fontWeight, 10) || 400 : 400\n const matter = deriveMatter({\n roundness: round,\n sizeT: st,\n depth,\n shadowBlurPx: shadowBlur,\n opacity: isNaN(opacity) ? 1 : opacity,\n dashedBorder: cs.borderTopStyle === 'dashed' || cs.borderTopStyle === 'dotted',\n isMedia: role === 'media',\n backdropBlurPx: parseBackdropBlur(cs),\n massBonus: massBonusFromFontWeight(fontWeight),\n })\n\n // The modular patch (MODULAR.md §1) — CSS plugs the cables.\n const modVisuals: ModularVisuals = {\n animationS: cs.animationName && cs.animationName !== 'none' ? firstSeconds(cs.animationDuration) : 0,\n borderStyle: (['solid', 'dashed', 'dotted'].includes(cs.borderTopStyle) ? cs.borderTopStyle : 'none') as ModularVisuals['borderStyle'],\n borderWidthPx: parseFloat(cs.borderTopWidth) || 0,\n transitionS: firstSeconds(cs.transitionDuration),\n }\n const patch = patchFrom(matter, modVisuals)\n // Chroma tints the matter (CH3–CH5) — never a second instrument.\n const env0 = envelopeWeave(matter.edge, matter.mass)\n const sub0 = subShimmer(matter.mass)\n const voice: MatterVoiceParams = {\n matter,\n partials: Array.from(genPartials(matter.edge, elongation, richnessFromSaturation(chroma.saturation))),\n transient: transient(matter.edge),\n breath: breath(matter.texture),\n subShimmer: {\n interval: sub0.interval,\n level: sub0.level + (sub0.interval < 0 ? subBonusFromWarmth(chroma.warmth) : 0),\n },\n glideS: glideS(matter.edge),\n jitterCents: detuneJitterCents(matter.texture),\n envelope: { ...env0, attackS: env0.attackS * attackScaleFromWarmth(chroma.warmth) },\n filter: filterWeave(matter.edge),\n reverb: reverbWeave(matter.edge, matter.mass, matter.texture),\n patch,\n }\n if (patch.fold.mix > 0.05 || patch.fm.index > 0.05 || patch.lfo.rateHz > 0.01 || patch.unison.mix > 0) {\n reasons.patch = [\n patch.fold.mix > 0.05 ? `border drives the wavefolder ×${patch.fold.drive.toFixed(2)}` : '',\n patch.fm.index > 0.05 ? `FM ring ${patch.fm.index.toFixed(2)}` : '',\n patch.unison.mix > 0 ? `unison +${patch.unison.detuneCents.toFixed(0)}¢` : '',\n patch.lfo.rateHz > 0.01 ? `${patch.lfo.shape} LFO ${patch.lfo.rateHz.toFixed(2)} Hz (${modVisuals.animationS > 0 ? 'css animation' : 'dashed border'})` : '',\n ].filter(Boolean).join(' · ')\n }\n reasons.chroma = `warmth ${chroma.warmth.toFixed(2)} · sat ${chroma.saturation.toFixed(2)} · lum ${chroma.luminance.toFixed(2)} → ${chroma.warmth > 0.6 ? 'eager onset, full body' : chroma.warmth < 0.4 ? 'cool, unhurried onset' : 'neutral temperament'}${chroma.saturation > 0.5 ? ', vivid spectrum' : ''}`\n reasons.matter = `edge ${matter.edge.toFixed(2)} · mass ${matter.mass.toFixed(2)} · texture ${matter.texture.toFixed(2)} · air ${matter.air.toFixed(2)} → ${voice.transient.level > 0.1 ? 'clicky' : 'soft'}, ${voice.breath.level > 0.05 ? 'breathy' : 'clean'}, ${voice.subShimmer.interval < 0 ? 'chest sub' : 'sparkle +8va'}, ${voice.reverb.bloom > 0.5 ? 'blooms into the room' : 'dry strike'}`\n\n // Room (G13 + MATTER reverb weave + SP3 distance wetness)\n const reverbSend = clamp(\n (0.18 + sendFromShadowBlur(shadowBlur) + 0.05 * Math.min(depth, 10) * 0.5) * voice.reverb.sendScale,\n 0,\n 1.2,\n )\n\n return {\n role, rect, pan, sphere,\n midi, freqHz: midiToFreq(midi), degree,\n wave, attack, release: 0.3 * recipe.releaseScale, durationS,\n filterHz, filterQ: qFromRoundness(round),\n velocityScale, reverbSend,\n synthKind: recipe.synthKind, octaveShift: recipe.octaveShift,\n voice, chroma,\n reasons,\n }\n}\n\n/** CHROMA.md §1 — text-ish roles speak in their text color; boxes speak in their background,\n * walking up past transparent ancestors. */\nfunction elementChroma(el: Element, cs: CSSStyleDeclaration, role: Role): Chroma {\n if (role === 'text' || role === 'heading' || role === 'link') {\n return chromaOf(parseCssColor(cs.color))\n }\n let probe: Element | null = el\n let style: CSSStyleDeclaration | undefined = cs\n for (let hops = 0; probe && hops < 6; hops++) {\n const rgb = parseCssColor((style ?? getComputedStyle(probe)).backgroundColor)\n if (rgb && rgb.a >= 0.05) return chromaOf(rgb)\n probe = probe.parentElement\n style = undefined\n }\n return chromaOf(parseCssColor(getComputedStyle(document.documentElement).backgroundColor))\n}\n\n/** First duration in a comma list (\"2s, 0.5s\" → 2; \"250ms\" → 0.25). */\nfunction firstSeconds(list: string): number {\n const first = (list || '').split(',')[0]?.trim() ?? ''\n if (!first) return 0\n const v = parseFloat(first)\n if (isNaN(v)) return 0\n return first.endsWith('ms') ? v / 1000 : v\n}\n\nfunction parseBackdropBlur(cs: CSSStyleDeclaration): number {\n const bf = cs.backdropFilter || (cs as unknown as Record<string, string>).webkitBackdropFilter || ''\n const m = bf.match(/blur\\((\\d+(\\.\\d+)?)px\\)/)\n return m ? parseFloat(m[1] as string) : 0\n}\n\nfunction parseShadowBlur(boxShadow: string): number {\n if (!boxShadow || boxShadow === 'none') return 0\n // blur is the 3rd length in each shadow; take the max across shadows\n let max = 0\n for (const part of boxShadow.split(/,(?![^(]*\\))/)) {\n const lengths = part.match(/-?\\d+(\\.\\d+)?px/g)\n if (lengths && lengths.length >= 3) max = Math.max(max, parseFloat(lengths[2] as string))\n }\n return max\n}\n","/**\n * L1 Page Reading — eligibility, registry, observers, visible set (ARCHITECTURE.md §5).\n * Imports DOM only; produces data + callbacks, triggers nothing audible itself.\n */\nimport type { SonicProfile } from '../types'\nimport { profileOf, roleOf, type ProfileEnv } from './profile'\n\nexport const ELIGIBLE_SELECTOR = [\n 'button', '[role=button]', 'input', 'textarea', 'select', '[contenteditable]',\n 'a[href]', '[role=link]', 'summary', '[role=switch]', '[role=checkbox]',\n 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', '[role=heading]',\n 'img', 'video', 'canvas', 'svg', 'picture',\n 'li', 'tr', '[role=listitem]', '[role=option]', '[role=menuitem]', '[role=tab]',\n 'nav', 'section', 'article', 'aside', 'form', 'fieldset', 'dialog',\n '[data-sonic-role]', '[data-sonic-note]',\n].join(',')\n\nconst MAX_TRACKED = 400\n\ninterface Entry {\n profile: SonicProfile | null\n visible: boolean\n}\n\nexport interface ScannerCallbacks {\n /** Fired when an element scrolls/loads into view after the initial scan (I7 whisper). */\n onAppear: (el: Element) => void\n}\n\nexport class Scanner {\n readonly registry = new Map<Element, Entry>()\n private io: IntersectionObserver | null = null\n private mo: MutationObserver | null = null\n private capWarned = false\n private initialScanDone = false\n private mutationTimer: ReturnType<typeof setTimeout> | null = null\n\n constructor(\n private env: ProfileEnv,\n private cb: ScannerCallbacks,\n ) {}\n\n scan(): void {\n if (typeof IntersectionObserver !== 'undefined') {\n this.io = new IntersectionObserver((entries) => {\n for (const e of entries) {\n const entry = this.registry.get(e.target)\n if (!entry) continue\n const was = entry.visible\n entry.visible = e.isIntersecting\n if (e.isIntersecting) entry.profile = null // rect changed while away; recompute lazily\n if (e.isIntersecting && !was && this.initialScanDone) this.cb.onAppear(e.target)\n }\n }, { threshold: 0.15 })\n }\n\n this.register(this.env.root)\n for (const el of Array.from(this.env.root.querySelectorAll(ELIGIBLE_SELECTOR))) this.register(el)\n\n if (typeof MutationObserver !== 'undefined') {\n this.mo = new MutationObserver((muts) => this.queueMutations(muts))\n this.mo.observe(this.env.root, { subtree: true, childList: true, attributes: true, attributeFilter: ['class', 'style', 'data-sonic', 'data-sonic-note', 'data-sonic-wave', 'data-sonic-role'] })\n }\n\n // Let the initial IntersectionObserver flood settle before treating entries as \"appearances\".\n setTimeout(() => { this.initialScanDone = true }, 300)\n }\n\n private register(el: Element): void {\n if (this.registry.has(el) || this.isOff(el)) return\n if (this.registry.size >= MAX_TRACKED) {\n if (!this.capWarned) {\n this.capWarned = true\n console.warn(`[sonarium] page exceeds ${MAX_TRACKED} tracked elements; extra elements stay silent`)\n }\n return\n }\n this.registry.set(el, { profile: null, visible: false })\n this.io?.observe(el)\n }\n\n private unregister(el: Element): void {\n if (!this.registry.has(el)) return\n this.registry.delete(el)\n this.io?.unobserve(el)\n }\n\n isOff(el: Element): boolean {\n let n: Element | null = el\n while (n) {\n if ((n as HTMLElement).dataset?.sonic === 'off') return true\n n = n.parentElement\n }\n return false\n }\n\n private queueMutations(muts: MutationRecord[]): void {\n if (this.mutationTimer) clearTimeout(this.mutationTimer)\n const records = muts\n this.mutationTimer = setTimeout(() => {\n for (const m of records) {\n if (m.type === 'attributes' && m.target instanceof Element) {\n const entry = this.registry.get(m.target)\n if (entry) entry.profile = null\n continue\n }\n for (const node of Array.from(m.addedNodes)) {\n if (!(node instanceof Element)) continue\n if (node.matches?.(ELIGIBLE_SELECTOR)) this.register(node)\n for (const el of Array.from(node.querySelectorAll?.(ELIGIBLE_SELECTOR) ?? [])) this.register(el)\n }\n for (const node of Array.from(m.removedNodes)) {\n if (!(node instanceof Element)) continue\n this.unregister(node)\n for (const el of Array.from(node.querySelectorAll?.(ELIGIBLE_SELECTOR) ?? [])) this.unregister(el)\n }\n }\n }, 150)\n }\n\n /** Profile with lazy compute + cache (cheap path: geometry invalidation only nulls it). */\n profileFor(el: Element): SonicProfile | null {\n if (this.isOff(el)) return null\n let entry = this.registry.get(el)\n if (!entry) {\n // Untracked but asked for (e.g. describe() on an arbitrary element): compute one-off.\n return safeProfile(el, this.env)\n }\n if (!entry.profile) entry.profile = safeProfile(el, this.env)\n return entry.profile\n }\n\n /** Geometry changed globally (scroll/resize): rects are stale, voices params survive. */\n invalidateRects(): void {\n for (const entry of this.registry.values()) entry.profile = null\n }\n\n visibleElements(): Element[] {\n const out: Element[] = []\n for (const [el, entry] of this.registry) if (entry.visible) out.push(el)\n return out\n }\n\n /** The element (or nearest registered ancestor) the scanner knows about. */\n resolve(target: Element | null): Element | null {\n let n: Element | null = target\n while (n) {\n if (this.registry.has(n)) return n\n n = n.parentElement\n }\n return null\n }\n\n updateEnv(vw: number, vh: number): void {\n this.env.vw = vw\n this.env.vh = vh\n }\n\n dispose(): void {\n if (this.mutationTimer) clearTimeout(this.mutationTimer)\n this.io?.disconnect()\n this.mo?.disconnect()\n this.registry.clear()\n }\n}\n\nfunction safeProfile(el: Element, env: ProfileEnv): SonicProfile | null {\n try {\n return profileOf(el, env)\n } catch (err) {\n console.warn('[sonarium] profile failed', err)\n return null\n }\n}\n\nexport { roleOf }\n","/**\n * MatterVoice — the woven, modular instrument (MATTER.md §3 + MODULAR.md §2).\n * Harmonic core (custom spectrum + sub/shimmer partner + unison twin) through a wavefolder,\n * audio-rate FM cable from oscB, breath + burst noise layers, and one LFO patched from CSS\n * (vibrato / tremolo / filter wobble). Supports one-shot triggers, sustained ribbon gating,\n * and sleeping (all sources stop when idle; restart in place). Imports Tone only.\n */\nimport * as Tone from 'tone'\nimport { foldCurve } from '../math/modular'\nimport type { MatterVoiceParams } from '../types'\n\nexport interface MatterTrigger {\n freqHz: number\n velocity: number\n durationS: number\n releaseScaleBase: number\n voice: MatterVoiceParams\n}\n\nconst FOLD_CURVE = foldCurve()\n\nexport class MatterVoice {\n /** Pool connects this to the lane filter's frequency param (LFO wobble tap). */\n readonly modFilterOut: Tone.Gain\n\n private oscA: Tone.Oscillator\n private oscA2: Tone.Oscillator\n private oscB: Tone.Oscillator\n private oscBGain: Tone.Gain\n private fmGain: Tone.Gain\n private foldPre: Tone.Gain\n private foldShaper: Tone.WaveShaper\n private foldWet: Tone.Gain\n private foldDry: Tone.Gain\n private unisonGain: Tone.Gain\n private breathNoise: Tone.Noise\n private breathFilter: Tone.Filter\n private breathGain: Tone.Gain\n private burstNoise: Tone.Noise\n private burstFilter: Tone.Filter\n private burstEnv: Tone.AmplitudeEnvelope\n private ampEnv: Tone.AmplitudeEnvelope\n private mix: Tone.Gain\n private lfo: Tone.LFO\n private lfoVib: Tone.Gain\n private lfoTrem: Tone.Gain\n private out: Tone.Gain\n private startedSources = false\n private held = false\n\n constructor() {\n this.out = new Tone.Gain(1)\n this.mix = new Tone.Gain(0.9)\n\n this.oscA = new Tone.Oscillator({ frequency: 220 })\n this.oscA2 = new Tone.Oscillator({ frequency: 220 })\n this.oscB = new Tone.Oscillator({ frequency: 110, type: 'sine' })\n this.oscBGain = new Tone.Gain(0.2)\n\n // The wavefolder (MODULAR.md M1): oscA splits dry/folded; envelope sweeps the fold.\n this.foldPre = new Tone.Gain(0.3)\n this.foldShaper = new Tone.WaveShaper(FOLD_CURVE)\n this.foldWet = new Tone.Gain(0)\n this.foldDry = new Tone.Gain(1)\n this.oscA.connect(this.foldPre)\n this.foldPre.connect(this.foldShaper)\n this.foldShaper.connect(this.foldWet)\n this.foldWet.connect(this.mix)\n this.oscA.connect(this.foldDry)\n this.foldDry.connect(this.mix)\n\n // Unison twin stays clean (thickness without mud).\n this.unisonGain = new Tone.Gain(0)\n this.oscA2.connect(this.unisonGain)\n this.unisonGain.connect(this.mix)\n\n // The FM cable (M2): oscB modulates oscA's frequency at audio rate.\n this.fmGain = new Tone.Gain(0)\n this.oscB.connect(this.fmGain)\n this.fmGain.connect(this.oscA.frequency)\n this.oscB.connect(this.oscBGain)\n this.oscBGain.connect(this.mix)\n\n this.breathNoise = new Tone.Noise('pink')\n this.breathFilter = new Tone.Filter({ type: 'bandpass', frequency: 600, Q: 1.1 })\n this.breathGain = new Tone.Gain(0)\n this.breathNoise.connect(this.breathFilter)\n this.breathFilter.connect(this.breathGain)\n this.breathGain.connect(this.mix)\n\n this.ampEnv = new Tone.AmplitudeEnvelope({ attack: 0.01, decay: 0.2, sustain: 0.25, release: 0.3 })\n this.mix.connect(this.ampEnv)\n this.ampEnv.connect(this.out)\n\n // The /k/ of kiki: bypasses the amp envelope so it stays a crisp onset event.\n this.burstNoise = new Tone.Noise('white')\n this.burstFilter = new Tone.Filter({ type: 'highpass', frequency: 3000 })\n this.burstEnv = new Tone.AmplitudeEnvelope({ attack: 0.001, decay: 0.02, sustain: 0, release: 0.02 })\n this.burstNoise.connect(this.burstFilter)\n this.burstFilter.connect(this.burstEnv)\n this.burstEnv.connect(this.out)\n\n // One LFO, three depth taps (M4/M5): vibrato, tremolo, filter wobble.\n this.lfo = new Tone.LFO({ frequency: 0.5, min: -1, max: 1, type: 'sine' })\n this.lfoVib = new Tone.Gain(0)\n this.lfoTrem = new Tone.Gain(0)\n this.modFilterOut = new Tone.Gain(0)\n this.lfo.connect(this.lfoVib)\n this.lfo.connect(this.lfoTrem)\n this.lfo.connect(this.modFilterOut)\n this.lfoVib.connect(this.oscA.detune)\n this.lfoVib.connect(this.oscA2.detune)\n this.lfoTrem.connect(this.mix.gain)\n }\n\n connect(dest: Tone.InputNode): this {\n this.out.connect(dest)\n return this\n }\n\n private ensureRunning(when: number): void {\n if (this.startedSources) return\n this.startedSources = true\n this.oscA.start(when)\n this.oscA2.start(when)\n this.oscB.start(when)\n this.breathNoise.start(when)\n this.burstNoise.start(when)\n this.lfo.start(when)\n }\n\n /** MODULAR.md §4 — idle lanes power down completely; the next trigger restarts in place. */\n sleep(): void {\n if (!this.startedSources || this.held) return\n this.startedSources = false\n try {\n this.oscA.stop()\n this.oscA2.stop()\n this.oscB.stop()\n this.breathNoise.stop()\n this.burstNoise.stop()\n this.lfo.stop()\n } catch { /* already stopped */ }\n }\n\n /** Everything both trigger() and gateOn() share: spectrum, patch, pitch, modulation. */\n private applyVoice(t: MatterTrigger, when: number, baseCutoffHz: number): void {\n const v = t.voice\n this.ensureRunning(when)\n this.oscA.partials = v.partials\n this.oscA2.partials = v.partials\n\n // Pitch behaviour: glide for round (+M6 portamento), jitter for rough texture.\n const jitter = (Math.random() * 2 - 1) * v.jitterCents\n this.oscA.detune.setValueAtTime(jitter, when)\n const glide = v.glideS + v.patch.portamentoS\n if (glide > 0.002 && !this.held) {\n this.oscA.frequency.setValueAtTime(t.freqHz * 0.917, when)\n this.oscA.frequency.rampTo(t.freqHz, glide, when)\n } else {\n this.oscA.frequency.setValueAtTime(t.freqHz, when)\n }\n this.oscA2.frequency.setValueAtTime(t.freqHz, when)\n this.oscA2.detune.setValueAtTime(jitter + v.patch.unison.detuneCents, when)\n this.unisonGain.gain.rampTo(v.patch.unison.mix, 0.02, when)\n this.oscB.frequency.setValueAtTime(t.freqHz * Math.pow(2, v.subShimmer.interval / 12), when)\n this.oscBGain.gain.rampTo(v.subShimmer.level, 0.02, when)\n\n // Modular patch: fold drive/mix, FM index (× carrier), LFO rate/shape/depths.\n this.foldPre.gain.rampTo(0.3 + v.patch.fold.drive * 1.2, 0.02, when)\n this.foldWet.gain.rampTo(v.patch.fold.mix, 0.02, when)\n this.foldDry.gain.rampTo(1 - v.patch.fold.mix * 0.7, 0.02, when)\n this.fmGain.gain.rampTo(v.patch.fm.index * t.freqHz, 0.02, when)\n const lfoOn = v.patch.lfo.rateHz > 0.01\n this.lfo.frequency.value = Math.max(0.01, v.patch.lfo.rateHz)\n this.lfo.type = v.patch.lfo.shape\n this.lfoVib.gain.rampTo(lfoOn ? v.patch.lfo.vibratoCents : 0, 0.05, when)\n this.lfoTrem.gain.rampTo(lfoOn ? 0.9 * v.patch.lfo.tremolo : 0, 0.05, when)\n this.modFilterOut.gain.rampTo(lfoOn ? v.patch.lfo.filterDepth * baseCutoffHz : 0, 0.05, when)\n\n // Breath rides the tone (common fate = fusion).\n this.breathFilter.frequency.rampTo(Math.min(8000, t.freqHz * v.breath.bpRatio), 0.02, when)\n this.breathGain.gain.rampTo(v.breath.level, 0.02, when)\n\n // Envelope weave.\n this.ampEnv.attack = v.envelope.attackS\n this.ampEnv.decay = v.envelope.decayS\n this.ampEnv.sustain = v.envelope.sustain\n this.ampEnv.release = 0.3 * t.releaseScaleBase * v.envelope.releaseScale\n }\n\n trigger(t: MatterTrigger, when: number, baseCutoffHz = 4000): void {\n this.applyVoice(t, when, baseCutoffHz)\n this.ampEnv.triggerAttackRelease(t.durationS, when, t.velocity)\n if (t.voice.transient.level > 0.02) {\n this.burstFilter.frequency.setValueAtTime(t.voice.transient.hpHz, when)\n this.burstEnv.decay = t.voice.transient.lengthS\n this.burstEnv.triggerAttackRelease(t.voice.transient.lengthS, when, t.velocity * t.voice.transient.level)\n }\n }\n\n // ----------------------------------------------------------- ribbon (MODULAR.md §3)\n\n gateOn(t: MatterTrigger, when: number, baseCutoffHz = 4000): void {\n this.applyVoice(t, when, baseCutoffHz)\n this.held = true\n this.ampEnv.sustain = Math.max(0.4, t.voice.envelope.sustain)\n this.ampEnv.triggerAttack(when, t.velocity)\n }\n\n /** Ribbon pitch move — quantized upstream; the portamento IS the glissando feel. */\n setFreq(freqHz: number, glideS: number, subInterval: number, fmIndex: number): void {\n const g = Math.max(0.015, glideS)\n this.oscA.frequency.rampTo(freqHz, g)\n this.oscA2.frequency.rampTo(freqHz, g)\n this.oscB.frequency.rampTo(freqHz * Math.pow(2, subInterval / 12), g)\n this.fmGain.gain.rampTo(fmIndex * freqHz, g)\n }\n\n gateOff(when?: number): number {\n this.held = false\n this.ampEnv.triggerRelease(when ?? Tone.now())\n return this.ampEnv.release as number\n }\n\n releaseTail(): number {\n return this.ampEnv.release as number\n }\n\n dispose(): void {\n for (const n of [\n this.oscA, this.oscA2, this.oscB, this.oscBGain, this.fmGain,\n this.foldPre, this.foldShaper, this.foldWet, this.foldDry, this.unisonGain,\n this.breathNoise, this.breathFilter, this.breathGain,\n this.burstNoise, this.burstFilter, this.burstEnv,\n this.lfo, this.lfoVib, this.lfoTrem, this.modFilterOut,\n this.ampEnv, this.mix, this.out,\n ]) n.dispose()\n }\n}\n","/**\n * L0 Acoustic Substrate — VoicePool (ARCHITECTURE.md §4).\n * Profiles are data; voices are rented lanes configured at trigger time. Spatial placement is\n * delegated to the active SpatialBackend (ambisonic field or per-voice panners — SPATIAL.md §6).\n * Imports Tone only; never reads the DOM.\n */\nimport * as Tone from 'tone'\nimport { clamp } from '../math/util'\nimport type { SonicProfile, SynthKind } from '../types'\nimport type { LaneOutput, SpatialBackend } from '../spatial/backend'\nimport { MatterVoice } from './matter-voice'\n\ntype AnySynth = Tone.Synth | Tone.FMSynth | Tone.PluckSynth | Tone.MembraneSynth | Tone.NoiseSynth | MatterVoice\n\ninterface Lane {\n kind: SynthKind\n synth: AnySynth\n filter: Tone.Filter\n out: LaneOutput\n busyUntil: number\n}\n\nexport interface VoiceBuses {\n dryIn: Tone.InputNode\n wetIn: Tone.InputNode\n}\n\nexport class VoicePool {\n private lanes: Lane[] = []\n private sleepTimer: ReturnType<typeof setInterval>\n\n constructor(\n private backend: SpatialBackend,\n private maxVoices: number,\n ) {\n this.maxVoices = clamp(maxVoices, 4, 24)\n // MODULAR.md §4 — idle matter lanes power down (silent page ⇒ ~zero steady-state CPU).\n this.sleepTimer = setInterval(() => {\n const now = Tone.now()\n for (const lane of this.lanes) {\n if (lane.synth instanceof MatterVoice && lane.busyUntil < now - 30) lane.synth.sleep()\n }\n }, 10000)\n }\n\n private createSynth(kind: SynthKind): AnySynth {\n switch (kind) {\n case 'matter':\n return new MatterVoice()\n case 'fm':\n return new Tone.FMSynth({ harmonicity: 3, modulationIndex: 8, envelope: { attack: 0.01, decay: 0.3, sustain: 0.1, release: 1.4 }, modulationEnvelope: { attack: 0.01, decay: 0.4, sustain: 0.2, release: 1 } })\n case 'pluck':\n return new Tone.PluckSynth({ attackNoise: 1, dampening: 3000, resonance: 0.92 })\n case 'membrane':\n return new Tone.MembraneSynth({ pitchDecay: 0.04, octaves: 5, envelope: { attack: 0.001, decay: 0.35, sustain: 0.01, release: 0.6 } })\n case 'noise':\n return new Tone.NoiseSynth({ noise: { type: 'white' }, envelope: { attack: 0.001, decay: 0.06, sustain: 0, release: 0.05 } })\n default:\n return new Tone.Synth({ oscillator: { type: 'triangle' }, envelope: { attack: 0.01, decay: 0.1, sustain: 0.25, release: 0.3 } })\n }\n }\n\n private createLane(kind: SynthKind): Lane {\n const synth = this.createSynth(kind)\n const filter = new Tone.Filter({ frequency: 4000, type: 'lowpass', rolloff: -12, Q: 1 })\n const out = this.backend.createOutput()\n synth.connect(filter)\n filter.connect(out.input)\n // The LFO's filter-wobble tap (MODULAR.md M4/M5) modulates the lane filter additively.\n if (synth instanceof MatterVoice) synth.modFilterOut.connect(filter.frequency)\n const lane: Lane = { kind, synth, filter, out, busyUntil: 0 }\n this.lanes.push(lane)\n return lane\n }\n\n private acquire(kind: SynthKind): Lane {\n const now = Tone.now()\n let candidate: Lane | null = null\n let oldestSameKind: Lane | null = null\n let oldestAny: Lane | null = null\n for (const lane of this.lanes) {\n if (lane.kind === kind) {\n if (lane.busyUntil <= now) { candidate = lane; break }\n if (!oldestSameKind || lane.busyUntil < oldestSameKind.busyUntil) oldestSameKind = lane\n }\n if (!oldestAny || lane.busyUntil < oldestAny.busyUntil) oldestAny = lane\n }\n if (candidate) return candidate\n if (this.lanes.length < this.maxVoices) return this.createLane(kind)\n if (oldestSameKind) return oldestSameKind\n // Cap reached and no lane of this kind: recycle the globally oldest lane into this kind.\n const victim = oldestAny ?? (this.lanes[0] as Lane)\n victim.synth.dispose()\n victim.synth = this.createSynth(kind)\n victim.synth.connect(victim.filter)\n victim.kind = kind\n return victim\n }\n\n /** Configure a lane from the profile, then sound it. `when` lets strums schedule ahead. */\n trigger(profile: SonicProfile, velocity: number, when?: number): void {\n const raw = velocity * profile.velocityScale\n if (raw <= 0.01) return // silent roles (e.g. mono theme text) stay silent\n const t = when ?? Tone.now()\n const vel = clamp(raw, 0.03, 1)\n const lane = this.acquire(profile.synthKind)\n\n const baseCutoff = Math.max(200, profile.filterHz)\n if (lane.kind === 'matter') {\n // EDGE bite: the filter strikes bright then settles (MATTER.md filter weave).\n const w = profile.voice\n lane.filter.Q.rampTo(w.filter.q, 0.02, t)\n lane.filter.frequency.cancelScheduledValues(t)\n lane.filter.frequency.setValueAtTime(Math.min(12000, baseCutoff * w.filter.biteAmount), t)\n lane.filter.frequency.exponentialRampTo(baseCutoff, w.filter.biteDecayS, t)\n } else {\n lane.filter.frequency.rampTo(baseCutoff, 0.02, t)\n lane.filter.Q.rampTo(profile.filterQ, 0.02, t)\n }\n lane.out.setPlacement(profile, t)\n\n const dur = profile.durationS\n try {\n switch (lane.kind) {\n case 'matter': {\n const mv = lane.synth as MatterVoice\n mv.trigger({\n freqHz: profile.freqHz,\n velocity: vel,\n durationS: dur,\n releaseScaleBase: profile.release / 0.3,\n voice: profile.voice,\n }, t, baseCutoff)\n lane.busyUntil = t + dur + mv.releaseTail()\n return\n }\n case 'noise': {\n ;(lane.synth as Tone.NoiseSynth).triggerAttackRelease(Math.min(dur, 0.2), t, vel)\n break\n }\n case 'pluck': {\n const pluck = lane.synth as Tone.PluckSynth\n pluck.set({ dampening: clamp(profile.filterHz, 400, 7000) })\n pluck.triggerAttackRelease(profile.freqHz, dur, t, vel)\n break\n }\n case 'membrane': {\n const mem = lane.synth as Tone.MembraneSynth\n mem.set({ envelope: { attack: Math.max(0.001, profile.attack / 4), release: profile.release } })\n mem.triggerAttackRelease(Math.max(30, profile.freqHz / 4), dur, t, vel)\n break\n }\n case 'fm': {\n const fm = lane.synth as Tone.FMSynth\n fm.set({ envelope: { attack: profile.attack, release: profile.release * 2 } })\n fm.triggerAttackRelease(profile.freqHz, dur, t, vel)\n break\n }\n default: {\n const syn = lane.synth as Tone.Synth\n syn.set({\n oscillator: { type: profile.wave },\n envelope: { attack: profile.attack, decay: 0.08, sustain: 0.25, release: profile.release },\n })\n syn.triggerAttackRelease(profile.freqHz, dur, t, vel)\n }\n }\n lane.busyUntil = t + dur + profile.release\n } catch (err) {\n console.warn('[sonarium] trigger failed', err)\n }\n }\n\n get activeCount(): number {\n const now = Tone.now()\n return this.lanes.filter((l) => l.busyUntil > now).length\n }\n\n /** MODULAR.md §3 — a sustained ribbon voice. Returns null when no matter lane can gate. */\n sustain(profile: SonicProfile, velocity: number): { setFreq(hz: number, glideS: number): void; release(): void } | null {\n const raw = velocity * profile.velocityScale\n if (raw <= 0.01) return null\n const lane = this.acquire('matter')\n if (!(lane.synth instanceof MatterVoice)) return null\n const mv = lane.synth\n const t = Tone.now()\n const baseCutoff = Math.max(200, profile.filterHz)\n lane.filter.Q.rampTo(profile.voice.filter.q, 0.02, t)\n lane.filter.frequency.cancelScheduledValues(t)\n lane.filter.frequency.setValueAtTime(Math.min(12000, baseCutoff * profile.voice.filter.biteAmount), t)\n lane.filter.frequency.exponentialRampTo(baseCutoff, profile.voice.filter.biteDecayS, t)\n lane.out.setPlacement(profile, t)\n mv.gateOn({\n freqHz: profile.freqHz,\n velocity: clamp(raw, 0.03, 1),\n durationS: 9999,\n releaseScaleBase: profile.release / 0.3,\n voice: profile.voice,\n }, t, baseCutoff)\n lane.busyUntil = t + 9999\n const voice = profile.voice\n return {\n setFreq(hz: number, glideS: number) {\n mv.setFreq(hz, glideS, voice.subShimmer.interval, voice.patch.fm.index)\n },\n release() {\n const tail = mv.gateOff()\n lane.busyUntil = Tone.now() + tail\n },\n }\n }\n\n dispose(): void {\n clearInterval(this.sleepTimer)\n for (const lane of this.lanes) {\n lane.synth.dispose()\n lane.filter.dispose()\n lane.out.dispose()\n }\n this.lanes = []\n }\n}\n","/**\n * L2 — pointer: hover previews (I1) + look-around (I9).\n * Ghost-trigger guards (v0.5, user-reported): a \"hover\" only counts when the POINTER moved onto\n * the element. Scrolling moves elements under a stationary cursor and DOM mutations appear under\n * it — both fire pointerover without any user hover intent, and both are suppressed here.\n */\nimport type { Engine } from '../core/engine'\nimport type { Role } from '../types'\n\nconst PREVIEW_ROLES: ReadonlySet<Role> = new Set(['button', 'link', 'toggle', 'input', 'item', 'heading', 'media', 'text'])\nconst HOVER_THROTTLE_MS = 80\n/** pointerover within this window after a scroll = the page moved, not the hand. */\nconst SCROLL_SUPPRESS_MS = 250\n/** pointerover needs pointer movement at most this long ago to count as intentional. */\nconst MOVE_FRESHNESS_MS = 400\n/** The resolved element must be within this many ancestors of the actual target —\n * hovering a blank region must not preview some distant registered container. */\nconst MAX_RESOLVE_HOPS = 4\n\nexport function attachPointer(engine: Engine): () => void {\n const lastHover = new WeakMap<Element, number>()\n let lastScrollT = -Infinity\n let lastMoveT = -Infinity\n\n const onMove = (e: PointerEvent) => {\n lastMoveT = performance.now()\n engine.rig?.pointTo(e.clientX / window.innerWidth, e.clientY / window.innerHeight)\n }\n\n const onScroll = () => {\n lastScrollT = performance.now()\n }\n\n const withinHops = (target: Element, resolved: Element): boolean => {\n let n: Element | null = target\n for (let d = 0; n && d <= MAX_RESOLVE_HOPS; d++) {\n if (n === resolved) return true\n n = n.parentElement\n }\n return false\n }\n\n const onOver = (e: PointerEvent) => {\n const now = performance.now()\n if (now - lastScrollT < SCROLL_SUPPRESS_MS) return // page slid under the cursor\n if (now - lastMoveT > MOVE_FRESHNESS_MS) return // nothing moved the pointer here\n const target = e.target as Element | null\n const el = engine.scanner?.resolve(target)\n if (!el || !target || !withinHops(target, el)) return\n const profile = engine.scanner.profileFor(el)\n if (!profile || !PREVIEW_ROLES.has(profile.role)) return\n if (now - (lastHover.get(el) ?? -Infinity) < HOVER_THROTTLE_MS) return\n lastHover.set(el, now)\n engine.excite(el, 0.25, 'preview')\n }\n\n window.addEventListener('pointermove', onMove, { passive: true })\n window.addEventListener('pointerover', onOver, { passive: true })\n window.addEventListener('scroll', onScroll, { passive: true, capture: true })\n return () => {\n window.removeEventListener('pointermove', onMove)\n window.removeEventListener('pointerover', onOver)\n window.removeEventListener('scroll', onScroll, { capture: true })\n }\n}\n","/**\n * L2 — activation: full notes on press (I2), container strums (I3), toggle intervals (I6).\n */\nimport type { Engine } from '../core/engine'\nimport { ELIGIBLE_SELECTOR } from '../core/scanner'\n\nconst DEDUPE_MS = 80\n\nexport function attachActivate(engine: Engine): () => void {\n const lastHit = new WeakMap<Element, number>()\n\n const activate = (target: Element | null) => {\n const el = engine.scanner?.resolve(target)\n if (!el) return\n const now = performance.now()\n if (now - (lastHit.get(el) ?? -Infinity) < DEDUPE_MS) return\n lastHit.set(el, now)\n\n const profile = engine.scanner.profileFor(el)\n if (!profile) return\n if (profile.role === 'toggle') return // sounded by the change handler (I6)\n if (profile.role === 'container') {\n const children = Array.from(el.querySelectorAll(ELIGIBLE_SELECTOR))\n .filter((c) => c.parentElement && engine.scanner.resolve(c) === c)\n .filter((c) => {\n const r = c.getBoundingClientRect()\n return r.width > 0 && r.bottom > 0 && r.top < window.innerHeight\n })\n if (children.length >= 2) {\n engine.strum(children, 0.5)\n return\n }\n }\n engine.excite(el, 0.75, 'hit')\n }\n\n // pointerdown for latency (<30 ms budget); click catches keyboard activation (Enter/Space).\n const onPointerDown = (e: PointerEvent) => activate(e.target as Element | null)\n const onClick = (e: MouseEvent) => activate(e.target as Element | null)\n\n const onChange = (e: Event) => {\n const t = e.target\n if (!(t instanceof HTMLInputElement) || (t.type !== 'checkbox' && t.type !== 'radio')) return\n const on = t.checked\n engine.excite(t, 0.5, on ? 'toggle-on' : 'toggle-off')\n }\n\n window.addEventListener('pointerdown', onPointerDown, { passive: true })\n window.addEventListener('click', onClick, { passive: true })\n window.addEventListener('change', onChange, { passive: true })\n return () => {\n window.removeEventListener('pointerdown', onPointerDown)\n window.removeEventListener('click', onClick)\n window.removeEventListener('change', onChange)\n }\n}\n","/**\n * L2 — keyboard: focus previews for Tab navigation (I4, accessibility parity) and\n * typing ticks that rise as the field fills (I5).\n */\nimport type { Engine } from '../core/engine'\n\nconst TICK_THROTTLE_MS = 30\n// Pentatonic-safe intervals: ticks climb without ever clashing with the site key.\nconst FILL_INTERVALS = [0, 2, 4, 7, 9, 12, 14, 16] as const\n\nexport function attachKeyboard(engine: Engine): () => void {\n let lastTick = 0\n let lastPointerDownT = -Infinity\n\n // Clicking focuses too — that focus must stay silent or every click sounds twice\n // (ghost-trigger fix, v0.5). Only keyboard-driven focus (Tab) previews.\n const onPointerDown = () => {\n lastPointerDownT = performance.now()\n }\n\n const onFocus = (e: FocusEvent) => {\n if (performance.now() - lastPointerDownT < 500) return\n const el = engine.scanner?.resolve(e.target as Element | null)\n if (el) engine.excite(el, 0.35, 'preview')\n }\n\n const onKeydown = (e: KeyboardEvent) => {\n const t = e.target\n const editable = t instanceof HTMLElement\n && (t instanceof HTMLInputElement || t instanceof HTMLTextAreaElement || t.isContentEditable)\n if (!editable) return\n const now = performance.now()\n if (now - lastTick < TICK_THROTTLE_MS) return\n lastTick = now\n const len = (t as HTMLInputElement).value?.length ?? t.textContent?.length ?? 0\n const interval = FILL_INTERVALS[Math.min(FILL_INTERVALS.length - 1, Math.floor(len / 4))] as number\n engine.excite(t, 0.15, 'tick', undefined, interval)\n }\n\n window.addEventListener('pointerdown', onPointerDown, { passive: true, capture: true })\n window.addEventListener('focusin', onFocus, { passive: true })\n window.addEventListener('keydown', onKeydown, { passive: true })\n return () => {\n window.removeEventListener('pointerdown', onPointerDown, { capture: true })\n window.removeEventListener('focusin', onFocus)\n window.removeEventListener('keydown', onKeydown)\n }\n}\n","/**\n * L2 — scroll & resize: cached rects go stale (I8), the room follows the viewport (S7/S8),\n * and scroll velocity becomes air rushing past (MATTER.md §2.2).\n */\nimport { airRushGain } from '../math/matter'\nimport type { Engine } from '../core/engine'\n\nexport function attachScroll(engine: Engine): () => void {\n let scrollQueued = false\n let lastY = window.scrollY\n let lastT = performance.now()\n const onScroll = () => {\n if (scrollQueued) return\n scrollQueued = true\n requestAnimationFrame(() => {\n scrollQueued = false\n engine.geometryChanged()\n const now = performance.now()\n const dt = Math.max(1, now - lastT)\n const v = Math.abs(window.scrollY - lastY) / dt // px per ms\n lastY = window.scrollY\n lastT = now\n engine.airRush(airRushGain(v))\n })\n }\n\n let resizeQueued = false\n const onResize = () => {\n if (resizeQueued) return\n resizeQueued = true\n requestAnimationFrame(() => {\n resizeQueued = false\n engine.roomResized()\n })\n }\n\n window.addEventListener('scroll', onScroll, { passive: true, capture: true })\n window.addEventListener('resize', onResize, { passive: true })\n return () => {\n window.removeEventListener('scroll', onScroll, { capture: true })\n window.removeEventListener('resize', onResize)\n }\n}\n","/**\n * L2 — embodied motion: device tilt steers the ears (I10), a shake strums the visible\n * page left→right (I11). iOS 13+ requires a permission request from a user gesture; attach()\n * runs inside the unlock gesture, so we ask immediately and degrade silently if refused.\n */\nimport type { Engine } from '../core/engine'\n\nconst SHAKE_THRESHOLD = 18 // m/s² deviation from gravity\nconst SHAKE_REFRACTORY_MS = 600\n\nexport function attachMotion(engine: Engine): () => void {\n if (typeof DeviceOrientationEvent === 'undefined') return () => {}\n\n let lastShake = 0\n let attached = false\n\n const onOrientation = (e: DeviceOrientationEvent) => {\n if (e.gamma == null || e.beta == null) return\n engine.rig?.tiltTo(e.gamma, e.beta)\n }\n\n const onMotion = (e: DeviceMotionEvent) => {\n const a = e.accelerationIncludingGravity\n if (!a || a.x == null || a.y == null || a.z == null) return\n const magnitude = Math.abs(Math.sqrt(a.x * a.x + a.y * a.y + a.z * a.z) - 9.81)\n const now = performance.now()\n if (now - lastShake <= SHAKE_REFRACTORY_MS) return\n if (magnitude > SHAKE_THRESHOLD) {\n lastShake = now\n engine.strum(engine.scanner.visibleElements(), 0.5)\n return\n }\n // Directional flick (v0.6 gesture grammar): a horizontal jab strums in its direction.\n if (Math.abs(a.x) > 12 && Math.abs(a.x) > 2 * Math.abs(a.y)) {\n lastShake = now\n engine.strum(engine.scanner.visibleElements(), 0.4, 'strum', a.x > 0)\n }\n }\n\n const listen = () => {\n if (attached) return\n attached = true\n window.addEventListener('deviceorientation', onOrientation, { passive: true })\n window.addEventListener('devicemotion', onMotion, { passive: true })\n }\n\n const request = (DeviceOrientationEvent as unknown as { requestPermission?: () => Promise<string> }).requestPermission\n if (typeof request === 'function') {\n request.call(DeviceOrientationEvent)\n .then((state) => { if (state === 'granted') listen() })\n .catch(() => { /* user said no, or we were outside a gesture — stay silent */ })\n } else {\n listen()\n }\n\n return () => {\n if (!attached) return\n window.removeEventListener('deviceorientation', onOrientation)\n window.removeEventListener('devicemotion', onMotion)\n }\n}\n","/**\n * L2 — drag glissando (MODULAR.md §3): press an interactive element and drag — the pointer\n * becomes a ribbon controller sweeping scale degrees. The initial hit stays immediate (the\n * ribbon only gates after 14 px of travel; latency invariant untouched).\n */\nimport type { Engine } from '../core/engine'\n\nconst START_PX = 14\n\nexport function attachDrag(engine: Engine): () => void {\n let session: { x0: number; el: Element; handle: ReturnType<Engine['ribbon']> } | null = null\n\n const onDown = (e: PointerEvent) => {\n if (!e.isPrimary) return\n const el = engine.scanner?.resolve(e.target as Element | null)\n if (!el) return\n const p = engine.scanner.profileFor(el)\n if (!p || p.role === 'container' || p.role === 'text') return\n session = { x0: e.clientX, el, handle: null }\n }\n\n const onMove = (e: PointerEvent) => {\n if (!session) return\n const dx = e.clientX - session.x0\n if (!session.handle) {\n if (Math.abs(dx) < START_PX) return\n session.handle = engine.ribbon(session.el)\n if (!session.handle) {\n session = null\n return\n }\n }\n session.handle.move(dx)\n }\n\n const end = () => {\n session?.handle?.release()\n session = null\n }\n\n window.addEventListener('pointerdown', onDown, { passive: true })\n window.addEventListener('pointermove', onMove, { passive: true })\n window.addEventListener('pointerup', end, { passive: true })\n window.addEventListener('pointercancel', end, { passive: true })\n return () => {\n end()\n window.removeEventListener('pointerdown', onDown)\n window.removeEventListener('pointermove', onMove)\n window.removeEventListener('pointerup', end)\n window.removeEventListener('pointercancel', end)\n }\n}\n","/**\n * L2-out — Web MIDI bridge (option `midi: true`): every trigger mirrors to the first MIDI\n * output as note events, channel per role. The page becomes a MIDI controller — record your\n * browsing into a DAW, or drive hardware from the DOM. Feature-detected; silent elsewhere.\n */\nimport type { Engine } from '../core/engine'\nimport type { Role, TriggerDetail } from '../types'\n\nconst ROLE_CHANNEL: Partial<Record<Role, number>> = {\n button: 0, link: 1, toggle: 2, input: 3, heading: 4, media: 5, item: 6, text: 7, container: 8,\n}\n\nexport function attachMidi(engine: Engine): () => void {\n const nav = navigator as Navigator & { requestMIDIAccess?: () => Promise<unknown> }\n if (typeof nav.requestMIDIAccess !== 'function') return () => {}\n let out: { send(data: number[]): void } | null = null\n let off: (() => void) | null = null\n\n nav.requestMIDIAccess()\n .then((access) => {\n const a = access as unknown as { outputs: Map<string, { send(data: number[]): void }> }\n out = a.outputs.values().next().value ?? null\n if (!out) return\n off = engine.on('trigger', (detail) => {\n const d = detail as TriggerDetail\n const note = Math.max(0, Math.min(127, Math.round(d.profile.midi)))\n const vel = Math.max(1, Math.min(127, Math.round(d.velocity * d.profile.velocityScale * 127)))\n const ch = ROLE_CHANNEL[d.profile.role] ?? 9\n try {\n out!.send([0x90 | ch, note, vel])\n setTimeout(() => {\n try { out?.send([0x80 | ch, note, 0]) } catch { /* device gone */ }\n }, Math.min(4000, d.profile.durationS * 1000 + 60))\n } catch { /* device gone */ }\n })\n })\n .catch(() => { /* permission denied — stay silent */ })\n\n return () => off?.()\n}\n","/**\n * The orchestrator — the only file allowed to know every layer (ARCHITECTURE.md §1).\n * Lifecycle: idle → armed → running ⇄ muted → disposed (§3).\n */\nimport * as Tone from 'tone'\nimport { SCALES, midiToFreq, parseKey, siteKey, stepInScale, type SiteKey } from '../math/scales'\nimport { ribbonSteps } from '../math/modular'\nimport { clamp } from '../math/util'\nimport {\n chromaOf, modeFromPalette, pagePalette, parseCssColor, roomToneScaleFromWarmth,\n tempoScaleFromWarmth, type Chroma,\n} from '../math/chroma'\nimport {\n ECHO_MIN_AHEAD_S, ECHO_TRANSPOSE, ECHO_VELOCITY_SCALE, PHRASE_MAX_NOTES, PHRASE_MIN_NOTES,\n PHRASE_PROBABILITY, decayCount, duckFactor, echoGridS, nextGridOffset, phraseWindow,\n readingOrderKey, secondsPerBeat, strumStepS, tempoFromPage,\n} from '../math/pulse'\nimport type { Articulation, PerceptualFactors, SonariumOptions, SonicProfile, SonariumEvent, Theme, TriggerDetail } from '../types'\nimport { resolveTheme } from '../themes/index'\nimport { mountGate, isMutedPersisted, persistMuted, type GateHandle } from '../ui/gate'\nimport { AmbisonicBackend, PannerBackend, type SpatialBackend } from '../spatial/backend'\nimport { FieldRig } from '../spatial/field'\nimport { resolveFactors } from '../spatial/perceptual'\nimport { ListenerRig } from './listener'\nimport type { ProfileEnv } from './profile'\nimport { Room } from './room'\nimport { Scanner } from './scanner'\nimport { VoicePool } from './voices'\nimport { attachPointer } from '../interact/pointer'\nimport { attachActivate } from '../interact/activate'\nimport { attachKeyboard } from '../interact/keyboard'\nimport { attachScroll } from '../interact/scroll'\nimport { attachMotion } from '../interact/motion'\nimport { attachDrag } from '../interact/drag'\nimport { attachMidi } from '../interact/midi'\n\ninterface ResolvedOptions {\n root: Element\n theme: Theme\n key: SiteKey\n listener: 'pointer' | 'center'\n ambient: number\n motion: boolean\n gate: 'chip' | 'none'\n volume: number\n maxVoices: number\n panning: 'HRTF' | 'equalpower'\n spatial: 'ambisonic' | 'panner'\n reverb: 'auto' | number\n velocityFactor: number\n midi: boolean\n}\n\ntype State = 'idle' | 'armed' | 'running' | 'disposed'\n\nexport class Engine {\n readonly opts: ResolvedOptions\n state: State = 'idle'\n muted = false\n\n scanner!: Scanner\n pool: VoicePool | null = null\n room: Room | null = null\n rig: ListenerRig | FieldRig | null = null\n backend: SpatialBackend | null = null\n factors: PerceptualFactors\n /** The page's mood (CHROMA.md §3) and pulse (PULSE.md §1), fixed at create(). */\n readonly palette: Chroma\n readonly tempo: number\n private phraseLoop: Tone.Loop | null = null\n private activity = new WeakMap<Element, { c: number; t: number }>()\n\n private gate: GateHandle | null = null\n private env: ProfileEnv\n private detachers: Array<() => void> = []\n private listeners = new Map<SonariumEvent, Set<(detail?: unknown) => void>>()\n private unlockHandler: ((e: Event) => void) | null = null\n private appearBucket = 6\n private bucketTimer: ReturnType<typeof setInterval> | null = null\n\n constructor(userOpts: SonariumOptions = {}) {\n if (typeof window === 'undefined' || typeof document === 'undefined') {\n throw new Error('[sonarium] requires a browser environment (create() in the client only)')\n }\n const reduced = (userOpts.respectReducedMotion ?? true)\n && typeof matchMedia === 'function'\n && matchMedia('(prefers-reduced-motion: reduce)').matches\n\n // CHROMA.md §3 — the palette chooses the mode; the hostname keeps the root (identity).\n const rootStyle = getComputedStyle(document.documentElement)\n const bodyStyle = getComputedStyle(document.body)\n this.palette = pagePalette(\n chromaOf(parseCssColor(bodyStyle.backgroundColor)),\n chromaOf(parseCssColor(bodyStyle.color)),\n )\n const cssKey = rootStyle.getPropertyValue('--sonic-key').trim()\n let key = (userOpts.key && userOpts.key !== 'auto' ? parseKey(userOpts.key) : null)\n ?? (cssKey ? parseKey(cssKey) : null)\n if (!key) {\n const hashed = siteKey(location.hostname)\n const mode = modeFromPalette(this.palette)\n key = mode\n ? { ...hashed, scaleName: mode, scale: SCALES[mode] as readonly number[], label: `${hashed.label.split(' ')[0]} ${mode}` }\n : hashed\n }\n\n this.opts = {\n root: userOpts.root ?? document.body,\n theme: resolveTheme(userOpts.theme),\n key,\n listener: userOpts.listener ?? 'pointer',\n ambient: reduced ? 0 : clamp(userOpts.ambient ?? 0.12, 0, 1),\n motion: userOpts.motion ?? true,\n gate: userOpts.gate ?? 'chip',\n volume: userOpts.volume ?? -10,\n maxVoices: clamp(userOpts.maxVoices ?? 18, 4, 24),\n panning: userOpts.panning === 'equalpower' ? 'equalpower' : 'HRTF',\n spatial: userOpts.spatial === 'panner' ? 'panner' : 'ambisonic',\n reverb: userOpts.reverb ?? 'auto',\n velocityFactor: reduced ? 0.7 : 1,\n midi: userOpts.midi === true,\n }\n this.factors = resolveFactors(userOpts.perceptual)\n\n this.env = {\n root: this.opts.root,\n key: this.opts.key,\n theme: this.opts.theme,\n vw: window.innerWidth,\n vh: window.innerHeight,\n }\n\n this.muted = isMutedPersisted()\n\n // L1 perception is always on: the page is readable (describe()) before it is audible.\n this.scanner = new Scanner(this.env, { onAppear: (el) => this.whisper(el) })\n this.scanner.scan()\n\n // PULSE.md §1 — the layout sets the pace (overridable via --sonic-tempo).\n const cssTempo = parseFloat(rootStyle.getPropertyValue('--sonic-tempo'))\n this.tempo = cssTempo > 0\n ? clamp(Math.round(cssTempo), 30, 200)\n : tempoFromPage(this.scanner.registry.size, tempoScaleFromWarmth(this.palette.warmth))\n\n this.arm()\n }\n\n // ---------------------------------------------------------------- lifecycle\n\n private arm(): void {\n this.state = 'armed'\n if (this.opts.gate === 'chip') {\n this.gate = mountGate(() => this.toggleMute())\n this.gate.setState(this.muted ? 'muted' : 'armed')\n }\n if (!this.muted) {\n // Any gesture may unlock (standard autoplay pattern); the chip is the explicit path.\n // 'click' included for assistive tech and synthetic activation, which may skip pointerdown.\n // Listeners stay armed until start() actually succeeds — a gesture that fails to resume\n // the context (no user activation) must not consume the only unlock chance.\n this.unlockHandler = () => { void this.start() }\n window.addEventListener('pointerdown', this.unlockHandler, { capture: true })\n window.addEventListener('keydown', this.unlockHandler, { capture: true })\n window.addEventListener('click', this.unlockHandler, { capture: true })\n }\n }\n\n private removeUnlockListeners(): void {\n if (!this.unlockHandler) return\n window.removeEventListener('pointerdown', this.unlockHandler, { capture: true })\n window.removeEventListener('keydown', this.unlockHandler, { capture: true })\n window.removeEventListener('click', this.unlockHandler, { capture: true })\n this.unlockHandler = null\n }\n\n private starting = false\n\n async start(): Promise<void> {\n if (this.state === 'running' || this.state === 'disposed' || this.starting) return\n this.starting = true\n try {\n // Tone.start() can stay pending forever without user activation; don't wedge on it —\n // stay 'armed' and let the next (real) gesture try again.\n await Promise.race([Tone.start(), new Promise((r) => setTimeout(r, 1500))])\n } catch (err) {\n console.warn('[sonarium] audio context could not start yet', err)\n } finally {\n this.starting = false\n }\n if (Tone.getContext().state !== 'running' || (this.state as State) === 'disposed') return\n this.state = 'running'\n this.removeUnlockListeners()\n this.gate?.setState(this.muted ? 'muted' : 'on')\n\n this.buildAudioGraph()\n if (this.muted) this.room?.setMuted(true)\n\n this.detachers.push(\n attachPointer(this),\n attachActivate(this),\n attachKeyboard(this),\n attachScroll(this),\n attachDrag(this),\n )\n if (this.opts.motion) this.detachers.push(attachMotion(this))\n if (this.opts.midi) this.detachers.push(attachMidi(this))\n\n const onVis = () => this.room?.setHidden(document.hidden)\n document.addEventListener('visibilitychange', onVis)\n this.detachers.push(() => document.removeEventListener('visibilitychange', onVis))\n\n this.bucketTimer = setInterval(() => { this.appearBucket = Math.min(6, this.appearBucket + 6) }, 1000)\n\n // PULSE.md — the page's clock drives ambience, echoes and phrases.\n Tone.getTransport().bpm.value = this.tempo\n Tone.getTransport().start()\n this.room?.startAmbience(this.env.vw, this.opts.ambient, roomToneScaleFromWarmth(this.palette.warmth))\n if (this.opts.ambient > 0) {\n this.phraseLoop = new Tone.Loop((time) => this.playPhrase(time), '1m')\n this.phraseLoop.start('1m')\n }\n this.playIntroMotif()\n this.emit('start')\n }\n\n /** PULSE.md §3 — the ambience reads the layout as a score; scroll moves the playhead. */\n private playPhrase(time?: number): void {\n if (this.state !== 'running' || this.muted || document.hidden) return\n if (time === undefined || !Number.isFinite(time)) time = Tone.now()\n if (Math.random() > PHRASE_PROBABILITY) return\n const pool = this.scanner.visibleElements()\n .map((el) => ({ el, p: this.scanner.profileFor(el) }))\n .filter((x): x is { el: Element; p: SonicProfile } => !!x.p && x.p.role !== 'container' && x.p.velocityScale > 0.01)\n .sort((a, b) => readingOrderKey(a.p.rect.y, a.p.rect.x) - readingOrderKey(b.p.rect.y, b.p.rect.x))\n if (pool.length < PHRASE_MIN_NOTES) return\n const len = Math.min(pool.length, PHRASE_MIN_NOTES + Math.floor(Math.random() * (PHRASE_MAX_NOTES - PHRASE_MIN_NOTES + 1)))\n const scrollable = Math.max(1, document.documentElement.scrollHeight - window.innerHeight)\n const start = phraseWindow(pool.length, len, window.scrollY / scrollable)\n const step = secondsPerBeat(this.tempo) / 2\n const level = 0.07 * (this.opts.ambient / 0.12)\n pool.slice(start, start + len).forEach(({ el }, i) => this.excite(el, level, 'phrase', time + i * step))\n }\n\n /**\n * SPATIAL.md §6 — ambisonic field by default; if its construction throws on an exotic\n * browser, fall back to the v0.1 per-voice panner world rather than staying silent.\n */\n private buildAudioGraph(): void {\n const roomOpts = { volumeDb: this.opts.volume, reverb: this.opts.reverb, ambient: this.opts.ambient }\n if (this.opts.spatial === 'ambisonic') {\n try {\n this.room = new Room({ ...roomOpts, mode: 'ambisonic' }, this.env.vw, this.factors)\n const decoderKind = this.opts.panning === 'equalpower' ? 'stereo' : 'binaural'\n this.backend = new AmbisonicBackend(this.room, decoderKind, this.env.vw, this.factors)\n this.rig = new FieldRig(this.backend, this.opts.listener)\n this.rig.start()\n this.pool = new VoicePool(this.backend, this.opts.maxVoices)\n return\n } catch (err) {\n console.warn('[sonarium] ambisonic backend unavailable, falling back to panner', err)\n this.room?.dispose()\n this.room = null\n }\n }\n this.room = new Room({ ...roomOpts, mode: 'panner' }, this.env.vw, this.factors)\n this.backend = new PannerBackend(this.room, this.opts.panning)\n this.rig = new ListenerRig(this.opts.listener)\n this.rig.start()\n this.pool = new VoicePool(this.backend, this.opts.maxVoices)\n }\n\n /**\n * MODULAR.md §3 — the ribbon controller: press-and-drag turns an element into a sustained\n * voice swept across scale degrees (quantized — the glide between steps is the glissando).\n */\n ribbon(el: Element): { move(dxPx: number): void; release(): void } | null {\n if (this.state !== 'running' || this.muted || !this.pool) return null\n const target = this.scanner.resolve(el) ?? el\n const profile = this.scanner.profileFor(target)\n if (!profile) return null\n const handle = this.pool.sustain(profile, 0.6)\n if (!handle) return null\n this.emit('trigger', { el: target, profile, velocity: 0.6, articulation: 'ribbon' } satisfies TriggerDetail)\n const key = this.opts.key\n const glide = 0.03 + profile.voice.patch.portamentoS\n let lastMidi = profile.midi\n return {\n move: (dxPx: number) => {\n const midi = stepInScale(profile.midi, key, ribbonSteps(dxPx, this.env.vw, key.scale.length))\n if (midi !== lastMidi) {\n lastMidi = midi\n handle.setFreq(midiToFreq(midi), glide)\n }\n },\n release: () => handle.release(),\n }\n }\n\n /** MATTER.md §2.2 — scroll drivers report air movement; rides the room-tone noise. */\n airRush(level: number): void {\n if (this.state !== 'running' || this.muted || level <= 0.005) return\n this.room?.rush(level)\n }\n\n /** Live spat5.oper surface: adjust presence/roomPresence/envelopment/warmth/brilliance. */\n setPerceptual(partial: Partial<PerceptualFactors>): void {\n this.factors = resolveFactors({ ...this.factors, ...partial })\n this.backend?.setFactors(this.factors)\n }\n\n toggleMute(): void {\n if (this.state !== 'running') {\n // First tap on the chip both unlocks and (if persisted-muted) unmutes.\n this.muted = false\n persistMuted(false)\n void this.start()\n return\n }\n this.muted = !this.muted\n persistMuted(this.muted)\n this.room?.setMuted(this.muted)\n this.gate?.setState(this.muted ? 'muted' : 'on')\n this.emit('mute', this.muted)\n }\n\n dispose(): void {\n if (this.state === 'disposed') return\n this.state = 'disposed'\n this.removeUnlockListeners()\n if (this.bucketTimer) clearInterval(this.bucketTimer)\n this.phraseLoop?.dispose()\n for (const detach of this.detachers.splice(0)) {\n try { detach() } catch { /* already gone */ }\n }\n this.scanner?.dispose()\n this.rig?.dispose()\n this.pool?.dispose()\n this.backend?.dispose()\n this.room?.dispose()\n this.gate?.dispose()\n this.emit('dispose')\n this.listeners.clear()\n }\n\n // ---------------------------------------------------------------- sounding\n\n /**\n * The single entry point for anything that wants to sound an element (Invariant: L2 drivers\n * never touch Tone). Resolves the element to its profile and rents a voice.\n * `transpose` shifts in semitones relative to the quantized pitch — callers must pass\n * consonant intervals only (e.g. keyboard.ts FILL_INTERVALS).\n */\n excite(el: Element, velocity: number, articulation: Articulation, when?: number, transpose = 0): void {\n if (this.state !== 'running' || this.muted || !this.pool) return\n if (when !== undefined && !Number.isFinite(when)) when = undefined // NaN must never reach a ramp\n const target = this.scanner.resolve(el) ?? el\n let profile = this.scanner.profileFor(target)\n if (!profile) return\n\n // PULSE.md §4 — the calm system: repeated sounds recede (motifs/echoes/phrases exempt).\n if (articulation !== 'motif' && articulation !== 'echo' && articulation !== 'phrase' && articulation !== 'whisper') {\n const now = performance.now()\n const a = this.activity.get(target) ?? { c: 0, t: now }\n a.c = decayCount(a.c, now - a.t) + 1\n a.t = now\n this.activity.set(target, a)\n velocity *= duckFactor(a.c - 1)\n }\n if (transpose !== 0) {\n profile = { ...profile, midi: profile.midi + transpose, freqHz: profile.freqHz * Math.pow(2, transpose / 12) }\n }\n if (articulation === 'tick') {\n profile = { ...profile, durationS: Math.min(profile.durationS, 0.07), release: 0.05 }\n }\n if (articulation === 'toggle-on' || articulation === 'toggle-off') {\n const dir = articulation === 'toggle-on' ? 1 : -1\n const base = { ...profile, durationS: 0.12 }\n this.pool.trigger(base, velocity * this.opts.velocityFactor, when)\n // perfect-5th answer note (I6): 7 semitones up/down from the quantized pitch\n const second = { ...profile, midi: profile.midi + dir * 7, freqHz: profile.freqHz * Math.pow(2, (dir * 7) / 12), durationS: 0.16 }\n this.pool.trigger(second, velocity * this.opts.velocityFactor, (when ?? Tone.now()) + 0.09)\n } else {\n this.pool.trigger(profile, velocity * this.opts.velocityFactor, when)\n }\n\n // PULSE.md §2 — the room answers strong hits on the next 8th, one octave up, quiet.\n // The primary hit above was NOT delayed (the latency invariant, §0).\n if (articulation === 'hit' && velocity >= 0.55) {\n const offset = nextGridOffset(Tone.getTransport().seconds, echoGridS(this.tempo), ECHO_MIN_AHEAD_S)\n this.excite(target, velocity * ECHO_VELOCITY_SCALE, 'echo', Tone.now() + offset, ECHO_TRANSPOSE)\n }\n\n this.emit('trigger', { el: target, profile, velocity, articulation } satisfies TriggerDetail)\n }\n\n /** I3/I11 — strum a set of elements left→right (or right→left for a reverse flick). */\n strum(els: Element[], velocity: number, articulation: Articulation = 'strum', reverse = false): void {\n if (this.state !== 'running' || !this.pool) return\n const sorted = els\n .map((el) => ({ el, p: this.scanner.profileFor(el) }))\n .filter((x): x is { el: Element; p: SonicProfile } => !!x.p)\n .sort((a, b) => (reverse ? b.p.rect.x - a.p.rect.x : a.p.rect.x - b.p.rect.x))\n .slice(0, 6)\n // metered: 32nd-note spacing at the page's tempo (PULSE.md §3)\n const t0 = Tone.now()\n const step = strumStepS(this.tempo)\n sorted.forEach(({ el }, i) => this.excite(el, velocity, articulation, t0 + i * step))\n }\n\n private whisper(el: Element): void {\n if (this.appearBucket <= 0) return\n this.appearBucket--\n this.excite(el, 0.12, 'whisper')\n }\n\n /** I12 — the page introduces itself: its largest landmarks, in DOM order, in the site key. */\n private playIntroMotif(): void {\n const candidates = Array.from(\n this.opts.root.querySelectorAll('h1, h2, nav, main, [role=banner], header, button, [role=button]'),\n ).filter((el) => {\n const r = el.getBoundingClientRect()\n return r.width > 0 && r.height > 0 && r.top < this.env.vh\n })\n const byArea = candidates\n .map((el) => ({ el, area: el.getBoundingClientRect().width * el.getBoundingClientRect().height }))\n .sort((a, b) => b.area - a.area)\n .slice(0, 5)\n .map((x) => x.el)\n const inDomOrder = candidates.filter((el) => byArea.includes(el))\n const t0 = Tone.now() + 0.1\n const step = secondsPerBeat(this.tempo) / 4 // the motif walks 16ths at the page's tempo\n inDomOrder.forEach((el, i) => this.excite(el, 0.3, 'motif', t0 + i * step))\n }\n\n // ---------------------------------------------------------------- introspection\n\n /** Invariant #6 — explain why an element sounds the way it does. Works before start(). */\n describe(el: Element): SonicProfile | null {\n return this.scanner.profileFor(el)\n }\n\n geometryChanged(): void {\n this.env.vw = window.innerWidth\n this.env.vh = window.innerHeight\n this.scanner?.updateEnv(this.env.vw, this.env.vh)\n this.scanner?.invalidateRects()\n }\n\n roomResized(): void {\n this.geometryChanged()\n this.room?.resize(this.env.vw)\n this.backend?.onViewport(this.env.vw)\n }\n\n // ---------------------------------------------------------------- events\n\n on(event: SonariumEvent, fn: (detail?: unknown) => void): () => void {\n if (!this.listeners.has(event)) this.listeners.set(event, new Set())\n this.listeners.get(event)!.add(fn)\n return () => this.listeners.get(event)?.delete(fn)\n }\n\n private emit(event: SonariumEvent, detail?: unknown): void {\n for (const fn of this.listeners.get(event) ?? []) {\n try { fn(detail) } catch (err) { console.warn('[sonarium] listener error', err) }\n }\n }\n}\n"],"mappings":"6pBAAA,IAAAA,GAAAC,GAAA,CAAAC,GAAAC,KAAA,uBAASC,GAAgBC,EAAG,CAC1B,GAAI,MAAM,QAAQA,CAAC,EAAG,OAAOA,CAC/B,CACAF,GAAO,QAAUC,GAAiBD,GAAO,QAAQ,WAAa,GAAMA,GAAO,QAAQ,QAAaA,GAAO,UCHvG,IAAAG,GAAAC,GAAA,CAAAC,GAAAC,KAAA,uBAASC,GAAsBC,EAAGC,EAAG,CACnC,IAAIC,EAAYF,GAAR,KAAY,KAAsB,OAAO,OAAtB,KAAgCA,EAAE,OAAO,QAAQ,GAAKA,EAAE,YAAY,EAC/F,GAAYE,GAAR,KAAW,CACb,IAAIC,EACF,EACAC,EACAC,EACAC,EAAI,CAAC,EACLC,EAAI,GACJC,EAAI,GACN,GAAI,CACF,GAAIJ,GAAKF,EAAIA,EAAE,KAAKF,CAAC,GAAG,KAAYC,IAAN,EAAS,CACrC,GAAI,OAAOC,CAAC,IAAMA,EAAG,OACrBK,EAAI,EACN,KAAO,MAAO,EAAEA,GAAKJ,EAAIC,EAAE,KAAKF,CAAC,GAAG,QAAUI,EAAE,KAAKH,EAAE,KAAK,EAAGG,EAAE,SAAWL,GAAIM,EAAI,GAAG,CACzF,OAASP,EAAG,CACVQ,EAAI,GAAI,EAAIR,CACd,QAAE,CACA,GAAI,CACF,GAAI,CAACO,GAAaL,EAAE,QAAV,OAAwBG,EAAIH,EAAE,OAAU,EAAG,OAAOG,CAAC,IAAMA,GAAI,MACzE,QAAE,CACA,GAAIG,EAAG,MAAM,CACf,CACF,CACA,OAAOF,CACT,CACF,CACAR,GAAO,QAAUC,GAAuBD,GAAO,QAAQ,WAAa,GAAMA,GAAO,QAAQ,QAAaA,GAAO,UC3B7G,IAAAW,GAAAC,GAAA,CAAAC,GAAAC,K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,IAAM6E,GAAU,QAyBhB,SAASC,GAAOC,EAA2B,CAAC,EAAW,CAC5D,OAAO,IAAIC,GAAOD,CAAO,CAC3B,CAIA,SAASE,IAAiB,CACxB,GAAI,OAAO,SAAa,IAAa,OACrC,IAAMC,EAAS,SAAS,cACxB,GAAI,CAACA,GAAUA,EAAO,QAAQ,OAAS,OAAW,OAClD,IAAMC,EAAwB,CAAC,EAC3BD,EAAO,QAAQ,QAAOC,EAAK,MAAQD,EAAO,QAAQ,OAClDA,EAAO,QAAQ,MAAKC,EAAK,IAAMD,EAAO,QAAQ,KAC9CA,EAAO,QAAQ,UAASC,EAAK,QAAU,WAAWD,EAAO,QAAQ,OAAO,GACxEA,EAAO,QAAQ,WAAUC,EAAK,SAAWD,EAAO,QAAQ,UACxDA,EAAO,QAAQ,SAAQC,EAAK,OAAS,WAAWD,EAAO,QAAQ,MAAM,GACrEA,EAAO,QAAQ,UAASC,EAAK,QAAUD,EAAO,QAAQ,SAC1D,IAAME,EAAO,IAAM,CACjB,GAAI,CACF,IAAMC,EAASP,GAAOK,CAAI,EACxB,OAA8C,SAAWE,CAC7D,OAASC,EAAK,CACZ,QAAQ,KAAK,8BAA+BA,CAAG,CACjD,CACF,EACI,SAAS,aAAe,UAC1B,SAAS,iBAAiB,mBAAoBF,EAAM,CAAE,KAAM,EAAK,CAAC,EAElEA,EAAK,CAET,CAEAH,GAAS","names":["require_arrayWithHoles","__commonJSMin","exports","module","_arrayWithHoles","r","require_iterableToArrayLimit","__commonJSMin","exports","module","_iterableToArrayLimit","r","l","t","e","i","u","a","f","o","require_arrayLikeToArray","__commonJSMin","exports","module","_arrayLikeToArray","r","a","n","require_unsupportedIterableToArray","__commonJSMin","exports","module","arrayLikeToArray","_unsupportedIterableToArray","r","a","t","require_nonIterableRest","__commonJSMin","exports","module","_nonIterableRest","require_slicedToArray","__commonJSMin","exports","module","arrayWithHoles","iterableToArrayLimit","unsupportedIterableToArray","nonIterableRest","_slicedToArray","r","e","require_classCallCheck","__commonJSMin","exports","module","_classCallCheck","a","n","require_typeof","__commonJSMin","exports","module","_typeof","o","require_toPrimitive","__commonJSMin","exports","module","_typeof","toPrimitive","t","r","i","require_toPropertyKey","__commonJSMin","exports","module","_typeof","toPrimitive","toPropertyKey","t","i","require_createClass","__commonJSMin","exports","module","toPropertyKey","_defineProperties","e","r","t","o","_createClass","require_bundle","__commonJSMin","exports","module","global","factory","_slicedToArray","_classCallCheck","_createClass","createExtendedExponentialRampToValueAutomationEvent","value","endTime","insertTime","createExtendedLinearRampToValueAutomationEvent","createSetValueAutomationEvent","startTime","createSetValueCurveAutomationEvent","values","duration","getTargetValueAtTime","time","valueAtStartTime","_ref","target","timeConstant","isExponentialRampToValueAutomationEvent","automationEvent","isLinearRampToValueAutomationEvent","isAnyRampToValueAutomationEvent","isSetValueAutomationEvent","isSetValueCurveAutomationEvent","_getValueOfAutomationEventAtIndexAtTime","automationEvents","index","defaultValue","getEndTimeAndValueOfPreviousAutomationEvent","currentAutomationEvent","nextAutomationEvent","isCancelAndHoldAutomationEvent","isCancelScheduledValuesAutomationEvent","getEventTime","getExponentialRampValueAtTime","getLinearRampValueAtTime","interpolateValue","theoreticIndex","lowerIndex","upperIndex","getValueCurveValueAtTime","truncateValueCurve","originalDuration","targetDuration","length","truncatedLength","truncatedValues","i","isSetTargetAutomationEvent","AutomationEventList","eventTime","removedAutomationEvent","lastAutomationEvent","startValue","truncatedAutomationEvent","_index","previousAutomationEvent","persistentAutomationEvent","remainingAutomationEvents","firstRemainingAutomationEvent","indexOfNextEvent","indexOfCurrentEvent","_getEndTimeAndValueOf","_getEndTimeAndValueOf2","_getEndTimeAndValueOf3","_getEndTimeAndValueOf4","_startTime","_value","createCancelAndHoldAutomationEvent","cancelTime","createCancelScheduledValuesAutomationEvent","createExponentialRampToValueAutomationEvent","createLinearRampToValueAutomationEvent","createSetTargetAutomationEvent","src_exports","__export","CUBE_LAYOUT","DEFAULT_FACTORS","DEG","SCALES","THEMES","applyMat3","chroma_exports","create","decodeGains","decodeMatrix","degreeToMidi","foaGains","lookMatrix","mapping_exports","matter_exports","midiToFreq","midiToNoteName","modular_exports","parseKey","pulse_exports","rotationMatrix","siteKey","sphere_exports","stepInScale","unitVector","version","version","import_automation_events","createAbortError","createAddActiveInputConnectionToAudioNode","insertElementInSet","activeInputs","source","output","input","eventListener","ignoreDuplicates","activeInputConnection","createAddAudioNodeConnections","audioNodeConnectionsStore","audioNode","audioNodeRenderer","nativeAudioNode","activeInputs","i","createAddAudioParamConnections","audioParamConnectionsStore","audioParam","audioParamRenderer","ACTIVE_AUDIO_NODE_STORE","AUDIO_NODE_CONNECTIONS_STORE","AUDIO_NODE_STORE","AUDIO_PARAM_CONNECTIONS_STORE","AUDIO_PARAM_STORE","CONTEXT_STORE","EVENT_LISTENERS","CYCLE_COUNTERS","NODE_NAME_TO_PROCESSOR_CONSTRUCTOR_MAPS","NODE_TO_PROCESSOR_MAPS","handler","isConstructible","constructible","proxy","IMPORT_STATEMENT_REGEX","splitImportStatements","source","url","importStatements","sourceWithoutImportStatements","result","unresolvedUrl","importStatementWithResolvedUrl","verifyParameterDescriptors","parameterDescriptors","verifyProcessorCtor","processorCtor","isConstructible","createAddAudioWorkletModule","cacheTestResult","createNotSupportedError","evaluateSource","exposeCurrentFrameAndCurrentTime","fetchSource","getNativeContext","getOrCreateBackupOfflineAudioContext","isNativeOfflineAudioContext","nativeAudioWorkletNodeConstructor","ongoingRequests","resolvedRequests","testAudioWorkletProcessorPostMessageSupport","window","index","context","moduleURL","options","resolvedRequestsOfContext","ongoingRequestsOfContext","promiseOfOngoingRequest","nativeContext","promise","source","absoluteUrl","importStatements","sourceWithoutImportStatements","splitImportStatements","wrappedSource","evaluateAudioWorkletGlobalScope","name","nodeNameToProcessorConstructorMap","NODE_NAME_TO_PROCESSOR_CONSTRUCTOR_MAPS","isSupportingPostMessage","currentIndex","blob","url","backupOfflineAudioContext","nativeContextOrBackupOfflineAudioContext","updatedResolvedRequestsOfContext","updatedOngoingRequestsOfContext","getValueForKey","map","key","value","pickElementFromSet","set","predicate","matchingElements","matchingElement","deletePassiveInputConnectionToAudioNode","passiveInputs","source","output","input","passiveInputConnections","getValueForKey","matchingConnection","pickElementFromSet","passiveInputConnection","getEventListenersOfAudioNode","audioNode","getValueForKey","EVENT_LISTENERS","setInternalStateToActive","audioNode","ACTIVE_AUDIO_NODE_STORE","getEventListenersOfAudioNode","eventListener","isAudioWorkletNode","audioNode","setInternalStateToPassive","audioNode","ACTIVE_AUDIO_NODE_STORE","getEventListenersOfAudioNode","eventListener","setInternalStateToPassiveWhenNecessary","audioNode","activeInputs","isAudioWorkletNode","connections","setInternalStateToPassive","createAddConnectionToAudioNode","addActiveInputConnectionToAudioNode","addPassiveInputConnectionToAudioNode","connectNativeAudioNodeToNativeAudioNode","deleteActiveInputConnectionToAudioNode","disconnectNativeAudioNodeFromNativeAudioNode","getAudioNodeConnections","getAudioNodeTailTime","getEventListenersOfAudioNode","getNativeAudioNode","insertElementInSet","isActiveAudioNode","isPartOfACycle","isPassiveAudioNode","tailTimeTimeoutIds","source","destination","output","input","isOffline","activeInputs","passiveInputs","outputs","eventListeners","eventListener","isActive","nativeDestinationAudioNode","nativeSourceAudioNode","partialConnection","deletePassiveInputConnectionToAudioNode","setInternalStateToActive","tailTime","setInternalStateToPassiveWhenNecessary","tailTimeTimeoutId","outputConnection","createAddPassiveInputConnectionToAudioNode","insertElementInSet","passiveInputs","input","source","output","eventListener","ignoreDuplicates","passiveInputConnections","passiveInputConnection","createAddSilentConnection","createNativeGainNode","nativeContext","nativeAudioScheduledSourceNode","nativeGainNode","disconnect","createAddUnrenderedAudioWorkletNode","getUnrenderedAudioWorkletNodes","nativeContext","audioWorkletNode","DEFAULT_OPTIONS","createAnalyserNodeConstructor","audionNodeConstructor","createAnalyserNodeRenderer","createIndexSizeError","createNativeAnalyserNode","getNativeContext","isNativeOfflineAudioContext","context","options","nativeContext","mergedOptions","nativeAnalyserNode","analyserNodeRenderer","value","maxDecibels","minDecibels","array","isOwnedByContext","nativeAudioNode","nativeContext","createAnalyserNodeRendererFactory","createNativeAnalyserNode","getNativeAudioNode","renderInputsOfAudioNode","renderedNativeAnalyserNodes","createAnalyserNode","proxy","nativeOfflineAudioContext","nativeAnalyserNode","isOwnedByContext","options","renderedNativeAnalyserNode","testAudioBufferCopyChannelMethodsOutOfBoundsSupport","nativeAudioBuffer","createIndexSizeError","wrapAudioBufferGetChannelDataMethod","audioBuffer","getChannelData","channel","err","createIndexSizeError","DEFAULT_OPTIONS","createAudioBufferConstructor","audioBufferStore","cacheTestResult","createNotSupportedError","nativeAudioBufferConstructor","nativeOfflineAudioContextConstructor","testNativeAudioBufferConstructorSupport","wrapAudioBufferCopyChannelMethods","wrapAudioBufferCopyChannelMethodsOutOfBounds","nativeOfflineAudioContext","AudioBuffer","options","length","numberOfChannels","sampleRate","audioBuffer","wrapAudioBufferGetChannelDataMethod","testAudioBufferCopyChannelMethodsOutOfBoundsSupport","instance","MOST_NEGATIVE_SINGLE_FLOAT","MOST_POSITIVE_SINGLE_FLOAT","isActiveAudioNode","audioNode","ACTIVE_AUDIO_NODE_STORE","DEFAULT_OPTIONS","createAudioBufferSourceNodeConstructor","audioNodeConstructor","createAudioBufferSourceNodeRenderer","createAudioParam","createInvalidStateError","createNativeAudioBufferSourceNode","getNativeContext","isNativeOfflineAudioContext","wrapEventListener","context","options","nativeContext","mergedOptions","nativeAudioBufferSourceNode","isOffline","audioBufferSourceNodeRenderer","MOST_POSITIVE_SINGLE_FLOAT","MOST_NEGATIVE_SINGLE_FLOAT","value","wrappedListener","nativeOnEnded","when","offset","duration","setInternalStateToActive","resetInternalStateToPassive","isActiveAudioNode","setInternalStateToPassive","createAudioBufferSourceNodeRendererFactory","connectAudioParam","createNativeAudioBufferSourceNode","getNativeAudioNode","renderAutomation","renderInputsOfAudioNode","renderedNativeAudioBufferSourceNodes","start","stop","createAudioBufferSourceNode","proxy","nativeOfflineAudioContext","nativeAudioBufferSourceNode","nativeAudioBufferSourceNodeIsOwnedByContext","isOwnedByContext","options","value","renderedNativeAudioBufferSourceNode","isAudioBufferSourceNode","audioNode","isBiquadFilterNode","audioNode","isConstantSourceNode","audioNode","isGainNode","audioNode","isOscillatorNode","audioNode","isStereoPannerNode","audioNode","getAudioNodeConnections","audioNode","getValueForKey","AUDIO_NODE_CONNECTIONS_STORE","getAudioParamConnections","audioParam","getValueForKey","AUDIO_PARAM_CONNECTIONS_STORE","deactivateActiveAudioNodeInputConnections","audioNode","trace","activeInputs","getAudioNodeConnections","connections","source","audioParams","isAudioBufferSourceNode","isAudioWorkletNode","isBiquadFilterNode","isConstantSourceNode","isGainNode","isOscillatorNode","isStereoPannerNode","audioParam","audioParamConnections","getAudioParamConnections","isActiveAudioNode","setInternalStateToPassive","deactivateAudioGraph","context","deactivateActiveAudioNodeInputConnections","isValidLatencyHint","latencyHint","createAudioContextConstructor","baseAudioContextConstructor","createInvalidStateError","createNotSupportedError","createUnknownError","mediaElementAudioSourceNodeConstructor","mediaStreamAudioDestinationNodeConstructor","mediaStreamAudioSourceNodeConstructor","mediaStreamTrackAudioSourceNodeConstructor","nativeAudioContextConstructor","options","nativeAudioContext","err","isValidLatencyHint","latencyHint","sampleRate","revokeState","deactivateAudioGraph","mediaElement","mediaStream","mediaStreamTrack","resolve","reject","resolvePromise","createAudioDestinationNodeConstructor","audioNodeConstructor","createAudioDestinationNodeRenderer","createIndexSizeError","createInvalidStateError","createNativeAudioDestinationNode","getNativeContext","isNativeOfflineAudioContext","renderInputsOfAudioNode","context","channelCount","nativeContext","isOffline","nativeAudioDestinationNode","audioDestinationNodeRenderer","value","createAudioDestinationNodeRenderer","renderInputsOfAudioNode","renderedNativeAudioDestinationNodes","createAudioDestinationNode","proxy","nativeOfflineAudioContext","nativeAudioDestinationNode","renderedNativeAudioDestinationNode","createAudioListenerFactory","createAudioParam","createNativeChannelMergerNode","createNativeConstantSourceNode","createNativeScriptProcessorNode","createNotSupportedError","getFirstSample","isNativeOfflineAudioContext","overwriteAccessors","context","nativeContext","nativeListener","createFakeAudioParams","buffer","channelMergerNode","isOffline","isScriptProcessorNodeCreated","lastOrientation","lastPosition","createScriptProcessorNode","scriptProcessorNode","inputBuffer","orientation","value","index","positon","createSetOrientation","createSetPosition","createFakeAudioParam","input","initialValue","setValue","constantSourceNode","audioParam","MOST_POSITIVE_SINGLE_FLOAT","MOST_NEGATIVE_SINGLE_FLOAT","get","set","err","cancelAndHoldAtTime","args","cancelScheduledValues","exponentialRampToValueAtTime","linearRampToValueAtTime","setTargetAtTime","setValueAtTime","setValueCurveAtTime","forwardX","forwardY","forwardZ","positionX","positionY","positionZ","upX","upY","upZ","isAudioNode","audioNodeOrAudioParam","isAudioNodeOutputConnection","outputConnection","isAudioNode","insertElementInSet","set","element","predicate","ignoreDuplicates","lmnt","addActiveInputConnectionToAudioParam","activeInputs","source","output","eventListener","ignoreDuplicates","insertElementInSet","activeInputConnection","addPassiveInputConnectionToAudioParam","passiveInputs","source","output","eventListener","ignoreDuplicates","passiveInputConnections","insertElementInSet","passiveInputConnection","isNativeAudioNodeFaker","nativeAudioNodeOrNativeAudioNodeFaker","connectNativeAudioNodeToNativeAudioNode","nativeSourceAudioNode","nativeDestinationAudioNode","output","input","isNativeAudioNodeFaker","fakeNativeDestinationAudioNode","deleteActiveInputConnection","activeInputConnections","source","output","activeInputConnection","deleteActiveInputConnectionToAudioParam","activeInputs","source","output","pickElementFromSet","activeInputConnection","deleteEventListenerOfAudioNode","audioNode","eventListener","getEventListenersOfAudioNode","deletePassiveInputConnectionToAudioParam","passiveInputs","source","output","passiveInputConnections","getValueForKey","matchingConnection","pickElementFromSet","passiveInputConnection","disconnectNativeAudioNodeFromNativeAudioNode","nativeSourceAudioNode","nativeDestinationAudioNode","output","input","isNativeAudioNodeFaker","getNativeAudioNode","audioNode","getValueForKey","AUDIO_NODE_STORE","getNativeAudioParam","audioParam","getValueForKey","AUDIO_PARAM_STORE","isPartOfACycle","audioNode","CYCLE_COUNTERS","isPassiveAudioNode","audioNode","ACTIVE_AUDIO_NODE_STORE","testAudioNodeDisconnectMethodSupport","nativeAudioContext","nativeAudioWorkletNodeConstructor","resolve","analyzer","dummy","ones","channelData","source","event","chnnlDt","sample","visitEachAudioNodeOnce","cycles","visitor","counts","cycle","audioNode","count","isNativeAudioNode","nativeAudioNodeOrAudioParam","wrapAudioNodeDisconnectMethod","nativeAudioNode","connections","connect","destination","output","input","returnValue","isNativeAudioNode","connectionsToDestination","connection","disconnect","destinationOrOutput","filteredConnections","addConnectionToAudioParamOfAudioContext","source","destination","output","isOffline","activeInputs","passiveInputs","getAudioParamConnections","outputs","getAudioNodeConnections","eventListeners","getEventListenersOfAudioNode","eventListener","isActive","nativeAudioNode","getNativeAudioNode","nativeAudioParam","getNativeAudioParam","partialConnection","deletePassiveInputConnectionToAudioParam","addActiveInputConnectionToAudioParam","isPartOfACycle","deleteActiveInputConnectionToAudioParam","addPassiveInputConnectionToAudioParam","insertElementInSet","outputConnection","isActiveAudioNode","deleteInputConnectionOfAudioNode","input","activeInputConnection","deleteActiveInputConnection","deletePassiveInputConnectionToAudioNode","deleteInputConnectionOfAudioParam","deleteInputsOfAudioNode","listener","deleteEventListenerOfAudioNode","disconnectNativeAudioNodeFromNativeAudioNode","setInternalStateToPassiveWhenNecessary","deleteInputsOfAudioParam","deleteAnyConnection","audioNodeConnectionsOfSource","destinations","isAudioNodeOutputConnection","deleteConnectionAtOutput","deleteConnectionToDestination","createAudioNodeConstructor","addAudioNodeConnections","addConnectionToAudioNode","cacheTestResult","createIncrementCycleCounter","createIndexSizeError","createInvalidAccessError","createNotSupportedError","decrementCycleCounter","detectCycles","eventTargetConstructor","getNativeContext","isNativeAudioContext","isNativeAudioNode","isNativeAudioParam","isNativeOfflineAudioContext","nativeAudioWorkletNodeConstructor","context","audioNodeRenderer","nativeContext","testAudioNodeDisconnectMethodSupport","wrapAudioNodeDisconnectMethod","AUDIO_NODE_STORE","EVENT_LISTENERS","setInternalStateToActive","value","isAudioNode","nativeDestinationAudioNode","connection","connectNativeAudioNodeToNativeAudioNode","isPassive","isPassiveAudioNode","err","cycles","visitEachAudioNodeOnce","destinationOrOutput","import_automation_events","createAudioParamFactory","addAudioParamConnections","audioParamAudioNodeStore","audioParamStore","createAudioParamRenderer","createCancelAndHoldAutomationEvent","createCancelScheduledValuesAutomationEvent","createExponentialRampToValueAutomationEvent","createLinearRampToValueAutomationEvent","createSetTargetAutomationEvent","createSetValueAutomationEvent","createSetValueCurveAutomationEvent","nativeAudioContextConstructor","setValueAtTimeUntilPossible","audioNode","isAudioParamOfOfflineAudioContext","nativeAudioParam","maxValue","minValue","defaultValue","automationEventList","audioParamRenderer","audioParam","value","cancelTime","previousLastEvent","currentLastEvent","endTime","currentTime","target","startTime","timeConstant","values","duration","convertedValues","sampleRate","firstSample","lastSample","numberOfInterpolatedValues","interpolatedValues","i","theoreticIndex","lowerIndex","upperIndex","timeOfLastSample","createAudioParamRenderer","automationEventList","audioParam","automationEvent","endTime","value","startTime","target","timeConstant","duration","values","ReadOnlyMap","parameters","callback","thisArg","value","key","name","DEFAULT_OPTIONS","createAudioWorkletNodeConstructor","addUnrenderedAudioWorkletNode","audioNodeConstructor","createAudioParam","createAudioWorkletNodeRenderer","createNativeAudioWorkletNode","getAudioNodeConnections","getBackupOfflineAudioContext","getNativeContext","isNativeOfflineAudioContext","nativeAudioWorkletNodeConstructor","sanitizeAudioWorkletNodeOptions","setActiveAudioWorkletNodeInputs","testAudioWorkletNodeOptionsClonability","wrapEventListener","context","name","options","nativeContext","isOffline","mergedOptions","nodeNameToProcessorConstructorMap","NODE_NAME_TO_PROCESSOR_CONSTRUCTOR_MAPS","processorConstructor","nativeContextOrBackupOfflineAudioContext","_a","nativeAudioWorkletNode","audioWorkletNodeRenderer","parameters","nativeAudioParam","nm","audioParam","ReadOnlyMap","activeInputs","value","wrappedListener","nativeOnProcessorError","copyFromChannel","audioBuffer","parent","key","channelNumber","bufferOffset","channelData","slicedInput","copyToChannel","audioBuffer","parent","key","channelNumber","bufferOffset","createNestedArrays","x","y","arrays","i","array","length","j","getAudioWorkletProcessor","nativeOfflineAudioContext","proxy","nodeToProcessorMap","getValueForKey","NODE_TO_PROCESSOR_MAPS","nativeAudioWorkletNode","getNativeAudioNode","processBuffer","proxy","renderedBuffer","nativeOfflineAudioContext","options","outputChannelCount","processorConstructor","exposeCurrentFrameAndCurrentTime","length","numberOfInputChannels","numberOfOutputChannels","sum","value","processedBuffer","audioNodeConnections","getAudioNodeConnections","audioWorkletProcessor","getAudioWorkletProcessor","inputs","createNestedArrays","outputs","parameters","prmtrs","name","i","j","k","copyFromChannel","index","potentiallyEmptyInputs","input","activeSourceFlag","outputChannelSplitterNodeOutput","copyToChannel","error","createAudioWorkletNodeRendererFactory","connectAudioParam","connectMultipleOutputs","createNativeAudioBufferSourceNode","createNativeChannelMergerNode","createNativeChannelSplitterNode","createNativeConstantSourceNode","createNativeGainNode","deleteUnrenderedAudioWorkletNode","disconnectMultipleOutputs","getNativeAudioNode","nativeAudioWorkletNodeConstructor","nativeOfflineAudioContextConstructor","renderAutomation","renderInputsOfAudioNode","renderNativeOfflineAudioContext","renderedNativeAudioNodes","processedBufferPromise","createAudioNode","nativeAudioWorkletNode","nativeOutputNodes","nativeAudioWorkletNodeIsOwnedByContext","isOwnedByContext","outputChannelSplitterNode","outputChannelMergerNodes","outputGainNode","numberOfParameters","numberOfChannels","partialOfflineAudioContext","gainNodes","inputChannelSplitterNodes","constantSourceNodes","audioParam","constantSourceNode","inputChannelMergerNode","gainNode","audioBufferSourceNode","outputChannelMergerNode","nm","renderedNativeAudioWorkletNodeOrGainNode","createBaseAudioContextConstructor","addAudioWorkletModule","analyserNodeConstructor","audioBufferConstructor","audioBufferSourceNodeConstructor","biquadFilterNodeConstructor","channelMergerNodeConstructor","channelSplitterNodeConstructor","constantSourceNodeConstructor","convolverNodeConstructor","decodeAudioData","delayNodeConstructor","dynamicsCompressorNodeConstructor","gainNodeConstructor","iIRFilterNodeConstructor","minimalBaseAudioContextConstructor","oscillatorNodeConstructor","pannerNodeConstructor","periodicWaveConstructor","stereoPannerNodeConstructor","waveShaperNodeConstructor","_nativeContext","numberOfChannels","moduleURL","options","length","sampleRate","numberOfInputs","numberOfOutputs","maxDelayTime","feedforward","feedback","real","imag","constraints","audioData","successCallback","errorCallback","audioBuffer","err","DEFAULT_OPTIONS","createBiquadFilterNodeConstructor","audioNodeConstructor","createAudioParam","createBiquadFilterNodeRenderer","createInvalidAccessError","createNativeBiquadFilterNode","getNativeContext","isNativeOfflineAudioContext","setAudioNodeTailTime","context","options","nativeContext","mergedOptions","nativeBiquadFilterNode","isOffline","biquadFilterNodeRenderer","MOST_POSITIVE_SINGLE_FLOAT","MOST_NEGATIVE_SINGLE_FLOAT","value","frequencyHz","magResponse","phaseResponse","err","createBiquadFilterNodeRendererFactory","connectAudioParam","createNativeBiquadFilterNode","getNativeAudioNode","renderAutomation","renderInputsOfAudioNode","renderedNativeBiquadFilterNodes","createBiquadFilterNode","proxy","nativeOfflineAudioContext","nativeBiquadFilterNode","nativeBiquadFilterNodeIsOwnedByContext","isOwnedByContext","options","renderedNativeBiquadFilterNode","createCacheTestResult","ongoingTests","testResults","tester","test","cachedTestResult","ongoingTest","synchronousTestResult","finalTestResult","DEFAULT_OPTIONS","createChannelMergerNodeConstructor","audioNodeConstructor","createChannelMergerNodeRenderer","createNativeChannelMergerNode","getNativeContext","isNativeOfflineAudioContext","context","options","nativeContext","mergedOptions","nativeChannelMergerNode","channelMergerNodeRenderer","createChannelMergerNodeRendererFactory","createNativeChannelMergerNode","getNativeAudioNode","renderInputsOfAudioNode","renderedNativeAudioNodes","createAudioNode","proxy","nativeOfflineAudioContext","nativeAudioNode","isOwnedByContext","options","renderedNativeAudioNode","DEFAULT_OPTIONS","createChannelSplitterNodeConstructor","audioNodeConstructor","createChannelSplitterNodeRenderer","createNativeChannelSplitterNode","getNativeContext","isNativeOfflineAudioContext","sanitizeChannelSplitterOptions","context","options","nativeContext","mergedOptions","nativeChannelSplitterNode","channelSplitterNodeRenderer","createChannelSplitterNodeRendererFactory","createNativeChannelSplitterNode","getNativeAudioNode","renderInputsOfAudioNode","renderedNativeAudioNodes","createAudioNode","proxy","nativeOfflineAudioContext","nativeAudioNode","isOwnedByContext","options","renderedNativeAudioNode","createConnectAudioParam","renderInputsOfAudioParam","nativeOfflineAudioContext","audioParam","nativeAudioParam","createConnectMultipleOutputs","createIndexSizeError","outputAudioNodes","destination","output","input","outputAudioNode","isNativeAudioNode","createConnectedNativeAudioBufferSourceNodeFactory","createNativeAudioBufferSourceNode","nativeContext","nativeAudioNode","nativeAudioBufferSourceNode","nativeAudioBuffer","DEFAULT_OPTIONS","createConstantSourceNodeConstructor","audioNodeConstructor","createAudioParam","createConstantSourceNodeRendererFactory","createNativeConstantSourceNode","getNativeContext","isNativeOfflineAudioContext","wrapEventListener","context","options","nativeContext","mergedOptions","nativeConstantSourceNode","isOffline","constantSourceNodeRenderer","MOST_POSITIVE_SINGLE_FLOAT","MOST_NEGATIVE_SINGLE_FLOAT","value","wrappedListener","nativeOnEnded","when","setInternalStateToActive","resetInternalStateToPassive","isActiveAudioNode","setInternalStateToPassive","createConstantSourceNodeRendererFactory","connectAudioParam","createNativeConstantSourceNode","getNativeAudioNode","renderAutomation","renderInputsOfAudioNode","renderedNativeConstantSourceNodes","start","stop","createConstantSourceNode","proxy","nativeOfflineAudioContext","nativeConstantSourceNode","nativeConstantSourceNodeIsOwnedByContext","isOwnedByContext","options","value","renderedNativeConstantSourceNode","createConvertNumberToUnsignedLong","unit32Array","value","DEFAULT_OPTIONS","createConvolverNodeConstructor","audioNodeConstructor","createConvolverNodeRenderer","createNativeConvolverNode","getNativeContext","isNativeOfflineAudioContext","setAudioNodeTailTime","context","options","nativeContext","mergedOptions","nativeConvolverNode","convolverNodeRenderer","value","createConvolverNodeRendererFactory","createNativeConvolverNode","getNativeAudioNode","renderInputsOfAudioNode","renderedNativeConvolverNodes","createConvolverNode","proxy","nativeOfflineAudioContext","nativeConvolverNode","isOwnedByContext","options","isNativeAudioNodeFaker","renderedNativeConvolverNode","createCreateNativeOfflineAudioContext","createNotSupportedError","nativeOfflineAudioContextConstructor","numberOfChannels","length","sampleRate","err","createDataCloneError","detachArrayBuffer","arrayBuffer","port1","port2","resolve","closeAndResolve","createDecodeAudioData","audioBufferStore","cacheTestResult","createDataCloneError","createEncodingError","detachedArrayBuffers","getNativeContext","isNativeContext","testAudioBufferCopyChannelMethodsOutOfBoundsSupport","testPromiseSupport","wrapAudioBufferCopyChannelMethods","wrapAudioBufferCopyChannelMethodsOutOfBounds","anyContext","audioData","nativeContext","err","audioBuffer","detachArrayBuffer","resolve","reject","complete","fail","wrapAudioBufferGetChannelDataMethod","createDecrementCycleCounter","connectNativeAudioNodeToNativeAudioNode","cycleCounters","getAudioNodeConnections","getNativeAudioNode","getNativeAudioParam","getNativeContext","isActiveAudioNode","isNativeOfflineAudioContext","audioNode","count","cycleCounter","nativeContext","isOffline","nativeSourceAudioNode","outputs","output","isAudioNodeOutputConnection","nativeDestinationAudioNode","nativeDestinationAudioParam","DEFAULT_OPTIONS","createDelayNodeConstructor","audioNodeConstructor","createAudioParam","createDelayNodeRenderer","createNativeDelayNode","getNativeContext","isNativeOfflineAudioContext","setAudioNodeTailTime","context","options","nativeContext","mergedOptions","nativeDelayNode","isOffline","delayNodeRenderer","createDelayNodeRendererFactory","connectAudioParam","createNativeDelayNode","getNativeAudioNode","renderAutomation","renderInputsOfAudioNode","maxDelayTime","renderedNativeDelayNodes","createDelayNode","proxy","nativeOfflineAudioContext","nativeDelayNode","nativeDelayNodeIsOwnedByContext","isOwnedByContext","options","renderedNativeDelayNode","createDeleteActiveInputConnectionToAudioNode","pickElementFromSet","activeInputs","source","output","input","activeInputConnection","createDeleteUnrenderedAudioWorkletNode","getUnrenderedAudioWorkletNodes","nativeContext","audioWorkletNode","isDelayNode","audioNode","createDetectCycles","audioParamAudioNodeStore","getAudioNodeConnections","getValueForKey","detectCycles","chain","nextLink","audioNode","isAudioNode","isDelayNode","outputs","outputConnection","mergedCycles","nestedCycles","getOutputAudioNodeAtIndex","createIndexSizeError","outputAudioNodes","output","outputAudioNode","createDisconnectMultipleOutputs","destinationOrOutput","input","isNativeAudioNode","DEFAULT_OPTIONS","createDynamicsCompressorNodeConstructor","audioNodeConstructor","createAudioParam","createDynamicsCompressorNodeRenderer","createNativeDynamicsCompressorNode","createNotSupportedError","getNativeContext","isNativeOfflineAudioContext","setAudioNodeTailTime","context","options","nativeContext","mergedOptions","nativeDynamicsCompressorNode","isOffline","dynamicsCompressorNodeRenderer","value","previousChannelCount","createDynamicsCompressorNodeRendererFactory","connectAudioParam","createNativeDynamicsCompressorNode","getNativeAudioNode","renderAutomation","renderInputsOfAudioNode","renderedNativeDynamicsCompressorNodes","createDynamicsCompressorNode","proxy","nativeOfflineAudioContext","nativeDynamicsCompressorNode","nativeDynamicsCompressorNodeIsOwnedByContext","isOwnedByContext","options","renderedNativeDynamicsCompressorNode","createEncodingError","createEvaluateSource","window","source","resolve","reject","head","script","blob","url","originalOnErrorHandler","removeErrorEventListenerAndRevokeUrl","message","src","lineno","colno","error","createEventTargetConstructor","wrapEventListener","_nativeEventTarget","type","listener","options","wrappedEventListener","event","createExposeCurrentFrameAndCurrentTime","window","currentTime","sampleRate","fn","createFetchSource","createAbortError","url","response","DEFAULT_OPTIONS","createGainNodeConstructor","audioNodeConstructor","createAudioParam","createGainNodeRenderer","createNativeGainNode","getNativeContext","isNativeOfflineAudioContext","context","options","nativeContext","mergedOptions","nativeGainNode","isOffline","gainNodeRenderer","MOST_POSITIVE_SINGLE_FLOAT","MOST_NEGATIVE_SINGLE_FLOAT","createGainNodeRendererFactory","connectAudioParam","createNativeGainNode","getNativeAudioNode","renderAutomation","renderInputsOfAudioNode","renderedNativeGainNodes","createGainNode","proxy","nativeOfflineAudioContext","nativeGainNode","nativeGainNodeIsOwnedByContext","isOwnedByContext","options","renderedNativeGainNode","createGetActiveAudioWorkletNodeInputs","activeAudioWorkletNodeInputsStore","getValueForKey","nativeAudioWorkletNode","createGetAudioNodeRenderer","getAudioNodeConnections","audioNode","audioNodeConnections","createGetAudioNodeTailTime","audioNodeTailTimeStore","audioNode","_a","createGetAudioParamRenderer","getAudioParamConnections","audioParam","audioParamConnections","createGetBackupOfflineAudioContext","backupOfflineAudioContextStore","nativeContext","createInvalidStateError","createGetNativeContext","contextStore","context","nativeContext","createInvalidStateError","createGetOrCreateBackupOfflineAudioContext","backupOfflineAudioContextStore","nativeOfflineAudioContextConstructor","nativeContext","backupOfflineAudioContext","createGetUnrenderedAudioWorkletNodes","unrenderedAudioWorkletNodeStore","nativeContext","unrenderedAudioWorkletNodes","createInvalidAccessError","wrapIIRFilterNodeGetFrequencyResponseMethod","nativeIIRFilterNode","getFrequencyResponse","frequencyHz","magResponse","phaseResponse","createInvalidAccessError","DEFAULT_OPTIONS","createIIRFilterNodeConstructor","audioNodeConstructor","createNativeIIRFilterNode","createIIRFilterNodeRenderer","getNativeContext","isNativeOfflineAudioContext","setAudioNodeTailTime","context","options","nativeContext","isOffline","mergedOptions","nativeIIRFilterNode","iirFilterNodeRenderer","wrapIIRFilterNodeGetFrequencyResponseMethod","frequencyHz","magResponse","phaseResponse","filterBuffer","feedback","feedbackLength","feedforward","feedforwardLength","minLength","xBuffer","yBuffer","bufferIndex","bufferLength","input","output","inputLength","i","j","y","k","x","filterFullBuffer","renderedBuffer","nativeOfflineAudioContext","feedback","feedforward","convertedFeedback","convertedFeedforward","feedbackLength","feedforwardLength","minLength","i","bufferLength","xBuffer","yBuffer","filteredBuffer","numberOfChannels","input","output","filterBuffer","createIIRFilterNodeRendererFactory","createNativeAudioBufferSourceNode","getNativeAudioNode","nativeOfflineAudioContextConstructor","renderInputsOfAudioNode","renderNativeOfflineAudioContext","renderedNativeAudioNodes","filteredBufferPromise","createAudioNode","proxy","nativeAudioBufferSourceNode","nativeIIRFilterNode","nativeIIRFilterNodeIsOwnedByContext","isOwnedByContext","partialOfflineAudioContext","renderedNativeAudioNode","createIncrementCycleCounterFactory","cycleCounters","disconnectNativeAudioNodeFromNativeAudioNode","getAudioNodeConnections","getNativeAudioNode","getNativeAudioParam","isActiveAudioNode","isOffline","audioNode","count","cycleCounter","nativeSourceAudioNode","outputs","output","isAudioNodeOutputConnection","nativeDestinationAudioNode","nativeDestinationAudioParam","createIsAnyAudioContext","contextStore","isNativeAudioContext","anything","nativeContext","createIsAnyAudioNode","audioNodeStore","isNativeAudioNode","anything","createIsAnyAudioParam","audioParamStore","isNativeAudioParam","anything","createIsAnyOfflineAudioContext","contextStore","isNativeOfflineAudioContext","anything","nativeContext","createIsNativeAudioContext","nativeAudioContextConstructor","anything","createIsNativeAudioNode","window","anything","createIsNativeAudioParam","window","anything","createIsNativeContext","isNativeAudioContext","isNativeOfflineAudioContext","anything","createIsNativeOfflineAudioContext","nativeOfflineAudioContextConstructor","anything","createIsSecureContext","window","createMediaElementAudioSourceNodeConstructor","audioNodeConstructor","createNativeMediaElementAudioSourceNode","getNativeContext","isNativeOfflineAudioContext","context","options","nativeContext","nativeMediaElementAudioSourceNode","DEFAULT_OPTIONS","createMediaStreamAudioDestinationNodeConstructor","audioNodeConstructor","createNativeMediaStreamAudioDestinationNode","getNativeContext","isNativeOfflineAudioContext","context","options","nativeContext","mergedOptions","nativeMediaStreamAudioDestinationNode","createMediaStreamAudioSourceNodeConstructor","audioNodeConstructor","createNativeMediaStreamAudioSourceNode","getNativeContext","isNativeOfflineAudioContext","context","options","nativeContext","nativeMediaStreamAudioSourceNode","createMediaStreamTrackAudioSourceNodeConstructor","audioNodeConstructor","createNativeMediaStreamTrackAudioSourceNode","getNativeContext","context","options","nativeContext","nativeMediaStreamTrackAudioSourceNode","createMinimalAudioContextConstructor","createInvalidStateError","createNotSupportedError","createUnknownError","minimalBaseAudioContextConstructor","nativeAudioContextConstructor","options","nativeAudioContext","err","isValidLatencyHint","latencyHint","sampleRate","revokeState","deactivateAudioGraph","resolve","reject","resolvePromise","createMinimalBaseAudioContextConstructor","audioDestinationNodeConstructor","createAudioListener","eventTargetConstructor","isNativeOfflineAudioContext","unrenderedAudioWorkletNodeStore","wrapEventListener","_nativeContext","numberOfChannels","CONTEXT_STORE","value","wrappedListener","nativeOnStateChange","testPromiseSupport","nativeContext","uint32Array","promise","DEFAULT_OPTIONS","createMinimalOfflineAudioContextConstructor","cacheTestResult","createInvalidStateError","createNativeOfflineAudioContext","minimalBaseAudioContextConstructor","startRendering","options","length","numberOfChannels","sampleRate","nativeOfflineAudioContext","testPromiseSupport","i","delayStateChangeEvent","event","deactivateAudioGraph","createMonitorConnections","insertElementInSet","isNativeAudioNode","nativeAudioNode","whenConnected","whenDisconnected","connections","connect","destination","output","input","wasDisconnected","connection","disconnect","destinationOrOutput","wasConnected","isDisconnected","assignNativeAudioNodeOption","nativeAudioNode","options","option","value","assignNativeAudioNodeOptions","nativeAudioNode","options","assignNativeAudioNodeOption","testAnalyserNodeGetFloatTimeDomainDataMethodSupport","nativeAnalyserNode","wrapAnalyserNodeGetFloatTimeDomainDataMethod","nativeAnalyserNode","array","byteTimeDomainData","length","i","createNativeAnalyserNodeFactory","cacheTestResult","createIndexSizeError","nativeContext","options","nativeAnalyserNode","assignNativeAudioNodeOptions","assignNativeAudioNodeOption","testAnalyserNodeGetFloatTimeDomainDataMethodSupport","wrapAnalyserNodeGetFloatTimeDomainDataMethod","createNativeAudioBufferConstructor","window","assignNativeAudioNodeAudioParamValue","nativeAudioNode","options","audioParam","value","wrapAudioBufferSourceNodeStartMethodConsecutiveCalls","nativeAudioBufferSourceNode","start","isScheduled","when","offset","duration","createInvalidStateError","wrapAudioScheduledSourceNodeStartMethodNegativeParameters","nativeAudioScheduledSourceNode","start","when","offset","duration","wrapAudioScheduledSourceNodeStopMethodNegativeParameters","nativeAudioScheduledSourceNode","stop","when","createNativeAudioBufferSourceNodeFactory","addSilentConnection","cacheTestResult","testAudioBufferSourceNodeStartMethodConsecutiveCallsSupport","testAudioBufferSourceNodeStartMethodOffsetClampingSupport","testAudioBufferSourceNodeStopMethodNullifiedBufferSupport","testAudioScheduledSourceNodeStartMethodNegativeParametersSupport","testAudioScheduledSourceNodeStopMethodConsecutiveCallsSupport","testAudioScheduledSourceNodeStopMethodNegativeParametersSupport","wrapAudioBufferSourceNodeStartMethodOffsetClampling","wrapAudioBufferSourceNodeStopMethodNullifiedBuffer","wrapAudioScheduledSourceNodeStopMethodConsecutiveCalls","nativeContext","options","nativeAudioBufferSourceNode","assignNativeAudioNodeOptions","assignNativeAudioNodeAudioParamValue","assignNativeAudioNodeOption","wrapAudioBufferSourceNodeStartMethodConsecutiveCalls","wrapAudioScheduledSourceNodeStartMethodNegativeParameters","wrapAudioScheduledSourceNodeStopMethodNegativeParameters","createNativeAudioContextConstructor","window","createNativeAudioDestinationNodeFactory","createNativeGainNode","overwriteAccessors","nativeContext","channelCount","isNodeOfNativeOfflineAudioContext","nativeAudioDestinationNode","gainNode","get","set","value","err","createNativeAudioWorkletNodeConstructor","window","testClonabilityOfAudioWorkletNodeOptions","audioWorkletNodeOptions","port1","createNativeAudioWorkletNodeFactory","createInvalidStateError","createNativeAudioWorkletNodeFaker","createNativeGainNode","createNotSupportedError","monitorConnections","nativeContext","baseLatency","nativeAudioWorkletNodeConstructor","name","processorConstructor","options","nativeAudioWorkletNode","patchedEventListeners","onprocessorerror","value","addEventListener","args","unpatchedEventListener","patchedEventListener","event","removeEventListener","nativeGainNode","err","testClonabilityOfAudioWorkletNodeOptions","computeBufferSize","baseLatency","sampleRate","cloneAudioWorkletNodeOptions","audioWorkletNodeOptions","resolve","reject","port1","port2","data","createAudioWorkletProcessorPromise","processorConstructor","audioWorkletNodeOptions","clonedAudioWorkletNodeOptions","cloneAudioWorkletNodeOptions","createAudioWorkletProcessor","nativeContext","nativeAudioWorkletNode","processorConstructor","audioWorkletNodeOptions","nodeToProcessorMap","NODE_TO_PROCESSOR_MAPS","audioWorkletProcessorPromise","createAudioWorkletProcessorPromise","createNativeAudioWorkletNodeFakerFactory","connectMultipleOutputs","createIndexSizeError","createInvalidStateError","createNativeChannelMergerNode","createNativeChannelSplitterNode","createNativeConstantSourceNode","createNativeGainNode","createNativeScriptProcessorNode","createNotSupportedError","disconnectMultipleOutputs","exposeCurrentFrameAndCurrentTime","getActiveAudioWorkletNodeInputs","monitorConnections","nativeContext","baseLatency","processorConstructor","options","outputChannelCount","channelCount","numberOfInputChannels","numberOfOutputChannels","sum","value","numberOfParameters","messageChannel","gainNodes","inputChannelSplitterNodes","i","constantSourceNodes","defaultValue","maxValue","minValue","name","constantSourceNode","MOST_POSITIVE_SINGLE_FLOAT","MOST_NEGATIVE_SINGLE_FLOAT","inputChannelMergerNode","bufferSize","computeBufferSize","scriptProcessorNode","outputChannelSplitterNode","outputChannelMergerNodes","j","parameterMap","ReadOnlyMap","index","channelInterpretation","onprocessorerror","outputAudioNodes","nativeAudioWorkletNodeFaker","_","gainNode","args","patchedEventListeners","addEventListener","unpatchedEventListener","patchedEventListener","event","removeEventListener","onmessage","audioWorkletProcessor","createAudioWorkletProcessor","dWrkltPrcssr","inputs","createNestedArrays","outputs","parameters","prmtrs","isActive","disconnectOutputsGraph","outputChannelSplitterNodeOutput","outputChannelMergerNode","activeInputIndexes","inputBuffer","outputBuffer","activeInputs","k","copyFromChannel","potentiallyEmptyInputs","input","count","channelData","sample","copyToChannel","error","length","isConnected","disconnectFakeGraph","nativeGainNode","connectFakeGraph","whenConnected","whenDisconnected","createNativeBiquadFilterNode","nativeContext","options","nativeBiquadFilterNode","assignNativeAudioNodeOptions","assignNativeAudioNodeAudioParamValue","assignNativeAudioNodeOption","createNativeChannelMergerNodeFactory","nativeAudioContextConstructor","wrapChannelMergerNode","nativeContext","options","nativeChannelMergerNode","assignNativeAudioNodeOptions","wrapChannelSplitterNode","channelSplitterNode","channelCount","value","createInvalidStateError","createNativeChannelSplitterNode","nativeContext","options","nativeChannelSplitterNode","assignNativeAudioNodeOptions","wrapChannelSplitterNode","createNativeConstantSourceNodeFactory","addSilentConnection","cacheTestResult","createNativeConstantSourceNodeFaker","testAudioScheduledSourceNodeStartMethodNegativeParametersSupport","testAudioScheduledSourceNodeStopMethodNegativeParametersSupport","nativeContext","options","nativeConstantSourceNode","assignNativeAudioNodeOptions","assignNativeAudioNodeAudioParamValue","wrapAudioScheduledSourceNodeStartMethodNegativeParameters","wrapAudioScheduledSourceNodeStopMethodNegativeParameters","interceptConnections","original","interceptor","createNativeConstantSourceNodeFakerFactory","addSilentConnection","createNativeAudioBufferSourceNode","createNativeGainNode","monitorConnections","nativeContext","offset","audioNodeOptions","audioBuffer","audioBufferSourceNode","gainNode","channelData","nativeConstantSourceNodeFaker","value","args","when","whenConnected","whenDisconnected","interceptConnections","createNativeConvolverNodeFactory","createNotSupportedError","overwriteAccessors","nativeContext","options","nativeConvolverNode","assignNativeAudioNodeOptions","assignNativeAudioNodeOption","get","set","value","createNativeDelayNode","nativeContext","options","nativeDelayNode","assignNativeAudioNodeOptions","assignNativeAudioNodeAudioParamValue","createNativeDynamicsCompressorNodeFactory","createNotSupportedError","nativeContext","options","nativeDynamicsCompressorNode","assignNativeAudioNodeOptions","assignNativeAudioNodeAudioParamValue","createNativeGainNode","nativeContext","options","nativeGainNode","assignNativeAudioNodeOptions","assignNativeAudioNodeAudioParamValue","createNativeIIRFilterNodeFactory","createNativeIIRFilterNodeFaker","nativeContext","baseLatency","options","nativeIIRFilterNode","assignNativeAudioNodeOptions","divide","a","b","denominator","multiply","evaluatePolynomial","coefficient","z","result","i","createNativeIIRFilterNodeFakerFactory","createInvalidAccessError","createInvalidStateError","createNativeScriptProcessorNode","createNotSupportedError","nativeContext","baseLatency","channelCount","channelCountMode","channelInterpretation","feedback","feedforward","bufferSize","computeBufferSize","convertedFeedback","convertedFeedforward","feedbackLength","feedforwardLength","minLength","scriptProcessorNode","bufferLength","bufferIndexes","xBuffers","yBuffers","xBuffer","yBuffer","event","inputBuffer","outputBuffer","numberOfChannels","input","output","filterBuffer","nyquist","interceptConnections","value","args","frequencyHz","magResponse","phaseResponse","length","omega","numerator","response","createNativeMediaElementAudioSourceNode","nativeAudioContext","options","createNativeMediaStreamAudioDestinationNode","nativeAudioContext","options","nativeMediaStreamAudioDestinationNode","assignNativeAudioNodeOptions","createNativeMediaStreamAudioSourceNode","nativeAudioContext","mediaStream","audioStreamTracks","a","b","filteredAudioStreamTracks","nativeMediaStreamAudioSourceNode","createNativeMediaStreamTrackAudioSourceNodeFactory","createInvalidStateError","isNativeOfflineAudioContext","nativeAudioContext","mediaStreamTrack","mediaStream","nativeMediaStreamAudioSourceNode","createNativeOfflineAudioContextConstructor","window","createNativeOscillatorNodeFactory","addSilentConnection","cacheTestResult","testAudioScheduledSourceNodeStartMethodNegativeParametersSupport","testAudioScheduledSourceNodeStopMethodConsecutiveCallsSupport","testAudioScheduledSourceNodeStopMethodNegativeParametersSupport","wrapAudioScheduledSourceNodeStopMethodConsecutiveCalls","nativeContext","options","nativeOscillatorNode","assignNativeAudioNodeOptions","assignNativeAudioNodeAudioParamValue","assignNativeAudioNodeOption","wrapAudioScheduledSourceNodeStartMethodNegativeParameters","wrapAudioScheduledSourceNodeStopMethodNegativeParameters","createNativePannerNodeFactory","createNativePannerNodeFaker","nativeContext","options","nativePannerNode","assignNativeAudioNodeOptions","assignNativeAudioNodeAudioParamValue","assignNativeAudioNodeOption","createNativePannerNodeFakerFactory","connectNativeAudioNodeToNativeAudioNode","createInvalidStateError","createNativeChannelMergerNode","createNativeGainNode","createNativeScriptProcessorNode","createNativeWaveShaperNode","createNotSupportedError","disconnectNativeAudioNodeFromNativeAudioNode","getFirstSample","monitorConnections","nativeContext","coneInnerAngle","coneOuterAngle","coneOuterGain","distanceModel","maxDistance","orientationX","orientationY","orientationZ","panningModel","positionX","positionY","positionZ","refDistance","rolloffFactor","audioNodeOptions","pannerNode","assignNativeAudioNodeOptions","SINGLE_CHANNEL_OPTIONS","channelMergerNode","inputGainNode","orientationXGainNode","orientationYGainNode","orientationZGainNode","positionXGainNode","positionYGainNode","positionZGainNode","scriptProcessorNode","waveShaperNode","lastOrientation","lastPosition","buffer","inputBuffer","orientation","value","index","positon","nativePannerNodeFaker","args","whenConnected","whenDisconnected","interceptConnections","createNativePeriodicWaveFactory","createIndexSizeError","nativeContext","disableNormalization","imag","real","convertedImag","convertedReal","nativePeriodicWave","createNativeScriptProcessorNode","nativeContext","bufferSize","numberOfInputChannels","numberOfOutputChannels","createNativeStereoPannerNodeFactory","createNativeStereoPannerNodeFaker","createNotSupportedError","nativeContext","options","channelCountMode","nativeStereoPannerNode","assignNativeAudioNodeOptions","assignNativeAudioNodeAudioParamValue","value","createNativeStereoPannerNodeFakerFactory","createNativeChannelMergerNode","createNativeChannelSplitterNode","createNativeGainNode","createNativeWaveShaperNode","createNotSupportedError","monitorConnections","DC_CURVE","HALF_PI","SINGLE_CHANNEL_OPTIONS","SINGLE_CHANNEL_WAVE_SHAPER_OPTIONS","buildInternalGraphForMono","nativeContext","inputGainNode","panGainNode","channelMergerNode","leftWaveShaperCurve","rightWaveShaperCurve","i","x","leftGainNode","leftWaveShaperNode","panWaveShaperNode","rightGainNode","rightWaveShaperNode","buildInternalGraphForStereo","leftInputForLeftOutputWaveShaperCurve","leftInputForRightOutputWaveShaperCurve","rightInputForLeftOutputWaveShaperCurve","rightInputForRightOutputWaveShaperCurve","centerIndex","channelSplitterNode","leftInputForLeftOutputGainNode","leftInputForLeftOutputWaveShaperNode","leftInputForRightOutputGainNode","leftInputForRightOutputWaveShaperNode","rightInputForLeftOutputGainNode","rightInputForLeftOutputWaveShaperNode","rightInputForRightOutputGainNode","rightInputForRightOutputWaveShaperNode","buildInternalGraph","channelCount","channelCountMode","pan","audioNodeOptions","connectGraph","disconnectGraph","nativeStereoPannerNodeFakerFactory","value","isConnected","args","whenConnected","whenDisconnected","interceptConnections","createNativeWaveShaperNodeFactory","createConnectedNativeAudioBufferSourceNode","createInvalidStateError","createNativeWaveShaperNodeFaker","isDCCurve","monitorConnections","nativeAudioContextConstructor","overwriteAccessors","nativeContext","options","nativeWaveShaperNode","assignNativeAudioNodeOptions","curve","assignNativeAudioNodeOption","disconnectNativeAudioBufferSourceNode","isConnected","get","set","value","createNativeWaveShaperNodeFakerFactory","createConnectedNativeAudioBufferSourceNode","createInvalidStateError","createNativeGainNode","isDCCurve","monitorConnections","nativeContext","curve","oversample","audioNodeOptions","negativeWaveShaperNode","positiveWaveShaperNode","assignNativeAudioNodeOptions","inputGainNode","invertGainNode","outputGainNode","revertGainNode","disconnectNativeAudioBufferSourceNode","isConnected","unmodifiedCurve","nativeWaveShaperNodeFaker","value","curveLength","negativeCurve","positiveCurve","length","centerIndex","i","theoreticIndex","lowerIndex","upperIndex","args","whenConnected","whenDisconnected","interceptConnections","createNotSupportedError","DEFAULT_OPTIONS","createOfflineAudioContextConstructor","baseAudioContextConstructor","cacheTestResult","createInvalidStateError","createNativeOfflineAudioContext","startRendering","b","options","length","numberOfChannels","sampleRate","nativeOfflineAudioContext","testPromiseSupport","i","delayStateChangeEvent","event","deactivateAudioGraph","DEFAULT_OPTIONS","createOscillatorNodeConstructor","audioNodeConstructor","createAudioParam","createNativeOscillatorNode","createOscillatorNodeRenderer","getNativeContext","isNativeOfflineAudioContext","wrapEventListener","context","options","nativeContext","mergedOptions","nativeOscillatorNode","isOffline","oscillatorNodeRenderer","nyquist","value","wrappedListener","nativeOnEnded","periodicWave","when","setInternalStateToActive","resetInternalStateToPassive","isActiveAudioNode","setInternalStateToPassive","createOscillatorNodeRendererFactory","connectAudioParam","createNativeOscillatorNode","getNativeAudioNode","renderAutomation","renderInputsOfAudioNode","renderedNativeOscillatorNodes","periodicWave","start","stop","createOscillatorNode","proxy","nativeOfflineAudioContext","nativeOscillatorNode","nativeOscillatorNodeIsOwnedByContext","isOwnedByContext","options","value","renderedNativeOscillatorNode","DEFAULT_OPTIONS","createPannerNodeConstructor","audioNodeConstructor","createAudioParam","createNativePannerNode","createPannerNodeRenderer","getNativeContext","isNativeOfflineAudioContext","setAudioNodeTailTime","context","options","nativeContext","mergedOptions","nativePannerNode","isOffline","pannerNodeRenderer","MOST_POSITIVE_SINGLE_FLOAT","MOST_NEGATIVE_SINGLE_FLOAT","value","createPannerNodeRendererFactory","connectAudioParam","createNativeChannelMergerNode","createNativeConstantSourceNode","createNativeGainNode","createNativePannerNode","getNativeAudioNode","nativeOfflineAudioContextConstructor","renderAutomation","renderInputsOfAudioNode","renderNativeOfflineAudioContext","renderedNativeAudioNodes","renderedBufferPromise","createAudioNode","proxy","nativeOfflineAudioContext","nativeGainNode","nativePannerNode","commonAudioNodeOptions","commonNativePannerNodeOptions","nativePannerNodeIsOwnedByContext","isOwnedByContext","options","partialOfflineAudioContext","nativeChannelMergerNode","nativeConstantSourceNodes","audioParam","index","nativeConstantSourceNode","i","renderedBuffer","inputGainNode","channelDatas","lastOrientation","lastPosition","gateGainNode","partialPannerNode","orientation","positon","value","currentTime","isNativeAudioNodeFaker","renderedNativeGainNodeOrNativePannerNode","DEFAULT_OPTIONS","createPeriodicWaveConstructor","createNativePeriodicWave","getNativeContext","periodicWaveStore","sanitizePeriodicWaveOptions","PeriodicWave","context","options","nativeContext","mergedOptions","periodicWave","instance","createRenderAutomation","getAudioParamRenderer","renderInputsOfAudioParam","nativeOfflineAudioContext","audioParam","nativeAudioParam","createRenderInputsOfAudioNode","getAudioNodeConnections","getAudioNodeRenderer","isPartOfACycle","audioNode","nativeOfflineAudioContext","nativeAudioNode","audioNodeConnections","connections","input","source","output","renderedNativeAudioNode","destination","allRenderingPromises","renderingPromises","createRenderInputsOfAudioParam","getAudioNodeRenderer","getAudioParamConnections","isPartOfACycle","audioParam","nativeOfflineAudioContext","nativeAudioParam","audioParamConnections","source","output","renderedNativeAudioNode","createRenderNativeOfflineAudioContext","cacheTestResult","createNativeGainNode","createNativeScriptProcessorNode","testOfflineAudioContextCurrentTimeSupport","nativeOfflineAudioContext","testPromiseSupport","isOfflineAudioContextCurrentTimeSupported","scriptProcessorNode","resolve","gainNode","event","createSetActiveAudioWorkletNodeInputs","activeAudioWorkletNodeInputsStore","nativeAudioWorkletNode","activeInputs","createSetAudioNodeTailTime","audioNodeTailTimeStore","audioNode","tailTime","createStartRendering","audioBufferStore","cacheTestResult","getAudioNodeRenderer","getUnrenderedAudioWorkletNodes","renderNativeOfflineAudioContext","testAudioBufferCopyChannelMethodsOutOfBoundsSupport","wrapAudioBufferCopyChannelMethods","wrapAudioBufferCopyChannelMethodsOutOfBounds","destination","nativeOfflineAudioContext","audioWorkletNode","audioBuffer","wrapAudioBufferGetChannelDataMethod","DEFAULT_OPTIONS","createStereoPannerNodeConstructor","audioNodeConstructor","createAudioParam","createNativeStereoPannerNode","createStereoPannerNodeRenderer","getNativeContext","isNativeOfflineAudioContext","context","options","nativeContext","mergedOptions","nativeStereoPannerNode","isOffline","stereoPannerNodeRenderer","createStereoPannerNodeRendererFactory","connectAudioParam","createNativeStereoPannerNode","getNativeAudioNode","renderAutomation","renderInputsOfAudioNode","renderedNativeStereoPannerNodes","createStereoPannerNode","proxy","nativeOfflineAudioContext","nativeStereoPannerNode","nativeStereoPannerNodeIsOwnedByContext","isOwnedByContext","options","isNativeAudioNodeFaker","renderedNativeStereoPannerNode","createTestAudioBufferConstructorSupport","nativeAudioBufferConstructor","createTestAudioWorkletProcessorPostMessageSupport","nativeAudioWorkletNodeConstructor","nativeOfflineAudioContextConstructor","blob","offlineAudioContext","url","isEmittingMessageEvents","isEmittingProcessorErrorEvents","audioWorkletNode","oscillator","resolve","createTestOfflineAudioContextCurrentTimeSupport","createNativeGainNode","nativeOfflineAudioContextConstructor","nativeOfflineAudioContext","gainNode","resolve","createUnknownError","DEFAULT_OPTIONS","createWaveShaperNodeConstructor","audioNodeConstructor","createInvalidStateError","createNativeWaveShaperNode","createWaveShaperNodeRenderer","getNativeContext","isNativeOfflineAudioContext","setAudioNodeTailTime","context","options","nativeContext","mergedOptions","nativeWaveShaperNode","waveShaperNodeRenderer","value","createWaveShaperNodeRendererFactory","createNativeWaveShaperNode","getNativeAudioNode","renderInputsOfAudioNode","renderedNativeWaveShaperNodes","createWaveShaperNode","proxy","nativeOfflineAudioContext","nativeWaveShaperNode","isOwnedByContext","options","isNativeAudioNodeFaker","renderedNativeWaveShaperNode","createWindow","createWrapAudioBufferCopyChannelMethods","convertNumberToUnsignedLong","createIndexSizeError","audioBuffer","destination","channelNumberAsNumber","bufferOffsetAsNumber","bufferOffset","channelNumber","audioBufferLength","channelData","destinationLength","i","source","sourceLength","createWrapAudioBufferCopyChannelMethodsOutOfBounds","convertNumberToUnsignedLong","audioBuffer","copyFromChannel","destination","channelNumberAsNumber","bufferOffsetAsNumber","bufferOffset","channelNumber","copyToChannel","source","createWrapAudioBufferSourceNodeStopMethodNullifiedBuffer","overwriteAccessors","nativeAudioBufferSourceNode","nativeContext","nullifiedBuffer","get","value","set","createWrapChannelMergerNode","createInvalidStateError","monitorConnections","nativeContext","channelMergerNode","audioBufferSourceNode","length","i","getFirstSample","audioBuffer","buffer","channelNumber","isDCCurve","curve","length","overwriteAccessors","object","property","createGetter","createSetter","prototype","get","set","sanitizeAudioWorkletNodeOptions","options","sanitizeChannelSplitterOptions","options","sanitizePeriodicWaveOptions","options","imag","real","setValueAtTimeUntilPossible","audioParam","value","startTime","err","testAudioBufferSourceNodeStartMethodConsecutiveCallsSupport","nativeContext","nativeAudioBufferSourceNode","testAudioBufferSourceNodeStartMethodOffsetClampingSupport","nativeContext","nativeAudioBufferSourceNode","nativeAudioBuffer","testAudioBufferSourceNodeStopMethodNullifiedBufferSupport","nativeContext","nativeAudioBufferSourceNode","testAudioScheduledSourceNodeStartMethodNegativeParametersSupport","nativeContext","nativeAudioBufferSourceNode","err","testAudioScheduledSourceNodeStopMethodConsecutiveCallsSupport","nativeContext","nativeAudioBuffer","nativeAudioBufferSourceNode","testAudioScheduledSourceNodeStopMethodNegativeParametersSupport","nativeContext","nativeAudioBufferSourceNode","err","testAudioWorkletNodeOptionsClonability","audioWorkletNodeOptions","port1","port2","wrapAudioBufferSourceNodeStartMethodOffsetClamping","nativeAudioBufferSourceNode","start","when","offset","duration","buffer","clampedOffset","wrapAudioScheduledSourceNodeStopMethodConsecutiveCalls","nativeAudioScheduledSourceNode","nativeContext","nativeGainNode","disconnectGainNode","disconnect","interceptConnections","stop","isStopped","when","wrapEventListener","target","eventListener","event","descriptor","addActiveInputConnectionToAudioNode","createAddActiveInputConnectionToAudioNode","insertElementInSet","addPassiveInputConnectionToAudioNode","createAddPassiveInputConnectionToAudioNode","deleteActiveInputConnectionToAudioNode","createDeleteActiveInputConnectionToAudioNode","pickElementFromSet","audioNodeTailTimeStore","getAudioNodeTailTime","createGetAudioNodeTailTime","cacheTestResult","createCacheTestResult","window","createWindow","createNativeAnalyserNode","createNativeAnalyserNodeFactory","createIndexSizeError","getAudioNodeRenderer","createGetAudioNodeRenderer","getAudioNodeConnections","renderInputsOfAudioNode","createRenderInputsOfAudioNode","isPartOfACycle","createAnalyserNodeRenderer","createAnalyserNodeRendererFactory","getNativeAudioNode","getNativeContext","createGetNativeContext","CONTEXT_STORE","nativeOfflineAudioContextConstructor","createNativeOfflineAudioContextConstructor","isNativeOfflineAudioContext","createIsNativeOfflineAudioContext","audioParamAudioNodeStore","eventTargetConstructor","createEventTargetConstructor","wrapEventListener","nativeAudioContextConstructor","createNativeAudioContextConstructor","isNativeAudioContext","createIsNativeAudioContext","isNativeAudioNode","createIsNativeAudioNode","isNativeAudioParam","createIsNativeAudioParam","nativeAudioWorkletNodeConstructor","createNativeAudioWorkletNodeConstructor","audioNodeConstructor","createAudioNodeConstructor","createAddAudioNodeConnections","AUDIO_NODE_CONNECTIONS_STORE","createAddConnectionToAudioNode","connectNativeAudioNodeToNativeAudioNode","disconnectNativeAudioNodeFromNativeAudioNode","getEventListenersOfAudioNode","isActiveAudioNode","isPassiveAudioNode","createIncrementCycleCounterFactory","CYCLE_COUNTERS","getNativeAudioParam","createInvalidAccessError","createNotSupportedError","createDecrementCycleCounter","createDetectCycles","getValueForKey","analyserNodeConstructor","createAnalyserNodeConstructor","audioBufferStore","nativeAudioBufferConstructor","createNativeAudioBufferConstructor","window","convertNumberToUnsignedLong","createConvertNumberToUnsignedLong","wrapAudioBufferCopyChannelMethods","createWrapAudioBufferCopyChannelMethods","createIndexSizeError","wrapAudioBufferCopyChannelMethodsOutOfBounds","createWrapAudioBufferCopyChannelMethodsOutOfBounds","audioBufferConstructor","createAudioBufferConstructor","cacheTestResult","createNotSupportedError","nativeOfflineAudioContextConstructor","createTestAudioBufferConstructorSupport","addSilentConnection","createAddSilentConnection","createNativeGainNode","renderInputsOfAudioParam","createRenderInputsOfAudioParam","getAudioNodeRenderer","getAudioParamConnections","isPartOfACycle","connectAudioParam","createConnectAudioParam","createNativeAudioBufferSourceNode","createNativeAudioBufferSourceNodeFactory","cacheTestResult","testAudioBufferSourceNodeStartMethodConsecutiveCallsSupport","testAudioBufferSourceNodeStartMethodOffsetClampingSupport","testAudioBufferSourceNodeStopMethodNullifiedBufferSupport","testAudioScheduledSourceNodeStartMethodNegativeParametersSupport","testAudioScheduledSourceNodeStopMethodConsecutiveCallsSupport","testAudioScheduledSourceNodeStopMethodNegativeParametersSupport","wrapAudioBufferSourceNodeStartMethodOffsetClamping","createWrapAudioBufferSourceNodeStopMethodNullifiedBuffer","overwriteAccessors","wrapAudioScheduledSourceNodeStopMethodConsecutiveCalls","renderAutomation","createRenderAutomation","createGetAudioParamRenderer","createAudioBufferSourceNodeRenderer","createAudioBufferSourceNodeRendererFactory","getNativeAudioNode","renderInputsOfAudioNode","createAudioParam","createAudioParamFactory","createAddAudioParamConnections","AUDIO_PARAM_CONNECTIONS_STORE","audioParamAudioNodeStore","AUDIO_PARAM_STORE","createAudioParamRenderer","nativeAudioContextConstructor","setValueAtTimeUntilPossible","audioBufferSourceNodeConstructor","createAudioBufferSourceNodeConstructor","audioNodeConstructor","createInvalidStateError","getNativeContext","isNativeOfflineAudioContext","wrapEventListener","audioDestinationNodeConstructor","createAudioDestinationNodeConstructor","audioNodeConstructor","createAudioDestinationNodeRenderer","createIndexSizeError","createInvalidStateError","createNativeAudioDestinationNodeFactory","createNativeGainNode","overwriteAccessors","getNativeContext","isNativeOfflineAudioContext","renderInputsOfAudioNode","createBiquadFilterNodeRenderer","createBiquadFilterNodeRendererFactory","connectAudioParam","createNativeBiquadFilterNode","getNativeAudioNode","renderAutomation","setAudioNodeTailTime","createSetAudioNodeTailTime","audioNodeTailTimeStore","biquadFilterNodeConstructor","createBiquadFilterNodeConstructor","createAudioParam","createInvalidAccessError","monitorConnections","createMonitorConnections","insertElementInSet","isNativeAudioNode","wrapChannelMergerNode","createWrapChannelMergerNode","createNativeChannelMergerNode","createNativeChannelMergerNodeFactory","nativeAudioContextConstructor","createChannelMergerNodeRenderer","createChannelMergerNodeRendererFactory","channelMergerNodeConstructor","createChannelMergerNodeConstructor","createChannelSplitterNodeRenderer","createChannelSplitterNodeRendererFactory","createNativeChannelSplitterNode","channelSplitterNodeConstructor","createChannelSplitterNodeConstructor","sanitizeChannelSplitterOptions","createNativeConstantSourceNodeFaker","createNativeConstantSourceNodeFakerFactory","addSilentConnection","createNativeAudioBufferSourceNode","createNativeConstantSourceNode","createNativeConstantSourceNodeFactory","cacheTestResult","testAudioScheduledSourceNodeStartMethodNegativeParametersSupport","testAudioScheduledSourceNodeStopMethodNegativeParametersSupport","createConstantSourceNodeRenderer","createConstantSourceNodeRendererFactory","constantSourceNodeConstructor","createConstantSourceNodeConstructor","wrapEventListener","createNativeConvolverNode","createNativeConvolverNodeFactory","createNotSupportedError","createConvolverNodeRenderer","createConvolverNodeRendererFactory","convolverNodeConstructor","createConvolverNodeConstructor","createDelayNodeRenderer","createDelayNodeRendererFactory","createNativeDelayNode","delayNodeConstructor","createDelayNodeConstructor","createNativeDynamicsCompressorNode","createNativeDynamicsCompressorNodeFactory","createDynamicsCompressorNodeRenderer","createDynamicsCompressorNodeRendererFactory","dynamicsCompressorNodeConstructor","createDynamicsCompressorNodeConstructor","createGainNodeRenderer","createGainNodeRendererFactory","gainNodeConstructor","createGainNodeConstructor","createNativeIIRFilterNodeFaker","createNativeIIRFilterNodeFakerFactory","createNativeScriptProcessorNode","renderNativeOfflineAudioContext","createRenderNativeOfflineAudioContext","createTestOfflineAudioContextCurrentTimeSupport","nativeOfflineAudioContextConstructor","createIIRFilterNodeRenderer","createIIRFilterNodeRendererFactory","createNativeIIRFilterNode","createNativeIIRFilterNodeFactory","iIRFilterNodeConstructor","createIIRFilterNodeConstructor","createAudioListener","createAudioListenerFactory","getFirstSample","unrenderedAudioWorkletNodeStore","minimalBaseAudioContextConstructor","createMinimalBaseAudioContextConstructor","eventTargetConstructor","createNativeOscillatorNode","createNativeOscillatorNodeFactory","testAudioScheduledSourceNodeStopMethodConsecutiveCallsSupport","wrapAudioScheduledSourceNodeStopMethodConsecutiveCalls","createOscillatorNodeRenderer","createOscillatorNodeRendererFactory","oscillatorNodeConstructor","createOscillatorNodeConstructor","createConnectedNativeAudioBufferSourceNode","createConnectedNativeAudioBufferSourceNodeFactory","createNativeWaveShaperNodeFaker","createNativeWaveShaperNodeFakerFactory","isDCCurve","createNativeWaveShaperNode","createNativeWaveShaperNodeFactory","createNativePannerNodeFaker","createNativePannerNodeFakerFactory","connectNativeAudioNodeToNativeAudioNode","disconnectNativeAudioNodeFromNativeAudioNode","createNativePannerNode","createNativePannerNodeFactory","createPannerNodeRenderer","createPannerNodeRendererFactory","pannerNodeConstructor","createPannerNodeConstructor","createNativePeriodicWave","createNativePeriodicWaveFactory","periodicWaveConstructor","createPeriodicWaveConstructor","sanitizePeriodicWaveOptions","nativeStereoPannerNodeFakerFactory","createNativeStereoPannerNodeFakerFactory","createNativeStereoPannerNode","createNativeStereoPannerNodeFactory","createStereoPannerNodeRenderer","createStereoPannerNodeRendererFactory","stereoPannerNodeConstructor","createStereoPannerNodeConstructor","createWaveShaperNodeRenderer","createWaveShaperNodeRendererFactory","waveShaperNodeConstructor","createWaveShaperNodeConstructor","isSecureContext","createIsSecureContext","window","exposeCurrentFrameAndCurrentTime","createExposeCurrentFrameAndCurrentTime","backupOfflineAudioContextStore","getOrCreateBackupOfflineAudioContext","createGetOrCreateBackupOfflineAudioContext","addAudioWorkletModule","createAddAudioWorkletModule","createEvaluateSource","createFetchSource","createAbortError","nativeAudioWorkletNodeConstructor","createTestAudioWorkletProcessorPostMessageSupport","isNativeContext","createIsNativeContext","isNativeAudioContext","decodeAudioData","createDecodeAudioData","audioBufferStore","createDataCloneError","createEncodingError","testAudioBufferCopyChannelMethodsOutOfBoundsSupport","testPromiseSupport","wrapAudioBufferCopyChannelMethods","wrapAudioBufferCopyChannelMethodsOutOfBounds","baseAudioContextConstructor","createBaseAudioContextConstructor","analyserNodeConstructor","audioBufferConstructor","audioBufferSourceNodeConstructor","mediaElementAudioSourceNodeConstructor","createMediaElementAudioSourceNodeConstructor","createNativeMediaElementAudioSourceNode","mediaStreamAudioDestinationNodeConstructor","createMediaStreamAudioDestinationNodeConstructor","createNativeMediaStreamAudioDestinationNode","mediaStreamAudioSourceNodeConstructor","createMediaStreamAudioSourceNodeConstructor","createNativeMediaStreamAudioSourceNode","createNativeMediaStreamTrackAudioSourceNode","createNativeMediaStreamTrackAudioSourceNodeFactory","mediaStreamTrackAudioSourceNodeConstructor","createMediaStreamTrackAudioSourceNodeConstructor","audioContextConstructor","createAudioContextConstructor","createUnknownError","getUnrenderedAudioWorkletNodes","createGetUnrenderedAudioWorkletNodes","unrenderedAudioWorkletNodeStore","addUnrenderedAudioWorkletNode","createAddUnrenderedAudioWorkletNode","connectMultipleOutputs","createConnectMultipleOutputs","createIndexSizeError","deleteUnrenderedAudioWorkletNode","createDeleteUnrenderedAudioWorkletNode","disconnectMultipleOutputs","createDisconnectMultipleOutputs","activeAudioWorkletNodeInputsStore","getActiveAudioWorkletNodeInputs","createGetActiveAudioWorkletNodeInputs","getValueForKey","createNativeAudioWorkletNodeFaker","createNativeAudioWorkletNodeFakerFactory","createInvalidStateError","createNativeChannelMergerNode","createNativeChannelSplitterNode","createNativeConstantSourceNode","createNativeGainNode","createNativeScriptProcessorNode","createNotSupportedError","exposeCurrentFrameAndCurrentTime","monitorConnections","createNativeAudioWorkletNode","createNativeAudioWorkletNodeFactory","createAudioWorkletNodeRenderer","createAudioWorkletNodeRendererFactory","connectAudioParam","createNativeAudioBufferSourceNode","getNativeAudioNode","nativeAudioWorkletNodeConstructor","nativeOfflineAudioContextConstructor","renderAutomation","renderInputsOfAudioNode","renderNativeOfflineAudioContext","getBackupOfflineAudioContext","createGetBackupOfflineAudioContext","backupOfflineAudioContextStore","setActiveAudioWorkletNodeInputs","createSetActiveAudioWorkletNodeInputs","audioWorkletNodeConstructor","isSecureContext","createAudioWorkletNodeConstructor","audioNodeConstructor","createAudioParam","getAudioNodeConnections","getNativeContext","isNativeOfflineAudioContext","sanitizeAudioWorkletNodeOptions","testAudioWorkletNodeOptionsClonability","wrapEventListener","minimalAudioContextConstructor","createMinimalAudioContextConstructor","createInvalidStateError","createNotSupportedError","createUnknownError","minimalBaseAudioContextConstructor","nativeAudioContextConstructor","createNativeOfflineAudioContext","createCreateNativeOfflineAudioContext","createNotSupportedError","nativeOfflineAudioContextConstructor","startRendering","createStartRendering","audioBufferStore","cacheTestResult","getAudioNodeRenderer","getUnrenderedAudioWorkletNodes","renderNativeOfflineAudioContext","testAudioBufferCopyChannelMethodsOutOfBoundsSupport","wrapAudioBufferCopyChannelMethods","wrapAudioBufferCopyChannelMethodsOutOfBounds","minimalOfflineAudioContextConstructor","createMinimalOfflineAudioContextConstructor","createInvalidStateError","minimalBaseAudioContextConstructor","offlineAudioContextConstructor","createOfflineAudioContextConstructor","baseAudioContextConstructor","cacheTestResult","createInvalidStateError","createNativeOfflineAudioContext","startRendering","isAnyAudioContext","createIsAnyAudioContext","CONTEXT_STORE","isNativeAudioContext","isAnyAudioNode","createIsAnyAudioNode","AUDIO_NODE_STORE","isNativeAudioNode","isAnyAudioParam","createIsAnyAudioParam","AUDIO_PARAM_STORE","isNativeAudioParam","isAnyOfflineAudioContext","createIsAnyOfflineAudioContext","isNativeOfflineAudioContext","isUndef","arg","isDefined","isFunction","isNumber","isObject","isBoolean","isArray","isString","isNote","assert","statement","error","assertRange","value","gte","lte","assertContextRunning","context","warn","isInsideScheduledCallback","printedScheduledWarning","enterScheduledCallback","insideCallback","assertUsedScheduleTime","time","isUndef","defaultLogger","log","args","defaultLogger","warn","createAudioContext","options","audioContextConstructor","createOfflineAudioContext","channels","length","sampleRate","offlineAudioContextConstructor","theWindow","hasAudioContext","createAudioWorkletNode","context","name","assert","isDefined","audioWorkletNodeConstructor","__decorate","decorators","target","key","desc","c","r","d","__awaiter","thisArg","_arguments","P","generator","adopt","value","resolve","reject","fulfilled","step","e","rejected","result","Ticker","callback","type","updateInterval","contextSampleRate","blob","blobUrl","worker","interval","_a","isAudioParam","arg","isAnyAudioParam","isAudioNode","isAnyAudioNode","isOfflineAudioContext","isAnyOfflineAudioContext","isAudioContext","isAnyAudioContext","isAudioBuffer","audioBufferConstructor","noCopy","key","arg","isAudioParam","isAudioNode","isAudioBuffer","deepMerge","target","sources","source","isObject","deepEquals","arrayA","arrayB","element","index","optionsFromArguments","defaults","argsArray","keys","objKey","opts","args","i","isDefined","getDefaultsFromInstance","instance","defaultArg","given","fallback","isUndef","omitFromObject","obj","omit","prop","Tone","args","theWindow","log","version","GT","a","b","GTE","EQ","LT","clamp","value","min","max","Timeline","_Timeline","Tone","options","optionsFromArguments","event","assert","lastValue","GTE","index","diff","time","param","len","after","EQ","i","beginning","end","midPoint","nextEvent","testEvent","LT","GT","callback","lowerBound","upperBound","startTime","endTime","notifyNewContext","onContextInit","cb","initializeContext","ctx","notifyCloseContext","onContextClose","closeContext","Emitter","_Emitter","Tone","event","callback","eventName","isUndef","boundCallback","args","eventList","i","len","constr","name","property","BaseContext","Emitter","Context","_Context","BaseContext","Timeline","options","optionsFromArguments","_a","createAudioContext","Ticker","_b","initializeContext","numberOfChannels","length","sampleRate","numberOfInputs","numberOfOutputs","maxDelayTime","feedForward","feedback","real","imag","constraints","stream","assert","isAudioContext","element","audioData","l","d","name","createAudioWorkletNode","url","isDefined","interval","type","time","closeContext","val","buffer","arr","i","constant","now","event","fn","timeout","id","intervalFn","DummyContext","BaseContext","_numberOfChannels","_length","_sampleRate","_numberOfInputs","_numberOfOutputs","_maxDelayTime","_feedForward","_feedback","_real","_imag","_constraints","_stream","_element","_audioData","_name","_options","_url","_fn","_timeout","_id","_interval","_val","_d","readOnly","target","property","isArray","str","writable","noOp","ToneAudioBuffer","_ToneAudioBuffer","Tone","noOp","options","optionsFromArguments","isString","getContext","buffer","url","doneLoading","audioBuffer","index","array","isMultidimensional","isArray","channels","len","context","multiChannelArray","chanNum","isNumber","outputArray","numChannels","channel","channelArray","i","sample","ret","c","start","end","assert","startSamples","endSamples","length","retBuffer","rev","baseUrl","response","arrayBuffer","extensions","extension","OfflineContext","Context","isOfflineAudioContext","createOfflineAudioContext","asynchronous","index","yieldEvery","done","buffer","ToneAudioBuffer","dummyContext","DummyContext","globalContext","getContext","hasAudioContext","setContext","Context","context","disposeOld","isAudioContext","isOfflineAudioContext","OfflineContext","start","theWindow","prefix","version","printString","dbToGain","db","gainToDb","gain","intervalToFrequencyRatio","interval","A4","getA4","setA4","freq","ftom","frequency","ftomf","mtof","midi","TimeBaseClass","_TimeBaseClass","Tone","context","value","units","dot","numericValue","scalar","m","q","s","total","isUndef","isString","isObject","typeName","isDefined","quantity","time","expr","matching","freq","beats","seconds","ticks","type","TimeClass","_TimeClass","TimeBaseClass","capture","quantTo","subdiv","percent","subdivision","value","diff","time","testNotations","power","closest","closestSeconds","notation","notationSeconds","quarterTime","quarters","measures","sixteenths","sixteenthString","ftom","FrequencyClass","_FrequencyClass","TimeClass","getA4","freq","setA4","value","pitch","octave","noteNumber","noteToScaleIndex","m","q","s","total","interval","intervalToFrequencyRatio","intervals","ftom","log","scaleIndexToNote","quarterTime","quarters","ticks","beats","seconds","midi","mtof","frequency","TransportTimeClass","TimeClass","ToneWithContext","_ToneWithContext","Tone","options","optionsFromArguments","getContext","time","assertUsedScheduleTime","TimeClass","freq","FrequencyClass","TransportTimeClass","props","name","isUndef","defaults","getDefaultsFromInstance","attribute","member","isDefined","isArray","isNumber","isString","isBoolean","StateTimeline","Timeline","initial","time","event","state","options","assertRange","index","i","Param","_Param","ToneWithContext","options","optionsFromArguments","assert","isDefined","isAudioParam","Timeline","now","value","arg","type","assertRange","val","dbToGain","gainToDb","time","computedTime","numericValue","after","before","previous","previousVal","beforeValue","currentVal","endTime","EQ","rampTime","startTime","timeConstant","values","duration","scaling","startingValue","segTime","valueAtTime","param","previousEvent","nextEvent","subdivisions","event","input","t0","v0","v1","t","t1","ToneAudioNode","_ToneAudioNode","ToneWithContext","isDefined","isAudioParam","Param","node","isAudioNode","nodeList","options","assert","channelCount","props","channelCountMode","channelInterpretation","destination","outputNum","inputNum","connect","warn","disconnect","nodes","connectSeries","first","prev","current","srcNode","dstNode","outputNumber","inputNumber","Gain","_Gain","ToneAudioNode","options","optionsFromArguments","Param","readOnly","OneShotSource","ToneAudioNode","options","noOp","Gain","time","computedTime","gain","assert","fadeInTime","fadeOutTime","additionalTail","disposeCallback","ToneConstantSource","_ToneConstantSource","OneShotSource","options","optionsFromArguments","connect","Param","time","computedTime","Signal","_Signal","ToneAudioNode","options","optionsFromArguments","ToneConstantSource","destination","outputNum","inputNum","connectSignal","value","time","rampTime","startTime","timeConstant","values","duration","scaling","convert","overridden","param","signal","Param","isAudioParam","connect","TickParam","_TickParam","Param","options","optionsFromArguments","Timeline","value","time","constant","computedValue","prevEvent","segments","segTime","rampVal","computedTime","event","previousEvent","ticksUntilTime","computedVal","segmentDur","isUndef","val0","val1","onTheLineEvent","ticks","currentTick","tick","before","after","delta","k","sol1","sol2","when","duration","computedDuration","startTicks","val","m","currentVal","TickSignal","_TickSignal","Signal","options","optionsFromArguments","TickParam","ticks","when","duration","tick","time","m","TickSource","_TickSource","ToneWithContext","options","optionsFromArguments","StateTimeline","Timeline","TickSignal","readOnly","time","offset","computedTime","isDefined","event","stopEvent","memoizedEvent","tmpEvent","lastState","elapsedTicks","eventToMemoize","e","periodStartTime","offsetEvent","s","now","ticks","elapsedSeconds","tick","before","startTime","absoluteTicks","endTime","callback","lastStateEvent","error","maxStartTime","startTicks","ticksAtStart","diff","EQ","nextTickTime","Clock","_Clock","ToneWithContext","options","optionsFromArguments","noOp","StateTimeline","TickSource","readOnly","time","offset","assertContextRunning","computedTime","s","ticks","tick","before","when","currentTick","startTime","endTime","e","Emitter","Delay","_Delay","ToneAudioNode","options","optionsFromArguments","maxDelayInSeconds","Param","readOnly","Volume","_Volume","ToneAudioNode","options","optionsFromArguments","Gain","readOnly","mute","DestinationClass","_DestinationClass","ToneAudioNode","options","optionsFromArguments","Volume","Gain","connectSeries","mute","args","onContextInit","context","onContextClose","ListenerClass","ToneAudioNode","Param","onContextInit","context","onContextClose","ToneAudioBuffers","_ToneAudioBuffers","Tone","options","optionsFromArguments","name","url","noOp","assert","callback","_","buffer","onerror","isString","ToneAudioBuffer","TicksClass","TransportTimeClass","beats","seconds","ticks","DrawClass","ToneWithContext","Timeline","callback","time","after","now","event","onContextInit","context","onContextClose","IntervalTimeline","Tone","event","assert","isDefined","node","IntervalNode","results","after","replacement","balance","temp","parent","isLeftChild","pivotNode","time","max","i","callback","allNodes","low","high","point","TimelineValue","Tone","initialValue","Timeline","value","time","event","SignalOperator","_SignalOperator","ToneAudioNode","optionsFromArguments","destination","outputNum","inputNum","connectSignal","WaveShaper","_WaveShaper","SignalOperator","options","optionsFromArguments","isArray","isFunction","Signal","mapping","length","array","i","len","normalized","oversampling","isOverSampleType","str","assert","Pow","_Pow","SignalOperator","options","optionsFromArguments","WaveShaper","exponent","val","TransportEvent","_TransportEvent","transport","opts","options","noOp","time","tickDuration","TransportRepeatEvent","_TransportRepeatEvent","TransportEvent","transport","opts","options","time","LT","TicksClass","ticks","GT","TransportClass","_TransportClass","ToneWithContext","options","optionsFromArguments","TimelineValue","Timeline","IntervalTimeline","Clock","readOnly","tickTime","ticks","progress","amount","TicksClass","enterScheduledCallback","event","callback","time","TransportEvent","TransportTimeClass","interval","startTime","duration","TransportRepeatEvent","TimeClass","eventId","item","timeline","after","computedAfter","offset","offsetTicks","isDefined","timeSig","isArray","startPosition","endPosition","loop","subdivision","now","s","remainingTick","ppq","transportPos","remainingTicks","signal","ratio","source","sourceValue","nodes","scaleFactor","scaleBefore","Gain","reciprocal","Pow","scaleAfter","ratioSignal","i","syncedSignal","node","writable","Emitter","onContextInit","context","onContextClose","Source","ToneAudioNode","options","StateTimeline","noOp","Volume","readOnly","mute","time","offset","duration","computedTime","isUndef","assert","GT","event","defaultArg","sched","t","assertContextRunning","isDefined","stateEvent","startOffset","seconds","id","ToneBufferSource","_ToneBufferSource","OneShotSource","options","optionsFromArguments","connect","Param","ToneAudioBuffer","noOp","time","offset","duration","gain","assert","computedTime","defaultArg","computedOffset","loopEnd","loopStart","loopDuration","GTE","EQ","LT","isDefined","computedDur","buffer","loop","Noise","_Noise","Source","options","optionsFromArguments","type","assert","_noiseBuffers","now","rate","time","buffer","ToneBufferSource","BUFFER_LENGTH","NUM_CHANNELS","_noiseCache","channelNum","channel","lastOut","i","white","ToneAudioBuffer","b0","b1","b2","b3","b4","b5","b6","generateWaveform","instance","length","duration","context","OfflineContext","ToneOscillatorNode","_ToneOscillatorNode","OneShotSource","options","optionsFromArguments","connect","Param","readOnly","time","computedTime","periodicWave","type","Oscillator","_Oscillator","Source","options","optionsFromArguments","Signal","readOnly","time","computedTime","oscillator","ToneOscillatorNode","description","deepEquals","oscProps","type","isBasicType","cache","isDefined","partials","wave","real","imag","periodicWave","baseType","p","assertRange","partial","fullPartials","v","i","phase","periodicWaveSize","partialCount","n","piFactor","b","sum","len","maxValue","twoPi","testPositions","clamp","length","generateWaveform","AudioToGain","SignalOperator","WaveShaper","x","Multiply","_Multiply","Signal","options","optionsFromArguments","Gain","AMOscillator","_AMOscillator","Source","options","optionsFromArguments","AudioToGain","Gain","Oscillator","Multiply","readOnly","time","type","baseType","partialCount","phase","partials","length","generateWaveform","FMOscillator","_FMOscillator","Source","options","optionsFromArguments","Gain","Oscillator","Signal","Multiply","readOnly","time","type","baseType","partialCount","phase","partials","length","generateWaveform","PulseOscillator","_PulseOscillator","Source","options","optionsFromArguments","Gain","WaveShaper","val","Signal","Oscillator","readOnly","time","phase","type","length","generateWaveform","FatOscillator","_FatOscillator","Source","options","optionsFromArguments","Signal","readOnly","Oscillator","time","osc","iterator","i","type","spread","start","step","count","assertRange","noOp","phase","baseType","partials","partialCount","length","generateWaveform","PWMOscillator","_PWMOscillator","Source","options","optionsFromArguments","Multiply","PulseOscillator","Oscillator","readOnly","time","phase","length","generateWaveform","OmniOscillatorSourceMap","AMOscillator","FatOscillator","FMOscillator","Oscillator","PulseOscillator","PWMOscillator","OmniOscillator","_OmniOscillator","Source","options","optionsFromArguments","Signal","readOnly","time","prefix","p","type","partials","partialCount","props","oscType","OscConstructor","now","oldOsc","phase","sType","baseType","osc","sourceType","count","isNumber","spread","mType","isString","length","generateWaveform","Add","_Add","Signal","optionsFromArguments","Gain","connectSeries","Scale","_Scale","SignalOperator","options","optionsFromArguments","Multiply","Add","min","max","Zero","_Zero","SignalOperator","optionsFromArguments","Gain","connect","disconnect","LFO","_LFO","ToneAudioNode","options","optionsFromArguments","Param","Oscillator","Gain","Signal","Zero","AudioToGain","Scale","readOnly","time","min","max","type","partials","phase","val","currentMin","currentMax","node","outputNum","inputNum","connectSignal","range","min","max","valueMap","target","propertyKey","newValue","assertRange","timeRange","Player","_Player","Source","options","optionsFromArguments","ToneAudioBuffer","noOp","url","callback","source","time","offset","duration","startTime","defaultArg","computedOffset","origDuration","computedDuration","ToneBufferSource","isUndef","computedTime","_a","when","loopStart","loopEnd","assertRange","buffer","loop","stopEvent","rate","now","rev","__decorate","timeRange","GainToAudio","SignalOperator","WaveShaper","x","Envelope","_Envelope","ToneAudioNode","options","optionsFromArguments","Signal","curve","direction","isString","curveName","EnvelopeCurves","name","curveDef","isObject","isArray","time","velocity","attack","decay","currentValue","attackRate","i","decayValue","decayStart","release","assert","duration","after","destination","outputNumber","inputNumber","connectSignal","length","context","OfflineContext","attackPortion","envelopeDuration","sustainTime","totalDuration","clone","__decorate","timeRange","range","k","cosineCurve","rippleCurve","rippleCurveFreq","sineWave","stairsCurve","steps","sineCurve","bounceCurve","freq","val","invertCurve","out","j","reverseCurve","Instrument","_Instrument","ToneAudioNode","options","optionsFromArguments","time","Volume","readOnly","changed","method","timePosition","originalMethod","args","id","t","note","duration","velocity","computedTime","computedDuration","Monophonic","_Monophonic","Instrument","options","optionsFromArguments","noOp","note","time","velocity","seconds","computedTime","computedFrequency","FrequencyClass","portTime","__decorate","timeRange","AmplitudeEnvelope","_AmplitudeEnvelope","Envelope","optionsFromArguments","Gain","Synth","_Synth","Monophonic","options","optionsFromArguments","OmniOscillator","AmplitudeEnvelope","readOnly","omitFromObject","Envelope","ToneAudioNode","Source","time","velocity","computedAttack","computedDecay","ModulationSynth","_ModulationSynth","Monophonic","options","optionsFromArguments","Synth","Signal","Multiply","Gain","readOnly","omitFromObject","OmniOscillator","Source","Envelope","ToneAudioNode","time","velocity","BiquadFilter","_BiquadFilter","ToneAudioNode","options","optionsFromArguments","Param","type","assert","len","freqValues","i","freq","magValues","phaseValues","filterClone","Filter","_Filter","ToneAudioNode","options","optionsFromArguments","Gain","Signal","readOnly","type","assert","filter","rolloff","rolloffNum","isNumber","possibilities","cascadingCount","count","BiquadFilter","connectSeries","len","filterClone","totalResponse","val","i","writable","FMSynth","_FMSynth","ModulationSynth","options","optionsFromArguments","Multiply","MembraneSynth","_MembraneSynth","Synth","options","optionsFromArguments","readOnly","deepMerge","Monophonic","note","time","seconds","hertz","FrequencyClass","maxNote","__decorate","range","timeRange","NoiseSynth","_NoiseSynth","Instrument","options","optionsFromArguments","Noise","AmplitudeEnvelope","omitFromObject","Envelope","ToneAudioNode","Source","time","velocity","duration","workletContext","addToWorklet","classOrFunction","registerProcessor","name","classDesc","processor","getWorkletGlobalScope","ToneAudioWorklet","ToneAudioNode","options","noOp","blobUrl","getWorkletGlobalScope","name","toneAudioWorkletProcessor","addToWorklet","singleIOProcess","addToWorklet","delayLine","addToWorklet","workletName","feedbackCombFilter","registerProcessor","FeedbackCombFilter","_FeedbackCombFilter","ToneAudioWorklet","options","optionsFromArguments","Gain","Param","readOnly","workletName","ToneAudioNode","node","connectSeries","delayTime","feedback","OnePoleFilter","_OnePoleFilter","ToneAudioNode","options","optionsFromArguments","Gain","oldFilter","freq","t","a0","b1","fq","len","freqValues","i","magValues","phaseValues","LowpassCombFilter","_LowpassCombFilter","ToneAudioNode","options","optionsFromArguments","FeedbackCombFilter","OnePoleFilter","fq","PluckSynth","_PluckSynth","Instrument","options","optionsFromArguments","Noise","LowpassCombFilter","deepMerge","fq","note","time","freq","delayAmount","Sampler","_Sampler","Instrument","options","optionsFromArguments","urlMap","note","noteNumber","assert","isNote","isNumber","mid","FrequencyClass","ToneAudioBuffers","noOp","midi","interval","notes","time","velocity","midiFloat","ftomf","remainder","difference","closestNote","buffer","playbackRate","intervalToFrequencyRatio","source","ToneBufferSource","isArray","sources","index","computedTime","duration","d","url","callback","__decorate","timeRange","ToneEvent","_ToneEvent","ToneWithContext","options","optionsFromArguments","StateTimeline","noOp","after","event","duration","startTick","isNumber","nextEvent","TicksClass","interval","offset","prob","variation","time","ticks","previousEvent","rescheduleTime","defaultArg","isBoolean","loop","rate","loopEnd","loopStart","lastEvent","loopDuration","Loop","_Loop","ToneWithContext","options","optionsFromArguments","ToneEvent","noOp","time","interval","rate","variation","prob","mute","iters","CrossFade","_CrossFade","ToneAudioNode","options","optionsFromArguments","GainToAudio","Gain","Signal","readOnly","connect","Effect","ToneAudioNode","options","CrossFade","Gain","readOnly","effect","Panner","_Panner","ToneAudioNode","options","optionsFromArguments","Param","readOnly","workletName","bitCrusherWorklet","registerProcessor","Split","_Split","ToneAudioNode","options","optionsFromArguments","Merge","_Merge","ToneAudioNode","options","optionsFromArguments","combFilterTunings","combFilterDelayTimes","Reverb","_Reverb","Effect","options","optionsFromArguments","decayTime","assertRange","preDelayTime","time","previousReady","context","OfflineContext","noiseL","Noise","noiseR","merge","Merge","gainNode","Gain","renderPromise","noOp","Solo","_Solo","ToneAudioNode","options","optionsFromArguments","Gain","solo","instance","PanVol","_PanVol","ToneAudioNode","options","optionsFromArguments","Panner","Volume","readOnly","mute","Channel","_Channel","ToneAudioNode","options","optionsFromArguments","Solo","PanVol","readOnly","solo","mute","name","Gain","volume","bus","sendKnob","Panner3D","_Panner3D","ToneAudioNode","options","optionsFromArguments","Param","x","y","z","val","Compressor","_Compressor","ToneAudioNode","options","optionsFromArguments","Param","readOnly","Limiter","_Limiter","ToneAudioNode","options","optionsFromArguments","Compressor","readOnly","now","getContext","Transport","getContext","getTransport","Destination","Master","Listener","getContext","getListener","Draw","context","getContext","clamp","v","a","b","lerp","t","norm","fnv1a","str","h","i","SCALES","SCALE_NAMES","OCTAVES","BASE_MIDI","NOTE_TO_PC","PC_TO_NOTE","siteKey","hostname","h","fnv1a","root","scaleName","scale","parseKey","spec","m","note","degreeToMidi","degree","key","stepOffset","steps","idx","clamp","oct","pc","midiToFreq","stepInScale","midi","pcs","s","dir","i","midiToNoteName","modular_exports","__export","fmIndex","foldCurve","foldFromBorder","lfoFromCss","massBonusFromFontWeight","patchFrom","portamentoFromTransition","ribbonSteps","unisonFromMass","foldFromBorder","borderWidthPx","edge","drive","clamp","fmIndex","texture","unisonFromMass","mass","m","lfoFromCss","animationS","borderStyle","portamentoFromTransition","transitionS","massBonusFromFontWeight","weight","patchFrom","matter","visuals","foldCurve","samples","out","i","x","ribbonSteps","dxPx","vw","scaleLen","t","chroma_exports","__export","attackScaleFromWarmth","brightnessFromLuminance","chromaOf","modeFromPalette","pagePalette","parseCssColor","rgbToHsl","richnessFromSaturation","roomToneScaleFromWarmth","subBonusFromWarmth","tempoScaleFromWarmth","velocityFromLuminance","warmthFromHue","parseCssColor","css","m","clamp","rgbToHsl","r","g","b","max","min","l","d","s","h","warmthFromHue","raw","lerp","chromaOf","rgb","brightnessFromLuminance","velocityFromLuminance","attackScaleFromWarmth","w","subBonusFromWarmth","richnessFromSaturation","modeFromPalette","pal","pagePalette","bg","text","roomToneScaleFromWarmth","tempoScaleFromWarmth","pulse_exports","__export","DUCK_RECOVERY_MS","ECHO_MIN_AHEAD_S","ECHO_TRANSPOSE","ECHO_VELOCITY_SCALE","PHRASE_MAX_NOTES","PHRASE_MIN_NOTES","PHRASE_PROBABILITY","decayCount","duckFactor","echoGridS","nextGridOffset","phraseWindow","readingOrderKey","secondsPerBeat","strumStepS","tempoFromPage","tempoFromPage","elementCount","warmthScale","base","lerp","clamp","secondsPerBeat","bpm","nextGridOffset","phaseS","gridS","minAheadS","offset","strumStepS","ECHO_TRANSPOSE","ECHO_VELOCITY_SCALE","ECHO_MIN_AHEAD_S","echoGridS","DUCK_RECOVERY_MS","decayCount","count","dtMs","duckFactor","PHRASE_PROBABILITY","PHRASE_MIN_NOTES","PHRASE_MAX_NOTES","readingOrderKey","top","left","phraseWindow","n","len","progress","aurora","mono","paper","THEMES","resolveTheme","theme","STORAGE_KEY","isMutedPersisted","persistMuted","muted","mountGate","onToggle","host","shadow","btn","e","state","DEG","foaGains","azimuth","elevation","extent","s","cosEl","dir","unitVector","C","CUBE_LAYOUT","MAXRE_G0","MAXRE_G1","decodeMatrix","layout","M","dir","decodeGains","rows","g","r","IDENTITY","mul","a","b","out","c","rotationMatrix","yaw","pitch","roll","cy","sy","cp","sp","cr","sr","Rz","Ry","Rx","applyMat3","m","v","lookMatrix","yawRight","pitchUp","SPEAKER_RADIUS","AmbisonicBus","destination","decoderKind","Gain","inXYZ","r","row","c","g","IDENTITY","decodeMatrix","CUBE_LAYOUT","i","dir","sum","mw","mx","my","mz","panner","Panner3D","L","R","wL","wR","yL","yR","merge","Merge","m","rampS","n","SourceEncoder","bus","Gain","g","directGain","when","rampS","t","now","sphere_exports","__export","AZ_MAX","EL_MAX","directivityFromRoundness","extentFromSize","reflectionScaleFromViewport","sphereFromRect","AZ_MAX","DEG","EL_MAX","sphereFromRect","rect","vw","vh","tx","norm","ty","extentFromSize","sizeT","clamp","directivityFromRoundness","roundness","reflectionScaleFromViewport","DEFAULT_FACTORS","resolveFactors","partial","f","k","clamp","directGain","presence","lerp","roomGain","roomPresence","tailExtent","envelopment","tailLevel","warmthDb","warmth","brillianceDb","brilliance","directivityDirectGain","d","directivitySendScale","directivityFilterScale","ER_BASE_TIMES","ER_TAP_LEVELS","ER_DIRECTIONS","DEG","FoaRoom","bus","reverb","vw","factors","Gain","roomGain","scale","reflectionScaleFromViewport","t","delay","Delay","tap","enc","SourceEncoder","az","el","foaGains","Split","f","ext","tailExtent","level","tailLevel","d","i","n","AmbisonicBackend","room","decoderKind","vw","factors","resolveFactors","AmbisonicBus","FoaRoom","enc","SourceEncoder","send","Gain","sendColor","Filter","backend","profile","when","t","now","s","w","extent","clamp","g","foaGains","direct","directGain","directivityDirectGain","wetSend","directivitySendScale","roomGain","m","PannerBackend","panningModel","panner","Panner3D","dry","POINTER_YAW_MAX","DEG","POINTER_PITCH_MAX","TILT_YAW_MAX","TILT_PITCH_MAX","FieldRig","backend","mode","step","gy","clamp","gp","ny","lerp","np","lookMatrix","tx","ty","gamma","beta","yawRight","pitchUp","mapping_exports","__export","ROOM_HALF_H","ROOM_HALF_W","ambienceCutoffFromViewport","attackFromRoundness","brightnessTilt","cutoffFromDepth","degreeFromSize","durationFromElongation","panX","panY","pitchNudgeFromRoundness","qFromRoundness","reverbFromViewport","roundness","sendFromShadowBlur","sizeT","stepsFromHeadingLevel","stepsFromSiblingIndex","velocityFromDepth","velocityFromSize","waveFromRoundness","zBonusFromZIndex","zFromDepth","ROOM_HALF_W","ROOM_HALF_H","panX","rect","vw","norm","panY","vh","brightnessTilt","lerp","sizeT","a","A","degreeFromSize","t","velocityFromSize","roundness","radiusPx","half","clamp","waveFromRoundness","r","attackFromRoundness","qFromRoundness","pitchNudgeFromRoundness","durationFromElongation","e","sendFromShadowBlur","blurPx","zFromDepth","depth","cutoffFromDepth","velocityFromDepth","zBonusFromZIndex","z","stepsFromSiblingIndex","i","scaleLen","stepsFromHeadingLevel","level","reverbFromViewport","ambienceCutoffFromViewport","ListenerRig","mode","listener","getListener","step","gx","clamp","ROOM_HALF_W","gy","ROOM_HALF_H","lerp","tx","ty","gamma","beta","Room","opts","vw","factors","Limiter","Volume","Filter","brillianceDb","warmthDb","Gain","decay","wet","Reverb","f","clamp","reverbFromViewport","ambienceCutoffFromViewport","err","level","toneScale","Noise","dbToGain","now","hidden","muted","matter_exports","__export","PARTIAL_COUNT","airRushGain","breath","deriveMatter","detuneJitterCents","envelopeWeave","filterWeave","genPartials","glideS","reverbWeave","subShimmer","transient","deriveMatter","v","texture","clamp","PARTIAL_COUNT","genPartials","edge","elongation","richness","p","evenness","lerp","a","energy","k","amp","norm","i","transient","e","breath","detuneJitterCents","subShimmer","mass","m","glideS","envelopeWeave","filterWeave","reverbWeave","t","airRushGain","pxPerMs","HEADING","roleOf","el","aria","override","tag","type","domDepth","root","d","n","eligibleSiblingIndex","parent","i","sib","recipeFor","role","theme","isQuiet","NOTE_RE","pinnedMidi","spec","m","pcs","name","pc","sonicVar","cs","profileOf","env","key","vw","vh","html","reasons","r","rect","recipe","radiusRaw","radiusPx","opacity","shadowBlur","parseShadowBlur","zIndex","depth","pan","panX","panY","zFromDepth","zBonusFromZIndex","st","sizeT","degree","degreeFromSize","round","roundness","steps","stepsFromSiblingIndex","pitchNudgeFromRoundness","level","stepsFromHeadingLevel","pinned","midi","degreeToMidi","midiToNoteName","wave","waveFromRoundness","attack","attackFromRoundness","durationS","durationFromElongation","dir","sphereFromRect","extentOverride","sphere","extentFromSize","clamp","directivityFromRoundness","DEG","chroma","elementChroma","filterHz","cutoffFromDepth","brightnessTilt","directivityFilterScale","brightnessFromLuminance","velocityScale","velocityFromSize","velocityFromDepth","velocityFromLuminance","sonicMode","elongation","fontWeight","matter","deriveMatter","parseBackdropBlur","massBonusFromFontWeight","modVisuals","firstSeconds","patch","patchFrom","env0","envelopeWeave","sub0","subShimmer","voice","genPartials","richnessFromSaturation","transient","breath","subBonusFromWarmth","glideS","detuneJitterCents","attackScaleFromWarmth","filterWeave","reverbWeave","reverbSend","sendFromShadowBlur","midiToFreq","qFromRoundness","chromaOf","parseCssColor","probe","style","hops","rgb","list","first","v","boxShadow","max","part","lengths","ELIGIBLE_SELECTOR","MAX_TRACKED","Scanner","env","cb","entries","entry","was","el","muts","n","records","m","node","safeProfile","out","target","vw","vh","profileOf","err","FOLD_CURVE","foldCurve","MatterVoice","Gain","Oscillator","WaveShaper","Noise","Filter","AmplitudeEnvelope","LFO","dest","when","baseCutoffHz","v","jitter","glide","lfoOn","freqHz","glideS","subInterval","fmIndex","g","now","n","VoicePool","backend","maxVoices","clamp","now","lane","MatterVoice","kind","FMSynth","PluckSynth","MembraneSynth","NoiseSynth","Synth","synth","filter","Filter","out","candidate","oldestSameKind","oldestAny","victim","profile","velocity","when","raw","t","vel","baseCutoff","w","dur","mv","pluck","mem","fm","syn","err","l","voice","hz","glideS","tail","PREVIEW_ROLES","HOVER_THROTTLE_MS","SCROLL_SUPPRESS_MS","MOVE_FRESHNESS_MS","MAX_RESOLVE_HOPS","attachPointer","engine","lastHover","lastScrollT","lastMoveT","onMove","e","onScroll","withinHops","target","resolved","n","d","onOver","now","el","profile","DEDUPE_MS","attachActivate","engine","lastHit","activate","target","el","now","profile","children","ELIGIBLE_SELECTOR","c","r","onPointerDown","e","onClick","onChange","t","on","FILL_INTERVALS","attachKeyboard","engine","lastTick","lastPointerDownT","onPointerDown","onFocus","e","el","onKeydown","t","now","len","interval","attachScroll","engine","scrollQueued","lastY","lastT","onScroll","now","dt","v","airRushGain","resizeQueued","onResize","attachMotion","engine","lastShake","attached","onOrientation","e","onMotion","a","magnitude","now","listen","request","state","attachDrag","engine","session","onDown","e","el","p","onMove","dx","end","ROLE_CHANNEL","attachMidi","engine","nav","out","off","access","detail","d","note","vel","ch","Engine","userOpts","reduced","rootStyle","bodyStyle","pagePalette","chromaOf","parseCssColor","cssKey","key","parseKey","hashed","siteKey","mode","modeFromPalette","SCALES","resolveTheme","clamp","resolveFactors","isMutedPersisted","Scanner","el","cssTempo","tempoFromPage","tempoScaleFromWarmth","mountGate","start","r","err","getContext","attachPointer","attachActivate","attachKeyboard","attachScroll","attachDrag","attachMotion","attachMidi","onVis","getTransport","roomToneScaleFromWarmth","Loop","time","now","PHRASE_PROBABILITY","pool","x","a","b","readingOrderKey","PHRASE_MIN_NOTES","len","PHRASE_MAX_NOTES","scrollable","phraseWindow","step","secondsPerBeat","level","i","roomOpts","Room","decoderKind","AmbisonicBackend","FieldRig","VoicePool","PannerBackend","ListenerRig","target","profile","handle","glide","lastMidi","dxPx","midi","stepInScale","ribbonSteps","midiToFreq","partial","persistMuted","detach","velocity","articulation","when","transpose","decayCount","duckFactor","dir","base","second","offset","nextGridOffset","echoGridS","ECHO_MIN_AHEAD_S","ECHO_VELOCITY_SCALE","ECHO_TRANSPOSE","els","reverse","sorted","t0","strumStepS","candidates","byArea","inDomOrder","event","fn","detail","version","create","options","Engine","autoInit","script","opts","boot","engine","err"]}