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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. /* global __filename, module */
  2. import EventEmitter from 'events';
  3. import { getLogger } from 'jitsi-meet-logger';
  4. import * as JitsiTrackEvents from '../../JitsiTrackEvents';
  5. import * as MediaType from '../../service/RTC/MediaType';
  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. * Adds onended/oninactive handler to a MediaStream.
  18. * @param mediaStream a MediaStream to attach onended/oninactive handler
  19. * @param handler the handler
  20. */
  21. function addMediaStreamInactiveHandler(mediaStream, handler) {
  22. // Temasys will use onended
  23. if (typeof mediaStream.active === 'undefined') {
  24. mediaStream.onended = handler;
  25. } else {
  26. mediaStream.oninactive = handler;
  27. }
  28. }
  29. /**
  30. * Represents a single media track (either audio or video).
  31. */
  32. export default class JitsiTrack extends EventEmitter {
  33. /* eslint-disable max-params */
  34. /**
  35. * Represents a single media track (either audio or video).
  36. * @constructor
  37. * @param conference the rtc instance
  38. * @param stream the WebRTC MediaStream instance
  39. * @param track the WebRTC MediaStreamTrack instance, must be part of
  40. * the given <tt>stream</tt>.
  41. * @param streamInactiveHandler the function that will handle
  42. * onended/oninactive events of the stream.
  43. * @param trackMediaType the media type of the JitsiTrack
  44. * @param videoType the VideoType for this track if any
  45. */
  46. constructor(
  47. conference,
  48. stream,
  49. track,
  50. streamInactiveHandler,
  51. trackMediaType,
  52. videoType) {
  53. super();
  54. // aliases for addListener/removeListener
  55. this.addEventListener = this.addListener;
  56. this.removeEventListener = this.off = this.removeListener;
  57. /**
  58. * Array with the HTML elements that are displaying the streams.
  59. * @type {Array}
  60. */
  61. this.containers = [];
  62. this.conference = conference;
  63. this.audioLevel = -1;
  64. this.type = trackMediaType;
  65. this.track = track;
  66. this.videoType = videoType;
  67. this.handlers = new Map();
  68. /**
  69. * Indicates whether this JitsiTrack has been disposed. If true, this
  70. * JitsiTrack is to be considered unusable and operations involving it
  71. * are to fail (e.g. {@link JitsiConference#addTrack(JitsiTrack)},
  72. * {@link JitsiConference#removeTrack(JitsiTrack)}).
  73. * @type {boolean}
  74. */
  75. this.disposed = false;
  76. /**
  77. * The inactive handler which will be triggered when the underlying
  78. * <tt>MediaStream</tt> ends.
  79. *
  80. * @private
  81. * @type {Function}
  82. */
  83. this._streamInactiveHandler = streamInactiveHandler;
  84. this._setStream(stream);
  85. }
  86. /* eslint-enable max-params */
  87. /**
  88. * Sets handler to the WebRTC MediaStream or MediaStreamTrack object
  89. * depending on the passed type.
  90. * @param {string} type the type of the handler that is going to be set
  91. * @param {Function} handler the handler.
  92. */
  93. _setHandler(type, handler) {
  94. if (!trackHandler2Prop.hasOwnProperty(type)) {
  95. logger.error(`Invalid handler type ${type}`);
  96. return;
  97. }
  98. if (handler) {
  99. this.handlers.set(type, handler);
  100. } else {
  101. this.handlers.delete(type);
  102. }
  103. if (this.stream) {
  104. // FIXME Why only video tracks?
  105. for (const track of this.stream.getVideoTracks()) {
  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. addMediaStreamInactiveHandler(this.stream, 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. addMediaStreamInactiveHandler(
  152. this.stream, this._streamInactiveHandler);
  153. }
  154. }
  155. }
  156. /**
  157. * Returns the type (audio or video) of this track.
  158. */
  159. getType() {
  160. return this.type;
  161. }
  162. /**
  163. * Check if this is an audio track.
  164. */
  165. isAudioTrack() {
  166. return this.getType() === MediaType.AUDIO;
  167. }
  168. /**
  169. * Checks whether the underlying WebRTC <tt>MediaStreamTrack</tt> is muted
  170. * according to it's 'muted' field status.
  171. * @return {boolean} <tt>true</tt> if the underlying
  172. * <tt>MediaStreamTrack</tt> is muted or <tt>false</tt> otherwise.
  173. */
  174. isWebRTCTrackMuted() {
  175. return this.track && this.track.muted;
  176. }
  177. /**
  178. * Check if this is a video track.
  179. */
  180. isVideoTrack() {
  181. return this.getType() === MediaType.VIDEO;
  182. }
  183. /**
  184. * Checks whether this is a local track.
  185. * @abstract
  186. * @return {boolean} 'true' if it's a local track or 'false' otherwise.
  187. */
  188. isLocal() {
  189. throw new Error('Not implemented by subclass');
  190. }
  191. /**
  192. * Returns the WebRTC MediaStream instance.
  193. */
  194. getOriginalStream() {
  195. return this.stream;
  196. }
  197. /**
  198. * Returns the ID of the underlying WebRTC Media Stream(if any)
  199. * @returns {String|null}
  200. */
  201. getStreamId() {
  202. return this.stream ? this.stream.id : null;
  203. }
  204. /**
  205. * Return the underlying WebRTC MediaStreamTrack
  206. * @returns {MediaStreamTrack}
  207. */
  208. getTrack() {
  209. return this.track;
  210. }
  211. /**
  212. * Returns the ID of the underlying WebRTC MediaStreamTrack(if any)
  213. * @returns {String|null}
  214. */
  215. getTrackId() {
  216. return this.track ? this.track.id : null;
  217. }
  218. /**
  219. * Return meaningful usage label for this track depending on it's media and
  220. * eventual video type.
  221. * @returns {string}
  222. */
  223. getUsageLabel() {
  224. if (this.isAudioTrack()) {
  225. return 'mic';
  226. }
  227. return this.videoType ? this.videoType : 'default';
  228. }
  229. /**
  230. * Eventually will trigger RTCEvents.TRACK_ATTACHED event.
  231. * @param container the video/audio container to which this stream is
  232. * attached and for which event will be fired.
  233. * @private
  234. */
  235. _maybeFireTrackAttached(container) {
  236. if (this.conference && container) {
  237. this.conference._onTrackAttach(this, container);
  238. }
  239. }
  240. /**
  241. * Attaches the MediaStream of this track to an HTML container.
  242. * Adds the container to the list of containers that are displaying the
  243. * track. Note that Temasys plugin will replace original audio/video element
  244. * with 'object' when stream is being attached to the container for the
  245. * first time.
  246. * * NOTE * if given container element is not visible when the stream is
  247. * being attached it will be shown back given that Temasys plugin is
  248. * currently in use.
  249. *
  250. * @param container the HTML container which can be 'video' or 'audio'
  251. * element. It can also be 'object' element if Temasys plugin is in use and
  252. * this method has been called previously on video or audio HTML element.
  253. *
  254. * @returns potentially new instance of container if it was replaced by the
  255. * library. That's the case when Temasys plugin is in use.
  256. */
  257. attach(container) {
  258. let c = container;
  259. if (this.stream) {
  260. c = RTCUtils.attachMediaStream(container, this.stream);
  261. }
  262. this.containers.push(c);
  263. this._maybeFireTrackAttached(c);
  264. this._attachTTFMTracker(c);
  265. return c;
  266. }
  267. /**
  268. * Removes this JitsiTrack from the passed HTML container.
  269. *
  270. * @param container the HTML container to detach from this JitsiTrack. If
  271. * <tt>null</tt> or <tt>undefined</tt>, all containers are removed. A
  272. * container can be a 'video', 'audio' or 'object' HTML element instance to
  273. * which this JitsiTrack is currently attached.
  274. */
  275. detach(container) {
  276. for (let cs = this.containers, i = cs.length - 1; i >= 0; --i) {
  277. const c = cs[i];
  278. if (!container) {
  279. RTCUtils.attachMediaStream(c, null);
  280. }
  281. if (!container || c === container) {
  282. cs.splice(i, 1);
  283. }
  284. }
  285. if (container) {
  286. RTCUtils.attachMediaStream(container, null);
  287. }
  288. }
  289. /**
  290. * Attach time to first media tracker only if there is conference and only
  291. * for the first element.
  292. *
  293. * @param {HTMLElement} container the HTML container which can be 'video' or
  294. * 'audio' element. It can also be 'object' element if Temasys plugin is in
  295. * use and this method has been called previously on video or audio HTML
  296. * element.
  297. * @private
  298. */
  299. _attachTTFMTracker(container) { // eslint-disable-line no-unused-vars
  300. // Should be defined by the classes that are extending JitsiTrack
  301. }
  302. /**
  303. * Removes attached event listeners.
  304. *
  305. * @returns {Promise}
  306. */
  307. dispose() {
  308. this.removeAllListeners();
  309. this.disposed = true;
  310. return Promise.resolve();
  311. }
  312. /**
  313. * Returns true if this is a video track and the source of the video is a
  314. * screen capture as opposed to a camera.
  315. */
  316. isScreenSharing() {
  317. // FIXME: Should be fixed or removed.
  318. }
  319. /**
  320. * Returns id of the track.
  321. * @returns {string|null} id of the track or null if this is fake track.
  322. */
  323. getId() {
  324. if (this.stream) {
  325. return RTCUtils.getStreamID(this.stream);
  326. }
  327. return null;
  328. }
  329. /**
  330. * Checks whether the MediaStream is active/not ended.
  331. * When there is no check for active we don't have information and so
  332. * will return that stream is active (in case of FF).
  333. * @returns {boolean} whether MediaStream is active.
  334. */
  335. isActive() {
  336. if (typeof this.stream.active !== 'undefined') {
  337. return this.stream.active;
  338. }
  339. return true;
  340. }
  341. /**
  342. * Sets the audio level for the stream
  343. * @param {number} audioLevel value between 0 and 1
  344. * @param {TraceablePeerConnection} [tpc] the peerconnection instance which
  345. * is source for the audio level. It can be <tt>undefined</tt> for
  346. * a local track if the audio level was measured outside of the
  347. * peerconnection (see /modules/statistics/LocalStatsCollector.js).
  348. */
  349. setAudioLevel(audioLevel, tpc) {
  350. if (this.audioLevel !== audioLevel) {
  351. this.audioLevel = audioLevel;
  352. this.emit(
  353. JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  354. audioLevel,
  355. tpc);
  356. }
  357. }
  358. /**
  359. * Returns the msid of the stream attached to the JitsiTrack object or null
  360. * if no stream is attached.
  361. */
  362. getMSID() {
  363. const streamId = this.getStreamId();
  364. const trackId = this.getTrackId();
  365. return streamId && trackId ? `${streamId} ${trackId}` : null;
  366. }
  367. /**
  368. * Sets new audio output device for track's DOM elements. Video tracks are
  369. * ignored.
  370. * @param {string} audioOutputDeviceId - id of 'audiooutput' device from
  371. * navigator.mediaDevices.enumerateDevices(), '' for default device
  372. * @emits JitsiTrackEvents.TRACK_AUDIO_OUTPUT_CHANGED
  373. * @returns {Promise}
  374. */
  375. setAudioOutput(audioOutputDeviceId) {
  376. if (!RTCUtils.isDeviceChangeAvailable('output')) {
  377. return Promise.reject(
  378. new Error('Audio output device change is not supported'));
  379. }
  380. // All audio communication is done through audio tracks, so ignore
  381. // changing audio output for video tracks at all.
  382. if (this.isVideoTrack()) {
  383. return Promise.resolve();
  384. }
  385. return (
  386. Promise.all(
  387. this.containers.map(
  388. element =>
  389. element.setSinkId(audioOutputDeviceId)
  390. .catch(error => {
  391. logger.warn(
  392. 'Failed to change audio output device on'
  393. + ' element. Default or previously set'
  394. + ' audio output device will be used.',
  395. element,
  396. error);
  397. throw error;
  398. }))
  399. )
  400. .then(() => {
  401. this.emit(
  402. JitsiTrackEvents.TRACK_AUDIO_OUTPUT_CHANGED,
  403. audioOutputDeviceId);
  404. }));
  405. }
  406. }