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 16KB

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