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

JitsiLocalTrack.js 26KB

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