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

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. const datachannel
  45. = peerconnection.createDataChannel(
  46. 'JVB data channel', {
  47. protocol: 'http://jitsi.org/protocols/colibri'
  48. });
  49. // Handle the RTCDataChannel.
  50. this._handleChannel(datachannel);
  51. this._mode = 'datachannel';
  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 endpoints changed" message via the channel.
  134. *
  135. * @param {Array<string>} endpointIds - The ids of the selected endpoints.
  136. * @throws NetworkError or InvalidStateError from RTCDataChannel#send (@see
  137. * {@link https://developer.mozilla.org/docs/Web/API/RTCDataChannel/send})
  138. * or from WebSocket#send or Error with "No opened channel" message.
  139. */
  140. sendSelectedEndpointsMessage(endpointIds) {
  141. logger.log(
  142. 'sending selected changed notification to the bridge for endpoints',
  143. endpointIds);
  144. this._send({
  145. colibriClass: 'SelectedEndpointsChangedEvent',
  146. selectedEndpoints: endpointIds
  147. });
  148. }
  149. /**
  150. * Sends a "receiver video constraint" message via the channel.
  151. * @param {Number} maxFrameHeightPixels the maximum frame height,
  152. * in pixels, this receiver is willing to receive
  153. */
  154. sendReceiverVideoConstraintMessage(maxFrameHeightPixels) {
  155. logger.log('sending a ReceiverVideoConstraint message with '
  156. + `a maxFrameHeight of ${maxFrameHeightPixels} pixels`);
  157. this._send({
  158. colibriClass: 'ReceiverVideoConstraint',
  159. maxFrameHeight: maxFrameHeightPixels
  160. });
  161. }
  162. /**
  163. * Set events on the given RTCDataChannel or WebSocket instance.
  164. */
  165. _handleChannel(channel) {
  166. const emitter = this._eventEmitter;
  167. channel.onopen = () => {
  168. logger.info(`${this._mode} channel opened`);
  169. // Code sample for sending string and/or binary data.
  170. // Sends string message to the bridge:
  171. // channel.send("Hello bridge!");
  172. // Sends 12 bytes binary message to the bridge:
  173. // channel.send(new ArrayBuffer(12));
  174. emitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  175. };
  176. channel.onerror = error => {
  177. logger.error('Channel error:', error);
  178. };
  179. channel.onmessage = ({ data }) => {
  180. // JSON object.
  181. let obj;
  182. try {
  183. obj = JSON.parse(data);
  184. } catch (error) {
  185. GlobalOnErrorHandler.callErrorHandler(error);
  186. logger.error(
  187. 'Failed to parse channel message as JSON: ',
  188. data, error);
  189. return;
  190. }
  191. const colibriClass = obj.colibriClass;
  192. switch (colibriClass) {
  193. case 'DominantSpeakerEndpointChangeEvent': {
  194. // Endpoint ID from the Videobridge.
  195. const dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  196. logger.info(
  197. 'Channel new dominant speaker event: ',
  198. dominantSpeakerEndpoint);
  199. emitter.emit(
  200. RTCEvents.DOMINANT_SPEAKER_CHANGED,
  201. dominantSpeakerEndpoint);
  202. break;
  203. }
  204. case 'EndpointConnectivityStatusChangeEvent': {
  205. const endpoint = obj.endpoint;
  206. const isActive = obj.active === 'true';
  207. logger.info(
  208. `Endpoint connection status changed: ${endpoint} active ? ${
  209. isActive}`);
  210. emitter.emit(RTCEvents.ENDPOINT_CONN_STATUS_CHANGED,
  211. endpoint, isActive);
  212. break;
  213. }
  214. case 'EndpointMessage': {
  215. emitter.emit(
  216. RTCEvents.ENDPOINT_MESSAGE_RECEIVED, obj.from,
  217. obj.msgPayload);
  218. break;
  219. }
  220. case 'LastNEndpointsChangeEvent': {
  221. // The new/latest list of last-n endpoint IDs.
  222. const lastNEndpoints = obj.lastNEndpoints;
  223. logger.info('Channel new last-n event: ',
  224. lastNEndpoints, obj);
  225. emitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  226. lastNEndpoints, obj);
  227. break;
  228. }
  229. case 'SelectedUpdateEvent': {
  230. const isSelected = obj.isSelected;
  231. logger.info(`SelectedUpdateEvent isSelected? ${isSelected}`);
  232. emitter.emit(RTCEvents.IS_SELECTED_CHANGED, isSelected);
  233. break;
  234. }
  235. default: {
  236. logger.debug('Channel JSON-formatted message: ', obj);
  237. // The received message appears to be appropriately formatted
  238. // (i.e. is a JSON object which assigns a value to the
  239. // mandatory property colibriClass) so don't just swallow it,
  240. // expose it to public consumption.
  241. emitter.emit(`rtc.datachannel.${colibriClass}`, obj);
  242. }
  243. }
  244. };
  245. channel.onclose = () => {
  246. logger.info('Channel closed');
  247. // Remove the channel.
  248. this._channel = null;
  249. };
  250. // Store the channel.
  251. this._channel = channel;
  252. }
  253. /**
  254. * Sends passed object via the channel.
  255. * @param {object} jsonObject The object that will be sent.
  256. * @throws NetworkError or InvalidStateError from RTCDataChannel#send (@see
  257. * {@link https://developer.mozilla.org/docs/Web/API/RTCDataChannel/send})
  258. * or from WebSocket#send or Error with "No opened channel" message.
  259. */
  260. _send(jsonObject) {
  261. const channel = this._channel;
  262. if (!this.isOpen()) {
  263. throw new Error('No opened channel');
  264. }
  265. channel.send(JSON.stringify(jsonObject));
  266. }
  267. }