@micdrop/webrtc 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +59 -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 +451 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +433 -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 +399 -0
- package/dist/react-native.js.map +1 -0
- package/dist/react-native.mjs +376 -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 +420 -0
- package/dist/server/index.js.map +1 -0
- package/dist/server/index.mjs +386 -0
- package/dist/server/index.mjs.map +1 -0
- package/package.json +88 -4
|
@@ -0,0 +1,386 @@
|
|
|
1
|
+
// src/protocol.ts
|
|
2
|
+
var DATA_CHANNEL_LABEL = "micdrop";
|
|
3
|
+
var PLAYBACK_START = "PlaybackStart";
|
|
4
|
+
var PLAYBACK_STOP = "PlaybackStop";
|
|
5
|
+
function encodeStartSpeaking(preroll = 0) {
|
|
6
|
+
return preroll > 0 ? `StartSpeaking ${Math.round(preroll)}` : "StartSpeaking";
|
|
7
|
+
}
|
|
8
|
+
function decodeStartSpeaking(text) {
|
|
9
|
+
if (text === "StartSpeaking") return 0;
|
|
10
|
+
const match = /^StartSpeaking (\d+)$/.exec(text);
|
|
11
|
+
return match ? Number(match[1]) : void 0;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// src/server/opus.ts
|
|
15
|
+
import OpusScript from "opusscript";
|
|
16
|
+
var OPUS_SAMPLE_RATE = 48e3;
|
|
17
|
+
var OPUS_FRAME_SAMPLES = 960;
|
|
18
|
+
var OPUS_DECODE_RATE = 16e3;
|
|
19
|
+
function createOpusScriptCodec() {
|
|
20
|
+
const encoder = new OpusScript(
|
|
21
|
+
OPUS_SAMPLE_RATE,
|
|
22
|
+
1,
|
|
23
|
+
OpusScript.Application.VOIP
|
|
24
|
+
);
|
|
25
|
+
const decoder = new OpusScript(
|
|
26
|
+
OPUS_DECODE_RATE,
|
|
27
|
+
1,
|
|
28
|
+
OpusScript.Application.VOIP
|
|
29
|
+
);
|
|
30
|
+
return {
|
|
31
|
+
encode: (pcm) => encoder.encode(pcm, OPUS_FRAME_SAMPLES),
|
|
32
|
+
decode: (packet) => decoder.decode(packet),
|
|
33
|
+
destroy: () => {
|
|
34
|
+
encoder.delete();
|
|
35
|
+
decoder.delete();
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// src/server/WebRtcTransport.ts
|
|
41
|
+
import {
|
|
42
|
+
decodeClientMessage,
|
|
43
|
+
DEFAULT_SAMPLE_RATE,
|
|
44
|
+
encodeServerMessage,
|
|
45
|
+
MicdropTransport,
|
|
46
|
+
Pcm16Resampler
|
|
47
|
+
} from "@micdrop/server";
|
|
48
|
+
import {
|
|
49
|
+
MediaStreamTrack,
|
|
50
|
+
RTCPeerConnection,
|
|
51
|
+
RTCRtpCodecParameters,
|
|
52
|
+
RtpHeader,
|
|
53
|
+
RtpPacket
|
|
54
|
+
} from "werift";
|
|
55
|
+
var FRAME_DURATION = 20;
|
|
56
|
+
var FRAME_BYTES = OPUS_FRAME_SAMPLES * 2;
|
|
57
|
+
var PREROLL_MAX = 2e3;
|
|
58
|
+
var PLAYOUT_DELAY = 200;
|
|
59
|
+
var MAX_CONCEALED_FRAMES = 10;
|
|
60
|
+
var WebRtcTransport = class _WebRtcTransport extends MicdropTransport {
|
|
61
|
+
constructor(options = {}) {
|
|
62
|
+
super();
|
|
63
|
+
this.options = options;
|
|
64
|
+
this.clientTurns = true;
|
|
65
|
+
this.outputTrack = new MediaStreamTrack({ kind: "audio" });
|
|
66
|
+
this.closed = false;
|
|
67
|
+
this.pendingMessages = [];
|
|
68
|
+
// Assistant voice, in frames of 20 ms at 48 kHz, sent at the pace it plays
|
|
69
|
+
this.frames = [];
|
|
70
|
+
this.remainder = Buffer.alloc(0);
|
|
71
|
+
this.resamplerRate = 0;
|
|
72
|
+
this.playing = false;
|
|
73
|
+
this.nextFrameAt = 0;
|
|
74
|
+
this.payloadType = 111;
|
|
75
|
+
this.ssrc = Math.floor(Math.random() * 4294967295);
|
|
76
|
+
this.sequenceNumber = Math.floor(Math.random() * 65535);
|
|
77
|
+
this.timestamp = Math.floor(Math.random() * 4294967295);
|
|
78
|
+
this.preroll = [];
|
|
79
|
+
this.prerollBytes = 0;
|
|
80
|
+
this.codec = (options.codec ?? createOpusScriptCodec)();
|
|
81
|
+
this.pc = new RTCPeerConnection({
|
|
82
|
+
...options.peerConfig,
|
|
83
|
+
iceServers: options.iceServers ?? options.peerConfig?.iceServers ?? [],
|
|
84
|
+
codecs: {
|
|
85
|
+
audio: [
|
|
86
|
+
new RTCRtpCodecParameters({
|
|
87
|
+
mimeType: "audio/opus",
|
|
88
|
+
clockRate: OPUS_SAMPLE_RATE,
|
|
89
|
+
channels: 2
|
|
90
|
+
})
|
|
91
|
+
]
|
|
92
|
+
}
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Answers the offer of a client
|
|
97
|
+
* @param offer - What the client posted, its parameters included
|
|
98
|
+
* @param options - ICE servers, codec and network settings
|
|
99
|
+
* @returns The transport of the call, with the `answer` to send back
|
|
100
|
+
*/
|
|
101
|
+
static async accept(offer, options = {}) {
|
|
102
|
+
if (offer?.type !== "offer" || typeof offer.sdp !== "string") {
|
|
103
|
+
throw new Error("Not a WebRTC offer");
|
|
104
|
+
}
|
|
105
|
+
const transport = new _WebRtcTransport(options);
|
|
106
|
+
try {
|
|
107
|
+
await transport.negotiate(offer);
|
|
108
|
+
} catch (error) {
|
|
109
|
+
transport.close(1011, "Negotiation failed");
|
|
110
|
+
throw error;
|
|
111
|
+
}
|
|
112
|
+
if (offer.params !== void 0) transport.receiveParams(offer.params);
|
|
113
|
+
transport.connectTimer = setTimeout(
|
|
114
|
+
() => transport.finish(1006, "Connection timeout"),
|
|
115
|
+
options.connectTimeout ?? 15e3
|
|
116
|
+
);
|
|
117
|
+
return transport;
|
|
118
|
+
}
|
|
119
|
+
get isOpen() {
|
|
120
|
+
return !this.closed;
|
|
121
|
+
}
|
|
122
|
+
send(message) {
|
|
123
|
+
this.sendText(encodeServerMessage(message));
|
|
124
|
+
}
|
|
125
|
+
sendAudio(audio, sampleRate) {
|
|
126
|
+
if (this.closed) return;
|
|
127
|
+
if (sampleRate !== this.resamplerRate) {
|
|
128
|
+
this.resamplerRate = sampleRate;
|
|
129
|
+
this.resampler = sampleRate === OPUS_SAMPLE_RATE ? void 0 : new Pcm16Resampler(sampleRate, OPUS_SAMPLE_RATE);
|
|
130
|
+
}
|
|
131
|
+
const pcm = this.resampler ? this.resampler.process(audio) : audio;
|
|
132
|
+
let data = Buffer.concat([this.remainder, pcm]);
|
|
133
|
+
while (data.length >= FRAME_BYTES) {
|
|
134
|
+
this.frames.push(data.subarray(0, FRAME_BYTES));
|
|
135
|
+
data = data.subarray(FRAME_BYTES);
|
|
136
|
+
}
|
|
137
|
+
this.remainder = data;
|
|
138
|
+
}
|
|
139
|
+
clearAudio() {
|
|
140
|
+
this.frames = [];
|
|
141
|
+
this.remainder = Buffer.alloc(0);
|
|
142
|
+
this.resampler?.reset();
|
|
143
|
+
this.setPlaying(false);
|
|
144
|
+
}
|
|
145
|
+
async waitForPlayback() {
|
|
146
|
+
if (this.remainder.length) {
|
|
147
|
+
const frame = Buffer.alloc(FRAME_BYTES);
|
|
148
|
+
this.remainder.copy(frame);
|
|
149
|
+
this.frames.push(frame);
|
|
150
|
+
this.remainder = Buffer.alloc(0);
|
|
151
|
+
}
|
|
152
|
+
while (!this.closed && this.frames.length) {
|
|
153
|
+
await new Promise((resolve) => setTimeout(resolve, FRAME_DURATION));
|
|
154
|
+
}
|
|
155
|
+
await new Promise((resolve) => setTimeout(resolve, PLAYOUT_DELAY));
|
|
156
|
+
}
|
|
157
|
+
close(code = 1e3, reason) {
|
|
158
|
+
if (this.closed) return;
|
|
159
|
+
this.sendText(`Close ${code}${reason ? ` ${reason}` : ""}`);
|
|
160
|
+
this.finish(code, reason, CLOSE_FLUSH);
|
|
161
|
+
}
|
|
162
|
+
async negotiate(offer) {
|
|
163
|
+
const pc = this.pc;
|
|
164
|
+
pc.ondatachannel = ({ channel }) => this.attachChannel(channel);
|
|
165
|
+
pc.ontrack = ({ track }) => {
|
|
166
|
+
track.onReceiveRtp.subscribe((rtp, _extensions, info) => {
|
|
167
|
+
if (info && info.type !== "media") return;
|
|
168
|
+
this.onRtp(rtp);
|
|
169
|
+
});
|
|
170
|
+
};
|
|
171
|
+
pc.onconnectionstatechange = () => this.onConnectionState();
|
|
172
|
+
await pc.setRemoteDescription({ type: "offer", sdp: offer.sdp });
|
|
173
|
+
pc.addTrack(this.outputTrack);
|
|
174
|
+
const gathered = this.trackGathering();
|
|
175
|
+
await pc.setLocalDescription(await pc.createAnswer());
|
|
176
|
+
await gathered;
|
|
177
|
+
const sdp = pc.localDescription.sdp;
|
|
178
|
+
const payloadType = /a=rtpmap:(\d+) opus\/48000/i.exec(sdp)?.[1];
|
|
179
|
+
if (payloadType) this.payloadType = Number(payloadType);
|
|
180
|
+
this.answer = { type: "answer", sdp };
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Resolves once the candidates are gathered. werift does not always say
|
|
184
|
+
* so, so a pause in the flow of candidates counts as the end: they all
|
|
185
|
+
* arrive within a few tens of milliseconds, the reflexive ones included.
|
|
186
|
+
*/
|
|
187
|
+
trackGathering() {
|
|
188
|
+
return new Promise((resolve) => {
|
|
189
|
+
const pc = this.pc;
|
|
190
|
+
let quietTimer;
|
|
191
|
+
const timer = setTimeout(done, this.options.gatheringTimeout ?? 3e3);
|
|
192
|
+
function done() {
|
|
193
|
+
clearTimeout(timer);
|
|
194
|
+
if (quietTimer) clearTimeout(quietTimer);
|
|
195
|
+
pc.onicecandidate = null;
|
|
196
|
+
pc.onicegatheringstatechange = null;
|
|
197
|
+
resolve();
|
|
198
|
+
}
|
|
199
|
+
pc.onicecandidate = (event) => {
|
|
200
|
+
if (!event.candidate) return done();
|
|
201
|
+
if (quietTimer) clearTimeout(quietTimer);
|
|
202
|
+
quietTimer = setTimeout(done, GATHERING_QUIET);
|
|
203
|
+
};
|
|
204
|
+
pc.onicegatheringstatechange = () => {
|
|
205
|
+
if (pc.iceGatheringState === "complete") done();
|
|
206
|
+
};
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
attachChannel(channel) {
|
|
210
|
+
if (channel.label !== DATA_CHANNEL_LABEL) return;
|
|
211
|
+
this.channel = channel;
|
|
212
|
+
channel.onmessage = (event) => {
|
|
213
|
+
const data = event.data;
|
|
214
|
+
if (typeof data === "string") this.onText(data);
|
|
215
|
+
else if (Buffer.isBuffer(data)) this.onText(data.toString());
|
|
216
|
+
else if (data instanceof ArrayBuffer)
|
|
217
|
+
this.onText(Buffer.from(data).toString());
|
|
218
|
+
};
|
|
219
|
+
channel.onclose = () => this.finish(1005, void 0);
|
|
220
|
+
const flush = () => {
|
|
221
|
+
if (this.connectTimer) clearTimeout(this.connectTimer);
|
|
222
|
+
this.connectTimer = void 0;
|
|
223
|
+
const messages = this.pendingMessages;
|
|
224
|
+
this.pendingMessages = [];
|
|
225
|
+
for (const text of messages) channel.send(text);
|
|
226
|
+
this.startPacer();
|
|
227
|
+
};
|
|
228
|
+
if (channel.readyState === "open") flush();
|
|
229
|
+
else channel.onopen = flush;
|
|
230
|
+
}
|
|
231
|
+
onConnectionState() {
|
|
232
|
+
const state = this.pc.connectionState;
|
|
233
|
+
this.logger.debug("Connection state", { state });
|
|
234
|
+
if (state === "connected") {
|
|
235
|
+
if (this.disconnectTimer) clearTimeout(this.disconnectTimer);
|
|
236
|
+
this.disconnectTimer = void 0;
|
|
237
|
+
} else if (state === "disconnected") {
|
|
238
|
+
this.disconnectTimer ?? (this.disconnectTimer = setTimeout(
|
|
239
|
+
() => this.finish(1006, "Connection lost"),
|
|
240
|
+
this.options.disconnectTimeout ?? 5e3
|
|
241
|
+
));
|
|
242
|
+
} else if (state === "failed" || state === "closed") {
|
|
243
|
+
this.finish(1006, `Connection ${state}`);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
onText(text) {
|
|
247
|
+
const preroll = decodeStartSpeaking(text);
|
|
248
|
+
if (preroll !== void 0) {
|
|
249
|
+
this.logger.debug("Command", {
|
|
250
|
+
command: "StartSpeaking",
|
|
251
|
+
prerollMs: preroll
|
|
252
|
+
});
|
|
253
|
+
this.emit("Command", { type: "StartSpeaking", preroll });
|
|
254
|
+
const audio = this.takePreroll(preroll);
|
|
255
|
+
if (audio.length) this.emit("Audio", audio);
|
|
256
|
+
return;
|
|
257
|
+
}
|
|
258
|
+
const command = decodeClientMessage(text);
|
|
259
|
+
if (command) {
|
|
260
|
+
this.logger.debug("Command", { command: text });
|
|
261
|
+
this.emit("Command", command);
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
try {
|
|
265
|
+
this.receiveParams(JSON.parse(text));
|
|
266
|
+
} catch {
|
|
267
|
+
this.logger.warn("Unknown message", { message: text.substring(0, 100) });
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
onRtp(rtp) {
|
|
271
|
+
if (this.closed) return;
|
|
272
|
+
const sequence = rtp.header.sequenceNumber;
|
|
273
|
+
if (this.lastSequence !== void 0) {
|
|
274
|
+
const gap = sequence - this.lastSequence + 65536 & 65535;
|
|
275
|
+
if (gap === 0 || gap > 32768) return;
|
|
276
|
+
const lost = gap - 1;
|
|
277
|
+
if (lost > 0 && lost <= MAX_CONCEALED_FRAMES) {
|
|
278
|
+
this.receiveAudio(
|
|
279
|
+
Buffer.alloc(
|
|
280
|
+
DEFAULT_SAMPLE_RATE * FRAME_DURATION / 1e3 * 2 * lost
|
|
281
|
+
)
|
|
282
|
+
);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
this.lastSequence = sequence;
|
|
286
|
+
if (rtp.payload.length === 0) return;
|
|
287
|
+
try {
|
|
288
|
+
this.receiveAudio(this.codec.decode(rtp.payload));
|
|
289
|
+
} catch (error) {
|
|
290
|
+
this.logger.trace("Undecodable packet", { error });
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
receiveAudio(pcm) {
|
|
294
|
+
this.preroll.push(pcm);
|
|
295
|
+
this.prerollBytes += pcm.length;
|
|
296
|
+
const max = DEFAULT_SAMPLE_RATE * PREROLL_MAX / 1e3 * 2;
|
|
297
|
+
while (this.prerollBytes - this.preroll[0].length >= max) {
|
|
298
|
+
this.prerollBytes -= this.preroll.shift().length;
|
|
299
|
+
}
|
|
300
|
+
this.emit("Audio", pcm);
|
|
301
|
+
}
|
|
302
|
+
/** The last `duration` ms of user audio */
|
|
303
|
+
takePreroll(duration) {
|
|
304
|
+
const bytes = Math.round(DEFAULT_SAMPLE_RATE * duration / 1e3) * 2;
|
|
305
|
+
if (bytes === 0) return Buffer.alloc(0);
|
|
306
|
+
const all = Buffer.concat(this.preroll);
|
|
307
|
+
return all.subarray(Math.max(0, all.length - bytes));
|
|
308
|
+
}
|
|
309
|
+
startPacer() {
|
|
310
|
+
if (this.pacer || this.closed) return;
|
|
311
|
+
this.nextFrameAt = performance.now();
|
|
312
|
+
this.pacer = setInterval(() => this.pace(), FRAME_DURATION / 2);
|
|
313
|
+
}
|
|
314
|
+
/** Sends every frame due, silence when the assistant is quiet */
|
|
315
|
+
pace() {
|
|
316
|
+
const now = performance.now();
|
|
317
|
+
if (now - this.nextFrameAt > 10 * FRAME_DURATION) this.nextFrameAt = now;
|
|
318
|
+
while (this.nextFrameAt <= now) {
|
|
319
|
+
this.sendFrame();
|
|
320
|
+
this.nextFrameAt += FRAME_DURATION;
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
sendFrame() {
|
|
324
|
+
const frame = this.frames.shift();
|
|
325
|
+
const talkspurt = !!frame && !this.playing;
|
|
326
|
+
if (frame) this.setPlaying(true);
|
|
327
|
+
else if (this.playing) this.setPlaying(false);
|
|
328
|
+
let payload;
|
|
329
|
+
try {
|
|
330
|
+
payload = this.codec.encode(frame ?? SILENCE);
|
|
331
|
+
} catch (error) {
|
|
332
|
+
this.logger.warn("Encoding failed", { error });
|
|
333
|
+
return;
|
|
334
|
+
}
|
|
335
|
+
const header = new RtpHeader({
|
|
336
|
+
payloadType: this.payloadType,
|
|
337
|
+
sequenceNumber: this.sequenceNumber,
|
|
338
|
+
timestamp: this.timestamp,
|
|
339
|
+
ssrc: this.ssrc,
|
|
340
|
+
marker: talkspurt
|
|
341
|
+
});
|
|
342
|
+
this.sequenceNumber = this.sequenceNumber + 1 & 65535;
|
|
343
|
+
this.timestamp = this.timestamp + OPUS_FRAME_SAMPLES >>> 0;
|
|
344
|
+
this.outputTrack.writeRtp(new RtpPacket(header, payload));
|
|
345
|
+
}
|
|
346
|
+
setPlaying(playing) {
|
|
347
|
+
if (playing === this.playing) return;
|
|
348
|
+
this.playing = playing;
|
|
349
|
+
this.sendText(playing ? PLAYBACK_START : PLAYBACK_STOP);
|
|
350
|
+
}
|
|
351
|
+
sendText(text) {
|
|
352
|
+
if (this.closed) return;
|
|
353
|
+
const channel = this.channel;
|
|
354
|
+
if (channel?.readyState === "open") channel.send(text);
|
|
355
|
+
else this.pendingMessages.push(text);
|
|
356
|
+
}
|
|
357
|
+
finish(code, reason, delay = 0) {
|
|
358
|
+
if (this.closed) return;
|
|
359
|
+
this.closed = true;
|
|
360
|
+
if (this.pacer) clearInterval(this.pacer);
|
|
361
|
+
if (this.disconnectTimer) clearTimeout(this.disconnectTimer);
|
|
362
|
+
if (this.connectTimer) clearTimeout(this.connectTimer);
|
|
363
|
+
this.frames = [];
|
|
364
|
+
this.codec.destroy();
|
|
365
|
+
const closePeer = () => this.pc.close().catch(() => void 0);
|
|
366
|
+
if (delay) setTimeout(closePeer, delay);
|
|
367
|
+
else closePeer();
|
|
368
|
+
this.emit("Close", code, reason);
|
|
369
|
+
}
|
|
370
|
+
};
|
|
371
|
+
var SILENCE = Buffer.alloc(FRAME_BYTES);
|
|
372
|
+
var GATHERING_QUIET = 200;
|
|
373
|
+
var CLOSE_FLUSH = 100;
|
|
374
|
+
export {
|
|
375
|
+
DATA_CHANNEL_LABEL,
|
|
376
|
+
OPUS_DECODE_RATE,
|
|
377
|
+
OPUS_FRAME_SAMPLES,
|
|
378
|
+
OPUS_SAMPLE_RATE,
|
|
379
|
+
PLAYBACK_START,
|
|
380
|
+
PLAYBACK_STOP,
|
|
381
|
+
WebRtcTransport,
|
|
382
|
+
createOpusScriptCodec,
|
|
383
|
+
decodeStartSpeaking,
|
|
384
|
+
encodeStartSpeaking
|
|
385
|
+
};
|
|
386
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/protocol.ts","../../src/server/opus.ts","../../src/server/WebRtcTransport.ts"],"sourcesContent":["/**\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 OpusScript from 'opusscript'\n\n/** Rate of the audio the encoder takes, and of the RTP clock of Opus */\nexport const OPUS_SAMPLE_RATE = 48000\n\n/** Samples in one frame of 20 ms at 48 kHz */\nexport const OPUS_FRAME_SAMPLES = 960\n\n/** Rate the decoder hands the user audio at, the one of the server */\nexport const OPUS_DECODE_RATE = 16000\n\n/**\n * Encodes the assistant voice and decodes the user, one per call.\n *\n * The default runs libopus compiled to WebAssembly, with nothing to build.\n * A server that holds many calls can bring a native binding instead.\n */\nexport interface OpusCodec {\n /**\n * Encodes one frame\n * @param pcm - 960 samples of PCM16 mono at 48 kHz, 20 ms\n * @returns One Opus packet\n */\n encode(pcm: Buffer): Buffer\n\n /**\n * Decodes one packet\n * @param packet - An Opus packet, mono or stereo\n * @returns PCM16 mono at 16 kHz\n */\n decode(packet: Buffer): Buffer\n\n /** Releases the codec */\n destroy(): void\n}\n\n/** Creates the codec of a call */\nexport type OpusCodecFactory = () => OpusCodec\n\n/** The codec on libopus compiled to WebAssembly, through opusscript */\nexport function createOpusScriptCodec(): OpusCodec {\n const encoder = new OpusScript(\n OPUS_SAMPLE_RATE,\n 1,\n OpusScript.Application.VOIP\n )\n const decoder = new OpusScript(\n OPUS_DECODE_RATE,\n 1,\n OpusScript.Application.VOIP\n )\n return {\n encode: (pcm) => encoder.encode(pcm, OPUS_FRAME_SAMPLES),\n decode: (packet) => decoder.decode(packet),\n destroy: () => {\n encoder.delete()\n decoder.delete()\n },\n }\n}\n","import {\n decodeClientMessage,\n DEFAULT_SAMPLE_RATE,\n encodeServerMessage,\n MicdropServerMessage,\n MicdropTransport,\n Pcm16Resampler,\n} from '@micdrop/server'\nimport {\n MediaStreamTrack,\n RTCPeerConnection,\n RTCRtpCodecParameters,\n RtpHeader,\n RtpPacket,\n type RTCDataChannel,\n type RTCPeerConnectionConfig,\n} from 'werift'\nimport {\n DATA_CHANNEL_LABEL,\n decodeStartSpeaking,\n MicdropWebRtcAnswer,\n MicdropWebRtcOffer,\n PLAYBACK_START,\n PLAYBACK_STOP,\n} from '../protocol'\nimport {\n createOpusScriptCodec,\n OPUS_FRAME_SAMPLES,\n OPUS_SAMPLE_RATE,\n OpusCodec,\n OpusCodecFactory,\n} from './opus'\n\nexport interface WebRtcIceServer {\n urls: string | string[]\n username?: string\n credential?: string\n}\n\nexport interface WebRtcTransportOptions {\n /**\n * STUN and TURN servers. A server with a public address needs none, one\n * behind a NAT needs a STUN server to learn its address, and the users on\n * networks that block UDP need a TURN server.\n */\n iceServers?: WebRtcIceServer[]\n /** Creates the Opus codec of each call, libopus in WebAssembly by default */\n codec?: OpusCodecFactory\n /**\n * More options of the werift peer connection: `icePortRange` to open only\n * a few UDP ports, `iceAdditionalHostAddresses` to announce the public\n * address of a server behind a NAT\n */\n peerConfig?: RTCPeerConnectionConfig\n /** How long the server gathers its candidates before answering, 3000 ms */\n gatheringTimeout?: number\n /** How long a lost connection may take to come back before the call ends, 5000 ms */\n disconnectTimeout?: number\n /**\n * How long the client has to open the call once answered, 15000 ms. A\n * client that never connects, behind a network that blocks it for\n * instance, ends the call rather than holding it open.\n */\n connectTimeout?: number\n}\n\nconst FRAME_DURATION = 20 // ms\nconst FRAME_BYTES = OPUS_FRAME_SAMPLES * 2\n// How much user audio is kept for the turns a client opens a little late\nconst PREROLL_MAX = 2000 // ms\n// Delay of the jitter buffer of the client, which plays the last frame sent\n// about this much later\nconst PLAYOUT_DELAY = 200 // ms\n// Gaps longer than this are a pause of the sender, not lost packets\nconst MAX_CONCEALED_FRAMES = 10\n\n/**\n * A call carried by WebRTC: the user and the assistant as Opus audio tracks,\n * the Micdrop protocol on a data channel.\n *\n * It holds up better than a WebSocket on a weak network, a lost packet being\n * skipped rather than resent, and the browser cancels the echo of an audio\n * track better than that of audio it plays itself. It runs on werift, an\n * implementation of WebRTC in TypeScript, with nothing native to build.\n *\n * The client posts its offer to the server, which answers with\n * {@link WebRtcTransport.accept}:\n *\n * ```ts\n * app.post('/call', async (req, res) => {\n * const transport = await WebRtcTransport.accept(req.body)\n * res.json(transport.answer)\n * new MicdropServer(transport, config)\n * })\n * ```\n */\nexport class WebRtcTransport extends MicdropTransport {\n readonly clientTurns = true\n\n /** What to send back to the client, once accepted */\n public answer!: MicdropWebRtcAnswer\n\n private pc: RTCPeerConnection\n private outputTrack = new MediaStreamTrack({ kind: 'audio' })\n private channel?: RTCDataChannel\n private codec: OpusCodec\n private closed = false\n private pendingMessages: string[] = []\n\n // Assistant voice, in frames of 20 ms at 48 kHz, sent at the pace it plays\n private frames: Buffer[] = []\n private remainder = Buffer.alloc(0)\n private resampler?: Pcm16Resampler\n private resamplerRate = 0\n private playing = false\n private pacer?: ReturnType<typeof setInterval>\n private nextFrameAt = 0\n private payloadType = 111\n private readonly ssrc = Math.floor(Math.random() * 0xffffffff)\n private sequenceNumber = Math.floor(Math.random() * 0xffff)\n private timestamp = Math.floor(Math.random() * 0xffffffff)\n\n // User audio\n private lastSequence?: number\n private preroll: Buffer[] = []\n private prerollBytes = 0\n private disconnectTimer?: ReturnType<typeof setTimeout>\n private connectTimer?: ReturnType<typeof setTimeout>\n\n private constructor(private options: WebRtcTransportOptions = {}) {\n super()\n this.codec = (options.codec ?? createOpusScriptCodec)()\n this.pc = new RTCPeerConnection({\n ...options.peerConfig,\n iceServers: options.iceServers ?? options.peerConfig?.iceServers ?? [],\n codecs: {\n audio: [\n new RTCRtpCodecParameters({\n mimeType: 'audio/opus',\n clockRate: OPUS_SAMPLE_RATE,\n channels: 2,\n }),\n ],\n },\n })\n }\n\n /**\n * Answers the offer of a client\n * @param offer - What the client posted, its parameters included\n * @param options - ICE servers, codec and network settings\n * @returns The transport of the call, with the `answer` to send back\n */\n static async accept(\n offer: MicdropWebRtcOffer,\n options: WebRtcTransportOptions = {}\n ): Promise<WebRtcTransport> {\n if (offer?.type !== 'offer' || typeof offer.sdp !== 'string') {\n throw new Error('Not a WebRTC offer')\n }\n const transport = new WebRtcTransport(options)\n try {\n await transport.negotiate(offer)\n } catch (error) {\n transport.close(1011, 'Negotiation failed')\n throw error\n }\n if (offer.params !== undefined) transport.receiveParams(offer.params)\n transport.connectTimer = setTimeout(\n () => transport.finish(1006, 'Connection timeout'),\n options.connectTimeout ?? 15000\n )\n return transport\n }\n\n get isOpen(): boolean {\n return !this.closed\n }\n\n send(message: MicdropServerMessage) {\n this.sendText(encodeServerMessage(message))\n }\n\n sendAudio(audio: Buffer, sampleRate: number) {\n if (this.closed) return\n if (sampleRate !== this.resamplerRate) {\n this.resamplerRate = sampleRate\n this.resampler =\n sampleRate === OPUS_SAMPLE_RATE\n ? undefined\n : new Pcm16Resampler(sampleRate, OPUS_SAMPLE_RATE)\n }\n const pcm = this.resampler ? this.resampler.process(audio) : audio\n let data = Buffer.concat([this.remainder, pcm])\n while (data.length >= FRAME_BYTES) {\n this.frames.push(data.subarray(0, FRAME_BYTES))\n data = data.subarray(FRAME_BYTES)\n }\n this.remainder = data\n }\n\n clearAudio() {\n this.frames = []\n this.remainder = Buffer.alloc(0)\n this.resampler?.reset()\n this.setPlaying(false)\n }\n\n async waitForPlayback(): Promise<void> {\n // The last incomplete frame goes too, padded with silence\n if (this.remainder.length) {\n const frame = Buffer.alloc(FRAME_BYTES)\n this.remainder.copy(frame)\n this.frames.push(frame)\n this.remainder = Buffer.alloc(0)\n }\n while (!this.closed && this.frames.length) {\n await new Promise((resolve) => setTimeout(resolve, FRAME_DURATION))\n }\n await new Promise((resolve) => setTimeout(resolve, PLAYOUT_DELAY))\n }\n\n close(code = 1000, reason?: string) {\n if (this.closed) return\n // Says why before leaving, as a WebSocket close frame would, and gives\n // the message a moment to leave\n this.sendText(`Close ${code}${reason ? ` ${reason}` : ''}`)\n this.finish(code, reason, CLOSE_FLUSH)\n }\n\n private async negotiate(offer: MicdropWebRtcOffer) {\n const pc = this.pc\n pc.ondatachannel = ({ channel }) => this.attachChannel(channel)\n pc.ontrack = ({ track }) => {\n track.onReceiveRtp.subscribe((rtp, _extensions, info) => {\n if (info && info.type !== 'media') return\n this.onRtp(rtp)\n })\n }\n pc.onconnectionstatechange = () => this.onConnectionState()\n\n await pc.setRemoteDescription({ type: 'offer', sdp: offer.sdp })\n pc.addTrack(this.outputTrack)\n const gathered = this.trackGathering()\n await pc.setLocalDescription(await pc.createAnswer())\n await gathered\n\n const sdp = pc.localDescription!.sdp\n const payloadType = /a=rtpmap:(\\d+) opus\\/48000/i.exec(sdp)?.[1]\n if (payloadType) this.payloadType = Number(payloadType)\n this.answer = { type: 'answer', sdp }\n }\n\n /**\n * Resolves once the candidates are gathered. werift does not always say\n * so, so a pause in the flow of candidates counts as the end: they all\n * arrive within a few tens of milliseconds, the reflexive ones included.\n */\n private trackGathering(): Promise<void> {\n return new Promise((resolve) => {\n const pc = this.pc\n let quietTimer: ReturnType<typeof setTimeout> | undefined\n const timer = setTimeout(done, this.options.gatheringTimeout ?? 3000)\n function done() {\n clearTimeout(timer)\n if (quietTimer) clearTimeout(quietTimer)\n pc.onicecandidate = null\n pc.onicegatheringstatechange = null\n resolve()\n }\n pc.onicecandidate = (event) => {\n if (!event.candidate) return done()\n if (quietTimer) clearTimeout(quietTimer)\n quietTimer = setTimeout(done, GATHERING_QUIET)\n }\n pc.onicegatheringstatechange = () => {\n if (pc.iceGatheringState === 'complete') done()\n }\n })\n }\n\n private attachChannel(channel: RTCDataChannel) {\n if (channel.label !== DATA_CHANNEL_LABEL) return\n this.channel = channel\n channel.onmessage = (event) => {\n const data: unknown = event.data\n if (typeof data === 'string') this.onText(data)\n else if (Buffer.isBuffer(data)) this.onText(data.toString())\n else if (data instanceof ArrayBuffer)\n this.onText(Buffer.from(data).toString())\n }\n channel.onclose = () => this.finish(1005, undefined)\n const flush = () => {\n if (this.connectTimer) clearTimeout(this.connectTimer)\n this.connectTimer = undefined\n const messages = this.pendingMessages\n this.pendingMessages = []\n for (const text of messages) channel.send(text)\n this.startPacer()\n }\n if (channel.readyState === 'open') flush()\n else channel.onopen = flush\n }\n\n private onConnectionState() {\n const state = this.pc.connectionState\n this.logger.debug('Connection state', { state })\n if (state === 'connected') {\n if (this.disconnectTimer) clearTimeout(this.disconnectTimer)\n this.disconnectTimer = undefined\n } else if (state === 'disconnected') {\n // A network change can bring it back\n this.disconnectTimer ??= setTimeout(\n () => this.finish(1006, 'Connection lost'),\n this.options.disconnectTimeout ?? 5000\n )\n } else if (state === 'failed' || state === 'closed') {\n this.finish(1006, `Connection ${state}`)\n }\n }\n\n private onText(text: string) {\n const preroll = decodeStartSpeaking(text)\n if (preroll !== undefined) {\n this.logger.debug('Command', {\n command: 'StartSpeaking',\n prerollMs: preroll,\n })\n this.emit('Command', { type: 'StartSpeaking', preroll })\n // The beginning of the turn, which the track sent before the command\n const audio = this.takePreroll(preroll)\n if (audio.length) this.emit('Audio', audio)\n return\n }\n const command = decodeClientMessage(text)\n if (command) {\n this.logger.debug('Command', { command: text })\n this.emit('Command', command)\n return\n }\n try {\n this.receiveParams(JSON.parse(text))\n } catch {\n this.logger.warn('Unknown message', { message: text.substring(0, 100) })\n }\n }\n\n private onRtp(rtp: RtpPacket) {\n if (this.closed) return\n const sequence = rtp.header.sequenceNumber\n if (this.lastSequence !== undefined) {\n const gap = (sequence - this.lastSequence + 0x10000) & 0xffff\n // Late or repeated, its moment has passed\n if (gap === 0 || gap > 0x8000) return\n // Lost packets come back as silence, so the turn keeps its timing\n const lost = gap - 1\n if (lost > 0 && lost <= MAX_CONCEALED_FRAMES) {\n this.receiveAudio(\n Buffer.alloc(\n ((DEFAULT_SAMPLE_RATE * FRAME_DURATION) / 1000) * 2 * lost\n )\n )\n }\n }\n this.lastSequence = sequence\n if (rtp.payload.length === 0) return\n try {\n this.receiveAudio(this.codec.decode(rtp.payload))\n } catch (error) {\n this.logger.trace('Undecodable packet', { error })\n }\n }\n\n private receiveAudio(pcm: Buffer) {\n this.preroll.push(pcm)\n this.prerollBytes += pcm.length\n const max = ((DEFAULT_SAMPLE_RATE * PREROLL_MAX) / 1000) * 2\n while (this.prerollBytes - this.preroll[0].length >= max) {\n this.prerollBytes -= this.preroll.shift()!.length\n }\n this.emit('Audio', pcm)\n }\n\n /** The last `duration` ms of user audio */\n private takePreroll(duration: number): Buffer {\n const bytes = Math.round((DEFAULT_SAMPLE_RATE * duration) / 1000) * 2\n if (bytes === 0) return Buffer.alloc(0)\n const all = Buffer.concat(this.preroll)\n return all.subarray(Math.max(0, all.length - bytes))\n }\n\n private startPacer() {\n if (this.pacer || this.closed) return\n this.nextFrameAt = performance.now()\n this.pacer = setInterval(() => this.pace(), FRAME_DURATION / 2)\n }\n\n /** Sends every frame due, silence when the assistant is quiet */\n private pace() {\n const now = performance.now()\n // The process stalled: start again from now rather than catching up\n if (now - this.nextFrameAt > 10 * FRAME_DURATION) this.nextFrameAt = now\n while (this.nextFrameAt <= now) {\n this.sendFrame()\n this.nextFrameAt += FRAME_DURATION\n }\n }\n\n private sendFrame() {\n const frame = this.frames.shift()\n const talkspurt = !!frame && !this.playing\n if (frame) this.setPlaying(true)\n else if (this.playing) this.setPlaying(false)\n\n let payload: Buffer\n try {\n payload = this.codec.encode(frame ?? SILENCE)\n } catch (error) {\n this.logger.warn('Encoding failed', { error })\n return\n }\n const header = new RtpHeader({\n payloadType: this.payloadType,\n sequenceNumber: this.sequenceNumber,\n timestamp: this.timestamp,\n ssrc: this.ssrc,\n marker: talkspurt,\n })\n this.sequenceNumber = (this.sequenceNumber + 1) & 0xffff\n this.timestamp = (this.timestamp + OPUS_FRAME_SAMPLES) >>> 0\n this.outputTrack.writeRtp(new RtpPacket(header, payload))\n }\n\n private setPlaying(playing: boolean) {\n if (playing === this.playing) return\n this.playing = playing\n this.sendText(playing ? PLAYBACK_START : PLAYBACK_STOP)\n }\n\n private sendText(text: string) {\n if (this.closed) return\n const channel = this.channel\n if (channel?.readyState === 'open') channel.send(text)\n else this.pendingMessages.push(text)\n }\n\n private finish(code: number, reason: string | undefined, delay = 0) {\n if (this.closed) return\n this.closed = true\n if (this.pacer) clearInterval(this.pacer)\n if (this.disconnectTimer) clearTimeout(this.disconnectTimer)\n if (this.connectTimer) clearTimeout(this.connectTimer)\n this.frames = []\n this.codec.destroy()\n const closePeer = () => this.pc.close().catch(() => undefined)\n if (delay) setTimeout(closePeer, delay)\n else closePeer()\n this.emit('Close', code, reason)\n }\n}\n\nconst SILENCE = Buffer.alloc(FRAME_BYTES)\n\n// Gathering counts as over once no candidate came for this long\nconst GATHERING_QUIET = 200 // ms\n\n// How long a close waits for its message to reach the client\nconst CLOSE_FLUSH = 100 // ms\n"],"mappings":";AAWO,IAAM,qBAAqB;AAoB3B,IAAM,iBAAiB;AAGvB,IAAM,gBAAgB;AAOtB,SAAS,oBAAoB,UAAU,GAAW;AACvD,SAAO,UAAU,IAAI,iBAAiB,KAAK,MAAM,OAAO,CAAC,KAAK;AAChE;AAMO,SAAS,oBAAoB,MAAkC;AACpE,MAAI,SAAS,gBAAiB,QAAO;AACrC,QAAM,QAAQ,wBAAwB,KAAK,IAAI;AAC/C,SAAO,QAAQ,OAAO,MAAM,CAAC,CAAC,IAAI;AACpC;;;ACrDA,OAAO,gBAAgB;AAGhB,IAAM,mBAAmB;AAGzB,IAAM,qBAAqB;AAG3B,IAAM,mBAAmB;AA+BzB,SAAS,wBAAmC;AACjD,QAAM,UAAU,IAAI;AAAA,IAClB;AAA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AAkB;AACnC,QAAI,YAAY,KAAK,QAAS;AAC9B,SAAK,UAAU;AACf,SAAK,SAAS,UAAU,iBAAiB,aAAa;AAAA,EACxD;AAAA,EAEQ,SAAS,MAAc;AAC7B,QAAI,KAAK,OAAQ;AACjB,UAAM,UAAU,KAAK;AACrB,QAAI,SAAS,eAAe,OAAQ,SAAQ,KAAK,IAAI;AAAA,QAChD,MAAK,gBAAgB,KAAK,IAAI;AAAA,EACrC;AAAA,EAEQ,OAAO,MAAc,QAA4B,QAAQ,GAAG;AAClE,QAAI,KAAK,OAAQ;AACjB,SAAK,SAAS;AACd,QAAI,KAAK,MAAO,eAAc,KAAK,KAAK;AACxC,QAAI,KAAK,gBAAiB,cAAa,KAAK,eAAe;AAC3D,QAAI,KAAK,aAAc,cAAa,KAAK,YAAY;AACrD,SAAK,SAAS,CAAC;AACf,SAAK,MAAM,QAAQ;AACnB,UAAM,YAAY,MAAM,KAAK,GAAG,MAAM,EAAE,MAAM,MAAM,MAAS;AAC7D,QAAI,MAAO,YAAW,WAAW,KAAK;AAAA,QACjC,WAAU;AACf,SAAK,KAAK,SAAS,MAAM,MAAM;AAAA,EACjC;AACF;AAEA,IAAM,UAAU,OAAO,MAAM,WAAW;AAGxC,IAAM,kBAAkB;AAGxB,IAAM,cAAc;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,90 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@micdrop/webrtc",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "🖐️🎤 Micdrop: voice conversations with AI over WebRTC, in the browser, on a phone and on a Node server",
|
|
5
|
+
"author": "Godefroy de Compreignac",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"main": "dist/index.js",
|
|
8
|
+
"module": "dist/index.mjs",
|
|
9
|
+
"types": "dist/index.d.ts",
|
|
10
|
+
"scripts": {
|
|
11
|
+
"build": "tsup",
|
|
12
|
+
"dev": "tsup --watch",
|
|
13
|
+
"clean": "rm -rf dist",
|
|
14
|
+
"typecheck": "tsc --noEmit",
|
|
15
|
+
"prepublishOnly": "npm run build",
|
|
16
|
+
"test": "node --import tsx --test tests/*.test.ts"
|
|
17
|
+
},
|
|
18
|
+
"files": [
|
|
19
|
+
"dist"
|
|
20
|
+
],
|
|
21
|
+
"repository": {
|
|
22
|
+
"type": "git",
|
|
23
|
+
"url": "git+https://github.com/Godefroy/micdrop.git",
|
|
24
|
+
"directory": "packages/webrtc"
|
|
25
|
+
},
|
|
26
|
+
"publishConfig": {
|
|
27
|
+
"access": "public"
|
|
28
|
+
},
|
|
29
|
+
"keywords": [
|
|
30
|
+
"webrtc",
|
|
31
|
+
"voice agent",
|
|
32
|
+
"realtime",
|
|
33
|
+
"opus",
|
|
34
|
+
"voice",
|
|
35
|
+
"conversation"
|
|
36
|
+
],
|
|
37
|
+
"peerDependencies": {
|
|
38
|
+
"@micdrop/client": "^3.9.0",
|
|
39
|
+
"@micdrop/server": "^2.15.0",
|
|
40
|
+
"opusscript": "^0.1.1",
|
|
41
|
+
"react-native-webrtc": ">=124.0.0",
|
|
42
|
+
"werift": "^0.29.0"
|
|
43
|
+
},
|
|
44
|
+
"peerDependenciesMeta": {
|
|
45
|
+
"@micdrop/client": {
|
|
46
|
+
"optional": true
|
|
47
|
+
},
|
|
48
|
+
"@micdrop/server": {
|
|
49
|
+
"optional": true
|
|
50
|
+
},
|
|
51
|
+
"opusscript": {
|
|
52
|
+
"optional": true
|
|
53
|
+
},
|
|
54
|
+
"react-native-webrtc": {
|
|
55
|
+
"optional": true
|
|
56
|
+
},
|
|
57
|
+
"werift": {
|
|
58
|
+
"optional": true
|
|
59
|
+
}
|
|
60
|
+
},
|
|
61
|
+
"devDependencies": {
|
|
62
|
+
"@micdrop/client": "*",
|
|
63
|
+
"@micdrop/core": "*",
|
|
64
|
+
"@micdrop/server": "*",
|
|
65
|
+
"@types/node": "^22.19.13",
|
|
66
|
+
"opusscript": "^0.1.1",
|
|
67
|
+
"react-native-webrtc": "^124.0.7",
|
|
68
|
+
"tsup": "^8.5.1",
|
|
69
|
+
"tsx": "^4.20.6",
|
|
70
|
+
"typescript": "^5.9.3",
|
|
71
|
+
"werift": "^0.29.0"
|
|
72
|
+
},
|
|
73
|
+
"exports": {
|
|
74
|
+
".": {
|
|
75
|
+
"types": "./dist/index.d.ts",
|
|
76
|
+
"import": "./dist/index.mjs",
|
|
77
|
+
"require": "./dist/index.js"
|
|
78
|
+
},
|
|
79
|
+
"./react-native": {
|
|
80
|
+
"types": "./dist/react-native.d.ts",
|
|
81
|
+
"import": "./dist/react-native.mjs",
|
|
82
|
+
"require": "./dist/react-native.js"
|
|
83
|
+
},
|
|
84
|
+
"./server": {
|
|
85
|
+
"types": "./dist/server/index.d.ts",
|
|
86
|
+
"import": "./dist/server/index.mjs",
|
|
87
|
+
"require": "./dist/server/index.js"
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|