Jitsi Meet - Secure, Simple and Scalable Video Conferences that you use as a standalone app or embed in your web application.
TypeScript debiandeep-videojitsijitsi-meetscalable-video-conferencessfuvideovideo-communicationvideo-conferencingwebrtc
feat(rtcstats): use rtcstats from lib-jitsi-meet (#13693)
Andrei Gavrilescu77d299338a93
diff --git a/react/features/base/lib-jitsi-meet/index.ts b/react/features/base/lib-jitsi-meet/index.tsindex 3b54d1ff7b..b83f6b85ce 100644--- a/react/features/base/lib-jitsi-meet/index.ts+++ b/react/features/base/lib-jitsi-meet/index.ts@@ -22,3 +22,4 @@ export const JitsiRecordingConstants = JitsiMeetJS.constants.recording;export const JitsiSIPVideoGWStatus = JitsiMeetJS.constants.sipVideoGW;export const JitsiTrackErrors = JitsiMeetJS.errors.track;export const JitsiTrackEvents = JitsiMeetJS.events.track;+export const RTCStatsEvents = JitsiMeetJS.events.rtcstats;diff --git a/react/features/base/logging/JitsiMeetLogStorage.ts b/react/features/base/logging/JitsiMeetLogStorage.tsindex be20a56741..ad016128ba 100644--- a/react/features/base/logging/JitsiMeetLogStorage.ts+++ b/react/features/base/logging/JitsiMeetLogStorage.ts@@ -1,6 +1,6 @@import { IStore } from '../../app/types';import RTCStats from '../../rtcstats/RTCStats';-import { canSendRtcstatsData } from '../../rtcstats/functions';+import { isRTCStatsEnabled } from '../../rtcstats/functions';import { getCurrentConference } from '../conference/functions';/**@@ -60,7 +60,7 @@ export default class JitsiMeetLogStorage {// Saving the logs in RTCStats is a new feature and so there is no prior behavior that needs to be maintained.// That said, this is still experimental and needs to be rolled out gradually so we want this to be off by// default.- return config?.analytics?.rtcstatsStoreLogs && canSendRtcstatsData(this.getState());+ return config?.analytics?.rtcstatsStoreLogs && isRTCStatsEnabled(this.getState());}/**diff --git a/react/features/rtcstats/RTCStats.ts b/react/features/rtcstats/RTCStats.tsindex 241a849cd0..bff467d627 100644--- a/react/features/rtcstats/RTCStats.ts+++ b/react/features/rtcstats/RTCStats.ts@@ -5,166 +5,40 @@ import {PC_STATE_FAILED// @ts-expect-error} from '@jitsi/rtcstats/events';-// @ts-expect-error-import rtcstatsInit from '@jitsi/rtcstats/rtcstats';-// @ts-expect-error-import traceInit from '@jitsi/rtcstats/trace-ws';-/* eslint-enable lines-around-comment */-import { createRTCStatsTraceCloseEvent } from '../analytics/AnalyticsEvents';-import { sendAnalytics } from '../analytics/functions';+import JitsiMeetJS, { RTCStatsEvents } from '../base/lib-jitsi-meet';import logger from './logger';import {DominantSpeakerData,E2ERTTData,FaceLandmarksData,- InitOptions,VideoTypeData} from './types';/**- * Filter out RTCPeerConnection that are created by callstats.io.- *- * @param {*} config - Config object sent to the PC c'tor.- * @returns {boolean}- */-function connectionFilter(config: any) {- if (config?.iceServers[0] && config.iceServers[0].urls) {- for (const iceUrl of config.iceServers[0].urls) {- if (iceUrl.indexOf('callstats.io') >= 0) {- return true;- }- }- }-}--/**- * Class that controls the rtcstats flow, because it overwrites and proxies global function it should only be- * initialized once.+ * Handle lib-jitsi-meet rtcstats events and send jitsi-meet specific statistics.*/class RTCStats {- trace: any;- options?: InitOptions;- isPeerConnectionWrapped = false;- connStateEvents: any = [];+ private _connStateEvents: Array<any> = [];+ private _initialized = false;/**- * Initialize the rtcstats components, if the options have changed.+ * Handles rtcstats events.*- * @param {Oject} newOptions -.* @returns {void}*/- maybeInit(newOptions: InitOptions) {- const oldOptions = this.options;- const changed = !oldOptions || (oldOptions.endpoint !== newOptions.endpoint- || oldOptions.meetingFqn !== newOptions.meetingFqn- || oldOptions.pollInterval !== newOptions.pollInterval- || oldOptions.sendSdp !== newOptions.sendSdp- || oldOptions.useLegacy !== newOptions.useLegacy);+ init() {+ this._connStateEvents = [];- if (changed) {- this.reset();-- if (newOptions.meetingFqn && newOptions.endpoint) {- this.init(newOptions);- } else {- logger.warn('RTCStats is enabled but it has not been configured.');- }+ if (!this._initialized) {+ JitsiMeetJS.rtcstats.on(+ RTCStatsEvents.RTC_STATS_PC_EVENT,+ (pcEvent: any) => this.handleRTCStatsEvent(pcEvent));+ this._initialized = true;}}- /**- * Wrapper method for the underlying trace object to be used as a static reference from inside the wrapped- * PeerConnection.- *- * @param {any[]} data - The stats entry to send to the rtcstats endpoint.- * @returns {void}- */- statsEntry(...data: any[]) {- this.trace?.statsEntry(...data);- }-- /**- * Initialize the rtcstats components. First off we initialize the trace, which is a wrapped websocket- * that does the actual communication with the server. Secondly, the rtcstats component is initialized,- * it overwrites GUM and PeerConnection global functions and adds a proxy over them used to capture stats.- * Note, lib-jitsi-meet takes references to these methods before initializing so the init method needs to be- * loaded before it does.- *- * @param {Object} options -.- * @param {string} options.endpoint - The Amplitude app key required.- * @param {string} options.meetingFqn - The meeting fqn.- * @param {boolean} options.useLegacy - Switch to legacy chrome webrtc statistics. Parameter will only have- * an effect on chrome based applications.- * @param {number} options.pollInterval - The getstats poll interval in ms.- * @param {boolean} options.sendSdp - Determines if the client sends SDP to the rtcstats server.- * @returns {void}- */- init(options: InitOptions) {-- const { endpoint, meetingFqn, useLegacy, pollInterval, sendSdp } = options;-- const traceOptions = {- endpoint,- meetingFqn,- onCloseCallback: this.handleTraceWSClose.bind(this),- useLegacy- };-- this.trace = traceInit(traceOptions);- if (!this.isPeerConnectionWrapped) {- const rtcstatsOptions = {- connectionFilter,- pollInterval,- useLegacy,- sendSdp,- eventCallback: this.handleRtcstatsEvent.bind(this)- };-- const statsEntryCallback = { statsEntry: this.statsEntry.bind(this) };-- rtcstatsInit(statsEntryCallback, rtcstatsOptions);- this.isPeerConnectionWrapped = true;- }- this.options = options;- }-- /**- * Check whether or not the RTCStats is initialized.- *- * @returns {boolean}- */- isInitialized() {- return this.options !== undefined;- }-- /**- * Resets the rtcstats.- *- * @returns {void}- */- reset() {- delete this.options;-- if (this.trace) {- this.trace.close();- delete this.trace;- }- }-- /**- * Send identity data to rtcstats server, this will be reflected in the identity section of the stats dump.- * It can be generally used to send additional metadata that might be relevant such as amplitude user data- * or deployment specific information.- *- * @param {any} identityData - Metadata object to send as identity.- * @returns {void}- */- sendIdentityData(identityData: any) {- this.trace?.identity('identity', null, identityData);- }-/*** Send console logs to rtcstats server.*@@ -172,7 +46,7 @@ class RTCStats {* @returns {void}*/sendLogs(logEntries: Array<string | any>) {- this.trace?.statsEntry('logs', null, logEntries);+ JitsiMeetJS.rtcstats.sendStatsEntry('logs', logEntries);}/**@@ -182,7 +56,7 @@ class RTCStats {* @returns {void}*/sendDominantSpeakerData(dominantSpeakerData: DominantSpeakerData) {- this.trace?.statsEntry('dominantSpeaker', null, dominantSpeakerData);+ JitsiMeetJS.rtcstats.sendStatsEntry('dominantSpeaker', dominantSpeakerData);}/**@@ -191,8 +65,8 @@ class RTCStats {* @param {Object} e2eRttData - The object that holds the e2e data.* @returns {void}*/- sendE2eRttData(e2eRttData: E2ERTTData) {- this.trace?.statsEntry('e2eRtt', null, e2eRttData);+ sendE2ERTTData(e2eRttData: E2ERTTData) {+ JitsiMeetJS.rtcstats.sendStatsEntry('e2eRtt', e2eRttData);}/**@@ -203,7 +77,7 @@ class RTCStats {* @returns {void}*/sendConferenceTimestamp(timestamp: number) {- this.trace?.statsEntry('conferenceStartTimestamp', null, timestamp);+ JitsiMeetJS.rtcstats.sendStatsEntry('conferenceStartTimestamp', timestamp);}/**@@ -213,7 +87,7 @@ class RTCStats {* @returns {void}*/sendVideoTypeData(videoTypeData: VideoTypeData) {- this.trace?.statsEntry('setVideoType', null, videoTypeData);+ JitsiMeetJS.rtcstats.sendStatsEntry('setVideoType', videoTypeData);}/**@@ -223,53 +97,32 @@ class RTCStats {* @returns {void}*/sendFaceLandmarksData(faceLandmarksData: FaceLandmarksData) {- this.trace?.statsEntry('faceLandmarks', null, faceLandmarksData);- }-- /**- * Connect to the rtcstats server instance. Stats (data obtained from getstats) won't be send until the- * connect successfully initializes, however calls to GUM are recorded in an internal buffer even if not- * connected and sent once it is established.- *- * @param {boolean} isBreakoutRoom - Flag indicating if the user is in a breakout room.- * @returns {void}- */- connect(isBreakoutRoom: boolean) {- this.trace?.connect(isBreakoutRoom);- }-- /**- * Self explanatory; closes the web socked connection.- * Note, at the point of writing this documentation there was no method to reset the function overwrites,- * thus even if the websocket is closed the global function proxies are still active but send no data,- * this shouldn't influence the normal flow of the application.- *- * @returns {void}- */- close() {- this.trace?.close();+ JitsiMeetJS.rtcstats.sendStatsEntry('faceLandmarks', faceLandmarksData);}/*** RTCStats client can notify the APP of any PeerConnection related event that occurs.*- * @param {Object} event - Rtcstats event.+ * @param {Object} event - The PeerConnection event.+ * @param {string} event.type - The event type.+ * @param {Object} event.body - Event body.+ * @param {string} event.body.isP2P - PeerConnection type.+ * @param {string} event.body.state - PeerConnection state change which triggered the event.* @returns {void}*/- handleRtcstatsEvent(event: any) {+ handleRTCStatsEvent(event: any) {switch (event.type) {case PC_CON_STATE_CHANGE: {- const { body: { isP2P, state } = { state: null,- isP2P: null } } = event;+ const { body: { isP2P = null, state = null } } = event;- this.connStateEvents.push(event.body);+ this._connStateEvents.push(event.body);// We only report PC related connection issues. If the rtcstats websocket is not connected at this point// it usually means that none of our services can be reached i.e. there's problem with the internet// connection and not necessarily with reaching the JVB (due to a firewall or other reasons).- if (state === PC_STATE_FAILED && this.trace.isConnected()) {+ if (state === PC_STATE_FAILED) {const connectionType = isP2P ? 'P2P' : 'JVB';- const wasConnected = this.connStateEvents.some((connectionEvent: { isP2P: any; state: string; }) =>+ const wasConnected = this._connStateEvents.some((connectionEvent: { isP2P: any; state: string; }) =>(connectionEvent.isP2P === isP2P) && (connectionEvent.state === PC_STATE_CONNECTED));logger.info(`${connectionType} PeerConnection failed, previously connected: ${wasConnected}`);@@ -283,21 +136,6 @@ class RTCStats {}}}-- /**- * The way rtcstats is currently designed the ws wouldn't normally be closed by the application logic but rather- * by the page being closed/reloaded. Using this assumption any onclose event is most likely something abnormal- * that happened on the ws. We then track this in order to determine how many rtcstats connection were closed- * prematurely.- *- * @param {Object} closeEvent - Event sent by ws onclose.- * @returns {void}- */- handleTraceWSClose(closeEvent: any) {- logger.info('RTCStats trace ws closed', closeEvent);-- sendAnalytics(createRTCStatsTraceCloseEvent(closeEvent));- }}export default new RTCStats();diff --git a/react/features/rtcstats/functions.ts b/react/features/rtcstats/functions.tsindex dc94df3c27..83d06877ac 100644--- a/react/features/rtcstats/functions.ts+++ b/react/features/rtcstats/functions.ts@@ -1,112 +1,29 @@-// @ts-expect-error-import { jitsiLocalStorage } from '@jitsi/js-utils';-import { getAmplitudeIdentity } from '../analytics/functions';-import { IStore } from '../app/types';import { IStateful } from '../base/app/types';-import { getAnalyticsRoomName, getConferenceOptions } from '../base/conference/functions';-import { getLocalParticipant } from '../base/participants/functions';import { toState } from '../base/redux/functions';-import RTCStats from './RTCStats';-import logger from './logger';-/*** Checks whether rtcstats is enabled or not.** @param {IStateful} stateful - The redux store or {@code getState} function.* @returns {boolean}*/-export function isRtcstatsEnabled(stateful: IStateful) {+export function isRTCStatsEnabled(stateful: IStateful) {const state = toState(stateful);const { analytics } = state['features/base/config'];return analytics?.rtcstatsEnabled ?? false;}-/**- * Can the rtcstats service send data.- *- * @param {IStateful} stateful - The redux store or {@code getState} function.- * @returns {boolean}- */-export function canSendRtcstatsData(stateful: IStateful) {- return isRtcstatsEnabled(stateful) && RTCStats.isInitialized();-}--type Identity = {- isBreakoutRoom: boolean;-- // Unique identifier for a conference session, not to be confused with meeting name- // i.e. If all participants leave a meeting it will have a different value on the next join.- meetingUniqueId?: string;- roomId?: string;-};--/**- * Connects to the rtcstats service and sends the identity data.- *- * @param {IStore} store - Redux Store.- * @param {Identity} identity - Identity data for the client.- * @returns {void}- */-export function connectAndSendIdentity({ getState, dispatch }: IStore, identity: Identity) {- const state = getState();-- if (canSendRtcstatsData(state)) {-- // Once the conference started connect to the rtcstats server and send data.- try {- RTCStats.connect(identity.isBreakoutRoom);- const localParticipant = getLocalParticipant(state);- const options = getConferenceOptions(state);-- // The current implementation of rtcstats-server is configured to send data to amplitude, thus- // we add identity specific information so we can correlate on the amplitude side. If amplitude is- // not configured an empty object will be sent.- // The current configuration of the conference is also sent as metadata to rtcstats server.- // This is done in order to facilitate queries based on different conference configurations.- // e.g. Find all RTCPeerConnections that connect to a specific shard or were created in a- // conference with a specific version.- let displayName = jitsiLocalStorage.getItem('callStatsUserName');-- if (options.statisticsId || options.statisticsDisplayName) {- if (options.statisticsId && options.statisticsDisplayName) {- displayName = `${options.statisticsDisplayName} (${options.statisticsId})`;- } else {- displayName = options.statisticsId || options.statisticsDisplayName;- }- }-- RTCStats.sendIdentityData({- ...getAmplitudeIdentity(),- ...options,- endpointId: localParticipant?.id,- confName: getAnalyticsRoomName(state, dispatch),- displayName,- ...identity- });- } catch (error) {- // If the connection failed do not impact jitsi-meet just silently fail.- logger.error('RTCStats connect failed with: ', error);- }- }--}-/*** Checks if the faceLandmarks data can be sent to the rtcstats server.** @param {IStateful} stateful - The redux store or {@code getState} function.* @returns {boolean}*/-export function canSendFaceLandmarksRtcstatsData(stateful: IStateful): boolean {+export function canSendFaceLandmarksRTCStatsData(stateful: IStateful): boolean {const state = toState(stateful);const { faceLandmarks } = state['features/base/config'];- if (faceLandmarks?.enableRTCStats && canSendRtcstatsData(state)) {- return true;- }-- return false;+ return Boolean(faceLandmarks?.enableRTCStats && isRTCStatsEnabled(state));}diff --git a/react/features/rtcstats/middleware.ts b/react/features/rtcstats/middleware.tsindex 31b869bb32..0953c046cc 100644--- a/react/features/rtcstats/middleware.ts+++ b/react/features/rtcstats/middleware.ts@@ -4,27 +4,19 @@ import { IStore } from '../app/types';import {CONFERENCE_JOINED,CONFERENCE_TIMESTAMP_CHANGED,- CONFERENCE_UNIQUE_ID_SET,- CONFERENCE_WILL_LEAVE,E2E_RTT_CHANGED} from '../base/conference/actionTypes';-import { LIB_WILL_INIT } from '../base/lib-jitsi-meet/actionTypes';import { DOMINANT_SPEAKER_CHANGED } from '../base/participants/actionTypes';import MiddlewareRegistry from '../base/redux/MiddlewareRegistry';import { TRACK_ADDED, TRACK_UPDATED } from '../base/tracks/actionTypes';-import { getCurrentRoomId, isInBreakoutRoom } from '../breakout-rooms/functions';-import { extractFqnFromPath } from '../dynamic-branding/functions.any';import { ADD_FACE_LANDMARKS } from '../face-landmarks/actionTypes';import { FaceLandmarks } from '../face-landmarks/types';import RTCStats from './RTCStats';import {- canSendFaceLandmarksRtcstatsData,- canSendRtcstatsData,- connectAndSendIdentity,- isRtcstatsEnabled+ canSendFaceLandmarksRTCStatsData,+ isRTCStatsEnabled} from './functions';-import logger from './logger';/*** Middleware which intercepts lib-jitsi-meet initialization and conference join in order init the@@ -36,77 +28,16 @@ import logger from './logger';MiddlewareRegistry.register((store: IStore) => (next: Function) => (action: AnyAction) => {const { getState } = store;const state = getState();- const config = state['features/base/config'];- const { analytics } = config;switch (action.type) {- case LIB_WILL_INIT: {- if (isRtcstatsEnabled(state)) {- // RTCStats "proxies" WebRTC functions such as GUM and RTCPeerConnection by rewriting the global- // window functions. Because lib-jitsi-meet uses references to those functions that are taken on- // init, we need to add these proxies before it initializes, otherwise lib-jitsi-meet will use the- // original non proxy versions of these functions.- try {- // Default poll interval is 10000ms and standard stats will be used, if not provided in the config.- const pollInterval = analytics?.rtcstatsPollInterval || 10000;- const useLegacy = analytics?.rtcstatsUseLegacy || false;- const sendSdp = analytics?.rtcstatsSendSdp || false;-- // Initialize but don't connect to the rtcstats server wss, as it will start sending data for all- // media calls made even before the conference started.-- RTCStats.maybeInit({- endpoint: analytics?.rtcstatsEndpoint,- meetingFqn: extractFqnFromPath(state),- useLegacy,- pollInterval,- sendSdp- });- } catch (error) {- logger.error('Failed to initialize RTCStats: ', error);- }- } else {- RTCStats.reset();- }- break;- }-- // Used for connecting to rtcstats server when joining a breakout room.- // Breakout rooms do not have a meetingUniqueId.case CONFERENCE_JOINED: {- if (isInBreakoutRoom(getState())) {- connectAndSendIdentity(- store,- {- isBreakoutRoom: true,- roomId: getCurrentRoomId(getState())- }- );- }- break;- }-- // Used for connecting to rtcstats server when joining the main room.- // Using this event to be sure the meetingUniqueId can be retrieved.- case CONFERENCE_UNIQUE_ID_SET: {- if (!isInBreakoutRoom(getState())) {- // Unique identifier for a conference session, not to be confused with meeting name- // i.e. If all participants leave a meeting it will have a different value on the next join.- const { conference } = action;- const meetingUniqueId = conference?.getMeetingUniqueId();-- connectAndSendIdentity(- store,- {- isBreakoutRoom: false,- meetingUniqueId- }- );+ if (isRTCStatsEnabled(state)) {+ RTCStats.init();}break;}case TRACK_ADDED: {- if (canSendRtcstatsData(state)) {+ if (isRTCStatsEnabled(state)) {const jitsiTrack = action?.track?.jitsiTrack;const { ssrc, videoType } = jitsiTrack || { };@@ -121,7 +52,7 @@ MiddlewareRegistry.register((store: IStore) => (next: Function) => (action: AnyAbreak;}case TRACK_UPDATED: {- if (canSendRtcstatsData(state)) {+ if (isRTCStatsEnabled(state)) {const { videoType, jitsiTrack, muted } = action?.track || { };const { ssrc, isLocal, videoType: trackVideoType, conference } = jitsiTrack || { };@@ -146,7 +77,7 @@ MiddlewareRegistry.register((store: IStore) => (next: Function) => (action: AnyAbreak;}case DOMINANT_SPEAKER_CHANGED: {- if (canSendRtcstatsData(state)) {+ if (isRTCStatsEnabled(state)) {const { id, previousSpeakers, silence } = action.participant;RTCStats.sendDominantSpeakerData({@@ -157,10 +88,10 @@ MiddlewareRegistry.register((store: IStore) => (next: Function) => (action: AnyAbreak;}case E2E_RTT_CHANGED: {- if (canSendRtcstatsData(state)) {+ if (isRTCStatsEnabled(state)) {const { participant, rtt } = action.e2eRtt;- RTCStats.sendE2eRttData({+ RTCStats.sendE2ERTTData({remoteEndpointId: participant.getId(),rtt,remoteRegion: participant.getProperty('region')@@ -169,7 +100,7 @@ MiddlewareRegistry.register((store: IStore) => (next: Function) => (action: AnyAbreak;}case ADD_FACE_LANDMARKS: {- if (canSendFaceLandmarksRtcstatsData(state)) {+ if (canSendFaceLandmarksRTCStatsData(state)) {const { duration, faceExpression, timestamp } = action.faceLandmarks as FaceLandmarks;const durationSeconds = Math.round(duration / 1000);@@ -182,19 +113,13 @@ MiddlewareRegistry.register((store: IStore) => (next: Function) => (action: AnyAbreak;}case CONFERENCE_TIMESTAMP_CHANGED: {- if (canSendRtcstatsData(state)) {+ if (isRTCStatsEnabled(state)) {const { conferenceTimestamp } = action;RTCStats.sendConferenceTimestamp(conferenceTimestamp);}break;}- case CONFERENCE_WILL_LEAVE: {- if (canSendRtcstatsData(state)) {- RTCStats.close();- }- break;- }}return next(action);diff --git a/react/features/rtcstats/types.ts b/react/features/rtcstats/types.tsindex a07a00dc2d..7dc399ddef 100644--- a/react/features/rtcstats/types.ts+++ b/react/features/rtcstats/types.ts@@ -1,11 +1,3 @@-export type InitOptions = {- endpoint?: string;- meetingFqn: string;- pollInterval: number;- sendSdp: boolean;- useLegacy: boolean;-};-export type VideoTypeData = {ssrc: number;videoType: string;