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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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 "selected endpoints changed" message via the channel.
  183. *
  184. * @param {Array<string>} endpointIds - The ids of the selected endpoints.
  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. sendSelectedEndpointsMessage(endpointIds) {
  190. logger.log(`Sending selected endpoints: ${endpointIds}.`);
  191. this._send({
  192. colibriClass: 'SelectedEndpointsChangedEvent',
  193. selectedEndpoints: endpointIds
  194. });
  195. }
  196. /**
  197. * Sends a "receiver video constraint" message via the channel.
  198. * @param {Number} maxFrameHeightPixels the maximum frame height,
  199. * in pixels, this receiver is willing to receive
  200. */
  201. sendReceiverVideoConstraintMessage(maxFrameHeightPixels) {
  202. logger.log(`Sending ReceiverVideoConstraint with maxFrameHeight=${maxFrameHeightPixels}px`);
  203. this._send({
  204. colibriClass: 'ReceiverVideoConstraint',
  205. maxFrameHeight: maxFrameHeightPixels
  206. });
  207. }
  208. /**
  209. * Set events on the given RTCDataChannel or WebSocket instance.
  210. */
  211. _handleChannel(channel) {
  212. const emitter = this._eventEmitter;
  213. channel.onopen = () => {
  214. logger.info(`${this._mode} channel opened`);
  215. // Code sample for sending string and/or binary data.
  216. // Sends string message to the bridge:
  217. // channel.send("Hello bridge!");
  218. // Sends 12 bytes binary message to the bridge:
  219. // channel.send(new ArrayBuffer(12));
  220. emitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  221. };
  222. channel.onerror = event => {
  223. // WS error events contain no information about the failure (this is available in the onclose event) and
  224. // the event references the WS object itself, which causes hangs on mobile.
  225. if (this._mode !== 'websocket') {
  226. logger.error(`Channel error: ${event.message}`);
  227. }
  228. };
  229. channel.onmessage = ({ data }) => {
  230. // JSON object.
  231. let obj;
  232. try {
  233. obj = JSON.parse(data);
  234. } catch (error) {
  235. GlobalOnErrorHandler.callErrorHandler(error);
  236. logger.error('Failed to parse channel message as JSON: ', data, error);
  237. return;
  238. }
  239. const colibriClass = obj.colibriClass;
  240. switch (colibriClass) {
  241. case 'DominantSpeakerEndpointChangeEvent': {
  242. // Endpoint ID from the Videobridge.
  243. const dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  244. logger.info(`New dominant speaker: ${dominantSpeakerEndpoint}.`);
  245. emitter.emit(RTCEvents.DOMINANT_SPEAKER_CHANGED, dominantSpeakerEndpoint);
  246. break;
  247. }
  248. case 'EndpointConnectivityStatusChangeEvent': {
  249. const endpoint = obj.endpoint;
  250. const isActive = obj.active === 'true';
  251. logger.info(`Endpoint connection status changed: ${endpoint} active=${isActive}`);
  252. emitter.emit(RTCEvents.ENDPOINT_CONN_STATUS_CHANGED, endpoint, isActive);
  253. break;
  254. }
  255. case 'EndpointMessage': {
  256. emitter.emit(RTCEvents.ENDPOINT_MESSAGE_RECEIVED, obj.from, obj.msgPayload);
  257. break;
  258. }
  259. case 'LastNEndpointsChangeEvent': {
  260. // The new/latest list of last-n endpoint IDs (i.e. endpoints for which the bridge is sending video).
  261. const lastNEndpoints = obj.lastNEndpoints;
  262. logger.info(`New forwarded endpoints: ${lastNEndpoints}`);
  263. emitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED, lastNEndpoints);
  264. break;
  265. }
  266. case 'SenderVideoConstraints': {
  267. const videoConstraints = obj.videoConstraints;
  268. if (videoConstraints) {
  269. logger.info(`SenderVideoConstraints: ${JSON.stringify(videoConstraints)}`);
  270. this._senderVideoConstraintsChanged(videoConstraints);
  271. }
  272. break;
  273. }
  274. case 'ServerHello': {
  275. logger.info(`Received ServerHello, version=${obj.version}.`);
  276. break;
  277. }
  278. default: {
  279. logger.debug('Channel JSON-formatted message: ', obj);
  280. // The received message appears to be appropriately formatted
  281. // (i.e. is a JSON object which assigns a value to the
  282. // mandatory property colibriClass) so don't just swallow it,
  283. // expose it to public consumption.
  284. emitter.emit(`rtc.datachannel.${colibriClass}`, obj);
  285. }
  286. }
  287. };
  288. channel.onclose = event => {
  289. logger.info(`Channel closed by ${this._closedFromClient ? 'client' : 'server'}`);
  290. if (this._mode === 'websocket') {
  291. if (!this._closedFromClient) {
  292. logger.error(`Channel closed: ${event.code} ${event.reason}`);
  293. this._retryWebSocketConnection(event);
  294. }
  295. }
  296. // Remove the channel.
  297. this._channel = null;
  298. };
  299. // Store the channel.
  300. this._channel = channel;
  301. }
  302. /**
  303. * Sends passed object via the channel.
  304. * @param {object} jsonObject The object that will be sent.
  305. * @throws NetworkError or InvalidStateError from RTCDataChannel#send (@see
  306. * {@link https://developer.mozilla.org/docs/Web/API/RTCDataChannel/send})
  307. * or from WebSocket#send or Error with "No opened channel" message.
  308. */
  309. _send(jsonObject) {
  310. const channel = this._channel;
  311. if (!this.isOpen()) {
  312. logger.error('Bridge Channel send: no opened channel.');
  313. throw new Error('No opened channel');
  314. }
  315. channel.send(JSON.stringify(jsonObject));
  316. }
  317. }