Debian Codegraph @

modules/webrtc/webrtc_multiplayer_peer.cpp

raw symbols SCIP
1 /**************************************************************************/
2 /* webrtc_multiplayer_peer.cpp */
3 /**************************************************************************/
4 /* This file is part of: */
5 /* GODOT ENGINE */
6 /* https://godotengine.org */
7 /**************************************************************************/
8 /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
9 /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
10 /* */
11 /* Permission is hereby granted, free of charge, to any person obtaining */
12 /* a copy of this software and associated documentation files (the */
13 /* "Software"), to deal in the Software without restriction, including */
14 /* without limitation the rights to use, copy, modify, merge, publish, */
15 /* distribute, sublicense, and/or sell copies of the Software, and to */
16 /* permit persons to whom the Software is furnished to do so, subject to */
17 /* the following conditions: */
18 /* */
19 /* The above copyright notice and this permission notice shall be */
20 /* included in all copies or substantial portions of the Software. */
21 /* */
22 /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
23 /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
24 /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
25 /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
26 /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
27 /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
28 /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
29 /**************************************************************************/
30
31 #include "webrtc_multiplayer_peer.h"
32
33 void WebRTCMultiplayerPeer::_bind_methods() {
34 ClassDB::bind_method(D_METHOD("create_server", "channels_config"), &WebRTCMultiplayerPeer::create_server, DEFVAL(Array()));
35 ClassDB::bind_method(D_METHOD("create_client", "peer_id", "channels_config"), &WebRTCMultiplayerPeer::create_client, DEFVAL(Array()));
36 ClassDB::bind_method(D_METHOD("create_mesh", "peer_id", "channels_config"), &WebRTCMultiplayerPeer::create_mesh, DEFVAL(Array()));
37 ClassDB::bind_method(D_METHOD("add_peer", "peer", "peer_id", "unreliable_lifetime"), &WebRTCMultiplayerPeer::add_peer, DEFVAL(1));
38 ClassDB::bind_method(D_METHOD("remove_peer", "peer_id"), &WebRTCMultiplayerPeer::remove_peer);
39 ClassDB::bind_method(D_METHOD("has_peer", "peer_id"), &WebRTCMultiplayerPeer::has_peer);
40 ClassDB::bind_method(D_METHOD("get_peer", "peer_id"), &WebRTCMultiplayerPeer::get_peer);
41 ClassDB::bind_method(D_METHOD("get_peers"), &WebRTCMultiplayerPeer::get_peers);
42 }
43
44 void WebRTCMultiplayerPeer::set_target_peer(int p_peer_id) {
45 target_peer = p_peer_id;
46 }
47
48 /* Returns the ID of the MultiplayerPeer who sent the most recent packet: */
49 int WebRTCMultiplayerPeer::get_packet_peer() const {
50 return next_packet_peer;
51 }
52
53 int WebRTCMultiplayerPeer::get_packet_channel() const {
54 return next_packet_channel < CH_RESERVED_MAX ? 0 : next_packet_channel - CH_RESERVED_MAX + 1;
55 }
56
57 MultiplayerPeer::TransferMode WebRTCMultiplayerPeer::get_packet_mode() const {
58 ERR_FAIL_INDEX_V(next_packet_channel, channels_modes.size(), TRANSFER_MODE_RELIABLE);
59 return channels_modes.get(next_packet_channel);
60 }
61
62 bool WebRTCMultiplayerPeer::is_server() const {
63 return unique_id == TARGET_PEER_SERVER;
64 }
65
66 void WebRTCMultiplayerPeer::poll() {
67 if (peer_map.is_empty()) {
68 return;
69 }
70
71 List<int> remove;
72 List<int> add;
73 for (KeyValue<int, Ref<ConnectedPeer>> &E : peer_map) {
74 Ref<ConnectedPeer> peer = E.value;
75 peer->connection->poll();
76 // Check peer state
77 switch (peer->connection->get_connection_state()) {
78 case WebRTCPeerConnection::STATE_NEW:
79 case WebRTCPeerConnection::STATE_CONNECTING:
80 // Go to next peer, not ready yet.
81 continue;
82 case WebRTCPeerConnection::STATE_CONNECTED:
83 // Good to go, go ahead and check channel state.
84 break;
85 default:
86 // Peer is closed or in error state. Got to next peer.
87 remove.push_back(E.key);
88 continue;
89 }
90 // Check channels state
91 int ready = 0;
92 for (List<Ref<WebRTCDataChannel>>::Element *C = peer->channels.front(); C && C->get().is_valid(); C = C->next()) {
93 Ref<WebRTCDataChannel> ch = C->get();
94 switch (ch->get_ready_state()) {
95 case WebRTCDataChannel::STATE_CONNECTING:
96 continue;
97 case WebRTCDataChannel::STATE_OPEN:
98 ready++;
99 continue;
100 default:
101 // Channel was closed or in error state, remove peer id.
102 remove.push_back(E.key);
103 }
104 // We got a closed channel break out, the peer will be removed.
105 break;
106 }
107 // This peer has newly connected, and all channels are now open.
108 if (ready == peer->channels.size() && !peer->connected) {
109 peer->connected = true;
110 add.push_back(E.key);
111 }
112 }
113 // Remove disconnected peers
114 for (int &E : remove) {
115 remove_peer(E);
116 if (next_packet_peer == E) {
117 next_packet_peer = 0;
118 }
119 }
120 // Signal newly connected peers
121 for (int &E : add) {
122 // Already connected to server: simply notify new peer.
123 if (network_mode == MODE_CLIENT) {
124 ERR_CONTINUE(E != TARGET_PEER_SERVER); // Bug.
125 // Server connected.
126 connection_status = CONNECTION_CONNECTED;
127 emit_signal(SNAME("peer_connected"), TARGET_PEER_SERVER);
128 } else {
129 emit_signal(SNAME("peer_connected"), E);
130 }
131 }
132 // Fetch next packet
133 if (next_packet_peer == 0) {
134 _find_next_peer();
135 }
136 }
137
138 void WebRTCMultiplayerPeer::_find_next_peer() {
139 HashMap<int, Ref<ConnectedPeer>>::Iterator E = peer_map.find(next_packet_peer);
140 if (E) {
141 ++E;
142 }
143 // After last.
144 while (E) {
145 if (!E->value->connected) {
146 ++E;
147 continue;
148 }
149 int idx = 0;
150 for (const Ref<WebRTCDataChannel> &F : E->value->channels) {
151 if (F->get_available_packet_count()) {
152 next_packet_channel = idx;
153 next_packet_peer = E->key;
154 return;
155 }
156 idx++;
157 }
158 ++E;
159 }
160 E = peer_map.begin();
161 // Before last
162 while (E) {
163 if (!E->value->connected) {
164 ++E;
165 continue;
166 }
167 int idx = 0;
168 for (const Ref<WebRTCDataChannel> &F : E->value->channels) {
169 if (F->get_available_packet_count()) {
170 next_packet_channel = idx;
171 next_packet_peer = E->key;
172 return;
173 }
174 idx++;
175 }
176 if (E->key == (int)next_packet_peer) {
177 break;
178 }
179 ++E;
180 }
181 // No packet found
182 next_packet_channel = 0;
183 next_packet_peer = 0;
184 }
185
186 MultiplayerPeer::ConnectionStatus WebRTCMultiplayerPeer::get_connection_status() const {
187 return connection_status;
188 }
189
190 Error WebRTCMultiplayerPeer::create_server(const Array &p_channels_config) {
191 return _initialize(1, MODE_SERVER, p_channels_config);
192 }
193
194 Error WebRTCMultiplayerPeer::create_client(int p_self_id, const Array &p_channels_config) {
195 ERR_FAIL_COND_V_MSG(p_self_id == 1, ERR_INVALID_PARAMETER, "Clients cannot have ID 1.");
196 return _initialize(p_self_id, MODE_CLIENT, p_channels_config);
197 }
198
199 Error WebRTCMultiplayerPeer::create_mesh(int p_self_id, const Array &p_channels_config) {
200 return _initialize(p_self_id, MODE_MESH, p_channels_config);
201 }
202
203 Error WebRTCMultiplayerPeer::_initialize(int p_self_id, NetworkMode p_mode, const Array &p_channels_config) {
204 ERR_FAIL_COND_V(p_self_id < 1 || p_self_id > ~(1 << 31), ERR_INVALID_PARAMETER);
205 channels_config.clear();
206 channels_modes.clear();
207 channels_modes.push_back(TRANSFER_MODE_RELIABLE);
208 channels_modes.push_back(TRANSFER_MODE_UNRELIABLE_ORDERED);
209 channels_modes.push_back(TRANSFER_MODE_UNRELIABLE);
210 for (int i = 0; i < p_channels_config.size(); i++) {
211 ERR_FAIL_COND_V_MSG(p_channels_config[i].get_type() != Variant::INT, ERR_INVALID_PARAMETER, "The 'channels_config' array must contain only enum values from 'MultiplayerPeer.TransferMode'");
212 int mode = p_channels_config[i].operator int();
213 // Initialize data channel configurations.
214 Dictionary cfg;
215 cfg["id"] = CH_RESERVED_MAX + i + 1;
216 cfg["negotiated"] = true;
217 cfg["ordered"] = true;
218
219 switch (mode) {
220 case TRANSFER_MODE_UNRELIABLE_ORDERED:
221 cfg["maxPacketLifetime"] = 1;
222 break;
223 case TRANSFER_MODE_UNRELIABLE:
224 cfg["maxPacketLifetime"] = 1;
225 cfg["ordered"] = false;
226 break;
227 case TRANSFER_MODE_RELIABLE:
228 break;
229 default:
230 ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, vformat("The 'channels_config' array must contain only enum values from 'MultiplayerPeer.TransferMode'. Got: %d", mode));
231 }
232 channels_config.push_back(cfg);
233 channels_modes.push_back((TransferMode)mode);
234 }
235
236 unique_id = p_self_id;
237 network_mode = p_mode;
238
239 // Mesh and server are always connected
240 if (p_mode != MODE_CLIENT) {
241 connection_status = CONNECTION_CONNECTED;
242 } else {
243 connection_status = CONNECTION_CONNECTING;
244 }
245 return OK;
246 }
247
248 bool WebRTCMultiplayerPeer::is_server_relay_supported() const {
249 return network_mode == MODE_SERVER || network_mode == MODE_CLIENT;
250 }
251
252 int WebRTCMultiplayerPeer::get_unique_id() const {
253 ERR_FAIL_COND_V(connection_status == CONNECTION_DISCONNECTED, 1);
254 return unique_id;
255 }
256
257 void WebRTCMultiplayerPeer::_peer_to_dict(const Ref<ConnectedPeer> &p_connected_peer, Dictionary &r_dict) {
258 Array channels;
259 for (Ref<WebRTCDataChannel> &F : p_connected_peer->channels) {
260 channels.push_back(F);
261 }
262 r_dict["connection"] = p_connected_peer->connection;
263 r_dict["connected"] = p_connected_peer->connected;
264 r_dict["channels"] = channels;
265 }
266
267 bool WebRTCMultiplayerPeer::has_peer(int p_peer_id) {
268 return peer_map.has(p_peer_id);
269 }
270
271 Dictionary WebRTCMultiplayerPeer::get_peer(int p_peer_id) {
272 ERR_FAIL_COND_V(!peer_map.has(p_peer_id), Dictionary());
273 Dictionary out;
274 _peer_to_dict(peer_map[p_peer_id], out);
275 return out;
276 }
277
278 Dictionary WebRTCMultiplayerPeer::get_peers() {
279 Dictionary out;
280 for (const KeyValue<int, Ref<ConnectedPeer>> &E : peer_map) {
281 Dictionary d;
282 _peer_to_dict(E.value, d);
283 out[E.key] = d;
284 }
285 return out;
286 }
287
288 Error WebRTCMultiplayerPeer::add_peer(const Ref<WebRTCPeerConnection> &p_peer, int p_peer_id, int p_unreliable_lifetime) {
289 ERR_FAIL_COND_V(network_mode == MODE_NONE, ERR_UNCONFIGURED);
290 ERR_FAIL_COND_V(network_mode == MODE_CLIENT && p_peer_id != 1, ERR_INVALID_PARAMETER);
291 ERR_FAIL_COND_V(network_mode == MODE_SERVER && p_peer_id == 1, ERR_INVALID_PARAMETER);
292 ERR_FAIL_COND_V(p_peer_id < 1 || p_peer_id > ~(1 << 31), ERR_INVALID_PARAMETER);
293 ERR_FAIL_COND_V(p_unreliable_lifetime < 0, ERR_INVALID_PARAMETER);
294 ERR_FAIL_COND_V(is_refusing_new_connections(), ERR_UNAUTHORIZED);
295 // Peer must be valid, and in new state (to create data channels)
296 ERR_FAIL_COND_V(p_peer.is_null(), ERR_INVALID_PARAMETER);
297 ERR_FAIL_COND_V(p_peer->get_connection_state() != WebRTCPeerConnection::STATE_NEW, ERR_INVALID_PARAMETER);
298
299 Ref<ConnectedPeer> peer = memnew(ConnectedPeer);
300 peer->connection = p_peer;
301
302 // Initialize data channels
303 Dictionary cfg;
304 cfg["negotiated"] = true;
305 cfg["ordered"] = true;
306
307 cfg["id"] = 1;
308 peer->channels.get(CH_RELIABLE) = p_peer->create_data_channel("reliable", cfg);
309 ERR_FAIL_COND_V(peer->channels.get(CH_RELIABLE).is_null(), FAILED);
310
311 cfg["id"] = 2;
312 cfg["maxPacketLifetime"] = p_unreliable_lifetime;
313 peer->channels.get(CH_ORDERED) = p_peer->create_data_channel("ordered", cfg);
314 ERR_FAIL_COND_V(peer->channels.get(CH_ORDERED).is_null(), FAILED);
315
316 cfg["id"] = 3;
317 cfg["ordered"] = false;
318 peer->channels.get(CH_UNRELIABLE) = p_peer->create_data_channel("unreliable", cfg);
319 ERR_FAIL_COND_V(peer->channels.get(CH_UNRELIABLE).is_null(), FAILED);
320
321 for (const Dictionary &dict : channels_config) {
322 Ref<WebRTCDataChannel> ch = p_peer->create_data_channel(String::num_int64(dict["id"]), dict);
323 ERR_FAIL_COND_V(ch.is_null(), FAILED);
324 peer->channels.push_back(ch);
325 }
326
327 peer_map[p_peer_id] = peer; // add the new peer connection to the peer_map
328
329 return OK;
330 }
331
332 void WebRTCMultiplayerPeer::remove_peer(int p_peer_id) {
333 ERR_FAIL_COND(!peer_map.has(p_peer_id));
334 Ref<ConnectedPeer> peer = peer_map[p_peer_id];
335 peer_map.erase(p_peer_id);
336 if (peer->connected) {
337 peer->connected = false;
338 emit_signal(SNAME("peer_disconnected"), p_peer_id);
339 if (network_mode == MODE_CLIENT && p_peer_id == TARGET_PEER_SERVER) {
340 connection_status = CONNECTION_DISCONNECTED;
341 }
342 }
343 }
344
345 void WebRTCMultiplayerPeer::disconnect_peer(int p_peer_id, bool p_force) {
346 ERR_FAIL_COND(!peer_map.has(p_peer_id));
347 if (p_force) {
348 peer_map.erase(p_peer_id);
349 if (network_mode == MODE_CLIENT && p_peer_id == TARGET_PEER_SERVER) {
350 connection_status = CONNECTION_DISCONNECTED;
351 }
352 } else {
353 peer_map[p_peer_id]->connection->close(); // Will be removed during next poll.
354 }
355 }
356
357 Error WebRTCMultiplayerPeer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) {
358 // Peer not available
359 if (next_packet_peer == 0 || !peer_map.has(next_packet_peer)) {
360 _find_next_peer();
361 ERR_FAIL_V(ERR_UNAVAILABLE);
362 }
363 for (Ref<WebRTCDataChannel> &E : peer_map[next_packet_peer]->channels) {
364 if (E->get_available_packet_count()) {
365 Error err = E->get_packet(r_buffer, r_buffer_size);
366 _find_next_peer();
367 return err;
368 }
369 }
370 // Channels for that peer were empty. Bug?
371 _find_next_peer();
372 ERR_FAIL_V(ERR_BUG);
373 }
374
375 Error WebRTCMultiplayerPeer::put_packet(const uint8_t *p_buffer, int p_buffer_size) {
376 ERR_FAIL_COND_V(connection_status == CONNECTION_DISCONNECTED, ERR_UNCONFIGURED);
377
378 int ch = get_transfer_channel();
379 if (ch == 0) {
380 switch (get_transfer_mode()) {
381 case TRANSFER_MODE_RELIABLE:
382 ch = CH_RELIABLE;
383 break;
384 case TRANSFER_MODE_UNRELIABLE_ORDERED:
385 ch = CH_ORDERED;
386 break;
387 case TRANSFER_MODE_UNRELIABLE:
388 ch = CH_UNRELIABLE;
389 break;
390 }
391 } else {
392 ch += CH_RESERVED_MAX - 1;
393 }
394
395 if (target_peer > 0) {
396 HashMap<int, Ref<ConnectedPeer>>::Iterator E = peer_map.find(target_peer);
397 ERR_FAIL_COND_V_MSG(!E, ERR_INVALID_PARAMETER, "Invalid target peer: " + itos(target_peer) + ".");
398
399 ERR_FAIL_COND_V_MSG(E->value->channels.size() <= ch, ERR_INVALID_PARAMETER, vformat("Unable to send packet on channel %d, max channels: %d", ch, E->value->channels.size()));
400 ERR_FAIL_COND_V(E->value->channels.get(ch).is_null(), ERR_BUG);
401 return E->value->channels.get(ch)->put_packet(p_buffer, p_buffer_size);
402
403 } else {
404 int exclude = -target_peer;
405
406 for (KeyValue<int, Ref<ConnectedPeer>> &F : peer_map) {
407 // Exclude packet. If target_peer == 0 then don't exclude any packets
408 if (target_peer != 0 && F.key == exclude) {
409 continue;
410 }
411
412 ERR_CONTINUE_MSG(F.value->channels.size() <= ch, vformat("Unable to send packet on channel %d, max channels: %d", ch, F.value->channels.size()));
413 ERR_CONTINUE(F.value->channels.get(ch).is_null());
414 F.value->channels.get(ch)->put_packet(p_buffer, p_buffer_size);
415 }
416 }
417 return OK;
418 }
419
420 int WebRTCMultiplayerPeer::get_available_packet_count() const {
421 if (next_packet_peer == 0) {
422 return 0; // To be sure next call to get_packet works if size > 0 .
423 }
424 int size = 0;
425 for (const KeyValue<int, Ref<ConnectedPeer>> &E : peer_map) {
426 if (!E.value->connected) {
427 continue;
428 }
429 for (const Ref<WebRTCDataChannel> &F : E.value->channels) {
430 size += F->get_available_packet_count();
431 }
432 }
433 return size;
434 }
435
436 int WebRTCMultiplayerPeer::get_max_packet_size() const {
437 return 1200;
438 }
439
440 void WebRTCMultiplayerPeer::close() {
441 peer_map.clear();
442 channels_config.clear();
443 unique_id = 0;
444 next_packet_peer = 0;
445 next_packet_channel = 0;
446 target_peer = 0;
447 network_mode = MODE_NONE;
448 connection_status = CONNECTION_DISCONNECTED;
449 }
450
451 WebRTCMultiplayerPeer::~WebRTCMultiplayerPeer() {
452 close();
453 }