# Effects SDK (Web) — LLM integration guide > Real-time AI video effects for the browser: virtual background (blur, image, video, > color, transparent), beautification (touch-up), portrait lighting, smart zoom > (auto-framing), low-light enhancement, color correction, LUT color filters, sharpness, > noise suppression, mirroring, chroma key, 3D face avatars, overlays (watermark, > lower thirds, stickers, full-screen overlay, fully custom animated overlays) and a > built-in recorder. Input is a camera MediaStream (or single VideoFrames); output is a > processed MediaStream or canvas. SDK version described here: 3.13.1 npm package: `effects-sdk` CDN bundle: `https://effectssdk.ai/sdk/web//tsvb-web.js` (e.g. `.../3.13.1/tsvb-web.js`) TypeScript types: shipped in the npm package (`effects-sdk.d.ts`) Repository / issues: https://github.com/EffectsSDK/video-effects-sdk-web A customer ID (license key) is required. It is issued by Effects SDK (https://effectssdk.ai). This file is written for AI coding assistants. Everything below is the public API. Prefer the patterns here over guesses; method names and argument ranges are exact. ------------------------------------------------------------------------------- ## 1. The 6 rules that prevent 90% of integration bugs 1. Call effect methods ONLY after `onReady` fires. Before that, effects are not loaded and every effect method silently returns `false` (no exception). 2. Call `sdk.run()` after `onReady`. Processing is OFF by default — without `run()` the output stream carries the original, unprocessed frames. 3. Register `sdk.onReady = ...` and `sdk.onError(...)` BEFORE `sdk.useStream(...)`. 4. `sdk.config({...})` must be called BEFORE `useStream()` / `initFrameProcessor()` / `preload()`. Settings are read during initialization. 5. Most methods return `boolean`: `false` means "effect not loaded / not ready", not an error. Check return values when debugging "nothing happens". 6. `LayoutMode`, `PresetType`, `ErrorCode`, `ErrorType`, `ErrorEmitter` are exported as TYPES only. Do NOT write `LayoutMode.TRANSPARENT` or `ErrorCode.CPU_FALLBACK` in runtime code — pass the string / compare the number (`'transparent'`, `3001`). The only runtime exports are `tsvb`, `SdkError`, `CustomOverlay`, `overlay`, `componentsMap`. ------------------------------------------------------------------------------- ## 2. Installation ### npm (bundlers: Vite, webpack, Next.js, etc.) ```bash npm install effects-sdk ``` ```js import { tsvb } from 'effects-sdk'; // optional: import { tsvb, SdkError, overlay } from 'effects-sdk'; ``` The package ships ESM (`tsvb.mjs`) and CJS (`tsvb.cjs`). It is browser-only: in SSR frameworks (Next.js, Nuxt, SvelteKit, Remix) create the SDK only on the client, e.g. inside `useEffect` / `onMounted`, or with a dynamic import: ```js // Next.js / React client component 'use client'; useEffect(() => { let sdk; (async () => { const { tsvb } = await import('effects-sdk'); sdk = new tsvb('YOUR_CUSTOMER_ID'); // ...setup, see section 3 })(); return () => { sdk?.destroy(); }; }, []); ``` ### Script tag (no bundler) ```html ``` Always pin the exact version in the URL. ------------------------------------------------------------------------------- ## 3. Minimal working integration (copy this) ```js import { tsvb } from 'effects-sdk'; const sdk = new tsvb('YOUR_CUSTOMER_ID'); // 1) configure (optional; before useStream) sdk.config({ preset: 'balanced', // segmentation quality/speed: quality | balanced | speed | lightning provider: 'auto', // webgpu | wasm | auto }); // 2) optional: start downloading ML models early (e.g. on page load) sdk.preload(); // 3) callbacks first sdk.onError((e) => { // e: { type: 'error' | 'warning' | 'info', code?: number, message, emitter?, data?, cause? } if (e.type === 'error') console.error('[EffectsSDK]', e.code, e.message, e.data); }); sdk.onReady = () => { sdk.run(); // REQUIRED: start applying effects sdk.setBlur(0.6); // blur background, 0..1 // or: sdk.setBackground('https://example.com/office.jpg'); }; // 4) feed the camera const camera = await navigator.mediaDevices.getUserMedia({ video: { width: 1280, height: 720, frameRate: 30 }, audio: false, }); sdk.useStream(camera); // 5) consume the result const processed = sdk.getStream(); // MediaStream (video only) document.querySelector('video').srcObject = processed; // or render into an existing canvas: sdk.toCanvas(canvasElement); ``` To send the processed video over WebRTC / a conferencing SDK, take the video track: ```js const track = sdk.getStream().getVideoTracks()[0]; peerConnection.addTrack(track, sdk.getStream()); // raw WebRTC // or sender.replaceTrack(track); // swap camera -> processed // Audio is NOT processed: add the original microphone track separately. ``` ------------------------------------------------------------------------------- ## 4. Lifecycle ``` new tsvb(customerId) -> config({...}) (optional, before init) -> preload() (optional, warms model downloads) -> onReady = fn; onError(fn) -> useStream(mediaStream) (or initFrameProcessor() for VideoFrame mode) ... async init: auth, model download, pipeline build ... -> onReady fires -> run() + configure effects -> getStream() / toCanvas() -> stop() / run() (bypass / resume effects; stream keeps flowing) -> freeze() / unfreeze() (pause / resume the effect pipeline) -> destroy() (release everything; create a new instance to reuse) ``` ### Switching cameras / changing resolution Call `useStream(newStream)` again with the new MediaStream. The already loaded pipeline is reused; `onReady` fires again. Stop the old camera tracks yourself. ```js const newCam = await navigator.mediaDevices.getUserMedia({ video: { deviceId: { exact: id } } }); oldCam.getTracks().forEach(t => t.stop()); sdk.useStream(newCam); ``` The output stream returned by `getStream()` may change after `useStream()`; re-read it in `onReady` and re-attach it where needed. ### Teardown ```js await sdk.destroy(); // destroy(true) also releases ML sessions and clears model cache camera.getTracks().forEach(t => t.stop()); ``` After `destroy()` the instance is unusable; create a new `tsvb` instance if needed. In React, destroy in the effect cleanup. With React StrictMode (double mount) make sure the cleanup awaits/handles `destroy()` and that you don't create two instances that both call `useStream()` on the same camera. ------------------------------------------------------------------------------- ## 5. `sdk.config(options)` — all keys All keys optional. Call before `useStream()` / `initFrameProcessor()` / `preload()`. | key | type | default | meaning | |---|---|---|---| | `preset` | `'quality' \| 'balanced' \| 'speed' \| 'lightning'` | `'balanced'` | initial segmentation preset | | `provider` | `'webgpu' \| 'wasm' \| 'auto'` | `'webgpu'` | where segmentation runs. `auto`/`webgpu` fall back to CPU WASM if WebGPU is unusable (reported as code 3001 `CPU_FALLBACK`) | | `effects` | `Array<'virtual_background' \| 'smart_zoom' \| 'low_light' \| 'color_correction'>` | all four | ML effects loaded at init. Exclude ones you don't need to save download/memory; load later with `loadEffect()` | | `proxy` | `boolean` | `true` | run inference in a Web Worker (keep `true` unless debugging) | | `cache_models` | `boolean` | `true` | cache downloaded models locally | | `sdk_url` | `string` | Effects SDK CDN | base URL of a self-hosted SDK folder (must contain `models/`) | | `model_url` | `string` | — | custom segmentation model URL (rarely needed) | | `api_url` | `string` | Effects SDK | custom auth server URL (on-premises) | | `wasmPaths` | `{ wasm: string }` or `string` (directory) | auto | location of `ort-wasm-simd-threaded.asyncify.wasm`. See section 13 | | `models` | `{ facedetector?: string, colorcorrector?: string }` | built-in | custom model paths; empty string disables that feature | | `presets` | `{ quality?, balanced?, speed?, lightning? }` | built-in | custom model path per preset (landscape) | | `stats` | `boolean` | `false` | send anonymous usage stats | | `test_inference` | `boolean` | `false` | verify WebGPU inference consistency at startup | | `allow_software_renderer` | `boolean` | `false` | by default effects are skipped on software WebGL (code 1064). `true` runs them anyway (slow) | | `preload_auth` | `boolean` | `true` | authenticate while loading. `false` makes no licensing request until an effect first needs its model: models still download at load/`preload()`, but the handshake and session creation happen at first use, so that first use takes longer | Example — only background effects, self-hosted assets: ```js sdk.config({ effects: ['virtual_background'], sdk_url: 'https://cdn.example.com/effects-sdk/3.13.1/', wasmPaths: { wasm: 'https://cdn.example.com/effects-sdk/3.13.1/ort-wasm-simd-threaded.asyncify.wasm' }, }); ``` ------------------------------------------------------------------------------- ## 6. Effects API (call after `onReady`) Return value `boolean`: `true` = applied, `false` = effect not loaded / SDK not ready. ### 6.1 Virtual background & segmentation (effect: `virtual_background`) ```ts setBlur(power: number): boolean // 0..1. Enables background blur. Higher = stronger (and heavier) clearBlur(): boolean setBackground(source: BackgroundSource, options?: { type?: string }): boolean clearBackground(): boolean // back to the original camera background setBackgroundColor(color: number): void // 0xRRGGBB, used with setBackground('color') setBackgroundFitMode(mode: 'fill' | 'fit'): boolean // default 'fill' setSegmentationPreset(preset: 'quality'|'balanced'|'speed'|'lightning'): Promise getSegmentationPreset(): 'quality'|'balanced'|'speed'|'lightning' setLayoutMode(mode: 'segmentation'|'full'|'hide'|'transparent'): boolean setLayout(mode: 'center'|'left-bottom'|'right-bottom'): boolean // presenter position setCustomLayout({ xOffset?: number /* -1..1 */, yOffset?: number /* -1..1 */, size?: number /* 0..1 */ }): boolean enableFrameSkipping(): boolean // segment every 2nd frame: +FPS, slight motion trail disableFrameSkipping(): boolean // default setProvider({ model: 'segmentation', provider: 'wasm' }): Promise // switch WebGPU -> CPU at runtime; throws SdkError onBackgroundSuccess(cb?: () => void): void // background source loaded and applied ``` `BackgroundSource` = `string` (image/video/GIF URL, or the literal `'color'`) | `MediaStream` | `MediaStreamTrack` | `HTMLVideoElement` | `HTMLCanvasElement` | `OffscreenCanvas` | `ImageBitmap`. - Image/video URLs must be CORS-enabled (`Access-Control-Allow-Origin`). Video backgrounds autoplay and loop from the start. - For extension-less URLs pass the MIME type: `setBackground(url, { type: 'video/mp4' })`. - Solid color: `sdk.setBackgroundColor(0x00ff00); sdk.setBackground('color');` - Blur and background image are alternatives: `setBlur` blurs the real background; `setBackground` replaces it. Use `clearBlur()` / `clearBackground()` to switch off. - Screen share as background: `sdk.setBackground(screenStream)` + `setLayout('left-bottom')` for a presenter-over-slides layout. Layout modes: - `segmentation` — default; person over chosen background. - `full` — original frame, no segmentation. - `hide` — hide the person, only background visible. - `transparent` — person with transparent background (alpha). Use with `toCanvas()` or `processFrame()`; most video encoders/WebRTC drop alpha. Presets: `quality` > `balanced` (default) > `speed` > `lightning` (fastest). On WebGPU only `quality` and `balanced` are supported — other values return `false` with an info message. `setSegmentationPreset` is async; await it. ### 6.2 Beautification, portrait lighting, chroma key (part of `virtual_background`) ```ts enableBeautification(): boolean disableBeautification(): boolean setBeautificationLevel(level: number): boolean // 0..1 enablePortraitLighting(): boolean disablePortraitLighting(): boolean setPortraitLightingOptions({ LightStrength: number /*0..1*/, BgDarkStrength: number /*0..1*/ }): boolean // note PascalCase keys enableChromaKey(): boolean // classic green-screen keying instead of AI segmentation disableChromaKey(): boolean setChromaKeySettings({ keyColor?: number /*0xRRGGBB*/, threshold?: number, softness?: number, detint?: number }): boolean ``` ### 6.3 Smart Zoom / auto-framing (effect: `smart_zoom`) ```ts enableSmartZoom(): boolean disableSmartZoom(): boolean setFaceArea(value: number): boolean // 0.01..1, default 0.1 — target share of frame the face occupies setFaceDetectorAccuracy(value: number): boolean // 0.2..1, default 0.75 setSmartZoomSmoothing(value: number): boolean // 0.01..1, default 0.2 — higher = smoother setSmartZoomSensitivity(value: number): boolean // 0..1, default 0.05 — min change that triggers re-framing setSmartZoomPerod(ms: number): boolean // 0..1000, default 100 (method name is spelled "Perod") switchDrawFaceSquare(on: boolean): boolean // debug overlay switchDrawPreFaceSquare(on: boolean): boolean // debug overlay getDetectedFaces(): FaceCombiner[] // faces from the detector; works while smart zoom is enabled ``` To get face boxes without visible zoom: `enableSmartZoom(); setFaceArea(0.01);` then poll `getDetectedFaces()` — each item has `getRect() -> {x1, y1, width, height}`, `getCoord()`, `getCenter()`, `getID()` (pixel coordinates of the processed frame). ### 6.4 Low light (effect: `low_light`) ```ts enableLowLightEffect(): boolean disableLowLightEffect(): boolean setLowLightEffectPower(value: number): boolean // 0..1, default 1 setLowLightEffectConfig({ power?: number }): boolean onLowLightSuccess(cb?: () => void): void // one-shot: fires when the effect becomes active ``` ### 6.5 Color correction (effect: `color_correction`) ```ts enableColorCorrector(): boolean disableColorCorrector(): boolean setColorCorrectorConfig(config: Partial<{ autoMode: boolean, // auto white balance + contrast + exposure power: number, // 0..1 strength of auto correction whiteBalance: number, // 0..1 (0 disables); ignored in autoMode exposure: number, // -1..1; ignored in autoMode contrast: number, // -1..1; ignored in autoMode temperature: number, // -1..1 cool -> warm tint: number, // -1..1 vibrance: number, // -1..1 updatePeriod: number, // 0..5000 ms between auto analyses filterPart: number, // 0..1 dev/debug split view }>): boolean setColorCorrectorPower(value: number): boolean // 0..1 setColorCorrectorPeriod(ms: number): boolean // 0..5000 ``` ### 6.6 Color filter / LUT (always available) ```ts enableColorFilter(): boolean disableColorFilter(): boolean setColorFilterConfig(config: Partial<{ lut: string | File, // URL of a .cube LUT file, or a File power: number, // 0..1 strength part: number, // 0..1 split view (1 = full frame) capacity: number, // number of LUTs kept cached promise: { resolve: Function, reject: Function }, // settles when this LUT load finishes }>): boolean ``` ```js function applyLut(sdk, url) { return new Promise((resolve, reject) => { const ok = sdk.setColorFilterConfig({ lut: url, power: 1, promise: { resolve, reject } }); if (!ok) reject(new Error('color filter not available')); else sdk.enableColorFilter(); }); } ``` ### 6.7 Always-available simple effects ```ts enableSharpnessEffect(): boolean disableSharpnessEffect(): boolean setSharpnessEffectConfig({ power?: number /*0..1*/ }): boolean enableNoiseSuppression(): boolean // VIDEO noise reduction (not audio) disableNoiseSuppression(): boolean enableMirroring(): boolean // mirrors the OUTPUT stream (remote viewers see it mirrored) disableMirroring(): boolean ``` Tip: for a self-view "mirror" that remote participants don't see, mirror the local `