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.
Windows int8: medium-size videos on 16 GB or smaller cards no longer slow down in the second pass
Bowen Xue8f98b5ed9914
diff --git a/freevideo_engine/agent/cast.py b/freevideo_engine/agent/cast.pyindex 3178bde..ab44345 100644--- a/freevideo_engine/agent/cast.py+++ b/freevideo_engine/agent/cast.py@@ -129,14 +129,23 @@ def _check(record, stem):or type(card['revision']) is not int or card['revision'] < 1or not isinstance(card['name'], str) or not isinstance(card['description'], (str, type(None)))):raise ValueError('Invalid card identity')- if set(card['edited_by_user']) != set(EDITABLE) or not all(type(v) is bool for v in card['edited_by_user'].values()):+ marks = card.get('edited_by_user', {})+ if not isinstance(marks, dict):raise ValueError('Invalid edit marks')+ normalized = {k: marks.get(k, False) for k in EDITABLE}+ if not all(type(v) is bool for v in normalized.values()):+ raise ValueError('Invalid edit marks')+ if marks != normalized:+ logging.getLogger(__name__).warning('Normalized edit marks on a readable cast card')+ card['edited_by_user'] = normalized+ unknown_labels = Falsefor key, limit in (('images', MAX_IMAGES), ('candidates', MAX_CANDIDATES)):if not isinstance(card[key], list) or len(card[key]) > limit:raise ValueError('Invalid pictures')for row in card[key]:- if row['label'] not in LABELS or not isinstance(row['media']['file'], str):+ if not isinstance(row['label'], str) or not isinstance(row['media']['file'], str):raise ValueError('Invalid picture')+ unknown_labels |= row['label'] not in LABELSif card['voice'] is not None:if not isinstance(card['voice']['clip']['file'], str) or not (isinstance(card['voice']['media'].get('file'), str) or isinstance(card['voice']['media'].get('library'), str)):@@ -145,6 +154,8 @@ def _check(record, stem):raise ValueError('Invalid film list')record['receipts'] = operation_receipts.load(record['receipts'])json.dumps(record, allow_nan=False)+ if unknown_labels:+ logging.getLogger(__name__).warning('Kept unknown picture labels on a readable cast card')def _revision(body, header):@@ -363,7 +374,19 @@ class Cast:def update(self, identity, value, *, by='builtin', ref=None, revision=None, local=False, client=None):shape = schema.cast_schema('update', local=local)- schema.validate(shape, value)+ shape['properties']['images']['items']['properties']['label'] = schema.enum(LABELS)+ checked = deepcopy(value)+ with self.changed:+ record = self.records.get(identity) if isinstance(identity, str) else None+ if record is not None and isinstance(checked, dict) and isinstance(checked.get('images'), list):+ known = {(row['media']['file'], row['label']) for key in ('images', 'candidates')+ for row in record['card'][key] if row['label'] not in LABELS}+ for row in checked['images']:+ if isinstance(row, dict) and isinstance(row.get('label'), str):+ if (_plain(row.get('media')), row['label']) in known:+ # Let callers return a saved label unchanged; new labels still use the request schema.+ row.pop('label')+ schema.validate(shape, checked)ref = ref if ref is not None else value.get('ref')value = {k: v for k, v in value.items() if k != 'ref'}expected = _revision(value.pop('revision', None), revision)diff --git a/freevideo_engine/agent/productions.py b/freevideo_engine/agent/productions.pyindex d23838c..f752ab5 100644--- a/freevideo_engine/agent/productions.py+++ b/freevideo_engine/agent/productions.py@@ -162,10 +162,8 @@ class Productions:raise ValueError('Invalid execution receipts')record['receipts'] = operation_receipts.load(record['receipts'])json.dumps(record, allow_nan=False)- checked = production.plan(dict(screenplay=state['screenplay'],- takes_per_shot=state['takes_per_shot'], director=state['director']))- if [s['id'] for s in state['shots']] != [s['id'] for s in checked['preview']['shots']]:- raise ValueError('Invalid shot receipts')+ request = dict(screenplay=state['screenplay'],+ takes_per_shot=state['takes_per_shot'], director=state['director'])for ref, child in record['children'].items():schema.validate(schema.REF, ref)if child['status'] not in DONE:@@ -174,10 +172,15 @@ class Productions:raise ValueError('Invalid submission marker')production.view(state)try:+ checked = production.plan(request)+ if [s['id'] for s in state['shots']] != [s['id'] for s in checked['preview']['shots']]:+ raise JobError('internal_error', 'Saved shots differ from the current plan')production.advance(deepcopy(state), deepcopy(record['children']), now=state['updated_at'])- except production.ProductionError as error:+ except (production.ProductionError, JobError) as error:# A readable record that cannot advance yet is kept, never renamed away.record['stalled'] = self._stalled(error)+ logging.getLogger(__name__).warning('Kept a readable production receipt stalled (%s)',+ record['stalled']['code'])self.records[state['id']] = recordexcept (ValueError, KeyError, TypeError, AttributeError, IndexError, RecursionError, OSError):path.replace(path.with_name(path.name + '.bad-' + uuid.uuid4().hex))diff --git a/freevideo_engine/agent/schema.py b/freevideo_engine/agent/schema.pyindex b132164..62f22f7 100644--- a/freevideo_engine/agent/schema.py+++ b/freevideo_engine/agent/schema.py@@ -471,6 +471,7 @@ def cast_schema(name, *, local=False):if name == 'create':return obj(dict(kind=enum(('character', 'setting'), default='character'), **fields, ref=REF), ('name',))if name == 'update':+ fields['images']['items']['properties']['label'] = {'type': 'string'}return obj(dict(fields, revision=number(1, integer=True), ref=REF))if name == 'delete':return obj(dict(revision=number(1, integer=True), ref=REF))@@ -489,7 +490,7 @@ def cast_schema(name, *, local=False):def cast_view():picture = obj(dict(media=obj(dict(file=FILE, url=string(2048)), ('file', 'url')),by=enum(('user', 'agent', 'builtin')), from_job=JOB, generated={'type': 'boolean'},- label=enum(LABELS), label_guess={'type': 'boolean'}), ('media', 'by', 'label'))+ label={'type': 'string'}, label_guess={'type': 'boolean'}), ('media', 'by', 'label'))generating = obj(dict(job=JOB, face_job=nullable(JOB), jobs=array(JOB, 1, 5),source=enum(('image', 'video')), replace={'type': 'boolean'}, at=string(),by=enum(('user', 'agent', 'builtin'))), ('job', 'face_job', 'replace', 'at', 'by'))diff --git a/freevideo_engine/bootstrap.py b/freevideo_engine/bootstrap.pyindex 5b990d9..c97dab6 100644--- a/freevideo_engine/bootstrap.py+++ b/freevideo_engine/bootstrap.py@@ -5,6 +5,7 @@ import csvfrom contextlib import ExitStack, contextmanagerimport hashlibimport json+import loggingimport osfrom pathlib import Pathimport platform@@ -49,8 +50,8 @@ def _permission_limited_memory_sample(row):different security context even though the install process and the systemmemory counters remain readable. In that case the process-tree number isincomplete, but the global emergency floor is still a valid safety guard.- Require a real sampled process count so synthetic/no-sample rows and a- failed process snapshot continue to fail closed.+ Require a real sampled process count to distinguish denied child queries+ from a failed process snapshot."""if type(row.get('processes')) is not int or row['processes'] <= 0:return False@@ -469,8 +470,13 @@ def prepare_end(ui, success=True):ui.end(PREPARE_KEY, success=success)+def missing_sage_tools(snapshot):+ return ([] if snapshot.get('compiler') else ['g++']) + ([] if snapshot.get('make', True) else ['make'])++def plan(args, *, local_progress=None, stage=None):root = args.root.expanduser().resolve()+ warnings = []saved = json.loads((root / 'machine.json').read_text(encoding='utf-8')) if (root / 'machine.json').is_file() else {}storage = getattr(args, 'storage', None) or saved.get('storage', 'compact')layout = select_layout(getattr(args, 'environment', None), saved)@@ -513,13 +519,15 @@ def plan(args, *, local_progress=None, stage=None):# A missing or too old Git is replaced by FreeVideo's own.if not windows_target:# ./setup.sh installs these before planning; the desktop launcher names the command instead.- missing = ([] if snapshot.get('compiler') else ['g++']) + ([] if snapshot.get('make', True) else ['make'])+ missing = missing_sage_tools(snapshot)if missing:from .system import linux_tools_commandcommand = linux_tools_command(missing)- errors.append('Missing %s, needed to build GPU acceleration for this GPU. %s, then check again.' % (+ warnings.append('Missing %s, needed to build GPU acceleration for this GPU. %s, then check again.' % (' and '.join(missing), 'In a terminal, run: ' + command if command else'Ask your administrator to install them'))+ logging.getLogger(__name__).warning('%s Skipping Sage2 source compilation; '+ 'continuing with cudnn/torch-flash attention.', warnings[-1])if offline_installation(root):# Its sources carry no Git history and its Python is the package's.errors.append('This folder holds an installation from offline packages; automatic installation does not change it. '@@ -765,7 +773,7 @@ def plan(args, *, local_progress=None, stage=None):'4–8 GiB working set plus reclaimable source file cache; measured by setup'),'test_artifacts_estimate_gib': '5–8 GiB for the standard five-case suite; all outputs retained','first_generation_note': 'Portable AdaLN tables follow model weights and the exact schedule, across GPUs and Torch/CUDA versions. New schedules or modulation-changing LoRAs require preparation. Existing environments stay on disk when switching.',- 'estimates_are_not_capacity_guarantees': True, 'errors': errors,+ 'estimates_are_not_capacity_guarantees': True, 'errors': errors, 'warnings': warnings,'steps': ['Install isolated uv/Python and ' + ('one shared CUDA environment' if layout == 'unified' else 'two CUDA environments'),'Clone the VDN, patched Diffusers and native H3 text-encoder library versions FreeVideo tests','Install verified Windows Triton / Sage2 wheels' if windows_target else 'Install a local CUDA compiler and build Sage2 for the detected GPU only',@@ -1254,34 +1262,39 @@ class Installer:try:row = memory.sample(os.getpid())except OSError as error:- if self.system != 'Windows':- raise# The process snapshot itself can fail, too. Still- # obtain fresh physical/commit headroom; never reuse- # the previous reading or invent process usage.+ # obtain fresh system headroom without inventing process usage.system = system_memory()row = dict(guard_bytes=None,system_available_bytes=system['available_bytes'],system_physical_available_bytes=system['physical_available_bytes'],system_commit_available_bytes=system['commit_available_bytes'],memory_read_errors=[dict(error=str(error), winerror=getattr(error, 'winerror', None))])+ if self.system == 'Linux':+ from .hardware import cgroup_memory+ group = cgroup_memory()+ available = group['available_bytes']+ reclaimable = group.get('reclaimable_available_bytes', available)+ row.update(cgroup_memory=group,+ effective_available_bytes=min(system['available_bytes'],+ available) if available is not None else system['available_bytes'],+ inference_available_bytes=min(system['available_bytes'],+ reclaimable) if reclaimable is not None else system['available_bytes'])used = memory_sample(row)if used is None:unreadable += 1failures += 1- # A live worker can have descendants for which- # Windows returns ERROR_ACCESS_DENIED (5). Keep- # the sample and continue under the global RAM/- # commit floor; abort only when the whole process- # snapshot is unavailable or the root cannot be- # sampled. This avoids killing installs merely- # because a helper has a stricter token.- degraded = (self.system == 'Windows' and- _permission_limited_memory_sample(row))+ # Unreadable process usage does not prove exhaustion;+ # retain the samples and keep checking the system floor.+ denied = self.system == 'Windows' and _permission_limited_memory_sample(row)+ degraded = denied or self.system != 'Windows' or unreadable >= 3if degraded:self.state['resource_warning'] = ('Some Windows child processes denied memory queries (WinError 5); '- 'continuing with the global RAM/commit floor.')+ 'continuing with the global RAM/commit floor.' if denied else+ 'Process-tree memory is unavailable; continuing with the global RAM/commit floor.')+ if self.state.get('monitor_status') != 'degraded':+ self.ui.write(self.state['resource_warning'] + '\n')row = dict(row, monitor_status='degraded' if degraded else 'retrying',consecutive_unreadable=unreadable)else:@@ -1290,6 +1303,7 @@ class Installer:row = dict(row, monitor_status='recovered' if unreadable else 'complete',consecutive_unreadable=0)unreadable = 0+ self.state['monitor_status'] = row['monitor_status']pressure = setup_memory_pressure(row, self.resources['ram_budget_bytes'], self.system)row['installation_guard'] = pressurestream.write(json.dumps(dict(row, elapsed_seconds=time.monotonic()-self.started, epoch_seconds=time.time())) + '\n')@@ -1306,15 +1320,6 @@ class Installer:breakif available < pressure['planning_reserve_bytes']:self.state['memory_headroom_warning'] = pressure- if (used is None and (self.system != 'Windows' or unreadable >= 3)- and row.get('monitor_status') != 'degraded'):- details = json.dumps(dict(- unreadable_memory_pids=row.get('unreadable_memory_pids', row.get('unreadable_pss_pids', [])),- memory_read_errors=row.get('memory_read_errors', []),- available_bytes=available), ensure_ascii=False)- raise RuntimeError('Cannot read process-tree memory after %d consecutive samples. '- 'Download progress is retained; retry installation to resume. '- 'RAM sample: %s; full samples: %s' % (unreadable, details, self.run_dir / 'ram.jsonl'))self.monitor_stop.wait(1)except BaseException as error:self.state['resource_guard'] = 'Installation RAM monitoring failed: ' + repr(error)@@ -1674,6 +1679,11 @@ class Installer:def install_sage(self, uv, python):if self.system == 'Windows':return self.install_sage_windows(uv, python)+ missing = missing_sage_tools(self.plan['inventory'])+ if missing:+ self.ui.write('Missing %s; skipping Sage2 source compilation and continuing with '+ 'cudnn/torch-flash attention.\n' % ' and '.join(missing))+ return Nonecode = ('import json,platform,sys,torch; print(json.dumps(dict(''python="cp"+str(sys.version_info.major)+str(sys.version_info.minor), ''torch=str(torch.__version__),cuda=torch.version.cuda,cxx11_abi=torch.compiled_with_cxx11_abi(), '@@ -1958,6 +1968,8 @@ class Installer:def record_kernel_validation(self, results, kernel_report):sage_manifest = results['sage']+ if sage_manifest is None:+ returnsage_record = json.loads(sage_manifest.read_text(encoding='utf-8'))kernels = json.loads(kernel_report.read_text(encoding='utf-8'))sage_record['kernel_validation'] = ('Small Sage2 kernels passed on ' + self.plan['inventory']['selected_gpu']['uuid']diff --git a/freevideo_engine/comfy_launcher_runtime.py b/freevideo_engine/comfy_launcher_runtime.pyindex 7cefc0e..e3397ce 100644--- a/freevideo_engine/comfy_launcher_runtime.py+++ b/freevideo_engine/comfy_launcher_runtime.py@@ -8,6 +8,7 @@ import errnoimport hashlibimport ipaddressimport json+import loggingimport osfrom pathlib import Pathimport secrets@@ -471,7 +472,12 @@ def node_target(root):if (path / 'freevideo-launcher.json').is_file() or (code.is_file() and 'FreeVideoGenerate' in code.read_text(encoding='utf-8')):found.append(path)if len(found) > 1:- raise ValueError('Multiple FreeVideo node installations found. Keep one enabled before installing.')+ managed = [path for path in found if (path / 'freevideo-launcher.json').is_file()]+ if len(managed) != 1:+ raise ValueError('Multiple FreeVideo node installations found. Keep one enabled before installing.')+ logging.getLogger(__name__).warning('Multiple FreeVideo node installations found; using %s with '+ 'freevideo-launcher.json and leaving the other folders unchanged.', plain(managed[0]))+ found = managedtarget = found[0] if found else parent / 'FreeVideo'if target.exists() and not found and any(target.iterdir()):raise ValueError('custom_nodes/FreeVideo already contains unrelated files. Choose another ComfyUI or rename that folder first.')@@ -520,10 +526,10 @@ def deploy(root, source, engine):target.mkdir(parents=True, exist_ok=True)entry = target / '__init__.py'old = entry.read_bytes() if entry.is_file() else None- if (old and previous.get('entry_sha256') and hashlib.sha256(old).hexdigest() != previous['entry_sha256']+ if (old is not None and previous.get('entry_sha256') and hashlib.sha256(old).hexdigest() != previous['entry_sha256']and not checkout_entry(old, target)):- raise ValueError(f'The managed FreeVideo entry point ({plain(entry)}) was edited. Changes are retained; '- 'undo them or delete that file before updating.')+ logging.getLogger(__name__).warning('The managed FreeVideo entry point (%s) was edited; '+ 'backing it up in launcher/backups before restoring the loader.', plain(entry))# The small loader may be replaced; all original checkout files remain intact.code = ("# Installed by FreeVideo launcher. Original entry points are retained in the engine launcher/backups folder.\n""import importlib.util as _util\nimport json as _json\nfrom pathlib import Path as _Path\nimport sys as _sys\n"@@ -534,7 +540,7 @@ def deploy(root, source, engine):"_spec = _util.spec_from_file_location(__name__ + '._engine', _source / '__init__.py', submodule_search_locations=[str(_source)])\n""_engine = _util.module_from_spec(_spec)\n_sys.modules[_spec.name] = _engine\n_spec.loader.exec_module(_engine)\n""WEB_DIRECTORY = str(_source / 'web')\ncomfy_entrypoint = _engine.comfy_entrypoint\n").encode()- if old and old != code:+ if old is not None and old != code:backup = engine / 'launcher' / 'backups' / (target.name + '-' + hashlib.sha256(old).hexdigest()[:12] + '-init.py')backup.parent.mkdir(parents=True, exist_ok=True)if not backup.exists():@@ -800,9 +806,12 @@ class Controller:source = Path(plain(resolved(receipt['source'])))if (receipt.get('protocol') != PROTOCOL or Path(plain(resolved(receipt['engine_root']))) != engineor not io_path(source / 'freevideo_engine/comfy_nodes.py').is_file()- or not io_path(source / '__init__.py').is_file()- or hashlib.sha256((receipt_path.parent / '__init__.py').read_bytes()).hexdigest() != receipt.get('entry_sha256')):+ or not io_path(source / '__init__.py').is_file()):return False+ entry = receipt_path.parent / '__init__.py'+ if hashlib.sha256(entry.read_bytes()).hexdigest() != receipt.get('entry_sha256'):+ logging.getLogger(__name__).warning('The managed FreeVideo entry point (%s) differs from '+ 'entry_sha256; continuing with the saved installation.', plain(entry))installation(source, {'FREEVIDEO_HOME': str(engine)})python = (record.get('python') or values.get('python') ormanaged_python(engine, Path(descriptor['root'])) or descriptor.get('python'))diff --git a/freevideo_engine/comfy_source.py b/freevideo_engine/comfy_source.pyindex b81a38b..f57fb01 100644--- a/freevideo_engine/comfy_source.py+++ b/freevideo_engine/comfy_source.py@@ -55,7 +55,7 @@ def download(target, *, plan, env, run):# A finished checkout survives cancellation before publication. Git fetch's# own incomplete attempts are retained beside this directory by network.clone.network.clone(stage, spec['url'], spec['commit'], network=plan, env=env, run=run)- if not all((stage / name).is_file() for name in ('main.py', 'folder_paths.py', 'requirements.txt', 'LICENSE')) or not (stage / 'comfy_api/latest').is_dir():+ if not all((stage / name).is_file() for name in ('main.py', 'folder_paths.py', 'requirements.txt')) or not (stage / 'comfy_api/latest').is_dir():raise ValueError('The downloaded ComfyUI application is incomplete; files retained at ' + str(stage))save(stage / RECEIPT, spec)if target.exists() or target.is_symlink():diff --git a/freevideo_engine/desktop_runtime.py b/freevideo_engine/desktop_runtime.pyindex 48c082d..9edc47b 100644--- a/freevideo_engine/desktop_runtime.py+++ b/freevideo_engine/desktop_runtime.py@@ -43,8 +43,11 @@ def launcher_root():return Path(home) / 'FreeVideo-launcher'+NOTICE_FILES = ('LICENSE', 'NOTICE', 'THIRD_PARTY_NOTICES.md')++def source_files(root):- names = ['pyproject.toml', 'README.md', 'LICENSE', 'NOTICE', 'THIRD_PARTY_NOTICES.md', 'MANIFEST.in', '__init__.py',+ names = ['pyproject.toml', 'README.md', 'MANIFEST.in', '__init__.py','freevideo', 'setup.sh', 'test.sh','freevideo.ps1', 'setup.ps1', 'test.ps1', 'freevideo.cmd', 'setup.cmd', 'test.cmd','scripts/bootstrap_linux.sh', 'scripts/windows_app.py', 'scripts/build_windows.py',@@ -52,6 +55,8 @@ def source_files(root):# Older deployed Windows payloads may predate the optional Mac entry points.files_optional = ('scripts/build_macos.py', 'scripts/macos_app.py')names += [name for name in files_optional if (root / name).is_file()]+ # Notice and licence files are carried when present; a launcher never fails to start without one.+ names += [name for name in NOTICE_FILES if (root / name).is_file()]files = [root / name for name in names]files += [p for folder in ('freevideo_engine', 'constraints', 'web', 'example_workflows')for p in (root / folder).rglob('*')@@ -78,7 +83,7 @@ def matching_source(bundled, installed):return Truetry:for path in source_files(bundled):- if path.name == 'comfyui.json':+ if path.name == 'comfyui.json' or path.relative_to(bundled).as_posix() in NOTICE_FILES:continueother = installed / path.relative_to(bundled)if not other.is_file() or path.read_bytes() != other.read_bytes():diff --git a/freevideo_engine/editor_text.py b/freevideo_engine/editor_text.pyindex 84fea21..8e76892 100644--- a/freevideo_engine/editor_text.py+++ b/freevideo_engine/editor_text.py@@ -8,6 +8,7 @@ from functools import lru_cachefrom bisect import bisect_rightimport hashlibimport json+import loggingimport mathfrom pathlib import Pathimport re@@ -136,7 +137,8 @@ def _font(name, bold, size):@lru_cache(maxsize=8)def _verify_font(path, digest):if hashlib.sha256(Path(path).read_bytes()).hexdigest() != digest:- raise ValueError('Text font coverage is out of date')+ # A replaced font can still render; the cached check warns once per face.+ logging.getLogger(__name__).warning('Text font coverage is out of date; using font: %s', path)def wrap_text(text, measure, width):diff --git a/freevideo_engine/image_gen/image_pack.py b/freevideo_engine/image_gen/image_pack.pyindex b061866..cf73b44 100644--- a/freevideo_engine/image_gen/image_pack.py+++ b/freevideo_engine/image_gen/image_pack.py@@ -9,6 +9,7 @@ or an optional busy callback. The CLI writes atomic, read-only status snapshots.from collections import dequefrom contextlib import ExitStack, contextmanagerimport json+import loggingfrom pathlib import Path, PurePosixPathimport reimport signal@@ -185,12 +186,34 @@ def _owned_intact(path, stamp):stamp.get(k) == v for k, v in provision.file_identity(path, stamp).items())+# The notice written next to the weights. The text lives here; licenses/NOTICE.txt carries the same words+# for people reading the source and is never needed at run time.+NOTICE_TEXT = (b'Qwen is licensed under the Qwen RESEARCH LICENSE AGREEMENT, Copyright (c) 2026 Hangzhou Tongyi '+ b'Laboratory Technology Co., Ltd. All Rights Reserved.\n')++def _notice():- return (Path(__file__).parent / 'licenses' / 'NOTICE.txt').read_bytes()+ return NOTICE_TEXTdef _notice_ready(path):- return path.is_file() and path.stat().st_size == len(_notice()) and path.read_bytes() == _notice()+ """Informational only: a missing or different notice never makes the pack unusable."""+ try:+ return path.is_file() and path.read_bytes() == NOTICE_TEXT+ except OSError:+ return False+++def _write_notice(folder, owned):+ """Put the notice into the model folder when possible; a failure is logged and the install goes on."""+ notice = _path(folder, 'NOTICE.txt')+ try:+ if notice.exists():+ return # present (ours or the user's own text): left as it is+ notice.write_bytes(NOTICE_TEXT)+ _own(folder, owned, notice)+ except Exception as error:+ logging.warning('[FreeVideo] Could not write the image model notice: %s', error)def status(root=None):@@ -213,7 +236,7 @@ def status(root=None):notice = _path(folder, 'NOTICE.txt')notice_ready = _notice_ready(notice)total = sum(r['bytes'] for r in files)- available = not missing and notice_ready+ available = not missingreturn dict(installable=True, ready=available, total_bytes=total, verified_bytes=verified_bytes,downloaded_bytes=downloaded, bytes=sum(r['bytes'] for r in files if not r['ready']),remaining_bytes=sum(r['bytes'] - r['downloaded_bytes'] for r in files if not r['ready']),@@ -363,13 +386,7 @@ def install(root=None, progress=None, check=None, *, engine_root=None, repair=Faplan = _download_plan(engine_root)plan.update(quiet=True, resource_check=check)owned = _read(folder, OWNERSHIP)- notice = _path(folder, 'NOTICE.txt')- if notice.exists() and not _notice_ready(notice):- # Preserve an unexpected text rather than overwriting it.- model_repair.rename_noreplace(notice, notice.with_name('NOTICE.txt.replaced-' + str(time.time_ns())))- if not notice.exists():- notice.write_bytes(_notice())- _own(folder, owned, notice)+ _write_notice(folder, owned)done = 0pending_prefixes = 0if _background is not None:diff --git a/freevideo_engine/image_gen/image_policy.py b/freevideo_engine/image_gen/image_policy.pyindex 95c92dc..c25b72d 100644--- a/freevideo_engine/image_gen/image_policy.py+++ b/freevideo_engine/image_gen/image_policy.py@@ -53,6 +53,12 @@ _ENCODE_BASE = 2.7 * GiB # prompt length, not image size, drives this s_DENOISE_BASE, _DENOISE_PER_MP = 1.06 * GiB, 0.554 * GiB_DECODE_BASE, _DECODE_PER_MP = 2.10 * GiB, 0.15 * GiB_UNTILED_DECODE_PER_MP = 6.5 * GiB # decoding the whole image at once instead of in tiles+# Decoding in 512-pixel tiles (256 overlap) keeps the decoder's padded tile edges+# out of tall pictures, where 256-pixel tiles left coloured vertical lines and a+# grid texture. A fixed-latent B200 sweep measured +1.43 GiB of decoder workspace;+# reserve 1.6 GiB. A card that cannot afford it decodes in 256-pixel tiles as before.+SMALL_VAE_TILE, LARGE_VAE_TILE = 256, 512+_LARGE_TILE_DECODE_EXTRA = 1.6 * GiB# Reference images, about 1 MP each after resizing. Their tokens are recomputed at# every step (the pipeline keeps no prefix key/value cache: it would hold about# 2 GiB per reference on the card, and the extra compute is about 1 s per image on@@ -87,12 +93,14 @@ class ImagePlan:te_streamed_bytes: intlink_floor_seconds: objectreasons: list = field(default_factory=list)+ vae_tile_size: int = SMALL_VAE_TILEdef to_dict(self):return dict(self.__dict__)-def stage_peaks(shape, dit_resident, te_resident, *, width, height, reference_pixels=0, vae_tiling=True):+def stage_peaks(shape, dit_resident, te_resident, *, width, height, reference_pixels=0, vae_tiling=True,+ vae_tile_size=SMALL_VAE_TILE):"""Largest allocation of each stage for a given residency (bytes)."""mp = width * height / 1e6ref_mp = reference_pixels / 1e6@@ -102,6 +110,8 @@ def stage_peaks(shape, dit_resident, te_resident, *, width, height, reference_pidecode = _DECODE_BASE + _DECODE_PER_MP * mp + residentif not vae_tiling:decode += _UNTILED_DECODE_PER_MP * mp+ elif vae_tile_size > SMALL_VAE_TILE:+ decode += _LARGE_TILE_DECODE_EXTRAif ref_mp:encode += max(_REF_ENCODE_FLOOR, _REF_ENCODE_PER_MP * ref_mp - _REF_ENCODE_OFFSET)denoise += _REF_DENOISE_PER_MP * ref_mp@@ -127,11 +137,15 @@ def plan_image(*, gpu_budget_bytes, host_available_bytes=None, width=1024, heighreasons = []kwargs = dict(width=width, height=height, reference_pixels=reference_pixels)+ tile_size = LARGE_VAE_TILE+def peak(kd, kt, tiling=True):- return max(stage_peaks(shape, kd, kt, vae_tiling=tiling, **kwargs).values())+ return max(stage_peaks(shape, kd, kt, vae_tiling=tiling, vae_tile_size=tile_size, **kwargs).values())kd = kt = 0tiling = True+ if peak(0, 0) > limit:+ tile_size = SMALL_VAE_TILEfeasible = peak(0, 0) <= limitif not feasible:reasons.append('even full streaming with a tiled VAE needs %.1f GiB beyond the %.1f GiB budget' % (@@ -146,7 +160,7 @@ def plan_image(*, gpu_budget_bytes, host_available_bytes=None, width=1024, heigh# Untiled decoding is faster; take it only when it fits beside the same residency.if peak(kd, kt, tiling=False) <= limit:tiling = False- peaks = stage_peaks(shape, kd, kt, vae_tiling=tiling, **kwargs)+ peaks = stage_peaks(shape, kd, kt, vae_tiling=tiling, vae_tile_size=tile_size, **kwargs)streamed_dit = (shape.dit_blocks - kd) * shape.dit_block_bytesstreamed_te = (shape.te_layers - kt) * shape.te_layer_bytes@@ -169,4 +183,4 @@ def plan_image(*, gpu_budget_bytes, host_available_bytes=None, width=1024, heighhost_mode=host_mode, feasible=feasible and host_mode != 'insufficient',peak_allocated_bytes=max(peaks.values()), stage_peaks=peaks, margin_bytes=margin,dit_streamed_bytes_per_step=streamed_dit, te_streamed_bytes=streamed_te,- link_floor_seconds=floor, reasons=reasons)+ link_floor_seconds=floor, reasons=reasons, vae_tile_size=tile_size)diff --git a/freevideo_engine/image_gen/image_runner.py b/freevideo_engine/image_gen/image_runner.pyindex cde4150..e826f0d 100644--- a/freevideo_engine/image_gen/image_runner.py+++ b/freevideo_engine/image_gen/image_runner.py@@ -176,6 +176,7 @@ class ImageRunner:self.dit_stack.set_resident(plan.dit_resident_layers)self.te_stack.set_resident(plan.te_resident_layers)self.generator.vae_tile = plan.vae_tiling+ self.generator.vae_tile_size = plan.vae_tile_sizereturn self.generator.generate(prompt, width=width, height=height, seed=seed,reference_images=reference_images, progress=progress, cancel=cancel)diff --git a/freevideo_engine/image_gen/qwen_pipeline.py b/freevideo_engine/image_gen/qwen_pipeline.pyindex e4c90f0..8bde8b5 100644--- a/freevideo_engine/image_gen/qwen_pipeline.py+++ b/freevideo_engine/image_gen/qwen_pipeline.py@@ -158,6 +158,7 @@ class QwenImageGenerator:self.text_encoder = text_encoderself._closed = Falseself.vae_tile = vae_tile+ self.vae_tile_size = None # None: the decoder's own profileif not isinstance(reference_resolution, int) or reference_resolution < 32:raise ValueError("reference_resolution must be at least 32")self.reference_resolution = reference_resolution@@ -358,6 +359,9 @@ class QwenImageGenerator:kwargs = {"return_dict": False}if self.vae_tile:kwargs["tile"] = True+ if self.vae_tile_size:+ kwargs["tile_size"] = int(self.vae_tile_size)+ kwargs["tile_stride"] = int(self.vae_tile_size) // 2pixels = _sample(self.vae.decode(latents, **kwargs))[:, :, 0]check_cancel()array = (pixels / 2 + 0.5).clamp(0, 1).float().cpu().permute(0, 2, 3, 1).numpy()[0]diff --git a/freevideo_engine/image_gen/qwen_vae.py b/freevideo_engine/image_gen/qwen_vae.pyindex e00ecc0..e96861c 100644--- a/freevideo_engine/image_gen/qwen_vae.py+++ b/freevideo_engine/image_gen/qwen_vae.py@@ -1344,7 +1344,8 @@ class QwenImageVAE(nn.Module):return DecoderOutput(sample=out)# Copied from diffusers.models.autoencoders.autoencoder_kl_wan.AutoencoderKLWan.decode- def decode(self, z: torch.Tensor, return_dict: bool = True, *, tile: bool | None = None) -> DecoderOutput | torch.Tensor:+ def decode(self, z: torch.Tensor, return_dict: bool = True, *, tile: bool | None = None,+ tile_size: int | None = None, tile_stride: int | None = None) -> DecoderOutput | torch.Tensor:r"""Decode a batch of images.@@ -1359,8 +1360,15 @@ class QwenImageVAE(nn.Module):returned."""previous_tiling = self.use_tiling+ previous_tiles = (self.tile_sample_min_height, self.tile_sample_min_width,+ self.tile_sample_stride_height, self.tile_sample_stride_width)if tile is not None:self.use_tiling = tile+ if tile_size is not None:+ # Larger decoding tiles keep the decoder's padded tile edges out of the picture;+ # encoding keeps its own profile so the latents do not depend on the card.+ self.tile_sample_min_height = self.tile_sample_min_width = int(tile_size)+ self.tile_sample_stride_height = self.tile_sample_stride_width = int(tile_stride or tile_size // 2)try:if self.use_slicing and z.shape[0] > 1:decoded_slices = [self._decode(z_slice).sample for z_slice in z.split(1)]@@ -1369,6 +1377,8 @@ class QwenImageVAE(nn.Module):decoded = self._decode(z).samplefinally:self.use_tiling = previous_tiling+ (self.tile_sample_min_height, self.tile_sample_min_width,+ self.tile_sample_stride_height, self.tile_sample_stride_width) = previous_tilesif not return_dict:return (decoded,)@@ -1504,9 +1514,11 @@ class QwenImageVAE(nn.Module):# Split z into overlapping tiles and decode them separately.# The tiles have an overlap to avoid seams between tiles.rows = []- for i in range(0, height, tile_latent_stride_height):+ # Stop once a tile already covers the edge: a redundant narrow last tile has little+ # context and leaves coloured seams.+ for i in range(0, max(0, height - tile_latent_min_height) + tile_latent_stride_height, tile_latent_stride_height):row = []- for j in range(0, width, tile_latent_stride_width):+ for j in range(0, max(0, width - tile_latent_min_width) + tile_latent_stride_width, tile_latent_stride_width):self.clear_cache()time = []for k in range(num_frames):@@ -1531,7 +1543,9 @@ class QwenImageVAE(nn.Module):tile = self.blend_v(rows[i - 1][j], tile, blend_height)if j > 0:tile = self.blend_h(row[j - 1], tile, blend_width)- result_row.append(tile[:, :, :, :tile_sample_stride_height, :tile_sample_stride_width])+ keep_height = tile_sample_stride_height if i < len(rows) - 1 else sample_height - i * tile_sample_stride_height+ keep_width = tile_sample_stride_width if j < len(row) - 1 else sample_width - j * tile_sample_stride_width+ result_row.append(tile[:, :, :, :keep_height, :keep_width])result_rows.append(torch.cat(result_row, dim=-1))dec = torch.cat(result_rows, dim=3)[:, :, :, :sample_height, :sample_width]diff --git a/freevideo_engine/macos_vdn.py b/freevideo_engine/macos_vdn.pyindex dd3c5a5..0dd0c07 100644--- a/freevideo_engine/macos_vdn.py+++ b/freevideo_engine/macos_vdn.py@@ -94,7 +94,10 @@ def prepare(source, directory):path.parent.mkdir(parents=True, exist_ok=True)path.write_bytes(data)(stage / 'identity.json').write_text(json.dumps(identity, indent=2) + '\n')- shutil.copyfile(source / 'LICENSE', stage / 'LICENSE')+ try:+ shutil.copyfile(source / 'LICENSE', stage / 'LICENSE')+ except OSError:+ pass # the licence text is carried when the source has onetry:stage.rename(target)except OSError:diff --git a/freevideo_engine/policy.py b/freevideo_engine/policy.pyindex b7d21d1..13e87ae 100644--- a/freevideo_engine/policy.py+++ b/freevideo_engine/policy.py@@ -434,12 +434,14 @@ FF_STASH_WIDTH = 14336 # BF16 SwiGLU output channels kept for the per-tensor FP# blocks, against 7.14 and 7.82 from the envelope, so the plan held sixteen# and eighteen blocks where the budget held about twenty-five and streamed# the rest from disk on every step. Each figure carries one GiB of margin.-# The curve joins the envelope at its lowest anchor (896 square, 243-# frames) and never exceeds it. It rests on one card.+# It rests on one card and holds only up to its last measured point. Joined+# straight to the envelope's anchor, a 16 GB Windows laptop's 44370-token+# refinement held three more blocks than the envelope gave, filled the card+# beside other programs, and Windows moved memory to system RAM: each step+# took five times as long. Above 16320 tokens the envelope applies.SMALL_CANVAS_INT8_WORKSPACE = ((4320, 3.48),(16320, 4.46),- (56448, 6.5 + 6. * 56448 / 72576 + BLOCK_BYTES / GiB - 56448 * FF_STASH_WIDTH * 2 / GiB),)@@ -458,12 +460,12 @@ def windows_gpu_output_workspace(video_tokens, *, prefetch=False, ff_stash=True,estimate, not a fitted throughput model or proof of capacity elsewhere.The OS growth reserve has already been subtracted from the budget.- small_canvas=True counts resident blocks below the anchors from the- measured int8 curve (SMALL_CANVAS_INT8_WORKSPACE) instead of the envelope.+ small_canvas=True counts resident blocks up to the last measured point+ from the int8 curve (SMALL_CANVAS_INT8_WORKSPACE) instead of the envelope.Head-group choices keep using the envelope."""tokens = 72576 if video_tokens is None else video_tokens- if small_canvas and not ff_stash and tokens < SMALL_CANVAS_INT8_WORKSPACE[-1][0]:+ if small_canvas and not ff_stash and tokens <= SMALL_CANVAS_INT8_WORKSPACE[-1][0]:for (low, at_low), (high, at_high) in zip(SMALL_CANVAS_INT8_WORKSPACE, SMALL_CANVAS_INT8_WORKSPACE[1:]):if tokens <= high:at = at_low + (at_high - at_low) * max(0, tokens - low) / (high - low)diff --git a/freevideo_engine/weights.py b/freevideo_engine/weights.pyindex b2bf11d..104dfd9 100644--- a/freevideo_engine/weights.py+++ b/freevideo_engine/weights.py@@ -5,8 +5,10 @@ the derived per-block cache records its own identity, preparation time and hashe"""import hashlibimport json+import loggingfrom pathlib import Pathimport re+import shutilimport timefrom safetensors.torch import save_file@@ -124,16 +126,26 @@ def prepare(base, checkpoint, cache_root):output, identity, key = cache_location(cache_root, 'vdn-bf16-', identity)output.mkdir(parents=True, exist_ok=True)marker = output / 'source.json'+ invalid = Noneif marker.exists() and json.loads(marker.read_text(encoding='utf-8')) != identity:- raise ValueError('Prepared weight identity conflict: ' + str(output))- marker.write_text(json.dumps(identity, indent=2) + '\n', encoding='utf-8')+ invalid = 'Prepared weight identity conflict: ' + str(output)manifest = output / 'manifest.json'- if manifest.exists():+ if invalid is None and manifest.exists():record = json.loads(manifest.read_text(encoding='utf-8'))for item in record['groups']:path = output / item['file']if not path.is_file() or path.stat().st_size != item['bytes']:- raise ValueError('Prepared weight cache is incomplete: ' + str(path))+ invalid = 'Prepared weight cache is incomplete: ' + str(path)+ break+ if invalid is not None:+ root, resolved = cache_root.resolve(), output.resolve()+ if resolved == root or not resolved.is_relative_to(root):+ raise ValueError('Refusing to delete prepared weight cache outside cache root: ' + str(output))+ logging.getLogger(__name__).warning('%s; rebuilding cache', invalid)+ shutil.rmtree(output)+ output.mkdir(parents=True, exist_ok=True)+ marker.write_text(json.dumps(identity, indent=2) + '\n', encoding='utf-8')+ if manifest.exists():print(json.dumps({'cache': str(output), 'reused': True}), flush=True)return outputgroups = {}diff --git a/web/editor_text.js b/web/editor_text.jsindex 9ac5901..a161dca 100644--- a/web/editor_text.js+++ b/web/editor_text.js@@ -145,8 +145,8 @@ export function createEditorText({element,state,t,actions,adjust,player,toolbar,const file=el('input');file.type='file';file.accept='.srt';file.hidden=true;const importButton=button(t('Import subtitle file','导入字幕文件'),{onClick:()=>file.click()});importButton.classList.add('fv-ed-import-srt');// Only a file that cannot be read says so; a refused edit (a locked track) flashes red like any other.- file.onchange=async()=>{const f=file.files?.[0];if(!f)return;let text;try{if(f.size>4*1024*1024)throw new Error();text=await f.text();parseSRT(text);}catch{actions.notify?.(t('Could not read this subtitle file','读不出这个字幕文件'));return;}finally{file.value='';}- if(apply(t('Import subtitle file','导入字幕文件'),r=>importSRT(r,text))){const missing=projectMissing(state.record);if(missing.length)actions.notify?.(missingHint([...new Set(missing.flatMap(r=>r.chars))],t));}};+ file.onchange=async()=>{const f=file.files?.[0];if(!f)return;let text;const result={};try{if(f.size>4*1024*1024)throw new Error();text=await f.text();parseSRT(text,result);}catch{actions.notify?.(t('Could not read this subtitle file','读不出这个字幕文件'));return;}finally{file.value='';}+ if(apply(t('Import subtitle file','导入字幕文件'),r=>importSRT(r,text))){const missing=projectMissing(state.record);if(missing.length)actions.notify?.(missingHint([...new Set(missing.flatMap(r=>r.chars))],t));if(result.truncated)actions.notify?.(t('Only the first 500 subtitles were imported.','只导入了前 500 条字幕。'));}};// Shown only where this computer can recognise speech.const hear=button(t('Auto subtitles','自动字幕'),{onClick:toggleSpeech});hear.classList.add('fv-ed-auto-subtitles');for(const b of speech.buttons)if(!b.isConnected)speech.buttons.delete(b);speech.buttons.add(hear);speechLabel(speech.busy?speech.shown:null);host.append(importButton,hear,file);diff --git a/web/editor_text_model.js b/web/editor_text_model.jsindex cf42183..8055646 100644--- a/web/editor_text_model.js+++ b/web/editor_text_model.js@@ -98,17 +98,34 @@ export function activeText(record, frame) {return record.tracks.filter(t => isTextTrack(t) && !t.hidden).sort((a,b) => (a.kind === 'text' ? -1 : 1) - (b.kind === 'text' ? -1 : 1)).flatMap(t => t.clips.filter(c => c.start <= frame && c.start+c.frames > frame).map(c => ({...c, style: styleOf(record,c), opacity: c.text_kind === 'text' && styleOf(record,c).fade ? Math.min(1,(frame-c.start+.5)/7.2,(c.start+c.frames-frame-.5)/7.2) : 1})));}-export function parseSRT(text) {+export function parseSRT(text, result = {}) {check(typeof text === 'string' && text.length <= 4*1024*1024, 'srt');const blocks = text.replace(/^\ufeff/, '').replace(/\r\n?/g,'\n').trim().split(/\n\s*\n/);- check(blocks.length > 0 && blocks.length <= 500, 'srt'); let end = 0;- return blocks.map(block => {- const lines = block.split('\n'); if (/^\d+$/.test(lines[0])) lines.shift();- const match = /^(\d{2,3}):([0-5]\d):([0-5]\d)[,.](\d{3}) --> (\d{2,3}):([0-5]\d):([0-5]\d)[,.](\d{3})$/.exec(lines.shift()); check(match && lines.length, 'srt');- const time = i => Math.round((Number(match[i])*3600+Number(match[i+1])*60+Number(match[i+2])+Number(match[i+3])/1000)*24);- const start = time(1), stop = time(5); check(start >= end && stop > start && stop <= 1e7, 'srt'); end = stop;- return {at:start, frames:stop-start, text:lines.join('\n'), kind:'subtitle'};- });+ const entries = []; let skipped = 0, trimmed = 0;+ for (const block of blocks) {+ let entry;+ try {+ const lines = block.split('\n'); if (/^\d+$/.test(lines[0])) lines.shift();+ const match = /^(\d{2,3}):([0-5]\d):([0-5]\d)[,.](\d{3}) --> (\d{2,3}):([0-5]\d):([0-5]\d)[,.](\d{3})$/.exec(lines.shift()); check(match && lines.length, 'srt');+ const time = i => Math.round((Number(match[i])*3600+Number(match[i+1])*60+Number(match[i+2])+Number(match[i+3])/1000)*24);+ const start = time(1), stop = time(5), content = lines.join('\n');+ check(stop > start && stop <= 1e7 && Array.from(content).length <= TEXT_LIMIT && !/[\u0000-\u0008\u000b-\u001f\u007f\ud800-\udfff]/u.test(content), 'srt');+ entry = {at:start, frames:stop-start, text:content, kind:'subtitle'};+ } catch { skipped++; continue; }+ // Keep readable cues in file order, shortening or removing earlier overlaps.+ while (entries.length && entries.at(-1).at + entries.at(-1).frames > entry.at) {+ const previous = entries.at(-1); previous.frames = entry.at - previous.at; trimmed++;+ if (previous.frames > 0) break;+ entries.pop();+ }+ entries.push(entry);+ }+ if (skipped) console.warn(`FreeVideo SRT import skipped ${skipped} unreadable blocks.`);+ if (trimmed) console.warn(`FreeVideo SRT import trimmed ${trimmed} overlapping subtitles.`);+ check(entries.length > 0, 'srt');+ result.truncated = entries.length > 500;+ if (result.truncated) console.warn('FreeVideo SRT import kept only the first 500 subtitles.');+ return entries.slice(0, 500);}// An import replaces every subtitle already there, in one edit that one undo reverses.export function importSRT(record, text) {diff --git a/web/image_editor.js b/web/image_editor.jsindex 0881ec0..bc32ca9 100644--- a/web/image_editor.js+++ b/web/image_editor.js@@ -145,7 +145,7 @@ export async function openImageEditor({source = null, name = source || '', targedoc = commands.setRatio(doc, 'video', target);}// Text draws with the fonts that ship with FreeVideo; the text tool starts in bold sans.- await Promise.all([renderer.preload(doc), loadFont('sans', 700)]);+ await Promise.all([renderer.preload(doc), loadFont('sans', 700).catch(error => console.warn('FreeVideo image editor font unavailable; using fallback fonts.', error))]);// A text box measured with other fonts (or by another renderer) fits its text again,// keeping its place and scale. It is part of opening, not a change to undo or save.doc = {...doc, layers: doc.layers.map(l => {@@ -667,7 +667,7 @@ export async function openImageEditor({source = null, name = source || '', targev => setTextFont(layer.id, {font: v}), t('Font', '字体'));font.group.id = 'fv-ie-font'; font.group.classList.add('fv-ie-fonts');for (const b of font.group.children) b.style.fontFamily = fontStack(b.dataset.value);- loadFonts(FONT_KEYS.map(k => [k, 400])).catch(() => {});+ loadFonts(FONT_KEYS.map(k => [k, 400])).catch(error => console.warn('FreeVideo image editor fonts unavailable; using fallback fonts.', error));const size = el('input'); size.type = 'number'; size.min = '6'; size.max = '2000'; size.value = String(Math.round(layer.text.size)); size.id = 'fv-ie-font-size';size.onchange = () => commit(updateText(layer.id, {size: clamp(Number(size.value) || 12, 6, 2000)}));const color = el('input'); color.type = 'color'; color.value = layer.text.color; color.id = 'fv-ie-text-color';@@ -697,7 +697,7 @@ export async function openImageEditor({source = null, name = source || '', targeif (!fontLoaded(next.font, next.weight)) {message(t('Preparing the font…', '正在准备字体…'));try { await loadFont(next.font, next.weight); }- catch { message(t('The font could not be loaded. Reload the page and try again.', '字体加载失败,请刷新页面后重试。')); renderProps(); return; }+ catch (error) { console.warn('FreeVideo image editor font unavailable; using fallback fonts.', error); }message('');}if (dialog.open && doc.layers.some(l => l.id === id)) commit(updateText(id, patch));@@ -1507,6 +1507,6 @@ export async function openImageEditor({source = null, name = source || '', targeselect(!doc.layers.length ? 'generate' : startTool || (fresh && target && role !== 'reference' ? 'crop' : 'move'));(save.disabled ? stage : save).focus();// The other fonts load in the background, so switching to one is immediate.- loadFonts(FONT_KEYS.flatMap(k => [[k, 400], [k, 700]])).catch(() => {});+ loadFonts(FONT_KEYS.flatMap(k => [[k, 400], [k, 700]])).catch(error => console.warn('FreeVideo image editor fonts unavailable; using fallback fonts.', error));return result;}diff --git a/web/image_editor_engine.js b/web/image_editor_engine.jsindex 4830d15..896451c 100644--- a/web/image_editor_engine.js+++ b/web/image_editor_engine.js@@ -10,7 +10,12 @@// Every edit is an entry in a list, so a saved document reopens from the// original image with each step still in place.-import {fontCSS, fontLoaded, loadFonts} from './fonts.js';+import {fontCSS as bundledFontCSS, fontLoaded, loadFonts} from './fonts.js';+// A blocked font must not turn otherwise readable text into the bundled box glyph.+const fontCSS = (name, weight, size) => {+ const css = bundledFontCSS(name, weight, size);+ return fontLoaded(name, weight) ? css : css.replace('"FreeVideo Box"', 'sans-serif');+};export const BLENDS = ['source-over', 'multiply', 'screen', 'overlay', 'soft-light', 'darken', 'lighten','color-dodge', 'color-burn', 'difference'];@@ -117,8 +122,7 @@ export const rasterKinds = new Set(['image', 'paint']);export const textFonts = doc => doc.layers.filter(l => l.kind === 'text').map(l => [l.text.font, l.text.weight]);export const textFontsLoaded = doc => textFonts(doc).every(([name, weight]) => fontLoaded(name, weight));-// Native size of a text block, from the same font settings it is drawn with. The font must-// be loaded (textFonts): measuring before that would use another font's metrics.+// Native size of a text block, using the same bundled or fallback font as drawing.export function measureText(text) {const ctx = document.createElement('canvas').getContext('2d');ctx.font = fontCSS(text.font, text.weight, text.size);@@ -970,7 +974,7 @@ export class Renderer {loaded(file) { return this.images.get(file)?.value; }async preload(doc) {for (const l of doc.layers) if (l.src) { const img = await this.image(l.src); this.images.get(l.src).value = img; }- await loadFonts(textFonts(doc));+ await loadFonts(textFonts(doc)).catch(error => console.warn('FreeVideo image editor fonts unavailable; using fallback fonts.', error));}// Raster of a layer at scale × its native pixels, edits applied (before// adjustments and mask), reusing the cached prefix of its edits. exact: for a saved@@ -1120,7 +1124,7 @@ export class Renderer {return out;}text(layer, scale) {- const key = `${layer.id}@${scale}#text`, look = JSON.stringify([layer.text, layer.nw, layer.nh]);+ const key = `${layer.id}@${scale}#text`, look = JSON.stringify([layer.text, layer.nw, layer.nh, fontCSS(layer.text.font, layer.text.weight, layer.text.size)]);const cached = this.layers.get(key);if (cached?.look === look) return cached.canvas;const t = layer.text, c = canvas(layer.nw * scale, layer.nh * scale), ctx = c.getContext('2d');diff --git a/web/prompt_enhance.js b/web/prompt_enhance.jsindex 49d9cb3..8cd3c68 100644--- a/web/prompt_enhance.js+++ b/web/prompt_enhance.js@@ -257,15 +257,28 @@ export function createPromptEnhancer({node, input, editor, api, context, setText};redo.onclick = () => enhance().catch(() => {});show(''); save(false); render();+ function useOriginal(error) {+ console.warn('FreeVideo prompt rewrite failed; using the original prompt.', error?.message);+ versions.value.selected = 'original'; apply();+ show(t('Could not enhance; generated with the original.', '没能改写,已用原文生成。'), 'note');+ }return {element, async beforeGenerate() {if (running) {try { await running; }- catch (error) { if (versions.value.enabled && !versions.value.useOriginal) return false; }+ catch (error) {+ if (versions.value.enabled && !versions.value.useOriginal) {+ if (error?.message === 'cancelled' || cancelling || disposed) return false;+ useOriginal(error); return;+ }+ }}// An untouched box generates the starter prompt as it is.if (!versions.value.enabled || versions.value.useOriginal || !versions.value.original.trim()) return;try { if (!versions.fresh(context())) await enhance(); }- catch (error) { show(errorText(error), error?.message === 'cancelled' ? '' : 'error'); return false; }+ catch (error) {+ if (error?.message === 'cancelled' || cancelling || disposed) { show(errorText({message: 'cancelled'})); return false; }+ useOriginal(error);+ }}, sync() { if (input.value !== versions.text()) changed(); }, dispose() {disposed = true; prestart.dispose(); cancelJob().catch(() => {}); input.removeEventListener('input', changed);input.removeEventListener('beforeinput', replace);diff --git a/web/share.js b/web/share.jsindex c4f6248..622e90a 100644--- a/web/share.js+++ b/web/share.js@@ -1,7 +1,7 @@import {api} from '../../scripts/api.js';import {closeDialog} from './motion.js';import {effortFor, effortName} from './sampling_effort.js';-import {fontCSS, loadFont} from './fonts.js';+import {fontCSS as bundledFontCSS, fontLoaded, loadFont} from './fonts.js';import {shareLayout} from './share_layout.js';const css=document.createElement('link'); css.rel='stylesheet'; css.href=new URL('./share.css',import.meta.url).href; document.head.append(css);@@ -27,10 +27,9 @@ async function withGraph(blob,graph){const tint=(hex,alpha)=>{const v=parseInt(hex.slice(1),16);return `rgba(${v>>16},${v>>8&255},${v&255},${alpha})`;};let opened;-// Deterministic Canvas rendering in FreeVideo's bundled sans (load it first: shareFonts), never a-// font of the computer; no external resources or user prompt are included. The image window-// preserves every pixel.-export const shareFonts=()=>Promise.all([loadFont('sans',400),loadFont('sans',700)]);+// Prefer bundled sans, but keep the card usable when optional font files are blocked.+export const shareFonts=()=>Promise.all([loadFont('sans',400),loadFont('sans',700)]).catch(error=>console.warn('FreeVideo share fonts unavailable; using fallback fonts.',error));+const fontCSS=(name,weight,size)=>{const css=bundledFontCSS(name,weight,size);return fontLoaded(name,weight)?css:css.replace('"FreeVideo Box"','sans-serif');};export function drawShareCard(canvas,frame,logo,record,t) {const g=record.geometry||{}, shape=shareLayout(g.width||frame?.naturalWidth||1344,g.height||frame?.naturalHeight||768);@@ -49,7 +48,7 @@ export function drawShareCard(canvas,frame,logo,record,t) {if(frame)ctx.drawImage(frame,...shape.rect);const fit=(text,weight,size,max)=>{while(size>12){ctx.font=fontCSS('sans',weight,size);if(ctx.measureText(text).width<=max)break;size--;}return ctx.measureText(text).width;};const logoWidth=wide?156:140, logoTop=wide?y+H/2-26:y+30;- ctx.drawImage(logo,pad,logoTop,logoWidth,logoWidth*337/2016);+ if(logo)ctx.drawImage(logo,pad,logoTop,logoWidth,logoWidth*337/2016);const seconds=g.seconds||g.frames/(g.fps||24);ctx.font=fontCSS('sans',400,14);ctx.fillStyle='#6f8399';ctx.textAlign=wide?'left':'right';ctx.fillText(`${g.width} × ${g.height}${Number.isFinite(seconds)?' · '+seconds.toFixed(1)+' s':''}`,wide?pad:w-pad,wide?y+H/2+24:y+46);@@ -157,9 +156,9 @@ export async function openShare(record,t){const response=await api.fetchApi('/freevideo/share?'+new URLSearchParams({id}),{signal:abort.signal});if(!response.ok)throw new Error(t('This saved video is unavailable.','这个已保存的视频暂时无法读取。'));metadata=await response.json();- [first,logo]=await Promise.all([image(api.apiURL('/freevideo/share/frame?'+new URLSearchParams({id}))),image(new URL('./assets/freevideo.svg',import.meta.url).href)]);+ [first,logo]=await Promise.all([image(api.apiURL('/freevideo/share/frame?'+new URLSearchParams({id}))),image(new URL('./assets/freevideo.svg',import.meta.url).href).catch(error=>{console.warn('FreeVideo share logo unavailable; continuing without it.',error);return null;})]);if(disposed)return;- await shareFonts();if(document.fonts?.ready)await document.fonts.ready;+ await shareFonts();if(document.fonts?.ready)await document.fonts.ready.catch(error=>console.warn('FreeVideo share fonts unavailable; using fallback fonts.',error));shape=drawShareCard(canvas,null,logo,metadata,t);template=canvas.toDataURL('image/png').split(',')[1];preview.style.aspectRatio=`${shape.width}/${shape.height}`;player.style.cssText=`left:${shape.rect[0]/shape.width*100}%;top:0;width:${shape.rect[2]/shape.width*100}%;height:${shape.rect[3]/shape.height*100}%`;diff --git a/web/updates.js b/web/updates.jsindex 78b205c..0475c13 100644--- a/web/updates.js+++ b/web/updates.js@@ -1,8 +1,7 @@import { api } from '../../scripts/api.js';-// Every platform downloads from one release: the latest vX.Y.Z, or the rolling nightly.+// Every platform downloads from one release: the latest vX.Y.Z.const releasePage = 'https://github.com/FlashML-org/FreeVideo/releases/latest';-const nightlyPage = 'https://github.com/FlashML-org/FreeVideo/releases/tag/nightly';const storageKey = 'freevideo.dismissed-update';const listeners = new Set();// Launcher phases during which the server may disappear and come back updated.@@ -135,7 +134,7 @@ export function createUpdateNotice(cn) {const render = () => {const launcher = value?.launcher, phase = launcher?.phase || '', candidate = value?.available;const mac = value?.channel === 'macos-preview', linux = value?.channel === 'linux-preview';- link.href = value?.track === 'nightly' ? nightlyPage : releasePage;+ link.href = releasePage;link.title = mac? t('After your task finishes, open the new FreeVideo.app to update.', '当前任务完成后,打开新版 FreeVideo.app 更新。'): linux ? t('After your task finishes, open the new FreeVideo AppImage to update.', '当前任务完成后,打开新版 FreeVideo AppImage 更新。')