@xmaxai/web-sdk 1.0.5 → 1.0.7

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
@@ -214,11 +214,6 @@ The following JavaScript snippet creates a camera stream, starts real-time gener
214
214
  and binds the output to a video view. Run this within an async function in the browser,
215
215
  after a user action such as clicking a Start button.
216
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
217
  ```javascript
223
218
  import {
224
219
  CameraPosition,
@@ -237,7 +232,7 @@ const client = new XmaxClient(
237
232
  );
238
233
 
239
234
  const realtime = client.createRealtimeManager(
240
- new RealtimeConfiguration({ model: RealtimeModel.x2_0_trtc })
235
+ new RealtimeConfiguration({ model: RealtimeModel.x2_1_preview })
241
236
  );
242
237
 
243
238
  const localStream = await realtime.createLocalCameraStream({
@@ -272,11 +267,11 @@ videoView.remoteTrack = remoteStream.videoTrack;
272
267
  Add a `video-container` element with an explicit width and height to your page.
273
268
  The view displays a local camera preview until the first generated frame arrives.
274
269
 
275
- Use `updateVideoFormat` after creating the local camera stream, including during
270
+ Use `updateUplinkVideoFormat` after creating the local camera stream, including during
276
271
  generation, to change upstream encoding without reconnecting or restarting the task:
277
272
 
278
273
  ```javascript
