WebRTC Voice Agent in Node.js, Without a Media Server
@micdrop/webrtc carries a call over WebRTC between the Micdrop client and
your own Node.js server. The microphone and the assistant voice travel as Opus
tracks, the Micdrop protocol on a data channel. The server side runs on
werift, a WebRTC stack written
in TypeScript, and libopus compiled to WebAssembly: no media server to rent,
nothing native to build.
npm install @micdrop/webrtcWhen WebRTC beats a WebSocket
A WebSocket runs over TCP, so one lost packet holds back everything after it until it is resent, which the user hears as a stutter. WebRTC sends the audio over UDP and skips a lost packet. On a weak mobile network or a crowded wifi, the voice keeps its pace. The browser also cancels the echo of a WebRTC track better than that of audio it plays itself, which lets the user interrupt the assistant on more laptops.
WebRTC asks for more than a WebSocket in return. The server needs UDP ports reachable from the internet, and some users sit behind networks that block UDP and need a TURN server to relay their audio. On a good network, a WebSocket is simpler and as good.
Server
The client posts its offer to an HTTP route, which answers with
WebRtcTransport.accept. The transport then goes to MicdropServer like a
socket would:
import Fastify from 'fastify'import { MicdropServer } from '@micdrop/server'import { WebRtcTransport } from '@micdrop/webrtc/server'
const app = Fastify()
app.post('/call', async (request) => { const transport = await WebRtcTransport.accept(request.body as any)
new MicdropServer(transport, { firstMessage: 'Hello, how can I help you?', agent, stt, tts, })
return transport.answer})
await app.listen({ port: 8081 })The offer carries the params of the call. waitForParams(transport, validate) hands them back as it does for a socket, and the route can check a
token before accepting anything:
import { MicdropWebRtcOffer, WebRtcTransport } from '@micdrop/webrtc/server'
app.post('/call', async (request, reply) => { const offer = request.body as MicdropWebRtcOffer if (!isValidToken(offer.params?.token)) { return reply.code(401).send('Unauthorized') } const transport = await WebRtcTransport.accept(offer) // ...})The client reads the status of a refused offer as the close code a WebSocket
would have sent: 401 and 403 give an Unauthorized error, 400 a BadRequest,
404 a NotFound, and 500 an InternalServer error the client retries.
Client
In a browser, hand a WebRTC transport to the client in place of a URL:
import { Micdrop } from '@micdrop/web'import { webRtcTransport } from '@micdrop/webrtc'
await Micdrop.start({ transport: webRtcTransport({ url: 'https://example.com/call' }), params: { token },})The rest of the client does not change: state, conversation, mute, pause, devices and reconnection work as over a WebSocket. The microphone track is the one the client already records from, so its VAD and the server hear the same audio, and the assistant plays through an audio element, which is where the browser applies its echo cancellation.
webRtcTransport also takes headers for the offer request and iceServers
for the browser.
Who detects the turns
The client keeps detecting the turns of its user, as over a WebSocket, and tells the server on the data channel. The track carries the microphone the whole time, so the server takes the beginning of each turn back from it: the start command says how much of the audio before it belongs to the turn.
Give the server a VAD and it detects the turns from the track instead, the client following on its own.
Network
A server with a public address answers with its own address and needs nothing more. Behind a NAT, in a container or on most cloud hosts, give it the way to reach it:
const transport = await WebRtcTransport.accept(offer, { // Learns the public address of the server iceServers: [{ urls: 'stun:stun.l.google.com:19302' }], peerConfig: { // Opens only these UDP ports in the firewall icePortRange: [40000, 40100], // Or announces the public address directly iceAdditionalHostAddresses: ['203.0.113.10'], },})Users behind a firewall that blocks UDP reach the server only through a TURN
server, given to both sides in iceServers. Hosted TURN services and coturn,
which you can run yourself, both work.
Opus codec
Each call encodes the assistant voice and decodes the microphone with libopus
compiled to WebAssembly, which takes a few percent of a core per call. A
server that holds many calls at once can bring a native binding through the
codec option, as an object with encode, decode and destroy.
React Native
@micdrop/webrtc/react-native runs the same transport on
react-native-webrtc:
import { Micdrop } from '@micdrop/react-native'import { webRtcTransport } from '@micdrop/webrtc/react-native'
await Micdrop.start({ transport: webRtcTransport({ url: 'https://example.com/call' }), serverTurns: true,})react-native-webrtc opens its own microphone track and gives the app no
samples of it, so the client cannot detect the turns from what it sends. Give
the server a VAD for these calls, and pass serverTurns so
the phone runs none. Like the rest of Micdrop on
a phone, it runs in a development build rather than in Expo Go.