@twilio/video-node-sdk 1.0.0-beta.1
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/CHANGELOG.md +409 -0
- package/FRAME_CONTRACT.md +204 -0
- package/LICENSE.md +3 -0
- package/LIFECYCLE.md +123 -0
- package/README.md +617 -0
- package/SECURITY-PRIVACY.md +25 -0
- package/dist/index.cjs +1822 -0
- package/dist/index.d.cts +1671 -0
- package/dist/index.d.mts +1671 -0
- package/dist/index.mjs +1740 -0
- package/package.json +111 -0
- package/prebuilds/darwin-x64/twilio_video_sdk_node-darwin-x64.node +0 -0
- package/prebuilds/linux-x64/twilio_video_sdk_node-linux-x64.node +0 -0
package/README.md
ADDED
|
@@ -0,0 +1,617 @@
|
|
|
1
|
+
# @twilio/video-node-sdk
|
|
2
|
+
|
|
3
|
+
[](https://github.com/twilio/twilio-video-node/actions/workflows/ci.yml)
|
|
4
|
+
|
|
5
|
+
Server-side Node.js SDK for Twilio Video Group Rooms with raw media frame access. Built on a native C++ addon over WebRTC, it lets you push and receive decoded video and audio frames from Node.js on realtime.
|
|
6
|
+
|
|
7
|
+
[API reference](https://twilio.github.io/twilio-video-node/latest/)
|
|
8
|
+
|
|
9
|
+
**Note: this is a beta release of the Twilio Media SDK for Node.js. It is provided for evaluation purposes only and should not be used with production traffic. During the beta period this SDK is not HIPAA eligible.**
|
|
10
|
+
|
|
11
|
+
## Installation
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
npm install @twilio/video-node-sdk
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
The native binary is prebuilt and bundled — no build step required.
|
|
18
|
+
|
|
19
|
+
**Requirements:**
|
|
20
|
+
|
|
21
|
+
- Node.js >= 24.0.0
|
|
22
|
+
- Linux x86-64, glibc >= 2.34 (Ubuntu 22.04+, Debian 12+), or
|
|
23
|
+
- macOS 26+ on x86-64 (Intel, or Apple Silicon with Node running under Rosetta)
|
|
24
|
+
|
|
25
|
+
Alpine/musl, native arm64 and Windows are not supported. See [Platform Support](#platform-support) for the full requirements.
|
|
26
|
+
|
|
27
|
+
### Access Token
|
|
28
|
+
|
|
29
|
+
The `connect()` function takes a standard Twilio Video Access Token with a
|
|
30
|
+
VideoGrant, the same token format used by the JavaScript SDK. Generate one
|
|
31
|
+
using the [`twilio`](https://www.npmjs.com/package/twilio) helper library. See
|
|
32
|
+
[User Identity and Access Tokens](https://www.twilio.com/docs/video/tutorials/user-identity-access-tokens)
|
|
33
|
+
for details.
|
|
34
|
+
|
|
35
|
+
## Quick Start
|
|
36
|
+
|
|
37
|
+
```js
|
|
38
|
+
const { connect, createLocalVideoTrack } = require('@twilio/video-node-sdk');
|
|
39
|
+
|
|
40
|
+
async function main() {
|
|
41
|
+
const videoTrack = createLocalVideoTrack('my-camera');
|
|
42
|
+
|
|
43
|
+
const room = await connect(token, {
|
|
44
|
+
name: 'my-room',
|
|
45
|
+
videoTracks: [videoTrack],
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
console.log('Connected:', room.name, room.sid);
|
|
49
|
+
|
|
50
|
+
// Push I420 video frames. connect() resolves only once the Room is connected;
|
|
51
|
+
// frames written before that are dropped and counted in getWriteStats().
|
|
52
|
+
videoTrack.write({
|
|
53
|
+
format: 'I420',
|
|
54
|
+
width: 1280,
|
|
55
|
+
height: 720,
|
|
56
|
+
y: { data: yPlane, stride: 1280, width: 1280, height: 720 },
|
|
57
|
+
u: { data: uPlane, stride: 640, width: 640, height: 360 },
|
|
58
|
+
v: { data: vPlane, stride: 640, width: 640, height: 360 },
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
async function trackSubscribed(track) {
|
|
62
|
+
if (track.kind !== 'video') return;
|
|
63
|
+
// Awaiting each frame is the backpressure. The loop ends by itself when the
|
|
64
|
+
// track is unsubscribed or the Room disconnects.
|
|
65
|
+
for await (const frame of track.frames()) {
|
|
66
|
+
console.log(`${frame.width}x${frame.height} @ ${frame.timestamp}us`);
|
|
67
|
+
frame.close?.();
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function participantConnected(participant) {
|
|
72
|
+
participant.on('trackSubscribed', trackSubscribed);
|
|
73
|
+
|
|
74
|
+
participant.tracks.forEach(publication => {
|
|
75
|
+
if (publication.isSubscribed) {
|
|
76
|
+
trackSubscribed(publication.track);
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// participantConnected does not fire for participants already in the Room, and a
|
|
82
|
+
// track can finish subscribing before this listener is attached. Seed from
|
|
83
|
+
// room.participants and check isSubscribed on the publications found there.
|
|
84
|
+
room.participants.forEach(participantConnected);
|
|
85
|
+
room.on('participantConnected', participantConnected);
|
|
86
|
+
|
|
87
|
+
room.on('disconnected', () => {
|
|
88
|
+
room.dispose();
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
main().catch(err => {
|
|
93
|
+
console.error('Error:', err);
|
|
94
|
+
process.exit(1);
|
|
95
|
+
});
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
## Releasing a Room
|
|
99
|
+
|
|
100
|
+
Call `room.dispose()` when you are done with a Room. Until you do, the process
|
|
101
|
+
does not exit on its own. `disconnect()` leaves the session but does not release
|
|
102
|
+
the native resources behind it.
|
|
103
|
+
|
|
104
|
+
The `disconnected` event is the clearest place to dispose, as in the quick
|
|
105
|
+
start.
|
|
106
|
+
|
|
107
|
+
For what each object owns, what teardown releases, and the ordering the SDK
|
|
108
|
+
guarantees during teardown, see [LIFECYCLE.md](LIFECYCLE.md).
|
|
109
|
+
|
|
110
|
+
## Differences from the JavaScript SDK
|
|
111
|
+
|
|
112
|
+
This SDK shares the same Room/Participant/Track model and event names as the
|
|
113
|
+
[Twilio Video JavaScript SDK](https://www.twilio.com/docs/video/javascript),
|
|
114
|
+
but is designed for server-side media processing rather than browser-based
|
|
115
|
+
conferencing. Key differences:
|
|
116
|
+
|
|
117
|
+
- **No device capture.** `createLocalVideoTrack()` and `createLocalAudioTrack()`
|
|
118
|
+
return pushable tracks with no media constraints. You supply raw frames via
|
|
119
|
+
`track.write()` instead of capturing from a camera or microphone.
|
|
120
|
+
|
|
121
|
+
- **No rendering.** There is no `track.attach(element)`. Remote media arrives as
|
|
122
|
+
raw decoded frames (I420 video, PCM audio) through
|
|
123
|
+
`for await (const frame of track.frames())`.
|
|
124
|
+
|
|
125
|
+
- **Fixed audio input format.** `LocalAudioTrack.write()` accepts only 48 kHz
|
|
126
|
+
mono S16LE PCM. Received audio may vary in sample rate and channel count.
|
|
127
|
+
|
|
128
|
+
- **No adaptive simulcast or track priority.** Published video tracks always use
|
|
129
|
+
standard priority with simulcast disabled; the deprecated `TrackPriority` API
|
|
130
|
+
is not exposed. Bandwidth and remote render-size hints are configurable
|
|
131
|
+
instead via `bandwidthProfile`, `encodingParameters`, and
|
|
132
|
+
`RemoteVideoTrack.setContentPreferences()`.
|
|
133
|
+
|
|
134
|
+
- **Synchronous track creation.** `createLocalVideoTrack()` returns a track
|
|
135
|
+
immediately (no async device permissions). Tracks can be passed to `connect()`
|
|
136
|
+
or published later via `localParticipant.publishTrack()`.
|
|
137
|
+
|
|
138
|
+
## API Overview
|
|
139
|
+
|
|
140
|
+
### Top-level Functions
|
|
141
|
+
|
|
142
|
+
| Function | Description |
|
|
143
|
+
| ---------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
144
|
+
| `connect(token, options?)` | Connect to a room. Returns `Promise<Room>`. |
|
|
145
|
+
| `createLocalVideoTrack(name?)` | Create a pushable local video track. |
|
|
146
|
+
| `createLocalAudioTrack(name?)` | Create a pushable local audio track. |
|
|
147
|
+
| `createLocalDataTrack(name \| options?)` | Create a local data track. Options are `name`, `ordered`, and one of `maxPacketLifeTime`/`maxRetransmits`. |
|
|
148
|
+
| `createLocalTracks(options?)` | Create local audio and/or video tracks. With no options, returns both. If either `audio` or `video` is specified, the other defaults to `false`. Each key accepts `true`/`false` or a per-track options object (e.g. `{ name }`). Returns `Promise<(LocalAudioTrack \| LocalVideoTrack)[]>`. |
|
|
149
|
+
| `twilioErrorFromCode(code, message?)` | Build a `TwilioError` (or matching subclass) from a numeric error code. |
|
|
150
|
+
| `setLogLevel(level)` | Set native log level. Accepts a name (`'off'` \| `'fatal'` \| `'error'` \| `'warning'` \| `'info'` \| `'debug'` \| `'trace'` \| `'all'`) or the equivalent number `0` (off) through `7` (all). |
|
|
151
|
+
| `getVersion()` | Returns the native SDK version string. |
|
|
152
|
+
| `MAX_QUEUE_CEILING` | Upper bound (`1024`) accepted for any `maxQueue`, on `frames()` and on `source.maxQueue`. |
|
|
153
|
+
| `SDK_LOCAL_CODE` | The `code` (`0`) carried by errors the SDK raises locally, which Twilio never assigns a code to. Match on the error class instead. |
|
|
154
|
+
|
|
155
|
+
### Key Classes
|
|
156
|
+
|
|
157
|
+
| Export | Description |
|
|
158
|
+
| ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
159
|
+
| `Room` | A connected video room. Emits events, exposes participants. |
|
|
160
|
+
| `LocalParticipant` | The local participant. Publish/unpublish tracks. |
|
|
161
|
+
| `RemoteParticipant` | A remote participant. Emits `trackSubscribed`/`trackUnsubscribed`. |
|
|
162
|
+
| `LocalVideoTrack` | Pushable video track (`write(frame)`). |
|
|
163
|
+
| `LocalAudioTrack` | Pushable audio track (`write(frame)`, `clearBuffer()`). |
|
|
164
|
+
| `LocalDataTrack` | Send arbitrary data (`send`). Create via `createLocalDataTrack(name \| options?)`. |
|
|
165
|
+
| `RemoteVideoTrack` | Receive video frames (`frames()`), `getStats()`, `frameDropped` event. |
|
|
166
|
+
| `RemoteAudioTrack` | Receive audio frames (`frames()`), `getStats()`, `frameDropped` event. |
|
|
167
|
+
| `RemoteDataTrack` | Receive data messages (`message` event). |
|
|
168
|
+
| `TrackPublication` | Base class for published tracks (`trackSid`, `trackName`, `kind`, `isTrackEnabled`). |
|
|
169
|
+
| `LocalTrackPublication` | Local publication. Exposes `track` and `unpublish()`. Subclassed per kind (`LocalVideoTrackPublication`, …). |
|
|
170
|
+
| `RemoteTrackPublication` | Remote publication. Exposes `track` and `isSubscribed`. Subclassed per kind (`RemoteVideoTrackPublication`, …). |
|
|
171
|
+
| `TwilioError` | Base error class, carrying a numeric `code`. One subclass per known Twilio code, plus SDK-local errors (`NativeBindingLoadError`, `RoomConnectTimeoutError`, …). |
|
|
172
|
+
| `ErrorCode` | Enum of Twilio Video error codes. |
|
|
173
|
+
|
|
174
|
+
## Room Events
|
|
175
|
+
|
|
176
|
+
### Room state at connect
|
|
177
|
+
|
|
178
|
+
`participantConnected` is not emitted for participants who were already in the Room when
|
|
179
|
+
`connect()` resolved. They are part of the Room's starting state: read them from
|
|
180
|
+
`room.participants`.
|
|
181
|
+
|
|
182
|
+
A participant who was already publishing emits `trackSubscribed` after `connect()` resolves.
|
|
183
|
+
Subscriptions that completed before the listener was attached are not replayed, and appear in
|
|
184
|
+
`participant.tracks` with `isSubscribed` set to `true`.
|
|
185
|
+
|
|
186
|
+
| Event | Handler Signature |
|
|
187
|
+
| ------------------------- | -------------------------------------------------- |
|
|
188
|
+
| `disconnected` | `(room: Room, error?: TwilioError) => void` |
|
|
189
|
+
| `connectFailure` | `(error: TwilioError) => void` |
|
|
190
|
+
| `reconnecting` | `(error?: TwilioError) => void` |
|
|
191
|
+
| `reconnected` | `() => void` |
|
|
192
|
+
| `participantConnected` | `(participant: RemoteParticipant) => void` |
|
|
193
|
+
| `participantDisconnected` | `(participant: RemoteParticipant) => void` |
|
|
194
|
+
| `participantReconnecting` | `(participant: RemoteParticipant) => void` |
|
|
195
|
+
| `participantReconnected` | `(participant: RemoteParticipant) => void` |
|
|
196
|
+
| `recordingStarted` | `() => void` |
|
|
197
|
+
| `recordingStopped` | `() => void` |
|
|
198
|
+
| `dominantSpeakerChanged` | `(participant: RemoteParticipant \| null) => void` |
|
|
199
|
+
| `transcription` | `(transcriptionJson: string) => void` |
|
|
200
|
+
|
|
201
|
+
The Room re-emits every track event in [RemoteParticipant Events](#remoteparticipant-events),
|
|
202
|
+
appending the `RemoteParticipant` that emitted it as the last argument. Handle every
|
|
203
|
+
participant's tracks from one place instead of attaching a listener to each participant.
|
|
204
|
+
|
|
205
|
+
### RemoteParticipant Events
|
|
206
|
+
|
|
207
|
+
| Event | Handler Signature |
|
|
208
|
+
| ---------------------------- | --------------------------------------------------------------------------------------------------------------- |
|
|
209
|
+
| `trackSubscribed` | `(track: RemoteVideoTrack \| RemoteAudioTrack \| RemoteDataTrack, publication: RemoteTrackPublication) => void` |
|
|
210
|
+
| `trackUnsubscribed` | `(track: RemoteVideoTrack \| RemoteAudioTrack \| RemoteDataTrack, publication: RemoteTrackPublication) => void` |
|
|
211
|
+
| `trackSubscriptionFailed` | `(error: TwilioError, publication: RemoteTrackPublication) => void` |
|
|
212
|
+
| `trackPublished` | `(publication: RemoteTrackPublication) => void` |
|
|
213
|
+
| `trackUnpublished` | `(publication: RemoteTrackPublication) => void` |
|
|
214
|
+
| `trackEnabled` | `(publication: RemoteTrackPublication) => void` |
|
|
215
|
+
| `trackDisabled` | `(publication: RemoteTrackPublication) => void` |
|
|
216
|
+
| `videoTrackSwitchedOff` | `(track: RemoteVideoTrack) => void` |
|
|
217
|
+
| `videoTrackSwitchedOn` | `(track: RemoteVideoTrack) => void` |
|
|
218
|
+
| `networkQualityLevelChanged` | `(level: number) => void` |
|
|
219
|
+
|
|
220
|
+
### LocalParticipant Events
|
|
221
|
+
|
|
222
|
+
| Event | Handler Signature |
|
|
223
|
+
| ---------------------------- | ------------------------------------------------------- |
|
|
224
|
+
| `trackPublished` | `(publication: LocalTrackPublication) => void` |
|
|
225
|
+
| `trackPublicationFailed` | `(error: TwilioError, localTrack?: LocalTrack) => void` |
|
|
226
|
+
| `networkQualityLevelChanged` | `(level: number) => void` |
|
|
227
|
+
|
|
228
|
+
### TrackPublication
|
|
229
|
+
|
|
230
|
+
`LocalTrackPublication` exposes `track` (the local track instance) and an `unpublish()` method:
|
|
231
|
+
|
|
232
|
+
```js
|
|
233
|
+
const pub = room.localParticipant.tracks.get(trackSid); // LocalTrackPublication
|
|
234
|
+
pub.unpublish(); // unpublishes the underlying track
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
`RemoteTrackPublication` exposes `track` (the subscribed remote track, if any) and `isSubscribed`.
|
|
238
|
+
|
|
239
|
+
### Room.getStats()
|
|
240
|
+
|
|
241
|
+
Returns a snapshot of WebRTC stats per peer connection. Rejects if the room is disconnected.
|
|
242
|
+
|
|
243
|
+
```js
|
|
244
|
+
const reports = await room.getStats();
|
|
245
|
+
// reports[i]: {
|
|
246
|
+
// peerConnectionId, localAudioTrackStats, localVideoTrackStats,
|
|
247
|
+
// remoteAudioTrackStats, remoteVideoTrackStats
|
|
248
|
+
// }
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
## Track Types
|
|
252
|
+
|
|
253
|
+
### LocalVideoTrack
|
|
254
|
+
|
|
255
|
+
Push raw I420 video frames into a room. Frames written before `connect()` resolves are dropped, and counted in `getWriteStats()`.
|
|
256
|
+
|
|
257
|
+
```js
|
|
258
|
+
const track = createLocalVideoTrack('camera');
|
|
259
|
+
track.write({
|
|
260
|
+
format: 'I420', // optional; only 'I420' is accepted
|
|
261
|
+
width,
|
|
262
|
+
height, // both must be positive and even
|
|
263
|
+
y: { data: yBuffer, stride: yStride, width, height },
|
|
264
|
+
u: { data: uBuffer, stride: uStride, width: width / 2, height: height / 2 },
|
|
265
|
+
v: { data: vBuffer, stride: vStride, width: width / 2, height: height / 2 },
|
|
266
|
+
timestamp, // optional microseconds; defaults to monotonic now
|
|
267
|
+
rotation, // optional 0 | 90 | 180 | 270
|
|
268
|
+
});
|
|
269
|
+
track.enabled = false; // mute
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
Buffers are copied synchronously, so they can be reused as soon as `write()` returns.
|
|
273
|
+
|
|
274
|
+
`write()` returns `false` when the frame was dropped rather than encoded - most often because the encoder sink has not attached yet, but also when libwebrtc's adapter rate-limits or rejects the resolution. It throws `TypeError`/`RangeError` on invalid input.
|
|
275
|
+
|
|
276
|
+
Optionally pin the frame size at creation, so a mismatched frame is rejected instead of silently rescaled:
|
|
277
|
+
|
|
278
|
+
```js
|
|
279
|
+
const track = createLocalVideoTrack({
|
|
280
|
+
name: 'camera',
|
|
281
|
+
source: { type: 'raw', format: 'I420', width: 1280, height: 720, fps: 30 },
|
|
282
|
+
});
|
|
283
|
+
```
|
|
284
|
+
|
|
285
|
+
Publish-side counters:
|
|
286
|
+
|
|
287
|
+
```js
|
|
288
|
+
const { framesWritten, framesDropped, sendQueueDepth, maxQueue, lastTimestamp } =
|
|
289
|
+
track.getWriteStats();
|
|
290
|
+
```
|
|
291
|
+
|
|
292
|
+
Video publish is synchronous - `write()` hands the frame straight to the encoder - so there is no SDK-side send queue and `sendQueueDepth`/`maxQueue` are always `0`. A `framesDropped` here means the frame was rejected, not shed from a queue.
|
|
293
|
+
|
|
294
|
+
### LocalAudioTrack
|
|
295
|
+
|
|
296
|
+
Push raw PCM audio samples into a room. Format is fixed to **48kHz mono S16LE**.
|
|
297
|
+
|
|
298
|
+
```js
|
|
299
|
+
const track = createLocalAudioTrack('mic');
|
|
300
|
+
const accepted = track.write({
|
|
301
|
+
pcm, // Buffer of interleaved int16 samples
|
|
302
|
+
frames, // samples per channel, e.g. 480 for a 10ms chunk
|
|
303
|
+
timestamp, // optional microseconds
|
|
304
|
+
});
|
|
305
|
+
```
|
|
306
|
+
|
|
307
|
+
Unlike video, audio publish has a real send queue, drained one 10 ms chunk at a
|
|
308
|
+
time. It is bounded (~500 ms by default) so a producer running faster than real
|
|
309
|
+
time cannot accumulate latency. A `write()` is accepted only if it fits whole in
|
|
310
|
+
the remaining space; otherwise nothing is buffered, `write()` returns `false`,
|
|
311
|
+
and the rejection is counted. A single `write()` larger than the bound can never
|
|
312
|
+
fit, so size `maxQueue` to the largest burst you intend to publish:
|
|
313
|
+
|
|
314
|
+
```js
|
|
315
|
+
const track = createLocalAudioTrack({
|
|
316
|
+
name: 'mic',
|
|
317
|
+
// maxQueue is in 10ms chunks: 200 => ~2s of smoothing. It binds the
|
|
318
|
+
// process-wide audio device, so it applies to every local audio track.
|
|
319
|
+
source: { type: 'raw', format: 'PCM_S16LE', sampleRate: 48000, channels: 1, maxQueue: 200 },
|
|
320
|
+
});
|
|
321
|
+
const { framesWritten, framesDropped, sendQueueDepth, maxQueue } = track.getWriteStats();
|
|
322
|
+
```
|
|
323
|
+
|
|
324
|
+
Publishing at real-time cadence should never drop. A non-zero `framesDropped`
|
|
325
|
+
means the producer is outrunning the wire, or that a single `write()` was larger
|
|
326
|
+
than `maxQueue`.
|
|
327
|
+
|
|
328
|
+
The `timestamp` on an audio frame is observability-only. Audio publish is FIFO:
|
|
329
|
+
the device emits queued samples on its own 10 ms cadence, so the timestamp feeds
|
|
330
|
+
`lastTimestamp` and `timestampRegressions` and does not change what is sent.
|
|
331
|
+
|
|
332
|
+
`clearBuffer()` discards whatever is still queued and not yet sent. Use it when
|
|
333
|
+
the queued audio has become stale rather than merely late - barge-in, where the
|
|
334
|
+
speaker is interrupted and the rest of the utterance should never play, is the
|
|
335
|
+
usual case. Writes after it resume from an empty queue.
|
|
336
|
+
|
|
337
|
+
```js
|
|
338
|
+
track.clearBuffer();
|
|
339
|
+
```
|
|
340
|
+
|
|
341
|
+
### LocalDataTrack
|
|
342
|
+
|
|
343
|
+
Send arbitrary string or binary messages. Delivery is reliable and ordered by default.
|
|
344
|
+
|
|
345
|
+
```js
|
|
346
|
+
const track = createLocalDataTrack({ name: 'chat', ordered: true });
|
|
347
|
+
room.localParticipant.publishTrack(track);
|
|
348
|
+
track.send('hello');
|
|
349
|
+
track.send(Buffer.from([0x01, 0x02]));
|
|
350
|
+
|
|
351
|
+
// send() reports the outcome. The promise always resolves - never rejects - so
|
|
352
|
+
// a fire-and-forget send cannot produce an unhandled rejection.
|
|
353
|
+
const result = await track.send('important');
|
|
354
|
+
if (!result.ok) console.warn('send failed:', result.error);
|
|
355
|
+
```
|
|
356
|
+
|
|
357
|
+
Messages larger than **64 KB** (`kMaxMessageSize`) are rejected synchronously
|
|
358
|
+
with a `RangeError` and never transmitted.
|
|
359
|
+
|
|
360
|
+
Pass `maxPacketLifeTime` (milliseconds) or `maxRetransmits` (a count) to trade reliability for
|
|
361
|
+
latency. The two are mutually exclusive, and each must be an integer from 0 to 65535.
|
|
362
|
+
|
|
363
|
+
```js
|
|
364
|
+
const telemetry = createLocalDataTrack({ name: 'telemetry', maxPacketLifeTime: 500 });
|
|
365
|
+
telemetry.maxPacketLifeTime; // 500
|
|
366
|
+
telemetry.maxRetransmits; // null
|
|
367
|
+
telemetry.reliable; // false
|
|
368
|
+
```
|
|
369
|
+
|
|
370
|
+
`maxPacketLifeTime` and `maxRetransmits` are `number | null`, reading back as `null` when the
|
|
371
|
+
limit was not set. `reliable` is `true` only when neither is set.
|
|
372
|
+
|
|
373
|
+
### RemoteVideoTrack
|
|
374
|
+
|
|
375
|
+
Receive decoded I420 video frames from a remote participant.
|
|
376
|
+
|
|
377
|
+
```js
|
|
378
|
+
for await (const frame of track.frames()) {
|
|
379
|
+
// frame: {
|
|
380
|
+
// format: 'I420',
|
|
381
|
+
// width, height,
|
|
382
|
+
// y, u, v, // I420Plane: { data: Buffer, stride, width, height }
|
|
383
|
+
// timestamp: number, // microseconds
|
|
384
|
+
// captureTimestamp?: number,
|
|
385
|
+
// rtpTimestamp?: number,
|
|
386
|
+
// frameId: number, // SDK-generated, monotonic per track
|
|
387
|
+
// rotation?: 0 | 90 | 180 | 270,
|
|
388
|
+
// close?(): void, // optional prompt release
|
|
389
|
+
// }
|
|
390
|
+
frame.close?.();
|
|
391
|
+
}
|
|
392
|
+
// The loop ends on unsubscribe or Room disconnect. `break` releases the track.
|
|
393
|
+
|
|
394
|
+
// Hint the desired render dimensions to the SFU. Width/height must be positive
|
|
395
|
+
// integers. Only takes effect when the room was connected with a
|
|
396
|
+
// bandwidthProfile that has `contentPreferencesMode: 'manual'`.
|
|
397
|
+
track.setContentPreferences({ renderDimensions: { width: 320, height: 240 } });
|
|
398
|
+
|
|
399
|
+
// `isSwitchedOff` is `true` when the SFU has stopped delivering this track
|
|
400
|
+
// (e.g. due to bandwidth-profile constraints). Pair with the
|
|
401
|
+
// `videoTrackSwitchedOff` / `videoTrackSwitchedOn` events on RemoteParticipant.
|
|
402
|
+
track.isSwitchedOff;
|
|
403
|
+
```
|
|
404
|
+
|
|
405
|
+
### RemoteAudioTrack
|
|
406
|
+
|
|
407
|
+
Receive decoded PCM audio frames from a remote participant.
|
|
408
|
+
|
|
409
|
+
```js
|
|
410
|
+
for await (const frame of track.frames()) {
|
|
411
|
+
// frame: {
|
|
412
|
+
// format: 'PCM_S16LE',
|
|
413
|
+
// sampleRate, channels, frames,
|
|
414
|
+
// pcm: Buffer, // interleaved int16 samples
|
|
415
|
+
// timestamp: number, // microseconds
|
|
416
|
+
// frameId: number, // SDK-generated, monotonic per track
|
|
417
|
+
// close?(): void,
|
|
418
|
+
// }
|
|
419
|
+
}
|
|
420
|
+
```
|
|
421
|
+
|
|
422
|
+
### RemoteDataTrack
|
|
423
|
+
|
|
424
|
+
Receive string or binary messages from a remote participant.
|
|
425
|
+
|
|
426
|
+
```js
|
|
427
|
+
track.on('message', (data, track) => {
|
|
428
|
+
/* data is string | Buffer; track is the RemoteDataTrack it arrived on */
|
|
429
|
+
});
|
|
430
|
+
```
|
|
431
|
+
|
|
432
|
+
`maxPacketLifeTime`, `maxRetransmits`, `reliable`, and `ordered` report how the publisher
|
|
433
|
+
configured delivery. A publisher's limit of `65535` reads back as `null`, because a subscribed
|
|
434
|
+
track reports it the same way it reports an unset limit; `reliable` still distinguishes the two.
|
|
435
|
+
|
|
436
|
+
For the precise guarantees - buffer ownership, where frames are dropped, drop
|
|
437
|
+
policy and ordering, timestamp rules, and the publish invariants - see
|
|
438
|
+
[FRAME_CONTRACT.md](FRAME_CONTRACT.md).
|
|
439
|
+
|
|
440
|
+
## Frame Formats
|
|
441
|
+
|
|
442
|
+
### Video (`VideoFrame` / `VideoFrameInput`)
|
|
443
|
+
|
|
444
|
+
I420 planar layout. Each plane is an `I420Plane`: `{ data: Buffer, stride, width, height }`, where `stride` is bytes per row (≥ the plane's width, padded for alignment).
|
|
445
|
+
|
|
446
|
+
| Plane | Logical size | `data` size | Description |
|
|
447
|
+
| ----- | ------------------------ | ----------------------- | ---------------- |
|
|
448
|
+
| Y | `width × height` | `y.stride × height` | Luminance |
|
|
449
|
+
| U | `⌈width/2⌉ × ⌈height/2⌉` | `u.stride × ⌈height/2⌉` | Chrominance (Cb) |
|
|
450
|
+
| V | `⌈width/2⌉ × ⌈height/2⌉` | `v.stride × ⌈height/2⌉` | Chrominance (Cr) |
|
|
451
|
+
|
|
452
|
+
Publish and receive use the **same** planar shape: each of `y`/`u`/`v` is an `I420Plane` (`{ data, stride, width, height }`). A received frame can be written straight back out without reshaping.
|
|
453
|
+
|
|
454
|
+
Timestamps are plain numbers of **microseconds** (`timestamp`). Microsecond resolution stays exact in a JS number for roughly 285 years, and the underlying engine reports microseconds natively. `rotation` is `0 | 90 | 180 | 270`.
|
|
455
|
+
|
|
456
|
+
### Audio (`AudioFrame` / `AudioFrameInput`)
|
|
457
|
+
|
|
458
|
+
Interleaved 16-bit signed little-endian PCM in a single `Buffer`.
|
|
459
|
+
|
|
460
|
+
- **Inputs** to `LocalAudioTrack.write()` are fixed at **48kHz mono** — only `pcm` and `frames` are accepted.
|
|
461
|
+
- **Received `AudioFrame`s** include `sampleRate`, `channels`, `frames`, `pcm`, `timestamp` (microseconds), and `frameId`.
|
|
462
|
+
|
|
463
|
+
## Configuration
|
|
464
|
+
|
|
465
|
+
### ConnectOptions
|
|
466
|
+
|
|
467
|
+
```ts
|
|
468
|
+
{
|
|
469
|
+
name?: string; // Room name
|
|
470
|
+
videoTracks?: LocalVideoTrack[]; // Tracks to publish on connect
|
|
471
|
+
audioTracks?: LocalAudioTrack[];
|
|
472
|
+
dataTracks?: LocalDataTrack[];
|
|
473
|
+
enableInsights?: boolean;
|
|
474
|
+
enableAutomaticSubscription?: boolean;
|
|
475
|
+
enableDominantSpeaker?: boolean;
|
|
476
|
+
networkQuality?: boolean | { local?: 1; remote?: 0 | 1 };
|
|
477
|
+
preferredAudioCodecs?: ('opus' | 'PCMU')[];
|
|
478
|
+
preferredVideoCodecs?: 'VP8'[];
|
|
479
|
+
videoEncodingMode?: 'auto';
|
|
480
|
+
bandwidthProfile?: BandwidthProfileOptions;
|
|
481
|
+
receiveTranscriptions?: boolean;
|
|
482
|
+
region?: string; // e.g. 'us1', 'au1'
|
|
483
|
+
iceOptions?: IceOptions;
|
|
484
|
+
encodingParameters?: EncodingParameters;
|
|
485
|
+
connectionTimeout?: number; // ms; default 30000, 0 waits indefinitely
|
|
486
|
+
}
|
|
487
|
+
```
|
|
488
|
+
|
|
489
|
+
### BandwidthProfileOptions
|
|
490
|
+
|
|
491
|
+
```ts
|
|
492
|
+
{
|
|
493
|
+
video?: {
|
|
494
|
+
mode?: 'collaboration' | 'grid' | 'presentation';
|
|
495
|
+
maxSubscriptionBitrate?: number; // bits per second
|
|
496
|
+
trackSwitchOffMode?: 'detected' | 'predicted' | 'disabled';
|
|
497
|
+
clientTrackSwitchOffControl?: 'auto' | 'manual';
|
|
498
|
+
contentPreferencesMode?: 'auto' | 'manual';
|
|
499
|
+
};
|
|
500
|
+
}
|
|
501
|
+
```
|
|
502
|
+
|
|
503
|
+
### EncodingParameters
|
|
504
|
+
|
|
505
|
+
```ts
|
|
506
|
+
{
|
|
507
|
+
maxAudioBitrate?: number; // bits per second
|
|
508
|
+
maxVideoBitrate?: number; // bits per second
|
|
509
|
+
}
|
|
510
|
+
```
|
|
511
|
+
|
|
512
|
+
### IceOptions
|
|
513
|
+
|
|
514
|
+
```ts
|
|
515
|
+
{
|
|
516
|
+
transportPolicy?: 'all' | 'relay'; // 'relay' forces TURN
|
|
517
|
+
iceServers?: IceServer[]; // { urls: string[]; username?: string; credential?: string }
|
|
518
|
+
}
|
|
519
|
+
```
|
|
520
|
+
|
|
521
|
+
## Platform Support
|
|
522
|
+
|
|
523
|
+
- **Node.js** >= 24.0.0
|
|
524
|
+
- **OS** Linux x86-64, macOS 26+ x86-64
|
|
525
|
+
- **Distros** Ubuntu 22.04+ and Debian 12+.
|
|
526
|
+
- **CPU** x86-64 only. There is no arm64 build, so on Apple Silicon Node must run under Rosetta.
|
|
527
|
+
|
|
528
|
+
The prebuilt native addon is linked against glibc and requires:
|
|
529
|
+
|
|
530
|
+
| Requirement | Minimum |
|
|
531
|
+
| --------------------- | ------- |
|
|
532
|
+
| glibc | 2.34 |
|
|
533
|
+
| libstdc++ (`GLIBCXX`) | 3.4.30 |
|
|
534
|
+
| C++ ABI (`CXXABI`) | 1.3.11 |
|
|
535
|
+
|
|
536
|
+
It also links `libX11.so.6`, which WebRTC requires unconditionally. Install your distro's X11 client library (`libx11-6` on Debian and Ubuntu) even on headless servers.
|
|
537
|
+
|
|
538
|
+
On macOS the prebuilt addon requires macOS 26 or later. npm cannot check the macOS version, so on an older release `npm install` succeeds and the SDK fails when it loads the addon.
|
|
539
|
+
|
|
540
|
+
Alpine and other musl-based distros are not supported: the addon is glibc-only. Windows is not supported.
|
|
541
|
+
|
|
542
|
+
## Examples
|
|
543
|
+
|
|
544
|
+
The example applications listed below demonstrate various ways to use the SDK for audio or video processing. They need a few packages the SDK itself does not depend on, and they load credentials from a `.env` file at the repo root. Install the dependencies, copy the template, fill in your credentials, and run:
|
|
545
|
+
|
|
546
|
+
```bash
|
|
547
|
+
npm install --prefix examples
|
|
548
|
+
cp .env.example .env
|
|
549
|
+
# edit .env: set TWILIO_ACCOUNT_SID / TWILIO_API_KEY / TWILIO_API_SECRET
|
|
550
|
+
node examples/virtual_camera.js [room-name] [identity]
|
|
551
|
+
```
|
|
552
|
+
|
|
553
|
+
Each example connects with its own default identity, so they can run against one room at the same time. Pass `[identity]` to override it; two Participants sharing an identity disconnect each other.
|
|
554
|
+
|
|
555
|
+
In a repo checkout the examples use your local build when one is present, and the published `@twilio/video-node-sdk` otherwise.
|
|
556
|
+
|
|
557
|
+
`.env` is gitignored, so your real credentials are never committed.
|
|
558
|
+
|
|
559
|
+
See the [`examples/`](https://github.com/twilio/twilio-video-node/tree/main/examples) directory:
|
|
560
|
+
|
|
561
|
+
| Example | Description |
|
|
562
|
+
| ----------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
|
|
563
|
+
| [`virtual_camera.js`](https://github.com/twilio/twilio-video-node/blob/main/examples/virtual_camera.js) | Decodes an MP4 with ffmpeg and pushes I420 frames to a room. |
|
|
564
|
+
| [`video_mirror.js`](https://github.com/twilio/twilio-video-node/blob/main/examples/video_mirror.js) | Receives remote video frames and pushes them back as-is. |
|
|
565
|
+
| [`audio_push.js`](https://github.com/twilio/twilio-video-node/blob/main/examples/audio_push.js) | Generates a sine wave tone and pushes PCM audio to a room. |
|
|
566
|
+
| [`data_channel.js`](https://github.com/twilio/twilio-video-node/blob/main/examples/data_channel.js) | Two participants exchange string and binary messages via data tracks. |
|
|
567
|
+
| [`voice_agent.js`](https://github.com/twilio/twilio-video-node/blob/main/examples/voice_agent.js) | Bridges room audio to the OpenAI Realtime API for a spoken voice agent (requires `OPENAI_API_KEY`). |
|
|
568
|
+
| [`cv_object_detection.js`](https://github.com/twilio/twilio-video-node/blob/main/examples/cv_object_detection.js) | Runs YOLOX object detection on a participant's webcam and re-publishes the video with bounding boxes. |
|
|
569
|
+
| [`cv_face_analysis.js`](https://github.com/twilio/twilio-video-node/blob/main/examples/cv_face_analysis.js) | Analyzes a participant's face — presence and an attention estimate (head orientation) — drawn on the video. |
|
|
570
|
+
|
|
571
|
+
The computer-vision examples (`cv_*.js`) run local ONNX models via
|
|
572
|
+
[`onnxruntime-node`](https://www.npmjs.com/package/onnxruntime-node) and draw with
|
|
573
|
+
[`@napi-rs/canvas`](https://www.npmjs.com/package/@napi-rs/canvas). These two are
|
|
574
|
+
large and only these examples need them, so they live in `examples/package.json`
|
|
575
|
+
rather than the SDK's own dependencies — install them separately:
|
|
576
|
+
|
|
577
|
+
```bash
|
|
578
|
+
npm install --prefix examples
|
|
579
|
+
```
|
|
580
|
+
|
|
581
|
+
No cloud service or API key is needed: each example analyzes the first
|
|
582
|
+
participant's video and expresses its result on a re-published video track. Run
|
|
583
|
+
them against any room you also join from a browser, publishing your webcam.
|
|
584
|
+
|
|
585
|
+
### Downloading the Computer Vision models
|
|
586
|
+
|
|
587
|
+
The ONNX model files are not shipped with the repo — download the ones you need
|
|
588
|
+
and save them to `examples/.models/`. The examples print these same instructions
|
|
589
|
+
if a model is missing.
|
|
590
|
+
|
|
591
|
+
```bash
|
|
592
|
+
mkdir -p examples/.models
|
|
593
|
+
|
|
594
|
+
# cv_object_detection.js — YOLOX-nano (~3.7 MB)
|
|
595
|
+
curl -L -o examples/.models/yolox_nano.onnx \
|
|
596
|
+
"https://github.com/Megvii-BaseDetection/YOLOX/releases/download/0.1.1rc0/yolox_nano.onnx"
|
|
597
|
+
|
|
598
|
+
# cv_face_analysis.js — RTMO-t (a zip containing end2end.onnx, ~27 MB extracted)
|
|
599
|
+
curl -L -o examples/.models/rtmo-t.zip \
|
|
600
|
+
"https://download.openmmlab.com/mmpose/v1/projects/rtmo/onnx_sdk/rtmo-t_8xb32-600e_body7-416x416-f48f75cb_20231219.zip"
|
|
601
|
+
unzip -j examples/.models/rtmo-t.zip '*end2end.onnx' -d examples/.models
|
|
602
|
+
mv examples/.models/end2end.onnx examples/.models/rtmo-t.onnx
|
|
603
|
+
|
|
604
|
+
# verify the downloads (the examples also check this on startup)
|
|
605
|
+
echo "c789161ed43c8269fcd4e67c67eeeb4e80c622da2eb296a20bc6007bd18a0b7d examples/.models/yolox_nano.onnx" | shasum -a 256 -c
|
|
606
|
+
echo "20aad6e2e42359cac1c5b4a0b2da00e29bfe91a72a782fdcf287d273a04c1b24 examples/.models/rtmo-t.onnx" | shasum -a 256 -c
|
|
607
|
+
```
|
|
608
|
+
|
|
609
|
+
Both models are **Apache-2.0** licensed and downloaded from their projects'
|
|
610
|
+
official channels — [YOLOX](https://github.com/Megvii-BaseDetection/YOLOX) by
|
|
611
|
+
Megvii and [RTMO](https://github.com/open-mmlab/mmpose/tree/main/projects/rtmo)
|
|
612
|
+
(OpenMMLab mmpose). Each example verifies its model's SHA-256 on startup and
|
|
613
|
+
refuses to run a file that doesn't match.
|
|
614
|
+
|
|
615
|
+
## License
|
|
616
|
+
|
|
617
|
+
See [LICENSE.md](./LICENSE.md).
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
# Security and privacy
|
|
2
|
+
|
|
3
|
+
What this SDK does with decoded media, and which obligations remain with the application. [README.md](README.md) covers usage, and [LIFECYCLE.md](LIFECYCLE.md) covers object ownership and teardown.
|
|
4
|
+
|
|
5
|
+
This document describes SDK behavior. It is not legal advice and does not establish Twilio's obligations under any agreement.
|
|
6
|
+
|
|
7
|
+
## Where decoded media goes
|
|
8
|
+
|
|
9
|
+
The SDK decodes subscribed audio and video in the Node process and delivers the decoded frames to the application. Video frames carry raw, uncompressed planes; audio frames carry uncompressed PCM. Both reach the application as ordinary JavaScript objects in the process heap, readable by any code in the process.
|
|
10
|
+
|
|
11
|
+
This differs from Twilio's browser and mobile Video SDKs, which run on an end user's own device and deliver media to a rendering surface. Here, decoded media is present in application memory on whatever host runs the process.
|
|
12
|
+
|
|
13
|
+
Once a frame reaches the application, what happens to it is the application's responsibility: how it is processed, where it is written, whether it is forwarded to another service, and who can read it. The SDK applies no restriction to a delivered frame and has no view of what the application does with it.
|
|
14
|
+
|
|
15
|
+
## Protected health information
|
|
16
|
+
|
|
17
|
+
The SDK provides no PHI-aware primitives: no tagging, redaction, retention control, encryption-at-rest helper, or access control for the decoded media described above. If an application requires these capabilities, they must be implemented outside the SDK.
|
|
18
|
+
|
|
19
|
+
## Retention
|
|
20
|
+
|
|
21
|
+
The SDK does not persist media. Frames are delivered to the application and released; nothing is written to disk. The only filesystem access is reading `package.json` and locating the prebuilt native addon at load time.
|
|
22
|
+
|
|
23
|
+
Observed: no media write path exists in either the JavaScript or the native layer.
|
|
24
|
+
|
|
25
|
+
Any persistence of media, or of data derived from media, is created by the application and retained under its own policy.
|