@xmaxai/web-sdk 1.0.6 → 1.0.8

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,9 +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
- For Agora, use `RealtimeModel.x2_1_preview` (`x2.1-preview`). For TRTC, use
218
- `RealtimeModel.x2_0_trtc` (`x2.0-trtc`). `RealtimeModel.x2_0` (`x2.0`) uses VeRTC.
219
-
220
217
  ```javascript
221
218
  import {
222
219
  CameraPosition,
@@ -235,7 +232,7 @@ const client = new XmaxClient(
235
232
  );
236
233
 
237
234
  const realtime = client.createRealtimeManager(
238
- new RealtimeConfiguration({ model: RealtimeModel.x2_0_trtc })
235
+ new RealtimeConfiguration({ model: RealtimeModel.x2_1_preview })
239
236
  );
240
237
 
241
238
  const localStream = await realtime.createLocalCameraStream({
@@ -283,141 +280,6 @@ await realtime.updateUplinkVideoFormat(new RealtimeVideoFormat({
283
280
  }));
284
281
  ```
285
282
 
286
- Pass a complete format; omitted bitrate and preference fields use SDK defaults.
287
- The local track's `videoFormat` is updated on success and reused on reconnect.
288
- Generation and remote frame interpolation retain the original format. Actual sent
289
- resolution, frame rate, and bitrate depend on the device, browser, and network;
290
- use the statistics callbacks to observe them. Await each operation before starting
291
- another configuration or lifecycle operation.
292
-
293
- For a frame-rate-only experiment after connecting a local camera or file stream:
294
-
295
- ```javascript
296
- await realtime.updateUplinkFrameRate(24);
297
- ```
298
-
299
- This preserves the last successfully applied width, height, resolved bitrate limits,
300
- and encoding preference. It does not recalculate default bitrates for the new frame
301
- rate or copy measured send statistics into the configuration. The complete encoder
302
- configuration is still resubmitted, so preservation of RTC's internal adaptation
303
- state is not guaranteed. Validate actual send statistics under weak networks.
304
-
305
- **Agora camera sender-only experiment:** camera capture stays at its initial settings.
306
- Camera updates use `RTCRtpSender.setParameters()` (`scaleResolutionDownBy`,
307
- `maxFramerate`, `maxBitrate` in bps), not Agora's `setEncoderConfiguration()`.
308
- Only the maximum bitrate is applied; the standard sender API cannot enforce the
309
- configured minimum bitrate. Pre-publish updates are queued and applied immediately
310
- after publication, so the very first transmitted frames may use the initial profile.
311
- Scaling uses the actual captured dimensions, preserves aspect ratio, and does not upscale.
312
- Sender replacement/rejoin reapplies the latest target. Unsupported or silently ignored
313
- parameters are reported as errors, without falling back to camera constraints.
314
- Read-back confirms accepted parameters, not actual frame dimensions or persistent
315
- ownership against Agora's later adjustments; validate Chrome/Safari using RTC statistics.
316
- Search `Agora Sender Parameters` for accepted limits and `Agora RTC Statistics` for
317
- capture/send dimensions. File-video encoding and other RTC providers are unchanged.
318
-
319
- Agora uplink and downlink adaptation are always enabled; no configuration flag or manual
320
- selector is needed. Other RTC providers are not yet integrated. After generation
321
- starts, three consecutive poor uplink quality samples lower one tier, and five good
322
- samples probe an upgrade. Five tiers jointly change resolution and frame rate:
323
- 1024×1920/30, 768×1440/24, 640×1200/24, 512×960/20, and 384×720/16.
324
- Landscape dimensions are swapped; custom sources scale proportionally from their
325
- initial or most recently manually applied format, with even dimensions and FPS
326
- capped by that baseline. Automatic updates preserve this baseline across reconnects.
327
- Default bitrate limits are recalculated for each tier; explicit limits and encoding
328
- preference are preserved. Uplink changes do not alter generation or result-stream sizes.
329
- Downlink independently uses the same quality thresholds and five resolution tiers,
330
- relative to the generation's original dimensions. It sends only `change_target_size`
331
- with `[width, height]`, without changing FPS, bitrate limits, or model inference.
332
- The protocol has no application ACK: a successful send records a requested tier,
333
- not a confirmed output size; use remote RTC statistics to verify actual dimensions.
334
- New Agora local tracks read the last applied uplink tier before publishing
335
- (the camera sender-only experiment applies it immediately after publication);
336
- new generation tasks restore the last requested downlink tier via `start.params.target_size`.
337
- Each direction falls back to L2 when no valid history is available. History is stored
338
- in `localStorage`, separately by model and direction, with no expiry or stability window
339
- in this first version. Storage failures never block generation. The original L1 baseline
340
- is retained for recovery; reconnecting the same local track keeps its in-memory uplink tier.
341
- Downlink changes only resolution, not FPS. Interpolation follows the requested dimensions,
342
- showing raw video while frame sizes do not match. See
343
- [the strategy and weak-network test steps](docs/realtime-adaptive-quality.md).
344
-
345
- Each model declares its supported RTC providers. The SDK selects the model's
346
- default provider when `provider` is omitted. To use Agora, replace the manager
347
- configuration above; camera capture, generation, rendering, and cleanup use the same APIs:
348
-
349
- ```javascript
350
- const realtime = client.createRealtimeManager(
351
- new RealtimeConfiguration({
352
- model: RealtimeModel.x2_1_preview,
353
- })
354
- );
355
- ```
356
-
357
- To use VeRTC, select `x2.0`:
358
-
359
- ```javascript
360
- const realtime = client.createRealtimeManager(
361
- new RealtimeConfiguration({
362
- model: RealtimeModel.x2_0,
363
- })
364
- );
365
- ```
366
-
367
- The provider is fixed for each manager: `x2.0-trtc` uses `RtcProvider.trtc`,
368
- `x2.1-preview` uses `RtcProvider.agora`, and `x2.0` uses `RtcProvider.vertc`.
369
- Import `RtcProvider` to specify it explicitly; unsupported known-model/provider
370
- combinations are rejected during configuration. Use the exported
371
- `supportedRtcProviders(model)` to inspect model capabilities. The SDK does not read
372
- `modelExtra.provider` from the backend; the resolved configuration determines how
373
- RTC credentials are parsed.
374
-
375
- The `x2.1-preview` model uses `https://cloud.xmax.22duck.cn/open/api/v1` in both environments.
376
- The other built-in models and file uploads use the configured
377
- environment's production API endpoint: `https://cloud.xmax.22duck.cn/open/api/v1`
378
- for China and `https://api.xmax.cloud/open/api/v1` for Global.
379
-
380
- Custom realtime model names are also accepted without an SDK update:
381
-
382
- ```javascript
383
- const realtime = client.createRealtimeManager(
384
- new RealtimeConfiguration({ model: "your-new-model" })
385
- );
386
- ```
387
-
388
- The model name is sent unchanged; the server determines whether it is available.
389
- Unknown models inherit the `x2.1-preview` defaults: Agora, the production session API above
390
- (in both client environments), a 1024 × 1920 camera at 30 fps, and the same
391
- 1024 × 1920 / 1920 × 1024 input resolution buckets and media rules.
392
- You may explicitly choose another supported `RtcProvider` for a custom model;
393
- `supportedRtcProviders` lists all SDK adapters for custom models, with Agora first,
394
- but this does not guarantee server-side support. `modelDisplayName` returns the
395
- custom name unchanged. Empty/blank or non-string model names, invalid RTC providers,
396
- and invalid video parameters are still rejected locally.
397
-
398
- VeRTC uses `@volcengine/rtc` 4.69.3 and the fixed AppID
399
- `69a177e226e9b90176a86b96`. Session credentials must contain this `rtc_app_id`,
400
- `room_id`, and `room_token`; the RTC user is `user_id` (falling back to `userUid`),
401
- and `bot_name` identifies the bot. Camera and microphone capture use VeRTC's SDK.
402
- The preview model uses the same media rules as `x2.0-trtc`: 1024 × 1920 or
403
- 1920 × 1024 input, with 30 fps by default.
404
-
405
- VeRTC sends the existing room-event JSON as a single room text message, without
406
- chunk envelopes. The adapter rejects messages above 64 KiB of UTF-8 data; vendor
407
- send failures are returned to the caller. TRTC and Agora retain their chunking.
408
- HTTP session heartbeats start after joining and publishing the local stream, with
409
- the first request after 10 seconds. Changed tokens returned by heartbeat are
410
- applied to Agora and VeRTC; expiry callbacks also request fresh credentials.
411
- VeRTC restores media after token expiry without creating another business session
412
- or restarting the generation task. HTTP heartbeats maintain the session and are
413
- not treated as a client-side billing trigger.
414
-
415
- `XmaxConfiguration.environment` selects the Agora region (`china` or `global`);
416
- concurrent Agora managers must use the same environment. RTC modules load on demand.
417
- Statistics not supplied by a provider are `undefined`, including Agora playback
418
- buffer delay and separate uplink/downlink RTT. RTC end-to-end estimates do not
419
- include AI generation time and use each provider's own measurement definition.
420
-
421
283
  <br>
