summaryrefslogtreecommitdiff
path: root/modules/webrtc/webrtc_peer_connection_js.cpp
blob: 9758ab3644df6defe39ed12dd2f2f7e69ce02e03 (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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
/*************************************************************************/
/*  webrtc_peer_connection_js.cpp                                        */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2019 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.                */
/*************************************************************************/

#ifdef JAVASCRIPT_ENABLED

#include "webrtc_peer_connection_js.h"

#include "webrtc_data_channel_js.h"

#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));
}

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));
}

EMSCRIPTEN_KEEPALIVE void _emrtc_on_connection_state_changed(void *obj) {
	WebRTCPeerConnectionJS *peer = static_cast<WebRTCPeerConnectionJS *>(obj);
	peer->_on_connection_state_changed();
}

EMSCRIPTEN_KEEPALIVE void _emrtc_on_error() {
	ERR_PRINT("RTCPeerConnection error!");
}

EMSCRIPTEN_KEEPALIVE void _emrtc_emit_channel(void *obj, int p_id) {
	WebRTCPeerConnectionJS *peer = static_cast<WebRTCPeerConnectionJS *>(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 */
	_conn_state = STATE_CLOSED;
}

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 */
	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 */
	return OK;
}

Error WebRTCPeerConnectionJS::set_remote_description(String type, String sdp) {
	if (type == "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 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 */
	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 */
	return OK;
}

Error WebRTCPeerConnectionJS::initialize(Dictionary p_config) {
	_emrtc_create_pc(_js_id, p_config);
	return OK;
}

Ref<WebRTCDataChannel> WebRTCPeerConnectionJS::create_data_channel(String p_channel, Dictionary p_channel_config) {
	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 */
	ERR_FAIL_COND_V(id == 0, NULL);
	return memnew(WebRTCDataChannelJS(id));
}

Error WebRTCPeerConnectionJS::poll() {
	return OK;
}

WebRTCPeerConnection::ConnectionState WebRTCPeerConnectionJS::get_connection_state() const {
	return _conn_state;
}

WebRTCPeerConnectionJS::WebRTCPeerConnectionJS() {
	_conn_state = STATE_NEW;

	/* 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);
}

WebRTCPeerConnectionJS::~WebRTCPeerConnectionJS() {
	close();
	/* clang-format off */
	EM_ASM({
		Module.IDHandler.remove($0);
	}, _js_id);
	/* clang-format on */
};
#endif