-
Notifications
You must be signed in to change notification settings - Fork 472
/
DefaultStatsCollector.ts
481 lines (431 loc) · 16.8 KB
/
DefaultStatsCollector.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import AudioVideoController from '../audiovideocontroller/AudioVideoController';
import BrowserBehavior from '../browserbehavior/BrowserBehavior';
import Direction from '../clientmetricreport/ClientMetricReportDirection';
import MediaType from '../clientmetricreport/ClientMetricReportMediaType';
import DefaultClientMetricReport from '../clientmetricreport/DefaultClientMetricReport';
import StreamMetricReport from '../clientmetricreport/StreamMetricReport';
import Logger from '../logger/Logger';
import MeetingSessionLifecycleEvent from '../meetingsession/MeetingSessionLifecycleEvent';
import MeetingSessionLifecycleEventCondition from '../meetingsession/MeetingSessionLifecycleEventCondition';
import MeetingSessionStatus from '../meetingsession/MeetingSessionStatus';
import IntervalScheduler from '../scheduler/IntervalScheduler';
import SignalingClient from '../signalingclient/SignalingClient';
import {
SdkClientMetricFrame,
SdkMetric,
SdkStreamMetricFrame,
} from '../signalingprotocol/SignalingProtocol.js';
import { Maybe } from '../utils/Types';
import VideoStreamIndex from '../videostreamindex/VideoStreamIndex';
import AudioLogEvent from './AudioLogEvent';
import StatsCollector from './StatsCollector';
import VideoLogEvent from './VideoLogEvent';
// eslint-disable-next-line
type RawMetricReport = any;
// eslint-disable-next-line
type StatsReportItem = any;
export default class DefaultStatsCollector implements StatsCollector {
private static readonly INTERVAL_MS = 1000;
private static readonly FIREFOX_UPDATED_GET_STATS_VERSION = '66.0.0';
private static readonly CLIENT_TYPE = 'amazon-chime-sdk-js';
private intervalScheduler: IntervalScheduler | null = null;
private signalingClient: SignalingClient;
private videoStreamIndex: VideoStreamIndex;
private clientMetricReport: DefaultClientMetricReport;
constructor(
private audioVideoController: AudioVideoController,
private logger: Logger,
private browserBehavior: BrowserBehavior,
private readonly interval: number = DefaultStatsCollector.INTERVAL_MS
) {}
// TODO: Update toAttribute() and toSuffix() methods to convert raw data to a required type.
toAttribute(str: string): string {
return this.toSuffix(str).substring(1);
}
private toSuffix(str: string): string {
if (str.toLowerCase() === str) {
// e.g. lower_case -> _lower_case
return `_${str}`;
} else if (str.toUpperCase() === str) {
// e.g. UPPER_CASE -> _upper_case
return `_${str.toLowerCase()}`;
} else {
// e.g. CamelCaseWithCAPS -> _camel_case_with_caps
return str
.replace(/([A-Z][a-z]+)/g, function ($1) {
return `_${$1}`;
})
.replace(/([A-Z][A-Z]+)/g, function ($1) {
return `_${$1}`;
})
.toLowerCase();
}
}
// TODO: Implement metricsAddTime() and metricsLogEvent().
metricsAddTime = (
_name: string,
_duration: number,
_attributes?: { [id: string]: string }
): void => {};
metricsLogEvent = (_name: string, _attributes: { [id: string]: string }): void => {};
logLatency(eventName: string, timeMs: number, attributes?: { [id: string]: string }): void {
const event = this.toSuffix(eventName);
this.logEventTime('meeting' + event, timeMs, attributes);
}
logStateTimeout(stateName: string, attributes?: { [id: string]: string }): void {
const state = this.toSuffix(stateName);
this.logEvent('meeting_session_state_timeout', {
...attributes,
state: `state${state}`,
});
}
logAudioEvent(eventName: AudioLogEvent, attributes?: { [id: string]: string }): void {
const event = 'audio' + this.toSuffix(AudioLogEvent[eventName]);
this.logEvent(event, attributes);
}
logVideoEvent(eventName: VideoLogEvent, attributes?: { [id: string]: string }): void {
const event = 'video' + this.toSuffix(VideoLogEvent[eventName]);
this.logEvent(event, attributes);
}
private logEventTime(
eventName: string,
timeMs: number,
attributes: { [id: string]: string } = {}
): void {
const finalAttributes = {
...attributes,
call_id: this.audioVideoController.configuration.meetingId,
client_type: DefaultStatsCollector.CLIENT_TYPE,
metric_type: 'latency',
};
this.logger.debug(() => {
return `[DefaultStatsCollector] ${eventName}: ${JSON.stringify(finalAttributes)}`;
});
this.metricsAddTime(eventName, timeMs, finalAttributes);
}
logMeetingSessionStatus(status: MeetingSessionStatus): void {
// TODO: Generate the status event name given the status code.
const statusEventName = `${status.statusCode()}`;
this.logEvent(statusEventName);
const statusAttribute: { [id: string]: string } = {
status: statusEventName,
status_code: `${status.statusCode()}`,
};
this.logEvent('meeting_session_status', statusAttribute);
if (status.isTerminal()) {
this.logEvent('meeting_session_stopped', statusAttribute);
}
if (status.isAudioConnectionFailure()) {
this.logEvent('meeting_session_audio_failed', statusAttribute);
}
if (status.isFailure()) {
this.logEvent('meeting_session_failed', statusAttribute);
}
}
logLifecycleEvent(
lifecycleEvent: MeetingSessionLifecycleEvent,
condition: MeetingSessionLifecycleEventCondition
): void {
const attributes: { [id: string]: string } = {
lifecycle_event: `lifecycle${this.toSuffix(MeetingSessionLifecycleEvent[lifecycleEvent])}`,
lifecycle_event_code: `${lifecycleEvent}`,
lifecycle_event_condition: `condition${this.toSuffix(
MeetingSessionLifecycleEventCondition[condition]
)}`,
lifecycle_event_condition_code: `${condition}`,
};
this.logEvent('meeting_session_lifecycle', attributes);
}
private logEvent(eventName: string, attributes: { [id: string]: string } = {}): void {
const finalAttributes = {
...attributes,
call_id: this.audioVideoController.configuration.meetingId,
client_type: DefaultStatsCollector.CLIENT_TYPE,
};
this.logger.debug(() => {
return `[DefaultStatsCollector] ${eventName}: ${JSON.stringify(finalAttributes)}`;
});
this.metricsLogEvent(eventName, finalAttributes);
}
/**
* WEBRTC METRICS COLLECTION.
*/
start(
signalingClient: SignalingClient,
videoStreamIndex: VideoStreamIndex,
clientMetricReport?: DefaultClientMetricReport
): boolean {
if (this.intervalScheduler) {
return false;
}
this.logger.info('Starting DefaultStatsCollector');
this.signalingClient = signalingClient;
this.videoStreamIndex = videoStreamIndex;
if (clientMetricReport) {
this.clientMetricReport = clientMetricReport;
} else {
this.clientMetricReport = new DefaultClientMetricReport(
this.logger,
this.videoStreamIndex,
this.audioVideoController.configuration.credentials.attendeeId
);
}
this.intervalScheduler = new IntervalScheduler(this.interval);
this.intervalScheduler.start(() => {
this.getStatsWrapper();
});
return true;
}
stop(): void {
this.logger.info('Stopping DefaultStatsCollector');
if (this.intervalScheduler) {
this.intervalScheduler.stop();
}
this.intervalScheduler = null;
}
/**
* Convert raw metrics to client metric report.
*/
private updateMetricValues(rawMetricReport: RawMetricReport, isStream: boolean): void {
const metricReport = isStream
? this.clientMetricReport.streamMetricReports[Number(rawMetricReport.ssrc)]
: this.clientMetricReport.globalMetricReport;
let metricMap: {
[id: string]: {
transform?: (metricName?: string, ssrc?: number) => number;
type?: SdkMetric.Type;
source?: string;
};
};
if (isStream) {
metricMap = this.clientMetricReport.getMetricMap(
(metricReport as StreamMetricReport).mediaType,
(metricReport as StreamMetricReport).direction
);
} else {
metricMap = this.clientMetricReport.getMetricMap();
}
for (const rawMetric in rawMetricReport) {
if (rawMetric in metricMap) {
metricReport.previousMetrics[rawMetric] = metricReport.currentMetrics[rawMetric];
metricReport.currentMetrics[rawMetric] = rawMetricReport[rawMetric];
}
}
}
private updateRawMetricReport(newReport: RTCStatsReport): void {
const rawMetricReport = this.clientMetricReport.rawMetricReport;
rawMetricReport.previousMetrics = rawMetricReport.currentMetrics;
rawMetricReport.currentMetrics = newReport;
}
private processRawMetricReports(rawMetricReports: RawMetricReport[]): void {
this.clientMetricReport.currentSsrcs = {};
const timeStamp = Date.now();
for (const rawMetricReport of rawMetricReports) {
const isStream = this.isStreamRawMetricReport(rawMetricReport.type);
if (isStream) {
const existingStreamMetricReport = this.clientMetricReport.streamMetricReports[
Number(rawMetricReport.ssrc)
];
if (!existingStreamMetricReport) {
const streamMetricReport = new StreamMetricReport();
streamMetricReport.mediaType = this.getMediaType(rawMetricReport);
streamMetricReport.direction = this.getDirectionType(rawMetricReport);
if (!this.videoStreamIndex.allStreams().empty()) {
streamMetricReport.streamId = this.videoStreamIndex.streamIdForSSRC(
Number(rawMetricReport.ssrc)
);
}
this.clientMetricReport.streamMetricReports[
Number(rawMetricReport.ssrc)
] = streamMetricReport;
} else {
// Update stream ID in case we have overriden it locally in the case of remote video
// updates completed without a negotiation
existingStreamMetricReport.streamId = this.videoStreamIndex.streamIdForSSRC(
Number(rawMetricReport.ssrc)
);
}
this.clientMetricReport.currentSsrcs[Number(rawMetricReport.ssrc)] = 1;
}
this.updateMetricValues(rawMetricReport, isStream);
}
this.clientMetricReport.removeDestroyedSsrcs();
this.clientMetricReport.previousTimestampMs = this.clientMetricReport.currentTimestampMs;
this.clientMetricReport.currentTimestampMs = timeStamp;
this.clientMetricReport.print();
}
/**
* Protobuf packaging.
*/
private addMetricFrame(
metricName: string,
clientMetricFrame: SdkClientMetricFrame,
metricSpec: {
transform?: (metricName?: string, ssrc?: number) => number;
type?: SdkMetric.Type;
source?: string;
},
ssrc?: number
): void {
const type = metricSpec.type;
const transform = metricSpec.transform;
const sourceMetric = metricSpec.source;
const streamMetricFramesLength = clientMetricFrame.streamMetricFrames.length;
const latestStreamMetricFrame =
clientMetricFrame.streamMetricFrames[streamMetricFramesLength - 1];
if (type) {
const metricFrame = SdkMetric.create();
metricFrame.type = type;
metricFrame.value = sourceMetric
? transform(sourceMetric, ssrc)
: transform(metricName, ssrc);
ssrc
? latestStreamMetricFrame.metrics.push(metricFrame)
: clientMetricFrame.globalMetrics.push(metricFrame);
}
}
private addGlobalMetricsToProtobuf(clientMetricFrame: SdkClientMetricFrame): void {
const metricMap = this.clientMetricReport.getMetricMap();
for (const metricName in this.clientMetricReport.globalMetricReport.currentMetrics) {
this.addMetricFrame(metricName, clientMetricFrame, metricMap[metricName]);
}
}
private addStreamMetricsToProtobuf(clientMetricFrame: SdkClientMetricFrame): void {
for (const ssrc in this.clientMetricReport.streamMetricReports) {
const streamMetricReport = this.clientMetricReport.streamMetricReports[ssrc];
const streamMetricFrame = SdkStreamMetricFrame.create();
streamMetricFrame.streamId = streamMetricReport.streamId;
streamMetricFrame.metrics = [];
clientMetricFrame.streamMetricFrames.push(streamMetricFrame);
const metricMap = this.clientMetricReport.getMetricMap(
streamMetricReport.mediaType,
streamMetricReport.direction
);
for (const metricName in streamMetricReport.currentMetrics) {
this.addMetricFrame(metricName, clientMetricFrame, metricMap[metricName], Number(ssrc));
}
}
}
private makeClientMetricProtobuf(): SdkClientMetricFrame {
const clientMetricFrame = SdkClientMetricFrame.create();
clientMetricFrame.globalMetrics = [];
clientMetricFrame.streamMetricFrames = [];
this.addGlobalMetricsToProtobuf(clientMetricFrame);
this.addStreamMetricsToProtobuf(clientMetricFrame);
return clientMetricFrame;
}
private sendClientMetricProtobuf(clientMetricFrame: SdkClientMetricFrame): void {
this.signalingClient.sendClientMetrics(clientMetricFrame);
}
/**
* Helper functions.
*/
private isStreamRawMetricReport(type: string): boolean {
return ['inbound-rtp', 'outbound-rtp', 'remote-inbound-rtp', 'remote-outbound-rtp'].includes(
type
);
}
private getMediaType(rawMetricReport: RawMetricReport): MediaType {
return rawMetricReport.mediaType === 'audio' ? MediaType.AUDIO : MediaType.VIDEO;
}
private getDirectionType(rawMetricReport: RawMetricReport): Direction {
return rawMetricReport.id.toLowerCase().indexOf('send') !== -1 ||
rawMetricReport.id.toLowerCase().indexOf('outbound') !== -1 ||
rawMetricReport.type === 'outbound-rtp'
? Direction.UPSTREAM
: Direction.DOWNSTREAM;
}
/**
* Metric report filter.
*/
isValidStandardRawMetric(rawMetricReport: RawMetricReport): boolean {
const valid: boolean =
rawMetricReport.type === 'inbound-rtp' ||
rawMetricReport.type === 'outbound-rtp' ||
rawMetricReport.type === 'remote-inbound-rtp' ||
rawMetricReport.type === 'remote-outbound-rtp' ||
(rawMetricReport.type === 'candidate-pair' && rawMetricReport.state === 'succeeded');
if (this.browserBehavior.hasFirefoxWebRTC()) {
if (
this.compareMajorVersion(DefaultStatsCollector.FIREFOX_UPDATED_GET_STATS_VERSION) === -1
) {
return valid;
} else {
return valid && rawMetricReport.isRemote === false;
}
}
return valid;
}
isValidSsrc(rawMetricReport: RawMetricReport): boolean {
let validSsrc = true;
if (
this.isStreamRawMetricReport(rawMetricReport.type) &&
this.getDirectionType(rawMetricReport) === Direction.DOWNSTREAM &&
this.getMediaType(rawMetricReport) === MediaType.VIDEO
) {
validSsrc = this.videoStreamIndex.streamIdForSSRC(Number(rawMetricReport.ssrc)) > 0;
}
return validSsrc;
}
isValidRawMetricReport(rawMetricReport: RawMetricReport): boolean {
return this.isValidStandardRawMetric(rawMetricReport) && this.isValidSsrc(rawMetricReport);
}
filterRawMetricReports(rawMetricReports: RawMetricReport[]): RawMetricReport[] {
const filteredRawMetricReports = [];
for (const rawMetricReport of rawMetricReports) {
if (this.isValidRawMetricReport(rawMetricReport)) {
filteredRawMetricReports.push(rawMetricReport);
}
}
return filteredRawMetricReports;
}
private handleRawMetricReports(rawMetricReports: RawMetricReport[]): void {
const filteredRawMetricReports = this.filterRawMetricReports(rawMetricReports);
this.logger.debug(() => {
return `Filtered raw metrics : ${JSON.stringify(filteredRawMetricReports)}`;
});
this.processRawMetricReports(filteredRawMetricReports);
const clientMetricFrame = this.makeClientMetricProtobuf();
this.sendClientMetricProtobuf(clientMetricFrame);
this.audioVideoController.forEachObserver(observer => {
Maybe.of(observer.metricsDidReceive).map(f =>
f.bind(observer)(this.clientMetricReport.clone())
);
});
}
/**
* Get raw webrtc metrics.
*/
private getStatsWrapper(): void {
if (!this.audioVideoController.rtcPeerConnection) {
return;
}
const rawMetricReports: RawMetricReport[] = [];
// @ts-ignore
this.audioVideoController.rtcPeerConnection
.getStats()
.then((report: RTCStatsReport) => {
this.updateRawMetricReport(report);
report.forEach((item: StatsReportItem) => {
rawMetricReports.push(item);
});
this.handleRawMetricReports(rawMetricReports);
})
.catch((error: Error) => {
this.logger.error(error.message);
});
}
private compareMajorVersion(version: string): number {
const currentMajorVersion = parseInt(this.browserBehavior.version().split('.')[0]);
const expectedMajorVersion = parseInt(version.split('.')[0]);
if (expectedMajorVersion === currentMajorVersion) {
return 0;
}
if (expectedMajorVersion > currentMajorVersion) {
return 1;
}
return -1;
}
}