modified lib-jitsi-meet dev repo
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

RTC.js 29KB

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