forked from jitsi/rtcstats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrtcstats.js
719 lines (605 loc) · 27.6 KB
/
rtcstats.js
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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
/* eslint-disable prefer-rest-params */
/* eslint-disable no-param-reassign */
import { BrowserDetection } from '@jitsi/js-utils/browser-detection';
import { getLogger } from '@jitsi/logger';
const logger = getLogger('rtctstats');
import { PC_CON_STATE_CHANGE, PC_ICE_CON_STATE_CHANGE } from './events';
/**
* transforms a maplike to an object. Mostly for getStats + JSON.parse(JSON.stringify())
* @param {*} m
*/
function map2obj(m) {
if (!m.entries) {
return m;
}
const o = {};
m.forEach((v, k) => {
o[k] = v;
});
return o;
}
/**
*
* @param {*} pc
* @param {*} response
*/
function mangleChromeStats(pc, response) {
const standardReport = {};
const reports = response.result();
reports.forEach(report => {
const standardStats = {
id: report.id,
timestamp: report.timestamp.getTime(),
type: report.type
};
report.names().forEach(name => {
standardStats[name] = report.stat(name);
});
standardReport[standardStats.id] = standardStats;
});
return standardReport;
}
/**
* Apply a delta compression to the stats report. Reduces size by ~90%.
* To reduce further, report keys could be compressed.
* @param {*} oldStats
* @param {*} newStats
*/
function deltaCompression(oldStats, newStatsArg) {
const newStats = JSON.parse(JSON.stringify(newStatsArg));
// Go through each report of the newly fetches stats entry and compare it with the previous one (old)
// If a field value (e.g. ssrc.id) from the new report matches the corresponding one from the old report
// delete it.
// The new stats entry will be returned thus any reports from the old stats entry that are no longer found
// in the new one will me considered as removed.
// stats entries are expected to have the following format:
// {reportName1: {
// key1: value,
// key2: value2
// },
// reportName2: {
// key1: value,
// key2, value2,
// }}
Object.keys(newStats).forEach(id => {
const report = newStats[id];
delete report.id;
if (!oldStats[id]) {
return;
}
Object.keys(report).forEach(name => {
if (report[name] === oldStats[id][name]) {
delete newStats[id][name];
}
});
});
// TODO Snippet bellow adds the last timestamp as a stats level fields, probably used in feature extraction on the
// rtcstats-server side, most likely not used anymore, verify if this can be removed.
let timestamp = -Infinity;
Object.keys(newStats).forEach(id => {
const report = newStats[id];
if (report.timestamp > timestamp) {
timestamp = report.timestamp;
}
});
Object.keys(newStats).forEach(id => {
const report = newStats[id];
if (report.timestamp === timestamp) {
report.timestamp = 0;
}
});
newStats.timestamp = timestamp;
return newStats;
}
/**
*
* @param {*} stream
*/
function dumpStream(stream) {
return {
id: stream.id,
tracks: stream.getTracks().map(track => {
return {
id: track.id, // unique identifier (GUID) for the track
kind: track.kind, // `audio` or `video`
label: track.label, // identified the track source
enabled: track.enabled, // application can control it
muted: track.muted, // application cannot control it (read-only)
readyState: track.readyState // `live` or `ended`
};
})
};
}
/**
*
* @param {*} trace
* @param {*} getStatsInterval
* @param {*} prefixesToWrap
* @param {*} connectionFilter
*/
export default function(
{ statsEntry: sendStatsEntry },
{ connectionFilter,
pollInterval,
useLegacy,
sendSdp = false,
prefixesToWrap = [ '' ],
eventCallback }
) {
let peerconnectioncounter = 0;
const browserDetection = new BrowserDetection();
const isFirefox = browserDetection.isFirefox();
const isChromiumBased = browserDetection.isChromiumBased();
const isWebKitBased = browserDetection.isWebKitBased();
const isReactNative = browserDetection.isReactNative();
// Only initialize rtcstats if it's run in a supported browser
if (!(isFirefox || isChromiumBased || isWebKitBased || isReactNative)) {
logger.warn('RTCStats unsupported browser.');
return;
}
prefixesToWrap.forEach(prefix => {
if (!window[`${prefix}RTCPeerConnection`]) {
return;
}
const OrigPeerConnection = window[`${prefix}RTCPeerConnection`];
const peerconnection = function(config, constraints) {
// We want to make sure that any potential errors that occur at this point, caused by rtcstats logic,
// does not affect the normal flow of any application that might integrate it.
const origConfig = { ...config };
const origConstraints = { ...constraints };
const { optional = [] } = constraints;
let isP2P = false;
try {
// Verify if the connection is configured as P2P
optional.some(option => option.rtcStatsSFUP2P === true) && (isP2P = true);
const pc = new OrigPeerConnection(config, constraints);
// In case the client wants to skip some rtcstats connections, a filter function can be provided which
// will return the original PC object without any strings attached.
if (connectionFilter && connectionFilter(config)) {
return pc;
}
const id = `PC_${peerconnectioncounter++}`;
pc.__rtcStatsId = id;
if (!config) {
config = { nullConfig: true };
}
config = JSON.parse(JSON.stringify(config)); // deepcopy
// don't log credentials
((config && config.iceServers) || []).forEach(server => {
delete server.credential;
});
if (isFirefox) {
config.browserType = 'moz';
} else {
config.browserType = 'webkit';
}
sendStatsEntry('create', id, config);
pc.__dtlsTransport = null;
// TODO: do we want to log constraints here? They are chrome-proprietary.
// eslint-disable-next-line max-len
// http://stackoverflow.com/questions/31003928/what-do-each-of-these-experimental-goog-rtcpeerconnectionconstraints-do
if (constraints) {
sendStatsEntry('constraints', id, constraints);
}
pc.addEventListener('icecandidate', e => {
sendStatsEntry('onicecandidate', id, e.candidate);
});
pc.addEventListener('addstream', e => {
sendStatsEntry(
'onaddstream',
id,
`${e.stream.id} ${e.stream.getTracks().map(t => `${t.kind}:${t.id}`)}`
);
});
pc.addEventListener('track', e => {
sendStatsEntry(
'ontrack',
id,
`${e.track.kind}:${e.track.id} ${e.streams.map(stream => `stream:${stream.id}`)}`
);
});
pc.addEventListener('removestream', e => {
sendStatsEntry(
'onremovestream',
id,
`${e.stream.id} ${e.stream.getTracks().map(t => `${t.kind}:${t.id}`)}`
);
});
pc.addEventListener('signalingstatechange', () => {
sendStatsEntry('onsignalingstatechange', id, pc.signalingState);
});
pc.addEventListener('iceconnectionstatechange', () => {
const { iceConnectionState } = pc;
sendStatsEntry('oniceconnectionstatechange', id, iceConnectionState);
eventCallback?.({
type: PC_ICE_CON_STATE_CHANGE,
body: {
pcId: id,
isP2P,
state: iceConnectionState
}
});
});
pc.addEventListener('icegatheringstatechange', () => {
sendStatsEntry('onicegatheringstatechange', id, pc.iceGatheringState);
});
pc.addEventListener('connectionstatechange', () => {
const { connectionState } = pc;
sendStatsEntry('onconnectionstatechange', id, pc.connectionState);
eventCallback?.({
type: PC_CON_STATE_CHANGE,
body: {
pcId: id,
isP2P,
state: connectionState
}
});
});
pc.addEventListener('negotiationneeded', () => {
sendStatsEntry('onnegotiationneeded', id, undefined);
});
pc.addEventListener('datachannel', event => {
sendStatsEntry('ondatachannel', id, [ event.channel.id, event.channel.label ]);
});
let prev = {};
const getStats = function() {
if (isFirefox || isWebKitBased || isReactNative || ((isChromiumBased && !useLegacy))) {
pc.getStats(null).then(res => {
const now = map2obj(res);
const base = JSON.parse(JSON.stringify(now)); // our new prev
sendStatsEntry('getstats', id, deltaCompression(prev, now));
prev = base;
});
} else if (isChromiumBased) {
// for chromium based env we have the option of using the chrome getstats api via the
// useLegacy flag.
pc.getStats(res => {
const now = mangleChromeStats(pc, res);
const base = JSON.parse(JSON.stringify(now)); // our new prev
sendStatsEntry('getstats', id, deltaCompression(prev, now));
prev = base;
});
}
// If the current env doesn't support any getstats call do nothing.
};
// TODO: do we want one big interval and all peerconnections
// queried in that or one setInterval per PC?
// we have to collect results anyway so...
if (pollInterval) {
const interval = window.setInterval(() => {
if (pc.signalingState === 'closed' || pc.iceConnectionState === 'closed') {
window.clearInterval(interval);
return;
}
getStats();
}, pollInterval);
}
pc.addEventListener('connectionstatechange', () => {
if ([ 'connected', 'failed' ].includes(pc.connectionState)) {
getStats();
}
});
return pc;
} catch (error) {
// If something went wrong, return a normal PeerConnection
console.error('RTCStats PeerConnection bind failed: ', error);
return new OrigPeerConnection(origConfig, origConstraints);
}
};
[ 'createDataChannel', 'close' ].forEach(method => {
const nativeMethod = OrigPeerConnection.prototype[method];
if (nativeMethod) {
OrigPeerConnection.prototype[method] = function() {
try {
sendStatsEntry(method, this.__rtcStatsId, arguments);
} catch (error) {
console.error(`RTCStats ${method} bind failed: `, error);
}
return nativeMethod.apply(this, arguments);
};
}
});
[ 'addStream', 'removeStream' ].forEach(method => {
const nativeMethod = OrigPeerConnection.prototype[method];
if (nativeMethod) {
OrigPeerConnection.prototype[method] = function() {
try {
const stream = arguments[0];
const streamInfo = stream
.getTracks()
.map(t => `${t.kind}:${t.id}`)
.join(',');
sendStatsEntry(method, this.__rtcStatsId, `${stream.id} ${streamInfo}`);
} catch (error) {
console.error(`RTCStats ${method} bind failed: `, error);
}
return nativeMethod.apply(this, arguments);
};
}
});
[ 'addTrack' ].forEach(method => {
const nativeMethod = OrigPeerConnection.prototype[method];
if (nativeMethod) {
OrigPeerConnection.prototype[method] = function() {
try {
const track = arguments[0];
const streams = [].slice.call(arguments, 1);
sendStatsEntry(
method,
this.__rtcStatsId,
`${track.kind}:${track.id} ${streams.map(s => `stream:${s.id}`).join(';') || '-'}`
);
} catch (error) {
console.error(`RTCStats ${method} bind failed: `, error);
}
return nativeMethod.apply(this, arguments);
};
}
});
[ 'removeTrack' ].forEach(method => {
const nativeMethod = OrigPeerConnection.prototype[method];
if (nativeMethod) {
OrigPeerConnection.prototype[method] = function() {
try {
const track = arguments[0].track;
sendStatsEntry(method, this.__rtcStatsId, track ? `${track.kind}:${track.id}` : 'null');
} catch (error) {
console.error(`RTCStats ${method} bind failed: `, error);
}
return nativeMethod.apply(this, arguments);
};
}
});
[ 'addTransceiver' ].forEach(method => {
const nativeMethod = OrigPeerConnection.prototype[method];
if (nativeMethod) {
OrigPeerConnection.prototype[method] = function() {
try {
const trackOrKind = arguments[0];
let opts;
if (typeof trackOrKind === 'string') {
opts = trackOrKind;
} else {
opts = `${trackOrKind.kind}:${trackOrKind.id}`;
}
if (arguments.length === 2 && typeof arguments[1] === 'object') {
opts += ` ${JSON.stringify(arguments[1])}`;
}
sendStatsEntry(method, this.__rtcStatsId, opts);
} catch (error) {
console.error(`RTCStats ${method} bind failed: `, error);
}
return nativeMethod.apply(this, arguments);
};
}
});
[ 'createOffer', 'createAnswer' ].forEach(method => {
const nativeMethod = OrigPeerConnection.prototype[method];
if (nativeMethod) {
OrigPeerConnection.prototype[method] = function() {
// The logic here extracts the arguments and establishes if the API
// is callback or Promise based.
const rtcStatsId = this.__rtcStatsId;
const args = arguments;
let opts;
if (arguments.length === 1 && typeof arguments[0] === 'object') {
opts = arguments[0];
} else if (arguments.length === 3 && typeof arguments[2] === 'object') {
opts = arguments[2];
}
// We can only put a "barrier" at this point because the above logic is
// necessary in all cases, if something fails there we can't just bypass it.
try {
sendStatsEntry(method, this.__rtcStatsId, opts);
} catch (error) {
console.error(`RTCStats ${method} bind failed: `, error);
}
return nativeMethod.apply(this, opts ? [ opts ] : undefined).then(
description => {
try {
const data = sendSdp ? description : '';
sendStatsEntry(`${method}OnSuccess`, rtcStatsId, data);
} catch (error) {
console.error(`RTCStats ${method} promise success bind failed: `, error);
}
// We can't safely bypass this part of logic because it's necessary for Proxying this
// request. It determines weather the call is callback or promise based.
if (args.length > 0 && typeof args[0] === 'function') {
args[0].apply(null, [ description ]);
return undefined;
}
return description;
},
err => {
try {
sendStatsEntry(`${method}OnFailure`, rtcStatsId, err.toString());
} catch (error) {
console.error(`RTCStats ${method} promise failure bind failed: `, error);
}
// We can't safely bypass this part of logic because it's necessary for
// Proxying this request. It determines weather the call is callback or promise based.
if (args.length > 1 && typeof args[1] === 'function') {
args[1].apply(null, [ err ]);
return;
}
throw err;
}
);
};
}
});
[ 'setLocalDescription', 'setRemoteDescription', 'addIceCandidate' ].forEach(method => {
const nativeMethod = OrigPeerConnection.prototype[method];
if (nativeMethod) {
OrigPeerConnection.prototype[method] = function() {
const rtcStatsId = this.__rtcStatsId;
const args = arguments;
try {
const data = sendSdp ? args[0] : '';
sendStatsEntry(method, this.__rtcStatsId, data);
} catch (error) {
console.error(`RTCStats ${method} bind failed: `, error);
}
return nativeMethod.apply(this, [ args[0] ]).then(
() => {
try {
sendStatsEntry(`${method}OnSuccess`, rtcStatsId, undefined);
} catch (error) {
console.error(`RTCStats ${method} promise success bind failed: `, error);
}
if (!this.__dtlsTransport && method.endsWith('Description') && !isReactNative) {
this.getSenders().forEach(sender => {
if (!this.__dtlsTransport && sender.transport) {
this.__dtlsTransport = sender.transport;
sender.transport.addEventListener('error', error => {
sendStatsEntry('ondtlserror', rtcStatsId, error);
});
sender.transport.addEventListener('statechange', () => {
const newstate = sender.transport.state;
sendStatsEntry('ondtlsstatechange', rtcStatsId, newstate);
});
}
});
}
// We can't safely bypass this part of logic because it's necessary for
// Proxying this request. It determines weather the call is callback or promise based.
if (args.length >= 2 && typeof args[1] === 'function') {
args[1].apply(null, []);
return undefined;
}
return undefined;
},
err => {
try {
sendStatsEntry(`${method}OnFailure`, rtcStatsId, err.toString());
} catch (error) {
console.error(`RTCStats ${method} promise failure bind failed: `, error);
}
// We can't safely bypass this part of logic because it's necessary for
// Proxying this request. It determines weather the call is callback or promise based
if (args.length >= 3 && typeof args[2] === 'function') {
args[2].apply(null, [ err ]);
return undefined;
}
throw err;
}
);
};
}
});
// wrap static methods. Currently just generateCertificate.
if (OrigPeerConnection.generateCertificate) {
Object.defineProperty(peerconnection, 'generateCertificate', {
get() {
return arguments.length
? OrigPeerConnection.generateCertificate.apply(null, arguments)
: OrigPeerConnection.generateCertificate;
}
});
}
window[`${prefix}RTCPeerConnection`] = peerconnection;
window[`${prefix}RTCPeerConnection`].prototype = OrigPeerConnection.prototype;
});
// getUserMedia wrappers
prefixesToWrap.forEach(prefix => {
const name = prefix + (prefix.length ? 'GetUserMedia' : 'getUserMedia');
if (!navigator[name]) {
return;
}
const origGetUserMedia = navigator[name].bind(navigator);
const gum = function() {
try {
sendStatsEntry('getUserMedia', null, arguments[0]);
} catch (error) {
console.error('RTCStats getUserMedia bind failed: ', error);
}
const cb = arguments[1];
const eb = arguments[2];
origGetUserMedia(
arguments[0],
stream => {
try {
sendStatsEntry('getUserMediaOnSuccess', null, dumpStream(stream));
} catch (error) {
console.error('RTCStats getUserMediaOnSuccess bind failed: ', error);
}
// we log the stream id, track ids and tracks readystate since that is ended GUM fails
// to acquire the cam (in chrome)
if (cb) {
cb(stream);
}
},
err => {
try {
sendStatsEntry('getUserMediaOnFailure', null, err.name);
} catch (error) {
console.error('RTCStats getUserMediaOnFailure bind failed: ', error);
}
if (eb) {
eb(err);
}
}
);
};
navigator[name] = gum.bind(navigator);
});
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
const origGetUserMedia = navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);
const gum = function() {
try {
sendStatsEntry('navigator.mediaDevices.getUserMedia', null, arguments[0]);
} catch (error) {
console.error('RTCStats navigator.mediaDevices.getUserMedia bind failed: ', error);
}
return origGetUserMedia.apply(navigator.mediaDevices, arguments).then(
stream => {
try {
sendStatsEntry('navigator.mediaDevices.getUserMediaOnSuccess', null, dumpStream(stream));
} catch (error) {
console.error('RTCStats navigator.mediaDevices.getUserMediaOnSuccess bind failed: ', error);
}
return stream;
},
err => {
try {
sendStatsEntry('navigator.mediaDevices.getUserMediaOnFailure', null, err.name);
} catch (error) {
console.error('RTCStats navigator.mediaDevices.getUserMediaOnFailure bind failed: ', error);
}
return Promise.reject(err);
}
);
};
navigator.mediaDevices.getUserMedia = gum.bind(navigator.mediaDevices);
}
// getDisplayMedia
if (navigator.mediaDevices && navigator.mediaDevices.getDisplayMedia) {
const origGetDisplayMedia = navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices);
const gdm = function() {
try {
sendStatsEntry('navigator.mediaDevices.getDisplayMedia', null, arguments[0]);
} catch (error) {
console.error('RTCStats navigator.mediaDevices.getDisplayMedia bind failed: ', error);
}
return origGetDisplayMedia.apply(navigator.mediaDevices, arguments).then(
stream => {
try {
sendStatsEntry('navigator.mediaDevices.getDisplayMediaOnSuccess', null, dumpStream(stream));
} catch (error) {
console.error('RTCStats navigator.mediaDevices.getDisplayMediaOnSuccess bind failed: ', error);
}
return stream;
},
err => {
try {
sendStatsEntry('navigator.mediaDevices.getDisplayMediaOnFailure', null, err.name);
} catch (error) {
console.error('RTCStats navigator.mediaDevices.getDisplayMediaOnFailure bind failed: ', error);
}
return Promise.reject(err);
}
);
};
navigator.mediaDevices.getDisplayMedia = gdm.bind(navigator.mediaDevices);
}
}