You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

RTC.js 29KB

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