279
- await realtime.updateVideoFormat(new RealtimeVideoFormat({
274
+ await realtime.updateUplinkVideoFormat(new RealtimeVideoFormat({
280
275
  width: 1024,
281
276
  height: 1920,
282
277
  fps: 20,
@@ -285,89 +280,6 @@ await realtime.updateVideoFormat(new RealtimeVideoFormat({
285
280
  }));
286
281
  ```
287
282
 
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
- Each model declares its supported RTC providers. The SDK selects the model's
296
- default provider when `provider` is omitted. To use Agora, replace the manager
297
- configuration above; camera capture, generation, rendering, and cleanup use the same APIs:
298
-
299
- ```javascript
300
- const realtime = client.createRealtimeManager(
301
- new RealtimeConfiguration({
302
- model: RealtimeModel.x2_0_agora,
303
- })
304
- );
305
- ```
306
-
307
- To use VeRTC, select the preview model:
308
-
309
- ```javascript
310
- const realtime = client.createRealtimeManager(
311
- new RealtimeConfiguration({
312
- model: RealtimeModel.x2_1_preview,
313
- })
314
- );
315
- ```
316
-
317
- The provider is fixed for each manager: `x2.0` and `x2.0-trtc` use
318
- `RtcProvider.trtc`, `x2.0-agora` uses `RtcProvider.agora`, and
319
- `x2.1-preview` uses `RtcProvider.vertc`.
320
- Import `RtcProvider` to specify it explicitly; unsupported known-model/provider
321
- combinations are rejected during configuration. Use the exported
322
- `supportedRtcProviders(model)` to inspect model capabilities. The SDK does not read
323
- `modelExtra.provider` from the backend; the resolved configuration determines how
324
- RTC credentials are parsed.
325
-
326
- The `x2.0-agora` and `x2.1-preview` models use
327
- `https://dev.xmaxai.com/open/api/v1` in both environments.
328
- The other built-in models and file uploads use the configured environment's API endpoint.
329
-
330
- Custom realtime model names are also accepted without an SDK update:
331
-
332
- ```javascript
333
- const realtime = client.createRealtimeManager(
334
- new RealtimeConfiguration({ model: "your-new-model" })
335
- );
336
- ```
337
-
338
- The model name is sent unchanged; the server determines whether it is available.
339
- Unknown models inherit the `x2.1-preview` defaults: VeRTC, the dev session API above
340
- (in both client environments), a 1024 × 1920 camera at 30 fps, and the same
341
- 1024 × 1920 / 1920 × 1024 input resolution buckets and media rules.
342
- You may explicitly choose another supported `RtcProvider` for a custom model;
343
- `supportedRtcProviders` lists all SDK adapters for custom models, with VeRTC first,
344
- but this does not guarantee server-side support. `modelDisplayName` returns the
345
- custom name unchanged. Empty/blank or non-string model names, invalid RTC providers,
346
- and invalid video parameters are still rejected locally.
347
-
348
- VeRTC uses `@volcengine/rtc` 4.69.3 and the fixed AppID
349
- `69a177e226e9b90176a86b96`. Session credentials must contain this `rtc_app_id`,
350
- `room_id`, and `room_token`; the RTC user is `user_id` (falling back to `userUid`),
351
- and `bot_name` identifies the bot. Camera and microphone capture use VeRTC's SDK.
352
- The preview model uses the same media rules as `x2.0-trtc`: 1024 × 1920 or
353
- 1920 × 1024 input, with 30 fps by default.
354
-
355
- VeRTC sends the existing room-event JSON as a single room text message, without
356
- chunk envelopes. The adapter rejects messages above 64 KiB of UTF-8 data; vendor
357
- send failures are returned to the caller. TRTC and Agora retain their chunking.
358
- HTTP session heartbeats start after joining and publishing the local stream, with
359
- the first request after 10 seconds. Changed tokens returned by heartbeat are
360
- applied to Agora and VeRTC; expiry callbacks also request fresh credentials.
361
- VeRTC restores media after token expiry without creating another business session
362
- or restarting the generation task. HTTP heartbeats maintain the session and are
363
- not treated as a client-side billing trigger.
364
-
365
- `XmaxConfiguration.environment` selects the Agora region (`china` or `global`);
366
- concurrent Agora managers must use the same environment. RTC modules load on demand.
367
- Statistics not supplied by a provider are `undefined`, including Agora playback
368
- buffer delay and separate uplink/downlink RTT. RTC end-to-end estimates do not
369
- include AI generation time and use each provider's own measurement definition.
370
-
371
283
  <br>
372
284
 
373
285
  ### Using React
@@ -422,6 +334,14 @@ For camera input, bind the returned video track to a preview view. The SDK enter
422
334
  `ready` after it has received a valid frame and the preview view is bound; observe
423
335
  this through `setStateListener`.
424
336
 
337
+ At generation start, the SDK sends `params.mirror: true` for the front camera
338
+ and `false` for the rear camera, local files, and network videos. The backend
339
+ mirrors the input; generated results are not automatically mirrored in the
340
+ browser. The front-camera local preview remains mirrored independently.
341
+ This flag is sent only with `start`: switching cameras during an active generation
342
+ does not update it. Disconnect and start generation again to apply the new camera
343
+ position to the backend.
344
+
425
345
  <br>
426
346
 
427
347
  ### Resource Cleanup
@@ -456,156 +376,6 @@ this through `setStateListener`.
456
376
 
457
377
  <br>
458
378
 
459
- ### Generate from a local video
460
-
461
- Use a manager configured for TRTC, Agora or VeRTC. The SDK decodes a local `File` or `Blob`, sends its video through Canvas and its audio through Web Audio, and receives the generated result over RTC. It does not upload the file to storage or request camera/microphone access.
462
-
463
- ```ts
464
- // Call directly from a file-selection or click handler to unlock browser playback.
465
- const localStream = await realtime.createLocalVideoStream({
466
- file,
467
- videoFormat: new RealtimeVideoFormat({ width: 1920, height: 1024, fps: 30 }),
468
- loop: true,
469
- includeAudio: true,
470
- });
471
-
472
- // Optionally bind localStream.videoTrack to an SDK video view.
473
- const remoteStream = await realtime.startGeneration({
474
- localStream,
475
- context: new RealtimeContext({ prompt: "Transform the scene into an animation" }),
476
- });
477
- ```
478
-
479
- Preparation stops at the first frame. After the connection is established and the start signal is sent, the file plays from the beginning; playback does not wait for a remote frame. `loop` defaults to `true`, looping both file video and audio; set it to `false` to play once. The current protocol does not acknowledge server input readiness, so frame-perfect processing of the very beginning is not guaranteed.
480
-
481
- For local files, requested dimensions automatically select the model resolution with the closest aspect ratio, preferring landscape on ties; exact matches are preserved. For example, `1280×720` selects `1920×1024`. Models without fixed resolutions retain their existing pixel-budget sizing rules. The file is scaled proportionally into the resulting Canvas, with black bars where needed, and the returned track's `videoFormat` reflects that target size. This does not change camera or network-video size validation. Local preview is always silent; `localAudioVolume` does not alter the file's uplink audio. File audio is enabled by default; a file without an audio track produces silence. Set `includeAudio: false` to omit the audio track entirely. Use `setRemoteAudioVolume` to hear the generated result (muted by default).
482
-
483
- `disconnect()` pauses playback and retains the source. A new generation after reconnecting starts from the beginning; updating conditions during generation does not restart playback. With looping disabled, file completion holds the final frame and leaves the RTC connection open so remote tail frames can play. `close()` releases all file resources and tracks. `updateVideoFormat()` can adjust uplink encoding without changing the original model input format.
484
-
485
- File codecs must be supported by the browser, and Canvas capture and Web Audio must be available. Keep the page foregrounded for stable frame delivery; browser background throttling can reduce the upload frame rate. Playback restrictions, decode errors and preparation timeouts are reported rather than silently sending an empty stream.
486
-
487
- ### Generate from a network video
488
-
489
- Pass an HTTP or HTTPS video URL to let the server read the source directly. The SDK joins the RTC room and receives generated video and audio without capturing or publishing local media.
490
-
491
- ```ts
492
- import { RealtimeContext, RealtimeVideoFormat, RealtimeVideoSampleMethod } from "@xmaxai/web-sdk";
493
-
494
- const localStream = await realtime.createNetworkVideoStream({
495
- url: "https://example.com/source.mp4",
496
- videoFormat: new RealtimeVideoFormat({ width: 1920, height: 1024, fps: 30 }),
497
- sampleMethod: RealtimeVideoSampleMethod.time,
498
- onFinish: () => {
499
- console.log("Server finished processing the video");
500
- },
501
- });
502
-
503
- const remoteStream = await realtime.startGeneration({
504
- localStream,
505
- context: new RealtimeContext({ prompt: "Transform the scene into an animation" }),
506
- });
507
- ```
508
-
509
- Use a video format supported by the selected model. Bind the returned tracks to SDK video views as usual. The optional local preview plays once, muted, independently of server processing; no Canvas or local upload is involved. Creating the source does not start generation. Sampling defaults to `time`; `fps` is also available.
510
-
511
- The URL must be directly accessible to the server. Browser cookies and custom authorization headers are not forwarded. Local preview playback depends on browser codec support and page security policies; a preview failure does not stop server processing. The selected model's backend must support network video input.
512
-
513
- `onFinish` is delivered once for the current task after the server's `video_stopped` message and generation readiness. It does not mean the last remote frame has finished playing, so the SDK does not automatically disconnect. Local preview completion does not trigger this callback. Remote audio follows `setRemoteAudioVolume` (muted by default).
514
-
515
- `disconnect()` retains the source and preview for reconnection; `close()` releases them. Close the current source before creating another. `updateVideoFormat()` adjusts camera uplink encoding and is not available for a network video source.
516
-
517
- ### Non-realtime video tasks
518
-
519
- Use `client.createNonRealtimeManager()` to submit video-file processing tasks.
520
- This is cloud processing, not on-device or offline execution. It uses the client's
521
- API key and selects a dedicated task endpoint from `XmaxEnvironment`:
522
-
523
- - `china`: `https://api.xmaxai.com/open/api/v1`
524
- - `global`: `https://api.xmax.ai/open/api/v1`
525
-
526
- Task requests append `/offline-task` and its subpaths to this base URL.
527
- Realtime model endpoint overrides do not affect task requests; storage credentials
528
- continue to use the environment's default API endpoint.
529
-
530
- ```typescript
531
- import { NonRealtimeQuality, NonRealtimeTaskError } from "@xmaxai/web-sdk";
532
-
533
- const manager = client.createNonRealtimeManager();
534
- const controller = new AbortController();
535
-
536
- // videoFile is a File selected by the user.
537
- const storedVideo = await client.createStorageService().uploadVideo({
538
- data: videoFile,
539
- fileName: videoFile.name,
540
- onProgress: (loaded, total) => console.log(loaded, total),
541
- });
542
-
543
- const task = await manager.submitTask({
544
- videoPath: storedVideo.url,
545
- referencePath: referenceImageURL, // Optional; obtain via uploadImage().
546
- prompt: "Change the character's clothing while preserving the motion.",
547
- quality: NonRealtimeQuality.hd,
548
- // Omit fps to retain the source frame rate, including fractional rates.
549
- });
550
-
551
- // Persist task.uid before waiting, so the task can be queried after a reload.
552
- try {
553
- const completed = await manager.waitForCompletion(task.uid, {
554
- intervalMs: 2000,
555
- timeoutMs: 30 * 60 * 1000, // Optional client-side deadline.
556
- signal: controller.signal,
557
- onTaskUpdated: (snapshot) => console.log(snapshot.status),
558
- });
559
- console.log(completed.result?.url);
560
- } catch (error) {
561
- if (error instanceof NonRealtimeTaskError) {
562
- console.error(error.message, error.task);
563
- } else {
564
- throw error;
565
- }
566
- }
567
- ```
568
-
569
- - `submitTask()` returns immediately after acceptance and never automatically
570
- retries. A timeout or invalid response may still mean the server created and
571
- charged for the task; do not blindly resubmit.
572
- - `waitForCompletion()` polls serially and retries transient query failures up to
573
- three consecutive times by default, with backoff. A successful query resets the
574
- retry count. Without `timeoutMs`, waiting continues until completion, failure, or
575
- cancellation. `controller.abort()` stops local waiting and the in-flight query;
576
- it does **not** cancel or refund the server task.
577
- - `getTask(uid)` returns any task status, including `error`. Waiting for an `error`
578
- task, or a completed task without a usable result, throws `NonRealtimeTaskError`
579
- with the task snapshot attached.
580
- - `getTasks([uid, ...])` queries up to 100 IDs. `listTasks({ pageNumber, pageSize,
581
- status })` retrieves one page, newest first. Saved IDs can be queried or waited
582
- on using a new manager instance.
583
- - Upload local videos with `client.createStorageService().uploadVideo()` before
584
- submitting a task. It shares the image upload options and progress callback,
585
- uploads the original bytes via COS `putObject`, and returns a `StoredFile`.
586
- It does not transcode or use multipart upload; COS simple upload supports files
587
- up to [5GB](https://cloud.tencent.com/document/product/436/14113).
588
- MIME inference supports MP4/M4V, MOV, WebM, AVI, MKV, and OGV; successful storage
589
- does not guarantee that the task processor supports the file's codec or container.
590
-
591
- ### Downloading videos
592
-
593
- Call this from a user-initiated action, such as a download button:
594
-
595
- ```typescript
596
- await client.createStorageService().downloadVideo({
597
- url: videoURL,
598
- fileName: "video.mp4",
599
- // signal: controller.signal, // Optional cancellation.
600
- });
601
- ```
602
-
603
- The method fetches the complete file as a Blob and then requests browser saving.
604
- The URL must be directly accessible and allow CORS for cross-origin requests;
605
- the SDK does not send API credentials or cookies to it. This requires a browser
606
- document and retains the complete file until the browser takes over. Resolution
607
- means saving was requested, not that the user saved the file to disk.
608
-
609
379
  ## Example Project
610
380
 
611
381
  A complete example application featuring React is available in
@@ -618,7 +388,7 @@ It demonstrates real-time generation using live camera feeds and reference image
618
388
 
619
389
  - <ins><strong>Tencent Cloud TRTC SDK for Web</strong></ins> enables low-latency, real-time audio and video communication.
620
390
  - <ins><strong>Agora RTC SDK for Web</strong></ins> provides an alternative RTC transport for the Agora model.
621
- - <ins><strong>Volcengine VeRTC SDK for Web</strong></ins> provides RTC transport and device capture for the X2.1 preview model.
391
+ - <ins><strong>Volcengine VeRTC SDK for Web</strong></ins> enables real-time audio and video communication.
622
392
  - <ins><strong>Tencent Cloud COS SDK</strong></ins> handles media upload and download via object storage.
623
393
 
624
394
  <br>
@@ -190,4 +190,26 @@ declare enum VideoContentMode {
190
190
  fill = "fill"
191
191
  }
192
192
 
193
- export { CameraPosition as C, RealtimeVideoFormat as R, VideoContentMode as V, RealtimeVideoTrack as a, RealtimeVideoEncoderPreference as b, type RealtimeVideoFormatInit as c };
193
+ /**
194
+ * 单个视频视图最近采样窗口的呈现帧率,不代表屏幕实际刷新帧率。
195
+ */
196
+ interface VideoRenderStatistics {
197
+ /**
198
+ * video 按浏览器 presentedFrames 增量计数;canvas 按实际呈现提交计数。
199
+ */
200
+ readonly source: "video" | "canvas";
201
+ /**
202
+ * 原帧与插值帧的总呈现帧率,单位 fps。
203
+ */
204
+ readonly frameRate: number;
205
+ /**
206
+ * 原帧呈现帧率,单位 fps。
207
+ */
208
+ readonly originalFrameRate: number;
209
+ /**
210
+ * 插值帧呈现帧率,单位 fps;未开启插帧时为 0。
211
+ */
212
+ readonly interpolatedFrameRate: number;
213
+ }
214
+
215
+ export { CameraPosition as C, RealtimeVideoFormat as R, VideoContentMode as V, RealtimeVideoTrack as a, type VideoRenderStatistics as b, RealtimeVideoEncoderPreference as c, type RealtimeVideoFormatInit as d };
@@ -190,4 +190,26 @@ declare enum VideoContentMode {
190
190
  fill = "fill"
191
191
  }
192
192
 
193
- export { CameraPosition as C, RealtimeVideoFormat as R, VideoContentMode as V, RealtimeVideoTrack as a, RealtimeVideoEncoderPreference as b, type RealtimeVideoFormatInit as c };
193
+ /**
194
+ * 单个视频视图最近采样窗口的呈现帧率,不代表屏幕实际刷新帧率。
195
+ */
196
+ interface VideoRenderStatistics {
197
+ /**
198
+ * video 按浏览器 presentedFrames 增量计数;canvas 按实际呈现提交计数。
199
+ */
200
+ readonly source: "video" | "canvas";
201
+ /**
202
+ * 原帧与插值帧的总呈现帧率,单位 fps。
203
+ */
204
+ readonly frameRate: number;
205
+ /**
206
+ * 原帧呈现帧率,单位 fps。
207
+ */
208
+ readonly originalFrameRate: number;
209
+ /**
210
+ * 插值帧呈现帧率,单位 fps;未开启插帧时为 0。
211
+ */
212
+ readonly interpolatedFrameRate: number;
213
+ }
214
+
215
+ export { CameraPosition as C, RealtimeVideoFormat as R, VideoContentMode as V, RealtimeVideoTrack as a, type VideoRenderStatistics as b, RealtimeVideoEncoderPreference as c, type RealtimeVideoFormatInit as d };