422
284
 
423
285
  ### Using React
@@ -514,156 +376,6 @@ position to the backend.
514
376
 
515
377
  <br>
516
378
 
517
- ### Generate from a local video
518
-
519
- 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.
520
-
521
- ```ts
522
- // Call directly from a file-selection or click handler to unlock browser playback.
523
- const localStream = await realtime.createLocalVideoStream({
524
- file,
525
- videoFormat: new RealtimeVideoFormat({ width: 1920, height: 1024, fps: 30 }),
526
- loop: true,
527
- includeAudio: true,
528
- });
529
-
530
- // Optionally bind localStream.videoTrack to an SDK video view.
531
- const remoteStream = await realtime.startGeneration({
532
- localStream,
533
- context: new RealtimeContext({ prompt: "Transform the scene into an animation" }),
534
- });
535
- ```
536
-
537
- 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.
538
-
539
- 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).
540
-
541
- `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. `updateUplinkVideoFormat()` can adjust uplink encoding without changing the original model input format.
542
-
543
- 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.
544
-
545
- ### Generate from a network video
546
-
547
- 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.
548
-
549
- ```ts
550
- import { RealtimeContext, RealtimeVideoFormat, RealtimeVideoSampleMethod } from "@xmaxai/web-sdk";
551
-
552
- const localStream = await realtime.createNetworkVideoStream({
553
- url: "https://example.com/source.mp4",
554
- videoFormat: new RealtimeVideoFormat({ width: 1920, height: 1024, fps: 30 }),
555
- sampleMethod: RealtimeVideoSampleMethod.time,
556
- onFinish: () => {
557
- console.log("Server finished processing the video");
558
- },
559
- });
560
-
561
- const remoteStream = await realtime.startGeneration({
562
- localStream,
563
- context: new RealtimeContext({ prompt: "Transform the scene into an animation" }),
564
- });
565
- ```
566
-
567
- 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.
568
-
569
- 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.
570
-
571
- `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).
572
-
573
- `disconnect()` retains the source and preview for reconnection; `close()` releases them. Close the current source before creating another. `updateUplinkVideoFormat()` adjusts camera uplink encoding and is not available for a network video source.
574
-
575
- ### Non-realtime video tasks
576
-
577
- Use `client.createNonRealtimeManager()` to submit video-file processing tasks.
578
- This is cloud processing, not on-device or offline execution. It uses the client's
579
- API key and selects a dedicated task endpoint from `XmaxEnvironment`:
580
-
581
- - `china`: `https://api.xmaxai.com/open/api/v1`
582
- - `global`: `https://api.xmax.ai/open/api/v1`
583
-
584
- Task requests append `/offline-task` and its subpaths to this base URL.
585
- Realtime model endpoint overrides do not affect task requests; storage credentials
586
- continue to use the environment's default API endpoint.
587
-
588
- ```typescript
589
- import { NonRealtimeQuality, NonRealtimeTaskError } from "@xmaxai/web-sdk";
590
-
591
- const manager = client.createNonRealtimeManager();
592
- const controller = new AbortController();
593
-
594
- // videoFile is a File selected by the user.
595
- const storedVideo = await client.createStorageService().uploadVideo({
596
- data: videoFile,
597
- fileName: videoFile.name,
598
- onProgress: (loaded, total) => console.log(loaded, total),
599
- });
600
-
601
- const task = await manager.submitTask({
602
- videoPath: storedVideo.url,
603
- referencePath: referenceImageURL, // Optional; obtain via uploadImage().
604
- prompt: "Change the character's clothing while preserving the motion.",
605
- quality: NonRealtimeQuality.hd,
606
- // Omit fps to retain the source frame rate, including fractional rates.
607
- });
608
-
609
- // Persist task.uid before waiting, so the task can be queried after a reload.
610
- try {
611
- const completed = await manager.waitForCompletion(task.uid, {
612
- intervalMs: 2000,
613
- timeoutMs: 30 * 60 * 1000, // Optional client-side deadline.
614
- signal: controller.signal,
615
- onTaskUpdated: (snapshot) => console.log(snapshot.status),
616
- });
617
- console.log(completed.result?.url);
618
- } catch (error) {
619
- if (error instanceof NonRealtimeTaskError) {
620
- console.error(error.message, error.task);
621
- } else {
622
- throw error;
623
- }
624
- }
625
- ```
626
-
627
- - `submitTask()` returns immediately after acceptance and never automatically
628
- retries. A timeout or invalid response may still mean the server created and
629
- charged for the task; do not blindly resubmit.
630
- - `waitForCompletion()` polls serially and retries transient query failures up to
631
- three consecutive times by default, with backoff. A successful query resets the
632
- retry count. Without `timeoutMs`, waiting continues until completion, failure, or
633
- cancellation. `controller.abort()` stops local waiting and the in-flight query;
634
- it does **not** cancel or refund the server task.
635
- - `getTask(uid)` returns any task status, including `error`. Waiting for an `error`
636
- task, or a completed task without a usable result, throws `NonRealtimeTaskError`
637
- with the task snapshot attached.
638
- - `getTasks([uid, ...])` queries up to 100 IDs. `listTasks({ pageNumber, pageSize,
639
- status })` retrieves one page, newest first. Saved IDs can be queried or waited
640
- on using a new manager instance.
641
- - Upload local videos with `client.createStorageService().uploadVideo()` before
642
- submitting a task. It shares the image upload options and progress callback,
643
- uploads the original bytes via COS `putObject`, and returns a `StoredFile`.
644
- It does not transcode or use multipart upload; COS simple upload supports files
645
- up to [5GB](https://cloud.tencent.com/document/product/436/14113).
646
- MIME inference supports MP4/M4V, MOV, WebM, AVI, MKV, and OGV; successful storage
647
- does not guarantee that the task processor supports the file's codec or container.
648
-
649
- ### Downloading videos
650
-
651
- Call this from a user-initiated action, such as a download button:
652
-
653
- ```typescript
654
- await client.createStorageService().downloadVideo({
655
- url: videoURL,
656
- fileName: "video.mp4",
657
- // signal: controller.signal, // Optional cancellation.
658
- });
659
- ```
660
-
661
- The method fetches the complete file as a Blob and then requests browser saving.
662
- The URL must be directly accessible and allow CORS for cross-origin requests;
663
- the SDK does not send API credentials or cookies to it. This requires a browser
664
- document and retains the complete file until the browser takes over. Resolution
665
- means saving was requested, not that the user saved the file to disk.
666
-
667
379
  ## Example Project
668
380
 
669
381
  A complete example application featuring React is available in
@@ -676,7 +388,7 @@ It demonstrates real-time generation using live camera feeds and reference image
676
388
 
677
389
  - <ins><strong>Tencent Cloud TRTC SDK for Web</strong></ins> enables low-latency, real-time audio and video communication.
678
390
  - <ins><strong>Agora RTC SDK for Web</strong></ins> provides an alternative RTC transport for the Agora model.
679
- - <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.
680
392
  - <ins><strong>Tencent Cloud COS SDK</strong></ins> handles media upload and download via object storage.
681
393
 
682
394
  <br>