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.

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