Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

RTC.js 27KB

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