Open History to see the last commit
1import { useEffect, useRef, useState } from 'react'
2import { Loader2, Square, TriangleAlert } from 'lucide-react'
3import { generateLiveVideoFn } from '@/lib/server-functions'
4import { attachStream } from '@/lib/attach-stream'
5import { SeedImageField } from '@/components/SeedImageField'
6import {
7 byok,
8 callWithByok,
9 falByok,
10 reactorByok,
11 requestByokFromError,
12} from '@/lib/byok'
13import {
14 FAL_LIVE_VIDEO_APP,
15 LIVE_VIDEO_MODEL_LABELS,
16 LIVE_VIDEO_MODELS,
17 LIVE_VIDEO_PROMPTS,
18 isFalLiveVideoModel,
19 isLiveVideoModelId,
20 liveVideoProvider,
21 liveVideoResolutions,
22} from '@/lib/models'
23import {
24 liveAcceptsSeedImage,
25 watchReactorFailure,
26} from '@/lib/reactor-session'
27import type { Reactor } from '@reactor-team/js-sdk'
28import type {
29 LiveVideoModelId,
30 LiveVideoProvider,
31 LiveVideoResolution,
32} from '@/lib/models'
33
34type SessionStatus = 'idle' | 'connecting' | 'live' | 'error'
35
36type FalLiveSession = {
37 send: (message: Record<string, unknown>) => void
38 close: () => void | Promise<void>
39}
40
41type LiveHandle =
42 | { provider: 'reactor'; reactor: Reactor; model: LiveVideoModelId }
43 | { provider: 'fal'; session: FalLiveSession }
44
45async function startReactorLive(
46 reactor: Reactor,
47 model: LiveVideoModelId,
48 prompt: string,
49 resolution: LiveVideoResolution,
50 seedFile: File | null,
51): Promise<void> {
52 if (model === 'fast-h3') {
53 await reactor.sendCommand('enqueue', { prompt })
54 return
55 }
56 if (model === 'longlive-v2') {
57 await reactor.sendCommand('set_shot', { prompt })
58 await reactor.sendCommand('start', {})
59 return
60 }
61 if (model === 'helios') {
62 await reactor.sendCommand('set_sr_scale', {
63 sr_scale: resolution === '2k' || resolution === '4k' ? '4x' : '2x',
64 })
65 if (seedFile) {
66 const image = await reactor.uploadFile(seedFile)
67 await reactor.sendCommand('set_conditioning', { prompt, image })
68 } else {
69 await reactor.sendCommand('set_prompt', { prompt })
70 }
71 await reactor.sendCommand('start', {})
72 return
73 }
74 if (resolution === '1080p' || resolution === '2k' || resolution === '4k') {
75 await reactor.sendCommand('set_resolution', { resolution })
76 }
77 await reactor.sendCommand('set_prompt', { prompt })
78 await reactor.sendCommand('start', {})
79}
80
81async function steerReactorLive(
82 reactor: Reactor,
83 model: LiveVideoModelId,
84 prompt: string,
85): Promise<void> {
86 if (model === 'fast-h3') {
87 await reactor.sendCommand('enqueue', { prompt })
88 return
89 }
90 if (model === 'longlive-v2') {
91 await reactor.sendCommand('set_shot', { prompt })
92 return
93 }
94 await reactor.sendCommand('set_prompt', { prompt })
95}
96
97function errorMessage(error: unknown): string {
98 if (!(error instanceof Error)) return String(error)
99 const cause = error.cause
100 if (cause instanceof Error && cause.message.length > 0) {
101 return `${error.message} ${cause.message}`
102 }
103 return error.message
104}
105
106function readLivePayload(value: unknown): {
107 token: string
108 model: string
109 prompt: string
110 provider: LiveVideoProvider
111} {
112 if (typeof value !== 'object' || value === null) {
113 throw new Error('Live video payload is incomplete')
114 }
115 const token =
116 'token' in value && typeof value.token === 'string' ? value.token : ''
117 const model =
118 'model' in value && typeof value.model === 'string' ? value.model : ''
119 const prompt =
120 'prompt' in value && typeof value.prompt === 'string' ? value.prompt : ''
121 const provider =
122 'provider' in value &&
123 (value.provider === 'reactor' || value.provider === 'fal')
124 ? value.provider
125 : null
126 if (
127 token.length === 0 ||
128 model.length === 0 ||
129 prompt.length === 0 ||
130 provider === null
131 ) {
132 throw new Error('Live video payload is incomplete')
133 }
134 return { token, model, prompt, provider }
135}
136
137function defaultResolution(provider: LiveVideoProvider): LiveVideoResolution {
138 return provider === 'fal' ? '768p' : '1080p'
139}
140
141async function openFalSession(args: {
142 model: string
143 prompt: string
144 resolution: LiveVideoResolution
145 onMedia: (stream: MediaStream) => void
146 onError: (error: unknown) => void
147}): Promise<FalLiveSession> {
148 const { createFalClient } = await import('@fal-ai/client')
149 const { wma } = await import('@fal-ai/client/realtime')
150 const fal = createFalClient({
151 proxyUrl: '/api/fal/proxy',
152 fetch: (input, init) => {
153 const headers = new Headers(init?.headers)
154 for (const [name, value] of Object.entries(byok.headers(falByok.id))) {
155 headers.set(name, value)
156 }
157 return fetch(input, { ...init, headers })
158 },
159 })
160 const wmaApp = isFalLiveVideoModel(args.model)
161 ? FAL_LIVE_VIDEO_APP[args.model]
162 : args.model
163 const session = fal.realtime.open(wma(wmaApp), {
164 receive: ['video', 'audio'],
165 onMedia: args.onMedia,
166 onError: args.onError,
167 onData: (raw) => {
168 let parsed: unknown
169 try {
170 parsed = JSON.parse(String(raw))
171 } catch {
172 return
173 }
174 if (
175 typeof parsed === 'object' &&
176 parsed !== null &&
177 'type' in parsed &&
178 parsed.type === 'error' &&
179 'error' in parsed &&
180 typeof parsed.error === 'string'
181 ) {
182 args.onError(new Error(parsed.error))
183 }
184 },
185 onState: (state) => {
186 if (state === 'failed') args.onError(new Error('Live session failed'))
187 },
188 })
189 session.send({
190 type: 'configure',
191 prompt: args.prompt,
192 prompt_version: 1,
193 protocol_version: 1,
194 ...(args.resolution === '480p' || args.resolution === '768p'
195 ? { resolution: args.resolution }
196 : {}),
197 })
198 await session.ready
199 return session
200}
201
202export default function LiveVideoStudio() {
203 const [prompt, setPrompt] = useState<string>(LIVE_VIDEO_PROMPTS[0] ?? '')
204 const [steerPrompt, setSteerPrompt] = useState('')
205 const [model, setModel] = useState<LiveVideoModelId>('helios')
206 const [resolution, setResolution] = useState<LiveVideoResolution>('1080p')
207 const [seedFile, setSeedFile] = useState<File | null>(null)
208 const [status, setStatus] = useState<SessionStatus>('idle')
209 const [error, setError] = useState<string | null>(null)
210 const [playing, setPlaying] = useState(false)
211 const videoRef = useRef<HTMLVideoElement>(null)
212 const handleRef = useRef<LiveHandle | null>(null)
213 const detachStreamRef = useRef<(() => void) | null>(null)
214 const unwatchRef = useRef<(() => void) | null>(null)
215 const falPromptVersionRef = useRef(1)
216 const statusRef = useRef<SessionStatus>('idle')
217 statusRef.current = status
218
219 const provider = liveVideoProvider(model)
220 const resolutions = liveVideoResolutions(provider)
221 const keyProvider = provider === 'fal' ? falByok : reactorByok
222 const showSeedField = liveAcceptsSeedImage(model)
223
224 async function teardown() {
225 unwatchRef.current?.()
226 unwatchRef.current = null
227 const handle = handleRef.current
228 handleRef.current = null
229 detachStreamRef.current?.()
230 detachStreamRef.current = null
231 if (handle?.provider === 'reactor') {
232 try {
233 await handle.reactor.disconnect()
234 } catch {
235 // Disconnect can fail if the session already ended.
236 }
237 } else if (handle?.provider === 'fal') {
238 try {
239 handle.session.send({ type: 'stop' })
240 await handle.session.close()
241 } catch {
242 // Close can fail if the session already ended.
243 }
244 }
245 const video = videoRef.current
246 if (video) {
247 video.srcObject = null
248 }
249 }
250
251 async function stop() {
252 await teardown()
253 setPlaying(false)
254 setStatus('idle')
255 }
256
257 useEffect(() => {
258 return () => {
259 void teardown()
260 }
261 }, [])
262
263 async function start() {
264 setError(null)
265 setPlaying(false)
266 setStatus('connecting')
267 try {
268 await byok.prepare(keyProvider.id)
269 const live = readLivePayload(
270 await callWithByok(
271 generateLiveVideoFn({
272 data: { prompt, model, resolution },
273 headers: byok.headers(keyProvider.id),
274 }),
275 ),
276 )
277 const video = videoRef.current
278 if (!video) throw new Error('Video element is missing')
279
280 if (live.provider === 'fal') {
281 falPromptVersionRef.current = 1
282 const session = await openFalSession({
283 model: live.model,
284 prompt: live.prompt,
285 resolution,
286 onMedia: (stream) => {
287 detachStreamRef.current?.()
288 detachStreamRef.current = attachStream(
289 video,
290 stream,
291 (playError) => {
292 setError(errorMessage(playError))
293 },
294 )
295 },
296 onError: (openError) => {
297 setError(errorMessage(openError))
298 setStatus('error')
299 },
300 })
301 handleRef.current = { provider: 'fal', session }
302 } else {
303 const { Reactor: ReactorClient } = await import('@reactor-team/js-sdk')
304 const reactor = new ReactorClient({
305 modelName: live.model,
306 })
307 handleRef.current = { provider: 'reactor', reactor, model }
308
309 let rejectStart: ((error: Error) => void) | undefined
310 const startFailed = new Promise<never>((_, reject) => {
311 rejectStart = reject
312 })
313 unwatchRef.current = watchReactorFailure(reactor, (message) => {
314 setError(message)
315 rejectStart?.(new Error(message))
316 if (statusRef.current === 'live') setStatus('error')
317 })
318 reactor.on('trackReceived', (name, _track, stream) => {
319 if (name !== 'main_video') return
320 detachStreamRef.current?.()
321 detachStreamRef.current = attachStream(video, stream, (playError) => {
322 setError(errorMessage(playError))
323 })
324 })
325
326 await reactor.connect(live.token)
327 try {
328 await Promise.race([
329 startReactorLive(reactor, model, live.prompt, resolution, seedFile),
330 startFailed,
331 ])
332 } finally {
333 rejectStart = undefined
334 }
335 }
336
337 setSteerPrompt('')
338 setStatus('live')
339 } catch (caught) {
340 await stop()
341 requestByokFromError(caught)
342 setError(errorMessage(caught))
343 setStatus('error')
344 }
345 }
346
347 async function steer() {
348 const handle = handleRef.current
349 const next = steerPrompt.trim()
350 if (!handle || next.length === 0) return
351 setError(null)
352 try {
353 if (handle.provider === 'fal') {
354 falPromptVersionRef.current += 1
355 handle.session.send({
356 type: 'prompt',
357 prompt: next,
358 prompt_version: falPromptVersionRef.current,
359 })
360 } else {
361 await steerReactorLive(handle.reactor, handle.model, next)
362 }
363 setPrompt(next)
364 setSteerPrompt('')
365 } catch (caught) {
366 setError(errorMessage(caught))
367 }
368 }
369
370 const isLive = status === 'live'
371 const isBusy = status === 'connecting'
372
373 return (
374 <div className="space-y-3">
375 <p className="text-sm text-gray-400">
376 Live video. Paste a key in the header dialog, or set{' '}
377 <code className="font-mono text-gray-300">
378 {provider === 'fal' ? 'FAL_KEY' : 'REACTOR_API_KEY'}
379 </code>{' '}
380 on the server. Then start a session and type under the view to steer.
381 </p>
382
383 <div className="overflow-hidden rounded-xl border border-gray-700 bg-black">
384 <video
385 ref={videoRef}
386 className="aspect-video w-full bg-black"
387 autoPlay
388 playsInline
389 muted
390 onPlaying={() => setPlaying(true)}
391 />
392 {status === 'idle' || status === 'error' ? (
393 <p className="px-4 py-3 text-sm text-gray-400">
394 The live stream appears here after you start a session.
395 </p>
396 ) : null}
397 {status === 'connecting' || (status === 'live' && !playing) ? (
398 <p className="px-4 py-3 text-sm text-gray-400">
399 {status === 'connecting'
400 ? 'Connecting to the video model…'
401 : 'Waiting for the first frame…'}
402 </p>
403 ) : null}
404 </div>
405
406 <form
407 className="space-y-2"
408 onSubmit={(event) => {
409 event.preventDefault()
410 if (isLive) {
411 void steer()
412 return
413 }
414 if (!isBusy && prompt.trim().length > 0) void start()
415 }}
416 >
417 <label className="block">
418 <span className="sr-only">{isLive ? 'Steer prompt' : 'Prompt'}</span>
419 <textarea
420 value={isLive ? steerPrompt : prompt}
421 onChange={(event) => {
422 const next = event.target.value
423 if (isLive) setSteerPrompt(next)
424 else setPrompt(next)
425 }}
426 disabled={isBusy}
427 onKeyDown={(event) => {
428 if (event.key !== 'Enter' || event.shiftKey) return
429 event.preventDefault()
430 event.currentTarget.form?.requestSubmit()
431 }}
432 rows={2}
433 placeholder={
434 isLive
435 ? 'Steer the scene. The picture morphs at the next chunk.'
436 : 'Describe the video to generate…'
437 }
438 className="w-full rounded-lg border border-gray-700 bg-gray-900 px-3 py-2 text-white placeholder-gray-500 focus:border-purple-500 focus:outline-none disabled:opacity-50"
439 />
440 </label>
441
442 {isLive ? null : (
443 <div className="flex flex-wrap gap-1.5">
444 {LIVE_VIDEO_PROMPTS.map((example) => (
445 <button
446 key={example}
447 type="button"
448 title={example}
449 onClick={() => setPrompt(example)}
450 disabled={isBusy}
451 className={`rounded-full border px-2.5 py-1 text-xs transition-colors ${
452 prompt === example
453 ? 'border-blue-500 bg-blue-600 text-white'
454 : 'border-gray-700 bg-gray-900 text-gray-400 hover:bg-gray-800 hover:text-gray-200'
455 } disabled:cursor-not-allowed disabled:opacity-50`}
456 >
457 {example.length > 36 ? `${example.slice(0, 36)}…` : example}
458 </button>
459 ))}
460 </div>
461 )}
462
463 <div className="flex flex-wrap items-center gap-2">
464 {isLive ? (
465 <>
466 <button
467 type="submit"
468 disabled={steerPrompt.trim().length === 0}
469 className="rounded-lg bg-blue-600 px-4 py-2 font-medium text-white hover:bg-blue-500 disabled:cursor-not-allowed disabled:opacity-50"
470 >
471 Send
472 </button>
473 <button
474 type="button"
475 onClick={() => void stop()}
476 className="inline-flex items-center gap-2 rounded-lg bg-red-600 px-4 py-2 font-medium text-white hover:bg-red-500"
477 >
478 <Square className="h-4 w-4" />
479 Stop
480 </button>
481 </>
482 ) : (
483 <button
484 type="submit"
485 disabled={isBusy || prompt.trim().length === 0}
486 className="inline-flex items-center gap-2 rounded-lg bg-blue-600 px-4 py-2 font-medium text-white hover:bg-blue-500 disabled:cursor-not-allowed disabled:opacity-50"
487 >
488 {isBusy ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
489 {isBusy ? 'Starting…' : 'Start live'}
490 </button>
491 )}
492
493 <label className="flex items-center gap-2 text-sm text-gray-400">
494 <span className="sr-only">Model</span>
495 <select
496 value={model}
497 onChange={(event) => {
498 const next = event.target.value
499 if (!isLiveVideoModelId(next)) return
500 setModel(next)
501 const nextProvider = liveVideoProvider(next)
502 const nextResolutions = liveVideoResolutions(nextProvider)
503 if (
504 !nextResolutions.includes(
505 resolution as (typeof nextResolutions)[number],
506 )
507 ) {
508 setResolution(defaultResolution(nextProvider))
509 }
510 }}
511 disabled={isLive || isBusy}
512 className="rounded-lg border border-gray-700 bg-gray-900 px-2 py-2 text-sm text-white focus:border-blue-500 focus:outline-none disabled:opacity-50"
513 >
514 {LIVE_VIDEO_MODELS.map((entry) => (
515 <option key={entry.id} value={entry.id}>
516 {LIVE_VIDEO_MODEL_LABELS[entry.id]}
517 </option>
518 ))}
519 </select>
520 </label>
521
522 <label className="flex items-center gap-2 text-sm text-gray-400">
523 <span className="sr-only">Resolution</span>
524 <select
525 value={resolution}
526 onChange={(event) => {
527 const next = event.target.value
528 if (
529 resolutions.includes(next as (typeof resolutions)[number])
530 ) {
531 setResolution(next as LiveVideoResolution)
532 }
533 }}
534 disabled={isLive || isBusy}
535 className="rounded-lg border border-gray-700 bg-gray-900 px-2 py-2 text-sm text-white focus:border-blue-500 focus:outline-none disabled:opacity-50"
536 >
537 {resolutions.map((value) => (
538 <option key={value} value={value}>
539 {value}
540 </option>
541 ))}
542 </select>
543 </label>
544
545 {isLive || !showSeedField ? null : (
546 <SeedImageField
547 files={seedFile ? [seedFile] : []}
548 onChange={(files) => setSeedFile(files[0] ?? null)}
549 required={false}
550 disabled={isBusy}
551 />
552 )}
553 </div>
554 </form>
555
556 {error ? (
557 <p className="flex items-start gap-2 text-sm text-red-400">
558 <TriangleAlert className="mt-0.5 h-4 w-4 shrink-0" />
559 {error}
560 </p>
561 ) : null}
562 </div>
563 )
564}