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

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