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.

Editor: a button next to the preview saves the frame under the playhead as a picture, kept in...

Bowen Xue2ef6d7f61a5f
diff --git a/freevideo_engine/editor_export.py b/freevideo_engine/editor_export.py
index a5fa123..0401f06 100644
--- a/freevideo_engine/editor_export.py
+++ b/freevideo_engine/editor_export.py
@@ -998,6 +998,77 @@ def resolve_source(key):
return dict(video=path, audio=path)
+class FrameError(ValueError):
+ """Why one frame cannot be saved as a picture: no_picture (nothing is shown there), generating (its part is not made yet) or range."""
+ def __init__(self, reason):
+ super().__init__(reason)
+ self.reason = reason
+
+
+def render_frame(project, resolve, number, *, cancelled=None):
+ """One timeline frame as the export draws it (same placement, fit, picture edits and text), without encoding a video."""
+ width, height, total, tracks = _layout(project)
+ if not _whole(number) or number >= total:
+ raise FrameError('range')
+ clip = next((c for c in tracks['v1'] if c['start'] <= number < c['start'] + c['frames']), None)
+ if clip is None:
+ raise FrameError('no_picture')
+ path = _media(resolve, clip, 'video')
+ if path is None:
+ raise FrameError('generating')
+ wanted = clip['in'] + number - clip['start']
+ # A plain clip seeks straight to the wanted frame; a changed speed or direction keeps the export's own reader.
+ reader = (VideoReader(path, clip, width, height, cancelled) if speed_changed(clip)
+ else _VideoReader(path, wanted, width, height, cancelled, clip))
+ try:
+ pixels = reader.pixels(wanted)
+ return paint_project(pixels, project, number, width, height)
+ finally:
+ reader.close()
+
+
+def _picture_folder():
+ """The folder of pictures made here (the image editor's history), created on first use and never a link."""
+ import folder_paths
+ base = Path(folder_paths.get_input_directory()).resolve()
+ folder = base / 'freevideo-image'
+ if folder.is_symlink() or folder.resolve().parent != base:
+ raise ExportError()
+ folder.mkdir(exist_ok=True)
+ return folder
+
+
+def store_picture(pixels):
+ """Write a frame as a lossless PNG named like the pictures the image editor lists (image-YYYYMMDD-HHMMSS-NN.png)."""
+ from PIL import Image
+ from .file_ops import publish
+ folder = _picture_folder()
+ temporary = folder / ('.frame-' + uuid.uuid4().hex + '.partial')
+ try:
+ with temporary.open('xb') as stream:
+ Image.fromarray(pixels, 'RGB').save(stream, 'PNG')
+ stream.flush()
+ os.fsync(stream.fileno())
+ stamp = time.strftime('image-%Y%m%d-%H%M%S')
+ for number in range(1, 100):
+ target = folder / ('%s-%02d.png' % (stamp, number))
+ try:
+ publish(temporary, target)
+ except FileExistsError:
+ continue
+ return dict(file='freevideo-image/' + target.name, name=target.name,
+ width=int(pixels.shape[1]), height=int(pixels.shape[0]))
+ raise ExportError()
+ finally:
+ temporary.unlink(missing_ok=True)
+
+
+def save_frame(identity, revision, number, *, cancelled=None):
+ """Render one frame of a saved project revision and keep it as a picture."""
+ project = load_project(identity, revision)
+ return store_picture(render_frame(project, resolve_source, number, cancelled=cancelled))
+
+
def _save_report(target, project, seconds, *, options=None):
"""Completion marker after media closes; only video.mp4 enters the library."""
frames = _layout(project)[2]
@@ -1159,7 +1230,7 @@ class ExportQueue:
def register():
- """Register the three endpoints once on the existing ComfyUI server."""
+ """Register the export and frame endpoints once on the existing ComfyUI server."""
from aiohttp import web
from server import PromptServer
server = PromptServer.instance
@@ -1211,3 +1282,27 @@ def register():
return web.json_response({'reason': 'failed'}, status=404)
except (ValueError, TypeError):
return web.json_response({'reason': 'failed'}, status=400)
+
+ frame_lock = asyncio.Lock()
+
+ @server.routes.post('/freevideo/editor/frame')
+ async def frame(request):
+ """Keep one frame of a saved project revision, as the export would draw it, in the pictures made here."""
+ try:
+ body = await request.json()
+ if (not isinstance(body, dict) or set(body) != {'id', 'revision', 'frame'}
+ or not _whole(body['revision']) or not _whole(body['frame'])):
+ raise ValueError('Invalid request')
+ async with frame_lock:
+ value = await asyncio.to_thread(save_frame, body['id'], body['revision'], body['frame'])
+ return web.json_response({'picture': value}, headers={'Cache-Control': 'no-store'})
+ except FrameError as error:
+ return web.json_response({'reason': error.reason}, status=422)
+ except ExportConflict as error:
+ return web.json_response({'revision': error.revision}, status=409, headers={'Cache-Control': 'no-store'})
+ except FileNotFoundError:
+ return web.json_response({'reason': 'source_missing'}, status=404)
+ except (ValueError, TypeError, KeyError):
+ return web.json_response({'reason': 'failed'}, status=400)
+ except Exception as error:
+ return web.json_response({'reason': _reason(error)}, status=503)
diff --git a/web/editor.js b/web/editor.js
index b6fc8e5..3dedf09 100644
--- a/web/editor.js
+++ b/web/editor.js
@@ -604,6 +604,39 @@ export function openEditor({api, app, from = null, panel = {}, components: given
if (queue.dirty) { notify(saveErrorText(queue.failure, t), EDITOR_ISSUE, failureKind('save', {reason: saveReason(queue.failure)})); return false; }
return !!state.record.id;
}
+ // Keeps the frame under the playhead as a picture in the image history, drawn as the export would draw it, from the saved project.
+ let savingFrame = false;
+ async function saveFrame() {
+ if (savingFrame) return;
+ if (initializing || switching) { notify(t('Opening the edit…', '正在打开…')); return; }
+ if (!model.exportFrames(state.record)) { notify(t('The timeline is empty. Add a clip first.', '时间线是空的,请先放入素材。')); return; }
+ const epoch = projectEpoch, shown = Math.min(state.playhead, Math.max(0, model.duration(state.record) - 1));
+ savingFrame = true;
+ try {
+ if (!await saveForExport(epoch)) return;
+ let picture = null;
+ for (let attempt = 0; ; attempt++) {
+ try { picture = await store.saveFrame(state.record.id, state.record.revision, shown); break; }
+ catch (value) {
+ if (value.status !== 409 || attempt >= 2) throw value;
+ queue.enqueue(state.record);
+ if (!await saveForExport(epoch)) return;
+ }
+ }
+ if (disposed || closing || epoch !== projectEpoch) return;
+ if (picture) notify(t('Saved the current frame to Edit image > Generate with AI > History.',
+ '已保存当前帧,位于“编辑图片 > AI 生成 > 历史”。'));
+ } catch (value) {
+ if (disposed || epoch !== projectEpoch) return;
+ const said = {no_picture: t('There is no picture at this position. Move the playhead onto a clip.', '这个位置没有画面,请把播放头移到片段上。'),
+ range: t('There is no picture at this position. Move the playhead onto a clip.', '这个位置没有画面,请把播放头移到片段上。'),
+ generating: t('This part is still being generated. Save the frame when it is done.', '这一段还在生成,完成后再保存。'),
+ unreadable: t('A source file cannot be read. Import it again from the library.', '有素材读不出来,请在素材库重新导入。'),
+ not_writable: t('The picture folder cannot be written to. Check that the folder can be written to, then save the frame again.', '图片文件夹不可写。请检查这个文件夹的写入权限后再保存。'),
+ disk_full: t('The disk is full. Free some space, then save the frame again.', '磁盘空间不足,请清理出空间后再保存。')}[value?.reason];
+ if (said) notify(said); else error(value, 'frame');
+ } finally { savingFrame = false; }
+ }
function updateTop() {
const name = state.record.name || new Date().toLocaleDateString();
if (title.firstElementChild?.textContent !== name) { title.replaceChildren(el('span', '', name), icon('m4 6 4 4 4-4')); headerFit.check(); }
@@ -1511,7 +1544,7 @@ export function openEditor({api, app, from = null, panel = {}, components: given
historyTools.append(toolUndo, toolRedo); editTools.append(split, remove, closeGap, previous, recordTool);
const pictureTools = createPictureTools({state, sources: store.sources, t, capabilities: () => capability, error});
toolbar.append(historyTools, editTools, zoomHost); element.insertBefore(toolbar, tracksHost);
- const transportControls = createEditorTransport({element, preview, transport, toolbar, editTools, zoomHost, state, player, t, notify});
+ const transportControls = createEditorTransport({element, preview, transport, toolbar, editTools, zoomHost, state, player, t, notify, saveFrame});
editTools.append(secondPassButton);
toolbar.append(adjust.toggleButton);
const textTools = createEditorText({element, state, t, actions, adjust, player, toolbar, exportBox, tracksHost});
diff --git a/web/editor_store.js b/web/editor_store.js
index 40441f2..950ae1e 100644
--- a/web/editor_store.js
+++ b/web/editor_store.js
@@ -537,6 +537,14 @@ export function createEditorStore(api, {t = en => en, notify = () => {}, onGener
},
watchExport(id, fn, lost) { return watch(async () => (await json('/freevideo/editor/export?' + new URLSearchParams({id})))?.export || null, fn, lost); },
cancelExport: id => json('/freevideo/editor/export/cancel', post({id})),
+ // One frame of the saved project, as the export draws it, kept as a picture in the image history; null where the server is older.
+ async saveFrame(id, revision, frame) {
+ const response = await request('/freevideo/editor/frame', post({id, revision, frame}));
+ const value = await response.json().catch(() => null);
+ if (!response.ok && (response.status !== 404 || value?.reason)) throw Object.assign(errorFor(response), {reason: value?.reason});
+ if (response.status === 404 || !value) { notice('frame', 'To save a frame, update FreeVideo and restart it.', '请更新 FreeVideo 并重新启动后再保存画面。'); return null; }
+ return value.picture || null;
+ },
// Subtitles from speech. What this computer can recognise; null where it cannot or the server is older.
async ears() { return (await json('/freevideo/editor/ears'))?.available || null; },
async startEars(id, revision) { return (await json('/freevideo/editor/ears', post({kind: 'transcribe', id, revision})))?.job || null; },
diff --git a/web/editor_transport.js b/web/editor_transport.js
index 537d308..ae85e74 100644
--- a/web/editor_transport.js
+++ b/web/editor_transport.js
@@ -67,9 +67,10 @@ const icons = {
loop: 'M4 6h12l-3-3m3 3-3 3M16 14H4l3 3m-3-3 3-3',
'play-range': 'M3 3v14m14-14v14M7 6l6 4-6 4z', fullscreen: 'M7 3H3v4m10-4h4v4M3 13v4h4m10-4v4h-4',
snapping: 'M4 3v8a6 6 0 0 0 12 0V3h-4v8a2 2 0 0 1-4 0V3zM4 7h4m4 0h4',
+ 'save-frame': 'M3 6h3l1.5-2h5L14 6h3v10H3zM10 13.5a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5z',
marker: 'm10 3 6 7-6 7-6-7z', shortcuts: 'M2 5h16v10H2zM5 8h1m3 0h1m3 0h1M5 11h1m3 0h5',
};
-export function createEditorTransport({element, preview, transport, toolbar, editTools, zoomHost, state, player, t, notify}) {
+export function createEditorTransport({element, preview, transport, toolbar, editTools, zoomHost, state, player, t, notify, saveFrame = null}) {
let tracks = null, align = null, layer = null, markerSelection = null, markerStamp = null, drag = null, kHeld = false, disposed = false;
const clock = player.playback, listeners = [], nodes = [];
const on = (target, type, callback, options) => { target.addEventListener(type, callback, options); listeners.push(() => target.removeEventListener(type, callback, options)); };
@@ -88,7 +89,15 @@ export function createEditorTransport({element, preview, transport, toolbar, edi
const loop = button('loop', t('Loop (Shift + L)', '循环播放(Shift + L)'));
const range = button('play-range', t('Play selected range (Shift + Space)', '播放选中范围(Shift + 空格)'));
const fullscreen = button('fullscreen', t('Full screen (F)', '全屏(F)'));
- tools.append(loop, range, fullscreen); transport.append(tools); nodes.push(tools);
+ // Keeps the frame under the playhead as a picture; the button is off on an empty timeline and while the editor saves it.
+ const frame = saveFrame && button('save-frame', t('Save current frame', '保存当前帧'));
+ let savingFrame = false;
+ if (frame) on(frame, 'click', async () => {
+ if (frame.disabled) return;
+ savingFrame = true; frame.disabled = true; frame.setAttribute('aria-busy', 'true');
+ try { await saveFrame(); } finally { savingFrame = false; frame.removeAttribute('aria-busy'); refresh(); }
+ });
+ tools.append(loop, range, ...(frame ? [frame] : []), fullscreen); transport.append(tools); nodes.push(tools);
const sheet = el('div', 'fv-ed-shortcut-sheet'); sheet.hidden = true; sheet.setAttribute('role', 'region'); sheet.setAttribute('aria-label', t('Shortcuts', '快捷键'));
element.append(sheet); nodes.push(sheet);
const fullHost = el('div', 'fv-ed-fullscreen-host'); preview.parentNode.insertBefore(fullHost, preview); fullHost.append(preview, transport); nodes.push(fullHost);
@@ -108,6 +117,7 @@ export function createEditorTransport({element, preview, transport, toolbar, edi
const bounds = selection(); range.disabled = !bounds;
range.title = t('Play selected range (Shift + Space)', '播放选中范围(Shift + 空格)');
range.setAttribute('aria-label', range.title); range.setAttribute('aria-pressed', String(!!clock.range));
+ if (frame) frame.disabled = savingFrame || !model.exportFrames(state.record);
fullscreen.setAttribute('aria-pressed', String(document.fullscreenElement === fullHost));
transport.dataset.rate = String(player.playing ? clock.rate : 0);
if (layer && !drag) renderMarkers();