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 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  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('modules/RTC/JitsiTrack');
  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. * @public
  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. const p = Promise.resolve();
  236. if (this.disposed) {
  237. return p;
  238. }
  239. this.detach();
  240. this.removeAllListeners();
  241. this.disposed = true;
  242. return p;
  243. }
  244. /**
  245. * Returns id of the track.
  246. * @returns {string|null} id of the track or null if this is fake track.
  247. */
  248. getId() {
  249. return this.getStreamId();
  250. }
  251. /**
  252. * Returns the WebRTC MediaStream instance.
  253. */
  254. getOriginalStream() {
  255. return this.stream;
  256. }
  257. /**
  258. * Returns the source name of the track.
  259. * @returns {String|undefined}
  260. */
  261. getSourceName() { // eslint-disable-line no-unused-vars
  262. // Should be defined by the classes that are extending JitsiTrack
  263. }
  264. /**
  265. * Returns the primary SSRC associated with the track.
  266. * @returns {number}
  267. */
  268. getSsrc() { // eslint-disable-line no-unused-vars
  269. // Should be defined by the classes that are extending JitsiTrack
  270. }
  271. /**
  272. * Returns the ID of the underlying WebRTC Media Stream(if any)
  273. * @returns {String|null}
  274. */
  275. getStreamId() {
  276. return this.stream ? this.stream.id : null;
  277. }
  278. /**
  279. * Return the underlying WebRTC MediaStreamTrack
  280. * @returns {MediaStreamTrack}
  281. */
  282. getTrack() {
  283. return this.track;
  284. }
  285. /**
  286. * Return the underlying WebRTC MediaStreamTrack label
  287. * @returns {string}
  288. */
  289. getTrackLabel() {
  290. return this.track.label;
  291. }
  292. /**
  293. * Returns the ID of the underlying WebRTC MediaStreamTrack(if any)
  294. * @returns {String|null}
  295. */
  296. getTrackId() {
  297. return this.track ? this.track.id : null;
  298. }
  299. /**
  300. * Returns the type (audio or video) of this track.
  301. */
  302. getType() {
  303. return this.type;
  304. }
  305. /**
  306. * Return meaningful usage label for this track depending on it's media and
  307. * eventual video type.
  308. * @returns {string}
  309. */
  310. getUsageLabel() {
  311. if (this.isAudioTrack()) {
  312. return 'mic';
  313. }
  314. return this.videoType ? this.videoType : 'default';
  315. }
  316. /**
  317. * Returns the video type (camera or desktop) of this track.
  318. */
  319. getVideoType() {
  320. return this.videoType;
  321. }
  322. /**
  323. * Returns the height of the track in normalized landscape format.
  324. */
  325. getHeight() {
  326. return Math.min(this.track.getSettings().height, this.track.getSettings().width);
  327. }
  328. /**
  329. * Returns the width of the track in normalized landscape format.
  330. */
  331. getWidth() {
  332. return Math.max(this.track.getSettings().height, this.track.getSettings().width);
  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. }