Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

DataChannels.js 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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. try {
  60. self.sendSelectedEndpointMessage(self.selectedEndpoint);
  61. } catch (error) {
  62. GlobalOnErrorHandler.callErrorHandler(error);
  63. logger.error("Cannot sendSelectedEndpointMessage ",
  64. self.selectedEndpoint, ". Error: ", error);
  65. }
  66. };
  67. dataChannel.onerror = function (error) {
  68. var e = new Error("Data Channel Error:" + error);
  69. GlobalOnErrorHandler.callErrorHandler(e);
  70. logger.error("Data Channel Error:", error, dataChannel);
  71. };
  72. dataChannel.onmessage = function (event) {
  73. var data = event.data;
  74. // JSON
  75. var obj;
  76. try {
  77. obj = JSON.parse(data);
  78. }
  79. catch (e) {
  80. GlobalOnErrorHandler.callErrorHandler(e);
  81. logger.error(
  82. "Failed to parse data channel message as JSON: ",
  83. data,
  84. dataChannel,
  85. e);
  86. }
  87. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  88. var colibriClass = obj.colibriClass;
  89. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  90. // Endpoint ID from the Videobridge.
  91. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  92. logger.info(
  93. "Data channel new dominant speaker event: ",
  94. dominantSpeakerEndpoint);
  95. self.eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  96. }
  97. else if ("InLastNChangeEvent" === colibriClass) {
  98. var oldValue = obj.oldValue;
  99. var newValue = obj.newValue;
  100. // Make sure that oldValue and newValue are of type boolean.
  101. var type;
  102. if ((type = typeof oldValue) !== 'boolean') {
  103. if (type === 'string') {
  104. oldValue = (oldValue == "true");
  105. } else {
  106. oldValue = new Boolean(oldValue).valueOf();
  107. }
  108. }
  109. if ((type = typeof newValue) !== 'boolean') {
  110. if (type === 'string') {
  111. newValue = (newValue == "true");
  112. } else {
  113. newValue = new Boolean(newValue).valueOf();
  114. }
  115. }
  116. self.eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  117. }
  118. else if ("LastNEndpointsChangeEvent" === colibriClass) {
  119. // The new/latest list of last-n endpoint IDs.
  120. var lastNEndpoints = obj.lastNEndpoints;
  121. // The list of endpoint IDs which are entering the list of
  122. // last-n at this time i.e. were not in the old list of last-n
  123. // endpoint IDs.
  124. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  125. logger.info(
  126. "Data channel new last-n event: ",
  127. lastNEndpoints, endpointsEnteringLastN, obj);
  128. self.eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  129. lastNEndpoints, endpointsEnteringLastN, obj);
  130. } else if("EndpointMessage" === colibriClass) {
  131. self.eventEmitter.emit(
  132. RTCEvents.ENDPOINT_MESSAGE_RECEIVED, obj.from,
  133. obj.msgPayload);
  134. }
  135. else {
  136. logger.debug("Data channel JSON-formatted message: ", obj);
  137. // The received message appears to be appropriately formatted
  138. // (i.e. is a JSON object which assigns a value to the mandatory
  139. // property colibriClass) so don't just swallow it, expose it to
  140. // public consumption.
  141. self.eventEmitter.emit("rtc.datachannel." + colibriClass, obj);
  142. }
  143. }
  144. };
  145. dataChannel.onclose = function () {
  146. logger.info("The Data Channel closed", dataChannel);
  147. var idx = self._dataChannels.indexOf(dataChannel);
  148. if (idx > -1)
  149. self._dataChannels = self._dataChannels.splice(idx, 1);
  150. };
  151. this._dataChannels.push(dataChannel);
  152. };
  153. /**
  154. * Closes all currently opened data channels.
  155. */
  156. DataChannels.prototype.closeAllChannels = function () {
  157. this._dataChannels.forEach(function (dc){
  158. // the DC will be removed from the array on 'onclose' event
  159. dc.close();
  160. });
  161. };
  162. /**
  163. * Sends a "selected endpoint changed" message via the data channel.
  164. * @param endpointId {string} the id of the selected endpoint
  165. * @throws NetworkError or InvalidStateError from RTCDataChannel#send (@see
  166. * {@link https://developer.mozilla.org/en-US/docs/Web/API/RTCDataChannel/send})
  167. * or Error with "No opened data channels found!" message.
  168. */
  169. DataChannels.prototype.sendSelectedEndpointMessage = function (endpointId) {
  170. this.selectedEndpoint = endpointId;
  171. this._onXXXEndpointChanged("selected", endpointId);
  172. };
  173. /**
  174. * Sends a "pinned endpoint changed" message via the data channel.
  175. * @param endpointId {string} the id of the pinned endpoint
  176. * @throws NetworkError or InvalidStateError from RTCDataChannel#send (@see
  177. * {@link https://developer.mozilla.org/en-US/docs/Web/API/RTCDataChannel/send})
  178. * or Error with "No opened data channels found!" message.
  179. */
  180. DataChannels.prototype.sendPinnedEndpointMessage = function (endpointId) {
  181. this._onXXXEndpointChanged("pinnned", endpointId);
  182. };
  183. /**
  184. * Notifies Videobridge about a change in the value of a specific
  185. * endpoint-related property such as selected endpoint and pinnned endpoint.
  186. *
  187. * @param xxx the name of the endpoint-related property whose value changed
  188. * @param userResource the new value of the endpoint-related property after the
  189. * change
  190. * @throws NetworkError or InvalidStateError from RTCDataChannel#send (@see
  191. * {@link https://developer.mozilla.org/en-US/docs/Web/API/RTCDataChannel/send})
  192. * or Error with "No opened data channels found!" message.
  193. */
  194. DataChannels.prototype._onXXXEndpointChanged = function (xxx, userResource) {
  195. // Derive the correct words from xxx such as selected and Selected, pinned
  196. // and Pinned.
  197. var head = xxx.charAt(0);
  198. var tail = xxx.substring(1);
  199. var lower = head.toLowerCase() + tail;
  200. var upper = head.toUpperCase() + tail;
  201. logger.log(
  202. 'sending ' + lower
  203. + ' endpoint changed notification to the bridge: ',
  204. userResource);
  205. var jsonObject = {};
  206. jsonObject.colibriClass = (upper + 'EndpointChangedEvent');
  207. jsonObject[lower + "Endpoint"]
  208. = (userResource ? userResource : null);
  209. this.send(jsonObject);
  210. // Notify Videobridge about the specified endpoint change.
  211. logger.log(lower + ' endpoint changed: ', userResource);
  212. };
  213. DataChannels.prototype._some = function (callback, thisArg) {
  214. var dataChannels = this._dataChannels;
  215. if (dataChannels && dataChannels.length !== 0) {
  216. if (thisArg)
  217. return dataChannels.some(callback, thisArg);
  218. else
  219. return dataChannels.some(callback);
  220. } else {
  221. return false;
  222. }
  223. };
  224. /**
  225. * Sends passed object via the first found open datachannel
  226. * @param jsonObject {object} the object that will be sent
  227. * @throws NetworkError or InvalidStateError from RTCDataChannel#send (@see
  228. * {@link https://developer.mozilla.org/en-US/docs/Web/API/RTCDataChannel/send})
  229. * or Error with "No opened data channels found!" message.
  230. */
  231. DataChannels.prototype.send = function (jsonObject) {
  232. if(!this._some(function (dataChannel) {
  233. if (dataChannel.readyState == 'open') {
  234. dataChannel.send(JSON.stringify(jsonObject));
  235. return true;
  236. }
  237. })) {
  238. throw new Error("No opened data channels found!");
  239. }
  240. }
  241. /**
  242. * Sends message via the datachannels.
  243. * @param to {string} the id of the endpoint that should receive the message.
  244. * If "" the message will be sent to all participants.
  245. * @param payload {object} the payload of the message.
  246. * @throws NetworkError or InvalidStateError from RTCDataChannel#send (@see
  247. * {@link https://developer.mozilla.org/en-US/docs/Web/API/RTCDataChannel/send})
  248. * or Error with "No opened data channels found!" message.
  249. */
  250. DataChannels.prototype.sendDataChannelMessage = function (to, payload) {
  251. this.send({
  252. colibriClass: "EndpointMessage",
  253. to: to,
  254. msgPayload: payload
  255. });
  256. }
  257. module.exports = DataChannels;