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

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