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

JitsiTrack.js 16KB

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