@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
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,436 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import {
|
|
3
|
+
getVolume,
|
|
4
|
+
Mic as Mic2,
|
|
5
|
+
resample,
|
|
6
|
+
VOLUME_SAMPLE_RATE
|
|
7
|
+
} from "@micdrop/client";
|
|
8
|
+
|
|
9
|
+
// src/client/WebRtcClientTransport.ts
|
|
10
|
+
import {
|
|
11
|
+
decodeServerMessage,
|
|
12
|
+
encodeClientMessage,
|
|
13
|
+
Mic,
|
|
14
|
+
MicdropClientTransport,
|
|
15
|
+
Speaker
|
|
16
|
+
} from "@micdrop/client";
|
|
17
|
+
|
|
18
|
+
// src/protocol.ts
|
|
19
|
+
var DATA_CHANNEL_LABEL = "micdrop";
|
|
20
|
+
var PLAYBACK_START = "PlaybackStart";
|
|
21
|
+
var PLAYBACK_STOP = "PlaybackStop";
|
|
22
|
+
function encodeStartSpeaking(preroll = 0) {
|
|
23
|
+
return preroll > 0 ? `StartSpeaking ${Math.round(preroll)}` : "StartSpeaking";
|
|
24
|
+
}
|
|
25
|
+
function decodeStartSpeaking(text) {
|
|
26
|
+
if (text === "StartSpeaking") return 0;
|
|
27
|
+
const match = /^StartSpeaking (\d+)$/.exec(text);
|
|
28
|
+
return match ? Number(match[1]) : void 0;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// src/client/WebRtcSpeaker.ts
|
|
32
|
+
import {
|
|
33
|
+
MicdropStorageKeys,
|
|
34
|
+
SpeakerDriver,
|
|
35
|
+
storage
|
|
36
|
+
} from "@micdrop/client";
|
|
37
|
+
var PLAYOUT_DELAY = 200;
|
|
38
|
+
var VOLUME_INTERVAL = 100;
|
|
39
|
+
var WebRtcSpeaker = class extends SpeakerDriver {
|
|
40
|
+
constructor() {
|
|
41
|
+
super(...arguments);
|
|
42
|
+
this.playing = false;
|
|
43
|
+
// Interrupted: what still arrives of the previous answer stays quiet
|
|
44
|
+
this.silenced = false;
|
|
45
|
+
}
|
|
46
|
+
get isPlaying() {
|
|
47
|
+
return this.playing;
|
|
48
|
+
}
|
|
49
|
+
get deviceId() {
|
|
50
|
+
return this._deviceId;
|
|
51
|
+
}
|
|
52
|
+
/** Plays through a player, once the remote track arrived */
|
|
53
|
+
attach(player) {
|
|
54
|
+
this.player = player;
|
|
55
|
+
player.setMuted(this.silenced);
|
|
56
|
+
const deviceId = this._deviceId ?? storage.getItem(MicdropStorageKeys.SpeakerDevice);
|
|
57
|
+
if (deviceId) {
|
|
58
|
+
player.setOutputDevice?.(deviceId).catch(() => void 0);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
/** The server started sending an answer */
|
|
62
|
+
playbackStarted() {
|
|
63
|
+
this.clearStopTimer();
|
|
64
|
+
if (this.silenced) {
|
|
65
|
+
this.silenced = false;
|
|
66
|
+
this.player?.setMuted(false);
|
|
67
|
+
}
|
|
68
|
+
this.setPlaying(true);
|
|
69
|
+
}
|
|
70
|
+
/** The server sent the last of the answer */
|
|
71
|
+
playbackStopped() {
|
|
72
|
+
this.clearStopTimer();
|
|
73
|
+
this.stopTimer = setTimeout(() => this.setPlaying(false), PLAYOUT_DELAY);
|
|
74
|
+
}
|
|
75
|
+
async start() {
|
|
76
|
+
}
|
|
77
|
+
// The voice arrives on the track, never as chunks
|
|
78
|
+
play() {
|
|
79
|
+
}
|
|
80
|
+
stopAudio() {
|
|
81
|
+
this.clearStopTimer();
|
|
82
|
+
this.silenced = true;
|
|
83
|
+
this.player?.setMuted(true);
|
|
84
|
+
this.setPlaying(false);
|
|
85
|
+
}
|
|
86
|
+
async stop() {
|
|
87
|
+
this.stopAudio();
|
|
88
|
+
}
|
|
89
|
+
async changeDevice(deviceId) {
|
|
90
|
+
await this.player?.setOutputDevice?.(deviceId);
|
|
91
|
+
this._deviceId = deviceId;
|
|
92
|
+
storage.setItem(MicdropStorageKeys.SpeakerDevice, deviceId);
|
|
93
|
+
}
|
|
94
|
+
async getDevices() {
|
|
95
|
+
return await this.player?.getOutputDevices?.() ?? [];
|
|
96
|
+
}
|
|
97
|
+
/** Lets go of the player, at the end of the call */
|
|
98
|
+
detach() {
|
|
99
|
+
this.clearStopTimer();
|
|
100
|
+
this.setPlaying(false);
|
|
101
|
+
this.player?.destroy();
|
|
102
|
+
this.player = void 0;
|
|
103
|
+
}
|
|
104
|
+
setPlaying(playing) {
|
|
105
|
+
if (playing === this.playing) return;
|
|
106
|
+
this.playing = playing;
|
|
107
|
+
if (playing) {
|
|
108
|
+
this.emit("StartPlaying");
|
|
109
|
+
this.volumeTimer = setInterval(() => {
|
|
110
|
+
const volume = this.player?.getVolume?.();
|
|
111
|
+
if (volume !== void 0) this.emit("Volume", volume);
|
|
112
|
+
}, VOLUME_INTERVAL);
|
|
113
|
+
} else {
|
|
114
|
+
if (this.volumeTimer) clearInterval(this.volumeTimer);
|
|
115
|
+
this.volumeTimer = void 0;
|
|
116
|
+
this.emit("StopPlaying");
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
clearStopTimer() {
|
|
120
|
+
if (!this.stopTimer) return;
|
|
121
|
+
clearTimeout(this.stopTimer);
|
|
122
|
+
this.stopTimer = void 0;
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
// src/client/WebRtcClientTransport.ts
|
|
127
|
+
var WebRtcClientTransport = class extends MicdropClientTransport {
|
|
128
|
+
constructor(options) {
|
|
129
|
+
super();
|
|
130
|
+
this.options = options;
|
|
131
|
+
this.sendsMic = true;
|
|
132
|
+
this.connectionTimeout = 15e3;
|
|
133
|
+
this.state = "idle";
|
|
134
|
+
this.muted = false;
|
|
135
|
+
this.speaker = new WebRtcSpeaker();
|
|
136
|
+
this.onMicStreamChange = () => {
|
|
137
|
+
this.options.platform.getMicTrack().then((mic) => {
|
|
138
|
+
if (this.state === "closed") return mic.release?.();
|
|
139
|
+
this.mic?.release?.();
|
|
140
|
+
this.mic = mic;
|
|
141
|
+
this.applyMicTrack();
|
|
142
|
+
}).catch((error) => {
|
|
143
|
+
console.error(
|
|
144
|
+
"[MicdropClient] The new microphone cannot be sent",
|
|
145
|
+
error
|
|
146
|
+
);
|
|
147
|
+
});
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
get isOpen() {
|
|
151
|
+
return this.state === "open";
|
|
152
|
+
}
|
|
153
|
+
get isConnecting() {
|
|
154
|
+
return this.state === "connecting";
|
|
155
|
+
}
|
|
156
|
+
// Read through a getter, an await can close the call under the compiler
|
|
157
|
+
get isClosed() {
|
|
158
|
+
return this.state === "closed";
|
|
159
|
+
}
|
|
160
|
+
connect(params) {
|
|
161
|
+
if (this.state !== "idle") return;
|
|
162
|
+
this.state = "connecting";
|
|
163
|
+
this.start(params).catch((error) => {
|
|
164
|
+
if (this.state === "closed") return;
|
|
165
|
+
console.error("[MicdropClient] WebRTC connection failed", error);
|
|
166
|
+
this.end({ code: 1006, reason: error?.message });
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
send(message) {
|
|
170
|
+
if (this.channel?.readyState !== "open") return;
|
|
171
|
+
this.channel.send(
|
|
172
|
+
message.type === "StartSpeaking" ? encodeStartSpeaking(message.preroll) : encodeClientMessage(message)
|
|
173
|
+
);
|
|
174
|
+
}
|
|
175
|
+
// The microphone goes on the track
|
|
176
|
+
sendAudio() {
|
|
177
|
+
}
|
|
178
|
+
setMicMuted(muted) {
|
|
179
|
+
if (muted === this.muted) return;
|
|
180
|
+
this.muted = muted;
|
|
181
|
+
this.applyMicTrack();
|
|
182
|
+
}
|
|
183
|
+
close() {
|
|
184
|
+
if (this.state === "closed") return;
|
|
185
|
+
this.state = "closed";
|
|
186
|
+
this.teardown();
|
|
187
|
+
}
|
|
188
|
+
async start(params) {
|
|
189
|
+
const { platform } = this.options;
|
|
190
|
+
const pc = new platform.RTCPeerConnection({
|
|
191
|
+
iceServers: this.options.iceServers ?? []
|
|
192
|
+
});
|
|
193
|
+
this.pc = pc;
|
|
194
|
+
this.mic = await platform.getMicTrack();
|
|
195
|
+
if (this.isClosed) return this.teardown();
|
|
196
|
+
this.sender = pc.addTrack(
|
|
197
|
+
this.mic.track,
|
|
198
|
+
...this.mic.stream ? [this.mic.stream] : []
|
|
199
|
+
);
|
|
200
|
+
if (this.muted) this.applyMicTrack();
|
|
201
|
+
Mic.on("StreamChange", this.onMicStreamChange);
|
|
202
|
+
const channel = pc.createDataChannel(DATA_CHANNEL_LABEL, { ordered: true });
|
|
203
|
+
this.channel = channel;
|
|
204
|
+
channel.onopen = () => this.onOpen();
|
|
205
|
+
channel.onmessage = (event) => {
|
|
206
|
+
const data = event.data;
|
|
207
|
+
this.onText(
|
|
208
|
+
typeof data === "string" ? data : new TextDecoder().decode(data)
|
|
209
|
+
);
|
|
210
|
+
};
|
|
211
|
+
channel.onclose = () => this.end({ code: 1006, reason: "Data channel closed" });
|
|
212
|
+
pc.ontrack = (event) => {
|
|
213
|
+
if (event.track?.kind !== "audio") return;
|
|
214
|
+
this.speaker.attach(
|
|
215
|
+
platform.createPlayer(event.track, event.streams?.[0])
|
|
216
|
+
);
|
|
217
|
+
};
|
|
218
|
+
pc.onconnectionstatechange = () => this.onConnectionState();
|
|
219
|
+
await pc.setLocalDescription(await pc.createOffer());
|
|
220
|
+
await this.waitForGathering();
|
|
221
|
+
if (this.isClosed) return;
|
|
222
|
+
const offer = {
|
|
223
|
+
type: "offer",
|
|
224
|
+
sdp: pc.localDescription.sdp,
|
|
225
|
+
...params ? { params } : {}
|
|
226
|
+
};
|
|
227
|
+
const response = await (platform.fetch ?? fetch)(this.options.url, {
|
|
228
|
+
method: "POST",
|
|
229
|
+
headers: { "Content-Type": "application/json", ...this.options.headers },
|
|
230
|
+
body: JSON.stringify(offer)
|
|
231
|
+
});
|
|
232
|
+
if (this.isClosed) return;
|
|
233
|
+
if (!response.ok) {
|
|
234
|
+
this.end({
|
|
235
|
+
code: closeCodeOfStatus(response.status),
|
|
236
|
+
reason: await response.text().catch(() => void 0)
|
|
237
|
+
});
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
const answer = await response.json();
|
|
241
|
+
if (this.isClosed) return;
|
|
242
|
+
await pc.setRemoteDescription(answer);
|
|
243
|
+
}
|
|
244
|
+
waitForGathering() {
|
|
245
|
+
const pc = this.pc;
|
|
246
|
+
if (pc.iceGatheringState === "complete") return Promise.resolve();
|
|
247
|
+
return new Promise((resolve) => {
|
|
248
|
+
const timer = setTimeout(resolve, this.options.gatheringTimeout ?? 2e3);
|
|
249
|
+
pc.onicegatheringstatechange = () => {
|
|
250
|
+
if (pc.iceGatheringState !== "complete") return;
|
|
251
|
+
clearTimeout(timer);
|
|
252
|
+
resolve();
|
|
253
|
+
};
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
onOpen() {
|
|
257
|
+
if (this.state !== "connecting") return;
|
|
258
|
+
this.state = "open";
|
|
259
|
+
try {
|
|
260
|
+
this.previousSpeaker = Speaker.getDriver();
|
|
261
|
+
} catch {
|
|
262
|
+
this.previousSpeaker = void 0;
|
|
263
|
+
}
|
|
264
|
+
Speaker.setDriver(this.speaker);
|
|
265
|
+
this.emit("Open");
|
|
266
|
+
}
|
|
267
|
+
onText(text) {
|
|
268
|
+
if (text === PLAYBACK_START) {
|
|
269
|
+
this.speaker.playbackStarted();
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
if (text === PLAYBACK_STOP) {
|
|
273
|
+
this.speaker.playbackStopped();
|
|
274
|
+
return;
|
|
275
|
+
}
|
|
276
|
+
const close = /^Close (\d+)(?: (.*))?$/.exec(text);
|
|
277
|
+
if (close) {
|
|
278
|
+
this.end({ code: Number(close[1]), reason: close[2] });
|
|
279
|
+
return;
|
|
280
|
+
}
|
|
281
|
+
let message;
|
|
282
|
+
try {
|
|
283
|
+
message = decodeServerMessage(text);
|
|
284
|
+
} catch (error) {
|
|
285
|
+
console.error("[MicdropClient] Error parsing message:", text, error);
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
if (message?.type === "SampleRate") return;
|
|
289
|
+
if (message) this.emit("Message", message);
|
|
290
|
+
}
|
|
291
|
+
onConnectionState() {
|
|
292
|
+
const state = this.pc?.connectionState;
|
|
293
|
+
if (state === "connected") {
|
|
294
|
+
if (this.disconnectTimer) clearTimeout(this.disconnectTimer);
|
|
295
|
+
this.disconnectTimer = void 0;
|
|
296
|
+
} else if (state === "disconnected") {
|
|
297
|
+
this.disconnectTimer ?? (this.disconnectTimer = setTimeout(
|
|
298
|
+
() => this.end({ code: 1006, reason: "Connection lost" }),
|
|
299
|
+
this.options.disconnectTimeout ?? 5e3
|
|
300
|
+
));
|
|
301
|
+
} else if (state === "failed") {
|
|
302
|
+
this.end({ code: 1006, reason: "Connection failed" });
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
/** Sends the microphone, or nothing at all while muted */
|
|
306
|
+
applyMicTrack() {
|
|
307
|
+
const track = this.mic?.track;
|
|
308
|
+
if (track) track.enabled = !this.muted;
|
|
309
|
+
if (!this.sender) return;
|
|
310
|
+
Promise.resolve(this.sender.replaceTrack(this.muted ? null : track)).catch(
|
|
311
|
+
() => void 0
|
|
312
|
+
);
|
|
313
|
+
}
|
|
314
|
+
/** The call ended on the other side, or failed */
|
|
315
|
+
end(event) {
|
|
316
|
+
if (this.state === "closed") return;
|
|
317
|
+
this.state = "closed";
|
|
318
|
+
this.teardown();
|
|
319
|
+
this.emit("Close", event);
|
|
320
|
+
}
|
|
321
|
+
teardown() {
|
|
322
|
+
if (this.disconnectTimer) clearTimeout(this.disconnectTimer);
|
|
323
|
+
Mic.off("StreamChange", this.onMicStreamChange);
|
|
324
|
+
if (this.channel) {
|
|
325
|
+
this.channel.onclose = null;
|
|
326
|
+
this.channel.onmessage = null;
|
|
327
|
+
}
|
|
328
|
+
try {
|
|
329
|
+
this.pc?.close();
|
|
330
|
+
} catch {
|
|
331
|
+
}
|
|
332
|
+
this.mic?.release?.();
|
|
333
|
+
this.speaker.detach();
|
|
334
|
+
try {
|
|
335
|
+
if (Speaker.getDriver() === this.speaker && this.previousSpeaker) {
|
|
336
|
+
Speaker.setDriver(this.previousSpeaker);
|
|
337
|
+
}
|
|
338
|
+
} catch {
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
};
|
|
342
|
+
function closeCodeOfStatus(status) {
|
|
343
|
+
if (status === 400) return 4400;
|
|
344
|
+
if (status === 401 || status === 403) return 4401;
|
|
345
|
+
if (status === 404) return 4404;
|
|
346
|
+
if (status >= 500) return 1011;
|
|
347
|
+
return 1006;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
// src/index.ts
|
|
351
|
+
var webPlatform = {
|
|
352
|
+
get RTCPeerConnection() {
|
|
353
|
+
return globalThis.RTCPeerConnection;
|
|
354
|
+
},
|
|
355
|
+
async getMicTrack() {
|
|
356
|
+
const stream = Mic2.mediaStream;
|
|
357
|
+
const track = stream?.getAudioTracks()[0];
|
|
358
|
+
if (stream && track) return { track, stream };
|
|
359
|
+
const own = await navigator.mediaDevices.getUserMedia({
|
|
360
|
+
audio: {
|
|
361
|
+
echoCancellation: true,
|
|
362
|
+
noiseSuppression: true,
|
|
363
|
+
autoGainControl: true
|
|
364
|
+
}
|
|
365
|
+
});
|
|
366
|
+
return {
|
|
367
|
+
track: own.getAudioTracks()[0],
|
|
368
|
+
stream: own,
|
|
369
|
+
release: () => own.getTracks().forEach((t) => t.stop())
|
|
370
|
+
};
|
|
371
|
+
},
|
|
372
|
+
createPlayer(track, stream) {
|
|
373
|
+
const source = stream ?? new MediaStream([track]);
|
|
374
|
+
const element = new Audio();
|
|
375
|
+
element.autoplay = true;
|
|
376
|
+
element.srcObject = source;
|
|
377
|
+
element.play().catch(() => void 0);
|
|
378
|
+
let context;
|
|
379
|
+
let analyser;
|
|
380
|
+
let samples;
|
|
381
|
+
try {
|
|
382
|
+
context = new AudioContext();
|
|
383
|
+
analyser = context.createAnalyser();
|
|
384
|
+
analyser.fftSize = 2048;
|
|
385
|
+
context.createMediaStreamSource(source).connect(analyser);
|
|
386
|
+
samples = new Float32Array(analyser.fftSize);
|
|
387
|
+
} catch {
|
|
388
|
+
context = void 0;
|
|
389
|
+
}
|
|
390
|
+
return {
|
|
391
|
+
setMuted: (muted) => {
|
|
392
|
+
element.muted = muted;
|
|
393
|
+
},
|
|
394
|
+
getVolume: () => {
|
|
395
|
+
if (!analyser || !samples || !context) return void 0;
|
|
396
|
+
analyser.getFloatTimeDomainData(samples);
|
|
397
|
+
return getVolume(
|
|
398
|
+
resample(samples, context.sampleRate, VOLUME_SAMPLE_RATE)
|
|
399
|
+
);
|
|
400
|
+
},
|
|
401
|
+
setOutputDevice: async (deviceId) => {
|
|
402
|
+
await element.setSinkId?.(
|
|
403
|
+
deviceId === "default" ? "" : deviceId
|
|
404
|
+
);
|
|
405
|
+
},
|
|
406
|
+
getOutputDevices: async () => {
|
|
407
|
+
const devices = await navigator.mediaDevices.enumerateDevices();
|
|
408
|
+
return devices.filter((device) => device.kind === "audiooutput").map((device) => ({
|
|
409
|
+
id: device.deviceId,
|
|
410
|
+
label: device.label,
|
|
411
|
+
kind: "audiooutput"
|
|
412
|
+
}));
|
|
413
|
+
},
|
|
414
|
+
destroy: () => {
|
|
415
|
+
element.pause();
|
|
416
|
+
element.srcObject = null;
|
|
417
|
+
context?.close().catch(() => void 0);
|
|
418
|
+
}
|
|
419
|
+
};
|
|
420
|
+
}
|
|
421
|
+
};
|
|
422
|
+
function webRtcTransport(options) {
|
|
423
|
+
return () => new WebRtcClientTransport({ ...options, platform: webPlatform });
|
|
424
|
+
}
|
|
425
|
+
export {
|
|
426
|
+
DATA_CHANNEL_LABEL,
|
|
427
|
+
PLAYBACK_START,
|
|
428
|
+
PLAYBACK_STOP,
|
|
429
|
+
WebRtcClientTransport,
|
|
430
|
+
WebRtcSpeaker,
|
|
431
|
+
decodeStartSpeaking,
|
|
432
|
+
encodeStartSpeaking,
|
|
433
|
+
webPlatform,
|
|
434
|
+
webRtcTransport
|
|
435
|
+
};
|
|
436
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/client/WebRtcClientTransport.ts","../src/protocol.ts","../src/client/WebRtcSpeaker.ts"],"sourcesContent":["import {\n getVolume,\n Mic,\n MicdropClientTransportFactory,\n resample,\n VOLUME_SAMPLE_RATE,\n} from '@micdrop/client'\nimport {\n WebRtcClientOptions,\n WebRtcClientTransport,\n WebRtcPlatform,\n WebRtcPlayer,\n} from './client'\n\nexport * from './client'\nexport * from './protocol'\n\n/**\n * WebRTC as a browser has it. The microphone track is the one the client\n * already records from, so the VAD and the server hear the same audio, and\n * the voice of the assistant plays through an audio element, which lets the\n * browser cancel its echo.\n */\nexport const webPlatform: WebRtcPlatform = {\n get RTCPeerConnection() {\n return globalThis.RTCPeerConnection\n },\n\n async getMicTrack() {\n const stream = Mic.mediaStream\n const track = stream?.getAudioTracks()[0]\n if (stream && track) return { track, stream }\n\n // A microphone driver without a stream: the call opens its own\n const own = await navigator.mediaDevices.getUserMedia({\n audio: {\n echoCancellation: true,\n noiseSuppression: true,\n autoGainControl: true,\n },\n })\n return {\n track: own.getAudioTracks()[0],\n stream: own,\n release: () => own.getTracks().forEach((t) => t.stop()),\n }\n },\n\n createPlayer(track: MediaStreamTrack, stream?: MediaStream): WebRtcPlayer {\n const source = stream ?? new MediaStream([track])\n const element = new Audio()\n element.autoplay = true\n element.srcObject = source\n element.play().catch(() => undefined)\n\n // Measures what plays, on the same scale as the Micdrop speaker\n let context: AudioContext | undefined\n let analyser: AnalyserNode | undefined\n let samples: Float32Array<ArrayBuffer> | undefined\n try {\n context = new AudioContext()\n analyser = context.createAnalyser()\n analyser.fftSize = 2048\n context.createMediaStreamSource(source).connect(analyser)\n samples = new Float32Array(analyser.fftSize)\n } catch {\n context = undefined\n }\n\n return {\n setMuted: (muted) => {\n element.muted = muted\n },\n getVolume: () => {\n if (!analyser || !samples || !context) return undefined\n analyser.getFloatTimeDomainData(samples)\n return getVolume(\n resample(samples, context.sampleRate, VOLUME_SAMPLE_RATE)\n )\n },\n setOutputDevice: async (deviceId) => {\n await (element as any).setSinkId?.(\n deviceId === 'default' ? '' : deviceId\n )\n },\n getOutputDevices: async () => {\n const devices = await navigator.mediaDevices.enumerateDevices()\n return devices\n .filter((device) => device.kind === 'audiooutput')\n .map((device) => ({\n id: device.deviceId,\n label: device.label,\n kind: 'audiooutput' as const,\n }))\n },\n destroy: () => {\n element.pause()\n element.srcObject = null\n context?.close().catch(() => undefined)\n },\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 () => new WebRtcClientTransport({ ...options, platform: webPlatform })\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"],"mappings":";AAAA;AAAA,EACE;AAAA,EACA,OAAAA;AAAA,EAEA;AAAA,EACA;AAAA,OACK;;;ACNP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,OAEK;;;ACGA,IAAM,qBAAqB;AAoB3B,IAAM,iBAAiB;AAGvB,IAAM,gBAAgB;AAOtB,SAAS,oBAAoB,UAAU,GAAW;AACvD,SAAO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
|
+
* The offer goes to the server with an HTTP POST, the answer comes back in its
|
|
5
|
+
* response, and the call then runs on a data channel named
|
|
6
|
+
* {@link DATA_CHANNEL_LABEL}. It carries the text messages of the Micdrop
|
|
7
|
+
* protocol, the same as a WebSocket, and the few below that only a transport
|
|
8
|
+
* carrying the audio as a track needs.
|
|
9
|
+
*/
|
|
10
|
+
/** Label of the data channel of a call */
|
|
11
|
+
declare const DATA_CHANNEL_LABEL = "micdrop";
|
|
12
|
+
/** What the client posts to start a call */
|
|
13
|
+
interface MicdropWebRtcOffer {
|
|
14
|
+
type: 'offer';
|
|
15
|
+
sdp: string;
|
|
16
|
+
/** Parameters of the call, which `waitForParams` hands back */
|
|
17
|
+
params?: Record<string, any>;
|
|
18
|
+
}
|
|
19
|
+
/** What the server answers */
|
|
20
|
+
interface MicdropWebRtcAnswer {
|
|
21
|
+
type: 'answer';
|
|
22
|
+
sdp: string;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* The server started sending the assistant voice. A WebSocket client knows it
|
|
26
|
+
* from the chunks it plays, a WebRTC one only hears a track.
|
|
27
|
+
*/
|
|
28
|
+
declare const PLAYBACK_START = "PlaybackStart";
|
|
29
|
+
/** The server sent the last of the assistant voice */
|
|
30
|
+
declare const PLAYBACK_STOP = "PlaybackStop";
|
|
31
|
+
/**
|
|
32
|
+
* Writes the start of a turn with the audio before it that belongs to it,
|
|
33
|
+
* which the server takes back from the stream of the track
|
|
34
|
+
* @param preroll - Duration of that audio, in ms
|
|
35
|
+
*/
|
|
36
|
+
declare function encodeStartSpeaking(preroll?: number): string;
|
|
37
|
+
/**
|
|
38
|
+
* Reads a start of turn written by {@link encodeStartSpeaking}
|
|
39
|
+
* @returns The preroll in ms, or undefined when the text is something else
|
|
40
|
+
*/
|
|
41
|
+
declare function decodeStartSpeaking(text: string): number | undefined;
|
|
42
|
+
|
|
43
|
+
export { DATA_CHANNEL_LABEL as D, type MicdropWebRtcAnswer as M, PLAYBACK_START as P, type MicdropWebRtcOffer as a, PLAYBACK_STOP as b, decodeStartSpeaking as d, encodeStartSpeaking as e };
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What travels between the WebRTC client and server besides the audio.
|
|
3
|
+
*
|
|
4
|
+
* The offer goes to the server with an HTTP POST, the answer comes back in its
|
|
5
|
+
* response, and the call then runs on a data channel named
|
|
6
|
+
* {@link DATA_CHANNEL_LABEL}. It carries the text messages of the Micdrop
|
|
7
|
+
* protocol, the same as a WebSocket, and the few below that only a transport
|
|
8
|
+
* carrying the audio as a track needs.
|
|
9
|
+
*/
|
|
10
|
+
/** Label of the data channel of a call */
|
|
11
|
+
declare const DATA_CHANNEL_LABEL = "micdrop";
|
|
12
|
+
/** What the client posts to start a call */
|
|
13
|
+
interface MicdropWebRtcOffer {
|
|
14
|
+
type: 'offer';
|
|
15
|
+
sdp: string;
|
|
16
|
+
/** Parameters of the call, which `waitForParams` hands back */
|
|
17
|
+
params?: Record<string, any>;
|
|
18
|
+
}
|
|
19
|
+
/** What the server answers */
|
|
20
|
+
interface MicdropWebRtcAnswer {
|
|
21
|
+
type: 'answer';
|
|
22
|
+
sdp: string;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* The server started sending the assistant voice. A WebSocket client knows it
|
|
26
|
+
* from the chunks it plays, a WebRTC one only hears a track.
|
|
27
|
+
*/
|
|
28
|
+
declare const PLAYBACK_START = "PlaybackStart";
|
|
29
|
+
/** The server sent the last of the assistant voice */
|
|
30
|
+
declare const PLAYBACK_STOP = "PlaybackStop";
|
|
31
|
+
/**
|
|
32
|
+
* Writes the start of a turn with the audio before it that belongs to it,
|
|
33
|
+
* which the server takes back from the stream of the track
|
|
34
|
+
* @param preroll - Duration of that audio, in ms
|
|
35
|
+
*/
|
|
36
|
+
declare function encodeStartSpeaking(preroll?: number): string;
|
|
37
|
+
/**
|
|
38
|
+
* Reads a start of turn written by {@link encodeStartSpeaking}
|
|
39
|
+
* @returns The preroll in ms, or undefined when the text is something else
|
|
40
|
+
*/
|
|
41
|
+
declare function decodeStartSpeaking(text: string): number | undefined;
|
|
42
|
+
|
|
43
|
+
export { DATA_CHANNEL_LABEL as D, type MicdropWebRtcAnswer as M, PLAYBACK_START as P, type MicdropWebRtcOffer as a, PLAYBACK_STOP as b, decodeStartSpeaking as d, encodeStartSpeaking as e };
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { MicdropClientTransportFactory } from '@micdrop/client';
|
|
2
|
+
import { W as WebRtcPlatform, a as WebRtcClientOptions } from './WebRtcSpeaker-C4pG0yfh.mjs';
|
|
3
|
+
export { b as WebRtcClientTransport, c as WebRtcMicTrack, d as WebRtcPlayer, e as WebRtcSpeaker } from './WebRtcSpeaker-C4pG0yfh.mjs';
|
|
4
|
+
export { D as DATA_CHANNEL_LABEL, M as MicdropWebRtcAnswer, a as MicdropWebRtcOffer, P as PLAYBACK_START, b as PLAYBACK_STOP, d as decodeStartSpeaking, e as encodeStartSpeaking } from './protocol-Ba3tnNV7.mjs';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* WebRTC on a phone, from react-native-webrtc.
|
|
8
|
+
*
|
|
9
|
+
* The native Micdrop microphone hands no stream over, so the call opens its
|
|
10
|
+
* own track. Without the samples, the client cannot find the turns from it:
|
|
11
|
+
* the server detects them, with `vad` in its config. The voice of the
|
|
12
|
+
* assistant plays on its own, as every remote track does with
|
|
13
|
+
* react-native-webrtc.
|
|
14
|
+
*/
|
|
15
|
+
declare const reactNativePlatform: WebRtcPlatform;
|
|
16
|
+
/**
|
|
17
|
+
* Creates the transport of each call, to hand to `MicdropClient` as
|
|
18
|
+
* `transport`
|
|
19
|
+
* @param options - Address of the offer, headers and ICE servers
|
|
20
|
+
*/
|
|
21
|
+
declare function webRtcTransport(options: WebRtcClientOptions): MicdropClientTransportFactory;
|
|
22
|
+
|
|
23
|
+
export { WebRtcClientOptions, WebRtcPlatform, reactNativePlatform, webRtcTransport };
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { MicdropClientTransportFactory } from '@micdrop/client';
|
|
2
|
+
import { W as WebRtcPlatform, a as WebRtcClientOptions } from './WebRtcSpeaker-C4pG0yfh.js';
|
|
3
|
+
export { b as WebRtcClientTransport, c as WebRtcMicTrack, d as WebRtcPlayer, e as WebRtcSpeaker } from './WebRtcSpeaker-C4pG0yfh.js';
|
|
4
|
+
export { D as DATA_CHANNEL_LABEL, M as MicdropWebRtcAnswer, a as MicdropWebRtcOffer, P as PLAYBACK_START, b as PLAYBACK_STOP, d as decodeStartSpeaking, e as encodeStartSpeaking } from './protocol-Ba3tnNV7.js';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* WebRTC on a phone, from react-native-webrtc.
|
|
8
|
+
*
|
|
9
|
+
* The native Micdrop microphone hands no stream over, so the call opens its
|
|
10
|
+
* own track. Without the samples, the client cannot find the turns from it:
|
|
11
|
+
* the server detects them, with `vad` in its config. The voice of the
|
|
12
|
+
* assistant plays on its own, as every remote track does with
|
|
13
|
+
* react-native-webrtc.
|
|
14
|
+
*/
|
|
15
|
+
declare const reactNativePlatform: WebRtcPlatform;
|
|
16
|
+
/**
|
|
17
|
+
* Creates the transport of each call, to hand to `MicdropClient` as
|
|
18
|
+
* `transport`
|
|
19
|
+
* @param options - Address of the offer, headers and ICE servers
|
|
20
|
+
*/
|
|
21
|
+
declare function webRtcTransport(options: WebRtcClientOptions): MicdropClientTransportFactory;
|
|
22
|
+
|
|
23
|
+
export { WebRtcClientOptions, WebRtcPlatform, reactNativePlatform, webRtcTransport };
|