Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

JitsiLocalTrack.js 34KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961
  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. if (stream) {
  450. // Store the MSID for video mute/unmute purposes.
  451. this.storedMSID = this.getMSID();
  452. logger.debug(`Setting new MSID: ${this.storedMSID} on ${this}`);
  453. } else {
  454. logger.debug(`Setting 'null' stream on ${this}`);
  455. }
  456. }
  457. /**
  458. * Starts the effect process and returns the modified stream.
  459. *
  460. * @param {Object} effect - Represents effect instance
  461. * @private
  462. * @returns {void}
  463. */
  464. _startStreamEffect(effect) {
  465. this._streamEffect = effect;
  466. this._originalStream = this.stream;
  467. this._setStream(this._streamEffect.startEffect(this._originalStream));
  468. this.track = this.stream.getTracks()[0];
  469. }
  470. /**
  471. * Stops the effect process and returns the original stream.
  472. *
  473. * @private
  474. * @returns {void}
  475. */
  476. _stopStreamEffect() {
  477. if (this._streamEffect) {
  478. this._streamEffect.stopEffect();
  479. this._setStream(this._originalStream);
  480. this._originalStream = null;
  481. this.track = this.stream ? this.stream.getTracks()[0] : null;
  482. }
  483. }
  484. /**
  485. * Switches the camera facing mode if the WebRTC implementation supports the custom MediaStreamTrack._switchCamera
  486. * method. Currently, the method in question is implemented in react-native-webrtc only. When such a WebRTC
  487. * implementation is executing, the method is the preferred way to switch between the front/user-facing and the
  488. * back/environment-facing cameras because it will likely be (as is the case of react-native-webrtc) noticeably
  489. * faster that creating a new MediaStreamTrack via a new getUserMedia call with the switched facingMode constraint
  490. * value. Moreover, the approach with a new getUserMedia call may not even work: WebRTC on Android and iOS is
  491. * either very slow to open the camera a second time or plainly freezes attempting to do that.
  492. *
  493. * @returns {void}
  494. */
  495. _switchCamera() {
  496. if (this.isVideoTrack()
  497. && this.videoType === VideoType.CAMERA
  498. && typeof this.track._switchCamera === 'function') {
  499. this.track._switchCamera();
  500. this._facingMode
  501. = this._facingMode === CameraFacingMode.ENVIRONMENT
  502. ? CameraFacingMode.USER
  503. : CameraFacingMode.ENVIRONMENT;
  504. }
  505. }
  506. /**
  507. * Stops the currently used effect (if there is one) and starts the passed effect (if there is one).
  508. *
  509. * @param {Object|undefined} effect - The new effect to be set.
  510. * @private
  511. * @returns {void}
  512. */
  513. _switchStreamEffect(effect) {
  514. if (this._streamEffect) {
  515. this._stopStreamEffect();
  516. this._streamEffect = undefined;
  517. }
  518. if (effect) {
  519. this._startStreamEffect(effect);
  520. }
  521. }
  522. /**
  523. * @inheritdoc
  524. *
  525. * Stops sending the media track. And removes it from the HTML. NOTE: Works for local tracks only.
  526. *
  527. * @extends JitsiTrack#dispose
  528. * @returns {Promise}
  529. */
  530. async dispose() {
  531. // Remove the effect instead of stopping it so that the original stream is restored
  532. // on both the local track and on the peerconnection.
  533. if (this._streamEffect) {
  534. await this.setEffect();
  535. }
  536. if (this.conference) {
  537. await this.conference.removeTrack(this);
  538. }
  539. if (this.stream) {
  540. this.stopStream();
  541. this.detach();
  542. }
  543. RTCUtils.removeListener(RTCEvents.DEVICE_LIST_WILL_CHANGE, this._onDeviceListWillChange);
  544. if (this._onAudioOutputDeviceChanged) {
  545. RTCUtils.removeListener(RTCEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  546. this._onAudioOutputDeviceChanged);
  547. }
  548. return super.dispose();
  549. }
  550. /**
  551. * Returns facing mode for video track from camera. For other cases (e.g. audio track or 'desktop' video track)
  552. * returns undefined.
  553. *
  554. * @returns {CameraFacingMode|undefined}
  555. */
  556. getCameraFacingMode() {
  557. if (this.isVideoTrack() && this.videoType === VideoType.CAMERA) {
  558. // MediaStreamTrack#getSettings() is not implemented in many
  559. // browsers, so we need feature checking here. Progress on the
  560. // respective browser's implementation can be tracked at
  561. // https://bugs.chromium.org/p/webrtc/issues/detail?id=2481 for
  562. // Chromium and https://bugzilla.mozilla.org/show_bug.cgi?id=1213517
  563. // for Firefox. Even if a browser implements getSettings() already,
  564. // it might still not return anything for 'facingMode'.
  565. const trackSettings = this.track.getSettings?.();
  566. if (trackSettings && 'facingMode' in trackSettings) {
  567. return trackSettings.facingMode;
  568. }
  569. if (typeof this._facingMode !== 'undefined') {
  570. return this._facingMode;
  571. }
  572. // In most cases we are showing a webcam. So if we've gotten here,
  573. // it should be relatively safe to assume that we are probably
  574. // showing the user-facing camera.
  575. return CameraFacingMode.USER;
  576. }
  577. return undefined;
  578. }
  579. /**
  580. * Returns the capture resolution of the video track.
  581. *
  582. * @returns {Number}
  583. */
  584. getCaptureResolution() {
  585. if (this.videoType === VideoType.CAMERA || !browser.isWebKitBased()) {
  586. return this.resolution;
  587. }
  588. return this.getHeight();
  589. }
  590. /**
  591. * Returns device id associated with track.
  592. *
  593. * @returns {string}
  594. */
  595. getDeviceId() {
  596. return this._realDeviceId || this.deviceId;
  597. }
  598. /**
  599. * Get the duration of the track.
  600. *
  601. * @returns {Number} the duration of the track in seconds
  602. */
  603. getDuration() {
  604. return (Date.now() / 1000) - (this.metadata.timestamp / 1000);
  605. }
  606. /**
  607. * Returns the participant id which owns the track.
  608. *
  609. * @returns {string} the id of the participants. It corresponds to the
  610. * Colibri endpoint id/MUC nickname in case of Jitsi-meet.
  611. */
  612. getParticipantId() {
  613. return this.conference && this.conference.myUserId();
  614. }
  615. /**
  616. * Returns the source name associated with the jitsi track.
  617. *
  618. * @returns {string | null} source name
  619. */
  620. getSourceName() {
  621. return this._sourceName;
  622. }
  623. /**
  624. * Returns if associated MediaStreamTrack is in the 'ended' state
  625. *
  626. * @returns {boolean}
  627. */
  628. isEnded() {
  629. if (this.isVideoTrack() && this.isMuted()) {
  630. // If a video track is muted the readyState will be ended, that's why we need to rely only on the
  631. // _trackEnded flag.
  632. return this._trackEnded;
  633. }
  634. return this.getTrack().readyState === 'ended' || this._trackEnded;
  635. }
  636. /**
  637. * Returns <tt>true</tt>.
  638. *
  639. * @returns {boolean} <tt>true</tt>
  640. */
  641. isLocal() {
  642. return true;
  643. }
  644. /**
  645. * Returns <tt>true</tt> - if the stream is muted and <tt>false</tt> otherwise.
  646. *
  647. * @returns {boolean} <tt>true</tt> - if the stream is muted and <tt>false</tt> otherwise.
  648. */
  649. isMuted() {
  650. // this.stream will be null when we mute local video on Chrome
  651. if (!this.stream) {
  652. return true;
  653. }
  654. if (this.isVideoTrack() && !this.isActive()) {
  655. return true;
  656. }
  657. // If currently used stream effect has its own muted state, use that.
  658. if (this._streamEffect && this._streamEffect.isMuted) {
  659. return this._streamEffect.isMuted();
  660. }
  661. return !this.track || !this.track.enabled;
  662. }
  663. /**
  664. * Checks whether the attached MediaStream is receiving data from source or not. If the stream property is null
  665. * (because of mute or another reason) this method will return false.
  666. * NOTE: This method doesn't indicate problem with the streams directly. For example in case of video mute the
  667. * method will return false or if the user has disposed the track.
  668. *
  669. * @returns {boolean} true if the stream is receiving data and false this otherwise.
  670. */
  671. isReceivingData() {
  672. if (this.isVideoTrack()
  673. && (this.isMuted() || this._stopStreamInProgress || this.videoType === VideoType.DESKTOP)) {
  674. return true;
  675. }
  676. if (!this.stream) {
  677. return false;
  678. }
  679. // In older version of the spec there is no muted property and readyState can have value muted. In the latest
  680. // versions readyState can have values "live" and "ended" and there is muted boolean property. If the stream is
  681. // muted that means that we aren't receiving any data from the source. We want to notify the users for error if
  682. // the stream is muted or ended on it's creation.
  683. // For video blur enabled use the original video stream
  684. const stream = this._effectEnabled ? this._originalStream : this.stream;
  685. return stream.getTracks().some(track =>
  686. (!('readyState' in track) || track.readyState === 'live')
  687. && (!('muted' in track) || track.muted !== true));
  688. }
  689. /**
  690. * Asynchronously mutes this track.
  691. *
  692. * @returns {Promise}
  693. */
  694. mute() {
  695. return this._queueSetMuted(true);
  696. }
  697. /**
  698. * Handles bytes sent statistics. NOTE: used only for audio tracks to detect audio issues.
  699. *
  700. * @param {TraceablePeerConnection} tpc - The peerconnection that is reporting the bytes sent stat.
  701. * @param {number} bytesSent - The new value.
  702. * @returns {void}
  703. */
  704. onByteSentStatsReceived(tpc, bytesSent) {
  705. if (bytesSent > 0) {
  706. this._hasSentData = true;
  707. }
  708. const iceConnectionState = tpc.getConnectionState();
  709. if (this._testDataSent && iceConnectionState === 'connected') {
  710. setTimeout(() => {
  711. if (!this._hasSentData) {
  712. logger.warn(`${this} 'bytes sent' <= 0: \
  713. ${bytesSent}`);
  714. Statistics.analytics.sendEvent(NO_BYTES_SENT, { 'media_type': this.getType() });
  715. }
  716. }, 3000);
  717. this._testDataSent = false;
  718. }
  719. }
  720. /**
  721. * Sets the JitsiConference object associated with the track. This is temp solution.
  722. *
  723. * @param conference - JitsiConference object.
  724. * @returns {void}
  725. */
  726. setConference(conference) {
  727. this.conference = conference;
  728. }
  729. /**
  730. * Sets the effect and switches between the modified stream and original one.
  731. *
  732. * @param {Object} effect - Represents the effect instance to be used.
  733. * @returns {Promise}
  734. */
  735. setEffect(effect) {
  736. if (typeof this._streamEffect === 'undefined' && typeof effect === 'undefined') {
  737. return Promise.resolve();
  738. }
  739. if (typeof effect !== 'undefined' && !effect.isEnabled(this)) {
  740. return Promise.reject(new Error('Incompatible effect instance!'));
  741. }
  742. if (this._setEffectInProgress === true) {
  743. return Promise.reject(new Error('setEffect already in progress!'));
  744. }
  745. // In case we have an audio track that is being enhanced with an effect, we still want it to be applied,
  746. // even if the track is muted. Where as for video the actual track doesn't exists if it's muted.
  747. if (this.isMuted() && !this.isAudioTrack()) {
  748. this._streamEffect = effect;
  749. return Promise.resolve();
  750. }
  751. const conference = this.conference;
  752. if (!conference) {
  753. this._switchStreamEffect(effect);
  754. if (this.isVideoTrack()) {
  755. this.containers.forEach(cont => {
  756. RTCUtils.attachMediaStream(cont, this.stream).catch(() => {
  757. logger.error(`Attach media failed for ${this} when trying to set effect.`);
  758. });
  759. });
  760. }
  761. return Promise.resolve();
  762. }
  763. this._setEffectInProgress = true;
  764. return conference._removeLocalTrackFromPc(this)
  765. .then(() => {
  766. this._switchStreamEffect(effect);
  767. if (this.isVideoTrack()) {
  768. this.containers.forEach(cont => {
  769. RTCUtils.attachMediaStream(cont, this.stream).catch(() => {
  770. logger.error(`Attach media failed for ${this} when trying to set effect.`);
  771. });
  772. });
  773. }
  774. return conference._addLocalTrackToPc(this);
  775. })
  776. .then(() => {
  777. this._setEffectInProgress = false;
  778. })
  779. .catch(error => {
  780. // Any error will be not recovarable and will trigger CONFERENCE_FAILED event. But let's try to cleanup
  781. // everyhting related to the effect functionality.
  782. this._setEffectInProgress = false;
  783. this._switchStreamEffect();
  784. logger.error('Failed to switch to the new stream!', error);
  785. throw error;
  786. });
  787. }
  788. /**
  789. * Sets the source name to be used for signaling the jitsi track.
  790. *
  791. * @param {string} name The source name.
  792. */
  793. setSourceName(name) {
  794. this._sourceName = name;
  795. }
  796. /**
  797. * Stops the associated MediaStream.
  798. *
  799. * @returns {void}
  800. */
  801. stopStream() {
  802. /**
  803. * Indicates that we are executing {@link #stopStream} i.e.
  804. * {@link RTCUtils#stopMediaStream} for the <tt>MediaStream</tt>
  805. * associated with this <tt>JitsiTrack</tt> instance.
  806. *
  807. * @private
  808. * @type {boolean}
  809. */
  810. this._stopStreamInProgress = true;
  811. try {
  812. RTCUtils.stopMediaStream(this.stream);
  813. } finally {
  814. this._stopStreamInProgress = false;
  815. }
  816. }
  817. /**
  818. * Creates a text representation of this local track instance.
  819. *
  820. * @return {string}
  821. */
  822. toString() {
  823. return `LocalTrack[${this.rtcId},${this.getType()}]`;
  824. }
  825. /**
  826. * Asynchronously unmutes this track.
  827. *
  828. * @returns {Promise}
  829. */
  830. unmute() {
  831. return this._queueSetMuted(false);
  832. }
  833. }