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. 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. const device
  210. = devices.find(
  211. d => d.kind === `${track.kind}input` && d.label === track.label);
  212. if (device) {
  213. this._realDeviceId = device.deviceId;
  214. }
  215. };
  216. /**
  217. * Sets the stream property of JitsiLocalTrack object and sets all stored
  218. * handlers to it.
  219. * @param {MediaStream} stream the new stream.
  220. */
  221. JitsiLocalTrack.prototype._setStream = function(stream) {
  222. JitsiTrack.prototype._setStream.call(this, stream);
  223. // Store the MSID for video mute/unmute purposes
  224. if (stream) {
  225. this.storedMSID = this.getMSID();
  226. logger.debug(`Setting new MSID: ${this.storedMSID} on ${this}`);
  227. } else {
  228. logger.debug(`Setting 'null' stream on ${this}`);
  229. }
  230. };
  231. /**
  232. * Mutes the track. Will reject the Promise if there is mute/unmute operation
  233. * in progress.
  234. * @returns {Promise}
  235. */
  236. JitsiLocalTrack.prototype.mute = function() {
  237. return createMuteUnmutePromise(this, true);
  238. };
  239. /**
  240. * Unmutes the track. Will reject the Promise if there is mute/unmute operation
  241. * in progress.
  242. * @returns {Promise}
  243. */
  244. JitsiLocalTrack.prototype.unmute = function() {
  245. return createMuteUnmutePromise(this, false);
  246. };
  247. /**
  248. * Creates Promise for mute/unmute operation.
  249. *
  250. * @param {JitsiLocalTrack} track - The track that will be muted/unmuted.
  251. * @param {boolean} mute - Whether to mute or unmute the track.
  252. * @returns {Promise}
  253. */
  254. function createMuteUnmutePromise(track, mute) {
  255. if (track.inMuteOrUnmuteProgress) {
  256. return Promise.reject(
  257. new JitsiTrackError(JitsiTrackErrors.TRACK_MUTE_UNMUTE_IN_PROGRESS)
  258. );
  259. }
  260. track.inMuteOrUnmuteProgress = true;
  261. return track._setMute(mute)
  262. .then(() => {
  263. track.inMuteOrUnmuteProgress = false;
  264. })
  265. .catch(status => {
  266. track.inMuteOrUnmuteProgress = false;
  267. throw status;
  268. });
  269. }
  270. /**
  271. * Mutes / unmutes the track.
  272. *
  273. * @param {boolean} mute - If true the track will be muted. Otherwise the track
  274. * will be unmuted.
  275. * @private
  276. * @returns {Promise}
  277. */
  278. JitsiLocalTrack.prototype._setMute = function(mute) {
  279. if (this.isMuted() === mute) {
  280. return Promise.resolve();
  281. }
  282. let promise = Promise.resolve();
  283. const self = this;
  284. this.dontFireRemoveEvent = false;
  285. // A function that will print info about muted status transition
  286. const logMuteInfo = () => logger.info(`Mute ${this}: ${mute}`);
  287. if (this.isAudioTrack()
  288. || this.videoType === VideoType.DESKTOP
  289. || !RTCBrowserType.doesVideoMuteByStreamRemove()) {
  290. logMuteInfo();
  291. if (this.track) {
  292. this.track.enabled = !mute;
  293. }
  294. } else if (mute) {
  295. this.dontFireRemoveEvent = true;
  296. promise = new Promise((resolve, reject) => {
  297. logMuteInfo();
  298. this._removeStreamFromConferenceAsMute(() => {
  299. // FIXME: Maybe here we should set the SRC for the containers
  300. // to something
  301. this._stopMediaStream();
  302. this._setStream(null);
  303. resolve();
  304. }, err => {
  305. reject(err);
  306. });
  307. });
  308. } else {
  309. logMuteInfo();
  310. // This path is only for camera.
  311. const streamOptions = {
  312. cameraDeviceId: this.getDeviceId(),
  313. devices: [ MediaType.VIDEO ],
  314. facingMode: this.getCameraFacingMode()
  315. };
  316. if (this.resolution) {
  317. streamOptions.resolution = this.resolution;
  318. }
  319. promise = RTCUtils.obtainAudioAndVideoPermissions(streamOptions)
  320. .then(streamsInfo => {
  321. const mediaType = self.getType();
  322. const streamInfo
  323. = streamsInfo.find(info => info.mediaType === mediaType);
  324. if (streamInfo) {
  325. self._setStream(streamInfo.stream);
  326. self.track = streamInfo.track;
  327. // This is not good when video type changes after
  328. // unmute, but let's not crash here
  329. if (self.videoType !== streamInfo.videoType) {
  330. logger.warn(
  331. `${this}: video type has changed after unmute!`,
  332. self.videoType, streamInfo.videoType);
  333. self.videoType = streamInfo.videoType;
  334. }
  335. } else {
  336. throw new JitsiTrackError(
  337. JitsiTrackErrors.TRACK_NO_STREAM_FOUND);
  338. }
  339. self.containers
  340. = self.containers.map(
  341. cont => RTCUtils.attachMediaStream(cont, self.stream));
  342. return self._addStreamToConferenceAsUnmute();
  343. });
  344. }
  345. return promise
  346. .then(() => this._sendMuteStatus(mute))
  347. .then(() => {
  348. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED, this);
  349. });
  350. };
  351. /**
  352. * Adds stream to conference and marks it as "unmute" operation.
  353. *
  354. * @private
  355. * @returns {Promise}
  356. */
  357. JitsiLocalTrack.prototype._addStreamToConferenceAsUnmute = function() {
  358. if (!this.conference) {
  359. return Promise.resolve();
  360. }
  361. // FIXME it would be good to not included conference as part of this process
  362. // Only TraceablePeerConnections to which the track is attached should care
  363. // about this action. The TPCs to which the track is not attached can sync
  364. // up when track is re-attached.
  365. // A problem with that is that the "modify sources" queue is part of
  366. // the JingleSessionPC and it would be excluded from the process. One
  367. // solution would be to extract class between TPC and JingleSessionPC which
  368. // would contain the queue and would notify the signaling layer when local
  369. // SSRCs are changed. This would help to separate XMPP from the RTC module.
  370. return new Promise((resolve, reject) => {
  371. this.conference._addLocalTrackAsUnmute(this)
  372. .then(resolve, error => reject(new Error(error)));
  373. });
  374. };
  375. /**
  376. * Removes stream from conference and marks it as "mute" operation.
  377. * @param {Function} successCallback will be called on success
  378. * @param {Function} errorCallback will be called on error
  379. * @private
  380. */
  381. JitsiLocalTrack.prototype._removeStreamFromConferenceAsMute
  382. = function(successCallback, errorCallback) {
  383. if (!this.conference) {
  384. successCallback();
  385. return;
  386. }
  387. this.conference._removeLocalTrackAsMute(this).then(
  388. successCallback,
  389. error => errorCallback(new Error(error)));
  390. };
  391. /**
  392. * Sends mute status for a track to conference if any.
  393. *
  394. * @param {boolean} mute - If track is muted.
  395. * @private
  396. * @returns {Promise}
  397. */
  398. JitsiLocalTrack.prototype._sendMuteStatus = function(mute) {
  399. if (!this.conference || !this.conference.room) {
  400. return Promise.resolve();
  401. }
  402. return new Promise(resolve => {
  403. this.conference.room[
  404. this.isAudioTrack()
  405. ? 'setAudioMute'
  406. : 'setVideoMute'](mute, resolve);
  407. });
  408. };
  409. /**
  410. * @inheritdoc
  411. *
  412. * Stops sending the media track. And removes it from the HTML.
  413. * NOTE: Works for local tracks only.
  414. *
  415. * @extends JitsiTrack#dispose
  416. * @returns {Promise}
  417. */
  418. JitsiLocalTrack.prototype.dispose = function() {
  419. const self = this;
  420. let promise = Promise.resolve();
  421. if (this.conference) {
  422. promise = this.conference.removeTrack(this);
  423. }
  424. if (this.stream) {
  425. this._stopMediaStream();
  426. this.detach();
  427. }
  428. RTCUtils.removeListener(RTCEvents.DEVICE_LIST_CHANGED,
  429. this._onDeviceListChanged);
  430. if (this._onAudioOutputDeviceChanged) {
  431. RTCUtils.removeListener(RTCEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  432. this._onAudioOutputDeviceChanged);
  433. }
  434. return promise
  435. .then(() => JitsiTrack.prototype.dispose.call(self) // super.dispose();
  436. );
  437. };
  438. /**
  439. * Returns <tt>true</tt> - if the stream is muted
  440. * and <tt>false</tt> otherwise.
  441. * @returns {boolean} <tt>true</tt> - if the stream is muted
  442. * and <tt>false</tt> otherwise.
  443. */
  444. JitsiLocalTrack.prototype.isMuted = function() {
  445. // this.stream will be null when we mute local video on Chrome
  446. if (!this.stream) {
  447. return true;
  448. }
  449. if (this.isVideoTrack() && !this.isActive()) {
  450. return true;
  451. }
  452. return !this.track || !this.track.enabled;
  453. };
  454. /**
  455. * Sets the JitsiConference object associated with the track. This is temp
  456. * solution.
  457. * @param conference the JitsiConference object
  458. */
  459. JitsiLocalTrack.prototype._setConference = function(conference) {
  460. this.conference = conference;
  461. // We want to keep up with postponed events which should have been fired
  462. // on "attach" call, but for local track we not always have the conference
  463. // before attaching. However this may result in duplicated events if they
  464. // have been triggered on "attach" already.
  465. for (let i = 0; i < this.containers.length; i++) {
  466. this._maybeFireTrackAttached(this.containers[i]);
  467. }
  468. };
  469. /**
  470. * Returns <tt>true</tt>.
  471. * @returns {boolean} <tt>true</tt>
  472. */
  473. JitsiLocalTrack.prototype.isLocal = function() {
  474. return true;
  475. };
  476. /**
  477. * Returns device id associated with track.
  478. * @returns {string}
  479. */
  480. JitsiLocalTrack.prototype.getDeviceId = function() {
  481. return this._realDeviceId || this.deviceId;
  482. };
  483. /**
  484. * Returns the participant id which owns the track.
  485. * @returns {string} the id of the participants. It corresponds to the Colibri
  486. * endpoint id/MUC nickname in case of Jitsi-meet.
  487. */
  488. JitsiLocalTrack.prototype.getParticipantId = function() {
  489. return this.conference && this.conference.myUserId();
  490. };
  491. /**
  492. * Sets the value of bytes sent statistic.
  493. * @param {TraceablePeerConnection} tpc the source of the "bytes sent" stat
  494. * @param {number} bytesSent the new value
  495. * NOTE: used only for audio tracks to detect audio issues.
  496. */
  497. JitsiLocalTrack.prototype._setByteSent = function(tpc, bytesSent) {
  498. this._bytesSent = bytesSent;
  499. const iceConnectionState = tpc.getConnectionState();
  500. if (this._testByteSent && iceConnectionState === 'connected') {
  501. setTimeout(() => {
  502. if (this._bytesSent <= 0) {
  503. logger.warn(`${this} 'bytes sent' <= 0: ${this._bytesSent}`);
  504. // we are not receiving anything from the microphone
  505. this._fireNoDataFromSourceEvent();
  506. }
  507. }, 3000);
  508. this._testByteSent = false;
  509. }
  510. };
  511. /**
  512. * Returns facing mode for video track from camera. For other cases (e.g. audio
  513. * track or 'desktop' video track) returns undefined.
  514. *
  515. * @returns {CameraFacingMode|undefined}
  516. */
  517. JitsiLocalTrack.prototype.getCameraFacingMode = function() {
  518. if (this.isVideoTrack() && this.videoType === VideoType.CAMERA) {
  519. // MediaStreamTrack#getSettings() is not implemented in many browsers,
  520. // so we need feature checking here. Progress on the respective
  521. // browser's implementation can be tracked at
  522. // https://bugs.chromium.org/p/webrtc/issues/detail?id=2481 for Chromium
  523. // and https://bugzilla.mozilla.org/show_bug.cgi?id=1213517 for Firefox.
  524. // Even if a browser implements getSettings() already, it might still
  525. // not return anything for 'facingMode'.
  526. let trackSettings;
  527. try {
  528. trackSettings = this.track.getSettings();
  529. } catch (e) {
  530. // XXX React-native-webrtc, for example, defines
  531. // MediaStreamTrack#getSettings() but the implementation throws a
  532. // "Not implemented" Error.
  533. }
  534. if (trackSettings && 'facingMode' in trackSettings) {
  535. return trackSettings.facingMode;
  536. }
  537. if (typeof this._facingMode !== 'undefined') {
  538. return this._facingMode;
  539. }
  540. // In most cases we are showing a webcam. So if we've gotten here, it
  541. // should be relatively safe to assume that we are probably showing
  542. // the user-facing camera.
  543. return CameraFacingMode.USER;
  544. }
  545. return undefined;
  546. };
  547. /**
  548. * Stops the associated MediaStream.
  549. */
  550. JitsiLocalTrack.prototype._stopMediaStream = function() {
  551. this.stopStreamInProgress = true;
  552. RTCUtils.stopMediaStream(this.stream);
  553. this.stopStreamInProgress = false;
  554. };
  555. /**
  556. * Switches the camera facing mode if the WebRTC implementation supports the
  557. * custom MediaStreamTrack._switchCamera method. Currently, the method in
  558. * question is implemented in react-native-webrtc only. When such a WebRTC
  559. * implementation is executing, the method is the preferred way to switch
  560. * between the front/user-facing and the back/environment-facing cameras because
  561. * it will likely be (as is the case of react-native-webrtc) noticeably faster
  562. * that creating a new MediaStreamTrack via a new getUserMedia call with the
  563. * switched facingMode constraint value. Moreover, the approach with a new
  564. * getUserMedia call may not even work: WebRTC on Android and iOS is either very
  565. * slow to open the camera a second time or plainly freezes attempting to do
  566. * that.
  567. */
  568. JitsiLocalTrack.prototype._switchCamera = function() {
  569. if (this.isVideoTrack()
  570. && this.videoType === VideoType.CAMERA
  571. && typeof this.track._switchCamera === 'function') {
  572. this.track._switchCamera();
  573. this._facingMode
  574. = this._facingMode === CameraFacingMode.ENVIRONMENT
  575. ? CameraFacingMode.USER
  576. : CameraFacingMode.ENVIRONMENT;
  577. }
  578. };
  579. /**
  580. * Detects camera issues on ended and mute events from MediaStreamTrack.
  581. * @returns {boolean} true if an issue is detected and false otherwise
  582. */
  583. JitsiLocalTrack.prototype._checkForCameraIssues = function() {
  584. if (!this.isVideoTrack() || this.stopStreamInProgress
  585. || this.videoType === VideoType.DESKTOP) {
  586. return false;
  587. }
  588. return !this._isReceivingData();
  589. };
  590. /**
  591. * Checks whether the attached MediaStream is receiving data from source or
  592. * not. If the stream property is null(because of mute or another reason) this
  593. * method will return false.
  594. * NOTE: This method doesn't indicate problem with the streams directly.
  595. * For example in case of video mute the method will return false or if the
  596. * user has disposed the track.
  597. * @returns {boolean} true if the stream is receiving data and false otherwise.
  598. */
  599. JitsiLocalTrack.prototype._isReceivingData = function() {
  600. if (!this.stream) {
  601. return false;
  602. }
  603. // In older version of the spec there is no muted property and
  604. // readyState can have value muted. In the latest versions
  605. // readyState can have values "live" and "ended" and there is
  606. // muted boolean property. If the stream is muted that means that
  607. // we aren't receiving any data from the source. We want to notify
  608. // the users for error if the stream is muted or ended on it's
  609. // creation.
  610. return this.stream.getTracks().some(track =>
  611. (!('readyState' in track) || track.readyState === 'live')
  612. && (!('muted' in track) || track.muted !== true));
  613. };
  614. /**
  615. * Creates a text representation of this local track instance.
  616. * @return {string}
  617. */
  618. JitsiLocalTrack.prototype.toString = function() {
  619. return `LocalTrack[${this.rtcId},${this.getType()}]`;
  620. };
  621. module.exports = JitsiLocalTrack;