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 continuation to the two-pass text generation engine
Bowen Xuedb160957d7ac
diff --git a/freevideo_engine/adaptive.py b/freevideo_engine/adaptive.pyindex e3e3a83..6fa6011 100644--- a/freevideo_engine/adaptive.py+++ b/freevideo_engine/adaptive.py@@ -659,13 +659,21 @@ def complete_observation(metrics, canvas, output, artifacts, telemetry):from .system import memory_complete, memory_peakfrom .validation import _retained_array_header, finite_numberexpected = canvas['frames']+ continuation = metrics.get('continuation')+ output_frames = expected+ if continuation is not None:+ from .continuation import OVERLAP_FRAMES+ if (not isinstance(continuation, dict) or continuation.get('overlap_frames') != OVERLAP_FRAMES+ or continuation.get('new_frames') != expected - OVERLAP_FRAMES):+ raise ValueError('Invalid continuation output geometry')+ output_frames = continuation['new_frames']preview = metrics.get('preview') is Trueif preview:# A preview decodes its first pass at the planned smaller canvas.first = (metrics.get('sampling_plan') or {}).get('first') or {}canvas = dict(canvas, width=first.get('width'), height=first.get('height'))if (metrics.get('success') is not True or metrics.get('phase') != 'complete'- or metrics.get('finite_latents') is not True or metrics.get('frames') != expected+ or metrics.get('finite_latents') is not True or metrics.get('frames') != output_framesor any(metrics.get('geometry', {}).get(k) != canvas[k] for k in ('width','height','frames','fps'))):raise ValueError('A successful complete request with matching geometry is required.')steps = metrics.get('config', {}).get('steps')@@ -678,11 +686,11 @@ def complete_observation(metrics, canvas, output, artifacts, telemetry):or not same_strategy(metrics, canvas) or not all(finite_number(t) and t > 0 for t in times)):raise ValueError('A probe or incomplete sample cannot become a resource observation.')rgb_shape, dtype = _retained_array_header(Path(artifacts)/'rgb.npy')- if str(dtype) != 'uint8' or rgb_shape != (expected, canvas['height'], canvas['width'], 3):+ if str(dtype) != 'uint8' or rgb_shape != (output_frames, canvas['height'], canvas['width'], 3):raise ValueError('Retained video frames do not match the complete request.')audio_shape, audio_dtype = _retained_array_header(Path(artifacts)/'audio.npy')if (str(audio_dtype) != 'float32' or len(audio_shape) != 2 or audio_shape[0] != 2- or abs(audio_shape[1]/32000. - expected/canvas['fps']) > 1/canvas['fps']):+ or abs(audio_shape[1]/32000. - output_frames/canvas['fps']) > 1/canvas['fps']):raise ValueError('Retained stereo audio does not match the request duration.')import avwith av.open(str(output)) as container:@@ -690,7 +698,9 @@ def complete_observation(metrics, canvas, output, artifacts, telemetry):if len(video) != 1 or len(audio) != 1:raise ValueError('The completed MP4 must contain video and audio.')stream = video[0]- if ((stream.width, stream.height, stream.frames) != (canvas['width'],canvas['height'],expected)+ # A request rendered at a larger size is saved at the size asked for.+ shown = metrics.get('output_size') or canvas+ if ((stream.width, stream.height, stream.frames) != (shown['width'],shown['height'],output_frames)or float(stream.average_rate) != canvas['fps'] or audio[0].codec_context.channels != 2):raise ValueError('MP4 metadata does not match the requested output.')if metrics.get('sampling_reused') is True:@@ -698,6 +708,10 @@ def complete_observation(metrics, canvas, output, artifacts, telemetry):# retry. Do not teach placement/ETA that a full request cost this little# time or occupied only the decoder's memory.return None+ if continuation is not None:+ # Clean prefix rows and the shorter decode have different timing from+ # ordinary text generation. Do not seed that request's history with it.+ return Noneif preview or metrics.get('first_pass_source') == 'preview':# A preview stops after its first pass, and its upscale reuses that pass# from an earlier request. Neither costs what a whole request costs.diff --git a/freevideo_engine/capabilities.py b/freevideo_engine/capabilities.pyindex ff295ea..9daddfb 100644--- a/freevideo_engine/capabilities.py+++ b/freevideo_engine/capabilities.py@@ -221,7 +221,8 @@ def _machine(machine, in_use=None):def _request(width, height, frames, steps, two_pass, task='t2va', refine=3,references=None, reference_rows=None):"""Scalar request shared by admission and offline, recorded-row reviews."""- canvas = dict(geometry(width, height, frames=frames), task=task, steps=steps)+ from .two_pass import render_canvas+ canvas = dict(render_canvas(geometry(width, height, frames=frames))[0], task=task, steps=steps)if reference_rows is not None:if not valid_reference_rows(reference_rows):raise ValueError('Invalid recorded reference rows.')@@ -233,8 +234,9 @@ def _request(width, height, frames, steps, two_pass, task='t2va', refine=3,if duration is not None:canvas['reference_seconds'] = durationsampling = sampling_plan(canvas, two_pass, task, base_steps=steps, refine_steps=refine)- request = dict(canvas, base_steps=steps, refine_steps=refine if two_pass else 0,- two_pass=two_pass, flow='full',+ # A small canvas runs in one pass even with two-pass on; follow the plan.+ request = dict(canvas, base_steps=steps, refine_steps=sampling['refine_steps'],+ two_pass=sampling['enabled'], flow='full',sampling_geometry={k: sampling[k] for k in ('first', 'second') if sampling[k]})return canvas, sampling, requestdiff --git a/freevideo_engine/cli.py b/freevideo_engine/cli.pyindex 6543b5e..732dd5d 100644--- a/freevideo_engine/cli.py+++ b/freevideo_engine/cli.py@@ -92,6 +92,7 @@ def main():from .media_request import TASKSgenerate.add_argument('--task', choices=TASKS, help='Input task; inferred when --media is provided')generate.add_argument('--media', type=Path, help='Versioned keyframe/reference/LoRA request JSON; local files only')+ generate.add_argument('--continue-from', type=Path, help='Continue an existing MP4 using its absolute path')generate.add_argument('--allocator-limit-gib', type=float,help='Explicit benchmark cap on PyTorch CUDA allocations; not a whole-device memory limit')generate.add_argument('--no-history-placement', action='store_true', help='Keep the starting placement for a matched baseline; still record measurements')@@ -116,9 +117,11 @@ def main():generate.add_argument('--out', type=Path, required=True)generate.add_argument('--width', type=int, default=1344)generate.add_argument('--height', type=int, default=768)- length = generate.add_mutually_exclusive_group()- length.add_argument('--frames', type=int)- length.add_argument('--seconds', type=float)+ duration = generate.add_mutually_exclusive_group()+ duration.add_argument('--frames', type=int, help='Frame count (rounded up); continuation requires 39, 56, 73, ... total frames')+ duration.add_argument('--seconds', type=float)+ generate.add_argument('--continuation-snapshot', type=Path, help=argparse.SUPPRESS)+ generate.add_argument('--continuation-snapshot-sha256', help=argparse.SUPPRESS)for command in (generate, encode):command.add_argument('--encoder-python', '--comfy-python', dest='comfy_python',default=os.environ.get('FREEVIDEO_COMFY_PYTHON', sys.executable))@@ -131,12 +134,21 @@ def main():help='Measure the placement questions this machine can settle')calibrate.add_argument('arguments', nargs=argparse.REMAINDER)args = parser.parse_args()+ if args.command == 'generate':+ from .continuation import validate_frames, validate_route+ if args.continue_from is not None:+ if args.frames is not None:+ validate_frames(args.frames)+ validate_route(task=args.task or 't2va', two_pass=args.two_pass, preview=args.preview,+ refine_from=args.refine_from)if sys.platform == 'darwin' and args.command in ('plan', 'generate', 'encode', 'doctor'):from .macos_generate import dispatchreturn dispatch(args)if args.command == 'plan':from .geometry import geometrycanvas = geometry(args.width, args.height, frames=args.frames, seconds=args.seconds)+ from .two_pass import render_canvas+ canvas = render_canvas(canvas)[0]hardware = Hardware.from_dict(json.loads(args.hardware_json.read_text(encoding='utf-8'))) if args.hardware_json else detect()available = {'sage2', 'cudnn', 'torch-flash', 'fa2', 'fa4'} if args.hardware_json else available_backends(hardware, probe_missing=False)policy = choose(hardware, **{key: getattr(args, key) for key indiff --git a/freevideo_engine/comfy_assets.py b/freevideo_engine/comfy_assets.pyindex 99d9e0e..51d13de 100644--- a/freevideo_engine/comfy_assets.py+++ b/freevideo_engine/comfy_assets.py@@ -151,7 +151,8 @@ def output_summary(report, relative_video):conditioning_cache_hit=report.get('encoding', {}).get('cache_hit', False),gpu_budget_bytes=report.get('profile', {}).get('policy', {}).get('gpu_budget_bytes'),gpu_total_bytes=report.get('profile', {}).get('policy', {}).get('hardware', {}).get('vram_total'),- geometry=report.get('geometry', {}),+ # A small size is sampled larger and scaled back; people see the size they asked for.+ geometry=dict(report.get('geometry', {}), **(report.get('output_size') or {})),sampling_plan=report.get('sampling_plan'),low_memory=bool(report.get('low_memory_mode')),thermal=thermal_slowdown(((report.get('memory') or {}).get('video') or {}).get('gpu')),@@ -186,4 +187,14 @@ def output_summary(report, relative_video):unified_total_bytes=hardware.get('ram_total'),unified_reserve_bytes=policy.get('reserve_bytes'),vram_peak_bytes=None, gpu_budget_bytes=None, gpu_total_bytes=None)+ continuation = report.get('continuation')+ if isinstance(continuation, dict):+ # Only chain counters, never retained source paths or conditioning.+ counters = {key: continuation[key] for key in+ ('overlap_frames', 'new_frames', 'frame_origin', 'audio_origin', 'segment', 'audio_lead_in_samples')+ if type(continuation.get(key)) is int}+ if counters:+ if 'overlap_frames' in counters and 'new_frames' in counters:+ counters['requested_frames'] = counters['overlap_frames'] + counters['new_frames']+ result['continuation'] = countersreturn resultdiff --git a/freevideo_engine/comfy_bridge.py b/freevideo_engine/comfy_bridge.pyindex aabf144..912f583 100644--- a/freevideo_engine/comfy_bridge.py+++ b/freevideo_engine/comfy_bridge.py@@ -252,10 +252,12 @@ class WholeVideoProgress:vars(self).clear()vars(self).update(saved)- def configure(self, *, plan=None, media=None, conditioning=False, placement=None):+ def configure(self, *, plan=None, canvas=None, media=None, conditioning=False, placement=None):"""Use facts already obtained by the bridge; never inspect media/models."""self._late_history()from .media_request import task_for+ if canvas:+ self.request.update({key: canvas[key] for key in ('width', 'height', 'frames')})if plan:self.sampling_plan = planself.request.update(two_pass=bool(plan.get('enabled')), base_steps=plan.get('base_steps', 8),@@ -761,14 +763,23 @@ def installation(source=None, environ=None):return root, plain_data(machine)-def validate_request(prompt, width, height, seconds, seed):+def validate_request(prompt, width, height, seconds, seed, *, continue_from=None, frames=None,+ two_pass=True, preview=False, refine_from=None, media=None):if not isinstance(prompt, str) or not prompt.strip():raise ValueError('Enter a prompt describing the video and its audio.')if type(seed) is not int or not 0 <= seed <= 2**53 - 1:raise ValueError('Seed must be an integer between 0 and 9007199254740991.')- if isinstance(seconds, bool) or not isinstance(seconds, (float, int)) or not math.isfinite(seconds):+ if frames is not None:+ from .continuation import validate_frames+ validate_frames(frames)+ elif isinstance(seconds, bool) or not isinstance(seconds, (float, int)) or not math.isfinite(seconds):raise ValueError('Duration must be a positive number of seconds.')- return geometry(width, height, seconds=seconds)+ canvas = geometry(width, height, frames=frames, seconds=None if frames is not None else seconds)+ if continue_from is not None:+ from .continuation import validate_path, validate_route+ validate_route(two_pass=two_pass, preview=preview, refine_from=refine_from, media=media)+ validate_path(continue_from)+ return canvasclass EventTail:@@ -1055,7 +1066,11 @@ def generate(prompt, width, height, seconds, seed, output_directory, *,source=None, environ=None, metadata=None, progress=None, interrupted=None,release_models=None, export_inputs=None, two_pass=True, encoder_prewarm=None,force_regenerate=False, base_steps=8, refine_steps=3, comfy_metadata=None,- prompt_rewrite_report=None, preview=False, refine_from=None, report_extra=None):+ prompt_rewrite_report=None, preview=False, refine_from=None, report_extra=None,+ continue_from=None, frames=None):+ if continue_from is not None:+ from .continuation import validate_route+ validate_route(two_pass=two_pass, preview=preview, refine_from=refine_from)if type(two_pass) is not bool:raise ValueError('Two-pass generation must be a boolean')if type(force_regenerate) is not bool:@@ -1080,9 +1095,16 @@ def generate(prompt, width, height, seconds, seed, output_directory, *,validate_flags(preview, upscale, two_pass)from .two_pass import validate_stepsvalidate_steps(base_steps, refine_steps, two_pass)- canvas = validate_request(prompt, width, height, seconds, seed)+ canvas = validate_request(prompt, width, height, seconds, seed, continue_from=continue_from, frames=frames)source = Path(source or source_root()).resolve()root, machine = installation(source, environ)+ if continue_from is not None:+ validate_route(backend=machine.get('device_backend', 'cuda'))+ from .continuation import prepare, summary+ from .two_pass import sampling_canvas+ # A continuation takes no media or preview, so its sampled size is known here; the snapshot+ # of the previous segment was written for that canvas, not for the requested size.+ continuation = prepare(continue_from, sampling_canvas(canvas)[0], directory=root / 'continuations')environment = engine_environment(root, source, environ)environment.update(FREEVIDEO_HOME=str(root), PYTHONPATH=str(source), PYTHONUNBUFFERED='1',PYTHONUTF8='1', PYTHONIOENCODING='utf-8', NO_COLOR='1', FREEVIDEO_UI_EVENTS='1')@@ -1106,6 +1128,15 @@ def generate(prompt, width, height, seconds, seed, output_directory, *,'--width', str(width), '--height', str(height), '--seconds', str(seconds), '--seed', str(seed),'--two-pass' if two_pass else '--no-two-pass','--base-steps', str(base_steps), '--refine-steps', str(refine_steps)]+ if frames is not None:+ position = command.index('--seconds')+ command[position:position + 2] = ['--frames', str(frames)]+ if continue_from is not None:+ command += ['--continue-from', str(continue_from)]+ from .continuation import persist_snapshot+ continuation = persist_snapshot(continuation, run / 'continuation-source.safetensors')+ command += ['--continuation-snapshot', continuation['snapshot'],+ '--continuation-snapshot-sha256', continuation['snapshot_sha256']]if upscale:command = command[:command.index('generate') + 1] + upscale_command(upscale[1], output, upscale[0], resources)else:@@ -1191,15 +1222,24 @@ def generate(prompt, width, height, seconds, seed, output_directory, *,send_progress({'label': 'Retaining and checking input media', 'timing_phase': 'encoding','references': any(media.get(key) for key in ('first', 'last', 'references'))})from .media_request import task_for- from .two_pass import plan- planned = plan(canvas, two_pass, task_for(extra.get('media', {})), base_steps=base_steps, refine_steps=refine_steps)+ from .two_pass import plan, sampling_canvas+ # The engine samples this canvas; results, cache keys and labels keep the requested size.+ sampled, output_size = sampling_canvas(canvas, staged=bool(preview or upscale), media=extra.get('media'),+ conditioned=bool(extra.get('conditioning')))+ planned = plan(sampled, two_pass, task_for(extra.get('media', {})), base_steps=base_steps, refine_steps=refine_steps,+ staged=bool(preview or upscale))+ if continue_from is not None:+ from .continuation import ADALN_TASK, validate_snapshot, summary+ validate_route(task=task_for(extra.get('media', {})), media=extra.get('media'))+ continuation = validate_snapshot(continuation, sampled, sampling_plan=planned)+ state['continuation'] = summary(continuation)# A preview is its own result; an upscale is always run from its preview.keyed = dict(planned, preview=True) if preview else plannedidentify = lambda check: request_key(prompt, seed, canvas, keyed, extra, machine,resources, source, environment, inspection=check)state['result_cache'] = dict(enabled=False, hit=False, forced=force_regenerate)reused = None- if not force_regenerate and not upscale:+ if not force_regenerate and not upscale and continue_from is None:send_progress({'label': 'Checking saved video', 'timing_phase': 'encoding'})def inspect_saved(check):key = identify(check)@@ -1225,7 +1265,8 @@ def generate(prompt, width, height, seconds, seed, output_directory, *,preparation_started = time.monotonic()try:# Reference audio selects its own tables; match the encoder's choice.- preparation = prepare_sampling_assets(root, machine, planned, engine_task(extra.get('media', {}), media_base),+ asset_task = ADALN_TASK if continue_from is not None else engine_task(extra.get('media', {}), media_base)+ preparation = prepare_sampling_assets(root, machine, planned, asset_task,progress=asset_progress, interrupted=interrupted, environ=environment)except BaseException:elapsed = time.monotonic() - preparation_started@@ -1236,7 +1277,7 @@ def generate(prompt, width, height, seconds, seed, output_directory, *,if preparation['seconds']:started += preparation['seconds']send_progress({'reset': True, 'label': 'Preparing video'})- whole_progress.configure(plan=planned, media=extra.get('media', {}),+ whole_progress.configure(plan=planned, canvas=sampled, media=extra.get('media', {}),conditioning=bool(extra.get('conditioning')))send_progress({'label': 'Preparing %.3f s video + audio · %d × %d' %(canvas['seconds'], width, height)})@@ -1276,9 +1317,9 @@ def generate(prompt, width, height, seconds, seed, output_directory, *,engine = json.loads(output.with_suffix('.engine.json').read_text(encoding='utf-8'))from .two_pass import steps, plancompleted_steps = steps(report.get('sampling_plan'))- expected_plan = plan(canvas, two_pass, report.get('profile', {}).get('engine', {}).get('task', 't2va'),- base_steps=base_steps, refine_steps=refine_steps)- shown = canvas+ expected_plan = plan(sampled, two_pass, report.get('profile', {}).get('engine', {}).get('task', 't2va'),+ base_steps=base_steps, refine_steps=refine_steps, staged=bool(preview or upscale))+ shown = sampledif preview:# A preview decodes its first pass at the planned smaller canvas.completed_steps = expected_plan['base_steps']@@ -1289,7 +1330,8 @@ def generate(prompt, width, height, seconds, seed, output_directory, *,or engine.get('sampling_plan') != report.get('sampling_plan')or report.get('sampling_plan') != expected_planor bool(report.get('preview')) != preview or bool(report.get('upscaled_preview')) != bool(upscale)- or any(engine.get('geometry', {}).get(k) != shown[k] for k in ('width', 'height', 'frames'))):+ or any(engine.get('geometry', {}).get(k) != shown[k] for k in ('width', 'height', 'frames'))+ or (report.get('output_size') or None) != output_size):from .comfy_launcher_api import repair_hintfrom .failure_details import generation_failureraise RuntimeError('FreeVideo did not complete the requested video.\n' + generation_failure(run, repair=repair_hint()))@@ -1298,6 +1340,9 @@ def generate(prompt, width, height, seconds, seed, output_directory, *,# return earlier and retain their historical report byte for byte.report.update(report_extra)save(output.with_suffix('.request.json'), report)+ if continue_from is not None:+ state['continuation']['audio_lead_in_samples'] = engine.get('continuation', {}).get(+ 'audio_lead_in_samples', 0)if comfy_metadata:# Dropping the video on the canvas restores this graph, as with ComfyUI's own video nodes.# Written before the result cache records the file's size and hash.diff --git a/freevideo_engine/comfy_continuation.py b/freevideo_engine/comfy_continuation.pynew file mode 100644index 0000000..115fd1c--- /dev/null+++ b/freevideo_engine/comfy_continuation.py@@ -0,0 +1,164 @@+"""ComfyUI continuation paths, capabilities and standalone audio export helpers."""+from pathlib import Path, PurePosixPath, PureWindowsPath++from .continuation import (INVALID_FILE, INVALID_FRAMES, LEAD_IN_SAMPLES,+ LEAD_IN_FADE, LEAD_IN_RATE)+++def request_frames(value):+ """Translate the node's duration sentinel into the bridge's optional count."""+ if type(value) is not int or value != 0 and (value < 39 or (value - 5) % 17):+ raise ValueError(INVALID_FRAMES)+ return value or None+++def resolve_continue_from(value, output_directory, input_directory):+ """Resolve an MP4 inside Comfy's roots, including output/FreeVideo creations.++ Relative history names always refer to output. An absolute input name is+ also accepted. Check both the original location and the resolved location+ so a link cannot grant access outside its allowed root.+ """+ if not isinstance(value, str) or len(value) > 4096 or '\x00' in value:+ raise ValueError(INVALID_FILE)+ if not value:+ return None+ path = Path(value)+ windows = PureWindowsPath(value)+ if ('..' in PurePosixPath(value).parts or '..' in windows.parts+ or windows.drive and not path.is_absolute()+ or '\\' in value and path.anchor != windows.anchor+ or any(':' in part for part in path.parts if part != path.anchor)+ or path.suffix.lower() != '.mp4'):+ raise ValueError(INVALID_FILE)+ roots = tuple(Path(root).resolve() for root in (output_directory, input_directory))+ candidate = path if path.is_absolute() else roots[0] / path+ allowed = [root for root in roots if candidate.is_relative_to(root)]+ if not allowed:+ raise ValueError(INVALID_FILE)+ try:+ resolved = candidate.resolve(strict=True)+ except (OSError, RuntimeError):+ raise ValueError(INVALID_FILE) from None+ if not any(resolved.is_relative_to(root) for root in allowed):+ raise ValueError(INVALID_FILE)+ if not resolved.is_file():+ raise ValueError(INVALID_FILE)+ return str(resolved)+++def request_options(continue_from='', frames=0):+ count = request_frames(frames)+ if not isinstance(continue_from, str):+ raise ValueError(INVALID_FILE)+ previous = None+ if continue_from:+ import folder_paths+ previous = resolve_continue_from(continue_from, folder_paths.get_output_directory(),+ folder_paths.get_input_directory())+ # Ordinary requests retain the existing bridge call and duration behavior.+ return dict(continue_from=previous, frames=count) if previous or count else {}+++def audio_lead_in(video, previous=None):+ """Read a new segment's seam audio, optionally checking its predecessor.++ Comfy paths follow continue_from's input/output root rules. Without Comfy,+ use absolute MP4 paths and the engine's selected FREEVIDEO_HOME. Missing,+ old or changed media/records return None.++ Export may use this only when the previous block's end and this block's+ start are untrimmed and the blocks are adjacent on the track. Apply before+ adjusting volume or resampling.+ """+ try:+ import numpy as np+ from av import FFmpegError+ from .continuation_store import load, video_id+ except ImportError:+ return None+ try:+ try:+ import folder_paths+ except ModuleNotFoundError as error:+ if error.name != 'folder_paths':+ raise+ from .continuation import validate_path+ resolve = validate_path+ directory = None+ else:+ from .comfy_bridge import installation_root+ directory = installation_root() / 'continuations'+ def resolve(value):+ return resolve_continue_from(str(value), folder_paths.get_output_directory(),+ folder_paths.get_input_directory())+ path = resolve(video)+ if path is None:+ return None+ value = load(path, directory=directory)+ if value is None or 'audio_lead_in' not in value:+ return None+ if previous is not None:+ source = resolve(previous)+ if source is None or value['metadata'].get('source_id') != video_id(source):+ return None+ return dict(samples=value['audio_lead_in'].astype(np.float32), before=LEAD_IN_SAMPLES,+ fade=LEAD_IN_FADE, sample_rate=LEAD_IN_RATE)+ except (OSError, ValueError, TypeError, KeyError, AttributeError, RuntimeError,+ ImportError, OverflowError, FFmpegError):+ return None+++def apply_audio_lead_in(previous_samples, samples, lead):+ """Repair an adjacent seam in place, returning False without edits if invalid.++ Both blocks must be float32 [n, 2] at 32 kHz. The previous block's end and+ this block's start must be untrimmed, with the blocks adjacent on the track.+ Call before adjusting volume or resampling. Correlated audio uses linear+ fades, with endpoints included, to avoid an equal-power gain bump.+ Call once per seam on the original decoded blocks: repeated calls compound+ both fades and are not idempotent when the sources differ.+ """+ import numpy as np+ if (not isinstance(lead, dict)+ or any(type(lead.get(key)) is not int or lead[key] != expected for key, expected in+ (('before', LEAD_IN_SAMPLES), ('fade', LEAD_IN_FADE), ('sample_rate', LEAD_IN_RATE)))):+ return False+ context = lead.get('samples')+ if any(not isinstance(value, np.ndarray) or value.dtype != np.float32+ or value.ndim != 2 or value.shape[1] != 2 for value in (previous_samples, samples, context)):+ return False+ if (context.shape[0] != LEAD_IN_SAMPLES + LEAD_IN_FADE+ or len(previous_samples) < LEAD_IN_SAMPLES or len(samples) < LEAD_IN_FADE+ or not previous_samples.flags.writeable or not samples.flags.writeable+ or np.shares_memory(previous_samples, samples)):+ return False+ # Distinct logical output samples must own distinct storage. Broadcast or+ # overlapping channel views could otherwise alter samples outside the seam.+ if any(abs(value.strides[0]) < value.itemsize+ or any(stride % value.itemsize for stride in value.strides)+ or np.shares_memory(value[:, 0], value[:, 1])+ for value in (previous_samples, samples)):+ return False+ old_tail = previous_samples[-LEAD_IN_SAMPLES:]+ if (not np.isfinite(context).all() or not np.isfinite(previous_samples).all()+ or not np.isfinite(samples).all()):+ return False+ weight = np.linspace(0., 1., LEAD_IN_FADE, dtype=np.float32)[:, None]+ # Compute both fades before the first write, even if context aliases a block.+ start = old_tail[:LEAD_IN_FADE] * (1. - weight) + context[:LEAD_IN_FADE] * weight+ end = context[LEAD_IN_SAMPLES:] * (1. - weight) + samples[:LEAD_IN_FADE] * weight+ old_tail[:] = context[:LEAD_IN_SAMPLES]+ old_tail[:LEAD_IN_FADE] = start+ samples[:LEAD_IN_FADE] = end+ return True+++def continuation_supported():+ """Return the engine's (supported, reason_code) for the capabilities route.++ Import lazily: loading the Comfy extension does not probe an engine backend.+ The engine implementation is supplied alongside this server integration.+ """+ from .continuation import supported+ return supported()diff --git a/freevideo_engine/comfy_library.py b/freevideo_engine/comfy_library.pyindex 869a2e5..f7b748b 100644--- a/freevideo_engine/comfy_library.py+++ b/freevideo_engine/comfy_library.py@@ -1,5 +1,6 @@"""Browse completed FreeVideo outputs across ComfyUI/browser restarts."""import asyncio+from contextlib import nullcontextimport ioimport jsonimport logging@@ -174,6 +175,7 @@ def video_download(output_directory, identity):# Windows would not let it replace a JSON record. A creation whose folder# holds anything else, or any link, is not deleted at all._OWNED_FILE = re.compile(r'(?:video\.[A-Za-z0-9._-]+|prompt\.txt|workflow\.json|comfy-request\.json|generate\.log'+ r'|continuation-source\.safetensors'r'|media\.json|prompt-rewrite\.json|input-conditioning\.pt|(?:first|last)\.png'r'|reference-\d{2}\.(?:png|mp4|wav))(?:\.[a-z0-9_]{8}\.tmp)?')_OWNED_FOLDER = 'video.artifacts'@@ -255,6 +257,10 @@ def _remove(folder):if not _plain(path):left.append(plain(path)); continuesize = path.stat().st_size+ if name == 'continuation-source.safetensors':+ # Request snapshots are read-only while used; Windows+ # requires clearing that flag when deleting their run.+ path.chmod(0o600)path.unlink()freed += sizeexcept OSError:@@ -387,7 +393,38 @@ def release_earlier(output_directory):return totals-def delete_video(output_directory, identity):+def _queued_continuation_uses(path, output_directory, queue):+ if queue is None:+ return False+ from .comfy_continuation import resolve_continue_from+ for rows in queue.get_current_queue():+ for entry in rows:+ prompt = entry[2] if isinstance(entry, (list, tuple)) and len(entry) > 2 else None+ if not isinstance(prompt, dict):+ continue+ for node in prompt.values():+ if not isinstance(node, dict) or node.get('class_type') != 'FreeVideoGenerate':+ continue+ inputs = node.get('inputs', {})+ source = inputs.get('continue_from') if isinstance(inputs, dict) else None+ if isinstance(source, (list, tuple)):+ # A connected path is resolved only by execution. Until+ # then the queue can still depend on this creation.+ return True+ if not isinstance(source, str) or not source:+ continue+ try:+ # Saved creations live under output; its absolute paths+ # and relative history names share the node's resolver.+ resolved = resolve_continue_from(source, output_directory, output_directory)+ except ValueError:+ continue+ if Path(resolved) == path:+ return True+ return False+++def delete_video(output_directory, identity, *, queue=None):"""Delete one saved creation: its whole run folder, only when FreeVideo wrote everything in it.The folder is first renamed into FreeVideo/.deleted, so it leaves the@@ -404,7 +441,7 @@ def delete_video(output_directory, identity):if folder.parent.parent != root or not _plain(folder.parent) or not _plain(folder):raise DeleteRefused('not-freevideo')# Not while the startup release is deleting files in this folder.- with _RELEASING:+ with _RELEASING, (queue.mutex if queue is not None else nullcontext()):from .comfy_editor import reference_userstry:users = reference_users(output_directory, identity)@@ -415,15 +452,35 @@ def delete_video(output_directory, identity):kept = _foreign(folder)if kept:raise DeleteRefused('foreign-files', kept)+ if _queued_continuation_uses(path, output_directory, queue):+ raise DeleteRefused('continuation-in-use')# A second pass of this preview may be reading its first pass right now.for state_path in root.glob('*/*/comfy-request.json'):try:state = json.loads(state_path.read_text(encoding='utf-8')) if state_path.stat().st_size <= 1024 * 1024 else {}except (OSError, ValueError):continue- source = state.get('upscaled_preview') if isinstance(state, dict) else None- if state.get('status') in ('starting', 'running') and isinstance(source, str) and Path(source).resolve() == path:+ if not isinstance(state, dict) or state.get('status') not in ('queued', 'starting', 'running'):+ continue+ source = state.get('upscaled_preview')+ if isinstance(source, str) and Path(source).resolve() == path:raise DeleteRefused('in-use')+ command = state.get('command', [])+ if isinstance(command, list) and '--continue-from' in command:+ index = command.index('--continue-from') + 1+ if index < len(command) and isinstance(command[index], str) and Path(command[index]).resolve() == path:+ raise DeleteRefused('continuation-in-use')+ # Content addressing needs the MP4 while it still exists. Optional+ # cleanup may fail, including in lightweight CI without PyAV.+ identifier = None+ try:+ from .continuation_store import video_id, delete_id+ identifier = video_id(path)+ except ModuleNotFoundError as error:+ if error.name not in ('av', __package__ + '.continuation_store'):+ raise+ except Exception as error:+ logging.warning('[FreeVideo] Continuation cleanup failed (%s).', type(error).__name__)trash = root / '.deleted'trash.mkdir(exist_ok=True)if not _plain(trash):@@ -433,6 +490,11 @@ def delete_video(output_directory, identity):folder.rename(target)except OSError as error:raise DeleteRefused('in-use') from error+ if identifier is not None:+ try:+ delete_id(identifier)+ except Exception as error:+ logging.warning('[FreeVideo] Continuation cleanup failed (%s).', type(error).__name__)freed, left = _remove(target)# A result-cache row naming this creation can no longer be reused.for index in (root / '.result-cache').glob('*.json'):@@ -476,12 +538,16 @@ def register():try:canvas = geometry(int(request.query['width']), int(request.query['height']),seconds=float(request.query['seconds']))+ from .two_pass import plan, sampling_canvas+ canvas = sampling_canvas(canvas)[0]+ task = request.query.get('task', 't2va')_, machine = installation()device = machine.get('device_identity') if machine.get('device_backend') == 'mps' else machine.get('gpu_uuid')rows = await asyncio.to_thread(local_records, folder_paths.get_output_directory(), device)- task = request.query.get('task', 't2va')adapters = request.query.get('adapters') == '1'- result = {name: {str(steps): estimate(rows, canvas, base_steps=steps, two_pass=enabled,+ # A small canvas runs in one pass whatever the switch says.+ result = {name: {str(steps): estimate(rows, canvas, base_steps=steps,+ two_pass=plan(canvas, enabled, task, base_steps=steps)['enabled'],task=task, adapters=adapters)for steps in ((8,) if enabled else (8, 12, 16, 20))}for name, enabled in (('single', False), ('two_pass', True))}@@ -516,7 +582,8 @@ def register():try:body = await request.json()result = await asyncio.to_thread(delete_video, folder_paths.get_output_directory(),- body.get('id') if isinstance(body, dict) else None)+ body.get('id') if isinstance(body, dict) else None,+ queue=getattr(server, 'prompt_queue', None))except DeleteRefused as error:return web.json_response(dict(deleted=False, reason=error.reason, kept=error.kept[:20]), status=409)except (OSError, ValueError, TypeError):diff --git a/freevideo_engine/comfy_nodes.py b/freevideo_engine/comfy_nodes.pyindex d6530a4..aa6518c 100644--- a/freevideo_engine/comfy_nodes.py+++ b/freevideo_engine/comfy_nodes.py@@ -5,6 +5,7 @@ from pathlib import Pathfrom comfy_api.latest import ComfyExtension, InputImpl, io, uifrom . import comfy_bridge+from .comfy_continuation import request_optionsfrom .default_prompt import DEFAULT_PROMPTReferences = io.Custom('FREEVIDEO_REFERENCES')@@ -55,6 +56,12 @@ class FreeVideoGenerate(io.ComfyNode):io.String.Input('refine_from', display_name='Second pass of preview', default='', optional=True, advanced=True,socketless=True, tooltip='Set by the Run second pass button: the preview video to continue. '"The second pass uses the preview's own prompt, seed, size and inputs."),+ io.String.Input('continue_from', display_name='Continue from video', default='', optional=True, advanced=True,+ tooltip='For long videos generated in segments: continue after this MP4. Use its ComfyUI output '+ 'subfolder/filename or an absolute path inside ComfyUI output or input.'),+ io.Int.Input('frames', display_name='Total frames', default=0, min=0, max=2**31-1, optional=True, advanced=True,+ tooltip='For long videos generated in segments: 0 uses Duration; otherwise use 5 + 17n, at least 39. '+ 'Includes the 22 overlap frames when continuing; the saved MP4 contains only new frames.'),],outputs=[io.Video.Output('video'), io.String.Output('report', display_name='Report JSON')],hidden=[io.Hidden.unique_id, io.Hidden.prompt, io.Hidden.extra_pnginfo],@@ -64,7 +71,22 @@ class FreeVideoGenerate(io.ComfyNode):@classmethoddef validate_inputs(cls, text, width, height, seconds, seed, **kwargs):try:- comfy_bridge.validate_request(text, width, height, seconds, seed)+ options = request_options(kwargs.get('continue_from', ''), kwargs.get('frames', 0))+ if options.get('continue_from'):+ # Use presence checks: tensor inputs have no scalar truth value.+ assets = kwargs.get('media')+ connected = assets.get('_connected', {}) if isinstance(assets, dict) else {}+ media = dict(first=kwargs.get('first') is not None or connected.get('first') is not None,+ last=kwargs.get('last') is not None or connected.get('last') is not None,+ references=bool(kwargs.get('references')) or any(+ connected.get(key) is not None for key in ('reference', 'reference_audio')),+ conditioning_info=kwargs.get('conditioning') is not None)+ if isinstance(assets, dict):+ for key in ('first', 'last', 'references', 'conditioning_info'):+ media[key] = media[key] or bool(assets.get(key))+ options.update(two_pass=kwargs.get('two_pass', True), preview=kwargs.get('preview', False),+ refine_from=kwargs.get('refine_from'), media=media)+ comfy_bridge.validate_request(text, width, height, seconds, seed, **options)if not kwargs.get('refine_from'):from .two_pass import validate_stepsvalidate_steps(kwargs.get('base_steps', 8), kwargs.get('refine_steps', 3), kwargs.get('two_pass', True))@@ -84,11 +106,13 @@ class FreeVideoGenerate(io.ComfyNode):@classmethoddef execute(cls, text, width, height, seconds, seed, first=None, last=None,references=None, loras=None, conditioning=None, media=None, two_pass=True,- force_regenerate=False, base_steps=8, refine_steps=3, preview=False, refine_from=''):+ force_regenerate=False, base_steps=8, refine_steps=3, preview=False, refine_from='',+ continue_from='', frames=0):from server import PromptServerfrom .comfy_chain import block_context, block_finished, report_fieldsnode_id = cls.hidden.unique_idchain = block_context(PromptServer.instance, node_id)+ options = request_options(continue_from, frames)from .two_pass import validate_stepsif not refine_from:validate_steps(base_steps, refine_steps, two_pass)@@ -107,7 +131,20 @@ class FreeVideoGenerate(io.ComfyNode):prewarm = {}result_reused = [False]result_report = [None]- bar = ProgressBar(base_steps + (refine_steps if two_pass and not preview else 0), node_id=node_id)+ total_steps = base_steps + (refine_steps if two_pass and not preview else 0)+ if two_pass and not preview and not refine_from:+ # A small canvas runs in one pass even with two-pass on.+ from .geometry import geometry+ from .two_pass import plan, sampling_canvas+ try:+ # Pre-encoded conditioning is tied to the requested canvas, so it is never rendered larger.+ sampled = sampling_canvas(geometry(width, height, seconds=seconds),+ conditioned=conditioning is not None)[0]+ total_steps = plan(sampled, True, base_steps=base_steps,+ refine_steps=refine_steps)['total_steps']+ except ValueError:+ pass+ bar = ProgressBar(total_steps, node_id=node_id)last_message = [None]last_count = [None]# Without FreeVideo's page scripts the nodes still generate; say why the@@ -174,6 +211,7 @@ class FreeVideoGenerate(io.ComfyNode):interrupted=memory.throw_exception_if_processing_interrupted, release_models=release,export_inputs=lambda run, canvas: export(run, canvas, first=first, last=last,references=references, loras=loras, conditioning=conditioning, assets=media),+ **options,**({'report_extra': {'chain': report_fields(chain)}} if chain is not None else {}))relative = output.relative_to(output_root)report = output.with_suffix('.request.json').read_text(encoding='utf-8')@@ -182,6 +220,8 @@ class FreeVideoGenerate(io.ComfyNode):from .comfy_assets import output_summary, saved_videopreview = ui.PreviewVideo([saved_video(output, output_root)]).as_dict()preview['freevideo_summary'] = [output_summary(measured, relative)]+ if 'continuation' in preview['freevideo_summary'][0] and options.get('frames'):+ preview['freevideo_summary'][0]['continuation']['requested_frames'] = options['frames']preview['freevideo_summary'][0]['result_cache_hit'] = result_reused[0]except BaseException as error:cancelled = isinstance(error, KeyboardInterrupt) or type(error).__name__ in ('InterruptProcessingException', 'CancelledError')diff --git a/freevideo_engine/continuation.py b/freevideo_engine/continuation.pynew file mode 100644index 0000000..20171cf--- /dev/null+++ b/freevideo_engine/continuation.py@@ -0,0 +1,306 @@+"""Fixed prefix context on the existing two-pass text sampler's clocks."""+from contextlib import contextmanager+import base64+import hashlib+import json+import os+from pathlib import Path+import sys++OVERLAP_FRAMES = 22+LATENT_FRAMES = 7+LEAD_IN_TICKS = 15+LEAD_IN_SAMPLES = LEAD_IN_TICKS * 800+LEAD_IN_FADE = 240+LEAD_IN_RATE = 32000+CLEAN_T = 1.+AUDIO_CONTEXT_DEFAULT = 'clean'+ADALN_TASK = 'ref2va_audio'+VERSION = 1++MISSING = 'The previous video has no usable continuation data. Generate it again with this version of FreeVideo.'+SIZE_MISMATCH = 'Use the same width and height as the previous video.'+UNSUPPORTED = 'Video continuation requires full two-pass text generation on an NVIDIA GPU, without first frames, last frames or reference media.'+INVALID_FRAMES = 'Frame count must be 5 + 17n and at least 39 (39, 56, 73, 90, ...).'+INVALID_FILE = 'Choose an existing MP4 video using its absolute path.'+++def validate_audio_context(value):+ if value not in ('clean', 'renoise'):+ raise ValueError('FREEVIDEO_CONTINUATION_AUDIO must be clean or renoise')+ return value+++def audio_context():+ """Resolve once at engine admission, then carry the value in the request."""+ return validate_audio_context(os.environ.get('FREEVIDEO_CONTINUATION_AUDIO', AUDIO_CONTEXT_DEFAULT))+++def supported():+ """Platform capability, without loading Torch or probing a GPU."""+ if sys.platform == 'darwin':+ return False, 'macos'+ from .paths import data_root+ try:+ machine = json.loads((data_root() / 'machine.json').read_text(encoding='utf-8'))+ except (OSError, ValueError):+ machine = {}+ if not isinstance(machine, dict):+ machine = {}+ if machine.get('device_backend', 'cuda') != 'cuda':+ return False, 'unsupported_device'+ return True, None+++def validate_frames(frames):+ if type(frames) is not int or frames < 39 or (frames - 5) % 17:+ raise ValueError(INVALID_FRAMES)+++def validate_route(*, task='t2va', two_pass=True, preview=False, refine_from=None,+ media=None, backend=None):+ media = media or {}+ if (not supported()[0] or backend not in (None, 'cuda') or task != 't2va'+ or not two_pass or preview or refine_from+ or any(media.get(key) for key in ('first', 'last', 'references', 'conditioning_info'))):+ raise ValueError(UNSUPPORTED)+++def validate_path(video_path):+ path = Path(video_path)+ if not path.is_absolute() or path.suffix.lower() != '.mp4' or not path.is_file():+ raise ValueError(INVALID_FILE)+ return path+++def audio_origin(frame):+ return int(round(frame * 40 / 24))+++def identity(manifest):+ """Only weights and the persisted context contract determine compatibility."""+ dependencies = json.loads(Path(__file__).with_name('dependencies.json').read_text(encoding='utf-8'))+ weights = dict(groups=sorted((row['group'], row['sha256']) for row in manifest['groups']),+ online_lora={key: spec['modules'] for key, spec in manifest.get('online_lora', {}).get('blocks', {}).items()})+ weights = hashlib.sha256(json.dumps(weights, sort_keys=True).encode('utf-8')).hexdigest()+ return dict(version=VERSION, weights=weights, precision=manifest.get('precision'),+ vdn=dependencies['vdn']['commit'], diffusers=dependencies['diffusers']['patched_tree'],+ models=dependencies['models']['vdn_revision'])+++def prepare(video_path, canvas, manifest=None, sampling_plan=None, *, directory=None):+ from .continuation_store import load+ from safetensors.numpy import save+ value = load(validate_path(video_path), directory=directory)+ if value is None:+ raise ValueError(MISSING)+ from .continuation_store import TAG+ metadata = dict(value['metadata'], source_id=value['id'])+ metadata.pop('audio_lead_in', None)+ if 'storage_max_abs_error' in metadata:+ metadata['storage_max_abs_error'] = {key: error for key, error in+ metadata['storage_max_abs_error'].items() if key != 'audio_lead_in'}+ # Freeze the accepted record as immutable bytes. Only the caller's run+ # directory owns a persisted copy; store retention never reaches it.+ raw = save({key: value[key] for key in ('video_lo', 'video_hi', 'audio')},+ metadata={TAG: json.dumps(metadata, sort_keys=True)})+ request = dict(snapshot_data=base64.b64encode(raw).decode('ascii'),+ snapshot_sha256=hashlib.sha256(raw).hexdigest(), source_id=value['id'])+ return _prepare_snapshot(request, value, canvas, manifest, sampling_plan)+++def _prepare_snapshot(request, value, canvas, manifest=None, sampling_plan=None):+ validate_frames(canvas['frames'])+ metadata = value['metadata']+ if any(metadata['geometry'][key] != canvas[key] for key in ('width', 'height')):+ raise ValueError(SIZE_MISMATCH)+ if manifest is not None and metadata['identity'] != identity(manifest):+ raise ValueError(MISSING)+ if sampling_plan is not None and metadata['first_canvas'] != {+ key: sampling_plan['first'][key] for key in ('width', 'height')}:+ raise ValueError(MISSING)+ chain = metadata['chain']+ origin = chain['frame_origin'] + metadata['geometry']['frames'] - OVERLAP_FRAMES+ ticks = value['audio'].shape[2]+ return dict(request, overlap_frames=OVERLAP_FRAMES, new_frames=canvas['frames'] - OVERLAP_FRAMES,+ frame_origin=origin, audio_origin=audio_origin(origin), segment=chain['segment'] + 1,+ audio_latents=ticks)+++def _snapshot_bytes(request):+ from .continuation_store import MAX_BYTES+ try:+ if 'snapshot_data' in request:+ if len(request['snapshot_data']) > (MAX_BYTES + 2) // 3 * 4:+ raise ValueError(MISSING)+ raw = base64.b64decode(request['snapshot_data'], validate=True)+ else:+ with Path(request['snapshot']).open('rb') as source:+ raw = source.read(MAX_BYTES + 1)+ if len(raw) > MAX_BYTES or hashlib.sha256(raw).hexdigest() != request['snapshot_sha256']:+ raise ValueError(MISSING)+ return raw+ except (OSError, ValueError, KeyError, TypeError):+ raise ValueError(MISSING) from None+++def _snapshot_value(request):+ from .continuation_store import read_bytes+ from safetensors import SafetensorError+ try:+ return read_bytes(_snapshot_bytes(request))+ except (OSError, ValueError, KeyError, TypeError, AttributeError, OverflowError, SafetensorError):+ raise ValueError(MISSING) from None+++def persist_snapshot(request, path):+ """Publish one exact, read-only copy for the managed CLI and all retries."""+ raw = _snapshot_bytes(request)+ path = Path(path)+ with path.open('xb') as target:+ target.write(raw)+ path.chmod(0o400)+ return dict({key: value for key, value in request.items() if key != 'snapshot_data'},+ snapshot=str(path.resolve()))+++def restore_snapshot(path, digest, canvas):+ request = dict(snapshot=str(Path(path).resolve()), snapshot_sha256=digest)+ value = _snapshot_value(request)+ from .continuation_store import _path+ source_id = value['metadata'].get('source_id')+ try:+ _path(source_id) # Validate the content identifier, without reading storage.+ except ValueError:+ raise ValueError(MISSING) from None+ return _prepare_snapshot(dict(request, source_id=source_id), value, canvas)+++def validate_snapshot(request, canvas, manifest=None, sampling_plan=None):+ """Later admission checks inspect the accepted snapshot, never the store."""+ return _prepare_snapshot(request, _snapshot_value(request), canvas, manifest, sampling_plan)+++def summary(request):+ return dict({key: request[key] for key in ('overlap_frames', 'new_frames', 'frame_origin', 'audio_origin', 'segment')},+ audio_lead_in_samples=request.get('audio_lead_in_samples', 0))+++def load(request, stage):+ import torch+ value = _snapshot_value(request)+ # Each pass receives writable tensors of its own; sampling cannot mutate+ # the immutable snapshot used by the next pass or retry.+ return dict(audio_context=validate_audio_context(request.get('audio_context', AUDIO_CONTEXT_DEFAULT)),+ video=torch.from_numpy(value['video_lo' if stage == 'first' else 'video_hi'].copy()),+ audio=torch.from_numpy(value['audio'].copy()))+++def tail(video):+ # clone avoids keeping the entire clip's storage behind a small view.+ return video[:, :, -LATENT_FRAMES:].detach().cpu().clone()+++def tail_data(first, video, audio, canvas, sampling_plan, manifest, request=None):+ chain = ({key: request[key] for key in ('segment', 'frame_origin', 'audio_origin')} if request+ else dict(segment=1, frame_origin=0, audio_origin=0))+ start = audio_origin(chain['frame_origin'] + canvas['frames'] - OVERLAP_FRAMES) - chain['audio_origin']+ return dict(video_lo=first, video_hi=tail(video), audio=audio[:, :, start:].detach().cpu().clone(),+ metadata=dict(identity=identity(manifest), geometry={key: canvas[key] for key in ('width', 'height', 'frames')},+ first_canvas={key: sampling_plan['first'][key] for key in ('width', 'height')}, chain=chain,+ **({'source_id': request['source_id']} if request and 'source_id' in request else {})))+++def capture_audio_lead_in(audio, request, sample_rate):+ """Copy only the seam context from decoded channel-first audio, before trimming."""+ if request is None or sample_rate != LEAD_IN_RATE:+ return None+ ticks = request.get('audio_latents')+ if type(ticks) is not int or ticks < LEAD_IN_TICKS:+ return None+ end = ticks * 800+ if audio.ndim != 2 or audio.shape[0] != 2 or audio.shape[1] < end + LEAD_IN_FADE:+ return None+ import numpy as np+ value = audio[:, end - LEAD_IN_SAMPLES:end + LEAD_IN_FADE]+ if hasattr(value, 'detach'):+ value = value.detach().float().cpu().numpy()+ return np.array(value.T, dtype=np.float32, order='C', copy=True)+++def trim_output(frames, audio, request):+ if request is None:+ return frames, audio+ return frames[OVERLAP_FRAMES:], audio[:, request['audio_latents'] * 800:]+++class Prefix:+ """Own one pass's small context; no changes to the sampler or its RNG.++ The pre-hook runs before ScheduleCursor and before offload hooks. The+ existing step callback restores the in-place video buffer after Euler's+ update. Audio is either kept clean or re-noised at each call, and restored+ on return. Only re-noising owns an independent RNG.+ """+ def __init__(self, transformer, data, seed, device):+ import torch+ from diffusers.modular_pipelines.minimax_h3.before_denoise import patchify_video_latents+ self.audio_context = validate_audio_context(data.get('audio_context', AUDIO_CONTEXT_DEFAULT))+ self.video = data['video'].to(device=device, dtype=torch.float32)+ self.audio = data['audio'].to(device=device, dtype=torch.float32)+ if (self.video.ndim != 5 or self.video.shape[:3] != (1, transformer.config.in_channels, LATENT_FRAMES)+ or self.audio.ndim != 3 or self.audio.shape[:2] != (2, 32)):+ raise ValueError(MISSING)+ self.video_rows = patchify_video_latents(self.video, tuple(transformer.config.patch_size))+ self.audio_rows = self.audio.permute(0, 2, 1).reshape(-1, 32).contiguous()+ if self.audio_context == 'renoise':+ generator = torch.Generator(device).manual_seed((seed + 1) % (1 << 64))+ self.noise = torch.randn(self.audio_rows.shape, generator=generator, device=device, dtype=torch.float32)+ from diffusers import MiniMaxH3Scheduler+ self.scheduler = MiniMaxH3Scheduler(shift=3.)+ self.current_video = None++ def before(self, model, args, kwargs):+ import torch+ video, audio = kwargs['hidden_states'][0], kwargs['audio_hidden_states'][0]+ count, ticks = self.video_rows.shape[0], self.audio.shape[2]+ if video.shape[0] <= count or audio.shape[0] // 2 < ticks:+ raise ValueError(MISSING)+ self.current_video = video+ self.restore_video()+ audio_rows = torch.cat([torch.arange(ticks, device=audio.device) + channel * (audio.shape[0] // 2)+ for channel in range(2)])+ row_times = kwargs['timestep'][kwargs['timestep_indices']].clone()+ if self.audio_context == 'clean':+ audio[audio_rows] = self.audio_rows+ row_times[kwargs['audio_indices'][audio_rows]] = CLEAN_T+ else:+ audio_t = row_times[kwargs['audio_indices'][0]]+ # scale_noise uses H3's clean-at-one convention, not a standard DDPM clock.+ audio[audio_rows] = self.scheduler.scale_noise(self.audio_rows, audio_t, self.noise)+ row_times[kwargs['video_indices'][:count]] = CLEAN_T+ kwargs['timestep'], kwargs['timestep_indices'] = torch.unique(row_times, sorted=True, return_inverse=True)+ return args, kwargs++ def restore_video(self):+ if self.current_video is not None:+ self.current_video[:self.video_rows.shape[0]] = self.video_rows++ def finish(self, video, audio):+ video[:, :, :LATENT_FRAMES] = self.video+ audio[:, :, :self.audio.shape[2]] = self.audio+ return video, audio+++@contextmanager+def sampling(transformer, data, seed, device):+ if data is None:+ yield None+ return+ prefix = Prefix(transformer, data, seed, device)+ handle = transformer.register_forward_pre_hook(prefix.before, with_kwargs=True, prepend=True)+ try:+ yield prefix+ finally:+ handle.remove()+ prefix.current_video = Nonediff --git a/freevideo_engine/continuation_store.py b/freevideo_engine/continuation_store.pynew file mode 100644index 0000000..c03b7f9--- /dev/null+++ b/freevideo_engine/continuation_store.py@@ -0,0 +1,201 @@+"""Small, bounded continuation records in FreeVideo's own data directory."""+import base64+import hashlib+import json+import logging+import os+from pathlib import Path+import re+import uuid++# Normal 1344x768 records are under 2 MiB. Larger requested canvases keep the+# same seven frames; the safety bound must not reduce their resolution.+MAX_BYTES = 64 * 1024 * 1024+TAG = 'freevideo.continuation'+++def root():+ from .paths import data_root+ return data_root() / 'continuations'+++def video_id(video_path):+ """Bind to media packets, so rename, move and workflow remux keep the ID.++ Hash each stream independently: interleaving and MP4 metadata are not+ content. A replaced or re-encoded file no longer selects the old record.+ """+ from .comfy_metadata import _media+ return hashlib.sha256(json.dumps(_media(video_path), sort_keys=True).encode('utf-8')).hexdigest()+++def _path(identifier, directory=None):+ if not isinstance(identifier, str) or not re.fullmatch('[0-9a-f]{64}', identifier):+ raise ValueError('Invalid continuation identifier')+ return (Path(directory) if directory is not None else root()) / (identifier + '.safetensors')+++def write(path, data):+ """Atomic tensor archive, also used by the existing sampling retry checkpoints."""+ import numpy as np+ from safetensors.numpy import save_file+ tensors, errors = {}, {}+ for key in ('video_lo', 'video_hi', 'audio', *(['audio_lead_in'] if 'audio_lead_in' in data else [])):+ value = data[key]+ if hasattr(value, 'detach'):+ value = value.detach().float().cpu().numpy()+ value = np.asarray(value, dtype=np.float32)+ if not np.isfinite(value).all():+ raise ValueError('Cannot save non-finite continuation data')+ with np.errstate(over='ignore'):+ packed = value.astype(np.float16)+ if not np.isfinite(packed).all():+ packed = value+ packed = np.ascontiguousarray(packed)+ if key != 'audio_lead_in':+ tensors[key] = packed+ errors[key] = float(np.max(np.abs(value - packed.astype(np.float32))))+ metadata = dict(data['metadata'], storage_max_abs_error=errors)+ if 'audio_lead_in' in data:+ from .continuation import LEAD_IN_RATE+ # Old readers validate every tensor name. Optional export audio belongs+ # in metadata, which those readers already accept and ignore.+ metadata['audio_lead_in'] = dict(sample_rate=LEAD_IN_RATE,+ dtype=packed.dtype.str, shape=list(packed.shape),+ samples=base64.b64encode(packed.tobytes()).decode('ascii'))+ path = Path(path)+ path.parent.mkdir(parents=True, exist_ok=True)+ temporary = path.with_name(path.name + '.' + uuid.uuid4().hex + '.partial')+ try:+ save_file(tensors, str(temporary), metadata={TAG: json.dumps(metadata, sort_keys=True)})+ if temporary.stat().st_size > MAX_BYTES:+ raise ValueError('Continuation data exceeds the storage limit')+ os.replace(temporary, path)+ finally:+ temporary.unlink(missing_ok=True)+++def read(path):+ path = Path(path)+ with path.open('rb') as source:+ raw = source.read(MAX_BYTES + 1)+ return read_bytes(raw)+++def read_bytes(raw):+ import numpy as np+ from safetensors.numpy import load+ from .continuation import (VERSION, LATENT_FRAMES, audio_origin, OVERLAP_FRAMES,+ LEAD_IN_SAMPLES, LEAD_IN_FADE, LEAD_IN_RATE)+ if len(raw) > MAX_BYTES:+ raise ValueError('Oversized continuation data')+ tensors = load(raw)+ header_size = int.from_bytes(raw[:8], 'little')+ metadata = json.loads(json.loads(raw[8:8 + header_size])['__metadata__'][TAG])+ canvas, first, chain = (metadata[key] for key in ('geometry', 'first_canvas', 'chain'))+ version = metadata['identity']['version']+ if (type(version) is not int or version != VERSION+ or any(type(canvas[key]) is not int for key in ('width', 'height', 'frames'))+ or any(canvas[key] < 256 or canvas[key] % 32 for key in ('width', 'height'))+ or any(type(first[key]) is not int or first[key] < 256 or first[key] % 32+ or first[key] > canvas[key] for key in ('width', 'height'))+ or canvas['frames'] < 39 or canvas['frames'] % 17 != 5+ or any(type(chain[key]) is not int for key in ('segment', 'frame_origin', 'audio_origin'))+ or chain['segment'] < 1 or chain['frame_origin'] < 0 or chain['audio_origin'] < 0+ or chain['segment'] == 1 and (chain['frame_origin'] != 0 or chain['audio_origin'] != 0)+ or chain['audio_origin'] != audio_origin(chain['frame_origin'])):+ raise ValueError('Invalid continuation metadata')+ ticks = round(canvas['frames'] * 40 / 24) - (+ audio_origin(chain['frame_origin'] + canvas['frames'] - OVERLAP_FRAMES) - chain['audio_origin'])+ expected = dict(video_hi=(1, 24, LATENT_FRAMES, canvas['height'] // 16, canvas['width'] // 16),+ video_lo=(1, 24, LATENT_FRAMES, first['height'] // 16, first['width'] // 16),+ audio=(2, 32, ticks))+ if not 0 < ticks <= 38:+ raise ValueError('Invalid continuation audio clock')+ if set(tensors) != set(expected):+ raise ValueError('Invalid continuation tensors')+ for key, tensor in tensors.items():+ if tensor.shape != expected[key] or tensor.dtype not in (np.float16, np.float32) or not np.isfinite(tensor).all():+ raise ValueError('Invalid continuation tensor')+ if 'audio_lead_in' in metadata:+ source_id = metadata.get('source_id')+ if not isinstance(source_id, str) or not re.fullmatch('[0-9a-f]{64}', source_id):+ raise ValueError('Invalid continuation audio source')+ lead = metadata['audio_lead_in']+ if (not isinstance(lead, dict) or type(lead.get('sample_rate')) is not int+ or lead['sample_rate'] != LEAD_IN_RATE+ or lead.get('shape') != [LEAD_IN_SAMPLES + LEAD_IN_FADE, 2]+ or any(type(size) is not int for size in lead['shape'])+ or lead.get('dtype') not in ('<f2', '>f2', '<f4', '>f4')):+ raise ValueError('Invalid continuation audio format')+ dtype = np.dtype(lead['dtype'])+ byte_count = (LEAD_IN_SAMPLES + LEAD_IN_FADE) * 2 * dtype.itemsize+ encoded = lead.get('samples')+ if not isinstance(encoded, str) or len(encoded) != (byte_count + 2) // 3 * 4:+ raise ValueError('Invalid continuation audio size')+ pcm = base64.b64decode(encoded, validate=True)+ if len(pcm) != byte_count:+ raise ValueError('Invalid continuation audio size')+ value = np.frombuffer(pcm, dtype=dtype).reshape(LEAD_IN_SAMPLES + LEAD_IN_FADE, 2)+ if not np.isfinite(value).all():+ raise ValueError('Invalid continuation audio samples')+ tensors['audio_lead_in'] = value+ return dict(tensors, metadata=metadata)+++def save(video_path, data):+ identifier = video_id(video_path)+ write(_path(identifier), data)+ result = dict(id=identifier, bytes=_path(identifier).stat().st_size)+ try:+ prune()+ except Exception as error:+ if isinstance(error, MemoryError) or type(error).__name__ in ('OutOfMemoryError', 'CancelledError', 'InterruptProcessingException'):+ raise+ logging.warning('[FreeVideo] Continuation retention failed (%s).', type(error).__name__)+ return result+++def load_id(identifier, *, directory=None):+ from safetensors import SafetensorError+ try:+ path = _path(identifier, directory)+ value = read(path)+ # Retention follows successful use. Losing a concurrent cleanup race+ # cannot invalidate the data already read by this request.+ try:+ os.utime(path, None)+ except OSError:+ pass+ return dict(value, id=identifier)+ except (OSError, ValueError, KeyError, TypeError, AttributeError, OverflowError, SafetensorError):+ return None+++def load(video_path, *, directory=None):+ from av import FFmpegError+ try:+ return load_id(video_id(video_path), directory=directory)+ except (OSError, ValueError, FFmpegError):+ return None+++def delete(video_path):+ delete_id(video_id(video_path))+++def delete_id(identifier):+ _path(identifier).unlink(missing_ok=True)+++def prune(keep=64):+ if type(keep) is not int or keep < 0:+ raise ValueError('Continuation retention must be a nonnegative integer')+ records = []+ for path in root().glob('*.safetensors'):+ try:+ records.append((path.stat().st_mtime_ns, path))+ except FileNotFoundError:+ continue+ for _, path in sorted(records, reverse=True)[keep:]:+ path.unlink(missing_ok=True)diff --git a/freevideo_engine/decode.py b/freevideo_engine/decode.pyindex 6d2cf57..1827f3c 100644--- a/freevideo_engine/decode.py+++ b/freevideo_engine/decode.py@@ -14,7 +14,7 @@ from .vae_tiles import TileDecoder, compile_blocksdef decode_to_file(latents, audio_latents, out_path, *, base, offload=False, prefetch=True, tile_group=False,preload=False, pin_weights=False, artifacts_dir=None, phase_callback=None,stream_output=False, stream_weights=False, resident_blocks=0, model_cache=None,- linear_compute_cache=False):+ linear_compute_cache=False, continuation=None, audio_lead_in_callback=None, output_size=None):from diffusers import AutoencoderKLMiniMaxH3from diffusers.utils.export_utils import encode_videofrom src.inference.render import PIXEL_MEAN, PIXEL_STD, FPS@@ -161,6 +161,9 @@ def decode_to_file(latents, audio_latents, out_path, *, base, offload=False, prechunk = (video[:, :, start:start + 8].float() * pixel_std + pixel_mean).clamp_(0, 1)frames[start:start + chunk.shape[2]] = (chunk[0].permute(1, 2, 3, 0) * 255).round().to(torch.uint8)del video+ if continuation is not None:+ from .continuation import OVERLAP_FRAMES+ frames = frames[OVERLAP_FRAMES:]artifact_seconds = streamed_timings.get('decoded_artifact_save_seconds', 0.)if artifacts_dir:import numpy as np@@ -168,8 +171,11 @@ def decode_to_file(latents, audio_latents, out_path, *, base, offload=False, pretick = time.perf_counter()artifacts_dir = Path(artifacts_dir)artifacts_dir.mkdir(parents=True, exist_ok=True)- if not stream_output:- np.save(artifacts_dir / 'rgb.npy', frames.numpy(), allow_pickle=False)+ if not stream_output or continuation is not None:+ # A streamed mapping still contains the overlap. Replace its+ # retained artifact after the mapping closes, below.+ rgb_path = artifacts_dir / ('rgb-new.npy' if stream_output else 'rgb.npy')+ np.save(rgb_path, frames.numpy() if hasattr(frames, 'numpy') else frames, allow_pickle=False)artifact_seconds += time.perf_counter() - tickaudio_start = time.perf_counter()phase('audio_load_decode')@@ -192,6 +198,11 @@ def decode_to_file(latents, audio_latents, out_path, *, base, offload=False, preaudio = audio_vae.decode(audio_latents * audio_std + audio_mean, return_dict=False)[0]audio = audio.float().permute(1, 0, 2)[0].cpu()rate = audio_vae.config.sampling_rate+ if continuation is not None:+ if audio_lead_in_callback is not None:+ from .continuation import capture_audio_lead_in+ audio_lead_in_callback(capture_audio_lead_in(audio, continuation, rate))+ audio = audio[:, continuation['audio_latents'] * 800:]del audio_vae, audio_mean, audio_stdgc.collect()torch.cuda.empty_cache()@@ -215,13 +226,21 @@ def decode_to_file(latents, audio_latents, out_path, *, base, offload=False, preencode_started = time.perf_counter()phase('mp4_save')print(json.dumps({'event': 'decode_phase', 'phase': 'Saving MP4 and audio'}), flush=True)- encode_video(frames, fps=FPS, output_path=str(temporary), audio=audio, audio_sample_rate=rate)+ if output_size is not None:+ # The model rendered a larger size; only the picture is scaled.+ from .output_fit import fit_frames+ encode_video(fit_frames(frames, *output_size), fps=FPS, output_path=str(temporary), audio=audio,+ audio_sample_rate=rate)+ else:+ encode_video(frames, fps=FPS, output_path=str(temporary), audio=audio, audio_sample_rate=rate)temporary.replace(destination)frame_count = len(frames)finally:if rgb_mapping is not None:del framesrgb_mapping._mmap.close()+ if continuation is not None and artifacts_dir and (artifacts_dir / 'rgb-new.npy').is_file():+ (artifacts_dir / 'rgb-new.npy').replace(artifacts_dir / 'rgb.npy')return {'vae_load_seconds': load_seconds, 'video_decode_seconds': video_decode_seconds,'vae_linear_compute_cache': linear_compute_cache, 'vae_compute_cache_preparation': compute_cache_metrics,'resident_vae_cache_hit': vae_cache_hit, 'resident_audio_vae_cache_hit': audio_cache_hit,diff --git a/freevideo_engine/decode_resume.py b/freevideo_engine/decode_resume.pyindex 76c4e6a..ff764dc 100644--- a/freevideo_engine/decode_resume.py+++ b/freevideo_engine/decode_resume.py@@ -24,7 +24,7 @@ SAMPLE_FIELDS = ('config', 'sample_seconds', 'step_seconds', 'finite_latents', ''attention_backend_calls', 'head_execution', 'text_refinement', 'sampling_memory','load_seconds', 'load_breakdown', 'load_peak_allocated_bytes', 'load_peak_reserved_bytes','torch_peak_allocated_bytes', 'torch_peak_reserved_bytes', 'latent_save_seconds', 'sample_metrics_scope',- 'sampling_plan', 'sampling_passes', 'latent_upscale', 'refinement', 'fp8_kernel_calls')+ 'sampling_plan', 'sampling_passes', 'latent_upscale', 'refinement', 'fp8_kernel_calls', 'continuation', 'audio_context')def completed_sampling(metrics):@@ -94,10 +94,15 @@ def sampling_provenance(request):result['upscaler_sha256'] = _digest(request['upscaler_checkpoint'])if result['upscaler_sha256'] != request['sampling_plan']['upscaler_sha256']:raise ValueError('Latent upscaler differs from the planned checkpoint')+ if request.get('continuation') is not None:+ # A retry's identity binds the accepted bytes, without embedding the+ # snapshot again or making a relocation change computation identity.+ result['continuation'] = {key: value for key, value in request['continuation'].items()+ if key not in ('snapshot', 'snapshot_data')}return result-def load_saved_sampling(request, torch):+def load_saved_sampling(request, torch, *, continuation_tail_callback=None):"""Load verified CPU tensors; caller controls CUDA admission and transfer."""resume = request['resume_decode']if not isinstance(resume, dict) or any(not isinstance(resume.get(key), str) or not resume[key]@@ -146,6 +151,8 @@ def load_saved_sampling(request, torch):sampling_source_metrics=copy.deepcopy(source), load_seconds=0.,sampling_metrics_scope='Reused completed sampling; sampling times and peaks belong to the source attempt.',work_seconds_scope='Current decoder retry, including retained latent validation and transfer only.')+ if continuation_tail_callback is not None:+ continuation_tail_callback(value.get('continuation_tail'))return value['video'], value['audio'], metrics, Path(provenance['base'])@@ -279,7 +286,7 @@ def refine_checkpoint_complete(metrics):and all(type(value) in (int, float) and math.isfinite(value) and value >= 0 for value in seconds))-def load_refine_input(request, torch):+def load_refine_input(request, torch, *, continuation_tail_callback=None):"""Load a verified retained first pass on the CPU; the caller moves it to the GPU."""resume = request['resume_refine']if not isinstance(resume, dict) or any(not isinstance(resume.get(key), str) or not resume[key]@@ -320,4 +327,6 @@ def load_refine_input(request, torch):first_pass_source_attempt=previous.get('refine_source_attempt', prior.get('resource_attempt')),first_pass_scope='Reused the retained first pass, latent upscale and crop; their times and ''peaks belong to the source attempt.')+ if continuation_tail_callback is not None:+ continuation_tail_callback(value.get('continuation_first'))return value['video'], value['audio'], first, lifted, receiptdiff --git a/freevideo_engine/diagnostic_summary.py b/freevideo_engine/diagnostic_summary.pyindex e80bb53..0405480 100644--- a/freevideo_engine/diagnostic_summary.py+++ b/freevideo_engine/diagnostic_summary.py@@ -73,6 +73,12 @@ def summary_report(report):if type(summary.get(key)) is bool:result[key] = summary[key]result['geometry'] = _measurements(summary.get('geometry'), ('width','height','frames','fps','video_tokens','reference_video_tokens','reference_audio_tokens'))+ continuation = _measurements(summary.get('continuation') or engine.get('continuation'),+ ('overlap_frames', 'new_frames', 'frame_origin', 'audio_origin', 'segment', 'audio_lead_in_samples'))+ if type(continuation.get('audio_lead_in_samples')) is not int:+ continuation.pop('audio_lead_in_samples', None)+ if continuation:+ result['continuation'] = continuationshape = engine.get('conditioning_shape')if isinstance(shape, (list, tuple)) and len(shape) == 2 and all(type(x) is int and x > 0 for x in shape):result['geometry']['text_tokens'] = shape[0]diff --git a/freevideo_engine/execution_config.py b/freevideo_engine/execution_config.pyindex 75c9b9b..864d139 100644--- a/freevideo_engine/execution_config.py+++ b/freevideo_engine/execution_config.py@@ -18,12 +18,13 @@ ENGINE_DEFAULTS = MappingProxyType({'window_batch': 1, 'linear_compute': 'native-fp8', 'fp8_gemm': 'auto','window_varlen': False, 'varlen_smooth_k': True, 'task': 't2va','stream_weights': False, 'head_parallelism': 1, 'residual_offload': False,+ 'adaln_task': None,})DECODER_DEFAULTS = MappingProxyType({'offload': False, 'prefetch': True, 'tile_group': False,'preload': False, 'pin_weights': False,'stream_output': False, 'stream_weights': False,- 'resident_blocks': 0, 'linear_compute_cache': False,+ 'resident_blocks': 0, 'linear_compute_cache': False, 'continuation': None,})diff --git a/freevideo_engine/failure_details.py b/freevideo_engine/failure_details.pyindex f2b6902..bb2d15b 100644--- a/freevideo_engine/failure_details.py+++ b/freevideo_engine/failure_details.py@@ -287,6 +287,25 @@ def launcher_failure(value, *, zh=False, other_disk=False, disk_name='', can_repaction='展开详情或导出报告,查看完整检查结果。' if zh else'Open the details or export the report for the complete results.', kind='kernels')rules = (+ (r'The previous video has no usable continuation data', 'continuation-missing',+ ('This video cannot be continued', '这个视频暂时不能接续'),+ ('Generate the previous video again with this version of FreeVideo. Older videos, replaced files and expired continuation data cannot be used.',+ '请用当前版本的 FreeVideo 重新生成上一段视频。旧版本的视频、被替换的文件或已清理接续数据的视频不能接续。')),+ (r'Use the same width and height as the previous video', 'continuation-size',+ ('The video sizes differ', '两段视频的画面大小不一致'),+ ('Set the width and height to the previous video’s size.', '请把宽度和高度设为与上一段视频相同。')),+ (r'Frame count must be 5 \+ 17n and at least 39', 'continuation-frames',+ ('Choose a supported frame count', '请选择支持的帧数'),+ ('Use 39, 56, 73, 90, or another value reached by adding 17. This includes the 22 repeated frames when continuing a video.',+ '请使用 39、56、73、90 等每次增加 17 的帧数;接续时,这个数包含开头重复的 22 帧。')),+ (r'Video continuation requires full two-pass text generation', 'continuation-route',+ ('This generation mode cannot continue a video', '当前生成方式不支持视频接续'),+ ('Use full two-pass text generation on an NVIDIA GPU and remove first frames, last frames and reference media. Mac and preview generation are not supported.',+ '请在 NVIDIA 显卡上使用完整的文字生成两遍流程,移除首帧、尾帧和参考素材。Mac 和预览生成暂不支持接续。')),+ (r'Choose an existing MP4 video using its absolute path', 'continuation-file',+ ('Choose the previous video', '请选择上一段视频'),+ ('Select an existing MP4 video generated by FreeVideo. In ComfyUI, keep it inside the output or input folder.',+ '请选择 FreeVideo 生成且仍存在的 MP4 视频;在 ComfyUI 中,请把它放在输出或输入文件夹内。')),# An engine update waits for a video being generated, whoever started this installation's ComfyUI.(r'ComfyUI is running a job, so the engine update waits', 'update-busy',('A video is still generating', '还有视频正在生成'),diff --git a/freevideo_engine/generate.py b/freevideo_engine/generate.pyindex fed4e8c..ae15914 100644--- a/freevideo_engine/generate.py+++ b/freevideo_engine/generate.py@@ -342,8 +342,16 @@ def run(args):def _run(args):from .hardware import detectfrom .geometry import geometry+ from .continuation import (validate_frames, validate_route, prepare as prepare_continuation,+ summary as continuation_summary, validate_snapshot, persist_snapshot, restore_snapshot,+ audio_context)+ frames = getattr(args, 'frames', None)+ continue_from = getattr(args, 'continue_from', None)+ if continue_from is not None and frames is not None:+ validate_frames(frames)canvas = geometry(getattr(args, 'width', 1344), getattr(args, 'height', 768),- frames=getattr(args, 'frames', None), seconds=getattr(args, 'seconds', None))+ frames=frames, seconds=getattr(args, 'seconds', None))+ continuation = Nonefrom .two_pass import validate_stepsrequested_steps = getattr(args, 'base_steps', None)refine_steps = getattr(args, 'refine_steps', 3)@@ -358,6 +366,21 @@ def _run(args):canvas['steps'] = requested_stepsfrom .media_request import read as read_media, task_for, cache_keymedia = read_media(getattr(args, 'media', None))+ # Too small to sample cleanly: render larger, scale the picture down. Decided before anything+ # compares or stores the canvas, so every later check sees the size that is sampled.+ from .two_pass import sampling_canvas+ canvas, output_size = sampling_canvas(canvas, staged=bool(preview or refine_source), media=media,+ conditioned=bool(args.conditioning))+ if continue_from is not None:+ validate_route(task=getattr(args, 'task', None) or 't2va', two_pass=two_pass,+ preview=preview, refine_from=getattr(args, 'refine_from', None), media=media)+ # Reject absent/mismatched context before text encoding or model loading.+ if getattr(args, 'continuation_snapshot', None):+ continuation = restore_snapshot(args.continuation_snapshot,+ getattr(args, 'continuation_snapshot_sha256', None), canvas)+ else:+ continuation = prepare_continuation(continue_from, canvas)+ continuation = dict(continuation, audio_context=audio_context())active_loras = [row for row in media.get('loras', []) if row['strength'] != 0]if media:inferred_task = task_for(media)@@ -402,6 +425,11 @@ def _run(args):if args.out.suffix.lower() != '.mp4':raise ValueError('--out must name an MP4 file')manifest = json.loads((args.cache / 'manifest.json').read_text(encoding='utf-8'))+ if continuation is not None:+ from .two_pass import plan as continuation_plan+ validate_route(task=profile['engine'].get('task', 't2va'))+ continuation = validate_snapshot(continuation, canvas, None if active_loras else manifest,+ continuation_plan(canvas, two_pass, base_steps=base_steps, refine_steps=refine_steps))if manifest.get('precision') not in ('fp8', 'int8', 'bf16'): # BF16: the unquantized referenceraise ValueError('Select the prepared official FP8 or int8 cache')destination = args.out.resolve()@@ -410,10 +438,13 @@ def _run(args):destination.parent.mkdir(parents=True, exist_ok=True)artifacts = destination.with_suffix('.artifacts')artifacts.mkdir(exist_ok=False)+ if continuation is not None and 'snapshot' not in continuation:+ continuation = persist_snapshot(continuation, artifacts / 'continuation-source.safetensors')if args.prompt_file:shutil.copyfile(args.prompt_file, artifacts / 'prompt.txt')repo = Path(__file__).resolve().parents[1]report = {'profile': profile, 'seed': args.seed, 'success': False, 'geometry': canvas,+ **({'output_size': output_size} if output_size else {}),'resource_planning': planning,'artifacts': str(artifacts),'idle_resources': dict(automatic=not bool(args.profile), system=hardware.system,@@ -422,6 +453,9 @@ def _run(args):allocator_limit_bytes=allocator_limit_bytes),'reclaimable_resident_models': resident_credit,'encoder_mode': 'native H3 encoder library child' if args.prompt_file else 'preencoded shared conditioning'}+ if continuation is not None:+ report['continuation'] = continuation_summary(continuation)+ report['audio_context'] = continuation['audio_context']from .support_report import code_identity, write as write_debugreport['runtime_hardware'] = hardware.to_dict()report['runtime_code'] = code_identity()@@ -448,6 +482,9 @@ def _run(args):report['lora'] = prepared['report']args._lora_max_block_bytes = prepared['report'].get('max_block_bytes', 0)args._lora_root_bytes = prepared['report'].get('root_bytes', 0)+ if continuation is not None:+ continuation = validate_snapshot(continuation, canvas,+ json.loads((args.cache / 'manifest.json').read_text(encoding='utf-8')))if args._lora_max_block_bytes or args._lora_root_bytes:profile.setdefault('policy', {})['lora_max_block_bytes'] = args._lora_max_block_bytesprofile['policy']['lora_root_bytes'] = args._lora_root_bytes@@ -599,8 +636,13 @@ def _run(args):raise FileNotFoundError(condition)from .two_pass import plan as plan_sampling, ensure_checkpointsampling_plan = plan_sampling(canvas, two_pass, profile['engine'].get('task', 't2va'),- base_steps=base_steps, refine_steps=refine_steps)+ base_steps=base_steps, refine_steps=refine_steps,+ staged=bool(preview or refine_source))report['sampling_plan'] = sampling_plan+ if continuation is not None:+ validate_route(task=profile['engine'].get('task', 't2va'))+ continuation = validate_snapshot(continuation, canvas,+ json.loads((args.cache / 'manifest.json').read_text(encoding='utf-8')), sampling_plan)if preview:report['preview'] = dict(geometry=dict(sampling_plan['first'], fps=canvas['fps']))if refine_source:@@ -690,9 +732,12 @@ def _run(args):'gpu_budget_bytes': round(profile['gpu_budget_gb'] * 1e9), 'engine_options': profile['engine'],'decoder_options': profile['decoder'], 'output': str(destination),'geometry': canvas, 'artifacts': str(artifacts),+ **({'output_size': output_size} if output_size else {}),'sampling_plan': sampling_plan, 'upscaler_checkpoint': upscaler_checkpoint,'automatic_pass_cache': not bool(args.profile),'metrics': str(destination.with_suffix('.engine.json'))}+ if continuation is not None:+ request['continuation'] = continuationif preview:request['preview'] = Trueif allocator_limit_bytes is not None:@@ -713,6 +758,9 @@ def _run(args):def launch(selected, attempt):nonlocal preview_passselected_env = inference_environment(engine_env, selected['inference_ram_budget_gb'] * 1e9)+ if continuation is not None:+ from .continuation import ADALN_TASK+ selected['engine'] = dict(selected['engine'], adaln_task=ADALN_TASK)request.update(engine_options=selected['engine'], decoder_options=selected['decoder'],ram_budget_bytes=round(selected['inference_ram_budget_gb'] * 1e9),ram_budget_is_estimate=ram_budget_is_estimate(args),@@ -856,6 +904,9 @@ def _run(args):archive=archive, report=report, persist=persist, on_retry=retry,automatic=not args.profile or getattr(args, 'recover_placement', False),max_retries=getattr(args, 'resource_retries', 2))+ if continuation is not None:+ report['continuation']['audio_lead_in_samples'] = report['video'].get('continuation', {}).get(+ 'audio_lead_in_samples', 0)if preview:# An upscale validates this receipt beside the retained first pass.shutil.copyfile(destination.with_suffix('.engine.json'), artifacts / 'first-pass.engine.json')diff --git a/freevideo_engine/keyframes.py b/freevideo_engine/keyframes.pyindex 9b9bbf7..ed3131a 100644--- a/freevideo_engine/keyframes.py+++ b/freevideo_engine/keyframes.py@@ -12,7 +12,7 @@ def first_pass_conditions(conditions, target, canvas):"""from torch.nn import functional as Ffrom .two_pass import plan- sampling = plan(target)+ sampling = plan(target, staged=True)if any(canvas[key] != sampling['first'][key] for key in ('width', 'height', 'frames')):raise ValueError('Keyframe resize must match the planned first-pass canvas')anchors, latents = conditionsdiff --git a/freevideo_engine/macos_decode.py b/freevideo_engine/macos_decode.pyindex 497c320..4b329bd 100644--- a/freevideo_engine/macos_decode.py+++ b/freevideo_engine/macos_decode.py@@ -29,7 +29,7 @@ def tile_group_size(allocator_bytes, *, cache_weights=True):def decode_to_file(latents, audio_latents, output, *, base, artifacts_dir,- budget_bytes=4 * 2**30, reserve_bytes=2 * 2**30, cache_weights=True):+ budget_bytes=4 * 2**30, reserve_bytes=2 * 2**30, cache_weights=True, output_size=None):if type(cache_weights) is not bool:raise ValueError('Decoder weight caching must be explicitly enabled or disabled')from .macos_vdn import activate@@ -126,7 +126,13 @@ def decode_to_file(latents, audio_latents, output, *, base, artifacts_dir,phase('Saving MP4 and audio')output.parent.mkdir(parents=True, exist_ok=True)temporary = output.with_name(output.stem + '.partial' + output.suffix)- encode_video(frames, fps=FPS, output_path=str(temporary), audio=audio, audio_sample_rate=rate)+ if output_size is not None:+ # The model rendered a larger size; only the picture is scaled.+ from .output_fit import fit_frames+ encode_video(fit_frames(frames, *output_size), fps=FPS, output_path=str(temporary), audio=audio,+ audio_sample_rate=rate)+ else:+ encode_video(frames, fps=FPS, output_path=str(temporary), audio=audio, audio_sample_rate=rate)temporary.replace(output)return dict(device_backend='mps', output=str(output), frames=len(frames),audio_sample_rate=rate, audio_shape=list(audio.shape), elapsed_seconds=time.monotonic()-started,diff --git a/freevideo_engine/macos_generate.py b/freevideo_engine/macos_generate.pyindex e0630b0..89a9646 100644--- a/freevideo_engine/macos_generate.py+++ b/freevideo_engine/macos_generate.py@@ -161,11 +161,18 @@ def run(args):raise ValueError('Preencoded conditioning already includes media; use its conditioning_info')if args.prompt_file and task != 't2va' and not raw_media:raise ValueError('Native media encoding requires its input files')- sampling = plan(canvas, args.two_pass, task, base_steps=args.base_steps or 8, refine_steps=args.refine_steps)+ # Too small to sample cleanly: render larger, scale the picture down.+ from .two_pass import sampling_canvas+ canvas, output_size = sampling_canvas(canvas, staged=bool(preview or refine_source), media=media,+ conditioned=bool(args.conditioning))+ sampling = plan(canvas, args.two_pass, task, base_steps=args.base_steps or 8, refine_steps=args.refine_steps,+ staged=bool(preview or refine_source))from .paths import base_path, checkpoint_pathbase = str(Path(args.base or base_path()).resolve())adapters = [row for row in media.get('loras', []) if row['strength'] != 0]prepared_cache = Path(args.cache).resolve()+ if output_size:+ report['output_size'] = output_sizereport.update(geometry=canvas, sampling_plan=sampling, profile=dict(policy=resource,engine=dict(device_backend='mps', task=task, attention='mps', steps=sampling['base_steps'])),encoder_mode='native H3 encoder library child' if args.prompt_file else 'preencoded shared conditioning')@@ -286,6 +293,8 @@ def run(args):base=base, task=task,checkpoint=str(Path(args.checkpoint or checkpoint_path()).resolve()),seed=args.seed, canvas=canvas, sampling=sampling, resources=resource)+ if output_size:+ engine['output_size'] = [output_size['width'], output_size['height']]if preview:engine['preview'] = Trueif refine_source:diff --git a/freevideo_engine/macos_runtime.py b/freevideo_engine/macos_runtime.pyindex 9d29056..2c8eebe 100644--- a/freevideo_engine/macos_runtime.py+++ b/freevideo_engine/macos_runtime.py@@ -600,7 +600,7 @@ class Engine:def generate(self, conditioning, seed, *, width, height, frames, two_pass=True, refine_steps=3,upscaler_checkpoint=None, first_pass_saved=None, reuse_weights=False,- refinement_resident_bytes=None, phase_changed=None):+ refinement_resident_bytes=None, phase_changed=None, staged=False):"""Optional cross-pass weight lifetime, isolated to this one request.Product admission remains separate. Retention obeys each sample's live@@ -617,7 +617,7 @@ class Engine:options = dict(width=width, height=height, frames=frames, two_pass=two_pass,refine_steps=refine_steps, upscaler_checkpoint=upscaler_checkpoint,first_pass_saved=first_pass_saved, phase_changed=phase_changed,- refinement_resident_bytes=refinement_resident_bytes)+ refinement_resident_bytes=refinement_resident_bytes, staged=staged)if getattr(self, '_reuse_sampling_weights', False) or getattr(self, '_shared_residency', None) is not None:raise RuntimeError('Native sampling weight lifetimes cannot overlap')if not reuse_weights:@@ -635,7 +635,7 @@ class Engine:def _generate(self, conditioning, seed, *, width, height, frames, two_pass=True, refine_steps=3,upscaler_checkpoint=None, first_pass_saved=None,- refinement_resident_bytes=None, phase_changed=None):+ refinement_resident_bytes=None, phase_changed=None, staged=False):"""Use the shared canvas/schedule, including the original audio clock.Single-pass behavior remains explicit; memory pressure never disables@@ -649,7 +649,7 @@ class Engine:if self.canvas is not None and any(canvas[k] != self.canvas[k] for k in ('width', 'height', 'frames')):raise ValueError('Native generation differs from its loaded target canvas')sampling = plan(canvas, enabled=two_pass, task=self.task,- base_steps=self.steps, refine_steps=refine_steps)+ base_steps=self.steps, refine_steps=refine_steps, staged=staged)if phase_changed is not None:phase_changed('first-pass')video, audio, first = self.sample(conditioning, seed, **sampling['first'],diff --git a/freevideo_engine/macos_stages.py b/freevideo_engine/macos_stages.pyindex cfc0ad0..94501a8 100644--- a/freevideo_engine/macos_stages.py+++ b/freevideo_engine/macos_stages.py@@ -376,7 +376,8 @@ def worker(value):width=value['canvas']['width'], height=value['canvas']['height'],frames=value['canvas']['frames'], two_pass=True, refine_steps=sampling['refine_steps'],reuse_weights=True, refinement_resident_bytes=admission['refinement_resident_bytes'],- first_pass_saved=first_saved, phase_changed=changed)+ first_pass_saved=first_saved, phase_changed=changed,+ staged=sampling.get('staged', False))result.update(sampling_passes=measured['sampling_passes'],shared_sampling_residency=measured['shared_sampling_residency'],latent_upscale=measured['latent_upscale'], sampling_phase='latent-save')@@ -419,7 +420,8 @@ def worker(value):tick = time.monotonic()result['decode'] = decode_to_file(initial['video'], initial['audio'], value['output'],base=value['base'], artifacts_dir=artifacts,- budget_bytes=resource['allocator_capacity_bytes'], reserve_bytes=resource['reserve_bytes'])+ budget_bytes=resource['allocator_capacity_bytes'], reserve_bytes=resource['reserve_bytes'],+ output_size=value.get('output_size'))result.update(work_seconds=time.monotonic() - tick, success=True)returnelse:diff --git a/freevideo_engine/output_fit.py b/freevideo_engine/output_fit.pynew file mode 100644index 0000000..529a6e0--- /dev/null+++ b/freevideo_engine/output_fit.py@@ -0,0 +1,31 @@+"""Scale decoded frames to the requested size when the model rendered a larger one."""+++def fit_frames(frames, width, height, chunk=16):+ """Return uint8 frames of exactly height x width; audio is not involved.++ The rendered frames are centre-cropped to the requested shape, then reduced+ with an area filter, so every output pixel averages the rendered pixels it+ covers.+ """+ import numpy as np+ import torch+ import torch.nn.functional as functional+ count, source_height, source_width = frames.shape[0], frames.shape[1], frames.shape[2]+ if (source_width, source_height) == (width, height):+ return frames+ if source_width < width or source_height < height:+ raise ValueError('Rendered frames are smaller than the requested size')+ crop_width, crop_height = source_width, source_height+ if source_width * height > source_height * width:+ crop_width = min(source_width, max(width, round(source_height * width / height)))+ else:+ crop_height = min(source_height, max(height, round(source_width * height / width)))+ left, top = (source_width - crop_width) // 2, (source_height - crop_height) // 2+ result = torch.empty((count, height, width, 3), dtype=torch.uint8)+ for start in range(0, count, chunk):+ block = frames[start:start + chunk, top:top + crop_height, left:left + crop_width]+ block = torch.from_numpy(np.ascontiguousarray(block)) if not torch.is_tensor(block) else block+ scaled = functional.interpolate(block.permute(0, 3, 1, 2).float(), size=(height, width), mode='area')+ result[start:start + block.shape[0]] = scaled.round_().clamp_(0, 255).to(torch.uint8).permute(0, 2, 3, 1)+ return resultdiff --git a/freevideo_engine/prediction_cli.py b/freevideo_engine/prediction_cli.pyindex 7eb8a36..d61b5f4 100644--- a/freevideo_engine/prediction_cli.py+++ b/freevideo_engine/prediction_cli.py@@ -129,6 +129,8 @@ def main(argv=None):args = parser.parse_args(argv)try:canvas = geometry(args.width, args.height, frames=args.frames, seconds=args.seconds)+ from .two_pass import render_canvas+ canvas = render_canvas(canvas)[0]hardware = detect()if args.profile:profile = json.loads(args.profile.expanduser().read_text(encoding='utf-8'))diff --git a/freevideo_engine/refine_schedule.py b/freevideo_engine/refine_schedule.pyindex 8b147e7..f9101fd 100644--- a/freevideo_engine/refine_schedule.py+++ b/freevideo_engine/refine_schedule.py@@ -48,10 +48,11 @@ def modulation(engine, schedule):yield dict(schedule=schedule, table_cache_hits=0)returnmanifest = json.loads((Path(engine.cache) / 'manifest.json').read_text(encoding='utf-8'))- times = timesteps(device, engine.task)+ task = getattr(engine, 'adaln_task', engine.task)+ times = timesteps(device, task)cursor = ScheduleCursor(times)fetch = getattr(engine, 'fetch_tables', True)- cache = TableCache(engine.cache, manifest['source_id'], 3, task=engine.task,+ cache = TableCache(engine.cache, manifest['source_id'], 3, task=task,manifest=manifest, timesteps=times, channels=model.config.hidden_size, device='cpu', fetch=fetch)originals = []started, hits = time.perf_counter(), 0diff --git a/freevideo_engine/resource_history.py b/freevideo_engine/resource_history.pyindex 1b19e3a..62ca498 100644--- a/freevideo_engine/resource_history.py+++ b/freevideo_engine/resource_history.py@@ -86,6 +86,11 @@ def _canonical_config(config, purpose):for name in ('task', 'steps'):if name not in engine:resolved_engine.pop(name, None)+ # The ordinary task's schedule has the same historical computation identity.+ if resolved_engine.get('adaln_task') in (None, engine.get('task', 't2va')):+ resolved_engine.pop('adaln_task', None)+ if resolved_decoder.get('continuation') is None:+ resolved_decoder.pop('continuation', None)normalized_engine = _computation(resolved_engine)normalized_engine.pop('allocator_config', None)return {'engine': normalized_engine, 'decoder': _computation(resolved_decoder),diff --git a/freevideo_engine/runtime.py b/freevideo_engine/runtime.pyindex fb04071..5f92cae 100644--- a/freevideo_engine/runtime.py+++ b/freevideo_engine/runtime.py@@ -57,7 +57,7 @@ class Engine:fp8_gemm='auto', window_varlen=False, varlen_smooth_k=True,task='t2va', stream_weights=False, canvas=None, head_parallelism=1,residual_offload=False, device_backend=None, gpu_allocation_bytes=None,- fetch_tables=True):+ fetch_tables=True, adaln_task=None):self.device_backend = device_backend if device_backend is not None else get_backend()if gpu_allocation_bytes is not None and (type(gpu_allocation_bytes) is not int or gpu_allocation_bytes < 0):raise ValueError('GPU allocation limit must be a nonnegative byte count')@@ -72,6 +72,9 @@ class Engine:if task not in TASKS:raise ValueError('Unsupported Engine task: ' + str(task))self.task = task+ if adaln_task not in (None, task, 'ref2va_audio'):+ raise ValueError('Unsupported continuation modulation schedule')+ self.adaln_task = adaln_task or taskif type(residual_offload) is not bool:raise ValueError('Residual offload must be boolean')if residual_offload and (not projection_chunk or not inference_kernels):@@ -270,8 +273,8 @@ class Engine:self.schedule_hook = Noneembeddings = Noneif adaln_cache:- self.cursor = ScheduleCursor(schedule_timesteps(steps, task=task))- table_cache = (TableCache(self.cache, manifest['source_id'], steps, task=task, manifest=manifest,+ self.cursor = ScheduleCursor(schedule_timesteps(steps, task=self.adaln_task))+ table_cache = (TableCache(self.cache, manifest['source_id'], steps, task=self.adaln_task, manifest=manifest,timesteps=self.cursor.timesteps, channels=model.config.hidden_size, device='cpu',fetch=fetch_tables)if adaln_cache and (adaln_disk_cache or portable_adaln) else None)@@ -305,7 +308,7 @@ class Engine:_load_safetensors(self.cache / f'adaln/{index:02d}.safetensors').items()}if adaln_cache and not cache_hit:if embeddings is None:- _, embeddings = schedule_embeddings(model, steps, task=task)+ _, embeddings = schedule_embeddings(model, steps, task=self.adaln_task)block.load_state_dict({name: value.to(self.device_backend.device) for name, value in adaln.items()}, strict=False, assign=True)table = [block.adaln_proj(embedding) for embedding in embeddings]block.adaln_proj = CachedModulation(table, self.cursor)@@ -511,6 +514,8 @@ class Engine:'window_varlen': window_varlen,'varlen_smooth_k': varlen_smooth_k if window_varlen else None,'steps': steps, 'source_id': manifest['source_id']}+ if self.adaln_task != self.task:+ self.config['adaln_task'] = self.adaln_taskdef gpu_commit_reserve(self):"""Allocator room this request may still reserve, which WDDM will charge to commit."""@@ -534,10 +539,16 @@ class Engine:step_callback=None, sampling_complete_callback=None, initial_latents=None, refine_steps=None, refine_schedule=None,allow_smaller_canvas=False, progress_offset=0, progress_total=None,pass_cache_budget_bytes=None, gpu_reserve_bytes=0, pass_resident_blocks=None,- budget_refresh=None):+ budget_refresh=None, continuation=None):from src.inference.render import load_prompt, generate_latentsfrom .geometry import geometry, sampler_for_canvasrefining = initial_latents is not None+ if continuation is not None:+ from .continuation import validate_route+ validate_route(task=self.task)+ if tuple(continuation['video'].shape[-2:]) != (height // 16, width // 16):+ from .continuation import SIZE_MISMATCH+ raise ValueError(SIZE_MISMATCH)if refining != (refine_steps is not None):raise ValueError('Refinement requires both initial latents and a tail step count')if refining:@@ -578,6 +589,9 @@ class Engine:prompt, tags = value['prompt_embeds'].to(self.device_backend.device, torch.bfloat16), value['text_token_tags']else:prompt, tags, conditions = load_prompt(str(conditioning), self.device_backend.device)+ if continuation is not None and conditions:+ from .continuation import UNSUPPORTED+ raise ValueError(UNSUPPORTED)from .keyframes import validate_conditioningsource_canvas = self.canvas if allow_smaller_canvas and self.canvas is not None else canvasvalidate_conditioning(prompt, tags, conditions, self.task,@@ -631,6 +645,8 @@ class Engine:class StepTimes(list):def append(self, value):+ if prefix is not None:+ prefix.restore_video()super().append(value)count = getattr(offloader, 'drive_reads', None)total = count() if count is not None else None@@ -725,12 +741,16 @@ class Engine:if active_steps == 1:trigger_prefetch()checkpoint_seconds = 0.+ from .continuation import samplingtry:with progress.layers(self.transformer.transformer_blocks), self.device_backend.make_offloader(- self.offload_layers, prefetch=self.prefetch, weight_source=self.stream_weight_source) as offloader:+ self.offload_layers, prefetch=self.prefetch, weight_source=self.stream_weight_source) as offloader, sampling(+ self.transformer, continuation, seed, self.device_backend.device) as prefix:latents, audio = generate_latents(self.transformer, prompt, tags, frames,self.steps, seed, self.device_backend.device, step_seconds=step_seconds,conditions=conditions)+ if prefix is not None:+ latents, audio = prefix.finish(latents, audio)stats = offloader.stats()# StepTimes.append closes over the live offloader. Retaining# that list subclass in a receipt also retains its pinneddiff --git a/freevideo_engine/support_report.py b/freevideo_engine/support_report.pyindex 87b21c1..d9fa71b 100644--- a/freevideo_engine/support_report.py+++ b/freevideo_engine/support_report.py@@ -194,6 +194,7 @@ def summarize(report, engine, encoding):largest_category=ranked[0]['stage'] if ranked else None,step_seconds=steps, completed_nfe=len(steps),sampling_plan=engine.get('sampling_plan') or report.get('sampling_plan'),+ continuation=engine.get('continuation') or report.get('continuation'),sampling_passes=engine.get('sampling_passes'), latent_upscale=engine.get('latent_upscale'),sampling_reused=sampling_reused,sampling_memory=sampling_memory or None,@@ -248,7 +249,7 @@ def summarize(report, engine, encoding):REQUEST_FIELDS = ('seed', 'encoder_mode', 'profile', 'resource_planning', 'compatibility','reclaimable_resident_models', 'idle_resources', 'tuning', 'input_cache', 'resource_attempts','resource_prediction', 'resource_prediction_error', 'error', 'error_message', 'error_type',- 'resource_error', 'exception', 'encoding_failure', 'phase')+ 'resource_error', 'exception', 'encoding_failure', 'phase', 'continuation')def preview_receipts(output, read_json):diff --git a/freevideo_engine/two_pass.py b/freevideo_engine/two_pass.pyindex 67435be..865a558 100644--- a/freevideo_engine/two_pass.py+++ b/freevideo_engine/two_pass.py@@ -22,12 +22,77 @@ def validate_steps(base_steps=8, refine_steps=3, enabled=True):raise ValueError('Second-pass steps must be fewer than first-pass steps')-def plan(canvas, enabled=True, task='t2va', *, base_steps=8, refine_steps=3):+# A first pass below this many pixels is too small for the learned lift: about+# a third of the clips at 768x512 and every clip at 512x512 had coloured+# bursts, and none did from 480x288 (960x544) upward. Those sizes run in one pass.+SMALL_FIRST_PASS_PIXELS = 138240+++# A requested size below this many pixels shows the same bursts in any pass+# layout. Such a request is rendered at a larger size of nearly the same shape+# and scaled down to the size asked for.+SMALL_TARGET_PIXELS = 131072+# How far the rendered shape may differ from the requested one; the rendered+# frames are centre-cropped to the requested shape before scaling.+RENDER_SHAPE_TOLERANCE = 0.03+++def render_size(width, height):+ """Return (width, height) to render for a small requested size, else None.++ The smallest multiple-of-32 size of at least SMALL_FIRST_PASS_PIXELS whose+ shape is within RENDER_SHAPE_TOLERANCE of the requested shape.+ """+ from math import log+ from .geometry import geometry+ geometry(width, height)+ if width * height >= SMALL_TARGET_PIXELS:+ return None+ wanted = log(width / height)+ best = None+ for rw in range(256, 4097, 32):+ for rh in range(256, 4097, 32):+ pixels = rw * rh+ if pixels < SMALL_FIRST_PASS_PIXELS:+ continue+ if best is not None and pixels > best[0]:+ break+ error = abs(log(rw / rh) - wanted)+ if error <= RENDER_SHAPE_TOLERANCE and (best is None or (pixels, error) < best[:2]):+ best = (pixels, error, rw, rh)+ return best[2:] if best else None+++def render_canvas(canvas):+ """Return (canvas to render, requested size or None) for a geometry() dict."""+ render = render_size(canvas['width'], canvas['height'])+ if render is None:+ return canvas, None+ from .geometry import geometry+ larger = geometry(*render, frames=canvas['frames'])+ return (dict(canvas, width=larger['width'], height=larger['height'], video_tokens=larger['video_tokens']),+ dict(width=canvas['width'], height=canvas['height']))+++def sampling_canvas(canvas, *, staged=False, media=None, conditioned=False):+ """The one place that decides what canvas a request samples.++ A preview, the upscale of a preview and pre-encoded conditioning (tied to+ the requested canvas) keep the requested size.+ """+ if staged or conditioned or (media or {}).get('conditioning_info'):+ return canvas, None+ return render_canvas(canvas)+++def plan(canvas, enabled=True, task='t2va', *, base_steps=8, refine_steps=3, staged=False):"""Align the smaller canvas, lift, center-crop, then refine at the target.Odd multiples of 32 need up to 32 extra pixels before the latent crop.- Small canvases use a smaller factor or same-size refinement. Size never- disables a requested second pass; memory pressure cannot change its math.+ Small canvases use a smaller factor or same-size refinement. A first pass+ below SMALL_FIRST_PASS_PIXELS is replaced by one pass at the target size,+ unless the first pass itself is wanted (a preview or its upscale: staged).+ Memory pressure never changes this math."""from .geometry import geometryfrom .media_request import TASKS@@ -58,6 +123,12 @@ def plan(canvas, enabled=True, task='t2va', *, base_steps=8, refine_steps=3):top=(lift['height'] - target['height']) // 2,width=target['width'], height=target['height'])upscaling = first != lift+ if upscaling and first['width'] * first['height'] < SMALL_FIRST_PASS_PIXELS:+ if not staged:+ single = plan(canvas, False, task, base_steps=base_steps)+ return dict(single, requested=True,+ reason='Small canvas: one pass at the target size.')+ result['staged'] = Trueresult.update(enabled=True, mode='vdn%d-lbh-tail%d' % (base_steps, refine_steps),refine_steps=refine_steps, total_steps=base_steps + refine_steps,first=first, second=shape, upscale_target=lift, crop=crop,diff --git a/freevideo_engine/worker.py b/freevideo_engine/worker.pyindex da00c2e..de41b90 100644--- a/freevideo_engine/worker.py+++ b/freevideo_engine/worker.py@@ -87,10 +87,29 @@ def generate(request, resident=None):expected = plan(request['geometry'], request['sampling_plan']['requested'],request['engine_options'].get('task', 't2va'),base_steps=request['engine_options'].get('steps', 8),- refine_steps=request['sampling_plan']['refine_steps'] if request['sampling_plan']['enabled'] else 2)+ refine_steps=request['sampling_plan']['refine_steps'] if request['sampling_plan']['enabled'] else 3,+ staged=request['sampling_plan'].get('staged', False))if request['sampling_plan'] != expected:raise ValueError('Sampling plan does not match the requested canvas and task')metrics['sampling_plan'] = expected+ continuation = request.get('continuation')+ if continuation is not None:+ from .continuation import (validate_route, summary, ADALN_TASK, UNSUPPORTED,+ validate_audio_context, AUDIO_CONTEXT_DEFAULT)+ # A plan that fell back to one pass on a small canvas still has+ # the two-pass flag set and keeps its continuation; an explicit+ # single-pass request does not.+ validate_route(task=request['engine_options'].get('task', 't2va'),+ two_pass=bool(request.get('sampling_plan', {}).get('requested')),+ preview=request.get('preview', False), refine_from=request.get('resume_first_pass'))+ if isinstance(getattr(torch.version, 'hip', None), str):+ raise ValueError(UNSUPPORTED)+ continuation = dict(continuation,+ audio_context=validate_audio_context(continuation.get('audio_context', AUDIO_CONTEXT_DEFAULT)))+ request['continuation'] = continuation+ request['engine_options'] = dict(request['engine_options'], adaln_task=ADALN_TASK)+ metrics['continuation'] = summary(continuation)+ metrics['audio_context'] = continuation['audio_context']metrics['device_memory'] = device_memory_report(request['gpu_budget_bytes'], request.get('allocator_limit_bytes'),reserve_bytes=request.get('gpu_reserve_bytes', 0), capacity_trial=request.get('capacity_trial', False))if request.get('dynamic_gpu_budget') and metrics['device_memory'].get('windows_allocator_limit_enforced'):@@ -159,13 +178,48 @@ def generate(request, resident=None):metrics['conditioning_info'] = actualcanvas = request.get('geometry', {})artifacts = Path(request['artifacts']) if request.get('artifacts') else None+ # A two-pass request that runs as one pass (small canvases) continues+ # too: its first and final canvases are the same one, so one tail+ # serves both stages. An explicit single-pass request keeps nothing.+ plan_flags = request.get('sampling_plan') or {}+ continuable = (bool(plan_flags.get('enabled') or plan_flags.get('requested'))+ and options.get('task', 't2va') == 't2va' and not request.get('preview'))+ first_tail = continuation_data = None+ def tail_failure(error):+ from .adaptive import classify_failure+ if (isinstance(error, torch.cuda.OutOfMemoryError)+ or type(error).__name__ in ('InterruptProcessingException', 'CancelledError')+ or classify_failure(error)['kind'] in ('gpu_oom', 'cancelled')):+ raise error+ metrics['continuation_store'] = dict(saved=False, error=type(error).__name__)+ def restore_first(value):+ nonlocal first_tail+ first_tail = value++ def restore_tail(value):+ nonlocal continuation_data+ continuation_data = value++ def capture_first(video):+ nonlocal first_tail+ if not continuable:+ return+ try:+ from .continuation import tail+ first_tail = tail(video)+ except Exception as error:+ tail_failure(error)+ first_tail = Noneif resume:from .decode_resume import load_saved_samplingmetrics.update(phase='decode', decode_phase='latent_load')save(request['metrics'], metrics)tick = time.perf_counter()- latents, audio, sampled, base = load_saved_sampling(request, torch)+ latents, audio, sampled, base = load_saved_sampling(request, torch,+ **({'continuation_tail_callback': restore_tail} if continuable else {}))metrics.update(sampled, phase='decode', decode_phase='latent_transfer')+ if continuation is not None:+ metrics['continuation'] = summary(continuation)save(request['metrics'], metrics)print(json.dumps(dict(event='decode_resume', sampling_source_attempt=metrics['sampling_source_attempt'])), flush=True)fit_decoder()@@ -219,6 +273,7 @@ def generate(request, resident=None):print(json.dumps(dict(event='sample_finalize', phase=name)), flush=True)def sampling_complete(latents, audio, sampled):+ nonlocal continuation_datametrics.update(sampled, sampling_checkpoint_complete=False,sample_metrics_scope='Completed sampling before offloader cleanup; finalization is excluded.')metrics['sampling_memory'] = memory_diagnostics.result()@@ -226,13 +281,24 @@ def generate(request, resident=None):if not bool(torch.isfinite(latents).all() and torch.isfinite(audio).all()):raise RuntimeError('Non-finite video/audio latents; refusing to save a corrupted result')metrics['finite_latents'] = True+ if continuable and not request['sampling_plan'].get('enabled'):+ capture_first(latents)+ if continuable and first_tail is not None:+ try:+ from .continuation import tail_data+ continuation_data = tail_data(first_tail, latents, audio, canvas,+ request['sampling_plan'], manifest, continuation)+ except Exception as error:+ tail_failure(error)+ continuation_data = Noneif artifacts:from .decode_resume import sampling_provenance, save_samplingtick = time.perf_counter()sample_finalize_phase('latent_save')provenance = sampling_provenance(request)save_sampling({'video': latents.cpu(), 'audio': audio.cpu(), 'seed': request['seed'],- 'geometry': canvas, 'sampling_provenance': provenance}, artifacts, torch)+ 'geometry': canvas, 'sampling_provenance': provenance,+ **({'continuation_tail': continuation_data} if continuation_data is not None else {})}, artifacts, torch)metrics.update(sampling_provenance=provenance, sampling_source_attempt=request.get('resource_attempt'),latent_save_seconds=time.perf_counter() - tick, sampling_checkpoint_complete=True)# The final latents supersede this attempt's retained first pass.@@ -257,7 +323,8 @@ def generate(request, resident=None):metrics.update(sample_stage='first_pass_load')save(request['metrics'], metrics)tick = time.perf_counter()- latents, audio, first, lifted, reused = load_refine_input(request, torch)+ latents, audio, first, lifted, reused = load_refine_input(request, torch,+ **({'continuation_tail_callback': restore_first} if continuable else {}))latents, audio = latents.to('cuda'), audio.to('cuda')metrics.update(reused, sampling_passes=[first], latent_upscale=lifted,first_pass_load_seconds=time.perf_counter() - tick)@@ -284,7 +351,12 @@ def generate(request, resident=None):if request.get('automatic_pass_cache', False) else None)first_options = request.get('first_pass_policy', {}).get('profile', {}).get('engine')metrics['first_pass_policy'] = request.get('first_pass_policy')+ first_context = None+ if continuation is not None:+ from .continuation import load+ first_context = load(continuation, 'first')latents, audio, first = engine.sample(request['conditioning'], request['seed'],+ **({'continuation': first_context} if first_context is not None else {}),**sampling_plan['first'], allow_smaller_canvas=True,pass_cache_budget_bytes=pass_budget, gpu_reserve_bytes=request.get('gpu_reserve_bytes', 0),compute_options=first_options,@@ -293,6 +365,7 @@ def generate(request, resident=None):progress_total=sampling_plan['base_steps'] if preview else sampling_plan['total_steps'],budget_refresh=refresh_budget if live_budget is not None else None)metrics['sampling_passes'] = [first]+ capture_first(latents)if preview:# Keep the first pass before the latent upscale; an# upscale of this preview starts from these latents.@@ -397,7 +470,8 @@ def generate(request, resident=None):from .decode_resume import refine_provenance, save_refine_inputprovenance = refine_provenance(request)save_refine_input({'video': latents.cpu(), 'audio': audio.cpu(), 'seed': request['seed'],- 'geometry': canvas, 'refine_provenance': provenance}, artifacts, torch)+ 'geometry': canvas, 'refine_provenance': provenance,+ **({'continuation_first': first_tail} if first_tail is not None else {})}, artifacts, torch)metrics.update(refine_checkpoint_complete=True, refine_provenance=provenance,refine_source_attempt=request.get('resource_attempt'))except (OSError, RuntimeError, ValueError) as error:@@ -421,7 +495,12 @@ def generate(request, resident=None):def refined_complete(video, sound, receipt):sampling_complete(video, sound, refined(receipt))restart_seed = (request['seed'] + sampling_plan['restart_seed_offset']) % (1 << 64)+ final_context = None+ if continuation is not None:+ from .continuation import load+ final_context = load(continuation, 'final')latents, audio, second = engine.sample(request['conditioning'], restart_seed,+ **({'continuation': final_context} if final_context is not None else {}),**sampling_plan['second'], initial_latents=(latents, audio), refine_steps=sampling_plan['refine_steps'],refine_schedule=sampling_plan.get('refine_schedule'),final_step_callback=None if decoder_cached else read_decoder_ahead,@@ -432,7 +511,12 @@ def generate(request, resident=None):sampled = refined(second)metrics.pop('sample_stage', None)else:+ single_context = None+ if continuation is not None:+ from .continuation import load+ single_context = load(continuation, 'final')latents, audio, sampled = engine.sample(request['conditioning'], request['seed'],+ **({'continuation': single_context} if single_context is not None else {}),frames=canvas.get('frames', 243), width=canvas.get('width', 1344), height=canvas.get('height', 768),final_step_callback=None if decoder_cached else read_decoder_ahead,step_callback=memory_diagnostics.complete, sampling_complete_callback=sampling_complete,@@ -484,8 +568,31 @@ def generate(request, resident=None):metrics['resident_admission'] = list(resident.decisions)save(request['metrics'], metrics)fit_decoder()+ output_size = request.get('output_size')+ if output_size is not None:+ output_size = (output_size['width'], output_size['height'])+ metrics['output_size'] = dict(width=output_size[0], height=output_size[1])+ def keep_audio_lead_in(value):+ if value is not None:+ continuation_data['audio_lead_in'] = value+ # Older retained sampling tails predate the predecessor binding.+ continuation_data['metadata']['source_id'] = continuation['source_id']metrics.update(decode_to_file(latents, audio, request['output'], base=base, artifacts_dir=artifacts,- model_cache=resident, phase_callback=decode_phase, **decoder))+ **({'continuation': continuation} if continuation is not None else {}),+ **({'audio_lead_in_callback': keep_audio_lead_in}+ if continuation is not None and continuation_data is not None else {}),+ model_cache=resident, phase_callback=decode_phase, output_size=output_size, **decoder))+ if continuable and continuation_data is not None:+ try:+ from .continuation_store import save as save_continuation+ metrics['continuation_store'] = dict(save_continuation(request['output'], continuation_data), saved=True)+ if continuation is not None and 'audio_lead_in' in continuation_data:+ from .continuation import LEAD_IN_SAMPLES+ metrics['continuation']['audio_lead_in_samples'] = LEAD_IN_SAMPLES+ except Exception as error:+ tail_failure(error)+ elif continuable:+ metrics.setdefault('continuation_store', dict(saved=False, reason='checkpoint_missing'))if resume and artifacts:from .decode_resume import retain_latentsretain_latents(request['resume_decode']['latents'], artifacts)diff --git a/web/error_panel.js b/web/error_panel.jsindex 3caab52..201756e 100644--- a/web/error_panel.js+++ b/web/error_panel.js@@ -9,6 +9,23 @@ const record = value => value && typeof value === 'object' && !Array.isArray(val// The engine's own messages for errors people can fix themselves.const PLAIN_ERRORS = [+ {key: 'continuation-missing', message: 'The previous video has no usable continuation data. Generate it again with this version of FreeVideo.',+ title: ['This video cannot be continued', '这个视频暂时不能接续'],+ summary: ['Generate the previous video again with this version of FreeVideo. Older videos, replaced files and expired continuation data cannot be used.', '请用当前版本的 FreeVideo 重新生成上一段视频。旧版本的视频、被替换的文件或已清理接续数据的视频不能接续。']},+ {key: 'continuation-size', message: 'Use the same width and height as the previous video.',+ title: ['The video sizes differ', '两段视频的画面大小不一致'],+ summary: ['Set the width and height to the previous video’s size.', '请把宽度和高度设为与上一段视频相同。']},+ {key: 'continuation-route', message: 'Video continuation requires full two-pass text generation on an NVIDIA GPU, without first frames, last frames or reference media.',+ title: ['This generation mode cannot continue a video', '当前生成方式不支持视频接续'],+ summary: ['Use full two-pass text generation on an NVIDIA GPU and remove first frames, last frames and reference media. Mac and preview generation are not supported.', '请在 NVIDIA 显卡上使用完整的文字生成两遍流程,移除首帧、尾帧和参考素材。Mac 和预览生成暂不支持接续。']},+ {key: 'continuation-frames', message: 'Frame count must be 5 + 17n and at least 39 (39, 56, 73, 90, ...).',+ aliases: ['Frames must be 0 to use Duration, or 5 + 17n and at least 39 (for example, 39, 56, 141 or 243). The total includes 22 overlap frames when continuing.'],+ title: ['Choose a supported frame count', '请选择支持的帧数'],+ summary: ['Use 39, 56, 73, 90, or another value reached by adding 17. This includes the 22 repeated frames when continuing a video.', '请使用 39、56、73、90 等每次增加 17 的帧数;接续时,这个数包含开头重复的 22 帧。']},+ {key: 'continuation-file', message: 'Choose an existing MP4 video using its absolute path.',+ aliases: ['Continue from must be an MP4 path without ".." or a drive-relative path.'],+ title: ['Choose the previous video', '请选择上一段视频'],+ summary: ['Select an existing MP4 video generated by FreeVideo. In ComfyUI, keep it inside the output or input folder.', '请选择 FreeVideo 生成且仍存在的 MP4 视频;在 ComfyUI 中,请把它放在输出或输入文件夹内。']},{key: 'reference-too-short', message: 'The reference video is too short; it needs to be at least about 1 s long.',title: ['The reference video is too short', '参考视频太短'],summary: ['It needs to be at least about 1 s long. Choose a longer video.', '参考视频至少需要约 1 秒,请换一段更长的视频。']},@@ -34,7 +51,7 @@ function knownError(text) {const lines = String(text).slice(0, 65536).split(/\r?\n/).map(line => line.trim()).filter(Boolean);const index = /^FreeVideo generation failed(?: \(exit -?\d+\))?$/.test(lines[0] ?? '') ? 1 : 0;const line = (lines[index] ?? '').replace(/^[A-Za-z_][\w.]*(?:Error|Exception):\s*/, '');- return PLAIN_ERRORS.find(error => line === error.message)?.key ?? null;+ return PLAIN_ERRORS.find(error => line === error.message || error.aliases?.includes(line))?.key ?? null;}// When a diagnostic report exists the card hides Export report; the same advicediff --git a/web/library.js b/web/library.jsindex 2942c17..65e9597 100644--- a/web/library.js+++ b/web/library.js@@ -200,6 +200,7 @@ export function openLibrary(t, {upscale = null, selectedWork = null} = {}) {? t('Not deleted: the folder also holds files FreeVideo did not write: ', '未删除:文件夹里还有不是 FreeVideo 生成的文件:') + (value.kept || []).join(', '): error.message === 'editor-in-use' ? t('Not deleted: these edits use it: ', '未删除:这些剪辑正在使用它:') + (value.kept || []).join(', '): error.message === 'editor-unavailable' ? t('Not deleted: saved edits could not be checked. Try again in a moment.', '未删除:暂时无法检查已保存的剪辑,请稍后再试。')+ : error.message === 'continuation-in-use' ? t('Not deleted: a video continuing from it is running or queued. Try again after it finishes.', '未删除:接在这条视频后面的生成正在运行或排队,请等它完成后再试。'): error.message === 'in-use' ? t('Not deleted: its second pass is running, or the video is still open. Try again in a moment.', '未删除:正在用它跑二采,或视频仍被占用,请稍后再试。'): t('Could not delete this creation.', '无法删除这条作品。'));}