您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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