Skip to content

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

feat(video-gen): 2× upscale, no-music toggle, mid-clip thumbnails

Adam Eivy452de5d7eec0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index f608b5c78f..3c8ec62c68 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,11 @@
## Added
+- **Video Gen — 2× Lanczos upscale on completed videos + "No music" prompt toggle + mid-clip thumbnail seek.** Three improvements lifted from the Phosphene LTX panel:
+ 1. **2× upscale action.** Every video in the gallery (Video Gen recent + Media History) now exposes a `Maximize2`-icon button that runs an ffmpeg Lanczos 2× upscale on the clip — H.264 yuv420p CRF 18, audio stream-copied, `+faststart` preserved, ~10-30s on a typical 5s LTX render. The result lands as a new history entry tagged with `upscaledFrom: <originalId>` and a "(2×)" prompt suffix; the source clip is left untouched so the user gets both versions side-by-side. A `2×` badge surfaces on upscaled tiles to keep them distinguishable. New helper `upscaleVideo2x()` in `server/lib/ffmpeg.js`, service entry `upscaleHistoryItem()` in `server/services/videoGen/local.js`, and `POST /api/video-gen/upscale/:id` route. The upscale button is hidden on already-upscaled clips so users don't chain 2×→4×→8× by accident.
+ 2. **"No music" prompt toggle.** New checkbox below the existing "Disable audio" toggle on `/media/video`. When on (and audio gen is itself active), submit-time prompt composition appends `\n\nno music, no soundtrack` so LTX-2 steers toward ambient/diegetic sound (footsteps, room tone) rather than generated background music — useful when the clip is destined for downstream scoring or VO. Idempotent: skipped if the user already typed "no music" themselves. Disabled when `disableAudio` is checked since there's no audio output to steer.
+ 3. **Mid-clip thumbnail seek.** Thumbnails were extracting frame 0 via `-vframes 1`, which on LTX-2 renders is the darkest moment of the clip (model fades IN from black, so 0-0.5s is near-zero brightness) and produced "broken black tile" complaints in the gallery. `generateThumbnail()` now ffprobes duration, seeks to `min(2.5s, duration/2)` (1s fallback when ffprobe is unavailable) so the cached JPG samples the visual peak instead of the fade-in. Affects every new render going forward — old thumbnails keep their existing frame until regenerated. Touched: `server/lib/ffmpeg.js`, `server/services/videoGen/local.js`, `server/routes/videoGen.{js,test.js}`, `client/src/components/media/{MediaCard,normalize}.{jsx,js}`, `client/src/pages/{VideoGen,MediaHistory}.jsx`, `client/src/services/apiImageVideo.js`.
+
- **Storyboard style presets — prompts expanded 2-4x with richer detail.** Every preset in `server/lib/writersRoomStylePresets.js` (all 40 across Cinema & Photo, Genre & Era, Animation, and Illustration & Comics) had its `prompt` rewritten from a 150-300 char stub into a 670-970 char production-grade descriptor. Each prompt now layers (1) named medium / film stock / brush technique, (2) lighting direction + quality + color temperature, (3) named color palette, (4) compositional + framing intent, (5) atmospheric / texture detail, and (6) explicit artist or studio influence (Roger Deakins, Frank Frazetta, Mucha, Hokusai, Mignola, McQuarrie, etc.). Negative prompts also enriched to better suppress unwanted hybrid styles. No schema changes — `id`, `label`, `category`, and `description` (UI text) all preserved, so existing Works that recorded a preset id still resolve to the new richer text on next render. Touched: `server/lib/writersRoomStylePresets.js`.
- **Style presets surfaced on Image / Video gen, expanded library, and Codex backend wired into Writers Room storyboard.** The world-style presets that previously only existed inside the Writers Room storyboard config are now available on the standalone **Image Gen** and **Video Gen** pages too — a category-grouped picker (`StylePresetPicker`) sits above each form's prompt textarea, prefixes the user's prompt with the preset's style at submit time, and appends the preset's negative-prompt to the user's negative. The library grew from 9 to **40 curated presets across four categories** — *Cinema & Photo* (cinematic, noir, photorealistic, vintage film, polaroid, golden hour, low-key dramatic), *Genre & Era* (cyberpunk neon, steampunk, dieselpunk, solarpunk, dark/high fantasy, space opera, cosmic horror, vaporwave, 80s sci-fi paperback, victorian, Wes Anderson), *Animation* (Studio Ghibli, Pixar 3D, Disney 2D classic, anime modern + 90s, claymation), and *Illustration & Comics* (graphic novel, comic book, manga B&W, watercolor storybook, oil painting, impressionist, art deco, art nouveau, ukiyo-e woodblock, concept art, pixel art, low-poly, isometric, technical blueprint, sumi-e ink wash) — every preset that nudges toward text/panel rendering aggressively negatives `text, words, letters, lettering, typography, title, logo, watermark, signature, caption, word balloon, speech bubble, sound effect` to suppress FLUX/Klein/Schnell's text-rendering gibberish. The Writers Room storyboard's Config tab gained a **Local | Codex** backend chip strip (only renders when more than one backend is configured); picking Codex routes scene renders through the `$imagegen` skill on the user's logged-in Codex session — model/steps/seed are hidden in that mode since `image_gen` picks them internally. Codex's sync response now also returns `status: 'running'` so SceneCard's UI stays in spinner state until the SSE `completed` event lands instead of flipping to `done` and 404'ing the placeholder `<img>`. New endpoint `GET /api/image-gen/style-presets` (canonical) replaces the old `/api/writers-room/style-presets`; client now caches the 40-item response with a module-level promise so navigating Image → Video → Writers Room doesn't refetch. New shared modules: `client/src/components/media/{StylePresetPicker,BackendChipStrip}.jsx`, `client/src/lib/{composeStyledPrompt,imageGenBackends}.js`. Touched: `server/lib/writersRoomStylePresets.js`, `server/routes/{imageGen,writersRoom}.js`, `server/services/imageGen/codex.js`, `client/src/pages/{ImageGen,VideoGen}.jsx`, `client/src/components/writers-room/StoryboardPanel.jsx`, `client/src/services/{apiSystem,apiWritersRoom}.js`.
diff --git a/client/src/components/media/MediaCard.jsx b/client/src/components/media/MediaCard.jsx
index 1439f6892b..30df7bdf64 100644
--- a/client/src/components/media/MediaCard.jsx
+++ b/client/src/components/media/MediaCard.jsx
@@ -1,4 +1,4 @@
-import { Trash2, Download, Film, Image as ImageIcon, Sparkles, Eye, EyeOff } from 'lucide-react';
+import { Trash2, Download, Film, Image as ImageIcon, Sparkles, Eye, EyeOff, Maximize2 } from 'lucide-react';
import AddToCollectionMenu from './AddToCollectionMenu';
// Single card used everywhere a generated image/video appears in a grid:
@@ -13,6 +13,7 @@ export default function MediaCard({
onRemix,
onSendToVideo,
onContinue,
+ onUpscale,
onDelete,
onToggleHidden,
selectionLabel = null, // e.g. "1", "2" — shown as the stitch order badge
@@ -51,6 +52,9 @@ export default function MediaCard({
{item.stitchedFrom && (
<span className="absolute top-1.5 right-1.5 text-[9px] px-1 py-0.5 bg-port-success/80 text-white rounded">stitched</span>
)}
+ {item.upscaledFrom && (
+ <span className="absolute top-1.5 right-1.5 text-[9px] px-1 py-0.5 bg-port-accent/80 text-white rounded">2×</span>
+ )}
</button>
<div className="p-2 space-y-1.5">
<p className="text-[11px] text-gray-300 line-clamp-2" title={prompt}>{prompt}</p>
@@ -94,6 +98,16 @@ export default function MediaCard({
<ImageIcon className="w-3 h-3" /> Continue
</button>
)}
+ {isVideo && onUpscale && !item.upscaledFrom && (
+ <button
+ type="button"
+ onClick={() => onUpscale(item)}
+ className="px-1.5 py-1 bg-port-border hover:bg-port-border/70 text-white text-[10px] rounded flex items-center justify-center"
+ title="Upscale 2× (Lanczos, ~10s)"
+ >
+ <Maximize2 className="w-3 h-3" />
+ </button>
+ )}
{showCollectionMenu && <AddToCollectionMenu item={item} />}
<a
href={downloadUrl}
diff --git a/client/src/components/media/normalize.js b/client/src/components/media/normalize.js
index e55a38b9cb..ae368ef7ef 100644
--- a/client/src/components/media/normalize.js
+++ b/client/src/components/media/normalize.js
@@ -37,6 +37,7 @@ export function normalizeVideo(v) {
numFrames: v.numFrames,
fps: v.fps,
stitchedFrom: v.stitchedFrom,
+ upscaledFrom: v.upscaledFrom,
createdAt: v.createdAt,
hidden: !!v.hidden,
raw: v,
diff --git a/client/src/pages/MediaHistory.jsx b/client/src/pages/MediaHistory.jsx
index 8d67848d24..98861aae33 100644
--- a/client/src/pages/MediaHistory.jsx
+++ b/client/src/pages/MediaHistory.jsx
@@ -13,6 +13,7 @@ import MediaLightbox from '../components/media/MediaLightbox';
import { normalizeImage, normalizeVideo } from '../components/media/normalize';
import {
listVideoHistory, deleteVideoHistoryItem, extractLastFrame, stitchVideos,
+ upscaleVideo,
listImageGallery, deleteImage,
} from '../services/api';
@@ -112,6 +113,22 @@ export default function MediaHistory() {
navigate(`/media/image?${params}`);
};
+ const [upscalingId, setUpscalingId] = useState(null);
+ const handleUpscale = async (item) => {
+ if (upscalingId) return;
+ setUpscalingId(item.id);
+ toast.info?.('Upscaling 2× — typically 10-30s…');
+ const result = await upscaleVideo(item.id).catch((err) => {
+ toast.error(err.message || 'Upscale failed');
+ return null;
+ });
+ setUpscalingId(null);
+ if (result?.video) {
+ setItems((all) => [normalizeVideo(result.video), ...all]);
+ toast.success('Upscaled 2×');
+ }
+ };
+
const handleSendToVideo = (item) => {
const params = new URLSearchParams({ sourceImageFile: item.filename });
if (item.prompt && item.prompt !== '(no prompt)') params.set('prompt', item.prompt);
@@ -194,6 +211,7 @@ export default function MediaHistory() {
onRemix={!stitchMode ? handleRemix : undefined}
onSendToVideo={!stitchMode ? handleSendToVideo : undefined}
onContinue={!stitchMode ? handleContinue : undefined}
+ onUpscale={!stitchMode && it.kind === 'video' ? handleUpscale : undefined}
onDelete={!stitchMode ? handleDelete : undefined}
selectionLabel={idx !== -1 ? idx + 1 : null}
selected={idx !== -1}
diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsx
index 3c1f21f92d..3ba9df7b32 100644
--- a/client/src/pages/VideoGen.jsx
+++ b/client/src/pages/VideoGen.jsx
@@ -41,6 +41,7 @@ import BatchQueuePanel from '../components/media/BatchQueuePanel';
import {
getVideoGenStatus, generateVideo, cancelVideoGen,
listVideoHistory, deleteVideoHistoryItem, setVideoHidden, extractLastFrame,
+ upscaleVideo,
listImageGallery,
} from '../services/api';
import { randomSeed, safeParseJSON } from '../lib/genUtils';
@@ -113,6 +114,12 @@ export default function VideoGen() {
const [seed, setSeed] = useState('');
const [tiling, setTiling] = useState('auto');
const [disableAudio, setDisableAudio] = useState(false);
+ // "No music" appends a soundscape constraint at submit time. LTX-2
+ // conditions audio on prompt text — adding "no music, no soundtrack"
+ // pushes the model toward ambient/diegetic sound (footsteps, room tone)
+ // and away from generated background music, which is hard to remove
+ // cleanly in post. Source: phosphene LTX-2 prompting guide.
+ const [noMusic, setNoMusic] = useState(false);
const [sourceImageFile, setSourceImageFile] = useState(incomingSourceImage || null);
const [sourceImageUpload, setSourceImageUpload] = useState(null);
const [lastImageFile, setLastImageFile] = useState(null);
@@ -188,6 +195,27 @@ export default function VideoGen() {
});
if (result) toast.success(nextHidden ? 'Video hidden' : 'Video unhidden');
};
+ // Track which history item is being upscaled so the same MediaCard's
+ // "Upscale" button disables and shows a "working" state. Storing the id
+ // (not a boolean) lets us also surface the spinner on the right tile when
+ // the user fires multiple upscales in succession; only one runs at a time
+ // because ffmpeg is single-flight on the server.
+ const [upscalingId, setUpscalingId] = useState(null);
+ const handleUpscaleHistory = async (item) => {
+ if (upscalingId) return;
+ setUpscalingId(item.id);
+ toast.info?.('Upscaling 2× — typically 10-30s…');
+ const result = await upscaleVideo(item.id).catch((err) => {
+ toast.error(err.message || 'Upscale failed');
+ return null;
+ });
+ setUpscalingId(null);
+ if (result?.video) {
+ setHistory((h) => [result.video, ...h]);
+ toast.success('Upscaled 2×');
+ }
+ };
+
const handleContinueHistory = async (item) => {
const { filename } = await extractLastFrame(item.id).catch((err) => {
toast.error(err.message || 'Failed to extract last frame');
@@ -333,8 +361,15 @@ export default function VideoGen() {
// inline Generate button and by enqueue, so the two paths stay in lockstep.
const buildGeneratePayload = () => {
const composed = composeStyledPrompt(prompt, negativePrompt, stylePreset);
+ // Append "no music, no soundtrack" only when the toggle is on AND audio
+ // generation is itself active — there's no point steering audio output
+ // when audio is disabled outright. Idempotent: if the user already
+ // typed "no music" we avoid double-appending.
+ const promptOut = (noMusic && !disableAudio && !/no music/i.test(composed.prompt))
+ ? `${composed.prompt}\n\nno music, no soundtrack`
+ : composed.prompt;
return {
- prompt: composed.prompt,
+ prompt: promptOut,
negativePrompt: composed.negativePrompt,
modelId,
width, height,
@@ -881,6 +916,19 @@ export default function VideoGen() {
/>
Disable audio (LTX-2 only — speeds up generation)
</label>
+ <label
+ className={`col-span-2 sm:col-span-3 flex items-center gap-2 text-xs cursor-pointer ${disableAudio ? 'text-gray-600 cursor-not-allowed' : 'text-gray-400'}`}
+ title="LTX-2 conditions audio on the prompt — appending 'no music, no soundtrack' at submit time pushes the model toward ambient/diegetic sound only"
+ >
+ <input
+ type="checkbox"
+ checked={noMusic}
+ disabled={disableAudio}
+ onChange={(e) => setNoMusic(e.target.checked)}
+ className="rounded"
+ />
+ No music — keep ambient/diegetic sound only (LTX-2)
+ </label>
</div>
<div className="flex flex-wrap items-center gap-2 pt-1">
@@ -988,6 +1036,7 @@ export default function VideoGen() {
item={item}
onPreview={() => setPreview(item)}
onContinue={() => handleContinueHistory(v)}
+ onUpscale={() => handleUpscaleHistory(v)}
onDelete={() => handleDeleteHistory(v)}
onToggleHidden={() => handleToggleHistoryHidden(v)}
/>
diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.js
index 53ac35ea17..c318861652 100644
--- a/client/src/services/apiImageVideo.js
+++ b/client/src/services/apiImageVideo.js
@@ -31,6 +31,7 @@ export const setVideoHidden = (id, hidden) => request(`/video-gen/history/${enco
body: JSON.stringify({ hidden }),
});
export const extractLastFrame = (id) => request(`/video-gen/last-frame/${encodeURIComponent(id)}`, { method: 'POST' });
+export const upscaleVideo = (id) => request(`/video-gen/upscale/${encodeURIComponent(id)}`, { method: 'POST' });
export const stitchVideos = (videoIds) => request('/video-gen/stitch', {
method: 'POST',
body: JSON.stringify({ videoIds }),
diff --git a/server/lib/ffmpeg.js b/server/lib/ffmpeg.js
index 7122a0d766..4f4da415b2 100644
--- a/server/lib/ffmpeg.js
+++ b/server/lib/ffmpeg.js
@@ -65,17 +65,56 @@ export const findFfprobe = async () => {
return cachedFfprobePath;
};
-// Single-video thumbnail extraction at frame 1. Returns the basename on
-// success, null when ffmpeg is missing or fails — callers should treat null
-// as "no thumbnail" rather than aborting the parent operation.
+// Single-video thumbnail extraction. Seeks to mid-clip rather than frame 0
+// because LTX-2 renders fade IN from black: the first ~0.5s is near-zero
+// brightness, so a frame-0 thumbnail looks like a "broken black" tile
+// even when the clip itself is fine. Mid-clip is reliably the visual peak.
+//
+// Strategy: probe duration via ffprobe and seek to duration/2 (capped at
+// 2.5s — the canonical mid-point of a 5s 24fps LTX clip). When ffprobe is
+// unavailable or returns a tiny duration we fall back to a fixed -ss 1.0
+// rather than frame 0, since 1s is still past the LTX fade-in on every
+// useful clip length. `-ss` BEFORE `-i` is the fast-seek path (keyframe
+// step), which is fine for thumbnails — exact-frame accuracy isn't needed.
+//
+// Returns the basename on success, null when ffmpeg is missing or fails —
+// callers should treat null as "no thumbnail" rather than aborting the
+// parent operation.
+const probeDurationSeconds = async (videoPath) => {
+ const ffprobe = await findFfprobe();
+ if (!ffprobe) return null;
+ const args = [
+ '-v', 'error',
+ '-show_entries', 'format=duration',
+ '-of', 'default=nokey=1:noprint_wrappers=1',
+ videoPath,
+ ];
+ const { stdout } = await execFileAsync(ffprobe, args, { timeout: 5000 }).catch(() => ({ stdout: '' }));
+ const n = parseFloat((stdout || '').trim());
+ return Number.isFinite(n) && n > 0 ? n : null;
+};
+
export const generateThumbnail = async (videoPath, jobId) => {
await ensureDir(PATHS.videoThumbnails);
const thumbFilename = `${jobId}.jpg`;
const thumbPath = join(PATHS.videoThumbnails, thumbFilename);
const ffmpeg = await findFfmpeg();
if (!ffmpeg) return null;
+ const duration = await probeDurationSeconds(videoPath);
+ // Cap at 2.5s — the midpoint of a 5s 24fps LTX clip (121 frames). For
+ // longer clips (Extend mode, 10s+) 2.5s is still past the LTX fade-in
+ // and not at an unreliable boundary. For short clips (<2s) seek to the
+ // actual midpoint. Fall back to 1s when ffprobe is unavailable.
+ const seekSec = duration ? Math.min(2.5, Math.max(0.5, duration / 2)) : 1.0;
return new Promise((resolve) => {
- const proc = spawn(ffmpeg, ['-i', videoPath, '-vframes', '1', '-q:v', '5', '-y', thumbPath], { stdio: 'ignore' });
+ const proc = spawn(ffmpeg, [
+ '-ss', seekSec.toFixed(2),
+ '-i', videoPath,
+ '-vframes', '1',
+ '-q:v', '5',
+ '-y',
+ thumbPath,
+ ], { stdio: 'ignore' });
proc.on('close', (code) => resolve(code === 0 ? thumbFilename : null));
proc.on('error', (err) => {
console.log(`⚠️ ffmpeg thumbnail failed to spawn: ${err.message}`);
@@ -202,6 +241,77 @@ export const extractEvaluationFrames = async (videoPath, jobId, count = 5) => {
return frameIndices.map((_, i) => `${jobId}-f${i + 1}.jpg`);
};
+// 2× Lanczos upscale of an MP4 in place. Doubles width and height while
+// preserving the exact aspect ratio and the audio track. Used as a quick
+// post-render export option for LTX renders that come out at sub-720p
+// (e.g. 768×512, 640×384) so they read crisply on bigger screens without
+// re-running the model. `+faststart` is preserved on the output.
+//
+// Returns `{ ok: true, outPath }` on success and `{ ok: false, reason }`
+// on any failure — callers decide whether to surface the error.
+//
+// Encoding choice: H.264 yuv420p CRF 18 (visually lossless to most
+// viewers, plays everywhere). The audio track is stream-copied so the
+// LTX-2 audio bed survives untouched. ffmpeg's lanczos scaler is the
+// classical "good default" for upscale — sharper than bicubic, no
+// ringing artifacts on smooth gradients.
+//
+// Concurrency contract: `optimizeForStreaming` and `upscaleVideo2x` both
+// rewrite the same file via a sibling tmp + atomic rename. Don't run them
+// concurrently against the same path; the queue worker that produces a
+// rendered clip already serializes both.
+export const upscaleVideo2x = async (videoPath) => {
+ if (typeof videoPath !== 'string' || !videoPath) {
+ return { ok: false, reason: 'invalid video path' };
+ }
+ if (!existsSync(videoPath)) {
+ return { ok: false, reason: 'video file missing' };
+ }
+ const ffmpeg = await findFfmpeg();
+ if (!ffmpeg) return { ok: false, reason: 'ffmpeg not found' };
+ // -2 keeps the dimension on an even multiple (libx264 requires even
+ // dimensions); pairing iw*2:-2 with the lanczos flag gives a clean
+ // exact 2× width and the matching height. Avoiding `iw*2:ih*2` because
+ // any user-supplied source with an odd dimension would otherwise fail.
+ const tmpPath = `${videoPath}.up2x.mp4`;
+ const ok = await new Promise((resolve) => {
+ const proc = spawn(ffmpeg, [
+ '-i', videoPath,
+ '-vf', 'scale=iw*2:-2:flags=lanczos',
+ '-c:v', 'libx264',
+ '-pix_fmt', 'yuv420p',
+ '-crf', '18',
+ '-preset', 'medium',
+ '-c:a', 'copy',
+ '-movflags', '+faststart',
+ '-y', tmpPath,
+ ], { stdio: 'ignore' });
+ proc.on('close', (code) => resolve(code === 0));
+ proc.on('error', () => resolve(false));
+ });
+ if (!ok) {
+ await unlink(tmpPath).catch(() => {});
+ return { ok: false, reason: 'ffmpeg upscale failed' };
+ }
+ let backupPath = null;
+ try {
+ if (IS_WIN) {
+ backupPath = `${videoPath}.bak.${randomUUID()}`;
+ await rename(videoPath, backupPath).catch((err) => {
+ if (err?.code === 'ENOENT') { backupPath = null; return; }
+ throw err;
+ });
+ }
+ await rename(tmpPath, videoPath);
+ if (backupPath) await unlink(backupPath).catch(() => {});
+ return { ok: true, outPath: videoPath };
+ } catch (err) {
+ if (backupPath) await rename(backupPath, videoPath).catch(() => {});
+ await unlink(tmpPath).catch(() => {});
+ return { ok: false, reason: `Failed to install upscaled video: ${err.message}` };
+ }
+};
+
// MP4s with the moov atom at the END require browsers to download the entire
// file before they can render the first-frame poster on preload="metadata".
// Remux with -movflags +faststart to move moov to the front. Stream copy —
diff --git a/server/routes/videoGen.js b/server/routes/videoGen.js
index e5b68c898b..7d454fb358 100644
--- a/server/routes/videoGen.js
+++ b/server/routes/videoGen.js
@@ -24,6 +24,7 @@ import {
setHistoryItemHidden,
extractLastFrame,
stitchVideos,
+ upscaleHistoryItem,
} from '../services/videoGen/local.js';
import { enqueueJob, attachSseClient, cancelJob, listJobs } from '../services/mediaJobQueue/index.js';
@@ -272,6 +273,11 @@ router.post('/last-frame/:id', asyncHandler(async (req, res) => {
res.json(await extractLastFrame(req.params.id));
}));
+router.post('/upscale/:id', asyncHandler(async (req, res) => {
+ const entry = await upscaleHistoryItem(req.params.id);
+ res.json({ ok: true, video: entry });
+}));
+
router.post('/stitch', asyncHandler(async (req, res) => {
const ids = req.body?.videoIds;
if (!Array.isArray(ids)) throw new ServerError('videoIds array required', { status: 400, code: 'VALIDATION_ERROR' });
diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.js
index 06933cf721..b719ad47ff 100644
--- a/server/routes/videoGen.test.js
+++ b/server/routes/videoGen.test.js
@@ -16,6 +16,7 @@ vi.mock('../services/videoGen/local.js', () => ({
setHistoryItemHidden: vi.fn(async (id, hidden) => ({ ok: true, id, hidden })),
extractLastFrame: vi.fn(),
stitchVideos: vi.fn(),
+ upscaleHistoryItem: vi.fn(),
}));
// Render submissions go through the mediaJobQueue. Mock its surface so the
@@ -273,4 +274,25 @@ describe('videoGen routes', () => {
expect(r.body.video.id).toBe('s1');
});
});
+
+ describe('POST /upscale/:id', () => {
+ it('forwards id to upscaleHistoryItem and wraps the new entry', async () => {
+ const upscaled = { id: 'new-id', filename: 'new-id.mp4', width: 1536, height: 1024, upscaledFrom: 'orig-id' };
+ videoGenService.upscaleHistoryItem.mockResolvedValue(upscaled);
+ const r = await request(app).post('/api/video-gen/upscale/orig-id').send({});
+ expect(r.status).toBe(200);
+ expect(r.body.ok).toBe(true);
+ expect(r.body.video).toEqual(upscaled);
+ expect(videoGenService.upscaleHistoryItem).toHaveBeenCalledWith('orig-id');
+ });
+
+ it('returns the ServerError status when the service rejects', async () => {
+ videoGenService.upscaleHistoryItem.mockRejectedValue(
+ Object.assign(new Error('Video not found'), { status: 404, code: 'NOT_FOUND' }),
+ );
+ const r = await request(app).post('/api/video-gen/upscale/missing').send({});
+ expect(r.status).toBe(404);
+ expect(r.body.error).toMatch(/not found/i);
+ });
+ });
});
diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.js
index d659df4756..ec86b85a7e 100644
--- a/server/services/videoGen/local.js
+++ b/server/services/videoGen/local.js
@@ -12,7 +12,7 @@
import { execFile, spawn } from 'child_process';
import { existsSync, statSync } from 'fs';
-import { unlink, writeFile } from 'fs/promises';
+import { unlink, writeFile, copyFile } from 'fs/promises';
import { join, basename } from 'path';
import { tmpdir } from 'os';
import { randomUUID } from 'crypto';
@@ -22,7 +22,7 @@ import { ServerError } from '../../lib/errorHandler.js';
import { videoGenEvents } from './events.js';
import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay, PYTHON_NOISE_RE } from '../../lib/sseUtils.js';
import { getVideoModels, getDefaultVideoModelId, getTextEncoderRepo } from '../../lib/mediaModels.js';
-import { findFfmpeg, safeUnder, generateThumbnail, optimizeForStreaming } from '../../lib/ffmpeg.js';
+import { findFfmpeg, safeUnder, generateThumbnail, optimizeForStreaming, upscaleVideo2x } from '../../lib/ffmpeg.js';
const execFileAsync = promisify(execFile);
@@ -477,6 +477,63 @@ export async function stitchVideos(videoIds) {
return stitchedMeta;
}
+// 2× Lanczos upscale of an existing history item. Writes the upscaled clip
+// to a new file (never overwrites the original) and inserts a new history
+// entry pointing at it, so the user gets both versions side-by-side in the
+// gallery. Doubles width and height; aspect-ratio is preserved exactly.
+//
+// Returns the new history entry on success; throws ServerError on any
+// missing-input / ffmpeg / file-system failure so the route can map it to
+// a clean HTTP status.
+export async function upscaleHistoryItem(historyId) {
+ const history = await loadHistory();
+ const item = history.find((h) => h.id === historyId);
+ if (!item) throw new ServerError('Video not found', { status: 404, code: 'NOT_FOUND' });
+ if (!/^[a-f0-9-]{36}$/i.test(item.id)) {
+ throw new ServerError('Invalid history id', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ const sourcePath = safeUnder(PATHS.videos, item.filename);
+ if (!sourcePath) throw new ServerError('Invalid video filename', { status: 400, code: 'VALIDATION_ERROR' });
+ if (!existsSync(sourcePath)) throw new ServerError('Video file not found on disk', { status: 404, code: 'NOT_FOUND' });
+
+ const newId = randomUUID();
+ const newFilename = `${newId}.mp4`;
+ const newPath = join(PATHS.videos, newFilename);
+ // Copy first, then upscale-in-place — keeps the upscaler's atomic-rename
+ // contract intact and means a mid-process kill leaves the source clip
+ // untouched.
+ await copyFile(sourcePath, newPath);
+ console.log(`🔍 Upscaling video [${historyId.slice(0, 8)} → ${newId.slice(0, 8)}]: 2×`);
+ const result = await upscaleVideo2x(newPath);
+ if (!result.ok) {
+ await unlink(newPath).catch(() => {});
+ throw new ServerError(`Upscale failed: ${result.reason}`, { status: 500, code: 'FFMPEG_FAILED' });
+ }
+ const thumbnail = await generateThumbnail(newPath, newId);
+ // Build the new history entry from the original, but bump dimensions and
+ // tag with `upscaledFrom: <id>` + a reusable suffix on the prompt so the
+ // gallery row reads as "<original prompt> (2×)".
+ const newEntry = {
+ ...item,
+ id: newId,
+ filename: newFilename,
+ width: (Number(item.width) || 0) * 2,
+ height: (Number(item.height) || 0) * 2,
+ thumbnail,
+ createdAt: new Date().toISOString(),
+ upscaledFrom: item.id,
+ prompt: item.prompt ? `${item.prompt} (2×)` : '(upscaled 2×)',
+ // Drop hidden so the upscaled version surfaces in the visible gallery
+ // even when the source clip was hidden.
+ hidden: false,
+ };
+ const refreshedHistory = await loadHistory();
+ refreshedHistory.unshift(newEntry);
+ await saveHistory(refreshedHistory);
+ console.log(`✅ Upscaled [${newId.slice(0, 8)}]: ${newFilename} (${newEntry.width}×${newEntry.height})`);
+ return newEntry;
+}
+
export async function setHistoryItemHidden(id, hidden) {
const history = await loadHistory();
const item = history.find((h) => h.id === id);