modified lib-jitsi-meet dev repo
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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