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 29KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924
  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 receiver video constraints that determine how bitrate is allocated to each of the video streams
  291. * requested from the bridge. The constraints are cached and sent through the bridge channel once the channel
  292. * is established.
  293. * @param {*} constraints
  294. */
  295. setNewReceiverVideoConstraints(constraints) {
  296. this._receiverVideoConstraints = constraints;
  297. if (this._channel && this._channel.isOpen()) {
  298. this._channel.sendNewReceiverVideoConstraintsMessage(constraints);
  299. }
  300. }
  301. /**
  302. * Sets the maximum video size the local participant should receive from
  303. * remote participants. Will cache the value and send it through the channel
  304. * once it is created.
  305. *
  306. * @param {number} maxFrameHeightPixels the maximum frame height, in pixels,
  307. * this receiver is willing to receive.
  308. * @returns {void}
  309. */
  310. setReceiverVideoConstraint(maxFrameHeight) {
  311. this._maxFrameHeight = maxFrameHeight;
  312. if (this._channel && this._channel.isOpen()) {
  313. this._channel.sendReceiverVideoConstraintMessage(maxFrameHeight);
  314. }
  315. }
  316. /**
  317. * Sets the video type and availability for the local video source.
  318. *
  319. * @param {string} videoType 'camera' for camera, 'desktop' for screenshare and
  320. * 'none' for when local video source is muted or removed from the peerconnection.
  321. * @returns {void}
  322. */
  323. setVideoType(videoType) {
  324. if (this._videoType !== videoType) {
  325. this._videoType = videoType;
  326. if (this._channel && this._channel.isOpen()) {
  327. this._channel.sendVideoTypeMessage(videoType);
  328. }
  329. }
  330. }
  331. /**
  332. * Elects the participants with the given ids to be the selected
  333. * participants in order to always receive video for this participant (even
  334. * when last n is enabled). If there is no channel we store it and send it
  335. * through the channel once it is created.
  336. *
  337. * @param {Array<string>} ids - The user ids.
  338. * @throws NetworkError or InvalidStateError or Error if the operation
  339. * fails.
  340. * @returns {void}
  341. */
  342. selectEndpoints(ids) {
  343. this._selectedEndpoints = ids;
  344. if (this._channel && this._channel.isOpen()) {
  345. this._channel.sendSelectedEndpointsMessage(ids);
  346. }
  347. }
  348. /**
  349. *
  350. * @param eventType
  351. * @param listener
  352. */
  353. static addListener(eventType, listener) {
  354. RTCUtils.addListener(eventType, listener);
  355. }
  356. /**
  357. *
  358. * @param eventType
  359. * @param listener
  360. */
  361. static removeListener(eventType, listener) {
  362. RTCUtils.removeListener(eventType, listener);
  363. }
  364. /**
  365. *
  366. * @param options
  367. */
  368. static init(options = {}) {
  369. this.options = options;
  370. return RTCUtils.init(this.options);
  371. }
  372. /* eslint-disable max-params */
  373. /**
  374. * Creates new <tt>TraceablePeerConnection</tt>
  375. * @param {SignalingLayer} signaling The signaling layer that will
  376. * provide information about the media or participants which is not
  377. * carried over SDP.
  378. * @param {object} iceConfig An object describing the ICE config like
  379. * defined in the WebRTC specification.
  380. * @param {boolean} isP2P Indicates whether or not the new TPC will be used
  381. * in a peer to peer type of session.
  382. * @param {object} options The config options.
  383. * @param {boolean} options.enableInsertableStreams - Set to true when the insertable streams constraints is to be
  384. * enabled on the PeerConnection.
  385. * @param {boolean} options.disableSimulcast If set to 'true' will disable
  386. * the simulcast.
  387. * @param {boolean} options.disableRtx If set to 'true' will disable the
  388. * RTX.
  389. * @param {boolean} options.disableH264 If set to 'true' H264 will be
  390. * disabled by removing it from the SDP.
  391. * @param {boolean} options.preferH264 If set to 'true' H264 will be
  392. * preferred over other video codecs.
  393. * @param {boolean} options.startSilent If set to 'true' no audio will be sent or received.
  394. * @return {TraceablePeerConnection}
  395. */
  396. createPeerConnection(signaling, iceConfig, isP2P, options) {
  397. const pcConstraints = JSON.parse(JSON.stringify(RTCUtils.pcConstraints));
  398. if (typeof options.abtestSuspendVideo !== 'undefined') {
  399. RTCUtils.setSuspendVideo(pcConstraints, options.abtestSuspendVideo);
  400. Statistics.analytics.addPermanentProperties(
  401. { abtestSuspendVideo: options.abtestSuspendVideo });
  402. }
  403. // FIXME: We should rename iceConfig to pcConfig.
  404. if (options.enableInsertableStreams) {
  405. logger.debug('E2EE - setting insertable streams constraints');
  406. iceConfig.encodedInsertableStreams = true;
  407. iceConfig.forceEncodedAudioInsertableStreams = true; // legacy, to be removed in M88.
  408. iceConfig.forceEncodedVideoInsertableStreams = true; // legacy, to be removed in M88.
  409. }
  410. const supportsSdpSemantics = browser.isReactNative()
  411. || (browser.isChromiumBased() && !options.usesUnifiedPlan);
  412. if (supportsSdpSemantics) {
  413. iceConfig.sdpSemantics = 'plan-b';
  414. }
  415. if (options.forceTurnRelay) {
  416. iceConfig.iceTransportPolicy = 'relay';
  417. }
  418. // Set the RTCBundlePolicy to max-bundle so that only one set of ice candidates is generated.
  419. // The default policy generates separate ice candidates for audio and video connections.
  420. // This change is necessary for Unified plan to work properly on Chrome and Safari.
  421. iceConfig.bundlePolicy = 'max-bundle';
  422. peerConnectionIdCounter = safeCounterIncrement(peerConnectionIdCounter);
  423. const newConnection
  424. = new TraceablePeerConnection(
  425. this,
  426. peerConnectionIdCounter,
  427. signaling,
  428. iceConfig, pcConstraints,
  429. isP2P, options);
  430. this.peerConnections.set(newConnection.id, newConnection);
  431. return newConnection;
  432. }
  433. /* eslint-enable max-params */
  434. /**
  435. * Removed given peer connection from this RTC module instance.
  436. * @param {TraceablePeerConnection} traceablePeerConnection
  437. * @return {boolean} <tt>true</tt> if the given peer connection was removed
  438. * successfully or <tt>false</tt> if there was no peer connection mapped in
  439. * this RTC instance.
  440. */
  441. _removePeerConnection(traceablePeerConnection) {
  442. const id = traceablePeerConnection.id;
  443. if (this.peerConnections.has(id)) {
  444. // NOTE Remote tracks are not removed here.
  445. this.peerConnections.delete(id);
  446. return true;
  447. }
  448. return false;
  449. }
  450. /**
  451. *
  452. * @param track
  453. */
  454. addLocalTrack(track) {
  455. if (!track) {
  456. throw new Error('track must not be null nor undefined');
  457. }
  458. this.localTracks.push(track);
  459. track.conference = this.conference;
  460. }
  461. /**
  462. * Get local video track.
  463. * @returns {JitsiLocalTrack|undefined}
  464. */
  465. getLocalVideoTrack() {
  466. const localVideo = this.getLocalTracks(MediaType.VIDEO);
  467. return localVideo.length ? localVideo[0] : undefined;
  468. }
  469. /**
  470. * Get local audio track.
  471. * @returns {JitsiLocalTrack|undefined}
  472. */
  473. getLocalAudioTrack() {
  474. const localAudio = this.getLocalTracks(MediaType.AUDIO);
  475. return localAudio.length ? localAudio[0] : undefined;
  476. }
  477. /**
  478. * Returns the endpoint id for the local user.
  479. * @returns {string}
  480. */
  481. getLocalEndpointId() {
  482. return this.conference.myUserId();
  483. }
  484. /**
  485. * Returns the local tracks of the given media type, or all local tracks if
  486. * no specific type is given.
  487. * @param {MediaType} [mediaType] Optional media type filter.
  488. * (audio or video).
  489. */
  490. getLocalTracks(mediaType) {
  491. let tracks = this.localTracks.slice();
  492. if (mediaType !== undefined) {
  493. tracks = tracks.filter(
  494. track => track.getType() === mediaType);
  495. }
  496. return tracks;
  497. }
  498. /**
  499. * Obtains all remote tracks currently known to this RTC module instance.
  500. * @param {MediaType} [mediaType] The remote tracks will be filtered
  501. * by their media type if this argument is specified.
  502. * @return {Array<JitsiRemoteTrack>}
  503. */
  504. getRemoteTracks(mediaType) {
  505. let remoteTracks = [];
  506. for (const tpc of this.peerConnections.values()) {
  507. const pcRemoteTracks = tpc.getRemoteTracks(undefined, mediaType);
  508. if (pcRemoteTracks) {
  509. remoteTracks = remoteTracks.concat(pcRemoteTracks);
  510. }
  511. }
  512. return remoteTracks;
  513. }
  514. /**
  515. * Set mute for all local audio streams attached to the conference.
  516. * @param value The mute value.
  517. * @returns {Promise}
  518. */
  519. setAudioMute(value) {
  520. const mutePromises = [];
  521. this.getLocalTracks(MediaType.AUDIO).forEach(audioTrack => {
  522. // this is a Promise
  523. mutePromises.push(value ? audioTrack.mute() : audioTrack.unmute());
  524. });
  525. // We return a Promise from all Promises so we can wait for their
  526. // execution.
  527. return Promise.all(mutePromises);
  528. }
  529. /**
  530. * Set mute for all local video streams attached to the conference.
  531. * @param value The mute value.
  532. * @returns {Promise}
  533. */
  534. setVideoMute(value) {
  535. const mutePromises = [];
  536. this.getLocalTracks(MediaType.VIDEO).concat(this.getLocalTracks(MediaType.PRESENTER))
  537. .forEach(videoTrack => {
  538. // this is a Promise
  539. mutePromises.push(value ? videoTrack.mute() : videoTrack.unmute());
  540. });
  541. // We return a Promise from all Promises so we can wait for their
  542. // execution.
  543. return Promise.all(mutePromises);
  544. }
  545. /**
  546. *
  547. * @param track
  548. */
  549. removeLocalTrack(track) {
  550. const pos = this.localTracks.indexOf(track);
  551. if (pos === -1) {
  552. return;
  553. }
  554. this.localTracks.splice(pos, 1);
  555. }
  556. /**
  557. *
  558. * @param elSelector
  559. * @param stream
  560. */
  561. static attachMediaStream(elSelector, stream) {
  562. return RTCUtils.attachMediaStream(elSelector, stream);
  563. }
  564. /**
  565. * Returns the id of the given stream.
  566. * @param {MediaStream} stream
  567. */
  568. static getStreamID(stream) {
  569. return RTCUtils.getStreamID(stream);
  570. }
  571. /**
  572. * Returns the id of the given track.
  573. * @param {MediaStreamTrack} track
  574. */
  575. static getTrackID(track) {
  576. return RTCUtils.getTrackID(track);
  577. }
  578. /**
  579. * Returns true if retrieving the list of input devices is supported
  580. * and false if not.
  581. */
  582. static isDeviceListAvailable() {
  583. return RTCUtils.isDeviceListAvailable();
  584. }
  585. /**
  586. * Returns true if changing the input (camera / microphone) or output
  587. * (audio) device is supported and false if not.
  588. * @param {string} [deviceType] Type of device to change. Default is
  589. * undefined or 'input', 'output' - for audio output device change.
  590. * @returns {boolean} true if available, false otherwise.
  591. */
  592. static isDeviceChangeAvailable(deviceType) {
  593. return RTCUtils.isDeviceChangeAvailable(deviceType);
  594. }
  595. /**
  596. * Returns whether the current execution environment supports WebRTC (for
  597. * use within this library).
  598. *
  599. * @returns {boolean} {@code true} if WebRTC is supported in the current
  600. * execution environment (for use within this library); {@code false},
  601. * otherwise.
  602. */
  603. static isWebRtcSupported() {
  604. return browser.isSupported();
  605. }
  606. /**
  607. * Returns currently used audio output device id, '' stands for default
  608. * device
  609. * @returns {string}
  610. */
  611. static getAudioOutputDevice() {
  612. return RTCUtils.getAudioOutputDevice();
  613. }
  614. /**
  615. * Returns list of available media devices if its obtained, otherwise an
  616. * empty array is returned/
  617. * @returns {array} list of available media devices.
  618. */
  619. static getCurrentlyAvailableMediaDevices() {
  620. return RTCUtils.getCurrentlyAvailableMediaDevices();
  621. }
  622. /**
  623. * Returns whether available devices have permissions granted
  624. * @returns {Boolean}
  625. */
  626. static arePermissionsGrantedForAvailableDevices() {
  627. return RTCUtils.arePermissionsGrantedForAvailableDevices();
  628. }
  629. /**
  630. * Returns event data for device to be reported to stats.
  631. * @returns {MediaDeviceInfo} device.
  632. */
  633. static getEventDataForActiveDevice(device) {
  634. return RTCUtils.getEventDataForActiveDevice(device);
  635. }
  636. /**
  637. * Sets current audio output device.
  638. * @param {string} deviceId Id of 'audiooutput' device from
  639. * navigator.mediaDevices.enumerateDevices().
  640. * @returns {Promise} resolves when audio output is changed, is rejected
  641. * otherwise
  642. */
  643. static setAudioOutputDevice(deviceId) {
  644. return RTCUtils.setAudioOutputDevice(deviceId);
  645. }
  646. /**
  647. * Returns <tt>true<tt/> if given WebRTC MediaStream is considered a valid
  648. * "user" stream which means that it's not a "receive only" stream nor a
  649. * "mixed" JVB stream.
  650. *
  651. * Clients that implement Unified Plan, such as Firefox use recvonly
  652. * "streams/channels/tracks" for receiving remote stream/tracks, as opposed
  653. * to Plan B where there are only 3 channels: audio, video and data.
  654. *
  655. * @param {MediaStream} stream The WebRTC MediaStream instance.
  656. * @returns {boolean}
  657. */
  658. static isUserStream(stream) {
  659. return RTC.isUserStreamById(RTCUtils.getStreamID(stream));
  660. }
  661. /**
  662. * Returns <tt>true<tt/> if a WebRTC MediaStream identified by given stream
  663. * ID is considered a valid "user" stream which means that it's not a
  664. * "receive only" stream nor a "mixed" JVB stream.
  665. *
  666. * Clients that implement Unified Plan, such as Firefox use recvonly
  667. * "streams/channels/tracks" for receiving remote stream/tracks, as opposed
  668. * to Plan B where there are only 3 channels: audio, video and data.
  669. *
  670. * @param {string} streamId The id of WebRTC MediaStream.
  671. * @returns {boolean}
  672. */
  673. static isUserStreamById(streamId) {
  674. return streamId && streamId !== 'mixedmslabel'
  675. && streamId !== 'default';
  676. }
  677. /**
  678. * Allows to receive list of available cameras/microphones.
  679. * @param {function} callback Would receive array of devices as an
  680. * argument.
  681. */
  682. static enumerateDevices(callback) {
  683. RTCUtils.enumerateDevices(callback);
  684. }
  685. /**
  686. * A method to handle stopping of the stream.
  687. * One point to handle the differences in various implementations.
  688. * @param {MediaStream} mediaStream MediaStream object to stop.
  689. */
  690. static stopMediaStream(mediaStream) {
  691. RTCUtils.stopMediaStream(mediaStream);
  692. }
  693. /**
  694. * Returns whether the desktop sharing is enabled or not.
  695. * @returns {boolean}
  696. */
  697. static isDesktopSharingEnabled() {
  698. return RTCUtils.isDesktopSharingEnabled();
  699. }
  700. /**
  701. * Closes the currently opened bridge channel.
  702. */
  703. closeBridgeChannel() {
  704. if (this._channel) {
  705. this._channel.close();
  706. this._channel = null;
  707. this.removeListener(RTCEvents.LASTN_ENDPOINT_CHANGED, this._lastNChangeListener);
  708. }
  709. }
  710. /* eslint-disable max-params */
  711. /**
  712. *
  713. * @param {TraceablePeerConnection} tpc
  714. * @param {number} ssrc
  715. * @param {number} audioLevel
  716. * @param {boolean} isLocal
  717. */
  718. setAudioLevel(tpc, ssrc, audioLevel, isLocal) {
  719. const track = tpc.getTrackBySSRC(ssrc);
  720. if (!track) {
  721. return;
  722. } else if (!track.isAudioTrack()) {
  723. logger.warn(`Received audio level for non-audio track: ${ssrc}`);
  724. return;
  725. } else if (track.isLocal() !== isLocal) {
  726. logger.error(
  727. `${track} was expected to ${isLocal ? 'be' : 'not be'} local`);
  728. }
  729. track.setAudioLevel(audioLevel, tpc);
  730. }
  731. /**
  732. * Sends message via the bridge channel.
  733. * @param {string} to The id of the endpoint that should receive the
  734. * message. If "" the message will be sent to all participants.
  735. * @param {object} payload The payload of the message.
  736. * @throws NetworkError or InvalidStateError or Error if the operation
  737. * fails or there is no data channel created.
  738. */
  739. sendChannelMessage(to, payload) {
  740. if (this._channel) {
  741. this._channel.sendMessage(to, payload);
  742. } else {
  743. throw new Error('Channel support is disabled!');
  744. }
  745. }
  746. /**
  747. * Sends the local stats via the bridge channel.
  748. * @param {Object} payload The payload of the message.
  749. * @throws NetworkError/InvalidStateError/Error if the operation fails or if there is no data channel created.
  750. */
  751. sendEndpointStatsMessage(payload) {
  752. if (this._channel && this._channel.isOpen()) {
  753. this._channel.sendEndpointStatsMessage(payload);
  754. }
  755. }
  756. /**
  757. * Selects a new value for "lastN". The requested amount of videos are going
  758. * to be delivered after the value is in effect. Set to -1 for unlimited or
  759. * all available videos.
  760. * @param {number} value the new value for lastN.
  761. */
  762. setLastN(value) {
  763. if (this._lastN !== value) {
  764. this._lastN = value;
  765. if (this._channel && this._channel.isOpen()) {
  766. this._channel.sendSetLastNMessage(value);
  767. }
  768. this.eventEmitter.emit(RTCEvents.LASTN_VALUE_CHANGED, value);
  769. }
  770. }
  771. /**
  772. * Indicates if the endpoint id is currently included in the last N.
  773. * @param {string} id The endpoint id that we check for last N.
  774. * @returns {boolean} true if the endpoint id is in the last N or if we
  775. * don't have bridge channel support, otherwise we return false.
  776. */
  777. isInLastN(id) {
  778. return !this._lastNEndpoints // lastNEndpoints not initialised yet.
  779. || this._lastNEndpoints.indexOf(id) > -1;
  780. }
  781. /**
  782. * Updates the target audio output device for all remote audio tracks.
  783. *
  784. * @param {string} deviceId - The device id of the audio ouput device to
  785. * use for all remote tracks.
  786. * @private
  787. * @returns {void}
  788. */
  789. _updateAudioOutputForAudioTracks(deviceId) {
  790. const remoteAudioTracks = this.getRemoteTracks(MediaType.AUDIO);
  791. for (const track of remoteAudioTracks) {
  792. track.setAudioOutput(deviceId);
  793. }
  794. }
  795. }