Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

BridgeChannel.js 13KB

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