Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

BridgeChannel.js 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  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} emitter the EventEmitter instance to use for event emission.
  21. * @param {function} senderVideoConstraintsChanged callback to call when the sender video constraints change.
  22. */
  23. constructor(peerconnection, wsUrl, emitter, senderVideoConstraintsChanged) {
  24. if (!peerconnection && !wsUrl) {
  25. throw new TypeError('At least peerconnection or wsUrl must be given');
  26. } else if (peerconnection && wsUrl) {
  27. throw new TypeError('Just one of peerconnection or wsUrl must be given');
  28. }
  29. if (peerconnection) {
  30. logger.debug('constructor() with peerconnection');
  31. } else {
  32. logger.debug(`constructor() with wsUrl:"${wsUrl}"`);
  33. }
  34. // The underlying WebRTC RTCDataChannel or WebSocket instance.
  35. // @type {RTCDataChannel|WebSocket}
  36. this._channel = null;
  37. // @type {EventEmitter}
  38. this._eventEmitter = emitter;
  39. // Whether a RTCDataChannel or WebSocket is internally used.
  40. // @type {string} "datachannel" / "websocket"
  41. this._mode = null;
  42. // Indicates whether the connection retries are enabled or not.
  43. this._areRetriesEnabled = false;
  44. // Indicates whether the connection was closed from the client or not.
  45. this._closedFromClient = false;
  46. this._senderVideoConstraintsChanged = senderVideoConstraintsChanged;
  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. logger.log(`Sending lastN=${value}.`);
  176. this._send({
  177. colibriClass: 'LastNChangedEvent',
  178. lastN: value
  179. });
  180. }
  181. /**
  182. * Sends a "pinned endpoint changed" message via the channel.
  183. * @param {string} endpointId The id of the pinned endpoint.
  184. * @throws NetworkError or InvalidStateError from RTCDataChannel#send (@see
  185. * {@link https://developer.mozilla.org/docs/Web/API/RTCDataChannel/send})
  186. * or from WebSocket#send or Error with "No opened channel" message.
  187. */
  188. sendPinnedEndpointMessage(endpointId) {
  189. logger.log(`Sending pinned endpoint: ${endpointId}.`);
  190. this._send({
  191. colibriClass: 'PinnedEndpointChangedEvent',
  192. pinnedEndpoint: endpointId || null
  193. });
  194. }
  195. /**
  196. * Sends a "selected endpoints changed" message via the channel.
  197. *
  198. * @param {Array<string>} endpointIds - The ids of the selected endpoints.
  199. * @throws NetworkError or InvalidStateError from RTCDataChannel#send (@see
  200. * {@link https://developer.mozilla.org/docs/Web/API/RTCDataChannel/send})
  201. * or from WebSocket#send or Error with "No opened channel" message.
  202. */
  203. sendSelectedEndpointsMessage(endpointIds) {
  204. logger.log(`Sending selected endpoints: ${endpointIds}.`);
  205. this._send({
  206. colibriClass: 'SelectedEndpointsChangedEvent',
  207. selectedEndpoints: endpointIds
  208. });
  209. }
  210. /**
  211. * Sends a "receiver video constraint" message via the channel.
  212. * @param {Number} maxFrameHeightPixels the maximum frame height,
  213. * in pixels, this receiver is willing to receive
  214. */
  215. sendReceiverVideoConstraintMessage(maxFrameHeightPixels) {
  216. logger.log(`Sending ReceiverVideoConstraint with maxFrameHeight=${maxFrameHeightPixels}px`);
  217. this._send({
  218. colibriClass: 'ReceiverVideoConstraint',
  219. maxFrameHeight: maxFrameHeightPixels
  220. });
  221. }
  222. /**
  223. * Set events on the given RTCDataChannel or WebSocket instance.
  224. */
  225. _handleChannel(channel) {
  226. const emitter = this._eventEmitter;
  227. channel.onopen = () => {
  228. logger.info(`${this._mode} channel opened`);
  229. // Code sample for sending string and/or binary data.
  230. // Sends string message to the bridge:
  231. // channel.send("Hello bridge!");
  232. // Sends 12 bytes binary message to the bridge:
  233. // channel.send(new ArrayBuffer(12));
  234. emitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  235. };
  236. channel.onerror = event => {
  237. // WS error events contain no information about the failure (this is available in the onclose event) and
  238. // the event references the WS object itself, which causes hangs on mobile.
  239. if (this._mode !== 'websocket') {
  240. logger.error(`Channel error: ${event.message}`);
  241. }
  242. };
  243. channel.onmessage = ({ data }) => {
  244. // JSON object.
  245. let obj;
  246. try {
  247. obj = JSON.parse(data);
  248. } catch (error) {
  249. GlobalOnErrorHandler.callErrorHandler(error);
  250. logger.error('Failed to parse channel message as JSON: ', data, error);
  251. return;
  252. }
  253. const colibriClass = obj.colibriClass;
  254. switch (colibriClass) {
  255. case 'DominantSpeakerEndpointChangeEvent': {
  256. // Endpoint ID from the Videobridge.
  257. const dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  258. logger.info(`New dominant speaker: ${dominantSpeakerEndpoint}.`);
  259. emitter.emit(RTCEvents.DOMINANT_SPEAKER_CHANGED, dominantSpeakerEndpoint);
  260. break;
  261. }
  262. case 'EndpointConnectivityStatusChangeEvent': {
  263. const endpoint = obj.endpoint;
  264. const isActive = obj.active === 'true';
  265. logger.info(`Endpoint connection status changed: ${endpoint} active=${isActive}`);
  266. emitter.emit(RTCEvents.ENDPOINT_CONN_STATUS_CHANGED, endpoint, isActive);
  267. break;
  268. }
  269. case 'EndpointMessage': {
  270. emitter.emit(RTCEvents.ENDPOINT_MESSAGE_RECEIVED, obj.from, obj.msgPayload);
  271. break;
  272. }
  273. case 'LastNEndpointsChangeEvent': {
  274. // The new/latest list of last-n endpoint IDs (i.e. endpoints for which the bridge is sending video).
  275. const lastNEndpoints = obj.lastNEndpoints;
  276. logger.info(`New forwarded endpoints: ${lastNEndpoints}`);
  277. emitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED, lastNEndpoints);
  278. break;
  279. }
  280. case 'SenderVideoConstraints': {
  281. const videoConstraints = obj.videoConstraints;
  282. if (videoConstraints) {
  283. logger.info(`SenderVideoConstraints: ${JSON.stringify(videoConstraints)}`);
  284. this._senderVideoConstraintsChanged(videoConstraints);
  285. }
  286. break;
  287. }
  288. case 'ServerHello': {
  289. logger.info(`Received ServerHello, version=${obj.version}.`);
  290. break;
  291. }
  292. default: {
  293. logger.debug('Channel JSON-formatted message: ', obj);
  294. // The received message appears to be appropriately formatted
  295. // (i.e. is a JSON object which assigns a value to the
  296. // mandatory property colibriClass) so don't just swallow it,
  297. // expose it to public consumption.
  298. emitter.emit(`rtc.datachannel.${colibriClass}`, obj);
  299. }
  300. }
  301. };
  302. channel.onclose = event => {
  303. logger.info(`Channel closed by ${this._closedFromClient ? 'client' : 'server'}`);
  304. if (this._mode === 'websocket') {
  305. if (!this._closedFromClient) {
  306. logger.error(`Channel closed: ${event.code} ${event.reason}`);
  307. this._retryWebSocketConnection(event);
  308. }
  309. }
  310. // Remove the channel.
  311. this._channel = null;
  312. };
  313. // Store the channel.
  314. this._channel = channel;
  315. }
  316. /**
  317. * Sends passed object via the channel.
  318. * @param {object} jsonObject The object that will be sent.
  319. * @throws NetworkError or InvalidStateError from RTCDataChannel#send (@see
  320. * {@link https://developer.mozilla.org/docs/Web/API/RTCDataChannel/send})
  321. * or from WebSocket#send or Error with "No opened channel" message.
  322. */
  323. _send(jsonObject) {
  324. const channel = this._channel;
  325. if (!this.isOpen()) {
  326. logger.error('Bridge Channel send: no opened channel.');
  327. throw new Error('No opened channel');
  328. }
  329. channel.send(JSON.stringify(jsonObject));
  330. }
  331. }