@twilio/video-node-sdk 1.0.0-rc.3 → 1.0.0-rc.4

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 CHANGED
@@ -1,54 +1,70 @@
1
1
  # @twilio/video-node-sdk
2
2
 
3
- [![CI](https://github.com/twilio/twilio-video-node/actions/workflows/ci.yml/badge.svg)](https://github.com/twilio/twilio-video-node/actions/workflows/ci.yml)
3
+ [![CI](https://github.com/twilio/twilio-video-node/actions/workflows/ci.yml/badge.svg?branch=main&event=push)](https://github.com/twilio/twilio-video-node/actions/workflows/ci.yml)
4
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.
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 a Node.js process push and receive decoded video and audio frames in real time.
6
6
 
7
- [API reference](https://twilio.github.io/twilio-video-node/latest/)
7
+ **Note: this is a beta release of the Twilio Media SDK for Node.js. It is provided for evaluation purposes only. During the beta period this SDK is not HIPAA eligible.**
8
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.**
9
+ - [Overview](https://www.twilio.com/docs/video/node)
10
+ - [Quickstart](https://www.twilio.com/docs/video/node-getting-started)
11
+ - [Work with media frames](https://www.twilio.com/docs/video/node-working-with-media-frames)
12
+ - [Best practices](https://www.twilio.com/docs/video/node-best-practices)
13
+ - [Differences from the JavaScript SDK](https://www.twilio.com/docs/video/node-differences-from-javascript-sdk)
14
+ - [Troubleshooting](https://www.twilio.com/docs/video/media-sdk-troubleshooting)
15
+ - [API reference](https://twilio.github.io/twilio-video-node/latest/)
16
+ - [Changelog](CHANGELOG.md)
10
17
 
11
- ## Installation
18
+ ## Requirements
12
19
 
13
- ```bash
14
- npm install @twilio/video-node-sdk
15
- ```
20
+ The native binary is prebuilt and bundled, so there is no build step.
16
21
 
17
- The native binary is prebuilt and bundled — no build step required.
22
+ - Node.js >= 24.0.0
23
+ - Linux x86-64 with glibc: Ubuntu 24.04+ or Debian 13+
24
+ - macOS 26+ on arm64 (Apple Silicon), for local development only. The macOS build is not supported in production.
18
25
 
19
- **Requirements:**
26
+ The binary is built for Linux x86-64 and macOS arm64 only. Intel Macs, Linux arm64, Alpine and other musl-based distros, and Windows are not supported.
20
27
 
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)
28
+ On Linux the addon is linked against glibc and requires:
29
+
30
+ | Requirement | Minimum |
31
+ | --------------------- | ------- |
32
+ | glibc | 2.38 |
33
+ | libstdc++ (`GLIBCXX`) | 3.4.30 |
34
+ | C++ ABI (`CXXABI`) | 1.3.13 |
35
+
36
+ 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.
37
+
38
+ On macOS, npm cannot check the OS version, so on a release older than macOS 26 `npm install` succeeds and the SDK fails when it loads the addon.
39
+
40
+ The addon is built with N-API, so it does not need rebuilding for each Node.js release.
24
41
 
25
- Alpine/musl, native arm64 and Windows are not supported. See [Platform Support](#platform-support) for the full requirements.
42
+ Load the SDK on the main thread. Importing it in a `worker_thread` throws `UnsupportedPlatformError`; frames can still be transferred to a worker for processing.
26
43
 
27
- ### Access Token
44
+ ## Installation
45
+
46
+ ```bash
47
+ npm install @twilio/video-node-sdk
48
+ ```
28
49
 
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.
50
+ `connect()` takes a standard Twilio Video Access Token with a VideoGrant, the same token format the JavaScript SDK uses. Generate one with the [`twilio`](https://www.npmjs.com/package/twilio) helper library; see [User Identity and Access Tokens](https://www.twilio.com/docs/video/tutorials/user-identity-access-tokens).
34
51
 
35
- ## Quick Start
52
+ ## Quick start
36
53
 
37
54
  ```js
38
55
  const { connect, createLocalVideoTrack } = require('@twilio/video-node-sdk');
39
56
 
40
57
  async function main() {
41
- const videoTrack = createLocalVideoTrack('my-camera');
58
+ const videoTrack = createLocalVideoTrack('virtual-camera');
42
59
 
43
60
  const room = await connect(token, {
44
61
  name: 'my-room',
45
62
  videoTracks: [videoTrack],
46
63
  });
47
64
 
48
- console.log('Connected:', room.name, room.sid);
65
+ console.log('Connected to Room:', room.name, room.sid);
49
66
 
50
- // Push I420 video frames. connect() resolves only once the Room is connected;
51
- // frames written before that are dropped and counted in getWriteStats().
67
+ // Push I420 video frames. Frames written before connect() resolves are dropped.
52
68
  videoTrack.write({
53
69
  format: 'I420',
54
70
  width: 1280,
@@ -60,11 +76,18 @@ async function main() {
60
76
 
61
77
  async function trackSubscribed(track) {
62
78
  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?.();
79
+ try {
80
+ // Frames that arrive while you process one are queued, and the SDK drops
81
+ // them if the queue fills. The loop ends by itself when the track is
82
+ // unsubscribed or the Room disconnects.
83
+ for await (const frame of track.frames()) {
84
+ console.log(`${frame.width}x${frame.height} @ ${frame.timestamp}us`);
85
+ frame.close?.();
86
+ }
87
+ } catch (err) {
88
+ // Nothing awaits this function, so an error that escapes here becomes an
89
+ // unhandled rejection and stops the process.
90
+ console.error('Frame loop failed:', err);
68
91
  }
69
92
  }
70
93
 
@@ -79,8 +102,8 @@ async function main() {
79
102
  }
80
103
 
81
104
  // 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.
105
+ // track can finish subscribing before the trackSubscribed listener is attached.
106
+ // Seed from room.participants and check isSubscribed on each publication.
84
107
  room.participants.forEach(participantConnected);
85
108
  room.on('participantConnected', participantConnected);
86
109
 
@@ -95,518 +118,36 @@ main().catch(err => {
95
118
  });
96
119
  ```
97
120
 
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
121
+ Call `room.dispose()` when you are done with a Room. Until you do, the Node.js process does not exit; `disconnect()` leaves the Room but does not release its native resources. See [LIFECYCLE.md](LIFECYCLE.md).
342
122
 
343
- Send arbitrary string or binary messages. Delivery is reliable and ordered by default.
123
+ ## Further reading
344
124
 
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.
125
+ - [FRAME_CONTRACT.md](FRAME_CONTRACT.md): buffer ownership, backpressure and drop semantics, timestamps, and publish invariants.
126
+ - [LIFECYCLE.md](LIFECYCLE.md): what each object owns, what `disconnect()` and `dispose()` release, and event ordering during teardown.
127
+ - [SECURITY-PRIVACY.md](SECURITY-PRIVACY.md): what the SDK does with decoded media, and which obligations remain with the application.
541
128
 
542
129
  ## Examples
543
130
 
544
- The example applications listed below demonstrate various ways to use the SDK for audio or video processing. They load credentials from a `.env` file at the repo root. Copy the template, fill in your credentials, and run:
131
+ The [`examples/`](examples/README.md) directory has runnable examples, with setup steps: a virtual camera, a video mirror, audio push, data tracks, a voice agent, and two computer-vision examples.
545
132
 
546
- ```bash
547
- cp .env.example .env
548
- # edit .env: set TWILIO_ACCOUNT_SID / TWILIO_API_KEY / TWILIO_API_SECRET
549
- node examples/virtual_camera.js [room-name]
550
- ```
133
+ <a id="feedback"></a>
551
134
 
552
- `.env` is gitignored, so your real credentials are never committed.
135
+ ## Community Contributions and Support
553
136
 
554
- See the [`examples/`](https://github.com/twilio/twilio-video-node/tree/main/examples) directory:
137
+ This repository is publicly available and maintained by Twilio under a limited external contribution model.
555
138
 
556
- | Example | Description |
557
- | ----------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
558
- | [`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. |
559
- | [`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. |
560
- | [`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. |
561
- | [`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. |
562
- | [`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`). |
563
- | [`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. |
564
- | [`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. |
139
+ Due to limited maintenance capacity, external pull requests are not currently accepted.
565
140
 
566
- The computer-vision examples (`cv_*.js`) run local ONNX models via
567
- [`onnxruntime-node`](https://www.npmjs.com/package/onnxruntime-node) and draw with
568
- [`@napi-rs/canvas`](https://www.npmjs.com/package/@napi-rs/canvas). These two are
569
- large and only these examples need them, so they live in `examples/package.json`
570
- rather than the SDK's own dependencies — install them separately:
141
+ GitHub Issues may be used to report reproducible bugs or provide feature feedback about this SDK. Issues are reviewed on a best-effort basis, with no SLA or guaranteed response.
571
142
 
572
- ```bash
573
- npm install --prefix examples
574
- ```
575
-
576
- No cloud service or API key is needed: each example analyzes the first
577
- participant's video and expresses its result on a re-published video track. Run
578
- them against any room you also join from a browser, publishing your webcam.
579
-
580
- ### Downloading the Computer Vision models
581
-
582
- The ONNX model files are not shipped with the repo — download the ones you need
583
- and save them to `examples/.models/`. The examples print these same instructions
584
- if a model is missing.
143
+ GitHub Issues are not an official Twilio support channel. For production issues, general usage questions, or account-specific assistance, please contact [Twilio Support](https://help.twilio.com/). If you have a Twilio account manager, you may also escalate through them.
585
144
 
586
- ```bash
587
- mkdir -p examples/.models
588
-
589
- # cv_object_detection.js — YOLOX-nano (~3.7 MB)
590
- curl -L -o examples/.models/yolox_nano.onnx \
591
- "https://github.com/Megvii-BaseDetection/YOLOX/releases/download/0.1.1rc0/yolox_nano.onnx"
145
+ Do not share [Personally Identifiable Information (PII)](https://www.twilio.com/docs/glossary/what-is-personally-identifiable-information-pii) or sensitive account information, including access tokens, API keys, and credentials, in issues, logs, or screenshots.
592
146
 
593
- # cv_face_analysis.js — RTMO-t (a zip containing end2end.onnx, ~27 MB extracted)
594
- curl -L -o examples/.models/rtmo-t.zip \
595
- "https://download.openmmlab.com/mmpose/v1/projects/rtmo/onnx_sdk/rtmo-t_8xb32-600e_body7-416x416-f48f75cb_20231219.zip"
596
- unzip -j examples/.models/rtmo-t.zip '*end2end.onnx' -d examples/.models
597
- mv examples/.models/end2end.onnx examples/.models/rtmo-t.onnx
598
-
599
- # verify the downloads (the examples also check this on startup)
600
- echo "c789161ed43c8269fcd4e67c67eeeb4e80c622da2eb296a20bc6007bd18a0b7d examples/.models/yolox_nano.onnx" | shasum -a 256 -c
601
- echo "20aad6e2e42359cac1c5b4a0b2da00e29bfe91a72a782fdcf287d273a04c1b24 examples/.models/rtmo-t.onnx" | shasum -a 256 -c
602
- ```
147
+ Report security vulnerabilities privately through [Twilio's Vulnerability Disclosure Program](https://www.twilio.com/en-us/security/vulnerability-disclosure-program), rather than public GitHub Issues.
603
148
 
604
- Both models are **Apache-2.0** licensed and downloaded from their projects'
605
- official channels — [YOLOX](https://github.com/Megvii-BaseDetection/YOLOX) by
606
- Megvii and [RTMO](https://github.com/open-mmlab/mmpose/tree/main/projects/rtmo)
607
- (OpenMMLab mmpose). Each example verifies its model's SHA-256 on startup and
608
- refuses to run a file that doesn't match.
149
+ See [CONTRIBUTING.md](https://github.com/twilio/twilio-video-node/blob/main/CONTRIBUTING.md) for reporting guidance.
609
150
 
610
151
  ## License
611
152
 
612
- See [LICENSE.md](./LICENSE.md).
153
+ The SDK source is licensed under the Apache License 2.0. The prebuilt native binaries also contain the Twilio Video SDK for C++, which is distributed under the [Twilio Terms of Service](https://www.twilio.com/legal/tos), and third-party software listed in [THIRD_PARTY_NOTICES](THIRD_PARTY_NOTICES). See [LICENSE.md](LICENSE.md), which also covers third-party codecs you load, such as OpenH264.