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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945
  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 FeatureFlags from '../flags/FeatureFlags';
  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. /**
  132. * The default video type assumed by the bridge.
  133. * @deprecated this will go away with multiple streams support
  134. * @type {BridgeVideoType}
  135. * @private
  136. */
  137. this._videoType = BridgeVideoType.NONE;
  138. // Switch audio output device on all remote audio tracks. Local audio
  139. // tracks handle this event by themselves.
  140. if (RTCUtils.isDeviceChangeAvailable('output')) {
  141. RTCUtils.addListener(
  142. RTCEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  143. this._updateAudioOutputForAudioTracks
  144. );
  145. RTCUtils.addListener(
  146. RTCEvents.DEVICE_LIST_CHANGED,
  147. this._onDeviceListChanged
  148. );
  149. }
  150. }
  151. /**
  152. * Removes any listeners and stored state from this {@code RTC} instance.
  153. *
  154. * @returns {void}
  155. */
  156. destroy() {
  157. RTCUtils.removeListener(RTCEvents.AUDIO_OUTPUT_DEVICE_CHANGED, this._updateAudioOutputForAudioTracks);
  158. RTCUtils.removeListener(RTCEvents.DEVICE_LIST_CHANGED, this._onDeviceListChanged);
  159. if (this._channelOpenListener) {
  160. this.removeListener(
  161. RTCEvents.DATA_CHANNEL_OPEN,
  162. this._channelOpenListener
  163. );
  164. }
  165. }
  166. /**
  167. * Exposes the private helper for converting a WebRTC MediaStream to a
  168. * JitsiLocalTrack.
  169. *
  170. * @param {Array<Object>} tracksInfo
  171. * @returns {Array<JitsiLocalTrack>}
  172. */
  173. static createLocalTracks(tracksInfo) {
  174. return _createLocalTracks(tracksInfo);
  175. }
  176. /**
  177. * Creates the local MediaStreams.
  178. * @param {object} [options] Optional parameters.
  179. * @param {array} options.devices The devices that will be requested.
  180. * @param {string} options.resolution Resolution constraints.
  181. * @param {string} options.cameraDeviceId
  182. * @param {string} options.micDeviceId
  183. * @returns {*} Promise object that will receive the new JitsiTracks
  184. */
  185. static obtainAudioAndVideoPermissions(options) {
  186. return RTCUtils.obtainAudioAndVideoPermissions(options)
  187. .then(tracksInfo => _createLocalTracks(tracksInfo));
  188. }
  189. /**
  190. * Initializes the bridge channel of this instance.
  191. * At least one of both, peerconnection or wsUrl parameters, must be
  192. * given.
  193. * @param {RTCPeerConnection} [peerconnection] WebRTC peer connection
  194. * instance.
  195. * @param {string} [wsUrl] WebSocket URL.
  196. */
  197. initializeBridgeChannel(peerconnection, wsUrl) {
  198. this._channel = new BridgeChannel(peerconnection, wsUrl, this.eventEmitter);
  199. this._channelOpenListener = () => {
  200. const logError = (error, msgType, value) => {
  201. GlobalOnErrorHandler.callErrorHandler(error);
  202. logger.error(`Cannot send ${msgType}(${JSON.stringify(value)}) endpoint message`, error);
  203. };
  204. // When the channel becomes available, tell the bridge about video selections so that it can do adaptive
  205. // simulcast, we want the notification to trigger even if userJid is undefined, or null.
  206. if (this._receiverVideoConstraints) {
  207. try {
  208. this._channel.sendNewReceiverVideoConstraintsMessage(this._receiverVideoConstraints);
  209. } catch (error) {
  210. logError(error, 'ReceiverVideoConstraints', this._receiverVideoConstraints);
  211. }
  212. }
  213. if (this._selectedEndpoints) {
  214. try {
  215. this._channel.sendSelectedEndpointsMessage(this._selectedEndpoints);
  216. } catch (error) {
  217. logError(error, 'SelectedEndpointsChangedEvent', this._selectedEndpoints);
  218. }
  219. }
  220. if (typeof this._maxFrameHeight !== 'undefined') {
  221. try {
  222. this._channel.sendReceiverVideoConstraintMessage(this._maxFrameHeight);
  223. } catch (error) {
  224. logError(error, 'ReceiverVideoConstraint', this._maxFrameHeight);
  225. }
  226. }
  227. if (typeof this._lastN !== 'undefined' && this._lastN !== -1) {
  228. try {
  229. this._channel.sendSetLastNMessage(this._lastN);
  230. } catch (error) {
  231. logError(error, 'LastNChangedEvent', this._lastN);
  232. }
  233. }
  234. if (!FeatureFlags.isSourceNameSignalingEnabled()) {
  235. try {
  236. this._channel.sendVideoTypeMessage(this._videoType);
  237. } catch (error) {
  238. logError(error, 'VideoTypeMessage', this._videoType);
  239. }
  240. }
  241. this.removeListener(RTCEvents.DATA_CHANNEL_OPEN, this._channelOpenListener);
  242. this._channelOpenListener = null;
  243. };
  244. this.addListener(RTCEvents.DATA_CHANNEL_OPEN, this._channelOpenListener);
  245. // Add Last N change listener.
  246. this.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED, this._lastNChangeListener);
  247. }
  248. /**
  249. * Callback invoked when the list of known audio and video devices has
  250. * been updated. Attempts to update the known available audio output
  251. * devices.
  252. *
  253. * @private
  254. * @returns {void}
  255. */
  256. _onDeviceListChanged() {
  257. this._updateAudioOutputForAudioTracks(RTCUtils.getAudioOutputDevice());
  258. }
  259. /**
  260. * Receives events when Last N had changed.
  261. * @param {array} lastNEndpoints The new Last N endpoints.
  262. * @private
  263. */
  264. _onLastNChanged(lastNEndpoints = []) {
  265. const oldLastNEndpoints = this._lastNEndpoints || [];
  266. let leavingLastNEndpoints = [];
  267. let enteringLastNEndpoints = [];
  268. this._lastNEndpoints = lastNEndpoints;
  269. leavingLastNEndpoints = oldLastNEndpoints.filter(
  270. id => !this.isInLastN(id));
  271. enteringLastNEndpoints = lastNEndpoints.filter(
  272. id => oldLastNEndpoints.indexOf(id) === -1);
  273. this.conference.eventEmitter.emit(
  274. JitsiConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  275. leavingLastNEndpoints,
  276. enteringLastNEndpoints);
  277. }
  278. /**
  279. * Should be called when current media session ends and after the
  280. * PeerConnection has been closed using PeerConnection.close() method.
  281. */
  282. onCallEnded() {
  283. if (this._channel) {
  284. // The BridgeChannel is not explicitly closed as the PeerConnection
  285. // is closed on call ended which triggers datachannel onclose
  286. // events. If using a WebSocket, the channel must be closed since
  287. // it is not managed by the PeerConnection.
  288. // The reference is cleared to disable any logic related to the
  289. // channel.
  290. if (this._channel && this._channel.mode === 'websocket') {
  291. this._channel.close();
  292. }
  293. this._channel = null;
  294. }
  295. }
  296. /**
  297. * Sets the capture frame rate to be used for desktop tracks.
  298. *
  299. * @param {number} maxFps framerate to be used for desktop track capture.
  300. */
  301. setDesktopSharingFrameRate(maxFps) {
  302. RTCUtils.setDesktopSharingFrameRate(maxFps);
  303. }
  304. /**
  305. * Sets the receiver video constraints that determine how bitrate is allocated to each of the video streams
  306. * requested from the bridge. The constraints are cached and sent through the bridge channel once the channel
  307. * is established.
  308. * @param {*} constraints
  309. */
  310. setNewReceiverVideoConstraints(constraints) {
  311. this._receiverVideoConstraints = constraints;
  312. if (this._channel && this._channel.isOpen()) {
  313. this._channel.sendNewReceiverVideoConstraintsMessage(constraints);
  314. }
  315. }
  316. /**
  317. * Sets the maximum video size the local participant should receive from
  318. * remote participants. Will cache the value and send it through the channel
  319. * once it is created.
  320. *
  321. * @param {number} maxFrameHeightPixels the maximum frame height, in pixels,
  322. * this receiver is willing to receive.
  323. * @returns {void}
  324. */
  325. setReceiverVideoConstraint(maxFrameHeight) {
  326. this._maxFrameHeight = maxFrameHeight;
  327. if (this._channel && this._channel.isOpen()) {
  328. this._channel.sendReceiverVideoConstraintMessage(maxFrameHeight);
  329. }
  330. }
  331. /**
  332. * Sets the video type and availability for the local video source.
  333. *
  334. * @param {string} videoType 'camera' for camera, 'desktop' for screenshare and
  335. * 'none' for when local video source is muted or removed from the peerconnection.
  336. * @returns {void}
  337. */
  338. setVideoType(videoType) {
  339. if (this._videoType !== videoType) {
  340. this._videoType = videoType;
  341. if (this._channel && this._channel.isOpen()) {
  342. this._channel.sendVideoTypeMessage(videoType);
  343. }
  344. }
  345. }
  346. /**
  347. * Sends the track's video type to the JVB.
  348. * @param {SourceName} sourceName - the track's source name.
  349. * @param {BridgeVideoType} videoType - the track's video type.
  350. */
  351. sendSourceVideoType(sourceName, videoType) {
  352. if (this._channel && this._channel.isOpen()) {
  353. this._channel.sendSourceVideoTypeMessage(sourceName, videoType);
  354. }
  355. }
  356. /**
  357. * Elects the participants with the given ids to be the selected
  358. * participants in order to always receive video for this participant (even
  359. * when last n is enabled). If there is no channel we store it and send it
  360. * through the channel once it is created.
  361. *
  362. * @param {Array<string>} ids - The user ids.
  363. * @throws NetworkError or InvalidStateError or Error if the operation
  364. * fails.
  365. * @returns {void}
  366. */
  367. selectEndpoints(ids) {
  368. this._selectedEndpoints = ids;
  369. if (this._channel && this._channel.isOpen()) {
  370. this._channel.sendSelectedEndpointsMessage(ids);
  371. }
  372. }
  373. /**
  374. *
  375. * @param eventType
  376. * @param listener
  377. */
  378. static addListener(eventType, listener) {
  379. RTCUtils.addListener(eventType, listener);
  380. }
  381. /**
  382. *
  383. * @param eventType
  384. * @param listener
  385. */
  386. static removeListener(eventType, listener) {
  387. RTCUtils.removeListener(eventType, listener);
  388. }
  389. /**
  390. *
  391. * @param options
  392. */
  393. static init(options = {}) {
  394. this.options = options;
  395. return RTCUtils.init(this.options);
  396. }
  397. /* eslint-disable max-params */
  398. /**
  399. * Creates new <tt>TraceablePeerConnection</tt>
  400. * @param {SignalingLayer} signaling The signaling layer that will provide information about the media or
  401. * participants which is not carried over SDP.
  402. * @param {object} pcConfig The {@code RTCConfiguration} to use for the WebRTC peer connection.
  403. * @param {boolean} isP2P Indicates whether or not the new TPC will be used in a peer to peer type of session.
  404. * @param {object} options The config options.
  405. * @param {boolean} options.enableInsertableStreams - Set to true when the insertable streams constraints is to be
  406. * enabled on the PeerConnection.
  407. * @param {boolean} options.disableSimulcast If set to 'true' will disable the simulcast.
  408. * @param {boolean} options.disableRtx If set to 'true' will disable the RTX.
  409. * @param {boolean} options.startSilent If set to 'true' no audio will be sent or received.
  410. * @return {TraceablePeerConnection}
  411. */
  412. createPeerConnection(signaling, pcConfig, isP2P, options) {
  413. const pcConstraints = JSON.parse(JSON.stringify(RTCUtils.pcConstraints));
  414. if (typeof options.abtestSuspendVideo !== 'undefined') {
  415. RTCUtils.setSuspendVideo(pcConstraints, options.abtestSuspendVideo);
  416. Statistics.analytics.addPermanentProperties(
  417. { abtestSuspendVideo: options.abtestSuspendVideo });
  418. }
  419. if (options.enableInsertableStreams) {
  420. logger.debug('E2EE - setting insertable streams constraints');
  421. pcConfig.encodedInsertableStreams = true;
  422. }
  423. const supportsSdpSemantics = browser.isReactNative()
  424. || (browser.isChromiumBased() && !options.usesUnifiedPlan);
  425. if (supportsSdpSemantics) {
  426. logger.debug('WebRTC application is running in plan-b mode');
  427. pcConfig.sdpSemantics = 'plan-b';
  428. }
  429. if (options.forceTurnRelay) {
  430. pcConfig.iceTransportPolicy = 'relay';
  431. }
  432. // Set the RTCBundlePolicy to max-bundle so that only one set of ice candidates is generated.
  433. // The default policy generates separate ice candidates for audio and video connections.
  434. // This change is necessary for Unified plan to work properly on Chrome and Safari.
  435. pcConfig.bundlePolicy = 'max-bundle';
  436. peerConnectionIdCounter = safeCounterIncrement(peerConnectionIdCounter);
  437. const newConnection
  438. = new TraceablePeerConnection(
  439. this,
  440. peerConnectionIdCounter,
  441. signaling,
  442. pcConfig, pcConstraints,
  443. isP2P, options);
  444. this.peerConnections.set(newConnection.id, newConnection);
  445. return newConnection;
  446. }
  447. /* eslint-enable max-params */
  448. /**
  449. * Removed given peer connection from this RTC module instance.
  450. * @param {TraceablePeerConnection} traceablePeerConnection
  451. * @return {boolean} <tt>true</tt> if the given peer connection was removed
  452. * successfully or <tt>false</tt> if there was no peer connection mapped in
  453. * this RTC instance.
  454. */
  455. _removePeerConnection(traceablePeerConnection) {
  456. const id = traceablePeerConnection.id;
  457. if (this.peerConnections.has(id)) {
  458. // NOTE Remote tracks are not removed here.
  459. this.peerConnections.delete(id);
  460. return true;
  461. }
  462. return false;
  463. }
  464. /**
  465. *
  466. * @param track
  467. */
  468. addLocalTrack(track) {
  469. if (!track) {
  470. throw new Error('track must not be null nor undefined');
  471. }
  472. this.localTracks.push(track);
  473. track.conference = this.conference;
  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).concat(this.getLocalTracks(MediaType.PRESENTER))
  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 the id of the given stream.
  587. * @param {MediaStream} stream
  588. */
  589. static getStreamID(stream) {
  590. return RTCUtils.getStreamID(stream);
  591. }
  592. /**
  593. * Returns the id of the given track.
  594. * @param {MediaStreamTrack} track
  595. */
  596. static getTrackID(track) {
  597. return RTCUtils.getTrackID(track);
  598. }
  599. /**
  600. * Returns true if retrieving the list of input devices is supported
  601. * and false if not.
  602. */
  603. static isDeviceListAvailable() {
  604. return RTCUtils.isDeviceListAvailable();
  605. }
  606. /**
  607. * Returns true if changing the input (camera / microphone) or output
  608. * (audio) device is supported and false if not.
  609. * @param {string} [deviceType] Type of device to change. Default is
  610. * undefined or 'input', 'output' - for audio output device change.
  611. * @returns {boolean} true if available, false otherwise.
  612. */
  613. static isDeviceChangeAvailable(deviceType) {
  614. return RTCUtils.isDeviceChangeAvailable(deviceType);
  615. }
  616. /**
  617. * Returns whether the current execution environment supports WebRTC (for
  618. * use within this library).
  619. *
  620. * @returns {boolean} {@code true} if WebRTC is supported in the current
  621. * execution environment (for use within this library); {@code false},
  622. * otherwise.
  623. */
  624. static isWebRtcSupported() {
  625. return browser.isSupported();
  626. }
  627. /**
  628. * Returns currently used audio output device id, '' stands for default
  629. * device
  630. * @returns {string}
  631. */
  632. static getAudioOutputDevice() {
  633. return RTCUtils.getAudioOutputDevice();
  634. }
  635. /**
  636. * Returns list of available media devices if its obtained, otherwise an
  637. * empty array is returned/
  638. * @returns {array} list of available media devices.
  639. */
  640. static getCurrentlyAvailableMediaDevices() {
  641. return RTCUtils.getCurrentlyAvailableMediaDevices();
  642. }
  643. /**
  644. * Returns whether available devices have permissions granted
  645. * @returns {Boolean}
  646. */
  647. static arePermissionsGrantedForAvailableDevices() {
  648. return RTCUtils.arePermissionsGrantedForAvailableDevices();
  649. }
  650. /**
  651. * Returns event data for device to be reported to stats.
  652. * @returns {MediaDeviceInfo} device.
  653. */
  654. static getEventDataForActiveDevice(device) {
  655. return RTCUtils.getEventDataForActiveDevice(device);
  656. }
  657. /**
  658. * Sets current audio output device.
  659. * @param {string} deviceId Id of 'audiooutput' device from
  660. * navigator.mediaDevices.enumerateDevices().
  661. * @returns {Promise} resolves when audio output is changed, is rejected
  662. * otherwise
  663. */
  664. static setAudioOutputDevice(deviceId) {
  665. return RTCUtils.setAudioOutputDevice(deviceId);
  666. }
  667. /**
  668. * Returns <tt>true<tt/> if given WebRTC MediaStream is considered a valid
  669. * "user" stream which means that it's not a "receive only" stream nor a
  670. * "mixed" JVB stream.
  671. *
  672. * Clients that implement Unified Plan, such as Firefox use recvonly
  673. * "streams/channels/tracks" for receiving remote stream/tracks, as opposed
  674. * to Plan B where there are only 3 channels: audio, video and data.
  675. *
  676. * @param {MediaStream} stream The WebRTC MediaStream instance.
  677. * @returns {boolean}
  678. */
  679. static isUserStream(stream) {
  680. return RTC.isUserStreamById(RTCUtils.getStreamID(stream));
  681. }
  682. /**
  683. * Returns <tt>true<tt/> if a WebRTC MediaStream identified by given stream
  684. * ID is considered a valid "user" stream which means that it's not a
  685. * "receive only" stream nor a "mixed" JVB stream.
  686. *
  687. * Clients that implement Unified Plan, such as Firefox use recvonly
  688. * "streams/channels/tracks" for receiving remote stream/tracks, as opposed
  689. * to Plan B where there are only 3 channels: audio, video and data.
  690. *
  691. * @param {string} streamId The id of WebRTC MediaStream.
  692. * @returns {boolean}
  693. */
  694. static isUserStreamById(streamId) {
  695. return streamId && streamId !== 'mixedmslabel'
  696. && streamId !== 'default';
  697. }
  698. /**
  699. * Allows to receive list of available cameras/microphones.
  700. * @param {function} callback Would receive array of devices as an
  701. * argument.
  702. */
  703. static enumerateDevices(callback) {
  704. RTCUtils.enumerateDevices(callback);
  705. }
  706. /**
  707. * A method to handle stopping of the stream.
  708. * One point to handle the differences in various implementations.
  709. * @param {MediaStream} mediaStream MediaStream object to stop.
  710. */
  711. static stopMediaStream(mediaStream) {
  712. RTCUtils.stopMediaStream(mediaStream);
  713. }
  714. /**
  715. * Returns whether the desktop sharing is enabled or not.
  716. * @returns {boolean}
  717. */
  718. static isDesktopSharingEnabled() {
  719. return RTCUtils.isDesktopSharingEnabled();
  720. }
  721. /**
  722. * Closes the currently opened bridge channel.
  723. */
  724. closeBridgeChannel() {
  725. if (this._channel) {
  726. this._channel.close();
  727. this._channel = null;
  728. this.removeListener(RTCEvents.LASTN_ENDPOINT_CHANGED, this._lastNChangeListener);
  729. }
  730. }
  731. /* eslint-disable max-params */
  732. /**
  733. *
  734. * @param {TraceablePeerConnection} tpc
  735. * @param {number} ssrc
  736. * @param {number} audioLevel
  737. * @param {boolean} isLocal
  738. */
  739. setAudioLevel(tpc, ssrc, audioLevel, isLocal) {
  740. const track = tpc.getTrackBySSRC(ssrc);
  741. if (!track) {
  742. return;
  743. } else if (!track.isAudioTrack()) {
  744. logger.warn(`Received audio level for non-audio track: ${ssrc}`);
  745. return;
  746. } else if (track.isLocal() !== isLocal) {
  747. logger.error(
  748. `${track} was expected to ${isLocal ? 'be' : 'not be'} local`);
  749. }
  750. track.setAudioLevel(audioLevel, tpc);
  751. }
  752. /**
  753. * Sends message via the bridge channel.
  754. * @param {string} to The id of the endpoint that should receive the
  755. * message. If "" the message will be sent to all participants.
  756. * @param {object} payload The payload of the message.
  757. * @throws NetworkError or InvalidStateError or Error if the operation
  758. * fails or there is no data channel created.
  759. */
  760. sendChannelMessage(to, payload) {
  761. if (this._channel) {
  762. this._channel.sendMessage(to, payload);
  763. } else {
  764. throw new Error('Channel support is disabled!');
  765. }
  766. }
  767. /**
  768. * Sends the local stats via the bridge channel.
  769. * @param {Object} payload The payload of the message.
  770. * @throws NetworkError/InvalidStateError/Error if the operation fails or if there is no data channel created.
  771. */
  772. sendEndpointStatsMessage(payload) {
  773. if (this._channel && this._channel.isOpen()) {
  774. this._channel.sendEndpointStatsMessage(payload);
  775. }
  776. }
  777. /**
  778. * Selects a new value for "lastN". The requested amount of videos are going
  779. * to be delivered after the value is in effect. Set to -1 for unlimited or
  780. * all available videos.
  781. * @param {number} value the new value for lastN.
  782. */
  783. setLastN(value) {
  784. if (this._lastN !== value) {
  785. this._lastN = value;
  786. if (this._channel && this._channel.isOpen()) {
  787. this._channel.sendSetLastNMessage(value);
  788. }
  789. this.eventEmitter.emit(RTCEvents.LASTN_VALUE_CHANGED, value);
  790. }
  791. }
  792. /**
  793. * Indicates if the endpoint id is currently included in the last N.
  794. * @param {string} id The endpoint id that we check for last N.
  795. * @returns {boolean} true if the endpoint id is in the last N or if we
  796. * don't have bridge channel support, otherwise we return false.
  797. */
  798. isInLastN(id) {
  799. return !this._lastNEndpoints // lastNEndpoints not initialised yet.
  800. || this._lastNEndpoints.indexOf(id) > -1;
  801. }
  802. /**
  803. * Updates the target audio output device for all remote audio tracks.
  804. *
  805. * @param {string} deviceId - The device id of the audio ouput device to
  806. * use for all remote tracks.
  807. * @private
  808. * @returns {void}
  809. */
  810. _updateAudioOutputForAudioTracks(deviceId) {
  811. const remoteAudioTracks = this.getRemoteTracks(MediaType.AUDIO);
  812. for (const track of remoteAudioTracks) {
  813. track.setAudioOutput(deviceId);
  814. }
  815. }
  816. }