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 26KB

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