Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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