peerpigeon 0.0.5 → 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,1033 +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
- this.audioTransceiver = null;
26
- this.videoTransceiver = null;
27
- }
28
-
29
- /**
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
+ /**
30
30
  * Force this connection into a terminal state (e.g., failed/timeout)
31
31
  */
32
- markAsFailed(reason = 'failed') {
33
- this._forcedStatus = reason;
34
- try {
35
- this.close();
36
- } 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;
37
45
  }
38
46
 
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;
45
- }
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
+ });
46
53
 
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
- });
54
+ this.setupConnectionHandlers();
53
55
 
54
- this.setupConnectionHandlers();
55
-
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;
60
-
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
- }
70
-
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
- }
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;
77
60
 
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
- }
61
+ if (intendToUseMedia) {
62
+ console.log('🔄 Pre-allocating transceivers for stable media negotiation');
86
63
 
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
- }
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
+ }
70
+
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
+ }
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)');
99
85
  }
100
86
 
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
- };
114
-
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
- };
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
+ };
114
+
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}`);
149
122
 
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
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;
169
+ }
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
+ };
207
+
208
+ this.connection.oniceconnectionstatechange = () => {
209
+ console.log(`🧊 ICE connection state with ${this.peerId}: ${this.connection.iceConnectionState}`);
210
+
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`);
154
227
  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}`);
228
+ this.connection.restartIce();
159
229
  } catch (error) {
160
- // Handle Node.js WebRTC compatibility issues
161
- console.log(`🔗 Media context: Unable to access transceiver details (${error.message})`);
230
+ console.error('Failed to restart ICE:', error);
231
+ this.emit('disconnected', { peerId: this.peerId, reason: 'ICE restart failed' });
162
232
  }
163
-
164
- if (this.connection.connectionState === 'connected') {
165
- // Clear any pending timeouts
166
- if (this.connectingTimeout) {
167
- clearTimeout(this.connectingTimeout);
168
- this.connectingTimeout = null;
169
- }
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
- };
207
-
208
- this.connection.oniceconnectionstatechange = () => {
209
- console.log(`🧊 ICE connection state with ${this.peerId}: ${this.connection.iceConnectionState}`);
210
-
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`);
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' });
232
- }
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' &&
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' &&
249
249
  !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' });
256
- }
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)
250
+ console.log(`❌ ICE remained disconnected for ${this.peerId}, attempting restart`);
270
251
  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
- })));
252
+ this.connection.restartIce();
278
253
  } 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
- };
254
+ console.error('Failed to restart ICE after disconnection:', error);
255
+ this.emit('disconnected', { peerId: this.peerId, reason: 'ICE disconnected' });
256
+ }
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}`);
285
336
  }
286
337
 
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
- };
338
+ await this.connection.setRemoteDescription(offer);
339
+ this.remoteDescriptionSet = true;
340
+ await this.processPendingIceCandidates();
303
341
 
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
- }
342
+ const answer = await this.connection.createAnswer();
343
+ await this.connection.setLocalDescription(answer);
344
+ return answer;
345
+ }
324
346
 
325
- async createOffer() {
326
- const offer = await this.connection.createOffer();
327
- await this.connection.setLocalDescription(offer);
328
- 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}`);
329
359
  }
330
360
 
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}`);
336
- }
337
-
338
- await this.connection.setRemoteDescription(offer);
339
- this.remoteDescriptionSet = true;
340
- await this.processPendingIceCandidates();
341
-
342
- const answer = await this.connection.createAnswer();
343
- await this.connection.setLocalDescription(answer);
344
- 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;
345
376
  }
346
377
 
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}`);
359
- }
360
-
361
- await this.connection.setRemoteDescription(answer);
362
- this.remoteDescriptionSet = true;
363
- 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);
364
383
  }
384
+ }
365
385
 
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;
376
- }
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)}...`);
377
389
 
390
+ for (const candidate of this.pendingIceCandidates) {
378
391
  try {
379
- await this.connection.addIceCandidate(candidate);
380
- 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)}...`);
381
394
  } catch (error) {
382
- 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);
383
396
  }
