@yrzhao/aves-core 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/README.md +55 -40
  2. package/dist/core/AvesClient.d.ts +32 -8
  3. package/dist/core/AvesClient.js +254 -55
  4. package/dist/core/AvesError.d.ts +1 -1
  5. package/dist/core/EventEmitter.d.ts +8 -16
  6. package/dist/core/EventEmitter.js +41 -10
  7. package/dist/core/SignalingClient.d.ts +39 -44
  8. package/dist/core/SignalingClient.js +434 -78
  9. package/dist/core/WebRTCManager.d.ts +67 -102
  10. package/dist/core/WebRTCManager.js +607 -136
  11. package/dist/core/webrtc/channels.d.ts +6 -0
  12. package/dist/core/webrtc/channels.js +15 -0
  13. package/dist/core/webrtc/fileTransfer.d.ts +46 -3
  14. package/dist/core/webrtc/fileTransfer.js +725 -78
  15. package/dist/core/webrtc/mediaTracks.d.ts +38 -5
  16. package/dist/core/webrtc/mediaTracks.js +269 -58
  17. package/dist/esm/core/AvesClient.d.ts +32 -8
  18. package/dist/esm/core/AvesClient.js +254 -55
  19. package/dist/esm/core/AvesError.d.ts +1 -1
  20. package/dist/esm/core/EventEmitter.d.ts +8 -16
  21. package/dist/esm/core/EventEmitter.js +41 -10
  22. package/dist/esm/core/SignalingClient.d.ts +39 -44
  23. package/dist/esm/core/SignalingClient.js +434 -78
  24. package/dist/esm/core/WebRTCManager.d.ts +67 -102
  25. package/dist/esm/core/WebRTCManager.js +608 -137
  26. package/dist/esm/core/webrtc/channels.d.ts +6 -0
  27. package/dist/esm/core/webrtc/channels.js +14 -0
  28. package/dist/esm/core/webrtc/fileTransfer.d.ts +46 -3
  29. package/dist/esm/core/webrtc/fileTransfer.js +722 -77
  30. package/dist/esm/core/webrtc/mediaTracks.d.ts +38 -5
  31. package/dist/esm/core/webrtc/mediaTracks.js +269 -58
  32. package/dist/esm/index.d.ts +2 -1
  33. package/dist/esm/types/types.d.ts +106 -9
  34. package/dist/index.d.ts +2 -1
  35. package/dist/types/types.d.ts +106 -9
  36. package/package.json +8 -6
