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.

RTC.js 26KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823
  1. import { getLogger } from '@jitsi/logger';
  2. import * as JitsiConferenceEvents from '../../JitsiConferenceEvents';
  3. import { MediaType } from '../../service/RTC/MediaType';
  4. import RTCEvents from '../../service/RTC/RTCEvents';
  5. import browser from '../browser';
  6. import GlobalOnErrorHandler from '../util/GlobalOnErrorHandler';
  7. import Listenable from '../util/Listenable';
  8. import { safeCounterIncrement } from '../util/MathUtil';
  9. import BridgeChannel from './BridgeChannel';
  10. import JitsiLocalTrack from './JitsiLocalTrack';
  11. import RTCUtils from './RTCUtils';
  12. import TraceablePeerConnection from './TraceablePeerConnection';
  13. const logger = getLogger(__filename);
  14. /**
  15. * The counter used to generated id numbers assigned to peer connections
  16. * @type {number}
  17. */
  18. let peerConnectionIdCounter = 0;
  19. /**
  20. * The counter used to generate id number for the local
  21. * <code>MediaStreamTrack</code>s.
  22. * @type {number}
  23. */
  24. let rtcTrackIdCounter = 0;
  25. /**
  26. * Creates {@code JitsiLocalTrack} instances from the passed in meta information
  27. * about MedieaTracks.
  28. *
  29. * @param {Object[]} mediaStreamMetaData - An array of meta information with
  30. * MediaTrack instances. Each can look like:
  31. * {{
  32. * stream: MediaStream instance that holds a track with audio or video,
  33. * track: MediaTrack within the MediaStream,
  34. * videoType: "camera" or "desktop" or falsy,
  35. * sourceId: ID of the desktopsharing source,
  36. * sourceType: The desktopsharing source type,
  37. * effects: Array of effect types
  38. * }}
  39. */
  40. function _createLocalTracks(mediaStreamMetaData = []) {
  41. return mediaStreamMetaData.map(metaData => {
  42. const {
  43. sourceId,
  44. sourceType,
  45. stream,
  46. track,
  47. videoType,
  48. effects
  49. } = metaData;
  50. const { deviceId, facingMode } = track.getSettings();
  51. // FIXME Move rtcTrackIdCounter to a static method in JitsiLocalTrack
  52. // so RTC does not need to handle ID management. This move would be
  53. // safer to do once the old createLocalTracks is removed.
  54. rtcTrackIdCounter = safeCounterIncrement(rtcTrackIdCounter);
  55. return new JitsiLocalTrack({
  56. deviceId,
  57. facingMode,
  58. mediaType: track.kind,
  59. rtcId: rtcTrackIdCounter,
  60. sourceId,
  61. sourceType,
  62. stream,
  63. track,
  64. videoType: videoType || null,
  65. effects
  66. });
  67. });
  68. }
  69. /**
  70. *
  71. */
  72. export default class RTC extends Listenable {
  73. /**
  74. *
  75. * @param conference
  76. * @param options
  77. */
  78. constructor(conference, options = {}) {
  79. super();
  80. this.conference = conference;
  81. /**
  82. * A map of active <tt>TraceablePeerConnection</tt>.
  83. * @type {Map.<number, TraceablePeerConnection>}
  84. */
  85. this.peerConnections = new Map();
  86. this.localTracks = [];
  87. this.options = options;
  88. // BridgeChannel instance.
  89. // @private
  90. // @type {BridgeChannel}
  91. this._channel = null;
  92. /**
  93. * The value specified to the last invocation of setLastN before the
  94. * channel completed opening. If non-null, the value will be sent
  95. * through a channel (once) as soon as it opens and will then be
  96. * discarded.
  97. * @private
  98. * @type {number}
  99. */
  100. this._lastN = undefined;
  101. /**
  102. * Defines the forwarded sources list. It can be null or an array once initialised with a channel forwarded
  103. * sources event.
  104. *
  105. * @type {Array<string>|null}
  106. * @private
  107. */
  108. this._forwardedSources = null;
  109. // The forwarded sources change listener.
  110. this._forwardedSourcesChangeListener = this._onForwardedSourcesChanged.bind(this);
  111. this._onDeviceListChanged = this._onDeviceListChanged.bind(this);
  112. this._updateAudioOutputForAudioTracks = this._updateAudioOutputForAudioTracks.bind(this);
  113. // Switch audio output device on all remote audio tracks. Local audio
  114. // tracks handle this event by themselves.
  115. if (RTCUtils.isDeviceChangeAvailable('output')) {
  116. RTCUtils.addListener(
  117. RTCEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  118. this._updateAudioOutputForAudioTracks
  119. );
  120. RTCUtils.addListener(
  121. RTCEvents.DEVICE_LIST_CHANGED,
  122. this._onDeviceListChanged
  123. );
  124. }
  125. }
  126. /**
  127. * Removes any listeners and stored state from this {@code RTC} instance.
  128. *
  129. * @returns {void}
  130. */
  131. destroy() {
  132. RTCUtils.removeListener(RTCEvents.AUDIO_OUTPUT_DEVICE_CHANGED, this._updateAudioOutputForAudioTracks);
  133. RTCUtils.removeListener(RTCEvents.DEVICE_LIST_CHANGED, this._onDeviceListChanged);
  134. if (this._channelOpenListener) {
  135. this.removeListener(RTCEvents.DATA_CHANNEL_OPEN, this._channelOpenListener);
  136. }
  137. }
  138. /**
  139. * Exposes the private helper for converting a WebRTC MediaStream to a
  140. * JitsiLocalTrack.
  141. *
  142. * @param {Array<Object>} tracksInfo
  143. * @returns {Array<JitsiLocalTrack>}
  144. */
  145. static createLocalTracks(tracksInfo) {
  146. return _createLocalTracks(tracksInfo);
  147. }
  148. /**
  149. * Creates the local MediaStreams.
  150. * @param {object} [options] Optional parameters.
  151. * @param {Array=} options.devices The devices that will be requested.
  152. * @param {string=} options.resolution Resolution constraints.
  153. * @param {string=} options.cameraDeviceId
  154. * @param {string=} options.micDeviceId
  155. * @returns {*} Promise object that will receive the new JitsiTracks
  156. */
  157. static obtainAudioAndVideoPermissions(options) {
  158. return RTCUtils.obtainAudioAndVideoPermissions(options)
  159. .then(tracksInfo => _createLocalTracks(tracksInfo));
  160. }
  161. /**
  162. * Initializes the bridge channel of this instance.
  163. * At least one of both, peerconnection or wsUrl parameters, must be
  164. * given.
  165. * @param {RTCPeerConnection} [peerconnection] WebRTC peer connection
  166. * instance.
  167. * @param {string} [wsUrl] WebSocket URL.
  168. */
  169. initializeBridgeChannel(peerconnection, wsUrl) {
  170. this._channel = new BridgeChannel(peerconnection, wsUrl, this.eventEmitter, this.conference);
  171. this._channelOpenListener = () => {
  172. const logError = (error, msgType, value) => {
  173. GlobalOnErrorHandler.callErrorHandler(error);
  174. logger.error(`Cannot send ${msgType}(${JSON.stringify(value)}) endpoint message`, error);
  175. };
  176. // When the channel becomes available, tell the bridge about video selections so that it can do adaptive
  177. // simulcast, we want the notification to trigger even if userJid is undefined, or null.
  178. if (this._receiverVideoConstraints) {
  179. try {
  180. this._channel.sendReceiverVideoConstraintsMessage(this._receiverVideoConstraints);
  181. } catch (error) {
  182. logError(error, 'ReceiverVideoConstraints', this._receiverVideoConstraints);
  183. }
  184. }
  185. if (typeof this._lastN !== 'undefined' && this._lastN !== -1) {
  186. try {
  187. this._channel.sendSetLastNMessage(this._lastN);
  188. } catch (error) {
  189. logError(error, 'LastNChangedEvent', this._lastN);
  190. }
  191. }
  192. };
  193. this.addListener(RTCEvents.DATA_CHANNEL_OPEN, this._channelOpenListener);
  194. // Add forwarded sources change listener.
  195. this.addListener(RTCEvents.FORWARDED_SOURCES_CHANGED, this._forwardedSourcesChangeListener);
  196. }
  197. /**
  198. * Callback invoked when the list of known audio and video devices has
  199. * been updated. Attempts to update the known available audio output
  200. * devices.
  201. *
  202. * @private
  203. * @returns {void}
  204. */
  205. _onDeviceListChanged() {
  206. this._updateAudioOutputForAudioTracks(RTCUtils.getAudioOutputDevice());
  207. }
  208. /**
  209. * Receives events when forwarded sources had changed.
  210. *
  211. * @param {array} forwardedSources The new forwarded sources.
  212. * @private
  213. */
  214. _onForwardedSourcesChanged(forwardedSources = []) {
  215. const oldForwardedSources = this._forwardedSources || [];
  216. let leavingForwardedSources = [];
  217. let enteringForwardedSources = [];
  218. const timestamp = Date.now();
  219. this._forwardedSources = forwardedSources;
  220. leavingForwardedSources = oldForwardedSources.filter(sourceName => !this.isInForwardedSources(sourceName));
  221. enteringForwardedSources = forwardedSources.filter(
  222. sourceName => oldForwardedSources.indexOf(sourceName) === -1);
  223. logger.debug(`Fowarded sources changed leaving=${leavingForwardedSources}, entering=`
  224. + `${enteringForwardedSources} at ${timestamp}`);
  225. this.conference.eventEmitter.emit(
  226. JitsiConferenceEvents.FORWARDED_SOURCES_CHANGED,
  227. leavingForwardedSources,
  228. enteringForwardedSources,
  229. timestamp);
  230. }
  231. /**
  232. * Should be called when current media session ends and after the
  233. * PeerConnection has been closed using PeerConnection.close() method.
  234. */
  235. onCallEnded() {
  236. if (this._channel) {
  237. // The BridgeChannel is not explicitly closed as the PeerConnection
  238. // is closed on call ended which triggers datachannel onclose
  239. // events. If using a WebSocket, the channel must be closed since
  240. // it is not managed by the PeerConnection.
  241. // The reference is cleared to disable any logic related to the
  242. // channel.
  243. if (this._channel && this._channel.mode === 'websocket') {
  244. this._channel.close();
  245. }
  246. this._channel = null;
  247. }
  248. }
  249. /**
  250. * Sets the capture frame rate to be used for desktop tracks.
  251. *
  252. * @param {number} maxFps framerate to be used for desktop track capture.
  253. */
  254. setDesktopSharingFrameRate(maxFps) {
  255. RTCUtils.setDesktopSharingFrameRate(maxFps);
  256. }
  257. /**
  258. * Sets the receiver video constraints that determine how bitrate is allocated to each of the video streams
  259. * requested from the bridge. The constraints are cached and sent through the bridge channel once the channel
  260. * is established.
  261. * @param {*} constraints
  262. */
  263. setReceiverVideoConstraints(constraints) {
  264. this._receiverVideoConstraints = constraints;
  265. if (this._channel && this._channel.isOpen()) {
  266. this._channel.sendReceiverVideoConstraintsMessage(constraints);
  267. }
  268. }
  269. /**
  270. * Sends the track's video type to the JVB.
  271. * @param {SourceName} sourceName - the track's source name.
  272. * @param {BridgeVideoType} videoType - the track's video type.
  273. */
  274. sendSourceVideoType(sourceName, videoType) {
  275. if (this._channel && this._channel.isOpen()) {
  276. this._channel.sendSourceVideoTypeMessage(sourceName, videoType);
  277. }
  278. }
  279. /**
  280. *
  281. * @param eventType
  282. * @param listener
  283. */
  284. static addListener(eventType, listener) {
  285. RTCUtils.addListener(eventType, listener);
  286. }
  287. /**
  288. *
  289. * @param eventType
  290. * @param listener
  291. */
  292. static removeListener(eventType, listener) {
  293. RTCUtils.removeListener(eventType, listener);
  294. }
  295. /**
  296. *
  297. * @param options
  298. */
  299. static init(options = {}) {
  300. this.options = options;
  301. return RTCUtils.init(this.options);
  302. }
  303. /* eslint-disable max-params */
  304. /**
  305. * Creates new <tt>TraceablePeerConnection</tt>
  306. * @param {SignalingLayer} signaling The signaling layer that will provide information about the media or
  307. * participants which is not carried over SDP.
  308. * @param {object} pcConfig The {@code RTCConfiguration} to use for the WebRTC peer connection.
  309. * @param {boolean} isP2P Indicates whether or not the new TPC will be used in a peer to peer type of session.
  310. * @param {object} options The config options.
  311. * @param {boolean} options.enableInsertableStreams - Set to true when the insertable streams constraints is to be
  312. * enabled on the PeerConnection.
  313. * @param {boolean} options.disableSimulcast If set to 'true' will disable the simulcast.
  314. * @param {boolean} options.disableRtx If set to 'true' will disable the RTX.
  315. * @param {boolean} options.startSilent If set to 'true' no audio will be sent or received.
  316. * @return {TraceablePeerConnection}
  317. */
  318. createPeerConnection(signaling, pcConfig, isP2P, options) {
  319. const pcConstraints = JSON.parse(JSON.stringify(RTCUtils.pcConstraints));
  320. if (options.enableInsertableStreams) {
  321. logger.debug('E2EE - setting insertable streams constraints');
  322. pcConfig.encodedInsertableStreams = true;
  323. }
  324. // TODO: remove this.
  325. const supportsSdpSemantics = browser.isChromiumBased() && !options.usesUnifiedPlan;
  326. if (supportsSdpSemantics) {
  327. logger.debug('WebRTC application is running in plan-b mode');
  328. pcConfig.sdpSemantics = 'plan-b';
  329. }
  330. if (options.forceTurnRelay) {
  331. pcConfig.iceTransportPolicy = 'relay';
  332. }
  333. // Set the RTCBundlePolicy to max-bundle so that only one set of ice candidates is generated.
  334. // The default policy generates separate ice candidates for audio and video connections.
  335. // This change is necessary for Unified plan to work properly on Chrome and Safari.
  336. pcConfig.bundlePolicy = 'max-bundle';
  337. peerConnectionIdCounter = safeCounterIncrement(peerConnectionIdCounter);
  338. const newConnection
  339. = new TraceablePeerConnection(
  340. this,
  341. peerConnectionIdCounter,
  342. signaling,
  343. pcConfig, pcConstraints,
  344. isP2P, options);
  345. this.peerConnections.set(newConnection.id, newConnection);
  346. return newConnection;
  347. }
  348. /* eslint-enable max-params */
  349. /**
  350. * Removed given peer connection from this RTC module instance.
  351. * @param {TraceablePeerConnection} traceablePeerConnection
  352. * @return {boolean} <tt>true</tt> if the given peer connection was removed
  353. * successfully or <tt>false</tt> if there was no peer connection mapped in
  354. * this RTC instance.
  355. */
  356. _removePeerConnection(traceablePeerConnection) {
  357. const id = traceablePeerConnection.id;
  358. if (this.peerConnections.has(id)) {
  359. // NOTE Remote tracks are not removed here.
  360. this.peerConnections.delete(id);
  361. return true;
  362. }
  363. return false;
  364. }
  365. /**
  366. *
  367. * @param track
  368. */
  369. addLocalTrack(track) {
  370. if (!track) {
  371. throw new Error('track must not be null nor undefined');
  372. }
  373. this.localTracks.push(track);
  374. track.conference = this.conference;
  375. }
  376. /**
  377. * Get forwarded sources list.
  378. * @returns {Array<string>|null}
  379. */
  380. getForwardedSources() {
  381. return this._forwardedSources;
  382. }
  383. /**
  384. * Get local video track.
  385. * @returns {JitsiLocalTrack|undefined}
  386. */
  387. getLocalVideoTrack() {
  388. const localVideo = this.getLocalTracks(MediaType.VIDEO);
  389. return localVideo.length ? localVideo[0] : undefined;
  390. }
  391. /**
  392. * Returns all the local video tracks.
  393. * @returns {Array<JitsiLocalTrack>}
  394. */
  395. getLocalVideoTracks() {
  396. return this.getLocalTracks(MediaType.VIDEO);
  397. }
  398. /**
  399. * Get local audio track.
  400. * @returns {JitsiLocalTrack|undefined}
  401. */
  402. getLocalAudioTrack() {
  403. const localAudio = this.getLocalTracks(MediaType.AUDIO);
  404. return localAudio.length ? localAudio[0] : undefined;
  405. }
  406. /**
  407. * Returns the endpoint id for the local user.
  408. * @returns {string}
  409. */
  410. getLocalEndpointId() {
  411. return this.conference.myUserId();
  412. }
  413. /**
  414. * Returns the local tracks of the given media type, or all local tracks if
  415. * no specific type is given.
  416. * @param {MediaType} [mediaType] Optional media type filter.
  417. * (audio or video).
  418. */
  419. getLocalTracks(mediaType) {
  420. let tracks = this.localTracks.slice();
  421. if (mediaType !== undefined) {
  422. tracks = tracks.filter(
  423. track => track.getType() === mediaType);
  424. }
  425. return tracks;
  426. }
  427. /**
  428. * Obtains all remote tracks currently known to this RTC module instance.
  429. * @param {MediaType} [mediaType] The remote tracks will be filtered
  430. * by their media type if this argument is specified.
  431. * @return {Array<JitsiRemoteTrack>}
  432. */
  433. getRemoteTracks(mediaType) {
  434. let remoteTracks = [];
  435. for (const tpc of this.peerConnections.values()) {
  436. const pcRemoteTracks = tpc.getRemoteTracks(undefined, mediaType);
  437. if (pcRemoteTracks) {
  438. remoteTracks = remoteTracks.concat(pcRemoteTracks);
  439. }
  440. }
  441. return remoteTracks;
  442. }
  443. /**
  444. * Set mute for all local audio streams attached to the conference.
  445. * @param value The mute value.
  446. * @returns {Promise}
  447. */
  448. setAudioMute(value) {
  449. const mutePromises = [];
  450. this.getLocalTracks(MediaType.AUDIO).forEach(audioTrack => {
  451. // this is a Promise
  452. mutePromises.push(value ? audioTrack.mute() : audioTrack.unmute());
  453. });
  454. // We return a Promise from all Promises so we can wait for their
  455. // execution.
  456. return Promise.all(mutePromises);
  457. }
  458. /**
  459. * Set mute for all local video streams attached to the conference.
  460. * @param value The mute value.
  461. * @returns {Promise}
  462. */
  463. setVideoMute(value) {
  464. const mutePromises = [];
  465. this.getLocalTracks(MediaType.VIDEO)
  466. .forEach(videoTrack => {
  467. // this is a Promise
  468. mutePromises.push(value ? videoTrack.mute() : videoTrack.unmute());
  469. });
  470. // We return a Promise from all Promises so we can wait for their
  471. // execution.
  472. return Promise.all(mutePromises);
  473. }
  474. /**
  475. *
  476. * @param track
  477. */
  478. removeLocalTrack(track) {
  479. const pos = this.localTracks.indexOf(track);
  480. if (pos === -1) {
  481. return;
  482. }
  483. this.localTracks.splice(pos, 1);
  484. }
  485. /**
  486. *
  487. * @param elSelector
  488. * @param stream
  489. */
  490. static attachMediaStream(elSelector, stream) {
  491. return RTCUtils.attachMediaStream(elSelector, stream);
  492. }
  493. /**
  494. * Returns true if retrieving the list of input devices is supported
  495. * and false if not.
  496. */
  497. static isDeviceListAvailable() {
  498. return RTCUtils.isDeviceListAvailable();
  499. }
  500. /**
  501. * Returns true if changing the input (camera / microphone) or output
  502. * (audio) device is supported and false if not.
  503. * @param {string} [deviceType] Type of device to change. Default is
  504. * undefined or 'input', 'output' - for audio output device change.
  505. * @returns {boolean} true if available, false otherwise.
  506. */
  507. static isDeviceChangeAvailable(deviceType) {
  508. return RTCUtils.isDeviceChangeAvailable(deviceType);
  509. }
  510. /**
  511. * Returns whether the current execution environment supports WebRTC (for
  512. * use within this library).
  513. *
  514. * @returns {boolean} {@code true} if WebRTC is supported in the current
  515. * execution environment (for use within this library); {@code false},
  516. * otherwise.
  517. */
  518. static isWebRtcSupported() {
  519. return browser.isSupported();
  520. }
  521. /**
  522. * Returns currently used audio output device id, '' stands for default
  523. * device
  524. * @returns {string}
  525. */
  526. static getAudioOutputDevice() {
  527. return RTCUtils.getAudioOutputDevice();
  528. }
  529. /**
  530. * Returns list of available media devices if its obtained, otherwise an
  531. * empty array is returned/
  532. * @returns {array} list of available media devices.
  533. */
  534. static getCurrentlyAvailableMediaDevices() {
  535. return RTCUtils.getCurrentlyAvailableMediaDevices();
  536. }
  537. /**
  538. * Returns whether available devices have permissions granted
  539. * @returns {Boolean}
  540. */
  541. static arePermissionsGrantedForAvailableDevices() {
  542. return RTCUtils.arePermissionsGrantedForAvailableDevices();
  543. }
  544. /**
  545. * Returns event data for device to be reported to stats.
  546. * @returns {MediaDeviceInfo} device.
  547. */
  548. static getEventDataForActiveDevice(device) {
  549. return RTCUtils.getEventDataForActiveDevice(device);
  550. }
  551. /**
  552. * Sets current audio output device.
  553. * @param {string} deviceId Id of 'audiooutput' device from
  554. * navigator.mediaDevices.enumerateDevices().
  555. * @returns {Promise} resolves when audio output is changed, is rejected
  556. * otherwise
  557. */
  558. static setAudioOutputDevice(deviceId) {
  559. return RTCUtils.setAudioOutputDevice(deviceId);
  560. }
  561. /**
  562. * Returns <tt>true<tt/> if given WebRTC MediaStream is considered a valid
  563. * "user" stream which means that it's not a "receive only" stream nor a
  564. * "mixed" JVB stream.
  565. *
  566. * Clients that implement Unified Plan, such as Firefox use recvonly
  567. * "streams/channels/tracks" for receiving remote stream/tracks, as opposed
  568. * to Plan B where there are only 3 channels: audio, video and data.
  569. *
  570. * @param {MediaStream} stream The WebRTC MediaStream instance.
  571. * @returns {boolean}
  572. */
  573. static isUserStream(stream) {
  574. return RTC.isUserStreamById(stream.id);
  575. }
  576. /**
  577. * Returns <tt>true<tt/> if a WebRTC MediaStream identified by given stream
  578. * ID is considered a valid "user" stream which means that it's not a
  579. * "receive only" stream nor a "mixed" JVB stream.
  580. *
  581. * Clients that implement Unified Plan, such as Firefox use recvonly
  582. * "streams/channels/tracks" for receiving remote stream/tracks, as opposed
  583. * to Plan B where there are only 3 channels: audio, video and data.
  584. *
  585. * @param {string} streamId The id of WebRTC MediaStream.
  586. * @returns {boolean}
  587. */
  588. static isUserStreamById(streamId) {
  589. return streamId && streamId !== 'mixedmslabel'
  590. && streamId !== 'default';
  591. }
  592. /**
  593. * Allows to receive list of available cameras/microphones.
  594. * @param {function} callback Would receive array of devices as an
  595. * argument.
  596. */
  597. static enumerateDevices(callback) {
  598. RTCUtils.enumerateDevices(callback);
  599. }
  600. /**
  601. * A method to handle stopping of the stream.
  602. * One point to handle the differences in various implementations.
  603. * @param {MediaStream} mediaStream MediaStream object to stop.
  604. */
  605. static stopMediaStream(mediaStream) {
  606. RTCUtils.stopMediaStream(mediaStream);
  607. }
  608. /**
  609. * Returns whether the desktop sharing is enabled or not.
  610. * @returns {boolean}
  611. */
  612. static isDesktopSharingEnabled() {
  613. return RTCUtils.isDesktopSharingEnabled();
  614. }
  615. /**
  616. * Closes the currently opened bridge channel.
  617. */
  618. closeBridgeChannel() {
  619. if (this._channel) {
  620. this._channel.close();
  621. this._channel = null;
  622. }
  623. }
  624. /* eslint-disable max-params */
  625. /**
  626. *
  627. * @param {TraceablePeerConnection} tpc
  628. * @param {number} ssrc
  629. * @param {number} audioLevel
  630. * @param {boolean} isLocal
  631. */
  632. setAudioLevel(tpc, ssrc, audioLevel, isLocal) {
  633. const track = tpc.getTrackBySSRC(ssrc);
  634. if (!track) {
  635. return;
  636. } else if (!track.isAudioTrack()) {
  637. logger.warn(`Received audio level for non-audio track: ${ssrc}`);
  638. return;
  639. } else if (track.isLocal() !== isLocal) {
  640. logger.error(
  641. `${track} was expected to ${isLocal ? 'be' : 'not be'} local`);
  642. }
  643. track.setAudioLevel(audioLevel, tpc);
  644. }
  645. /**
  646. * Sends message via the bridge channel.
  647. * @param {string} to The id of the endpoint that should receive the
  648. * message. If "" the message will be sent to all participants.
  649. * @param {object} payload The payload of the message.
  650. * @throws NetworkError or InvalidStateError or Error if the operation
  651. * fails or there is no data channel created.
  652. */
  653. sendChannelMessage(to, payload) {
  654. if (this._channel) {
  655. this._channel.sendMessage(to, payload);
  656. } else {
  657. throw new Error('Channel support is disabled!');
  658. }
  659. }
  660. /**
  661. * Sends the local stats via the bridge channel.
  662. * @param {Object} payload The payload of the message.
  663. * @throws NetworkError/InvalidStateError/Error if the operation fails or if there is no data channel created.
  664. */
  665. sendEndpointStatsMessage(payload) {
  666. if (this._channel && this._channel.isOpen()) {
  667. this._channel.sendEndpointStatsMessage(payload);
  668. }
  669. }
  670. /**
  671. * Selects a new value for "lastN". The requested amount of videos are going
  672. * to be delivered after the value is in effect. Set to -1 for unlimited or
  673. * all available videos.
  674. * @param {number} value the new value for lastN.
  675. */
  676. setLastN(value) {
  677. if (this._lastN !== value) {
  678. this._lastN = value;
  679. if (this._channel && this._channel.isOpen()) {
  680. this._channel.sendSetLastNMessage(value);
  681. }
  682. this.eventEmitter.emit(RTCEvents.LASTN_VALUE_CHANGED, value);
  683. }
  684. }
  685. /**
  686. * Indicates if the source name is currently included in the forwarded sources.
  687. *
  688. * @param {string} sourceName The source name that we check for forwarded sources.
  689. * @returns {boolean} true if the source name is in the forwarded sources or if we don't have bridge channel
  690. * support, otherwise we return false.
  691. */
  692. isInForwardedSources(sourceName) {
  693. return !this._forwardedSources // forwardedSources not initialised yet.
  694. || this._forwardedSources.indexOf(sourceName) > -1;
  695. }
  696. /**
  697. * Updates the target audio output device for all remote audio tracks.
  698. *
  699. * @param {string} deviceId - The device id of the audio ouput device to
  700. * use for all remote tracks.
  701. * @private
  702. * @returns {void}
  703. */
  704. _updateAudioOutputForAudioTracks(deviceId) {
  705. const remoteAudioTracks = this.getRemoteTracks(MediaType.AUDIO);
  706. for (const track of remoteAudioTracks) {
  707. track.setAudioOutput(deviceId);
  708. }
  709. }
  710. }