peerpigeon 0.0.7 → 0.1.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.
@@ -1,10 +1,12 @@
1
1
  import { EventEmitter } from './EventEmitter.js';
2
2
  import { environmentDetector } from './EnvironmentDetector.js';
3
+ import DebugLogger from './DebugLogger.js';
3
4
 
4
5
  export class PeerConnection extends EventEmitter {
5
6
  constructor(peerId, isInitiator = false, options = {}) {
6
7
  super();
7
8
  this.peerId = peerId;
9
+ this.debug = DebugLogger.create('PeerConnection');
8
10
  this.isInitiator = isInitiator;
9
11
  this.connection = null;
10
12
  this.dataChannel = null;
@@ -14,6 +16,7 @@ export class PeerConnection extends EventEmitter {
14
16
  this.pendingIceCandidates = [];
15
17
  this.iceCheckingTimeout = null; // Timeout for ICE checking state
16
18
  this.connectingTimeout = null; // Timeout for stuck connecting state
19
+ this.dataChannelHealthMonitor = null; // Health monitoring for data channel when signaling is unavailable
17
20
  this.isClosing = false; // Flag to prevent disconnection events during intentional close
18
21
  this._forcedStatus = null; // Track forced status (e.g., failed)
19
22
 
@@ -53,35 +56,24 @@ export class PeerConnection extends EventEmitter {
53
56
 
54
57
  this.setupConnectionHandlers();
55
58
 
56
- // Only pre-allocate transceivers if media is actually intended to be used
57
- // This prevents unnecessary WebRTC negotiations for data-only connections
58
- const hasLocalMedia = this.localStream && (this.localStream.getAudioTracks().length > 0 || this.localStream.getVideoTracks().length > 0);
59
- const intendToUseMedia = this.enableVideo || this.enableAudio || hasLocalMedia;
59
+ // ALWAYS pre-allocate transceivers for audio and video to enable future media streaming
60
+ // This ensures connections can handle media even if no media stream is available initially
61
+ this.debug.log('🔄 Pre-allocating audio and video transceivers for future media capability');
60
62
 
61
- if (intendToUseMedia) {
62
- console.log('🔄 Pre-allocating transceivers for stable media negotiation');
63
-
64
- // Add audio transceiver only if audio is enabled or present
65
- if (this.enableAudio || (this.localStream && this.localStream.getAudioTracks().length > 0)) {
66
- this.audioTransceiver = this.connection.addTransceiver('audio', {
67
- direction: 'recvonly'
68
- });
69
- }
63
+ // Always add audio transceiver
64
+ this.audioTransceiver = this.connection.addTransceiver('audio', {
65
+ direction: 'sendrecv'
66
+ });
70
67
 
71
- // Add video transceiver only if video is enabled or present
72
- if (this.enableVideo || (this.localStream && this.localStream.getVideoTracks().length > 0)) {
73
- this.videoTransceiver = this.connection.addTransceiver('video', {
74
- direction: 'recvonly'
75
- });
76
- }
68
+ // Always add video transceiver
69
+ this.videoTransceiver = this.connection.addTransceiver('video', {
70
+ direction: 'sendrecv'
71
+ });
77
72
 
78
- // Add local media stream if provided
79
- if (this.localStream) {
80
- console.log('Adding local stream tracks to existing transceivers');
81
- await this.setLocalStreamToTransceivers(this.localStream);
82
- }
83
- } else {
84
- console.log('📡 Creating data-only connection (no media transceivers)');
73
+ // Add local media stream if provided
74
+ if (this.localStream) {
75
+ this.debug.log('Adding local stream tracks to existing transceivers');
76
+ await this.setLocalStreamToTransceivers(this.localStream);
85
77
  }
86
78
 
87
79
  if (this.isInitiator) {
@@ -91,7 +83,7 @@ export class PeerConnection extends EventEmitter {
91
83
  this.setupDataChannel();
92
84
  } else {
93
85
  this.connection.ondatachannel = (event) => {
94
- console.log('Received data channel from', this.peerId);
86
+ this.debug.log('Received data channel from', this.peerId);
95
87
  this.dataChannel = event.channel;
96
88
  this.setupDataChannel();
97
89
  };
@@ -101,64 +93,71 @@ export class PeerConnection extends EventEmitter {
101
93
  setupConnectionHandlers() {
102
94
  this.connection.onicecandidate = (event) => {
103
95
  if (event.candidate) {
104
- console.log(`🧊 Generated ICE candidate for ${this.peerId.substring(0, 8)}...`, {
96
+ this.debug.log(`🧊 Generated ICE candidate for ${this.peerId.substring(0, 8)}...`, {
105
97
  type: event.candidate.type,
106
98
  protocol: event.candidate.protocol,
107
99
  address: event.candidate.address?.substring(0, 10) + '...' || 'unknown'
108
100
  });
109
101
  this.emit('iceCandidate', { peerId: this.peerId, candidate: event.candidate });
110
102
  } else {
111
- console.log(`🧊 ICE gathering complete for ${this.peerId.substring(0, 8)}...`);
103
+ this.debug.log(`🧊 ICE gathering complete for ${this.peerId.substring(0, 8)}...`);
112
104
  }
113
105
  };
114
106
 
115
107
  // Handle remote media streams
116
108
  this.connection.ontrack = (event) => {
117
- console.log('🎵 Received remote media stream from', this.peerId);
109
+ this.debug.log('🎵 Received remote media stream from', this.peerId);
118
110
  const stream = event.streams[0];
119
111
  const track = event.track;
120
112
 
121
- console.log(`🎵 Track received: kind=${track.kind}, id=${track.id}, enabled=${track.enabled}, readyState=${track.readyState}`);
113
+ this.debug.log(`🎵 Track received: kind=${track.kind}, id=${track.id}, enabled=${track.enabled}, readyState=${track.readyState}`);
122
114
 
123
115
  // CRITICAL: Enhanced loopback detection and stream validation
116
+ this.debug.log('🔍 ONTRACK DEBUG: Starting stream validation...');
124
117
  if (!this.validateRemoteStream(stream, track)) {
118
+ this.debug.error('❌ ONTRACK DEBUG: Stream validation FAILED - rejecting remote stream');
125
119
  return; // Don't process invalid or looped back streams
126
120
  }
121
+ this.debug.log('✅ ONTRACK DEBUG: Stream validation PASSED - processing remote stream');
127
122
 
128
123
  if (stream) {
129
124
  this.remoteStream = stream;
130
125
  const audioTracks = stream.getAudioTracks();
131
126
  const videoTracks = stream.getVideoTracks();
132
127
 
133
- console.log(`🎵 Remote stream tracks: ${audioTracks.length} audio, ${videoTracks.length} video`);
134
- console.log(`🎵 Remote stream ID: ${stream.id} (vs local: ${this.localStream?.id || 'none'})`);
128
+ this.debug.log(`🎵 Remote stream tracks: ${audioTracks.length} audio, ${videoTracks.length} video`);
129
+ this.debug.log(`🎵 Remote stream ID: ${stream.id} (vs local: ${this.localStream?.id || 'none'})`);
135
130
 
136
131
  // Mark stream as genuinely remote to prevent future confusion
137
132
  this.markStreamAsRemote(stream);
138
133
 
139
134
  audioTracks.forEach((audioTrack, index) => {
140
- console.log(`🎵 Audio track ${index}: enabled=${audioTrack.enabled}, readyState=${audioTrack.readyState}, muted=${audioTrack.muted}, id=${audioTrack.id}`);
135
+ this.debug.log(`🎵 Audio track ${index}: enabled=${audioTrack.enabled}, readyState=${audioTrack.readyState}, muted=${audioTrack.muted}, id=${audioTrack.id}`);
141
136
 
142
137
  // Add audio data monitoring
143
138
  this.setupAudioDataMonitoring(audioTrack, index);
144
139
  });
145
140
 
141
+ this.debug.log('🚨 ONTRACK DEBUG: About to emit remoteStream event');
146
142
  this.emit('remoteStream', { peerId: this.peerId, stream: this.remoteStream });
143
+ this.debug.log('✅ ONTRACK DEBUG: remoteStream event emitted successfully');
144
+ } else {
145
+ this.debug.error('❌ ONTRACK DEBUG: No stream in ontrack event - this should not happen');
147
146
  }
148
147
  };
149
148
 
150
149
  this.connection.onconnectionstatechange = () => {
151
- console.log(`🔗 Connection state with ${this.peerId}: ${this.connection.connectionState} (previous signaling: ${this.connection.signalingState})`);
150
+ this.debug.log(`🔗 Connection state with ${this.peerId}: ${this.connection.connectionState} (previous signaling: ${this.connection.signalingState})`);
152
151
 
153
152
  // Log additional context about transceivers and media with Node.js compatibility
154
153
  try {
155
154
  const transceivers = this.connection.getTransceivers();
156
155
  const audioSending = this.audioTransceiver && this.audioTransceiver.sender && this.audioTransceiver.sender.track;
157
156
  const videoSending = this.videoTransceiver && this.videoTransceiver.sender && this.videoTransceiver.sender.track;
158
- console.log(`🔗 Media context: Audio sending=${!!audioSending}, Video sending=${!!videoSending}, Transceivers=${transceivers.length}`);
157
+ this.debug.log(`🔗 Media context: Audio sending=${!!audioSending}, Video sending=${!!videoSending}, Transceivers=${transceivers.length}`);
159
158
  } catch (error) {
160
159
  // Handle Node.js WebRTC compatibility issues
161
- console.log(`🔗 Media context: Unable to access transceiver details (${error.message})`);
160
+ this.debug.log(`🔗 Media context: Unable to access transceiver details (${error.message})`);
162
161
  }
163
162
 
164
163
  if (this.connection.connectionState === 'connected') {
@@ -167,46 +166,46 @@ export class PeerConnection extends EventEmitter {
167
166
  clearTimeout(this.connectingTimeout);
168
167
  this.connectingTimeout = null;
169
168
  }
170
- console.log(`✅ Connection established with ${this.peerId}`);
169
+ this.debug.log(`✅ Connection established with ${this.peerId}`);
171
170
  this.emit('connected', { peerId: this.peerId });
172
171
  } else if (this.connection.connectionState === 'connecting') {
173
- console.log(`🔄 Connection to ${this.peerId} is connecting...`);
172
+ this.debug.log(`🔄 Connection to ${this.peerId} is connecting...`);
174
173
  // Add timeout for stuck connecting state
175
174
  if (this.connectingTimeout) {
176
175
  clearTimeout(this.connectingTimeout);
177
176
  }
178
177
  this.connectingTimeout = setTimeout(() => {
179
178
  if (this.connection && this.connection.connectionState === 'connecting' && !this.isClosing) {
180
- console.log(`⏰ Connection stuck in connecting state for ${this.peerId}, treating as failed`);
179
+ this.debug.log(`⏰ Connection stuck in connecting state for ${this.peerId}, treating as failed`);
181
180
  this.emit('disconnected', { peerId: this.peerId, reason: 'connection timeout' });
182
181
  }
183
182
  }, 20000); // Increased timeout to 20 seconds for better stability
184
183
  } else if (this.connection.connectionState === 'disconnected') {
185
184
  // Give WebRTC more time to recover - it's common for connections to briefly disconnect during renegotiation
186
- console.log(`⚠️ WebRTC connection disconnected for ${this.peerId}, waiting for potential recovery...`);
185
+ this.debug.log(`⚠️ WebRTC connection disconnected for ${this.peerId}, waiting for potential recovery...`);
187
186
  setTimeout(() => {
188
187
  if (this.connection &&
189
188
  this.connection.connectionState === 'disconnected' &&
190
189
  !this.isClosing) {
191
- console.log(`❌ WebRTC connection remained disconnected for ${this.peerId}, treating as failed`);
190
+ this.debug.log(`❌ WebRTC connection remained disconnected for ${this.peerId}, treating as failed`);
192
191
  this.emit('disconnected', { peerId: this.peerId, reason: 'connection disconnected' });
193
192
  }
194
193
  }, 8000); // Increased wait time to 8 seconds to account for renegotiation
195
194
  } else if (this.connection.connectionState === 'failed') {
196
195
  if (!this.isClosing) {
197
- console.log(`❌ Connection failed for ${this.peerId}`);
196
+ this.debug.log(`❌ Connection failed for ${this.peerId}`);
198
197
  this.emit('disconnected', { peerId: this.peerId, reason: 'connection failed' });
199
198
  }
200
199
  } else if (this.connection.connectionState === 'closed') {
201
200
  if (!this.isClosing) {
202
- console.log(`❌ Connection closed for ${this.peerId}`);
201
+ this.debug.log(`❌ Connection closed for ${this.peerId}`);
203
202
  this.emit('disconnected', { peerId: this.peerId, reason: 'connection closed' });
204
203
  }
205
204
  }
206
205
  };
207
206
 
208
207
  this.connection.oniceconnectionstatechange = () => {
209
- console.log(`🧊 ICE connection state with ${this.peerId}: ${this.connection.iceConnectionState}`);
208
+ this.debug.log(`🧊 ICE connection state with ${this.peerId}: ${this.connection.iceConnectionState}`);
210
209
 
211
210
  if (this.connection.iceConnectionState === 'connected') {
212
211
  // Clear any pending timeout
@@ -214,85 +213,137 @@ export class PeerConnection extends EventEmitter {
214
213
  clearTimeout(this.iceCheckingTimeout);
215
214
  this.iceCheckingTimeout = null;
216
215
  }
217
- console.log(`✅ ICE connection established with ${this.peerId}`);
216
+ this.debug.log(`✅ ICE connection established with ${this.peerId}`);
218
217
  } else if (this.connection.iceConnectionState === 'checking') {
219
- console.log(`🔄 ICE checking for ${this.peerId}...`);
220
- // Set a timeout for ICE checking state - if it takes too long, restart
218
+ this.debug.log(`🔄 ICE checking for ${this.peerId}...`);
219
+ // Set a timeout for ICE checking state - if it takes too long, only restart if signaling is available
221
220
  if (this.iceCheckingTimeout) {
222
221
  clearTimeout(this.iceCheckingTimeout);
223
222
  }
224
223
  this.iceCheckingTimeout = setTimeout(() => {
225
224
  if (this.connection && this.connection.iceConnectionState === 'checking') {
226
- console.log(`⏰ ICE checking timeout for ${this.peerId}, attempting restart`);
227
- try {
228
- this.connection.restartIce();
229
- } catch (error) {
230
- console.error('Failed to restart ICE:', error);
231
- this.emit('disconnected', { peerId: this.peerId, reason: 'ICE restart failed' });
225
+ // Check if signaling is available before attempting ICE restart
226
+ const hasSignaling = this.mesh && this.mesh.signalingClient && this.mesh.signalingClient.isConnected();
227
+ const hasMeshConnectivity = this.mesh && this.mesh.connected && this.mesh.connectionManager.getConnectedPeerCount() > 0;
228
+
229
+ if (hasSignaling || hasMeshConnectivity) {
230
+ this.debug.log(`⏰ ICE checking timeout for ${this.peerId}, attempting restart (signaling: ${hasSignaling}, mesh: ${hasMeshConnectivity})`);
231
+ try {
232
+ this.restartIceViaSignaling().catch(error => {
233
+ this.debug.error('Failed to restart ICE:', error);
234
+ this.emit('disconnected', { peerId: this.peerId, reason: 'ICE restart failed' });
235
+ });
236
+ } catch (error) {
237
+ this.debug.error('Failed to restart ICE:', error);
238
+ this.emit('disconnected', { peerId: this.peerId, reason: 'ICE restart failed' });
239
+ }
240
+ } else {
241
+ this.debug.log(`⏰ ICE checking timeout for ${this.peerId}, but no signaling available - keeping connection alive`);
242
+ // Don't disconnect - peer connection may still work without signaling server
232
243
  }
233
244
  }
234
- }, 20000); // Increased timeout to 20 seconds for ICE checking
245
+ }, 30000); // Increased timeout to 30 seconds to be more tolerant
235
246
  } else if (this.connection.iceConnectionState === 'failed') {
236
- console.log(`❌ ICE connection failed for ${this.peerId}, attempting restart`);
237
- try {
238
- this.connection.restartIce();
239
- } catch (error) {
240
- console.error('Failed to restart ICE after failure:', error);
241
- this.emit('disconnected', { peerId: this.peerId, reason: 'ICE failed' });
247
+ // Check if signaling is available before attempting ICE restart
248
+ const hasSignaling = this.mesh && this.mesh.signalingClient && this.mesh.signalingClient.isConnected();
249
+ const hasMeshConnectivity = this.mesh && this.mesh.connected && this.mesh.connectionManager.getConnectedPeerCount() > 0;
250
+
251
+ if (hasSignaling || hasMeshConnectivity) {
252
+ this.debug.log(`❌ ICE connection failed for ${this.peerId}, attempting restart (signaling: ${hasSignaling}, mesh: ${hasMeshConnectivity})`);
253
+ try {
254
+ // For ICE restart, we need to coordinate new ICE candidates through signaling
255
+ this.restartIceViaSignaling().catch(error => {
256
+ this.debug.error('Failed to restart ICE after failure:', error);
257
+ this.emit('disconnected', { peerId: this.peerId, reason: 'ICE failed' });
258
+ });
259
+ } catch (error) {
260
+ this.debug.error('Failed to restart ICE after failure:', error);
261
+ this.emit('disconnected', { peerId: this.peerId, reason: 'ICE failed' });
262
+ }
263
+ } else {
264
+ this.debug.log(`❌ ICE connection failed for ${this.peerId}, but no signaling available - monitoring data channel`);
265
+ // Don't immediately disconnect - monitor data channel health instead
266
+ this.monitorDataChannelHealth();
242
267
  }
243
268
  } else if (this.connection.iceConnectionState === 'disconnected') {
244
269
  // Give more time for ICE reconnection - this is common during renegotiation
245
- console.log(`⚠️ ICE connection disconnected for ${this.peerId}, waiting for potential reconnection...`);
270
+ this.debug.log(`⚠️ ICE connection disconnected for ${this.peerId}, waiting for potential reconnection...`);
246
271
  setTimeout(() => {
247
272
  if (this.connection &&
248
273
  this.connection.iceConnectionState === 'disconnected' &&
249
274
  !this.isClosing) {
250
- console.log(`❌ ICE remained disconnected for ${this.peerId}, attempting restart`);
251
- try {
252
- this.connection.restartIce();
253
- } catch (error) {
254
- console.error('Failed to restart ICE after disconnection:', error);
255
- this.emit('disconnected', { peerId: this.peerId, reason: 'ICE disconnected' });
275
+ // Check if signaling is available before attempting ICE restart
276
+ const hasSignaling = this.mesh && this.mesh.signalingClient && this.mesh.signalingClient.isConnected();
277
+ const hasMeshConnectivity = this.mesh && this.mesh.connected && this.mesh.connectionManager.getConnectedPeerCount() > 0;
278
+
279
+ if (hasSignaling || hasMeshConnectivity) {
280
+ this.debug.log(`❌ ICE remained disconnected for ${this.peerId}, attempting restart (signaling: ${hasSignaling}, mesh: ${hasMeshConnectivity})`);
281
+ try {
282
+ this.restartIceViaSignaling().catch(error => {
283
+ this.debug.error('Failed to restart ICE after disconnection:', error);
284
+ this.emit('disconnected', { peerId: this.peerId, reason: 'ICE disconnected' });
285
+ });
286
+ } catch (error) {
287
+ this.debug.error('Failed to restart ICE after disconnection:', error);
288
+ this.emit('disconnected', { peerId: this.peerId, reason: 'ICE disconnected' });
289
+ }
290
+ } else {
291
+ this.debug.log(`❌ ICE remained disconnected for ${this.peerId}, but no signaling available - monitoring data channel`);
292
+ // Monitor data channel health instead of immediately disconnecting
293
+ this.monitorDataChannelHealth();
256
294
  }
257
295
  }
258
- }, 10000); // Increased wait time to 10 seconds for ICE reconnection
296
+ }, 15000); // Increased wait time to 15 seconds for ICE reconnection
259
297
  }
260
298
  };
261
299
 
262
300
  // Handle renegotiation when tracks are added/removed
263
301
  this.connection.onnegotiationneeded = () => {
264
- console.log(`🔄 Negotiation needed for ${this.peerId} (WebRTC detected track changes)`);
265
- // With pre-allocated transceivers, we should NEVER need renegotiation
266
- // Any renegotiation indicates a problem with our transceiver approach
267
- console.log('🚫 UNEXPECTED: Renegotiation triggered despite transceiver approach - investigating...');
302
+ this.debug.log(`🔄 Negotiation needed for ${this.peerId} (WebRTC detected track changes)`);
303
+ // CRITICAL: Renegotiation IS needed when tracks are added/replaced, even with pre-allocated transceivers
304
+ // Pre-allocated transceivers only avoid m-line changes, but SDP still needs to be renegotiated
305
+ this.debug.log('✅ RENEGOTIATION: Track changes detected - triggering renegotiation as expected');
268
306
 
269
307
  // Log debug info about current transceivers (with error handling for Node.js WebRTC)
270
308
  try {
271
309
  const transceivers = this.connection.getTransceivers();
272
- console.log('� Transceivers state during unexpected negotiation:', transceivers.map(t => ({
310
+ this.debug.log('🔄 Transceivers state during renegotiation:', transceivers.map(t => ({
273
311
  kind: t.receiver?.track?.kind || 'unknown',
274
312
  direction: t.direction,
275
313
  hasTrack: !!t.sender?.track,
276
314
  mid: t.mid
277
315
  })));
278
316
  } catch (error) {
279
- console.log('� Cannot inspect transceivers (Node.js WebRTC limitation):', error.message);
317
+ this.debug.log('🔄 Cannot inspect transceivers (Node.js WebRTC limitation):', error.message);
280
318
  }
281
319
 
282
- // For now, ignore renegotiation to prevent connection issues
283
- // this.emit('renegotiationNeeded', { peerId: this.peerId });
320
+ // Emit renegotiation needed event to trigger SDP exchange
321
+ this.emit('renegotiationNeeded', { peerId: this.peerId });
322
+ };
323
+
324
+ // CRITICAL FIX: Handle track changes manually after renegotiation
325
+ // Since we use replaceTrack() with pre-allocated transceivers, ontrack events don't fire
326
+ // We need to monitor transceivers for new tracks after SDP exchanges
327
+ this.connection.onsignalingstatechange = () => {
328
+ this.debug.log(`🔄 Signaling state changed for ${this.peerId}: ${this.connection.signalingState}`);
329
+
330
+ // When signaling becomes stable after renegotiation, check for new remote tracks
331
+ if (this.connection.signalingState === 'stable') {
332
+ this.debug.log('🔍 Signaling stable - checking for new remote tracks...');
333
+ this.checkForNewRemoteTracks();
334
+ }
284
335
  };
285
336
  }
286
337
 
287
338
  setupDataChannel() {
288
339
  this.dataChannel.onopen = () => {
289
- console.log(`Data channel opened with ${this.peerId}`);
340
+ this.debug.log(`Data channel opened with ${this.peerId}`);
290
341
  this.dataChannelReady = true;
291
342
  this.emit('dataChannelOpen', { peerId: this.peerId });
292
343
  };
293
344
 
294
345
  this.dataChannel.onclose = () => {
295
- console.log(`Data channel closed with ${this.peerId}`);
346
+ this.debug.log(`Data channel closed with ${this.peerId}`);
296
347
  this.dataChannelReady = false;
297
348
 
298
349
  // Only emit disconnection if we're not intentionally closing
@@ -304,15 +355,39 @@ export class PeerConnection extends EventEmitter {
304
355
  this.dataChannel.onmessage = (event) => {
305
356
  try {
306
357
  const message = JSON.parse(event.data);
358
+
359
+ // Handle internal ping messages for health monitoring
360
+ if (message.type === 'ping') {
361
+ this.debug.log(`📡 Received health ping from ${this.peerId}, responding with pong`);
362
+ try {
363
+ const pongMessage = {
364
+ type: 'pong',
365
+ timestamp: Date.now(),
366
+ originalTimestamp: message.timestamp,
367
+ from: this.mesh?.peerId || 'unknown'
368
+ };
369
+ this.dataChannel.send(JSON.stringify(pongMessage));
370
+ } catch (error) {
371
+ this.debug.error('Failed to send pong response:', error);
372
+ }
373
+ return; // Don't emit this as a regular message
374
+ }
375
+
376
+ // Handle pong responses (optional logging)
377
+ if (message.type === 'pong') {
378
+ this.debug.log(`📡 Received health pong from ${this.peerId}`);
379
+ return; // Don't emit this as a regular message
380
+ }
381
+
307
382
  this.emit('message', { peerId: this.peerId, message });
308
383
  } catch (error) {
309
- console.error('Failed to parse message:', error);
384
+ this.debug.error('Failed to parse message:', error);
310
385
  this.emit('message', { peerId: this.peerId, message: { content: event.data } });
311
386
  }
312
387
  };
313
388
 
314
389
  this.dataChannel.onerror = (error) => {
315
- console.error(`Data channel error with ${this.peerId}:`, error);
390
+ this.debug.error(`Data channel error with ${this.peerId}:`, error);
316
391
  this.dataChannelReady = false;
317
392
 
318
393
  // Only emit disconnection if we're not intentionally closing
@@ -329,75 +404,177 @@ export class PeerConnection extends EventEmitter {
329
404
  }
330
405
 
331
406
  async handleOffer(offer) {
407
+ // Validate offer data structure
408
+ if (!offer || typeof offer !== 'object') {
409
+ this.debug.error(`Invalid offer from ${this.peerId} - not an object:`, offer);
410
+ throw new Error('Invalid offer: not an object');
411
+ }
412
+
413
+ if (!offer.type || offer.type !== 'offer') {
414
+ this.debug.error(`Invalid offer from ${this.peerId} - wrong type:`, offer.type);
415
+ throw new Error(`Invalid offer: expected type 'offer', got '${offer.type}'`);
416
+ }
417
+
418
+ if (!offer.sdp || typeof offer.sdp !== 'string') {
419
+ this.debug.error(`Invalid offer from ${this.peerId} - missing or invalid SDP:`, typeof offer.sdp);
420
+ throw new Error('Invalid offer: missing or invalid SDP');
421
+ }
422
+
423
+ // Basic SDP validation
424
+ if (offer.sdp.length < 10 || !offer.sdp.includes('v=0')) {
425
+ this.debug.error(`Invalid offer SDP from ${this.peerId} - malformed:`, offer.sdp.substring(0, 100) + '...');
426
+ throw new Error('Invalid offer: malformed SDP');
427
+ }
428
+
429
+ // ENHANCED DEBUGGING: Log detailed state before processing offer
430
+ this.debug.log(`🔄 OFFER DEBUG: Processing offer from ${this.peerId.substring(0, 8)}...`);
431
+ this.debug.log(`🔄 OFFER DEBUG: Current signaling state: ${this.connection.signalingState}`);
432
+ this.debug.log(`🔄 OFFER DEBUG: Current connection state: ${this.connection.connectionState}`);
433
+ this.debug.log(`🔄 OFFER DEBUG: Current ICE state: ${this.connection.iceConnectionState}`);
434
+ this.debug.log(`🔄 OFFER DEBUG: Offer SDP length: ${offer.sdp.length}`);
435
+
332
436
  // Check if we're in the right state to handle an offer
333
437
  if (this.connection.signalingState !== 'stable') {
334
- console.log(`Cannot handle offer from ${this.peerId} - connection state is ${this.connection.signalingState} (expected: stable)`);
438
+ this.debug.log(`❌ OFFER DEBUG: Cannot handle offer from ${this.peerId} - connection state is ${this.connection.signalingState} (expected: stable)`);
335
439
  throw new Error(`Cannot handle offer in state: ${this.connection.signalingState}`);
336
440
  }
337
441
 
338
- await this.connection.setRemoteDescription(offer);
339
- this.remoteDescriptionSet = true;
340
- await this.processPendingIceCandidates();
442
+ this.debug.log(`🔄 OFFER DEBUG: State validation passed, processing offer from ${this.peerId.substring(0, 8)}... SDP length: ${offer.sdp.length}`);
341
443
 
342
- const answer = await this.connection.createAnswer();
343
- await this.connection.setLocalDescription(answer);
344
- return answer;
444
+ try {
445
+ await this.connection.setRemoteDescription(offer);
446
+ this.remoteDescriptionSet = true;
447
+ this.debug.log(`✅ OFFER DEBUG: Offer processed successfully from ${this.peerId.substring(0, 8)}...`);
448
+ this.debug.log(`✅ OFFER DEBUG: New signaling state after offer: ${this.connection.signalingState}`);
449
+ await this.processPendingIceCandidates();
450
+
451
+ const answer = await this.connection.createAnswer();
452
+ await this.connection.setLocalDescription(answer);
453
+ this.debug.log(`✅ OFFER DEBUG: Answer created for offer from ${this.peerId.substring(0, 8)}...`);
454
+ this.debug.log(`✅ OFFER DEBUG: Final signaling state after answer: ${this.connection.signalingState}`);
455
+ return answer;
456
+ } catch (error) {
457
+ this.debug.error(`❌ OFFER DEBUG: Failed to process offer from ${this.peerId}:`, error);
458
+ this.debug.error('OFFER DEBUG: Offer SDP that failed:', offer.sdp);
459
+ this.debug.error('OFFER DEBUG: Current connection state:', this.connection.signalingState);
460
+ this.debug.error('OFFER DEBUG: Current ICE state:', this.connection.iceConnectionState);
461
+ throw error;
462
+ }
345
463
  }
346
464
 
347
465
  async handleAnswer(answer) {
466
+ // Validate answer data structure
467
+ if (!answer || typeof answer !== 'object') {
468
+ this.debug.error(`Invalid answer from ${this.peerId} - not an object:`, answer);
469
+ throw new Error('Invalid answer: not an object');
470
+ }
471
+
472
+ if (!answer.type || answer.type !== 'answer') {
473
+ this.debug.error(`Invalid answer from ${this.peerId} - wrong type:`, answer.type);
474
+ throw new Error(`Invalid answer: expected type 'answer', got '${answer.type}'`);
475
+ }
476
+
477
+ if (!answer.sdp || typeof answer.sdp !== 'string') {
478
+ this.debug.error(`Invalid answer from ${this.peerId} - missing or invalid SDP:`, typeof answer.sdp);
479
+ throw new Error('Invalid answer: missing or invalid SDP');
480
+ }
481
+
482
+ // Basic SDP validation
483
+ if (answer.sdp.length < 10 || !answer.sdp.includes('v=0')) {
484
+ this.debug.error(`Invalid answer SDP from ${this.peerId} - malformed:`, answer.sdp.substring(0, 100) + '...');
485
+ throw new Error('Invalid answer: malformed SDP');
486
+ }
487
+
488
+ // ENHANCED DEBUGGING: Log detailed state before processing answer
489
+ this.debug.log(`🔄 ANSWER DEBUG: Processing answer from ${this.peerId.substring(0, 8)}...`);
490
+ this.debug.log(`🔄 ANSWER DEBUG: Current signaling state: ${this.connection.signalingState}`);
491
+ this.debug.log(`🔄 ANSWER DEBUG: Current connection state: ${this.connection.connectionState}`);
492
+ this.debug.log(`🔄 ANSWER DEBUG: Current ICE state: ${this.connection.iceConnectionState}`);
493
+ this.debug.log(`🔄 ANSWER DEBUG: Answer SDP length: ${answer.sdp.length}`);
494
+
348
495
  // Check if we're in the right state to handle an answer
349
496
  if (this.connection.signalingState !== 'have-local-offer') {
350
- console.log(`Cannot handle answer from ${this.peerId} - connection state is ${this.connection.signalingState} (expected: have-local-offer)`);
497
+ this.debug.log(`❌ ANSWER DEBUG: Cannot handle answer from ${this.peerId} - connection state is ${this.connection.signalingState} (expected: have-local-offer)`);
351
498
 
352
499
  // If we're already stable, the connection might already be established
353
500
  if (this.connection.signalingState === 'stable') {
354
- console.log('Connection already stable, answer not needed');
501
+ this.debug.log('✅ ANSWER DEBUG: Connection already stable, answer not needed');
355
502
  return;
356
503
  }
357
504
 
358
505
  throw new Error(`Cannot handle answer in state: ${this.connection.signalingState}`);
359
506
  }
360
507
 
361
- await this.connection.setRemoteDescription(answer);
362
- this.remoteDescriptionSet = true;
363
- await this.processPendingIceCandidates();
508
+ this.debug.log(`🔄 ANSWER DEBUG: State validation passed, processing answer from ${this.peerId.substring(0, 8)}... SDP length: ${answer.sdp.length}`);
509
+
510
+ try {
511
+ await this.connection.setRemoteDescription(answer);
512
+ this.remoteDescriptionSet = true;
513
+ this.debug.log(`✅ ANSWER DEBUG: Answer processed successfully from ${this.peerId.substring(0, 8)}...`);
514
+ this.debug.log(`✅ ANSWER DEBUG: New signaling state: ${this.connection.signalingState}`);
515
+ this.debug.log(`✅ ANSWER DEBUG: New connection state: ${this.connection.connectionState}`);
516
+ await this.processPendingIceCandidates();
517
+ } catch (error) {
518
+ this.debug.error(`❌ ANSWER DEBUG: Failed to set remote description for answer from ${this.peerId}:`, error);
519
+ this.debug.error('ANSWER DEBUG: Answer SDP that failed:', answer.sdp);
520
+ this.debug.error('ANSWER DEBUG: Current connection state:', this.connection.signalingState);
521
+ this.debug.error('ANSWER DEBUG: Current ICE state:', this.connection.iceConnectionState);
522
+ throw error;
523
+ }
364
524
  }
365
525
 
366
526
  async handleIceCandidate(candidate) {
367
- console.log(`🧊 Received ICE candidate for ${this.peerId.substring(0, 8)}...`, {
527
+ // Validate ICE candidate data structure
528
+ if (!candidate || typeof candidate !== 'object') {
529
+ this.debug.error(`Invalid ICE candidate from ${this.peerId} - not an object:`, candidate);
530
+ throw new Error('Invalid ICE candidate: not an object');
531
+ }
532
+
533
+ // Basic ICE candidate validation
534
+ if (!candidate.candidate || typeof candidate.candidate !== 'string') {
535
+ this.debug.error(`Invalid ICE candidate from ${this.peerId} - missing candidate string:`, candidate);
536
+ throw new Error('Invalid ICE candidate: missing candidate string');
537
+ }
538
+
539
+ this.debug.log(`🧊 Received ICE candidate for ${this.peerId.substring(0, 8)}...`, {
368
540
  type: candidate.type,
369
- protocol: candidate.protocol
541
+ protocol: candidate.protocol,
542
+ candidateLength: candidate.candidate?.length || 0
370
543
  });
371
544
 
372
545
  if (!this.remoteDescriptionSet) {
373
- console.log(`🧊 Buffering ICE candidate for ${this.peerId.substring(0, 8)}... (remote description not set yet)`);
546
+ this.debug.log(`🧊 Buffering ICE candidate for ${this.peerId.substring(0, 8)}... (remote description not set yet)`);
374
547
  this.pendingIceCandidates.push(candidate);
375
548
  return;
376
549
  }
377
550
 
378
551
  try {
379
552
  await this.connection.addIceCandidate(candidate);
380
- console.log(`🧊 Successfully added ICE candidate for ${this.peerId.substring(0, 8)}...`);
553
+ this.debug.log(`🧊 Successfully added ICE candidate for ${this.peerId.substring(0, 8)}...`);
381
554
  } catch (error) {
382
- console.error(`🧊 Failed to add ICE candidate for ${this.peerId.substring(0, 8)}...:`, error);
555
+ this.debug.error(`🧊 Failed to add ICE candidate for ${this.peerId.substring(0, 8)}...:`, error);
556
+ this.debug.error('ICE candidate that failed:', candidate);
557
+ this.debug.error('Current connection state:', this.connection.connectionState);
558
+ this.debug.error('Current ICE state:', this.connection.iceConnectionState);
559
+ // Don't rethrow - ICE candidate failures are often recoverable
383
560
  }
384
561
  }
385
562
 
386
563
  async processPendingIceCandidates() {
387
564
  if (this.pendingIceCandidates.length > 0) {
388
- console.log(`🧊 Processing ${this.pendingIceCandidates.length} buffered ICE candidates for ${this.peerId.substring(0, 8)}...`);
565
+ this.debug.log(`🧊 Processing ${this.pendingIceCandidates.length} buffered ICE candidates for ${this.peerId.substring(0, 8)}...`);
389
566
 
390
567
  for (const candidate of this.pendingIceCandidates) {
391
568
  try {
392
569
  await this.connection.addIceCandidate(candidate);
393
- console.log(`🧊 Successfully added buffered ICE candidate (${candidate.type}) for ${this.peerId.substring(0, 8)}...`);
570
+ this.debug.log(`🧊 Successfully added buffered ICE candidate (${candidate.type}) for ${this.peerId.substring(0, 8)}...`);
394
571
  } catch (error) {
395
- console.error(`🧊 Failed to add buffered ICE candidate for ${this.peerId.substring(0, 8)}...:`, error);
572
+ this.debug.error(`🧊 Failed to add buffered ICE candidate for ${this.peerId.substring(0, 8)}...:`, error);
396
573
  }
397
574
  }
398
575
 
399
576
  this.pendingIceCandidates = [];
400
- console.log(`🧊 Finished processing buffered ICE candidates for ${this.peerId.substring(0, 8)}...`);
577
+ this.debug.log(`🧊 Finished processing buffered ICE candidates for ${this.peerId.substring(0, 8)}...`);
401
578
  }
402
579
  }
403
580
 
@@ -407,59 +584,124 @@ export class PeerConnection extends EventEmitter {
407
584
  this.dataChannel.send(JSON.stringify(message));
408
585
  return true;
409
586
  } catch (error) {
410
- console.error(`Failed to send message to ${this.peerId}:`, error);
587
+ this.debug.error(`Failed to send message to ${this.peerId}:`, error);
411
588
  return false;
412
589
  }
413
590
  }
414
591
  return false;
415
592
  }
416
593
 
594
+ /**
595
+ * CRITICAL FIX: Manually check for new remote tracks after renegotiation
596
+ * This is needed because replaceTrack() doesn't trigger ontrack events
597
+ */
598
+ checkForNewRemoteTracks() {
599
+ this.debug.log(`🔍 TRACK CHECK: Checking transceivers for new remote tracks from ${this.peerId.substring(0, 8)}...`);
600
+
601
+ try {
602
+ const transceivers = this.connection.getTransceivers();
603
+ let foundNewTracks = false;
604
+
605
+ transceivers.forEach((transceiver, index) => {
606
+ const track = transceiver.receiver.track;
607
+ if (track && track.readyState === 'live') {
608
+ this.debug.log(`🔍 TRACK CHECK: Transceiver ${index} has live ${track.kind} track: ${track.id.substring(0, 8)}...`);
609
+
610
+ // Check if this is a new track we haven't processed
611
+ const isNewTrack = !this.processedTrackIds || !this.processedTrackIds.has(track.id);
612
+
613
+ if (isNewTrack) {
614
+ this.debug.log(`🎵 NEW TRACK FOUND: Processing new ${track.kind} track from ${this.peerId.substring(0, 8)}...`);
615
+
616
+ // Create a stream from this track (simulate ontrack event)
617
+ const stream = new MediaStream([track]);
618
+
619
+ // Validate and process like ontrack would
620
+ if (this.validateRemoteStream(stream, track)) {
621
+ this.remoteStream = stream;
622
+ this.markStreamAsRemote(stream);
623
+
624
+ // Track that we've processed this track
625
+ if (!this.processedTrackIds) this.processedTrackIds = new Set();
626
+ this.processedTrackIds.add(track.id);
627
+
628
+ this.debug.log('🚨 TRACK CHECK: Emitting remoteStream event for new track');
629
+ this.emit('remoteStream', { peerId: this.peerId, stream: this.remoteStream });
630
+ foundNewTracks = true;
631
+ }
632
+ }
633
+ }
634
+ });
635
+
636
+ if (!foundNewTracks) {
637
+ this.debug.log('🔍 TRACK CHECK: No new remote tracks found');
638
+ }
639
+ } catch (error) {
640
+ this.debug.error('❌ TRACK CHECK: Failed to check for remote tracks:', error);
641
+ }
642
+ }
643
+
417
644
  /**
418
645
  * Enhanced validation to ensure received stream is genuinely remote
419
646
  */
420
647
  validateRemoteStream(stream, track) {
648
+ this.debug.log('🔍 VALIDATION: Starting remote stream validation...');
649
+
421
650
  // Check 1: Stream ID collision (basic loopback detection)
422
651
  if (this.localStream && stream.id === this.localStream.id) {
423
- console.error('❌ LOOPBACK DETECTED: Received our own local stream as remote!');
424
- console.error('Local stream ID:', this.localStream.id);
425
- console.error('Received stream ID:', stream.id);
652
+ this.debug.error('❌ LOOPBACK DETECTED: Received our own local stream as remote!');
653
+ this.debug.error('Local stream ID:', this.localStream.id);
654
+ this.debug.error('Received stream ID:', stream.id);
426
655
  return false;
427
656
  }
657
+ this.debug.log('✅ VALIDATION: Stream ID check passed');
428
658
 
429
659
  // Check 2: Track ID collision (more granular loopback detection)
430
660
  if (this.localStream) {
431
661
  const localTracks = this.localStream.getTracks();
432
662
  const isOwnTrack = localTracks.some(localTrack => localTrack.id === track.id);
433
663
  if (isOwnTrack) {
434
- console.error('❌ TRACK LOOPBACK: This track is our own local track!');
435
- console.error('Local track ID:', track.id);
664
+ this.debug.error('❌ TRACK LOOPBACK: This track is our own local track!');
665
+ this.debug.error('Local track ID:', track.id);
436
666
  return false;
437
667
  }
438
668
  }
669
+ this.debug.log('✅ VALIDATION: Track ID check passed');
439
670
 
440
671
  // Check 3: Verify track comes from remote peer transceiver
441
672
  if (this.connection) {
442
673
  const transceivers = this.connection.getTransceivers();
674
+ this.debug.log(`🔍 VALIDATION: Checking ${transceivers.length} transceivers for track ${track.id.substring(0, 8)}...`);
675
+
443
676
  const sourceTransceiver = transceivers.find(t => t.receiver.track === track);
444
677
  if (!sourceTransceiver) {
445
- console.warn('⚠️ Track not found in any transceiver - may be invalid');
446
- return false;
447
- }
448
-
449
- // Ensure this is a receiving transceiver (not sending our own track back)
450
- if (sourceTransceiver.direction === 'sendonly') {
451
- console.error('❌ Invalid direction: Receiving track from sendonly transceiver');
452
- return false;
678
+ this.debug.warn('⚠️ VALIDATION: Track not found in any transceiver - may be invalid');
679
+ this.debug.warn('Available transceivers:', transceivers.map(t => ({
680
+ kind: t.receiver?.track?.kind || 'no-track',
681
+ direction: t.direction,
682
+ trackId: t.receiver?.track?.id?.substring(0, 8) || 'none'
683
+ })));
684
+ // TEMPORARY FIX: Don't reject just because transceiver lookup fails
685
+ // return false;
686
+ this.debug.log('⚠️ VALIDATION: Allowing track despite transceiver lookup failure (temporary fix)');
687
+ } else {
688
+ // Ensure this is a receiving transceiver (not sending our own track back)
689
+ if (sourceTransceiver.direction === 'sendonly') {
690
+ this.debug.error('❌ Invalid direction: Receiving track from sendonly transceiver');
691
+ return false;
692
+ }
693
+ this.debug.log(`✅ VALIDATION: Transceiver check passed (direction: ${sourceTransceiver.direction})`);
453
694
  }
454
695
  }
455
696
 
456
697
  // Check 4: Verify stream hasn't been marked as local origin
457
698
  if (stream._peerPigeonOrigin === 'local') {
458
- console.error('❌ Stream marked as local origin - preventing synchronization loop');
699
+ this.debug.error('❌ Stream marked as local origin - preventing synchronization loop');
459
700
  return false;
460
701
  }
702
+ this.debug.log('✅ VALIDATION: Local origin check passed');
461
703
 
462
- console.log('✅ Remote stream validation passed for peer', this.peerId.substring(0, 8));
704
+ this.debug.log('✅ Remote stream validation passed for peer', this.peerId.substring(0, 8));
463
705
  return true;
464
706
  }
465
707
 
@@ -482,7 +724,7 @@ export class PeerConnection extends EventEmitter {
482
724
  configurable: false
483
725
  });
484
726
 
485
- console.log(`🔒 Stream ${stream.id} marked as remote from peer ${this.peerId.substring(0, 8)}`);
727
+ this.debug.log(`🔒 Stream ${stream.id} marked as remote from peer ${this.peerId.substring(0, 8)}`);
486
728
  }
487
729
 
488
730
  /**
@@ -498,7 +740,7 @@ export class PeerConnection extends EventEmitter {
498
740
  configurable: false
499
741
  });
500
742
 
501
- console.log(`🔒 Stream ${stream.id} marked as local origin`);
743
+ this.debug.log(`🔒 Stream ${stream.id} marked as local origin`);
502
744
  }
503
745
 
504
746
  /**
@@ -509,11 +751,11 @@ export class PeerConnection extends EventEmitter {
509
751
  throw new Error('Connection not initialized');
510
752
  }
511
753
 
512
- console.log(`Setting local stream for ${this.peerId}, current state: ${this.connection.connectionState}, signaling: ${this.connection.signalingState}`);
754
+ this.debug.log(`Setting local stream for ${this.peerId}, current state: ${this.connection.connectionState}, signaling: ${this.connection.signalingState}`);
513
755
 
514
756
  // DEBUG: Log current transceivers before any changes
515
757
  const transceivers = this.connection.getTransceivers();
516
- console.log('🔍 Current transceivers before stream change:', transceivers.map(t => ({
758
+ this.debug.log('🔍 Current transceivers before stream change:', transceivers.map(t => ({
517
759
  kind: t.receiver.track?.kind || 'unknown',
518
760
  direction: t.direction,
519
761
  hasTrack: !!t.sender.track,
@@ -521,7 +763,7 @@ export class PeerConnection extends EventEmitter {
521
763
  })));
522
764
 
523
765
  // Use stored transceiver references for reliable access
524
- console.log('🔄 Using stored transceiver references for media');
766
+ this.debug.log('🔄 Using stored transceiver references for media');
525
767
 
526
768
  if (stream) {
527
769
  const audioTracks = stream.getAudioTracks();
@@ -533,65 +775,128 @@ export class PeerConnection extends EventEmitter {
533
775
  // Handle audio track using stored reference
534
776
  if (this.audioTransceiver) {
535
777
  if (audioTracks.length > 0) {
536
- console.log('🔄 Replacing audio track in stored transceiver');
778
+ this.debug.log('🔄 Replacing audio track in stored transceiver');
537
779
  await this.audioTransceiver.sender.replaceTrack(audioTracks[0]);
538
780
  this.audioTransceiver.direction = 'sendrecv';
539
781
 
540
782
  // Setup audio sending monitoring
541
783
  this.setupAudioSendingMonitoring(audioTracks[0]);
542
- console.log(`🎤 SENDING AUDIO to peer ${this.peerId.substring(0, 8)} - track enabled: ${audioTracks[0].enabled}`);
784
+ this.debug.log(`🎤 SENDING AUDIO to peer ${this.peerId.substring(0, 8)} - track enabled: ${audioTracks[0].enabled}`);
543
785
  } else {
544
- console.log('🔄 Removing audio track from stored transceiver');
786
+ this.debug.log('🔄 Removing audio track from stored transceiver');
545
787
  await this.audioTransceiver.sender.replaceTrack(null);
546
788
  this.audioTransceiver.direction = 'recvonly';
547
- console.log(`🎤 STOPPED SENDING AUDIO to peer ${this.peerId.substring(0, 8)}`);
789
+ this.debug.log(`🎤 STOPPED SENDING AUDIO to peer ${this.peerId.substring(0, 8)}`);
548
790
  }
549
791
  }
550
792
 
551
793
  // Handle video track using stored reference
552
794
  if (this.videoTransceiver) {
553
795
  if (videoTracks.length > 0) {
554
- console.log('🔄 Replacing video track in stored transceiver');
796
+ this.debug.log('🔄 Replacing video track in stored transceiver');
555
797
  await this.videoTransceiver.sender.replaceTrack(videoTracks[0]);
556
798
  this.videoTransceiver.direction = 'sendrecv';
557
799
  } else {
558
- console.log('🔄 Removing video track from stored transceiver');
800
+ this.debug.log('🔄 Removing video track from stored transceiver');
559
801
  await this.videoTransceiver.sender.replaceTrack(null);
560
802
  this.videoTransceiver.direction = 'recvonly';
561
803
  }
562
804
  }
563
805
 
564
806
  this.localStream = stream;
565
- console.log('✅ Stream set successfully using stored transceivers');
807
+ this.debug.log('✅ Stream set successfully using stored transceivers');
566
808
  } else {
567
809
  // Remove all tracks using stored references
568
810
  if (this.audioTransceiver) {
569
- console.log('🔄 Removing audio track from stored transceiver');
811
+ this.debug.log('🔄 Removing audio track from stored transceiver');
570
812
  await this.audioTransceiver.sender.replaceTrack(null);
571
813
  this.audioTransceiver.direction = 'recvonly';
572
814
  }
573
815
 
574
816
  if (this.videoTransceiver) {
575
- console.log('🔄 Removing video track from stored transceiver');
817
+ this.debug.log('🔄 Removing video track from stored transceiver');
576
818
  await this.videoTransceiver.sender.replaceTrack(null);
577
819
  this.videoTransceiver.direction = 'recvonly';
578
820
  }
579
821
 
580
822
  this.localStream = null;
581
- console.log('✅ All tracks removed using stored transceivers');
823
+ this.debug.log('✅ All tracks removed using stored transceivers');
582
824
  }
583
825
 
584
- console.log('Updated local media stream for', this.peerId);
826
+ this.debug.log('Updated local media stream for', this.peerId);
585
827
 
586
828
  // DEBUG: Log final transceivers after changes
587
829
  const finalTransceivers = this.connection.getTransceivers();
588
- console.log('🔍 Final transceivers after stream change:', finalTransceivers.map(t => ({
589
- kind: t.receiver.track?.kind || 'unknown',
830
+ this.debug.log('🔍 Final transceivers after stream change:', finalTransceivers.map(t => ({
831
+ kind: t.receiver?.track?.kind || 'unknown',
590
832
  direction: t.direction,
591
- hasTrack: !!t.sender.track,
592
- trackId: t.sender.track?.id?.substring(0, 8) || 'none',
833
+ hasTrack: !!t.sender?.track,
834
+ trackId: t.sender?.track?.id?.substring(0, 8) || 'none',
593
835
  mid: t.mid
594
836
  })));
837
+
838
+ // AGGRESSIVE FIX: Force immediate renegotiation if connection is stuck
839
+ if (this.connection.signalingState === 'have-local-offer') {
840
+ this.debug.log('🆘 FORCE RENEGOTIATION: Connection stuck in \'have-local-offer\' - forcing immediate renegotiation');
841
+
842
+ // Force renegotiation event
843
+ this.emit('renegotiationNeeded', { peerId: this.peerId });
844
+
845
+ // Also try direct renegotiation as backup
846
+ setTimeout(() => {
847
+ if (this.connection.signalingState === 'have-local-offer') {
848
+ this.debug.log('🆘 EMERGENCY: Still stuck after forced renegotiation - attempting direct recovery');
849
+ this.forceConnectionRecovery().catch(err => {
850
+ this.debug.error('❌ EMERGENCY: Direct recovery failed', err);
851
+ });
852
+ }
853
+ }, 5000);
854
+ } else {
855
+ // Normal renegotiation for stable connections
856
+ this.debug.log('✅ RENEGOTIATION: Triggering normal renegotiation for media changes');
857
+ this.emit('renegotiationNeeded', { peerId: this.peerId });
858
+ }
859
+
860
+ // CRITICAL: Force renegotiation when media changes
861
+ this.debug.log('✅ Stream updated - forcing renegotiation for media changes');
862
+ this.debug.log(` Current state: connectionState=${this.connection.connectionState}, signalingState=${this.connection.signalingState}`);
863
+
864
+ // Always trigger renegotiation when stream changes, regardless of connection state
865
+ if (stream) {
866
+ setTimeout(() => {
867
+ this.debug.log('🔄 Forcing renegotiation for media stream changes');
868
+ this.emit('renegotiationNeeded', { peerId: this.peerId });
869
+ }, 200); // Increased delay to ensure replaceTrack completes
870
+ }
871
+ }
872
+
873
+ /**
874
+ * Force connection recovery for stuck connections
875
+ */
876
+ async forceConnectionRecovery() {
877
+ this.debug.log(`🆘 FORCE RECOVERY: Attempting emergency recovery for ${this.peerId.substring(0, 8)}...`);
878
+
879
+ try {
880
+ // Create a new offer to break the stuck state
881
+ const offer = await this.connection.createOffer({ iceRestart: true });
882
+ await this.connection.setLocalDescription(offer);
883
+
884
+ // Emit recovery offer via mesh signaling
885
+ if (this.mesh && this.mesh.sendSignalingMessage) {
886
+ await this.mesh.sendSignalingMessage({
887
+ type: 'recovery-offer',
888
+ data: offer,
889
+ emergency: true
890
+ }, this.peerId);
891
+
892
+ this.debug.log(`✅ RECOVERY: Emergency offer sent for ${this.peerId.substring(0, 8)}...`);
893
+ } else {
894
+ this.debug.error(`❌ RECOVERY: No mesh signaling available for ${this.peerId.substring(0, 8)}...`);
895
+ }
896
+ } catch (error) {
897
+ this.debug.error(`❌ RECOVERY: Emergency recovery failed for ${this.peerId.substring(0, 8)}...`, error);
898
+ throw error;
899
+ }
595
900
  }
596
901
 
597
902
  /**
@@ -604,18 +909,18 @@ export class PeerConnection extends EventEmitter {
604
909
 
605
910
  // Set audio track to stored audio transceiver
606
911
  if (this.audioTransceiver && audioTracks.length > 0) {
607
- console.log('🔄 Setting audio track to stored audio transceiver');
912
+ this.debug.log('🔄 Setting audio track to stored audio transceiver');
608
913
  await this.audioTransceiver.sender.replaceTrack(audioTracks[0]);
609
914
  this.audioTransceiver.direction = 'sendrecv';
610
915
 
611
916
  // Setup audio sending monitoring
612
917
  this.setupAudioSendingMonitoring(audioTracks[0]);
613
- console.log(`🎤 SENDING AUDIO to peer ${this.peerId.substring(0, 8)} via transceiver - track enabled: ${audioTracks[0].enabled}`);
918
+ this.debug.log(`🎤 SENDING AUDIO to peer ${this.peerId.substring(0, 8)} via transceiver - track enabled: ${audioTracks[0].enabled}`);
614
919
  }
615
920
 
616
921
  // Set video track to stored video transceiver
617
922
  if (this.videoTransceiver && videoTracks.length > 0) {
618
- console.log('🔄 Setting video track to stored video transceiver');
923
+ this.debug.log('🔄 Setting video track to stored video transceiver');
619
924
  await this.videoTransceiver.sender.replaceTrack(videoTracks[0]);
620
925
  this.videoTransceiver.direction = 'sendrecv';
621
926
  }
@@ -626,13 +931,13 @@ export class PeerConnection extends EventEmitter {
626
931
  * Setup audio data monitoring for received audio tracks
627
932
  */
628
933
  setupAudioDataMonitoring(audioTrack, trackIndex) {
629
- console.log(`🎵 Setting up audio data monitoring for track ${trackIndex} from peer ${this.peerId.substring(0, 8)}`);
934
+ this.debug.log(`🎵 Setting up audio data monitoring for track ${trackIndex} from peer ${this.peerId.substring(0, 8)}`);
630
935
 
631
936
  try {
632
937
  // Create audio context for analyzing audio data
633
938
  const AudioContext = window.AudioContext || window.webkitAudioContext;
634
939
  if (!AudioContext) {
635
- console.warn('🎵 AudioContext not available - cannot monitor audio data');
940
+ this.debug.warn('🎵 AudioContext not available - cannot monitor audio data');
636
941
  return;
637
942
  }
638
943
 
@@ -656,7 +961,7 @@ export class PeerConnection extends EventEmitter {
656
961
  // Monitor audio levels periodically
657
962
  const monitorAudio = () => {
658
963
  if (audioTrack.readyState === 'ended') {
659
- console.log(`🎵 Audio track ${trackIndex} ended, stopping monitoring for peer ${this.peerId.substring(0, 8)}`);
964
+ this.debug.log(`🎵 Audio track ${trackIndex} ended, stopping monitoring for peer ${this.peerId.substring(0, 8)}`);
660
965
  audioContext.close();
661
966
  return;
662
967
  }
@@ -676,7 +981,7 @@ export class PeerConnection extends EventEmitter {
676
981
  // Log every 5 seconds
677
982
  if (currentTime - lastLogTime > 5000) {
678
983
  const audioActivity = totalSamples > 0 ? (samplesWithAudio / totalSamples * 100) : 0;
679
- console.log(`🎵 Audio data from peer ${this.peerId.substring(0, 8)} track ${trackIndex}:`, {
984
+ this.debug.log(`🎵 Audio data from peer ${this.peerId.substring(0, 8)} track ${trackIndex}:`, {
680
985
  enabled: audioTrack.enabled,
681
986
  readyState: audioTrack.readyState,
682
987
  muted: audioTrack.muted,
@@ -705,21 +1010,21 @@ export class PeerConnection extends EventEmitter {
705
1010
 
706
1011
  // Track state changes
707
1012
  audioTrack.addEventListener('ended', () => {
708
- console.log(`🎵 Audio track ${trackIndex} from peer ${this.peerId.substring(0, 8)} ended`);
1013
+ this.debug.log(`🎵 Audio track ${trackIndex} from peer ${this.peerId.substring(0, 8)} ended`);
709
1014
  audioContext.close();
710
1015
  });
711
1016
 
712
1017
  audioTrack.addEventListener('mute', () => {
713
- console.log(`🎵 Audio track ${trackIndex} from peer ${this.peerId.substring(0, 8)} muted`);
1018
+ this.debug.log(`🎵 Audio track ${trackIndex} from peer ${this.peerId.substring(0, 8)} muted`);
714
1019
  });
715
1020
 
716
1021
  audioTrack.addEventListener('unmute', () => {
717
- console.log(`🎵 Audio track ${trackIndex} from peer ${this.peerId.substring(0, 8)} unmuted`);
1022
+ this.debug.log(`🎵 Audio track ${trackIndex} from peer ${this.peerId.substring(0, 8)} unmuted`);
718
1023
  });
719
1024
 
720
- console.log(`🎵 Audio monitoring started for track ${trackIndex} from peer ${this.peerId.substring(0, 8)}`);
1025
+ this.debug.log(`🎵 Audio monitoring started for track ${trackIndex} from peer ${this.peerId.substring(0, 8)}`);
721
1026
  } catch (error) {
722
- console.error(`🎵 Failed to setup audio monitoring for track ${trackIndex}:`, error);
1027
+ this.debug.error(`🎵 Failed to setup audio monitoring for track ${trackIndex}:`, error);
723
1028
  }
724
1029
  }
725
1030
 
@@ -727,26 +1032,26 @@ export class PeerConnection extends EventEmitter {
727
1032
  * Setup audio sending monitoring for outgoing audio tracks
728
1033
  */
729
1034
  setupAudioSendingMonitoring(audioTrack) {
730
- console.log(`🎤 Setting up audio SENDING monitoring to peer ${this.peerId.substring(0, 8)}`);
1035
+ this.debug.log(`🎤 Setting up audio SENDING monitoring to peer ${this.peerId.substring(0, 8)}`);
731
1036
 
732
1037
  try {
733
1038
  // Monitor track state changes
734
1039
  audioTrack.addEventListener('ended', () => {
735
- console.log(`🎤 Audio SENDING track ended to peer ${this.peerId.substring(0, 8)}`);
1040
+ this.debug.log(`🎤 Audio SENDING track ended to peer ${this.peerId.substring(0, 8)}`);
736
1041
  });
737
1042
 
738
1043
  audioTrack.addEventListener('mute', () => {
739
- console.log(`🎤 Audio SENDING track muted to peer ${this.peerId.substring(0, 8)}`);
1044
+ this.debug.log(`🎤 Audio SENDING track muted to peer ${this.peerId.substring(0, 8)}`);
740
1045
  });
741
1046
 
742
1047
  audioTrack.addEventListener('unmute', () => {
743
- console.log(`🎤 Audio SENDING track unmuted to peer ${this.peerId.substring(0, 8)}`);
1048
+ this.debug.log(`🎤 Audio SENDING track unmuted to peer ${this.peerId.substring(0, 8)}`);
744
1049
  });
745
1050
 
746
1051
  // Monitor audio input levels if possible
747
1052
  const AudioContext = window.AudioContext || window.webkitAudioContext;
748
1053
  if (!AudioContext) {
749
- console.warn('🎤 AudioContext not available - basic sending monitoring only');
1054
+ this.debug.warn('🎤 AudioContext not available - basic sending monitoring only');
750
1055
  return;
751
1056
  }
752
1057
 
@@ -768,7 +1073,7 @@ export class PeerConnection extends EventEmitter {
768
1073
 
769
1074
  const monitorSending = () => {
770
1075
  if (audioTrack.readyState === 'ended') {
771
- console.log(`🎤 Audio sending track ended, stopping monitoring to peer ${this.peerId.substring(0, 8)}`);
1076
+ this.debug.log(`🎤 Audio sending track ended, stopping monitoring to peer ${this.peerId.substring(0, 8)}`);
772
1077
  audioContext.close();
773
1078
  return;
774
1079
  }
@@ -787,7 +1092,7 @@ export class PeerConnection extends EventEmitter {
787
1092
  // Log every 5 seconds
788
1093
  if (currentTime - lastLogTime > 5000) {
789
1094
  const sendingActivity = totalSamples > 0 ? (activeSamples / totalSamples * 100) : 0;
790
- console.log(`🎤 Audio SENDING to peer ${this.peerId.substring(0, 8)}:`, {
1095
+ this.debug.log(`🎤 Audio SENDING to peer ${this.peerId.substring(0, 8)}:`, {
791
1096
  trackEnabled: audioTrack.enabled,
792
1097
  trackReadyState: audioTrack.readyState,
793
1098
  trackMuted: audioTrack.muted,
@@ -810,9 +1115,9 @@ export class PeerConnection extends EventEmitter {
810
1115
  };
811
1116
 
812
1117
  requestAnimationFrame(monitorSending);
813
- console.log(`🎤 Audio sending monitoring started to peer ${this.peerId.substring(0, 8)}`);
1118
+ this.debug.log(`🎤 Audio sending monitoring started to peer ${this.peerId.substring(0, 8)}`);
814
1119
  } catch (error) {
815
- console.error(`🎤 Failed to setup audio sending monitoring to peer ${this.peerId.substring(0, 8)}:`, error);
1120
+ this.debug.error(`🎤 Failed to setup audio sending monitoring to peer ${this.peerId.substring(0, 8)}:`, error);
816
1121
  }
817
1122
  }
818
1123
 
@@ -915,9 +1220,163 @@ export class PeerConnection extends EventEmitter {
915
1220
  isClosing: this.isClosing,
916
1221
  overallStatus: this.getStatus()
917
1222
  };
1223
+
1224
+ // Add media stream information if available
1225
+ if (this.remoteStream || this.localStream) {
1226
+ status.audioTracks = {
1227
+ remote: this.remoteStream ? this.remoteStream.getAudioTracks().length : 0,
1228
+ local: this.localStream ? this.localStream.getAudioTracks().length : 0
1229
+ };
1230
+ status.videoTracks = {
1231
+ remote: this.remoteStream ? this.remoteStream.getVideoTracks().length : 0,
1232
+ local: this.localStream ? this.localStream.getVideoTracks().length : 0
1233
+ };
1234
+ }
1235
+
918
1236
  return status;
919
1237
  }
920
1238
 
1239
+ /**
1240
+ * Monitor data channel health when ICE connection is problematic but signaling is unavailable
1241
+ * This allows peer connections to survive signaling server outages
1242
+ */
1243
+ monitorDataChannelHealth() {
1244
+ if (this.dataChannelHealthMonitor) {
1245
+ clearTimeout(this.dataChannelHealthMonitor);
1246
+ }
1247
+
1248
+ this.debug.log(`📡 Monitoring data channel health for ${this.peerId} (signaling unavailable)`);
1249
+
1250
+ // Test data channel by sending a ping message
1251
+ const testDataChannel = () => {
1252
+ if (!this.dataChannel || this.dataChannel.readyState !== 'open' || this.isClosing) {
1253
+ this.debug.log(`❌ Data channel not available for ${this.peerId}, disconnecting`);
1254
+ this.emit('disconnected', { peerId: this.peerId, reason: 'data channel unavailable' });
1255
+ return;
1256
+ }
1257
+
1258
+ try {
1259
+ // Send a small ping message to test connectivity
1260
+ const pingMessage = {
1261
+ type: 'ping',
1262
+ timestamp: Date.now(),
1263
+ from: this.mesh?.peerId || 'unknown'
1264
+ };
1265
+
1266
+ this.dataChannel.send(JSON.stringify(pingMessage));
1267
+ this.debug.log(`✅ Data channel ping sent to ${this.peerId} - connection appears healthy`);
1268
+
1269
+ // Schedule next health check in 30 seconds
1270
+ this.dataChannelHealthMonitor = setTimeout(testDataChannel, 30000);
1271
+ } catch (error) {
1272
+ this.debug.error(`❌ Data channel ping failed for ${this.peerId}:`, error);
1273
+ this.emit('disconnected', { peerId: this.peerId, reason: 'data channel ping failed' });
1274
+ }
1275
+ };
1276
+
1277
+ // Start monitoring after a short delay
1278
+ this.dataChannelHealthMonitor = setTimeout(testDataChannel, 5000);
1279
+ }
1280
+
1281
+ /**
1282
+ * Restart ICE using signaling coordination (WebSocket or mesh)
1283
+ * This allows ICE restart to work even when the signaling server is down
1284
+ * by using the mesh for coordination
1285
+ */
1286
+ async restartIceViaSignaling() {
1287
+ if (!this.connection) {
1288
+ throw new Error('No connection to restart ICE for');
1289
+ }
1290
+
1291
+ this.debug.log(`🔄 Restarting ICE via signaling for ${this.peerId}`);
1292
+
1293
+ try {
1294
+ // Trigger ICE restart - this will generate new ICE candidates
1295
+ this.connection.restartIce();
1296
+
1297
+ // Create a new offer with the restarted ICE
1298
+ const offer = await this.connection.createOffer({ iceRestart: true });
1299
+ await this.connection.setLocalDescription(offer);
1300
+
1301
+ // Send the new offer via our mesh signaling system
1302
+ if (this.mesh && this.mesh.sendSignalingMessage) {
1303
+ await this.mesh.sendSignalingMessage({
1304
+ type: 'ice-restart-offer',
1305
+ data: { offer }
1306
+ }, this.peerId);
1307
+
1308
+ this.debug.log(`✅ ICE restart offer sent for ${this.peerId}`);
1309
+ } else {
1310
+ throw new Error('No signaling method available for ICE restart');
1311
+ }
1312
+ } catch (error) {
1313
+ this.debug.error(`Failed to restart ICE for ${this.peerId}:`, error);
1314
+ throw error;
1315
+ }
1316
+ }
1317
+
1318
+ /**
1319
+ * Handle incoming ICE restart offers
1320
+ */
1321
+ async handleIceRestartOffer(offer) {
1322
+ if (!this.connection) {
1323
+ this.debug.error('Cannot handle ICE restart offer - no connection');
1324
+ return;
1325
+ }
1326
+
1327
+ this.debug.log(`🔄 Handling ICE restart offer from ${this.peerId}`);
1328
+
1329
+ try {
1330
+ await this.connection.setRemoteDescription(offer);
1331
+ const answer = await this.connection.createAnswer();
1332
+ await this.connection.setLocalDescription(answer);
1333
+
1334
+ // Send the answer back
1335
+ if (this.mesh && this.mesh.sendSignalingMessage) {
1336
+ await this.mesh.sendSignalingMessage({
1337
+ type: 'ice-restart-answer',
1338
+ data: { answer }
1339
+ }, this.peerId);
1340
+
1341
+ this.debug.log(`✅ ICE restart answer sent for ${this.peerId}`);
1342
+ }
1343
+ } catch (error) {
1344
+ this.debug.error(`Failed to handle ICE restart offer from ${this.peerId}:`, error);
1345
+ throw error;
1346
+ }
1347
+ }
1348
+
1349
+ /**
1350
+ * Handle incoming ICE restart answers
1351
+ */
1352
+ async handleIceRestartAnswer(answer) {
1353
+ if (!this.connection) {
1354
+ this.debug.error('Cannot handle ICE restart answer - no connection');
1355
+ return;
1356
+ }
1357
+
1358
+ this.debug.log(`🔄 Handling ICE restart answer from ${this.peerId}`);
1359
+
1360
+ try {
1361
+ await this.connection.setRemoteDescription(answer);
1362
+ this.debug.log(`✅ ICE restart completed for ${this.peerId}`);
1363
+ } catch (error) {
1364
+ this.debug.error(`Failed to handle ICE restart answer from ${this.peerId}:`, error);
1365
+ throw error;
1366
+ }
1367
+ }
1368
+
1369
+ /**
1370
+ * Stop data channel health monitoring
1371
+ */
1372
+ stopDataChannelHealthMonitoring() {
1373
+ if (this.dataChannelHealthMonitor) {
1374
+ clearTimeout(this.dataChannelHealthMonitor);
1375
+ this.dataChannelHealthMonitor = null;
1376
+ this.debug.log(`📡 Stopped data channel health monitoring for ${this.peerId}`);
1377
+ }
1378
+ }
1379
+
921
1380
  close() {
922
1381
  // Set flag to prevent disconnection events during intentional close
923
1382
  this.isClosing = true;
@@ -933,6 +1392,9 @@ export class PeerConnection extends EventEmitter {
933
1392
  this.connectingTimeout = null;
934
1393
  }
935
1394
 
1395
+ // Stop data channel health monitoring
1396
+ this.stopDataChannelHealthMonitoring();
1397
+
936
1398
  if (this.connection) {
937
1399
  this.connection.close();
938
1400
  }