You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

JitsiLocalTrack.js 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  1. /* global __filename, Promise */
  2. import CameraFacingMode from '../../service/RTC/CameraFacingMode';
  3. import { getLogger } from 'jitsi-meet-logger';
  4. import JitsiTrack from './JitsiTrack';
  5. import JitsiTrackError from '../../JitsiTrackError';
  6. import * as JitsiTrackErrors from '../../JitsiTrackErrors';
  7. import * as JitsiTrackEvents from '../../JitsiTrackEvents';
  8. import * as MediaType from '../../service/RTC/MediaType';
  9. import RTCBrowserType from './RTCBrowserType';
  10. import RTCEvents from '../../service/RTC/RTCEvents';
  11. import RTCUtils from './RTCUtils';
  12. import Statistics from '../statistics/statistics';
  13. import VideoType from '../../service/RTC/VideoType';
  14. const logger = getLogger(__filename);
  15. /* eslint-disable max-params */
  16. /**
  17. * Represents a single media track(either audio or video).
  18. * One <tt>JitsiLocalTrack</tt> corresponds to one WebRTC MediaStreamTrack.
  19. * @param {number} rtcId the ID assigned by the RTC module
  20. * @param stream WebRTC MediaStream, parent of the track
  21. * @param track underlying WebRTC MediaStreamTrack for new JitsiRemoteTrack
  22. * @param mediaType the MediaType of the JitsiRemoteTrack
  23. * @param videoType the VideoType of the JitsiRemoteTrack
  24. * @param resolution the video resolution if it's a video track
  25. * @param deviceId the ID of the local device for this track
  26. * @param facingMode the camera facing mode used in getUserMedia call
  27. * @constructor
  28. */
  29. export default function JitsiLocalTrack(
  30. rtcId,
  31. stream,
  32. track,
  33. mediaType,
  34. videoType,
  35. resolution,
  36. deviceId,
  37. facingMode) {
  38. /**
  39. * The ID assigned by the RTC module on instance creation.
  40. * @type {number}
  41. */
  42. this.rtcId = rtcId;
  43. JitsiTrack.call(
  44. this,
  45. null /* RTC */,
  46. stream,
  47. track,
  48. () => {
  49. if (!this.dontFireRemoveEvent) {
  50. this.eventEmitter.emit(JitsiTrackEvents.LOCAL_TRACK_STOPPED);
  51. }
  52. this.dontFireRemoveEvent = false;
  53. } /* inactiveHandler */,
  54. mediaType,
  55. videoType);
  56. this.dontFireRemoveEvent = false;
  57. this.resolution = resolution;
  58. // FIXME: currently firefox is ignoring our constraints about resolutions
  59. // so we do not store it, to avoid wrong reporting of local track resolution
  60. if (RTCBrowserType.isFirefox()) {
  61. this.resolution = null;
  62. }
  63. this.deviceId = deviceId;
  64. this.storedMSID = this.getMSID();
  65. this.inMuteOrUnmuteProgress = false;
  66. /**
  67. * The facing mode of the camera from which this JitsiLocalTrack instance
  68. * was obtained.
  69. *
  70. * @private
  71. * @type {CameraFacingMode|undefined}
  72. */
  73. this._facingMode = facingMode;
  74. // Currently there is no way to know the MediaStreamTrack ended due to to
  75. // device disconnect in Firefox through e.g. "readyState" property. Instead
  76. // we will compare current track's label with device labels from
  77. // enumerateDevices() list.
  78. this._trackEnded = false;
  79. /**
  80. * The value of bytes sent received from the statistics module.
  81. */
  82. this._bytesSent = null;
  83. /**
  84. * Used only for detection of audio problems. We want to check only once
  85. * whether the track is sending bytes ot not. This flag is set to false
  86. * after the check.
  87. */
  88. this._testByteSent = true;
  89. // Currently there is no way to determine with what device track was
  90. // created (until getConstraints() support), however we can associate tracks
  91. // with real devices obtained from enumerateDevices() call as soon as it's
  92. // called.
  93. this._realDeviceId = this.deviceId === '' ? undefined : this.deviceId;
  94. /**
  95. * Indicates that we have called RTCUtils.stopMediaStream for the
  96. * MediaStream related to this JitsiTrack object.
  97. */
  98. this.stopStreamInProgress = false;
  99. /**
  100. * On mute event we are waiting for 3s to check if the stream is going to
  101. * be still muted before firing the event for camera issue detected
  102. * (NO_DATA_FROM_SOURCE).
  103. */
  104. this._noDataFromSourceTimeout = null;
  105. this._onDeviceListChanged = devices => {
  106. this._setRealDeviceIdFromDeviceList(devices);
  107. // Mark track as ended for those browsers that do not support
  108. // "readyState" property. We do not touch tracks created with default
  109. // device ID "".
  110. if (typeof this.getTrack().readyState === 'undefined'
  111. && typeof this._realDeviceId !== 'undefined'
  112. && !devices.find(d => d.deviceId === this._realDeviceId)) {
  113. this._trackEnded = true;
  114. }
  115. };
  116. // Subscribe each created local audio track to
  117. // RTCEvents.AUDIO_OUTPUT_DEVICE_CHANGED event. This is different from
  118. // handling this event for remote tracks (which are handled in RTC.js),
  119. // because there might be local tracks not attached to a conference.
  120. if (this.isAudioTrack() && RTCUtils.isDeviceChangeAvailable('output')) {
  121. this._onAudioOutputDeviceChanged = this.setAudioOutput.bind(this);
  122. RTCUtils.addListener(
  123. RTCEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  124. this._onAudioOutputDeviceChanged);
  125. }
  126. RTCUtils.addListener(
  127. RTCEvents.DEVICE_LIST_CHANGED,
  128. this._onDeviceListChanged);
  129. this._initNoDataFromSourceHandlers();
  130. }
  131. /* eslint-enable max-params */
  132. JitsiLocalTrack.prototype = Object.create(JitsiTrack.prototype);
  133. JitsiLocalTrack.prototype.constructor = JitsiLocalTrack;
  134. /**
  135. * Returns if associated MediaStreamTrack is in the 'ended' state
  136. * @returns {boolean}
  137. */
  138. JitsiLocalTrack.prototype.isEnded = function() {
  139. return this.getTrack().readyState === 'ended' || this._trackEnded;
  140. };
  141. /**
  142. * Sets handlers to the MediaStreamTrack object that will detect camera issues.
  143. */
  144. JitsiLocalTrack.prototype._initNoDataFromSourceHandlers = function() {
  145. if (this.isVideoTrack() && this.videoType === VideoType.CAMERA) {
  146. const _onNoDataFromSourceError
  147. = this._onNoDataFromSourceError.bind(this);
  148. this._setHandler('track_mute', () => {
  149. if (this._checkForCameraIssues()) {
  150. const now = window.performance.now();
  151. this._noDataFromSourceTimeout
  152. = setTimeout(_onNoDataFromSourceError, 3000);
  153. this._setHandler('track_unmute', () => {
  154. this._clearNoDataFromSourceMuteResources();
  155. Statistics.sendEventToAll(
  156. `${this.getType()}.track_unmute`,
  157. { value: window.performance.now() - now });
  158. });
  159. }
  160. });
  161. this._setHandler('track_ended', _onNoDataFromSourceError);
  162. }
  163. };
  164. /**
  165. * Clears all timeouts and handlers set on MediaStreamTrack mute event.
  166. * FIXME: Change the name of the method with better one.
  167. */
  168. JitsiLocalTrack.prototype._clearNoDataFromSourceMuteResources = function() {
  169. if (this._noDataFromSourceTimeout) {
  170. clearTimeout(this._noDataFromSourceTimeout);
  171. this._noDataFromSourceTimeout = null;
  172. }
  173. this._setHandler('track_unmute', undefined);
  174. };
  175. /**
  176. * Called when potential camera issue is detected. Clears the handlers and
  177. * timeouts set on MediaStreamTrack muted event. Verifies that the camera
  178. * issue persists and fires NO_DATA_FROM_SOURCE event.
  179. */
  180. JitsiLocalTrack.prototype._onNoDataFromSourceError = function() {
  181. this._clearNoDataFromSourceMuteResources();
  182. if (this._checkForCameraIssues()) {
  183. this._fireNoDataFromSourceEvent();
  184. }
  185. };
  186. /**
  187. * Fires JitsiTrackEvents.NO_DATA_FROM_SOURCE and logs it to analytics and
  188. * callstats.
  189. */
  190. JitsiLocalTrack.prototype._fireNoDataFromSourceEvent = function() {
  191. this.eventEmitter.emit(JitsiTrackEvents.NO_DATA_FROM_SOURCE);
  192. const eventName = `${this.getType()}.no_data_from_source`;
  193. Statistics.analytics.sendEvent(eventName);
  194. const log = { name: eventName };
  195. if (this.isAudioTrack()) {
  196. log.isReceivingData = this._isReceivingData();
  197. }
  198. Statistics.sendLog(JSON.stringify(log));
  199. };
  200. /**
  201. * Sets real device ID by comparing track information with device information.
  202. * This is temporary solution until getConstraints() method will be implemented
  203. * in browsers.
  204. * @param {MediaDeviceInfo[]} devices - list of devices obtained from
  205. * enumerateDevices() call
  206. */
  207. JitsiLocalTrack.prototype._setRealDeviceIdFromDeviceList = function(devices) {
  208. const track = this.getTrack();
  209. // FIXME for temasys video track, label refers to id not the actual device
  210. const device
  211. = devices.find(
  212. d => d.kind === `${track.kind}input` && d.label === track.label);
  213. if (device) {
  214. this._realDeviceId = device.deviceId;
  215. }
  216. };
  217. /**
  218. * Sets the stream property of JitsiLocalTrack object and sets all stored
  219. * handlers to it.
  220. * @param {MediaStream} stream the new stream.
  221. */
  222. JitsiLocalTrack.prototype._setStream = function(stream) {
  223. JitsiTrack.prototype._setStream.call(this, stream);
  224. // Store the MSID for video mute/unmute purposes
  225. if (stream) {
  226. this.storedMSID = this.getMSID();
  227. logger.debug(`Setting new MSID: ${this.storedMSID} on ${this}`);
  228. } else {
  229. logger.debug(`Setting 'null' stream on ${this}`);
  230. }
  231. };
  232. /**
  233. * Mutes the track. Will reject the Promise if there is mute/unmute operation
  234. * in progress.
  235. * @returns {Promise}
  236. */
  237. JitsiLocalTrack.prototype.mute = function() {
  238. return createMuteUnmutePromise(this, true);
  239. };
  240. /**
  241. * Unmutes the track. Will reject the Promise if there is mute/unmute operation
  242. * in progress.
  243. * @returns {Promise}
  244. */
  245. JitsiLocalTrack.prototype.unmute = function() {
  246. return createMuteUnmutePromise(this, false);
  247. };
  248. /**
  249. * Creates Promise for mute/unmute operation.
  250. *
  251. * @param {JitsiLocalTrack} track - The track that will be muted/unmuted.
  252. * @param {boolean} mute - Whether to mute or unmute the track.
  253. * @returns {Promise}
  254. */
  255. function createMuteUnmutePromise(track, mute) {
  256. if (track.inMuteOrUnmuteProgress) {
  257. return Promise.reject(
  258. new JitsiTrackError(JitsiTrackErrors.TRACK_MUTE_UNMUTE_IN_PROGRESS)
  259. );
  260. }
  261. track.inMuteOrUnmuteProgress = true;
  262. return track._setMute(mute)
  263. .then(() => {
  264. track.inMuteOrUnmuteProgress = false;
  265. })
  266. .catch(status => {
  267. track.inMuteOrUnmuteProgress = false;
  268. throw status;
  269. });
  270. }
  271. /**
  272. * Mutes / unmutes the track.
  273. *
  274. * @param {boolean} mute - If true the track will be muted. Otherwise the track
  275. * will be unmuted.
  276. * @private
  277. * @returns {Promise}
  278. */
  279. JitsiLocalTrack.prototype._setMute = function(mute) {
  280. if (this.isMuted() === mute) {
  281. return Promise.resolve();
  282. }
  283. let promise = Promise.resolve();
  284. const self = this;
  285. this.dontFireRemoveEvent = false;
  286. // A function that will print info about muted status transition
  287. const logMuteInfo = () => logger.info(`Mute ${this}: ${mute}`);
  288. if (this.isAudioTrack()
  289. || this.videoType === VideoType.DESKTOP
  290. || !RTCBrowserType.doesVideoMuteByStreamRemove()) {
  291. logMuteInfo();
  292. if (this.track) {
  293. this.track.enabled = !mute;
  294. }
  295. } else if (mute) {
  296. this.dontFireRemoveEvent = true;
  297. promise = new Promise((resolve, reject) => {
  298. logMuteInfo();
  299. this._removeStreamFromConferenceAsMute(() => {
  300. // FIXME: Maybe here we should set the SRC for the containers
  301. // to something
  302. this._stopMediaStream();
  303. this._setStream(null);
  304. resolve();
  305. }, err => {
  306. reject(err);
  307. });
  308. });
  309. } else {
  310. logMuteInfo();
  311. // This path is only for camera.
  312. const streamOptions = {
  313. cameraDeviceId: this.getDeviceId(),
  314. devices: [ MediaType.VIDEO ],
  315. facingMode: this.getCameraFacingMode()
  316. };
  317. if (this.resolution) {
  318. streamOptions.resolution = this.resolution;
  319. }
  320. promise = RTCUtils.obtainAudioAndVideoPermissions(streamOptions)
  321. .then(streamsInfo => {
  322. const mediaType = self.getType();
  323. const streamInfo
  324. = streamsInfo.find(info => info.mediaType === mediaType);
  325. if (streamInfo) {
  326. self._setStream(streamInfo.stream);
  327. self.track = streamInfo.track;
  328. // This is not good when video type changes after
  329. // unmute, but let's not crash here
  330. if (self.videoType !== streamInfo.videoType) {
  331. logger.warn(
  332. `${this}: video type has changed after unmute!`,
  333. self.videoType, streamInfo.videoType);
  334. self.videoType = streamInfo.videoType;
  335. }
  336. } else {
  337. throw new JitsiTrackError(
  338. JitsiTrackErrors.TRACK_NO_STREAM_FOUND);
  339. }
  340. self.containers
  341. = self.containers.map(
  342. cont => RTCUtils.attachMediaStream(cont, self.stream));
  343. return self._addStreamToConferenceAsUnmute();
  344. });
  345. }
  346. return promise
  347. .then(() => this._sendMuteStatus(mute))
  348. .then(() => {
  349. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED, this);
  350. });
  351. };
  352. /**
  353. * Adds stream to conference and marks it as "unmute" operation.
  354. *
  355. * @private
  356. * @returns {Promise}
  357. */
  358. JitsiLocalTrack.prototype._addStreamToConferenceAsUnmute = function() {
  359. if (!this.conference) {
  360. return Promise.resolve();
  361. }
  362. // FIXME it would be good to not included conference as part of this process
  363. // Only TraceablePeerConnections to which the track is attached should care
  364. // about this action. The TPCs to which the track is not attached can sync
  365. // up when track is re-attached.
  366. // A problem with that is that the "modify sources" queue is part of
  367. // the JingleSessionPC and it would be excluded from the process. One
  368. // solution would be to extract class between TPC and JingleSessionPC which
  369. // would contain the queue and would notify the signaling layer when local
  370. // SSRCs are changed. This would help to separate XMPP from the RTC module.
  371. return new Promise((resolve, reject) => {
  372. this.conference._addLocalTrackAsUnmute(this)
  373. .then(resolve, error => reject(new Error(error)));
  374. });
  375. };
  376. /**
  377. * Removes stream from conference and marks it as "mute" operation.
  378. * @param {Function} successCallback will be called on success
  379. * @param {Function} errorCallback will be called on error
  380. * @private
  381. */
  382. JitsiLocalTrack.prototype._removeStreamFromConferenceAsMute
  383. = function(successCallback, errorCallback) {
  384. if (!this.conference) {
  385. successCallback();
  386. return;
  387. }
  388. this.conference._removeLocalTrackAsMute(this).then(
  389. successCallback,
  390. error => errorCallback(new Error(error)));
  391. };
  392. /**
  393. * Sends mute status for a track to conference if any.
  394. *
  395. * @param {boolean} mute - If track is muted.
  396. * @private
  397. * @returns {Promise}
  398. */
  399. JitsiLocalTrack.prototype._sendMuteStatus = function(mute) {
  400. if (!this.conference || !this.conference.room) {
  401. return Promise.resolve();
  402. }
  403. return new Promise(resolve => {
  404. this.conference.room[
  405. this.isAudioTrack()
  406. ? 'setAudioMute'
  407. : 'setVideoMute'](mute, resolve);
  408. });
  409. };
  410. /**
  411. * @inheritdoc
  412. *
  413. * Stops sending the media track. And removes it from the HTML.
  414. * NOTE: Works for local tracks only.
  415. *
  416. * @extends JitsiTrack#dispose
  417. * @returns {Promise}
  418. */
  419. JitsiLocalTrack.prototype.dispose = function() {
  420. const self = this;
  421. let promise = Promise.resolve();
  422. if (this.conference) {
  423. promise = this.conference.removeTrack(this);
  424. }
  425. if (this.stream) {
  426. this._stopMediaStream();
  427. this.detach();
  428. }
  429. RTCUtils.removeListener(RTCEvents.DEVICE_LIST_CHANGED,
  430. this._onDeviceListChanged);
  431. if (this._onAudioOutputDeviceChanged) {
  432. RTCUtils.removeListener(RTCEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  433. this._onAudioOutputDeviceChanged);
  434. }
  435. return promise
  436. .then(() => JitsiTrack.prototype.dispose.call(self) // super.dispose();
  437. );
  438. };
  439. /**
  440. * Returns <tt>true</tt> - if the stream is muted
  441. * and <tt>false</tt> otherwise.
  442. * @returns {boolean} <tt>true</tt> - if the stream is muted
  443. * and <tt>false</tt> otherwise.
  444. */
  445. JitsiLocalTrack.prototype.isMuted = function() {
  446. // this.stream will be null when we mute local video on Chrome
  447. if (!this.stream) {
  448. return true;
  449. }
  450. if (this.isVideoTrack() && !this.isActive()) {
  451. return true;
  452. }
  453. return !this.track || !this.track.enabled;
  454. };
  455. /**
  456. * Sets the JitsiConference object associated with the track. This is temp
  457. * solution.
  458. * @param conference the JitsiConference object
  459. */
  460. JitsiLocalTrack.prototype._setConference = function(conference) {
  461. this.conference = conference;
  462. // We want to keep up with postponed events which should have been fired
  463. // on "attach" call, but for local track we not always have the conference
  464. // before attaching. However this may result in duplicated events if they
  465. // have been triggered on "attach" already.
  466. for (let i = 0; i < this.containers.length; i++) {
  467. this._maybeFireTrackAttached(this.containers[i]);
  468. }
  469. };
  470. /**
  471. * Returns <tt>true</tt>.
  472. * @returns {boolean} <tt>true</tt>
  473. */
  474. JitsiLocalTrack.prototype.isLocal = function() {
  475. return true;
  476. };
  477. /**
  478. * Returns device id associated with track.
  479. * @returns {string}
  480. */
  481. JitsiLocalTrack.prototype.getDeviceId = function() {
  482. return this._realDeviceId || this.deviceId;
  483. };
  484. /**
  485. * Returns the participant id which owns the track.
  486. * @returns {string} the id of the participants. It corresponds to the Colibri
  487. * endpoint id/MUC nickname in case of Jitsi-meet.
  488. */
  489. JitsiLocalTrack.prototype.getParticipantId = function() {
  490. return this.conference && this.conference.myUserId();
  491. };
  492. /**
  493. * Sets the value of bytes sent statistic.
  494. * @param {TraceablePeerConnection} tpc the source of the "bytes sent" stat
  495. * @param {number} bytesSent the new value
  496. * NOTE: used only for audio tracks to detect audio issues.
  497. */
  498. JitsiLocalTrack.prototype._setByteSent = function(tpc, bytesSent) {
  499. this._bytesSent = bytesSent;
  500. const iceConnectionState = tpc.getConnectionState();
  501. if (this._testByteSent && iceConnectionState === 'connected') {
  502. setTimeout(() => {
  503. if (this._bytesSent <= 0) {
  504. logger.warn(`${this} 'bytes sent' <= 0: ${this._bytesSent}`);
  505. // we are not receiving anything from the microphone
  506. this._fireNoDataFromSourceEvent();
  507. }
  508. }, 3000);
  509. this._testByteSent = false;
  510. }
  511. };
  512. /**
  513. * Returns facing mode for video track from camera. For other cases (e.g. audio
  514. * track or 'desktop' video track) returns undefined.
  515. *
  516. * @returns {CameraFacingMode|undefined}
  517. */
  518. JitsiLocalTrack.prototype.getCameraFacingMode = function() {
  519. if (this.isVideoTrack() && this.videoType === VideoType.CAMERA) {
  520. // MediaStreamTrack#getSettings() is not implemented in many browsers,
  521. // so we need feature checking here. Progress on the respective
  522. // browser's implementation can be tracked at
  523. // https://bugs.chromium.org/p/webrtc/issues/detail?id=2481 for Chromium
  524. // and https://bugzilla.mozilla.org/show_bug.cgi?id=1213517 for Firefox.
  525. // Even if a browser implements getSettings() already, it might still
  526. // not return anything for 'facingMode'.
  527. let trackSettings;
  528. try {
  529. trackSettings = this.track.getSettings();
  530. } catch (e) {
  531. // XXX React-native-webrtc, for example, defines
  532. // MediaStreamTrack#getSettings() but the implementation throws a
  533. // "Not implemented" Error.
  534. }
  535. if (trackSettings && 'facingMode' in trackSettings) {
  536. return trackSettings.facingMode;
  537. }
  538. if (typeof this._facingMode !== 'undefined') {
  539. return this._facingMode;
  540. }
  541. // In most cases we are showing a webcam. So if we've gotten here, it
  542. // should be relatively safe to assume that we are probably showing
  543. // the user-facing camera.
  544. return CameraFacingMode.USER;
  545. }
  546. return undefined;
  547. };
  548. /**
  549. * Stops the associated MediaStream.
  550. */
  551. JitsiLocalTrack.prototype._stopMediaStream = function() {
  552. this.stopStreamInProgress = true;
  553. RTCUtils.stopMediaStream(this.stream);
  554. this.stopStreamInProgress = false;
  555. };
  556. /**
  557. * Switches the camera facing mode if the WebRTC implementation supports the
  558. * custom MediaStreamTrack._switchCamera method. Currently, the method in
  559. * question is implemented in react-native-webrtc only. When such a WebRTC
  560. * implementation is executing, the method is the preferred way to switch
  561. * between the front/user-facing and the back/environment-facing cameras because
  562. * it will likely be (as is the case of react-native-webrtc) noticeably faster
  563. * that creating a new MediaStreamTrack via a new getUserMedia call with the
  564. * switched facingMode constraint value. Moreover, the approach with a new
  565. * getUserMedia call may not even work: WebRTC on Android and iOS is either very
  566. * slow to open the camera a second time or plainly freezes attempting to do
  567. * that.
  568. */
  569. JitsiLocalTrack.prototype._switchCamera = function() {
  570. if (this.isVideoTrack()
  571. && this.videoType === VideoType.CAMERA
  572. && typeof this.track._switchCamera === 'function') {
  573. this.track._switchCamera();
  574. this._facingMode
  575. = this._facingMode === CameraFacingMode.ENVIRONMENT
  576. ? CameraFacingMode.USER
  577. : CameraFacingMode.ENVIRONMENT;
  578. }
  579. };
  580. /**
  581. * Detects camera issues on ended and mute events from MediaStreamTrack.
  582. * @returns {boolean} true if an issue is detected and false otherwise
  583. */
  584. JitsiLocalTrack.prototype._checkForCameraIssues = function() {
  585. if (!this.isVideoTrack() || this.stopStreamInProgress
  586. || this.videoType === VideoType.DESKTOP) {
  587. return false;
  588. }
  589. return !this._isReceivingData();
  590. };
  591. /**
  592. * Checks whether the attached MediaStream is receiving data from source or
  593. * not. If the stream property is null(because of mute or another reason) this
  594. * method will return false.
  595. * NOTE: This method doesn't indicate problem with the streams directly.
  596. * For example in case of video mute the method will return false or if the
  597. * user has disposed the track.
  598. * @returns {boolean} true if the stream is receiving data and false otherwise.
  599. */
  600. JitsiLocalTrack.prototype._isReceivingData = function() {
  601. if (!this.stream) {
  602. return false;
  603. }
  604. // In older version of the spec there is no muted property and
  605. // readyState can have value muted. In the latest versions
  606. // readyState can have values "live" and "ended" and there is
  607. // muted boolean property. If the stream is muted that means that
  608. // we aren't receiving any data from the source. We want to notify
  609. // the users for error if the stream is muted or ended on it's
  610. // creation.
  611. return this.stream.getTracks().some(track =>
  612. (!('readyState' in track) || track.readyState === 'live')
  613. && (!('muted' in track) || track.muted !== true));
  614. };
  615. /**
  616. * Creates a text representation of this local track instance.
  617. * @return {string}
  618. */
  619. JitsiLocalTrack.prototype.toString = function() {
  620. return `LocalTrack[${this.rtcId},${this.getType()}]`;
  621. };