@@ -1,7 +1,9 @@
1
- import { AvesVideoConstraints, LocalAudioState, LocalVideoState, ScreenShareState } from "../../types/types";
1
+ import { AvesError } from "../AvesError";
2
+ import { AvesAudioConstraints, AvesVideoConstraints, LocalAudioState, LocalVideoState, ScreenShareOptions, ScreenShareState } from "../../types/types";
2
3
  export declare class MediaTrackManager {
3
4
  private readonly peerConnections;
4
5
  private readonly getActivePeers;
6
+ private readonly onError?;
5
7
  readonly audioSenders: Map<string, RTCRtpSender | null>;
6
8
  readonly remoteAudioStreams: Map<string, MediaStream>;
7
9
  readonly videoSenders: Map<string, RTCRtpSender | null>;
@@ -9,32 +11,56 @@ export declare class MediaTrackManager {
9
11
  private localAudioStream;
10
12
  private localAudioTrack;
11
13
  private isMuted;
14
+ private readonly audioConstraints;
12
15
  private localVideoStream;
13
16
  private localVideoTrack;
14
17
  private isVideoMuted;
15
18
  private readonly videoConstraints;
16
19
  private screenShareStream;
17
20
  private screenShareTrack;
21
+ private screenShareAudioTrack;
18
22
  private screenShareActive;
19
- private cameraTrackBeforeShare;
20
23
  readonly remoteAudioTrackCallbacks: Set<(peerId: string, stream: MediaStream, track: MediaStreamTrack) => void>;
21
24
  readonly localAudioStateCallbacks: Set<(state: LocalAudioState) => void>;
22
25
  readonly remoteVideoTrackCallbacks: Set<(peerId: string, stream: MediaStream, track: MediaStreamTrack) => void>;
23
26
  readonly localVideoStateCallbacks: Set<(state: LocalVideoState) => void>;
24
27
  readonly screenShareStateCallbacks: Set<(state: ScreenShareState) => void>;
25
- constructor(peerConnections: Map<string, RTCPeerConnection>, getActivePeers: () => string[], videoConstraints?: AvesVideoConstraints);
28
+ readonly remoteTrackEndedCallbacks: Set<(peerId: string, kind: "audio" | "video", track: MediaStreamTrack) => void>;
29
+ readonly remoteTrackMutedCallbacks: Set<(peerId: string, kind: "audio" | "video", muted: boolean, track: MediaStreamTrack) => void>;
30
+ constructor(peerConnections: Map<string, RTCPeerConnection>, getActivePeers: () => string[], videoConstraints?: AvesVideoConstraints, audioConstraints?: AvesAudioConstraints, onError?: ((error: AvesError) => void) | undefined);
31
+ /**
32
+ * Bind `ontrack` handler to a PeerConnection.
33
+ *
34
+ * Note: We intentionally do NOT blindly call `addTransceiver` here for every
35
+ * peer connection. In Unified Plan WebRTC, only the offerer pre-creates
36
+ * sendrecv transceivers (`prepareOfferTransceivers`), while the answerer
37
+ * binds to the transceivers created by `setRemoteDescription(offer)` via
38
+ * `bindAnswerTransceivers`. This prevents duplicate unnegotiated m-lines.
39
+ */
26
40
  bindPeerConnection(peerId: string, pc: RTCPeerConnection): void;
27
- startVoice(): Promise<MediaStream>;
41
+ /**
42
+ * Ensure sendrecv audio and video transceivers exist before creating an offer.
43
+ */
44
+ prepareOfferTransceivers(peerId: string, pc: RTCPeerConnection): void;
45
+ /**
46
+ * Bind answer-side senders to the transceivers negotiated by `setRemoteDescription(offer)`
47
+ * and upgrade their direction to `sendrecv` so the answerer can transmit media
48
+ * on the exact same m-lines without creating orphan transceivers.
49
+ */
50
+ bindAnswerTransceivers(peerId: string, pc: RTCPeerConnection): void;
51
+ startVoice(constraints?: AvesAudioConstraints): Promise<MediaStream>;
52
+ switchAudioDevice(deviceId: string): Promise<MediaStream>;
28
53
  stopVoice(): void;
29
54
  setMuted(muted: boolean): void;
30
55
  getLocalAudioState(): LocalAudioState;
31
56
  getRemoteAudioStream(peerId: string): MediaStream | null;
32
57
  startVideo(constraints?: AvesVideoConstraints): Promise<MediaStream>;
58
+ switchVideoDevice(deviceId: string): Promise<MediaStream>;
33
59
  stopVideo(): void;
34
60
  setVideoMuted(muted: boolean): void;
35
61
  getLocalVideoState(): LocalVideoState;
36
62
  getRemoteVideoStream(peerId: string): MediaStream | null;
37
- startScreenShare(): Promise<MediaStream>;
63
+ startScreenShare(options?: ScreenShareOptions): Promise<MediaStream>;
38
64
  stopScreenShare(): void;
39
65
  getScreenShareState(): ScreenShareState;
40
66
  onRemoteAudioTrack(callback: (peerId: string, stream: MediaStream, track: MediaStreamTrack) => void): void;
@@ -42,9 +68,16 @@ export declare class MediaTrackManager {
42
68
  onRemoteVideoTrack(callback: (peerId: string, stream: MediaStream, track: MediaStreamTrack) => void): void;
43
69
  onLocalVideoStateChange(callback: (state: LocalVideoState) => void): void;
44
70
  onScreenShareStateChange(callback: (state: ScreenShareState) => void): void;
71
+ onRemoteTrackEnded(callback: (peerId: string, kind: "audio" | "video", track: MediaStreamTrack) => void): void;
72
+ onRemoteTrackMuted(callback: (peerId: string, kind: "audio" | "video", muted: boolean, track: MediaStreamTrack) => void): void;
45
73
  closePeer(peerId: string): void;
46
74
  clearCallbacks(): void;
75
+ private attachRemoteTrackLifecycle;
76
+ private findExistingTransceiverSender;
47
77
  private createTransceiverSender;
78
+ private safeSyncLocalAudioTrack;
79
+ private safeSyncLocalVideoTrack;
80
+ private safeReplaceTrack;
48
81
  private syncLocalAudioTrack;
49
82
  private syncLocalVideoTrack;
50
83
  private getOutgoingVideoTrack;
@@ -3,9 +3,10 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.MediaTrackManager = void 0;
4
4
  const AvesError_1 = require("../AvesError");
5
5
  class MediaTrackManager {
6
- constructor(peerConnections, getActivePeers, videoConstraints = {}) {
6
+ constructor(peerConnections, getActivePeers, videoConstraints = {}, audioConstraints = {}, onError) {
7
7
  this.peerConnections = peerConnections;
8
8
  this.getActivePeers = getActivePeers;
9
+ this.onError = onError;
9
10
  this.audioSenders = new Map();
10
11
  this.remoteAudioStreams = new Map();
11
12
  this.videoSenders = new Map();
@@ -18,44 +19,145 @@ class MediaTrackManager {
18
19
  this.isVideoMuted = false;
19
20
  this.screenShareStream = null;
20
21
  this.screenShareTrack = null;
22
+ this.screenShareAudioTrack = null;
21
23
  this.screenShareActive = false;
22
- this.cameraTrackBeforeShare = null;
23
24
  this.remoteAudioTrackCallbacks = new Set();
24
25
  this.localAudioStateCallbacks = new Set();
25
26
  this.remoteVideoTrackCallbacks = new Set();
26
27
  this.localVideoStateCallbacks = new Set();
27
28
  this.screenShareStateCallbacks = new Set();
29
+ this.remoteTrackEndedCallbacks = new Set();
30
+ this.remoteTrackMutedCallbacks = new Set();
28
31
  this.videoConstraints = videoConstraints;
32
+ this.audioConstraints = audioConstraints;
29
33
  }
34
+ /**
35
+ * Bind `ontrack` handler to a PeerConnection.
36
+ *
37
+ * Note: We intentionally do NOT blindly call `addTransceiver` here for every
38
+ * peer connection. In Unified Plan WebRTC, only the offerer pre-creates
39
+ * sendrecv transceivers (`prepareOfferTransceivers`), while the answerer
40
+ * binds to the transceivers created by `setRemoteDescription(offer)` via
41
+ * `bindAnswerTransceivers`. This prevents duplicate unnegotiated m-lines.
42
+ */
30
43
  bindPeerConnection(peerId, pc) {
31
44
  pc.ontrack = (event) => {
32
- const stream = event.streams[0] ??
45
+ const track = event.track;
46
+ const incomingStream = event.streams?.[0] ??
33
47
  (typeof MediaStream !== "undefined"
34
- ? new MediaStream([event.track])
48
+ ? new MediaStream([track])
35
49
  : null);
36
- if (event.track.kind === "audio") {
37
- this.remoteAudioStreams.set(peerId, stream);
38
- this.remoteAudioTrackCallbacks.forEach((callback) => callback(peerId, stream, event.track));
50
+ if (track.kind === "audio") {
51
+ const existingStream = this.remoteAudioStreams.get(peerId);
52
+ let targetStream = incomingStream;
53
+ if (existingStream && existingStream !== incomingStream) {
54
+ existingStream
55
+ .getAudioTracks()
56
+ .filter((t) => t !== track)
57
+ .forEach((t) => {
58
+ // Detach old lifecycle listeners BEFORE stopping to prevent stale callbacks.
59
+ t.onended = null;
60
+ t.onmute = null;
61
+ t.onunmute = null;
62
+ existingStream.removeTrack(t);
63
+ t.stop();
64
+ });
65
+ if (!existingStream.getAudioTracks().includes(track)) {
66
+ existingStream.addTrack(track);
67
+ }
68
+ targetStream = existingStream;
69
+ }
70
+ else {
71
+ this.remoteAudioStreams.set(peerId, incomingStream);
72
+ }
73
+ this.attachRemoteTrackLifecycle(peerId, "audio", track, targetStream);
74
+ this.remoteAudioTrackCallbacks.forEach((callback) => callback(peerId, targetStream, track));
39
75
  }
40
- else if (event.track.kind === "video") {
76
+ else if (track.kind === "video") {
41
77
  const existingStream = this.remoteVideoStreams.get(peerId);
78
+ let targetStream = incomingStream;
42
79
  if (existingStream) {
43
- existingStream.getVideoTracks().forEach((track) => track.stop());
44
- existingStream.addTrack(event.track);
80
+ existingStream
81
+ .getVideoTracks()
82
+ .filter((t) => t !== track)
83
+ .forEach((t) => {
84
+ t.onended = null;
85
+ t.onmute = null;
86
+ t.onunmute = null;
87
+ if (typeof existingStream.removeTrack === "function") {
88
+ existingStream.removeTrack(t);
89
+ }
90
+ t.stop();
91
+ });
92
+ if (!existingStream.getVideoTracks().includes(track)) {
93
+ existingStream.addTrack(track);
94
+ }
95
+ targetStream = existingStream;
45
96
  }
46
97
  else {
47
- this.remoteVideoStreams.set(peerId, stream);
98
+ this.remoteVideoStreams.set(peerId, incomingStream);
48
99
  }
49
- this.remoteVideoTrackCallbacks.forEach((callback) => callback(peerId, stream, event.track));
100
+ this.attachRemoteTrackLifecycle(peerId, "video", track, targetStream);
101
+ this.remoteVideoTrackCallbacks.forEach((callback) => callback(peerId, targetStream, track));
50
102
  }
51
103
  };
52
- this.audioSenders.set(peerId, this.createTransceiverSender(pc, "audio"));
53
- this.videoSenders.set(peerId, this.createTransceiverSender(pc, "video"));
54
- void this.syncLocalAudioTrack(peerId);
55
- void this.syncLocalVideoTrack(peerId);
104
+ // For mock/non-Unified-Plan peer connections that lack getTransceivers,
105
+ // eagerly create transceivers so legacy tests & environments continue working.
106
+ const transceiversCapable = pc;
107
+ if (typeof transceiversCapable.getTransceivers !== "function") {
108
+ this.prepareOfferTransceivers(peerId, pc);
109
+ }
110
+ }
111
+ /**
112
+ * Ensure sendrecv audio and video transceivers exist before creating an offer.
113
+ */
114
+ prepareOfferTransceivers(peerId, pc) {
115
+ if (!this.audioSenders.get(peerId)) {
116
+ const sender = this.findExistingTransceiverSender(pc, "audio") ??
117
+ this.createTransceiverSender(pc, "audio");
118
+ this.audioSenders.set(peerId, sender);
119
+ }
120
+ if (!this.videoSenders.get(peerId)) {
121
+ const sender = this.findExistingTransceiverSender(pc, "video") ??
122
+ this.createTransceiverSender(pc, "video");
123
+ this.videoSenders.set(peerId, sender);
124
+ }
125
+ this.safeSyncLocalAudioTrack(peerId);
126
+ this.safeSyncLocalVideoTrack(peerId);
56
127
  }
57
- async startVoice() {
58
- if (this.localAudioStream && this.localAudioTrack) {
128
+ /**
129
+ * Bind answer-side senders to the transceivers negotiated by `setRemoteDescription(offer)`
130
+ * and upgrade their direction to `sendrecv` so the answerer can transmit media
131
+ * on the exact same m-lines without creating orphan transceivers.
132
+ */
133
+ bindAnswerTransceivers(peerId, pc) {
134
+ const transceiversCapable = pc;
135
+ if (typeof transceiversCapable.getTransceivers === "function") {
136
+ const transceivers = transceiversCapable.getTransceivers();
137
+ const audioTransceiver = transceivers.find((t) => t.receiver?.track?.kind === "audio" ||
138
+ t.sender?.track?.kind === "audio");
139
+ if (audioTransceiver) {
140
+ if (audioTransceiver.direction === "recvonly" ||
141
+ audioTransceiver.direction === "inactive") {
142
+ audioTransceiver.direction = "sendrecv";
143
+ }
144
+ this.audioSenders.set(peerId, audioTransceiver.sender);
145
+ }
146
+ const videoTransceiver = transceivers.find((t) => t.receiver?.track?.kind === "video" ||
147
+ t.sender?.track?.kind === "video");
148
+ if (videoTransceiver) {
149
+ if (videoTransceiver.direction === "recvonly" ||
150
+ videoTransceiver.direction === "inactive") {
151
+ videoTransceiver.direction = "sendrecv";
152
+ }
153
+ this.videoSenders.set(peerId, videoTransceiver.sender);
154
+ }
155
+ }
156
+ this.safeSyncLocalAudioTrack(peerId);
157
+ this.safeSyncLocalVideoTrack(peerId);
158
+ }
159
+ async startVoice(constraints) {
160
+ if (this.localAudioStream && this.localAudioTrack && !constraints) {
59
161
  this.emitLocalAudioState();
60
162
  return this.localAudioStream;
61
163
  }
@@ -69,7 +171,11 @@ class MediaTrackManager {
69
171
  retryable: false,
70
172
  });
71
173
  }
72
- const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
174
+ const merged = { ...this.audioConstraints, ...constraints };
175
+ const audioConstraint = Object.keys(merged).length > 0 ? merged : true;
176
+ const stream = await navigator.mediaDevices.getUserMedia({
177
+ audio: audioConstraint,
178
+ });
73
179
  const [track] = stream.getAudioTracks();
74
180
  if (!track) {
75
181
  throw new AvesError_1.AvesError({
@@ -79,6 +185,10 @@ class MediaTrackManager {
79
185
  retryable: false,
80
186
  });
81
187
  }
188
+ // Stop previous track if switching devices
189
+ if (this.localAudioTrack && this.localAudioTrack !== track) {
190
+ this.localAudioTrack.stop();
191
+ }
82
192
  track.enabled = !this.isMuted;
83
193
  this.localAudioStream = stream;
84
194
  this.localAudioTrack = track;
@@ -86,12 +196,13 @@ class MediaTrackManager {
86
196
  this.emitLocalAudioState();
87
197
  return stream;
88
198
  }
199
+ async switchAudioDevice(deviceId) {
200
+ return this.startVoice({ ...this.audioConstraints, deviceId });
201
+ }
89
202
  stopVoice() {
90
203
  if (this.localAudioTrack) {
91
- this.audioSenders.forEach((sender) => {
92
- if (sender && typeof sender.replaceTrack === "function") {
93
- void sender.replaceTrack(null);
94
- }
204
+ this.audioSenders.forEach((sender, peerId) => {
205
+ this.safeReplaceTrack(peerId, sender, null);
95
206
  });
96
207
  this.localAudioTrack.stop();
97
208
  }
@@ -123,7 +234,7 @@ class MediaTrackManager {
123
234
  return this.remoteAudioStreams.get(peerId) ?? null;
124
235
  }
125
236
  async startVideo(constraints) {
126
- if (this.localVideoStream && this.localVideoTrack) {
237
+ if (this.localVideoStream && this.localVideoTrack && !constraints) {
127
238
  this.emitLocalVideoState();
128
239
  return this.localVideoStream;
129
240
  }
@@ -150,6 +261,9 @@ class MediaTrackManager {
150
261
  retryable: false,
151
262
  });
152
263
  }
264
+ if (this.localVideoTrack && this.localVideoTrack !== track) {
265
+ this.localVideoTrack.stop();
266
+ }
153
267
  track.enabled = !this.isVideoMuted;
154
268
  this.localVideoStream = stream;
155
269
  this.localVideoTrack = track;
@@ -159,13 +273,14 @@ class MediaTrackManager {
159
273
  this.emitLocalVideoState();
160
274
  return stream;
161
275
  }
276
+ async switchVideoDevice(deviceId) {
277
+ return this.startVideo({ ...this.videoConstraints, deviceId });
278
+ }
162
279
  stopVideo() {
163
280
  if (this.localVideoTrack) {
164
281
  if (!this.screenShareActive) {
165
- this.videoSenders.forEach((sender) => {
166
- if (sender && typeof sender.replaceTrack === "function") {
167
- void sender.replaceTrack(null);
168
- }
282
+ this.videoSenders.forEach((sender, peerId) => {
283
+ this.safeReplaceTrack(peerId, sender, null);
169
284
  });
170
285
  }
171
286
  this.localVideoTrack.stop();
@@ -179,7 +294,6 @@ class MediaTrackManager {
179
294
  }
180
295
  this.localVideoTrack = null;
181
296
  this.localVideoStream = null;
182
- this.cameraTrackBeforeShare = null;
183
297
  this.emitLocalVideoState();
184
298
  }
185
299
  setVideoMuted(muted) {
@@ -198,7 +312,7 @@ class MediaTrackManager {
198
312
  getRemoteVideoStream(peerId) {
199
313
  return this.remoteVideoStreams.get(peerId) ?? null;
200
314
  }
201
- async startScreenShare() {
315
+ async startScreenShare(options = {}) {
202
316
  if (this.screenShareActive && this.screenShareStream) {
203
317
  this.emitScreenShareState();
204
318
  return this.screenShareStream;
@@ -213,9 +327,10 @@ class MediaTrackManager {
213
327
  retryable: false,
214
328
  });
215
329
  }
216
- const stream = await navigator.mediaDevices.getDisplayMedia({
217
- video: true,
218
- });
330
+ const displayOptions = options.audio
331
+ ? { video: true, audio: true }
332
+ : { video: true };
333
+ const stream = await navigator.mediaDevices.getDisplayMedia(displayOptions);
219
334
  const [track] = stream.getVideoTracks();
220
335
  if (!track) {
221
336
  throw new AvesError_1.AvesError({
@@ -225,14 +340,17 @@ class MediaTrackManager {
225
340
  retryable: false,
226
341
  });
227
342
  }
228
- this.cameraTrackBeforeShare = this.localVideoTrack;
343
+ const [audioTrack] = typeof stream.getAudioTracks === "function"
344
+ ? stream.getAudioTracks()
345
+ : [];
229
346
  this.screenShareStream = stream;
230
347
  this.screenShareTrack = track;
348
+ this.screenShareAudioTrack = audioTrack ?? null;
231
349
  this.screenShareActive = true;
232
350
  await Promise.all(this.getActivePeers().map(async (peerId) => {
233
- const sender = this.videoSenders.get(peerId);
234
- if (sender && typeof sender.replaceTrack === "function") {
235
- await sender.replaceTrack(track);
351
+ await this.syncLocalVideoTrack(peerId);
352
+ if (this.screenShareAudioTrack && !this.localAudioTrack) {
353
+ this.safeReplaceTrack(peerId, this.audioSenders.get(peerId) ?? null, this.screenShareAudioTrack);
236
354
  }
237
355
  }));
238
356
  track.onended = () => {
@@ -245,7 +363,9 @@ class MediaTrackManager {
245
363
  if (!this.screenShareActive) {
246
364
  return;
247
365
  }
366
+ const hadScreenAudio = Boolean(this.screenShareAudioTrack);
248
367
  if (this.screenShareTrack) {
368
+ this.screenShareTrack.onended = null;
249
369
  this.screenShareTrack.stop();
250
370
  }
251
371
  if (this.screenShareStream) {
@@ -257,26 +377,22 @@ class MediaTrackManager {
257
377
  }
258
378
  this.screenShareStream = null;
259
379
  this.screenShareTrack = null;
380
+ this.screenShareAudioTrack = null;
260
381
  this.screenShareActive = false;
261
- const restoreTrack = this.cameraTrackBeforeShare;
262
- this.cameraTrackBeforeShare = null;
263
- if (restoreTrack && restoreTrack.readyState === "live") {
264
- this.localVideoTrack = restoreTrack;
265
- void Promise.all(this.getActivePeers().map(async (peerId) => {
266
- const sender = this.videoSenders.get(peerId);
267
- if (sender && typeof sender.replaceTrack === "function") {
268
- await sender.replaceTrack(restoreTrack);
269
- }
270
- }));
271
- }
272
- else {
273
- void Promise.all(this.getActivePeers().map(async (peerId) => {
274
- const sender = this.videoSenders.get(peerId);
275
- if (sender && typeof sender.replaceTrack === "function") {
276
- await sender.replaceTrack(null);
277
- }
278
- }));
279
- }
382
+ // Always inspect the current localVideoTrack so camera devices switched or
383
+ // started during screen sharing are seamlessly restored rather than stale tracks.
384
+ const activeCamera = this.localVideoTrack && this.localVideoTrack.readyState === "live"
385
+ ? this.localVideoTrack
386
+ : null;
387
+ this.getActivePeers().forEach((peerId) => {
388
+ this.safeReplaceTrack(peerId, this.videoSenders.get(peerId) ?? null, activeCamera);
389
+ if (hadScreenAudio) {
390
+ const restoreAudio = this.localAudioTrack && this.localAudioTrack.readyState === "live"
391
+ ? this.localAudioTrack
392
+ : null;
393
+ this.safeReplaceTrack(peerId, this.audioSenders.get(peerId) ?? null, restoreAudio);
394
+ }
395
+ });
280
396
  this.emitScreenShareState();
281
397
  this.emitLocalVideoState();
282
398
  }
@@ -301,6 +417,12 @@ class MediaTrackManager {
301
417
  onScreenShareStateChange(callback) {
302
418
  this.screenShareStateCallbacks.add(callback);
303
419
  }
420
+ onRemoteTrackEnded(callback) {
421
+ this.remoteTrackEndedCallbacks.add(callback);
422
+ }
423
+ onRemoteTrackMuted(callback) {
424
+ this.remoteTrackMutedCallbacks.add(callback);
425
+ }
304
426
  closePeer(peerId) {
305
427
  this.audioSenders.delete(peerId);
306
428
  this.remoteAudioStreams.delete(peerId);
@@ -313,6 +435,52 @@ class MediaTrackManager {
313
435
  this.remoteVideoTrackCallbacks.clear();
314
436
  this.localVideoStateCallbacks.clear();
315
437
  this.screenShareStateCallbacks.clear();
438
+ this.remoteTrackEndedCallbacks.clear();
439
+ this.remoteTrackMutedCallbacks.clear();
440
+ }
441
+ attachRemoteTrackLifecycle(peerId, kind, track, stream) {
442
+ track.onmute = () => {
443
+ this.remoteTrackMutedCallbacks.forEach((callback) => callback(peerId, kind, true, track));
444
+ };
445
+ track.onunmute = () => {
446
+ this.remoteTrackMutedCallbacks.forEach((callback) => callback(peerId, kind, false, track));
447
+ };
448
+ track.onended = () => {
449
+ if (stream && typeof stream.removeTrack === "function") {
450
+ try {
451
+ stream.removeTrack(track);
452
+ }
453
+ catch {
454
+ // Ignore removal errors on ended tracks.
455
+ }
456
+ }
457
+ // Only fire remoteTrackEnded if no newer live track of the same kind replaced it.
458
+ const remainingLive = stream && typeof stream.getTracks === "function"
459
+ ? stream
460
+ .getTracks()
461
+ .some((t) => t.kind === kind && t !== track && t.readyState === "live")
462
+ : false;
463
+ if (!remainingLive) {
464
+ this.remoteTrackEndedCallbacks.forEach((callback) => callback(peerId, kind, track));
465
+ }
466
+ };
467
+ }
468
+ findExistingTransceiverSender(pc, kind) {
469
+ const transceiversCapable = pc;
470
+ if (typeof transceiversCapable.getTransceivers !== "function") {
471
+ return null;
472
+ }
473
+ const transceiver = transceiversCapable
474
+ .getTransceivers()
475
+ .find((t) => t.receiver?.track?.kind === kind || t.sender?.track?.kind === kind);
476
+ if (!transceiver) {
477
+ return null;
478
+ }
479
+ if (transceiver.direction === "recvonly" ||
480
+ transceiver.direction === "inactive") {
481
+ transceiver.direction = "sendrecv";
482
+ }
483
+ return transceiver.sender;
316
484
  }
317
485
  createTransceiverSender(pc, kind) {
318
486
  const capable = pc;
@@ -324,13 +492,54 @@ class MediaTrackManager {
324
492
  }
325
493
  return null;
326
494
  }
495
+ safeSyncLocalAudioTrack(peerId) {
496
+ void this.syncLocalAudioTrack(peerId).catch((error) => {
497
+ this.onError?.(new AvesError_1.AvesError({
498
+ message: `Failed to sync local audio track for ${peerId}: ${error instanceof Error ? error.message : String(error)}`,
499
+ code: "MEDIA_CAPTURE_FAILED",
500
+ stage: "transport",
501
+ retryable: true,
502
+ peerId,
503
+ cause: error,
504
+ }));
505
+ });
506
+ }
507
+ safeSyncLocalVideoTrack(peerId) {
508
+ void this.syncLocalVideoTrack(peerId).catch((error) => {
509
+ this.onError?.(new AvesError_1.AvesError({
510
+ message: `Failed to sync local video track for ${peerId}: ${error instanceof Error ? error.message : String(error)}`,
511
+ code: "MEDIA_CAPTURE_FAILED",
512
+ stage: "transport",
513
+ retryable: true,
514
+ peerId,
515
+ cause: error,
516
+ }));
517
+ });
518
+ }
519
+ safeReplaceTrack(peerId, sender, track) {
520
+ if (!sender || typeof sender.replaceTrack !== "function") {
521
+ return;
522
+ }
523
+ void sender.replaceTrack(track).catch((error) => {
524
+ this.onError?.(new AvesError_1.AvesError({
525
+ message: `Failed to replace media track for ${peerId}: ${error instanceof Error ? error.message : String(error)}`,
526
+ code: "MEDIA_CAPTURE_FAILED",
527
+ stage: "transport",
528
+ retryable: true,
529
+ peerId,
530
+ cause: error,
531
+ }));
532
+ });
533
+ }
327
534
  async syncLocalAudioTrack(peerId) {
328
535
  const pc = this.peerConnections.get(peerId);
329
536
  if (!pc) {
330
537
  return;
331
538
  }
332
- let sender = this.audioSenders.get(peerId) ?? null;
539
+ let sender = this.audioSenders.get(peerId) ??
540
+ this.findExistingTransceiverSender(pc, "audio");
333
541
  if (sender && typeof sender.replaceTrack === "function") {
542
+ this.audioSenders.set(peerId, sender);
334
543
  await sender.replaceTrack(this.localAudioTrack);
335
544
  return;
336
545
  }
@@ -353,8 +562,10 @@ class MediaTrackManager {
353
562
  return;
354
563
  }
355
564
  const outgoingTrack = this.getOutgoingVideoTrack();
356
- let sender = this.videoSenders.get(peerId) ?? null;
565
+ let sender = this.videoSenders.get(peerId) ??
566
+ this.findExistingTransceiverSender(pc, "video");
357
567
  if (sender && typeof sender.replaceTrack === "function") {
568
+ this.videoSenders.set(peerId, sender);
358
569
  await sender.replaceTrack(outgoingTrack);
359
570
  return;
360
571
  }
@@ -1,16 +1,20 @@
1
1
  import { EventEmitter } from "./EventEmitter";
2
2
  import { AvesError } from "./AvesError";
3
- import { AvesClientConfig, AvesConnectionSnapshot, AvesMessage, AvesPeerSnapshot, AvesVideoConstraints, FileTransferInfo, FileTransferOptions, FileTransferProgress, FileTransferResult, LocalAudioState, LocalVideoState, Participant, ScreenShareState, WaitForPeerOptions } from "../types/types";
3
+ import { AvesAudioConstraints, AvesClientConfig, AvesConnectionSnapshot, AvesMessage, AvesPeerSnapshot, AvesPeerStats, AvesVideoConstraints, CreateRoomOptions, FileTransferInfo, FileTransferOptions, FileTransferProgress, FileTransferResult, JoinRoomOptions, LocalAudioState, LocalVideoState, Participant, ScreenShareOptions, ScreenShareState, WaitForPeerOptions } from "../types/types";
4
4
  export type AvesClientEvents = {
5
5
  signalingStateChange: [state: string];
6
+ sessionRestored: [participants: Participant[]];
6
7
  error: [error: AvesError];
7
8
  userJoined: [user: Participant];
8
9
  userLeft: [userId: string];
9
10
  connectionStateChange: [peerId: string, state: RTCPeerConnectionState];
10
11
  dataChannelStateChange: [peerId: string, state: RTCDataChannelState];
12
+ fileChannelStateChange: [peerId: string, state: RTCDataChannelState];
11
13
  message: [peerId: string, message: AvesMessage];
12
14
  remoteAudioTrack: [peerId: string, stream: MediaStream, track: MediaStreamTrack];
13
15
  remoteVideoTrack: [peerId: string, stream: MediaStream, track: MediaStreamTrack];
16
+ remoteTrackEnded: [peerId: string, kind: "audio" | "video", track: MediaStreamTrack];
17
+ remoteTrackMuted: [peerId: string, kind: "audio" | "video", muted: boolean, track: MediaStreamTrack];
14
18
  localAudioStateChange: [state: LocalAudioState];
15
19
  localVideoStateChange: [state: LocalVideoState];
16
20
  screenShareStateChange: [state: ScreenShareState];
@@ -20,7 +24,7 @@ export type AvesClientEvents = {
20
24
  fileTransferFailed: [peerId: string, info: FileTransferInfo | null, error: AvesError];
21
25
  };
22
26
  /**
23
- * AvesClient - Main client class for WebRTC communication.
27
+ * AvesClient - Main browser WebRTC client for P2P rooms.
24
28
  */
25
29
  export declare class AvesClient extends EventEmitter<AvesClientEvents> {
26
30
  private config;
@@ -29,35 +33,55 @@ export declare class AvesClient extends EventEmitter<AvesClientEvents> {
29
33
  private currentRoomId;
30
34
  private currentUserId;
31
35
  private currentUserName;
36
+ private currentRoomPassword;
37
+ private currentReconnectToken;
32
38
  private participants;
33
- private preparedPeers;
39
+ private preparedPeerConnections;
34
40
  private shouldRestoreSession;
35
41
  constructor(config: AvesClientConfig);
42
+ private isPoliteForPeer;
36
43
  private setupEventHandlers;
37
44
  private restoreRoomSession;
38
45
  private preparePeerConnection;
39
46
  private initiateConnection;
40
- createRoom(): Promise<string>;
41
- joinRoom(roomId: string, userName: string): Promise<Participant[]>;
42
- joinRoom(roomId: string, userId: string, userName: string): Promise<Participant[]>;
47
+ /**
48
+ * Update authentication token for subsequent signaling connections.
49
+ */
50
+ setAuthToken(token?: string): void;
51
+ /**
52
+ * Update ICE/TURN servers dynamically (e.g. rotating time-limited TURN credentials).
53
+ */
54
+ updateIceServers(iceServers: RTCIceServer[]): void;
55
+ /**
56
+ * Create a new room with optional name, capacity, and password.
57
+ */
58
+ createRoom(options?: CreateRoomOptions): Promise<string>;
59
+ joinRoom(roomId: string, userName: string, options?: JoinRoomOptions): Promise<Participant[]>;
60
+ joinRoom(roomId: string, userId: string, userName: string, password?: string): Promise<Participant[]>;
43
61
  leaveRoom(): Promise<void>;
44
62
  sendMessage(message: AvesMessage): void;
45
63
  sendMessageToPeer(peerId: string, message: AvesMessage): void;
46
64
  sendFile(blob: Blob, options?: FileTransferOptions): Promise<FileTransferInfo[]>;
47
- startVoice(): Promise<MediaStream>;
65
+ cancelFileTransfer(peerId: string, transferId?: string): boolean;
66
+ startVoice(constraints?: AvesAudioConstraints): Promise<MediaStream>;
67
+ switchAudioDevice(deviceId: string): Promise<MediaStream>;
48
68
  stopVoice(): void;
49
69
  setMuted(muted: boolean): void;
50
70
  getLocalAudioState(): LocalAudioState;
51
71
  getRemoteAudioStream(peerId: string): MediaStream | null;
52
72
  startVideo(constraints?: AvesVideoConstraints): Promise<MediaStream>;
73
+ switchVideoDevice(deviceId: string): Promise<MediaStream>;
53
74
  stopVideo(): void;
54
75
  setVideoMuted(muted: boolean): void;
55
76
  getLocalVideoState(): LocalVideoState;
56
77
  getRemoteVideoStream(peerId: string): MediaStream | null;
57
- startScreenShare(): Promise<MediaStream>;
78
+ startScreenShare(options?: ScreenShareOptions): Promise<MediaStream>;
58
79
  stopScreenShare(): void;
59
80
  getScreenShareState(): ScreenShareState;
60
81
  getConnectionState(peerId: string): RTCPeerConnectionState;
82
+ getPeerStats(peerId: string): Promise<AvesPeerStats | null>;
83
+ getAllPeerStats(): Promise<AvesPeerStats[]>;
84
+ restartPeerIce(peerId: string): Promise<void>;
61
85
  getConnectionSnapshot(): AvesConnectionSnapshot;
62
86
  waitForPeer(peerId: string, options?: WaitForPeerOptions): Promise<AvesPeerSnapshot>;
63
87
  getParticipants(): Participant[];