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

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