Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

RTC.js 27KB

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