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.

Cast mention: type @ in the prompt to bring a character's pictures in as references

Bowen Xueb86f757d10d1
diff --git a/freevideo_engine/agent/drama.py b/freevideo_engine/agent/drama.py
index 0ec7e13..877c5d1 100644
--- a/freevideo_engine/agent/drama.py
+++ b/freevideo_engine/agent/drama.py
@@ -265,7 +265,9 @@ def prompt(play, shot):
def subject_definitions(subjects):
"""The prompt prefix tying cast cards to their reference tags; the one place its wording lives.
- subjects: [{'name', 'description', 'pictures': (first, last) or None, 'audio': number or None}]."""
+ subjects: [{'name', 'description', 'pictures': (first, last), a list of such pairs, or None, 'audio': number or None}].
+ The page writes the same prompt from the same wording (web/cast_mention.js); tests/fixtures/subject_definitions.json
+ holds the cases both sides must reproduce exactly."""
parts = []
for number, subject in enumerate(subjects, 1):
text = '<Subject %d> is %s' % (number, subject['name'])
@@ -273,9 +275,12 @@ def subject_definitions(subjects):
text += (': %s.' % description) if description else '.'
tags = []
if subject.get('pictures'):
- first, last = subject['pictures']
- pictures = '<Picture %d>' % first if first == last else '<Picture %d> to <Picture %d>' % (first, last)
- tags.append('%s show%s its appearance' % (pictures, 's' if first == last else ''))
+ # One (first, last) pair, or several when the person's pictures are not side by side.
+ ranges = [subject['pictures']] if isinstance(subject['pictures'][0], int) else subject['pictures']
+ pictures = ', '.join('<Picture %d>' % a if a == b else '<Picture %d> to <Picture %d>' % (a, b)
+ for a, b in ranges)
+ single = len(ranges) == 1 and ranges[0][0] == ranges[0][1]
+ tags.append('%s show%s its appearance' % (pictures, 's' if single else ''))
if subject.get('audio'):
tags.append('<Audio %d> is its voice' % subject['audio'])
if tags:
diff --git a/scripts/test_freevideo_entry.mjs b/scripts/test_freevideo_entry.mjs
index 0d0003d..f6eeaaa 100644
--- a/scripts/test_freevideo_entry.mjs
+++ b/scripts/test_freevideo_entry.mjs
@@ -3,7 +3,8 @@ import {readFile} from 'node:fs/promises';
import test from 'node:test';
import {outputDownloadURL} from '../web/output_download.js';
import {regenerateResult, upscaleResult, createSecondPassQueue} from '../web/studio_queue.js';
-import {referenceInputs} from '../web/prompt_references.js';
+import {referenceInputs, mediaRows} from '../web/prompt_references.js';
+import {expandCast} from '../web/cast_mention.js';
import {cleanOptionalPrompt, cleanOptionalWidgets} from '../web/optional_inputs.js';
class Element {
@@ -37,7 +38,7 @@ test('main browser entry registers both views and preserves node hooks', async t
const document = {head: new Element('head'), createElement: tag => new Element(tag),
createRange: () => ({createContextualFragment: () => new Element('span')})};
const dependencies = {
- app, api, outputDownloadURL, regenerateResult, upscaleResult, createSecondPassQueue, referenceInputs, cleanOptionalPrompt, cleanOptionalWidgets,
+ app, api, outputDownloadURL, regenerateResult, upscaleResult, createSecondPassQueue, referenceInputs, mediaRows, expandCast, cleanOptionalPrompt, cleanOptionalWidgets,
createCastLibrary: options => {
const cast = {element: new Element('cast'), options, destroyed: false, destroy() { this.destroyed = true; }};
casts.push(cast); return cast;
@@ -97,7 +98,8 @@ test('main browser entry registers both views and preserves node hooks', async t
.replace("import { notifyCompatibility } from './compatibility.js';", 'const {notifyCompatibility} = globalThis.__freevideoEntryTest;')
.replace("import { startUpdateChecks } from './updates.js';", 'const {startUpdateChecks} = globalThis.__freevideoEntryTest;')
.replace("import { startDoneNotify, askDesktopPermission, DESKTOP_SETTING } from './done_notify.js';", 'const {startDoneNotify,askDesktopPermission} = globalThis.__freevideoEntryTest; const DESKTOP_SETTING = "FreeVideo.DoneNotify.Desktop";')
- .replace("import { attachReferencePicker, referenceItems, syncReferencePrompt, referenceInputs } from './prompt_references.js';", 'const {attachReferencePicker,referenceItems,syncReferencePrompt,referenceInputs} = globalThis.__freevideoEntryTest;')
+ .replace("import { attachReferencePicker, referenceItems, syncReferencePrompt, referenceInputs, mediaRows } from './prompt_references.js';", 'const {attachReferencePicker,referenceItems,syncReferencePrompt,referenceInputs,mediaRows} = globalThis.__freevideoEntryTest;')
+ .replace("import { expandCast } from './cast_mention.js';", 'const {expandCast} = globalThis.__freevideoEntryTest;')
.replace("import { outputDownloadURL } from './output_download.js';", 'const {outputDownloadURL} = globalThis.__freevideoEntryTest;')
.replace("import { shareButton } from './share.js';", 'const {shareButton} = globalThis.__freevideoEntryTest;')
.replace("import { reportFileName } from './report_issue.js';", 'const {reportFileName} = globalThis.__freevideoEntryTest;')
diff --git a/web/cast_mention.js b/web/cast_mention.js
new file mode 100644
index 0000000..a402bb4
--- /dev/null
+++ b/web/cast_mention.js
@@ -0,0 +1,145 @@
+// @-mentions of library characters in the prompt box.
+// While editing, the text keeps the character's name ("@Su Wan"); the character's pictures are ordinary reference rows
+// of the media list that carry `cast: {id, name, description}`. When a request is made the names become <Subject N>
+// and the subject definitions go in front, the same wording the Agent's drama planner writes (agent/drama.py).
+export const MAX_PEOPLE = 3;
+export const MAX_PICTURES_EACH = 6;
+export const MAX_REFERENCES = 32;
+// Which of a card's pictures come first; the others follow in the card's own order.
+export const PICTURE_ORDER = ['sheet', 'front', 'three_quarter', 'face'];
+
+// subjects: [{name, description, pictures: [first, last] | null, audio: number | null}]. This is the one JS place for
+// the wording; its Python twin is subject_definitions() and tests/fixtures/subject_definitions.json holds the cases
+// both sides must reproduce character for character.
+export function subjectDefinitions(subjects) {
+ const parts = subjects.map((subject, index) => {
+ let text = `<Subject ${index + 1}> is ${subject.name}`;
+ const description = String(subject.description || '').trim().replace(/\.+$/, '');
+ text += description ? `: ${description}.` : '.';
+ const tags = [];
+ if (subject.pictures) {
+ // One [first, last] pair, or several when the person's pictures are not side by side.
+ const ranges = typeof subject.pictures[0] === 'number' ? [subject.pictures] : subject.pictures;
+ const pictures = ranges.map(([a, b]) => a === b ? `<Picture ${a}>` : `<Picture ${a}> to <Picture ${b}>`).join(', ');
+ const single = ranges.length === 1 && ranges[0][0] === ranges[0][1];
+ tags.push(`${pictures} show${single ? 's' : ''} its appearance`);
+ }
+ if (subject.audio) tags.push(`<Audio ${subject.audio}> is its voice`);
+ if (tags.length) text += ' ' + tags.join('; ') + '.';
+ return text;
+ });
+ return 'subject_definitions: ' + parts.join(' ');
+}
+
+const IMAGE = /\.(png|jpe?g|webp|bmp|tiff?)$/i;
+const enabled = row => row && row.enabled !== false;
+// The number H3 gives each reference picture: images in list order (connected inputs come after the list).
+function pictureNumbers(rows) {
+ const numbers = new Map();
+ let count = 0;
+ rows.forEach((row, index) => {
+ if (enabled(row) && row.role === 'reference' && IMAGE.test(row.file || '')) numbers.set(index, ++count);
+ });
+ return numbers;
+}
+
+// The characters present in the media list, in list order, with the rows that carry each one's pictures.
+export function castInRows(rows) {
+ const people = new Map();
+ (Array.isArray(rows) ? rows : []).forEach((row, index) => {
+ if (!enabled(row) || !row.cast?.id || row.role !== 'reference' || !IMAGE.test(row.file || '')) return;
+ const person = people.get(row.cast.id) || {id: row.cast.id, name: row.cast.name || '', description: row.cast.description || '', rows: []};
+ person.rows.push(index); people.set(row.cast.id, person);
+ });
+ return [...people.values()];
+}
+
+// Ids of the characters present in the media list and written in the text, in list order.
+export function mentionedIds(text, rows) {
+ const people = castInRows(rows), names = new Set(mentionRanges(String(text ?? ''), people).map(range => range.name));
+ return people.filter(person => names.has(person.name)).map(person => person.id);
+}
+
+const escape = text => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+// Where `@name` of a present character stands in the text; longer names win, an @ right after a word or an address is not
+// a mention (the same rule as the @ list's).
+export function mentionRanges(text, people) {
+ const names = [...new Set(people.map(person => person.name).filter(Boolean))].sort((a, b) => b.length - a.length);
+ if (!names.length || !text.includes('@')) return [];
+ // A name written in Latin letters does not end in the middle of a longer word ("@Su Wanda" is not "@Su Wan").
+ const whole = name => escape(name) + (/[A-Za-z0-9_]$/.test(name) ? '(?![A-Za-z0-9_])' : '');
+ const pattern = new RegExp('(^|[^\\w.%+\\-])@(' + names.map(whole).join('|') + ')', 'gu');
+ const ranges = [];
+ for (const match of text.matchAll(pattern)) {
+ const start = match.index + match[1].length;
+ ranges.push({start, end: start + 1 + match[2].length, name: match[2]});
+ }
+ return ranges;
+}
+
+// The prompt a request carries. Characters mentioned in the text are numbered in order of first mention; one whose
+// pictures are gone is written as a plain name. `active: false` (first/last frames, a continued video) leaves every
+// name plain too, since pictures of people cannot go with those.
+export function expandCast(text, rows, {active = true} = {}) {
+ text = String(text ?? '');
+ const list = Array.isArray(rows) ? rows : [];
+ const people = castInRows(list);
+ const ranges = mentionRanges(text, people);
+ if (!ranges.length) return {text, subjects: []};
+ if (list.some(row => enabled(row) && (row.role === 'first' || row.role === 'last'))) active = false;
+ const numbers = pictureNumbers(list);
+ const order = [];
+ let result = '', at = 0;
+ for (const range of ranges) {
+ result += text.slice(at, range.start); at = range.end;
+ const person = people.find(p => p.name === range.name);
+ if (!active || !person) { result += range.name; continue; }
+ let number = order.indexOf(person) + 1;
+ if (!number) {
+ if (order.length >= MAX_PEOPLE) { result += range.name; continue; }
+ order.push(person); number = order.length;
+ }
+ result += `<Subject ${number}>`;
+ }
+ result += text.slice(at);
+ if (!order.length) return {text: result, subjects: []};
+ const subjects = order.map(person => {
+ // Consecutive picture numbers make one range; a person whose pictures are apart gets several.
+ const ranges = [];
+ for (const number of person.rows.map(index => numbers.get(index)).sort((a, b) => a - b)) {
+ const last = ranges[ranges.length - 1];
+ if (last && number === last[1] + 1) last[1] = number; else ranges.push([number, number]);
+ }
+ return {name: person.name, description: person.description, pictures: ranges, audio: null};
+ });
+ return {text: subjectDefinitions(subjects) + '\n\n' + result, subjects};
+}
+
+// The pictures of a card to put in the media list: the card's own order after the preferred labels, the first six.
+export function cardPictures(card) {
+ const rank = new Map(PICTURE_ORDER.map((label, index) => [label, index]));
+ return (card?.images || []).map((image, index) => ({image, index}))
+ .filter(({image}) => image?.media?.file && IMAGE.test(image.media.file))
+ .sort((a, b) => (rank.get(a.image.label) ?? PICTURE_ORDER.length) - (rank.get(b.image.label) ?? PICTURE_ORDER.length) || a.index - b.index)
+ .slice(0, MAX_PICTURES_EACH).map(({image}) => image.media.file);
+}
+
+// Whether a character can be mentioned now; `reason` is the one thing in the way.
+// `count` is how many pictures the card would add when only its list row is known.
+export function mentionState(rows, card, count = cardPictures(card).length) {
+ const list = Array.isArray(rows) ? rows : [];
+ const people = castInRows(list);
+ if (people.some(person => person.id === card.id)) return {ok: true, present: true};
+ if (list.some(row => enabled(row) && (row.role === 'first' || row.role === 'last'))) return {ok: false, reason: 'frames'};
+ if (people.length >= MAX_PEOPLE) return {ok: false, reason: 'people'};
+ if (list.filter(enabled).length + count > MAX_REFERENCES) return {ok: false, reason: 'full'};
+ return {ok: true, present: false};
+}
+
+// The media list with the character's pictures appended together, so one range of picture numbers covers them.
+export function withCharacter(rows, card) {
+ const list = Array.isArray(rows) ? rows.map(row => ({...row})) : [];
+ if (castInRows(list).some(person => person.id === card.id)) return list;
+ const cast = {id: card.id, name: card.name, description: card.description || ''};
+ return [...list, ...cardPictures(card).map(file => ({file, role: 'reference', enabled: true, cast}))];
+}
diff --git a/web/cast_overlay.js b/web/cast_overlay.js
new file mode 100644
index 0000000..01cf3c2
--- /dev/null
+++ b/web/cast_overlay.js
@@ -0,0 +1,47 @@
+// Shows @mentions of characters in the accent colour. The textarea keeps the text; while a mention is present a copy of
+// the text (same font, wrapping and scroll) is drawn over it and the textarea's own glyphs are made transparent.
+import {mentionRanges} from './cast_mention.js';
+
+const COPIED = ['fontFamily', 'fontSize', 'fontWeight', 'fontStyle', 'fontVariantLigatures', 'letterSpacing', 'wordSpacing', 'lineHeight',
+ 'textIndent', 'textTransform', 'tabSize', 'paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft', 'direction'];
+
+// `people()` lists the characters present in the media list: [{name}].
+export function attachMentionOverlay(input, {people}) {
+ const mirror = document.createElement('div'), inner = document.createElement('div');
+ mirror.className = 'fv-mention-mirror'; mirror.setAttribute('aria-hidden', 'true'); mirror.hidden = true;
+ mirror.append(inner);
+ input.parentNode.insertBefore(mirror, input.nextSibling);
+ let composing = false, disposed = false;
+ function layout() {
+ const style = getComputedStyle(input);
+ for (const name of COPIED) mirror.style[name] = style[name];
+ Object.assign(mirror.style, {left: `${input.offsetLeft + input.clientLeft}px`, top: `${input.offsetTop + input.clientTop}px`,
+ width: `${input.clientWidth}px`, height: `${input.clientHeight}px`, opacity: input.disabled ? '.5' : ''});
+ inner.style.transform = `translateY(${-input.scrollTop}px)`;
+ }
+ function refresh() {
+ if (disposed) return;
+ const text = input.value, ranges = composing ? [] : mentionRanges(text, people());
+ const live = ranges.length > 0;
+ input.classList.toggle('fv-mention-live', live); mirror.hidden = !live;
+ if (!live) { inner.replaceChildren(); return; }
+ const parts = []; let at = 0;
+ for (const range of ranges) {
+ if (range.start > at) parts.push(document.createTextNode(text.slice(at, range.start)));
+ const name = document.createElement('span'); name.className = 'fv-mention'; name.textContent = text.slice(range.start, range.end);
+ parts.push(name); at = range.end;
+ }
+ parts.push(document.createTextNode(text.slice(at) + (text.endsWith('\n') ? '​' : '')));
+ inner.replaceChildren(...parts);
+ layout();
+ }
+ const listeners = [], listen = (target, name, fn) => { target.addEventListener(name, fn); listeners.push(() => target.removeEventListener(name, fn)); };
+ listen(input, 'input', refresh);
+ listen(input, 'scroll', () => { if (!mirror.hidden) inner.style.transform = `translateY(${-input.scrollTop}px)`; });
+ listen(input, 'compositionstart', () => { composing = true; refresh(); });
+ listen(input, 'compositionend', () => { composing = false; refresh(); });
+ listen(window, 'resize', () => { if (!mirror.hidden) layout(); });
+ const observer = typeof ResizeObserver === 'function' ? new ResizeObserver(() => { if (!mirror.hidden) layout(); }) : null;
+ observer?.observe(input);
+ return {refresh, dispose() { disposed = true; observer?.disconnect(); listeners.forEach(stop => stop()); mirror.remove(); input.classList.remove('fv-mention-live'); }};
+}
diff --git a/web/cast_source.js b/web/cast_source.js
new file mode 100644
index 0000000..5806387
--- /dev/null
+++ b/web/cast_source.js
@@ -0,0 +1,7 @@
+// The character library the @ list reads: the library module's own object, or nothing while that module is absent.
+export async function openCastLibrary(deps) {
+ try {
+ const {createCastLibrary} = await import('./cast_library.js');
+ return createCastLibrary(deps);
+ } catch { return null; }
+}
diff --git a/web/freevideo.js b/web/freevideo.js
index 893ac08..95c77bb 100644
--- a/web/freevideo.js
+++ b/web/freevideo.js
@@ -10,7 +10,8 @@ import { startUpdateChecks } from './updates.js';
import { startDoneNotify, askDesktopPermission, DESKTOP_SETTING } from './done_notify.js';
import { installNavigation, refreshNavigation, preferredView } from './view_navigation.js';
import { agentInterfaceEnabled } from './agent_connect.js';
-import { attachReferencePicker, referenceItems, syncReferencePrompt, referenceInputs } from './prompt_references.js';
+import { attachReferencePicker, referenceItems, syncReferencePrompt, referenceInputs, mediaRows } from './prompt_references.js';
+import { expandCast } from './cast_mention.js';
import { outputDownloadURL } from './output_download.js';
import { shareButton } from './share.js';
import { reportFileName } from './report_issue.js';
@@ -265,7 +266,7 @@ function mediaPanel(node, mount = null) {
const top = el("div", undefined, "fv-row");
const enabled = el("input"); enabled.type = "checkbox"; enabled.checked = row.enabled !== false;
enabled.setAttribute("aria-label", text("Use media", "使用素材")); enabled.onchange = () => { rows[index].enabled = enabled.checked; update(rows); };
- const label = el("span", (row.source || row.file).split("/").pop(), "fv-file"); label.title = row.file;
+ const label = el("span", row.cast?.name || (row.source || row.file).split("/").pop(), "fv-file"); label.title = row.file;
const select = el("select"); select.setAttribute("aria-label", text("Media role", "素材用途"));
const kind = mediaKind(row.file);
for (const [value, title] of (kind === "image" ? [["reference", text("Reference", "参考")], ["first", text("First frame", "首帧")], ["last", text("Last frame", "尾帧")]] : [["reference", text("Reference", "参考")]])) {
@@ -678,6 +679,9 @@ app.registerExtension({
force.type = 'hidden'; force.computeSize = () => [0, -4]; force.draw = () => {};
force.value = false; force.serializeValue = () => false;
}
+ // Characters mentioned with @ travel as <Subject N> plus their definitions; the draft keeps the typed names.
+ const prompt = this.widgets?.find(w => w.name === 'text');
+ if (prompt) { const owner = this; prompt.serializeValue = () => expandCast(prompt.value, mediaRows(owner), {active: !owner.freevideoCastOff?.()}).text; }
const quality = this.widgets?.find(w => w.name === 'two_pass');
if (quality) {
quality.label = text('Two-pass acceleration', '二次采样加速');
diff --git a/web/health.js b/web/health.js
index af36a9d..82f1a2f 100644
--- a/web/health.js
+++ b/web/health.js
@@ -13,7 +13,7 @@ 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', 'autopilot.js', 'autopilot_chat.js', 'autopilot_conversations.js', 'browser_extension.js', 'caret_rect.js', 'chain_support.js', 'capability_view.js', 'cast_generate.js', 'compatibility.js', 'error_panel.js', 'first_run_guide.js', 'fonts.js', 'freevideo.js', 'generation_progress.js',
+export const MODULES = ['agent_activity.js', 'agent_connect.js', 'agent_session.js', 'autopilot.js', 'autopilot_chat.js', 'autopilot_conversations.js', 'browser_extension.js', 'caret_rect.js', 'chain_support.js', 'capability_view.js', 'cast_generate.js', 'cast_mention.js', 'cast_overlay.js', 'cast_source.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_media_references.js', 'editor_references.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_failure.js', 'editor_header_fit.js',
'editor_loader.js', 'editor_text_coverage.js', 'editor_text.js', 'editor_toolbar_more.js', 'editor_text_model.js', 'editor_text_layout.js', 'editor_notes.js', 'editor_icons.js', 'dialog_keys.js', 'done_notify.js', 'frame_sizes.js', 'health.js', 'image_commands.js', 'image_editor.js', 'image_editor_engine.js', 'image_generation.js', 'launcher.js', 'length_plan.js', 'lora_triggers.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', 'prompt_terms.js', 'report_issue.js', 'studio_recent.js',
diff --git a/web/prompt_enhance.js b/web/prompt_enhance.js
index 1af8c72..28d2168 100644
--- a/web/prompt_enhance.js
+++ b/web/prompt_enhance.js
@@ -64,7 +64,8 @@ export function promptPrestart(api, nodeId, enabled, alive = () => true) {
// An empty box is never rewritten, the untouched starter prompt included:
// enhancement waits for the user's own scene.
-export function createPromptEnhancer({node, input, editor, api, context, setText, t, starter = '', onReport = () => {}, onChange = () => {}}) {
+// `prepare` turns the user's text into what the model reads (character mentions written out with their pictures).
+export function createPromptEnhancer({node, input, editor, api, context, setText, t, starter = '', prepare = text => text, onReport = () => {}, onChange = () => {}}) {
const saved = node.properties?.freevideo_prompt_versions;
// Drafts saved before the starter became a placeholder hold it as the original.
const versions = new PromptVersions(starter && saved?.original === starter ? {...saved, original: ''} : saved, input.value);
@@ -248,7 +249,7 @@ export function createPromptEnhancer({node, input, editor, api, context, setText
}
await poll('install', {accept_download: true});
}
- const result = await poll('rewrite', {text: original, ...scene});
+ const result = await poll('rewrite', {text: prepare(original), ...scene});
if (disposed || cancelling) throw new Error('cancelled');
if (edits !== versions.value.edits || !versions.accept(key, context(), result.text)) throw new Error('stale');
apply(); show('');
diff --git a/web/prompt_references.css b/web/prompt_references.css
index 476afa4..332485e 100644
--- a/web/prompt_references.css
+++ b/web/prompt_references.css
@@ -13,3 +13,14 @@
.fv-term-picker .fv-reference-options{max-height:220px}
.fv-term-option{min-height:34px;padding:5px 10px}
.fv-term-option strong{flex:none;font-size:13px}
+
+.fv-reference-group{padding:6px 8px 3px;font-size:11px;color:var(--fv-muted,#a9b3c4)}
+.fv-reference-person{min-height:36px;padding:5px 8px;gap:10px}
+.fv-reference-face{width:24px;height:24px;flex:none;border-radius:50%;object-fit:cover;background:var(--fv-raised,#252e39)}
+.fv-reference-person strong{font-size:13px;font-weight:550;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
+.fv-reference-person[aria-disabled=true]{opacity:.5;cursor:not-allowed}
+.fv-prompt-editor{position:relative}
+.fv-mention-mirror{position:absolute;box-sizing:border-box;overflow:hidden;pointer-events:none;white-space:pre-wrap;overflow-wrap:break-word;word-break:normal;color:var(--fv-ink,#eee);z-index:1}
+.fv-mention-mirror[hidden]{display:none}
+.fv-mention{color:var(--fv-accent,#6cb4ff)}
+.fv-studio textarea.fv-mention-live{color:transparent;caret-color:var(--fv-ink,#eee)}
diff --git a/web/prompt_references.js b/web/prompt_references.js
index 3dfb0ac..7cbd307 100644
--- a/web/prompt_references.js
+++ b/web/prompt_references.js
@@ -12,6 +12,11 @@ export function referenceKind(file) {
: ['wav','mp3','flac','ogg','m4a','aac','opus'].includes(ext) ? 'audio' : null;
}
+// The raw media list a generate node reads, [] when there is none or it cannot be read.
+export function mediaRows(node) {
+ try { const rows = JSON.parse(widget(sourceFor(node, 'media'), 'assets')?.value || '[]'); return Array.isArray(rows) ? rows : []; } catch { return []; }
+}
+
export function referenceItems(node) {
if (linkFor(node, 'conditioning')) return [];
const refs = [], anchors = {}, seen = new Set();
@@ -33,7 +38,7 @@ export function referenceItems(node) {
const kind = referenceKind(row.file);
if (!kind) throw new Error('invalid_media');
const item = {key: `file:${media.id}:${row.file}:${occurrence}`, kind, file: row.file,
- name: row.file.split('/').pop(), assetIndex: rows.indexOf(row)};
+ name: row.cast?.name || row.file.split('/').pop(), assetIndex: rows.indexOf(row)};
if (row.role === 'reference') refs.push(item);
else if (kind === 'image' && ['first','last'].includes(row.role) && !anchors[row.role]) anchors[row.role] = item;
else throw new Error('invalid_media');
@@ -97,7 +102,9 @@ export function mentionAt(text, start, end = start) {
}
let serial = 0;
-export function attachReferencePicker(input, {items, t = en => en, view, host, addMedia} = {}) {
+// `characters()` lists library characters for the same popup: [{id, name, thumb, blocked}], `blocked` being the reason
+// one cannot be used now; `onCharacter(character)` puts its pictures in the media list and may return false to refuse.
+export function attachReferencePicker(input, {items, t = en => en, view, host, addMedia, characters = () => [], onCharacter = () => true} = {}) {
if (!document.querySelector('link[data-freevideo-references]')) {
const css = document.createElement('link'); css.rel = 'stylesheet';
css.dataset.freevideoReferences = ''; css.href = new URL('./prompt_references.css', import.meta.url).href;
@@ -129,11 +136,21 @@ export function attachReferencePicker(input, {items, t = en => en, view, host, a
const line = caretRect(input);
popup.style.top = `${Math.max(12, line.bottom + height + 8 < innerHeight ? line.bottom + 4 : line.top - height - 4)}px`;
}
+ const usable = index => Boolean(matches[index]) && !matches[index].character?.blocked;
+ // The next row a key can land on, skipping blocked characters; -1 when every row is blocked.
+ function step(from, direction) {
+ for (let i = 1; i <= matches.length; i++) {
+ const index = (from + direction * i + matches.length * 2) % matches.length;
+ if (usable(index)) return index;
+ }
+ return -1;
+ }
function select(index) {
active = index;
- for (const [i, option] of [...list.children].entries()) option.setAttribute('aria-selected', String(i === active));
- const selected = list.children[active];
- if (selected && matches.length) {
+ const options = list.querySelectorAll('[role=option]');
+ for (const [i, option] of [...options].entries()) option.setAttribute('aria-selected', String(i === active));
+ const selected = options[active];
+ if (selected && matches.length && usable(active)) {
input.setAttribute('aria-activedescendant', selected.id);
if (selected.offsetTop < list.scrollTop) list.scrollTop = selected.offsetTop;
else if (selected.offsetTop + selected.offsetHeight > list.scrollTop + list.clientHeight)
@@ -151,6 +168,11 @@ export function attachReferencePicker(input, {items, t = en => en, view, host, a
function choose(index) {
if (!range || !matches[index]) return;
const item = matches[index], selection = range;
+ if (item.character) {
+ if (item.character.blocked || onCharacter(item.character) === false) return;
+ close(); insert('@' + item.character.name + (/^\s/.test(input.value.slice(selection.end)) ? '' : ' '), selection.start, selection.end); close();
+ return;
+ }
close(); insert(item.token + (/^\s/.test(input.value.slice(selection.end)) ? '' : ' '), selection.start, selection.end); close();
}
function refresh() {
@@ -159,22 +181,39 @@ export function attachReferencePicker(input, {items, t = en => en, view, host, a
if (!range) { close(); return; }
let available = [], invalid = false;
try { available = items(); } catch { invalid = true; }
- matches = available.filter(item => `${item.name} ${item.token} ${t(item.kind, {image:'图片',video:'视频',audio:'音频'}[item.kind])} ${item.number}`.toLowerCase().includes(range.query));
+ const media = available.filter(item => `${item.name} ${item.token} ${t(item.kind, {image:'图片',video:'视频',audio:'音频'}[item.kind])} ${item.number}`.toLowerCase().includes(range.query));
+ let everyone = [];
+ try { everyone = characters(); } catch {}
+ const people = everyone.filter(person => person.name.toLowerCase().includes(range.query));
+ matches = [...people.map(character => ({character})), ...media];
list.replaceChildren();
if (!matches.length) {
const empty = document.createElement('div'); empty.className = 'fv-reference-empty';
empty.textContent = invalid ? t('Check your media selection.', '请检查素材用途是否冲突。')
- : available.length ? t('No matching references', '没有匹配的素材') : t('Add reference media to use @', '添加参考素材后即可使用 @');
+ : available.length || everyone.length ? t('No matching references', '没有匹配的素材') : t('Add reference media to use @', '添加参考素材后即可使用 @');
list.append(empty);
- if (!available.length && !invalid && addMedia) {
+ if (!available.length && !everyone.length && !invalid && addMedia) {
const add = document.createElement('button'); add.type = 'button'; add.textContent = t('Add media', '添加素材');
add.onpointerdown = e => e.preventDefault();
add.onclick = () => { close(); addMedia(); }; list.append(add);
}
}
+ const heading = (en, zh) => { const h = document.createElement('div'); h.className = 'fv-reference-group'; h.setAttribute('role', 'presentation'); h.textContent = t(en, zh); list.append(h); };
+ if (people.length) heading('Characters', '角色');
for (const [index, item] of matches.entries()) {
+ if (index === people.length && people.length && media.length) heading('Media', '素材');
const option = document.createElement('div'); option.id = `${list.id}-${index}`;
option.className = 'fv-reference-option'; option.setAttribute('role', 'option');
+ if (item.character) {
+ const person = item.character, face = document.createElement('img');
+ face.className = 'fv-reference-face'; face.alt = ''; face.src = person.thumb || '';
+ const name = document.createElement('strong'); name.textContent = person.name;
+ option.className += ' fv-reference-person'; option.append(face, name);
+ if (person.blocked) { option.setAttribute('aria-disabled', 'true'); option.title = person.blocked; }
+ option.onpointerdown = e => e.preventDefault(); option.onclick = () => choose(index);
+ option.onpointermove = () => { if (usable(index)) select(index); }; list.append(option);
+ continue;
+ }
const thumb = document.createElement(item.file && item.kind === 'image' ? 'img' : 'span');
thumb.className = 'fv-reference-thumb';
if (thumb.tagName === 'IMG') { thumb.src = view(item.file); thumb.alt = ''; }
@@ -189,7 +228,7 @@ export function attachReferencePicker(input, {items, t = en => en, view, host, a
}
const wasHidden = popup.hidden; popup.hidden = false;
if (wasHidden && popup.showPopover) popup.showPopover();
- input.setAttribute('aria-expanded', 'true'); active = 0; select(active); place();
+ input.setAttribute('aria-expanded', 'true'); select(usable(0) ? 0 : step(0, 1)); place();
}
listen(input, 'input', refresh); listen(input, 'click', refresh);
listen(input, 'compositionstart', () => { composing = true; close(); });
@@ -197,9 +236,9 @@ export function attachReferencePicker(input, {items, t = en => en, view, host, a
listen(input, 'keydown', e => {
if (composing || e.isComposing || e.keyCode === 229 || popup.hidden || e.ctrlKey || e.metaKey || e.altKey) return;
if (['ArrowDown','ArrowUp'].includes(e.key) && matches.length) {
- e.preventDefault(); e.stopPropagation(); select((active + (e.key === 'ArrowDown' ? 1 : -1) + matches.length) % matches.length);
+ e.preventDefault(); e.stopPropagation(); select(step(active < 0 ? 0 : active, e.key === 'ArrowDown' ? 1 : -1));
} else if ((e.key === 'Enter' || e.key === 'Tab') && !e.shiftKey && matches.length) {
- e.preventDefault(); e.stopPropagation(); choose(active);
+ e.preventDefault(); e.stopPropagation(); if (usable(active)) choose(active);
} else if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); close(); }
});
listen(input, 'keyup', e => { if (['ArrowLeft','ArrowRight','Home','End'].includes(e.key)) refresh(); });
diff --git a/web/studio.js b/web/studio.js
index e6533e8..f3405c4 100644
--- a/web/studio.js
+++ b/web/studio.js
@@ -17,8 +17,11 @@ import { openLibrary } from './library.js';
import { createRecentVideos } from './studio_recent.js';
import { createAgentActivity } from './agent_activity.js';
import { createStudioQueue, randomSeed } from './studio_queue.js';
-import { attachReferencePicker, referenceItems, syncReferencePrompt, referenceInputs, mentionAt } from './prompt_references.js';
+import { attachReferencePicker, referenceItems, syncReferencePrompt, referenceInputs, mentionAt, mediaRows } from './prompt_references.js';
import { attachTermSuggest } from './prompt_terms.js';
+import { castInRows, expandCast, mentionState, mentionedIds, withCharacter, MAX_PICTURES_EACH } from './cast_mention.js';
+import { attachMentionOverlay } from './cast_overlay.js';
+import { openCastLibrary } from './cast_source.js';
import { reconcileLoraTriggers } from './lora_triggers.js';
import { createSamplingEffort } from './sampling_effort.js';
import { resultActions, previewBadge, icon } from './result_actions.js';
@@ -497,7 +500,46 @@ export function openStudio(node, {extendFrom = null} = {}) {
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);
+ // Library characters offered in the @ list; a mention puts the character's pictures in the media list.
+ let castLibrary = null;
+ const castAssets = () => { const owner = upstream(node, 'media'); const field = owner && widget(owner, 'assets'); return field ? {owner, field} : null; };
+ // The library's own upload of a picture goes to the same streaming upload the media panel uses.
+ const castUpload = async file => {
+ const body = new FormData(); body.append('file', file);
+ const response = await api.fetchApi('/freevideo/media/upload', {method: 'POST', body});
+ const result = await response.json(); if (!response.ok) throw new Error(result.error || response.statusText);
+ return result;
+ };
+ const castBlocked = reason => ({frames: t('Not available with first and last frames', '首尾帧不能和角色同时使用'),
+ people: t('Up to 3 characters', '最多 3 个角色'), full: t('Up to 32 references', '参考素材最多 32 个'),
+ extend: t('Not available when continuing a video', '接着生成时不能使用角色')}[reason] || '');
+ function castChoices() {
+ if (!castLibrary || linked(node, 'text') || !castAssets()) return [];
+ const rows = mediaRows(node);
+ return castLibrary.list().filter(card => card.name).map(card => {
+ const state = extension.source ? {ok: false, reason: 'extend'}
+ : mentionState(rows, card, Math.min(MAX_PICTURES_EACH, Number(card.images) || 0));
+ return {id: card.id, name: card.name, thumb: card.thumbnail?.file ? view(card.thumbnail.file) : card.thumbnail?.url || '',
+ blocked: state.ok ? '' : castBlocked(state.reason)};
+ });
+ }
+ // The name goes into the text at once; the card's pictures follow when the full card has been read.
+ function mentionCharacter(person) {
+ if (!castLibrary || extension.source) return false;
+ if (castInRows(mediaRows(node)).some(entry => entry.id === person.id)) return true;
+ if (!mentionState(mediaRows(node), {id: person.id}, 1).ok) return false;
+ castLibrary.get(person.id).then(card => {
+ if (disposed) return;
+ const rows = mediaRows(node), target = castAssets();
+ if (!target || !mentionState(rows, card).ok) return;
+ target.field.value = JSON.stringify(withCharacter(rows, card));
+ target.owner.graph?.change?.();
+ window.dispatchEvent(new CustomEvent('freevideo-media', {detail: target.owner.id}));
+ }).catch(() => { if (!disposed) { status.dataset.error = 'true'; status.textContent = t('Could not add the character\'s pictures', '无法加入角色的图片'); } });
+ return true;
+ }
const references = attachReferencePicker(prompt, {items: () => referenceItems(node), t, view, host: dialog,
+ characters: castChoices, onCharacter: mentionCharacter,
addMedia: () => { mediaDetails.open = true; mediaDetails.scrollIntoView({block: 'nearest', behavior: 'smooth'}); mediaMount.querySelector('button')?.focus(); }});
const mention = button('@', () => references.open(), 'fv-reference-trigger');
mention.setAttribute('aria-label', t('Reference media (@)', '引用素材(@)'));
@@ -506,7 +548,22 @@ export function openStudio(node, {extendFrom = null} = {}) {
cleanup.push(() => references.dispose());
const terms = attachTermSuggest(prompt, {t, host: dialog, suppressed: () => !!mentionAt(prompt.value, prompt.selectionStart, prompt.selectionEnd)});
cleanup.push(() => terms.dispose());
+ const castOverlay = attachMentionOverlay(prompt, {people: () => castInRows(mediaRows(node))});
+ // The library's entry row rings the characters this prompt uses.
+ let castShown = '';
+ const announceCast = () => {
+ const ids = mentionedIds(prompt.value, mediaRows(node));
+ if (ids.join() !== castShown) { castShown = ids.join(); window.dispatchEvent(new CustomEvent('freevideo-cast-mentioned', {detail: ids})); }
+ };
+ prompt.addEventListener('input', announceCast);
+ const castChanged = event => { if (String(event.detail) === String(mediaNode?.id)) { castOverlay.refresh(); references.refresh(); announceCast(); } };
+ window.addEventListener('freevideo-media', castChanged);
+ node.freevideoCastOff = () => Boolean(extension.source);
+ cleanup.push(() => { castLibrary?.destroy?.(); castLibrary = null; window.removeEventListener('freevideo-media', castChanged); prompt.removeEventListener('input', announceCast); castOverlay.dispose(); delete node.freevideoCastOff; });
+ openCastLibrary({api, text: t, viewURL: view, uploadOne: castUpload, onChange: () => { castOverlay.refresh(); references.refresh(); }})
+ .then(library => { if (disposed) library?.destroy?.(); else castLibrary = library; });
const enhancer = createPromptEnhancer({node, input: prompt, editor: promptEditor, api, t, starter,
+ prepare: text => expandCast(text, mediaRows(node), {active: !extension.source}).text,
onReport: row => { node.freevideoReportId = row.report_id; progress.updateReport(row); },
onChange: () => rememberPromptDraft(api, node),
setText: text => { set(node, 'text', text || (untouched() ? starter : '')); placeholder(); }, context: () => {
@@ -515,7 +572,7 @@ export function openStudio(node, {extendFrom = null} = {}) {
return {seconds: Number(value(node, 'seconds')), media: items.map(row => ({file: row.file, role: row.role || 'reference'}))};
}});
cleanup.push(() => enhancer.dispose());
- const promptChanged = e => { if (String(e.detail) === String(node.id)) { if (prompt.value !== shown(value(node, 'text'))) prompt.value = shown(value(node, 'text')); prompt.disabled = linked(node, 'text'); mention.disabled = prompt.disabled; placeholder(); references.refresh(); enhancer.sync(); } };
+ const promptChanged = e => { if (String(e.detail) === String(node.id)) { if (prompt.value !== shown(value(node, 'text'))) prompt.value = shown(value(node, 'text')); prompt.disabled = linked(node, 'text'); mention.disabled = prompt.disabled; placeholder(); castOverlay.refresh(); references.refresh(); announceCast(); enhancer.sync(); } };
window.addEventListener('freevideo-reference-prompt', promptChanged);
cleanup.push(() => window.removeEventListener('freevideo-reference-prompt', promptChanged));
const promptSection = section(t('Describe your scene', '描述画面'));