X2 real-time video editing
X2 and X2.1 (by Xmax AI) edit a live camera or video stream as it plays: swap the character, try on clothes, restyle the scene or add a subject, from a text prompt and an optional reference image. Each model is served by two hosts. Your server books a session, and your user's browser streams straight to the host with short-lived credentials. Video never passes through VideoRouter.
| Model id | Model | Host SDK in the browser | Price | Output for a portrait 3:4 camera |
|---|---|---|---|---|
xmax/x2.1 | X2.1 | @xmaxai/web-sdk | $0.0017083/s ($6.15/h) | up to 1152×1536 |
reactor/xmax-x2-1 | X2.1 | @reactor-team/js-sdk | $0.0017425/s ($6.27/h) | up to 1152×1536 |
xmax/x2.0 | X2.0 | @xmaxai/web-sdk | $0.0017083/s ($6.15/h) | 768×1024 |
reactor/x2 | X2.0 | @reactor-team/js-sdk | $0.0017425/s ($6.27/h) | 832×1088 |
Current prices are always in GET /v1/live-video/models. The picture size can step down with network quality. Xmax says it will retire X2.0, so use X2.1 for new work.
Billing. Booking holds price × max_duration_seconds from your balance. When the session ends you pay for the seconds the host meters, and the rest of the hold is released. A session that never connects costs nothing. The meter runs while the stream is connected, including before the first frame, so end sessions you are not using. A session can be 10 to 1800 seconds long (default 300), and an organization can have 3 live sessions open at once.
Integration takes three steps: mint a browser token on your server, upload reference images to VideoRouter, then connect with RealtimeEditModel from our JavaScript SDK. The same code runs on both hosts, with failover, and on every other real-time editing model: change only the model id.
Browser requirements and install
- A modern WebRTC browser, on HTTPS or localhost.
- Ask for the camera (and the microphone, if you send audio) from a user action such as a button click. Browsers may also need a user action before media can play.
- Inside an iframe, the host page must allow it:
<iframe allow="camera; microphone; autoplay">. - In server-rendered frameworks, create SDK clients and video views in the browser only.
npm install videorouter-live @xmaxai/web-sdk @reactor-team/js-sdkRealtimeEditModel, X2_PRESETS and lv.upload() need videorouter-live 0.3.0 or newer. Tested with @xmaxai/web-sdk 1.1.5 and @reactor-team/js-sdk 3.4.0. RealtimeEditModel runs in web browsers; there is no iOS or Android version.
1. Mint a browser token on your server
Never put your API key in a page. Mint a short-lived token that is limited to the models you list. It can open and drive live-video sessions and upload reference images, and nothing else.
curl https://videorouter.sh/api/v1/live-video/tokens \
-H "Authorization: Bearer $VIDEOROUTER_API_KEY" -H "Content-Type: application/json" \
-d '{"models": ["xmax/x2.1", "reactor/xmax-x2-1"], "expires_in": 3600, "max_sessions": 1, "max_session_duration_seconds": 300}'
# -> {"token": "...", "expires_at": "...", ...}For failover, list both hosts' model ids.
2. Upload reference images to VideoRouter
Upload images to VideoRouter, not to a model host. One upload endpoint and one URL work whichever host serves the session. Do not use the Xmax SDK's createStorageService() for reference images.
// browser, with the token (or on your server with your API key)
import { LiveVideo } from "videorouter-live";
const lv = new LiveVideo({ token });
const { url, expiresIn } = await lv.upload(file); // File or Blob; expiresIn = 1800 (seconds)curl https://videorouter.sh/api/v1/uploads \
-H "Authorization: Bearer $TOKEN" -F "file=@character.png;type=image/png"
# -> {"url": "https://videorouter.sh/media/uploads/<name>", "expires_in": 1800}| Rule | Value |
|---|---|
| Formats with a browser token | PNG, JPEG, WebP. The file's Content-Type must match its contents. |
| Size | Up to 20 MB per image |
| Uploads per browser token | 100 (429 after that; mint a new token) |
| Lifetime | 30 minutes. Upload again after that. |
An expired or broken link is not reported. When we tested xmax/x2.1 with a link that returned 404, there was no error and the model kept the previous reference image. Upload shortly before you use the image.
To read an upload back from a web page (for example to hand the file to Reactor's SDK), use GET /v1/uploads/{name}, where name is the last part of the URL, with your token. The URL itself cannot be read by fetch() across origins. It does work as a link you give to a model.
3. Connect with RealtimeEditModel
import { RealtimeEditModel, X2_PRESETS } from "videorouter-live";
import * as xmax from "@xmaxai/web-sdk";
import * as reactor from "@reactor-team/js-sdk";
const model = new RealtimeEditModel({ model: "xmax/x2.1", maxDurationSeconds: 300, hostSdk: { xmax, reactor } });
await model.connect(token); // from step 1
const camera = await navigator.mediaDevices.getUserMedia({ video: { width: 768, height: 1024, frameRate: 24 } });
await model.start(camera, {
prompt: X2_PRESETS.charx,
image: file, // File / Blob / data URI (uploaded for you), or an uploaded URL
onRemoteStream: (stream) => (video.srcObject = stream), // <video autoplay playsinline>
onState: ({ host, state }) => console.log(host, state),
onError: (error) => console.error(error), // the stream failed after it had started
});
await model.setPrompt("Now standing outside in heavy snow"); // the reference image is kept
await model.setPrompt(X2_PRESETS.clothx, { image: outfit }); // or replace it
await model.end(); // stops the stream and settles the billstart() uploads a new File to VideoRouter before booking, so the upload does not use any of your session time. The session heartbeat is sent for you. end() also stops the tracks of the MediaStream you passed in.
Constructor options
| Option | Default | What it does |
|---|---|---|
model | xmax/x2.1 | Preferred model id (see the table above) |
maxDurationSeconds | 300 | Session cap; the price of this much time is held |
fallback | true | Use the other host if this one cannot open or connect |
connectTimeout / uploadTimeout | 45000 / 60000 ms | How long to wait for the stream / for the image upload |
hostSdk | dynamic import | { xmax, reactor }, the two host SDK modules (both are needed for fallback) |
container | - | Xmax only: a sized element that shows the output and accepts drags (MoX) |
configureRealtime(realtime, sdk) | - | Xmax only: runs before media is created; register Xmax listeners here |
realtimeOptions | - | Xmax only: provider, isAdaptiveQualityEnabled |
start(input, options) and setPrompt(text, options)
| Option | Where | Notes |
|---|---|---|
prompt | start (required) | A string. Empty only for MoX (Xmax only). |
image | both | Reference image. Without it, setPrompt keeps the current one. |
faceRestoration, extraParams | both | Xmax only |
restart | setPrompt | Xmax only: restart the task on the same connection |
onRemoteStream, onState, onError | start | Work on both hosts. state values are the host's own. |
model.activeModel is the model that served the session. model.session holds billedSeconds and costUsd after end(). model.host gives the host SDK objects: { name: "xmax", client, realtime, view, localStream } or { name: "reactor", reactor }.
Failover
If the first host cannot open the session, VideoRouter opens it on the other. If it opens but no video arrives in time, RealtimeEditModel ends it (you pay only what that host metered) and retries on the other host. A stream that drops after start() resolved is not moved: handle onError and start again. Each host is billed at its own price (see the table above).
Xmax-only features
Using any of these keeps the session on Xmax (no failover to Reactor), and with a reactor/… model it is refused before anything is booked: an empty prompt, faceRestoration, extraParams, restart, container, configureRealtime, realtimeOptions, or an input function.
Microphone, video file or your own input. A MediaStream sends video only. For anything else, pass start() a function that creates the input with Xmax's SDK. realtime is Xmax's realtime manager and sdk is the @xmaxai/web-sdk module:
// camera + microphone
await model.start((realtime, sdk) => realtime.createLocalCameraStream({
videoFormat: sdk.defaultCameraVideoFormat("x2.1"), position: sdk.CameraPosition.front, useMicrophone: true,
}), { prompt: "Restyle the video as a watercolor painting", onRemoteStream });
// a local video file
await model.start((realtime, sdk) => realtime.createLocalVideoStream({
file, videoFormat: sdk.defaultCameraVideoFormat("x2.1"), loop: true, includeAudio: true,
}), { prompt: "Restyle the video as an anime film", onRemoteStream });The same way: createLocalImageStream({ file, videoFormat }) edits a still image, and createExternalVideoStream({ source }) sends your own video frames and PCM audio. A local file does not need uploading.
Statistics, recording and audio. Register Xmax's listeners in configureRealtime, which runs before any media is created:
const model = new RealtimeEditModel({
model: "xmax/x2.1", hostSdk: { xmax },
configureRealtime: async (realtime) => {
await realtime.setDownlinkVideoStatisticsListener((stats) => stats && console.log(stats.width, stats.height));
await realtime.setRemoteMediaFrameListener((packet) => { // output video frames and returned PCM audio
if (packet.content.type === "video") packet.content.frame.frame.close(); // always close video frames
else console.log(packet.content.frame.sampleRate, packet.content.frame.data);
});
},
});onRemoteStream gives you the video to display; use the frame listener when you need the audio data or want to record. The timing listener is setTimingListener (Xmax's documentation calls it setLaunchTimingListener, which SDK 1.1.5 does not have). setNetworkQualityListener and setUplinkVideoStatisticsListener are registered the same way.
Other controls. After start(), model.host.realtime is Xmax's realtime manager, for example setRemoteAudioVolume(0.5) or setDownlinkQualityLevel(level). model.host is { name: "xmax", client, realtime, view, localStream }.
- Never call
model.host.realtime.setStateListener. It replaces the listenerRealtimeEditModelneeds to report the session and detect failures. UseonState. - X2.0 does not accept the 1920×1080 camera preset.
sdk.defaultCameraVideoFormat(model)works for both models ("x2.1"or"x2.0"). - A front camera created by Xmax's SDK is mirrored. A
MediaStreamyou pass in is not.
Preset modes
These are Xmax's recommended prompts. In RealtimeEditModel they are X2_PRESETS.charx and so on; with any SDK, send the text as the prompt. Results vary with the input and the reference image, so test with your own.
| Mode | Use | Prompt | Reference image |
|---|---|---|---|
| CharX | Character swap | Become the character in the reference image | the character |
| ClothX | Virtual try-on | Keep the character and background unchanged, only replace clothing with the reference-image outfit. | the outfit |
| VibeX | Animate the reference | The character from the reference image recreates the actions in the video. Preserve all appearance details of the reference character exactly, and keep the original background from the reference image unchanged. | character and background |
| DimX | Add a subject | Summon / Add a Subject: Keep all existing subjects in the original video. Add the subject from the reference image without replacing any existing subject. Summon the reference character onto the shoulder or hand of the person in the video. | the subject |
| MoX (Instant and Continuous) | Drag to move | (empty string) | - |
MoX is steered by dragging on the output with a mouse, pen or fingers, and works on Xmax only. Pass container, a sized element; RealtimeEditModel shows the output in it and takes the drags:
// MoX: RealtimeEditModel shows Xmax's view in your element, and drags on it move the subject
const model = new RealtimeEditModel({ model: "xmax/x2.1", hostSdk: { xmax }, container: document.querySelector("#stage") }); // give #stage a width and height
await model.connect(token);
await model.start(camera, { prompt: X2_PRESETS.mox });Errors and troubleshooting
VideoRouter errors
| Response | Meaning |
|---|---|
400 unknown live-video model | The id is not offered |
402 insufficient_credits | Your balance cannot cover the hold. Add credit or lower maxDurationSeconds. |
429 concurrency_limit / host_capacity | Too many open sessions, or the host is full. Retry after Retry-After. |
502 host_unavailable | No host could take the session. With fallback on, RealtimeEditModel has already tried the other host, unless you used an Xmax-only feature. |
/v1/uploads 400 / 429 | Not a PNG, JPEG or WebP (browser token), too large, or the token's upload limit is reached |
Stream errors
start() rejects, or onError is called after the stream has started. On Xmax the error is usually an XmaxError with code, message and sometimes apiCode. A SessionStateError comes from RealtimeEditModel itself, for example when a stream does not connect in time or an Xmax-only feature is used with a Reactor model.
| Code | What to do |
|---|---|
INVALID_CONFIGURATION | Check the video format and your input function or configureRealtime |
CAMERA_PERMISSION_DENIED, MICROPHONE_PERMISSION_DENIED | Check browser and system permissions |
NETWORK_ERROR, TIMEOUT | Check the network, proxy, VPN and firewall |
API_ERROR, SESSION_ERROR | Look at apiCode. 46019 or TEMPORARY_API_KEY_LIMIT_REACHED means the booked time is used up or the session was ended: start a new one. |
RTC_ERROR, MEDIA_ERROR | Check browser support and the input media |
UNSAFE_IMAGE | Use an image that meets the content rules |
CANCELLED, INTERNAL_ERROR | Keep the session id for support |
Troubleshooting
| Symptom | Check |
|---|---|
| The reference image has no effect | The link expired or cannot be fetched. Upload again. |
Nothing shows in container | Give the element a width and a height |
| "Realtime generation start timed out" | Make sure the browser is really sending video. In automated Chrome on macOS, hardware H.264 sent none; --disable-accelerated-video-encode fixed it. |
| The output is mirrored | Xmax mirrors a front camera created by its SDK. A MediaStream passed to RealtimeEditModel is not mirrored. |
| Slow start on Xmax | A few seconds is normal; a new reference image adds its upload time |