You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

DataChannels.js 9.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. /* global config, APP, Strophe */
  2. // cache datachannels to avoid garbage collection
  3. // https://code.google.com/p/chromium/issues/detail?id=405545
  4. var logger = require("jitsi-meet-logger").getLogger(__filename);
  5. var RTCEvents = require("../../service/RTC/RTCEvents");
  6. var GlobalOnErrorHandler = require("../util/GlobalOnErrorHandler");
  7. /**
  8. * Binds "ondatachannel" event listener to given PeerConnection instance.
  9. * @param peerConnection WebRTC peer connection instance.
  10. */
  11. function DataChannels(peerConnection, emitter) {
  12. peerConnection.ondatachannel = this.onDataChannel.bind(this);
  13. this.eventEmitter = emitter;
  14. this._dataChannels = [];
  15. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  16. // Although it's not a requirement to open separate channels from both bridge
  17. // and peer as single channel can be used for sending and receiving data.
  18. // So either channel opened by the bridge or the one opened here is enough
  19. // for communication with the bridge.
  20. /*var dataChannelOptions =
  21. {
  22. reliable: true
  23. };
  24. var dataChannel
  25. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  26. // Can be used only when is in open state
  27. dataChannel.onopen = function ()
  28. {
  29. dataChannel.send("My channel !!!");
  30. };
  31. dataChannel.onmessage = function (event)
  32. {
  33. var msgData = event.data;
  34. logger.info("Got My Data Channel Message:", msgData, dataChannel);
  35. };*/
  36. };
  37. /**
  38. * Callback triggered by PeerConnection when new data channel is opened
  39. * on the bridge.
  40. * @param event the event info object.
  41. */
  42. DataChannels.prototype.onDataChannel = function (event) {
  43. var dataChannel = event.channel;
  44. var self = this;
  45. var selectedEndpoint = null;
  46. dataChannel.onopen = function () {
  47. logger.info("Data channel opened by the Videobridge!", dataChannel);
  48. // Code sample for sending string and/or binary data
  49. // Sends String message to the bridge
  50. //dataChannel.send("Hello bridge!");
  51. // Sends 12 bytes binary message to the bridge
  52. //dataChannel.send(new ArrayBuffer(12));
  53. self.eventEmitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  54. // when the data channel becomes available, tell the bridge about video
  55. // selections so that it can do adaptive simulcast,
  56. // we want the notification to trigger even if userJid is undefined,
  57. // or null.
  58. // XXX why do we not do the same for pinned endpoints?
  59. self.sendSelectedEndpointMessage(self.selectedEndpoint);
  60. };
  61. dataChannel.onerror = function (error) {
  62. var e = new Error("Data Channel Error:" + error);
  63. GlobalOnErrorHandler.callErrorHandler(e);
  64. logger.error("Data Channel Error:", error, dataChannel);
  65. };
  66. dataChannel.onmessage = function (event) {
  67. var data = event.data;
  68. // JSON
  69. var obj;
  70. try {
  71. obj = JSON.parse(data);
  72. }
  73. catch (e) {
  74. GlobalOnErrorHandler.callErrorHandler(e);
  75. logger.error(
  76. "Failed to parse data channel message as JSON: ",
  77. data,
  78. dataChannel,
  79. e);
  80. }
  81. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  82. var colibriClass = obj.colibriClass;
  83. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  84. // Endpoint ID from the Videobridge.
  85. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  86. logger.info(
  87. "Data channel new dominant speaker event: ",
  88. dominantSpeakerEndpoint);
  89. self.eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  90. }
  91. else if ("InLastNChangeEvent" === colibriClass) {
  92. var oldValue = obj.oldValue;
  93. var newValue = obj.newValue;
  94. // Make sure that oldValue and newValue are of type boolean.
  95. var type;
  96. if ((type = typeof oldValue) !== 'boolean') {
  97. if (type === 'string') {
  98. oldValue = (oldValue == "true");
  99. } else {
  100. oldValue = new Boolean(oldValue).valueOf();
  101. }
  102. }
  103. if ((type = typeof newValue) !== 'boolean') {
  104. if (type === 'string') {
  105. newValue = (newValue == "true");
  106. } else {
  107. newValue = new Boolean(newValue).valueOf();
  108. }
  109. }
  110. self.eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  111. }
  112. else if ("LastNEndpointsChangeEvent" === colibriClass) {
  113. // The new/latest list of last-n endpoint IDs.
  114. var lastNEndpoints = obj.lastNEndpoints;
  115. // The list of endpoint IDs which are entering the list of
  116. // last-n at this time i.e. were not in the old list of last-n
  117. // endpoint IDs.
  118. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  119. logger.info(
  120. "Data channel new last-n event: ",
  121. lastNEndpoints, endpointsEnteringLastN, obj);
  122. self.eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  123. lastNEndpoints, endpointsEnteringLastN, obj);
  124. } else if("EndpointMessage" === colibriClass) {
  125. self.eventEmitter.emit(
  126. RTCEvents.DATACHANNEL_ENDPOINT_MESSAGE_RECEIVED,
  127. obj.msgPayload);
  128. }
  129. else {
  130. logger.debug("Data channel JSON-formatted message: ", obj);
  131. // The received message appears to be appropriately formatted
  132. // (i.e. is a JSON object which assigns a value to the mandatory
  133. // property colibriClass) so don't just swallow it, expose it to
  134. // public consumption.
  135. self.eventEmitter.emit("rtc.datachannel." + colibriClass, obj);
  136. }
  137. }
  138. };
  139. dataChannel.onclose = function () {
  140. logger.info("The Data Channel closed", dataChannel);
  141. var idx = self._dataChannels.indexOf(dataChannel);
  142. if (idx > -1)
  143. self._dataChannels = self._dataChannels.splice(idx, 1);
  144. };
  145. this._dataChannels.push(dataChannel);
  146. };
  147. /**
  148. * Closes all currently opened data channels.
  149. */
  150. DataChannels.prototype.closeAllChannels = function () {
  151. this._dataChannels.forEach(function (dc){
  152. // the DC will be removed from the array on 'onclose' event
  153. dc.close();
  154. });
  155. };
  156. /**
  157. * Sends a "selected endpoint changed" message via the data channel.
  158. */
  159. DataChannels.prototype.sendSelectedEndpointMessage = function (endpointId) {
  160. this.selectedEndpoint = endpointId;
  161. this._onXXXEndpointChanged("selected", endpointId);
  162. };
  163. /**
  164. * Sends a "pinned endpoint changed" message via the data channel.
  165. */
  166. DataChannels.prototype.sendPinnedEndpointMessage = function (endpointId) {
  167. this._onXXXEndpointChanged("pinnned", endpointId);
  168. };
  169. /**
  170. * Notifies Videobridge about a change in the value of a specific
  171. * endpoint-related property such as selected endpoint and pinnned endpoint.
  172. *
  173. * @param xxx the name of the endpoint-related property whose value changed
  174. * @param userResource the new value of the endpoint-related property after the
  175. * change
  176. */
  177. DataChannels.prototype._onXXXEndpointChanged = function (xxx, userResource) {
  178. // Derive the correct words from xxx such as selected and Selected, pinned
  179. // and Pinned.
  180. var head = xxx.charAt(0);
  181. var tail = xxx.substring(1);
  182. var lower = head.toLowerCase() + tail;
  183. var upper = head.toUpperCase() + tail;
  184. logger.log(
  185. 'sending ' + lower
  186. + ' endpoint changed notification to the bridge: ',
  187. userResource);
  188. var jsonObject = {};
  189. jsonObject.colibriClass = (upper + 'EndpointChangedEvent');
  190. jsonObject[lower + "Endpoint"]
  191. = (userResource ? userResource : null);
  192. this.send(jsonObject);
  193. // Notify Videobridge about the specified endpoint change.
  194. logger.log(lower + ' endpoint changed: ', userResource);
  195. };
  196. DataChannels.prototype._some = function (callback, thisArg) {
  197. var dataChannels = this._dataChannels;
  198. if (dataChannels && dataChannels.length !== 0) {
  199. if (thisArg)
  200. return dataChannels.some(callback, thisArg);
  201. else
  202. return dataChannels.some(callback);
  203. } else {
  204. return false;
  205. }
  206. };
  207. /**
  208. * Sends passed object via the first found open datachannel
  209. * @param jsonObject {object} the object that will be sent
  210. */
  211. DataChannels.prototype.send = function (jsonObject) {
  212. this._some(function (dataChannel) {
  213. if (dataChannel.readyState == 'open') {
  214. dataChannel.send(JSON.stringify(jsonObject));
  215. return true;
  216. }
  217. });
  218. }
  219. /**
  220. * Sends broadcast message via the datachannels.
  221. * @param payload {object} the payload of the message.
  222. */
  223. DataChannels.prototype.sendBroadcastMessage = function (payload) {
  224. var jsonObject = {};
  225. jsonObject.colibriClass = "EndpointMessage";
  226. jsonObject.to = "";
  227. // following the same format for the payload in order to be able to
  228. // recognise the message on the receiving side.
  229. jsonObject.msgPayload = {
  230. colibriClass: "EndpointMessage",
  231. to: "",
  232. msgPayload: payload
  233. };
  234. this.send(jsonObject);
  235. }
  236. module.exports = DataChannels;