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

BridgeChannel.js 15KB

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