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

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