Skip to content

Make videos on the computer you already own. FreeVideo runs MiniMax H3 in as little as 8 GB of VRAM and 16 GB of RAM, and adapts its acceleration path to your hardware.

Generation preview plays its sampled frames as a loop instead of a still contact sheet

Bowen Xue91d396572baa
diff --git a/freevideo_engine/comfy_bridge.py b/freevideo_engine/comfy_bridge.py
index 31dcf63..cf1fa8a 100644
--- a/freevideo_engine/comfy_bridge.py
+++ b/freevideo_engine/comfy_bridge.py
@@ -970,8 +970,11 @@ class EventTail:
def preview_state(event):
"""The few facts the page needs to show the newest frame preview, or None."""
values = {key: event.get(key) for key in ('serial', 'step', 'total', 'frames', 'frame_width', 'frame_height')}
- if any(type(value) is not int or value < 1 or value > 100000 for value in values.values()) or values['frames'] > 8:
+ if any(type(value) is not int or value < 1 or value > 100000 for value in values.values()) or values['frames'] > 16:
return None
+ duration = event.get('duration_ms') # optional: the playback speed follows the video's length
+ if type(duration) is int and 0 < duration <= 86400000:
+ values['duration_ms'] = duration
return values
diff --git a/freevideo_engine/frame_preview.py b/freevideo_engine/frame_preview.py
index f59c605..ba47d8f 100644
--- a/freevideo_engine/frame_preview.py
+++ b/freevideo_engine/frame_preview.py
@@ -2,7 +2,8 @@
At each step the scheduler already holds the model's prediction of the clean
latents. A fixed per-pixel affine map from the 24 latent channels to RGB turns
-four of those latent frames into a small picture without running the VAE. The
+up to sixteen evenly spaced latent frames into one small strip without running
+the VAE, which the page plays as a loop. The
observer only reads tensors the sampler already produced and never writes to
them, so the sampled latents are identical with it on or off. Any failure
silently turns it off for the rest of the request.
@@ -17,7 +18,7 @@ FILE = 'frame-preview.jpg'
MARKER = 'frame-preview-off'
ENV = 'FREEVIDEO_FRAME_PREVIEW'
FIRST_STEP = 3
-FRAMES = 4
+FRAMES = 16 # evenly spaced latent frames in the strip; the page guards use the same bound
QUALITY = 82
MAX_FRAME_WIDTH = 336
CHANNELS = 24
@@ -110,10 +111,11 @@ def _fail():
class _Preview:
- def __init__(self, latent_frames, frame_h, frame_w, step_offset, total):
+ def __init__(self, latent_frames, frame_h, frame_w, step_offset, total, seconds=None):
self.rows = latent_frames * frame_h * frame_w
self.shape = (latent_frames, frame_h, frame_w)
self.step_offset, self.total = step_offset, total
+ self.duration_ms = round(seconds * 1000) if isinstance(seconds, (int, float)) and 0 < seconds < 86400 else None
self.calls = 0
count = min(FRAMES, latent_frames)
self.indices = sorted({round(i * (latent_frames - 1) / max(1, count - 1)) for i in range(count)})
@@ -164,18 +166,19 @@ class _Preview:
_serial = max(_serial + 1, step)
n = len(self.indices)
emit(dict(event='frame_preview', step=step, total=self.total, serial=_serial, frames=n,
- frame_width=strip.shape[1] // n, frame_height=strip.shape[0]))
+ frame_width=strip.shape[1] // n, frame_height=strip.shape[0],
+ **({'duration_ms': self.duration_ms} if self.duration_ms else {})))
@contextmanager
-def observing(*, latent_frames, frame_h, frame_w, step_offset=0, total=None):
+def observing(*, latent_frames, frame_h, frame_w, step_offset=0, total=None, seconds=None):
"""Observe the video scheduler of one sampling pass; no-op unless configured."""
global _active
previous = _active
_active = None
if _sink is not None and not _failed:
try:
- _active = _Preview(latent_frames, frame_h, frame_w, step_offset, total)
+ _active = _Preview(latent_frames, frame_h, frame_w, step_offset, total, seconds)
except Exception:
_active = None
_fail()
diff --git a/freevideo_engine/macos_runtime.py b/freevideo_engine/macos_runtime.py
index 19a4185..6bce3c5 100644
--- a/freevideo_engine/macos_runtime.py
+++ b/freevideo_engine/macos_runtime.py
@@ -602,7 +602,8 @@ class Engine:
progress.layers(self.model.transformer_blocks), \
frame_preview.observing(latent_frames=canvas['latent_frames'], frame_h=height // 32,
frame_w=width // 32, step_offset=progress_offset + start,
- total=progress_total if progress_total is not None else active_steps):
+ total=progress_total if progress_total is not None else active_steps,
+ seconds=canvas.get('seconds')):
self.residency = residency
from .step_cache import begin_pass, end_pass
step_cache = None
diff --git a/freevideo_engine/runtime.py b/freevideo_engine/runtime.py
index 49226a7..5d08750 100644
--- a/freevideo_engine/runtime.py
+++ b/freevideo_engine/runtime.py
@@ -862,7 +862,8 @@ class Engine:
(watch.layers(self.transformer.transformer_blocks) if watch is not None else nullcontext()), \
frame_preview.observing(latent_frames=canvas.get('latent_frames'), frame_h=height // 32,
frame_w=width // 32, step_offset=progress_offset,
- total=progress_total if progress_total is not None else active_steps):
+ total=progress_total if progress_total is not None else active_steps,
+ seconds=canvas.get('seconds')):
from .step_cache import begin_pass, end_pass
if not refining:
disabled = ('residual_offload' if self.config.get('residual_offload') and self.config.get('step_cache') == 'fbcache' else
diff --git a/web/generation_progress.css b/web/generation_progress.css
index 2485fd5..b540771 100644
--- a/web/generation_progress.css
+++ b/web/generation_progress.css
@@ -25,10 +25,10 @@
.fv-generation-status{box-sizing:border-box;width:100%;flex:none;margin-top:10px;font-size:12px;line-height:18px;color:var(--fv-muted,#a2abba);text-align:center;text-wrap:balance}
.fv-generation-compatibility{box-sizing:border-box;width:100%;flex:none;margin-top:10px;font-size:12px;line-height:18px;color:var(--fv-ink,#e8edf5);text-align:center;text-wrap:balance}
.fv-generation-compatibility[hidden]{display:none!important}
-.fv-generation-frames{display:block;box-sizing:border-box;width:auto;max-width:100%;max-height:min(30vh,200px);margin:12px auto 0;border-radius:var(--fv-r-sm,6px);object-fit:contain;background:var(--fv-raised,#212a37)}
-.fv-studio .fv-stage .fv-generation-frames{width:auto;height:auto}
-.fv-generation-frames[data-wide=true],.fv-studio .fv-stage .fv-generation-frames[data-wide=true]{height:64px}
-.fv-generation-frames[hidden]{display:none!important}
+.fv-generation-frames{display:block;box-sizing:border-box;width:auto;max-width:100%;height:min(var(--fv-frame-height,120px),120px);aspect-ratio:var(--fv-frame-ratio,16 / 9);margin:12px auto 0;border-radius:var(--fv-r-sm,6px);background:var(--fv-raised,#212a37) no-repeat 0 0}
+.fv-generation-frames[data-wide=true],.fv-studio .fv-stage .fv-generation-frames[data-wide=true]{height:128px}
+.fv-generation-frames[hidden],.fv-generation-frames[data-fit=false]{display:none!important}
+.fv-studio .fv-stage .fv-generation-progress[data-tight=true],.fv-studio .fv-stage .fv-generation-progress.fv-generation-compact[data-tight=true]{padding:8px 16px}
.fv-studio .fv-stage[data-short=true] .fv-generation-frames{display:none!important}
.fv-generation-live{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap;border:0}
/* Studio shows progress with the preview's rising wave, so its bar stays
diff --git a/web/generation_progress.js b/web/generation_progress.js
index def8c13..83aa711 100644
--- a/web/generation_progress.js
+++ b/web/generation_progress.js
@@ -449,8 +449,8 @@ export function createGenerationProgress(t, now = () => Date.now(), {compact = f
const track = el('div', 'fv-generation-track'), fill = el('div', 'fv-generation-fill');
track.setAttribute('role', 'progressbar'); track.setAttribute('aria-valuemin', '0'); track.append(fill);
// The sampler's newest coarse frames; decorative, so it carries no text.
- const frames = el('img', 'fv-generation-frames'); frames.alt = ''; frames.hidden = true;
- frames.decoding = 'async'; frames.setAttribute('aria-hidden', 'true'); frames.draggable = false;
+ // One frame shows in place; the strip of frames plays through it as a loop (see playFrames).
+ const frames = el('div', 'fv-generation-frames'); frames.hidden = true; frames.setAttribute('aria-hidden', 'true');
const times = el('div', 'fv-generation-times');
const elapsed = el('span', ''), eta = el('span', 'fv-generation-eta'); times.append(elapsed, eta);
const late = el('div', 'fv-generation-late'); late.hidden = true;
@@ -517,22 +517,60 @@ export function createGenerationProgress(t, now = () => Date.now(), {compact = f
const {report, updateReport, fetchReport, downloadReport} = diagnostic;
// The newest frame picture. Any failure leaves the page as it was without one.
// `framesToken` changes whenever a pending fetch stops being wanted, so a late answer is dropped.
- let framesKey = '', framesUrl = null, framesLoading = null, framesToken = 0;
+ let framesKey = '', framesUrl = null, framesLoading = null, framesToken = 0, strip = null, stripTimer = null;
+ function stopPlayback() { if (stripTimer !== null) cancelAnimationFrame(stripTimer); stripTimer = null; }
function clearFrames() {
- framesKey = ''; framesLoading = null; framesToken++; frames.hidden = true;
+ framesKey = ''; framesLoading = null; framesToken++; frames.hidden = true; strip = null; stopPlayback();
if (framesUrl) { URL.revokeObjectURL(framesUrl); framesUrl = null; }
- frames.removeAttribute('src');
+ frames.style.backgroundImage = '';
}
- // In a wide column each frame is 64 px high; a narrow one keeps the picture's own size.
+ // The frame is at most 128 px high in a wide column and 120 px in a narrow one, never above the picture's own
+ // height. In the Studio stage the percentage, step and times come first: the frame takes what is left of the
+ // stage (the padding shrinks first, as in a short stage) and is left out below 48 px.
+ let fitWatch = null;
function fitFrames() {
const width = (element.parentElement || element).clientWidth;
- frames.dataset.wide = width > 480 ? 'true' : 'false';
+ const wide = width > 480;
+ frames.dataset.wide = wide ? 'true' : 'false';
+ const stage = element.closest?.('.fv-stage') ?? null;
+ if (typeof ResizeObserver === 'function') {
+ fitWatch ??= new ResizeObserver(() => fitFrames());
+ fitWatch.observe(element.parentElement || element); if (stage) fitWatch.observe(stage);
+ }
+ if (!strip || frames.hidden) return;
+ let height = Math.min(wide ? 128 : 120, strip.height), tight = false;
+ if (stage && stage.clientHeight > 0) {
+ const room = () => {
+ frames.style.display = 'none';
+ const rest = element.offsetHeight;
+ frames.style.display = '';
+ return Math.floor(stage.clientHeight - rest - 12);
+ };
+ element.dataset.tight = 'false';
+ let left = room();
+ if (left < height) { tight = true; element.dataset.tight = 'true'; left = room(); }
+ height = Math.min(height, left);
+ }
+ if (height < 48) { frames.dataset.fit = 'false'; element.dataset.tight = 'false'; }
+ else { frames.dataset.fit = 'true'; frames.style.height = `${height}px`; }
+ }
+ // Where the loop stands, from 0 up to (not including) 1.
+ const stripPhase = () => strip ? (strip.phase + (now() - strip.start) / 1000 * strip.fps / strip.count) % 1 : 0;
+ // The strip plays forward at its frames per second over the video's length, 4 to 8 a second; with reduced
+ // motion, or a single frame, the last frame stands still.
+ function playFrames() {
+ stripTimer = null;
+ if (!strip || frames.hidden) return;
+ const playing = strip.count > 1 && moving();
+ const index = playing ? Math.min(strip.count - 1, Math.floor(stripPhase() * strip.count)) : strip.count - 1;
+ frames.style.backgroundPosition = strip.count > 1 ? `${100 * index / (strip.count - 1)}% 0` : '0 0';
+ if (playing) stripTimer = requestAnimationFrame(playFrames);
}
function updateFrames(message, id) {
const value = message.frame_preview;
fitFrames();
const usable = value && typeof value === 'object' && Number.isInteger(value.serial) && value.serial > 0
- && Number.isInteger(value.frames) && value.frames > 0 && value.frames <= 8;
+ && Number.isInteger(value.frames) && value.frames > 0 && value.frames <= 16;
if (!usable || !id || ['complete', 'failed', 'cancelled'].includes(message.phase)) { if (framesKey || framesLoading) clearFrames(); return; }
const key = `${id}:${value.serial}`;
if (key === framesKey || key === framesLoading) return;
@@ -540,18 +578,32 @@ export function createGenerationProgress(t, now = () => Date.now(), {compact = f
const token = ++framesToken;
const path = `/freevideo/frame-preview/${id}`;
(async () => {
+ let url = null;
try {
const response = await (api ? api.fetchApi(path) : fetch(path));
if (!response.ok) throw new Error('No picture');
const blob = await response.blob();
if (framesToken !== token) return;
- const url = URL.createObjectURL(blob);
- const old = framesUrl;
- frames.onload = () => { fitFrames(); if (framesUrl === url) frames.hidden = false; try { onLayout?.(); } catch {} };
- frames.onerror = () => { if (framesUrl === url) clearFrames(); };
- framesUrl = url; framesKey = key; frames.src = url;
+ url = URL.createObjectURL(blob);
+ // The new strip replaces the old one only once it has loaded, and the loop carries on from the same place.
+ const picture = new Image();
+ await new Promise((resolve, reject) => { picture.onload = resolve; picture.onerror = () => reject(new Error('No picture')); picture.src = url; });
+ if (framesToken !== token) { URL.revokeObjectURL(url); return; }
+ const seconds = Number.isInteger(value.duration_ms) && value.duration_ms > 0 ? value.duration_ms / 1000 : null;
+ const fps = Math.min(8, Math.max(4, seconds ? value.frames / seconds : 6));
+ const frameWidth = picture.naturalWidth / value.frames, frameHeight = picture.naturalHeight;
+ const old = framesUrl, phase = stripPhase();
+ strip = {count: value.frames, fps, phase, start: now(), height: frameHeight};
+ frames.style.setProperty('--fv-frame-height', `${frameHeight}px`);
+ frames.style.setProperty('--fv-frame-ratio', `${frameWidth} / ${frameHeight}`);
+ frames.style.backgroundSize = `${value.frames * 100}% 100%`;
+ frames.style.backgroundImage = `url("${url}")`;
+ framesUrl = url; framesKey = key; framesLoading = null;
+ frames.hidden = false; fitFrames(); stopPlayback(); playFrames();
+ try { onLayout?.(); } catch {}
if (old) URL.revokeObjectURL(old);
} catch {
+ if (url && url !== framesUrl) URL.revokeObjectURL(url);
if (framesToken === token) clearFrames();
}
})();
diff --git a/web/phone.js b/web/phone.js
index 0943f35..1434109 100644
--- a/web/phone.js
+++ b/web/phone.js
@@ -138,14 +138,34 @@ compose.onsubmit = async event => {
} catch { notice(t('Could not send. Please try again.', '没有发送成功,请重试。')); }
finally { sending = false; grow(); }
};
-function picture(job, preview = false) {
+// Large previews play their strip forward as a loop, 4 to 8 frames a second over the video's length. The position
+// follows the clock, so a redraw that builds a new image carries on from the same place; with reduced motion, or in the
+// small list picture, the last frame stands still.
+const playing = new Set();
+let playTimer = null;
+const reducedMotion = () => typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
+function playStrips() {
+ playTimer = null;
+ for (const item of playing) {
+ if (!item.img.isConnected) { playing.delete(item); continue; }
+ const index = Math.min(item.count - 1, Math.floor((Date.now() / 1000 * item.fps / item.count) % 1 * item.count));
+ item.img.style.transform = `translateX(-${index * 100 / item.count}%)`;
+ }
+ if (playing.size && !reducedMotion() && typeof requestAnimationFrame === 'function') playTimer = requestAnimationFrame(playStrips);
+}
+function picture(job, preview = false, play = false) {
const box = el('div', 'phone-picture');
const p = job.progress || {}, frame = p.frame_preview;
- const path = preview && frame?.serial > 0 && frame.frames > 0 && frame.frames <= 8 && job.node != null
+ const path = preview && frame?.serial > 0 && frame.frames > 0 && frame.frames <= 16 && job.node != null
? `/freevideo/frame-preview/${encodeURIComponent(job.node)}?serial=${frame.serial}` : mediaPath(job.thumbnail, 'image');
if (path) {
const img = el('img'); img.alt = ''; img.loading = 'lazy'; img.src = path; box.append(img);
- if (preview && frame?.frames > 0) { box.classList.add('strip'); img.style.width = `${frame.frames * 100}%`; img.style.transform = `translateX(-${(frame.frames - 1) * 100 / frame.frames}%)`; }
+ if (preview && frame?.frames > 0) { box.classList.add('strip'); img.style.width = `${frame.frames * 100}%`; img.style.transform = `translateX(-${(frame.frames - 1) * 100 / frame.frames}%)`;
+ if (play && frame.frames > 1 && !reducedMotion()) {
+ const seconds = frame.duration_ms > 0 ? frame.duration_ms / 1000 : null;
+ playing.add({img, count: frame.frames, fps: Math.min(8, Math.max(4, seconds ? frame.frames / seconds : 6))});
+ if (playTimer === null && typeof requestAnimationFrame === 'function') playTimer = requestAnimationFrame(playStrips);
+ } }
img.onerror = () => { img.remove(); box.closest('.phone-frame')?.classList.add('no-frame'); };
}
return box;
@@ -206,7 +226,7 @@ function renderJobs() {
if (running.length) generations.append(el('h2', 'phone-section', t('Generating', '正在生成')));
for (const job of running) {
const card = el('article', 'phone-running'), frame = el('div', 'phone-frame'), info = el('div', 'phone-info'); card.dataset.job = job.id;
- const img = picture(job, true); img.style.aspectRatio = `${job.width || 9}/${job.height || 16}`; frame.append(img); frame.classList.toggle('no-frame', !img.firstChild);
+ const img = picture(job, true, true); img.style.aspectRatio = `${job.width || 9}/${job.height || 16}`; frame.append(img); frame.classList.toggle('no-frame', !img.firstChild);
if (!img.firstChild) frame.append(el('span', 'phone-frame-pct', `${Math.floor(fraction(job) * 100)}%`));
const row = el('div', 'phone-job-row'), numbers = el('div'); numbers.append(el('span', 'phone-pct', `${Math.floor(fraction(job) * 100)}%`), document.createTextNode(' '), el('span', 'phone-eta', remainingWords(job.progress?.remaining_seconds, t)));
const stop = button('phone-quiet', t('Stop', '停止'), () => cancel(job, true)); stop.disabled = job.status === 'cancelling'; stop.dataset.action = 'stop-' + job.id; row.append(numbers, stop);