You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

JitsiRemoteTrack.js 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. import * as JitsiTrackEvents from '../../JitsiTrackEvents';
  2. import { createTtfmEvent } from '../../service/statistics/AnalyticsEvents';
  3. import TrackStreamingStatusImpl, { TrackStreamingStatus } from '../connectivity/TrackStreamingStatus';
  4. import FeatureFlags from '../flags/FeatureFlags';
  5. import Statistics from '../statistics/statistics';
  6. import JitsiTrack from './JitsiTrack';
  7. const logger = require('@jitsi/logger').getLogger(__filename);
  8. const RTCEvents = require('../../service/RTC/RTCEvents');
  9. let ttfmTrackerAudioAttached = false;
  10. let ttfmTrackerVideoAttached = false;
  11. /**
  12. * List of container events that we are going to process. _onContainerEventHandler will be added as listener to the
  13. * container for every event in the list.
  14. */
  15. const containerEvents = [ 'abort', 'canplaythrough', 'ended', 'error' ];
  16. /* eslint-disable max-params */
  17. /**
  18. * Represents a single media track (either audio or video).
  19. */
  20. export default class JitsiRemoteTrack extends JitsiTrack {
  21. /**
  22. * Creates new JitsiRemoteTrack instance.
  23. * @param {RTC} rtc the RTC service instance.
  24. * @param {JitsiConference} conference the conference to which this track
  25. * belongs to
  26. * @param {string} ownerEndpointId the endpoint ID of the track owner
  27. * @param {MediaStream} stream WebRTC MediaStream, parent of the track
  28. * @param {MediaStreamTrack} track underlying WebRTC MediaStreamTrack for
  29. * the new JitsiRemoteTrack
  30. * @param {MediaType} mediaType the type of the media
  31. * @param {VideoType} videoType the type of the video if applicable
  32. * @param {number} ssrc the SSRC number of the Media Stream
  33. * @param {boolean} muted the initial muted state
  34. * @param {boolean} isP2P indicates whether or not this track belongs to a
  35. * P2P session
  36. * @param {String} sourceName the source name signaled for the track
  37. * @throws {TypeError} if <tt>ssrc</tt> is not a number.
  38. * @constructor
  39. */
  40. constructor(
  41. rtc,
  42. conference,
  43. ownerEndpointId,
  44. stream,
  45. track,
  46. mediaType,
  47. videoType,
  48. ssrc,
  49. muted,
  50. isP2P,
  51. sourceName) {
  52. super(
  53. conference,
  54. stream,
  55. track,
  56. () => {
  57. // Nothing to do if the track is inactive.
  58. },
  59. mediaType,
  60. videoType);
  61. this.rtc = rtc;
  62. // Prevent from mixing up type of SSRC which should be a number
  63. if (typeof ssrc !== 'number') {
  64. throw new TypeError(`SSRC ${ssrc} is not a number`);
  65. }
  66. this.ssrc = ssrc;
  67. this.ownerEndpointId = ownerEndpointId;
  68. this.muted = muted;
  69. this.isP2P = isP2P;
  70. this._sourceName = sourceName;
  71. this._trackStreamingStatus = null;
  72. this._trackStreamingStatusImpl = null;
  73. /**
  74. * This holds the timestamp indicating when remote video track entered forwarded sources set. Track entering
  75. * forwardedSources will have streaming status restoring and when we start receiving video will become active,
  76. * but if video is not received for certain time {@link DEFAULT_RESTORING_TIMEOUT} that track streaming status
  77. * will become interrupted.
  78. */
  79. this._enteredForwardedSourcesTimestamp = null;
  80. this.addEventListener = this.on = this._addEventListener.bind(this);
  81. this.removeEventListener = this.off = this._removeEventListener.bind(this);
  82. logger.debug(`New remote track added: ${this}`);
  83. // we want to mark whether the track has been ever muted
  84. // to detect ttfm events for startmuted conferences, as it can
  85. // significantly increase ttfm values
  86. this.hasBeenMuted = muted;
  87. // Bind 'onmute' and 'onunmute' event handlers
  88. if (this.rtc && this.track) {
  89. this._bindTrackHandlers();
  90. }
  91. this._containerHandlers = {};
  92. containerEvents.forEach(event => {
  93. this._containerHandlers[event] = this._containerEventHandler.bind(this, event);
  94. });
  95. }
  96. /* eslint-enable max-params */
  97. /**
  98. * Attaches the track handlers.
  99. *
  100. * @returns {void}
  101. */
  102. _bindTrackHandlers() {
  103. this.track.addEventListener('mute', () => this._onTrackMute());
  104. this.track.addEventListener('unmute', () => this._onTrackUnmute());
  105. this.track.addEventListener('ended', () => {
  106. logger.debug(`"onended" event(${Date.now()}): ${this}`);
  107. });
  108. }
  109. /**
  110. * Overrides addEventListener method to init TrackStreamingStatus instance when there are listeners for the
  111. * {@link JitsiTrackEvents.TRACK_STREAMING_STATUS_CHANGED} event.
  112. *
  113. * @param {string} event - event name
  114. * @param {function} handler - event handler
  115. */
  116. _addEventListener(event, handler) {
  117. super.addListener(event, handler);
  118. if (FeatureFlags.isSourceNameSignalingEnabled()
  119. && event === JitsiTrackEvents.TRACK_STREAMING_STATUS_CHANGED
  120. && this.listenerCount(JitsiTrackEvents.TRACK_STREAMING_STATUS_CHANGED)
  121. && !this._trackStreamingStatusImpl
  122. ) {
  123. this._initTrackStreamingStatus();
  124. logger.debug(`Initializing track streaming status: ${this._sourceName}`);
  125. }
  126. }
  127. /**
  128. * Overrides removeEventListener method to dispose TrackStreamingStatus instance.
  129. *
  130. * @param {string} event - event name
  131. * @param {function} handler - event handler
  132. */
  133. _removeEventListener(event, handler) {
  134. super.removeListener(event, handler);
  135. if (FeatureFlags.isSourceNameSignalingEnabled()
  136. && event === JitsiTrackEvents.TRACK_STREAMING_STATUS_CHANGED
  137. && !this.listenerCount(JitsiTrackEvents.TRACK_STREAMING_STATUS_CHANGED)
  138. ) {
  139. this._disposeTrackStreamingStatus();
  140. logger.debug(`Disposing track streaming status: ${this._sourceName}`);
  141. }
  142. }
  143. /**
  144. * Callback invoked when the track is muted. Emits an event notifying
  145. * listeners of the mute event.
  146. *
  147. * @private
  148. * @returns {void}
  149. */
  150. _onTrackMute() {
  151. logger.debug(`"onmute" event(${Date.now()}): ${this}`);
  152. this.rtc.eventEmitter.emit(RTCEvents.REMOTE_TRACK_MUTE, this);
  153. }
  154. /**
  155. * Callback invoked when the track is unmuted. Emits an event notifying
  156. * listeners of the mute event.
  157. *
  158. * @private
  159. * @returns {void}
  160. */
  161. _onTrackUnmute() {
  162. logger.debug(`"onunmute" event(${Date.now()}): ${this}`);
  163. this.rtc.eventEmitter.emit(RTCEvents.REMOTE_TRACK_UNMUTE, this);
  164. }
  165. /**
  166. * Removes attached event listeners and dispose TrackStreamingStatus .
  167. *
  168. * @returns {Promise}
  169. */
  170. dispose() {
  171. if (FeatureFlags.isSourceNameSignalingEnabled()) {
  172. this._disposeTrackStreamingStatus();
  173. }
  174. return super.dispose();
  175. }
  176. /**
  177. * Sets current muted status and fires an events for the change.
  178. * @param value the muted status.
  179. */
  180. setMute(value) {
  181. if (this.muted === value) {
  182. return;
  183. }
  184. if (value) {
  185. this.hasBeenMuted = true;
  186. }
  187. // we can have a fake video stream
  188. if (this.stream) {
  189. this.stream.muted = value;
  190. }
  191. this.muted = value;
  192. this.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED, this);
  193. }
  194. /**
  195. * Returns the current muted status of the track.
  196. * @returns {boolean|*|JitsiRemoteTrack.muted} <tt>true</tt> if the track is
  197. * muted and <tt>false</tt> otherwise.
  198. */
  199. isMuted() {
  200. return this.muted;
  201. }
  202. /**
  203. * Returns the participant id which owns the track.
  204. *
  205. * @returns {string} the id of the participants. It corresponds to the
  206. * Colibri endpoint id/MUC nickname in case of Jitsi-meet.
  207. */
  208. getParticipantId() {
  209. return this.ownerEndpointId;
  210. }
  211. /**
  212. * Return false;
  213. */
  214. isLocal() {
  215. return false;
  216. }
  217. /**
  218. * Returns the synchronization source identifier (SSRC) of this remote
  219. * track.
  220. *
  221. * @returns {number} the SSRC of this remote track.
  222. */
  223. getSSRC() {
  224. return this.ssrc;
  225. }
  226. /**
  227. * Returns the tracks source name
  228. *
  229. * @returns {string} the track's source name
  230. */
  231. getSourceName() {
  232. return this._sourceName;
  233. }
  234. /**
  235. * Changes the video type of the track.
  236. *
  237. * @param {string} type - The new video type("camera", "desktop").
  238. */
  239. _setVideoType(type) {
  240. if (this.videoType === type) {
  241. return;
  242. }
  243. this.videoType = type;
  244. this.emit(JitsiTrackEvents.TRACK_VIDEOTYPE_CHANGED, type);
  245. }
  246. /**
  247. * Handles track play events.
  248. */
  249. _playCallback() {
  250. const type = this.isVideoTrack() ? 'video' : 'audio';
  251. const now = window.performance.now();
  252. console.log(`(TIME) Render ${type}:\t`, now);
  253. this.conference.getConnectionTimes()[`${type}.render`] = now;
  254. // The conference can be started without calling GUM
  255. // FIXME if there would be a module for connection times this kind
  256. // of logic (gumDuration or ttfm) should end up there
  257. const gumStart = window.connectionTimes['obtainPermissions.start'];
  258. const gumEnd = window.connectionTimes['obtainPermissions.end'];
  259. const gumDuration
  260. = !isNaN(gumEnd) && !isNaN(gumStart) ? gumEnd - gumStart : 0;
  261. // Subtract the muc.joined-to-session-initiate duration because jicofo
  262. // waits until there are 2 participants to start Jingle sessions.
  263. const ttfm = now
  264. - (this.conference.getConnectionTimes()['session.initiate']
  265. - this.conference.getConnectionTimes()['muc.joined'])
  266. - gumDuration;
  267. this.conference.getConnectionTimes()[`${type}.ttfm`] = ttfm;
  268. console.log(`(TIME) TTFM ${type}:\t`, ttfm);
  269. Statistics.sendAnalytics(createTtfmEvent(
  270. {
  271. 'media_type': type,
  272. muted: this.hasBeenMuted,
  273. value: ttfm
  274. }));
  275. }
  276. /**
  277. * Attach time to first media tracker only if there is conference and only
  278. * for the first element.
  279. * @param container the HTML container which can be 'video' or 'audio'
  280. * element.
  281. * @private
  282. */
  283. _attachTTFMTracker(container) {
  284. if ((ttfmTrackerAudioAttached && this.isAudioTrack())
  285. || (ttfmTrackerVideoAttached && this.isVideoTrack())) {
  286. return;
  287. }
  288. if (this.isAudioTrack()) {
  289. ttfmTrackerAudioAttached = true;
  290. }
  291. if (this.isVideoTrack()) {
  292. ttfmTrackerVideoAttached = true;
  293. }
  294. container.addEventListener('canplay', this._playCallback.bind(this));
  295. }
  296. /**
  297. * Called when the track has been attached to a new container.
  298. *
  299. * @param {HTMLElement} container the HTML container which can be 'video' or 'audio' element.
  300. * @private
  301. */
  302. _onTrackAttach(container) {
  303. containerEvents.forEach(event => {
  304. container.addEventListener(event, this._containerHandlers[event]);
  305. });
  306. }
  307. /**
  308. * Called when the track has been detached from a container.
  309. *
  310. * @param {HTMLElement} container the HTML container which can be 'video' or 'audio' element.
  311. * @private
  312. */
  313. _onTrackDetach(container) {
  314. containerEvents.forEach(event => {
  315. container.removeEventListener(event, this._containerHandlers[event]);
  316. });
  317. }
  318. /**
  319. * An event handler for events triggered by the attached container.
  320. *
  321. * @param {string} type - The type of the event.
  322. */
  323. _containerEventHandler(type) {
  324. logger.debug(`${type} handler was called for a container with attached ${this}`);
  325. }
  326. /**
  327. * Returns a string with a description of the current status of the track.
  328. *
  329. * @returns {string}
  330. */
  331. _getStatus() {
  332. const { enabled, muted, readyState } = this.track;
  333. return `readyState: ${readyState}, muted: ${muted}, enabled: ${enabled}`;
  334. }
  335. /**
  336. * Initializes trackStreamingStatusImpl.
  337. */
  338. _initTrackStreamingStatus() {
  339. const config = this.conference.options.config;
  340. this._trackStreamingStatus = TrackStreamingStatus.ACTIVE;
  341. this._trackStreamingStatusImpl = new TrackStreamingStatusImpl(
  342. this.rtc,
  343. this.conference,
  344. this,
  345. {
  346. // These options are not public API, leaving it here only as an entry point through config for
  347. // tuning up purposes. Default values should be adjusted as soon as optimal values are discovered.
  348. p2pRtcMuteTimeout: config._p2pConnStatusRtcMuteTimeout,
  349. rtcMuteTimeout: config._peerConnStatusRtcMuteTimeout,
  350. outOfForwardedSourcesTimeout: config._peerConnStatusOutOfLastNTimeout
  351. });
  352. this._trackStreamingStatusImpl.init();
  353. }
  354. /**
  355. * Disposes trackStreamingStatusImpl and clears trackStreamingStatus.
  356. */
  357. _disposeTrackStreamingStatus() {
  358. if (this._trackStreamingStatusImpl) {
  359. this._trackStreamingStatusImpl.dispose();
  360. this._trackStreamingStatusImpl = null;
  361. this._trackStreamingStatus = null;
  362. }
  363. }
  364. /**
  365. * Updates track's streaming status.
  366. *
  367. * @param {string} state the current track streaming state. {@link TrackStreamingStatus}.
  368. */
  369. _setTrackStreamingStatus(status) {
  370. this._trackStreamingStatus = status;
  371. }
  372. /**
  373. * Returns track's streaming status.
  374. *
  375. * @returns {string} the streaming status <tt>TrackStreamingStatus</tt> of the track. Returns null
  376. * if trackStreamingStatusImpl hasn't been initialized.
  377. *
  378. * {@link TrackStreamingStatus}.
  379. */
  380. getTrackStreamingStatus() {
  381. return this._trackStreamingStatus;
  382. }
  383. /**
  384. * Clears the timestamp of when the track entered forwarded sources.
  385. */
  386. _clearEnteredForwardedSourcesTimestamp() {
  387. this._enteredForwardedSourcesTimestamp = null;
  388. }
  389. /**
  390. * Updates the timestamp of when the track entered forwarded sources.
  391. *
  392. * @param {number} timestamp the time in millis
  393. */
  394. _setEnteredForwardedSourcesTimestamp(timestamp) {
  395. this._enteredForwardedSourcesTimestamp = timestamp;
  396. }
  397. /**
  398. * Returns the timestamp of when the track entered forwarded sources.
  399. *
  400. * @returns {number} the time in millis
  401. */
  402. _getEnteredForwardedSourcesTimestamp() {
  403. return this._enteredForwardedSourcesTimestamp;
  404. }
  405. /**
  406. * Creates a text representation of this remote track instance.
  407. * @return {string}
  408. */
  409. toString() {
  410. return `RemoteTrack[userID: ${this.getParticipantId()}, type: ${this.getType()}, ssrc: ${
  411. this.getSSRC()}, p2p: ${this.isP2P}, sourceName: ${this._sourceName}, status: ${this._getStatus()}]`;
  412. }
  413. }