feat: Add Remotion integration for animated subtitles, hooks and effects

Replace static FFmpeg post-processing with Remotion-powered browser rendering:
- Animated word-by-word subtitles (pop, karaoke, glow styles) with real-time preview
- Hook overlays with entrance animations (spring, fade, slide-up)
- Video effects layer (zoom, brightness, contrast, saturate)
- Browser-side rendering via @remotion/web-renderer (WebCodecs)
- Editable transcript text in subtitle modal
- Layers accumulate across operations (subtitles + hook rendered together)
- Gemini EffectsConfig endpoint for structured JSON instead of fragile FFmpeg strings
- Render service (Node.js) as alternative server-side renderer
- New API endpoints: /api/clip/transcript, /api/effects/generate, /api/render

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
juancarlos.cavero 2026-04-10 14:00:11 +02:00
parent ccf86d61a9
commit 9c9342c499
40 changed files with 7413 additions and 82 deletions

View file

@ -15,6 +15,12 @@ ENV/
*.egg-info/ *.egg-info/
.pytest_cache/ .pytest_cache/
# Node
node_modules/
remotion/node_modules/
render-service/node_modules/
dashboard/node_modules/
# IDE # IDE
.idea/ .idea/
.vscode/ .vscode/

185
app.py
View file

@ -532,6 +532,191 @@ class SubtitleRequest(BaseModel):
bg_opacity: float = 0.0 bg_opacity: float = 0.0
input_filename: Optional[str] = None input_filename: Optional[str] = None
@app.get("/api/clip/{job_id}/{clip_index}/transcript")
async def get_clip_transcript(job_id: str, clip_index: int):
"""Return word-level captions for a specific clip, formatted for Remotion."""
if job_id not in jobs:
raise HTTPException(status_code=404, detail="Job not found")
output_dir = os.path.join(OUTPUT_DIR, job_id)
json_files = glob.glob(os.path.join(output_dir, "*_metadata.json"))
if not json_files:
raise HTTPException(status_code=404, detail="Metadata not found")
with open(json_files[0], 'r') as f:
data = json.load(f)
transcript = data.get('transcript')
if not transcript:
raise HTTPException(status_code=400, detail="Transcript not found in metadata")
clips = data.get('shorts', [])
if clip_index >= len(clips):
raise HTTPException(status_code=404, detail="Clip not found")
clip_data = clips[clip_index]
clip_start = clip_data.get('start', 0)
clip_end = clip_data.get('end', 0)
# Extract words within clip range and convert to CaptionWord format
captions = []
for segment in transcript.get('segments', []):
for word_info in segment.get('words', []):
if word_info['end'] > clip_start and word_info['start'] < clip_end:
captions.append({
"text": word_info.get('word', '').strip(),
"startMs": int((max(0, word_info['start'] - clip_start)) * 1000),
"endMs": int((max(0, word_info['end'] - clip_start)) * 1000),
})
duration_sec = clip_end - clip_start
return {
"captions": captions,
"durationSec": duration_sec,
"language": transcript.get('language', 'en'),
}
# --- Remotion Render Proxy ---
RENDER_SERVICE_URL = os.getenv("RENDER_SERVICE_URL", "http://renderer:3100")
@app.post("/api/render")
async def proxy_render(request: Request):
"""Proxy render requests to the Node.js Remotion render service."""
import httpx
body = await request.json()
try:
async with httpx.AsyncClient(timeout=30.0) as client:
resp = await client.post(f"{RENDER_SERVICE_URL}/render", json=body)
return resp.json()
except Exception as e:
raise HTTPException(status_code=502, detail=f"Render service unavailable: {e}")
@app.get("/api/render/{render_id}")
async def proxy_render_status(render_id: str):
"""Proxy render status polling to the Node.js Remotion render service."""
import httpx
try:
async with httpx.AsyncClient(timeout=10.0) as client:
resp = await client.get(f"{RENDER_SERVICE_URL}/render/{render_id}")
return resp.json()
except Exception as e:
raise HTTPException(status_code=502, detail=f"Render service unavailable: {e}")
class EffectsGenerateRequest(BaseModel):
job_id: str
clip_index: int
input_filename: Optional[str] = None
@app.post("/api/effects/generate")
async def generate_effects_config(
req: EffectsGenerateRequest,
x_gemini_key: Optional[str] = Header(None, alias="X-Gemini-Key")
):
"""Generate structured EffectsConfig JSON for Remotion rendering via Gemini AI."""
final_api_key = x_gemini_key or os.environ.get("GEMINI_API_KEY")
if not final_api_key:
raise HTTPException(status_code=400, detail="Missing Gemini API Key (Header)")
if req.job_id not in jobs:
raise HTTPException(status_code=404, detail="Job not found")
job = jobs[req.job_id]
if 'result' not in job or 'clips' not in job['result']:
raise HTTPException(status_code=400, detail="Job result not available")
try:
# Resolve input path
if req.input_filename:
safe_name = os.path.basename(req.input_filename)
input_path = os.path.join(OUTPUT_DIR, req.job_id, safe_name)
else:
clip = job['result']['clips'][req.clip_index]
filename = clip['video_url'].split('/')[-1]
input_path = os.path.join(OUTPUT_DIR, req.job_id, filename)
if not os.path.exists(input_path):
raise HTTPException(status_code=404, detail=f"Video file not found: {input_path}")
def run_effects_generation():
editor = VideoEditor(api_key=final_api_key)
# Create safe ASCII filename to avoid encoding issues
safe_filename = f"temp_effects_{req.job_id}.mp4"
safe_input_path = os.path.join(OUTPUT_DIR, req.job_id, safe_filename)
shutil.copy(input_path, safe_input_path)
try:
# Upload video to Gemini
vid_file = editor.upload_video(safe_input_path)
# Get video metadata via ffprobe
probe_cmd = [
'ffprobe', '-v', 'error',
'-select_streams', 'v:0',
'-show_entries', 'stream=width,height,r_frame_rate,duration',
'-show_entries', 'format=duration',
'-of', 'json',
safe_input_path
]
probe_result = subprocess.check_output(probe_cmd).decode().strip()
probe_data = json.loads(probe_result)
stream = probe_data.get('streams', [{}])[0]
width = int(stream.get('width', 1080))
height = int(stream.get('height', 1920))
# Parse fps from r_frame_rate (e.g. "30/1")
r_frame_rate = stream.get('r_frame_rate', '30/1')
num, den = r_frame_rate.split('/')
fps = round(int(num) / int(den), 2)
# Get duration from stream or format
duration = float(stream.get('duration', 0))
if duration == 0:
duration = float(probe_data.get('format', {}).get('duration', 0))
# Load transcript from metadata
transcript = None
try:
meta_files = glob.glob(os.path.join(OUTPUT_DIR, req.job_id, "*_metadata.json"))
if meta_files:
with open(meta_files[0], 'r') as f:
data = json.load(f)
transcript = data.get('transcript')
except Exception as e:
print(f"⚠️ Could not load transcript for effects config: {e}")
# Generate effects config
effects_config = editor.get_effects_config(
vid_file, duration, fps=fps, width=width, height=height, transcript=transcript
)
return effects_config
finally:
if os.path.exists(safe_input_path):
os.remove(safe_input_path)
loop = asyncio.get_event_loop()
effects_config = await loop.run_in_executor(None, run_effects_generation)
if effects_config is None:
raise HTTPException(status_code=500, detail="Failed to generate effects config from Gemini")
return {"effects": effects_config}
except HTTPException:
raise
except Exception as e:
print(f"❌ Effects Generation Error: {e}")
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/subtitle") @app.post("/api/subtitle")
async def add_subtitles(req: SubtitleRequest): async def add_subtitles(req: SubtitleRequest):
if req.job_id not in jobs: if req.job_id not in jobs:

View file

