Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

JitsiRemoteTrack.js 15KB

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