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 33KB

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