您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

JitsiLocalTrack.js 32KB

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