0
# Utility Functions
1
2
WebRTC Adapter provides a comprehensive set of utility functions for logging control, browser detection, event handling, and WebRTC statistics processing.
3
4
## Capabilities
5
6
### Logging Control
7
8
Functions for controlling adapter.js logging output and deprecation warnings.
9
10
```javascript { .api }
11
/**
12
* Enable or disable adapter.js logging
13
* @param bool - true to disable logging, false to enable
14
* @returns Success message or Error object for invalid input
15
*/
16
function disableLog(bool: boolean): string | Error;
17
18
/**
19
* Enable or disable deprecation warnings
20
* @param bool - true to disable warnings, false to enable
21
* @returns Success message for valid input, Error object for invalid input
22
*/
23
function disableWarnings(bool: boolean): string | Error;
24
25
/**
26
* Internal logging function used by adapter
27
* Only outputs when logging is enabled and console is available
28
*/
29
function log(...args: any[]): void;
30
31
/**
32
* Display deprecation warning for old API usage
33
* Only shows warning when deprecation warnings are enabled
34
* @param oldMethod - Name of the deprecated method
35
* @param newMethod - Name of the recommended replacement method
36
*/
37
function deprecated(oldMethod: string, newMethod: string): void;
38
```
39
40
**Usage Examples:**
41
42
```javascript
43
import adapter from 'webrtc-adapter';
44
45
// Disable all adapter logging
46
const result = adapter.disableLog(true);
47
console.log(result); // "adapter.js logging disabled"
48
49
// Enable logging back
50
adapter.disableLog(false); // "adapter.js logging enabled"
51
52
// Disable deprecation warnings
53
adapter.disableWarnings(true); // "adapter.js deprecation warnings disabled"
54
55
// Invalid input handling
56
const error = adapter.disableLog("invalid");
57
console.log(error); // Error: Argument type: string. Please use a boolean.
58
```
59
60
### Browser Detection Utilities
61
62
Core browser detection and version extraction functions.
63
64
```javascript { .api }
65
/**
66
* Comprehensive browser detection from window object
67
* @param window - Browser window object to analyze
68
* @returns Browser details with type, version, and capabilities
69
*/
70
function detectBrowser(window: Window): IBrowserDetails;
71
72
/**
73
* Extract version number from user agent string using regex
74
* @param uastring - User agent string to parse
75
* @param expr - Regular expression pattern for extraction
76
* @param pos - Position in regex match array containing version
77
* @returns Parsed version number or null if not found
78
*/
79
function extractVersion(uastring: string, expr: string, pos: number): number | null;
80
81
interface IBrowserDetails {
82
browser: string;
83
version: number | null;
84
supportsUnifiedPlan?: boolean;
85
}
86
```
87
88
**Usage Examples:**
89
90
```javascript
91
import { detectBrowser, extractVersion } from 'webrtc-adapter/src/js/utils.js';
92
93
// Detect current browser
94
const browserInfo = detectBrowser(window);
95
console.log(`Running on ${browserInfo.browser} version ${browserInfo.version}`);
96
97
// Extract specific version information
98
const chromeVersion = extractVersion(
99
navigator.userAgent,
100
/Chrome\/(\d+)\./,
101
1
102
);
103
104
// Custom version extraction
105
const appVersion = extractVersion(
106
'MyWebRTCApp/2.1.0',
107
/MyWebRTCApp\/(\d+\.\d+\.\d+)/,
108
1
109
);
110
```
111
112
### Event Handling Utilities
113
114
Functions for wrapping and managing RTCPeerConnection events.
115
116
```javascript { .api }
117
/**
118
* Wrap RTCPeerConnection events with custom handling logic
119
* @param window - Browser window object
120
* @param eventNameToWrap - Name of the event to wrap (e.g., 'icecandidate')
121
* @param wrapper - Function to modify or filter events
122
*/
123
function wrapPeerConnectionEvent(
124
window: Window,
125
eventNameToWrap: string,
126
wrapper: (event: Event) => Event | false
127
): void;
128
```
129
130
**Usage Examples:**
131
132
```javascript
133
import { wrapPeerConnectionEvent } from 'webrtc-adapter/src/js/utils.js';
134
135
// Wrap icecandidate events to add custom logging
136
wrapPeerConnectionEvent(window, 'icecandidate', (event) => {
137
if (event.candidate) {
138
console.log('ICE candidate generated:', event.candidate.candidate);
139
}
140
return event; // Return event to continue normal processing
141
});
142
143
// Filter out specific types of ICE candidates
144
wrapPeerConnectionEvent(window, 'icecandidate', (event) => {
145
if (event.candidate && event.candidate.candidate.includes('typ relay')) {
146
console.log('Blocking relay candidate');
147
return false; // Block this event
148
}
149
return event;
150
});
151
```
152
153
### Data Processing Utilities
154
155
Functions for processing and cleaning nested objects and data structures.
156
157
```javascript { .api }
158
/**
159
* Remove empty objects and undefined values from nested objects
160
* Enhanced version of Lodash's compact function for object cleanup
161
* @param data - Data object to clean
162
* @returns Cleaned object with empty values removed
163
*/
164
function compactObject(data: any): any;
165
```
166
167
**Usage Examples:**
168
169
```javascript
170
import { compactObject } from 'webrtc-adapter/src/js/utils.js';
171
172
// Clean configuration object
173
const dirtyConfig = {
174
servers: {
175
stun: 'stun:stun.l.google.com:19302',
176
turn: undefined,
177
backup: {}
178
},
179
options: {
180
audio: true,
181
video: undefined,
182
advanced: {
183
echoCancellation: true,
184
noiseSuppression: undefined
185
}
186
}
187
};
188
189
const cleanConfig = compactObject(dirtyConfig);
190
// Result: { servers: { stun: 'stun...' }, options: { audio: true, advanced: { echoCancellation: true } } }
191
```
192
193
### WebRTC Statistics Utilities
194
195
Specialized functions for processing WebRTC statistics and navigating the stats graph.
196
197
```javascript { .api }
198
/**
199
* Recursively walk through WebRTC statistics graph
200
* Follows ID references to build complete stat relationships
201
* @param stats - WebRTC stats Map object
202
* @param base - Starting stats object
203
* @param resultSet - Map to store visited stats objects
204
*/
205
function walkStats(stats: Map<any, any>, base: any, resultSet: Map<any, any>): void;
206
207
/**
208
* Filter WebRTC statistics for a specific media track
209
* Extracts track-specific stats for detailed analysis
210
* @param result - Complete WebRTC stats Map
211
* @param track - MediaStreamTrack to filter for (null for all tracks)
212
* @param outbound - true for outbound stats, false for inbound stats
213
* @returns Filtered Map containing only relevant statistics
214
*/
215
function filterStats(
216
result: Map<any, any>,
217
track: MediaStreamTrack | null,
218
outbound: boolean
219
): Map<any, any>;
220
```
221
222
**Usage Examples:**
223
224
```javascript
225
import { walkStats, filterStats } from 'webrtc-adapter/src/js/utils.js';
226
227
// Process complete WebRTC statistics
228
async function analyzeConnectionStats(pc) {
229
const stats = await pc.getStats();
230
231
// Find outbound video stats for specific track
232
const videoTrack = localStream.getVideoTracks()[0];
233
const videoStats = filterStats(stats, videoTrack, true);
234
235
videoStats.forEach((report) => {
236
if (report.type === 'outbound-rtp') {
237
console.log('Video bytes sent:', report.bytesSent);
238
console.log('Video packets sent:', report.packetsSent);
239
}
240
});
241
}
242
243
// Build complete statistics graph
244
function buildStatsGraph(stats) {
245
const completeStats = new Map();
246
247
// Walk from each top-level stat to build relationships
248
stats.forEach((stat) => {
249
if (stat.type === 'peer-connection') {
250
walkStats(stats, stat, completeStats);
251
}
252
});
253
254
return completeStats;
255
}
256
```
257
258
### Advanced Statistics Processing
259
260
```javascript
261
// Track-specific statistics analysis
262
async function getTrackStatistics(pc, track, isOutbound = true) {
263
const allStats = await pc.getStats();
264
const trackStats = filterStats(allStats, track, isOutbound);
265
266
const analysis = {
267
bandwidth: 0,
268
packets: 0,
269
quality: 'unknown'
270
};
271
272
trackStats.forEach((report) => {
273
const rtpType = isOutbound ? 'outbound-rtp' : 'inbound-rtp';
274
if (report.type === rtpType) {
275
analysis.bandwidth = report.bytesSent || report.bytesReceived || 0;
276
analysis.packets = report.packetsSent || report.packetsReceived || 0;
277
278
// Calculate quality metrics
279
if (report.packetsLost !== undefined) {
280
const lossRate = report.packetsLost / (analysis.packets + report.packetsLost);
281
analysis.quality = lossRate < 0.02 ? 'good' : lossRate < 0.05 ? 'fair' : 'poor';
282
}
283
}
284
});
285
286
return analysis;
287
}
288
```
289
290
## Error Handling
291
292
All utility functions include appropriate error handling:
293
294
- **Type Validation**: Boolean functions return Error objects for invalid input types
295
- **Null Safety**: Functions handle null/undefined inputs gracefully
296
- **Browser Compatibility**: Functions degrade gracefully in unsupported environments
297
- **Console Safety**: Logging functions check for console availability before output
298
299
## Performance Considerations
300
301
- **Statistics Processing**: Use filterStats() to reduce processing overhead for large stats objects
302
- **Object Cleaning**: compactObject() creates new objects - use sparingly for large data structures
303
- **Event Wrapping**: Wrapped events add minimal overhead but should be used judiciously
304
- **Browser Detection**: Detection is cached after first call for performance