summaryrefslogtreecommitdiff
path: root/platform/javascript/audio_driver_javascript.cpp
blob: 03ca5f78d16d1ba95df89ebb78d570a3b91a0bfe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
/*************************************************************************/
/*  audio_driver_javascript.cpp                                          */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#include "audio_driver_javascript.h"

#include <emscripten.h>

AudioDriverJavaScript *AudioDriverJavaScript::singleton = nullptr;

const char *AudioDriverJavaScript::get_name() const {
	return "JavaScript";
}

extern "C" EMSCRIPTEN_KEEPALIVE void audio_driver_js_mix() {
	AudioDriverJavaScript::singleton->mix_to_js();
}

extern "C" EMSCRIPTEN_KEEPALIVE void audio_driver_process_capture(float sample) {
	AudioDriverJavaScript::singleton->process_capture(sample);
}

void AudioDriverJavaScript::mix_to_js() {
	int channel_count = get_total_channels_by_speaker_mode(get_speaker_mode());
	int sample_count = memarr_len(internal_buffer) / channel_count;
	int32_t *stream_buffer = reinterpret_cast<int32_t *>(internal_buffer);
	audio_server_process(sample_count, stream_buffer);
	for (int i = 0; i < sample_count * channel_count; i++) {
		internal_buffer[i] = float(stream_buffer[i] >> 16) / 32768.f;
	}
}

void AudioDriverJavaScript::process_capture(float sample) {
	int32_t sample32 = int32_t(sample * 32768.f) * (1U << 16);
	input_buffer_write(sample32);
}

Error AudioDriverJavaScript::init() {
	/* clang-format off */
	_driver_id = EM_ASM_INT({
		return Module.IDHandler.add({
			'context': new (window.AudioContext || window.webkitAudioContext),
			'input': null,
			'stream': null,
			'script': null
		});
	});
	/* clang-format on */

	int channel_count = get_total_channels_by_speaker_mode(get_speaker_mode());
	/* clang-format off */
	buffer_length = EM_ASM_INT({
		var ref = Module.IDHandler.get($0);
		var ctx = ref['context'];
		var CHANNEL_COUNT = $1;

		var channelCount = ctx.destination.channelCount;
		var script = null;
		try {
			// Try letting the browser recommend a buffer length.
			script = ctx.createScriptProcessor(0, 2, channelCount);
		} catch (e) {
			// ...otherwise, default to 4096.
			script = ctx.createScriptProcessor(4096, 2, channelCount);
		}
		script.connect(ctx.destination);
		ref['script'] = script;

		return script.bufferSize;
	}, _driver_id, channel_count);
	/* clang-format on */
	if (!buffer_length) {
		return FAILED;
	}

	if (!internal_buffer || (int)memarr_len(internal_buffer) != buffer_length * channel_count) {
		if (internal_buffer)
			memdelete_arr(internal_buffer);
		internal_buffer = memnew_arr(float, buffer_length *channel_count);
	}

	return internal_buffer ? OK : ERR_OUT_OF_MEMORY;
}

void AudioDriverJavaScript::start() {
	/* clang-format off */
	EM_ASM({
		const ref = Module.IDHandler.get($0);
		var INTERNAL_BUFFER_PTR = $1;

		var audioDriverMixFunction = cwrap('audio_driver_js_mix');
		var audioDriverProcessCapture = cwrap('audio_driver_process_capture', null, ['number']);
		ref['script'].onaudioprocess = function(audioProcessingEvent) {
			audioDriverMixFunction();

			var input = audioProcessingEvent.inputBuffer;
			var output = audioProcessingEvent.outputBuffer;
			var internalBuffer = HEAPF32.subarray(
					INTERNAL_BUFFER_PTR / HEAPF32.BYTES_PER_ELEMENT,
					INTERNAL_BUFFER_PTR / HEAPF32.BYTES_PER_ELEMENT + output.length * output.numberOfChannels);

			for (var channel = 0; channel < output.numberOfChannels; channel++) {
				var outputData = output.getChannelData(channel);
				// Loop through samples.
				for (var sample = 0; sample < outputData.length; sample++) {
					outputData[sample] = internalBuffer[sample * output.numberOfChannels + channel];
				}
			}

			if (ref['input']) {
				var inputDataL = input.getChannelData(0);
				var inputDataR = input.getChannelData(1);
				for (var i = 0; i < inputDataL.length; i++) {
					audioDriverProcessCapture(inputDataL[i]);
					audioDriverProcessCapture(inputDataR[i]);
				}
			}
		};
	}, _driver_id, internal_buffer);
	/* clang-format on */
}

