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

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