@xmaxai/web-sdk 1.0.2 → 1.0.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 ADDED
@@ -0,0 +1,468 @@
1
+ <p align="center">
2
+ <img src="./docs/images/brand/xmax-sdk.png" alt="XmaxSDK — Realtime Interactive Video Generation" width="880">
3
+ </p>
4
+
5
+ <p align="center">
6
+ <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript"><img src="https://img.shields.io/badge/JavaScript-ES2020-F7DF1E" alt="JavaScript ES2020"></a>
7
+ <a href="https://platform.xmaxai.com/"><img src="https://img.shields.io/badge/Realtime-AI-FF9500" alt="Realtime AI"></a>
8
+ <a href="./LICENSE"><img src="https://img.shields.io/badge/License-MIT-4C9A2A" alt="MIT License"></a>
9
+ </p>
10
+
11
+ We introduce XmaxSDK, a JavaScript SDK designed for real-time interactive video generation via Xmax models. XmaxSDK implements an end-to-end pipeline covering media acquisition, video streaming, frame-by-frame generation, and on-device rendering, enabling developers to seamlessly integrate low-latency, high-fidelity video transformations into creative applications at a much lower cost than alternative solutions.
12
+
13
+ <p align="center"><img src="./docs/images/xlab/generation-demo.gif" alt="X-Lab realtime generation demo" width="33%" /><img src="./docs/images/xlab/index-demo.gif" alt="X-Lab index demo" width="33%" /><img src="./docs/images/xlab/storage-demo.gif" alt="X-Lab storage demo" width="33%" /></p>
14
+
15
+ <br>
16
+
17
+ ## What you can build with XmaxSDK
18
+
19
+ <table>
20
+ <tr>
21
+ <th width="24%" align="left">Realtime Use Case</th>
22
+ <th width="60%" align="left">Description</th>
23
+ <th width="16%" align="center">Demo</th>
24
+ </tr>
25
+ <tr>
26
+ <td rowspan="2" width="24%" valign="middle">
27
+ <strong>Character Swapping</strong>
28
+ </td>
29
+ <td width="60%" valign="middle">
30
+ Replace anyone in your live feed with a designated avatar in real-time.
31
+ </td>
32
+ <td rowspan="2" width="16%" align="center" valign="middle">
33
+ <a href="./docs/videos/use-cases/character-swapping.mp4">
34
+ <img src="./docs/images/use-cases/character-swapping-poster.png" alt="Play the Character Swapping demo" width="120">
35
+ <br>
36
+ <sub>▶ Play demo</sub>
37
+ </a>
38
+ </td>
39
+ </tr>
40
+ <tr>
41
+ <td width="60%" valign="middle">
42
+ <strong>Prompt:</strong> <code>视频中角色替换成参考图中角色</code>
43
+ <br><br>
44
+ <strong>Reference image:</strong> Select a clear image of the desired character with a clean background.
45
+ </td>
46
+ </tr>
47
+ <tr>
48
+ <td rowspan="2" width="24%" valign="middle">
49
+ <strong>Virtual Try-On</strong>
50
+ </td>
51
+ <td width="60%" valign="middle">
52
+ Seamlessly change outfits, preserving exact body shape, natural motion, and an
53
+ authentic fit.
54
+ </td>
55
+ <td rowspan="2" width="16%" align="center" valign="middle">
56
+ <a href="./docs/videos/use-cases/virtual-try-on.mp4">
57
+ <img src="./docs/images/use-cases/virtual-try-on-poster.png" alt="Play the Virtual Try-On demo" width="120">
58
+ <br>
59
+ <sub>▶ Play demo</sub>
60
+ </a>
61
+ </td>
62
+ </tr>
63
+ <tr>
64
+ <td width="60%" valign="middle">
65
+ <strong>Prompt:</strong> <code>视频中人物衣服替换成参考图中衣服</code>
66
+ <br><br>
67
+ <strong>Reference image:</strong> Select a clear image of the target outfit with a clean background.
68
+ </td>
69
+ </tr>
70
+ <tr>
71
+ <td rowspan="2" width="24%" valign="middle">
72
+ <strong>Video Restyling</strong>
73
+ </td>
74
+ <td width="60%" valign="middle">
75
+ Reimagine your world in any style with an immersive visual experience.
76
+ </td>
77
+ <td rowspan="2" width="16%" align="center" valign="middle">
78
+ <a href="./docs/videos/use-cases/video-restyling.mp4">
79
+ <img src="./docs/images/use-cases/video-restyling-poster.png" alt="Play the Video Restyling demo" width="120">
80
+ <br>
81
+ <sub>▶ Play demo</sub>
82
+ </a>
83
+ </td>
84
+ </tr>
85
+ <tr>
86
+ <td width="60%" valign="middle">
87
+ <strong>Prompt:</strong> <code>视频风格变为参考图指定的风格</code>
88
+ <br><br>
89
+ <strong>Reference image:</strong> Select an image that captures the artistic style you want to apply.
90
+ </td>
91
+ </tr>
92
+ <tr>
93
+ <td rowspan="2" width="24%" valign="middle">
94
+ <strong>AI Companions</strong>
95
+ </td>
96
+ <td width="60%" valign="middle">
97
+ Summon virtual characters into your live camera feed and interact with them
98
+ through gestures.
99
+ </td>
100
+ <td rowspan="2" width="16%" align="center" valign="middle">
101
+ <a href="./docs/videos/use-cases/ai-companions.mp4">
102
+ <img src="./docs/images/use-cases/ai-companions-poster.png" alt="Play the AI Companions demo" width="120">
103
+ <br>
104
+ <sub>▶ Play demo</sub>
105
+ </a>
106
+ </td>
107
+ </tr>
108
+ <tr>
109
+ <td width="60%" valign="middle">
110
+ <strong>Prompt:</strong> <code>指定角色在场景中互动</code>
111
+ <br><br>
112
+ <strong>Reference image:</strong> Select a clear image of the virtual character you want to summon with a clean background.
113
+ </td>
114
+ </tr>
115
+ <tr>
116
+ <td rowspan="2" width="24%" valign="middle">
117
+ <strong>Live Photo</strong>
118
+ </td>
119
+ <td width="60%" valign="middle">
120
+ Animate and control characters in your images simply by drawing motion
121
+ trajectories.
122
+ </td>
123
+ <td rowspan="2" width="16%" align="center" valign="middle">
124
+ <a href="./docs/videos/use-cases/live-photo.mp4">
125
+ <img src="./docs/images/use-cases/live-photo-poster.png" alt="Play the Live Photo demo" width="120">
126
+ <br>
127
+ <sub>▶ Play demo</sub>
128
+ </a>
129
+ </td>
130
+ </tr>
131
+ <tr>
132
+ <td width="60%" valign="middle">
133
+ <strong>Prompt:</strong> <code>让画面自然动起来</code>
134
+ <br><br>
135
+ <strong>Reference image:</strong> Use the input image as the reference
136
+ </td>
137
+ </tr>
138
+ </table>
139
+
140
+ <br>
141
+
142
+ ## Why XmaxSDK?
143
+
144
+ <table>
145
+ <thead>
146
+ <tr>
147
+ <th height="104" align="center" valign="middle">
148
+ <img src="./docs/images/why/low-latency.svg" alt="Low latency" width="36" height="36"><br>Low latency
149
+ </th>
150
+ <th height="104" align="center" valign="middle">
151
+ <img src="./docs/images/why/low-cost.svg" alt="Cost efficiency" width="36" height="36"><br>Cost efficiency
152
+ </th>
153
+ <th height="104" align="center" valign="middle">
154
+ <img src="./docs/images/why/high-fidelity.svg" alt="High fidelity" width="36" height="36"><br>High fidelity
155
+ </th>
156
+ </tr>
157
+ </thead>
158
+ <tbody>
159
+ <tr>
160
+ <td>End-to-end latency is measured in <img src="./docs/images/why/latency-highlight.svg" alt="hundreds of milliseconds" width="192" height="20" align="absmiddle">, ensuring that updates to generation conditions and interaction controls are reflected instantly.</td>
161
+ <td>Run on a <img src="./docs/images/why/gpu-highlight.svg" alt="single RTX 5090" width="126" height="20" align="absmiddle">, reducing inference costs by orders of magnitude versus datacenter GPUs like H100.</td>
162
+ <td>Our models support real-time generation at up to <img src="./docs/images/why/resolution-highlight.svg" alt="1080p" width="48" height="20" align="absmiddle">, delivering production-ready, high-quality video output.</td>
163
+ </tr>
164
+ </tbody>
165
+ </table>
166
+
167
+ <br>
168
+
169
+ ## Prerequisites
170
+
171
+ - A WebRTC-enabled browser running on HTTPS or localhost
172
+ - Node.js 18 or later, with pnpm or npm for development
173
+ - An Xmax API key
174
+
175
+ > [!WARNING]
176
+ > Never commit your Xmax API key to version control or embed a long-lived key in
177
+ > client-side bundles. Use short-lived temporary keys issued by your backend
178
+ > through the Xmax API. For step-by-step
179
+ > instructions, see [Authentication](https://platform.xmaxai.com/docs/authentication).
180
+
181
+ <br>
182
+
183
+ ## Installation
184
+
185
+ ```bash
186
+ npm install @xmaxai/web-sdk
187
+ ```
188
+
189
+ The package includes optional React components at `@xmaxai/web-sdk/react`.
190
+ React applications use their own React installation; non-React applications do not need React.
191
+
192
+ <br>
193
+
194
+ ## Quick Start
195
+
196
+ ### Configure permissions
197
+
198
+ Serve your application over HTTPS or localhost and allow camera access in the
199
+ browser. When embedding the application in an iframe, allow camera access:
200
+
201
+ ```html
202
+ <iframe src="https://your-app.example" allow="camera; microphone; autoplay"></iframe>
203
+ ```
204
+
205
+ Configure permissions to match your application's user experience. XmaxSDK
206
+ automatically prompts for camera access when creating the video stream and throws
207
+ an `XmaxError` if permission is denied or unavailable.
208
+
209
+ <br>
210
+
211
+ ### Generate and display video
212
+
213
+ The following JavaScript snippet creates a camera stream, starts real-time generation,
214
+ and binds the output to a video view. Run this within an async function in the browser,
215
+ after a user action such as clicking a Start button.
216
+
217
+ Choose a model with `RealtimeModel.x2_0` (`x2.0`) or
218
+ `RealtimeModel.x2_0_trtc` (`x2.0-trtc`). For Agora, use
219
+ `RealtimeModel.x2_0_agora` (`x2.0-agora`) with `RtcProvider.agora`. For VeRTC, use
220
+ `RealtimeModel.x2_1_preview` (`x2.1-preview`) with `RtcProvider.vertc`.
221
+
222
+ ```javascript
223
+ import {
224
+ CameraPosition,
225
+ RealtimeConfiguration,
226
+ RealtimeContext,
227
+ RealtimeModel,
228
+ RealtimeVideoFormat,
229
+ VideoContentMode,
230
+ XmaxClient,
231
+ XmaxConfiguration,
232
+ XmaxRealtimeVideoView,
233
+ } from "@xmaxai/web-sdk";
234
+
235
+ const client = new XmaxClient(
236
+ new XmaxConfiguration({ apiKey: "YOUR_TEMPORARY_XMAX_API_KEY" })
237
+ );
238
+
239
+ const realtime = client.createRealtimeManager(
240
+ new RealtimeConfiguration({ model: RealtimeModel.x2_0_trtc })
241
+ );
242
+
243
+ const localStream = await realtime.createLocalCameraStream({
244
+ videoFormat: new RealtimeVideoFormat({ width: 1024, height: 1920, fps: 30 }),
245
+ position: CameraPosition.front,
246
+ useMicrophone: false,
247
+ enableFrameValidation: true, // Optional; waits a fixed 200ms camera warmup before publishing; false skips it.
248
+ });
249
+
250
+ const videoView = new XmaxRealtimeVideoView({
251
+ localTrack: localStream.videoTrack,
252
+ videoContentMode: VideoContentMode.fill,
253
+ });
254
+
255
+ videoView.element.style.width = "100%";
256
+ videoView.element.style.height = "100%";
257
+ const container = document.getElementById("video-container");
258
+ if (!container) throw new Error("Missing #video-container element");
259
+ videoView.attach(container);
260
+
261
+ const remoteStream = await realtime.startGeneration({
262
+ localStream,
263
+ context: new RealtimeContext({
264
+ prompt: "视频中角色替换成参考图中角色",
265
+ referencePath: "https://platform.xmaxai.com/images/source/charx/chatx_image1.jpg",
266
+ }),
267
+ });
268
+
269
+ videoView.remoteTrack = remoteStream.videoTrack;
270
+ ```
271
+
272
+ Add a `video-container` element with an explicit width and height to your page.
273
+ The view displays a local camera preview until the first generated frame arrives.
274
+
275
+ Use `updateVideoFormat` after creating the local camera stream, including during
276
+ generation, to change upstream encoding without reconnecting or restarting the task:
277
+
278
+ ```javascript
279
+ await realtime.updateVideoFormat(new RealtimeVideoFormat({
280
+ width: 1024,
281
+ height: 1920,
282
+ fps: 20,
283
+ minimumBitrate: 1000,
284
+ maximumBitrate: 2000,
285
+ }));
286
+ ```
287
+
288
+ Pass a complete format; omitted bitrate and preference fields use SDK defaults.
289
+ The local track's `videoFormat` is updated on success and reused on reconnect.
290
+ Generation and remote frame interpolation retain the original format. Actual sent
291
+ resolution, frame rate, and bitrate depend on the device, browser, and network;
292
+ use the statistics callbacks to observe them. Await each operation before starting
293
+ another configuration or lifecycle operation.
294
+
295
+ TRTC is the default RTC provider. To use Agora, replace the manager configuration
296
+ above; camera capture, generation, rendering, and cleanup use the same APIs:
297
+
298
+ ```javascript
299
+ import { RtcProvider } from "@xmaxai/web-sdk";
300
+
301
+ const realtime = client.createRealtimeManager(
302
+ new RealtimeConfiguration({
303
+ provider: RtcProvider.agora,
304
+ model: RealtimeModel.x2_0_agora,
305
+ })
306
+ );
307
+ ```
308
+
309
+ To use VeRTC, set both values explicitly:
310
+
311
+ ```javascript
312
+ const realtime = client.createRealtimeManager(
313
+ new RealtimeConfiguration({
314
+ provider: RtcProvider.vertc,
315
+ model: RealtimeModel.x2_1_preview,
316
+ })
317
+ );
318
+ ```
319
+
320
+ The provider is fixed for each manager, defaults to TRTC, and is chosen only by
321
+ `RealtimeConfiguration.provider`. The SDK does not infer it from the model or read
322
+ `modelExtra.provider` from the backend. The selected provider determines how RTC
323
+ credentials are parsed.
324
+
325
+ The `x2.0-agora` and `x2.1-preview` models use
326
+ `https://dev.xmaxai.com/open/api/v1` in both environments.
327
+ Other models and file uploads use the configured environment's API endpoint.
328
+
329
+ VeRTC uses `@volcengine/rtc` 4.69.3 and the fixed AppID
330
+ `69a177e226e9b90176a86b96`. Session credentials must contain this `rtc_app_id`,
331
+ `room_id`, and `room_token`; the RTC user is `user_id` (falling back to `userUid`),
332
+ and `bot_name` identifies the bot. Camera and microphone capture use VeRTC's SDK.
333
+ The preview model uses the same media rules as `x2.0-trtc`: 1024 × 1920 or
334
+ 1920 × 1024 input, with 30 fps by default.
335
+
336
+ VeRTC sends the existing room-event JSON as a single room text message, without
337
+ chunk envelopes. The adapter rejects messages above 64 KiB of UTF-8 data; vendor
338
+ send failures are returned to the caller. TRTC and Agora retain their chunking.
339
+ HTTP session heartbeats start after joining and publishing the local stream, with
340
+ the first request after 10 seconds. Changed tokens returned by heartbeat are
341
+ applied to Agora and VeRTC; expiry callbacks also request fresh credentials.
342
+ VeRTC restores media after token expiry without creating another business session
343
+ or restarting the generation task. HTTP heartbeats maintain the session and are
344
+ not treated as a client-side billing trigger.
345
+
346
+ `XmaxConfiguration.environment` selects the Agora region (`china` or `global`);
347
+ concurrent Agora managers must use the same environment. RTC modules load on demand.
348
+ Statistics not supplied by a provider are `undefined`, including Agora playback
349
+ buffer delay and separate uplink/downlink RTT. RTC end-to-end estimates do not
350
+ include AI generation time and use each provider's own measurement definition.
351
+
352
+ <br>
353
+
354
+ ### Using React
355
+
356
+ Use `XmaxRealtimeVideo` as your primary React view. Store the local and remote
357
+ tracks in component state, updating them dynamically as streams become available:
358
+
359
+ ```jsx
360
+ import { XmaxRealtimeVideo } from "@xmaxai/web-sdk/react";
361
+ import { VideoContentMode } from "@xmaxai/web-sdk";
362
+
363
+ <XmaxRealtimeVideo
364
+ localTrack={localTrack}
365
+ remoteTrack={remoteTrack}
366
+ videoContentMode={VideoContentMode.fill}
367
+ style={{ width: "100%", height: "100%" }}
368
+ />
369
+ ```
370
+
371
+ See the [React component](./packages/xmax-sdk/src/react/XmaxRealtimeVideo.tsx) for state binding and the
372
+ [example project](#example-project) for a complete implementation.
373
+
374
+ <br>
375
+
376
+ ### Listen for events
377
+
378
+ After creating `realtime`, register the listeners you need before creating the
379
+ input stream or starting generation.
380
+
381
+ | Listener | Purpose |
382
+ | --- | --- |
383
+ | `setStateListener` | Observe pipeline states and termination reasons during real-time generation. |
384
+ | `setLaunchTimingListener` | Monitor camera, connection, first-frame, and total launch timings. |
385
+ | `setLocalVideoStatisticsListener` | Monitor uplink video resolution, frame rate, and bitrate. |
386
+ | `setRemoteVideoStatisticsListener` | Monitor downlink video statistics, packet loss, playback buffer delay, RTT, and estimated RTC end-to-end delay. |
387
+
388
+ For example, monitor state changes and errors:
389
+
390
+ ```javascript
391
+ await realtime.setStateListener((state) => {
392
+ console.log("State:", state.connectionState);
393
+ if (state.reason?.kind === "failure") {
394
+ console.error("Error:", state.reason.error.code, state.reason.error.message);
395
+ }
396
+ });
397
+ ```
398
+
399
+ Handle errors thrown by async calls with `try/catch`. Failures that end the realtime
400
+ workflow are also available through `state.reason` after cleanup completes.
401
+
402
+ For camera input, bind the returned video track to a preview view. The SDK enters
403
+ `ready` after it has received a valid frame and the preview view is bound; observe
404
+ this through `setStateListener`.
405
+
406
+ <br>
407
+
408
+ ### Resource Cleanup
409
+
410
+ - **`disconnect()` — Stop Remote Generation**
411
+
412
+ Stops remote generation and cancels billing while keeping the local camera stream
413
+ and preview active. Use this when ending the online session but staying on the
414
+ current screen. You can start a new session later using the same local stream:
415
+
416
+ ```javascript
417
+ await realtime.disconnect();
418
+ ```
419
+
420
+ - **`close()` — Full Teardown & Release**
421
+
422
+ Ends the remote session, stops local media capture, and releases all engine
423
+ resources. Use this when leaving or dismissing the generation screen:
424
+
425
+ ```javascript
426
+ await realtime.close();
427
+ ```
428
+
429
+ > **Note:** These methods are alternatives, not sequential steps. When exiting a
430
+ > screen, call `close()` directly—there is no need to call `disconnect()` first.
431
+
432
+ <br>
433
+
434
+ > [!TIP]
435
+ > For complete usage examples, including camera input, reference images,
436
+ > and live statistics, see the [example project](./examples/xlab-react).
437
+
438
+ <br>
439
+
440
+ ## Example Project
441
+
442
+ A complete example application featuring React is available in
443
+ [`examples/xlab-react`](./examples/xlab-react).
444
+ It demonstrates real-time generation using live camera feeds and reference images.
445
+
446
+ <br>
447
+
448
+ ## Dependencies
449
+
450
+ - <ins><strong>Tencent Cloud TRTC SDK for Web</strong></ins> enables low-latency, real-time audio and video communication.
451
+ - <ins><strong>Agora RTC SDK for Web</strong></ins> provides an alternative RTC transport for the Agora model.
452
+ - <ins><strong>Volcengine VeRTC SDK for Web</strong></ins> provides RTC transport and device capture for the X2.1 preview model.
453
+ - <ins><strong>Tencent Cloud COS SDK</strong></ins> handles media upload and download via object storage.
454
+
455
+ <br>
456
+
457
+ ## Contact us
458
+
459
+ For bug reports and feature requests, please open a
460
+ [GitHub Issue](../../issues). For integration
461
+ assistance and technical support, contact us at [sdk@xmax.ai](mailto:sdk@xmax.ai).
462
+
463
+ <br>
464
+
465
+ ## License
466
+
467
+ XmaxSDK Web is available under the terms of the [MIT License](./LICENSE).
468
+ Third-party dependencies and model weights retain their respective licenses.