The Realtime API enables you to transform live video streams with minimal latency using WebRTC. Perfect for building Android camera effects, video restyling apps, AR experiences, and interactive live streaming.Documentation Index
Fetch the complete documentation index at: https://docs.platform.decart.ai/llms.txt
Use this file to discover all available pages before exploring further.
Quick Start
Client-Side Authentication
For production Android apps, use ephemeral keys instead of embedding your permanent API key in the APK. Ephemeral keys are short-lived tokens safe to include in client applications.Learn more about client tokens and why they’re important for security.
Fetching an Ephemeral Key
Your app should fetch an ephemeral key from your backend server before connecting:Connecting with an Ephemeral Key
Connecting
Initializing WebRTC
Before connecting, initialize the WebRTC peer connection factory. This sets up video encoding/decoding with hardware acceleration:Creating a Camera Track
UsecreateCameraVideoTrack for a one-call pipeline. Pass the model’s dimensions:
CameraVideoTrack exposes track, source, capturer, and surfaceTextureHelper; stop() releases all of them in order.
Manual capture pipeline
If you already manage your own camera, use the lower-level helpers and attachMirrorVideoProcessor to mirror the input:
Front-camera mirroring
Pre-flipping the selfie input keeps server-baked pixels (watermarks, overlays) correctly oriented when you render the remote stream as-is. Do not callsetMirror(true) on the remote SurfaceViewRenderer — that would re-flip the baked pixels.
MirrorMode values:
OFF— never mirror.ON— always mirror.AUTO— mirror whenfacing == FacingMode.FRONT.
Establishing Connection
Connect to the Realtime API with your camera track:localVideoTrack(optional) - WebRTCVideoTrackfrom camera (null for Live Avatar or subscribe mode)localAudioTrack(optional) - WebRTCAudioTrackfrom microphoneoptions.model(required) - Realtime model fromRealtimeModelsoptions.onRemoteVideoTrack(required) - Callback that receives the transformed video trackoptions.onRemoteAudioTrack(optional) - Callback for remote audio trackoptions.resolution(optional) -Resolution.P720orResolution.P1080. Omit for the server’s 720p default; passResolution.P1080to request a 1080p remote stream from supported models.options.initialPrompt(optional) - Starting prompttext- Style descriptionenhance- Whether to auto-enhance the prompt (default:true)
options.initialImage(optional) - Base64-encoded reference image
Managing Prompts
Change the transformation style dynamically without reconnecting:prompt: String(required) - Text description of desired styleenhance: Boolean(optional) - Whether to enhance the prompt (default:true)
Prompt enhancement uses Decart’s AI to expand simple prompts for better results. Disable it if you want full control over the exact prompt.
Reference Images
Send a reference image (and optionally a prompt) for image-guided models:imageBase64: String?(required) - Base64-encoded image, ornullto clearprompt: String?(optional) - Text prompt to send with the imageenhance: Boolean?(optional) - Whether to enhance the prompttimeout: Long(optional) - Timeout in milliseconds for the server ack (default: 30,000)
Connection State
Monitor and react to connection state changes using Kotlin Flow:DISCONNECTED- Not connected (initial state, afterdisconnect(), or after reconnect failure)CONNECTING- Initial connection in progressCONNECTED- Connected and ready to send promptsGENERATING- Actively generating transformed video (sticky until disconnected)RECONNECTING- Connection lost unexpectedly; the SDK is automatically retrying
The SDK automatically reconnects when an unexpected disconnection occurs (e.g., network interruption). During auto-reconnect, the state transitions to
RECONNECTING while the SDK retries. If all retries fail, the state moves to DISCONNECTED and an error is emitted.Error Handling
Handle errors using theerrors SharedFlow:
INVALID_API_KEY- API key is invalid or missingWEBRTC_TIMEOUT_ERROR- Connection timed outWEBRTC_ICE_ERROR- ICE negotiation failedWEBRTC_WEBSOCKET_ERROR- WebSocket connection errorWEBRTC_SERVER_ERROR- Server-side errorWEBRTC_SIGNALING_ERROR- Signaling protocol error
WebRTC Stats
Monitor real-time performance metrics:video- Inbound video: FPS, resolution, bitrate, packets lost, jitter, freeze countaudio- Inbound audio: bitrate, packets lost, jitteroutboundVideo- Outbound video: FPS, resolution, bitrate, quality limitation reasonconnection- Round-trip time, available outgoing bitrate
Generation Ticks
Track session duration for billing and usage display:Diagnostics
Monitor detailed connection diagnostics for debugging:Session Management
Access the current session ID for logging, analytics, or debugging:Cleanup
Always disconnect and release resources when done:Complete Jetpack Compose Example
A full Jetpack Compose application with camera capture, video transformation, and prompt input:Best Practices
Use model properties for camera constraints
Use model properties for camera constraints
Always use the model’s
fps, width, and height properties when configuring camera capture to ensure optimal performance.Enable prompt enrichment
Enable prompt enrichment
For best results, keep
enhance = true (default) to let Decart’s AI enhance your prompts. Only disable it if you need exact prompt control.Collect flows in lifecycle-aware scopes
Collect flows in lifecycle-aware scopes
Always collect
connectionState, errors, and other flows in lifecycleScope or viewModelScope to avoid leaks and ensure proper cancellation.Clean up properly
Clean up properly
Always call
disconnect() then release() when done. Stop camera capture separately. Failing to release can leak native WebRTC resources.Test on real devices
Test on real devices
Always test camera features on real Android devices. The emulator does not support WebRTC camera access.
Request permissions properly
Request permissions properly
Request
CAMERA and RECORD_AUDIO permissions at runtime before attempting to connect. Handle permission denials gracefully in your UI.API Reference
realtime.initialize(eglBase?)
Initialize the WebRTC peer connection factory. Optional - called automatically by connect() if not called explicitly.
Parameters:
eglBase: EglBase?(optional) - EGL context for hardware-accelerated video. A default is created if omitted.
realtime.connect(localVideoTrack, localAudioTrack, options)
Connect to a realtime model and start streaming. Suspend function.
Parameters:
localVideoTrack: VideoTrack?- Camera video tracklocalAudioTrack: AudioTrack?- Microphone audio track (null to omit)options: ConnectOptions- Connection configurationmodel: RealtimeModel- Model fromRealtimeModelsonRemoteVideoTrack: (VideoTrack) -> Unit- Callback for transformed videoonRemoteAudioTrack: ((AudioTrack) -> Unit)?- Callback for remote audioinitialPrompt: InitialPrompt?- Starting prompt (text + enhance)initialImage: String?- Base64-encoded reference image
IllegalStateException if factory initialization fails
realtime.setPrompt(prompt, enhance)
Change the transformation style.
Parameters:
prompt: String- Text description of desired styleenhance: Boolean- Whether to enhance the prompt (default:true)
IllegalStateException if not connected
realtime.setImage(imageBase64, prompt, enhance, timeout)
Send a reference image. Suspend function.
Parameters:
imageBase64: String?- Base64-encoded image, or null to clearprompt: String?- Optional text promptenhance: Boolean?- Whether to enhance the prompttimeout: Long- Ack timeout in ms (default: 30,000)
IllegalStateException if not connected
realtime.disconnect()
End the current session and clean up WebRTC resources.
realtime.release()
Release all resources including the peer connection factory and EGL context. Call when done with the client entirely.
realtime.isConnected()
Returns: Boolean - Whether currently connected.
realtime.isPlayAudioAvailable()
Returns: Boolean - Whether playAudio() is available (Live Avatar mode).
realtime.getEglBaseContext()
Returns: EglBase.Context? - EGL context for initializing SurfaceViewRenderer.
realtime.createVideoSource(isScreencast)
Returns: VideoSource? - A new video source for camera capture.
realtime.createVideoTrack(id, source)
Returns: VideoTrack? - A new video track from a video source.
realtime.createCameraVideoTrack(facing, mirror, width, height, fps, trackId)
One-call camera setup. Returns a CameraVideoTrack with track, source, capturer, surfaceTextureHelper, and stop().
Parameters:
facing: FacingMode-FRONT(default) orBACK.mirror: MirrorMode-AUTO(default),OFF, orON.width: Int,height: Int,fps: Int- capture parameters (defaults:1280,720,30).trackId: String- track id (default:"local_video").
initialize() and android.permission.CAMERA. Throws IllegalStateException if no camera is available.
MirrorVideoProcessor
Public VideoProcessor that horizontally flips frames. Attach via source.setVideoProcessor(MirrorVideoProcessor()) when you manage your own capture pipeline.
Observable State
| Property | Type | Description |
|---|---|---|
connectionState | StateFlow<ConnectionState> | Current connection state |
errors | SharedFlow<DecartError> | Error events |
stats | SharedFlow<WebRTCStats> | WebRTC performance stats |
generationTicks | SharedFlow<GenerationTickMessage> | Billing/usage tick events |
diagnostics | SharedFlow<DiagnosticEvent> | Connection diagnostic events |
sessionId | String? | Current session ID |
Next Steps
Queue API
Generate and transform videos with batch processing and Flow-based progress
SDK Overview
Installation, setup, and Android SDK fundamentals