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

JitsiLocalTrack.js 32KB

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