@ -1,16 +1,22 @@
{ {
"name": "dashboard", "name": "openshorts-app",
"version": "0.0.0", "version": "0.0.0",
"lockfileVersion": 2, "lockfileVersion": 2,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "dashboard", "name": "openshorts-app",
"version": "0.0.0", "version": "0.0.0",
"dependencies": { "dependencies": {
"@remotion/media": "^4.0.447",
"@remotion/media-utils": "^4.0.447",
"@remotion/player": "^4.0.447",
"@remotion/web-renderer": "^4.0.447",
"lucide-react": "^0.344.0", "lucide-react": "^0.344.0",
"react": "^18.2.0", "react": "^18.2.0",
"react-dom": "^18.2.0" "react-dom": "^18.2.0",
"remotion": "^4.0.447",
"zod": "^4.3.6"
}, },
"devDependencies": { "devDependencies": {
"@types/react": "^18.2.64", "@types/react": "^18.2.64",
@ -792,6 +798,45 @@
"@jridgewell/sourcemap-codec": "^1.4.14" "@jridgewell/sourcemap-codec": "^1.4.14"
} }
}, },
"node_modules/@mediabunny/aac-encoder": {
"version": "1.39.2",
"resolved": "https://registry.npmjs.org/@mediabunny/aac-encoder/-/aac-encoder-1.39.2.tgz",
"integrity": "sha512-KD6KADVzAnW7tqhRFGBOX4uaiHbd0Yxvg0lfthj3wJLAEEgEBAvi43w+ZXWeEn54X/jpabrLe4bW/eYFFvlbUA==",
"license": "MPL-2.0",
"funding": {
"type": "individual",
"url": "https://github.com/sponsors/Vanilagy"
},
"peerDependencies": {
"mediabunny": "^1.0.0"
}
},
"node_modules/@mediabunny/flac-encoder": {
"version": "1.39.2",
"resolved": "https://registry.npmjs.org/@mediabunny/flac-encoder/-/flac-encoder-1.39.2.tgz",
"integrity": "sha512-VwBr3AzZTPEEPvt4aladZiXwOf3W293eq213zDupGQi/taS8WWNqDd3eBdf8FfvlbXATfbRiycXDKyQ0HlOZaQ==",
"license": "MPL-2.0",
"funding": {
"type": "individual",
"url": "https://github.com/sponsors/Vanilagy"
},
"peerDependencies": {
"mediabunny": "^1.0.0"
}
},
"node_modules/@mediabunny/mp3-encoder": {
"version": "1.39.2",
"resolved": "https://registry.npmjs.org/@mediabunny/mp3-encoder/-/mp3-encoder-1.39.2.tgz",
"integrity": "sha512-3rrodrGnUpUP8F2d1aRUl8IvjqK3jegkupbOzvOokooSAO5rXk2Lr5jZe7TnPeiVGiXfmnoJ7s9uyUOHlCd8qw==",
"license": "MPL-2.0",
"funding": {
"type": "individual",
"url": "https://github.com/sponsors/Vanilagy"
},
"peerDependencies": {
"mediabunny": "^1.0.0"
}
},
"node_modules/@nodelib/fs.scandir": { "node_modules/@nodelib/fs.scandir": {
"version": "2.1.5", "version": "2.1.5",
"resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz",
@ -827,6 +872,71 @@
"node": ">= 8" "node": ">= 8"
} }
}, },
"node_modules/@remotion/licensing": {
"version": "4.0.447",
"resolved": "https://registry.npmjs.org/@remotion/licensing/-/licensing-4.0.447.tgz",
"integrity": "sha512-/pqArZCErkX0jVroK6tvTLuWpgFGiu/z5nTyCkaQogg6xvQKi7QQBXBb8mUJ/BvUeiWOUX/eVJ2khDGhSzQpUQ==",
"license": "MIT"
},
"node_modules/@remotion/media": {
"version": "4.0.447",
"resolved": "https://registry.npmjs.org/@remotion/media/-/media-4.0.447.tgz",
"integrity": "sha512-WWwOXAToVjwNxh9SfbBpdOweqbpOXLNoC7AaGKEv+AAH1RxVfNhc8ZzfFUgCtD7aBH4HHjva/Beca0C6LLVwKA==",
"dependencies": {
"mediabunny": "1.39.2",
"remotion": "4.0.447",
"zod": "4.3.6"
},
"peerDependencies": {
"react": ">=16.8.0",
"react-dom": ">=16.8.0"
}
},
"node_modules/@remotion/media-utils": {
"version": "4.0.447",
"resolved": "https://registry.npmjs.org/@remotion/media-utils/-/media-utils-4.0.447.tgz",
"integrity": "sha512-PltvSZsY+By8DlsZeAN63D1cMsgXewCqEq39nJrO0VZVc5nnWyd+nvMZz9yhGsoMo2Z5xNkfZhPkl+Gs25wn0Q==",
"license": "MIT",
"dependencies": {
"mediabunny": "1.39.2",
"remotion": "4.0.447"
},
"peerDependencies": {
"react": ">=16.8.0",
"react-dom": ">=16.8.0"
}
},
"node_modules/@remotion/player": {
"version": "4.0.447",
"resolved": "https://registry.npmjs.org/@remotion/player/-/player-4.0.447.tgz",
"integrity": "sha512-xKpdzlE8Gyceir/irJ2qsBK3hKJfILSTxQAQUtDWykehhC/OpizS9yl2//ZWghid9nNAL49QkbFcsqdcgcMocQ==",
"license": "SEE LICENSE IN LICENSE.md",
"dependencies": {
"remotion": "4.0.447"
},
"peerDependencies": {
"react": ">=16.8.0",
"react-dom": ">=16.8.0"
}
},
"node_modules/@remotion/web-renderer": {
"version": "4.0.447",
"resolved": "https://registry.npmjs.org/@remotion/web-renderer/-/web-renderer-4.0.447.tgz",
"integrity": "sha512-gzLLbglpu2DyH/WUywi599QICkcFjSf8VwANsLIUL/tUlr8RHjiJWr6XBgWYHHBtAXipRlmW7hRvP16j3wICiQ==",
"license": "UNLICENSED",
"dependencies": {
"@mediabunny/aac-encoder": "1.39.2",
"@mediabunny/flac-encoder": "1.39.2",
"@mediabunny/mp3-encoder": "1.39.2",
"@remotion/licensing": "4.0.447",
"mediabunny": "1.39.2",
"remotion": "4.0.447"
},
"peerDependencies": {
"react": ">=18.0.0",
"react-dom": ">=18.0.0"
}
},
"node_modules/@rolldown/pluginutils": { "node_modules/@rolldown/pluginutils": {
"version": "1.0.0-beta.27", "version": "1.0.0-beta.27",
"resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.27.tgz", "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.27.tgz",
@ -874,6 +984,21 @@
"@babel/types": "^7.28.2" "@babel/types": "^7.28.2"
} }
}, },
"node_modules/@types/dom-mediacapture-transform": {
"version": "0.1.11",
"resolved": "https://registry.npmjs.org/@types/dom-mediacapture-transform/-/dom-mediacapture-transform-0.1.11.tgz",
"integrity": "sha512-Y2p+nGf1bF2XMttBnsVPHUWzRRZzqUoJAKmiP10b5umnO6DDrWI0BrGDJy1pOHoOULVmGSfFNkQrAlC5dcj6nQ==",
"license": "MIT",
"dependencies": {
"@types/dom-webcodecs": "*"
}
},
"node_modules/@types/dom-webcodecs": {
"version": "0.1.13",
"resolved": "https://registry.npmjs.org/@types/dom-webcodecs/-/dom-webcodecs-0.1.13.tgz",
"integrity": "sha512-O5hkiFIcjjszPIYyUSyvScyvrBoV3NOEEZx/pMlsu44TKzWNkLVBBxnxJz42in5n3QIolYOcBYFCPZZ0h8SkwQ==",
"license": "MIT"
},
"node_modules/@types/prop-types": { "node_modules/@types/prop-types": {
"version": "15.7.15", "version": "15.7.15",
"resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz", "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz",
@ -3190,6 +3315,23 @@
"node": ">= 0.4" "node": ">= 0.4"
} }
}, },
"node_modules/mediabunny": {
"version": "1.39.2",
"resolved": "https://registry.npmjs.org/mediabunny/-/mediabunny-1.39.2.tgz",
"integrity": "sha512-VcrisGRt+OI7tTPrziucJoCIPYIS/DEWY37TqzQVLWSUUHiyvsiRizEypQ3FOlhfIZ4ytAG/Mw4zxfetCTyKUg==",
"license": "MPL-2.0",
"workspaces": [
"packages/*"
],
"dependencies": {
"@types/dom-mediacapture-transform": "^0.1.11",
"@types/dom-webcodecs": "0.1.13"
},
"funding": {
"type": "individual",
"url": "https://github.com/sponsors/Vanilagy"
}
},
"node_modules/merge2": { "node_modules/merge2": {
"version": "1.4.1", "version": "1.4.1",
"resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz",
@ -3879,6 +4021,16 @@
"url": "https://github.com/sponsors/ljharb" "url": "https://github.com/sponsors/ljharb"
} }
}, },
"node_modules/remotion": {
"version": "4.0.447",
"resolved": "https://registry.npmjs.org/remotion/-/remotion-4.0.447.tgz",
"integrity": "sha512-p2J+iGxmBL4TDUeAAlXrfxl9SfU/GRJEoVUpqJGYP8YJw/IKT2WbXngXHf4UWE0R2MHYAVtznuA640ktSSJwWw==",
"license": "SEE LICENSE IN LICENSE.md",
"peerDependencies": {
"react": ">=16.8.0",
"react-dom": ">=16.8.0"
}
},
"node_modules/resolve": { "node_modules/resolve": {
"version": "2.0.0-next.5", "version": "2.0.0-next.5",
"resolved": "https://registry.npmjs.org/resolve/-/resolve-2.0.0-next.5.tgz", "resolved": "https://registry.npmjs.org/resolve/-/resolve-2.0.0-next.5.tgz",
@ -4858,6 +5010,15 @@
"funding": { "funding": {
"url": "https://github.com/sponsors/sindresorhus" "url": "https://github.com/sponsors/sindresorhus"
} }
},
"node_modules/zod": {
"version": "4.3.6",
"resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz",
"integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}
} }
}, },
"dependencies": { "dependencies": {
@ -5314,6 +5475,24 @@
"@jridgewell/sourcemap-codec": "^1.4.14" "@jridgewell/sourcemap-codec": "^1.4.14"
} }
}, },
"@mediabunny/aac-encoder": {
"version": "1.39.2",
"resolved": "https://registry.npmjs.org/@mediabunny/aac-encoder/-/aac-encoder-1.39.2.tgz",
"integrity": "sha512-KD6KADVzAnW7tqhRFGBOX4uaiHbd0Yxvg0lfthj3wJLAEEgEBAvi43w+ZXWeEn54X/jpabrLe4bW/eYFFvlbUA==",
"requires": {}
},
"@mediabunny/flac-encoder": {
"version": "1.39.2",
"resolved": "https://registry.npmjs.org/@mediabunny/flac-encoder/-/flac-encoder-1.39.2.tgz",
"integrity": "sha512-VwBr3AzZTPEEPvt4aladZiXwOf3W293eq213zDupGQi/taS8WWNqDd3eBdf8FfvlbXATfbRiycXDKyQ0HlOZaQ==",
"requires": {}
},
"@mediabunny/mp3-encoder": {
"version": "1.39.2",
"resolved": "https://registry.npmjs.org/@mediabunny/mp3-encoder/-/mp3-encoder-1.39.2.tgz",
"integrity": "sha512-3rrodrGnUpUP8F2d1aRUl8IvjqK3jegkupbOzvOokooSAO5rXk2Lr5jZe7TnPeiVGiXfmnoJ7s9uyUOHlCd8qw==",
"requires": {}
},
"@nodelib/fs.scandir": { "@nodelib/fs.scandir": {
"version": "2.1.5", "version": "2.1.5",
"resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz",
@ -5340,6 +5519,51 @@
"fastq": "^1.6.0" "fastq": "^1.6.0"
} }
}, },
"@remotion/licensing": {
"version": "4.0.447",
"resolved": "https://registry.npmjs.org/@remotion/licensing/-/licensing-4.0.447.tgz",
"integrity": "sha512-/pqArZCErkX0jVroK6tvTLuWpgFGiu/z5nTyCkaQogg6xvQKi7QQBXBb8mUJ/BvUeiWOUX/eVJ2khDGhSzQpUQ=="
},
"@remotion/media": {
"version": "4.0.447",
"resolved": "https://registry.npmjs.org/@remotion/media/-/media-4.0.447.tgz",
"integrity": "sha512-WWwOXAToVjwNxh9SfbBpdOweqbpOXLNoC7AaGKEv+AAH1RxVfNhc8ZzfFUgCtD7aBH4HHjva/Beca0C6LLVwKA==",
"requires": {
"mediabunny": "1.39.2",
"remotion": "4.0.447",
"zod": "4.3.6"
}
},
"@remotion/media-utils": {
"version": "4.0.447",
"resolved": "https://registry.npmjs.org/@remotion/media-utils/-/media-utils-4.0.447.tgz",
"integrity": "sha512-PltvSZsY+By8DlsZeAN63D1cMsgXewCqEq39nJrO0VZVc5nnWyd+nvMZz9yhGsoMo2Z5xNkfZhPkl+Gs25wn0Q==",
"requires": {
"mediabunny": "1.39.2",
"remotion": "4.0.447"
}
},
"@remotion/player": {
"version": "4.0.447",
"resolved": "https://registry.npmjs.org/@remotion/player/-/player-4.0.447.tgz",
"integrity": "sha512-xKpdzlE8Gyceir/irJ2qsBK3hKJfILSTxQAQUtDWykehhC/OpizS9yl2//ZWghid9nNAL49QkbFcsqdcgcMocQ==",
"requires": {
"remotion": "4.0.447"
}
},
"@remotion/web-renderer": {
"version": "4.0.447",
"resolved": "https://registry.npmjs.org/@remotion/web-renderer/-/web-renderer-4.0.447.tgz",
"integrity": "sha512-gzLLbglpu2DyH/WUywi599QICkcFjSf8VwANsLIUL/tUlr8RHjiJWr6XBgWYHHBtAXipRlmW7hRvP16j3wICiQ==",
"requires": {
"@mediabunny/aac-encoder": "1.39.2",
"@mediabunny/flac-encoder": "1.39.2",
"@mediabunny/mp3-encoder": "1.39.2",
"@remotion/licensing": "4.0.447",
"mediabunny": "1.39.2",
"remotion": "4.0.447"
}
},
"@rolldown/pluginutils": { "@rolldown/pluginutils": {
"version": "1.0.0-beta.27", "version": "1.0.0-beta.27",
"resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.27.tgz", "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.27.tgz",
@ -5387,6 +5611,19 @@
"@babel/types": "^7.28.2" "@babel/types": "^7.28.2"
} }
}, },
"@types/dom-mediacapture-transform": {
"version": "0.1.11",
"resolved": "https://registry.npmjs.org/@types/dom-mediacapture-transform/-/dom-mediacapture-transform-0.1.11.tgz",
"integrity": "sha512-Y2p+nGf1bF2XMttBnsVPHUWzRRZzqUoJAKmiP10b5umnO6DDrWI0BrGDJy1pOHoOULVmGSfFNkQrAlC5dcj6nQ==",
"requires": {
"@types/dom-webcodecs": "*"
}
},
"@types/dom-webcodecs": {
"version": "0.1.13",
"resolved": "https://registry.npmjs.org/@types/dom-webcodecs/-/dom-webcodecs-0.1.13.tgz",
"integrity": "sha512-O5hkiFIcjjszPIYyUSyvScyvrBoV3NOEEZx/pMlsu44TKzWNkLVBBxnxJz42in5n3QIolYOcBYFCPZZ0h8SkwQ=="
},
"@types/prop-types": { "@types/prop-types": {
"version": "15.7.15", "version": "15.7.15",
"resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz", "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz",
@ -7016,6 +7253,15 @@
"integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
"dev": true "dev": true
}, },
"mediabunny": {
"version": "1.39.2",
"resolved": "https://registry.npmjs.org/mediabunny/-/mediabunny-1.39.2.tgz",
"integrity": "sha512-VcrisGRt+OI7tTPrziucJoCIPYIS/DEWY37TqzQVLWSUUHiyvsiRizEypQ3FOlhfIZ4ytAG/Mw4zxfetCTyKUg==",
"requires": {
"@types/dom-mediacapture-transform": "^0.1.11",
"@types/dom-webcodecs": "0.1.13"
}
},
"merge2": { "merge2": {
"version": "1.4.1", "version": "1.4.1",
"resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz",
@ -7455,6 +7701,12 @@
"set-function-name": "^2.0.2" "set-function-name": "^2.0.2"
} }
}, },
"remotion": {
"version": "4.0.447",
"resolved": "https://registry.npmjs.org/remotion/-/remotion-4.0.447.tgz",
"integrity": "sha512-p2J+iGxmBL4TDUeAAlXrfxl9SfU/GRJEoVUpqJGYP8YJw/IKT2WbXngXHf4UWE0R2MHYAVtznuA640ktSSJwWw==",
"requires": {}
},
"resolve": { "resolve": {
"version": "2.0.0-next.5", "version": "2.0.0-next.5",
"resolved": "https://registry.npmjs.org/resolve/-/resolve-2.0.0-next.5.tgz", "resolved": "https://registry.npmjs.org/resolve/-/resolve-2.0.0-next.5.tgz",
@ -8100,6 +8352,11 @@
"resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz",
"integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==",
"dev": true "dev": true
},
"zod": {
"version": "4.3.6",
"resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz",
"integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg=="
} }
} }
} }

View file

