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.

Long video parts: redo a part as a new video, part details, seam playback and a seam check

Bowen Xue41698c86f60d
diff --git a/freevideo_engine/chain_leads.py b/freevideo_engine/chain_leads.py
index bfa0f90..a6ef240 100644
--- a/freevideo_engine/chain_leads.py
+++ b/freevideo_engine/chain_leads.py
@@ -55,6 +55,27 @@ def load(directory, chain, index, previous, output=None):
return None
+def copy(directory, source, target, index):
+ """Give chain `target` the seam sound `source` kept for block `index`; False when there is none."""
+ import os
+ import uuid
+ origin, path = _path(directory, source, index), _path(directory, target, index)
+ try:
+ data = origin.read_bytes()
+ except FileNotFoundError:
+ return False
+ temporary = path.with_name(path.name + '.' + uuid.uuid4().hex[:8] + '.tmp')
+ try:
+ with temporary.open('wb') as stream:
+ stream.write(data)
+ stream.flush()
+ os.fsync(stream.fileno())
+ os.replace(temporary, path)
+ finally:
+ temporary.unlink(missing_ok=True)
+ return True
+
+
def has(directory, chain, index):
try:
return _path(directory, chain, index).is_file()
diff --git a/freevideo_engine/chain_runner.py b/freevideo_engine/chain_runner.py
index 2194ded..bf37a1f 100644
--- a/freevideo_engine/chain_runner.py
+++ b/freevideo_engine/chain_runner.py
@@ -3,7 +3,8 @@ from copy import deepcopy
import json
import logging
import math
-from pathlib import PurePosixPath
+from pathlib import Path, PurePosixPath
+import random
import threading
import time
import uuid
@@ -68,8 +69,9 @@ def node_prompt(prompt, node):
class ChainRunner:
def __init__(self, store_dir, host, clock=time.monotonic, wall=time.time, estimate=None, poll=0.5, inputs=None,
- max_parts=None, min_part_frames=None):
+ max_parts=None, min_part_frames=None, seeds=None):
self.store_dir, self.host = store_dir, host
+ self.seeds = seeds or random.SystemRandom()
self.max_parts = max_parts or store.MAX_PARTS
self.min_part_frames = chain_plan.MIN_PART_FRAMES if min_part_frames is None else min_part_frames
self.clock, self.wall, self.estimate, self.poll = clock, wall, estimate, poll
@@ -336,6 +338,81 @@ class ChainRunner:
self.wake.set()
return self._view(record)
+ def redo(self, chain_id, block_id, text=None, client_id=None):
+ """A new chain that keeps the parts before `block_id` and makes that part and every later one
+ again with new seeds. Later parts continue the part before them, so redoing one part alone would
+ break the next seam. The original chain, its parts and its joined video stay as they are."""
+ if text is not None and (not isinstance(text, str) or not text.strip() or len(text) > 20000):
+ raise ValueError('Text must be a nonempty string of at most 20000 characters')
+ if client_id is not None and not isinstance(client_id, str):
+ raise ValueError('Client ID must be a string')
+ from .lora_triggers import apply_chain_triggers
+ with self.lock:
+ source = self.records[chain_id]
+ start = next((row for row in source['blocks'] if row['id'] == block_id), None)
+ if start is None:
+ raise KeyError(block_id)
+ if source['state'] in store.ACTIVE or source['output_state'] == 'joining':
+ raise ChainBusy('This chain is already active')
+ kept = [row for row in source['blocks'] if row['index'] < start['index']]
+ if any(row['state'] != 'done' or not row['output'] for row in kept):
+ raise ValueError('The parts before this one are not finished')
+ names = {row['id'] for row in kept}
+ if any(isinstance(row[key], str) and row[key] not in names for row in kept for key in ('after', 'before')):
+ raise ValueError('A kept part depends on a part that is made again')
+ record = deepcopy(source)
+ identity = source['id']
+ while identity in self.records or (Path(self.store_dir) / (identity + '.json')).exists():
+ identity = 'c-' + uuid.uuid4().hex[:12]
+ for key in ('last_report_id', 'last_heartbeat_at', 'output_seams', 'join_final_state'):
+ record.pop(key, None)
+ now = self.wall()
+ record.update(id=identity, created=now, state='queued', redo_of=dict(chain=chain_id, block=block_id),
+ output=None, output_state='pending' if record['join'] else 'none',
+ output_error=None, output_blocks=0)
+ if client_id is not None:
+ record['client_id'] = client_id
+ if record.get('split') is not None and record['split']['state'] == 'running':
+ record['split']['state'] = 'pending'
+ for block in record['blocks'][start['index']:]:
+ seed = block['inputs']['seed']
+ while seed == block['inputs']['seed']:
+ seed = self.seeds.randrange(2 ** 31)
+ block['inputs']['seed'] = seed
+ block.update(state='pending', prompt_id=None, attempts=0, started=None, finished=None,
+ seconds=None, output=None, report_id=None, error=None,
+ fraction=0., remaining_seconds=None, continuation=None,
+ skip_frames=0, skip_audio_samples=0)
+ if text is not None:
+ # Only the new words take the LoRA triggers; the other parts keep their texts as written.
+ probe = dict(node=record['node'], snapshot=deepcopy(record['snapshot']),
+ blocks=[dict(inputs=dict(text=text))])
+ try:
+ apply_chain_triggers(probe)
+ except Exception:
+ raise ValueError('Text must be at most 20000 characters with LoRA triggers') from None
+ record['blocks'][start['index']]['inputs']['text'] = probe['blocks'][0]['inputs']['text']
+ short = [row['inputs']['frames'] for row in record['blocks']
+ if (row['after'] is not None or row['before'] is not None)
+ and row['inputs']['frames'] < self.min_part_frames]
+ if short:
+ raise ChainPartTooShort(min(short) / chain_plan.FPS, chain_plan.MIN_PART_SECONDS)
+ parts = max(self._depths(record).values())
+ if parts > self.max_parts:
+ raise ChainTooLong(parts, self.max_parts)
+ # The kept seams are repaired with the sound the original chain kept for them. Copies left by
+ # a failed save have no record, so the next start prunes them.
+ try:
+ for row in kept[1:]:
+ chain_leads.copy(self.store_dir, chain_id, identity, row['index'])
+ self._save(record)
+ except OSError:
+ raise ValueError('The kept parts could not be copied') from None
+ self.records[identity] = record
+ self.queue.append(identity)
+ self.wake.set()
+ return self._view(record)
+
def list(self, client_id=None):
with self.lock:
records = [row for row in self.records.values()
diff --git a/freevideo_engine/chain_store.py b/freevideo_engine/chain_store.py
index 2c2c5d4..de2c093 100644
--- a/freevideo_engine/chain_store.py
+++ b/freevideo_engine/chain_store.py
@@ -198,6 +198,7 @@ def summary(record):
('version', 'id', 'node', 'created', 'updated', 'state',
'join', 'output', 'output_state', 'output_error', 'output_blocks')},
output_seams=deepcopy(record.get('output_seams')), split=deepcopy(record.get('split')),
+ redo_of=deepcopy(record.get('redo_of')),
count=len(blocks), done=sum(row['state'] == 'done' for row in blocks),
current=current, elapsed_seconds=sum(row['seconds'] or 0 for row in blocks if row['state'] == 'done'),
last_report_id=record.get('last_report_id') or next((row['report_id'] for row in reversed(blocks)
@@ -268,6 +269,12 @@ def load_all(directory, limit=200, *, identity=None):
if seams is not None and (not isinstance(seams, dict) or set(seams) != {'expected', 'kept'}
or any(type(value) is not int or value < 0 for value in seams.values())):
raise ValueError('Invalid chain seam count')
+ redo = record.get('redo_of')
+ if redo is not None and (not isinstance(redo, dict) or set(redo) != {'chain', 'block'}
+ or not isinstance(redo['chain'], str)
+ or not re.fullmatch(r'c-[0-9a-f]{12}', redo['chain'])
+ or not isinstance(redo['block'], str) or not redo['block']):
+ raise ValueError('Invalid chain redo source')
if record.get('join_final_state', 'done') not in ('done', 'cancelled', 'failed', 'interrupted'):
raise ValueError('Invalid chain join final state')
if record['plan'] is not None:
diff --git a/freevideo_engine/comfy_chain.py b/freevideo_engine/comfy_chain.py
index cb50be2..482e681 100644
--- a/freevideo_engine/comfy_chain.py
+++ b/freevideo_engine/comfy_chain.py
@@ -408,6 +408,32 @@ def register(host_factory=None):
except ValueError as failure:
return response({'error': str(failure)}, 400)
+ @server.routes.post('/freevideo/chain/{id}/blocks/{block}/redo')
+ async def redo(request):
+ # A new chain from this part on; the original chain and its video are kept.
+ try:
+ value = await body(request) if request.can_read_body else {}
+ identity, block = request.match_info['id'], request.match_info['block']
+ if not fake and os.environ.get('FREEVIDEO_CHAIN_INDEPENDENT') != '1':
+ missing = {key for row in runner.get(identity)['blocks'] for key in CONTINUE_INPUTS
+ if row[key] is not None} - continuation_directions()
+ if missing:
+ return response({'error': 'Continuing a video is not available in this version'}, 409)
+ return response({'chain': await asyncio.to_thread(runner.redo, identity, block,
+ value.get('text'), value.get('client_id'))})
+ except KeyError:
+ return response({'error': 'Unknown chain or part'}, 404)
+ except ChainBusy as failure:
+ return response({'error': str(failure)}, 409)
+ except ChainTooLong as failure:
+ return response({'error': str(failure), 'error_zh': failure.message_zh, 'code': failure.code,
+ 'parts': failure.parts, 'max_parts': failure.limit}, 400)
+ except ChainPartTooShort as failure:
+ return response({'error': str(failure), 'error_zh': failure.message_zh, 'code': failure.code,
+ 'min_seconds': failure.limit}, 400)
+ except ValueError as failure:
+ return response({'error': str(failure)}, 400)
+
@server.routes.post('/freevideo/chain/{id}/resume')
async def resume(request):
try:
diff --git a/web/studio.css b/web/studio.css
index 3eb8aef..2308945 100644
--- a/web/studio.css
+++ b/web/studio.css
@@ -203,22 +203,31 @@
.fv-studio .fv-first-frame input:checked{background:var(--fv-accent,#6db8fa)}
.fv-studio .fv-first-frame input:checked::before{transform:translateX(10px)}
.fv-studio .fv-first-frame:has(input:disabled){opacity:.4}
-.fv-studio .fv-chain-parts{display:grid;gap:2px;margin-top:-7px}
+/* Lines share the list's columns, so names, lengths and words line up whatever each line holds. */
+.fv-studio .fv-chain-parts{display:grid;grid-template-columns:auto auto minmax(0,1fr) auto auto;gap:2px 14px;margin-top:-7px}
.fv-studio .fv-chain-parts[hidden]{display:none}
-.fv-studio .fv-chain-part{display:grid;grid-template-columns:auto minmax(0,1fr) auto;align-items:start;gap:14px;padding:4px 4px 4px 12px;border-radius:var(--fv-r-sm);font-size:var(--fv-micro);line-height:20px}
-.fv-studio .fv-chain-part-name{padding-top:7px;color:var(--fv-muted);white-space:nowrap}
-.fv-studio .fv-chain-part .fv-chain-part-text{display:block;min-width:0;min-height:32px;padding:6px 10px;border-color:transparent;background:transparent;color:var(--fv-ink);font-weight:var(--fv-regular);text-align:left;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
+.fv-studio .fv-chain-part{display:grid;grid-column:1/-1;grid-template-columns:subgrid;align-items:start;padding:4px 4px 4px 12px;border-radius:var(--fv-r-sm);font-size:var(--fv-micro);line-height:20px}
+.fv-studio .fv-chain-part-name{grid-column:1;grid-row:1;padding-top:7px;color:var(--fv-muted);white-space:nowrap}
+.fv-studio .fv-chain-part .fv-chain-part-meta{grid-column:2;grid-row:1;align-self:start;justify-self:start;display:block;min-height:0;padding:7px 0 0;border:0;border-radius:2px;background:none;color:var(--fv-muted);font-weight:inherit;white-space:nowrap;text-align:left}
+.fv-studio .fv-chain-part .fv-chain-part-meta:disabled{opacity:1}
+.fv-studio .fv-chain-part .fv-chain-part-meta:not(:disabled){text-decoration:underline;text-decoration-color:var(--fv-border);text-underline-offset:3px}
+.fv-studio .fv-chain-part .fv-chain-part-meta:not(:disabled):hover{background:none;color:var(--fv-ink);text-decoration-color:currentColor}
+/* Sized like the Creations button above the preview, so it reads as a button and not as a state. */
+.fv-studio .fv-chain-part .fv-chain-part-redo{grid-column:5;grid-row:1;min-height:var(--fv-h-sm);padding:5px 12px;white-space:nowrap}
+.fv-studio .fv-chain-part .fv-chain-part-redo[hidden]{display:none}
+.fv-studio .fv-chain-part .fv-chain-part-text{grid-column:3;grid-row:1;display:block;min-width:0;min-height:32px;padding:6px 10px;border-color:transparent;background:transparent;color:var(--fv-ink);font-weight:var(--fv-regular);text-align:left;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.fv-studio .fv-chain-part:has(.fv-chain-part-text:not(:disabled):not([hidden])):hover{background:var(--fv-hover);cursor:text}
.fv-studio .fv-chain-part:has(.fv-chain-part-text:not(:disabled):not([hidden])):hover .fv-chain-part-text{background:transparent;cursor:text}
.fv-studio .fv-chain-part .fv-chain-part-text:disabled{opacity:1;color:var(--fv-disabled)}
-.fv-studio .fv-chain-part:has(.fv-chain-part-text:disabled) :is(.fv-chain-part-name,.fv-chain-part-tag:not([data-kind=error])){color:var(--fv-disabled)}
+.fv-studio .fv-chain-part:has(.fv-chain-part-text:disabled) :is(.fv-chain-part-name,.fv-chain-part-meta,.fv-chain-part-tag:not([data-kind=error]):not([data-kind=failed])){color:var(--fv-disabled)}
.fv-studio .fv-chain-part-text[hidden]{display:none}
-.fv-studio .fv-chain-part-edit{position:relative;min-width:0}
+.fv-studio .fv-chain-part-edit{grid-column:3;grid-row:1;position:relative;min-width:0}
.fv-studio .fv-chain-part .fv-chain-part-editor{min-height:76px;height:96px;max-height:220px;padding:6px 36px 6px 10px;font-size:var(--fv-micro);line-height:20px;outline:none}
-.fv-studio .fv-chain-part-tag{padding:7px 8px 0 0;color:var(--fv-muted);white-space:nowrap}
+.fv-studio .fv-chain-part-tag{grid-column:4;grid-row:1;padding:7px 8px 0 0;color:var(--fv-muted);white-space:nowrap}
.fv-studio .fv-chain-part-tag:empty{display:none}
.fv-studio .fv-chain-part-tag[data-kind=error]{color:var(--fv-warning);white-space:normal;max-width:16em;text-align:right}
-@media(max-width:680px){.fv-studio .fv-chain-part{gap:8px;padding-left:4px}}
+.fv-studio .fv-chain-part-tag[data-kind=failed]{color:var(--fv-danger)}
+@media(max-width:680px){.fv-studio .fv-chain-parts{grid-template-columns:auto minmax(0,1fr) auto;column-gap:8px}.fv-studio .fv-chain-part{row-gap:0;padding-left:4px}.fv-studio .fv-chain-part .fv-chain-part-meta{grid-column:1;grid-row:2;align-self:center;min-height:32px;margin:4px 0;padding:0;display:flex;align-items:center}.fv-studio .fv-chain-part :is(.fv-chain-part-text,.fv-chain-part-edit){grid-column:2}.fv-studio .fv-chain-part-tag{grid-column:3;text-align:right}.fv-studio .fv-chain-part .fv-chain-part-redo{grid-column:2/4;grid-row:2;justify-self:end;margin:4px 0}}
.fv-studio .fv-request-assets{font-size:12px;line-height:1.5;margin:0 0 8px}
.fv-lora-problem{grid-column:var(--lora-lead,2)/span 3;grid-row:4;display:flex;flex-direction:column;align-items:flex-start;gap:6px;font-size:var(--fv-micro)}.fv-lora-problem p{margin:0;color:var(--fv-danger)}.fv-lora-problem.fv-lora-partial{color:var(--fv-muted)}.fv-lora-problem[hidden]{display:none}.fv-lora-why summary{cursor:pointer;color:var(--fv-muted)}.fv-lora-why pre{margin:6px 0 0;white-space:pre-wrap;word-break:break-all;color:var(--fv-muted);font:inherit;font-family:ui-monospace,monospace}.fv-lora-row[data-unusable=true] select{color:var(--fv-muted)}
diff --git a/web/studio.js b/web/studio.js
index ecc8c57..a03a98e 100644
--- a/web/studio.js
+++ b/web/studio.js
@@ -42,7 +42,7 @@ import { createFirstRunGuide } from './first_run_guide.js';
import { SHOWCASE_SCENE } from './entry_showcase.js';
import { createStudioLength, savedSeconds } from './studio_length.js?v=20261011-length';
import { firstFrameRow } from './first_frame_row.js';
-import { createStudioChain, chainPosition, chainParts, chainSplit, readChainResult, sumPartEstimates, singleRunSnapshot } from './studio_chain.js?v=20261014-parts';
+import { createStudioChain, chainPosition, chainParts, chainSplit, readChainResult, sumPartEstimates, singleRunSnapshot } from './studio_chain.js?v=20261018-redo';
import { createExtendState, extendText, extendSourceExists, readExtendRecord, extendSnapshot, mountExtendThumbnail, videoUnavailableText } from './studio_extend.js';
const languageOverride = typeof location !== 'undefined'
@@ -75,7 +75,8 @@ const enhanceCss = document.createElement('link'); enhanceCss.rel = 'stylesheet'
const el = (tag, label, cls) => { const e = document.createElement(tag); if (label != null) e.textContent = label; if (cls) e.className = cls; return e; };
// One line per part of a long video, under the preview. A part that has not started opens in
// place for editing and saves when it loses focus; the server's reply decides what stays.
-function createChainPartList(t, save, {onShow = () => {}, onHide = () => {}} = {}) {
+// After the video stops, an ended part can be made again from there on as a new video.
+function createChainPartList(t, save, {onShow = () => {}, onHide = () => {}, redo = async () => {}, resume = async () => {}, playSeam = null} = {}) {
const element = el('div', null, 'fv-chain-parts'); element.hidden = true;
const rows = new Map(), timers = new Map();
let editing = null, showing = null;
@@ -93,8 +94,33 @@ function createChainPartList(t, save, {onShow = () => {}, onHide = () => {}} = {
if (!writing && row.editor) removeEditor(row);
// A note about a lost edit stays on its line until that part is done.
if (row.tag.dataset.kind === 'error' && part.state === 'done') row.tag.dataset.kind = '';
- if (timers.has(part.id) || row.tag.dataset.kind === 'error') return;
- tag(row, part.state === 'done' ? t('Done', '已完成') : part.editable || !['queued', 'running', 'pending'].includes(part.state) ? '' : t('Generating', '生成中'));
+ // In the joined video a continuing part plays its seam: two seconds either side.
+ const seam = playSeam && part.seam != null;
+ row.meta.disabled = !seam; row.meta.dataset.seam = String(seam);
+ if (seam) row.meta.setAttribute('aria-label', t(`Play the seam before part ${part.index + 1}`, `播放第 ${part.index + 1} 段的接缝`));
+ else row.meta.removeAttribute('aria-label');
+ // One way on per part: a stopped video continues from its first unfinished part; a finished part makes a new video.
+ const action = part.action, number = part.index + 1;
+ row.redo.hidden = !action;
+ if (action) {
+ row.redo.textContent = action === 'resume' ? t('Continue from here', '从这段继续') : t('Redo from here', '从这段重新生成');
+ row.redo.setAttribute('aria-label', action === 'resume' ? t(`Continue from part ${number}`, `从第 ${number} 段继续`)
+ : t(`Redo from part ${number}`, `从第 ${number} 段重新生成`));
+ }
+ if (timers.has(part.id) || row.tag.dataset.kind === 'error' || row.starting) return;
+ const ended = {done: t('Done', '已完成'), failed: t('Failed', '失败'), cancelled: t('Stopped', '已停止'), interrupted: t('Stopped', '已停止')}[part.state];
+ tag(row, ended ?? (part.live && !part.editable && ['queued', 'running', 'pending'].includes(part.state) ? t('Generating', '生成中') : ''),
+ part.state === 'failed' ? 'failed' : '');
+ }
+ async function remake(row) {
+ if (row.starting) return;
+ // The click answers at once; the new video replaces this list when the server takes it.
+ row.starting = true; row.redo.disabled = true; tag(row, t('Starting…', '正在开始…'));
+ try { await (row.part.action === 'resume' ? resume() : redo(row.part.id)); }
+ catch (error) {
+ if (rows.get(row.part.id) === row) flash(row, error.status === 409 ? t('Another video is generating. Try again when it finishes.', '正在生成别的视频,完成后再试。')
+ : t('Could not start. Try again.', '没能开始,请重试。'), 'error');
+ } finally { row.starting = false; row.redo.disabled = false; }
}
function flash(row, text, kind) {
clearTimeout(timers.get(row.part.id)); tag(row, text, kind);
@@ -150,9 +176,10 @@ function createChainPartList(t, save, {onShow = () => {}, onHide = () => {}} = {
element.hidden = true; element.replaceChildren(); rows.clear(); showing = null;
for (const id of timers.values()) clearTimeout(id); timers.clear();
}
- return {element, clear, update(chain, active) {
- // The list belongs to one generation: it shows once the descriptions are written and closes when that ends.
- if (!active || !chain?.split || chainSplit(chain).writing) { clear(); return; }
+ return {element, clear, resumes: () => !element.hidden && [...rows.values()].some(row => row.part.action === 'resume'), update(chain, active, shown = false) {
+ // The list belongs to one long video: it shows once the descriptions are written, and stays after the
+ // video stops while the preview still shows it.
+ if (!(active || shown) || !chain?.split || chainSplit(chain).writing) { clear(); return; }
if (showing !== chain.id) clear();
showing = chain.id;
const first = element.hidden; element.hidden = false;
@@ -164,19 +191,26 @@ function createChainPartList(t, save, {onShow = () => {}, onHide = () => {}} = {
}
parts.forEach((part, index) => {
part.state = chain.blocks[index].state === 'pending' && chain.blocks[index].prompt_id != null ? 'queued' : chain.blocks[index].state;
+ part.live = active;
let row = rows.get(part.id);
if (!row) {
row = {element: el('div', null, 'fv-chain-part'), tag: el('span', null, 'fv-chain-part-tag')};
row.text = el('button', null, 'fv-chain-part-text'); row.text.type = 'button';
+ row.redo = el('button', null, 'fv-chain-part-redo'); row.redo.type = 'button';
+ row.redo.onclick = event => { event.stopPropagation(); remake(row); };
row.element.onclick = () => open(row);
- row.element.append(el('span', t(`Part ${index + 1}`, `第 ${index + 1} 段`), 'fv-chain-part-name'), row.text, row.tag);
+ const joins = part.continues === 'part' ? t('After the previous part', '接上一段') : part.continues === 'video' ? t('After the video', '接原视频') : '';
+ row.meta = el('button', [joins, t(`${part.seconds} s`, `${part.seconds} 秒`)].filter(Boolean).join(' · '), 'fv-chain-part-meta');
+ row.meta.type = 'button';
+ row.meta.onclick = event => { event.stopPropagation(); if (row.part.seam != null) playSeam?.(row.part.seam); };
+ row.element.append(el('span', t(`Part ${index + 1}`, `第 ${index + 1} 段`), 'fv-chain-part-name'), row.meta, row.text, row.tag, row.redo);
rows.set(part.id, row); element.append(row.element);
}
if (editing === row && !part.editable) {
- // The part began while it was open: the words typed so far cannot reach it.
+ // The part began while it was open: the words typed so far cannot reach it. A video that ended just closes it.
const changed = row.draft !== row.part.text;
editing = null; row.part = part; draw(row);
- if (changed) flash(row, t('This part is already generating. Your edit was not saved.', '这一段已在生成,改动没有保存'), 'error');
+ if (changed && active) flash(row, t('This part is already generating. Your edit was not saved.', '这一段已在生成,改动没有保存'), 'error');
return;
}
if (editing === row) { row.part = {...part, text: row.part.text}; return; }
@@ -1091,13 +1125,43 @@ export function openStudio(node, {extendFrom = null} = {}) {
// The preview keeps the size it has once the list is in; an opened part grows the column, which scrolls.
const partList = createChainPartList(t, (block, text) => chainController.setText(block, text), {
onShow: () => { previewSpace.style.flex = `0 0 ${previewSpace.getBoundingClientRect().height}px`; },
- onHide: () => { previewSpace.style.flex = ''; }});
+ onHide: () => { previewSpace.style.flex = ''; },
+ redo: block => { failure.clear(); return chainController.redo(block); },
+ resume: () => { failure.clear(); return chainController.resume(); },
+ playSeam: seconds => playAround(seconds)});
+ // Set once the queue buttons exist: "Continue generating" stays hidden while a listed part offers the same.
+ let syncResume = () => {};
+ // A stopped long video keeps its parts listed while the preview shows it.
+ const syncPartList = () => {
+ const chain = chainController?.state;
+ if (chain) partList.update(chain, chainController.active, Boolean(result?.request_id) && result.request_id === chain.id);
+ syncResume();
+ };
output.append(partList.element);
cleanup.push(() => partList.clear());
const stage = el('div', null, 'fv-stage');
stage.setAttribute('aria-label', t('Video preview', '视频预览'));
const stageMedia = el('div', null, 'fv-stage-media');
stage.append(stageMedia); previewSpace.append(stage);
+ // Plays two seconds either side of a seam and stops there; pausing or jumping elsewhere hands the video back.
+ let seamFrame = 0;
+ function playAround(seconds) {
+ const video = stageMedia.querySelector('video');
+ if (!video) return;
+ cancelAnimationFrame(seamFrame);
+ const end = seconds + 2;
+ let last = Math.max(0, seconds - 2);
+ video.currentTime = last;
+ video.play().catch(() => {});
+ const watch = () => {
+ const now = video.currentTime;
+ if (Math.abs(now - last) > 1 || (video.paused && !video.seeking)) return;
+ if (now >= end) { video.pause(); return; }
+ last = now; seamFrame = requestAnimationFrame(watch);
+ };
+ seamFrame = requestAnimationFrame(watch);
+ }
+ cleanup.push(() => cancelAnimationFrame(seamFrame));
const progress = createGenerationProgress(t, undefined, {compact: true, api}); stage.append(progress.element);
const chainLine = el('div', '', 'fv-muted fv-chain-position'); chainLine.hidden = true; progress.element.prepend(chainLine);
// The queued count sits after the part number; a line too narrow for both keeps the part number only.
@@ -1221,7 +1285,7 @@ export function openStudio(node, {extendFrom = null} = {}) {
// chosen: a video picked from Recent videos. It only changes the picture; a run in progress keeps its progress.
function showResult(r, {chosen = false} = {}) {
if (!r?.video || disposed) return; result = r;
- recent.setSelected(r.video);
+ recent.setSelected(r.video); syncPartList();
refreshEffortEstimate(true);
// The report belongs to the video that run made; a video picked from Recent videos
// shows its own report, or none when this window never saw its run.
@@ -1330,7 +1394,7 @@ export function openStudio(node, {extendFrom = null} = {}) {
// Parts download what they need while they run; the line above Generate is read again when they stop.
if (chainWasActive && !active) requestAssets?.refresh(true);
chainWasActive = active;
- partList.update(chain, active);
+ partList.update(chain, active, Boolean(result?.request_id) && result.request_id === chain?.id);
busy = active || Boolean(queueState?.running || queueState?.pending.length); queued = chain?.state === 'queued';
chainLine.hidden = !active;
setChainLine(outcome?.joining ? t('Joining the parts.', '正在接合各段。')
@@ -1341,8 +1405,7 @@ export function openStudio(node, {extendFrom = null} = {}) {
if (chain?.state === 'cancelled') status.textContent = t('Cancelled', '已取消');
// After a stop with videos queued the next one starts at once; its line says so until something else is done.
if (stopNote) { status.dataset.error = 'false'; status.textContent = stopNote; }
- resumeChain.hidden = !['cancelled', 'failed', 'interrupted'].includes(chain?.state);
- queueActions.hidden = !active && !busy && resumeChain.hidden;
+ syncResume();
updateRunButton();
},
onResult: (result, outcome) => { node.freevideoLastResult = result; showResult(result, {chosen: outcome.partial});
@@ -1408,6 +1471,10 @@ export function openStudio(node, {extendFrom = null} = {}) {
finally { stopLoop.disabled = false; }
}, 'fv-quiet');
queueActions.append(queueDetails, cancelCurrent, stopLoop, resumeChain);
+ syncResume = () => {
+ resumeChain.hidden = !['cancelled', 'failed', 'interrupted'].includes(chainController?.state?.state) || partList.resumes();
+ queueActions.hidden = !chainController?.active && !busy && !queueState?.looping && resumeChain.hidden;
+ };
runbar.append(requestAssets.element, runrow, queueActions); controls.append(runbar);
const queueError = error => ({
queue_unavailable: t('Could not read the queue. The loop has stopped; videos already added stay queued.', '暂时读不到队列,循环已停止;已加入的视频还在队列中。'),
diff --git a/web/studio_chain.js b/web/studio_chain.js
index 88b74c3..8f8288e 100644
--- a/web/studio_chain.js
+++ b/web/studio_chain.js
@@ -4,6 +4,7 @@ import {buildChainRequest} from './length_plan.js?v=20261011-length';
export const CHAIN_PROPERTY = 'freevideo_chain';
const activeStates = new Set(['queued', 'running', 'cancelling']);
const MAX_WAITING = 5;
+const FPS = 24;
const finite = value => typeof value === 'number' && Number.isFinite(value) && value >= 0;
const post = body => ({method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(body)});
@@ -35,10 +36,25 @@ export function chainSplit(chain) {
const split = chain?.split;
return {writing: ['pending', 'running'].includes(split?.state), reason: split?.state === 'failed' ? split.reason || 'failed' : null};
}
+// Once the video has ended, each part offers one way on: a stopped video continues from its first unfinished part,
+// and a finished part, with every part before it done, can be made again as a new video.
+const STOPPED = new Set(['failed', 'cancelled', 'interrupted']);
export function chainParts(chain) {
- const writing = chainSplit(chain).writing;
- return (chain?.blocks || []).map((block, index) => ({id: block.id, index, text: block.inputs?.text ?? '',
- editable: !writing && block.state === 'pending' && block.prompt_id == null}));
+ const writing = chainSplit(chain).writing, blocks = chain?.blocks || [];
+ const idle = Boolean(chain) && !activeStates.has(chain.state) && chain.output_state !== 'joining' && !writing;
+ const unfinished = blocks.findIndex(block => block.state !== 'done' || !block.output);
+ // Where each part begins in the joined video: the parts are joined end to end, each without the opening it repeats.
+ const joined = readChainResult(chain)?.joined, kept = Number.isInteger(chain?.output_blocks) ? chain.output_blocks : blocks.length;
+ let start = 0;
+ const starts = blocks.map(block => { const at = start; start = Number.isInteger(block.new_frames) && start != null ? start + block.new_frames : null; return at; });
+ return blocks.map((block, index) => ({id: block.id, index, text: block.inputs?.text ?? '',
+ editable: !writing && block.state === 'pending' && block.prompt_id == null,
+ // The seconds this part adds to the video; a continuing part repeats the end of the one before it.
+ seconds: Math.max(1, Math.round((block.new_frames ?? block.inputs?.frames ?? 0) / FPS)),
+ continues: typeof block.after === 'string' ? 'part' : block.after ? 'video' : null,
+ seam: joined && index > 0 && index < kept && typeof block.after === 'string' && starts[index] != null ? starts[index] / FPS : null,
+ action: !idle ? null : index === unfinished ? (STOPPED.has(chain.state) ? 'resume' : null)
+ : unfinished < 0 || index < unfinished ? 'redo' : null}));
}
export function sumPartEstimates(plan, estimate) {
@@ -231,6 +247,18 @@ export function createStudioChain({api, node, onState = () => {}, onProgress = (
if (value?.id === id && version === epoch && !disposed) deliver(value);
return value;
},
+ // A new video from this part on; the finished one stays in Creations as it was.
+ async redo(block) {
+ if (!chain || active()) throw new Error('chain_busy');
+ const id = chain.id, version = epoch;
+ const value = (await json(chainRoute(id, `blocks/${encodeURIComponent(block)}/redo`),
+ post(api.clientId ? {client_id: api.clientId} : {})))?.chain;
+ if (!value?.id) throw new Error('chain_missing');
+ if (version !== epoch || disposed) return value;
+ const {id: _, ...metadata} = node.properties?.[CHAIN_PROPERTY] || {};
+ epoch++; adopt(value, metadata);
+ return value;
+ },
async cancel() {
if (!chain) return;
await changeState('cancel', {});