0
# Configuration
1
2
WebRTC configuration objects, RTP parameters, codec capabilities, and session description handling for connection setup and media negotiation.
3
4
## Capabilities
5
6
### RTCConfiguration Class
7
8
Configuration options for RTCPeerConnection setup.
9
10
```python { .api }
11
class RTCConfiguration:
12
"""Configuration for RTCPeerConnection."""
13
14
def __init__(self, iceServers=None, bundlePolicy=RTCBundlePolicy.BALANCED):
15
"""
16
Create RTCConfiguration.
17
18
Parameters:
19
- iceServers (list, optional): List of RTCIceServer objects
20
- bundlePolicy (RTCBundlePolicy, optional): Media bundling policy (default: BALANCED)
21
"""
22
23
@property
24
def iceServers(self) -> list:
25
"""List of RTCIceServer objects for STUN/TURN servers"""
26
27
@property
28
def bundlePolicy(self) -> RTCBundlePolicy:
29
"""Media bundling policy"""
30
```
31
32
### RTCIceServer Class
33
34
STUN/TURN server configuration for ICE connectivity.
35
36
```python { .api }
37
class RTCIceServer:
38
"""STUN/TURN server configuration."""
39
40
def __init__(self, urls, username=None, credential=None, credentialType="password"):
41
"""
42
Create ICE server configuration.
43
44
Parameters:
45
- urls (str or list): STUN/TURN server URLs
46
- username (str, optional): Authentication username (required for TURN)
47
- credential (str, optional): Authentication credential (required for TURN)
48
- credentialType (str, optional): Credential type (default: "password")
49
"""
50
51
@property
52
def urls(self) -> list:
53
"""List of server URLs"""
54
55
@property
56
def username(self) -> str:
57
"""Authentication username"""
58
59
@property
60
def credential(self) -> str:
61
"""Authentication credential"""
62
63
@property
64
def credentialType(self) -> str:
65
"""Credential type"""
66
```
67
68
### RTCBundlePolicy Enum
69
70
Media bundling policy options for ICE candidate gathering.
71
72
```python { .api }
73
class RTCBundlePolicy:
74
"""Media bundling policy enumeration."""
75
76
BALANCED = "balanced" # Gather ICE candidates per media type
77
MAX_COMPAT = "max-compat" # Gather ICE candidates per track
78
MAX_BUNDLE = "max-bundle" # Gather ICE candidates for single track only
79
```
80
81
### RTP Parameters and Capabilities
82
83
Configuration objects for RTP media negotiation.
84
85
```python { .api }
86
class RTCRtpParameters:
87
"""RTP connection parameters."""
88
89
@property
90
def codecs(self) -> list:
91
"""List of RTCRtpCodecParameters"""
92
93
@property
94
def headerExtensions(self) -> list:
95
"""List of RTCRtpHeaderExtensionParameters"""
96
97
@property
98
def rtcp(self) -> RTCRtcpParameters:
99
"""RTCP parameters"""
100
101
class RTCRtpCapabilities:
102
"""RTP codec and extension capabilities."""
103
104
@property
105
def codecs(self) -> list:
106
"""List of RTCRtpCodecCapability objects"""
107
108
@property
109
def headerExtensions(self) -> list:
110
"""List of RTCRtpHeaderExtensionCapability objects"""
111
112
class RTCRtpCodecCapability:
113
"""Individual codec capability."""
114
115
@property
116
def mimeType(self) -> str:
117
"""Codec MIME type (e.g., "audio/opus", "video/VP8")"""
118
119
@property
120
def clockRate(self) -> int:
121
"""Codec clock rate in Hz"""
122
123
@property
124
def channels(self) -> int:
125
"""Number of audio channels (None for video)"""
126
127
@property
128
def parameters(self) -> dict:
129
"""Codec-specific parameters"""
130
131
class RTCRtpCodecParameters:
132
"""Codec configuration parameters."""
133
134
@property
135
def mimeType(self) -> str:
136
"""Codec MIME type"""
137
138
@property
139
def clockRate(self) -> int:
140
"""Codec clock rate"""
141
142
@property
143
def channels(self) -> int:
144
"""Number of channels"""
145
146
@property
147
def payloadType(self) -> int:
148
"""RTP payload type (96-127 for dynamic types)"""
149
150
@property
151
def parameters(self) -> dict:
152
"""Codec parameters"""
153
154
class RTCRtpHeaderExtensionCapability:
155
"""Header extension capability."""
156
157
@property
158
def uri(self) -> str:
159
"""Extension URI"""
160
161
class RTCRtpHeaderExtensionParameters:
162
"""Header extension parameters."""
163
164
@property
165
def uri(self) -> str:
166
"""Extension URI"""
167
168
@property
169
def id(self) -> int:
170
"""Extension ID (1-14)"""
171
172
class RTCRtcpParameters:
173
"""RTCP configuration parameters."""
174
175
@property
176
def cname(self) -> str:
177
"""Canonical name for RTCP"""
178
179
@property
180
def reducedSize(self) -> bool:
181
"""Whether to use reduced-size RTCP"""
182
```
183
184
### Session Description
185
186
SDP session description handling for offer/answer exchange.
187
188
```python { .api }
189
class RTCSessionDescription:
190
"""Session Description Protocol representation."""
191
192
def __init__(self, sdp: str, type: str):
193
"""
194
Create session description.
195
196
Parameters:
197
- sdp (str): SDP string content
198
- type (str): Description type ("offer", "answer", "pranswer", "rollback")
199
"""
200
201
@property
202
def sdp(self) -> str:
203
"""SDP string content"""
204
205
@property
206
def type(self) -> str:
207
"""Description type"""
208
```
209
210
## Usage Examples
211
212
### Basic Configuration
213
214
```python
215
import aiortc
216
217
# Create basic configuration with STUN server
218
config = aiortc.RTCConfiguration(
219
iceServers=[
220
aiortc.RTCIceServer("stun:stun.l.google.com:19302")
221
]
222
)
223
224
# Create peer connection with configuration
225
pc = aiortc.RTCPeerConnection(configuration=config)
226
227
print(f"Bundle policy: {config.bundlePolicy}")
228
print(f"ICE servers: {[server.urls for server in config.iceServers]}")
229
```
230
231
### Advanced ICE Server Configuration
232
233
```python
234
# Multiple STUN/TURN servers with authentication
235
config = aiortc.RTCConfiguration(
236
iceServers=[
237
# Public STUN servers
238
aiortc.RTCIceServer([
239
"stun:stun.l.google.com:19302",
240
"stun:stun1.l.google.com:19302"
241
]),
242
243
# TURN server with authentication
244
aiortc.RTCIceServer(
245
urls="turn:turnserver.example.com:3478",
246
username="myusername",
247
credential="mypassword"
248
),
249
250
# TURN server with TCP transport
251
aiortc.RTCIceServer(
252
urls="turn:turnserver.example.com:443?transport=tcp",
253
username="myusername",
254
credential="mypassword"
255
)
256
],
257
bundlePolicy=aiortc.RTCBundlePolicy.MAX_BUNDLE
258
)
259
260
pc = aiortc.RTCPeerConnection(configuration=config)
261
262
# Access configuration details
263
for i, server in enumerate(config.iceServers):
264
print(f"Server {i+1}:")
265
print(f" URLs: {server.urls}")
266
print(f" Username: {server.username}")
267
print(f" Credential type: {server.credentialType}")
268
```
269
270
### Bundle Policy Configuration
271
272
```python
273
# Different bundle policies
274
configs = {
275
"balanced": aiortc.RTCConfiguration(
276
bundlePolicy=aiortc.RTCBundlePolicy.BALANCED
277
),
278
"max_compat": aiortc.RTCConfiguration(
279
bundlePolicy=aiortc.RTCBundlePolicy.MAX_COMPAT
280
),
281
"max_bundle": aiortc.RTCConfiguration(
282
bundlePolicy=aiortc.RTCBundlePolicy.MAX_BUNDLE
283
)
284
}
285
286
for policy_name, config in configs.items():
287
print(f"{policy_name}: {config.bundlePolicy}")
288
289
# Different bundle policies affect ICE candidate gathering
290
pc = aiortc.RTCPeerConnection(configuration=config)
291
# ... use peer connection
292
```
293
294
### RTP Capabilities Inspection
295
296
```python
297
# Get available codec capabilities
298
audio_caps = aiortc.RTCRtpSender.getCapabilities("audio")
299
video_caps = aiortc.RTCRtpSender.getCapabilities("video")
300
301
print("Audio Codecs:")
302
for codec in audio_caps.codecs:
303
print(f" {codec.mimeType}")
304
print(f" Clock rate: {codec.clockRate} Hz")
305
print(f" Channels: {codec.channels}")
306
print(f" Parameters: {codec.parameters}")
307
308
print("\nVideo Codecs:")
309
for codec in video_caps.codecs:
310
print(f" {codec.mimeType}")
311
print(f" Clock rate: {codec.clockRate} Hz")
312
print(f" Parameters: {codec.parameters}")
313
314
print("\nAudio Header Extensions:")
315
for ext in audio_caps.headerExtensions:
316
print(f" {ext.uri}")
317
318
print("\nVideo Header Extensions:")
319
for ext in video_caps.headerExtensions:
320
print(f" {ext.uri}")
321
```
322
323
### Session Description Handling
324
325
```python
326
async def handle_session_descriptions():
327
pc1 = aiortc.RTCPeerConnection()
328
pc2 = aiortc.RTCPeerConnection()
329
330
# PC1 creates offer
331
offer = await pc1.createOffer()
332
print(f"Offer type: {offer.type}")
333
print(f"Offer SDP length: {len(offer.sdp)} characters")
334
335
# Set local description on PC1
336
await pc1.setLocalDescription(offer)
337
print(f"PC1 signaling state: {pc1.signalingState}")
338
339
# Send offer to PC2 and set as remote description
340
await pc2.setRemoteDescription(offer)
341
print(f"PC2 signaling state: {pc2.signalingState}")
342
343
# PC2 creates answer
344
answer = await pc2.createAnswer()
345
print(f"Answer type: {answer.type}")
346
347
# Set local description on PC2
348
await pc2.setLocalDescription(answer)
349
print(f"PC2 signaling state: {pc2.signalingState}")
350
351
# Send answer to PC1 and set as remote description
352
await pc1.setRemoteDescription(answer)
353
print(f"PC1 signaling state: {pc1.signalingState}")
354
355
# Access session descriptions
356
print(f"PC1 local: {pc1.localDescription.type}")
357
print(f"PC1 remote: {pc1.remoteDescription.type}")
358
print(f"PC2 local: {pc2.localDescription.type}")
359
print(f"PC2 remote: {pc2.remoteDescription.type}")
360
```
361
362
### Custom RTP Parameters
363
364
```python
365
async def custom_rtp_parameters():
366
pc = aiortc.RTCPeerConnection()
367
368
# Add transceiver to get RTP parameters
369
transceiver = pc.addTransceiver("video")
370
371
# Get current parameters (after negotiation)
372
# Note: This would typically be done after setLocalDescription
373
try:
374
# Create a mock RTP parameters object for demonstration
375
class MockRtpParameters:
376
def __init__(self):
377
self.codecs = []
378
self.headerExtensions = []
379
self.rtcp = None
380
381
# In real usage, you'd get this from the transceiver after negotiation
382
params = MockRtpParameters()
383
384
# Example of how you might inspect codec parameters
385
video_caps = aiortc.RTCRtpSender.getCapabilities("video")
386
387
print("Available video codecs:")
388
for codec in video_caps.codecs:
389
print(f" {codec.mimeType} - Clock: {codec.clockRate}")
390
391
except Exception as e:
392
print(f"Could not get RTP parameters: {e}")
393
```
394
395
### Configuration Validation
396
397
```python
398
def validate_configuration():
399
"""Validate RTCConfiguration settings."""
400
401
# Test various configuration scenarios
402
test_configs = [
403
# Valid configuration
404
{
405
"name": "Valid STUN only",
406
"config": aiortc.RTCConfiguration(
407
iceServers=[aiortc.RTCIceServer("stun:stun.l.google.com:19302")]
408
)
409
},
410
411
# Valid TURN configuration
412
{
413
"name": "Valid TURN with auth",
414
"config": aiortc.RTCConfiguration(
415
iceServers=[aiortc.RTCIceServer(
416
"turn:turnserver.example.com:3478",
417
username="user",
418
credential="pass"
419
)]
420
)
421
},
422
423
# No ICE servers (valid, will use defaults)
424
{
425
"name": "No ICE servers",
426
"config": aiortc.RTCConfiguration()
427
}
428
]
429
430
for test in test_configs:
431
try:
432
pc = aiortc.RTCPeerConnection(configuration=test["config"])
433
print(f"✓ {test['name']}: Valid")
434
435
# Access configuration properties
436
config = test["config"]
437
print(f" Bundle policy: {config.bundlePolicy}")
438
print(f" ICE servers: {len(config.iceServers) if config.iceServers else 0}")
439
440
except Exception as e:
441
print(f"✗ {test['name']}: Invalid - {e}")
442
```
443
444
### Dynamic Configuration Updates
445
446
```python
447
async def dynamic_configuration():
448
"""Demonstrate dynamic configuration scenarios."""
449
450
# Start with basic configuration
451
initial_config = aiortc.RTCConfiguration(
452
iceServers=[aiortc.RTCIceServer("stun:stun.l.google.com:19302")]
453
)
454
455
pc = aiortc.RTCPeerConnection(configuration=initial_config)
456
457
print("Initial configuration:")
458
print(f" ICE servers: {len(pc.configuration.iceServers)}")
459
print(f" Bundle policy: {pc.configuration.bundlePolicy}")
460
461
# Note: RTCPeerConnection doesn't support configuration changes after creation
462
# You would need to create a new peer connection with updated configuration
463
464
updated_config = aiortc.RTCConfiguration(
465
iceServers=[
466
aiortc.RTCIceServer("stun:stun.l.google.com:19302"),
467
aiortc.RTCIceServer(
468
"turn:turnserver.example.com:3478",
469
username="newuser",
470
credential="newpass"
471
)
472
],
473
bundlePolicy=aiortc.RTCBundlePolicy.MAX_BUNDLE
474
)
475
476
# Create new peer connection with updated config
477
new_pc = aiortc.RTCPeerConnection(configuration=updated_config)
478
479
print("Updated configuration:")
480
print(f" ICE servers: {len(new_pc.configuration.iceServers)}")
481
print(f" Bundle policy: {new_pc.configuration.bundlePolicy}")
482
483
# Clean up original connection
484
await pc.close()
485
```