webrtc_data_channel_js.cpp 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. /*************************************************************************/
  2. /* webrtc_data_channel_js.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
  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. #ifdef JAVASCRIPT_ENABLED
  31. #include "webrtc_data_channel_js.h"
  32. #include "emscripten.h"
  33. extern "C" {
  34. EMSCRIPTEN_KEEPALIVE void _emrtc_on_ch_error(void *obj) {
  35. WebRTCDataChannelJS *peer = static_cast<WebRTCDataChannelJS *>(obj);
  36. peer->_on_error();
  37. }
  38. EMSCRIPTEN_KEEPALIVE void _emrtc_on_ch_open(void *obj) {
  39. WebRTCDataChannelJS *peer = static_cast<WebRTCDataChannelJS *>(obj);
  40. peer->_on_open();
  41. }
  42. EMSCRIPTEN_KEEPALIVE void _emrtc_on_ch_close(void *obj) {
  43. WebRTCDataChannelJS *peer = static_cast<WebRTCDataChannelJS *>(obj);
  44. peer->_on_close();
  45. }
  46. EMSCRIPTEN_KEEPALIVE void _emrtc_on_ch_message(void *obj, uint8_t *p_data, uint32_t p_size, bool p_is_string) {
  47. WebRTCDataChannelJS *peer = static_cast<WebRTCDataChannelJS *>(obj);
  48. peer->_on_message(p_data, p_size, p_is_string);
  49. }
  50. }
  51. void WebRTCDataChannelJS::_on_open() {
  52. in_buffer.resize(_in_buffer_shift);
  53. }
  54. void WebRTCDataChannelJS::_on_close() {
  55. close();
  56. }
  57. void WebRTCDataChannelJS::_on_error() {
  58. close();
  59. }
  60. void WebRTCDataChannelJS::_on_message(uint8_t *p_data, uint32_t p_size, bool p_is_string) {
  61. if (in_buffer.space_left() < (int)(p_size + 5)) {
  62. ERR_EXPLAIN("Buffer full! Dropping data");
  63. ERR_FAIL();
  64. }
  65. uint8_t is_string = p_is_string ? 1 : 0;
  66. in_buffer.write((uint8_t *)&p_size, 4);
  67. in_buffer.write((uint8_t *)&is_string, 1);
  68. in_buffer.write(p_data, p_size);
  69. queue_count++;
  70. }
  71. void WebRTCDataChannelJS::close() {
  72. in_buffer.resize(0);
  73. queue_count = 0;
  74. _was_string = false;
  75. /* clang-format off */
  76. EM_ASM({
  77. var dict = Module.IDHandler.get($0);
  78. if (!dict) return;
  79. var channel = dict["channel"];
  80. channel.onopen = null;
  81. channel.onclose = null;
  82. channel.onerror = null;
  83. channel.onmessage = null;
  84. channel.close();
  85. }, _js_id);
  86. /* clang-format on */
  87. }
  88. Error WebRTCDataChannelJS::poll() {
  89. return OK;
  90. }
  91. WebRTCDataChannelJS::ChannelState WebRTCDataChannelJS::get_ready_state() const {
  92. /* clang-format off */
  93. return (ChannelState) EM_ASM_INT({
  94. var dict = Module.IDHandler.get($0);
  95. if (!dict) return 3; // CLOSED
  96. var channel = dict["channel"];
  97. switch(channel.readyState) {
  98. case "connecting":
  99. return 0;
  100. case "open":
  101. return 1;
  102. case "closing":
  103. return 2;
  104. case "closed":
  105. return 3;
  106. }
  107. return 3; // CLOSED
  108. }, _js_id);
  109. /* clang-format on */
  110. }
  111. int WebRTCDataChannelJS::get_available_packet_count() const {
  112. return queue_count;
  113. }
  114. Error WebRTCDataChannelJS::get_packet(const uint8_t **r_buffer, int &r_buffer_size) {
  115. ERR_FAIL_COND_V(get_ready_state() != STATE_OPEN, ERR_UNCONFIGURED);
  116. if (queue_count == 0)
  117. return ERR_UNAVAILABLE;
  118. uint32_t to_read = 0;
  119. uint32_t left = 0;
  120. uint8_t is_string = 0;
  121. r_buffer_size = 0;
  122. in_buffer.read((uint8_t *)&to_read, 4);
  123. --queue_count;
  124. left = in_buffer.data_left();
  125. if (left < to_read + 1) {
  126. in_buffer.advance_read(left);
  127. return FAILED;
  128. }
  129. in_buffer.read(&is_string, 1);
  130. _was_string = is_string == 1;
  131. in_buffer.read(packet_buffer, to_read);
  132. *r_buffer = packet_buffer;
  133. r_buffer_size = to_read;
  134. return OK;
  135. }
  136. Error WebRTCDataChannelJS::put_packet(const uint8_t *p_buffer, int p_buffer_size) {
  137. ERR_FAIL_COND_V(get_ready_state() != STATE_OPEN, ERR_UNCONFIGURED);
  138. int is_bin = _write_mode == WebRTCDataChannel::WRITE_MODE_BINARY ? 1 : 0;
  139. /* clang-format off */
  140. EM_ASM({
  141. var dict = Module.IDHandler.get($0);
  142. var channel = dict["channel"];
  143. var bytes_array = new Uint8Array($2);
  144. var i = 0;
  145. for(i=0; i<$2; i++) {
  146. bytes_array[i] = getValue($1+i, 'i8');
  147. }
  148. if ($3) {
  149. channel.send(bytes_array.buffer);
  150. } else {
  151. var string = new TextDecoder("utf-8").decode(bytes_array);
  152. channel.send(string);
  153. }
  154. }, _js_id, p_buffer, p_buffer_size, is_bin);
  155. /* clang-format on */
  156. return OK;
  157. }
  158. int WebRTCDataChannelJS::get_max_packet_size() const {
  159. return 1200;
  160. }
  161. void WebRTCDataChannelJS::set_write_mode(WriteMode p_mode) {
  162. _write_mode = p_mode;
  163. }
  164. WebRTCDataChannel::WriteMode WebRTCDataChannelJS::get_write_mode() const {
  165. return _write_mode;
  166. }
  167. bool WebRTCDataChannelJS::was_string_packet() const {
  168. return _was_string;
  169. }
  170. String WebRTCDataChannelJS::get_label() const {
  171. return _label;
  172. }
  173. /* clang-format off */
  174. #define _JS_GET(PROP, DEF) \
  175. EM_ASM_INT({ \
  176. var dict = Module.IDHandler.get($0); \
  177. if (!dict || !dict["channel"]) { \
  178. return DEF; \
  179. } \
  180. var out = dict["channel"].PROP; \
  181. return out === null ? DEF : out; \
  182. }, _js_id)
  183. /* clang-format on */
  184. bool WebRTCDataChannelJS::is_ordered() const {
  185. return _JS_GET(ordered, true);
  186. }
  187. int WebRTCDataChannelJS::get_id() const {
  188. return _JS_GET(id, 65535);
  189. }
  190. int WebRTCDataChannelJS::get_max_packet_life_time() const {
  191. // Can't use macro, webkit workaround.
  192. /* clang-format off */
  193. return EM_ASM_INT({
  194. var dict = Module.IDHandler.get($0);
  195. if (!dict || !dict["channel"]) {
  196. return 65535;
  197. }
  198. if (dict["channel"].maxRetransmitTime !== undefined) {
  199. // Guess someone didn't appreciate the standardization process.
  200. return dict["channel"].maxRetransmitTime;
  201. }
  202. var out = dict["channel"].maxPacketLifeTime;
  203. return out === null ? 65535 : out;
  204. }, _js_id);
  205. /* clang-format on */
  206. }
  207. int WebRTCDataChannelJS::get_max_retransmits() const {
  208. return _JS_GET(maxRetransmits, 65535);
  209. }
  210. String WebRTCDataChannelJS::get_protocol() const {
  211. return _protocol;
  212. }
  213. bool WebRTCDataChannelJS::is_negotiated() const {
  214. return _JS_GET(negotiated, false);
  215. }
  216. WebRTCDataChannelJS::WebRTCDataChannelJS() {
  217. queue_count = 0;
  218. _was_string = false;
  219. _write_mode = WRITE_MODE_BINARY;
  220. _js_id = 0;
  221. }
  222. WebRTCDataChannelJS::WebRTCDataChannelJS(int js_id) {
  223. queue_count = 0;
  224. _was_string = false;
  225. _write_mode = WRITE_MODE_BINARY;
  226. _js_id = js_id;
  227. /* clang-format off */
  228. EM_ASM({
  229. var c_ptr = $0;
  230. var dict = Module.IDHandler.get($1);
  231. if (!dict) return;
  232. var channel = dict["channel"];
  233. dict["ptr"] = c_ptr;
  234. channel.binaryType = "arraybuffer";
  235. channel.onopen = function (evt) {
  236. ccall("_emrtc_on_ch_open",
  237. "void",
  238. ["number"],
  239. [c_ptr]
  240. );
  241. };
  242. channel.onclose = function (evt) {
  243. ccall("_emrtc_on_ch_close",
  244. "void",
  245. ["number"],
  246. [c_ptr]
  247. );
  248. };
  249. channel.onerror = function (evt) {
  250. ccall("_emrtc_on_ch_error",
  251. "void",
  252. ["number"],
  253. [c_ptr]
  254. );
  255. };
  256. channel.onmessage = function(event) {
  257. var buffer;
  258. var is_string = 0;
  259. if (event.data instanceof ArrayBuffer) {
  260. buffer = new Uint8Array(event.data);
  261. } else if (event.data instanceof Blob) {
  262. console.error("Blob type not supported");
  263. return;
  264. } else if (typeof event.data === "string") {
  265. is_string = 1;
  266. var enc = new TextEncoder("utf-8");
  267. buffer = new Uint8Array(enc.encode(event.data));
  268. } else {
  269. console.error("Unknown message type");
  270. return;
  271. }
  272. var len = buffer.length*buffer.BYTES_PER_ELEMENT;
  273. var out = Module._malloc(len);
  274. Module.HEAPU8.set(buffer, out);
  275. ccall("_emrtc_on_ch_message",
  276. "void",
  277. ["number", "number", "number", "number"],
  278. [c_ptr, out, len, is_string]
  279. );
  280. Module._free(out);
  281. }
  282. }, this, js_id);
  283. // Parse label
  284. char *str;
  285. str = (char *)EM_ASM_INT({
  286. var dict = Module.IDHandler.get($0);
  287. if (!dict || !dict["channel"]) return 0;
  288. var str = dict["channel"].label;
  289. var len = lengthBytesUTF8(str)+1;
  290. var ptr = _malloc(str);
  291. stringToUTF8(str, ptr, len+1);
  292. return ptr;
  293. }, js_id);
  294. if(str != NULL) {
  295. _label.parse_utf8(str);
  296. EM_ASM({ _free($0) }, str);
  297. }
  298. str = (char *)EM_ASM_INT({
  299. var dict = Module.IDHandler.get($0);
  300. if (!dict || !dict["channel"]) return 0;
  301. var str = dict["channel"].protocol;
  302. var len = lengthBytesUTF8(str)+1;
  303. var ptr = _malloc(str);
  304. stringToUTF8(str, ptr, len+1);
  305. return ptr;
  306. }, js_id);
  307. if(str != NULL) {
  308. _protocol.parse_utf8(str);
  309. EM_ASM({ _free($0) }, str);
  310. }
  311. /* clang-format on */
  312. }
  313. WebRTCDataChannelJS::~WebRTCDataChannelJS() {
  314. close();
  315. /* clang-format off */
  316. EM_ASM({
  317. Module.IDHandler.remove($0);
  318. }, _js_id);
  319. /* clang-format on */
  320. };
  321. #endif