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

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