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

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