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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  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. * Update the properties when the track is remapped to another source.
  236. *
  237. * @param {string} owner The endpoint ID of the new owner.
  238. * @param {string} name The new source name.
  239. */
  240. setNewSource(owner, name) {
  241. this.ownerEndpointId = owner;
  242. this._sourceName = name;
  243. this.emit(JitsiTrackEvents.TRACK_OWNER_CHANGED, owner);
  244. }
  245. /**
  246. * Changes the video type of the track.
  247. *
  248. * @param {string} type - The new video type("camera", "desktop").
  249. */
  250. _setVideoType(type) {
  251. if (this.videoType === type) {
  252. return;
  253. }
  254. this.videoType = type;
  255. this.emit(JitsiTrackEvents.TRACK_VIDEOTYPE_CHANGED, type);
  256. }
  257. /**
  258. * Handles track play events.
  259. */
  260. _playCallback() {
  261. if (!this.conference.room) {
  262. return;
  263. }
  264. const type = this.isVideoTrack() ? 'video' : 'audio';
  265. const now = window.performance.now();
  266. console.log(`(TIME) Render ${type}:\t`, now);
  267. this.conference.getConnectionTimes()[`${type}.render`] = now;
  268. // The conference can be started without calling GUM
  269. // FIXME if there would be a module for connection times this kind
  270. // of logic (gumDuration or ttfm) should end up there
  271. const gumStart = window.connectionTimes['obtainPermissions.start'];
  272. const gumEnd = window.connectionTimes['obtainPermissions.end'];
  273. const gumDuration
  274. = !isNaN(gumEnd) && !isNaN(gumStart) ? gumEnd - gumStart : 0;
  275. // Subtract the muc.joined-to-session-initiate duration because jicofo
  276. // waits until there are 2 participants to start Jingle sessions.
  277. const ttfm = now
  278. - (this.conference.getConnectionTimes()['session.initiate']
  279. - this.conference.getConnectionTimes()['muc.joined'])
  280. - gumDuration;
  281. this.conference.getConnectionTimes()[`${type}.ttfm`] = ttfm;
  282. console.log(`(TIME) TTFM ${type}:\t`, ttfm);
  283. Statistics.sendAnalytics(createTtfmEvent(
  284. {
  285. 'media_type': type,
  286. muted: this.hasBeenMuted,
  287. value: ttfm
  288. }));
  289. }
  290. /**
  291. * Attach time to first media tracker only if there is conference and only
  292. * for the first element.
  293. * @param container the HTML container which can be 'video' or 'audio'
  294. * element.
  295. * @private
  296. */
  297. _attachTTFMTracker(container) {
  298. if ((ttfmTrackerAudioAttached && this.isAudioTrack())
  299. || (ttfmTrackerVideoAttached && this.isVideoTrack())) {
  300. return;
  301. }
  302. if (this.isAudioTrack()) {
  303. ttfmTrackerAudioAttached = true;
  304. }
  305. if (this.isVideoTrack()) {
  306. ttfmTrackerVideoAttached = true;
  307. }
  308. container.addEventListener('canplay', this._playCallback.bind(this));
  309. }
  310. /**
  311. * Called when the track has been attached to a new container.
  312. *
  313. * @param {HTMLElement} container the HTML container which can be 'video' or 'audio' element.
  314. * @private
  315. */
  316. _onTrackAttach(container) {
  317. containerEvents.forEach(event => {
  318. container.addEventListener(event, this._containerHandlers[event]);
  319. });
  320. }
  321. /**
  322. * Called when the track has been detached from a container.
  323. *
  324. * @param {HTMLElement} container the HTML container which can be 'video' or 'audio' element.
  325. * @private
  326. */
  327. _onTrackDetach(container) {
  328. containerEvents.forEach(event => {
  329. container.removeEventListener(event, this._containerHandlers[event]);
  330. });
  331. }
  332. /**
  333. * An event handler for events triggered by the attached container.
  334. *
  335. * @param {string} type - The type of the event.
  336. */
  337. _containerEventHandler(type) {
  338. logger.debug(`${type} handler was called for a container with attached ${this}`);
  339. }
  340. /**
  341. * Returns a string with a description of the current status of the track.
  342. *
  343. * @returns {string}
  344. */
  345. _getStatus() {
  346. const { enabled, muted, readyState } = this.track;
  347. return `readyState: ${readyState}, muted: ${muted}, enabled: ${enabled}`;
  348. }
  349. /**
  350. * Initializes trackStreamingStatusImpl.
  351. */
  352. _initTrackStreamingStatus() {
  353. const config = this.conference.options.config;
  354. this._trackStreamingStatus = TrackStreamingStatus.ACTIVE;
  355. this._trackStreamingStatusImpl = new TrackStreamingStatusImpl(
  356. this.rtc,
  357. this.conference,
  358. this,
  359. {
  360. // These options are not public API, leaving it here only as an entry point through config for
  361. // tuning up purposes. Default values should be adjusted as soon as optimal values are discovered.
  362. p2pRtcMuteTimeout: config._p2pConnStatusRtcMuteTimeout,
  363. rtcMuteTimeout: config._peerConnStatusRtcMuteTimeout,
  364. outOfForwardedSourcesTimeout: config._peerConnStatusOutOfLastNTimeout
  365. });
  366. this._trackStreamingStatusImpl.init();
  367. // In some edge cases, both browser 'unmute' and bridge's forwarded sources events are received before a
  368. // LargeVideoUpdate is scheduled for auto-pinning a new screenshare track. If there are no layout changes and
  369. // no further track events are received for the SS track, a black tile will be displayed for screenshare on
  370. // stage. Fire a TRACK_STREAMING_STATUS_CHANGED event if the media is already being received for the remote
  371. // track to prevent this from happening.
  372. !this._trackStreamingStatusImpl.isVideoTrackFrozen()
  373. && this.rtc.eventEmitter.emit(
  374. JitsiTrackEvents.TRACK_STREAMING_STATUS_CHANGED,
  375. this,
  376. this._trackStreamingStatus);
  377. }
  378. /**
  379. * Disposes trackStreamingStatusImpl and clears trackStreamingStatus.
  380. */
  381. _disposeTrackStreamingStatus() {
  382. if (this._trackStreamingStatusImpl) {
  383. this._trackStreamingStatusImpl.dispose();
  384. this._trackStreamingStatusImpl = null;
  385. this._trackStreamingStatus = null;
  386. }
  387. }
  388. /**
  389. * Updates track's streaming status.
  390. *
  391. * @param {string} state the current track streaming state. {@link TrackStreamingStatus}.
  392. */
  393. _setTrackStreamingStatus(status) {
  394. this._trackStreamingStatus = status;
  395. }
  396. /**
  397. * Returns track's streaming status.
  398. *
  399. * @returns {string} the streaming status <tt>TrackStreamingStatus</tt> of the track. Returns null
  400. * if trackStreamingStatusImpl hasn't been initialized.
  401. *
  402. * {@link TrackStreamingStatus}.
  403. */
  404. getTrackStreamingStatus() {
  405. return this._trackStreamingStatus;
  406. }
  407. /**
  408. * Clears the timestamp of when the track entered forwarded sources.
  409. */
  410. _clearEnteredForwardedSourcesTimestamp() {
  411. this._enteredForwardedSourcesTimestamp = null;
  412. }
  413. /**
  414. * Updates the timestamp of when the track entered forwarded sources.
  415. *
  416. * @param {number} timestamp the time in millis
  417. */
  418. _setEnteredForwardedSourcesTimestamp(timestamp) {
  419. this._enteredForwardedSourcesTimestamp = timestamp;
  420. }
  421. /**
  422. * Returns the timestamp of when the track entered forwarded sources.
  423. *
  424. * @returns {number} the time in millis
  425. */
  426. _getEnteredForwardedSourcesTimestamp() {
  427. return this._enteredForwardedSourcesTimestamp;
  428. }
  429. /**
  430. * Creates a text representation of this remote track instance.
  431. * @return {string}
  432. */
  433. toString() {
  434. return `RemoteTrack[userID: ${this.getParticipantId()}, type: ${this.getType()}, ssrc: ${
  435. this.getSSRC()}, p2p: ${this.isP2P}, sourceName: ${this._sourceName}, status: {${this._getStatus()}}]`;
  436. }
  437. }