Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

RTC.js 29KB

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