@ -10,9 +10,15 @@
"preview": "vite preview" "preview": "vite preview"
}, },
"dependencies": { "dependencies": {
"@remotion/media": "^4.0.447",
"@remotion/media-utils": "^4.0.447",
"@remotion/player": "^4.0.447",
"@remotion/web-renderer": "^4.0.447",
"lucide-react": "^0.344.0", "lucide-react": "^0.344.0",
"react": "^18.2.0", "react": "^18.2.0",
"react-dom": "^18.2.0" "react-dom": "^18.2.0",
"remotion": "^4.0.447",
"zod": "^4.3.6"
}, },
"devDependencies": { "devDependencies": {
"@types/react": "^18.2.64", "@types/react": "^18.2.64",

View file

@ -1,14 +1,35 @@
import React, { useState } from 'react'; import React, { useState } from 'react';
import { X, Sparkles, Loader2, Maximize, MoveVertical } from 'lucide-react'; import { X, Sparkles, Loader2, Maximize, MoveVertical, Zap } from 'lucide-react';
import RemotionPreview from './RemotionPreview';
export default function HookModal({ isOpen, onClose, onGenerate, isProcessing, videoUrl, initialText }) { const ENTRANCE_OPTIONS = [
{ value: 'spring', label: 'Bounce' },
{ value: 'fade', label: 'Fade' },
{ value: 'slide-up', label: 'Slide Up' },
{ value: 'none', label: 'None' },
];
export default function HookModal({ isOpen, onClose, onGenerate, isProcessing, videoUrl, initialText, durationInSeconds, existingSubtitles }) {
const [text, setText] = useState(initialText || 'POV: You are using the viral hook feature'); const [text, setText] = useState(initialText || 'POV: You are using the viral hook feature');
const [position, setPosition] = useState('top'); // top, center, bottom const [position, setPosition] = useState('top');
const [size, setSize] = useState('M'); // S, M, L const [size, setSize] = useState('M');
const [entranceAnimation, setEntranceAnimation] = useState('spring');
const [displayDuration, setDisplayDuration] = useState(5);
if (!isOpen) return null; if (!isOpen) return null;
// Preview Logic // Build hook config for Remotion preview
const hookConfig = {
text: text || 'Enter your text...',
position,
size,
entranceAnimation,
displayDurationSec: displayDuration,
};
const useRemotionPreview = !!videoUrl;
// Fallback preview logic (same as original)
const getPositionClass = () => { const getPositionClass = () => {
switch (position) { switch (position) {
case 'center': return 'items-center justify-center'; case 'center': return 'items-center justify-center';
@ -37,26 +58,35 @@ export default function HookModal({ isOpen, onClose, onGenerate, isProcessing, v
{/* Left: Preview */} {/* Left: Preview */}
<div className="flex-1 flex flex-col items-center justify-center bg-black rounded-lg border border-white/5 overflow-hidden relative aspect-[9/16] max-h-[600px]"> <div className="flex-1 flex flex-col items-center justify-center bg-black rounded-lg border border-white/5 overflow-hidden relative aspect-[9/16] max-h-[600px]">
<video src={videoUrl} className="w-full h-full object-contain opacity-50" muted playsInline /> {useRemotionPreview ? (
<RemotionPreview
{/* Hook Overlay Preview */} videoUrl={videoUrl}
<div className={`absolute w-full px-8 text-center transition-all duration-300 pointer-events-none flex flex-col h-full ${getPositionClass()}`}> durationInSeconds={durationInSeconds || 30}
<div hook={hookConfig}
className="text-black font-bold px-3 py-2 rounded-xl shadow-2xl text-center whitespace-pre-wrap transition-all duration-200" subtitles={existingSubtitles || null}
style={{ />
...getSizeStyle(), ) : (
backgroundColor: 'rgba(255, 255, 255, 0.82)', // Match backend 210/255 alpha <>
fontFamily: 'Noto Serif, serif', <video src={videoUrl} className="w-full h-full object-contain opacity-50" muted playsInline />
boxShadow: '0 4px 15px rgba(0,0,0,0.5)', <div className={`absolute w-full px-8 text-center transition-all duration-300 pointer-events-none flex flex-col h-full ${getPositionClass()}`}>
paddingTop: '10px', // Reduced to scale (backend is 20px on 1080p ~ 2%) <div
paddingBottom: '10px', className="text-black font-bold px-3 py-2 rounded-xl shadow-2xl text-center whitespace-pre-wrap transition-all duration-200"
paddingLeft: '12px', style={{
paddingRight: '12px' ...getSizeStyle(),
}} backgroundColor: 'rgba(255, 255, 255, 0.82)',
> fontFamily: 'Noto Serif, serif',
{text || "Enter your text..."} boxShadow: '0 4px 15px rgba(0,0,0,0.5)',
</div> paddingTop: '10px',
</div> paddingBottom: '10px',
paddingLeft: '12px',
paddingRight: '12px'
}}
>
{text || "Enter your text..."}
</div>
</div>
</>
)}
</div> </div>
{/* Right: Controls */} {/* Right: Controls */}
@ -120,13 +150,55 @@ export default function HookModal({ isOpen, onClose, onGenerate, isProcessing, v
</div> </div>
</div> </div>
{/* Entrance Animation (new) */}
<div>
<label className="text-xs font-bold text-zinc-400 uppercase tracking-wider mb-3 flex items-center gap-2">
<Zap size={12} /> Entrance
</label>
<div className="grid grid-cols-2 gap-2">
{ENTRANCE_OPTIONS.map((opt) => (
<button
key={opt.value}
onClick={() => setEntranceAnimation(opt.value)}
className={`py-2 px-1 rounded-lg text-xs font-bold transition-all border ${entranceAnimation === opt.value
? 'bg-white text-black border-white'
: 'bg-white/5 text-zinc-400 border-white/5 hover:bg-white/10'
}`}
>
{opt.label}
</button>
))}
</div>
</div>
{/* Display Duration (new) */}
<div>
<label className="text-xs font-bold text-zinc-400 uppercase tracking-wider mb-2 block">Duration: {displayDuration}s</label>
<input
type="range"
min="2"
max="15"
value={displayDuration}
onChange={(e) => setDisplayDuration(parseInt(e.target.value))}
className="w-full accent-yellow-500"
/>
<div className="flex justify-between text-[10px] text-zinc-500">
<span>2s</span>
<span>15s</span>
</div>
</div>
<div className="p-3 bg-white/5 rounded-lg border border-white/5 text-[11px] text-zinc-400"> <div className="p-3 bg-white/5 rounded-lg border border-white/5 text-[11px] text-zinc-400">
<strong>Tip:</strong> Keep it short and punchy. Using "POV:" or specific questions works best for retention. <strong>Tip:</strong> Keep it short and punchy. Using "POV:" or specific questions works best for retention.
</div> </div>
</div> </div>
<button <button
onClick={() => onGenerate({ text, position, size })} onClick={() => onGenerate({
text, position, size,
// Remotion data
remotion: hookConfig,
})}
disabled={isProcessing || !text.trim()} disabled={isProcessing || !text.trim()}
className="w-full py-4 mt-4 bg-gradient-to-r from-yellow-500 to-amber-600 hover:from-yellow-400 hover:to-amber-500 text-black font-bold rounded-xl shadow-lg shadow-amber-500/20 transition-all active:scale-[0.98] flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed shrink-0" className="w-full py-4 mt-4 bg-gradient-to-r from-yellow-500 to-amber-600 hover:from-yellow-400 hover:to-amber-500 text-black font-bold rounded-xl shadow-lg shadow-amber-500/20 transition-all active:scale-[0.98] flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed shrink-0"
> >

View file

@ -0,0 +1,61 @@
import React, { useMemo } from 'react';
import { Player } from '@remotion/player';
import { ShortVideo } from '../remotion/compositions/ShortVideo';
/**
* Wraps Remotion's Player component for real-time preview in modals.
* Accepts the same ShortVideoProps interface as the Remotion composition.
*
* @param {object} props
* @param {string} props.videoUrl - URL to the base clip video
* @param {number} props.durationInSeconds - Video duration in seconds
* @param {object|null} props.subtitles - SubtitleConfig or null
* @param {object|null} props.hook - HookConfig or null
* @param {object|null} props.effects - EffectsConfig or null
* @param {string} [props.className] - Additional CSS classes
*/
export default function RemotionPreview({
videoUrl,
durationInSeconds = 30,
subtitles = null,
hook = null,
effects = null,
className = '',
}) {
const fps = 30;
const durationInFrames = Math.max(1, Math.round(durationInSeconds * fps));
const inputProps = useMemo(
() => ({
videoUrl,
durationInFrames,
fps,
width: 1080,
height: 1920,
subtitles,
hook,
effects,
}),
[videoUrl, durationInFrames, subtitles, hook, effects]
);
return (
<div className={`w-full h-full ${className}`}>
<Player
component={ShortVideo}
inputProps={inputProps}
durationInFrames={durationInFrames}
fps={fps}
compositionWidth={1080}
compositionHeight={1920}
style={{
width: '100%',
height: '100%',
}}
controls
autoPlay
loop
/>
</div>
);
}

View file

@ -4,12 +4,14 @@ import { getApiUrl } from '../config';
import SubtitleModal from './SubtitleModal'; import SubtitleModal from './SubtitleModal';
import HookModal from './HookModal'; import HookModal from './HookModal';
import TranslateModal from './TranslateModal'; import TranslateModal from './TranslateModal';
import { renderInBrowser } from '../lib/renderInBrowser';
export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUserId, geminiApiKey, elevenLabsKey, onPlay, onPause }) { export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUserId, geminiApiKey, elevenLabsKey, onPlay, onPause }) {
const [showModal, setShowModal] = useState(false); const [showModal, setShowModal] = useState(false);
const [showSubtitleModal, setShowSubtitleModal] = useState(false); const [showSubtitleModal, setShowSubtitleModal] = useState(false);
const videoRef = React.useRef(null); const videoRef = React.useRef(null);
const [currentVideoUrl, setCurrentVideoUrl] = useState(getApiUrl(clip.video_url)); const originalVideoUrl = getApiUrl(clip.video_url); // Never changes — used for Remotion previews
const [currentVideoUrl, setCurrentVideoUrl] = useState(originalVideoUrl);
const [platforms, setPlatforms] = useState({ const [platforms, setPlatforms] = useState({
tiktok: true, tiktok: true,
@ -32,6 +34,22 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs
const [showTranslateModal, setShowTranslateModal] = useState(false); const [showTranslateModal, setShowTranslateModal] = useState(false);
const [editError, setEditError] = useState(null); const [editError, setEditError] = useState(null);
const [clipDuration, setClipDuration] = useState(clip.end && clip.start ? clip.end - clip.start : 30);
// Accumulate Remotion layers across operations
const [activeLayers, setActiveLayers] = useState({ subtitles: null, hook: null, effects: null });
// Fetch clip duration from transcript endpoint
useEffect(() => {
if (!jobId || index === undefined) return;
fetch(getApiUrl(`/api/clip/${jobId}/${index}/transcript`))
.then(res => res.ok ? res.json() : null)
.then(data => {
if (data && data.durationSec) setClipDuration(data.durationSec);
})
.catch(() => {});
}, [jobId, index]);
// Initialize/Reset form when modal opens // Initialize/Reset form when modal opens
useEffect(() => { useEffect(() => {
if (showModal) { if (showModal) {
@ -47,13 +65,36 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs
setIsEditing(true); setIsEditing(true);
setEditError(null); setEditError(null);
try { try {
// Use passed prop or fallback
const apiKey = geminiApiKey || localStorage.getItem('gemini_key'); const apiKey = geminiApiKey || localStorage.getItem('gemini_key');
if (!apiKey) { if (!apiKey) {
throw new Error("Gemini API Key is missing. Please set it in Settings."); throw new Error("Gemini API Key is missing. Please set it in Settings.");
} }
// Try Remotion effects endpoint first
const effectsRes = await fetch(getApiUrl('/api/effects/generate'), {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Gemini-Key': apiKey
},
body: JSON.stringify({
job_id: jobId,
clip_index: index,
input_filename: currentVideoUrl.split('/').pop()
})
});
if (effectsRes.ok) {
const data = await effectsRes.json();
if (data.effects && data.effects.segments) {
setCompositionParams(prev => ({ ...prev, effects: data.effects }));
setShowPreviewModal(true);
return;
}
}
// Fallback: legacy FFmpeg edit endpoint
const res = await fetch(getApiUrl('/api/edit'), { const res = await fetch(getApiUrl('/api/edit'), {
method: 'POST', method: 'POST',
headers: { headers: {
@ -80,7 +121,6 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs
const data = await res.json(); const data = await res.json();
if (data.new_video_url) { if (data.new_video_url) {
setCurrentVideoUrl(getApiUrl(data.new_video_url)); setCurrentVideoUrl(getApiUrl(data.new_video_url));
// Reload video
if (videoRef.current) { if (videoRef.current) {
videoRef.current.load(); videoRef.current.load();
} }
@ -98,6 +138,24 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs
setIsSubtitling(true); setIsSubtitling(true);
setEditError(null); setEditError(null);
try { try {
if (options.remotion) {
// Accumulate layer and render all layers together
const newLayers = { ...activeLayers, subtitles: options.remotion };
setActiveLayers(newLayers);
const blobUrl = await renderInBrowser({
videoUrl: originalVideoUrl,
durationInSeconds: clipDuration,
subtitles: newLayers.subtitles,
hook: newLayers.hook,
effects: newLayers.effects,
});
setCurrentVideoUrl(blobUrl);
if (videoRef.current) videoRef.current.load();
setShowSubtitleModal(false);
return;
}
// Fallback: legacy FFmpeg
const res = await fetch(getApiUrl('/api/subtitle'), { const res = await fetch(getApiUrl('/api/subtitle'), {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
@ -116,20 +174,13 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs
}) })
}); });
if (!res.ok) { if (!res.ok) throw new Error(await res.text());
const errText = await res.text();
throw new Error(errText);
}
const data = await res.json(); const data = await res.json();
if (data.new_video_url) { if (data.new_video_url) {
setCurrentVideoUrl(getApiUrl(data.new_video_url)); setCurrentVideoUrl(getApiUrl(data.new_video_url));
if (videoRef.current) { if (videoRef.current) videoRef.current.load();
videoRef.current.load();
}
setShowSubtitleModal(false); setShowSubtitleModal(false);
} }
} catch (e) { } catch (e) {
setEditError(e.message); setEditError(e.message);
setTimeout(() => setEditError(null), 5000); setTimeout(() => setEditError(null), 5000);
@ -142,7 +193,24 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs
setIsHooking(true); setIsHooking(true);
setEditError(null); setEditError(null);
try { try {
// Support both string (legacy) and object if (hookData.remotion) {
// Accumulate layer and render all layers together
const newLayers = { ...activeLayers, hook: hookData.remotion };
setActiveLayers(newLayers);
const blobUrl = await renderInBrowser({
videoUrl: originalVideoUrl,
durationInSeconds: clipDuration,
subtitles: newLayers.subtitles,
hook: newLayers.hook,
effects: newLayers.effects,
});
setCurrentVideoUrl(blobUrl);
if (videoRef.current) videoRef.current.load();
setShowHookModal(false);
return;
}
// Fallback: legacy FFmpeg
const payload = typeof hookData === 'string' const payload = typeof hookData === 'string'
? { text: hookData, position: 'top', size: 'M' } ? { text: hookData, position: 'top', size: 'M' }
: hookData; : hookData;
@ -160,20 +228,13 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs
}) })
}); });
if (!res.ok) { if (!res.ok) throw new Error(await res.text());
const errText = await res.text();
throw new Error(errText);
}
const data = await res.json(); const data = await res.json();
if (data.new_video_url) { if (data.new_video_url) {
setCurrentVideoUrl(getApiUrl(data.new_video_url)); setCurrentVideoUrl(getApiUrl(data.new_video_url));
if (videoRef.current) { if (videoRef.current) videoRef.current.load();
videoRef.current.load();
}
setShowHookModal(false); setShowHookModal(false);
} }
} catch (e) { } catch (e) {
setEditError(e.message); setEditError(e.message);
setTimeout(() => setEditError(null), 5000); setTimeout(() => setEditError(null), 5000);
@ -584,7 +645,10 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs
onClose={() => setShowSubtitleModal(false)} onClose={() => setShowSubtitleModal(false)}
onGenerate={handleSubtitle} onGenerate={handleSubtitle}
isProcessing={isSubtitling} isProcessing={isSubtitling}
videoUrl={currentVideoUrl} videoUrl={originalVideoUrl}
jobId={jobId}
clipIndex={index}
existingHook={activeLayers.hook}
/> />
<HookModal <HookModal
@ -592,8 +656,10 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs
onClose={() => setShowHookModal(false)} onClose={() => setShowHookModal(false)}
onGenerate={handleHook} onGenerate={handleHook}
isProcessing={isHooking} isProcessing={isHooking}
videoUrl={currentVideoUrl} videoUrl={originalVideoUrl}
initialText={clip.viral_hook_text} initialText={clip.viral_hook_text}
durationInSeconds={clip.end && clip.start ? clip.end - clip.start : 30}
existingSubtitles={activeLayers.subtitles}
/> />
<TranslateModal <TranslateModal
@ -604,6 +670,7 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs
videoUrl={currentVideoUrl} videoUrl={currentVideoUrl}
hasApiKey={!!elevenLabsKey} hasApiKey={!!elevenLabsKey}
/> />
</div> </div>
); );
} }

View file

@ -1,5 +1,7 @@
import React, { useState } from 'react'; import React, { useState, useEffect } from 'react';
import { X, Type, Loader2 } from 'lucide-react'; import { X, Type, Loader2 } from 'lucide-react';
import { getApiUrl } from '../config';
import RemotionPreview from './RemotionPreview';
const FONT_OPTIONS = [ const FONT_OPTIONS = [
{ value: 'Verdana', label: 'Verdana' }, { value: 'Verdana', label: 'Verdana' },
@ -19,22 +21,100 @@ const COLOR_PRESETS = [
{ color: '#FF69B4', label: 'Pink' }, { color: '#FF69B4', label: 'Pink' },
]; ];
export default function SubtitleModal({ isOpen, onClose, onGenerate, isProcessing, videoUrl }) { const ANIMATION_OPTIONS = [
{ value: 'pop', label: 'Pop' },
{ value: 'word-highlight', label: 'Glow' },
{ value: 'karaoke', label: 'Karaoke' },
{ value: 'none', label: 'None' },
];
export default function SubtitleModal({ isOpen, onClose, onGenerate, isProcessing, videoUrl, jobId, clipIndex, existingHook }) {
const [position, setPosition] = useState('bottom'); const [position, setPosition] = useState('bottom');
const [fontSize, setFontSize] = useState(24); const [fontSize, setFontSize] = useState(24);
const [fontName, setFontName] = useState('Verdana'); const [fontName, setFontName] = useState('Verdana');
const [fontColor, setFontColor] = useState('#FFFFFF'); const [fontColor, setFontColor] = useState('#FFFFFF');
const [highlightColor, setHighlightColor] = useState('#FFDD00');
const [borderColor, setBorderColor] = useState('#000000'); const [borderColor, setBorderColor] = useState('#000000');
const [borderWidth, setBorderWidth] = useState(2); const [borderWidth, setBorderWidth] = useState(2);
const [bgColor, setBgColor] = useState('#000000'); const [bgColor, setBgColor] = useState('#000000');
const [bgOpacity, setBgOpacity] = useState(0.0); const [bgOpacity, setBgOpacity] = useState(0.0);
const [animation, setAnimation] = useState('pop');
const [showTextEditor, setShowTextEditor] = useState(false);
// Remotion preview state
const [captions, setCaptions] = useState([]);
const [originalCaptions, setOriginalCaptions] = useState([]);
const [editableText, setEditableText] = useState('');
const [durationSec, setDurationSec] = useState(30);
const [captionsLoading, setCaptionsLoading] = useState(false);
const [useRemotionPreview, setUseRemotionPreview] = useState(false);
// Fetch word-level captions when modal opens
useEffect(() => {
if (!isOpen || !jobId || clipIndex === undefined) return;
setCaptionsLoading(true);
fetch(getApiUrl(`/api/clip/${jobId}/${clipIndex}/transcript`))
.then((res) => res.ok ? res.json() : null)
.then((data) => {
if (data && data.captions && data.captions.length > 0) {
setCaptions(data.captions);
setOriginalCaptions(data.captions);
setEditableText(data.captions.map(c => c.text).join(' '));
setDurationSec(data.durationSec || 30);
setUseRemotionPreview(true);
} else {
setUseRemotionPreview(false);
}
})
.catch(() => setUseRemotionPreview(false))
.finally(() => setCaptionsLoading(false));
}, [isOpen, jobId, clipIndex]);
// When user edits text, redistribute words across original timestamps
const handleTextEdit = (newText) => {
setEditableText(newText);
const newWords = newText.split(/\s+/).filter(w => w.length > 0);
if (newWords.length === 0 || originalCaptions.length === 0) {
setCaptions([]);
return;
}
// Distribute new words across the time span of original captions
const totalDurationMs = originalCaptions[originalCaptions.length - 1].endMs - originalCaptions[0].startMs;
const startMs = originalCaptions[0].startMs;
const wordDurationMs = totalDurationMs / newWords.length;
const newCaptions = newWords.map((word, i) => ({
text: word,
startMs: Math.round(startMs + i * wordDurationMs),
endMs: Math.round(startMs + (i + 1) * wordDurationMs),
}));
setCaptions(newCaptions);
};
if (!isOpen) return null; if (!isOpen) return null;
// Scale border width for preview (preview font is small, so amplify the effect) // Build subtitle config for Remotion
const subtitleConfig = {
captions,
position,
style: {
fontFamily: fontName,
fontSize: fontSize * 2.2, // Scale up for 1080p (modal fontSize is for small preview)
fontColor,
highlightColor,
borderColor,
borderWidth: borderWidth * 1.5,
bgColor,
bgOpacity,
animation,
},
};
// Fallback: static CSS preview (same as original)
const bw = Math.max(borderWidth, 0); const bw = Math.max(borderWidth, 0);
const bc = borderColor; const bc = borderColor;
// Build outline text-shadow (8-direction) — always applied for visibility
const outlineShadow = bw > 0 ? [ const outlineShadow = bw > 0 ? [
`-${bw}px -${bw}px 0 ${bc}`, `${bw}px -${bw}px 0 ${bc}`, `-${bw}px -${bw}px 0 ${bc}`, `${bw}px -${bw}px 0 ${bc}`,
`-${bw}px ${bw}px 0 ${bc}`, `${bw}px ${bw}px 0 ${bc}`, `-${bw}px ${bw}px 0 ${bc}`, `${bw}px ${bw}px 0 ${bc}`,
@ -42,7 +122,7 @@ export default function SubtitleModal({ isOpen, onClose, onGenerate, isProcessin
`-${bw}px 0 0 ${bc}`, `${bw}px 0 0 ${bc}`, `-${bw}px 0 0 ${bc}`, `${bw}px 0 0 ${bc}`,
].join(', ') : 'none'; ].join(', ') : 'none';
const previewStyle = { const fallbackPreviewStyle = {
fontFamily: fontName, fontFamily: fontName,
color: fontColor, color: fontColor,
fontSize: '20px', fontSize: '20px',
@ -63,7 +143,7 @@ export default function SubtitleModal({ isOpen, onClose, onGenerate, isProcessin
return ( return (
<div className="fixed inset-0 z-[100] flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm animate-[fadeIn_0.2s_ease-out]"> <div className="fixed inset-0 z-[100] flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm animate-[fadeIn_0.2s_ease-out]">
<div className="bg-[#121214] border border-white/10 p-6 rounded-2xl w-full max-w-4xl shadow-2xl relative flex flex-col md:flex-row gap-6 max-h-[90vh]"> <div className="bg-[#121214] border border-white/10 p-6 rounded-2xl w-full max-w-5xl shadow-2xl relative flex flex-col md:flex-row gap-6 max-h-[90vh]">
<button <button
onClick={onClose} onClick={onClose}
className="absolute top-4 right-4 text-zinc-500 hover:text-white z-10" className="absolute top-4 right-4 text-zinc-500 hover:text-white z-10"
@ -73,27 +153,41 @@ export default function SubtitleModal({ isOpen, onClose, onGenerate, isProcessin
{/* Left: Preview */} {/* Left: Preview */}
<div className="flex-1 flex flex-col items-center justify-center bg-black rounded-lg border border-white/5 overflow-hidden relative aspect-[9/16] max-h-[600px]"> <div className="flex-1 flex flex-col items-center justify-center bg-black rounded-lg border border-white/5 overflow-hidden relative aspect-[9/16] max-h-[600px]">
<video src={videoUrl} className="w-full h-full object-contain opacity-50" muted playsInline /> {captionsLoading ? (
<div className="flex items-center gap-2 text-zinc-400">
{/* Subtitle Overlay Preview */} <Loader2 size={16} className="animate-spin" />
<div className={`absolute w-full px-8 text-center transition-all duration-300 pointer-events-none flex flex-col items-center justify-center <span className="text-sm">Loading preview...</span>
${position === 'top' ? 'top-20' : ''} </div>
${position === 'middle' ? 'top-0 bottom-0' : ''} ) : useRemotionPreview ? (
${position === 'bottom' ? 'bottom-20' : ''} <RemotionPreview
`}> videoUrl={videoUrl}
<span style={previewStyle}> durationInSeconds={durationSec}
This is how your subtitles<br/>will appear on the video subtitles={subtitleConfig}
</span> hook={existingHook || null}
</div> />
) : (
<>
<video src={videoUrl} className="w-full h-full object-contain opacity-50" muted playsInline />
<div className={`absolute w-full px-8 text-center transition-all duration-300 pointer-events-none flex flex-col items-center justify-center
${position === 'top' ? 'top-20' : ''}
${position === 'middle' ? 'top-0 bottom-0' : ''}
${position === 'bottom' ? 'bottom-20' : ''}
`}>
<span style={fallbackPreviewStyle}>
This is how your subtitles<br/>will appear on the video
</span>
</div>
</>
)}
</div> </div>
{/* Right: Controls */} {/* Right: Controls */}
<div className="w-full md:w-80 flex flex-col overflow-y-auto custom-scrollbar"> <div className="w-full md:w-80 flex flex-col">
<h3 className="text-xl font-bold text-white mb-6 flex items-center gap-2"> <h3 className="text-xl font-bold text-white mb-4 flex items-center gap-2 shrink-0">
<Type className="text-primary" /> Auto Subtitles <Type className="text-primary" /> Auto Subtitles
</h3> </h3>
<div className="space-y-5 flex-1"> <div className="space-y-5 flex-1 overflow-y-auto custom-scrollbar pr-1">
{/* Position Selector */} {/* Position Selector */}
<div> <div>
<label className="text-xs font-bold text-zinc-400 uppercase tracking-wider mb-2 block">Position</label> <label className="text-xs font-bold text-zinc-400 uppercase tracking-wider mb-2 block">Position</label>
@ -110,6 +204,45 @@ export default function SubtitleModal({ isOpen, onClose, onGenerate, isProcessin
</div> </div>
</div> </div>
{/* Animation Style (new) */}
<div>
<label className="text-xs font-bold text-zinc-400 uppercase tracking-wider mb-2 block">Animation</label>
<div className="grid grid-cols-2 gap-2">
{ANIMATION_OPTIONS.map((opt) => (
<button
key={opt.value}
onClick={() => setAnimation(opt.value)}
className={`p-2 rounded-lg border text-center text-xs font-medium transition-all ${animation === opt.value ? 'bg-primary/20 border-primary text-white' : 'bg-white/5 border-white/5 text-zinc-400 hover:bg-white/10'}`}
>
{opt.label}
</button>
))}
</div>
</div>
{/* Editable Transcript (collapsible) */}
{useRemotionPreview && (
<div>
<button
type="button"
onClick={() => setShowTextEditor(!showTextEditor)}
className="w-full flex items-center justify-between text-xs font-bold text-zinc-400 uppercase tracking-wider mb-2"
>
<span>Edit Text ({captions.length} words)</span>
<span className={`transition-transform ${showTextEditor ? 'rotate-180' : ''}`}>▾</span>
</button>
{showTextEditor && (
<textarea
value={editableText}
onChange={(e) => handleTextEdit(e.target.value)}
rows={5}
className="w-full bg-black/40 border border-white/10 rounded-lg p-2.5 text-sm text-white focus:outline-none focus:border-primary/50 resize-none leading-relaxed animate-[fadeIn_0.15s_ease-out]"
placeholder="Edit subtitle text..."
/>
)}
</div>
)}
{/* Font Family */} {/* Font Family */}
<div> <div>
<label className="text-xs font-bold text-zinc-400 uppercase tracking-wider mb-2 block">Font</label> <label className="text-xs font-bold text-zinc-400 uppercase tracking-wider mb-2 block">Font</label>
@ -144,6 +277,22 @@ export default function SubtitleModal({ isOpen, onClose, onGenerate, isProcessin
</div> </div>
</div> </div>
{/* Highlight Color (new) */}
<div>
<label className="text-xs font-bold text-zinc-400 uppercase tracking-wider mb-2 block">Highlight Color</label>
<div className="flex flex-wrap gap-2">
{[{ color: '#FFDD00', label: 'Gold' }, { color: '#FF4444', label: 'Red' }, { color: '#00FF88', label: 'Green' }, { color: '#00BBFF', label: 'Blue' }, { color: '#FF69B4', label: 'Pink' }].map((c) => (
<button
key={c.color}
onClick={() => setHighlightColor(c.color)}
className={`w-7 h-7 rounded-full border-2 transition-all ${highlightColor === c.color ? 'border-white scale-110' : 'border-white/20 hover:border-white/50'}`}
style={{ backgroundColor: c.color }}
title={c.label}
/>
))}
</div>
</div>
{/* Border / Outline */} {/* Border / Outline */}
<div> <div>
<label className="text-xs font-bold text-zinc-400 uppercase tracking-wider mb-2 block">Border</label> <label className="text-xs font-bold text-zinc-400 uppercase tracking-wider mb-2 block">Border</label>
@ -206,17 +355,17 @@ export default function SubtitleModal({ isOpen, onClose, onGenerate, isProcessin
</div> </div>
<button <button
onClick={() => onGenerate({ position, fontSize, fontName, fontColor, borderColor, borderWidth, bgColor, bgOpacity })} onClick={() => onGenerate({
position, fontSize, fontName, fontColor, borderColor, borderWidth, bgColor, bgOpacity,
// Remotion data
remotion: useRemotionPreview ? subtitleConfig : null,
})}
disabled={isProcessing} disabled={isProcessing}
className="w-full py-4 mt-6 bg-gradient-to-r from-yellow-500 to-orange-500 hover:from-yellow-400 hover:to-orange-400 text-black font-bold rounded-xl shadow-lg shadow-orange-500/20 transition-all active:scale-[0.98] flex items-center justify-center gap-2" className="w-full py-3 mt-4 bg-gradient-to-r from-yellow-500 to-orange-500 hover:from-yellow-400 hover:to-orange-400 text-black font-bold rounded-xl shadow-lg shadow-orange-500/20 transition-all active:scale-[0.98] flex items-center justify-center gap-2 shrink-0"
> >
{isProcessing ? <Loader2 size={20} className="animate-spin" /> : <Type size={20} />} {isProcessing ? <Loader2 size={20} className="animate-spin" /> : <Type size={20} />}
{isProcessing ? 'Generating...' : 'Generate Subtitles'} {isProcessing ? 'Generating...' : 'Generate Subtitles'}
</button> </button>
<p className="text-[10px] text-zinc-500 text-center mt-3">
Uses AI word-level timestamps to sync perfectly.
</p>
</div> </div>
</div> </div>
</div> </div>

View file

@ -0,0 +1,74 @@
import { renderMediaOnWeb } from '@remotion/web-renderer';
import { ShortVideo } from '../remotion/compositions/ShortVideo';
/**
* Renders a Remotion composition directly in the browser using WebCodecs.
* Returns a blob URL to the rendered MP4.
*
* @param {object} params
* @param {string} params.videoUrl - Source video URL
* @param {number} params.durationInSeconds - Video duration
* @param {object|null} params.subtitles - SubtitleConfig
* @param {object|null} params.hook - HookConfig
* @param {object|null} params.effects - EffectsConfig
* @param {function} [params.onProgress] - Progress callback (0-1)
* @param {AbortSignal} [params.signal] - Abort signal for cancellation
* @returns {Promise<string>} Blob URL of the rendered MP4
*/
export async function renderInBrowser({
videoUrl,
durationInSeconds = 30,
subtitles = null,
hook = null,
effects = null,
onProgress,
signal,
}) {
const fps = 30;
const durationInFrames = Math.max(1, Math.round(durationInSeconds * fps));
const { getBlob } = await renderMediaOnWeb({
composition: {
component: ShortVideo,
durationInFrames,
fps,
width: 1080,
height: 1920,
id: 'ShortVideo',
calculateMetadata: null,
},
inputProps: {
videoUrl,
durationInFrames,
fps,
width: 1080,
height: 1920,
subtitles,
hook,
effects,
},
container: 'mp4',
videoCodec: 'h264',
videoBitrate: 'high',
audioCodec: 'aac',
onProgress: onProgress
? ({ progress }) => onProgress(progress)
: undefined,
signal,
});
const blob = await getBlob();
return URL.createObjectURL(blob);
}
/**
* Triggers a download of a blob URL as an MP4 file.
*/
export function downloadBlobUrl(blobUrl, filename = 'output.mp4') {
const link = document.createElement('a');
link.href = blobUrl;
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}

View file

@ -0,0 +1,144 @@
import React from "react";
import {
AbsoluteFill,
Sequence,
useCurrentFrame,
useVideoConfig,
spring,
interpolate,
} from "remotion";
import type { HookConfig } from "../lib/types";
import { notoSerifFontFace, NOTO_SERIF_FONT_FAMILY } from "../lib/fonts";
interface HookOverlayProps {
config: HookConfig;
}
const SIZE_SCALE: Record<string, number> = {
S: 0.8,
M: 1.0,
L: 1.3,
};
const POSITION_STYLE: Record<string, React.CSSProperties> = {
top: { top: "18%", bottom: "auto" },
center: { top: "50%", bottom: "auto", transform: "translateY(-50%)" },
bottom: { top: "68%", bottom: "auto" },
};
export const HookOverlay: React.FC<HookOverlayProps> = ({ config }) => {
const { fps } = useVideoConfig();
const displayFrames = Math.round(config.displayDurationSec * fps);
return (
<AbsoluteFill>
<style>{notoSerifFontFace}</style>
<Sequence from={0} durationInFrames={displayFrames} layout="none">
<HookBox config={config} displayFrames={displayFrames} />
</Sequence>
</AbsoluteFill>
);
};
interface HookBoxProps {
config: HookConfig;
displayFrames: number;
}
const HookBox: React.FC<HookBoxProps> = ({ config, displayFrames }) => {
const frame = useCurrentFrame();
const { fps } = useVideoConfig();
const scale = SIZE_SCALE[config.size] ?? 1.0;
// Entrance animation
let animOpacity = 1;
let animScale = 1;
let animTranslateY = 0;
switch (config.entranceAnimation) {
case "spring": {
const prog = spring({
frame,
fps,
config: { mass: 0.8, stiffness: 200, damping: 15 },
durationInFrames: 20,
});
animScale = interpolate(prog, [0, 1], [0.7, 1]);
animOpacity = interpolate(prog, [0, 1], [0, 1]);
break;
}
case "fade": {
animOpacity = interpolate(frame, [0, 15], [0, 1], {
extrapolateRight: "clamp",
});
break;
}
case "slide-up": {
const prog = spring({
frame,
fps,
config: { mass: 1, stiffness: 150, damping: 18 },
durationInFrames: 20,
});
animTranslateY = interpolate(prog, [0, 1], [60, 0]);
animOpacity = interpolate(prog, [0, 1], [0, 1]);
break;
}
default:
break;
}
// Exit fade (last 15 frames)
const fadeOutStart = displayFrames - 15;
if (frame > fadeOutStart) {
animOpacity *= interpolate(frame, [fadeOutStart, displayFrames], [1, 0], {
extrapolateLeft: "clamp",
extrapolateRight: "clamp",
});
}
const positionStyle = POSITION_STYLE[config.position] ?? POSITION_STYLE.top;
// Base font size: 5% of 1080 width (matches hooks.py logic)
const baseFontSize = 1080 * 0.05;
const fontSize = Math.round(baseFontSize * scale);
return (
<div
style={{
position: "absolute",
left: 0,
right: 0,
display: "flex",
justifyContent: "center",
...positionStyle,
}}
>
<div
style={{
opacity: animOpacity,
transform: `scale(${animScale}) translateY(${animTranslateY}px)`,
maxWidth: "90%",
backgroundColor: "rgba(255, 255, 255, 0.94)",
borderRadius: 20,
padding: `${25 * scale}px ${30 * scale}px`,
boxShadow: "5px 5px 15px rgba(0, 0, 0, 0.25)",
textAlign: "center",
}}
>
<span
style={{
fontFamily: `'${NOTO_SERIF_FONT_FAMILY}', 'Noto Serif', Georgia, serif`,
fontSize,
fontWeight: 700,
color: "#000000",
lineHeight: 1.4,
wordBreak: "break-word",
}}
>
{config.text}
</span>
</div>
</div>
);
};

View file

@ -0,0 +1,33 @@
import React from "react";
import { AbsoluteFill } from "remotion";
import { Video } from "@remotion/media";
import type { ShortVideoProps } from "../lib/types";
import { Subtitles } from "./Subtitles";
import { HookOverlay } from "./HookOverlay";
import { VideoEffects } from "./VideoEffects";
/**
* Main composition that layers all post-processing on top of the base video.
* Uses @remotion/media Video for browser-side rendering compatibility.
*/
export const ShortVideo: React.FC<Record<string, unknown>> = (rawProps) => {
const { videoUrl, subtitles, hook, effects } =
rawProps as unknown as ShortVideoProps;
return (
<AbsoluteFill style={{ backgroundColor: "#000" }}>
{/* Layer 1: Base video with optional zoom/color effects */}
<VideoEffects config={effects}>
<Video
src={videoUrl}
style={{ width: "100%", height: "100%", objectFit: "cover" }}
/>
</VideoEffects>
{/* Layer 2: Animated subtitles */}
{subtitles && <Subtitles config={subtitles} />}
{/* Layer 3: Hook text overlay */}
{hook && <HookOverlay config={hook} />}
</AbsoluteFill>
);
};

View file

@ -0,0 +1,227 @@
import React from "react";
import {
AbsoluteFill,
Sequence,
useCurrentFrame,
useVideoConfig,
spring,
interpolate,
} from "remotion";
import type { SubtitleConfig } from "../lib/types";
import { groupCaptionsIntoBlocks, getActiveWordIndex } from "../lib/captions";
import { getFontStack } from "../lib/fonts";
interface SubtitlesProps {
config: SubtitleConfig;
}
const POSITION_MAP: Record<string, React.CSSProperties> = {
top: { top: "12%", bottom: "auto" },
middle: { top: "45%", bottom: "auto" },
bottom: { bottom: "10%", top: "auto" },
};
export const Subtitles: React.FC<SubtitlesProps> = ({ config }) => {
const { fps } = useVideoConfig();
const blocks = groupCaptionsIntoBlocks(config.captions);
return (
<AbsoluteFill>
{blocks.map((block, i) => {
const startFrame = Math.round((block.startMs / 1000) * fps);
const durationFrames = Math.max(
1,
Math.round(((block.endMs - block.startMs) / 1000) * fps)
);
return (
<Sequence
key={i}
from={startFrame}
durationInFrames={durationFrames}
layout="none"
>
<SubtitleBlock
block={block}
config={config}
blockStartMs={block.startMs}
/>
</Sequence>
);
})}
</AbsoluteFill>
);
};
interface SubtitleBlockProps {
block: ReturnType<typeof groupCaptionsIntoBlocks>[number];
config: SubtitleConfig;
blockStartMs: number;
}
const SubtitleBlock: React.FC<SubtitleBlockProps> = ({
block,
config,
blockStartMs,
}) => {
const frame = useCurrentFrame();
const { fps } = useVideoConfig();
const { style, position } = config;
// Current time relative to composition start (sequence-relative frame)
const currentTimeMs = blockStartMs + (frame / fps) * 1000;
const activeIndex = getActiveWordIndex(block.words, currentTimeMs);
const positionStyle = POSITION_MAP[position] ?? POSITION_MAP.bottom;
const fontStack = getFontStack(style.fontFamily);
// Background box style
const hasBg = style.bgOpacity > 0;
const bgStyle: React.CSSProperties = hasBg
? {
backgroundColor: `${style.bgColor}${Math.round(style.bgOpacity * 255)
.toString(16)
.padStart(2, "0")}`,
borderRadius: 8,
padding: "8px 16px",
}
: {};
return (
<div
style={{
position: "absolute",
left: 0,
right: 0,
display: "flex",
justifyContent: "center",
...positionStyle,
}}
>
<div
style={{
display: "flex",
flexWrap: "wrap",
justifyContent: "center",
gap: "6px 8px",
maxWidth: "85%",
...bgStyle,
}}
>
{block.words.map((word, i) => (
<WordSpan
key={i}
word={word.text}
isActive={i === activeIndex}
style={style}
fontStack={fontStack}
animation={style.animation}
frame={frame}
fps={fps}
wordStartMs={word.startMs}
blockStartMs={blockStartMs}
/>
))}
</div>
</div>
);
};
interface WordSpanProps {
word: string;
isActive: boolean;
style: SubtitleConfig["style"];
fontStack: string;
animation: SubtitleConfig["style"]["animation"];
frame: number;
fps: number;
wordStartMs: number;
blockStartMs: number;
}
const WordSpan: React.FC<WordSpanProps> = ({
word,
isActive,
style,
fontStack,
animation,
frame,
fps,
wordStartMs,
blockStartMs,
}) => {
const wordStartFrame = Math.round(
((wordStartMs - blockStartMs) / 1000) * fps
);
let transform = "";
let color = style.fontColor;
let extraStyle: React.CSSProperties = {};
if (isActive) {
color = style.highlightColor;
switch (animation) {
case "pop": {
const scale = spring({
frame: frame - wordStartFrame,
fps,
config: { mass: 0.5, stiffness: 300, damping: 12 },
durationInFrames: 10,
});
const scaleValue = interpolate(scale, [0, 1], [1, 1.25]);
transform = `scale(${scaleValue})`;
break;
}
case "karaoke": {
extraStyle = {
backgroundColor: style.highlightColor,
color: style.bgColor || "#000000",
borderRadius: 4,
padding: "2px 6px",
};
break;
}
case "word-highlight": {
extraStyle = {
textShadow: `0 0 12px ${style.highlightColor}, 0 0 24px ${style.highlightColor}40`,
};
break;
}
default:
break;
}
}
// Text stroke via textShadow (CSS paint-order not reliable in Remotion)
const strokeShadow =
style.borderWidth > 0
? [
`${style.borderWidth}px 0 0 ${style.borderColor}`,
`-${style.borderWidth}px 0 0 ${style.borderColor}`,
`0 ${style.borderWidth}px 0 ${style.borderColor}`,
`0 -${style.borderWidth}px 0 ${style.borderColor}`,
].join(", ")
: "none";
return (
<span
style={{
fontFamily: fontStack,
fontSize: style.fontSize,
fontWeight: 700,
color: animation === "karaoke" && isActive ? undefined : color,
textShadow:
animation !== "karaoke"
? [strokeShadow, extraStyle.textShadow].filter(Boolean).join(", ")
: strokeShadow,
transform,
display: "inline-block",
transition: "none",
...extraStyle,
}}
>
{word}
</span>
);
};

View file

@ -0,0 +1,209 @@
import React from "react";
import { useCurrentFrame, useVideoConfig, interpolate } from "remotion";
import type { EffectsConfig, EffectSegment } from "../lib/types";
interface VideoEffectsProps {
config: EffectsConfig | null;
children: React.ReactNode;
}
/**
* Wraps children (typically <OffthreadVideo>) with dynamic CSS transforms and filters.
* Interpolates smoothly between effect segments.
*/
export const VideoEffects: React.FC<VideoEffectsProps> = ({
config,
children,
}) => {
const frame = useCurrentFrame();
const { fps } = useVideoConfig();
if (!config || config.segments.length === 0) {
return <>{children}</>;
}
const currentTimeSec = frame / fps;
const { zoom, centerX, centerY, brightness, contrast, saturate } =
getInterpolatedValues(config.segments, currentTimeSec, frame, fps);
const filterParts: string[] = [];
if (brightness !== 1) filterParts.push(`brightness(${brightness})`);
if (contrast !== 1) filterParts.push(`contrast(${contrast})`);
if (saturate !== 1) filterParts.push(`saturate(${saturate})`);
const filterStr = filterParts.length > 0 ? filterParts.join(" ") : "none";
return (
<div
style={{
width: "100%",
height: "100%",
overflow: "hidden",
position: "relative",
}}
>
<div
style={{
width: "100%",
height: "100%",
transform: `scale(${zoom})`,
transformOrigin: `${centerX * 100}% ${centerY * 100}%`,
filter: filterStr,
}}
>
{children}
</div>
</div>
);
};
interface InterpolatedValues {
zoom: number;
centerX: number;
centerY: number;
brightness: number;
contrast: number;
saturate: number;
}
function getInterpolatedValues(
segments: EffectSegment[],
timeSec: number,
frame: number,
fps: number
): InterpolatedValues {
// Default values (no effect)
const defaults: InterpolatedValues = {
zoom: 1,
centerX: 0.5,
centerY: 0.5,
brightness: 1,
contrast: 1,
saturate: 1,
};
// Find active segment
const active = segments.find(
(s) => timeSec >= s.startSec && timeSec < s.endSec
);
if (!active) {
// Check if we're transitioning between segments (smooth fade)
const prev = segments.filter((s) => s.endSec <= timeSec).pop();
const next = segments.find((s) => s.startSec > timeSec);
if (prev && next) {
const gap = next.startSec - prev.endSec;
if (gap < 1.0) {
// Short gap: interpolate between prev and next
const progress = (timeSec - prev.endSec) / gap;
return lerpSegments(prev, next, progress);
}
}
// Transition out from previous segment
if (prev) {
const fadeOutDuration = 0.3; // seconds
const elapsed = timeSec - prev.endSec;
if (elapsed < fadeOutDuration) {
const progress = elapsed / fadeOutDuration;
return lerpToDefaults(prev, progress, defaults);
}
}
// Transition into next segment
if (next) {
const fadeInDuration = 0.3;
const remaining = next.startSec - timeSec;
if (remaining < fadeInDuration) {
const progress = 1 - remaining / fadeInDuration;
return lerpFromDefaults(next, progress, defaults);
}
}
return defaults;
}
// Inside active segment: smooth entrance/exit at edges
const segDuration = active.endSec - active.startSec;
const transitionSec = Math.min(0.3, segDuration * 0.15);
const startFrame = Math.round(active.startSec * fps);
const endFrame = Math.round(active.endSec * fps);
const transitionFrames = Math.round(transitionSec * fps);
// Entrance ease
const entranceFactor = interpolate(
frame,
[startFrame, startFrame + transitionFrames],
[0, 1],
{ extrapolateLeft: "clamp", extrapolateRight: "clamp" }
);
// Exit ease
const exitFactor = interpolate(
frame,
[endFrame - transitionFrames, endFrame],
[1, 0],
{ extrapolateLeft: "clamp", extrapolateRight: "clamp" }
);
const factor = Math.min(entranceFactor, exitFactor);
return {
zoom: lerp(1, active.zoom, factor),
centerX: lerp(0.5, active.zoomCenterX, factor),
centerY: lerp(0.5, active.zoomCenterY, factor),
brightness: lerp(1, active.brightness, factor),
contrast: lerp(1, active.contrast, factor),
saturate: lerp(1, active.saturate, factor),
};
}
function lerp(a: number, b: number, t: number): number {
return a + (b - a) * t;
}
function lerpSegments(
a: EffectSegment,
b: EffectSegment,
t: number
): InterpolatedValues {
return {
zoom: lerp(a.zoom, b.zoom, t),
centerX: lerp(a.zoomCenterX, b.zoomCenterX, t),
centerY: lerp(a.zoomCenterY, b.zoomCenterY, t),
brightness: lerp(a.brightness, b.brightness, t),
contrast: lerp(a.contrast, b.contrast, t),
saturate: lerp(a.saturate, b.saturate, t),
};
}
function lerpToDefaults(
seg: EffectSegment,
t: number,
defaults: InterpolatedValues
): InterpolatedValues {
return {
zoom: lerp(seg.zoom, defaults.zoom, t),
centerX: lerp(seg.zoomCenterX, defaults.centerX, t),
centerY: lerp(seg.zoomCenterY, defaults.centerY, t),
brightness: lerp(seg.brightness, defaults.brightness, t),
contrast: lerp(seg.contrast, defaults.contrast, t),
saturate: lerp(seg.saturate, defaults.saturate, t),
};
}
function lerpFromDefaults(
seg: EffectSegment,
t: number,
defaults: InterpolatedValues
): InterpolatedValues {
return {
zoom: lerp(defaults.zoom, seg.zoom, t),
centerX: lerp(defaults.centerX, seg.zoomCenterX, t),
centerY: lerp(defaults.centerY, seg.zoomCenterY, t),
brightness: lerp(defaults.brightness, seg.brightness, t),
contrast: lerp(defaults.contrast, seg.contrast, t),
saturate: lerp(defaults.saturate, seg.saturate, t),
};
}

View file

@ -0,0 +1,83 @@
import type { CaptionWord } from "./types";
export interface CaptionBlock {
words: CaptionWord[];
startMs: number;
endMs: number;
text: string;
}
/**
* Groups word-level captions into display blocks.
* Same logic as OpenShorts' generate_srt: max chars per block, max duration per block.
*/
export function groupCaptionsIntoBlocks(
captions: CaptionWord[],
maxChars = 20,
maxDurationMs = 2000
): CaptionBlock[] {
const blocks: CaptionBlock[] = [];
let currentWords: CaptionWord[] = [];
let blockStartMs = 0;
for (const word of captions) {
if (currentWords.length === 0) {
currentWords.push(word);
blockStartMs = word.startMs;
continue;
}
const currentTextLen = currentWords.reduce(
(sum, w) => sum + w.text.length + 1,
0
);
const duration = word.endMs - blockStartMs;
if (
currentTextLen + word.text.length > maxChars ||
duration > maxDurationMs
) {
// Finalize current block
const lastWord = currentWords[currentWords.length - 1];
blocks.push({
words: [...currentWords],
startMs: blockStartMs,
endMs: lastWord.endMs,
text: currentWords.map((w) => w.text).join(" "),
});
currentWords = [word];
blockStartMs = word.startMs;
} else {
currentWords.push(word);
}
}
// Final block
if (currentWords.length > 0) {
const lastWord = currentWords[currentWords.length - 1];
blocks.push({
words: [...currentWords],
startMs: blockStartMs,
endMs: lastWord.endMs,
text: currentWords.map((w) => w.text).join(" "),
});
}
return blocks;
}
/**
* Find the active word at a given time in milliseconds.
*/
export function getActiveWordIndex(
words: CaptionWord[],
timeMs: number
): number {
for (let i = 0; i < words.length; i++) {
if (timeMs >= words[i].startMs && timeMs < words[i].endMs) {
return i;
}
}
return -1;
}

View file

@ -0,0 +1,33 @@
import { staticFile } from "remotion";
/**
* CSS @font-face declaration for NotoSerif-Bold (bundled locally).
* Use in components via: <style>{notoSerifFontFace}</style>
*/
export const NOTO_SERIF_FONT_FAMILY = "NotoSerif-Bold";
export const notoSerifFontFace = `
@font-face {
font-family: '${NOTO_SERIF_FONT_FAMILY}';
src: url('${staticFile("fonts/NotoSerif-Bold.ttf")}') format('truetype');
font-weight: 700;
font-style: normal;
}
`;
/**
* Map of subtitle font families to their CSS-safe names.
* These match the options available in SubtitleModal.jsx.
*/
export const SUBTITLE_FONTS: Record<string, string> = {
Verdana: "Verdana, Geneva, sans-serif",
Arial: "Arial, Helvetica, sans-serif",
Impact: "Impact, Haettenschweiler, sans-serif",
Helvetica: "Helvetica, Arial, sans-serif",
Georgia: "Georgia, 'Times New Roman', serif",
"Courier New": "'Courier New', Courier, monospace",
};
export function getFontStack(fontFamily: string): string {
return SUBTITLE_FONTS[fontFamily] ?? fontFamily;
}

View file

@ -0,0 +1,130 @@
import { z } from "zod";
// --- Word-level caption ---
export interface CaptionWord {
text: string;
startMs: number;
endMs: number;
}
// --- Subtitle config ---
export type SubtitleAnimation = "none" | "word-highlight" | "pop" | "karaoke";
export type SubtitlePosition = "top" | "middle" | "bottom";
export interface SubtitleStyle {
fontFamily: string;
fontSize: number;
fontColor: string;
highlightColor: string;
borderColor: string;
borderWidth: number;
bgColor: string;
bgOpacity: number;
animation: SubtitleAnimation;
}
export interface SubtitleConfig {
captions: CaptionWord[];
position: SubtitlePosition;
style: SubtitleStyle;
}
// --- Hook config ---
export type HookPosition = "top" | "center" | "bottom";
export type HookSize = "S" | "M" | "L";
export type HookEntrance = "spring" | "fade" | "slide-up" | "none";
export interface HookConfig {
text: string;
position: HookPosition;
size: HookSize;
entranceAnimation: HookEntrance;
displayDurationSec: number;
}
// --- Effects config ---
export interface EffectSegment {
startSec: number;
endSec: number;
zoom: number;
zoomCenterX: number;
zoomCenterY: number;
brightness: number;
contrast: number;
saturate: number;
}
export interface EffectsConfig {
segments: EffectSegment[];
}
// --- Main composition props ---
export interface ShortVideoProps {
videoUrl: string;
durationInFrames: number;
fps: number;
width: number;
height: number;
subtitles: SubtitleConfig | null;
hook: HookConfig | null;
effects: EffectsConfig | null;
}
// --- Zod schemas for validation (used by render service) ---
export const captionWordSchema = z.object({
text: z.string(),
startMs: z.number(),
endMs: z.number(),
});
export const subtitleStyleSchema = z.object({
fontFamily: z.string(),
fontSize: z.number(),
fontColor: z.string(),
highlightColor: z.string(),
borderColor: z.string(),
borderWidth: z.number(),
bgColor: z.string(),
bgOpacity: z.number().min(0).max(1),
animation: z.enum(["none", "word-highlight", "pop", "karaoke"]),
});
export const subtitleConfigSchema = z.object({
captions: z.array(captionWordSchema),
position: z.enum(["top", "middle", "bottom"]),
style: subtitleStyleSchema,
});
export const hookConfigSchema = z.object({
text: z.string(),
position: z.enum(["top", "center", "bottom"]),
size: z.enum(["S", "M", "L"]),
entranceAnimation: z.enum(["spring", "fade", "slide-up", "none"]),
displayDurationSec: z.number().positive(),
});
export const effectSegmentSchema = z.object({
startSec: z.number().min(0),
endSec: z.number().positive(),
zoom: z.number().min(0.5).max(3),
zoomCenterX: z.number().min(0).max(1),
zoomCenterY: z.number().min(0).max(1),
brightness: z.number().min(0).max(3),
contrast: z.number().min(0).max(3),
saturate: z.number().min(0).max(3),
});
export const effectsConfigSchema = z.object({
segments: z.array(effectSegmentSchema),
});
export const shortVideoPropsSchema = z.object({
videoUrl: z.string(),
durationInFrames: z.number().int().positive(),
fps: z.number().positive(),
width: z.number().int().positive(),
height: z.number().int().positive(),
subtitles: subtitleConfigSchema.nullable(),
hook: hookConfigSchema.nullable(),
effects: effectsConfigSchema.nullable(),
});

View file

@ -29,6 +29,10 @@ export default defineConfig({
'/video': { '/video': {
target: 'http://backend:8000', target: 'http://backend:8000',
changeOrigin: true, changeOrigin: true,
},
'/render': {
target: 'http://renderer:3100',
changeOrigin: true,
} }
} }
} }

View file

@ -7,6 +7,7 @@ services:
volumes: volumes:
- .:/app - .:/app
- /app/__pycache__ - /app/__pycache__
- ./output:/app/output
restart: unless-stopped restart: unless-stopped
frontend: frontend:
@ -20,3 +21,20 @@ services:
restart: unless-stopped restart: unless-stopped
depends_on: depends_on:
- backend - backend
renderer:
build:
context: .
dockerfile: render-service/Dockerfile
container_name: openshorts-renderer
ports:
- "3100:3100"
volumes:
- ./output:/output
environment:
- REMOTION_BUNDLE_PATH=/app/remotion
- OUTPUT_DIR=/output
- PORT=3100
restart: unless-stopped
depends_on:
- backend

View file

@ -150,6 +150,101 @@ class VideoEditor:
print(f"❌ Failed to parse JSON: {response.text}") print(f"❌ Failed to parse JSON: {response.text}")
return None return None
def get_effects_config(self, video_file_obj, duration, fps=30, width=None, height=None, transcript=None):
"""Asks Gemini for a structured EffectsConfig JSON for Remotion rendering."""
if width is None or height is None:
width, height = 1080, 1920
transcript_text = json.dumps(transcript) if transcript else "Not available."
prompt = f"""
You are an expert video editor analyzing a video and its transcript to generate dynamic visual effects for a Remotion-based renderer.
Video Duration: {duration} seconds.
Video FPS: {fps}
Video Resolution: {width}x{height}
TRANSCRIPT (Context of what is being said):
{transcript_text}
Your task is to produce a structured JSON describing time-based effect segments that cover the FULL video duration.
Each segment has these fields:
- "startSec" (number): Start time in seconds.
- "endSec" (number): End time in seconds.
- "zoom" (number): Zoom level. 1.0 = no zoom, max 1.5. Use subtle values like 1.05-1.2 for most cases.
- "zoomCenterX" (number): Horizontal focus point for zoom, 0.0 (left) to 1.0 (right). 0.5 = center.
- "zoomCenterY" (number): Vertical focus point for zoom, 0.0 (top) to 1.0 (bottom). 0.5 = center.
- "brightness" (number): Brightness multiplier. 1.0 = normal. Range 0.8-1.2.
- "contrast" (number): Contrast multiplier. 1.0 = normal. Range 0.8-1.3.
- "saturate" (number): Saturation multiplier. 1.0 = normal. Range 0.8-1.3.
Instructions:
1. ANALYZE the video content and transcript to understand mood, pacing, and key moments.
2. Apply CONTEXTUAL effects aligned with speech and action:
- Use slow, subtle zooms toward the speaker's face during speaking moments.
- Emphasize key moments, punchlines, or dramatic beats with slightly stronger zoom or contrast.
- Keep transitions smooth — avoid jarring jumps between segments.
- If nothing significant is happening, keep values at defaults (zoom 1.0, all multipliers 1.0).
3. Segments MUST cover the entire video duration from 0 to {duration} seconds with no gaps.
4. Prefer fewer, longer segments with gradual changes over many rapid short segments.
5. Output ONLY valid JSON, no explanations.
Output format:
{{
"segments": [
{{
"startSec": 0,
"endSec": 3.5,
"zoom": 1.0,
"zoomCenterX": 0.5,
"zoomCenterY": 0.5,
"brightness": 1.0,
"contrast": 1.0,
"saturate": 1.0
}}
]
}}
"""
print("🤖 Asking Gemini for Remotion effects config...")
response = self.client.models.generate_content(
model=self.model_name,
contents=[video_file_obj, prompt],
config=types.GenerateContentConfig(
response_mime_type="application/json"
)
)
print(f"🔍 DEBUG: Gemini Raw Response:\n{response.text}")
try:
# Clean response text (remove potential markdown blocks)
text = response.text
if text.startswith("```json"):
text = text[7:]
elif text.startswith("```"):
text = text[3:]
if text.endswith("```"):
text = text[:-3]
text = text.strip()
# Find the first '{' and last '}'
start_idx = text.find('{')
end_idx = text.rfind('}')
if start_idx != -1 and end_idx != -1:
text = text[start_idx:end_idx+1]
print(f"🔍 DEBUG: Cleaned JSON Text:\n{text}")
return json.loads(text)
except json.JSONDecodeError:
print(f"❌ Failed to parse effects config JSON: {response.text}")
return None
@staticmethod @staticmethod
def _split_filter_chain(filter_string: str) -> list[str]: def _split_filter_chain(filter_string: str) -> list[str]:
"""Split a -vf filter chain on commas, respecting single-quoted substrings.""" """Split a -vf filter chain on commas, respecting single-quoted substrings."""

2
remotion/.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
node_modules/
dist/

27
remotion/package.json Normal file
View file

@ -0,0 +1,27 @@
{
"name": "openshorts-remotion",
"version": "1.0.0",
"private": true,
"type": "module",
"scripts": {
"studio": "remotion studio",
"render": "remotion render",
"build": "tsc --noEmit"
},
"dependencies": {
"@remotion/cli": "^4.0.0",
"@remotion/google-fonts": "^4.0.0",
"@remotion/layout-utils": "^4.0.0",
"@remotion/media": "^4.0.447",
"@remotion/player": "^4.0.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"remotion": "^4.0.0",
"zod": "^4.3.6"
},
"devDependencies": {
"@types/react": "^18.2.64",
"@types/react-dom": "^18.2.21",
"typescript": "^5.4.0"
}
}

Binary file not shown.

90
remotion/src/Root.tsx Normal file
View file

@ -0,0 +1,90 @@
import React from "react";
import { Composition } from "remotion";
import { ShortVideo } from "./compositions/ShortVideo";
import type { ShortVideoProps } from "./lib/types";
import { shortVideoPropsSchema } from "./lib/types";
const DEFAULT_PROPS: ShortVideoProps = {
videoUrl: "",
durationInFrames: 900, // 30s at 30fps
fps: 30,
width: 1080,
height: 1920,
subtitles: {
captions: [
{ text: "This", startMs: 0, endMs: 400 },
{ text: "is", startMs: 400, endMs: 600 },
{ text: "a", startMs: 600, endMs: 750 },
{ text: "demo", startMs: 750, endMs: 1200 },
{ text: "of", startMs: 1200, endMs: 1400 },
{ text: "animated", startMs: 1400, endMs: 2000 },
{ text: "subtitles", startMs: 2000, endMs: 2800 },
{ text: "in", startMs: 2800, endMs: 3000 },
{ text: "Remotion", startMs: 3000, endMs: 3800 },
{ text: "with", startMs: 4000, endMs: 4300 },
{ text: "word", startMs: 4300, endMs: 4700 },
{ text: "level", startMs: 4700, endMs: 5100 },
{ text: "highlighting", startMs: 5100, endMs: 6000 },
],
position: "bottom",
style: {
fontFamily: "Arial",
fontSize: 52,
fontColor: "#FFFFFF",
highlightColor: "#FFDD00",
borderColor: "#000000",
borderWidth: 3,
bgColor: "#000000",
bgOpacity: 0,
animation: "pop",
},
},
hook: {
text: "POV: You just discovered OpenShorts",
position: "top",
size: "M",
entranceAnimation: "spring",
displayDurationSec: 5,
},
effects: {
segments: [
{
startSec: 2,
endSec: 5,
zoom: 1.2,
zoomCenterX: 0.5,
zoomCenterY: 0.35,
brightness: 1.05,
contrast: 1.1,
saturate: 1.15,
},
{
startSec: 8,
endSec: 12,
zoom: 1.15,
zoomCenterX: 0.5,
zoomCenterY: 0.4,
brightness: 1,
contrast: 1,
saturate: 1,
},
],
},
};
export const RemotionRoot: React.FC = () => {
return (
<>
<Composition
id="ShortVideo"
schema={shortVideoPropsSchema}
component={ShortVideo}
durationInFrames={DEFAULT_PROPS.durationInFrames}
fps={DEFAULT_PROPS.fps}
width={DEFAULT_PROPS.width}
height={DEFAULT_PROPS.height}
defaultProps={DEFAULT_PROPS}
/>
</>
);
};

View file

@ -0,0 +1,144 @@
import React from "react";
import {
AbsoluteFill,
Sequence,
useCurrentFrame,
useVideoConfig,
spring,
interpolate,
} from "remotion";
import type { HookConfig } from "../lib/types";
import { notoSerifFontFace, NOTO_SERIF_FONT_FAMILY } from "../lib/fonts";
interface HookOverlayProps {
config: HookConfig;
}
const SIZE_SCALE: Record<string, number> = {
S: 0.8,
M: 1.0,
L: 1.3,
};
const POSITION_STYLE: Record<string, React.CSSProperties> = {
top: { top: "18%", bottom: "auto" },
center: { top: "50%", bottom: "auto", transform: "translateY(-50%)" },
bottom: { top: "68%", bottom: "auto" },
};
export const HookOverlay: React.FC<HookOverlayProps> = ({ config }) => {
const { fps } = useVideoConfig();
const displayFrames = Math.round(config.displayDurationSec * fps);
return (
<AbsoluteFill>
<style>{notoSerifFontFace}</style>
<Sequence from={0} durationInFrames={displayFrames} layout="none">
<HookBox config={config} displayFrames={displayFrames} />
</Sequence>
</AbsoluteFill>
);
};
interface HookBoxProps {
config: HookConfig;
displayFrames: number;
}
const HookBox: React.FC<HookBoxProps> = ({ config, displayFrames }) => {
const frame = useCurrentFrame();
const { fps } = useVideoConfig();
const scale = SIZE_SCALE[config.size] ?? 1.0;
// Entrance animation
let animOpacity = 1;
let animScale = 1;
let animTranslateY = 0;
switch (config.entranceAnimation) {
case "spring": {
const prog = spring({
frame,
fps,
config: { mass: 0.8, stiffness: 200, damping: 15 },
durationInFrames: 20,
});
animScale = interpolate(prog, [0, 1], [0.7, 1]);
animOpacity = interpolate(prog, [0, 1], [0, 1]);
break;
}
case "fade": {
animOpacity = interpolate(frame, [0, 15], [0, 1], {
extrapolateRight: "clamp",
});
break;
}
case "slide-up": {
const prog = spring({
frame,
fps,
config: { mass: 1, stiffness: 150, damping: 18 },
durationInFrames: 20,
});
animTranslateY = interpolate(prog, [0, 1], [60, 0]);
animOpacity = interpolate(prog, [0, 1], [0, 1]);
break;
}
default:
break;
}
// Exit fade (last 15 frames)
const fadeOutStart = displayFrames - 15;
if (frame > fadeOutStart) {
animOpacity *= interpolate(frame, [fadeOutStart, displayFrames], [1, 0], {
extrapolateLeft: "clamp",
extrapolateRight: "clamp",
});
}
const positionStyle = POSITION_STYLE[config.position] ?? POSITION_STYLE.top;
// Base font size: 5% of 1080 width (matches hooks.py logic)
const baseFontSize = 1080 * 0.05;
const fontSize = Math.round(baseFontSize * scale);
return (
<div
style={{
position: "absolute",
left: 0,
right: 0,
display: "flex",
justifyContent: "center",
...positionStyle,
}}
>
<div
style={{
opacity: animOpacity,
transform: `scale(${animScale}) translateY(${animTranslateY}px)`,
maxWidth: "90%",
backgroundColor: "rgba(255, 255, 255, 0.94)",
borderRadius: 20,
padding: `${25 * scale}px ${30 * scale}px`,
boxShadow: "5px 5px 15px rgba(0, 0, 0, 0.25)",
textAlign: "center",
}}
>
<span
style={{
fontFamily: `'${NOTO_SERIF_FONT_FAMILY}', 'Noto Serif', Georgia, serif`,
fontSize,
fontWeight: 700,
color: "#000000",
lineHeight: 1.4,
wordBreak: "break-word",
}}
>
{config.text}
</span>
</div>
</div>
);
};

View file

@ -0,0 +1,33 @@
import React from "react";
import { AbsoluteFill } from "remotion";
import { Video } from "@remotion/media";
import type { ShortVideoProps } from "../lib/types";
import { Subtitles } from "./Subtitles";
import { HookOverlay } from "./HookOverlay";
import { VideoEffects } from "./VideoEffects";
/**
* Main composition that layers all post-processing on top of the base video.
* Uses @remotion/media Video for browser-side rendering compatibility.
*/
export const ShortVideo: React.FC<Record<string, unknown>> = (rawProps) => {
const { videoUrl, subtitles, hook, effects } =
rawProps as unknown as ShortVideoProps;
return (
<AbsoluteFill style={{ backgroundColor: "#000" }}>
{/* Layer 1: Base video with optional zoom/color effects */}
<VideoEffects config={effects}>
<Video
src={videoUrl}
style={{ width: "100%", height: "100%", objectFit: "cover" }}
/>
</VideoEffects>
{/* Layer 2: Animated subtitles */}
{subtitles && <Subtitles config={subtitles} />}
{/* Layer 3: Hook text overlay */}
{hook && <HookOverlay config={hook} />}
</AbsoluteFill>
);
};

View file

@ -0,0 +1,227 @@
import React from "react";
import {
AbsoluteFill,
Sequence,
useCurrentFrame,
useVideoConfig,
spring,
interpolate,
} from "remotion";
import type { SubtitleConfig } from "../lib/types";
import { groupCaptionsIntoBlocks, getActiveWordIndex } from "../lib/captions";
import { getFontStack } from "../lib/fonts";
interface SubtitlesProps {
config: SubtitleConfig;
}
const POSITION_MAP: Record<string, React.CSSProperties> = {
top: { top: "12%", bottom: "auto" },
middle: { top: "45%", bottom: "auto" },
bottom: { bottom: "10%", top: "auto" },
};
export const Subtitles: React.FC<SubtitlesProps> = ({ config }) => {
const { fps } = useVideoConfig();
const blocks = groupCaptionsIntoBlocks(config.captions);
return (
<AbsoluteFill>
{blocks.map((block, i) => {
const startFrame = Math.round((block.startMs / 1000) * fps);
const durationFrames = Math.max(
1,
Math.round(((block.endMs - block.startMs) / 1000) * fps)
);
return (
<Sequence
key={i}
from={startFrame}
durationInFrames={durationFrames}
layout="none"
>
<SubtitleBlock
block={block}
config={config}
blockStartMs={block.startMs}
/>
</Sequence>
);
})}
</AbsoluteFill>
);
};
interface SubtitleBlockProps {
block: ReturnType<typeof groupCaptionsIntoBlocks>[number];
config: SubtitleConfig;
blockStartMs: number;
}
const SubtitleBlock: React.FC<SubtitleBlockProps> = ({
block,
config,
blockStartMs,
}) => {
const frame = useCurrentFrame();
const { fps } = useVideoConfig();
const { style, position } = config;
// Current time relative to composition start (sequence-relative frame)
const currentTimeMs = blockStartMs + (frame / fps) * 1000;
const activeIndex = getActiveWordIndex(block.words, currentTimeMs);
const positionStyle = POSITION_MAP[position] ?? POSITION_MAP.bottom;
const fontStack = getFontStack(style.fontFamily);
// Background box style
const hasBg = style.bgOpacity > 0;
const bgStyle: React.CSSProperties = hasBg
? {
backgroundColor: `${style.bgColor}${Math.round(style.bgOpacity * 255)
.toString(16)
.padStart(2, "0")}`,
borderRadius: 8,
padding: "8px 16px",
}
: {};
return (
<div
style={{
position: "absolute",
left: 0,
right: 0,
display: "flex",
justifyContent: "center",
...positionStyle,
}}
>
<div
style={{
display: "flex",
flexWrap: "wrap",
justifyContent: "center",
gap: "6px 8px",
maxWidth: "85%",
...bgStyle,
}}
>
{block.words.map((word, i) => (
<WordSpan
key={i}
word={word.text}
isActive={i === activeIndex}
style={style}
fontStack={fontStack}
animation={style.animation}
frame={frame}
fps={fps}
wordStartMs={word.startMs}
blockStartMs={blockStartMs}
/>
))}
</div>
</div>
);
};
interface WordSpanProps {
word: string;
isActive: boolean;
style: SubtitleConfig["style"];
fontStack: string;
animation: SubtitleConfig["style"]["animation"];
frame: number;
fps: number;
wordStartMs: number;
blockStartMs: number;
}
const WordSpan: React.FC<WordSpanProps> = ({
word,
isActive,
style,
fontStack,
animation,
frame,
fps,
wordStartMs,
blockStartMs,
}) => {
const wordStartFrame = Math.round(
((wordStartMs - blockStartMs) / 1000) * fps
);
let transform = "";
let color = style.fontColor;
let extraStyle: React.CSSProperties = {};
if (isActive) {
color = style.highlightColor;
switch (animation) {
case "pop": {
const scale = spring({
frame: frame - wordStartFrame,
fps,
config: { mass: 0.5, stiffness: 300, damping: 12 },
durationInFrames: 10,
});
const scaleValue = interpolate(scale, [0, 1], [1, 1.25]);
transform = `scale(${scaleValue})`;
break;
}
case "karaoke": {
extraStyle = {
backgroundColor: style.highlightColor,
color: style.bgColor || "#000000",
borderRadius: 4,
padding: "2px 6px",
};
break;
}
case "word-highlight": {
extraStyle = {
textShadow: `0 0 12px ${style.highlightColor}, 0 0 24px ${style.highlightColor}40`,
};
break;
}
default:
break;
}
}
// Text stroke via textShadow (CSS paint-order not reliable in Remotion)
const strokeShadow =
style.borderWidth > 0
? [
`${style.borderWidth}px 0 0 ${style.borderColor}`,
`-${style.borderWidth}px 0 0 ${style.borderColor}`,
`0 ${style.borderWidth}px 0 ${style.borderColor}`,
`0 -${style.borderWidth}px 0 ${style.borderColor}`,
].join(", ")
: "none";
return (
<span
style={{
fontFamily: fontStack,
fontSize: style.fontSize,
fontWeight: 700,
color: animation === "karaoke" && isActive ? undefined : color,
textShadow:
animation !== "karaoke"
? [strokeShadow, extraStyle.textShadow].filter(Boolean).join(", ")
: strokeShadow,
transform,
display: "inline-block",
transition: "none",
...extraStyle,
}}
>
{word}
</span>
);
};

View file

@ -0,0 +1,209 @@
import React from "react";
import { useCurrentFrame, useVideoConfig, interpolate } from "remotion";
import type { EffectsConfig, EffectSegment } from "../lib/types";
interface VideoEffectsProps {
config: EffectsConfig | null;
children: React.ReactNode;
}
/**
* Wraps children (typically <OffthreadVideo>) with dynamic CSS transforms and filters.
* Interpolates smoothly between effect segments.
*/
export const VideoEffects: React.FC<VideoEffectsProps> = ({
config,
children,
}) => {
const frame = useCurrentFrame();
const { fps } = useVideoConfig();
if (!config || config.segments.length === 0) {
return <>{children}</>;
}
const currentTimeSec = frame / fps;
const { zoom, centerX, centerY, brightness, contrast, saturate } =
getInterpolatedValues(config.segments, currentTimeSec, frame, fps);
const filterParts: string[] = [];
if (brightness !== 1) filterParts.push(`brightness(${brightness})`);
if (contrast !== 1) filterParts.push(`contrast(${contrast})`);
if (saturate !== 1) filterParts.push(`saturate(${saturate})`);
const filterStr = filterParts.length > 0 ? filterParts.join(" ") : "none";
return (
<div
style={{
width: "100%",
height: "100%",
overflow: "hidden",
position: "relative",
}}
>
<div
style={{
width: "100%",
height: "100%",
transform: `scale(${zoom})`,
transformOrigin: `${centerX * 100}% ${centerY * 100}%`,
filter: filterStr,
}}
>
{children}
</div>
</div>
);
};
interface InterpolatedValues {
zoom: number;
centerX: number;
centerY: number;
brightness: number;
contrast: number;
saturate: number;
}
function getInterpolatedValues(
segments: EffectSegment[],
timeSec: number,
frame: number,
fps: number
): InterpolatedValues {
// Default values (no effect)
const defaults: InterpolatedValues = {
zoom: 1,
centerX: 0.5,
centerY: 0.5,
brightness: 1,
contrast: 1,
saturate: 1,
};
// Find active segment
const active = segments.find(
(s) => timeSec >= s.startSec && timeSec < s.endSec
);
if (!active) {
// Check if we're transitioning between segments (smooth fade)
const prev = segments.filter((s) => s.endSec <= timeSec).pop();
const next = segments.find((s) => s.startSec > timeSec);
if (prev && next) {
const gap = next.startSec - prev.endSec;
if (gap < 1.0) {
// Short gap: interpolate between prev and next
const progress = (timeSec - prev.endSec) / gap;
return lerpSegments(prev, next, progress);
}
}
// Transition out from previous segment
if (prev) {
const fadeOutDuration = 0.3; // seconds
const elapsed = timeSec - prev.endSec;
if (elapsed < fadeOutDuration) {
const progress = elapsed / fadeOutDuration;
return lerpToDefaults(prev, progress, defaults);
}
}
// Transition into next segment
if (next) {
const fadeInDuration = 0.3;
const remaining = next.startSec - timeSec;
if (remaining < fadeInDuration) {
const progress = 1 - remaining / fadeInDuration;
return lerpFromDefaults(next, progress, defaults);
}
}
return defaults;
}
// Inside active segment: smooth entrance/exit at edges
const segDuration = active.endSec - active.startSec;
const transitionSec = Math.min(0.3, segDuration * 0.15);
const startFrame = Math.round(active.startSec * fps);
const endFrame = Math.round(active.endSec * fps);
const transitionFrames = Math.round(transitionSec * fps);
// Entrance ease
const entranceFactor = interpolate(
frame,
[startFrame, startFrame + transitionFrames],
[0, 1],
{ extrapolateLeft: "clamp", extrapolateRight: "clamp" }
);
// Exit ease
const exitFactor = interpolate(
frame,
[endFrame - transitionFrames, endFrame],
[1, 0],
{ extrapolateLeft: "clamp", extrapolateRight: "clamp" }
);
const factor = Math.min(entranceFactor, exitFactor);
return {
zoom: lerp(1, active.zoom, factor),
centerX: lerp(0.5, active.zoomCenterX, factor),
centerY: lerp(0.5, active.zoomCenterY, factor),
brightness: lerp(1, active.brightness, factor),
contrast: lerp(1, active.contrast, factor),
saturate: lerp(1, active.saturate, factor),
};
}
function lerp(a: number, b: number, t: number): number {
return a + (b - a) * t;
}
function lerpSegments(
a: EffectSegment,
b: EffectSegment,
t: number
): InterpolatedValues {
return {
zoom: lerp(a.zoom, b.zoom, t),
centerX: lerp(a.zoomCenterX, b.zoomCenterX, t),
centerY: lerp(a.zoomCenterY, b.zoomCenterY, t),
brightness: lerp(a.brightness, b.brightness, t),
contrast: lerp(a.contrast, b.contrast, t),
saturate: lerp(a.saturate, b.saturate, t),
};
}
function lerpToDefaults(
seg: EffectSegment,
t: number,
defaults: InterpolatedValues
): InterpolatedValues {
return {
zoom: lerp(seg.zoom, defaults.zoom, t),
centerX: lerp(seg.zoomCenterX, defaults.centerX, t),
centerY: lerp(seg.zoomCenterY, defaults.centerY, t),
brightness: lerp(seg.brightness, defaults.brightness, t),
contrast: lerp(seg.contrast, defaults.contrast, t),
saturate: lerp(seg.saturate, defaults.saturate, t),
};
}
function lerpFromDefaults(
seg: EffectSegment,
t: number,
defaults: InterpolatedValues
): InterpolatedValues {
return {
zoom: lerp(defaults.zoom, seg.zoom, t),
centerX: lerp(defaults.centerX, seg.zoomCenterX, t),
centerY: lerp(defaults.centerY, seg.zoomCenterY, t),
brightness: lerp(defaults.brightness, seg.brightness, t),
contrast: lerp(defaults.contrast, seg.contrast, t),
saturate: lerp(defaults.saturate, seg.saturate, t),
};
}

4
remotion/src/index.ts Normal file
View file

@ -0,0 +1,4 @@
import { registerRoot } from "remotion";
import { RemotionRoot } from "./Root";
registerRoot(RemotionRoot);

View file

@ -0,0 +1,83 @@
import type { CaptionWord } from "./types";
export interface CaptionBlock {
words: CaptionWord[];
startMs: number;
endMs: number;
text: string;
}
/**
* Groups word-level captions into display blocks.
* Same logic as OpenShorts' generate_srt: max chars per block, max duration per block.
*/
export function groupCaptionsIntoBlocks(
captions: CaptionWord[],
maxChars = 20,
maxDurationMs = 2000
): CaptionBlock[] {
const blocks: CaptionBlock[] = [];
let currentWords: CaptionWord[] = [];
let blockStartMs = 0;
for (const word of captions) {
if (currentWords.length === 0) {
currentWords.push(word);
blockStartMs = word.startMs;
continue;
}
const currentTextLen = currentWords.reduce(
(sum, w) => sum + w.text.length + 1,
0
);
const duration = word.endMs - blockStartMs;
if (
currentTextLen + word.text.length > maxChars ||
duration > maxDurationMs
) {
// Finalize current block
const lastWord = currentWords[currentWords.length - 1];
blocks.push({
words: [...currentWords],
startMs: blockStartMs,
endMs: lastWord.endMs,
text: currentWords.map((w) => w.text).join(" "),
});
currentWords = [word];
blockStartMs = word.startMs;
} else {
currentWords.push(word);
}
}
// Final block
if (currentWords.length > 0) {
const lastWord = currentWords[currentWords.length - 1];
blocks.push({
words: [...currentWords],
startMs: blockStartMs,
endMs: lastWord.endMs,
text: currentWords.map((w) => w.text).join(" "),
});
}
return blocks;
}
/**
* Find the active word at a given time in milliseconds.
*/
export function getActiveWordIndex(
words: CaptionWord[],
timeMs: number
): number {
for (let i = 0; i < words.length; i++) {
if (timeMs >= words[i].startMs && timeMs < words[i].endMs) {
return i;
}
}
return -1;
}

33
remotion/src/lib/fonts.ts Normal file
View file

@ -0,0 +1,33 @@
import { staticFile } from "remotion";
/**
* CSS @font-face declaration for NotoSerif-Bold (bundled locally).
* Use in components via: <style>{notoSerifFontFace}</style>
*/
export const NOTO_SERIF_FONT_FAMILY = "NotoSerif-Bold";
export const notoSerifFontFace = `
@font-face {
font-family: '${NOTO_SERIF_FONT_FAMILY}';
src: url('${staticFile("fonts/NotoSerif-Bold.ttf")}') format('truetype');
font-weight: 700;
font-style: normal;
}
`;
/**
* Map of subtitle font families to their CSS-safe names.
* These match the options available in SubtitleModal.jsx.
*/
export const SUBTITLE_FONTS: Record<string, string> = {
Verdana: "Verdana, Geneva, sans-serif",
Arial: "Arial, Helvetica, sans-serif",
Impact: "Impact, Haettenschweiler, sans-serif",
Helvetica: "Helvetica, Arial, sans-serif",
Georgia: "Georgia, 'Times New Roman', serif",
"Courier New": "'Courier New', Courier, monospace",
};
export function getFontStack(fontFamily: string): string {
return SUBTITLE_FONTS[fontFamily] ?? fontFamily;
}

130
remotion/src/lib/types.ts Normal file
View file

@ -0,0 +1,130 @@
import { z } from "zod";
// --- Word-level caption ---
export interface CaptionWord {
text: string;
startMs: number;
endMs: number;
}
// --- Subtitle config ---
export type SubtitleAnimation = "none" | "word-highlight" | "pop" | "karaoke";
export type SubtitlePosition = "top" | "middle" | "bottom";
export interface SubtitleStyle {
fontFamily: string;
fontSize: number;
fontColor: string;
highlightColor: string;
borderColor: string;
borderWidth: number;
bgColor: string;
bgOpacity: number;
animation: SubtitleAnimation;
}
export interface SubtitleConfig {
captions: CaptionWord[];
position: SubtitlePosition;
style: SubtitleStyle;
}
// --- Hook config ---
export type HookPosition = "top" | "center" | "bottom";
export type HookSize = "S" | "M" | "L";
export type HookEntrance = "spring" | "fade" | "slide-up" | "none";
export interface HookConfig {
text: string;
position: HookPosition;
size: HookSize;
entranceAnimation: HookEntrance;
displayDurationSec: number;
}
// --- Effects config ---
export interface EffectSegment {
startSec: number;
endSec: number;
zoom: number;
zoomCenterX: number;
zoomCenterY: number;
brightness: number;
contrast: number;
saturate: number;
}
export interface EffectsConfig {
segments: EffectSegment[];
}
// --- Main composition props ---
export interface ShortVideoProps {
videoUrl: string;
durationInFrames: number;
fps: number;
width: number;
height: number;
subtitles: SubtitleConfig | null;
hook: HookConfig | null;
effects: EffectsConfig | null;
}
// --- Zod schemas for validation (used by render service) ---
export const captionWordSchema = z.object({
text: z.string(),
startMs: z.number(),
endMs: z.number(),
});
export const subtitleStyleSchema = z.object({
fontFamily: z.string(),
fontSize: z.number(),
fontColor: z.string(),
highlightColor: z.string(),
borderColor: z.string(),
borderWidth: z.number(),
bgColor: z.string(),
bgOpacity: z.number().min(0).max(1),
animation: z.enum(["none", "word-highlight", "pop", "karaoke"]),
});
export const subtitleConfigSchema = z.object({
captions: z.array(captionWordSchema),
position: z.enum(["top", "middle", "bottom"]),
style: subtitleStyleSchema,
});
export const hookConfigSchema = z.object({
text: z.string(),
position: z.enum(["top", "center", "bottom"]),
size: z.enum(["S", "M", "L"]),
entranceAnimation: z.enum(["spring", "fade", "slide-up", "none"]),
displayDurationSec: z.number().positive(),
});
export const effectSegmentSchema = z.object({
startSec: z.number().min(0),
endSec: z.number().positive(),
zoom: z.number().min(0.5).max(3),
zoomCenterX: z.number().min(0).max(1),
zoomCenterY: z.number().min(0).max(1),
brightness: z.number().min(0).max(3),
contrast: z.number().min(0).max(3),
saturate: z.number().min(0).max(3),
});
export const effectsConfigSchema = z.object({
segments: z.array(effectSegmentSchema),
});
export const shortVideoPropsSchema = z.object({
videoUrl: z.string(),
durationInFrames: z.number().int().positive(),
fps: z.number().positive(),
width: z.number().int().positive(),
height: z.number().int().positive(),
subtitles: subtitleConfigSchema.nullable(),
hook: hookConfigSchema.nullable(),
effects: effectsConfigSchema.nullable(),
});

16
remotion/tsconfig.json Normal file
View file

@ -0,0 +1,16 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ES2022",
"moduleResolution": "bundler",
"jsx": "react-jsx",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"outDir": "./dist",
"rootDir": "./src",
"declaration": true
},
"include": ["src/**/*"]
}

2
render-service/.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
node_modules/
dist/

34
render-service/Dockerfile Normal file
View file

@ -0,0 +1,34 @@
FROM node:18-bookworm-slim
# Install Chromium and FFmpeg for Remotion rendering
RUN apt-get update && \
apt-get install -y --no-install-recommends chromium ffmpeg && \
rm -rf /var/lib/apt/lists/*
ENV PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium
ENV REMOTION_BUNDLE_PATH=/app/remotion
ENV OUTPUT_DIR=/output
WORKDIR /app
# Copy render service source
COPY render-service/package.json ./
RUN npm install
COPY render-service/tsconfig.json ./
COPY render-service/src/ ./src/
# Copy remotion source for bundling
COPY remotion/package.json /app/remotion/package.json
COPY remotion/tsconfig.json /app/remotion/tsconfig.json
COPY remotion/src/ /app/remotion/src/
COPY remotion/public/ /app/remotion/public/
# Install remotion deps
RUN cd /app/remotion && npm install
# Build TypeScript
RUN npm run build
EXPOSE 3100
CMD ["node", "dist/server.js"]

4097
render-service/package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,25 @@
{
"name": "openshorts-render-service",
"version": "1.0.0",
"private": true,
"type": "module",
"scripts": {
"dev": "tsx watch src/server.ts",
"build": "tsc",
"start": "node dist/server.js"
},
"dependencies": {
"@remotion/bundler": "^4.0.0",
"@remotion/renderer": "^4.0.0",
"express": "^4.21.0",
"remotion": "^4.0.0",
"uuid": "^10.0.0",
"zod": "^4.3.6"
},
"devDependencies": {
"@types/express": "^5.0.0",
"@types/uuid": "^10.0.0",
"tsx": "^4.19.0",
"typescript": "^5.4.0"
}
}

View file

@ -0,0 +1,43 @@
import path from "node:path";
import { bundle } from "@remotion/bundler";
let bundleLocation: string | null = null;
/**
* Bundles the Remotion project on startup and caches the result.
* Uses REMOTION_BUNDLE_PATH env var to locate the remotion source
* (default: "../remotion" relative to this service's root).
*/
export async function initBundle(): Promise<void> {
const remotionRoot = process.env.REMOTION_BUNDLE_PATH
? path.resolve(process.env.REMOTION_BUNDLE_PATH)
: path.resolve(import.meta.dirname, "../../remotion");
const entryPoint = path.join(remotionRoot, "src", "index.ts");
console.log(`[bundle] Bundling Remotion project from: ${entryPoint}`);
bundleLocation = await bundle({
entryPoint,
onProgress: (progress: number) => {
if (progress % 10 === 0) {
console.log(`[bundle] Progress: ${progress}%`);
}
},
});
console.log(`[bundle] Bundle created at: ${bundleLocation}`);
}
/**
* Returns the cached bundle location.
* Throws if initBundle() has not been called yet.
*/
export function getBundleLocation(): string {
if (!bundleLocation) {
throw new Error(
"Bundle not initialized. Call initBundle() before getBundleLocation()."
);
}
return bundleLocation;
}

View file

@ -0,0 +1,96 @@
import fs from "node:fs";
import path from "node:path";
import { selectComposition, renderMedia } from "@remotion/renderer";
import { getBundleLocation } from "./bundle.js";
import { renderJobs } from "./server.js";
export interface RenderParams {
renderId: string;
jobId: string;
clipIndex: number;
props: {
videoUrl: string;
durationInFrames: number;
fps: number;
width: number;
height: number;
subtitles: unknown;
hook: unknown;
effects: unknown;
};
}
/**
* Executes a Remotion render in the background.
* Updates the in-memory render job map with progress and final status.
*/
export async function executeRender(params: RenderParams): Promise<void> {
const { renderId, jobId, clipIndex, props } = params;
const job = renderJobs.get(renderId);
if (!job) {
console.error(`[render-worker] Job ${renderId} not found in map`);
return;
}
try {
job.status = "rendering";
job.progress = 0;
console.log(
`[render-worker] Starting render ${renderId} (job=${jobId}, clip=${clipIndex})`
);
const bundleLocation = getBundleLocation();
// Select the composition with the provided input props
const composition = await selectComposition({
serveUrl: bundleLocation,
id: "ShortVideo",
inputProps: props,
});
// Determine output directory and file path
const outputDir = process.env.OUTPUT_DIR
? path.resolve(process.env.OUTPUT_DIR)
: path.resolve(import.meta.dirname, "../../output");
const jobOutputDir = path.join(outputDir, jobId);
fs.mkdirSync(jobOutputDir, { recursive: true });
const timestamp = Date.now();
const outputFileName = `remotion_${clipIndex}_${timestamp}.mp4`;
const outputLocation = path.join(jobOutputDir, outputFileName);
console.log(`[render-worker] Output: ${outputLocation}`);
// Render the video
await renderMedia({
composition,
serveUrl: bundleLocation,
codec: "h264",
crf: 22,
outputLocation,
onProgress: ({ progress }) => {
const percent = Math.round(progress * 100);
job.progress = percent;
if (percent % 10 === 0) {
console.log(`[render-worker] ${renderId} progress: ${percent}%`);
}
},
});
// Success
job.status = "done";
job.progress = 100;
job.outputUrl = outputLocation;
console.log(`[render-worker] Render ${renderId} completed: ${outputLocation}`);
} catch (err) {
job.status = "error";
job.error = err instanceof Error ? err.message : String(err);
console.error(`[render-worker] Render ${renderId} failed:`, err);
}
}

View file

@ -0,0 +1,166 @@
import express from "express";
import { v4 as uuidv4 } from "uuid";
import { z } from "zod";
import { initBundle } from "./bundle.js";
import { executeRender } from "./render-worker.js";
// --- Render status types ---
export type RenderStatus = "queued" | "rendering" | "done" | "error";
export interface RenderJob {
renderId: string;
jobId: string;
clipIndex: number;
status: RenderStatus;
progress: number;
outputUrl?: string;
error?: string;
}
// In-memory render job map
export const renderJobs = new Map<string, RenderJob>();
// --- Request validation schema ---
const renderRequestSchema = z.object({
jobId: z.string().min(1),
clipIndex: z.number().int().min(0),
props: z.object({
videoUrl: z.string(),
durationInFrames: z.number().int().positive(),
fps: z.number().positive(),
width: z.number().int().positive(),
height: z.number().int().positive(),
subtitles: z.any().nullable().optional(),
hook: z.any().nullable().optional(),
effects: z.any().nullable().optional(),
}),
});
// --- Express app ---
const app = express();
app.use(express.json({ limit: "10mb" }));
const PORT = parseInt(process.env.PORT || "3100", 10);
const OUTPUT_DIR = process.env.OUTPUT_DIR || "/output";
// Serve video files from the shared output volume so Remotion can access them via HTTP
app.use("/output", express.static(OUTPUT_DIR));
// Health check
app.get("/health", (_req, res) => {
res.json({ ok: true });
});
// Submit a render job
app.post("/render", (req, res) => {
const parsed = renderRequestSchema.safeParse(req.body);
if (!parsed.success) {
res.status(400).json({
error: "Invalid request body",
details: parsed.error.issues,
});
return;
}
const { jobId, clipIndex, props } = parsed.data;
const renderId = uuidv4();
const job: RenderJob = {
renderId,
jobId,
clipIndex,
status: "queued",
progress: 0,
};
renderJobs.set(renderId, job);
console.log(
`[render] Queued render ${renderId} for job=${jobId} clip=${clipIndex}`
);
// Resolve video URL: convert frontend/backend URLs to renderer's own static server
// The renderer serves /output/* from the shared Docker volume
let resolvedVideoUrl = props.videoUrl;
const videoPathMatch = props.videoUrl.match(/\/videos\/([^/]+)\/(.+)$/);
if (videoPathMatch) {
resolvedVideoUrl = `http://localhost:${PORT}/output/${videoPathMatch[1]}/${videoPathMatch[2]}`;
console.log(`[render] Resolved video URL: ${props.videoUrl} -> ${resolvedVideoUrl}`);
}
// Fire and forget - render runs in background
executeRender({
renderId,
jobId,
clipIndex,
props: {
videoUrl: resolvedVideoUrl,
durationInFrames: props.durationInFrames,
fps: props.fps,
width: props.width,
height: props.height,
subtitles: props.subtitles ?? null,
hook: props.hook ?? null,
effects: props.effects ?? null,
},
}).catch((err) => {
console.error(`[render] Unhandled error for ${renderId}:`, err);
const existingJob = renderJobs.get(renderId);
if (existingJob) {
existingJob.status = "error";
existingJob.error =
err instanceof Error ? err.message : "Unknown error";
}
});
res.status(202).json({ renderId, status: "queued" });
});
// Get render status
app.get("/render/:renderId", (req, res) => {
const { renderId } = req.params;
const job = renderJobs.get(renderId);
if (!job) {
res.status(404).json({ error: "Render not found" });
return;
}
const response: Record<string, unknown> = {
renderId: job.renderId,
status: job.status,
};
if (job.progress !== undefined) {
response.progress = job.progress;
}
if (job.outputUrl) {
response.outputUrl = job.outputUrl;
}
if (job.error) {
response.error = job.error;
}
res.json(response);
});
// --- Start server ---
async function main() {
console.log("[render-service] Initializing Remotion bundle...");
await initBundle();
console.log("[render-service] Bundle ready.");
app.listen(PORT, () => {
console.log(`[render-service] Listening on port ${PORT}`);
});
}
main().catch((err) => {
console.error("[render-service] Fatal error during startup:", err);
process.exit(1);
});

View file

@ -0,0 +1,17 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"outDir": "dist",
"rootDir": "src",
"declaration": true,
"resolveJsonModule": true
},
"include": ["src"],
"exclude": ["node_modules", "dist"]
}