Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

RTC.js 27KB

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