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.

BridgeChannel.js 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. import { getLogger } from 'jitsi-meet-logger';
  2. import RTCEvents from '../../service/RTC/RTCEvents';
  3. import GlobalOnErrorHandler from '../util/GlobalOnErrorHandler';
  4. const logger = getLogger(__filename);
  5. /**
  6. * Handles a WebRTC RTCPeerConnection or a WebSocket instance to communicate
  7. * with the videobridge.
  8. */
  9. export default class BridgeChannel {
  10. /**
  11. * Binds "ondatachannel" event listener on the given RTCPeerConnection
  12. * instance, or creates a WebSocket connection with the videobridge.
  13. * At least one of both, peerconnection or wsUrl parameters, must be
  14. * given.
  15. * @param {RTCPeerConnection} [peerconnection] WebRTC peer connection
  16. * instance.
  17. * @param {string} [wsUrl] WebSocket URL.
  18. * @param {EventEmitter} eventEmitter EventEmitter instance.
  19. */
  20. constructor(peerconnection, wsUrl, emitter) {
  21. if (!peerconnection && !wsUrl) {
  22. throw new TypeError(
  23. 'At least peerconnection or wsUrl must be given');
  24. } else if (peerconnection && wsUrl) {
  25. throw new TypeError(
  26. 'Just one of peerconnection or wsUrl must be given');
  27. }
  28. if (peerconnection) {
  29. logger.debug('constructor() with peerconnection');
  30. } else {
  31. logger.debug(`constructor() with wsUrl:"${wsUrl}"`);
  32. }
  33. // The underlying WebRTC RTCDataChannel or WebSocket instance.
  34. // @type {RTCDataChannel|WebSocket}
  35. this._channel = null;
  36. // @type {EventEmitter}
  37. this._eventEmitter = emitter;
  38. // Whether a RTCDataChannel or WebSocket is internally used.
  39. // @type {string} "datachannel" / "websocket"
  40. this._mode = null;
  41. // If a RTCPeerConnection is given, listen for new RTCDataChannel
  42. // event.
  43. if (peerconnection) {
  44. peerconnection.ondatachannel = event => {
  45. // NOTE: We assume that the "onDataChannel" event just fires
  46. // once.
  47. const datachannel = event.channel;
  48. // Handle the RTCDataChannel.
  49. this._handleChannel(datachannel);
  50. this._mode = 'datachannel';
  51. };
  52. // Otherwise create a WebSocket connection.
  53. } else if (wsUrl) {
  54. // Create a WebSocket instance.
  55. const ws = new WebSocket(wsUrl);
  56. // Handle the WebSocket.
  57. this._handleChannel(ws);
  58. this._mode = 'websocket';
  59. }
  60. }
  61. /**
  62. * The channel mode.
  63. * @return {string} "datachannel" or "websocket" (or null if not yet set).
  64. */
  65. get mode() {
  66. return this._mode;
  67. }
  68. /**
  69. * Closes the currently opened channel.
  70. */
  71. close() {
  72. if (this._channel) {
  73. try {
  74. this._channel.close();
  75. } catch (error) {} // eslint-disable-line no-empty
  76. this._channel = null;
  77. }
  78. }
  79. /**
  80. * Whether there is an underlying RTCDataChannel or WebSocket and it's
  81. * open.
  82. * @return {boolean}
  83. */
  84. isOpen() {
  85. return this._channel && (this._channel.readyState === 'open'
  86. || this._channel.readyState === WebSocket.OPEN);
  87. }
  88. /**
  89. * Sends message via the channel.
  90. * @param {string} to The id of the endpoint that should receive the
  91. * message. If "" the message will be sent to all participants.
  92. * @param {object} payload The payload of the message.
  93. * @throws NetworkError or InvalidStateError from RTCDataChannel#send (@see
  94. * {@link https://developer.mozilla.org/docs/Web/API/RTCDataChannel/send})
  95. * or from WebSocket#send or Error with "No opened channel" message.
  96. */
  97. sendMessage(to, payload) {
  98. this._send({
  99. colibriClass: 'EndpointMessage',
  100. msgPayload: payload,
  101. to
  102. });
  103. }
  104. /**
  105. * Sends a "lastN value changed" message via the channel.
  106. * @param {number} value The new value for lastN. -1 means unlimited.
  107. */
  108. sendSetLastNMessage(value) {
  109. const jsonObject = {
  110. colibriClass: 'LastNChangedEvent',
  111. lastN: value
  112. };
  113. this._send(jsonObject);
  114. logger.log(`Channel lastN set to: ${value}`);
  115. }
  116. /**
  117. * Sends a "pinned endpoint changed" message via the channel.
  118. * @param {string} endpointId The id of the pinned endpoint.
  119. * @throws NetworkError or InvalidStateError from RTCDataChannel#send (@see
  120. * {@link https://developer.mozilla.org/docs/Web/API/RTCDataChannel/send})
  121. * or from WebSocket#send or Error with "No opened channel" message.
  122. */
  123. sendPinnedEndpointMessage(endpointId) {
  124. logger.log(
  125. 'sending pinned changed notification to the bridge for endpoint ',
  126. endpointId);
  127. this._send({
  128. colibriClass: 'PinnedEndpointChangedEvent',
  129. pinnedEndpoint: endpointId || null
  130. });
  131. }
  132. /**
  133. * Sends a "selected endpoint changed" message via the channel.
  134. * @param {string} endpointId The id of the selected endpoint.
  135. * @throws NetworkError or InvalidStateError from RTCDataChannel#send (@see
  136. * {@link https://developer.mozilla.org/docs/Web/API/RTCDataChannel/send})
  137. * or from WebSocket#send or Error with "No opened channel" message.
  138. */
  139. sendSelectedEndpointMessage(endpointId) {
  140. logger.log(
  141. 'sending selected changed notification to the bridge for endpoint ',
  142. endpointId);
  143. this._send({
  144. colibriClass: 'SelectedEndpointChangedEvent',
  145. selectedEndpoint: endpointId || null
  146. });
  147. }
  148. /**
  149. * Sends a "receiver video constraint" message via the channel.
  150. * @param {Number} maxFrameHeightPixels the maximum frame height,
  151. * in pixels, this receiver is willing to receive
  152. */
  153. sendReceiverVideoConstraintMessage(maxFrameHeightPixels) {
  154. logger.log('sending a ReceiverVideoConstraint message with '
  155. + `a maxFrameHeight of ${maxFrameHeightPixels} pixels`);
  156. this._send({
  157. colibriClass: 'ReceiverVideoConstraint',
  158. maxFrameHeight: maxFrameHeightPixels
  159. });
  160. }
  161. /**
  162. * Set events on the given RTCDataChannel or WebSocket instance.
  163. */
  164. _handleChannel(channel) {
  165. const emitter = this._eventEmitter;
  166. channel.onopen = () => {
  167. logger.info(`${this._mode} channel opened`);
  168. // Code sample for sending string and/or binary data.
  169. // Sends string message to the bridge:
  170. // channel.send("Hello bridge!");
  171. // Sends 12 bytes binary message to the bridge:
  172. // channel.send(new ArrayBuffer(12));
  173. emitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  174. };
  175. channel.onerror = error => {
  176. logger.error('Channel error:', error);
  177. };
  178. channel.onmessage = ({ data }) => {
  179. // JSON object.
  180. let obj;
  181. try {
  182. obj = JSON.parse(data);
  183. } catch (error) {
  184. GlobalOnErrorHandler.callErrorHandler(error);
  185. logger.error(
  186. 'Failed to parse channel message as JSON: ',
  187. data, error);
  188. return;
  189. }
  190. const colibriClass = obj.colibriClass;
  191. switch (colibriClass) {
  192. case 'DominantSpeakerEndpointChangeEvent': {
  193. // Endpoint ID from the Videobridge.
  194. const dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  195. logger.info(
  196. 'Channel new dominant speaker event: ',
  197. dominantSpeakerEndpoint);
  198. emitter.emit(
  199. RTCEvents.DOMINANT_SPEAKER_CHANGED,
  200. dominantSpeakerEndpoint);
  201. break;
  202. }
  203. case 'EndpointConnectivityStatusChangeEvent': {
  204. const endpoint = obj.endpoint;
  205. const isActive = obj.active === 'true';
  206. logger.info(
  207. `Endpoint connection status changed: ${endpoint} active ? ${
  208. isActive}`);
  209. emitter.emit(RTCEvents.ENDPOINT_CONN_STATUS_CHANGED,
  210. endpoint, isActive);
  211. break;
  212. }
  213. case 'EndpointMessage': {
  214. emitter.emit(
  215. RTCEvents.ENDPOINT_MESSAGE_RECEIVED, obj.from,
  216. obj.msgPayload);
  217. break;
  218. }
  219. case 'LastNEndpointsChangeEvent': {
  220. // The new/latest list of last-n endpoint IDs.
  221. const lastNEndpoints = obj.lastNEndpoints;
  222. logger.info('Channel new last-n event: ',
  223. lastNEndpoints, obj);
  224. emitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  225. lastNEndpoints, obj);
  226. break;
  227. }
  228. case 'SelectedUpdateEvent': {
  229. const isSelected = obj.isSelected;
  230. logger.info(`SelectedUpdateEvent isSelected? ${isSelected}`);
  231. emitter.emit(RTCEvents.IS_SELECTED_CHANGED, isSelected);
  232. break;
  233. }
  234. default: {
  235. logger.debug('Channel JSON-formatted message: ', obj);
  236. // The received message appears to be appropriately formatted
  237. // (i.e. is a JSON object which assigns a value to the
  238. // mandatory property colibriClass) so don't just swallow it,
  239. // expose it to public consumption.
  240. emitter.emit(`rtc.datachannel.${colibriClass}`, obj);
  241. }
  242. }
  243. };
  244. channel.onclose = () => {
  245. logger.info('Channel closed');
  246. // Remove the channel.
  247. this._channel = null;
  248. };
  249. // Store the channel.
  250. this._channel = channel;
  251. }
  252. /**
  253. * Sends passed object via the channel.
  254. * @param {object} jsonObject The object that will be sent.
  255. * @throws NetworkError or InvalidStateError from RTCDataChannel#send (@see
  256. * {@link https://developer.mozilla.org/docs/Web/API/RTCDataChannel/send})
  257. * or from WebSocket#send or Error with "No opened channel" message.
  258. */
  259. _send(jsonObject) {
  260. const channel = this._channel;
  261. if (!this.isOpen()) {
  262. throw new Error('No opened channel');
  263. }
  264. channel.send(JSON.stringify(jsonObject));
  265. }
  266. }