Playground key
create a key →

API v2 and SDK

SDK.

@droidhub/sdk connects any app to a room: send video into it, receive video out of it, send and receive real-time data, and manage rooms, keys and your organisation. What the video and the data mean is up to your app. A remote desktop sends its screen and takes pointer data; a robot sends its cameras and takes drive commands. It works in Node and in browsers, on top of the v2 API.

Install

sh
npm install @droidhub/sdk
npm install @livekit/rtc-node   # to connect from Node
npm install livekit-client      # to connect from a browser

Only the side that connects needs the second package. Managing rooms and keys needs neither. The source is on GitHub.

Keys

Every client takes one key, and its permissions decide what works.

KeyWhat it is
dh_api_…An API key. Belongs to your organisation and acts for it within its scopes. Keep it on your server.
dh_sk_…A stream key. Bound to one room, optionally to one identity and an expiry, and says what a connection may do: video.publish, video.receive, audio.publish, audio.receive, data.publish. Mint them on your server and hand them to the apps that connect.

Everyone in a room receives its data; data.publish decides who may send it. Revoke a stream key and whoever holds it is disconnected and can't connect again.

A remote desktop in three parts

Your server makes the room and mints a key for each side.

server.ts
import { DroidHub } from "@droidhub/sdk";

const dh = new DroidHub({ key: process.env.DROIDHUB_API_KEY });

const room = await dh.room.create({ name: "Support session 42" });
const host = await dh.room(room.id).keys.create({
  identity: "host-laptop",
  can: ["video.publish"],
  expiresIn: "1h",
});
const viewer = await dh.room(room.id).keys.create({
  identity: "agent-7",
  can: ["video.receive", "data.publish"],
  expiresIn: "1h",
});
// host.streamKey goes to the host app, viewer.streamKey to the viewer.

The host, in Node, publishes its screen and moves its mouse.

host.ts
const conn = await new DroidHub({ key: hostStreamKey }).room(roomId).connect();

const screen = await conn.video.publish({ width: 1280, height: 720 });
setInterval(() => screen.pushFrame(captureScreenAsRGBA()), 33);

conn.data.on("pointer", (message) => {
  const { x, y, buttons } = message.json();
  moveMouse(x, y, buttons);
});

The viewer, in a browser, watches and sends pointer data.

viewer.ts
const conn = await new DroidHub({ key: viewerStreamKey }).room(roomId).connect();

conn.video.on("stream", (video) => video.attach(document.querySelector("video")));

screenElement.addEventListener("pointermove", (e) => {
  conn.data.send("pointer", JSON.stringify({ x: e.offsetX, y: e.offsetY, buttons: e.buttons }), {
    reliable: false,
  });
});

When the session ends, await dh.keys.revoke(host.key.id) disconnects the host at once.

Sound

A call needs audio.publish to talk and audio.receive to listen. Your server mutes someone by taking audio.publish away with participants.update.

browser.ts
const conn = await new DroidHub({ key: streamKey }).room(roomId).connect();

const mic = await conn.audio.publish("microphone");
conn.audio.on("stream", (sound) => document.body.append(sound.attach()));
if (conn.audio.blocked) playButton.onclick = () => conn.audio.unblock();

muteButton.onclick = () => (mic.muted ? mic.unmute() : mic.mute());
node.ts
const speaker = await conn.audio.publish({ sampleRate: 48000, channels: 1 });
for await (const samples of synthesize(text)) {
  await speaker.pushFrame({ sampleRate: 48000, channels: 1, samples }); // Int16Array
}

conn.audio.on("stream", async (sound) => {
  for await (const frame of sound.frames()) transcribe(frame.samples);
});

One driver at a time

Your server decides who may send commands, and changes it while everyone stays connected. Mint viewers' keys without data.publish (a change lasts for the connection, and reconnecting gets the key's capabilities again); give it to whoever's turn it is and take it from the last driver.

server.ts
const room = dh.room(roomId);

async function handOver(from: string | null, to: string) {
  if (from) await room.participants.update(from, { can: ["video.receive"] });
  await room.participants.update(to, { can: ["video.receive", "data.publish"] });
  await room.data.send("turn", JSON.stringify({ driver: to }));
}

// Stop everything, whoever is driving.
await room.estop("Operator pressed stop");
driver.ts
conn.on("capabilities", (can) => setControlsEnabled(can.includes("data.publish")));
conn.on("estop", (estop) => showBanner(estop ? `Stopped: ${estop.reason}` : null));

Calls

