@rtcstats/rtcstats-js 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.md ADDED
@@ -0,0 +1,25 @@
1
+ The MIT License
2
+
3
+ Copyright (c) 2016 TokBox, Inc.
4
+ Copyright (c) 2025 rtcstats.com
5
+
6
+ Permission is hereby granted, free of charge,
7
+ to any person obtaining a copy of this software and
8
+ associated documentation files (the "Software"), to
9
+ deal in the Software without restriction, including
10
+ without limitation the rights to use, copy, modify,
11
+ merge, publish, distribute, sublicense, and/or sell
12
+ copies of the Software, and to permit persons to whom
13
+ the Software is furnished to do so,
14
+ subject to the following conditions:
15
+
16
+ The above copyright notice and this permission notice
17
+ shall be included in all copies or substantial portions of the Software.
18
+
19
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
20
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
21
+ OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
22
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
23
+ ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
24
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
25
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,3 @@
1
+ # rtcstats.js
2
+
3
+ Javascript SDK for RTCStats. See the top-level README.md file.
package/media.js ADDED
@@ -0,0 +1,131 @@
1
+ import {compressMethod, dumpTrackWithStreams} from '@rtcstats/rtcstats-shared';
2
+
3
+ /**
4
+ * Wrap the setter for MediaStreamTrack.{property}.
5
+ * Does not work on the prototype but needs a track instance.
6
+ * Only done for local tracks where this is most useful.
7
+ *
8
+ * @protected
9
+ * @param {MediaStrackTrack} track - the track whose property (e.g. `enabled`) should be wrapped.
10
+ * @param {string} property - the track whose property (e.g. `enabled`) should be wrapped.
11
+ * @param {function} trace - RTCStats trace callback.
12
+ */
13
+ function wrapTrackProperty(track, property, trace) {
14
+ const prop = Object.getOwnPropertyDescriptor(
15
+ MediaStreamTrack.prototype, property);
16
+
17
+ // Replace the property with a custom one
18
+ Object.defineProperty(track, property, {
19
+ configurable: true,
20
+ enumerable: true,
21
+ get() {
22
+ return prop.get.call(this);
23
+ },
24
+ set(value) {
25
+ trace('MediaStreamTrack.' + property, null, value, this.id);
26
+ prop.set.call(this, value);
27
+ }
28
+ });
29
+ }
30
+
31
+ /**
32
+ * Wraps getUserMedia and getDisplayMedia for RTCStats.
33
+ * Legacy getUserMedia is not wrapped.
34
+ * Also wraps these methods on MediaStreamTrack
35
+ * * stop
36
+ * * applyConstraints
37
+ * The `ended` event is wrapped as are the setters fro `enabled`
38
+ * and `contentHint`.
39
+ *
40
+ * @protected
41
+ * @param {function} trace - RTCStats trace callback.
42
+ * @param {object} window - window object with navigator and MediaStreamTrack.
43
+ */
44
+ export function wrapGetUserMedia(trace, {navigator, MediaStreamTrack}) {
45
+ const counters = {getUserMedia: 0, getDisplayMedia: 0};
46
+ if (!(navigator && navigator.mediaDevices)) {
47
+ return;
48
+ }
49
+ if (navigator.mediaDevices.__rtcStats) {
50
+ // Prevent double-wrapping.
51
+ return;
52
+ }
53
+ ['getUserMedia', 'getDisplayMedia'].forEach(method => {
54
+ if (!(navigator && 'mediaDevices' in navigator && navigator.mediaDevices[method])) {
55
+ return;
56
+ }
57
+ const origMethod = navigator.mediaDevices[method].bind(navigator.mediaDevices);
58
+ const wrappedMethod = (...args) => {
59
+ const trackingId = compressMethod('navigator.mediaDevices.' + method) +
60
+ '-' + (counters[method]++);
61
+ trace('navigator.mediaDevices.' + method, null, args[0], trackingId);
62
+ return origMethod.apply(navigator.mediaDevices, args)
63
+ .then((stream) => {
64
+ trace('navigator.mediaDevices.' + method + 'OnSuccess', null,
65
+ stream.getTracks().map(t => dumpTrackWithStreams(t, stream)),
66
+ trackingId);
67
+ stream.getTracks().forEach(track => {
68
+ track.__rtcStatsId = trackingId;
69
+ track.addEventListener('ended', () => {
70
+ trace('MediaStreamTrack.onended', null, this.id, this.__rtcStatsId);
71
+ });
72
+ wrapTrackProperty(track, 'enabled', trace);
73
+ wrapTrackProperty(track, 'contentHint', trace);
74
+ });
75
+ return stream;
76
+ }, (err) => {
77
+ trace('navigator.mediaDevices.' + method + 'OnFailure', null,
78
+ err.toString(), trackingId);
79
+ return Promise.reject(err);
80
+ });
81
+ };
82
+ navigator.mediaDevices[method] = wrappedMethod.bind(navigator.mediaDevices);
83
+ });
84
+ if (MediaStreamTrack) {
85
+ ['stop', 'applyConstraints'].forEach(method => {
86
+ const origMethod = MediaStreamTrack.prototype[method];
87
+ MediaStreamTrack.prototype[method] = function(...args) {
88
+ if (this.readyState !== 'ended') {
89
+ trace('MediaStreamTrack.' + method, null, args, this.id, this.__rtcStatsId);
90
+ }
91
+ return origMethod.apply(this, args);
92
+ };
93
+ });
94
+ }
95
+ navigator.mediaDevices.__rtcStats = true;
96
+ }
97
+
98
+ /**
99
+ * Wraps enumerateDevices and the devicechange event for RTCStats.
100
+ *
101
+ * @param {function} trace - RTCStats trace callback.
102
+ * @param {object} window - window object with navigator.
103
+ */
104
+ export function wrapEnumerateDevices(trace, {navigator}) {
105
+ if (!(navigator && 'mediaDevices' in navigator && navigator.mediaDevices.enumerateDevices)) {
106
+ return;
107
+ }
108
+ if (navigator.mediaDevices.enumerateDevices.__rtcStats) {
109
+ // Prevent double-wrapping.
110
+ return;
111
+ }
112
+ const origMethod = navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices);
113
+ const wrappedMethod = (...args) => {
114
+ return origMethod.apply(navigator.mediaDevices, args)
115
+ .then((devices) => {
116
+ trace('navigator.mediaDevices.enumerateDevices', null,
117
+ JSON.parse(JSON.stringify(devices)));
118
+ return devices;
119
+ });
120
+ };
121
+ navigator.mediaDevices.enumerateDevices = wrappedMethod.bind(navigator.mediaDevices);
122
+ navigator.mediaDevices.enumerateDevices.__rtcStats = true;
123
+
124
+ // Listen to devicechange event (which often causes enumerateDevices to be called).
125
+ if ('ondevicechange' in navigator.mediaDevices) {
126
+ navigator.mediaDevices.addEventListener('devicechange', () => {
127
+ trace('navigator.mediaDevices.ondevicechange', null, null);
128
+ });
129
+ }
130
+ }
131
+
package/package.json ADDED
@@ -0,0 +1,33 @@
1
+ {
2
+ "name": "@rtcstats/rtcstats-js",
3
+ "version": "1.0.0",
4
+ "description": "gather WebRTC API traces and statistics",
5
+ "main": "rtcstats.js",
6
+ "type": "module",
7
+ "devDependencies": {
8
+ "@puppeteer/browsers": "^2.10.9",
9
+ "jest": "^30.1.3",
10
+ "karma": "^6.4.4",
11
+ "karma-chai": "^0.1.0",
12
+ "karma-chrome-launcher": "^3.2.0",
13
+ "karma-coverage": "^2.2.1",
14
+ "karma-firefox-launcher": "^2.1.3",
15
+ "karma-mocha": "^2.0.1",
16
+ "karma-mocha-reporter": "^2.2.5",
17
+ "karma-webpack": "^5.0.1"
18
+ },
19
+ "scripts": {
20
+ "lint": "eslint *.js test/",
21
+ "coverage": "c8 karma start test/karma.conf.js",
22
+ "test": "npm run lint && npm run coverage"
23
+ },
24
+ "repository": {
25
+ "type": "git",
26
+ "url": "git+https://github.com/rtcstats/rtcstats.git"
27
+ },
28
+ "author": "rtcstats.com",
29
+ "license": "MIT",
30
+ "publishConfig": {
31
+ "access": "public"
32
+ }
33
+ }
@@ -0,0 +1,387 @@
1
+ import {statsCompression, descriptionCompression, compressMethod} from '@rtcstats/rtcstats-shared';
2
+ import {map2obj, dumpTrackWithStreams, copyAndSanitizeConfig} from '@rtcstats/rtcstats-shared';
3
+
4
+ /**
5
+ * Wraps a RTCRtpTransceiver for RTCStats. Currently applied to these methods:
6
+ * * setCodecPreferences
7
+ * * setHeaderExtensionsToNegotiate
8
+ *
9
+ * @protected
10
+ * @param {function} trace - RTCStats trace callback
11
+ * @param {object} window - window object from which to take the RTCRtpTransceiver protoype.
12
+ */
13
+ function wrapRTCRtpTransceiver(trace, window) {
14
+ if (!window.RTCRtpTransceiver) {
15
+ return;
16
+ }
17
+ ['setCodecPreferences', 'setHeaderExtensionsToNegotiate'].forEach(method => {
18
+ const nativeMethod = window.RTCRtpTransceiver.prototype[method];
19
+ if (!nativeMethod) return;
20
+ window.RTCRtpTransceiver.prototype[method] = function(arg) {
21
+ trace(method, this.__rtcStatsId, arg,
22
+ this.receiver.track.id);
23
+ return nativeMethod.apply(this, [arg]);
24
+ };
25
+ });
26
+ }
27
+
28
+ /**
29
+ * Wraps a RTCRtpSenderfor RTCStats. Currently applied to these methods:
30
+ * * setParameters
31
+ * * replaceTrack
32
+ *
33
+ * @protected
34
+ * @param {function} trace - RTCStats trace callback
35
+ * @param {object} window - window object from which to take the RTCRtpSender protoype.
36
+ */
37
+ function wrapRTCRtpSender(trace, window) {
38
+ if (!window.RTCRtpSender) {
39
+ return;
40
+ }
41
+ ['setParameters'].forEach(method => {
42
+ const nativeMethod = window.RTCRtpSender.prototype[method];
43
+ if (!nativeMethod) return;
44
+
45
+ window.RTCRtpSender.prototype[method] = function(...args) {
46
+ const serializedArgs = JSON.parse(JSON.stringify(args));
47
+ delete serializedArgs[0].transactionId;
48
+ trace(method, this.__rtcStatsId,
49
+ serializedArgs,
50
+ this.__rtcStatsSenderId);
51
+ return nativeMethod.apply(this, args);
52
+ };
53
+ });
54
+ ['replaceTrack'].forEach(method => {
55
+ const nativeMethod = window.RTCRtpSender.prototype[method];
56
+ if (!nativeMethod) return;
57
+ window.RTCRtpSender.prototype[method] = function(...args) {
58
+ const serializedArgs = [
59
+ this.track === null ? null : dumpTrackWithStreams(this.track),
60
+ args[0] === null ? null : dumpTrackWithStreams(args[0]),
61
+ ];
62
+ trace(method, this.__rtcStatsId,
63
+ serializedArgs,
64
+ this.__rtcStatsSenderId);
65
+ return nativeMethod.apply(this, args);
66
+ };
67
+ });
68
+ }
69
+
70
+ /**
71
+ * Wraps RTCPeerConnection for RTCStats.
72
+ * Legacy methods and events are not wrapped.
73
+ *
74
+ * @param {function} trace - RTCStats trace callback
75
+ * @param {object} window - window object from which to take the RTCPeerConnection protoype.
76
+ * @param {object} configuration - various configurable properties. Currently:
77
+ * * getStatsInterval {number} - interval at which getStats will be polled.
78
+ */
79
+ export function wrapRTCPeerConnection(trace, window, {getStatsInterval}) {
80
+ if (!window.RTCPeerConnection) {
81
+ return;
82
+ }
83
+ if (window.RTCPeerConnection.prototype.hasOwnProperty('__rtcStats')) {
84
+ // Prevent double-wrapping.
85
+ return;
86
+ }
87
+ wrapRTCRtpTransceiver(trace, window);
88
+ wrapRTCRtpSender(trace, window);
89
+ const OrigPeerConnection = window.RTCPeerConnection;
90
+ let peerconnectioncounter = 0;
91
+ // Counters for event correlation.
92
+ const counters = {
93
+ createOffer: 0,
94
+ createAnswer: 0,
95
+ setLocalDescription: 0,
96
+ setRemoteDescription: 0,
97
+ addIceCandidate: 0
98
+ };
99
+
100
+ const RTCStatsPeerConnection = function(config, constraints) {
101
+ const pc = new OrigPeerConnection(config, constraints);
102
+ const pcId = 'PC_' + peerconnectioncounter++;
103
+ pc.__rtcStatsId = pcId;
104
+
105
+ trace('create', pcId, copyAndSanitizeConfig(config));
106
+ if (constraints) {
107
+ trace('constraints', pcId, constraints);
108
+ }
109
+
110
+ pc.addEventListener('icecandidate', (e) => {
111
+ trace('onicecandidate', pcId, e.candidate);
112
+ });
113
+ pc.addEventListener('icecandidateerror', (e) => {
114
+ const serializedArgs = {};
115
+ ['address', 'port', 'hostCandidate',
116
+ 'url', 'errorCode', 'errorText'].forEach(key => {
117
+ serializedArgs[key] = e[key];
118
+ });
119
+ trace('onicecandidateerror', pcId, serializedArgs);
120
+ });
121
+ pc.addEventListener('track', (e) => {
122
+ trace('ontrack', pcId, dumpTrackWithStreams(e.track, ...e.streams));
123
+ e.track.addEventListener('unmute', () => {
124
+ trace('MediaStreamTrack.onunmute', pcId, e.track.id);
125
+ });
126
+ e.track.addEventListener('mute', () => {
127
+ trace('MediaStreamTrack.onmute', pcId, e.track.id);
128
+ });
129
+ if (e.transceiver) {
130
+ e.transceiver.__rtcStatsId = pcId;
131
+ e.transceiver.sender.__rtcStatsId = pcId;
132
+ e.transceiver.sender.__rtcStatsSenderId = e.track.id;
133
+ }
134
+ if (e.track.kind === 'video') {
135
+ setTimeout(() => {
136
+ document.querySelectorAll('video').forEach(el => {
137
+ if (!el.srcObject) return;
138
+ if (el.srcObject.getTracks().indexOf(e.track) === -1) return;
139
+ el.addEventListener('resize', () => {
140
+ if (el.srcObject.getTracks().indexOf(e.track) === -1) return;
141
+ trace('HTMLMediaElement.resize', pcId, {
142
+ width: el.scrollWidth, // displayed size.
143
+ height: el.scrollHeight,
144
+ videoWidth: el.videoWidth, // received size.
145
+ videoHeight: el.videoHeight,
146
+ }, e.track.id);
147
+ });
148
+ });
149
+ }, 0);
150
+ }
151
+ });
152
+ ['signalingState', 'iceConnectionState', 'connectionState',
153
+ 'iceGatheringState'].forEach(state => {
154
+ pc.addEventListener(state.toLowerCase() + 'change', () => {
155
+ trace('on' + state.toLowerCase() + 'change', pcId, pc[state]);
156
+ });
157
+ });
158
+ pc.addEventListener('negotiationneeded', () => {
159
+ trace('onnegotiationneeded', pcId, undefined);
160
+ });
161
+ pc.addEventListener('datachannel', (e) => {
162
+ trace('ondatachannel', pcId, [e.channel.id, e.channel.label]);
163
+ });
164
+
165
+ let prevStats = {};
166
+ let statsInterval;
167
+ const statsIdMap = {};
168
+ const getStats = async (reason) => {
169
+ if (pc.signalingState === 'closed') {
170
+ if (statsInterval) {
171
+ window.clearInterval(statsInterval);
172
+ }
173
+ return;
174
+ }
175
+ const stats = map2obj(await pc.getStats());
176
+ if (pc.signalingState === 'closed') {
177
+ return;
178
+ }
179
+ const baseStats = JSON.parse(JSON.stringify(stats)); // our new prevStats.
180
+ const compressedStats = statsCompression(prevStats, stats, statsIdMap);
181
+ if (reason) {
182
+ trace('getStats', pc.__rtcStatsId, compressedStats, reason);
183
+ } else {
184
+ trace('getStats', pc.__rtcStatsId, compressedStats);
185
+ }
186
+ prevStats = baseStats;
187
+ };
188
+ // Listen to the connection establishment and start polling getStats then.
189
+ pc.addEventListener('connectionstatechange', function firstConnect() {
190
+ if (['connected', 'failed'].includes(pc.connectionState)) {
191
+ pc.removeEventListener('connectionstatechange', firstConnect);
192
+ if (getStatsInterval) {
193
+ statsInterval = window.setInterval(getStats, getStatsInterval);
194
+ }
195
+ getStats(pc.connectionState + '-0');
196
+ }
197
+ });
198
+ return pc;
199
+ };
200
+
201
+ ['createDataChannel'].forEach(method => {
202
+ const nativeMethod = OrigPeerConnection.prototype[method];
203
+ if (!nativeMethod) return;
204
+ OrigPeerConnection.prototype[method] = function(...args) {
205
+ trace(method, this.__rtcStatsId, args);
206
+ return nativeMethod.apply(this, args);
207
+ };
208
+ });
209
+
210
+ ['close', 'restartIce'].forEach(method => {
211
+ const nativeMethod = OrigPeerConnection.prototype[method];
212
+ if (!nativeMethod) return;
213
+ OrigPeerConnection.prototype[method] = function() {
214
+ trace(method, this.__rtcStatsId, undefined);
215
+ return nativeMethod.apply(this, []);
216
+ };
217
+ });
218
+
219
+ ['addTrack'].forEach(method => {
220
+ const nativeMethod = OrigPeerConnection.prototype[method];
221
+ if (!nativeMethod) return;
222
+ OrigPeerConnection.prototype[method] = function(...args) {
223
+ const track = args[0];
224
+ const streams = args.slice(1);
225
+ trace(method, this.__rtcStatsId, dumpTrackWithStreams(track, ...streams));
226
+ const sender = nativeMethod.apply(this, args);
227
+ sender.__rtcStatsId = this.__rtcStatsId;
228
+ const transceiver = this.getTransceivers().find(t => t.sender === sender);
229
+ if (transceiver) {
230
+ transceiver.__rtcStatsId = this.__rtcStatsId;
231
+ sender.__rtcStatsSenderId = transceiver.receiver.track.id;
232
+ trace(method + 'OnSuccess', this.__rtcStatsId, null, transceiver.receiver.track.id);
233
+ }
234
+ return sender;
235
+ };
236
+ });
237
+
238
+ ['addTransceiver'].forEach(method => {
239
+ const nativeMethod = OrigPeerConnection.prototype[method];
240
+ if (!nativeMethod) return;
241
+ OrigPeerConnection.prototype[method] = function(...args) {
242
+ const serializedArgs = [
243
+ typeof(args[0]) === 'string' ? args[0] : dumpTrackWithStreams(args[0]), // trackOrKind,
244
+ ];
245
+ if (args[1]) {
246
+ serializedArgs.push(JSON.parse(JSON.stringify(args[1])));
247
+ if (args[1].streams) {
248
+ serializedArgs[serializedArgs.length - 1].streams = args[1].streams.map(s => s.id);
249
+ }
250
+ }
251
+ trace(method, this.__rtcStatsId, serializedArgs);
252
+ const transceiver = nativeMethod.apply(this, args);
253
+ transceiver.__rtcStatsId = this.__rtcStatsId;
254
+ transceiver.sender.__rtcStatsId = this.__rtcStatsId;
255
+ transceiver.sender.__rtcStatsSenderId = transceiver.receiver.track.id;
256
+ trace(method + 'OnSuccess', this.__rtcStatsId, null, transceiver.receiver.track.id);
257
+ return transceiver;
258
+ };
259
+ });
260
+
261
+ ['removeTrack'].forEach(method => {
262
+ const nativeMethod = OrigPeerConnection.prototype[method];
263
+ if (!nativeMethod) return;
264
+ OrigPeerConnection.prototype[method] = function(...args) {
265
+ trace(method, this.__rtcStatsId, args[0].__rtcStatsSenderId);
266
+ return nativeMethod.apply(this, args);
267
+ };
268
+ });
269
+
270
+ ['createOffer', 'createAnswer'].forEach(method => {
271
+ const nativeMethod = OrigPeerConnection.prototype[method];
272
+ if (!nativeMethod) return;
273
+ OrigPeerConnection.prototype[method] = function(...args) {
274
+ const trackingId = compressMethod(method) + '-' + (counters[method]++);
275
+ trace(method, this.__rtcStatsId, args[0], trackingId);
276
+ return nativeMethod.apply(this, args)
277
+ .then((description) => {
278
+ trace(method + 'OnSuccess', this.__rtcStatsId,
279
+ descriptionCompression(this.localDescription, description),
280
+ trackingId);
281
+ if (!this.localDescription) {
282
+ if (method === 'createOffer') {
283
+ this.__rtcStatsLastCreatedOffer = description;
284
+ } else {
285
+ this.__rtcStatsLastCreatedAnswer = description;
286
+ }
287
+ }
288
+ return description;
289
+ }, (err) => {
290
+ trace(method + 'OnFailure', this.__rtcStatsId, err.toString(),
291
+ trackingId);
292
+ throw err;
293
+ });
294
+ };
295
+ });
296
+
297
+ ['setLocalDescription', 'setRemoteDescription'].forEach(method => {
298
+ const nativeMethod = OrigPeerConnection.prototype[method];
299
+ if (!nativeMethod) return;
300
+ OrigPeerConnection.prototype[method] = function(...args) {
301
+ const trackingId = compressMethod(method) + '-' + (counters[method]++);
302
+ let implicitBaseDescription;
303
+ if (method === 'setLocalDescription') {
304
+ if (args[0]) {
305
+ let explicitBaseDescription;
306
+ if (args[0].type === 'offer') {
307
+ explicitBaseDescription = this.__rtcStatsLastCreatedOffer;
308
+ } else if (args[0].type === 'answer') {
309
+ explicitBaseDescription = this.__rtcStatsLastCreatedAnswer;
310
+ }
311
+ delete this.__rtcStatsLastCreatedOffer;
312
+ delete this.__rtcStatsLastCreatedAnswer;
313
+ trace(method, this.__rtcStatsId,
314
+ descriptionCompression(this.localDescription || explicitBaseDescription, args[0]),
315
+ trackingId);
316
+ } else {
317
+ // Save previous localDescription for delta.
318
+ implicitBaseDescription = JSON.parse(JSON.stringify(this.localDescription));
319
+ trace(method, this.__rtcStatsId, null, trackingId);
320
+ }
321
+ } else if (method === 'setRemoteDescription') {
322
+ trace(method, this.__rtcStatsId,
323
+ descriptionCompression(this.remoteDescription, args[0]),
324
+ trackingId);
325
+ }
326
+
327
+ return nativeMethod.apply(this, args)
328
+ .then(() => {
329
+ if (method === 'setLocalDescription' && args.length === 0) {
330
+ trace(method + 'OnSuccess', this.__rtcStatsId,
331
+ descriptionCompression(implicitBaseDescription, this.localDescription),
332
+ trackingId);
333
+ } else {
334
+ trace(method + 'OnSuccess', this.__rtcStatsId, undefined,
335
+ trackingId);
336
+ }
337
+ }, (err) => {
338
+ trace(method + 'OnFailure', this.__rtcStatsId, err.toString(),
339
+ trackingId);
340
+ throw err;
341
+ });
342
+ };
343
+ });
344
+
345
+ ['addIceCandidate'].forEach(method => {
346
+ const nativeMethod = OrigPeerConnection.prototype[method];
347
+ if (!nativeMethod) return;
348
+ OrigPeerConnection.prototype[method] = function(...args) {
349
+ const trackingId = compressMethod(method) + '-' + (counters[method]++);
350
+ trace(method, this.__rtcStatsId, args[0], trackingId);
351
+ return nativeMethod.apply(this, args)
352
+ .then((description) => {
353
+ trace(method + 'OnSuccess', this.__rtcStatsId, undefined,
354
+ trackingId);
355
+ return description;
356
+ }, (err) => {
357
+ trace(method + 'OnFailure', this.__rtcStatsId, err.toString(),
358
+ trackingId);
359
+ throw err;
360
+ });
361
+ };
362
+ });
363
+
364
+ ['setConfiguration'].forEach(method => {
365
+ const nativeMethod = OrigPeerConnection.prototype[method];
366
+ if (!nativeMethod) return;
367
+ OrigPeerConnection.prototype[method] = function(...args) {
368
+ trace(method, this.__rtcStatsId, copyAndSanitizeConfig(args[0]));
369
+ // TODO: should this catch, log and rethrow? Rare...
370
+ return nativeMethod.apply(this, args);
371
+ };
372
+ });
373
+
374
+ // wrap static methods. Currently just generateCertificate.
375
+ if (OrigPeerConnection.generateCertificate) {
376
+ Object.defineProperty(RTCStatsPeerConnection, 'generateCertificate', {
377
+ get(...args) {
378
+ return args.length ?
379
+ OrigPeerConnection.generateCertificate.apply(null, args)
380
+ : OrigPeerConnection.generateCertificate;
381
+ },
382
+ });
383
+ }
384
+ window.RTCPeerConnection = RTCStatsPeerConnection;
385
+ window.RTCPeerConnection.prototype = OrigPeerConnection.prototype;
386
+ window.RTCPeerConnection.prototype.__rtcStats = true;
387
+ }
package/rtcstats.js ADDED
@@ -0,0 +1,10 @@
1
+ import {wrapRTCPeerConnection} from './peerconnection.js';
2
+ import {wrapGetUserMedia, wrapEnumerateDevices} from './media.js';
3
+ import {WebSocketTrace} from './trace-websocket.js';
4
+
5
+ export {
6
+ wrapRTCPeerConnection,
7
+ wrapGetUserMedia,
8
+ wrapEnumerateDevices,
9
+ WebSocketTrace,
10
+ };
@@ -0,0 +1,78 @@
1
+ import {compressMethod} from '@rtcstats/rtcstats-shared';
2
+
3
+ const PROTOCOL_VERSION = '4.0';
4
+
5
+ export function WebSocketTrace() {
6
+ let buffer = [];
7
+ let connection;
8
+ let lastTime = 0;
9
+ const trace = function(...args) {
10
+ const now = Date.now();
11
+ args.push(now - lastTime);
12
+ lastTime = now;
13
+
14
+ if (args[1] instanceof RTCPeerConnection) {
15
+ args[1] = args[1].__rtcStatsId;
16
+ }
17
+ const method = args[0];
18
+ args[0] = compressMethod(method);
19
+ if (connection.readyState === WebSocket.OPEN) {
20
+ if (buffer.length === 0) {
21
+ connection.send(JSON.stringify(args));
22
+ } else {
23
+ buffer.push(args);
24
+ }
25
+ } else if (connection.readyState >= WebSocket.CLOSING) {
26
+ // no-op. Possibly log?
27
+ } else {
28
+ buffer.push(args);
29
+ }
30
+ };
31
+
32
+ trace.close = () => {
33
+ connection.close();
34
+ };
35
+ trace.connect = (wsURL) => {
36
+ buffer = [];
37
+ if (connection) {
38
+ connection.close();
39
+ }
40
+ connection = new WebSocket(wsURL, 'rtcstats#' + PROTOCOL_VERSION);
41
+ connection.addEventListener('error', (e) => {
42
+ // console.error('WS ERROR', e);
43
+ });
44
+
45
+ connection.addEventListener('close', () => {
46
+ // reconnect?
47
+ });
48
+
49
+ connection.addEventListener('open', () => {
50
+ trace('create', null, {
51
+ hardwareConcurrency: navigator.hardwareConcurrency,
52
+ userAgentData: navigator.userAgentData,
53
+ deviceMemory: navigator.deviceMemory,
54
+ screen: {
55
+ width: window.screen.availWidth,
56
+ height: window.screen.availHeight,
57
+ devicePixelRatio: window.devicePixelRatio,
58
+ },
59
+ window: {
60
+ width: window.innerWidth,
61
+ height: window.innerHeight,
62
+ },
63
+ });
64
+ setTimeout(function flush() {
65
+ if (!buffer.length) {
66
+ return;
67
+ }
68
+ connection.send(JSON.stringify(buffer.shift()));
69
+ setTimeout(flush, 0);
70
+ }, 0);
71
+ });
72
+
73
+ connection.addEventListener('message', (msg) => {
74
+ // no messages from the server defined yet.
75
+ });
76
+ };
77
+ return trace;
78
+ }