Godot Engine – Multi-platform 2D and 3D game engine
web: Various fixes to the Sample audio driver
Fabio Alessandrellifb7c35615204
diff --git a/modules/mp3/audio_stream_mp3.cpp b/modules/mp3/audio_stream_mp3.cppindex cd38f59e249..1dc4ef52acb 100644--- a/modules/mp3/audio_stream_mp3.cpp+++ b/modules/mp3/audio_stream_mp3.cpp@@ -36,6 +36,7 @@#include "core/io/file_access.h"#include "core/object/class_db.h"+#include "servers/audio/audio_server.h"#include <thirdparty/dr_libs/dr_bridge.h>@@ -307,13 +308,13 @@ int AudioStreamMP3::get_bar_beats() const {}Ref<AudioSample> AudioStreamMP3::generate_sample() const {+ const int mix_rate = AudioServer::get_singleton()->get_mix_rate();Ref<AudioSample> sample;sample.instantiate();sample->stream = this;- sample->loop_mode = loop- ? AudioSample::LoopMode::LOOP_FORWARD- : AudioSample::LoopMode::LOOP_DISABLED;- sample->loop_begin = loop_offset;+ sample->loop_mode = loop ? AudioSample::LoopMode::LOOP_FORWARD : AudioSample::LoopMode::LOOP_DISABLED;+ sample->sample_rate = mix_rate;+ sample->loop_begin = Math::round(loop_offset * mix_rate);sample->loop_end = 0;return sample;}diff --git a/modules/vorbis/audio_stream_ogg_vorbis.cpp b/modules/vorbis/audio_stream_ogg_vorbis.cppindex 036476f011c..3535062f177 100644--- a/modules/vorbis/audio_stream_ogg_vorbis.cpp+++ b/modules/vorbis/audio_stream_ogg_vorbis.cpp@@ -33,6 +33,7 @@#include "core/io/file_access.h"#include "core/object/class_db.h"#include "core/templates/rb_map.h"+#include "servers/audio/audio_server.h"#include <ogg/ogg.h>@@ -563,13 +564,13 @@ void AudioStreamOggVorbis::get_parameter_list(List<Parameter> *r_parameters) {}Ref<AudioSample> AudioStreamOggVorbis::generate_sample() const {+ const int mix_rate = AudioServer::get_singleton()->get_mix_rate();Ref<AudioSample> sample;sample.instantiate();sample->stream = this;- sample->loop_mode = loop- ? AudioSample::LoopMode::LOOP_FORWARD- : AudioSample::LoopMode::LOOP_DISABLED;- sample->loop_begin = loop_offset;+ sample->loop_mode = loop ? AudioSample::LoopMode::LOOP_FORWARD : AudioSample::LoopMode::LOOP_DISABLED;+ sample->sample_rate = mix_rate;+ sample->loop_begin = Math::round(loop_offset * mix_rate);sample->loop_end = 0;return sample;}diff --git a/platform/web/audio_driver_web.cpp b/platform/web/audio_driver_web.cppindex 38e083fa821..3fc102e8e6d 100644--- a/platform/web/audio_driver_web.cpp+++ b/platform/web/audio_driver_web.cpp@@ -253,13 +253,22 @@ void AudioDriverWeb::register_sample(const Ref<AudioSample> &p_sample) {data_ptrw[i + frames_total] = frames[i].right;}+ // Adjust loop start/end to match mix rate.+ const int sample_rate = p_sample->sample_rate;+ int loop_begin = p_sample->loop_begin;+ int loop_end = p_sample->loop_end;+ if (sample_rate != mix_rate) {+ loop_begin = Math::round(loop_begin * (float(mix_rate) / sample_rate));+ loop_end = Math::round(loop_end * (float(mix_rate) / sample_rate));+ }+godot_audio_sample_register_stream(itos(p_sample->stream->get_instance_id()).utf8().get_data(),data_ptrw,frames_total,loop_mode.utf8().get_data(),- p_sample->loop_begin,- p_sample->loop_end);+ loop_begin,+ loop_end);}void AudioDriverWeb::unregister_sample(const Ref<AudioSample> &p_sample) {diff --git a/platform/web/js/engine/features.js b/platform/web/js/engine/features.jsindex 12d8ac9113c..95debed1ca5 100644--- a/platform/web/js/engine/features.js+++ b/platform/web/js/engine/features.js@@ -88,11 +88,11 @@ const Features = {if (!Features.isFetchAvailable()) {missing.push('Fetch - Check web browser version');}- if (!Features.isSecureContext()) {- missing.push('Secure Context - Check web server configuration (use HTTPS)');- }if (supportsThreads) {+ if (!Features.isSecureContext()) {+ missing.push('Secure Context - Check web server configuration (use HTTPS)');+ }if (!Features.isCrossOriginIsolated()) {missing.push('Cross-Origin Isolation - Check that the web server configuration sends the correct headers.');}diff --git a/platform/web/js/libs/audio.position.worklet.js b/platform/web/js/libs/audio.position.worklet.jsindex 4e512c1e3c9..e0c6576e38b 100644--- a/platform/web/js/libs/audio.position.worklet.js+++ b/platform/web/js/libs/audio.position.worklet.js@@ -32,33 +32,30 @@ class GodotPositionReportingProcessor extends AudioWorkletProcessor {static get parameterDescriptors() {return [{- name: 'reset',+ name: 'id',defaultValue: 0,minValue: 0,- maxValue: 1,+ maxValue: 16777215,+ automationRate: 'k-rate',+ },+ {+ name: 'scale',+ defaultValue: 1,+ minValue: 0,+ maxValue: 4,automationRate: 'k-rate',},];}- constructor(...args) {- super(...args);- this.position = 0;- }-process(inputs, _outputs, parameters) {- if (parameters['reset'][0] > 0) {- this.position = 0;- }-if (inputs.length > 0) {const input = inputs[0];if (input.length > 0) {- this.position += input[0].length;- this.port.postMessage({ type: 'position', data: this.position });+ const size = input[0].length * parameters['scale'][0];+ this.port.postMessage([parameters['id'][0], size]);}}-return true;}}diff --git a/platform/web/js/libs/library_godot_audio.js b/platform/web/js/libs/library_godot_audio.jsindex d1c996efe46..52cbba7ed31 100644--- a/platform/web/js/libs/library_godot_audio.js+++ b/platform/web/js/libs/library_godot_audio.js@@ -28,1219 +28,629 @@/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *//**************************************************************************/-/**- * @typedef { "disabled" | "forward" | "backward" | "pingpong" } LoopMode- */--/**- * @typedef {{- * id: string- * audioBuffer: AudioBuffer- * }} SampleParams- * @typedef {{- * numberOfChannels?: number- * sampleRate?: number- * loopMode?: LoopMode- * loopBegin?: number- * loopEnd?: number- * }} SampleOptions- */--/**- * Represents a sample, memory-wise.- * @class- */-class Sample {- /**- * Returns a `Sample`.- * @param {string} id Id of the `Sample` to get.- * @returns {Sample}- * @throws {ReferenceError} When no `Sample` is found- */- static getSample(id) {- if (!GodotAudio.samples.has(id)) {- throw new ReferenceError(`Could not find sample "${id}"`);- }- return GodotAudio.samples.get(id);- }-- /**- * Returns a `Sample` or `null`, if it doesn't exist.- * @param {string} id Id of the `Sample` to get.- * @returns {Sample?}- */- static getSampleOrNull(id) {- return GodotAudio.samples.get(id) ?? null;- }-- /**- * Creates a `Sample` based on the params. Will register it to the- * `GodotAudio.samples` registry.- * @param {SampleParams} params Base params- * @param {SampleOptions | undefined} options Optional params.- * @returns {Sample}- */- static create(params, options = {}) {- const sample = new GodotAudio.Sample(params, options);- GodotAudio.samples.set(params.id, sample);- return sample;- }-- /**- * Deletes a `Sample` based on the id.- * @param {string} id `Sample` id to delete- * @returns {void}- */- static delete(id) {- GodotAudio.samples.delete(id);- }-- /**- * `Sample` constructor.- * @param {SampleParams} params Base params- * @param {SampleOptions | undefined} options Optional params.- */- constructor(params, options = {}) {- /** @type {string} */- this.id = params.id;- /** @type {AudioBuffer} */- this._audioBuffer = null;- /** @type {number} */- this.numberOfChannels = options.numberOfChannels ?? 2;- /** @type {number} */- this.sampleRate = options.sampleRate ?? 44100;- /** @type {LoopMode} */- this.loopMode = options.loopMode ?? 'disabled';- /** @type {number} */- this.loopBegin = options.loopBegin ?? 0;- /** @type {number} */- this.loopEnd = options.loopEnd ?? 0;-- this.setAudioBuffer(params.audioBuffer);- }-- /**- * Gets the audio buffer of the sample.- * @returns {AudioBuffer}- */- getAudioBuffer() {- return this._duplicateAudioBuffer();- }-- /**- * Sets the audio buffer of the sample.- * @param {AudioBuffer} val The audio buffer to set.- * @returns {void}- */- setAudioBuffer(val) {- this._audioBuffer = val;- }-- /**- * Clears the current sample.- * @returns {void}- */- clear() {- this.setAudioBuffer(null);- GodotAudio.Sample.delete(this.id);- }-- /**- * Returns a duplicate of the stored audio buffer.- * @returns {AudioBuffer}- */- _duplicateAudioBuffer() {- if (this._audioBuffer == null) {- throw new Error('couldn\'t duplicate a null audioBuffer');- }- /** @type {Array<Float32Array>} */- const channels = new Array(this._audioBuffer.numberOfChannels);- for (let i = 0; i < this._audioBuffer.numberOfChannels; i++) {- const channel = new Float32Array(this._audioBuffer.getChannelData(i));- channels[i] = channel;- }- const buffer = GodotAudio.ctx.createBuffer(- this.numberOfChannels,- this._audioBuffer.length,- this._audioBuffer.sampleRate- );- for (let i = 0; i < channels.length; i++) {- buffer.copyToChannel(channels[i], i, 0);- }- return buffer;- }-}--/**- * Represents a `SampleNode` linked to a `Bus`.- * @class- */-class SampleNodeBus {- /**- * Creates a new `SampleNodeBus`.- * @param {Bus} bus The bus related to the new `SampleNodeBus`.- * @returns {SampleNodeBus}- */- static create(bus) {- return new GodotAudio.SampleNodeBus(bus);- }-- /**- * `SampleNodeBus` constructor.- * @param {Bus} bus The bus related to the new `SampleNodeBus`.- */- constructor(bus) {- const NUMBER_OF_WEB_CHANNELS = 6;-- /** @type {Bus} */- this._bus = bus;-- /** @type {ChannelSplitterNode} */- this._channelSplitter = GodotAudio.ctx.createChannelSplitter(NUMBER_OF_WEB_CHANNELS);- /** @type {GainNode} */- this._l = GodotAudio.ctx.createGain();- /** @type {GainNode} */- this._r = GodotAudio.ctx.createGain();- /** @type {GainNode} */- this._sl = GodotAudio.ctx.createGain();- /** @type {GainNode} */- this._sr = GodotAudio.ctx.createGain();- /** @type {GainNode} */- this._c = GodotAudio.ctx.createGain();- /** @type {GainNode} */- this._lfe = GodotAudio.ctx.createGain();- /** @type {ChannelMergerNode} */- this._channelMerger = GodotAudio.ctx.createChannelMerger(NUMBER_OF_WEB_CHANNELS);-- this._channelSplitter- .connect(this._l, GodotAudio.WebChannel.CHANNEL_L)- .connect(- this._channelMerger,- GodotAudio.WebChannel.CHANNEL_L,- GodotAudio.WebChannel.CHANNEL_L- );- this._channelSplitter- .connect(this._r, GodotAudio.WebChannel.CHANNEL_R)- .connect(- this._channelMerger,- GodotAudio.WebChannel.CHANNEL_L,- GodotAudio.WebChannel.CHANNEL_R- );- this._channelSplitter- .connect(this._sl, GodotAudio.WebChannel.CHANNEL_SL)- .connect(- this._channelMerger,- GodotAudio.WebChannel.CHANNEL_L,- GodotAudio.WebChannel.CHANNEL_SL- );- this._channelSplitter- .connect(this._sr, GodotAudio.WebChannel.CHANNEL_SR)- .connect(- this._channelMerger,- GodotAudio.WebChannel.CHANNEL_L,- GodotAudio.WebChannel.CHANNEL_SR- );- this._channelSplitter- .connect(this._c, GodotAudio.WebChannel.CHANNEL_C)- .connect(- this._channelMerger,- GodotAudio.WebChannel.CHANNEL_L,- GodotAudio.WebChannel.CHANNEL_C- );- this._channelSplitter- .connect(this._lfe, GodotAudio.WebChannel.CHANNEL_L)- .connect(- this._channelMerger,- GodotAudio.WebChannel.CHANNEL_L,- GodotAudio.WebChannel.CHANNEL_LFE- );-- this._channelMerger.connect(this._bus.getInputNode());- }-- /**- * Returns the input node.- * @returns {AudioNode}- */- getInputNode() {- return this._channelSplitter;- }-- /**- * Returns the output node.- * @returns {AudioNode}- */- getOutputNode() {- return this._channelMerger;- }-- /**- * Sets the volume for each (split) channel.- * @param {Float32Array} volume Volume array from the engine for each channel.- * @returns {void}- */- setVolume(volume) {- if (volume.length !== GodotAudio.MAX_VOLUME_CHANNELS) {- throw new Error(- `Volume length isn't "${GodotAudio.MAX_VOLUME_CHANNELS}", is ${volume.length} instead`- );- }- this._l.gain.value = volume[GodotAudio.GodotChannel.CHANNEL_L] ?? 0;- this._r.gain.value = volume[GodotAudio.GodotChannel.CHANNEL_R] ?? 0;- this._sl.gain.value = volume[GodotAudio.GodotChannel.CHANNEL_SL] ?? 0;- this._sr.gain.value = volume[GodotAudio.GodotChannel.CHANNEL_SR] ?? 0;- this._c.gain.value = volume[GodotAudio.GodotChannel.CHANNEL_C] ?? 0;- this._lfe.gain.value = volume[GodotAudio.GodotChannel.CHANNEL_LFE] ?? 0;- }-- /**- * Clears the current `SampleNodeBus` instance.- * @returns {void}- */- clear() {- this._bus = null;- this._channelSplitter.disconnect();- this._channelSplitter = null;- this._l.disconnect();- this._l = null;- this._r.disconnect();- this._r = null;- this._sl.disconnect();- this._sl = null;- this._sr.disconnect();- this._sr = null;- this._c.disconnect();- this._c = null;- this._lfe.disconnect();- this._lfe = null;- this._channelMerger.disconnect();- this._channelMerger = null;- }-}--/**- * @typedef {{- * id: string- * streamObjectId: string- * busIndex: number- * }} SampleNodeParams- * @typedef {{- * offset?: number- * playbackRate?: number- * startTime?: number- * pitchScale?: number- * loopMode?: LoopMode- * volume?: Float32Array- * start?: boolean- * }} SampleNodeOptions- */--/**- * Represents an `AudioNode` of a `Sample`.- * @class- */-class SampleNode {- /**- * Returns a `SampleNode`.- * @param {string} id Id of the `SampleNode`.- * @returns {SampleNode}- * @throws {ReferenceError} When no `SampleNode` is not found- */- static getSampleNode(id) {- if (!GodotAudio.sampleNodes.has(id)) {- throw new ReferenceError(`Could not find sample node "${id}"`);- }- return GodotAudio.sampleNodes.get(id);- }-- /**- * Returns a `SampleNode`, returns null if not found.- * @param {string} id Id of the SampleNode.- * @returns {SampleNode?}- */- static getSampleNodeOrNull(id) {- return GodotAudio.sampleNodes.get(id) ?? null;- }-- /**- * Stops a `SampleNode` by id.- * @param {string} id Id of the `SampleNode` to stop.- * @returns {void}- */- static stopSampleNode(id) {- const sampleNode = GodotAudio.SampleNode.getSampleNodeOrNull(id);- if (sampleNode == null) {- return;- }- sampleNode.stop();- }-- /**- * Pauses the `SampleNode` by id.- * @param {string} id Id of the `SampleNode` to pause.- * @param {boolean} enable State of the pause- * @returns {void}- */- static pauseSampleNode(id, enable) {- const sampleNode = GodotAudio.SampleNode.getSampleNodeOrNull(id);- if (sampleNode == null) {- return;- }- sampleNode.pause(enable);- }-- /**- * Creates a `SampleNode` based on the params. Will register the `SampleNode` to- * the `GodotAudio.sampleNodes` regisery.- * @param {SampleNodeParams} params Base params.- * @param {SampleNodeOptions | undefined} options Optional params.- * @returns {SampleNode}- */- static create(params, options = {}) {- const sampleNode = new GodotAudio.SampleNode(params, options);- GodotAudio.sampleNodes.set(params.id, sampleNode);- return sampleNode;+function GodotSampleDriver(audioContext, positionWorkletPath) {+ /** @type {?AudioContext} */+ let ctx = audioContext;+ /** @type {?Promise} */+ let audioPositionWorkletPromise = ctx.audioWorklet ? ctx.audioWorklet.addModule(positionWorkletPath) : null;+ /** @type {!Array<AudioWorkletNode>} */+ const audioPositionWorkletNodes = [];++ /** @enum {string} */+ const LoopMode = {+ DISABLED: 'disabled',+ FORWARD: 'forward',+ BACKWARD: 'backward',+ PINGPONG: 'pingpong',+ };+ const GodotChannel = Object.freeze({+ CHANNEL_L: 0,+ CHANNEL_R: 1,+ CHANNEL_C: 2,+ CHANNEL_LFE: 3,+ CHANNEL_SL: 4, // Surround left+ CHANNEL_SR: 5, // Surround right+ CHANNEL_SBL: 6, // Surround back left (7.1)+ CHANNEL_SBR: 7, // Surround back right (7.1)+ });+ const WebChannel = Object.freeze({+ CHANNEL_L: 0,+ CHANNEL_R: 1,+ CHANNEL_SL: 2,+ CHANNEL_SR: 3,+ CHANNEL_C: 4,+ CHANNEL_LFE: 5,+ });+ const MAX_VOLUME_CHANNELS = 8;+ const NUMBER_OF_WEB_CHANNELS = Object.keys(WebChannel).length;+ const MAX_SAFE_FLOAT32_INTEGER = 16777215;+ /**+ * JS pair of a Godot AudioBus.+ * @typedef {{+ * getId: function(): number,+ * getInputNode: function(): !AudioNode,+ * getOutputNode: function(): !AudioNode,+ * setVolumeDb: function (GodotBus?): void,+ * setSend: function(GodotBus?): void,+ * setMute: function(boolean): void,+ * setSoloMute: function(boolean): void,+ * clear: function(): void,+ * }}+ */+ var GodotBus; // eslint-disable-line no-var, no-unassigned-vars+ /**+ * A mixing sub-graph to control GodotPlayback volume outputs to a GodotBus.+ * @typedef {{+ * setVolume: function(!Float32Array): void,+ * getInputNode: function(): !AudioNode,+ * getOutputNode: function(): !AudioNode,+ * clear: function(): void,+ * }}+ */+ var GodotVolumeMixer; // eslint-disable-line no-var, no-unassigned-vars+ /**+ * JS pair of a Godot AudioStream/AudioSample.+ * @typedef {{+ * loopBegin: number,+ * loopEnd: number,+ * loopMode: LoopMode,+ * length: number,+ * copyBuffer: function(): !AudioBuffer,+ * }}+ */+ var GodotStream; // eslint-disable-line no-var, no-unassigned-vars+ /**+ * JS pair of a Godot AudioStreamPlayback/AudioSamplePlayback.+ * @typedef {{+ * stop: function(): void,+ * start: function(number): void,+ * pause: function(boolean): void,+ * setVolumes: function(Array<number>, !Float32Array),+ * setPitchScale: function(number): void,+ * getPlaybackPosition: function(): number,+ * }}+ */+ var GodotPlayback; // eslint-disable-line no-var, no-unassigned-vars++ /** @type {GodotBus?} */+ let busSolo = null;+ /** @type {Array<GodotBus>} */+ let buses = [];+ /** @type {Map<string, GodotStream>} */+ const streams = new Map();+ /** @type {Map<string, GodotPlayback>} */+ const playbacks = new Map();++ /** @type {?function(number): void}*/+ let finishedCallback = null;++ /**+ * @param {?function(number): void} callback+ */+ function setFinishedCallback(callback) {+ finishedCallback = callback;+ }++ /**+ * @param {number} db+ * @return {number}+ */+ function db_to_linear(db) {+ return Math.exp(db * 0.11512925464970228420089957273422); // eslint-disable-line no-loss-of-precision+ }++ /**+ * @return {!GodotBus}+ */+ function createBus() {+ /** @type {!GainNode} */ const muteNode = ctx.createGain();+ /** @type {!GainNode} */ const gainNode = ctx.createGain();+ /** @type {!GainNode} */ const soloNode = ctx.createGain();+ gainNode.connect(soloNode).connect(muteNode);++ const bus = {};+ /** @return {!AudioNode} */ bus.getInputNode = () => gainNode;+ /** @return {!AudioNode} */ bus.getOutputNode = () => muteNode;+ /** @return {number} */+ bus.getId = function () {+ return buses.indexOf(bus);+ };+ /** @param {number} val */+ bus.setVolumeDb = function (val) {+ const linear = db_to_linear(val);+ if (isFinite(linear)) {+ gainNode.gain.value = linear;+ }+ };+ /** @param {?GodotBus} val */+ bus.setSend = function (val) {+ if (val == null) {+ if (bus.getId() != 0) {+ GodotRuntime.error(`Cannot set bus send to null when the bus not at index 0 (current index: ${bus.getId()})`);+ return;+ }+ bus.getOutputNode().connect(ctx.destination);+ } else {+ bus.getOutputNode().disconnect();+ bus.getOutputNode().connect(val.getInputNode());+ }+ };+ /** @param {boolean} enable */+ bus.setMute = function (enable) {+ muteNode.gain.value = enable ? 0 : 1;+ };+ /** @param {boolean} enable */+ bus.setSoloMute = function (enable) {+ soloNode.gain.value = enable ? 0 : 1;+ };+ bus.clear = function () {+ bus.getInputNode().disconnect();+ bus.getOutputNode().disconnect();+ };+ buses.push(bus);+ return bus;}-/**- * Deletes a `SampleNode` based on the id.- * @param {string} id Id of the `SampleNode` to delete.- * @returns {void}+ * @param {number} index+ * @return {?GodotBus}*/- static delete(id) {- GodotAudio.deleteSampleNode(id);+ function getBus(index) {+ return buses[index] ?? null;}/**- * @param {SampleNodeParams} params Base params- * @param {SampleNodeOptions | undefined} options Optional params.+ * @param {number} bus+ * @return {!GodotVolumeMixer}*/- constructor(params, options = {}) {- /** @type {string} */- this.id = params.id;- /** @type {string} */- this.streamObjectId = params.streamObjectId;- /** @type {number} */- this.offset = options.offset ?? 0;- /** @type {number} */- this._playbackPosition = options.offset;- /** @type {number} */- this.startTime = options.startTime ?? 0;- /** @type {boolean} */- this.isPaused = false;- /** @type {boolean} */- this.isStarted = false;- /** @type {boolean} */- this.isCanceled = false;- /** @type {number} */- this.pauseTime = 0;- /** @type {number} */- this._playbackRate = 44100;- /** @type {LoopMode} */- this.loopMode = options.loopMode ?? this.getSample().loopMode ?? 'disabled';- /** @type {number} */- this._pitchScale = options.pitchScale ?? 1;- /** @type {number} */- this._sourceStartTime = 0;- /** @type {Map<Bus, SampleNodeBus>} */- this._sampleNodeBuses = new Map();- /** @type {AudioBufferSourceNode | null} */- this._source = GodotAudio.ctx.createBufferSource();-- this._onended = null;- /** @type {AudioWorkletNode | null} */- this._positionWorklet = null;-- this.setPlaybackRate(options.playbackRate ?? 44100);- this._source.buffer = this.getSample().getAudioBuffer();-- this._addEndedListener();-- const bus = GodotAudio.Bus.getBus(params.busIndex);- const sampleNodeBus = this.getSampleNodeBus(bus);- sampleNodeBus.setVolume(options.volume);-- this.connectPositionWorklet(options.start).catch((err) => {- const newErr = new Error('Failed to create PositionWorklet.');- newErr.cause = err;- GodotRuntime.error(newErr);+ function createVolumeMixer(bus) {+ /** @type {!ChannelSplitterNode} */ const splitter = ctx.createChannelSplitter(NUMBER_OF_WEB_CHANNELS);+ /** @type {!Array<!GainNode>} */ const channels = [];+ /** @type {!ChannelMergerNode} */ const merger = ctx.createChannelMerger(NUMBER_OF_WEB_CHANNELS);+ Object.values(WebChannel).forEach((idx) => {+ const ch = ctx.createGain();+ splitter.connect(ch, idx).connect(merger, 0, idx);+ channels[idx] = ch;});+ merger.connect(getBus(bus).getInputNode());++ const node = {};+ /** @return {!AudioNode} */ node.getInputNode = () => splitter;+ /** @return {!AudioNode} */ node.getOutputNode = () => merger;+ /** @param {!Float32Array} volume */+ node.setVolume = function (volume) {+ if (volume.length !== MAX_VOLUME_CHANNELS) {+ GodotRuntime.error(`Volume length isn't "${MAX_VOLUME_CHANNELS}", is ${volume.length} instead`);+ return;+ }+ channels[WebChannel.CHANNEL_L].gain.value = volume[GodotChannel.CHANNEL_L] ?? 0;+ channels[WebChannel.CHANNEL_R].gain.value = volume[GodotChannel.CHANNEL_R] ?? 0;+ channels[WebChannel.CHANNEL_SL].gain.value = volume[GodotChannel.CHANNEL_SL] ?? 0;+ channels[WebChannel.CHANNEL_SR].gain.value = volume[GodotChannel.CHANNEL_SR] ?? 0;+ channels[WebChannel.CHANNEL_C].gain.value = volume[GodotChannel.CHANNEL_C] ?? 0;+ channels[WebChannel.CHANNEL_LFE].gain.value = volume[GodotChannel.CHANNEL_LFE] ?? 0;+ };+ node.clear = function () {+ splitter.disconnect();+ channels.forEach((ch) => {+ ch.disconnect();+ });+ merger.disconnect();+ };+ return node;+ }+ /**+ * @param {string} streamId+ * @param {!AudioBuffer} sourceBuffer+ * @param {{+ * loopMode: (LoopMode|undefined),+ * loopBegin: (number|undefined),+ * loopEnd: (number|undefined),+ * }=} options+ * @return {!GodotStream}+ */+ function createStream(streamId, sourceBuffer, options = {}) {+ const stream = {+ /** @type {LoopMode} */ loopMode: options.loopMode ?? LoopMode.DISABLED,+ /** @type {number} */ loopBegin: options.loopBegin ?? 0,+ /** @type {number} */ loopEnd: options.loopEnd ?? 0,+ /** @type {number} */ length: sourceBuffer.length,+ };+ /** @return {!AudioBuffer} */+ stream.copyBuffer = function () {+ const channels = new Array(sourceBuffer.numberOfChannels);+ for (let i = 0; i < sourceBuffer.numberOfChannels; i++) {+ channels[i] = new Float32Array(sourceBuffer.getChannelData(i));+ }+ const buffer = ctx.createBuffer(sourceBuffer.numberOfChannels, sourceBuffer.length, sourceBuffer.sampleRate);+ for (let i = 0; i < channels.length; i++) {+ buffer.copyToChannel(channels[i], i, 0);+ }+ return buffer;+ };+ streams.set(streamId, stream);+ return stream;}-- /**- * Gets the playback rate.- * @returns {number}- */- getPlaybackRate() {- return this._playbackRate;- }-- /**- * Gets the playback position.- * @returns {number}- */- getPlaybackPosition() {- return this._playbackPosition;- }-- /**- * Sets the playback rate.- * @param {number} val Value to set.- * @returns {void}- */- setPlaybackRate(val) {- this._playbackRate = val;- this._syncPlaybackRate();- }-- /**- * Gets the pitch scale.- * @returns {number}- */- getPitchScale() {- return this._pitchScale;- }-- /**- * Sets the pitch scale.- * @param {number} val Value to set.- * @returns {void}- */- setPitchScale(val) {- this._pitchScale = val;- this._syncPlaybackRate();- }-- /**- * Returns the linked `Sample`.- * @returns {Sample}- */- getSample() {- return GodotAudio.Sample.getSample(this.streamObjectId);- }-- /**- * Returns the output node.- * @returns {AudioNode}- */- getOutputNode() {- return this._source;- }-- /**- * Starts the `SampleNode`.- * @returns {void}- */- start() {- if (this.isStarted) {- return;- }- this._resetSourceStartTime();- this._source.start(this.startTime, this.offset);- this.isStarted = true;- }-- /**- * Stops the `SampleNode`.- * @returns {void}- */- stop() {- this.clear();- }-- /**- * Restarts the `SampleNode`.- */- restart() {- this.isPaused = false;- this.pauseTime = 0;- this._resetSourceStartTime();- this._restart();- }-/**- * Pauses the `SampleNode`.- * @param {boolean} [enable=true] State of the pause.- * @returns {void}+ * @param {string} id+ * @return {!GodotStream}*/- pause(enable = true) {- if (enable) {- this._pause();- return;- }-- this._unpause();+ function getStream(id) {+ return streams.get(id) ?? null;}-- /**- * Connects an AudioNode to the output node of this `SampleNode`.- * @param {AudioNode} node AudioNode to connect.- * @returns {void}- */- connect(node) {- return this.getOutputNode().connect(node);+ /** @param {string} id */+ function removeStream(id) {+ streams.delete(id);}/**- * Sets the volumes of the `SampleNode` for each buses passed in parameters.- * @param {Array<Bus>} buses- * @param {Float32Array} volumes+ * @param {string} playbackId+ * @return {!GodotPlayback}*/- setVolumes(buses, volumes) {- for (let busIdx = 0; busIdx < buses.length; busIdx++) {- const sampleNodeBus = this.getSampleNodeBus(buses[busIdx]);- sampleNodeBus.setVolume(- volumes.slice(- busIdx * GodotAudio.MAX_VOLUME_CHANNELS,- (busIdx * GodotAudio.MAX_VOLUME_CHANNELS) + GodotAudio.MAX_VOLUME_CHANNELS- )- );+ function createPlayback(playbackId, streamId) {+ /** @type {number} */ const sampleRate = ctx.sampleRate;+ const output = /** @struct */ {+ /** @type {!Map<number, GodotVolumeMixer|null>} */+ mixers: new Map(),+ /** @type {!Float32Array} */+ volumes: new Float32Array(0),+ };+ const {+ /** @type {number} */ length,+ /** @type {LoopMode} */ loopMode,+ /** @type {number} */ loopBegin,+ /** @type {number} */ loopEnd,+ } = getStream(streamId);+ /** @type {boolean} */ const looping = loopMode !== LoopMode.DISABLED;+ /** @type {boolean} */ let started = false;+ /** @type {boolean} */ let paused = false;+ /** @type {number} */ let processed = 0;+ /** @type {number} */ let pitchScale = 1;+ /** @type {?AudioBufferSourceNode} */ let source = null;+ /** @type {?AudioWorkletNode} */ let worklet = null;+ /** @type {number} */ let workletId = 0;++ const node = {};+ function attachWorklet() {+ if (!source) {+ return; // Already stopped.+ }+ if (audioPositionWorkletNodes.length > 0) {+ worklet = audioPositionWorkletNodes.pop();+ } else {+ worklet = new AudioWorkletNode(/** @type {!AudioContext} */ (ctx), 'godot-position-reporting-processor');+ }+ const end = loopEnd ? Math.min(loopEnd, length) : length;+ worklet.port.onmessage = (event) => {+ const [id, data] = event.data;+ if (id != workletId) {+ return;+ }+ processed += data;+ if (processed > end) {+ processed -= end;+ if (looping) {+ processed += loopBegin;+ }+ }+ };+ worklet.parameters.get('id').setValueAtTime(workletId, ctx.currentTime);+ worklet.parameters.get('scale').setValueAtTime(pitchScale, ctx.currentTime);+ source.connect(worklet);}- }-- /**- * Returns the SampleNodeBus based on the bus in parameters.- * @param {Bus} bus Bus to get the SampleNodeBus from.- * @returns {SampleNodeBus}- */- getSampleNodeBus(bus) {- if (!this._sampleNodeBuses.has(bus)) {- const sampleNodeBus = GodotAudio.SampleNodeBus.create(bus);- this._sampleNodeBuses.set(bus, sampleNodeBus);- this._source.connect(sampleNodeBus.getInputNode());+ /** @param {!Array<number>} newBuses */+ function compareOutputs(newBuses) {+ const keys = Array.from(output.mixers.keys());+ if (keys.length != newBuses.length) {+ return false;+ }+ return newBuses.find((b) => !keys.includes(b)) === undefined;}- return this._sampleNodeBuses.get(bus);- }-- /**- * Sets up and connects the source to the GodotPositionReportingProcessor- * If the worklet module is not loaded in, it will be added- */- async connectPositionWorklet(start) {- await GodotAudio.audioPositionWorkletPromise;- if (this.isCanceled) {- return;+ /**+ * @param {!Array<number>} newBuses+ * @param {!Float32Array} volumes+ */+ function setVolumes(newBuses, volumes) {+ if (!compareOutputs(newBuses)) {+ for (const mixer of output.mixers.values()) {+ if (!mixer) {+ continue;+ }+ if (source) {+ source.disconnect(mixer.getInputNode());+ }+ mixer.clear();+ }+ output.mixers.clear();+ }+ output.volumes = volumes;+ for (let idx = 0; idx < newBuses.length; idx++) {+ const bus = newBuses[idx];+ let mixer = output.mixers.get(bus);+ if (!mixer) {+ mixer = createVolumeMixer(bus);+ if (source) {+ source.connect(mixer.getInputNode());+ }+ output.mixers.set(bus, mixer);+ }+ const size = MAX_VOLUME_CHANNELS;+ mixer.setVolume(volumes.slice(idx * size, (idx * size) + size));+ }}- this._source.connect(this.getPositionWorklet());- if (start) {- this.start();+ function clearSource() {+ if (source) {+ source.onended = null;+ source.stop();+ source.disconnect();+ source = null;+ }+ output.mixers.forEach(function (mixer, key, map) {+ if (mixer) {+ if (source) {+ source.disconnect(mixer.getInputNode());+ }+ mixer.clear();+ }+ map.set(key, null);+ });+ if (worklet) {+ worklet.disconnect();+ worklet.port.onmessage = null;+ audioPositionWorkletNodes.push(worklet);+ worklet = null;+ }+ started = false;+ paused = false;+ processed = 0;}- }-- /**- * Get a AudioWorkletProcessor- * @returns {AudioWorkletNode}- */- getPositionWorklet() {- if (this._positionWorklet != null) {- return this._positionWorklet;+ function createSource() {+ clearSource();++ // Source+ source = ctx.createBufferSource();+ source.buffer = getStream(streamId).copyBuffer();+ source.onended = (_) => {+ if (paused) {+ return;+ }+ node.stop();+ if (!finishedCallback) {+ playbacks.delete(playbackId); // Cleanup after ourselves.+ return;+ }+ const cstr = GodotRuntime.allocString(playbackId);+ finishedCallback(cstr);+ GodotRuntime.free(cstr);+ };+ if (looping) {+ source.loop = true;+ source.loopStart = loopBegin / sampleRate;+ source.loopEnd = (loopEnd ? loopEnd : length) / sampleRate;+ }+ node.setPitchScale(pitchScale);+ node.setVolumes(Array.from(output.mixers.keys()), output.volumes);++ // Worklet+ workletId = Math.floor(Math.random() * MAX_SAFE_FLOAT32_INTEGER);+ if (audioPositionWorkletPromise) { // Unavailable outside secure contexts.+ audioPositionWorkletPromise.then(attachWorklet).catch((err) => {+ const newErr = new Error('Failed to create PositionWorklet.');+ newErr.cause = err;+ GodotRuntime.error(newErr);+ });+ }}- if (GodotAudio.audioPositionWorkletNodes.length > 0) {- this._positionWorklet = GodotAudio.audioPositionWorkletNodes.pop();- } else {- this._positionWorklet = new AudioWorkletNode(- GodotAudio.ctx,- 'godot-position-reporting-processor'- );+ /** @param {number} startPosition */+ function start(startPosition) {+ if (started) {+ return;+ }+ createSource();+ processed = startPosition * sampleRate;+ source.start(0, startPosition);+ started = true;+ paused = false;}- this._playbackPosition = this.offset;- this._positionWorklet.port.onmessage = (event) => {- switch (event.data['type']) {- case 'position':- this._playbackPosition = (parseInt(event.data.data, 10) / this.getSample().sampleRate) + this.offset;- break;- default:- // Do nothing.+ /** @param {number} newPitchScale */+ function setPitchScale(newPitchScale) {+ pitchScale = newPitchScale;+ if (!source || paused) {+ return;+ }+ source.playbackRate.value = pitchScale;+ if (worklet) {+ worklet.parameters.get('scale').setValueAtTime(pitchScale, ctx.currentTime);}};-- const resetParameter = this._positionWorklet.parameters.get('reset');- resetParameter.setValueAtTime(1, GodotAudio.ctx.currentTime);- resetParameter.setValueAtTime(0, GodotAudio.ctx.currentTime + 1);-- return this._positionWorklet;- }-- /**- * Clears the `SampleNode`.- * @returns {void}- */- clear() {- this.isCanceled = true;- this.isPaused = false;- this.pauseTime = 0;-- if (this._source != null) {- this._source.removeEventListener('ended', this._onended);- this._onended = null;- if (this.isStarted) {- this._source.stop();+ /** @param {boolean} enable */+ function pause(enable) {+ if (paused == enable) {+ return;}- this._source.disconnect();- this._source = null;- }-- for (const sampleNodeBus of this._sampleNodeBuses.values()) {- sampleNodeBus.clear();- }- this._sampleNodeBuses.clear();-- if (this._positionWorklet) {- this._positionWorklet.disconnect();- this._positionWorklet.port.onmessage = null;- GodotAudio.audioPositionWorkletNodes.push(this._positionWorklet);- this._positionWorklet = null;- }-- GodotAudio.SampleNode.delete(this.id);- }-- /**- * Resets the source start time- * @returns {void}- */- _resetSourceStartTime() {- this._sourceStartTime = GodotAudio.ctx.currentTime;- }-- /**- * Syncs the `AudioNode` playback rate based on the `SampleNode` playback rate and pitch scale.- * @returns {void}- */- _syncPlaybackRate() {- this._source.playbackRate.value = this.getPlaybackRate() * this.getPitchScale();- }-- /**- * Restarts the `SampleNode`.- * Honors `isPaused` and `pauseTime`.- * @returns {void}- */- _restart() {- if (this._source != null) {- this._source.disconnect();- }- this._source = GodotAudio.ctx.createBufferSource();- this._source.buffer = this.getSample().getAudioBuffer();-- // Make sure that we connect the new source to the sample node bus.- for (const sampleNodeBus of this._sampleNodeBuses.values()) {- this.connect(sampleNodeBus.getInputNode());- }-- this._addEndedListener();- const pauseTime = this.isPaused- ? this.pauseTime- : 0;- if (this._positionWorklet != null) {- this._positionWorklet.port.postMessage({ type: 'clear' });- this._source.connect(this._positionWorklet);- }- this._source.start(this.startTime, this.offset + pauseTime);- this.isStarted = true;- }-- /**- * Pauses the `SampleNode`.- * @returns {void}- */- _pause() {- if (!this.isStarted) {- return;- }- this.isPaused = true;- this.pauseTime = (GodotAudio.ctx.currentTime - this._sourceStartTime) / this.getPlaybackRate();- this._source.stop();- }-- /**- * Unpauses the `SampleNode`.- * @returns {void}- */- _unpause() {- this._restart();- this.isPaused = false;- this.pauseTime = 0;- }-- /**- * Adds an "ended" listener to the source node to repeat it if necessary.- * @returns {void}- */- _addEndedListener() {- if (this._onended != null) {- this._source.removeEventListener('ended', this._onended);- }-- /** @type {SampleNode} */- // eslint-disable-next-line consistent-this- const self = this;- this._onended = (_) => {- if (self.isPaused) {+ paused = enable;+ if (!started || !source) {return;}-- switch (self.getSample().loopMode) {- case 'disabled':- self.stop();- break;- case 'forward':- case 'backward':- self.restart();- break;- default:- // do nothing+ if (enable) {+ source.playbackRate.value = 0;+ if (worklet) {+ worklet.parameters.get('scale').setValueAtTime(0, ctx.currentTime);+ }+ } else {+ setPitchScale(pitchScale);}};- this._source.addEventListener('ended', this._onended);- }-}--/**- * Collection of nodes to represents a Godot Engine audio bus.- * @class- */-class Bus {- /**- * Returns the number of registered buses.- * @returns {number}- */- static getCount() {- return GodotAudio.buses.length;+ /** @return {number} */+ function getPlaybackPosition() {+ return processed / sampleRate;+ }+ node.stop = clearSource;+ node.start = start;+ node.pause = pause;+ node.setVolumes = setVolumes;+ node.setPitchScale = setPitchScale;+ node.getPlaybackPosition = getPlaybackPosition;+ playbacks.set(playbackId, node);+ return node;+ }+ /**+ * @param {string} id+ * @return {?GodotPlayback}+ */+ function getPlayback(id) {+ return playbacks.get(id) ?? null;+ }+ /** @param {string} id */+ function removePlayback(id) {+ const playback = playbacks.get(id) ?? null;+ if (playback) {+ playback.stop();+ playbacks.delete(id);+ }}-- /**- * Sets the number of registered buses.- * Will delete buses if lower than the current number.- * @param {number} val Count of registered buses.- * @returns {void}- */- static setCount(val) {- const buses = GodotAudio.buses;- if (val === buses.length) {+ /** @param {number} count */+ function setBusCount(count) {+ if (count < 1) {+ GodotRuntime.error('Invalid bus index, driver bug');return;}-- if (val < buses.length) {+ if (count === buses.length) {+ return;+ }+ if (count < buses.length) {// TODO: what to do with nodes connected to the deleted buses?- const deletedBuses = buses.slice(val);+ const deletedBuses = buses.slice(count);for (let i = 0; i < deletedBuses.length; i++) {const deletedBus = deletedBuses[i];deletedBus.clear();- }- GodotAudio.buses = buses.slice(0, val);- return;- }-- for (let i = GodotAudio.buses.length; i < val; i++) {- GodotAudio.Bus.create();- }- }-- /**- * Returns a `Bus` based on it's index number.- * @param {number} index- * @returns {Bus}- * @throws {ReferenceError} If the index value is outside the registry.- */- static getBus(index) {- if (index < 0 || index >= GodotAudio.buses.length) {- throw new ReferenceError(`invalid bus index "${index}"`);- }- return GodotAudio.buses[index];- }-- /**- * Returns a `Bus` based on it's index number. Returns null if it doesn't exist.- * @param {number} index- * @returns {Bus?}- */- static getBusOrNull(index) {- if (index < 0 || index >= GodotAudio.buses.length) {- return null;- }- return GodotAudio.buses[index];- }-- /**- * Move a bus from an index to another.- * @param {number} fromIndex From index- * @param {number} toIndex To index- * @returns {void}- */- static move(fromIndex, toIndex) {- const movedBus = GodotAudio.Bus.getBusOrNull(fromIndex);- if (movedBus == null) {- return;- }- const buses = GodotAudio.buses.filter((_, i) => i !== fromIndex);- // Inserts at index.- buses.splice(toIndex - 1, 0, movedBus);- GodotAudio.buses = buses;- }-- /**- * Adds a new bus at the specified index.- * @param {number} index Index to add a new bus.- * @returns {void}- */- static addAt(index) {- const newBus = GodotAudio.Bus.create();- if (index !== newBus.getId()) {- GodotAudio.Bus.move(newBus.getId(), index);- }- }-- /**- * Creates a `Bus` and registers it.- * @returns {Bus}- */- static create() {- const newBus = new GodotAudio.Bus();- const isFirstBus = GodotAudio.buses.length === 0;- GodotAudio.buses.push(newBus);- if (isFirstBus) {- newBus.setSend(null);- } else {- newBus.setSend(GodotAudio.Bus.getBus(0));- }- return newBus;- }-- /**- * `Bus` constructor.- */- constructor() {- /** @type {Set<SampleNode>} */- this._sampleNodes = new Set();- /** @type {boolean} */- this.isSolo = false;- /** @type {Bus?} */- this._send = null;-- /** @type {GainNode} */- this._gainNode = GodotAudio.ctx.createGain();- /** @type {GainNode} */- this._soloNode = GodotAudio.ctx.createGain();- /** @type {GainNode} */- this._muteNode = GodotAudio.ctx.createGain();-- this._gainNode- .connect(this._soloNode)- .connect(this._muteNode);- }-- /**- * Returns the current id of the bus (its index).- * @returns {number}- */- getId() {- return GodotAudio.buses.indexOf(this);- }-- /**- * Returns the bus volume db value.- * @returns {number}- */- getVolumeDb() {- return GodotAudio.linear_to_db(this._gainNode.gain.value);- }-- /**- * Sets the bus volume db value.- * @param {number} val Value to set- * @returns {void}- */- setVolumeDb(val) {- const linear = GodotAudio.db_to_linear(val);- if (isFinite(linear)) {- this._gainNode.gain.value = linear;- }- }-- /**- * Returns the "send" bus.- * If null, this bus sends its contents directly to the output.- * If not null, this bus sends its contents to another bus.- * @returns {Bus?}- */- getSend() {- return this._send;- }-- /**- * Sets the "send" bus.- * If null, this bus sends its contents directly to the output.- * If not null, this bus sends its contents to another bus.- *- * **Note:** if null, `getId()` must be equal to 0. Otherwise, it will throw.- * @param {Bus?} val- * @returns {void}- * @throws {Error} When val is `null` and `getId()` isn't equal to 0- */- setSend(val) {- this._send = val;- if (val == null) {- if (this.getId() == 0) {- this.getOutputNode().connect(GodotAudio.ctx.destination);- return;- }- throw new Error(- `Cannot send to "${val}" without the bus being at index 0 (current index: ${this.getId()})`- );- }- this.connect(val);- }-- /**- * Returns the input node of the bus.- * @returns {AudioNode}- */- getInputNode() {- return this._gainNode;- }-- /**- * Returns the output node of the bus.- * @returns {AudioNode}- */- getOutputNode() {- return this._muteNode;- }-- /**- * Sets the mute status of the bus.- * @param {boolean} enable- */- mute(enable) {- this._muteNode.gain.value = enable ? 0 : 1;- }-- /**- * Sets the solo status of the bus.- * @param {boolean} enable- */- solo(enable) {- if (this.isSolo === enable) {+ }+ buses = buses.slice(0, count);return;}-- if (enable) {- if (GodotAudio.busSolo != null && GodotAudio.busSolo !== this) {- GodotAudio.busSolo._disableSolo();+ for (let i = buses.length; i < count; i++) {+ const bus = createBus();+ if (i === 0) {+ bus.setSend(null);+ } else {+ bus.setSend(getBus(0));}- this._enableSolo();- return;}-- this._disableSolo();- }-- /**- * Wrapper to simply add a sample node to the bus.- * @param {SampleNode} sampleNode `SampleNode` to remove- * @returns {void}- */- addSampleNode(sampleNode) {- this._sampleNodes.add(sampleNode);- sampleNode.getOutputNode().connect(this.getInputNode());- }-- /**- * Wrapper to simply remove a sample node from the bus.- * @param {SampleNode} sampleNode `SampleNode` to remove- * @returns {void}- */- removeSampleNode(sampleNode) {- this._sampleNodes.delete(sampleNode);- sampleNode.getOutputNode().disconnect();}-/**- * Wrapper to simply connect to another bus.- * @param {Bus} bus- * @returns {void}+ * @param {number} fromIndex+ * @param {number} toIndex*/- connect(bus) {- if (bus == null) {- throw new Error('cannot connect to null bus');+ function moveBus(fromIndex, toIndex) {+ if (fromIndex < 1 || toIndex < 1) {+ GodotRuntime.error('Invalid bus index, driver bug');+ return;}- this.getOutputNode().disconnect();- this.getOutputNode().connect(bus.getInputNode());- return bus;- }-- /**- * Clears the current bus.- * @returns {void}- */- clear() {- GodotAudio.buses = GodotAudio.buses.filter((v) => v !== this);+ const movedBus = getBus(fromIndex);+ if (!movedBus) {+ return;+ }+ const newBuses = buses.filter((_, i) => i !== fromIndex);+ // Inserts at index.+ newBuses.splice(toIndex - 1, 0, movedBus);+ buses = newBuses;}-- _syncSampleNodes() {- const sampleNodes = Array.from(this._sampleNodes);- for (let i = 0; i < sampleNodes.length; i++) {- const sampleNode = sampleNodes[i];- sampleNode.getOutputNode().disconnect();- sampleNode.getOutputNode().connect(this.getInputNode());+ /** @param {number} index */+ function addBusAt(index) {+ if (index < 1) {+ GodotRuntime.error('Invalid bus index, driver bug');+ return;+ }+ const bus = createBus();+ if (index !== bus.getId()) {+ moveBus(bus.getId(), index);+ }+ if (bus.getId() === 0) {+ bus.setSend(null);+ } else {+ bus.setSend(getBus(0));}}-- /**- * Process to enable solo.- * @returns {void}- */- _enableSolo() {- this.isSolo = true;- GodotAudio.busSolo = this;- this._soloNode.gain.value = 1;- const otherBuses = GodotAudio.buses.filter(- (otherBus) => otherBus !== this- );- for (let i = 0; i < otherBuses.length; i++) {- const otherBus = otherBuses[i];- otherBus._soloNode.gain.value = 0;+ /** @param {number} index */+ function removeBus(index) {+ if (index < 1) {+ GodotRuntime.error('Invalid bus index, driver bug');+ return;+ }+ const bus = getBus(index);+ if (!bus) {+ return;}+ bus.clear();+ buses = buses.filter((v) => v !== bus);}-/**- * Process to disable solo.- * @returns {void}+ * @param {number} busIndex+ * @param {boolean} enable*/- _disableSolo() {- this.isSolo = false;- GodotAudio.busSolo = null;- this._soloNode.gain.value = 1;- const otherBuses = GodotAudio.buses.filter(- (otherBus) => otherBus !== this- );- for (let i = 0; i < otherBuses.length; i++) {- const otherBus = otherBuses[i];- otherBus._soloNode.gain.value = 1;+ function setBusSolo(busIndex, enable) {+ const bus = getBus(busIndex);+ if (!bus) {+ return;+ }+ const current = busSolo;+ if (enable && current != bus) {+ busSolo = bus;+ bus.setSoloMute(false);+ buses.filter((o) => o !== bus).forEach((b) => {+ b.setSoloMute(true);+ });+ } else if (!enable && current == bus) {+ busSolo = null;+ buses.forEach((b) => {+ b.setSoloMute(false);+ });}}-}+ function clear() {+ audioPositionWorkletPromise = null;+ playbacks.forEach((p) => p.stop());+ playbacks.clear();+ streams.clear();+ buses.splice(0, buses.length).forEach((b) => b.clear());+ audioPositionWorkletNodes.splice(0, audioPositionWorkletNodes.length);+ ctx = null;+ }+ const driver = /** @struct */ {+ setFinishedCallback,+ clear,+ // Streams+ createStream,+ getStream,+ removeStream,+ // Playbacks+ createPlayback,+ getPlayback,+ removePlayback,+ // Buses+ getBus,+ setBusSolo,+ setBusCount,+ moveBus,+ addBusAt,+ removeBus,+ // So they survive pre-stripping.+ _: { GodotBus, GodotVolumeMixer, GodotStream, GodotPlayback },+ };+ return driver;+};const _GodotAudio = {$GodotAudio__deps: ['$GodotRuntime', '$GodotOS'],$GodotAudio: {- /**- * Max number of volume channels.- */- MAX_VOLUME_CHANNELS: 8,-- /**- * Represents the index of each sound channel relative to the engine.- */- GodotChannel: Object.freeze({- CHANNEL_L: 0,- CHANNEL_R: 1,- CHANNEL_C: 3,- CHANNEL_LFE: 4,- CHANNEL_RL: 5,- CHANNEL_RR: 6,- CHANNEL_SL: 7,- CHANNEL_SR: 8,- }),-- /**- * Represents the index of each sound channel relative to the Web Audio API.- */- WebChannel: Object.freeze({- CHANNEL_L: 0,- CHANNEL_R: 1,- CHANNEL_SL: 2,- CHANNEL_SR: 3,- CHANNEL_C: 4,- CHANNEL_LFE: 5,- }),-- // `Sample` class- /**- * Registry of `Sample`s.- * @type {Map<string, Sample>}- */- samples: null,- Sample,-- // `SampleNodeBus` class- SampleNodeBus,-- // `SampleNode` class- /**- * Registry of `SampleNode`s.- * @type {Map<string, SampleNode>}- */- sampleNodes: null,- SampleNode,- deleteSampleNode: (pSampleNodeId) => {- GodotAudio.sampleNodes.delete(pSampleNodeId);- if (GodotAudio.sampleFinishedCallback == null) {- return;- }- const sampleNodeIdPtr = GodotRuntime.allocString(pSampleNodeId);- GodotAudio.sampleFinishedCallback(sampleNodeIdPtr);- GodotRuntime.free(sampleNodeIdPtr);- },-- // `Bus` class- /**- * Registry of `Bus`es.- * @type {Array<Bus>}- */- buses: null,- /**- * Reference to the current bus in solo mode.- * @type {Bus | null}- */- busSolo: null,- Bus,-- /**- * Callback to signal that a sample has finished.- * @type {(playbackObjectIdPtr: number) => void | null}- */- sampleFinishedCallback: null,-/** @type {AudioContext} */ctx: null,input: null,driver: null,+ sample_driver: null,interval: 0,- /** @type {Promise} */- audioPositionWorkletPromise: null,- /** @type {Array<AudioWorkletNode>} */- audioPositionWorkletNodes: null,-- /**- * Converts linear volume to Db.- * @param {number} linear Linear value to convert.- * @returns {number}- */- linear_to_db: function (linear) {- // eslint-disable-next-line no-loss-of-precision- return Math.log(linear) * 8.6858896380650365530225783783321;- },- /**- * Converts Db volume to linear.- * @param {number} db Db value to convert.- * @returns {number}- */- db_to_linear: function (db) {- // eslint-disable-next-line no-loss-of-precision- return Math.exp(db * 0.11512925464970228420089957273422);- },-+ GodotSampleDriver,init: function (mix_rate, latency, onstatechange, onlatencyupdate) {- // Initialize classes static values.- GodotAudio.samples = new Map();- GodotAudio.sampleNodes = new Map();- GodotAudio.buses = [];- GodotAudio.busSolo = null;- GodotAudio.audioPositionWorkletNodes = [];-const opts = {};// If mix_rate is 0, let the browser choose.if (mix_rate) {@@ -1282,8 +692,9 @@ const _GodotAudio = {}, 1000);GodotOS.atexit(GodotAudio.close_async);+ // Initialize sample driver.const path = GodotConfig.locate_file('godot.audio.position.worklet.js');- GodotAudio.audioPositionWorkletPromise = ctx.audioWorklet.addModule(path);+ GodotAudio.sample_driver = GodotAudio.GodotSampleDriver(ctx, path);return ctx.destination.channelCount;},@@ -1331,6 +742,11 @@ const _GodotAudio = {resolve();return;}+ // Clear audio driver+ if (GodotAudio.sample_driver) {+ GodotAudio.sample_driver.clear();+ GodotAudio.sample_driver = null;+ }// Remove latency callbackif (GodotAudio.interval) {clearInterval(GodotAudio.interval);@@ -1357,183 +773,6 @@ const _GodotAudio = {resolve();});},-- /**- * Triggered when a sample node needs to start.- * @param {string} playbackObjectId The unique id of the sample playback- * @param {string} streamObjectId The unique id of the stream- * @param {number} busIndex Index of the bus currently binded to the sample playback- * @param {SampleNodeOptions | undefined} startOptions Optional params.- * @returns {void}- */- start_sample: function (- playbackObjectId,- streamObjectId,- busIndex,- startOptions- ) {- GodotAudio.SampleNode.stopSampleNode(playbackObjectId);- GodotAudio.SampleNode.create(- {- busIndex,- id: playbackObjectId,- streamObjectId,- },- startOptions- );- },-- /**- * Triggered when a sample node needs to be stopped.- * @param {string} playbackObjectId Id of the sample playback- * @returns {void}- */- stop_sample: function (playbackObjectId) {- GodotAudio.SampleNode.stopSampleNode(playbackObjectId);- },-- /**- * Triggered when a sample node needs to be paused or unpaused.- * @param {string} playbackObjectId Id of the sample playback- * @param {boolean} pause State of the pause- * @returns {void}- */- sample_set_pause: function (playbackObjectId, pause) {- GodotAudio.SampleNode.pauseSampleNode(playbackObjectId, pause);- },-- /**- * Triggered when a sample node needs its pitch scale to be updated.- * @param {string} playbackObjectId Id of the sample playback- * @param {number} pitchScale Pitch scale of the sample playback- * @returns {void}- */- update_sample_pitch_scale: function (playbackObjectId, pitchScale) {- const sampleNode = GodotAudio.SampleNode.getSampleNodeOrNull(playbackObjectId);- if (sampleNode == null) {- return;- }- sampleNode.setPitchScale(pitchScale);- },-- /**- * Triggered when a sample node volumes need to be updated.- * @param {string} playbackObjectId Id of the sample playback- * @param {Array<number>} busIndexes Indexes of the buses that need to be updated- * @param {Float32Array} volumes Array of the volumes- * @returns {void}- */- sample_set_volumes_linear: function (playbackObjectId, busIndexes, volumes) {- const sampleNode = GodotAudio.SampleNode.getSampleNodeOrNull(playbackObjectId);- if (sampleNode == null) {- return;- }- const buses = busIndexes.map((busIndex) => GodotAudio.Bus.getBus(busIndex));- sampleNode.setVolumes(buses, volumes);- },-- /**- * Triggered when the bus count changes.- * @param {number} count Number of buses- * @returns {void}- */- set_sample_bus_count: function (count) {- GodotAudio.Bus.setCount(count);- },-- /**- * Triggered when a bus needs to be removed.- * @param {number} index Bus index- * @returns {void}- */- remove_sample_bus: function (index) {- const bus = GodotAudio.Bus.getBusOrNull(index);- if (bus == null) {- return;- }- bus.clear();- },-- /**- * Triggered when a bus needs to be at the desired position.- * @param {number} atPos Position to add the bus- * @returns {void}- */- add_sample_bus: function (atPos) {- GodotAudio.Bus.addAt(atPos);- },-- /**- * Triggered when a bus needs to be moved.- * @param {number} busIndex Index of the bus to move- * @param {number} toPos Index of the new position of the bus- * @returns {void}- */- move_sample_bus: function (busIndex, toPos) {- GodotAudio.Bus.move(busIndex, toPos);- },-- /**- * Triggered when the "send" value of a bus changes.- * @param {number} busIndex Index of the bus to update the "send" value- * @param {number} sendIndex Index of the bus that is the new "send"- * @returns {void}- */- set_sample_bus_send: function (busIndex, sendIndex) {- const bus = GodotAudio.Bus.getBusOrNull(busIndex);- if (bus == null) {- // Cannot send from an invalid bus.- return;- }- let targetBus = GodotAudio.Bus.getBusOrNull(sendIndex);- if (targetBus == null) {- // Send to master.- targetBus = GodotAudio.Bus.getBus(0);- }- bus.setSend(targetBus);- },-- /**- * Triggered when a bus needs its volume db to be updated.- * @param {number} busIndex Index of the bus to update its volume db- * @param {number} volumeDb Volume of the bus- * @returns {void}- */- set_sample_bus_volume_db: function (busIndex, volumeDb) {- const bus = GodotAudio.Bus.getBusOrNull(busIndex);- if (bus == null) {- return;- }- bus.setVolumeDb(volumeDb);- },-- /**- * Triggered when a bus needs to update its solo status- * @param {number} busIndex Index of the bus to update its solo status- * @param {boolean} enable Status of the solo- * @returns {void}- */- set_sample_bus_solo: function (busIndex, enable) {- const bus = GodotAudio.Bus.getBusOrNull(busIndex);- if (bus == null) {- return;- }- bus.solo(enable);- },-- /**- * Triggered when a bus needs to update its mute status- * @param {number} busIndex Index of the bus to update its mute status- * @param {boolean} enable Status of the mute- * @returns {void}- */- set_sample_bus_mute: function (busIndex, enable) {- const bus = GodotAudio.Bus.getBusOrNull(busIndex);- if (bus == null) {- return;- }- bus.mute(enable);- },},godot_audio_is_available__sig: 'i',@@ -1606,342 +845,250 @@ const _GodotAudio = {GodotAudio.input = null;}},+};++autoAddDeps(_GodotAudio, '$GodotAudio');+mergeInto(LibraryManager.library, _GodotAudio);++/**+ * The audio sample driver used by AudioStreamPlayer with playback_type = Sample.+ */+const _GodotAudioSampleDriver = {+ $GodotAudioSampleDriver__deps: ['$GodotAudio', '$GodotRuntime'],+ $GodotAudioSampleDriver: {},godot_audio_sample_stream_is_registered__proxy: 'sync',godot_audio_sample_stream_is_registered__sig: 'ii',- /**- * Returns if the sample stream is registered- * @param {number} streamObjectIdStrPtr Pointer of the streamObjectId- * @returns {number}- */- godot_audio_sample_stream_is_registered: function (streamObjectIdStrPtr) {- const streamObjectId = GodotRuntime.parseString(streamObjectIdStrPtr);- return Number(GodotAudio.Sample.getSampleOrNull(streamObjectId) != null);+ godot_audio_sample_stream_is_registered: function (p_id) {+ if (!GodotAudio.sample_driver) {+ return 0;+ }+ return GodotAudio.sample_driver.getStream(GodotRuntime.parseString(p_id)) ? 1 : 0;},godot_audio_sample_register_stream__proxy: 'sync',- godot_audio_sample_register_stream__sig: 'viiiiiii',- /**- * Registers a stream.- * @param {number} streamObjectIdStrPtr StreamObjectId pointer- * @param {number} framesPtr Frames pointer- * @param {number} framesTotal Frames total value- * @param {number} loopModeStrPtr Loop mode pointer- * @param {number} loopBegin Loop begin value- * @param {number} loopEnd Loop end value- * @returns {void}- */- godot_audio_sample_register_stream: function (- streamObjectIdStrPtr,- framesPtr,- framesTotal,- loopModeStrPtr,- loopBegin,- loopEnd- ) {+ godot_audio_sample_register_stream__sig: 'viiiiii',+ godot_audio_sample_register_stream: function (p_id, p_frames, p_frames_count, p_loop_mode, p_loop_begin, p_loop_end) {+ if (!GodotAudio.sample_driver) {+ return;+ }const BYTES_PER_FLOAT32 = 4;- const streamObjectId = GodotRuntime.parseString(streamObjectIdStrPtr);- const loopMode = GodotRuntime.parseString(loopModeStrPtr);+ const sid = GodotRuntime.parseString(p_id);+ const loopMode = GodotRuntime.parseString(p_loop_mode);const numberOfChannels = 2;const sampleRate = GodotAudio.ctx.sampleRate;- /** @type {Float32Array} */- const subLeft = GodotRuntime.heapSub(HEAPF32, framesPtr, framesTotal);- /** @type {Float32Array} */- const subRight = GodotRuntime.heapSub(- HEAPF32,- framesPtr + framesTotal * BYTES_PER_FLOAT32,- framesTotal- );-- const audioBuffer = GodotAudio.ctx.createBuffer(- numberOfChannels,- framesTotal,- sampleRate- );- audioBuffer.copyToChannel(new Float32Array(subLeft), 0, 0);- audioBuffer.copyToChannel(new Float32Array(subRight), 1, 0);-- GodotAudio.Sample.create(- {- id: streamObjectId,- audioBuffer,- },- {- loopBegin,- loopEnd,- loopMode,- numberOfChannels,- sampleRate,- }- );+ // AudioBuffer Cant's copy from a SharedArrayBuffer-backed view.+ const sliceOrSub = HEAPF32.buffer instanceof ArrayBuffer ? GodotRuntime.heapSub : GodotRuntime.heapSlice;+ const subLeft = sliceOrSub(HEAPF32, p_frames, p_frames_count);+ const subRight = sliceOrSub(HEAPF32, p_frames + p_frames_count * BYTES_PER_FLOAT32, p_frames_count);+ const audioBuffer = GodotAudio.ctx.createBuffer(numberOfChannels, p_frames_count, sampleRate);+ audioBuffer.copyToChannel(subLeft, 0, 0);+ audioBuffer.copyToChannel(subRight, 1, 0);++ const opts = {+ /** @export */ loopBegin: p_loop_begin,+ /** @export */ loopEnd: p_loop_end,+ /** @export */ loopMode,+ };+ GodotAudio.sample_driver.createStream(sid, audioBuffer, opts);},godot_audio_sample_unregister_stream__proxy: 'sync',godot_audio_sample_unregister_stream__sig: 'vi',- /**- * Unregisters a stream.- * @param {number} streamObjectIdStrPtr StreamObjectId pointer- * @returns {void}- */- godot_audio_sample_unregister_stream: function (streamObjectIdStrPtr) {- const streamObjectId = GodotRuntime.parseString(streamObjectIdStrPtr);- const sample = GodotAudio.Sample.getSampleOrNull(streamObjectId);- if (sample != null) {- sample.clear();+ godot_audio_sample_unregister_stream: function (p_id) {+ if (!GodotAudio.sample_driver) {+ return;}+ GodotAudio.sample_driver.removeStream(GodotRuntime.parseString(p_id));},godot_audio_sample_start__proxy: 'sync',godot_audio_sample_start__sig: 'viiiifi',- /**- * Starts a sample.- * @param {number} playbackObjectIdStrPtr Playback object id pointer- * @param {number} streamObjectIdStrPtr Stream object id pointer- * @param {number} busIndex Bus index- * @param {number} offset Sample offset- * @param {number} pitchScale Pitch scale- * @param {number} volumePtr Volume pointer- * @returns {void}- */- godot_audio_sample_start: function (- playbackObjectIdStrPtr,- streamObjectIdStrPtr,- busIndex,- offset,- pitchScale,- volumePtr- ) {- /** @type {string} */- const playbackObjectId = GodotRuntime.parseString(playbackObjectIdStrPtr);- /** @type {string} */- const streamObjectId = GodotRuntime.parseString(streamObjectIdStrPtr);- /** @type {Float32Array} */- const volume = GodotRuntime.heapSub(HEAPF32, volumePtr, 8);- /** @type {SampleNodeOptions} */- const startOptions = {- offset,- volume,- playbackRate: 1,- pitchScale,- start: true,- };- GodotAudio.start_sample(- playbackObjectId,- streamObjectId,- busIndex,- startOptions- );+ godot_audio_sample_start: function (p_playback, p_stream, p_bus, p_offset, p_pitch_scale, p_volume) {+ if (!GodotAudio.sample_driver) {+ return;+ }+ const sid = GodotRuntime.parseString(p_stream);+ if (!GodotAudio.sample_driver.getStream(sid)) {+ return;+ }+ const pid = GodotRuntime.parseString(p_playback);+ GodotAudio.sample_driver.removePlayback(pid);+ const playback = GodotAudio.sample_driver.createPlayback(pid, sid);+ const volume = GodotRuntime.heapSlice(HEAPF32, p_volume, 8); // Slice (copy) since it will be stored.+ playback.setVolumes([p_bus], volume);+ playback.setPitchScale(p_pitch_scale);+ playback.start(p_offset);},godot_audio_sample_stop__proxy: 'sync',godot_audio_sample_stop__sig: 'vi',- /**- * Stops a sample from playing.- * @param {number} playbackObjectIdStrPtr Playback object id pointer- * @returns {void}- */- godot_audio_sample_stop: function (playbackObjectIdStrPtr) {- const playbackObjectId = GodotRuntime.parseString(playbackObjectIdStrPtr);- GodotAudio.stop_sample(playbackObjectId);+ godot_audio_sample_stop: function (p_id) {+ if (!GodotAudio.sample_driver) {+ return;+ }+ GodotAudio.sample_driver.removePlayback(GodotRuntime.parseString(p_id));},godot_audio_sample_set_pause__proxy: 'sync',godot_audio_sample_set_pause__sig: 'vii',- /**- * Sets the pause state of a sample.- * @param {number} playbackObjectIdStrPtr Playback object id pointer- * @param {number} pause Pause state- */- godot_audio_sample_set_pause: function (playbackObjectIdStrPtr, pause) {- const playbackObjectId = GodotRuntime.parseString(playbackObjectIdStrPtr);- GodotAudio.sample_set_pause(playbackObjectId, Boolean(pause));+ godot_audio_sample_set_pause: function (p_id, p_pause) {+ if (!GodotAudio.sample_driver) {+ return;+ }+ const playback = GodotAudio.sample_driver.getPlayback(GodotRuntime.parseString(p_id));+ if (playback) {+ playback.pause(Boolean(p_pause));+ }},godot_audio_sample_is_active__proxy: 'sync',godot_audio_sample_is_active__sig: 'ii',- /**- * Returns if the sample is active.- * @param {number} playbackObjectIdStrPtr Playback object id pointer- * @returns {number}- */- godot_audio_sample_is_active: function (playbackObjectIdStrPtr) {- const playbackObjectId = GodotRuntime.parseString(playbackObjectIdStrPtr);- return Number(GodotAudio.sampleNodes.has(playbackObjectId));+ godot_audio_sample_is_active: function (p_id) {+ if (!GodotAudio.sample_driver) {+ return 0;+ }+ return GodotAudio.sample_driver.getPlayback(GodotRuntime.parseString(p_id)) ? 1 : 0;},godot_audio_get_sample_playback_position__proxy: 'sync',godot_audio_get_sample_playback_position__sig: 'di',- /**- * Returns the position of the playback position.- * @param {number} playbackObjectIdStrPtr Playback object id pointer- * @returns {number}- */- godot_audio_get_sample_playback_position: function (playbackObjectIdStrPtr) {- const playbackObjectId = GodotRuntime.parseString(playbackObjectIdStrPtr);- const sampleNode = GodotAudio.SampleNode.getSampleNodeOrNull(playbackObjectId);- if (sampleNode == null) {+ godot_audio_get_sample_playback_position: function (p_id) {+ if (!GodotAudio.sample_driver) {return 0;}- return sampleNode.getPlaybackPosition();+ const playback = GodotAudio.sample_driver.getPlayback(GodotRuntime.parseString(p_id));+ return playback ? playback.getPlaybackPosition() : 0;},godot_audio_sample_update_pitch_scale__proxy: 'sync',godot_audio_sample_update_pitch_scale__sig: 'vii',- /**- * Updates the pitch scale of a sample.- * @param {number} playbackObjectIdStrPtr Playback object id pointer- * @param {number} pitchScale Pitch scale value- * @returns {void}- */- godot_audio_sample_update_pitch_scale: function (- playbackObjectIdStrPtr,- pitchScale- ) {- const playbackObjectId = GodotRuntime.parseString(playbackObjectIdStrPtr);- GodotAudio.update_sample_pitch_scale(playbackObjectId, pitchScale);+ godot_audio_sample_update_pitch_scale: function (p_id, p_pitch_scale) {+ if (!GodotAudio.sample_driver) {+ return;+ }+ const playback = GodotAudio.sample_driver.getPlayback(GodotRuntime.parseString(p_id));+ if (playback) {+ playback.setPitchScale(p_pitch_scale);+ }},godot_audio_sample_set_volumes_linear__proxy: 'sync',- godot_audio_sample_set_volumes_linear__sig: 'vii',- /**- * Sets the volumes linear of each mentioned bus for the sample.- * @param {number} playbackObjectIdStrPtr Playback object id pointer- * @param {number} busesPtr Buses array pointer- * @param {number} busesSize Buses array size- * @param {number} volumesPtr Volumes array pointer- * @param {number} volumesSize Volumes array size- * @returns {void}- */- godot_audio_sample_set_volumes_linear: function (- playbackObjectIdStrPtr,- busesPtr,- busesSize,- volumesPtr,- volumesSize- ) {- /** @type {string} */- const playbackObjectId = GodotRuntime.parseString(playbackObjectIdStrPtr);-- /** @type {Uint32Array} */- const buses = GodotRuntime.heapSub(HEAP32, busesPtr, busesSize);- /** @type {Float32Array} */- const volumes = GodotRuntime.heapSub(HEAPF32, volumesPtr, volumesSize);-- GodotAudio.sample_set_volumes_linear(- playbackObjectId,- Array.from(buses),- volumes- );+ godot_audio_sample_set_volumes_linear__sig: 'viiiii',+ godot_audio_sample_set_volumes_linear: function (p_id, p_buses, p_buses_size, p_volume, p_volume_size) {+ if (!GodotAudio.sample_driver) {+ return;+ }+ const playback = GodotAudio.sample_driver.getPlayback(GodotRuntime.parseString(p_id));+ if (!playback) {+ return;+ }+ const busesIndexes = Array.from(GodotRuntime.heapSub(HEAP32, p_buses, p_buses_size));+ const volumes = GodotRuntime.heapSlice(HEAPF32, p_volume, p_volume_size); // Slice (copy) since it will be stored.+ playback.setVolumes(busesIndexes, volumes);},godot_audio_sample_bus_set_count__proxy: 'sync',godot_audio_sample_bus_set_count__sig: 'vi',- /**- * Sets the bus count.- * @param {number} count Bus count- * @returns {void}- */- godot_audio_sample_bus_set_count: function (count) {- GodotAudio.set_sample_bus_count(count);+ godot_audio_sample_bus_set_count: function (p_count) {+ if (!GodotAudio.sample_driver) {+ return;+ }+ GodotAudio.sample_driver.setBusCount(p_count);},godot_audio_sample_bus_remove__proxy: 'sync',godot_audio_sample_bus_remove__sig: 'vi',- /**- * Removes a bus.- * @param {number} index Index of the bus to remove- * @returns {void}- */- godot_audio_sample_bus_remove: function (index) {- GodotAudio.remove_sample_bus(index);+ godot_audio_sample_bus_remove: function (p_index) {+ if (!GodotAudio.sample_driver) {+ return;+ }+ GodotAudio.sample_driver.removeBus(p_index);},godot_audio_sample_bus_add__proxy: 'sync',godot_audio_sample_bus_add__sig: 'vi',- /**- * Adds a bus at the defined position.- * @param {number} atPos Position to add the bus- * @returns {void}- */- godot_audio_sample_bus_add: function (atPos) {- GodotAudio.add_sample_bus(atPos);+ godot_audio_sample_bus_add: function (p_index) {+ if (!GodotAudio.sample_driver) {+ return;+ }+ GodotAudio.sample_driver.addBusAt(p_index);},godot_audio_sample_bus_move__proxy: 'sync',godot_audio_sample_bus_move__sig: 'vii',- /**- * Moves the bus from a position to another.- * @param {number} fromPos Position of the bus to move- * @param {number} toPos Final position of the bus- * @returns {void}- */- godot_audio_sample_bus_move: function (fromPos, toPos) {- GodotAudio.move_sample_bus(fromPos, toPos);+ godot_audio_sample_bus_move: function (p_from, p_to) {+ if (!GodotAudio.sample_driver) {+ return;+ }+ GodotAudio.sample_driver.moveBus(p_from, p_to);},godot_audio_sample_bus_set_send__proxy: 'sync',godot_audio_sample_bus_set_send__sig: 'vii',- /**- * Sets the "send" of a bus.- * @param {number} bus Position of the bus to set the send- * @param {number} sendIndex Position of the "send" bus- * @returns {void}- */- godot_audio_sample_bus_set_send: function (bus, sendIndex) {- GodotAudio.set_sample_bus_send(bus, sendIndex);+ godot_audio_sample_bus_set_send: function (p_index, p_send_index) {+ if (!GodotAudio.sample_driver) {+ return;+ }+ const bus = GodotAudio.sample_driver.getBus(p_index);+ if (!bus) {+ return;+ }+ let target = GodotAudio.sample_driver.getBus(p_send_index);+ if (target == null) { // Send to master.+ target = GodotAudio.sample_driver.getBus(0);+ }+ bus.setSend(target);},godot_audio_sample_bus_set_volume_db__proxy: 'sync',godot_audio_sample_bus_set_volume_db__sig: 'vii',- /**- * Sets the volume db of a bus.- * @param {number} bus Position of the bus to set the volume db- * @param {number} volumeDb Volume db to set- * @returns {void}- */- godot_audio_sample_bus_set_volume_db: function (bus, volumeDb) {- GodotAudio.set_sample_bus_volume_db(bus, volumeDb);+ godot_audio_sample_bus_set_volume_db: function (p_bus, p_volume_db) {+ if (!GodotAudio.sample_driver) {+ return;+ }+ const bus = GodotAudio.sample_driver.getBus(p_bus);+ if (!bus) {+ return;+ }+ bus.setVolumeDb(p_volume_db);},godot_audio_sample_bus_set_solo__proxy: 'sync',godot_audio_sample_bus_set_solo__sig: 'vii',- /**- * Sets the state of solo for a bus- * @param {number} bus Position of the bus to set the solo state- * @param {number} enable State of the solo- * @returns {void}- */- godot_audio_sample_bus_set_solo: function (bus, enable) {- GodotAudio.set_sample_bus_solo(bus, Boolean(enable));+ godot_audio_sample_bus_set_solo: function (p_bus, p_enable) {+ if (!GodotAudio.sample_driver) {+ return;+ }+ GodotAudio.sample_driver.setBusSolo(p_bus, p_enable);},godot_audio_sample_bus_set_mute__proxy: 'sync',godot_audio_sample_bus_set_mute__sig: 'vii',- /**- * Sets the state of mute for a bus- * @param {number} bus Position of the bus to set the mute state- * @param {number} enable State of the mute- * @returns {void}- */- godot_audio_sample_bus_set_mute: function (bus, enable) {- GodotAudio.set_sample_bus_mute(bus, Boolean(enable));+ godot_audio_sample_bus_set_mute: function (p_bus, p_enable) {+ if (!GodotAudio.sample_driver) {+ return;+ }+ const bus = GodotAudio.sample_driver.getBus(p_bus);+ if (!bus) {+ return;+ }+ bus.setMute(Boolean(p_enable));},godot_audio_sample_set_finished_callback__proxy: 'sync',godot_audio_sample_set_finished_callback__sig: 'vi',- /**- * Sets the finished callback- * @param {Number} callbackPtr Finished callback pointer- * @returns {void}- */- godot_audio_sample_set_finished_callback: function (callbackPtr) {- GodotAudio.sampleFinishedCallback = GodotRuntime.get_func(callbackPtr);+ godot_audio_sample_set_finished_callback: function (p_callback) {+ if (!GodotAudio.sample_driver) {+ return;+ }+ GodotAudio.sample_driver.setFinishedCallback(GodotRuntime.get_func(p_callback));},};-autoAddDeps(_GodotAudio, '$GodotAudio');-mergeInto(LibraryManager.library, _GodotAudio);+autoAddDeps(_GodotAudioSampleDriver, '$GodotAudioSampleDriver');+mergeInto(LibraryManager.library, _GodotAudioSampleDriver);/*** The AudioWorklet API driver, used when threads are available.@@ -1992,6 +1139,7 @@ const GodotAudioWorklet = {p_in_size,in_callback) {+ /** @constructor */function RingBuffer() {let wpos = 0;let rpos = 0;@@ -2237,7 +1385,7 @@ const GodotAudioScript = {close: function () {return new Promise(function (resolve, reject) {GodotAudioScript.script.disconnect();- GodotAudioScript.script.onaudioprocess = null;+ GodotAudioScript.script.onaudioprocess = function () {};GodotAudioScript.script = null;resolve();});diff --git a/servers/audio/audio_server.cpp b/servers/audio/audio_server.cppindex b7730d7f28f..6bbd240d365 100644--- a/servers/audio/audio_server.cpp+++ b/servers/audio/audio_server.cpp@@ -720,6 +720,7 @@ void AudioServer::add_bus(int p_at_pos) {bus_map[attempt] = bus;if (p_at_pos == -1) {+ p_at_pos = buses.size();buses.push_back(bus);} else {buses.insert(p_at_pos, bus);