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

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