peerpigeon 0.0.4 → 0.0.6

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