Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

DataChannels.js 8.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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 lastSelectedEndpoint = 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. self.handleSelectedEndpointEvent(self.lastSelectedEndpoint);
  59. };
  60. dataChannel.onerror = function (error) {
  61. var e = new Error("Data Channel Error:" + error);
  62. GlobalOnErrorHandler.callErrorHandler(e);
  63. logger.error("Data Channel Error:", error, dataChannel);
  64. };
  65. dataChannel.onmessage = function (event) {
  66. var data = event.data;
  67. // JSON
  68. var obj;
  69. try {
  70. obj = JSON.parse(data);
  71. }
  72. catch (e) {
  73. GlobalOnErrorHandler.callErrorHandler(e);
  74. logger.error(
  75. "Failed to parse data channel message as JSON: ",
  76. data,
  77. dataChannel,
  78. e);
  79. }
  80. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  81. var colibriClass = obj.colibriClass;
  82. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  83. // Endpoint ID from the Videobridge.
  84. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  85. logger.info(
  86. "Data channel new dominant speaker event: ",
  87. dominantSpeakerEndpoint);
  88. self.eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  89. }
  90. else if ("InLastNChangeEvent" === colibriClass) {
  91. var oldValue = obj.oldValue;
  92. var newValue = obj.newValue;
  93. // Make sure that oldValue and newValue are of type boolean.
  94. var type;
  95. if ((type = typeof oldValue) !== 'boolean') {
  96. if (type === 'string') {
  97. oldValue = (oldValue == "true");
  98. } else {
  99. oldValue = new Boolean(oldValue).valueOf();
  100. }
  101. }
  102. if ((type = typeof newValue) !== 'boolean') {
  103. if (type === 'string') {
  104. newValue = (newValue == "true");
  105. } else {
  106. newValue = new Boolean(newValue).valueOf();
  107. }
  108. }
  109. self.eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  110. }
  111. else if ("LastNEndpointsChangeEvent" === colibriClass) {
  112. // The new/latest list of last-n endpoint IDs.
  113. var lastNEndpoints = obj.lastNEndpoints;
  114. // The list of endpoint IDs which are entering the list of
  115. // last-n at this time i.e. were not in the old list of last-n
  116. // endpoint IDs.
  117. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  118. logger.info(
  119. "Data channel new last-n event: ",
  120. lastNEndpoints, endpointsEnteringLastN, obj);
  121. self.eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  122. lastNEndpoints, endpointsEnteringLastN, obj);
  123. }
  124. else {
  125. logger.debug("Data channel JSON-formatted message: ", obj);
  126. // The received message appears to be appropriately formatted
  127. // (i.e. is a JSON object which assigns a value to the mandatory
  128. // property colibriClass) so don't just swallow it, expose it to
  129. // public consumption.
  130. self.eventEmitter.emit("rtc.datachannel." + colibriClass, obj);
  131. }
  132. }
  133. };
  134. dataChannel.onclose = function () {
  135. logger.info("The Data Channel closed", dataChannel);
  136. var idx = self._dataChannels.indexOf(dataChannel);
  137. if (idx > -1)
  138. self._dataChannels = self._dataChannels.splice(idx, 1);
  139. };
  140. this._dataChannels.push(dataChannel);
  141. };
  142. DataChannels.prototype.handleSelectedEndpointEvent = function (userResource) {
  143. this.lastSelectedEndpoint = userResource;
  144. this._onXXXEndpointChanged("selected", userResource);
  145. }
  146. DataChannels.prototype.handlePinnedEndpointEvent = function (userResource) {
  147. this._onXXXEndpointChanged("pinnned", userResource);
  148. }
  149. /**
  150. * Notifies Videobridge about a change in the value of a specific
  151. * endpoint-related property such as selected endpoint and pinnned endpoint.
  152. *
  153. * @param xxx the name of the endpoint-related property whose value changed
  154. * @param userResource the new value of the endpoint-related property after the
  155. * change
  156. */
  157. DataChannels.prototype._onXXXEndpointChanged = function (xxx, userResource) {
  158. // Derive the correct words from xxx such as selected and Selected, pinned
  159. // and Pinned.
  160. var head = xxx.charAt(0);
  161. var tail = xxx.substring(1);
  162. var lower = head.toLowerCase() + tail;
  163. var upper = head.toUpperCase() + tail;
  164. // Notify Videobridge about the specified endpoint change.
  165. logger.log(lower + ' endpoint changed: ', userResource);
  166. this._some(function (dataChannel) {
  167. if (dataChannel.readyState == 'open') {
  168. logger.log(
  169. 'sending ' + lower
  170. + ' endpoint changed notification to the bridge: ',
  171. userResource);
  172. var jsonObject = {};
  173. jsonObject.colibriClass = (upper + 'EndpointChangedEvent');
  174. jsonObject[lower + "Endpoint"]
  175. = (userResource ? userResource : null);
  176. try {
  177. dataChannel.send(JSON.stringify(jsonObject));
  178. } catch (e) {
  179. // FIXME: Maybe we should check if the conference is left
  180. // before calling _onXXXEndpointChanged method.
  181. // FIXME: We should check if we are disposing correctly the
  182. // data channels.
  183. logger.warn(e);
  184. }
  185. return true;
  186. }
  187. });
  188. }
  189. DataChannels.prototype._some = function (callback, thisArg) {
  190. var dataChannels = this._dataChannels;
  191. if (dataChannels && dataChannels.length !== 0) {
  192. if (thisArg)
  193. return dataChannels.some(callback, thisArg);
  194. else
  195. return dataChannels.some(callback);
  196. } else {
  197. return false;
  198. }
  199. }
  200. module.exports = DataChannels;