This repository was archived by the owner on Jan 29, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathwebrtc-architecture.ts
More file actions
825 lines (716 loc) · 21.3 KB
/
webrtc-architecture.ts
File metadata and controls
825 lines (716 loc) · 21.3 KB
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
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
/**
* WebRTC Integration Architecture
*
* Production-ready WebRTC implementation with:
* - Peer-to-peer streaming capabilities
* - Advanced signaling with failover
* - Adaptive quality control
* - Multi-agent coordination
* - Performance optimization
*/
import { EventEmitter } from "events";
import { Logger } from "../utils/logger.js";
import {
WebRTCConfig,
VideoStreamRequest,
AudioStreamRequest,
VideoStreamResponse,
AudioStreamResponse,
StreamingSession,
NetworkConditions,
PerformanceMetrics,
StreamingError,
QualityAdaptationRule,
SynchronizationConfig,
} from "../types/streaming.js";
export interface WebRTCPeer {
id: string;
connection: RTCPeerConnection;
state: RTCPeerConnectionState;
capabilities: RTCRtpCapabilities;
streams: {
outgoing: MediaStream[];
incoming: MediaStream[];
};
stats: RTCStatsReport;
lastActivity: number;
}
export interface SignalingMessage {
type: "offer" | "answer" | "ice-candidate" | "renegotiation" | "bye";
from: string;
to: string;
data: any;
timestamp: number;
sessionId: string;
}
export class WebRTCArchitecture extends EventEmitter {
private logger: Logger;
private config: WebRTCConfig;
private peers = new Map<string, WebRTCPeer>();
private sessions = new Map<string, StreamingSession>();
private signalingEndpoints: WebSocket[] = [];
private iceServers: RTCIceServer[];
private performanceMonitor: PerformanceMonitor;
private qualityAdapter: QualityAdapter;
private syncManager: SynchronizationManager;
constructor(config: WebRTCConfig) {
super();
this.logger = new Logger("WebRTCArchitecture");
this.config = config;
this.iceServers = config.iceServers;
this.performanceMonitor = new PerformanceMonitor();
this.qualityAdapter = new QualityAdapter();
this.syncManager = new SynchronizationManager();
this.setupSignaling();
this.startMonitoring();
}
/**
* Create a new peer connection with optimized configuration
*/
async createPeerConnection(
peerId: string,
options?: RTCConfiguration,
): Promise<WebRTCPeer> {
const peerConfig: RTCConfiguration = {
iceServers: this.iceServers,
iceTransportPolicy: this.config.iceTransportPolicy || "all",
bundlePolicy: this.config.bundlePolicy || "balanced",
rtcpMuxPolicy: this.config.rtcpMuxPolicy || "require",
iceCandidatePoolSize: this.config.iceCandidatePoolSize || 10,
...options,
};
const connection = new RTCPeerConnection(peerConfig);
// Optimize connection settings
this.optimizeConnection(connection);
const peer: WebRTCPeer = {
id: peerId,
connection,
state: "new",
capabilities:
RTCRtpReceiver.getCapabilities("video") || ({} as RTCRtpCapabilities),
streams: {
outgoing: [],
incoming: [],
},
stats: new Map(),
lastActivity: Date.now(),
};
// Setup event handlers
this.setupPeerHandlers(peer);
this.peers.set(peerId, peer);
this.logger.info("Peer connection created", { peerId, state: peer.state });
return peer;
}
/**
* Initiate video streaming with adaptive quality
*/
async startVideoStream(
request: VideoStreamRequest,
): Promise<VideoStreamResponse> {
try {
const stream = await this.createVideoStream(request);
const peer =
this.peers.get(request.id) ||
(await this.createPeerConnection(request.id));
// Add stream to peer connection
stream.getTracks().forEach((track) => {
const sender = peer.connection.addTrack(track, stream);
this.configureVideoSender(sender, request.quality.video!);
});
peer.streams.outgoing.push(stream);
// Start quality adaptation
this.qualityAdapter.startAdaptation(request.id, "video", request.quality);
const response: VideoStreamResponse = {
id: request.id,
status: "streaming",
stream,
quality: request.quality,
stats: {
bytesTransferred: 0,
framesRendered: 0,
droppedFrames: 0,
currentBitrate: request.quality.video!.bitrate,
averageLatency: 0,
jitter: 0,
packetsLost: 0,
},
endpoints: {
webrtc: peer.connection,
},
};
this.emit("video_stream_started", response);
return response;
} catch (error) {
const streamError: StreamingError = this.createStreamingError(
"VIDEO_STREAM_FAILED",
`Failed to start video stream: ${(error as Error).message}`,
"high",
true,
"encoding",
{ streamId: request.id },
);
this.emit("streaming_error", streamError);
throw streamError;
}
}
/**
* Initiate audio streaming with processing
*/
async startAudioStream(
request: AudioStreamRequest,
): Promise<AudioStreamResponse> {
try {
const stream = await this.createAudioStream(request);
const peer =
this.peers.get(request.id) ||
(await this.createPeerConnection(request.id));
// Add stream to peer connection
stream.getTracks().forEach((track) => {
const sender = peer.connection.addTrack(track, stream);
this.configureAudioSender(sender, request.quality.audio!);
});
peer.streams.outgoing.push(stream);
// Start quality adaptation
this.qualityAdapter.startAdaptation(request.id, "audio", request.quality);
const response: AudioStreamResponse = {
id: request.id,
status: "streaming",
stream,
quality: request.quality,
stats: {
bytesTransferred: 0,
samplesProcessed: 0,
bufferUnderuns: 0,
currentBitrate: request.quality.audio!.bitrate,
averageLatency: 0,
signalLevel: 0,
noiseLevel: 0,
},
endpoints: {
webrtc: peer.connection,
},
};
// Setup transcription if requested
if (request.metadata?.transcriptionEnabled) {
this.setupTranscription(response, request.metadata.language);
}
this.emit("audio_stream_started", response);
return response;
} catch (error) {
const streamError: StreamingError = this.createStreamingError(
"AUDIO_STREAM_FAILED",
`Failed to start audio stream: ${(error as Error).message}`,
"high",
true,
"encoding",
{ streamId: request.id },
);
this.emit("streaming_error", streamError);
throw streamError;
}
}
/**
* Create optimized offer with codec preferences
*/
async createOffer(
peerId: string,
options?: RTCOfferOptions,
): Promise<RTCSessionDescriptionInit> {
const peer = this.peers.get(peerId);
if (!peer) {
throw new Error(`Peer not found: ${peerId}`);
}
const offerOptions: RTCOfferOptions = {
offerToReceiveAudio: true,
offerToReceiveVideo: true,
iceRestart: false,
...options,
};
const offer = await peer.connection.createOffer(offerOptions);
// Optimize SDP for better performance
offer.sdp = this.optimizeSDP(offer.sdp!, "offer");
await peer.connection.setLocalDescription(offer);
this.logger.info("Offer created", {
peerId,
sdp: offer.sdp?.substring(0, 100),
});
return offer;
}
/**
* Handle incoming offer and create answer
*/
async handleOffer(
peerId: string,
offer: RTCSessionDescriptionInit,
): Promise<RTCSessionDescriptionInit> {
const peer =
this.peers.get(peerId) || (await this.createPeerConnection(peerId));
// Optimize incoming SDP
offer.sdp = this.optimizeSDP(offer.sdp!, "offer");
await peer.connection.setRemoteDescription(offer);
const answer = await peer.connection.createAnswer();
// Optimize answer SDP
answer.sdp = this.optimizeSDP(answer.sdp!, "answer");
await peer.connection.setLocalDescription(answer);
this.logger.info("Answer created", {
peerId,
sdp: answer.sdp?.substring(0, 100),
});
return answer;
}
/**
* Handle incoming answer
*/
async handleAnswer(
peerId: string,
answer: RTCSessionDescriptionInit,
): Promise<void> {
const peer = this.peers.get(peerId);
if (!peer) {
throw new Error(`Peer not found: ${peerId}`);
}
// Optimize answer SDP
answer.sdp = this.optimizeSDP(answer.sdp!, "answer");
await peer.connection.setRemoteDescription(answer);
this.logger.info("Answer handled", { peerId });
}
/**
* Add ICE candidate with validation
*/
async addIceCandidate(
peerId: string,
candidate: RTCIceCandidateInit,
): Promise<void> {
const peer = this.peers.get(peerId);
if (!peer) {
throw new Error(`Peer not found: ${peerId}`);
}
// Validate candidate before adding
if (this.validateIceCandidate(candidate)) {
await peer.connection.addIceCandidate(candidate);
this.logger.debug("ICE candidate added", {
peerId,
candidate: candidate.candidate,
});
} else {
this.logger.warn("Invalid ICE candidate rejected", { peerId, candidate });
}
}
/**
* Get comprehensive peer statistics
*/
async getPeerStats(peerId: string): Promise<RTCStatsReport> {
const peer = this.peers.get(peerId);
if (!peer) {
throw new Error(`Peer not found: ${peerId}`);
}
const stats = await peer.connection.getStats();
peer.stats = stats;
peer.lastActivity = Date.now();
return stats;
}
/**
* Monitor network conditions and adapt quality
*/
async monitorNetworkConditions(peerId: string): Promise<NetworkConditions> {
const stats = await this.getPeerStats(peerId);
const conditions = this.performanceMonitor.analyzeStats(stats);
// Trigger quality adaptation if needed
this.qualityAdapter.evaluateConditions(peerId, conditions);
return conditions;
}
/**
* Setup multi-agent coordination session
*/
async createCoordinationSession(
sessionId: string,
participants: string[],
): Promise<StreamingSession> {
const session: StreamingSession = {
id: sessionId,
type: "multicast",
participants: participants.map((id) => ({
id,
role: "prosumer",
capabilities: ["video", "audio", "data"],
connection: this.peers.get(id)?.connection || new RTCPeerConnection(),
})),
streams: {
video: [],
audio: [],
data: [],
},
coordination: {
master: participants[0], // First participant is master
consensus: true,
synchronization: {
enabled: true,
tolerance: 50, // 50ms
maxDrift: 200,
resyncThreshold: 500,
method: "rtp",
masterClock: "audio",
},
},
metrics: {
startTime: Date.now(),
duration: 0,
totalBytes: 0,
qualityChanges: 0,
errors: 0,
averageLatency: 0,
},
};
this.sessions.set(sessionId, session);
this.syncManager.initializeSession(session);
this.logger.info("Coordination session created", {
sessionId,
participants,
});
return session;
}
/**
* Optimize connection settings for low latency
*/
private optimizeConnection(connection: RTCPeerConnection): void {
// Set up data channel for low-latency coordination
const dataChannel = connection.createDataChannel("coordination", {
ordered: false,
maxRetransmits: 0,
priority: "high",
});
dataChannel.onopen = () => {
this.logger.debug("Coordination data channel opened");
};
dataChannel.onmessage = (event) => {
this.handleCoordinationMessage(JSON.parse(event.data));
};
}
/**
* Setup peer event handlers
*/
private setupPeerHandlers(peer: WebRTCPeer): void {
const { connection } = peer;
connection.onicecandidate = (event) => {
if (event.candidate) {
this.emit("ice_candidate", {
peerId: peer.id,
candidate: event.candidate,
});
}
};
connection.onconnectionstatechange = () => {
peer.state = connection.connectionState;
this.logger.info("Peer connection state changed", {
peerId: peer.id,
state: peer.state,
});
this.emit("peer_state_changed", {
peerId: peer.id,
state: peer.state,
});
};
connection.ontrack = (event) => {
const [stream] = event.streams;
peer.streams.incoming.push(stream);
this.emit("track_received", {
peerId: peer.id,
track: event.track,
stream,
});
};
connection.ondatachannel = (event) => {
const channel = event.channel;
channel.onmessage = (messageEvent) => {
this.handleCoordinationMessage(JSON.parse(messageEvent.data));
};
};
}
/**
* Create video stream with specified constraints
*/
private async createVideoStream(
request: VideoStreamRequest,
): Promise<MediaStream> {
const constraints: MediaStreamConstraints = {
video: {
width: { ideal: request.quality.video!.resolution.width },
height: { ideal: request.quality.video!.resolution.height },
frameRate: { ideal: request.quality.video!.framerate },
...request.constraints?.video,
},
};
if (request.source === "camera") {
return navigator.mediaDevices.getUserMedia(constraints);
} else if (request.source === "screen") {
return navigator.mediaDevices.getDisplayMedia(constraints);
} else {
throw new Error(`Unsupported video source: ${request.source}`);
}
}
/**
* Create audio stream with processing options
*/
private async createAudioStream(
request: AudioStreamRequest,
): Promise<MediaStream> {
const constraints: MediaStreamConstraints = {
audio: {
sampleRate: { ideal: request.quality.audio!.sampleRate },
channelCount: { ideal: request.quality.audio!.channels },
echoCancellation: request.processing?.echoCancellation ?? true,
noiseSuppression: request.processing?.noiseSuppression ?? true,
autoGainControl: request.processing?.autoGainControl ?? true,
...request.constraints?.audio,
},
};
if (request.source === "microphone") {
return navigator.mediaDevices.getUserMedia(constraints);
} else {
throw new Error(`Unsupported audio source: ${request.source}`);
}
}
/**
* Configure video sender with codec preferences
*/
private configureVideoSender(sender: RTCRtpSender, config: any): void {
const params = sender.getParameters();
// Set bitrate constraints
if (params.encodings.length > 0) {
params.encodings[0].maxBitrate = config.bitrate;
params.encodings[0].maxFramerate = config.framerate;
}
sender.setParameters(params);
}
/**
* Configure audio sender with quality settings
*/
private configureAudioSender(sender: RTCRtpSender, config: any): void {
const params = sender.getParameters();
// Set bitrate constraints
if (params.encodings.length > 0) {
params.encodings[0].maxBitrate = config.bitrate;
}
sender.setParameters(params);
}
/**
* Optimize SDP for better performance and codec preferences
*/
private optimizeSDP(sdp: string, type: "offer" | "answer"): string {
let optimizedSdp = sdp;
// Prefer VP9 for video
optimizedSdp = this.preferCodec(optimizedSdp, "video", "VP9");
// Prefer Opus for audio
optimizedSdp = this.preferCodec(optimizedSdp, "audio", "opus");
// Enable hardware acceleration hints
optimizedSdp = optimizedSdp.replace(
/a=fmtp:(\d+) /g,
"a=fmtp:$1 profile-id=1;",
);
return optimizedSdp;
}
/**
* Prefer specific codec in SDP
*/
private preferCodec(
sdp: string,
type: "video" | "audio",
codec: string,
): string {
const lines = sdp.split("\r\n");
const mLineIndex = lines.findIndex((line) => line.startsWith(`m=${type}`));
if (mLineIndex === -1) return sdp;
const mLine = lines[mLineIndex];
const codecPayloads = this.extractCodecPayloads(lines, codec);
if (codecPayloads.length > 0) {
const otherPayloads = mLine
.split(" ")
.slice(3)
.filter((p) => !codecPayloads.includes(p));
const newMLine = `${mLine.split(" ").slice(0, 3).join(" ")} ${codecPayloads.join(" ")} ${otherPayloads.join(" ")}`;
lines[mLineIndex] = newMLine;
}
return lines.join("\r\n");
}
/**
* Extract codec payload types from SDP
*/
private extractCodecPayloads(lines: string[], codec: string): string[] {
const payloads: string[] = [];
for (const line of lines) {
if (
line.includes(`a=rtpmap:`) &&
line.toLowerCase().includes(codec.toLowerCase())
) {
const payload = line.split(":")[1].split(" ")[0];
payloads.push(payload);
}
}
return payloads;
}
/**
* Validate ICE candidate
*/
private validateIceCandidate(candidate: RTCIceCandidateInit): boolean {
if (!candidate.candidate) return false;
// Basic validation - could be enhanced with security checks
const parts = candidate.candidate.split(" ");
return parts.length >= 6 && parts[0] === "candidate";
}
/**
* Setup signaling infrastructure
*/
private setupSignaling(): void {
// WebSocket signaling implementation would go here
// This is a placeholder for the signaling architecture
this.logger.info("Signaling setup completed");
}
/**
* Start performance monitoring
*/
private startMonitoring(): void {
setInterval(async () => {
for (const [peerId] of this.peers) {
try {
await this.monitorNetworkConditions(peerId);
} catch (error) {
this.logger.warn("Monitoring error", {
peerId,
error: (error as Error).message,
});
}
}
}, 5000); // Monitor every 5 seconds
}
/**
* Handle coordination messages
*/
private handleCoordinationMessage(message: any): void {
this.emit("coordination_message", message);
}
/**
* Setup transcription for audio stream
*/
private setupTranscription(
response: AudioStreamResponse,
language?: string,
): void {
// Speech recognition implementation would go here
response.transcription = {
enabled: true,
language: language || "en-US",
confidence: 0,
interim: "",
final: "",
};
}
/**
* Create standardized streaming error
*/
private createStreamingError(
code: string,
message: string,
severity: "low" | "medium" | "high" | "critical",
recoverable: boolean,
category:
| "network"
| "encoding"
| "decoding"
| "sync"
| "coordination"
| "permission",
context: any,
): StreamingError {
return {
code,
message,
severity,
recoverable,
category,
timestamp: Date.now(),
context,
recovery: {
suggested: ["retry", "reduce_quality", "switch_codec"],
automatic: recoverable,
retryable: recoverable,
fallback: "websocket",
},
};
}
/**
* Clean up peer connection
*/
async closePeer(peerId: string): Promise<void> {
const peer = this.peers.get(peerId);
if (peer) {
peer.connection.close();
this.peers.delete(peerId);
this.logger.info("Peer connection closed", { peerId });
}
}
/**
* Clean up all resources
*/
async cleanup(): Promise<void> {
for (const [peerId] of this.peers) {
await this.closePeer(peerId);
}
this.signalingEndpoints.forEach((ws) => ws.close());
this.removeAllListeners();
this.logger.info("WebRTC architecture cleaned up");
}
}
/**
* Performance monitoring helper class
*/
class PerformanceMonitor {
analyzeStats(stats: RTCStatsReport): NetworkConditions {
const conditions: NetworkConditions = {
bandwidth: { upload: 0, download: 0, available: 0 },
latency: { rtt: 0, jitter: 0 },
jitter: 0,
packetLoss: 0,
quality: { packetLoss: 0, stability: 1, congestion: 0 },
timestamp: Date.now(),
};
stats.forEach((report) => {
if (report.type === "candidate-pair" && report.state === "succeeded") {
(conditions.latency as { rtt: number; jitter: number }).rtt = report.currentRoundTripTime * 1000;
}
if (report.type === "inbound-rtp") {
conditions.quality!.packetLoss =
report.packetsLost / (report.packetsLost + report.packetsReceived);
(conditions.latency as { rtt: number; jitter: number }).jitter = report.jitter;
}
if (report.type === "outbound-rtp") {
(conditions.bandwidth as { upload: number; download: number; available: number }).upload = (report.bytesSent / report.timestamp) * 8;
}
});
return conditions;
}
}
/**
* Quality adaptation helper class
*/
class QualityAdapter {
private adaptationRules: QualityAdaptationRule[] = [];
private cooldowns = new Map<string, number>();
startAdaptation(
streamId: string,
type: "video" | "audio",
initialQuality: any,
): void {
// Initialize adaptation monitoring
}
evaluateConditions(streamId: string, conditions: NetworkConditions): void {
// Evaluate adaptation rules and adjust quality
}
}
/**
* Synchronization manager helper class
*/
class SynchronizationManager {
initializeSession(session: StreamingSession): void {
// Initialize synchronization for multi-agent session
}
}