384
- }
397
+ }
385
398
 
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)}...`);
389
-
390
- for (const candidate of this.pendingIceCandidates) {
391
- try {
392
- await this.connection.addIceCandidate(candidate);
393
- console.log(`🧊 Successfully added buffered ICE candidate (${candidate.type}) for ${this.peerId.substring(0, 8)}...`);
394
- } catch (error) {
395
- console.error(`🧊 Failed to add buffered ICE candidate for ${this.peerId.substring(0, 8)}...:`, error);
396
- }
397
- }
398
-
399
- this.pendingIceCandidates = [];
400
- console.log(`🧊 Finished processing buffered ICE candidates for ${this.peerId.substring(0, 8)}...`);
401
- }
399
+ this.pendingIceCandidates = [];
400
+ console.log(`🧊 Finished processing buffered ICE candidates for ${this.peerId.substring(0, 8)}...`);
402
401
  }
402
+ }
403
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
- }
413
- }
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);
414
411
  return false;
412
+ }
415
413
  }
414
+ return false;
415
+ }
416
416
 
417
- /**
417
+ /**
418
418
  * Enhanced validation to ensure received stream is genuinely remote
419
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;
427
- }
428
-
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);
436
- return false;
437
- }
438
- }
439
-
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;
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;
464
427
  }
465
428
 
466
- /**
467
- * Mark a stream as genuinely remote to prevent future confusion
468
- */
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;
493
-
494
- Object.defineProperty(stream, '_peerPigeonOrigin', {
495
- value: 'local',
496
- writable: false,
497
- enumerable: false,
498
- configurable: false
499
- });
500
-
501
- console.log(`🔒 Stream ${stream.id} marked as local origin`);
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);
436
+ return false;
437
+ }
502
438
  }
503
439
 
504
- async createOffer() {
505
- const offer = await this.connection.createOffer();
506
- await this.connection.setLocalDescription(offer);
507
- return offer;
508
- }
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
+ }
509
448
 
510
- async handleOffer(offer) {
511
- // Check if we're in the right state to handle an offer
512
- if (this.connection.signalingState !== 'stable') {
513
- console.log(`Cannot handle offer from ${this.peerId} - connection state is ${this.connection.signalingState} (expected: stable)`);
514
- throw new Error(`Cannot handle offer in state: ${this.connection.signalingState}`);
515
- }
516
-
517
- await this.connection.setRemoteDescription(offer);
518
- this.remoteDescriptionSet = true;
519
- await this.processPendingIceCandidates();
520
-
521
- const answer = await this.connection.createAnswer();
522
- await this.connection.setLocalDescription(answer);
523
- return answer;
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
+ }
524
454
  }
525
455
 
526
- async handleAnswer(answer) {
527
- // Check if we're in the right state to handle an answer
528
- if (this.connection.signalingState !== 'have-local-offer') {
529
- console.log(`Cannot handle answer from ${this.peerId} - connection state is ${this.connection.signalingState} (expected: have-local-offer)`);
530
-
531
- // If we're already stable, the connection might already be established
532
- if (this.connection.signalingState === 'stable') {
533
- console.log('Connection already stable, answer not needed');
534
- return;
535
- }
536
-
537
- throw new Error(`Cannot handle answer in state: ${this.connection.signalingState}`);
538
- }
539
-
540
- await this.connection.setRemoteDescription(answer);
541
- this.remoteDescriptionSet = true;
542
- await this.processPendingIceCandidates();
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;
543
460
  }
544
461
 
545
- async handleIceCandidate(candidate) {
546
- console.log(`🧊 Received ICE candidate for ${this.peerId.substring(0, 8)}...`, {
547
- type: candidate.type,
548
- protocol: candidate.protocol
549
- });
550
-
551
- if (!this.remoteDescriptionSet) {
552
- console.log(`🧊 Buffering ICE candidate for ${this.peerId.substring(0, 8)}... (remote description not set yet)`);
553
- this.pendingIceCandidates.push(candidate);
554
- return;
555
- }
462
+ console.log('✅ Remote stream validation passed for peer', this.peerId.substring(0, 8));
463
+ return true;
464
+ }
556
465
 
557
- try {
558
- await this.connection.addIceCandidate(candidate);
559
- console.log(`🧊 Successfully added ICE candidate for ${this.peerId.substring(0, 8)}...`);
560
- } catch (error) {
561
- console.error(`🧊 Failed to add ICE candidate for ${this.peerId.substring(0, 8)}...:`, error);
562
- }
563
- }
466
+ /**
467
+ * Mark a stream as genuinely remote to prevent future confusion
468
+ */
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;
564
493
 
565
- async processPendingIceCandidates() {
566
- if (this.pendingIceCandidates.length > 0) {
567
- console.log(`🧊 Processing ${this.pendingIceCandidates.length} buffered ICE candidates for ${this.peerId.substring(0, 8)}...`);
568
-
569
- for (const candidate of this.pendingIceCandidates) {
570
- try {
571
- await this.connection.addIceCandidate(candidate);
572
- console.log(`🧊 Successfully added buffered ICE candidate (${candidate.type}) for ${this.peerId.substring(0, 8)}...`);
573
- } catch (error) {
574
- console.error(`🧊 Failed to add buffered ICE candidate for ${this.peerId.substring(0, 8)}...:`, error);
575
- }
576
- }
577
-
578
- this.pendingIceCandidates = [];
579
- console.log(`🧊 Finished processing buffered ICE candidates for ${this.peerId.substring(0, 8)}...`);
580
- }
581
- }
494
+ Object.defineProperty(stream, '_peerPigeonOrigin', {
495
+ value: 'local',
496
+ writable: false,
497
+ enumerable: false,
498
+ configurable: false
499
+ });
582
500
 
583
- sendMessage(message) {
584
- if (this.dataChannel && this.dataChannel.readyState === 'open') {
585
- try {
586
- this.dataChannel.send(JSON.stringify(message));
587
- return true;
588
- } catch (error) {
589
- console.error(`Failed to send message to ${this.peerId}:`, error);
590
- return false;
591
- }
592
- }
593
- return false;
594
- }
501
+ console.log(`🔒 Stream ${stream.id} marked as local origin`);
502
+ }
595
503
 
596
- /**
504
+ /**
597
505
  * Add or replace local media stream
598
506
  */
599
- async setLocalStream(stream) {
600
- if (!this.connection) {
601
- throw new Error('Connection not initialized');
602
- }
603
-
604
- console.log(`Setting local stream for ${this.peerId}, current state: ${this.connection.connectionState}, signaling: ${this.connection.signalingState}`);
605
-
606
- // DEBUG: Log current transceivers before any changes
607
- const transceivers = this.connection.getTransceivers();
608
- console.log(`🔍 Current transceivers before stream change:`, transceivers.map(t => ({
609
- kind: t.receiver.track?.kind || 'unknown',
610
- direction: t.direction,
611
- hasTrack: !!t.sender.track,
612
- mid: t.mid
613
- })));
507
+ async setLocalStream(stream) {
508
+ if (!this.connection) {
509
+ throw new Error('Connection not initialized');
510
+ }
614
511
 
615
- // Use stored transceiver references for reliable access
616
- console.log('🔄 Using stored transceiver references for media');
617
-
618
- if (stream) {
619
- const audioTracks = stream.getAudioTracks();
620
- const videoTracks = stream.getVideoTracks();
621
-
622
- // Mark stream as local origin to prevent loopback
623
- this.markStreamAsLocal(stream);
624
-
625
- // Handle audio track using stored reference
626
- if (this.audioTransceiver) {
627
- if (audioTracks.length > 0) {
628
- console.log('🔄 Replacing audio track in stored transceiver');
629
- await this.audioTransceiver.sender.replaceTrack(audioTracks[0]);
630
- this.audioTransceiver.direction = 'sendrecv';
631
-
632
- // Setup audio sending monitoring
633
- this.setupAudioSendingMonitoring(audioTracks[0]);
634
- console.log(`🎤 SENDING AUDIO to peer ${this.peerId.substring(0, 8)} - track enabled: ${audioTracks[0].enabled}`);
635
- } else {
636
- console.log('🔄 Removing audio track from stored transceiver');
637
- await this.audioTransceiver.sender.replaceTrack(null);
638
- this.audioTransceiver.direction = 'recvonly';
639
- console.log(`🎤 STOPPED SENDING AUDIO to peer ${this.peerId.substring(0, 8)}`);
640
- }
641
- }
642
-
643
- // Handle video track using stored reference
644
- if (this.videoTransceiver) {
645
- if (videoTracks.length > 0) {
646
- console.log('🔄 Replacing video track in stored transceiver');
647
- await this.videoTransceiver.sender.replaceTrack(videoTracks[0]);
648
- this.videoTransceiver.direction = 'sendrecv';
649
- } else {
650
- console.log('🔄 Removing video track from stored transceiver');
651
- await this.videoTransceiver.sender.replaceTrack(null);
652
- this.videoTransceiver.direction = 'recvonly';
653
- }
654
- }
655
-
656
- this.localStream = stream;
657
- console.log('✅ Stream set successfully using stored transceivers');
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}`);
658
543
  } else {
659
- // Remove all tracks using stored references
660
- if (this.audioTransceiver) {
661
- console.log('🔄 Removing audio track from stored transceiver');
662
- await this.audioTransceiver.sender.replaceTrack(null);
663
- this.audioTransceiver.direction = 'recvonly';
664
- }
665
-
666
- if (this.videoTransceiver) {
667
- console.log('🔄 Removing video track from stored transceiver');
668
- await this.videoTransceiver.sender.replaceTrack(null);
669
- this.videoTransceiver.direction = 'recvonly';
670
- }
671
-
672
- this.localStream = null;
673
- console.log('✅ All tracks removed using stored transceivers');
674
- }
675
-
676
- console.log('Updated local media stream for', this.peerId);
677
-
678
- // DEBUG: Log final transceivers after changes
679
- const finalTransceivers = this.connection.getTransceivers();
680
- console.log(`🔍 Final transceivers after stream change:`, finalTransceivers.map(t => ({
681
- kind: t.receiver.track?.kind || 'unknown',
682
- direction: t.direction,
683
- hasTrack: !!t.sender.track,
684
- trackId: t.sender.track?.id?.substring(0, 8) || 'none',
685
- mid: t.mid
686
- })));
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)}`);
548
+ }
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');
687
582
  }
688
583
 
689
- /**
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
+ /**
690
598
  * Helper method to set local stream tracks to existing transceivers
691
599
  */
692
- async setLocalStreamToTransceivers(stream) {
693
- if (stream) {
694
- const audioTracks = stream.getAudioTracks();
695
- const videoTracks = stream.getVideoTracks();
696
-
697
- // Set audio track to stored audio transceiver
698
- if (this.audioTransceiver && audioTracks.length > 0) {
699
- console.log('🔄 Setting audio track to stored audio transceiver');
700
- await this.audioTransceiver.sender.replaceTrack(audioTracks[0]);
701
- this.audioTransceiver.direction = 'sendrecv';
702
-
703
- // Setup audio sending monitoring
704
- this.setupAudioSendingMonitoring(audioTracks[0]);
705
- console.log(`🎤 SENDING AUDIO to peer ${this.peerId.substring(0, 8)} via transceiver - track enabled: ${audioTracks[0].enabled}`);
706
- }
707
-
708
- // Set video track to stored video transceiver
709
- if (this.videoTransceiver && videoTracks.length > 0) {
710
- console.log('🔄 Setting video track to stored video transceiver');
711
- await this.videoTransceiver.sender.replaceTrack(videoTracks[0]);
712
- this.videoTransceiver.direction = 'sendrecv';
713
- }
714
- }
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
+ }
715
622
  }
623
+ }
716
624
 
717
- /**
625
+ /**
718
626
  * Setup audio data monitoring for received audio tracks
719
627
  */
720
- setupAudioDataMonitoring(audioTrack, trackIndex) {
721
- console.log(`🎵 Setting up audio data monitoring for track ${trackIndex} from peer ${this.peerId.substring(0, 8)}`);
722
-
723
- try {
724
- // Create audio context for analyzing audio data
725
- const AudioContext = window.AudioContext || window.webkitAudioContext;
726
- if (!AudioContext) {
727
- console.warn('🎵 AudioContext not available - cannot monitor audio data');
728
- return;
729
- }
730
-
731
- // Create a MediaStream with just this audio track for analysis
732
- const trackStream = new MediaStream([audioTrack]);
733
- const audioContext = new AudioContext();
734
- const source = audioContext.createMediaStreamSource(trackStream);
735
- const analyser = audioContext.createAnalyser();
736
-
737
- analyser.fftSize = 256;
738
- const bufferLength = analyser.frequencyBinCount;
739
- const dataArray = new Uint8Array(bufferLength);
740
-
741
- source.connect(analyser);
742
-
743
- let lastLogTime = 0;
744
- let totalSamples = 0;
745
- let samplesWithAudio = 0;
746
- let maxLevel = 0;
747
-
748
- // Monitor audio levels periodically
749
- const monitorAudio = () => {
750
- if (audioTrack.readyState === 'ended') {
751
- console.log(`🎵 Audio track ${trackIndex} ended, stopping monitoring for peer ${this.peerId.substring(0, 8)}`);
752
- audioContext.close();
753
- return;
754
- }
755
-
756
- analyser.getByteFrequencyData(dataArray);
757
-
758
- // Calculate audio level (0-255)
759
- const average = dataArray.reduce((sum, value) => sum + value, 0) / bufferLength;
760
- const currentTime = Date.now();
761
-
762
- totalSamples++;
763
- if (average > 5) { // Threshold for detecting audio activity
764
- samplesWithAudio++;
765
- maxLevel = Math.max(maxLevel, average);
766
- }
767
-
768
- // Log every 5 seconds
769
- if (currentTime - lastLogTime > 5000) {
770
- const audioActivity = totalSamples > 0 ? (samplesWithAudio / totalSamples * 100) : 0;
771
- console.log(`🎵 Audio data from peer ${this.peerId.substring(0, 8)} track ${trackIndex}:`, {
772
- enabled: audioTrack.enabled,
773
- readyState: audioTrack.readyState,
774
- muted: audioTrack.muted,
775
- currentLevel: Math.round(average),
776
- maxLevel: Math.round(maxLevel),
777
- activityPercent: Math.round(audioActivity),
778
- samplesAnalyzed: totalSamples,
779
- hasAudioData: samplesWithAudio > 0
780
- });
781
-
782
- lastLogTime = currentTime;
783
- // Reset counters for next period
784
- totalSamples = 0;
785
- samplesWithAudio = 0;
786
- maxLevel = 0;
787
- }
788
-
789
- // Continue monitoring if track is still active
790
- if (audioTrack.readyState === 'live') {
791
- requestAnimationFrame(monitorAudio);
792
- }
793
- };
794
-
795
- // Start monitoring
796
- requestAnimationFrame(monitorAudio);
797
-
798
- // Track state changes
799
- audioTrack.addEventListener('ended', () => {
800
- console.log(`🎵 Audio track ${trackIndex} from peer ${this.peerId.substring(0, 8)} ended`);
801
- audioContext.close();
802
- });
803
-
804
- audioTrack.addEventListener('mute', () => {
805
- console.log(`🎵 Audio track ${trackIndex} from peer ${this.peerId.substring(0, 8)} muted`);
806
- });
807
-
808
- audioTrack.addEventListener('unmute', () => {
809
- console.log(`🎵 Audio track ${trackIndex} from peer ${this.peerId.substring(0, 8)} unmuted`);
810
- });
811
-
812
- console.log(`🎵 Audio monitoring started for track ${trackIndex} from peer ${this.peerId.substring(0, 8)}`);
813
-
814
- } catch (error) {
815
- console.error(`🎵 Failed to setup audio monitoring for track ${trackIndex}:`, error);
816
- }
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;
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);
817
723
  }
724
+ }
818
725
 
819
- /**
726
+ /**
820
727
  * Setup audio sending monitoring for outgoing audio tracks
821
728
  */
822
- setupAudioSendingMonitoring(audioTrack) {
823
- console.log(`🎤 Setting up audio SENDING monitoring to peer ${this.peerId.substring(0, 8)}`);
824
-
825
- try {
826
- // Monitor track state changes
827
- audioTrack.addEventListener('ended', () => {
828
- console.log(`🎤 Audio SENDING track ended to peer ${this.peerId.substring(0, 8)}`);
829
- });
830
-
831
- audioTrack.addEventListener('mute', () => {
832
- console.log(`🎤 Audio SENDING track muted to peer ${this.peerId.substring(0, 8)}`);
833
- });
834
-
835
- audioTrack.addEventListener('unmute', () => {
836
- console.log(`🎤 Audio SENDING track unmuted to peer ${this.peerId.substring(0, 8)}`);
837
- });
838
-
839
- // Monitor audio input levels if possible
840
- const AudioContext = window.AudioContext || window.webkitAudioContext;
841
- if (!AudioContext) {
842
- console.warn('🎤 AudioContext not available - basic sending monitoring only');
843
- return;
844
- }
845
-
846
- const trackStream = new MediaStream([audioTrack]);
847
- const audioContext = new AudioContext();
848
- const source = audioContext.createMediaStreamSource(trackStream);
849
- const analyser = audioContext.createAnalyser();
850
-
851
- analyser.fftSize = 256;
852
- const bufferLength = analyser.frequencyBinCount;
853
- const dataArray = new Uint8Array(bufferLength);
854
-
855
- source.connect(analyser);
856
-
857
- let lastLogTime = 0;
858
- let totalSamples = 0;
859
- let activeSamples = 0;
860
- let maxSendLevel = 0;
861
-
862
- const monitorSending = () => {
863
- if (audioTrack.readyState === 'ended') {
864
- console.log(`🎤 Audio sending track ended, stopping monitoring to peer ${this.peerId.substring(0, 8)}`);
865
- audioContext.close();
866
- return;
867
- }
868
-
869
- analyser.getByteFrequencyData(dataArray);
870
-
871
- const average = dataArray.reduce((sum, value) => sum + value, 0) / bufferLength;
872
- const currentTime = Date.now();
873
-
874
- totalSamples++;
875
- if (average > 5) {
876
- activeSamples++;
877
- maxSendLevel = Math.max(maxSendLevel, average);
878
- }
879
-
880
- // Log every 5 seconds
881
- if (currentTime - lastLogTime > 5000) {
882
- const sendingActivity = totalSamples > 0 ? (activeSamples / totalSamples * 100) : 0;
883
- console.log(`🎤 Audio SENDING to peer ${this.peerId.substring(0, 8)}:`, {
884
- trackEnabled: audioTrack.enabled,
885
- trackReadyState: audioTrack.readyState,
886
- trackMuted: audioTrack.muted,
887
- currentSendLevel: Math.round(average),
888
- maxSendLevel: Math.round(maxSendLevel),
889
- sendingActivityPercent: Math.round(sendingActivity),
890
- samplesAnalyzed: totalSamples,
891
- audioBeingSent: activeSamples > 0
892
- });
893
-
894
- lastLogTime = currentTime;
895
- totalSamples = 0;
896
- activeSamples = 0;
897
- maxSendLevel = 0;
898
- }
899
-
900
- if (audioTrack.readyState === 'live') {
901
- requestAnimationFrame(monitorSending);
902
- }
903
- };
904
-
905
- requestAnimationFrame(monitorSending);
906
- console.log(`🎤 Audio sending monitoring started to peer ${this.peerId.substring(0, 8)}`);
907
-
908
- } catch (error) {
909
- console.error(`🎤 Failed to setup audio sending monitoring to peer ${this.peerId.substring(0, 8)}:`, error);
910
- }
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;
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);
911
816
  }
817
+ }
912
818
 
913
- /**
819
+ /**
914
820
  * Get remote media stream
915
821
  */
916
- getRemoteStream() {
917
- return this.remoteStream;
918
- }
822
+ getRemoteStream() {
823
+ return this.remoteStream;
824
+ }
919
825
 
920
- /**
826
+ /**
921
827
  * Get local media stream
922
828
  */
923
- getLocalStream() {
924
- return this.localStream;
925
- }
829
+ getLocalStream() {
830
+ return this.localStream;
831
+ }
926
832
 
927
- /**
833
+ /**
928
834
  * Check if connection has video/audio capabilities
929
835
  */
930
- getMediaCapabilities() {
931
- const capabilities = {
932
- hasLocalVideo: false,
933
- hasLocalAudio: false,
934
- hasRemoteVideo: false,
935
- hasRemoteAudio: false
936
- };
937
-
938
- if (this.localStream) {
939
- capabilities.hasLocalVideo = this.localStream.getVideoTracks().length > 0;
940
- capabilities.hasLocalAudio = this.localStream.getAudioTracks().length > 0;
941
- }
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
+ }
942
848
 
943
- if (this.remoteStream) {
944
- capabilities.hasRemoteVideo = this.remoteStream.getVideoTracks().length > 0;
945
- capabilities.hasRemoteAudio = this.remoteStream.getAudioTracks().length > 0;
946
- }
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
+ }
947
856
 
948
- 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';
949
864
  }
950
865
 
951
- getStatus() {
952
- if (this._forcedStatus) {
953
- return this._forcedStatus;
954
- }
955
- // First check if data channel is closed - this indicates disconnection regardless of WebRTC state
956
- if (this.dataChannel && this.dataChannel.readyState === 'closed') {
957
- return 'disconnected';
958
- }
959
-
960
- // If we have a WebRTC connection, check its state
961
- if (this.connection) {
962
- const connectionState = this.connection.connectionState;
963
-
964
- if (connectionState === 'connected') {
965
- // Connection is established, now check data channel
966
- if (this.dataChannel && this.dataChannel.readyState === 'open' && this.dataChannelReady) {
967
- return 'connected';
968
- } else if (this.dataChannel && this.dataChannel.readyState === 'open') {
969
- return 'connected';
970
- } else if (this.dataChannel && this.dataChannel.readyState === 'connecting') {
971
- return 'channel-connecting';
972
- } else {
973
- return 'connected';
974
- }
975
- } else if (connectionState === 'connecting') {
976
- // Check data channel state even during connection
977
- if (this.dataChannel && this.dataChannel.readyState === 'connecting') {
978
- return 'channel-connecting';
979
- } else {
980
- return 'connecting';
981
- }
982
- } else if (connectionState === 'new') {
983
- return 'connecting'; // Map 'new' to 'connecting' for UI consistency
984
- } else {
985
- // Failed, disconnected, closed, etc.
986
- return connectionState;
987
- }
988
- }
989
-
990
- // If no connection but we have a data channel (edge case)
991
- if (this.dataChannel) {
992
- if (this.dataChannel.readyState === 'connecting') {
993
- return 'channel-connecting';
994
- } else if (this.dataChannel.readyState === 'closed') {
995
- return 'disconnected';
996
- }
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';
997
880
  }
998
-
999
- // Default state when just created
1000
- return 'connecting';
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';
887
+ }
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
+ }
1001
894
  }
1002
895
 
1003
- getDetailedStatus() {
1004
- const status = {
1005
- connectionState: this.connection ? this.connection.connectionState : 'no-connection',
1006
- iceConnectionState: this.connection ? this.connection.iceConnectionState : 'no-connection',
1007
- dataChannelState: this.dataChannel ? this.dataChannel.readyState : 'no-channel',
1008
- dataChannelReady: this.dataChannelReady,
1009
- isClosing: this.isClosing,
1010
- overallStatus: this.getStatus()
1011
- };
1012
- 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
+ }
1013
903
  }
1014
904
 
1015
- close() {
1016
- // Set flag to prevent disconnection events during intentional close
1017
- this.isClosing = true;
1018
-
1019
- // Clear any pending timeouts
1020
- if (this.iceCheckingTimeout) {
1021
- clearTimeout(this.iceCheckingTimeout);
1022
- this.iceCheckingTimeout = null;
1023
- }
1024
-
1025
- if (this.connectingTimeout) {
1026
- clearTimeout(this.connectingTimeout);
1027
- this.connectingTimeout = null;
1028
- }
1029
-
1030
- if (this.connection) {
1031
- this.connection.close();
1032
- }
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();
1033
938
  }
939
+ }
1034
940
  }