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

JitsiLocalTrack.js 32KB

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