diff options
author | RĂ©mi Verschelde <rverschelde@gmail.com> | 2020-11-11 10:07:28 +0100 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-11-11 10:07:28 +0100 |
commit | 10fd10759978f01e9152278e905f32c1117d2841 (patch) | |
tree | 0fea30ec74363a4c1eb2b69105caf29bb695b130 /modules/webrtc | |
parent | 88d463cabcfe2bf2b0f14e4ad34cb2741b8da686 (diff) | |
parent | 179ec3ca0ef909592eece8c907ec0cd855ef5b04 (diff) |
Merge pull request #43443 from Faless/js/4.0_audio_worklet
[HTML5] Port inline JS code to libraries, AudioWorklet support.
Diffstat (limited to 'modules/webrtc')
-rw-r--r-- | modules/webrtc/SCsub | 4 | ||||
-rw-r--r-- | modules/webrtc/library_godot_webrtc.js | 407 | ||||
-rw-r--r-- | modules/webrtc/webrtc_data_channel_js.cpp | 245 | ||||
-rw-r--r-- | modules/webrtc/webrtc_data_channel_js.h | 10 | ||||
-rw-r--r-- | modules/webrtc/webrtc_peer_connection_js.cpp | 244 | ||||
-rw-r--r-- | modules/webrtc/webrtc_peer_connection_js.h | 23 |
6 files changed, 521 insertions, 412 deletions
diff --git a/modules/webrtc/SCsub b/modules/webrtc/SCsub index 20b4c8f8d2..4f870ddb2f 100644 --- a/modules/webrtc/SCsub +++ b/modules/webrtc/SCsub @@ -12,4 +12,8 @@ if use_gdnative: # GDNative is retained in Javascript for export compatibility env_webrtc.Append(CPPDEFINES=["WEBRTC_GDNATIVE_ENABLED"]) env_webrtc.Prepend(CPPPATH=["#modules/gdnative/include/"]) +if env["platform"] == "javascript": + # Our JavaScript/C++ interface. + env.AddJSLibraries(["library_godot_webrtc.js"]) + env_webrtc.add_source_files(env.modules_sources, "*.cpp") diff --git a/modules/webrtc/library_godot_webrtc.js b/modules/webrtc/library_godot_webrtc.js new file mode 100644 index 0000000000..b75996b1f3 --- /dev/null +++ b/modules/webrtc/library_godot_webrtc.js @@ -0,0 +1,407 @@ +/*************************************************************************/ +/* library_godot_webrtc.js */ +/*************************************************************************/ +/* 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. */ +/*************************************************************************/ + +var GodotRTCDataChannel = { + // Our socket implementation that forwards events to C++. + $GodotRTCDataChannel__deps: ['$IDHandler', '$GodotOS'], + $GodotRTCDataChannel: { + + connect: function(p_id, p_on_open, p_on_message, p_on_error, p_on_close) { + const ref = IDHandler.get(p_id); + if (!ref) { + return; + } + + ref.binaryType = 'arraybuffer'; + ref.onopen = function (event) { + p_on_open(); + }; + ref.onclose = function (event) { + p_on_close(); + }; + ref.onerror = function (event) { + p_on_error(); + }; + ref.onmessage = function(event) { + var buffer; + var is_string = 0; + if (event.data instanceof ArrayBuffer) { + buffer = new Uint8Array(event.data); + } else if (event.data instanceof Blob) { + console.error("Blob type not supported"); + return; + } else if (typeof event.data === "string") { + is_string = 1; + var enc = new TextEncoder("utf-8"); + buffer = new Uint8Array(enc.encode(event.data)); + } else { + console.error("Unknown message type"); + return; + } + var len = buffer.length*buffer.BYTES_PER_ELEMENT; + var out = _malloc(len); + HEAPU8.set(buffer, out); + p_on_message(out, len, is_string); + _free(out); + } + }, + + close: function(p_id) { + const ref = IDHandler.get(p_id); + if (!ref) { + return; + } + ref.onopen = null; + ref.onmessage = null; + ref.onerror = null; + ref.onclose = null; + ref.close(); + }, + + get_prop: function(p_id, p_prop, p_def) { + const ref = IDHandler.get(p_id); + return (ref && ref[p_prop] !== undefined) ? ref[p_prop] : p_def; + }, + }, + + godot_js_rtc_datachannel_ready_state_get: function(p_id) { + const ref = IDHandler.get(p_id); + if (!ref) { + return 3; // CLOSED + } + + switch(ref.readyState) { + case "connecting": + return 0; + case "open": + return 1; + case "closing": + return 2; + case "closed": + return 3; + } + return 3; // CLOSED + }, + + godot_js_rtc_datachannel_send: function(p_id, p_buffer, p_length, p_raw) { + const ref = IDHandler.get(p_id); + if (!ref) { + return 1; + } + + const bytes_array = new Uint8Array(p_length); + for (var i = 0; i < p_length; i++) { + bytes_array[i] = getValue(p_buffer + i, 'i8'); + } + + if (p_raw) { + ref.send(bytes_array.buffer); + } else { + const string = new TextDecoder('utf-8').decode(bytes_array); + ref.send(string); + } + }, + + godot_js_rtc_datachannel_is_ordered: function(p_id) { + return IDHandler.get_prop(p_id, 'ordered', true); + }, + + godot_js_rtc_datachannel_id_get: function(p_id) { + return IDHandler.get_prop(p_id, 'id', 65535); + }, + + godot_js_rtc_datachannel_max_packet_lifetime_get: function(p_id) { + const ref = IDHandler.get(p_id); + if (!ref) { + return 65535; + } + if (ref['maxPacketLifeTime'] !== undefined) { + return ref['maxPacketLifeTime']; + } else if (ref['maxRetransmitTime'] !== undefined) { + // Guess someone didn't appreciate the standardization process. + return ref['maxRetransmitTime']; + } + return 65535; + }, + + godot_js_rtc_datachannel_max_retransmits_get: function(p_id) { + return IDHandler.get_prop(p_id, 'maxRetransmits', 65535); + }, + + godot_js_rtc_datachannel_is_negotiated: function(p_id, p_def) { + return IDHandler.get_prop(p_id, 'negotiated', 65535); + }, + + godot_js_rtc_datachannel_label_get: function(p_id) { + const ref = IDHandler.get(p_id); + if (!ref || !ref.label) { + return 0; + } + return GodotOS.allocString(ref.label); + }, + + godot_js_rtc_datachannel_protocol_get: function(p_id) { + const ref = IDHandler.get(p_id); + if (!ref || !ref.protocol) { + return 0; + } + return GodotOS.allocString(ref.protocol); + }, + + godot_js_rtc_datachannel_destroy: function(p_id) { + GodotRTCDataChannel.close(p_id); + IDHandler.remove(p_id); + }, + + godot_js_rtc_datachannel_connect: function(p_id, p_ref, p_on_open, p_on_message, p_on_error, p_on_close) { + const onopen = GodotOS.get_func(p_on_open).bind(null, p_ref); + const onmessage = GodotOS.get_func(p_on_message).bind(null, p_ref); + const onerror = GodotOS.get_func(p_on_error).bind(null, p_ref); + const onclose = GodotOS.get_func(p_on_close).bind(null, p_ref); + GodotRTCDataChannel.connect(p_id, onopen, onmessage, onerror, onclose); + }, + + godot_js_rtc_datachannel_close: function(p_id) { + const ref = IDHandler.get(p_id); + if (!ref) { + return; + } + GodotRTCDataChannel.close(p_id); + }, +}; + +autoAddDeps(GodotRTCDataChannel, '$GodotRTCDataChannel'); +mergeInto(LibraryManager.library, GodotRTCDataChannel); + +var GodotRTCPeerConnection = { + + $GodotRTCPeerConnection__deps: ['$IDHandler', '$GodotOS', '$GodotRTCDataChannel'], + $GodotRTCPeerConnection: { + onstatechange: function(p_id, p_conn, callback, event) { + const ref = IDHandler.get(p_id); + if (!ref) { + return; + } + var state = 5; // CLOSED + switch(p_conn.iceConnectionState) { + case "new": + state = 0; + case "checking": + state = 1; + case "connected": + case "completed": + state = 2; + case "disconnected": + state = 3; + case "failed": + state = 4; + case "closed": + state = 5; + } + callback(state); + }, + + onicecandidate: function(p_id, callback, event) { + const ref = IDHandler.get(p_id); + if (!ref || !event.candidate) { + return; + } + + let c = event.candidate; + let candidate_str = GodotOS.allocString(c.candidate); + let mid_str = GodotOS.allocString(c.sdpMid); + callback(mid_str, c.sdpMLineIndex, candidate_str); + _free(candidate_str); + _free(mid_str); + }, + + ondatachannel: function(p_id, callback, event) { + const ref = IDHandler.get(p_id); + if (!ref) { + return; + } + + const cid = IDHandler.add(event.channel); + callback(cid); + }, + + onsession: function(p_id, callback, session) { + const ref = IDHandler.get(p_id); + if (!ref) { + return; + } + let type_str = GodotOS.allocString(session.type); + let sdp_str = GodotOS.allocString(session.sdp); + callback(type_str, sdp_str); + _free(type_str); + _free(sdp_str); + }, + + onerror: function(p_id, callback, error) { + const ref = IDHandler.get(p_id); + if (!ref) { + return; + } + console.error(error); + callback(); + }, + }, + + godot_js_rtc_pc_create: function(p_config, p_ref, p_on_state_change, p_on_candidate, p_on_datachannel) { + const onstatechange = GodotOS.get_func(p_on_state_change).bind(null, p_ref); + const oncandidate = GodotOS.get_func(p_on_candidate).bind(null, p_ref); + const ondatachannel = GodotOS.get_func(p_on_datachannel).bind(null, p_ref); + + var config = JSON.parse(UTF8ToString(p_config)); + var conn = null; + try { + conn = new RTCPeerConnection(config); + } catch (e) { + console.error(e); + return 0; + } + + const base = GodotRTCPeerConnection; + const id = IDHandler.add(conn); + conn.oniceconnectionstatechange = base.onstatechange.bind(null, id, conn, onstatechange); + conn.onicecandidate = base.onicecandidate.bind(null, id, oncandidate); + conn.ondatachannel = base.ondatachannel.bind(null, id, ondatachannel); + return id; + }, + + godot_js_rtc_pc_close: function(p_id) { + const ref = IDHandler.get(p_id); + if (!ref) { + return; + } + ref.close(); + }, + + godot_js_rtc_pc_destroy: function(p_id) { + const ref = IDHandler.get(p_id); + if (!ref) { + return; + } + ref.oniceconnectionstatechange = null; + ref.onicecandidate = null; + ref.ondatachannel = null; + IDHandler.remove(p_id); + }, + + godot_js_rtc_pc_offer_create: function(p_id, p_obj, p_on_session, p_on_error) { + const ref = IDHandler.get(p_id); + if (!ref) { + return; + } + const onsession = GodotOS.get_func(p_on_session).bind(null, p_obj); + const onerror = GodotOS.get_func(p_on_error).bind(null, p_obj); + ref.createOffer().then(function(session) { + GodotRTCPeerConnection.onsession(p_id, onsession, session); + }).catch(function(error) { + GodotRTCPeerConnection.onerror(p_id, onerror, error); + }); + }, + + godot_js_rtc_pc_local_description_set: function(p_id, p_type, p_sdp, p_obj, p_on_error) { + const ref = IDHandler.get(p_id); + if (!ref) { + return; + } + const type = UTF8ToString(p_type); + const sdp = UTF8ToString(p_sdp); + const onerror = GodotOS.get_func(p_on_error).bind(null, p_obj); + ref.setLocalDescription({ + 'sdp': sdp, + 'type': type + }).catch(function(error) { + GodotRTCPeerConnection.onerror(p_id, onerror, error); + }); + }, + + godot_js_rtc_pc_remote_description_set: function(p_id, p_type, p_sdp, p_obj, p_session_created, p_on_error) { + const ref = IDHandler.get(p_id); + if (!ref) { + return; + } + const type = UTF8ToString(p_type); + const sdp = UTF8ToString(p_sdp); + const onerror = GodotOS.get_func(p_on_error).bind(null, p_obj); + const onsession = GodotOS.get_func(p_session_created).bind(null, p_obj); + ref.setRemoteDescription({ + 'sdp': sdp, + 'type': type + }).then(function() { + if (type != 'offer') { + return; + } + return ref.createAnswer().then(function(session) { + GodotRTCPeerConnection.onsession(p_id, onsession, session); + }); + }).catch(function(error) { + GodotRTCPeerConnection.onerror(p_id, onerror, error); + }); + }, + + godot_js_rtc_pc_ice_candidate_add: function(p_id, p_mid_name, p_mline_idx, p_sdp) { + const ref = IDHandler.get(p_id); + if (!ref) { + return; + } + var sdpMidName = UTF8ToString(p_mid_name); + var sdpName = UTF8ToString(p_sdp); + ref.addIceCandidate(new RTCIceCandidate({ + "candidate": sdpName, + "sdpMid": sdpMidName, + "sdpMlineIndex": p_mline_idx, + })); + }, + + godot_js_rtc_pc_datachannel_create__deps: ['$GodotRTCDataChannel'], + godot_js_rtc_pc_datachannel_create: function(p_id, p_label, p_config) { + try { + const ref = IDHandler.get(p_id); + if (!ref) { + return 0; + } + + const label = UTF8ToString(p_label); + const config = JSON.parse(UTF8ToString(p_config)); + + const channel = ref.createDataChannel(label, config); + return IDHandler.add(channel); + } catch (e) { + console.error(e); + return 0; + } + }, +}; + +autoAddDeps(GodotRTCPeerConnection, '$GodotRTCPeerConnection') +mergeInto(LibraryManager.library, GodotRTCPeerConnection); diff --git a/modules/webrtc/webrtc_data_channel_js.cpp b/modules/webrtc/webrtc_data_channel_js.cpp index 2c648ba9f9..3a63001a56 100644 --- a/modules/webrtc/webrtc_data_channel_js.cpp +++ b/modules/webrtc/webrtc_data_channel_js.cpp @@ -34,65 +34,58 @@ #include "emscripten.h" extern "C" { -EMSCRIPTEN_KEEPALIVE void _emrtc_on_ch_error(void *obj) { - WebRTCDataChannelJS *peer = static_cast<WebRTCDataChannelJS *>(obj); - peer->_on_error(); -} +typedef void (*RTCChOnOpen)(void *p_obj); +typedef void (*RTCChOnMessage)(void *p_obj, const uint8_t *p_buffer, int p_size, int p_is_string); +typedef void (*RTCChOnClose)(void *p_obj); +typedef void (*RTCChOnError)(void *p_obj); -EMSCRIPTEN_KEEPALIVE void _emrtc_on_ch_open(void *obj) { - WebRTCDataChannelJS *peer = static_cast<WebRTCDataChannelJS *>(obj); - peer->_on_open(); +extern int godot_js_rtc_datachannel_ready_state_get(int p_id); +extern int godot_js_rtc_datachannel_send(int p_id, const uint8_t *p_buffer, int p_length, int p_raw); +extern int godot_js_rtc_datachannel_is_ordered(int p_id); +extern int godot_js_rtc_datachannel_id_get(int p_id); +extern int godot_js_rtc_datachannel_max_packet_lifetime_get(int p_id); +extern int godot_js_rtc_datachannel_max_retransmits_get(int p_id); +extern int godot_js_rtc_datachannel_is_negotiated(int p_id); +extern char *godot_js_rtc_datachannel_label_get(int p_id); // Must free the returned string. +extern char *godot_js_rtc_datachannel_protocol_get(int p_id); // Must free the returned string. +extern void godot_js_rtc_datachannel_destroy(int p_id); +extern void godot_js_rtc_datachannel_connect(int p_id, void *p_obj, RTCChOnOpen p_on_open, RTCChOnMessage p_on_message, RTCChOnError p_on_error, RTCChOnClose p_on_close); +extern void godot_js_rtc_datachannel_close(int p_id); } -EMSCRIPTEN_KEEPALIVE void _emrtc_on_ch_close(void *obj) { - WebRTCDataChannelJS *peer = static_cast<WebRTCDataChannelJS *>(obj); - peer->_on_close(); +void WebRTCDataChannelJS::_on_open(void *p_obj) { + WebRTCDataChannelJS *peer = static_cast<WebRTCDataChannelJS *>(p_obj); + peer->in_buffer.resize(peer->_in_buffer_shift); } -EMSCRIPTEN_KEEPALIVE void _emrtc_on_ch_message(void *obj, uint8_t *p_data, uint32_t p_size, bool p_is_string) { - WebRTCDataChannelJS *peer = static_cast<WebRTCDataChannelJS *>(obj); - peer->_on_message(p_data, p_size, p_is_string); -} +void WebRTCDataChannelJS::_on_close(void *p_obj) { + WebRTCDataChannelJS *peer = static_cast<WebRTCDataChannelJS *>(p_obj); + peer->close(); } -void WebRTCDataChannelJS::_on_open() { - in_buffer.resize(_in_buffer_shift); +void WebRTCDataChannelJS::_on_error(void *p_obj) { + WebRTCDataChannelJS *peer = static_cast<WebRTCDataChannelJS *>(p_obj); + peer->close(); } -void WebRTCDataChannelJS::_on_close() { - close(); -} +void WebRTCDataChannelJS::_on_message(void *p_obj, const uint8_t *p_data, int p_size, int p_is_string) { + WebRTCDataChannelJS *peer = static_cast<WebRTCDataChannelJS *>(p_obj); + RingBuffer<uint8_t> &in_buffer = peer->in_buffer; -void WebRTCDataChannelJS::_on_error() { - close(); -} - -void WebRTCDataChannelJS::_on_message(uint8_t *p_data, uint32_t p_size, bool p_is_string) { ERR_FAIL_COND_MSG(in_buffer.space_left() < (int)(p_size + 5), "Buffer full! Dropping data."); uint8_t is_string = p_is_string ? 1 : 0; in_buffer.write((uint8_t *)&p_size, 4); in_buffer.write((uint8_t *)&is_string, 1); in_buffer.write(p_data, p_size); - queue_count++; + peer->queue_count++; } void WebRTCDataChannelJS::close() { in_buffer.resize(0); queue_count = 0; _was_string = false; - /* clang-format off */ - EM_ASM({ - var dict = Module.IDHandler.get($0); - if (!dict) return; - var channel = dict["channel"]; - channel.onopen = null; - channel.onclose = null; - channel.onerror = null; - channel.onmessage = null; - channel.close(); - }, _js_id); - /* clang-format on */ + godot_js_rtc_datachannel_close(_js_id); } Error WebRTCDataChannelJS::poll() { @@ -100,24 +93,7 @@ Error WebRTCDataChannelJS::poll() { } WebRTCDataChannelJS::ChannelState WebRTCDataChannelJS::get_ready_state() const { - /* clang-format off */ - return (ChannelState) EM_ASM_INT({ - var dict = Module.IDHandler.get($0); - if (!dict) return 3; // CLOSED - var channel = dict["channel"]; - switch(channel.readyState) { - case "connecting": - return 0; - case "open": - return 1; - case "closing": - return 2; - case "closed": - return 3; - } - return 3; // CLOSED - }, _js_id); - /* clang-format on */ + return (ChannelState)godot_js_rtc_datachannel_ready_state_get(_js_id); } int WebRTCDataChannelJS::get_available_packet_count() const { @@ -157,27 +133,7 @@ Error WebRTCDataChannelJS::put_packet(const uint8_t *p_buffer, int p_buffer_size ERR_FAIL_COND_V(get_ready_state() != STATE_OPEN, ERR_UNCONFIGURED); int is_bin = _write_mode == WebRTCDataChannel::WRITE_MODE_BINARY ? 1 : 0; - - /* clang-format off */ - EM_ASM({ - var dict = Module.IDHandler.get($0); - var channel = dict["channel"]; - var bytes_array = new Uint8Array($2); - var i = 0; - - for(i=0; i<$2; i++) { - bytes_array[i] = getValue($1+i, 'i8'); - } - - if ($3) { - channel.send(bytes_array.buffer); - } else { - var string = new TextDecoder("utf-8").decode(bytes_array); - channel.send(string); - } - }, _js_id, p_buffer, p_buffer_size, is_bin); - /* clang-format on */ - + godot_js_rtc_datachannel_send(_js_id, p_buffer, p_buffer_size, is_bin); return OK; } @@ -201,46 +157,20 @@ String WebRTCDataChannelJS::get_label() const { return _label; } -/* clang-format off */ -#define _JS_GET(PROP, DEF) \ -EM_ASM_INT({ \ - var dict = Module.IDHandler.get($0); \ - if (!dict || !dict["channel"]) { \ - return DEF; \ - } \ - var out = dict["channel"].PROP; \ - return out === null ? DEF : out; \ -}, _js_id) -/* clang-format on */ - bool WebRTCDataChannelJS::is_ordered() const { - return _JS_GET(ordered, true); + return godot_js_rtc_datachannel_is_ordered(_js_id); } int WebRTCDataChannelJS::get_id() const { - return _JS_GET(id, 65535); + return godot_js_rtc_datachannel_id_get(_js_id); } int WebRTCDataChannelJS::get_max_packet_life_time() const { - // Can't use macro, webkit workaround. - /* clang-format off */ - return EM_ASM_INT({ - var dict = Module.IDHandler.get($0); - if (!dict || !dict["channel"]) { - return 65535; - } - if (dict["channel"].maxRetransmitTime !== undefined) { - // Guess someone didn't appreciate the standardization process. - return dict["channel"].maxRetransmitTime; - } - var out = dict["channel"].maxPacketLifeTime; - return out === null ? 65535 : out; - }, _js_id); - /* clang-format on */ + return godot_js_rtc_datachannel_max_packet_lifetime_get(_js_id); } int WebRTCDataChannelJS::get_max_retransmits() const { - return _JS_GET(maxRetransmits, 65535); + return godot_js_rtc_datachannel_max_retransmits_get(_js_id); } String WebRTCDataChannelJS::get_protocol() const { @@ -248,7 +178,7 @@ String WebRTCDataChannelJS::get_protocol() const { } bool WebRTCDataChannelJS::is_negotiated() const { - return _JS_GET(negotiated, false); + return godot_js_rtc_datachannel_is_negotiated(_js_id); } WebRTCDataChannelJS::WebRTCDataChannelJS() { @@ -264,101 +194,22 @@ WebRTCDataChannelJS::WebRTCDataChannelJS(int js_id) { _write_mode = WRITE_MODE_BINARY; _js_id = js_id; - /* clang-format off */ - EM_ASM({ - var c_ptr = $0; - var dict = Module.IDHandler.get($1); - if (!dict) return; - var channel = dict["channel"]; - dict["ptr"] = c_ptr; - - channel.binaryType = "arraybuffer"; - channel.onopen = function (evt) { - ccall("_emrtc_on_ch_open", - "void", - ["number"], - [c_ptr] - ); - }; - channel.onclose = function (evt) { - ccall("_emrtc_on_ch_close", - "void", - ["number"], - [c_ptr] - ); - }; - channel.onerror = function (evt) { - ccall("_emrtc_on_ch_error", - "void", - ["number"], - [c_ptr] - ); - }; - channel.onmessage = function(event) { - var buffer; - var is_string = 0; - if (event.data instanceof ArrayBuffer) { - buffer = new Uint8Array(event.data); - } else if (event.data instanceof Blob) { - console.error("Blob type not supported"); - return; - } else if (typeof event.data === "string") { - is_string = 1; - var enc = new TextEncoder("utf-8"); - buffer = new Uint8Array(enc.encode(event.data)); - } else { - console.error("Unknown message type"); - return; - } - var len = buffer.length*buffer.BYTES_PER_ELEMENT; - var out = _malloc(len); - HEAPU8.set(buffer, out); - ccall("_emrtc_on_ch_message", - "void", - ["number", "number", "number", "number"], - [c_ptr, out, len, is_string] - ); - _free(out); - } - - }, this, js_id); + godot_js_rtc_datachannel_connect(js_id, this, &_on_open, &_on_message, &_on_error, &_on_close); // Parse label - char *str; - str = (char *)EM_ASM_INT({ - var dict = Module.IDHandler.get($0); - if (!dict || !dict["channel"]) return 0; - var str = dict["channel"].label; - var len = lengthBytesUTF8(str)+1; - var ptr = _malloc(str); - stringToUTF8(str, ptr, len+1); - return ptr; - }, js_id); - if(str != nullptr) { - _label.parse_utf8(str); - EM_ASM({ _free($0) }, str); + char *label = godot_js_rtc_datachannel_label_get(js_id); + if (label) { + _label.parse_utf8(label); + free(label); } - str = (char *)EM_ASM_INT({ - var dict = Module.IDHandler.get($0); - if (!dict || !dict["channel"]) return 0; - var str = dict["channel"].protocol; - var len = lengthBytesUTF8(str)+1; - var ptr = _malloc(str); - stringToUTF8(str, ptr, len+1); - return ptr; - }, js_id); - if(str != nullptr) { - _protocol.parse_utf8(str); - EM_ASM({ _free($0) }, str); + char *protocol = godot_js_rtc_datachannel_protocol_get(js_id); + if (protocol) { + _protocol.parse_utf8(protocol); + free(protocol); } - /* clang-format on */ } WebRTCDataChannelJS::~WebRTCDataChannelJS() { close(); - /* clang-format off */ - EM_ASM({ - Module.IDHandler.remove($0); - }, _js_id); - /* clang-format on */ -}; + godot_js_rtc_datachannel_destroy(_js_id); +} #endif diff --git a/modules/webrtc/webrtc_data_channel_js.h b/modules/webrtc/webrtc_data_channel_js.h index 7545910e66..e251760019 100644 --- a/modules/webrtc/webrtc_data_channel_js.h +++ b/modules/webrtc/webrtc_data_channel_js.h @@ -54,12 +54,12 @@ private: int queue_count; uint8_t packet_buffer[PACKET_BUFFER_SIZE]; -public: - void _on_open(); - void _on_close(); - void _on_error(); - void _on_message(uint8_t *p_data, uint32_t p_size, bool p_is_string); + static void _on_open(void *p_obj); + static void _on_close(void *p_obj); + static void _on_error(void *p_obj); + static void _on_message(void *p_obj, const uint8_t *p_data, int p_size, int p_is_string); +public: virtual void set_write_mode(WriteMode mode) override; virtual WriteMode get_write_mode() const override; virtual bool was_string_packet() const override; diff --git a/modules/webrtc/webrtc_peer_connection_js.cpp b/modules/webrtc/webrtc_peer_connection_js.cpp index 593c3a5162..ad9b46a8af 100644 --- a/modules/webrtc/webrtc_peer_connection_js.cpp +++ b/modules/webrtc/webrtc_peer_connection_js.cpp @@ -37,116 +37,32 @@ #include "core/io/json.h" #include "emscripten.h" -extern "C" { -EMSCRIPTEN_KEEPALIVE void _emrtc_on_ice_candidate(void *obj, char *p_MidName, int p_MlineIndexName, char *p_sdpName) { - WebRTCPeerConnectionJS *peer = static_cast<WebRTCPeerConnectionJS *>(obj); - peer->emit_signal("ice_candidate_created", String(p_MidName), p_MlineIndexName, String(p_sdpName)); +void WebRTCPeerConnectionJS::_on_ice_candidate(void *p_obj, const char *p_mid_name, int p_mline_idx, const char *p_candidate) { + WebRTCPeerConnectionJS *peer = static_cast<WebRTCPeerConnectionJS *>(p_obj); + peer->emit_signal("ice_candidate_created", String(p_mid_name), p_mline_idx, String(p_candidate)); } -EMSCRIPTEN_KEEPALIVE void _emrtc_session_description_created(void *obj, char *p_type, char *p_offer) { - WebRTCPeerConnectionJS *peer = static_cast<WebRTCPeerConnectionJS *>(obj); - peer->emit_signal("session_description_created", String(p_type), String(p_offer)); +void WebRTCPeerConnectionJS::_on_session_created(void *p_obj, const char *p_type, const char *p_session) { + WebRTCPeerConnectionJS *peer = static_cast<WebRTCPeerConnectionJS *>(p_obj); + peer->emit_signal("session_description_created", String(p_type), String(p_session)); } -EMSCRIPTEN_KEEPALIVE void _emrtc_on_connection_state_changed(void *obj) { - WebRTCPeerConnectionJS *peer = static_cast<WebRTCPeerConnectionJS *>(obj); - peer->_on_connection_state_changed(); +void WebRTCPeerConnectionJS::_on_connection_state_changed(void *p_obj, int p_state) { + WebRTCPeerConnectionJS *peer = static_cast<WebRTCPeerConnectionJS *>(p_obj); + peer->_conn_state = (ConnectionState)p_state; } -EMSCRIPTEN_KEEPALIVE void _emrtc_on_error() { +void WebRTCPeerConnectionJS::_on_error(void *p_obj) { ERR_PRINT("RTCPeerConnection error!"); } -EMSCRIPTEN_KEEPALIVE void _emrtc_emit_channel(void *obj, int p_id) { - WebRTCPeerConnectionJS *peer = static_cast<WebRTCPeerConnectionJS *>(obj); +void WebRTCPeerConnectionJS::_on_data_channel(void *p_obj, int p_id) { + WebRTCPeerConnectionJS *peer = static_cast<WebRTCPeerConnectionJS *>(p_obj); peer->emit_signal("data_channel_received", Ref<WebRTCDataChannelJS>(new WebRTCDataChannelJS(p_id))); } -} - -void _emrtc_create_pc(int p_id, const Dictionary &p_config) { - String config = JSON::print(p_config); - /* clang-format off */ - EM_ASM({ - var dict = Module.IDHandler.get($0); - var c_ptr = dict["ptr"]; - var config = JSON.parse(UTF8ToString($1)); - // Setup local connaction - var conn = null; - try { - conn = new RTCPeerConnection(config); - } catch (e) { - console.log(e); - return; - } - conn.oniceconnectionstatechange = function(event) { - if (!Module.IDHandler.get($0)) return; - ccall("_emrtc_on_connection_state_changed", "void", ["number"], [c_ptr]); - }; - conn.onicecandidate = function(event) { - if (!Module.IDHandler.get($0)) return; - if (!event.candidate) return; - - var c = event.candidate; - // should emit on ice candidate - ccall("_emrtc_on_ice_candidate", - "void", - ["number", "string", "number", "string"], - [c_ptr, c.sdpMid, c.sdpMLineIndex, c.candidate] - ); - }; - conn.ondatachannel = function (evt) { - var dict = Module.IDHandler.get($0); - if (!dict) { - return; - } - var id = Module.IDHandler.add({"channel": evt.channel, "ptr": null}); - ccall("_emrtc_emit_channel", - "void", - ["number", "number"], - [c_ptr, id] - ); - }; - dict["conn"] = conn; - }, p_id, config.utf8().get_data()); - /* clang-format on */ -} - -void WebRTCPeerConnectionJS::_on_connection_state_changed() { - /* clang-format off */ - _conn_state = (ConnectionState)EM_ASM_INT({ - var dict = Module.IDHandler.get($0); - if (!dict) return 5; // CLOSED - var conn = dict["conn"]; - switch(conn.iceConnectionState) { - case "new": - return 0; - case "checking": - return 1; - case "connected": - case "completed": - return 2; - case "disconnected": - return 3; - case "failed": - return 4; - case "closed": - return 5; - } - return 5; // CLOSED - }, _js_id); - /* clang-format on */ -} void WebRTCPeerConnectionJS::close() { - /* clang-format off */ - EM_ASM({ - var dict = Module.IDHandler.get($0); - if (!dict) return; - if (dict["conn"]) { - dict["conn"].close(); - } - }, _js_id); - /* clang-format on */ + godot_js_rtc_pc_close(_js_id); _conn_state = STATE_CLOSED; } @@ -154,46 +70,12 @@ Error WebRTCPeerConnectionJS::create_offer() { ERR_FAIL_COND_V(_conn_state != STATE_NEW, FAILED); _conn_state = STATE_CONNECTING; - /* clang-format off */ - EM_ASM({ - var dict = Module.IDHandler.get($0); - var conn = dict["conn"]; - var c_ptr = dict["ptr"]; - var onError = function(error) { - console.error(error); - ccall("_emrtc_on_error", "void", [], []); - }; - var onCreated = function(offer) { - ccall("_emrtc_session_description_created", - "void", - ["number", "string", "string"], - [c_ptr, offer.type, offer.sdp] - ); - }; - conn.createOffer().then(onCreated).catch(onError); - }, _js_id); - /* clang-format on */ + godot_js_rtc_pc_offer_create(_js_id, this, &_on_session_created, &_on_error); return OK; } Error WebRTCPeerConnectionJS::set_local_description(String type, String sdp) { - /* clang-format off */ - EM_ASM({ - var dict = Module.IDHandler.get($0); - var conn = dict["conn"]; - var c_ptr = dict["ptr"]; - var type = UTF8ToString($1); - var sdp = UTF8ToString($2); - var onError = function(error) { - console.error(error); - ccall("_emrtc_on_error", "void", [], []); - }; - conn.setLocalDescription({ - "sdp": sdp, - "type": type - }).catch(onError); - }, _js_id, type.utf8().get_data(), sdp.utf8().get_data()); - /* clang-format on */ + godot_js_rtc_pc_local_description_set(_js_id, type.utf8().get_data(), sdp.utf8().get_data(), this, &_on_error); return OK; } @@ -202,83 +84,32 @@ Error WebRTCPeerConnectionJS::set_remote_description(String type, String sdp) { ERR_FAIL_COND_V(_conn_state != STATE_NEW, FAILED); _conn_state = STATE_CONNECTING; } - /* clang-format off */ - EM_ASM({ - var dict = Module.IDHandler.get($0); - var conn = dict["conn"]; - var c_ptr = dict["ptr"]; - var type = UTF8ToString($1); - var sdp = UTF8ToString($2); - - var onError = function(error) { - console.error(error); - ccall("_emrtc_on_error", "void", [], []); - }; - var onCreated = function(offer) { - ccall("_emrtc_session_description_created", - "void", - ["number", "string", "string"], - [c_ptr, offer.type, offer.sdp] - ); - }; - var onSet = function() { - if (type != "offer") { - return; - } - conn.createAnswer().then(onCreated); - }; - conn.setRemoteDescription({ - "sdp": sdp, - "type": type - }).then(onSet).catch(onError); - }, _js_id, type.utf8().get_data(), sdp.utf8().get_data()); - /* clang-format on */ + godot_js_rtc_pc_remote_description_set(_js_id, type.utf8().get_data(), sdp.utf8().get_data(), this, &_on_session_created, &_on_error); return OK; } Error WebRTCPeerConnectionJS::add_ice_candidate(String sdpMidName, int sdpMlineIndexName, String sdpName) { - /* clang-format off */ - EM_ASM({ - var dict = Module.IDHandler.get($0); - var conn = dict["conn"]; - var c_ptr = dict["ptr"]; - var sdpMidName = UTF8ToString($1); - var sdpMlineIndexName = UTF8ToString($2); - var sdpName = UTF8ToString($3); - conn.addIceCandidate(new RTCIceCandidate({ - "candidate": sdpName, - "sdpMid": sdpMidName, - "sdpMlineIndex": sdpMlineIndexName - })); - }, _js_id, sdpMidName.utf8().get_data(), sdpMlineIndexName, sdpName.utf8().get_data()); - /* clang-format on */ + godot_js_rtc_pc_ice_candidate_add(_js_id, sdpMidName.utf8().get_data(), sdpMlineIndexName, sdpName.utf8().get_data()); return OK; } Error WebRTCPeerConnectionJS::initialize(Dictionary p_config) { - _emrtc_create_pc(_js_id, p_config); - return OK; + if (_js_id) { + godot_js_rtc_pc_destroy(_js_id); + _js_id = 0; + } + _conn_state = STATE_NEW; + + String config = JSON::print(p_config); + _js_id = godot_js_rtc_pc_create(config.utf8().get_data(), this, &_on_connection_state_changed, &_on_ice_candidate, &_on_data_channel); + return _js_id ? OK : FAILED; } Ref<WebRTCDataChannel> WebRTCPeerConnectionJS::create_data_channel(String p_channel, Dictionary p_channel_config) { + ERR_FAIL_COND_V(_conn_state != STATE_NEW, nullptr); + String config = JSON::print(p_channel_config); - /* clang-format off */ - int id = EM_ASM_INT({ - try { - var dict = Module.IDHandler.get($0); - if (!dict) return 0; - var label = UTF8ToString($1); - var config = JSON.parse(UTF8ToString($2)); - var conn = dict["conn"]; - return Module.IDHandler.add({ - "channel": conn.createDataChannel(label, config), - "ptr": null - }) - } catch (e) { - return 0; - } - }, _js_id, p_channel.utf8().get_data(), config.utf8().get_data()); - /* clang-format on */ + int id = godot_js_rtc_pc_datachannel_create(_js_id, p_channel.utf8().get_data(), config.utf8().get_data()); ERR_FAIL_COND_V(id == 0, nullptr); return memnew(WebRTCDataChannelJS(id)); } @@ -293,22 +124,17 @@ WebRTCPeerConnection::ConnectionState WebRTCPeerConnectionJS::get_connection_sta WebRTCPeerConnectionJS::WebRTCPeerConnectionJS() { _conn_state = STATE_NEW; + _js_id = 0; - /* clang-format off */ - _js_id = EM_ASM_INT({ - return Module.IDHandler.add({"conn": null, "ptr": $0}); - }, this); - /* clang-format on */ Dictionary config; - _emrtc_create_pc(_js_id, config); + initialize(config); } WebRTCPeerConnectionJS::~WebRTCPeerConnectionJS() { close(); - /* clang-format off */ - EM_ASM({ - Module.IDHandler.remove($0); - }, _js_id); - /* clang-format on */ + if (_js_id) { + godot_js_rtc_pc_destroy(_js_id); + _js_id = 0; + } }; #endif diff --git a/modules/webrtc/webrtc_peer_connection_js.h b/modules/webrtc/webrtc_peer_connection_js.h index cdaf3068e3..e33dd5f259 100644 --- a/modules/webrtc/webrtc_peer_connection_js.h +++ b/modules/webrtc/webrtc_peer_connection_js.h @@ -35,16 +35,37 @@ #include "webrtc_peer_connection.h" +extern "C" { +typedef void (*RTCOnIceConnectionStateChange)(void *p_obj, int p_state); +typedef void (*RTCOnIceCandidate)(void *p_obj, const char *p_mid, int p_mline_idx, const char *p_candidate); +typedef void (*RTCOnDataChannel)(void *p_obj, int p_id); +typedef void (*RTCOnSession)(void *p_obj, const char *p_type, const char *p_sdp); +typedef void (*RTCOnError)(void *p_obj); +extern int godot_js_rtc_pc_create(const char *p_config, void *p_obj, RTCOnIceConnectionStateChange p_on_state_change, RTCOnIceCandidate p_on_candidate, RTCOnDataChannel p_on_datachannel); +extern void godot_js_rtc_pc_close(int p_id); +extern void godot_js_rtc_pc_destroy(int p_id); +extern void godot_js_rtc_pc_offer_create(int p_id, void *p_obj, RTCOnSession p_on_session, RTCOnError p_on_error); +extern void godot_js_rtc_pc_local_description_set(int p_id, const char *p_type, const char *p_sdp, void *p_obj, RTCOnError p_on_error); +extern void godot_js_rtc_pc_remote_description_set(int p_id, const char *p_type, const char *p_sdp, void *p_obj, RTCOnSession p_on_session, RTCOnError p_on_error); +extern void godot_js_rtc_pc_ice_candidate_add(int p_id, const char *p_mid_name, int p_mline_idx, const char *p_sdo); +extern int godot_js_rtc_pc_datachannel_create(int p_id, const char *p_label, const char *p_config); +} + class WebRTCPeerConnectionJS : public WebRTCPeerConnection { private: int _js_id; ConnectionState _conn_state; + static void _on_connection_state_changed(void *p_obj, int p_state); + static void _on_ice_candidate(void *p_obj, const char *p_mid_name, int p_mline_idx, const char *p_candidate); + static void _on_data_channel(void *p_obj, int p_channel); + static void _on_session_created(void *p_obj, const char *p_type, const char *p_session); + static void _on_error(void *p_obj); + public: static WebRTCPeerConnection *_create() { return memnew(WebRTCPeerConnectionJS); } static void make_default() { WebRTCPeerConnection::_create = WebRTCPeerConnectionJS::_create; } - void _on_connection_state_changed(); virtual ConnectionState get_connection_state() const; virtual Error initialize(Dictionary configuration = Dictionary()); |