@micdrop/webrtc 0.0.0-stage → 0.1.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 +55 -2
- package/dist/WebRtcSpeaker-C4pG0yfh.d.mts +136 -0
- package/dist/WebRtcSpeaker-C4pG0yfh.d.ts +136 -0
- package/dist/index.d.mts +20 -0
- package/dist/index.d.ts +20 -0
- package/dist/index.js +454 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +436 -0
- package/dist/index.mjs.map +1 -0
- package/dist/protocol-Ba3tnNV7.d.mts +43 -0
- package/dist/protocol-Ba3tnNV7.d.ts +43 -0
- package/dist/react-native.d.mts +23 -0
- package/dist/react-native.d.ts +23 -0
- package/dist/react-native.js +402 -0
- package/dist/react-native.js.map +1 -0
- package/dist/react-native.mjs +379 -0
- package/dist/react-native.mjs.map +1 -0
- package/dist/server/index.d.mts +154 -0
- package/dist/server/index.d.ts +154 -0
- package/dist/server/index.js +417 -0
- package/dist/server/index.js.map +1 -0
- package/dist/server/index.mjs +383 -0
- package/dist/server/index.mjs.map +1 -0
- package/package.json +82 -4
|
@@ -0,0 +1,379 @@
|
|
|
1
|
+
// src/react-native.ts
|
|
2
|
+
import { mediaDevices, RTCPeerConnection } from "react-native-webrtc";
|
|
3
|
+
|
|
4
|
+
// src/client/WebRtcClientTransport.ts
|
|
5
|
+
import {
|
|
6
|
+
decodeServerMessage,
|
|
7
|
+
encodeClientMessage,
|
|
8
|
+
Mic,
|
|
9
|
+
MicdropClientTransport,
|
|
10
|
+
Speaker
|
|
11
|
+
} from "@micdrop/client";
|
|
12
|
+
|
|
13
|
+
// src/protocol.ts
|
|
14
|
+
var DATA_CHANNEL_LABEL = "micdrop";
|
|
15
|
+
var PLAYBACK_START = "PlaybackStart";
|
|
16
|
+
var PLAYBACK_STOP = "PlaybackStop";
|
|
17
|
+
function encodeStartSpeaking(preroll = 0) {
|
|
18
|
+
return preroll > 0 ? `StartSpeaking ${Math.round(preroll)}` : "StartSpeaking";
|
|
19
|
+
}
|
|
20
|
+
function decodeStartSpeaking(text) {
|
|
21
|
+
if (text === "StartSpeaking") return 0;
|
|
22
|
+
const match = /^StartSpeaking (\d+)$/.exec(text);
|
|
23
|
+
return match ? Number(match[1]) : void 0;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// src/client/WebRtcSpeaker.ts
|
|
27
|
+
import {
|
|
28
|
+
MicdropStorageKeys,
|
|
29
|
+
SpeakerDriver,
|
|
30
|
+
storage
|
|
31
|
+
} from "@micdrop/client";
|
|
32
|
+
var PLAYOUT_DELAY = 200;
|
|
33
|
+
var VOLUME_INTERVAL = 100;
|
|
34
|
+
var WebRtcSpeaker = class extends SpeakerDriver {
|
|
35
|
+
constructor() {
|
|
36
|
+
super(...arguments);
|
|
37
|
+
this.playing = false;
|
|
38
|
+
// Interrupted: what still arrives of the previous answer stays quiet
|
|
39
|
+
this.silenced = false;
|
|
40
|
+
}
|
|
41
|
+
get isPlaying() {
|
|
42
|
+
return this.playing;
|
|
43
|
+
}
|
|
44
|
+
get deviceId() {
|
|
45
|
+
return this._deviceId;
|
|
46
|
+
}
|
|
47
|
+
/** Plays through a player, once the remote track arrived */
|
|
48
|
+
attach(player) {
|
|
49
|
+
this.player = player;
|
|
50
|
+
player.setMuted(this.silenced);
|
|
51
|
+
const deviceId = this._deviceId ?? storage.getItem(MicdropStorageKeys.SpeakerDevice);
|
|
52
|
+
if (deviceId) {
|
|
53
|
+
player.setOutputDevice?.(deviceId).catch(() => void 0);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
/** The server started sending an answer */
|
|
57
|
+
playbackStarted() {
|
|
58
|
+
this.clearStopTimer();
|
|
59
|
+
if (this.silenced) {
|
|
60
|
+
this.silenced = false;
|
|
61
|
+
this.player?.setMuted(false);
|
|
62
|
+
}
|
|
63
|
+
this.setPlaying(true);
|
|
64
|
+
}
|
|
65
|
+
/** The server sent the last of the answer */
|
|
66
|
+
playbackStopped() {
|
|
67
|
+
this.clearStopTimer();
|
|
68
|
+
this.stopTimer = setTimeout(() => this.setPlaying(false), PLAYOUT_DELAY);
|
|
69
|
+
}
|
|
70
|
+
async start() {
|
|
71
|
+
}
|
|
72
|
+
// The voice arrives on the track, never as chunks
|
|
73
|
+
play() {
|
|
74
|
+
}
|
|
75
|
+
stopAudio() {
|
|
76
|
+
this.clearStopTimer();
|
|
77
|
+
this.silenced = true;
|
|
78
|
+
this.player?.setMuted(true);
|
|
79
|
+
this.setPlaying(false);
|
|
80
|
+
}
|
|
81
|
+
async stop() {
|
|
82
|
+
this.stopAudio();
|
|
83
|
+
}
|
|
84
|
+
async changeDevice(deviceId) {
|
|
85
|
+
await this.player?.setOutputDevice?.(deviceId);
|
|
86
|
+
this._deviceId = deviceId;
|
|
87
|
+
storage.setItem(MicdropStorageKeys.SpeakerDevice, deviceId);
|
|
88
|
+
}
|
|
89
|
+
async getDevices() {
|
|
90
|
+
return await this.player?.getOutputDevices?.() ?? [];
|
|
91
|
+
}
|
|
92
|
+
/** Lets go of the player, at the end of the call */
|
|
93
|
+
detach() {
|
|
94
|
+
this.clearStopTimer();
|
|
95
|
+
this.setPlaying(false);
|
|
96
|
+
this.player?.destroy();
|
|
97
|
+
this.player = void 0;
|
|
98
|
+
}
|
|
99
|
+
setPlaying(playing) {
|
|
100
|
+
if (playing === this.playing) return;
|
|
101
|
+
this.playing = playing;
|
|
102
|
+
if (playing) {
|
|
103
|
+
this.emit("StartPlaying");
|
|
104
|
+
this.volumeTimer = setInterval(() => {
|
|
105
|
+
const volume = this.player?.getVolume?.();
|
|
106
|
+
if (volume !== void 0) this.emit("Volume", volume);
|
|
107
|
+
}, VOLUME_INTERVAL);
|
|
108
|
+
} else {
|
|
109
|
+
if (this.volumeTimer) clearInterval(this.volumeTimer);
|
|
110
|
+
this.volumeTimer = void 0;
|
|
111
|
+
this.emit("StopPlaying");
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
clearStopTimer() {
|
|
115
|
+
if (!this.stopTimer) return;
|
|
116
|
+
clearTimeout(this.stopTimer);
|
|
117
|
+
this.stopTimer = void 0;
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
// src/client/WebRtcClientTransport.ts
|
|
122
|
+
var WebRtcClientTransport = class extends MicdropClientTransport {
|
|
123
|
+
constructor(options) {
|
|
124
|
+
super();
|
|
125
|
+
this.options = options;
|
|
126
|
+
this.sendsMic = true;
|
|
127
|
+
this.connectionTimeout = 15e3;
|
|
128
|
+
this.state = "idle";
|
|
129
|
+
this.muted = false;
|
|
130
|
+
this.speaker = new WebRtcSpeaker();
|
|
131
|
+
this.onMicStreamChange = () => {
|
|
132
|
+
this.options.platform.getMicTrack().then((mic) => {
|
|
133
|
+
if (this.state === "closed") return mic.release?.();
|
|
134
|
+
this.mic?.release?.();
|
|
135
|
+
this.mic = mic;
|
|
136
|
+
this.applyMicTrack();
|
|
137
|
+
}).catch((error) => {
|
|
138
|
+
console.error(
|
|
139
|
+
"[MicdropClient] The new microphone cannot be sent",
|
|
140
|
+
error
|
|
141
|
+
);
|
|
142
|
+
});
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
get isOpen() {
|
|
146
|
+
return this.state === "open";
|
|
147
|
+
}
|
|
148
|
+
get isConnecting() {
|
|
149
|
+
return this.state === "connecting";
|
|
150
|
+
}
|
|
151
|
+
// Read through a getter, an await can close the call under the compiler
|
|
152
|
+
get isClosed() {
|
|
153
|
+
return this.state === "closed";
|
|
154
|
+
}
|
|
155
|
+
connect(params) {
|
|
156
|
+
if (this.state !== "idle") return;
|
|
157
|
+
this.state = "connecting";
|
|
158
|
+
this.start(params).catch((error) => {
|
|
159
|
+
if (this.state === "closed") return;
|
|
160
|
+
console.error("[MicdropClient] WebRTC connection failed", error);
|
|
161
|
+
this.end({ code: 1006, reason: error?.message });
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
send(message) {
|
|
165
|
+
if (this.channel?.readyState !== "open") return;
|
|
166
|
+
this.channel.send(
|
|
167
|
+
message.type === "StartSpeaking" ? encodeStartSpeaking(message.preroll) : encodeClientMessage(message)
|
|
168
|
+
);
|
|
169
|
+
}
|
|
170
|
+
// The microphone goes on the track
|
|
171
|
+
sendAudio() {
|
|
172
|
+
}
|
|
173
|
+
setMicMuted(muted) {
|
|
174
|
+
if (muted === this.muted) return;
|
|
175
|
+
this.muted = muted;
|
|
176
|
+
this.applyMicTrack();
|
|
177
|
+
}
|
|
178
|
+
close() {
|
|
179
|
+
if (this.state === "closed") return;
|
|
180
|
+
this.state = "closed";
|
|
181
|
+
this.teardown();
|
|
182
|
+
}
|
|
183
|
+
async start(params) {
|
|
184
|
+
const { platform } = this.options;
|
|
185
|
+
const pc = new platform.RTCPeerConnection({
|
|
186
|
+
iceServers: this.options.iceServers ?? []
|
|
187
|
+
});
|
|
188
|
+
this.pc = pc;
|
|
189
|
+
this.mic = await platform.getMicTrack();
|
|
190
|
+
if (this.isClosed) return this.teardown();
|
|
191
|
+
this.sender = pc.addTrack(
|
|
192
|
+
this.mic.track,
|
|
193
|
+
...this.mic.stream ? [this.mic.stream] : []
|
|
194
|
+
);
|
|
195
|
+
if (this.muted) this.applyMicTrack();
|
|
196
|
+
Mic.on("StreamChange", this.onMicStreamChange);
|
|
197
|
+
const channel = pc.createDataChannel(DATA_CHANNEL_LABEL, { ordered: true });
|
|
198
|
+
this.channel = channel;
|
|
199
|
+
channel.onopen = () => this.onOpen();
|
|
200
|
+
channel.onmessage = (event) => {
|
|
201
|
+
const data = event.data;
|
|
202
|
+
this.onText(
|
|
203
|
+
typeof data === "string" ? data : new TextDecoder().decode(data)
|
|
204
|
+
);
|
|
205
|
+
};
|
|
206
|
+
channel.onclose = () => this.end({ code: 1006, reason: "Data channel closed" });
|
|
207
|
+
pc.ontrack = (event) => {
|
|
208
|
+
if (event.track?.kind !== "audio") return;
|
|
209
|
+
this.speaker.attach(
|
|
210
|
+
platform.createPlayer(event.track, event.streams?.[0])
|
|
211
|
+
);
|
|
212
|
+
};
|
|
213
|
+
pc.onconnectionstatechange = () => this.onConnectionState();
|
|
214
|
+
await pc.setLocalDescription(await pc.createOffer());
|
|
215
|
+
await this.waitForGathering();
|
|
216
|
+
if (this.isClosed) return;
|
|
217
|
+
const offer = {
|
|
218
|
+
type: "offer",
|
|
219
|
+
sdp: pc.localDescription.sdp,
|
|
220
|
+
...params ? { params } : {}
|
|
221
|
+
};
|
|
222
|
+
const response = await (platform.fetch ?? fetch)(this.options.url, {
|
|
223
|
+
method: "POST",
|
|
224
|
+
headers: { "Content-Type": "application/json", ...this.options.headers },
|
|
225
|
+
body: JSON.stringify(offer)
|
|
226
|
+
});
|
|
227
|
+
if (this.isClosed) return;
|
|
228
|
+
if (!response.ok) {
|
|
229
|
+
this.end({
|
|
230
|
+
code: closeCodeOfStatus(response.status),
|
|
231
|
+
reason: await response.text().catch(() => void 0)
|
|
232
|
+
});
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
const answer = await response.json();
|
|
236
|
+
if (this.isClosed) return;
|
|
237
|
+
await pc.setRemoteDescription(answer);
|
|
238
|
+
}
|
|
239
|
+
waitForGathering() {
|
|
240
|
+
const pc = this.pc;
|
|
241
|
+
if (pc.iceGatheringState === "complete") return Promise.resolve();
|
|
242
|
+
return new Promise((resolve) => {
|
|
243
|
+
const timer = setTimeout(resolve, this.options.gatheringTimeout ?? 2e3);
|
|
244
|
+
pc.onicegatheringstatechange = () => {
|
|
245
|
+
if (pc.iceGatheringState !== "complete") return;
|
|
246
|
+
clearTimeout(timer);
|
|
247
|
+
resolve();
|
|
248
|
+
};
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
onOpen() {
|
|
252
|
+
if (this.state !== "connecting") return;
|
|
253
|
+
this.state = "open";
|
|
254
|
+
try {
|
|
255
|
+
this.previousSpeaker = Speaker.getDriver();
|
|
256
|
+
} catch {
|
|
257
|
+
this.previousSpeaker = void 0;
|
|
258
|
+
}
|
|
259
|
+
Speaker.setDriver(this.speaker);
|
|
260
|
+
this.emit("Open");
|
|
261
|
+
}
|
|
262
|
+
onText(text) {
|
|
263
|
+
if (text === PLAYBACK_START) {
|
|
264
|
+
this.speaker.playbackStarted();
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
if (text === PLAYBACK_STOP) {
|
|
268
|
+
this.speaker.playbackStopped();
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
const close = /^Close (\d+)(?: (.*))?$/.exec(text);
|
|
272
|
+
if (close) {
|
|
273
|
+
this.end({ code: Number(close[1]), reason: close[2] });
|
|
274
|
+
return;
|
|
275
|
+
}
|
|
276
|
+
let message;
|
|
277
|
+
try {
|
|
278
|
+
message = decodeServerMessage(text);
|
|
279
|
+
} catch (error) {
|
|
280
|
+
console.error("[MicdropClient] Error parsing message:", text, error);
|
|
281
|
+
return;
|
|
282
|
+
}
|
|
283
|
+
if (message?.type === "SampleRate") return;
|
|
284
|
+
if (message) this.emit("Message", message);
|
|
285
|
+
}
|
|
286
|
+
onConnectionState() {
|
|
287
|
+
const state = this.pc?.connectionState;
|
|
288
|
+
if (state === "connected") {
|
|
289
|
+
if (this.disconnectTimer) clearTimeout(this.disconnectTimer);
|
|
290
|
+
this.disconnectTimer = void 0;
|
|
291
|
+
} else if (state === "disconnected") {
|
|
292
|
+
this.disconnectTimer ?? (this.disconnectTimer = setTimeout(
|
|
293
|
+
() => this.end({ code: 1006, reason: "Connection lost" }),
|
|
294
|
+
this.options.disconnectTimeout ?? 5e3
|
|
295
|
+
));
|
|
296
|
+
} else if (state === "failed") {
|
|
297
|
+
this.end({ code: 1006, reason: "Connection failed" });
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
/** Sends the microphone, or nothing at all while muted */
|
|
301
|
+
applyMicTrack() {
|
|
302
|
+
const track = this.mic?.track;
|
|
303
|
+
if (track) track.enabled = !this.muted;
|
|
304
|
+
if (!this.sender) return;
|
|
305
|
+
Promise.resolve(this.sender.replaceTrack(this.muted ? null : track)).catch(
|
|
306
|
+
() => void 0
|
|
307
|
+
);
|
|
308
|
+
}
|
|
309
|
+
/** The call ended on the other side, or failed */
|
|
310
|
+
end(event) {
|
|
311
|
+
if (this.state === "closed") return;
|
|
312
|
+
this.state = "closed";
|
|
313
|
+
this.teardown();
|
|
314
|
+
this.emit("Close", event);
|
|
315
|
+
}
|
|
316
|
+
teardown() {
|
|
317
|
+
if (this.disconnectTimer) clearTimeout(this.disconnectTimer);
|
|
318
|
+
Mic.off("StreamChange", this.onMicStreamChange);
|
|
319
|
+
if (this.channel) {
|
|
320
|
+
this.channel.onclose = null;
|
|
321
|
+
this.channel.onmessage = null;
|
|
322
|
+
}
|
|
323
|
+
try {
|
|
324
|
+
this.pc?.close();
|
|
325
|
+
} catch {
|
|
326
|
+
}
|
|
327
|
+
this.mic?.release?.();
|
|
328
|
+
this.speaker.detach();
|
|
329
|
+
try {
|
|
330
|
+
if (Speaker.getDriver() === this.speaker && this.previousSpeaker) {
|
|
331
|
+
Speaker.setDriver(this.previousSpeaker);
|
|
332
|
+
}
|
|
333
|
+
} catch {
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
};
|
|
337
|
+
function closeCodeOfStatus(status) {
|
|
338
|
+
if (status === 400) return 4400;
|
|
339
|
+
if (status === 401 || status === 403) return 4401;
|
|
340
|
+
if (status === 404) return 4404;
|
|
341
|
+
if (status >= 500) return 1011;
|
|
342
|
+
return 1006;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
// src/react-native.ts
|
|
346
|
+
var reactNativePlatform = {
|
|
347
|
+
RTCPeerConnection,
|
|
348
|
+
async getMicTrack() {
|
|
349
|
+
const stream = await mediaDevices.getUserMedia({ audio: true });
|
|
350
|
+
return {
|
|
351
|
+
track: stream.getAudioTracks()[0],
|
|
352
|
+
stream,
|
|
353
|
+
release: () => stream.getTracks().forEach((track) => track.stop())
|
|
354
|
+
};
|
|
355
|
+
},
|
|
356
|
+
createPlayer(track) {
|
|
357
|
+
return {
|
|
358
|
+
setMuted: (muted) => {
|
|
359
|
+
track.enabled = !muted;
|
|
360
|
+
},
|
|
361
|
+
destroy: () => void 0
|
|
362
|
+
};
|
|
363
|
+
}
|
|
364
|
+
};
|
|
365
|
+
function webRtcTransport(options) {
|
|
366
|
+
return () => new WebRtcClientTransport({ ...options, platform: reactNativePlatform });
|
|
367
|
+
}
|
|
368
|
+
export {
|
|
369
|
+
DATA_CHANNEL_LABEL,
|
|
370
|
+
PLAYBACK_START,
|
|
371
|
+
PLAYBACK_STOP,
|
|
372
|
+
WebRtcClientTransport,
|
|
373
|
+
WebRtcSpeaker,
|
|
374
|
+
decodeStartSpeaking,
|
|
375
|
+
encodeStartSpeaking,
|
|
376
|
+
reactNativePlatform,
|
|
377
|
+
webRtcTransport
|
|
378
|
+
};
|
|
379
|
+
//# sourceMappingURL=react-native.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/react-native.ts","../src/client/WebRtcClientTransport.ts","../src/protocol.ts","../src/client/WebRtcSpeaker.ts"],"sourcesContent":["import type { MicdropClientTransportFactory } from '@micdrop/client'\nimport { mediaDevices, RTCPeerConnection } from 'react-native-webrtc'\nimport {\n WebRtcClientOptions,\n WebRtcClientTransport,\n WebRtcPlatform,\n} from './client'\n\nexport * from './client'\nexport * from './protocol'\n\n/**\n * WebRTC on a phone, from react-native-webrtc.\n *\n * The native Micdrop microphone hands no stream over, so the call opens its\n * own track. Without the samples, the client cannot find the turns from it:\n * the server detects them, with `vad` in its config. The voice of the\n * assistant plays on its own, as every remote track does with\n * react-native-webrtc.\n */\nexport const reactNativePlatform: WebRtcPlatform = {\n RTCPeerConnection: RTCPeerConnection as any,\n\n async getMicTrack() {\n const stream = await mediaDevices.getUserMedia({ audio: true })\n return {\n track: stream.getAudioTracks()[0],\n stream,\n release: () => stream.getTracks().forEach((track) => track.stop()),\n }\n },\n\n createPlayer(track) {\n return {\n setMuted: (muted) => {\n track.enabled = !muted\n },\n destroy: () => undefined,\n }\n },\n}\n\n/**\n * Creates the transport of each call, to hand to `MicdropClient` as\n * `transport`\n * @param options - Address of the offer, headers and ICE servers\n */\nexport function webRtcTransport(\n options: WebRtcClientOptions\n): MicdropClientTransportFactory {\n return () =>\n new WebRtcClientTransport({ ...options, platform: reactNativePlatform })\n}\n","import {\n decodeServerMessage,\n encodeClientMessage,\n Mic,\n MicdropClientMessage,\n MicdropClientTransport,\n Speaker,\n SpeakerDriver,\n} from '@micdrop/client'\nimport {\n DATA_CHANNEL_LABEL,\n encodeStartSpeaking,\n MicdropWebRtcAnswer,\n MicdropWebRtcOffer,\n PLAYBACK_START,\n PLAYBACK_STOP,\n} from '../protocol'\nimport type { WebRtcMicTrack, WebRtcPlatform } from './platform'\nimport { WebRtcSpeaker } from './WebRtcSpeaker'\n\nexport interface WebRtcClientOptions {\n /** Address the offer is posted to, where the server answers it */\n url: string\n /** Headers of that request, to authenticate the call for instance */\n headers?: Record<string, string>\n /** STUN and TURN servers, the user behind a strict network needs TURN */\n iceServers?: {\n urls: string | string[]\n username?: string\n credential?: string\n }[]\n /** How long the browser gathers its candidates before posting, 2000 ms */\n gatheringTimeout?: number\n /** How long a lost connection may take to come back, 5000 ms */\n disconnectTimeout?: number\n}\n\n/**\n * Carries a call to a `WebRtcTransport` of `@micdrop/webrtc/server`: the\n * microphone as an Opus track, the assistant voice on the track the server\n * sends back, and the Micdrop protocol on a data channel.\n *\n * The client keeps detecting the turns on its microphone, and the server\n * takes the beginning of each turn back from the track. Told `ServerTurns`,\n * the client leaves the turns to the server, as over a WebSocket.\n */\nexport class WebRtcClientTransport extends MicdropClientTransport {\n readonly sendsMic = true\n readonly connectionTimeout = 15000\n\n private state: 'idle' | 'connecting' | 'open' | 'closed' = 'idle'\n private pc?: any\n private channel?: any\n private mic?: WebRtcMicTrack\n private sender?: any\n private muted = false\n private speaker = new WebRtcSpeaker()\n private previousSpeaker?: SpeakerDriver\n private disconnectTimer?: ReturnType<typeof setTimeout>\n\n constructor(\n private options: WebRtcClientOptions & { platform: WebRtcPlatform }\n ) {\n super()\n }\n\n get isOpen(): boolean {\n return this.state === 'open'\n }\n\n get isConnecting(): boolean {\n return this.state === 'connecting'\n }\n\n // Read through a getter, an await can close the call under the compiler\n private get isClosed(): boolean {\n return this.state === 'closed'\n }\n\n connect(params?: Record<string, any>) {\n if (this.state !== 'idle') return\n this.state = 'connecting'\n this.start(params).catch((error) => {\n if (this.state === 'closed') return\n console.error('[MicdropClient] WebRTC connection failed', error)\n this.end({ code: 1006, reason: error?.message })\n })\n }\n\n send(message: MicdropClientMessage) {\n if (this.channel?.readyState !== 'open') return\n this.channel.send(\n message.type === 'StartSpeaking'\n ? encodeStartSpeaking(message.preroll)\n : encodeClientMessage(message)\n )\n }\n\n // The microphone goes on the track\n sendAudio() {}\n\n setMicMuted(muted: boolean) {\n if (muted === this.muted) return\n this.muted = muted\n this.applyMicTrack()\n }\n\n close() {\n if (this.state === 'closed') return\n this.state = 'closed'\n this.teardown()\n }\n\n private async start(params?: Record<string, any>) {\n const { platform } = this.options\n const pc = new platform.RTCPeerConnection({\n iceServers: this.options.iceServers ?? [],\n })\n this.pc = pc\n\n this.mic = await platform.getMicTrack()\n if (this.isClosed) return this.teardown()\n this.sender = pc.addTrack(\n this.mic.track,\n ...(this.mic.stream ? [this.mic.stream] : [])\n )\n if (this.muted) this.applyMicTrack()\n Mic.on('StreamChange', this.onMicStreamChange)\n\n const channel = pc.createDataChannel(DATA_CHANNEL_LABEL, { ordered: true })\n this.channel = channel\n channel.onopen = () => this.onOpen()\n channel.onmessage = (event: { data: unknown }) => {\n const data = event.data\n this.onText(\n typeof data === 'string'\n ? data\n : new TextDecoder().decode(data as ArrayBuffer)\n )\n }\n channel.onclose = () =>\n this.end({ code: 1006, reason: 'Data channel closed' })\n\n pc.ontrack = (event: { track: any; streams?: any[] }) => {\n if (event.track?.kind !== 'audio') return\n this.speaker.attach(\n platform.createPlayer(event.track, event.streams?.[0])\n )\n }\n pc.onconnectionstatechange = () => this.onConnectionState()\n\n await pc.setLocalDescription(await pc.createOffer())\n await this.waitForGathering()\n if (this.isClosed) return\n\n const offer: MicdropWebRtcOffer = {\n type: 'offer',\n sdp: pc.localDescription.sdp,\n ...(params ? { params } : {}),\n }\n const response = await (platform.fetch ?? fetch)(this.options.url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...this.options.headers },\n body: JSON.stringify(offer),\n })\n if (this.isClosed) return\n if (!response.ok) {\n this.end({\n code: closeCodeOfStatus(response.status),\n reason: await response.text().catch(() => undefined),\n })\n return\n }\n const answer = (await response.json()) as MicdropWebRtcAnswer\n if (this.isClosed) return\n await pc.setRemoteDescription(answer)\n }\n\n private waitForGathering(): Promise<void> {\n const pc = this.pc\n if (pc.iceGatheringState === 'complete') return Promise.resolve()\n return new Promise((resolve) => {\n const timer = setTimeout(resolve, this.options.gatheringTimeout ?? 2000)\n pc.onicegatheringstatechange = () => {\n if (pc.iceGatheringState !== 'complete') return\n clearTimeout(timer)\n resolve()\n }\n })\n }\n\n private onOpen() {\n if (this.state !== 'connecting') return\n this.state = 'open'\n // The voice of the call plays through its track while it lasts\n try {\n this.previousSpeaker = Speaker.getDriver()\n } catch {\n this.previousSpeaker = undefined\n }\n Speaker.setDriver(this.speaker)\n this.emit('Open')\n }\n\n private onText(text: string) {\n if (text === PLAYBACK_START) {\n this.speaker.playbackStarted()\n return\n }\n if (text === PLAYBACK_STOP) {\n this.speaker.playbackStopped()\n return\n }\n const close = /^Close (\\d+)(?: (.*))?$/.exec(text)\n if (close) {\n this.end({ code: Number(close[1]), reason: close[2] })\n return\n }\n let message\n try {\n message = decodeServerMessage(text)\n } catch (error) {\n console.error('[MicdropClient] Error parsing message:', text, error)\n return\n }\n if (message?.type === 'SampleRate') return\n if (message) this.emit('Message', message)\n }\n\n private onConnectionState() {\n const state = this.pc?.connectionState\n if (state === 'connected') {\n if (this.disconnectTimer) clearTimeout(this.disconnectTimer)\n this.disconnectTimer = undefined\n } else if (state === 'disconnected') {\n this.disconnectTimer ??= setTimeout(\n () => this.end({ code: 1006, reason: 'Connection lost' }),\n this.options.disconnectTimeout ?? 5000\n )\n } else if (state === 'failed') {\n this.end({ code: 1006, reason: 'Connection failed' })\n }\n }\n\n private onMicStreamChange = () => {\n this.options.platform\n .getMicTrack()\n .then((mic) => {\n if (this.state === 'closed') return mic.release?.()\n this.mic?.release?.()\n this.mic = mic\n this.applyMicTrack()\n })\n .catch((error) => {\n console.error(\n '[MicdropClient] The new microphone cannot be sent',\n error\n )\n })\n }\n\n /** Sends the microphone, or nothing at all while muted */\n private applyMicTrack() {\n const track = this.mic?.track\n // A disabled track sends silence on every platform, even where replacing\n // it with nothing is not supported\n if (track) track.enabled = !this.muted\n if (!this.sender) return\n Promise.resolve(this.sender.replaceTrack(this.muted ? null : track)).catch(\n () => undefined\n )\n }\n\n /** The call ended on the other side, or failed */\n private end(event: { code?: number; reason?: string }) {\n if (this.state === 'closed') return\n this.state = 'closed'\n this.teardown()\n this.emit('Close', event)\n }\n\n private teardown() {\n if (this.disconnectTimer) clearTimeout(this.disconnectTimer)\n Mic.off('StreamChange', this.onMicStreamChange)\n if (this.channel) {\n this.channel.onclose = null\n this.channel.onmessage = null\n }\n try {\n this.pc?.close()\n } catch {\n // Already closed\n }\n this.mic?.release?.()\n this.speaker.detach()\n // Gives the speaker back to the platform, unless another call took it\n try {\n if (Speaker.getDriver() === this.speaker && this.previousSpeaker) {\n Speaker.setDriver(this.previousSpeaker)\n }\n } catch {\n // No speaker driver at all\n }\n }\n}\n\n/** The close code a WebSocket server would have given for the same refusal */\nfunction closeCodeOfStatus(status: number): number {\n if (status === 400) return 4400\n if (status === 401 || status === 403) return 4401\n if (status === 404) return 4404\n if (status >= 500) return 1011\n return 1006\n}\n","/**\n * What travels between the WebRTC client and server besides the audio.\n *\n * The offer goes to the server with an HTTP POST, the answer comes back in its\n * response, and the call then runs on a data channel named\n * {@link DATA_CHANNEL_LABEL}. It carries the text messages of the Micdrop\n * protocol, the same as a WebSocket, and the few below that only a transport\n * carrying the audio as a track needs.\n */\n\n/** Label of the data channel of a call */\nexport const DATA_CHANNEL_LABEL = 'micdrop'\n\n/** What the client posts to start a call */\nexport interface MicdropWebRtcOffer {\n type: 'offer'\n sdp: string\n /** Parameters of the call, which `waitForParams` hands back */\n params?: Record<string, any>\n}\n\n/** What the server answers */\nexport interface MicdropWebRtcAnswer {\n type: 'answer'\n sdp: string\n}\n\n/**\n * The server started sending the assistant voice. A WebSocket client knows it\n * from the chunks it plays, a WebRTC one only hears a track.\n */\nexport const PLAYBACK_START = 'PlaybackStart'\n\n/** The server sent the last of the assistant voice */\nexport const PLAYBACK_STOP = 'PlaybackStop'\n\n/**\n * Writes the start of a turn with the audio before it that belongs to it,\n * which the server takes back from the stream of the track\n * @param preroll - Duration of that audio, in ms\n */\nexport function encodeStartSpeaking(preroll = 0): string {\n return preroll > 0 ? `StartSpeaking ${Math.round(preroll)}` : 'StartSpeaking'\n}\n\n/**\n * Reads a start of turn written by {@link encodeStartSpeaking}\n * @returns The preroll in ms, or undefined when the text is something else\n */\nexport function decodeStartSpeaking(text: string): number | undefined {\n if (text === 'StartSpeaking') return 0\n const match = /^StartSpeaking (\\d+)$/.exec(text)\n return match ? Number(match[1]) : undefined\n}\n","import {\n MicdropDevice,\n MicdropStorageKeys,\n SpeakerDriver,\n storage,\n} from '@micdrop/client'\nimport type { WebRtcPlayer } from './platform'\n\n// The client plays the last frame sent about this long after the server says\n// it is done, once it went through the network and the jitter buffer\nconst PLAYOUT_DELAY = 200 // ms\nconst VOLUME_INTERVAL = 100 // ms\n\n/**\n * The speaker of a call on WebRTC.\n *\n * The voice arrives as a track the platform plays on its own, so nothing is\n * queued here: the server says when it starts and stops sending, and an\n * interruption mutes the track until the next answer starts.\n */\nexport class WebRtcSpeaker extends SpeakerDriver {\n private player?: WebRtcPlayer\n private playing = false\n // Interrupted: what still arrives of the previous answer stays quiet\n private silenced = false\n private stopTimer?: ReturnType<typeof setTimeout>\n private volumeTimer?: ReturnType<typeof setInterval>\n private _deviceId: string | undefined\n\n get isPlaying(): boolean {\n return this.playing\n }\n\n get deviceId(): string | undefined {\n return this._deviceId\n }\n\n /** Plays through a player, once the remote track arrived */\n attach(player: WebRtcPlayer) {\n this.player = player\n player.setMuted(this.silenced)\n const deviceId =\n this._deviceId ?? storage.getItem(MicdropStorageKeys.SpeakerDevice)\n if (deviceId) {\n player.setOutputDevice?.(deviceId).catch(() => undefined)\n }\n }\n\n /** The server started sending an answer */\n playbackStarted() {\n this.clearStopTimer()\n if (this.silenced) {\n this.silenced = false\n this.player?.setMuted(false)\n }\n this.setPlaying(true)\n }\n\n /** The server sent the last of the answer */\n playbackStopped() {\n this.clearStopTimer()\n this.stopTimer = setTimeout(() => this.setPlaying(false), PLAYOUT_DELAY)\n }\n\n async start() {}\n\n // The voice arrives on the track, never as chunks\n play() {}\n\n stopAudio() {\n this.clearStopTimer()\n this.silenced = true\n this.player?.setMuted(true)\n this.setPlaying(false)\n }\n\n async stop() {\n this.stopAudio()\n }\n\n async changeDevice(deviceId: string) {\n await this.player?.setOutputDevice?.(deviceId)\n this._deviceId = deviceId\n storage.setItem(MicdropStorageKeys.SpeakerDevice, deviceId)\n }\n\n async getDevices(): Promise<MicdropDevice[]> {\n return (await this.player?.getOutputDevices?.()) ?? []\n }\n\n /** Lets go of the player, at the end of the call */\n detach() {\n this.clearStopTimer()\n this.setPlaying(false)\n this.player?.destroy()\n this.player = undefined\n }\n\n private setPlaying(playing: boolean) {\n if (playing === this.playing) return\n this.playing = playing\n if (playing) {\n this.emit('StartPlaying')\n this.volumeTimer = setInterval(() => {\n const volume = this.player?.getVolume?.()\n if (volume !== undefined) this.emit('Volume', volume)\n }, VOLUME_INTERVAL)\n } else {\n if (this.volumeTimer) clearInterval(this.volumeTimer)\n this.volumeTimer = undefined\n this.emit('StopPlaying')\n }\n }\n\n private clearStopTimer() {\n if (!this.stopTimer) return\n clearTimeout(this.stopTimer)\n this.stopTimer = undefined\n }\n}\n"],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,SAAS,UAAU,oBAAoB,CAAC;AAC3E;","names":[]}
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import { M as MicdropWebRtcAnswer, a as MicdropWebRtcOffer } from '../protocol-Ba3tnNV7.mjs';
|
|
2
|
+
export { D as DATA_CHANNEL_LABEL, P as PLAYBACK_START, b as PLAYBACK_STOP, d as decodeStartSpeaking, e as encodeStartSpeaking } from '../protocol-Ba3tnNV7.mjs';
|
|
3
|
+
import { MicdropTransport, MicdropServerMessage } from '@micdrop/server';
|
|
4
|
+
import { RTCPeerConnectionConfig } from 'werift';
|
|
5
|
+
|
|
6
|
+
/** Rate of the audio the encoder takes, and of the RTP clock of Opus */
|
|
7
|
+
declare const OPUS_SAMPLE_RATE = 48000;
|
|
8
|
+
/** Samples in one frame of 20 ms at 48 kHz */
|
|
9
|
+
declare const OPUS_FRAME_SAMPLES = 960;
|
|
10
|
+
/** Rate the decoder hands the user audio at, the one of the server */
|
|
11
|
+
declare const OPUS_DECODE_RATE = 16000;
|
|
12
|
+
/**
|
|
13
|
+
* Encodes the assistant voice and decodes the user, one per call.
|
|
14
|
+
*
|
|
15
|
+
* The default runs libopus compiled to WebAssembly, with nothing to build.
|
|
16
|
+
* A server that holds many calls can bring a native binding instead.
|
|
17
|
+
*/
|
|
18
|
+
interface OpusCodec {
|
|
19
|
+
/**
|
|
20
|
+
* Encodes one frame
|
|
21
|
+
* @param pcm - 960 samples of PCM16 mono at 48 kHz, 20 ms
|
|
22
|
+
* @returns One Opus packet
|
|
23
|
+
*/
|
|
24
|
+
encode(pcm: Buffer): Buffer;
|
|
25
|
+
/**
|
|
26
|
+
* Decodes one packet
|
|
27
|
+
* @param packet - An Opus packet, mono or stereo
|
|
28
|
+
* @returns PCM16 mono at 16 kHz
|
|
29
|
+
*/
|
|
30
|
+
decode(packet: Buffer): Buffer;
|
|
31
|
+
/** Releases the codec */
|
|
32
|
+
destroy(): void;
|
|
33
|
+
}
|
|
34
|
+
/** Creates the codec of a call */
|
|
35
|
+
type OpusCodecFactory = () => OpusCodec;
|
|
36
|
+
/** The codec on libopus compiled to WebAssembly, through opusscript */
|
|
37
|
+
declare function createOpusScriptCodec(): OpusCodec;
|
|
38
|
+
|
|
39
|
+
interface WebRtcIceServer {
|
|
40
|
+
urls: string | string[];
|
|
41
|
+
username?: string;
|
|
42
|
+
credential?: string;
|
|
43
|
+
}
|
|
44
|
+
interface WebRtcTransportOptions {
|
|
45
|
+
/**
|
|
46
|
+
* STUN and TURN servers. A server with a public address needs none, one
|
|
47
|
+
* behind a NAT needs a STUN server to learn its address, and the users on
|
|
48
|
+
* networks that block UDP need a TURN server.
|
|
49
|
+
*/
|
|
50
|
+
iceServers?: WebRtcIceServer[];
|
|
51
|
+
/** Creates the Opus codec of each call, libopus in WebAssembly by default */
|
|
52
|
+
codec?: OpusCodecFactory;
|
|
53
|
+
/**
|
|
54
|
+
* More options of the werift peer connection: `icePortRange` to open only
|
|
55
|
+
* a few UDP ports, `iceAdditionalHostAddresses` to announce the public
|
|
56
|
+
* address of a server behind a NAT
|
|
57
|
+
*/
|
|
58
|
+
peerConfig?: RTCPeerConnectionConfig;
|
|
59
|
+
/** How long the server gathers its candidates before answering, 3000 ms */
|
|
60
|
+
gatheringTimeout?: number;
|
|
61
|
+
/** How long a lost connection may take to come back before the call ends, 5000 ms */
|
|
62
|
+
disconnectTimeout?: number;
|
|
63
|
+
/**
|
|
64
|
+
* How long the client has to open the call once answered, 15000 ms. A
|
|
65
|
+
* client that never connects, behind a network that blocks it for
|
|
66
|
+
* instance, ends the call rather than holding it open.
|
|
67
|
+
*/
|
|
68
|
+
connectTimeout?: number;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* A call carried by WebRTC: the user and the assistant as Opus audio tracks,
|
|
72
|
+
* the Micdrop protocol on a data channel.
|
|
73
|
+
*
|
|
74
|
+
* It holds up better than a WebSocket on a weak network, a lost packet being
|
|
75
|
+
* skipped rather than resent, and the browser cancels the echo of an audio
|
|
76
|
+
* track better than that of audio it plays itself. It runs on werift, an
|
|
77
|
+
* implementation of WebRTC in TypeScript, with nothing native to build.
|
|
78
|
+
*
|
|
79
|
+
* The client posts its offer to the server, which answers with
|
|
80
|
+
* {@link WebRtcTransport.accept}:
|
|
81
|
+
*
|
|
82
|
+
* ```ts
|
|
83
|
+
* app.post('/call', async (req, res) => {
|
|
84
|
+
* const transport = await WebRtcTransport.accept(req.body)
|
|
85
|
+
* res.json(transport.answer)
|
|
86
|
+
* new MicdropServer(transport, config)
|
|
87
|
+
* })
|
|
88
|
+
* ```
|
|
89
|
+
*/
|
|
90
|
+
declare class WebRtcTransport extends MicdropTransport {
|
|
91
|
+
private options;
|
|
92
|
+
readonly clientTurns = true;
|
|
93
|
+
/** What to send back to the client, once accepted */
|
|
94
|
+
answer: MicdropWebRtcAnswer;
|
|
95
|
+
private pc;
|
|
96
|
+
private outputTrack;
|
|
97
|
+
private channel?;
|
|
98
|
+
private codec;
|
|
99
|
+
private closed;
|
|
100
|
+
private pendingMessages;
|
|
101
|
+
private frames;
|
|
102
|
+
private remainder;
|
|
103
|
+
private resampler?;
|
|
104
|
+
private resamplerRate;
|
|
105
|
+
private playing;
|
|
106
|
+
private pacer?;
|
|
107
|
+
private nextFrameAt;
|
|
108
|
+
private payloadType;
|
|
109
|
+
private readonly ssrc;
|
|
110
|
+
private sequenceNumber;
|
|
111
|
+
private timestamp;
|
|
112
|
+
private lastSequence?;
|
|
113
|
+
private preroll;
|
|
114
|
+
private prerollBytes;
|
|
115
|
+
private disconnectTimer?;
|
|
116
|
+
private connectTimer?;
|
|
117
|
+
private constructor();
|
|
118
|
+
/**
|
|
119
|
+
* Answers the offer of a client
|
|
120
|
+
* @param offer - What the client posted, its parameters included
|
|
121
|
+
* @param options - ICE servers, codec and network settings
|
|
122
|
+
* @returns The transport of the call, with the `answer` to send back
|
|
123
|
+
*/
|
|
124
|
+
static accept(offer: MicdropWebRtcOffer, options?: WebRtcTransportOptions): Promise<WebRtcTransport>;
|
|
125
|
+
get isOpen(): boolean;
|
|
126
|
+
send(message: MicdropServerMessage): void;
|
|
127
|
+
sendAudio(audio: Buffer, sampleRate: number): void;
|
|
128
|
+
clearAudio(): void;
|
|
129
|
+
waitForPlayback(): Promise<void>;
|
|
130
|
+
close(code?: number, reason?: string): void;
|
|
131
|
+
private negotiate;
|
|
132
|
+
/**
|
|
133
|
+
* Resolves once the candidates are gathered. werift does not always say
|
|
134
|
+
* so, so a pause in the flow of candidates counts as the end: they all
|
|
135
|
+
* arrive within a few tens of milliseconds, the reflexive ones included.
|
|
136
|
+
*/
|
|
137
|
+
private trackGathering;
|
|
138
|
+
private attachChannel;
|
|
139
|
+
private onConnectionState;
|
|
140
|
+
private onText;
|
|
141
|
+
private onRtp;
|
|
142
|
+
private receiveAudio;
|
|
143
|
+
/** The last `duration` ms of user audio */
|
|
144
|
+
private takePreroll;
|
|
145
|
+
private startPacer;
|
|
146
|
+
/** Sends every frame due, silence when the assistant is quiet */
|
|
147
|
+
private pace;
|
|
148
|
+
private sendFrame;
|
|
149
|
+
private setPlaying;
|
|
150
|
+
private sendText;
|
|
151
|
+
private finish;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export { MicdropWebRtcAnswer, MicdropWebRtcOffer, OPUS_DECODE_RATE, OPUS_FRAME_SAMPLES, OPUS_SAMPLE_RATE, type OpusCodec, type OpusCodecFactory, type WebRtcIceServer, WebRtcTransport, type WebRtcTransportOptions, createOpusScriptCodec };
|