webrtc_data_channel_js.cpp 9.8 KB

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