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

BridgeChannel.js 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. import { getLogger } from '@jitsi/logger';
  2. import RTCEvents from '../../service/RTC/RTCEvents';
  3. import { createBridgeChannelClosedEvent } from '../../service/statistics/AnalyticsEvents';
  4. import FeatureFlags from '../flags/FeatureFlags';
  5. import Statistics from '../statistics/statistics';
  6. import GlobalOnErrorHandler from '../util/GlobalOnErrorHandler';
  7. const logger = getLogger(__filename);
  8. /**
  9. * Handles a WebRTC RTCPeerConnection or a WebSocket instance to communicate
  10. * with the videobridge.
  11. */
  12. export default class BridgeChannel {
  13. /**
  14. * Binds "ondatachannel" event listener on the given RTCPeerConnection
  15. * instance, or creates a WebSocket connection with the videobridge.
  16. * At least one of both, peerconnection or wsUrl parameters, must be
  17. * given.
  18. * @param {RTCPeerConnection} [peerconnection] WebRTC peer connection
  19. * instance.
  20. * @param {string} [wsUrl] WebSocket URL.
  21. * @param {EventEmitter} emitter the EventEmitter instance to use for event emission.
  22. */
  23. constructor(peerconnection, wsUrl, emitter) {
  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. // If a RTCPeerConnection is given, listen for new RTCDataChannel
  47. // event.
  48. if (peerconnection) {
  49. const datachannel
  50. = peerconnection.createDataChannel(
  51. 'JVB data channel', {
  52. protocol: 'http://jitsi.org/protocols/colibri'
  53. });
  54. // Handle the RTCDataChannel.
  55. this._handleChannel(datachannel);
  56. this._mode = 'datachannel';
  57. // Otherwise create a WebSocket connection.
  58. } else if (wsUrl) {
  59. this._areRetriesEnabled = true;
  60. this._wsUrl = wsUrl;
  61. this._initWebSocket();
  62. }
  63. }
  64. /**
  65. * Initializes the web socket channel.
  66. *
  67. * @returns {void}
  68. */
  69. _initWebSocket() {
  70. // Create a WebSocket instance.
  71. const ws = new WebSocket(this._wsUrl);
  72. // Handle the WebSocket.
  73. this._handleChannel(ws);
  74. this._mode = 'websocket';
  75. }
  76. /**
  77. * Starts the websocket connection retries.
  78. *
  79. * @returns {void}
  80. */
  81. _startConnectionRetries() {
  82. let timeoutS = 1;
  83. const reload = () => {
  84. if (this.isOpen()) {
  85. return;
  86. }
  87. this._initWebSocket(this._wsUrl);
  88. timeoutS = Math.min(timeoutS * 2, 60);
  89. this._retryTimeout = setTimeout(reload, timeoutS * 1000);
  90. };
  91. this._retryTimeout = setTimeout(reload, timeoutS * 1000);
  92. }
  93. /**
  94. * Stops the websocket connection retries.
  95. *
  96. * @returns {void}
  97. */
  98. _stopConnectionRetries() {
  99. if (this._retryTimeout) {
  100. clearTimeout(this._retryTimeout);
  101. this._retryTimeout = undefined;
  102. }
  103. }
  104. /**
  105. * Retries to establish the websocket connection after the connection was closed by the server.
  106. *
  107. * @param {CloseEvent} closeEvent - The close event that triggered the retries.
  108. * @returns {void}
  109. */
  110. _retryWebSocketConnection(closeEvent) {
  111. if (!this._areRetriesEnabled) {
  112. return;
  113. }
  114. const { code, reason } = closeEvent;
  115. Statistics.sendAnalytics(createBridgeChannelClosedEvent(code, reason));
  116. this._areRetriesEnabled = false;
  117. this._eventEmitter.once(RTCEvents.DATA_CHANNEL_OPEN, () => {
  118. this._stopConnectionRetries();
  119. this._areRetriesEnabled = true;
  120. });
  121. this._startConnectionRetries();
  122. }
  123. /**
  124. * The channel mode.
  125. * @return {string} "datachannel" or "websocket" (or null if not yet set).
  126. */
  127. get mode() {
  128. return this._mode;
  129. }
  130. /**
  131. * Closes the currently opened channel.
  132. */
  133. close() {
  134. this._closedFromClient = true;
  135. this._stopConnectionRetries();
  136. this._areRetriesEnabled = false;
  137. if (this._channel) {
  138. try {
  139. this._channel.close();
  140. } catch (error) {} // eslint-disable-line no-empty
  141. this._channel = null;
  142. }
  143. }
  144. /**
  145. * Whether there is an underlying RTCDataChannel or WebSocket and it's
  146. * open.
  147. * @return {boolean}
  148. */
  149. isOpen() {
  150. return this._channel && (this._channel.readyState === 'open'
  151. || this._channel.readyState === WebSocket.OPEN);
  152. }
  153. /**
  154. * Sends local stats via the bridge channel.
  155. * @param {Object} payload The payload of the message.
  156. * @throws NetworkError/InvalidStateError/Error if the operation fails or if there is no data channel created.
  157. */
  158. sendEndpointStatsMessage(payload) {
  159. this._send({
  160. colibriClass: 'EndpointStats',
  161. ...payload
  162. });
  163. }
  164. /**
  165. * Sends message via the channel.
  166. * @param {string} to The id of the endpoint that should receive the
  167. * message. If "" the message will be sent to all participants.
  168. * @param {object} payload The payload of the message.
  169. * @throws NetworkError or InvalidStateError from RTCDataChannel#send (@see
  170. * {@link https://developer.mozilla.org/docs/Web/API/RTCDataChannel/send})
  171. * or from WebSocket#send or Error with "No opened channel" message.
  172. */
  173. sendMessage(to, payload) {
  174. this._send({
  175. colibriClass: 'EndpointMessage',
  176. msgPayload: payload,
  177. to
  178. });
  179. }
  180. /**
  181. * Sends a "lastN value changed" message via the channel.
  182. * @param {number} value The new value for lastN. -1 means unlimited.
  183. */
  184. sendSetLastNMessage(value) {
  185. logger.log(`Sending lastN=${value}.`);
  186. this._send({
  187. colibriClass: 'LastNChangedEvent',
  188. lastN: value
  189. });
  190. }
  191. /**
  192. * Sends a "selected endpoints changed" message via the channel.
  193. *
  194. * @param {Array<string>} endpointIds - The ids of the selected endpoints.
  195. * @throws NetworkError or InvalidStateError from RTCDataChannel#send (@see
  196. * {@link https://developer.mozilla.org/docs/Web/API/RTCDataChannel/send})
  197. * or from WebSocket#send or Error with "No opened channel" message.
  198. */
  199. sendSelectedEndpointsMessage(endpointIds) {
  200. logger.log(`Sending selected endpoints: ${endpointIds}.`);
  201. this._send({
  202. colibriClass: 'SelectedEndpointsChangedEvent',
  203. selectedEndpoints: endpointIds
  204. });
  205. }
  206. /**
  207. * Sends a "receiver video constraint" message via the channel.
  208. * @param {Number} maxFrameHeightPixels the maximum frame height,
  209. * in pixels, this receiver is willing to receive
  210. */
  211. sendReceiverVideoConstraintMessage(maxFrameHeightPixels) {
  212. logger.log(`Sending ReceiverVideoConstraint with maxFrameHeight=${maxFrameHeightPixels}px`);
  213. this._send({
  214. colibriClass: 'ReceiverVideoConstraint',
  215. maxFrameHeight: maxFrameHeightPixels
  216. });
  217. }
  218. /**
  219. * Sends a 'ReceiverVideoConstraints' message via the bridge channel.
  220. *
  221. * @param {ReceiverVideoConstraints} constraints video constraints.
  222. */
  223. sendNewReceiverVideoConstraintsMessage(constraints) {
  224. logger.log(`Sending ReceiverVideoConstraints with ${JSON.stringify(constraints)}`);
  225. this._send({
  226. colibriClass: 'ReceiverVideoConstraints',
  227. ...constraints
  228. });
  229. }
  230. /**
  231. * Sends a 'VideoTypeMessage' message via the bridge channel.
  232. *
  233. * @param {string} videoType 'camera', 'desktop' or 'none'.
  234. * @deprecated to be replaced with sendSourceVideoTypeMessage
  235. */
  236. sendVideoTypeMessage(videoType) {
  237. logger.debug(`Sending VideoTypeMessage with video type as ${videoType}`);
  238. this._send({
  239. colibriClass: 'VideoTypeMessage',
  240. videoType
  241. });
  242. }
  243. /**
  244. * Sends a 'VideoTypeMessage' message via the bridge channel.
  245. *
  246. * @param {BridgeVideoType} videoType - the video type.
  247. * @param {SourceName} sourceName - the source name of the video track.
  248. * @returns {void}
  249. */
  250. sendSourceVideoTypeMessage(sourceName, videoType) {
  251. logger.info(`Sending SourceVideoTypeMessage with video type ${sourceName}: ${videoType}`);
  252. this._send({
  253. colibriClass: 'SourceVideoTypeMessage',
  254. sourceName,
  255. videoType
  256. });
  257. }
  258. /**
  259. * Set events on the given RTCDataChannel or WebSocket instance.
  260. */
  261. _handleChannel(channel) {
  262. const emitter = this._eventEmitter;
  263. channel.onopen = () => {
  264. logger.info(`${this._mode} channel opened`);
  265. // Code sample for sending string and/or binary data.
  266. // Sends string message to the bridge:
  267. // channel.send("Hello bridge!");
  268. // Sends 12 bytes binary message to the bridge:
  269. // channel.send(new ArrayBuffer(12));
  270. emitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  271. };
  272. channel.onerror = event => {
  273. // WS error events contain no information about the failure (this is available in the onclose event) and
  274. // the event references the WS object itself, which causes hangs on mobile.
  275. if (this._mode !== 'websocket') {
  276. logger.error(`Channel error: ${event.message}`);
  277. }
  278. };
  279. channel.onmessage = ({ data }) => {
  280. // JSON object.
  281. let obj;
  282. try {
  283. obj = JSON.parse(data);
  284. } catch (error) {
  285. GlobalOnErrorHandler.callErrorHandler(error);
  286. logger.error('Failed to parse channel message as JSON: ', data, error);
  287. return;
  288. }
  289. const colibriClass = obj.colibriClass;
  290. switch (colibriClass) {
  291. case 'DominantSpeakerEndpointChangeEvent': {
  292. const { dominantSpeakerEndpoint, previousSpeakers = [] } = obj;
  293. logger.debug(`Dominant speaker: ${dominantSpeakerEndpoint}, previous speakers: ${previousSpeakers}`);
  294. emitter.emit(RTCEvents.DOMINANT_SPEAKER_CHANGED, dominantSpeakerEndpoint, previousSpeakers);
  295. break;
  296. }
  297. case 'EndpointConnectivityStatusChangeEvent': {
  298. const endpoint = obj.endpoint;
  299. const isActive = obj.active === 'true';
  300. logger.info(`Endpoint connection status changed: ${endpoint} active=${isActive}`);
  301. emitter.emit(RTCEvents.ENDPOINT_CONN_STATUS_CHANGED, endpoint, isActive);
  302. break;
  303. }
  304. case 'EndpointMessage': {
  305. emitter.emit(RTCEvents.ENDPOINT_MESSAGE_RECEIVED, obj.from, obj.msgPayload);
  306. break;
  307. }
  308. case 'EndpointStats': {
  309. emitter.emit(RTCEvents.ENDPOINT_STATS_RECEIVED, obj.from, obj);
  310. break;
  311. }
  312. case 'LastNEndpointsChangeEvent': {
  313. if (!FeatureFlags.isSourceNameSignalingEnabled()) {
  314. // The new/latest list of last-n endpoint IDs (i.e. endpoints for which the bridge is sending
  315. // video).
  316. const lastNEndpoints = obj.lastNEndpoints;
  317. logger.info(`New forwarded endpoints: ${lastNEndpoints}`);
  318. emitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED, lastNEndpoints);
  319. }
  320. break;
  321. }
  322. case 'ForwardedSources': {
  323. if (FeatureFlags.isSourceNameSignalingEnabled()) {
  324. // The new/latest list of forwarded sources
  325. const forwardedSources = obj.forwardedSources;
  326. logger.info(`New forwarded sources: ${forwardedSources}`);
  327. emitter.emit(RTCEvents.FORWARDED_SOURCES_CHANGED, forwardedSources);
  328. }
  329. break;
  330. }
  331. case 'SenderVideoConstraints': {
  332. const videoConstraints = obj.videoConstraints;
  333. if (videoConstraints) {
  334. logger.info(`SenderVideoConstraints: ${JSON.stringify(videoConstraints)}`);
  335. emitter.emit(RTCEvents.SENDER_VIDEO_CONSTRAINTS_CHANGED, videoConstraints);
  336. }
  337. break;
  338. }
  339. case 'SenderSourceConstraints': {
  340. if (FeatureFlags.isSourceNameSignalingEnabled()) {
  341. const { sourceName, maxHeight } = obj;
  342. if (typeof sourceName === 'string' && typeof maxHeight === 'number') {
  343. // eslint-disable-next-line object-property-newline
  344. logger.info(`SenderSourceConstraints: ${JSON.stringify({ sourceName, maxHeight })}`);
  345. emitter.emit(
  346. RTCEvents.SENDER_VIDEO_CONSTRAINTS_CHANGED, {
  347. sourceName,
  348. maxHeight
  349. }
  350. );
  351. } else {
  352. logger.error(`Invalid SenderSourceConstraints: ${JSON.stringify(obj)}`);
  353. }
  354. }
  355. break;
  356. }
  357. case 'ServerHello': {
  358. logger.info(`Received ServerHello, version=${obj.version}.`);
  359. break;
  360. }
  361. default: {
  362. logger.debug('Channel JSON-formatted message: ', obj);
  363. // The received message appears to be appropriately formatted
  364. // (i.e. is a JSON object which assigns a value to the
  365. // mandatory property colibriClass) so don't just swallow it,
  366. // expose it to public consumption.
  367. emitter.emit(`rtc.datachannel.${colibriClass}`, obj);
  368. }
  369. }
  370. };
  371. channel.onclose = event => {
  372. logger.info(`Channel closed by ${this._closedFromClient ? 'client' : 'server'}`);
  373. if (this._mode === 'websocket') {
  374. if (!this._closedFromClient) {
  375. logger.error(`Channel closed: ${event.code} ${event.reason}`);
  376. this._retryWebSocketConnection(event);
  377. }
  378. }
  379. // Remove the channel.
  380. this._channel = null;
  381. };
  382. // Store the channel.
  383. this._channel = channel;
  384. }
  385. /**
  386. * Sends passed object via the channel.
  387. * @param {object} jsonObject The object that will be sent.
  388. * @throws NetworkError or InvalidStateError from RTCDataChannel#send (@see
  389. * {@link https://developer.mozilla.org/docs/Web/API/RTCDataChannel/send})
  390. * or from WebSocket#send or Error with "No opened channel" message.
  391. */
  392. _send(jsonObject) {
  393. const channel = this._channel;
  394. if (!this.isOpen()) {
  395. logger.error('Bridge Channel send: no opened channel.');
  396. throw new Error('No opened channel');
  397. }
  398. channel.send(JSON.stringify(jsonObject));
  399. }
  400. }