Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

JitsiTrack.js 15KB

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