@furious.luke/argus-js 0.4.0 → 0.5.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.
- package/README.md +127 -23
- package/dist/index.cjs +1442 -171
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +330 -23
- package/dist/index.d.ts +330 -23
- package/dist/index.js +1441 -171
- package/dist/index.js.map +1 -1
- package/package.json +4 -2
package/dist/index.js
CHANGED
|
@@ -25,11 +25,11 @@ var SignalingChannel = class _SignalingChannel {
|
|
|
25
25
|
ws.onclose = () => ch.onClose?.();
|
|
26
26
|
return ch;
|
|
27
27
|
}
|
|
28
|
-
/** Sends a JSON message
|
|
28
|
+
/** Sends a JSON message when the socket is open and reports whether it was sent. */
|
|
29
29
|
send(msg) {
|
|
30
|
-
if (this.ws.readyState
|
|
31
|
-
|
|
32
|
-
|
|
30
|
+
if (this.ws.readyState !== WebSocket.OPEN) return false;
|
|
31
|
+
this.ws.send(JSON.stringify(msg));
|
|
32
|
+
return true;
|
|
33
33
|
}
|
|
34
34
|
/** Closes the underlying WebSocket. */
|
|
35
35
|
close() {
|
|
@@ -45,30 +45,132 @@ function parseSignal(data) {
|
|
|
45
45
|
}
|
|
46
46
|
|
|
47
47
|
// src/publisher.ts
|
|
48
|
+
function selectGatewayTURNURLs(advertised, policy = "all") {
|
|
49
|
+
if (policy === "all") return advertised;
|
|
50
|
+
const selected = advertised.filter((raw) => {
|
|
51
|
+
let parsed;
|
|
52
|
+
try {
|
|
53
|
+
parsed = new URL(raw);
|
|
54
|
+
} catch {
|
|
55
|
+
return false;
|
|
56
|
+
}
|
|
57
|
+
const transport = (parsed.searchParams.get("transport") ?? "").toLowerCase();
|
|
58
|
+
if (policy === "tls") {
|
|
59
|
+
return parsed.protocol.toLowerCase() === "turns:" && (transport === "" || transport === "tcp");
|
|
60
|
+
}
|
|
61
|
+
return parsed.protocol.toLowerCase() === "turn:" && (transport === "" || transport === "udp");
|
|
62
|
+
});
|
|
63
|
+
if (selected.length === 0) {
|
|
64
|
+
throw new Error(`gateway advertised no TURN URLs for required ${policy} transport`);
|
|
65
|
+
}
|
|
66
|
+
return selected;
|
|
67
|
+
}
|
|
48
68
|
var defaultSignalingReconnectTimeoutMs = 2e4;
|
|
69
|
+
var defaultGatewayHandshakeTimeoutMs = 2e4;
|
|
70
|
+
var defaultPeerConnectionTimeoutMs = 3e4;
|
|
71
|
+
var initialGatewayAttemptTimeoutMs = 3e3;
|
|
49
72
|
var signalingResumeAttemptTimeoutMs = 3e3;
|
|
50
73
|
var signalingResumeMaxBackoffMs = 3e3;
|
|
51
74
|
var senderRestartPauseMs = 100;
|
|
52
75
|
var senderRecoveryWaitMs = 4e3;
|
|
53
76
|
var iceRecoveryWaitMs = 8e3;
|
|
77
|
+
var minimumNegotiationAnswerTimeoutMs = 15e3;
|
|
78
|
+
var negotiationReconnectGraceMs = 5e3;
|
|
79
|
+
var minimumIntentionalTrackEndRetentionMs = 35e3;
|
|
80
|
+
var maxUserTextBytes = 4 * 1024;
|
|
81
|
+
var maxRetainedICECandidates = 64;
|
|
82
|
+
var ReportedPublisherError = class extends Error {
|
|
83
|
+
constructor(message, fatal = false) {
|
|
84
|
+
super(message);
|
|
85
|
+
this.fatal = fatal;
|
|
86
|
+
}
|
|
87
|
+
fatal;
|
|
88
|
+
};
|
|
89
|
+
var NegotiationTimeoutError = class extends Error {
|
|
90
|
+
};
|
|
91
|
+
var SenderRestoreError = class extends Error {
|
|
92
|
+
};
|
|
93
|
+
var PublisherStoppedError = class extends Error {
|
|
94
|
+
};
|
|
54
95
|
var Publisher = class {
|
|
55
96
|
opts;
|
|
56
97
|
sig = null;
|
|
57
98
|
pc = null;
|
|
58
99
|
hasAnswer = false;
|
|
59
100
|
pendingRemoteCandidates = [];
|
|
60
|
-
|
|
101
|
+
// Setting a local description starts ICE gathering. Candidates may therefore
|
|
102
|
+
// arrive before the corresponding offer has crossed the signaling socket.
|
|
103
|
+
// Hold them until sendOffer confirms that the offer was sent, then trickle
|
|
104
|
+
// them in order. This keeps startup fast without allowing candidate/offer
|
|
105
|
+
// reordering at the media server.
|
|
106
|
+
pendingLocalCandidates = [];
|
|
107
|
+
localCandidateOfferSent = false;
|
|
108
|
+
// WebSocket.send() only proves local queueing. Retain the current ICE
|
|
109
|
+
// generation so a replacement signaling socket can replay candidates whose
|
|
110
|
+
// delivery on the old socket was ambiguous.
|
|
111
|
+
retainedLocalCandidates = [];
|
|
112
|
+
retainedLocalCandidateKeys = /* @__PURE__ */ new Set();
|
|
113
|
+
localCandidateGeneration = null;
|
|
114
|
+
// Both peers replay after reconnect. Receiving the same candidate must be
|
|
115
|
+
// idempotent, whether it is still buffered behind an answer or already
|
|
116
|
+
// applied to the peer connection.
|
|
117
|
+
remoteCandidateKeys = /* @__PURE__ */ new Set();
|
|
118
|
+
remoteCandidateOrder = [];
|
|
119
|
+
remoteCandidateGeneration = null;
|
|
61
120
|
readToken = null;
|
|
62
121
|
gatewayURL = null;
|
|
122
|
+
lastReportedICEPath = null;
|
|
123
|
+
watchedICETransports = /* @__PURE__ */ new WeakSet();
|
|
63
124
|
stopped = true;
|
|
125
|
+
// Every start/stop boundary advances lifecycleGeneration. Async work captures
|
|
126
|
+
// the generation it belongs to and may never mutate or terminate a later run.
|
|
127
|
+
lifecycleGeneration = 0;
|
|
128
|
+
runAbort = null;
|
|
129
|
+
peerConnectionTimer = null;
|
|
64
130
|
reconnecting = false;
|
|
65
131
|
reconnectGeneration = 0;
|
|
66
132
|
resumeSocket = null;
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
133
|
+
signalingWaiters = /* @__PURE__ */ new Set();
|
|
134
|
+
pendingOffer = null;
|
|
135
|
+
recoverySequence = 0;
|
|
136
|
+
recoveryStates = /* @__PURE__ */ new Map();
|
|
137
|
+
// ICE restart applies to the whole peer connection. Keep one attempt shared
|
|
138
|
+
// by every track currently recovering so simultaneous camera/screen stalls do
|
|
139
|
+
// not create duplicate ICE offers.
|
|
140
|
+
iceRestartSequence = 0;
|
|
141
|
+
iceRestartAttempt = null;
|
|
71
142
|
trackEndHandlers = /* @__PURE__ */ new Map();
|
|
143
|
+
// published is the source of truth for the live video tracks and their logical
|
|
144
|
+
// types. It drives the track labels sent on every offer, per-track recovery
|
|
145
|
+
// reporting, and add/remove of individual tracks. At most one track per type is
|
|
146
|
+
// kept (publishing a second track of a type replaces the first).
|
|
147
|
+
published = /* @__PURE__ */ new Map();
|
|
148
|
+
publishedStreams = /* @__PURE__ */ new Map();
|
|
149
|
+
// Own the active sender for each logical type. Active source replacement uses
|
|
150
|
+
// replaceTrack on that sender. Unpublish removes the mapping because addTrack
|
|
151
|
+
// may later reuse any compatible inactive transceiver, not necessarily the one
|
|
152
|
+
// that previously carried the same logical type.
|
|
153
|
+
typeSenders = /* @__PURE__ */ new Map();
|
|
154
|
+
// intentionalTrackEnds holds physical track ids removed by publish/unpublish
|
|
155
|
+
// whose server-side `media_track_ended` has not yet arrived. Correlating by id
|
|
156
|
+
// keeps a delayed end for an old screen track from being mistaken for failure
|
|
157
|
+
// of a newly-published screen track.
|
|
158
|
+
intentionalTrackEnds = /* @__PURE__ */ new Map();
|
|
159
|
+
// negotiationChain serializes every offer/answer exchange, including recovery.
|
|
160
|
+
// User operations do not resolve until their answer is applied, so no caller
|
|
161
|
+
// or recovery timer can create a second offer while one is outstanding.
|
|
162
|
+
negotiationChain = Promise.resolve();
|
|
163
|
+
// pendingAnswer resolves the one in-flight negotiation once its matching answer
|
|
164
|
+
// arrives, or rejects it on timeout/teardown. All offers, including recovery,
|
|
165
|
+
// pass through negotiationChain, so this slot is never intentionally replaced.
|
|
166
|
+
pendingAnswer = null;
|
|
167
|
+
// negotiationSeq stamps each offer with a monotonically increasing id.
|
|
168
|
+
negotiationSeq = 0;
|
|
169
|
+
textChannel = null;
|
|
170
|
+
speechEnabled = false;
|
|
171
|
+
speechPending = false;
|
|
172
|
+
speechTransceiver = null;
|
|
173
|
+
microphoneTransceiver = null;
|
|
72
174
|
constructor(opts) {
|
|
73
175
|
this.opts = opts;
|
|
74
176
|
}
|
|
@@ -84,96 +186,328 @@ var Publisher = class {
|
|
|
84
186
|
get selectedGatewayURL() {
|
|
85
187
|
return this.gatewayURL;
|
|
86
188
|
}
|
|
189
|
+
/** Requests the persistent outbound `speech` track. This is explicit user
|
|
190
|
+
* opt-in and renegotiates only once; the track remains silent between turns. */
|
|
191
|
+
async enableSpeech() {
|
|
192
|
+
if (this.speechEnabled) return;
|
|
193
|
+
await this.enqueueNegotiation(() => {
|
|
194
|
+
const pc = this.pc;
|
|
195
|
+
if (!pc || this.speechEnabled || this.speechPending) return false;
|
|
196
|
+
if (!this.speechTransceiver) {
|
|
197
|
+
this.speechTransceiver = pc.addTransceiver("audio", { direction: "recvonly" });
|
|
198
|
+
} else {
|
|
199
|
+
this.speechTransceiver.direction = "recvonly";
|
|
200
|
+
}
|
|
201
|
+
this.speechPending = true;
|
|
202
|
+
return {
|
|
203
|
+
commit: () => {
|
|
204
|
+
this.speechPending = false;
|
|
205
|
+
this.speechEnabled = true;
|
|
206
|
+
},
|
|
207
|
+
rollback: () => {
|
|
208
|
+
this.speechPending = false;
|
|
209
|
+
}
|
|
210
|
+
};
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
/** Sends typed input over the reliable ordered Argus text channel. */
|
|
214
|
+
sendUserText(messageId, text) {
|
|
215
|
+
if (!messageId || !text.trim()) throw new Error("messageId and text are required");
|
|
216
|
+
if (new TextEncoder().encode(text).byteLength > maxUserTextBytes) {
|
|
217
|
+
throw new Error("text must not exceed 4 KiB");
|
|
218
|
+
}
|
|
219
|
+
if (!this.textChannel || this.textChannel.readyState !== "open") {
|
|
220
|
+
throw new Error("Argus text channel is not open");
|
|
221
|
+
}
|
|
222
|
+
this.textChannel.send(JSON.stringify({ type: "user_text", message_id: messageId, text }));
|
|
223
|
+
}
|
|
87
224
|
/**
|
|
88
225
|
* Starts the publisher: races all gateways to find the fastest, completes
|
|
89
226
|
* the two-phase handshake, creates the peer connection, and sends the SDP
|
|
90
227
|
* offer. Resolves when the offer has been sent (not when ICE completes —
|
|
91
228
|
* use onConnected for that).
|
|
229
|
+
*
|
|
230
|
+
* The stream's single video track is published under `type` (default `"camera"`),
|
|
231
|
+
* declared to the server so reads and change notifications can address them by
|
|
232
|
+
* type. Add or remove further tracks live with {@link Publisher.publish} and
|
|
233
|
+
* {@link Publisher.unpublish}.
|
|
92
234
|
*/
|
|
93
|
-
async start(stream) {
|
|
235
|
+
async start(stream, type = "camera") {
|
|
236
|
+
const track = this.requireSingleVideoTrack(stream);
|
|
237
|
+
await this.startSession({ track, stream, type, watchForRecovery: true });
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* Starts the publisher with a microphone track and no video — a fully valid
|
|
241
|
+
* audio-only stream, the natural starting point for a voice agent. Exactly one
|
|
242
|
+
* audio track must be present in `stream`. Video can be added later with
|
|
243
|
+
* {@link Publisher.publish}; a stream carries at most one microphone track.
|
|
244
|
+
*
|
|
245
|
+
* Like {@link Publisher.start} it races the gateways, completes the handshake,
|
|
246
|
+
* and sends the offer; it resolves once the offer is sent. The microphone is not
|
|
247
|
+
* subject to the video recovery ladder — a mic that stops simply ends
|
|
248
|
+
* transcription for the stream.
|
|
249
|
+
*/
|
|
250
|
+
async startAudioOnly(stream) {
|
|
251
|
+
const track = this.requireSingleAudioTrack(stream);
|
|
252
|
+
await this.startSession({ track, stream, type: "audio", watchForRecovery: false });
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* Starts a WebRTC session with only the ordered `argus.text` data channel.
|
|
256
|
+
* This is the natural entry point for a typed, text-only agent: it requests no
|
|
257
|
+
* camera or microphone permission and publishes no media. Camera, screen, or
|
|
258
|
+
* microphone tracks can be added later with {@link Publisher.publish} or
|
|
259
|
+
* {@link Publisher.publishMicrophone}; {@link Publisher.enableSpeech} can add
|
|
260
|
+
* the optional inbound speech track independently.
|
|
261
|
+
*/
|
|
262
|
+
async startTextOnly() {
|
|
263
|
+
await this.startSession(null);
|
|
264
|
+
}
|
|
265
|
+
/**
|
|
266
|
+
* Shared startup for video, audio-only, and text-only entry points: race the
|
|
267
|
+
* gateways, build the peer connection and text channel, optionally add an
|
|
268
|
+
* initial media track, and send the first offer.
|
|
269
|
+
*/
|
|
270
|
+
async startSession(initialTrack) {
|
|
271
|
+
if (!this.stopped || this.pc || this.published.size > 0) {
|
|
272
|
+
throw new Error("publisher already started");
|
|
273
|
+
}
|
|
274
|
+
const trackKind = initialTrack ? initialTrack.type === "audio" ? "audio" : "video" : null;
|
|
275
|
+
const generation = ++this.lifecycleGeneration;
|
|
276
|
+
const runAbort = new AbortController();
|
|
277
|
+
this.runAbort = runAbort;
|
|
278
|
+
this.negotiationChain = Promise.resolve();
|
|
94
279
|
this.stopped = false;
|
|
95
|
-
this.
|
|
96
|
-
this.
|
|
97
|
-
this.
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
this.
|
|
102
|
-
}
|
|
103
|
-
const iceServers = [...this.opts.iceServers ?? []];
|
|
104
|
-
if (readyInfo.turn_urls && readyInfo.turn_urls.length > 0) {
|
|
105
|
-
iceServers.push({
|
|
106
|
-
urls: readyInfo.turn_urls,
|
|
107
|
-
username: readyInfo.turn_username,
|
|
108
|
-
credential: readyInfo.turn_credential
|
|
109
|
-
});
|
|
280
|
+
this.recoveryStates.clear();
|
|
281
|
+
this.typeSenders.clear();
|
|
282
|
+
this.lastReportedICEPath = null;
|
|
283
|
+
this.watchedICETransports = /* @__PURE__ */ new WeakSet();
|
|
284
|
+
if (initialTrack) {
|
|
285
|
+
this.published.set(initialTrack.track, initialTrack.type);
|
|
286
|
+
this.publishedStreams.set(initialTrack.track, initialTrack.stream);
|
|
110
287
|
}
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
this.
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
288
|
+
let startupWS = null;
|
|
289
|
+
try {
|
|
290
|
+
const { ws, readyInfo, gatewayURL } = await this.raceGateways(runAbort.signal);
|
|
291
|
+
startupWS = ws;
|
|
292
|
+
this.assertActiveRun(generation);
|
|
293
|
+
if (initialTrack && trackKind) this.requireLiveTrack(initialTrack.track, trackKind);
|
|
294
|
+
this.gatewayURL = gatewayURL;
|
|
295
|
+
if (readyInfo.read_token) {
|
|
296
|
+
this.readToken = readyInfo.read_token;
|
|
297
|
+
}
|
|
298
|
+
const iceServers = [...this.opts.iceServers ?? []];
|
|
299
|
+
const advertisedTURNURLs = readyInfo.turn_urls ?? [];
|
|
300
|
+
if (advertisedTURNURLs.length > 0 || this.opts.turnTransportPolicy !== void 0) {
|
|
301
|
+
const turnURLs = selectGatewayTURNURLs(
|
|
302
|
+
advertisedTURNURLs,
|
|
303
|
+
this.opts.turnTransportPolicy
|
|
304
|
+
);
|
|
305
|
+
if (turnURLs.length > 0) {
|
|
306
|
+
iceServers.push({
|
|
307
|
+
urls: turnURLs,
|
|
308
|
+
username: readyInfo.turn_username,
|
|
309
|
+
credential: readyInfo.turn_credential
|
|
310
|
+
});
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
const pc = new RTCPeerConnection({
|
|
314
|
+
iceServers,
|
|
315
|
+
iceTransportPolicy: this.opts.iceTransportPolicy
|
|
121
316
|
});
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
this.
|
|
317
|
+
this.pc = pc;
|
|
318
|
+
this.textChannel = pc.createDataChannel("argus.text", { ordered: true });
|
|
319
|
+
this.textChannel.onmessage = (event) => this.handleTextMessage(event.data);
|
|
320
|
+
pc.ontrack = (event) => {
|
|
321
|
+
if (!this.isActiveRun(generation, pc) || event.track.kind !== "audio") return;
|
|
322
|
+
this.opts.callbacks?.onSpeechTrack?.(event.track, event.streams);
|
|
323
|
+
};
|
|
324
|
+
pc.onicecandidate = (ev) => {
|
|
325
|
+
if (!this.isActiveRun(generation, pc) || !ev.candidate) return;
|
|
326
|
+
this.handleLocalICECandidate(ev.candidate);
|
|
327
|
+
};
|
|
328
|
+
pc.onconnectionstatechange = () => {
|
|
329
|
+
if (!this.isActiveRun(generation, pc)) return;
|
|
330
|
+
const state = pc.connectionState;
|
|
331
|
+
if (state) this.opts.callbacks?.onConnectionStateChange?.(state);
|
|
332
|
+
if (state === "connected") {
|
|
333
|
+
this.clearPeerConnectionTimeout();
|
|
334
|
+
void this.reportSelectedICEPath(pc);
|
|
335
|
+
this.opts.callbacks?.onConnected?.();
|
|
336
|
+
} else if (state === "failed") {
|
|
337
|
+
this.clearPeerConnectionTimeout();
|
|
338
|
+
this.terminateWithError(new Error("WebRTC connection failed"), true, generation);
|
|
339
|
+
}
|
|
340
|
+
};
|
|
341
|
+
if (initialTrack) {
|
|
342
|
+
const sender = initialTrack.type === "audio" ? this.addMicrophoneTrack(pc, initialTrack.track, initialTrack.stream) : pc.addTrack(initialTrack.track, initialTrack.stream);
|
|
343
|
+
this.typeSenders.set(
|
|
344
|
+
initialTrack.type,
|
|
345
|
+
sender
|
|
346
|
+
);
|
|
149
347
|
}
|
|
348
|
+
this.installSignaling(ws);
|
|
349
|
+
startupWS = null;
|
|
350
|
+
const offer = await pc.createOffer();
|
|
351
|
+
this.assertActiveRun(generation, pc);
|
|
352
|
+
if (initialTrack && trackKind) this.requireLiveTrack(initialTrack.track, trackKind);
|
|
353
|
+
this.beginLocalCandidateBatch();
|
|
354
|
+
await pc.setLocalDescription(offer);
|
|
355
|
+
this.assertActiveRun(generation, pc);
|
|
356
|
+
if (initialTrack && trackKind) this.requireLiveTrack(initialTrack.track, trackKind);
|
|
357
|
+
const local = pc.localDescription;
|
|
358
|
+
if (!local) throw new Error("local description missing");
|
|
359
|
+
const id = this.nextNegotiationId();
|
|
360
|
+
const { answered } = await this.sendOffer({
|
|
361
|
+
type: "offer",
|
|
362
|
+
sdp: local.sdp,
|
|
363
|
+
sdp_type: "offer",
|
|
364
|
+
negotiation_id: id,
|
|
365
|
+
tracks: this.buildTrackLabels(),
|
|
366
|
+
speech_enabled: this.speechEnabled || this.speechPending || void 0
|
|
367
|
+
});
|
|
368
|
+
this.releaseLocalCandidateBatch();
|
|
369
|
+
this.assertActiveRun(generation, pc);
|
|
370
|
+
this.armPeerConnectionTimeout(generation, pc);
|
|
371
|
+
if (initialTrack && trackKind) this.requireLiveTrack(initialTrack.track, trackKind);
|
|
372
|
+
if (initialTrack?.watchForRecovery) this.watchTrack(initialTrack.track);
|
|
373
|
+
else if (initialTrack) this.watchMicrophone(initialTrack.track);
|
|
374
|
+
const initial = answered.then(async (sdp) => {
|
|
375
|
+
this.assertActiveRun(generation, pc);
|
|
376
|
+
await pc.setRemoteDescription(
|
|
377
|
+
new RTCSessionDescription({ type: "answer", sdp })
|
|
378
|
+
);
|
|
379
|
+
this.assertActiveRun(generation, pc);
|
|
380
|
+
this.applyAnswered(pc);
|
|
381
|
+
});
|
|
382
|
+
this.negotiationChain = initial.catch((err) => {
|
|
383
|
+
if (this.isActiveRun(generation, pc)) {
|
|
384
|
+
const reported = err instanceof Error ? err : new Error(String(err));
|
|
385
|
+
const alreadyReported = err instanceof ReportedPublisherError && err.fatal;
|
|
386
|
+
this.terminateWithError(reported, !alreadyReported, generation);
|
|
387
|
+
}
|
|
388
|
+
throw err;
|
|
389
|
+
});
|
|
390
|
+
void this.negotiationChain.catch(() => {
|
|
391
|
+
});
|
|
392
|
+
} catch (err) {
|
|
393
|
+
startupWS?.close();
|
|
394
|
+
if (generation === this.lifecycleGeneration) this.stop();
|
|
395
|
+
throw err;
|
|
150
396
|
}
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
397
|
+
}
|
|
398
|
+
/**
|
|
399
|
+
* Adds the single video track from `stream` to the live session under `type`,
|
|
400
|
+
* renegotiating so the media server begins ingesting them. Use this to add a
|
|
401
|
+
* track after {@link Publisher.start} — for example to begin a screen share on
|
|
402
|
+
* top of a live camera.
|
|
403
|
+
*
|
|
404
|
+
* Exactly one video track must be present in `stream`. If a track of `type` is already
|
|
405
|
+
* live it is removed and replaced (a "screen" published while another "screen"
|
|
406
|
+
* is live supersedes it).
|
|
407
|
+
*/
|
|
408
|
+
async publish(stream, type) {
|
|
409
|
+
if (!this.pc) throw new Error("publisher not started");
|
|
410
|
+
const track = this.requireSingleVideoTrack(stream);
|
|
411
|
+
await this.enqueueNegotiation(() => this.stagePublish(track, stream, type));
|
|
412
|
+
}
|
|
413
|
+
/**
|
|
414
|
+
* Removes the live track(s) of the given type, stops their local capture, and
|
|
415
|
+
* renegotiates so the media server ends ingestion for that track. A no-op if
|
|
416
|
+
* no track of that type is published.
|
|
417
|
+
*/
|
|
418
|
+
async unpublish(type) {
|
|
419
|
+
if (!this.pc) throw new Error("publisher not started");
|
|
420
|
+
await this.enqueueNegotiation(() => {
|
|
421
|
+
if (this.tracksOfType(type).length === 0) {
|
|
422
|
+
return false;
|
|
423
|
+
}
|
|
424
|
+
return this.stageUnpublish(type);
|
|
425
|
+
});
|
|
426
|
+
}
|
|
427
|
+
/**
|
|
428
|
+
* Adds the microphone (audio) track from `stream` to the live session and
|
|
429
|
+
* renegotiates, so the media server begins transcribing it. Exactly one audio
|
|
430
|
+
* track must be present in `stream`. Publishing a microphone while one is
|
|
431
|
+
* already live replaces it.
|
|
432
|
+
*
|
|
433
|
+
* The audio track feeds server-side speech-to-text; its transcripts are
|
|
434
|
+
* delivered to the customer server over the change-notification subscription,
|
|
435
|
+
* not to the browser. Audio is not subject to the video recovery ladder — a
|
|
436
|
+
* mic that stops is simply removed.
|
|
437
|
+
*/
|
|
438
|
+
async publishMicrophone(stream) {
|
|
439
|
+
if (!this.pc) throw new Error("publisher not started");
|
|
440
|
+
const track = this.requireSingleAudioTrack(stream);
|
|
441
|
+
await this.enqueueNegotiation(() => this.stagePublishAudio(track, stream));
|
|
442
|
+
}
|
|
443
|
+
/**
|
|
444
|
+
* Removes the live microphone track, stops its local capture, and
|
|
445
|
+
* renegotiates so the media server ends transcription. A no-op if no
|
|
446
|
+
* microphone is published.
|
|
447
|
+
*/
|
|
448
|
+
async unpublishMicrophone() {
|
|
449
|
+
if (!this.pc) throw new Error("publisher not started");
|
|
450
|
+
await this.enqueueNegotiation(() => {
|
|
451
|
+
if (this.tracksOfType("audio").length === 0) return false;
|
|
452
|
+
return this.stageUnpublish("audio");
|
|
453
|
+
});
|
|
454
|
+
}
|
|
455
|
+
/**
|
|
456
|
+
* Replaces the published track of a single type with a new stream and
|
|
457
|
+
* renegotiates in place — e.g. to swap to a freshly reacquired screen share
|
|
458
|
+
* after {@link PublisherCallbacks.onRecoveryRequired}. Defaults to the
|
|
459
|
+
* `"camera"` type. This is a convenience over {@link Publisher.publish}, which
|
|
460
|
+
* it delegates to (publishing one track per type replaces any existing track
|
|
461
|
+
* of that type).
|
|
462
|
+
*/
|
|
463
|
+
async replaceStream(stream, type = "camera") {
|
|
464
|
+
await this.publish(stream, type);
|
|
157
465
|
}
|
|
158
466
|
/** Stops publishing and tears down the peer connection. */
|
|
159
467
|
stop() {
|
|
468
|
+
this.lifecycleGeneration++;
|
|
469
|
+
this.runAbort?.abort();
|
|
470
|
+
this.runAbort = null;
|
|
471
|
+
this.clearPeerConnectionTimeout();
|
|
160
472
|
this.stopped = true;
|
|
161
|
-
this.
|
|
473
|
+
this.cancelAllMediaRecovery();
|
|
162
474
|
this.reconnectGeneration++;
|
|
163
475
|
this.reconnecting = false;
|
|
164
476
|
this.resumeSocket?.close();
|
|
165
477
|
this.resumeSocket = null;
|
|
166
478
|
this.sig?.close();
|
|
167
479
|
this.sig = null;
|
|
480
|
+
this.rejectSignalingWaiters(new Error("publisher stopped"));
|
|
168
481
|
this.unwatchStreamTracks();
|
|
169
|
-
this.
|
|
170
|
-
this.
|
|
482
|
+
this.stopPublishedTracks();
|
|
483
|
+
this.clearIntentionalTrackEnds();
|
|
484
|
+
this.rejectPendingAnswer(new Error("publisher stopped"));
|
|
485
|
+
this.pendingOffer = null;
|
|
171
486
|
this.pc?.close();
|
|
172
487
|
this.pc = null;
|
|
488
|
+
this.textChannel = null;
|
|
489
|
+
this.speechEnabled = false;
|
|
490
|
+
this.speechPending = false;
|
|
491
|
+
this.speechTransceiver = null;
|
|
492
|
+
this.microphoneTransceiver = null;
|
|
493
|
+
this.typeSenders.clear();
|
|
173
494
|
this.hasAnswer = false;
|
|
174
495
|
this.pendingRemoteCandidates = [];
|
|
496
|
+
this.pendingLocalCandidates = [];
|
|
497
|
+
this.localCandidateOfferSent = false;
|
|
498
|
+
this.clearRetainedICECandidates();
|
|
175
499
|
this.readToken = null;
|
|
176
500
|
this.gatewayURL = null;
|
|
501
|
+
this.lastReportedICEPath = null;
|
|
502
|
+
}
|
|
503
|
+
// rejectPendingAnswer fails any in-flight negotiation so a queued
|
|
504
|
+
// publish()/unpublish() rejects promptly instead of hanging until timeout.
|
|
505
|
+
rejectPendingAnswer(err) {
|
|
506
|
+
const pending = this.pendingAnswer;
|
|
507
|
+
if (pending) {
|
|
508
|
+
this.pendingAnswer = null;
|
|
509
|
+
pending.reject(err);
|
|
510
|
+
}
|
|
177
511
|
}
|
|
178
512
|
/** Returns the current RTCPeerConnection, or null if not started. */
|
|
179
513
|
get peerConnection() {
|
|
@@ -186,7 +520,7 @@ var Publisher = class {
|
|
|
186
520
|
// -------------------------------------------------------------------------
|
|
187
521
|
// Private helpers
|
|
188
522
|
// -------------------------------------------------------------------------
|
|
189
|
-
raceGateways() {
|
|
523
|
+
raceGateways(signal) {
|
|
190
524
|
return new Promise((resolve, reject) => {
|
|
191
525
|
const { gatewayURLs, token } = this.opts;
|
|
192
526
|
if (gatewayURLs.length === 0) {
|
|
@@ -194,9 +528,21 @@ var Publisher = class {
|
|
|
194
528
|
return;
|
|
195
529
|
}
|
|
196
530
|
const sockets = [];
|
|
531
|
+
const attemptTimers = /* @__PURE__ */ new Map();
|
|
197
532
|
let settled = false;
|
|
533
|
+
let timeoutTimer = null;
|
|
534
|
+
const clearTimeoutTimer = () => {
|
|
535
|
+
if (timeoutTimer !== null) clearTimeout(timeoutTimer);
|
|
536
|
+
timeoutTimer = null;
|
|
537
|
+
};
|
|
538
|
+
const clearAttemptTimer = (socket) => {
|
|
539
|
+
const timer = attemptTimers.get(socket);
|
|
540
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
541
|
+
attemptTimers.delete(socket);
|
|
542
|
+
};
|
|
198
543
|
const closeAll = (except) => {
|
|
199
544
|
for (const s of sockets) {
|
|
545
|
+
clearAttemptTimer(s);
|
|
200
546
|
if (s !== except) {
|
|
201
547
|
s.onmessage = null;
|
|
202
548
|
s.onerror = null;
|
|
@@ -209,39 +555,107 @@ var Publisher = class {
|
|
|
209
555
|
if (settled) return;
|
|
210
556
|
if (sockets.every((s) => s.readyState === WebSocket.CLOSED || s.readyState === WebSocket.CLOSING)) {
|
|
211
557
|
settled = true;
|
|
558
|
+
clearTimeoutTimer();
|
|
559
|
+
signal.removeEventListener("abort", abort);
|
|
212
560
|
reject(new Error("all gateways failed to connect"));
|
|
213
561
|
}
|
|
214
562
|
};
|
|
215
|
-
|
|
563
|
+
const abort = () => {
|
|
564
|
+
if (settled) return;
|
|
565
|
+
settled = true;
|
|
566
|
+
clearTimeoutTimer();
|
|
567
|
+
closeAll();
|
|
568
|
+
reject(new PublisherStoppedError("publisher stopped"));
|
|
569
|
+
};
|
|
570
|
+
if (signal.aborted) {
|
|
571
|
+
abort();
|
|
572
|
+
return;
|
|
573
|
+
}
|
|
574
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
575
|
+
const timeoutMs = Math.max(
|
|
576
|
+
0,
|
|
577
|
+
this.opts.gatewayHandshakeTimeoutMs ?? defaultGatewayHandshakeTimeoutMs
|
|
578
|
+
);
|
|
579
|
+
timeoutTimer = setTimeout(() => {
|
|
580
|
+
if (settled) return;
|
|
581
|
+
settled = true;
|
|
582
|
+
signal.removeEventListener("abort", abort);
|
|
583
|
+
closeAll();
|
|
584
|
+
reject(new Error(`gateway handshake timed out after ${timeoutMs}ms`));
|
|
585
|
+
}, timeoutMs);
|
|
586
|
+
const openGateway = (gatewayURL) => {
|
|
587
|
+
if (settled) return;
|
|
216
588
|
const u = new URL(gatewayURL);
|
|
217
589
|
u.searchParams.set("token", token);
|
|
218
590
|
const ws = new WebSocket(u.toString());
|
|
219
591
|
sockets.push(ws);
|
|
220
592
|
let accepted = false;
|
|
593
|
+
const attemptTimer = setTimeout(() => {
|
|
594
|
+
attemptTimers.delete(ws);
|
|
595
|
+
if (settled || accepted) return;
|
|
596
|
+
ws.onmessage = null;
|
|
597
|
+
ws.onerror = null;
|
|
598
|
+
ws.onclose = null;
|
|
599
|
+
ws.close();
|
|
600
|
+
try {
|
|
601
|
+
openGateway(gatewayURL);
|
|
602
|
+
} catch (err) {
|
|
603
|
+
settled = true;
|
|
604
|
+
clearTimeoutTimer();
|
|
605
|
+
signal.removeEventListener("abort", abort);
|
|
606
|
+
closeAll();
|
|
607
|
+
reject(err);
|
|
608
|
+
}
|
|
609
|
+
}, initialGatewayAttemptTimeoutMs);
|
|
610
|
+
attemptTimers.set(ws, attemptTimer);
|
|
221
611
|
ws.onmessage = (ev) => {
|
|
222
612
|
if (settled) return;
|
|
223
613
|
try {
|
|
224
614
|
const msg = JSON.parse(ev.data);
|
|
225
615
|
if (!accepted && msg.type === "accepted") {
|
|
226
616
|
accepted = true;
|
|
617
|
+
clearAttemptTimer(ws);
|
|
227
618
|
ws.send(JSON.stringify({ type: "proceed" }));
|
|
228
619
|
} else if (accepted && msg.type === "ready") {
|
|
229
620
|
settled = true;
|
|
621
|
+
clearTimeoutTimer();
|
|
622
|
+
signal.removeEventListener("abort", abort);
|
|
230
623
|
closeAll(ws);
|
|
231
624
|
resolve({ ws, readyInfo: msg, gatewayURL });
|
|
232
625
|
}
|
|
233
626
|
} catch {
|
|
234
627
|
}
|
|
235
628
|
};
|
|
236
|
-
ws.onerror = () =>
|
|
237
|
-
|
|
629
|
+
ws.onerror = () => {
|
|
630
|
+
clearAttemptTimer(ws);
|
|
631
|
+
checkAllFailed();
|
|
632
|
+
};
|
|
633
|
+
ws.onclose = () => {
|
|
634
|
+
clearAttemptTimer(ws);
|
|
635
|
+
checkAllFailed();
|
|
636
|
+
};
|
|
637
|
+
};
|
|
638
|
+
try {
|
|
639
|
+
for (const gatewayURL of gatewayURLs) {
|
|
640
|
+
openGateway(gatewayURL);
|
|
641
|
+
}
|
|
642
|
+
} catch (err) {
|
|
643
|
+
settled = true;
|
|
644
|
+
clearTimeoutTimer();
|
|
645
|
+
signal.removeEventListener("abort", abort);
|
|
646
|
+
closeAll();
|
|
647
|
+
reject(err);
|
|
238
648
|
}
|
|
239
649
|
});
|
|
240
650
|
}
|
|
241
651
|
installSignaling(ws) {
|
|
242
652
|
const channel = SignalingChannel.wrap(ws);
|
|
653
|
+
const generation = this.lifecycleGeneration;
|
|
243
654
|
this.sig = channel;
|
|
244
|
-
channel.onMessage = (msg) =>
|
|
655
|
+
channel.onMessage = (msg) => {
|
|
656
|
+
if (this.sig !== channel || !this.isActiveRun(generation)) return;
|
|
657
|
+
this.handleSignal(msg);
|
|
658
|
+
};
|
|
245
659
|
channel.onClose = () => {
|
|
246
660
|
if (this.sig !== channel || this.stopped) return;
|
|
247
661
|
this.sig = null;
|
|
@@ -249,8 +663,82 @@ var Publisher = class {
|
|
|
249
663
|
};
|
|
250
664
|
channel.onError = () => {
|
|
251
665
|
};
|
|
666
|
+
this.resolveSignalingWaiters(channel);
|
|
667
|
+
const pending = this.pendingOffer;
|
|
668
|
+
if (pending?.sent) {
|
|
669
|
+
try {
|
|
670
|
+
channel.send(pending.message);
|
|
671
|
+
} catch {
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
if (this.localCandidateOfferSent) {
|
|
675
|
+
for (const candidate of this.retainedLocalCandidates) {
|
|
676
|
+
try {
|
|
677
|
+
channel.send(candidate);
|
|
678
|
+
} catch {
|
|
679
|
+
break;
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
}
|
|
252
683
|
return channel;
|
|
253
684
|
}
|
|
685
|
+
awaitSignaling() {
|
|
686
|
+
if (this.sig) return Promise.resolve(this.sig);
|
|
687
|
+
if (this.stopped) return Promise.reject(new Error("publisher stopped"));
|
|
688
|
+
return new Promise((resolve, reject) => {
|
|
689
|
+
this.signalingWaiters.add({ resolve, reject });
|
|
690
|
+
});
|
|
691
|
+
}
|
|
692
|
+
resolveSignalingWaiters(channel) {
|
|
693
|
+
const waiters = [...this.signalingWaiters];
|
|
694
|
+
this.signalingWaiters.clear();
|
|
695
|
+
for (const waiter of waiters) waiter.resolve(channel);
|
|
696
|
+
}
|
|
697
|
+
rejectSignalingWaiters(err) {
|
|
698
|
+
const waiters = [...this.signalingWaiters];
|
|
699
|
+
this.signalingWaiters.clear();
|
|
700
|
+
for (const waiter of waiters) waiter.reject(err);
|
|
701
|
+
}
|
|
702
|
+
async sendWhenSignalingAvailable(msg) {
|
|
703
|
+
while (!this.stopped) {
|
|
704
|
+
const channel = await this.awaitSignaling();
|
|
705
|
+
try {
|
|
706
|
+
if (channel.send(msg)) return;
|
|
707
|
+
} catch {
|
|
708
|
+
}
|
|
709
|
+
if (this.sig === channel) {
|
|
710
|
+
this.sig = null;
|
|
711
|
+
void this.resumeSignaling();
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
throw new Error("publisher stopped");
|
|
715
|
+
}
|
|
716
|
+
async sendOffer(message) {
|
|
717
|
+
if (this.pendingOffer) {
|
|
718
|
+
throw new Error("another negotiation offer is already pending");
|
|
719
|
+
}
|
|
720
|
+
const pending = { message, sent: false };
|
|
721
|
+
this.pendingOffer = pending;
|
|
722
|
+
try {
|
|
723
|
+
await this.sendWhenSignalingAvailable(message);
|
|
724
|
+
pending.sent = true;
|
|
725
|
+
const id = message.negotiation_id;
|
|
726
|
+
if (!id) throw new Error("negotiation offer is missing an id");
|
|
727
|
+
const answered = this.awaitAnswer(id);
|
|
728
|
+
void answered.then(
|
|
729
|
+
() => {
|
|
730
|
+
if (this.pendingOffer === pending) this.pendingOffer = null;
|
|
731
|
+
},
|
|
732
|
+
() => {
|
|
733
|
+
if (this.pendingOffer === pending) this.pendingOffer = null;
|
|
734
|
+
}
|
|
735
|
+
);
|
|
736
|
+
return { answered };
|
|
737
|
+
} catch (err) {
|
|
738
|
+
if (this.pendingOffer === pending) this.pendingOffer = null;
|
|
739
|
+
throw err;
|
|
740
|
+
}
|
|
741
|
+
}
|
|
254
742
|
async resumeSignaling() {
|
|
255
743
|
if (this.reconnecting || this.stopped) return;
|
|
256
744
|
if (!this.gatewayURL || !this.readToken) {
|
|
@@ -326,47 +814,88 @@ var Publisher = class {
|
|
|
326
814
|
wait(ms) {
|
|
327
815
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
328
816
|
}
|
|
329
|
-
|
|
817
|
+
isActiveRun(generation, pc) {
|
|
818
|
+
return generation === this.lifecycleGeneration && !this.stopped && !this.runAbort?.signal.aborted && (!pc || this.pc === pc);
|
|
819
|
+
}
|
|
820
|
+
assertActiveRun(generation, pc) {
|
|
821
|
+
if (!this.isActiveRun(generation, pc)) {
|
|
822
|
+
throw new PublisherStoppedError("publisher stopped");
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
armPeerConnectionTimeout(generation, pc) {
|
|
826
|
+
this.clearPeerConnectionTimeout();
|
|
827
|
+
if (pc.connectionState === "connected") return;
|
|
828
|
+
const timeoutMs = Math.max(
|
|
829
|
+
0,
|
|
830
|
+
this.opts.peerConnectionTimeoutMs ?? defaultPeerConnectionTimeoutMs
|
|
831
|
+
);
|
|
832
|
+
const timer = setTimeout(() => {
|
|
833
|
+
if (this.peerConnectionTimer !== timer) return;
|
|
834
|
+
this.peerConnectionTimer = null;
|
|
835
|
+
if (!this.isActiveRun(generation, pc) || pc.connectionState === "connected") return;
|
|
836
|
+
this.terminateWithError(
|
|
837
|
+
new Error(`WebRTC connection timed out after ${timeoutMs}ms`),
|
|
838
|
+
true,
|
|
839
|
+
generation
|
|
840
|
+
);
|
|
841
|
+
}, timeoutMs);
|
|
842
|
+
this.peerConnectionTimer = timer;
|
|
843
|
+
}
|
|
844
|
+
clearPeerConnectionTimeout() {
|
|
845
|
+
if (this.peerConnectionTimer !== null) clearTimeout(this.peerConnectionTimer);
|
|
846
|
+
this.peerConnectionTimer = null;
|
|
847
|
+
}
|
|
848
|
+
terminateWithError(err, notify = true, generation = this.lifecycleGeneration) {
|
|
849
|
+
if (generation !== this.lifecycleGeneration) return;
|
|
850
|
+
this.lifecycleGeneration++;
|
|
851
|
+
this.runAbort?.abort();
|
|
852
|
+
this.runAbort = null;
|
|
853
|
+
this.clearPeerConnectionTimeout();
|
|
330
854
|
this.stopped = true;
|
|
331
|
-
this.
|
|
855
|
+
this.cancelAllMediaRecovery();
|
|
332
856
|
this.reconnectGeneration++;
|
|
333
857
|
this.resumeSocket?.close();
|
|
334
858
|
this.resumeSocket = null;
|
|
335
859
|
this.sig?.close();
|
|
336
860
|
this.sig = null;
|
|
861
|
+
this.rejectSignalingWaiters(err);
|
|
337
862
|
this.pc?.close();
|
|
338
863
|
this.pc = null;
|
|
864
|
+
this.textChannel = null;
|
|
865
|
+
this.speechEnabled = false;
|
|
866
|
+
this.speechPending = false;
|
|
867
|
+
this.speechTransceiver = null;
|
|
868
|
+
this.microphoneTransceiver = null;
|
|
869
|
+
this.typeSenders.clear();
|
|
339
870
|
this.unwatchStreamTracks();
|
|
340
|
-
this.
|
|
341
|
-
this.
|
|
871
|
+
this.stopPublishedTracks();
|
|
872
|
+
this.clearIntentionalTrackEnds();
|
|
873
|
+
this.rejectPendingAnswer(new Error("publisher terminated"));
|
|
874
|
+
this.pendingOffer = null;
|
|
342
875
|
this.hasAnswer = false;
|
|
343
876
|
this.pendingRemoteCandidates = [];
|
|
877
|
+
this.pendingLocalCandidates = [];
|
|
878
|
+
this.localCandidateOfferSent = false;
|
|
879
|
+
this.clearRetainedICECandidates();
|
|
344
880
|
this.readToken = null;
|
|
345
881
|
this.gatewayURL = null;
|
|
346
|
-
this.
|
|
882
|
+
this.lastReportedICEPath = null;
|
|
883
|
+
if (notify) this.opts.callbacks?.onError?.(err);
|
|
347
884
|
}
|
|
348
885
|
handleSignal(msg) {
|
|
349
886
|
switch (msg.type) {
|
|
350
887
|
case "answer": {
|
|
351
888
|
if (!this.pc) return;
|
|
352
|
-
this.
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
this.pc?.addIceCandidate(init).catch(() => {
|
|
358
|
-
});
|
|
359
|
-
}
|
|
360
|
-
this.pendingRemoteCandidates = [];
|
|
361
|
-
}).catch((err) => {
|
|
362
|
-
this.opts.callbacks?.onError?.(
|
|
363
|
-
new Error(`failed to set remote description: ${err}`)
|
|
364
|
-
);
|
|
365
|
-
});
|
|
889
|
+
const pending = this.pendingAnswer;
|
|
890
|
+
if (!pending) break;
|
|
891
|
+
if (msg.negotiation_id && msg.negotiation_id !== pending.id) break;
|
|
892
|
+
this.pendingAnswer = null;
|
|
893
|
+
pending.resolve(msg.sdp);
|
|
366
894
|
break;
|
|
367
895
|
}
|
|
368
896
|
case "ice_candidate": {
|
|
369
897
|
if (!this.pc) return;
|
|
898
|
+
if (!this.retainRemoteCandidate(msg)) return;
|
|
370
899
|
const init = {
|
|
371
900
|
candidate: msg.candidate,
|
|
372
901
|
sdpMid: msg.sdp_mid ?? null,
|
|
@@ -384,8 +913,14 @@ var Publisher = class {
|
|
|
384
913
|
case "connection_state": {
|
|
385
914
|
break;
|
|
386
915
|
}
|
|
387
|
-
case "media_stall":
|
|
388
916
|
case "media_track_ended": {
|
|
917
|
+
if (msg.track === "audio") break;
|
|
918
|
+
if (this.consumeIntentionalTrackEnd(msg.track, msg.track_id)) break;
|
|
919
|
+
void this.beginMediaRecovery(msg.track);
|
|
920
|
+
break;
|
|
921
|
+
}
|
|
922
|
+
case "media_stall": {
|
|
923
|
+
if (msg.track === "audio") break;
|
|
389
924
|
void this.beginMediaRecovery(msg.track);
|
|
390
925
|
break;
|
|
391
926
|
}
|
|
@@ -394,7 +929,18 @@ var Publisher = class {
|
|
|
394
929
|
break;
|
|
395
930
|
}
|
|
396
931
|
case "error": {
|
|
397
|
-
|
|
932
|
+
const err = new ReportedPublisherError(msg.error, msg.fatal === true);
|
|
933
|
+
const pending = this.pendingAnswer;
|
|
934
|
+
let matchedPending = false;
|
|
935
|
+
if (pending && (!msg.negotiation_id || msg.negotiation_id === pending.id)) {
|
|
936
|
+
matchedPending = true;
|
|
937
|
+
this.pendingAnswer = null;
|
|
938
|
+
pending.reject(err);
|
|
939
|
+
}
|
|
940
|
+
if (err.fatal) this.opts.callbacks?.onError?.(err);
|
|
941
|
+
if (err.fatal && !matchedPending) {
|
|
942
|
+
this.terminateWithError(err, false);
|
|
943
|
+
}
|
|
398
944
|
break;
|
|
399
945
|
}
|
|
400
946
|
case "resumed":
|
|
@@ -402,86 +948,482 @@ var Publisher = class {
|
|
|
402
948
|
}
|
|
403
949
|
}
|
|
404
950
|
async beginMediaRecovery(trackType) {
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
const liveTracks =
|
|
951
|
+
const state = this.recoveryState(trackType);
|
|
952
|
+
if (this.stopped || state.recovering || state.required) return;
|
|
953
|
+
const liveTracks = this.tracksOfType(trackType).filter(
|
|
954
|
+
(track) => track.readyState !== "ended"
|
|
955
|
+
);
|
|
408
956
|
if (liveTracks.length === 0) {
|
|
409
957
|
this.failMediaRecovery(trackType, "capture_ended");
|
|
410
958
|
return;
|
|
411
959
|
}
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
960
|
+
state.recovering = true;
|
|
961
|
+
state.generation = ++this.recoverySequence;
|
|
962
|
+
const generation = state.generation;
|
|
963
|
+
state.action = "sender_restart";
|
|
415
964
|
this.emitRecoveryTransition({ state: "recovering", track: trackType, action: "sender_restart" });
|
|
416
965
|
this.sendRecoveryDiagnostic("recovery_started", trackType, "sender_restart");
|
|
417
|
-
await this.restartSenders(liveTracks, generation);
|
|
418
|
-
if (!this.isCurrentRecovery(generation)) return;
|
|
966
|
+
await this.restartSenders(trackType, liveTracks, generation);
|
|
967
|
+
if (!this.isCurrentRecovery(trackType, generation)) return;
|
|
419
968
|
await this.wait(senderRecoveryWaitMs);
|
|
420
|
-
if (!this.isCurrentRecovery(generation)) return;
|
|
421
|
-
|
|
969
|
+
if (!this.isCurrentRecovery(trackType, generation)) return;
|
|
970
|
+
state.action = "ice_restart";
|
|
422
971
|
this.emitRecoveryTransition({ state: "recovering", track: trackType, action: "ice_restart" });
|
|
423
972
|
this.sendRecoveryDiagnostic("recovery_retry", trackType, "ice_restart");
|
|
424
973
|
try {
|
|
425
|
-
await this.
|
|
974
|
+
await this.sharedIceRestart();
|
|
426
975
|
} catch {
|
|
427
976
|
}
|
|
977
|
+
if (!this.isCurrentRecovery(trackType, generation)) return;
|
|
428
978
|
await this.wait(iceRecoveryWaitMs);
|
|
429
|
-
if (!this.isCurrentRecovery(generation)) return;
|
|
979
|
+
if (!this.isCurrentRecovery(trackType, generation)) return;
|
|
430
980
|
this.failMediaRecovery(trackType, "automatic_recovery_failed");
|
|
431
981
|
}
|
|
432
|
-
async restartSenders(tracks, generation) {
|
|
433
|
-
const
|
|
434
|
-
const senders = this.pc?.getSenders().filter(
|
|
435
|
-
(sender) => sender.track && live.has(sender.track)
|
|
436
|
-
) ?? [];
|
|
437
|
-
if (senders.length === 0) return;
|
|
438
|
-
const originals = senders.map((sender) => ({ sender, track: sender.track }));
|
|
982
|
+
async restartSenders(trackType, tracks, generation) {
|
|
983
|
+
const lifecycleGeneration = this.lifecycleGeneration;
|
|
439
984
|
try {
|
|
440
|
-
await
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
985
|
+
await this.enqueueNegotiation(async () => {
|
|
986
|
+
if (!this.isCurrentRecovery(trackType, generation)) return false;
|
|
987
|
+
const live = new Set(tracks);
|
|
988
|
+
const senders = this.pc?.getSenders().filter(
|
|
989
|
+
(sender) => sender.track && live.has(sender.track)
|
|
990
|
+
) ?? [];
|
|
991
|
+
if (senders.length === 0) return false;
|
|
992
|
+
const originals = senders.map((sender) => ({ sender, track: sender.track }));
|
|
993
|
+
try {
|
|
994
|
+
await Promise.all(originals.map(({ sender }) => sender.replaceTrack(null)));
|
|
995
|
+
await this.wait(senderRestartPauseMs);
|
|
996
|
+
if (!this.isCurrentRecovery(trackType, generation)) return false;
|
|
997
|
+
await Promise.all(originals.map(({ sender, track }) => sender.replaceTrack(track)));
|
|
998
|
+
if (!this.isCurrentRecovery(trackType, generation)) return false;
|
|
999
|
+
return;
|
|
1000
|
+
} finally {
|
|
1001
|
+
const restored = await Promise.allSettled(originals.map(async ({ sender, track }) => {
|
|
1002
|
+
if (sender.track === null && this.published.has(track) && track.readyState !== "ended") {
|
|
1003
|
+
await sender.replaceTrack(track);
|
|
1004
|
+
}
|
|
1005
|
+
}));
|
|
1006
|
+
if (restored.some((result) => result.status === "rejected")) {
|
|
1007
|
+
throw new SenderRestoreError("failed to restore a detached media sender");
|
|
1008
|
+
}
|
|
1009
|
+
}
|
|
1010
|
+
});
|
|
1011
|
+
} catch (err) {
|
|
1012
|
+
if (err instanceof SenderRestoreError && lifecycleGeneration === this.lifecycleGeneration && !this.stopped) {
|
|
1013
|
+
this.terminateWithError(err, true, lifecycleGeneration);
|
|
1014
|
+
return;
|
|
1015
|
+
}
|
|
446
1016
|
}
|
|
447
1017
|
}
|
|
448
|
-
|
|
1018
|
+
/**
|
|
1019
|
+
* Adds a recovery renegotiation to the same queue as user operations. The
|
|
1020
|
+
* recovery ladder awaits its completion before starting the stage observation
|
|
1021
|
+
* window. If recovery has completed by the time this reaches the head of the
|
|
1022
|
+
* queue, it is skipped.
|
|
1023
|
+
*/
|
|
1024
|
+
/** Returns the peer-wide ICE attempt shared by all active track recoveries. */
|
|
1025
|
+
sharedIceRestart() {
|
|
1026
|
+
if (this.iceRestartAttempt) return this.iceRestartAttempt.promise;
|
|
1027
|
+
const id = ++this.iceRestartSequence;
|
|
1028
|
+
const promise = this.enqueueNegotiation(
|
|
1029
|
+
() => {
|
|
1030
|
+
if (this.iceRestartAttempt?.id !== id || !this.hasActiveMediaRecovery()) return false;
|
|
1031
|
+
},
|
|
1032
|
+
{ iceRestart: true }
|
|
1033
|
+
);
|
|
1034
|
+
const attempt = { id, promise };
|
|
1035
|
+
this.iceRestartAttempt = attempt;
|
|
1036
|
+
void promise.finally(() => {
|
|
1037
|
+
if (this.iceRestartAttempt === attempt) this.iceRestartAttempt = null;
|
|
1038
|
+
}).catch(() => {
|
|
1039
|
+
});
|
|
1040
|
+
return promise;
|
|
1041
|
+
}
|
|
1042
|
+
/**
|
|
1043
|
+
* Serializes a renegotiation onto the shared chain: it waits for any prior
|
|
1044
|
+
* negotiation to finish (its answer applied), sends a fresh offer, and resolves
|
|
1045
|
+
* only once this offer's answer has been applied. This prevents overlapping
|
|
1046
|
+
* offers and answers being applied to the wrong offer.
|
|
1047
|
+
*/
|
|
1048
|
+
enqueueNegotiation(mutate, opts = {}) {
|
|
1049
|
+
const generation = this.lifecycleGeneration;
|
|
1050
|
+
const run = this.negotiationChain.catch(() => {
|
|
1051
|
+
}).then(() => {
|
|
1052
|
+
this.assertActiveRun(generation);
|
|
1053
|
+
return this.negotiateOnce(mutate, opts, generation);
|
|
1054
|
+
});
|
|
1055
|
+
this.negotiationChain = run.catch(() => {
|
|
1056
|
+
});
|
|
1057
|
+
return run;
|
|
1058
|
+
}
|
|
1059
|
+
async negotiateOnce(mutate, opts, generation) {
|
|
449
1060
|
const pc = this.pc;
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
const
|
|
457
|
-
|
|
458
|
-
|
|
1061
|
+
if (!pc || !this.isActiveRun(generation, pc)) {
|
|
1062
|
+
throw new PublisherStoppedError("publisher stopped");
|
|
1063
|
+
}
|
|
1064
|
+
if (!this.runAbort?.signal) throw new PublisherStoppedError("publisher stopped");
|
|
1065
|
+
const previousHasAnswer = this.hasAnswer;
|
|
1066
|
+
const previousRemoteCandidates = this.pendingRemoteCandidates;
|
|
1067
|
+
const previousLocalCandidateOfferSent = this.localCandidateOfferSent;
|
|
1068
|
+
const previousRetainedLocalCandidates = [...this.retainedLocalCandidates];
|
|
1069
|
+
const previousRetainedLocalCandidateKeys = new Set(this.retainedLocalCandidateKeys);
|
|
1070
|
+
const previousLocalCandidateGeneration = this.localCandidateGeneration;
|
|
1071
|
+
await this.awaitSignaling();
|
|
1072
|
+
this.assertActiveRun(generation, pc);
|
|
1073
|
+
let change;
|
|
1074
|
+
let localOfferSet = false;
|
|
1075
|
+
let answerReceived = false;
|
|
1076
|
+
try {
|
|
1077
|
+
const result = await mutate();
|
|
1078
|
+
this.assertActiveRun(generation, pc);
|
|
1079
|
+
if (result === false) return;
|
|
1080
|
+
if (result && typeof result === "object") change = result;
|
|
1081
|
+
if (opts.iceRestart) pc.restartIce?.();
|
|
1082
|
+
const offer = await pc.createOffer(opts.iceRestart ? { iceRestart: true } : void 0);
|
|
1083
|
+
this.assertActiveRun(generation, pc);
|
|
1084
|
+
this.beginLocalCandidateBatch();
|
|
1085
|
+
await pc.setLocalDescription(offer);
|
|
1086
|
+
localOfferSet = true;
|
|
1087
|
+
this.assertActiveRun(generation, pc);
|
|
1088
|
+
const local = pc.localDescription;
|
|
1089
|
+
if (!local) throw new Error("local description missing");
|
|
1090
|
+
this.hasAnswer = false;
|
|
1091
|
+
this.pendingRemoteCandidates = [];
|
|
1092
|
+
const id = this.nextNegotiationId();
|
|
1093
|
+
const { answered } = await this.sendOffer({
|
|
1094
|
+
type: "offer",
|
|
1095
|
+
sdp: local.sdp,
|
|
1096
|
+
sdp_type: "offer",
|
|
1097
|
+
negotiation_id: id,
|
|
1098
|
+
tracks: change?.labels ?? this.buildTrackLabels(),
|
|
1099
|
+
speech_enabled: this.speechEnabled || this.speechPending || void 0
|
|
1100
|
+
});
|
|
1101
|
+
this.releaseLocalCandidateBatch();
|
|
1102
|
+
const sdp = await answered;
|
|
1103
|
+
this.assertActiveRun(generation, pc);
|
|
1104
|
+
answerReceived = true;
|
|
1105
|
+
await pc.setRemoteDescription(new RTCSessionDescription({ type: "answer", sdp }));
|
|
1106
|
+
this.assertActiveRun(generation, pc);
|
|
1107
|
+
this.applyAnswered(pc);
|
|
1108
|
+
await change?.commit?.();
|
|
1109
|
+
} catch (err) {
|
|
1110
|
+
let rollbackFailed = false;
|
|
1111
|
+
if (localOfferSet && this.pc === pc && pc.signalingState === "have-local-offer") {
|
|
1112
|
+
try {
|
|
1113
|
+
await pc.setLocalDescription({ type: "rollback" });
|
|
1114
|
+
} catch {
|
|
1115
|
+
rollbackFailed = true;
|
|
1116
|
+
}
|
|
1117
|
+
}
|
|
1118
|
+
try {
|
|
1119
|
+
await change?.rollback?.();
|
|
1120
|
+
} catch {
|
|
1121
|
+
rollbackFailed = true;
|
|
1122
|
+
}
|
|
1123
|
+
const ambiguous = rollbackFailed || answerReceived || err instanceof NegotiationTimeoutError || err instanceof SenderRestoreError || err instanceof ReportedPublisherError && err.fatal;
|
|
1124
|
+
if (this.isActiveRun(generation, pc) && ambiguous) {
|
|
1125
|
+
try {
|
|
1126
|
+
await change?.discard?.();
|
|
1127
|
+
} catch {
|
|
1128
|
+
}
|
|
1129
|
+
const failure = err instanceof Error ? err : new Error(String(err));
|
|
1130
|
+
this.terminateWithError(
|
|
1131
|
+
failure,
|
|
1132
|
+
!(err instanceof ReportedPublisherError),
|
|
1133
|
+
generation
|
|
1134
|
+
);
|
|
1135
|
+
} else if (this.isActiveRun(generation, pc)) {
|
|
1136
|
+
const buffered = this.pendingRemoteCandidates;
|
|
1137
|
+
this.hasAnswer = previousHasAnswer;
|
|
1138
|
+
this.pendingRemoteCandidates = previousRemoteCandidates;
|
|
1139
|
+
this.pendingLocalCandidates = [];
|
|
1140
|
+
this.localCandidateOfferSent = previousLocalCandidateOfferSent;
|
|
1141
|
+
this.retainedLocalCandidates = previousRetainedLocalCandidates;
|
|
1142
|
+
this.retainedLocalCandidateKeys = previousRetainedLocalCandidateKeys;
|
|
1143
|
+
this.localCandidateGeneration = previousLocalCandidateGeneration;
|
|
1144
|
+
if (previousHasAnswer) {
|
|
1145
|
+
for (const init of buffered) {
|
|
1146
|
+
pc.addIceCandidate(init).catch(() => {
|
|
1147
|
+
});
|
|
1148
|
+
}
|
|
1149
|
+
}
|
|
1150
|
+
}
|
|
1151
|
+
throw err;
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1154
|
+
/**
|
|
1155
|
+
* Registers interest in the answer for the offer identified by `id` and returns
|
|
1156
|
+
* a promise for its SDP. A second pending answer is an invariant violation: all
|
|
1157
|
+
* offer creation, including recovery, must pass through negotiationChain.
|
|
1158
|
+
*/
|
|
1159
|
+
nextNegotiationId() {
|
|
1160
|
+
return `n${++this.negotiationSeq}`;
|
|
1161
|
+
}
|
|
1162
|
+
handleTextMessage(data) {
|
|
1163
|
+
if (typeof data !== "string") return;
|
|
1164
|
+
try {
|
|
1165
|
+
const message = JSON.parse(data);
|
|
1166
|
+
if (message.type === "assistant_text" && message.utterance_id && message.text) {
|
|
1167
|
+
this.opts.callbacks?.onAssistantText?.({ utteranceId: message.utterance_id, text: message.text });
|
|
1168
|
+
} else if ((message.type === "user_text_accepted" || message.type === "user_text_rejected") && message.message_id) {
|
|
1169
|
+
this.opts.callbacks?.onUserTextResult?.({
|
|
1170
|
+
messageId: message.message_id,
|
|
1171
|
+
accepted: message.type === "user_text_accepted",
|
|
1172
|
+
reason: message.reason
|
|
1173
|
+
});
|
|
1174
|
+
}
|
|
1175
|
+
} catch {
|
|
1176
|
+
}
|
|
1177
|
+
}
|
|
1178
|
+
awaitAnswer(id) {
|
|
1179
|
+
if (this.pendingAnswer) {
|
|
1180
|
+
return Promise.reject(new Error("another negotiation is already awaiting an answer"));
|
|
1181
|
+
}
|
|
1182
|
+
return new Promise((resolve, reject) => {
|
|
1183
|
+
const timer = setTimeout(() => {
|
|
1184
|
+
if (this.pendingAnswer?.id === id) {
|
|
1185
|
+
this.pendingAnswer = null;
|
|
1186
|
+
reject(new NegotiationTimeoutError("timed out waiting for renegotiation answer"));
|
|
1187
|
+
}
|
|
1188
|
+
}, this.negotiationAnswerTimeoutMs());
|
|
1189
|
+
this.pendingAnswer = {
|
|
1190
|
+
id,
|
|
1191
|
+
resolve: (sdp) => {
|
|
1192
|
+
clearTimeout(timer);
|
|
1193
|
+
resolve(sdp);
|
|
1194
|
+
},
|
|
1195
|
+
reject: (err) => {
|
|
1196
|
+
clearTimeout(timer);
|
|
1197
|
+
reject(err);
|
|
1198
|
+
}
|
|
1199
|
+
};
|
|
1200
|
+
});
|
|
1201
|
+
}
|
|
1202
|
+
negotiationAnswerTimeoutMs() {
|
|
1203
|
+
const reconnectTimeout = this.opts.signalingReconnectTimeoutMs ?? defaultSignalingReconnectTimeoutMs;
|
|
1204
|
+
return Math.max(
|
|
1205
|
+
minimumNegotiationAnswerTimeoutMs,
|
|
1206
|
+
Math.max(0, reconnectTimeout) + negotiationReconnectGraceMs
|
|
1207
|
+
);
|
|
1208
|
+
}
|
|
1209
|
+
handleLocalICECandidate(candidate) {
|
|
1210
|
+
const message = {
|
|
1211
|
+
type: "ice_candidate",
|
|
1212
|
+
candidate: candidate.candidate,
|
|
1213
|
+
sdp_mid: candidate.sdpMid ?? void 0,
|
|
1214
|
+
sdp_mline_index: candidate.sdpMLineIndex ?? void 0,
|
|
1215
|
+
username_fragment: candidate.usernameFragment ?? void 0
|
|
1216
|
+
};
|
|
1217
|
+
if (!this.retainLocalCandidate(message)) return;
|
|
1218
|
+
if (!this.localCandidateOfferSent) {
|
|
1219
|
+
this.pendingLocalCandidates.push(message);
|
|
1220
|
+
return;
|
|
1221
|
+
}
|
|
1222
|
+
void this.sendWhenSignalingAvailable(message).catch(() => {
|
|
1223
|
+
});
|
|
1224
|
+
}
|
|
1225
|
+
candidateKey(candidate) {
|
|
1226
|
+
return JSON.stringify([
|
|
1227
|
+
candidate.candidate,
|
|
1228
|
+
candidate.sdp_mid ?? null,
|
|
1229
|
+
candidate.sdp_mline_index ?? null,
|
|
1230
|
+
candidate.username_fragment ?? null
|
|
1231
|
+
]);
|
|
1232
|
+
}
|
|
1233
|
+
retainLocalCandidate(candidate) {
|
|
1234
|
+
const generation = candidate.username_fragment;
|
|
1235
|
+
if (generation) {
|
|
1236
|
+
if (this.localCandidateGeneration && this.localCandidateGeneration !== generation) {
|
|
1237
|
+
this.retainedLocalCandidates = [];
|
|
1238
|
+
this.retainedLocalCandidateKeys.clear();
|
|
1239
|
+
}
|
|
1240
|
+
this.localCandidateGeneration = generation;
|
|
1241
|
+
}
|
|
1242
|
+
const key = this.candidateKey(candidate);
|
|
1243
|
+
if (this.retainedLocalCandidateKeys.has(key)) return false;
|
|
1244
|
+
if (this.retainedLocalCandidates.length === maxRetainedICECandidates) {
|
|
1245
|
+
const evicted = this.retainedLocalCandidates.shift();
|
|
1246
|
+
if (evicted) this.retainedLocalCandidateKeys.delete(this.candidateKey(evicted));
|
|
1247
|
+
}
|
|
1248
|
+
this.retainedLocalCandidates.push(candidate);
|
|
1249
|
+
this.retainedLocalCandidateKeys.add(key);
|
|
1250
|
+
return true;
|
|
1251
|
+
}
|
|
1252
|
+
retainRemoteCandidate(candidate) {
|
|
1253
|
+
const generation = candidate.username_fragment;
|
|
1254
|
+
if (generation) {
|
|
1255
|
+
if (this.remoteCandidateGeneration && this.remoteCandidateGeneration !== generation) {
|
|
1256
|
+
this.remoteCandidateKeys.clear();
|
|
1257
|
+
this.remoteCandidateOrder = [];
|
|
1258
|
+
}
|
|
1259
|
+
this.remoteCandidateGeneration = generation;
|
|
1260
|
+
}
|
|
1261
|
+
const key = this.candidateKey(candidate);
|
|
1262
|
+
if (this.remoteCandidateKeys.has(key)) return false;
|
|
1263
|
+
if (this.remoteCandidateOrder.length === maxRetainedICECandidates) {
|
|
1264
|
+
const evicted = this.remoteCandidateOrder.shift();
|
|
1265
|
+
if (evicted) this.remoteCandidateKeys.delete(evicted);
|
|
1266
|
+
}
|
|
1267
|
+
this.remoteCandidateOrder.push(key);
|
|
1268
|
+
this.remoteCandidateKeys.add(key);
|
|
1269
|
+
return true;
|
|
1270
|
+
}
|
|
1271
|
+
clearRetainedICECandidates() {
|
|
1272
|
+
this.retainedLocalCandidates = [];
|
|
1273
|
+
this.retainedLocalCandidateKeys.clear();
|
|
1274
|
+
this.localCandidateGeneration = null;
|
|
1275
|
+
this.remoteCandidateKeys.clear();
|
|
1276
|
+
this.remoteCandidateOrder = [];
|
|
1277
|
+
this.remoteCandidateGeneration = null;
|
|
1278
|
+
}
|
|
1279
|
+
beginLocalCandidateBatch() {
|
|
1280
|
+
this.localCandidateOfferSent = false;
|
|
1281
|
+
this.pendingLocalCandidates = [];
|
|
1282
|
+
}
|
|
1283
|
+
releaseLocalCandidateBatch() {
|
|
1284
|
+
this.localCandidateOfferSent = true;
|
|
1285
|
+
const candidates = this.pendingLocalCandidates;
|
|
1286
|
+
this.pendingLocalCandidates = [];
|
|
1287
|
+
for (const candidate of candidates) {
|
|
1288
|
+
void this.sendWhenSignalingAvailable(candidate).catch(() => {
|
|
1289
|
+
});
|
|
1290
|
+
}
|
|
1291
|
+
}
|
|
1292
|
+
// applyAnswered flushes ICE candidates buffered before the answer landed.
|
|
1293
|
+
applyAnswered(pc) {
|
|
1294
|
+
if (this.pc !== pc) return;
|
|
1295
|
+
this.hasAnswer = true;
|
|
1296
|
+
for (const init of this.pendingRemoteCandidates) {
|
|
1297
|
+
pc.addIceCandidate(init).catch(() => {
|
|
1298
|
+
});
|
|
1299
|
+
}
|
|
459
1300
|
this.pendingRemoteCandidates = [];
|
|
460
|
-
|
|
1301
|
+
this.watchSelectedICEPairChanges(pc);
|
|
1302
|
+
void this.reportSelectedICEPath(pc);
|
|
1303
|
+
}
|
|
1304
|
+
watchSelectedICEPairChanges(pc) {
|
|
1305
|
+
try {
|
|
1306
|
+
const dtlsTransports = [
|
|
1307
|
+
pc.sctp?.transport,
|
|
1308
|
+
...pc.getSenders().map((sender) => sender.transport),
|
|
1309
|
+
...pc.getReceivers().map((receiver) => receiver.transport)
|
|
1310
|
+
];
|
|
1311
|
+
for (const dtls of dtlsTransports) {
|
|
1312
|
+
const ice = dtls?.iceTransport;
|
|
1313
|
+
if (!ice || this.watchedICETransports.has(ice)) continue;
|
|
1314
|
+
this.watchedICETransports.add(ice);
|
|
1315
|
+
ice.addEventListener("selectedcandidatepairchange", () => {
|
|
1316
|
+
void this.reportSelectedICEPath(pc);
|
|
1317
|
+
});
|
|
1318
|
+
}
|
|
1319
|
+
} catch {
|
|
1320
|
+
}
|
|
1321
|
+
}
|
|
1322
|
+
async reportSelectedICEPath(pc) {
|
|
1323
|
+
if (this.pc !== pc || this.stopped) return;
|
|
1324
|
+
let stats;
|
|
1325
|
+
try {
|
|
1326
|
+
stats = await pc.getStats();
|
|
1327
|
+
} catch {
|
|
1328
|
+
return;
|
|
1329
|
+
}
|
|
1330
|
+
if (this.pc !== pc || this.stopped) return;
|
|
1331
|
+
let selectedPairID;
|
|
1332
|
+
let selectedPair;
|
|
1333
|
+
stats.forEach((report) => {
|
|
1334
|
+
const value = report;
|
|
1335
|
+
if (value.type === "transport" && typeof value.selectedCandidatePairId === "string") {
|
|
1336
|
+
selectedPairID = value.selectedCandidatePairId;
|
|
1337
|
+
}
|
|
1338
|
+
});
|
|
1339
|
+
if (selectedPairID) {
|
|
1340
|
+
selectedPair = stats.get(selectedPairID);
|
|
1341
|
+
}
|
|
1342
|
+
if (!selectedPair) {
|
|
1343
|
+
stats.forEach((report) => {
|
|
1344
|
+
const value = report;
|
|
1345
|
+
if (!selectedPair && value.type === "candidate-pair" && value.state === "succeeded" && value.nominated === true) {
|
|
1346
|
+
selectedPair = value;
|
|
1347
|
+
}
|
|
1348
|
+
});
|
|
1349
|
+
}
|
|
1350
|
+
if (!selectedPair) return;
|
|
1351
|
+
const localID = selectedPair.localCandidateId;
|
|
1352
|
+
const remoteID = selectedPair.remoteCandidateId;
|
|
1353
|
+
if (typeof localID !== "string") return;
|
|
1354
|
+
const local = stats.get(localID);
|
|
1355
|
+
const remote = typeof remoteID === "string" ? stats.get(remoteID) : void 0;
|
|
1356
|
+
if (!local || typeof local.candidateType !== "string") return;
|
|
1357
|
+
const message = {
|
|
1358
|
+
type: "ice_path",
|
|
1359
|
+
local_candidate_type: local.candidateType,
|
|
1360
|
+
local_protocol: typeof local.protocol === "string" ? local.protocol : void 0,
|
|
1361
|
+
remote_candidate_type: typeof remote?.candidateType === "string" ? remote.candidateType : void 0,
|
|
1362
|
+
remote_protocol: typeof remote?.protocol === "string" ? remote.protocol : void 0,
|
|
1363
|
+
relay_protocol: typeof local.relayProtocol === "string" ? local.relayProtocol : void 0,
|
|
1364
|
+
turn_url: typeof local.url === "string" ? local.url : void 0
|
|
1365
|
+
};
|
|
1366
|
+
const fingerprint = JSON.stringify(message);
|
|
1367
|
+
if (fingerprint === this.lastReportedICEPath) return;
|
|
1368
|
+
this.lastReportedICEPath = fingerprint;
|
|
1369
|
+
try {
|
|
1370
|
+
await this.sendWhenSignalingAvailable(message);
|
|
1371
|
+
} catch {
|
|
1372
|
+
if (this.lastReportedICEPath === fingerprint) {
|
|
1373
|
+
this.lastReportedICEPath = null;
|
|
1374
|
+
}
|
|
1375
|
+
}
|
|
461
1376
|
}
|
|
462
1377
|
completeMediaRecovery(trackType) {
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
1378
|
+
const state = this.recoveryStates.get(trackType);
|
|
1379
|
+
if (!state?.recovering) return;
|
|
1380
|
+
const action = state.action ?? void 0;
|
|
1381
|
+
this.cancelMediaRecovery(trackType);
|
|
466
1382
|
this.emitRecoveryTransition({ state: "recovered", track: trackType, action });
|
|
467
1383
|
}
|
|
468
1384
|
failMediaRecovery(trackType, reason) {
|
|
469
|
-
|
|
470
|
-
this.
|
|
471
|
-
|
|
472
|
-
|
|
1385
|
+
const state = this.recoveryState(trackType);
|
|
1386
|
+
if (this.stopped || state.required) return;
|
|
1387
|
+
state.required = true;
|
|
1388
|
+
const action = state.action ?? void 0;
|
|
1389
|
+
this.cancelMediaRecovery(trackType);
|
|
473
1390
|
const event = { state: "failed", track: trackType, action, reason };
|
|
474
1391
|
this.emitRecoveryTransition(event);
|
|
475
1392
|
this.opts.callbacks?.onRecoveryRequired?.(event);
|
|
476
1393
|
this.sendRecoveryDiagnostic("recovery_failed", trackType, action, reason);
|
|
477
1394
|
}
|
|
478
|
-
|
|
479
|
-
this.
|
|
480
|
-
|
|
481
|
-
|
|
1395
|
+
recoveryState(trackType) {
|
|
1396
|
+
let state = this.recoveryStates.get(trackType);
|
|
1397
|
+
if (!state) {
|
|
1398
|
+
state = { generation: 0, recovering: false, required: false, action: null };
|
|
1399
|
+
this.recoveryStates.set(trackType, state);
|
|
1400
|
+
}
|
|
1401
|
+
return state;
|
|
1402
|
+
}
|
|
1403
|
+
cancelMediaRecovery(trackType) {
|
|
1404
|
+
const state = this.recoveryState(trackType);
|
|
1405
|
+
state.generation = ++this.recoverySequence;
|
|
1406
|
+
state.recovering = false;
|
|
1407
|
+
state.action = null;
|
|
1408
|
+
this.clearSharedIceRestartIfIdle();
|
|
1409
|
+
}
|
|
1410
|
+
cancelAllMediaRecovery() {
|
|
1411
|
+
for (const trackType of this.recoveryStates.keys()) {
|
|
1412
|
+
this.cancelMediaRecovery(trackType);
|
|
1413
|
+
}
|
|
1414
|
+
}
|
|
1415
|
+
isCurrentRecovery(trackType, generation) {
|
|
1416
|
+
const state = this.recoveryStates.get(trackType);
|
|
1417
|
+
return !this.stopped && !!state?.recovering && state.generation === generation;
|
|
482
1418
|
}
|
|
483
|
-
|
|
484
|
-
|
|
1419
|
+
hasActiveMediaRecovery() {
|
|
1420
|
+
for (const state of this.recoveryStates.values()) {
|
|
1421
|
+
if (state.recovering) return true;
|
|
1422
|
+
}
|
|
1423
|
+
return false;
|
|
1424
|
+
}
|
|
1425
|
+
clearSharedIceRestartIfIdle() {
|
|
1426
|
+
if (!this.hasActiveMediaRecovery()) this.iceRestartAttempt = null;
|
|
485
1427
|
}
|
|
486
1428
|
emitRecoveryTransition(event) {
|
|
487
1429
|
this.opts.callbacks?.onRecoveryStateChange?.(event);
|
|
@@ -489,39 +1431,354 @@ var Publisher = class {
|
|
|
489
1431
|
sendRecoveryDiagnostic(event, track, action, reason) {
|
|
490
1432
|
this.sig?.send({ type: "recovery_event", event, track, action, reason });
|
|
491
1433
|
}
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
1434
|
+
// -------------------------------------------------------------------------
|
|
1435
|
+
// Published-track bookkeeping
|
|
1436
|
+
// -------------------------------------------------------------------------
|
|
1437
|
+
requireSingleVideoTrack(stream) {
|
|
1438
|
+
const tracks = stream.getVideoTracks();
|
|
1439
|
+
if (tracks.length !== 1) {
|
|
1440
|
+
throw new Error(
|
|
1441
|
+
`expected exactly one video track, received ${tracks.length}`
|
|
1442
|
+
);
|
|
497
1443
|
}
|
|
1444
|
+
this.requireLiveVideoTrack(tracks[0]);
|
|
1445
|
+
return tracks[0];
|
|
498
1446
|
}
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
1447
|
+
requireLiveVideoTrack(track) {
|
|
1448
|
+
if (track.readyState === "ended") {
|
|
1449
|
+
throw new Error("video track has already ended");
|
|
502
1450
|
}
|
|
503
|
-
this.trackEndHandlers.clear();
|
|
504
1451
|
}
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
1452
|
+
requireLiveTrack(track, kind) {
|
|
1453
|
+
if (track.readyState === "ended") {
|
|
1454
|
+
throw new Error(`${kind} track has already ended`);
|
|
1455
|
+
}
|
|
1456
|
+
}
|
|
1457
|
+
requireSingleAudioTrack(stream) {
|
|
1458
|
+
const tracks = stream.getAudioTracks();
|
|
1459
|
+
if (tracks.length !== 1) {
|
|
1460
|
+
throw new Error(
|
|
1461
|
+
`expected exactly one audio track, received ${tracks.length}`
|
|
1462
|
+
);
|
|
1463
|
+
}
|
|
1464
|
+
if (tracks[0].readyState === "ended") {
|
|
1465
|
+
throw new Error("audio track has already ended");
|
|
1466
|
+
}
|
|
1467
|
+
return tracks[0];
|
|
1468
|
+
}
|
|
1469
|
+
/**
|
|
1470
|
+
* Stages the microphone track onto the peer connection. Unlike video, audio
|
|
1471
|
+
* has no recovery ladder and no SSIM/frame semantics, so this simply adds (or
|
|
1472
|
+
* replaces) the single audio sender and declares the updated labels.
|
|
1473
|
+
*/
|
|
1474
|
+
async stagePublishAudio(track, stream) {
|
|
1475
|
+
const pc = this.pc;
|
|
1476
|
+
if (!pc) throw new Error("publisher not started");
|
|
1477
|
+
if (track.readyState === "ended") throw new Error("audio track has already ended");
|
|
1478
|
+
const type = "audio";
|
|
1479
|
+
if (this.published.get(track) === type) return false;
|
|
1480
|
+
const previous = this.tracksOfType(type).map((oldTrack) => ({
|
|
1481
|
+
track: oldTrack,
|
|
1482
|
+
stream: this.publishedStreams.get(oldTrack)
|
|
1483
|
+
}));
|
|
1484
|
+
const typeSender = this.typeSenders.get(type) ?? null;
|
|
1485
|
+
let addedSender = null;
|
|
1486
|
+
let replacedSender = null;
|
|
1487
|
+
if (previous.length > 0) {
|
|
1488
|
+
if (previous.length !== 1 || !typeSender || typeSender.track !== previous[0].track) {
|
|
1489
|
+
throw new SenderRestoreError("published audio sender is unavailable");
|
|
512
1490
|
}
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
1491
|
+
replacedSender = typeSender;
|
|
1492
|
+
await replacedSender.replaceTrack(track);
|
|
1493
|
+
} else {
|
|
1494
|
+
if (typeSender?.track) {
|
|
1495
|
+
throw new SenderRestoreError("inactive audio sender still has a track");
|
|
516
1496
|
}
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
1497
|
+
if (this.microphoneTransceiver && this.microphoneTransceiver.sender.track === null) {
|
|
1498
|
+
addedSender = this.microphoneTransceiver.sender;
|
|
1499
|
+
await addedSender.replaceTrack(track);
|
|
1500
|
+
this.microphoneTransceiver.direction = "sendonly";
|
|
1501
|
+
} else {
|
|
1502
|
+
addedSender = this.addMicrophoneTrack(pc, track, stream);
|
|
1503
|
+
}
|
|
1504
|
+
this.typeSenders.set(type, addedSender);
|
|
1505
|
+
}
|
|
1506
|
+
return {
|
|
1507
|
+
labels: this.labelsReplacingType(type, track),
|
|
1508
|
+
commit: () => {
|
|
1509
|
+
for (const { track: oldTrack } of previous) {
|
|
1510
|
+
this.unwatchTrack(oldTrack);
|
|
1511
|
+
this.published.delete(oldTrack);
|
|
1512
|
+
this.publishedStreams.delete(oldTrack);
|
|
1513
|
+
oldTrack.stop();
|
|
521
1514
|
}
|
|
522
|
-
|
|
523
|
-
|
|
1515
|
+
this.published.set(track, type);
|
|
1516
|
+
this.publishedStreams.set(track, stream);
|
|
1517
|
+
this.watchMicrophone(track);
|
|
1518
|
+
},
|
|
1519
|
+
rollback: async () => {
|
|
1520
|
+
if (this.pc !== pc) return;
|
|
1521
|
+
if (addedSender && pc.getSenders().includes(addedSender)) {
|
|
1522
|
+
pc.removeTrack(addedSender);
|
|
1523
|
+
if (typeSender) this.typeSenders.set(type, typeSender);
|
|
1524
|
+
else this.typeSenders.delete(type);
|
|
1525
|
+
}
|
|
1526
|
+
if (replacedSender && previous.length > 0) {
|
|
1527
|
+
const oldTrack = previous[0].track;
|
|
1528
|
+
if (oldTrack.readyState !== "ended") {
|
|
1529
|
+
await replacedSender.replaceTrack(oldTrack);
|
|
1530
|
+
}
|
|
1531
|
+
} else if (replacedSender) {
|
|
1532
|
+
pc.removeTrack(replacedSender);
|
|
1533
|
+
}
|
|
1534
|
+
},
|
|
1535
|
+
discard: () => track.stop()
|
|
1536
|
+
};
|
|
1537
|
+
}
|
|
1538
|
+
/**
|
|
1539
|
+
* Gives the microphone its own sendonly transceiver. addTrack() may reuse an
|
|
1540
|
+
* existing compatible recvonly transceiver, which would collapse the
|
|
1541
|
+
* microphone and assistant speech roles when speech was enabled first.
|
|
1542
|
+
* addTransceiver() always creates a distinct m-line and its direction keeps
|
|
1543
|
+
* the server's outbound speech sender on the dedicated speech transceiver.
|
|
1544
|
+
*/
|
|
1545
|
+
addMicrophoneTrack(pc, track, stream) {
|
|
1546
|
+
const transceiver = pc.addTransceiver(track, {
|
|
1547
|
+
direction: "sendonly",
|
|
1548
|
+
streams: [stream]
|
|
524
1549
|
});
|
|
1550
|
+
this.microphoneTransceiver = transceiver;
|
|
1551
|
+
return transceiver.sender;
|
|
1552
|
+
}
|
|
1553
|
+
/** Registers one physical video track under its logical type and source stream. */
|
|
1554
|
+
registerTrack(track, stream, type) {
|
|
1555
|
+
this.published.set(track, type);
|
|
1556
|
+
this.publishedStreams.set(track, stream);
|
|
1557
|
+
this.watchTrack(track);
|
|
1558
|
+
}
|
|
1559
|
+
/** The live video tracks currently published under the given type. */
|
|
1560
|
+
tracksOfType(type) {
|
|
1561
|
+
const out = [];
|
|
1562
|
+
for (const [track, tt] of this.published) {
|
|
1563
|
+
if (tt === type) out.push(track);
|
|
1564
|
+
}
|
|
1565
|
+
return out;
|
|
1566
|
+
}
|
|
1567
|
+
/** Builds the id → type label array declared to the server on every offer. */
|
|
1568
|
+
buildTrackLabels() {
|
|
1569
|
+
const labels = [];
|
|
1570
|
+
for (const [track, type] of this.published) {
|
|
1571
|
+
labels.push({ id: track.id, type });
|
|
1572
|
+
}
|
|
1573
|
+
return labels;
|
|
1574
|
+
}
|
|
1575
|
+
labelsReplacingType(type, replacement) {
|
|
1576
|
+
const labels = [];
|
|
1577
|
+
for (const [track, publishedType] of this.published) {
|
|
1578
|
+
if (publishedType !== type) labels.push({ id: track.id, type: publishedType });
|
|
1579
|
+
}
|
|
1580
|
+
if (replacement) labels.push({ id: replacement.id, type });
|
|
1581
|
+
return labels;
|
|
1582
|
+
}
|
|
1583
|
+
async stagePublish(track, stream, type) {
|
|
1584
|
+
const pc = this.pc;
|
|
1585
|
+
if (!pc) throw new Error("publisher not started");
|
|
1586
|
+
this.requireLiveVideoTrack(track);
|
|
1587
|
+
const alreadyPublishedAs = this.published.get(track);
|
|
1588
|
+
if (alreadyPublishedAs === type) return false;
|
|
1589
|
+
if (alreadyPublishedAs) {
|
|
1590
|
+
throw new Error(`video track is already published as ${alreadyPublishedAs}`);
|
|
1591
|
+
}
|
|
1592
|
+
const previous = this.tracksOfType(type).map((oldTrack) => ({
|
|
1593
|
+
track: oldTrack,
|
|
1594
|
+
stream: this.publishedStreams.get(oldTrack)
|
|
1595
|
+
}));
|
|
1596
|
+
const typeSender = this.typeSenders.get(type) ?? null;
|
|
1597
|
+
let addedSender = null;
|
|
1598
|
+
let replacedSender = null;
|
|
1599
|
+
if (previous.length > 0) {
|
|
1600
|
+
if (previous.length !== 1 || !typeSender || typeSender.track !== previous[0].track) {
|
|
1601
|
+
throw new SenderRestoreError(`published ${type} sender is unavailable`);
|
|
1602
|
+
}
|
|
1603
|
+
replacedSender = typeSender;
|
|
1604
|
+
await replacedSender.replaceTrack(track);
|
|
1605
|
+
} else {
|
|
1606
|
+
if (typeSender?.track) {
|
|
1607
|
+
throw new SenderRestoreError(`inactive ${type} sender still has a track`);
|
|
1608
|
+
}
|
|
1609
|
+
addedSender = pc.addTrack(track, stream);
|
|
1610
|
+
this.typeSenders.set(type, addedSender);
|
|
1611
|
+
}
|
|
1612
|
+
return {
|
|
1613
|
+
labels: this.labelsReplacingType(type, track),
|
|
1614
|
+
commit: () => {
|
|
1615
|
+
this.cancelMediaRecovery(type);
|
|
1616
|
+
this.recoveryState(type).required = false;
|
|
1617
|
+
for (const { track: oldTrack } of previous) {
|
|
1618
|
+
this.unwatchTrack(oldTrack);
|
|
1619
|
+
this.published.delete(oldTrack);
|
|
1620
|
+
this.publishedStreams.delete(oldTrack);
|
|
1621
|
+
oldTrack.stop();
|
|
1622
|
+
}
|
|
1623
|
+
this.registerTrack(track, stream, type);
|
|
1624
|
+
if (track.readyState === "ended") {
|
|
1625
|
+
this.failMediaRecovery(type, "capture_ended");
|
|
1626
|
+
}
|
|
1627
|
+
},
|
|
1628
|
+
rollback: async () => {
|
|
1629
|
+
if (this.pc !== pc) return;
|
|
1630
|
+
if (addedSender && pc.getSenders().includes(addedSender)) {
|
|
1631
|
+
pc.removeTrack(addedSender);
|
|
1632
|
+
if (typeSender) this.typeSenders.set(type, typeSender);
|
|
1633
|
+
else this.typeSenders.delete(type);
|
|
1634
|
+
}
|
|
1635
|
+
if (replacedSender && previous.length > 0) {
|
|
1636
|
+
const oldTrack = previous[0].track;
|
|
1637
|
+
if (oldTrack.readyState !== "ended") {
|
|
1638
|
+
await replacedSender.replaceTrack(oldTrack);
|
|
1639
|
+
}
|
|
1640
|
+
} else if (replacedSender) {
|
|
1641
|
+
pc.removeTrack(replacedSender);
|
|
1642
|
+
}
|
|
1643
|
+
},
|
|
1644
|
+
discard: () => track.stop()
|
|
1645
|
+
};
|
|
1646
|
+
}
|
|
1647
|
+
stageUnpublish(type) {
|
|
1648
|
+
const pc = this.pc;
|
|
1649
|
+
if (!pc) throw new Error("publisher not started");
|
|
1650
|
+
const previous = this.tracksOfType(type).map((track) => ({
|
|
1651
|
+
track,
|
|
1652
|
+
stream: this.publishedStreams.get(track)
|
|
1653
|
+
}));
|
|
1654
|
+
const typeSender = this.typeSenders.get(type);
|
|
1655
|
+
if (previous.length !== 1 || !typeSender || typeSender.track !== previous[0].track) {
|
|
1656
|
+
throw new SenderRestoreError(`published ${type} sender is unavailable`);
|
|
1657
|
+
}
|
|
1658
|
+
for (const { track } of previous) this.expectIntentionalTrackEnd(track.id, type);
|
|
1659
|
+
pc.removeTrack(typeSender);
|
|
1660
|
+
return {
|
|
1661
|
+
labels: this.labelsReplacingType(type),
|
|
1662
|
+
commit: () => {
|
|
1663
|
+
this.cancelMediaRecovery(type);
|
|
1664
|
+
this.recoveryState(type).required = false;
|
|
1665
|
+
this.typeSenders.delete(type);
|
|
1666
|
+
for (const { track } of previous) {
|
|
1667
|
+
this.unwatchTrack(track);
|
|
1668
|
+
this.published.delete(track);
|
|
1669
|
+
this.publishedStreams.delete(track);
|
|
1670
|
+
track.stop();
|
|
1671
|
+
}
|
|
1672
|
+
},
|
|
1673
|
+
rollback: () => {
|
|
1674
|
+
if (this.pc !== pc) return;
|
|
1675
|
+
this.forgetIntentionalTrackEnds(previous.map(({ track }) => track.id));
|
|
1676
|
+
return Promise.all(previous.map(async ({ track }) => {
|
|
1677
|
+
if (track.readyState === "ended") return;
|
|
1678
|
+
await typeSender.replaceTrack(track);
|
|
1679
|
+
})).then(() => void 0);
|
|
1680
|
+
}
|
|
1681
|
+
};
|
|
1682
|
+
}
|
|
1683
|
+
/** Stops every published local track and clears the published map. */
|
|
1684
|
+
stopPublishedTracks() {
|
|
1685
|
+
for (const track of this.published.keys()) {
|
|
1686
|
+
track.stop();
|
|
1687
|
+
}
|
|
1688
|
+
this.published.clear();
|
|
1689
|
+
this.publishedStreams.clear();
|
|
1690
|
+
}
|
|
1691
|
+
expectIntentionalTrackEnd(trackID, type) {
|
|
1692
|
+
const prior = this.intentionalTrackEnds.get(trackID);
|
|
1693
|
+
if (prior) clearTimeout(prior.timer);
|
|
1694
|
+
const retentionMs = Math.max(
|
|
1695
|
+
minimumIntentionalTrackEndRetentionMs,
|
|
1696
|
+
this.negotiationAnswerTimeoutMs()
|
|
1697
|
+
);
|
|
1698
|
+
const timer = setTimeout(() => {
|
|
1699
|
+
const current = this.intentionalTrackEnds.get(trackID);
|
|
1700
|
+
if (current?.timer === timer) this.intentionalTrackEnds.delete(trackID);
|
|
1701
|
+
}, retentionMs);
|
|
1702
|
+
this.intentionalTrackEnds.set(trackID, { type, timer });
|
|
1703
|
+
}
|
|
1704
|
+
forgetIntentionalTrackEnds(trackIDs) {
|
|
1705
|
+
for (const trackID of trackIDs) {
|
|
1706
|
+
const expected = this.intentionalTrackEnds.get(trackID);
|
|
1707
|
+
if (!expected) continue;
|
|
1708
|
+
clearTimeout(expected.timer);
|
|
1709
|
+
this.intentionalTrackEnds.delete(trackID);
|
|
1710
|
+
}
|
|
1711
|
+
}
|
|
1712
|
+
consumeIntentionalTrackEnd(type, trackID) {
|
|
1713
|
+
if (trackID) {
|
|
1714
|
+
const expected = this.intentionalTrackEnds.get(trackID);
|
|
1715
|
+
if (!expected || expected.type !== type) return false;
|
|
1716
|
+
clearTimeout(expected.timer);
|
|
1717
|
+
this.intentionalTrackEnds.delete(trackID);
|
|
1718
|
+
return true;
|
|
1719
|
+
}
|
|
1720
|
+
for (const [id, expected] of this.intentionalTrackEnds) {
|
|
1721
|
+
if (expected.type !== type) continue;
|
|
1722
|
+
clearTimeout(expected.timer);
|
|
1723
|
+
this.intentionalTrackEnds.delete(id);
|
|
1724
|
+
return true;
|
|
1725
|
+
}
|
|
1726
|
+
return false;
|
|
1727
|
+
}
|
|
1728
|
+
clearIntentionalTrackEnds() {
|
|
1729
|
+
for (const expected of this.intentionalTrackEnds.values()) {
|
|
1730
|
+
clearTimeout(expected.timer);
|
|
1731
|
+
}
|
|
1732
|
+
this.intentionalTrackEnds.clear();
|
|
1733
|
+
}
|
|
1734
|
+
/**
|
|
1735
|
+
* Watches a track's "ended" event so an involuntary capture stop (the user
|
|
1736
|
+
* revokes a screen share, a device unplugs) reports as a recovery failure for
|
|
1737
|
+
* that track's actual type. Intentional removals unwatch first.
|
|
1738
|
+
*/
|
|
1739
|
+
watchTrack(track) {
|
|
1740
|
+
if (this.trackEndHandlers.has(track)) return;
|
|
1741
|
+
const handler = () => {
|
|
1742
|
+
const type = this.published.get(track) ?? "camera";
|
|
1743
|
+
this.failMediaRecovery(type, "capture_ended");
|
|
1744
|
+
};
|
|
1745
|
+
track.addEventListener("ended", handler);
|
|
1746
|
+
this.trackEndHandlers.set(track, handler);
|
|
1747
|
+
}
|
|
1748
|
+
/**
|
|
1749
|
+
* Watches a microphone only for lifecycle removal. An ended microphone is not
|
|
1750
|
+
* recovered like video; it is negotiated away so the media server can flush
|
|
1751
|
+
* the utterance and release transcription resources.
|
|
1752
|
+
*/
|
|
1753
|
+
watchMicrophone(track) {
|
|
1754
|
+
if (this.trackEndHandlers.has(track)) return;
|
|
1755
|
+
const generation = this.lifecycleGeneration;
|
|
1756
|
+
const handler = () => {
|
|
1757
|
+
if (this.published.get(track) !== "audio") return;
|
|
1758
|
+
void this.enqueueNegotiation(() => {
|
|
1759
|
+
if (this.published.get(track) !== "audio") return false;
|
|
1760
|
+
return this.stageUnpublish("audio");
|
|
1761
|
+
}).catch((err) => {
|
|
1762
|
+
if (!this.isActiveRun(generation)) return;
|
|
1763
|
+
const failure = err instanceof Error ? err : new Error(String(err));
|
|
1764
|
+
this.terminateWithError(failure, true, generation);
|
|
1765
|
+
});
|
|
1766
|
+
};
|
|
1767
|
+
track.addEventListener("ended", handler);
|
|
1768
|
+
this.trackEndHandlers.set(track, handler);
|
|
1769
|
+
if (track.readyState === "ended") handler(new Event("ended"));
|
|
1770
|
+
}
|
|
1771
|
+
unwatchTrack(track) {
|
|
1772
|
+
const handler = this.trackEndHandlers.get(track);
|
|
1773
|
+
if (!handler) return;
|
|
1774
|
+
track.removeEventListener("ended", handler);
|
|
1775
|
+
this.trackEndHandlers.delete(track);
|
|
1776
|
+
}
|
|
1777
|
+
unwatchStreamTracks() {
|
|
1778
|
+
for (const [track, handler] of this.trackEndHandlers) {
|
|
1779
|
+
track.removeEventListener("ended", handler);
|
|
1780
|
+
}
|
|
1781
|
+
this.trackEndHandlers.clear();
|
|
525
1782
|
}
|
|
526
1783
|
};
|
|
527
1784
|
|
|
@@ -549,9 +1806,22 @@ async function captureScreen(opts = {}) {
|
|
|
549
1806
|
const mediaDevices = opts.mediaDevices ?? navigator.mediaDevices;
|
|
550
1807
|
return mediaDevices.getDisplayMedia(constraints);
|
|
551
1808
|
}
|
|
1809
|
+
async function captureMicrophone(opts = {}) {
|
|
1810
|
+
const constraints = {
|
|
1811
|
+
audio: opts.audio ?? {
|
|
1812
|
+
echoCancellation: true,
|
|
1813
|
+
noiseSuppression: true,
|
|
1814
|
+
autoGainControl: true
|
|
1815
|
+
},
|
|
1816
|
+
video: false
|
|
1817
|
+
};
|
|
1818
|
+
const mediaDevices = opts.mediaDevices ?? navigator.mediaDevices;
|
|
1819
|
+
return mediaDevices.getUserMedia(constraints);
|
|
1820
|
+
}
|
|
552
1821
|
export {
|
|
553
1822
|
Publisher,
|
|
554
1823
|
captureCamera,
|
|
1824
|
+
captureMicrophone,
|
|
555
1825
|
captureScreen
|
|
556
1826
|
};
|
|
557
1827
|
//# sourceMappingURL=index.js.map
|