Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

JitsiLocalTrack.js 25KB

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