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

BridgeChannel.js 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. import { getLogger } from 'jitsi-meet-logger';
  2. import RTCEvents from '../../service/RTC/RTCEvents';
  3. import { createBridgeChannelClosedEvent } from '../../service/statistics/AnalyticsEvents';
  4. import Statistics from '../statistics/statistics';
  5. import GlobalOnErrorHandler from '../util/GlobalOnErrorHandler';
  6. const logger = getLogger(__filename);
  7. /**
  8. * Handles a WebRTC RTCPeerConnection or a WebSocket instance to communicate
  9. * with the videobridge.
  10. */
  11. export default class BridgeChannel {
  12. /**
  13. * Binds "ondatachannel" event listener on the given RTCPeerConnection
  14. * instance, or creates a WebSocket connection with the videobridge.
  15. * At least one of both, peerconnection or wsUrl parameters, must be
  16. * given.
  17. * @param {RTCPeerConnection} [peerconnection] WebRTC peer connection
  18. * instance.
  19. * @param {string} [wsUrl] WebSocket URL.
  20. * @param {EventEmitter} eventEmitter EventEmitter instance.
  21. */
  22. constructor(peerconnection, wsUrl, emitter) {
  23. if (!peerconnection && !wsUrl) {
  24. throw new TypeError(
  25. 'At least peerconnection or wsUrl must be given');
  26. } else if (peerconnection && wsUrl) {
  27. throw new TypeError(
  28. 'Just one of peerconnection or wsUrl must be given');
  29. }
  30. if (peerconnection) {
  31. logger.debug('constructor() with peerconnection');
  32. } else {
  33. logger.debug(`constructor() with wsUrl:"${wsUrl}"`);
  34. }
  35. // The underlying WebRTC RTCDataChannel or WebSocket instance.
  36. // @type {RTCDataChannel|WebSocket}
  37. this._channel = null;
  38. // @type {EventEmitter}
  39. this._eventEmitter = emitter;
  40. // Whether a RTCDataChannel or WebSocket is internally used.
  41. // @type {string} "datachannel" / "websocket"
  42. this._mode = null;
  43. // Indicates whether the connection retries are enabled or not.
  44. this._areRetriesEnabled = false;
  45. // Indicates whether the connection was closed from the client or not.
  46. this._closedFromClient = false;
  47. // If a RTCPeerConnection is given, listen for new RTCDataChannel
  48. // event.
  49. if (peerconnection) {
  50. const datachannel
  51. = peerconnection.createDataChannel(
  52. 'JVB data channel', {
  53. protocol: 'http://jitsi.org/protocols/colibri'
  54. });
  55. // Handle the RTCDataChannel.
  56. this._handleChannel(datachannel);
  57. this._mode = 'datachannel';
  58. // Otherwise create a WebSocket connection.
  59. } else if (wsUrl) {
  60. this._areRetriesEnabled = true;
  61. this._wsUrl = wsUrl;
  62. this._initWebSocket();
  63. }
  64. }
  65. /**
  66. * Initializes the web socket channel.
  67. *
  68. * @returns {void}
  69. */
  70. _initWebSocket() {
  71. // Create a WebSocket instance.
  72. const ws = new WebSocket(this._wsUrl);
  73. // Handle the WebSocket.
  74. this._handleChannel(ws);
  75. this._mode = 'websocket';
  76. }
  77. /**
  78. * Starts the websocket connection retries.
  79. *
  80. * @returns {void}
  81. */
  82. _startConnectionRetries() {
  83. let timeoutS = 1;
  84. const reload = () => {
  85. if (this.isOpen()) {
  86. return;
  87. }
  88. this._initWebSocket(this._wsUrl);
  89. timeoutS = Math.min(timeoutS * 2, 60);
  90. this._retryTimeout = setTimeout(reload, timeoutS * 1000);
  91. };
  92. this._retryTimeout = setTimeout(reload, timeoutS * 1000);
  93. }
  94. /**
  95. * Stops the websocket connection retries.
  96. *
  97. * @returns {void}
  98. */
  99. _stopConnectionRetries() {
  100. if (this._retryTimeout) {
  101. clearTimeout(this._retryTimeout);
  102. this._retryTimeout = undefined;
  103. }
  104. }
  105. /**
  106. * Retries to establish the websocket connection after the connection was closed by the server.
  107. *
  108. * @param {CloseEvent} closeEvent - The close event that triggered the retries.
  109. * @returns {void}
  110. */
  111. _retryWebSocketConnection(closeEvent) {
  112. if (!this._areRetriesEnabled) {
  113. return;
  114. }
  115. const { code, reason } = closeEvent;
  116. Statistics.sendAnalytics(createBridgeChannelClosedEvent(code, reason));
  117. this._areRetriesEnabled = false;
  118. this._eventEmitter.once(RTCEvents.DATA_CHANNEL_OPEN, () => {
  119. this._stopConnectionRetries();
  120. this._areRetriesEnabled = true;
  121. });
  122. this._startConnectionRetries();
  123. }
  124. /**
  125. * The channel mode.
  126. * @return {string} "datachannel" or "websocket" (or null if not yet set).
  127. */
  128. get mode() {
  129. return this._mode;
  130. }
  131. /**
  132. * Closes the currently opened channel.
  133. */
  134. close() {
  135. this._closedFromClient = true;
  136. this._stopConnectionRetries();
  137. this._areRetriesEnabled = false;
  138. if (this._channel) {
  139. try {
  140. this._channel.close();
  141. } catch (error) {} // eslint-disable-line no-empty
  142. this._channel = null;
  143. }
  144. }
  145. /**
  146. * Whether there is an underlying RTCDataChannel or WebSocket and it's
  147. * open.
  148. * @return {boolean}
  149. */
  150. isOpen() {
  151. return this._channel && (this._channel.readyState === 'open'
  152. || this._channel.readyState === WebSocket.OPEN);
  153. }
  154. /**
  155. * Sends message via the channel.
  156. * @param {string} to The id of the endpoint that should receive the
  157. * message. If "" the message will be sent to all participants.
  158. * @param {object} payload The payload of the message.
  159. * @throws NetworkError or InvalidStateError from RTCDataChannel#send (@see
  160. * {@link https://developer.mozilla.org/docs/Web/API/RTCDataChannel/send})
  161. * or from WebSocket#send or Error with "No opened channel" message.
  162. */
  163. sendMessage(to, payload) {
  164. this._send({
  165. colibriClass: 'EndpointMessage',
  166. msgPayload: payload,
  167. to
  168. });
  169. }
  170. /**
  171. * Sends a "lastN value changed" message via the channel.
  172. * @param {number} value The new value for lastN. -1 means unlimited.
  173. */
  174. sendSetLastNMessage(value) {
  175. const jsonObject = {
  176. colibriClass: 'LastNChangedEvent',
  177. lastN: value
  178. };
  179. this._send(jsonObject);
  180. logger.log(`Channel lastN set to: ${value}`);
  181. }
  182. /**
  183. * Sends a "pinned endpoint changed" message via the channel.
  184. * @param {string} endpointId The id of the pinned endpoint.
  185. * @throws NetworkError or InvalidStateError from RTCDataChannel#send (@see
  186. * {@link https://developer.mozilla.org/docs/Web/API/RTCDataChannel/send})
  187. * or from WebSocket#send or Error with "No opened channel" message.
  188. */
  189. sendPinnedEndpointMessage(endpointId) {
  190. logger.log(
  191. 'sending pinned changed notification to the bridge for endpoint ',
  192. endpointId);
  193. this._send({
  194. colibriClass: 'PinnedEndpointChangedEvent',
  195. pinnedEndpoint: endpointId || null
  196. });
  197. }
  198. /**
  199. * Sends a "selected endpoints changed" message via the channel.
  200. *
  201. * @param {Array<string>} endpointIds - The ids of the selected endpoints.
  202. * @throws NetworkError or InvalidStateError from RTCDataChannel#send (@see
  203. * {@link https://developer.mozilla.org/docs/Web/API/RTCDataChannel/send})
  204. * or from WebSocket#send or Error with "No opened channel" message.
  205. */
  206. sendSelectedEndpointsMessage(endpointIds) {
  207. logger.log(
  208. 'sending selected changed notification to the bridge for endpoints',
  209. endpointIds);
  210. this._send({
  211. colibriClass: 'SelectedEndpointsChangedEvent',
  212. selectedEndpoints: endpointIds
  213. });
  214. }
  215. /**
  216. * Sends a "receiver video constraint" message via the channel.
  217. * @param {Number} maxFrameHeightPixels the maximum frame height,
  218. * in pixels, this receiver is willing to receive
  219. */
  220. sendReceiverVideoConstraintMessage(maxFrameHeightPixels) {
  221. logger.log('sending a ReceiverVideoConstraint message with '
  222. + `a maxFrameHeight of ${maxFrameHeightPixels} pixels`);
  223. this._send({
  224. colibriClass: 'ReceiverVideoConstraint',
  225. maxFrameHeight: maxFrameHeightPixels
  226. });
  227. }
  228. /**
  229. * Set events on the given RTCDataChannel or WebSocket instance.
  230. */
  231. _handleChannel(channel) {
  232. const emitter = this._eventEmitter;
  233. channel.onopen = () => {
  234. logger.info(`${this._mode} channel opened`);
  235. // Code sample for sending string and/or binary data.
  236. // Sends string message to the bridge:
  237. // channel.send("Hello bridge!");
  238. // Sends 12 bytes binary message to the bridge:
  239. // channel.send(new ArrayBuffer(12));
  240. emitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  241. };
  242. channel.onerror = error => {
  243. logger.error('Channel error:', error);
  244. };
  245. channel.onmessage = ({ data }) => {
  246. // JSON object.
  247. let obj;
  248. try {
  249. obj = JSON.parse(data);
  250. } catch (error) {
  251. GlobalOnErrorHandler.callErrorHandler(error);
  252. logger.error(
  253. 'Failed to parse channel message as JSON: ',
  254. data, error);
  255. return;
  256. }
  257. const colibriClass = obj.colibriClass;
  258. switch (colibriClass) {
  259. case 'DominantSpeakerEndpointChangeEvent': {
  260. // Endpoint ID from the Videobridge.
  261. const dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  262. logger.info(
  263. 'Channel new dominant speaker event: ',
  264. dominantSpeakerEndpoint);
  265. emitter.emit(
  266. RTCEvents.DOMINANT_SPEAKER_CHANGED,
  267. dominantSpeakerEndpoint);
  268. break;
  269. }
  270. case 'EndpointConnectivityStatusChangeEvent': {
  271. const endpoint = obj.endpoint;
  272. const isActive = obj.active === 'true';
  273. logger.info(
  274. `Endpoint connection status changed: ${endpoint} active ? ${
  275. isActive}`);
  276. emitter.emit(RTCEvents.ENDPOINT_CONN_STATUS_CHANGED,
  277. endpoint, isActive);
  278. break;
  279. }
  280. case 'EndpointMessage': {
  281. emitter.emit(
  282. RTCEvents.ENDPOINT_MESSAGE_RECEIVED, obj.from,
  283. obj.msgPayload);
  284. break;
  285. }
  286. case 'LastNEndpointsChangeEvent': {
  287. // The new/latest list of last-n endpoint IDs.
  288. const lastNEndpoints = obj.lastNEndpoints;
  289. logger.info('Channel new last-n event: ',
  290. lastNEndpoints, obj);
  291. emitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  292. lastNEndpoints, obj);
  293. break;
  294. }
  295. case 'SelectedUpdateEvent': {
  296. const isSelected = obj.isSelected;
  297. logger.info(`SelectedUpdateEvent isSelected? ${isSelected}`);
  298. emitter.emit(RTCEvents.IS_SELECTED_CHANGED, isSelected);
  299. break;
  300. }
  301. default: {
  302. logger.debug('Channel JSON-formatted message: ', obj);
  303. // The received message appears to be appropriately formatted
  304. // (i.e. is a JSON object which assigns a value to the
  305. // mandatory property colibriClass) so don't just swallow it,
  306. // expose it to public consumption.
  307. emitter.emit(`rtc.datachannel.${colibriClass}`, obj);
  308. }
  309. }
  310. };
  311. channel.onclose = event => {
  312. logger.info(`Channel closed by ${this._closedFromClient ? 'client' : 'server'}`);
  313. if (this._mode === 'websocket') {
  314. if (!this._closedFromClient) {
  315. this._retryWebSocketConnection(event);
  316. }
  317. }
  318. // Remove the channel.
  319. this._channel = null;
  320. };
  321. // Store the channel.
  322. this._channel = channel;
  323. }
  324. /**
  325. * Sends passed object via the channel.
  326. * @param {object} jsonObject The object that will be sent.
  327. * @throws NetworkError or InvalidStateError from RTCDataChannel#send (@see
  328. * {@link https://developer.mozilla.org/docs/Web/API/RTCDataChannel/send})
  329. * or from WebSocket#send or Error with "No opened channel" message.
  330. */
  331. _send(jsonObject) {
  332. const channel = this._channel;
  333. if (!this.isOpen()) {
  334. logger.error('Bridge Channel send: no opened channel.');
  335. throw new Error('No opened channel');
  336. }
  337. channel.send(JSON.stringify(jsonObject));
  338. }
  339. }