Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

JitsiLocalTrack.js 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  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 JitsiTrackError from "../../JitsiTrackError";
  6. import * as JitsiTrackErrors from "../../JitsiTrackErrors";
  7. import * as JitsiTrackEvents from "../../JitsiTrackEvents";
  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 = new Promise( (resolve, reject) => {
  189. this._removeStreamFromConferenceAsMute(() => {
  190. //FIXME: Maybe here we should set the SRC for the containers
  191. // to something
  192. RTCUtils.stopMediaStream(this.stream);
  193. this._setStream(null);
  194. resolve();
  195. }, (err) => {
  196. reject(err);
  197. });
  198. });
  199. } else {
  200. // This path is only for camera.
  201. var streamOptions = {
  202. cameraDeviceId: this.getDeviceId(),
  203. devices: [ MediaType.VIDEO ],
  204. facingMode: this.getCameraFacingMode(),
  205. resolution: this.resolution
  206. };
  207. promise = RTCUtils.obtainAudioAndVideoPermissions(streamOptions)
  208. .then(function (streamsInfo) {
  209. var mediaType = self.getType();
  210. var streamInfo = streamsInfo.find(function(info) {
  211. return info.mediaType === mediaType;
  212. });
  213. if(!streamInfo) {
  214. throw new JitsiTrackError(
  215. JitsiTrackErrors.TRACK_NO_STREAM_FOUND);
  216. }else {
  217. self._setStream(streamInfo.stream);
  218. self.track = streamInfo.track;
  219. // This is not good when video type changes after
  220. // unmute, but let's not crash here
  221. if (self.videoType !== streamInfo.videoType) {
  222. logger.warn(
  223. "Video type has changed after unmute!",
  224. self.videoType, streamInfo.videoType);
  225. self.videoType = streamInfo.videoType;
  226. }
  227. }
  228. self.containers = self.containers.map(function(cont) {
  229. return RTCUtils.attachMediaStream(cont, self.stream);
  230. });
  231. return self._addStreamToConferenceAsUnmute();
  232. });
  233. }
  234. }
  235. return promise
  236. .then(function() {
  237. return self._sendMuteStatus(mute);
  238. })
  239. .then(function() {
  240. self.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  241. });
  242. };
  243. /**
  244. * Adds stream to conference and marks it as "unmute" operation.
  245. *
  246. * @private
  247. * @returns {Promise}
  248. */
  249. JitsiLocalTrack.prototype._addStreamToConferenceAsUnmute = function () {
  250. if (!this.conference || !this.conference.room) {
  251. return Promise.resolve();
  252. }
  253. var self = this;
  254. return new Promise(function(resolve, reject) {
  255. self.conference.room.addStream(
  256. self.stream,
  257. resolve,
  258. reject,
  259. {
  260. mtype: self.type,
  261. type: "unmute",
  262. ssrc: self.ssrc,
  263. msid: self.getMSID()
  264. });
  265. });
  266. };
  267. /**
  268. * Removes stream from conference and marks it as "mute" operation.
  269. * @param {Function} successCallback will be called on success
  270. * @param {Function} errorCallback will be called on error
  271. * @private
  272. */
  273. JitsiLocalTrack.prototype._removeStreamFromConferenceAsMute =
  274. function (successCallback, errorCallback) {
  275. if (!this.conference || !this.conference.room) {
  276. successCallback();
  277. return;
  278. }
  279. this.conference.room.removeStream(
  280. this.stream,
  281. successCallback,
  282. errorCallback,
  283. {
  284. mtype: this.type,
  285. type: "mute",
  286. ssrc: this.ssrc
  287. });
  288. };
  289. /**
  290. * Sends mute status for a track to conference if any.
  291. *
  292. * @param {boolean} mute - If track is muted.
  293. * @private
  294. * @returns {Promise}
  295. */
  296. JitsiLocalTrack.prototype._sendMuteStatus = function(mute) {
  297. if (!this.conference || !this.conference.room) {
  298. return Promise.resolve();
  299. }
  300. var self = this;
  301. return new Promise(function(resolve) {
  302. self.conference.room[
  303. self.isAudioTrack()
  304. ? 'setAudioMute'
  305. : 'setVideoMute'](mute, resolve);
  306. });
  307. };
  308. /**
  309. * @inheritdoc
  310. *
  311. * Stops sending the media track. And removes it from the HTML.
  312. * NOTE: Works for local tracks only.
  313. *
  314. * @extends JitsiTrack#dispose
  315. * @returns {Promise}
  316. */
  317. JitsiLocalTrack.prototype.dispose = function () {
  318. var self = this;
  319. var promise = Promise.resolve();
  320. if (this.conference){
  321. promise = this.conference.removeTrack(this);
  322. }
  323. if (this.stream) {
  324. RTCUtils.stopMediaStream(this.stream);
  325. this.detach();
  326. }
  327. RTCUtils.removeListener(RTCEvents.DEVICE_LIST_CHANGED,
  328. this._onDeviceListChanged);
  329. if (this._onAudioOutputDeviceChanged) {
  330. RTCUtils.removeListener(RTCEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  331. this._onAudioOutputDeviceChanged);
  332. }
  333. return promise
  334. .then(function() {
  335. return JitsiTrack.prototype.dispose.call(self); // super.dispose();
  336. });
  337. };
  338. /**
  339. * Returns <tt>true</tt> - if the stream is muted
  340. * and <tt>false</tt> otherwise.
  341. * @returns {boolean} <tt>true</tt> - if the stream is muted
  342. * and <tt>false</tt> otherwise.
  343. */
  344. JitsiLocalTrack.prototype.isMuted = function () {
  345. // this.stream will be null when we mute local video on Chrome
  346. if (!this.stream)
  347. return true;
  348. if (this.isVideoTrack() && !this.isActive()) {
  349. return true;
  350. } else {
  351. return !this.track || !this.track.enabled;
  352. }
  353. };
  354. /**
  355. * Updates the SSRC associated with the MediaStream in JitsiLocalTrack object.
  356. * @ssrc the new ssrc
  357. */
  358. JitsiLocalTrack.prototype._setSSRC = function (ssrc) {
  359. this.ssrc = ssrc;
  360. };
  361. /**
  362. * Sets the JitsiConference object associated with the track. This is temp
  363. * solution.
  364. * @param conference the JitsiConference object
  365. */
  366. JitsiLocalTrack.prototype._setConference = function(conference) {
  367. this.conference = conference;
  368. // We want to keep up with postponed events which should have been fired
  369. // on "attach" call, but for local track we not always have the conference
  370. // before attaching. However this may result in duplicated events if they
  371. // have been triggered on "attach" already.
  372. for(var i = 0; i < this.containers.length; i++)
  373. {
  374. this._maybeFireTrackAttached(this.containers[i]);
  375. }
  376. };
  377. /**
  378. * Gets the SSRC of this local track if it's available already or <tt>null</tt>
  379. * otherwise. That's because we don't know the SSRC until local description is
  380. * created.
  381. * In case of video and simulcast returns the the primarySSRC.
  382. * @returns {string} or {null}
  383. */
  384. JitsiLocalTrack.prototype.getSSRC = function () {
  385. if(this.ssrc && this.ssrc.groups && this.ssrc.groups.length)
  386. return this.ssrc.groups[0].primarySSRC;
  387. else if(this.ssrc && this.ssrc.ssrcs && this.ssrc.ssrcs.length)
  388. return this.ssrc.ssrcs[0];
  389. else
  390. return null;
  391. };
  392. /**
  393. * Returns <tt>true</tt>.
  394. * @returns {boolean} <tt>true</tt>
  395. */
  396. JitsiLocalTrack.prototype.isLocal = function () {
  397. return true;
  398. };
  399. /**
  400. * Returns device id associated with track.
  401. * @returns {string}
  402. */
  403. JitsiLocalTrack.prototype.getDeviceId = function () {
  404. return this._realDeviceId || this.deviceId;
  405. };
  406. /**
  407. * Sets the value of bytes sent statistic.
  408. * @param bytesSent {intiger} the new value
  409. * NOTE: used only for audio tracks to detect audio issues.
  410. */
  411. JitsiLocalTrack.prototype._setByteSent = function (bytesSent) {
  412. this._bytesSent = bytesSent;
  413. if(this._testByteSent) {
  414. setTimeout(function () {
  415. if(this._bytesSent <= 0){
  416. //we are not receiving anything from the microphone
  417. this.eventEmitter.emit(JitsiTrackEvents.TRACK_AUDIO_NOT_WORKING);
  418. }
  419. }.bind(this), 3000);
  420. this._testByteSent = false;
  421. }
  422. }
  423. /**
  424. * Returns facing mode for video track from camera. For other cases (e.g. audio
  425. * track or 'desktop' video track) returns undefined.
  426. *
  427. * @returns {CameraFacingMode|undefined}
  428. */
  429. JitsiLocalTrack.prototype.getCameraFacingMode = function () {
  430. if (this.isVideoTrack() && this.videoType === VideoType.CAMERA) {
  431. // MediaStreamTrack#getSettings() is not implemented in many browsers,
  432. // so we need feature checking here. Progress on the respective
  433. // browser's implementation can be tracked at
  434. // https://bugs.chromium.org/p/webrtc/issues/detail?id=2481 for Chromium
  435. // and https://bugzilla.mozilla.org/show_bug.cgi?id=1213517 for Firefox.
  436. // Even if a browser implements getSettings() already, it might still
  437. // not return anything for 'facingMode'.
  438. var trackSettings;
  439. try {
  440. trackSettings = this.track.getSettings();
  441. } catch (e) {
  442. // XXX React-native-webrtc, for example, defines
  443. // MediaStreamTrack#getSettings() but the implementation throws a
  444. // "Not implemented" Error.
  445. }
  446. if (trackSettings && 'facingMode' in trackSettings) {
  447. return trackSettings.facingMode;
  448. }
  449. if (typeof this._facingMode !== 'undefined') {
  450. return this._facingMode;
  451. }
  452. // In most cases we are showing a webcam. So if we've gotten here, it
  453. // should be relatively safe to assume that we are probably showing
  454. // the user-facing camera.
  455. return CameraFacingMode.USER;
  456. }
  457. return undefined;
  458. };
  459. module.exports = JitsiLocalTrack;