modified lib-jitsi-meet dev repo
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

RTC.js 28KB

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