Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: audio-to-video mode on the dgrauet runtime
Adam Eivy607588669771
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 1ff31dfb97..a536bf3d44 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -11,6 +11,7 @@- Video Gen "Chunks" control (1–8) chains multiple LTX renders into a single longer clip. Each chunk's last frame seeds the next, then ffmpeg stitches them into one output. The individual chunks land in history hidden by default, so the gallery shows just the stitched result.- Two new LTX-2.3 video models — "dgrauet Q4" and "dgrauet Q8" — running on a more capable runtime that supports true keyframe interpolation (proper FFLF that respects both start AND end frames), native video extend, and audio-to-video. Install with `INSTALL_LTX2=1 bash scripts/setup-image-video.sh`. The existing notapalindrome models keep working unchanged; pick the new "dgrauet" entries from the model dropdown to use the new pipeline. FFLF on these models has a stage-2 OOM ceiling — the server auto-clamps frame count to a memory-safe budget (override via `FFLF_LTX2_PIXEL_BUDGET` env var if you have more RAM than 48 GB).- "Extend" mode on the new dgrauet runtime now uses a true latent video extension (conditions on the entire source video's motion + visual content) instead of last-frame i2v conditioning. The visible motion stall at scene boundaries is gone — extensions continue movement naturally from the source. Legacy notapalindrome models keep using the old chained-i2v workaround.+- New "Audio" mode in Video Gen renders a clip whose motion and on-screen audio sync to an uploaded audio track (WAV / MP3 / M4A). Pick the new mode tile, drop in a 4–8 second clip, write a directive prompt ("a person dancing to this track in a studio"), and the dgrauet runtime drives the video to the audio. Requires one of the new dgrauet models — legacy LTX models don't expose an audio-conditioned pipeline.## Changeddiff --git a/PLAN.md b/PLAN.mdindex 3bfbd2ce97..bfd7811610 100644--- a/PLAN.md+++ b/PLAN.md@@ -29,7 +29,7 @@ The PR landed with full pipeline mechanics + auto-recovery + smoke-test fixture,The dgrauet/ltx-2-mlx runtime now ships with FFLF (true keyframe interpolation) verified on hardware (commit `ef5d9081`). The pipeline supports more native modes that PortOS still emulates with workarounds — wiring each to the proper subcommand will materially improve quality. Helper script (`scripts/generate_ltx2.py`) already accepts the args; the gaps are server dispatch + client routing.- [ ] **Native video Extend (replace chained-i2v workaround).** Today the UI's "Extend" mode extracts the last frame and runs i2v on it — visible motion stalls at every chunk seam. Dgrauet's `ExtendPipeline.extend_from_video()` conditions on the *whole input video's latent* (motion + visual content), so new frames flow naturally. Files (~70 LOC): (1) fix `scripts/generate_ltx2.py` `run_extend` to mirror cli's `_decode_and_save` cleanup pattern (free DiT+TextEncoder, load decoders on-demand, then save) — current implementation OOMs at decode; (2) `server/services/videoGen/local.js` `buildLtx2Args` route extend → helperMode='extend' on ltx2, take new `extendFromVideoPath` param + validate; (3) `server/routes/videoGen.js` accept `extendFromVideoId` in body, resolve to absolute video path under `data/videos/`; (4) `client/src/pages/VideoGen.jsx` when mode=extend AND selected model has runtime='ltx2' skip `extractLastFrame`, send `extendFromVideoId` instead — fall back to existing chained-i2v on legacy runtime. Plus tests for the route's id resolution. Validate on hardware with a known-motion source clip — extension should continue motion vs. start cold.-- [ ] **Audio-to-video (a2v).** Dgrauet ships a true audio-conditioned T2V pipeline (`AudioToVideoPipeline.generate_and_save` — takes a WAV/MP3 path + optional reference image, generates video that syncs to the audio). PortOS doesn't expose this today. Files (~120 LOC): (1) `scripts/generate_ltx2.py` add `run_a2v` that imports `AudioToVideoPipeline`, takes `--audio` (WAV/MP3), optional `--image` for I2V conditioning, emits same STAGE/STATUS protocol; (2) `data/media-models.json` no new model entry needed (uses same ltx2 runtime); (3) `server/lib/validation.js` extend video-gen schema with `mode: 'a2v'` enum value + `audioFile` field; (4) `server/routes/videoGen.js` add multipart audio upload (re-use `uploadSingle('audioFile', ...)` pattern from sourceImage), stage to `data/uploads/`, pass to enqueueJob; (5) `server/services/videoGen/local.js` `buildLtx2Args` map mode='a2v' → helperMode='a2v', pass `--audio <path>`; (6) `client/src/pages/VideoGen.jsx` add a new mode tile (icon: Music/Mic), audio file picker (no gallery — direct upload), maybe a duration display from probing the audio. Audio stripping (`--no-audio`) is a no-op in this mode (the audio IS the input). UAT: pick or upload a 4–8 second audio clip with clear rhythm + a directive prompt ("a person dancing to this track in a studio"), verify the rendered video's motion syncs to the audio's beats.+- [x] ~~**Audio-to-video (a2v).**~~ Done — `run_a2v` in `scripts/generate_ltx2.py` invokes `AudioToVideoPipeline.generate_and_save` with `--audio` (WAV/MP3) and optional `--image` for first-frame conditioning. `server/lib/multipart.js`'s `uploadSingle` now accepts an array of field names so the route can take EITHER `sourceImage` (image/fflf) OR `audioFile` (a2v) through the same single-file uploader (mutually exclusive per request). `server/routes/videoGen.js` mode enum extended to include `a2v`, audio uploads stage to `data/uploads/video-audio-<uuid>.<ext>` and route to `audioFilePath`. `server/services/videoGen/local.js` `buildLtx2Args` maps `mode='a2v'` → `helperMode='a2v'`, passes `--audio`; rejects a2v on legacy `mlx_video` runtime with a clear error. `client/src/pages/VideoGen.jsx` adds the `a2v` mode tile (Music icon), an audio file picker that shows name + size + expected-duration hint, and submit guards for missing audio + non-ltx2 model. UAT: pick a 4–8 second audio clip with clear rhythm + a directive prompt ("a person dancing to this track in a studio"), verify the rendered video's motion syncs to the audio's beats.- [ ] **Native FFLF deeper test on real keyframe pairs.** FFLF wiring is verified on synthetic ball-motion keyframes (commit `ef5d9081`). Validate with REAL pairs: take last frame of clip A + first frame of clip B from the same scene/camera, render an interpolation, confirm temporally-coherent transition. If it looks weak even on similar keyframes, file a follow-up to expose more pipeline knobs in the UI (cfg-scale, stg-scale, stage1-steps).- [ ] **Add UI hint under FFLF mode.** "Use keyframes that share scene geometry — same camera, same subject; the model interpolates between them. Random unrelated images produce a visual cut." Prevents the "looks like two stills" complaint that surfaced during testing.- [ ] **Once dgrauet is the default for everything we care about, deprecate notapalindrome models.** Mark `ltx2_unified`, `ltx23_unified`, `ltx23_distilled_q4` with `deprecated: true` in `media-models.json` so the model dropdown groups them under a "Legacy" section. Eventually drop them and the `runtime: 'mlx_video'` dispatch entirely (~50 LOC removal in videoGen/local.js).diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsxindex 0c8fbec8bb..883931b07e 100644--- a/client/src/pages/VideoGen.jsx+++ b/client/src/pages/VideoGen.jsx@@ -33,7 +33,7 @@ import { normalizeVideo } from '../components/media/normalize';import { composeStyledPrompt } from '../lib/composeStyledPrompt';import {Film, Sparkles, Settings as SettingsIcon, RefreshCw, AlertTriangle,- Dice5, X, Upload, Type, Image as ImageIcon, GitBranch, ListPlus,+ Dice5, X, Upload, Type, Image as ImageIcon, GitBranch, ListPlus, Music,} from 'lucide-react';import toast from '../components/ui/Toast';import BrailleSpinner from '../components/BrailleSpinner';@@ -71,6 +71,7 @@ const MODES = [{ id: 'image', label: 'Image', icon: ImageIcon, desc: 'Image-to-video (start frame)' },{ id: 'fflf', label: 'FFLF', icon: GitBranch, desc: 'First frame + last frame' },{ id: 'extend', label: 'Extend', icon: Film, desc: 'Continue from a prior render' },+ { id: 'a2v', label: 'Audio', icon: Music, desc: 'Audio-to-video (audio drives motion + sync)' },];const newQueueId = () =>@@ -126,6 +127,10 @@ export default function VideoGen() {const [lastImageFile, setLastImageFile] = useState(null);const [extendFromVideoId, setExtendFromVideoId] = useState('');const [extendingFrame, setExtendingFrame] = useState(false);+ // a2v mode — direct audio upload only (no gallery for audio yet). The File+ // is sent as multipart field name 'audioFile'; the server stages it under+ // data/uploads, then the python helper passes it to AudioToVideoPipeline.+ const [audioFile, setAudioFile] = useState(null);// Image gallery for the FFLF end-frame picker (gallery only — no upload// for the second image so the multipart parser stays single-file).@@ -297,6 +302,9 @@ export default function VideoGen() {// carry over because they apply to all modes.)const handleModeChange = (next) => {setMode(next);+ // Audio is only meaningful in a2v mode — drop it on every other switch+ // so a stale upload from a prior pick doesn't sneak into a non-a2v post.+ if (next !== 'a2v') setAudioFile(null);if (next === 'text') {clearSourceImage();setLastImageFile(null);@@ -314,6 +322,12 @@ export default function VideoGen() {// extend leaves a stale source that gets silently submitted alongside// an empty extendFromVideoId.clearSourceImage();+ } else if (next === 'a2v') {+ // a2v takes audio + optional first-frame image. Drop FFLF end-frame ++ // extend pick so they don't get silently submitted; keep the source+ // image (acts as i2v conditioning when present).+ setLastImageFile(null);+ setExtendFromVideoId('');}};@@ -402,6 +416,9 @@ export default function VideoGen() {lastImageFile: mode === 'fflf' ? (lastImageFile || '') : '',extendFromVideoId: (mode === 'extend' && currentModel?.runtime === 'ltx2')? (extendFromVideoId || '') : '',+ // Audio File goes through under the multipart field 'audioFile'. Server+ // routes it to the durable uploads dir and into the a2v helper.+ audioFile: mode === 'a2v' ? (audioFile || '') : '',chunks: chunks > 1 ? chunks : '',};};@@ -510,6 +527,10 @@ export default function VideoGen() {!extendFromVideoId|| (currentModel?.runtime !== 'ltx2' && (extendingFrame || !sourceImageFile)));+ // a2v requires an audio upload AND an ltx2-runtime model — the legacy+ // mlx_video runtime has no audio-conditioned pipeline. Block submit when+ // either is missing so the request fails the form, not the worker.+ const a2vModeBlocked = mode === 'a2v' && (!audioFile || currentModel?.runtime !== 'ltx2');const handleGenerate = async (e) => {e?.preventDefault?.();@@ -518,22 +539,23 @@ export default function VideoGen() {// Without these guards the user could press Enter in the prompt// textarea and fire a request the disabled button would otherwise// have prevented.- if (!prompt.trim() || generating || (status && status.connected === false) || extendModeBlocked) return;+ if (!prompt.trim() || generating || (status && status.connected === false) || extendModeBlocked || a2vModeBlocked) return;await runGeneration(buildGeneratePayload()).catch(() => {});};const handleEnqueue = () => {- if (!prompt.trim() || (status && status.connected === false) || extendModeBlocked) return;+ if (!prompt.trim() || (status && status.connected === false) || extendModeBlocked || a2vModeBlocked) return;const payload = buildGeneratePayload();- // Strip the File blob for snapshot — re-using a File across multiple+ // Strip the File blobs for snapshot — re-using a File across multiple// queued submissions is fine, but we need a stable JSON-ish summary- // for the queue UI display. Hold the File in `_blob` separately.- const { sourceImage, ...summary } = payload;+ // for the queue UI display. Hold the Files in `_blob`/`_audioBlob`.+ const { sourceImage, audioFile: audioBlob, ...summary } = payload;setQueue((q) => [...q, {id: newQueueId(),status: 'pending',params: summary,_blob: sourceImage instanceof File ? sourceImage : null,+ _audioBlob: audioBlob instanceof File ? audioBlob : null,enqueuedAt: Date.now(),}]);toast.success('Added to queue');@@ -565,6 +587,7 @@ export default function VideoGen() {setQueue((q) => q.map((item) => item.id === next.id ? { ...item, status: 'running', startedAt: Date.now() } : item));const payload = { ...next.params };if (next._blob) payload.sourceImage = next._blob;+ if (next._audioBlob) payload.audioFile = next._audioBlob;let busyRetry = false;let busyRetryTimer = null;runGeneration(payload).then((res) => {@@ -618,7 +641,7 @@ export default function VideoGen() {};const notConnected = status && status.connected === false;- const canEnqueue = prompt.trim() && !notConnected && !extendModeBlocked;+ const canEnqueue = prompt.trim() && !notConnected && !extendModeBlocked && !a2vModeBlocked;return (<div className="space-y-3">@@ -789,6 +812,43 @@ export default function VideoGen() {</div>)}+ {mode === 'a2v' && (+ <div className="border border-port-border/50 rounded-lg p-2 space-y-1.5">+ <div className="flex items-center justify-between">+ <span className="text-[11px] font-medium text-gray-400">Audio (drives motion + sync)</span>+ {audioFile && (+ <button type="button" onClick={() => setAudioFile(null)} className="text-[11px] text-port-error hover:underline">Clear</button>+ )}+ </div>+ {audioFile ? (+ <div className="flex items-center gap-2 text-[11px] text-gray-300">+ <Music className="w-3.5 h-3.5 text-port-accent" />+ <span className="truncate" title={audioFile.name}>{audioFile.name}</span>+ <span className="text-gray-500">{(audioFile.size / 1024 / 1024).toFixed(2)} MB</span>+ </div>+ ) : (+ <label className="flex items-center gap-2 text-[11px] text-gray-400 cursor-pointer hover:text-white">+ <Upload className="w-3.5 h-3.5" />+ <span className="truncate">Upload audio (WAV / MP3 / M4A)</span>+ <input+ type="file"+ accept="audio/*"+ onChange={(e) => setAudioFile(e.target.files?.[0] || null)}+ className="hidden"+ />+ </label>+ )}+ <p className="text-[10px] text-gray-500 leading-snug">+ Audio length should match {`${(numFrames / fps).toFixed(1)}s`} (frames ÷ fps). Longer clips are trimmed to fit; shorter clips fail.+ </p>+ {currentModel?.runtime !== 'ltx2' && (+ <p className="text-[11px] text-port-warning">+ a2v requires an ltx2-runtime model — switch the Model dropdown to one of the dgrauet entries.+ </p>+ )}+ </div>+ )}+{mode === 'extend' && (<div className="border border-port-border/50 rounded-lg p-2 space-y-1.5"><div className="flex items-center justify-between">@@ -984,9 +1044,15 @@ export default function VideoGen() {) : (<buttontype="submit"- disabled={!prompt.trim() || notConnected || extendModeBlocked}+ disabled={!prompt.trim() || notConnected || extendModeBlocked || a2vModeBlocked}className="flex items-center gap-2 px-4 py-2 bg-port-accent hover:bg-port-accent/80 disabled:opacity-50 disabled:cursor-not-allowed text-white text-sm font-medium rounded-lg min-h-[40px]"- title={extendModeBlocked ? 'Pick a prior render and wait for the last frame to extract before generating' : undefined}+ title={+ extendModeBlocked ? 'Pick a prior render and wait for the last frame to extract before generating'+ : a2vModeBlocked ? (currentModel?.runtime !== 'ltx2'+ ? 'a2v mode requires an ltx2-runtime model — pick one from the Model dropdown'+ : 'Pick an audio file before generating')+ : undefined+ }><Sparkles className="w-4 h-4" /> Generate</button>diff --git a/scripts/generate_ltx2.py b/scripts/generate_ltx2.pyindex d19e5001f7..d655d466b7 100644--- a/scripts/generate_ltx2.py+++ b/scripts/generate_ltx2.py@@ -22,6 +22,7 @@ Modes:image → ImageToVideoPipeline.generate_and_save (--image)fflf → KeyframeInterpolationPipeline.generate_and_save (--image start, --last-image end)extend → ExtendPipeline.extend_from_video (--extend-from-video, --extend-frames, --direction)+ a2v → AudioToVideoPipeline.generate_and_save (--audio, optional --image)Output: writes the rendered .mp4 to --output. Emits a final JSON line onstdout ({"video_path": "<output>"}) so the Node parent can read the result@@ -53,7 +54,7 @@ def emit_download(msg: str) -> None:def parse_args() -> argparse.Namespace:p = argparse.ArgumentParser(description="PortOS ltx-2-mlx bridge")- p.add_argument("--mode", required=True, choices=["text", "image", "fflf", "extend"])+ p.add_argument("--mode", required=True, choices=["text", "image", "fflf", "extend", "a2v"])p.add_argument("--prompt", required=True)p.add_argument("--negative-prompt", default="")p.add_argument("--output", required=True, help="Output .mp4 path")@@ -85,6 +86,9 @@ def parse_args() -> argparse.Namespace:p.add_argument("--extend-frames", type=int, default=2,help="Number of latent frames to add (extend mode); 1 latent ≈ 8 pixel frames")p.add_argument("--extend-direction", choices=["before", "after"], default="after")+ p.add_argument("--audio", default=None, help="Source audio path (a2v mode) — WAV/MP3/etc.")+ p.add_argument("--audio-start", type=float, default=0.0,+ help="Start offset in seconds into the audio file (a2v mode).")p.add_argument("--no-audio", action="store_true",help="Strip audio from output. The dgrauet pipeline always generates A/V; ""we re-mux without the audio stream when requested.")@@ -213,6 +217,43 @@ def run_extend(args: argparse.Namespace) -> str:return pipe._decode_and_save_video(video_latent, audio_latent, args.output)+def run_a2v(args: argparse.Namespace) -> str:+ """Audio-to-video — generate a clip whose motion + audio track sync to an+ input WAV/MP3. Two-stage pipeline (dev model + CFG at half-res, then+ distilled-LoRA refine at full-res), so it shares the same dev_transformer ++ distilled_lora layout as fflf — a fully-distilled-only repo will fail+ here for the same reason it fails for fflf.++ The pipeline always emits A/V; --no-audio re-muxes after to drop audio,+ but doing that for a2v is unusual (the audio is the conditioning input).+ --image is optional: when provided, conditions the FIRST frame the same+ way ImageToVideoPipeline does, so motion + audio sync to a chosen still.+ """+ from ltx_pipelines_mlx import AudioToVideoPipeline+ if not args.audio:+ raise SystemExit("--audio is required for a2v mode")+ emit_status(f"Loading A2V pipeline ({args.model})…")+ emit_stage(1, 0, 1, "Loading model")+ pipe = AudioToVideoPipeline(model_dir=args.model, gemma_model_id=args.gemma)+ emit_stage(1, 1, 1, "Loaded")+ emit_status(f"Generating A2V from {Path(args.audio).name}…")+ return pipe.generate_and_save(+ prompt=args.prompt,+ output_path=args.output,+ audio_path=args.audio,+ image=args.image,+ height=args.height,+ width=args.width,+ num_frames=args.num_frames,+ fps=args.fps,+ seed=args.seed,+ stage1_steps=args.steps,+ stage2_steps=args.stage2_steps,+ cfg_scale=args.cfg_scale if args.cfg_scale is not None else 3.0,+ audio_start_time=args.audio_start,+ )++def maybe_strip_audio(output_path: str) -> None:"""Remux the output without the audio stream when --no-audio is set.@@ -254,6 +295,7 @@ def main() -> int:"image": run_image,"fflf": run_fflf,"extend": run_extend,+ "a2v": run_a2v,}runner = runners[args.mode]saved_path = runner(args)diff --git a/server/lib/multipart.js b/server/lib/multipart.jsindex 13e3de8f2b..dc690acc94 100644--- a/server/lib/multipart.js+++ b/server/lib/multipart.js@@ -19,8 +19,14 @@ import { tmpdir } from 'os';import { join } from 'path';import { randomUUID } from 'crypto';+// fieldName accepts either a string (single accepted file field) or an array+// of strings (any one of which is the accepted file field). Mutually-exclusive+// uploads — e.g. videoGen's `sourceImage` (image mode) vs. `audioFile` (a2v+// mode) — pass the array form so a single middleware handles both without+// chaining two parsers (which can't share the streamed request body).export function uploadSingle(fieldName, { limits = {}, fileFilter } = {}) {const maxSize = limits.fileSize ?? Infinity;+ const fieldNames = Array.isArray(fieldName) ? fieldName : [fieldName];return (req, res, next) => {const ct = req.headers['content-type'] || '';@@ -38,7 +44,7 @@ export function uploadSingle(fieldName, { limits = {}, fileFilter } = {}) {err.status = 400; err.code = 'INVALID_CONTENT_TYPE';return next(err);}- streamMultipart(req, bm[1], fieldName, maxSize, fileFilter, next);+ streamMultipart(req, bm[1], fieldNames, maxSize, fileFilter, next);};}@@ -54,7 +60,7 @@ export function optionalUpload(fieldName, opts) {};}-function streamMultipart(req, boundary, fileFieldName, maxSize, fileFilter, next) {+function streamMultipart(req, boundary, fileFieldNames, maxSize, fileFilter, next) {const PART_DELIM = Buffer.from('\r\n--' + boundary);const FIRST_DELIM = Buffer.from('--' + boundary);const HEADER_END = Buffer.from('\r\n\r\n');@@ -142,11 +148,11 @@ function streamMultipart(req, boundary, fileFieldName, maxSize, fileFilter, nextcurrentFilename = filenameMatch?.[1];if (currentFilename != null && currentFilename !== '') {- isMatchingFile = currentName === fileFieldName;+ isMatchingFile = fileFieldNames.includes(currentName);const mimeMatch = headerStr.match(/Content-Type:\s*([^\r\n]+)/i);currentFileMimetype = mimeMatch ? mimeMatch[1].trim() : 'application/octet-stream';if (isMatchingFile) {- const fileMeta = { originalname: currentFilename, mimetype: currentFileMimetype };+ const fileMeta = { fieldname: currentName, originalname: currentFilename, mimetype: currentFileMimetype };if (fileFilter) {// CONTRACT: fileFilter MUST call its `cb` synchronously. We read@@ -233,11 +239,12 @@ function streamMultipart(req, boundary, fileFieldName, maxSize, fileFilter, nextconst size = bytesWritten;const filename = currentFilename;const mimetype = currentFileMimetype || 'application/octet-stream';+ const fieldname = currentName;writeStream = null;writePath = null;pendingFlush += 1;ws.end(() => {- fileResult = { path, originalname: filename, mimetype, size };+ fileResult = { fieldname, path, originalname: filename, mimetype, size };pendingFlush -= 1;cb();// If 'end' arrived while we were still flushing, finalize now.diff --git a/server/routes/videoGen.js b/server/routes/videoGen.jsindex 0c922894a7..654713bb29 100644--- a/server/routes/videoGen.js+++ b/server/routes/videoGen.js@@ -31,9 +31,17 @@ import { enqueueJob, attachSseClient, cancelJob, listJobs } from '../services/meconst router = Router();-const sourceImageUpload = uploadSingle('sourceImage', {- limits: { fileSize: 50 * 1024 * 1024 },- fileFilter: (_req, file, cb) => cb(null, file.mimetype.startsWith('image/')),+// Single uploader handles both sourceImage (image/fflf modes) and audioFile+// (a2v mode). They're mutually exclusive per request — the parser keeps the+// first matching file part and discards bytes for any other file fields, so+// this is safe even if a malformed client sends both.+const mediaUpload = uploadSingle(['sourceImage', 'audioFile'], {+ limits: { fileSize: 100 * 1024 * 1024 },+ fileFilter: (_req, file, cb) => {+ const okImage = file.fieldname === 'sourceImage' && file.mimetype.startsWith('image/');+ const okAudio = file.fieldname === 'audioFile' && file.mimetype.startsWith('audio/');+ cb(null, okImage || okAudio);+ },});// Multipart bodies arrive as strings; coerce numerics in the schema. The@@ -71,7 +79,7 @@ const generateBodySchema = z.object({lastImageFile: z.string().max(512).optional(),// UI mode hint — backend only uses it for logging/branching; absence// falls back to inferring (sourceImage→i2v, no source→t2v).- mode: z.enum(['text', 'image', 'fflf', 'extend']).optional(),+ mode: z.enum(['text', 'image', 'fflf', 'extend', 'a2v']).optional(),// Chain N renders end-to-end: each chunk's last frame becomes the next// chunk's start frame, then ffmpeg concats them into one clip. 1..8 to// keep the worst-case wall time bounded (8 × ~5min ≈ 40min on M3 Max).@@ -123,7 +131,7 @@ const resolveGalleryImage = (name) => {}};-router.post('/', sourceImageUpload, asyncHandler(async (req, res) => {+router.post('/', mediaUpload, asyncHandler(async (req, res) => {// Pre-enqueue cleanup hook: every throw path below MUST drop the multipart// temp upload (Multer wrote it before this handler ran). Without this a// configuration/validation error leaks the upload in the OS temp dir.@@ -164,6 +172,7 @@ router.post('/', sourceImageUpload, asyncHandler(async (req, res) => {}let sourceImagePath = null;+ let audioFilePath = null;let uploadedTempPath = null;if (req.file) {// Copy the multipart upload into a durable location under data/uploads@@ -174,7 +183,9 @@ router.post('/', sourceImageUpload, asyncHandler(async (req, res) => {// restarts; the worker unlinks it on completion or cancel.await ensureDir(PATHS.uploads);const ext = extname(req.file.originalname || req.file.path) || '.bin';- const durablePath = join(PATHS.uploads, `video-source-${randomUUID()}${ext}`);+ const isAudio = req.file.fieldname === 'audioFile';+ const prefix = isAudio ? 'video-audio' : 'video-source';+ const durablePath = join(PATHS.uploads, `${prefix}-${randomUUID()}${ext}`);// copyFile can throw on disk-full / permission errors. If it does we// need to clean up: drop the multipart temp upload AND the half-written// durablePath (copyFile may have created a zero-byte sentinel before@@ -190,12 +201,27 @@ router.post('/', sourceImageUpload, asyncHandler(async (req, res) => {);}await unlink(req.file.path).catch(() => {});- sourceImagePath = durablePath;+ if (isAudio) {+ audioFilePath = durablePath;+ } else {+ sourceImagePath = durablePath;+ }uploadedTempPath = durablePath;} else if (body.sourceImageFile) {sourceImagePath = resolveGalleryImage(body.sourceImageFile);}+ // a2v mode requires an audio upload — fail fast at the route boundary so+ // the UI gets a clear 400 instead of a queued job that fails late on the+ // python helper's "audio_path is required" check.+ if (body.mode === 'a2v' && !audioFilePath) {+ await cleanupTempUpload();+ throw new ServerError(+ 'a2v mode requires an audioFile upload (multipart field name: audioFile).',+ { status: 400, code: 'VIDEO_GEN_AUDIO_REQUIRED' },+ );+ }+// FFLF end-frame: gallery-pick only. Same path-traversal guard.const lastImagePath = body.lastImageFile ? resolveGalleryImage(body.lastImageFile) : null;@@ -244,6 +270,7 @@ router.post('/', sourceImageUpload, asyncHandler(async (req, res) => {tiling: body.tiling || 'auto',disableAudio: body.disableAudio === true || body.disableAudio === 'true',sourceImagePath,+ audioFilePath,uploadedTempPath,lastImagePath,extendFromVideoPath,diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.jsindex e0f39976b1..3fb3eb15a5 100644--- a/server/services/videoGen/local.js+++ b/server/services/videoGen/local.js@@ -87,7 +87,7 @@ export const saveHistory = (h) => atomicWrite(HISTORY_FILE, h);// The helper lives in the ltx-2-mlx venv (so its `import ltx_pipelines_mlx`// resolves) but the script file lives in the PortOS repo so updates ship// with PortOS releases instead of the user's HF cache.-const buildLtx2Args = ({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, guidance, seed, sourceImagePath, lastImagePath, extendFromVideoPath, mode, disableAudio, outputPath, textEncoderRepo }) => {+const buildLtx2Args = ({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, guidance, seed, sourceImagePath, lastImagePath, extendFromVideoPath, audioFilePath, mode, disableAudio, outputPath, textEncoderRepo }) => {if (!existsSync(LTX2_VENV_PYTHON)) {throw new ServerError(`ltx-2-mlx venv not found at ${LTX2_VENV_PYTHON}. Run \`INSTALL_LTX2=1 bash scripts/setup-image-video.sh\` to install.`,@@ -101,6 +101,7 @@ const buildLtx2Args = ({ model, prompt, negativePrompt, width, height, numFrames// video (e.g., the chained-render orchestrator already handed us a frame).const wantsNativeExtend = mode === 'extend' && !!extendFromVideoPath;const helperMode = mode === 'fflf' ? 'fflf'+ : mode === 'a2v' ? 'a2v': wantsNativeExtend ? 'extend': mode === 'image' || mode === 'extend' ? 'image': 'text';@@ -116,6 +117,14 @@ const buildLtx2Args = ({ model, prompt, negativePrompt, width, height, numFrames{ status: 400, code: 'LTX2_EXTEND_SOURCE_MISSING' },);}+ if (helperMode === 'a2v') {+ if (!audioFilePath || !existsSync(audioFilePath)) {+ throw new ServerError(+ `Audio file not found on disk for a2v mode: ${audioFilePath || '(missing)'}`,+ { status: 400, code: 'LTX2_A2V_AUDIO_MISSING' },+ );+ }+ }// Stage-2 OOM clamp on the keyframe pipeline.//// The KeyframeInterpolationPipeline runs a 2× spatial upscale + full-res@@ -175,15 +184,28 @@ const buildLtx2Args = ({ model, prompt, negativePrompt, width, height, numFramesargs.push('--extend-frames', String(extendLatents));args.push('--extend-direction', 'after');}+ if (helperMode === 'a2v') {+ args.push('--audio', audioFilePath);+ // Optional first-frame conditioning — when the user supplied a source+ // image, AudioToVideoPipeline conditions frame 0 the same way I2V does+ // so motion + audio sync to the chosen still.+ if (sourceImagePath) args.push('--image', sourceImagePath);+ }return { bin: LTX2_VENV_PYTHON, args };};-const buildArgs = ({ pythonPath, modelId, model, prompt, negativePrompt, width, height, numFrames, fps, steps, guidance, seed, tiling, disableAudio, sourceImagePath, lastImagePath, extendFromVideoPath, mode, imageStrength, textEncoderRepo, outputPath }) => {+const buildArgs = ({ pythonPath, modelId, model, prompt, negativePrompt, width, height, numFrames, fps, steps, guidance, seed, tiling, disableAudio, sourceImagePath, lastImagePath, extendFromVideoPath, audioFilePath, mode, imageStrength, textEncoderRepo, outputPath }) => {// Route to the dgrauet/ltx-2-mlx helper when the model declares the new// runtime. Existing notapalindrome models default to runtime: 'mlx_video'// (or undefined in legacy registries — see backfillRuntime in mediaModels.js).if (model.runtime === 'ltx2') {- return buildLtx2Args({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, guidance, seed, sourceImagePath, lastImagePath, extendFromVideoPath, mode, disableAudio, outputPath, textEncoderRepo });+ return buildLtx2Args({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, guidance, seed, sourceImagePath, lastImagePath, extendFromVideoPath, audioFilePath, mode, disableAudio, outputPath, textEncoderRepo });+ }+ if (mode === 'a2v') {+ throw new ServerError(+ 'a2v mode is only supported on the ltx2 runtime. Pick a model with runtime: "ltx2" in data/media-models.json.',+ { status: 400, code: 'A2V_REQUIRES_LTX2' },+ );}if (IS_WIN) {const scriptPath = join(PATHS.root, 'scripts', 'generate_win.py');@@ -237,7 +259,7 @@ const buildArgs = ({ pythonPath, modelId, model, prompt, negativePrompt, width,return { bin: pythonPath, args };};-export async function generateVideo({ pythonPath, prompt, negativePrompt = '', modelId = defaultVideoModelId(), width = 768, height = 512, numFrames = 121, fps = 24, steps, guidanceScale, seed, tiling = 'auto', disableAudio = false, sourceImagePath = null, uploadedTempPath = null, lastImagePath = null, extendFromVideoPath = null, mode = null, imageStrength = null, jobId: providedJobId = null }) {+export async function generateVideo({ pythonPath, prompt, negativePrompt = '', modelId = defaultVideoModelId(), width = 768, height = 512, numFrames = 121, fps = 24, steps, guidanceScale, seed, tiling = 'auto', disableAudio = false, sourceImagePath = null, uploadedTempPath = null, lastImagePath = null, extendFromVideoPath = null, audioFilePath = null, mode = null, imageStrength = null, jobId: providedJobId = null }) {if (!pythonPath) throw new ServerError('Python path not configured — set it in Settings > Image Gen', { status: 400, code: 'VIDEO_GEN_NOT_CONFIGURED' });if (!prompt?.trim()) throw new ServerError('Prompt is required', { status: 400, code: 'VALIDATION_ERROR' });// Single-flight is now enforced by the mediaJobQueue worker upstream — only@@ -312,7 +334,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', mconst job = { ...meta, clients: [], status: 'running' };jobs.set(jobId, job);- const { bin, args } = buildArgs({ pythonPath, modelId, model, prompt, negativePrompt, width: w, height: h, numFrames: parsedNumFrames, fps: parsedFps, steps: actualSteps, guidance: actualGuidance, seed: actualSeed, tiling, disableAudio, sourceImagePath: resolvedSourceImage, lastImagePath: resolvedLastImage, extendFromVideoPath, mode, imageStrength: actualImageStrength, textEncoderRepo: actualTextEncoderRepo, outputPath });+ const { bin, args } = buildArgs({ pythonPath, modelId, model, prompt, negativePrompt, width: w, height: h, numFrames: parsedNumFrames, fps: parsedFps, steps: actualSteps, guidance: actualGuidance, seed: actualSeed, tiling, disableAudio, sourceImagePath: resolvedSourceImage, lastImagePath: resolvedLastImage, extendFromVideoPath, audioFilePath, mode, imageStrength: actualImageStrength, textEncoderRepo: actualTextEncoderRepo, outputPath });console.log(`🎬 Generating video [${jobId.slice(0, 8)}]: ${modelId} ${w}x${h} frames=${parsedNumFrames} steps=${actualSteps}`);videoGenEvents.emit('started', { generationId: jobId, totalSteps: actualSteps, ...meta });