@xmaxai/web-sdk 1.0.4 → 1.0.5

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
@@ -292,39 +292,58 @@ resolution, frame rate, and bitrate depend on the device, browser, and network;
292
292
  use the statistics callbacks to observe them. Await each operation before starting
293
293
  another configuration or lifecycle operation.
294
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:
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:
297
298
 
298
299
  ```javascript
299
- import { RtcProvider } from "@xmaxai/web-sdk";
300
-
301
300
  const realtime = client.createRealtimeManager(
302
301
  new RealtimeConfiguration({
303
- provider: RtcProvider.agora,
304
302
  model: RealtimeModel.x2_0_agora,
305
303
  })
306
304
  );
307
305
  ```
308
306
 
309
- To use VeRTC, set both values explicitly:
307
+ To use VeRTC, select the preview model:
310
308
 
311
309
  ```javascript
312
310
  const realtime = client.createRealtimeManager(
313
311
  new RealtimeConfiguration({
314
- provider: RtcProvider.vertc,
315
312
  model: RealtimeModel.x2_1_preview,
316
313
  })
317
314
  );
318
315
  ```
319
316
 
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.
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.
324
325
 
325
326
  The `x2.0-agora` and `x2.1-preview` models use
326
327
  `https://dev.xmaxai.com/open/api/v1` in both environments.
327
- Other models and file uploads use the configured environment's API endpoint.
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.
328
347
 
329
348
  VeRTC uses `@volcengine/rtc` 4.69.3 and the fixed AppID
330
349
  `69a177e226e9b90176a86b96`. Session credentials must contain this `rtc_app_id`,
@@ -437,6 +456,156 @@ this through `setStateListener`.
437
456
 
438
457
  <br>
439
458
 
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
+
440
609
  ## Example Project
441
610
 
442
611
  A complete example application featuring React is available in