Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

JitsiTrack.js 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  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 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 type (audio or video) of this track.
  157. */
  158. getType() {
  159. return this.type;
  160. }
  161. /**
  162. * Check if this is an audio track.
  163. */
  164. isAudioTrack() {
  165. return this.getType() === MediaType.AUDIO;
  166. }
  167. /**
  168. * Checks whether the underlying WebRTC <tt>MediaStreamTrack</tt> is muted
  169. * according to it's 'muted' field status.
  170. * @return {boolean} <tt>true</tt> if the underlying
  171. * <tt>MediaStreamTrack</tt> is muted or <tt>false</tt> otherwise.
  172. */
  173. isWebRTCTrackMuted() {
  174. return this.track && this.track.muted;
  175. }
  176. /**
  177. * Check if this is a video track.
  178. */
  179. isVideoTrack() {
  180. return this.getType() === MediaType.VIDEO;
  181. }
  182. /**
  183. * Checks whether this is a local track.
  184. * @abstract
  185. * @return {boolean} 'true' if it's a local track or 'false' otherwise.
  186. */
  187. isLocal() {
  188. throw new Error('Not implemented by subclass');
  189. }
  190. /**
  191. * Check whether this is a local audio track.
  192. *
  193. * @return {boolean} - true if track represents a local audio track, false otherwise.
  194. */
  195. isLocalAudioTrack() {
  196. return this.isAudioTrack() && this.isLocal();
  197. }
  198. /**
  199. * Returns the WebRTC MediaStream instance.
  200. */
  201. getOriginalStream() {
  202. return this.stream;
  203. }
  204. /**
  205. * Returns the ID of the underlying WebRTC Media Stream(if any)
  206. * @returns {String|null}
  207. */
  208. getStreamId() {
  209. return this.stream ? this.stream.id : null;
  210. }
  211. /**
  212. * Return the underlying WebRTC MediaStreamTrack
  213. * @returns {MediaStreamTrack}
  214. */
  215. getTrack() {
  216. return this.track;
  217. }
  218. /**
  219. * Return the underlying WebRTC MediaStreamTrack label
  220. * @returns {string}
  221. */
  222. getTrackLabel() {
  223. return this.track.label;
  224. }
  225. /**
  226. * Returns the ID of the underlying WebRTC MediaStreamTrack(if any)
  227. * @returns {String|null}
  228. */
  229. getTrackId() {
  230. return this.track ? this.track.id : null;
  231. }
  232. /**
  233. * Return meaningful usage label for this track depending on it's media and
  234. * eventual video type.
  235. * @returns {string}
  236. */
  237. getUsageLabel() {
  238. if (this.isAudioTrack()) {
  239. return 'mic';
  240. }
  241. return this.videoType ? this.videoType : 'default';
  242. }
  243. /**
  244. * Eventually will trigger RTCEvents.TRACK_ATTACHED event.
  245. * @param container the video/audio container to which this stream is
  246. * attached and for which event will be fired.
  247. * @private
  248. */
  249. _maybeFireTrackAttached(container) {
  250. if (this.conference && container) {
  251. this.conference._onTrackAttach(this, container);
  252. }
  253. }
  254. /**
  255. * Attaches the MediaStream of this track to an HTML container.
  256. * Adds the container to the list of containers that are displaying the
  257. * track.
  258. *
  259. * @param container the HTML container which can be 'video' or 'audio'
  260. * element.
  261. *
  262. * @returns {void}
  263. */
  264. attach(container) {
  265. if (this.stream) {
  266. this._onTrackAttach(container);
  267. RTCUtils.attachMediaStream(container, this.stream);
  268. }
  269. this.containers.push(container);
  270. this._maybeFireTrackAttached(container);
  271. this._attachTTFMTracker(container);
  272. }
  273. /**
  274. * Removes this JitsiTrack from the passed HTML container.
  275. *
  276. * @param container the HTML container to detach from this JitsiTrack. If
  277. * <tt>null</tt> or <tt>undefined</tt>, all containers are removed. A
  278. * container can be a 'video', 'audio' or 'object' HTML element instance to
  279. * which this JitsiTrack is currently attached.
  280. */
  281. detach(container) {
  282. for (let cs = this.containers, i = cs.length - 1; i >= 0; --i) {
  283. const c = cs[i];
  284. if (!container) {
  285. this._onTrackDetach(c);
  286. RTCUtils.attachMediaStream(c, null);
  287. }
  288. if (!container || c === container) {
  289. cs.splice(i, 1);
  290. }
  291. }
  292. if (container) {
  293. this._onTrackDetach(container);
  294. RTCUtils.attachMediaStream(container, null);
  295. }
  296. }
  297. /**
  298. * Called when the track has been attached to a new container.
  299. *
  300. * @param {HTMLElement} container the HTML container which can be 'video' or
  301. * 'audio' element.
  302. * @private
  303. */
  304. _onTrackAttach(container) { // eslint-disable-line no-unused-vars
  305. // Should be defined by the classes that are extending JitsiTrack
  306. }
  307. /**
  308. * Called when the track has been detached from a container.
  309. *
  310. * @param {HTMLElement} container the HTML container which can be 'video' or
  311. * 'audio' element.
  312. * @private
  313. */
  314. _onTrackDetach(container) { // eslint-disable-line no-unused-vars
  315. // Should be defined by the classes that are extending JitsiTrack
  316. }
  317. /**
  318. * Attach time to first media tracker only if there is conference and only
  319. * for the first element.
  320. *
  321. * @param {HTMLElement} container the HTML container which can be 'video' or
  322. * 'audio' element.
  323. * @private
  324. */
  325. _attachTTFMTracker(container) { // eslint-disable-line no-unused-vars
  326. // Should be defined by the classes that are extending JitsiTrack
  327. }
  328. /**
  329. * Removes attached event listeners.
  330. *
  331. * @returns {Promise}
  332. */
  333. dispose() {
  334. this.removeAllListeners();
  335. this.disposed = true;
  336. return Promise.resolve();
  337. }
  338. /**
  339. * Returns true if this is a video track and the source of the video is a
  340. * screen capture as opposed to a camera.
  341. */
  342. isScreenSharing() {
  343. // FIXME: Should be fixed or removed.
  344. }
  345. /**
  346. * Returns id of the track.
  347. * @returns {string|null} id of the track or null if this is fake track.
  348. */
  349. getId() {
  350. if (this.stream) {
  351. return RTCUtils.getStreamID(this.stream);
  352. }
  353. return null;
  354. }
  355. /**
  356. * Checks whether the MediaStream is active/not ended.
  357. * When there is no check for active we don't have information and so
  358. * will return that stream is active (in case of FF).
  359. * @returns {boolean} whether MediaStream is active.
  360. */
  361. isActive() {
  362. if (typeof this.stream.active !== 'undefined') {
  363. return this.stream.active;
  364. }
  365. return true;
  366. }
  367. /**
  368. * Sets the audio level for the stream
  369. * @param {number} audioLevel value between 0 and 1
  370. * @param {TraceablePeerConnection} [tpc] the peerconnection instance which
  371. * is source for the audio level. It can be <tt>undefined</tt> for
  372. * a local track if the audio level was measured outside of the
  373. * peerconnection (see /modules/statistics/LocalStatsCollector.js).
  374. */
  375. setAudioLevel(audioLevel, tpc) {
  376. // The receiver seems to be reporting audio level immediately after the
  377. // remote user has muted, so do not set the audio level on the track
  378. // if it is muted.
  379. if (browser.supportsReceiverStats()
  380. && !this.isLocalAudioTrack()
  381. && this.isWebRTCTrackMuted()) {
  382. return;
  383. }
  384. if (this.audioLevel !== audioLevel) {
  385. this.audioLevel = audioLevel;
  386. this.emit(
  387. JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  388. audioLevel,
  389. tpc);
  390. // LocalStatsCollector reports a value of 0.008 for muted mics
  391. // and a value of 0 when there is no audio input.
  392. } else if (this.audioLevel === 0
  393. && audioLevel === 0
  394. && this.isLocal()
  395. && !this.isWebRTCTrackMuted()) {
  396. this.emit(
  397. JitsiTrackEvents.NO_AUDIO_INPUT,
  398. audioLevel);
  399. }
  400. }
  401. /**
  402. * Returns the msid of the stream attached to the JitsiTrack object or null
  403. * if no stream is attached.
  404. */
  405. getMSID() {
  406. const streamId = this.getStreamId();
  407. const trackId = this.getTrackId();
  408. return streamId && trackId ? `${streamId} ${trackId}` : null;
  409. }
  410. /**
  411. * Sets new audio output device for track's DOM elements. Video tracks are
  412. * ignored.
  413. * @param {string} audioOutputDeviceId - id of 'audiooutput' device from
  414. * navigator.mediaDevices.enumerateDevices(), '' for default device
  415. * @emits JitsiTrackEvents.TRACK_AUDIO_OUTPUT_CHANGED
  416. * @returns {Promise}
  417. */
  418. setAudioOutput(audioOutputDeviceId) {
  419. if (!RTCUtils.isDeviceChangeAvailable('output')) {
  420. return Promise.reject(
  421. new Error('Audio output device change is not supported'));
  422. }
  423. // All audio communication is done through audio tracks, so ignore
  424. // changing audio output for video tracks at all.
  425. if (this.isVideoTrack()) {
  426. return Promise.resolve();
  427. }
  428. return (
  429. Promise.all(
  430. this.containers.map(
  431. element =>
  432. element.setSinkId(audioOutputDeviceId)
  433. .catch(error => {
  434. logger.warn(
  435. 'Failed to change audio output device on'
  436. + ' element. Default or previously set'
  437. + ' audio output device will be used.',
  438. element,
  439. error);
  440. throw error;
  441. }))
  442. )
  443. .then(() => {
  444. this.emit(
  445. JitsiTrackEvents.TRACK_AUDIO_OUTPUT_CHANGED,
  446. audioOutputDeviceId);
  447. }));
  448. }
  449. }