void AudioDriverJavaScript::resume() {
	/* clang-format off */
	EM_ASM({
		const ref = Module.IDHandler.get($0);
		if (ref && ref['context'] && ref['context'].resume)
			ref['context'].resume();
	}, _driver_id);
	/* clang-format on */
}

int AudioDriverJavaScript::get_mix_rate() const {
	/* clang-format off */
	return EM_ASM_INT({
		const ref = Module.IDHandler.get($0);
		return ref && ref['context'] ? ref['context'].sampleRate : 0;
	}, _driver_id);
	/* clang-format on */
}

AudioDriver::SpeakerMode AudioDriverJavaScript::get_speaker_mode() const {
	/* clang-format off */
	return get_speaker_mode_by_total_channels(EM_ASM_INT({
		const ref = Module.IDHandler.get($0);
		return ref && ref['context'] ? ref['context'].destination.channelCount : 0;
	}, _driver_id));
	/* clang-format on */
}

// No locking, as threads are not supported.
void AudioDriverJavaScript::lock() {
}

void AudioDriverJavaScript::unlock() {
}

void AudioDriverJavaScript::finish_async() {
	// Close the context, add the operation to the async_finish list in module.
	int id = _driver_id;
	_driver_id = 0;

	/* clang-format off */
	EM_ASM({
		var ref = Module.IDHandler.get($0);
		Module.async_finish.push(new Promise(function(accept, reject) {
			if (!ref) {
				console.log("Ref not found!", $0, Module.IDHandler);
				setTimeout(accept, 0);
			} else {
				const context = ref['context'];
				// Disconnect script and input.
				ref['script'].disconnect();
				if (ref['input'])
					ref['input'].disconnect();
				ref = null;
				context.close().then(function() {
					accept();
				}).catch(function(e) {
					accept();
				});
			}
		}));
		Module.IDHandler.remove($0);
	}, id);
	/* clang-format on */
}

void AudioDriverJavaScript::finish() {
	if (internal_buffer) {
		memdelete_arr(internal_buffer);
		internal_buffer = nullptr;
	}
}

Error AudioDriverJavaScript::capture_start() {
	input_buffer_init(buffer_length);

	/* clang-format off */
	EM_ASM({
		function gotMediaInput(stream) {
			var ref = Module.IDHandler.get($0);
			ref['stream'] = stream;
			ref['input'] = ref['context'].createMediaStreamSource(stream);
			ref['input'].connect(ref['script']);
		}

		function gotMediaInputError(e) {
			out(e);
		}

		if (navigator.mediaDevices.getUserMedia) {
			navigator.mediaDevices.getUserMedia({"audio": true}).then(gotMediaInput, gotMediaInputError);
		} else {
			if (!navigator.getUserMedia)
				navigator.getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
			navigator.getUserMedia({"audio": true}, gotMediaInput, gotMediaInputError);
		}
	}, _driver_id);
	/* clang-format on */

	return OK;
}

Error AudioDriverJavaScript::capture_stop() {
	/* clang-format off */
	EM_ASM({
		var ref = Module.IDHandler.get($0);
		if (ref['stream']) {
			const tracks = ref['stream'].getTracks();
			for (var i = 0; i < tracks.length; i++) {
				tracks[i].stop();
			}
			ref['stream'] = null;
		}

		if (ref['input']) {
			ref['input'].disconnect();
			ref['input'] = null;
		}

	}, _driver_id);
	/* clang-format on */

	input_buffer.clear();

	return OK;
}

AudioDriverJavaScript::AudioDriverJavaScript() {
	_driver_id = 0;
	internal_buffer = nullptr;
	buffer_length = 0;

	singleton = this;
}