您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

DataChannels.js 8.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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. }
  125. else {
  126. logger.debug("Data channel JSON-formatted message: ", obj);
  127. // The received message appears to be appropriately formatted
  128. // (i.e. is a JSON object which assigns a value to the mandatory
  129. // property colibriClass) so don't just swallow it, expose it to
  130. // public consumption.
  131. self.eventEmitter.emit("rtc.datachannel." + colibriClass, obj);
  132. }
  133. }
  134. };
  135. dataChannel.onclose = function () {
  136. logger.info("The Data Channel closed", dataChannel);
  137. var idx = self._dataChannels.indexOf(dataChannel);
  138. if (idx > -1)
  139. self._dataChannels = self._dataChannels.splice(idx, 1);
  140. };
  141. this._dataChannels.push(dataChannel);
  142. };
  143. /**
  144. * Closes all currently opened data channels.
  145. */
  146. DataChannels.prototype.closeAllChannels = function () {
  147. this._dataChannels.forEach(function (dc){
  148. // the DC will be removed from the array on 'onclose' event
  149. dc.close();
  150. });
  151. };
  152. /**
  153. * Sends a "selected endpoint changed" message via the data channel.
  154. */
  155. DataChannels.prototype.sendSelectedEndpointMessage = function (endpointId) {
  156. this.selectedEndpoint = endpointId;
  157. this._onXXXEndpointChanged("selected", endpointId);
  158. };
  159. /**
  160. * Sends a "pinned endpoint changed" message via the data channel.
  161. */
  162. DataChannels.prototype.sendPinnedEndpointMessage = function (endpointId) {
  163. this._onXXXEndpointChanged("pinnned", endpointId);
  164. };
  165. /**
  166. * Notifies Videobridge about a change in the value of a specific
  167. * endpoint-related property such as selected endpoint and pinnned endpoint.
  168. *
  169. * @param xxx the name of the endpoint-related property whose value changed
  170. * @param userResource the new value of the endpoint-related property after the
  171. * change
  172. */
  173. DataChannels.prototype._onXXXEndpointChanged = function (xxx, userResource) {
  174. // Derive the correct words from xxx such as selected and Selected, pinned
  175. // and Pinned.
  176. var head = xxx.charAt(0);
  177. var tail = xxx.substring(1);
  178. var lower = head.toLowerCase() + tail;
  179. var upper = head.toUpperCase() + tail;
  180. // Notify Videobridge about the specified endpoint change.
  181. logger.log(lower + ' endpoint changed: ', userResource);
  182. this._some(function (dataChannel) {
  183. if (dataChannel.readyState == 'open') {
  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. try {
  193. dataChannel.send(JSON.stringify(jsonObject));
  194. } catch (e) {
  195. // FIXME: Maybe we should check if the conference is left
  196. // before calling _onXXXEndpointChanged method.
  197. // FIXME: We should check if we are disposing correctly the
  198. // data channels.
  199. logger.warn(e);
  200. }
  201. return true;
  202. }
  203. });
  204. };
  205. DataChannels.prototype._some = function (callback, thisArg) {
  206. var dataChannels = this._dataChannels;
  207. if (dataChannels && dataChannels.length !== 0) {
  208. if (thisArg)
  209. return dataChannels.some(callback, thisArg);
  210. else
  211. return dataChannels.some(callback);
  212. } else {
  213. return false;
  214. }
  215. };
  216. module.exports = DataChannels;