您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

JitsiTrack.js 15KB

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