選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

JitsiLocalTrack.js 20KB

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