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

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