You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

BridgeChannel.ts 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. import { safeJsonParse } from '@jitsi/js-utils/json';
  2. import { getLogger } from '@jitsi/logger';
  3. import { EventEmitter } from 'events';
  4. import JitsiConference from '../../JitsiConference';
  5. import { BridgeVideoType } from '../../service/RTC/BridgeVideoType';
  6. import RTCEvents from '../../service/RTC/RTCEvents';
  7. import { SourceName } from '../../service/RTC/SignalingLayer';
  8. import { createBridgeChannelClosedEvent } from '../../service/statistics/AnalyticsEvents';
  9. import ReceiverVideoConstraints from '../qualitycontrol/ReceiveVideoController';
  10. import Statistics from '../statistics/statistics';
  11. const logger = getLogger('modules/RTC/BridgeChannel');
  12. /**
  13. * Handles a WebRTC RTCPeerConnection or a WebSocket instance to communicate
  14. * with the videobridge.
  15. */
  16. export default class BridgeChannel {
  17. private _channel: RTCDataChannel | WebSocket | null = null;
  18. private _conference: JitsiConference;
  19. private _connected: boolean | undefined = undefined;
  20. private _eventEmitter: EventEmitter;
  21. private _mode: 'datachannel' | 'websocket' | null = null;
  22. private _areRetriesEnabled: boolean = false;
  23. private _closedFromClient: boolean = false;
  24. private _wsUrl?: string;
  25. private _retryTimeout?: ReturnType<typeof setTimeout>;
  26. /**
  27. * Binds "ondatachannel" event listener on the given RTCPeerConnection
  28. * instance, or creates a WebSocket connection with the videobridge.
  29. * At least one of both, peerconnection or wsUrl parameters, must be
  30. * given.
  31. * @param {RTCPeerConnection} [peerconnection] WebRTC peer connection
  32. * instance.
  33. * @param {string} [wsUrl] WebSocket URL.
  34. * @param {EventEmitter} emitter the EventEmitter instance to use for event emission.
  35. * @param {JitsiConference} conference the conference instance.
  36. */
  37. constructor(
  38. peerconnection: RTCPeerConnection | null,
  39. wsUrl: string | null,
  40. emitter: EventEmitter,
  41. conference: JitsiConference
  42. ) {
  43. if (!peerconnection && !wsUrl) {
  44. throw new TypeError('At least peerconnection or wsUrl must be given');
  45. } else if (peerconnection && wsUrl) {
  46. throw new TypeError('Just one of peerconnection or wsUrl must be given');
  47. }
  48. if (peerconnection) {
  49. logger.debug('constructor() with peerconnection');
  50. } else {
  51. logger.debug(`constructor() with wsUrl:"${wsUrl}"`);
  52. }
  53. // The underlying WebRTC RTCDataChannel or WebSocket instance.
  54. // @type {RTCDataChannel|WebSocket}
  55. this._channel = null;
  56. // The conference that uses this bridge channel.
  57. this._conference = conference;
  58. // Whether the channel is connected or not. It will start as undefined
  59. // for the first connection attempt. Then transition to either true or false.
  60. this._connected = undefined;
  61. // @type {EventEmitter}
  62. this._eventEmitter = emitter;
  63. // Whether a RTCDataChannel or WebSocket is internally used.
  64. // @type {string} "datachannel" / "websocket"
  65. this._mode = null;
  66. // Indicates whether the connection retries are enabled or not.
  67. this._areRetriesEnabled = false;
  68. // Indicates whether the connection was closed from the client or not.
  69. this._closedFromClient = false;
  70. // If a RTCPeerConnection is given, listen for new RTCDataChannel
  71. // event.
  72. if (peerconnection) {
  73. const datachannel
  74. = peerconnection.createDataChannel(
  75. 'JVB data channel', {
  76. protocol: 'http://jitsi.org/protocols/colibri'
  77. });
  78. // Handle the RTCDataChannel.
  79. this._handleChannel(datachannel);
  80. this._mode = 'datachannel';
  81. // Otherwise create a WebSocket connection.
  82. } else if (wsUrl) {
  83. this._areRetriesEnabled = true;
  84. this._wsUrl = wsUrl;
  85. this._initWebSocket();
  86. }
  87. }
  88. /**
  89. * Initializes the web socket channel.
  90. *
  91. * @returns {void}
  92. */
  93. _initWebSocket(): void {
  94. // Create a WebSocket instance.
  95. const ws = new WebSocket(this._wsUrl);
  96. // Handle the WebSocket.
  97. this._handleChannel(ws);
  98. this._mode = 'websocket';
  99. }
  100. /**
  101. * Starts the websocket connection retries.
  102. *
  103. * @returns {void}
  104. */
  105. _startConnectionRetries(): void {
  106. let timeoutS = 1;
  107. const reload = (): void => {
  108. const isConnecting = this._channel && (this._channel.readyState === 'connecting'
  109. || this._channel.readyState === WebSocket.CONNECTING);
  110. // Should not spawn new websockets while one is already trying to connect.
  111. if (isConnecting) {
  112. // Timeout is still required as there is flag `_areRetriesEnabled` that
  113. // blocks new retrying cycles until any channel opens in current cycle.
  114. this._retryTimeout = setTimeout(reload, timeoutS * 1000);
  115. return;
  116. }
  117. if (this.isOpen()) {
  118. return;
  119. }
  120. this._initWebSocket();
  121. timeoutS = Math.min(timeoutS * 2, 60);
  122. this._retryTimeout = setTimeout(reload, timeoutS * 1000);
  123. };
  124. this._retryTimeout = setTimeout(reload, timeoutS * 1000);
  125. }
  126. /**
  127. * Stops the websocket connection retries.
  128. *
  129. * @returns {void}
  130. */
  131. _stopConnectionRetries(): void {
  132. if (this._retryTimeout) {
  133. clearTimeout(this._retryTimeout);
  134. this._retryTimeout = undefined;
  135. }
  136. }
  137. /**
  138. * Retries to establish the websocket connection after the connection was closed by the server.
  139. *
  140. * @param {CloseEvent} closeEvent - The close event that triggered the retries.
  141. * @returns {void}
  142. */
  143. _retryWebSocketConnection(closeEvent: CloseEvent): void {
  144. if (!this._areRetriesEnabled) {
  145. return;
  146. }
  147. const { code, reason } = closeEvent;
  148. Statistics.sendAnalytics(createBridgeChannelClosedEvent(code.toString(), reason));
  149. this._areRetriesEnabled = false;
  150. this._eventEmitter.once(RTCEvents.DATA_CHANNEL_OPEN, () => {
  151. this._stopConnectionRetries();
  152. this._areRetriesEnabled = true;
  153. });
  154. this._startConnectionRetries();
  155. }
  156. /**
  157. * The channel mode.
  158. * @return {string} "datachannel" or "websocket" (or null if not yet set).
  159. */
  160. get mode(): string {
  161. return this._mode;
  162. }
  163. /**
  164. * Closes the currently opened channel.
  165. */
  166. close(): void {
  167. this._closedFromClient = true;
  168. this._stopConnectionRetries();
  169. this._areRetriesEnabled = false;
  170. if (this._channel) {
  171. try {
  172. this._channel.close();
  173. } catch (error) {} // eslint-disable-line no-empty
  174. this._channel = null;
  175. }
  176. }
  177. /**
  178. * Whether there is an underlying RTCDataChannel or WebSocket and it's
  179. * open.
  180. * @return {boolean}
  181. */
  182. isOpen(): boolean {
  183. return this._channel && (this._channel.readyState === 'open'
  184. || this._channel.readyState === WebSocket.OPEN);
  185. }
  186. /**
  187. * Sends local stats via the bridge channel.
  188. * @param {Object} payload The payload of the message.
  189. * @throws NetworkError/InvalidStateError/Error if the operation fails or if there is no data channel created.
  190. */
  191. sendEndpointStatsMessage(payload: Record<string, unknown>): void {
  192. this._send({
  193. colibriClass: 'EndpointStats',
  194. ...payload
  195. });
  196. }
  197. /**
  198. * Sends message via the channel.
  199. * @param {string} to The id of the endpoint that should receive the
  200. * message. If "" the message will be sent to all participants.
  201. * @param {object} payload The payload of the message.
  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. sendMessage(to: string, payload: Record<string, unknown>): void {
  207. this._send({
  208. colibriClass: 'EndpointMessage',
  209. msgPayload: payload,
  210. to
  211. });
  212. }
  213. /**
  214. * Sends a "lastN value changed" message via the channel.
  215. * @param {number} value The new value for lastN. -1 means unlimited.
  216. */
  217. sendSetLastNMessage(value: number): void {
  218. logger.debug(`Sending lastN=${value}.`);
  219. this._send({
  220. colibriClass: 'LastNChangedEvent',
  221. lastN: value
  222. });
  223. }
  224. /**
  225. * Sends a 'ReceiverVideoConstraints' message via the bridge channel.
  226. *
  227. * @param {ReceiverVideoConstraints} constraints video constraints.
  228. */
  229. sendReceiverVideoConstraintsMessage(constraints: ReceiverVideoConstraints): void {
  230. logger.info(`Sending ReceiverVideoConstraints with ${JSON.stringify(constraints)}`);
  231. this._send({
  232. colibriClass: 'ReceiverVideoConstraints',
  233. ...constraints
  234. });
  235. }
  236. /**
  237. * Sends a 'SourceVideoTypeMessage' message via the bridge channel.
  238. *
  239. * @param {BridgeVideoType} videoType - the video type.
  240. * @param {SourceName} sourceName - the source name of the video track.
  241. * @returns {void}
  242. */
  243. sendSourceVideoTypeMessage(sourceName: SourceName, videoType: BridgeVideoType): void {
  244. logger.info(`Sending SourceVideoTypeMessage with video type ${sourceName}: ${videoType}`);
  245. this._send({
  246. colibriClass: 'SourceVideoTypeMessage',
  247. sourceName,
  248. videoType
  249. });
  250. }
  251. /**
  252. * Set events on the given RTCDataChannel or WebSocket instance.
  253. */
  254. _handleChannel(channel: RTCDataChannel | WebSocket): void {
  255. const emitter = this._eventEmitter;
  256. channel.onopen = (): void | null => {
  257. logger.info(`${this._mode} channel opened`);
  258. this._connected = true;
  259. emitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  260. };
  261. channel.onerror = (event: ErrorEvent): void => {
  262. // WS error events contain no information about the failure (this is available in the onclose event) and
  263. // the event references the WS object itself, which causes hangs on mobile.
  264. if (this._mode !== 'websocket') {
  265. logger.error(`Channel error: ${event.message}`);
  266. }
  267. };
  268. channel.onmessage = ({ data }: { data: string; }): void => {
  269. // JSON object.
  270. let obj;
  271. try {
  272. obj = safeJsonParse(data);
  273. } catch (error) {
  274. logger.error('Failed to parse channel message as JSON: ', data, error);
  275. return;
  276. }
  277. const colibriClass = obj.colibriClass;
  278. switch (colibriClass) {
  279. case 'ConnectionStats': {
  280. const { estimatedDownlinkBandwidth } = obj;
  281. logger.debug(`Connection stats: bwe=${estimatedDownlinkBandwidth} bps`);
  282. emitter.emit(RTCEvents.BRIDGE_BWE_STATS_RECEIVED, estimatedDownlinkBandwidth);
  283. break;
  284. }
  285. case 'DominantSpeakerEndpointChangeEvent': {
  286. const { dominantSpeakerEndpoint, previousSpeakers = [], silence } = obj;
  287. logger.debug(`Dominant speaker: ${dominantSpeakerEndpoint}, previous speakers: ${previousSpeakers}`);
  288. emitter.emit(RTCEvents.DOMINANT_SPEAKER_CHANGED, dominantSpeakerEndpoint, previousSpeakers, silence);
  289. break;
  290. }
  291. case 'EndpointConnectivityStatusChangeEvent': {
  292. const endpoint = obj.endpoint;
  293. const isActive = obj.active === 'true';
  294. logger.info(`Endpoint connection status changed: ${endpoint} active=${isActive}`);
  295. emitter.emit(RTCEvents.ENDPOINT_CONN_STATUS_CHANGED, endpoint, isActive);
  296. break;
  297. }
  298. case 'EndpointMessage': {
  299. emitter.emit(RTCEvents.ENDPOINT_MESSAGE_RECEIVED, obj.from, obj.msgPayload);
  300. break;
  301. }
  302. case 'EndpointStats': {
  303. emitter.emit(RTCEvents.ENDPOINT_STATS_RECEIVED, obj.from, obj);
  304. break;
  305. }
  306. case 'ForwardedSources': {
  307. const forwardedSources = obj.forwardedSources;
  308. logger.info(`New forwarded sources: ${forwardedSources}`);
  309. emitter.emit(RTCEvents.FORWARDED_SOURCES_CHANGED, forwardedSources);
  310. break;
  311. }
  312. case 'SenderSourceConstraints': {
  313. if (typeof obj.sourceName === 'string' && typeof obj.maxHeight === 'number') {
  314. logger.info(`SenderSourceConstraints: ${obj.sourceName} - ${obj.maxHeight}`);
  315. emitter.emit(RTCEvents.SENDER_VIDEO_CONSTRAINTS_CHANGED, obj);
  316. } else {
  317. logger.error(`Invalid SenderSourceConstraints: ${obj.sourceName} - ${obj.maxHeight}`);
  318. }
  319. break;
  320. }
  321. case 'ServerHello': {
  322. logger.info(`Received ServerHello, version=${obj.version}.`);
  323. break;
  324. }
  325. case 'VideoSourcesMap': {
  326. logger.info(`Received VideoSourcesMap: ${JSON.stringify(obj.mappedSources)}`);
  327. emitter.emit(RTCEvents.VIDEO_SSRCS_REMAPPED, obj);
  328. break;
  329. }
  330. case 'AudioSourcesMap': {
  331. logger.info(`Received AudioSourcesMap: ${JSON.stringify(obj.mappedSources)}`);
  332. emitter.emit(RTCEvents.AUDIO_SSRCS_REMAPPED, obj);
  333. break;
  334. }
  335. default: {
  336. logger.debug('Channel JSON-formatted message: ', obj);
  337. // The received message appears to be appropriately formatted
  338. // (i.e. is a JSON object which assigns a value to the
  339. // mandatory property colibriClass) so don't just swallow it,
  340. // expose it to public consumption.
  341. emitter.emit(`rtc.datachannel.${colibriClass}`, obj);
  342. }
  343. }
  344. };
  345. channel.onclose = (event: CloseEvent): void => {
  346. logger.debug(`Channel closed by ${this._closedFromClient ? 'client' : 'server'}`);
  347. if (channel !== this._channel) {
  348. logger.debug('Skip close handler, channel instance is not equal to stored one');
  349. return;
  350. }
  351. // When the JVB closes the connection gracefully due to the participant being alone in the meeting it uses
  352. // code 1001. However, the same code is also used by Cloudflare when it terminates the ws. Therefore, check
  353. // for the number of remote participants in the call and abort retries only when the endpoint is the only
  354. // endpoint in the call.
  355. const isGracefulClose = this._closedFromClient
  356. || (event.code === 1001 && this._conference.getParticipantCount() === 1);
  357. if (!isGracefulClose) {
  358. const { code, reason } = event;
  359. logger.error(`Channel closed: ${code} ${reason}`);
  360. if (this._mode === 'websocket') {
  361. this._retryWebSocketConnection(event);
  362. // We only want to send this event the first time the failure happens.
  363. if (this._connected !== false) {
  364. emitter.emit(RTCEvents.DATA_CHANNEL_CLOSED, {
  365. code,
  366. reason
  367. });
  368. }
  369. }
  370. }
  371. this._connected = false;
  372. // Remove the channel.
  373. this._channel = null;
  374. };
  375. // Store the channel.
  376. this._channel = channel;
  377. }
  378. /**
  379. * Sends passed object via the channel.
  380. * @param {object} jsonObject The object that will be sent.
  381. * @throws NetworkError or InvalidStateError from RTCDataChannel#send (@see
  382. * {@link https://developer.mozilla.org/docs/Web/API/RTCDataChannel/send})
  383. * or from WebSocket#send or Error with "No opened channel" message.
  384. */
  385. _send(jsonObject: Record<string, unknown>): void {
  386. const channel = this._channel;
  387. if (!this.isOpen()) {
  388. logger.error('Bridge Channel send: no opened channel.');
  389. throw new Error('No opened channel');
  390. }
  391. channel.send(JSON.stringify(jsonObject));
  392. }
  393. }