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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881
  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 endpoint ID of currently pinned participant or <tt>null</tt> if
  144. * no user is pinned.
  145. * @type {string|null}
  146. * @private
  147. */
  148. this._pinnedEndpoint = null;
  149. /**
  150. * The endpoint ID of currently selected participant or <tt>null</tt> if
  151. * no user is selected.
  152. * @type {string|null}
  153. * @private
  154. */
  155. this._selectedEndpoint = null;
  156. // The last N change listener.
  157. this._lastNChangeListener = this._onLastNChanged.bind(this);
  158. // Switch audio output device on all remote audio tracks. Local audio
  159. // tracks handle this event by themselves.
  160. if (RTCUtils.isDeviceChangeAvailable('output')) {
  161. RTCUtils.addListener(RTCEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  162. deviceId => this._updateAudioOutputForAudioTracks(deviceId));
  163. RTCUtils.addListener(
  164. RTCEvents.DEVICE_LIST_CHANGED,
  165. () => this._updateAudioOutputForAudioTracks(
  166. RTCUtils.getAudioOutputDevice()));
  167. }
  168. }
  169. /**
  170. * Creates the local MediaStreams.
  171. * @param {object} [options] Optional parameters.
  172. * @param {array} options.devices The devices that will be requested.
  173. * @param {string} options.resolution Resolution constraints.
  174. * @param {bool} options.dontCreateJitsiTrack If <tt>true</tt> objects with
  175. * the following structure {stream: the Media Stream, type: "audio" or
  176. * "video", videoType: "camera" or "desktop"} will be returned trough
  177. * the Promise, otherwise JitsiTrack objects will be returned.
  178. * @param {string} options.cameraDeviceId
  179. * @param {string} options.micDeviceId
  180. * @returns {*} Promise object that will receive the new JitsiTracks
  181. */
  182. static obtainAudioAndVideoPermissions(options) {
  183. const usesNewGumFlow = browser.usesNewGumFlow();
  184. const obtainMediaPromise = usesNewGumFlow
  185. ? RTCUtils.newObtainAudioAndVideoPermissions(options)
  186. : RTCUtils.obtainAudioAndVideoPermissions(options);
  187. return obtainMediaPromise.then(
  188. tracksInfo => {
  189. const tracks = usesNewGumFlow
  190. ? _newCreateLocalTracks(tracksInfo)
  191. : createLocalTracks(tracksInfo, options);
  192. return tracks.some(track => !track._isReceivingData())
  193. ? Promise.reject(
  194. new JitsiTrackError(
  195. JitsiTrackErrors.NO_DATA_FROM_SOURCE))
  196. : tracks;
  197. });
  198. }
  199. /**
  200. * Initializes the bridge channel of this instance.
  201. * At least one of both, peerconnection or wsUrl parameters, must be
  202. * given.
  203. * @param {RTCPeerConnection} [peerconnection] WebRTC peer connection
  204. * instance.
  205. * @param {string} [wsUrl] WebSocket URL.
  206. */
  207. initializeBridgeChannel(peerconnection, wsUrl) {
  208. this._channel = new BridgeChannel(
  209. peerconnection, wsUrl, this.eventEmitter);
  210. this._channelOpenListener = () => {
  211. // Mark that channel as opened.
  212. this._channelOpen = true;
  213. // When the channel becomes available, tell the bridge about
  214. // video selections so that it can do adaptive simulcast,
  215. // we want the notification to trigger even if userJid
  216. // is undefined, or null.
  217. try {
  218. this._channel.sendPinnedEndpointMessage(
  219. this._pinnedEndpoint);
  220. this._channel.sendSelectedEndpointMessage(
  221. this._selectedEndpoint);
  222. } catch (error) {
  223. GlobalOnErrorHandler.callErrorHandler(error);
  224. logger.error(
  225. `Cannot send selected(${this._selectedEndpoint})`
  226. + `pinned(${this._pinnedEndpoint}) endpoint message.`,
  227. error);
  228. }
  229. this.removeListener(RTCEvents.DATA_CHANNEL_OPEN,
  230. this._channelOpenListener);
  231. this._channelOpenListener = null;
  232. // If setLastN was invoked before the bridge channel completed
  233. // opening, apply the specified value now that the channel
  234. // is open. NOTE that -1 is the default value assumed by both
  235. // RTC module and the JVB.
  236. if (this._lastN !== -1) {
  237. this._channel.sendSetLastNMessage(this._lastN);
  238. }
  239. };
  240. this.addListener(RTCEvents.DATA_CHANNEL_OPEN,
  241. this._channelOpenListener);
  242. // Add Last N change listener.
  243. this.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  244. this._lastNChangeListener);
  245. }
  246. /**
  247. * Receives events when Last N had changed.
  248. * @param {array} lastNEndpoints The new Last N endpoints.
  249. * @private
  250. */
  251. _onLastNChanged(lastNEndpoints = []) {
  252. const oldLastNEndpoints = this._lastNEndpoints || [];
  253. let leavingLastNEndpoints = [];
  254. let enteringLastNEndpoints = [];
  255. this._lastNEndpoints = lastNEndpoints;
  256. leavingLastNEndpoints = oldLastNEndpoints.filter(
  257. id => !this.isInLastN(id));
  258. enteringLastNEndpoints = lastNEndpoints.filter(
  259. id => oldLastNEndpoints.indexOf(id) === -1);
  260. this.conference.eventEmitter.emit(
  261. JitsiConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  262. leavingLastNEndpoints,
  263. enteringLastNEndpoints);
  264. }
  265. /**
  266. * Should be called when current media session ends and after the
  267. * PeerConnection has been closed using PeerConnection.close() method.
  268. */
  269. onCallEnded() {
  270. if (this._channel) {
  271. // The BridgeChannel is not explicitly closed as the PeerConnection
  272. // is closed on call ended which triggers datachannel onclose
  273. // events. If using a WebSocket, the channel must be closed since
  274. // it is not managed by the PeerConnection.
  275. // The reference is cleared to disable any logic related to the
  276. // channel.
  277. if (this._channel && this._channel.mode === 'websocket') {
  278. this._channel.close();
  279. }
  280. this._channel = null;
  281. this._channelOpen = false;
  282. }
  283. }
  284. /**
  285. * Sets the maximum video size the local participant should receive from
  286. * remote participants. Will no-op if no data channel has been established.
  287. *
  288. * @param {number} maxFrameHeightPixels the maximum frame height, in pixels,
  289. * this receiver is willing to receive.
  290. * @returns {void}
  291. */
  292. setReceiverVideoConstraint(maxFrameHeight) {
  293. if (this._channel) {
  294. this._channel.sendReceiverVideoConstraintMessage(maxFrameHeight);
  295. }
  296. }
  297. /**
  298. * Elects the participant with the given id to be the selected participant
  299. * in order to always receive video for this participant (even when last n
  300. * is enabled).
  301. * If there is no channel we store it and send it through the channel once
  302. * it is created.
  303. * @param {string} id The user id.
  304. * @throws NetworkError or InvalidStateError or Error if the operation
  305. * fails.
  306. */
  307. selectEndpoint(id) {
  308. // Cache the value if channel is missing, till we open it.
  309. this._selectedEndpoint = id;
  310. if (this._channel && this._channelOpen) {
  311. this._channel.sendSelectedEndpointMessage(id);
  312. }
  313. }
  314. /**
  315. * Elects the participant with the given id to be the pinned participant in
  316. * order to always receive video for this participant (even when last n is
  317. * enabled).
  318. * @param {stirng} id The user id.
  319. * @throws NetworkError or InvalidStateError or Error if the operation
  320. * fails.
  321. */
  322. pinEndpoint(id) {
  323. // Cache the value if channel is missing, till we open it.
  324. this._pinnedEndpoint = id;
  325. if (this._channel && this._channelOpen) {
  326. this._channel.sendPinnedEndpointMessage(id);
  327. }
  328. }
  329. /**
  330. *
  331. * @param eventType
  332. * @param listener
  333. */
  334. static addListener(eventType, listener) {
  335. RTCUtils.addListener(eventType, listener);
  336. }
  337. /**
  338. *
  339. * @param eventType
  340. * @param listener
  341. */
  342. static removeListener(eventType, listener) {
  343. RTCUtils.removeListener(eventType, listener);
  344. }
  345. /**
  346. *
  347. * @param options
  348. */
  349. static init(options = {}) {
  350. this.options = options;
  351. return RTCUtils.init(this.options);
  352. }
  353. /**
  354. *
  355. */
  356. static getDeviceAvailability() {
  357. return RTCUtils.getDeviceAvailability();
  358. }
  359. /* eslint-disable max-params */
  360. /**
  361. * Creates new <tt>TraceablePeerConnection</tt>
  362. * @param {SignalingLayer} signaling The signaling layer that will
  363. * provide information about the media or participants which is not
  364. * carried over SDP.
  365. * @param {object} iceConfig An object describing the ICE config like
  366. * defined in the WebRTC specification.
  367. * @param {boolean} isP2P Indicates whether or not the new TPC will be used
  368. * in a peer to peer type of session.
  369. * @param {object} options The config options.
  370. * @param {boolean} options.disableSimulcast If set to 'true' will disable
  371. * the simulcast.
  372. * @param {boolean} options.disableRtx If set to 'true' will disable the
  373. * RTX.
  374. * @param {boolean} options.disableH264 If set to 'true' H264 will be
  375. * disabled by removing it from the SDP.
  376. * @param {boolean} options.preferH264 If set to 'true' H264 will be
  377. * preferred over other video codecs.
  378. * @return {TraceablePeerConnection}
  379. */
  380. createPeerConnection(signaling, iceConfig, isP2P, options) {
  381. const pcConstraints = RTC.getPCConstraints(isP2P);
  382. if (typeof options.abtestSuspendVideo !== 'undefined') {
  383. RTCUtils.setSuspendVideo(pcConstraints, options.abtestSuspendVideo);
  384. Statistics.analytics.addPermanentProperties(
  385. { abtestSuspendVideo: options.abtestSuspendVideo });
  386. }
  387. peerConnectionIdCounter = safeCounterIncrement(peerConnectionIdCounter);
  388. const newConnection
  389. = new TraceablePeerConnection(
  390. this,
  391. peerConnectionIdCounter,
  392. signaling,
  393. iceConfig, pcConstraints,
  394. isP2P, options);
  395. this.peerConnections.set(newConnection.id, newConnection);
  396. return newConnection;
  397. }
  398. /* eslint-enable max-params */
  399. /**
  400. * Removed given peer connection from this RTC module instance.
  401. * @param {TraceablePeerConnection} traceablePeerConnection
  402. * @return {boolean} <tt>true</tt> if the given peer connection was removed
  403. * successfully or <tt>false</tt> if there was no peer connection mapped in
  404. * this RTC instance.
  405. */
  406. _removePeerConnection(traceablePeerConnection) {
  407. const id = traceablePeerConnection.id;
  408. if (this.peerConnections.has(id)) {
  409. // NOTE Remote tracks are not removed here.
  410. this.peerConnections.delete(id);
  411. return true;
  412. }
  413. return false;
  414. }
  415. /**
  416. *
  417. * @param track
  418. */
  419. addLocalTrack(track) {
  420. if (!track) {
  421. throw new Error('track must not be null nor undefined');
  422. }
  423. this.localTracks.push(track);
  424. track.conference = this.conference;
  425. }
  426. /**
  427. * Returns the current value for "lastN" - the amount of videos are going
  428. * to be delivered. When set to -1 for unlimited or all available videos.
  429. * @return {number}
  430. */
  431. getLastN() {
  432. return this._lastN;
  433. }
  434. /**
  435. * Get local video track.
  436. * @returns {JitsiLocalTrack|undefined}
  437. */
  438. getLocalVideoTrack() {
  439. const localVideo = this.getLocalTracks(MediaType.VIDEO);
  440. return localVideo.length ? localVideo[0] : undefined;
  441. }
  442. /**
  443. * Get local audio track.
  444. * @returns {JitsiLocalTrack|undefined}
  445. */
  446. getLocalAudioTrack() {
  447. const localAudio = this.getLocalTracks(MediaType.AUDIO);
  448. return localAudio.length ? localAudio[0] : undefined;
  449. }
  450. /**
  451. * Returns the local tracks of the given media type, or all local tracks if
  452. * no specific type is given.
  453. * @param {MediaType} [mediaType] Optional media type filter.
  454. * (audio or video).
  455. */
  456. getLocalTracks(mediaType) {
  457. let tracks = this.localTracks.slice();
  458. if (mediaType !== undefined) {
  459. tracks = tracks.filter(
  460. track => track.getType() === mediaType);
  461. }
  462. return tracks;
  463. }
  464. /**
  465. * Obtains all remote tracks currently known to this RTC module instance.
  466. * @param {MediaType} [mediaType] The remote tracks will be filtered
  467. * by their media type if this argument is specified.
  468. * @return {Array<JitsiRemoteTrack>}
  469. */
  470. getRemoteTracks(mediaType) {
  471. let remoteTracks = [];
  472. for (const tpc of this.peerConnections.values()) {
  473. const pcRemoteTracks = tpc.getRemoteTracks(undefined, mediaType);
  474. if (pcRemoteTracks) {
  475. remoteTracks = remoteTracks.concat(pcRemoteTracks);
  476. }
  477. }
  478. return remoteTracks;
  479. }
  480. /**
  481. * Set mute for all local audio streams attached to the conference.
  482. * @param value The mute value.
  483. * @returns {Promise}
  484. */
  485. setAudioMute(value) {
  486. const mutePromises = [];
  487. this.getLocalTracks(MediaType.AUDIO).forEach(audioTrack => {
  488. // this is a Promise
  489. mutePromises.push(value ? audioTrack.mute() : audioTrack.unmute());
  490. });
  491. // We return a Promise from all Promises so we can wait for their
  492. // execution.
  493. return Promise.all(mutePromises);
  494. }
  495. /**
  496. *
  497. * @param track
  498. */
  499. removeLocalTrack(track) {
  500. const pos = this.localTracks.indexOf(track);
  501. if (pos === -1) {
  502. return;
  503. }
  504. this.localTracks.splice(pos, 1);
  505. }
  506. /**
  507. * Removes all JitsiRemoteTracks associated with given MUC nickname
  508. * (resource part of the JID). Returns array of removed tracks.
  509. *
  510. * @param {string} Owner The resource part of the MUC JID.
  511. * @returns {JitsiRemoteTrack[]}
  512. */
  513. removeRemoteTracks(owner) {
  514. let removedTracks = [];
  515. for (const tpc of this.peerConnections.values()) {
  516. const pcRemovedTracks = tpc.removeRemoteTracks(owner);
  517. removedTracks = removedTracks.concat(pcRemovedTracks);
  518. }
  519. logger.debug(
  520. `Removed remote tracks for ${owner}`
  521. + ` count: ${removedTracks.length}`);
  522. return removedTracks;
  523. }
  524. /**
  525. *
  526. */
  527. static getPCConstraints(isP2P) {
  528. const pcConstraints
  529. = isP2P ? RTCUtils.p2pPcConstraints : RTCUtils.pcConstraints;
  530. if (!pcConstraints) {
  531. return {};
  532. }
  533. return JSON.parse(JSON.stringify(pcConstraints));
  534. }
  535. /**
  536. *
  537. * @param elSelector
  538. * @param stream
  539. */
  540. static attachMediaStream(elSelector, stream) {
  541. return RTCUtils.attachMediaStream(elSelector, stream);
  542. }
  543. /**
  544. * Returns the id of the given stream.
  545. * @param {MediaStream} stream
  546. */
  547. static getStreamID(stream) {
  548. return RTCUtils.getStreamID(stream);
  549. }
  550. /**
  551. * Returns the id of the given track.
  552. * @param {MediaStreamTrack} track
  553. */
  554. static getTrackID(track) {
  555. return RTCUtils.getTrackID(track);
  556. }
  557. /**
  558. * Returns true if retrieving the the list of input devices is supported
  559. * and false if not.
  560. */
  561. static isDeviceListAvailable() {
  562. return RTCUtils.isDeviceListAvailable();
  563. }
  564. /**
  565. * Returns true if changing the input (camera / microphone) or output
  566. * (audio) device is supported and false if not.
  567. * @param {string} [deviceType] Type of device to change. Default is
  568. * undefined or 'input', 'output' - for audio output device change.
  569. * @returns {boolean} true if available, false otherwise.
  570. */
  571. static isDeviceChangeAvailable(deviceType) {
  572. return RTCUtils.isDeviceChangeAvailable(deviceType);
  573. }
  574. /**
  575. * Returns whether the current execution environment supports WebRTC (for
  576. * use within this library).
  577. *
  578. * @returns {boolean} {@code true} if WebRTC is supported in the current
  579. * execution environment (for use within this library); {@code false},
  580. * otherwise.
  581. */
  582. static isWebRtcSupported() {
  583. return browser.isSupported();
  584. }
  585. /**
  586. * Returns currently used audio output device id, '' stands for default
  587. * device
  588. * @returns {string}
  589. */
  590. static getAudioOutputDevice() {
  591. return RTCUtils.getAudioOutputDevice();
  592. }
  593. /**
  594. * Returns list of available media devices if its obtained, otherwise an
  595. * empty array is returned/
  596. * @returns {array} list of available media devices.
  597. */
  598. static getCurrentlyAvailableMediaDevices() {
  599. return RTCUtils.getCurrentlyAvailableMediaDevices();
  600. }
  601. /**
  602. * Returns event data for device to be reported to stats.
  603. * @returns {MediaDeviceInfo} device.
  604. */
  605. static getEventDataForActiveDevice(device) {
  606. return RTCUtils.getEventDataForActiveDevice(device);
  607. }
  608. /**
  609. * Sets current audio output device.
  610. * @param {string} deviceId Id of 'audiooutput' device from
  611. * navigator.mediaDevices.enumerateDevices().
  612. * @returns {Promise} resolves when audio output is changed, is rejected
  613. * otherwise
  614. */
  615. static setAudioOutputDevice(deviceId) {
  616. return RTCUtils.setAudioOutputDevice(deviceId);
  617. }
  618. /**
  619. * Returns <tt>true<tt/> if given WebRTC MediaStream is considered a valid
  620. * "user" stream which means that it's not a "receive only" stream nor a
  621. * "mixed" JVB stream.
  622. *
  623. * Clients that implement Unified Plan, such as Firefox use recvonly
  624. * "streams/channels/tracks" for receiving remote stream/tracks, as opposed
  625. * to Plan B where there are only 3 channels: audio, video and data.
  626. *
  627. * @param {MediaStream} stream The WebRTC MediaStream instance.
  628. * @returns {boolean}
  629. */
  630. static isUserStream(stream) {
  631. return RTC.isUserStreamById(RTCUtils.getStreamID(stream));
  632. }
  633. /**
  634. * Returns <tt>true<tt/> if a WebRTC MediaStream identified by given stream
  635. * ID is considered a valid "user" stream which means that it's not a
  636. * "receive only" stream nor a "mixed" JVB stream.
  637. *
  638. * Clients that implement Unified Plan, such as Firefox use recvonly
  639. * "streams/channels/tracks" for receiving remote stream/tracks, as opposed
  640. * to Plan B where there are only 3 channels: audio, video and data.
  641. *
  642. * @param {string} streamId The id of WebRTC MediaStream.
  643. * @returns {boolean}
  644. */
  645. static isUserStreamById(streamId) {
  646. return streamId && streamId !== 'mixedmslabel'
  647. && streamId !== 'default';
  648. }
  649. /**
  650. * Allows to receive list of available cameras/microphones.
  651. * @param {function} callback Would receive array of devices as an
  652. * argument.
  653. */
  654. static enumerateDevices(callback) {
  655. RTCUtils.enumerateDevices(callback);
  656. }
  657. /**
  658. * A method to handle stopping of the stream.
  659. * One point to handle the differences in various implementations.
  660. * @param {MediaStream} mediaStream MediaStream object to stop.
  661. */
  662. static stopMediaStream(mediaStream) {
  663. RTCUtils.stopMediaStream(mediaStream);
  664. }
  665. /**
  666. * Returns whether the desktop sharing is enabled or not.
  667. * @returns {boolean}
  668. */
  669. static isDesktopSharingEnabled() {
  670. return RTCUtils.isDesktopSharingEnabled();
  671. }
  672. /**
  673. * Closes the currently opened bridge channel.
  674. */
  675. closeBridgeChannel() {
  676. if (this._channel) {
  677. this._channel.close();
  678. this._channelOpen = false;
  679. this.removeListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  680. this._lastNChangeListener);
  681. }
  682. }
  683. /* eslint-disable max-params */
  684. /**
  685. *
  686. * @param {TraceablePeerConnection} tpc
  687. * @param {number} ssrc
  688. * @param {number} audioLevel
  689. * @param {boolean} isLocal
  690. */
  691. setAudioLevel(tpc, ssrc, audioLevel, isLocal) {
  692. const track = tpc.getTrackBySSRC(ssrc);
  693. if (!track) {
  694. return;
  695. } else if (!track.isAudioTrack()) {
  696. logger.warn(`Received audio level for non-audio track: ${ssrc}`);
  697. return;
  698. } else if (track.isLocal() !== isLocal) {
  699. logger.error(
  700. `${track} was expected to ${isLocal ? 'be' : 'not be'} local`);
  701. }
  702. track.setAudioLevel(audioLevel, tpc);
  703. }
  704. /* eslint-enable max-params */
  705. /**
  706. * Sends message via the bridge channel.
  707. * @param {string} to The id of the endpoint that should receive the
  708. * message. If "" the message will be sent to all participants.
  709. * @param {object} payload The payload of the message.
  710. * @throws NetworkError or InvalidStateError or Error if the operation
  711. * fails or there is no data channel created.
  712. */
  713. sendChannelMessage(to, payload) {
  714. if (this._channel) {
  715. this._channel.sendMessage(to, payload);
  716. } else {
  717. throw new Error('Channel support is disabled!');
  718. }
  719. }
  720. /**
  721. * Selects a new value for "lastN". The requested amount of videos are going
  722. * to be delivered after the value is in effect. Set to -1 for unlimited or
  723. * all available videos.
  724. * @param {number} value the new value for lastN.
  725. */
  726. setLastN(value) {
  727. if (this._lastN !== value) {
  728. this._lastN = value;
  729. if (this._channel && this._channelOpen) {
  730. this._channel.sendSetLastNMessage(value);
  731. }
  732. this.eventEmitter.emit(RTCEvents.LASTN_VALUE_CHANGED, value);
  733. }
  734. }
  735. /**
  736. * Indicates if the endpoint id is currently included in the last N.
  737. * @param {string} id The endpoint id that we check for last N.
  738. * @returns {boolean} true if the endpoint id is in the last N or if we
  739. * don't have bridge channel support, otherwise we return false.
  740. */
  741. isInLastN(id) {
  742. return !this._lastNEndpoints // lastNEndpoints not initialised yet.
  743. || this._lastNEndpoints.indexOf(id) > -1;
  744. }
  745. /**
  746. * Updates the target audio output device for all remote audio tracks.
  747. *
  748. * @param {string} deviceId - The device id of the audio ouput device to
  749. * use for all remote tracks.
  750. * @private
  751. * @returns {void}
  752. */
  753. _updateAudioOutputForAudioTracks(deviceId) {
  754. const remoteAudioTracks = this.getRemoteTracks(MediaType.AUDIO);
  755. for (const track of remoteAudioTracks) {
  756. track.setAudioOutput(deviceId);
  757. }
  758. }
  759. }