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.

Add video extension entries to the creative workspace

Bowen Xue6d8f678da9e4
diff --git a/web/chain_support.js b/web/chain_support.js
new file mode 100644
index 0000000..9471f2a
--- /dev/null
+++ b/web/chain_support.js
@@ -0,0 +1,64 @@
+// Pure helpers the creative panel's long-video planning shares with the editor store; kept out of
+// editor_store.js so the panel does not load the editing implementation.
+const clockDefault = {now: () => Date.now(), setTimeout: (fn, ms) => setTimeout(fn, ms), clearTimeout: id => clearTimeout(id)};
+export const chainRoute = (id, action) => '/freevideo/chain' + (id ? '/' + encodeURIComponent(id) : '') + (action ? '/' + action : '');
+
+// No overlapping polls and no delivery after disposal, including a slow response.
+export function createPoller(read, deliver, {clock = clockDefault, interval = 2000, onError = () => {}} = {}) {
+ let active = true, timer = null, running = null;
+ async function poll() {
+ if (!active || running) return running;
+ running = (async () => {
+ try { const value = await read(); if (active && await deliver(value) === false) active = false; }
+ catch (error) { if (active) onError(error); }
+ })().finally(() => {
+ running = null;
+ if (active) timer = clock.setTimeout(() => { timer = null; poll(); }, interval);
+ });
+ return running;
+ }
+ poll();
+ return {poll, dispose() { active = false; clock.clearTimeout(timer); }};
+}
+
+export function interpolate(points, seconds) {
+ const rows = points.filter(([x, y]) => Number.isFinite(x) && Number.isFinite(y) && y >= 0).sort((a, b) => a[0] - b[0]);
+ if (!rows.length) return null;
+ if (rows.length === 1) return rows[0][1];
+ let i = rows.findIndex(([x]) => x >= seconds);
+ if (i < 1) i = seconds <= rows[0][0] ? 1 : rows.length - 1;
+ const [a, b] = [rows[i - 1], rows[i]];
+ return b[0] === a[0] ? b[1] : Math.max(0, a[1] + (seconds - a[0]) * (b[1] - a[1]) / (b[0] - a[0]));
+}
+// The reply groups its numbers by quality level. An edit keeps the panel's steps,
+// not a level's name, so the level is the one those steps describe (as the
+// creative panel's range view picks it); other steps have no numbers.
+function capabilityTier(reply, settings) {
+ const tiers = reply.tiers;
+ if (!tiers || typeof tiers !== 'object') return reply;
+ if (tiers[settings?.tier]) return tiers[settings.tier];
+ const steps = Number(settings?.base_steps), twoPass = !!settings?.two_pass;
+ return Object.values(tiers).find(tier => tier.steps === steps && tier.two_pass === twoPass
+ && (!twoPass || Number(settings?.refine_steps) === 3)) || {};
+}
+export function capabilityPoints(reply, {width, height, settings = {}}) {
+ const tier = capabilityTier(reply, settings);
+ const i = reply.sizes?.findIndex(size => size.width === width && size.height === height) ?? -1;
+ const max = Array.isArray(tier.max_seconds) ? tier.max_seconds[i] : tier.max_seconds;
+ const known = Array.isArray(tier.max_frames) ? tier.max_frames[i] : tier.max_frames;
+ const maxRequestFrames = Number.isSafeInteger(known) && known >= 0 ? known
+ : Number.isFinite(max) ? Math.max(39, 5 + 17 * Math.ceil((24 * max - 5) / 17)) : null;
+ const longest = continues => {
+ if (maxRequestFrames === null) return 15;
+ for (let seconds = 30; seconds >= 2; seconds--) {
+ const frames = continues ? 17 * Math.ceil(seconds * 24 / 17) + 22 : Math.max(39, 5 + 17 * Math.ceil((seconds * 24 - 5) / 17));
+ if (frames <= maxRequestFrames) return seconds;
+ }
+ return 2; // The final request check reports too_long when even 2s cannot fit.
+ };
+ const estimates = i >= 0 && Array.isArray(tier.estimate_seconds?.[i]) ? tier.estimate_seconds[i] : tier.estimate_seconds;
+ const lengths = reply.lengths || reply.seconds || [5, 10, 15];
+ return {maxSeconds: longest(false), maxFollowSeconds: longest(true), maxRequestFrames,
+ points: lengths.map((length, j) => [Number(length.seconds ?? length),
+ Array.isArray(estimates) ? estimates[j] : estimates?.[length.seconds ?? length]])};
+}
diff --git a/web/editor.css b/web/editor.css
index a2ab957..c3dca78 100644
--- a/web/editor.css
+++ b/web/editor.css
@@ -65,6 +65,13 @@
.fv-ed-clip[data-state=running] .fv-block-progress.fv-ed-block-progress{display:grid}
.fv-ed-gen-hint{font-size:13px;color:var(--fv-muted);flex:1;min-width:0}
.fv-ed-description{flex:1;width:0}
+.fv-ed-first-frame{display:flex;align-items:center;gap:8px;flex:none;font-size:13px;white-space:nowrap}
+.fv-ed-first-frame[hidden]{display:none}
+.fv-ed-first-frame input{appearance:none;position:relative;flex:none;width:26px;height:16px;min-height:16px;padding:0;border:0;border-radius:12px;margin:0;background:#ffffff24;cursor:pointer;transition:background .2s}
+.fv-ed-first-frame input::before{content:'';position:absolute;top:3px;left:3px;width:10px;height:10px;border-radius:50%;background:white;transition:transform .2s}
+.fv-ed-first-frame input:checked{background:var(--fv-accent,#6db8fa)}
+.fv-ed-first-frame input:checked::before{transform:translateX(10px)}
+.fv-ed-first-frame:has(input:disabled){opacity:.4}
.fv-ed-description:disabled{opacity:.4}
.fv-editor .fv-ed-gen-target{height:36px;align-items:center}
.fv-editor .fv-ed-gen-target button{height:30px;box-shadow:none}
diff --git a/web/editor.js b/web/editor.js
index f9bd12e..026a02f 100644
--- a/web/editor.js
+++ b/web/editor.js
@@ -468,6 +468,16 @@ export function openEditor({api, app, from = null, panel = {}, components: given
clip.start + clip.frames === range.start && clip.source && clip.extend && clip.in + clip.frames === clip.length);
return !!text.trim() || before;
},
+ // Only where earlier footage is continued: a part right after an extendable clip, or a range split into several parts.
+ firstFrameVisible() {
+ if (!store.generationAvailable || !actions.supportedSelection()) return false;
+ const range = selectionRange(); if (!range) return false;
+ const head = state.record.tracks[0].clips.find(clip => clip.start === range.start);
+ const before = !!head && model.continuesBefore(state.record, head.id) && state.record.tracks[0].clips.some(clip =>
+ clip.start + clip.frames === range.start && clip.source && clip.extend && clip.in + clip.frames === clip.length);
+ return before || model.rangeParts(state.record, {...range, ...capability}).length > 1;
+ },
+ setFirstFrame: value => { state.apply(t('First-frame reference', '首帧参考'), record => model.setFlag(record, 'first_frame_reference', value)); },
previewRange: selection => genbar?.preview(selection),
async estimate(selection) {
const range = selectionRange(selection); if (!range) return null;
@@ -595,7 +605,11 @@ export function openEditor({api, app, from = null, panel = {}, components: given
// A sound-only export is not a work: it opens as a file the browser plays and can save.
if (value.only === 'sound') { if (value.url) window.open(mediaURL(api, value.url), '_blank', 'noopener'); return; }
const module = await import('./library.js');
- module.openLibrary(t, {selectedWork: value.work});
+ module.openLibrary(t, {selectedWork: value.work, extend: async record => {
+ if (await handle.close() === false) throw new Error(saveWarning.textContent);
+ await onView('studio');
+ return (await import('./studio.js')).extendVideo(record);
+ }});
}
function updateExport(value) {
if (!value) return false;
diff --git a/web/editor_first_frame.js b/web/editor_first_frame.js
new file mode 100644
index 0000000..6bd31f6
--- /dev/null
+++ b/web/editor_first_frame.js
@@ -0,0 +1,22 @@
+import {firstFrameRow} from './first_frame_row.js';
+// "First-frame reference": one switch for continued generation, kept with the project.
+export const FIRST_FRAME_KEY = 'first_frame_reference';
+const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; };
+export const firstFrameOn = record => record.settings?.[FIRST_FRAME_KEY] === true;
+// actions.firstFrameVisible(): the selection continues earlier footage and this machine can;
+// actions.setFirstFrame(value): saves the choice with the project.
+export function createFirstFrameSwitch(host, {state, t, actions}) {
+ const {row, input} = firstFrameRow(t, 'fv-ed-first-frame');
+ host.append(row);
+ let shown = false;
+ // While generating the row stays as it was and cannot be changed.
+ function update(busy = false) {
+ if (!busy) shown = !!actions.firstFrameVisible?.();
+ row.hidden = !shown;
+ input.checked = firstFrameOn(state.record);
+ input.disabled = busy;
+ }
+ input.onchange = () => { try { actions.setFirstFrame(input.checked); } catch (error) { actions.error?.(error); } finally { input.checked = firstFrameOn(state.record); } };
+ update();
+ return {element: row, update};
+}
diff --git a/web/editor_genbar.js b/web/editor_genbar.js
index c17e012..a2ce09d 100644
--- a/web/editor_genbar.js
+++ b/web/editor_genbar.js
@@ -1,4 +1,5 @@
// The editor owns its generation controls; progress can use the optional component.
+import {createFirstFrameSwitch} from './editor_first_frame.js';
const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; };
export const timeEstimate = (seconds, t) => seconds == null ? '' : seconds < 60
? t(`about ${Math.max(1, Math.ceil(seconds))} s`, `约 ${Math.max(1, Math.ceil(seconds))} 秒`)
@@ -9,6 +10,8 @@ export function createEditorGenbar(host, {state, t, actions, text = ''}) {
const generate = el('button', 'fv-ed-generate'), cancel = el('button', null, t('Cancel', '取消')), resume = el('button', null, t('Continue', '继续'));
for (const button of [generate, cancel, resume]) button.type = 'button';
host.append(hint, input, generate, cancel, resume);
+ const firstFrame = createFirstFrameSwitch(host, {state, t, actions});
+ input.after(firstFrame.element);
let status = null, serial = 0, disposed = false, submitting = false, previewSelection = null, estimateCache = null;
async function render() {
if (disposed) return;
@@ -31,6 +34,7 @@ export function createEditorGenbar(host, {state, t, actions, text = ''}) {
hint.textContent = t(`Part ${number}/${count}`, `第 ${number}/${count} 段`)
+ (remaining != null ? ' · ' + timeEstimate(remaining, t) : '');
}
+ firstFrame.update(busy);
generate.textContent = t('Generate', '生成');
generate.disabled = busy || !!previewSelection || !selected || !actions.canGenerate?.(input.value);
generate.title = '';
diff --git a/web/editor_model.js b/web/editor_model.js
index 6c5b47f..6703160 100644
--- a/web/editor_model.js
+++ b/web/editor_model.js
@@ -90,6 +90,14 @@ export function emptyProject({width = 1344, height = 768, settings = null, name
return parse({version: VERSION, id: null, revision: 0, name, fps: FPS, width, height,
settings, serial: 0, tracks: [{id: 'v1', kind: 'video', clips: []}, {id: 'a1', kind: 'audio', clips: []}]});
}
+// One project-wide generation setting; a false flag is stored as no key at all.
+export function setFlag(record, key, value) {
+ check(typeof key === 'string' && /^[a-z][a-z0-9_]*$/.test(key) && typeof value === 'boolean', 'settings');
+ const next = serialize(record), settings = {...(next.settings || {})};
+ if (value) settings[key] = true; else delete settings[key];
+ next.settings = Object.keys(settings).length ? settings : null;
+ return parse(next);
+}
export function addAudioTrack(record) {
const next = serialize(record);
check(!next.tracks.some(track => track.id === 'a2'), 'track');
diff --git a/web/editor_store.js b/web/editor_store.js
index dcf1040..c27ba23 100644
--- a/web/editor_store.js
+++ b/web/editor_store.js
@@ -7,7 +7,8 @@ const memoryProjects = new Map();
const errorFor = response => Object.assign(new Error('editor_request'), {status: response.status});
const post = value => ({method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(value)});
export const sourceKey = source => source ? `${source.kind}:${source.id}` : null;
-export const chainRoute = (id, action) => '/freevideo/chain' + (id ? '/' + encodeURIComponent(id) : '') + (action ? '/' + action : '');
+import {chainRoute, createPoller, interpolate, capabilityPoints} from './chain_support.js';
+export {chainRoute, createPoller, interpolate, capabilityPoints};
// Debounce from the first edit, rather than postponing indefinitely while dragging.
// Writes are serialized; a response supplies metadata to the next snapshot only.
@@ -157,65 +158,6 @@ export function createSaveQueue({write, read, onSaved = () => {}, onConflict = (
};
}
-// No overlapping polls and no delivery after disposal, including a slow response.
-export function createPoller(read, deliver, {clock = clockDefault, interval = 2000, onError = () => {}} = {}) {
- let active = true, timer = null, running = null;
- async function poll() {
- if (!active || running) return running;
- running = (async () => {
- try { const value = await read(); if (active && await deliver(value) === false) active = false; }
- catch (error) { if (active) onError(error); }
- })().finally(() => {
- running = null;
- if (active) timer = clock.setTimeout(() => { timer = null; poll(); }, interval);
- });
- return running;
- }
- poll();
- return {poll, dispose() { active = false; clock.clearTimeout(timer); }};
-}
-
-export function interpolate(points, seconds) {
- const rows = points.filter(([x, y]) => Number.isFinite(x) && Number.isFinite(y) && y >= 0).sort((a, b) => a[0] - b[0]);
- if (!rows.length) return null;
- if (rows.length === 1) return rows[0][1];
- let i = rows.findIndex(([x]) => x >= seconds);
- if (i < 1) i = seconds <= rows[0][0] ? 1 : rows.length - 1;
- const [a, b] = [rows[i - 1], rows[i]];
- return b[0] === a[0] ? b[1] : Math.max(0, a[1] + (seconds - a[0]) * (b[1] - a[1]) / (b[0] - a[0]));
-}
-// The reply groups its numbers by quality level. An edit keeps the panel's steps,
-// not a level's name, so the level is the one those steps describe (as the
-// creative panel's range view picks it); other steps have no numbers.
-function capabilityTier(reply, settings) {
- const tiers = reply.tiers;
- if (!tiers || typeof tiers !== 'object') return reply;
- if (tiers[settings?.tier]) return tiers[settings.tier];
- const steps = Number(settings?.base_steps), twoPass = !!settings?.two_pass;
- return Object.values(tiers).find(tier => tier.steps === steps && tier.two_pass === twoPass
- && (!twoPass || Number(settings?.refine_steps) === 3)) || {};
-}
-export function capabilityPoints(reply, {width, height, settings = {}}) {
- const tier = capabilityTier(reply, settings);
- const i = reply.sizes?.findIndex(size => size.width === width && size.height === height) ?? -1;
- const max = Array.isArray(tier.max_seconds) ? tier.max_seconds[i] : tier.max_seconds;
- const known = Array.isArray(tier.max_frames) ? tier.max_frames[i] : tier.max_frames;
- const maxRequestFrames = Number.isSafeInteger(known) && known >= 0 ? known
- : Number.isFinite(max) ? Math.max(39, 5 + 17 * Math.ceil((24 * max - 5) / 17)) : null;
- const longest = continues => {
- if (maxRequestFrames === null) return 15;
- for (let seconds = 30; seconds >= 2; seconds--) {
- const frames = continues ? 17 * Math.ceil(seconds * 24 / 17) + 22 : Math.max(39, 5 + 17 * Math.ceil((seconds * 24 - 5) / 17));
- if (frames <= maxRequestFrames) return seconds;
- }
- return 2; // The final request check reports too_long when even 2s cannot fit.
- };
- const estimates = i >= 0 && Array.isArray(tier.estimate_seconds?.[i]) ? tier.estimate_seconds[i] : tier.estimate_seconds;
- const lengths = reply.lengths || reply.seconds || [5, 10, 15];
- return {maxSeconds: longest(false), maxFollowSeconds: longest(true), maxRequestFrames,
- points: lengths.map((length, j) => [Number(length.seconds ?? length),
- Array.isArray(estimates) ? estimates[j] : estimates?.[length.seconds ?? length]])};
-}
export function mediaURL(api, value) {
if (!value) return null;
if (/^(?:https?:|blob:|data:|\/)/.test(value)) return api.apiURL?.(value) || value;
diff --git a/web/first_frame_row.js b/web/first_frame_row.js
new file mode 100644
index 0000000..0de03ac
--- /dev/null
+++ b/web/first_frame_row.js
@@ -0,0 +1,11 @@
+const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text) e.textContent = text; return e; };
+// The label and switch alone: the name, the hover text and nothing else.
+// Shared by the studio and the editing view; neither pulls in the other.
+export function firstFrameRow(t, className) {
+ const row = el('label', className, t('First-frame reference', '首帧参考'));
+ row.title = t('Reduces drift', '减小漂移');
+ const input = el('input'); input.type = 'checkbox'; input.setAttribute('role', 'switch');
+ input.setAttribute('aria-label', t('First-frame reference', '首帧参考'));
+ row.append(input);
+ return {row, input};
+}
diff --git a/web/health.js b/web/health.js
index 191050c..3a808b4 100644
--- a/web/health.js
+++ b/web/health.js
@@ -13,11 +13,11 @@ const t = (en, zh) => cn ? zh : en;
// launcher.js removes this flag during setup; read it before that.
const launchVisit = query.get('freevideo') === 'launch';
// Every script this folder ships; a test keeps the list in step with web/*.js.
-export const MODULES = ['agent_activity.js', 'agent_connect.js', 'agent_session.js', 'browser_extension.js', 'capability_view.js', 'compatibility.js', 'error_panel.js', 'first_run_guide.js', 'fonts.js', 'freevideo.js', 'generation_progress.js',
- 'editor.js', 'editor_actions.js', 'editor_adjust.js', 'editor_adjust_picture.js', 'editor_picture_fields.js', 'editor_picture_session.js', 'editor_preview_picture.js', 'editor_entry.js', 'editor_export_dialog.js', 'editor_genbar.js', 'editor_geometry.js', 'editor_library.js', 'editor_menu.js', 'editor_model.js', 'editor_frame.js', 'editor_player.js', 'editor_room.js', 'editor_select.js', 'editor_state.js', 'editor_store.js', 'editor_tracks.js', 'editor_generation.js', 'editor_transport.js', 'editor_transport_model.js', 'editor_audio.js', 'editor_audio_model.js', 'editor_audio_notes.js', 'editor_audio_replace.js', 'editor_audio_rules.js', 'editor_speed.js', 'editor_speed_model.js',
- 'editor_loader.js', 'editor_text_coverage.js', 'editor_text.js', 'editor_text_model.js', 'editor_text_layout.js', 'editor_notes.js', 'editor_icons.js', 'dialog_keys.js', 'frame_sizes.js', 'health.js', 'image_commands.js', 'image_editor.js', 'image_editor_engine.js', 'launcher.js', 'library.js', 'motion.js', 'output_download.js', 'port_notice.js', 'preview_scene.js',
+export const MODULES = ['agent_activity.js', 'agent_connect.js', 'agent_session.js', 'browser_extension.js', 'chain_support.js', 'capability_view.js', 'compatibility.js', 'error_panel.js', 'first_run_guide.js', 'fonts.js', 'freevideo.js', 'generation_progress.js',
+ 'editor.js', 'editor_actions.js', 'editor_adjust.js', 'editor_adjust_picture.js', 'editor_picture_fields.js', 'editor_picture_session.js', 'editor_preview_picture.js', 'editor_entry.js', 'editor_export_dialog.js', 'editor_first_frame.js', 'editor_genbar.js', 'editor_geometry.js', 'editor_library.js', 'editor_menu.js', 'editor_model.js', 'editor_frame.js', 'editor_player.js', 'editor_room.js', 'editor_select.js', 'editor_state.js', 'editor_store.js', 'editor_tracks.js', 'editor_generation.js', 'editor_transport.js', 'editor_transport_model.js', 'editor_audio.js', 'editor_audio_model.js', 'editor_audio_notes.js', 'editor_audio_replace.js', 'editor_audio_rules.js', 'editor_speed.js', 'editor_speed_model.js',
+ 'editor_loader.js', 'editor_text_coverage.js', 'editor_text.js', 'editor_text_model.js', 'editor_text_layout.js', 'editor_notes.js', 'editor_icons.js', 'dialog_keys.js', 'frame_sizes.js', 'health.js', 'image_commands.js', 'image_editor.js', 'image_editor_engine.js', 'launcher.js', 'length_plan.js', 'library.js', 'motion.js', 'output_download.js', 'port_notice.js', 'preview_scene.js',
'progress_connection.js', 'prompt_draft.js', 'prompt_enhance.js', 'prompt_references.js', 'report_issue.js', 'studio_recent.js',
- 'result_actions.js', 'sampling_effort.js', 'setup.js', 'share.js', 'share_layout.js', 'studio.js', 'studio_queue.js', 'studio_size.js',
+ 'result_actions.js', 'sampling_effort.js', 'setup.js', 'share.js', 'share_layout.js', 'studio.js', 'studio_chain.js', 'studio_extend.js', 'studio_length.js', 'first_frame_row.js', 'studio_queue.js', 'studio_size.js',
'toolbar_position.js', 'updates.js', 'view_navigation.js', 'wordmark.js'];
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
let visibleAt = 0;
diff --git a/web/length_plan.js b/web/length_plan.js
new file mode 100644
index 0000000..773bad3
--- /dev/null
+++ b/web/length_plan.js
@@ -0,0 +1,43 @@
+// The server owns segmentation. These helpers only describe requests and replies.
+export const BLOCK_SECONDS_FIELD = 'block_seconds';
+const positive = value => typeof value === 'number' && Number.isFinite(value) && value > 0;
+
+export const singleLimitSeconds = maximum => positive(maximum) ? Math.min(30, maximum) : 15;
+export const defaultBlockSeconds = maximum => positive(maximum) ? Math.min(15, maximum) : 15;
+
+export function buildPlanRequest({seconds, single = false, singleLimit = null, maxFrames = null, blockSeconds = null}) {
+ const body = {seconds, single: Boolean(single)};
+ if (positive(singleLimit)) body.single_limit_seconds = singleLimit;
+ if (Number.isSafeInteger(maxFrames) && maxFrames >= 0) body.max_frames = maxFrames;
+ if (positive(blockSeconds)) body[BLOCK_SECONDS_FIELD] = blockSeconds;
+ return body;
+}
+
+export function buildChainRequest(options, {node, prompt, extra_data, client_id, text, seed}) {
+ const body = {...buildPlanRequest(options), node: String(node), prompt};
+ for (const [key, value] of Object.entries({extra_data, client_id, text, seed})) {
+ if (value !== undefined) body[key] = value;
+ }
+ if (options.after) body.after = options.after;
+ return body;
+}
+
+export function readLengthPlan(reply) {
+ const plan = reply?.plan;
+ if (!plan || !Array.isArray(plan.blocks) || !plan.blocks.length
+ || !plan.blocks.every(block => positive(block.new_frames)) || !positive(plan.seconds)) return null;
+ return {single: plan.single === true, forced: typeof plan.forced === 'boolean' ? plan.forced : null, count: plan.blocks.length,
+ partSeconds: plan.blocks.map(block => block.new_frames / 24), seconds: plan.seconds, blocks: plan.blocks};
+}
+
+export function classifyPlanError(reply) {
+ if (reply?.code === 'device_limit') return 'continuation_unavailable';
+ if (reply?.code === 'too_long') return 'too_long';
+ if (['block_too_long', 'block_too_short', 'too_short', 'invalid'].includes(reply?.code)) return 'other';
+ const value = reply?.error;
+ const message = reply?.code || (typeof value === 'string' ? value : value?.code || value?.message || '');
+ if (/single.*(?:limit|long|cannot|unavailable|impossible)|force.*single|强制单次/i.test(message)) return 'single_unavailable';
+ if (/minimum|shortest|continuation|最短|接续/i.test(message)) return 'continuation_unavailable';
+ if (/too[_ -]?long|too[_ -]?many|480|太长/i.test(message)) return 'too_long';
+ return 'other';
+}
diff --git a/web/library.js b/web/library.js
index 65e9597..a57faad 100644
--- a/web/library.js
+++ b/web/library.js
@@ -1,6 +1,7 @@
import { api } from '../../scripts/api.js';
import { closeDialog } from './motion.js';
import { resultActions, previewBadge } from './result_actions.js';
+import { extendSourceExists } from './studio_extend.js';
const style = document.createElement('link');
style.rel = 'stylesheet'; style.href = new URL('./library.css', import.meta.url).href; document.head.append(style);
@@ -85,7 +86,7 @@ async function workflowBackfill(collection, t) {
}
// ``upscale`` queues the second pass of a first-pass preview (the studio's node).
-export function openLibrary(t, {upscale = null, selectedWork = null} = {}) {
+export function openLibrary(t, {upscale = null, selectedWork = null, extend = null} = {}) {
if (opened?.open) { if (selectedWork) opened.close(); else { opened.focus(); return; } }
const dialog = el('dialog', null, 'fv-studio fv-library'); opened = dialog;
dialog.setAttribute('aria-label', t('Your creations', '我的作品'));
@@ -135,10 +136,11 @@ export function openLibrary(t, {upscale = null, selectedWork = null} = {}) {
media.append(player);
if (row.preview) media.append(previewBadge(row, t));
frame.append(media);
- player.addEventListener('error', () => {
+ player.addEventListener('error', async () => {
if (!disposed && selected === row.video) {
const note = el('p', t('This video is unavailable. Refresh if it was moved.', '视频暂时无法打开,若文件已移动请刷新。'), 'fv-library-message');
frame.replaceChildren(note);
+ if (!await extendSourceExists(api, row) && selected === row.video) links.querySelector('.fv-action-extend')?.remove();
}
}, {once: true});
}
@@ -148,6 +150,12 @@ export function openLibrary(t, {upscale = null, selectedWork = null} = {}) {
mountPlayer(row);
date.textContent = timestamp(row); geometry.textContent = dimensions(row);
links.replaceChildren(resultActions(row, t, {
+ extend: async saved => {
+ player?.pause();
+ const run = extend || (async record => (await import('./studio.js')).extendVideo(record));
+ try { const studio = await run(saved); dialog.close(); studio?.querySelector('.fv-prompt-editor textarea')?.focus({preventScroll: true}); }
+ catch (error) { notice.textContent = error.message; }
+ },
secondPass: row.preview && upscale ? () => secondPass(row) : null,
remove: () => remove(row)}));
notice.textContent = '';
diff --git a/web/result_actions.js b/web/result_actions.js
index 854e17a..2bbe5f2 100644
--- a/web/result_actions.js
+++ b/web/result_actions.js
@@ -1,6 +1,7 @@
import { api } from '../../scripts/api.js';
import { outputDownloadURL } from './output_download.js';
import { shareButton } from './share.js';
+import { canExtend, extendText, extendSourceExists } from './studio_extend.js';
const css = document.createElement('link');
css.rel = 'stylesheet'; css.href = new URL('./result_actions.css', import.meta.url).href; document.head.append(css);
@@ -11,6 +12,9 @@ const ICONS = {
share: '<path d="M8 10V2.5m0 0L5.2 5.3M8 2.5l2.8 2.8M4.5 7.5H4a1 1 0 0 0-1 1v4a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1v-4a1 1 0 0 0-1-1h-.5"/>',
report: '<path d="M9.5 2H5a1 1 0 0 0-1 1v10a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V4.5L9.5 2Z"/><path d="M9.5 2v2.5H12M6.5 8h3M6.5 10.5h3"/>',
chevron: '<path d="m4.5 6.5 3.5 3 3.5-3"/>',
+ extend: '<rect x="1.5" y="4" width="8" height="8" rx="1.5"/><path d="M11.5 8h3m0 0-1.5-1.5M14.5 8 13 9.5"/>',
+ lock: '<rect x="3.5" y="7" width="9" height="6.5" rx="1.5"/><path d="M5.5 7V5a2.5 2.5 0 0 1 5 0v2"/>',
+ close: '<path d="m4 4 8 8M12 4l-8 8"/>',
expand: '<path d="M9.5 2.5h4v4M13.5 2.5 9 7M6.5 13.5h-4v-4M2.5 13.5 7 9"/>',
trash: '<path d="M3 4.5h10M6.5 4.5V3h3v1.5M4.5 4.5l.6 8.1a1 1 0 0 0 1 .9h3.8a1 1 0 0 0 1-.9l.6-8.1M7 7v4M9 7v4"/>',
};
@@ -103,7 +107,7 @@ function deleteAction(t, remove) {
// `diagnostic` downloads the redacted report (and may offer to send it); a
// result without one shows no report entry, because the full generation
// record keeps local paths and is not meant to be shared.
-export function resultActions(record, t, {diagnostic = null, secondPass = null, remove = null} = {}) {
+export function resultActions(record, t, {diagnostic = null, secondPass = null, remove = null, extend = null} = {}) {
const bar = document.createElement('div'); bar.className = 'fv-actions';
if (secondPass) bar.append(secondPassAction(t, secondPass));
if (record.video) {
@@ -111,6 +115,20 @@ export function resultActions(record, t, {diagnostic = null, secondPass = null,
download.href = outputDownloadURL(api, record.video); download.download = '';
bar.append(download);
}
+ if (extend && canExtend(record)) {
+ const button = action('button', extendText(t, 'action'), 'extend', 'fv-action-secondary fv-action-extend');
+ button.hidden = true;
+ extendSourceExists(api, record).then(exists => { button.hidden = !exists; });
+ button.onclick = async () => {
+ if (button.disabled) return;
+ button.disabled = true;
+ try {
+ if (!await extendSourceExists(api, record)) { button.hidden = true; return; }
+ await extend(record);
+ } finally { button.disabled = false; }
+ };
+ bar.append(button);
+ }
const share = shareButton(record, t);
share.className = 'fv-action fv-action-secondary fv-share-trigger';
const label = document.createElement('span'); label.textContent = share.textContent;
diff --git a/web/sampling_effort.js b/web/sampling_effort.js
index 9780a84..aaac906 100644
--- a/web/sampling_effort.js
+++ b/web/sampling_effort.js
@@ -107,7 +107,7 @@ export function createSamplingEffort(t, {onChange, onPreview = () => {}}) {
custom.textContent = `${t('Custom', '自定义')} · ${currentSteps}${twoPass ? ' + ' + currentRefine : ''} ${unit}`;
paint(selected);
if (isCustom) rail.setAttribute('aria-valuetext', custom.textContent);
- rail.title = disabled ? t('Controlled by connected nodes.', '由连接的节点控制。')
+ rail.title = disabled ? state.reason || t('Controlled by connected nodes.', '由连接的节点控制。')
: t('Same model. Higher effort uses more sampling steps; results vary by scene.', '使用同一模型,提高档位会增加采样步数;效果因场景而异。');
}
return {element, update, setEstimate(text, title = '') { estimate.textContent = text; estimate.title = title; }, dispose: cancel};
diff --git a/web/studio.css b/web/studio.css
index 19dff35..86cf8b2 100644
--- a/web/studio.css
+++ b/web/studio.css
@@ -162,3 +162,21 @@
.fv-studio .fv-status:empty,.fv-studio .fv-budget:empty,.fv-studio .fv-prewarm:empty,.fv-studio .fv-result-links:empty{display:none}
@media(max-width:1050px) and (min-width:681px){.fv-studio .fv-wordmark{width:150px}.fv-studio .fv-view-switch button{padding-inline:10px}}
@media(max-width:480px){.fv-studio .fv-header:has(.fv-view-switch){height:auto;min-height:98px;grid-template-columns:1fr auto;padding-block:10px}.fv-studio .fv-header>.fv-view-switch{grid-column:1/-1;grid-row:2}.fv-studio .fv-header>.fv-header-actions{grid-column:2;grid-row:1}.fv-studio .fv-stats{grid-template-columns:repeat(2,minmax(0,1fr))}}
+.fv-studio .fv-extend-source{display:flex;align-items:center;gap:12px;margin-bottom:14px;padding:10px;border:1px solid var(--fv-border);border-radius:var(--fv-r-md);background:var(--fv-card)}
+.fv-studio .fv-extend-source[hidden]{display:none}
+.fv-studio .fv-extend-active>:not(.fv-extend-source){display:none}
+.fv-studio .fv-extend-source img{width:80px;height:50px;object-fit:cover;border-radius:var(--fv-r-sm)}
+.fv-studio .fv-extend-source>span{flex:1;font-size:var(--fv-micro)}
+.fv-studio .fv-canvas-lock{display:inline-flex;margin-left:6px;vertical-align:-3px;color:var(--fv-muted)}
+.fv-studio .fv-canvas-lock .fv-icon{width:13px;height:13px}
+.fv-studio .fv-canvas-lock[hidden]{display:none}
+.fv-studio .fv-extend-source{position:relative}
+.fv-studio .fv-extend-source .fv-extend-remove{position:absolute;top:6px;right:6px;width:24px;height:24px;min-height:0;padding:0;display:inline-flex;align-items:center;justify-content:center}
+.fv-studio .fv-extend-source .fv-extend-remove .fv-icon{width:12px;height:12px}
+.fv-studio .fv-first-frame{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-top:14px;font-size:var(--fv-small,13px)}
+.fv-studio .fv-first-frame[hidden]{display:none}
+.fv-studio .fv-first-frame input{appearance:none;position:relative;flex:none;width:26px;height:16px;min-height:16px;padding:0;border:0;border-radius:12px;margin:0;background:#ffffff24;cursor:pointer;transition:background .2s}
+.fv-studio .fv-first-frame input::before{content:'';position:absolute;top:3px;left:3px;width:10px;height:10px;border-radius:50%;background:white;transition:transform .2s}
+.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}
diff --git a/web/studio.js b/web/studio.js
index a33958d..9d08f79 100644
--- a/web/studio.js
+++ b/web/studio.js
@@ -16,7 +16,7 @@ import { createAgentActivity } from './agent_activity.js';
import { createStudioQueue, randomSeed } from './studio_queue.js';
import { attachReferencePicker, referenceItems, syncReferencePrompt, referenceInputs } from './prompt_references.js';
import { createSamplingEffort } from './sampling_effort.js';
-import { resultActions, previewBadge } from './result_actions.js';
+import { resultActions, previewBadge, icon } from './result_actions.js';
import { createPromptEnhancer } from './prompt_enhance.js';
import { rememberPromptDraft } from './prompt_draft.js';
import { canvasDimensions, imageSizeSelection } from './studio_size.js';
@@ -24,6 +24,10 @@ import { createCapabilityView } from './capability_view.js';
import { openEditorView } from './editor_loader.js';
import { frameShapes, frameSize } from './frame_sizes.js';
import { createFirstRunGuide } from './first_run_guide.js';
+import { createStudioLength, savedSeconds } from './studio_length.js?v=20261011-length';
+import { firstFrameRow } from './first_frame_row.js';
+import { createStudioChain, chainPosition, readChainResult, sumPartEstimates, singleRunSnapshot } from './studio_chain.js?v=20261011-length';
+import { createExtendState, extendText, extendSourceExists, readExtendRecord, extendSnapshot, mountExtendThumbnail } from './studio_extend.js';
const languageOverride = typeof location !== 'undefined'
? new URLSearchParams(location.search).get('freevideo_lang') : null;
@@ -180,9 +184,19 @@ export function showNodes(node, dialog = null) {
}
const studioQueues = new WeakMap();
-export function openStudio(node) {
- if (current?.node === node && current.dialog.open) { current.dialog.focus(); viewChanged('studio', node); return current.dialog; }
+export async function extendVideo(record, node = current?.node || app.graph?._nodes?.find(row => row.type === 'FreeVideoGenerate')) {
+ if (!node || !await extendSourceExists(api, record)) throw new Error(extendText(t, 'unavailable'));
+ return openStudio(node, {extendFrom: await readExtendRecord(api, record)});
+}
+
+export function openStudio(node, {extendFrom = null} = {}) {
+ if (current?.node === node && current.dialog.open) {
+ if (extendFrom) current.enterExtend(extendFrom); else current.dialog.focus();
+ viewChanged('studio', node); return current.dialog;
+ }
current?.dialog.close();
+ const extension = createExtendState(node, name => value(node, name), (name, v) => set(node, name, v));
+ if (extendFrom && !extension.enter(extendFrom)) throw new Error(extendText(t, 'unavailable'));
const dialog = el('dialog', null, 'fv-studio'); dialog.setAttribute('aria-label', t('FreeVideo creative workspace', 'FreeVideo 创作面板'));
current = {node, dialog}; const cleanup = [];
const header = el('header', null, 'fv-header'), brand = el('div', null, 'fv-brand');
@@ -216,7 +230,7 @@ export function openStudio(node) {
const shown = text => starter && text === starter ? '' : String(text || '');
const prompt = el('textarea'); prompt.value = shown(value(node, 'text')); prompt.setAttribute('aria-label', t('Prompt', '提示词'));
prompt.dataset.fvGuide = 'describe';
- const placeholder = () => { prompt.placeholder = untouched() ? starter : t('Describe the scene… Type @ to reference media', '描述画面… 输入 @ 引用素材'); };
+ const placeholder = () => { prompt.placeholder = extension.source ? extendText(t, 'prompt') : untouched() ? starter : t('Describe the scene… Type @ to reference media', '描述画面… 输入 @ 引用素材'); };
placeholder();
prompt.disabled = linked(node, 'text'); prompt.oninput = () => { set(node, 'text', prompt.value); placeholder(); };
const promptEditor = el('div', null, 'fv-prompt-editor'); promptEditor.append(prompt);
@@ -246,6 +260,8 @@ export function openStudio(node) {
promptSection.querySelector('.fv-label').append(promptHelp);
promptSection.append(enhancer.element);
const canvas = section(t('Frame & duration', '画幅与时长'));
+ const canvasLock = el('span', null, 'fv-canvas-lock'); canvasLock.hidden = true; canvasLock.append(icon('lock'));
+ canvas.querySelector('.fv-label').append(canvasLock);
const shapes = el('div', null, 'fv-shapes'); canvas.append(shapes);
const dimensionsLinked = linked(node, 'width') || linked(node, 'height');
let selected = node.properties?.freevideo_aspect || 'custom', ratio = Number(value(node, 'width')) / Number(value(node, 'height'));
@@ -267,7 +283,7 @@ export function openStudio(node) {
mp.value = sizeSelection.value;
const legacyOption = [...mp.options].find(o => Number(o.value) === 1);
mp.title = t('1 MP = 1024 × 1024, as in ComfyUI.', '1 MP = 1024 × 1024,与 ComfyUI 一致。'); mp.disabled = dimensionsLinked;
- const seconds = el('input'); seconds.type = 'number'; seconds.min = '1.625'; seconds.max = '60'; seconds.step = 'any'; seconds.value = value(node, 'seconds'); seconds.disabled = linked(node, 'seconds'); seconds.setAttribute('aria-label', t('Duration in seconds', '时长(秒)'));
+ const seconds = el('input'); seconds.type = 'number'; seconds.min = '1.625'; seconds.step = 'any'; seconds.value = savedSeconds(node, value(node, 'seconds')); seconds.disabled = linked(node, 'seconds'); seconds.setAttribute('aria-label', t('Duration in seconds', '时长(秒)'));
const fields = el('div', null, 'fv-fields'); fields.append(field(t('Total pixels', '总像素'), mp), field(t('Duration · seconds', '时长 · 秒'), seconds)); canvas.append(fields);
const canvasNote = el('div', null, 'fv-canvas-note'), dimensions = el('span'), duration = el('span'); canvasNote.append(dimensions, duration); canvas.append(canvasNote);
const rangeMount = el('div'); canvas.append(rangeMount);
@@ -301,19 +317,20 @@ export function openStudio(node) {
if (next) { next.click(); next.focus(); }
});
twoPassLabel.append(el('span', t('Two-pass', '二次采样')), twoPassStatus, passMode);
- let effortEstimate = {}, effortEstimateKey = '', effortEstimateTimer = null, effortEstimateRequest = null;
+ let effortEstimate = {}, effortEstimateKey = '', effortEstimateTimer = null, effortEstimateRequest = null, lengthControl = null, chainController = null;
const effort = createSamplingEffort(t, {onChange: tier => {
baseSteps.value = tier.steps;
refineSteps.value = 3;
twoPass.checked = tier.twoPass;
autoSinglePass = false;
- set(node, 'two_pass', tier.twoPass);
+ set(node, 'two_pass', twoPass.checked);
set(node, 'refine_steps', 3);
syncSamplingSteps();
}, onPreview: tier => tier ? showEffortEstimate(tier.steps, tier.twoPass) : showEffortEstimate()});
const samplingSettings = el('div', null, 'fv-sampling-settings');
const previewFirst = el('input'); previewFirst.type = 'checkbox'; previewFirst.checked = value(node, 'preview') === true;
function choosePassMode(mode) {
+ if (extension.source) return;
const wantsTwoPass = mode !== 'off', wantsPreview = mode === 'preview';
if (twoPass.checked !== wantsTwoPass) { twoPass.checked = wantsTwoPass; autoSinglePass = false; set(node, 'two_pass', wantsTwoPass); }
if (previewFirst.checked !== wantsPreview) { previewFirst.checked = wantsPreview; set(node, 'preview', wantsPreview); }
@@ -325,9 +342,9 @@ export function openStudio(node) {
const selected = option.dataset.mode === mode;
option.setAttribute('aria-checked', String(selected)); option.tabIndex = selected ? 0 : -1;
}
- passOptions[0].disabled = linked(node, 'two_pass') || !widget(node, 'two_pass');
+ passOptions[0].disabled = Boolean(extension.source) || linked(node, 'two_pass') || !widget(node, 'two_pass');
passOptions[1].disabled = twoPass.disabled;
- passOptions[2].disabled = twoPass.disabled || linked(node, 'preview') || !widget(node, 'preview');
+ passOptions[2].disabled = Boolean(extension.source) || twoPass.disabled || linked(node, 'preview') || !widget(node, 'preview');
passOptions[2].hidden = !widget(node, 'preview');
}
samplingSettings.append(effort.element, twoPassLabel);
@@ -335,6 +352,9 @@ export function openStudio(node) {
cleanup.push(() => { clearTimeout(effortEstimateTimer); effortEstimateRequest?.abort(); });
const mediaNode = upstream(node, 'media');
const [mediaDetails, mediaMount] = expand(t('Media', '素材'));
+ const extendMount = el('div', null, 'fv-extend-source'); extendMount.hidden = true; mediaMount.prepend(extendMount);
+ let releaseExtendThumbnail = () => {};
+ cleanup.push(() => releaseExtendThumbnail());
if (mediaNode?.freevideoCreateMediaEditor) { cleanup.push(mediaNode.freevideoCreateMediaEditor(mediaMount)); mediaDetails.open = JSON.parse(value(mediaNode, 'assets') || '[]').some(r => r.enabled !== false) || mediaNode.inputs?.some(input => ['first', 'last', ...referenceInputs, 'reference_audio'].includes(input.name) && input.link != null); }
else mediaMount.append(el('p', t('Connect a FreeVideo Media panel in node view to upload here.', '在节点视图连接 FreeVideo 素材面板,即可在这里上传。'), 'fv-legacy'));
const connectedLora = upstream(node, 'loras');
@@ -357,6 +377,22 @@ export function openStudio(node) {
const width = el('input'), height = el('input');
for (const [w, name, label] of [[width, 'width', t('Width', '宽度')], [height, 'height', t('Height', '高度')]]) { w.type = 'number'; w.min = '256'; w.max = '4096'; w.step = '32'; w.value = value(node, name); w.disabled = dimensionsLinked; w.setAttribute('aria-label', label); custom.append(field(label, w)); w.onchange = () => { if (w.value && w.reportValidity()) { set(node, name, Number(w.value)); selected = 'custom'; node.properties.freevideo_aspect = selected; ratio = Number(width.value) / Number(height.value); updateCanvas(); } }; }
advanced.append(custom);
+ lengthControl = createStudioLength({api, node, seconds, advanced, fields, t, field,
+ setSeconds: seconds => set(node, 'seconds', seconds), onChange: () => { if (runButtonReady) { updateRunButton(); showEffortEstimate(); updateDuration(); } }});
+ cleanup.push(() => lengthControl.dispose());
+ // Under the length row, only where a video is continued and the node can take it.
+ const firstFrame = firstFrameRow(t, 'fv-first-frame');
+ firstFrame.row.hidden = true; fields.after(firstFrame.row);
+ firstFrame.input.checked = value(node, 'first_frame_reference') === true;
+ firstFrame.input.onchange = () => { set(node, 'first_frame_reference', firstFrame.input.checked); firstFrame.input.checked = value(node, 'first_frame_reference') === true; };
+ let manyParts = false;
+ function updateFirstFrame() {
+ // While a new plan is being worked out the row keeps its place.
+ const plan = lengthControl.plan; if (plan || !lengthControl.needsPlan) manyParts = plan?.count > 1;
+ firstFrame.row.hidden = !widget(node, 'first_frame_reference') || !(manyParts || extension.source);
+ firstFrame.input.checked = value(node, 'first_frame_reference') === true;
+ firstFrame.input.disabled = Boolean(capturing || queueState?.submitting || queueState?.running || chainController?.active);
+ }
const samplingFields = el('div', null, 'fv-fields'); samplingFields.style.marginTop = '14px';
const baseSteps = el('input'), refineSteps = el('input');
const samplingWarning = el('p', t('Changing sampling steps may reduce generation quality. Defaults: 8 + 3 steps.', '修改采样步数可能降低生成质量。默认一采 8 步、二采 3 步。'), 'fv-muted');
@@ -380,7 +416,7 @@ export function openStudio(node) {
if (baseSteps.value !== '' && Number.isInteger(steps) && steps >= 1 && steps <= 32
&& !linked(node, 'two_pass') && widget(node, 'two_pass')) {
if (steps !== 8 && twoPass.checked) { twoPass.checked = false; set(node, 'two_pass', false); autoSinglePass = true; }
- else if (steps === 8 && autoSinglePass) { twoPass.checked = true; set(node, 'two_pass', true); autoSinglePass = false; }
+ else if (steps === 8 && autoSinglePass && !extension.source) { twoPass.checked = true; set(node, 'two_pass', true); autoSinglePass = false; }
}
syncSamplingSteps();
baseSteps.reportValidity();
@@ -388,11 +424,12 @@ export function openStudio(node) {
// The run button exists only further down; until then its label is set there.
let runButtonReady = false;
function syncSamplingSteps() {
+ if (extension.source) { baseSteps.value = '8'; refineSteps.value = '3'; twoPass.checked = true; set(node, 'two_pass', true); autoSinglePass = false; }
const baseLinked = linked(node, 'base_steps');
// Two-pass is offered at 8 first-pass steps. A saved workflow that already
// uses it with other steps is shown as custom and left unchanged.
const unavailable = Number(baseSteps.value) !== 8 && !twoPass.checked;
- twoPass.disabled = unavailable || linked(node, 'two_pass') || !widget(node, 'two_pass');
+ twoPass.disabled = Boolean(extension.source) || unavailable || linked(node, 'two_pass') || !widget(node, 'two_pass');
twoPassStatus.textContent = unavailable ? t('Coming soon', '即将推出') : '';
twoPassLabel.classList.toggle('fv-two-pass-unavailable', unavailable);
// A preview stops after the first pass, so it needs two-pass sampling.
@@ -402,8 +439,8 @@ export function openStudio(node) {
}
previewFirst.disabled = !twoPass.checked || linked(node, 'preview') || !widget(node, 'preview');
syncPassMode();
- baseSteps.disabled = baseLinked || !widget(node, 'base_steps');
- refineSteps.disabled = !twoPass.checked || linked(node, 'refine_steps') || !widget(node, 'refine_steps');
+ baseSteps.disabled = baseLinked || !widget(node, 'base_steps') || Boolean(extension.source);
+ refineSteps.disabled = !twoPass.checked || linked(node, 'refine_steps') || !widget(node, 'refine_steps') || Boolean(extension.source);
baseSteps.min = twoPass.checked ? '2' : '1';
refineSteps.max = baseLinked ? '31' : String(Math.max(3, Math.min(31, Number(baseSteps.value || 8) - 1)));
refineSteps.setCustomValidity(twoPass.checked && !baseLinked && !refineSteps.disabled && Number(refineSteps.value) !== 3 && Number(refineSteps.value) >= Number(baseSteps.value)
@@ -416,12 +453,31 @@ export function openStudio(node) {
}
}
effort.update({baseSteps: Number(baseSteps.value), refineSteps: Number(refineSteps.value),
- twoPass: twoPass.checked, disabled: baseSteps.disabled || linked(node, 'two_pass') || linked(node, 'refine_steps')});
+ twoPass: twoPass.checked, disabled: baseSteps.disabled || linked(node, 'two_pass') || linked(node, 'refine_steps'),
+ reason: extension.source ? t('A continuation uses the Light level.', '接着生成使用轻量档。') : ''});
refreshEffortEstimate();
}
syncSamplingSteps();
advanced.append(samplingFields, samplingWarning);
function showEffortEstimate(steps = Number(baseSteps.value), twoPassPlan = twoPass.checked) {
+ const parts = lengthControl.plan?.count > 1 ? t(`${lengthControl.plan.count} parts`, `分 ${lengthControl.plan.count} 段`) : '';
+ // A request that fits one run keeps its own estimate while the longest run is unknown.
+ if ((lengthControl.capabilityState === 'pending' || lengthControl.capabilityState === 'unavailable')
+ && (lengthControl.needsPlan || lengthControl.plan?.count > 1)) {
+ const waiting = lengthControl.estimating ? t('Estimating time…', '正在估算用时…') : '';
+ effort.setEstimate([parts, waiting].filter(Boolean).join(' · '));
+ return;
+ }
+ if (lengthControl.plan?.single && Number(seconds.value) > 60) { effort.setEstimate(''); return; }
+ if (lengthControl.needsPlan && !lengthControl.plan) { effort.setEstimate(''); return; }
+ if (lengthControl.plan?.count > 1) {
+ const plan = lengthControl.plan;
+ const seconds = steps === Number(baseSteps.value) && twoPassPlan === twoPass.checked
+ ? sumPartEstimates(plan, lengthControl.estimate) : null;
+ effort.setEstimate(seconds > 0 ? t(`${plan.count} parts · about ${Math.ceil(seconds / 60)} min`, `分 ${plan.count} 段 · 约 ${Math.ceil(seconds / 60)} 分钟`)
+ : t(`${plan.count} parts`, `分 ${plan.count} 段`));
+ return;
+ }
const rangeEstimate = capabilityView?.estimate(steps, twoPassPlan, arguments.length ? 3 : Number(refineSteps.value));
if (rangeEstimate) { effort.setEstimate(rangeEstimate); return; }
const mode = twoPassPlan ? 'two_pass' : 'single';
@@ -455,7 +511,12 @@ export function openStudio(node) {
let adapters = false;
try { adapters = JSON.parse(value(loraNode, 'adapters') || '[]').some(r => r.enabled !== false && Number(r.strength ?? 1) !== 0); } catch {}
if (loraNode && !widget(loraNode, 'adapters')) adapters = value(loraNode, 'lora') !== 'None';
- const query = new URLSearchParams({width: value(node, 'width'), height: value(node, 'height'), seconds: value(node, 'seconds'), task, adapters: adapters ? '1' : '0'}).toString();
+ const requestWidth = extension.source?.geometry.width ?? value(node, 'width');
+ const requestHeight = extension.source?.geometry.height ?? value(node, 'height');
+ lengthControl?.refresh({width: requestWidth, height: requestHeight, task, adapters,
+ settings: {tier: twoPass.checked ? 'light' : ({12: 'medium', 16: 'high', 20: 'max'}[Number(baseSteps.value)] || 'custom'),
+ base_steps: Number(baseSteps.value), refine_steps: Number(refineSteps.value), two_pass: twoPass.checked}}, force);
+ const query = new URLSearchParams({width: requestWidth, height: requestHeight, seconds: value(node, 'seconds'), task, adapters: adapters ? '1' : '0'}).toString();
if (query === effortEstimateKey && !force) { showEffortEstimate(); return; }
clearTimeout(effortEstimateTimer);
effortEstimateKey = query; effortEstimate = {}; showEffortEstimate(); effortEstimateRequest?.abort();
@@ -480,7 +541,7 @@ export function openStudio(node) {
const previewCaption = el('span'), previewTools = el('div', null, 'fv-preview-tools');
previewTools.append(previewCaption);
previewTools.append(button(t('Creations', '作品'), () => {
- stage.querySelector('video')?.pause(); openLibrary(t, {upscale: value => node.freevideoUpscaleResult(value)});
+ stage.querySelector('video')?.pause(); openLibrary(t, {upscale: value => node.freevideoUpscaleResult(value), extend: saved => extendVideo(saved, node)});
})); previewHead.append(previewTools); output.append(previewHead);
const previewSpace = el('div', null, 'fv-preview-space'); output.append(previewSpace);
const stage = el('div', null, 'fv-stage');
@@ -488,6 +549,7 @@ export function openStudio(node) {
const stageMedia = el('div', null, 'fv-stage-media');
stage.append(stageMedia); previewSpace.append(stage);
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);
progress.updateReport({report_id: node.freevideoReportId});
cleanup.push(() => progress.dispose());
cleanup.push(createPreviewScene(stage, progress.element, stageMedia));
@@ -605,7 +667,10 @@ export function openStudio(node) {
refreshEffortEstimate(true);
progress.updateReport({report_id: node.freevideoReportId});
stage.querySelector('video')?.pause(); stageMedia.replaceChildren();
- const video = el('video'); video.src = view(r.video, 'output'); video.controls = true; video.preload = 'metadata'; video.playsInline = true; stageMedia.append(video);
+ const video = el('video'); video.src = view(r.video, 'output') + (r.version ? `&fv=${encodeURIComponent(r.version)}` : ''); video.controls = true; video.preload = 'metadata'; video.playsInline = true; stageMedia.append(video);
+ video.addEventListener('error', async () => {
+ if (!await extendSourceExists(api, r) && result === r) links.querySelector('.fv-action-extend')?.remove();
+ }, {once: true});
// A preview is marked on the picture itself; its timings describe only
// the half-resolution first pass, so they stay in the report.
if (r.preview) stageMedia.append(previewBadge(r, t));
@@ -631,7 +696,9 @@ export function openStudio(node) {
const reported = progress.hasReport();
const tipShowing = !!links.querySelector('.fv-report-tip:not(.fv-report-tip-leaving)');
links.replaceChildren(resultActions(r, t, {diagnostic: reported ? downloadReport : null,
+ extend: async saved => { try { await extendVideo(saved, node); } catch (error) { resultActionFailed(error); } },
secondPass: r.preview ? secondPass(r) : null}));
+ if (runButtonReady) updateExtendButton();
// After a video finished just now, point at the report menu until the
// user closes the tip once, whichever version they first saw it in.
if (!chosen && watchedRun && reported && !r.preview && !r.result_cache_hit && !reportTipClosed()) reportTipFor = r.video;
@@ -652,6 +719,7 @@ export function openStudio(node) {
formatError: (error, snapshot) => createErrorReport(error, {stage: 'submission', snapshot, node, graph: app.graph}),
// Direct snapshot submission still feeds the same graph result panel.
onResult: (output, requestId) => {
+ if (node.freevideoStudioChain?.isBlockOutput({...output.freevideo_summary[0], request_id: requestId})) return;
output = {...output, freevideo_summary: [{...output.freevideo_summary[0], request_id: requestId}]};
if (app.graph?.getNodeById(node.id) !== node) { node.freevideoLastResult = output.freevideo_summary[0]; return; }
app.nodeOutputs = {...app.nodeOutputs, [node.id]: output};
@@ -659,6 +727,35 @@ export function openStudio(node) {
},
}));
const queueController = studioQueues.get(node);
+ chainController = createStudioChain({api, node, onProgress: (message, chain) => {
+ const position = chainPosition(chain, message);
+ const joining = readChainResult(chain).joining, waiting = chain.state === 'queued' && message.phase === 'prepare';
+ chainLine.textContent = joining ? t('Joining the parts.', '正在接合各段。')
+ : waiting ? t(`Waiting in queue · Part ${position.index + 1} of ${position.count}`, `正在排队 · 第 ${position.index + 1} 段,共 ${position.count} 段`)
+ : t(`Part ${position.index + 1} of ${position.count}`, `第 ${position.index + 1} 段,共 ${position.count} 段`);
+ progress.element.querySelector('.fv-generation-label').hidden = joining || waiting;
+ progress.updateReport(message); showProgress(message);
+ },
+ onState: chain => {
+ const active = chainController.active, position = chainPosition(chain), outcome = readChainResult(chain);
+ busy = active || Boolean(queueState?.running || queueState?.pending.length); queued = chain?.state === 'queued';
+ chainLine.hidden = !active;
+ chainLine.textContent = outcome?.joining ? t('Joining the parts.', '正在接合各段。')
+ : t(`Part ${position.index + 1} of ${position.count}`, `第 ${position.index + 1} 段,共 ${position.count} 段`);
+ if (active && node.properties.freevideo_chain?.width) previewSize(node.properties.freevideo_chain.width, node.properties.freevideo_chain.height);
+ if (!active) { cancelling = false; hideProgress(); }
+ if (!active) progress.element.querySelector('.fv-generation-label').hidden = false;
+ if (chain?.state === 'cancelled') status.textContent = t('Cancelled', '已取消');
+ resumeChain.hidden = !['cancelled', 'failed', 'interrupted'].includes(chain?.state);
+ queueActions.hidden = !active && !busy && resumeChain.hidden;
+ updateRunButton();
+ },
+ onResult: (result, outcome) => { node.freevideoLastResult = result; showResult(result, {chosen: outcome.partial});
+ if (outcome.partial && !outcome.joined) status.textContent = t('Showing the last completed part.', '正在显示最后完成的一段。'); },
+ onError: error => showQueueError(new Error(error.joining ? t(`Could not join the parts: ${error.message}`, `未能接合各段:${error.message}`)
+ : t(`Part ${error.index + 1} failed: ${error.message}`, `第 ${error.index + 1} 段失败:${error.message}`)))});
+ cleanup.push(() => chainController.dispose());
+ node.freevideoStudioChain = chainController;
node.freevideoEditorLooping = () => queueController.state().looping;
if (!node.freevideoQueueCleanup) {
node.freevideoQueueCleanup = true;
@@ -695,13 +792,18 @@ export function openStudio(node) {
const queueToggle = el('summary'), queueList = el('div', null, 'fv-queue-list');
queueDetails.append(queueToggle, queueList);
const cancelCurrent = button(t('Cancel current', '取消当前'), cancelGeneration, 'fv-quiet');
+ const resumeChain = button(t('Continue generating', '继续生成'), async () => {
+ resumeChain.disabled = true; failure.clear();
+ try { await chainController.resume(); } catch (error) { showQueueError(error); }
+ finally { resumeChain.disabled = false; }
+ }, 'fv-quiet'); resumeChain.hidden = true;
const stopLoop = button(t('Stop after this video', '完成当前后停止'), async () => {
stopLoop.disabled = true;
try { await queueController.stopLoop(); }
catch (error) { showQueueError(error); }
finally { stopLoop.disabled = false; }
}, 'fv-quiet');
- queueActions.append(queueDetails, cancelCurrent, stopLoop);
+ queueActions.append(queueDetails, cancelCurrent, stopLoop, resumeChain);
runbar.append(runrow, queueActions); controls.append(runbar);
const queueError = error => ({
queue_unavailable: t('Could not read the queue. Any loop has been stopped; already submitted videos stay queued.', '暂时无法读取队列。循环已停止追加,已提交的任务仍在队列中。'),
@@ -714,6 +816,7 @@ export function openStudio(node) {
}[error?.message] || error?.message || String(error));
let lastQueueError = null;
function showQueueError(error) {
+ if (disposed) return;
status.dataset.error = 'true';
// Polling and loop shutdown must not replace the original exception
// with a generic "loop stopped" notice or reopen a dismissed dialog.
@@ -731,26 +834,36 @@ export function openStudio(node) {
}
function updateRunButton() {
const submitting = capturing || queueState?.submitting;
- generate.disabled = submitting || (runMode === 'loop' && queueState?.looping);
+ updateFirstFrame();
+ const multiple = lengthControl.plan?.count > 1;
+ if (multiple) runMode = 'single';
+ generate.disabled = submitting || chainController?.active || lengthControl.blocked || (runMode === 'loop' && queueState?.looping);
generate.textContent = submitting ? t('Adding…', '正在添加…')
: runMode === 'batch' ? t(`Add ${count.value || '…'} videos`, `添加 ${count.value || '…'} 条任务`)
: runMode === 'loop' ? (queueState?.looping ? t('Looping', '循环中') : t('Start loop', '开始循环'))
: busy ? t('Add to queue', '添加到队列')
: previewFirst.checked && !previewFirst.disabled ? t('Generate preview', '生成预览') : t('Generate video', '生成视频');
for (const b of modeButtons) b.setAttribute('aria-pressed', String(b.dataset.mode === runMode));
+ for (const b of modeButtons) if (b.dataset.mode !== 'single') b.disabled = multiple;
countField.hidden = runMode !== 'batch'; count.disabled = runMode !== 'batch';
- modeHelp.hidden = runMode === 'single';
- modeHelp.textContent = runMode === 'loop'
+ modeHelp.hidden = runMode === 'single' && !multiple;
+ modeHelp.textContent = multiple ? t('Batch and loop are unavailable for videos made in parts.', '分段视频暂不支持批量和循环生成。') : runMode === 'loop'
? t('Use these settings with a new seed each time. Closing this page stops adding videos.', '固定当前设置,每条使用不同种子。关闭网页后不再追加。')
: t('Use these settings with a different seed for each video.', '固定当前设置,每条使用不同种子。');
- cancelCurrent.hidden = !queueState?.running;
+ cancelCurrent.hidden = !queueState?.running && !chainController?.active;
cancelCurrent.disabled = cancelling;
cancelCurrent.textContent = cancelling ? t('Cancelling…', '正在取消…') : t('Cancel current', '取消当前');
stopLoop.hidden = !queueState?.looping;
+ updateExtendButton();
+ }
+ function updateExtendButton() {
+ const button = links.querySelector('.fv-action-extend');
+ if (button) button.disabled = busy || queued || capturing || Boolean(chainController?.active);
}
function renderQueue(state) {
if (disposed) return;
queueState = state;
+ if (chainController?.active) { queueActions.hidden = false; updateRunButton(); return; }
const active = state.running || state.pending[0];
activePrompt = active?.id || null;
busy = Boolean(active); queued = !state.running && Boolean(state.pending.length);
@@ -760,7 +873,7 @@ export function openStudio(node) {
if (Number.isFinite(g?.width) && Number.isFinite(g?.height)) previewSize(g.width, g.height);
queueToggle.textContent = t(`Queue · ${state.pending.length}`, `等待 ${state.pending.length} 条`);
queueDetails.hidden = state.pending.length === 0;
- queueActions.hidden = !busy && !state.looping;
+ queueActions.hidden = !busy && !state.looping && resumeChain.hidden;
const signature = JSON.stringify(state.pending.map(row => [row.id, row.inputs.width, row.inputs.height]));
if (queueList.dataset.signature !== signature) {
queueList.dataset.signature = signature; queueList.replaceChildren();
@@ -785,6 +898,7 @@ export function openStudio(node) {
if (cancelling) return;
try {
cancelling = true; updateRunButton();
+ if (chainController.active) { await chainController.cancel(); cancelling = false; updateRunButton(); return; }
await syncQueue();
const id = queueController.state().running?.id;
if (!id) { cancelling = false; updateRunButton(); return; }
@@ -800,23 +914,39 @@ export function openStudio(node) {
const editing = dialog.contains(document.activeElement) ? document.activeElement : null;
if (editing && editing !== generate) { editing.blur(); editing.focus({preventScroll: true}); }
if ([...dialog.querySelectorAll('input:not(:disabled)')].some(e => !e.reportValidity())) return;
- if (!prompt.disabled && !prompt.value.trim() && !untouched()) { prompt.focus(); status.textContent = t('Describe your scene first.', '请先描述画面。'); return; }
+ if (!extension.source && !prompt.disabled && !prompt.value.trim() && !untouched()) { prompt.focus(); status.textContent = t('Describe your scene first.', '请先描述画面。'); return; }
const chosenMode = runMode, batchCount = chosenMode === 'batch' ? Number(count.value) : 1;
const originalSeed = value(node, 'seed'), seedMode = mode.value;
try {
lastQueueError = null; failure.clear(); node.freevideoFailure = ''; node.freevideoFailureReport = null;
capturing = true; updateRunButton(); status.dataset.error = 'false'; runOptions.open = false;
- if (await enhancer.beforeGenerate() === false) return;
+ lengthControl.freeze();
+ if ((!extension.source || prompt.value.trim()) && await enhancer.beforeGenerate() === false) return;
if (disposed) return;
+ if (selected === 'input' && !dimensionsLinked) await inputRatio(true);
+ const lengthPlan = await lengthControl.ready();
+ if (disposed || lengthControl.blocked) return;
+ if (lengthControl.absent && !seconds.reportValidity()) return;
+ if (lengthPlan?.count > 1 && chosenMode !== 'single') { status.textContent = t('Batch and loop are unavailable for videos made in parts.', '分段视频暂不支持批量和循环生成。'); return; }
+ const lengthOptions = lengthControl.options();
+ const source = extension.source;
+ if (source && !await extendSourceExists(api, source)) throw new Error(extendText(t, 'unavailable'));
+ if (source && lengthPlan?.count > 1) lengthOptions.after = {work: source.video};
// Only serialization briefly locks the editor. Network submission
// and all GPU execution leave the next draft fully editable.
for (const section of controls.querySelectorAll('.fv-section')) section.inert = true;
- if (selected === 'input' && !dimensionsLinked) await inputRatio(true);
- const snapshot = structuredClone(await app.graphToPrompt());
+ const snapshot = singleRunSnapshot(extendSnapshot(structuredClone(await app.graphToPrompt()), node.id, source,
+ {multiple: lengthPlan?.count > 1}), node.id, lengthPlan);
+ if (!snapshot) { status.textContent = t('Could not plan this single run. Try again.', '暂时无法计算这次单次生成,请重试。'); return; }
const seedIndex = node.widgets.findIndex(w => w.name === 'seed');
capturing = false;
for (const section of controls.querySelectorAll('.fv-section')) section.inert = false;
- await queueController.start(snapshot, {count: batchCount, repeat: chosenMode === 'loop', seedIndex});
+ if (lengthPlan?.count > 1) {
+ const chain = await chainController.start(snapshot, lengthOptions);
+ if (disposed) return;
+ if (!chain) { if (source) throw new Error(extendText(t, 'unavailable')); lengthControl.fallback(); if (!seconds.reportValidity()) return;
+ await queueController.start(snapshot, {count: batchCount, repeat: chosenMode === 'loop', seedIndex}); }
+ } else await queueController.start(snapshot, {count: batchCount, repeat: chosenMode === 'loop', seedIndex});
// Preserve draft changes made while the POST was in flight.
if (chosenMode === 'single' && !linked(node, 'seed') && value(node, 'seed') === originalSeed) {
const max = Number.MAX_SAFE_INTEGER;
@@ -839,11 +969,17 @@ export function openStudio(node) {
if (!queueDetails.contains(event.target)) queueDetails.open = false;
};
dialog.addEventListener('pointerdown', closeMenus);
- function updateCanvas() {
- width.value = value(node, 'width'); height.value = value(node, 'height');
- dimensionText(dimensions, dimensionsLinked ? t('Size from connected nodes', '尺寸来自已连接节点') : `${width.value} × ${height.value}`);
+ function updateDuration() {
const requested = Math.ceil(Number(seconds.value) * 24), frames = requested + ((5 - requested) % 17 + 17) % 17;
- duration.textContent = Number.isFinite(frames) ? `${(frames / 24).toFixed(3)} s · 24 fps` : '—';
+ const length = lengthControl.plan?.count > 1 ? lengthControl.plan.seconds : Number.isFinite(frames) ? frames / 24 : null;
+ const whole = Math.round(length), minutes = Math.floor(whole / 60), rest = whole % 60;
+ duration.textContent = length === null ? '—' : `${length <= 60 ? `${lengthControl.plan?.count > 1 ? length : length.toFixed(3)} s`
+ : rest ? t(`${minutes} min ${rest} s`, `${minutes} 分 ${rest} 秒`) : t(`${minutes} min`, `${minutes} 分钟`)} · 24 fps`;
+ }
+ function updateCanvas() {
+ width.value = extension.source?.geometry.width ?? value(node, 'width'); height.value = extension.source?.geometry.height ?? value(node, 'height');
+ dimensionText(dimensions, dimensionsLinked && !extension.source ? t('Size from connected nodes', '尺寸来自已连接节点') : `${width.value} × ${height.value}`);
+ updateDuration();
for (const b of shapes.children) b.setAttribute('aria-pressed', String(b.dataset.ratio === selected));
const shapeIndex = [...shapes.children].findIndex(b => b.dataset.ratio === selected);
shapes.style.setProperty('--fv-shape-index', Math.max(0, shapeIndex));
@@ -852,7 +988,7 @@ export function openStudio(node) {
refreshEffortEstimate();
}
function applySize() {
- if (dimensionsLinked) return;
+ if (dimensionsLinked || extension.source) return;
const [w, h] = canvasDimensions(pixels, ratio);
if (w < 256 || h < 256 || w > 4096 || h > 4096) throw new Error(t('This aspect ratio and pixel count exceed the supported dimensions. Use custom dimensions.', '该比例与像素数超出尺寸范围,请使用自定义宽高。'));
set(node, 'width', w); set(node, 'height', h); node.properties.freevideo_aspect = selected; node.properties.freevideo_pixels = pixels; updateCanvas();
@@ -873,12 +1009,12 @@ export function openStudio(node) {
b.append(el('span', null, 'fv-shape-icon'), el('span', label)); shapes.append(b);
}
mp.onchange = () => { try { pixels = Number(mp.value); applySize(); if (pixels !== 1) legacyOption?.remove(); } catch (error) { status.dataset.error = 'true'; status.textContent = error.message; } };
- seconds.onchange = () => { if (seconds.value && seconds.reportValidity()) { set(node, 'seconds', Number(seconds.value)); updateCanvas(); } };
- const mediaChanged = async e => { if (String(e.detail) !== String(mediaNode?.id)) return; refreshEffortEstimate(); if (selected !== 'input') return; try { await inputRatio(); } catch (error) { status.textContent = error.message; } };
- const lorasChanged = e => { if (String(e.detail) === String(loraNode?.id)) refreshEffortEstimate(); };
+ seconds.onchange = () => { if (lengthControl.commit()) updateCanvas(); };
+ const mediaChanged = async e => { if (String(e.detail) !== String(mediaNode?.id)) return; refreshEffortEstimate(true); if (selected !== 'input') return; try { await inputRatio(); } catch (error) { status.textContent = error.message; } };
+ const lorasChanged = e => { if (String(e.detail) === String(loraNode?.id)) refreshEffortEstimate(true); };
window.addEventListener('freevideo-loras', lorasChanged);
cleanup.push(() => window.removeEventListener('freevideo-loras', lorasChanged));
- const resultChanged = e => { if (String(e.detail.node) === String(node.id)) { failure.clear(); showResult(e.detail.value); cancelling = false; status.textContent = ''; syncQueue().catch(() => {}); } };
+ const resultChanged = e => { if (String(e.detail.node) === String(node.id)) { if (chainController.active || chainController.isBlockOutput(e.detail.value)) { node.freevideoLastResult = result; return; } failure.clear(); showResult(e.detail.value); cancelling = false; status.textContent = ''; syncQueue().catch(() => {}); } };
const prewarmChanged = e => { if (String(e.detail.node) === String(node.id)) prewarm.textContent = e.detail.label; };
window.addEventListener('freevideo-prewarm', prewarmChanged);
cleanup.push(() => window.removeEventListener('freevideo-prewarm', prewarmChanged));
@@ -886,9 +1022,10 @@ export function openStudio(node) {
cleanup.push(() => { window.removeEventListener('freevideo-media', mediaChanged); window.removeEventListener('freevideo-result', resultChanged); });
const listen = (type, handler) => { api.addEventListener(type, handler); cleanup.push(() => api.removeEventListener(type, handler)); };
listen('status', () => { syncQueue().catch(() => {}); });
- listen('executing', e => { const id = typeof e.detail === 'object' ? e.detail?.node : e.detail; if (String(id) === String(node.id)) { failure.clear(); node.freevideoFailure = ''; node.freevideoFailureReport = null; busy = true; queued = false; updateRunButton(); showProgress(node.freevideoProgress || {label: t('Preparing your video', '正在准备视频'), reset: true, new_request: true}); status.textContent = ''; } syncQueue().catch(() => {}); });
+ listen('executing', e => { const id = typeof e.detail === 'object' ? e.detail?.node : e.detail; if (String(id) === String(node.id)) { if (chainController.active) { chainController.refresh(); return; } failure.clear(); node.freevideoFailure = ''; node.freevideoFailureReport = null; busy = true; queued = false; updateRunButton(); showProgress(node.freevideoProgress || {label: t('Preparing your video', '正在准备视频'), reset: true, new_request: true}); status.textContent = ''; } syncQueue().catch(() => {}); });
const progressChanged = e => {
if (String(e.detail.node) !== String(node.id)) return;
+ if (chainController.progress(e.detail)) return;
progress.updateReport(e.detail);
if (['failed', 'cancelled'].includes(e.detail.phase) || e.detail.result) {
busy = cancelling = false; updateRunButton();
@@ -905,6 +1042,7 @@ export function openStudio(node) {
window.addEventListener('freevideo-progress', progressChanged);
cleanup.push(() => window.removeEventListener('freevideo-progress', progressChanged));
listen('execution_error', e => {
+ if (chainController.active && String(e.detail?.node_id) === String(node.id)) { chainController.refresh(); return; }
const seen = new Set(), pending = [node];
while (pending.length) {
const currentNode = pending.pop(); if (!currentNode || seen.has(String(currentNode.id))) continue;
@@ -918,6 +1056,7 @@ export function openStudio(node) {
status.textContent = t('Generation stopped. See the explanation below.', '生成已停止,原因和处理建议见下方。');
});
listen('execution_interrupted', e => {
+ if (chainController.active && String(e.detail?.node_id) === String(node.id)) { chainController.refresh(); return; }
if (activePrompt ? e.detail?.prompt_id !== activePrompt : String(e.detail?.node_id) !== String(node.id)) return;
busy = cancelling = false; activePrompt = null; updateRunButton(); hideProgress();
failure.clear(); node.freevideoFailure = ''; node.freevideoFailureReport = null; status.dataset.error = 'false'; status.textContent = t('Cancelled', '已取消');
@@ -927,7 +1066,7 @@ export function openStudio(node) {
dialog.onclose = () => { disposed = true; for (const f of cleanup) f(); stage.querySelector('video')?.pause(); dialog.remove(); if (current?.dialog === dialog) { current = null; viewChanged('nodes', node); } };
capabilityView = createCapabilityView({node, api, t, getState: () => ({ratio,
custom: selected === 'custom', steps: Number(baseSteps.value), twoPass: twoPass.checked,
- refine: Number(refineSteps.value), disabled: dimensionsLinked || seconds.disabled}), onEstimate: () => showEffortEstimate(), onPick: point => {
+ refine: Number(refineSteps.value), disabled: Boolean(extension.source) || dimensionsLinked || seconds.disabled}), onEstimate: () => showEffortEstimate(), onPick: point => {
pixels = point.pixels; mp.value = String(pixels);
set(node, 'width', point.width); set(node, 'height', point.height);
node.properties.freevideo_pixels = pixels;
@@ -935,14 +1074,56 @@ export function openStudio(node) {
}});
rangeMount.append(capabilityView.element); cleanup.push(capabilityView.dispose);
controls.addEventListener('change', () => capabilityView.update());
+ function syncExtension() {
+ releaseExtendThumbnail(); extendMount.replaceChildren();
+ const source = extension.source;
+ extendMount.hidden = !source; mediaMount.classList.toggle('fv-extend-active', Boolean(source));
+ if (source) runMode = 'single';
+ canvasLock.hidden = !source;
+ mp.disabled = width.disabled = height.disabled = Boolean(source) || dimensionsLinked;
+ for (const shape of shapes.children) shape.disabled = Boolean(source) || dimensionsLinked;
+ seconds.value = savedSeconds(node, value(node, 'seconds'));
+ pixels = node.properties.freevideo_pixels ?? Number(value(node, 'width')) * Number(value(node, 'height')) / 1024 ** 2;
+ if (![...mp.options].some(option => Number(option.value) === pixels)) {
+ const option = el('option', `${pixels.toFixed(2)} MP`); option.value = pixels; mp.append(option);
+ }
+ mp.value = String(pixels);
+ ratio = source ? source.geometry.width / source.geometry.height : Number(value(node, 'width')) / Number(value(node, 'height'));
+ selected = node.properties.freevideo_aspect || 'custom';
+ if (source) {
+ selected = [['16:9', 16 / 9], ['9:16', 9 / 16], ['1:1', 1]].find(([, r]) => Math.abs(Math.log(ratio / r)) < .035)?.[0] || 'custom';
+ const image = el('img'); image.alt = extendText(t, 'source');
+ const label = el('span', extendText(t, 'source'));
+ const remove = button('', () => { extension.remove(); syncExtension(); }, 'fv-quiet fv-extend-remove');
+ remove.append(icon('close')); remove.title = remove.ariaLabel = extendText(t, 'remove');
+ extendMount.append(image, label, remove); mediaDetails.open = true;
+ releaseExtendThumbnail = mountExtendThumbnail(image, api, source);
+ }
+ twoPass.checked = Boolean(source) || value(node, 'two_pass') !== false;
+ previewFirst.checked = !source && value(node, 'preview') === true;
+ prompt.value = shown(value(node, 'text')); placeholder(); enhancer.sync();
+ syncSamplingSteps(); updateCanvas(); seconds.dispatchEvent(new Event('input'));
+ prompt.focus({preventScroll: true});
+ }
+ current.enterExtend = record => {
+ if (!extension.enter(record)) throw new Error(extendText(t, 'unavailable'));
+ syncExtension();
+ };
+ const sourceDeleted = event => {
+ if (event.detail?.video === result?.video) links.querySelector('.fv-action-extend')?.remove();
+ if (event.detail?.video === extension.source?.video) { extension.remove(); syncExtension(); }
+ };
+ window.addEventListener('freevideo-library-deleted', sourceDeleted);
+ cleanup.push(() => window.removeEventListener('freevideo-library-deleted', sourceDeleted));
document.body.append(dialog); dialog.showModal(); viewChanged('studio', node); updateCanvas();
+ if (extension.source) syncExtension();
let guide = null, closed = false;
cleanup.push(() => { closed = true; guide?.dispose(); });
agentDiscovery.then(() => {
if (!closed) guide = createFirstRunGuide({dialog, api, cn, isBusy: () => busy || queued || capturing});
});
const recentLoad = recent.refresh();
- if (node.freevideoProgress) showProgress(node.freevideoProgress);
+ if (node.freevideoProgress && !node.freevideoProgress.chain) showProgress(node.freevideoProgress);
else if (result) showResult(result);
// Do not change any saved width/height simply by opening a workflow.
syncQueue().then(async () => {
@@ -953,6 +1134,6 @@ export function openStudio(node) {
if (!disposed && !busy && !result && saved) showResult(saved);
}
}).catch(() => {});
- requestAnimationFrame(() => { if (dialog.open && !dialog.querySelector('.fv-guide-layer') && !document.querySelector('dialog.fv-editor[open]')) generate.focus({preventScroll: true}); });
+ requestAnimationFrame(() => { if (dialog.open && !dialog.querySelector('.fv-guide-layer') && !document.querySelector('dialog.fv-editor[open]')) (extension.source ? prompt : generate).focus({preventScroll: true}); });
return dialog;
}
diff --git a/web/studio_chain.js b/web/studio_chain.js
new file mode 100644
index 0000000..1939f5f
--- /dev/null
+++ b/web/studio_chain.js
@@ -0,0 +1,170 @@
+import {chainRoute, createPoller} from './chain_support.js';
+import {buildChainRequest} from './length_plan.js?v=20261011-length';
+
+export const CHAIN_PROPERTY = 'freevideo_chain';
+const activeStates = new Set(['queued', 'running', 'cancelling']);
+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)});
+
+export function chainPosition(chain, message = {}) {
+ const count = message.chain?.count ?? chain?.count ?? chain?.blocks?.length ?? 0;
+ let index = message.chain?.index ?? chain?.current?.index;
+ if (!Number.isInteger(index)) index = chain?.blocks?.findIndex(block => block.id === chain.current) ?? -1;
+ if (index < 0) index = chain?.blocks?.findIndex(block => ['queued', 'running', 'failed', 'cancelled'].includes(block.state)) ?? -1;
+ if (index < 0) index = chain?.blocks?.findIndex(block => block.state === 'pending') ?? -1;
+ if (index < 0) index = Math.max(0, count - 1);
+ return {index: Math.min(Math.max(0, index), Math.max(0, count - 1)), count};
+}
+
+// A fallback part is explicitly distinct from a joined partial result.
+export function readChainResult(chain) {
+ if (!chain) return null;
+ const joining = chain.output_state === 'joining' || (chain.output_state == null && chain.joining === true);
+ const failedJoin = chain.output_state === 'failed';
+ const stopped = ['failed', 'cancelled', 'interrupted'].includes(chain.state);
+ const last = chain.blocks?.filter(block => block.state === 'done' && block.output).at(-1);
+ const joined = chain.output_state === 'done' && typeof chain.output === 'string' && Boolean(chain.output);
+ const video = joined ? chain.output : !joining && (failedJoin || stopped) ? last?.output || null : null;
+ return {video, joined, joining, partial: Boolean(video) && (!joined || stopped),
+ error: failedJoin ? chain.output_error || 'join_failed' : chain.error || chain.blocks?.find(block => block.state === 'failed')?.error || null};
+}
+
+export function sumPartEstimates(plan, estimate) {
+ if (!plan || plan.count < 2 || typeof estimate !== 'function') return null;
+ const values = plan.blocks.map(block => estimate(block.frames));
+ return values.every(finite) ? values.reduce((total, value) => total + value, 0) : null;
+}
+
+export function singleRunSnapshot(snapshot, node, plan) {
+ if (!plan?.single || plan.seconds <= 60) return snapshot;
+ const frames = plan.blocks?.[0]?.frames, id = String(node), output = snapshot.output?.[id];
+ if (plan.count !== 1 || !Number.isSafeInteger(frames) || frames <= 0 || !output) return null;
+ return {...snapshot, output: {...snapshot.output, [id]: {...output, inputs: {...output.inputs, frames}}}};
+}
+
+export function createStudioChain({api, node, onState = () => {}, onProgress = () => {}, onResult = () => {},
+ onError = () => {}, pollMs = 2000, now = () => Date.now()}) {
+ let chain = null, poller = null, disposed = false, epoch = 0, submitting = false;
+ let previous = {}, lastMessage = {}, delivered = null, errorShown = null, corrected = false, etaAt = 0, lastIndex = -1;
+ const timers = new Set();
+ const clock = {now, setTimeout(fn, ms) { const id = setTimeout(() => { timers.delete(id); fn(); }, ms); timers.add(id); return id; },
+ clearTimeout(id) { clearTimeout(id); timers.delete(id); }};
+ function clearPolls() { for (const id of timers) clearTimeout(id); timers.clear(); }
+ function refresh() { clearPolls(); return poller?.poll(); }
+ const active = () => submitting || activeStates.has(chain?.state) || chain?.output_state === 'joining';
+ async function json(path, options) {
+ const response = await api.fetchApi(path, options);
+ if (response.status === 404) return null;
+ const value = await response.json();
+ if (!response.ok) throw Object.assign(new Error(value.error || 'chain_request_failed'), {code: value.code, status: response.status});
+ return value;
+ }
+ function progress(message = {}, fresh = false) {
+ if (!chain || disposed) return;
+ if (message.chain?.id && message.chain.id !== chain.id) return;
+ const position = chainPosition(chain, message);
+ if (position.index !== lastIndex) { lastMessage = {}; lastIndex = position.index; }
+ const raw = message.chain?.overall || chain.overall;
+ const overall = {...previous};
+ if (raw) {
+ if (finite(raw.fraction)) overall.fraction = Math.max(previous.fraction || 0, Math.min(.99, raw.fraction));
+ if (finite(raw.elapsed_seconds)) overall.elapsed_seconds = Math.max(previous.elapsed_seconds || 0, raw.elapsed_seconds);
+ if (finite(raw.remaining_seconds) && (etaAt === 0 || now() - etaAt >= 5000)) {
+ const rises = finite(previous.remaining_seconds) && raw.remaining_seconds > previous.remaining_seconds;
+ if (!rises || (position.index > 0 && !corrected)) {
+ overall.remaining_seconds = raw.remaining_seconds; etaAt = now(); if (rises) corrected = true;
+ }
+ }
+ }
+ if (Object.keys(overall).length) Object.assign(overall, {status: 'running', reset: false, estimated: false, sampling_time_weighted: true});
+ previous = overall;
+ lastMessage = {...lastMessage, ...message};
+ const phase = readChainResult(chain).joining ? 'save'
+ : ['complete', 'failed', 'cancelled'].includes(lastMessage.phase) ? 'prepare' : lastMessage.phase || 'prepare';
+ onProgress({...lastMessage, phase, result: null, reset: false, new_request: fresh,
+ chain: {id: chain.id, ...position}, overall}, chain);
+ }
+ function deliver(value, fresh = false) {
+ if (disposed) return false;
+ if (!value?.id) return active();
+ chain = value; onState(chain);
+ const result = readChainResult(chain);
+ if (active()) progress({}, fresh);
+ if (result.error && errorShown !== result.error) {
+ errorShown = result.error; onError(Object.assign(new Error(result.error), {joining: chain.output_state === 'failed', ...chainPosition(chain)}));
+ }
+ // Continuing a stopped chain can write the joined video to the path already shown.
+ const version = `${chain.blocks?.filter(block => block.state === 'done').length || 0}-${result.joined ? 'joined' : 'part'}`;
+ const key = result.video && `${result.video}\n${version}`;
+ if (key && delivered !== key) {
+ delivered = key;
+ const metadata = node.properties?.[CHAIN_PROPERTY] || {};
+ onResult({video: result.video, request_id: chain.id, version,
+ geometry: {width: metadata.width, height: metadata.height}, report_id: chain.last_report_id}, result, chain);
+ }
+ return active();
+ }
+ function watch(fresh = false) {
+ poller?.dispose(); clearPolls();
+ const id = chain.id, version = epoch;
+ poller = createPoller(async () => (await json(chainRoute(id)))?.chain || null,
+ value => version === epoch && !disposed ? deliver(value, fresh) : false,
+ {interval: pollMs, clock});
+ }
+ function adopt(value, metadata = null) {
+ if (chain?.id !== value.id) { epoch++; previous = {}; lastMessage = {}; delivered = errorShown = null; corrected = false; etaAt = 0; lastIndex = -1; }
+ if (metadata) { node.properties ||= {}; node.properties[CHAIN_PROPERTY] = {id: value.id, ...metadata}; node.graph?.change(); }
+ if (disposed) return;
+ deliver(value, true); if (active()) watch();
+ }
+ async function recover() {
+ const version = epoch;
+ try {
+ const known = node.properties?.[CHAIN_PROPERTY]?.id;
+ const reply = await json('/freevideo/chains');
+ if (disposed || version !== epoch || chain) return;
+ const found = reply?.chains?.find(row => String(row.node) === String(node.id) && (known ? row.id === known
+ : activeStates.has(row.state) && row.client_id && row.client_id === api.clientId));
+ if (!found) return;
+ const value = (await json(chainRoute(found.id)))?.chain;
+ if (disposed || version !== epoch || chain || !value) return;
+ adopt(value);
+ if (node.freevideoProgress?.chain?.id === value.id) progress(node.freevideoProgress);
+ } catch {} // Recovery must never enqueue a request or block ordinary generation.
+ }
+ recover();
+ return {
+ get active() { return active(); }, get state() { return chain; },
+ async start(snapshot, options) {
+ if (disposed || active()) throw new Error('chain_busy');
+ submitting = true; epoch++;
+ try {
+ const body = buildChainRequest(options, {node: node.id, prompt: snapshot.output,
+ extra_data: {extra_pnginfo: {workflow: snapshot.workflow || {}}}, ...(api.clientId ? {client_id: api.clientId} : {})});
+ const value = (await json(chainRoute(), post(body)))?.chain;
+ if (!value) return null;
+ if (!value.id) throw new Error('chain_missing');
+ const inputs = snapshot.output[String(node.id)].inputs;
+ submitting = false; adopt(value, {width: inputs.width, height: inputs.height, seconds: options.seconds});
+ return value;
+ } finally { submitting = false; }
+ },
+ refresh,
+ async cancel() {
+ if (!chain) return;
+ const id = chain.id, version = epoch;
+ const value = (await json(chainRoute(id, 'cancel'), post({})))?.chain;
+ if (version === epoch && !disposed && value) { epoch++; poller?.dispose(); clearPolls(); deliver(value); if (active()) watch(); }
+ },
+ async resume() {
+ if (!chain || active()) return;
+ const id = chain.id, version = epoch;
+ const value = (await json(chainRoute(id, 'resume'), post({client_id: api.clientId})))?.chain;
+ if (version === epoch && !disposed && value) { epoch++; poller?.dispose(); clearPolls(); previous = {}; corrected = false; etaAt = 0; delivered = errorShown = null; deliver(value, true); if (active()) watch(); }
+ },
+ progress(message) { if (!chain || message.chain?.id !== chain.id) return false; progress(message);
+ if (message.result || ['complete', 'failed', 'cancelled'].includes(message.phase)) refresh(); return true; },
+ isBlockOutput(result) { return Boolean(chain?.blocks?.some(block => result?.request_id && block.prompt_id === result.request_id || result?.video && block.output === result.video)); },
+ dispose() { disposed = true; epoch++; poller?.dispose(); clearPolls(); },
+ };
+}
diff --git a/web/studio_extend.js b/web/studio_extend.js
new file mode 100644
index 0000000..c465213
--- /dev/null
+++ b/web/studio_extend.js
@@ -0,0 +1,139 @@
+export const EXTEND_PROPERTY = 'freevideo_extend';
+export const EXTEND_TEXT = Object.freeze({
+ action: ['Extend', '接着生成'],
+ source: ['Continues this video', '接在这条视频后面'],
+ remove: ['Remove', '移除'],
+ prompt: ['Prompt', '描述'],
+ unavailable: ['Video unavailable', '视频不可用'],
+});
+export const extendText = (t, key) => t(...EXTEND_TEXT[key]);
+
+export function canExtend(record) {
+ return Boolean(record?.video && /\.mp4$/i.test(record.video) && !record.preview
+ && record.has_video !== false && !['image', 'audio'].includes(record.kind)
+ && record.exists !== false && record.missing !== true);
+}
+
+export function extendVideoURL(record) {
+ const split = record.video.lastIndexOf('/');
+ return '/view?' + new URLSearchParams({filename: record.video.slice(split + 1),
+ subfolder: split < 0 ? '' : record.video.slice(0, split), type: 'output'});
+}
+
+export async function extendSourceExists(api, record) {
+ if (!canExtend(record)) return false;
+ try { return (await api.fetchApi(extendVideoURL(record), {method: 'HEAD'})).ok; }
+ catch { return false; }
+}
+
+export async function readExtendRecord(api, record) {
+ if (record.geometry?.width && record.geometry?.height && (record.geometry.seconds || record.geometry.frames)) return record;
+ let before = null;
+ do {
+ const query = new URLSearchParams({limit: '48'}); if (before) query.set('before', before);
+ const response = await api.fetchApi('/freevideo/library?' + query);
+ if (!response.ok) return record;
+ const page = await response.json(), saved = page.items?.find(row => row.video === record.video);
+ if (saved) return saved;
+ before = page.next;
+ } while (before);
+ return record;
+}
+
+export function createExtendState(node, read, write) {
+ const keys = ['width', 'height', 'seconds', 'two_pass', 'preview', 'base_steps', 'refine_steps'];
+ return {
+ get source() { return node.properties?.[EXTEND_PROPERTY]?.source || null; },
+ enter(record) {
+ const g = record.geometry || {};
+ let seconds = record.continuation?.new_frames ? record.continuation.new_frames / (g.fps || 24)
+ : g.seconds || g.frames / (g.fps || 24);
+ if (!canExtend(record) || ![g.width, g.height, seconds].every(n => Number.isFinite(n) && n > 0)) return false;
+ node.properties ||= {};
+ const previous = node.properties[EXTEND_PROPERTY]?.previous || {
+ values: Object.fromEntries(keys.map(key => [key, read(key)])),
+ aspect: node.properties.freevideo_aspect, pixels: node.properties.freevideo_pixels,
+ seconds: node.properties.freevideo_seconds,
+ };
+ // Whole milliseconds, never rounded up past the frame count.
+ seconds = Math.floor(seconds * 1000 + 1e-6) / 1000;
+ const source = structuredClone(record); source.geometry = {...g, seconds};
+ node.properties[EXTEND_PROPERTY] = {source, previous};
+ for (const [key, value] of Object.entries({width: g.width, height: g.height,
+ seconds: Math.min(60, seconds), text: '', preview: false,
+ // A continuation always runs the Light plan: two passes, 8 + 3 steps.
+ two_pass: true, base_steps: 8, refine_steps: 3})) write(key, value);
+ node.properties.freevideo_seconds = seconds;
+ node.properties.freevideo_aspect = 'custom';
+ node.properties.freevideo_pixels = g.width * g.height / 1024 ** 2;
+ return true;
+ },
+ remove() {
+ const previous = node.properties?.[EXTEND_PROPERTY]?.previous;
+ if (!previous) return;
+ delete node.properties[EXTEND_PROPERTY];
+ for (const [key, value] of Object.entries(previous.values)) if (value !== undefined) write(key, value);
+ for (const [key, value] of Object.entries({freevideo_aspect: previous.aspect,
+ freevideo_pixels: previous.pixels, freevideo_seconds: previous.seconds})) {
+ if (value === undefined) delete node.properties[key]; else node.properties[key] = value;
+ }
+ },
+ };
+}
+
+export function extendSnapshot(snapshot, node, source, {multiple = false} = {}) {
+ if (!source) return snapshot;
+ const copy = structuredClone(snapshot), inputs = copy.output[String(node)].inputs;
+ inputs.width = source.geometry.width; inputs.height = source.geometry.height;
+ inputs.preview = false; inputs.refine_from = ''; inputs.two_pass = true;
+ for (const [key, value] of [['base_steps', 8], ['refine_steps', 3]]) if (key in inputs) inputs[key] = value;
+ delete inputs.first;
+ if (multiple) delete inputs.continue_from; else inputs.continue_from = source.video;
+ // The predecessor's tail replaces the draft's first frame.
+ const media = copy.output[String(inputs.media?.[0])];
+ if (media?.class_type === 'FreeVideoMedia') {
+ // The continuation's own last frames stand in for every first, last and reference item.
+ delete media.inputs.first;
+ if (media.inputs.assets) media.inputs.assets = '[]';
+ }
+ return copy;
+}
+
+// Seek the actual video tail; the library thumbnail is its first frame.
+export function mountExtendThumbnail(image, api, record) {
+ const video = document.createElement('video'); video.preload = 'auto'; video.muted = true;
+ video.playsInline = true; video.setAttribute('aria-hidden', 'true');
+ Object.assign(video.style, {position: 'absolute', width: '1px', height: '1px', opacity: '.01', pointerEvents: 'none'});
+ image.parentElement.append(video);
+ let disposed = false, captured = false, target = 0, callback = null;
+ const capture = () => {
+ if (disposed || captured || !video.videoWidth) return;
+ captured = true;
+ video.pause();
+ const canvas = document.createElement('canvas'); canvas.width = 192;
+ canvas.height = Math.round(192 * video.videoHeight / video.videoWidth);
+ canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
+ image.src = canvas.toDataURL('image/jpeg', .8);
+ video.removeAttribute('src'); video.load(); video.remove();
+ };
+ const waitForFrame = () => {
+ callback = video.requestVideoFrameCallback((_now, metadata) => {
+ if (disposed || captured) return;
+ if (metadata.mediaTime + .001 >= target) capture(); else waitForFrame();
+ });
+ };
+ video.onloadedmetadata = () => {
+ if (!Number.isFinite(video.duration)) return;
+ target = Math.max(0, video.duration - 1 / (record.geometry?.fps || 24));
+ if (video.requestVideoFrameCallback) waitForFrame();
+ video.currentTime = target;
+ };
+ video.onseeked = () => {
+ // A paused video may not present its newly decoded frame.
+ if (video.requestVideoFrameCallback) video.play().catch(() => requestAnimationFrame(capture));
+ else requestAnimationFrame(capture);
+ };
+ video.src = api.apiURL(extendVideoURL(record));
+ return () => { disposed = true; video.pause(); if (callback !== null) video.cancelVideoFrameCallback?.(callback);
+ video.onloadedmetadata = video.onseeked = null; video.removeAttribute('src'); video.load(); video.remove(); };
+}
diff --git a/web/studio_length.js b/web/studio_length.js
new file mode 100644
index 0000000..201a722
--- /dev/null
+++ b/web/studio_length.js
@@ -0,0 +1,170 @@
+import {capabilityPoints, interpolate} from './chain_support.js';
+import {buildPlanRequest, readLengthPlan, classifyPlanError, singleLimitSeconds, defaultBlockSeconds} from './length_plan.js?v=20261011-length';
+
+export const LENGTH_PROPERTIES = Object.freeze({seconds: 'freevideo_seconds', single: 'freevideo_single', block: 'freevideo_block_seconds'});
+const positive = value => typeof value === 'number' && Number.isFinite(value) && value > 0;
+export const savedSeconds = (node, fallback) => positive(node.properties?.[LENGTH_PROPERTIES.seconds]) ? node.properties[LENGTH_PROPERTIES.seconds] : fallback;
+
+// Use the editor's capability adapter, including its new 30s display ceiling.
+// Only the explicit single-run override reads the raw frame limit.
+export async function readLengthCapability(api, context, signal, onReply = () => {}) {
+ try {
+ const {width, height, settings, task, adapters} = context;
+ const response = await api.fetchApi('/freevideo/capabilities?' + new URLSearchParams({width, height,
+ tier: settings.tier, base_steps: settings.base_steps, refine_steps: settings.refine_steps,
+ two_pass: settings.two_pass ? '1' : '0', task, adapters: adapters ? '1' : '0'}), {signal});
+ onReply();
+ if (!response.ok) return null;
+ const reply = await response.json();
+ if (reply.status && reply.status !== 'ready') return null;
+ const value = capabilityPoints(reply, {width, height, settings});
+ if (value.maxRequestFrames === null) return null;
+ return {maximum: value.maxSeconds, singleMaximum: value.maxRequestFrames / 24, maxFrames: value.maxRequestFrames,
+ estimate: frames => interpolate(value.points, frames / 24)};
+ } catch { return null; }
+}
+
+export function createStudioLength({api, node, seconds, advanced, fields, t, field, setSeconds,
+ onChange = () => {}, capability = readLengthCapability, delay = 220, capabilityTimeout = 10000}) {
+ const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text) e.textContent = text; return e; };
+ const controls = el('div', 'fv-length-controls'); controls.style.marginTop = '14px';
+ const single = el('input'); single.type = 'checkbox'; single.dataset.fvLength = 'single';
+ single.setAttribute('aria-label', t('Force a single run', '强制单次生成'));
+ single.style.minHeight = '0'; single.style.marginRight = '8px';
+ const toggle = el('label'); toggle.append(single, document.createTextNode(t('Force a single run', '强制单次生成')));
+ const explanation = el('p', 'fv-muted', t('Generate in one run, even beyond 30 seconds.', '超过 30 秒时也一次生成。'));
+ const unavailable = el('p', 'fv-muted'); unavailable.hidden = true;
+ const block = el('input'); block.type = 'number'; block.min = '5'; block.step = '1'; block.required = true;
+ block.dataset.fvLength = 'block'; block.setAttribute('aria-label', t('Part length · seconds', '每段时长 · 秒'));
+ const reset = el('button', 'fv-quiet', t('Restore default', '恢复默认')); reset.type = 'button';
+ controls.append(toggle, explanation, unavailable, field(t('Part length · seconds', '每段时长 · 秒'), block), reset); advanced.append(controls);
+ const note = el('div', 'fv-muted fv-length-plan');
+ note.hidden = true; fields.after(note); note.setAttribute('role', 'status');
+ let limits = null, planLimits = null, contextKey = '', revision = 0, timer = null, request = null, capabilityRequest = null, capabilityRevision = 0;
+ let capabilityState = 'idle', waiting = false, waitingTimer = null, timeoutTimer = null, submitted = false;
+ let segmentationEdited = node.properties?.[LENGTH_PROPERTIES.single] === true || Object.hasOwn(node.properties || {}, LENGTH_PROPERTIES.block);
+ let plan = null, error = null, absent = false, disposed = false, pending = null, edited = false, blockEdited = false;
+ const remember = (key, value) => { node.properties ||= {}; node.properties[key] = value; node.graph?.change(); node.setDirtyCanvas?.(true, true); };
+ const total = () => Number(seconds.value);
+ const effectiveSingle = () => node.properties?.[LENGTH_PROPERTIES.single] === true && total() <= (planLimits?.singleMaximum ?? 15);
+ function options() {
+ // Pin short fallback plans that would otherwise qualify for a single run.
+ return {seconds: total(), single: effectiveSingle(), singleLimit: planLimits ? effectiveSingle() ? planLimits.singleMaximum : planLimits.maximum : null,
+ maxFrames: planLimits?.maxFrames ?? null,
+ blockSeconds: blockEdited || Object.hasOwn(node.properties || {}, LENGTH_PROPERTIES.block) ? Number(block.value)
+ : !planLimits && total() > 15 && total() <= 30 ? defaultBlockSeconds(null) : null};
+ }
+ function paint() {
+ const maximum = planLimits?.maximum, forcedMaximum = planLimits?.singleMaximum;
+ const clamped = positive(maximum) && node.properties?.[LENGTH_PROPERTIES.block] > maximum;
+ const cannot = total() > (forcedMaximum ?? 15);
+ single.disabled = absent || seconds.disabled || cannot; single.checked = !absent && effectiveSingle();
+ if (absent) seconds.max = '60';
+ unavailable.hidden = absent || !planLimits || (!cannot && !clamped);
+ unavailable.textContent = planLimits ? t(`Up to ${Math.floor(clamped ? maximum : forcedMaximum)} s in one run at this size.`, `当前画面大小单次最长 ${Math.floor(clamped ? maximum : forcedMaximum)} 秒。`) : '';
+ if (positive(maximum)) block.max = String(maximum); else block.removeAttribute('max');
+ if (!edited) block.value = Math.min(node.properties?.[LENGTH_PROPERTIES.block] || defaultBlockSeconds(maximum), maximum || Infinity);
+ block.disabled = absent || seconds.disabled || effectiveSingle() || (positive(maximum) && maximum < 5); controls.hidden = absent;
+ reset.hidden = !Object.hasOwn(node.properties || {}, LENGTH_PROPERTIES.block); reset.disabled = block.disabled;
+ note.hidden = absent || !error;
+ note.textContent = error ? errorMessage(error) : '';
+ }
+ function errorMessage(kind) {
+ return {single_unavailable: t('This length is beyond a single run.', '这个长度超出了单次能生成的范围。'),
+ continuation_unavailable: t('Choose a smaller picture size to make a longer video.', '如需生成更长的视频,请选择更小的画面大小。'),
+ too_long: t('This video is too long. Choose a shorter duration.', '这条视频太长,请缩短时长。'),
+ other: t('Could not plan this video. Try again.', '暂时无法安排这条视频的分段,请重试。')}[kind];
+ }
+ function invalidate() {
+ revision++; plan = null; error = null; clearTimeout(timer); timer = null; request?.abort(); request = null; pending = null;
+ paint(); onChange();
+ }
+ async function calculate(version = revision) {
+ if (disposed || absent || !seconds.checkValidity() || (!block.disabled && !block.checkValidity())) return null;
+ if (!effectiveSingle() && total() <= singleLimitSeconds(planLimits?.maximum) && !edited
+ && !Object.hasOwn(node.properties || {}, LENGTH_PROPERTIES.block)) return null;
+ const controller = new AbortController(); request = controller;
+ try {
+ const response = await api.fetchApi('/freevideo/chain/plan', {method: 'POST', headers: {'Content-Type': 'application/json'},
+ body: JSON.stringify(buildPlanRequest(options())), signal: controller.signal});
+ const reply = response.status === 404 ? null : await response.json();
+ if (disposed || controller.signal.aborted || version !== revision) return null;
+ if (response.status === 404) { absent = true; plan = null; error = null; }
+ else if (response.status === 400) error = classifyPlanError(reply);
+ else if (response.ok) { plan = readLengthPlan(reply); if (!plan) error = 'other'; }
+ else error = 'other';
+ } catch { if (!controller.signal.aborted && version === revision) error = 'other'; }
+ if (!disposed && !controller.signal.aborted && version === revision) { paint(); onChange(); }
+ return plan;
+ }
+ function schedule() { const version = revision; timer = setTimeout(() => { timer = null; pending = calculate(version); }, delay); }
+ single.onchange = () => { remember(LENGTH_PROPERTIES.single, single.checked); segmentationEdited = true; edited = true; invalidate(); schedule(); };
+ block.oninput = () => { segmentationEdited = true; edited = blockEdited = true; invalidate(); schedule(); };
+ block.onchange = () => { if (block.reportValidity()) remember(LENGTH_PROPERTIES.block, Number(block.value)); };
+ reset.onclick = () => {
+ delete node.properties[LENGTH_PROPERTIES.block]; node.graph?.change(); submitted = false;
+ segmentationEdited = true; planLimits = limits;
+ edited = blockEdited = false; invalidate(); edited = true; schedule();
+ };
+ const input = () => { submitted = false; if (!segmentationEdited) planLimits = limits; edited = false; invalidate(); schedule(); };
+ seconds.addEventListener('input', input);
+ function commit() {
+ if (!seconds.value || !seconds.reportValidity()) return false;
+ const value = total() > 30 ? Math.round(total()) : total(); seconds.value = value;
+ if (value > 60) remember(LENGTH_PROPERTIES.seconds, value);
+ else if (node.properties && Object.hasOwn(node.properties, LENGTH_PROPERTIES.seconds)) { delete node.properties[LENGTH_PROPERTIES.seconds]; node.graph?.change(); }
+ setSeconds(Math.min(60, value)); invalidate(); schedule(); return true;
+ }
+ paint();
+ return {
+ commit, options, get plan() { return plan; }, get absent() { return absent; },
+ get needsPlan() { return !absent && !effectiveSingle() && (total() > singleLimitSeconds(planLimits?.maximum)
+ || Object.hasOwn(node.properties || {}, LENGTH_PROPERTIES.block)); },
+ get estimate() { return limits?.estimate || null; },
+ get capabilityState() { return capabilityState; }, get estimating() { return waiting; },
+ get blocked() { return !absent && Boolean(error); }, get message() { return error ? errorMessage(error) : ''; },
+ fallback() { absent = true; invalidate(); },
+ freeze() { submitted = true; },
+ async ready() {
+ while (!disposed) {
+ const version = revision; clearTimeout(timer); timer = null;
+ if (pending) await pending;
+ if (version !== revision) continue;
+ if (!plan && !absent) pending = calculate();
+ if (pending) await pending;
+ if (version === revision) return plan;
+ }
+ return null;
+ },
+ refresh(next, force = false) {
+ const key = JSON.stringify(next); if ((!force && key === contextKey) || disposed) return;
+ contextKey = key; limits = planLimits = null; edited = blockEdited = false; submitted = false;
+ capabilityState = 'pending'; waiting = false;
+ clearTimeout(waitingTimer); clearTimeout(timeoutTimer); invalidate(); schedule();
+ capabilityRequest?.abort(); capabilityRequest = new AbortController();
+ const controller = capabilityRequest, version = ++capabilityRevision;
+ const settle = value => {
+ if (disposed || controller.signal.aborted || version !== capabilityRevision) return;
+ clearTimeout(waitingTimer); clearTimeout(timeoutTimer); waiting = false;
+ limits = value; capabilityState = value ? 'ready' : 'unavailable';
+ if (value && !segmentationEdited && !submitted) { planLimits = value; invalidate(); schedule(); }
+ else { paint(); onChange(); }
+ };
+ timeoutTimer = setTimeout(() => { settle(null); controller.abort(); }, capabilityTimeout);
+ let replied = false;
+ const onReply = () => {
+ if (disposed || controller.signal.aborted || version !== capabilityRevision) return;
+ replied = true; clearTimeout(waitingTimer);
+ };
+ let reading;
+ try { reading = capability(api, next, controller.signal, onReply); }
+ catch { settle(null); return; }
+ if (!replied) waitingTimer = setTimeout(() => { waiting = true; onChange(); }, 350);
+ (async () => {
+ try { settle(await reading); }
+ catch { settle(null); }
+ })();
+ },
+ dispose() { disposed = true; clearTimeout(timer); clearTimeout(waitingTimer); clearTimeout(timeoutTimer); request?.abort(); capabilityRequest?.abort(); seconds.removeEventListener('input', input); },
+ };
+}