peerpigeon 0.0.1

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.
Files changed (54) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1187 -0
  3. package/examples/browser/app-dht-disabled.js +42 -0
  4. package/examples/browser/app.js +51 -0
  5. package/examples/browser/assets/images/favicon.png +0 -0
  6. package/examples/browser/assets/images/pigeon.png +0 -0
  7. package/examples/browser/index-dht-disabled.html +123 -0
  8. package/examples/browser/index.html +340 -0
  9. package/examples/browser/styles.css +1288 -0
  10. package/examples/browser/ui-clean.js +0 -0
  11. package/examples/browser/ui.js +1930 -0
  12. package/index.js +8 -0
  13. package/package.json +70 -0
  14. package/server/index.js +515 -0
  15. package/src/CleanupManager.js +181 -0
  16. package/src/ConnectionManager.js +841 -0
  17. package/src/EventEmitter.js +27 -0
  18. package/src/EvictionManager.js +257 -0
  19. package/src/GossipManager.js +416 -0
  20. package/src/MediaManager.js +225 -0
  21. package/src/MeshOptimizer.js +181 -0
  22. package/src/PeerConnection.js +831 -0
  23. package/src/PeerDiscovery.js +297 -0
  24. package/src/PeerPigeonMesh.js +703 -0
  25. package/src/SignalingClient.js +536 -0
  26. package/src/SignalingHandler.js +325 -0
  27. package/src/StorageManager.js +88 -0
  28. package/src/TimerUtils.js +46 -0
  29. package/src/WebDHT.js +1099 -0
  30. package/websocket-server/README.md +257 -0
  31. package/websocket-server/memory-leak-test.js +193 -0
  32. package/websocket-server/node_modules/.package-lock.json +29 -0
  33. package/websocket-server/node_modules/ws/LICENSE +20 -0
  34. package/websocket-server/node_modules/ws/README.md +548 -0
  35. package/websocket-server/node_modules/ws/browser.js +8 -0
  36. package/websocket-server/node_modules/ws/index.js +13 -0
  37. package/websocket-server/node_modules/ws/lib/buffer-util.js +131 -0
  38. package/websocket-server/node_modules/ws/lib/constants.js +18 -0
  39. package/websocket-server/node_modules/ws/lib/event-target.js +292 -0
  40. package/websocket-server/node_modules/ws/lib/extension.js +203 -0
  41. package/websocket-server/node_modules/ws/lib/limiter.js +55 -0
  42. package/websocket-server/node_modules/ws/lib/permessage-deflate.js +528 -0
  43. package/websocket-server/node_modules/ws/lib/receiver.js +706 -0
  44. package/websocket-server/node_modules/ws/lib/sender.js +602 -0
  45. package/websocket-server/node_modules/ws/lib/stream.js +161 -0
  46. package/websocket-server/node_modules/ws/lib/subprotocol.js +62 -0
  47. package/websocket-server/node_modules/ws/lib/validation.js +152 -0
  48. package/websocket-server/node_modules/ws/lib/websocket-server.js +550 -0
  49. package/websocket-server/node_modules/ws/lib/websocket.js +1388 -0
  50. package/websocket-server/node_modules/ws/package.json +69 -0
  51. package/websocket-server/node_modules/ws/wrapper.mjs +8 -0
  52. package/websocket-server/package-lock.json +39 -0
  53. package/websocket-server/server.js +298 -0
  54. package/websocket-server/test.js +133 -0
