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.

JitsiTrack.js 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. /* global __filename, module */
  2. import { getLogger } from '@jitsi/logger';
  3. import EventEmitter from 'events';
  4. import * as JitsiTrackEvents from '../../JitsiTrackEvents';
  5. import * as MediaType from '../../service/RTC/MediaType';
  6. import browser from '../browser';
  7. import RTCUtils from './RTCUtils';
  8. const logger = getLogger(__filename);
  9. /**
  10. * Maps our handler types to MediaStreamTrack properties.
  11. */
  12. const trackHandler2Prop = {
  13. 'track_mute': 'onmute', // Not supported on FF
  14. 'track_unmute': 'onunmute',
  15. 'track_ended': 'onended'
  16. };
  17. /**
  18. * Represents a single media track (either audio or video).
  19. */
  20. export default class JitsiTrack extends EventEmitter {
  21. /* eslint-disable max-params */
  22. /**
  23. * Represents a single media track (either audio or video).
  24. * @constructor
  25. * @param conference the rtc instance
  26. * @param stream the WebRTC MediaStream instance
  27. * @param track the WebRTC MediaStreamTrack instance, must be part of
  28. * the given <tt>stream</tt>.
  29. * @param streamInactiveHandler the function that will handle
  30. * onended/oninactive events of the stream.
  31. * @param trackMediaType the media type of the JitsiTrack
  32. * @param videoType the VideoType for this track if any
  33. */
  34. constructor(
  35. conference,
  36. stream,
  37. track,
  38. streamInactiveHandler,
  39. trackMediaType,
  40. videoType) {
  41. super();
  42. // aliases for addListener/removeListener
  43. this.addEventListener = this.addListener;
  44. this.removeEventListener = this.off = this.removeListener;
  45. /**
  46. * Array with the HTML elements that are displaying the streams.
  47. * @type {Array}
  48. */
  49. this.containers = [];
  50. this.conference = conference;
  51. this.audioLevel = -1;
  52. this.type = trackMediaType;
  53. this.track = track;
  54. this.videoType = videoType;
  55. this.handlers = new Map();
  56. /**
  57. * Indicates whether this JitsiTrack has been disposed. If true, this
  58. * JitsiTrack is to be considered unusable and operations involving it
  59. * are to fail (e.g. {@link JitsiConference#addTrack(JitsiTrack)},
  60. * {@link JitsiConference#removeTrack(JitsiTrack)}).
  61. * @type {boolean}
  62. */
  63. this.disposed = false;
  64. /**
  65. * The inactive handler which will be triggered when the underlying
  66. * <tt>MediaStream</tt> ends.
  67. *
  68. * @private
  69. * @type {Function}
  70. */
  71. this._streamInactiveHandler = streamInactiveHandler;
  72. this._setStream(stream);
  73. }
  74. /* eslint-enable max-params */
  75. /**
  76. * Adds onended/oninactive handler to a MediaStream or a MediaStreamTrack.
  77. * Firefox doesn't fire a inactive event on the MediaStream, instead it fires
  78. * a onended event on the MediaStreamTrack.
  79. * @param {Function} handler the handler
  80. */
  81. _addMediaStreamInactiveHandler(handler) {
  82. if (browser.isFirefox()) {
  83. this.track.onended = handler;
  84. } else {
  85. this.stream.oninactive = handler;
  86. }
  87. }
  88. /**
  89. * Sets handler to the WebRTC MediaStream or MediaStreamTrack object
  90. * depending on the passed type.
  91. * @param {string} type the type of the handler that is going to be set
  92. * @param {Function} handler the handler.
  93. */
  94. _setHandler(type, handler) {
  95. if (!trackHandler2Prop.hasOwnProperty(type)) {
  96. logger.error(`Invalid handler type ${type}`);
  97. return;
  98. }
  99. if (handler) {
  100. this.handlers.set(type, handler);
  101. } else {
  102. this.handlers.delete(type);
  103. }
  104. if (this.stream) {
  105. for (const track of this.stream.getTracks()) {
  106. track[trackHandler2Prop[type]] = handler;
  107. }
  108. }
  109. }
  110. /**
  111. * Unregisters all event handlers bound to the underlying media stream/track
  112. * @private
  113. */
  114. _unregisterHandlers() {
  115. if (!this.stream) {
  116. logger.warn(
  117. `${this}: unable to unregister handlers - no stream object`);
  118. return;
  119. }
  120. for (const type of this.handlers.keys()) {
  121. // FIXME Why only video tracks?
  122. for (const videoTrack of this.stream.getVideoTracks()) {
  123. videoTrack[trackHandler2Prop[type]] = undefined;
  124. }
  125. }
  126. if (this._streamInactiveHandler) {
  127. this._addMediaStreamInactiveHandler(undefined);
  128. }
  129. }
  130. /**
  131. * Sets the stream property of JitsiTrack object and sets all stored
  132. * handlers to it.
  133. *
  134. * @param {MediaStream} stream the new stream.
  135. * @protected
  136. */
  137. _setStream(stream) {
  138. if (this.stream === stream) {
  139. return;
  140. }
  141. this.stream = stream;
  142. // TODO Practically, that's like the opposite of _unregisterHandlers
  143. // i.e. may be abstracted into a function/method called
  144. // _registerHandlers for clarity and easing the maintenance of the two
  145. // pieces of source code.
  146. if (this.stream) {
  147. for (const type of this.handlers.keys()) {
  148. this._setHandler(type, this.handlers.get(type));
  149. }
  150. if (this._streamInactiveHandler) {
  151. this._addMediaStreamInactiveHandler(this._streamInactiveHandler);
  152. }
  153. }
  154. }
  155. /**
  156. * Returns the video type (camera or desktop) of this track.
  157. */
  158. getVideoType() {
  159. return this.videoType;
  160. }
  161. /**
  162. * Returns the type (audio or video) of this track.
  163. */
  164. getType() {
  165. return this.type;
  166. }
  167. /**
  168. * Check if this is an audio track.
  169. */
  170. isAudioTrack() {
  171. return this.getType() === MediaType.AUDIO;
  172. }
  173. /**
  174. * Checks whether the underlying WebRTC <tt>MediaStreamTrack</tt> is muted
  175. * according to it's 'muted' field status.
  176. * @return {boolean} <tt>true</tt> if the underlying
  177. * <tt>MediaStreamTrack</tt> is muted or <tt>false</tt> otherwise.
  178. */
  179. isWebRTCTrackMuted() {
  180. return this.track && this.track.muted;
  181. }
  182. /**
  183. * Check if this is a video track.
  184. */
  185. isVideoTrack() {
  186. return this.getType() === MediaType.VIDEO;
  187. }
  188. /**
  189. * Checks whether this is a local track.
  190. * @abstract
  191. * @return {boolean} 'true' if it's a local track or 'false' otherwise.
  192. */
  193. isLocal() {
  194. throw new Error('Not implemented by subclass');
  195. }
  196. /**
  197. * Check whether this is a local audio track.
  198. *
  199. * @return {boolean} - true if track represents a local audio track, false otherwise.
  200. */
  201. isLocalAudioTrack() {
  202. return this.isAudioTrack() && this.isLocal();
  203. }
  204. /**
  205. * Returns the WebRTC MediaStream instance.
  206. */
  207. getOriginalStream() {
  208. return this.stream;
  209. }
  210. /**
  211. * Returns the ID of the underlying WebRTC Media Stream(if any)
  212. * @returns {String|null}
  213. */
  214. getStreamId() {
  215. return this.stream ? this.stream.id : null;
  216. }
  217. /**
  218. * Return the underlying WebRTC MediaStreamTrack
  219. * @returns {MediaStreamTrack}
  220. */
  221. getTrack() {
  222. return this.track;
  223. }
  224. /**
  225. * Return the underlying WebRTC MediaStreamTrack label
  226. * @returns {string}
  227. */
  228. getTrackLabel() {
  229. return this.track.label;
  230. }
  231. /**
  232. * Returns the ID of the underlying WebRTC MediaStreamTrack(if any)
  233. * @returns {String|null}
  234. */
  235. getTrackId() {
  236. return this.track ? this.track.id : null;
  237. }
  238. /**
  239. * Return meaningful usage label for this track depending on it's media and
  240. * eventual video type.
  241. * @returns {string}
  242. */
  243. getUsageLabel() {
  244. if (this.isAudioTrack()) {
  245. return 'mic';
  246. }
  247. return this.videoType ? this.videoType : 'default';
  248. }
  249. /**
  250. * Eventually will trigger RTCEvents.TRACK_ATTACHED event.
  251. * @param container the video/audio container to which this stream is
  252. * attached and for which event will be fired.
  253. * @private
  254. */
  255. _maybeFireTrackAttached(container) {
  256. if (this.conference && container) {
  257. this.conference._onTrackAttach(this, container);
  258. }
  259. }
  260. /**
  261. * Attaches the MediaStream of this track to an HTML container.
  262. * Adds the container to the list of containers that are displaying the
  263. * track.
  264. *
  265. * @param container the HTML container which can be 'video' or 'audio'
  266. * element.
  267. *
  268. * @returns {void}
  269. */
  270. attach(container) {
  271. if (this.stream) {
  272. this._onTrackAttach(container);
  273. RTCUtils.attachMediaStream(container, this.stream);
  274. }
  275. this.containers.push(container);
  276. this._maybeFireTrackAttached(container);
  277. this._attachTTFMTracker(container);
  278. }
  279. /**
  280. * Removes this JitsiTrack from the passed HTML container.
  281. *
  282. * @param container the HTML container to detach from this JitsiTrack. If
  283. * <tt>null</tt> or <tt>undefined</tt>, all containers are removed. A
  284. * container can be a 'video', 'audio' or 'object' HTML element instance to
  285. * which this JitsiTrack is currently attached.
  286. */
  287. detach(container) {
  288. for (let cs = this.containers, i = cs.length - 1; i >= 0; --i) {
  289. const c = cs[i];
  290. if (!container) {
  291. this._onTrackDetach(c);
  292. RTCUtils.attachMediaStream(c, null);
  293. }
  294. if (!container || c === container) {
  295. cs.splice(i, 1);
  296. }
  297. }
  298. if (container) {
  299. this._onTrackDetach(container);
  300. RTCUtils.attachMediaStream(container, null);
  301. }
  302. }
  303. /**
  304. * Called when the track has been attached to a new container.
  305. *
  306. * @param {HTMLElement} container the HTML container which can be 'video' or
  307. * 'audio' element.
  308. * @private
  309. */
  310. _onTrackAttach(container) { // eslint-disable-line no-unused-vars
  311. // Should be defined by the classes that are extending JitsiTrack
  312. }
  313. /**
  314. * Called when the track has been detached from a container.
  315. *
  316. * @param {HTMLElement} container the HTML container which can be 'video' or
  317. * 'audio' element.
  318. * @private
  319. */
  320. _onTrackDetach(container) { // eslint-disable-line no-unused-vars
  321. // Should be defined by the classes that are extending JitsiTrack
  322. }
  323. /**
  324. * Attach time to first media tracker only if there is conference and only
  325. * for the first element.
  326. *
  327. * @param {HTMLElement} container the HTML container which can be 'video' or
  328. * 'audio' element.
  329. * @private
  330. */
  331. _attachTTFMTracker(container) { // eslint-disable-line no-unused-vars
  332. // Should be defined by the classes that are extending JitsiTrack
  333. }
  334. /**
  335. * Removes attached event listeners.
  336. *
  337. * @returns {Promise}
  338. */
  339. dispose() {
  340. this.removeAllListeners();
  341. this.disposed = true;
  342. return Promise.resolve();
  343. }
  344. /**
  345. * Returns true if this is a video track and the source of the video is a
  346. * screen capture as opposed to a camera.
  347. */
  348. isScreenSharing() {
  349. // FIXME: Should be fixed or removed.
  350. }
  351. /**
  352. * Returns id of the track.
  353. * @returns {string|null} id of the track or null if this is fake track.
  354. */
  355. getId() {
  356. if (this.stream) {
  357. return RTCUtils.getStreamID(this.stream);
  358. }
  359. return null;
  360. }
  361. /**
  362. * Checks whether the MediaStream is active/not ended.
  363. * When there is no check for active we don't have information and so
  364. * will return that stream is active (in case of FF).
  365. * @returns {boolean} whether MediaStream is active.
  366. */
  367. isActive() {
  368. if (typeof this.stream.active !== 'undefined') {
  369. return this.stream.active;
  370. }
  371. return true;
  372. }
  373. /**
  374. * Sets the audio level for the stream
  375. * @param {number} audioLevel value between 0 and 1
  376. * @param {TraceablePeerConnection} [tpc] the peerconnection instance which
  377. * is source for the audio level. It can be <tt>undefined</tt> for
  378. * a local track if the audio level was measured outside of the
  379. * peerconnection (see /modules/statistics/LocalStatsCollector.js).
  380. */
  381. setAudioLevel(audioLevel, tpc) {
  382. let newAudioLevel = audioLevel;
  383. // When using getSynchornizationSources on the audio receiver to gather audio levels for
  384. // remote tracks, browser reports last known audio levels even when the remote user is
  385. // audio muted, we need to reset the value to zero here so that the audio levels are cleared.
  386. // Remote tracks have the tpc info present while local tracks do not.
  387. if (browser.supportsReceiverStats() && typeof tpc !== 'undefined' && this.isMuted()) {
  388. newAudioLevel = 0;
  389. }
  390. if (this.audioLevel !== newAudioLevel) {
  391. this.audioLevel = newAudioLevel;
  392. this.emit(
  393. JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  394. newAudioLevel,
  395. tpc);
  396. // LocalStatsCollector reports a value of 0.008 for muted mics
  397. // and a value of 0 when there is no audio input.
  398. } else if (this.audioLevel === 0
  399. && newAudioLevel === 0
  400. && this.isLocal()
  401. && !this.isWebRTCTrackMuted()) {
  402. this.emit(
  403. JitsiTrackEvents.NO_AUDIO_INPUT,
  404. newAudioLevel);
  405. }
  406. }
  407. /**
  408. * Returns the msid of the stream attached to the JitsiTrack object or null
  409. * if no stream is attached.
  410. */
  411. getMSID() {
  412. const streamId = this.getStreamId();
  413. const trackId = this.getTrackId();
  414. return streamId && trackId ? `${streamId} ${trackId}` : null;
  415. }
  416. /**
  417. * Sets new audio output device for track's DOM elements. Video tracks are
  418. * ignored.
  419. * @param {string} audioOutputDeviceId - id of 'audiooutput' device from
  420. * navigator.mediaDevices.enumerateDevices(), '' for default device
  421. * @emits JitsiTrackEvents.TRACK_AUDIO_OUTPUT_CHANGED
  422. * @returns {Promise}
  423. */
  424. setAudioOutput(audioOutputDeviceId) {
  425. if (!RTCUtils.isDeviceChangeAvailable('output')) {
  426. return Promise.reject(
  427. new Error('Audio output device change is not supported'));
  428. }
  429. // All audio communication is done through audio tracks, so ignore
  430. // changing audio output for video tracks at all.
  431. if (this.isVideoTrack()) {
  432. return Promise.resolve();
  433. }
  434. return (
  435. Promise.all(
  436. this.containers.map(
  437. element =>
  438. element.setSinkId(audioOutputDeviceId)
  439. .catch(error => {
  440. logger.warn(
  441. 'Failed to change audio output device on'
  442. + ' element. Default or previously set'
  443. + ' audio output device will be used.',
  444. element,
  445. error);
  446. throw error;
  447. }))
  448. )
  449. .then(() => {
  450. this.emit(
  451. JitsiTrackEvents.TRACK_AUDIO_OUTPUT_CHANGED,
  452. audioOutputDeviceId);
  453. }));
  454. }
  455. }