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

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