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.

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