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

JitsiTrack.js 16KB

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