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.

Chain keeps each block's seam sound and never reports an unrepaired seam as a finished video

Bowen Xuef7a94d85ba74
diff --git a/freevideo_engine/chain_join.py b/freevideo_engine/chain_join.py
index 83cfcbb..4f41a00 100644
--- a/freevideo_engine/chain_join.py
+++ b/freevideo_engine/chain_join.py
@@ -147,27 +147,34 @@ def _exact_tail(source, target, wanted, cancelled=None):
temporary.unlink(missing_ok=True)
-def join_files(sources, target, cancelled=None, frames=None):
+def join_files(sources, target, cancelled=None, frames=None, leads=None, expected=None):
"""Write `target` from `sources` in order; returns the joined frame and sample counts.
`frames`: stop at this length when a compatible short tail can close it exactly,
otherwise keep the packet-copy ending at or just after it.
+ `leads`: optional `leads(following, previous)` returning a seam lead kept by the chain;
+ the shared continuation record is read only when it has none.
+ `expected`: how many seams should be repaired; only reported back, the caller decides.
"""
sources = list(sources)
try:
- return _join_files(sources, target, cancelled, frames)
+ return _join_files(sources, target, cancelled, frames, leads=leads, expected=expected)
except _ExactEndFailed:
# A late mux or validation error must also leave the original ending available.
- return _join_files(sources, target, cancelled, frames, exact=False)
+ return _join_files(sources, target, cancelled, frames, exact=False, leads=leads, expected=expected)
-def _join_files(sources, target, cancelled, frames, exact=True):
+def _join_files(sources, target, cancelled, frames, exact=True, leads=None, expected=None):
import av
from .comfy_metadata import _copy_stream
try:
from .comfy_continuation import audio_lead_in, apply_audio_lead_in
except ImportError:
audio_lead_in = apply_audio_lead_in = None
+ if leads is not None and audio_lead_in is not None:
+ stored = audio_lead_in
+ def audio_lead_in(video, previous=None):
+ return leads(video, previous) or stored(video, previous=previous)
sources, target = [Path(source) for source in sources], Path(target)
if len(sources) < 2:
raise ValueError('Joining needs at least two videos')
@@ -276,7 +283,8 @@ def _join_files(sources, target, cancelled, frames, exact=True):
os.replace(temporary, target)
return dict(exact_end=wanted is not None and frames == wanted, frames=frames, width=shape[1], height=shape[2],
audio_samples=samples, sample_rate=rate,
- seams_repaired=joined_audio.seams_repaired if joined_audio is not None else 0)
+ seams_repaired=joined_audio.seams_repaired if joined_audio is not None else 0,
+ seams_expected=expected)
except JoinCancelled:
raise
except Exception as error:
@@ -494,7 +502,7 @@ def _replace_target(root, replace, identity, sources):
return None
-def join_outputs(outputs, identity, cancelled=None, frames=None, replace=None):
+def join_outputs(outputs, identity, cancelled=None, frames=None, replace=None, leads=None, expected_seams=None):
"""Join relative block outputs into a saved video, replacing only this chain's earlier join."""
import folder_paths
root = Path(folder_paths.get_output_directory()).resolve()
@@ -506,6 +514,9 @@ def join_outputs(outputs, identity, cancelled=None, frames=None, replace=None):
if not source.is_relative_to(root) or not source.is_file():
raise ValueError('A block video is missing')
sources.append(source)
+ if leads is not None and len(set(sources)) != len(sources):
+ # The chain's seam sounds are looked up per video; one video in two places would take the wrong one.
+ raise ValueError('Two blocks share one video')
# A saved video is a folder the library lists once its report says it is complete.
target = _replace_target(root, replace, identity, sources)
replacing = target is not None
@@ -516,12 +527,23 @@ def join_outputs(outputs, identity, cancelled=None, frames=None, replace=None):
temporary = path.with_name(path.name + '.' + uuid.uuid4().hex[:8] + '.tmp')
backup = target.with_name('.join-backup-' + uuid.uuid4().hex + '.mp4') if replacing else None
try:
- joined = join_files(sources, staged, cancelled, frames)
+ kept = None
+ if leads is not None:
+ # The chain asks for its own output strings, never a path rebuilt from the disk.
+ originals = {str(source): output for source, output in zip(sources, outputs)}
+ def kept(following, previous):
+ return leads(originals.get(str(following)), originals.get(str(previous)) if previous is not None else None)
+ joined = join_files(sources, staged, cancelled, frames, leads=kept, expected=expected_seams)
+ if expected_seams is not None and joined['seams_repaired'] < expected_seams:
+ # A seam sound left unrepaired is never reported as a finished video.
+ raise ValueError('Only %d of %d seam sounds could be repaired' % (joined['seams_repaired'], expected_seams))
report = dict(success=True, geometry=dict(width=joined['width'], height=joined['height'], frames=joined['frames'],
fps=FPS, seconds=joined['frames'] / FPS),
request_seconds=_request_seconds(sources), video={}, encoding={},
chain_join=dict(chain=identity, blocks=len(sources), seams_repaired=joined['seams_repaired'],
exact_end=joined['exact_end']))
+ if expected_seams is not None:
+ report['chain_join']['seams_expected'] = expected_seams
with temporary.open('w', encoding='utf-8') as stream:
json.dump(report, stream, ensure_ascii=False)
stream.flush()
diff --git a/freevideo_engine/chain_leads.py b/freevideo_engine/chain_leads.py
new file mode 100644
index 0000000..66b1229
--- /dev/null
+++ b/freevideo_engine/chain_leads.py
@@ -0,0 +1,73 @@
+"""Seam sound kept by the chain itself, one small file per block.
+
+A block's opening seam sound lives in its shared continuation record, and the
+shared store keeps only the newest records. A chain joins after its last block,
+so a long chain would find its earliest records gone. The runner copies each
+block's seam sound here as the block finishes; joining reads these copies.
+"""
+import logging
+from pathlib import Path
+import re
+
+SUFFIX = '.lead.npz'
+
+
+def _path(directory, chain, index):
+ if not isinstance(chain, str) or not re.fullmatch(r'c-[0-9a-f]{12}', chain) or type(index) is not int or index < 0:
+ raise ValueError('Invalid chain lead')
+ return Path(directory) / ('%s.%d%s' % (chain, index, SUFFIX))
+
+
+def save(directory, chain, index, lead, previous, output=None):
+ """Keep block `index`'s seam sound with the output of the block it follows and its own output."""
+ import numpy as np
+ import os
+ import uuid
+ samples = np.ascontiguousarray(lead['samples'], dtype=np.float32)
+ path = _path(directory, chain, index)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ temporary = path.with_name(path.name + '.' + uuid.uuid4().hex[:8] + '.tmp')
+ try:
+ with temporary.open('wb') as stream:
+ np.savez(stream, samples=samples, previous=np.array(previous if isinstance(previous, str) else ''),
+ output=np.array(output if isinstance(output, str) else ''))
+ stream.flush()
+ os.fsync(stream.fileno())
+ os.replace(temporary, path)
+ finally:
+ temporary.unlink(missing_ok=True)
+
+
+def load(directory, chain, index, previous, output=None):
+ """The lead dict the seam repair takes, or None when absent, unreadable, or kept for another
+ predecessor or another render of this block."""
+ import numpy as np
+ from .continuation import LEAD_IN_SAMPLES, LEAD_IN_FADE, LEAD_IN_RATE
+ try:
+ with np.load(_path(directory, chain, index), allow_pickle=False) as data:
+ samples, kept = data['samples'], str(data['previous'])
+ own = str(data['output']) if 'output' in data.files else ''
+ if kept and kept != previous or own and output is not None and own != output or samples.dtype != np.float32 or samples.shape != (LEAD_IN_SAMPLES + LEAD_IN_FADE, 2):
+ return None
+ return dict(samples=samples, before=LEAD_IN_SAMPLES, fade=LEAD_IN_FADE, sample_rate=LEAD_IN_RATE)
+ except (OSError, ValueError, KeyError, TypeError, EOFError):
+ return None
+
+
+def has(directory, chain, index):
+ try:
+ return _path(directory, chain, index).is_file()
+ except (OSError, ValueError):
+ return False
+
+
+def prune(directory, chains):
+ """Drop the kept leads of chains the store no longer lists; a listed chain keeps all of them,
+ because a longer chain is joined again from its first block."""
+ chains = set(chains)
+ try:
+ for path in Path(directory).glob('c-*' + SUFFIX):
+ if path.name.split('.', 1)[0] not in chains:
+ path.unlink(missing_ok=True)
+ except OSError:
+ logging.warning('[FreeVideo] Chain seam sound could not be removed')
diff --git a/freevideo_engine/chain_runner.py b/freevideo_engine/chain_runner.py
index 75a2b69..797efd8 100644
--- a/freevideo_engine/chain_runner.py
+++ b/freevideo_engine/chain_runner.py
@@ -7,6 +7,7 @@ import threading
import time
import uuid
+from . import chain_leads
from . import chain_store as store
@@ -50,6 +51,7 @@ class ChainRunner:
self.wake = threading.Event()
self.closed = threading.Event()
self.records = {row['id']: row for row in store.load_all(store_dir)}
+ chain_leads.prune(store_dir, self.records)
self.starts, self.success, self.cancel_sent, self.progress_values = {}, {}, set(), {}
self.progress_messages = {}
self.estimates, self.queue, self.active = {}, [], None
@@ -269,6 +271,45 @@ class ChainRunner:
self.success[prompt_id] = (self.clock(), self.wall())
self._save(record)
self.wake.set()
+ previous = self._sources(record, block)['after']
+ keep = (record['id'], block['index'], output, previous['output'] if previous is not None else None,
+ bool(saved))
+ self._keep_lead(*keep)
+
+ def _keep_lead(self, identity, index, output, previous, continues):
+ """Copy the block's seam sound out of the shared store before newer records push it out."""
+ reader = getattr(self.host, 'lead', None)
+ if not continues or reader is None or not getattr(self.host, 'repairs_seams', True) or not isinstance(output, str) or not isinstance(previous, str):
+ return False
+ try:
+ lead = reader(output, previous)
+ if lead is not None:
+ chain_leads.save(self.store_dir, identity, index, lead, previous, output)
+ return True
+ except Exception:
+ pass
+ logging.warning('[FreeVideo] A chain block\'s seam sound could not be kept: %s', identity)
+ return False
+
+ @staticmethod
+ def _continues(row):
+ """A block generated from the one before it: its seam must be repaired, whatever its receipt promised."""
+ return isinstance(row['after'], str) and bool(row['continuation'])
+
+ def _seams_kept(self, snapshot):
+ """(expected, kept) seam sounds of the leading blocks, keeping late any a record still has."""
+ identity, blocks = snapshot['id'], store.leading_blocks(snapshot)
+ expected = kept = 0
+ for row in blocks[1:] if getattr(self.host, 'repairs_seams', True) else ():
+ if not self._continues(row):
+ continue
+ expected += 1
+ after = self._sources(snapshot, row)['after']
+ if chain_leads.load(self.store_dir, identity, row['index'], after['output'], row['output']) is not None:
+ kept += 1
+ elif self._keep_lead(identity, row['index'], row['output'], after['output'], True):
+ kept += 1
+ return expected, kept
def _finish_blocks(self, record, final_state='done'):
if not record['join']:
@@ -459,11 +500,20 @@ class ChainRunner:
with self.lock:
return self.closed.is_set() or (final_state != 'cancelled'
and self.records[identity]['state'] == 'cancelling')
+ index_by_output = {row['output']: row['index'] for row in snapshot['blocks'] if row['output']}
+ def lead_reader(following, previous):
+ index = index_by_output.get(following)
+ return chain_leads.load(self.store_dir, identity, index, previous, following) if index is not None else None
+ promised, kept = self._seams_kept(snapshot)
+ snapshot = dict(snapshot, lead_reader=lead_reader, expected_seams=promised)
texts = [row['inputs']['text'] for row in snapshot['blocks']]
texts += [row['inputs'].get('text') for row in snapshot['snapshot']['prompt'].values()
if isinstance(row, dict) and isinstance(row.get('inputs'), dict)]
failure = None
try:
+ if kept < promised:
+ # A sound seam that cannot be repaired is never published as a finished video.
+ raise ValueError('%d of %d seam sounds were not kept' % (promised - kept, promised))
output = self.host.join(snapshot, cancelled)
if not isinstance(output, str) or not output:
raise ValueError('Joining did not return a video path')
@@ -484,7 +534,7 @@ class ChainRunner:
logging.warning('[FreeVideo] Chain joining failed: %s', identity)
else:
record.update(state=final_state, output=output, output_blocks=len(store.leading_blocks(snapshot)),
- output_state='done', output_error=None)
+ output_state='done', output_error=None, output_seams=dict(expected=promised, kept=kept))
if record['state'] not in store.ACTIVE and self.active == identity:
self.active = None
self._save(record)
diff --git a/freevideo_engine/chain_store.py b/freevideo_engine/chain_store.py
index 2597b70..ce9e909 100644
--- a/freevideo_engine/chain_store.py
+++ b/freevideo_engine/chain_store.py
@@ -164,6 +164,7 @@ def summary(record):
return dict({key: deepcopy(record[key]) for key in
('version', 'id', 'node', 'created', 'updated', 'state',
'join', 'output', 'output_state', 'output_error', 'output_blocks')},
+ output_seams=deepcopy(record.get('output_seams')),
count=len(blocks), done=sum(row['state'] == 'done' for row in blocks),
current=current, elapsed_seconds=sum(row['seconds'] or 0 for row in blocks if row['state'] == 'done'),
last_report_id=record.get('last_report_id') or next((row['report_id'] for row in reversed(blocks)
@@ -221,6 +222,10 @@ def load_all(directory, limit=200, *, identity=None):
if (type(record['output_blocks']) is not int or not 0 <= record['output_blocks'] <= len(record['blocks'])
or record['output'] is None and record['output_blocks'] != 0):
raise ValueError('Invalid chain output block count')
+ seams = record.get('output_seams')
+ if seams is not None and (not isinstance(seams, dict) or set(seams) != {'expected', 'kept'}
+ or any(type(value) is not int or value < 0 for value in seams.values())):
+ raise ValueError('Invalid chain seam count')
if record.get('join_final_state', 'done') not in ('done', 'cancelled', 'failed', 'interrupted'):
raise ValueError('Invalid chain join final state')
if record['plan'] is not None:
diff --git a/freevideo_engine/comfy_chain.py b/freevideo_engine/comfy_chain.py
index cc72eec..afa5e94 100644
--- a/freevideo_engine/comfy_chain.py
+++ b/freevideo_engine/comfy_chain.py
@@ -152,8 +152,15 @@ class ComfyHost:
blocks = chain_store.leading_blocks(record)
# A planned chain shows exactly the requested length: what the last block made beyond it is left out.
frames = planned['frames'] if planned and not planned['single'] and len(blocks) == len(record['blocks']) else None
+ kept = {'leads': record['lead_reader'], 'expected_seams': record.get('expected_seams')} \
+ if record.get('lead_reader') is not None else {}
return join_outputs([block['output'] for block in blocks], record['id'], cancelled,
- frames=frames, replace=record.get('output'))
+ frames=frames, replace=record.get('output'), **kept)
+
+ def lead(self, output, previous):
+ """A finished block's seam sound, read while its record is still in the shared store."""
+ from .comfy_continuation import audio_lead_in
+ return audio_lead_in(output, previous=previous)
def continuation_directions():
@@ -198,6 +205,7 @@ def block_finished(chain, node_id, output, report_id, continuation=None):
class FakeHost(ComfyHost):
"""Optional CPU-only prompts for development; never touch the host queue."""
fake = True
+ repairs_seams = False # It saves no new sound: its join returns the last block as it is.
def __init__(self, server, seconds=None):
super().__init__(server)