@yrzhao/aves-core 1.0.1 → 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 +131 -75
  2. package/dist/core/AvesClient.d.ts +35 -8
  3. package/dist/core/AvesClient.js +351 -52
  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 +68 -99
  10. package/dist/core/WebRTCManager.js +611 -133
  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 +35 -8
  18. package/dist/esm/core/AvesClient.js +351 -52
  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 +68 -99
  25. package/dist/esm/core/WebRTCManager.js +612 -134
  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 +126 -9
  34. package/dist/index.d.ts +2 -1
  35. package/dist/types/types.d.ts +126 -9
  36. package/package.json +22 -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;
@@ -1,8 +1,9 @@
1
1
  import { AvesError } from "../AvesError.js";
2
2
  export class MediaTrackManager {
3
- constructor(peerConnections, getActivePeers, videoConstraints = {}) {
3
+ constructor(peerConnections, getActivePeers, videoConstraints = {}, audioConstraints = {}, onError) {
4
4
  this.peerConnections = peerConnections;
5
5
  this.getActivePeers = getActivePeers;
6
+ this.onError = onError;
6
7
  this.audioSenders = new Map();
7
8
  this.remoteAudioStreams = new Map();
8
9
  this.videoSenders = new Map();
@@ -15,44 +16,145 @@ export class MediaTrackManager {
15
16
  this.isVideoMuted = false;
16
17
  this.screenShareStream = null;
17
18
  this.screenShareTrack = null;
19
+ this.screenShareAudioTrack = null;
18
20
  this.screenShareActive = false;
19
- this.cameraTrackBeforeShare = null;
20
21
  this.remoteAudioTrackCallbacks = new Set();
21
22
  this.localAudioStateCallbacks = new Set();
22
23
  this.remoteVideoTrackCallbacks = new Set();
23
24
  this.localVideoStateCallbacks = new Set();
24
25
  this.screenShareStateCallbacks = new Set();
26
+ this.remoteTrackEndedCallbacks = new Set();
27
+ this.remoteTrackMutedCallbacks = new Set();
25
28
  this.videoConstraints = videoConstraints;
29
+ this.audioConstraints = audioConstraints;
26
30
  }
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
+ */
27
40
  bindPeerConnection(peerId, pc) {
28
41
  pc.ontrack = (event) => {
29
- const stream = event.streams[0] ??
42
+ const track = event.track;
43
+ const incomingStream = event.streams?.[0] ??
30
44
  (typeof MediaStream !== "undefined"
31
- ? new MediaStream([event.track])
45
+ ? new MediaStream([track])
32
46
  : null);
33
- if (event.track.kind === "audio") {
34
- this.remoteAudioStreams.set(peerId, stream);
35
- this.remoteAudioTrackCallbacks.forEach((callback) => callback(peerId, stream, event.track));
47
+ if (track.kind === "audio") {
48
+ const existingStream = this.remoteAudioStreams.get(peerId);
49
+ let targetStream = incomingStream;
50
+ if (existingStream && existingStream !== incomingStream) {
51
+ existingStream
52
+ .getAudioTracks()
53
+ .filter((t) => t !== track)
54
+ .forEach((t) => {
55
+ // Detach old lifecycle listeners BEFORE stopping to prevent stale callbacks.
56
+ t.onended = null;
57
+ t.onmute = null;
58
+ t.onunmute = null;
59
+ existingStream.removeTrack(t);
60
+ t.stop();
61
+ });
62
+ if (!existingStream.getAudioTracks().includes(track)) {
63
+ existingStream.addTrack(track);
64
+ }
65
+ targetStream = existingStream;
66
+ }
67
+ else {
68
+ this.remoteAudioStreams.set(peerId, incomingStream);
69
+ }
70
+ this.attachRemoteTrackLifecycle(peerId, "audio", track, targetStream);
71
+ this.remoteAudioTrackCallbacks.forEach((callback) => callback(peerId, targetStream, track));
36
72
  }
37
- else if (event.track.kind === "video") {
73
+ else if (track.kind === "video") {
38
74
  const existingStream = this.remoteVideoStreams.get(peerId);
75
+ let targetStream = incomingStream;
39
76
  if (existingStream) {
40
- existingStream.getVideoTracks().forEach((track) => track.stop());
41
- existingStream.addTrack(event.track);
77
+ existingStream
78
+ .getVideoTracks()
79
+ .filter((t) => t !== track)
80
+ .forEach((t) => {
81
+ t.onended = null;
82
+ t.onmute = null;
83
+ t.onunmute = null;
84
+ if (typeof existingStream.removeTrack === "function") {
85
+ existingStream.removeTrack(t);
86
+ }
87
+ t.stop();
88
+ });
89
+ if (!existingStream.getVideoTracks().includes(track)) {
90
+ existingStream.addTrack(track);
91
+ }
92
+ targetStream = existingStream;
42
93
  }
43
94
  else {
44
- this.remoteVideoStreams.set(peerId, stream);
95
+ this.remoteVideoStreams.set(peerId, incomingStream);
45
96
  }
46
- this.remoteVideoTrackCallbacks.forEach((callback) => callback(peerId, stream, event.track));
97
+ this.attachRemoteTrackLifecycle(peerId, "video", track, targetStream);
98
+ this.remoteVideoTrackCallbacks.forEach((callback) => callback(peerId, targetStream, track));
47
99
  }
48
100
  };
49
- this.audioSenders.set(peerId, this.createTransceiverSender(pc, "audio"));
50
- this.videoSenders.set(peerId, this.createTransceiverSender(pc, "video"));
51
- void this.syncLocalAudioTrack(peerId);
52
- void this.syncLocalVideoTrack(peerId);
101
+ // For mock/non-Unified-Plan peer connections that lack getTransceivers,
102
+ // eagerly create transceivers so legacy tests & environments continue working.
103
+ const transceiversCapable = pc;
104
+ if (typeof transceiversCapable.getTransceivers !== "function") {
105
+ this.prepareOfferTransceivers(peerId, pc);
106
+ }
107
+ }
108
+ /**
109
+ * Ensure sendrecv audio and video transceivers exist before creating an offer.
110
+ */
111
+ prepareOfferTransceivers(peerId, pc) {
112
+ if (!this.audioSenders.get(peerId)) {
113
+ const sender = this.findExistingTransceiverSender(pc, "audio") ??
114
+ this.createTransceiverSender(pc, "audio");
115
+ this.audioSenders.set(peerId, sender);
116
+ }
117
+ if (!this.videoSenders.get(peerId)) {
118
+ const sender = this.findExistingTransceiverSender(pc, "video") ??
119
+ this.createTransceiverSender(pc, "video");
120
+ this.videoSenders.set(peerId, sender);
121
+ }
122
+ this.safeSyncLocalAudioTrack(peerId);
123
+ this.safeSyncLocalVideoTrack(peerId);
53
124
  }
54
- async startVoice() {
55
- if (this.localAudioStream && this.localAudioTrack) {
125
+ /**
126
+ * Bind answer-side senders to the transceivers negotiated by `setRemoteDescription(offer)`
127
+ * and upgrade their direction to `sendrecv` so the answerer can transmit media
128
+ * on the exact same m-lines without creating orphan transceivers.
129
+ */
130
+ bindAnswerTransceivers(peerId, pc) {
131
+ const transceiversCapable = pc;
132
+ if (typeof transceiversCapable.getTransceivers === "function") {
133
+ const transceivers = transceiversCapable.getTransceivers();
134
+ const audioTransceiver = transceivers.find((t) => t.receiver?.track?.kind === "audio" ||
135
+ t.sender?.track?.kind === "audio");
136
+ if (audioTransceiver) {
137
+ if (audioTransceiver.direction === "recvonly" ||
138
+ audioTransceiver.direction === "inactive") {
139
+ audioTransceiver.direction = "sendrecv";
140
+ }
141
+ this.audioSenders.set(peerId, audioTransceiver.sender);
142
+ }
143
+ const videoTransceiver = transceivers.find((t) => t.receiver?.track?.kind === "video" ||
144
+ t.sender?.track?.kind === "video");
145
+ if (videoTransceiver) {
146
+ if (videoTransceiver.direction === "recvonly" ||
147
+ videoTransceiver.direction === "inactive") {
148
+ videoTransceiver.direction = "sendrecv";
149
+ }
150
+ this.videoSenders.set(peerId, videoTransceiver.sender);
151
+ }
152
+ }
153
+ this.safeSyncLocalAudioTrack(peerId);
154
+ this.safeSyncLocalVideoTrack(peerId);
155
+ }
156
+ async startVoice(constraints) {
157
+ if (this.localAudioStream && this.localAudioTrack && !constraints) {
56
158
  this.emitLocalAudioState();
57
159
  return this.localAudioStream;
58
160
  }
@@ -66,7 +168,11 @@ export class MediaTrackManager {
66
168
  retryable: false,
67
169
  });
68
170
  }
69
- const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
171
+ const merged = { ...this.audioConstraints, ...constraints };
172
+ const audioConstraint = Object.keys(merged).length > 0 ? merged : true;
173
+ const stream = await navigator.mediaDevices.getUserMedia({
174
+ audio: audioConstraint,
175
+ });
70
176
  const [track] = stream.getAudioTracks();
71
177
  if (!track) {
72
178
  throw new AvesError({
@@ -76,6 +182,10 @@ export class MediaTrackManager {
76
182
  retryable: false,
77
183
  });
78
184
  }
185
+ // Stop previous track if switching devices
186
+ if (this.localAudioTrack && this.localAudioTrack !== track) {
187
+ this.localAudioTrack.stop();
188
+ }
79
189
  track.enabled = !this.isMuted;
80
190
  this.localAudioStream = stream;
81
191
  this.localAudioTrack = track;
@@ -83,12 +193,13 @@ export class MediaTrackManager {
83
193
  this.emitLocalAudioState();
84
194
  return stream;
85
195
  }
196
+ async switchAudioDevice(deviceId) {
197
+ return this.startVoice({ ...this.audioConstraints, deviceId });
198
+ }
86
199
  stopVoice() {
87
200
  if (this.localAudioTrack) {
88
- this.audioSenders.forEach((sender) => {
89
- if (sender && typeof sender.replaceTrack === "function") {
90
- void sender.replaceTrack(null);
91
- }
201
+ this.audioSenders.forEach((sender, peerId) => {
202
+ this.safeReplaceTrack(peerId, sender, null);
92
203
  });
93
204
  this.localAudioTrack.stop();
94
205
  }
@@ -120,7 +231,7 @@ export class MediaTrackManager {
120
231
  return this.remoteAudioStreams.get(peerId) ?? null;
121
232
  }
122
233
  async startVideo(constraints) {
123
- if (this.localVideoStream && this.localVideoTrack) {
234
+ if (this.localVideoStream && this.localVideoTrack && !constraints) {
124
235
  this.emitLocalVideoState();
125
236
  return this.localVideoStream;
126
237
  }
@@ -147,6 +258,9 @@ export class MediaTrackManager {
147
258
  retryable: false,
148
259
  });
149
260
  }
261
+ if (this.localVideoTrack && this.localVideoTrack !== track) {
262
+ this.localVideoTrack.stop();
263
+ }
150
264
  track.enabled = !this.isVideoMuted;
151
265
  this.localVideoStream = stream;
152
266
  this.localVideoTrack = track;
@@ -156,13 +270,14 @@ export class MediaTrackManager {
156
270
  this.emitLocalVideoState();
157
271
  return stream;
158
272
  }
273
+ async switchVideoDevice(deviceId) {
274
+ return this.startVideo({ ...this.videoConstraints, deviceId });
275
+ }
159
276
  stopVideo() {
160
277
  if (this.localVideoTrack) {
161
278
  if (!this.screenShareActive) {
162
- this.videoSenders.forEach((sender) => {
163
- if (sender && typeof sender.replaceTrack === "function") {
164
- void sender.replaceTrack(null);
165
- }
279
+ this.videoSenders.forEach((sender, peerId) => {
280
+ this.safeReplaceTrack(peerId, sender, null);
166
281
  });
167
282
  }
168
283
  this.localVideoTrack.stop();
@@ -176,7 +291,6 @@ export class MediaTrackManager {
176
291
  }
177
292
  this.localVideoTrack = null;
178
293
  this.localVideoStream = null;
179
- this.cameraTrackBeforeShare = null;
180
294
  this.emitLocalVideoState();
181
295
  }
182
296
  setVideoMuted(muted) {
@@ -195,7 +309,7 @@ export class MediaTrackManager {
195
309
  getRemoteVideoStream(peerId) {
196
310
  return this.remoteVideoStreams.get(peerId) ?? null;
197
311
  }
198
- async startScreenShare() {
312
+ async startScreenShare(options = {}) {
199
313
  if (this.screenShareActive && this.screenShareStream) {
200
314
  this.emitScreenShareState();
201
315
  return this.screenShareStream;
@@ -210,9 +324,10 @@ export class MediaTrackManager {
210
324
  retryable: false,
211
325
  });
212
326
  }
213
- const stream = await navigator.mediaDevices.getDisplayMedia({
214
- video: true,
215
- });
327
+ const displayOptions = options.audio
328
+ ? { video: true, audio: true }
329
+ : { video: true };
330
+ const stream = await navigator.mediaDevices.getDisplayMedia(displayOptions);
216
331
  const [track] = stream.getVideoTracks();
217
332
  if (!track) {
218
333
  throw new AvesError({
@@ -222,14 +337,17 @@ export class MediaTrackManager {
222
337
  retryable: false,
223
338
  });
224
339
  }
225
- this.cameraTrackBeforeShare = this.localVideoTrack;
340
+ const [audioTrack] = typeof stream.getAudioTracks === "function"
341
+ ? stream.getAudioTracks()
342
+ : [];
226
343
  this.screenShareStream = stream;
227
344
  this.screenShareTrack = track;
345
+ this.screenShareAudioTrack = audioTrack ?? null;
228
346
  this.screenShareActive = true;
229
347
  await Promise.all(this.getActivePeers().map(async (peerId) => {
230
- const sender = this.videoSenders.get(peerId);
231
- if (sender && typeof sender.replaceTrack === "function") {
232
- await sender.replaceTrack(track);
348
+ await this.syncLocalVideoTrack(peerId);
349
+ if (this.screenShareAudioTrack && !this.localAudioTrack) {
350
+ this.safeReplaceTrack(peerId, this.audioSenders.get(peerId) ?? null, this.screenShareAudioTrack);
233
351
  }
234
352
  }));
235
353
  track.onended = () => {
@@ -242,7 +360,9 @@ export class MediaTrackManager {
242
360
  if (!this.screenShareActive) {
243
361
  return;
244
362
  }
363
+ const hadScreenAudio = Boolean(this.screenShareAudioTrack);
245
364
  if (this.screenShareTrack) {
365
+ this.screenShareTrack.onended = null;
246
366
  this.screenShareTrack.stop();
247
367
  }
248
368
  if (this.screenShareStream) {
@@ -254,26 +374,22 @@ export class MediaTrackManager {
254
374
  }
255
375
  this.screenShareStream = null;
256
376
  this.screenShareTrack = null;
377
+ this.screenShareAudioTrack = null;
257
378
  this.screenShareActive = false;
258
- const restoreTrack = this.cameraTrackBeforeShare;
259
- this.cameraTrackBeforeShare = null;
260
- if (restoreTrack && restoreTrack.readyState === "live") {
261
- this.localVideoTrack = restoreTrack;
262
- void Promise.all(this.getActivePeers().map(async (peerId) => {
263
- const sender = this.videoSenders.get(peerId);
264
- if (sender && typeof sender.replaceTrack === "function") {
265
- await sender.replaceTrack(restoreTrack);
266
- }
267
- }));
268
- }
269
- else {
270
- void Promise.all(this.getActivePeers().map(async (peerId) => {
271
- const sender = this.videoSenders.get(peerId);
272
- if (sender && typeof sender.replaceTrack === "function") {
273
- await sender.replaceTrack(null);
274
- }
275
- }));
276
- }
379
+ // Always inspect the current localVideoTrack so camera devices switched or
380
+ // started during screen sharing are seamlessly restored rather than stale tracks.
381
+ const activeCamera = this.localVideoTrack && this.localVideoTrack.readyState === "live"
382
+ ? this.localVideoTrack
383
+ : null;
384
+ this.getActivePeers().forEach((peerId) => {
385
+ this.safeReplaceTrack(peerId, this.videoSenders.get(peerId) ?? null, activeCamera);
386
+ if (hadScreenAudio) {
387
+ const restoreAudio = this.localAudioTrack && this.localAudioTrack.readyState === "live"
388
+ ? this.localAudioTrack
389
+ : null;
390
+ this.safeReplaceTrack(peerId, this.audioSenders.get(peerId) ?? null, restoreAudio);
391
+ }
392
+ });
277
393
  this.emitScreenShareState();
278
394
  this.emitLocalVideoState();
279
395
  }
@@ -298,6 +414,12 @@ export class MediaTrackManager {
298
414
  onScreenShareStateChange(callback) {
299
415
  this.screenShareStateCallbacks.add(callback);
300
416
  }
417
+ onRemoteTrackEnded(callback) {
418
+ this.remoteTrackEndedCallbacks.add(callback);
419
+ }
420
+ onRemoteTrackMuted(callback) {
421
+ this.remoteTrackMutedCallbacks.add(callback);
422
+ }
301
423
  closePeer(peerId) {
302
424
  this.audioSenders.delete(peerId);
303
425
  this.remoteAudioStreams.delete(peerId);
@@ -310,6 +432,52 @@ export class MediaTrackManager {
310
432
  this.remoteVideoTrackCallbacks.clear();
311
433
  this.localVideoStateCallbacks.clear();
312
434
  this.screenShareStateCallbacks.clear();
435
+ this.remoteTrackEndedCallbacks.clear();
436
+ this.remoteTrackMutedCallbacks.clear();
437
+ }
438
+ attachRemoteTrackLifecycle(peerId, kind, track, stream) {
439
+ track.onmute = () => {
440
+ this.remoteTrackMutedCallbacks.forEach((callback) => callback(peerId, kind, true, track));
441
+ };
442
+ track.onunmute = () => {
443
+ this.remoteTrackMutedCallbacks.forEach((callback) => callback(peerId, kind, false, track));
444
+ };
445
+ track.onended = () => {
446
+ if (stream && typeof stream.removeTrack === "function") {
447
+ try {
448
+ stream.removeTrack(track);
449
+ }
450
+ catch {
451
+ // Ignore removal errors on ended tracks.
452
+ }
453
+ }
454
+ // Only fire remoteTrackEnded if no newer live track of the same kind replaced it.
455
+ const remainingLive = stream && typeof stream.getTracks === "function"
456
+ ? stream
457
+ .getTracks()
458
+ .some((t) => t.kind === kind && t !== track && t.readyState === "live")
459
+ : false;
460
+ if (!remainingLive) {
461
+ this.remoteTrackEndedCallbacks.forEach((callback) => callback(peerId, kind, track));
462
+ }
463
+ };
464
+ }
465
+ findExistingTransceiverSender(pc, kind) {
466
+ const transceiversCapable = pc;
467
+ if (typeof transceiversCapable.getTransceivers !== "function") {
468
+ return null;
469
+ }
470
+ const transceiver = transceiversCapable
471
+ .getTransceivers()
472
+ .find((t) => t.receiver?.track?.kind === kind || t.sender?.track?.kind === kind);
473
+ if (!transceiver) {
474
+ return null;
475
+ }
476
+ if (transceiver.direction === "recvonly" ||
477
+ transceiver.direction === "inactive") {
478
+ transceiver.direction = "sendrecv";
479
+ }
480
+ return transceiver.sender;
313
481
  }
314
482
  createTransceiverSender(pc, kind) {
315
483
  const capable = pc;
@@ -321,13 +489,54 @@ export class MediaTrackManager {
321
489
  }
322
490
  return null;
323
491
  }
492
+ safeSyncLocalAudioTrack(peerId) {
493
+ void this.syncLocalAudioTrack(peerId).catch((error) => {
494
+ this.onError?.(new AvesError({
495
+ message: `Failed to sync local audio track for ${peerId}: ${error instanceof Error ? error.message : String(error)}`,
496
+ code: "MEDIA_CAPTURE_FAILED",
497
+ stage: "transport",
498
+ retryable: true,
499
+ peerId,
500
+ cause: error,
501
+ }));
502
+ });
503
+ }
504
+ safeSyncLocalVideoTrack(peerId) {
505
+ void this.syncLocalVideoTrack(peerId).catch((error) => {
506
+ this.onError?.(new AvesError({
507
+ message: `Failed to sync local video track for ${peerId}: ${error instanceof Error ? error.message : String(error)}`,
508
+ code: "MEDIA_CAPTURE_FAILED",
509
+ stage: "transport",
510
+ retryable: true,
511
+ peerId,
512
+ cause: error,
513
+ }));
514
+ });
515
+ }
516
+ safeReplaceTrack(peerId, sender, track) {
517
+ if (!sender || typeof sender.replaceTrack !== "function") {
518
+ return;
519
+ }
520
+ void sender.replaceTrack(track).catch((error) => {
521
+ this.onError?.(new AvesError({
522
+ message: `Failed to replace media track for ${peerId}: ${error instanceof Error ? error.message : String(error)}`,
523
+ code: "MEDIA_CAPTURE_FAILED",
524
+ stage: "transport",
525
+ retryable: true,
526
+ peerId,
527
+ cause: error,
528
+ }));
529
+ });
530
+ }
324
531
  async syncLocalAudioTrack(peerId) {
325
532
  const pc = this.peerConnections.get(peerId);
326
533
  if (!pc) {
327
534
  return;
328
535
  }
329
- let sender = this.audioSenders.get(peerId) ?? null;
536
+ let sender = this.audioSenders.get(peerId) ??
537
+ this.findExistingTransceiverSender(pc, "audio");
330
538
  if (sender && typeof sender.replaceTrack === "function") {
539
+ this.audioSenders.set(peerId, sender);
331
540
  await sender.replaceTrack(this.localAudioTrack);
332
541
  return;
333
542
  }
@@ -350,8 +559,10 @@ export class MediaTrackManager {
350
559
  return;
351
560
  }
352
561
  const outgoingTrack = this.getOutgoingVideoTrack();
353
- let sender = this.videoSenders.get(peerId) ?? null;
562
+ let sender = this.videoSenders.get(peerId) ??
563
+ this.findExistingTransceiverSender(pc, "video");
354
564
  if (sender && typeof sender.replaceTrack === "function") {
565
+ this.videoSenders.set(peerId, sender);
355
566
  await sender.replaceTrack(outgoingTrack);
356
567
  return;
357
568
  }
@@ -9,5 +9,6 @@ export { AvesError } from "./core/AvesError";
9
9
  export type { AvesErrorCode } from "./core/AvesError";
10
10
  export { EventEmitter } from "./core/EventEmitter";
11
11
  export { WebRTCManager } from "./core/WebRTCManager";
12
+ export type { WebRTCManagerOptions } from "./core/WebRTCManager";
12
13
  export { SignalingClient } from "./core/SignalingClient";
13
- export type { Participant, AvesMessage, AvesClientConfig, AvesVideoConstraints, FileTransferOptions, FileTransferInfo, FileTransferProgress, FileTransferResult, LocalAudioState, LocalVideoState, ScreenShareState, ScreenShareSource, JsonObject, JsonPrimitive, JsonValue, SignalingMessage, SignalingErrorCode, SignalingErrorStage, SignalingErrorPayload, JoinRoomResult, ReconnectConfig, } from "./types/types";
14
+ export type { Participant, AvesMessage, AvesClientConfig, AvesConnectionSnapshot, AvesPeerSnapshot, AvesPeerStats, CandidatePairType, CreateRoomOptions, JoinRoomOptions, AvesAudioConstraints, AvesVideoConstraints, ScreenShareOptions, FileTransferConfig, IncomingFileDecision, FileTransferOptions, FileTransferInfo, FileTransferProgress, FileTransferResult, LocalAudioState, LocalVideoState, ScreenShareState, ScreenShareSource, JsonObject, JsonPrimitive, JsonValue, SignalingMessage, SignalingErrorCode, SignalingErrorStage, SignalingErrorPayload, JoinRoomResult, ReconnectConfig, WaitForPeerOptions, } from "./types/types";