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.
Extend: a video without stored continuation data is continued from its own ending
Bowen Xue9ee81f4ee787
diff --git a/freevideo_engine/continuation_tail.py b/freevideo_engine/continuation_tail.pynew file mode 100644index 0000000..6c508db--- /dev/null+++ b/freevideo_engine/continuation_tail.py@@ -0,0 +1,267 @@+"""A continuation context encoded from the ending of a finished video.++A video made by an earlier version, or one whose file was replaced after it+was made, has no stored context. Its last 22 frames and the sound under them+are read back and encoded instead. The video encoder works on independent+17-frame clips, so those frames (17 + 5) fall on the same clip grid as the+last 7 latent frames of a generation: nothing before them has to be encoded.+The sound encoder looks back, so it is given up to 15 s and only its last+latents are kept.++The record describes the ending as a first block of 39 frames. Only the sound+clock reads that length: the kept sound ends exactly where the picture ends.+"""+import math+from pathlib import Path++from .continuation import (LATENT_FRAMES, MISSING, OVERLAP_FRAMES, SIZE_MISMATCH, audio_origin, validate_frames,+ validate_path)+++NOMINAL_FRAMES = 39+AUDIO_TICKS = round(NOMINAL_FRAMES * 40 / 24) - audio_origin(NOMINAL_FRAMES - OVERLAP_FRAMES)+AUDIO_RATE = 32000+TICK_SAMPLES = 800+AUDIO_WINDOW_TICKS = 600 # 15 s, the longest sound H3 generates+FPS = 24+TOO_SHORT = 'The previous video is too short to continue; it needs to be at least 2 s long.'+UNREADABLE = 'The previous video cannot be read.'+++def _fit(image, width, height):+ from PIL import Image+ return image if image.size == (width, height) else image.resize((width, height), Image.Resampling.LANCZOS)+++def _picture(frame):+ """The frame as an RGB image.++ The decoder library's own conversion comes out about 1/255 darker than the picture that was saved,+ which would show as a step where the next part begins. An 8-bit 4:2:0 frame of the usual range is+ converted with the exact matrix instead.+ """+ import numpy as np+ from PIL import Image+ if frame.format.name != 'yuv420p' or getattr(frame.color_range, 'value', frame.color_range) not in (0, 1):+ return frame.to_image().convert('RGB')+ y, cb, cr = frame.reformat(format='yuv444p', interpolation='BICUBIC').to_ndarray().astype(np.float32)+ kr, kb = (.2126, .0722) if getattr(frame.colorspace, 'value', frame.colorspace) == 1 else (.299, .114)+ y, cb, cr = (y - 16) * (255 / 219), (cb - 128) * (255 / 224), (cr - 128) * (255 / 224)+ red, blue = y + 2 * (1 - kr) * cr, y + 2 * (1 - kb) * cb+ green = (y - kr * red - kb * blue) / (1 - kr - kb)+ return Image.fromarray(np.clip(np.stack([red, green, blue], -1) + .5, 0, 255).astype(np.uint8))+++def _rate(stream):+ rate = float(stream.average_rate or stream.guessed_rate or 0)+ if not 10 <= rate <= 121:+ raise ValueError(UNREADABLE)+ return rate+++def _admit(count, rate, width, height, canvas):+ """The length of the video as 24 fps frames, when its ending can be continued on `canvas`."""+ frames = count if abs(rate - FPS) <= .01 else round(count * FPS / rate)+ if frames < NOMINAL_FRAMES:+ raise ValueError(TOO_SHORT)+ # The same shape within one 32-pixel step of the canvas; another size of the same shape is scaled.+ if min(width, height) < 1 or abs(width * canvas['height'] - height * canvas['width']) > 32 * max(width, height):+ raise ValueError(SIZE_MISMATCH)+ return frames+++def check(video_path, canvas):+ """Whether the ending of this video can be encoded for `canvas`; a ValueError says why not.++ Reads the file's packets and decodes nothing, so a caller can ask before it queues a run.+ """+ import av+ try:+ with av.open(str(validate_path(video_path))) as container:+ if not container.streams.video:+ raise ValueError(UNREADABLE)+ stream = container.streams.video[0]+ count = sum(1 for packet in container.demux(stream) if packet.size)+ return _admit(count, _rate(stream), stream.width or 0, stream.height or 0, canvas)+ except (av.FFmpegError, OSError) as error:+ raise ValueError(UNREADABLE) from error+++def pending(video_path, canvas):+ """A continuation request whose context is encoded from the video when the run starts."""+ validate_frames(canvas['frames'])+ check(video_path, canvas)+ origin = NOMINAL_FRAMES - OVERLAP_FRAMES+ return dict(tail=dict(video=str(Path(video_path).resolve())), overlap_frames=OVERLAP_FRAMES,+ new_frames=canvas['frames'] - OVERLAP_FRAMES, frame_origin=origin,+ audio_origin=audio_origin(origin), segment=2, audio_latents=AUDIO_TICKS)+++def read(video_path, canvas, first, directory):+ """The last 22 frames at both pass sizes and the sound under them, as files of this run.++ `first` is the first pass's width and height. A video at another frame rate gives the+ pictures a 24 fps copy of it would end with. Runs without a GPU.+ """+ import av+ import numpy as np+ from collections import deque+ directory = Path(directory)+ directory.mkdir(parents=True, exist_ok=True)+ try:+ with av.open(str(video_path)) as container:+ if not container.streams.video:+ raise ValueError(UNREADABLE)+ rate = _rate(container.streams.video[0])+ kept, count = deque(maxlen=math.ceil(OVERLAP_FRAMES * rate / FPS) + 2), 0+ for frame in container.decode(video=0):+ kept.append(frame)+ count += 1+ if not count:+ raise ValueError(UNREADABLE)+ frames = _admit(count, rate, kept[-1].width, kept[-1].height, canvas)+ oldest = count - len(kept)+ if abs(rate - FPS) <= .01:+ picked = range(count - OVERLAP_FRAMES, count)+ else:+ picked = [min(count - 1, max(oldest, round((frames - OVERLAP_FRAMES + index) * rate / FPS)))+ for index in range(OVERLAP_FRAMES)]+ images = [_picture(kept[index - oldest]) for index in picked]+ del kept+ sound = _sound(video_path, count / rate)+ except (av.FFmpegError, OSError) as error:+ raise ValueError(UNREADABLE) from error+ width, height = images[0].size+ result = {'frames': frames, 'source': {'width': width, 'height': height, 'fps': rate}}+ for name, size in (('hi', canvas), ('lo', first)):+ target = directory / ('continuation-tail-%s.npy' % name)+ np.save(target, np.stack([np.asarray(_fit(image, size['width'], size['height'])) for image in images]),+ allow_pickle=False)+ result[name] = str(target)+ target = directory / 'continuation-tail-audio.npy'+ np.save(target, sound, allow_pickle=False)+ result['audio'] = str(target)+ return result+++def _sound(video_path, seconds):+ """Up to 15 s of 32 kHz stereo ending where the picture ends; silence where the file has none."""+ import av+ import numpy as np+ end = round(seconds * AUDIO_RATE)+ window = min(AUDIO_WINDOW_TICKS, end // TICK_SAMPLES) * TICK_SAMPLES+ begin = end - window+ data = np.zeros((2, window), dtype=np.float32)+ with av.open(str(video_path)) as container:+ if not container.streams.audio:+ return data+ stream = container.streams.audio[0]+ mono = stream.layout.name == 'mono' or stream.channels == 1+ # A mono track has its channel repeated, as reference sound is; a stereo resampler would lower it by 3 dB.+ resampler = av.AudioResampler(format='fltp', layout='mono' if mono else 'stereo', rate=AUDIO_RATE)+ position = 0+ def place(item):+ nonlocal position+ block = item.to_ndarray()+ start, stop = max(position, begin), min(position + block.shape[1], end)+ if stop > start:+ data[:, start - begin:stop - begin] = block[:, start - position:stop - position]+ position += block.shape[1]+ for frame in container.decode(audio=0):+ for item in resampler.resample(frame):+ place(item)+ if position >= end:+ break+ else:+ for item in resampler.resample(None):+ place(item)+ if not np.isfinite(data).all():+ raise ValueError(UNREADABLE)+ return data+++def encode(tail, base, *, device='cuda', before_upload=None, posterior='mode'):+ """Encode the files of `read` into the three tensors of a continuation record."""+ import gc+ import numpy as np+ import torch+ from .media_encoding import encode_visual+ from .vae_weights import load_audio_vae, load_video_encoder+ empty = torch.mps.empty_cache if torch.device(device).type == 'mps' else (+ torch.cuda.empty_cache if torch.device(device).type == 'cuda' else lambda: None)+ result = {}+ vae, _ = load_video_encoder(base, before_upload=None if before_upload is None else+ lambda model: before_upload(model, False), device=device)+ for name in ('hi', 'lo'):+ pixels = np.load(tail[name], mmap_mode='r', allow_pickle=False)+ latent = encode_visual(vae, pixels, device=device, posterior=posterior)+ if latent.shape[2] != LATENT_FRAMES:+ raise ValueError('Unexpected continuation latent frames')+ result['video_' + name] = latent.numpy()+ del pixels, latent+ del vae+ gc.collect()+ empty()+ vae, _ = load_audio_vae(base, before_upload=None if before_upload is None else+ lambda model: before_upload(model, True), device=device)+ if vae.config.sampling_rate != AUDIO_RATE:+ raise ValueError('Continuation sound requires the pinned 32 kHz H3 VAE')+ mean = torch.tensor(vae.config.latents_mean).view(1, 1, -1)+ std = torch.tensor(vae.config.latents_std).view(1, 1, -1)+ audio = torch.from_numpy(np.load(tail['audio'], allow_pickle=False)).to(device)+ latent = vae.encode(audio[:, None], return_dict=False)[0].mode().float().cpu().transpose(1, 2)+ latent = ((latent - mean) / std).transpose(1, 2)+ if latent.shape[2] < AUDIO_TICKS:+ raise ValueError('Unexpected continuation sound latents')+ result['audio'] = latent[:, :, -AUDIO_TICKS:].contiguous().numpy()+ del vae, audio, latent+ gc.collect()+ empty()+ return result+++def metadata(identity, canvas, first):+ """The record's description: a first block whose last 22 frames are the file's."""+ return dict(identity=identity,+ geometry=dict(width=canvas['width'], height=canvas['height'], frames=NOMINAL_FRAMES),+ first_canvas=dict(width=first['width'], height=first['height']),+ chain=dict(segment=1, frame_origin=0, audio_origin=0), context='encoded')+++def freeze(request, canvas, first, directory, base):+ """Keep the ending `pending` asked for as files of this run; the worker encodes them."""+ from .continuation_store import video_id+ directory = Path(directory)+ video = request['tail']['video']+ size = lambda value: {key: value[key] for key in ('width', 'height')}+ tail = read(video, canvas, first, directory)+ return dict(request, tail=dict(tail, video=video, canvas=size(canvas), first=size(first), base=str(base),+ source_id=video_id(video),+ snapshot=str((directory / 'continuation-encoded.safetensors').resolve())))+++def complete(request, canvas, manifest, sampling_plan=None, *, resident=None, device='cuda'):+ """The ordinary snapshot request for a frozen ending, and how long encoding it took.++ The first attempt of a run encodes and writes the record beside its other files; a retry reads it.+ """+ import hashlib+ import time+ from .continuation import identity, validate_snapshot+ from .continuation_store import write+ tail = request['tail']+ path = Path(tail['snapshot'])+ if sampling_plan is not None and any(sampling_plan['first'][key] != tail['first'][key] for key in ('width', 'height')):+ raise ValueError(MISSING)+ seconds = None+ if not path.is_file():+ started = time.perf_counter()+ data = encode(tail, tail['base'], device=device, before_upload=None if resident is None else+ lambda model, audio: resident.input_vae_room(model, tail['canvas'], audio=audio))+ write(path, dict(data, metadata=dict(metadata(identity(manifest), tail['canvas'], tail['first']),+ source_id=tail['source_id'])))+ path.chmod(0o400)+ seconds = time.perf_counter() - started+ result = dict({key: value for key, value in request.items() if key != 'tail'}, snapshot=str(path),+ snapshot_sha256=hashlib.sha256(path.read_bytes()).hexdigest(), source_id=tail['source_id'])+ return validate_snapshot(result, canvas, manifest, sampling_plan), dict(seconds=seconds, reused=seconds is None)diff --git a/freevideo_engine/decode_resume.py b/freevideo_engine/decode_resume.pyindex eff5581..4a27033 100644--- a/freevideo_engine/decode_resume.py+++ b/freevideo_engine/decode_resume.py@@ -97,7 +97,14 @@ def sampling_provenance(request):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()+ value = request['continuation']+ tail = value.get('tail')+ if isinstance(tail, dict) and Path(tail.get('snapshot') or '.').is_file():+ # The request as it was sent asks for the ending to be encoded; the worker goes on with the+ # record it wrote. A retry compares the two, so both are named by that record.+ value = dict({key: item for key, item in value.items() if key != 'tail'},+ snapshot_sha256=_digest(tail['snapshot']), source_id=tail['source_id'])+ result['continuation'] = {key: item for key, item in value.items()if key not in ('snapshot', 'snapshot_data', 'source_video')}return resultdiff --git a/freevideo_engine/failure_details.py b/freevideo_engine/failure_details.pyindex 455eabf..ef0772d 100644--- a/freevideo_engine/failure_details.py+++ b/freevideo_engine/failure_details.py@@ -388,8 +388,13 @@ def launcher_failure(value, *, zh=False, other_disk=False, disk_name='', can_reprules = ((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 重新生成上一段视频。旧版本的视频、被替换的文件或已清理接续数据的视频不能接续。')),+ ('Generate the previous video again, then continue it.', '请重新生成上一段视频,再接续。')),+ (r'The previous video is too short to continue', 'continuation-short',+ ('The previous video is too short', '上一段视频太短'),+ ('Choose a video that is at least 2 seconds long.', '请选择至少 2 秒的视频。')),+ (r'The previous video cannot be read', 'continuation-unreadable',+ ('The previous video cannot be read', '无法读取上一段视频'),+ ('Choose an MP4 video that plays normally.', '请选择能正常播放的 MP4 视频。')),(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.', '请把宽度和高度设为与上一段视频相同。')),diff --git a/freevideo_engine/generate.py b/freevideo_engine/generate.pyindex 758b8d5..1603fc7 100644--- a/freevideo_engine/generate.py+++ b/freevideo_engine/generate.py@@ -344,7 +344,29 @@ def _run(args):from .geometry import geometryfrom .continuation import (validate_frames, validate_route, prepare as prepare_continuation,summary as continuation_summary, validate_snapshot, persist_snapshot, restore_snapshot,- audio_context)+ audio_context, MISSING as CONTINUATION_MISSING)+ from .continuation_tail import pending as encoded_continuation, freeze as freeze_tail+ continuation_directory = continuation_first = None++ def freeze_continuation(value):+ from .paths import base_path+ return freeze_tail(value, canvas, continuation_first, continuation_directory,+ profile['engine'].get('base') or base_path())++ def usable_continuation(value, *check):+ """The stored context when it fits this run, otherwise the previous video's own ending."""+ if 'tail' in value:+ return value+ try:+ return validate_snapshot(value, *check)+ except ValueError as error:+ if str(error) != CONTINUATION_MISSING:+ raise+ # A record of another version, other weights or another first-pass size.+ value = dict(encoded_continuation(continue_from, canvas),+ **{key: value[key] for key in ('audio_context', 'source_video', 'anchor') if key in value})+ return freeze_continuation(value) if continuation_directory is not None else value+frames = getattr(args, 'frames', None)continue_from = getattr(args, 'continue_from', None)continue_anchor = getattr(args, 'continue_anchor', None)@@ -392,12 +414,19 @@ def _run(args):continuation = restore_snapshot(args.continuation_snapshot,getattr(args, 'continuation_snapshot_sha256', None), canvas)else:- continuation = prepare_continuation(continue_from, canvas)+ try:+ continuation = prepare_continuation(continue_from, canvas)+ except ValueError as error:+ if str(error) != CONTINUATION_MISSING:+ raise+ # Nothing was stored for this file: its own ending is encoded when the run starts.+ continuation = encoded_continuation(continue_from, canvas)continuation = dict(continuation, audio_context=audio_context(), source_video=str(continue_from))if first_frame is not None:from .continuation import anchor_media, chain_first_frame_picturetry:- kept = chain_first_frame_picture(continuation, continue_from)+ # A context encoded from the file carries no first frame; whoever planned this run saw none either.+ kept = None if 'tail' in continuation else chain_first_frame_picture(continuation, continue_from)except ValueError:kept = Nonefirst_frame['reason'] = 'unreadable'@@ -464,8 +493,9 @@ def _run(args):if continuation is not None:from .two_pass import plan as continuation_planvalidate_route(task=profile['engine'].get('task', 't2va'), anchor=continue_anchor is not None)- continuation = validate_snapshot(continuation, canvas, None if active_loras else manifest,- continuation_plan(canvas, two_pass, base_steps=base_steps, refine_steps=refine_steps))+ planned = continuation_plan(canvas, two_pass, base_steps=base_steps, refine_steps=refine_steps)+ continuation_first = planned['first']+ continuation = usable_continuation(continuation, canvas, None if active_loras else manifest, planned)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()@@ -474,7 +504,10 @@ 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_directory = artifacts+ if continuation is not None and 'tail' in continuation:+ continuation = freeze_continuation(continuation)+ elif 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')@@ -491,6 +524,8 @@ def _run(args):'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)+ if 'tail' in continuation:+ report['continuation']['context'] = 'encoded'report['audio_context'] = continuation['audio_context']if continue_anchor is not None:report['continue_anchor'] = continuation['anchor']@@ -523,8 +558,10 @@ def _run(args):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,+ continuation = usable_continuation(continuation, canvas,json.loads((args.cache / 'manifest.json').read_text(encoding='utf-8')))+ if 'tail' in continuation:+ report['continuation']['context'] = 'encoded'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@@ -691,8 +728,10 @@ def _run(args):report['sampling_plan'] = sampling_planif continuation is not None:validate_route(task=profile['engine'].get('task', 't2va'), anchor=continue_anchor is not None)- continuation = validate_snapshot(continuation, canvas,+ continuation = usable_continuation(continuation, canvas,json.loads((args.cache / 'manifest.json').read_text(encoding='utf-8')), sampling_plan)+ if 'tail' in continuation:+ report['continuation']['context'] = 'encoded'if preview:report['preview'] = dict(geometry=dict(sampling_plan['first'], fps=canvas['fps']))if refine_source:diff --git a/freevideo_engine/media_encoding.py b/freevideo_engine/media_encoding.pyindex a67d4e3..a81c779 100644--- a/freevideo_engine/media_encoding.py+++ b/freevideo_engine/media_encoding.py@@ -34,7 +34,7 @@ def reference_size(width, height, canvas):return max(32, round(width * scale / 32) * 32), max(32, round(height * scale / 32) * 32)-def encode_visual(vae, pixels, *, device='cuda'):+def encode_visual(vae, pixels, *, device='cuda', posterior='sample'):"""The pinned VAE chunk/padding/posterior recipe with one live pixel chunk.Posterior sampling still occurs once on the original device with seed 42;@@ -58,7 +58,9 @@ def encode_visual(vae, pixels, *, device='cuda'):moments = torch.cat(moments, dim=2).to(device)if len(pixels) > 1 and vae.config.token_drop:moments = moments[:, :, :-vae.config.token_drop]- latent = DiagonalGaussianDistribution(moments).sample(generator=torch.Generator().manual_seed(42))+ distribution = DiagonalGaussianDistribution(moments)+ # References keep the pipeline's seeded sample; a continuation context wants the picture itself.+ latent = distribution.mode() if posterior == 'mode' else distribution.sample(generator=torch.Generator().manual_seed(42))latent = latent.to(torch.float16).float().cpu()mean = torch.tensor(vae.config.latents_mean).view(1, -1, 1, 1, 1)std = torch.tensor(vae.config.latents_std).view(1, -1, 1, 1, 1)diff --git a/freevideo_engine/worker.py b/freevideo_engine/worker.pyindex db0b8e2..5b25e9f 100644--- a/freevideo_engine/worker.py+++ b/freevideo_engine/worker.py@@ -164,6 +164,13 @@ def generate(request, resident=None):resident.gpu_budget = min(resident.gpu_budget, limit)save(request['metrics'], metrics)manifest = json.loads((Path(request['cache']) / 'manifest.json').read_text(encoding='utf-8'))+ if continuation is not None and 'tail' in continuation:+ # Nothing was stored for the previous video: its ending is encoded here, before any model of+ # this run is loaded, and every later attempt reads the same record.+ from .continuation_tail import complete+ continuation, metrics['continuation_encode'] = complete(+ continuation, request['geometry'], manifest, request.get('sampling_plan'), resident=resident)+ request['continuation'] = continuationif manifest.get('precision') not in ('fp8', 'int8', 'bf16'):raise ValueError('The Engine requires an official FP8 or int8 cache')options, decoder = request['engine_options'], request['decoder_options']diff --git a/web/error_panel.js b/web/error_panel.jsindex dc15853..ef625d6 100644--- a/web/error_panel.js+++ b/web/error_panel.js@@ -11,7 +11,13 @@ const record = value => value && typeof value === 'object' && !Array.isArray(valconst 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 重新生成上一段视频。旧版本的视频、被替换的文件或已清理接续数据的视频不能接续。']},+ summary: ['Generate the previous video again, then continue it.', '请重新生成上一段视频,再接续。']},+ {key: 'continuation-short', message: 'The previous video is too short to continue; it needs to be at least 2 s long.',+ title: ['The previous video is too short', '上一段视频太短'],+ summary: ['Choose a video that is at least 2 seconds long.', '请选择至少 2 秒的视频。']},+ {key: 'continuation-unreadable', message: 'The previous video cannot be read.',+ title: ['The previous video cannot be read', '无法读取上一段视频'],+ summary: ['Choose an MP4 video that plays normally.', '请选择能正常播放的 MP4 视频。']},{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.', '请把宽度和高度设为与上一段视频相同。']},