@@ -0,0 +1,831 @@
1
+ import { EventEmitter } from './EventEmitter.js';
2
+
3
+ export class PeerConnection extends EventEmitter {
4
+ constructor(peerId, isInitiator = false, options = {}) {
5
+ super();
6
+ this.peerId = peerId;
7
+ this.isInitiator = isInitiator;
8
+ this.connection = null;
9
+ this.dataChannel = null;
10
+ this.remoteDescriptionSet = false;
11
+ this.dataChannelReady = false;
12
+ this.connectionStartTime = Date.now();
13
+ this.pendingIceCandidates = [];
14
+ this.iceCheckingTimeout = null; // Timeout for ICE checking state
15
+ this.connectingTimeout = null; // Timeout for stuck connecting state
16
+ this.isClosing = false; // Flag to prevent disconnection events during intentional close
17
+ this._forcedStatus = null; // Track forced status (e.g., failed)
18
+
19
+ // Media stream support
20
+ this.localStream = options.localStream || null;
21
+ this.remoteStream = null;
22
+ this.enableVideo = options.enableVideo || false;
23
+ this.enableAudio = options.enableAudio || false;
24
+ }
25
+
26
+ /**
27
+ * Force this connection into a terminal state (e.g., failed/timeout)
28
+ */
29
+ markAsFailed(reason = 'failed') {
30
+ this._forcedStatus = reason;
31
+ try {
32
+ this.close();
33
+ } catch (e) {}
34
+ }
35
+
36
+ async createConnection() {
37
+ this.connection = new RTCPeerConnection({
38
+ iceServers: [
39
+ { urls: 'stun:stun.l.google.com:19302' },
40
+ { urls: 'stun:stun1.l.google.com:19302' }
41
+ ]
42
+ });
43
+
44
+ this.setupConnectionHandlers();
45
+
46
+ // Pre-allocate placeholder transceivers for audio and video to avoid m-line order issues
47
+ // This ensures consistent SDP structure even when media is added later
48
+ console.log('🔄 Pre-allocating transceivers for stable media negotiation');
49
+
50
+ // Add audio transceiver (inactive initially) - start with recvonly to avoid conflicts
51
+ this.audioTransceiver = this.connection.addTransceiver('audio', {
52
+ direction: 'recvonly'
53
+ });
54
+
55
+ // Add video transceiver (inactive initially) - for future use
56
+ this.videoTransceiver = this.connection.addTransceiver('video', {
57
+ direction: 'recvonly'
58
+ });
59
+
60
+ // Add local media stream if provided
61
+ if (this.localStream) {
62
+ console.log('Adding local stream tracks to existing transceivers');
63
+ await this.setLocalStreamToTransceivers(this.localStream);
64
+ }
65
+
66
+ if (this.isInitiator) {
67
+ this.dataChannel = this.connection.createDataChannel('messages', {
68
+ ordered: true
69
+ });
70
+ this.setupDataChannel();
71
+ } else {
72
+ this.connection.ondatachannel = (event) => {
73
+ console.log('Received data channel from', this.peerId);
74
+ this.dataChannel = event.channel;
75
+ this.setupDataChannel();
76
+ };
77
+ }
78
+ }
79
+
80
+ setupConnectionHandlers() {
81
+ this.connection.onicecandidate = (event) => {
82
+ if (event.candidate) {
83
+ console.log(`🧊 Generated ICE candidate for ${this.peerId.substring(0, 8)}...`, {
84
+ type: event.candidate.type,
85
+ protocol: event.candidate.protocol,
86
+ address: event.candidate.address?.substring(0, 10) + '...' || 'unknown'
87
+ });
88
+ this.emit('iceCandidate', { peerId: this.peerId, candidate: event.candidate });
89
+ } else {
90
+ console.log(`🧊 ICE gathering complete for ${this.peerId.substring(0, 8)}...`);
91
+ }
92
+ };
93
+
94
+ // Handle remote media streams
95
+ this.connection.ontrack = (event) => {
96
+ console.log('🎵 Received remote media stream from', this.peerId);
97
+ const stream = event.streams[0];
98
+ const track = event.track;
99
+
100
+ console.log(`🎵 Track received: kind=${track.kind}, id=${track.id}, enabled=${track.enabled}, readyState=${track.readyState}`);
101
+
102
+ // CRITICAL: Check if this is actually a remote stream or our own local stream
103
+ if (this.localStream && stream.id === this.localStream.id) {
104
+ console.error('❌ LOOPBACK DETECTED: Received our own local stream as remote!');
105
+ console.error('Local stream ID:', this.localStream.id);
106
+ console.error('Received stream ID:', stream.id);
107
+ return; // Don't process our own stream as remote
108
+ }
109
+
110
+ if (stream) {
111
+ this.remoteStream = stream;
112
+ const audioTracks = stream.getAudioTracks();
113
+ const videoTracks = stream.getVideoTracks();
114
+
115
+ console.log(`🎵 Remote stream tracks: ${audioTracks.length} audio, ${videoTracks.length} video`);
116
+ console.log(`🎵 Remote stream ID: ${stream.id} (vs local: ${this.localStream?.id || 'none'})`);
117
+
118
+ audioTracks.forEach((audioTrack, index) => {
119
+ console.log(`🎵 Audio track ${index}: enabled=${audioTrack.enabled}, readyState=${audioTrack.readyState}, muted=${audioTrack.muted}, id=${audioTrack.id}`);
120
+
121
+ // Check if this track ID matches any of our local tracks
122
+ if (this.localStream) {
123
+ const localAudioTracks = this.localStream.getAudioTracks();
124
+ const isOwnTrack = localAudioTracks.some(localTrack => localTrack.id === audioTrack.id);
125
+ if (isOwnTrack) {
126
+ console.error('❌ LOOPBACK: This audio track is our own local track!');
127
+ }
128
+ }
129
+
130
+ // Add audio data monitoring
131
+ this.setupAudioDataMonitoring(audioTrack, index);
132
+ });
133
+
134
+ this.emit('remoteStream', { peerId: this.peerId, stream: this.remoteStream });
135
+ }
136
+ };
137
+
138
+ this.connection.onconnectionstatechange = () => {
139
+ console.log(`🔗 Connection state with ${this.peerId}: ${this.connection.connectionState} (previous signaling: ${this.connection.signalingState})`);
140
+
141
+ // Log additional context about transceivers and media
142
+ const transceivers = this.connection.getTransceivers();
143
+ const audioSending = this.audioTransceiver && this.audioTransceiver.sender.track;
144
+ const videoSending = this.videoTransceiver && this.videoTransceiver.sender.track;
145
+ console.log(`🔗 Media context: Audio sending=${!!audioSending}, Video sending=${!!videoSending}, Transceivers=${transceivers.length}`);
146
+
147
+ if (this.connection.connectionState === 'connected') {
148
+ // Clear any pending timeouts
149
+ if (this.connectingTimeout) {
150
+ clearTimeout(this.connectingTimeout);
151
+ this.connectingTimeout = null;
152
+ }
153
+ console.log(`✅ Connection established with ${this.peerId}`);
154
+ this.emit('connected', { peerId: this.peerId });
155
+ } else if (this.connection.connectionState === 'connecting') {
156
+ console.log(`🔄 Connection to ${this.peerId} is connecting...`);
157
+ // Add timeout for stuck connecting state
158
+ if (this.connectingTimeout) {
159
+ clearTimeout(this.connectingTimeout);
160
+ }
161
+ this.connectingTimeout = setTimeout(() => {
162
+ if (this.connection && this.connection.connectionState === 'connecting' && !this.isClosing) {
163
+ console.log(`⏰ Connection stuck in connecting state for ${this.peerId}, treating as failed`);
164
+ this.emit('disconnected', { peerId: this.peerId, reason: 'connection timeout' });
165
+ }
166
+ }, 20000); // Increased timeout to 20 seconds for better stability
167
+ } else if (this.connection.connectionState === 'disconnected') {
168
+ // Give WebRTC more time to recover - it's common for connections to briefly disconnect during renegotiation
169
+ console.log(`⚠️ WebRTC connection disconnected for ${this.peerId}, waiting for potential recovery...`);
170
+ setTimeout(() => {
171
+ if (this.connection &&
172
+ this.connection.connectionState === 'disconnected' &&
173
+ !this.isClosing) {
174
+ console.log(`❌ WebRTC connection remained disconnected for ${this.peerId}, treating as failed`);
175
+ this.emit('disconnected', { peerId: this.peerId, reason: 'connection disconnected' });
176
+ }
177
+ }, 8000); // Increased wait time to 8 seconds to account for renegotiation
178
+ } else if (this.connection.connectionState === 'failed') {
179
+ if (!this.isClosing) {
180
+ console.log(`❌ Connection failed for ${this.peerId}`);
181
+ this.emit('disconnected', { peerId: this.peerId, reason: 'connection failed' });
182
+ }
183
+ } else if (this.connection.connectionState === 'closed') {
184
+ if (!this.isClosing) {
185
+ console.log(`❌ Connection closed for ${this.peerId}`);
186
+ this.emit('disconnected', { peerId: this.peerId, reason: 'connection closed' });
187
+ }
188
+ }
189
+ };
190
+
191
+ this.connection.oniceconnectionstatechange = () => {
192
+ console.log(`🧊 ICE connection state with ${this.peerId}: ${this.connection.iceConnectionState}`);
193
+
194
+ if (this.connection.iceConnectionState === 'connected') {
195
+ // Clear any pending timeout
196
+ if (this.iceCheckingTimeout) {
197
+ clearTimeout(this.iceCheckingTimeout);
198
+ this.iceCheckingTimeout = null;
199
+ }
200
+ console.log(`✅ ICE connection established with ${this.peerId}`);
201
+ } else if (this.connection.iceConnectionState === 'checking') {
202
+ console.log(`🔄 ICE checking for ${this.peerId}...`);
203
+ // Set a timeout for ICE checking state - if it takes too long, restart
204
+ if (this.iceCheckingTimeout) {
205
+ clearTimeout(this.iceCheckingTimeout);
206
+ }
207
+ this.iceCheckingTimeout = setTimeout(() => {
208
+ if (this.connection && this.connection.iceConnectionState === 'checking') {
209
+ console.log(`⏰ ICE checking timeout for ${this.peerId}, attempting restart`);
210
+ try {
211
+ this.connection.restartIce();
212
+ } catch (error) {
213
+ console.error('Failed to restart ICE:', error);
214
+ this.emit('disconnected', { peerId: this.peerId, reason: 'ICE restart failed' });
215
+ }
216
+ }
217
+ }, 20000); // Increased timeout to 20 seconds for ICE checking
218
+ } else if (this.connection.iceConnectionState === 'failed') {
219
+ console.log(`❌ ICE connection failed for ${this.peerId}, attempting restart`);
220
+ try {
221
+ this.connection.restartIce();
222
+ } catch (error) {
223
+ console.error('Failed to restart ICE after failure:', error);
224
+ this.emit('disconnected', { peerId: this.peerId, reason: 'ICE failed' });
225
+ }
226
+ } else if (this.connection.iceConnectionState === 'disconnected') {
227
+ // Give more time for ICE reconnection - this is common during renegotiation
228
+ console.log(`⚠️ ICE connection disconnected for ${this.peerId}, waiting for potential reconnection...`);
229
+ setTimeout(() => {
230
+ if (this.connection &&
231
+ this.connection.iceConnectionState === 'disconnected' &&
232
+ !this.isClosing) {
233
+ console.log(`❌ ICE remained disconnected for ${this.peerId}, attempting restart`);
234
+ try {
235
+ this.connection.restartIce();
236
+ } catch (error) {
237
+ console.error('Failed to restart ICE after disconnection:', error);
238
+ this.emit('disconnected', { peerId: this.peerId, reason: 'ICE disconnected' });
239
+ }
240
+ }
241
+ }, 10000); // Increased wait time to 10 seconds for ICE reconnection
242
+ }
243
+ };
244
+
245
+ // Handle renegotiation when tracks are added/removed
246
+ this.connection.onnegotiationneeded = () => {
247
+ console.log(`🔄 Negotiation needed for ${this.peerId} (WebRTC detected track changes)`);
248
+ // With pre-allocated transceivers, we should NEVER need renegotiation
249
+ // Any renegotiation indicates a problem with our transceiver approach
250
+ console.log('🚫 UNEXPECTED: Renegotiation triggered despite transceiver approach - investigating...');
251
+
252
+ // Log debug info about current transceivers
253
+ const transceivers = this.connection.getTransceivers();
254
+ console.log('� Transceivers state during unexpected negotiation:', transceivers.map(t => ({
255
+ kind: t.receiver.track?.kind || 'unknown',
256
+ direction: t.direction,
257
+ hasTrack: !!t.sender.track,
258
+ mid: t.mid
259
+ })));
260
+
261
+ // For now, ignore renegotiation to prevent connection issues
262
+ // this.emit('renegotiationNeeded', { peerId: this.peerId });
263
+ };
264
+ }
265
+
266
+ setupDataChannel() {
267
+ this.dataChannel.onopen = () => {
268
+ console.log(`Data channel opened with ${this.peerId}`);
269
+ this.dataChannelReady = true;
270
+ this.emit('dataChannelOpen', { peerId: this.peerId });
271
+ };
272
+
273
+ this.dataChannel.onclose = () => {
274
+ console.log(`Data channel closed with ${this.peerId}`);
275
+ this.dataChannelReady = false;
276
+
277
+ // Only emit disconnection if we're not intentionally closing
278
+ if (!this.isClosing) {
279
+ this.emit('disconnected', { peerId: this.peerId, reason: 'data channel closed' });
280
+ }
281
+ };
282
+
283
+ this.dataChannel.onmessage = (event) => {
284
+ try {
285
+ const message = JSON.parse(event.data);
286
+ this.emit('message', { peerId: this.peerId, message });
287
+ } catch (error) {
288
+ console.error('Failed to parse message:', error);
289
+ this.emit('message', { peerId: this.peerId, message: { content: event.data } });
290
+ }
291
+ };
292
+
293
+ this.dataChannel.onerror = (error) => {
294
+ console.error(`Data channel error with ${this.peerId}:`, error);
295
+ this.dataChannelReady = false;
296
+
297
+ // Only emit disconnection if we're not intentionally closing
298
+ if (!this.isClosing) {
299
+ this.emit('disconnected', { peerId: this.peerId, reason: 'data channel error' });
300
+ }
301
+ };
302
+ }
303
+
304
+ async createOffer() {
305
+ const offer = await this.connection.createOffer();
306
+ await this.connection.setLocalDescription(offer);
307
+ return offer;
308
+ }
309
+
310
+ async handleOffer(offer) {
311
+ // Check if we're in the right state to handle an offer
312
+ if (this.connection.signalingState !== 'stable') {
313
+ console.log(`Cannot handle offer from ${this.peerId} - connection state is ${this.connection.signalingState} (expected: stable)`);
314
+ throw new Error(`Cannot handle offer in state: ${this.connection.signalingState}`);
315
+ }
316
+
317
+ await this.connection.setRemoteDescription(offer);
318
+ this.remoteDescriptionSet = true;
319
+ await this.processPendingIceCandidates();
320
+
321
+ const answer = await this.connection.createAnswer();
322
+ await this.connection.setLocalDescription(answer);
323
+ return answer;
324
+ }
325
+
326
+ async handleAnswer(answer) {
327
+ // Check if we're in the right state to handle an answer
328
+ if (this.connection.signalingState !== 'have-local-offer') {
329
+ console.log(`Cannot handle answer from ${this.peerId} - connection state is ${this.connection.signalingState} (expected: have-local-offer)`);
330
+
331
+ // If we're already stable, the connection might already be established
332
+ if (this.connection.signalingState === 'stable') {
333
+ console.log('Connection already stable, answer not needed');
334
+ return;
335
+ }
336
+
337
+ throw new Error(`Cannot handle answer in state: ${this.connection.signalingState}`);
338
+ }
339
+
340
+ await this.connection.setRemoteDescription(answer);
341
+ this.remoteDescriptionSet = true;
342
+ await this.processPendingIceCandidates();
343
+ }
344
+
345
+ async handleIceCandidate(candidate) {
346
+ console.log(`🧊 Received ICE candidate for ${this.peerId.substring(0, 8)}...`, {
347
+ type: candidate.type,
348
+ protocol: candidate.protocol
349
+ });
350
+
351
+ if (!this.remoteDescriptionSet) {
352
+ console.log(`🧊 Buffering ICE candidate for ${this.peerId.substring(0, 8)}... (remote description not set yet)`);
353
+ this.pendingIceCandidates.push(candidate);
354
+ return;
355
+ }
356
+
357
+ try {
358
+ await this.connection.addIceCandidate(candidate);
359
+ console.log(`🧊 Successfully added ICE candidate for ${this.peerId.substring(0, 8)}...`);
360
+ } catch (error) {
361
+ console.error(`🧊 Failed to add ICE candidate for ${this.peerId.substring(0, 8)}...:`, error);
362
+ }
363
+ }
364
+
365
+ async processPendingIceCandidates() {
366
+ if (this.pendingIceCandidates.length > 0) {
367
+ console.log(`🧊 Processing ${this.pendingIceCandidates.length} buffered ICE candidates for ${this.peerId.substring(0, 8)}...`);
368
+
369
+ for (const candidate of this.pendingIceCandidates) {
370
+ try {
371
+ await this.connection.addIceCandidate(candidate);
372
+ console.log(`🧊 Successfully added buffered ICE candidate (${candidate.type}) for ${this.peerId.substring(0, 8)}...`);
373
+ } catch (error) {
374
+ console.error(`🧊 Failed to add buffered ICE candidate for ${this.peerId.substring(0, 8)}...:`, error);
375
+ }
376
+ }
377
+
378
+ this.pendingIceCandidates = [];
379
+ console.log(`🧊 Finished processing buffered ICE candidates for ${this.peerId.substring(0, 8)}...`);
380
+ }
381
+ }
382
+
383
+ sendMessage(message) {
384
+ if (this.dataChannel && this.dataChannel.readyState === 'open') {
385
+ try {
386
+ this.dataChannel.send(JSON.stringify(message));
387
+ return true;
388
+ } catch (error) {
389
+ console.error(`Failed to send message to ${this.peerId}:`, error);
390
+ return false;
391
+ }
392
+ }
393
+ return false;
394
+ }
395
+
396
+ /**
397
+ * Add or replace local media stream
398
+ */
399
+ async setLocalStream(stream) {
400
+ if (!this.connection) {
401
+ throw new Error('Connection not initialized');
402
+ }
403
+
404
+ console.log(`Setting local stream for ${this.peerId}, current state: ${this.connection.connectionState}, signaling: ${this.connection.signalingState}`);
405
+
406
+ // DEBUG: Log current transceivers before any changes
407
+ const transceivers = this.connection.getTransceivers();
408
+ console.log(`🔍 Current transceivers before stream change:`, transceivers.map(t => ({
409
+ kind: t.receiver.track?.kind || 'unknown',
410
+ direction: t.direction,
411
+ hasTrack: !!t.sender.track,
412
+ mid: t.mid
413
+ })));
414
+
415
+ // Use stored transceiver references for reliable access
416
+ console.log('🔄 Using stored transceiver references for media');
417
+
418
+ if (stream) {
419
+ const audioTracks = stream.getAudioTracks();
420
+ const videoTracks = stream.getVideoTracks();
421
+
422
+ // Handle audio track using stored reference
423
+ if (this.audioTransceiver) {
424
+ if (audioTracks.length > 0) {
425
+ console.log('🔄 Replacing audio track in stored transceiver');
426
+ await this.audioTransceiver.sender.replaceTrack(audioTracks[0]);
427
+ this.audioTransceiver.direction = 'sendrecv';
428
+
429
+ // Setup audio sending monitoring
430
+ this.setupAudioSendingMonitoring(audioTracks[0]);
431
+ console.log(`🎤 SENDING AUDIO to peer ${this.peerId.substring(0, 8)} - track enabled: ${audioTracks[0].enabled}`);
432
+ } else {
433
+ console.log('🔄 Removing audio track from stored transceiver');
434
+ await this.audioTransceiver.sender.replaceTrack(null);
435
+ this.audioTransceiver.direction = 'recvonly';
436
+ console.log(`🎤 STOPPED SENDING AUDIO to peer ${this.peerId.substring(0, 8)}`);
437
+ }
438
+ }
439
+
440
+ // Handle video track using stored reference
441
+ if (this.videoTransceiver) {
442
+ if (videoTracks.length > 0) {
443
+ console.log('🔄 Replacing video track in stored transceiver');
444
+ await this.videoTransceiver.sender.replaceTrack(videoTracks[0]);
445
+ this.videoTransceiver.direction = 'sendrecv';
446
+ } else {
447
+ console.log('🔄 Removing video track from stored transceiver');
448
+ await this.videoTransceiver.sender.replaceTrack(null);
449
+ this.videoTransceiver.direction = 'recvonly';
450
+ }
451
+ }
452
+
453
+ this.localStream = stream;
454
+ console.log('✅ Stream set successfully using stored transceivers');
455
+ } else {
456
+ // Remove all tracks using stored references
457
+ if (this.audioTransceiver) {
458
+ console.log('🔄 Removing audio track from stored transceiver');
459
+ await this.audioTransceiver.sender.replaceTrack(null);
460
+ this.audioTransceiver.direction = 'recvonly';
461
+ }
462
+
463
+ if (this.videoTransceiver) {
464
+ console.log('🔄 Removing video track from stored transceiver');
465
+ await this.videoTransceiver.sender.replaceTrack(null);
466
+ this.videoTransceiver.direction = 'recvonly';
467
+ }
468
+
469
+ this.localStream = null;
470
+ console.log('✅ All tracks removed using stored transceivers');
471
+ }
472
+
473
+ console.log('Updated local media stream for', this.peerId);
474
+
475
+ // DEBUG: Log final transceivers after changes
476
+ const finalTransceivers = this.connection.getTransceivers();
477
+ console.log(`🔍 Final transceivers after stream change:`, finalTransceivers.map(t => ({
478
+ kind: t.receiver.track?.kind || 'unknown',
479
+ direction: t.direction,
480
+ hasTrack: !!t.sender.track,
481
+ trackId: t.sender.track?.id?.substring(0, 8) || 'none',
482
+ mid: t.mid
483
+ })));
484
+ }
485
+
486
+ /**
487
+ * Helper method to set local stream tracks to existing transceivers
488
+ */
489
+ async setLocalStreamToTransceivers(stream) {
490
+ if (stream) {
491
+ const audioTracks = stream.getAudioTracks();
492
+ const videoTracks = stream.getVideoTracks();
493
+
494
+ // Set audio track to stored audio transceiver
495
+ if (this.audioTransceiver && audioTracks.length > 0) {
496
+ console.log('🔄 Setting audio track to stored audio transceiver');
497
+ await this.audioTransceiver.sender.replaceTrack(audioTracks[0]);
498
+ this.audioTransceiver.direction = 'sendrecv';
499
+
500
+ // Setup audio sending monitoring
501
+ this.setupAudioSendingMonitoring(audioTracks[0]);
502
+ console.log(`🎤 SENDING AUDIO to peer ${this.peerId.substring(0, 8)} via transceiver - track enabled: ${audioTracks[0].enabled}`);
503
+ }
504
+
505
+ // Set video track to stored video transceiver
506
+ if (this.videoTransceiver && videoTracks.length > 0) {
507
+ console.log('🔄 Setting video track to stored video transceiver');
508
+ await this.videoTransceiver.sender.replaceTrack(videoTracks[0]);
509
+ this.videoTransceiver.direction = 'sendrecv';
510
+ }
511
+ }
512
+ }
513
+
514
+ /**
515
+ * Setup audio data monitoring for received audio tracks
516
+ */
517
+ setupAudioDataMonitoring(audioTrack, trackIndex) {
518
+ console.log(`🎵 Setting up audio data monitoring for track ${trackIndex} from peer ${this.peerId.substring(0, 8)}`);
519
+
520
+ try {
521
+ // Create audio context for analyzing audio data
522
+ const AudioContext = window.AudioContext || window.webkitAudioContext;
523
+ if (!AudioContext) {
524
+ console.warn('🎵 AudioContext not available - cannot monitor audio data');
525
+ return;
526
+ }
527
+
528
+ // Create a MediaStream with just this audio track for analysis
529
+ const trackStream = new MediaStream([audioTrack]);
530
+ const audioContext = new AudioContext();
531
+ const source = audioContext.createMediaStreamSource(trackStream);
532
+ const analyser = audioContext.createAnalyser();
533
+
534
+ analyser.fftSize = 256;
535
+ const bufferLength = analyser.frequencyBinCount;
536
+ const dataArray = new Uint8Array(bufferLength);
537
+
538
+ source.connect(analyser);
539
+
540
+ let lastLogTime = 0;
541
+ let totalSamples = 0;
542
+ let samplesWithAudio = 0;
543
+ let maxLevel = 0;
544
+
545
+ // Monitor audio levels periodically
546
+ const monitorAudio = () => {
547
+ if (audioTrack.readyState === 'ended') {
548
+ console.log(`🎵 Audio track ${trackIndex} ended, stopping monitoring for peer ${this.peerId.substring(0, 8)}`);
549
+ audioContext.close();
550
+ return;
551
+ }
552
+
553
+ analyser.getByteFrequencyData(dataArray);
554
+
555
+ // Calculate audio level (0-255)
556
+ const average = dataArray.reduce((sum, value) => sum + value, 0) / bufferLength;
557
+ const currentTime = Date.now();
558
+
559
+ totalSamples++;
560
+ if (average > 5) { // Threshold for detecting audio activity
561
+ samplesWithAudio++;
562
+ maxLevel = Math.max(maxLevel, average);
563
+ }
564
+
565
+ // Log every 5 seconds
566
+ if (currentTime - lastLogTime > 5000) {
567
+ const audioActivity = totalSamples > 0 ? (samplesWithAudio / totalSamples * 100) : 0;
568
+ console.log(`🎵 Audio data from peer ${this.peerId.substring(0, 8)} track ${trackIndex}:`, {
569
+ enabled: audioTrack.enabled,
570
+ readyState: audioTrack.readyState,
571
+ muted: audioTrack.muted,
572
+ currentLevel: Math.round(average),
573
+ maxLevel: Math.round(maxLevel),
574
+ activityPercent: Math.round(audioActivity),
575
+ samplesAnalyzed: totalSamples,
576
+ hasAudioData: samplesWithAudio > 0
577
+ });
578
+
579
+ lastLogTime = currentTime;
580
+ // Reset counters for next period
581
+ totalSamples = 0;
582
+ samplesWithAudio = 0;
583
+ maxLevel = 0;
584
+ }
585
+
586
+ // Continue monitoring if track is still active
587
+ if (audioTrack.readyState === 'live') {
588
+ requestAnimationFrame(monitorAudio);
589
+ }
590
+ };
591
+
592
+ // Start monitoring
593
+ requestAnimationFrame(monitorAudio);
594
+
595
+ // Track state changes
596
+ audioTrack.addEventListener('ended', () => {
597
+ console.log(`🎵 Audio track ${trackIndex} from peer ${this.peerId.substring(0, 8)} ended`);
598
+ audioContext.close();
599
+ });
600
+
601
+ audioTrack.addEventListener('mute', () => {
602
+ console.log(`🎵 Audio track ${trackIndex} from peer ${this.peerId.substring(0, 8)} muted`);
603
+ });
604
+
605
+ audioTrack.addEventListener('unmute', () => {
606
+ console.log(`🎵 Audio track ${trackIndex} from peer ${this.peerId.substring(0, 8)} unmuted`);
607
+ });
608
+
609
+ console.log(`🎵 Audio monitoring started for track ${trackIndex} from peer ${this.peerId.substring(0, 8)}`);
610
+
611
+ } catch (error) {
612
+ console.error(`🎵 Failed to setup audio monitoring for track ${trackIndex}:`, error);
613
+ }
614
+ }
615
+
616
+ /**
617
+ * Setup audio sending monitoring for outgoing audio tracks
618
+ */
619
+ setupAudioSendingMonitoring(audioTrack) {
620
+ console.log(`🎤 Setting up audio SENDING monitoring to peer ${this.peerId.substring(0, 8)}`);
621
+
622
+ try {
623
+ // Monitor track state changes
624
+ audioTrack.addEventListener('ended', () => {
625
+ console.log(`🎤 Audio SENDING track ended to peer ${this.peerId.substring(0, 8)}`);
626
+ });
627
+
628
+ audioTrack.addEventListener('mute', () => {
629
+ console.log(`🎤 Audio SENDING track muted to peer ${this.peerId.substring(0, 8)}`);
630
+ });
631
+
632
+ audioTrack.addEventListener('unmute', () => {
633
+ console.log(`🎤 Audio SENDING track unmuted to peer ${this.peerId.substring(0, 8)}`);
634
+ });
635
+
636
+ // Monitor audio input levels if possible
637
+ const AudioContext = window.AudioContext || window.webkitAudioContext;
638
+ if (!AudioContext) {
639
+ console.warn('🎤 AudioContext not available - basic sending monitoring only');
640
+ return;
641
+ }
642
+
643
+ const trackStream = new MediaStream([audioTrack]);
644
+ const audioContext = new AudioContext();
645
+ const source = audioContext.createMediaStreamSource(trackStream);
646
+ const analyser = audioContext.createAnalyser();
647
+
648
+ analyser.fftSize = 256;
649
+ const bufferLength = analyser.frequencyBinCount;
650
+ const dataArray = new Uint8Array(bufferLength);
651
+
652
+ source.connect(analyser);
653
+
654
+ let lastLogTime = 0;
655
+ let totalSamples = 0;
656
+ let activeSamples = 0;
657
+ let maxSendLevel = 0;
658
+
659
+ const monitorSending = () => {
660
+ if (audioTrack.readyState === 'ended') {
661
+ console.log(`🎤 Audio sending track ended, stopping monitoring to peer ${this.peerId.substring(0, 8)}`);
662
+ audioContext.close();
663
+ return;
664
+ }
665
+
666
+ analyser.getByteFrequencyData(dataArray);
667
+
668
+ const average = dataArray.reduce((sum, value) => sum + value, 0) / bufferLength;
669
+ const currentTime = Date.now();
670
+
671
+ totalSamples++;
672
+ if (average > 5) {
673
+ activeSamples++;
674
+ maxSendLevel = Math.max(maxSendLevel, average);
675
+ }
676
+
677
+ // Log every 5 seconds
678
+ if (currentTime - lastLogTime > 5000) {
679
+ const sendingActivity = totalSamples > 0 ? (activeSamples / totalSamples * 100) : 0;
680
+ console.log(`🎤 Audio SENDING to peer ${this.peerId.substring(0, 8)}:`, {
681
+ trackEnabled: audioTrack.enabled,
682
+ trackReadyState: audioTrack.readyState,
683
+ trackMuted: audioTrack.muted,
684
+ currentSendLevel: Math.round(average),
685
+ maxSendLevel: Math.round(maxSendLevel),
686
+ sendingActivityPercent: Math.round(sendingActivity),
687
+ samplesAnalyzed: totalSamples,
688
+ audioBeingSent: activeSamples > 0
689
+ });
690
+
691
+ lastLogTime = currentTime;
692
+ totalSamples = 0;
693
+ activeSamples = 0;
694
+ maxSendLevel = 0;
695
+ }
696
+
697
+ if (audioTrack.readyState === 'live') {
698
+ requestAnimationFrame(monitorSending);
699
+ }
700
+ };
701
+
702
+ requestAnimationFrame(monitorSending);
703
+ console.log(`🎤 Audio sending monitoring started to peer ${this.peerId.substring(0, 8)}`);
704
+
705
+ } catch (error) {
706
+ console.error(`🎤 Failed to setup audio sending monitoring to peer ${this.peerId.substring(0, 8)}:`, error);
707
+ }
708
+ }
709
+
710
+ /**
711
+ * Get remote media stream
712
+ */
713
+ getRemoteStream() {
714
+ return this.remoteStream;
715
+ }
716
+
717
+ /**
718
+ * Get local media stream
719
+ */
720
+ getLocalStream() {
721
+ return this.localStream;
722
+ }
723
+
724
+ /**
725
+ * Check if connection has video/audio capabilities
726
+ */
727
+ getMediaCapabilities() {
728
+ const capabilities = {
729
+ hasLocalVideo: false,
730
+ hasLocalAudio: false,
731
+ hasRemoteVideo: false,
732
+ hasRemoteAudio: false
733
+ };
734
+
735
+ if (this.localStream) {
736
+ capabilities.hasLocalVideo = this.localStream.getVideoTracks().length > 0;
737
+ capabilities.hasLocalAudio = this.localStream.getAudioTracks().length > 0;
738
+ }
739
+
740
+ if (this.remoteStream) {
741
+ capabilities.hasRemoteVideo = this.remoteStream.getVideoTracks().length > 0;
742
+ capabilities.hasRemoteAudio = this.remoteStream.getAudioTracks().length > 0;
743
+ }
744
+
745
+ return capabilities;
746
+ }
747
+
748
+ getStatus() {
749
+ if (this._forcedStatus) {
750
+ return this._forcedStatus;
751
+ }
752
+ // First check if data channel is closed - this indicates disconnection regardless of WebRTC state
753
+ if (this.dataChannel && this.dataChannel.readyState === 'closed') {
754
+ return 'disconnected';
755
+ }
756
+
757
+ // If we have a WebRTC connection, check its state
758
+ if (this.connection) {
759
+ const connectionState = this.connection.connectionState;
760
+
761
+ if (connectionState === 'connected') {
762
+ // Connection is established, now check data channel
763
+ if (this.dataChannel && this.dataChannel.readyState === 'open' && this.dataChannelReady) {
764
+ return 'connected';
765
+ } else if (this.dataChannel && this.dataChannel.readyState === 'open') {
766
+ return 'connected';
767
+ } else if (this.dataChannel && this.dataChannel.readyState === 'connecting') {
768
+ return 'channel-connecting';
769
+ } else {
770
+ return 'connected';
771
+ }
772
+ } else if (connectionState === 'connecting') {
773
+ // Check data channel state even during connection
774
+ if (this.dataChannel && this.dataChannel.readyState === 'connecting') {
775
+ return 'channel-connecting';
776
+ } else {
777
+ return 'connecting';
778
+ }
779
+ } else if (connectionState === 'new') {
780
+ return 'connecting'; // Map 'new' to 'connecting' for UI consistency
781
+ } else {
782
+ // Failed, disconnected, closed, etc.
783
+ return connectionState;
784
+ }
785
+ }
786
+
787
+ // If no connection but we have a data channel (edge case)
788
+ if (this.dataChannel) {
789
+ if (this.dataChannel.readyState === 'connecting') {
790
+ return 'channel-connecting';
791
+ } else if (this.dataChannel.readyState === 'closed') {
792
+ return 'disconnected';
793
+ }
794
+ }
795
+
796
+ // Default state when just created
797
+ return 'connecting';
798
+ }
799
+
800
+ getDetailedStatus() {
801
+ const status = {
802
+ connectionState: this.connection ? this.connection.connectionState : 'no-connection',
803
+ iceConnectionState: this.connection ? this.connection.iceConnectionState : 'no-connection',
804
+ dataChannelState: this.dataChannel ? this.dataChannel.readyState : 'no-channel',
805
+ dataChannelReady: this.dataChannelReady,
806
+ isClosing: this.isClosing,
807
+ overallStatus: this.getStatus()
808
+ };
809
+ return status;
810
+ }
811
+
812
+ close() {
813
+ // Set flag to prevent disconnection events during intentional close
814
+ this.isClosing = true;
815
+
816
+ // Clear any pending timeouts
817
+ if (this.iceCheckingTimeout) {
818
+ clearTimeout(this.iceCheckingTimeout);
819
+ this.iceCheckingTimeout = null;
820
+ }
821
+
822
+ if (this.connectingTimeout) {
823
+ clearTimeout(this.connectingTimeout);
824
+ this.connectingTimeout = null;
825
+ }
826
+
827
+ if (this.connection) {
828
+ this.connection.close();
829
+ }
830
+ }
831
+ }