modified lib-jitsi-meet dev repo
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

JitsiTrack.js 14KB

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