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

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