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

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