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

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