Paid, hosted product at menivor.com, now retired as a company project. Fresh squashed history of the cleaned working tree (secret-scanned, no .env, no customer data, no outreach logs). Built on MoneyPrinterTurbo (MIT, harry0703) — see NOTICE.
24 KiB
AI B-roll Studio — Architecture Plan
Historical design record. This proposal predates the implemented
app/domains/brollpackage and canonical/api/v1/generation/broll/*contract. Current changes followPLATFORM_ARCHITECTURE_SPEC.mdandREPOSITORY_LAYOUT_SPEC.md; old paths below are retained only to explain the original migration.
Engineering plan for adding a Higgsfield-style AI B-roll studio (text/image → AI-generated motion clips via ComfyUI/Wan GPU workers) as a new footage source in ReelForge. Companion to RESEARCH_HIGGSFIELD_OSS.md (the what to combine); this doc is the where it bolts on and in what order.
Status: PROPOSED · No code yet · Design against real seams (all paths verified against the tree).
1. Goal & scope
Let a creator generate short AI motion clips (not stock footage) from a text prompt or a
reference image, and use them as B-roll in a reel — or browse/regenerate them in a standalone
"studio" gallery. The generation backend is self-hosted ComfyUI workflows (Wan 2.2 t2v/i2v,
camera LoRAs, VACE) deployed as serverless RunPod endpoints via comfyui-deploy.
In scope
- A pluggable AI-video provider (
comfyui/wan) that submits a workflow, polls, and re-hosts the result to R2. - A service seam so
broll.suggest_broll(source="ai", ...)produces AI clips using the existing{broll_key,...}contract. - A preset library (shareable ComfyUI workflow configs = "motion presets" — the Higgsfield UX primitive).
- API + web/mobile surfaces to request generations, poll them, and attach chosen clips to a reel.
Explicitly out of scope (v1)
- Training/fine-tuning LoRAs (consume prebaked ones only).
- Full node-graph editor in-app (presets are curated server-side; users pick + fill a form — the ViewComfy model).
- Replacing the avatar pipeline. This is additive footage, not a new core DAG.
Deferred decision (flagged, not blocking): whether AI clips remain intro/outro stingers (today's B-roll model) or become full-timeline overlays. See §11-D1. v1 ships stingers (zero compose changes); full-timeline is a fast-follow.
2. Where it slots in — the confirmed seams
The recon confirmed ReelForge deliberately does not source stock footage in its core DAG
(script → tts → {avatar ∥ captions} → compose → upload). B-roll is an opt-in, best-effort
overlay. That gives us three clean, already-audited seams — we add a backend, we don't rewire the pipeline.
| # | Seam | File | What we reuse |
|---|---|---|---|
| A | Provider registry | app/services/avatar/base.py |
Protocol + AVATAR_PROVIDERS + register_*/get_* pattern → copy as broll_gen/base.py |
| B | RunPod worker client | app/services/avatar/latentsync_runpod.py |
run()→wait()→_materialize_output()→_rehost() → copy as comfyui_runpod.py |
| C | B-roll service | app/services/broll.py |
suggest_broll(source=...) switch + jobs/<job_id>/broll/<uuid>.mp4 R2 key + best-effort contract |
| D | Render consumption | reelforge._apply_broll → compose_ffmpeg.concat_with_broll |
already consumes a broll_key; no change for stingers |
| E | Config | app/config/config.py (~L540/L621) |
env-override precedence; config.runpod already wired — add config.comfyui sibling |
| F | Frontend attach point | web/lib/api.ts suggestBroll() + BrollClip type |
already call POST /jobs/{id}/broll/suggest — extend, don't invent |
Key insight: latentsync_runpod.py is already a serverless GPU-worker client with submit/poll/
materialize/re-host/retry/duration-validation baked in. comfyui-deploy exposes the same RunPod
/run + /status/{id} REST shape. So the worker client is a copy-and-adapt, not a from-scratch build.
3. Topology
┌─────────────┐ POST /jobs/{id}/broll/generate ┌────────────────────────┐
│ web / mobile│ ─────────────────────────────────────────▶│ FastAPI │
│ (studio UI)│ GET /broll/generations/{gid} (poll) │ controllers/v1/ │
└─────────────┘◀───────────────────────────────────────── │ broll_studio.py │
└───────────┬────────────┘
│ enqueue (render queue)
▼
┌──────────────────────────────┐
│ Celery worker (queue=render) │
│ workers/tasks.py │
│ generate_broll_clip_task │
└───────────┬──────────────────┘
│ service call
▼
┌────────────────────────────────────────────┐
│ services/broll_gen/ (provider registry) │
│ comfyui_runpod.ComfyUIProvider.generate() │
└───────────┬─────────────────────┬───────────┘
POST /run │ poll /status/{id} │ materialize+re-host
▼ ▼
┌──────────────────────────────┐ ┌────────────────┐
│ RunPod Serverless (GPU) │ │ Cloudflare R2 │
│ comfyui-deploy → ComfyUI │ │ jobs/<id>/broll│
│ workflow: Wan2.2 + LoRA/VACE │ │ /<uuid>.mp4 │
└──────────────────────────────┘ └────────────────┘
Generation is async job → poll, matching the existing avatar/RunPod flow. GPU work rides the
existing render queue (already carved out for avatar/compose in celery_app.py), so a
separate/autoscaled worker pool services it without touching the light API workers.
4. Component design
4.1 Provider layer — app/services/broll_gen/ (new, mirrors avatar/)
-
base.py—BrollGenProvider@runtime_checkable Protocol, copied fromTalkingHeadProvider:class BrollGenProvider(Protocol): name: str def is_enabled(self) -> bool: ... def list_workflows(self) -> list[dict]: ... # available motion presets (may be static) def generate_clip( self, prompt: str, *, mode: str = "t2v", # "t2v" | "i2v" image_url: str | None = None, # required for i2v width: int = 1080, height: int = 1920, duration_s: float = 5.0, workflow_id: str | None = None, # comfyui-deploy workflow / preset id seed: int | None = None, extra_inputs: dict | None = None, # LoRA weights, motion strength, camera path… timeout_s: float = 1800.0, ) -> dict | None: # {'clip_path','duration','provider_job_id', +'clip_key'/'clip_url'} ...Plus
BROLL_GEN_PROVIDERS,register_broll_provider,get_broll_provider(id), lazy default import. Same graceful-degradation contract: never raise on external I/O; returnNone. -
comfyui_runpod.py—ComfyUIProvider+ComfyUIClient, copied fromlatentsync_runpod.py.run()/wait()/status constants/_materialize_output()/_download_to_temp()/_decode_b64_to_temp()/_render_with_retry()transfer verbatim (RunPod REST shape is identical via comfyui-deploy). Adaptations:worker_inputbecomes{workflow_id, prompt, mode, image_url, width, height, num_frames, fps, seed, ...extra_inputs}instead of{audio_url, avatar_image}._rehost()targetsjobs/<job_id>/broll/<uuid>.mp4(notavatars/)._validate_duration()kept but relaxed — video length isnum_frames/fps, not audio-locked; warn-only.is_enabled()=bool(api_key and endpoint_id).
-
Provider variants (later):
wan_local.py(self-hosted ComfyUI on your own GPU box for dev),fal_broll.py/replicate_broll.py(managed API fallback). All satisfy the same Protocol → hot-swappable via config, exactly like heygen↔latentsync.
4.2 Service layer — extend app/services/broll.py
Add a source="ai" branch (keep pexels/pixabay/coverr untouched):
def suggest_broll(job_id, subject, script="", source="pexels", amount=6, aspect=...):
if source == "ai":
return _suggest_broll_ai(job_id, subject, script, amount, aspect) # new private fn
... # existing stock path unchanged
_suggest_broll_ai:
- Derive prompts from
subject/scriptvia existing_derive_terms(reuse — LLM term gen already there). - For each prompt call
get_broll_provider().generate_clip(...)(or enqueue N generation jobs — see §5). - Provider already re-hosts to R2; return the same record shape
{"broll_key","duration","source":"ai","term"}. - Best-effort preserved — wrap in try/except, return
[]on failure. A B-roll failure never fails a job.
get_broll_local() and _assert_owned_r2_key need no change — AI clips use the same jobs/<id>/broll/ prefix, so the BOLA ownership guard covers them for free.
4.3 Render consumption — compose
- v1 (stingers): zero change. Chosen
broll_key→ReelForgeParams.broll_intro_key/outro_key→reelforge._apply_broll→compose_ffmpeg.concat_with_broll. Already works. - v2 (full-timeline overlays): new insertion path —
_apply_broll_overlays(main, [(t_start, broll_key), ...])incompose_ffmpeg.py, driven by a newReelForgeParams.broll_timeline: list(JSON inJob.params, no migration). This is the only place that needs real FFmpeg work; deferred to fast-follow (§11-D1).
4.4 Task layer — app/workers/tasks.py
A generation can take 30–120s of GPU time → must be a Celery task, not inline in the request.
- New task
generate_broll_clip_task(self, ctx: dict) -> dictonqueue="render",base=StageTask, generoussoft_time_limit/time_limit(mirror avatar's 1800/1860). Wrapsbroll_genprovider call, reports progress via_safe_set_progress, records cost viatelemetry/cost, persists anAssetrow. - Studio (standalone) generations are independent jobs (
Job.kind="broll_gen") — they reuse the Job/Asset/progress/credit machinery but run a single-task "chain of one," not the full DAG.
4.5 API layer — app/controllers/v1/broll_studio.py (new controller)
Follow the new_router() + guarded-import + get_response envelope pattern (template: studio.py).
| Route | Purpose |
|---|---|
GET /broll/presets |
list motion presets (curated workflow configs) |
POST /broll/generate |
start N AI clip generations (prompt/image/preset) → returns generation ids |
GET /broll/generations/{gid} |
poll status/result of a generation |
POST /jobs/{id}/broll/generate |
job-scoped variant (attaches directly to a reel) |
(reuse) POST /jobs/{id}/broll/suggest |
extend existing route to accept source:"ai" |
- Auth/rate-limit reuse
jobs.pyhelpers (_resolve_user, a dedicatedbroll_gen_rate_limitlike the existing 20/hr B-roll limit — GPU is expensive, keep it tight). - Request/response DTOs added to
app/models/schema.py(BrollGenerateRequest,BrollGenerationResponse,BrollPresetResponse), alongside existingBrollSuggestRequest/Response. - Register in
app/router.py:root_api_router.include_router(broll_studio.router).
4.6 Config — app/config/config.py
Add a config.comfyui section next to config.runpod, same env-override precedence (env > toml > ""):
COMFYUI_ENDPOINT_ID # comfyui-deploy RunPod endpoint id
COMFYUI_API_KEY # RunPod bearer key
COMFYUI_BASE_URL # optional (default https://api.runpod.ai/v2)
COMFYUI_TIMEOUT_S # default 1800
BROLL_GEN_PROVIDER # "comfyui" (default) | "wan_local" | "fal" — provider switch
BROLL_GEN_ENABLED # feature flag (default off)
Provider reads via getattr(config, "comfyui", {}) — the same defensive pattern as latentsync._runpod_config(), so the module imports cleanly before wiring lands. Add stanzas to config.example.toml + .env.full.example + docs/reelforge/CONFIG.md.
4.7 Frontend
- web (
web/lib/api.ts+types.ts): extend existingsuggestBrollto passsource; addgenerateBroll(),getBrollGeneration(),listBrollPresets(); addBrollGeneration/BrollPresettypes. Newweb/lib/use-broll-studio.tshook (polling at existingPOLL_INTERVAL_MS = 3000). A studio page underweb/app/broll/with preset picker + prompt box + gallery (ViewComfy-style form-over-nodes UX). - mobile (
mobile/lib/api.ts): mirror the same calls; reusemobile/lib/pick-*.tsfor i2v reference-image upload via the existingpresignflow.
5. Sync vs async execution — recommendation
Recommend async job + poll (not blocking request), because:
- ComfyUI/Wan clips are 30–120s of GPU; a blocking HTTP request would tie up API workers and hit gateway timeouts.
- The whole codebase is already poll-shaped (
POLL_INTERVAL_MS,getJob, avatar RunPod flow).
POST /broll/generate creates one Job(kind="broll_gen") per requested clip (fan-out like the existing
variants batch), enqueues generate_broll_clip_task on render, returns ids immediately; UI polls
getBrollGeneration. Chosen clips' broll_keys are then passed into createJob/reel params.
6. Data model
Minimize migrations — lean on existing JSON columns.
| Need | Approach | Migration? |
|---|---|---|
| Persist an AI clip + provenance (prompt/model/seed/workflow) | Reuse Asset with kind="broll" + meta={prompt,model,seed,workflow_id,mode} (Asset.meta:JSON + duration_s already exist) |
No |
| Track a generation's lifecycle/credits | Reuse Job with kind="broll_gen" (state/progress/params/credit machinery already there) |
No (new kind string only) |
| Per-reel AI-clip settings | Ride in Job.params JSON (precedent: broll_intro_key, auto_zoom) |
No |
| Motion presets (curated workflow configs) | New BrollPreset table, mirror AvatarPreset: user_id?, provider, workflow_id, name, thumbnail_url, default_params:JSON, is_public, is_active |
Yes (1 table) |
| Full-timeline overlays (v2) | Job.params.broll_timeline: list[{t_start, broll_key, duration}] |
No |
So v1 is one Alembic migration (broll_presets), following the 20260813_... naming already in migrations/versions/. Everything else is additive JSON — the same discipline the codebase already uses for B-roll keys.
Credits/metering: AI generation is far costlier than a stock fetch → add a broll_gen cost entry to
the credit/pricing config and debit in the controller (same CreditRepository.debit transaction pattern
as jobs.create_job), refund on failure via existing refund.
7. GPU / worker topology
- Serving: ComfyUI workflows packaged with
comfyui-deploy→ RunPod Serverless endpoint (autoscale to zero when idle → no idle GPU cost). One endpoint per workflow family (t2v, i2v) or one multi-workflow endpoint keyed byworkflow_id. - Models/presets: Wan 2.2 (t2v + i2v) as the base, camera-control LoRAs + VACE for motion presets. Presets = versioned workflow JSON in a repo dir (e.g.
resource/broll_workflows/) + aBrollPresetrow per curated entry. - App-side: the existing
renderCelery queue already isolates GPU/heavy work; the generation task lands there. Concurrency capped by RunPod endpoint max workers + Celeryrenderpool size. - Dev/local:
docker-compose.gpu.yml/Dockerfile.gpualready exist — awan_localprovider hitting a local ComfyUI lets devs iterate without RunPod spend.
8. Security & safety (reuse the audited guards)
- BOLA: AI clips use server-generated
jobs/<job_id>/broll/<uuid>.mp4keys → covered by_assert_owned_r2_key. Never accept a client-supplied output key. - SSRF: i2v reference images must come from our R2 (via
presignupload), not arbitrary client URLs, or be validated/allow-listed before forwarding to the worker. - Prompt safety: run generation prompts through the existing moderation/LLM guardrails (same path as script gen) before spending GPU; NSFW/deepfake policy gate.
- Secrets: RunPod/ComfyUI keys only via env/
config(never logged) — mirrorlatentsync's redaction. - Rate limiting: dedicated tight
broll_gen_rate_limit(GPU cost) + credit debit as a hard gate. - Best-effort contract: an AI-B-roll failure returns
[]/Noneand never fails the parent reel job.
9. Testing (TDD, mirror tests/reelforge/)
- Unit:
ComfyUIProvider.generate_clipwith a fake RunPod (monkeypatchrequests) — success (URL + base64 outputs), retry-once, timeout, missing-output,is_enabled()gating. Copy the shape of the latentsync provider tests. - Registry: unknown provider id → fallback; fake provider swap-in (registry is monkeypatch-friendly by design).
- Service:
suggest_broll(source="ai")returns the{broll_key,...}contract; failure →[](best-effort invariant, liketest_no_stock_sourcing.py). - Security: cross-tenant key rejected; SSRF image URL rejected.
- API: controller routes — auth, rate-limit, credit debit/refund, poll lifecycle.
- Integration (opt-in / gated): one real RunPod smoke test behind an env flag.
- Target the repo's 80% coverage bar.
10. Phased rollout
| Phase | Deliverable | Touches | Risk |
|---|---|---|---|
| 0 — Spike (1–2d) | comfyui-deploy a Wan2.2 t2v workflow on RunPod; hit /run+/status with curl; confirm output URL shape |
infra only | low |
| 1 — Provider (2–3d) | broll_gen/base.py + comfyui_runpod.py (copy latentsync) + config + unit tests |
backend | low |
| 2 — Service + task (2–3d) | broll.suggest_broll(source="ai") + generate_broll_clip_task on render + credits |
backend | med (GPU cost/timeouts) |
| 3 — API + presets (2–3d) | broll_studio.py controller + BrollPreset migration + curated t2v/i2v presets |
backend + db | med |
| 4 — Web studio (3–4d) | preset picker + prompt/image form + gallery + attach-to-reel; use-broll-studio.ts |
web | med |
| 5 — Mobile + i2v polish (2–3d) | mobile studio; image→video via presign upload | mobile | low |
| 6 — Full-timeline (v2) | _apply_broll_overlays + broll_timeline param |
compose | high (FFmpeg) |
≈ 2–3 weeks to Phase 5 (matches the research doc's estimate); Phase 6 is a separate fast-follow.
11. Open decisions (need a call before/at build)
- D1 — Placement: intro/outro stingers (v1, zero compose work) vs full-timeline overlays (v2, real FFmpeg). Recommend stingers first.
- D2 — Backend: RunPod serverless via comfyui-deploy (scale-to-zero, recommended) vs Modal vs a managed API (fal/Replicate) as the day-1 provider to de-risk the ComfyUI ops learning curve. Recommend: managed API fallback provider behind the same Protocol so we ship UX before mastering GPU ops.
- D3 — Studio scope: clips only-usable-in-a-reel vs a standalone gallery users generate into freely (browse/download). Recommend job-scoped v1, standalone gallery as
Job(kind="broll_gen")in Phase 3. - D4 — Product shape: ReelForge feature (this plan) vs standalone "B-roll studio" product. The provider/service/registry design keeps the core reusable either way, so this can stay deferred.
- D5 — Preset storage:
BrollPresettable vs reuseUserPresetwith akinddiscriminator. Recommend dedicated table for thumbnails + public/shared presets (the Higgsfield "shareable preset" primitive).
12. Why this is low-risk
Every heavy piece already exists in a proven form: a serverless GPU-worker client
(latentsync_runpod.py), a monkeypatch-friendly provider registry (avatar/base.py), a best-effort
B-roll service with R2 conventions and BOLA guards (broll.py), a render queue for GPU work, JSON
param/asset columns that avoid migrations, and a frontend that already calls a B-roll endpoint. The AI
B-roll studio is mostly copy-adapt-register, not net-new architecture — the ComfyUI/comfyui-deploy
REST shape maps 1:1 onto the RunPod client we already ship.
13. Implementation status & notes (as built)
Phases 1–4 landed, plus the standalone studio and the i2v + wizard-attach surfaces.
Shipped
- Provider (Phase 1) —
broll_gen/base.py(registry) +comfyui_deploy.py(create-run/poll/download) +config.comfyui. - Service seam (Phase 2) —
broll.suggest_broll(source="ai")→broll_genprovider, same{broll_key,…}contract. - Async studio (Phase 2/3) —
Job(kind="broll_gen")+generate_broll_clip_taskon therenderqueue (BrollGenTaskrefunds credits on terminal failure) +services/broll_gen/job.pydelegate. Endpoints:POST /broll/generate,GET /broll/generations/{id},GET /broll/generations. - Presets (Phase 3) —
BrollPresetmodel + migration…_broll_presets.pyseeding 5 curated global presets +BrollPresetRepository.list_available+GET /broll/presets. - Web studio (Phase 4) —
web/app/broll+BrollStudio+use-broll-studiopolling hook + dashboard link. - i2v upload —
POST /uploads/registerrecords anuploads/object as a caller-ownedAsset(rejectsjobs/keys; idempotent), unblocking the i2v ownership check (also repairs the avatar-from-photo path). Studio i2v uses a reference-image picker (SelfieInput) →uploadAndRegisterImage→generate({mode:"i2v", image_key}). - Wizard attach —
BrollPanellists the caller's finished studio clips (GET /broll/generations) and attaches one as intro/outro via the existingrerunJobflow (no copy-paste).
Security note
BOLA holds for free: a studio clip lives under jobs/<gen_job_id>/broll/… owned by the same user, which rerun's _assert_owned_r2_key already permits (same-user cross-job).
Verified
- Backend smoke:
POST /uploads/registeris idempotent, owner-verifiable, foreign key rejected (403);list_for_user_by_kindis correctly kind-scoped.broll_presetsmigration upgrade+downgrade round-trip;default_paramsdecodes to a dict. - 389 backend tests green (broll, api, db, schema, studio_avatars).
- Frontend
tsc --noEmitexit 0; ESLint clean on all touched files.
Honest remaining gaps
- No mode toggle back to t2v once an i2v preset is picked — you switch by choosing a t2v preset chip. Minor UX; a segmented control would be cleaner.
- Studio-clip labels in the wizard show the raw
broll_key(mono text), no thumbnail — studio generations don't produce poster frames yet. - Mobile still has none of the studio surface (Phase 5).
- The
uploadAndRegisterImageprogress callback isn't surfaced in the studio (upload shows a generic spinner) — fine for a 5–12 MB image.
The full product loop now works end-to-end: generate (t2v or i2v) in the studio → poll to Ready → open a reel → attach the finished AI clip as intro/outro in one click. Next highest-value is mobile parity or poster thumbnails for studio clips (so the wizard shows previews instead of keys).