CallNeeds
dh.room.create({ name, hls? })rooms:write
dh.room.list()rooms:read
dh.room(id).get()rooms:read, or a stream key for that room
dh.room(id).update({ name?, hls? })rooms:write
dh.room(id).delete()rooms:write
dh.room(id).keys.create({ can, identity?, label?, expiresIn? })keys:write
dh.room(id).keys.list()keys:read
dh.room(id).connect({ identity?, can?, video?, name? })rooms:connect, or a stream key for that room
dh.room(id).sessions()rooms:read, or a stream key for that room
dh.room(id).participants.list() / .get(identity)rooms:read, or a stream key for that room
dh.room(id).participants.update(identity, { can })rooms:write, plus rooms:connect to add a capability
dh.room(id).participants.remove(identity)rooms:write
dh.room(id).data.send(topic, payload, { to?, reliable? })rooms:connect
dh.room(id).estop(reason?) / .clearEstop()rooms:write or controller:write
dh.keys.get(keyId) / .revoke(keyId)keys:read / keys:write
dh.whoami()any key
dh.org.get() / .update({ name?, slug? })org:read / org:write
dh.org.keys.list() / .get() / .create({ name, permissions, expiresIn? }) / .delete()org:read / org:write
dh.org.members.list()org:read
dh.org.members.update(userId, { role }) / .remove(userId)every scope
dh.org.invitations.list()org:read
dh.org.invitations.create({ email, role? }) / .cancel(id)every scope
dh.org.webhooks.list() / .create(url) / .update(id, { enabled }) / .test(id) / .delete(id)webhooks:manage

With an API key, connect needs an identity, and the connection receives video and audio and sends data unless you pass can; add video.publish or audio.publish to publish. A stream key connects as its fixed identity, or as a made-up guest identity when it has none; it can't choose one. A key can't create or delete another key holding a scope it doesn't hold.

In a room

MemberWhat it does
video.publish(source)Node: { width, height }, then pushFrame({ width, height, format: "rgba", data }). Browser: a video MediaStreamTrack, or "camera" or "screen". Published under the name given at connect (video, default "main").
audio.publish(source) / mute() / unmute()Node: { sampleRate, channels }, then await pushFrame({ sampleRate, channels, samples }) with 16-bit PCM. Browser: "microphone" or an audio MediaStreamTrack.
audio.on("stream" | "ended") / audio.streams()Other connections' sound. Node: for await (const frame of sound.frames()) gives PCM. Browser: document.body.append(sound.attach()).
audio.blocked / audio.unblock()Browsers hold sound back until the user interacts with the page: call unblock() from a click.
video.on("stream" | "ended") / video.streams()Other connections' video. Node: for await (const frame of video.frames()) gives RGBA frames. Browser: video.attach(element).
data.send(topic, payload, { reliable?, to? })A string or bytes. Reliable messages arrive in order; lossy ones are faster and may drop.
data.on(topic | "*", handler)message.topic, from, bytes, text(), json().
rpc.handle(method, handler) / rpc.call(identity, method, payload?, { timeoutMs? })Request and response between connections over the data channel. Both sides need data.publish. A handler's thrown error reaches the caller.
participants() / on("participant.joined" | "participant.left" | "participant.updated")Who else is in the room, and what they may do.
can / on("capabilities")What this connection may do now. Follows changes your server makes with participants.update().
estop / on("estop")The room's e-stop while it's latched. Sending data fails with estopped until it's cleared.
state / on("reconnecting" | "reconnected" | "disconnected")The link to the room: connected, reconnecting or disconnected.

In a browser, video.publish("camera"), video.publish("screen") and audio.publish("microphone") ask the user for a track and stop it when the publishing stops. Messages your server sends with dh.room(id).data.send() arrive with from: null.

In Node, a message sent in a newcomer's first moments, before the room has announced it (about 3 seconds), arrives with from: null. Everything is delivered; only the sender can be unknown that early.

Errors and webhooks

Every failure is a DroidHubError with status, code (such as insufficient_scope or rate_limited) and, when the API asks you to wait, retryAfter. The client retries rate-limited requests after their Retry-After, and reads that hit a network error or a 502, 503 or 504, up to maxRetries times (default 2).

webhook handler
const event = await DroidHub.verifyWebhook(rawBody, signatureHeader, secret);

if (event.type === "stream.live") {
  console.log(event.data.streamId, event.data.name); // typed by event type
}

Pass the raw request body, before any JSON parsing. Events are typed by type, and dh.org.webhooks.test(id) sends a signed webhook.test event to check your handler.