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.

JitsiLocalTrack.js 34KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953
  1. import { getLogger } from '@jitsi/logger';
  2. import JitsiTrackError from '../../JitsiTrackError';
  3. import {
  4. TRACK_IS_DISPOSED,
  5. TRACK_NO_STREAM_FOUND
  6. } from '../../JitsiTrackErrors';
  7. import {
  8. LOCAL_TRACK_STOPPED,
  9. NO_DATA_FROM_SOURCE,
  10. TRACK_MUTE_CHANGED
  11. } from '../../JitsiTrackEvents';
  12. import { CameraFacingMode } from '../../service/RTC/CameraFacingMode';
  13. import { MediaType } from '../../service/RTC/MediaType';
  14. import RTCEvents from '../../service/RTC/RTCEvents';
  15. import { VideoType } from '../../service/RTC/VideoType';
  16. import {
  17. NO_BYTES_SENT,
  18. TRACK_UNMUTED,
  19. createNoDataFromSourceEvent
  20. } from '../../service/statistics/AnalyticsEvents';
  21. import browser from '../browser';
  22. import Statistics from '../statistics/statistics';
  23. import JitsiTrack from './JitsiTrack';
  24. import RTCUtils from './RTCUtils';
  25. const logger = getLogger(__filename);
  26. /**
  27. * Represents a single media track(either audio or video).
  28. * One <tt>JitsiLocalTrack</tt> corresponds to one WebRTC MediaStreamTrack.
  29. */
  30. export default class JitsiLocalTrack extends JitsiTrack {
  31. /**
  32. * Constructs a new JitsiLocalTrack instance.
  33. *
  34. * @constructor
  35. * @param {Object} trackInfo
  36. * @param {Object} trackInfo.constraints - The contraints used for creating the track.
  37. * @param {number} trackInfo.rtcId - The ID assigned by the RTC module.
  38. * @param {Object} trackInfo.stream - The WebRTC MediaStream, parent of the track.
  39. * @param {Object} trackInfo.track - The underlying WebRTC MediaStreamTrack for new JitsiLocalTrack.
  40. * @param {string} trackInfo.mediaType - The MediaType of the JitsiLocalTrack.
  41. * @param {string} trackInfo.videoType - The VideoType of the JitsiLocalTrack.
  42. * @param {Array<Object>} trackInfo.effects - The effects to be applied to the JitsiLocalTrack.
  43. * @param {string} trackInfo.deviceId - The ID of the local device for this track.
  44. * @param {string} trackInfo.facingMode - Thehe camera facing mode used in getUserMedia call (for mobile only).
  45. * @param {string} trackInfo.sourceId - The id of the desktop sharing source, which is the Chrome media source ID,
  46. * returned by Desktop Picker on Electron. NOTE: defined for desktop sharing tracks only.
  47. * @param {string} trackInfo.sourceType - The type of source the track originates from.
  48. */
  49. constructor({
  50. constraints,
  51. deviceId,
  52. facingMode,
  53. mediaType,
  54. rtcId,
  55. sourceId,
  56. sourceType,
  57. stream,
  58. track,
  59. videoType,
  60. effects = []
  61. }) {
  62. super(
  63. /* conference */ null,
  64. stream,
  65. track,
  66. /* streamInactiveHandler */ () => this.emit(LOCAL_TRACK_STOPPED, this),
  67. mediaType,
  68. videoType);
  69. this._setEffectInProgress = false;
  70. const effect = effects.find(e => e.isEnabled(this));
  71. if (effect) {
  72. this._startStreamEffect(effect);
  73. }
  74. const displaySurface = videoType === VideoType.DESKTOP
  75. ? track.getSettings().displaySurface
  76. : null;
  77. /**
  78. * Track metadata.
  79. */
  80. this.metadata = {
  81. timestamp: Date.now(),
  82. ...displaySurface ? { displaySurface } : {}
  83. };
  84. /**
  85. * The ID assigned by the RTC module on instance creation.
  86. *
  87. * @type {number}
  88. */
  89. this.rtcId = rtcId;
  90. this.sourceId = sourceId;
  91. this.sourceType = sourceType ?? displaySurface;
  92. // Cache the constraints of the track in case of any this track
  93. // model needs to call getUserMedia again, such as when unmuting.
  94. this._constraints = track.getConstraints();
  95. if (mediaType === MediaType.VIDEO) {
  96. if (videoType === VideoType.CAMERA) {
  97. // Safari returns an empty constraints object, construct the constraints using getSettings.
  98. if (!Object.keys(this._constraints).length) {
  99. this._constraints = {
  100. height: { ideal: this.getHeight() },
  101. width: { ideal: this.getWidth() }
  102. };
  103. }
  104. // If the constraints are still empty, fallback to the constraints used for initial gUM.
  105. if (isNaN(this._constraints.height.ideal) && isNaN(this._constraints.width.ideal)) {
  106. this._constraints.height = { ideal: constraints.height.ideal };
  107. this._constraints.width = { ideal: constraints.width.ideal };
  108. }
  109. }
  110. // Get the resolution from the track itself since we do not know what camera capability the browser has
  111. // picked for the given constraints, fallback to the constraints if MediaStreamTrack.getSettings() doesn't
  112. // return the height.
  113. this.resolution = this.getHeight();
  114. if (isNaN(this.resolution) && this._constraints.height?.ideal) {
  115. this.resolution = this._constraints.height.ideal;
  116. }
  117. this.maxEnabledResolution = this.resolution;
  118. }
  119. this.deviceId = deviceId;
  120. /**
  121. * The <tt>Promise</tt> which represents the progress of a previously
  122. * queued/scheduled {@link _setMuted} (from the point of view of
  123. * {@link _queueSetMuted}).
  124. *
  125. * @private
  126. * @type {Promise}
  127. */
  128. this._prevSetMuted = Promise.resolve();
  129. /**
  130. * The facing mode of the camera from which this JitsiLocalTrack
  131. * instance was obtained.
  132. *
  133. * @private
  134. * @type {CameraFacingMode|undefined}
  135. */
  136. this._facingMode = facingMode;
  137. // Currently there is no way to know the MediaStreamTrack ended due to
  138. // to device disconnect in Firefox through e.g. "readyState" property.
  139. // Instead we will compare current track's label with device labels from
  140. // enumerateDevices() list.
  141. this._trackEnded = false;
  142. /**
  143. * Indicates whether data has been sent or not.
  144. */
  145. this._hasSentData = false;
  146. /**
  147. * Used only for detection of audio problems. We want to check only once
  148. * whether the track is sending data ot not. This flag is set to false
  149. * after the check.
  150. */
  151. this._testDataSent = true;
  152. // Currently there is no way to determine with what device track was
  153. // created (until getConstraints() support), however we can associate
  154. // tracks with real devices obtained from enumerateDevices() call as
  155. // soon as it's called.
  156. // NOTE: this.deviceId corresponds to the device id specified in GUM constraints and this._realDeviceId seems to
  157. // correspond to the id of a matching device from the available device list.
  158. this._realDeviceId = this.deviceId === '' ? undefined : this.deviceId;
  159. // The source name that will be signaled for this track.
  160. this._sourceName = null;
  161. this._trackMutedTS = 0;
  162. this._onDeviceListWillChange = devices => {
  163. const oldRealDeviceId = this._realDeviceId;
  164. this._setRealDeviceIdFromDeviceList(devices);
  165. if (
  166. // Mark track as ended for those browsers that do not support
  167. // "readyState" property. We do not touch tracks created with
  168. // default device ID "".
  169. (typeof this.getTrack().readyState === 'undefined'
  170. && typeof this._realDeviceId !== 'undefined'
  171. && !devices.find(d => d.deviceId === this._realDeviceId))
  172. // If there was an associated realDeviceID and after the device change the realDeviceId is undefined
  173. // then the associated device has been disconnected and the _trackEnded flag needs to be set. In
  174. // addition on some Chrome versions the readyState property is set after the device change event is
  175. // triggered which causes issues in jitsi-meet with the selection of a new device because we don't
  176. // detect that the old one was removed.
  177. || (typeof oldRealDeviceId !== 'undefined' && typeof this._realDeviceId === 'undefined')
  178. ) {
  179. this._trackEnded = true;
  180. }
  181. };
  182. // Subscribe each created local audio track to
  183. // RTCEvents.AUDIO_OUTPUT_DEVICE_CHANGED event. This is different from
  184. // handling this event for remote tracks (which are handled in RTC.js),
  185. // because there might be local tracks not attached to a conference.
  186. if (this.isAudioTrack() && RTCUtils.isDeviceChangeAvailable('output')) {
  187. this._onAudioOutputDeviceChanged = this.setAudioOutput.bind(this);
  188. RTCUtils.addListener(
  189. RTCEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  190. this._onAudioOutputDeviceChanged);
  191. }
  192. RTCUtils.addListener(RTCEvents.DEVICE_LIST_WILL_CHANGE, this._onDeviceListWillChange);
  193. this._initNoDataFromSourceHandlers();
  194. }
  195. /**
  196. * Adds stream to conference and marks it as "unmute" operation.
  197. *
  198. * @private
  199. * @returns {Promise}
  200. */
  201. _addStreamToConferenceAsUnmute() {
  202. if (!this.conference) {
  203. return Promise.resolve();
  204. }
  205. // FIXME it would be good to not included conference as part of this process. Only TraceablePeerConnections to
  206. // which the track is attached should care about this action. The TPCs to which the track is not attached can
  207. // sync up when track is re-attached. A problem with that is that the "modify sources" queue is part of the
  208. // JingleSessionPC and it would be excluded from the process. One solution would be to extract class between
  209. // TPC and JingleSessionPC which would contain the queue and would notify the signaling layer when local SSRCs
  210. // are changed. This would help to separate XMPP from the RTC module.
  211. return new Promise((resolve, reject) => {
  212. this.conference._addLocalTrackToPc(this)
  213. .then(resolve, error => reject(new Error(error)));
  214. });
  215. }
  216. /**
  217. * Fires NO_DATA_FROM_SOURCE event and logs it to analytics
  218. *
  219. * @private
  220. * @returns {void}
  221. */
  222. _fireNoDataFromSourceEvent() {
  223. const value = !this.isReceivingData();
  224. this.emit(NO_DATA_FROM_SOURCE, value);
  225. logger.debug(`NO_DATA_FROM_SOURCE event with value ${value} detected for track: ${this}`);
  226. // FIXME: Should we report all of those events
  227. Statistics.sendAnalytics(createNoDataFromSourceEvent(this.getType(), value));
  228. }
  229. /**
  230. * Sets handlers to the MediaStreamTrack object that will detect camera issues.
  231. *
  232. * @private
  233. * @returns {void}
  234. */
  235. _initNoDataFromSourceHandlers() {
  236. if (!this._isNoDataFromSourceEventsEnabled()) {
  237. return;
  238. }
  239. this._setHandler('track_mute', () => {
  240. this._trackMutedTS = window.performance.now();
  241. this._fireNoDataFromSourceEvent();
  242. });
  243. this._setHandler('track_unmute', () => {
  244. this._fireNoDataFromSourceEvent();
  245. Statistics.sendAnalyticsAndLog(
  246. TRACK_UNMUTED,
  247. {
  248. 'media_type': this.getType(),
  249. 'track_type': 'local',
  250. value: window.performance.now() - this._trackMutedTS
  251. });
  252. });
  253. if (this.isVideoTrack() && this.videoType === VideoType.CAMERA) {
  254. this._setHandler('track_ended', () => {
  255. if (!this.isReceivingData()) {
  256. this._fireNoDataFromSourceEvent();
  257. }
  258. });
  259. }
  260. }
  261. /**
  262. * Returns true if no data from source events are enabled for this JitsiLocalTrack and false otherwise.
  263. *
  264. * @private
  265. * @returns {boolean} - True if no data from source events are enabled for this JitsiLocalTrack and false otherwise.
  266. */
  267. _isNoDataFromSourceEventsEnabled() {
  268. // Disable the events for screen sharing.
  269. return !this.isVideoTrack() || this.videoType !== VideoType.DESKTOP;
  270. }
  271. /**
  272. * Initializes a new Promise to execute {@link #_setMuted}. May be called multiple times in a row and the
  273. * invocations of {@link #_setMuted} and, consequently, {@link #mute} and/or {@link #unmute} will be resolved in a
  274. * serialized fashion.
  275. *
  276. * @param {boolean} muted - The value to invoke <tt>_setMuted</tt> with.
  277. * @private
  278. * @returns {Promise}
  279. */
  280. _queueSetMuted(muted) {
  281. const setMuted = this._setMuted.bind(this, muted);
  282. this._prevSetMuted = this._prevSetMuted.then(setMuted, setMuted);
  283. return this._prevSetMuted;
  284. }
  285. /**
  286. * Removes stream from conference and marks it as "mute" operation.
  287. *
  288. * @param {Function} successCallback - Callback that will be called when the operation is successful.
  289. * @param {Function} errorCallback - Callback that will be called when the operation fails.
  290. * @private
  291. * @returns {Promise}
  292. */
  293. _removeStreamFromConferenceAsMute(successCallback, errorCallback) {
  294. if (!this.conference) {
  295. successCallback();
  296. return;
  297. }
  298. this.conference._removeLocalTrackFromPc(this).then(
  299. successCallback,
  300. error => errorCallback(new Error(error)));
  301. }
  302. /**
  303. * Sends mute status for a track to conference if any.
  304. *
  305. * @param {boolean} mute - If track is muted.
  306. * @private
  307. * @returns {void}
  308. */
  309. _sendMuteStatus(mute) {
  310. if (this.conference) {
  311. this.conference._setTrackMuteStatus(this.getType(), this, mute) && this.conference.room.sendPresence();
  312. }
  313. }
  314. /**
  315. * Mutes / unmutes this track.
  316. *
  317. * @param {boolean} muted - If <tt>true</tt>, this track will be muted; otherwise, this track will be unmuted.
  318. * @private
  319. * @returns {Promise}
  320. */
  321. _setMuted(muted) {
  322. if (this.isMuted() === muted && this.videoType !== VideoType.DESKTOP) {
  323. return Promise.resolve();
  324. }
  325. if (this.disposed) {
  326. return Promise.reject(new JitsiTrackError(TRACK_IS_DISPOSED));
  327. }
  328. let promise = Promise.resolve();
  329. // A function that will print info about muted status transition
  330. const logMuteInfo = () => logger.info(`Mute ${this}: ${muted}`);
  331. // In React Native we mute the camera by setting track.enabled but that doesn't
  332. // work for screen-share tracks, so do the remove-as-mute for those.
  333. const doesVideoMuteByStreamRemove
  334. = browser.isReactNative() ? this.videoType === VideoType.DESKTOP : browser.doesVideoMuteByStreamRemove();
  335. // In the multi-stream mode, desktop tracks are muted from jitsi-meet instead of being removed from the
  336. // conference. This is needed because we don't want the client to signal a source-remove to the remote peer for
  337. // the desktop track when screenshare is stopped. Later when screenshare is started again, the same sender will
  338. // be re-used without the need for signaling a new ssrc through source-add.
  339. if (this.isAudioTrack() || !doesVideoMuteByStreamRemove) {
  340. logMuteInfo();
  341. // If we have a stream effect that implements its own mute functionality, prioritize it before
  342. // normal mute e.g. the stream effect that implements system audio sharing has a custom
  343. // mute state in which if the user mutes, system audio still has to go through.
  344. if (this._streamEffect && this._streamEffect.setMuted) {
  345. this._streamEffect.setMuted(muted);
  346. } else if (this.track) {
  347. this.track.enabled = !muted;
  348. }
  349. } else if (muted) {
  350. promise = new Promise((resolve, reject) => {
  351. logMuteInfo();
  352. this._removeStreamFromConferenceAsMute(
  353. () => {
  354. if (this._streamEffect) {
  355. this._stopStreamEffect();
  356. }
  357. // FIXME: Maybe here we should set the SRC for the
  358. // containers to something
  359. // We don't want any events to be fired on this stream
  360. this._unregisterHandlers();
  361. this.stopStream();
  362. this._setStream(null);
  363. resolve();
  364. },
  365. reject);
  366. });
  367. } else {
  368. logMuteInfo();
  369. // This path is only for camera.
  370. const streamOptions = {
  371. cameraDeviceId: this.getDeviceId(),
  372. devices: [ MediaType.VIDEO ],
  373. effects: this._streamEffect ? [ this._streamEffect ] : [],
  374. facingMode: this.getCameraFacingMode()
  375. };
  376. promise
  377. = RTCUtils.obtainAudioAndVideoPermissions(Object.assign(
  378. {},
  379. streamOptions,
  380. { constraints: { video: this._constraints } }));
  381. promise = promise.then(streamsInfo => {
  382. const streamInfo = streamsInfo.find(info => info.track.kind === this.getType());
  383. if (streamInfo) {
  384. this._setStream(streamInfo.stream);
  385. this.track = streamInfo.track;
  386. // This is not good when video type changes after
  387. // unmute, but let's not crash here
  388. if (this.videoType !== streamInfo.videoType) {
  389. logger.warn(
  390. `${this}: video type has changed after unmute!`,
  391. this.videoType, streamInfo.videoType);
  392. this.videoType = streamInfo.videoType;
  393. }
  394. } else {
  395. throw new JitsiTrackError(TRACK_NO_STREAM_FOUND);
  396. }
  397. if (this._streamEffect) {
  398. this._startStreamEffect(this._streamEffect);
  399. }
  400. this.containers.map(cont => RTCUtils.attachMediaStream(cont, this.stream).catch(() => {
  401. logger.error(`Attach media failed for ${this} on video unmute!`);
  402. }));
  403. return this._addStreamToConferenceAsUnmute();
  404. });
  405. }
  406. return promise
  407. .then(() => {
  408. this._sendMuteStatus(muted);
  409. // Send the videoType message to the bridge.
  410. this.isVideoTrack() && this.conference && this.conference._sendBridgeVideoTypeMessage(this);
  411. this.emit(TRACK_MUTE_CHANGED, this);
  412. });
  413. }
  414. /**
  415. * Sets real device ID by comparing track information with device information. This is temporary solution until
  416. * getConstraints() method will be implemented in browsers.
  417. *
  418. * @param {MediaDeviceInfo[]} devices - The list of devices obtained from enumerateDevices() call.
  419. * @private
  420. * @returns {void}
  421. */
  422. _setRealDeviceIdFromDeviceList(devices) {
  423. const track = this.getTrack();
  424. const kind = `${track.kind}input`;
  425. // We need to match by deviceId as well, in case of multiple devices with the same label.
  426. let device = devices.find(d => d.kind === kind && d.label === track.label && d.deviceId === this.deviceId);
  427. if (!device && this._realDeviceId === 'default') { // the default device has been changed.
  428. // If the default device was 'A' and the default device is changed to 'B' the label for the track will
  429. // remain 'Default - A' but the label for the device in the device list will be updated to 'A'. That's
  430. // why in order to match it we need to remove the 'Default - ' part.
  431. const label = (track.label || '').replace('Default - ', '');
  432. device = devices.find(d => d.kind === kind && d.label === label);
  433. }
  434. if (device) {
  435. this._realDeviceId = device.deviceId;
  436. } else {
  437. this._realDeviceId = undefined;
  438. }
  439. }
  440. /**
  441. * Sets the stream property of JitsiLocalTrack object and sets all stored handlers to it.
  442. *
  443. * @param {MediaStream} stream - The new MediaStream.
  444. * @private
  445. * @returns {void}
  446. */
  447. _setStream(stream) {
  448. super._setStream(stream);
  449. }
  450. /**
  451. * Starts the effect process and returns the modified stream.
  452. *
  453. * @param {Object} effect - Represents effect instance
  454. * @private
  455. * @returns {void}
  456. */
  457. _startStreamEffect(effect) {
  458. this._streamEffect = effect;
  459. this._originalStream = this.stream;
  460. this._setStream(this._streamEffect.startEffect(this._originalStream));
  461. this.track = this.stream.getTracks()[0];
  462. }
  463. /**
  464. * Stops the effect process and returns the original stream.
  465. *
  466. * @private
  467. * @returns {void}
  468. */
  469. _stopStreamEffect() {
  470. if (this._streamEffect) {
  471. this._streamEffect.stopEffect();
  472. this._setStream(this._originalStream);
  473. this._originalStream = null;
  474. this.track = this.stream ? this.stream.getTracks()[0] : null;
  475. }
  476. }
  477. /**
  478. * Switches the camera facing mode if the WebRTC implementation supports the custom MediaStreamTrack._switchCamera
  479. * method. Currently, the method in question is implemented in react-native-webrtc only. When such a WebRTC
  480. * implementation is executing, the method is the preferred way to switch between the front/user-facing and the
  481. * back/environment-facing cameras because it will likely be (as is the case of react-native-webrtc) noticeably
  482. * faster that creating a new MediaStreamTrack via a new getUserMedia call with the switched facingMode constraint
  483. * value. Moreover, the approach with a new getUserMedia call may not even work: WebRTC on Android and iOS is
  484. * either very slow to open the camera a second time or plainly freezes attempting to do that.
  485. *
  486. * @returns {void}
  487. */
  488. _switchCamera() {
  489. if (this.isVideoTrack()
  490. && this.videoType === VideoType.CAMERA
  491. && typeof this.track._switchCamera === 'function') {
  492. this.track._switchCamera();
  493. this._facingMode
  494. = this._facingMode === CameraFacingMode.ENVIRONMENT
  495. ? CameraFacingMode.USER
  496. : CameraFacingMode.ENVIRONMENT;
  497. }
  498. }
  499. /**
  500. * Stops the currently used effect (if there is one) and starts the passed effect (if there is one).
  501. *
  502. * @param {Object|undefined} effect - The new effect to be set.
  503. * @private
  504. * @returns {void}
  505. */
  506. _switchStreamEffect(effect) {
  507. if (this._streamEffect) {
  508. this._stopStreamEffect();
  509. this._streamEffect = undefined;
  510. }
  511. if (effect) {
  512. this._startStreamEffect(effect);
  513. }
  514. }
  515. /**
  516. * @inheritdoc
  517. *
  518. * Stops sending the media track. And removes it from the HTML. NOTE: Works for local tracks only.
  519. *
  520. * @extends JitsiTrack#dispose
  521. * @returns {Promise}
  522. */
  523. async dispose() {
  524. // Remove the effect instead of stopping it so that the original stream is restored
  525. // on both the local track and on the peerconnection.
  526. if (this._streamEffect) {
  527. await this.setEffect();
  528. }
  529. if (this.conference) {
  530. await this.conference.removeTrack(this);
  531. }
  532. if (this.stream) {
  533. this.stopStream();
  534. this.detach();
  535. }
  536. RTCUtils.removeListener(RTCEvents.DEVICE_LIST_WILL_CHANGE, this._onDeviceListWillChange);
  537. if (this._onAudioOutputDeviceChanged) {
  538. RTCUtils.removeListener(RTCEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  539. this._onAudioOutputDeviceChanged);
  540. }
  541. return super.dispose();
  542. }
  543. /**
  544. * Returns facing mode for video track from camera. For other cases (e.g. audio track or 'desktop' video track)
  545. * returns undefined.
  546. *
  547. * @returns {CameraFacingMode|undefined}
  548. */
  549. getCameraFacingMode() {
  550. if (this.isVideoTrack() && this.videoType === VideoType.CAMERA) {
  551. // MediaStreamTrack#getSettings() is not implemented in many
  552. // browsers, so we need feature checking here. Progress on the
  553. // respective browser's implementation can be tracked at
  554. // https://bugs.chromium.org/p/webrtc/issues/detail?id=2481 for
  555. // Chromium and https://bugzilla.mozilla.org/show_bug.cgi?id=1213517
  556. // for Firefox. Even if a browser implements getSettings() already,
  557. // it might still not return anything for 'facingMode'.
  558. const trackSettings = this.track.getSettings?.();
  559. if (trackSettings && 'facingMode' in trackSettings) {
  560. return trackSettings.facingMode;
  561. }
  562. if (typeof this._facingMode !== 'undefined') {
  563. return this._facingMode;
  564. }
  565. // In most cases we are showing a webcam. So if we've gotten here,
  566. // it should be relatively safe to assume that we are probably
  567. // showing the user-facing camera.
  568. return CameraFacingMode.USER;
  569. }
  570. return undefined;
  571. }
  572. /**
  573. * Returns the capture resolution of the video track.
  574. *
  575. * @returns {Number}
  576. */
  577. getCaptureResolution() {
  578. if (this.videoType === VideoType.CAMERA || !browser.isWebKitBased()) {
  579. return this.resolution;
  580. }
  581. return this.getHeight();
  582. }
  583. /**
  584. * Returns device id associated with track.
  585. *
  586. * @returns {string}
  587. */
  588. getDeviceId() {
  589. return this._realDeviceId || this.deviceId;
  590. }
  591. /**
  592. * Get the duration of the track.
  593. *
  594. * @returns {Number} the duration of the track in seconds
  595. */
  596. getDuration() {
  597. return (Date.now() / 1000) - (this.metadata.timestamp / 1000);
  598. }
  599. /**
  600. * Returns the participant id which owns the track.
  601. *
  602. * @returns {string} the id of the participants. It corresponds to the
  603. * Colibri endpoint id/MUC nickname in case of Jitsi-meet.
  604. */
  605. getParticipantId() {
  606. return this.conference && this.conference.myUserId();
  607. }
  608. /**
  609. * Returns the source name associated with the jitsi track.
  610. *
  611. * @returns {string | null} source name
  612. */
  613. getSourceName() {
  614. return this._sourceName;
  615. }
  616. /**
  617. * Returns if associated MediaStreamTrack is in the 'ended' state
  618. *
  619. * @returns {boolean}
  620. */
  621. isEnded() {
  622. if (this.isVideoTrack() && this.isMuted()) {
  623. // If a video track is muted the readyState will be ended, that's why we need to rely only on the
  624. // _trackEnded flag.
  625. return this._trackEnded;
  626. }
  627. return this.getTrack().readyState === 'ended' || this._trackEnded;
  628. }
  629. /**
  630. * Returns <tt>true</tt>.
  631. *
  632. * @returns {boolean} <tt>true</tt>
  633. */
  634. isLocal() {
  635. return true;
  636. }
  637. /**
  638. * Returns <tt>true</tt> - if the stream is muted and <tt>false</tt> otherwise.
  639. *
  640. * @returns {boolean} <tt>true</tt> - if the stream is muted and <tt>false</tt> otherwise.
  641. */
  642. isMuted() {
  643. // this.stream will be null when we mute local video on Chrome
  644. if (!this.stream) {
  645. return true;
  646. }
  647. if (this.isVideoTrack() && !this.isActive()) {
  648. return true;
  649. }
  650. // If currently used stream effect has its own muted state, use that.
  651. if (this._streamEffect && this._streamEffect.isMuted) {
  652. return this._streamEffect.isMuted();
  653. }
  654. return !this.track || !this.track.enabled;
  655. }
  656. /**
  657. * Checks whether the attached MediaStream is receiving data from source or not. If the stream property is null
  658. * (because of mute or another reason) this method will return false.
  659. * NOTE: This method doesn't indicate problem with the streams directly. For example in case of video mute the
  660. * method will return false or if the user has disposed the track.
  661. *
  662. * @returns {boolean} true if the stream is receiving data and false this otherwise.
  663. */
  664. isReceivingData() {
  665. if (this.isVideoTrack()
  666. && (this.isMuted() || this._stopStreamInProgress || this.videoType === VideoType.DESKTOP)) {
  667. return true;
  668. }
  669. if (!this.stream) {
  670. return false;
  671. }
  672. // In older version of the spec there is no muted property and readyState can have value muted. In the latest
  673. // versions readyState can have values "live" and "ended" and there is muted boolean property. If the stream is
  674. // muted that means that we aren't receiving any data from the source. We want to notify the users for error if
  675. // the stream is muted or ended on it's creation.
  676. // For video blur enabled use the original video stream
  677. const stream = this._effectEnabled ? this._originalStream : this.stream;
  678. return stream.getTracks().some(track =>
  679. (!('readyState' in track) || track.readyState === 'live')
  680. && (!('muted' in track) || track.muted !== true));
  681. }
  682. /**
  683. * Asynchronously mutes this track.
  684. *
  685. * @returns {Promise}
  686. */
  687. mute() {
  688. return this._queueSetMuted(true);
  689. }
  690. /**
  691. * Handles bytes sent statistics. NOTE: used only for audio tracks to detect audio issues.
  692. *
  693. * @param {TraceablePeerConnection} tpc - The peerconnection that is reporting the bytes sent stat.
  694. * @param {number} bytesSent - The new value.
  695. * @returns {void}
  696. */
  697. onByteSentStatsReceived(tpc, bytesSent) {
  698. if (bytesSent > 0) {
  699. this._hasSentData = true;
  700. }
  701. const iceConnectionState = tpc.getConnectionState();
  702. if (this._testDataSent && iceConnectionState === 'connected') {
  703. setTimeout(() => {
  704. if (!this._hasSentData) {
  705. logger.warn(`${this} 'bytes sent' <= 0: \
  706. ${bytesSent}`);
  707. Statistics.analytics.sendEvent(NO_BYTES_SENT, { 'media_type': this.getType() });
  708. }
  709. }, 3000);
  710. this._testDataSent = false;
  711. }
  712. }
  713. /**
  714. * Sets the JitsiConference object associated with the track. This is temp solution.
  715. *
  716. * @param conference - JitsiConference object.
  717. * @returns {void}
  718. */
  719. setConference(conference) {
  720. this.conference = conference;
  721. }
  722. /**
  723. * Sets the effect and switches between the modified stream and original one.
  724. *
  725. * @param {Object} effect - Represents the effect instance to be used.
  726. * @returns {Promise}
  727. */
  728. setEffect(effect) {
  729. if (typeof this._streamEffect === 'undefined' && typeof effect === 'undefined') {
  730. return Promise.resolve();
  731. }
  732. if (typeof effect !== 'undefined' && !effect.isEnabled(this)) {
  733. return Promise.reject(new Error('Incompatible effect instance!'));
  734. }
  735. if (this._setEffectInProgress === true) {
  736. return Promise.reject(new Error('setEffect already in progress!'));
  737. }
  738. // In case we have an audio track that is being enhanced with an effect, we still want it to be applied,
  739. // even if the track is muted. Where as for video the actual track doesn't exists if it's muted.
  740. if (this.isMuted() && !this.isAudioTrack()) {
  741. this._streamEffect = effect;
  742. return Promise.resolve();
  743. }
  744. const conference = this.conference;
  745. if (!conference) {
  746. this._switchStreamEffect(effect);
  747. if (this.isVideoTrack()) {
  748. this.containers.forEach(cont => {
  749. RTCUtils.attachMediaStream(cont, this.stream).catch(() => {
  750. logger.error(`Attach media failed for ${this} when trying to set effect.`);
  751. });
  752. });
  753. }
  754. return Promise.resolve();
  755. }
  756. this._setEffectInProgress = true;
  757. return conference._removeLocalTrackFromPc(this)
  758. .then(() => {
  759. this._switchStreamEffect(effect);
  760. if (this.isVideoTrack()) {
  761. this.containers.forEach(cont => {
  762. RTCUtils.attachMediaStream(cont, this.stream).catch(() => {
  763. logger.error(`Attach media failed for ${this} when trying to set effect.`);
  764. });
  765. });
  766. }
  767. return conference._addLocalTrackToPc(this);
  768. })
  769. .then(() => {
  770. this._setEffectInProgress = false;
  771. })
  772. .catch(error => {
  773. // Any error will be not recovarable and will trigger CONFERENCE_FAILED event. But let's try to cleanup
  774. // everyhting related to the effect functionality.
  775. this._setEffectInProgress = false;
  776. this._switchStreamEffect();
  777. logger.error('Failed to switch to the new stream!', error);
  778. throw error;
  779. });
  780. }
  781. /**
  782. * Sets the source name to be used for signaling the jitsi track.
  783. *
  784. * @param {string} name The source name.
  785. */
  786. setSourceName(name) {
  787. this._sourceName = name;
  788. }
  789. /**
  790. * Stops the associated MediaStream.
  791. *
  792. * @returns {void}
  793. */
  794. stopStream() {
  795. /**
  796. * Indicates that we are executing {@link #stopStream} i.e.
  797. * {@link RTCUtils#stopMediaStream} for the <tt>MediaStream</tt>
  798. * associated with this <tt>JitsiTrack</tt> instance.
  799. *
  800. * @private
  801. * @type {boolean}
  802. */
  803. this._stopStreamInProgress = true;
  804. try {
  805. RTCUtils.stopMediaStream(this.stream);
  806. } finally {
  807. this._stopStreamInProgress = false;
  808. }
  809. }
  810. /**
  811. * Creates a text representation of this local track instance.
  812. *
  813. * @return {string}
  814. */
  815. toString() {
  816. return `LocalTrack[${this.rtcId},${this.getType()}]`;
  817. }
  818. /**
  819. * Asynchronously unmutes this track.
  820. *
  821. * @returns {Promise}
  822. */
  823. unmute() {
  824. return this._queueSetMuted(false);
  825. }
  826. }