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