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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. /* global __filename, Promise */
  2. var CameraFacingMode = require('../../service/RTC/CameraFacingMode');
  3. var JitsiTrack = require("./JitsiTrack");
  4. import JitsiTrackError from "../../JitsiTrackError";
  5. import * as JitsiTrackErrors from "../../JitsiTrackErrors";
  6. import * as JitsiTrackEvents from "../../JitsiTrackEvents";
  7. var logger = require("jitsi-meet-logger").getLogger(__filename);
  8. var MediaType = require('../../service/RTC/MediaType');
  9. var RTCBrowserType = require("./RTCBrowserType");
  10. var RTCEvents = require("../../service/RTC/RTCEvents");
  11. var RTCUtils = require("./RTCUtils");
  12. var Statistics = require("../statistics/statistics");
  13. var VideoType = require('../../service/RTC/VideoType');
  14. /**
  15. * Represents a single media track(either audio or video).
  16. * One <tt>JitsiLocalTrack</tt> corresponds to one WebRTC MediaStreamTrack.
  17. * @param stream WebRTC MediaStream, parent of the track
  18. * @param track underlying WebRTC MediaStreamTrack for new JitsiRemoteTrack
  19. * @param mediaType the MediaType of the JitsiRemoteTrack
  20. * @param videoType the VideoType of the JitsiRemoteTrack
  21. * @param resolution the video resoultion if it's a video track
  22. * @param deviceId the ID of the local device for this track
  23. * @param facingMode the camera facing mode used in getUserMedia call
  24. * @constructor
  25. */
  26. function JitsiLocalTrack(stream, track, mediaType, videoType, resolution,
  27. deviceId, facingMode) {
  28. var self = this;
  29. JitsiTrack.call(this,
  30. null /* RTC */, stream, track,
  31. function () {
  32. if(!this.dontFireRemoveEvent)
  33. this.eventEmitter.emit(
  34. JitsiTrackEvents.LOCAL_TRACK_STOPPED);
  35. this.dontFireRemoveEvent = false;
  36. }.bind(this) /* inactiveHandler */,
  37. mediaType, videoType, null /* ssrc */);
  38. this.dontFireRemoveEvent = false;
  39. this.resolution = resolution;
  40. this.deviceId = deviceId;
  41. this.startMuted = false;
  42. this.initialMSID = this.getMSID();
  43. this.inMuteOrUnmuteProgress = false;
  44. /**
  45. * The facing mode of the camera from which this JitsiLocalTrack instance
  46. * was obtained.
  47. */
  48. this._facingMode = facingMode;
  49. // Currently there is no way to know the MediaStreamTrack ended due to to
  50. // device disconnect in Firefox through e.g. "readyState" property. Instead
  51. // we will compare current track's label with device labels from
  52. // enumerateDevices() list.
  53. this._trackEnded = false;
  54. /**
  55. * The value of bytes sent received from the statistics module.
  56. */
  57. this._bytesSent = null;
  58. /**
  59. * Used only for detection of audio problems. We want to check only once
  60. * whether the track is sending bytes ot not. This flag is set to false
  61. * after the check.
  62. */
  63. this._testByteSent = true;
  64. // Currently there is no way to determine with what device track was
  65. // created (until getConstraints() support), however we can associate tracks
  66. // with real devices obtained from enumerateDevices() call as soon as it's
  67. // called.
  68. this._realDeviceId = this.deviceId === '' ? undefined : this.deviceId;
  69. /**
  70. * Indicates that we have called RTCUtils.stopMediaStream for the
  71. * MediaStream related to this JitsiTrack object.
  72. */
  73. this.stopStreamInProgress = false;
  74. /**
  75. * On mute event we are waiting for 3s to check if the stream is going to
  76. * be still muted before firing the event for camera issue detected
  77. * (NO_DATA_FROM_SOURCE).
  78. */
  79. this._noDataFromSourceTimeout = null;
  80. this._onDeviceListChanged = function (devices) {
  81. self._setRealDeviceIdFromDeviceList(devices);
  82. // Mark track as ended for those browsers that do not support
  83. // "readyState" property. We do not touch tracks created with default
  84. // device ID "".
  85. if (typeof self.getTrack().readyState === 'undefined'
  86. && typeof self._realDeviceId !== 'undefined'
  87. && !devices.find(function (d) {
  88. return d.deviceId === self._realDeviceId;
  89. })) {
  90. self._trackEnded = true;
  91. }
  92. };
  93. // Subscribe each created local audio track to
  94. // RTCEvents.AUDIO_OUTPUT_DEVICE_CHANGED event. This is different from
  95. // handling this event for remote tracks (which are handled in RTC.js),
  96. // because there might be local tracks not attached to a conference.
  97. if (this.isAudioTrack() && RTCUtils.isDeviceChangeAvailable('output')) {
  98. this._onAudioOutputDeviceChanged = this.setAudioOutput.bind(this);
  99. RTCUtils.addListener(RTCEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  100. this._onAudioOutputDeviceChanged);
  101. }
  102. RTCUtils.addListener(RTCEvents.DEVICE_LIST_CHANGED,
  103. this._onDeviceListChanged);
  104. this._initNoDataFromSourceHandlers();
  105. }
  106. JitsiLocalTrack.prototype = Object.create(JitsiTrack.prototype);
  107. JitsiLocalTrack.prototype.constructor = JitsiLocalTrack;
  108. /**
  109. * Returns if associated MediaStreamTrack is in the 'ended' state
  110. * @returns {boolean}
  111. */
  112. JitsiLocalTrack.prototype.isEnded = function () {
  113. return this.getTrack().readyState === 'ended' || this._trackEnded;
  114. };
  115. /**
  116. * Sets handlers to the MediaStreamTrack object that will detect camera issues.
  117. */
  118. JitsiLocalTrack.prototype._initNoDataFromSourceHandlers = function () {
  119. if(this.isVideoTrack() && this.videoType === VideoType.CAMERA) {
  120. let _onNoDataFromSourceError
  121. = this._onNoDataFromSourceError.bind(this);
  122. this._setHandler("track_mute", () => {
  123. if(this._checkForCameraIssues()) {
  124. let now = window.performance.now();
  125. this._noDataFromSourceTimeout
  126. = setTimeout(_onNoDataFromSourceError, 3000);
  127. this._setHandler("track_unmute", () => {
  128. this._clearNoDataFromSourceMuteResources();
  129. Statistics.sendEventToAll(
  130. this.getType() + ".track_unmute",
  131. window.performance.now() - now);
  132. });
  133. }
  134. });
  135. this._setHandler("track_ended", _onNoDataFromSourceError);
  136. }
  137. };
  138. /**
  139. * Clears all timeouts and handlers set on MediaStreamTrack mute event.
  140. * FIXME: Change the name of the method with better one.
  141. */
  142. JitsiLocalTrack.prototype._clearNoDataFromSourceMuteResources = function () {
  143. if(this._noDataFromSourceTimeout) {
  144. clearTimeout(this._noDataFromSourceTimeout);
  145. this._noDataFromSourceTimeout = null;
  146. }
  147. this._setHandler("track_unmute", undefined);
  148. };
  149. /**
  150. * Called when potential camera issue is detected. Clears the handlers and
  151. * timeouts set on MediaStreamTrack muted event. Verifies that the camera
  152. * issue persists and fires NO_DATA_FROM_SOURCE event.
  153. */
  154. JitsiLocalTrack.prototype._onNoDataFromSourceError = function () {
  155. this._clearNoDataFromSourceMuteResources();
  156. if(this._checkForCameraIssues())
  157. this._fireNoDataFromSourceEvent();
  158. };
  159. /**
  160. * Fires JitsiTrackEvents.NO_DATA_FROM_SOURCE and logs it to analytics and
  161. * callstats.
  162. */
  163. JitsiLocalTrack.prototype._fireNoDataFromSourceEvent = function () {
  164. this.eventEmitter.emit(JitsiTrackEvents.NO_DATA_FROM_SOURCE);
  165. Statistics.sendEventToAll(this.getType() + ".no_data_from_source");
  166. };
  167. /**
  168. * Sets real device ID by comparing track information with device information.
  169. * This is temporary solution until getConstraints() method will be implemented
  170. * in browsers.
  171. * @param {MediaDeviceInfo[]} devices - list of devices obtained from
  172. * enumerateDevices() call
  173. */
  174. JitsiLocalTrack.prototype._setRealDeviceIdFromDeviceList = function (devices) {
  175. var track = this.getTrack(),
  176. device = devices.find(function (d) {
  177. return d.kind === track.kind + 'input' && d.label === track.label;
  178. });
  179. if (device) {
  180. this._realDeviceId = device.deviceId;
  181. }
  182. };
  183. /**
  184. * Mutes the track. Will reject the Promise if there is mute/unmute operation
  185. * in progress.
  186. * @returns {Promise}
  187. */
  188. JitsiLocalTrack.prototype.mute = function () {
  189. return createMuteUnmutePromise(this, true);
  190. };
  191. /**
  192. * Unmutes the track. Will reject the Promise if there is mute/unmute operation
  193. * in progress.
  194. * @returns {Promise}
  195. */
  196. JitsiLocalTrack.prototype.unmute = function () {
  197. return createMuteUnmutePromise(this, false);
  198. };
  199. /**
  200. * Creates Promise for mute/unmute operation.
  201. *
  202. * @param {JitsiLocalTrack} track - The track that will be muted/unmuted.
  203. * @param {boolean} mute - Whether to mute or unmute the track.
  204. * @returns {Promise}
  205. */
  206. function createMuteUnmutePromise(track, mute) {
  207. if (track.inMuteOrUnmuteProgress) {
  208. return Promise.reject(
  209. new JitsiTrackError(JitsiTrackErrors.TRACK_MUTE_UNMUTE_IN_PROGRESS)
  210. );
  211. }
  212. track.inMuteOrUnmuteProgress = true;
  213. return track._setMute(mute)
  214. .then(function() {
  215. track.inMuteOrUnmuteProgress = false;
  216. })
  217. .catch(function(status) {
  218. track.inMuteOrUnmuteProgress = false;
  219. throw status;
  220. });
  221. }
  222. /**
  223. * Mutes / unmutes the track.
  224. *
  225. * @param {boolean} mute - If true the track will be muted. Otherwise the track
  226. * will be unmuted.
  227. * @private
  228. * @returns {Promise}
  229. */
  230. JitsiLocalTrack.prototype._setMute = function (mute) {
  231. if (this.isMuted() === mute) {
  232. return Promise.resolve();
  233. }
  234. var promise = Promise.resolve();
  235. var self = this;
  236. // Local track can be used out of conference, so we need to handle that
  237. // case and mark that track should start muted or not when added to
  238. // conference.
  239. if(!this.conference || !this.conference.room) {
  240. this.startMuted = mute;
  241. }
  242. this.dontFireRemoveEvent = false;
  243. // FIXME FF does not support 'removeStream' method used to mute
  244. if (window.location.protocol !== "https:" ||
  245. this.isAudioTrack() ||
  246. this.videoType === VideoType.DESKTOP ||
  247. RTCBrowserType.isFirefox()) {
  248. if(this.track)
  249. this.track.enabled = !mute;
  250. } else {
  251. if(mute) {
  252. this.dontFireRemoveEvent = true;
  253. promise = new Promise( (resolve, reject) => {
  254. this._removeStreamFromConferenceAsMute(() => {
  255. //FIXME: Maybe here we should set the SRC for the containers
  256. // to something
  257. this._stopMediaStream();
  258. this._setStream(null);
  259. resolve();
  260. }, (err) => {
  261. reject(err);
  262. });
  263. });
  264. } else {
  265. // This path is only for camera.
  266. var streamOptions = {
  267. cameraDeviceId: this.getDeviceId(),
  268. devices: [ MediaType.VIDEO ],
  269. facingMode: this.getCameraFacingMode(),
  270. resolution: this.resolution
  271. };
  272. promise = RTCUtils.obtainAudioAndVideoPermissions(streamOptions)
  273. .then(function (streamsInfo) {
  274. var mediaType = self.getType();
  275. var streamInfo = streamsInfo.find(function(info) {
  276. return info.mediaType === mediaType;
  277. });
  278. if(!streamInfo) {
  279. throw new JitsiTrackError(
  280. JitsiTrackErrors.TRACK_NO_STREAM_FOUND);
  281. }else {
  282. self._setStream(streamInfo.stream);
  283. self.track = streamInfo.track;
  284. // This is not good when video type changes after
  285. // unmute, but let's not crash here
  286. if (self.videoType !== streamInfo.videoType) {
  287. logger.warn(
  288. "Video type has changed after unmute!",
  289. self.videoType, streamInfo.videoType);
  290. self.videoType = streamInfo.videoType;
  291. }
  292. }
  293. self.containers = self.containers.map(function(cont) {
  294. return RTCUtils.attachMediaStream(cont, self.stream);
  295. });
  296. return self._addStreamToConferenceAsUnmute();
  297. });
  298. }
  299. }
  300. return promise
  301. .then(function() {
  302. return self._sendMuteStatus(mute);
  303. })
  304. .then(function() {
  305. self.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED, this);
  306. });
  307. };
  308. /**
  309. * Adds stream to conference and marks it as "unmute" operation.
  310. *
  311. * @private
  312. * @returns {Promise}
  313. */
  314. JitsiLocalTrack.prototype._addStreamToConferenceAsUnmute = function () {
  315. if (!this.conference || !this.conference.room) {
  316. return Promise.resolve();
  317. }
  318. var self = this;
  319. return new Promise(function(resolve, reject) {
  320. self.conference.room.addStream(
  321. self.stream,
  322. resolve,
  323. reject,
  324. {
  325. mtype: self.type,
  326. type: "unmute",
  327. ssrc: self.ssrc,
  328. msid: self.getMSID()
  329. });
  330. });
  331. };
  332. /**
  333. * Removes stream from conference and marks it as "mute" operation.
  334. * @param {Function} successCallback will be called on success
  335. * @param {Function} errorCallback will be called on error
  336. * @private
  337. */
  338. JitsiLocalTrack.prototype._removeStreamFromConferenceAsMute =
  339. function (successCallback, errorCallback) {
  340. if (!this.conference || !this.conference.room) {
  341. successCallback();
  342. return;
  343. }
  344. this.conference.room.removeStream(
  345. this.stream,
  346. successCallback,
  347. errorCallback,
  348. {
  349. mtype: this.type,
  350. type: "mute",
  351. ssrc: this.ssrc
  352. });
  353. };
  354. /**
  355. * Sends mute status for a track to conference if any.
  356. *
  357. * @param {boolean} mute - If track is muted.
  358. * @private
  359. * @returns {Promise}
  360. */
  361. JitsiLocalTrack.prototype._sendMuteStatus = function(mute) {
  362. if (!this.conference || !this.conference.room) {
  363. return Promise.resolve();
  364. }
  365. var self = this;
  366. return new Promise(function(resolve) {
  367. self.conference.room[
  368. self.isAudioTrack()
  369. ? 'setAudioMute'
  370. : 'setVideoMute'](mute, resolve);
  371. });
  372. };
  373. /**
  374. * @inheritdoc
  375. *
  376. * Stops sending the media track. And removes it from the HTML.
  377. * NOTE: Works for local tracks only.
  378. *
  379. * @extends JitsiTrack#dispose
  380. * @returns {Promise}
  381. */
  382. JitsiLocalTrack.prototype.dispose = function () {
  383. var self = this;
  384. var promise = Promise.resolve();
  385. if (this.conference){
  386. promise = this.conference.removeTrack(this);
  387. }
  388. if (this.stream) {
  389. this._stopMediaStream();
  390. this.detach();
  391. }
  392. RTCUtils.removeListener(RTCEvents.DEVICE_LIST_CHANGED,
  393. this._onDeviceListChanged);
  394. if (this._onAudioOutputDeviceChanged) {
  395. RTCUtils.removeListener(RTCEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  396. this._onAudioOutputDeviceChanged);
  397. }
  398. return promise
  399. .then(function() {
  400. return JitsiTrack.prototype.dispose.call(self); // super.dispose();
  401. });
  402. };
  403. /**
  404. * Returns <tt>true</tt> - if the stream is muted
  405. * and <tt>false</tt> otherwise.
  406. * @returns {boolean} <tt>true</tt> - if the stream is muted
  407. * and <tt>false</tt> otherwise.
  408. */
  409. JitsiLocalTrack.prototype.isMuted = function () {
  410. // this.stream will be null when we mute local video on Chrome
  411. if (!this.stream)
  412. return true;
  413. if (this.isVideoTrack() && !this.isActive()) {
  414. return true;
  415. } else {
  416. return !this.track || !this.track.enabled;
  417. }
  418. };
  419. /**
  420. * Updates the SSRC associated with the MediaStream in JitsiLocalTrack object.
  421. * @ssrc the new ssrc
  422. */
  423. JitsiLocalTrack.prototype._setSSRC = function (ssrc) {
  424. this.ssrc = ssrc;
  425. };
  426. /**
  427. * Sets the JitsiConference object associated with the track. This is temp
  428. * solution.
  429. * @param conference the JitsiConference object
  430. */
  431. JitsiLocalTrack.prototype._setConference = function(conference) {
  432. this.conference = conference;
  433. // We want to keep up with postponed events which should have been fired
  434. // on "attach" call, but for local track we not always have the conference
  435. // before attaching. However this may result in duplicated events if they
  436. // have been triggered on "attach" already.
  437. for(var i = 0; i < this.containers.length; i++)
  438. {
  439. this._maybeFireTrackAttached(this.containers[i]);
  440. }
  441. };
  442. /**
  443. * Gets the SSRC of this local track if it's available already or <tt>null</tt>
  444. * otherwise. That's because we don't know the SSRC until local description is
  445. * created.
  446. * In case of video and simulcast returns the the primarySSRC.
  447. * @returns {string} or {null}
  448. */
  449. JitsiLocalTrack.prototype.getSSRC = function () {
  450. if(this.ssrc && this.ssrc.groups && this.ssrc.groups.length)
  451. return this.ssrc.groups[0].primarySSRC;
  452. else if(this.ssrc && this.ssrc.ssrcs && this.ssrc.ssrcs.length)
  453. return this.ssrc.ssrcs[0];
  454. else
  455. return null;
  456. };
  457. /**
  458. * Returns <tt>true</tt>.
  459. * @returns {boolean} <tt>true</tt>
  460. */
  461. JitsiLocalTrack.prototype.isLocal = function () {
  462. return true;
  463. };
  464. /**
  465. * Returns device id associated with track.
  466. * @returns {string}
  467. */
  468. JitsiLocalTrack.prototype.getDeviceId = function () {
  469. return this._realDeviceId || this.deviceId;
  470. };
  471. /**
  472. * Sets the value of bytes sent statistic.
  473. * @param bytesSent {intiger} the new value
  474. * NOTE: used only for audio tracks to detect audio issues.
  475. */
  476. JitsiLocalTrack.prototype._setByteSent = function (bytesSent) {
  477. this._bytesSent = bytesSent;
  478. if(this._testByteSent) {
  479. setTimeout(function () {
  480. if(this._bytesSent <= 0){
  481. //we are not receiving anything from the microphone
  482. this._fireNoDataFromSourceEvent();
  483. }
  484. }.bind(this), 3000);
  485. this._testByteSent = false;
  486. }
  487. };
  488. /**
  489. * Returns facing mode for video track from camera. For other cases (e.g. audio
  490. * track or 'desktop' video track) returns undefined.
  491. *
  492. * @returns {CameraFacingMode|undefined}
  493. */
  494. JitsiLocalTrack.prototype.getCameraFacingMode = function () {
  495. if (this.isVideoTrack() && this.videoType === VideoType.CAMERA) {
  496. // MediaStreamTrack#getSettings() is not implemented in many browsers,
  497. // so we need feature checking here. Progress on the respective
  498. // browser's implementation can be tracked at
  499. // https://bugs.chromium.org/p/webrtc/issues/detail?id=2481 for Chromium
  500. // and https://bugzilla.mozilla.org/show_bug.cgi?id=1213517 for Firefox.
  501. // Even if a browser implements getSettings() already, it might still
  502. // not return anything for 'facingMode'.
  503. var trackSettings;
  504. try {
  505. trackSettings = this.track.getSettings();
  506. } catch (e) {
  507. // XXX React-native-webrtc, for example, defines
  508. // MediaStreamTrack#getSettings() but the implementation throws a
  509. // "Not implemented" Error.
  510. }
  511. if (trackSettings && 'facingMode' in trackSettings) {
  512. return trackSettings.facingMode;
  513. }
  514. if (typeof this._facingMode !== 'undefined') {
  515. return this._facingMode;
  516. }
  517. // In most cases we are showing a webcam. So if we've gotten here, it
  518. // should be relatively safe to assume that we are probably showing
  519. // the user-facing camera.
  520. return CameraFacingMode.USER;
  521. }
  522. return undefined;
  523. };
  524. /**
  525. * Stops the associated MediaStream.
  526. */
  527. JitsiLocalTrack.prototype._stopMediaStream = function () {
  528. this.stopStreamInProgress = true;
  529. RTCUtils.stopMediaStream(this.stream);
  530. this.stopStreamInProgress = false;
  531. };
  532. /**
  533. * Detects camera issues on ended and mute events from MediaStreamTrack.
  534. * @returns {boolean} true if an issue is detected and false otherwise
  535. */
  536. JitsiLocalTrack.prototype._checkForCameraIssues = function () {
  537. if(!this.isVideoTrack() || this.stopStreamInProgress ||
  538. this.videoType === VideoType.DESKTOP)
  539. return false;
  540. return !this._isReceivingData();
  541. };
  542. /**
  543. * Checks whether the attached MediaStream is reveiving data from source or
  544. * not. If the stream property is null(because of mute or another reason) this
  545. * method will return false.
  546. * NOTE: This method doesn't indicate problem with the streams directly.
  547. * For example in case of video mute the method will return false or if the
  548. * user has disposed the track.
  549. * @returns {boolean} true if the stream is receiving data and false otherwise.
  550. */
  551. JitsiLocalTrack.prototype._isReceivingData = function () {
  552. if(!this.stream)
  553. return false;
  554. // In older version of the spec there is no muted property and
  555. // readyState can have value muted. In the latest versions
  556. // readyState can have values "live" and "ended" and there is
  557. // muted boolean property. If the stream is muted that means that
  558. // we aren't receiving any data from the source. We want to notify
  559. // the users for error if the stream is muted or ended on it's
  560. // creation.
  561. return this.stream.getTracks().some(track =>
  562. ((!("readyState" in track) || track.readyState === "live")
  563. && (!("muted" in track) || track.muted === false)));
  564. };
  565. module.exports = JitsiLocalTrack;