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

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