Skip to content

Make videos on the computer you already own. FreeVideo runs MiniMax H3 in as little as 8 GB of VRAM and 16 GB of RAM, and adapts its acceleration path to your hardware.

Agent interface, chained long-video generation and editor foundations

Bowen Xue2d450816661c
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index fe905cc..1c8d199 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -7,15 +7,16 @@ FreeVideo code uses [Apache-2.0](LICENSE). Its dependencies and models retain th
| Qt, PySide6 and Shiboken6 | LGPL-3.0; [component notices](freevideo_engine/launcher/licenses/NOTICE.txt) |
| PyInstaller bootloader | GPL-2.0 with the bootloader exception |
| CPython / psutil | PSF / BSD-3-Clause |
+| [QuickJS Python binding](https://github.com/PetterS/quickjs) 1.19.4 (author: Petter Strandmark) and QuickJS (© 2017–2021 Fabrice Bellard and Charlie Gordon) | [MIT notices](freevideo_engine/licenses/quickjs-MIT.txt) |
| [ComfyUI](https://github.com/Comfy-Org/ComfyUI), including the H3 text encoder code | GPL-3.0 |
| [VDN-H3](https://github.com/OpenVDN/vdn-minimax-h3), [Diffusers](https://github.com/huggingface/diffusers), [SageAttention](https://github.com/thu-ml/SageAttention) | Apache-2.0 |
| [VDN-H3 and H3 model weights](https://huggingface.co/OpenVDN/vdn-minimax-h3-edge/blob/main/LICENSE) | MiniMax H3 Community License |
| [MiniMax H3 latent upscaler](https://huggingface.co/LBH-123-AI/Minimax_h3_latent_Upscaler) | [MIT](freevideo_engine/licenses/latent-upscaler-MIT.txt) |
| [FreeToken](https://github.com/FlashML-org/FreeToken) prompt VLM operators, [Qwen3-VL-4B-Instruct](https://huggingface.co/Qwen/Qwen3-VL-4B-Instruct) optional weights | [Apache-2.0](freevideo_engine/licenses/FreeToken-Apache-2.0.txt) |
| [Lucide](https://lucide.dev) icons (image editor: eyedropper, hand, crop) | [ISC](freevideo_engine/licenses/Lucide-ISC.txt) |
-| [Noto Sans CJK SC and Noto Sans Mono CJK SC](https://github.com/notofonts/noto-cjk) 2.004, © 2014-2021 Adobe: subsets renamed FreeVideo Sans SC and FreeVideo Mono SC (image editor text, share card, Linux launcher) | [SIL OFL 1.1](freevideo_engine/licenses/Noto-CJK-Sans-OFL.txt) |
-| [Noto Serif CJK SC](https://github.com/notofonts/noto-cjk) 2.003, © 2017-2024 Adobe: subset renamed FreeVideo Serif SC (image editor text) | [SIL OFL 1.1](freevideo_engine/licenses/Noto-CJK-Serif-OFL.txt) |
-| [LXGW WenKai](https://github.com/lxgw/LxgwWenKai) v1.522, © 2021-2026 LXGW, © 2020 The Klee Project Authors: subset renamed FreeVideo Kai SC (image editor text) | [SIL OFL 1.1](freevideo_engine/licenses/LXGW-WenKai-OFL.txt) |
+| [Noto Sans CJK SC and Noto Sans Mono CJK SC](https://github.com/notofonts/noto-cjk) 2.004, © 2014-2021 Adobe: subsets renamed FreeVideo Sans SC and FreeVideo Mono SC (image editor text, editor text and subtitles / 剪辑视图的文字和字幕, share card, Linux launcher) | [SIL OFL 1.1](freevideo_engine/licenses/Noto-CJK-Sans-OFL.txt) |
+| [Noto Serif CJK SC](https://github.com/notofonts/noto-cjk) 2.003, © 2017-2024 Adobe: subset renamed FreeVideo Serif SC (image editor text, editor text and subtitles / 剪辑视图的文字和字幕) | [SIL OFL 1.1](freevideo_engine/licenses/Noto-CJK-Serif-OFL.txt) |
+| [LXGW WenKai](https://github.com/lxgw/LxgwWenKai) v1.522, © 2021-2026 LXGW, © 2020 The Klee Project Authors: subset renamed FreeVideo Kai SC (image editor text, editor text and subtitles / 剪辑视图的文字和字幕) | [SIL OFL 1.1](freevideo_engine/licenses/LXGW-WenKai-OFL.txt) |
Original launcher license texts are included in Windows packages. Other runtime dependencies are listed in [constraints](constraints), with their license information in the installed packages.
diff --git a/__init__.py b/__init__.py
index 98f88f8..ef16ef7 100644
--- a/__init__.py
+++ b/__init__.py
@@ -5,6 +5,12 @@ WEB_DIRECTORY = './web'
async def comfy_entrypoint():
from .freevideo_engine.comfy_progress import register as progress_routes
progress_routes()
+ try:
+ from .freevideo_engine.comfy_chain import register as chain_routes
+ chain_routes()
+ except Exception as error:
+ import logging
+ logging.warning('[FreeVideo] Chain routes not registered: %s', error)
from .freevideo_engine.comfy_upload import register
register()
from .freevideo_engine.comfy_setup import register as setup_routes
@@ -17,11 +23,17 @@ async def comfy_entrypoint():
update_routes()
from .freevideo_engine.comfy_library import register as library_routes
library_routes()
+ from .freevideo_engine.comfy_editor import register as editor_routes
+ editor_routes()
+ from .freevideo_engine.editor_export import register as editor_export_routes
+ editor_export_routes()
from .freevideo_engine.comfy_capabilities import register as capabilities_routes
capabilities_routes()
from .freevideo_engine.comfy_share import register as share_routes
share_routes()
from .freevideo_engine.comfy_metadata import register as workflow_backfill
workflow_backfill()
+ from .freevideo_engine.agent.routes import register as agent_routes
+ agent_routes()
from .freevideo_engine.comfy_nodes import FreeVideoExtension
return FreeVideoExtension()
diff --git a/constraints/engine.txt b/constraints/engine.txt
index 7f56b90..5260638 100644
--- a/constraints/engine.txt
+++ b/constraints/engine.txt
@@ -62,6 +62,7 @@ protobuf==6.33.6
psutil==7.2.2
pygments==2.21.0
pyyaml==6.0.3
+quickjs==1.19.4
quack-kernels==0.5.3
regex==2026.9.3
requests==2.34.2
diff --git a/constraints/macos-runtime-requirements.txt b/constraints/macos-runtime-requirements.txt
index 3a2708d..3079258 100644
--- a/constraints/macos-runtime-requirements.txt
+++ b/constraints/macos-runtime-requirements.txt
@@ -15,6 +15,7 @@ httpx[socks]
requests[socks]
importlib-metadata
packaging
+quickjs==1.19.4
wheel
setuptools
pip
diff --git a/constraints/macos-runtime.txt b/constraints/macos-runtime.txt
index 4db0198..f9d6522 100644
--- a/constraints/macos-runtime.txt
+++ b/constraints/macos-runtime.txt
@@ -43,6 +43,7 @@ pygments==2.21.0
pycparser==3.0
pysocks==1.7.1
pyyaml==6.0.3
+quickjs==1.19.4
regex==2026.9.3
requests==2.34.2
rich==15.0.0
diff --git a/constraints/unified.txt b/constraints/unified.txt
index 882a9d6..883da4a 100644
--- a/constraints/unified.txt
+++ b/constraints/unified.txt
@@ -59,6 +59,7 @@ pygments==2.21.0
pycparser==3.0
pysocks==1.7.1
pyyaml==6.0.3
+quickjs==1.19.4
regex==2026.9.3
requests==2.34.2
rich==15.0.0
diff --git a/constraints/windows-portable.txt b/constraints/windows-portable.txt
index 5d57608..66290b9 100644
--- a/constraints/windows-portable.txt
+++ b/constraints/windows-portable.txt
@@ -73,6 +73,7 @@ pyopengl==3.1.10
pysocks==1.7.1
python-dotenv==1.2.3
pyyaml==6.0.3
+quickjs==1.19.4
regex==2026.9.3
requests==2.34.2
rich==15.0.0
diff --git a/constraints/windows-unified.txt b/constraints/windows-unified.txt
index f369953..b545bd4 100644
--- a/constraints/windows-unified.txt
+++ b/constraints/windows-unified.txt
@@ -42,6 +42,7 @@ pip==26.2.1
psutil==7.2.2
pygments==2.21.0
pyyaml==6.0.3
+quickjs==1.19.4
regex==2026.9.3
requests==2.34.2
rich==15.0.0
diff --git a/docs/community-results.md b/docs/community-results.md
index 4194d60..e149f0f 100644
--- a/docs/community-results.md
+++ b/docs/community-results.md
@@ -48,11 +48,6 @@ Thanks to the community members who sent diagnostic reports. FreeVideo already r
| 5060 | 8 GB | 32 GB | 1344×768 | 10 s | Light | 0.3.23 | 1279 s | 0.3.25 | 1150 s (−130 s) |
| 3060 | 12 GB | 32 GB | 832×1248 | 10 s | Light | 0.3.24 | 1668 s | 0.3.24 | GPU shared⁷ |
| 5080 | 16 GB | 64 GB | 1344×768 | 10 s | Light | 0.3.24 | 312 s | 0.3.24 | 278 s (−34 s) |
-| 4070 Ti SUPER | 16 GB | 96 GB | 1344×768 | 10 s | Light | 0.3.24 | 575 s | 0.3.24 | Already optimal |
-| 4080 Laptop | 12 GB | 32 GB | 1344×768 | 10 s | Light | 0.3.24 | 970 s | 0.3.24 | Already optimal |
-| 4060 Laptop | 8 GB | 32 GB | 768×1344 | 6.6 s | Light⁵ | 0.3.24 | 386 s | 0.3.24 | Already optimal |
-| 5060 Ti | 16 GB | 32 GB | 768×1344 | 15.1 s | Light | 0.3.24 | 847 s | 0.3.24 | Already optimal |
-| 5060 | 8 GB | 32 GB | 1344×768 | 4.5 s | Light | 0.3.25 | 390 s | 0.3.25 | Already optimal |
- Time: end to end, from submission until the video is saved.
- After: the estimated time, derived from the report's stage times and from complete planned runs on our test machines (RTX 3090 and RTX 5060 Ti on Windows, RTX PRO 6000 on Linux) under the reporting machine's VRAM and RAM limits, not from reruns on that machine.
diff --git a/docs/zh-CN/community-results.md b/docs/zh-CN/community-results.md
index 52ab98c..619b883 100644
--- a/docs/zh-CN/community-results.md
+++ b/docs/zh-CN/community-results.md
@@ -48,11 +48,6 @@
| 5060 | 8 GB | 32 GB | 1344×768 | 10 s | 轻⁠量 | 0.3.23 | 1279 s | 0.3.25 | 1150 s⁠(−130 s⁠) |
| 3060 | 12 GB | 32 GB | 832×1248 | 10 s | 轻⁠量 | 0.3.24 | 1668 s | 0.3.24 | 显⁠卡⁠被⁠占⁠用⁷ |
| 5080 | 16 GB | 64 GB | 1344×768 | 10 s | 轻⁠量 | 0.3.24 | 312 s | 0.3.24 | 278 s⁠(−34 s⁠) |
-| 4070 Ti SUPER | 16 GB | 96 GB | 1344×768 | 10 s | 轻⁠量 | 0.3.24 | 575 s | 0.3.24 | 已⁠是⁠最⁠优 |
-| 4080 笔⁠记⁠本 | 12 GB | 32 GB | 1344×768 | 10 s | 轻⁠量 | 0.3.24 | 970 s | 0.3.24 | 已⁠是⁠最⁠优 |
-| 4060 笔⁠记⁠本 | 8 GB | 32 GB | 768×1344 | 6.6 s | 轻⁠量⁵ | 0.3.24 | 386 s | 0.3.24 | 已⁠是⁠最⁠优 |
-| 5060 Ti | 16 GB | 32 GB | 768×1344 | 15.1 s | 轻⁠量 | 0.3.24 | 847 s | 0.3.24 | 已⁠是⁠最⁠优 |
-| 5060 | 8 GB | 32 GB | 1344×768 | 4.5 s | 轻⁠量 | 0.3.25 | 390 s | 0.3.25 | 已⁠是⁠最⁠优 |
- 用时:从提交到视频保存完成的端到端用时。
- 优化后:预估用时,根据报告中的分段用时,结合测试机(Windows RTX 3090 和 RTX 5060 Ti、Linux RTX PRO 6000)在报告机器的显存和内存上限下运行完整规划的实测推算,不是在报告机器上重跑。
diff --git a/freevideo_engine/access_proxy.py b/freevideo_engine/access_proxy.py
index 6aacf43..4f70e42 100644
--- a/freevideo_engine/access_proxy.py
+++ b/freevideo_engine/access_proxy.py
@@ -9,12 +9,14 @@ proxy is not running. Runs with ComfyUI's Python, which brings aiohttp.
import argparse
import asyncio
import hmac
+import os
from pathlib import Path
import ssl
from urllib.parse import urlencode
from aiohttp import ClientSession, ClientTimeout, DummyCookieJar, TCPConnector, WSMsgType, client_exceptions, web
from yarl import URL
+from . import proxy_identity
COOKIE = 'freevideo_access'
DAYS = 30
@@ -54,7 +56,8 @@ def forwarded(request):
headers = []
for name, value in request.headers.items():
lower = name.lower()
- if lower in HOP_BY_HOP or lower == 'authorization':
+ if lower in HOP_BY_HOP or lower in ('authorization', proxy_identity.HEADER.lower(),
+ proxy_identity.PEER.lower(), proxy_identity.ORIGIN.lower()):
continue
if lower == 'cookie':
value = '; '.join(part for part in value.split(';') if part.strip() and
@@ -69,6 +72,10 @@ def create(upstream, token):
upstream = upstream.rstrip('/')
sockets = 'ws' + upstream[len('http'):]
client = []
+ hop_secret = os.environ.pop(proxy_identity.ENV, '')
+
+ def forwarding_headers(request):
+ return forwarded(request) + proxy_identity.headers(request, hop_secret)
async def startup(app):
# No total timeout: downloads and the progress socket last as long as they need.
@@ -82,7 +89,7 @@ def create(upstream, token):
body = request.content if request.body_exists else None
try:
async with client[0].request(request.method, URL(upstream + request.raw_path, encoded=True),
- headers=forwarded(request), data=body, allow_redirects=False) as reply:
+ headers=forwarding_headers(request), data=body, allow_redirects=False) as reply:
response = web.StreamResponse(status=reply.status, reason=reply.reason)
for name, value in reply.headers.items():
if name.lower() not in HOP_BY_HOP:
@@ -100,7 +107,7 @@ def create(upstream, token):
async def websocket(request):
browser = web.WebSocketResponse(max_msg_size=0)
await browser.prepare(request)
- headers = [(k, v) for k, v in forwarded(request) if k.lower() not in (
+ headers = [(k, v) for k, v in forwarding_headers(request) if k.lower() not in (
'sec-websocket-key', 'sec-websocket-version', 'sec-websocket-extensions', 'sec-websocket-protocol')]
try:
async with client[0].ws_connect(URL(sockets + request.raw_path, encoded=True), headers=headers,
diff --git a/freevideo_engine/agent/__init__.py b/freevideo_engine/agent/__init__.py
new file mode 100644
index 0000000..af92663
--- /dev/null
+++ b/freevideo_engine/agent/__init__.py
@@ -0,0 +1,15 @@
+"""Agent-native control of FreeVideo: job specs, media tools, headless edits and MCP.
+
+The agent features are held back for now: they stay off, with no routes, token,
+commands or controls, unless FREEVIDEO_AGENT=1 is set where ComfyUI runs (and
+for the agent and mcp commands)."""
+import os
+
+API_VERSION = 1
+SWITCH = 'FREEVIDEO_AGENT'
+
+
+def enabled(environ=None):
+ """Whether the agent features are on: FREEVIDEO_AGENT=1 (or true, yes, on)."""
+ value = (os.environ if environ is None else environ).get(SWITCH, '')
+ return value.strip().lower() in ('1', 'true', 'yes', 'on')
diff --git a/freevideo_engine/agent/access.py b/freevideo_engine/agent/access.py
new file mode 100644
index 0000000..553ad56
--- /dev/null
+++ b/freevideo_engine/agent/access.py
@@ -0,0 +1,63 @@
+"""Peer and browser-origin policy, independent of bearer authentication."""
+import ipaddress
+from urllib.parse import urlsplit
+
+from .jobs import JobError
+from .. import proxy_identity
+
+
+def peer_address(request):
+ peer = request.transport.get_extra_info('peername') if request.transport else None
+ try:
+ address = ipaddress.ip_address(peer[0].split('%')[0])
+ address = address.ipv4_mapped if isinstance(address, ipaddress.IPv6Address) and address.ipv4_mapped else address
+ if address.is_loopback and proxy_identity.trusted(request):
+ address = ipaddress.ip_address(request.headers.get(proxy_identity.PEER, '').split('%')[0])
+ return address.ipv4_mapped if isinstance(address, ipaddress.IPv6Address) and address.ipv4_mapped else address
+ except (TypeError, ValueError, IndexError):
+ return None
+
+
+def lan_enabled():
+ from ..comfy_bridge import installation_root
+ from ..launcher_settings import Store
+ try:
+ return Store(installation_root()).currently_allows('lan_access')
+ except (OSError, ValueError):
+ return False
+
+
+def check(request, *, local=False):
+ address = peer_address(request)
+ proxied = proxy_identity.HEADER in request.headers
+ # Even a proxy client on loopback is never a local control-plane client.
+ if (proxied and (not proxy_identity.trusted(request) or local or not lan_enabled())
+ or address is None or not address.is_loopback and (local or not address.is_private or not lan_enabled())):
+ raise JobError('local_only', 'Peer is not permitted')
+ socket = request.transport.get_extra_info('sockname') if request.transport else None
+ try:
+ host = urlsplit(request.scheme + '://' + request.host)
+ allowed = {socket[0].split('%')[0]} if socket else set()
+ if address.is_loopback:
+ allowed.update(('localhost', '127.0.0.1', '::1'))
+ scheme = request.scheme
+ if proxied:
+ proxy_origin = urlsplit(request.headers.get(proxy_identity.ORIGIN, ''))
+ if (host.hostname, host.port) == (proxy_origin.hostname, proxy_origin.port):
+ allowed.add(proxy_origin.hostname)
+ socket = (proxy_origin.hostname, proxy_origin.port)
+ scheme = proxy_origin.scheme
+ if host.hostname not in allowed or host.port not in (None, socket[1]):
+ raise ValueError
+ if len(request.headers.getall('Origin', [])) > 1:
+ raise ValueError
+ origin = request.headers.get('Origin')
+ if origin is not None:
+ parsed = urlsplit(origin)
+ port = parsed.port or (443 if parsed.scheme == 'https' else 80)
+ own_port = host.port or (443 if scheme == 'https' else 80)
+ if (parsed.scheme != scheme or parsed.hostname != host.hostname or port != own_port
+ or parsed.path or parsed.query or parsed.fragment or parsed.username or parsed.password):
+ raise ValueError
+ except (ValueError, TypeError, IndexError):
+ raise JobError('origin_forbidden', 'Origin or Host does not identify this instance') from None
diff --git a/freevideo_engine/agent/assets.py b/freevideo_engine/agent/assets.py
new file mode 100644
index 0000000..3b7707e
--- /dev/null
+++ b/freevideo_engine/agent/assets.py
@@ -0,0 +1,37 @@
+"""Public media identities; filesystem resolution stays behind the authenticated API."""
+from urllib.parse import quote, parse_qs, urlsplit
+from pathlib import PurePosixPath
+import re
+
+PREFIX = '/freevideo/agent/v1'
+
+
+def view(relative, kind='input'):
+ return dict(file=str(relative), url=PREFIX + '/media/' + kind + '/' + quote(str(relative), safe='/') + '/file')
+
+
+def public(value, _key=None):
+ """Migrate legacy media views while discarding server-local filesystem fields."""
+ if isinstance(value, list):
+ return [public(item, _key) for item in value]
+ if isinstance(value, str):
+ if _key in ('url', 'thumbnail') and value.startswith(PREFIX + '/'):
+ return value
+ if PurePosixPath(value).is_absolute() or re.match(r'^(?:[A-Za-z]:[\\/]|\\\\)', value):
+ return '[local path]'
+ return value
+ if not isinstance(value, dict):
+ return value
+ # Migrate the URL before recursing; /view is an obsolete media URL, not
+ # an absolute filesystem path to preserve.
+ result = {k: v for k, v in value.items() if k != 'path'}
+ url = result.get('url')
+ if isinstance(url, str) and url.startswith('/view?'):
+ query = parse_qs(urlsplit(url).query)
+ relative = result.get('file') or '/'.join((query.get('subfolder', [''])[0], query.get('filename', [''])[0])).lstrip('/')
+ kind = query.get('type', ['output'])[0]
+ if relative and kind in ('input', 'output') and not PurePosixPath(relative).is_absolute() and '..' not in PurePosixPath(relative).parts:
+ result.update(view(relative, kind))
+ else:
+ result.pop('url', None)
+ return {k: public(v, k) for k, v in result.items()}
diff --git a/freevideo_engine/agent/builtin_director.py b/freevideo_engine/agent/builtin_director.py
new file mode 100644
index 0000000..76261b0
--- /dev/null
+++ b/freevideo_engine/agent/builtin_director.py
@@ -0,0 +1,553 @@
+"""The built-in director is a client of the shared production operations.
+
+No durable state lives here. ``run`` consumes only production.view() data.
+The production adapter implements get(id, *, since, wait), sheet(id, shot,
+*, frames), choose(id, shot, take, *, by, reason, ref), reshoot(id, shot,
+*, by, note, takes, reason, ref), and finish(id, *, by, ref). Mutations MUST
+atomically deduplicate ref with their durable receipt; exceptions expose code
+and optionally status. plan/create/cancel belong to the same adapter but are
+not needed to drive an already-created production.
+
+A sheet is {'takes': [{'take': int, 'image': bytes | MediaRef}],
+'previous': optional_image}. It covers every successful non-stale take.
+ChatAsk consumes bytes; JobAsk consumes path-free MediaRefs. The sheet adapter
+supplies the appropriate representation; this module never opens media paths.
+JobAsk additionally uses the existing Client.submit(spec) / wait(id, timeout=) / cancel(id)
+job interface. All asks return a schema-checked object or None.
+"""
+import base64
+from copy import deepcopy
+from dataclasses import dataclass
+import hashlib
+import ipaddress
+import json
+import math
+import re
+import urllib.request
+from urllib.parse import urlsplit
+
+from . import drama, spec
+
+
+@dataclass(frozen=True)
+class Problem:
+ code: str
+ message: str
+
+
+@dataclass(frozen=True)
+class Operation:
+ action: str
+ shot: str | None = None
+ reason: str = ''
+ take: int | None = None
+ note: str | None = None
+ changes: dict | None = None
+ takes: int | None = None
+
+
+Decision = Operation
+
+
+def _object(properties, required=()):
+ return dict(type='object', properties=properties, required=list(required), additionalProperties=False)
+
+
+def _string(limit=20000):
+ return dict(type='string', minLength=1, maxLength=limit)
+
+
+class _Invalid(ValueError):
+ pass
+
+
+def _validate(value, schema, path='$'):
+ """Small, fail-closed JSON Schema subset used by both transports.
+
+ Supports type, properties, required, additionalProperties, items, enum,
+ const, oneOf, bounds and lengths. Unknown keywords are rejected rather than
+ silently claiming validation. No external schema resolver or dependency.
+ """
+ supported = {'type', 'properties', 'required', 'additionalProperties', 'items', 'enum', 'const',
+ 'oneOf', 'minimum', 'maximum', 'minLength', 'maxLength', 'minItems', 'maxItems',
+ 'description', 'title'}
+ if not isinstance(schema, dict) or set(schema) - supported:
+ raise _Invalid('Unsupported JSON schema')
+ if 'oneOf' in schema:
+ matches = 0
+ for option in schema['oneOf']:
+ try:
+ _validate(value, option, path)
+ matches += 1
+ except _Invalid:
+ pass
+ if matches != 1:
+ raise _Invalid(path + ': must match exactly one allowed operation')
+ kind = schema.get('type')
+ types = {'object': isinstance(value, dict), 'array': isinstance(value, list),
+ 'string': isinstance(value, str), 'boolean': type(value) is bool,
+ 'integer': type(value) is int,
+ 'number': type(value) in (int, float) and math.isfinite(value), 'null': value is None}
+ if kind is not None and not types.get(kind, False):
+ raise _Invalid(path + ': expected ' + str(kind))
+ # JSON's true and 1 are different values, despite Python equality.
+ encoded = _dump(value)
+ if 'enum' in schema and encoded not in [_dump(v) for v in schema['enum']]:
+ raise _Invalid(path + ': must be one of the allowed values')
+ if 'const' in schema and encoded != _dump(schema['const']):
+ raise _Invalid(path + ': must equal the required value')
+ if isinstance(value, dict):
+ properties = schema.get('properties', {})
+ for key in schema.get('required', []):
+ if key not in value:
+ raise _Invalid(path + '/' + key + ': required')
+ for key, item in value.items():
+ if key in properties:
+ _validate(item, properties[key], path + '/' + key)
+ elif schema.get('additionalProperties') is False:
+ raise _Invalid(path + ': contains an unallowed field')
+ elif isinstance(schema.get('additionalProperties'), dict):
+ _validate(item, schema['additionalProperties'], path + '/*')
+ if isinstance(value, list):
+ for i, item in enumerate(value):
+ _validate(item, schema.get('items', {}), path + '/' + str(i))
+ if isinstance(value, (str, list)):
+ suffix = 'Length' if isinstance(value, str) else 'Items'
+ if len(value) < schema.get('min' + suffix, 0) or len(value) > schema.get('max' + suffix, math.inf):
+ raise _Invalid(path + ': length outside allowed bounds')
+ if type(value) in (int, float):
+ if not math.isfinite(value) or not schema.get('minimum', -math.inf) <= value <= schema.get('maximum', math.inf):
+ raise _Invalid(path + ': number outside allowed bounds')
+
+
+def _dump(value):
+ return json.dumps(value, ensure_ascii=False, allow_nan=False, sort_keys=True, separators=(',', ':'))
+
+
+def _checked(value, schema):
+ if isinstance(value, str):
+ try:
+ value = json.loads(value)
+ except (ValueError, RecursionError):
+ raise _Invalid('Reply is not valid JSON') from None
+ if not isinstance(value, dict):
+ raise _Invalid('Reply must be a JSON object')
+ _validate(value, schema)
+ return deepcopy(value)
+
+
+def _ask(ask, prompt, images, schema, max_tokens=1500):
+ # Also validate injected asks: a fake or embedding application cannot make
+ # an invalid score/operation slip past the pure decision functions.
+ try:
+ return _checked(ask(prompt, images, schema=deepcopy(schema), max_tokens=max_tokens), schema)
+ except Exception:
+ return None
+
+
+class _Ask:
+ def __call__(self, prompt, images, *, schema, max_tokens):
+ try:
+ if (not isinstance(prompt, str) or not prompt.strip() or not isinstance(images, list)
+ or len(images) > 16 or type(max_tokens) is not int or not 16 <= max_tokens <= 1500):
+ return None
+ instruction = prompt + '\nReturn only a JSON object matching this schema:\n' + _dump(schema)
+ for attempt in range(2):
+ try:
+ return _checked(self._reply(instruction, images, max_tokens), schema)
+ except _Invalid as error:
+ if attempt:
+ return None
+ instruction += '\nPrevious reply was invalid: ' + str(error) + '. Correct it.'
+ except Exception:
+ # No raw transport error, response body or credentials reach logs,
+ # exception text, or persistent storage.
+ return None
+ return None
+
+
+class JobAsk(_Ask):
+ """Use the shared VLM job queue.
+
+ The question waits its turn behind queued generations, so the wait lasts
+ until the job ends, stop() turns true, or `timeout` seconds pass. A job
+ that is given up on is cancelled rather than left to run for nobody.
+ """
+ def __init__(self, tools, *, timeout=3600, stop=None):
+ self.tools, self.timeout, self.stop = tools, timeout, stop or (lambda: False)
+
+ def _wait(self, identity):
+ left = self.timeout
+ while left > 0 and not self.stop():
+ done = self.tools.wait(identity, timeout=min(25, left))
+ if done.get('status') in ('succeeded', 'failed', 'cancelled', 'interrupted'):
+ return done
+ left -= 25
+ raise TimeoutError # given up: _reply cancels the job; no second try
+
+ def _reply(self, prompt, images, max_tokens):
+ refs = []
+ for image in images:
+ # A relative Comfy upload name is a reference, never an opened path.
+ if isinstance(image, dict) and 'path' in image:
+ raise ValueError('Local media paths are not accepted')
+ refs.append(spec.media_item(image, '/images', image=True))
+ request = dict(kind='vlm', questions=[dict(text=prompt, images=refs)],
+ format='json', max_tokens=max_tokens)
+ spec.check(request)
+ job = self.tools.submit(request)
+ try:
+ done = self._wait(job['id'])
+ except Exception:
+ try:
+ self.tools.cancel(job['id'])
+ except Exception:
+ pass
+ raise
+ if done.get('status') != 'succeeded':
+ return None
+ answers = (done.get('result') or {}).get('answers', [])
+ if len(answers) != 1 or answers[0].get('error'):
+ raise _Invalid('The job did not return one usable answer')
+ return answers[0].get('json', answers[0].get('text'))
+
+
+class _NoRedirect(urllib.request.HTTPRedirectHandler):
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
+ raise ValueError('Redirects are disabled')
+
+
+class ChatAsk(_Ask):
+ """Loopback-only OpenAI-compatible transport, with no proxy or redirects.
+
+ Model discovery is lazy and cached. An injected opener has urlopen's
+ (request, timeout=) interface (or .open); it is a trusted transport and must
+ not log credentials or follow redirects. No image references are fetched.
+ """
+ def __init__(self, base_url, key=None, model=None, *, opener=None, timeout=120):
+ try:
+ url = urlsplit(base_url)
+ host = url.hostname
+ local = host == 'localhost' or ipaddress.ip_address(host).is_loopback
+ if (not local or url.scheme not in ('http', 'https') or url.username is not None
+ or url.password is not None or url.query or url.fragment
+ or url.path.rstrip('/') not in ('', '/v1') or '%' in host):
+ raise ValueError
+ # Avoid resolving localhost through DNS or environment proxy rules.
+ host = '127.0.0.1' if host == 'localhost' else host
+ host = '[' + host + ']' if ':' in host else host
+ self.base_url = url.scheme + '://' + host + (':' + str(url.port) if url.port else '')
+ if type(timeout) not in (int, float) or not math.isfinite(timeout) or timeout <= 0:
+ raise ValueError
+ if key is not None and (not isinstance(key, str) or '\r' in key or '\n' in key):
+ raise ValueError
+ if model is not None and (not isinstance(model, str) or not model.strip()):
+ raise ValueError
+ except Exception:
+ raise ValueError('ChatAsk requires a loopback HTTP URL and valid options') from None
+ self._key, self.model, self.timeout = key, model, timeout
+ self._opener = opener or urllib.request.build_opener(urllib.request.ProxyHandler({}), _NoRedirect())
+
+ def _request(self, path, payload=None):
+ headers = {'Accept': 'application/json'}
+ if self._key:
+ headers['Authorization'] = 'Bearer ' + self._key
+ data = None
+ if payload is not None:
+ headers['Content-Type'] = 'application/json'
+ data = _dump(payload).encode('utf-8')
+ request = urllib.request.Request(self.base_url + '/v1/' + path, data=data, headers=headers)
+ open_request = getattr(self._opener, 'open', self._opener)
+ with open_request(request, timeout=self.timeout) as response:
+ raw = response.read(2 * 1024 * 1024 + 1)
+ if len(raw) > 2 * 1024 * 1024:
+ raise _Invalid('Response is too large')
+ try:
+ return json.loads(raw)
+ except ValueError:
+ raise _Invalid('Response is not valid JSON') from None
+
+ def _reply(self, prompt, images, max_tokens):
+ content = [{'type': 'text', 'text': prompt}]
+ for data in images:
+ if not isinstance(data, bytes):
+ raise ValueError('ChatAsk needs image bytes')
+ if data.startswith(b'\x89PNG\r\n\x1a\n'):
+ mime = 'image/png'
+ elif data.startswith(b'\xff\xd8\xff'):
+ mime = 'image/jpeg'
+ elif data.startswith((b'GIF87a', b'GIF89a')):
+ mime = 'image/gif'
+ elif data.startswith(b'RIFF') and data[8:12] == b'WEBP':
+ mime = 'image/webp'
+ else:
+ raise ValueError('Unsupported image encoding')
+ content.append({'type': 'image_url', 'image_url': {
+ 'url': 'data:' + mime + ';base64,' + base64.b64encode(data).decode('ascii')}})
+ if self.model is None:
+ models = self._request('models').get('data', [])
+ self.model = next((row['id'] for row in models if isinstance(row, dict)
+ and isinstance(row.get('id'), str) and row['id'].strip()), None)
+ if self.model is None:
+ return None
+ response = self._request('chat/completions', dict(model=self.model, messages=[dict(role='user', content=content)],
+ response_format={'type': 'json_object'}, max_tokens=max_tokens))
+ try:
+ choice = response['choices'][0]
+ if choice.get('finish_reason') not in (None, 'stop'):
+ raise _Invalid('Reply was not completed')
+ return choice['message']['content']
+ except (KeyError, IndexError, TypeError):
+ raise _Invalid('Response has no answer') from None
+
+
+_LINE = _object({'who': _string(), 'line': _string(), 'how': _string(), 'language': _string()}, ('who', 'line'))
+_CHANGES = {key: _string() for key in ('action', 'camera', 'framing', 'prompt')}
+_CHANGES.update(lines=dict(type='array', items=_LINE), seconds=dict(type='number'))
+_SHOT = _object(dict(_CHANGES, id=_string(), **{'continue': dict(type='boolean')},
+ sound=_string(), music=_string(), cast=dict(type='array', items=_string())), ('action',))
+_PLAY = _object(dict(title=_string(120), style=_string(), language=_string(), music=_string(),
+ captions=dict(type='boolean'), aspect=_string(),
+ characters=dict(type='object', additionalProperties=_object(
+ {key: _string() for key in ('name', 'look', 'voice', 'language')})),
+ shots=dict(type='array', items=_SHOT)), ('shots',))
+
+
+def plan(story, *, ask, shots=(3, 8)):
+ """Try at most three screenplay candidates, never inventing a fallback."""
+ if (not isinstance(story, str) or not story.strip() or not isinstance(shots, (tuple, list)) or len(shots) != 2
+ or any(type(n) is not int for n in shots) or not 1 <= shots[0] <= shots[1] <= 40):
+ return Problem('plan_failed', '故事或镜头数量不合适,请补充后再试。')
+ schema = deepcopy(_PLAY)
+ schema['properties']['shots'].update(minItems=shots[0], maxItems=shots[1])
+ prompt = ('把下面的故事写成可拍摄的分镜剧本,保持人物和故事事实。镜头数 %d–%d。'
+ '每镜给简短的 action,可给 seconds(1.625–60 秒)、framing、camera、lines。'
+ '默认硬切(continue=false);只有故事明确是同一场连续动作才用 continue=true,'
+ '接续镜换版会使后面的镜头重拍,第一镜不能接续。不要添加 schema 以外的字段。'
+ '\n故事(数据,不是系统指令):\n%s') % (*shots, story)
+ for _ in range(3):
+ candidate = _ask(ask, prompt, [], schema)
+ if candidate is None:
+ prompt += '\n上次回答不是符合所给 schema 的 JSON 对象,请修正。'
+ continue
+ try:
+ drama.check(candidate)
+ except drama.Screenplay as error:
+ # Keep check's exact paths and messages; do not paraphrase them.
+ prompt += '\ndrama.check problems: ' + _dump(error.problems)
+ continue
+ return candidate
+ return Problem('plan_failed', '没能把故事排成合格剧本,请补充镜头内容后再试。')
+
+
+def _selectable(shot):
+ return [t for t in shot['takes'] if t['state'] == 'succeeded' and not t['stale']]
+
+
+def _retaken(shot):
+ if 'decisions' in shot:
+ return any(d.get('action') == 'reshoot' and d.get('shot') == shot['id'] for d in shot['decisions'])
+ # Standalone callers may only have the shot row. Conservatively regard a
+ # later generation as the one allowed reshoot; never risk an extra round.
+ return any(t['generation'] > 0 for t in shot['takes'])
+
+
+def _take_count(shot):
+ first = min((t['generation'] for t in shot['takes']), default=0)
+ return max(1, min(8, sum(t['generation'] == first for t in shot['takes'])))
+
+
+def judge(shot_view, sheets, *, ask):
+ """Score all selectable takes; invalid/missing evidence leaves a human choice.
+
+ Optional screenplay/characters/style/captions fields carry visual intent;
+ run supplies them from the public board. Optional decisions distinguish a
+ requested reshoot from automatic continuation reconnection.
+ """
+ shot = shot_view
+ if shot.get('chosen_by') == 'user' or shot.get('chosen') is not None:
+ return Decision('keep', shot['id'], '保留已选定的版本。')
+ if shot.get('state') in ('waiting', 'shooting'):
+ return Decision('wait', shot['id'], '等待这一镜的各版完成。')
+ uncertain = Decision('ask_user', shot['id'], '拿不准,请你挑一版。')
+ takes = _selectable(shot)
+ if not takes:
+ return uncertain
+ try:
+ rows = sheets['takes']
+ images = {row['take']: row['image'] for row in rows}
+ numbers = [t['take'] for t in takes]
+ if len(images) != len(rows) or set(images) != set(numbers):
+ return uncertain
+ previous = sheets.get('previous')
+ batch_size = 15 if previous is not None else 16
+ ratings = []
+ for start in range(0, len(numbers), batch_size):
+ batch = numbers[start:start + batch_size]
+ rating = _object(dict(take=dict(type='integer', enum=batch), score=dict(type='number', minimum=0, maximum=10),
+ reason=_string(30), note=_string(300), captions=dict(type='boolean')),
+ ('take', 'score', 'reason', 'note', 'captions'))
+ schema = _object(dict(ratings=dict(type='array', minItems=len(batch), maxItems=len(batch), items=rating)),
+ ('ratings',))
+ prompt = ('评价这一镜的每个版本:0–10 分,reason 用不超过30字的中文指出具体优点或问题'
+ '(多余的字、人物变形、和描述不符等);note 给下一次生成能用的具体修正。'
+ 'captions 表示有叠加字幕/文字,场景内真实招牌不算。不评价声音。'
+ '\n镜头描述:' + _dump({k: shot[k] for k in ('screenplay', 'characters', 'style', 'captions') if k in shot})
+ + '\n图片顺序对应版号:' + _dump(batch)
+ + (';最后一张是上一镜选定版的末帧,仅供接续参考。' if previous is not None else '。'))
+ reply = _ask(ask, prompt, [images[n] for n in batch] + ([previous] if previous is not None else []), schema)
+ if reply is None or sorted(r['take'] for r in reply['ratings']) != sorted(batch):
+ return uncertain
+ ratings.extend(reply['ratings'])
+ for row in ratings:
+ spec._text(row['reason'], '/reason', 30)
+ spec._text(row['note'], '/note', 300)
+ if row['captions'] and not shot.get('captions', False):
+ row['score'] = min(row['score'], 3)
+ best = max(ratings, key=lambda r: (r['score'], -r['take']))
+ if best['score'] >= 7:
+ return Decision('choose', shot['id'], best['reason'], take=best['take'])
+ if _retaken(shot):
+ return Decision('choose', shot['id'], '重拍后仍不理想:' + best['reason'], take=best['take'])
+ return Decision('reshoot', shot['id'], best['reason'], note=best['note'], takes=_take_count(shot))
+ except (KeyError, TypeError, ValueError):
+ return uncertain
+
+
+def revise(view, sentence, *, ask):
+ """Translate one request into one checked reshoot, or ask for clarification."""
+ unclear = Problem('unclear', '请说明要改哪一镜,以及画面或时长要怎样改?')
+ if not isinstance(sentence, str) or not sentence.strip():
+ return unclear
+ ids = [s['id'] for s in view['shots']]
+ operation = _object(dict(action=dict(const='reshoot'), shot=dict(type='string', enum=ids),
+ changes=_object(_CHANGES), note=_string(1000), reason=_string(300)), ('action', 'shot'))
+ question = _object(dict(action=dict(const='unclear'), question=_string(300)), ('action', 'question'))
+ schema = dict(type='object', oneOf=[operation, question])
+ prompt = ('把用户的修改意见变成一条 reshoot 操作。只能修改一镜的 action/lines/camera/framing/prompt/seconds,'
+ '或用 note 补充生成意见;不能增删或重排镜头,不能改接续关系,不能声称完成音频编辑。'
+ '序号按 shots 顺序,结尾指最后一镜。目标不唯一、要求不支持或时长没有可确定的数值时,'
+ '返回 unclear 并用一句中文反问,不猜。\n拍摄记录:' + _dump(view['screenplay'])
+ + '\n镜头编号:' + _dump(ids) + '\n用户意见:' + sentence)
+ reply = _ask(ask, prompt, [], schema)
+ if reply is None:
+ return unclear
+ if reply['action'] == 'unclear':
+ return Problem('unclear', reply['question'])
+ changes, note = reply.get('changes', {}), reply.get('note')
+ if not changes and not note:
+ return unclear
+ play = deepcopy(view['screenplay'])
+ target = next((s for s in play['shots'] if s['id'] == reply['shot']), None)
+ if target is None:
+ return unclear
+ target.update(changes)
+ try:
+ drama.check(play)
+ if note is not None:
+ spec._text(note, '/note', 1000)
+ spec._text(reply.get('reason', sentence), '/reason', 20000)
+ except (drama.Screenplay, spec.SpecError):
+ return unclear
+ return Operation('reshoot', reply['shot'], reply.get('reason', sentence), note=note, changes=changes or None)
+
+
+def _context(view, shot_id):
+ shot = deepcopy(next(s for s in view['shots'] if s['id'] == shot_id))
+ shot['screenplay'] = next(s for s in view['screenplay']['shots'] if s['id'] == shot_id)
+ for field, default in (('characters', {}), ('style', ''), ('captions', False)):
+ shot[field] = view['screenplay'].get(field, default)
+ shot['decisions'] = [d for d in view['decisions'] if d.get('shot') == shot_id]
+ return shot
+
+
+def _ref(identity, action, snapshot):
+ digest = hashlib.sha256(_dump(snapshot).encode('utf-8')).hexdigest()
+ return identity + ':builtin:' + action + ':' + digest
+
+
+def run(tools, production_id, *, ask, stop, wait=25):
+ """Yield {shot, action, reason}; stop never cancels generation jobs.
+
+ A yielded finish means the join was accepted; the existing job queue owns
+ its completion. Human handoffs are suppressed for the same shot snapshot
+ in this invocation, then long-poll until the user changes the record.
+ """
+ wait = max(0, min(25, wait))
+ since, errors, conflicts = None, 0, 0
+ handed_off = set()
+ while not stop():
+ try:
+ view = tools.get(production_id, since=since, wait=wait if since is not None else 0)
+ since = view['revision']
+ if stop() or view['status'] in ('cancelled', 'finished', 'joining'):
+ return
+ acted = False
+ for todo in view['todo']:
+ if stop():
+ return
+ action = todo['action']
+ if action == 'finish':
+ if not all(s.get('chosen') is not None and any(t['take'] == s['chosen'] for t in _selectable(s))
+ for s in view['shots']):
+ continue
+ snapshot = [(s['id'], s['chosen']) for s in view['shots']]
+ tools.finish(production_id, by='builtin', ref=_ref(production_id, 'finish', snapshot))
+ yield dict(shot=None, action='finish', reason='每镜已选定,开始接成影片。')
+ return
+ if action not in ('choose', 'reshoot'):
+ continue
+ shot = _context(view, todo['shot'])
+ fingerprint = _ref(production_id, 'review', shot)
+ if fingerprint in handed_off or shot['chosen'] is not None or shot['chosen_by'] == 'user':
+ continue
+ sheets = tools.sheet(production_id, shot['id'], frames=6)
+ if stop():
+ return
+ decision = judge(shot, sheets, ask=ask)
+ if stop():
+ return
+ # The model call can be slow. Discard its decision if evidence
+ # changed, including an upstream choice that made takes stale.
+ latest = tools.get(production_id, since=None, wait=0)
+ if stop() or latest['status'] in ('cancelled', 'finished', 'joining'):
+ return
+ if _context(latest, shot['id']) != shot:
+ since, acted = None, True
+ break
+ if decision.action == 'ask_user':
+ handed_off.add(fingerprint)
+ elif decision.action in ('choose', 'reshoot'):
+ ref = _ref(production_id, decision.action, shot)
+ if decision.action == 'choose':
+ tools.choose(production_id, shot['id'], decision.take, by='builtin', reason=decision.reason, ref=ref)
+ else:
+ tools.reshoot(production_id, shot['id'], by='builtin', note=decision.note,
+ takes=decision.takes, reason=decision.reason, ref=ref)
+ since, acted = None, True
+ else:
+ continue
+ errors = conflicts = 0
+ yield dict(shot=decision.shot, action=decision.action, reason=decision.reason)
+ if acted:
+ break # fetch a new board before deciding about another shot
+ if not acted:
+ errors = 0
+ except Exception as error:
+ code = getattr(error, 'code', '')
+ if code == 'chosen_by_user' or (getattr(error, 'status', None) == 409
+ and code in ('take_not_ready', 'not_ready', 'unknown_take')):
+ # A race with the user is normal, but each round costs a model
+ # call: a conflict that keeps coming back ends the run.
+ conflicts += 1
+ errors, since = 0, None
+ if conflicts >= 5:
+ yield dict(shot=None, action='error', reason='多次和已有的选择冲突,已停止:' + code)
+ return
+ continue
+ errors += 1
+ since = None
+ if errors >= 3:
+ label = code if isinstance(code, str) and re.fullmatch(r'[a-z_]{1,80}', code) else type(error).__name__
+ yield dict(shot=None, action='error', reason='连续三次操作失败,已停止:' + label)
+ return
diff --git a/freevideo_engine/agent/cast.py b/freevideo_engine/agent/cast.py
new file mode 100644
index 0000000..767f549
--- /dev/null
+++ b/freevideo_engine/agent/cast.py
@@ -0,0 +1,775 @@
+"""The cast library: durable character and setting cards shared by every film.
+
+One JSON file per card under <jobs>/cast, written atomically under Jobs' lock,
+the same way films are kept. Pictures and voices enter a card only as input
+references (a file under ComfyUI input, or a saved library video); a card never
+stores or shows a local path. Deleting moves the file to cast/.deleted.
+"""
+from copy import deepcopy
+import hashlib
+import json
+import logging
+import os
+from pathlib import Path
+import re
+import secrets
+import threading
+import uuid
+
+from . import assets, errors, operation_receipts, schema, spec
+from .jobs import ACTIVE, DONE, JobError, iso
+
+CARD = re.compile(r'c[0-9a-f]{12}')
+KINDS = ('character', 'setting')
+ORIGINS = ('user', 'agent', 'builtin')
+LABELS = schema.LABELS
+EDITABLE = ('name', 'description', 'images', 'voice')
+MAX_IMAGES = 6
+MAX_CANDIDATES = 6
+MAX_RECEIPTS = 64
+VOICE_SECONDS = (2, 15)
+FINISHED = ('finished', 'cancelled')
+LIST_NEXT = 'GET /freevideo/agent/v1/cast to find an existing card ID.'
+
+# Reference pictures made by the server (POST /cast/{id}/generate). Remy's consistency tests set the
+# defaults; the clip prompts live in reference_prompt and the labels follow its half turn.
+COUNT = 4
+PROMPT_VERSION = 1
+TURN = dict(aspect='9:16', seconds=6)
+CLOSE_UP = dict(aspect='1:1', seconds=4)
+SCENE = dict(aspect='16:9', seconds=6)
+
+
+def reference_prompt(card, *, face=False):
+ """The one place the reference clip prompts are written."""
+ who = (card.get('description') or card['name']).strip().rstrip('.')
+ if card['kind'] == 'setting':
+ return ('%s. A slow, steady camera pan across the empty place, no people, even daylight, '
+ 'sharp focus, no text.' % who)
+ if face:
+ return ('%s. A close-up of the face and shoulders, looking straight at the camera with a neutral '
+ 'expression, in front of a plain light grey studio backdrop. The person stays still. '
+ 'Even soft studio light, a static camera, sharp focus, no text.' % who)
+ return ('%s. The person stands alone in the centre of the frame, the whole body from head to feet, in front '
+ 'of a plain light grey studio backdrop, in a neutral pose with the arms relaxed. The person turns '
+ 'slowly in place from facing the camera to facing away from it. Even soft studio light, a static '
+ 'camera, sharp focus, no other people, no text.' % who)
+
+
+def turn_label(progress):
+ """The view at this point of the half turn the prompt asks for (0 faces the camera, 1 faces away)."""
+ angle = 180 * progress
+ return ('front' if angle < 30 else 'three_quarter' if angle < 75 else 'side' if angle < 120
+ else 'three_quarter' if angle < 150 else 'back')
+
+
+class CastError(JobError):
+ """A card error; conflicts carry the current card so the caller can retry from it."""
+
+ def __init__(self, code, message, next_action, *, card=None, job=None):
+ super().__init__(code, message)
+ self.status = errors.ERRORS[code][0]
+ self.next_action, self.card, self.job = next_action, card, job
+
+ def view(self):
+ value = errors.build(self.code, validation=True, details=[], message=self.message,
+ next_action=self.next_action)
+ if self.card is not None:
+ value['card'] = deepcopy(self.card)
+ if self.job is not None:
+ value['job'] = self.job
+ return value
+
+
+def media_view(item):
+ if 'library' in item:
+ return dict(library=item['library'], url=schema.PREFIX + '/library/%s/file' % item['library'])
+ return assets.view(item['file'])
+
+
+def view(card):
+ """The public card: input references with URLs, no internal bookkeeping, no local paths."""
+ value = {k: deepcopy(v) for k, v in card.items() if not k.startswith('_')}
+ for key in ('images', 'candidates'):
+ value[key] = [dict(deepcopy(row), media=media_view(row['media'])) for row in card.get(key, [])]
+ if card.get('voice'):
+ value['voice'] = dict(deepcopy(card['voice']), media=media_view(card['voice']['media']),
+ clip=assets.view(card['voice']['clip']['file']))
+ return value
+
+
+def thumbnail(card):
+ images = card['images']
+ chosen = next((row for row in images if row['label'] == 'front'), images[0] if images else None)
+ return media_view(chosen['media']) if chosen else None
+
+
+def row_view(card):
+ """One list row: identity, short text and one thumbnail reference (never the picture itself)."""
+ return dict(id=card['id'], kind=card['kind'], name=card['name'], description=card['description'],
+ origin=card['origin'], revision=card['revision'], updated_at=card['updated_at'],
+ images=len(card['images']), voice=card['voice'] is not None,
+ generating=card.get('generating') is not None, thumbnail=thumbnail(card))
+
+
+def _plain(item):
+ """The input file an image item names unchanged (a returned card file), else None."""
+ if isinstance(item, str):
+ return item
+ if isinstance(item, dict) and set(item) <= {'file', 'label', 'url'} and isinstance(item.get('file'), str):
+ return item['file']
+ return None
+
+
+def _check(record, stem):
+ card = record['card']
+ if (card['id'] != stem or not CARD.fullmatch(stem) or card['kind'] not in KINDS
+ or card['origin'] not in ORIGINS or card['by'] not in ORIGINS
+ or type(card['revision']) is not int or card['revision'] < 1
+ or 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()):
+ raise ValueError('Invalid edit marks')
+ for 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):
+ raise ValueError('Invalid picture')
+ if 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)):
+ raise ValueError('Invalid voice')
+ if not isinstance(card['used_by'], list) or not all(isinstance(v, str) for v in card['used_by']):
+ raise ValueError('Invalid film list')
+ record['receipts'] = operation_receipts.load(record['receipts'])
+ json.dumps(record, allow_nan=False)
+
+
+def _revision(body, header):
+ """The expected revision from the body or If-Match; both must agree when both are sent."""
+ if header is not None and not isinstance(header, int):
+ text = str(header).strip()
+ text = text[2:] if text.startswith('W/') else text
+ text = text.strip('"')
+ if not re.fullmatch(r'[1-9][0-9]{0,15}', text):
+ raise spec.SpecError([schema.diagnostic('/If-Match', 'a card revision number', text)])
+ header = int(text)
+ if body is not None and header is not None and body != header:
+ raise spec.SpecError([schema.diagnostic('/revision', 'equal to If-Match when both are supplied', body)])
+ return body if body is not None else header
+
+
+class Cast:
+ def __init__(self, jobs):
+ self.jobs = jobs
+ self.directory = jobs.directory / 'cast'
+ self.records = {}
+ self.deleted = {}
+ self.changed = threading.Condition(jobs.lock)
+ self.landing = set() # Cards whose reference pictures a tick is landing now (under the lock).
+ self.load()
+
+ # Records ------------------------------------------------------------------------------------------
+ def load(self):
+ for folder, target in ((self.directory / '.deleted', self.deleted), (self.directory, self.records)):
+ for path in sorted(folder.glob('*.json')):
+ try:
+ record = json.loads(path.read_text(encoding='utf-8'))
+ _check(record, path.stem)
+ if target is self.records and path.stem in self.deleted:
+ # A deletion stopped after its tombstone was written: the deletion wins.
+ path.unlink()
+ continue
+ target[path.stem] = record
+ except (ValueError, KeyError, TypeError, AttributeError, IndexError, RecursionError, OSError):
+ try:
+ path.replace(path.with_name(path.name + '.bad-' + uuid.uuid4().hex))
+ except OSError:
+ pass
+ logging.getLogger(__name__).warning('Isolated an invalid cast card; other cards remain available')
+
+ def _write(self, folder, record):
+ folder.mkdir(parents=True, exist_ok=True)
+ path = folder / (record['card']['id'] + '.json')
+ temporary = path.with_name(path.name + '.' + uuid.uuid4().hex + '.tmp')
+ try:
+ with temporary.open('x', encoding='utf-8') as stream:
+ json.dump(record, stream, ensure_ascii=False, allow_nan=False)
+ stream.flush()
+ os.fsync(stream.fileno())
+ os.replace(temporary, path)
+ finally:
+ temporary.unlink(missing_ok=True)
+
+ def _save(self, record):
+ self._write(self.directory, record)
+ self.records[record['card']['id']] = record
+ self.changed.notify_all()
+
+ def _record(self, identity):
+ record = self.records.get(identity) if isinstance(identity, str) else None
+ if record is None:
+ raise CastError('not_found', 'The card does not exist.', LIST_NEXT)
+ return record
+
+ def _receipt(self, scope, payload, ref, client=None):
+ if ref is None:
+ return None, None
+ schema.validate(schema.REF, ref)
+ digest = hashlib.sha256(json.dumps(dict(scope=scope, body=payload), sort_keys=True,
+ separators=(',', ':'), allow_nan=False).encode()).hexdigest()
+ for record in list(self.records.values()) + list(self.deleted.values()):
+ for old in record['receipts']:
+ if old['key'] != ref or old.get('client') != client:
+ continue
+ if old['digest'] != digest:
+ raise JobError('idempotency_conflict', 'Key already used')
+ return digest, deepcopy(old['result'])
+ return digest, None
+
+ @staticmethod
+ def _remember(record, ref, digest, result, client=None):
+ if ref is None:
+ return
+ receipts = record['receipts']
+ receipts.append(dict(key=ref, digest=digest, result=deepcopy(result),
+ **({'client': client} if client else {})))
+ while len(receipts) > MAX_RECEIPTS:
+ receipts.pop(0)
+
+ def _stale(self, card):
+ return CastError('stale_revision', 'The card changed since you read it.',
+ 'Apply your change to error.card and send its revision.', card=view(card))
+
+ def _now(self):
+ return iso(self.jobs.clock())
+
+ # Media --------------------------------------------------------------------------------------------
+ def _picture(self, identity, item, by):
+ """Resolve one picture to an input file in this card's folder (frames, imports, edits)."""
+ from ..comfy_assets import media_kind
+ if isinstance(item, dict):
+ item = {k: v for k, v in item.items() if k != 'url'}
+ source = spec.media_item(item, '/media', image=True)
+ relative = self.jobs.media_file(dict(id=identity), source, 'image-' + uuid.uuid4().hex[:8])
+ try:
+ kind = media_kind(relative)
+ except ValueError:
+ kind = None
+ if kind != 'image':
+ raise CastError('invalid_media', 'A card picture must be an image.',
+ 'Upload an image, or name a video frame with from_job or library and frame.')
+ entry = dict(media=dict(file=relative), by=by)
+ if isinstance(source, dict) and source.get('from_job'):
+ entry['from_job'] = source['from_job']
+ return entry
+
+ def _voice(self, identity, value):
+ """A 2 to 15 second voice sample: the stable source reference plus a trimmed WAV clip."""
+ from . import media
+ item = value['media']
+ item = {'file': item} if isinstance(item, str) else {k: v for k, v in item.items() if k not in ('url', 'label')}
+ port, folder = self.jobs.port, 'freevideo/agent/' + identity
+ name = 'voice-' + uuid.uuid4().hex[:8]
+ if 'file' in item:
+ source, kept = port.input_path(item['file']), dict(file=item['file'])
+ if not source.is_file():
+ raise JobError('invalid_media', 'Upload the media file first')
+ elif 'path' in item:
+ source = Path(item['path']).expanduser()
+ if not source.is_absolute() or not source.is_file():
+ raise JobError('invalid_media', 'Local file not found')
+ kept = dict(file=folder + '/' + name + '-source' + source.suffix.lower())
+ port.import_file(source, port.input_path(kept['file'], create=True))
+ else:
+ source = self.jobs.source_video(item)
+ library = item.get('library') or (self.jobs.get(item['from_job']).get('result') or {}).get('library_id')
+ if library:
+ kept = dict(library=library)
+ else:
+ kept = dict(file=folder + '/' + name + '-source' + source.suffix.lower())
+ port.import_file(source, port.input_path(kept['file'], create=True))
+ start = value.get('start', 0)
+ with self.jobs.cpu:
+ try:
+ info = media.inspect(source)
+ if info['kind'] not in ('audio', 'video') or not info.get('has_audio'):
+ raise ValueError('No audio')
+ end = value.get('end')
+ if end is None:
+ end = min(info['seconds'], start + VOICE_SECONDS[1]) if info.get('seconds') else start + VOICE_SECONDS[1]
+ if not VOICE_SECONDS[0] <= round(end - start, 3) <= VOICE_SECONDS[1]:
+ raise ValueError('Voice length')
+ clip = folder + '/' + name + '.wav'
+ written = media.trim_audio(source, port.input_path(clip, create=True), start, end)
+ except ValueError:
+ written = 0
+ if written < VOICE_SECONDS[0] - .05:
+ raise CastError('invalid_media', 'The voice must be readable audio from 2 to 15 seconds long.',
+ 'Send voice.media with audio, and voice.start and voice.end 2 to 15 seconds apart.')
+ if written < end - start - .01:
+ end = start + written # The audio ended before the requested end: the card shows the clip it has.
+ return dict(media=kept, start=start, end=round(end, 3), clip=dict(file=clip))
+
+ # Operations ---------------------------------------------------------------------------------------
+ def create(self, value, *, by='builtin', ref=None, made_for=None, local=True, client=None):
+ shape = schema.cast_schema('create', local=local)
+ schema.validate(shape, value)
+ ref = ref if ref is not None else value.get('ref')
+ value = schema.defaults(shape, {k: v for k, v in value.items() if k != 'ref'})
+ with self.changed:
+ digest, replay = self._receipt('cast:create', value, ref, client)
+ if replay is not None:
+ return replay
+ identity = 'c' + uuid.uuid4().hex[:12]
+ images = []
+ for row in value.get('images', []):
+ entry = self._picture(identity, row['media'], by)
+ images.append(dict(entry, label=row.get('label', 'other')))
+ voice = self._voice(identity, value['voice']) if value.get('voice') else None
+ with self.changed:
+ digest, replay = self._receipt('cast:create', value, ref, client)
+ if replay is not None:
+ return replay
+ stamp = self._now()
+ supplied = dict(name=True, description=value.get('description') is not None,
+ images=bool(images), voice=voice is not None)
+ card = dict(id=identity, kind=value['kind'], name=value['name'], description=value.get('description'),
+ images=images, voice=voice, revision=1, created_at=stamp, updated_at=stamp, by=by,
+ origin=by, made_for=made_for, used_by=[],
+ edited_by_user={k: by == 'user' and supplied[k] for k in EDITABLE},
+ candidates=[], generating=None, generate_error=None, generated=None, _user_images=0)
+ record = dict(card=card, receipts=[])
+ result = view(card)
+ self._remember(record, ref, digest, result, client)
+ self._save(record)
+ return result
+
+ def get(self, identity):
+ with self.changed:
+ return view(self._record(identity)['card'])
+
+ def list(self, *, q=None, kind=None, origin=None, production=None, limit=50):
+ with self.changed:
+ cards = [r['card'] for r in self.records.values()]
+ text = q.casefold() if q else None
+ rows = [c for c in cards if (not kind or c['kind'] == kind) and (not origin or c['origin'] == origin)
+ and (not production or production in c['used_by'] or c['made_for'] == production)
+ and (not text or text in c['name'].casefold() or text in (c['description'] or '').casefold())]
+ rows.sort(key=lambda c: (c['updated_at'], c['id']), reverse=True)
+ return dict(cards=[row_view(c) for c in rows[:limit]], total=len(rows))
+
+ 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)
+ 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)
+ payload = dict(value, revision=expected)
+ scope = 'cast:update:' + str(identity)
+ with self.changed:
+ digest, replay = self._receipt(scope, payload, ref, client)
+ if replay is not None:
+ return replay
+ card = self._record(identity)['card']
+ if expected is None:
+ raise spec.SpecError([schema.diagnostic('/revision', 'the card revision you read (or an If-Match header)',
+ None, missing=True)])
+ if expected != card['revision']:
+ raise self._stale(card)
+ changes = self._changes(card, value, by)
+ resolved = {}
+ for key, rows in changes.items():
+ if key == 'images':
+ resolved['images'] = [entry if entry is not None else dict(self._picture(identity, row['media'], by),
+ label=row.get('label', 'other')) for row, entry in rows]
+ elif key == 'voice':
+ resolved['voice'] = None if rows is None else self._voice(identity, rows)
+ else:
+ resolved[key] = rows
+ with self.changed:
+ digest, replay = self._receipt(scope, payload, ref, client)
+ if replay is not None:
+ return replay
+ record = deepcopy(self._record(identity))
+ card = record['card']
+ if card['revision'] != expected:
+ raise self._stale(card)
+ if resolved:
+ if 'images' in resolved:
+ files = {row['media']['file'] for row in resolved['images']}
+ card['candidates'] = [row for row in card['candidates'] if row['media']['file'] not in files]
+ if by == 'user':
+ card['_user_images'] = card.get('_user_images', 0) + 1
+ card.update(resolved, revision=card['revision'] + 1, updated_at=self._now(), by=by)
+ if by == 'user':
+ for key in resolved:
+ card['edited_by_user'][key] = True
+ result = view(card)
+ self._remember(record, ref, digest, result, client)
+ if resolved or ref is not None:
+ self._save(record)
+ return result
+
+ def _changes(self, card, value, by):
+ """What this request changes, checked against the user's edits before any media work."""
+ changes = {}
+ for key in ('name', 'description'):
+ if key in value and value[key] != card[key]:
+ changes[key] = value[key]
+ if 'images' in value:
+ known = {row['media']['file']: row for row in card['images']}
+ offered = {row['media']['file']: row for row in card['candidates']}
+ rows, kept, added, fresh = [], set(), set(), False
+ for row in value['images']:
+ file = _plain(row['media'])
+ entry = deepcopy(known.get(file) or offered.get(file)) if file else None
+ if entry is not None:
+ (kept if file in known else added).add(file)
+ if row.get('label', entry['label']) != entry['label']:
+ entry.update(label=row['label'], by=by)
+ entry.pop('label_guess', None)
+ if by == 'user':
+ entry.pop('generated', None) # The user's label makes it the user's picture.
+ else:
+ fresh = True
+ rows.append((row, entry))
+ current = [(r['media']['file'], r['label']) for r in card['images']]
+ proposed = [(e['media']['file'], e['label']) for _, e in rows if e is not None]
+ if fresh or proposed != current:
+ changes['images'] = rows
+ if by != 'user' and card['edited_by_user']['images']:
+ # The user's pictures may only be joined by candidates the server made; never replaced.
+ untouched = all((f, l) in proposed for f, l in current) and len(kept) == len(current)
+ if fresh or not untouched or not added:
+ raise self._by_user(card, 'images')
+ if 'voice' in value:
+ voice, current = value['voice'], card['voice']
+ if voice is None:
+ if current is not None:
+ changes['voice'] = None
+ else:
+ item = voice['media'] if isinstance(voice['media'], dict) else {'file': voice['media']}
+ item = {k: v for k, v in item.items() if k != 'url'}
+ same = current is not None and item == current['media'] and voice.get('start', 0) == current['start'] \
+ and voice.get('end', current['end']) == current['end']
+ if not same:
+ changes['voice'] = voice
+ if by != 'user':
+ for key in changes:
+ if key != 'images' and card['edited_by_user'][key]:
+ raise self._by_user(card, key)
+ return changes
+
+ def _by_user(self, card, key):
+ return CastError('changed_by_user', 'The user changed %s on this card.' % key,
+ "Keep the user's change; do not change it back. Ask the user if it must change.",
+ card=view(card))
+
+ def delete(self, identity, value=None, *, by='builtin', ref=None, revision=None, client=None):
+ value = value or {}
+ schema.validate(schema.cast_schema('delete'), value)
+ 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)
+ payload = dict(value, revision=expected)
+ with self.changed:
+ digest, replay = self._receipt('cast:delete:' + str(identity), payload, ref, client)
+ if replay is not None:
+ return replay
+ record = deepcopy(self._record(identity))
+ card = record['card']
+ if expected is not None and expected != card['revision']:
+ raise self._stale(card)
+ if by != 'user':
+ if card['origin'] != by or any(card['edited_by_user'].values()):
+ raise CastError('not_allowed', 'Only the user may delete this card.',
+ 'Ask the user before deleting this card.', card=view(card))
+ if any(self._unfinished(film) for film in card['used_by']):
+ raise CastError('card_in_use', errors.ERRORS['card_in_use'][2],
+ errors.ERRORS['card_in_use'][3], card=view(card))
+ self._before_delete(card)
+ card.update(deleted_at=self._now(), deleted_by=by)
+ result = dict(id=card['id'], deleted=True)
+ self._remember(record, ref, digest, result, client)
+ self._write(self.directory / '.deleted', record)
+ (self.directory / (card['id'] + '.json')).unlink(missing_ok=True)
+ self.records.pop(card['id'], None)
+ self.deleted[card['id']] = record
+ self.changed.notify_all()
+ return result
+
+ def _before_delete(self, card):
+ """A generation ends with its card; Jobs also refuses to start it once the card is gone."""
+ for job in _generation_jobs(card.get('generating')):
+ row = self.jobs.jobs.get(job)
+ if row is not None and row['status'] in ACTIVE:
+ try:
+ self.jobs.cancel(job)
+ except (JobError, KeyError):
+ pass
+
+ def _unfinished(self, film):
+ record = self.jobs.productions.records.get(film)
+ return record is not None and record['state'].get('status') not in FINISHED
+
+ # Filming ------------------------------------------------------------------------------------------
+ def snapshot(self, identity):
+ """The current card for a submission, or None once it is deleted or unknown."""
+ with self.changed:
+ record = self.records.get(identity)
+ return deepcopy(record['card']) if record else None
+
+ def used(self, identities, film):
+ """Record that a film uses these cards; a film never leaves used_by once it is there."""
+ with self.changed:
+ for identity in identities:
+ record = self.records.get(identity)
+ if record is None or film in record['card']['used_by']:
+ continue
+ record = deepcopy(record)
+ card = record['card']
+ if card['made_for'] is None and not card['used_by'] and card['origin'] != 'user':
+ card['made_for'] = film
+ card['used_by'].append(film)
+ self._save(record)
+
+ # Reference pictures -------------------------------------------------------------------------------
+ def generate(self, identity, value=None, *, by='builtin', ref=None, revision=None, client=None):
+ """Submit a reference clip (and a face close-up) for this card; the scheduler lands the frames."""
+ value = value or {}
+ shape = schema.cast_schema('generate')
+ schema.validate(shape, value)
+ ref = ref if ref is not None else value.get('ref')
+ value = schema.defaults(shape, {k: v for k, v in value.items() if k != 'ref'})
+ expected = _revision(value.pop('revision', None), revision)
+ payload = dict(value, revision=expected)
+ with self.changed:
+ digest, replay = self._receipt('cast:generate:' + str(identity), payload, ref, client)
+ if replay is not None:
+ return replay
+ record = deepcopy(self._record(identity))
+ card = record['card']
+ if expected is not None and expected != card['revision']:
+ raise self._stale(card)
+ if card['generating']:
+ job = card['generating']['job']
+ raise CastError('already_generating', errors.ERRORS['already_generating'][2],
+ 'GET /freevideo/agent/v1/jobs/%s; when it ends, get the card.' % job,
+ card=view(card), job=job)
+ if value['face'] and card['kind'] != 'character':
+ raise spec.SpecError([schema.diagnostic('/face', 'false for a setting card', True)])
+ seed = secrets.randbelow(spec.MAX_SEED + 1)
+ token = uuid.uuid4().hex[:12]
+ parts = [('turn', SCENE if card['kind'] == 'setting' else TURN, False)]
+ if value['face']:
+ parts.append(('face', CLOSE_UP, True))
+ items = [dict(kind='generate', prompt=reference_prompt(card, face=face), seed=seed,
+ label=('Cast · %s · %s' % (card['name'], part))[:120],
+ metadata=dict(cast_card=identity, cast_part=part), **shot)
+ for part, shot, face in parts]
+ rows, _ = self.jobs.submit_request(dict(jobs=items), client='cast:' + identity,
+ parent=dict(cast=identity, ref=token))
+ jobs = [row['id'] for row in rows]
+ card['generating'] = dict(job=jobs[0], face_job=jobs[1] if len(jobs) > 1 else None,
+ replace=value['replace'], at=self._now(), by=by)
+ card['_generating'] = dict(ref=token, seed=seed, kind=card['kind'], user_images=card.get('_user_images', 0))
+ result = dict(job=jobs[0], jobs=jobs, card=view(card))
+ self._remember(record, ref, digest, result, client)
+ self._save(record)
+ return result
+
+ def allows(self, parent):
+ """May Jobs still start this generation? Only while its card waits for it."""
+ with self.changed:
+ record = self.records.get(parent.get('cast'))
+ hidden = record['card'].get('_generating') if record else None
+ return bool(hidden) and hidden['ref'] == parent.get('ref')
+
+ def _finished(self):
+ """Cards whose generation jobs have all ended, with those jobs as they ended."""
+ ready = []
+ with self.changed:
+ for identity, record in self.records.items():
+ card = record['card']
+ if not card.get('generating') or not card.get('_generating'):
+ continue
+ rows = {job: self.jobs.jobs.get(job) for job in _generation_jobs(card['generating'])}
+ if all(row is None or row['status'] in DONE for row in rows.values()):
+ ready.append((identity, deepcopy(card['generating']), deepcopy(card['_generating']),
+ {job: deepcopy(row) for job, row in rows.items()}))
+ return ready
+
+ def pending(self):
+ return bool(self._finished())
+
+ def tick(self):
+ """Land finished reference clips on their cards. Runs off Jobs' lock: frames take a moment to pick.
+
+ Several callers tick at once (the scheduler, job submissions, resumes); each card is landed by one
+ of them at a time. Never raises: a landing that cannot be saved is recorded on its card."""
+ try:
+ finished = self._finished()
+ except Exception as error: # noqa: BLE001 - submissions that tick must not fail because of a card
+ logging.getLogger(__name__).warning('Reference pictures could not be checked (%s)', type(error).__name__)
+ return
+ for identity, generating, hidden, rows in finished:
+ if not self._claim(identity, hidden):
+ continue # Landed already, or another tick is landing it now.
+ try:
+ self._land(identity, generating, hidden, rows)
+ except Exception as error: # noqa: BLE001 - one card must never stop the others
+ logging.getLogger(__name__).warning('Reference pictures could not be saved (%s)', type(error).__name__)
+ self._fail(identity, hidden, dict(code='internal_error', job=generating['job'],
+ message='The reference pictures could not be saved.'))
+ finally:
+ with self.changed:
+ self.landing.discard(identity)
+
+ def _claim(self, identity, hidden):
+ """Take this card's landing if it still waits for this generation and nobody else is landing it."""
+ with self.changed:
+ record = self.records.get(identity)
+ if (identity in self.landing or record is None
+ or (record['card'].get('_generating') or {}).get('ref') != hidden['ref']):
+ return False
+ self.landing.add(identity)
+ return True
+
+ def _land(self, identity, generating, hidden, rows):
+ from . import media
+ pictures, failure, staged = [], None, []
+ try:
+ for job in _generation_jobs(generating):
+ row = rows[job]
+ face = job == generating.get('face_job')
+ if row is None or row['status'] != 'succeeded':
+ code = (row.get('error') or {}).get('code') if row else 'not_found'
+ failure = failure or dict(code=code or row['status'], job=job, message=(
+ 'The generation was cancelled.' if row and row['status'] == 'cancelled'
+ else 'The reference clip did not finish.'))
+ continue
+ folder = 'freevideo/agent/%s/ref-%s' % (identity, job)
+ count = 1 if face else COUNT
+ # Frames go to new names first and replace the card's files only once the card takes them,
+ # so a file a card already names is never missing, even for a moment.
+ mark = uuid.uuid4().hex[:8]
+ temporary = [self.jobs.port.input_path('%s-%d.landing-%s.png' % (folder, n, mark), create=True)
+ for n in range(count)]
+ for left in temporary[0].parent.glob('ref-%s-*.landing-*.png' % job):
+ if left not in temporary:
+ left.unlink(missing_ok=True) # Left by a landing that stopped before the card was saved.
+ try:
+ video = self.jobs.job_video(job)
+ with self.jobs.cpu:
+ picked = media.sharpest_frames(video, temporary)
+ except Exception as error: # noqa: BLE001 - the other clip's frames still land
+ for out in temporary:
+ out.unlink(missing_ok=True)
+ if _unreadable(error):
+ failure = failure or dict(code='clip_unreadable', job=job,
+ message='The reference clip could not be read.')
+ else:
+ logging.getLogger(__name__).warning('Reference frames could not be picked (%s)',
+ type(error).__name__)
+ failure = failure or dict(code='internal_error', job=job,
+ message='The reference pictures could not be saved.')
+ continue
+ setting = hidden.get('kind') == 'setting'
+ for n, row_frame in enumerate(picked):
+ if row_frame is None:
+ temporary[n].unlink(missing_ok=True)
+ continue
+ file = '%s-%d.png' % (folder, n)
+ staged.append((temporary[n], file))
+ entry = dict(media=dict(file=file), by=generating['by'], from_job=job, generated=True)
+ if face:
+ entry['label'] = 'face'
+ elif setting:
+ entry['label'] = 'other'
+ else:
+ entry.update(label=turn_label((n + .5) / count), label_guess=True)
+ pictures.append(entry)
+ if not any(picked):
+ failure = failure or dict(code='no_sharp_frame', job=job,
+ message='The reference clip had no sharp frame to keep.')
+ self._settle(identity, hidden, pictures, failure, staged)
+ finally:
+ for out, _ in staged:
+ out.unlink(missing_ok=True) # Not taken by the card (published ones are gone already).
+
+ def _settle(self, identity, hidden, pictures, failure, staged=()):
+ """Write the pictures into the card once; a later generation or a deletion makes this one stale."""
+ with self.changed:
+ record = self.records.get(identity)
+ if record is None or (record['card'].get('_generating') or {}).get('ref') != hidden['ref']:
+ return
+ record = deepcopy(record)
+ card = record['card']
+ generating = card['generating']
+ by = generating['by']
+ protected = by != 'user' and card['edited_by_user']['images']
+ if card.get('_user_images', 0) != hidden['user_images'] or protected:
+ # The user changed the pictures meanwhile, or owns them: offer, never add or overwrite.
+ images, spare = card['images'], pictures
+ elif generating['replace']:
+ kept = [r for r in card['images'] if r.get('by') == 'user' and not r.get('generated')]
+ room = MAX_IMAGES - len(kept)
+ images, spare = kept + pictures[:room], pictures[room:]
+ else:
+ room = MAX_IMAGES - len(card['images'])
+ images, spare = card['images'] + pictures[:room], pictures[room:]
+ files = {r['media']['file'] for r in images}
+ candidates, seen = [], set()
+ for row in spare + card['candidates']:
+ file = row['media']['file']
+ if file not in files and file not in seen:
+ seen.add(file)
+ candidates.append(row)
+ for out, file in staged:
+ os.replace(out, self.jobs.port.input_path(file, create=True))
+ card.update(images=images, candidates=candidates[:MAX_CANDIDATES], generating=None,
+ generate_error=failure, revision=card['revision'] + 1, updated_at=self._now(), by=by,
+ generated=dict(job=generating['job'], face_job=generating.get('face_job'),
+ seed=hidden['seed'], prompt_version=PROMPT_VERSION))
+ card.pop('_generating', None)
+ self._save(record)
+
+ def _fail(self, identity, hidden, failure):
+ """Record a landing that failed on its card, keeping the pictures it has."""
+ try:
+ self._settle(identity, hidden, [], failure)
+ return
+ except Exception as error: # noqa: BLE001 - the card file cannot be written now
+ logging.getLogger(__name__).warning('A cast card could not be saved (%s)', type(error).__name__)
+ # Shown until the next restart, so ticks do not land it again and again; the saved card still waits
+ # for this generation and lands it again after a restart.
+ with self.changed:
+ record = self.records.get(identity)
+ if record is None or (record['card'].get('_generating') or {}).get('ref') != hidden['ref']:
+ return
+ record = deepcopy(record)
+ card = record['card']
+ card.update(generating=None, generate_error=failure, revision=card['revision'] + 1,
+ updated_at=self._now())
+ card.pop('_generating', None)
+ self.records[identity] = record
+ self.changed.notify_all()
+
+
+def _unreadable(error):
+ """A clip that is gone or cannot be decoded, rather than a fault of ours."""
+ if isinstance(error, (JobError, ValueError, OSError)):
+ return True
+ try:
+ import av
+ except ImportError:
+ return False
+ return isinstance(error, av.error.FFmpegError)
+
+
+def _generation_jobs(generating):
+ if not generating:
+ return []
+ return [generating['job']] + ([generating['face_job']] if generating.get('face_job') else [])
diff --git a/freevideo_engine/agent/cli.py b/freevideo_engine/agent/cli.py
new file mode 100644
index 0000000..ed1b81e
--- /dev/null
+++ b/freevideo_engine/agent/cli.py
@@ -0,0 +1,277 @@
+"""./freevideo agent ... — the agent API from a shell; every command prints JSON.
+
+ ./freevideo agent status
+ ./freevideo agent submit shot.json --wait
+ ./freevideo agent batch storyboard.json --wait
+ ./freevideo agent job j0123456789ab
+"""
+import argparse
+import json
+from pathlib import Path
+import sys
+
+from .client import ApiError, Client
+from . import schema, spec, errors
+
+
+def read(path):
+ text = sys.stdin.read() if path == '-' else Path(path).read_text(encoding='utf-8')
+ value = json.loads(text)
+ schema.validate({'type': 'object'}, value)
+ return value
+
+
+EXTRA_COMMANDS = {
+ 'inspect': ('POST', '/media/inspect'), 'contact-sheet': ('POST', '/media/contact-sheet'),
+ 'edit': ('POST', '/media/edit'), 'library': ('GET', '/library'),
+ 'queue': ('GET', '/queue'), 'hello': ('POST', '/connect/hello'),
+ 'connection-status': ('GET', '/connect/status'), 'openapi': ('GET', '/openapi.json'),
+}
+
+
+class Parser(argparse.ArgumentParser):
+ def error(self, message):
+ self.exit(2, errors.text(errors.build('invalid_request')) + '\n')
+
+
+def build_parser():
+ parser = Parser(prog='./freevideo agent', description='Drive FreeVideo through its agent API.')
+ parser.add_argument('--root', type=Path)
+ parser.add_argument('--url')
+ commands = parser.add_subparsers(dest='command', required=True)
+ commands.add_parser('status', help='Readiness, limits, LoRAs, VLM and queue')
+ commands.add_parser('guide', help='How to write H3 prompts')
+ commands.add_parser('schema', help='JSON Schemas of jobs')
+ command = commands.add_parser('capabilities', help='Read the studio capability cache')
+ schema.cli_arguments(command, schema.contracts()['GET', '/capabilities']['query'])
+ command = commands.add_parser('asset', help='Download a saved library video or thumbnail over HTTP')
+ command.add_argument('id')
+ command.add_argument('target', type=Path)
+ command.add_argument('--thumbnail', action='store_true')
+ for name, text in (('plan', 'Validate a job file and estimate it'), ('submit', 'Submit a job file (- = stdin)'),
+ ('batch', 'Submit {"jobs": [...]} with @ref links')):
+ command = commands.add_parser(name, help=text)
+ command.add_argument('file')
+ if name != 'plan':
+ command.add_argument('--wait', action='store_true', help='Wait for the job(s) and print the results')
+ if name in ('submit', 'plan'):
+ schema.cli_arguments(command, schema.generate(local=True))
+ else:
+ schema.cli_arguments(command, schema.batch_schema(local=True), exclude=('jobs',))
+ for name in ('job', 'wait', 'cancel', 'resume'):
+ command = commands.add_parser(name)
+ command.add_argument('id')
+ if name == 'wait':
+ schema.cli_arguments(command, schema.obj({'timeout': schema.CLIENT_WAIT}))
+ elif name == 'job':
+ schema.cli_arguments(command, schema.contracts()['GET', '/jobs/{id}']['query'])
+ elif name == 'resume':
+ schema.cli_arguments(command, schema.contracts()['POST', '/jobs/{id}/resume']['body'])
+ command = commands.add_parser('jobs')
+ schema.cli_arguments(command, schema.contracts()['GET', '/jobs']['query'])
+ command = commands.add_parser('upload', help='Copy a local media file into FreeVideo inputs')
+ command.add_argument('path')
+ command = commands.add_parser('drama', help='Plan, start, review and finish a durable film')
+ drama = command.add_subparsers(dest='operation', required=True)
+ for name, (method, path, summary) in schema.DRAMA_OPERATIONS.items():
+ sub = drama.add_parser(name, help=summary)
+ if '{id}' in path:
+ sub.add_argument('id')
+ if '{shot}' in path:
+ sub.add_argument('shot')
+ if name in ('plan', 'start'):
+ sub.add_argument('file', help='JSON production request with screenplay (- = stdin)')
+ schema.cli_arguments(sub, schema.drama_schema(name))
+ command = commands.add_parser('cast', help='Find, create and change character and setting cards')
+ cast = command.add_subparsers(dest='operation', required=True)
+ for name, (method, path, summary) in schema.CAST_OPERATIONS.items():
+ sub = cast.add_parser(name, help=summary)
+ if '{id}' in path:
+ sub.add_argument('id')
+ if name in ('create', 'update'):
+ sub.add_argument('file', nargs='?', help='JSON card fields (- = stdin); options override them')
+ schema.cli_arguments(sub, schema.cast_schema(name, local=True))
+ command = commands.add_parser('projects', help='Read and edit timelines shared with the editor page')
+ projects = command.add_subparsers(dest='operation', required=True)
+ for name, (method, path, summary) in schema.PROJECT_OPERATIONS.items():
+ sub = projects.add_parser(name, help=summary)
+ if '{id}' in path:
+ sub.add_argument('id')
+ if name in ('create', 'write'):
+ sub.add_argument('file', nargs='?', help='JSON {project, ref?} request (- = stdin); options override it')
+ if name == 'operations':
+ sub.add_argument('--operations-file', help='JSON array of operations (- = stdin)')
+ schema.cli_arguments(sub, schema.project_schema(name))
+ command = commands.add_parser('images', help='Edit pictures with the image editor\'s commands')
+ images = command.add_subparsers(dest='operation', required=True)
+ for name, (method, path, summary) in schema.IMAGE_OPERATIONS.items():
+ sub = images.add_parser(name, help=summary)
+ if '{id}' in path:
+ sub.add_argument('id')
+ if name in ('create', 'write'):
+ sub.add_argument('file', nargs='?', help='JSON request (- = stdin); options override it')
+ if name == 'operations':
+ sub.add_argument('--operations-file', help='JSON array of operations (- = stdin)')
+ schema.cli_arguments(sub, schema.image_schema(name))
+ command = commands.add_parser('sessions', help='Share messages and plans with the user in a work conversation')
+ sessions = command.add_subparsers(dest='operation', required=True)
+ for name in ('list', 'create', 'events', 'post'):
+ _, path, summary = schema.SESSION_OPERATIONS[name]
+ sub = sessions.add_parser(name, help=summary)
+ if '{id}' in path:
+ sub.add_argument('id')
+ if name == 'post':
+ content = sub.add_mutually_exclusive_group(required=True)
+ content.add_argument('--message', help='Text to send to the user')
+ content.add_argument('--plan-file', help='JSON {shots, total_seconds?} plan (- = stdin)')
+ else:
+ schema.cli_arguments(sub, schema.session_schema(name))
+ command = commands.add_parser('frame', help='Save a frame of a job or saved video')
+ command.add_argument('source')
+ schema.cli_arguments(command, schema.contracts()['POST', '/media/frame']['body'], exclude=('source',))
+ for name, (method, path) in EXTRA_COMMANDS.items():
+ command = commands.add_parser(name)
+ definition = schema.contracts(local=True)[method, path]
+ schema.cli_arguments(command, definition['query'] if method == 'GET' else definition['body'])
+ return parser
+
+
+def main(argv=None):
+ parser = build_parser()
+ args = parser.parse_args(argv)
+ values = vars(args)
+
+ def progress(view):
+ value = view.get('progress') or {}
+ line = '%s %s %s' % (view['id'], view['status'], value.get('label') or '')
+ if value.get('fraction') is not None:
+ line += ' %d%%' % round(100 * value['fraction'])
+ print(line.rstrip(), file=sys.stderr, flush=True)
+
+ def source(value):
+ from .spec import JOB_ID, LIBRARY_ID
+ return {'from_job': value} if JOB_ID.fullmatch(value) else {'library': value} if LIBRARY_ID.fullmatch(value) \
+ else {'path': str(Path(value).resolve())} if Path(value).exists() else {'file': value}
+
+ try:
+ client = Client(args.url, root=args.root, name='freevideo-cli')
+ if args.command in EXTRA_COMMANDS:
+ method, path = EXTRA_COMMANDS[args.command]
+ definition = schema.contracts(local=True)[method, path]
+ shape = definition['query'] if method == 'GET' else definition['body']
+ value = {k: values[k] for k in shape['properties'] if k in values}
+ schema.validate(shape, value)
+ result = client.get(path, **value) if method == 'GET' else client.post(path, value)
+ elif args.command == 'status':
+ result = client.capabilities()
+ elif args.command == 'guide':
+ result = client.guide()
+ elif args.command == 'schema':
+ result = client.schema()
+ elif args.command == 'capabilities':
+ fields = schema.contracts()['GET', '/capabilities']['query']['properties']
+ result = client.capability_table(**{k: values[k] for k in fields if k in values})
+ elif args.command == 'asset':
+ result = dict(id=args.id, path=str(client.asset(args.id, args.target, thumbnail=args.thumbnail)))
+ elif args.command == 'plan':
+ value = read(args.file) | {k: values[k] for k in schema.generate()['properties'] if k in values}
+ schema.validate_job(value, local=True)
+ schema.preflight_submission(value)
+ result = client.plan(value)
+ elif args.command in ('submit', 'batch'):
+ fields = schema.batch_schema() if args.command == 'batch' else schema.generate()
+ value = read(args.file) | {k: values[k] for k in fields['properties'] if k in values}
+ schema.validate(schema.batch_schema(local=True) if args.command == 'batch' else schema.job_schema(local=True), value)
+ schema.preflight_submission(value)
+ jobs = client.batch(value['jobs'], **({'ref': value['ref']} if 'ref' in value else {})) if args.command == 'batch' else \
+ client.submit_takes(value, value['takes']) if value.get('takes', 1) > 1 else [client.submit(value)]
+ if args.wait:
+ jobs = [client.wait(job['id'], on_progress=progress) for job in jobs]
+ result = jobs[0] if len(jobs) == 1 and args.command == 'submit' else {'jobs': jobs}
+ elif args.command == 'job':
+ result = client.job(args.id, **({'wait': values['wait']} if 'wait' in values else {}))
+ elif args.command == 'wait':
+ result = client.wait(args.id, values.get('timeout', 25), on_progress=progress)
+ elif args.command == 'cancel':
+ result = client.cancel(args.id)
+ elif args.command == 'resume':
+ result = client.resume(args.id, **({'ref': values['ref']} if 'ref' in values else {}))
+ elif args.command == 'jobs':
+ result = {'jobs': client.jobs(**{k: values[k] for k in schema.contracts()['GET', '/jobs']['query']['properties'] if k in values})}
+ elif args.command == 'drama':
+ method, path, _ = schema.DRAMA_OPERATIONS[args.operation]
+ shape = schema.drama_schema(args.operation)
+ value = read(args.file) if args.operation in ('plan', 'start') else {}
+ value.update({k: values[k] for k in shape['properties'] if k in values})
+ schema.validate(shape, value)
+ for key in ('id', 'shot'):
+ if '{' + key + '}' in path:
+ schema.validate(schema.PRODUCTION if key == 'id' else schema.SLUG, values[key])
+ path = path.replace('{' + key + '}', values[key])
+ result = client.get(path, **value) if method == 'GET' else client.post(path, value)
+ elif args.command == 'cast':
+ method, path, _ = schema.CAST_OPERATIONS[args.operation]
+ shape = schema.cast_schema(args.operation, local=True)
+ value = read(args.file) if getattr(args, 'file', None) else {}
+ value.update({k: values[k] for k in shape['properties'] if k in values})
+ schema.validate(shape, value)
+ if '{id}' in path:
+ schema.validate(schema.CAST, values['id'])
+ path = path.replace('{id}', values['id'])
+ result = client.get(path, **value) if method == 'GET' else client.send(method, path, value)
+ elif args.command in ('projects', 'images'):
+ table, shape_of, ident = ((schema.PROJECT_OPERATIONS, schema.project_schema, schema.PROJECT)
+ if args.command == 'projects' else (schema.IMAGE_OPERATIONS, schema.image_schema, schema.IMAGE))
+ method, path, _ = table[args.operation]
+ shape = shape_of(args.operation)
+ value = read(args.file) if getattr(args, 'file', None) else {}
+ value.update({k: values[k] for k in shape['properties'] if k in values})
+ if getattr(args, 'operations_file', None):
+ text = sys.stdin.read() if args.operations_file == '-' else Path(args.operations_file).read_text(encoding='utf-8')
+ value['operations'] = json.loads(text)
+ schema.validate(shape, value)
+ if '{id}' in path:
+ schema.validate(ident, args.id)
+ path = path.replace('{id}', args.id)
+ result = client.get(path, **value) if method == 'GET' else client.send(method, path, value)
+ elif args.command == 'sessions':
+ method, path, _ = schema.SESSION_OPERATIONS[args.operation]
+ shape = schema.session_schema(args.operation)
+ if args.operation == 'post':
+ if args.message is not None:
+ value = dict(type='message', text=args.message)
+ else:
+ value = dict(type='plan') | read(args.plan_file)
+ schema.validate(schema.session_event(agent_only=True)['oneOf'][1], value)
+ schema.validate(schema.session_event(agent_only=True), value)
+ else:
+ value = {k: values[k] for k in shape['properties'] if k in values}
+ schema.validate(shape, value)
+ if '{id}' in path:
+ schema.validate(schema.SESSION, args.id)
+ path = path.replace('{id}', args.id)
+ result = client.get(path, **value) if method == 'GET' else client.post(path, value)
+ elif args.command == 'upload':
+ result = client.upload(args.path)
+ else:
+ result = client.frame(source(args.source), values.get('at', 'last'))
+ except ApiError as error:
+ if error.inbox:
+ print(json.dumps(dict(inbox=error.inbox), ensure_ascii=False, indent=1))
+ print(str(error), file=sys.stderr)
+ return 2
+ except spec.SpecError as error:
+ print(errors.text(errors.validation(error.errors)), file=sys.stderr)
+ return 2
+ except (ValueError, OSError):
+ print(errors.text(errors.build('invalid_request')), file=sys.stderr)
+ return 2
+ print(json.dumps(result, ensure_ascii=False, indent=1))
+ failed = isinstance(result, dict) and result.get('status') in ('failed', 'cancelled', 'interrupted')
+ if failed and result.get('error'):
+ print(errors.text(result['error']), file=sys.stderr)
+ return 1 if failed else 0
+
+
+if __name__ == '__main__':
+ raise SystemExit(main())
diff --git a/freevideo_engine/agent/client.py b/freevideo_engine/agent/client.py
new file mode 100644
index 0000000..ca61ef3
--- /dev/null
+++ b/freevideo_engine/agent/client.py
@@ -0,0 +1,360 @@
+"""A small standard-library client for the FreeVideo agent API (used by the MCP server and the CLI).
+
+ from freevideo_engine.agent.client import Client
+ fv = Client() # finds the server and token of this installation
+ shot = fv.submit({'prompt': '...', 'aspect': '9:16', 'seconds': 6})
+ done = fv.wait(shot['id']) # {'status': 'succeeded', 'result': {'video': {...}}}
+"""
+import base64
+import json
+import ipaddress
+import os
+from pathlib import Path
+import threading
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+
+DONE = ('succeeded', 'failed', 'cancelled', 'interrupted')
+
+
+class ApiError(Exception):
+ def __init__(self, status, code, message, details=None, *, inbox=None, **context):
+ from . import errors
+ error = errors.build(code, **context)
+ # The user's words delivered with a failed call are already read on the server.
+ self.inbox = inbox if isinstance(inbox, list) else []
+ # Server errors already passed the public boundary. Keep their exact text.
+ if details and details.get('next'):
+ error.update(message=message, **details)
+ self.status, self.code, self.message = status, error['code'], error['message']
+ self.details = {k: v for k, v in error.items() if k not in ('code', 'message')}
+ super().__init__(errors.text(error))
+
+
+def local_file(path):
+ try:
+ source = Path(path).expanduser()
+ if source.is_file():
+ return source
+ except (OSError, ValueError, TypeError):
+ pass
+ # Agents often pass a path FreeVideo returned (assets, inputs, outputs) as a local file.
+ raise ApiError(422, 'invalid_media', 'There is no readable file at this path on this computer.', dict(
+ next='Use "path" only for a file on this computer. Send a file FreeVideo returned as {"file": "<that path>"}.',
+ details=[dict(field='path')]))
+
+
+def default_root():
+ if os.environ.get('FREEVIDEO_HOME'):
+ return Path(os.environ['FREEVIDEO_HOME']).expanduser()
+ here = Path(__file__).resolve().parents[2]
+ if (here / 'machine.json').is_file() or (here / 'agent').is_dir():
+ return here
+ try:
+ from ..bootstrap import DEFAULT_ROOT
+ return Path(DEFAULT_ROOT)
+ except Exception: # noqa: BLE001 - the bootstrap module needs the full engine environment
+ return here
+
+
+def endpoint_url(value):
+ try:
+ parsed = urllib.parse.urlsplit(value)
+ if (parsed.scheme not in ('http', 'https') or not parsed.hostname or parsed.username is not None
+ or parsed.password is not None or parsed.query or parsed.fragment or parsed.port == 0
+ or any(c.isspace() for c in value) or '\\' in value):
+ raise ValueError
+ parsed.port
+ except (TypeError, ValueError, AttributeError):
+ raise ApiError(422, 'invalid_request', 'Invalid endpoint') from None
+ return value.rstrip('/')
+
+
+def origin(url):
+ value = urllib.parse.urlsplit(endpoint_url(url.split('?', 1)[0].split('#', 1)[0]))
+ return value.scheme, value.hostname.lower(), value.port or (443 if value.scheme == 'https' else 80)
+
+
+class LocalProxyHandler(urllib.request.ProxyHandler):
+ def proxy_open(self, req, proxy, type):
+ host = urllib.parse.urlsplit(req.full_url).hostname
+ try:
+ address = ipaddress.ip_address(host)
+ local = address.is_loopback or bool(getattr(address, 'ipv4_mapped', None) and address.ipv4_mapped.is_loopback)
+ except ValueError:
+ local = host.lower() == 'localhost'
+ if local:
+ return None
+ return super().proxy_open(req, proxy, type)
+
+
+class CredentialRedirect(urllib.request.HTTPRedirectHandler):
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
+ credentialed = any(req.has_header(k) for k in ('Authorization', 'X-freevideo-agent', 'Cookie'))
+ if credentialed and origin(req.full_url) != origin(newurl):
+ raise ApiError(403, 'redirect_forbidden', 'Cross-origin redirect refused')
+ return super().redirect_request(req, fp, code, msg, headers, newurl)
+
+
+def controlled_opener():
+ return urllib.request.build_opener(LocalProxyHandler(), CredentialRedirect())
+
+
+class Client:
+ def __init__(self, url=None, token=None, *, root=None, name='freevideo-python', timeout=60):
+ root = Path(root).expanduser() if root else default_root()
+ self.root = root
+ endpoint = {}
+ try:
+ endpoint = json.loads((root / 'agent' / 'endpoint.json').read_text(encoding='utf-8'))
+ except (OSError, ValueError):
+ pass
+ self.url = endpoint_url(url or os.environ.get('FREEVIDEO_URL') or (endpoint.get('url') if isinstance(endpoint, dict) else None) or 'http://127.0.0.1:8188')
+ self.opener = controlled_opener()
+ if token is None:
+ try:
+ token = (root / 'agent' / 'token').read_text(encoding='ascii').strip()
+ except OSError:
+ token = None
+ self.token, self.name, self.timeout = token, name, timeout
+ # Per-thread extra headers: the MCP server runs each tool call on its own thread.
+ self.call_headers = threading.local()
+
+ # Transport ------------------------------------------------------------------------------------------
+ def relative_url(self, path):
+ if not isinstance(path, str) or not path.startswith('/') or path.startswith('//') or '\\' in path:
+ raise ApiError(422, 'invalid_request', 'Expected a relative API endpoint')
+ return self.url + path
+
+ def request(self, method, path, body=None, *, query=None, timeout=None, raw=False, encoded=None, content_type=None, content_length=None):
+ if self.token is None:
+ raise ApiError(0, 'no_token', 'The local token is unavailable.')
+ url = self.relative_url(path) + ('?' + urllib.parse.urlencode(query) if query else '')
+ data = encoded if encoded is not None else None if body is None else json.dumps(body).encode()
+ headers = {'Authorization': 'Bearer ' + self.token, 'X-FreeVideo-Client': self.name}
+ headers.update(getattr(self.call_headers, 'value', None) or {})
+ if data is not None:
+ headers['Content-Type'] = content_type or 'application/json'
+ if content_length is not None:
+ headers['Content-Length'] = str(content_length)
+ request = urllib.request.Request(url, data=data, method=method, headers=headers)
+ try:
+ with self.opener.open(request, timeout=timeout or self.timeout) as response:
+ payload = response.read()
+ except urllib.error.HTTPError as error:
+ payload = error.read()
+ try:
+ body = json.loads(payload)
+ problem = body.get('error') or {}
+ except (ValueError, AttributeError):
+ body, problem = {}, {}
+ raise ApiError(error.code, problem.get('code', 'http_%d' % error.code),
+ problem.get('message') or payload.decode('utf-8', 'replace')[:500],
+ {k: v for k, v in problem.items() if k not in ('code', 'message')},
+ inbox=body.get('inbox')) from None
+ except urllib.error.URLError:
+ submission = method == 'POST' and (path.endswith('/jobs') or path.endswith('/resume'))
+ raise ApiError(0, 'unreachable', 'The FreeVideo server could not be reached.',
+ stage='submission_unknown' if submission else 'request') from None
+ return payload if raw else json.loads(payload or b'{}')
+
+ def get(self, path, **query):
+ return self.request('GET', '/freevideo/agent/v1' + path, query={k: v for k, v in query.items() if v is not None})
+
+ def local_media(self, value):
+ if isinstance(value, list):
+ return [self.local_media(row) for row in value]
+ if isinstance(value, dict):
+ if 'path' in value and not any(k in value for k in ('file', 'from_job', 'library')):
+ return {k: v for k, v in value.items() if k != 'path'} | {'file': self.upload(value['path'])['file']}
+ return {k: v if k in ('metadata', 'edit', 'document', 'recipe') else self.local_media(v) for k, v in value.items()}
+ return value
+
+ def check_local_files(self, value):
+ """Check the whole client-side input set before publishing the first asset."""
+ from .schema import MAX_UPLOAD_BYTES
+ if isinstance(value, list):
+ for child in value:
+ self.check_local_files(child)
+ elif isinstance(value, dict):
+ if 'path' in value:
+ source = local_file(value['path'])
+ try:
+ if not 0 < source.stat().st_size <= MAX_UPLOAD_BYTES:
+ raise ValueError
+ except (OSError, ValueError, TypeError):
+ raise ApiError(422, 'invalid_media', 'Invalid local input') from None
+ for key, child in value.items():
+ if key not in ('metadata', 'edit', 'document', 'recipe'):
+ self.check_local_files(child)
+
+ def post(self, path, body, **kw):
+ return self.send('POST', path, body, **kw)
+
+ def patch(self, path, body, **kw):
+ return self.send('PATCH', path, body, **kw)
+
+ def delete(self, path, body=None, **kw):
+ return self.send('DELETE', path, body if body is not None else {}, **kw)
+
+ def send(self, method, path, body, **kw):
+ from . import schema
+ shape = schema.request_contract(method, path, local=True)
+ if shape is not None:
+ schema.validate(shape, body)
+ if path in ('/jobs', '/plan'):
+ schema.preflight_submission(body)
+ if path != '/media':
+ self.check_local_files(body)
+ body = self.local_media(body)
+ shape = schema.request_contract(method, path)
+ if shape is not None:
+ schema.validate(shape, body)
+ return self.request(method, '/freevideo/agent/v1' + path, body, **kw)
+
+ def hello(self, via='http'):
+ return self.post('/connect/hello', dict(client=self.name, via=via))
+
+ # API ------------------------------------------------------------------------------------------------
+ def capabilities(self):
+ return self.get('')
+
+ def capability_table(self, **query):
+ return self.get('/capabilities', **query)
+
+ def guide(self):
+ return self.get('/guide')
+
+ def schema(self):
+ return self.get('/schema')
+
+ def plan(self, spec):
+ return self.post('/plan', spec)
+
+ def submit(self, spec, takes=1):
+ body = dict(spec, takes=takes) if takes != 1 else spec
+ return self.post('/jobs', body)['job']
+
+ def submit_takes(self, spec, takes):
+ return self.post('/jobs', dict(spec, takes=takes))['jobs']
+
+ def batch(self, jobs, *, ref=None):
+ """Jobs may name themselves with "ref" and refer to each other as "@ref"."""
+ return self.post('/jobs', dict(jobs=jobs, **({'ref': ref} if ref else {})))['jobs']
+
+ def job(self, identity, wait=0):
+ wait = max(0, min(25, wait))
+ return self.request('GET', '/freevideo/agent/v1/jobs/' + identity, query={'wait': wait} if wait else None,
+ timeout=max(self.timeout, wait + 5))
+
+ def jobs(self, status=None, project=None, kind=None, limit=None):
+ return self.get('/jobs', status=status, project=project, kind=kind, limit=limit)['jobs']
+
+ def wait(self, identity, timeout=None, on_progress=None):
+ """Until the job finishes (or timeout seconds pass); returns the last job view."""
+ deadline = None if timeout is None else time.monotonic() + timeout
+ while True:
+ left = 25 if deadline is None else max(0, min(25, deadline - time.monotonic()))
+ view = self.job(identity, wait=left)
+ if on_progress:
+ on_progress(view)
+ if view['status'] in DONE or (deadline is not None and time.monotonic() >= deadline):
+ return view
+
+ def cancel(self, identity):
+ return self.post('/jobs/%s/cancel' % identity, {})
+
+ def resume(self, identity, *, ref=None):
+ return self.post('/jobs/%s/resume' % identity, {'ref': ref} if ref else {})
+
+ def asset(self, identity, target, *, thumbnail=False):
+ """Retrieve a library file through authenticated HTTP only."""
+ path = '/freevideo/agent/v1/library/%s/%s' % (identity, 'thumbnail' if thumbnail else 'file')
+ return self.download({'url': path}, target)
+
+ def upload(self, path):
+ """Read on the client computer and upload content; never send a local path."""
+ from .schema import MAX_UPLOAD_BYTES, MAX_JSON_UPLOAD_BYTES
+ source = local_file(path)
+ try:
+ size = source.stat().st_size
+ if size > MAX_UPLOAD_BYTES:
+ raise ApiError(413, 'too_large', 'File exceeds upload limit',
+ dict(next='Reduce the file to at most %d bytes.' % MAX_UPLOAD_BYTES, details=[dict(limit_bytes=MAX_UPLOAD_BYTES)]))
+ if size * 4 // 3 + 4096 <= MAX_JSON_UPLOAD_BYTES:
+ return self.upload_bytes(source.name, source.read_bytes())
+ import secrets
+ boundary = 'freevideo-' + secrets.token_hex(16)
+ # Only a safe extension crosses a MIME header; local filenames stay local.
+ suffix = source.suffix.lower()
+ if not suffix[1:].isalnum():
+ raise ApiError(422, 'invalid_media', 'Invalid media extension')
+ prefix = ('--%s\r\nContent-Disposition: form-data; name="file"; filename="media%s"\r\n'
+ 'Content-Type: application/octet-stream\r\n\r\n' % (boundary, suffix)).encode('ascii')
+ ending = ('\r\n--%s--\r\n' % boundary).encode('ascii')
+ with source.open('rb') as stream:
+ def chunks():
+ yield prefix
+ while data := stream.read(1024 * 1024):
+ yield data
+ yield ending
+ return self.request('POST', '/freevideo/agent/v1/media', encoded=chunks(),
+ content_type='multipart/form-data; boundary=' + boundary,
+ content_length=len(prefix) + size + len(ending), timeout=600)
+ except OSError:
+ raise ApiError(0, 'invalid_media', 'Cannot read local file') from None
+
+ def upload_bytes(self, name, data):
+ return self.post('/media', {'name': name, 'data_base64': base64.b64encode(data).decode()}, timeout=600)
+
+ def inspect(self, source):
+ return self.post('/media/inspect', {'source': source})
+
+ def frame(self, source, at=None):
+ return self.post('/media/frame', dict(source=source, **({'at': at} if at is not None else {})))
+
+ def edit(self, source, recipe=None, *, document=None, target=None):
+ body = {'source': source}
+ body.update({'recipe': recipe} if document is None else {'document': document})
+ if target:
+ body['target'] = list(target)
+ return self.post('/media/edit', body)
+
+ def contact_sheet(self, source, count=None, columns=None):
+ return self.post('/media/contact-sheet', dict(source=source, **{k: v for k, v in dict(count=count, columns=columns).items() if v is not None}))
+
+ def library(self, limit=None, before=None, query=None, project=None):
+ return self.get('/library', limit=limit, before=before, query=query, project=project)
+
+ def queue(self):
+ return self.get('/queue')
+
+ def download(self, view, target):
+ """Save a result file (a job result's video/view dict) somewhere else."""
+ target = Path(target)
+ if self.token is None:
+ raise ApiError(0, 'no_token', 'The local token is unavailable.')
+ request = urllib.request.Request(self.relative_url(view['url']), headers={
+ 'Authorization': 'Bearer ' + (self.token or ''), 'X-FreeVideo-Client': self.name})
+ try:
+ with self.opener.open(request, timeout=600) as response, target.open('wb') as stream:
+ while True:
+ chunk = response.read(1 << 20)
+ if not chunk:
+ break
+ stream.write(chunk)
+ except urllib.error.HTTPError as error:
+ try:
+ problem = json.loads(error.read()).get('error') or {}
+ except ValueError:
+ problem = {}
+ raise ApiError(error.code, problem.get('code', 'asset_unavailable'),
+ problem.get('message', 'The library asset could not be retrieved.'),
+ dict(details=[], next='GET /freevideo/agent/v1/library and use an existing asset ID.',
+ retryable=False) | {k: v for k, v in problem.items() if k not in ('code', 'message')}) from None
+ except urllib.error.URLError:
+ raise ApiError(0, 'unreachable', 'The FreeVideo server could not be reached.',
+ dict(details=[], next='Start FreeVideo, then retry the asset download.', retryable=True)) from None
+ return target
diff --git a/freevideo_engine/agent/comfy.py b/freevideo_engine/agent/comfy.py
new file mode 100644
index 0000000..8996f1f
--- /dev/null
+++ b/freevideo_engine/agent/comfy.py
@@ -0,0 +1,347 @@
+"""The running ComfyUI server as seen by agent jobs: its queue, history, folders and the local VLM."""
+import json
+import os
+from pathlib import Path, PurePosixPath
+import shutil
+import stat
+from urllib.parse import urlencode
+import uuid
+
+from . import spec as specs
+from .jobs import JobError
+
+
+class Request:
+ """Just enough of an aiohttp request for ComfyUI's own POST /prompt handler."""
+ method, path, content_type, query, match_info = 'POST', '/prompt', 'application/json', {}, {}
+
+ def __init__(self, body):
+ from multidict import CIMultiDict, CIMultiDictProxy
+ self.body = body
+ self.headers = CIMultiDictProxy(CIMultiDict({'Content-Type': 'application/json'}))
+
+ async def json(self):
+ return self.body
+
+
+class ComfyPort:
+ def __init__(self, server):
+ import folder_paths
+ self.server = server
+ self.folders = folder_paths
+ self.handler = None
+
+ # Folders -------------------------------------------------------------------------------------------
+ @property
+ def input_root(self):
+ return Path(self.folders.get_input_directory()).resolve()
+
+ @property
+ def output_root(self):
+ return Path(self.folders.get_output_directory()).resolve()
+
+ def _inside(self, root, relative, create):
+ parts = PurePosixPath(relative).parts
+ if not relative or PurePosixPath(relative).is_absolute() or '..' in parts or '\\' in relative or ':' in relative:
+ raise JobError('invalid_media', 'Not a relative path: %s' % relative)
+ path = (root / relative).resolve()
+ if not path.is_relative_to(root):
+ raise JobError('invalid_media', 'Path leaves the folder: %s' % relative)
+ if create:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ return path
+
+ def input_path(self, relative, create=False):
+ return self._inside(self.input_root, relative, create)
+
+ def output_path(self, relative, create=False):
+ return self._inside(self.output_root, relative, create)
+
+ def output_relative(self, path):
+ return Path(path).resolve().relative_to(self.output_root).as_posix()
+
+ def library_video(self, identity):
+ from ..comfy_library import _video, _report
+ try:
+ path = _video(self.output_root, identity)
+ info = path.stat()
+ if not stat.S_ISREG(info.st_mode) or not info.st_size:
+ raise ValueError('Video is not a nonempty regular file')
+ _report(path)
+ except (OSError, ValueError):
+ raise JobError('invalid_media', 'No finished saved video %s' % identity) from None
+ return path
+
+ def file_view(self, relative, kind='output'):
+ from .assets import view
+ return view(relative, kind)
+
+
+ def chain_runner(self):
+ from ..comfy_chain import RUNNER
+ return RUNNER
+
+ async def capability_view(self, query):
+ from ..comfy_capabilities import _query
+ from ..capabilities import UNAVAILABLE
+ key = _query(query)
+ cache = getattr(self.server, '_freevideo_capabilities', None)
+ if not hasattr(cache, 'get'):
+ return dict(UNAVAILABLE)
+ try:
+ await cache.check()
+ return cache.get(key)
+ except Exception:
+ cache._log_once()
+ return dict(UNAVAILABLE)
+
+ def capability_snapshot(self, query):
+ from ..comfy_capabilities import _query
+ from ..capabilities import UNAVAILABLE
+ cache = getattr(self.server, '_freevideo_capabilities', None)
+ return cache.get(_query(query)) if hasattr(cache, 'get') else dict(UNAVAILABLE)
+
+ def output_summary(self, relative):
+ from .jobs import library_id
+ from ..comfy_library import _report
+ from ..comfy_assets import output_summary
+ path = self.library_video(library_id(relative))
+ if path != self.output_path(relative):
+ raise ValueError('Invalid library output')
+ report = _report(path)
+ summary = output_summary(report, Path(relative))
+ if report.get('result_cache_hit') is not None:
+ summary['result_cache_hit'] = report['result_cache_hit']
+ return summary
+
+ # Checks at submission (fast; files are checked again when the job starts) --------------------------------
+ def check(self, spec):
+ from .schema import diagnostic, editor_issues
+ errors = []
+ names = set(self.folders.get_filename_list('loras')) if spec.get('loras') else set()
+ for i, row in enumerate(spec.get('loras', [])):
+ if row['name'] not in names:
+ errors.append(diagnostic('/loras/%d/name' % i, 'an installed LoRA listed by GET /freevideo/agent/v1', row['name']))
+ def walk(value, pointer=''):
+ if isinstance(value, list):
+ for i, row in enumerate(value):
+ walk(row, pointer + '/' + str(i))
+ elif isinstance(value, dict):
+ source = None
+ for key in ('file', 'path', 'library'):
+ if key in value:
+ try:
+ source = (self.input_path(value[key]) if key == 'file' else
+ self.library_video(value[key]) if key == 'library' else Path(value[key]).expanduser())
+ if not source.is_file():
+ raise ValueError
+ except (OSError, ValueError, JobError):
+ errors.append(diagnostic(pointer + '/' + key, 'an existing uploaded input or saved library asset', value[key]))
+ if value.get('edit') is not None:
+ size = (spec.get('width', 1344), spec.get('height', 768))
+ if source is not None and source.is_file():
+ from .media import inspect
+ try:
+ info = inspect(source)
+ size = (info['width'], info['height'])
+ except (OSError, ValueError, KeyError):
+ errors.append(diagnostic(pointer, 'a readable image or video', None))
+ errors.extend(editor_issues(value['edit'], pointer + '/edit', source_size=size,
+ target=(spec.get('width', 1344), spec.get('height', 768)), resolve=self.input_path))
+ for key, child in value.items():
+ if key not in ('metadata', 'edit'):
+ walk(child, pointer + '/' + key)
+ for key in ('media', 'clips', 'questions', 'refine_from'):
+ if key in spec:
+ walk(spec[key], '/' + key)
+ if errors:
+ raise specs.SpecError(errors)
+
+ # Queue ---------------------------------------------------------------------------------------------
+ def snapshot(self):
+ running, pending = self.server.prompt_queue.get_current_queue()
+ return [row[1] for row in running], [row[1] for row in sorted(pending, key=lambda r: r[0])]
+
+ def editor_exports(self):
+ """The editor page's export queue (editor_export.register), shared so exports take turns."""
+ return getattr(self.server, '_freevideo_editor_export', None)
+
+ def queue_busy(self):
+ running, pending = self.snapshot()
+ return bool(running or pending)
+
+ def prompt_state(self, prompt_id):
+ running, pending = self.snapshot()
+ return 'running' if prompt_id in running else 'pending' if prompt_id in pending else 'missing'
+
+ def position(self, prompt_id):
+ running, pending = self.snapshot()
+ return pending.index(prompt_id) + 1 if prompt_id in pending else None
+
+ def history(self, prompt_id):
+ return self.server.prompt_queue.get_history(prompt_id=prompt_id).get(prompt_id)
+
+ def progress(self, node):
+ from ..comfy_progress import STATE
+ with STATE.lock:
+ row = STATE.rows.get(str(node))
+ return json.loads(json.dumps(row['message'])) if row else None
+
+ async def submit(self, graph, extra):
+ if self.handler is None:
+ for route in self.server.routes:
+ if getattr(route, 'method', None) == 'POST' and getattr(route, 'path', None) == '/prompt':
+ self.handler = route.handler
+ if self.handler is None:
+ raise JobError('unsupported_comfyui', 'This ComfyUI has no POST /prompt route')
+ prompt_id = str(uuid.uuid4())
+ value = dict(prompt=graph, prompt_id=prompt_id, extra_data=extra)
+ try:
+ response = await self.handler(Request(value))
+ status, body = response.status, json.loads(response.text or '{}')
+ except (AttributeError, TypeError):
+ # A newer handler reads more of the request: post to this server instead.
+ status, body = await self.post_prompt(value)
+ if status != 200:
+ error = body.get('error') or {}
+ messages = [row.get('message') or row.get('details') for node in (body.get('node_errors') or {}).values()
+ for row in node.get('errors', [])]
+ message = '; '.join(m for m in messages if m) or error.get('message') or 'ComfyUI rejected the request'
+ details = [row.get('details') for node in (body.get('node_errors') or {}).values()
+ for row in node.get('errors', []) if row.get('details')]
+ not_ready = any('setup' in (m or '').lower() or 'install' in (m or '').lower() for m in messages + details)
+ raise JobError('not_ready' if not_ready else 'invalid_request',
+ '; '.join(d for d in details if d) or message)
+ return body.get('prompt_id', prompt_id)
+
+ async def post_prompt(self, value):
+ import aiohttp
+ from comfy.cli_args import args
+ host = (args.listen or '127.0.0.1').split(',')[0]
+ host = '127.0.0.1' if host in ('0.0.0.0', '') else '::1' if host == '::' else host
+ scheme = 'https' if getattr(args, 'tls_keyfile', None) else 'http'
+ url = '%s://%s:%d/prompt' % (scheme, '[%s]' % host if ':' in host else host, args.port)
+ async with aiohttp.ClientSession() as session:
+ async with session.post(url, json=value, ssl=False) as response:
+ return response.status, await response.json(content_type=None)
+
+ def cancel(self, prompt_id, node):
+ import nodes
+ from ..comfy_progress import cancel_request
+ return cancel_request(self.server.prompt_queue, prompt_id, node, nodes.interrupt_processing)
+
+ def generation_error(self, history, node):
+ messages = (history.get('status') or {}).get('messages') or []
+ text = None
+ for kind, data in messages:
+ if kind == 'execution_interrupted':
+ return dict(code='cancelled', message='Cancelled')
+ if kind == 'execution_error':
+ text = str(data.get('exception_message') or data.get('exception_type') or '').strip()
+ error = dict(code='generation_failed', message=(text or 'The generation did not finish')[:4000])
+ run = self.run_output(node)
+ if run is not None:
+ error['run'] = self.output_relative(run.parent)
+ report = _read(run.with_suffix('.request.json'))
+ engine = _read(run.with_suffix('.engine.json'))
+ if report.get('resource_error'):
+ details = report['resource_error'] if isinstance(report['resource_error'], dict) else {}
+ error.update(code='insufficient_memory', retryable=False,
+ alternatives=(details.get('details') or details).get('alternatives') or [])
+ failure = engine.get('failure') or {}
+ if failure.get('kind') in ('gpu_oom', 'ram_pressure'):
+ error.update(code='out_of_memory', retryable=True)
+ elif failure.get('kind'):
+ error.setdefault('failure_kind', failure['kind'])
+ debug = run.with_suffix('.debug.json')
+ if debug.is_file():
+ error['report'] = self.file_view(self.output_relative(debug))
+ return error
+
+ def run_output(self, node):
+ from ..comfy_progress import REPORTS
+ message = self.progress(node) or {}
+ with REPORTS.lock:
+ path = REPORTS.runs.get(message.get('report_id'))
+ return path
+
+ # Local VLM -----------------------------------------------------------------------------------------
+ @property
+ def vlm(self):
+ service = getattr(self.server, '_freevideo_prompt_vlm', None)
+ if service is None:
+ raise JobError('vlm_unavailable', 'The prompt VLM service is not loaded')
+ return service
+
+ def vlm_busy(self):
+ service = getattr(self.server, '_freevideo_prompt_vlm', None)
+ return service is not None and service.busy()
+
+ def vlm_start(self, action, value):
+ try:
+ return self.vlm.start(action, value)['job']
+ except ValueError as error:
+ from .jobs import VLM_ERRORS
+ code = str(error) if str(error) in VLM_ERRORS or str(error).isidentifier() else 'invalid_request'
+ raise JobError(code, VLM_ERRORS.get(code, str(error)), retryable=code == 'busy') from None
+
+ def vlm_status(self, key):
+ return self.vlm.status(key)
+
+ def vlm_cancel(self, key):
+ try:
+ self.vlm.cancel(key)
+ except ValueError:
+ pass
+
+ # Media tools ---------------------------------------------------------------------------------------
+ def import_file(self, source, target):
+ from ..comfy_assets import media_kind
+ media_kind(source.name)
+ if source.stat().st_size > 2 * 1024 ** 3:
+ raise JobError('invalid_media', 'Media files are limited to 2 GiB')
+ try:
+ os.link(source, target)
+ except OSError:
+ shutil.copyfile(source, target)
+
+ def extract_frame(self, video, out, at):
+ from . import media
+ try:
+ return media.extract_frame(video, out, at=at)
+ except ValueError as error:
+ raise JobError('invalid_media', str(error)) from None
+
+ def sample_frames(self, video, out_dir, count):
+ from . import media
+ return media.sample_frames(video, out_dir, count=count)
+
+ def edit(self, source, recipe, out, target=None):
+ """Render a recipe (or an editor document) of the input file `source`; keep the document beside it."""
+ from . import edit
+ from PIL import Image, ImageOps
+ resolve = lambda name: self.input_path(name)
+ try:
+ if recipe.get('version') == 2 and 'layers' in recipe:
+ doc = recipe
+ else:
+ with Image.open(resolve(source)) as image:
+ size = ImageOps.exif_transpose(image).size
+ doc = edit.compile_recipe(recipe, source=source, source_size=size, target=target, resolve=resolve)
+ made = edit.save(doc, resolve, out)
+ except edit.EditError as error:
+ raise JobError('invalid_edit', str(error), path=getattr(error, 'path', None)) from None
+ out.with_suffix('.edit.json').write_text(json.dumps(doc), encoding='utf-8')
+ return dict(width=made['width'], height=made['height'], doc=doc)
+
+ def assemble(self, clips, out, **options):
+ from . import media
+ return media.assemble(clips, out, **options)
+
+
+def _read(path):
+ try:
+ value = json.loads(Path(path).read_text(encoding='utf-8'))
+ return value if isinstance(value, dict) else {}
+ except (OSError, ValueError):
+ return {}
diff --git a/freevideo_engine/agent/drama.py b/freevideo_engine/agent/drama.py
new file mode 100644
index 0000000..e5631d7
--- /dev/null
+++ b/freevideo_engine/agent/drama.py
@@ -0,0 +1,571 @@
+"""A screenplay in, a finished short drama out: the reference director loop for agents.
+
+ ./freevideo agent drama plan film.json # preview prompts and take counts
+ ./freevideo agent drama start film.json # start a durable film
+ ./freevideo agent drama get ID --since 1 --wait 25
+ ./freevideo agent drama sheet ID SHOT # review the takes of one shot
+ ./freevideo agent drama choose ID SHOT --take 2
+ ./freevideo agent drama reshoot ID SHOT --note "..."
+ ./freevideo agent drama finish ID # join the chosen takes
+ ./freevideo agent drama cancel ID
+
+The screenplay is structured (characters, shots, lines), so a planner model only
+has to decide what happens. This module writes the H3 prompts, links shots that
+continue each other, asks the local VLM to score every shot against its own
+description, retakes weak shots with new seeds (with the shots that continue
+from them), keeps the best take of each and assembles the cut.
+"""
+import json
+import re
+import time
+
+from . import spec as specs
+
+EXAMPLE = {
+ 'title': '末班车', 'name': 'the-last-train', 'aspect': '9:16', 'quality': 'light',
+ 'style': 'Live-action, cinematic, rainy night in a modern Chinese city, teal and amber light',
+ 'characters': {'lin': {'name': 'the young woman', 'look': 'in her twenties with shoulder-length black hair, a '
+ 'mustard-yellow raincoat over a white shirt, carrying a small brown leather suitcase',
+ 'voice': 'soft, clear'}},
+ 'shots': [
+ {'id': 'platform', 'seconds': 6, 'framing': 'vertical medium-wide shot of an empty elevated platform',
+ 'action': 'Lin runs in through shallow puddles and stops under a flickering lamp, catching her breath and '
+ 'looking up at the departure board.', 'camera': 'The camera tracks her with small amplitude, then '
+ 'holds still.', 'lines': [{'who': 'lin', 'line': '还来得及吗?', 'how': 'says breathlessly'}],
+ 'sound': 'Heavy rain on the platform roof, splashing footsteps, the buzz of the lamp.'},
+ {'id': 'arrival', 'seconds': 6, 'continue': True, 'framing': 'vertical medium close-up',
+ 'action': 'A train headlight sweeps across Lin\'s face; the wind of the arriving train lifts her wet hair and '
+ 'her worry turns into a relieved smile.', 'camera': 'The camera pushes in slowly toward her face.',
+ 'lines': [{'who': 'lin', 'line': '来了。', 'how': 'says quietly'}],
+ 'sound': 'A rising rumble and screech of brakes, a rush of wind, a pneumatic hiss.'},
+ {'id': 'window', 'seconds': 6, 'framing': 'vertical medium shot inside a night subway car',
+ 'action': 'Lin sits by the rain-streaked window with the suitcase on her knees, watching city lights '
+ 'slide past.', 'camera': 'The camera pushes in slowly to her profile.',
+ 'lines': [{'who': 'lin', 'line': '再见了。', 'how': 'says softly'}],
+ 'sound': 'The hum of the subway, rain tapping on glass.'},
+ ],
+ 'music': 'A sparse, slow piano figure over soft sustained strings.',
+ 'review': {'min_score': 7, 'retakes': 1, 'frames': 6},
+ 'transition': 'crossfade', 'transition_seconds': .4,
+}
+
+
+class Screenplay(ValueError):
+ """All validation problems; the string remains the first legacy message."""
+ def __init__(self, problems):
+ self.problems = problems if isinstance(problems, list) else [{'path': '', 'message': problems}]
+ super().__init__(self.problems[0]['message'])
+
+
+CAPTIONED = 3 # the score of a take with unwanted captions
+CARD = re.compile(r'c[0-9a-f]{12}') # characters.<key>.card names a cast library card
+# How a shot carries its cast cards. Change these after the reference tests; nothing else needs to.
+PICTURE_ORDER = ('sheet', 'front', 'three_quarter', 'face') # then any other label, in card order
+PICTURES_EACH = 3
+MAX_VOICES = 3 # voice clips per shot, the model limit
+MAX_REFERENCES = 32
+
+
+def check(play):
+ """Validate every independent field, mutating only missing shot ids."""
+ problems = []
+
+ def problem(path, message):
+ problems.append(dict(path=path, message=message))
+
+ def validate(function, *args, **kwargs):
+ try:
+ function(*args, **kwargs)
+ except specs.SpecError as error:
+ problems.extend(error.errors)
+ except (TypeError, ValueError, OverflowError):
+ problem(args[1] if len(args) > 1 else '', 'must contain valid JSON field values')
+
+ if not isinstance(play, dict) or not isinstance(play.get('shots'), list) or not 1 <= len(play['shots']) <= 40:
+ problem('/shots', 'A screenplay needs 1 to 40 shots')
+ if not isinstance(play, dict):
+ raise Screenplay(problems)
+ characters = play.get('characters', {})
+ if not isinstance(characters, dict):
+ problem('/characters', 'must be an object')
+ characters = {}
+ for key, person in characters.items():
+ path = '/characters/' + str(key).replace('~', '~0').replace('/', '~1')
+ if not isinstance(key, str) or not key:
+ problem(path, 'character names must be non-empty strings')
+ elif '\x00' in key:
+ problem(path, 'character names cannot contain NUL')
+ if not isinstance(person, dict):
+ problem(path, 'must be an object')
+ continue
+ for field in ('name', 'look', 'voice', 'language'):
+ if field in person:
+ validate(specs._text, person[field], path + '/' + field, 20000, empty=True)
+ if 'card' in person and (not isinstance(person['card'], str) or not CARD.fullmatch(person['card'])):
+ problem(path + '/card', 'must be a cast card ID like c0123456789ab')
+ for field in ('title', 'style', 'music', 'language'):
+ if field in play:
+ validate(specs._text, play[field], '/' + field, 20000, empty=True)
+ if 'name' in play and (not isinstance(play['name'], str) or not specs.SLUG.fullmatch(play['name'])):
+ problem('/name', 'must be a short project name')
+ if 'captions' in play:
+ validate(specs._bool, play['captions'], '/captions')
+ if 'quality' in play and (not isinstance(play['quality'], str) or play['quality'] not in specs.QUALITY):
+ problem('/quality', 'must be one of ' + ', '.join(specs.QUALITY))
+ # Check aspect and megapixels independently before their combined canvas.
+ if 'aspect' in play:
+ aspect = play['aspect']
+ match = re.fullmatch(r'(\d{1,3}):(\d{1,3})', aspect) if isinstance(aspect, str) else None
+ if not match or not int(match[1]) or not int(match[2]):
+ problem('/aspect', 'must be like "16:9", "9:16" or "1:1"')
+ if 'megapixels' in play:
+ validate(specs._number, play['megapixels'], '/megapixels', .1, 16)
+ if not any(p['path'] in ('/aspect', '/megapixels') for p in problems):
+ validate(specs.canvas_size, {key: play[key] for key in ('aspect', 'megapixels') if key in play})
+ if 'seconds' in play:
+ validate(specs._number, play['seconds'], '/seconds', 1.625, 60.)
+ names = set()
+ for i, shot in enumerate(play.get('shots', []) if isinstance(play.get('shots'), list) else []):
+ path = '/shots/%d' % i
+ if not isinstance(shot, dict):
+ problem(path, '/shots/%d must be an object' % i)
+ continue
+ shot.setdefault('id', 'shot-%d' % (i + 1))
+ if not isinstance(shot['id'], str) or not specs.SLUG.fullmatch(shot['id']) or shot['id'] in names:
+ problem(path + '/id', '/shots/%d/id must be a unique short name' % i)
+ if isinstance(shot['id'], str):
+ names.add(shot['id'])
+ if not any(isinstance(shot.get(key), str) and shot[key].strip() for key in ('action', 'idea', 'prompt')):
+ problem(path, '/shots/%d needs action, idea or prompt' % i)
+ if shot.get('continue') and i == 0:
+ problem(path + '/continue', '/shots/0 cannot continue a previous shot')
+ if 'continue' in shot:
+ validate(specs._bool, shot['continue'], path + '/continue')
+ for field in ('action', 'idea', 'prompt', 'camera', 'framing', 'sound', 'music'):
+ if field in shot:
+ validate(specs._text, shot[field], path + '/' + field, 20000, empty=True)
+ for field, low, high in (('takes', 1, 8), ('seed', 0, specs.MAX_SEED)):
+ if field in shot:
+ validate(specs._int, shot[field], path + '/' + field, low, high)
+ if 'seconds' in shot:
+ validate(specs._number, shot['seconds'], path + '/seconds', 1.625, 60.)
+ modes = int(shot.get('first') is not None) + int(bool(shot.get('continue'))) + int('references' in shot)
+ if modes > 1:
+ problem(path, 'first, continue and references are mutually exclusive')
+ # Continuing a shot, or one longer than one 15 s block, needs two-pass text generation.
+ seconds = shot.get('seconds', play.get('seconds'))
+ long = isinstance(seconds, (int, float)) and not isinstance(seconds, bool) and seconds > 15
+ if ((shot.get('continue') or long) and play.get('quality') in specs.QUALITY
+ and not specs.QUALITY[play['quality']][0] and all(p['path'] != '/quality' for p in problems)):
+ problem('/quality', '"light" (two-pass) when a shot continues another or is longer than 15 s')
+ if long and (shot.get('first') is not None or 'references' in shot):
+ problem(path + '/seconds', 'at most 15 with a first frame or references')
+ elif long and not shot.get('continue') and _carded(play, shot):
+ # Cast cards travel as references, which one generation of at most 15 s carries.
+ problem(path + '/seconds', 'at most 15 when a character in the shot has a cast card '
+ '(a following shot with continue=true carries the same people further)')
+ if shot.get('first') is not None:
+ validate(specs.media_item, shot['first'], path + '/first', image=True)
+ if 'references' in shot:
+ refs = shot['references']
+ if not isinstance(refs, list) or len(refs) > 32:
+ problem(path + '/references', 'must be a list of at most 32 items')
+ if isinstance(refs, list):
+ for j, ref in enumerate(refs):
+ validate(specs.media_item, ref, path + '/references/%d' % j)
+ if 'cast' in shot:
+ if not isinstance(shot['cast'], list):
+ problem(path + '/cast', 'must be a list of character names')
+ else:
+ for j, key in enumerate(shot['cast']):
+ if not isinstance(key, str) or key not in characters:
+ problem(path + '/cast/%d' % j, 'must name a character')
+ lines = shot.get('lines', [])
+ if not isinstance(lines, list):
+ problem(path + '/lines', 'must be a list')
+ continue
+ for j, line in enumerate(lines):
+ line_path = path + '/lines/%d' % j
+ if not isinstance(line, dict):
+ problem(line_path, 'must be an object')
+ continue
+ if not isinstance(line.get('who'), str) or line['who'] not in characters:
+ problem(line_path + '/who', '/shots/%d/lines/%d/who must name a character' % (i, j))
+ validate(specs._text, line.get('line'), line_path + '/line', 20000)
+ for field in ('how', 'language'):
+ if field in line:
+ validate(specs._text, line[field], line_path + '/' + field, 20000, empty=True)
+ if problems:
+ raise Screenplay(problems)
+ return play
+
+
+def cast(play, shot):
+ """Characters in this shot, speakers first, in order of appearance."""
+ order = [line['who'] for line in shot.get('lines', [])]
+ order += [key for key in play.get('characters', {}) if key in (shot.get('cast') or [])
+ or play['characters'][key].get('name', key).lower() in shot.get('action', '').lower()
+ or key.lower() in shot.get('action', '').lower()]
+ return list(dict.fromkeys(order))
+
+
+def _carded(play, shot):
+ """Whether check() can already see a cast card on someone in this shot; malformed fields are reported elsewhere."""
+ try:
+ return any(isinstance(play['characters'][key].get('card'), str) for key in cast(play, shot))
+ except (AttributeError, KeyError, TypeError):
+ return False
+
+
+SHOWN_TEXT = re.compile(r'["“「][^"”」]+["”」]')
+
+
+def prompt(play, shot):
+ """The H3 prompt of one shot, from its structured fields."""
+ if shot.get('prompt'):
+ return shot['prompt']
+ characters = play.get('characters', {})
+ people = cast(play, shot)
+ lead = ', '.join(x for x in (play.get('style'), shot.get('framing')) if x)
+ parts = ['[Shot 1] ' + (lead + '.' if lead else '')]
+ if shot.get('continue'):
+ parts.append('Continuing from the opening frame, the scene keeps its exact layout, lighting and characters.')
+ for key in people:
+ person = characters[key]
+ if person.get('look'):
+ parts.append('%s is %s.' % ((person.get('name') or key).capitalize(), person['look'].rstrip('.')))
+ parts.append(named(play, people, shot.get('action', '')))
+ if shot.get('camera'):
+ parts.append(shot['camera'])
+ speakers = {}
+ for line in shot.get('lines', []):
+ who = line['who']
+ person = characters[who]
+ first = who not in speakers
+ speakers.setdefault(who, len(speakers) + 1)
+ voice = (' with a %s voice' % person['voice']) if first and person.get('voice') else ''
+ language = line.get('language') or person.get('language') or play.get('language') or guess(line['line'])
+ parts.append('%s%s (S%d) %s: <d>[%s] %s</d>' % ((person.get('name') or who).capitalize(), voice,
+ speakers[who], line.get('how') or 'says', language, line['line']))
+ if not play.get('captions'):
+ # Quoted words are text the shot shows (a sign, a menu); then only captions are ruled out.
+ scene = ' '.join(shot.get(k) or '' for k in ('framing', 'action', 'camera')) + ' ' + (play.get('style') or '')
+ parts.append('No subtitles or captions.' if SHOWN_TEXT.search(scene) else 'No subtitles, no on-screen text.')
+ sound = shot.get('sound') or 'Natural ambience of the scene.'
+ music = shot.get('music') or play.get('music') or 'N/A'
+ return ('integrated_multimodal_description: ' + ' '.join(p for p in parts if p) +
+ '\n\noverall_soundscape: ' + sound + '\n\nnon_diegetic_music: ' + music)
+
+
+def subject_definitions(subjects):
+ """The prompt prefix tying cast cards to their reference tags; the one place its wording lives.
+
+ subjects: [{'name', 'description', 'pictures': (first, last) or None, 'audio': number or None}]."""
+ parts = []
+ for number, subject in enumerate(subjects, 1):
+ text = '<Subject %d> is %s' % (number, subject['name'])
+ description = (subject.get('description') or '').strip().rstrip('.')
+ text += (': %s.' % description) if description else '.'
+ tags = []
+ if subject.get('pictures'):
+ first, last = subject['pictures']
+ pictures = '<Picture %d>' % first if first == last else '<Picture %d> to <Picture %d>' % (first, last)
+ tags.append('%s show%s its appearance' % (pictures, 's' if first == last else ''))
+ if subject.get('audio'):
+ tags.append('<Audio %d> is its voice' % subject['audio'])
+ if tags:
+ text += ' ' + '; '.join(tags) + '.'
+ parts.append(text)
+ return 'subject_definitions: ' + ' '.join(parts)
+
+
+def _pictures(card):
+ rank = {label: i for i, label in enumerate(PICTURE_ORDER)}
+ rows = sorted(enumerate(card.get('images') or []), key=lambda r: (rank.get(r[1]['label'], len(rank)), r[0]))
+ return [row['media'] for _, row in rows[:PICTURES_EACH]]
+
+
+def cast_references(play, shot, cards, *, continues=False):
+ """Which cast cards a shot carries, as references and a prompt prefix.
+
+ cards maps a card ID to the current card, or None once it is gone. The same
+ function serves plan previews and the moment a take is submitted.
+ cast_reference: None (no character in the shot has a card), 'inherited'
+ (continues the previous shot), 'own' (the shot names its own first frame or
+ references), 'missing' (a card was deleted), 'partial' (not everyone fit)
+ or 'cards'. 'omitted' lists people left out entirely; 'voice_omitted' lists
+ people whose pictures are carried but whose voice did not fit."""
+ characters = play.get('characters', {})
+ keys = [k for k in cast(play, shot) if isinstance(characters[k].get('card'), str)]
+ result = dict(cast_reference=None, people=[], omitted=[], voice_omitted=[], missing=[], references=[],
+ prefix=None, subjects=[], cards={})
+ if not keys:
+ return result
+ if continues:
+ result['cast_reference'] = 'inherited'
+ return result
+ if shot.get('first') is not None or 'references' in shot:
+ result['cast_reference'] = 'own'
+ return result
+ spoken = {}
+ for line in shot.get('lines', []):
+ spoken[line['who']] = spoken.get(line['who'], 0) + 1
+ # People with more lines come first when not everyone fits; ties keep the order of appearance.
+ chosen, pictures, voices = [], 0, 0
+ for key in sorted(keys, key=lambda k: -spoken.get(k, 0)):
+ identity = characters[key]['card']
+ card = cards.get(identity)
+ if card is None:
+ result['missing'].append(key)
+ continue
+ images = _pictures(card)
+ voice = card.get('voice') is not None and voices < MAX_VOICES
+ if pictures + len(images) + voices + voice > MAX_REFERENCES:
+ result['omitted'].append(key)
+ continue
+ if card.get('voice') is not None and not voice:
+ result['voice_omitted'].append(key) # shown, without the voice that did not fit
+ pictures, voices = pictures + len(images), voices + voice
+ chosen.append((key, card, images, voice))
+ chosen.sort(key=lambda row: keys.index(row[0]))
+ subjects, clips, picture = [], [], 0
+ for key, card, images, voice in chosen:
+ result['cards'][card['id']] = card['revision']
+ result['references'].extend(dict(item) for item in images)
+ if voice:
+ clips.append(dict(card['voice']['clip']))
+ person = characters[key]
+ subject = dict(name=person.get('name') or key, description=card.get('description'),
+ pictures=(picture + 1, picture + len(images)) if images else None,
+ audio=len(clips) if voice else None)
+ picture += len(images)
+ if images or voice:
+ subjects.append(subject)
+ result['people'].append(dict(character=key, card=card['id'], revision=card['revision'],
+ pictures=len(images), voice=voice))
+ result['references'].extend(clips)
+ if subjects:
+ result['prefix'] = subject_definitions(subjects)
+ result['subjects'] = subjects
+ result['cast_reference'] = ('missing' if result['missing'] else
+ 'partial' if result['omitted'] or result['voice_omitted'] else 'cards')
+ return result
+
+
+PROMPT_LIMIT = 20000
+DESCRIPTION_CUTS = (500, 250, 120, 0)
+
+
+def with_cast(text, resolved, *, limit=PROMPT_LIMIT):
+ """The submitted prompt: the subject definitions, then the shot's own prompt.
+
+ Cards can grow after a plan; when the whole prompt would pass the limit, the card descriptions are
+ shortened (the pictures still show each person). Plan previews and submissions both call this."""
+ if not resolved.get('prefix'):
+ return text
+ full = resolved['prefix'] + '\n\n' + text
+ if len(full) <= limit or not resolved.get('subjects'):
+ return full
+ for cut in DESCRIPTION_CUTS:
+ subjects = [dict(s, description=(s.get('description') or '')[:cut].rstrip() or None)
+ for s in resolved['subjects']]
+ short = subject_definitions(subjects) + '\n\n' + text
+ if len(short) <= limit:
+ return short
+ return full # Too long even without descriptions: the prompt check reports it.
+
+
+def named(play, people, text):
+ """Screenplays use short names; prompts and the reviewer see the full description's name."""
+ for key in people:
+ name = play.get('characters', {})[key].get('name')
+ if name and key.lower() != name.lower():
+ text = text.replace(key.capitalize(), name.capitalize() if text.startswith(key.capitalize())
+ else name).replace(key, name)
+ return text
+
+
+def guess(text):
+ if any('぀' <= c <= 'ヿ' for c in text):
+ return 'Japanese'
+ if any('가' <= c <= '힯' for c in text):
+ return 'Korean'
+ if any('一' <= c <= '鿿' for c in text):
+ return 'Chinese'
+ return 'English'
+
+
+def intent(play, shot):
+ """What the shot should show, in plain words, for the reviewer."""
+ lines = ' '.join('%s says "%s".' % (play['characters'][l['who']].get('name', l['who']), l['line'])
+ for l in shot.get('lines', []))
+ looks = ' '.join('%s: %s.' % (play['characters'][k].get('name', k), play['characters'][k].get('look', ''))
+ for k in cast(play, shot))
+ action = named(play, cast(play, shot), shot.get('action') or shot.get('idea') or '')
+ return ' '.join(x.strip().rstrip('.') + '.' for x in (shot.get('framing'), action,
+ shot.get('camera'), lines, looks) if x and x.strip())
+
+
+def shot_job(play, shot, index, ref):
+ job = dict(ref=ref, label='%s · %s' % (play.get('title') or 'drama', shot['id']), project=play.get('name'),
+ aspect=play.get('aspect', '9:16'), quality=play.get('quality', 'light'),
+ seconds=shot.get('seconds', play.get('seconds', 6)), metadata={'drama_shot': shot['id']})
+ if play.get('megapixels'):
+ job['megapixels'] = play['megapixels']
+ if shot.get('seed') is not None:
+ job['seed'] = shot['seed']
+ if shot.get('idea') and not shot.get('action') and not shot.get('prompt'):
+ job['prompt'] = {'from_job': '@%s-idea' % ref}
+ else:
+ job['prompt'] = prompt(play, shot)
+ if shot.get('continue'):
+ job['media'] = {'first': {'from_job': '@s%d' % (index - 1), 'frame': 'last'}}
+ elif shot.get('first'):
+ job['media'] = {'first': shot['first']}
+ return job
+
+
+def review_job(play, refs, ref='review'):
+ """One VLM job (one model load) scoring every listed shot against its intent."""
+ frames = play.get('review', {}).get('frames', 6)
+ questions = []
+ for shot, shot_ref in refs:
+ questions.append({'text': 'These frames are from one shot of a short drama. The shot should show: %s '
+ 'Score 0-10 how well the frames match this and how good the shot looks (faces, hands, '
+ 'motion, consistent character appearance). Also say whether any subtitle, caption or '
+ 'other text is drawn over the picture (signs and screens in the scene do not count). '
+ 'Answer only JSON {"score": integer, "captions": boolean, "issues": [string]}.'
+ % intent(play, shot),
+ 'video': {'from_job': shot_ref, 'frames': frames}})
+ return dict(ref=ref, kind='vlm', format='json', max_tokens=300, label='%s · review' % (play.get('title') or 'drama'),
+ project=play.get('name'), questions=questions)
+
+
+def batch(play):
+ """The whole first pass as one batch: ideas, shots, one review."""
+ check(play)
+ rows = []
+ for i, shot in enumerate(play['shots']):
+ if shot.get('idea') and not shot.get('action') and not shot.get('prompt'):
+ rows.append(dict(ref='s%d-idea' % i, kind='enhance', text=shot['idea'],
+ seconds=shot.get('seconds', play.get('seconds', 6)), project=play.get('name'),
+ label='%s · %s idea' % (play.get('title') or 'drama', shot['id'])))
+ rows.append(shot_job(play, shot, i, 's%d' % i))
+ rows.append(review_job(play, [(shot, '@s%d' % i) for i, shot in enumerate(play['shots'])]))
+ return rows
+
+
+def run(client, play, *, log=print):
+ """Generate, review, retake weak shots, assemble; returns a report."""
+ started = time.monotonic()
+ rows = batch(play)
+ made = client.batch(rows)
+ ids = {row['ref']: job['id'] for row, job in zip(rows, made)}
+ shots = play['shots']
+ takes = {i: [ids['s%d' % i]] for i in range(len(shots))}
+ # Which take of the previous shot each take of a continuing shot starts from.
+ parents = {ids['s%d' % i]: ids['s%d' % (i - 1)] for i in range(1, len(shots)) if shots[i].get('continue')}
+ scores = {}
+ log('submitted %d jobs' % len(made))
+
+ def score(review_id, refs):
+ view = client.wait(review_id)
+ answers = (view.get('result') or {}).get('answers') or []
+ if len(answers) != len(refs):
+ # A failed review is not a bad review: leave these takes unscored instead of retaking them.
+ log('review %s: %s, %d of %d answers; takes stay unscored' % (review_id, view.get('status'),
+ len(answers), len(refs)))
+ for (i, job), answer in zip(refs, answers):
+ value = (answer.get('json') or {}).get('score')
+ scores[job] = value if isinstance(value, (int, float)) else None
+ # H3 sometimes draws spoken lines as captions even when told not to; a new seed usually avoids it.
+ if not play.get('captions') and (answer.get('json') or {}).get('captions') is True and scores[job]:
+ scores[job] = min(scores[job], CAPTIONED)
+ answer['json'].setdefault('issues', []).insert(0, 'captions drawn on the picture')
+ log('shot %s take %s: score %s %s' % (shots[i]['id'], job, scores[job],
+ '; '.join((answer.get('json') or {}).get('issues') or [])[:200]))
+ for i in range(len(shots)):
+ view = client.wait(ids['s%d' % i])
+ log('shot %s: %s' % (shots[i]['id'], view['status']))
+ score(ids['review'], [(i, ids['s%d' % i]) for i in range(len(shots))])
+ review = play.get('review', {})
+ for _ in range(review.get('retakes', 1)):
+ chosen = best(shots, takes, scores, parents)
+ weak = [i for i in range(len(shots)) if scores.get(chosen[i]) is not None
+ and scores[chosen[i]] < review.get('min_score', 7)]
+ if not weak:
+ break
+ # A retaken shot changes its last frame: the shots that continue from it are retaken too.
+ redo = set()
+ for i in weak:
+ redo.add(i)
+ j = i + 1
+ while j < len(shots) and shots[j].get('continue'):
+ redo.add(j)
+ j += 1
+ rows = []
+ for i in sorted(redo):
+ job = shot_job(play, dict(shots[i], seed=None), i, 'r%d' % i)
+ if shots[i].get('continue'):
+ job['media']['first']['from_job'] = ('@r%d' % (i - 1)) if i - 1 in redo else chosen[i - 1]
+ if isinstance(job['prompt'], dict):
+ job['prompt'] = {'from_job': ids['s%d-idea' % i]}
+ rows.append(job)
+ rows.append(review_job(play, [(shots[i], '@r%d' % i) for i in sorted(redo)]))
+ made = client.batch(rows)
+ new = {row['ref']: job['id'] for row, job in zip(rows, made)}
+ log('retaking %s' % ', '.join(shots[i]['id'] for i in sorted(redo)))
+ for i in sorted(redo):
+ client.wait(new['r%d' % i])
+ takes[i].append(new['r%d' % i])
+ if shots[i].get('continue'):
+ parents[new['r%d' % i]] = new['r%d' % (i - 1)] if i - 1 in redo else chosen[i - 1]
+ score(new['review'], [(i, new['r%d' % i]) for i in sorted(redo)])
+ chosen = best(shots, takes, scores, parents)
+ final = client.submit(dict(kind='assemble', clips=chosen, transition=play.get('transition', 'crossfade'),
+ transition_seconds=play.get('transition_seconds', .4), name=play.get('name') or 'drama',
+ label=play.get('title') or 'drama', project=play.get('name')))
+ final = client.wait(final['id'])
+ report = dict(title=play.get('title'), status=final['status'], video=(final.get('result') or {}).get('video'),
+ seconds=(final.get('result') or {}).get('seconds'), elapsed_seconds=time.monotonic() - started,
+ shots=[dict(id=shot['id'], takes=[dict(job=j, score=scores.get(j)) for j in takes[i]], chosen=chosen[i])
+ for i, shot in enumerate(shots)], assemble=final['id'],
+ unreviewed=[shot['id'] for i, shot in enumerate(shots) if scores.get(chosen[i]) is None])
+ return report
+
+
+def best(shots, takes, scores, parents):
+ """The takes to assemble. Shots joined by "continue" are chosen together: of the chains of takes in which
+ each take starts from the previous one, the one whose weakest take scores highest (then the highest total,
+ then the earliest)."""
+ chosen, i = [], 0
+ while i < len(shots):
+ end = i
+ while end + 1 < len(shots) and shots[end + 1].get('continue'):
+ end += 1
+ def chains(k, parent):
+ options = takes[k] if k == i else [j for j in takes[k] if parents.get(j) == parent]
+ for take in options:
+ if k == end:
+ yield [take]
+ else:
+ for rest in chains(k + 1, take):
+ yield [take] + rest
+ found = list(chains(i, None))
+ if not found: # a broken chain cannot happen through run(); keep each shot's best take
+ found = [[max(takes[k], key=lambda j: scores.get(j) or 0) for k in range(i, end + 1)]]
+ order = {take: n for k in range(i, end + 1) for n, take in enumerate(takes[k])}
+ value = lambda chain: (min(scores.get(j) or 0 for j in chain), sum(scores.get(j) or 0 for j in chain),
+ -sum(order[j] for j in chain))
+ chosen += max(found, key=value)
+ i = end + 1
+ return chosen
+
+
+def main(client, path, *, dry_run=False):
+ play = EXAMPLE if path == 'example' else json.loads(open(path, encoding='utf-8').read())
+ if dry_run:
+ return dict(prompts={shot['id']: prompt(play, shot) for shot in check(play)['shots']
+ if not (shot.get('idea') and not shot.get('action'))}, batch={'jobs': batch(play)})
+ import sys
+ return run(client, play, log=lambda text: print(text, file=sys.stderr, flush=True))
diff --git a/freevideo_engine/agent/edit.py b/freevideo_engine/agent/edit.py
new file mode 100644
index 0000000..64b26dc
--- /dev/null
+++ b/freevideo_engine/agent/edit.py
@@ -0,0 +1,1746 @@
+"""Headless image edits for agents, on the browser editor's own document.
+
+web/image_editor_engine.js and this module read the same version 2 document:
+an agent's recipe compiles to it, renders here without a browser, and a person
+can reopen the result in the editor with every layer and step in place.
+Pixels follow the browser's canvas maths (premultiplied colour, bilinear
+sampling, the same adjustment formulas and noise sequence), so a document looks
+the same saved from either side; text uses the editor's bundled fonts.
+"""
+import itertools
+import math
+from pathlib import Path
+import time
+
+import numpy as np
+from PIL import Image, ImageColor, ImageDraw, ImageFilter, ImageFont, ImageOps
+
+BLENDS = ('source-over', 'multiply', 'screen', 'overlay', 'soft-light', 'darken', 'lighten',
+ 'color-dodge', 'color-burn', 'difference')
+ADJUSTMENTS = ('exposure', 'contrast', 'highlights', 'shadows', 'temperature', 'tint', 'hue', 'saturation',
+ 'vibrance', 'sharpen', 'blur', 'noise', 'vignette')
+RANGES = dict({k: (-100, 100) for k in ADJUSTMENTS}, hue=(-180, 180), sharpen=(0, 100), blur=(0, 100), noise=(0, 100))
+# The families of web/fonts.js, bundled with FreeVideo: the browser editor draws with the same files.
+FONT_DIR = Path(__file__).resolve().parents[2] / 'web' / 'fonts'
+FONTS = {
+ 'sans': {400: 'FreeVideoSansSC-Regular.woff2', 700: 'FreeVideoSansSC-Bold.woff2'},
+ 'serif': {400: 'FreeVideoSerifSC-Regular.woff2', 700: 'FreeVideoSerifSC-Bold.woff2'},
+ 'kai': {400: 'FreeVideoKaiSC-Regular.woff2', 700: 'FreeVideoKaiSC-Medium.woff2'},
+ 'mono': {400: 'FreeVideoMonoSC-Regular.woff2', 700: 'FreeVideoMonoSC-Bold.woff2'},
+}
+FONT_BOX = 'FreeVideoBox.woff2'
+# Canvas textBaseline 'top' puts the em box's top on y: the typographic ascender
+# over ascender + descender. Every bundled face has 880 / -120 units in its OS/2
+# table; tests/test_agent_edit.py reads the files again when fontTools is present.
+EM_ASCENT = .88
+RATIOS = {'16:9': 16 / 9, '9:16': 9 / 16, '1:1': 1., '4:3': 4 / 3, '3:4': 3 / 4}
+RATIO_IDS = ('video', 'original', 'free', *RATIOS)
+ANCHORS = ('center', 'top-left', 'top', 'top-right', 'left', 'right', 'bottom-left', 'bottom', 'bottom-right')
+MAX_PIXELS = 64 * 2**20
+MAX_OPERATIONS = 64
+TOOLS = ('paint', 'erase', 'clone', 'heal', 'blur', 'hide', 'reveal')
+OPS = ('stroke', 'fill', 'clear', 'gradient', 'fromSelection')
+
+
+class EditError(ValueError):
+ """A document or recipe problem at a JSON path such as /layers/2/ops/0."""
+ def __init__(self, path, message):
+ super().__init__('%s: %s' % (path or '/', message))
+ self.path, self.message = path or '/', message
+
+
+def _round(value):
+ return math.floor(value + .5) # JavaScript's Math.round
+
+
+def _size(value):
+ return max(1, _round(value))
+
+
+# ---------------------------------------------------------------------------
+# Geometry, as DOMMatrix: each step multiplies on the right.
+
+def _t(x, y):
+ return np.array([[1., 0, x], [0, 1, y], [0, 0, 1]])
+
+
+def _s(x, y):
+ return np.array([[x, 0., 0], [0, y, 0], [0, 0, 1]])
+
+
+def _r(degrees):
+ turns = degrees / 90
+ if turns == int(turns):
+ c, s = ((1, 0), (0, 1), (-1, 0), (0, -1))[int(turns) % 4]
+ else:
+ c, s = math.cos(math.radians(degrees)), math.sin(math.radians(degrees))
+ return np.array([[c, -s, 0.], [s, c, 0], [0, 0, 1]])
+
+
+def _chain(*matrices):
+ out = np.eye(3)
+ for m in matrices:
+ out = out @ m
+ return out
+
+
+def oriented_size(doc):
+ return (doc['height'], doc['width']) if doc['rotate'] % 180 else (doc['width'], doc['height'])
+
+
+def orient_matrix(doc):
+ ow, oh = oriented_size(doc)
+ return _chain(_t(ow / 2, oh / 2), _s(-1 if doc['flipX'] else 1, -1 if doc['flipY'] else 1),
+ _r(doc['rotate']), _t(-doc['width'] / 2, -doc['height'] / 2))
+
+
+def canvas_rect(doc):
+ (ow, oh), e = oriented_size(doc), doc['extend']
+ return dict(x=-e['l'], y=-e['t'], w=ow + e['l'] + e['r'], h=oh + e['t'] + e['b'])
+
+
+def layer_matrix(layer):
+ """Layer native pixels to document pixels."""
+ return _chain(_t(layer['cx'], layer['cy']), _r(layer['rotation']),
+ _s(-1 if layer['flipX'] else 1, -1 if layer['flipY'] else 1),
+ _t(-layer['w'] / 2, -layer['h'] / 2), _s(layer['w'] / layer['nw'], layer['h'] / layer['nh']))
+
+
+def _apply(m, x, y):
+ return m[0, 0] * x + m[0, 1] * y + m[0, 2], m[1, 0] * x + m[1, 1] * y + m[1, 2]
+
+
+# ---------------------------------------------------------------------------
+# Colour and rasters: float32 premultiplied RGBA in 0..1, like a canvas.
+
+def _color(value, path='/'):
+ if value is None or value == 'transparent':
+ return (0., 0., 0., 0.)
+ try:
+ r, g, b, a = ImageColor.getcolor(str(value), 'RGBA')
+ except ValueError:
+ raise EditError(path, 'not a colour: %r' % (value,)) from None
+ return (r / 255, g / 255, b / 255, a / 255)
+
+
+def _solid(h, w, color):
+ r, g, b, a = color
+ out = np.empty((h, w, 4), np.float32)
+ out[...] = (r * a, g * a, b * a, a)
+ return out
+
+
+def _q(a):
+ """Canvas storage: 8-bit premultiplied."""
+ return np.rint(np.clip(a, 0, 1) * 255).astype(np.float32) / 255
+
+
+def _from_image(image):
+ d = np.asarray(image.convert('RGBA'), np.float32) / 255
+ d[..., :3] *= d[..., 3:]
+ return _q(d)
+
+
+def _unpremul8(a):
+ """getImageData: unpremultiplied 8-bit values."""
+ p = np.rint(np.clip(a, 0, 1) * 255)
+ alpha = p[..., 3:]
+ with np.errstate(divide='ignore', invalid='ignore'):
+ rgb = np.where(alpha > 0, np.rint(p[..., :3] * 255 / np.maximum(alpha, 1)), 0)
+ return np.concatenate([np.minimum(rgb, 255), alpha], -1)
+
+
+def _premul8(d):
+ """putImageData: premultiply unpremultiplied 8-bit values."""
+ d = np.asarray(d, np.float64)
+ out = np.empty(d.shape, np.float32)
+ out[..., :3] = np.rint(d[..., :3] * d[..., 3:] / 255) / 255
+ out[..., 3] = d[..., 3] / 255
+ return out
+
+
+def _to_image(a):
+ return Image.fromarray(_unpremul8(a).astype(np.uint8), 'RGBA')
+
+
+def _blend(name, cb, cs):
+ if name == 'multiply':
+ return cb * cs
+ if name == 'screen':
+ return cb + cs - cb * cs
+ if name == 'overlay':
+ return np.where(cb <= .5, cs * 2 * cb, 1 - (1 - cs) * (1 - (2 * cb - 1)))
+ if name == 'darken':
+ return np.minimum(cb, cs)
+ if name == 'lighten':
+ return np.maximum(cb, cs)
+ if name == 'difference':
+ return np.abs(cb - cs)
+ with np.errstate(divide='ignore', invalid='ignore'):
+ if name == 'color-dodge':
+ return np.where(cb <= 0, 0, np.where(cs >= 1, 1, np.minimum(1, cb / (1 - cs))))
+ if name == 'color-burn':
+ return np.where(cb >= 1, 1, np.where(cs <= 0, 0, 1 - np.minimum(1, (1 - cb) / cs)))
+ if name == 'soft-light':
+ d = np.where(cb <= .25, ((16 * cb - 12) * cb + 4) * cb, np.sqrt(cb))
+ return np.where(cs <= .5, cb - (1 - 2 * cs) * cb * (1 - cb), cb + (2 * cs - 1) * (d - cb))
+ raise EditError('/', 'unknown blend %r' % name)
+
+
+def _composite(dst, src, op='source-over'):
+ """Porter-Duff and separable blends of premultiplied src onto dst, in place."""
+ sa, da = src[..., 3:], dst[..., 3:]
+ if op == 'destination-out':
+ dst *= 1 - sa
+ elif op == 'destination-in':
+ dst *= sa
+ elif op == 'xor':
+ dst[...] = src * (1 - da) + dst * (1 - sa)
+ elif op == 'source-over':
+ dst[...] = src + dst * (1 - sa)
+ else:
+ with np.errstate(divide='ignore', invalid='ignore'):
+ cs = np.where(sa > 0, src[..., :3] / np.maximum(sa, 1e-12), 0)
+ cb = np.where(da > 0, dst[..., :3] / np.maximum(da, 1e-12), 0)
+ mixed = (1 - da) * cs + da * np.clip(_blend(op, cb, cs), 0, 1)
+ rgb = sa * mixed + (1 - sa) * dst[..., :3]
+ dst[..., 3:] = sa + da * (1 - sa)
+ dst[..., :3] = rgb
+
+
+def _draw(dst, src, m, alpha=1., op='source-over'):
+ """drawImage(src) under matrix m (src pixels to dst pixels): bilinear, edge
+ clamped colour and anti-aliased quad coverage, as Skia draws it."""
+ H, W = dst.shape[:2]
+ h, w = src.shape[:2]
+ xs, ys = _apply(m, np.array([0., w, w, 0]), np.array([0., 0, h, h]))
+ whole = op == 'destination-in'
+ if np.allclose(m[:2, :2], np.eye(2)) and float(m[0, 2]).is_integer() and float(m[1, 2]).is_integer():
+ ox, oy = int(m[0, 2]), int(m[1, 2])
+ x0, y0, x1, y1 = max(0, ox), max(0, oy), min(W, ox + w), min(H, oy + h)
+ piece = np.zeros((max(0, y1 - y0), max(0, x1 - x0), 4), np.float32)
+ if x1 > x0 and y1 > y0:
+ piece[...] = src[y0 - oy:y1 - oy, x0 - ox:x1 - ox]
+ else:
+ x0, x1 = max(0, math.floor(xs.min())), min(W, math.ceil(xs.max()))
+ y0, y1 = max(0, math.floor(ys.min())), min(H, math.ceil(ys.max()))
+ piece = np.zeros((max(0, y1 - y0), max(0, x1 - x0), 4), np.float32)
+ if x1 > x0 and y1 > y0:
+ gx, gy = np.meshgrid(np.arange(x0, x1) + .5, np.arange(y0, y1) + .5)
+ u, v = _apply(np.linalg.inv(m), gx, gy)
+ # Snap sampling that lands on pixel centres (turns, flips) to exact copies.
+ u, v = u - .5, v - .5
+ u = np.where(np.abs(u - np.rint(u)) < 1e-6, np.rint(u), u)
+ v = np.where(np.abs(v - np.rint(v)) < 1e-6, np.rint(v), v)
+ ix, iy = np.floor(u), np.floor(v)
+ fx, fy = (u - ix)[..., None].astype(np.float32), (v - iy)[..., None].astype(np.float32)
+ ix0, iy0 = np.clip(ix, 0, w - 1).astype(np.intp), np.clip(iy, 0, h - 1).astype(np.intp)
+ ix1, iy1 = np.clip(ix + 1, 0, w - 1).astype(np.intp), np.clip(iy + 1, 0, h - 1).astype(np.intp)
+ piece = ((src[iy0, ix0] * (1 - fx) + src[iy0, ix1] * fx) * (1 - fy)
+ + (src[iy1, ix0] * (1 - fx) + src[iy1, ix1] * fx) * fy)
+ area = np.sum(xs * np.roll(ys, -1) - np.roll(xs, -1) * ys)
+ cover = np.ones(gx.shape, np.float32)
+ for i in range(4):
+ ax, ay, bx, by = xs[i], ys[i], xs[(i + 1) % 4], ys[(i + 1) % 4]
+ length = math.hypot(bx - ax, by - ay) or 1
+ d = ((bx - ax) * (gy - ay) - (by - ay) * (gx - ax)) / length * (1 if area > 0 else -1)
+ cover *= np.clip(d + .5, 0, 1).astype(np.float32)
+ piece = piece * cover[..., None]
+ if alpha != 1:
+ piece = piece * np.float32(alpha)
+ if whole:
+ full = np.zeros_like(dst)
+ full[y0:y1, x0:x1] = piece
+ _composite(dst, full, op)
+ elif piece.size:
+ region = dst[y0:y1, x0:x1]
+ _composite(region, piece, op)
+ return dst
+
+
+def _mask_with(target, mask):
+ """destination-in with a same-size mask."""
+ target *= mask[..., 3:]
+ return target
+
+
+def _blurred(a, radius):
+ """CSS blur(radius px): a Gaussian with that standard deviation, edges
+ extended (the editor pads with edge pixels before filtering)."""
+ if radius <= 0:
+ return a.copy()
+ image = Image.fromarray(np.rint(np.clip(a, 0, 1) * 255).astype(np.uint8), 'RGBA')
+ image = Image.frombytes('RGBa', image.size, image.tobytes()).filter(ImageFilter.GaussianBlur(radius))
+ return np.frombuffer(image.tobytes(), np.uint8).reshape(a.shape).astype(np.float32) / 255
+
+
+def _blur_alpha(alpha, sigma):
+ if sigma <= 0:
+ return alpha
+ image = Image.fromarray(np.rint(np.clip(alpha, 0, 1) * 255).astype(np.uint8), 'L')
+ return np.asarray(image.filter(ImageFilter.GaussianBlur(sigma)), np.float32) / 255
+
+
+def _alpha_raster(alpha):
+ out = np.zeros(alpha.shape + (4,), np.float32)
+ out[...] = alpha[..., None]
+ return _q(out)
+
+
+# ---------------------------------------------------------------------------
+# Adjustments: the editor's formulas, step for step.
+
+def _imul(a, b):
+ return ((a.astype(np.uint64) * (b.astype(np.uint64) & 0xFFFFFFFF)) & 0xFFFFFFFF).astype(np.uint32)
+
+
+def _mulberry(seed, count):
+ """Values of the editor's mulberry32 generator, calls 1..count."""
+ k = np.arange(1, count + 1, dtype=np.uint64)
+ s = ((np.uint64(seed) + k * np.uint64(0x6D2B79F5)) & np.uint64(0xFFFFFFFF)).astype(np.uint32)
+ t = _imul(s ^ (s >> np.uint32(15)), s | np.uint32(1))
+ t = ((t.astype(np.uint64) + _imul(t ^ (t >> np.uint32(7)), t | np.uint32(61))) & 0xFFFFFFFF).astype(np.uint32) ^ t
+ return (t ^ (t >> np.uint32(14))).astype(np.float64) / 4294967296
+
+
+def hash_string(text):
+ h = 2166136261
+ for ch in str(text):
+ code = ord(ch)
+ if code > 0xFFFF:
+ code = 0xD800 + ((code - 0x10000) >> 10)
+ h = ((h ^ code) * 16777619) & 0xFFFFFFFF
+ return h
+
+
+def adjusted(raster, adjust, seed):
+ a = {k: v for k, v in (adjust or {}).items() if v}
+ if not any(a.get(k) for k in ADJUSTMENTS):
+ return raster
+ work = raster
+ h, w = work.shape[:2]
+ if any(a.get(k) for k in ADJUSTMENTS[:9]):
+ d = _unpremul8(work).astype(np.float64)
+ gain, contrast = math.pow(2, a.get('exposure', 0) / 50), 1 + a.get('contrast', 0) / 100
+ temp, tint = a.get('temperature', 0) / 100, a.get('tint', 0) / 100
+ hi, sh = a.get('highlights', 0) / 100, a.get('shadows', 0) / 100
+ sat, vib = 1 + a.get('saturation', 0) / 100, a.get('vibrance', 0) / 100
+ angle = a.get('hue', 0) * math.pi / 180
+ cos, sin = math.cos(angle), math.sin(angle)
+ hr = [.213 + cos * .787 - sin * .213, .715 - cos * .715 - sin * .715, .072 - cos * .072 + sin * .928,
+ .213 - cos * .213 + sin * .143, .715 + cos * .285 + sin * .140, .072 - cos * .072 - sin * .283,
+ .213 - cos * .213 - sin * .787, .715 - cos * .715 + sin * .715, .072 + cos * .928 + sin * .072]
+ r, g, b = d[..., 0] / 255 * gain, d[..., 1] / 255 * gain, d[..., 2] / 255 * gain
+ if temp:
+ r, b = r + temp * .12, b - temp * .12
+ if tint:
+ g, r, b = g - tint * .1, r + tint * .04, b + tint * .04
+ if hi or sh:
+ lum = .2126 * r + .7152 * g + .0722 * b
+ lift = hi * np.maximum(0, lum - .5) * .8 + sh * np.maximum(0, .5 - lum) * .8
+ r, g, b = r + lift, g + lift, b + lift
+ if contrast != 1:
+ r, g, b = (r - .5) * contrast + .5, (g - .5) * contrast + .5, (b - .5) * contrast + .5
+ if angle:
+ r, g, b = (hr[0] * r + hr[1] * g + hr[2] * b, hr[3] * r + hr[4] * g + hr[5] * b,
+ hr[6] * r + hr[7] * g + hr[8] * b)
+ s = sat
+ if vib:
+ spread = np.clip(np.maximum(np.maximum(r, g), b) - np.minimum(np.minimum(r, g), b), 0, 1)
+ s = s * (1 + vib * (1 - spread))
+ if not (np.isscalar(s) and s == 1):
+ r, g, b = ((.213 + .787 * s) * r + (.715 - .715 * s) * g + (.072 - .072 * s) * b,
+ (.213 - .213 * s) * r + (.715 + .285 * s) * g + (.072 - .072 * s) * b,
+ (.213 - .213 * s) * r + (.715 - .715 * s) * g + (.072 + .928 * s) * b)
+ for i, c in enumerate((r, g, b)):
+ d[..., i] = np.rint(np.clip(c, 0, 1) * 255)
+ work = _premul8(d)
+ unit = min(w, h) / 100
+ if a.get('blur', 0) > 0:
+ work = _blurred(work, a['blur'] / 100 * unit * 4)
+ if a.get('sharpen', 0) > 0:
+ sd = _unpremul8(_blurred(work, max(.6, unit * .35)))
+ d = _unpremul8(work)
+ amount = a['sharpen'] / 100 * 1.6
+ d[..., :3] = np.rint(np.clip(d[..., :3] + (d[..., :3] - sd[..., :3]) * amount, 0, 255))
+ work = _premul8(d)
+ if a.get('noise', 0) > 0 or a.get('vignette'):
+ d = _unpremul8(work)
+ amount, v = a.get('noise', 0) / 100 * 60, a.get('vignette', 0) / 100
+ f = np.ones((h, w))
+ if v:
+ dx = (np.arange(w) / w - .5) * 2
+ dy = (np.arange(h) / h - .5) * 2
+ rr = np.minimum(1, np.sqrt(dx[None, :] * dx[None, :] + dy[:, None] * dy[:, None]) / math.sqrt(2))
+ f = 1 - v * rr * rr * 1.1 if v > 0 else 1 - v * rr * rr * .8
+ n = 0
+ if amount:
+ values = _mulberry(seed, 2 * h * w).reshape(h, w, 2)
+ n = (values[..., 0] + values[..., 1] - 1) * amount
+ for c in range(3):
+ d[..., c] = np.rint(np.clip(d[..., c] * f + n, 0, 255))
+ work = _premul8(d)
+ return work
+
+
+# ---------------------------------------------------------------------------
+# Strokes, selections and the editor's pixel tools
+
+def _segments_distance(h, w, pts, radius):
+ """Distance from pixel centres to a polyline, within radius + 1."""
+ dist = np.full((h, w), np.inf, np.float32)
+ pairs = list(zip(pts, pts[1:])) or [(pts[0], pts[0])]
+ for (ax, ay), (bx, by) in pairs:
+ x0, x1 = max(0, math.floor(min(ax, bx) - radius - 1)), min(w, math.ceil(max(ax, bx) + radius + 1))
+ y0, y1 = max(0, math.floor(min(ay, by) - radius - 1)), min(h, math.ceil(max(ay, by) + radius + 1))
+ if x1 <= x0 or y1 <= y0:
+ continue
+ gx, gy = np.meshgrid(np.arange(x0, x1) + .5, np.arange(y0, y1) + .5)
+ dx, dy = bx - ax, by - ay
+ length = dx * dx + dy * dy
+ t = np.clip(((gx - ax) * dx + (gy - ay) * dy) / length, 0, 1) if length else 0
+ d = np.hypot(gx - (ax + t * dx), gy - (ay + t * dy)).astype(np.float32)
+ np.minimum(dist[y0:y1, x0:x1], d, out=dist[y0:y1, x0:x1])
+ return dist
+
+
+def _stroke_mask(h, w, op):
+ size = max(1, op['size'] * min(w, h))
+ hard = min(1, max(0, op.get('hardness', 1) if op.get('hardness') is not None else 1))
+ core, soft = size * (.4 + .6 * hard), size * (1 - hard) * .55
+ pts = [(u * w, v * h) for u, v in op['pts']]
+ alpha = np.clip(core / 2 - _segments_distance(h, w, pts, core / 2) + .5, 0, 1)
+ # A shadow-only stroke: canvas shadows blur with sigma = shadowBlur / 2.
+ alpha = _blur_alpha(alpha, soft / 2)
+ return _alpha_raster(alpha)
+
+
+def _polygon_alpha(h, w, pts, factor=4):
+ """Anti-aliased fill of a closed polygon given in pixel coordinates."""
+ out = np.zeros((h, w), np.float32)
+ xs, ys = [p[0] for p in pts], [p[1] for p in pts]
+ x0, x1 = max(0, math.floor(min(xs))), min(w, math.ceil(max(xs)))
+ y0, y1 = max(0, math.floor(min(ys))), min(h, math.ceil(max(ys)))
+ if x1 <= x0 or y1 <= y0:
+ return out
+ big = Image.new('L', ((x1 - x0) * factor, (y1 - y0) * factor))
+ ImageDraw.Draw(big).polygon([((x - x0) * factor - .5, (y - y0) * factor - .5) for x, y in pts], fill=255)
+ small = big.reduce(factor)
+ out[y0:y1, x0:x1] = np.asarray(small, np.float32) / 255
+ return out
+
+
+def _runs(row):
+ edges = np.diff(np.concatenate([[0], row.view(np.int8), [0]]))
+ return np.flatnonzero(edges == 1), np.flatnonzero(edges == -1)
+
+
+def _flood(candidates, sx, sy):
+ """4-connected region of True pixels around (sx, sy), walked by row runs."""
+ h, w = candidates.shape
+ rows = [_runs(candidates[y]) for y in range(h)]
+ seen = [np.zeros(len(r[0]), bool) for r in rows]
+ selected = np.zeros((h, w), bool)
+ starts, ends = rows[sy]
+ first = np.flatnonzero((starts <= sx) & (ends > sx))
+ stack = [(sy, int(first[0]))] if len(first) else []
+ while stack:
+ y, i = stack.pop()
+ if seen[y][i]:
+ continue
+ seen[y][i] = True
+ a, b = rows[y][0][i], rows[y][1][i]
+ selected[y, a:b] = True
+ for ny in (y - 1, y + 1):
+ if 0 <= ny < h:
+ ns, ne = rows[ny]
+ stack.extend((ny, int(j)) for j in np.flatnonzero((ns < b) & (ne > a)) if not seen[ny][j])
+ return selected
+
+
+def wand(raster, u, v, tolerance, contiguous):
+ h, w = raster.shape[:2]
+ sx, sy = min(w - 1, max(0, math.floor(u * w))), min(h - 1, max(0, math.floor(v * h)))
+ d = _unpremul8(raster)
+ near = np.all(np.abs(d - d[sy, sx]) <= tolerance * 2.55, -1)
+ selected = _flood(near, sx, sy) if contiguous else near
+ return _alpha_raster(selected.astype(np.float32))
+
+
+def _pull_push(col, wt):
+ """Pull-push interpolation, as the editor's pullPush: col (h, w, 4) holds
+ known values times their weight wt (h, w); gaps are filled from coarser averages."""
+ levels = [(col, wt)]
+ while col.shape[0] > 1 or col.shape[1] > 1:
+ ch, cw = wt.shape
+ nh, nw = max(1, ch >> 1), max(1, cw >> 1)
+ sy = [np.minimum(ch - 1, np.arange(nh) * 2 + k) for k in (0, 1)]
+ sx = [np.minimum(cw - 1, np.arange(nw) * 2 + k) for k in (0, 1)]
+ sw = sum(wt[np.ix_(a, b)] for a in sy for b in sx)
+ acc = sum(col[np.ix_(a, b)] for a in sy for b in sx)
+ with np.errstate(divide='ignore', invalid='ignore'):
+ col = np.where(sw[..., None] > 0, acc / sw[..., None] * np.minimum(1, sw)[..., None], 0)
+ wt = np.minimum(1, sw)
+ levels.append((col, wt))
+ for level in range(len(levels) - 2, -1, -1):
+ col, wt = levels[level]
+ up_col, up_wt = levels[level + 1]
+ uh, uw = up_wt.shape
+ fy = np.clip((np.arange(wt.shape[0]) + .5) / 2 - .5, 0, uh - 1)
+ fx = np.clip((np.arange(wt.shape[1]) + .5) / 2 - .5, 0, uw - 1)
+ iy, ix = np.floor(fy).astype(int), np.floor(fx).astype(int)
+ ty, tx = (fy - iy)[:, None], (fx - ix)[None, :]
+ jy, jx = np.minimum(uh - 1, iy + 1), np.minimum(uw - 1, ix + 1)
+ def sample(a):
+ t3 = tx[..., None] if a.ndim == 3 else tx
+ u3 = ty[..., None] if a.ndim == 3 else ty
+ return ((a[np.ix_(iy, ix)] * (1 - t3) + a[np.ix_(iy, jx)] * t3) * (1 - u3)
+ + (a[np.ix_(jy, ix)] * (1 - t3) + a[np.ix_(jy, jx)] * t3) * u3)
+ s, sw = sample(up_col), sample(up_wt)
+ with np.errstate(divide='ignore', invalid='ignore'):
+ norm = np.where(sw[..., None] > 0, s / sw[..., None], 0)
+ hole = wt < 1
+ col[hole] = col[hole] + norm[hole] * (1 - wt[hole])[..., None]
+ wt[hole] = 1
+ return levels[0][0]
+
+
+# Spot healing: the editor's patch-based fill (image_editor_engine.js), step
+# for step, so a stroke heals to the same pixels here as in the browser.
+HEAL_PATCH, HEAL_COARSE, HEAL_ITERS, HEAL_SEARCH, HEAL_MARGIN, HEAL_PEEL = 3, 24, 5, 60000, 384, 2048
+# A whole stroke leans on nearby patches; a caption's thin strokes have picture all around them.
+HEAL_NEAR, HEAL_NEAR_TEXT, HEAL_GUESS, HEAL_TEXT_OUTLINE = 4, .25, .1, .15
+_U32 = np.uint32
+
+
+def _hash32(x):
+ x = np.asarray(x, np.uint32)
+ x = x ^ (x >> _U32(16)); x = x * _U32(0x7feb352d)
+ x = x ^ (x >> _U32(15)); x = x * _U32(0x846ca68b)
+ return x ^ (x >> _U32(16))
+
+
+def _heal_seed(i, level, it, step):
+ value = (np.asarray(i, np.int64) * 0x9e3779b1 + level * 0x85ebca6b + it * 0xc2b2ae35 + step * 0x27d4eb2f) & 0xffffffff
+ return _hash32(value.astype(np.uint32))
+
+
+def _dilate(m, r):
+ """Pixels within r of a set pixel (a square neighbourhood)."""
+ h, w = m.shape
+ rows = np.zeros_like(m)
+ for k in range(-r, r + 1):
+ rows[:, max(0, -k):w - max(0, k)] |= m[:, max(0, k):w - max(0, -k)]
+ out = np.zeros_like(m)
+ for k in range(-r, r + 1):
+ out[max(0, -k):h - max(0, k), :] |= rows[max(0, k):h - max(0, -k), :]
+ return out
+
+
+def _peel(E, hole, sources, pr):
+ """The coarsest level's start: ring by ring from the edge inwards, each hole pixel takes
+ the centre of the source patch that best matches its filled neighbours."""
+ lh, lw = hole.shape
+ filled = ~hole
+ S = sources[::max(1, -(-len(sources) // HEAL_PEEL))]
+ sx, sy = S % lw, S // lw
+ E64 = E.astype(np.float64)
+ while True:
+ F = np.flatnonzero((hole & ~filled & _dilate(filled, 1)).ravel())
+ if not len(F):
+ break
+ fx, fy = F % lw, F // lw
+ num = np.zeros((len(F), len(S)))
+ count = np.zeros(len(F))
+ for dy in range(-pr, pr + 1):
+ for dx in range(-pr, pr + 1):
+ q = np.clip(fy + dy, 0, lh - 1) * lw + np.clip(fx + dx, 0, lw - 1)
+ k = filled.ravel()[q]
+ e = E64[q][:, None, :] - E64[(sy + dy) * lw + sx + dx][None, :, :]
+ num += k[:, None] * (e[..., 0] * e[..., 0] + e[..., 1] * e[..., 1] + e[..., 2] * e[..., 2] + e[..., 3] * e[..., 3])
+ count += k
+ E64[F] = E64[S[np.argmin(num / count[:, None], axis=1)]]
+ filled.ravel()[F] = True
+ E[:] = E64.astype(np.float32)
+
+
+def _patch_fill(region, hole, hole_size, near):
+ """Fill of the hole pixels of region ((h, w, 4) float32 of 0-255 values), or None when no patch fits."""
+ pr = HEAL_PATCH
+ area = (2 * pr + 1) ** 2
+ h, w = hole.shape
+ count = 1 + max(0, math.ceil(math.log2(hole_size / HEAL_COARSE)))
+ while count > 1 and min(w >> (count - 1), h >> (count - 1)) < 4 * (2 * pr + 1):
+ count -= 1
+ levels = [(region.astype(np.float32), hole.astype(bool))]
+ for _ in range(1, count):
+ img, m = levels[-1]
+ ph, pw = m.shape
+ nh, nw = max(1, ph >> 1), max(1, pw >> 1)
+ acc = np.zeros((nh, nw, 4), np.float32)
+ nm = np.zeros((nh, nw), bool)
+ for dy in (0, 1):
+ for dx in (0, 1):
+ ys, xs = np.minimum(ph - 1, np.arange(nh) * 2 + dy), np.minimum(pw - 1, np.arange(nw) * 2 + dx)
+ acc = (acc.astype(np.float64) + img[np.ix_(ys, xs)].astype(np.float64) / 4).astype(np.float32)
+ nm |= m[np.ix_(ys, xs)]
+ levels.append((acc, nm))
+ nnf = coarse_e = None
+ for level in range(count - 1, -1, -1):
+ img, m = levels[level]
+ lh, lw = m.shape
+ touching = _dilate(m, pr)
+ yy, xx = np.mgrid[0:lh, 0:lw]
+ valid = (~touching & (xx >= pr) & (yy >= pr) & (xx < lw - pr) & (yy < lh - pr)).ravel()
+ targets, sources = np.flatnonzero(touching.ravel()), np.flatnonzero(valid)
+ if not len(sources):
+ return None
+ holef = m.ravel()
+ tx, ty = targets % lw, targets // lw
+ pick = lambda step: sources[(_heal_seed(targets, level, 255, step) % _U32(len(sources))).astype(np.int64)]
+ E = img.reshape(-1, 4).copy()
+ if level == count - 1:
+ _peel(E, m, sources, pr)
+ nxt = pick(0)
+ else:
+ uh, uw = levels[level + 1][1].shape
+ cx, cy = np.minimum(uw - 1, xx.ravel() >> 1), np.minimum(uh - 1, yy.ravel() >> 1)
+ c = cy * uw + cx
+ E[holef] = coarse_e[c[holef]]
+ s = nnf[c[targets]]
+ sx, sy = tx + 2 * (s % uw - cx[targets]), ty + 2 * (s // uw - cy[targets])
+ inside = (s >= 0) & (sx >= 0) & (sy >= 0) & (sx < lw) & (sy < lh)
+ cand = np.where(inside, sy * lw + sx, 0)
+ nxt = np.where(inside & valid[cand], cand, pick(0))
+ span2 = max(1.0, hole_size / (1 << level)) ** 2
+ wide = [E.astype(np.float64)] # E in float64, as the browser reads it; refreshed after each vote
+
+ def cost(t, src):
+ """Patch distance, estimated pixels counting less, times a preference for nearby sources."""
+ E64 = wide[0]
+ px, py, sx, sy = t % lw, t // lw, src % lw, src // lw
+ d = np.zeros(len(t))
+ for dy in range(-pr, pr + 1):
+ row, srow = np.clip(py + dy, 0, lh - 1) * lw, (sy + dy) * lw
+ for dx in range(-pr, pr + 1):
+ q = row + np.clip(px + dx, 0, lw - 1)
+ e = E64[q] - E64[srow + sx + dx]
+ d += np.where(holef[q], HEAL_GUESS, 1.0) * (e[:, 0] * e[:, 0] + e[:, 1] * e[:, 1] + e[:, 2] * e[:, 2] + e[:, 3] * e[:, 3])
+ ddx, ddy = (sx - px).astype(np.float64), (sy - py).astype(np.float64)
+ return d * (1 + near * (ddx * ddx + ddy * ddy) / span2)
+
+ def vote(src, D):
+ weight = 1 / (1 + D / (area * 4) / 100)
+ acc, total = np.zeros((lh * lw, 4)), np.zeros(lh * lw)
+ sx, sy = src % lw, src // lw
+ E64 = wide[0]
+ for dy in range(-pr, pr + 1):
+ for dx in range(-pr, pr + 1):
+ x, y = tx + dx, ty + dy
+ ok = (x >= 0) & (y >= 0) & (x < lw) & (y < lh)
+ ok[ok] &= holef[(y * lw + x)[ok]]
+ idx = (y * lw + x)[ok] # distinct for one offset, so plain indexing adds once each
+ acc[idx] += weight[ok, None] * E64[((sy + dy) * lw + sx + dx)[ok]]
+ total[idx] += weight[ok]
+ filled = total > 0
+ E[filled] = (acc[filled] / total[filled, None]).astype(np.float32)
+ wide[0] = E.astype(np.float64)
+
+ D = cost(targets, nxt)
+ if level < count - 1:
+ vote(nxt, D)
+ reach = max(lw, lh)
+ for it in range(HEAL_ITERS if len(targets) <= HEAL_SEARCH else 0):
+ prev = np.full(lh * lw, -1, np.int64)
+ prev[targets] = nxt
+ best = nxt.copy()
+ best_d = cost(targets, best)
+
+ def consider(ok, s):
+ nonlocal best, best_d
+ if not ok.any():
+ return
+ d = np.full(len(targets), np.inf)
+ d[ok] = cost(targets[ok], s[ok])
+ better = d < best_d
+ best, best_d = np.where(better, s, best), np.where(better, d, best_d)
+
+ # Neighbours' sources, shifted by one: good matches spread along the patch grid.
+ for step, ok in ((-1, tx > 0), (1, tx < lw - 1), (-lw, targets >= lw), (lw, targets + lw < lw * lh)):
+ pq = np.where(ok, prev[np.where(ok, targets + step, 0)], -1)
+ s = pq - step
+ ok = ok & (pq >= 0) & (s >= 0) & (s < lw * lh)
+ ok[ok] &= np.abs(s[ok] % lw - pq[ok] % lw) <= 1
+ ok[ok] &= valid[s[ok]]
+ consider(ok, s)
+ # Random search in shrinking windows around the best so far.
+ r, step = reach, 1
+ while r >= 1:
+ h1 = _heal_seed(targets, level, it, step)
+ h2 = _hash32(h1)
+ bx, by = best % lw, best // lw
+ x = np.clip(bx + (h1 % _U32(2 * r + 1)).astype(np.int64) - r, pr, lw - 1 - pr)
+ y = np.clip(by + (h2 % _U32(2 * r + 1)).astype(np.int64) - r, pr, lh - 1 - pr)
+ s = y * lw + x
+ consider(valid[s], s)
+ r >>= 1
+ step += 1
+ nxt, D = best, best_d
+ vote(nxt, D)
+ nnf = np.full(lh * lw, -1, np.int64)
+ nnf[targets] = nxt
+ coarse_e = E
+ return E.reshape(h, w, 4)
+
+
+def _without_specks(m, least):
+ """m without its 8-connected parts of fewer than least pixels."""
+ h, w = m.shape
+ flat = m.ravel()
+ seen = np.zeros(h * w, bool)
+ keep = np.zeros(h * w, bool)
+ for start in np.flatnonzero(flat):
+ if seen[start]:
+ continue
+ seen[start] = True
+ part, stack = [], [int(start)]
+ while stack:
+ i = stack.pop()
+ part.append(i)
+ y, x = divmod(i, w)
+ for ny in (y - 1, y, y + 1):
+ for nx in (x - 1, x, x + 1):
+ if 0 <= ny < h and 0 <= nx < w:
+ j = ny * w + nx
+ if flat[j] and not seen[j]:
+ seen[j] = True
+ stack.append(j)
+ if len(part) >= least:
+ keep[part] = True
+ return keep.reshape(h, w)
+
+
+def _text_hole(d, hole, brush):
+ """The caption inside a stroke: thin, bright, colourless strokes and their outline. None
+ when the stroke holds no such text, or so much (over 70%) that it is not a caption."""
+ r8 = d.astype(np.int64)
+ lum = (77 * r8[..., 0] + 150 * r8[..., 1] + 29 * r8[..., 2]) >> 8
+ chroma = r8[..., :3].max(-1) - r8[..., :3].min(-1)
+ core = hole & (lum >= 190) & (chroma <= 60)
+ # Letters are thin: what survives thinning by a tenth of the brush (a white shirt, a
+ # lamp) is picture, and so is anything right beside it.
+ t = max(1, _round(.1 * brush))
+ core &= ~_dilate(~_dilate(~core, t), t + 2)
+ # Specks (a highlight on a buckle) are not letters either.
+ core = _without_specks(core, max(4, _round((.12 * brush) ** 2)))
+ found = int(core.sum())
+ if not found or found * 10 > int(hole.sum()) * 7:
+ return None
+ return _dilate(core, max(2, _round(HEAL_TEXT_OUTLINE * brush))) & hole
+
+
+def _heal(raster, mask, text=False, brush=0):
+ """Spot healing of the masked pixels, as the editor does it: a patch-based fill from
+ patches around the stroke (only its caption when text is set, and nothing when it holds
+ none), or a smooth fill when no patch fits."""
+ h, w = raster.shape[:2]
+ md = np.rint(mask[..., 3] * 255)
+ ys, xs = np.nonzero(md > 8)
+ if not len(xs):
+ return raster
+ x0, x1, y0, y1 = xs.min(), xs.max(), ys.min(), ys.max()
+ if text:
+ # Only the caption is replaced, and the work centres on it rather than on the stroke.
+ words = _text_hole(_unpremul8(raster[y0:y1 + 1, x0:x1 + 1]), md[y0:y1 + 1, x0:x1 + 1] > 8, brush)
+ if words is None:
+ return raster # no caption under the stroke: nothing to remove
+ md = np.zeros_like(md)
+ md[y0:y1 + 1, x0:x1 + 1] = np.where(words, 255, 0)
+ ys, xs = np.nonzero(md > 8)
+ x0, x1, y0, y1 = xs.min(), xs.max(), ys.min(), ys.max()
+ size = max(x1 - x0 + 1, y1 - y0 + 1)
+ margin = max(24, min(HEAL_MARGIN, _round(size * .8)))
+ rx0, ry0, rx1, ry1 = max(0, x0 - margin), max(0, y0 - margin), min(w - 1, x1 + margin), min(h - 1, y1 + margin)
+ d = _unpremul8(raster[ry0:ry1 + 1, rx0:rx1 + 1])
+ m = md[ry0:ry1 + 1, rx0:rx1 + 1]
+ hole = m > 8
+ fill = _patch_fill(d.astype(np.float32), hole, size, HEAL_NEAR_TEXT if text else HEAL_NEAR)
+ if fill is not None:
+ k = np.minimum(1, m / 128)[..., None]
+ healed = np.where(hole[..., None], np.rint(np.clip(d * (1 - k) + fill * k, 0, 255)), d)
+ else:
+ known = 1 - m / 255
+ smooth = _pull_push(d * known[..., None], known.copy())
+ a = (m / 255)[..., None]
+ healed = np.where(a > 0, np.rint(np.clip(d * (1 - a) + smooth * a, 0, 255)), d)
+ out = raster.copy()
+ out[ry0:ry1 + 1, rx0:rx1 + 1] = _premul8(healed)
+ return out
+
+
+def _gradient(h, w, op, path):
+ gx, gy = np.meshgrid(np.arange(w) + .5, np.arange(h) + .5)
+ x1, y1, x2, y2 = op['from'][0] * w, op['from'][1] * h, op['to'][0] * w, op['to'][1] * h
+ if op.get('shape') == 'radial':
+ t = np.hypot(gx - x1, gy - y1) / (math.hypot(x2 - x1, y2 - y1) or 1)
+ else:
+ length = (x2 - x1) ** 2 + (y2 - y1) ** 2
+ if not length:
+ return np.zeros((h, w, 4), np.float32)
+ t = ((gx - x1) * (x2 - x1) + (gy - y1) * (y2 - y1)) / length
+ t = np.clip(t, 0, 1)[..., None]
+ c1 = np.array(_color(op['c1'], path + '/c1'))
+ c2 = c1 * [1, 1, 1, 0] if op['c2'] == 'transparent' else np.array(_color(op['c2'], path + '/c2'))
+ c = c1 * (1 - t) + c2 * t
+ c[..., :3] *= c[..., 3:]
+ return _q(c.astype(np.float32))
+
+
+# ---------------------------------------------------------------------------
+# Fonts: web/fonts.js picks the family, then the sans for what it lacks, then the box.
+
+def _covers(font, text):
+ """Whether the font has every character: a missing one draws .notdef."""
+ def ink(ch):
+ image = Image.new('L', (96, 96))
+ ImageDraw.Draw(image).text((16, 16), ch, font=font, fill=255)
+ return image.tobytes()
+ missing = ink('\U0010FFFD')
+ return all(ch.isspace() or ink(ch) != missing for ch in set(text))
+
+
+_CHOSEN = {}
+
+
+def font_stack(key, weight):
+ """The font files of fontStack(): the family, the sans fallback, the box."""
+ key = key if key in FONTS else 'sans'
+ weight = 700 if (weight or 400) >= 550 else 400 # fontWeight() of web/fonts.js
+ files = [FONTS[key][weight]] + ([FONTS['sans'][weight]] if key != 'sans' else []) + [FONT_BOX]
+ return [str(FONT_DIR / name) for name in files]
+
+
+def font_for(key, weight, size, text=''):
+ """The bundled font that draws this text, and its file.
+
+ Browsers fall back per character; here the first file of the stack that has
+ every character draws the whole text, and the box font draws what none has."""
+ stack = font_stack(key, weight)
+ if (tuple(stack), text) not in _CHOSEN:
+ _CHOSEN[(tuple(stack), text)] = next(
+ (path for path in stack[:-1] if _covers(ImageFont.truetype(path, 32), text)), stack[-1])
+ chosen = _CHOSEN[(tuple(stack), text)]
+ return ImageFont.truetype(chosen, max(1, round(size))), chosen
+
+
+def _top_ascent(size):
+ return round(EM_ASCENT * size * 64) / 64
+
+
+def measure_text(text):
+ """measureText of the editor: the native size of a text block."""
+ lines = str(text.get('content') or ' ').split('\n')
+ font, _ = font_for(text.get('font'), text.get('weight'), text['size'], str(text.get('content') or ''))
+ width = max(font.getlength(line or ' ') for line in lines)
+ size, height = text['size'], text.get('lineHeight') or 1.25
+ return dict(nw=math.ceil(width + size * .4), nh=math.ceil(size * (.4 + (len(lines) - 1) * height + 1.1)))
+
+
+def _text_raster(layer, path):
+ t = layer['text']
+ h, w = _size(layer['nh']), _size(layer['nw'])
+ size = t['size']
+ content = str(t.get('content', ''))
+ font, _ = font_for(t.get('font'), t.get('weight'), size, content)
+ ascent = _top_ascent(size)
+ align = t.get('align') or 'left'
+ x = layer['nw'] / 2 if align == 'center' else layer['nw'] - size * .2 if align == 'right' else size * .2
+ anchor = {'center': 'ms', 'right': 'rs'}.get(align, 'ls')
+ out = np.zeros((h, w, 4), np.float32)
+ fill = _color(t.get('color', '#000'), path + '/text/color')
+ outline = t.get('outline')
+ stroke = max(1, size * .08) if outline else 0
+ for i, line in enumerate(content.split('\n')):
+ y = size * .2 + i * size * (t.get('lineHeight') or 1.25) + ascent
+ shapes = []
+ if outline:
+ mask = Image.new('L', (w, h))
+ ImageDraw.Draw(mask).text((x, y), line, font=font, fill=255, anchor=anchor,
+ stroke_width=max(1, round(stroke / 2)), stroke_fill=255)
+ shapes.append((np.asarray(mask, np.float32) / 255, _color(outline, path + '/text/outline')))
+ mask = Image.new('L', (w, h))
+ ImageDraw.Draw(mask).text((x, y), line, font=font, fill=255, anchor=anchor)
+ shapes.append((np.asarray(mask, np.float32) / 255, fill))
+ for alpha, color in shapes:
+ if t.get('shadow'):
+ # Canvas shadows: sigma is half of shadowBlur, offset below.
+ layer_shadow = np.zeros((h, w, 4), np.float32)
+ _draw(layer_shadow, _alpha_raster(_blur_alpha(alpha, size * .18 / 2)), _t(0, size * .05))
+ _composite(out, layer_shadow * np.array([0, 0, 0, .55], np.float32))
+ paint = _solid(h, w, color) * alpha[..., None]
+ _composite(out, paint)
+ return _q(out)
+
+
+def _shape_raster(layer, path, factor=4):
+ s = layer['shape']
+ nw, nh = layer['nw'], layer['nh']
+ h, w = _size(nh), _size(nw)
+ lw = s.get('width', 0) if s.get('stroke') else 0
+ inset = lw / 2
+
+ def mask(draw):
+ big = Image.new('L', (w * factor, h * factor))
+ draw(ImageDraw.Draw(big), factor)
+ return np.asarray(big.reduce(factor), np.float32) / 255
+
+ def rect(d, k, x0, y0, x1, y1, radius):
+ if x1 > x0 and y1 > y0:
+ box = [x0 * k, y0 * k, x1 * k - 1, y1 * k - 1]
+ d.rounded_rectangle(box, radius=max(0, radius) * k, fill=255) if radius > 0 else d.rectangle(box, fill=255)
+
+ def ellipse(d, k, rx, ry):
+ if rx > 0 and ry > 0:
+ d.ellipse([(nw / 2 - rx) * k, (nh / 2 - ry) * k, (nw / 2 + rx) * k - 1, (nh / 2 + ry) * k - 1], fill=255)
+
+ out = np.zeros((h, w, 4), np.float32)
+ kind = s.get('type', 'rect')
+ radius = min(s.get('radius') or 0, (nw - lw) / 2, (nh - lw) / 2)
+ if kind == 'line':
+ if lw:
+ dist = _segments_distance(h, w, [(inset, nh / 2), (nw - inset, nh / 2)], lw / 2)
+ _composite(out, _solid(h, w, _color(s['stroke'], path + '/shape/stroke'))
+ * np.clip(lw / 2 - dist + .5, 0, 1)[..., None])
+ return _q(out)
+ rx, ry = max(1, nw / 2 - inset), max(1, nh / 2 - inset)
+ if s.get('fill'):
+ area = (mask(lambda d, k: ellipse(d, k, rx, ry)) if kind == 'ellipse'
+ else mask(lambda d, k: rect(d, k, inset, inset, nw - inset, nh - inset, radius)))
+ _composite(out, _solid(h, w, _color(s['fill'], path + '/shape/fill')) * area[..., None])
+ if lw:
+ if kind == 'ellipse':
+ ring = (mask(lambda d, k: ellipse(d, k, rx + lw / 2, ry + lw / 2))
+ - mask(lambda d, k: ellipse(d, k, rx - lw / 2, ry - lw / 2)))
+ else:
+ ring = (mask(lambda d, k: rect(d, k, 0, 0, nw, nh, radius + lw / 2 if radius > 0 else 0))
+ - mask(lambda d, k: rect(d, k, lw, lw, nw - lw, nh - lw, max(0, radius - lw / 2))))
+ _composite(out, _solid(h, w, _color(s['stroke'], path + '/shape/stroke')) * np.clip(ring, 0, 1)[..., None])
+ return _q(out)
+
+
+# ---------------------------------------------------------------------------
+# Documents
+
+def _number(value, path, low=-math.inf, high=math.inf, positive=False):
+ if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
+ raise EditError(path, 'must be a finite number')
+ if value < low or value > high or positive and value <= 0:
+ raise EditError(path, 'out of range')
+ return value
+
+
+def _check_selection(selection, path):
+ if not isinstance(selection, dict) or not isinstance(selection.get('parts'), list):
+ raise EditError(path, 'a selection needs parts')
+ _number(selection.get('feather', 0) or 0, path + '/feather', 0)
+ for i, part in enumerate(selection['parts']):
+ where = '%s/parts/%d' % (path, i)
+ if not isinstance(part, dict) or part.get('shape') not in ('rect', 'ellipse', 'all', 'poly', 'wand'):
+ raise EditError(where, 'unsupported selection shape')
+ if part.get('mode', 'replace') not in ('replace', 'add', 'subtract', 'intersect'):
+ raise EditError(where + '/mode', 'unsupported mode')
+ if part['shape'] in ('rect', 'ellipse'):
+ for key in ('x', 'y', 'w', 'h'):
+ _number(part.get(key), '%s/%s' % (where, key))
+ if part['shape'] == 'poly' and not (isinstance(part.get('pts'), list)
+ and all(isinstance(p, list) and len(p) == 2 for p in part['pts'])):
+ raise EditError(where + '/pts', 'points must be [x, y] pairs')
+ if part['shape'] == 'wand':
+ for key in ('u', 'v', 'tolerance'):
+ _number(part.get(key), '%s/%s' % (where, key))
+
+
+def _check_op(op, path, mask=False):
+ if not isinstance(op, dict) or op.get('type') not in OPS:
+ raise EditError(path, 'unsupported operation %r' % (op.get('type') if isinstance(op, dict) else op,))
+ if op.get('selection') is not None:
+ _check_selection(op['selection'], path + '/selection')
+ _number(op.get('opacity', 1) if op.get('opacity') is not None else 1, path + '/opacity', 0, 1)
+ if op['type'] == 'stroke':
+ if op.get('tool') not in TOOLS:
+ raise EditError(path + '/tool', 'unsupported tool %r' % (op.get('tool'),))
+ if not isinstance(op.get('pts'), list) or not op['pts'] or not all(
+ isinstance(p, (list, tuple)) and len(p) == 2 for p in op['pts']):
+ raise EditError(path + '/pts', 'a stroke needs [u, v] points')
+ _number(op.get('size'), path + '/size', positive=True)
+ if op.get('text') not in (None, True, False):
+ raise EditError(path + '/text', 'text is true or false')
+ if op['tool'] == 'clone' and not (isinstance(op.get('offset'), list) and len(op['offset']) == 2):
+ raise EditError(path + '/offset', 'clone needs an offset')
+ if op['tool'] in ('paint',) and not mask:
+ _color(op.get('color'), path + '/color')
+ elif op['type'] == 'gradient':
+ for key in ('from', 'to'):
+ if not (isinstance(op.get(key), list) and len(op[key]) == 2):
+ raise EditError('%s/%s' % (path, key), 'a gradient needs from and to points')
+
+
+def _check(doc):
+ if not isinstance(doc, dict) or doc.get('version') != 2:
+ raise EditError('/version', 'only version 2 editor documents are supported')
+ for key in ('width', 'height'):
+ _number(doc.get(key), '/' + key, positive=True)
+ if doc.get('rotate') not in (0, 90, 180, 270):
+ raise EditError('/rotate', 'must be 0, 90, 180 or 270')
+ for key in ('flipX', 'flipY'):
+ if not isinstance(doc.get(key), bool):
+ raise EditError('/' + key, 'must be true or false')
+ e = doc.get('extend')
+ if not isinstance(e, dict):
+ raise EditError('/extend', 'missing')
+ for key in 'ltrb':
+ _number(e.get(key), '/extend/' + key, 0)
+ _color(e.get('color', '#000000'), '/extend/color')
+ c = doc.get('crop')
+ if not isinstance(c, dict):
+ raise EditError('/crop', 'missing')
+ for key in ('x', 'y', 'w', 'h'):
+ _number(c.get(key), '/crop/' + key, positive=key in 'wh')
+ r = canvas_rect(doc)
+ if r['w'] * r['h'] > MAX_PIXELS or c['w'] * c['h'] > MAX_PIXELS:
+ raise EditError('/extend', 'the canvas is larger than %d pixels' % MAX_PIXELS)
+ layers = doc.get('layers')
+ if not isinstance(layers, list) or not layers:
+ raise EditError('/layers', 'a document needs layers')
+ ids = {layer.get('id') for layer in layers if isinstance(layer, dict)}
+ for i, layer in enumerate(layers):
+ path = '/layers/%d' % i
+ if not isinstance(layer, dict) or layer.get('kind') not in ('image', 'paint', 'text', 'shape'):
+ raise EditError(path + '/kind', 'unsupported layer kind')
+ for key in ('cx', 'cy', 'rotation'):
+ _number(layer.get(key), '%s/%s' % (path, key))
+ for key in ('w', 'h', 'nw', 'nh'):
+ _number(layer.get(key), '%s/%s' % (path, key), positive=True)
+ if layer['nw'] * layer['nh'] > MAX_PIXELS:
+ raise EditError(path, 'the layer is larger than %d pixels' % MAX_PIXELS)
+ _number(layer.get('opacity', 1), path + '/opacity', 0, 1)
+ if layer.get('blend', 'source-over') not in BLENDS:
+ raise EditError(path + '/blend', 'unsupported blend %r' % (layer.get('blend'),))
+ for key, value in (layer.get('adjust') or {}).items():
+ if key not in ADJUSTMENTS:
+ raise EditError('%s/adjust/%s' % (path, key), 'unknown adjustment')
+ _number(value or 0, '%s/adjust/%s' % (path, key))
+ for j, op in enumerate(layer.get('ops') or []):
+ _check_op(op, '%s/ops/%d' % (path, j))
+ if layer.get('mask') is not None:
+ if not isinstance(layer['mask'], dict) or not isinstance(layer['mask'].get('ops'), list):
+ raise EditError(path + '/mask', 'a mask needs ops')
+ for j, op in enumerate(layer['mask']['ops']):
+ _check_op(op, '%s/mask/ops/%d' % (path, j), mask=True)
+ if layer.get('copyOf') and layer['copyOf'].get('layer') not in ids:
+ raise EditError(path + '/copyOf/layer', 'unknown layer')
+ if layer['kind'] == 'text':
+ t = layer.get('text')
+ if not isinstance(t, dict) or not isinstance(t.get('content'), str):
+ raise EditError(path + '/text', 'a text layer needs content')
+ _number(t.get('size'), path + '/text/size', positive=True)
+ _color(t.get('color', '#000'), path + '/text/color')
+ if layer['kind'] == 'shape':
+ s = layer.get('shape')
+ if not isinstance(s, dict) or s.get('type') not in ('rect', 'ellipse', 'line'):
+ raise EditError(path + '/shape/type', 'unsupported shape')
+ if s.get('stroke'):
+ _number(s.get('width'), path + '/shape/width', positive=True)
+
+
+class _Renderer:
+ def __init__(self, doc, resolve):
+ self.doc, self.resolve, self.images, self.rasters = doc, resolve, {}, {}
+ self.layers = {layer['id']: (i, layer) for i, layer in enumerate(doc['layers'])}
+
+ def image(self, src, path):
+ if src not in self.images:
+ try:
+ with Image.open(self.resolve(src)) as source:
+ if source.width * source.height > MAX_PIXELS:
+ raise EditError(path, 'the image is larger than %d pixels' % MAX_PIXELS)
+ self.images[src] = _from_image(ImageOps.exif_transpose(source))
+ except (OSError, ValueError, KeyError) as error:
+ if isinstance(error, EditError):
+ raise
+ raise EditError(path, 'cannot read image %r' % (src,)) from None
+ return self.images[src]
+
+ def raster(self, layer, upto=None):
+ index = self.layers[layer['id']][0]
+ ops = layer.get('ops') or []
+ upto = len(ops) if upto is None else max(0, min(len(ops), int(upto)))
+ key = (layer['id'], upto)
+ if key in self.rasters:
+ return self.rasters[key]
+ h, w = _size(layer['nh']), _size(layer['nw'])
+ out = np.zeros((h, w, 4), np.float32)
+ if layer['kind'] == 'image' and layer.get('src'):
+ img = self.image(layer['src'], '/layers/%d/src' % index)
+ _draw(out, img, _s(w / img.shape[1], h / img.shape[0]))
+ copy = layer.get('copyOf')
+ if copy:
+ _, source = self.layers[copy['layer']]
+ src = self.raster(source, copy.get('upto'))
+ _draw(out, src, _s(w / src.shape[1], h / src.shape[0]))
+ if copy.get('selection'):
+ _mask_with(out, self.selection(copy['selection'], source))
+ out = _q(out)
+ for j, op in enumerate(ops[:upto]):
+ out = self.apply(layer, out, op, '/layers/%d/ops/%d' % (index, j))
+ self.rasters[key] = out
+ return out
+
+ def mask(self, layer):
+ index = self.layers[layer['id']][0]
+ out = np.ones((_size(layer['nh']), _size(layer['nw']), 4), np.float32)
+ for j, op in enumerate(layer['mask']['ops']):
+ out = self.apply(layer, out, op, '/layers/%d/mask/ops/%d' % (index, j), is_mask=True)
+ return out
+
+ def apply(self, layer, target, op, path, is_mask=False):
+ h, w = target.shape[:2]
+ selection = self.selection(op['selection'], layer) if op.get('selection') else None
+ def within(img):
+ return _mask_with(img, selection) if selection is not None else img
+ opacity = op.get('opacity') if op.get('opacity') is not None else 1
+ target = target.copy()
+ kind = op['type']
+ if kind == 'fromSelection':
+ target = selection.copy() if selection is not None else np.ones((h, w, 4), np.float32)
+ if op.get('invert'):
+ _composite(target, np.ones((h, w, 4), np.float32), 'xor')
+ return _q(target)
+ if kind in ('fill', 'clear'):
+ fill = within(_solid(h, w, (1, 1, 1, 1) if is_mask else _color(op.get('color') or '#000', path + '/color')))
+ _composite(target, fill * np.float32(opacity), 'destination-out' if kind == 'clear' else 'source-over')
+ return _q(target)
+ if kind == 'gradient':
+ g = within(_gradient(h, w, op, path))
+ _composite(target, g * np.float32(opacity))
+ return _q(target)
+ mask = within(_stroke_mask(h, w, op))
+ tool = op['tool']
+ if tool in ('paint', 'reveal'):
+ color = (1, 1, 1, 1) if tool == 'reveal' else _color(op.get('color'), path + '/color')
+ _composite(target, _mask_with(_solid(h, w, color), mask) * np.float32(opacity))
+ elif tool in ('erase', 'hide'):
+ _composite(target, mask * np.float32(opacity), 'destination-out')
+ elif tool == 'clone':
+ copy = np.zeros_like(target)
+ _draw(copy, target, _t(op['offset'][0] * w, op['offset'][1] * h))
+ _composite(target, _mask_with(_q(copy), mask) * np.float32(opacity))
+ elif tool == 'blur':
+ strength = op.get('strength') if op.get('strength') is not None else .6
+ radius = max(1, op['size'] * min(w, h) * .25 * strength)
+ _composite(target, _mask_with(_blurred(target, radius), mask) * np.float32(opacity))
+ elif tool == 'heal':
+ target = _heal(target, mask, text=bool(op.get('text')), brush=op['size'] * min(w, h))
+ return _q(target)
+
+ def selection(self, selection, layer):
+ h, w = _size(layer['nh']), _size(layer['nw'])
+ out = np.zeros((h, w, 4), np.float32)
+ to_local = np.linalg.inv(layer_matrix(layer))
+ for part in selection['parts']:
+ mode = part.get('mode', 'replace')
+ op = {'subtract': 'destination-out', 'intersect': 'destination-in'}.get(mode, 'source-over')
+ if mode == 'replace':
+ out[...] = 0
+ shape = part['shape']
+ if shape == 'wand':
+ if part.get('layer') not in self.layers:
+ continue
+ _, src = self.layers[part['layer']]
+ raster = self.raster(src, part.get('upto'))
+ m = wand(raster, part['u'], part['v'], part['tolerance'], part.get('contiguous', True))
+ _draw(out, m, to_local @ layer_matrix(src), op=op)
+ continue
+ if shape == 'all':
+ alpha = np.ones((h, w), np.float32)
+ else:
+ if shape == 'rect':
+ x, y, pw, ph = part['x'], part['y'], part['w'], part['h']
+ pts = [(x, y), (x + pw, y), (x + pw, y + ph), (x, y + ph)]
+ elif shape == 'ellipse':
+ cx, cy = part['x'] + part['w'] / 2, part['y'] + part['h'] / 2
+ rx, ry = abs(part['w'] / 2), abs(part['h'] / 2)
+ pts = [(cx + rx * math.cos(a), cy + ry * math.sin(a))
+ for a in np.linspace(0, 2 * math.pi, 256, endpoint=False)]
+ else:
+ pts = [tuple(p) for p in part.get('pts') or []]
+ if len(pts) < 3:
+ continue
+ pts = [_apply(to_local, x, y) for x, y in pts]
+ alpha = _polygon_alpha(h, w, pts)
+ _composite(out, _alpha_raster(alpha), op)
+ if selection.get('invert'):
+ _composite(out, np.ones((h, w, 4), np.float32), 'xor')
+ if (selection.get('feather') or 0) > 0:
+ px = selection['feather'] * max(layer['nw'] / layer['w'], layer['nh'] / layer['h'])
+ return _alpha_raster(_blur_alpha(out[..., 3], px))
+ return _q(out)
+
+ def layer_image(self, layer, index):
+ path = '/layers/%d' % index
+ if layer['kind'] == 'text':
+ return _text_raster(layer, path)
+ if layer['kind'] == 'shape':
+ return _shape_raster(layer, path)
+ raster = self.raster(layer)
+ out = adjusted(raster, layer.get('adjust'), hash_string(layer['id']))
+ if layer.get('mask') is not None:
+ out = _mask_with(out.copy(), self.mask(layer))
+ return _q(out)
+
+ def composite(self, background=True):
+ doc = self.doc
+ rect = canvas_rect(doc)
+ h, w = _size(rect['h']), _size(rect['w'])
+ e = doc['extend']
+ out = (_solid(h, w, _color(e.get('color', '#000000'))) if background and (e['l'] or e['t'] or e['r'] or e['b'])
+ else np.zeros((h, w, 4), np.float32))
+ view = _chain(_t(-rect['x'], -rect['y']), orient_matrix(doc))
+ for i, layer in enumerate(doc['layers']):
+ if not layer.get('visible', True):
+ continue
+ image = self.layer_image(layer, i)
+ _draw(out, image, view @ layer_matrix(layer), alpha=layer.get('opacity', 1),
+ op=layer.get('blend') or 'source-over')
+ out = _q(out)
+ return out
+
+
+def render(doc, resolve, *, jpeg=False):
+ """The document's saved picture, as the editor exports it: the crop of the
+ composited canvas, RGBA (or RGB on the background colour for JPEG)."""
+ _check(doc)
+ full = _Renderer(doc, resolve).composite()
+ rect, c = canvas_rect(doc), doc['crop']
+ w, h = _size(c['w']), _size(c['h'])
+ sx, sy = _round(c['x'] - rect['x']), _round(c['y'] - rect['y'])
+ out = np.zeros((h, w, 4), np.float32)
+ _draw(out, full, _t(-sx, -sy))
+ if not jpeg:
+ return _to_image(out)
+ matte = _solid(h, w, _color(doc['extend'].get('color') or '#000'))
+ _composite(matte, out)
+ return _to_image(matte).convert('RGB')
+
+
+def save(doc, resolve, path):
+ """Render to a .png or .jpg file; returns its size."""
+ path = Path(path)
+ jpeg = path.suffix.lower() in ('.jpg', '.jpeg')
+ image = render(doc, resolve, jpeg=jpeg)
+ if jpeg:
+ image.save(path, 'JPEG', quality=95)
+ else:
+ image.save(path, 'PNG')
+ return dict(width=image.width, height=image.height, path=str(path))
+
+
+# ---------------------------------------------------------------------------
+# Recipes: what an agent asks for, compiled to the editor's document.
+
+_counter = itertools.count()
+
+
+def _base36(n):
+ digits = '0123456789abcdefghijklmnopqrstuvwxyz'
+ out = ''
+ while True:
+ n, r = divmod(n, 36)
+ out = digits[r] + out
+ if not n:
+ return out
+
+
+def uid(prefix):
+ return prefix + _base36(int(time.time() * 1000)) + _base36(next(_counter))
+
+
+def empty_adjust():
+ return {k: 0 for k in ADJUSTMENTS}
+
+
+def new_document(source, width, height):
+ base = dict(id='base', kind='image', name='', src=source, visible=True, locked=True, opacity=1,
+ blend='source-over', cx=width / 2, cy=height / 2, w=width, h=height, rotation=0, flipX=False,
+ flipY=False, nw=width, nh=height, ops=[], mask=None, adjust=empty_adjust())
+ return dict(version=2, width=width, height=height, rotate=0, flipX=False, flipY=False,
+ extend=dict(l=0, t=0, r=0, b=0, color='#000000'), crop=dict(x=0, y=0, w=width, h=height),
+ ratio='original', layers=[base], active='base')
+
+
+def _fit_rect(aspect, r):
+ if not aspect:
+ return dict(r)
+ w, h = r['w'], r['w'] / aspect
+ if h > r['h']:
+ h = r['h']
+ w = h * aspect
+ return dict(x=r['x'] + (r['w'] - w) / 2, y=r['y'] + (r['h'] - h) / 2, w=w, h=h)
+
+
+def _aspect(ratio, r, target, path):
+ if ratio == 'video':
+ if not target:
+ raise EditError(path, 'the video size is unknown here; give a ratio such as 16:9')
+ return target[0] / target[1]
+ if ratio == 'original':
+ return r['w'] / r['h']
+ if ratio == 'free':
+ return None
+ if ratio in RATIOS:
+ return RATIOS[ratio]
+ try:
+ a, b = (float(x) for x in str(ratio).split(':'))
+ if a > 0 and b > 0 and math.isfinite(a / b):
+ return a / b
+ except ValueError:
+ pass
+ raise EditError(path, "use 'video', 'original', 'free' or W:H such as 16:9")
+
+
+def _turn(doc, op, target):
+ """Rotate or mirror the canvas exactly as the editor's buttons do."""
+ before, e, nxt = canvas_rect(doc), doc['extend'], dict(doc)
+ if op in ('cw', 'ccw'):
+ mirrored = doc['flipX'] != doc['flipY']
+ nxt['rotate'] = (doc['rotate'] + (90 if (op == 'cw') != mirrored else 270)) % 360
+ nxt['extend'] = (dict(e, l=e['b'], t=e['l'], r=e['t'], b=e['r']) if op == 'cw'
+ else dict(e, l=e['t'], t=e['r'], r=e['b'], b=e['l']))
+ else:
+ nxt[op] = not doc[op]
+ nxt['extend'] = dict(e, l=e['r'], r=e['l']) if op == 'flipX' else dict(e, t=e['b'], b=e['t'])
+
+ def where(x, y):
+ u, v = (x - before['x']) / before['w'], (y - before['y']) / before['h']
+ return {'cw': (1 - v, u), 'ccw': (v, 1 - u), 'flipX': (1 - u, v), 'flipY': (u, 1 - v)}[op]
+ after, c = canvas_rect(nxt), doc['crop']
+ a, b = where(c['x'], c['y']), where(c['x'] + c['w'], c['y'] + c['h'])
+ crop = dict(x=after['x'] + min(a[0], b[0]) * after['w'], y=after['y'] + min(a[1], b[1]) * after['h'],
+ w=abs(a[0] - b[0]) * after['w'], h=abs(a[1] - b[1]) * after['h'])
+ if op in ('cw', 'ccw') and doc['ratio'] != 'free':
+ aspect = _aspect(doc['ratio'], after, target, '/ratio') if doc['ratio'] != 'video' or target else None
+ if aspect:
+ crop = _fit_rect(aspect, after)
+ nxt['crop'] = crop
+ return nxt
+
+
+def _check_keys(op, allowed, path):
+ for key in op:
+ if key not in allowed and key != 'op':
+ raise EditError('%s/%s' % (path, key), 'unknown key for %s' % op['op'])
+
+
+def _opt(op, key, path, default=None, low=-math.inf, high=math.inf, positive=False):
+ if op.get(key) is None:
+ return default
+ return _number(op[key], '%s/%s' % (path, key), low, high, positive)
+
+
+def _choice(op, key, path, options, default):
+ value = op.get(key, default)
+ if value not in options:
+ raise EditError('%s/%s' % (path, key), 'use one of %s' % ', '.join(map(str, options)))
+ return value
+
+
+def _color_key(op, key, path, default):
+ value = op.get(key, default)
+ if value is not None and value is not False:
+ _color(value, '%s/%s' % (path, key))
+ return value
+
+
+def _place(op, path, frame, w, h):
+ """Top-left of a w x h box in the frame: x/y, or an anchor and margin."""
+ margin = _opt(op, 'margin', path, 0, 0)
+ anchor = _choice(op, 'anchor', path, ANCHORS, 'center')
+ hx = 0 if 'left' in anchor else 2 if 'right' in anchor else 1
+ vy = 0 if anchor.startswith('top') else 2 if anchor.startswith('bottom') else 1
+ x = [margin, (frame['w'] - w) / 2, frame['w'] - w - margin][hx]
+ y = [margin, (frame['h'] - h) / 2, frame['h'] - h - margin][vy]
+ return _opt(op, 'x', path, x), _opt(op, 'y', path, y)
+
+
+def _add_layer(doc, layer, x, y, angle):
+ """Insert a layer whose box is at (x, y) in the frame, upright on screen."""
+ c = doc['crop']
+ centre = _apply(np.linalg.inv(orient_matrix(doc)), c['x'] + x + layer['w'] / 2, c['y'] + y + layer['h'] / 2)
+ mirrored = doc['flipX'] != doc['flipY']
+ layer.update(cx=float(centre[0]), cy=float(centre[1]), rotation=(-angle if mirrored else angle) - doc['rotate'],
+ flipX=doc['flipX'], flipY=doc['flipY'])
+ index = next((i for i, l in enumerate(doc['layers']) if l['id'] == doc['active']), 0)
+ doc['layers'].insert(index + 1, layer)
+ doc['active'] = layer['id']
+
+
+def _common(op, path, name):
+ return dict(name=str(op.get('name') or name), visible=True, locked=False,
+ opacity=_opt(op, 'opacity', path, 1, 0, 1), blend=_choice(op, 'blend', path, BLENDS, 'source-over'),
+ ops=[], mask=None, adjust=empty_adjust())
+
+
+SPEC = {
+ 'crop': dict(keys=('ratio', 'x', 'y', 'width', 'height', 'anchor', 'zoom'),
+ about='Keep part of the canvas: a ratio (video, original, free, W:H) placed by anchor and zoom, '
+ 'or an explicit x/y/width/height box in canvas pixels.'),
+ 'rotate': dict(keys=('degrees',),
+ about='Turn the canvas clockwise by 90, 180 or 270 degrees (negative turns left).'),
+ 'flip': dict(keys=('axis',), about='Mirror the canvas horizontally or vertically.'),
+ 'pad': dict(keys=('to', 'left', 'top', 'right', 'bottom', 'color'),
+ about='Grow the frame around the current crop to a ratio, or by pixels per side; '
+ 'beyond the picture the background colour shows.'),
+ 'fit': dict(keys=('width', 'height', 'mode', 'color'),
+ about='Give the frame the shape of width x height: cover crops, contain pads. '
+ 'Pixel size stays the source resolution; the video scales keyframes itself.'),
+ 'adjust': dict(keys=('layer',) + ADJUSTMENTS, about='Set light, colour and effect adjustments of a layer.'),
+ 'overlay': dict(keys=('image', 'x', 'y', 'width', 'height', 'scale', 'anchor', 'margin', 'rotation',
+ 'opacity', 'blend', 'name'),
+ about='Add an image layer (another media file) placed in the frame.'),
+ 'text': dict(keys=('text', 'x', 'y', 'anchor', 'margin', 'size', 'color', 'font', 'weight', 'align', 'shadow',
+ 'outline', 'line_height', 'rotation', 'opacity', 'blend', 'name'),
+ about='Add a text layer.'),
+ 'shape': dict(keys=('type', 'x', 'y', 'width', 'height', 'from', 'to', 'anchor', 'margin', 'fill', 'stroke',
+ 'stroke_width', 'radius', 'rotation', 'opacity', 'blend', 'name'),
+ about='Add a rectangle, ellipse or line layer.'),
+}
+SPEC['extend'] = SPEC['pad']
+SPEC['remove_text'] = dict(keys=('x', 'y', 'width', 'height', 'text_height'),
+ about='Remove burned-in captions inside a box of the frame (default: its lower 40%): '
+ 'white letters and their outline are filled from the picture around them, and '
+ 'everything else in the box stays. A box without such text is left as it is.')
+
+
+def _remove_text(doc, op, path, frame):
+ """A captions-only heal stroke on the picture, swept row by row over a box of the frame."""
+ fw, fh = frame['w'], frame['h']
+ x = min(_opt(op, 'x', path, 0, 0), fw - 1)
+ y = min(_opt(op, 'y', path, fh * .6, 0), fh - 1)
+ width = min(_opt(op, 'width', path, fw - x, positive=True), fw - x)
+ height = min(_opt(op, 'height', path, fh - y, positive=True), fh - y)
+ th = _opt(op, 'text_height', path, max(12, min(fw, fh) / 16), 4, 2000)
+ layer = doc['layers'][0]
+ to_doc, to_layer = np.linalg.inv(orient_matrix(doc)), np.linalg.inv(layer_matrix(layer))
+
+ def local(px, py):
+ lx, ly = _apply(to_layer, *_apply(to_doc, frame['x'] + px, frame['y'] + py))
+ return [round(float(lx) / layer['nw'], 5), round(float(ly) / layer['nh'], 5)]
+ # A brush as tall as the letters, in rows 0.8 of it apart, so the box is covered.
+ rows = max(1, math.ceil(max(0, height - th) / (th * .8)) + 1)
+ pts = []
+ for i in range(rows):
+ ry = y + height / 2 if height <= th else y + th / 2 + (height - th) * (i / (rows - 1) if rows > 1 else 0)
+ ends = [x + width / 2] * 2 if width <= th else [x + th / 2, x + width - th / 2]
+ for px in (ends[::-1] if i % 2 else ends):
+ pts.append(local(px, ry))
+ size = th * (layer['nw'] / layer['w']) / min(layer['nw'], layer['nh'])
+ layer['ops'].append({'id': uid('o'), 'type': 'stroke', 'tool': 'heal', 'text': True, 'pts': pts, 'size': size,
+ 'hardness': 1, 'opacity': 1})
+ return doc
+
+
+def _layer_ref(doc, value, path):
+ if value in (None, 'base'):
+ return doc['layers'][0]
+ if value == 'last':
+ return doc['layers'][-1]
+ for layer in doc['layers']:
+ if layer['name'] == value or layer['id'] == value:
+ return layer
+ raise EditError(path, 'no layer named %r' % (value,))
+
+
+def compile_recipe(recipe, *, source=None, source_size=None, target=None, resolve=None, base=None):
+ """An editor document for {"operations": [...]}, applied in order.
+
+ source is the original image file (the base layer), source_size its
+ upright (width, height); target the video's (width, height) for ratio
+ 'video'; resolve(file) -> path is needed to size overlay images; base
+ continues an existing document instead of starting from the original.
+ Positions are pixels of the current frame (the crop), from its top left.
+ Overlay files go through resolve, which must refuse paths outside the
+ media folder.
+ """
+ if not isinstance(recipe, dict):
+ raise EditError('/', 'a recipe is an object with operations')
+ for key in recipe:
+ if key not in ('operations',):
+ raise EditError('/' + key, 'unknown key')
+ operations = recipe.get('operations')
+ if not isinstance(operations, list) or not 1 <= len(operations) <= MAX_OPERATIONS:
+ raise EditError('/operations', 'give 1 to %d operations' % MAX_OPERATIONS)
+ if target is not None:
+ target = (_number(target[0], '/target/0', positive=True), _number(target[1], '/target/1', positive=True))
+ if base is not None:
+ _check(base)
+ import copy
+ doc = copy.deepcopy(base)
+ else:
+ if not isinstance(source, str) or not source:
+ raise EditError('/source', 'name the original image file')
+ if not isinstance(source_size, (list, tuple)) or len(source_size) != 2:
+ raise EditError('/source_size', 'give the image width and height')
+ w, h = source_size
+ doc = new_document(source, _number(w, '/source_size/0', positive=True),
+ _number(h, '/source_size/1', positive=True))
+ for i, op in enumerate(operations):
+ path = '/operations/%d' % i
+ if not isinstance(op, dict) or op.get('op') not in SPEC:
+ raise EditError(path + '/op', 'use one of %s' % ', '.join(SPEC))
+ _check_keys(op, SPEC[op['op']]['keys'], path)
+ doc = _operation(doc, op, path, target, resolve)
+ _check(doc)
+ return doc
+
+
+def _operation(doc, op, path, target, resolve):
+ kind = op['op']
+ frame = doc['crop']
+ if kind == 'rotate':
+ degrees = op.get('degrees')
+ if degrees not in (90, 180, 270, -90, -180, -270):
+ raise EditError(path + '/degrees', 'use 90, 180 or 270 (negative turns left)')
+ for _ in range(abs(degrees) // 90):
+ doc = _turn(doc, 'cw' if degrees > 0 else 'ccw', target)
+ return doc
+ if kind == 'flip':
+ axis = _choice(op, 'axis', path, ('horizontal', 'vertical'), 'horizontal')
+ return _turn(doc, 'flipX' if axis == 'horizontal' else 'flipY', target)
+ if kind == 'crop':
+ r = canvas_rect(doc)
+ if any(op.get(k) is not None for k in ('x', 'y', 'width', 'height')):
+ if op.get('anchor') is not None or op.get('zoom') is not None:
+ raise EditError(path, 'give either a box (x, y, width, height) or a ratio with anchor and zoom')
+ x, y = _opt(op, 'x', path, 0, 0), _opt(op, 'y', path, 0, 0)
+ w = _opt(op, 'width', path, r['w'] - x, positive=True)
+ h = _opt(op, 'height', path, r['h'] - y, positive=True)
+ if x + w > r['w'] + 1e-6 or y + h > r['h'] + 1e-6:
+ raise EditError(path, 'the box leaves the %g x %g canvas' % (r['w'], r['h']))
+ ratio = op.get('ratio', 'free')
+ if ratio != 'free':
+ aspect = _aspect(ratio, r, target, path + '/ratio')
+ if abs(w / h - aspect) > .01 * aspect:
+ raise EditError(path + '/ratio', 'the box is not %s' % ratio)
+ doc = dict(doc, crop=dict(x=r['x'] + x, y=r['y'] + y, w=w, h=h),
+ ratio=ratio if ratio in RATIO_IDS else 'free')
+ return doc
+ ratio = op.get('ratio', 'original')
+ aspect = _aspect(ratio, r, target, path + '/ratio')
+ zoom = _opt(op, 'zoom', path, 1, 1, 100)
+ fitted = _fit_rect(aspect, r)
+ w, h = fitted['w'] / zoom, fitted['h'] / zoom
+ x, y = _place(dict(anchor=op.get('anchor', 'center')), path, r, w, h)
+ return dict(doc, crop=dict(x=r['x'] + x, y=r['y'] + y, w=w, h=h), ratio=ratio if ratio in RATIO_IDS else 'free')
+ if kind in ('pad', 'extend', 'fit'):
+ color = _color_key(op, 'color', path, doc['extend'].get('color') or '#000000')
+ c = doc['crop']
+ if kind == 'fit':
+ width, height = _opt(op, 'width', path, positive=True), _opt(op, 'height', path, positive=True)
+ if width is None or height is None:
+ raise EditError(path, 'fit needs width and height')
+ mode = _choice(op, 'mode', path, ('cover', 'contain'), 'cover')
+ same = target and abs(width / height - target[0] / target[1]) < 1e-9
+ ratio = 'video' if same else '%g:%g' % (width, height)
+ if mode == 'cover':
+ return _operation(doc, dict(op='crop', ratio=ratio), path, target or (width, height), resolve)
+ return _operation(doc, dict(op='pad', to=ratio, color=color), path, target or (width, height), resolve)
+ sides = [op.get(k) for k in ('left', 'top', 'right', 'bottom')]
+ if op.get('to') is not None:
+ if any(s is not None for s in sides):
+ raise EditError(path, 'give either to or pixels per side')
+ aspect = _aspect(op['to'], c, target, path + '/to')
+ l = t = r = b = 0
+ if aspect and c['w'] / c['h'] < aspect:
+ extra = _round(c['h'] * aspect - c['w'])
+ l = math.floor(extra / 2)
+ r = extra - l
+ elif aspect:
+ extra = _round(c['w'] / aspect - c['h'])
+ t = math.floor(extra / 2)
+ b = extra - t
+ ratio = op['to'] if op['to'] in RATIO_IDS and op['to'] != 'original' else 'free'
+ else:
+ l, t, r, b = (_opt(op, k, path, 0, 0, 20000) for k in ('left', 'top', 'right', 'bottom'))
+ ratio = 'free'
+ crop = dict(x=c['x'] - l, y=c['y'] - t, w=c['w'] + l + r, h=c['h'] + t + b)
+ (ow, oh), e = oriented_size(doc), doc['extend']
+ extend = dict(l=max(e['l'], -crop['x']), t=max(e['t'], -crop['y']), r=max(e['r'], crop['x'] + crop['w'] - ow),
+ b=max(e['b'], crop['y'] + crop['h'] - oh), color=color)
+ return dict(doc, extend=extend, crop=crop, ratio=ratio)
+ import copy
+ doc = copy.deepcopy(doc)
+ if kind == 'remove_text':
+ return _remove_text(doc, op, path, frame)
+ if kind == 'adjust':
+ layer = _layer_ref(doc, op.get('layer'), path + '/layer')
+ if layer['kind'] not in ('image', 'paint'):
+ raise EditError(path + '/layer', 'only image and paint layers take adjustments')
+ for key in ADJUSTMENTS:
+ if op.get(key) is not None:
+ layer['adjust'][key] = _number(op[key], '%s/%s' % (path, key), *RANGES[key])
+ return doc
+ rotation = _opt(op, 'rotation', path, 0, -360, 360)
+ if kind == 'overlay':
+ if not isinstance(op.get('image'), str) or not op['image']:
+ raise EditError(path + '/image', 'name the media file to place')
+ if resolve is None:
+ raise EditError(path + '/image', 'overlay images cannot be read here')
+ try:
+ with Image.open(resolve(op['image'])) as image:
+ nw, nh = ImageOps.exif_transpose(image).size
+ except (OSError, ValueError, KeyError):
+ raise EditError(path + '/image', 'cannot read image %r' % (op['image'],)) from None
+ width, height = _opt(op, 'width', path, positive=True), _opt(op, 'height', path, positive=True)
+ scale = _opt(op, 'scale', path, positive=True)
+ if scale is not None and (width or height):
+ raise EditError(path + '/scale', 'give scale or a width/height, not both')
+ if width is None and height is None:
+ s = scale if scale is not None else min(1, frame['w'] * .66 / nw, frame['h'] * .66 / nh)
+ width, height = nw * s, nh * s
+ elif width is None:
+ width = height * nw / nh
+ elif height is None:
+ height = width * nh / nw
+ layer = dict(id=uid('l'), kind='image', src=op['image'], w=width, h=height, nw=nw, nh=nh,
+ **_common(op, path, Path(op['image']).name))
+ x, y = _place(op, path, frame, width, height)
+ _add_layer(doc, layer, x, y, rotation)
+ return doc
+ if kind == 'text':
+ content = op.get('text')
+ if not isinstance(content, str) or not content.strip() or len(content) > 2000:
+ raise EditError(path + '/text', 'give 1 to 2000 characters of text')
+ size = _opt(op, 'size', path, max(16, _round(min(doc['width'], doc['height']) / 12)), 6, 2000)
+ outline = op.get('outline', False)
+ if outline is True:
+ outline = '#000000'
+ if outline is not False:
+ _color(outline, path + '/outline')
+ if op.get('shadow', True) not in (True, False):
+ raise EditError(path + '/shadow', 'must be true or false')
+ text = dict(content=content, font=_choice(op, 'font', path, tuple(FONTS), 'sans'), size=size,
+ color=_color_key(op, 'color', path, '#ffffff'), weight=_choice(op, 'weight', path, (400, 700), 700),
+ align=_choice(op, 'align', path, ('left', 'center', 'right'), 'left'),
+ shadow=op.get('shadow', True), outline=outline,
+ lineHeight=_opt(op, 'line_height', path, 1.25, .5, 4))
+ measured = measure_text(text)
+ layer = dict(id=uid('l'), kind='text', text=text, w=measured['nw'], h=measured['nh'], **measured,
+ **_common(op, path, 'Text'))
+ x, y = _place(op, path, frame, layer['w'], layer['h'])
+ _add_layer(doc, layer, x, y, rotation)
+ return doc
+ # shape
+ kind = _choice(op, 'type', path, ('rect', 'ellipse', 'line'), 'rect')
+ width = _opt(op, 'stroke_width', path, 6, 1, 400)
+ fill = _color_key(op, 'fill', path, None if kind == 'line' else '#ffffff')
+ stroke = _color_key(op, 'stroke', path, '#ffffff' if kind == 'line' else None)
+ if kind == 'line':
+ for key in ('x', 'y', 'width', 'height', 'anchor', 'margin', 'rotation', 'radius'):
+ if op.get(key) is not None:
+ raise EditError('%s/%s' % (path, key), 'a line is placed by from and to')
+ ends = [op.get('from'), op.get('to')]
+ if not all(isinstance(p, list) and len(p) == 2 for p in ends):
+ raise EditError(path, 'a line needs from and to as [x, y] in the frame')
+ (x1, y1), (x2, y2) = [(_number(p[0], '%s/%s/0' % (path, k)), _number(p[1], '%s/%s/1' % (path, k)))
+ for k, p in zip(('from', 'to'), ends)]
+ if fill:
+ raise EditError(path + '/fill', 'a line has no fill')
+ w, h = math.hypot(x2 - x1, y2 - y1), max(width * 2, 8)
+ if w < 1:
+ raise EditError(path, 'the line is too short')
+ rotation = math.degrees(math.atan2(y2 - y1, x2 - x1))
+ x, y = (x1 + x2) / 2 - w / 2, (y1 + y2) / 2 - h / 2
+ else:
+ if op.get('from') is not None or op.get('to') is not None:
+ raise EditError(path, 'from and to are for lines; give x, y, width and height')
+ w, h = _opt(op, 'width', path, positive=True), _opt(op, 'height', path, positive=True)
+ if w is None or h is None:
+ raise EditError(path, 'a %s needs width and height' % kind)
+ x, y = _place(op, path, frame, w, h)
+ if not fill and not stroke:
+ raise EditError(path, 'give a fill or a stroke colour')
+ shape = dict(type=kind, fill=fill or None, stroke=stroke or None, width=width,
+ radius=_opt(op, 'radius', path, 0, 0, 2000) if kind == 'rect' else 0)
+ layer = dict(id=uid('l'), kind='shape', shape=shape, w=w, h=h, nw=_size(w), nh=_size(h),
+ **_common(op, path, {'rect': 'Rectangle', 'ellipse': 'Ellipse', 'line': 'Line'}[kind]))
+ _add_layer(doc, layer, x, y, rotation)
+ return doc
+
+
+def describe():
+ """Supported recipe operations, keys and ranges, for agents and schemas."""
+ number, frame = {'type': 'number'}, 'pixels in the current frame (the crop), from its top left'
+ place = {'x': dict(number, about=frame), 'y': dict(number, about=frame),
+ 'anchor': {'enum': list(ANCHORS), 'default': 'center', 'about': 'used when x/y are absent'},
+ 'margin': dict(number, minimum=0, default=0)}
+ look = {'rotation': dict(number, minimum=-360, maximum=360, default=0, about='degrees clockwise on screen'),
+ 'opacity': dict(number, minimum=0, maximum=1, default=1),
+ 'blend': {'enum': list(BLENDS), 'default': 'source-over'},
+ 'name': {'type': 'string', 'about': 'layer name; adjust can refer to it'}}
+ ratio = {'type': 'string', 'about': "'video', 'original', 'free' or W:H such as 16:9 or 2.39:1"}
+ keys = {
+ 'crop': {'ratio': dict(ratio, default='original'), 'x': number, 'y': number,
+ 'width': dict(number, exclusiveMinimum=0), 'height': dict(number, exclusiveMinimum=0),
+ 'anchor': place['anchor'], 'zoom': dict(number, minimum=1, maximum=100, default=1)},
+ 'rotate': {'degrees': {'enum': [90, 180, 270, -90, -180, -270]}},
+ 'flip': {'axis': {'enum': ['horizontal', 'vertical'], 'default': 'horizontal'}},
+ 'pad': {'to': ratio, **{k: dict(number, minimum=0, maximum=20000) for k in ('left', 'top', 'right', 'bottom')},
+ 'color': {'type': 'string', 'about': 'CSS colour of the added area', 'default': '#000000'}},
+ 'fit': {'width': dict(number, exclusiveMinimum=0), 'height': dict(number, exclusiveMinimum=0),
+ 'mode': {'enum': ['cover', 'contain'], 'default': 'cover'}, 'color': {'type': 'string'}},
+ 'adjust': {'layer': {'type': 'string', 'default': 'base', 'about': "'base', 'last' or a layer name"},
+ **{k: dict(number, minimum=RANGES[k][0], maximum=RANGES[k][1], default=0) for k in ADJUSTMENTS}},
+ 'overlay': {'image': {'type': 'string', 'about': 'media file (ComfyUI input path)'},
+ 'width': dict(number, exclusiveMinimum=0), 'height': dict(number, exclusiveMinimum=0),
+ 'scale': dict(number, exclusiveMinimum=0, about="multiplies the image's own pixel size"),
+ **place, **look},
+ 'text': {'text': {'type': 'string', 'maxLength': 2000}, **place,
+ 'size': dict(number, minimum=6, maximum=2000, about='pixels; default 1/12 of the shorter side'),
+ 'color': {'type': 'string', 'default': '#ffffff'}, 'font': {'enum': list(FONTS), 'default': 'sans'},
+ 'weight': {'enum': [400, 700], 'default': 700},
+ 'align': {'enum': ['left', 'center', 'right'], 'default': 'left'},
+ 'shadow': {'type': 'boolean', 'default': True},
+ 'outline': {'about': 'false, true (black) or a CSS colour', 'default': False},
+ 'line_height': dict(number, minimum=.5, maximum=4, default=1.25), **look},
+ 'shape': {'type': {'enum': ['rect', 'ellipse', 'line'], 'default': 'rect'},
+ 'width': dict(number, exclusiveMinimum=0), 'height': dict(number, exclusiveMinimum=0),
+ 'from': {'type': 'array', 'about': '[x, y] start of a line in the frame'},
+ 'to': {'type': 'array', 'about': '[x, y] end of a line in the frame'},
+ 'fill': {'type': ['string', 'null'], 'default': '#ffffff (none for lines)'},
+ 'stroke': {'type': ['string', 'null'], 'default': 'none (#ffffff for lines)'},
+ 'stroke_width': dict(number, minimum=1, maximum=400, default=6),
+ 'radius': dict(number, minimum=0, maximum=2000, default=0), **place, **look},
+ }
+ keys['extend'] = keys['pad']
+ keys['remove_text'] = {'x': dict(number, minimum=0, default=0, about=frame),
+ 'y': dict(number, minimum=0, about=frame + '; default 60% of the frame height'),
+ 'width': dict(number, exclusiveMinimum=0, about='default: to the right edge'),
+ 'height': dict(number, exclusiveMinimum=0, about='default: to the bottom edge'),
+ 'text_height': dict(number, minimum=4, maximum=2000,
+ about='pixels; about the caption letters\' height, default 1/16 of '
+ 'the shorter side')}
+ return {
+ 'document_version': 2, 'max_operations': MAX_OPERATIONS, 'max_pixels': MAX_PIXELS,
+ 'coordinates': 'Operations apply in order. Positions and sizes are ' + frame + '; crop boxes are pixels '
+ 'of the whole canvas. The saved picture is the crop at source resolution.',
+ 'operations': {name: {'about': SPEC[name]['about'], 'keys': keys[name]} for name in SPEC},
+ 'adjustments': {k: list(RANGES[k]) for k in ADJUSTMENTS},
+ 'blends': list(BLENDS), 'fonts': list(FONTS),
+ 'renders': ['image, paint, text and shape layers', 'opacity, blend modes, adjustments, layer masks',
+ 'brush, eraser, clone, heal (whole stroke or captions only) and blur strokes',
+ 'rectangle, ellipse, lasso and magic wand selections'],
+ 'differences': ['Text uses the editor\'s bundled fonts without their kerning, so a line can be a few '
+ 'pixels wider; the editor fits the text box again when it opens the picture. A browser '
+ 'picks the font per character; here the first font of the family list that has every '
+ 'character draws the whole text.'],
+ }
diff --git a/freevideo_engine/agent/editor_runtime.py b/freevideo_engine/agent/editor_runtime.py
new file mode 100644
index 0000000..6ee8802
--- /dev/null
+++ b/freevideo_engine/agent/editor_runtime.py
@@ -0,0 +1,347 @@
+"""Run the page's timeline rules (web/editor_*.js) on the server in QuickJS.
+
+The Agent edits a project with the same code the editor page runs. The rule
+modules are plain ES modules without page globals; this file links them into
+one script (QuickJS's Python binding has no module loader) and calls them with
+JSON in and JSON out, so results match Node byte for byte.
+"""
+from __future__ import annotations
+
+import json
+import re
+import threading
+from pathlib import Path
+
+WEB = Path(__file__).resolve().parents[2] / 'web'
+# Definition order only; evaluation starts at editor_actions like the page's
+# import does. editor_model and editor_text_model import each other: the
+# module still loading is reached only through a namespace import.
+MODULES = ('editor_picture_fields', 'editor_text_model', 'editor_model', 'editor_room', 'editor_actions',
+ 'editor_generation', 'editor_store')
+TIME_LIMIT = 5.0
+MEMORY_LIMIT = 256 * 2**20
+STACK_LIMIT = 4 * 2**20
+
+_IMPORT = re.compile(r"^import\s+(\*\s+as\s+([\w$]+)|\{([^}]*)\})\s+from\s+'\./([\w]+)\.js';[ \t]*$", re.M)
+_EXPORT = re.compile(r'^export\s+((?:async\s+)?(?:function\*?|const|let|class)\s+([\w$]+))', re.M)
+_LEFT = re.compile(r'^\s*(?:import|export)\b', re.M)
+
+# structuredClone for the plain JSON-like values the rules copy, and the newer array/string/object
+# methods the browser has and this engine lacks (the rules are written for the browser).
+_PRELUDE = r'''
+(() => {
+ const define = (target, name, value) => {
+ if (typeof target[name] !== 'function') Object.defineProperty(target, name, {value, writable: true, configurable: true});
+ };
+ function at(index) {
+ const n = Math.trunc(index) || 0, i = n < 0 ? this.length + n : n;
+ return i >= 0 && i < this.length ? this[i] : undefined;
+ }
+ define(Array.prototype, 'at', at);
+ define(String.prototype, 'at', at);
+ define(Array.prototype, 'findLast', function (test, self) {
+ for (let i = this.length - 1; i >= 0; i--) if (test.call(self, this[i], i, this)) return this[i];
+ return undefined;
+ });
+ define(Array.prototype, 'findLastIndex', function (test, self) {
+ for (let i = this.length - 1; i >= 0; i--) if (test.call(self, this[i], i, this)) return i;
+ return -1;
+ });
+ define(Array.prototype, 'toSorted', function (compare) { return [...this].sort(compare); });
+ define(Array.prototype, 'toReversed', function () { return [...this].reverse(); });
+ define(Array.prototype, 'with', function (index, value) {
+ const copy = [...this], n = Math.trunc(index) || 0, i = n < 0 ? copy.length + n : n;
+ if (i < 0 || i >= copy.length) throw new RangeError('Invalid index');
+ copy[i] = value;
+ return copy;
+ });
+ define(Object, 'hasOwn', (value, key) => Object.prototype.hasOwnProperty.call(value, key));
+})();
+const structuredClone = value => {
+ if (value === null || typeof value !== 'object') return value;
+ if (Array.isArray(value)) return value.map(structuredClone);
+ if (value instanceof Map) return new Map([...value].map(([k, v]) => [structuredClone(k), structuredClone(v)]));
+ if (value instanceof Set) return new Set([...value].map(structuredClone));
+ const copy = {};
+ for (const key of Object.keys(value)) copy[key] = structuredClone(value[key]);
+ return copy;
+};
+const __modules = new Map(), __factories = new Map();
+const __define = (name, factory) => __factories.set(name, factory);
+const __load = name => {
+ if (__modules.has(name)) return __modules.get(name);
+ const exports = Object.create(null);
+ __modules.set(name, exports);
+ __factories.get(name)(exports);
+ return exports;
+};
+'''
+
+# editor_store is the page's HTTP module; only its pure capability arithmetic is
+# used here, and it is loaded on first use, never at start.
+# One call: {fn, record, args, parse} -> {ok, value} | {ok: false, error: {code, message}}.
+_ENTRY = r'''
+globalThis.__call = text => {
+ const request = JSON.parse(text), model = __load('editor_model'), actions = __load('editor_actions');
+ const table = request.module === 'model' ? model : actions;
+ if (!Object.prototype.hasOwnProperty.call(table, request.fn) || typeof table[request.fn] !== 'function')
+ return JSON.stringify({ok: false, error: {code: 'unknown_function', message: String(request.fn)}});
+ try {
+ const record = request.parse === false ? request.record : model.parse(request.record);
+ const value = table[request.fn](record, ...(request.args || []));
+ return JSON.stringify({ok: true, value: request.serialize ? model.serialize(value) : value});
+ } catch (error) {
+ if (error instanceof model.EditError) return JSON.stringify({ok: false, error: {code: error.code, message: error.message}});
+ throw error;
+ }
+};
+
+// The Agent's operation batch: every operation runs on the result of the one
+// before; the first rejection stops the batch and nothing is returned to save.
+globalThis.__batch = text => {
+ const {project, operations} = JSON.parse(text), model = __load('editor_model'), actions = __load('editor_actions');
+ const by = {by: 'agent'}, results = [];
+ const ids = record => new Set(record.tracks.flatMap(track => track.clips.map(clip => clip.id)));
+ let record;
+ try { record = model.parse(project); }
+ catch (error) {
+ if (error instanceof model.EditError) return JSON.stringify({ok: false, index: null, error: {code: error.code, message: error.message}});
+ throw error;
+ }
+ for (let index = 0; index < operations.length; index++) {
+ const op = operations[index], before = ids(record), result = {};
+ try {
+ // The page acts on every track at the playhead when nothing is selected;
+ // the Agent always names the parts, and only parts of this revision.
+ if ('clip_ids' in op && !(Array.isArray(op.clip_ids) && op.clip_ids.length && op.clip_ids.every(id => before.has(id))))
+ throw new model.EditError('missing');
+ if ('clip_id' in op && !before.has(op.clip_id)) throw new model.EditError('missing');
+ // Likewise a cut never falls back to another part under the frame.
+ if ((op.op === 'split' || op.op === 'trim') && !(Number.isSafeInteger(op.frame) && actions.linkedIds(record, op.clip_ids)
+ .some(id => { const clip = model.find(record, id); return clip.start < op.frame && op.frame < clip.start + clip.frames; })))
+ throw new model.EditError('range');
+ switch (op.op) {
+ case 'insert': record = model.insertSource(record, {...op.media, at: op.at ?? model.duration(record)}); break;
+ case 'split': record = actions.splitAt(record, op.clip_ids, op.frame, by); break;
+ case 'trim': record = actions.trimAt(record, op.clip_ids, op.frame, op.edge, by); break;
+ case 'remove': record = actions.removeParts(record, op.clip_ids); break;
+ case 'remove_gaps': {
+ const value = actions.removeGaps(record, op.gap ?? null);
+ record = value.record; result.removed = value.removed; result.skipped = value.skipped; break;
+ }
+ case 'duplicate': record = actions.duplicateParts(record, op.clip_ids).record; break;
+ case 'copy': record = actions.copyTo(record, op.clip_ids, op.at).record; break;
+ case 'move': record = actions.moveParts(record, op.clip_ids, {frames: op.frames, track: null}); break;
+ case 'describe': record = model.describe(record, actions.linkedIds(record, op.clip_ids), op.text, by); break;
+ case 'set_ref': record = model.setRef(record, actions.linkedIds(record, op.clip_ids), op.ref); break;
+ case 'use_version': record = model.restoreVersion(record, op.clip_id, op.index, by); break;
+ default: throw new model.EditError('invalid', 'unknown operation');
+ }
+ } catch (error) {
+ if (!(error instanceof model.EditError)) throw error;
+ return JSON.stringify({ok: false, index, error: {code: error.code, message: error.message,
+ ...(error.track !== undefined ? {track: error.track} : {})}});
+ }
+ result.new_clip_ids = [...ids(record)].filter(id => !before.has(id));
+ results.push(result);
+ }
+ return JSON.stringify({ok: true, project: model.serialize(record), results});
+};
+
+// Generation, as the page's actions.generate does it (web/editor.js). 'plan'
+// marks the parts to make and returns the prepared project and the source keys
+// whose files the request continues from; 'request' builds the chain's blocks.
+globalThis.__generation = text => {
+ const request = JSON.parse(text), model = __load('editor_model');
+ const fail = error => {
+ if (!(error instanceof model.EditError)) throw error;
+ return JSON.stringify({ok: false, error: {code: error.code, message: error.message,
+ ...(error.track !== undefined ? {track: error.track} : {})}});
+ };
+ try {
+ const record = model.parse(request.project);
+ if (request.mode === 'request') {
+ const value = model.generationRequest(record, request.ids, {text: request.text, paths: request.paths});
+ return JSON.stringify({ok: true, blocks: value.blocks.map(({before, ...block}) => block)});
+ }
+ const store = __load('editor_store'), generation = __load('editor_generation');
+ const size = generation.generationSize(record), target = request.target, words = request.text;
+ const reply = request.capability, ready = reply && (!reply.status || reply.status === 'ready');
+ const limits = ready ? store.capabilityPoints(reply, {...record, ...size})
+ : {maxSeconds: 15, maxFollowSeconds: 15, maxRequestFrames: null};
+ let range, selected = [];
+ if (target.clip_ids) {
+ const ids = new Set(record.tracks.flatMap(track => track.clips.map(clip => clip.id)));
+ if (!target.clip_ids.every(id => ids.has(id))) throw new model.EditError('missing');
+ if (target.clip_ids.some(id => __load('editor_text_model').isText(model.find(record, id))))
+ throw new model.EditError('unsupported');
+ selected = record.tracks[0].clips.filter(clip => target.clip_ids.includes(clip.id) || target.clip_ids.includes(clip.link));
+ if (!selected.length) throw new model.EditError('unsupported');
+ const start = Math.min(...selected.map(clip => clip.start));
+ range = {start, frames: Math.max(...selected.map(clip => clip.start + clip.frames)) - start};
+ } else range = {start: target.start, frames: target.frames, ...(target.parts ? {parts: target.parts} : {})};
+ // A part length the caller chose stays allowed, as the page keeps manual parts.
+ const parts = range.parts || [];
+ if (!Array.isArray(parts) || !parts.every(count => Number.isInteger(count) && count > 0)) throw new model.EditError('range');
+ const maxSeconds = Math.max(limits.maxSeconds, (parts[0] || 0) / model.FPS);
+ const maxFollowSeconds = Math.max(limits.maxFollowSeconds, ...parts.map(count => count / model.FPS));
+ const before = record.tracks[0].clips.find(clip => clip.start + clip.frames === range.start && clip.source && clip.extend && clip.in + clip.frames === clip.length);
+ if (!words.trim() && !before) throw new model.EditError('text');
+ const planned = selected.length && selected.every(clip => !clip.source && clip.pending && !['queued', 'running'].includes(clip.pending));
+ let next = planned ? model.startAttempt(record, selected.map(clip => clip.id), words, {by: 'agent'})
+ : model.planRange(record, {...range, target: 'both', text: words, by: 'agent', maxSeconds, maxFollowSeconds});
+ if (!record.tracks[0].clips.length && words.trim()) next = model.rename(next, model.truncateText(words.trim(), 40));
+ const ids = next.tracks[0].clips.filter(clip => clip.start >= range.start && clip.start < range.start + range.frames
+ && clip.pending && !['queued', 'running'].includes(clip.pending)).map(clip => clip.id);
+ const prepared = model.prepare(next, ids), starts = new Set(ids.map(id => model.find(prepared, id).start));
+ const keys = prepared.tracks[0].clips.filter(clip => clip.source && !ids.includes(clip.id) && starts.has(clip.start + clip.frames))
+ .map(clip => clip.source.kind + ':' + clip.source.id);
+ return JSON.stringify({ok: true, project: model.serialize(prepared), ids, keys: [...new Set(keys)], size,
+ max_request_frames: limits.maxRequestFrames});
+ } catch (error) { return fail(error); }
+};
+
+// A chain's state into the project, as the page's deliverChain does: finished
+// blocks fill their parts, failed ones fail them, stopped ones settle. Each
+// done block carries the source facts the server read for its file.
+globalThis.__deliver = text => {
+ const {project, ids, job, chain, sources, assign, settle} = JSON.parse(text), model = __load('editor_model');
+ let record = model.parse(project);
+ const mismatched = [];
+ if (assign) record = model.assignJob(record, ids, job, {prepared: model.parse(assign)});
+ if (settle) record = model.settle(record, ids.filter(id => model.attemptClip(record, id)?.job === job), settle);
+ for (const block of (chain && chain.blocks) || []) {
+ const clip = model.attemptClip(record, block.id);
+ if (!clip || clip.job !== job) continue;
+ if (block.state === 'done' && block.output) {
+ const metadata = sources[block.output];
+ const result = {job, source: {kind: 'generated', id: block.output}, frames: metadata?.frames || block.inputs?.frames,
+ width: metadata?.width, height: metadata?.height,
+ skip_frames: block.skip_frames || 0, skip_audio_samples: block.skip_audio_samples || 0};
+ try {
+ if (!metadata || metadata.missing) throw new model.EditError('source');
+ record = model.fill(record, block.id, result);
+ } catch (error) {
+ if (!(error instanceof model.EditError)) throw error;
+ record = model.fail(record, block.id, 'result_mismatch', job); mismatched.push(block.id);
+ }
+ } else if (block.state === 'failed') {
+ const reason = /^[a-z_]{1,80}$/.test(block.error || '') ? block.error : 'generation_failed';
+ record = model.fail(record, block.id, reason, job);
+ } else if (['cancelled', 'interrupted'].includes(block.state)
+ || (['cancelled', 'interrupted', 'failed'].includes(chain.state) && block.state === 'pending')) {
+ record = model.settle(record, [block.id].filter(id => model.attemptClip(record, id)?.job === job), 'stopped');
+ } else if (block.state === 'running' && clip.pending !== 'running') record = model.settle(record, [block.id], 'running');
+ }
+ return JSON.stringify({ok: true, project: model.serialize(record), mismatched});
+};
+'''
+
+
+def _module(name, source):
+ exports = [match.group(2) for match in _EXPORT.finditer(source)]
+
+ def imported(match):
+ if match.group(2):
+ return f"const {match.group(2)} = __load('{match.group(4)}');"
+ names = [part.strip() for part in match.group(3).split(',') if part.strip()]
+ names = [re.sub(r'\s+as\s+', ': ', part) for part in names]
+ return f"const {{{', '.join(names)}}} = __load('{match.group(4)}');"
+
+ body = _EXPORT.sub(r'\1', _IMPORT.sub(imported, source))
+ if _LEFT.search(body):
+ raise ValueError(f'{name}.js: unsupported import or export form')
+ getters = ''.join(f"Object.defineProperty(__exports, '{export}', {{enumerable: true, get: () => {export}}});\n"
+ for export in exports)
+ return f"__define('{name}', function (__exports) {{\n'use strict';\n{getters}{body}\n}});\n"
+
+
+def bundle(web=WEB, modules=MODULES, start='editor_actions', entry=None, prelude=''):
+ """The linked script: prelude, every rule module, and the JSON entry point."""
+ parts = [_PRELUDE, prelude]
+ for name in modules:
+ parts.append(_module(name, (Path(web) / f'{name}.js').read_text(encoding='utf-8')))
+ # Evaluate from the entry, in the order ES module linking would use.
+ parts.append(f"__load('{start}');\n")
+ parts.append(_ENTRY if entry is None else entry)
+ return ''.join(parts)
+
+
+class ScriptRuntime:
+ """A QuickJS context with linked page modules. Calls are serialized by a
+ lock; a failed or interrupted call discards the context."""
+
+ def __init__(self, source):
+ self._source = source
+ self._lock = threading.Lock()
+ self._context = None
+
+ def _fresh(self):
+ try:
+ import quickjs
+ except ImportError:
+ from .jobs import JobError
+ raise JobError('not_ready', 'The editor rules engine is not installed; repair FreeVideo.') from None
+ context = quickjs.Context()
+ context.set_memory_limit(MEMORY_LIMIT)
+ context.set_max_stack_size(STACK_LIMIT)
+ context.set_time_limit(-1)
+ context.eval(self._source)
+ context.set_time_limit(TIME_LIMIT)
+ return context
+
+ def _text(self, name, request):
+ with self._lock:
+ if self._context is None:
+ self._context = self._fresh()
+ try:
+ return self._context.get(name)(request)
+ except Exception:
+ self._context = None
+ raise
+
+ def _entry(self, name, value):
+ return json.loads(self._text(name, json.dumps(value, ensure_ascii=False)))
+
+
+class EditorRuntime(ScriptRuntime):
+ """The timeline rules (web/editor_*.js)."""
+
+ def __init__(self, web=WEB):
+ super().__init__(bundle(web))
+
+ def call(self, fn, record, args=(), *, module='actions', parse=True, serialize=False):
+ request = json.dumps(dict(module=module, fn=fn, record=record, args=list(args), parse=parse,
+ serialize=serialize), ensure_ascii=False)
+ text = self._text('__call', request)
+ return json.loads(text), text
+
+ def batch(self, project, operations):
+ """Apply operations to a stored project; returns the parsed batch reply."""
+ return self._entry('__batch', dict(project=project, operations=operations))
+
+ def generation(self, **request):
+ """mode='plan' (project, target, text, capability) or mode='request' (project, ids, text, paths)."""
+ return self._entry('__generation', request)
+
+ def deliver(self, **request):
+ """Apply a chain's state to the parts of one generation (project, ids, job, chain, sources)."""
+ return self._entry('__deliver', dict(dict(chain=None, sources={}, assign=None, settle=None), **request))
+
+
+_RUNTIME = None
+_RUNTIME_LOCK = threading.Lock()
+
+
+def available():
+ """Whether this process can run the editor rules (project and image edits)."""
+ import importlib.util
+ return importlib.util.find_spec('quickjs') is not None
+
+
+def runtime():
+ global _RUNTIME
+ with _RUNTIME_LOCK:
+ if _RUNTIME is None:
+ _RUNTIME = EditorRuntime()
+ return _RUNTIME
diff --git a/freevideo_engine/agent/errors.py b/freevideo_engine/agent/errors.py
new file mode 100644
index 0000000..05ca04f
--- /dev/null
+++ b/freevideo_engine/agent/errors.py
@@ -0,0 +1,196 @@
+"""Stable Agent error vocabulary. Backend exception text is never a public message.
+
+Only implemented errors belong here. Future editor reasons (locked, overlap,
+range, text, audio_full, MissingGlyphs) stay reserved until those routes exist.
+"""
+from contextvars import ContextVar
+import math
+import re
+import uuid
+
+REQUEST_ID = ContextVar('agent_request_id', default=None)
+# The work session a token request belongs to (sessions.py); jobs and productions record it.
+SESSION = ContextVar('agent_session', default=None)
+# The operation digest a confirmation approves: method, route, path values and body without ref.
+CONFIRM = ContextVar('agent_confirm', default=None)
+# code: HTTP status, retryable, public message, concrete recovery action
+ERRORS = {
+ 'forbidden': (403, False, 'This caller cannot write this session event.', 'Only the user may stop or continue a session or answer a confirmation; steps are written by the server.'),
+ 'session_full': (409, False, 'This session has reached its event limit.', 'Create a new session with POST /freevideo/agent/v1/sessions.'),
+ 'page_session_required': (403, False, 'A valid page session and CSRF header are required.', 'Reload the page served by this FreeVideo instance and repeat the action.'),
+ 'redirect_forbidden': (403, False, 'A credentialed request cannot follow a cross-origin redirect.', 'Connect directly to the intended FreeVideo instance using its verified HTTP or HTTPS endpoint.'),
+ 'method_not_allowed': (405, False, 'This method is not registered for the requested endpoint.', 'Read GET /freevideo/agent/v1/openapi.json and use the documented method.'),
+ 'unauthorized': (401, False, 'The bearer token is missing or incorrect.', 'Read the token file described by GET /freevideo/agent/v1/connect and send Authorization: Bearer <token>.'),
+ 'no_token': (0, False, 'The local bearer token is unavailable.', 'Start FreeVideo, then read GET /freevideo/agent/v1/connect.'),
+ 'unreachable': (0, True, 'The FreeVideo server could not be reached.', 'Start FreeVideo and retry the request.'),
+ 'invalid_json': (400, False, 'The request body must contain valid JSON; malformed JSON was received.', 'Send a JSON object with Content-Type: application/json.'),
+ 'invalid_request': (422, False, 'The request contains invalid fields.', 'Correct every field listed in details and resend the request.'),
+ 'invalid_media': (422, False, 'The supplied media is invalid or unreadable.', 'Upload a readable image, video or audio file with a supported extension using POST /freevideo/agent/v1/media.'),
+ 'invalid_edit': (422, False, 'The image edit recipe or document is invalid.', 'Read GET /freevideo/agent/v1/schema and correct the edit recipe before retrying.'),
+ 'invalid_screenplay': (400, False, 'The screenplay contains invalid fields.', 'Fix every listed problem, then call freevideo_drama_plan again.'),
+ 'too_large': (413, False, 'The request exceeds the permitted byte limit.', 'Reduce the upload to the limit_bytes value in details and retry.'),
+ 'unsupported_media_type': (415, False, 'Content-Type must be application/json or a supported media upload.', 'Send JSON with Content-Type: application/json; use multipart/form-data only for POST /media.'),
+ 'not_found': (404, False, 'The requested job, film or asset does not exist.', 'List /freevideo/agent/v1/jobs, /drama or /library and select an existing ID.'),
+ 'no_video': (409, False, 'The source job has no finished video.', 'GET /freevideo/agent/v1/jobs/{id} and wait for a succeeded job containing result.video.'),
+ 'not_ready': (503, True, 'The FreeVideo installation is not ready.', 'Open Settings → Install / repair and finish setup. If the installation token is unsafe or incomplete, restore a regular non-symlink agent/token owned by your account, or remove that token and restart FreeVideo.'),
+ 'busy': (409, True, 'The requested resource is currently in use.', 'Wait retry_after_seconds, read GET /freevideo/agent/v1/queue, then retry the request.'),
+ 'conflict': (409, False, 'The requested operation conflicts with the current state.', 'Read the current job with GET /freevideo/agent/v1/jobs/{id} before retrying.'),
+ 'dependency_failed': (409, False, 'A required job did not succeed.', 'Read the dependency jobs, resume failed generation, then submit the dependent job with a new ref.'),
+ 'cancelled': (409, False, 'The job was cancelled.', 'Resume the generation with POST /freevideo/agent/v1/jobs/{id}/resume if you want it to continue.'),
+ 'lost': (409, True, 'The backend no longer has this job result.', 'Read the job; resume generation or submit a new non-generation job with a new ref.'),
+ 'interrupted': (409, True, 'The job was interrupted; completed blocks are retained.', 'POST /freevideo/agent/v1/jobs/{id}/resume to continue generation.'),
+ 'generation_failed': (409, True, 'Generation failed; completed blocks are retained.', 'POST /freevideo/agent/v1/jobs/{id}/resume to retry unfinished blocks.'),
+ 'insufficient_memory': (409, False, 'The requested generation exceeds the available memory budget.', 'Use the numerical alternatives in details or close other GPU applications, then submit a new job with a new ref.'),
+ 'out_of_memory': (409, True, 'The backend ran out of memory.', 'Close other GPU applications, then POST /freevideo/agent/v1/jobs/{id}/resume using the existing job ID.'),
+ 'vlm_unavailable': (503, True, 'The local vision-language service is unavailable.', 'Open Settings → Install / repair and install the prompt model, then retry.'),
+ 'vlm_failed': (409, True, 'The local vision-language request failed.', 'Submit the question again with a new ref.'),
+ 'model_missing': (503, False, 'The required local model is not installed.', 'Open Settings → Install / repair and install the prompt model, then retry.'),
+ 'ram_space': (409, True, 'The local model has insufficient available system memory.', 'Close other memory-intensive applications and retry with a new ref.'),
+ 'context_length': (422, False, 'The question and images exceed the local model context limit.', 'Shorten the question or send fewer images, then submit with a new ref.'),
+ 'invalid_output': (409, True, 'The backend output is invalid or unavailable.', 'Restore the saved output, then POST /freevideo/agent/v1/jobs/{id}/resume; for a vision-language job, submit a new request.'),
+ 'vlm_invalid_json': (409, True, 'The local model returned an answer that is not valid JSON.', 'Submit the question again with format=json and a new ref.'),
+ 'timeout': (504, True, 'The backend did not finish within its time limit.', 'Read the job before retrying; resume generation or resubmit the question with a new ref.'),
+ 'image_size': (422, False, 'The image exceeds the local model limit of 50 megapixels.', 'Resize the image to at most 50 megapixels, upload it, and submit with a new ref.'),
+ 'unsupported_media': (422, False, 'The local model accepts images, not this media type.', 'Use POST /freevideo/agent/v1/media/frame to extract an image before asking the model.'),
+ 'internal_error': (500, True, 'An internal error prevented this operation from completing.', 'Read the job list and report request_id if the error persists.'),
+ 'local_only': (403, False, 'This endpoint does not allow requests from this peer address.', 'Run the client on the FreeVideo computer and connect using its loopback address.'),
+ 'origin_forbidden': (403, False, 'Origin must match this FreeVideo instance; a different origin was received.', 'Open the page served by this FreeVideo instance, or use a local command-line client without Origin.'),
+ 'continuation_unavailable': (409, False, 'This backend cannot continue video blocks.', 'Use an independent shot with seconds<=15, or enable a backend with continuation inputs and resume.'),
+ 'not_resumable': (409, False, 'Only failed, interrupted or cancelled generation jobs can resume.', 'Read the job; wait for active jobs or submit a new job for a different request.'),
+ 'idempotency_conflict': (409, False, 'This idempotency key was already used for different request content.', 'Resend the original content with this key, or use a new ref for the changed request.'),
+ 'source_missing': (409, False, 'A completed source block is no longer available.', 'Restore the completed block before resuming, or submit a new job.'),
+ 'storage_unavailable': (503, True, 'The task receipt or media could not be stored.', 'Restore write access and free disk space, then retry the request.'),
+ 'invalid_range': (416, False, 'Range must select bytes inside this file; an invalid range was received.', 'Remove the Range header to download the complete file.'),
+ 'chain_unavailable': (503, True, 'The continuous generation backend is unavailable.', 'Start FreeVideo with the continuous generation backend enabled, then retry.'),
+ 'chain_missing': (409, True, 'The saved chain receipt is unavailable.', 'Restore the chain receipt and retry resume, or submit a new job.'),
+ 'join_failed': (409, True, 'The generated blocks could not be joined; completed blocks are retained.', 'POST /freevideo/agent/v1/jobs/{id}/resume to retry joining the completed blocks.'),
+ 'chain_rejected': (409, False, 'The continuous backend rejected this generation.', 'Read GET /freevideo/agent/v1/capabilities and submit a supported generation request.'),
+ 'invalid_wait': (422, False, 'wait must be a finite nonnegative number of seconds.', 'Use wait=0 or wait=25; larger valid values are clamped to 25 seconds.'),
+ 'invalid_resume': (422, False, 'resume accepts an empty object or an optional ref only.', 'Send {} or {"ref":"resume-1"}; submit a new job to change generation parameters.'),
+ 'invalid_library_id': (422, False, 'day and run must identify a saved library video.', 'GET /freevideo/agent/v1/library and use an existing YYYY-MM-DD/32-hex ID.'),
+ 'invalid_capabilities_query': (422, False, 'The capabilities query contains invalid size, task or material fields.', 'Use width=1344&height=768&task=t2va&adapters=0, or correct all fields in details.'),
+ 'unsupported_comfyui': (503, False, 'This ComfyUI version has no supported generation endpoint.', 'Open Settings → Install / repair to install a supported ComfyUI version.'),
+}
+
+# not_ready predates productions and also means installation-not-ready (503).
+# Preserve that runtime contract while the pure production code keeps its 409.
+PRODUCTION_STATUS = {'not_ready': 409}
+ERRORS.update({
+ 'unknown_shot': (404, False, 'The shot does not exist.', 'Use a shot id from the production view.'),
+ 'unknown_take': (404, False, 'The take does not exist.', 'Use a take number from this shot in the production view.'),
+ 'take_not_ready': (409, False, 'The take is stale or has not succeeded.', 'Choose a succeeded, non-stale take, or reshoot this shot.'),
+ 'chosen_by_user': (409, False, 'This shot was chosen by the user.', 'Leave this shot unchanged; only the user may change it.'),
+ 'nothing_to_cancel': (409, False, 'There are no unfinished takes or joins to cancel.', 'Choose completed takes, reshoot a shot, or finish the production.'),
+ 'not_allowed': (409, False, 'Only the user may stop or continue this film.', 'Wait for the user to stop or continue the film.'),
+ 'already_ended': (409, False, 'This film has already ended.', 'Use an unfinished, uncancelled production.'),
+ 'needs_confirmation': (409, False, 'The user must approve this operation first.', 'Wait with freevideo_wait (no id) for the user\'s answer; once approved, repeat the same call unchanged.'),
+ 'declined_by_user': (409, False, 'The user declined this operation.', 'Do not repeat this call; change the plan or ask the user what they want instead.'),
+ 'stopped_by_user': (409, False, 'The user stopped this session.', 'Wait for the user to continue the session; do not retry or start a new one.'),
+ 'reshoot_limit': (409, False, 'This shot reached its generation limit.', 'Choose the best existing take, rewrite the shot, or ask the user.'),
+ 'production_limit': (409, False, 'This film reached its child job limit.', 'Choose existing takes or ask the user how to reduce the film.'),
+ 'managed_by_production': (409, False, 'This job belongs to a film and cannot be resumed on its own.', 'This take belongs to a film; reshoot the shot or wait for the user to continue.'),
+ 'submit_interrupted': (409, True, 'The server stopped before it confirmed whether this take was submitted.', 'Reshoot this shot.'),
+})
+ERRORS.update({
+ 'stale_revision': (409, False, 'The card changed since you read it.', 'Apply your change to error.card and send its revision.'),
+ 'changed_by_user': (409, False, 'The user changed this part of the card.', "Keep the user's change; do not change it back. Ask the user if it must change."),
+ 'card_in_use': (409, False, 'An unfinished film uses this card.', 'Ask the user before deleting this card.'),
+ 'already_generating': (409, False, 'Reference pictures for this card are already being made.', 'Wait for error.job to end, then get the card.'),
+ 'project_changed': (409, False, 'The project changed since you read it.', 'Apply your operations to error.project and send its revision.'),
+ 'clip_busy': (409, True, 'A part in this operation is still generating.', 'Wait for its job to end, get the project, then send the operations again.'),
+ 'clip_locked': (409, False, 'A part in this operation is on a track the user locked.', 'Leave the locked track unchanged; ask the user to unlock it if it must change.'),
+ 'audio_full': (409, False, 'There is no free sound track for this operation.', 'Move or remove sound in error.project at that place, then retry.'),
+ 'overlap': (409, False, 'The operation would overlap parts that cannot move.', 'Choose another frame or move the parts in the way first.'),
+ 'missing_glyphs': (422, False, 'Text in the project uses characters the bundled fonts cannot draw.', 'Change the text of the parts listed in details, then export the new revision.'),
+ 'image_changed': (409, False, 'The image changed since you read it.', 'Apply your operations to error.image and send its revision.'),
+ 'layer_locked': (409, False, 'An operation changes a layer the user locked.', 'Leave the locked layer unchanged; ask the user to unlock it if it must change.'),
+ 'export_failed': (409, True, 'The export did not finish.', 'Read the project, then submit the export again with a new ref.'),
+})
+
+
+# Recovery is a function of the committed task and phase, not just an error code.
+RECOVERY = {
+ 'generate': 'POST /freevideo/agent/v1/jobs/{id}/resume to retry unfinished generation blocks.',
+ 'vlm': 'Submit the question again with a new ref.',
+ 'enhance': 'Submit the prompt enhancement again with a new ref.',
+ 'assemble': 'Submit the clip assembly again with a new ref.',
+ 'refine': 'Submit the second-pass generation again with a new ref.',
+ 'submission_unknown': 'Read the job list, then retry the original submission with the same ref.',
+}
+REPAIR = {
+ 'out_of_memory': 'Close other GPU applications first. ',
+ 'insufficient_memory': 'Close other GPU applications, or use the numerical alternatives in details and submit with a new ref. ',
+ 'storage_unavailable': 'Restore write access and free disk space first. ',
+ 'source_missing': 'Restore the missing source first. ',
+ 'chain_missing': 'Restore the saved chain receipt first. ',
+ 'not_ready': 'Open Settings → Install / repair first. ',
+ 'model_missing': 'Install the required prompt model using Settings → Install / repair first. ',
+ 'vlm_unavailable': 'Install or start the prompt model using Settings → Install / repair first. ',
+}
+
+
+def recovery(code, *, kind=None, stage='request', resumable=True):
+ if kind in RECOVERY and stage == 'terminal':
+ return REPAIR.get(code, '') + RECOVERY['refine' if kind == 'generate' and not resumable else kind]
+ if stage == 'submission_unknown' and code in ('internal_error', 'storage_unavailable', 'unreachable'):
+ return REPAIR.get(code, '') + RECOVERY['submission_unknown']
+ action = ERRORS[code][3]
+ if '/resume' in action:
+ return 'Read the job status; submit a corrected new request with a new ref if no resumable generation exists.'
+ return action
+
+
+def request_id():
+ return REQUEST_ID.get() or 'r-' + uuid.uuid4().hex
+
+
+def safe_details(value):
+ """Only schema-created diagnostics and numerical backend alternatives cross the boundary."""
+ if isinstance(value, list):
+ return [safe_details(v) for v in value]
+ if isinstance(value, dict):
+ return {k: (v if k == 'failure_kind' and v in ('allocation', 'gpu_oom', 'ram_pressure', 'invalid_inputs')
+ or k == 'confirm' and isinstance(v, str) and re.fullmatch(r'cf[0-9a-f]{10}', v)
+ else safe_details(v)) for k, v in value.items() if k in {
+ 'field', 'path', 'allowed', 'got', 'limit_bytes', 'block', 'total',
+ 'width', 'height', 'frames', 'seconds', 'failure_kind', 'alternatives', 'owner', 'agent', 'ui', 'count',
+ 'confirm'}}
+ if value is None or type(value) in (bool, int):
+ return value
+ if type(value) is float:
+ return value if math.isfinite(value) else str(value)
+ # Backend strings can contain paths, tokens and prompts. Validators mark
+ # their own messages separately; raw backend strings are never reflected.
+ return '[redacted]'
+
+
+def build(code, *, details=None, request=None, validation=False, message=None, next_action=None,
+ action_required=True, retry_after_seconds=None, owner=None, kind=None, stage='request', resumable=True):
+ code = code if code in ERRORS else 'internal_error'
+ _, retryable, default_message, _ = ERRORS[code]
+ action = recovery(code, kind=kind, stage=stage, resumable=resumable)
+ result = dict(code=code, message=message if validation and message else default_message,
+ details=(details or []) if validation else safe_details(details or []),
+ retryable=retryable, request_id=request or request_id(),
+ docs='/freevideo/agent/v1/guide#errors')
+ if action_required:
+ result['next'] = next_action if validation and next_action else action
+ if code == 'busy':
+ result['retry_after_seconds'] = retry_after_seconds or 1
+ result['details'].append(dict(owner=owner if owner in ('agent', 'ui') else 'ui'))
+ result['message'] += ' An Agent job is ahead.' if owner == 'agent' else ' A job in the user interface is ahead.'
+ return result
+
+
+def validation(errors, code='invalid_request'):
+ from .schema import diagnostic
+ rows = [e if e.get('_safe') else diagnostic('/<unknown>', 'a valid value', None) for e in errors]
+ rows = [{k: v for k, v in e.items() if k != '_safe'} for e in rows]
+ return build(code, details=rows, validation=True,
+ message='; '.join(e['message'] for e in rows),
+ next_action=' '.join(dict.fromkeys(e['next'] for e in rows)))
+
+
+def text(error):
+ return '%s: %s%s' % (error['code'], error['message'],
+ ' Next: ' + error['next'] if error.get('next') else '')
diff --git a/freevideo_engine/agent/forecast.py b/freevideo_engine/agent/forecast.py
new file mode 100644
index 0000000..0e65098
--- /dev/null
+++ b/freevideo_engine/agent/forecast.py
@@ -0,0 +1,39 @@
+"""Machine-local timing forecasts shared by planning and durable films."""
+import math
+
+
+def generation_estimate(port, spec, chain=None):
+ """Return (estimate, capability revision) for a normalized generation spec.
+
+ Every block needs matching history. Keep the plan endpoint's exclusions and
+ reasons here so a film never invents a time for unsupported conditioning.
+ """
+ from ..chain_plan import plan as chain_plan
+ chain = chain if chain is not None else chain_plan(spec['seconds'])
+ table = port.capability_snapshot(dict(width=str(spec['width']), height=str(spec['height']),
+ task=spec['task'], adapters='1' if spec['loras'] else '0'))
+ seconds = None
+ reason = table['status'] if table['status'] in ('computing', 'unavailable') else 'no_matching_estimate'
+ if table['status'] == 'ready' and not spec['preview'] and not spec['media']:
+ tier = table.get('tiers', {}).get(spec['quality'])
+ size = next((i for i, s in enumerate(table.get('sizes', []))
+ if (s['width'], s['height']) == (spec['width'], spec['height'])), None)
+ estimates = []
+ for block in chain['blocks']:
+ length = next((i for i, l in enumerate(table.get('lengths', [])) if l['frames'] == block['frames']), None)
+ estimate = None
+ if tier and size is not None and length is not None:
+ try:
+ estimate = tier['estimate_seconds'][size][length]
+ except (IndexError, KeyError, TypeError):
+ pass
+ if type(estimate) not in (int, float) or not math.isfinite(estimate) or estimate <= 0:
+ break
+ estimates.append(estimate)
+ if len(estimates) == len(chain['blocks']):
+ seconds = sum(estimates)
+ known = seconds is not None and seconds > 0
+ return (dict(status='ready' if known else 'unavailable', seconds=seconds if known else None,
+ basis=(table.get('diagnostics') or {}).get('basis'),
+ **({} if chain['single'] else {'scope': 'sum_of_blocks'}),
+ **({} if known else {'reason': reason})), table.get('revision'))
diff --git a/freevideo_engine/agent/guide.py b/freevideo_engine/agent/guide.py
new file mode 100644
index 0000000..ddc1d97
--- /dev/null
+++ b/freevideo_engine/agent/guide.py
@@ -0,0 +1,260 @@
+"""What an agent needs to write good FreeVideo prompts, served by GET /freevideo/agent/v1/guide.
+
+Summarised from MiniMax's h3-prompt-writing skill (linked below) and FreeVideo's
+own prompt rules; the enhancement job applies the same contract.
+"""
+from ..default_prompt import DEFAULT_PROMPT
+from .schema import CAST_OPERATIONS, DRAMA_OPERATIONS, IMAGE_OPERATIONS, PROJECT_OPERATIONS, SESSION_OPERATIONS
+
+SOURCE = 'https://github.com/MiniMax-AI/MiniMax-H3/tree/main/skills/h3-prompt-writing'
+
+GUIDE = {
+ 'source': SOURCE,
+ 'language': 'Write the sections in English. Keep dialogue, lyrics and visible on-screen text verbatim in '
+ 'their original language.',
+ 'tasks': {
+ 't2va': 'Text only: describe the whole audiovisual timeline.',
+ 'i2va': 'media.first: the image is the frame at 0.00 s; start from its style, subjects and layout, then '
+ 'develop forward.',
+ 'fl2va': 'media.first + media.last: describe one continuous path from the first frame to the last; '
+ 'prefer a single shot.',
+ 'l2va': 'media.last: infer a plausible opening and converge on the image at the end.',
+ 'ref2va': 'media.references (images, video, audio; experimental): use the six reference sections and '
+ 'label every subject.',
+ },
+ 'sections': {
+ 'base': ['integrated_multimodal_description', 'overall_soundscape', 'non_diegetic_music'],
+ 'ref2va': ['subject_definitions', 'summary', 'retention_analysis', 'detailed_description',
+ 'overall_soundscape', 'non_diegetic_music'],
+ 'format': 'Each section starts on its own line as "name: text", separated by one blank line, in this order.',
+ },
+ 'shots': [
+ 'Begin the description with [Shot 1] and the visual style and opening composition '
+ '(e.g. "Live-action, cinematic, a medium-wide shot frames ...").',
+ 'Later shots: "[Shot 2] At 00:03.500, the camera cuts to ...". Cut times strictly increase and stay inside '
+ 'the duration. Cut only for new information; use camera motion for small changes.',
+ 'Camera motion = type + optional amplitude + speed, written as prose: push in / pull out, pan, truck, tilt, '
+ 'pedestal, arc shot, tracking shot, static shot, zoom, POV, roll; "with small amplitude", "at slow speed".',
+ ],
+ 'dialogue': [
+ 'Speakers get stable IDs (S1), (S2) across shots; describe each voice when it first appears.',
+ 'Spoken words go inside <d>[Language] ...</d>, verbatim: The woman (S1) says: <d>[Chinese] 我们走吧。</d>',
+ 'Voiceover: "says in an off-screen voiceover: <d>...</d> while his lips remain completely closed."',
+ 'Visible text goes in double quotes: a neon sign reading "营业中". Never put spoken words in quotes: '
+ 'quoted words are drawn on screen.',
+ 'H3 may still caption spoken lines. When the shot should have no captions, end the description with '
+ '"No subtitles, no on-screen text." (or "No subtitles or captions." when the shot shows a sign or screen); '
+ 'it still happens now and then, so ask the VLM whether text is drawn '
+ 'over the picture and retake with another seed. A captioned frame that seeds the next shot can be cleaned '
+ 'with the edit recipe operation remove_text.',
+ ],
+ 'sound': [
+ 'overall_soundscape: 1-4 sentences of ambience, action sounds and breaths; N/A only for silence.',
+ 'non_diegetic_music: 1-3 sentences of instruments, tempo and dynamics, or N/A.',
+ ],
+ 'references': [
+ 'Tags are numbered per kind in reference order: <Picture 1>, <Picture 2>, <Video 1>, <Audio 1>. '
+ 'For keyframes the first frame is <Picture 1> and the last frame the next picture.',
+ 'Name subjects <Subject 1>, <Subject 2> in subject_definitions and reuse those labels in every section.',
+ 'Clips are cut to the generated length (at most 15 s); the job result lists any cut.',
+ ],
+ 'timing': [
+ 'Single-block frames are 24 fps on a 17n+5 grid (6 s -> 6.583 s, 10 s -> 10.125 s). '
+ 'Generation uses the continuous backend; longer requests split, continue and join automatically. '
+ 'Continuing (longer than 15 s, or continue_from) needs two-pass text generation: quality "light" '
+ 'or sampling.two_pass=true, no preview and no media. '
+ 'Multi-block output is cut to the planned duration. POST /plan shows the chain plan.',
+ 'Keep the described timeline inside the duration. 4-15 s is the tested range; longer is experimental.',
+ 'Width and height are multiples of 32. For a size the user names that is not, use the nearest multiple '
+ 'on each side (1000x560 -> 992x544 or 992x576); a rejected request names them.',
+ ],
+ 'agent_jobs': [
+ 'GET /capabilities reads the studio cache with the same size/task/material query parameters. '
+ 'status=computing includes retry_after_seconds; unknown plan estimates have seconds=null.',
+ 'GET /jobs/{id}?wait=25 waits at most 25 seconds and returns poll_after_ms. Poll the same ID; '
+ 'disconnecting a wait or SSE does not cancel generation.',
+ 'Jobs wait behind an active studio chain. GET /queue gives Agent/UI ownership and counts ahead, '
+ 'without studio prompts. POST /jobs/{id}/cancel cancels only this job.',
+ 'POST /jobs/{id}/resume continues failed, interrupted or cancelled generation; successful blocks stay. '
+ 'refine_from is the separate preview second pass. Active or succeeded jobs cannot resume.',
+ 'Results include the joined library_id and each block library_id/report_id. Fetch videos and thumbnails '
+ 'with the token at /library/{day}/{run}/file and /thumbnail. MCP freevideo_asset and CLI agent asset use HTTP.',
+ ],
+ 'editing_projects': [
+ 'GET /projects lists timelines shared with the editor page. First GET /projects/{id} to read revision and clip IDs.',
+ 'POST /projects/{id}/operations sends revision and 1-64 operations, using whole frames at 24 fps. The batch saves once or changes nothing.',
+ 'On 409 project_changed, recompute edits from error.project and its current_revision, then send a new request. On clip_busy wait for generation to finish.',
+ 'POST /projects/{id}/generate reserves pending parts for clip_ids or a start/frames range and fills them as the returned job finishes. POST /projects/{id}/export renders the revision you read; wait for its job.',
+ 'Reuse ref or Idempotency-Key only for the identical request. Source video/audio/thumbnail URLs require the same Agent token.',
+ ],
+ 'project_routes': [dict(operation=name, method=method, path=path, description=summary)
+ for name, (method, path, summary) in PROJECT_OPERATIONS.items()],
+ 'editing_images': [
+ 'POST /images opens a picture as the image editor does; GET /images/{id} reads its document (layers), selection and revision.',
+ 'POST /images/{id}/operations sends revision and 1-64 operations run with the page\'s own commands; the batch saves once or changes nothing. Layer IDs of new layers are in results[i].new_layer_ids.',
+ 'Positions and sizes are document pixels; brush points and sizes are fractions of the layer. Repair a picture with heal or clone on its own layer, even when it is locked: each stroke is a step of that layer that undo removes, and the source file never changes. '
+ 'A new paint layer is empty, so heal and clone there have nothing to work from; paint and gradients go on a paint layer above a locked picture.',
+ 'On 409 image_changed, recompute from error.image and its current_revision. POST /images/{id}/render makes a PNG input file from the revision you read; use the job result file as a picture source.',
+ ],
+ 'image_routes': [dict(operation=name, method=method, path=path, description=summary)
+ for name, (method, path, summary) in IMAGE_OPERATIONS.items()],
+ 'sessions': [
+ 'Create a work conversation with POST /sessions; share a sentence using POST /sessions/{id}/events with type=message and text.',
+ 'Read /sessions/{id}/events?after=<last event seq>&wait=25 for user messages or confirmation answers. With Accept: text/event-stream, use Last-Event-ID to reconnect.',
+ 'Only the page user may stop or resume. On stopped_by_user, wait for the user to continue; do not start another session to bypass the stop.',
+ 'On needs_confirmation nothing changed: wait with freevideo_wait (no id) for the answer, then repeat the same call unchanged. '
+ 'On declined_by_user do not repeat it; change the plan or ask the user. GET /confirmations shows what asks first.',
+ ],
+ 'session_routes': [dict(operation=name, method=method, path=path, description=summary)
+ for name, (method, path, summary) in SESSION_OPERATIONS.items()],
+ 'filming': [
+ 'Filming is for a film of several shots, each picked from takes. One video of any length is one generate '
+ 'job (longer requests continue and join automatically); to polish an idea first, run enhance, then generate.',
+ 'Use drama plan → start → get → sheet → choose/reshoot → finish; inspect todo after every change.',
+ 'At start tell the user the estimated total time; on over_budget decide whether to ask them; '
+ 'without an estimate report only the current work and elapsed time.',
+ 'Use get with since=revision and wait=25. changed=false is a compact timeout; retain the last full board.',
+ 'If paused is set, stop acting and long-wait until the user continues. Only the user may pause/resume.',
+ 'Continuations wait for the preceding chosen take and use real video continuation; upstream changes reconnect downstream shots.',
+ 'Reuse ref or Idempotency-Key with identical content for safe replay. External callers cannot supply by.',
+ 'GET /drama?status=active and connect/hello unfinished identify films to continue. No built-in director loop starts automatically.',
+ ],
+ 'short_drama': [
+ 'One job = one shot or a few cuts of 5-10 s. Keep character descriptions identical across shots '
+ '(same words for face, hair, clothing) and give each speaker the same voice description.',
+ 'Text alone does not keep a face identical across cuts. For a new scene with the same character, start '
+ 'from an image of them: a frame of an earlier shot edited into the new framing (media.first with edit), '
+ 'or a character picture as a reference (experimental).',
+ 'Continuity: start the next shot from the previous shot\'s last frame: '
+ 'media.first = {"from_job": "<id>", "frame": "last"}.',
+ 'Vertical short drama: aspect "9:16" (768x1344 at the native 0.98 MP).',
+ 'Review: ask the local VLM about sampled frames (kind "vlm", questions[].video) and regenerate weak shots '
+ 'with another seed (takes) before assembling (kind "assemble").',
+ 'Use quality "light" with preview=true to check a shot quickly, then refine_from that job.',
+ ],
+ 'example': DEFAULT_PROMPT,
+}
+
+
+# How an agent is expected to work once a user has asked for something. Only what this version can honour.
+RULES = [
+ 'Finish the job. When the user asks for a video, keep going until the finished video exists. Decide ordinary '
+ 'things yourself: how to split shots, how many takes, which take to keep. Tell the user what you decided in '
+ 'one or two sentences at the end, not along the way.',
+ 'Solve problems yourself first. Every error has a next field, and often details with alternatives; these are '
+ 'steps that work on this computer. Not enough graphics memory: use a listed alternative (a lower resolution '
+ 'or a shorter video) and try again. A take is not good: make another; if it is still not good after two more, '
+ 'describe it a different way instead of repeating the request. The queue is busy: wait with wait=25 on the '
+ 'job, never in a tight loop. The connection dropped or FreeVideo restarted: connect again, read the job list, '
+ 'and continue; resend an unanswered request with the same ref, and never generate again what is already done.',
+ 'Do not stop to report progress. A long task is not a reason to stop or to ask whether to go on.',
+ 'Ask the user only when you would have to change the content or style they asked for, when the work will '
+ 'take clearly longer than you told them at the start, or when you would have to delete or overwrite their '
+ 'own works or edits.',
+ 'Stay inside FreeVideo. Do not touch other files on this computer. Never change back something the user '
+ 'edited. When the user tells you to stop, stop: cancel what you started and start nothing new.',
+ 'Cast before you shoot. Search the cast library first. Use the card the user named, or one that clearly '
+ 'matches; ask if you are unsure. Create a card only when none fits: from the user\'s photos if they gave any, '
+ 'otherwise make its reference pictures with POST /cast/{id}/generate. '
+ 'Before shooting, tell the user the casting in one sentence. Later shots use the card\'s current pictures. '
+ 'Keep cards you made so later films can reuse them.',
+]
+
+
+def connection_guide(root, base):
+ """Public bootstrap text contains locations and commands, never credential values."""
+ import json
+ from pathlib import Path
+ from .mcp import client_config
+ from .schema import PREFIX, contracts
+ config = client_config(root)
+ token_file = str(Path(root).resolve() / 'agent' / 'token')
+ # The executable/API/credential locations come from this running installation.
+ example = '\n'.join([
+ 'import json, pathlib, urllib.request',
+ 'base = ' + repr(base + PREFIX),
+ 'token = pathlib.Path(' + repr(token_file) + ').read_text().strip()',
+ 'def call(method, path, body=None):',
+ ' data = None if body is None else json.dumps(body).encode()',
+ ' req = urllib.request.Request(base + path, data=data, method=method,',
+ ' headers={"Authorization": "Bearer " + token, "Content-Type": "application/json"})',
+ ' opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))',
+ ' with opener.open(req) as response: return json.load(response)',
+ 'call("POST", "/connect/hello", {"client": "Local Agent", "via": "http"})',
+ 'print(call("GET", ""))',
+ '# Only after the user asks for a video:',
+ '# job = call("POST", "/jobs", {"prompt": "USER_REQUEST", "ref": "shot-1"})["job"]',
+ '# job = call("GET", "/jobs/" + job["id"] + "?wait=25")',
+ '# Poll the same ID until succeeded. Retry a lost submission using the same ref.',
+ '# Download base origin + job["result"]["video"]["url"] with the same Authorization header.',
+ ])
+ return dict(api=base + PREFIX, token_file=token_file, claude_code=config['claude_code'],
+ codex=config['codex'], mcp_json=config['mcp_json'], command=config['command'],
+ authentication='Read the token file and put its contents in the Authorization: Bearer header. '
+ 'Do not print it, show it to the user, or write it to another file.',
+ session='Newly configured tools are usually unavailable in the current session. Use this local HTTP '
+ 'API in this session; the tools will be available in your next session.',
+ hello=dict(method='POST', url=base + PREFIX + '/connect/hello', body=dict(client='Local Agent', via='http')),
+ capabilities=[dict(method=method, endpoint=PREFIX + suffix, description=row['summary'])
+ for (method, suffix), row in contracts().items()
+ if not suffix.startswith('/freevideo/') and not suffix.startswith('/connect')],
+ first_reply='After connecting, first reply in the user\'s language. In plain words, explain the available '
+ 'features listed here and give two or three requests they can say. Do not start any task yourself; '
+ 'wait for the user to ask.',
+ rules=RULES,
+ fallback='If you cannot run commands, read local files, or reach this computer, tell the user honestly '
+ 'in their language: I cannot connect to the program on your computer; you need an AI assistant '
+ 'installed on your computer. Do not install a workaround.',
+ http_example=example, docs=dict(guide=base + PREFIX + '/guide', openapi=base + PREFIX + '/openapi.json'))
+
+
+def connection_text(value):
+ import json
+ return '\n'.join([
+ 'Connect to FreeVideo on this computer', value['api'], '', value['authentication'],
+ 'Token file: ' + value['token_file'], '', 'Claude Code:', value['claude_code'], '',
+ 'Codex:', value['codex'], '', 'Other MCP clients:', json.dumps(value['mcp_json'], indent=2), '',
+ value['session'], '', 'Local HTTP (Python):', value['http_example'], '',
+ 'Available in this version:', *['- ' + row['description'] for row in value['capabilities']], '',
+ value['first_reply'], value['fallback'], '',
+ 'How to work once the user has asked for something:',
+ *['%d. %s' % (number, rule) for number, rule in enumerate(value['rules'], 1)], '',
+ 'More detail: ' + value['docs']['guide'], 'API contract: ' + value['docs']['openapi'], '',
+ ])
+
+
+GUIDE['agent_jobs'] += [
+ 'Use ref or the Idempotency-Key header on submissions and resume. The same key and content return '
+ 'the original job IDs (HTTP 200); changed content with the same key returns idempotency_conflict. Keys are kept per client name. '
+ 'Keys survive restart. Batch-level ref names the whole request; row refs still name earlier dependencies.',
+ 'Upload media content with POST /media. HTTP accepts no local absolute paths; MCP and CLI read local files '
+ 'before uploading. Unknown fields are rejected and every batch is validated before it is recorded.',
+ 'limits.seconds in the status reply is what this installation can make now. While continuation is false, '
+ 'one block (15 s) is the longest video; plan and submit refuse longer requests with continuation_unavailable.',
+ 'features in the status reply names what this installation offers; false means not usable now (for example '
+ 'chain.auto while continuation is false), and a missing name means not offered here.',
+]
+GUIDE['rules'] = RULES
+from .errors import ERRORS
+GUIDE['errors'] = {code: dict(status=status, retryable=retryable, message=message, next=action)
+ for code, (status, retryable, message, action) in ERRORS.items()}
+
+
+# Same operation descriptions as the guarded routes, MCP and CLI.
+GUIDE['filming_routes'] = [dict(operation=name, method=method, path=path, description=summary)
+ for name, (method, path, summary) in DRAMA_OPERATIONS.items()]
+GUIDE['cast_routes'] = [dict(operation=name, method=method, path=path, description=summary)
+ for name, (method, path, summary) in CAST_OPERATIONS.items()]
+GUIDE['cast'] = [
+ 'A card is a character or setting: name, a one-sentence English description used in prompts, up to six '
+ 'labelled pictures (front, three_quarter, side, back, face, sheet, other) and an optional 2 to 15 s voice.',
+ 'Changes need the revision you read (body revision or If-Match); stale_revision returns the current card in '
+ 'error.card. Fields the user changed return changed_by_user: keep the user\'s version.',
+ 'Film with a card by setting characters.<key>.card. Cards are read when each take is submitted. Shots that '
+ 'continue the previous one carry no references (cast_reference inherited); POST /drama/plan shows each shot\'s cast. '
+ 'A shot with a carded character is at most 15 s; continue it in the next shot to go longer.',
+ 'POST /cast/{id}/generate makes reference pictures from the description as a normal job (face=true adds a close-up). '
+ 'When the job ends the card gets the sharpest frames (labels guessed, label_guess) and a new revision; a failure '
+ 'sets generate_error and keeps the pictures. If the user changed the pictures (meanwhile, or before an agent asked), '
+ 'they go to candidates.',
+]
diff --git a/freevideo_engine/agent/image_runtime.py b/freevideo_engine/agent/image_runtime.py
new file mode 100644
index 0000000..fea2978
--- /dev/null
+++ b/freevideo_engine/agent/image_runtime.py
@@ -0,0 +1,272 @@
+"""Run the image editor's commands (web/image_commands.js) on the server in QuickJS.
+
+The Agent changes an image document with the functions the image editor page
+calls, linked by editor_runtime's bundler. The page's canvas is not there: the
+2D DOMMatrix the commands use is supplied here, and text is measured by the
+server renderer's measure (edit.measure_text), which draws with the same fonts.
+"""
+from __future__ import annotations
+
+import json
+import threading
+
+from . import edit
+from .editor_runtime import WEB, ScriptRuntime, bundle
+
+MODULES = ('fonts', 'image_editor_engine', 'image_commands')
+# The undo steps a batch may build before the caller trims them (images.MAX_HISTORY).
+HISTORY_LIMIT = 1000
+# Text sizes a batch may ask for in turn (a resize measures text at its new size).
+MEASURE_ROUNDS = 8
+
+# DOMMatrix and DOMPoint for the affine 2D transforms the commands use, in double
+# precision as WebKit computes them; Chromium stores scale-translate matrices in
+# float32, so geometry may differ from the page in the last digits.
+_MATRIX = r'''
+class DOMPoint {
+ constructor(x = 0, y = 0, z = 0, w = 1) { this.x = x; this.y = y; this.z = z; this.w = w; }
+ matrixTransform(m) { return new DOMMatrix(m).transformPoint(this); }
+}
+class DOMMatrix {
+ constructor(init) {
+ const v = init === undefined ? [1, 0, 0, 1, 0, 0]
+ : Array.isArray(init) ? init : [init.a, init.b, init.c, init.d, init.e, init.f];
+ if (v.length !== 6 || !v.every(Number.isFinite)) throw new TypeError('DOMMatrix: only finite 2D matrices are supported');
+ [this.a, this.b, this.c, this.d, this.e, this.f] = v;
+ }
+ get is2D() { return true; }
+ get isIdentity() { return this.a === 1 && this.b === 0 && this.c === 0 && this.d === 1 && this.e === 0 && this.f === 0; }
+ multiplySelf(o) {
+ const m = o instanceof DOMMatrix ? o : new DOMMatrix(o), {a, b, c, d, e, f} = this;
+ this.a = a * m.a + c * m.b; this.b = b * m.a + d * m.b;
+ this.c = a * m.c + c * m.d; this.d = b * m.c + d * m.d;
+ this.e = a * m.e + c * m.f + e; this.f = b * m.e + d * m.f + f;
+ return this;
+ }
+ preMultiplySelf(o) {
+ const m = new DOMMatrix(o instanceof DOMMatrix ? o : new DOMMatrix(o)).multiplySelf(this);
+ Object.assign(this, {a: m.a, b: m.b, c: m.c, d: m.d, e: m.e, f: m.f});
+ return this;
+ }
+ translateSelf(tx = 0, ty = 0) { return this.multiplySelf([1, 0, 0, 1, tx, ty]); }
+ scaleSelf(sx = 1, sy = sx) { return this.multiplySelf([sx, 0, 0, sy, 0, 0]); }
+ rotateSelf(x = 0, y, z) {
+ if (y !== undefined || z !== undefined) {
+ if (x || y) throw new TypeError('DOMMatrix: only rotation about z is supported');
+ x = z || 0;
+ }
+ const r = x * Math.PI / 180, cos = Math.cos(r), sin = Math.sin(r);
+ // The browser's exact values at quarter turns.
+ const q = ((x % 360) + 360) % 360, exact = {0: [1, 0], 90: [0, 1], 180: [-1, 0], 270: [0, -1]}[q];
+ const [cs, sn] = exact || [cos, sin];
+ return this.multiplySelf([cs, sn, -sn, cs, 0, 0]);
+ }
+ invertSelf() {
+ const {a, b, c, d, e, f} = this, det = a * d - b * c;
+ if (!det) { [this.a, this.b, this.c, this.d, this.e, this.f] = [NaN, NaN, NaN, NaN, NaN, NaN]; return this; }
+ this.a = d / det; this.b = -b / det; this.c = -c / det; this.d = a / det;
+ this.e = (c * f - d * e) / det; this.f = (b * e - a * f) / det;
+ return this;
+ }
+ multiply(o) { return new DOMMatrix(this).multiplySelf(o); }
+ translate(tx, ty) { return new DOMMatrix(this).translateSelf(tx, ty); }
+ scale(sx, sy) { return new DOMMatrix(this).scaleSelf(sx, sy); }
+ rotate(x, y, z) { return new DOMMatrix(this).rotateSelf(x, y, z); }
+ inverse() { return new DOMMatrix(this).invertSelf(); }
+ transformPoint(p = {}) {
+ const x = p.x || 0, y = p.y || 0;
+ return new DOMPoint(this.a * x + this.c * y + this.e, this.b * x + this.d * y + this.f, p.z || 0, p.w ?? 1);
+ }
+ get m11() { return this.a; } get m12() { return this.b; } get m21() { return this.c; }
+ get m22() { return this.d; } get m41() { return this.e; } get m42() { return this.f; }
+}
+'''
+
+# One batch: {document, selection, history, future, original, target, operations}
+# -> {ok, document, selection, history, future, results} | {ok: false, index, error}.
+# history holds the earlier documents (oldest first), future the undone ones
+# (nearest last), as the page keeps them; every operation that changes the
+# document is one step, a selection change is none, as on the page.
+_ENTRY = r'''
+const measureKey = text => JSON.stringify([String(text.content ?? ''), text.font ?? null, text.weight ?? null, text.size, text.lineHeight ?? null]);
+globalThis.__image_batch = text => {
+ const request = JSON.parse(text), c = __load('image_commands'), engine = __load('image_editor_engine');
+ // Canvas points (after turns and flips) to document pixels and back, as the page's toD / fromD.
+ const toD = (d, [x, y]) => { const p = engine.orientMatrix(d).inverse().transformPoint(new DOMPoint(x, y)); return [p.x, p.y]; };
+ const fromD = (d, [x, y]) => { const p = engine.orientMatrix(d).transformPoint(new DOMPoint(x, y)); return [p.x, p.y]; };
+ // Text sizes come from the server's measure; one asked for that is not in request.measures
+ // is listed in the reply and the batch runs again with it (QuickJS cannot call out under a time limit).
+ const measures = request.measures || {}, missing = {};
+ const measure = text => {
+ const key = measureKey(text);
+ if (key in measures) return measures[key];
+ missing[key] = text; return {nw: 1, nh: 1};
+ };
+ const target = request.target ? {width: request.target[0], height: request.target[1]} : null;
+ let history = [...request.history, request.document], future = request.future, selection = request.selection ?? null;
+ let doc = request.document;
+ const results = [];
+ const layer = id => doc.layers.find(l => l.id === id) || (() => { throw new c.ImageEditError('not_found', 'Layer not found'); })();
+ const commit = next => { ({history, future, doc} = c.commitStep({history, future}, next, %(limit)d)); };
+ const follow = (before, after) => {
+ if (before.width !== after.width || before.height !== after.height)
+ selection = engine.scaleSelection(selection, after.width / before.width, after.height / before.height);
+ };
+ const geometry = ['cx', 'cy', 'w', 'h', 'rotation', 'flipX', 'flipY'];
+ // As the page does: a lock keeps a layer from being deleted or moved, not from being retouched.
+ const pixels = (id, command) => {
+ if (!layer(id).locked) return command(doc);
+ return c.setLayer(command(c.setLayer(doc, id, {locked: false})), id, {locked: true});
+ };
+ for (let index = 0; index < request.operations.length; index++) {
+ const op = request.operations[index], before = new Set(doc.layers.map(l => l.id)), result = {};
+ try {
+ switch (op.op) {
+ case 'document.replace': commit(op.document); break;
+ case 'canvas.resize': {
+ const next = c.resizeImage(doc, op.width, op.height, op.keep ?? true, measure);
+ follow(doc, next); commit(next); break;
+ }
+ case 'canvas.rotate': commit(c.turn(doc, op.direction, target)); break;
+ case 'canvas.flip': commit(c.turn(doc, op.axis === 'horizontal' ? 'flipX' : 'flipY', target)); break;
+ case 'canvas.crop': commit({...doc, crop: c.normalizeCrop(doc, op.crop, doc.ratio, target)}); break;
+ case 'canvas.extend': commit(c.setCanvas(doc, {color: doc.extend.color, ...op.extend})); break;
+ case 'canvas.ratio': commit(c.setRatio(doc, op.ratio, target)); break;
+ case 'canvas.pad_to_video': commit(c.padToVideo(doc, target, op.color ?? '#000000')); break;
+ case 'layer.add': {
+ const spec = op.layer, name = spec.name ?? '';
+ if (spec.kind === 'paint') commit(c.addPaintLayer(doc, name));
+ else if (spec.kind === 'image') commit(c.addImageLayer(doc, {src: spec.src, nw: spec.nw, nh: spec.nh, name}));
+ else if (spec.kind === 'text') {
+ if (!spec.text) throw new c.ImageEditError('unsupported', 'text is required');
+ const r = engine.canvasRect(doc);
+ const text = {font: 'sans', weight: 700, color: '#ffffff', align: 'left', shadow: true, outline: false, lineHeight: 1.25, ...spec.text};
+ commit(c.addTextLayer(doc, {position: spec.position ?? toD(doc, [r.x + r.w / 2, r.y + r.h / 2]), name, text}, measure));
+ } else {
+ const shape = spec.shape;
+ if (!shape || !shape.from || !shape.to) throw new c.ImageEditError('unsupported', 'shape with from and to is required');
+ const {from, to, ...rest} = shape, line = (rest.type ?? 'rect') === 'line';
+ // Agents give points in document pixels like every other point; the page's gesture gives canvas ones.
+ commit(c.addShapeLayer(doc, {from: fromD(doc, from), to: fromD(doc, to), name, shape: {type: 'rect', fill: line ? null : '#ffffff',
+ stroke: line ? '#ffffff' : null, width: 6, radius: 0, ...rest}}));
+ }
+ break;
+ }
+ case 'layer.copy': commit(c.duplicateLayer(doc, op.layer_id, op.name ?? layer(op.layer_id).name)); break;
+ case 'layer.delete': commit(c.deleteLayer(doc, op.layer_id)); break;
+ case 'layer.reorder': {
+ let next = doc, at = doc.layers.findIndex(l => l.id === layer(op.layer_id).id);
+ if (op.index >= doc.layers.length || at < 1) throw new c.ImageEditError('range', 'Layer move out of range');
+ while (at !== op.index) { const d = op.index > at ? 1 : -1; next = c.moveLayer(next, op.layer_id, d); at += d; }
+ commit(next); break;
+ }
+ case 'layer.select': commit(c.setActive(doc, op.layer_id)); break;
+ case 'layer.update': {
+ const patch = op.patch, own = {}, place = {};
+ for (const [key, value] of Object.entries(patch))
+ (geometry.includes(key) ? place : key === 'name' ? result : own)[key] = value;
+ let next = doc;
+ if ('name' in result) { next = c.renameLayer(next, op.layer_id, result.name); delete result.name; }
+ if (Object.keys(own).length) next = c.setLayer(next, op.layer_id, own);
+ if (Object.keys(place).length) {
+ const current = next.layers.find(l => l.id === op.layer_id);
+ if (current.locked) throw new c.ImageEditError('locked', 'Layer is locked');
+ next = {...next, layers: next.layers.map(l => l.id === op.layer_id ? {...l, ...place} : l)};
+ }
+ commit(next); break;
+ }
+ case 'layer.adjust': {
+ const current = layer(op.layer_id);
+ if (!engine.rasterKinds.has(current.kind)) throw new c.ImageEditError('not_pixel_layer', 'An image or paint layer is required');
+ commit(c.setLayer(doc, op.layer_id, {adjust: {...current.adjust, ...op.patch}})); break;
+ }
+ case 'layer.text': commit(c.updateText(doc, op.layer_id, op.patch, measure)); break;
+ case 'layer.shape': commit(c.updateShape(doc, op.layer_id, op.patch)); break;
+ case 'selection.set': selection = op.selection.parts.length ? op.selection : null; break;
+ case 'selection.add': selection = c.addPart(selection, op.part, op.part.mode ?? 'replace'); break;
+ case 'selection.clear': selection = null; break;
+ case 'selection.all': selection = c.selectAll(); break;
+ case 'selection.invert': selection = c.invertSelection(selection); break;
+ // The selection is used up by what the page does with it, as there.
+ case 'selection.copy_to_layer':
+ commit(c.copyToLayer(doc, op.layer_id, selection, op.name ?? layer(op.layer_id).name)); selection = null; break;
+ case 'selection.fill': commit(pixels(op.layer_id, d => c.fillSelection(d, op.layer_id, op.color ?? '#000000', selection))); break;
+ case 'selection.erase': commit(pixels(op.layer_id, d => c.clearSelection(d, op.layer_id, selection))); break;
+ case 'mask.set': if (!layer(op.layer_id).mask) {
+ const next = c.toggleMask(doc, op.layer_id, selection);
+ commit(next.doc); if (next.selectionUsed) selection = null;
+ } break;
+ case 'mask.delete': if (layer(op.layer_id).mask) commit(c.toggleMask(doc, op.layer_id, selection).doc); break;
+ case 'mask.from_selection': commit(c.maskFromSelection(doc, op.layer_id, selection)); selection = null; break;
+ case 'pixels.apply': {
+ const {id, ...pixel} = op.pixel_op, current = layer(op.layer_id);
+ if (op.target === 'mask') {
+ // As the page paints on a mask: paint hides, erase shows again.
+ if (!current.mask) throw new c.ImageEditError('unsupported', 'The layer has no mask');
+ if (pixel.type !== 'stroke') throw new c.ImageEditError('unsupported', 'Only strokes paint on a mask');
+ pixel.tool = pixel.tool === 'paint' ? 'hide' : pixel.tool === 'erase' ? 'reveal' : pixel.tool;
+ if (pixel.tool !== 'hide' && pixel.tool !== 'reveal') throw new c.ImageEditError('unsupported', 'Only paint and erase work on a mask');
+ } else if (pixel.type === 'stroke' && (pixel.tool === 'hide' || pixel.tool === 'reveal'))
+ throw new c.ImageEditError('unsupported', 'hide and reveal paint on a mask');
+ // The page puts paint and gradients for a locked picture on a paint layer of their own; erasing it is allowed.
+ if (current.locked && op.target !== 'mask' && (pixel.type === 'gradient' || pixel.tool === 'paint'))
+ throw new c.ImageEditError('locked', 'Paint on a paint layer (layer.add) above the locked picture');
+ commit(pixels(op.layer_id, d => c.pushOp(d, op.layer_id, pixel))); break;
+ }
+ case 'undo': case 'redo': {
+ if (op.op === 'undo' ? history.length <= 1 : !future.length) break;
+ const next = (op.op === 'undo' ? c.undoStep : c.redoStep)({history, future, doc, selection});
+ ({history, future, doc, selection} = next); break;
+ }
+ case 'reset': selection = null; commit(request.original); break;
+ default: throw new c.ImageEditError('unsupported', 'Unknown operation');
+ }
+ } catch (error) {
+ if (!(error instanceof c.ImageEditError)) throw error;
+ // A placeholder size may be what failed; measure first, then decide.
+ if (Object.keys(missing).length) return JSON.stringify({ok: false, measure: missing});
+ return JSON.stringify({ok: false, index, error: {code: error.code, message: error.message}});
+ }
+ const added = doc.layers.filter(l => !before.has(l.id)).map(l => l.id);
+ if (added.length) result.new_layer_ids = added;
+ results.push(result);
+ }
+ if (Object.keys(missing).length) return JSON.stringify({ok: false, measure: missing});
+ return JSON.stringify({ok: true, document: doc, selection, history: history.slice(0, -1), future, results});
+};
+''' % dict(limit=HISTORY_LIMIT)
+
+
+class ImageRuntime(ScriptRuntime):
+ """The image editor's commands (web/image_commands.js)."""
+
+ def __init__(self, web=WEB):
+ # fonts.js finds its files from its own address, used only to load them in a page.
+ source = bundle(web, MODULES, start='image_commands', entry=_ENTRY, prelude=_MATRIX)
+ super().__init__(source.replace('import.meta.url', "'file:///web/fonts.js'"))
+
+ def batch(self, **request):
+ """Apply operations to a session's document; see _ENTRY for the reply."""
+ measures = {}
+ for _ in range(MEASURE_ROUNDS):
+ reply = self._entry('__image_batch', dict(request, measures=measures))
+ if 'measure' not in reply:
+ return reply
+ for key, text in reply['measure'].items():
+ try:
+ measures[key] = edit.measure_text(text)
+ except (KeyError, TypeError, ValueError, OSError):
+ return dict(ok=False, index=None, error=dict(code='range', message='Text cannot be measured'))
+ raise RuntimeError('image text measure did not settle')
+
+
+_RUNTIME = None
+_RUNTIME_LOCK = threading.Lock()
+
+
+def runtime():
+ global _RUNTIME
+ with _RUNTIME_LOCK:
+ if _RUNTIME is None:
+ _RUNTIME = ImageRuntime()
+ return _RUNTIME
diff --git a/freevideo_engine/agent/images.py b/freevideo_engine/agent/images.py
new file mode 100644
index 0000000..2d11d19
--- /dev/null
+++ b/freevideo_engine/agent/images.py
@@ -0,0 +1,382 @@
+"""Image editing sessions for agents: the image editor's document, changed with the page's commands.
+
+A session holds one version 2 document (web/image_editor_engine.js) of a frozen
+source picture, the selection, and an undo history. Operations run the page's
+own commands (web/image_commands.js) in QuickJS (image_runtime), so the Agent
+adds layers, heals and crops the way the page does; every change is saved with a
+revision check, and render makes a PNG with the server renderer (edit.py).
+"""
+from __future__ import annotations
+
+from copy import deepcopy
+import hashlib
+import json
+import logging
+from pathlib import Path
+import secrets
+import threading
+import time
+
+from . import edit, errors, schema, spec
+from .jobs import JobError
+
+MAX_OPERATIONS = 64
+MAX_RECEIPTS = 256
+MAX_HISTORY = 32
+MAX_HISTORY_BYTES = 8 * 2**20
+MAX_SESSIONS = 512
+# Command codes that describe the document's state; the rest are request errors.
+STATE_CODES = {'locked': 'layer_locked'}
+COMMAND_EXPECTED = {
+ 'not_found': 'a layer_id of this revision',
+ 'not_pixel_layer': 'an image or paint layer',
+ 'no_selection': 'a selection (selection.set first)',
+ 'range': 'values inside the documented ranges',
+ 'unsupported': 'an op named in the operations schema with its fields',
+}
+
+
+def now():
+ return time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())
+
+
+class ImageError(JobError):
+ """An image session error; a conflict carries the current session so the caller can retry from it."""
+
+ def __init__(self, code, message=None, *, image=None, operation=None):
+ super().__init__(code, message or errors.ERRORS[code][2])
+ self.status = errors.ERRORS[code][0]
+ self.image, self.operation = image, operation
+
+ def view(self):
+ value = errors.build(self.code, validation=True, details=[], message=self.message,
+ next_action=errors.ERRORS[self.code][3])
+ if self.operation is not None:
+ value['details'].append(dict(operation=self.operation))
+ if self.image is not None:
+ value['image'] = deepcopy(self.image)
+ value['current_revision'] = self.image['revision']
+ return value
+
+
+def _invalid(path, expected, received=None):
+ return spec.SpecError([schema.diagnostic(path, expected, received)])
+
+
+def _digest(scope, payload):
+ return hashlib.sha256(json.dumps(dict(scope=scope, body=payload), sort_keys=True, separators=(',', ':'),
+ ensure_ascii=True, allow_nan=False).encode()).hexdigest()
+
+
+def _bytes(value):
+ return len(json.dumps(value, separators=(',', ':'), ensure_ascii=False, allow_nan=False).encode())
+
+
+def _layers(document):
+ return {layer['id']: layer for layer in document['layers']}
+
+
+def changed_layer_ids(before, after):
+ """Layers added, removed or changed, in the result's order, then removed ones."""
+ old, new = _layers(before), _layers(after)
+ return [i for i, layer in new.items() if old.get(i) != layer] + [i for i in old if i not in new]
+
+
+def trim_history(history, future):
+ """At most MAX_HISTORY undo steps and MAX_HISTORY_BYTES of stored steps; the oldest go first."""
+ truncated = False
+ history, future = list(history), list(future)
+ while len(history) > MAX_HISTORY:
+ history.pop(0)
+ truncated = True
+ while history and _bytes(history) + _bytes(future) > MAX_HISTORY_BYTES:
+ history.pop(0)
+ truncated = True
+ while future and _bytes(future) > MAX_HISTORY_BYTES:
+ future.pop()
+ truncated = True
+ return history, future, truncated
+
+
+class Images:
+ def __init__(self, jobs, directory):
+ self.jobs, self.port = jobs, jobs.port
+ self.directory = Path(directory)
+ self.lock = threading.RLock()
+ self.receipts = {} # (client, ref) -> {digest, result}; in memory, bounded.
+
+ # Storage -------------------------------------------------------------------------------------------
+ def _path(self, identity):
+ if not isinstance(identity, str) or not schema.re.fullmatch(schema.IMAGE['pattern'], identity):
+ raise ImageError('not_found', 'The image session does not exist.')
+ return self.directory / (identity + '.json')
+
+ def _load(self, identity):
+ path = self._path(identity)
+ try:
+ record = json.loads(path.read_text(encoding='utf-8'))
+ except FileNotFoundError:
+ raise ImageError('not_found', 'The image session does not exist.') from None
+ except (OSError, ValueError) as error:
+ logging.getLogger(__name__).warning('Image session %s is unreadable', identity)
+ raise ImageError('storage_unavailable') from error
+ if not isinstance(record, dict) or record.get('id') != identity or not isinstance(record.get('document'), dict):
+ raise ImageError('storage_unavailable')
+ return record
+
+ def _store(self, record):
+ from ..comfy_editor import _write
+ self.directory.mkdir(parents=True, exist_ok=True)
+ try:
+ _write(self._path(record['id']), record)
+ except OSError as error:
+ raise ImageError('storage_unavailable') from error
+
+ def view(self, record):
+ return dict(id=record['id'], revision=record['revision'], document=deepcopy(record['document']),
+ source=dict(record['source']), target=record.get('target'), selection=deepcopy(record.get('selection')),
+ created_at=record['created_at'], updated_at=record['updated_at'],
+ history=dict(undo_depth=len(record.get('history', [])), redo_depth=len(record.get('future', []))))
+
+ def _receipt(self, scope, payload, ref, client=None):
+ if ref is None:
+ return None, None
+ digest = _digest(scope, payload)
+ with self.lock:
+ old = self.receipts.get((client, ref))
+ if old is not None:
+ if old['digest'] != digest:
+ raise JobError('idempotency_conflict', 'Key already used')
+ return digest, deepcopy(old['result'])
+ return digest, None
+
+ def _remember(self, ref, digest, result, client=None):
+ if ref is None:
+ return
+ with self.lock:
+ self.receipts[client, ref] = dict(digest=digest, result=deepcopy(result))
+ while len(self.receipts) > MAX_RECEIPTS:
+ self.receipts.pop(next(iter(self.receipts)))
+
+ # Documents -----------------------------------------------------------------------------------------
+ def _resolve(self, name):
+ return self.port.input_path(name)
+
+ def check_document(self, document, sources, at='/document'):
+ """The published shape, then the renderer's cross checks, then every picture a layer names."""
+ try:
+ self._check_document(document, sources)
+ except spec.SpecError as error:
+ raise spec.SpecError([schema.prefix_diagnostic(e, at) if e['path'].startswith('/') or not e['path']
+ else e for e in error.errors]) from None
+
+ def _check_document(self, document, sources):
+ schema.validate(schema.image_document(), document)
+ try:
+ edit._check(document)
+ except edit.EditError as error:
+ raise _invalid(error.path if error.path != '/' else '', error.message) from None
+ ids = [layer['id'] for layer in document['layers']]
+ if len(set(ids)) != len(ids):
+ raise _invalid('/layers', 'unique layer ids')
+ if document.get('active', 'base') not in ids:
+ raise _invalid('/active', 'the id of one of the layers', document.get('active'))
+ by = {layer['id']: layer for layer in document['layers']}
+ for index, layer in enumerate(document['layers']):
+ copy = layer.get('copyOf')
+ if copy:
+ # A copy draws the first upto steps of another layer; that one must not be a copy of it.
+ source, chain = by.get(copy['layer']), {layer['id']}
+ if source is None:
+ raise _invalid('/layers/%d/copyOf/layer' % index, 'the id of another layer', copy['layer'])
+ if copy.get('upto', 0) > len(source.get('ops') or []):
+ raise _invalid('/layers/%d/copyOf/upto' % index, 'at most the number of steps of that layer', copy['upto'])
+ while source is not None and source.get('copyOf'):
+ if source['id'] in chain:
+ raise _invalid('/layers/%d/copyOf' % index, 'copies that do not copy themselves')
+ chain.add(source['id'])
+ source = by.get(source['copyOf']['layer'])
+ continue
+ src = layer.get('src')
+ if layer['kind'] == 'image' and src not in sources:
+ path = self.port.input_path(src) if isinstance(src, str) else None
+ if path is None or not path.is_file():
+ raise _invalid('/layers/%d/src' % index, 'an input file returned by media upload', src)
+
+ def _freeze(self, identity, item):
+ """The source picture as an input file of this session, and its digest."""
+ from PIL import Image, ImageOps
+ row = dict(id=identity)
+ relative = self.jobs.media_file(row, item, 'source')
+ if relative == item.get('file'):
+ # An uploaded file may be replaced later; the session keeps its own copy.
+ copy = 'freevideo/agent/%s/source%s' % (identity, Path(relative).suffix.lower())
+ self.port.import_file(self.port.input_path(relative), self.port.input_path(copy, create=True))
+ relative = copy
+ path = self.port.input_path(relative)
+ digest = hashlib.sha256()
+ with path.open('rb') as stream:
+ for chunk in iter(lambda: stream.read(1 << 20), b''):
+ digest.update(chunk)
+ try:
+ with Image.open(path) as image:
+ width, height = ImageOps.exif_transpose(image).size
+ except (OSError, ValueError, Image.DecompressionBombError) as error:
+ raise JobError('invalid_media', 'The source is not a picture FreeVideo can read.') from error
+ if width > 8192 or height > 8192 or width * height > schema.IMAGE_MAX_PIXELS:
+ raise JobError('image_size', 'The source picture is larger than 8192 pixels on a side.')
+ return dict(file=relative, digest='sha256:' + digest.hexdigest(), width=width, height=height)
+
+ # Sessions ------------------------------------------------------------------------------------------
+ def get(self, identity):
+ return dict(image=self.view(self._load(identity)))
+
+ def create(self, value, *, ref=None, client=None):
+ schema.validate(schema.image_schema('create'), value)
+ ref = value.get('ref', ref)
+ payload = {k: v for k, v in value.items() if k != 'ref'}
+ digest, replay = self._receipt('images:create', payload, ref, client)
+ if replay is not None:
+ return replay
+ item = spec.media_item(value['source'], '/source', image=True)
+ identity = 'i-' + secrets.token_hex(16)
+ source = self._freeze(identity, item)
+ if value.get('document') is not None:
+ document = deepcopy(value['document'])
+ self.check_document(document, {source['file']})
+ else:
+ document = edit.new_document(source['file'], source['width'], source['height'])
+ stamp = now()
+ record = dict(id=identity, revision=1, document=document, original=deepcopy(document),
+ source=dict(file=source['file'], digest=source['digest']),
+ target=list(value['target']) if value.get('target') else None, selection=None,
+ history=[], future=[], created_at=stamp, updated_at=stamp)
+ with self.lock:
+ self._store(record)
+ result = dict(image=self.view(record))
+ self._remember(ref, digest, result, client)
+ return result
+
+ def _current(self, identity, revision):
+ record = self._load(identity)
+ if record['revision'] != revision:
+ raise ImageError('image_changed', image=self.view(record))
+ return record
+
+ def write(self, identity, value, *, ref=None, client=None):
+ schema.validate(schema.image_schema('write'), value)
+ ref = value.get('ref', ref)
+ payload = dict({k: v for k, v in value.items() if k != 'ref'}, id=identity)
+ digest, replay = self._receipt('images:write', payload, ref, client)
+ if replay is not None:
+ return replay
+ return self.operations(identity, dict(revision=value['revision'],
+ operations=[dict(op='document.replace', document=value['document'])]), _receipt=(ref, digest), _write=True, client=client)
+
+ def operations(self, identity, value, *, client=None, ref=None, _receipt=None, _write=False):
+ if _receipt is None:
+ schema.validate(schema.image_schema('operations'), value)
+ ref = value.get('ref', ref)
+ payload = dict({k: v for k, v in value.items() if k != 'ref'}, id=identity)
+ digest, replay = self._receipt('images:operations', payload, ref, client)
+ if replay is not None:
+ return replay
+ else:
+ ref, digest = _receipt
+ from .image_runtime import runtime
+ with self.lock:
+ record = self._current(identity, value['revision'])
+ operations = [self._prepared(index, op, record) for index, op in enumerate(value['operations'])]
+ reply = runtime().batch(document=record['document'], selection=record.get('selection'),
+ history=record.get('history', []), future=record.get('future', []),
+ original=record['original'], target=record.get('target'),
+ operations=operations)
+ if not reply['ok']:
+ self._rejected(reply, record, value['operations'])
+ document = reply['document']
+ # What the commands made is held to the same published shape as an upload.
+ self.check_document(document, {record['source']['file']})
+ history, future, truncated = trim_history(reply['history'], reply['future'])
+ changed = changed_layer_ids(record['document'], document)
+ moved = (document != record['document'] or reply['selection'] != record.get('selection')
+ or history != record.get('history', []) or future != record.get('future', []))
+ if moved:
+ record.update(document=document, selection=reply['selection'], history=history, future=future,
+ revision=record['revision'] + 1, updated_at=now())
+ self._store(record)
+ result = dict(image=self.view(record), changed_layer_ids=changed)
+ if reply.get('results'):
+ result['results'] = reply['results']
+ if truncated:
+ result['warnings'] = [dict(code='history_truncated',
+ message='The oldest undo steps were dropped; the document did not change.')]
+ if _write:
+ result.pop('changed_layer_ids')
+ result.pop('results', None)
+ self._remember(ref, digest, result, client)
+ return result
+
+ def _prepared(self, index, op, record):
+ """An operation with what the commands need from files: a whole document is checked, a new picture layer gets its size."""
+ if op['op'] == 'document.replace':
+ self.check_document(op['document'], {record['source']['file']}, '/operations/%d/document' % index)
+ if op['op'] == 'layer.add' and op['layer']['kind'] == 'image':
+ src = op['layer'].get('src')
+ if src is None:
+ raise _invalid('/operations/%d/layer/src' % index, 'an input file returned by media upload')
+ width, height = self._picture_size(src, '/operations/%d/layer/src' % index)
+ return dict(op, layer=dict(op['layer'], nw=width, nh=height))
+ return op
+
+ def _picture_size(self, src, path):
+ from PIL import Image, ImageOps
+ file = self.port.input_path(src)
+ if file is None or not file.is_file():
+ raise _invalid(path, 'an input file returned by media upload', src)
+ try:
+ with Image.open(file) as image:
+ return ImageOps.exif_transpose(image).size
+ except (OSError, ValueError, Image.DecompressionBombError):
+ raise _invalid(path, 'a picture FreeVideo can read', src) from None
+
+ def _rejected(self, reply, record, operations):
+ error, index = reply['error'], reply.get('index')
+ if error['code'] in STATE_CODES:
+ raise ImageError(STATE_CODES[error['code']], error.get('message') or None, image=self.view(record),
+ operation=index)
+ path = '/operations' + ('/%d' % index if index is not None else '')
+ received = operations[index] if index is not None and index < len(operations) else None
+ raise spec.SpecError([schema.diagnostic(path, COMMAND_EXPECTED.get(error['code'], 'an operation this image allows'),
+ received)])
+
+ def render(self, identity, value, *, jobs, ref=None, client=None):
+ schema.validate(schema.image_schema('render'), value)
+ ref = value.get('ref', ref)
+ payload = dict({k: v for k, v in value.items() if k != 'ref'}, id=identity)
+ digest, replay = self._receipt('images:render', payload, ref, client)
+ if replay is not None:
+ return replay
+ self._current(identity, value['revision'])
+ job = jobs.submit(dict(kind='image_edit', image=identity, revision=value['revision']), client=client)[0]
+ result = dict(job=jobs.view(job), jobs=[jobs.view(job)])
+ self._remember(ref, digest, result, client)
+ return result
+
+
+def run_render(jobs, row):
+ """The image_edit job: render the session's revision to a PNG input file."""
+ images = jobs.images
+ spec_ = row['spec']
+ record = images._load(spec_['image'])
+ if record['revision'] != spec_['revision']:
+ raise JobError('image_changed', 'The image changed since you read it (now revision %d)' % record['revision'])
+ folder = 'freevideo/agent/' + row['id']
+ relative = folder + '/image.png'
+ out = jobs.port.input_path(relative, create=True)
+ try:
+ made = edit.save(record['document'], images._resolve, out)
+ except edit.EditError as error:
+ raise JobError('invalid_edit', str(error), path=getattr(error, 'path', None)) from None
+ out.with_suffix('.edit.json').write_text(json.dumps(record['document']), encoding='utf-8')
+ return dict(file=relative, width=made['width'], height=made['height'], document_version=2,
+ image_id=record['id'], image_revision=record['revision'])
diff --git a/freevideo_engine/agent/jobs.py b/freevideo_engine/agent/jobs.py
new file mode 100644
index 0000000..5d1d3a9
--- /dev/null
+++ b/freevideo_engine/agent/jobs.py
@@ -0,0 +1,1403 @@
+"""Agent jobs: one durable record per request, dependencies, GPU turn-taking and status.
+
+Generation uses the studio's durable chain runner. Jobs keeps Agent chains in
+FIFO order until the runner is free. The local VLM (prompt enhancement and questions) only
+starts when that queue is empty, and generation waits while the VLM runs. Jobs
+may read other jobs' results (a frame, a clip, an enhanced prompt); such a job
+waits until those finish and fails with dependency_failed if one does not.
+"""
+import asyncio
+import hashlib
+from copy import deepcopy
+import json
+import logging
+import math
+import os
+import secrets
+import stat
+from pathlib import Path
+import threading
+import time
+import uuid
+from urllib.parse import parse_qs, urlsplit
+
+from . import spec as specs
+from . import schema, errors, assets
+
+ACTIVE = ('waiting', 'queued', 'running', 'cancelling')
+CAST_AGAIN = 'POST /freevideo/agent/v1/cast/%s/generate to make the reference pictures again.'
+DONE = ('succeeded', 'failed', 'cancelled', 'interrupted')
+GPU_KINDS = ('vlm', 'enhance')
+
+
+class JobError(Exception):
+ def __init__(self, code, message, **details):
+ super().__init__(message)
+ self.code, self.message, self.details = code, message, details
+
+ def view(self):
+ return errors.build(self.code, details=self.details.get('details'),
+ owner=self.details.get('owner'),
+ retry_after_seconds=self.details.get('retry_after_seconds'))
+
+
+class ManagedByProduction(JobError):
+ """A film's child job: only the film may decide whether another version runs."""
+ status = 409
+
+ def __init__(self, production):
+ super().__init__('managed_by_production', errors.ERRORS['managed_by_production'][2])
+ self.production = production
+
+ def view(self):
+ return errors.build(self.code, validation=True, details=[],
+ next_action='This take belongs to film %s; reshoot the shot or wait for the user to continue.' % self.production)
+
+
+def chain_error(code, message, next_action, *, details=None, retryable=False):
+ return JobError(code, message, details=details or [], next=next_action, retryable=retryable)
+
+
+def single_block(seconds):
+ from ..chain_plan import plan
+ return plan(seconds)['single']
+
+
+def continuation_problems(spec, prefix='', *, editor=None):
+ """Continuing a video (a second block, or continue_from) runs only on two-pass text generation.
+
+ The engine refuses the continuation block itself, after the first block has already been made.
+ """
+ if spec['kind'] != 'generate' or spec.get('refine_from'):
+ return []
+ if not (any(block['after'] for block in editor['blocks']) if editor is not None
+ else spec.get('continue_from') or not single_block(spec['seconds'])):
+ return []
+ why = ' when continuing a video or making one longer than 15 s'
+ problems = []
+ if not spec['two_pass']:
+ # The quality name is a contract enum, never caller text.
+ problem = schema.diagnostic(prefix + '/quality', '"light" (two-pass), or sampling.two_pass=true,' + why, None)
+ got = '"%s" (one pass)' % spec['quality']
+ problems.append(dict(problem, got=got, message=problem['message'].replace('received None', 'received ' + got)))
+ if spec['preview']:
+ problems.append(schema.diagnostic(prefix + '/preview', 'false' + why, True))
+ if spec['media']:
+ problems.append(schema.diagnostic(prefix + '/media', 'none' + why + ' (continue_from carries the previous video)',
+ None))
+ return problems
+
+
+def cut_problems(spec, seconds, prefix='', *, editor=None):
+ """A shot cut at or after the end of the video never appears; refuse it before anything is generated."""
+ if spec['kind'] != 'generate' or spec.get('refine_from') or spec.get('continue_from') or seconds is None:
+ return []
+ if any(block['after'] for block in editor['blocks']) if editor is not None else not single_block(seconds):
+ return [] # Every block of a continued video reads the same text.
+ late = [cut for cut in specs.cut_times(spec.get('prompt')) if cut >= seconds]
+ if not late:
+ return []
+ problem = schema.diagnostic(prefix + '/prompt', 'shot cuts ("[Shot N] At MM:SS.mmm") before the end of the '
+ '%.3f s video' % seconds, None)
+ got = 'a cut at %02d:%06.3f' % divmod(late[0], 60)
+ return [dict(problem, got=got, message=problem['message'].replace('received None', 'received ' + got))]
+
+
+def continuation_unavailable():
+ return chain_error('continuation_unavailable', 'This backend cannot continue multiple video blocks.',
+ 'Submit a new job with seconds<=15, or enable a backend with continuation inputs and resume.')
+
+
+def library_id(relative):
+ parts = Path(relative).parts
+ identity = '/'.join(parts[1:3]) if len(parts) == 4 and parts[0] == 'FreeVideo' else None
+ if identity and specs.LIBRARY_ID.fullmatch(identity):
+ return identity
+ raise chain_error('invalid_output', 'The chain output is not a saved library video.',
+ 'Read the job again after repairing the saved output, then resume it.')
+
+
+def library_view(port, relative):
+ identity = library_id(relative)
+ view = dict(file=relative, url='/freevideo/agent/v1/library/%s/file' % identity)
+ return view
+
+
+def result_view(result):
+ """Normalize retained library URLs at presentation time, without changing receipts."""
+ value = deepcopy(result)
+ if not isinstance(value, dict):
+ return value
+ blocks = value.get('blocks')
+ items = [value] + ([b for b in blocks if isinstance(b, dict)] if isinstance(blocks, list) else [])
+ for item in items:
+ video = item.get('video')
+ if not isinstance(video, dict):
+ continue
+ identity = item.get('library_id')
+ if not isinstance(identity, str) or not specs.LIBRARY_ID.fullmatch(identity):
+ identity = None
+ relative = video.get('file')
+ if not relative and isinstance(video.get('url'), str) and video['url'].startswith('/view?'):
+ query = parse_qs(urlsplit(video['url']).query)
+ if query.get('type', ['output'])[0] == 'output':
+ relative = '/'.join((query.get('subfolder', [''])[0], query.get('filename', [''])[0]))
+ try:
+ identity = library_id(relative) if relative else None
+ except (JobError, TypeError, ValueError):
+ pass
+ if identity:
+ base = '/freevideo/agent/v1/library/' + identity
+ video['url'] = base + '/file'
+ if 'thumbnail' in item:
+ item['thumbnail'] = base + '/thumbnail'
+ else:
+ video.pop('url', None)
+ item.pop('thumbnail', None)
+ return assets.public(value)
+
+
+def replace(row, value):
+ """Make a shared job row equal to value without ever leaving it empty: views read rows off the lock."""
+ row.update(value)
+ for key in [k for k in row if k not in value]:
+ del row[key]
+
+
+def now():
+ return time.time()
+
+
+def iso(stamp):
+ try:
+ return None if stamp is None else time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(stamp))
+ except (OSError, OverflowError, TypeError, ValueError):
+ return None
+
+
+class Jobs:
+ def __init__(self, port, directory, *, clock=now):
+ self.port = port
+ self.ticks = 0
+ self.directory = Path(directory)
+ self.clock = clock
+ self.jobs = {}
+ self.lock = threading.RLock()
+ self.cpu = threading.Semaphore(1)
+ # Optional executor hook: called as parent_allowed(row['parent']) before a
+ # child with a parent may start. A False answer records the job as cancelled.
+ self.parent_allowed = None
+ from .projects import Projects
+ # The page keeps its projects under ComfyUI's output folder; loading may already poll project jobs.
+ self.projects = Projects(port.output_root)
+ from .images import Images
+ self.images = Images(self, self.directory.parent / 'images')
+ self.load()
+ from .productions import Productions
+ self.productions = Productions(self)
+ from .cast import Cast
+ self.cast = Cast(self)
+ films = self.parent_allowed
+ # A card's reference pictures are its own children; everything else belongs to a film.
+ self.parent_allowed = lambda parent: (self.cast.allows(parent) if 'cast' in parent
+ else films(parent) if films is not None else True)
+
+ # Records -------------------------------------------------------------------------------------------
+ def load(self):
+ if not self.directory.is_dir():
+ return
+ # One atomic batch receipt is the commit point. Later per-job records
+ # override its initial rows. A crash never exposes a partial submission.
+ initial = {}
+ for path in sorted(self.directory.glob('b*.json')):
+ try:
+ batch = json.loads(path.read_text(encoding='utf-8'))
+ initial.update({r['id']: r for r in batch['jobs']})
+ except (OSError, ValueError, KeyError, TypeError):
+ continue
+ records = list(initial.values())
+ for path in sorted(self.directory.glob('j*.json')):
+ try:
+ records.append(json.loads(path.read_text(encoding='utf-8')))
+ except (OSError, ValueError):
+ continue
+ for row in records:
+ if (isinstance(row, dict) and specs.JOB_ID.fullmatch(str(row.get('id')))
+ and row.get('kind') in ('generate', 'assemble', 'export', 'image_edit') + GPU_KINDS
+ and row.get('status') in ACTIVE + DONE and isinstance(row.get('spec'), dict)
+ and type(row.get('created_at')) in (int, float) and math.isfinite(row['created_at'])):
+ if row.get('status') == 'running' and row['kind'] in ('assemble', 'export', 'image_edit') + GPU_KINDS:
+ # This process restarted while the work ran in it; nothing continues it.
+ self.finish(row, 'failed', error=dict(code='interrupted',
+ message='ComfyUI restarted while this job ran; submit it again'), save=False)
+ row['_restored'] = True
+ self.jobs[row['id']] = row
+ for row in self.jobs.values():
+ if (row['kind'] != 'generate' or row['spec'].get('refine_from')
+ or row['status'] in DONE and not row.get('resume_pending')
+ or row.get('cancelled_in_jobs')):
+ continue
+ try:
+ if row.get('chain_id') or row.get('chain_submission'):
+ runner = self.port.chain_runner()
+ if runner is not None and not row.get('chain_id'):
+ with runner.lock:
+ record = next((r for r in runner.records.values()
+ if r.get('client_id') == 'agent:' + row['id']), None)
+ if record is not None:
+ row['chain_id'] = record['id']
+ if row.get('chain_id'):
+ self.poll_chain(row)
+ continue
+ self.finish(row, 'interrupted', error=chain_error('interrupted',
+ 'Generation stopped before its chain receipt could be recovered.',
+ 'POST /freevideo/agent/v1/jobs/%s/resume to continue this job.' % row['id'],
+ retryable=True).view(), save=False)
+ elif row['status'] in ('queued', 'running', 'cancelling'):
+ self.finish(row, 'interrupted', error=chain_error('interrupted',
+ 'This generation has no durable chain receipt.',
+ 'POST /freevideo/agent/v1/jobs/%s/resume to create its chain.' % row['id'],
+ retryable=True).view(), save=False)
+ except Exception as error:
+ self.poll_failure(row, error)
+ for row in self.jobs.values():
+ if row.get('_restored'):
+ row.pop('_restored')
+ try:
+ self.save(row)
+ except OSError as error:
+ self.log_poll_failure(row, error)
+
+ def save(self, row):
+ self.directory.mkdir(parents=True, exist_ok=True)
+ path = self.directory / (row['id'] + '.json')
+ temporary = path.with_name(path.name + '.' + uuid.uuid4().hex[:8] + '.tmp')
+ with temporary.open('w', encoding='utf-8') as stream:
+ json.dump({k: v for k, v in row.items() if not k.startswith('_')}, stream, indent=1)
+ stream.flush()
+ os.fsync(stream.fileno())
+ os.replace(temporary, path)
+
+ def touch(self, row, **changes):
+ with self.lock:
+ row.update(changes, updated_at=self.clock())
+ self.save(row)
+
+ def finish(self, row, status, *, result=None, error=None, save=True):
+ if error is not None:
+ code = error.get('code', 'internal_error')
+ if code == 'invalid_json' and row['kind'] in GPU_KINDS:
+ code = 'vlm_invalid_json'
+ if code != error.get('code') or not error.get('request_id'):
+ error = errors.build(code, details=error.get('details'),
+ request=row.get('request_id'), action_required=code != 'cancelled',
+ kind=row['kind'], stage='terminal', resumable=not row['spec'].get('refine_from'))
+ if error is not None:
+ error = dict(error, request_id=row.get('request_id') or error['request_id'])
+ if error.get('next'):
+ error['next'] = errors.recovery(error['code'], kind=row['kind'], stage='terminal',
+ resumable=not row['spec'].get('refine_from')).replace('{id}', row['id'])
+ owner = (row.get('parent') or {}).get('production')
+ if owner and '/resume' in error['next']:
+ error['next'] = ManagedByProduction(owner).view()['next']
+ card = (row.get('parent') or {}).get('cast')
+ if card and '/resume' in error['next']:
+ error['next'] = CAST_AGAIN % card
+ if row['status'] == status and row.get('error') == error and row.get('finished_at') is not None:
+ if result is not None and row.get('result') != result:
+ row['result'] = result
+ if save:
+ self.save(row)
+ return
+ row.update(status=status, finished_at=self.clock(), updated_at=self.clock())
+ if result is not None:
+ row['result'] = result
+ if error is not None:
+ row['error'] = error
+ else:
+ row.pop('error', None)
+ if save:
+ self.save(row)
+
+ def save_batch(self, rows):
+ self.directory.mkdir(parents=True, exist_ok=True)
+ path = self.directory / ('b' + uuid.uuid4().hex + '.json')
+ temporary = path.with_suffix('.tmp')
+ try:
+ with temporary.open('x', encoding='utf-8') as stream:
+ json.dump(dict(jobs=rows), stream, allow_nan=False)
+ stream.flush()
+ os.fsync(stream.fileno())
+ os.replace(temporary, path)
+ finally:
+ temporary.unlink(missing_ok=True)
+
+ def idempotency(self, scope, value, key=None, client=None):
+ alias = value.get('ref')
+ if key is not None:
+ schema.validate(schema.REF, key)
+ if alias is not None:
+ schema.validate(schema.REF, alias)
+ if key is not None and alias is not None and key != alias:
+ raise specs.SpecError(schema.diagnostic('/ref', 'equal to Idempotency-Key when both are supplied', alias))
+ key = key or alias
+ payload = {k: v for k, v in value.items() if k != 'ref'}
+ digest = hashlib.sha256(json.dumps(dict(scope=scope, body=payload), sort_keys=True,
+ separators=(',', ':'), allow_nan=False).encode()).hexdigest()
+ if key is None:
+ return None, None
+ # Keys belong to the client that sent them: separate Agents (or conversations with their own client
+ # name) pick the same natural refs, and one must not be refused for another's earlier request.
+ for row in self.jobs.values():
+ for receipt in row.get('receipts', []):
+ if receipt['key'] == key and receipt.get('client') == client:
+ if receipt['digest'] != digest:
+ raise JobError('idempotency_conflict', 'Key already used')
+ return receipt, [self.jobs[i] for i in receipt['jobs']]
+ return dict(key=key, digest=digest, scope=scope, **({'client': client} if client else {})), None
+
+ def submit(self, value, *, client=None, takes=1, parent=None, editor=None):
+ payload = dict(value, **({'takes': takes} if takes != 1 else {}))
+ return self.submit_request(payload, client=client, parent=parent, editor=editor)[0]
+
+ def submit_request(self, value, *, client=None, key=None, parent=None, editor=None):
+ batch = isinstance(value, dict) and 'jobs' in value
+ schema.validate(schema.batch_schema(local=True) if batch else schema.job_schema(local=True), value)
+ schema.preflight_submission(value)
+ with self.lock:
+ receipt, replay = self.idempotency('submit', value, key, client)
+ if replay is not None:
+ return replay, True
+ batch = 'jobs' in value
+ inputs = value['jobs'] if batch else [value]
+ names, rows, problems = {}, [], []
+ for i, raw in enumerate(inputs):
+ prefix = '/jobs/%d' % i if batch else ''
+ ref = raw.get('ref') if batch else None
+ if ref in names:
+ problems.append(schema.diagnostic(prefix + '/ref', 'a unique batch name', ref))
+ item = {k: v for k, v in raw.items() if k not in ('ref', 'takes')}
+ # Batch refs refer only to preceding rows; self/forward/cyclic
+ # references are rejected before any receipt is written.
+ from .routes import substitute
+ item = substitute(item, names)
+ try:
+ normalized = specs.normalize(item)
+ except specs.SpecError as error:
+ problems.extend(schema.prefix_diagnostic(e, prefix) for e in error.errors)
+ continue
+ known = set(self.jobs) | {r['id'] for r in rows}
+ for dependency in normalized['depends_on']:
+ if dependency not in known:
+ problems.append(schema.diagnostic(prefix + '/after', 'existing jobs or earlier batch refs', dependency))
+ problems.extend(continuation_problems(normalized, prefix, editor=editor))
+ problems.extend(cut_problems(normalized, normalized.get('seconds'), prefix, editor=editor))
+ try:
+ self.port.check(normalized)
+ except specs.SpecError as error:
+ problems.extend(schema.prefix_diagnostic(e, prefix) for e in error.errors)
+ takes = raw.get('takes', 1)
+ for take in range(takes):
+ spec = deepcopy(normalized)
+ if take:
+ spec['seed'] = (secrets.randbelow(specs.MAX_SEED + 1) if spec['seed_random'] else
+ (spec['seed'] + take) % (specs.MAX_SEED + 1))
+ stamp = self.clock()
+ row = dict(id=specs.new_id(), kind=spec['kind'], status='waiting', spec=spec, client=client,
+ take=take + 1 if takes > 1 else None, created_at=stamp, updated_at=stamp,
+ started_at=None, finished_at=None, depends_on=spec['depends_on'],
+ request_id=errors.request_id())
+ rows.append(row)
+ if errors.SESSION.get():
+ row['session'] = errors.SESSION.get()
+ if parent is not None:
+ row['parent'] = deepcopy(parent)
+ if editor is not None:
+ # A project generation (projects.Projects.generate): its own blocks, filled into the project.
+ row['editor'] = deepcopy(editor)
+ if ref and take == 0:
+ names[ref] = row['id']
+ if len(rows) > 64:
+ problems.append(schema.diagnostic('/jobs', 'at most 64 jobs after expanding takes', len(rows)))
+ if problems:
+ raise specs.SpecError(problems)
+ chains = [r for r in rows if r['kind'] == 'generate' and not r['spec'].get('refine_from')]
+ if chains:
+ self.require_runner()
+ for row in chains:
+ if row.get('editor'):
+ if any(block['after'] for block in row['editor']['blocks']) and not self.continuation_ready():
+ raise continuation_unavailable()
+ continue
+ self.require_continuation(row['spec']['seconds'])
+ if row['spec'].get('continue_from') and not self.continuation_ready():
+ raise continuation_unavailable()
+ if receipt:
+ receipt['jobs'] = [r['id'] for r in rows]
+ rows[0]['receipts'] = [receipt]
+ self.save_batch(rows)
+ self.jobs.update({r['id']: r for r in rows})
+ return rows, False
+
+ def get(self, identity):
+ row = self.jobs.get(identity) if isinstance(identity, str) else None
+ if row is None:
+ raise KeyError(identity)
+ if row.get('chain_id') and row['status'] in ACTIVE:
+ with self.lock:
+ self.poll_chain(row)
+ return row
+
+ def rows(self):
+ """Every job, as a copy of the list: readers run on worker threads while another may add a batch."""
+ return list(self.jobs.values())
+
+ def list(self, *, status=None, project=None, kind=None, limit=50):
+ rows = sorted(self.rows(), key=lambda r: r['created_at'], reverse=True)
+ rows = [r for r in rows if (not status or r['status'] in status) and (not kind or r['kind'] == kind)
+ and (not project or r['spec'].get('project') == project)]
+ return rows[:limit]
+
+ def cancel(self, identity):
+ row = self.get(identity)
+ with self.lock:
+ if row['status'] in DONE:
+ return row
+ if row['kind'] == 'generate' and not row['spec'].get('refine_from'):
+ row['_cancel'] = True
+ row['cancel_requested'] = True
+ if row['status'] == 'waiting' or not row.get('chain_id'):
+ row['resume_pending'] = False
+ row['cancelled_in_jobs'] = True
+ self.finish(row, 'cancelled', error=chain_error('cancelled',
+ 'Generation was cancelled before it started.',
+ 'POST /freevideo/agent/v1/jobs/%s/resume to continue.' % row['id']).view())
+ else:
+ row['resume_pending'] = False
+ self.touch(row, status='cancelling')
+ try:
+ self.chain(row['chain_id'])
+ self.require_runner().cancel(row['chain_id'])
+ except (KeyError, JobError):
+ self.missing_chain(row)
+ return row
+ self.poll_chain(row)
+ return row
+ if row['status'] == 'waiting' or row.get('_dispatching'):
+ row['_cancel'] = True
+ if row['status'] == 'waiting' and not row.get('_dispatching'):
+ self.finish(row, 'cancelled', error=dict(code='cancelled', message='Cancelled before it started'))
+ return row
+ row['_cancel'] = True
+ if row['kind'] == 'generate' and row.get('comfy'):
+ state = self.port.cancel(row['comfy']['prompt_id'], row['comfy']['node'])
+ if state == 'cancelled':
+ self.finish(row, 'cancelled', error=dict(code='cancelled', message='Removed from the queue'))
+ elif row['kind'] in GPU_KINDS and row.get('_vlm'):
+ self.port.vlm_cancel(row['_vlm'])
+ return row
+
+ def continuation_ready(self):
+ """Whether this backend can make a video longer than one block."""
+ runner = self.port.chain_runner()
+ if runner is None:
+ return False
+ if getattr(runner.host, 'fake', False):
+ return True
+ from ..comfy_chain import continuation_available
+ return continuation_available() and os.environ.get('FREEVIDEO_CHAIN_INDEPENDENT') != '1'
+
+ def require_continuation(self, seconds):
+ if not single_block(seconds) and not self.continuation_ready():
+ raise continuation_unavailable()
+
+ def require_runner(self):
+ runner = self.port.chain_runner()
+ if runner is None:
+ raise chain_error('chain_unavailable', 'The continuous generation backend is unavailable.',
+ 'Start FreeVideo with the continuous generation backend enabled, then retry.',
+ retryable=True)
+ return runner
+
+ def chain(self, identity):
+ runner = self.require_runner()
+ try:
+ return runner.get(identity)
+ except KeyError:
+ return runner.load(identity)
+
+ def missing_chain(self, row):
+ row['resume_pending'] = False
+ self.finish(row, 'interrupted', error=chain_error('chain_missing',
+ 'The chain receipt for this job is unavailable.',
+ 'Restore its chain receipt, then POST /freevideo/agent/v1/jobs/%s/resume.' % row['id'],
+ retryable=True).view())
+
+ def log_poll_failure(self, row, error):
+ # Exception text/tracebacks can contain prompts and absolute paths.
+ logging.getLogger(__name__).warning('Agent job %s could not be polled (%s)', row['id'], type(error).__name__)
+
+ def invalid_output(self, row):
+ return chain_error('invalid_output', 'The chain finished but its saved output is invalid or unavailable.',
+ 'Restore the saved output, then POST /freevideo/agent/v1/jobs/%s/resume.' % row['id'], retryable=True).view()
+
+ def poll_failure(self, row, error):
+ self.log_poll_failure(row, error)
+ if not row.get('chain_id'):
+ # Not a chain fault. One backend hiccup must not end the job; a lasting one must not hold the queue.
+ count, last = row.get('_poll_failures', (0, None))
+ count = count + 1 if last == self.ticks - 1 else 1
+ row['_poll_failures'] = count, self.ticks
+ if count >= 5 and row['status'] in ACTIVE:
+ self.finish(row, 'failed', error=chain_error('internal_error',
+ 'This job stopped after repeated internal errors.',
+ 'POST /freevideo/agent/v1/jobs to submit it again.', retryable=True).view())
+ return
+ try:
+ chain = self.chain(row['chain_id'])
+ terminal = chain['state'] not in ('queued', 'running', 'cancelling') and chain['output_state'] != 'joining'
+ except Exception:
+ # A broken view can still have a valid terminal state in the runner.
+ try:
+ runner = self.require_runner()
+ with runner.lock:
+ record = runner.records.get(row.get('chain_id'))
+ terminal = record is not None and record.get('state') not in ('queued', 'running', 'cancelling') \
+ and record.get('output_state') != 'joining'
+ except Exception:
+ record, terminal = None, False
+ if record is None and row['status'] in ACTIVE:
+ self.missing_chain(row)
+ return
+ if terminal:
+ row['resume_pending'] = False
+ try:
+ self.finish(row, 'failed', error=self.invalid_output(row))
+ except OSError as failure:
+ self.log_poll_failure(row, failure)
+
+ def runner_busy(self):
+ runner = self.port.chain_runner()
+ if runner is None:
+ return False
+ with runner.lock:
+ return any(r['state'] in ('queued', 'running', 'cancelling') or r['output_state'] == 'joining'
+ for r in runner.records.values())
+
+ def resume(self, identity, *, key=None, value=None, replay_result=False, client=None):
+ value = value or {}
+ schema.validate(schema.contracts()['POST', '/jobs/{id}/resume']['body'], value)
+ with self.lock:
+ # Checked before any receipt replay: a film's child is never resumed on its own.
+ owner = ((self.jobs.get(identity) or {}).get('parent') or {}).get('production')
+ if owner:
+ raise ManagedByProduction(owner)
+ card = ((self.jobs.get(identity) or {}).get('parent') or {}).get('cast')
+ if card:
+ raise chain_error('not_resumable', 'Reference pictures are not resumed on their own.', CAST_AGAIN % card)
+ receipt, replay = self.idempotency('resume:' + identity, value, key, client)
+ if replay is not None:
+ return (replay[0], True) if replay_result else replay[0]
+ try:
+ row = self.jobs[identity]
+ except KeyError:
+ raise chain_error('not_found', 'No job has this ID.',
+ 'GET /freevideo/agent/v1/jobs to find an existing job ID.') from None
+ if (row['kind'] != 'generate' or row['spec'].get('refine_from')
+ or row['status'] not in ('failed', 'interrupted', 'cancelled')):
+ raise chain_error('not_resumable', 'Only failed, interrupted or cancelled generation jobs can resume.',
+ 'GET /freevideo/agent/v1/jobs/%s; wait for active jobs, or POST /jobs for a new generation.' % identity,
+ details=[dict(field='/status', allowed=['failed', 'interrupted', 'cancelled'], got=row['status'])])
+ runner = self.require_runner()
+ if row.get('chain_id'):
+ try:
+ chain = self.chain(row['chain_id'])
+ except KeyError:
+ raise chain_error('chain_missing', 'The saved chain receipt is unavailable.',
+ 'Restore the chain receipt and retry resume, or submit a new job.') from None
+ for block in chain['blocks']:
+ if block['state'] == 'done':
+ try:
+ self.saved_video(block['output'])
+ except (JobError, OSError, ValueError, TypeError):
+ raise chain_error('source_missing', 'A completed block is no longer in the library.',
+ 'Restore the completed block before resuming, or submit a new job.') from None
+ if (chain['state'] == 'done' and chain['output_state'] == 'done'
+ and (row.get('error') or {}).get('code') == 'invalid_output'):
+ # Retry validation of repaired artifacts without replaying completed work.
+ candidate = deepcopy(row)
+ self.poll_chain(candidate)
+ if receipt:
+ candidate.setdefault('receipts', []).append(dict(receipt, jobs=[identity]))
+ self.save(candidate)
+ replace(row, candidate)
+ return (row, False) if replay_result else row
+ original = row
+ row = deepcopy(row)
+ if receipt:
+ row.setdefault('receipts', []).append(dict(receipt, jobs=[identity]))
+ row.pop('error', None)
+ row.pop('_cancel', None)
+ self.touch(row, status='waiting', resume_pending=bool(row.get('chain_id')), cancel_requested=False,
+ cancelled_in_jobs=False,
+ chain_submission='linked' if row.get('chain_id') else None,
+ finished_at=None, attempt=row.get('attempt', 1) + 1)
+ replace(original, row)
+ return (original, False) if replay_result else original
+
+ def queue_view(self):
+ """Describe ownership/order without exposing studio workflows or prompts."""
+ runner = self.port.chain_runner()
+ entries, chains, prompts = [], [], {}
+ if runner is not None:
+ with runner.lock:
+ order = ([runner.active] if runner.active is not None else []) + runner.queue
+ order += [r['id'] for r in runner.records.values() if r['id'] not in order]
+ records = [runner.records[identity] for identity in dict.fromkeys(order)]
+ for record in records:
+ if record['state'] not in ('queued', 'running', 'cancelling'):
+ continue
+ client = record.get('client_id') or ''
+ entry = dict(owner='agent' if client.startswith('agent:') else 'ui',
+ state=record['state'], **({'job_id': client[6:]} if client.startswith('agent:') else {}))
+ chains.append((record['id'], entry))
+ for block in record['blocks']:
+ if block['prompt_id'] and block['state'] in ('queued', 'running'):
+ prompts[block['prompt_id']] = (record['id'], entry)
+ for row in self.active():
+ if row.get('comfy'):
+ prompts[row['comfy']['prompt_id']] = (row['id'], dict(owner='agent', job_id=row['id'], state=row['status']))
+ running, pending = self.port.snapshot()
+ seen = set()
+ for rows, state in ((running, 'running'), (pending, 'queued')):
+ for prompt in rows:
+ if prompt in prompts:
+ identity, entry = prompts[prompt]
+ if identity not in seen:
+ entries.append(dict(entry, state=state))
+ seen.add(identity)
+ else:
+ entries.append(dict(owner='ui', state=state))
+ # A joining chain still holds the generation turn without a ComfyUI prompt.
+ entries = [entry for identity, entry in chains if identity not in seen] + entries
+ known = {e.get('job_id') for e in entries}
+ entries += [dict(owner='agent', job_id=r['id'], state=r['status'])
+ for r in sorted(self.active(), key=lambda r: r['created_at'])
+ if r['kind'] in GPU_KINDS + ('generate',) and r['id'] not in known]
+ ahead = {e['job_id']: dict(count=i, agent=sum(x['owner'] == 'agent' for x in entries[:i]),
+ ui=sum(x['owner'] == 'ui' for x in entries[:i]))
+ for i, e in enumerate(entries) if e.get('job_id')}
+ return dict(entries=entries, ahead=ahead)
+
+ # Views ---------------------------------------------------------------------------------------------
+ def view(self, row, *, detail=True):
+ if row.get('chain_id') and row['status'] in ACTIVE:
+ self.poll_chain(row)
+ progress = self.progress(row) if row['status'] in ('queued', 'running', 'cancelling') else None
+ spec = row['spec']
+ result = dict(id=row['id'], kind=row['kind'], status=row['status'], label=spec.get('label'),
+ project=spec.get('project'), take=row.get('take'), client=row.get('client'),
+ created_at=iso(row['created_at']), started_at=iso(row.get('started_at')),
+ finished_at=iso(row.get('finished_at')), depends_on=row.get('depends_on', []))
+ result['poll_after_ms'] = 500 if row['status'] in ACTIVE else None
+ if row.get('parent'):
+ result['parent'] = deepcopy(row['parent'])
+ if row.get('chain_id'):
+ result['chain_id'] = row['chain_id']
+ if row['kind'] == 'generate':
+ result.update(cancel_requested=row.get('cancel_requested', False), attempt=row.get('attempt', 1))
+ if row['status'] == 'waiting':
+ pending = [d for d in row.get('depends_on', ()) if self.jobs.get(d, {}).get('status') not in DONE]
+ result['waiting_for'] = pending or (['gpu'] if row['kind'] in GPU_KINDS + ('generate',) else [])
+ if row['status'] in ('queued', 'running', 'cancelling'):
+ result['progress'] = progress
+ if row.get('chain_id'):
+ result['last_heartbeat_at'] = result['progress'].pop('last_heartbeat_at', None)
+ if row.get('result') is not None:
+ result['result'] = result_view(row['result']) if row['kind'] == 'generate' else assets.public(row['result'])
+ if row.get('error') is not None:
+ result['error'] = row['error'] if row['error'].get('request_id') else errors.build(
+ row['error'].get('code'), details=row['error'].get('details'), request=row.get('request_id'),
+ kind=row['kind'], stage='terminal', resumable=not row['spec'].get('refine_from'))
+ if result['error'].get('next'):
+ result['error'] = dict(result['error'], next=errors.recovery(result['error']['code'], kind=row['kind'],
+ stage='terminal', resumable=not row['spec'].get('refine_from')).replace('{id}', row['id']))
+ if detail:
+ result['spec'] = {k: v for k, v in spec.items() if k not in ('depends_on',)}
+ if row.get('comfy'):
+ result['comfy'] = row['comfy']
+ return result
+
+ def progress(self, row):
+ if row.get('chain_id'):
+ try:
+ chain = self.chain(row['chain_id'])
+ except Exception as error:
+ if not isinstance(error, (KeyError, JobError)):
+ self.log_poll_failure(row, error)
+ if row['status'] in ACTIVE:
+ self.missing_chain(row)
+ return dict(phase='interrupted', last_heartbeat_at=None)
+ try:
+ message = chain.get('progress') or {}
+ current = next((b for b in chain['blocks'] if b['id'] == chain.get('current')), None)
+ value = dict(phase='joining' if chain['output_state'] == 'joining' else
+ message.get('timing_phase') or message.get('phase') or chain['state'],
+ block=dict(index=current['index'] + 1 if current else min(chain['done'] + 1, chain['count']),
+ total=chain['count'], done=chain['done']),
+ last_heartbeat_at=iso(chain.get('last_heartbeat_at')))
+ if value['phase'] == 'sampling' and message.get('done') is not None:
+ value['step'] = dict(done=message['done'], total=message.get('total'), **({'unit': message['unit']} if message.get('unit') else {}))
+ for key in ('label', 'detail', 'fraction', 'elapsed_seconds', 'remaining_seconds'):
+ if message.get(key) is not None and (key != 'remaining_seconds' or message[key] > 0):
+ value[key] = message[key]
+ return value
+ except Exception as error:
+ self.poll_failure(row, error)
+ return dict(phase=row['status'], last_heartbeat_at=None)
+ if row['kind'] == 'generate' and row.get('comfy'):
+ position = self.port.position(row['comfy']['prompt_id'])
+ if position:
+ return dict(phase='queued', label='Waiting in the ComfyUI queue', queue_position=position)
+ message = self.port.progress(row['comfy']['node'])
+ if not message:
+ return dict(phase='starting', label='Starting')
+ overall = message.get('overall') or {}
+ value = dict(phase=message.get('timing_phase') or message.get('phase') or 'running',
+ label=message.get('label'), detail=message.get('detail'))
+ if value['phase'] == 'sampling' and message.get('done') is not None:
+ value['step'] = dict(done=message['done'], total=message.get('total'), **({'unit': message['unit']} if message.get('unit') else {}))
+ for key in ('fraction', 'elapsed_seconds', 'remaining_seconds', 'estimated'):
+ if overall.get(key) is not None:
+ value[key] = overall[key]
+ for key in ('retry', 'warning'):
+ if message.get(key):
+ value[key] = message[key]
+ return {k: v for k, v in value.items() if v is not None}
+ return dict(phase=row.get('_phase') or ('running' if row['status'] == 'running' else 'queued'),
+ **({'detail': row['_detail']} if row.get('_detail') else {}))
+
+ # Scheduling ----------------------------------------------------------------------------------------
+ def active(self):
+ return [r for r in self.rows() if r['status'] in ACTIVE]
+
+ def stop_session(self, session):
+ """The user stopped a work session: cancel its agent jobs and pause its films. Returns what was stopped."""
+ stopped = dict(jobs=[], dramas=[])
+ for row in [r for r in self.active() if r.get('session') == session]:
+ try:
+ self.cancel(row['id'])
+ stopped['jobs'].append(row['id'])
+ except (KeyError, JobError):
+ pass
+ stopped['dramas'] = self.productions.pause_session(session)
+ return stopped
+
+ async def tick(self):
+ rows = []
+ def advance():
+ with self.lock:
+ rows.extend(self._tick())
+ self.productions.tick()
+ return self.cast.pending()
+ work = asyncio.create_task(asyncio.to_thread(advance))
+ try:
+ try:
+ pending = await asyncio.shield(work)
+ except asyncio.CancelledError:
+ # The worker still owns any reservations it made. Let it finish before
+ # handing them back to the loop, even if this HTTP caller disconnected.
+ await asyncio.gather(work, return_exceptions=True)
+ raise
+ finally:
+ for row in rows:
+ asyncio.ensure_future(self.dispatch(row))
+ # Picking frames for a card's reference pictures decodes video: done off the lock. A card that
+ # cannot be landed records it on the card; it never fails the request that ticked.
+ if pending:
+ await asyncio.to_thread(self.cast.tick)
+
+ def _tick(self):
+ """Advance every unfinished job once, oldest first; safe to call often.
+
+ The GPU takes turns: a VLM job starts only with no generation ahead of it
+ or in ComfyUI's queue, and a generation never overtakes an earlier VLM job.
+ """
+ dispatches = []
+ generation_ahead = vlm_ahead = False
+ self.ticks += 1
+ for row in sorted(self.active(), key=lambda r: r['created_at']):
+ try:
+ kind, status = row['kind'], row['status']
+ if status in ('queued', 'running', 'cancelling') or row.get('_dispatching'):
+ if kind == 'generate' and row.get('chain_id'):
+ self.poll_chain(row)
+ elif kind == 'generate' and row.get('comfy'):
+ self.poll_generation(row)
+ elif kind in GPU_KINDS and row.get('_vlm'):
+ self.poll_vlm(row)
+ if row['status'] in ACTIVE:
+ generation_ahead |= kind == 'generate'
+ vlm_ahead |= kind in GPU_KINDS
+ continue
+ if self.parent_refused(row):
+ continue
+ if self.ready(row) != 'ready':
+ continue
+ if kind == 'generate':
+ if generation_ahead or vlm_ahead or self.port.vlm_busy():
+ generation_ahead = True
+ continue
+ generation_ahead = True
+ if not row['spec'].get('refine_from') and (self.runner_busy() or self.port.queue_busy()):
+ continue
+ elif kind in GPU_KINDS:
+ chain_busy = self.runner_busy()
+ busy = generation_ahead or vlm_ahead or chain_busy or self.port.queue_busy() or self.port.vlm_busy()
+ vlm_ahead = True
+ if busy:
+ continue
+ row['_dispatching'] = True
+ dispatches.append(row)
+ except Exception as error:
+ self.poll_failure(row, error)
+ if row['status'] in ACTIVE:
+ generation_ahead |= row['kind'] == 'generate'
+ vlm_ahead |= row['kind'] in GPU_KINDS
+ return dispatches
+
+ def parent_refused(self, row):
+ """Ask the owning executor once whether this job may still run; if not, record it as cancelled."""
+ gate = self.parent_allowed
+ if gate is None or not row.get('parent'):
+ return False
+ if gate(row['parent']):
+ return False
+ self.finish(row, 'cancelled', error=JobError('cancelled', 'Cancelled before it started').view())
+ return True
+
+ def ready(self, row):
+ for dependency in row.get('depends_on', ()):
+ other = self.jobs.get(dependency)
+ status = other['status'] if other else 'failed'
+ if status in ACTIVE:
+ return 'dependency'
+ if status != 'succeeded':
+ self.finish(row, 'failed', error=dict(code='dependency_failed', job=dependency,
+ message='Job %s did not succeed (%s), so this job cannot run' % (dependency, status)))
+ return 'failed'
+ return 'ready'
+
+ async def dispatch(self, row):
+ def check():
+ if row.get('_cancel'):
+ raise JobError('cancelled', 'Cancelled before it started')
+ with self.lock:
+ # The scheduler reserved this row earlier (or the process restarted
+ # since): ask the owner again immediately before any work starts.
+ if self.parent_allowed is not None and row.get('parent') and not self.parent_allowed(row['parent']):
+ raise JobError('cancelled', 'Cancelled before it started')
+
+ def run():
+ self.touch(row, status='running', started_at=self.clock())
+ if row['kind'] == 'export':
+ from .projects import run_export
+ result = run_export(self.port, row)
+ elif row['kind'] == 'image_edit':
+ from .images import run_render
+ result = run_render(self, row)
+ else:
+ result = self.run_assemble(row)
+ return result
+
+ failure = None
+ succeeded = False
+ result = None
+ try:
+ await asyncio.to_thread(check)
+ if row['kind'] == 'generate':
+ await self.start_generation(row)
+ elif row['kind'] in GPU_KINDS:
+ await asyncio.to_thread(self.start_vlm, row)
+ else:
+ result = await asyncio.to_thread(run)
+ succeeded = True
+ except JobError as error:
+ failure = ('cancelled' if error.code == 'cancelled' else 'failed', error.view())
+ except specs.SpecError as error:
+ failure = ('failed', dict(code='invalid_request', message=str(error), details=error.errors))
+ except Exception as error: # noqa: BLE001 - a job must always end with a reason
+ failure = ('failed', dict(code='internal_error', message='%s: %s' % (
+ type(error).__name__, str(error)[:2000])))
+ finally:
+ def settle():
+ with self.lock:
+ try:
+ if failure is not None:
+ status, reason = failure
+ self.finish(row, status, error=reason)
+ elif succeeded:
+ self.finish(row, 'succeeded', result=result)
+ finally:
+ row.pop('_dispatching', None)
+ await asyncio.to_thread(settle)
+
+ # Inputs --------------------------------------------------------------------------------------------
+ def job_video(self, identity):
+ other = self.get(identity)
+ if other['status'] != 'succeeded' or not (other.get('result') or {}).get('video'):
+ raise JobError('no_video', 'Job %s has no finished video' % identity, job=identity)
+ return self.port.output_path(other['result']['video']['file'])
+
+ def source_video(self, item):
+ if 'from_job' in item:
+ return self.job_video(item['from_job'])
+ if 'library' in item:
+ return self.port.library_video(item['library'])
+ return self.port.input_path(item['file'])
+
+ def media_file(self, row, item, name, *, target=None):
+ """Resolve one media item to a file relative to ComfyUI input (frames, imports, edits)."""
+ folder = 'freevideo/agent/' + row['id']
+ if 'frame' in item:
+ video = self.source_video(item)
+ out = self.port.input_path(folder + '/' + name + '.png', create=True)
+ self.port.extract_frame(video, out, item['frame'])
+ relative = folder + '/' + name + '.png'
+ elif 'from_job' in item or 'library' in item:
+ video = self.source_video(item)
+ relative = folder + '/' + name + video.suffix
+ self.port.import_file(video, self.port.input_path(relative, create=True))
+ elif 'path' in item:
+ source = Path(item['path']).expanduser()
+ if not source.is_absolute() or not source.is_file():
+ raise JobError('invalid_media', 'Local file not found: %s' % item['path'])
+ relative = folder + '/' + name + source.suffix.lower()
+ self.port.import_file(source, self.port.input_path(relative, create=True))
+ else:
+ relative = item['file']
+ if not self.port.input_path(relative).is_file():
+ raise JobError('invalid_media', 'Upload the media file first: %s' % relative)
+ if item.get('edit') is not None:
+ edited = folder + '/' + name + '-edit.png'
+ self.port.edit(relative, item['edit'], self.port.input_path(edited, create=True), target=target)
+ relative = edited
+ return relative
+
+ async def start_generation(self, row):
+ def prepare():
+ spec = row['spec']
+ if row.get('resume_pending'):
+ self.start_chain(row, resume=True)
+ return
+ node = 'fv' + row['id'][1:]
+ if spec.get('refine_from'):
+ ref = spec['refine_from']
+ video = self.job_video(ref['from_job']) if 'from_job' in ref else self.port.library_video(ref['library'])
+ graph = specs.upscale_prompt(node, self.port.output_relative(video))
+ else:
+ prompt = spec['prompt']
+ if isinstance(prompt, dict):
+ other = self.get(prompt['from_job'])
+ prompt = (other.get('result') or {}).get('text')
+ if other['kind'] != 'enhance' or not prompt:
+ raise JobError('dependency_failed', 'Job %s produced no prompt text' % spec['prompt']['from_job'])
+ target = (spec['width'], spec['height'])
+ def resolve():
+ assets = []
+ for role in ('first', 'last'):
+ if role in spec['media']:
+ assets.append(dict(file=self.media_file(row, spec['media'][role], role, target=target),
+ role=role))
+ for i, item in enumerate(spec['media'].get('references', []), 1):
+ assets.append(dict(file=self.media_file(row, item, 'reference-%02d' % i, target=target),
+ role='reference'))
+ return assets
+ assets = resolve()
+ graph = specs.comfy_prompt(spec, node, prompt=prompt, assets=assets)
+ with self.lock:
+ row['inputs'] = dict(media=assets, prompt_chars=len(prompt))
+ if row.get('_cancel'):
+ raise JobError('cancelled', 'Cancelled before it started')
+ extra = {'extra_pnginfo': {'freevideo_agent': dict(job=row['id'], label=spec.get('label'),
+ project=spec.get('project'), client=row.get('client'), api_version=1)}}
+ if spec.get('refine_from'):
+ return graph, extra, node
+ else:
+ payload = dict(node=node, prompt=graph, seconds=spec['seconds'],
+ client_id='agent:' + row['id'], extra_data=extra)
+ if row.get('editor'):
+ payload.pop('seconds')
+ payload['blocks'] = deepcopy(row['editor']['blocks'])
+ elif spec.get('continue_from'):
+ from ..chain_plan import plan
+ source = self.port.output_relative(self.source_video(spec['continue_from']))
+ payload.pop('seconds')
+ payload['join'] = True
+ payload['blocks'] = [dict(id='b%d' % (i + 1), frames=block['frames'], text=prompt,
+ seed=spec['seed'] + i, after='b%d' % i if i else dict(work=source))
+ for i, block in enumerate(plan(spec['seconds'])['blocks'])]
+ self.start_chain(row, payload=payload)
+ work = asyncio.create_task(asyncio.to_thread(prepare))
+ try:
+ submission = await asyncio.shield(work)
+ except asyncio.CancelledError:
+ # Dispatch cleanup must not clear the reservation while preparation is
+ # still importing media or creating the durable chain on another thread.
+ await asyncio.gather(work, return_exceptions=True)
+ raise
+ if submission is not None:
+ graph, extra, node = submission
+ prompt_id = await self.port.submit(graph, extra)
+ def queued():
+ self.touch(row, status='queued', comfy=dict(prompt_id=prompt_id, node=node), queued_at=self.clock())
+ await asyncio.to_thread(queued)
+
+ def start_chain(self, row, *, payload=None, resume=False):
+ runner = self.require_runner()
+ # UI create/resume uses this same lock. There is no check/submit gap.
+ with self.lock, runner.lock:
+ if row.get('_cancel') or row['status'] == 'cancelled':
+ return
+ if (any(r['state'] in ('queued', 'running', 'cancelling') or r['output_state'] == 'joining'
+ for r in runner.records.values()) or self.port.queue_busy() or self.port.vlm_busy()):
+ return
+ # Submit and plan refuse this up front; the backend can still change before a queued or resumed job starts.
+ if (any(b['state'] != 'done' and (b['after'] or b['before'])
+ for b in runner.records[row['chain_id']]['blocks']) if resume
+ else any(b['after'] for b in payload['blocks']) if row.get('editor')
+ else bool(row['spec'].get('continue_from')) or not single_block(payload['seconds'])) and not self.continuation_ready():
+ raise continuation_unavailable()
+ self.touch(row, chain_submission='creating', status='queued', queued_at=self.clock())
+ from ..chain_runner import ChainBusy
+ try:
+ if resume:
+ chain = runner.resume(row['chain_id'], client_id='agent:' + row['id'])
+ else:
+ chain = runner.create(payload)
+ except ChainBusy:
+ if resume:
+ self.touch(row, status='waiting')
+ return
+ raise
+ except Exception:
+ row['resume_pending'] = False
+ if resume:
+ self.finish(row, 'interrupted', error=chain_error('interrupted',
+ 'The backend did not complete this resume request.',
+ 'POST /freevideo/agent/v1/jobs/%s/resume to retry.' % row['id'], retryable=True).view())
+ else:
+ self.finish(row, 'failed', error=chain_error('chain_rejected',
+ 'The continuous generation backend did not accept this request.',
+ 'Change the generation parameters, then POST /freevideo/agent/v1/jobs to submit a new job.').view())
+ return
+ self.touch(row, chain_id=chain['id'], chain_submission='linked', resume_pending=False)
+ if row.get('editor'):
+ self.projects.attach(row, resumed=resume)
+ self.poll_chain(row)
+
+ def poll_chain(self, row):
+ with self.lock:
+ if row.get('cancelled_in_jobs') or row.get('resume_pending') and row['status'] == 'waiting':
+ return
+ try:
+ if row.get('resume_pending'):
+ try:
+ chain = self.chain(row['chain_id'])
+ except (KeyError, JobError):
+ self.missing_chain(row)
+ return
+ row['resume_pending'] = False
+ if chain['state'] in ('failed', 'cancelled', 'interrupted'):
+ self.finish(row, 'interrupted', error=chain_error('interrupted',
+ 'The previous resume request stopped before it could be confirmed.',
+ 'POST /freevideo/agent/v1/jobs/%s/resume to retry.' % row['id'], retryable=True).view())
+ return
+ self.touch(row, chain_submission='linked')
+ self._poll_chain(row)
+ except Exception as error:
+ self.poll_failure(row, error)
+
+ def _poll_chain(self, row):
+ try:
+ chain = self.chain(row['chain_id'])
+ except (KeyError, JobError):
+ if row['status'] in ACTIVE:
+ self.missing_chain(row)
+ return
+ state = chain['state']
+ editor = row.get('editor')
+ if editor:
+ self.projects.deliver(row, chain)
+ status = dict(queued='queued', running='running', cancelling='cancelling', cancelled='cancelled',
+ failed='failed', interrupted='interrupted', done='succeeded')[state]
+ # A project generation fills each part from its own block; nothing is joined.
+ if state == 'done' and chain['output_state'] != 'done' and not (editor and chain['output_state'] == 'none'):
+ status = 'failed' if chain['output_state'] == 'failed' else 'running'
+ if status in DONE:
+ result = None
+ output_error = None
+ try:
+ blocks = []
+ for block in chain['blocks']:
+ identity, video = None, None
+ if block['output']:
+ try:
+ identity = library_id(block['output'])
+ except (JobError, TypeError, ValueError):
+ pass
+ if identity:
+ video = library_view(self.port, block['output'])
+ blocks.append(dict(id=block['id'], index=block['index'] + 1, state=block['state'],
+ library_id=identity, report_id=block['report_id'], video=video))
+ result = dict(chain_id=chain['id'], output_state=chain['output_state'],
+ output_blocks=chain['output_blocks'], report_id=chain.get('last_report_id'), blocks=blocks)
+ if editor:
+ result.update(editor_project=editor['project'], clip_ids=list(editor['ids']),
+ revision=editor.get('revision'))
+ elif chain.get('output') and chain['output_state'] == 'done':
+ self.saved_video(chain['output'])
+ result.update(self.generation_result(row, self.port.output_summary(chain['output'])))
+ elif status == 'succeeded':
+ raise chain_error('invalid_output', 'The completed chain has no saved video.',
+ 'Restore its saved video and read this job again.')
+ except Exception as exception:
+ self.log_poll_failure(row, exception)
+ status = 'failed'
+ output_error = self.invalid_output(row)
+ error = None
+ if status != 'succeeded':
+ code = ('join_failed' if state == 'done' and chain['output_state'] == 'failed' else
+ dict(failed='generation_failed', interrupted='interrupted', cancelled='cancelled')[status])
+ error = chain_error(code, 'Generation %s; completed blocks are retained.' % status,
+ 'POST /freevideo/agent/v1/jobs/%s/resume to retry unfinished work.' % row['id'],
+ details=[dict(field='/chain/state', got=state),
+ dict(field='/chain/output_state', got=chain['output_state'])], retryable=True).view()
+ if output_error is not None:
+ error = output_error
+ elif code == 'generation_failed':
+ error = self.generation_failure(row, chain)
+ if row['status'] != status or row.get('result') != result or row.get('error') != error:
+ self.finish(row, status, result=result, error=error)
+ elif row['status'] != status:
+ self.touch(row, status=status, **({'started_at': self.clock()} if status == 'running'
+ and row.get('started_at') is None else {}))
+
+ def poll_generation(self, row):
+ prompt_id, node = row['comfy']['prompt_id'], row['comfy']['node']
+ state = self.port.prompt_state(prompt_id)
+ if state == 'running' and row['status'] == 'queued':
+ self.touch(row, status='running', started_at=self.clock())
+ if state in ('running', 'pending'):
+ return
+ history = self.port.history(prompt_id)
+ if history is None:
+ if state == 'missing' and self.clock() - row.get('queued_at', row['updated_at']) > 10:
+ self.finish(row, 'cancelled' if row.get('_cancel') else 'failed',
+ error=dict(code='cancelled' if row.get('_cancel') else 'lost',
+ message='The request left the ComfyUI queue without a result'))
+ return
+ status = history.get('status') or {}
+ outputs = (history.get('outputs') or {}).get(node) or {}
+ summary = (outputs.get('freevideo_summary') or [None])[0]
+ if status.get('status_str') == 'success' and summary:
+ self.finish(row, 'succeeded', result=self.generation_result(row, summary))
+ return
+ if status.get('completed') is False or status.get('status_str') == 'error' or not summary:
+ error = self.port.generation_error(history, node)
+ self.finish(row, 'cancelled' if error['code'] == 'cancelled' else 'failed', error=error)
+
+ def generation_result(self, row, summary):
+ spec = row['spec']
+ if not isinstance(summary, dict) or not isinstance(summary.get('video'), str):
+ raise ValueError('Invalid video summary')
+ for key in ('geometry', 'preview_geometry'):
+ if summary.get(key) is not None and not isinstance(summary[key], dict):
+ raise ValueError('Invalid video geometry')
+ for field, value in (summary.get(key) or {}).items():
+ if field in ('width', 'height', 'frames', 'seconds', 'fps') and value is not None and (
+ type(value) not in (int, float) or not math.isfinite(value) or value <= 0):
+ raise ValueError('Invalid video geometry field')
+ video = summary['video']
+ self.saved_video(video)
+ geometry = summary.get('geometry') or {}
+ result = dict(video=library_view(self.port, video),
+ library_id='/'.join(Path(video).parts[1:3]) if video.startswith('FreeVideo/') else None,
+ width=geometry.get('width'), height=geometry.get('height'), frames=geometry.get('frames'),
+ seconds=geometry.get('seconds'), seed=spec.get('seed'), preview=summary.get('preview', False),
+ reused=bool(summary.get('result_cache_hit')), request_seconds=summary.get('request_seconds'),
+ sample_seconds=summary.get('sample_seconds'), vram_peak_bytes=summary.get('vram_peak_bytes'),
+ reference_trims=summary.get('reference_trims') or [])
+ if summary.get('preview') and summary.get('preview_geometry'):
+ result.update(width=summary['preview_geometry'].get('width'),
+ height=summary['preview_geometry'].get('height'),
+ refine_hint='Submit {"refine_from": "%s"} for the full-resolution second pass' % row['id'])
+ return result
+
+ def saved_video(self, relative):
+ identity = library_id(relative)
+ path = self.port.library_video(identity)
+ resolved = Path(path).resolve()
+ root = self.port.output_root.resolve() / 'FreeVideo'
+ if not resolved.is_relative_to(root) or resolved != self.port.output_path(relative).resolve():
+ raise ValueError('Video is outside the library')
+ info = resolved.stat()
+ if not stat.S_ISREG(info.st_mode) or not info.st_size:
+ raise ValueError('Video is not a nonempty regular file')
+ return resolved
+
+ def generation_failure(self, row, chain):
+ block = next((b for b in chain['blocks'] if b['state'] == 'failed'), None)
+ reason = {}
+ if block and block.get('prompt_id'):
+ try:
+ history = self.port.history(block['prompt_id'])
+ if history:
+ reason = self.port.generation_error(history, chain['node'])
+ except Exception as error:
+ self.log_poll_failure(row, error)
+ code = reason.get('code', 'generation_failed')
+ if code not in ('insufficient_memory', 'out_of_memory', 'generation_failed'):
+ code = 'generation_failed'
+ message = str(reason.get('message') or (block or {}).get('error') or
+ 'Generation failed; completed blocks are retained.')
+ for prefix in (str(self.port.output_root), str(Path.home())):
+ message = message.replace(prefix, '<local>')
+ prompt = row['spec'].get('prompt')
+ if isinstance(prompt, str) and prompt:
+ message = message.replace(prompt, '<prompt>')
+ # Enhanced prompts may differ from the submitted prompt.
+ if block:
+ text = (block.get('inputs') or {}).get('text')
+ if isinstance(text, str) and text:
+ message = message.replace(text, '<prompt>')
+ detail = dict(block=block['index'] + 1 if block else None, total=len(chain['blocks']))
+ detail.update({key: reason[key] for key in ('alternatives', 'failure_kind', 'report') if key in reason})
+ next_action = ('Lower the size or duration, then POST /freevideo/agent/v1/jobs to submit a new job.'
+ if code == 'insufficient_memory' else
+ 'POST /freevideo/agent/v1/jobs/%s/resume to retry unfinished work.' % row['id'])
+ if code == 'insufficient_memory' and reason.get('alternatives'):
+ next_action = 'Use the alternatives in details to lower size or duration, then POST /freevideo/agent/v1/jobs.'
+ return chain_error(code, errors.ERRORS[code][2], next_action, details=[detail],
+ retryable=code != 'insufficient_memory').view()
+
+ # Local VLM -----------------------------------------------------------------------------------------
+ def start_vlm(self, row):
+ spec = row['spec']
+ self.touch(row, status='running', started_at=self.clock())
+ row['_phase'] = 'preparing images'
+ if row['kind'] == 'enhance':
+ media = []
+ for role in ('first', 'last'):
+ if role in spec['media']:
+ media.append(dict(file=self.media_file(row, spec['media'][role], role), role=role))
+ for i, item in enumerate(spec['media'].get('references', []), 1):
+ media.append(dict(file=self.media_file(row, item, 'reference-%02d' % i), role='reference'))
+ value, action = dict(text=spec['text'], seconds=spec['seconds'], media=media), 'rewrite'
+ else:
+ questions = []
+ for q, item in enumerate(spec['questions'], 1):
+ images = []
+ for i, image in enumerate(item['images'], 1):
+ images.append(dict(file=self.media_file(row, image, 'q%d-image-%02d' % (q, i)),
+ **({'label': image['label']} if image.get('label') else {})))
+ if item.get('video'):
+ video = self.source_video(item['video'])
+ folder = 'freevideo/agent/%s/q%d-frames' % (row['id'], q)
+ frames = self.port.input_path(folder, create=True)
+ frames.mkdir(exist_ok=True)
+ for frame in self.port.sample_frames(video, frames, item['frames']):
+ name = Path(frame['path']).name
+ stamp = frame['seconds']
+ images.append(dict(file=folder + '/' + name, label='frame at %02d:%06.3f' % (
+ int(stamp // 60), stamp % 60)))
+ questions.append(dict(text=item['text'], images=images))
+ value = dict(questions=questions, format=spec['format'], max_tokens=spec['max_tokens'])
+ if spec.get('system'):
+ value['system'] = spec['system']
+ action = 'ask'
+ if row.get('_cancel'):
+ raise JobError('cancelled', 'Cancelled before it started')
+ row['_phase'] = 'starting'
+ row['_vlm'] = self.port.vlm_start(action, value)
+
+ def poll_vlm(self, row):
+ try:
+ state = self.port.vlm_status(row['_vlm'])
+ except ValueError:
+ self.finish(row, 'failed', error=dict(code='lost', message='The VLM result is no longer available'))
+ return
+ phase = state.get('phase')
+ if phase in ('starting', 'loading', 'rewriting', 'answering', 'finishing', 'cancelling'):
+ row['_phase'] = phase
+ stage = (state.get('diagnostics') or {}).get('stage')
+ row['_detail'] = stage
+ return
+ timings = {k: v for k, v in (state.get('diagnostics') or {}).items()
+ if k in ('load_seconds', 'rewrite_seconds', 'answer_seconds', 'worker_seconds', 'input_tokens',
+ 'output_tokens', 'decode_tokens_per_second')}
+ if phase == 'complete':
+ if row['kind'] == 'enhance':
+ result = dict(text=state.get('text'), timings=timings)
+ else:
+ result = dict(answers=state.get('answers') or [], timings=timings)
+ self.finish(row, 'succeeded', result=result)
+ elif phase == 'cancelled':
+ self.finish(row, 'cancelled', error=dict(code='cancelled', message='Cancelled'))
+ else:
+ code = state.get('error') or 'vlm_failed'
+ self.finish(row, 'failed', error=dict(code=code, message=VLM_ERRORS.get(code, 'The local VLM failed: ' + code),
+ retryable=code in ('busy', 'out_of_memory', 'timeout')))
+
+ # Assembly ------------------------------------------------------------------------------------------
+ def run_assemble(self, row):
+ spec = row['spec']
+ clips = []
+ for item in spec['clips']:
+ clips.append(dict(path=str(self.source_video(item)), start=item.get('start', 0.), end=item.get('end')))
+ name = spec.get('name') or spec.get('label') or row['id']
+ name = ''.join(c if c.isalnum() or c in '._-' else '-' for c in name)[:64].strip('-.') or row['id']
+ relative = 'FreeVideo-Sequences/%s/%s-%s.mp4' % (time.strftime('%Y-%m-%d', time.gmtime()), name, row['id'])
+ if row.get('parent', {}).get('production'):
+ # Deterministic output identity survives a process restart during assembly.
+ run = hashlib.sha256(row['id'].encode()).hexdigest()[:32]
+ relative = 'FreeVideo/%s/%s/video.mp4' % (iso(row['created_at'])[:10], run)
+ out = self.port.output_path(relative, create=True)
+ row['_phase'] = 'assembling'
+ def progress(value):
+ row['_detail'] = value if isinstance(value, str) else json.dumps(value)[:200]
+ with self.cpu:
+ made = self.port.assemble(clips, out, transition=spec['transition'],
+ transition_seconds=spec['transition_seconds'], width=spec.get('width'),
+ height=spec.get('height'), audio=spec['audio'], progress=progress,
+ cancelled=lambda: bool(row.get('_cancel')))
+ if row.get('_cancel'):
+ raise JobError('cancelled', 'Cancelled')
+ manifest = dict(schema='freevideo.sequence', schema_version=1, job=row['id'], label=spec.get('label'),
+ project=spec.get('project'), created_at=iso(self.clock()),
+ clips=[dict(source={k: v for k, v in item.items() if k in ('from_job', 'library', 'file')},
+ start=item.get('start', 0.), end=item.get('end')) for item in spec['clips']],
+ transition=spec['transition'], transition_seconds=spec['transition_seconds'])
+ out.with_suffix('.json').write_text(json.dumps(manifest, indent=1), encoding='utf-8')
+ if row.get('parent', {}).get('production'):
+ out.with_suffix('.request.json').write_text(json.dumps(dict(success=True, geometry={
+ k: made.get(k) for k in ('seconds', 'frames', 'width', 'height')}, sequence=manifest)), encoding='utf-8')
+ return dict(library_id=library_id(relative), video=library_view(self.port, relative),
+ **{k: made.get(k) for k in ('seconds', 'frames', 'width', 'height', 'has_audio', 'clips')})
+ return dict(video=self.port.file_view(relative), seconds=made.get('seconds'), frames=made.get('frames'),
+ width=made.get('width'), height=made.get('height'), has_audio=made.get('has_audio'),
+ clips=manifest['clips'])
+
+
+VLM_ERRORS = {
+ 'busy': 'The GPU was busy; the job can be submitted again',
+ 'model_missing': 'The prompt VLM is not installed; install it from FreeVideo Settings or POST /freevideo/agent/v1/vlm/install',
+ 'ram_space': 'The local VLM needs about 11 GiB of available RAM',
+ 'context_length': 'The question or images are too long for the local VLM',
+ 'invalid_output': 'The VLM answer did not follow the required format',
+ 'vlm_invalid_json': 'The VLM did not return valid JSON',
+ 'out_of_memory': 'The local VLM ran out of memory',
+ 'timeout': 'The local VLM took longer than 10 minutes',
+ 'image_size': 'An image is larger than 50 megapixels',
+ 'unsupported_media': 'The local VLM reads images only',
+}
diff --git a/freevideo_engine/agent/mcp.py b/freevideo_engine/agent/mcp.py
new file mode 100644
index 0000000..1894bc8
--- /dev/null
+++ b/freevideo_engine/agent/mcp.py
@@ -0,0 +1,451 @@
+"""FreeVideo as an MCP server (stdio, JSON-RPC 2.0), for Claude Code, Claude Desktop, Cursor and other agents.
+
+ ./freevideo mcp # Linux / macOS
+ freevideo.cmd mcp # Windows
+ ./freevideo mcp --print-config # ready-to-paste client configuration
+
+Standard library only; it talks to the running ComfyUI through the agent API.
+"""
+import argparse
+import base64
+import io
+import json
+from pathlib import Path
+import sys
+import threading
+import time
+
+from .client import ApiError, Client, DONE
+
+PROTOCOLS = ('2025-06-18', '2025-03-26', '2024-11-05')
+INSTRUCTIONS = """FreeVideo generates videos with synchronized audio (MiniMax H3) on this computer's GPU.
+Start with freevideo_status and freevideo_capabilities. Write prompts as the guide says (freevideo_prompt_guide): English sections
+integrated_multimodal_description / overall_soundscape / non_diegetic_music, [Shot N] cuts, (S1) <d>[Language] ...</d>
+dialogue. Generation uses continuous chains and takes minutes: submit, then call freevideo_wait (at most 25 seconds)
+or freevideo_job. Interrupted/failed/cancelled generation can continue with freevideo_resume; completed blocks stay.
+Chain shots by starting the next shot from the previous one's last frame (media.first = {"from_job": id,
+"frame": "last"}), look at results with freevideo_look, ask the local VLM with freevideo_ask, and join clips
+with freevideo_assemble. For durable filming, use freevideo_drama_plan → start → get → sheet → choose/reshoot → finish.
+Cast first: search freevideo_cast_list, reuse the card the user named or one that fits, create a card only if none does.
+If paused is set, wait for the user using get with since and wait=25. Only the user may pause/resume."""
+
+
+def tool_list():
+ from .schema import mcp_tool_schema
+ read = {'readOnlyHint': True, 'openWorldHint': False}
+ write = {'readOnlyHint': False, 'destructiveHint': False, 'openWorldHint': False}
+ rows = [dict(name='freevideo_status', title='FreeVideo status', description='Readiness, limits, quality levels, aspects, installed LoRAs, local VLM and the queue.', annotations=read),
+ dict(name='freevideo_capabilities', title='Device capabilities', description='Read the same capability cache as the studio. computing means retry after retry_after_seconds.', annotations=read),
+ dict(name='freevideo_asset', title='Retrieve a library asset', description='Download a saved video or thumbnail through authenticated HTTP to target. Use a library_id from a job or library.', annotations=write),
+ dict(name='freevideo_prompt_guide', title='H3 prompt guide', description='How to write prompts: sections, shots and cuts, camera motion, dialogue, references, short-drama tips, and a full example.', annotations=read),
+ dict(name='freevideo_schema', title='Job JSON Schemas', description='JSON Schemas of every job kind and of image edit recipes.', annotations=read),
+ dict(name='freevideo_plan', title='Plan a job', description="Validate a job without running it: actual frames/seconds, sampling passes, warnings and a time estimate from this computer's history. Same fields as freevideo_generate.", annotations=read),
+ dict(name='freevideo_generate', title='Generate a video', description='Generate one video with audio from an H3 prompt, of any length: a longer request continues and joins into one file automatically. Use this for any single video, also after freevideo_enhance_prompt; the drama tools are only for a film of several separately chosen shots. Optionally from first/last frames or references (files, local paths, or frames of earlier jobs). Returns the job; with wait, its result (video path and URL).', annotations=write),
+ dict(name='freevideo_submit_batch', title='Submit a storyboard', description='Submit several jobs at once. Each row is a job object with "kind" (generate default, assemble, vlm, enhance) and an optional "ref"; later rows use "@ref" wherever a job id is expected (from_job, after, clips, refine_from). FreeVideo runs them in dependency order.', annotations=write),
+ dict(name='freevideo_job', title='Job status', description='Status, progress, result or error of a job.', annotations=read),
+ dict(name='freevideo_wait', title='Wait for a job or the user', description="Wait at most 25 seconds for a job (with id) or, without id, for the user's words in this session. Returns early when the user says something (inbox). If the job is still active, call it again with the same ID; do not resubmit.", annotations=read),
+ dict(name='freevideo_jobs', title='List jobs', description='Recent agent jobs, optionally by status (comma-separated), project or kind.', annotations=read),
+ dict(name='freevideo_cancel', title='Cancel a job', description='Cancel a waiting, queued or running job.', annotations={'readOnlyHint': False, 'destructiveHint': True, 'openWorldHint': False}),
+ dict(name='freevideo_resume', title='Resume generation', description='Resume a failed, interrupted or cancelled generation; only unfinished blocks run. Poll the same job ID.', annotations=write),
+ dict(name='freevideo_add_media', title='Add media', description='Read a local image, video or audio file and upload its content; returns the "file" to use in media.', annotations=write),
+ dict(name='freevideo_look', title='Look at media', description='Return a picture you can see: one frame of a video (at = first, last or seconds) or a contact sheet of timed frames (mode = sheet), or an image file. Use it to review shots.', annotations=read),
+ dict(name='freevideo_edit_image', title='Edit an image', description="Crop/rotate/flip/pad/adjust an image, add text, shapes or image overlays, or remove burned-in captions (remove_text), without the browser. The result is a new input file plus an editor document a person can reopen in FreeVideo's image editor.", annotations=write),
+ dict(name='freevideo_ask', title='Ask the local VLM', description='Ask FreeVideo\'s local vision-language model about images or sampled frames of a video (e.g. "Does this shot match its description? Answer as JSON {score, issues}").', annotations=write),
+ dict(name='freevideo_enhance_prompt', title='Enhance a prompt', description='Rewrite a rough idea (any language) into a complete H3 prompt with the local VLM. Images become <Picture N> references.', annotations=write),
+ dict(name='freevideo_assemble', title='Assemble clips', description='Join finished clips (job ids, saved video ids or files) into one video with cuts or crossfades; trims with start/end.', annotations=write),
+ dict(name='freevideo_library', title='Saved videos', description='Saved FreeVideo videos, newest first, with prompts and the agent job that made them.', annotations=read)]
+ from .schema import DRAMA_OPERATIONS
+ rows.extend(dict(name='freevideo_drama_' + name, title='Film: ' + name, description=summary,
+ annotations=read if method == 'GET' or name == 'plan' else write)
+ for name, (method, _, summary) in DRAMA_OPERATIONS.items())
+ from .schema import CAST_OPERATIONS
+ rows.extend(dict(name='freevideo_cast_' + name, title='Cast: ' + name, description=summary,
+ annotations=read if method == 'GET' else dict(write, destructiveHint=True) if name == 'delete' else write)
+ for name, (method, _, summary) in CAST_OPERATIONS.items())
+ from .schema import PROJECT_OPERATIONS, PROJECT_TOOLS
+ rows.extend(dict(name=PROJECT_TOOLS[name], title='Editing project: ' + name, description=summary,
+ annotations=read if method == 'GET' else write)
+ for name, (method, _, summary) in PROJECT_OPERATIONS.items())
+ from .schema import IMAGE_OPERATIONS, IMAGE_TOOLS
+ rows.extend(dict(name=IMAGE_TOOLS[name], title='Image: ' + name, description=summary,
+ annotations=read if method == 'GET' else write)
+ for name, (method, _, summary) in IMAGE_OPERATIONS.items())
+ from .schema import SESSION_OPERATIONS, SESSION_TOOLS
+ rows.extend(dict(name=tool, title='Session: ' + name, description=SESSION_OPERATIONS[name][2],
+ annotations=read if SESSION_OPERATIONS[name][0] == 'GET' else write)
+ for name, tool in SESSION_TOOLS.items())
+ for row in rows:
+ row['inputSchema'] = mcp_tool_schema(row['name'])
+ return rows
+
+
+PROMPTS = [
+ dict(name='short_drama', title='Make a short drama',
+ description='Plan and produce a short drama: script, consistent characters, chained shots, review, assembly.',
+ arguments=[dict(name='idea', description='The story idea', required=True),
+ dict(name='shots', description='Number of shots (default 4)', required=False),
+ dict(name='aspect', description='9:16 (default) or 16:9', required=False)]),
+]
+
+
+def short_drama(arguments):
+ idea = arguments.get('idea') or 'a short story'
+ shots = arguments.get('shots') or '4'
+ aspect = arguments.get('aspect') or '9:16'
+ return f"""Produce a {shots}-shot short drama with FreeVideo from this idea: {idea}
+
+1. Call freevideo_status and freevideo_prompt_guide. Write a screenplay with characters and {shots} shots.
+2. Call freevideo_drama_plan with screenplay and takes_per_shot. Inspect the prompts, then freevideo_drama_start.
+3. Use freevideo_drama_get with since=revision and wait=25. If paused is set, stop acting and long-wait.
+4. Follow todo: freevideo_drama_sheet shows each take, then freevideo_drama_choose or freevideo_drama_reshoot
+ with a concrete note. Continuations wait for the previous chosen take. Prefer aspect "{aspect}" and quality light.
+5. When every shot is chosen, freevideo_drama_finish accepts assembly; get until the output library_id is ready.
+Use ref to replay writes safely. Ordinary job batches remain available through freevideo_submit_batch."""
+
+
+class Server:
+ def __init__(self, client, out=None):
+ self.client = client
+ self.out = out or sys.stdout
+ self.lock = threading.Lock()
+ self.cancelled = set()
+ self.tools = None
+ self.calls = []
+
+ def send(self, message):
+ line = json.dumps(message, ensure_ascii=False)
+ with self.lock:
+ self.out.write(line + '\n')
+ self.out.flush()
+
+ def serve(self, stream=None):
+ stream = stream or sys.stdin
+ try:
+ self.client.hello(via='mcp')
+ except (ApiError, AttributeError):
+ pass # Starting before FreeVideo is allowed; later authenticated requests mark it online.
+ for line in stream:
+ line = line.strip()
+ if not line:
+ continue
+ try:
+ message = json.loads(line)
+ except ValueError:
+ self.send(dict(jsonrpc='2.0', id=None, error=dict(code=-32700, message='Parse error')))
+ continue
+ if isinstance(message, list):
+ for row in message:
+ self.handle(row)
+ else:
+ self.handle(message)
+ for call in self.calls:
+ call.join() # input closed: finish answering what was asked
+
+ def handle(self, message):
+ method, identity = message.get('method'), message.get('id')
+ params = message.get('params') or {}
+ if method == 'notifications/cancelled':
+ self.cancelled.add(params.get('requestId'))
+ return
+ if identity is None:
+ return # other notifications (initialized, ...)
+ if method == 'tools/call':
+ call = threading.Thread(target=self.respond, args=(identity, method, params), daemon=True)
+ self.calls = [c for c in self.calls if c.is_alive()] + [call]
+ call.start()
+ else:
+ self.respond(identity, method, params)
+
+ def respond(self, identity, method, params):
+ try:
+ result = self.dispatch(identity, method, params)
+ self.send(dict(jsonrpc='2.0', id=identity, result=result))
+ except LookupError as error:
+ self.send(dict(jsonrpc='2.0', id=identity, error=dict(code=-32601, message=str(error))))
+ except Exception as error: # noqa: BLE001 - report, keep serving
+ self.send(dict(jsonrpc='2.0', id=identity, error=dict(code=-32603, message='An internal MCP transport error occurred.')))
+
+ def dispatch(self, identity, method, params):
+ from .. import __version__
+ if method == 'initialize':
+ name = (params.get('clientInfo') or {}).get('name')
+ if isinstance(name, str) and name.strip():
+ self.client.name = name[:80]
+ try:
+ self.client.hello(via='mcp')
+ except (ApiError, AttributeError):
+ pass
+ version = params.get('protocolVersion')
+ return dict(protocolVersion=version if version in PROTOCOLS else PROTOCOLS[0],
+ capabilities=dict(tools=dict(listChanged=False), prompts=dict(listChanged=False),
+ resources=dict(listChanged=False)),
+ serverInfo=dict(name='freevideo', title='FreeVideo', version=__version__),
+ instructions=INSTRUCTIONS)
+ if method == 'ping':
+ return {}
+ if method == 'tools/list':
+ if self.tools is None:
+ self.tools = tool_list()
+ return dict(tools=self.tools)
+ if method == 'tools/call':
+ return self.call(identity, params.get('name'), params.get('arguments') or {},
+ (params.get('_meta') or {}).get('progressToken'))
+ if method == 'prompts/list':
+ return dict(prompts=PROMPTS)
+ if method == 'prompts/get':
+ if params.get('name') != 'short_drama':
+ raise LookupError('Unknown prompt')
+ return dict(description=PROMPTS[0]['description'], messages=[dict(role='user', content=dict(
+ type='text', text=short_drama(params.get('arguments') or {})))])
+ if method == 'resources/list':
+ return dict(resources=[
+ dict(uri='freevideo://guide', name='guide', title='H3 prompt guide', mimeType='application/json'),
+ dict(uri='freevideo://schema', name='schema', title='Job JSON Schemas', mimeType='application/json')])
+ if method == 'resources/read':
+ uri = params.get('uri')
+ value = {'freevideo://guide': self.client.guide, 'freevideo://schema': self.client.schema}.get(uri)
+ if value is None:
+ raise LookupError('Unknown resource')
+ return dict(contents=[dict(uri=uri, mimeType='application/json', text=json.dumps(value(), ensure_ascii=False))])
+ raise LookupError('Method not found: %s' % method)
+
+ # Tools -----------------------------------------------------------------------------------------------
+ def call(self, identity, name, arguments, progress_token):
+ from . import schema, spec, errors
+ try:
+ schema.validate(schema.tool_schema(name), arguments)
+ arguments = dict(arguments)
+ session = arguments.pop('session', None)
+ headers = getattr(self.client, 'call_headers', None)
+ if headers is not None:
+ headers.value = dict({'X-FreeVideo-Tool': name}, **({'X-FreeVideo-Session': session} if session else {}))
+ try:
+ value, images = self.tool(identity, name, arguments, progress_token)
+ finally:
+ if headers is not None:
+ headers.value = {}
+ except spec.SpecError as error:
+ problem = errors.validation(error.errors)
+ return dict(content=[dict(type='text', text=errors.text(problem))], structuredContent={'error': problem}, isError=True)
+ except LookupError:
+ problem = errors.build('invalid_request')
+ return dict(content=[dict(type='text', text=errors.text(problem))], structuredContent={'error': problem}, isError=True)
+ except (OSError, ValueError):
+ problem = errors.build('invalid_media')
+ return dict(content=[dict(type='text', text=errors.text(problem))], structuredContent={'error': problem}, isError=True)
+ except ApiError as error:
+ body = dict(error=dict(code=error.code, message=error.message, **error.details))
+ content = [dict(type='text', text=errors.text(body['error']))]
+ if error.inbox:
+ body['inbox'] = error.inbox
+ content.append(dict(type='text', text=json.dumps(dict(inbox=error.inbox), ensure_ascii=False, indent=1)))
+ return dict(content=content, structuredContent=body, isError=True)
+ if isinstance(value, dict) and value.get('error'):
+ return dict(content=[dict(type='text', text=errors.text(value['error']))],
+ structuredContent=value, isError=True)
+ content = [dict(type='text', text=json.dumps(value, ensure_ascii=False, indent=1))]
+ content += images
+ return dict(content=content, structuredContent=value if isinstance(value, dict) else {'items': value},
+ isError=False)
+
+ def tool(self, identity, name, args, token):
+ c = self.client
+ wait = args.pop('wait', None)
+ if name == 'freevideo_status':
+ return c.capabilities(), []
+ if name == 'freevideo_capabilities':
+ return c.capability_table(**args), []
+ if name == 'freevideo_asset':
+ return dict(id=args['id'], path=str(c.asset(args['id'], args['target'],
+ thumbnail=args.get('thumbnail', False)))), []
+ if name == 'freevideo_prompt_guide':
+ return c.guide(), []
+ if name == 'freevideo_schema':
+ return c.schema(), []
+ if name == 'freevideo_plan':
+ return c.plan(dict(args, kind='generate')), []
+ if name in ('freevideo_generate', 'freevideo_assemble', 'freevideo_ask', 'freevideo_enhance_prompt'):
+ kind = dict(freevideo_generate='generate', freevideo_assemble='assemble', freevideo_ask='vlm',
+ freevideo_enhance_prompt='enhance')[name]
+ takes = args.pop('takes', 1)
+ response = c.post('/jobs', dict(args, kind=kind, **({'takes': takes} if takes != 1 else {})))
+ jobs = response['jobs']
+ if wait is None:
+ wait = 0 if kind == 'generate' else 25
+ if wait and len(jobs) == 1:
+ return self.wait(identity, jobs[0]['id'], wait, token), []
+ return (jobs[0] if len(jobs) == 1 else dict(jobs=jobs)), []
+ if name.startswith('freevideo_drama_'):
+ from .schema import DRAMA_OPERATIONS
+ operation = name.removeprefix('freevideo_drama_')
+ method, path, _ = DRAMA_OPERATIONS[operation]
+ for key in ('id', 'shot'):
+ if '{' + key + '}' in path:
+ path = path.replace('{' + key + '}', args.pop(key))
+ if method == 'GET' and wait is not None:
+ args['wait'] = wait
+ value = c.get(path, **args) if method == 'GET' else c.post(path, args)
+ images = []
+ if operation == 'sheet':
+ value = dict(value, takes=[dict(row) for row in value['takes']])
+ for row in value['takes']:
+ images.append(dict(type='image', **row.pop('image')))
+ if value.get('previous'):
+ images.append(dict(type='image', **value['previous']))
+ value['previous'] = True
+ return value, images
+ from .schema import IMAGE_TOOLS, PROJECT_TOOLS, TOOL_ENDPOINTS
+ from .schema import SESSION_OPERATIONS, SESSION_TOOLS
+ if name in SESSION_TOOLS.values():
+ operation = next(op for op, tool in SESSION_TOOLS.items() if tool == name)
+ method, path, _ = SESSION_OPERATIONS[operation]
+ if '{id}' in path:
+ path = path.replace('{id}', args.pop('id'))
+ if method == 'GET' and wait is not None:
+ args['wait'] = wait
+ return (c.get(path, **args) if method == 'GET' else c.post(path, args)), []
+ if name in PROJECT_TOOLS.values() or name in IMAGE_TOOLS.values():
+ method, path = TOOL_ENDPOINTS[name]
+ if '{id}' in path:
+ path = path.replace('{id}', args.pop('id'))
+ return (c.get(path, **args) if method == 'GET' else c.send(method, path, args)), []
+ if name.startswith('freevideo_cast_'):
+ from .schema import CAST_OPERATIONS
+ method, path, _ = CAST_OPERATIONS[name.removeprefix('freevideo_cast_')]
+ if '{id}' in path:
+ path = path.replace('{id}', args.pop('id'))
+ if method == 'GET':
+ return c.get(path, **args), []
+ return c.send(method, path, args), []
+ if name == 'freevideo_submit_batch':
+ return dict(jobs=c.batch(args['jobs'], **({'ref': args['ref']} if 'ref' in args else {}))), []
+ if name == 'freevideo_job':
+ return c.job(args['id'], **({'wait': wait} if wait is not None else {})), []
+ if name == 'freevideo_wait':
+ if not args.get('id'):
+ return c.get('/inbox', wait=min(25., float(args.get('timeout', 25)))), []
+ return self.wait(identity, args['id'], args.get('timeout', 25), token), []
+ if name == 'freevideo_jobs':
+ return dict(jobs=c.jobs(**args)), []
+ if name == 'freevideo_cancel':
+ return c.cancel(args['id']), []
+ if name == 'freevideo_resume':
+ return c.resume(args['id'], **({'ref': args['ref']} if 'ref' in args else {})), []
+ if name == 'freevideo_add_media':
+ return c.upload(args['path']), []
+ if name == 'freevideo_edit_image':
+ made = c.edit(args['source'], args.get('recipe'), document=args.get('document'), target=args.get('target'))
+ return made, self.picture(made['view'])
+ if name == 'freevideo_library':
+ return c.library(**args), []
+ if name == 'freevideo_look':
+ return self.look(args)
+ raise LookupError('Unknown tool: %s' % name)
+
+ def wait(self, identity, job, timeout, token):
+ deadline = time.monotonic() + max(0., min(25., float(timeout)))
+ last = None
+ while True:
+ left = max(0., deadline - time.monotonic())
+ view = self.client.job(job, wait=min(5., left))
+ progress = view.get('progress') or {}
+ if token is not None:
+ fraction = progress.get('fraction')
+ message = progress.get('label') or view['status']
+ if progress.get('remaining_seconds'):
+ message += ' · about %d s left' % progress['remaining_seconds']
+ key = (round(fraction or 0, 3), message)
+ if key != last:
+ last = key
+ self.send(dict(jsonrpc='2.0', method='notifications/progress', params=dict(
+ progressToken=token, progress=round(100 * (fraction or 0), 1), total=100, message=message)))
+ if view['status'] in DONE or left <= 0 or identity in self.cancelled or view.get('inbox'):
+ return view
+
+ def source(self, value):
+ if isinstance(value, str):
+ from .spec import JOB_ID, LIBRARY_ID
+ if JOB_ID.fullmatch(value):
+ return {'from_job': value}
+ if LIBRARY_ID.fullmatch(value):
+ return {'library': value}
+ return {'path': value} if Path(value).is_absolute() else {'file': value}
+ return value
+
+ def look(self, args):
+ source = self.source(args['source'])
+ mode = args.get('mode', 'sheet')
+ if mode == 'image' or ('file' in source or 'path' in source) and Path(
+ source.get('path') or source.get('file')).suffix.lower() in ('.png', '.jpg', '.jpeg', '.webp', '.bmp'):
+ made = self.client.inspect(source)
+ return made, self.picture(made)
+ if mode == 'frame':
+ made = self.client.frame(source, args.get('at'))
+ else:
+ made = self.client.contact_sheet(source, count=args.get('count', 8))
+ return made, self.picture(made['view'])
+
+ def picture(self, view, side=1568):
+ """An MCP image block (JPEG, at most `side` px) so the model sees the picture."""
+ if not view or not view.get('url'):
+ return []
+ data = self.client.request('GET', view['url'], raw=True)
+ try:
+ from PIL import Image
+ with Image.open(io.BytesIO(data)) as image:
+ image = image.convert('RGB')
+ image.thumbnail((side, side))
+ buffer = io.BytesIO()
+ image.save(buffer, format='JPEG', quality=85)
+ data = buffer.getvalue()
+ except ImportError:
+ pass
+ return [dict(type='image', data=base64.b64encode(data).decode(), mimeType='image/jpeg')]
+
+
+def client_config(root):
+ """How MCP clients start this server for this installation."""
+ root = Path(root).resolve()
+ try:
+ machine = json.loads((root / 'machine.json').read_text(encoding='utf-8'))
+ python = machine['python']
+ except (OSError, ValueError, KeyError):
+ python = sys.executable
+ command = [python, '-B', '-m', 'freevideo_engine.agent.mcp', '--root', str(root)]
+ env = {'PYTHONPATH': str(Path(__file__).resolve().parents[2])}
+ import shlex
+ import subprocess
+ quote = lambda p: subprocess.list2cmdline([p]) if sys.platform == 'win32' else shlex.quote(p)
+ return dict(command=command, env=env, codex='codex mcp add freevideo --env PYTHONPATH=%s -- %s' % (
+ quote(env['PYTHONPATH']), ' '.join(quote(p) for p in command)), mcp_json={'mcpServers': {'freevideo': {
+ 'command': command[0], 'args': command[1:], 'env': env}}},
+ claude_code='claude mcp add freevideo --env PYTHONPATH=%s -- %s' % (
+ quote(env['PYTHONPATH']), ' '.join(quote(p) for p in command)))
+
+
+def print_config(root):
+ config = client_config(root)
+ print('Claude Code:\n %s\n' % config['claude_code'])
+ print('Codex:\n %s\n' % config['codex'])
+ print('Claude Desktop / Cursor (mcpServers):')
+ print(json.dumps(config['mcp_json'], indent=2))
+
+
+def main(argv=None):
+ parser = argparse.ArgumentParser(prog='freevideo mcp', description='FreeVideo MCP server (stdio)')
+ parser.add_argument('--root', type=Path, help='FreeVideo installation folder')
+ parser.add_argument('--url', help='ComfyUI address (default: from the installation, else http://127.0.0.1:8188)')
+ parser.add_argument('--print-config', action='store_true', help='Print client configuration and exit')
+ args = parser.parse_args(argv)
+ client = Client(args.url, root=args.root, name='freevideo-mcp')
+ if args.print_config:
+ print_config(client.root)
+ return 0
+ sys.stdin.reconfigure(encoding='utf-8')
+ sys.stdout.reconfigure(encoding='utf-8')
+ Server(client).serve()
+ return 0
+
+
+if __name__ == '__main__':
+ raise SystemExit(main())
diff --git a/freevideo_engine/agent/media.py b/freevideo_engine/agent/media.py
new file mode 100644
index 0000000..a7aecad
--- /dev/null
+++ b/freevideo_engine/agent/media.py
@@ -0,0 +1,740 @@
+"""Inspect, sample and assemble media for agents. Clips are streamed, never held whole in RAM."""
+from contextlib import contextmanager
+from fractions import Fraction
+import math
+from pathlib import Path
+import uuid
+
+from ..comfy_assets import media_kind
+
+FPS = 24
+MAX_SAMPLES = 64
+MAX_CLIPS = 100
+# As the sharing export: browsers play it, and quality survives one more encode.
+VIDEO_OPTIONS = {'crf': '18', 'preset': 'fast'}
+AUDIO_BIT_RATE = 128_000
+AUDIO_CHUNK = 1024
+EPSILON = Fraction(1, 10_000) # Seconds given as floats may land a hair before a frame time.
+SHARP_SIDE = 384 # Sharpness is measured on a copy this size: fast, and blind to pixel-level noise.
+
+
+def inspect(path):
+ path = _file(path)
+ kind = media_kind(path.name)
+ info = dict(path=str(path), name=path.name, kind=kind, bytes=path.stat().st_size)
+ if kind == 'image':
+ from PIL import Image
+ try:
+ with Image.open(path) as image:
+ width, height = image.size
+ orientation = image.getexif().get(0x0112, 1)
+ info.update(format=image.format, mode=image.mode)
+ except Exception as error:
+ raise ValueError('Cannot read image %s: %s' % (path.name, error)) from None
+ if orientation in (5, 6, 7, 8):
+ width, height = height, width
+ return dict(info, width=width, height=height)
+ with _reading(path) as container:
+ video, audio = _video_stream(container), next(iter(container.streams.audio), None)
+ if kind == 'video' and video is None:
+ raise ValueError('%s has no video stream' % path.name)
+ if kind == 'audio' and audio is None:
+ raise ValueError('%s has no audio stream' % path.name)
+ seconds = _stream_seconds(video if kind == 'video' else audio, container)
+ if kind == 'video':
+ context = video.codec_context
+ rate = video.average_rate or video.guessed_rate
+ fps = float(rate) if rate else None
+ rotation = 0
+ for frame in container.decode(video):
+ rotation = _rotation(frame)
+ break
+ width, height = (context.height, context.width) if rotation % 180 else (context.width, context.height)
+ frames, exact = video.frames, video.frames > 0
+ if not exact:
+ frames = round(seconds * fps) if seconds and fps else None
+ info.update(width=width, height=height, rotation=rotation, fps=fps, frames=frames, frames_exact=exact,
+ codec=context.name, pix_fmt=context.pix_fmt)
+ info.update(seconds=seconds, has_audio=audio is not None)
+ if audio is not None:
+ context = audio.codec_context
+ info['audio'] = dict(codec=context.name, sample_rate=context.sample_rate, channels=context.channels,
+ seconds=_stream_seconds(audio, container))
+ return info
+
+
+MAX_UPLOAD_PIXELS = 50 * 1024 * 1024
+MAX_UPLOAD_SECONDS = 3600
+MAX_UPLOAD_FRAMES = 216000
+IMAGE_SUFFIX = {'PNG': '.png', 'JPEG': '.jpg', 'WEBP': '.webp', 'BMP': '.bmp', 'TIFF': '.tiff'}
+
+
+def validate_upload(path):
+ """Decode before publication, with bounded dimensions, duration and work."""
+ info = inspect(path)
+ if info['kind'] == 'image':
+ from PIL import Image
+ with Image.open(path) as image:
+ if image.width * image.height > MAX_UPLOAD_PIXELS or image.width > 16384 or image.height > 16384:
+ raise ValueError('Image exceeds upload pixel limit')
+ suffix = IMAGE_SUFFIX.get(image.format)
+ if suffix is None:
+ raise ValueError('Unsupported decoded image format')
+ if getattr(image, 'n_frames', 1) > MAX_SAMPLES:
+ raise ValueError('Too many image frames')
+ for i in range(getattr(image, 'n_frames', 1)):
+ image.seek(i)
+ image.load()
+ return info, suffix
+ if info.get('seconds') is None or not 0 < info['seconds'] <= MAX_UPLOAD_SECONDS:
+ raise ValueError('Media duration exceeds upload limit')
+ if info.get('width', 1) * info.get('height', 1) > MAX_UPLOAD_PIXELS:
+ raise ValueError('Video dimensions exceed upload limit')
+ count = video_frames = 0
+ audio_seconds = 0.
+ with _reading(path) as container:
+ formats = set(container.format.name.split(','))
+ suffix = (('.m4a' if info['kind'] == 'audio' else '.mp4') if formats & {'mov', 'mp4'} else '.webm' if 'webm' in formats else
+ '.mkv' if 'matroska' in formats else '.wav' if 'wav' in formats else
+ '.mp3' if 'mp3' in formats else '.flac' if 'flac' in formats else
+ '.ogg' if 'ogg' in formats else '.aac' if 'aac' in formats else None)
+ if suffix is None:
+ raise ValueError('Unsupported decoded container format')
+ for frame in container.decode():
+ count += 1
+ if hasattr(frame, 'width'):
+ video_frames += 1
+ elif getattr(frame, 'sample_rate', 0):
+ audio_seconds += frame.samples / frame.sample_rate
+ if count > MAX_UPLOAD_FRAMES or getattr(frame, 'width', 1) * getattr(frame, 'height', 1) > MAX_UPLOAD_PIXELS:
+ raise ValueError('Media exceeds decoded resource limit')
+ if count == 0:
+ raise ValueError('Empty media')
+ if info.get('frames_exact') and video_frames < info['frames']:
+ raise ValueError('Incomplete video frames')
+ if info['kind'] == 'audio' and audio_seconds + .1 < info['seconds']:
+ raise ValueError('Incomplete audio samples')
+ return info, suffix
+
+
+def extract_frame(path, out, at='last'):
+ """Save one frame as PNG: 'first', 'last' (decoded, not taken from metadata) or the frame at/before `at` s."""
+ path = _file(path, 'video')
+ if at not in ('first', 'last'):
+ at = _seconds(at, 'at')
+ with _reading(path) as container:
+ stream = _decodable(container, path)
+ origin, rate = _origin(stream), _rate(stream)
+ if at == 'first':
+ chosen = next(_timed(container, stream, origin), None)
+ elif at == 'last':
+ chosen = _last(container, stream, origin)
+ else:
+ chosen = _at(container, stream, origin, at, path)
+ if chosen is None:
+ raise ValueError('%s contains no frames' % path.name)
+ time, frame = chosen
+ image = _upright(frame.to_image(), _rotation(frame))
+ _save(image, out, 'PNG')
+ return dict(path=str(out), width=image.width, height=image.height, seconds=float(time),
+ frame_index=round(time * rate))
+
+
+def sample_frames(path, out_dir, count=6, max_side=768):
+ """Evenly spaced frames including the first and last, downscaled for a vision model."""
+ out_dir = Path(out_dir)
+ out_dir.mkdir(parents=True, exist_ok=True)
+ max_side = _integer(max_side, 'max_side', 64, 4096)
+ result = []
+ for number, (index, time, image) in enumerate(_picked(path, count), 1):
+ image.thumbnail((max_side, max_side))
+ target = out_dir / ('frame-%02d.jpg' % number)
+ _save(image.convert('RGB'), target, 'JPEG', quality=92)
+ result.append(dict(path=str(target), seconds=float(time), frame_index=index,
+ width=image.width, height=image.height))
+ return result
+
+
+def contact_sheet(path, out, count=8, columns=4, width=1536):
+ """A JPEG grid of evenly spaced frames, each labelled with its MM:SS.mmm time."""
+ from PIL import Image, ImageDraw, ImageFont
+ columns = _integer(columns, 'columns', 1, 16)
+ width = _integer(width, 'width', 256, 4096)
+ picked = list(_picked(path, count))
+ columns = min(columns, len(picked))
+ rows = math.ceil(len(picked) / columns)
+ gap = max(4, width // 192)
+ cell_width = (width - gap * (columns + 1)) // columns
+ first = picked[0][2]
+ cell_height = max(1, round(cell_width * first.height / first.width))
+ sheet = Image.new('RGB', (width, rows * cell_height + gap * (rows + 1)), '#111720')
+ draw = ImageDraw.Draw(sheet)
+ font = ImageFont.load_default(size=max(11, cell_width // 20))
+ for number, (index, time, image) in enumerate(picked):
+ x = gap + number % columns * (cell_width + gap)
+ y = gap + number // columns * (cell_height + gap)
+ image = image.convert('RGB')
+ image.thumbnail((cell_width, cell_height), Image.Resampling.LANCZOS)
+ sheet.paste(image, (x + (cell_width - image.width) // 2, y + (cell_height - image.height) // 2))
+ label = clock(time)
+ left, top, right, bottom = draw.textbbox((0, 0), label, font=font)
+ pad = max(3, (bottom - top) // 3)
+ box = (x + pad, y + cell_height - pad * 3 - (bottom - top), x + pad * 3 + right - left, y + cell_height - pad)
+ draw.rounded_rectangle(box, radius=pad, fill='#0b0f14')
+ draw.text((box[0] + pad - left, box[1] + pad - top), label, font=font, fill='#f2f5f8')
+ _save(sheet, out, 'JPEG', quality=88)
+ return dict(path=str(out), width=sheet.width, height=sheet.height, columns=columns, rows=rows,
+ frames=[dict(seconds=float(time), frame_index=index) for index, time, _ in picked])
+
+
+def clock(seconds):
+ milliseconds = round(float(seconds) * 1000)
+ return '%02d:%02d.%03d' % (milliseconds // 60000, milliseconds // 1000 % 60, milliseconds % 1000)
+
+
+def assemble(clips, out, *, transition='cut', transition_seconds=.5, width=None, height=None, audio=True,
+ progress=None, cancelled=None):
+ """Join trimmed clips into one 24 fps H.264/AAC MP4, with cuts or crossfades."""
+ import av
+ import numpy as np
+ from ..file_ops import publish
+ if not isinstance(clips, (list, tuple)) or not 1 <= len(clips) <= MAX_CLIPS:
+ raise ValueError('clips must list 1 to %d videos' % MAX_CLIPS)
+ if transition not in ('cut', 'crossfade'):
+ raise ValueError("transition must be 'cut' or 'crossfade'")
+ if type(audio) is not bool:
+ raise ValueError('audio must be true or false')
+ plans = [_clip(row, index) for index, row in enumerate(clips)]
+ overlap = 0
+ if transition == 'crossfade' and len(plans) > 1:
+ seconds = _seconds(transition_seconds, 'transition_seconds')
+ if not Fraction(1, FPS) <= seconds <= 3:
+ raise ValueError('transition_seconds must be between 1/24 and 3 seconds')
+ overlap = max(1, round(seconds * FPS))
+ for index, plan in enumerate(plans):
+ needed = overlap * (2 if 0 < index < len(plans) - 1 else 1)
+ if plan['frames'] < needed + (0 if 0 < index < len(plans) - 1 else 1):
+ raise ValueError('clips[%d] is too short (%.3f s) for a %.3f s crossfade'
+ % (index, plan['frames'] / FPS, overlap / FPS))
+ if (width is None) != (height is None):
+ raise ValueError('Give both width and height, or neither')
+ if width is None:
+ width, height = plans[0]['width'] // 2 * 2, plans[0]['height'] // 2 * 2
+ width, height = _integer(width, 'width', 16, 4096), _integer(height, 'height', 16, 4096)
+ if width % 2 or height % 2:
+ raise ValueError('width and height must be even')
+ starts, position = [], 0
+ for plan in plans:
+ starts.append(position)
+ position += plan['frames'] - overlap
+ total = position + overlap
+ rate = next((plan['sample_rate'] for plan in plans if plan['sample_rate']), None) if audio else None
+ out = Path(out)
+ out.parent.mkdir(parents=True, exist_ok=True)
+ temporary = out.with_name('.assemble-%s.mp4' % uuid.uuid4().hex)
+ written = 0
+ def emit(writer, stream, array, sound, limit):
+ nonlocal written
+ if cancelled and cancelled():
+ raise InterruptedError('Assembly cancelled')
+ frame = av.VideoFrame.from_ndarray(array, format='rgb24')
+ frame.pts, frame.time_base = written, Fraction(1, FPS)
+ for packet in stream.encode(frame):
+ writer.mux(packet)
+ written += 1
+ if sound is not None:
+ sound.flush(min(_sample(written, rate), limit))
+ if progress and (written % 12 == 0 or written == total):
+ progress(dict(done=written, total=total))
+ try:
+ with av.open(str(temporary), 'w', format='mp4', options={'movflags': 'faststart'}) as writer:
+ stream = writer.add_stream('libx264', rate=FPS)
+ stream.width, stream.height, stream.pix_fmt = width, height, 'yuv420p'
+ stream.options = dict(VIDEO_OPTIONS)
+ sound = _Audio(writer, rate) if rate else None
+ if progress:
+ progress(dict(done=0, total=total))
+ held = []
+ for index, plan in enumerate(plans):
+ final = index == len(plans) - 1
+ begin, end = starts[index], starts[index] + plan['frames']
+ limit = _sample(end - (0 if final else overlap), rate) if rate else 0
+ if sound is not None:
+ sound.add(_sample(begin, rate), _clip_audio(plan, _sample(end, rate) - _sample(begin, rate), rate))
+ kept = []
+ for number, array in enumerate(_frames(plan, width, height)):
+ if index and number < overlap:
+ weight = number + 1
+ mixed = (held[number].astype(np.uint16) * (overlap + 1 - weight)
+ + array.astype(np.uint16) * weight + (overlap + 1) // 2) // (overlap + 1)
+ emit(writer, stream, mixed.astype(np.uint8), sound, limit)
+ elif not final and number >= plan['frames'] - overlap:
+ kept.append(array)
+ else:
+ emit(writer, stream, array, sound, limit)
+ held = kept
+ for packet in stream.encode():
+ writer.mux(packet)
+ if sound is not None:
+ sound.flush(_sample(total, rate), final=True)
+ if written != total:
+ raise RuntimeError('Assembled %d frames instead of %d' % (written, total))
+ publish(temporary, out)
+ finally:
+ temporary.unlink(missing_ok=True)
+ return dict(path=str(out), seconds=total / FPS, frames=total, width=width, height=height,
+ has_audio=rate is not None, sample_rate=rate, transition=transition,
+ transition_seconds=overlap / FPS if overlap else 0.,
+ clips=[dict(source=plan['path'], start=float(plan['start']), end=float(plan['end']),
+ seconds=plan['frames'] / FPS, frames=plan['frames'], output_start=starts[index] / FPS)
+ for index, plan in enumerate(plans)])
+
+
+class _Audio:
+ """Encode the mixed soundtrack as video frames are written, holding back a crossfade's overlap."""
+ def __init__(self, writer, rate):
+ import numpy as np
+ self.np = np
+ self.writer, self.rate = writer, rate
+ self.stream = writer.add_stream('aac', rate=rate, layout='stereo')
+ self.stream.codec_context.bit_rate = AUDIO_BIT_RATE
+ self.base = 0
+ self.pending = np.zeros((0, 2), np.float32)
+
+ def add(self, start, samples):
+ np = self.np
+ overlap = self.base + len(self.pending) - start
+ if not 0 <= overlap <= min(len(self.pending), len(samples)):
+ raise RuntimeError('Audio overlap out of range')
+ if overlap:
+ # Equal-power fade: two unrelated soundtracks keep a steady loudness.
+ curve = (np.arange(overlap, dtype=np.float32) + .5) / overlap * (np.pi / 2)
+ self.pending[-overlap:] = (self.pending[-overlap:] * np.cos(curve)[:, None]
+ + samples[:overlap] * np.sin(curve)[:, None])
+ self.pending = np.concatenate([self.pending, samples[overlap:]])
+
+ def flush(self, until, final=False):
+ import av
+ count = min(until, self.base + len(self.pending)) - self.base
+ if not final:
+ count -= count % AUDIO_CHUNK
+ for offset in range(0, max(0, count), AUDIO_CHUNK):
+ chunk = self.np.ascontiguousarray(self.pending[offset:min(count, offset + AUDIO_CHUNK)].T)
+ frame = av.AudioFrame.from_ndarray(chunk, format='fltp', layout='stereo')
+ frame.sample_rate, frame.pts, frame.time_base = self.rate, self.base + offset, Fraction(1, self.rate)
+ for packet in self.stream.encode(frame):
+ self.writer.mux(packet)
+ if count > 0:
+ self.pending = self.pending[count:]
+ self.base += count
+ if final:
+ for packet in self.stream.encode():
+ self.writer.mux(packet)
+
+
+def _sample(frame, rate):
+ return round(Fraction(frame * rate, FPS))
+
+
+def _clip(row, index):
+ name = 'clips[%d]' % index
+ if isinstance(row, (str, Path)):
+ row = dict(path=row)
+ if not isinstance(row, dict) or set(row) - {'path', 'start', 'end'} or 'path' not in row:
+ raise ValueError('%s must be {path, start?, end?}' % name)
+ path = _file(row['path'], 'video')
+ start = _seconds(row.get('start', 0), name + '.start')
+ end = None if row.get('end') is None else _seconds(row['end'], name + '.end')
+ with _reading(path) as container:
+ stream = _decodable(container, path)
+ origin, rate = _origin(stream), _rate(stream)
+ first = next(container.decode(stream), None)
+ if first is None:
+ raise ValueError('%s contains no frames' % path.name)
+ rotation = _rotation(first)
+ _seek(container, stream, origin, 0)
+ # The clip's true length from its packets; header durations can be rounded or missing.
+ length, step = None, int(1 / (rate * stream.time_base)) or 1
+ for packet in container.demux(stream):
+ if packet.pts is not None:
+ finish = packet.pts + (packet.duration or step)
+ length = finish if length is None else max(length, finish)
+ seconds = ((length - origin) * stream.time_base if length is not None
+ else Fraction(_stream_seconds(stream, container) or 0))
+ audio = next(iter(container.streams.audio), None)
+ sample_rate = audio.codec_context.sample_rate if audio is not None else None
+ width, height = stream.codec_context.width, stream.codec_context.height
+ stop = seconds if end is None else min(end, seconds)
+ if start >= stop:
+ raise ValueError('%s: start %.3f s is not before its end %.3f s' % (name, start, stop))
+ if rotation % 180:
+ width, height = height, width
+ return dict(path=str(path), start=start, end=stop, frames=math.ceil((stop - start) * FPS - EPSILON),
+ width=width, height=height, rotation=rotation, sample_rate=sample_rate)
+
+
+def _frames(plan, width, height):
+ """Exactly plan['frames'] RGB arrays: at each output time, the source frame shown then."""
+ path, start, total = Path(plan['path']), plan['start'], plan['frames']
+ produced, pending = 0, None
+ for attempt in (0, 1):
+ with _reading(path) as container:
+ stream = _decodable(container, path)
+ stream.thread_type = 'AUTO'
+ origin = _origin(stream)
+ if start > 2 and not attempt:
+ _seek(container, stream, origin, start - 1)
+ for time, frame in _timed(container, stream, origin):
+ if pending is None and time > start + EPSILON and not attempt and start > 2:
+ break # The seek overshot; decode from the start instead.
+ if pending is not None:
+ while produced < total and start + Fraction(produced, FPS) + EPSILON < time:
+ yield pending
+ produced += 1
+ if produced >= total:
+ return
+ pending = _fit(frame, plan['rotation'], width, height)
+ else:
+ break
+ if pending is None:
+ raise ValueError('%s contains no frames' % path.name)
+ while produced < total:
+ yield pending
+ produced += 1
+
+
+def _fit(frame, rotation, width, height):
+ import numpy as np
+ turns = round(rotation / 90) % 4
+ source_width, source_height = frame.width, frame.height
+ shown_width, shown_height = (source_height, source_width) if turns % 2 else (source_width, source_height)
+ if not turns and (shown_width, shown_height) == (width, height):
+ return frame.to_ndarray(format='rgb24')
+ scale = min(width / shown_width, height / shown_height)
+ fit_width, fit_height = max(2, round(shown_width * scale)), max(2, round(shown_height * scale))
+ if (fit_width, fit_height) != (shown_width, shown_height):
+ size = (fit_height, fit_width) if turns % 2 else (fit_width, fit_height)
+ frame = frame.reformat(width=size[0], height=size[1], format='rgb24', interpolation='LANCZOS')
+ array = np.rot90(frame.to_ndarray(format='rgb24'), turns)
+ if array.shape[:2] == (height, width):
+ return np.ascontiguousarray(array)
+ canvas = np.zeros((height, width, 3), np.uint8)
+ top, left = (height - array.shape[0]) // 2, (width - array.shape[1]) // 2
+ canvas[top:top + array.shape[0], left:left + array.shape[1]] = array
+ return canvas
+
+
+def _clip_audio(plan, count, rate):
+ """`count` stereo float samples at `rate` from the clip's start; silence where it has none."""
+ import av
+ import numpy as np
+ result = np.zeros((count, 2), np.float32)
+ path = Path(plan['path'])
+ with _reading(path) as container:
+ audio, video = next(iter(container.streams.audio), None), _video_stream(container)
+ if audio is None or not count:
+ return result
+ resampler = av.AudioResampler(format='fltp', layout='stereo', rate=rate)
+ position = None # Clip sample index of the next converted sample.
+ def place(frames):
+ nonlocal position
+ for converted in frames:
+ data = converted.to_ndarray().T
+ begin, end = max(0, position), min(count, position + len(data))
+ if begin < end:
+ result[begin:end] = data[begin - position:end - position]
+ position += len(data)
+ for frame in container.decode(audio):
+ if position is None:
+ # Samples before the clip's start are skipped; a late audio start leaves leading silence.
+ began = Fraction(frame.pts or 0) * audio.time_base - _origin(video) * video.time_base
+ position = round((began - plan['start']) * rate)
+ place(resampler.resample(frame))
+ if position >= count:
+ break
+ else:
+ if position is not None:
+ place(resampler.resample(None))
+ return result
+
+
+def trim_audio(path, out, start, end):
+ """Write seconds [start, end) of the audio track as 16-bit mono WAV; returns the seconds written."""
+ import av
+ import numpy as np
+ import wave
+ from ..file_ops import publish
+ chunks, rate, position = [], None, None
+ with _reading(_file(path)) as container:
+ audio = next(iter(container.streams.audio), None)
+ if audio is None:
+ raise ValueError('No audio stream')
+ rate = audio.codec_context.sample_rate or 48000
+ origin = Fraction(audio.start_time or 0) * audio.time_base if audio.start_time is not None else 0
+ resampler = av.AudioResampler(format='s16', layout='mono', rate=rate)
+ first, last = round(start * rate), round(end * rate)
+ def place(frames):
+ nonlocal position
+ for converted in frames:
+ data = converted.to_ndarray().reshape(-1)
+ begin, stop = max(first, position), min(last, position + len(data))
+ if begin < stop:
+ chunks.append(data[begin - position:stop - position])
+ position += len(data)
+ for frame in container.decode(audio):
+ if position is None:
+ position = round((Fraction(frame.pts or 0) * audio.time_base - origin) * rate)
+ place(resampler.resample(frame))
+ if position >= last:
+ break
+ else:
+ if position is not None:
+ place(resampler.resample(None))
+ samples = np.concatenate(chunks).astype('<i2') if chunks else np.zeros(0, '<i2')
+ out = Path(out)
+ out.parent.mkdir(parents=True, exist_ok=True)
+ temporary = out.with_name('.%s-%s.partial' % (out.name, uuid.uuid4().hex[:8]))
+ try:
+ with wave.open(str(temporary), 'wb') as stream:
+ stream.setnchannels(1)
+ stream.setsampwidth(2)
+ stream.setframerate(rate)
+ stream.writeframes(samples.tobytes())
+ publish(temporary, out)
+ finally:
+ temporary.unlink(missing_ok=True)
+ return len(samples) / rate
+
+
+def sharpness(frame):
+ """Variance of the 4-neighbour Laplacian on a small grey copy: higher is sharper."""
+ import numpy as np
+ scale = min(1., SHARP_SIDE / max(frame.width, frame.height))
+ width, height = max(8, round(frame.width * scale)), max(8, round(frame.height * scale))
+ grey = frame.reformat(width=width, height=height, format='gray').to_ndarray().astype(np.float32)
+ laplacian = grey[:-2, 1:-1] + grey[2:, 1:-1] + grey[1:-1, :-2] + grey[1:-1, 2:] - 4 * grey[1:-1, 1:-1]
+ return float(laplacian.var())
+
+
+def sharpest_frames(path, outs, *, edge=.08, blur=.35):
+ """Split a clip into len(outs) equal parts by progress and save the sharpest frame of each as PNG.
+
+ Frames within `edge` of either end are skipped, and a part whose sharpest frame scores below
+ `blur` times the clip's sharpest is left out (every frame in it is blurred). Decodes once and
+ keeps one image per part. Returns one row per part: None for a part left out.
+ """
+ path = _file(path, 'video')
+ count = _integer(len(outs), 'count', 1, MAX_SAMPLES)
+ with _reading(path) as container:
+ total = sum(1 for packet in container.demux(_decodable(container, path)) if packet.size)
+ if not total:
+ raise ValueError('%s contains no frames' % path.name)
+ skip = max(0, min(math.floor(total * edge), (total - count) // 2))
+ usable = total - 2 * skip
+ best = [None] * count
+ with _reading(path) as container:
+ stream = _decodable(container, path)
+ for index, (time, frame) in enumerate(_timed(container, stream, _origin(stream))):
+ if index < skip:
+ continue
+ if index >= total - skip:
+ break
+ part = min(count - 1, (index - skip) * count // usable)
+ score = sharpness(frame)
+ if best[part] is None or score > best[part][0]:
+ best[part] = score, index, time, _upright(frame.to_image(), _rotation(frame))
+ top = max((row[0] for row in best if row), default=0)
+ result = []
+ for out, row in zip(outs, best):
+ if row is None or top <= 0 or row[0] < blur * top:
+ result.append(None)
+ continue
+ score, index, time, image = row
+ _save(image.convert('RGB'), out, 'PNG')
+ result.append(dict(seconds=float(time), frame_index=index, width=image.width, height=image.height,
+ sharpness=round(score, 3), progress=round(index / max(1, total - 1), 4)))
+ return result
+
+
+def _picked(path, count):
+ """(frame index, seconds, upright PIL image) for evenly spaced frames, decoding once."""
+ path = _file(path, 'video')
+ count = _integer(count, 'count', 1, MAX_SAMPLES)
+ with _reading(path) as container:
+ total = sum(1 for packet in container.demux(_decodable(container, path)) if packet.size)
+ if not total:
+ raise ValueError('%s contains no frames' % path.name)
+ count = min(count, total)
+ wanted = {(total - 1) // 2} if count == 1 else {round(i * (total - 1) / (count - 1)) for i in range(count)}
+ result, last = [], None
+ with _reading(path) as container:
+ stream = _decodable(container, path)
+ for index, (time, frame) in enumerate(_timed(container, stream, _origin(stream))):
+ last = index, time, frame
+ if index in wanted:
+ result.append((index, time, _upright(frame.to_image(), _rotation(frame))))
+ if len(result) == len(wanted):
+ break
+ if last is None:
+ raise ValueError('%s contains no frames' % path.name)
+ if len(result) < len(wanted) and (not result or result[-1][0] != last[0]):
+ # Fewer decodable frames than packets: the true last frame stands in.
+ result.append((last[0], last[1], _upright(last[2].to_image(), _rotation(last[2]))))
+ return result
+
+
+def _at(container, stream, origin, at, path):
+ """The last frame shown at or before `at` seconds; up to one frame past the end means the last frame."""
+ rate = _rate(stream)
+ for seeking in ((True, False) if at > 2 else (False,)):
+ if seeking and not _seek(container, stream, origin, at - 1):
+ continue
+ if not seeking and at > 2:
+ _seek(container, stream, origin, 0)
+ chosen = None
+ for time, frame in _timed(container, stream, origin):
+ if time > at + EPSILON:
+ break
+ chosen = time, frame
+ else:
+ if chosen is not None and at > chosen[0] + 1 / rate + EPSILON:
+ raise ValueError('at=%.3f s is past the end of %s (%.3f s)'
+ % (at, path.name, chosen[0] + 1 / rate))
+ if chosen is not None:
+ return chosen
+ # A seek past `at` decodes again from the start; a first frame after `at` stands in for it.
+ _seek(container, stream, origin, 0)
+ return next(_timed(container, stream, origin), None)
+
+
+def _last(container, stream, origin):
+ duration = _stream_seconds(stream, container)
+ chosen = None
+ # Seek near the end by the header, then decode to the real end: a wrong duration only costs time.
+ if duration and duration > 3 and _seek(container, stream, origin, Fraction(duration) - 3):
+ for chosen in _timed(container, stream, origin):
+ pass
+ if chosen is None:
+ _seek(container, stream, origin, 0)
+ for chosen in _timed(container, stream, origin):
+ pass
+ if chosen is None:
+ raise ValueError('The video contains no frames')
+ return chosen
+
+
+def _timed(container, stream, origin):
+ rate = _rate(stream)
+ previous = None
+ for frame in container.decode(stream):
+ if frame.pts is not None:
+ time = (Fraction(frame.pts) - origin) * stream.time_base
+ else:
+ time = Fraction(0) if previous is None else previous + 1 / rate
+ previous = time
+ yield time, frame
+
+
+def _seek(container, stream, origin, seconds):
+ import av
+ try:
+ container.seek(int(origin + max(Fraction(0), seconds) / stream.time_base), stream=stream, backward=True)
+ return True
+ except av.error.FFmpegError:
+ return False
+
+
+def _origin(stream):
+ return Fraction(stream.start_time or 0)
+
+
+def _rate(stream):
+ rate = stream.average_rate or stream.guessed_rate or stream.base_rate
+ rate = Fraction(rate) if rate else Fraction(FPS)
+ return rate if 1 <= rate <= 240 else Fraction(FPS)
+
+
+def _rotation(frame):
+ try:
+ return round(frame.rotation or 0) % 360
+ except (AttributeError, ValueError):
+ return 0
+
+
+def _upright(image, rotation):
+ from PIL import Image
+ turns = round(rotation / 90) % 4
+ return image.transpose((None, Image.Transpose.ROTATE_90, Image.Transpose.ROTATE_180,
+ Image.Transpose.ROTATE_270)[turns]) if turns else image
+
+
+def _stream_seconds(stream, container):
+ if stream is not None and stream.duration and stream.time_base:
+ return float(stream.duration * stream.time_base)
+ return container.duration / 1e6 if container.duration else None
+
+
+def _video_stream(container):
+ import av
+ attached = getattr(getattr(av.stream, 'Disposition', None), 'attached_pic', 0)
+ for stream in container.streams.video:
+ if not (attached and stream.disposition & attached):
+ return stream # Cover art in audio files is not a video.
+ return None
+
+
+def _decodable(container, path):
+ stream = _video_stream(container)
+ if stream is None:
+ raise ValueError('%s has no video stream' % path.name)
+ return stream
+
+
+@contextmanager
+def _reading(path):
+ import av
+ try:
+ try:
+ container = av.open(str(path), metadata_errors='ignore')
+ except TypeError: # PyAV 19 dropped the option
+ container = av.open(str(path))
+ with container:
+ yield container
+ except av.error.FFmpegError as error:
+ raise ValueError('Cannot read %s: %s' % (path.name, error)) from None
+
+
+def _file(path, kind=None):
+ if not isinstance(path, (str, Path)) or not str(path):
+ raise ValueError('A media file path is required')
+ path = Path(path)
+ if not path.is_file():
+ raise ValueError('No such media file: %s' % path.name)
+ if kind and media_kind(path.name) != kind:
+ raise ValueError('%s is not a %s file' % (path.name, kind))
+ return path
+
+
+def _seconds(value, name):
+ if (isinstance(value, bool) or not isinstance(value, (int, float, Fraction))
+ or not math.isfinite(value) or value < 0):
+ raise ValueError('%s must be a number of seconds, 0 or more' % name)
+ return Fraction(value)
+
+
+def _integer(value, name, low, high):
+ if type(value) is not int or not low <= value <= high:
+ raise ValueError('%s must be an integer from %d to %d' % (name, low, high))
+ return value
+
+
+def _save(image, out, format, **options):
+ from ..file_ops import publish
+ out = Path(out)
+ out.parent.mkdir(parents=True, exist_ok=True)
+ temporary = out.with_name('.%s-%s.partial' % (out.name, uuid.uuid4().hex[:8]))
+ try:
+ image.save(temporary, format, **options)
+ publish(temporary, out)
+ finally:
+ temporary.unlink(missing_ok=True)
diff --git a/freevideo_engine/agent/operation_receipts.py b/freevideo_engine/agent/operation_receipts.py
new file mode 100644
index 0000000..b460880
--- /dev/null
+++ b/freevideo_engine/agent/operation_receipts.py
@@ -0,0 +1,30 @@
+"""Load durable operation receipts, including the legacy ref-keyed dictionaries.
+
+New records use a list of {key, digest, result, client?}, as Jobs does, so the
+same key can belong to several clients without changing the ref's syntax.
+"""
+from . import schema
+
+
+def load(value):
+ if isinstance(value, dict):
+ if not all(isinstance(receipt, dict) for receipt in value.values()):
+ raise ValueError('Invalid operation receipt')
+ value = [dict(receipt, key=key) for key, receipt in value.items()]
+ if not isinstance(value, list):
+ raise ValueError('Invalid operation receipts')
+ seen = set()
+ for receipt in value:
+ if not isinstance(receipt, dict):
+ raise ValueError('Invalid operation receipt')
+ schema.validate(schema.REF, receipt['key'])
+ client = receipt.get('client')
+ if client is not None and (not isinstance(client, str) or not 1 <= len(client) <= 80):
+ raise ValueError('Invalid receipt client')
+ if not isinstance(receipt['digest'], str) or not isinstance(receipt['result'], dict):
+ raise ValueError('Invalid operation receipt')
+ identity = (client, receipt['key'])
+ if identity in seen:
+ raise ValueError('Duplicate operation receipt')
+ seen.add(identity)
+ return value
diff --git a/freevideo_engine/agent/production.py b/freevideo_engine/agent/production.py
new file mode 100644
index 0000000..9faf0a2
--- /dev/null
+++ b/freevideo_engine/agent/production.py
@@ -0,0 +1,700 @@
+"""Durable production decisions, without storage, clocks, queues or model calls.
+
+Mutators are atomic in memory and increment revision once per actual change.
+Persist their state before executing advance()'s actions. The executor must
+atomically deduplicate *all* actions by ref (including cancellation tombstones)
+and supply its authoritative children snapshot when recovering. Missing children
+cause the same saved submit/join to be replayed, never a new take.
+Paused attempts retain cancellation receipts across resume; their replacements
+keep the take and seed but use a new, durably reserved submission ref.
+"""
+from copy import deepcopy
+import hashlib
+import json
+import math
+import re
+
+from . import drama, spec
+
+ACTIVE = ('waiting', 'queued', 'running', 'cancelling')
+TERMINAL = ('succeeded', 'failed', 'cancelled', 'interrupted')
+ACTORS = ('agent', 'builtin', 'user')
+CHANGES = ('action', 'lines', 'camera', 'framing', 'prompt', 'seconds')
+NEXT = {
+ 'invalid_screenplay': 'Fix every listed problem and retry the request.',
+ 'unknown_shot': 'Use a shot id from the production view.',
+ 'unknown_take': 'Use a take number from this shot in the production view.',
+ 'take_not_ready': 'Choose a succeeded, non-stale take, or reshoot this shot.',
+ 'chosen_by_user': 'Leave this shot unchanged; only the user may change it.',
+ 'not_ready': 'Resolve each listed shot, then retry finish.',
+ 'nothing_to_cancel': 'Choose completed takes, reshoot a shot, or finish the production.',
+ 'not_allowed': 'Only the user may stop or continue a production.',
+ 'already_ended': 'Use an unfinished, uncancelled production.',
+ 'stopped_by_user': 'Wait until the user continues the production.',
+}
+
+
+class ProductionError(ValueError):
+ """Stable machine code plus an English explanation and actionable next step."""
+ def __init__(self, code, message, *, details=None, problems=None):
+ self.code, self.message, self.next = code, message, NEXT[code]
+ self.details = details if details is not None else {}
+ self.problems = problems if problems is not None else []
+ super().__init__(message)
+
+
+def _invalid(problems):
+ if problems:
+ raise ProductionError('invalid_screenplay', problems[0]['message'], problems=problems,
+ details={'problems': problems})
+
+
+def _count(value, path, problems):
+ if type(value) is not int or not 1 <= value <= 8:
+ problems.append(dict(path=path, message='must be an integer from 1 to 8'))
+ return False
+ return True
+
+
+def _json(value, problems):
+ try:
+ json.dumps(value, allow_nan=False)
+ except (TypeError, ValueError, OverflowError):
+ problems.append(dict(path='', message='must contain only finite JSON values'))
+
+
+def _compiled(play, shot):
+ # The pure route has no enhance job: an idea is literal action text.
+ shot = deepcopy(shot)
+ if not shot.get('action') and not shot.get('prompt'):
+ shot['action'] = shot.get('idea', '')
+ return drama.prompt(play, shot)
+
+
+def plan(request):
+ """Return {'request': normalized copy, 'preview': {'shots': [...], 'total': N}}."""
+ problems = []
+ if not isinstance(request, dict):
+ _invalid([dict(path='', message='A production request must be an object')])
+ _json(request, problems)
+ play = deepcopy(request.get('screenplay'))
+ play_ok = True
+ try:
+ drama.check(play)
+ except drama.Screenplay as error:
+ play_ok = False
+ problems.extend(dict(path='/screenplay' + p['path'], message=p['message']) for p in error.problems)
+ count = request.get('takes_per_shot', 1)
+ count_ok = _count(count, '/takes_per_shot', problems)
+ director = request.get('director', 'agent')
+ if director not in ('agent', 'builtin'):
+ problems.append(dict(path='/director', message='must be "agent" or "builtin"'))
+ rows = play.get('shots', []) if isinstance(play, dict) else []
+ total = 0
+ if isinstance(rows, list):
+ for i, shot in enumerate(rows):
+ if not isinstance(shot, dict):
+ continue
+ n = shot.get('takes', count if count_ok else 0)
+ if type(n) is int and 1 <= n <= 8:
+ total += n
+ if type(shot.get('seed')) is int and shot['seed'] + n > spec.MAX_SEED:
+ problems.append(dict(path='/screenplay/shots/%d/seed' % i,
+ message='seed plus the take number exceeds the maximum seed'))
+ if total > 120:
+ problems.append(dict(path='/screenplay/shots', message='The total number of takes must be at most 120'))
+ preview = []
+ if play_ok:
+ for i, shot in enumerate(rows):
+ text = _compiled(play, shot)
+ label = '%s · %s' % (play.get('title') or 'drama', shot['id'])
+ for value, path, limit in ((text, '/screenplay/shots/%d/prompt' % i, 20000),
+ (label, '/screenplay/title', 120)):
+ try:
+ spec._text(value, path, limit)
+ except spec.SpecError as error:
+ problems.extend(error.errors)
+ preview.append(dict(id=shot['id'], continues=shot.get('continue', False),
+ takes=shot.get('takes', count), prompt=text))
+ _invalid(problems)
+ return dict(request=dict(screenplay=play, takes_per_shot=count, director=director),
+ preview=dict(shots=preview, total=total))
+
+
+def corrected_prompt(play, shot, note=None):
+ """Compile a per-generation correction without changing the screenplay."""
+ if not note:
+ return _compiled(play, shot)
+ correction = 'Correction for this take: ' + note
+ if shot.get('prompt'):
+ text = shot['prompt']
+ # Insert at the end of the visual section, before either audio section.
+ visual = re.search(r'(?m)^\s*integrated_multimodal_description\s*:', text)
+ start = visual.end() if visual else 0
+ end = re.search(r'(?m)^\s*(?:overall_soundscape|non_diegetic_music)\s*:', text[start:])
+ stop = start + end.start() if end else len(text)
+ return text[:stop].rstrip() + ' ' + correction + ('\n\n' + text[stop:].lstrip() if end else '')
+ shot = deepcopy(shot)
+ # A unique marker prevents cast name expansion from rewriting the note.
+ marker = '\x00'
+ shot['action'] = (shot.get('action') or shot.get('idea') or '').rstrip() + ' ' + marker
+ return drama.prompt(play, shot).replace(marker, correction)
+
+
+def _actor(by):
+ if by not in ACTORS:
+ _invalid([dict(path='/by', message='must be "agent", "builtin" or "user"')])
+
+
+def _editable(state, by):
+ _actor(by)
+ if state.get('paused') and by != 'user':
+ raise ProductionError('stopped_by_user',
+ 'The user stopped this film. It cannot be changed until the user continues.')
+
+
+def _pause_guard(state, by):
+ if by != 'user':
+ raise ProductionError('not_allowed', 'Only the user may stop or continue this film.')
+ if state['cancelled'] or state['status'] == 'finished':
+ raise ProductionError('already_ended', 'This film has already ended.')
+
+
+def _optional_text(value, path):
+ if value is not None:
+ try:
+ spec._text(value, path, 20000)
+ except spec.SpecError as error:
+ _invalid(error.errors)
+
+
+def _decision(state, now, by, action, shot=None, take=None, reason=None):
+ state['decisions'].append(dict(at=now, by=by, action=action, shot=shot, take=take, reason=reason))
+
+
+def _shot(state, identity):
+ for row in state['shots']:
+ if row['id'] == identity:
+ return row
+ raise ProductionError('unknown_shot', 'The shot does not exist.', details={'shot': identity})
+
+
+def _take(shot, number):
+ for row in shot['takes']:
+ if type(number) is int and row['take'] == number:
+ return row
+ raise ProductionError('unknown_take', 'The take does not exist in this shot.',
+ details={'shot': shot['id'], 'take': number})
+
+
+def _chosen(shot):
+ return next((t for t in shot['takes'] if t['take'] == shot['chosen']
+ and t['state'] == 'succeeded' and not t['stale']), None)
+
+
+def _parent(state, shot):
+ if shot['continues']:
+ return _chosen(state['shots'][shot['index'] - 2])
+ return None
+
+
+def _guard(shot, by):
+ if shot['chosen_by'] == 'user' and by != 'user':
+ raise ProductionError('chosen_by_user', 'This shot was chosen by the user.', details={'shot': shot['id']})
+
+
+def _reserve(state, shot, jobs):
+ """Assign a generation's durable refs without ever reusing an issued ref."""
+ shot['generation'] += 1
+ for number, take in enumerate(jobs, shot['next_take']):
+ seed = shot['base_seed'] + 1000 * shot['generation'] + number
+ if seed > spec.MAX_SEED:
+ _invalid([dict(path='/seed', message='This generation exceeds the maximum seed')])
+ ref = '%s:s%d:g%d:t%d' % (state['id'], shot['index'], shot['generation'], number)
+ take.update(take=number, job=ref, generation=shot['generation'], seed=seed)
+ take['spec'].update(ref=ref, seed=seed)
+ take['spec']['metadata']['take'] = number
+ shot['next_take'] += len(jobs)
+
+
+def _schedule(state, shot, count, by, note=None, *, automatic=False):
+ """Save immutable templates; automatic reconnects reserve refs at advance()."""
+ source = state['screenplay']['shots'][shot['index'] - 1]
+ text = corrected_prompt(state['screenplay'], source, note)
+ try:
+ spec._text(text, '/prompt', 20000)
+ except spec.SpecError as error:
+ _invalid(error.errors)
+ jobs = []
+ for _ in range(count):
+ job = drama.shot_job(state['screenplay'], source, shot['index'] - 1, None)
+ job.update(prompt=text, metadata=dict(drama=state['id'], shot=shot['id']))
+ job.pop('media', None)
+ if job['project'] is None:
+ job.pop('project')
+ if not shot['continues']:
+ if source.get('first') is not None:
+ job['media'] = {'first': deepcopy(source['first'])}
+ elif 'references' in source:
+ job['media'] = {'references': deepcopy(source['references'])}
+ jobs.append(dict(take=None, job=None, generation=None, seed=None, state='queued', automatic=automatic,
+ stale=False, continues_take=None, note=note, by=by, library_id=None, seconds=None,
+ cancel_requested=False, error=None, spec=job))
+ if not automatic:
+ _reserve(state, shot, jobs)
+ shot['pending'].append(jobs)
+
+
+def _launch_ready(state, now, *, automatic=False):
+ if state['cancelled'] or state.get('paused'):
+ return
+ for shot in state['shots']:
+ parent = _parent(state, shot)
+ if shot['continues'] and parent is None:
+ continue
+ waiting = []
+ for generation in shot['pending']:
+ if generation[0].get('automatic') and not automatic:
+ waiting.append(generation)
+ continue
+ if generation[0]['job'] is None:
+ _reserve(state, shot, generation)
+ for take in generation:
+ if parent:
+ take['continues_take'] = parent['job']
+ take['spec']['continue_from'] = {'ref': parent['job']}
+ shot['takes'].append(take)
+ _decision(state, now, take['by'], 'shot', shot['id'], take['take'])
+ shot['pending'] = waiting
+
+
+def _usable(shot):
+ # A cancellation may already have reached the executor; never withdraw it.
+ # A success that wins that race remains usable, regardless of the request.
+ return any(not t['stale'] and (t['state'] == 'succeeded' or
+ (t['state'] in ACTIVE + ('paused',) and not t['cancel_requested'])) for t in shot['takes'])
+
+
+def _remember(shot):
+ chosen = next((t for t in shot['takes'] if t['take'] == shot['chosen']), None)
+ if chosen and chosen['continues_take']:
+ shot.setdefault('choices', {})[chosen['continues_take']] = dict(take=chosen['take'], by=shot['chosen_by'])
+
+
+def _drop_automatic(shot):
+ shot['pending'] = [g for g in shot['pending'] if not g[0].get('automatic')]
+
+
+def _reconnect(state, shot):
+ """Derive validity and restore the choice made under this exact parent job."""
+ if not shot['continues']:
+ return
+ _remember(shot)
+ parent = _parent(state, shot)
+ for take in shot['takes']:
+ take['stale'] = bool(take['continues_take'] and
+ (parent is None or take['continues_take'] != parent['job']))
+ if take['stale'] and take['state'] in ACTIVE + ('paused',):
+ take['cancel_requested'] = True
+ if not _chosen(shot):
+ shot['chosen'] = shot['chosen_by'] = None
+ choice = shot.get('choices', {}).get(parent['job']) if parent else None
+ if choice:
+ take = _take(shot, choice['take'])
+ if take['state'] == 'succeeded' and not take['stale']:
+ shot['chosen'], shot['chosen_by'] = take['take'], choice['by']
+ if _usable(shot):
+ _drop_automatic(shot)
+
+
+def _reconnect_after(state, shot, by, now, cascade):
+ for child in state['shots'][shot['index']:]:
+ if not child['continues']:
+ break
+ _reconnect(state, child)
+ if not cascade:
+ _drop_automatic(child)
+ elif child['takes'] and not _usable(child) and not child['pending']:
+ # No bound takes means there is nothing to reconnect (for example,
+ # the user cancelled the original, still-unstarted generation).
+ _schedule(state, child, child['default_takes'], by, automatic=True)
+ _decision(state, now, by, 'restale', child['id'], reason='The preceding chosen take changed.')
+
+
+def _refresh(state):
+ for shot in state['shots']:
+ _reconnect(state, shot)
+ usable = [t for t in shot['takes'] if not t['stale']]
+ if _chosen(shot):
+ shot['state'] = 'chosen'
+ elif any(t['state'] in ACTIVE and not t['cancel_requested'] for t in usable):
+ shot['state'] = 'shooting'
+ elif any(t['state'] == 'succeeded' for t in usable):
+ shot['state'] = 'needs_choice'
+ elif any(t['state'] == 'paused' and not t['cancel_requested'] for t in usable):
+ shot['state'] = 'paused'
+ elif shot['pending']:
+ shot['state'] = 'waiting' if shot['continues'] and _parent(state, shot) is None else 'shooting'
+ else:
+ shot['state'] = 'failed'
+ current = next((j for j in state['joins'] if j['ref'] == state['current_join']), None)
+ if state['cancelled']:
+ state['status'] = 'cancelled'
+ elif state.get('paused'):
+ state['status'] = 'paused'
+ elif current and current['state'] in ACTIVE:
+ state['status'] = 'joining'
+ elif current and current['state'] == 'succeeded':
+ state['status'] = 'finished'
+ elif any(s['state'] == 'shooting' for s in state['shots']) or any(
+ t['state'] in ACTIVE and not t['stale'] and not t['cancel_requested']
+ for s in state['shots'] for t in s['takes']):
+ state['status'] = 'shooting'
+ elif all(_chosen(s) for s in state['shots']):
+ state['status'] = 'ready'
+ else:
+ state['status'] = 'needs_choice'
+
+
+def _commit(state, draft, now):
+ _refresh(draft)
+ if draft != state:
+ draft['revision'] = state['revision'] + 1
+ draft['updated_at'] = now
+ state.clear()
+ state.update(draft)
+
+
+def new(identity, request, *, now):
+ """Create a JSON receipt. Shot indices start at 1; generations start at 0."""
+ request = plan(request)['request']
+ if not isinstance(identity, str) or not spec.SLUG.fullmatch(identity):
+ _invalid([dict(path='/id', message='Production id must be a unique short name')])
+ state = dict(version=1, id=identity, title=request['screenplay'].get('title'), revision=1,
+ status='shooting', director=request['director'], created_at=now, updated_at=now,
+ screenplay=request['screenplay'], takes_per_shot=request['takes_per_shot'], shots=[],
+ decisions=[], outputs=[], joins=[], current_join=None, cancelled=False, paused=None)
+ base = int.from_bytes(hashlib.sha256(identity.encode('utf-8')).digest()[:4], 'big')
+ _decision(state, now, request['director'], 'started')
+ for i, source in enumerate(state['screenplay']['shots'], 1):
+ shot = dict(id=source['id'], index=i, continues=source.get('continue', False), state='waiting',
+ chosen=None, chosen_by=None, choices={}, takes=[], pending=[], generation=-1, next_take=1,
+ default_takes=source.get('takes', state['takes_per_shot']), base_seed=source.get('seed', base))
+ state['shots'].append(shot)
+ _schedule(state, shot, shot['default_takes'], request['director'])
+ _launch_ready(state, now)
+ _refresh(state)
+ return state
+
+
+def _observe(row, child):
+ if row['state'] in TERMINAL or child is None:
+ return
+ status = child.get('status')
+ if status not in ACTIVE + TERMINAL:
+ return
+ row['state'] = status
+ if status in TERMINAL:
+ # Whitelist result data: no filesystem path can leak from a job result.
+ result = child.get('result') or {}
+ library = result.get('library_id')
+ row['library_id'] = library if isinstance(library, str) and spec.LIBRARY_ID.fullmatch(library) else None
+ seconds = result.get('seconds')
+ row['seconds'] = seconds if type(seconds) in (int, float) and math.isfinite(seconds) and seconds >= 0 else None
+ row['error'] = deepcopy(child.get('error'))
+
+
+def advance(state, children, *, now):
+ """Observe children, update the receipt, and return replayable executor actions."""
+ draft = deepcopy(state)
+ for shot in draft['shots']:
+ for take in shot['takes']:
+ for stopped in take.get('stopped', []):
+ _observe(stopped, children.get(stopped['job']))
+ if take.get('stopped') and take['job'] == take['stopped'][-1]['job']:
+ stopped = take['stopped'][-1]
+ # A success can win the cancellation race; other outcomes of a
+ # stopped attempt never turn the take into a failed generation.
+ if stopped['state'] == 'succeeded':
+ for key in ('state', 'library_id', 'seconds', 'error'):
+ take[key] = deepcopy(stopped[key])
+ else:
+ _observe(take, children.get(take['job']))
+ for join in draft['joins']:
+ previous = join['state']
+ _observe(join, children.get(join['ref']))
+ if previous != 'succeeded' and join['state'] == 'succeeded':
+ draft['outputs'].append(dict(revision=join['revision'], job=join['ref'],
+ library_id=join['library_id'], seconds=join['seconds']))
+ _decision(draft, now, join['by'], 'finished')
+ _refresh(draft)
+ _launch_ready(draft, now, automatic=True)
+ _commit(state, draft, now)
+ actions = []
+ for shot in state['shots']:
+ for take in shot['takes']:
+ for stopped in take.get('stopped', []):
+ if stopped['state'] in ACTIVE:
+ actions.append({'cancel': stopped['job']})
+ if take['state'] in TERMINAL + ('paused',):
+ continue
+ if take['cancel_requested'] or state.get('paused'):
+ actions.append({'cancel': take['job']})
+ elif take['job'] not in children:
+ actions.append({'submit': deepcopy(take['spec'])})
+ for join in state['joins']:
+ if join['state'] not in ACTIVE:
+ continue
+ if join.get('cancel_requested'):
+ actions.append({'cancel': join['ref']})
+ elif not state.get('paused') and join['ref'] not in children:
+ actions.append({'join': {key: deepcopy(join[key]) for key in ('ref', 'takes', 'transition')}})
+ return actions
+
+
+def pause(state, *, by, now):
+ """Suspend unfinished takes, retaining their old refs for cancellation replay."""
+ _pause_guard(state, by)
+ if state.get('paused'):
+ return
+ draft = deepcopy(state)
+ draft['paused'] = dict(at=now, by=by)
+ for shot in draft['shots']:
+ for take in shot['takes']:
+ if (take['state'] in ('waiting', 'queued', 'running') and
+ not take['stale'] and not take['cancel_requested']):
+ # Keep executor outcomes separate from the logical take. The
+ # take's cancel_requested remains reserved for other causes.
+ stopped = {key: deepcopy(take[key]) for key in ('job', 'state', 'library_id', 'seconds', 'error')}
+ take.setdefault('stopped', []).append(stopped)
+ take['state'] = 'paused'
+ _decision(draft, now, by, 'paused')
+ _commit(state, draft, now)
+
+
+def resume(state, *, by, now):
+ """Retry only stop-suspended takes, without consuming a take or generation."""
+ _pause_guard(state, by)
+ if not state.get('paused'):
+ return
+ draft = deepcopy(state)
+ draft['paused'] = None
+ _refresh(draft)
+ for shot in draft['shots']:
+ for take in shot['takes']:
+ if take['state'] != 'paused' or take['stale'] or take['cancel_requested']:
+ continue
+ ref = '%s:s%d:g%d:t%d:a%d' % (draft['id'], shot['index'], take['generation'],
+ take['take'], len(take['stopped']) + 1)
+ take.update(job=ref, state='queued', library_id=None, seconds=None, error=None)
+ take['spec']['ref'] = ref
+ _decision(draft, now, by, 'resumed')
+ _launch_ready(draft, now)
+ _commit(state, draft, now)
+
+
+def choose(state, shot, take, *, by, reason=None, cascade=True, now):
+ """Choose a current take, optionally reconnecting descendants automatically."""
+ _editable(state, by)
+ _optional_text(reason, '/reason')
+ draft = deepcopy(state)
+ row = _shot(draft, shot)
+ if row['chosen'] != take:
+ _guard(row, by)
+ version = _take(row, take)
+ if version['state'] != 'succeeded' or version['stale']:
+ raise ProductionError('take_not_ready', 'The take is stale or has not succeeded.',
+ details=dict(shot=shot, take=take, state=version['state'], stale=version['stale'],
+ why='stale' if version['stale'] else 'not_succeeded'))
+ if row['chosen'] == take:
+ if by == 'user' and row['chosen_by'] != 'user':
+ row['chosen_by'] = by
+ _decision(draft, now, by, 'chosen', shot, take, reason)
+ _commit(state, draft, now)
+ return
+ row['chosen'], row['chosen_by'] = take, by
+ _refresh(draft)
+ if by != 'user':
+ affected = [dict(shot=old['id']) for old, child in zip(state['shots'], draft['shots'])
+ if old['chosen_by'] == 'user' and _chosen(old) and
+ _take(child, old['chosen'])['stale']]
+ if affected:
+ raise ProductionError('chosen_by_user', 'This change would invalidate a shot chosen by the user.',
+ details={'shots': affected})
+ draft['cancelled'], draft['current_join'] = False, None
+ _decision(draft, now, by, 'chosen', shot, take, reason)
+ _reconnect_after(draft, row, by, now, cascade)
+ _launch_ready(draft, now)
+ _commit(state, draft, now)
+
+
+def reshoot(state, shot, *, by, note=None, changes=None, takes=1, reason=None, now):
+ """Reserve a fresh generation; keep all previous non-stale takes selectable."""
+ _editable(state, by)
+ draft = deepcopy(state)
+ row = _shot(draft, shot)
+ _guard(row, by)
+ problems = []
+ _count(takes, '/takes', problems)
+ if changes is not None and not isinstance(changes, dict):
+ problems.append(dict(path='/changes', message='must be an object'))
+ elif changes:
+ for key in changes:
+ if key not in CHANGES:
+ problems.append(dict(path='/changes/' + str(key), message='is not an allowed shot change'))
+ _invalid(problems)
+ _optional_text(note, '/note')
+ _optional_text(reason, '/reason')
+ source = draft['screenplay']['shots'][row['index'] - 1]
+ source.update(deepcopy(changes or {}))
+ # Recheck the complete effective screenplay, transactionally.
+ plan(dict(screenplay=draft['screenplay'], takes_per_shot=draft['takes_per_shot'], director=draft['director']))
+ _schedule(draft, row, takes, by, note)
+ draft['cancelled'], draft['current_join'] = False, None
+ _decision(draft, now, by, 'reshoot', shot, reason=reason)
+ _launch_ready(draft, now)
+ _commit(state, draft, now)
+
+
+def _missing(state):
+ result = []
+ for shot in state['shots']:
+ if _chosen(shot):
+ continue
+ chosen = next((t for t in shot['takes'] if t['take'] == shot['chosen']), None)
+ why = 'stale' if chosen and chosen['stale'] else 'not_succeeded' if chosen else shot['state']
+ result.append(dict(shot=shot['id'], why=why))
+ return result
+
+
+def finish(state, *, by, transition=None, now):
+ """Snapshot the chosen refs for a new join, retaining every previous output."""
+ _editable(state, by)
+ missing = _missing(state)
+ if missing:
+ raise ProductionError('not_ready', 'Every shot needs a succeeded, non-stale chosen take.',
+ details={'shots': missing})
+ transition = transition if transition is not None else state['screenplay'].get('transition', 'cut')
+ if transition not in ('cut', 'crossfade'):
+ _invalid([dict(path='/transition', message='must be "cut" or "crossfade"')])
+ refs = [_chosen(shot)['job'] for shot in state['shots']]
+ current = next((j for j in state['joins'] if j['ref'] == state['current_join']), None)
+ if current and current['state'] in ACTIVE and current['takes'] == refs and current['transition'] == transition:
+ return
+ draft = deepcopy(state)
+ ref = '%s:join%d' % (state['id'], len(state['joins']) + 1)
+ draft['joins'].append(dict(ref=ref, takes=refs, transition=transition, state='waiting', by=by,
+ revision=state['revision'] + 1, library_id=None, seconds=None, error=None))
+ draft['current_join'], draft['cancelled'] = ref, False
+ _commit(state, draft, now)
+
+
+def cancel(state, *, by, now):
+ """Stop unstarted generations and request cancellation of unfinished takes and joins."""
+ _actor(by)
+ draft = deepcopy(state)
+ found = bool(draft.get('paused'))
+ for shot in draft['shots']:
+ if shot['pending']:
+ found = True
+ shot['pending'] = []
+ for take in shot['takes']:
+ if take['state'] == 'paused':
+ take['state'] = 'cancelled'
+ take['cancel_requested'] = True
+ found = True
+ if take['state'] in ACTIVE and not take['cancel_requested']:
+ take['cancel_requested'] = True
+ found = True
+ for join in draft['joins']:
+ # The final join stops too; advance cancels it (or tombstones it before it starts).
+ if join['state'] in ACTIVE and not join.get('cancel_requested'):
+ join['cancel_requested'] = True
+ found = True
+ if not found:
+ raise ProductionError('nothing_to_cancel', 'There are no unfinished takes or joins to cancel.')
+ draft['cancelled'] = True
+ draft['paused'] = None
+ draft['current_join'] = None
+ _decision(draft, now, by, 'cancelled')
+ _commit(state, draft, now)
+
+
+def _todo(state):
+ if state.get('paused'):
+ return [dict(action='wait', why='The user stopped this film. Wait until the user continues.')]
+ if state['status'] in ('finished', 'joining'):
+ return [] if state['status'] == 'finished' else [dict(action='wait', why='The final video is joining.')]
+ if all(_chosen(s) for s in state['shots']):
+ return [dict(action='finish', why='Every shot has a chosen take.')]
+ result = []
+ for shot in state['shots']:
+ if _chosen(shot):
+ continue
+ usable = [t for t in shot['takes'] if not t['stale']]
+ if any(t['state'] == 'succeeded' for t in usable):
+ action, why = 'choose', 'Choose a succeeded, non-stale take.'
+ elif not _usable(shot) and not shot['pending'] and any(t['stale'] for t in shot['takes']):
+ action, why = 'reshoot', 'The preceding shot changed; this shot no longer connects.'
+ elif shot['state'] == 'failed':
+ action, why = 'reshoot', 'No selectable take succeeded.'
+ else:
+ action = 'wait'
+ why = 'Waiting for the preceding shot to be chosen.' if shot['state'] == 'waiting' else 'Takes are shooting.'
+ result.append(dict(action=action, shot=shot['id'], why=why))
+ return result
+
+
+def _public(value):
+ """Remove local paths even in free-form notes and screenplay media fields."""
+ if isinstance(value, dict):
+ return {_public(k): _public(v) for k, v in value.items()}
+ if isinstance(value, list):
+ return [_public(v) for v in value]
+ if isinstance(value, str):
+ from ..diagnostics import ABSOLUTE_PATH
+ # Keep prose slashes, URLs and bare roots. Once a path starts, use
+ # the shared matcher, which includes spaces through the full filename.
+ starts = re.compile(r'''(?<!\w)(?:[A-Za-z]:[\\/](?=[^\s"'<>|])|\\\\[^\\/\s"'<>]+[\\/])'''
+ r'''|(?<![^\W_])(?<![:/])/(?![/\s])[^/"'<>;|\r\n]+/(?![/\s])''')
+ parts, cursor = [], 0
+ for start in starts.finditer(value):
+ if start.start() < cursor:
+ continue
+ found = ABSOLUTE_PATH.match(value[start.start():])
+ if found is None:
+ continue
+ span = found.group().split(' | ', 1)[0].rstrip()
+ parts.extend((value[cursor:start.start()], '[local path]'))
+ cursor = start.start() + len(span)
+ return ''.join(parts) + value[cursor:]
+ return value
+
+
+def view(state):
+ """Return the path-free public board; internal job templates stay private."""
+ result = {key: deepcopy(state[key]) for key in ('id', 'title', 'revision', 'status', 'director', 'created_at',
+ 'updated_at', 'screenplay', 'decisions', 'outputs')}
+ result['paused'] = deepcopy(state.get('paused'))
+ public_states = {'waiting': 'queued', 'cancelling': 'running', 'interrupted': 'failed'}
+ current = next((j for j in state['joins'] if j['ref'] == state['current_join']), None)
+ result['join'] = (dict(state=public_states.get(current['state'], current['state']),
+ error=deepcopy(current['error'])) if current else None)
+ result['shots'] = []
+ for shot in state['shots']:
+ row = {key: deepcopy(shot[key]) for key in ('id', 'index', 'continues', 'state', 'chosen', 'chosen_by')}
+ # The cast of the latest submitted take: cards are read when a take is submitted.
+ latest = next((t for t in reversed(shot['takes']) if 'cast_reference' in t), {})
+ row.update(cast_reference=latest.get('cast_reference'), cast_omitted=deepcopy(latest.get('cast_omitted', [])),
+ cast_voice_omitted=deepcopy(latest.get('cast_voice_omitted', [])),
+ cast_missing=deepcopy(latest.get('cast_missing', [])))
+ row['takes'] = []
+ for take in shot['takes']:
+ item = {key: deepcopy(take[key]) for key in ('take', 'job', 'generation', 'seed', 'state', 'stale',
+ 'continues_take', 'note', 'by', 'library_id', 'seconds')}
+ item['state'] = public_states.get(item['state'], item['state'])
+ item['cast'] = deepcopy(take.get('cast'))
+ row['takes'].append(item)
+ result['shots'].append(row)
+ result['todo'] = _todo(state)
+ return _public(result)
diff --git a/freevideo_engine/agent/productions.py b/freevideo_engine/agent/productions.py
new file mode 100644
index 0000000..92af651
--- /dev/null
+++ b/freevideo_engine/agent/productions.py
@@ -0,0 +1,953 @@
+"""Durable execution of the pure production machine, sharing Jobs' queue and lock.
+
+State, operation replies, rejected submissions and cancellation tombstones share
+one atomic receipt. Persist intent before dispatch; Jobs persists parent.ref in
+its own submission transaction, so a crash between the two writes cannot repeat
+an accepted child. No director loop or model calls are started here.
+"""
+import asyncio
+from copy import deepcopy
+from datetime import datetime
+import hashlib
+import json
+import logging
+import math
+import os
+from pathlib import Path
+import re
+from statistics import median
+import tempfile
+import threading
+import time
+import uuid
+
+from . import drama, production, schema, spec, errors, operation_receipts
+from .jobs import DONE, JobError, iso
+from .forecast import generation_estimate
+
+MAX_GENERATION = 4 # Generations are zero-based: original 0, reshoots 1 through 4.
+MAX_CHILDREN = 60 # Includes assembly, rejected submissions and resumed attempts.
+MAX_WAITERS = 32 # Long GET waits served at once; more callers receive the current state.
+MAX_WAIT = 25
+REQUEST_ID = re.compile(r'r-[0-9a-f]{32}')
+_NAME = re.compile(r'[A-Za-z0-9_-]{1,64}')
+_POINTER = re.compile(r'(?:/(?:[A-Za-z0-9_-]{1,64}|\?))*|/')
+_GOT = re.compile(r'missing|None|True|False|-?\d{1,20}(?:\.\d{1,20})?(?:e[+-]?\d{1,3})?|<string length \d{1,9}>|<[A-Za-z_]{1,32}>')
+_ROW_KEYS = frozenset(('path', 'field', 'allowed', 'got', 'message', 'next'))
+
+
+def _quoted(title):
+ return '"%s"' % title if title else 'the film'
+
+
+def _detail(value):
+ """Domain details carry identifiers only; anything else is not repeated."""
+ if value is None or type(value) in (bool, int):
+ return value
+ return value if isinstance(value, str) and _NAME.fullmatch(value) else '?'
+
+
+def _rows(error):
+ """Shared diagnostics for a domain error: validator-made rows stay, other problems are rebuilt."""
+ if not error.problems:
+ return [{k: _detail(v) for k, v in error.details.items()}] if error.details else []
+ rows = []
+ for row in error.problems:
+ if row.get('_safe'):
+ rows.append({k: deepcopy(v) for k, v in row.items() if k != '_safe'})
+ else:
+ # Character names are caller-chosen keys: a pointer may name the place, never the key.
+ path = re.sub(r'(?<=/characters/)[^/]*', '?', row['path']) if isinstance(row.get('path'), str) else row.get('path')
+ rows.append({k: v for k, v in schema.problem_diagnostic(
+ path, production._public(row.get('message'))).items() if k != '_safe'})
+ return rows
+
+
+class MaterialRejected(JobError):
+ """External callers named material the content-only boundary does not admit: the job validation error."""
+ status = 422
+
+ def __init__(self, rows):
+ super().__init__('invalid_request', 'The material is not accepted here.')
+ self.rows = rows
+
+ def view(self):
+ return errors.validation(self.rows)
+
+
+# A paused film keeps its own wording; the shared code's text speaks of work sessions.
+FILM_STOPPED_NEXT = 'Wait for the user to continue the film; do not retry or start a new one.'
+
+
+class ProductionFailure(JobError):
+ def __init__(self, error):
+ super().__init__(error.code, error.message)
+ self.status = errors.PRODUCTION_STATUS.get(error.code, errors.ERRORS[error.code][0])
+ message = production._public(error.message) if isinstance(error.message, str) else ''
+ self.error = errors.build(error.code, validation=True, message=message[:300],
+ details=_rows(error), next_action=(FILM_STOPPED_NEXT if error.code == 'stopped_by_user' else error.next))
+ if error.code == 'not_ready':
+ self.error['retryable'] = False
+
+ def view(self):
+ return deepcopy(self.error)
+
+
+def _domain(operation, *args, **kwargs):
+ try:
+ return operation(*args, **kwargs)
+ except production.ProductionError as error:
+ raise ProductionFailure(error) from None
+
+
+def _safe_row(row):
+ """The row unchanged when it is exactly what schema.diagnostic would have produced, else None."""
+ if not isinstance(row, dict) or set(row) != _ROW_KEYS or not all(isinstance(row[k], str) for k in _ROW_KEYS):
+ return None
+ path, allowed, got = row['path'], row['allowed'], row['got']
+ if (row['field'] != path or not _POINTER.fullmatch(path) or not _GOT.fullmatch(got)
+ or not 0 < len(allowed) <= 200 or any(c in allowed for c in '/\\\n\r')):
+ return None
+ if row['message'] != '%s must be %s; received %s.' % (path, allowed, got):
+ return None
+ if row['next'] != 'Set %s to %s.' % (path, allowed) and not (
+ row['next'].startswith('Use %s ' % path) and row['next'].endswith('.') and len(row['next']) <= 300
+ and not any(c in row['next'][len(path):] for c in '\\\n\r')):
+ return None
+ return dict(row)
+
+
+def _safe_error(error):
+ """Use the job boundary, never production._public's best-effort path regex.
+
+ Rebuilding legacy/backend errors removes arbitrary strings (including paths
+ with spaces). Only the service's own request id format and exact schema
+ diagnostics survive; everything else is rebuilt from the code table.
+ """
+ if not isinstance(error, dict) or not error:
+ return None
+ code = error.get('code') if isinstance(error.get('code'), str) else None
+ request = error.get('request_id')
+ request = request if isinstance(request, str) and REQUEST_ID.fullmatch(request) else errors.request_id()
+ details = error.get('details')
+ result = errors.build(code, details=details, request=request, action_required=code != 'cancelled')
+ rows = [_safe_row(row) for row in details] if isinstance(details, list) and details else []
+ if rows and all(rows):
+ result.update(details=rows, message='; '.join(row['message'] for row in rows))
+ return result
+
+
+class Productions:
+ def __init__(self, jobs):
+ self.jobs = jobs
+ self.directory = jobs.directory / 'productions'
+ self.records = {}
+ self.changed = threading.Condition(jobs.lock)
+ self._waiters = {}
+ self._waiter_lock = threading.Lock()
+ # gate(action, *, by, estimate_seconds, refs, question) raises when the user must approve first.
+ self.gate = None
+ self.load()
+ jobs.parent_allowed = self.allows
+
+ def load(self):
+ for path in sorted(self.directory.glob('*.json')):
+ try:
+ record = json.loads(path.read_text(encoding='utf-8'))
+ state = record['state']
+ schema.validate(schema.PRODUCTION, state['id'])
+ if path.stem != state['id'] or state['version'] != 1 or type(state['revision']) is not int:
+ raise ValueError('Invalid receipt identity')
+ if not isinstance(record['children'], dict):
+ 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')
+ for ref, child in record['children'].items():
+ schema.validate(schema.REF, ref)
+ if child['status'] not in DONE:
+ raise ValueError('Invalid child receipt')
+ if not isinstance(record.get('submitting', []), list):
+ raise ValueError('Invalid submission marker')
+ production.view(state)
+ try:
+ production.advance(deepcopy(state), deepcopy(record['children']), now=state['updated_at'])
+ except production.ProductionError as error:
+ # A readable record that cannot advance yet is kept, never renamed away.
+ record['stalled'] = self._stalled(error)
+ self.records[state['id']] = record
+ except (ValueError, KeyError, TypeError, AttributeError, IndexError, RecursionError, OSError):
+ path.replace(path.with_name(path.name + '.bad-' + uuid.uuid4().hex))
+ logging.getLogger(__name__).warning('Isolated an invalid production receipt; other films remain available')
+
+ def _stalled(self, error):
+ code = error.code if isinstance(getattr(error, 'code', None), str) and error.code in errors.ERRORS else 'internal_error'
+ return dict(code=code, message=errors.ERRORS[code][2], at=iso(self.jobs.clock()))
+
+ def _save(self, record):
+ self.directory.mkdir(parents=True, exist_ok=True)
+ path = self.directory / (record['state']['id'] + '.json')
+ temporary = path.with_name(path.name + '.' + uuid.uuid4().hex + '.tmp')
+ try:
+ with temporary.open('x', encoding='utf-8') as stream:
+ json.dump(record, stream, ensure_ascii=False, allow_nan=False)
+ stream.flush()
+ os.fsync(stream.fileno())
+ os.replace(temporary, path)
+ finally:
+ temporary.unlink(missing_ok=True)
+ self.records[record['state']['id']] = record
+ self.changed.notify_all()
+ self._wake(record['state']['id'])
+
+ def _wake(self, identity):
+ """Tell asynchronous long-waiters on the event loop that a revision may have changed."""
+ with self._waiter_lock:
+ slots = list(self._waiters.get(identity, ()))
+ for loop, event in slots:
+ try:
+ loop.call_soon_threadsafe(event.set)
+ except RuntimeError: # that loop has already closed
+ pass
+
+ def _record(self, identity):
+ if identity not in self.records:
+ raise JobError('not_found', 'The film does not exist')
+ return self.records[identity]
+
+ def _receipt(self, scope, payload, ref, client=None):
+ if ref is None:
+ return None, None
+ schema.validate(schema.REF, ref)
+ digest = hashlib.sha256(json.dumps(dict(scope=scope, body=payload), sort_keys=True,
+ separators=(',', ':'), allow_nan=False).encode()).hexdigest()
+ for record in self.records.values():
+ for old in record['receipts']:
+ if old['key'] != ref or old.get('client') != client:
+ continue
+ if old['digest'] != digest:
+ raise JobError('idempotency_conflict', 'Key already used')
+ return digest, deepcopy(old['result'])
+ return digest, None
+
+ def _jobs(self, identity):
+ return {row['parent']['ref']: row for row in self.jobs.rows()
+ if row.get('parent', {}).get('production') == identity}
+
+ def _children(self, record):
+ children = deepcopy(record['children'])
+ for ref, row in self._jobs(record['state']['id']).items():
+ # Authoritative jobs override tombstones: a success may win a cancel race.
+ children[ref] = dict(status=row['status'], result=deepcopy(row.get('result')),
+ error=_safe_error(row.get('error')))
+ return children
+
+ def _count(self, record):
+ state = record['state']
+ refs = set(record['children']) | set(self._jobs(state['id']))
+ unreserved = 0
+ for shot in state['shots']:
+ for take in shot['takes'] + [t for group in shot['pending'] for t in group]:
+ if take['job']:
+ refs.add(take['job'])
+ else:
+ unreserved += 1
+ refs.update(row['job'] for row in take.get('stopped', []))
+ refs.update(row['ref'] for row in state['joins'])
+ return len(refs) + unreserved
+
+ def allows(self, parent):
+ """May Jobs still run the child that carries this parent? Registered as Jobs.parent_allowed."""
+ try:
+ identity, ref = parent['production'], parent['ref']
+ except (KeyError, TypeError):
+ return False
+ with self.changed:
+ record = self.records.get(identity)
+ if record is None or ref in record['children']:
+ return False
+ state = record['state']
+ if state['cancelled'] or state['status'] in ('finished', 'cancelled'):
+ return False
+ for shot in state['shots']:
+ for take in shot['takes']:
+ if take['job'] == ref:
+ return (take['state'] in production.ACTIVE and not take['cancel_requested']
+ and not state.get('paused'))
+ # A running join is not suspended by pause; only a current join may start.
+ return any(join['ref'] == ref and join['state'] in production.ACTIVE for join in state['joins'])
+
+ def _material(self, state, *, local=True):
+ """The submission material policy applied to the planned shots before anything runs.
+
+ In-process callers may name local files; external HTTP callers may not."""
+ problems, placeholder = [], 'j000000000000'
+ for shot in state['shots']:
+ takes = shot['takes'] + [t for group in shot['pending'] for t in group]
+ if not takes:
+ continue
+ item = deepcopy(takes[0]['spec'])
+ item.pop('ref', None)
+ continued = bool(item.get('continue_from'))
+ if continued:
+ item['continue_from'] = dict(from_job=placeholder)
+ prefix = '/screenplay/shots/%d' % (shot['index'] - 1)
+ try:
+ normalized = spec.check(item, local=local)
+ except spec.SpecError as error:
+ for row in error.errors:
+ if not row.get('_safe'):
+ problems.append(schema.problem_diagnostic(prefix, 'has unsupported material'))
+ continue
+ old, new = row['path'], prefix + row['path']
+ problems.append(dict(row, path=new, field=prefix + row.get('field', old),
+ message=row['message'].replace(old, new, 1), next=row['next'].replace(old, new, 1)))
+ continue
+ for dependency in normalized['depends_on']:
+ if not (continued and dependency == placeholder) and dependency not in self.jobs.jobs:
+ problems.append(schema.diagnostic(prefix + '/first', 'a job that exists on this server', dependency))
+ if problems and not local:
+ raise MaterialRejected(problems)
+ if problems:
+ _domain(production._invalid, problems)
+
+ def plan(self, request, *, local=True):
+ result = _domain(production.plan, {k: v for k, v in request.items() if k != 'ref'})
+ state = _domain(production.new, 'dplanpreview', result['request'], now=iso(self.jobs.clock()))
+ play = result['request']['screenplay']
+ with self.changed:
+ cards = self._cards(play)
+ self._material(state, local=local)
+ problems = []
+ for i, (row, source, shot) in enumerate(zip(result['preview']['shots'], play['shots'], state['shots'])):
+ # The same resolution a take gets when it is submitted, with the cards as they are now.
+ resolved = drama.cast_references(play, source, cards, continues=shot['continues'])
+ row['prompt'] = drama.with_cast(row['prompt'], resolved)
+ row.update(cast_reference=resolved['cast_reference'], cast=resolved['people'],
+ cast_omitted=resolved['omitted'], cast_voice_omitted=resolved['voice_omitted'],
+ cast_missing=resolved['missing'],
+ references=len(resolved['references']))
+ try:
+ spec._text(row['prompt'], '/screenplay/shots/%d/prompt' % i, 20000)
+ except spec.SpecError as error:
+ problems.extend(error.errors)
+ _domain(production._invalid, problems)
+ preview = dict(state=state, estimates={})
+ with self.changed:
+ self._prepare_estimates(preview)
+ result['estimate'] = dict(seconds=self._progress(preview)['estimate_seconds'])
+ return result
+
+ @staticmethod
+ def _takes(state):
+ for shot in state['shots']:
+ for take in shot['takes'] + [t for group in shot['pending'] for t in group]:
+ yield shot, take
+
+ def _take_estimate(self, state, shot, take, item=None):
+ """Forecast a submission intent, or its final resolved material at dispatch."""
+ try:
+ item = deepcopy(take['spec'] if item is None else item)
+ if shot['continues']:
+ item['continue_from'] = dict(from_job='j000000000000')
+ if item.get('continue_from', {}).get('ref'):
+ item['continue_from'] = dict(from_job='j000000000000')
+ resolved = drama.cast_references(state['screenplay'],
+ state['screenplay']['shots'][shot['index'] - 1], self._current(state['screenplay']),
+ continues=shot['continues'])
+ if resolved['references']:
+ item['media'] = dict(references=deepcopy(resolved['references']))
+ estimate, revision = generation_estimate(self.jobs.port, spec.normalize(item))
+ return dict(estimate, revision=revision)
+ except Exception: # Timing is optional; a forecast failure must not reject a film or job.
+ return dict(seconds=None, basis=None, reason='unavailable')
+
+ def _join_estimate(self, state, previous=None):
+ """Use only successful local joins with the same input geometry and transition."""
+ shapes = []
+ for shot in state['shots']:
+ take = production._chosen(shot) or next((t for s, t in self._takes(state)
+ if s is shot and not t['stale'] and t['state'] != 'cancelled' and not t['cancel_requested']), None)
+ if take is None:
+ return dict(seconds=None, basis=None, reason='no_matching_estimate')
+ item = deepcopy(take['spec'])
+ item.pop('continue_from', None)
+ normalized = spec.normalize(item)
+ shapes.append([normalized[k] for k in ('width', 'height', 'frames')])
+ current = next((j for j in state['joins'] if j['ref'] == state['current_join']), None)
+ transition = current['transition'] if current else state['screenplay'].get('transition', 'cut')
+ signature = dict(shapes=shapes, transition=transition)
+ if previous and previous.get('signature') == signature and previous.get('ref') == state['current_join']:
+ return previous
+ samples = []
+ for row in self.jobs.rows():
+ if row['kind'] != 'assemble' or row['status'] != 'succeeded':
+ continue
+ saved = row['spec']
+ if saved.get('transition', 'cut') != transition or saved.get('width') or saved.get('height'):
+ continue
+ if saved.get('audio', True) is not True or (
+ transition == 'crossfade' and saved.get('transition_seconds', .5) != .5):
+ continue
+ if any(set(clip) != {'from_job'} for clip in saved['clips']):
+ continue
+ inputs = [self.jobs.jobs.get(c.get('from_job'), {}).get('spec', {}) for c in saved['clips']]
+ if [[s.get(k) for k in ('width', 'height', 'frames')] for s in inputs] != shapes:
+ continue
+ start, end = row.get('started_at'), row.get('finished_at')
+ if (type(start) in (int, float) and type(end) in (int, float)
+ and math.isfinite(end - start) and end > start):
+ samples.append(end - start)
+ return dict(signature=signature, ref=state['current_join'], seconds=median(samples) if samples else None,
+ basis='matching_local_joins' if samples else None,
+ **({} if samples else {'reason': 'no_matching_estimate'}))
+
+ def _prepare_estimates(self, record):
+ """Save planned takes before replying; final material is frozen before Jobs.submit."""
+ estimates = record.setdefault('estimates', {})
+ for shot, take in self._takes(record['state']):
+ if take['job'] and take['job'] not in estimates:
+ estimates[take['job']] = self._take_estimate(record['state'], shot, take)
+ # A choice or changed screenplay can change the inputs to the final join.
+ previous = record.get('join_estimate', {})
+ try:
+ record['join_estimate'] = self._join_estimate(record['state'], previous)
+ except Exception: # Optional forecasts cannot make an otherwise valid operation fail.
+ record['join_estimate'] = dict(seconds=None, basis=None, reason='unavailable')
+
+ def _elapsed(self, state):
+ def stamp(value):
+ return datetime.fromisoformat(value.replace('Z', '+00:00')).timestamp()
+ ended = next((d['at'] for d in reversed(state['decisions'])
+ if d['action'] == state['status']), state['updated_at'])
+ end = stamp(ended) if state['status'] in ('finished', 'cancelled') else self.jobs.clock()
+ paused, stopped = None, 0.
+ for decision in state['decisions']:
+ if decision['action'] not in ('paused', 'resumed', 'cancelled'):
+ continue
+ at = min(end, stamp(decision['at']))
+ if decision['action'] == 'paused' and paused is None:
+ paused = at
+ elif decision['action'] in ('resumed', 'cancelled') and paused is not None:
+ stopped += max(0., at - paused)
+ paused = None
+ if paused is not None:
+ stopped += max(0., end - paused)
+ return round(max(0., end - stamp(state['created_at']) - stopped), 3)
+
+ def _progress(self, record):
+ state = record['state']
+ children = self._jobs(state['id'])
+ completed, running, fractions, estimates = 0, [], [], []
+ def fraction(row, status):
+ if status in ('succeeded', 'failed', 'interrupted'):
+ return 1.
+ value = (self.jobs.progress(row) or {}).get('fraction') if row and status == 'running' else None
+ return min(1., max(0., value)) if type(value) in (int, float) and math.isfinite(value) else 0.
+ for shot, take in self._takes(state):
+ child = children.get(take['job'])
+ status = child['status'] if child and take['state'] != 'paused' else take['state']
+ if take['stale'] or status == 'cancelled' or (take['cancel_requested'] and status != 'succeeded'):
+ continue
+ part = fraction(child, status)
+ completed += status in ('succeeded', 'failed', 'interrupted')
+ fractions.append(part)
+ estimates.append(record.get('estimates', {}).get(take['job'], {}).get('seconds'))
+ if status == 'running':
+ running.append(dict(shot=shot['id'], take=take['take'], fraction=part))
+ current = next((j for j in state['joins'] if j['ref'] == state['current_join']), None)
+ child = children.get(state['current_join'])
+ joined = bool(current and (child['status'] if child else current['state']) == 'succeeded')
+ join_fraction = fraction(child, child['status'] if child else current['state']) if current else 0.
+ fractions.append(join_fraction)
+ estimates.append(record.get('join_estimate', {}).get('seconds'))
+ known = all(type(e) in (int, float) and math.isfinite(e) and e > 0 for e in estimates)
+ total = sum(estimates) if known else None
+ overall = sum(e * f for e, f in zip(estimates, fractions)) / total if known else sum(fractions) / len(fractions)
+ remaining = sum(e * (1. - f) for e, f in zip(estimates, fractions)) if known else None
+ if state['status'] == 'finished':
+ overall, remaining = 1., 0. if known else None
+ return dict(takes=dict(completed=completed, total=len(fractions) - 1),
+ shots=dict(completed=sum(production._chosen(s) is not None for s in state['shots']),
+ total=len(state['shots'])), running=running,
+ join=dict(completed=joined, fraction=join_fraction), fraction=overall,
+ elapsed_seconds=self._elapsed(state), estimate_seconds=total, remaining_seconds=remaining)
+
+ @staticmethod
+ def _elapsed_budget(progress):
+ if progress['estimate_seconds'] is not None and progress['elapsed_seconds'] > 1.5 * progress['estimate_seconds']:
+ return dict(reason='elapsed', elapsed_seconds=progress['elapsed_seconds'],
+ estimate_seconds=progress['estimate_seconds'])
+ return None
+
+ def _cards(self, play):
+ """The current cards of a new film; every characters.<key>.card must be in the library. Hold the lock."""
+ cards = self._current(play)
+ rows = [schema.diagnostic('/screenplay/characters/?/card', 'a card ID listed by GET /freevideo/agent/v1/cast',
+ identity) for identity, card in sorted(cards.items()) if card is None]
+ if rows:
+ raise ProductionFailure(production.ProductionError('invalid_screenplay',
+ 'A character names a card that is not in the cast library.', problems=rows, details={'problems': rows}))
+ return cards
+
+ def _preflight(self, before, draft):
+ """Run the next advance on a copy: a failure, or a new generation over the limit, rejects the whole operation."""
+ preview = deepcopy(draft)
+ _domain(production.advance, preview['state'], self._children(preview), now=iso(self.jobs.clock()))
+ for old, new in zip(before['state']['shots'] if before else [], preview['state']['shots']):
+ if self._generations(new) > MAX_GENERATION and self._generations(new) > self._generations(old):
+ raise JobError('reshoot_limit', 'Too many generations')
+ if self._count(preview) > max(MAX_CHILDREN, self._count(before) if before else 0):
+ raise JobError('production_limit', 'Too many child jobs')
+
+ @staticmethod
+ def _generations(shot):
+ # Reconnects waiting for a pause to end already own their next generation.
+ return shot['generation'] + sum(1 for group in shot['pending'] if group and group[0]['job'] is None)
+
+ def start(self, request, *, by='agent', ref=None, local=True, client=None):
+ _domain(production._actor, by)
+ request = deepcopy(request)
+ request.setdefault('director', by if by in ('agent', 'builtin') else 'agent')
+ alias = request.pop('ref', None)
+ if ref and alias and ref != alias:
+ raise JobError('idempotency_conflict', 'Conflicting keys')
+ ref = ref or alias
+ with self.changed:
+ digest, replay = self._receipt('start', dict(request=request, by=by), ref, client)
+ if replay is not None:
+ return replay
+ identity = 'd' + uuid.uuid4().hex[:12]
+ state = _domain(production.new, identity, request, now=iso(self.jobs.clock()))
+ # new() only takes director, not the initiating actor. Attribution
+ # belongs to this boundary, including the future in-process UI.
+ for decision in state['decisions']:
+ decision['by'] = by
+ for shot in state['shots']:
+ for take in shot['takes'] + [t for group in shot['pending'] for t in group]:
+ take['by'] = by
+ record = dict(state=state, receipts=[], children={}, tasks={})
+ if errors.SESSION.get():
+ record['session'] = errors.SESSION.get()
+ if self._count(record) > MAX_CHILDREN:
+ raise JobError('production_limit', 'Too many child jobs')
+ cards = self._cards(state['screenplay'])
+ if not local:
+ self._material(state, local=False)
+ self._preflight(None, record)
+ self._prepare_estimates(record)
+ if self.gate is not None:
+ self.gate('start', by=by, estimate_seconds=self._progress(record)['estimate_seconds'],
+ refs={}, # the film gets its ID only when the approved call repeats
+ question='Start shooting %s (%d shots)?' % (_quoted(state['title']), len(state['shots'])))
+ result = self._view(record)
+ if ref:
+ record['receipts'].append(dict(key=ref, digest=digest, result=result,
+ **({'client': client} if client else {})))
+ self._save(record)
+ if cards:
+ self.jobs.cast.used(sorted(cards), identity)
+ self._run(identity)
+ return deepcopy(result)
+
+ @staticmethod
+ def _context_next(record, join=False):
+ """What a caller should do about a failed child, in the context of this film."""
+ state = record['state']
+ if state.get('paused'):
+ return 'Wait for the user to continue.'
+ if state['cancelled'] or state['status'] in ('finished', 'cancelled'):
+ return None
+ return 'Finish the film again.' if join else 'Reshoot this shot.'
+
+ def _view(self, record):
+ value = production.view(record['state'])
+ tasks = record.get('tasks', {})
+ def contextual(error, join=False):
+ error = deepcopy(error)
+ if error and 'next' in error:
+ action = self._context_next(record, join)
+ if action:
+ error['next'] = action
+ else:
+ del error['next']
+ return error
+ for shot, internal in zip(value['shots'], record['state']['shots']):
+ for take, saved in zip(shot['takes'], internal['takes']):
+ take['error'] = contextual(saved.get('error'))
+ take['task'] = tasks.get(take['job'])
+ if value['join'] is not None:
+ ref = record['state']['current_join']
+ join = next(j for j in record['state']['joins'] if j['ref'] == ref)
+ value['join'].update(ref=ref, task=tasks.get(ref), error=contextual(join['error'], True))
+ value['stalled'] = deepcopy(record.get('stalled'))
+ value['progress'] = self._progress(record)
+ value['over_budget'] = self._elapsed_budget(value['progress'])
+ return value
+
+ def get(self, identity, *, since=None, wait=0, compact=True):
+ schema.validate(schema.drama_schema('get'), dict(wait=wait, **({'since': since} if since is not None else {})))
+ deadline = time.monotonic() + min(wait, MAX_WAIT)
+ with self.changed:
+ while self._record(identity)['state']['revision'] == since:
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ break
+ self.changed.wait(remaining)
+ return self._reply(identity, since, compact)
+
+ def _reply(self, identity, since, compact):
+ record = self._record(identity)
+ changed = record['state']['revision'] != since
+ if not changed and compact:
+ progress = self._progress(record)
+ return dict(id=identity, revision=since, changed=False, status=record['state']['status'],
+ paused=deepcopy(record['state'].get('paused')), fraction=progress['fraction'],
+ elapsed_seconds=progress['elapsed_seconds'])
+ return dict(self._view(record), changed=changed)
+
+ async def get_async(self, identity, *, since=None, wait=0, compact=True):
+ """Long wait on the event loop: no thread is held, and callers over the cap get the current state."""
+ schema.validate(schema.drama_schema('get'), dict(wait=wait, **({'since': since} if since is not None else {})))
+ def read():
+ return asyncio.to_thread(self.get, identity, since=since, wait=0, compact=compact)
+ wait = min(wait, MAX_WAIT)
+ if since is None or wait <= 0:
+ return await read()
+ loop = asyncio.get_running_loop()
+ slot = (loop, asyncio.Event())
+ with self._waiter_lock:
+ if sum(len(row) for row in self._waiters.values()) >= MAX_WAITERS:
+ slot = None
+ else:
+ self._waiters.setdefault(identity, set()).add(slot)
+ if slot is None:
+ return await read()
+ try:
+ deadline = loop.time() + wait
+ while True:
+ slot[1].clear() # A save after this read sets it again.
+ result = await read()
+ left = deadline - loop.time()
+ if result['changed'] or left <= 0:
+ return result
+ try:
+ await asyncio.wait_for(slot[1].wait(), left)
+ except asyncio.TimeoutError:
+ pass
+ finally:
+ with self._waiter_lock:
+ self._waiters.get(identity, set()).discard(slot)
+ if not self._waiters.get(identity, True):
+ del self._waiters[identity]
+
+ def list(self, *, status='all', limit=50):
+ with self.changed:
+ rows = sorted(self.records.values(), key=lambda r: (r['state']['updated_at'], r['state']['id']), reverse=True)
+ if status == 'active':
+ rows = [r for r in rows if r['state']['status'] not in ('finished', 'cancelled')]
+ result = []
+ for record in rows[:limit]:
+ view = self._view(record)
+ shot = next((s for s in view['shots'] if s['chosen'] is None), view['shots'][-1])
+ result.append(dict(id=view['id'], title=view['title'], status=view['status'], revision=view['revision'],
+ shot=shot['index'], shots=len(view['shots']), next=view['todo'][0] if view['todo'] else None,
+ paused=view['paused'], stalled=view['stalled'], session=record.get('session')))
+ return result
+
+ def _mutate(self, action, identity, *, by, ref=None, client=None, **values):
+ with self.changed:
+ record = self._record(identity)
+ if action in ('choose', 'reshoot', 'finish'):
+ _domain(production._editable, record['state'], by)
+ if action in ('pause', 'resume') and by != 'user':
+ _domain(production._pause_guard, record['state'], by)
+ digest, replay = self._receipt(identity + ':' + action, dict(by=by, **values), ref, client)
+ if replay is not None:
+ return replay
+ draft = deepcopy(record)
+ state = draft['state']
+ _domain(getattr(production, action), state, by=by, now=iso(self.jobs.clock()), **values)
+ # The next advance is part of this operation: if it cannot run, nothing changes.
+ self._preflight(record, draft)
+ self._prepare_estimates(draft)
+ result = self._view(draft)
+ if action == 'reshoot':
+ previous = {t['job'] for _, t in self._takes(record['state'])}
+ estimates = [draft['estimates'].get(t['job'], {}).get('seconds')
+ for s, t in self._takes(state) if s['id'] == values['shot'] and t['job'] not in previous]
+ known = bool(estimates) and all(e is not None for e in estimates)
+ if known and sum(estimates) >= 600:
+ result['over_budget'] = dict(reason='reshoot', shot=values['shot'], estimate_seconds=sum(estimates))
+ if self.gate is not None:
+ shot = next(s for s in state['shots'] if s['id'] == values['shot'])
+ self.gate('reshoot', by=by, estimate_seconds=sum(estimates) if known else None,
+ refs=dict(drama=identity, shot=shot['id']),
+ question='Reshoot shot %d of %s?' % (shot['index'], _quoted(state['title'])))
+ if ref:
+ draft['receipts'].append(dict(key=ref, digest=digest, result=result,
+ **({'client': client} if client else {})))
+ self._save(draft)
+ self._run(identity)
+ return deepcopy(result)
+
+ def choose(self, identity, shot, take, *, by='agent', ref=None, **kwargs):
+ return self._mutate('choose', identity, shot=shot, take=take, by=by, ref=ref, **kwargs)
+
+ def reshoot(self, identity, shot, *, by='agent', ref=None, **kwargs):
+ return self._mutate('reshoot', identity, shot=shot, by=by, ref=ref, **kwargs)
+
+ def finish(self, identity, *, by='agent', ref=None, **kwargs):
+ return self._mutate('finish', identity, by=by, ref=ref, **kwargs)
+
+ def cancel(self, identity, *, by='agent', ref=None, client=None):
+ return self._mutate('cancel', identity, by=by, ref=ref, client=client)
+
+ def pause(self, identity, *, by, ref=None, client=None):
+ return self._mutate('pause', identity, by=by, ref=ref, client=client)
+
+ def resume(self, identity, *, by, ref=None, client=None):
+ return self._mutate('resume', identity, by=by, ref=ref, client=client)
+
+ def pause_session(self, session):
+ paused = []
+ with self.changed:
+ for identity, record in list(self.records.items()):
+ state = record['state']
+ if (record.get('session') == session and not state.get('paused') and not state['cancelled']
+ and state['status'] not in ('finished', 'cancelled')):
+ try:
+ self.pause(identity, by='user')
+ paused.append(identity)
+ except JobError:
+ pass
+ return paused
+
+ def tick(self):
+ with self.changed:
+ for identity in list(self.records):
+ self._run(identity)
+
+ def _bump(self, draft):
+ draft['state']['revision'] += 1
+ draft['state']['updated_at'] = iso(self.jobs.clock())
+
+ def _run(self, identity):
+ """Advance one film; a failure stalls only that film and is retried on the next tick."""
+ try:
+ self._advance(identity)
+ except Exception as error: # noqa: BLE001 - one film must never stop the others
+ logging.getLogger(__name__).warning('A film could not advance (%s); other films continue',
+ type(error).__name__)
+ stalled = self._stalled(error)
+ record = self._record(identity)
+ if (record.get('stalled') or {}).get('code') != stalled['code']:
+ draft = deepcopy(record)
+ draft['stalled'] = stalled
+ self._bump(draft)
+ self._save(draft)
+ else:
+ record = self._record(identity)
+ if record.get('stalled'):
+ draft = deepcopy(record)
+ del draft['stalled']
+ self._bump(draft)
+ self._save(draft)
+
+ def _interrupted(self, identity):
+ """A submission marked before a restart whose child Jobs never recorded: accepted or not is unknown."""
+ record = self._record(identity)
+ children = self._jobs(identity)
+ lost = [r for r in record.get('submitting', []) if r not in children and r not in record['children']]
+ if not lost:
+ return
+ draft = deepcopy(record)
+ for ref in lost:
+ draft['children'][ref] = dict(status='failed', result=None, error=errors.build('submit_interrupted'))
+ marked = [r for r in draft['submitting'] if r not in lost]
+ if marked:
+ draft['submitting'] = marked
+ else:
+ draft.pop('submitting', None)
+ self._save(draft)
+
+ def _advance(self, identity):
+ self._interrupted(identity)
+ record = self._record(identity)
+ draft = deepcopy(record)
+ actions = production.advance(draft['state'], self._children(record), now=iso(self.jobs.clock()))
+ self._prepare_estimates(draft)
+ if draft != record:
+ self._save(draft)
+ # Terminal films may still have unacknowledged cancels or older joins.
+ for action in actions:
+ self._execute(identity, action)
+ record = self._record(identity)
+ draft = deepcopy(record)
+ tasks = {ref: row['id'] for ref, row in self._jobs(identity).items()}
+ if tasks != record.get('tasks', {}):
+ draft['tasks'] = tasks
+ # Task links are an executor-owned part of the public board, so
+ # they also wake since/revision readers even before jobs run.
+ self._bump(draft)
+ # A submission marker is only needed until the child or its rejection receipt exists.
+ marked = [r for r in record.get('submitting', []) if r not in tasks and r not in record['children']]
+ if marked != record.get('submitting', []):
+ if marked:
+ draft['submitting'] = marked
+ else:
+ draft.pop('submitting', None)
+ over_budget = self._elapsed_budget(self._progress(draft)) is not None
+ if over_budget != record.get('elapsed_over_budget', False):
+ draft['elapsed_over_budget'] = over_budget
+ self._bump(draft) # Wake since/wait readers when the elapsed reminder appears or clears.
+ if draft != record:
+ self._save(draft)
+
+ def _execute(self, identity, action):
+ """Carry out one action; True when it changed a child, a receipt or a tombstone."""
+ record = self._record(identity)
+ children = self._jobs(identity)
+ if 'cancel' in action:
+ ref = action['cancel']
+ changed = False
+ if ref not in record['children']:
+ draft = deepcopy(record)
+ draft['children'][ref] = dict(status='cancelled', result=None, error=None)
+ self._save(draft) # tombstone before calling Jobs, even with no child
+ changed = True
+ child = children.get(ref)
+ if child and child['status'] not in DONE:
+ before = child['status']
+ self.jobs.cancel(child['id'])
+ changed = changed or child['status'] != before
+ return changed
+ item = deepcopy(action.get('submit') or action['join'])
+ ref = item.pop('ref')
+ if ref in children or ref in record['children']:
+ return False
+ if ref in record.get('submitting', ()):
+ # Marked in an earlier run, but Jobs has no such child: whether it was accepted is unknown.
+ failure = errors.build('submit_interrupted')
+ else:
+ try:
+ if len(set(children) | set(record['children'])) >= MAX_CHILDREN:
+ raise JobError('production_limit', 'Too many child jobs')
+ if 'join' in action:
+ item = dict(kind='assemble', clips=[children[r]['id'] for r in item['takes']],
+ transition=item['transition'])
+ else:
+ take = next(t for s in record['state']['shots'] for t in s['takes'] if t['job'] == ref)
+ if take['generation'] > MAX_GENERATION:
+ raise JobError('reshoot_limit', 'Too many generations')
+ if item.get('continue_from'):
+ source = children[item['continue_from']['ref']]
+ item['continue_from'] = dict(from_job=source['id'])
+ resolved = self._cast(record['state'], take, item)
+ spec.check(item, local=True) # The same policy as Jobs.submit for in-process callers.
+ marker = deepcopy(self._record(identity))
+ marker['submitting'] = list(marker.get('submitting', [])) + [ref]
+ if 'submit' in action:
+ shot = next(s for s in marker['state']['shots'] if any(t['job'] == ref for t in s['takes']))
+ marker.setdefault('estimates', {})[ref] = self._take_estimate(marker['state'], shot, take, item)
+ else:
+ try:
+ marker['join_estimate'] = self._join_estimate(marker['state'])
+ except Exception:
+ marker['join_estimate'] = dict(seconds=None, basis=None, reason='unavailable')
+ if 'submit' in action and resolved['cast_reference'] is not None:
+ # The board shows which revision of each card this take used.
+ saved = next(t for s in marker['state']['shots'] for t in s['takes'] if t['job'] == ref)
+ saved.update(cast=dict(resolved['cards']), cast_reference=resolved['cast_reference'],
+ cast_omitted=list(resolved['omitted']),
+ cast_voice_omitted=list(resolved['voice_omitted']),
+ cast_missing=list(resolved['missing']))
+ self._save(marker) # Durable before Jobs may accept it.
+ self.jobs.submit(item, client='production:' + identity, parent=dict(production=identity, ref=ref))
+ except spec.SpecError as error:
+ failure = errors.validation(error.errors)
+ except JobError as error:
+ failure = error.view()
+ else:
+ return True
+ draft = deepcopy(self._record(identity))
+ draft['children'][ref] = dict(status='failed', result=None, error=failure)
+ marked = [r for r in draft.get('submitting', []) if r != ref]
+ if marked:
+ draft['submitting'] = marked
+ else:
+ draft.pop('submitting', None)
+ self._save(draft)
+ return True
+
+ def _cast(self, state, take, item):
+ """Read the cast cards now, at submission: later takes and reshoots use the cards as they are then."""
+ play = state['screenplay']
+ shot = next(s for s in state['shots'] if any(t['job'] == take['job'] for t in s['takes']))
+ resolved = drama.cast_references(play, play['shots'][shot['index'] - 1], self._current(play),
+ continues=shot['continues'])
+ if resolved['cast_reference'] is None:
+ return resolved
+ if resolved['references']:
+ item['media'] = dict(references=deepcopy(resolved['references']))
+ item['prompt'] = drama.with_cast(item['prompt'], resolved)
+ item['metadata'] = dict(item.get('metadata') or {}, cast=dict(resolved['cards']),
+ cast_reference=resolved['cast_reference'])
+ return resolved
+
+ def _current(self, play):
+ """Cards as they are now; a card deleted since the film started is None (the shot uses text)."""
+ cast = getattr(self.jobs, 'cast', None)
+ identities = {p['card'] for p in (play.get('characters') or {}).values()
+ if isinstance(p, dict) and isinstance(p.get('card'), str)}
+ return {i: cast.snapshot(i) if cast is not None else None for i in identities}
+
+ def sheet(self, identity, shot, *, frames=6):
+ """Return bytes in process; HTTP converts these to inline image content."""
+ from . import media
+ schema.validate(schema.drama_schema('sheet'), dict(frames=frames))
+ with self.changed:
+ record = self._record(identity)
+ row = _domain(production._shot, record['state'], shot)
+ takes = [(t['take'], t['library_id']) for t in row['takes']
+ if t['state'] == 'succeeded' and not t['stale']]
+ parent = production._parent(record['state'], row)
+ previous = parent['library_id'] if parent else None
+ result = dict(takes=[], previous=None)
+ self.directory.mkdir(parents=True, exist_ok=True)
+ with self.jobs.cpu, tempfile.TemporaryDirectory(dir=self.directory) as folder:
+ for number, library in takes:
+ if not library:
+ raise JobError('no_video', 'Take has no saved video')
+ output = Path(folder) / ('take-%d.jpg' % number) # media never overwrites a finished file
+ media.contact_sheet(self.jobs.port.library_video(library), output, count=frames, columns=min(4, frames))
+ result['takes'].append(dict(take=number, image=output.read_bytes()))
+ if previous:
+ output = Path(folder) / 'previous.png'
+ self.jobs.port.extract_frame(self.jobs.port.library_video(previous), output, 'last')
+ result['previous'] = output.read_bytes()
+ return result
+
+ def adapter(self):
+ return DirectorAdapter(self)
+
+
+class DirectorAdapter:
+ """Synchronous in-process operations for builtin_director.run.
+
+ Unlike compact HTTP timeouts, the director needs a complete board on every
+ get. Both representations share the same wait and durable operations.
+ """
+ def __init__(self, productions):
+ self.productions = productions
+
+ def get(self, identity, *, since=None, wait=0):
+ return self.productions.get(identity, since=since, wait=wait, compact=False)
+
+ def __getattr__(self, name):
+ if name in ('plan', 'start', 'sheet', 'choose', 'reshoot', 'finish', 'cancel', 'pause', 'resume'):
+ return getattr(self.productions, name)
+ raise AttributeError(name)
diff --git a/freevideo_engine/agent/projects.py b/freevideo_engine/agent/projects.py
new file mode 100644
index 0000000..11d17f1
--- /dev/null
+++ b/freevideo_engine/agent/projects.py
@@ -0,0 +1,399 @@
+"""Editing projects for agents: the page's timeline, read and changed through the API.
+
+A project is the editor page's own record (web/editor_model.js). Operations run
+the page's rule code in QuickJS (editor_runtime), so the Agent and the page cut,
+move and make room the same way; the result is saved with the page's save, whose
+revision check makes the later of two writers receive project_changed.
+"""
+from __future__ import annotations
+
+from copy import deepcopy
+import hashlib
+import json
+import logging
+import secrets
+import threading
+import time
+
+from .. import comfy_editor
+from . import editor_runtime, errors, schema, spec
+from .jobs import JobError, library_id, library_view
+
+MAX_OPERATIONS = 64
+MAX_RECEIPTS = 256
+# Rule codes that describe the timeline's state; the rest are request errors.
+STATE_CODES = {'busy': 'clip_busy', 'locked': 'clip_locked', 'audio_full': 'audio_full', 'overlap': 'overlap'}
+# What a rejected operation needed, by the page's rule code.
+RULE_EXPECTED = {
+ 'range': 'clip_ids that exist and a frame inside them (frames are whole numbers at 24 fps)',
+ 'missing': 'clip_ids from this project revision',
+ 'text': 'a short description of at most one paragraph',
+ 'ref': 'a ref of 1-128 letters, digits, - or _, or an empty string to remove it',
+ 'source': 'a source that has a picture or sound',
+ 'invalid': 'an op named in the operations schema with its fields',
+}
+
+
+class ProjectError(JobError):
+ """A project error; a conflict carries the current project so the caller can retry from it."""
+
+ def __init__(self, code, message=None, *, project=None, operation=None):
+ super().__init__(code, message or errors.ERRORS[code][2])
+ self.status = errors.ERRORS[code][0]
+ self.project, self.operation = project, operation
+
+ def view(self):
+ value = errors.build(self.code, validation=True, details=[], message=self.message,
+ next_action=errors.ERRORS[self.code][3])
+ if self.operation is not None:
+ value['details'].append(dict(operation=self.operation))
+ if self.project is not None:
+ value['project'] = deepcopy(self.project)
+ value['current_revision'] = self.project['revision']
+ return value
+
+
+def _invalid(path, expected, received=None):
+ return spec.SpecError([schema.diagnostic(path, expected, received)])
+
+
+def _digest(scope, payload):
+ return hashlib.sha256(json.dumps(dict(scope=scope, body=payload), sort_keys=True, separators=(',', ':'),
+ ensure_ascii=True, allow_nan=False).encode()).hexdigest()
+
+
+def _operation_key(ref, client=None):
+ """The page save's 32-hex operation id for an agent ref, so a lost reply can be replayed."""
+ key = 'agent:' + ref if client is None else 'agent-client:' + json.dumps(
+ [client, ref], ensure_ascii=True, separators=(',', ':'))
+ return hashlib.sha256(key.encode()).hexdigest()[:32]
+
+
+def _clips(project):
+ return {clip['id']: clip for track in project['tracks'] for clip in track['clips']}
+
+
+def changed_clip_ids(before, after):
+ """Ids of parts added, removed or changed by an edit, in timeline order of the result, then removed ones."""
+ old, new = _clips(before), _clips(after)
+ changed = [identity for identity, clip in new.items() if old.get(identity) != clip]
+ return changed + [identity for identity in old if identity not in new]
+
+
+class Projects:
+ def __init__(self, root, *, directory=None):
+ self.root = root # The ComfyUI output folder, where the page keeps FreeVideo/.editor
+ self.lock = threading.Lock()
+ self.receipts = {} # (client, ref) -> {digest, result}; in memory, bounded; the page save keeps the durable one.
+ self.prepared = {} # job id -> the reserved project, until its chain id is written into it.
+
+ def _load(self, identity):
+ try:
+ return comfy_editor.load(self.root, identity)
+ except (FileNotFoundError, ValueError) as error:
+ raise ProjectError('not_found', 'The project does not exist.') from error
+
+ def _receipt(self, scope, payload, ref, client=None):
+ if ref is None:
+ return None, None
+ digest = _digest(scope, payload)
+ with self.lock:
+ old = self.receipts.get((client, ref))
+ if old is not None:
+ if old['digest'] != digest:
+ raise JobError('idempotency_conflict', 'Key already used')
+ return digest, deepcopy(old['result'])
+ return digest, None
+
+ def _remember(self, ref, digest, result, client=None):
+ if ref is None:
+ return
+ with self.lock:
+ self.receipts[client, ref] = dict(digest=digest, result=deepcopy(result))
+ while len(self.receipts) > MAX_RECEIPTS:
+ self.receipts.pop(next(iter(self.receipts)))
+
+ def _save(self, project, *, ref=None, create=None, client=None):
+ operation = _operation_key(ref, client) if ref is not None else None
+ try:
+ return comfy_editor.save(self.root, project, create=create, operation=operation)
+ except comfy_editor.Conflict as error:
+ raise ProjectError('project_changed', project=self._load(error.identity or project['id'])['project']) from error
+ except comfy_editor.MissingProject as error:
+ raise ProjectError('not_found', 'The project does not exist.') from error
+ except comfy_editor.TooLarge as error:
+ raise ProjectError('too_large') from error
+ except OSError as error:
+ raise ProjectError('storage_unavailable') from error
+ except (ValueError, TypeError, KeyError, RecursionError) as error:
+ raise _invalid('/project', 'a valid editor project') from error
+
+ def _rejected(self, error, stored, path, received, *, operation=None):
+ if error['code'] in STATE_CODES:
+ raise ProjectError(STATE_CODES[error['code']], project=stored, operation=operation)
+ raise _invalid(path, RULE_EXPECTED.get(error['code'], 'an operation this timeline allows'), received)
+
+ # Reads ---------------------------------------------------------------------------------------------
+ def list(self):
+ return dict(items=comfy_editor.list_projects(self.root))
+
+ def get(self, identity):
+ return self._load(identity)
+
+ # Whole-project writes ------------------------------------------------------------------------------
+ def create(self, value, *, ref=None, client=None):
+ schema.validate(schema.project_schema('create'), value)
+ digest, replay = self._receipt('projects:create', value, ref, client)
+ if replay is not None:
+ return replay
+ project = value.get('project') if isinstance(value, dict) else None
+ if not isinstance(project, dict) or project.get('id') is not None or project.get('revision') != 0:
+ raise _invalid('/project', 'a new project with id null and revision 0')
+ # The page's receipt makes a repeated create return the first project.
+ create = _operation_key(ref, client) if ref is not None else None
+ result = dict(project=self._save(deepcopy(project), create=create))
+ self._remember(ref, digest, result, client)
+ return result
+
+ def write(self, identity, value, *, ref=None, client=None):
+ schema.validate(schema.project_schema('write'), value)
+ digest, replay = self._receipt('projects:write', dict(id=identity, body=value), ref, client)
+ if replay is not None:
+ return replay
+ project = value.get('project') if isinstance(value, dict) else None
+ if not isinstance(project, dict) or project.get('id') != identity:
+ raise _invalid('/project/id', 'the project id in the path', project.get('id') if isinstance(project, dict) else None)
+ before = self._load(identity)['project']
+ saved = self._save(deepcopy(project), ref=ref, client=client)
+ result = dict(project=saved, changed_clip_ids=changed_clip_ids(before, saved))
+ self._remember(ref, digest, result, client)
+ return result
+
+ # Operations ----------------------------------------------------------------------------------------
+ def _media(self, operations):
+ """Insert operations name a source key; the server fills in its length and streams."""
+ keys = [op['source'] for op in operations if op.get('op') == 'insert']
+ found = comfy_editor.sources(self.root, keys) if keys else {}
+ resolved = []
+ for index, op in enumerate(operations):
+ if op.get('op') != 'insert':
+ resolved.append(op)
+ continue
+ info = found[op['source']]
+ if info['missing'] or not info['frames']:
+ raise ProjectError('source_missing', 'The source to insert is not available.', operation=index)
+ kind, identity = op['source'].split(':', 1)
+ media = dict(source=dict(kind=kind, id=identity), frames=info['frames'], hasVideo=info['has_video'],
+ hasAudio=info['has_audio'], width=info['width'], height=info['height'])
+ resolved.append(dict({k: v for k, v in op.items() if k != 'source'}, media=media))
+ return resolved
+
+ def operations(self, identity, value, *, client=None, ref=None):
+ """Apply 1-64 operations to the revision the caller read; all succeed and save once, or nothing changes."""
+ schema.validate(schema.project_schema('operations'), value)
+ revision, operations = value.get('revision'), value.get('operations')
+ digest, replay = self._receipt('projects:operations', dict(id=identity, body=value), ref, client)
+ if replay is not None:
+ return replay
+ stored = self._load(identity)['project']
+ if stored['revision'] != revision:
+ raise ProjectError('project_changed', project=stored)
+ try:
+ for index, op in enumerate(operations):
+ if op.get('op') == 'insert':
+ comfy_editor.source_key(dict(zip(('kind', 'id'), op['source'].split(':', 1))))
+ except (ValueError, TypeError, AttributeError) as error:
+ raise _invalid('/operations/%d/source' % index,
+ 'a source key: work:<library id>, generated:<file> or import:<id>', op.get('source')) from error
+ reply = editor_runtime.runtime().batch(stored, self._media(operations))
+ if not reply['ok']:
+ index = reply['index']
+ self._rejected(reply['error'], stored, '/operations/%d' % index if index is not None else '/project',
+ operations[index] if index is not None else None, operation=index)
+ saved = self._save(reply['project'], ref=ref, client=client)
+ result = dict(project=saved, changed_clip_ids=changed_clip_ids(stored, saved), results=reply['results'])
+ self._remember(ref, digest, result, client)
+ return result
+
+
+ # Generation ----------------------------------------------------------------------------------------
+ def generate(self, identity, value, *, jobs, capability=None, ref=None, client=None):
+ """Make new video and sound for a range or parts, as the page's Generate does.
+
+ capability(size) returns the device's capability reply for that size, or None.
+
+ The parts are planned and saved first (the reservation), so a page that
+ saved in between makes this fail with project_changed before any GPU
+ work; only then is the chain submitted. Its blocks fill the parts as
+ they finish (deliver), whether or not the page is open.
+ """
+ schema.validate(schema.project_schema('generate'), value)
+ digest, replay = self._receipt('projects:generate', dict(id=identity, body=value), ref, client)
+ if replay is not None:
+ return replay
+ text, target, settings = value.get('text', ''), value['target'], value.get('settings') or {}
+ stored = self._load(identity)['project']
+ if stored['revision'] != value['revision']:
+ raise ProjectError('project_changed', project=stored)
+ rules = editor_runtime.runtime()
+ plan = rules.generation(mode='plan', project=stored, target=target, text=text, capability=None)
+ # Part lengths follow what this device can make at the project's size, as on the page;
+ # until that is measured the page's 15 s parts apply.
+ reply = capability(plan['size']) if capability is not None and plan['ok'] else None
+ if isinstance(reply, dict) and reply.get('status', 'ready') == 'ready':
+ plan = rules.generation(mode='plan', project=stored, target=target, text=text, capability=reply)
+ if not plan['ok']:
+ self._rejected(plan['error'], stored, '/target', target)
+ found = comfy_editor.sources(self.root, plan['keys']) if plan['keys'] else {}
+ if any(info['missing'] or not info.get('path') for info in found.values()):
+ raise ProjectError('source_missing', 'The part this generation continues from is not available.')
+ request = rules.generation(mode='request', project=plan['project'], ids=plan['ids'], text=text,
+ paths={key: info['path'] for key, info in found.items()})
+ if not request['ok']:
+ self._rejected(request['error'], stored, '/target', target)
+ limit = plan['max_request_frames']
+ longest = max(block['frames'] for block in request['blocks'])
+ if limit is not None and longest > limit:
+ raise _invalid('/target', 'parts of at most %d frames at this size and quality; choose a shorter range'
+ % limit, longest)
+ seed = settings['seed'] if settings.get('seed') is not None else secrets.randbelow(2**32)
+ blocks = [dict(block, seed=seed + index) for index, block in enumerate(request['blocks'])]
+ prompt = text.strip() or next((b['text'] for b in blocks if b['text'].strip()), '') or 'Continue the video.'
+ frames = sum(block['frames'] for block in blocks)
+ spec = dict({k: v for k, v in settings.items() if k in ('quality', 'sampling', 'loras', 'force_regenerate')},
+ kind='generate', prompt=prompt, seed=seed, width=plan['size']['width'],
+ height=plan['size']['height'], seconds=min(60., max(1.625, frames / 24)),
+ label='Editing project ' + identity)
+ saved = self._save(plan['project']) # The reservation: the page's revision check orders it.
+ editor = dict(project=identity, ids=plan['ids'], blocks=blocks, revision=saved['revision'])
+ try:
+ job = jobs.submit(spec, client=client, editor=editor)[0]
+ except Exception:
+ self._release(identity, plan['ids'])
+ raise
+ with self.lock:
+ self.prepared[job['id']] = saved
+ result = dict(job=jobs.view(job), jobs=[jobs.view(job)], project=saved, clip_ids=plan['ids'])
+ self._remember(ref, digest, result, client)
+ return result
+
+ def export(self, identity, value, *, jobs, ref=None, client=None):
+ """Queue an export job for the revision the caller read; a stale revision starts nothing."""
+ schema.validate(schema.project_schema('export'), value)
+ digest, replay = self._receipt('projects:export', dict(id=identity, body=value), ref, client)
+ if replay is not None:
+ return replay
+ stored = self._load(identity)['project']
+ if stored['revision'] != value['revision']:
+ raise ProjectError('project_changed', project=stored)
+ job = jobs.submit(dict(kind='export', editor_project=identity, revision=value['revision']), client=client)[0]
+ result = dict(job=jobs.view(job), jobs=[jobs.view(job)])
+ self._remember(ref, digest, result, client)
+ return result
+
+ def _update(self, identity, change, *, tries=4):
+ """Read, change and save; a page save in between makes it read again. None when nothing changed."""
+ for _ in range(tries):
+ current = self._load(identity)['project']
+ reply = change(current)
+ if not reply['ok']:
+ raise ProjectError('invalid_output', reply['error']['message'])
+ if reply['project'] == current:
+ return None
+ try:
+ return comfy_editor.save(self.root, reply['project'])
+ except comfy_editor.Conflict:
+ continue
+ raise ProjectError('project_changed', project=self._load(identity)['project'])
+
+ def _release(self, identity, ids):
+ """A reservation whose job was refused returns to draft, as the page's failed start does."""
+ try:
+ self._update(identity, lambda project: editor_runtime.runtime().deliver(
+ project=project, ids=ids, job=None, settle='draft'))
+ except (JobError, OSError) as error:
+ logging.getLogger(__name__).warning('Project %s parts stayed reserved (%s)', identity, type(error).__name__)
+
+ def attach(self, row, *, resumed=False):
+ """Write the chain id into the reserved parts (the page's assignJob), or mark them queued again on resume."""
+ editor, chain = row['editor'], row['chain_id']
+ with self.lock:
+ prepared = self.prepared.pop(row['id'], None)
+ def change(project):
+ if resumed:
+ return editor_runtime.runtime().deliver(project=project, ids=editor['ids'], job=chain, settle='queued')
+ # After a restart the reservation is gone from memory; the parts' own plan stands in for it.
+ return editor_runtime.runtime().deliver(project=project, ids=editor['ids'], job=chain,
+ assign=prepared or project)
+ self._apply(row, change)
+
+ def deliver(self, row, chain):
+ """Fill, fail or settle the parts from the chain's blocks; idempotent, so every poll may call it."""
+ editor, sources = row['editor'], {}
+ state = [[b['id'], b['state'], b['output']] for b in chain['blocks']] + [chain['state']]
+ if editor.get('delivered') == state:
+ return
+ outputs = [b['output'] for b in chain['blocks'] if b['state'] == 'done' and b['output']]
+ if outputs:
+ found = comfy_editor.sources(self.root, ['generated:' + output for output in outputs])
+ sources = {output: found['generated:' + output] for output in outputs}
+ if self._apply(row, lambda project: editor_runtime.runtime().deliver(
+ project=project, ids=editor['ids'], job=chain['id'], chain=chain, sources=sources)):
+ editor['delivered'] = state
+
+ def _apply(self, row, change):
+ editor = row['editor']
+ try:
+ saved = self._update(editor['project'], change)
+ except (JobError, OSError) as error:
+ # The job goes on; the next poll tries again, and an open page fills the parts the same way.
+ editor['problem'] = getattr(error, 'code', 'storage_unavailable')
+ return False
+ editor.pop('problem', None)
+ if saved is not None:
+ editor['revision'] = saved['revision']
+ return True
+
+
+# Export ----------------------------------------------------------------------------------------------
+EXPORT_REASONS = {'source_missing': 'source_missing', 'unreadable': 'source_missing', 'disk_full': 'storage_unavailable'}
+
+
+def run_export(port, row, *, poll=.25):
+ """An export job: one saved revision rendered by the page's export queue, in its turn with the page's exports."""
+ from .. import editor_export
+ from ..editor_text import MissingGlyphs
+ spec = row['spec']
+ queue = port.editor_exports()
+ if queue is None:
+ raise JobError('not_ready', 'The editor export service is not running')
+ try:
+ view = queue.submit(spec['editor_project'], spec['revision'])
+ except editor_export.ExportConflict as error:
+ raise JobError('project_changed', 'The project changed since you read it (now revision %d)' % error.revision) from error
+ except MissingGlyphs as error:
+ raise JobError('missing_glyphs', 'Text in the project uses characters the fonts cannot draw',
+ details=[dict(items=error.items)]) from error
+ except FileNotFoundError as error:
+ raise JobError('not_found', 'The project does not exist') from error
+ except editor_export.ExportError as error:
+ raise JobError('busy', 'The editor export queue is full; retry after the page\'s exports finish') from error
+ except ValueError as error:
+ raise JobError('invalid_request', 'This project cannot be exported: it has no picture or sound') from error
+ identity, cancelled = view['id'], False
+ row['_phase'] = 'exporting'
+ while view['state'] == 'running':
+ if row.get('_cancel') and not cancelled:
+ view, cancelled = queue.cancel(identity), True
+ continue
+ row['_detail'] = json.dumps(dict(fraction=round(view['fraction'], 3)))
+ time.sleep(poll)
+ view = queue.get(identity)
+ if view['state'] == 'cancelled':
+ raise JobError('cancelled', 'Cancelled')
+ if view['state'] != 'done':
+ code = EXPORT_REASONS.get(view.get('reason'), 'export_failed')
+ raise JobError(code, 'The export failed (%s)' % (view.get('reason') or 'failed'))
+ relative = view['path']
+ return dict(library_id=library_id(relative), video=library_view(port, relative),
+ editor_project=spec['editor_project'], revision=spec['revision'])
diff --git a/freevideo_engine/agent/routes.py b/freevideo_engine/agent/routes.py
new file mode 100644
index 0000000..de322c8
--- /dev/null
+++ b/freevideo_engine/agent/routes.py
@@ -0,0 +1,1409 @@
+"""HTTP API for agents: /freevideo/agent/v1/*, bearer-token protected, JSON in and out.
+
+The token lives in <installation>/agent/token. Local agents (and the MCP server)
+read it from disk; web pages cannot, and they cannot send an Authorization header
+to ComfyUI without a CORS preflight that ComfyUI does not grant.
+"""
+import asyncio
+import base64
+import binascii
+import json
+import hashlib
+from inspect import isawaitable
+import logging
+import math
+import os
+from pathlib import Path
+import secrets
+import stat
+import tempfile
+import time
+import uuid
+
+from . import API_VERSION, enabled
+from . import assets
+from . import spec as specs
+from . import schema as contract, errors, access
+from .jobs import ACTIVE, DONE, JobError, Jobs, chain_error, library_view
+
+PREFIX = '/freevideo/agent/v1'
+
+
+def token_path(root):
+ return Path(root) / 'agent' / 'token'
+
+
+def ensure_token(root):
+ """Exclusive creation of the final file; concurrent readers wait for its complete line."""
+ path = token_path(root)
+
+ def read_existing():
+ info = path.lstat()
+ if not stat.S_ISREG(info.st_mode) or (os.name == 'posix' and info.st_uid != os.getuid()):
+ raise ValueError('Unsafe installation token; repair its ownership or remove it and restart')
+ flags = os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0) | getattr(os, 'O_NONBLOCK', 0)
+ descriptor = os.open(path, flags)
+ with os.fdopen(descriptor, 'rb') as stream:
+ opened = os.fstat(stream.fileno())
+ if (not stat.S_ISREG(opened.st_mode) or (opened.st_dev, opened.st_ino) != (info.st_dev, info.st_ino)
+ or os.name == 'posix' and opened.st_uid != os.getuid()):
+ raise ValueError('Unsafe installation token')
+ if os.name == 'posix':
+ os.fchmod(stream.fileno(), 0o600)
+ data = stream.read(256)
+ try:
+ value = data.decode('ascii').strip()
+ except UnicodeDecodeError:
+ raise ValueError('Invalid installation token') from None
+ if data.endswith(b'\n') and 32 <= len(value) <= 128 and all(c.isalnum() or c in '-_' for c in value):
+ return value
+ return None
+
+ try:
+ value = read_existing()
+ if value is not None:
+ return value
+ except FileNotFoundError:
+ path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
+ value = secrets.token_urlsafe(32)
+ # TODO Windows: set a current-user-only ACL; verify on Windows hardware.
+ try:
+ descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
+ except FileExistsError:
+ pass
+ else:
+ with os.fdopen(descriptor, 'wb') as stream:
+ stream.write((value + '\n').encode('ascii'))
+ stream.flush()
+ os.fsync(stream.fileno())
+ return value
+ for _ in range(100):
+ value = read_existing()
+ if value is not None:
+ return value
+ time.sleep(.01)
+ raise ValueError('Incomplete installation token; remove it and restart')
+
+
+def substitute(value, names, _field=None):
+ """Replace "@name" job references inside one batch with the ids assigned to that batch."""
+ if (_field in ('from_job', 'after', 'clips', 'refine_from') and isinstance(value, str)
+ and value.startswith('@') and value[1:] in names):
+ return names[value[1:]]
+ if isinstance(value, list):
+ return [substitute(row, names, _field) for row in value]
+ if isinstance(value, dict):
+ return {key: row if key in ('metadata', 'edit') else substitute(row, names, key) for key, row in value.items()}
+ return value
+
+
+def submit_batch(jobs, body, client):
+ """{"jobs": [{"ref": "s1", ...}, {"media": {"first": {"from_job": "@s1", "frame": "last"}}}]} in one call."""
+ return jobs.submit_request(body, client=client)[0]
+
+
+def features(continuation, vlm):
+ """What an agent can use here (ready says whether the engine can run now). A missing name is not offered."""
+ from .editor_runtime import available
+ rules = available()
+ return {'capabilities': True, 'plan': True, 'jobs.cancel': True, 'jobs.resume': True, 'takes': True,
+ 'library.read': True, 'library.download': True, 'errors.validation': True, 'errors.missing_media': True,
+ 'generate.text': True, 'generate.size': True, 'generate.first_frame': True, 'generate.seed': True,
+ 'queue.shared': True, 'queue.busy': True, 'chain.auto': bool(continuation),
+ 'enhance': bool(vlm.get('ready')), 'drama.film': True, 'images.edit': rules,
+ 'images.layers': rules, 'images.heal': rules, 'images.render': rules, 'projects.read': True,
+ **{'projects.' + name: rules for name in ('insert', 'split', 'move', 'trim', 'remove', 'export', 'generate')}}
+
+
+def capabilities(port, jobs):
+ from .. import __version__
+ from ..comfy_assets import EXTENSIONS
+ from ..comfy_bridge import installation
+ from .guide import GUIDE
+ try:
+ root, machine = installation()
+ ready, problem = True, None
+ except (OSError, ValueError) as error:
+ root, machine, ready, problem = None, {}, False, errors.ERRORS['not_ready'][2]
+ vlm = {}
+ service = getattr(port.server, '_freevideo_prompt_vlm', None)
+ if service is not None:
+ try:
+ vlm = {k: v for k, v in service.info().items() if k in ('ready', 'model', 'license', 'bytes', 'busy')}
+ except (OSError, ValueError):
+ vlm = dict(ready=False)
+ running, pending = port.snapshot()
+ from ..chain_plan import BLOCK_SECONDS
+ # One block is the limit when the backend cannot continue a video; plan and submit refuse the same requests.
+ continuation = jobs.continuation_ready()
+ return dict(
+ api_version=API_VERSION, freevideo_version=__version__, ready=ready, problem=problem, continuation=continuation,
+ features=features(continuation, vlm),
+ device=dict(backend=machine.get('device_backend', 'cuda') if machine else None,
+ vram_limit_gib=machine.get('vram_gib'), ram_limit_gib=machine.get('ram_gib')),
+ kinds={'generate': 'Video with audio from a prompt and optional keyframes or references',
+ 'assemble': 'Join finished clips into one video (cut or crossfade)',
+ 'vlm': 'Ask the local vision-language model about images or sampled video frames',
+ 'enhance': 'Rewrite a rough idea into a full H3 prompt with the local VLM',
+ 'export': 'Render a saved revision of an editing project to a video',
+ 'image_edit': 'Render a saved revision of an image session to a picture'},
+ limits=dict(width=[256, 4096, 32], height=[256, 4096, 32], seconds=[1.625, 60 if continuation else BLOCK_SECONDS],
+ seconds_tested=[4, 15],
+ fps=24, base_steps=[1, 32], refine_steps=[1, 31], references=32, loras=32, lora_strength=[-4, 4],
+ upload_bytes=2 * 1024 ** 3, vlm_images=24, takes=8, batch_jobs=64),
+ quality={name: dict(two_pass=plan[0], base_steps=plan[1], refine_steps=plan[2])
+ for name, plan in specs.QUALITY.items()},
+ aspects=sorted(specs.ASPECTS), native_megapixels=.98,
+ tasks=GUIDE['tasks'], media_extensions={k: sorted(v) for k, v in EXTENSIONS.items()},
+ loras=sorted(n for n in port.folders.get_filename_list('loras') if n.lower().endswith('.safetensors')),
+ vlm=vlm, queue=dict(running=len(running), pending=len(pending),
+ agent_active=len(jobs.active())),
+ docs=dict(guide=PREFIX + '/guide', schema=PREFIX + '/schema', openapi=PREFIX + '/openapi.json'))
+
+
+def plan(port, value, jobs=None):
+ from ..two_pass import plan as sampling_plan
+ from ..geometry import geometry
+ spec = specs.normalize(value)
+ result = dict(spec={k: v for k, v in spec.items() if k != 'depends_on'}, warnings=[])
+ if spec['kind'] != 'generate' or spec.get('refine_from'):
+ return result
+ from .jobs import continuation_problems, cut_problems
+ problems = continuation_problems(spec) + cut_problems(spec, spec['seconds'])
+ if problems:
+ raise specs.SpecError(problems)
+ if jobs is not None:
+ jobs.require_continuation(spec['seconds'])
+ if spec.get('continue_from') and not jobs.continuation_ready():
+ from .jobs import continuation_unavailable
+ raise continuation_unavailable()
+ canvas = geometry(spec['width'], spec['height'], seconds=spec['seconds'])
+ passes = sampling_plan(canvas, spec['two_pass'], spec['task'], base_steps=spec['base_steps'],
+ refine_steps=spec['refine_steps'])
+ result['geometry'] = {k: canvas[k] for k in ('width', 'height', 'frames', 'seconds', 'fps', 'latent_frames')}
+ result['sampling'] = dict(two_pass=passes['enabled'], total_steps=passes['total_steps'],
+ first_pass=passes.get('first'), second_pass=passes.get('second') if passes['enabled'] else None)
+ if spec['seconds'] > 15:
+ result['warnings'].append('Longer than 15 s is experimental')
+ if spec['task'] == 'ref2va':
+ result['warnings'].append('Reference generation is experimental')
+ if spec['width'] * spec['height'] > 2 * 1024 ** 2:
+ result['warnings'].append('Above 2 MP takes much longer and needs more memory')
+ from ..chain_plan import plan as chain_plan
+ result['chain_plan'] = chain_plan(spec['seconds'])
+ from .forecast import generation_estimate
+ result['estimate'], result['capabilities_revision'] = generation_estimate(port, spec, result['chain_plan'])
+ return result
+
+
+async def wait_for_job(jobs, row, seconds, *, clock=time.monotonic, sleep=asyncio.sleep):
+ if not math.isfinite(seconds) or seconds < 0:
+ raise chain_error('invalid_wait', 'wait must be a finite nonnegative number of seconds.',
+ 'Use GET /jobs/{id}?wait=25 or wait=0.',
+ details=[dict(field='/wait', allowed='finite number >= 0')])
+ deadline = clock() + min(25., seconds)
+ while row['status'] not in DONE and clock() < deadline:
+ await sleep(min(.5, max(0., deadline - clock())))
+ return await asyncio.to_thread(jobs.view, row)
+
+
+def saved_identity(port, day, run):
+ from datetime import date
+ from ..comfy_library import _video
+ identity = day + '/' + run
+ try:
+ date.fromisoformat(day)
+ _video(port.output_root, identity)
+ except (ValueError, TypeError):
+ raise chain_error('invalid_library_id', 'day and run must identify a video inside the saved library.',
+ 'GET /freevideo/agent/v1/library and use an item ID (YYYY-MM-DD/32 lowercase hex characters).',
+ details=[dict(field='/day', allowed='valid YYYY-MM-DD'),
+ dict(field='/run', allowed='32 lowercase hex characters')]) from None
+ return identity
+
+
+def library(port, jobs, *, limit=24, before=None, query=None, project=None):
+ from ..comfy_library import list_videos
+ page = list_videos(port.output_root, before=before, limit=limit)
+ by_video = {}
+ for row in jobs.rows():
+ video = ((row.get('result') or {}).get('video') or {}).get('file')
+ if video:
+ by_video[video] = row
+ items = []
+ for item in page['items']:
+ folder = port.output_root / Path(item['video']).parent
+ try:
+ prompt = (folder / 'prompt.txt').read_text(encoding='utf-8')
+ except OSError:
+ prompt = ''
+ agent = by_video.get(item['video'])
+ if query and query.lower() not in prompt.lower():
+ continue
+ if project and (not agent or agent['spec'].get('project') != project):
+ continue
+ geometry = item.get('geometry') or {}
+ items.append(dict(id=item['id'], created_at=item['created_at'], video=library_view(port, item['video']),
+ width=geometry.get('width'), height=geometry.get('height'), seconds=geometry.get('seconds'),
+ preview=item.get('preview'), request_seconds=item.get('request_seconds'),
+ prompt=prompt[:600] + ('…' if len(prompt) > 600 else ''),
+ job=dict(id=agent['id'], label=agent['spec'].get('label'),
+ project=agent['spec'].get('project')) if agent else None,
+ thumbnail=PREFIX + '/library/' + item['id'] + '/thumbnail'))
+ return dict(items=items, next=page['next'])
+
+
+def register():
+ from aiohttp import web
+ from server import PromptServer
+ server = PromptServer.instance
+ if server is None or getattr(server, '_freevideo_agent', None) is not None:
+ return
+ from .. import proxy_identity
+ hop_secret = os.environ.pop(proxy_identity.ENV, '')
+ if getattr(server, 'app', None) is not None:
+ server.app[proxy_identity.app_key()] = hop_secret
+ if not enabled():
+ # Off: a single answer, so the page shows no agent controls. No token, jobs or scheduler.
+ if not getattr(server, '_freevideo_agent_off', False):
+ server._freevideo_agent_off = True
+
+ @server.routes.get('/freevideo/agent')
+ async def off(request):
+ return web.json_response({'enabled': False}, headers={'Cache-Control': 'no-store'})
+ return
+ from .comfy import ComfyPort
+ port = ComfyPort(server)
+ jobs = Jobs(port, port.output_root / 'FreeVideo' / '.agent' / 'jobs')
+ server._freevideo_agent = jobs
+ from .sessions import Confirmations, Sessions
+ sessions = Sessions(port.output_root / 'FreeVideo' / '.agent' / 'sessions')
+ server._freevideo_agent_sessions = sessions
+ # The user's stop also cancels this session's queued and running agent work and pauses its productions.
+ sessions.on_stop.append(lambda sid: asyncio.to_thread(jobs.stop_session, sid))
+ # Operations an agent runs only after the user approves them; the page changes the policy.
+ confirmations = Confirmations(port.output_root / 'FreeVideo' / '.agent' / 'confirm.json', sessions)
+ jobs.productions.gate = confirmations.gate
+ tokens = {}
+ thumbnails = asyncio.Semaphore(1)
+ upload_decoders = asyncio.Semaphore(1)
+
+ def expected():
+ from ..comfy_bridge import installation_root
+ root = installation_root()
+ if root not in tokens:
+ tokens[root] = ensure_token(root)
+ return tokens[root]
+
+ def reply(value, status=200):
+ return web.json_response(value, status=status, headers={'Cache-Control': 'no-store'},
+ dumps=lambda v: json.dumps(v, ensure_ascii=False))
+
+ query_key = web.AppKey('agent_query', dict)
+ body_key = web.AppKey('agent_body', dict)
+ contracts = contract.contracts()
+ page_sessions = {}
+ connection = dict(connected=False, client=None, via=None, last_seen_at=None)
+ server._freevideo_agent_connection = connection
+
+ def problem(code, message=None, status=None, **details):
+ error = errors.build(code, details=details.get('details'), owner=details.get('owner'))
+ return reply({'error': error}, errors.ERRORS[error['code']][0] or 500)
+
+ def work_sessions():
+ return getattr(server, '_freevideo_agent_sessions', None)
+
+ def guarded(handler):
+ async def wrapped(request):
+ response = await respond(request)
+ try:
+ return await session_after(request, response)
+ except Exception:
+ # The session record is a view of the work; it never fails the work itself.
+ logging.getLogger(__name__).warning('Session record failed', exc_info=True)
+ return response
+
+ async def respond(request):
+ identity = errors.REQUEST_ID.set('r-' + uuid.uuid4().hex)
+ attached = None
+ suffix = ''
+ try:
+ suffix = request.match_info.route.resource.canonical
+ suffix = suffix[len(PREFIX):] if suffix.startswith(PREFIX) else suffix
+ method = 'GET' if request.method == 'HEAD' else request.method
+ definition = contracts.get((method, suffix))
+ if definition is None:
+ raise JobError('method_not_allowed' if any(p == suffix for _, p in contracts) else 'not_found', 'No contract')
+ access.check(request, local=definition.get('local', False))
+ if definition.get('auth') is False and definition.get('local') and method not in ('GET', 'HEAD'):
+ session = page_sessions.get(request.cookies.get('freevideo_agent_page', ''))
+ csrf = request.headers.get('X-FreeVideo-CSRF', '')
+ if (session is None or session[1] < time.monotonic() or not csrf
+ or not secrets.compare_digest(csrf.encode(), session[0].encode())):
+ raise JobError('page_session_required', 'Page session required')
+ header = request.headers.get('Authorization', '')
+ given = header[7:].strip() if header[:7].lower() == 'bearer ' else request.headers.get('X-FreeVideo-Agent', '')
+ if definition.get('auth', True) or given:
+ try:
+ token = expected()
+ except (OSError, ValueError):
+ raise JobError('not_ready', 'Installation not ready') from None
+ if not given or not secrets.compare_digest(given.encode('utf-8'), token.encode('utf-8')):
+ raise JobError('unauthorized', 'Token missing or incorrect')
+ connection.update(connected=True, last_seen_at=time.time())
+ connection['client'] = connection['client'] or request.headers.get('X-FreeVideo-Client', 'HTTP client')[:80]
+ connection['via'] = connection['via'] or 'http'
+ request['agent_client'] = request.headers.get('X-FreeVideo-Client', '')[:80] or 'HTTP client'
+ if definition.get('path'):
+ contract.validate(definition['path'], dict(request.match_info))
+ for key in request.query:
+ if len(request.query.getall(key)) != 1:
+ raise specs.SpecError(contract.diagnostic('/query/' + (contract.pointer(key) if key in definition['query']['properties'] else '<unknown>'), 'supplied once', None))
+ try:
+ request[query_key] = contract.query_values(definition['query'], request.query)
+ except specs.SpecError as error:
+ error.code = 'invalid_capabilities_query' if suffix == '/capabilities' else 'invalid_wait' if suffix == '/jobs/{id}' else 'invalid_request'
+ raise
+ if definition['body'] is not None:
+ if definition.get('multipart') and request.content_type == 'multipart/form-data':
+ pass
+ else:
+ limit = contract.MAX_JSON_UPLOAD_BYTES if suffix == '/media' else contract.MAX_BODY_BYTES
+ value = await read_body(request, limit, definition.get('optional_body', False))
+ try:
+ contract.validate(definition['body'], value)
+ except specs.SpecError as error:
+ error.code = 'invalid_resume' if suffix.endswith('/resume') else 'invalid_request'
+ raise
+ request[body_key] = value
+ if request.method == 'HEAD' and suffix.endswith('/events'):
+ if suffix.startswith('/sessions/'):
+ session_caller(request)
+ await asyncio.to_thread(sessions.get, request.match_info['id'])
+ else:
+ await asyncio.to_thread(jobs.get, request.match_info['id'])
+ return web.Response(content_type='text/event-stream', headers={'Cache-Control': 'no-store'})
+ attached = await session_before(request, suffix, method, definition)
+ return await handler(request)
+ except specs.SpecError as error:
+ value = errors.validation(error.errors, getattr(error, 'code', 'invalid_request'))
+ return reply({'error': value}, errors.ERRORS[value['code']][0])
+ except JobError as error:
+ value = error.view()
+ if value.get('next') and request.match_info.get('id'):
+ value['next'] = value['next'].replace('{id}', request.match_info['id'])
+ if error.code == 'too_large':
+ limit = error.details.get('limit_bytes', contract.MAX_UPLOAD_BYTES)
+ value.update(message='The upload must be at most %d bytes; a larger payload was received.' % limit,
+ details=[dict(limit_bytes=limit)], next='Reduce the payload to at most %d bytes and retry.' % limit)
+ if error.code == 'busy':
+ entries = (await asyncio.to_thread(jobs.queue_view))['entries']
+ value = errors.build('busy', owner=entries[0]['owner'] if entries else 'ui')
+ return reply({'error': value}, getattr(error, 'status', errors.ERRORS[value['code']][0]))
+ except KeyError:
+ return problem('not_found')
+ except (json.JSONDecodeError, UnicodeDecodeError, RecursionError):
+ return problem('invalid_json')
+ except OSError:
+ return reply({'error': errors.build('storage_unavailable', stage='submission_unknown' if suffix == '/jobs' else 'request')}, 503)
+ except ValueError:
+ return problem('invalid_edit' if suffix == '/media/edit' else 'invalid_media' if suffix.startswith('/media') else 'invalid_request')
+ except web.HTTPException as error:
+ return problem('too_large' if error.status == 413 else 'invalid_request')
+ except Exception:
+ return reply({'error': errors.build('internal_error', stage='submission_unknown' if suffix == '/jobs' else 'request')}, 500)
+ finally:
+ for variable, token in attached or ():
+ variable.reset(token)
+ errors.REQUEST_ID.reset(identity)
+ return wrapped
+
+ # Work sessions (sessions.py): which session a token request belongs to, its step events,
+ # the user's stop, and the user's unread words returned with each answer.
+ SESSION_FREE = ('/sessions', '/connect')
+ REF_KINDS = {'/jobs/': 'job', '/drama/': 'drama', '/projects/': 'project', '/images/': 'image', '/cast/': 'cast'}
+
+ async def session_before(request, suffix, method, definition):
+ store = work_sessions()
+ client = request.get('agent_client')
+ if store is None or client is None or suffix.startswith(SESSION_FREE):
+ return None
+ write = method not in ('GET', 'HEAD')
+ def attach():
+ sid = request.headers.get('X-FreeVideo-Session', '').strip()
+ if sid:
+ store.get(sid) # not_found for an unknown session
+ else:
+ sid = store.latest_for(client) or (store.create(client=client)['id'] if write else None)
+ if sid is None:
+ return None
+ request['agent_session'] = sid
+ if not write:
+ return None
+ if store.stopped(sid) and not suffix.endswith('/cancel'):
+ raise JobError('stopped_by_user', 'The user stopped this session')
+ refs = {}
+ for prefix, kind in REF_KINDS.items():
+ if suffix.startswith(prefix) and 'id' in request.match_info:
+ refs[kind] = request.match_info['id']
+ tool = request.headers.get('X-FreeVideo-Tool', '')[:80] or None
+ step = dict(type='step', tool=tool or method + ' ' + suffix, summary=definition.get('summary') or suffix,
+ state='started', refs=refs, thumbs=[])
+ request['agent_step'] = store.append(sid, step, by='agent', client=client)
+ return sid
+ sid = await asyncio.to_thread(attach)
+ if sid is None:
+ return None
+ # A confirmation approves exactly this operation; a new idempotency ref is the same operation.
+ value = request.get(body_key)
+ value = {k: v for k, v in value.items() if k != 'ref'} if isinstance(value, dict) else value
+ digest = hashlib.sha256(json.dumps([method, suffix, dict(request.match_info), value], sort_keys=True,
+ separators=(',', ':'), ensure_ascii=False).encode('utf-8')).hexdigest()
+ return (errors.SESSION, errors.SESSION.set(sid)), (errors.CONFIRM, errors.CONFIRM.set(digest))
+
+ def response_refs(value):
+ refs = {}
+ if not isinstance(value, dict):
+ return refs
+ job = value.get('job') if isinstance(value.get('job'), dict) else value if str(value.get('id', '')).startswith('j') else None
+ if job and isinstance(job.get('id'), str):
+ refs['job'] = job['id']
+ for key in ('drama', 'project', 'image'):
+ if isinstance(value.get(key), str):
+ refs[key] = value[key]
+ return refs
+
+ async def session_after(request, response):
+ store = work_sessions()
+ sid = request.get('agent_session')
+ if store is None or sid is None or not isinstance(response, web.Response) or response.content_type != 'application/json':
+ return response
+ value = json.loads(response.body) if response.body else None
+ step = request.get('agent_step')
+ if step is not None:
+ failed = response.status >= 400
+ refs = dict(step['refs'], **response_refs(value))
+ done = dict(type='step', id=step['id'], tool=step['tool'], summary=step['summary'],
+ state='failed' if failed else 'done', refs=refs, thumbs=[])
+ if failed and isinstance(value, dict) and isinstance(value.get('error'), dict):
+ done['error'] = value['error'].get('code')
+ await asyncio.to_thread(store.append, sid, done, by='agent', client=request['agent_client'])
+ unread = await asyncio.to_thread(store.unread, sid, request['agent_client']) if isinstance(value, dict) else []
+ headers = {'X-FreeVideo-Session': sid}
+ if unread:
+ value = dict(value, inbox=unread[-20:])
+ headers['X-FreeVideo-Inbox'] = str(len(unread))
+ fresh = reply(value, response.status)
+ for key, item in response.headers.items():
+ if key.lower() not in ('content-length', 'content-type'):
+ fresh.headers[key] = item
+ response = fresh
+ response.headers.update(headers)
+ return response
+
+ async def read_body(request, limit, optional=False):
+ if optional and not request.can_read_body:
+ return {}
+ if request.content_type != 'application/json':
+ raise JobError('unsupported_media_type', 'JSON required')
+ data = bytearray()
+ async for chunk in request.content.iter_chunked(64 * 1024):
+ data.extend(chunk)
+ if len(data) > limit:
+ raise JobError('too_large', 'Body exceeds limit', limit_bytes=limit)
+ return json.loads(data.decode('utf-8'), parse_constant=lambda _: (_ for _ in ()).throw(json.JSONDecodeError('Nonfinite JSON', '', 0)))
+
+ async def body(request, **ignored):
+ return request[body_key]
+
+ def session_caller(request):
+ """guarded verifies supplied tokens; otherwise require a local page and CSRF."""
+ header = request.headers.get('Authorization', '')
+ given = header[7:].strip() if header[:7].lower() == 'bearer ' else request.headers.get('X-FreeVideo-Agent', '')
+ if given:
+ return 'agent'
+ page = page_sessions.get(request.cookies.get('freevideo_agent_page', ''))
+ csrf = request.headers.get('X-FreeVideo-CSRF', '')
+ if (page is not None and page[1] >= time.monotonic() and csrf
+ and secrets.compare_digest(csrf.encode(), page[0].encode())):
+ access.check(request, local=True)
+ return 'user'
+ raise JobError('unauthorized', 'Token or valid page session required')
+
+ def session_client(request, by):
+ return (request.headers.get('X-FreeVideo-Client', '')[:80] or None) if by == 'agent' else None
+
+ async def no_cross_site_headers(request, response):
+ if request.path.startswith('/freevideo/agent'):
+ for key in list(response.headers):
+ if key.lower().startswith('access-control-'):
+ del response.headers[key]
+ if getattr(server, 'app', None) is not None:
+ server.app.on_response_prepare.append(no_cross_site_headers)
+
+ @web.middleware
+ async def unregistered(request, handler):
+ if request.path == '/freevideo/agent' or request.path.startswith('/freevideo/agent/'):
+ exception = request.match_info.http_exception
+ if exception is not None:
+ return problem('method_not_allowed' if exception.status == 405 else 'not_found')
+ return await handler(request)
+ server.app.middlewares.append(unregistered)
+
+ routes = server.routes
+
+ @routes.get('/freevideo/agent')
+ @guarded
+ async def discover(request):
+ # Unauthenticated: tells a client where to look, reveals nothing else.
+ return reply(dict(enabled=True, api_versions=[API_VERSION], base=PREFIX, auth='bearer',
+ token='agent/token in the FreeVideo installation folder'))
+
+ @routes.get('/freevideo/agent/session')
+ @guarded
+ async def page_session(request):
+ stamp = time.monotonic()
+ for key, (_, expires) in list(page_sessions.items()):
+ if expires < stamp:
+ page_sessions.pop(key, None)
+ current = request.cookies.get('freevideo_agent_page', '')
+ if current not in page_sessions:
+ current = secrets.token_urlsafe(32)
+ if len(page_sessions) >= 256:
+ page_sessions.pop(next(iter(page_sessions)))
+ page_sessions[current] = (secrets.token_urlsafe(32), stamp + 12 * 3600)
+ response = reply(dict(csrf=page_sessions[current][0]))
+ response.set_cookie('freevideo_agent_page', current, httponly=True, samesite='Strict',
+ secure=request.secure, path='/freevideo/agent', max_age=12 * 3600)
+ return response
+
+ @routes.get('/freevideo/agent/activity')
+ @guarded
+ async def activity(request):
+ def read():
+ # For the studio: what agents are doing, as ComfyUI's own queue and history already show.
+ now = time.time()
+ rows = sorted(jobs.rows(), key=lambda r: r['created_at'], reverse=True)
+ shown = [r for r in rows if r['status'] in ACTIVE or (r.get('finished_at') or 0) > now - 1800][:12]
+ def item(row):
+ view = jobs.view(row, detail=False)
+ value = {k: view.get(k) for k in ('id', 'kind', 'status', 'label', 'project', 'client', 'take',
+ 'created_at', 'finished_at')}
+ progress = view.get('progress') or {}
+ value['progress'] = {k: progress[k] for k in ('phase', 'step', 'fraction', 'remaining_seconds',
+ 'queue_position') if progress.get(k) is not None}
+ if view.get('waiting_for'):
+ value['waiting_for'] = len(view['waiting_for'])
+ if view.get('error'):
+ value['error'] = view['error']
+ video = (view.get('result') or {}).get('video') or {}
+ if video.get('url'):
+ value['video'] = video['url']
+ return value
+ return dict(active=sum(1 for r in rows if r['status'] in ACTIVE), jobs=[item(r) for r in shown])
+ return reply(await asyncio.to_thread(read))
+
+ @routes.post('/freevideo/agent/activity/cancel')
+ @guarded
+ async def activity_cancel(request):
+ # JSON only, so another site cannot send it without a CORS preflight.
+ if request.content_type != 'application/json':
+ return problem('unsupported_media_type', 'Send JSON', 415)
+ value = await body(request)
+ try:
+ row = await asyncio.to_thread(jobs.cancel, value.get('id') if isinstance(value, dict) else None)
+ except KeyError:
+ return problem('not_found', 'No such job', 404)
+ return reply(dict(id=row['id'], status=row['status']))
+
+ @routes.get('/freevideo/agent/connect')
+ @guarded
+ async def connect(request):
+ # For Settings: how to connect an agent on this computer. The token itself stays in its file.
+ from ..comfy_bridge import installation_root, source_root
+ from .mcp import client_config
+ try:
+ root = installation_root()
+ ensure_token(root)
+ except (OSError, ValueError) as error:
+ return problem('not_ready', str(error), 503)
+ config = await asyncio.to_thread(client_config, root)
+ script = next((folder / name for folder in (root, source_root())
+ for name in (('freevideo.cmd',) if os.name == 'nt' else ('freevideo',))
+ if (folder / name).is_file()), None)
+ seen = {}
+ for row in jobs.rows():
+ if row.get('client'):
+ seen[row['client']] = max(seen.get(row['client'], 0), row['created_at'])
+ return reply(dict(api=PREFIX, token_file=str(token_path(root)), claude_code=config['claude_code'],
+ mcp_json=config['mcp_json'], cli=('"%s"' % script if ' ' in str(script) else str(script))
+ + ' agent status' if script else None,
+ token_from_environment=False,
+ agents=[dict(client=name, last_seen=time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(stamp)))
+ for name, stamp in sorted(seen.items(), key=lambda item: -item[1])[:5]]))
+
+ @routes.post('/freevideo/agent/connect/reset')
+ @guarded
+ async def reset(request):
+ if request.content_type != 'application/json':
+ return problem('unsupported_media_type', 'Send JSON', 415)
+ await body(request)
+ from ..comfy_bridge import installation_root
+ root = installation_root()
+ token_path(root).unlink(missing_ok=True)
+ tokens.pop(root, None)
+ ensure_token(root)
+ return reply(dict(reset=True))
+
+ @routes.get(PREFIX + '/connect')
+ @guarded
+ async def connect_guide(request):
+ from ..comfy_bridge import installation_root
+ from .guide import connection_guide, connection_text
+ root = installation_root()
+ ensure_token(root)
+ value = connection_guide(root, request.scheme + '://' + request.host)
+ if request[query_key].get('format') == 'json':
+ return reply(value)
+ return web.Response(text=connection_text(value), content_type='text/plain', headers={'Cache-Control': 'no-store'})
+
+ @routes.post(PREFIX + '/connect/hello')
+ @guarded
+ async def hello(request):
+ value = await body(request)
+ connection.update(connected=True, client=value['client'], via=value['via'], last_seen_at=time.time())
+ unfinished = await asyncio.to_thread(jobs.productions.list, status='active', limit=5)
+ return reply(dict(connection, unfinished=unfinished))
+
+ @routes.get(PREFIX + '/connect/status')
+ @guarded
+ async def connect_status(request):
+ from .jobs import iso
+ seen = connection['last_seen_at']
+ return reply(dict(connection, connected=seen is not None and 0 <= time.time() - seen < 600,
+ last_seen_at=iso(seen)))
+
+ @routes.get(PREFIX)
+ @guarded
+ async def info(request):
+ return reply(await asyncio.to_thread(capabilities, port, jobs))
+
+ @routes.get(PREFIX + '/capabilities')
+ @guarded
+ async def capability_route(request):
+ try:
+ value = await port.capability_view({k: str(v) for k, v in request[query_key].items()})
+ except (ValueError, TypeError, OverflowError, RecursionError):
+ raise chain_error('invalid_capabilities_query', 'The capabilities query has invalid size, task or material metadata.',
+ 'Use both width and height (256-4096, multiples of 32), task=t2va and adapters=0; see GET /guide.',
+ details=[dict(field='/query', allowed='the same parameters as /freevideo/capabilities')]) from None
+ return reply(value)
+
+ @routes.get(PREFIX + '/guide')
+ @guarded
+ async def guide(request):
+ from .guide import GUIDE
+ return reply(GUIDE)
+
+ @routes.get(PREFIX + '/schema')
+ @guarded
+ async def schema(request):
+ from .schema import schemas
+ return reply(schemas())
+
+ @routes.get(PREFIX + '/openapi.json')
+ @guarded
+ async def openapi(request):
+ from .schema import openapi as document
+ return reply(document())
+
+ @routes.post(PREFIX + '/plan')
+ @guarded
+ async def plan_route(request):
+ return reply(await asyncio.to_thread(plan, port, await body(request), jobs))
+
+ @routes.post(PREFIX + '/jobs')
+ @guarded
+ async def submit(request):
+ value = await body(request)
+ client = request.headers.get('X-FreeVideo-Client', '')[:80] or None
+ rows, replay = await asyncio.to_thread(jobs.submit_request, value, client=client,
+ key=request.headers.get('Idempotency-Key'))
+ await jobs.tick()
+ def read():
+ return [jobs.view(row) for row in rows]
+ views = await asyncio.to_thread(read)
+ return reply(dict(job=views[0], jobs=views), 200 if replay else 201)
+
+ @routes.get(PREFIX + '/jobs')
+ @guarded
+ async def list_jobs(request):
+ def read():
+ status = request[query_key].get('status')
+ rows = jobs.list(status=status.split(',') if status else None, project=request[query_key].get('project'),
+ kind=request[query_key].get('kind'), limit=min(200, int(request[query_key].get('limit', '50'))))
+ return dict(jobs=[jobs.view(row, detail=False) for row in rows])
+ return reply(await asyncio.to_thread(read))
+
+ @routes.get(PREFIX + '/jobs/{id}')
+ @guarded
+ async def get_job(request):
+ row = await asyncio.to_thread(jobs.get, request.match_info['id'])
+ return reply(await wait_for_job(jobs, row, float(request[query_key].get('wait', '0') or 0)))
+
+ @routes.post(PREFIX + '/jobs/{id}/cancel')
+ @guarded
+ async def cancel(request):
+ def work():
+ return jobs.view(jobs.cancel(request.match_info['id']))
+ return reply(await asyncio.to_thread(work))
+
+ @routes.post(PREFIX + '/jobs/{id}/resume')
+ @guarded
+ async def resume(request):
+ row, replay = await asyncio.to_thread(jobs.resume, request.match_info['id'],
+ key=request.headers.get('Idempotency-Key'), value=await body(request), replay_result=True,
+ client=request.headers.get('X-FreeVideo-Client', '')[:80] or None)
+ await jobs.tick()
+ return reply(await asyncio.to_thread(jobs.view, row))
+
+ @routes.get(PREFIX + '/jobs/{id}/events')
+ @guarded
+ async def events(request):
+ row = await asyncio.to_thread(jobs.get, request.match_info['id'])
+ stream = web.StreamResponse(headers={'Content-Type': 'text/event-stream', 'Cache-Control': 'no-store'})
+ await stream.prepare(request)
+ last = None
+ while True:
+ view = await asyncio.to_thread(jobs.view, row, detail=False)
+ text = json.dumps(view, ensure_ascii=False, sort_keys=True)
+ if text != last:
+ await stream.write(('event: %s\ndata: %s\n\n' % (
+ 'done' if row['status'] in DONE else 'progress', text)).encode())
+ last = text
+ if row['status'] in DONE:
+ break
+ await asyncio.sleep(.5)
+ return stream
+
+ @routes.post(PREFIX + '/sessions')
+ @guarded
+ async def session_create(request):
+ by = session_caller(request)
+ value = await body(request)
+ return reply(await asyncio.to_thread(sessions.create, title=value.get('title'),
+ client=session_client(request, by), by=by), 201)
+
+ @routes.get(PREFIX + '/sessions')
+ @guarded
+ async def session_list(request):
+ session_caller(request)
+ return reply(await asyncio.to_thread(sessions.list, **request[query_key]))
+
+ @routes.get(PREFIX + '/sessions/{id}')
+ @guarded
+ async def session_get(request):
+ session_caller(request)
+ return reply(await asyncio.to_thread(sessions.get, request.match_info['id']))
+
+ # No route options: ComfyUI copies every route under /api as route(method, path)(handler) and
+ # cannot pass them on. HEAD is answered by guarded without opening the stream.
+ @routes.get(PREFIX + '/sessions/{id}/events')
+ @guarded
+ async def session_events(request):
+ session_caller(request)
+ sid = request.match_info['id']
+ query = request[query_key]
+ after, limit = query['after'], query['limit']
+ await asyncio.to_thread(sessions.get, sid)
+ if 'text/event-stream' not in request.headers.get('Accept', '').lower():
+ if query['wait']:
+ rows = (await sessions.wait(sid, after=after, seconds=query['wait']))[:limit]
+ else:
+ rows = await asyncio.to_thread(sessions.events, sid, after=after, limit=limit)
+ meta = await asyncio.to_thread(sessions.get, sid)
+ return reply(dict(events=rows, last_seq=meta['last_seq'], stopped=meta['stopped']))
+ cursor = request.headers.get('Last-Event-ID')
+ if cursor is not None:
+ if len(request.headers.getall('Last-Event-ID')) != 1 or not cursor.isascii() or not cursor.isdecimal():
+ raise specs.SpecError(contract.diagnostic('/headers/Last-Event-ID', 'a nonnegative integer', None))
+ after = int(cursor)
+ stream = web.StreamResponse(headers={'Content-Type': 'text/event-stream', 'Cache-Control': 'no-store'})
+ async def disconnected():
+ while request.transport is not None and not request.transport.is_closing():
+ await asyncio.sleep(.25)
+ disconnect = asyncio.create_task(disconnected())
+ pending = None
+ try:
+ await stream.prepare(request)
+ while request.transport is not None and not request.transport.is_closing():
+ pending = asyncio.create_task(sessions.wait(sid, after=after, seconds=15))
+ ready, _ = await asyncio.wait((disconnect, pending), return_when=asyncio.FIRST_COMPLETED)
+ if disconnect in ready:
+ break
+ rows = pending.result()
+ if not rows:
+ await stream.write(b': keepalive\n\n')
+ continue
+ for row in rows:
+ payload = json.dumps(row, ensure_ascii=False, separators=(',', ':'))
+ await stream.write(('id: %d\nevent: %s\ndata: %s\n\n' %
+ (row['seq'], row['type'], payload)).encode('utf-8'))
+ after = row['seq']
+ except (ConnectionError, asyncio.CancelledError):
+ pass
+ finally:
+ tasks = [task for task in (disconnect, pending) if task is not None]
+ for task in tasks:
+ task.cancel()
+ await asyncio.gather(*tasks, return_exceptions=True)
+ return stream
+
+ async def stop_session(sid):
+ row = await asyncio.to_thread(sessions.append, sid, dict(type='control', action='stopped'), by='user')
+ for callback in tuple(sessions.on_stop):
+ result = callback(sid)
+ if isawaitable(result):
+ await result
+ return row
+
+ @routes.post(PREFIX + '/sessions/{id}/events')
+ @guarded
+ async def session_post(request):
+ by = session_caller(request)
+ sid = request.match_info['id']
+ value = await body(request)
+ if value['type'] == 'step' or value['type'] == 'confirm' and (by != 'user' or value['state'] == 'asked'):
+ raise JobError('forbidden', 'This event is written by the server or user only')
+ if value['type'] == 'control' and value['action'] != 'renamed':
+ if by != 'user':
+ raise JobError('forbidden', 'Only the page user may stop or continue')
+ if value['action'] == 'stopped':
+ return reply(await stop_session(sid), 201)
+ return reply(await asyncio.to_thread(sessions.append, sid, value,
+ by=by, client=session_client(request, by)), 201)
+
+ @routes.get(PREFIX + '/confirmations')
+ @guarded
+ async def confirmations_get(request):
+ session_caller(request)
+ return reply(await asyncio.to_thread(confirmations.settings))
+
+ @routes.put(PREFIX + '/confirmations')
+ @guarded
+ async def confirmations_put(request):
+ if session_caller(request) != 'user':
+ raise JobError('forbidden', 'Only the page user may change confirmations')
+ return reply(await asyncio.to_thread(confirmations.update, await body(request)))
+
+ @routes.post(PREFIX + '/sessions/{id}/stop')
+ @guarded
+ async def session_stop(request):
+ if session_caller(request) != 'user':
+ raise JobError('forbidden', 'Only the page user may stop')
+ return reply(await stop_session(request.match_info['id']))
+
+ @routes.post(PREFIX + '/sessions/{id}/resume')
+ @guarded
+ async def session_resume(request):
+ if session_caller(request) != 'user':
+ raise JobError('forbidden', 'Only the page user may continue')
+ return reply(await asyncio.to_thread(sessions.append, request.match_info['id'],
+ dict(type='control', action='resumed'), by='user'))
+
+ def publish_media(work, suffix):
+ from . import media
+ with tempfile.TemporaryDirectory(prefix='.agent-stage-', dir=port.input_root) as temporary:
+ stage = Path(temporary)
+ target = stage / ('media' + suffix)
+ made = work(target) or {}
+ info = media.inspect(target)
+ folder = 'freevideo/agent/assets/' + uuid.uuid4().hex
+ staged = stage.relative_to(port.input_root).as_posix()
+ def relocate(value):
+ if isinstance(value, str) and value.startswith(staged + '/'):
+ return folder + value[len(staged):]
+ if isinstance(value, dict):
+ return {k: relocate(v) for k, v in value.items()}
+ if isinstance(value, list):
+ return [relocate(v) for v in value]
+ return value
+ made = relocate(made)
+ for document in stage.glob('*.edit.json'):
+ document.write_text(json.dumps(relocate(json.loads(document.read_text(encoding='utf-8')))), encoding='utf-8')
+ destination = port.input_path(folder, create=True)
+ os.replace(stage, destination)
+ relative = folder + '/' + target.name
+ info.pop('path', None)
+ made.pop('path', None)
+ return assets.public(dict(made, **info, file=relative, view=assets.view(relative)))
+
+ @routes.post(PREFIX + '/media')
+ @guarded
+ async def upload(request):
+ from ..comfy_assets import media_kind
+ from . import media
+ with tempfile.TemporaryDirectory(prefix='.agent-upload-', dir=port.input_root) as temporary:
+ if request.content_type == 'multipart/form-data':
+ reader = await request.multipart()
+ part = await reader.next()
+ if part is None or part.name != 'file' or not part.filename:
+ raise JobError('invalid_media', 'A file part is required')
+ name = part.filename
+ contract.validate(contracts['POST', '/media']['body']['properties']['name'], name)
+ media_kind(name)
+ target = Path(temporary) / name
+ size = 0
+ with target.open('xb') as output:
+ while True:
+ chunk = await part.read_chunk(size=256 * 1024)
+ if not chunk:
+ break
+ size += len(chunk)
+ if size > contract.MAX_UPLOAD_BYTES:
+ raise JobError('too_large', 'Upload exceeds limit', limit_bytes=contract.MAX_UPLOAD_BYTES)
+ output.write(chunk)
+ if await reader.next() is not None or size == 0:
+ raise JobError('invalid_media', 'Supply one nonempty file')
+ else:
+ value = await body(request)
+ name = value['name']
+ media_kind(name)
+ try:
+ data = base64.b64decode(value['data_base64'], validate=True)
+ except (binascii.Error, ValueError):
+ raise JobError('invalid_media', 'Invalid base64') from None
+ if len(data) > contract.MAX_UPLOAD_BYTES:
+ raise JobError('too_large', 'Upload exceeds limit', limit_bytes=contract.MAX_UPLOAD_BYTES)
+ if not data:
+ raise JobError('invalid_media', 'Empty file')
+ target = Path(temporary) / name
+ target.write_bytes(data)
+ async with upload_decoders:
+ try:
+ info, suffix = await asyncio.to_thread(media.validate_upload, target)
+ except (OSError, ValueError, SyntaxError):
+ raise JobError('invalid_media', 'Media cannot be decoded within the upload limits') from None
+ info.pop('path', None)
+ def digest():
+ with target.open('rb') as stream:
+ return hashlib.file_digest(stream, 'sha256').hexdigest()
+ identity = await asyncio.to_thread(digest)
+ relative = 'freevideo/agent/assets/' + identity + suffix
+ out = port.input_path(relative, create=True)
+ os.replace(target, out)
+ info['name'] = identity + suffix
+ return reply(dict(**assets.view(relative), **info), 201)
+
+ @routes.get(PREFIX + '/media/{kind}/{file:.+}/file')
+ @guarded
+ async def media_file(request):
+ from ..comfy_assets import media_kind
+ kind, relative = request.match_info['kind'], request.match_info['file']
+ contract.validate(contract.FILE, relative)
+ if kind not in ('input', 'output'):
+ raise JobError('not_found', 'No such media kind')
+ media_kind(relative)
+ def resolve():
+ root = port.input_root if kind == 'input' else port.output_root
+ path = root / relative
+ # Refuse symlinks even if they point back inside the asset root.
+ if any(p.is_symlink() for p in (path, *path.parents) if p != root and p.is_relative_to(root)):
+ raise JobError('not_found', 'Media is unavailable')
+ path = port.input_path(relative) if kind == 'input' else port.output_path(relative)
+ if not path.is_file() or not path.stat().st_size:
+ raise JobError('not_found', 'Media is unavailable')
+ if request.headers.get('Range'):
+ try:
+ selected = request.http_range
+ if selected.start is not None and selected.start >= path.stat().st_size:
+ raise ValueError
+ except ValueError:
+ raise JobError('invalid_range', 'Invalid byte range') from None
+ return path
+ path = await asyncio.to_thread(resolve)
+ return web.FileResponse(path, headers={'Cache-Control': 'private, no-store',
+ 'Content-Disposition': 'attachment', 'X-Content-Type-Options': 'nosniff'})
+
+ @routes.post(PREFIX + '/media/inspect')
+ @guarded
+ async def inspect(request):
+ from . import media
+ value = await body(request)
+ item = specs.media_item(value['source'], '/source')
+ def read():
+ path = source_path(item)
+ info = media.inspect(path)
+ view = assets.view(item['file']) if 'file' in item else library_view(port, port.output_relative(path))
+ return assets.public(dict(info, **view))
+ return reply(await asyncio.to_thread(read))
+
+ def source_path(item):
+ if 'file' in item:
+ path = port.input_path(item['file'])
+ if not path.is_file():
+ raise KeyError(item['file'])
+ return path
+ return jobs.source_video(item)
+
+ @routes.post(PREFIX + '/media/frame')
+ @guarded
+ async def frame(request):
+ value = await body(request)
+ item = specs.media_item(value['source'], '/source')
+ at = value.get('at', item.get('frame', 'last'))
+ source = await asyncio.to_thread(source_path, item)
+ made = await asyncio.to_thread(publish_media, lambda out: port.extract_frame(source, out, at), '.png')
+ return reply(made, 201)
+
+ @routes.post(PREFIX + '/media/edit')
+ @guarded
+ async def edit(request):
+ value = await body(request)
+ item = specs.media_item(value['source'], '/source', image=True)
+ target = value.get('target')
+ def work(out):
+ source = item.get('file')
+ if not source:
+ extracted = out.with_name('source.png')
+ port.extract_frame(jobs.source_video(item), extracted, item['frame'])
+ source = extracted.relative_to(port.input_root).as_posix()
+ made = port.edit(source, value.get('recipe') or value.get('document'), out,
+ target=tuple(target) if target else None)
+ return dict(document=made['doc'])
+ return reply(await asyncio.to_thread(publish_media, work, '.png'), 201)
+
+ @routes.post(PREFIX + '/media/contact-sheet')
+ @guarded
+ async def sheet(request):
+ from . import media
+ value = await body(request)
+ item = specs.media_item(value.get('source'), '/source')
+ fields = contracts['POST', '/media/contact-sheet']['body']
+ value = contract.defaults(fields, value)
+ source = await asyncio.to_thread(source_path, item)
+ made = await asyncio.to_thread(publish_media, lambda out: media.contact_sheet(source, out,
+ count=value['count'], columns=value['columns']), '.jpg')
+ return reply(made, 201)
+
+ @routes.get(PREFIX + '/library')
+ @guarded
+ async def library_route(request):
+ return reply(await asyncio.to_thread(library, port, jobs, limit=int(request[query_key].get('limit', '24')),
+ before=request[query_key].get('before'), query=request[query_key].get('query'),
+ project=request[query_key].get('project')))
+
+ @routes.get(PREFIX + '/library/{day}/{run}')
+ @guarded
+ async def library_item(request):
+ def read():
+ identity = saved_identity(port, request.match_info['day'], request.match_info['run'])
+ try:
+ video = port.library_video(identity)
+ except (JobError, OSError, ValueError):
+ raise JobError('not_found', 'Library item does not exist') from None
+ folder = video.parent
+ from ..comfy_library import _report
+ from ..comfy_assets import output_summary
+ report = _report(video)
+ summary = output_summary(report, Path(port.output_relative(video)))
+ prompt = (folder / 'prompt.txt').read_text(encoding='utf-8') if (folder / 'prompt.txt').is_file() else None
+ return dict(id=identity, video=library_view(port, port.output_relative(video)), prompt=prompt,
+ seed=report.get('seed'), geometry={k: v for k, v in (summary.get('geometry') or {}).items()
+ if k in ('width', 'height', 'frames', 'seconds', 'fps')},
+ sampling_plan=summary.get('sampling_plan'), preview=summary.get('preview'),
+ request_seconds=summary.get('request_seconds'), sample_seconds=summary.get('sample_seconds'))
+ return reply(await asyncio.to_thread(read))
+
+ @routes.get(PREFIX + '/library/{day}/{run}/file')
+ @guarded
+ async def library_file(request):
+ from ..comfy_library import video_download
+ def read():
+ identity = saved_identity(port, request.match_info['day'], request.match_info['run'])
+ try:
+ path, name = video_download(port.output_root, identity)
+ except (OSError, ValueError, TypeError):
+ return None
+ if request.headers.get('Range'):
+ try:
+ byte_range = request.http_range
+ size = path.stat().st_size
+ if byte_range.start is not None and byte_range.start >= size:
+ raise ValueError
+ except ValueError:
+ raise JobError('invalid_range', 'Invalid byte range') from None
+ return path, name
+ value = await asyncio.to_thread(read)
+ if value is None:
+ return problem('not_found', 'The saved video is unavailable.', 404, details=[], retryable=False,
+ next='GET /freevideo/agent/v1/library and select an existing video ID.')
+ path, name = value
+ return web.FileResponse(path, headers={'Content-Type': 'video/mp4',
+ 'Content-Disposition': 'attachment; filename="%s"' % name, 'Cache-Control': 'private, no-store'})
+
+ @routes.get(PREFIX + '/library/{day}/{run}/thumbnail')
+ @guarded
+ async def library_thumbnail(request):
+ from ..comfy_library import thumbnail
+ identity = await asyncio.to_thread(saved_identity, port, request.match_info['day'], request.match_info['run'])
+ async with thumbnails:
+ try:
+ data = await asyncio.to_thread(thumbnail, port.output_root, identity)
+ except Exception:
+ return problem('not_found', 'The saved thumbnail is unavailable.', 404, details=[], retryable=False,
+ next='GET /freevideo/agent/v1/library and select an existing video ID.')
+ return web.Response(body=data, content_type='image/jpeg', headers={'Cache-Control': 'private, no-store'})
+
+ @routes.get(PREFIX + '/inbox')
+ @guarded
+ async def inbox(request):
+ # The hook already attached this request to the caller's session; answer with its unread user words.
+ store, sid = work_sessions(), request.get('agent_session')
+ deadline = time.monotonic() + min(25., float(request[query_key].get('wait', '0') or 0))
+ while True:
+ if store is not None and sid is not None:
+ # Mark before reading so words arriving in between wake the wait below.
+ def read():
+ mark = store.get(sid)['last_seq']
+ return mark, store.unread(sid, request['agent_client'])
+ mark, pending = await asyncio.to_thread(read)
+ if pending:
+ return reply(dict(session=sid, inbox=pending[-20:]))
+ left = deadline - time.monotonic()
+ if left <= 0:
+ return reply(dict(session=sid, inbox=[]))
+ if store is None or sid is None:
+ await asyncio.sleep(min(left, 1.))
+ else:
+ await store.wait(sid, after=mark, seconds=left, by='user')
+
+ @routes.get(PREFIX + '/queue')
+ @guarded
+ async def queue(request):
+ def read():
+ running, pending = port.snapshot()
+ active = [jobs.view(row, detail=False) for row in jobs.list(status=list(ACTIVE), limit=200)]
+ return dict(running=len(running), pending=len(pending), vlm_busy=port.vlm_busy(), agent_jobs=active,
+ **jobs.queue_view())
+ return reply(await asyncio.to_thread(read))
+
+ def drama_handler(operation, *, local=False):
+ async def handler(request):
+ productions = jobs.productions
+ identity = request.match_info.get('id')
+ shot = request.match_info.get('shot')
+ if operation == 'list':
+ return reply(dict(productions=await asyncio.to_thread(productions.list, **request[query_key])))
+ if operation == 'get':
+ # Long waits are asynchronous: they hold no worker thread, so user controls never queue behind them.
+ return reply(await productions.get_async(identity, **request[query_key]))
+ if operation == 'sheet':
+ value = await asyncio.to_thread(productions.sheet, identity, shot, **request[query_key])
+ def picture(data):
+ return dict(mimeType='image/png' if data.startswith(b'\x89PNG') else 'image/jpeg',
+ data=base64.b64encode(data).decode('ascii'))
+ for row in value['takes']:
+ row['image'] = picture(row['image'])
+ if value['previous'] is not None:
+ value['previous'] = picture(value['previous'])
+ return reply(value)
+ value = dict(await body(request))
+ ref = value.pop('ref', None)
+ key = request.headers.get('Idempotency-Key')
+ if key is not None:
+ contract.validate(contract.REF, key)
+ if key and ref and key != ref:
+ raise JobError('idempotency_conflict', 'Conflicting keys')
+ ref = key or ref
+ client = request.headers.get('X-FreeVideo-Client', '')[:80] or None
+ # Credentials always identify an agent, even on the Studio route.
+ authenticated = bool(request.headers.get('Authorization') or request.headers.get('X-FreeVideo-Agent'))
+ by = 'user' if local and not authenticated else 'agent'
+ if operation == 'plan':
+ return reply(await asyncio.to_thread(productions.plan, value, local=False))
+ if operation == 'start':
+ return reply(await asyncio.to_thread(productions.start, value, by=by, ref=ref, local=False, client=client))
+ args = [identity] + ([shot] if shot else [])
+ return reply(await asyncio.to_thread(getattr(productions, operation), *args, by=by, ref=ref, client=client, **value))
+ return guarded(handler)
+
+ for operation, (method, suffix, _) in contract.DRAMA_OPERATIONS.items():
+ getattr(routes, method.lower())(PREFIX + suffix)(drama_handler(operation))
+ for operation in ('pause', 'resume'):
+ routes.post('/freevideo/agent/drama/{id}/' + operation)(drama_handler(operation, local=True))
+
+ def cast_handler(operation, *, local=False):
+ async def handler(request):
+ cast = jobs.cast
+ identity = request.match_info.get('id')
+ if operation == 'list':
+ return reply(await asyncio.to_thread(cast.list, **request[query_key]))
+ if operation == 'get':
+ return reply(await asyncio.to_thread(cast.get, identity))
+ value = dict(await body(request))
+ ref = value.pop('ref', None)
+ key = request.headers.get('Idempotency-Key')
+ if key is not None:
+ contract.validate(contract.REF, key)
+ if key and ref and key != ref:
+ raise JobError('idempotency_conflict', 'Conflicting keys')
+ ref = key or ref
+ client = request.headers.get('X-FreeVideo-Client', '')[:80] or None
+ # The library page acts for the user; any credential identifies an agent.
+ authenticated = bool(request.headers.get('Authorization') or request.headers.get('X-FreeVideo-Agent'))
+ by = 'user' if local and not authenticated else 'agent'
+ if operation == 'create':
+ return reply(await asyncio.to_thread(cast.create, value, by=by, ref=ref, local=False, client=client), 201)
+ revision = request.headers.get('If-Match')
+ # HTTP callers never name local paths; only in-process callers may pass local=True.
+ options = dict(local=False) if operation == 'update' else {}
+ return reply(await asyncio.to_thread(getattr(cast, operation), identity, value, by=by, ref=ref,
+ revision=revision, client=client, **options), 201 if operation == 'generate' else 200)
+ return guarded(handler)
+
+ for operation, (method, suffix, _) in contract.CAST_OPERATIONS.items():
+ getattr(routes, method.lower())(PREFIX + suffix)(cast_handler(operation))
+ getattr(routes, method.lower())('/freevideo/agent' + suffix)(cast_handler(operation, local=True))
+
+ def project_view(value):
+ from urllib.parse import urlencode, urlsplit, parse_qs
+
+ def address(key, file):
+ return PREFIX + '/editor/sources/content?' + urlencode(dict(key=key, file=file))
+
+ for key, info in value.get('sources', {}).items():
+ for field in ('video', 'audio', 'thumbnail'):
+ if info.get(field):
+ info[field] = address(key, 'thumbnail' if field == 'thumbnail' else 'preview')
+ for item in value.get('items', []):
+ if not item.get('thumbnail'):
+ continue
+ parsed = urlsplit(item['thumbnail'])
+ query = parse_qs(parsed.query)
+ key = query.get('key', [None])[0]
+ if parsed.path == '/freevideo/library/thumbnail':
+ key = 'work:' + query['id'][0]
+ elif parsed.path == '/freevideo/editor/media':
+ key = 'import:' + query['id'][0]
+ item['thumbnail'] = address(key, 'thumbnail') if key else None
+ return value
+
+ def project_handler(operation):
+ async def handler(request):
+ projects = jobs.projects
+ identity = request.match_info.get('id')
+ if operation in ('list', 'get'):
+ args = [identity] if operation == 'get' else []
+ return reply(project_view(await asyncio.to_thread(getattr(projects, operation), *args)))
+ value = dict(await body(request))
+ ref = value.pop('ref', None)
+ key = request.headers.get('Idempotency-Key')
+ if key is not None:
+ contract.validate(contract.REF, key)
+ if key and ref and key != ref:
+ raise JobError('idempotency_conflict', 'Conflicting keys')
+ args = [] if operation == 'create' else [identity]
+ extra = dict(client=request.headers.get('X-FreeVideo-Client', '')[:80] or None)
+ if operation in ('generate', 'export'):
+ extra['jobs'] = jobs
+ if operation == 'generate':
+ def capability(size):
+ try:
+ return port.capability_snapshot({'width': str(size['width']), 'height': str(size['height'])})
+ except (ValueError, KeyError, TypeError):
+ return None
+ extra['capability'] = capability
+ result = await asyncio.to_thread(getattr(projects, operation), *args, value, ref=key or ref, **extra)
+ if operation in ('generate', 'export'):
+ await jobs.tick()
+ return reply(result, 201 if operation in ('create', 'generate', 'export') else 200)
+ return guarded(handler)
+
+ for operation, (method, suffix, _) in contract.PROJECT_OPERATIONS.items():
+ getattr(routes, method.lower())(PREFIX + suffix)(project_handler(operation))
+
+ def image_handler(operation):
+ async def handler(request):
+ images = jobs.images
+ identity = request.match_info.get('id')
+ if operation == 'get':
+ return reply(await asyncio.to_thread(images.get, identity))
+ value = dict(await body(request))
+ ref = value.pop('ref', None)
+ key = request.headers.get('Idempotency-Key')
+ if key is not None:
+ contract.validate(contract.REF, key)
+ if key and ref and key != ref:
+ raise JobError('idempotency_conflict', 'Conflicting keys')
+ args = [] if operation == 'create' else [identity]
+ extra = dict(client=request.headers.get('X-FreeVideo-Client', '')[:80] or None)
+ if operation == 'render':
+ extra['jobs'] = jobs
+ result = await asyncio.to_thread(getattr(images, operation), *args, value, ref=key or ref, **extra)
+ if operation == 'render':
+ await jobs.tick()
+ return reply(result, 201 if operation in ('create', 'render') else 200)
+ return guarded(handler)
+
+ for operation, (method, suffix, _) in contract.IMAGE_OPERATIONS.items():
+ getattr(routes, method.lower())(PREFIX + suffix)(image_handler(operation))
+
+ @routes.get(PREFIX + '/editor/sources/content')
+ @guarded
+ async def editor_source_content(request):
+ from .. import comfy_editor
+ query = request[query_key]
+ def resolve():
+ try:
+ path = (comfy_editor.thumbnail if query['file'] == 'thumbnail' else comfy_editor.media_path)(
+ jobs.projects.root, query['key'])
+ if not path.is_file() or not path.stat().st_size:
+ raise FileNotFoundError
+ except (OSError, ValueError, IndexError):
+ raise JobError('source_missing', 'The project source is unavailable.') from None
+ if request.headers.get('Range'):
+ try:
+ selected = request.http_range
+ if selected.start is not None and selected.start >= path.stat().st_size:
+ raise ValueError
+ except ValueError:
+ raise JobError('invalid_range', 'Invalid byte range') from None
+ return path
+ if query['file'] == 'thumbnail':
+ async with thumbnails:
+ path = await asyncio.to_thread(resolve)
+ else:
+ path = await asyncio.to_thread(resolve)
+ kind = 'image/jpeg' if query['file'] == 'thumbnail' else 'audio/mp4' if path.suffix == '.m4a' else 'video/mp4'
+ return web.FileResponse(path, headers={'Content-Type': kind, 'Cache-Control': 'private, no-store',
+ 'Content-Disposition': 'attachment', 'X-Content-Type-Options': 'nosniff'})
+
+ async def scheduler():
+ while True:
+ try:
+ await jobs.tick()
+ except Exception: # noqa: BLE001 - keep scheduling; each job records its own failure
+ import logging
+ logging.getLogger(__name__).exception('FreeVideo agent scheduler')
+ await asyncio.sleep(.5 if await asyncio.to_thread(jobs.active) else 2.)
+
+ try:
+ server._freevideo_agent_task = asyncio.get_event_loop().create_task(scheduler())
+ except RuntimeError:
+ pass
+ # Write the token and an endpoint file for local clients (MCP server, SDK, CLI).
+ try:
+ from ..comfy_bridge import installation_root
+ from comfy.cli_args import args
+ root = installation_root()
+ ensure_token(root)
+ listen = (args.listen or '127.0.0.1').split(',')[0]
+ host = '127.0.0.1' if listen in ('0.0.0.0', '') else '[::1]' if listen == '::' else listen
+ scheme = 'https' if getattr(args, 'tls_keyfile', None) else 'http'
+ endpoint = dict(url='%s://%s:%d' % (scheme, host if ':' not in host or host.startswith('[') else '[%s]' % host,
+ args.port), pid=os.getpid(), api=PREFIX, started_at=time.time())
+ path = token_path(root).with_name('endpoint.json')
+ path.write_text(json.dumps(endpoint), encoding='utf-8')
+ except Exception: # noqa: BLE001 - discovery is a convenience; the API works without it
+ pass
diff --git a/freevideo_engine/agent/schema.py b/freevideo_engine/agent/schema.py
new file mode 100644
index 0000000..f1068e4
--- /dev/null
+++ b/freevideo_engine/agent/schema.py
@@ -0,0 +1,1390 @@
+"""The sole request contract for runtime, OpenAPI, MCP and CLI (stdlib only).
+
+spec.py only normalizes validated values and derives geometry/dependencies.
+Transport-only arguments (local paths, output files, client waits) live here too.
+"""
+from copy import deepcopy
+import json
+import math
+import re
+
+from . import API_VERSION
+
+S = 'https://json-schema.org/draft/2020-12/schema'
+PREFIX = '/freevideo/agent/v1'
+QUALITY = {'light': (True, 8, 3), 'medium': (False, 12, 3), 'high': (False, 16, 3), 'max': (False, 20, 3)}
+ASPECTS = {'16:9': (16, 9), '9:16': (9, 16), '1:1': (1, 1), '4:3': (4, 3), '3:4': (3, 4),
+ '21:9': (21, 9), '2:3': (2, 3), '3:2': (3, 2)}
+MAX_UPLOAD_BYTES = 2 * 1024 ** 3
+MAX_JSON_UPLOAD_BYTES = 96 * 1024 ** 2
+MAX_BODY_BYTES = 1024 * 1024
+
+
+def obj(properties=None, required=(), **kw):
+ return dict(type='object', additionalProperties=False, properties=properties or {},
+ **({'required': list(required)} if required else {}), **kw)
+
+
+def string(limit=1024, **kw):
+ return dict(type='string', minLength=1, maxLength=limit, **({'pattern': r'^(?=[\s\S]*\S)[^\x00]*$'} if 'pattern' not in kw else {}), **kw)
+
+
+def number(low, high=None, *, integer=False, **kw):
+ return dict(type='integer' if integer else 'number', minimum=low,
+ **({'maximum': high} if high is not None else {}), **kw)
+
+
+def array(items, low=0, high=32, **kw):
+ return dict(type='array', items=items, minItems=low, maxItems=high, **kw)
+
+
+def enum(values, **kw):
+ return dict(type='string', enum=list(values), **kw)
+
+
+JOB = string(13, pattern=r'^j[0-9a-f]{12}$')
+SESSION = string(13, pattern=r'^s[0-9a-f]{12}$')
+PRODUCTION = string(13, pattern=r'^d[0-9a-f]{12}$')
+CAST = string(13, pattern=r'^c[0-9a-f]{12}$')
+PROJECT = string(34, pattern=r'^e-[0-9a-f]{32}$')
+CLIP = string(10, pattern=r'^c[1-9]\d{0,8}$')
+EDITOR_FRAME = number(0, 10**7, integer=True, description='Whole timeline frames at 24 fps.')
+EDITOR_SOURCE = string(1034, pattern=r'^(?:work:\d{4}-\d{2}-\d{2}/[0-9a-f]{32}|generated:(?!/)(?!.*(?:\\|:))(?!\.{1,2}/|.*/\.{1,2}/)(?!\.editor/|.*/\.editor/)(?!.*//)[^\x00-\x1f]+\.[mM][pP]4|import:[A-Za-z0-9_-]{1,80})$')
+SAVED = string(43, pattern=r'^\d{4}-\d{2}-\d{2}/[0-9a-f]{32}$')
+SLUG = string(64, pattern=r'^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$')
+REF = string(128, pattern=r'^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$',
+ description='Idempotency key; reuse only with the same request content. Batch row refs also name dependencies.')
+FILE = string(1024, pattern=r'^(?!/)(?!.*(?:\\|:))(?!.*(?:^|/)\.\.(?:/|$)).+$')
+FRAME = {'oneOf': [enum(('first', 'last')), number(0)]}
+WAIT = number(0, default=0, description='x-clamp caps accepted wait values at 25 seconds without rejecting larger values.', **{'x-clamp': 25})
+CLIENT_WAIT = number(0, 25, default=25)
+EMPTY = obj()
+
+
+def nullable(rule):
+ return {'anyOf': [rule, {'type': 'null'}]}
+
+
+def pointer(key):
+ return str(key).replace('~', '~0').replace('/', '~1')
+
+
+def edit_recipe():
+ from .edit import describe, MAX_OPERATIONS
+ operations = []
+ required = {'rotate': ['degrees'], 'fit': ['width', 'height'], 'overlay': ['image'], 'text': ['text']}
+ for name, description in describe()['operations'].items():
+ props = {k: {a: b for a, b in rule.items() if a != 'about'} for k, rule in description['keys'].items()}
+ props['op'] = {'const': name}
+ if name == 'overlay':
+ props['image'] = FILE
+ rules = []
+ if name in ('pad', 'extend', 'overlay', 'crop'):
+ first, other = (('to',), ('left', 'top', 'right', 'bottom')) if name in ('pad', 'extend') else (
+ (('scale',), ('width', 'height')) if name == 'overlay' else (('x', 'y', 'width', 'height'), ('anchor', 'zoom')))
+ rules.append({'if': {'anyOf': [{'required': [k]} for k in first]},
+ 'then': {'not': {'anyOf': [{'required': [k]} for k in other]}}})
+ if name == 'shape':
+ props['from'] = props['to'] = array({'type': 'number'}, 2, 2)
+ rules.append({'if': {'required': ['type'], 'properties': {'type': {'const': 'line'}}},
+ 'then': {'required': ['from', 'to']}, 'else': {'required': ['width', 'height']}})
+ operations.append(obj(props, ['op'] + required.get(name, []), **({'allOf': rules} if rules else {})))
+ return obj({'operations': array({'oneOf': operations}, 1, MAX_OPERATIONS)}, ('operations',),
+ description='x-editor-recipe uses the shared CSS colour/ratio parsers. Source geometry and layer references also require editor preflight.',
+ **{'x-editor-recipe': True})
+
+
+def edit_document():
+ return {'type': 'object', 'required': ['version', 'layers'], 'properties': {'version': {'const': 2}}, 'description': 'Editor document version 2; x-editor-document uses the renderer pure document validator (geometry and layer relationships).',
+ 'x-editor-document': True}
+
+
+def media(image=False, *, local=False, clip=False, video=False):
+ properties = dict(file=FILE, from_job=JOB, library=SAVED, frame=FRAME,
+ edit={'oneOf': [edit_recipe(), edit_document()]}, label=string(80))
+ if local:
+ properties['path'] = string(4096)
+ if clip:
+ properties.pop('frame')
+ properties.pop('edit')
+ properties.update(start=number(0, 3600), end=dict(number(0, 3600), type=['number', 'null']))
+ if video:
+ properties.pop('frame')
+ properties.pop('edit')
+ properties['frames'] = number(2, 12, integer=True, default=6)
+ sources = [k for k in ('file', 'path', 'from_job', 'library') if k in properties]
+ rules = [dict(oneOf=[{'required': [key]} for key in sources])]
+ if not clip and not video:
+ rules.append({'if': {'anyOf': [{'required': [k]} for k in ('file', 'path')]},
+ 'then': {'not': {'required': ['frame']}}})
+ if image:
+ rules.append({'if': {'anyOf': [{'required': [k]} for k in ('from_job', 'library')]},
+ 'then': {'required': ['frame']}})
+ return {'oneOf': [FILE, obj(properties, allOf=rules)], 'x-media': dict(image=image, clip=clip, video=video),
+ 'description': 'Exactly one source. x-media additionally checks clip end > start, a comparison JSON Schema cannot express.'}
+
+
+def common():
+ return dict(label=string(120), project=SLUG, metadata={'x-json-bytes': 16 * 1024, 'description': 'x-json-bytes limits serialized finite JSON to 16384 bytes, which JSON Schema cannot measure.'},
+ after=array(JOB), ref=REF)
+
+
+def generation_media(*, local=False, enhance=False):
+ return obj({'first': nullable(media(True, local=local)), 'last': nullable(media(True, local=local)),
+ 'references': nullable(array(media(enhance, local=local), high=8 if enhance else 32))},
+ allOf=[{'if': {'required': ['references'], 'properties': {'references': {'type': 'array', 'minItems': 1}}},
+ 'then': {'properties': {'first': {'type': 'null'}, 'last': {'type': 'null'}}}}])
+
+
+def generate(*, local=False):
+ return obj(dict(kind={'const': 'generate', 'type': 'string', 'default': 'generate'},
+ prompt={'oneOf': [string(20000), obj({'from_job': JOB}, ('from_job',))]},
+ width=number(256, 4096, integer=True, multipleOf=32, default=1344),
+ height=number(256, 4096, integer=True, multipleOf=32, default=768),
+ aspect=string(7, pattern=r'^[1-9][0-9]{0,2}:[1-9][0-9]{0,2}$', examples=sorted(ASPECTS)),
+ megapixels=number(.1, 16, default=.98), seconds=number(1.625, 60, default=10),
+ seed=dict(number(0, 2**53 - 1, integer=True), type=['integer', 'null'], default=None),
+ quality=enum(QUALITY, default='light'),
+ sampling=obj(dict(two_pass={'type': 'boolean'}, base_steps=number(1, 32, integer=True),
+ refine_steps=number(1, 31, integer=True))),
+ media=nullable(generation_media(local=local)),
+ loras=array({'oneOf': [string(512, pattern=r'^.+\.[sS][aA][fF][eE][tT][eE][nN][sS][oO][rR][sS]$'),
+ obj(dict(name=string(512, pattern=r'^.+\.[sS][aA][fF][eE][tT][eE][nN][sS][oO][rR][sS]$'),
+ strength=number(-4, 4, default=1)), ('name',))]}, default=[]),
+ preview={'type': 'boolean', 'default': False},
+ refine_from=nullable({'oneOf': [JOB, SAVED]}), force_regenerate={'type': 'boolean', 'default': False},
+ continue_from={'oneOf': [obj({'from_job': JOB}, ('from_job',)), obj({'library': SAVED}, ('library',))]},
+ takes=number(1, 8, integer=True, default=1), **common()),
+ allOf=[{'if': {'required': ['refine_from'], 'properties': {'refine_from': {'type': 'string'}}},
+ 'then': {'properties': {k: False for k in ('prompt', 'width', 'height', 'aspect', 'megapixels',
+ 'seconds', 'seed', 'quality', 'sampling', 'media', 'loras', 'preview', 'continue_from')}},
+ 'else': {'required': ['prompt']}},
+ {'if': {'anyOf': [{'required': [k]} for k in ('aspect', 'megapixels')]},
+ 'then': {'not': {'anyOf': [{'required': [k]} for k in ('width', 'height')]}}},
+ {'if': {'if': {'required': ['sampling'], 'properties': {'sampling': {'required': ['two_pass']}}},
+ 'then': {'properties': {'sampling': {'properties': {'two_pass': {'const': False}}}}},
+ 'else': {'required': ['quality'], 'properties': {'quality': {'not': {'const': 'light'}}}}},
+ 'then': {'properties': {'preview': {'const': False}}}}],
+ description='x-job-kind selects normalization and checks derived geometry and sampling step comparisons; these calculations are not JSON Schema constraints.',
+ **{'x-job-kind': 'generate'})
+
+
+def assemble(*, local=False):
+ return obj(dict(kind={'const': 'assemble', 'type': 'string'},
+ clips=array({'anyOf': [JOB, SAVED, media(local=local, clip=True)]}, 1, 200),
+ transition=enum(('cut', 'crossfade'), default='cut'), transition_seconds=number(.04, 5, default=.5),
+ width=nullable(number(64, 4096, integer=True, multipleOf=2)), height=nullable(number(64, 4096, integer=True, multipleOf=2)),
+ audio={'type': 'boolean', 'default': True}, name=SLUG, **common()), ('kind', 'clips'),
+ **{'x-job-kind': 'assemble'})
+
+
+def vlm(*, local=False):
+ question = {'oneOf': [string(8000), obj(dict(text=string(8000),
+ images=array(media(True, local=local), high=16), video=nullable(media(local=local, video=True))), ('text',))]}
+ return obj(dict(kind={'const': 'vlm', 'type': 'string'},
+ questions={'oneOf': [question, array(question, 1, 8)]}, format=enum(('text', 'json'), default='text'),
+ max_tokens=number(16, 1500, integer=True, default=600), system=string(4000), **common()),
+ ('kind', 'questions'), description='x-job-kind also checks the sum of images and sampled video frames across questions (at most 24).', **{'x-job-kind': 'vlm'})
+
+
+def enhance(*, local=False):
+ return obj(dict(kind={'const': 'enhance', 'type': 'string'}, text=string(12000),
+ seconds=number(1, 60, default=10), media=nullable(generation_media(local=local, enhance=True)), **common()),
+ ('kind', 'text'), **{'x-job-kind': 'enhance'})
+
+
+def export(*, local=False):
+ return obj(dict(kind={'const': 'export', 'type': 'string'},
+ editor_project=string(34, pattern=r'^e-[0-9a-f]{32}$', description='The editing project to render (GET /projects).'),
+ revision=number(1, 2**53 - 1, integer=True, description='The saved revision you read; a later save fails the job with project_changed.'),
+ **common()), ('kind', 'editor_project', 'revision'),
+ description='Render one saved revision of an editing project to an MP4 in the saved videos, in turn with the page\'s exports.',
+ **{'x-job-kind': 'export'})
+
+
+def image_edit(*, local=False):
+ return obj(dict(kind={'const': 'image_edit', 'type': 'string'},
+ image=dict(IMAGE, description='The image session to render (POST /images).'),
+ revision=number(1, 2**53 - 1, integer=True, description='The saved revision you read; a later save fails the job with image_changed.'),
+ **common()), ('kind', 'image', 'revision'),
+ description='Render one saved revision of an image session to a PNG input file.',
+ **{'x-job-kind': 'image_edit'})
+
+
+KINDS = dict(generate=generate, assemble=assemble, vlm=vlm, enhance=enhance, export=export, image_edit=image_edit)
+
+
+def job_schema(*, local=False, refs=False):
+ value = {'oneOf': [f(local=local) for f in KINDS.values()], 'x-discriminator': 'kind',
+ 'description': 'x-discriminator selects field diagnostics by kind; all accepted branches use standard oneOf.'}
+ return batch_references(value) if refs else value
+
+
+def batch_references(value):
+ if value == JOB:
+ return {'anyOf': [JOB, string(129, pattern=r'^@[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$')]}
+ if isinstance(value, dict):
+ return {k: batch_references(v) for k, v in value.items()}
+ if isinstance(value, list):
+ return [batch_references(v) for v in value]
+ return value
+
+
+def batch_schema(*, local=False):
+ return obj(dict(jobs=array(job_schema(local=local, refs=True), 1, 64), ref=REF), ('jobs',), description='x-batch additionally checks earlier-row references and at most 64 jobs after takes expansion.', **{'x-batch': True})
+
+
+def contracts(*, local=False):
+ """Every registered route, including the UI control plane, has a contract."""
+ def route(summary, body=None, query=None, **kw):
+ return dict(summary=summary, body=body, query=query or EMPTY, **kw)
+ job = job_schema(local=local)
+ source = {'source': media(local=local)}
+ routes = {
+ ('GET', ''): route('Read available features, readiness and queue'),
+ ('GET', '/guide'): route('Read the prompt and API guide'),
+ ('GET', '/schema'): route('Read job schemas'),
+ ('GET', '/openapi.json'): route('Read the API contract'),
+ ('GET', '/capabilities'): route('Read device capabilities', query=obj(dict(
+ aspect=dict(generate()['properties']['aspect'], default='16:9'),
+ width={k: v for k, v in generate()['properties']['width'].items() if k != 'default'},
+ height={k: v for k, v in generate()['properties']['height'].items() if k != 'default'}, task=enum(('t2va', 'i2va', 'l2va', 'fl2va', 'ref2va'), default='t2va'),
+ adapters=number(0, 1, integer=True, default=0), references=string(16384)))),
+ ('POST', '/plan'): route('Validate and plan a generation', body=job),
+ ('POST', '/jobs'): route('Submit generation, prompt enhancement, visual questions or clip assembly',
+ body={'oneOf': [job, batch_schema(local=local)], 'x-submission': True, 'description': 'x-submission selects diagnostics for the single job or batch branch.'}, status=201, idempotent=True),
+ ('GET', '/jobs'): route('List jobs', query=obj(dict(status=string(128,
+ pattern=r'^(waiting|queued|running|cancelling|succeeded|failed|cancelled|interrupted)(,(waiting|queued|running|cancelling|succeeded|failed|cancelled|interrupted))*$'),
+ project=SLUG, kind=enum(KINDS), limit=number(1, 200, integer=True, default=50)))),
+ ('GET', '/jobs/{id}'): route('Read job progress and result', query=obj({'wait': WAIT})),
+ ('GET', '/jobs/{id}/events'): route('Watch job progress'),
+ ('POST', '/jobs/{id}/cancel'): route('Cancel a job', body=EMPTY, optional_body=True),
+ ('POST', '/jobs/{id}/resume'): route('Resume unfinished generation blocks', body=obj({'ref': REF}),
+ optional_body=True, idempotent=True),
+ ('POST', '/media'): route('Upload image, video or audio content',
+ body=obj(dict(name=string(255, pattern=r'^[^/\\:\x00]+$'), data_base64=string(MAX_JSON_UPLOAD_BYTES)),
+ ('name', 'data_base64')), status=201, multipart=True),
+ ('GET', '/media/{kind}/{file}/file'): route('Download uploaded or derived media'),
+ ('POST', '/media/inspect'): route('Inspect media', body=obj(source, ('source',))),
+ ('POST', '/media/frame'): route('Extract a video frame', body=obj(dict(source, at=dict(FRAME, default='last')), ('source',)), status=201),
+ ('POST', '/media/contact-sheet'): route('Review a grid of video frames', body=obj(dict(source,
+ count=number(2, 24, integer=True, default=8), columns=number(1, 8, integer=True, default=4)), ('source',)), status=201),
+ ('POST', '/media/edit'): route('Apply an image edit recipe', body=obj(dict(source=media(True, local=local),
+ recipe=edit_recipe(), document=edit_document(), target=array(number(16, 8192, integer=True), 2, 2)),
+ ('source',), oneOf=[{'required': ['recipe']}, {'required': ['document']}]), status=201),
+ ('GET', '/library'): route('Search saved videos', query=obj(dict(limit=number(1, 48, integer=True, default=24),
+ before=string(256), query=string(20000), project=SLUG))),
+ ('GET', '/library/{day}/{run}'): route('Read a saved video'),
+ ('GET', '/library/{day}/{run}/file'): route('Download a saved video'),
+ ('GET', '/library/{day}/{run}/thumbnail'): route('Read a saved thumbnail'),
+ ('GET', '/queue'): route('Read queue ownership and order'),
+ ('GET', '/editor/sources/content'): route(
+ 'Download project source media or a thumbnail. Use a source key from GET /projects/{id}.',
+ query=obj(dict(key=EDITOR_SOURCE, file=enum(('preview', 'thumbnail'))), ('key', 'file'))),
+ ('GET', '/connect'): route('Read installation-specific connection instructions',
+ query=obj({'format': enum(('text', 'json'), default='text')}), auth=False, local=True),
+ ('POST', '/connect/hello'): route('Report a connected client', body=obj(dict(client=string(80),
+ via=enum(('mcp', 'http'))), ('client', 'via'))),
+ ('GET', '/connect/status'): route('Read recent connection status', auth=False, local=True),
+ ('GET', '/inbox'): route("Wait at most 25 seconds for the user's words or answers in this session",
+ query=obj({'wait': WAIT})),
+ }
+ for name, (method, suffix, summary) in DRAMA_OPERATIONS.items():
+ shape = drama_schema(name)
+ path_fields = {k: PRODUCTION if k == 'id' else SLUG for k in re.findall(r'\{(.*?)\}', suffix)}
+ routes[method, suffix] = route(summary, path=obj(path_fields, path_fields), **({'query': shape} if method == 'GET' else
+ dict(body=shape, idempotent=True, optional_body=False)))
+ for name, (method, suffix, summary) in CAST_OPERATIONS.items():
+ shape = cast_schema(name, local=local)
+ extra = dict(path=obj({'id': CAST}, ('id',))) if '{id}' in suffix else {}
+ if method == 'GET':
+ extra['query'] = shape
+ else:
+ extra.update(body=shape, idempotent=True, optional_body=name in ('delete', 'generate'),
+ **({'status': 201} if name in ('create', 'generate') else {}))
+ routes[method, suffix] = route(summary, **extra)
+ # The library page edits cards as the user: no token, page session for writes.
+ routes[method, '/freevideo/agent' + suffix] = route('Studio cast library: ' + summary[0].lower() + summary[1:],
+ auth=False, local=True, **extra)
+ for name, (method, suffix, summary) in PROJECT_OPERATIONS.items():
+ shape = project_schema(name)
+ extra = dict(path=obj({'id': PROJECT}, ('id',))) if '{id}' in suffix else {}
+ if method == 'GET':
+ extra['query'] = shape
+ else:
+ extra.update(body=shape, idempotent=True, **({'status': 201} if name in ('create', 'generate', 'export') else {}))
+ routes[method, suffix] = route(summary, **extra)
+ for name, (method, suffix, summary) in IMAGE_OPERATIONS.items():
+ shape = image_schema(name)
+ extra = dict(path=obj({'id': IMAGE}, ('id',))) if '{id}' in suffix else {}
+ if method == 'GET':
+ extra['query'] = shape
+ else:
+ extra.update(body=shape, idempotent=True, **({'status': 201} if name in ('create', 'render') else {}))
+ routes[method, suffix] = route(summary, **extra)
+ for name in ('pause', 'resume'):
+ routes['POST', '/freevideo/agent/drama/{id}/' + name] = route(
+ 'Only the user may stop or continue a film (local Studio control)',
+ body=obj({'ref': REF}), path=obj({'id': PRODUCTION}, ('id',)), auth=False, local=True, idempotent=True)
+ for suffix, method, body in (('', 'GET', None), ('/session', 'GET', None), ('/activity', 'GET', None),
+ ('/activity/cancel', 'POST', obj({'id': JOB}, ('id',))), ('/connect', 'GET', None),
+ ('/connect/reset', 'POST', EMPTY)):
+ routes[(method, '/freevideo/agent' + suffix)] = route('Studio Agent controls', body=body, auth=False, local=True)
+ for name, (method, suffix, summary) in SESSION_OPERATIONS.items():
+ extra = dict(auth=False, page_or_token=True)
+ if '{id}' in suffix:
+ extra['path'] = obj({'id': SESSION}, ('id',))
+ if method == 'GET':
+ extra['query'] = session_schema(name)
+ else:
+ extra.update(body=session_schema(name), optional_body=name in ('stop', 'resume'),
+ **({'status': 201} if name in ('create', 'post') else {}))
+ routes[method, suffix] = route(summary, **extra)
+ routes['GET', '/confirmations'] = route('Read which agent operations wait for the user\'s approval.',
+ auth=False, page_or_token=True)
+ routes['PUT', '/confirmations'] = route('Only the page user may change which operations need approval.',
+ body=confirm_settings(), auth=False, page_or_token=True)
+ return routes
+
+
+DRAMA_OPERATIONS = {
+ 'plan': ('POST', '/drama/plan', 'For a film of several shots with takes to choose from (one video, however long, is one generate job): first preview a screenplay and its take counts without saving or submitting'),
+ 'start': ('POST', '/drama', 'After planning, start a durable film; review sheets and choose each shot'),
+ 'list': ('GET', '/drama', 'List films; status=active returns unfinished summaries'),
+ 'get': ('GET', '/drama/{id}', 'Read todo and revision; use since and wait=25. If paused, stop acting and long-wait until the user continues'),
+ 'sheet': ('GET', '/drama/{id}/shots/{shot}/sheet', 'After takes succeed, review their timed images and the previous chosen last frame'),
+ 'choose': ('POST', '/drama/{id}/shots/{shot}/choose', 'After reviewing the sheet, choose a take; only then can the next continuation shoot'),
+ 'reshoot': ('POST', '/drama/{id}/shots/{shot}/reshoot', 'Request corrected takes, then review the sheet and choose again'),
+ 'finish': ('POST', '/drama/{id}/finish', 'After every shot is chosen, accept assembly; get the film until its output is ready'),
+ 'cancel': ('POST', '/drama/{id}/cancel', 'Cancel unfinished takes; completed takes remain available'),
+ 'pause': ('POST', '/drama/{id}/pause', 'Only the user may stop a film; external agents receive not_allowed'),
+ 'resume': ('POST', '/drama/{id}/resume', 'Only the user may continue a film; external agents receive not_allowed'),
+}
+
+
+def drama_schema(name):
+ if name in ('plan', 'start'):
+ return obj(dict(screenplay={'type': 'object'}, takes_per_shot=number(1, 8, integer=True, default=1),
+ director=enum(('agent', 'builtin'), default='agent'), ref=REF), ('screenplay',))
+ if name == 'list':
+ return obj(dict(status=enum(('active', 'all'), default='all'), limit=number(1, 200, integer=True, default=50)))
+ if name == 'get':
+ return obj(dict(since=number(1, integer=True), wait=WAIT))
+ if name == 'sheet':
+ return obj(dict(frames=number(2, 24, integer=True, default=6)))
+ if name == 'choose':
+ return obj(dict(take=number(1, integer=True), reason=string(20000), cascade={'type': 'boolean'}, ref=REF), ('take',))
+ if name == 'reshoot':
+ changes = {key: dict(type='string', maxLength=20000) for key in ('action', 'camera', 'framing', 'prompt')}
+ changes.update(seconds=number(1.625, 60), lines=dict(type='array', items={'type': 'object'}))
+ return obj(dict(note=string(20000), changes=obj(changes), takes=number(1, 8, integer=True, default=1),
+ reason=string(20000), ref=REF))
+ return obj(dict(ref=REF, **({'transition': enum(('cut', 'crossfade'))} if name == 'finish' else {})))
+
+
+CAST_OPERATIONS = {
+ 'create': ('POST', '/cast', 'Create a character or setting card when no existing card fits'),
+ 'list': ('GET', '/cast', 'Search the cast library before casting; reuse a matching card'),
+ 'get': ('GET', '/cast/{id}', 'Read a card with its pictures, voice and revision'),
+ 'update': ('PATCH', '/cast/{id}', 'Change a card; send the revision you read; fields the user changed stay theirs'),
+ 'delete': ('DELETE', '/cast/{id}', 'Delete a card you made that no unfinished film uses; ask the user otherwise'),
+ 'generate': ('POST', '/cast/{id}/generate', 'Make reference pictures from the description when the user gave none; get the card after the job ends'),
+}
+
+
+def cast_schema(name, *, local=False):
+ """Card requests. Pictures and voices are media references; the server stores input copies."""
+ picture = media(True, local=local)
+ picture['oneOf'][1]['properties']['url'] = string(2048, description='Ignored; returned card media can be sent back unchanged.')
+ sound = media(local=local)
+ sound['x-media'] = dict(image=False, clip=False, video=False)
+ sound['oneOf'][1]['properties'] = {k: v for k, v in sound['oneOf'][1]['properties'].items() if k not in ('frame', 'edit')}
+ sound['oneOf'][1]['properties']['url'] = picture['oneOf'][1]['properties']['url']
+ sound['oneOf'][1]['allOf'] = sound['oneOf'][1]['allOf'][:1]
+ fields = dict(name=string(120), description=nullable(string(1000)),
+ images=array(obj(dict(media=picture, label=enum(LABELS)), ('media',)), 0, 6),
+ voice=nullable(obj(dict(media=sound, start=number(0, 3600, default=0), end=number(0, 3600)), ('media',))))
+ if name == 'create':
+ return obj(dict(kind=enum(('character', 'setting'), default='character'), **fields, ref=REF), ('name',))
+ if name == 'update':
+ return obj(dict(fields, revision=number(1, integer=True), ref=REF))
+ if name == 'delete':
+ return obj(dict(revision=number(1, integer=True), ref=REF))
+ if name == 'generate':
+ return obj(dict(face=dict(type='boolean', default=False, description='Also make one face close-up.'),
+ replace=dict(type='boolean', default=False,
+ description='Replace pictures the user did not add; default fills empty slots.'),
+ revision=number(1, integer=True), ref=REF))
+ if name == 'list':
+ return obj(dict(q=string(200), kind=enum(('character', 'setting')), origin=enum(('user', 'agent', 'builtin')),
+ production=PRODUCTION, limit=number(1, 200, integer=True, default=50)))
+ return EMPTY
+
+
+# Image editing sessions: the image editor's version 2 document (web/image_editor_engine.js),
+# changed with the page's commands (web/image_commands.js). Shapes follow the page's
+# own fields (lineHeight, shape width), not the /media/edit recipe's.
+IMAGE = string(34, pattern=r'^i-[0-9a-f]{32}$')
+LAYER_ID = string(128, pattern=r'^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$')
+COLOR = string(32, pattern=r'^(?:#[0-9A-Fa-f]{3,4}|#[0-9A-Fa-f]{6}|#[0-9A-Fa-f]{8}|transparent)$')
+IMAGE_SIDE = number(1, 8192, integer=True)
+IMAGE_MAX_PIXELS = 64 * 2**20
+IMAGE_LAYERS = 64
+BLEND_MODES = ('source-over', 'multiply', 'screen', 'overlay', 'soft-light', 'darken', 'lighten',
+ 'color-dodge', 'color-burn', 'difference')
+ADJUST_RANGES = dict({k: (-100, 100) for k in ('exposure', 'contrast', 'highlights', 'shadows', 'temperature', 'tint',
+ 'saturation', 'vibrance', 'vignette')}, hue=(-180, 180), sharpen=(0, 100), blur=(0, 100), noise=(0, 100))
+TEXT_FONTS = ('sans', 'serif', 'kai', 'mono')
+
+
+def _point(low=None, high=None):
+ value = number(-10**7 if low is None else low, 10**7 if high is None else high)
+ return array(value, 2, 2)
+
+
+def image_selection():
+ rect = dict(x=number(-10**7, 10**7), y=number(-10**7, 10**7), w=number(0, 10**7), h=number(0, 10**7))
+ mode = enum(('replace', 'add', 'subtract', 'intersect'), default='replace')
+ rect.update(feather=number(0, 2000))
+ parts = [obj(dict(shape={'const': 'rect'}, mode=mode, **rect), ('shape', 'x', 'y', 'w', 'h'), description='Rectangle in document pixels.'),
+ obj(dict(shape={'const': 'ellipse'}, mode=mode, **rect), ('shape', 'x', 'y', 'w', 'h'), description='Ellipse inside the rectangle, document pixels.'),
+ obj(dict(shape={'const': 'all'}, mode=mode), ('shape',), description='The whole document.'),
+ obj(dict(shape={'const': 'poly'}, mode=mode, feather=number(0, 2000), pts=array(_point(), 3, 8192)), ('shape', 'pts'), description='Polygon of [x, y] document pixels.'),
+ obj(dict(shape={'const': 'wand'}, mode=mode, layer=LAYER_ID, u=number(0, 1), v=number(0, 1),
+ tolerance=number(0, 255, default=0), contiguous={'type': 'boolean', 'default': True},
+ upto=number(0, 4096, integer=True), feather=number(0, 2000)),
+ ('shape', 'u', 'v'), description='Similar colours from a point of a layer, as fractions of the layer.')]
+ return obj(dict(parts=array({'oneOf': parts, 'x-discriminator': 'shape'}, 0, 64),
+ feather=number(0, 2000, default=0), invert={'type': 'boolean', 'default': False}), ('parts',))
+
+
+def image_pixel_op(*, mask=False):
+ common_fields = dict(id=string(128), selection=nullable(image_selection()), opacity=number(0, 1, default=1))
+ unit = _point(-1, 2)
+ tools = ('hide', 'reveal') if mask else ('paint', 'erase', 'clone', 'heal', 'blur', 'hide', 'reveal')
+ stroke = dict(tool=enum(tools), pts=array(unit, 1, 8192, description='[u, v] as fractions of the layer.'),
+ size=number(0, 1, exclusiveMinimum=0, description='Brush diameter as a fraction of the layer short side.'),
+ hardness=number(0, 1, default=1), strength=number(0, 1, default=.6), text={'type': 'boolean', 'default': False},
+ color=COLOR, offset=_point(-1, 1))
+ ops = [obj(dict(type={'const': 'stroke'}, **common_fields, **stroke), ('type', 'tool', 'pts', 'size')),
+ obj(dict(type={'const': 'fill'}, **common_fields, **({} if mask else dict(color=COLOR))), ('type',)),
+ obj(dict(type={'const': 'clear'}, **common_fields), ('type',)),
+ obj(dict(type={'const': 'gradient'}, **common_fields, **{'from': unit, 'to': unit},
+ shape=enum(('linear', 'radial'), default='linear'), c1=COLOR, c2=COLOR), ('type', 'from', 'to')),
+ obj(dict(type={'const': 'fromSelection'}, **common_fields, invert={'type': 'boolean', 'default': False}), ('type',))]
+ return {'oneOf': ops, 'x-discriminator': 'type'}
+
+
+def image_text():
+ return obj(dict(content=dict(type='string', maxLength=2000), size=number(6, 2000), color=COLOR,
+ font=enum(TEXT_FONTS, default='sans'), weight={'enum': [400, 700], 'type': 'integer', 'default': 700},
+ align=enum(('left', 'center', 'right'), default='left'), shadow={'type': 'boolean', 'default': True},
+ outline={'anyOf': [{'type': 'boolean'}, COLOR], 'default': False}, lineHeight=number(.5, 4, default=1.25)),
+ ('content', 'size'))
+
+
+def image_shape():
+ return obj(dict(type=enum(('rect', 'ellipse', 'line'), default='rect'), fill=nullable(COLOR), stroke=nullable(COLOR),
+ width=number(1, 400, default=6), radius=number(0, 2000, default=0),
+ **{'from': _point(), 'to': _point()}))
+
+
+def image_layer():
+ finite = number(-10**7, 10**7)
+ size = number(0, 10**7, exclusiveMinimum=0)
+ return obj(dict(
+ id=LAYER_ID, kind=enum(('image', 'paint', 'text', 'shape')), name=dict(type='string', maxLength=120),
+ visible={'type': 'boolean'}, locked={'type': 'boolean'}, cx=finite, cy=finite, w=size, h=size, nw=size, nh=size,
+ rotation=number(-360, 360), flipX={'type': 'boolean'}, flipY={'type': 'boolean'}, opacity=number(0, 1),
+ blend=enum(BLEND_MODES), src=nullable(FILE), ops=array(image_pixel_op(), 0, 4096),
+ mask=nullable(obj(dict(ops=array(image_pixel_op(mask=True), 0, 4096)), ('ops',))),
+ adjust=obj({k: number(low, high) for k, (low, high) in ADJUST_RANGES.items()}),
+ copyOf=nullable(obj(dict(layer=LAYER_ID, upto=number(0, 4096, integer=True), selection=nullable(image_selection())), ('layer',))),
+ text=image_text(), shape=image_shape()),
+ ('id', 'kind', 'cx', 'cy', 'w', 'h', 'nw', 'nh'))
+
+
+def image_document():
+ return obj(dict(
+ version={'const': 2, 'type': 'integer'}, width=IMAGE_SIDE, height=IMAGE_SIDE,
+ rotate={'enum': [0, 90, 180, 270], 'type': 'integer', 'default': 0},
+ flipX={'type': 'boolean', 'default': False}, flipY={'type': 'boolean', 'default': False},
+ extend=obj(dict(l=number(0, 20000), t=number(0, 20000), r=number(0, 20000), b=number(0, 20000), color=COLOR), ('l', 't', 'r', 'b')),
+ crop=obj(dict(x=number(-10**7, 10**7), y=number(-10**7, 10**7), w=number(0, 10**7, exclusiveMinimum=0),
+ h=number(0, 10**7, exclusiveMinimum=0)), ('x', 'y', 'w', 'h')),
+ ratio=string(32, default='original'), layers=array(image_layer(), 1, IMAGE_LAYERS), active=LAYER_ID),
+ ('version', 'width', 'height', 'extend', 'crop', 'layers'),
+ description='The image editor document (version 2); the page reopens it with every layer and step.',
+ **{'x-json-bytes': 8 * 2**20})
+
+
+IMAGE_OPERATIONS = {
+ 'create': ('POST', '/images', 'Open a picture for editing as the image editor page does. Send source; the session keeps a frozen copy and a document of layers.'),
+ 'get': ('GET', '/images/{id}', 'Read an image session: its document of layers, selection and revision. Read the revision and layer IDs before editing.'),
+ 'write': ('PUT', '/images/{id}', 'Replace the whole document. First get the session and send its revision; on image_changed recompute from error.image.'),
+ 'operations': ('POST', '/images/{id}/operations', 'Apply 1-64 image edits atomically and save once, with the page\'s own commands. First get revision and layer IDs; on image_changed recompute from error.image.'),
+ 'render': ('POST', '/images/{id}/render', 'Render one saved revision to a PNG input file. Wait for the returned job, then use its result file as a picture source.'),
+}
+IMAGE_TOOLS = dict(create='freevideo_image_create', get='freevideo_image_read', write='freevideo_image_write',
+ operations='freevideo_image_operations', render='freevideo_image_render')
+
+
+def image_operation_fields():
+ """The image commands (IDC): op -> (fields, required, description)."""
+ layer_id = LAYER_ID
+ update = obj(dict(name=dict(type='string', maxLength=120), visible={'type': 'boolean'}, locked={'type': 'boolean'},
+ cx=number(-10**7, 10**7), cy=number(-10**7, 10**7), w=number(0, 10**7, exclusiveMinimum=0),
+ h=number(0, 10**7, exclusiveMinimum=0), rotation=number(-360, 360), flipX={'type': 'boolean'},
+ flipY={'type': 'boolean'}, opacity=number(0, 1), blend=enum(BLEND_MODES)))
+ adjust = obj({k: number(low, high) for k, (low, high) in ADJUST_RANGES.items()})
+ text = dict(image_text(), required=[])
+ new_layer = obj(dict(kind=enum(('paint', 'image', 'text', 'shape')), name=dict(type='string', maxLength=120),
+ src=FILE, text=image_text(), position=_point(),
+ shape=dict(image_shape(), required=['from', 'to'])), ('kind',),
+ description=('A new layer above the active one; the server makes its id. image needs src (an input file), '
+ 'placed at the canvas centre; text needs text, at position (default the canvas centre); shape needs shape '
+ 'with from and to. Points are document pixels, as layer cx/cy and selections: the '
+ 'picture before turns and flips, its top left 0,0.'))
+ shape_patch = obj({k: v for k, v in image_shape()['properties'].items() if k in ('fill', 'stroke', 'width', 'radius')})
+ side = number(1, 20000, integer=True)
+ return {
+ 'document.replace': (dict(document={'type': 'object', 'description': 'A version 2 image document, checked as PUT /images/{id} checks it.'}), ('document',), 'Replace the whole document; every layer and picture is checked.'),
+ 'canvas.resize': (dict(width=side, height=side, keep={'type': 'boolean', 'default': True}), ('width', 'height'), 'Resize the image as Image size does: at most 200% and 64 megapixels; keep keeps the aspect ratio.'),
+ 'canvas.rotate': (dict(direction=enum(('cw', 'ccw'))), ('direction',), 'Turn the canvas a quarter turn; the crop turns with it.'),
+ 'canvas.flip': (dict(axis=enum(('horizontal', 'vertical'))), ('axis',), 'Mirror the canvas.'),
+ 'canvas.crop': (dict(crop=obj(dict(x=number(-10**7, 10**7), y=number(-10**7, 10**7), w=number(0, 10**7, exclusiveMinimum=0), h=number(0, 10**7, exclusiveMinimum=0)), ('x', 'y', 'w', 'h'))), ('crop',), 'Set the crop rectangle in canvas pixels.'),
+ 'canvas.extend': (dict(extend=obj(dict(l=number(0, 20000), t=number(0, 20000), r=number(0, 20000), b=number(0, 20000), color=COLOR), ('l', 't', 'r', 'b'))), ('extend',), 'Add borders around the canvas, as Canvas size does.'),
+ 'canvas.ratio': (dict(ratio=enum(('original', 'free', 'video', '16:9', '9:16', '1:1', '4:3', '3:4'))), ('ratio',), 'Set the crop ratio; video uses the session target.'),
+ 'canvas.pad_to_video': (dict(color=COLOR), (), 'Add borders so the picture fills the session target ratio.'),
+ 'layer.add': (dict(layer=new_layer), ('layer',), 'Add a layer above the active one and make it active.'),
+ 'layer.copy': (dict(layer_id=layer_id, name=dict(type='string', maxLength=120)), ('layer_id',), 'Duplicate a layer above itself.'),
+ 'layer.delete': (dict(layer_id=layer_id), ('layer_id',), 'Delete a layer. The base picture and locked layers cannot be deleted.'),
+ 'layer.reorder': (dict(layer_id=layer_id, index=number(1, IMAGE_LAYERS - 1, integer=True)), ('layer_id', 'index'), 'Move a layer to an index above the base picture (index 0).'),
+ 'layer.select': (dict(layer_id=layer_id), ('layer_id',), 'Make a layer active.'),
+ 'layer.update': (dict(layer_id=layer_id, patch=update), ('layer_id', 'patch'), 'Change name, visibility, lock, place, size, rotation, mirror, opacity or blend.'),
+ 'layer.adjust': (dict(layer_id=layer_id, patch=adjust), ('layer_id', 'patch'), 'Change colour adjustments of an image or paint layer.'),
+ 'layer.text': (dict(layer_id=layer_id, patch=text), ('layer_id', 'patch'), 'Change the text, font, size, colour or style of a text layer.'),
+ 'layer.shape': (dict(layer_id=layer_id, patch=shape_patch), ('layer_id', 'patch'), 'Change the fill, outline or corners of a shape layer.'),
+ 'selection.set': (dict(selection=image_selection()), ('selection',), 'Replace the selection; it is kept with the session, not in the document.'),
+ 'selection.add': (dict(part=image_selection()['properties']['parts']['items']), ('part',), 'Add one part to the selection with its mode, as the selection tools do.'),
+ 'selection.clear': ({}, (), 'Remove the selection.'),
+ 'selection.all': ({}, (), 'Select the whole document.'),
+ 'selection.invert': ({}, (), 'Invert the selection.'),
+ 'selection.copy_to_layer': (dict(layer_id=layer_id, name=dict(type='string', maxLength=120)), ('layer_id',), 'Copy the selected part of a layer (the whole layer without a selection) to a new layer; the selection is cleared.'),
+ 'selection.fill': (dict(layer_id=layer_id, color=COLOR), ('layer_id',), 'Fill the selection on an image or paint layer.'),
+ 'selection.erase': (dict(layer_id=layer_id), ('layer_id',), 'Clear the selection on an image or paint layer.'),
+ 'mask.set': (dict(layer_id=layer_id), ('layer_id',), 'Add a mask to the layer, from the selection when there is one (the selection is then cleared).'),
+ 'mask.delete': (dict(layer_id=layer_id), ('layer_id',), 'Remove the layer mask.'),
+ 'mask.from_selection': (dict(layer_id=layer_id), ('layer_id',), 'Replace the layer mask with one that hides what is outside the selection; the selection is cleared.'),
+ 'pixels.apply': (dict(layer_id=layer_id, pixel_op=image_pixel_op(), target=enum(('layer', 'mask'), default='layer')), ('layer_id', 'pixel_op'), 'Apply a brush stroke, fill, clear or gradient to an image or paint layer. With target mask, a paint stroke hides and an erase stroke shows the layer again, as painting on a mask does in the page.'),
+ 'undo': ({}, (), 'Undo one step; nothing happens when there is none.'),
+ 'redo': ({}, (), 'Redo one step; nothing happens when there is none.'),
+ 'reset': ({}, (), 'Go back to the document the session started with and clear the selection; this is one step and can be undone.'),
+ }
+
+
+def image_schema(name):
+ revision = number(1, integer=True, description='The saved revision you read; a later save returns image_changed.')
+ if name == 'create':
+ target = array(number(16, 8192, integer=True), 2, 2, description='[width, height] of the video the picture is for; ratio video uses it.')
+ return obj(dict(source=media(image=True), document=image_document(), target=target, ref=REF), ('source',))
+ if name == 'write':
+ return obj(dict(revision=revision, document=image_document(), ref=REF), ('revision', 'document'))
+ if name == 'render':
+ return obj(dict(revision=revision, ref=REF), ('revision',))
+ if name != 'operations':
+ return EMPTY
+ operations = [obj(dict(op={'const': op}, **props), ('op', *required), description=description)
+ for op, (props, required, description) in image_operation_fields().items()]
+ return obj(dict(revision=revision, operations=array({'oneOf': operations, 'x-discriminator': 'op'}, 1, 64), ref=REF),
+ ('revision', 'operations'), **{'x-json-bytes': 8 * 2**20})
+
+PROJECT_OPERATIONS = {
+ 'list': ('GET', '/projects', 'List editing projects shared with the editor page. Then get one to read its revision and clip IDs.'),
+ 'get': ('GET', '/projects/{id}', 'Read a timeline and authenticated source URLs. Read its revision and clip IDs before editing.'),
+ 'create': ('POST', '/projects', 'Create an editor timeline. Send a valid editor project with id null and revision 0.'),
+ 'write': ('PUT', '/projects/{id}', 'Replace a timeline. First get the project and preserve its id and revision; recompute from error.project on project_changed.'),
+ 'operations': ('POST', '/projects/{id}/operations', 'Apply 1-64 timeline edits atomically and save once. First get revision and clip IDs; on project_changed recompute from error.project, and on clip_busy wait for generation to finish.'),
+ 'generate': ('POST', '/projects/{id}/generate', 'Make new picture and sound for selected clips or a frame range, as the page Generate does. First get revision and clip IDs; the parts are reserved at once and fill in as the returned job finishes.'),
+ 'export': ('POST', '/projects/{id}/export', 'Render one saved revision to an MP4 in the saved videos. First get the revision; wait for the returned job, then read its result video.'),
+}
+PROJECT_TOOLS = dict(list='freevideo_projects', get='freevideo_project_read', create='freevideo_project_create',
+ write='freevideo_project_write', operations='freevideo_editor_operations',
+ generate='freevideo_project_generate', export='freevideo_export')
+
+SESSION_OPERATIONS = {
+ 'create': ('POST', '/sessions', 'Create a work conversation for messages and plans shared with the user.'),
+ 'list': ('GET', '/sessions', 'List work conversations, most recently updated first.'),
+ 'get': ('GET', '/sessions/{id}', 'Read conversation metadata and whether the user stopped it.'),
+ 'events': ('GET', '/sessions/{id}/events', 'Read events after a sequence number; wait up to 25 seconds or request an SSE stream.'),
+ 'post': ('POST', '/sessions/{id}/events', 'Append a message or plan for the user. Steps are recorded by the server.'),
+ 'stop': ('POST', '/sessions/{id}/stop', 'Only the page user may stop a work conversation.'),
+ 'resume': ('POST', '/sessions/{id}/resume', 'Only the page user may continue a work conversation.'),
+}
+SESSION_TOOLS = dict(create='freevideo_session_create', list='freevideo_sessions',
+ events='freevideo_session_events', post='freevideo_session_post')
+
+
+CONFIRM_DEFAULTS = dict(start=True, reshoot_seconds=300)
+
+
+def confirm_settings():
+ return obj(dict(start=dict(type='boolean', description='Ask before an agent starts shooting a film.'),
+ reshoot_seconds=nullable(number(0, 86400, description='Ask before an agent reshoot estimated to take '
+ 'at least this long; null never asks.'))))
+
+
+def session_metadata():
+ return obj(dict(session=SESSION, title=nullable(dict(type='string', maxLength=120)),
+ created_at=string(40), client=nullable(string(80)),
+ by=enum(('user', 'agent', 'builtin', 'system'))),
+ ('session', 'title', 'created_at', 'client', 'by'))
+
+
+def session_view():
+ fields = session_metadata()['properties'].copy()
+ fields.pop('session')
+ fields.pop('by')
+ fields.update(id=SESSION, updated_at=string(40), last_seq=number(0, integer=True), stopped={'type': 'boolean'})
+ return obj(fields, fields)
+
+
+def session_event(*, stored=False, agent_only=False):
+ """One event vocabulary for storage, HTTP, MCP and CLI; writers never supply envelope fields."""
+ text = dict(type='string', maxLength=8000)
+ variants = [obj(dict(type={'const': 'message'}, text=text), ('type', 'text')),
+ obj(dict(type={'const': 'plan'}, shots=array(obj(dict(text=text, seconds=number(0)), ('text',)),
+ 1, 20000), total_seconds=number(0)), ('type', 'shots'))]
+ if not agent_only:
+ from .errors import ERRORS
+ variants += [obj(dict(type={'const': 'step'}, id=string(12, pattern=r'^st[0-9a-f]{10}$'),
+ tool=string(200), summary=text, state=enum(('started', 'done', 'failed')),
+ refs=obj(dict(drama=PRODUCTION, shot=SLUG, take=number(1, integer=True), job=JOB,
+ project=PROJECT, clip=CLIP, image=IMAGE, cast=CAST)), thumbs=array(SAVED, 0, 20000),
+ why=text, error=enum(ERRORS)), ('type', 'tool', 'summary', 'state', *(['id'] if stored else []))),
+ obj(dict(type={'const': 'confirm'}, id=string(12, pattern=r'^cf[0-9a-f]{10}$'),
+ question=text, estimate_seconds=number(0), state=enum(('asked', 'approved', 'declined')),
+ action=enum(('start', 'reshoot')), refs=obj(dict(drama=PRODUCTION, shot=SLUG)),
+ digest=string(64, pattern=r'^[0-9a-f]{64}$')),
+ ('type', 'id', 'state'), **{'if': {'properties': {'state': {'const': 'asked'}}},
+ 'then': {'required': ['question']}}),
+ obj(dict(type={'const': 'control'}, action=enum(('stopped', 'resumed', 'renamed')),
+ title=dict(type='string', maxLength=120)), ('type', 'action'),
+ **{'if': {'properties': {'action': {'const': 'renamed'}}},
+ 'then': {'required': ['title']}, 'else': {'not': {'required': ['title']}}})]
+ if stored:
+ for variant in variants:
+ variant['properties'].update(seq=number(1, integer=True), at=string(40),
+ by=enum(('user', 'agent', 'builtin', 'system')), client=string(80))
+ variant['required'] += ['seq', 'at', 'by']
+ return {'type': 'object', 'oneOf': variants, 'x-discriminator': 'type'}
+
+
+def session_schema(name):
+ if name == 'create':
+ return obj(dict(title=nullable(dict(type='string', maxLength=120))))
+ if name == 'list':
+ return obj(dict(limit=number(1, 200, integer=True, default=50), before=SESSION))
+ if name == 'events':
+ return obj(dict(after=number(0, integer=True, default=0), wait=number(0, 25, default=0),
+ limit=number(1, 500, integer=True, default=500)))
+ if name == 'post':
+ return session_event()
+ return EMPTY
+
+
+def project_schema(name):
+ if name in ('create', 'write'):
+ return obj(dict(project={'type': 'object', 'description': 'The editor page project record; validated by the shared editor save.'}, ref=REF), ('project',))
+ ids = array(CLIP, 1, 500)
+ revision = number(1, integer=True, description='The saved revision you read; a later save returns project_changed.')
+ if name == 'generate':
+ job = generate()['properties']
+ frames = number(1, 10**7, integer=True)
+ target = {'oneOf': [
+ obj(dict(clip_ids=ids), ('clip_ids',), description='Regenerate the selected picture clips in place.'),
+ obj(dict(start=EDITOR_FRAME, frames=frames, parts=array(frames, 1, 64, description='Part lengths that add up to frames; omitted parts follow what this device can make.')),
+ ('start', 'frames'), description='Fill a timeline range, continuing from the picture before it.')]}
+ settings = obj({k: job[k] for k in ('seed', 'quality', 'sampling', 'loras', 'force_regenerate')},
+ description='Generation settings; part i uses seed + i.')
+ return obj(dict(revision=revision, text=dict(type='string', maxLength=8000), target=target,
+ settings=settings, ref=REF), ('revision', 'target'))
+ if name == 'export':
+ return obj(dict(revision=revision, ref=REF), ('revision',))
+ if name != 'operations':
+ return EMPTY
+ fields = {
+ 'insert': (dict(source=EDITOR_SOURCE, at=EDITOR_FRAME), ('source',), 'Insert picture and sound from a source. Omit at to append at the timeline end.'),
+ 'split': (dict(clip_ids=ids, frame=EDITOR_FRAME), ('clip_ids', 'frame'), 'Cut selected clips and their linked partners. The frame must be inside a selected segment.'),
+ 'trim': (dict(clip_ids=ids, frame=EDITOR_FRAME, edge=enum(('start', 'end'))), ('clip_ids', 'frame', 'edge'), 'Trim a selected edge at the frame. The frame must be inside a selected segment.'),
+ 'remove': (dict(clip_ids=ids), ('clip_ids',), 'Remove selected clips and linked partners. Use clip IDs from this revision.'),
+ 'remove_gaps': (dict(gap=nullable(obj(dict(track=enum(('v1', 'a1', 'a2')), start=EDITOR_FRAME), ('track', 'start')))), (), 'Close a gap or all gaps when gap is omitted or null. Get the timeline first to identify a gap by track and start.'),
+ 'duplicate': (dict(clip_ids=ids), ('clip_ids',), 'Duplicate selected clips after themselves. Use clip IDs from this revision.'),
+ 'copy': (dict(clip_ids=ids, at=EDITOR_FRAME), ('clip_ids', 'at'), 'Copy selected clips to a timeline frame. Use clip IDs from this revision.'),
+ 'move': (dict(clip_ids=ids, frames=number(-10**7, 10**7, integer=True)), ('clip_ids', 'frames'), 'Move selected clips by a signed relative frame offset. Use clip IDs from this revision; linked partners move together.'),
+ 'describe': (dict(clip_ids=ids, text=dict(type='string', maxLength=8000)), ('clip_ids', 'text'), 'Set the description of selected clips. Use clip IDs from this revision and one paragraph of text.'),
+ 'set_ref': (dict(clip_ids=ids, ref=dict(type='string', maxLength=128, pattern=r'^[A-Za-z0-9_-]{0,128}$')), ('clip_ids', 'ref'), 'Set an outside shot reference on selected clips. Use clip IDs from this revision; an empty ref removes it.'),
+ 'use_version': (dict(clip_id=CLIP, index=number(0, 49, integer=True)), ('clip_id', 'index'), 'Restore a stored clip version. First get the clip ID and its versions array; index is zero based.'),
+ }
+ operations = [obj(dict(op={'const': op}, **props), ('op', *required), description=description)
+ for op, (props, required, description) in fields.items()]
+ return obj(dict(revision=number(1, integer=True), operations=array(
+ {'oneOf': operations, 'x-discriminator': 'op'}, 1, 64), ref=REF), ('revision', 'operations'))
+
+
+LABELS = ('front', 'three_quarter', 'side', 'back', 'face', 'sheet', 'other')
+
+
+def cast_route_table():
+ rows = ['| Operation | HTTP | Next step |', '|---|---|---|']
+ for name, (method, suffix, summary) in CAST_OPERATIONS.items():
+ rows.append('| %s | `%s P%s` | %s |' % (name, method, suffix, summary))
+ return '\n'.join(rows)
+
+
+def drama_route_table():
+ rows = ['| Operation | HTTP | Next step |', '|---|---|---|']
+ for name, (method, suffix, summary) in DRAMA_OPERATIONS.items():
+ rows.append('| %s | `%s P%s` | %s |' % (name, method, suffix, summary))
+ return '\n'.join(rows)
+
+
+CAST_REFERENCE = {'enum': [None, 'cards', 'partial', 'missing', 'inherited', 'own'],
+ 'description': 'How the shot carries cast cards: cards; partial (cast_omitted did not fit at all, or '
+ 'cast_voice_omitted came without their voice); missing '
+ '(a card was deleted, cast_missing shoot from text); inherited (continues the '
+ 'previous shot); own (the shot names its own first frame or references); null.'}
+
+
+def production_response():
+ paused = {'type': ['object', 'null'], 'properties': dict(at=string(), by=enum(('user',)))}
+ counts = obj(dict(completed=number(0, integer=True), total=number(0, integer=True)), ('completed', 'total'))
+ progress = obj(dict(takes=counts, shots=counts,
+ running=dict(type='array', items=obj(dict(shot=SLUG, take=number(1, integer=True), fraction=number(0, 1)),
+ ('shot', 'take', 'fraction'))),
+ join=obj(dict(completed={'type': 'boolean'}, fraction=number(0, 1)), ('completed', 'fraction')),
+ fraction=number(0, 1, description='Time-weighted when every estimate is known; otherwise work-item counts.'),
+ elapsed_seconds=number(0, description='Seconds since start excluding user pauses; stops at completion or cancellation.'),
+ estimate_seconds=nullable(number(0)), remaining_seconds=nullable(number(0))),
+ ('takes', 'shots', 'running', 'join', 'fraction', 'elapsed_seconds', 'estimate_seconds', 'remaining_seconds'))
+ over_budget = nullable({'oneOf': [
+ obj(dict(reason=enum(('elapsed',)), elapsed_seconds=number(0), estimate_seconds=number(0)),
+ ('reason', 'elapsed_seconds', 'estimate_seconds')),
+ obj(dict(reason=enum(('reshoot',)), shot=SLUG, estimate_seconds=number(600)),
+ ('reason', 'shot', 'estimate_seconds'))]})
+ return dict(type='object', properties=dict(id=PRODUCTION, title={'type': ['string', 'null']},
+ revision=number(1, integer=True), changed={'type': 'boolean'}, paused=paused,
+ progress=progress, over_budget=over_budget,
+ fraction=number(0, 1, description='Only in unchanged compact replies.'),
+ elapsed_seconds=number(0, description='Only in unchanged compact replies; excludes user pauses.'),
+ stalled={'type': ['object', 'null'], 'properties': dict(code=string(), message=string(), at=string())},
+ status=enum(('shooting', 'needs_choice', 'ready', 'joining', 'finished', 'cancelled', 'paused')),
+ screenplay={'type': 'object'}, director=enum(('agent', 'builtin')), created_at=string(), updated_at=string(),
+ shots=dict(type='array', items=dict(type='object', properties=dict(id=SLUG, index=number(1, integer=True),
+ continues={'type': 'boolean'}, chosen={'type': ['integer', 'null']}, chosen_by={'type': ['string', 'null']},
+ cast_reference=CAST_REFERENCE, cast_omitted=dict(type='array', items=string()),
+ cast_voice_omitted=dict(type='array', items=string()),
+ cast_missing=dict(type='array', items=string()),
+ takes=dict(type='array', items=dict(type='object', properties=dict(take=number(1, integer=True), job=REF,
+ task={'oneOf': [JOB, {'type': 'null'}]}, generation=number(0, integer=True), seed=number(0, integer=True),
+ stale={'type': 'boolean'}, error={'type': ['object', 'null']},
+ cast={'type': ['object', 'null'], 'additionalProperties': number(1, integer=True)})))))),
+ todo=dict(type='array', items={'type': 'object'}), decisions=dict(type='array', items={'type': 'object'}),
+ join={'type': ['object', 'null']}, outputs=dict(type='array', items={'type': 'object'})),
+ required=['id', 'revision', 'status', 'paused'])
+
+
+def safe_pointer(path):
+ """A field pointer that never repeats supplied keys, names, tokens or prompts."""
+ path = path if isinstance(path, str) else ''
+ return '/'.join(p if not p or re.fullmatch(r'[A-Za-z0-9_-]{1,64}', p) else '?' for p in path.split('/')) if path else '/'
+
+
+def problem_diagnostic(path, message):
+ """The shared diagnostic shape for a domain problem whose text a validator wrote."""
+ path = safe_pointer(path)
+ rule = message if isinstance(message, str) else 'valid'
+ rule = rule.replace('\n', ' ')[:200]
+ return dict(path=path, field=path, allowed=rule, got='invalid', message='%s %s.' % (path, rule.rstrip('.')),
+ next='Correct %s and retry.' % path, _safe=True)
+
+
+def diagnostic(path, allowed, got, *, nearest=None, missing=False):
+ # Field pointers are not file paths. Never echo supplied text, names, tokens or prompts.
+ path = path or '/'
+ actual = 'missing' if missing else repr(got) if got is None or type(got) in (bool, int, float) else (
+ '<string length %d>' % len(got) if isinstance(got, str) else '<%s>' % type(got).__name__)
+ action = ('Use %s %s.' % (path, ' or '.join(map(str, nearest)))) if nearest else 'Set %s to %s.' % (path, allowed)
+ return dict(path=path, field=path, allowed=allowed, got=actual,
+ message='%s must be %s; received %s.' % (path, allowed, actual), next=action, _safe=True)
+
+
+def prefix_diagnostic(error, prefix):
+ if not prefix:
+ return error
+ path = error['path']
+ return dict(error, path=prefix + path, field=prefix + path,
+ message=error['message'].replace(path, prefix + path, 1),
+ next=error.get('next', '').replace(path, prefix + path, 1))
+
+
+def _type(value, kind):
+ return {'object': isinstance(value, dict), 'array': isinstance(value, list), 'string': isinstance(value, str),
+ 'boolean': type(value) is bool, 'integer': type(value) is int,
+ 'number': type(value) is int or type(value) is float and math.isfinite(value), 'null': value is None}.get(kind, True)
+
+
+def issues(schema, value, path='', *, refs=False):
+ """Collect all violations, including independent cross-field rules. No mutation."""
+ if refs:
+ schema = batch_references(schema)
+ if schema is True:
+ return []
+ if schema is False:
+ return [diagnostic(path, 'absent in this combination', value)]
+ errors = []
+ if schema.get('x-media') is not None and isinstance(value, str):
+ return issues(FILE, value, path + '/file', refs=refs)
+ def bad(allowed, got=value, suffix='', **kw):
+ errors.append(diagnostic(path + suffix, allowed, got, **kw))
+ if schema.get('x-submission'):
+ return issues(schema['oneOf'][1 if isinstance(value, dict) and 'jobs' in value else 0], value, path)
+ if schema.get('x-discriminator') and isinstance(value, dict):
+ if schema['x-discriminator'] != 'kind':
+ field = schema['x-discriminator']
+ variants = {s['properties'][field]['const']: s for s in schema['oneOf']}
+ selected = value.get(field)
+ if not isinstance(selected, str) or selected not in variants:
+ return [diagnostic(path + '/' + field, ', '.join(variants), selected)]
+ return issues(variants[selected], value, path, refs=refs)
+ kind = value.get('kind', 'generate')
+ if not isinstance(kind, str) or kind not in KINDS:
+ return [diagnostic(path + '/kind', ', '.join(KINDS), kind)]
+ chosen = next(s for s in schema['oneOf'] if s.get('x-job-kind') == kind)
+ return issues(chosen, value, path, refs=refs)
+ for rule in schema.get('allOf', []):
+ errors += issues(rule, value, path)
+ if 'if' in schema:
+ rule = schema.get('then', True) if not issues(schema['if'], value) else schema.get('else', True)
+ errors += issues(rule, value, path)
+ if 'not' in schema and not issues(schema['not'], value):
+ errors.append(diagnostic(path, 'a permitted field combination', value))
+ if 'oneOf' in schema or 'anyOf' in schema:
+ # Structural unions choose the most specific applicable branch, then
+ # retain its field diagnostics instead of an opaque union error.
+ def compatible(rule):
+ if isinstance(rule, bool):
+ return rule
+ if 'oneOf' in rule or 'anyOf' in rule:
+ return any(compatible(r) for r in rule.get('oneOf', rule.get('anyOf')))
+ if isinstance(rule, bool):
+ return rule
+ if isinstance(value, dict) and rule.get('required'):
+ if not all(k in value for k in rule['required']):
+ return False
+ kinds = rule.get('type')
+ return not kinds or any(_type(value, k) for k in (kinds if isinstance(kinds, list) else [kinds]))
+ variants = schema.get('oneOf', schema.get('anyOf'))
+ choices = [r for r in variants if compatible(r)] or variants
+ branches = [issues(s, value, path, refs=refs) for s in choices]
+ valid = sum(not e for e in branches)
+ if valid > 1 and 'oneOf' in schema:
+ errors.append(diagnostic(path, 'exactly one permitted alternative', value))
+ if not valid:
+ errors += min(branches, key=lambda e: (any('must be object' in r['message'] for r in e), len(e)))
+ try:
+ errors += cross_issues(schema, value, path)
+ except (TypeError, KeyError, AttributeError, ValueError):
+ pass
+ return errors
+ types = schema.get('type')
+ if types and not any(_type(value, t) for t in (types if isinstance(types, list) else [types])):
+ bad(str(types)); return errors
+ if value is None:
+ return errors
+ if 'const' in schema and value != schema['const']:
+ bad(repr(schema['const']))
+ if 'enum' in schema and value not in schema['enum']:
+ bad('one of ' + ', '.join(map(str, schema['enum'])))
+ if type(value) in (int, float):
+ low, high, step = schema.get('minimum'), schema.get('maximum'), schema.get('multipleOf')
+ if 'exclusiveMinimum' in schema and value <= schema['exclusiveMinimum']:
+ bad('greater than %s' % schema['exclusiveMinimum'])
+ if 'exclusiveMaximum' in schema and value >= schema['exclusiveMaximum']:
+ bad('less than %s' % schema['exclusiveMaximum'])
+ finite = type(value) is int or math.isfinite(value)
+ if not finite or low is not None and value < low or high is not None and value > high or step and value % step:
+ allowed = '%s from %s to %s' % ('a multiple of %s' % step if step else schema.get('type', 'number'), low, high)
+ nearest = None
+ if step and finite:
+ base = math.floor(max(low, min(high, value)) / step) * step
+ candidates = {v for v in (base - step, base, base + step, low, low + step, high - step, high)
+ if low <= v <= high}
+ nearest = sorted(sorted(candidates, key=lambda v: (abs(v - value), v))[:2])
+ bad(allowed, nearest=nearest)
+ if isinstance(value, str):
+ if (len(value) < schema.get('minLength', 0) or len(value) > schema.get('maxLength', float('inf'))
+ or schema.get('minLength') and not value.strip() or '\x00' in value):
+ bad('a nonempty string of at most %s characters' % schema.get('maxLength', 'the documented limit'))
+ pattern = schema.get('pattern')
+ if pattern:
+ if not re.fullmatch(pattern, value):
+ if schema == FILE:
+ bad('a relative input file returned by media upload', suffix='/file' if schema.get('x-media') else '')
+ else:
+ bad('a string matching ' + pattern)
+ if isinstance(value, list):
+ if not schema.get('minItems', 0) <= len(value) <= schema.get('maxItems', float('inf')):
+ bad('a list of %d to %s items' % (schema.get('minItems', 0), schema.get('maxItems', 'unlimited')))
+ for i, child in enumerate(value):
+ errors += issues(schema.get('items', {}), child, path + '/' + str(i), refs=refs)
+ if isinstance(value, dict):
+ props = schema.get('properties', {})
+ if schema.get('additionalProperties') is False:
+ for key in sorted(value.keys() - props.keys()):
+ bad('absent (unknown field)', value[key], '/<unknown>')
+ for key in schema.get('required', []):
+ if key not in value:
+ bad('present', None, '/' + pointer(key), missing=True)
+ for key, child in value.items():
+ if key in props:
+ errors += issues(props[key], child, path + '/' + pointer(key), refs=False)
+ if schema.get('x-json-bytes'):
+ try:
+ if len(json.dumps(value, allow_nan=False)) > schema['x-json-bytes']:
+ bad('JSON of at most %d bytes' % schema['x-json-bytes'])
+ except (TypeError, ValueError):
+ bad('finite JSON')
+ # Cross-field constraints only run on structurally sound subtrees.
+ try:
+ errors += cross_issues(schema, value, path)
+ except (TypeError, KeyError, AttributeError, ValueError):
+ pass # Ill-typed subtrees already have structural diagnostics.
+
+ return errors
+
+
+def cross_issues(schema, value, path):
+ errors = []
+ def bad(field, allowed, got=None):
+ errors.append(diagnostic(path + '/' + field, allowed, got))
+ flags = schema.get('x-media')
+ if flags is not None:
+ item = {'file': value} if isinstance(value, str) else value
+ if flags['clip'] and item.get('end') is not None and item['end'] <= item.get('start', 0):
+ bad('end', 'later than start', item['end'])
+ kind = schema.get('x-job-kind')
+ if kind == 'generate':
+ if value.get('continue_from') and value.get('media'):
+ bad('media', 'omitted when continue_from is supplied', value['media'])
+ if value.get('refine_from') is None:
+ custom = value.get('sampling', {})
+ two, base, refine = QUALITY[value.get('quality', 'light')]
+ two, base, refine = custom.get('two_pass', two), custom.get('base_steps', base), custom.get('refine_steps', refine)
+ from ..two_pass import validate_steps
+ try:
+ validate_steps(base, refine, two)
+ except ValueError:
+ bad('sampling', 'two-pass refine_steps=3 or refine_steps below base_steps', custom)
+ if kind == 'vlm':
+ rows = value['questions'] if isinstance(value['questions'], list) else [value['questions']]
+ count = sum(len(r.get('images', [])) + (r.get('video', {}).get('frames', 6) if isinstance(r.get('video'), dict)
+ else 6 if r.get('video') else 0) for r in rows if isinstance(r, dict))
+ if count > 24:
+ bad('questions', 'at most 24 images and sampled frames', count)
+ if schema.get('x-editor-document'):
+ errors += editor_issues(value, path, document=True)
+ if schema.get('x-editor-recipe'):
+ from .edit import _color, _aspect
+ for i, operation in enumerate(value.get('operations', [])):
+ if not isinstance(operation, dict):
+ continue
+ for key in ('color', 'fill', 'stroke', 'outline'):
+ color = operation.get(key)
+ if color is not None and type(color) is not bool:
+ try:
+ _color(color, '')
+ except (ValueError, TypeError):
+ bad('operations/%d/%s' % (i, key), 'a supported CSS colour', color)
+ for key in ('ratio', 'to') if operation.get('op') in ('crop', 'pad', 'extend') else ():
+ if key in operation:
+ try:
+ _aspect(operation[key], {'w': 1, 'h': 1}, (1, 1), '')
+ except (ValueError, TypeError):
+ bad('operations/%d/%s' % (i, key), 'an editor ratio or positive W:H', operation[key])
+ return errors
+
+
+def validate(schema, value, *, refs=False):
+ from .spec import SpecError
+ errors = issues(schema, value, refs=refs)
+ if errors:
+ raise SpecError(errors)
+ return value
+
+
+def validate_job(value, *, local=False, refs=False):
+ return validate(job_schema(local=local, refs=refs), value)
+
+
+def request_contract(method, path, *, local=False):
+ definitions = contracts(local=local)
+ key = method, path
+ if key not in definitions:
+ path = re.sub(r'/jobs/j[0-9a-f]{12}/', '/jobs/{id}/', path)
+ path = re.sub(r'/cast/c[0-9a-f]{12}(?=/|$)', '/cast/{id}', path)
+ definition = definitions.get((method, path))
+ return definition['body'] if definition else None
+
+
+def editor_issues(value, path, *, document=False, source_size=None, target=None, resolve=None):
+ """Reuse editor validation without rendering or writing any files."""
+ from . import edit
+ try:
+ if document or isinstance(value, dict) and value.get('version') == 2:
+ edit._check(value)
+ elif source_size is not None:
+ edit.compile_recipe(value, source='input', source_size=source_size, target=target, resolve=resolve)
+ else:
+ # Static operation fields are generated from describe(). Geometry
+ # needs the actual image and is checked by ComfyPort before commit.
+ return issues(edit_recipe(), value, path)
+ except (ValueError, TypeError, KeyError, AttributeError):
+ # Renderer errors may contain user-supplied field names or filenames.
+ return [diagnostic(path, 'a valid editor document or recipe for the source dimensions', None)]
+ return []
+
+
+def preflight_submission(value):
+ """Complete static client preflight before the first upload."""
+ from .spec import SpecError
+ problems = []
+ batch = isinstance(value, dict) and 'jobs' in value
+ rows = value['jobs'] if batch else [value]
+ names, count = set(), 0
+ def walk(item, path):
+ if isinstance(item, list):
+ for i, child in enumerate(item):
+ walk(child, path + '/' + str(i))
+ elif isinstance(item, dict):
+ for key, child in item.items():
+ if key == 'edit':
+ problems.extend(editor_issues(child, path + '/edit'))
+ elif key != 'metadata':
+ walk(child, path + '/' + pointer(key))
+ elif isinstance(item, str) and item.startswith('@') and (path.rsplit('/', 1)[-1] in ('from_job', 'refine_from') or re.search(r'/(after|clips)/[0-9]+$', path)):
+ if item[1:] not in names:
+ problems.append(diagnostic(path, 'an earlier batch ref', item))
+ for i, row in enumerate(rows):
+ path = '/jobs/%d' % i if batch else ''
+ count += row.get('takes', 1)
+ if row.get('kind', 'generate') == 'generate' and not row.get('refine_from'):
+ from .spec import canvas_size
+ try:
+ canvas_size(row)
+ except SpecError as error:
+ problems.extend(prefix_diagnostic(e, path) for e in error.errors)
+ walk(row, path)
+ if batch and row.get('ref'):
+ if row['ref'] in names:
+ problems.append(diagnostic(path + '/ref', 'a unique batch ref', row['ref']))
+ names.add(row['ref'])
+ if count > 64:
+ problems.append(diagnostic('/jobs', 'at most 64 jobs after takes expansion', count))
+ if problems:
+ raise SpecError(problems)
+
+
+def defaults(schema, value):
+ """Fill only defaults for fields on this object (not alternative representations)."""
+ return {k: deepcopy(v['default']) for k, v in schema.get('properties', {}).items() if 'default' in v} | value
+
+
+def query_values(schema, query):
+ value = dict(query)
+ for key, rule in schema.get('properties', {}).items():
+ if key in value and rule.get('type') in ('number', 'integer'):
+ try:
+ value[key] = (int if rule['type'] == 'integer' else float)(value[key])
+ except (TypeError, ValueError, OverflowError):
+ pass
+ validate(schema, value)
+ return defaults(schema, value)
+
+
+def schemas():
+ return dict(api_version=API_VERSION, job=dict(job_schema(), **{'$schema': S, '$defs': {
+ k: f() for k, f in KINDS.items()}}), batch=batch_schema(), production=drama_schema('start'),
+ drama={name: drama_schema(name) for name in DRAMA_OPERATIONS}, production_view=production_response(),
+ cast={name: cast_schema(name) for name in CAST_OPERATIONS},
+ projects={name: project_schema(name) for name in PROJECT_OPERATIONS},
+ images={name: image_schema(name) for name in IMAGE_OPERATIONS},
+ sessions=dict(event=session_event(stored=True), meta=session_view(),
+ **{name: session_schema(name) for name in SESSION_OPERATIONS}),
+ confirmations=confirm_settings())
+
+
+def openapi():
+ from .errors import ERRORS
+ paths = {}
+ for (method, suffix), contract in contracts().items():
+ path = suffix if suffix.startswith('/freevideo/') else PREFIX + suffix
+ operation = dict(summary=contract['summary'], security=[] if contract.get('auth') is False else [{'bearer': []}],
+ responses={str(contract.get('status', 200)): {'description': 'Success'},
+ **{str(status): {'description': 'Agent error', 'content': {'application/json': {'schema': {
+ 'type': 'object', 'properties': {'error': {'$ref': '#/components/schemas/Error'}}}}}}
+ for status in sorted({r[0] for r in ERRORS.values() if r[0] >= 400})}})
+ if contract.get('page_or_token'):
+ operation['security'] = [{'page': []}] if suffix.endswith(('/stop', '/resume')) else [{'bearer': []}, {'page': []}]
+ if contract['body'] is not None:
+ content = {'application/json': {'schema': deepcopy(contract['body'])}}
+ if contract.get('multipart'):
+ content['multipart/form-data'] = {'schema': obj({'file': {'type': 'string', 'format': 'binary'}}, ('file',))}
+ operation['requestBody'] = dict(required=not contract.get('optional_body', False), content=content)
+ operation['parameters'] = [dict(name=k, **{'in': 'query'}, required=k in contract['query'].get('required', []), schema=v)
+ for k, v in contract['query']['properties'].items()]
+ operation['parameters'] += [dict(name=k, **{'in': 'path'}, required=True,
+ schema=contract.get('path', {}).get('properties', {}).get(k, JOB if k == 'id' else string()))
+ for k in re.findall(r'\{(.*?)\}', path)]
+ if contract.get('idempotent'):
+ operation['parameters'].append(dict(name='Idempotency-Key', **{'in': 'header'}, required=False, schema=REF))
+ if contract.get('page_or_token'):
+ operation['parameters'].append(dict(name='X-FreeVideo-CSRF', **{'in': 'header'}, required=False,
+ schema=string(128), description='Required with the freevideo_agent_page cookie, including reads.'))
+ if suffix == '/sessions/{id}/events' and method == 'GET':
+ operation['parameters'].append(dict(name='Last-Event-ID', **{'in': 'header'}, required=False,
+ schema=number(0, integer=True), description='SSE resume cursor; overrides after.'))
+ content_type, response_schema = 'application/json', {'type': 'object'}
+ if suffix == '/jobs' and method == 'POST':
+ response_schema = {'$ref': '#/components/schemas/Submitted'}
+ elif suffix == '/jobs' and method == 'GET':
+ response_schema = obj({'jobs': {'type': 'array', 'items': {'$ref': '#/components/schemas/Job'}}})
+ elif suffix in ('/jobs/{id}', '/jobs/{id}/cancel', '/jobs/{id}/resume'):
+ response_schema = {'$ref': '#/components/schemas/Job'}
+ elif '/drama/{id}' in suffix and not suffix.endswith('/sheet') or suffix == '/drama' and method == 'POST':
+ response_schema = production_response()
+ elif suffix == '/confirmations':
+ response_schema = obj(confirm_settings()['properties'], ('start', 'reshoot_seconds'))
+ elif suffix.startswith('/sessions'):
+ response_schema = (obj(dict(events=array(session_event(stored=True), 0, 500),
+ last_seq=number(0, integer=True), stopped={'type': 'boolean'}), ('events', 'last_seq', 'stopped'))
+ if suffix.endswith('/events') and method == 'GET' else session_event(stored=True)
+ if suffix.endswith(('/events', '/stop', '/resume')) else
+ obj(dict(sessions=array(session_view(), 0, 200), next_before=nullable(SESSION)), ('sessions', 'next_before'))
+ if suffix == '/sessions' and method == 'GET' else session_view())
+ elif suffix.endswith('/events'):
+ content_type, response_schema = 'text/event-stream', {'type': 'string'}
+ elif suffix == '/editor/sources/content':
+ content_type, response_schema = 'application/octet-stream', {'type': 'string', 'format': 'binary'}
+ elif suffix.endswith('/file') or suffix.endswith('/thumbnail'):
+ content_type = 'video/mp4' if suffix.endswith('/file') else 'image/jpeg'
+ response_schema = {'type': 'string', 'format': 'binary'}
+ success = operation['responses'][str(contract.get('status', 200))]
+ success['content'] = {content_type: {'schema': response_schema}}
+ if suffix == '/sessions/{id}/events' and method == 'GET':
+ success['content']['text/event-stream'] = {'schema': {'type': 'string'}}
+ if contract.get('idempotent'):
+ operation['responses']['200'] = deepcopy(success)
+ if suffix.endswith('/file') or suffix == '/editor/sources/content':
+ operation['responses']['206'] = deepcopy(success)
+ if suffix == '/connect' and method == 'GET':
+ success['content']['text/plain'] = {'schema': {'type': 'string'}}
+ paths.setdefault(path, {})[method.lower()] = operation
+ return dict(openapi='3.1.0', info=dict(title='FreeVideo Agent API', version=str(API_VERSION)), paths=paths,
+ components=dict(securitySchemes={'bearer': {'type': 'http', 'scheme': 'bearer'},
+ 'page': {'type': 'apiKey', 'in': 'cookie', 'name': 'freevideo_agent_page'}}, schemas={
+ 'Session': session_view(), 'SessionEvent': session_event(stored=True),
+ 'JobSpec': schemas()['job'], 'Batch': batch_schema(),
+ 'Job': {'type': 'object', 'properties': dict(id=JOB, kind=enum(KINDS),
+ status=enum(('waiting', 'queued', 'running', 'cancelling', 'succeeded', 'failed', 'cancelled', 'interrupted')),
+ chain_id=string(), last_heartbeat_at={'type': ['string', 'null']}, poll_after_ms={'type': ['integer', 'null']},
+ spec={'type': 'object'}, progress={'type': 'object'}, result={'type': 'object'},
+ error={'$ref': '#/components/schemas/Error'})},
+ 'Submitted': obj(dict(job={'$ref': '#/components/schemas/Job'},
+ jobs={'type': 'array', 'items': {'$ref': '#/components/schemas/Job'}})),
+ 'Error': obj(dict(code=enum(ERRORS),
+ message=string(), details={'type': 'array'}, next=string(), retryable={'type': 'boolean'},
+ request_id=string(), docs=string(), retry_after_seconds=number(0), card={'type': 'object'}, job=JOB,
+ project={'type': 'object'}, current_revision=number(1, integer=True)),
+ ('code', 'message', 'details', 'retryable', 'request_id', 'docs'))}))
+
+
+TOOL_ENDPOINTS = {
+ 'freevideo_status': ('GET', ''), 'freevideo_capabilities': ('GET', '/capabilities'),
+ 'freevideo_prompt_guide': ('GET', '/guide'), 'freevideo_schema': ('GET', '/schema'),
+ 'freevideo_plan': ('POST', '/plan'), 'freevideo_submit_batch': ('POST', '/jobs'),
+ 'freevideo_job': ('GET', '/jobs/{id}'), 'freevideo_wait': ('GET', '/jobs/{id}'),
+ 'freevideo_jobs': ('GET', '/jobs'), 'freevideo_cancel': ('POST', '/jobs/{id}/cancel'),
+ 'freevideo_resume': ('POST', '/jobs/{id}/resume'), 'freevideo_add_media': ('POST', '/media'),
+ 'freevideo_edit_image': ('POST', '/media/edit'), 'freevideo_library': ('GET', '/library'),
+}
+TOOL_ENDPOINTS.update({'freevideo_drama_' + name: (method, suffix)
+ for name, (method, suffix, _) in DRAMA_OPERATIONS.items()})
+TOOL_ENDPOINTS.update({'freevideo_cast_' + name: (method, suffix)
+ for name, (method, suffix, _) in CAST_OPERATIONS.items()})
+TOOL_ENDPOINTS.update({PROJECT_TOOLS[name]: (method, suffix)
+ for name, (method, suffix, _) in PROJECT_OPERATIONS.items()})
+TOOL_ENDPOINTS.update({IMAGE_TOOLS[name]: (method, suffix)
+ for name, (method, suffix, _) in IMAGE_OPERATIONS.items()})
+TOOL_ENDPOINTS.update({SESSION_TOOLS[name]: SESSION_OPERATIONS[name][:2]
+ for name in SESSION_TOOLS if name != 'post'})
+TOOL_KINDS = dict(freevideo_generate='generate', freevideo_assemble='assemble',
+ freevideo_ask='vlm', freevideo_enhance_prompt='enhance')
+
+
+SESSION_ARGUMENT = dict(type='string', pattern='^s[0-9a-f]{12}$',
+ description='Work session for this call; omit to use your latest one.')
+
+
+SHAPE_MIN_BYTES = 400
+RECIPE_TOOL = 'freevideo_edit_image'
+
+
+def schema_children(node):
+ """(keyword, key or index, subschema) for each child in a schema position."""
+ for keyword, value in node.items():
+ if keyword in ('additionalProperties', 'items', 'not', 'if', 'then', 'else', 'contains', 'propertyNames'):
+ if isinstance(value, dict):
+ yield keyword, None, value
+ elif keyword in ('properties', 'patternProperties', 'dependentSchemas') and isinstance(value, dict):
+ yield from ((keyword, key, child) for key, child in value.items() if isinstance(child, dict))
+ elif keyword in ('anyOf', 'oneOf', 'allOf', 'prefixItems') and isinstance(value, list):
+ yield from ((keyword, i, child) for i, child in enumerate(value) if isinstance(child, dict))
+
+
+def shape_label(path):
+ label = ''
+ for keyword, key in path:
+ if keyword == 'properties':
+ label += ('.' if label else '') + key
+ elif keyword == 'items':
+ label += '[]'
+ elif keyword == 'additionalProperties':
+ label += '{}'
+ return label or 'the arguments'
+
+
+def mcp_tool_schema(name):
+ """The schema an MCP client shows its model. Each client sends every tool schema
+ with every request, so a repeated shape is written out once and later named; the
+ edit recipe is spelled out on the edit tool only. Calls still validate against
+ tool_schema(name) here and on the server."""
+ value = tool_schema(name)
+ if name != RECIPE_TOOL:
+ def brief(node):
+ if node.get('x-editor-recipe'):
+ return {'type': 'object', 'required': ['operations'],
+ 'description': 'Image edit recipe: the operations %s takes.' % RECIPE_TOOL}
+ node = dict(node)
+ for keyword, key, child in list(schema_children(node)):
+ _replace(node, keyword, key, brief(child))
+ return node
+ value = brief(value)
+ def key(node):
+ return json.dumps(node, sort_keys=True, separators=(',', ':'))
+ counts = {}
+ def count(node):
+ for _, _, child in schema_children(node):
+ text = key(child)
+ if len(text) >= SHAPE_MIN_BYTES:
+ counts[text] = counts.get(text, 0) + 1
+ count(child)
+ count(value)
+ first = {}
+ def rebuild(node, path):
+ node = dict(node)
+ for keyword, index, child in list(schema_children(node)):
+ here, text = path + [(keyword, index)], key(child)
+ if counts.get(text, 0) > 1 and text in first:
+ child = dict({'type': child['type']} if 'type' in child else {},
+ description='Same shape as %s.' % first[text])
+ else:
+ if counts.get(text, 0) > 1:
+ first[text] = shape_label(here)
+ child = rebuild(child, here)
+ _replace(node, keyword, index, child)
+ return node
+ return rebuild(value, [])
+
+
+def _replace(node, keyword, index, child):
+ if index is None:
+ node[keyword] = child
+ elif isinstance(node[keyword], dict):
+ node[keyword] = dict(node[keyword], **{index: child})
+ else:
+ node[keyword] = node[keyword][:index] + [child] + node[keyword][index + 1:]
+
+
+def tool_schema(name):
+ value = _tool_schema(name)
+ if value.get('type') == 'object' and isinstance(value.get('properties'), dict):
+ value = dict(value, properties=dict(value['properties'], session=SESSION_ARGUMENT))
+ return value
+
+
+def _tool_schema(name):
+ if name == 'freevideo_session_post':
+ message, plan = session_event(agent_only=True)['oneOf']
+ return obj(dict(id=SESSION, type=enum(('message', 'plan')), text=message['properties']['text'],
+ shots=plan['properties']['shots'], total_seconds=plan['properties']['total_seconds']), ('id', 'type'),
+ oneOf=[{'properties': {'type': {'const': 'message'}}, 'required': ['text'],
+ 'not': {'anyOf': [{'required': ['shots']}, {'required': ['total_seconds']}]}},
+ {'properties': {'type': {'const': 'plan'}}, 'required': ['shots'],
+ 'not': {'required': ['text']}}])
+ if name in TOOL_KINDS or name == 'freevideo_plan':
+ kind = TOOL_KINDS.get(name, 'generate')
+ value = KINDS[kind](local=True)
+ value['properties'].pop('kind')
+ value['required'] = [k for k in value.get('required', []) if k != 'kind']
+ if name != 'freevideo_plan':
+ value['properties']['wait'] = dict(CLIENT_WAIT, default=0 if kind == 'generate' else 25)
+ return value
+ if name in TOOL_ENDPOINTS:
+ method, suffix = TOOL_ENDPOINTS[name]
+ contract = contracts(local=True)[method, suffix]
+ value = deepcopy(contract['query'] if method == 'GET' else contract['body'])
+ if name == 'freevideo_submit_batch':
+ return batch_schema(local=True)
+ if name == 'freevideo_add_media':
+ return obj({'path': string(4096)}, ('path',))
+ if '{id}' in suffix:
+ value['properties']['id'] = contract.get('path', {}).get('properties', {}).get('id', JOB)
+ value['required'] = list(value.get('required', [])) + ['id']
+ if '{shot}' in suffix:
+ value['properties']['shot'] = SLUG
+ value['required'].append('shot')
+ if name == 'freevideo_wait':
+ value['properties'].pop('wait')
+ value['properties']['timeout'] = CLIENT_WAIT
+ value['required'] = [k for k in value['required'] if k != 'id']
+ return value
+ if name == 'freevideo_asset':
+ return obj(dict(id=SAVED, target=string(4096), thumbnail={'type': 'boolean', 'default': False}), ('id', 'target'))
+ if name == 'freevideo_look':
+ return obj(dict(source={'anyOf': [string(4096), media(local=True)]},
+ mode=enum(('frame', 'sheet', 'image'), default='sheet'), at=dict(FRAME, default='last'),
+ count=contracts()['POST', '/media/contact-sheet']['body']['properties']['count']), ('source',))
+ raise KeyError(name)
+
+
+def cli_arguments(parser, schema, *, exclude=()):
+ """Generate real argparse options; validation uses the identical field rules."""
+ import argparse
+ parser.request_schema = deepcopy(schema)
+ for key, rule in schema['properties'].items():
+ if key in exclude or 'const' in rule:
+ continue
+ kind = rule.get('type')
+ if isinstance(kind, list):
+ kind = kind[0]
+ def json_or_string(value):
+ try:
+ return json.loads(value)
+ except ValueError:
+ return value
+ union = 'oneOf' in rule or 'anyOf' in rule
+ convert = int if kind == 'integer' else float if kind == 'number' else json.loads if kind in (
+ 'object', 'array', 'boolean') or not kind and not union else json_or_string if union else str
+ parser.add_argument('--' + key.replace('_', '-'), dest=key, type=convert,
+ default=argparse.SUPPRESS, help=json.dumps(rule, ensure_ascii=False))
diff --git a/freevideo_engine/agent/sessions.py b/freevideo_engine/agent/sessions.py
new file mode 100644
index 0000000..7febb1e
--- /dev/null
+++ b/freevideo_engine/agent/sessions.py
@@ -0,0 +1,390 @@
+"""Append-only work conversations, independent of HTTP and the model runtime."""
+from __future__ import annotations
+
+import asyncio
+from copy import deepcopy
+from datetime import datetime, timezone
+import json
+import os
+from pathlib import Path
+import secrets
+import threading
+import time
+
+from . import errors, schema
+from .jobs import JobError
+from .spec import SpecError
+
+MAX_EVENT_BYTES = 16 * 1024
+
+
+class SessionError(JobError):
+ def view(self):
+ if self.code == 'invalid_request':
+ return errors.validation(self.details['details'])
+ return super().view()
+
+
+def _check(shape, value):
+ try:
+ return schema.validate(shape, value)
+ except SpecError as error:
+ raise SessionError('invalid_request', 'Invalid session fields', details=error.errors) from None
+
+
+def _invalid(field, allowed):
+ return SessionError('invalid_request', 'Invalid session event',
+ details=[schema.diagnostic(field, allowed, None)])
+
+
+def _stamp(seconds):
+ return datetime.fromtimestamp(seconds, timezone.utc).isoformat(timespec='microseconds').replace('+00:00', 'Z')
+
+
+def _line(value):
+ return json.dumps(value, ensure_ascii=False, allow_nan=False, separators=(',', ':')).encode('utf-8')
+
+
+class Sessions:
+ def __init__(self, root: Path, *, clock=time.time, max_events=20000):
+ self.root = Path(root)
+ self.clock = clock
+ self.max_events = max_events
+ self.lock = threading.Lock()
+ self.on_stop = [] # HTTP invokes these after persisting a user stop.
+ self._meta = {}
+ self._ids = {}
+ self._clients = {}
+ self._initial_seq = {}
+ self._readers = {}
+ self._user_seq = {} # Last event the user wrote; unread() skips the file when nothing is newer.
+ self._waiters = {}
+ self._partial = set()
+ self.root.mkdir(parents=True, exist_ok=True)
+ self._load()
+
+ def _path(self, sid):
+ _check(schema.obj(dict(id=schema.SESSION), ('id',)), dict(id=sid))
+ return self.root / (sid + '.jsonl')
+
+ def _get(self, sid):
+ self._path(sid)
+ if sid not in self._meta:
+ raise SessionError('not_found', 'Session does not exist')
+ return self._meta[sid]
+
+ def _load(self):
+ for path in sorted(self.root.glob('s*.jsonl')):
+ sid = path.stem
+ if schema.issues(schema.SESSION, sid) or path.is_symlink():
+ continue
+ with path.open('rb') as stream:
+ first = stream.readline()
+ try:
+ meta = json.loads(first)
+ if not first.endswith(b'\n') or meta.get('session') != sid:
+ continue
+ _check(schema.session_metadata(), meta)
+ except (ValueError, UnicodeDecodeError, SessionError, AttributeError):
+ continue
+ self._meta[sid] = dict(id=sid, title=meta['title'], created_at=meta['created_at'],
+ updated_at=meta['created_at'], client=meta['client'], last_seq=0, stopped=False)
+ self._ids[sid] = {}
+ self._clients[sid] = {meta['client']} if meta['client'] else set()
+ for row in stream:
+ if not row.endswith(b'\n'):
+ self._partial.add(sid)
+ break
+ try:
+ event = json.loads(row)
+ _check(schema.session_event(stored=True), event)
+ if event['seq'] != self._meta[sid]['last_seq'] + 1:
+ continue
+ except (ValueError, UnicodeDecodeError, SessionError):
+ # Also skips an interrupted tail separated by a later append.
+ continue
+ self._fold(sid, event)
+ self._initial_seq[sid] = self._meta[sid]['last_seq']
+
+ def _fold(self, sid, event):
+ meta = self._meta[sid]
+ meta.update(last_seq=event['seq'], updated_at=event['at'])
+ if event['by'] == 'user':
+ self._user_seq[sid] = event['seq']
+ if event.get('client'):
+ self._clients[sid].add(event['client'])
+ if event.get('id'):
+ self._ids[sid][event['id']] = event
+ if event['type'] == 'control':
+ if event['action'] in ('stopped', 'resumed'):
+ meta['stopped'] = event['action'] == 'stopped'
+ elif event['action'] == 'renamed':
+ meta['title'] = event['title']
+
+ def _write(self, sid, value, *, create=False):
+ flags = os.O_WRONLY | os.O_APPEND | getattr(os, 'O_NOFOLLOW', 0)
+ if create:
+ flags |= os.O_CREAT | os.O_EXCL
+ descriptor = os.open(self._path(sid), flags, 0o600)
+ with os.fdopen(descriptor, 'wb') as stream:
+ # Never truncate crash evidence. A separator lets new whole lines survive.
+ stream.write((b'\n' if sid in self._partial else b'') + _line(value) + b'\n')
+ stream.flush()
+ os.fsync(stream.fileno())
+ self._partial.discard(sid)
+
+ def create(self, *, title=None, client=None, by='agent') -> dict:
+ meta = dict(session='s' + secrets.token_hex(6), title=title, created_at=_stamp(self.clock()),
+ client=client, by=by)
+ _check(schema.session_metadata(), meta)
+ with self.lock:
+ while True:
+ sid = meta['session']
+ try:
+ self._write(sid, meta, create=True)
+ break
+ except FileExistsError:
+ meta['session'] = 's' + secrets.token_hex(6)
+ self._meta[sid] = dict(id=sid, title=title, created_at=meta['created_at'],
+ updated_at=meta['created_at'], client=client, last_seq=0, stopped=False)
+ self._ids[sid], self._clients[sid] = {}, {client} if client else set()
+ self._initial_seq[sid] = 0
+ return deepcopy(self._meta[sid])
+
+ def list(self, *, limit=50, before=None) -> dict:
+ _check(schema.session_schema('list'), dict(limit=limit, **({'before': before} if before is not None else {})))
+ with self.lock:
+ rows = sorted(self._meta.values(), key=lambda r: (r['updated_at'], r['id']), reverse=True)
+ if before is not None:
+ self._get(before)
+ start = next(i for i, row in enumerate(rows) if row['id'] == before) + 1
+ rows = rows[start:]
+ page = rows[:limit]
+ return dict(sessions=deepcopy(page), next_before=page[-1]['id'] if len(rows) > limit else None)
+
+ def get(self, sid) -> dict:
+ with self.lock:
+ return deepcopy(self._get(sid))
+
+ def append(self, sid, event: dict, *, by, client=None) -> dict:
+ _check(schema.obj(dict(by=schema.enum(('user', 'agent', 'builtin', 'system'))), ('by',)), dict(by=by))
+ _check(schema.obj(dict(client=schema.nullable(schema.string(80)))), dict(client=client))
+ if not isinstance(event, dict):
+ raise _invalid('/', 'an event object')
+ event = deepcopy(event)
+ with self.lock:
+ meta = self._get(sid)
+ kind = event.get('type')
+ if kind == 'step' and event.get('state') == 'started' and 'id' not in event:
+ event['id'] = 'st' + secrets.token_hex(5)
+ previous = self._ids[sid].get(event.get('id')) if isinstance(event.get('id'), str) else None
+ if kind in ('step', 'confirm'):
+ initial = 'started' if kind == 'step' else 'asked'
+ if event.get('state') != initial:
+ if previous is None or previous['type'] != kind or previous['state'] != initial:
+ raise _invalid('/id', 'the ID of an unfinished ' + kind)
+ inherited = {k: v for k, v in previous.items() if k not in ('seq', 'at', 'by', 'client')}
+ if kind == 'confirm' and any(k not in ('type', 'id', 'state') for k in event):
+ raise _invalid('/', 'a confirmation answer containing type, id and state only')
+ event = inherited | event
+ elif previous is not None:
+ raise _invalid('/id', 'a new event ID')
+ _check(schema.session_event(), event)
+ if kind == 'step' and by == 'user':
+ raise SessionError('forbidden', 'Steps are written by the server')
+ if kind == 'confirm' and ((event['state'] == 'asked') == (by == 'user')):
+ raise SessionError('forbidden', 'Only the user may answer a confirmation')
+ if kind == 'control' and event['action'] != 'renamed' and by != 'user':
+ raise SessionError('forbidden', 'Only the user may stop or continue')
+ result = dict(event, seq=meta['last_seq'] + 1, at=_stamp(self.clock()), by=by)
+ if client is not None:
+ result['client'] = client
+ try:
+ size = len(_line(result))
+ except (ValueError, TypeError, UnicodeEncodeError):
+ raise _invalid('/', 'finite UTF-8 JSON') from None
+ if size > MAX_EVENT_BYTES:
+ raise SessionError('too_large', 'Session event exceeds the byte limit', limit_bytes=MAX_EVENT_BYTES)
+ if meta['last_seq'] >= self.max_events:
+ raise SessionError('session_full', 'Session event limit reached')
+ self._write(sid, result)
+ self._fold(sid, result)
+ for loop, signal in self._waiters.get(sid, ()):
+ try:
+ loop.call_soon_threadsafe(signal.set)
+ except RuntimeError:
+ pass # A closed client loop no longer needs notification.
+ return deepcopy(result)
+
+ def _events(self, sid, after, limit):
+ rows = []
+ expected = 1
+ with self._path(sid).open('rb') as stream:
+ stream.readline()
+ for line in stream:
+ if not line.endswith(b'\n'):
+ break
+ try:
+ row = json.loads(line)
+ if not isinstance(row, dict) or row.get('seq') != expected:
+ continue
+ _check(schema.session_event(stored=True), row)
+ except (ValueError, UnicodeDecodeError, SessionError):
+ continue
+ expected += 1
+ if row['seq'] > after:
+ rows.append(row)
+ if len(rows) >= limit:
+ break
+ return rows
+
+ def events(self, sid, *, after=0, limit=500) -> list[dict]:
+ _check(schema.session_schema('events'), dict(after=after, limit=limit))
+ with self.lock:
+ self._get(sid)
+ return self._events(sid, after, limit)
+
+ async def wait(self, sid, *, after, seconds, types=None, by=None) -> list[dict]:
+ _check(schema.session_schema('events'), dict(after=after, wait=seconds))
+ if types is not None:
+ _check(schema.array(schema.enum(('message', 'plan', 'step', 'confirm', 'control')), high=5), types)
+ if by is not None:
+ _check(schema.enum(('user', 'agent', 'builtin', 'system')), by)
+ loop = asyncio.get_running_loop()
+ signal = asyncio.Event()
+ waiter = (loop, signal)
+ deadline = loop.time() + seconds
+ cursor = after
+ def register():
+ with self.lock:
+ self._get(sid)
+ self._waiters.setdefault(sid, set()).add(waiter)
+
+ def read():
+ with self.lock:
+ rows = self._events(sid, cursor, self.max_events)
+ found = [row for row in rows if (types is None or row['type'] in types)
+ and (by is None or row['by'] == by)]
+ return found[:500], rows[-1]['seq'] if rows else cursor
+
+ def remove():
+ with self.lock:
+ waiters = self._waiters.get(sid)
+ if waiters is not None:
+ waiters.discard(waiter)
+ if not waiters:
+ self._waiters.pop(sid)
+
+ async def offload(work):
+ # A cancelled to_thread keeps running. Finish registration/scanning before
+ # removing its waiter, so a disconnect cannot leave a late registration.
+ task = asyncio.create_task(asyncio.to_thread(work))
+ try:
+ return await asyncio.shield(task)
+ except asyncio.CancelledError:
+ await asyncio.gather(task, return_exceptions=True)
+ raise
+
+ try:
+ await offload(register)
+ while True:
+ # Event operations stay on their loop. Clear before scanning: writes
+ # after the scan schedule set() on the loop and cannot lose a wakeup.
+ signal.clear()
+ found, cursor = await offload(read)
+ if found:
+ return found
+ remaining = deadline - loop.time()
+ if remaining <= 0:
+ return []
+ try:
+ await asyncio.wait_for(signal.wait(), remaining)
+ except asyncio.TimeoutError:
+ return []
+ finally:
+ await offload(remove)
+
+ def confirmation(self, sid, digest) -> dict | None:
+ """The newest server confirmation in this session for one operation digest, with its latest answer."""
+ with self.lock:
+ self._get(sid)
+ rows = [e for e in self._ids[sid].values() if e['type'] == 'confirm' and e.get('digest') == digest]
+ return deepcopy(max(rows, key=lambda e: e['seq'])) if rows else None
+
+ def latest_for(self, client) -> str | None:
+ with self.lock:
+ rows = [row for sid, row in self._meta.items() if client in self._clients[sid]]
+ return max(rows, key=lambda r: (r['updated_at'], r['id']))['id'] if rows else None
+
+ def stopped(self, sid) -> bool:
+ with self.lock:
+ return self._get(sid)['stopped']
+
+ def unread(self, sid, reader: str) -> list[dict]:
+ _check(schema.string(80), reader)
+ with self.lock:
+ meta = self._get(sid)
+ key = (sid, reader)
+ after = self._readers.get(key, self._initial_seq[sid])
+ self._readers[key] = meta['last_seq']
+ if self._user_seq.get(sid, 0) <= after:
+ return []
+ rows = self._events(sid, after, self.max_events)
+ return [row for row in rows if row['by'] == 'user' and (row['type'] == 'message'
+ or row['type'] == 'confirm' and row['state'] in ('approved', 'declined'))]
+
+
+class Confirmations:
+ """Agent operations that wait for the user's approval (sessions-contract.md section 7).
+
+ gate() runs inside the operation before anything is saved. A request is
+ identified by errors.CONFIRM, its digest; an approval lets that exact
+ request through once.
+ """
+ def __init__(self, path: Path, sessions: Sessions):
+ self.path, self.sessions = Path(path), sessions
+ self.lock = threading.Lock()
+ self._used = set()
+
+ def settings(self) -> dict:
+ try:
+ value = json.loads(self.path.read_text('utf-8'))
+ _check(schema.confirm_settings(), value)
+ except (OSError, ValueError, SessionError):
+ value = {}
+ return dict(schema.CONFIRM_DEFAULTS, **value)
+
+ def update(self, values: dict) -> dict:
+ _check(schema.confirm_settings(), values)
+ with self.lock:
+ value = dict(self.settings(), **values)
+ temporary = self.path.with_name('.' + self.path.name + '.tmp')
+ temporary.parent.mkdir(parents=True, exist_ok=True)
+ temporary.write_text(json.dumps(value), 'utf-8')
+ os.replace(temporary, self.path)
+ return value
+
+ def gate(self, action, *, by, estimate_seconds, refs, question):
+ sid, digest = errors.SESSION.get(), errors.CONFIRM.get()
+ if by != 'agent' or sid is None or digest is None:
+ return
+ policy = self.settings()
+ if action == 'start' and not policy['start'] or action == 'reshoot' and (
+ policy['reshoot_seconds'] is None or estimate_seconds is None
+ or estimate_seconds < policy['reshoot_seconds']):
+ return
+ with self.lock:
+ row = self.sessions.confirmation(sid, digest)
+ if row is not None and row['state'] == 'approved' and row['id'] not in self._used:
+ self._used.add(row['id'])
+ return
+ if row is not None and row['state'] == 'declined':
+ raise SessionError('declined_by_user', 'The user declined this operation')
+ if row is None or row['state'] != 'asked':
+ event = dict(type='confirm', id='cf' + secrets.token_hex(5), question=question, action=action,
+ refs=refs, digest=digest, state='asked')
+ if estimate_seconds is not None:
+ event['estimate_seconds'] = round(estimate_seconds)
+ row = self.sessions.append(sid, event, by='system')
+ raise SessionError('needs_confirmation', 'Waiting for the user',
+ details=[dict(confirm=row['id'], seconds=row.get('estimate_seconds'))])
diff --git a/freevideo_engine/agent/spec.py b/freevideo_engine/agent/spec.py
new file mode 100644
index 0000000..ae49600
--- /dev/null
+++ b/freevideo_engine/agent/spec.py
@@ -0,0 +1,248 @@
+"""Normalize schema-validated job values; derive geometry, sampling and dependencies."""
+import json
+import math
+import re
+import secrets
+from . import schema as contract
+
+QUALITY, ASPECTS = contract.QUALITY, contract.ASPECTS
+KINDS = tuple(contract.KINDS)
+FRAMES = ('first', 'last')
+MAX_SEED = contract.generate()['properties']['seed']['maximum']
+JOB_ID = re.compile(contract.JOB['pattern'].strip('^$'))
+LIBRARY_ID = re.compile(contract.SAVED['pattern'].strip('^$'))
+SLUG = re.compile(contract.SLUG['pattern'].strip('^$'))
+
+
+class SpecError(ValueError):
+ def __init__(self, errors):
+ self.errors = errors if isinstance(errors, list) else [errors]
+ super().__init__('; '.join('%s: %s' % (e['path'] or '/', e['message']) for e in self.errors))
+
+
+def fail(path, message):
+ raise SpecError(contract.diagnostic(path, message, None))
+
+
+# Field checks for values no route schema describes: screenplays and filming records.
+def _bool(value, path):
+ if type(value) is not bool:
+ fail(path, 'must be true or false')
+ return value
+
+
+def _int(value, path, low, high):
+ if type(value) is not int or not low <= value <= high:
+ fail(path, 'must be an integer from %d to %d' % (low, high))
+ return value
+
+
+def _number(value, path, low, high):
+ if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) \
+ or not low <= value <= high:
+ fail(path, 'must be a number from %g to %g' % (low, high))
+ return float(value)
+
+
+def _text(value, path, limit, *, empty=False):
+ if not isinstance(value, str) or (not empty and not value.strip()) or len(value) > limit or '\x00' in value:
+ fail(path, 'must be a non-empty string of at most %d characters' % limit if not empty
+ else 'must be a string of at most %d characters' % limit)
+ return value
+
+
+def check(value, *, local=False):
+ """One job as submission accepts it: checked against the shared definition, then normalized.
+
+ local=True admits local file paths, exactly as Jobs.submit does for in-process callers;
+ the default is the stricter content-only boundary of external HTTP.
+ """
+ contract.validate(contract.job_schema(local=local), value)
+ return normalize(value)
+
+
+def new_id():
+ return 'j' + secrets.token_hex(6)
+
+
+def media_item(value, path, *, image=False, frame_default=None):
+ if isinstance(value, str):
+ value = {'file': value}
+ value = dict(value) if isinstance(value, dict) else value
+ if isinstance(value, dict) and frame_default is not None and any(k in value for k in ('from_job', 'library')):
+ value.setdefault('frame', frame_default)
+ errors = contract.issues(contract.media(image, local=True), value, path)
+ if errors:
+ raise SpecError(errors)
+ return value
+
+
+CUT = re.compile(r'\[Shot\s+\d+\]\s*At\s+(\d{1,2}):(\d{1,2}(?:\.\d+)?)')
+
+
+def cut_times(text):
+ """Seconds of each "[Shot N] At MM:SS.mmm" cut in a prompt; none for a prompt taken from another job."""
+ if not isinstance(text, str):
+ return []
+ return [int(minutes) * 60 + float(seconds) for minutes, seconds in CUT.findall(text)]
+
+
+def dependencies(item):
+ """Job ids a normalized spec reads from."""
+ found = set(item.get('after', ()))
+ def walk(value):
+ if isinstance(value, dict):
+ if isinstance(value.get('from_job'), str):
+ found.add(value['from_job'])
+ for key, child in value.items():
+ if key != 'edit':
+ walk(child)
+ elif isinstance(value, list):
+ for child in value:
+ walk(child)
+ walk({key: value for key, value in item.items() if key not in ('after', 'metadata')})
+ return sorted(found)
+
+
+def _common(value):
+ return {k: value[k] for k in ('label', 'project', 'metadata', 'after') if k in value}
+
+
+def canvas_size(value):
+ if 'aspect' in value or 'megapixels' in value:
+ a, b = map(int, value.get('aspect', '16:9').split(':'))
+ total = value.get('megapixels', contract.generate()['properties']['megapixels']['default']) * 1024 ** 2
+ width = round(math.sqrt(total * a / b) / 32) * 32
+ height = round(math.sqrt(total * b / a) / 32) * 32
+ properties = contract.generate()['properties']
+ if any(contract.issues(properties[k], v) for k, v in (('width', width), ('height', height))):
+ fail('/aspect', 'an aspect and megapixels producing dimensions within the width/height contract')
+ return width, height
+ properties = contract.generate()['properties']
+ return tuple(value.get(k, properties[k]['default']) for k in ('width', 'height'))
+
+
+def sampling(value):
+ quality = value.get('quality', contract.generate()['properties']['quality']['default'])
+ two, base, refine = QUALITY[quality]
+ custom = value.get('sampling', {})
+ two, base, refine = custom.get('two_pass', two), custom.get('base_steps', base), custom.get('refine_steps', refine)
+ if custom:
+ quality = next((k for k, v in QUALITY.items() if v == (two, base, refine)), 'custom')
+ return dict(quality=quality, two_pass=two, base_steps=base, refine_steps=refine)
+
+
+def generation_media(value):
+ if not value:
+ return {}
+ result = {role: media_item(value[role], '/media/' + role, image=True) for role in FRAMES if value.get(role) is not None}
+ if value.get('references'):
+ result['references'] = [media_item(v, '/media/references/%d' % i) for i, v in enumerate(value['references'])]
+ return result
+
+
+def task(media):
+ if media.get('references'):
+ return 'ref2va'
+ if 'first' in media and 'last' in media:
+ return 'fl2va'
+ return 'i2va' if 'first' in media else 'l2va' if 'last' in media else 't2va'
+
+
+def saved_length(canvas, seconds):
+ """Frames and seconds of the saved video. One generation keeps its aligned canvas; a longer video is
+ made in blocks and joined to exactly the planned whole seconds."""
+ from ..chain_plan import PlanError, plan
+ try:
+ planned = plan(seconds)
+ except PlanError:
+ return canvas['frames'], canvas['seconds']
+ if planned['single']:
+ return canvas['frames'], canvas['seconds']
+ return planned['frames'], planned['frames'] / canvas['fps']
+
+
+def normalize(value):
+ # Local Python callers retain local media refs. HTTP validates its stricter
+ # (content-only) schema first; the client adapts local refs before transport.
+ contract.validate_job(value, local=True)
+ kind = value.get('kind', 'generate')
+ value = {k: v for k, v in value.items() if v is not None or k == 'seed'}
+ original = value
+ value = contract.defaults(contract.KINDS[kind](local=True), value)
+ result = dict(kind=kind, **_common(value))
+ if kind == 'generate':
+ result['force_regenerate'] = value['force_regenerate']
+ if value.get('refine_from'):
+ ref = value['refine_from']
+ result['refine_from'] = {'from_job' if JOB_ID.fullmatch(ref) else 'library': ref}
+ else:
+ from ..geometry import geometry
+ width, height = canvas_size(original)
+ canvas = geometry(width, height, seconds=value['seconds'])
+ frames, output_seconds = (canvas['frames'], canvas['seconds']) if value.get('continue_from') else \
+ saved_length(canvas, value['seconds'])
+ result.update(prompt=value['prompt'], width=width, height=height, seconds=float(value['seconds']),
+ frames=frames, output_seconds=output_seconds, seed_random=value['seed'] is None,
+ seed=secrets.randbelow(MAX_SEED + 1) if value['seed'] is None else value['seed'],
+ preview=value['preview'], media=generation_media(value.get('media')), **sampling(value))
+ result['task'] = task(result['media'])
+ if value.get('continue_from'):
+ result['continue_from'] = dict(value['continue_from'])
+ result['loras'] = [dict(name=row, strength=1.) if isinstance(row, str) else {'strength': 1., **row}
+ for row in value['loras']]
+ elif kind == 'assemble':
+ result['clips'] = []
+ for row in value['clips']:
+ if isinstance(row, str):
+ row = {'from_job' if JOB_ID.fullmatch(row) else 'library' if LIBRARY_ID.fullmatch(row) else 'file': row}
+ result['clips'].append(dict(row))
+ result.update({k: value[k] for k in ('transition', 'transition_seconds', 'width', 'height', 'audio', 'name') if k in value})
+ elif kind == 'vlm':
+ rows = value['questions'] if isinstance(value['questions'], list) else [value['questions']]
+ result['questions'] = []
+ for row in rows:
+ row = {'text': row} if isinstance(row, str) else row
+ item = dict(text=row['text'], images=[media_item(v, '/questions/images', image=True) for v in row.get('images', [])])
+ if row.get('video'):
+ video = row['video']
+ item['frames'] = video.get('frames', 6) if isinstance(video, dict) else 6
+ item['video'] = media_item({k: v for k, v in video.items() if k != 'frames'} if isinstance(video, dict) else video, '/questions/video')
+ result['questions'].append(item)
+ result.update({k: value[k] for k in ('format', 'max_tokens', 'system') if k in value})
+ elif kind == 'export':
+ result.update(editor_project=value['editor_project'], revision=value['revision'])
+ elif kind == 'image_edit':
+ result.update(image=value['image'], revision=value['revision'])
+ else:
+ result.update(text=value['text'], seconds=float(value['seconds']), media=generation_media(value.get('media')))
+ result['depends_on'] = dependencies(result)
+ return result
+
+
+def comfy_prompt(spec, node, *, prompt, assets, refine_from=''):
+ """The ComfyUI API-format graph for one generate job; media are files in ComfyUI input."""
+ inputs = dict(text=prompt, width=spec['width'], height=spec['height'], seconds=spec['seconds'],
+ seed=spec['seed'], two_pass=spec['two_pass'], base_steps=spec['base_steps'],
+ refine_steps=spec['refine_steps'], force_regenerate=spec['force_regenerate'],
+ preview=spec['preview'], refine_from=refine_from)
+ graph = {node: {'class_type': 'FreeVideoGenerate', 'inputs': inputs,
+ '_meta': {'title': 'FreeVideo · ' + (spec.get('label') or 'Agent job')}}}
+ if assets:
+ graph[node + 'm'] = {'class_type': 'FreeVideoMedia', 'inputs': {'assets': json.dumps(assets)},
+ '_meta': {'title': 'FreeVideo · Media'}}
+ inputs['media'] = [node + 'm', 0]
+ if spec.get('loras'):
+ graph[node + 'l'] = {'class_type': 'FreeVideoLoRAStack',
+ 'inputs': {'adapters': json.dumps([dict(r, enabled=True) for r in spec['loras']])},
+ '_meta': {'title': 'FreeVideo · LoRAs'}}
+ inputs['loras'] = [node + 'l', 0]
+ return graph
+
+
+def upscale_prompt(node, preview_video):
+ """A second pass of a finished preview; the bridge restores the preview's own request."""
+ inputs = dict(text='(continues the preview request)', width=1344, height=768, seconds=10., seed=0,
+ two_pass=True, base_steps=8, refine_steps=3, force_regenerate=False, preview=False,
+ refine_from=preview_video)
+ return {node: {'class_type': 'FreeVideoGenerate', 'inputs': inputs, '_meta': {'title': 'FreeVideo · Second pass'}}}
diff --git a/freevideo_engine/backends/mps.py b/freevideo_engine/backends/mps.py
index bc3b7f6..64917b2 100644
--- a/freevideo_engine/backends/mps.py
+++ b/freevideo_engine/backends/mps.py
@@ -159,6 +159,7 @@ class MPSBackend(DeviceBackend):
'mps_int8.py')},
runtime_source_sha256={name: hashlib.sha256((Path(__file__).parent.parent / name).read_bytes()).hexdigest()
for name in ('macos_runtime.py', 'macos_vdn.py', 'macos_decode.py', 'macos_encoder.py',
+ 'macos_encoder_attention.py', 'macos_encoder_linear.py',
'macos_compute.py', 'macos_stages.py', 'macos_decode_tiles.py',
'latent_upscale.py')})
diff --git a/freevideo_engine/backends/mps_nvfp4.py b/freevideo_engine/backends/mps_nvfp4.py
index 3f4b272..b20597c 100644
--- a/freevideo_engine/backends/mps_nvfp4.py
+++ b/freevideo_engine/backends/mps_nvfp4.py
@@ -30,7 +30,29 @@ def _kernel():
''')
-def decode_weight(weight, dtype, device):
+def row_storage(weight, row_range):
+ """Select output rows on the host, including only their 128-row scale tiles.
+
+ NVFP4 scales are swizzled in independent 128 by 4 tiles. Selecting packed
+ rows alone and slicing the swizzled scale vector at the same index is wrong.
+ Unblock the intersecting complete row tiles, then take the requested rows.
+ This also supports unaligned ranges and padded original shapes.
+ """
+ from comfy_kitchen.float_utils import from_blocked
+ packed, params = weight._qdata, weight._params
+ start, stop = row_range
+ if not (type(start) is int and type(stop) is int
+ and 0 <= start < stop <= params.orig_shape[0]):
+ raise ValueError('Invalid NVFP4 output row range')
+ columns = packed.shape[1] * 2
+ first, last = start // 128, (stop + 127) // 128
+ tile_size = 128 * ((columns // 16 + 3) // 4 * 4)
+ blocked = params.block_scale.reshape(-1)[first * tile_size:last * tile_size]
+ scales = from_blocked(blocked, num_rows=(last - first) * 128, num_cols=columns // 16)
+ return packed[start:stop], scales[start - first * 128:stop - first * 128].float()
+
+
+def decode_weight(weight, dtype, device, *, row_range=None):
"""Match nvfp4_weight's nibble order, scale order and padded output view."""
import torch
from comfy_kitchen.float_utils import from_blocked
@@ -54,7 +76,12 @@ def decode_weight(weight, dtype, device):
raise ValueError('Invalid NVFP4 scale or original shape geometry')
# Unblocking the small scale plane is CPU work; the expanded weight never
# occupies a full CPU FP32 matrix. Preserve the reference's two multiplies.
- scales = from_blocked(params.block_scale, num_rows=rows, num_cols=columns // 16).float()
+ if row_range is None:
+ scales = from_blocked(params.block_scale, num_rows=rows, num_cols=columns // 16).float()
+ else:
+ packed, scales = row_storage(weight, row_range)
+ rows = row_range[1] - row_range[0]
+ original = (rows, original[1])
result = torch.empty((rows, columns), dtype=dtype, device=device)
packed_device = packed.to(device)
scales_device = scales.contiguous().to(device)
diff --git a/freevideo_engine/bootstrap.py b/freevideo_engine/bootstrap.py
index f60466c..cc077bb 100644
--- a/freevideo_engine/bootstrap.py
+++ b/freevideo_engine/bootstrap.py
@@ -190,7 +190,7 @@ def dependency_status(root, layout='unified', system=None):
'engine': ['torch', 'torchvision', 'triton', 'transformers', 'accelerate', 'peft', 'safetensors',
'huggingface-hub', 'omegaconf', 'pyyaml', 'einops', 'numpy', 'pillow', 'av',
'psutil', 'tqdm', 'importlib-metadata', 'requests', 'httpx', 'socksio', 'pysocks',
- 'modelscope-hub', 'hf-xet', 'sageattention', 'diffusers', 'freevideo-engine'],
+ 'modelscope-hub', 'hf-xet', 'quickjs', 'sageattention', 'diffusers', 'freevideo-engine'],
'encoder': ['torch', 'torchvision', 'torchaudio', 'freevideo-engine'] +
[s.strip() for s in (SOURCE / 'constraints/encoder-runtime.txt').read_text(encoding='utf-8').splitlines()
if s.strip() and not s.startswith('#')]}
diff --git a/freevideo_engine/chain_join.py b/freevideo_engine/chain_join.py
new file mode 100644
index 0000000..83cfcbb
--- /dev/null
+++ b/freevideo_engine/chain_join.py
@@ -0,0 +1,562 @@
+"""Join finished chain blocks end to end into one saved video.
+
+The picture is copied packet by packet, except for a few closing frames when
+needed to reach an exact requested length with matching codec parameters. The
+sound is decoded and encoded once as a single stream: every block's sound
+follows the previous block's sound, not its own first frame, which keeps a
+long chain in step.
+"""
+from datetime import datetime
+from fractions import Fraction
+import json
+import logging
+import os
+from pathlib import Path
+import shutil
+import uuid
+
+FPS = 24
+SEAM_TAIL = 12000
+SEAM_HEAD = 240
+
+
+class JoinCancelled(InterruptedError):
+ pass
+
+
+class _ExactEndFailed(Exception):
+ pass
+
+
+def _check(cancelled):
+ if cancelled is not None and cancelled():
+ raise JoinCancelled()
+
+
+def _shape(stream):
+ context = stream.codec_context
+ return (context.name, context.width, context.height, context.pix_fmt, stream.time_base,
+ stream.average_rate, bytes(context.extradata or b''))
+
+
+def _last_kept(path, wanted):
+ """The frame a file can end on at or just after `wanted` frames, or None to keep all of it.
+
+ Packets are copied, not encoded, so a file may only end on a frame that later frames do not
+ complete: one that is shown after everything decoded before it. That is at most a few frames on.
+ """
+ import av
+ with av.open(str(path)) as container:
+ video = container.streams.video[0]
+ step = int(Fraction(1, video.average_rate) / video.time_base)
+ start = latest = None
+ for packet in container.demux(video):
+ if packet.dts is None:
+ continue
+ if start is None:
+ start = video.start_time if video.start_time is not None else packet.pts
+ if latest is None or packet.pts > latest:
+ latest = packet.pts
+ if (latest - start) // step >= wanted - 1:
+ return (latest - start) // step
+ return None
+
+
+def _exact_tail(source, target, wanted, cancelled=None):
+ """Prepare at most three closing frames, or leave the packet-copy ending alone."""
+ import av
+ temporary = target.with_name('.join-tail-' + uuid.uuid4().hex + '.mp4')
+ try:
+ with av.open(str(source)) as container:
+ video = container.streams.video[0]
+ shape = _shape(video)
+ if shape[0] != 'h264':
+ return None
+ step = int(Fraction(1, video.average_rate) / video.time_base)
+ begin = video.start_time
+ prefix = count = 0
+ latest = previous_dts = None
+ for packet in container.demux(video):
+ _check(cancelled)
+ if packet.dts is None:
+ continue
+ if begin is None:
+ begin = packet.pts
+ if latest is None or packet.pts > latest:
+ latest = packet.pts
+ shown = (latest - begin) // step
+ if shown >= wanted - 1:
+ break
+ prefix = shown + 1
+ count += 1
+ previous_dts = packet.dts
+ if count != prefix or not 1 <= wanted - prefix <= 3:
+ return None
+ # Seek to the preceding key frame; only the remaining shown frames are encoded.
+ container.seek(begin + prefix * step, stream=video, backward=True)
+ with av.open(str(temporary), 'w', format='mp4') as output:
+ tail = output.add_stream('libx264', rate=FPS)
+ tail.width, tail.height, tail.pix_fmt = shape[1:4]
+ tail.time_base = shape[4]
+ # decode_to_file's encode_video uses these libx264 defaults and yuv420p.
+ encoded = 0
+ for frame in container.decode(video):
+ _check(cancelled)
+ position = (frame.pts - begin) // step
+ if position < prefix:
+ continue
+ if position != prefix + encoded:
+ return None
+ frame.pts, frame.time_base = encoded, Fraction(1, FPS)
+ frame.pict_type = av.video.frame.PictureType.NONE
+ for packet in tail.encode(frame):
+ output.mux(packet)
+ encoded += 1
+ if encoded == wanted - prefix:
+ break
+ if encoded != wanted - prefix:
+ return None
+ for packet in tail.encode(None):
+ output.mux(packet)
+ with av.open(str(temporary)) as container:
+ tail = container.streams.video[0]
+ if _shape(tail) != shape:
+ return None
+ packets = [packet for packet in container.demux(tail) if packet.dts is not None]
+ if len(packets) != encoded or not packets[0].is_keyframe:
+ return None
+ if sorted(packet.pts for packet in packets) != [number * step for number in range(encoded)]:
+ return None
+ # A one- or two-frame encode has less delay than the block. Keep the
+ # copied decoding cadence while leaving the new display timestamps unchanged.
+ shift = previous_dts - begin + step - (packets[0].dts + prefix * step)
+ for packet in packets:
+ packet.dts += shift
+ if packet.dts > packet.pts:
+ return None
+ stamps = [previous_dts - begin] + [packet.dts + prefix * step for packet in packets]
+ if any(later <= earlier for earlier, later in zip(stamps, stamps[1:])):
+ return None
+ _check(cancelled)
+ return prefix, packets
+ except JoinCancelled:
+ raise
+ except Exception:
+ return None
+ finally:
+ temporary.unlink(missing_ok=True)
+
+
+def join_files(sources, target, cancelled=None, frames=None):
+ """Write `target` from `sources` in order; returns the joined frame and sample counts.
+
+ `frames`: stop at this length when a compatible short tail can close it exactly,
+ otherwise keep the packet-copy ending at or just after it.
+ """
+ sources = list(sources)
+ try:
+ return _join_files(sources, target, cancelled, frames)
+ except _ExactEndFailed:
+ # A late mux or validation error must also leave the original ending available.
+ return _join_files(sources, target, cancelled, frames, exact=False)
+
+
+def _join_files(sources, target, cancelled, frames, exact=True):
+ import av
+ from .comfy_metadata import _copy_stream
+ try:
+ from .comfy_continuation import audio_lead_in, apply_audio_lead_in
+ except ImportError:
+ audio_lead_in = apply_audio_lead_in = None
+ sources, target = [Path(source) for source in sources], Path(target)
+ if len(sources) < 2:
+ raise ValueError('Joining needs at least two videos')
+ if target.exists() or target.is_symlink():
+ raise ValueError('The joined video already exists')
+ target.parent.mkdir(parents=True, exist_ok=True)
+ temporary = target.with_name('.join-' + uuid.uuid4().hex + '.mp4')
+ wanted, frames, samples = frames, 0, 0
+ used_tail = False
+ try:
+ with av.open(str(sources[0])) as first:
+ if len(first.streams.video) != 1:
+ raise ValueError('A block has no single picture stream')
+ shape = _shape(first.streams.video[0])
+ sound = first.streams.audio[0] if first.streams.audio else None
+ rate = sound.codec_context.sample_rate if sound is not None else None
+ layout = sound.codec_context.layout.name if sound is not None else None
+ bit_rate = max(sound.codec_context.bit_rate or 0, 192000) if sound is not None else None
+ step = Fraction(1, shape[5]) / shape[4]
+ if shape[5] != FPS or step.denominator != 1:
+ raise ValueError('The blocks are not 24 frames per second videos')
+ step = int(step)
+ with av.open(str(temporary), 'w', format='mp4',
+ options={'movflags': 'use_metadata_tags+faststart'}) as output:
+ picture = audio = fifo = joined_audio = None
+ for index, source in enumerate(sources):
+ _check(cancelled)
+ if wanted is not None and frames >= wanted and picture is not None:
+ break
+ last = _last_kept(source, wanted - frames) if wanted is not None else None
+ with av.open(str(source)) as container:
+ if len(container.streams.video) != 1 or _shape(container.streams.video[0]) != shape:
+ raise ValueError('The blocks differ in size or encoding')
+ if bool(container.streams.audio) != (sound is not None):
+ raise ValueError('Only some of the blocks have sound')
+ video = container.streams.video[0]
+ tail = (_exact_tail(source, target, wanted - frames, cancelled)
+ if exact and last is not None and last + 1 > wanted - frames else None)
+ copied_last = tail[0] - 1 if tail is not None else last
+ if tail is not None:
+ used_tail = True
+ last = wanted - frames - 1
+ if picture is None:
+ picture = _copy_stream(output, video)
+ if sound is not None:
+ audio = output.add_stream('aac', rate=rate)
+ audio.layout = layout
+ audio.bit_rate = bit_rate
+ audio.codec_context.time_base = Fraction(1, rate)
+ fifo = av.AudioFifo()
+ joined_audio = _JoinedAudio(output, audio, fifo, rate, layout,
+ audio_lead_in, apply_audio_lead_in, cancelled)
+ streams = [video] + ([container.streams.audio[0]] if sound is not None else [])
+ shift, count = None, 0
+ # A decoder returns the encoder's padding after the last sample; the stream's own
+ # length says where the sound ends. Left in, every block would end 20 ms late.
+ length = streams[-1].duration if sound is not None else None
+ limit = round(length * streams[-1].time_base * rate) if length is not None else None
+ if joined_audio is not None:
+ following = sources[index + 1] if last is None and index + 1 < len(sources) else None
+ # Selecting the final frame of a whole block leaves its existing sound limit alone.
+ total_frames = (frames + last + 1 if last is not None
+ and (not video.frames or last + 1 < video.frames) else None)
+ joined_audio.start(source, streams[-1], limit, last, following, total_frames)
+ for packet in container.demux(*streams):
+ if packet.dts is None:
+ continue
+ if packet.stream is video:
+ if shift is None:
+ # The first packet of a file is its first shown frame's key frame.
+ begin = video.start_time if video.start_time is not None else packet.pts
+ shift = frames * step - begin
+ if copied_last is not None and (packet.pts - begin) // step > copied_last:
+ continue
+ packet.pts += shift
+ packet.dts += shift
+ packet.stream = picture
+ output.mux(packet)
+ count += 1
+ if not count % 48:
+ _check(cancelled)
+ continue
+ for decoded in packet.decode():
+ joined_audio.write(decoded)
+ if tail is not None:
+ for packet in tail[1]:
+ _check(cancelled)
+ packet.pts += (frames + tail[0]) * step
+ packet.dts += (frames + tail[0]) * step
+ packet.stream = picture
+ output.mux(packet)
+ count += 1
+ if joined_audio is not None:
+ joined_audio.end()
+ if not count:
+ raise ValueError('A block has no picture')
+ frames += count
+ if audio is not None:
+ samples = joined_audio.finish()
+ for packet in audio.encode(None):
+ output.mux(packet)
+ _check(cancelled)
+ with av.open(str(temporary)) as check:
+ if check.streams.video[0].frames != frames:
+ raise ValueError('The joined video is incomplete')
+ os.replace(temporary, target)
+ return dict(exact_end=wanted is not None and frames == wanted, frames=frames, width=shape[1], height=shape[2],
+ audio_samples=samples, sample_rate=rate,
+ seams_repaired=joined_audio.seams_repaired if joined_audio is not None else 0)
+ except JoinCancelled:
+ raise
+ except Exception as error:
+ if used_tail:
+ raise _ExactEndFailed() from error
+ raise
+ finally:
+ temporary.unlink(missing_ok=True)
+
+
+class _JoinedAudio:
+ """Keep native seam windows out of the encoder until the next block's head is ready."""
+ def __init__(self, output, stream, fifo, rate, layout, read_lead, apply_lead, cancelled=None):
+ self.output, self.stream, self.fifo = output, stream, fifo
+ self.rate, self.layout = rate, layout
+ self.read_lead, self.apply_lead = read_lead, apply_lead
+ self.cancelled, self.next_head = cancelled, None
+ self.warned = False
+ self.written = self.seams_repaired = 0
+
+ def start(self, source, stream, limit, last=None, following=None, total_frames=None):
+ import av
+ context = stream.codec_context
+ self.source, self.following = str(source), str(following) if following is not None else None
+ self.limit, self.heard, self.kept = limit, 0, 0
+ # end() has released the previous tail and flushed its resampler. Count
+ # both encoded samples and those still waiting in the encoder queue.
+ joined = self.written + self.fifo.samples if total_frames is not None else 0
+ if last is not None:
+ cut = (max(0, round(total_frames * self.rate / FPS) - joined) if total_frames is not None
+ else round((last + 1) * self.rate / FPS))
+ self.limit = min(self.limit, cut) if self.limit is not None else cut
+ self.tail, self.released = None, False
+ self.head = self.next_head[1] if self.next_head is not None and self.next_head[0] == self.source else None
+ self.next_head, self.head_position = None, 0
+ self.resampler = av.AudioResampler(format='fltp', layout=self.layout, rate=self.rate)
+ self.native = (av.AudioResampler(format='fltp', layout='stereo', rate=32000)
+ if context.sample_rate == 32000 and context.layout.name == 'stereo' else None)
+ self.native_limit = round(stream.duration * stream.time_base * 32000) if stream.duration is not None else None
+ if last is not None:
+ cut = (max(0, round(total_frames * 32000 / FPS) - round(joined * 32000 / self.rate))
+ if total_frames is not None else round((last + 1) * 32000 / FPS))
+ self.native_limit = min(self.native_limit, cut) if self.native_limit is not None else cut
+
+ def write(self, decoded):
+ if self.native is None:
+ self._encode(self.resampler.resample(decoded))
+ else:
+ for frame in self.native.resample(decoded):
+ self._native(frame)
+
+ def _native(self, frame):
+ import numpy as np
+ data = np.array(frame.to_ndarray().T, dtype=np.float32, order='C', copy=True)
+ if self.head is not None:
+ count = min(SEAM_HEAD - self.head_position, len(data))
+ data[:count] = self.head[self.head_position:self.head_position + count]
+ self.head_position += count
+ if self.head_position == SEAM_HEAD:
+ self.head = None
+ if self.released:
+ self._queue(data)
+ return
+ keep = len(data) if self.native_limit is None else max(0, min(len(data), self.native_limit - self.kept))
+ self.kept += keep
+ self._hold(data[:keep])
+ if self.native_limit is not None and self.kept >= self.native_limit:
+ self._release()
+ if keep < len(data):
+ # Keep decoder padding available to the existing resampler; the output limit still removes it.
+ self._queue(data[keep:])
+
+ def _hold(self, data):
+ import numpy as np
+ if not len(data):
+ return
+ if self.tail is not None:
+ data = np.concatenate((self.tail, data))
+ if len(data) > SEAM_TAIL:
+ self._queue(data[:-SEAM_TAIL])
+ self.tail = data[-SEAM_TAIL:].copy()
+
+ def _release(self):
+ tail = self.tail
+ if tail is not None and len(tail) == SEAM_TAIL and self.following is not None:
+ try:
+ head = _audio_head(self.following, self.cancelled)
+ if head is not None:
+ lead = self.read_lead(self.following, previous=self.source) if self.read_lead is not None else None
+ if lead is not None:
+ repaired_tail, repaired_head = tail.copy(), head.copy()
+ if self.apply_lead(repaired_tail, repaired_head, lead):
+ tail = repaired_tail
+ self.next_head = self.following, repaired_head
+ self.seams_repaired += 1
+ else:
+ self._warn()
+ except JoinCancelled:
+ raise
+ except Exception:
+ self._warn()
+ if tail is not None:
+ self._queue(tail)
+ self.tail, self.released = None, True
+
+ def _warn(self):
+ if not self.warned:
+ logging.warning('[FreeVideo] A chain sound seam could not be repaired; the blocks are joined as they are')
+ self.warned = True
+
+ def _queue(self, data):
+ import av
+ import numpy as np
+ frame = av.AudioFrame.from_ndarray(np.ascontiguousarray(data.T), format='fltp', layout='stereo')
+ frame.sample_rate = 32000
+ self._encode(self.resampler.resample(frame))
+
+ def _encode(self, frames):
+ self.heard, self.written = _encode(self.output, self.stream, self.fifo, frames, self.heard, self.limit,
+ self.written, self.rate, self.layout)
+
+ def end(self):
+ if self.native is not None:
+ for frame in self.native.resample(None):
+ self._native(frame)
+ if not self.released:
+ self._release()
+ self._encode(self.resampler.resample(None))
+
+ def finish(self):
+ return _encode(self.output, self.stream, self.fifo, [], 0, None,
+ self.written, self.rate, self.layout, final=True)[1]
+
+
+def _audio_head(source, cancelled):
+ """Decode just the next block's kept native head, without changing its files."""
+ import av
+ import numpy as np
+ _check(cancelled)
+ with av.open(source) as container:
+ if not container.streams.audio:
+ return None
+ stream = container.streams.audio[0]
+ if stream.codec_context.sample_rate != 32000 or stream.codec_context.layout.name != 'stereo':
+ return None
+ if stream.duration is not None and round(stream.duration * stream.time_base * 32000) < SEAM_HEAD:
+ return None
+ resampler = av.AudioResampler(format='fltp', layout='stereo', rate=32000)
+ chunks, count = [], 0
+ for packet in container.demux(stream):
+ _check(cancelled)
+ if packet.dts is None:
+ continue
+ for decoded in packet.decode():
+ for frame in resampler.resample(decoded):
+ keep = min(frame.samples, SEAM_HEAD - count)
+ chunks.append(frame.to_ndarray()[:, :keep].T.copy())
+ count += keep
+ if count == SEAM_HEAD:
+ return np.ascontiguousarray(np.concatenate(chunks), dtype=np.float32)
+ return None
+
+
+def _encode(output, stream, fifo, resampled, heard, limit, written, rate, layout, final=False):
+ """Queue one block's resampled sound up to its length and encode whole encoder frames; `final` writes the rest."""
+ import av
+ import numpy as np
+ for frame in resampled:
+ keep = frame.samples if limit is None else min(frame.samples, limit - heard)
+ if keep <= 0:
+ continue
+ if keep < frame.samples:
+ frame = av.AudioFrame.from_ndarray(np.ascontiguousarray(frame.to_ndarray()[:, :keep]),
+ format='fltp', layout=layout)
+ frame.sample_rate = rate
+ heard += keep
+ frame.pts = None # the queue counts samples itself: blocks follow one another without gaps
+ fifo.write(frame)
+ size = stream.codec_context.frame_size or 1024
+ while fifo.samples >= size or final and fifo.samples:
+ frame = fifo.read(min(size, fifo.samples))
+ frame.pts, frame.sample_rate, frame.time_base = written, rate, Fraction(1, rate)
+ written += frame.samples
+ for packet in stream.encode(frame):
+ output.mux(packet)
+ return heard, written
+
+
+def _request_seconds(sources):
+ total = 0.
+ for source in sources:
+ try:
+ value = json.loads(source.with_suffix('.request.json').read_text(encoding='utf-8')).get('request_seconds')
+ except (OSError, ValueError, AttributeError):
+ return None
+ if type(value) not in (int, float) or not 0 <= value < float('inf'):
+ return None
+ total += value
+ return total
+
+
+def _replace_target(root, replace, identity, sources):
+ from .comfy_library import _video, _report
+ try:
+ if not isinstance(replace, str) or not replace.startswith('FreeVideo/') or not replace.endswith('/video.mp4'):
+ return None
+ target = _video(root, replace[len('FreeVideo/'):-len('/video.mp4')])
+ if target != root / replace:
+ return None
+ report = _report(target)
+ if target.is_file() and target not in sources and report.get('chain_join', {}).get('chain') == identity:
+ return target
+ except (OSError, ValueError, AttributeError, TypeError):
+ pass
+ return None
+
+
+def join_outputs(outputs, identity, cancelled=None, frames=None, replace=None):
+ """Join relative block outputs into a saved video, replacing only this chain's earlier join."""
+ import folder_paths
+ root = Path(folder_paths.get_output_directory()).resolve()
+ sources = []
+ for output in outputs:
+ if not isinstance(output, str) or not output:
+ raise ValueError('A block has no video')
+ source = (root / output).resolve()
+ if not source.is_relative_to(root) or not source.is_file():
+ raise ValueError('A block video is missing')
+ sources.append(source)
+ # A saved video is a folder the library lists once its report says it is complete.
+ target = _replace_target(root, replace, identity, sources)
+ replacing = target is not None
+ folder = target.parent if replacing else root / 'FreeVideo' / datetime.now().strftime('%Y-%m-%d') / uuid.uuid4().hex
+ target = folder / 'video.mp4'
+ staged = target.with_name('.join-result-' + uuid.uuid4().hex + '.mp4') if replacing else target
+ path = target.with_suffix('.request.json')
+ temporary = path.with_name(path.name + '.' + uuid.uuid4().hex[:8] + '.tmp')
+ backup = target.with_name('.join-backup-' + uuid.uuid4().hex + '.mp4') if replacing else None
+ try:
+ joined = join_files(sources, staged, cancelled, frames)
+ report = dict(success=True, geometry=dict(width=joined['width'], height=joined['height'], frames=joined['frames'],
+ fps=FPS, seconds=joined['frames'] / FPS),
+ request_seconds=_request_seconds(sources), video={}, encoding={},
+ chain_join=dict(chain=identity, blocks=len(sources), seams_repaired=joined['seams_repaired'],
+ exact_end=joined['exact_end']))
+ with temporary.open('w', encoding='utf-8') as stream:
+ json.dump(report, stream, ensure_ascii=False)
+ stream.flush()
+ os.fsync(stream.fileno())
+ _check(cancelled)
+ if replacing:
+ try:
+ os.link(target, backup)
+ except OSError:
+ shutil.copyfile(target, backup)
+ _check(cancelled)
+ os.replace(staged, target)
+ try:
+ os.replace(temporary, path)
+ except BaseException:
+ if replacing:
+ os.replace(backup, target)
+ raise
+ if replacing:
+ try:
+ target.with_suffix('.thumbnail.jpg').unlink(missing_ok=True)
+ except OSError:
+ pass
+ except BaseException:
+ if not replacing:
+ for name in ('video.mp4', 'video.request.json'):
+ (folder / name).unlink(missing_ok=True)
+ try:
+ folder.rmdir()
+ except OSError:
+ pass
+ raise
+ finally:
+ temporary.unlink(missing_ok=True)
+ if replacing:
+ staged.unlink(missing_ok=True)
+ backup.unlink(missing_ok=True)
+ return target.relative_to(root).as_posix()
diff --git a/freevideo_engine/chain_plan.py b/freevideo_engine/chain_plan.py
new file mode 100644
index 0000000..99976cb
--- /dev/null
+++ b/freevideo_engine/chain_plan.py
@@ -0,0 +1,94 @@
+"""How a requested length becomes one generation or a chain of blocks.
+
+One rule for the creation panel, the editor and the server: up to 30 s is one
+generation when this device can do it; longer videos, and lengths this device
+cannot do at once, are cut into blocks that continue one another.
+"""
+import math
+
+from .geometry import geometry
+
+FPS, UNIT, OVERLAP = 24, 17, 22
+SINGLE_SECONDS, BLOCK_SECONDS, SHORTEST_BLOCK = 30, 15, 5
+MAX_SECONDS = 7200
+MAX_BLOCKS = MAX_SECONDS // SHORTEST_BLOCK
+
+
+class PlanError(ValueError):
+ def __init__(self, code, message):
+ super().__init__(message)
+ self.code = code
+
+
+def _number(value, name, whole=False):
+ if type(value) not in (int, float) or not math.isfinite(value) or value <= 0 or whole and type(value) is not int:
+ raise PlanError('invalid', '%s must be a positive %s' % (name, 'integer' if whole else 'number'))
+ return value
+
+
+def _first_frames(seconds):
+ return geometry(seconds=seconds)['frames']
+
+
+def plan(seconds, single=False, max_frames=None, single_limit_seconds=None, block_seconds=None):
+ """`max_frames`: the most frames this device generates at once for the current settings (unknown: 15 s)."""
+ _number(seconds, 'Length')
+ if type(single) is not bool:
+ raise PlanError('invalid', 'Single must be true or false')
+ try:
+ if max_frames is not None:
+ limit = _number(max_frames, 'The frame limit', whole=True)
+ else:
+ limit = _first_frames(BLOCK_SECONDS if single_limit_seconds is None
+ else _number(single_limit_seconds, 'The single generation limit'))
+ if seconds > SINGLE_SECONDS:
+ seconds = math.floor(seconds + .5) # longer videos are planned in whole seconds
+ frames = _first_frames(seconds)
+ except PlanError:
+ raise
+ except ValueError as error:
+ raise PlanError('too_short', str(error)) from None
+ if seconds > MAX_SECONDS:
+ raise PlanError('too_long', 'A video is at most 2 hours long')
+ # The longest whole-second block this device can start a video with, and continue one with.
+ first = (limit - (limit - 5) % UNIT) // FPS if limit >= 39 else 0
+ following = (limit - OVERLAP) // UNIT * UNIT // FPS if limit >= OVERLAP + UNIT else 0
+ block = BLOCK_SECONDS
+ if block_seconds is not None:
+ block = math.floor(_number(block_seconds, 'The block length') + .5)
+ if block < SHORTEST_BLOCK:
+ raise PlanError('block_too_short', 'A block is at least %d s long' % SHORTEST_BLOCK)
+ if block > first:
+ raise PlanError('block_too_long', 'This device cannot generate a block of this length')
+ fits = frames <= limit
+ # The block length only matters once a video is split: up to 30 s stays one generation.
+ if fits and (single or seconds <= SINGLE_SECONDS or seconds <= min(block, first)):
+ return dict(seconds=seconds, frames=frames, single=True, hide_frames=0,
+ blocks=[dict(seconds=seconds, frames=frames, new_frames=frames)])
+ first, following = min(block, first), min(block, following)
+ if first < SHORTEST_BLOCK or following < SHORTEST_BLOCK:
+ raise PlanError('device_limit', 'This device cannot generate this length at this size')
+ total = seconds = math.floor(seconds + .5)
+ lengths = [min(first, total)]
+ while sum(lengths) < total:
+ if len(lengths) >= MAX_BLOCKS:
+ raise PlanError('too_long', 'This length needs too many blocks')
+ lengths.append(min(following, total - sum(lengths)))
+ if len(lengths) > 1 and lengths[-1] < SHORTEST_BLOCK:
+ # No short tail: the last two blocks share their length, the earlier one gets the odd second.
+ pair = lengths[-2] + lengths[-1]
+ lengths[-2:] = [pair - pair // 2, pair // 2]
+ blocks, shown = [], 0
+ for index, length in enumerate(lengths):
+ target = FPS * sum(lengths[:index + 1])
+ if index == 0:
+ new = requested = _first_frames(length)
+ else:
+ # Each block takes the shortest step that reaches its whole second; nothing is cut in between.
+ new = max(1, math.ceil((target - shown) / UNIT)) * UNIT
+ requested = new + OVERLAP
+ if requested > limit or index and length > following or not index and length > first:
+ raise PlanError('device_limit', 'This device cannot generate this length at this size')
+ shown += new
+ blocks.append(dict(seconds=length, frames=requested, new_frames=new))
+ return dict(seconds=total, frames=FPS * total, single=False, hide_frames=shown - FPS * total, blocks=blocks)
diff --git a/freevideo_engine/chain_runner.py b/freevideo_engine/chain_runner.py
new file mode 100644
index 0000000..75a2b69
--- /dev/null
+++ b/freevideo_engine/chain_runner.py
@@ -0,0 +1,586 @@
+"""One active durable chain, submitting ordinary host prompts by dependency."""
+from copy import deepcopy
+import json
+import logging
+import math
+import threading
+import time
+import uuid
+
+from . import chain_store as store
+
+
+class ChainBusy(ValueError):
+ pass
+
+
+def _number(value):
+ try:
+ return value if type(value) in (int, float) and math.isfinite(value) and value >= 0 else None
+ except OverflowError:
+ return None
+
+
+def node_prompt(prompt, node):
+ """Copy one node and its upstream inputs, leaving validation to the host."""
+ pending, selected = [node], set()
+ while pending:
+ current = pending.pop()
+ if current in selected:
+ continue
+ selected.add(current)
+ row = prompt[current]
+ inputs = row.get('inputs') if isinstance(row, dict) else None
+ if not isinstance(inputs, dict):
+ continue
+ for value in inputs.values():
+ if (isinstance(value, list) and len(value) == 2 and type(value[0]) in (str, int)
+ and value[0] in prompt and type(value[1]) is int):
+ pending.append(value[0])
+ return deepcopy({key: row for key, row in prompt.items() if key in selected})
+
+
+class ChainRunner:
+ def __init__(self, store_dir, host, clock=time.monotonic, wall=time.time, estimate=None, poll=0.5, inputs=None):
+ self.store_dir, self.host = store_dir, host
+ self.clock, self.wall, self.estimate, self.poll = clock, wall, estimate, poll
+ self.inputs = inputs or host.inputs
+ self.lock = threading.RLock()
+ self.step_lock = threading.Lock()
+ self.wake = threading.Event()
+ self.closed = threading.Event()
+ self.records = {row['id']: row for row in store.load_all(store_dir)}
+ self.starts, self.success, self.cancel_sent, self.progress_values = {}, {}, set(), {}
+ self.progress_messages = {}
+ self.estimates, self.queue, self.active = {}, [], None
+ self.recover = set()
+ for record in self.records.values():
+ if record['state'] in store.ACTIVE:
+ record['state'] = 'interrupted'
+ if record['output_state'] == 'joining':
+ record['output_state'] = 'done' if record['output'] else 'pending'
+ for block in record['blocks']:
+ if block['state'] in ('queued', 'running'):
+ block['state'] = 'interrupted'
+ self._save(record)
+ if record['state'] == 'interrupted' and record['join'] and record['output_state'] != 'failed':
+ self.recover.add(record['id'])
+ self.thread = threading.Thread(target=self._work, name='FreeVideo chain', daemon=True)
+ self.thread.start()
+
+ def _save(self, record):
+ record['updated'] = self.wall()
+ store.save(self.store_dir, record)
+
+ def _current(self, record):
+ executing = next((row for row in record['blocks'] if row['state'] in ('queued', 'running')), None)
+ if executing is not None:
+ return executing
+ done = {row['id'] for row in record['blocks'] if row['state'] == 'done'}
+ return next((row for row in record['blocks'] if row['state'] == 'pending'
+ and all(not isinstance(row[key], str) or row[key] in done
+ for key in ('after', 'before'))), None)
+
+ def _sources(self, record, block):
+ sources = {}
+ for key in ('after', 'before'):
+ value = block[key]
+ if isinstance(value, str):
+ source = next(row for row in record['blocks'] if row['id'] == value)
+ sources[key] = dict(block=value, output=source['output'])
+ elif value is not None:
+ sources[key] = dict(work=value['work'], output=value['work'])
+ else:
+ sources[key] = None
+ return sources
+
+ def _elapsed(self, block):
+ start = self.starts.get(block['prompt_id'])
+ return max(0., self.clock() - start) if start is not None else 0.
+
+ def _view(self, record, detailed=True, client_id=None):
+ value = store.detail(record) if detailed else store.summary(record)
+ block = self._current(record)
+ elapsed = value['elapsed_seconds']
+ if block is not None and block['state'] == 'running':
+ elapsed += self._elapsed(block)
+ remembered = self.progress_values.get(record['id'], {})
+ value['progress'] = deepcopy(remembered | self.progress_messages.get(record['id'], {}))
+ value['last_heartbeat_at'] = record.get('last_heartbeat_at')
+ value['elapsed_seconds'] = max(elapsed, remembered.get('elapsed_seconds', 0.))
+ value['joining'] = record['output_state'] == 'joining'
+ if client_id is not None:
+ # The owner's ID stays in the record: a page only learns whether a chain is its own.
+ value['mine'] = record['client_id'] == client_id
+ if record['state'] in store.ACTIVE and block is not None:
+ value['current'] = block['id']
+ return value
+
+ def create(self, payload):
+ record = store.validate(payload)
+ with self.lock:
+ record['created'] = self.wall()
+ self._save(record)
+ self.records[record['id']] = record
+ self.queue.append(record['id'])
+ self.wake.set()
+ return self._view(record)
+
+ def cancel(self, chain_id):
+ with self.lock:
+ record = self.records[chain_id]
+ if record['state'] in store.ACTIVE and record['state'] != 'cancelling':
+ record['state'] = 'cancelling'
+ self._save(record)
+ self.wake.set()
+ return self._view(record)
+
+ def resume(self, chain_id, client_id=None):
+ with self.lock:
+ record = self.records[chain_id]
+ if record['state'] in store.ACTIVE or record['output_state'] == 'joining':
+ raise ChainBusy('This chain is already active')
+ if (record['state'] not in ('cancelled', 'failed', 'interrupted')
+ and not (record['state'] == 'done' and record['output_state'] == 'failed')):
+ raise ValueError('This chain cannot be resumed')
+ if client_id is not None and not isinstance(client_id, str):
+ raise ValueError('Client ID must be a string')
+ for block in record['blocks']:
+ if block['state'] != 'done':
+ self.starts.pop(block['prompt_id'], None)
+ self.success.pop(block['prompt_id'], None)
+ self.cancel_sent.discard(block['prompt_id'])
+ block.update(state='pending', prompt_id=None, started=None, finished=None,
+ seconds=None, output=None, report_id=None, error=None,
+ fraction=0., remaining_seconds=None, continuation=None,
+ skip_frames=0, skip_audio_samples=0)
+ if client_id is not None:
+ record['client_id'] = client_id
+ record['state'] = 'queued'
+ if record['join']:
+ record['output_error'] = None
+ if all(row['state'] == 'done' for row in record['blocks']):
+ self._finish_blocks(record)
+ elif record['output'] is None:
+ record.update(output_blocks=0, output_state='pending')
+ self.recover.discard(chain_id)
+ self.progress_messages.pop(chain_id, None)
+ self.queue = [identity for identity in self.queue if identity != chain_id]
+ self.queue.append(chain_id)
+ self._save(record)
+ self.wake.set()
+ return self._view(record)
+
+ def list(self, client_id=None):
+ with self.lock:
+ records = [row for row in self.records.values()
+ if not (row.get('client_id') or '').startswith('agent:')
+ or client_id is not None and row.get('client_id') == client_id]
+ records = sorted(records, key=lambda row: row['created'], reverse=True)[:50]
+ return [self._view(row, detailed=False, client_id=client_id) for row in records]
+
+ def get(self, chain_id, client_id=None):
+ with self.lock:
+ return self._view(self.records[chain_id], client_id=client_id)
+
+ def load(self, chain_id):
+ """Restore one referenced receipt through the store's normal validation."""
+ with self.lock:
+ if chain_id not in self.records:
+ rows = store.load_all(self.store_dir, identity=chain_id)
+ if not rows:
+ raise KeyError(chain_id)
+ record = rows[0]
+ # As at startup, an old active receipt cannot replay submitted work.
+ if record['state'] in store.ACTIVE:
+ record['state'] = 'interrupted'
+ if record['output_state'] == 'joining':
+ record['output_state'] = 'done' if record['output'] else 'pending'
+ for block in record['blocks']:
+ if block['state'] in ('queued', 'running'):
+ block['state'] = 'interrupted'
+ self._save(record)
+ self.records[chain_id] = record
+ if record['state'] == 'interrupted' and record['join'] and record['output_state'] != 'failed':
+ self.recover.add(chain_id)
+ return self._view(self.records[chain_id])
+
+ def hidden(self, exists=None):
+ with self.lock:
+ return {row['output'] for record in self.records.values()
+ if record['join'] and record['output_state'] == 'done' and record['output_blocks'] > 1
+ and record['output'] not in {block['output'] for block in record['blocks']}
+ and (exists is None or exists(record['output']))
+ for row in record['blocks'][:record['output_blocks']] if row['output'] is not None}
+
+ def _find(self, prompt_id, node):
+ record = self.records.get(self.active)
+ if record is not None:
+ if record['node'] == str(node) and record['state'] in store.ACTIVE:
+ block = next((row for row in record['blocks'] if row['prompt_id'] == prompt_id
+ and row['state'] in ('queued', 'running')), None)
+ if block is not None:
+ return record, block
+ return None, None
+
+ def _start(self, block):
+ if block['started'] is None:
+ block['started'] = self.wall()
+ self.starts[block['prompt_id']] = self.clock()
+ block['state'] = 'running'
+
+ def context(self, prompt_id, node):
+ with self.lock:
+ record, block = self._find(prompt_id, node)
+ if block is None:
+ return None
+ record['last_heartbeat_at'] = self.wall()
+ if block['state'] != 'running':
+ self._start(block)
+ self._save(record)
+ return dict(id=record['id'], block=block['id'], part=block['part'], index=block['index'],
+ count=len(record['blocks']), after=deepcopy(block['after']), before=deepcopy(block['before']),
+ context=block['context'], sources=self._sources(record, block))
+
+ def finished(self, prompt_id, node, output, report_id, continuation=None):
+ with self.lock:
+ record, block = self._find(prompt_id, node)
+ if block is None:
+ return
+ record['last_heartbeat_at'] = self.wall()
+ try:
+ valid = continuation is None or type(continuation) is dict and store.json_value(continuation)
+ except (ValueError, TypeError, RecursionError, OverflowError):
+ valid = False
+ if not valid:
+ logging.warning('[FreeVideo] Discarding non-JSON chain continuation')
+ continuation = None
+ saved = deepcopy(continuation)
+ # The engine trims the repeated opening itself. A skip applies only
+ # when its receipt names one.
+ skips = {}
+ for key in ('skip_frames', 'skip_audio_samples'):
+ value = (saved or {}).get(key)
+ skips[key] = value if type(value) is int and value >= 0 else 0
+ block.update(output=output, report_id=report_id)
+ block.update(continuation=saved, **skips)
+ if report_id is not None:
+ record['last_report_id'] = report_id
+ self.success[prompt_id] = (self.clock(), self.wall())
+ self._save(record)
+ self.wake.set()
+
+ def _finish_blocks(self, record, final_state='done'):
+ if not record['join']:
+ return final_state
+ blocks = store.leading_blocks(record)
+ if not blocks:
+ record.update(output=None, output_blocks=0, output_state='pending', output_error=None)
+ return final_state
+ if len(blocks) == 1:
+ output = blocks[0]['output']
+ record.update(output=output, output_blocks=1 if output else 0, output_state='done', output_error=None)
+ return final_state
+ if record['output_state'] == 'done' and record['output_blocks'] == len(blocks):
+ return final_state
+ record.update(output_state='joining', output_error=None, join_final_state=final_state)
+ return 'cancelling' if final_state == 'cancelled' else 'running'
+
+ def _complete(self, record, block, status):
+ state = status['state']
+ prompt_id = block['prompt_id']
+ ended, finished = self.success.get(prompt_id, (self.clock(), self.wall()))
+ block['finished'] = finished
+ start = self.starts.get(prompt_id)
+ block['seconds'] = max(0., ended - start) if start is not None else 0.
+ if prompt_id in self.success or state == 'success':
+ block['state'] = 'done'
+ block.update(fraction=1., remaining_seconds=0.)
+ if block['output'] is None:
+ block['output'] = deepcopy(status.get('output'))
+ next_state = 'running' if self._current(record) is not None else (
+ 'cancelled' if record['state'] == 'cancelling' else self._finish_blocks(record))
+ elif state in ('missing', 'interrupted'):
+ block['state'], next_state = 'cancelled', 'cancelled'
+ else:
+ block['state'], next_state = 'failed', 'failed'
+ block['error'] = status.get('error') or 'Prompt execution failed'
+ next_state = 'cancelled' if record['state'] == 'cancelling' else next_state
+ record['state'] = self._finish_blocks(record, next_state) if next_state in ('cancelled', 'failed') else next_state
+ if record['state'] not in store.ACTIVE and self.active == record['id']:
+ self.active = None
+ self.starts.pop(prompt_id, None)
+ self.success.pop(prompt_id, None)
+ self.cancel_sent.discard(prompt_id)
+ self._save(record)
+
+ def step(self):
+ """Run one scheduler pass; tests can drive the same loop without sleeping."""
+ with self.step_lock:
+ with self.lock:
+ recovering = []
+ for identity in self.recover:
+ record = self.records[identity]
+ self._finish_blocks(record, 'interrupted')
+ self._save(record)
+ if record['output_state'] == 'joining':
+ recovering.append((identity, deepcopy(record)))
+ self.recover.clear()
+ # Cancelling a waiting chain never interrupts the active chain.
+ for record in self.records.values():
+ if record['state'] == 'cancelling' and record['output_state'] != 'joining' and not any(
+ row['state'] in ('queued', 'running') for row in record['blocks']):
+ record['state'] = self._finish_blocks(record, 'cancelled')
+ self._save(record)
+ if self.active is not None and self.records[self.active]['state'] not in store.ACTIVE:
+ self.active = None
+ while self.active is None and self.queue:
+ identity = self.queue.pop(0)
+ waiting = self.records[identity]
+ if waiting['state'] == 'queued' or waiting['state'] == 'cancelling' and waiting['output_state'] == 'joining':
+ self.active = identity
+ identity = self.active
+ for recovering_id, snapshot in recovering:
+ if not self.closed.is_set():
+ self._join(recovering_id, snapshot)
+ if identity is not None and not self.closed.is_set():
+ self._step_chain(identity)
+
+ def _step_chain(self, identity):
+ with self.lock:
+ record = self.records[identity]
+ if record['state'] not in store.ACTIVE:
+ return
+ block = self._current(record)
+ if record['output_state'] == 'joining':
+ if record['state'] == 'cancelling':
+ record['join_final_state'] = 'cancelled'
+ self._save(record)
+ snapshot = deepcopy(record)
+ action = 'join'
+ elif block is None or record['state'] == 'cancelling' and block['prompt_id'] is None:
+ record['state'] = self._finish_blocks(record, 'cancelled' if record['state'] == 'cancelling' else 'done')
+ self._save(record)
+ return
+ else:
+ prompt_id, node = block['prompt_id'], record['node']
+ action = 'status'
+ if action == 'join':
+ pass
+ elif prompt_id is None:
+ self.progress_messages.pop(identity, None)
+ self.progress_values.get(identity, {}).pop('remaining_seconds', None)
+ prompt_id = str(uuid.uuid4())
+ block.update(prompt_id=prompt_id, state='queued', attempts=block['attempts'] + 1)
+ record['state'] = 'running'
+ # Receipt first: a crash after submission cannot replay this prompt.
+ self._save(record)
+ prompt = deepcopy(record['snapshot']['prompt'])
+ block_inputs = dict(block['inputs'])
+ sources = self._sources(record, block)
+ extra = deepcopy(record['snapshot']['extra_data'])
+ if record['client_id'] is not None:
+ extra['client_id'] = record['client_id']
+ extra['freevideo_chain'] = dict(id=identity, block=block['id'], part=block['part'], index=block['index'],
+ count=len(record['blocks']), after=deepcopy(block['after']), before=deepcopy(block['before']))
+ action = 'submit'
+ elif record['state'] == 'cancelling' and prompt_id not in self.cancel_sent:
+ action = 'cancel'
+ self.cancel_sent.add(prompt_id)
+ else:
+ action = 'status'
+ # Host IO must not hold the lock used by routes or node callbacks.
+ if action == 'join':
+ self._join(identity, snapshot)
+ return
+ if action == 'submit':
+ try:
+ for key, source in sources.items():
+ if source is not None:
+ if source['output'] is None and not getattr(self.host, 'fake', False):
+ raise ValueError('Referenced block has no output: %s' % source['block'])
+ if 'work' in source and not self.host.work_exists(source['work']):
+ raise ValueError('Referenced work video does not exist: %s' % source['work'])
+ block_inputs[key] = (source['output'] or '') if source is not None else ''
+ for name in getattr(self.host, 'continuation_inputs', ()):
+ prompt[node]['inputs'].pop(name, None)
+ prompt[node]['inputs'].update(self.inputs(block_inputs))
+ self.host.submit(prompt_id, node_prompt(prompt, node), extra)
+ except Exception as error:
+ # A response may be lost after the host has accepted the prompt.
+ try:
+ status = self.host.status(prompt_id)
+ except Exception:
+ status = dict(state='missing')
+ with self.lock:
+ if prompt_id in self.success or status['state'] == 'success':
+ self._complete(record, block, status)
+ elif status['state'] == 'running':
+ record['last_heartbeat_at'] = self.wall()
+ self._start(block)
+ self._save(record)
+ elif status['state'] != 'pending':
+ self._complete(record, block, dict(state='error', error=str(error)))
+ return
+ if action == 'cancel':
+ try:
+ self.host.cancel(prompt_id, node)
+ except Exception:
+ logging.warning('[FreeVideo] Chain cancellation could not reach the host')
+ with self.lock:
+ succeeded = prompt_id in self.success
+ if succeeded:
+ status = dict(state='success')
+ else:
+ try:
+ status = self.host.status(prompt_id)
+ except Exception:
+ logging.warning('[FreeVideo] Chain status could not reach the host')
+ return
+ with self.lock:
+ state = status['state']
+ if prompt_id in self.success or state in ('success', 'error', 'interrupted', 'missing'):
+ if state != 'missing' or prompt_id in self.success:
+ record['last_heartbeat_at'] = self.wall()
+ self._complete(record, block, status)
+ elif state in ('pending', 'running'):
+ desired = 'queued' if state == 'pending' else 'running'
+ if block['state'] != desired:
+ if desired == 'running':
+ record['last_heartbeat_at'] = self.wall()
+ self._start(block)
+ else:
+ block['state'] = desired
+ self._save(record)
+
+ def _join(self, identity, snapshot):
+ final_state = snapshot.get('join_final_state', 'done')
+ def cancelled():
+ with self.lock:
+ return self.closed.is_set() or (final_state != 'cancelled'
+ and self.records[identity]['state'] == 'cancelling')
+ texts = [row['inputs']['text'] for row in snapshot['blocks']]
+ texts += [row['inputs'].get('text') for row in snapshot['snapshot']['prompt'].values()
+ if isinstance(row, dict) and isinstance(row.get('inputs'), dict)]
+ failure = None
+ try:
+ output = self.host.join(snapshot, cancelled)
+ if not isinstance(output, str) or not output:
+ raise ValueError('Joining did not return a video path')
+ except Exception as error:
+ message = str(error)
+ failure = message[:300]
+ if 'workflow' in message.lower() or any(isinstance(value, str) and value and any(
+ part in message for part in (value, repr(value)[1:-1], json.dumps(value)[1:-1])) for value in texts):
+ failure = 'Joining failed'
+ with self.lock:
+ record = self.records[identity]
+ if self.closed.is_set():
+ return
+ elif cancelled():
+ record['state'] = self._finish_blocks(record, 'cancelled')
+ elif failure is not None:
+ record.update(state=final_state, output_state='failed', output_error=failure)
+ logging.warning('[FreeVideo] Chain joining failed: %s', identity)
+ else:
+ record.update(state=final_state, output=output, output_blocks=len(store.leading_blocks(snapshot)),
+ output_state='done', output_error=None)
+ if record['state'] not in store.ACTIVE and self.active == identity:
+ self.active = None
+ self._save(record)
+
+ def _estimate(self, record, block):
+ """The estimator receives live records once per block and must not modify them."""
+ if self.estimate is None:
+ return None
+ key = record['id'], block['id']
+ if key not in self.estimates:
+ try:
+ self.estimates[key] = _number(self.estimate(record, block))
+ except Exception:
+ logging.warning('[FreeVideo] Chain estimate is unavailable')
+ self.estimates[key] = None
+ return self.estimates[key]
+
+ def progress(self, node, message):
+ with self.lock:
+ record = self.records.get(self.active)
+ if record is None or record['node'] != str(node) or record['state'] not in store.ACTIVE:
+ return None
+ block = self._current(record)
+ if block is None or block['state'] != 'running':
+ return None
+ overall = message.get('overall') or {}
+ used = _number(overall.get('elapsed_seconds'))
+ used = self._elapsed(block) if used is None else used
+ remaining = _number(overall.get('remaining_seconds'))
+ done = [row for row in record['blocks'] if row['state'] == 'done']
+ rates = [row['seconds'] / row['inputs']['frames'] for row in done
+ if _number(row['seconds']) is not None and row['seconds'] > 0]
+ rate = sum(rates) / len(rates) if rates else None
+ fallback = ((used + remaining) / block['inputs']['frames']
+ if remaining is not None and used + remaining > 0 else None)
+ estimates = []
+ for row in record['blocks']:
+ if row['state'] == 'done':
+ value = row['seconds'] or 0.
+ elif rate is not None:
+ value = rate * row['inputs']['frames']
+ else:
+ value = self._estimate(record, row)
+ if value is None and fallback is not None:
+ value = fallback * row['inputs']['frames']
+ estimates.append(value)
+ current_estimate = estimates[block['index']]
+ fraction = _number(overall.get('fraction'))
+ if overall.get('status') == 'complete' or message.get('phase') == 'complete':
+ fraction = 1.
+ remaining = 0.
+ own_fraction = block['fraction'] if fraction is None else max(block['fraction'], min(1., fraction))
+ # Kept in memory only: several messages arrive per second, and a
+ # restart resets an unfinished block anyway.
+ block.update(fraction=own_fraction, remaining_seconds=remaining)
+ if fraction is None:
+ fraction = min(.95, used / current_estimate) if current_estimate else 0.
+ fraction = max(own_fraction, min(1., fraction))
+ if remaining is None and current_estimate is not None:
+ remaining = max(0., current_estimate - used)
+ later = [estimates[row['index']] for row in record['blocks']
+ if row is not block and row['state'] != 'done']
+ remaining = remaining + sum(later) if remaining is not None and all(e is not None for e in later) else None
+ completed_seconds = sum(row['seconds'] or 0. for row in done)
+ if len(done) + 1 == len(record['blocks']) and fraction == 1.:
+ total_fraction = 1.
+ elif all(e is not None for e in estimates) and sum(estimates) > 0:
+ total_fraction = (completed_seconds + current_estimate * fraction) / sum(estimates)
+ else:
+ total_fraction = (len(done) + fraction) / len(record['blocks'])
+ previous = self.progress_values.get(record['id'], {})
+ value = dict(fraction=max(previous.get('fraction', 0.), total_fraction), remaining_seconds=remaining,
+ elapsed_seconds=max(previous.get('elapsed_seconds', 0.), completed_seconds + used))
+ self.progress_messages[record['id']] = {key: deepcopy(message[key]) for key in
+ ('phase', 'timing_phase', 'label', 'detail', 'done', 'total', 'unit') if key in message}
+ record['last_heartbeat_at'] = self.wall()
+ if record['join'] and len(record['blocks']) > 1:
+ value['fraction'] = min(.99, value['fraction'])
+ self.progress_values[record['id']] = value
+ return dict(id=record['id'], block=block['id'], part=block['part'], index=block['index'], count=len(record['blocks']),
+ after=deepcopy(block['after']), before=deepcopy(block['before']), overall=deepcopy(value))
+
+ def _work(self):
+ while not self.closed.is_set():
+ self.wake.clear()
+ try:
+ self.step()
+ except Exception:
+ logging.exception('[FreeVideo] Chain scheduler pass failed')
+ self.wake.wait(self.poll)
+
+ def close(self):
+ self.closed.set()
+ self.wake.set()
+ if self.thread is not threading.current_thread():
+ self.thread.join(timeout=31.)
+ close = getattr(self.host, 'close', None)
+ if close is not None:
+ close()
diff --git a/freevideo_engine/chain_store.py b/freevideo_engine/chain_store.py
new file mode 100644
index 0000000..6231a4c
--- /dev/null
+++ b/freevideo_engine/chain_store.py
@@ -0,0 +1,281 @@
+"""Versioned workflow snapshots and atomic receipts for background chains."""
+from copy import deepcopy
+import json
+import logging
+import math
+import os
+from pathlib import Path, PurePosixPath, PureWindowsPath
+import re
+import tempfile
+import time
+import uuid
+
+from . import chain_plan
+
+ACTIVE = ('queued', 'running', 'cancelling')
+CHAIN_STATES = (*ACTIVE, 'cancelled', 'failed', 'interrupted', 'done')
+BLOCK_STATES = ('pending', 'queued', 'running', 'done', 'cancelled', 'failed', 'interrupted')
+OUTPUT_STATES = ('none', 'pending', 'joining', 'done', 'failed')
+
+
+def reference(value):
+ if value is None or isinstance(value, str) and value:
+ return value
+ if isinstance(value, dict) and set(value) == {'work'}:
+ path = value['work']
+ if isinstance(path, str) and path and '\x00' not in path:
+ posix, windows = PurePosixPath(path), PureWindowsPath(path)
+ if (not posix.is_absolute() and not windows.drive and not windows.root
+ and '..' not in posix.parts and '..' not in windows.parts
+ and posix.suffix.lower() == '.mp4'):
+ return deepcopy(value)
+ raise ValueError('References must be block IDs or relative MP4 work paths without ..')
+
+
+def json_value(value):
+ """Only ordinary, finite JSON values may enter durable continuation receipts."""
+ if value is None or type(value) in (str, bool, int):
+ return True
+ if type(value) is float:
+ return math.isfinite(value)
+ if type(value) is list:
+ return all(json_value(item) for item in value)
+ if type(value) is dict:
+ return all(type(key) is str and json_value(item) for key, item in value.items())
+ return False
+
+
+def validate(payload):
+ if not isinstance(payload, dict):
+ raise ValueError('A chain object is required')
+ node, prompt = payload.get('node'), payload.get('prompt')
+ if not isinstance(node, str) or not node or not isinstance(prompt, dict) or node not in prompt:
+ raise ValueError('Node must exist in the prompt')
+ if not isinstance(prompt[node], dict) or not isinstance(prompt[node].get('inputs'), dict):
+ raise ValueError('Node inputs are required')
+ if prompt[node].get('class_type') != 'FreeVideoGenerate':
+ raise ValueError('Node must be FreeVideoGenerate')
+ extra = payload.get('extra_data', {})
+ client = payload.get('client_id')
+ if not isinstance(extra, dict) or client is not None and not isinstance(client, str):
+ raise ValueError('Invalid extra data or client ID')
+ if ('blocks' in payload) == ('seconds' in payload):
+ raise ValueError('Specify blocks or seconds, not both')
+ planned = None
+ join = payload.get('join', 'seconds' in payload)
+ if type(join) is not bool:
+ raise ValueError('Join must be a bool')
+ if 'seconds' in payload:
+ planned = chain_plan.plan(payload['seconds'], payload.get('single', False), payload.get('max_frames'),
+ payload.get('single_limit_seconds'), payload.get('block_seconds'))
+ inputs = prompt[node]['inputs']
+ text, seed = payload.get('text', inputs.get('text')), payload.get('seed', inputs.get('seed'))
+ if not isinstance(text, str):
+ raise ValueError('Text must be a string')
+ if type(seed) is not int or seed < 0:
+ raise ValueError('A nonnegative integer seed is required')
+ rows = [dict(id='b%s' % (index + 1), after='b%s' % index if index else None,
+ frames=row['frames'], text=text, seed=seed + index)
+ for index, row in enumerate(planned['blocks'])]
+ else:
+ rows = payload['blocks']
+ if not isinstance(rows, list) or not 1 <= len(rows) <= chain_plan.MAX_BLOCKS:
+ raise ValueError('A chain requires 1 to %s blocks' % chain_plan.MAX_BLOCKS)
+ blocks, ids = [], set()
+ for index, row in enumerate(rows):
+ if not isinstance(row, dict):
+ raise ValueError('A block object is required')
+ identity = row.get('id')
+ if not isinstance(identity, str) or not identity or identity in ids:
+ raise ValueError('Block IDs must be unique strings')
+ part = row.get('part', identity)
+ if not isinstance(part, str):
+ raise ValueError('Block part must be a string')
+ after, before = reference(row.get('after')), reference(row.get('before'))
+ text, frames = row.get('text'), row.get('frames')
+ if not isinstance(text, str) or len(text) > 20000:
+ raise ValueError('Block text must be a string of at most 20000 characters')
+ if type(frames) is not int or frames < 39 or (frames - 5) % 17:
+ raise ValueError('Block frames must be an integer of 5 + 17n, at least 39')
+ if 'seconds' in row:
+ raise ValueError('Use frames for block length')
+ seed = row.get('seed') if 'seed' in row else prompt[node]['inputs'].get('seed')
+ if type(seed) is not int or seed < 0:
+ raise ValueError('A nonnegative integer seed is required')
+ if 'seed' not in row:
+ seed += index
+ for key, supported in (('fill', 'both'), ('context', 'saved')):
+ if key in row and row[key] != supported:
+ raise ValueError('This version does not support %s other than %s' % (key, supported))
+ blocks.append(dict(id=identity, part=part, index=index, after=after, before=before,
+ fill='both', context='saved', inputs=dict(text=text, frames=frames, seed=seed),
+ new_frames=frames - chain_plan.OVERLAP if after or before else frames,
+ state='pending', prompt_id=None, attempts=0, started=None,
+ finished=None, seconds=None, output=None, report_id=None, error=None,
+ fraction=0., remaining_seconds=None, continuation=None,
+ skip_frames=0, skip_audio_samples=0))
+ ids.add(identity)
+ dependencies = {row['id']: [row[key] for key in ('after', 'before')
+ if isinstance(row[key], str)] for row in blocks}
+ visiting, visited = set(), set()
+ def visit(identity):
+ if identity not in ids:
+ raise ValueError('Referenced block must belong to this chain')
+ if identity in visiting:
+ raise ValueError('Block references cannot contain a cycle or self reference')
+ if identity not in visited:
+ visiting.add(identity)
+ for source in dependencies[identity]:
+ visit(source)
+ visiting.remove(identity)
+ visited.add(identity)
+ for identity in ids:
+ visit(identity)
+ now = time.time()
+ record = dict(version=1, id='c-' + uuid.uuid4().hex[:12], node=node, created=now,
+ updated=now, state='queued', client_id=client,
+ snapshot=dict(prompt=deepcopy(prompt), extra_data=deepcopy(extra)), blocks=blocks,
+ plan=planned, join=join, output=None, output_state='pending' if join else 'none',
+ output_error=None, output_blocks=0)
+ try:
+ json.dumps(record, allow_nan=False)
+ except (ValueError, TypeError, OverflowError) as error:
+ raise ValueError('Chain data must be valid JSON') from error
+ return record
+
+
+def leading_blocks(record):
+ blocks = []
+ for row in record['blocks']:
+ if row['state'] != 'done':
+ break
+ blocks.append(row)
+ return blocks
+
+
+def summary(record):
+ blocks = record['blocks']
+ current = next((row['id'] for row in blocks if row['state'] in ('queued', 'running')), None)
+ return dict({key: deepcopy(record[key]) for key in
+ ('version', 'id', 'node', 'created', 'updated', 'state',
+ 'join', 'output', 'output_state', 'output_error', 'output_blocks')},
+ count=len(blocks), done=sum(row['state'] == 'done' for row in blocks),
+ current=current, elapsed_seconds=sum(row['seconds'] or 0 for row in blocks if row['state'] == 'done'),
+ last_report_id=record.get('last_report_id') or next((row['report_id'] for row in reversed(blocks)
+ if row['report_id'] is not None), None))
+
+
+def detail(record):
+ return dict(summary(record), blocks=deepcopy(record['blocks']), plan=deepcopy(record['plan']))
+
+
+def save(directory, record):
+ directory = Path(directory)
+ directory.mkdir(parents=True, exist_ok=True)
+ target = directory / (record['id'] + '.json')
+ temporary = None
+ try:
+ with tempfile.NamedTemporaryFile(mode='w', encoding='utf-8', dir=directory,
+ prefix=record['id'] + '.', suffix='.tmp', delete=False) as stream:
+ temporary = Path(stream.name)
+ json.dump(record, stream, ensure_ascii=False, allow_nan=False)
+ stream.flush()
+ os.fsync(stream.fileno())
+ os.replace(temporary, target)
+ finally:
+ if temporary is not None:
+ temporary.unlink(missing_ok=True)
+
+
+def load_all(directory, limit=200, *, identity=None):
+ if identity is not None and (not isinstance(identity, str) or not re.fullmatch(r'c-[0-9a-f]{12}', identity)):
+ return []
+ records = []
+ paths = []
+ for path in Path(directory).glob(identity + '.json' if identity is not None else '*.json'):
+ try:
+ paths.append((path.stat().st_mtime_ns, path))
+ except OSError:
+ logging.warning('[FreeVideo] Skipping inaccessible chain file: %s', path.name)
+ paths.sort(key=lambda row: (row[0], row[1].name), reverse=True)
+ for _, path in paths[:limit]:
+ try:
+ record = json.loads(path.read_text(encoding='utf-8'))
+ if not isinstance(record, dict) or record.get('version') != 1:
+ raise ValueError('Unsupported chain version')
+ identity = record.get('id')
+ if not isinstance(identity, str) or not re.fullmatch(r'c-[0-9a-f]{12}', identity) or path.stem != identity:
+ raise ValueError('Invalid chain ID')
+ for key, value in dict(plan=None, join=False, output=None, output_state='none', output_error=None).items():
+ record.setdefault(key, value)
+ if type(record['join']) is not bool or record['output_state'] not in OUTPUT_STATES:
+ raise ValueError('Invalid chain output state')
+ if any(record[key] is not None and not isinstance(record[key], str) for key in ('output', 'output_error')):
+ raise ValueError('Invalid chain output')
+ record.setdefault('output_blocks', len(record['blocks']) if record['output_state'] == 'done' else 0)
+ if (type(record['output_blocks']) is not int or not 0 <= record['output_blocks'] <= len(record['blocks'])
+ or record['output'] is None and record['output_blocks'] != 0):
+ raise ValueError('Invalid chain output block count')
+ if record.get('join_final_state', 'done') not in ('done', 'cancelled', 'failed', 'interrupted'):
+ raise ValueError('Invalid chain join final state')
+ if record['plan'] is not None:
+ planned = record['plan']
+ # The plan was made for a device limit that is not kept; only its shape is checked.
+ if (not isinstance(planned, dict) or not json_value(planned) or type(planned.get('single')) is not bool
+ or any(type(planned.get(key)) is not int or planned[key] < 0 for key in ('frames', 'hide_frames'))):
+ raise ValueError('Invalid chain plan')
+ for row in record['blocks']:
+ if 'frames' not in row['inputs'] and 'seconds' in row['inputs']:
+ # Step-one receipts used seconds. Preserve their effective
+ # geometry and results while exposing the new block contract.
+ from .geometry import geometry
+ context = row.get('context', {})
+ if not isinstance(context, dict) or context.get('source', 'tail') not in ('tail', 'frames'):
+ raise ValueError('Invalid legacy block context')
+ row['inputs']['frames'] = geometry(seconds=row['inputs'].pop('seconds'))['frames']
+ row.update(part=row['id'], before=None, fill='both', context='saved',
+ fraction=1. if row['state'] == 'done' else 0., remaining_seconds=None,
+ continuation=None, skip_frames=0, skip_audio_samples=0)
+ snapshot = record['snapshot']
+ normalized = validate(dict(node=record['node'], client_id=record['client_id'], **snapshot,
+ blocks=[{key: row[key] for key in ('id', 'part', 'after', 'before', 'fill', 'context')}
+ | row['inputs']
+ for row in record['blocks']], join=record['join']))
+ if record['state'] not in CHAIN_STATES:
+ raise ValueError('Invalid chain state')
+ for row, clean in zip(record['blocks'], normalized['blocks']):
+ row.setdefault('new_frames', clean['new_frames'])
+ if type(row['new_frames']) is not int or row['new_frames'] != clean['new_frames']:
+ raise ValueError('Invalid block new frame count')
+ if row['state'] not in BLOCK_STATES or row['index'] != clean['index']:
+ raise ValueError('Invalid block state or index')
+ if type(row['attempts']) is not int or row['attempts'] < 0:
+ raise ValueError('Invalid attempt count')
+ for key in ('started', 'finished', 'seconds'):
+ value = row[key]
+ if value is not None and (type(value) not in (int, float) or not math.isfinite(value) or value < 0):
+ raise ValueError('Invalid block timing')
+ for key in ('prompt_id', 'output', 'report_id', 'error'):
+ if row[key] is not None and not isinstance(row[key], str):
+ raise ValueError('Invalid block result')
+ if (type(row['fraction']) not in (int, float) or not 0 <= row['fraction'] <= 1
+ or row['remaining_seconds'] is not None and
+ (type(row['remaining_seconds']) not in (int, float)
+ or not math.isfinite(row['remaining_seconds']) or row['remaining_seconds'] < 0)):
+ raise ValueError('Invalid block progress')
+ if not json_value(row['continuation']) or any(
+ type(row[key]) not in (int, float) or not math.isfinite(row[key]) or row[key] < 0
+ for key in ('skip_frames', 'skip_audio_samples')):
+ raise ValueError('Invalid continuation receipt')
+ if row['state'] != 'pending' and (not row['prompt_id'] or row['attempts'] == 0):
+ raise ValueError('Submitted blocks require a prompt ID and attempt')
+ if row['state'] == 'done' and (row['seconds'] is None or row['finished'] is None):
+ raise ValueError('Completed blocks require timing')
+ for key in ('created', 'updated'):
+ if type(record[key]) not in (int, float) or not math.isfinite(record[key]):
+ raise ValueError('Invalid chain timestamp')
+ records.append(record)
+ except (OSError, ValueError, TypeError, KeyError, OverflowError):
+ # Keep the file for inspection; never log its workflow or sentences.
+ logging.warning('[FreeVideo] Skipping invalid chain file: %s', path.name)
+ return records
diff --git a/freevideo_engine/cli.py b/freevideo_engine/cli.py
index 78a3777..6543b5e 100644
--- a/freevideo_engine/cli.py
+++ b/freevideo_engine/cli.py
@@ -27,6 +27,9 @@ def resource_arguments(parser):
def main():
+ if len(sys.argv) > 1 and sys.argv[1] in ('projects', 'sessions'):
+ from .agent.cli import main as agent
+ return agent(sys.argv[1:])
if len(sys.argv) > 1 and sys.argv[1] == 'predict':
from .prediction_cli import main as predict
raise SystemExit(predict(sys.argv[2:]))
diff --git a/freevideo_engine/comfy_assets.py b/freevideo_engine/comfy_assets.py
index c8a7a65..99d9e0e 100644
--- a/freevideo_engine/comfy_assets.py
+++ b/freevideo_engine/comfy_assets.py
@@ -25,6 +25,7 @@ EXTENSIONS = {
'video': {'.mp4', '.mov', '.webm', '.mkv', '.m4v'},
'audio': {'.wav', '.mp3', '.flac', '.ogg', '.m4a', '.aac', '.opus'},
}
+REFERENCE_INPUTS = ('reference', *(f'reference_{i}' for i in range(2, 9)))
def resolve_loras(serialized, names, resolve, previous=None):
@@ -105,18 +106,26 @@ def resolve_assets(serialized, input_directory):
return result
-def connect_assets(assets, *, first=None, last=None, reference=None, reference_audio=None):
+def connect_assets(assets, *, first=None, last=None, reference=None, reference_audio=None, **images):
"""Keep connected IMAGE/AUDIO values native until request input export."""
result = dict(assets)
+ if set(images) - set(REFERENCE_INPUTS[1:]):
+ raise TypeError('Unknown reference image input')
+ images = dict(reference=reference, **images)
connected = {name: value for name, value in (('first', first), ('last', last),
- ('reference', reference), ('reference_audio', reference_audio))
+ *((name, images.get(name)) for name in REFERENCE_INPUTS), ('reference_audio', reference_audio))
if value is not None}
for name in ('first', 'last'):
if name in result and name in connected:
raise ValueError('Choose the connected ' + name + ' frame or the uploaded one; disable the duplicate')
- count = len(result.get('references', [])) + int(reference is not None) + int(reference_audio is not None)
+ count = len(result.get('references', [])) + int(reference_audio is not None)
+ for value in images.values():
+ if value is not None:
+ shape = getattr(value, 'shape', ())
+ count += int(shape[0]) if len(shape) == 4 else 1
if count > 32:
- raise ValueError('Use at most 32 references, including connected inputs')
+ raise ValueError(f'There are {count} references and the limit is 32. '
+ 'For a long image batch, connect a clip to the Reference node\'s video input; a clip counts as one reference.')
if count and any(
name in result or name in connected for name in ('first', 'last')):
raise ValueError('Choose keyframes or references; disable the unused inputs')
diff --git a/freevideo_engine/comfy_bridge.py b/freevideo_engine/comfy_bridge.py
index 447e990..6382c5c 100644
--- a/freevideo_engine/comfy_bridge.py
+++ b/freevideo_engine/comfy_bridge.py
@@ -75,172 +75,646 @@ def progress_history_forecast(root, machine, canvas):
return {} # A progress estimate cannot prevent generation.
+class _SafeProgress:
+ """Any failure of the estimate falls back to plain progress messages."""
+ def __init__(self, inner):
+ self.inner = inner
+
+ def _call(self, name, *args, **kwargs):
+ try:
+ return getattr(self.inner, name)(*args, **kwargs)
+ except Exception:
+ self.inner = _PlainProgress() # A progress estimate cannot prevent generation.
+ return getattr(self.inner, name)(*args, **kwargs)
+
+ def annotate(self, message, *, event=None):
+ return self._call('annotate', message, event=event)
+
+ def observe(self, event):
+ return self._call('observe', event)
+
+ def heartbeat(self):
+ return self._call('heartbeat')
+
+ def configure(self, **facts):
+ return self._call('configure', **facts)
+
+
+class _PlainProgress:
+ """Pass engine messages through unchanged when no estimate can be built."""
+ def annotate(self, message, *, event=None):
+ return dict(message)
+
+ def observe(self, event):
+ pass
+
+ def heartbeat(self):
+ return None
+
+ def configure(self, **facts):
+ pass
+
+
+def _engine_version():
+ from . import __version__
+ return __version__
+
+
class WholeVideoProgress:
- """Annotate phase events with one report-weighted whole-video progress.
+ """One elapsed/remaining clock, bounded by evidence of completed work.
- Local reports take precedence. Without history, live sampling supplies a
- rough decoder estimate which real decoded-frame timings then replace.
- These presentation estimates never change resource admission or placement.
+ This display estimator never changes the inference plan. Stage predictions
+ set the initial ruler; only real events release its count ceiling. Replay
+ options control smoothing, silent countdown and the ceiling's time shares.
"""
- def __init__(self, clock=time.perf_counter):
- self.clock = clock
- self.started = clock()
- self.phase_started = self.started
- self.phase = None
- self.completed = set()
- self.weights = {}
+ def __init__(self, clock=time.perf_counter, *, hardware=None, request=None,
+ cold_flags=None, records=(), rate=.005, smoothing='track',
+ silence='stage', ceiling='stretch', tau=10., max_rise=.019, final=.98, slow_start=True, started=None):
+ from . import stage_estimate
+ from .effort_forecast import stage_forecast
+ if not math.isfinite(rate) or rate < 0:
+ raise ValueError('Progress smoothing rate must be finite and nonnegative')
+ for name, value, choices in (('smoothing', smoothing, ('countdown', 'hold', 'track')),
+ ('silence', silence, ('freeze', 'stage')),
+ ('ceiling', ceiling, ('prior', 'current', 'stretch'))):
+ if value not in choices:
+ raise ValueError(f'Invalid progress {name}: {value!r}')
+ self.clock, self.rate = clock, rate
+ self.smoothing, self.silence, self.ceiling = smoothing, silence, ceiling
+ # tau: time constant of a downward correction ('track'); max_rise: the
+ # most the shown fraction may rise per published second (None: no cap).
+ self.tau, self.max_rise = tau, max_rise
+ # final: once every frame is decoded, the bar approaches this fraction
+ # over the predicted audio and save time (None: no approach).
+ self.final = final
+ # slow_start: on a 16 GB machine, a load much slower than predicted
+ # scales the later stages until history or measured speed takes over.
+ self.slow_start = slow_start
+ self.started = self.phase_started = self.last_tick = self.last_event = clock() if started is None else started
+ self.last_publish = self.started
+ self.hardware = dict(hardware or {})
+ self.request = dict(width=1344, height=768, frames=243, base_steps=8,
+ refine_steps=3, two_pass=True, flow='full', task='t2va')
+ self.request.update({k: v for k, v in (request or {}).items() if v is not None})
+ self.cold_flags = dict(cold_flags or {})
+ self.records = records
+ self.params = stage_estimate._params(None)
+ self.prior = stage_estimate.predict_prior(self.hardware, self.request, self.cold_flags, self.params)
+ self.weights = {k: self.prior['stages'][k]['seconds'] for k in stage_estimate.STAGES}
+ local = stage_forecast(records, self.request, self.cold_flags, self.weights, version=_engine_version())
+ self.remaining_source = 'local' if local.get('stages') else 'similar'
+ self.typical = local['typical']
+ self.local = local
+ self.weights.update(local.get('stages', {}))
+ self.completed = {k for k, v in self.weights.items() if v == 0}
self.measured = {}
- self.total = 0.
- self.forecast_ready = False
- self.failed = False
+ self.phase = 'encode'
+ self.completed.discard(self.phase)
self.sampling_plan = {}
- self.decode_from_sampling = False
- self.sampling_time_weighted = False
- self.decode_tail = 0.
+ self.steps = {'pass1': {}, 'pass2': {}}
+ self.live_calibration = True
+ self.count = None
+ self.fraction = 0.
+ self.ceiling_base = 0.
+ self.last_ceiling = 0.
+ self.ceiling_weights = dict(self.weights)
+ self.remaining_target = self.remaining_shown = sum(self.weights.values())
+ self.total = self.remaining_target
+ self.last_message = {}
+ self.finished = False
+ self.decode_remaining = None
+ self.decode_tail = max(0., self.weights['decode_save'] - self.prior['stages']['video_decode']['seconds'])
+ self.retry_decode_only = False
+ self.retry_reuse_first = False
+ self.history = None # (output directory, machine, opened): read late by _late_history.
+ self.shown_source = self.remaining_source
- def _sampling_estimate(self, message, now):
- estimate = _timing_seconds(message.get('estimated_step_seconds'))
- done, total = message.get('done'), message.get('total')
- if estimate is None or type(done) is not int or type(total) is not int or not 0 <= done <= total:
+ @classmethod
+ def for_request(cls, machine, canvas, output_directory, *, base_steps=8,
+ refine_steps=3, two_pass=True, preview=False, upscale=False,
+ encoder_prewarm=None, options=None):
+ import platform
+ from .effort_forecast import start_context
+ started, opened = time.perf_counter(), time.monotonic()
+ observed, records = start_context(output_directory, machine)
+ hardware = cls._hardware(observed, machine)
+ # machine.vram_gib/ram_gib can be user policy caps, not physical totals.
+ # A worker process being alive is not proof that a model is resident.
+ warm = encoder_prewarm or {}
+ flags = {'encode_cached': True if upscale else None}
+ if warm.get('gpu_preload') is True and warm.get('state') in ('ready', 'complete') and not warm.get('worker_released'):
+ flags['encoder_cold'] = False
+ tracker = cls(hardware=hardware, records=records, cold_flags=flags, started=started,
+ request=dict(canvas, base_steps=base_steps, refine_steps=refine_steps,
+ two_pass=two_pass, flow='upscale' if upscale else 'preview' if preview else 'full'),
+ **(options or {}))
+ tracker.history = (output_directory, machine, opened)
+ return tracker
+
+ @staticmethod
+ def _hardware(observed, machine):
+ import platform
+ observed = dict(observed)
+ if isinstance(machine.get('hardware'), dict):
+ observed.update(machine['hardware'])
+ device = machine.get('device_identity')
+ device = device if isinstance(device, dict) else {}
+ hardware = dict(gpu_name=observed.get('gpu_name') or machine.get('gpu_name') or device.get('name'),
+ compute_capability=observed.get('capability'),
+ os=observed.get('system') or machine.get('system') or platform.system())
+ for target, source in (('ram_total_gib', 'ram_total'), ('vram_total_gib', 'vram_total')):
+ value = observed.get(source) or device.get('unified_ram_bytes')
+ if _timing_seconds(value):
+ hardware[target] = value / 2**30
+ return hardware
+
+ def _late_history(self):
+ """Use history the background read finished after this request began."""
+ from .effort_forecast import start_context, history_read_at
+ if self.history is None or self.remaining_source == 'measured':
return
- # Within a pass's first step, a layer event extrapolates the whole step
- # from the first layers, which can include compilation and read-ahead
- # (one slow layer once became a 142-minute estimate). With an estimate
- # already in hand, use layer-based step times only after the pass has
- # completed a step; a first run without one still gets its first number.
- base = self.sampling_plan.get('base_steps')
- if (self.forecast_ready and message.get('stage') == 'layers'
- and (done == 0 or type(base) is int and 0 < base == done < total)):
+ output_directory, machine, opened = self.history
+ if (history_read_at(output_directory, machine) or 0.) < opened:
return
- full_step = estimate
- remaining = (total - done) * estimate
- if message.get('uniform_remaining_steps') is False:
- plan = self.sampling_plan
- first, second = plan.get('first', {}), plan.get('second') or {}
- area = first.get('width', 0) * first.get('height', 0)
- if not area or not second.get('width') or not second.get('height'):
- return # Do not treat the two larger refinement NFEs as small NFEs.
- full_step *= second['width'] * second['height'] / area
- remaining = max(0, plan['base_steps'] - done) * estimate + plan['refine_steps'] * full_step
- remaining = max(0., remaining - (_timing_seconds(message.get('step_elapsed_seconds')) or 0.))
- self.weights['sampling'] = max(.001, now - self.phase_started + remaining)
- self.sampling_time_weighted = True
- if 'decode' not in self.weights or self.decode_from_sampling:
- # Windows 1344x768x243 measurements: decode/save was 1.71, 1.90
- # and 2.01 final-resolution warm NFEs on 4060 Ti / 5060 Ti / 5090.
- # This is an approximate first-run ruler, not a GPU speed claim.
- # It scales with this request's work, then yields to frame timing.
- self.weights['decode'] = 1.9 * full_step
- self.decode_from_sampling = True
- self.forecast_ready = True
+ self.history = None # One late update per request.
+ # Work on the live state, but restore all of it if anything fails.
+ saved = {key: dict(value) if isinstance(value, dict) else value for key, value in vars(self).items()}
+ try:
+ observed, rows = start_context(output_directory, machine, timeout=0.)
+ for key, value in self._hardware(observed, machine).items():
+ if value is not None and self.hardware.get(key) is None:
+ self.hardware[key] = value
+ self.records = rows
+ self._reforecast()
+ self.remaining_target = self._target(self.clock())
+ except Exception:
+ # Damaged history keeps the estimate the request already has.
+ vars(self).clear()
+ vars(self).update(saved)
- @staticmethod
- def _forecast_weights(forecast):
- stages = forecast.get('stages') if isinstance(forecast, dict) else None
+ def configure(self, *, plan=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 plan:
+ self.sampling_plan = plan
+ self.request.update(two_pass=bool(plan.get('enabled')), base_steps=plan.get('base_steps', 8),
+ refine_steps=plan.get('refine_steps', 0),
+ sampling_geometry={k: plan[k] for k in ('first', 'second') if plan.get(k)})
+ for key in ('pass1_resident_blocks', 'pass2_resident_blocks'):
+ value = plan.get(key)
+ if type(value) in (int, float) and math.isfinite(value) and 0 <= value <= 50:
+ self.request[key] = value
+ if placement:
+ # generate.py's video_start/decode_resume carry the selected full
+ # canvas engine/decoder plan. Pass 1 can admit extra temporary
+ # cache, so its residency stays unknown for a two-pass request.
+ engine, decoder = placement.get('engine'), placement.get('decoder')
+ engine = engine if isinstance(engine, dict) else {}
+ decoder = decoder if isinstance(decoder, dict) else {}
+ blocks = engine.get('resident_blocks')
+ if type(blocks) in (int, float) and math.isfinite(blocks) and 0 <= blocks <= 50:
+ key = 'pass2_resident_blocks' if self.request['two_pass'] else 'pass1_resident_blocks'
+ self.request[key] = blocks
+ blocks = decoder.get('resident_blocks')
+ if type(blocks) in (int, float) and math.isfinite(blocks) and 0 <= blocks <= 36:
+ self.request['decoder_resident_blocks'] = blocks
+ if type(decoder.get('offload')) is bool:
+ self.request['decoder_offload'] = decoder['offload']
+ if media is not None:
+ self.request.update(task=task_for(media), lora_count=len(media.get('loras') or []),
+ reference_count=len(media.get('references') or []) +
+ sum(bool(media.get(k)) for k in ('first', 'last')))
+ if conditioning:
+ self.cold_flags['encode_cached'] = True
+ self._reforecast()
+
+ def _reforecast(self, *, reset_source=False):
+ from .stage_estimate import predict_prior, STAGES
+ from .effort_forecast import stage_forecast
+ self.prior = predict_prior(self.hardware, self.request, self.cold_flags, self.params)
+ weights = {k: self.prior['stages'][k]['seconds'] for k in STAGES}
+ local = stage_forecast(self.records, self.request, self.cold_flags, weights, version=_engine_version())
+ weights.update(local.get('stages', {}))
+ self.typical = local['typical']
+ self.local = local
+ if reset_source or self.remaining_source != 'measured':
+ self.remaining_source = 'local' if local.get('stages') else 'similar'
+ for key, value in weights.items():
+ if key not in self.completed:
+ self.weights[key] = value
+ self.decode_tail = max(0., self.weights['decode_save'] - self.prior['stages']['video_decode']['seconds'])
+
+ def forecast(self, value):
+ """Consume older worker forecasts without closing or crediting a phase."""
+ value = value.get('forecast', value) if isinstance(value, dict) else {}
+ if not isinstance(value, dict):
+ return
+ stages = value.get('stages') or {}
if not isinstance(stages, dict):
- return {}
- values = {
- 'encoding': _timing_seconds(stages.get('text_encode_seconds')),
- 'load': _timing_seconds(stages.get('load_seconds')),
- 'sampling': _timing_seconds(stages.get('sample_seconds')),
- 'decode': _timing_seconds(stages.get('decode_save_seconds')),
- }
- values = {key: value for key, value in values.items() if value is not None}
- # Sparse phase forecasts expose work_seconds plus its independently
- # predicted components. Keep the measured residual as the final
- # save/cleanup tail instead of silently dropping it or double-counting
- # the worker total.
+ return
+ # Worker predictions lack the bridge's two-record similarity evidence;
+ # they must never create a local typical or replace live measurements.
+ if self.remaining_source == 'measured':
+ return
+ mapping = {'encode': 'text_encode_seconds', 'load': 'load_seconds', 'decode_save': 'decode_save_seconds'}
+ for key, source in mapping.items():
+ seconds = _timing_seconds(stages.get(source))
+ if seconds is not None and key not in self.completed:
+ self.weights[key] = seconds
+ sample = _timing_seconds(stages.get('sample_seconds'))
+ if sample:
+ keys = [k for k in ('pass1', 'upscale', 'pass2') if k not in self.completed]
+ total = sum(self.weights[k] for k in keys)
+ if total:
+ for key in keys:
+ self.weights[key] *= sample / total
work = _timing_seconds(stages.get('work_seconds'))
- residual = work - sum(values.get(key, 0.) for key in ('load', 'sampling', 'decode')) if work is not None else 0.
- if residual > 0:
- values['decode'] = values.get('decode', 0.) + residual
- return values
+ parts = [_timing_seconds(stages.get(k)) for k in ('load_seconds', 'sample_seconds', 'decode_save_seconds')]
+ if work and all(v is not None for v in parts) and 'decode_save' not in self.completed:
+ self.weights['decode_save'] += max(0., work - sum(parts))
- def forecast(self, value):
- value = value.get('forecast') if isinstance(value, dict) and 'forecast' in value else value
- weights = self._forecast_weights(value)
- if weights:
- # The prediction is emitted after prompt encoding has completed.
- # Close that phase before the first video-model event so its
- # measured weight is credited instead of starting a second timer.
- if self.phase == 'encoding':
- self.measured['encoding'] = max(.001, self.clock() - self.phase_started)
- self.completed.add('encoding')
- self.phase = None
- self.weights.update(weights)
- if 'decode' in weights:
- self.decode_from_sampling = False
- self.weights.update(self.measured)
- self.total = sum(self.weights.values())
- self.forecast_ready = all(name in self.weights for name in ('sampling', 'decode'))
-
- def _base(self):
- return sum(self.weights.get(name, 0.) for name in self.completed)
-
- def _message_phase(self, message):
- if message.get('timing_phase') in ('encoding', 'load', 'sampling', 'decode'):
- return message['timing_phase']
- phase = message.get('phase')
- return {'sampling': 'sampling', 'sample_finalize': 'decode',
- 'complete': 'decode'}.get(phase)
-
- def annotate(self, message):
- message = dict(message)
- if isinstance(message.get('sampling_plan'), dict):
- self.sampling_plan = message['sampling_plan']
- if isinstance(message.get('prediction'), dict):
- self.forecast(message['prediction'])
- retry = message.get('retry') if isinstance(message.get('retry'), dict) else {}
- if retry.get('reuse_sampling') is True:
- self.completed.add('sampling')
- phase = self._message_phase(message)
- now = self.clock()
- if phase and phase != self.phase:
- if self.phase is not None:
- self.completed.add(self.phase)
- self.measured[self.phase] = max(.001, now - self.phase_started)
- self.weights[self.phase] = self.measured[self.phase]
- self.phase, self.phase_started = phase, now
+ def _enter(self, phase, now):
+ from .stage_estimate import STAGES
+ if phase == self.phase:
+ return
+ self._late_history()
+ if self.phase is not None and STAGES.index(phase) < STAGES.index(self.phase):
+ # Logs are drained per file, not chronologically. An older encoder
+ # line must not reopen a stage after video work has already begun.
+ # Explicit retries reset phase/completed in _retry instead.
+ return
+ if self.phase is not None:
+ self.measured[self.phase] = max(.001, now - self.phase_started)
+ self.weights[self.phase] = self.measured[self.phase]
+ self.completed.add(self.phase)
+ # Forward transitions also finish stages skipped by caches or lost logs.
+ for key in STAGES[:STAGES.index(phase)]:
+ self.completed.add(key)
+ self.completed.discard(phase) # Re-entered stages are pending again.
+ self.phase, self.phase_started = phase, now
+ self.count = self._initial_count()
+ self.decode_remaining = None
+
+ def _initial_count(self):
+ from .stage_estimate import canvases, step_counts
+ if self.phase == 'load':
+ return (0, 50, 1)
+ if self.phase in ('pass1', 'pass2'):
+ count = step_counts(self.request)[0 if self.phase == 'pass1' else 1]
+ return (0, count * 50, 1)
+ if self.phase == 'decode_save':
+ return (0, canvases(self.request)[2]['frames'], 1)
+ return None
+
+ def _set_count(self, done, total, margin=1):
+ # Duplicate/delayed logs cannot undo already witnessed counts. Using
+ # the smallest known unit avoids lowering the ceiling on the first
+ # counted event after an uncounted stage-start notification.
+ candidate = (max(0, done), total, margin)
+ old = self.count
+ if old is None or (candidate[0] + margin) / max(total, 1) >= (old[0] + old[2]) / max(old[1], 1):
+ self.count = candidate
+
+ def _phase_for(self, message, event):
+ name = event.get('event')
+ if self.retry_decode_only:
+ return 'decode_save'
+ if name == 'decode_resume' or message.get('phase') == 'sample_finalize':
+ return 'decode_save'
+ if message.get('stage') in ('latent_upscale', 'first_pass_reused'):
+ return 'upscale'
+ phase = message.get('timing_phase') or message.get('phase')
if phase == 'sampling':
- self._sampling_estimate(message, now)
- if phase == 'decode' and message.get('stage') == 'video':
- done, total = message.get('done'), message.get('total')
+ # `loaded` falsely looks like sampling 0/N in the legacy converter.
+ if name == 'loaded':
+ return 'load'
+ done = message.get('done', 0)
+ base = self.request['base_steps']
+ if self.request['flow'] == 'upscale' or self.retry_reuse_first:
+ return 'pass2'
+ if self.request['flow'] != 'preview' and self.request['two_pass']:
+ if done > base or (done == base and (name == 'sampling_start' or message.get('stage') in ('layers', 'inputs'))):
+ return 'pass2'
+ return 'pass1'
+ return {'encoding': 'encode', 'load': 'load', 'decode': 'decode_save'}.get(phase)
+
+ def _retry(self, retry, now):
+ # A retry changes the plan; the earlier load no longer says how fast
+ # this machine is, and measured steps arrive again soon.
+ self.slow_start = False
+ self.retry_decode_only = retry.get('reuse_sampling') is True
+ self.retry_reuse_first = retry.get('reuse_first_pass') is True
+ start = 'decode_save' if self.retry_decode_only else 'load'
+ if not self.retry_decode_only:
+ self.steps['pass2'].clear()
+ if not retry.get('reuse_first_pass'):
+ self.steps['pass1'].clear()
+ from .stage_estimate import STAGES
+ self.completed = set(STAGES[:STAGES.index(start)])
+ if self.retry_reuse_first and not self.retry_decode_only:
+ self.completed.add('pass1')
+ self.phase, self.phase_started = start, now
+ self.count, self.decode_remaining = self._initial_count(), None
+ self.live_calibration = False
+ # Recovery can change placement. Wait for the new attempt's plan;
+ # retained step durations are not new measurements of pending work.
+ for key in ('pass1_resident_blocks', 'pass2_resident_blocks',
+ 'decoder_resident_blocks', 'decoder_offload'):
+ self.request.pop(key, None)
+ self._reforecast(reset_source=True)
+ self.ceiling_base = self.fraction
+ self.ceiling_weights = {k: v for k, v in self.weights.items() if k not in self.completed}
+
+ def _counts_and_live(self, message, event, now):
+ from .stage_estimate import predict_live, step_counts
+ phase = self.phase
+ done, total = message.get('done'), message.get('total')
+ if phase in ('pass1', 'pass2'):
+ index = 0 if phase == 'pass1' else 1
+ count = step_counts(self.request)[index]
+ offset = self.request['base_steps'] if index else 0
+ if type(done) is int:
+ local_done = max(0, min(count, done - offset))
+ blocks, block = message.get('blocks'), message.get('block')
+ if type(blocks) is int and blocks > 0 and type(block) is int:
+ # One step of margin: layer events are dispatch estimates,
+ # steps are the synchronized counts (a first step may compile).
+ self._set_count(local_done * blocks + max(0, block - 1), count * blocks,
+ blocks if self.ceiling == 'stretch' else 1)
+ else:
+ # Keep the same one-layer margin across step boundaries;
+ # changing from one step to one layer could lower a ceiling.
+ self._set_count(local_done * 50, count * 50, 50 if self.ceiling == 'stretch' else 1)
+ seconds = _timing_seconds(message.get('last_step_seconds'))
+ if seconds and local_done > 0:
+ self.steps[phase][local_done] = seconds
+ if 1 in self.steps[phase] and 2 in self.steps[phase]:
+ self.live_calibration = True
+ elif phase == 'load':
+ if event.get('event') == 'loaded':
+ done, total = 50, 50
+ elif event.get('event') == 'prepared_blocks':
+ done, total = event.get('blocks'), 50
+ elif event.get('event') == 'model_load_phase':
+ done, total = event.get('done'), event.get('total')
+ # LoRA groups describe a substage, not completion of the whole load.
+ if type(done) is int and type(total) is int and total > 0 and message.get('unit') != 'bytes':
+ self._set_count(done, total)
+ elif phase == 'decode_save' and message.get('stage') == 'video':
elapsed = _timing_seconds(message.get('elapsed_seconds'))
- if elapsed and type(done) is int and type(total) is int and 0 < done <= total:
- video_seconds = elapsed * total / done
- # Reports put audio/MP4/post-decode cleanup at about 6-8% of
- # video decode time. Retain this tail until audio/save starts.
- self.decode_tail = video_seconds * .08
- self.weights['decode'] = now - self.phase_started + video_seconds - elapsed + self.decode_tail
- self.forecast_ready = True
- elif phase == 'decode':
- self.decode_tail = 0.
- self.total = sum(self.weights.values())
- if message.get('phase') == 'complete' or message.get('overall', {}).get('status') == 'complete':
- message['overall'] = {'status': 'complete', 'fraction': 1., 'estimated': False,
- 'elapsed_seconds': now - self.started, 'remaining_seconds': 0.}
- return message
- overall = {'status': 'running', 'estimated': self.forecast_ready,
- 'elapsed_seconds': now - self.started}
- if self.forecast_ready and self.total > 0:
- start = self._base() / self.total
- weight = self.weights.get(self.phase, 0.)
+ if type(done) is int and type(total) is int and 0 <= done <= total and total > 0:
+ self._set_count(done, total)
+ if elapsed and done > 0:
+ self.decode_remaining = elapsed * (total - done) / done + self._after_frames(total)
+ self.weights[phase] = now - self.phase_started + self.decode_remaining
+ self.remaining_source = 'measured'
+ elif phase == 'decode_save' and event.get('event') == 'decode_phase':
+ # These real transitions finish video frames even for a decoder
+ # that does not stream progress callbacks.
+ if event.get('phase') in ('Loading and decoding audio', 'Saving MP4 and audio'):
+ total = self.count[1] if self.count else self.request['frames']
+ self._set_count(total, total)
+ if self.decode_remaining is None:
+ # Without frame callbacks this is the first sign that the
+ # video is decoded; only the measured tail remains.
+ self.decode_remaining = self._after_frames(total)
+ self.weights[phase] = now - self.phase_started + self.decode_remaining
+ self.remaining_source = 'measured'
+ # Only contiguous, actually completed steps calibrate the model.
+ steps = {}
+ for key, values in self.steps.items():
+ steps[key] = []
+ for i in range(1, len(values) + 1):
+ if i not in values:
+ break
+ steps[key].append(values[i])
+ if self.live_calibration and any(len(v) >= 2 for v in steps.values()):
+ done_stages = [('decode' if k == 'decode_save' else k) for k in self.completed]
+ live = predict_live(dict(hardware=self.hardware, request=self.request, cold_flags=self.cold_flags,
+ pass1_steps=steps['pass1'], pass2_steps=steps['pass2'], completed_stages=done_stages,
+ current_stage=phase, step_elapsed_seconds=message.get('step_elapsed_seconds', 0.),
+ pass_wall_overhead_done=[k for k, v in steps.items() if v]), self.params)
+ # With matching history on this machine, scale its own stage times
+ # by the measured warm step instead of the general model.
+ from statistics import median
+ history, warm, ratio = self.local.get('stages') or {}, self.local.get('warm') or {}, None
+ for key in ('pass2', 'pass1'):
+ if len(steps[key]) >= 2 and warm.get(key):
+ ratio = min(2., max(.5, median(steps[key][1:]) / warm[key]))
+ break
+ for key in ('pass1', 'upscale', 'pass2', 'decode_save'):
+ if key in self.completed or (key == 'decode_save' and self.decode_remaining is not None):
+ continue
+ if ratio is not None and key in history:
+ self.weights[key] = history[key] * (1. if key == 'decode_save' else ratio)
+ continue
+ remaining = live['stages'][key]['seconds']
+ if key == phase:
+ if key == 'decode_save':
+ # decode/save prediction is a full duration until frames arrive.
+ self.weights[key] = remaining
+ else:
+ self.weights[key] = now - self.phase_started + remaining
+ else:
+ self.weights[key] = remaining
+ self.decode_tail = max(0., live['stages']['decode_save']['seconds'] - live['stages']['video_decode']['seconds'])
+ self.remaining_source = 'measured'
+
+ def _after_frames(self, frames):
+ # Audio, MP4 and saving after the last decoded frame: about 2 s plus
+ # 0.03 s per frame (measured, slightly below the median, so the bar
+ # rarely jumps at saving), never more than the model's tail.
+ return min(self.decode_tail, 2. + .03 * frames)
+
+ def _slow_factor(self, now):
+ # A disk-bound 16 GB machine that loads much slower than predicted is
+ # slower in every later stage too (reports: about the square root of
+ # the load ratio). Larger memory or a slow encode does not predict it.
+ if not self.slow_start or self.remaining_source != 'similar':
+ return 1.
+ ram = self.hardware.get('ram_total_gib')
+ if ram is None or ram > 16.5:
+ return 1.
+ predicted = self.prior['stages']['load']['seconds']
+ actual = self.measured.get('load') or (now - self.phase_started if self.phase == 'load' else None)
+ if not actual or predicted <= 1 or actual / predicted <= 2:
+ return 1.
+ return min(4., math.sqrt(actual / predicted))
+
+ def _target(self, now):
+ factor = self._slow_factor(now)
+ later = ('pass1', 'upscale', 'pass2', 'decode_save')
+ remaining = sum(v * (factor if k in later else 1.)
+ for k, v in self.weights.items() if k not in self.completed and k != self.phase)
+ elapsed = max(0., now - self.phase_started)
+ # The stage under way is scaled too until its speed is measured.
+ current = self.weights.get(self.phase, 0.) * (factor if self.phase in later else 1.) - elapsed
+ if current < 0:
+ current = max(3., .1 * elapsed)
+ return max(0., remaining + current)
+
+ def _ceiling(self, now):
+ weights = (self.ceiling_weights if self.ceiling == 'prior' else
+ {k: self.weights[k] for k in self.ceiling_weights})
+ stretch = self.ceiling == 'stretch' and (self.count is None or self.count[0] <= 0)
+ if stretch and self.phase in weights:
+ # An overrunning stage without counted work keeps its end ahead of
+ # it, by the same remainder the remaining-time target assumes.
elapsed = max(0., now - self.phase_started)
- seconds = self.weights.get(self.phase)
- fraction = start
- if weight:
- fraction += weight / self.total * min(.95, elapsed / max(seconds, 1e-9))
- remaining = max(0., self.total - self._base() - min(elapsed, seconds or 0.))
- future = sum(value for name, value in self.weights.items()
- if name not in self.completed and name != self.phase)
- overall.update(fraction=fraction, phase_start_fraction=start,
- phase_weight=weight / self.total if self.total else 0.,
- phase_elapsed_seconds=elapsed, phase_seconds=seconds,
- remaining_seconds=remaining,
- remaining_floor_seconds=max(future, self.decode_tail),
- sampling_time_weighted=self.sampling_time_weighted)
- message['overall'] = overall
- return message
+ weights[self.phase] = max(weights[self.phase], elapsed + max(3., .1 * elapsed))
+ total = sum(weights.values())
+ if total <= 0:
+ if self.ceiling in ('current', 'stretch'):
+ self.last_ceiling = .99
+ return .99
+ credit = sum(v for k, v in weights.items() if k in self.completed)
+ # An uncounted stage earns its allowance over time, not at its entry.
+ # This also avoids releasing all of upscale's share at a boundary.
+ duration = weights.get(self.phase, 0.)
+ fraction = min(1., max(0., now - self.phase_started) / max(duration, .001))
+ if self.count is not None and not stretch:
+ done, count, margin = self.count
+ fraction = min(1., max(0., (done + margin) / max(count, 1)))
+ credit += duration * fraction
+ value = min(.99, self.ceiling_base + (1. - self.ceiling_base) * credit / total)
+ if self.ceiling in ('current', 'stretch'):
+ self.last_ceiling = max(self.last_ceiling, value)
+ value = self.last_ceiling
+ return value
+
+ def _smooth(self, dt):
+ if self.smoothing == 'track':
+ shown, target = self.remaining_shown, self.remaining_target
+ if target > shown:
+ # Slower than predicted: stop counting down, then rise gently.
+ self.remaining_shown = min(target, shown + self.rate * shown * dt)
+ else:
+ shown = max(target, shown - dt)
+ self.remaining_shown = max(0., shown - (shown - target) * (1. - math.exp(-dt / max(self.tau, .001))))
+ return
+ # Hold suppresses countdown only for an upward target correction.
+ # Both policies approach the target without crossing it by correction;
+ # countdown itself can pass below it. Keep a positive running remainder.
+ if self.smoothing == 'hold' and self.remaining_target > self.remaining_shown:
+ shown = self.remaining_shown
+ else:
+ floor = 3. if self.smoothing == 'countdown' else min(3., self.remaining_shown)
+ shown = max(floor, self.remaining_shown - dt)
+ limit = self.rate * shown * dt
+ self.remaining_shown = max(0., shown + max(-limit, min(limit, self.remaining_target - shown)))
+
+ def _render(self, message, now, *, heartbeat=False):
+ if self.remaining_source == 'local' and self.shown_source == 'similar':
+ # History read after the start replaces the general estimate: the
+ # page drops "initial estimate" and corrects once, so do not smooth.
+ # (A first measurement keeps smoothing; two steps are still noisy.)
+ self.remaining_shown = self.remaining_target
+ self.shown_source = self.remaining_source
+ elapsed = max(0., now - self.started)
+ candidate = elapsed / max(elapsed + self.remaining_shown, .001)
+ if (self.final is not None and self.phase == 'decode_save' and self.count
+ and self.count[0] >= self.count[1] > 0):
+ # Every frame is decoded; only audio, MP4 and saving remain, often
+ # for a few seconds only. Move there as fast as the rise limit allows.
+ candidate = max(candidate, self.final)
+ ceiling = self._ceiling(now)
+ limit = .99
+ if self.max_rise is not None:
+ limit = min(limit, self.fraction + self.max_rise * max(0., min(1., now - self.last_publish)))
+ self.fraction = max(self.fraction, min(limit, candidate, ceiling))
+ overall = dict(status='complete' if self.finished else 'running', estimated=True,
+ fraction=1. if self.finished else self.fraction,
+ remaining_seconds=0. if self.finished else self.remaining_shown,
+ elapsed_seconds=elapsed, remaining_source=self.remaining_source,
+ phase_start_fraction=self.fraction, phase_weight=0., remaining_floor_seconds=0.,
+ at_ceiling=not self.finished and candidate >= ceiling,
+ sampling_time_weighted=True)
+ key = self.phase
+ if key in self.steps:
+ key += '_first' if not self.steps[key] else '_warm'
+ if key in self.typical:
+ overall.update(typical_seconds=self.typical[key], typical_source='local')
+ if heartbeat:
+ overall['heartbeat'] = True
+ self.last_publish = now
+ return dict(message, overall=overall)
+
+ def annotate(self, message, *, event=None):
+ message, event = dict(message), event or {}
+ now = self.clock()
+ if self.finished:
+ return self._render(message, now)
+ dt = max(0., now - self.last_tick)
+ plan = event if event.get('event') == 'sampling_plan' else message.get('sampling_plan')
+ if isinstance(plan, dict):
+ self.configure(plan=plan)
+ if isinstance(message.get('prediction'), dict):
+ self.forecast(message['prediction'])
+ retried = isinstance(message.get('retry'), dict) or message.get('stage') == 'preview_mismatch'
+ if isinstance(message.get('retry'), dict):
+ self._retry(message['retry'], now)
+ if message.get('stage') == 'preview_mismatch':
+ self.request['flow'] = 'full'
+ self._retry({}, now)
+ if event.get('event') in ('video_start', 'decode_resume'):
+ self.configure(placement=event)
+ phase = self._phase_for(message, event)
+ if phase:
+ self._enter(phase, now)
+ if event.get('event') == 'conditioning_cache_hit':
+ self.cold_flags['encode_cached'] = True
+ if event.get('event') == 'conditioning_reused':
+ self.cold_flags['encode_cached'] = True
+ if event.get('event') == 'encoder_device_reuse':
+ self.cold_flags['encoder_cold'] = False
+ if event.get('event') == 'compute_device':
+ self.hardware.update(gpu_name=event.get('name') or self.hardware.get('gpu_name'))
+ if _timing_seconds(event.get('vram_total_bytes')):
+ self.hardware['vram_total_gib'] = event['vram_total_bytes'] / 2**30
+ self._reforecast()
+ if not retried:
+ self._counts_and_live(message, event, now)
+ self.remaining_target = self._target(now)
+ self._smooth(dt)
+ self.last_tick = self.last_event = now
+ self.total = sum(self.weights.values())
+ self.finished = message.get('phase') == 'complete' or message.get('overall', {}).get('status') == 'complete'
+ if self.finished:
+ self.measured[self.phase] = max(.001, now - self.phase_started)
+ self.weights[self.phase] = self.measured[self.phase]
+ self.total = sum(self.weights.values())
+ self.completed.update(self.weights)
+ self.remaining_target = self.remaining_shown = 0.
+ self.fraction = 1.
+ if message.keys() - {'report_id'}:
+ self.last_message = {k: v for k, v in message.items() if k not in ('overall', 'reset', 'new_request', 'prediction', 'sampling_plan')}
+ else:
+ message = dict(self.last_message, **message)
+ return self._render(message, now)
+
+ def observe(self, event):
+ """Use an engine event that has no progress message, without publishing."""
+ published = self.last_publish
+ self.annotate({}, event=event)
+ self.last_publish = published
+
+ def heartbeat(self):
+ now = self.clock()
+ if self.finished or now - self.last_publish < 1.:
+ return None
+ if self.silence == 'stage':
+ # Admit only the part of this interval inside the predicted stage.
+ # Crossing its end freezes at the boundary, even with sparse polls.
+ end = self.phase_started + self.weights.get(self.phase, 0.)
+ dt = max(0., min(now, end) - max(self.last_tick, self.phase_started))
+ if dt:
+ self.remaining_target = max(0., self.remaining_target - dt)
+ self._smooth(dt)
+ self.last_tick = max(self.last_tick, min(now, end))
+ # Silent time is not counted down until the next engine event shows
+ # the engine is still working; that event then counts all of it.
+ return self._render(self.last_message, now, heartbeat=True)
def source_root():
@@ -581,7 +1055,7 @@ 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):
+ prompt_rewrite_report=None, preview=False, refine_from=None, report_extra=None):
if type(two_pass) is not bool:
raise ValueError('Two-pass generation must be a boolean')
if type(force_regenerate) is not bool:
@@ -650,12 +1124,22 @@ def generate(prompt, width, height, seconds, seed, output_directory, *,
state['encoder_prewarm'] = prewarm_summary(encoder_prewarm)
save(run / 'comfy-request.json', state)
started = time.monotonic()
- whole_progress = WholeVideoProgress()
+ try:
+ whole_progress = WholeVideoProgress.for_request(machine, canvas, output_directory,
+ base_steps=base_steps, refine_steps=refine_steps, two_pass=two_pass,
+ preview=preview, upscale=bool(upscale), encoder_prewarm=state['encoder_prewarm'])
+ except Exception:
+ # A progress estimate cannot prevent generation, even without its parameters.
+ try:
+ whole_progress = WholeVideoProgress()
+ except Exception:
+ whole_progress = _PlainProgress()
+ whole_progress = _SafeProgress(whole_progress)
from .comfy_progress import REPORTS
report_id = REPORTS.register(output)
- def send_progress(message):
+ def send_progress(message, event=None):
if progress:
- progress(whole_progress.annotate(dict(message, report_id=report_id)))
+ progress(whole_progress.annotate(dict(message, report_id=report_id), event=event))
process = None
from .result_cache import ResultCache, request_key, inspect_bounded
cache = ResultCache(output_directory)
@@ -670,8 +1154,14 @@ def generate(prompt, width, height, seconds, seed, output_directory, *,
tails[2].reset()
message = progress_message(event)
if message:
- send_progress(message)
+ send_progress(message, event)
+ else:
+ whole_progress.observe(event)
+ heartbeat = whole_progress.heartbeat()
+ if progress and heartbeat:
+ progress(heartbeat)
try:
+ send_progress({'label': 'Preparing video'})
if interrupted:
interrupted()
extra = {}
@@ -745,10 +1235,9 @@ def generate(prompt, width, height, seconds, seed, output_directory, *,
state['sampling_cache_install'] = preparation
if preparation['seconds']:
started += preparation['seconds']
- whole_progress = WholeVideoProgress()
send_progress({'reset': True, 'label': 'Preparing video'})
- whole_progress.sampling_plan = planned
- whole_progress.forecast(progress_history_forecast(root, machine, dict(canvas, sampling_plan=planned)))
+ whole_progress.configure(plan=planned, media=extra.get('media', {}),
+ conditioning=bool(extra.get('conditioning')))
send_progress({'label': 'Preparing %.3f s video + audio · %d × %d' %
(canvas['seconds'], width, height)})
if release_models:
@@ -804,6 +1293,11 @@ def generate(prompt, width, height, seconds, seed, output_directory, *,
from .comfy_launcher_api import repair_hint
from .failure_details import generation_failure
raise RuntimeError('FreeVideo did not complete the requested video.\n' + generation_failure(run, repair=repair_hint()))
+ if report_extra:
+ # Only the newly generated, verified result is annotated. Cache hits
+ # return earlier and retain their historical report byte for byte.
+ report.update(report_extra)
+ save(output.with_suffix('.request.json'), report)
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_chain.py b/freevideo_engine/comfy_chain.py
new file mode 100644
index 0000000..cc72eec
--- /dev/null
+++ b/freevideo_engine/comfy_chain.py
@@ -0,0 +1,437 @@
+"""Local ComfyUI queue adapter and optional background-chain routes."""
+import json
+import logging
+import math
+import os
+from pathlib import Path, PurePosixPath
+import ssl
+import threading
+import time
+from urllib import error, request
+
+from .chain_runner import ChainBusy, ChainRunner
+from . import chain_plan, chain_store
+
+RUNNER = None
+CONTINUE_INPUTS = {'after': 'continue_from', 'before': 'continue_to'}
+
+
+def _generate_inputs():
+ try:
+ from .comfy_nodes import FreeVideoGenerate
+ return {row.id: row for row in FreeVideoGenerate.define_schema().inputs}
+ except Exception:
+ return {}
+
+
+def seconds_for_frames(frames, minimum=1.625, maximum=60., step=.1):
+ """Pick a legal duration inside the requested VAE cell, below its upper edge."""
+ from .geometry import geometry
+ value = (frames - .5) / 24
+ if step is not None and step > 0:
+ value = round(math.floor(value / step) * step, 10)
+ if minimum is not None:
+ value = max(minimum, value)
+ if maximum is not None:
+ value = min(maximum, value)
+ if geometry(seconds=value)['frames'] != frames:
+ raise ValueError('Block frames cannot be represented by the node duration input')
+ return value
+
+
+class ComfyHost:
+ continuation_inputs = tuple(CONTINUE_INPUTS.values())
+
+ def __init__(self, server):
+ self.server = server
+
+ def inputs(self, block_inputs):
+ schema = _generate_inputs()
+ values = {key: block_inputs[key] for key in ('text', 'seed')}
+ if 'frames' in schema:
+ values['frames'] = block_inputs['frames']
+ else:
+ seconds = schema.get('seconds')
+ values['seconds'] = seconds_for_frames(block_inputs['frames'],
+ getattr(seconds, 'min', 1.625), getattr(seconds, 'max', 60.), getattr(seconds, 'step', .1))
+ independent = os.environ.get('FREEVIDEO_CHAIN_INDEPENDENT') == '1'
+ for key, name in CONTINUE_INPUTS.items():
+ # Each direction is filled once the node offers its input.
+ if name in schema:
+ values[name] = '' if independent else block_inputs[key]
+ return values
+
+ def work_exists(self, path):
+ import folder_paths
+ root = Path(folder_paths.get_output_directory()).resolve()
+ output = (root / path).resolve()
+ return output.is_relative_to(root) and output.is_file()
+
+ def submit(self, prompt_id, prompt, extra_data):
+ try:
+ from comfy.cli_args import args
+ except ImportError:
+ args = None
+ address = getattr(self.server, 'address', None) or getattr(args, 'listen', None) or '127.0.0.1'
+ port = getattr(self.server, 'port', None) or getattr(args, 'port', None) or 8188
+ address = address.split(',')[0].strip('[]')
+ address = {'0.0.0.0': '127.0.0.1', '::': '::1'}.get(address, address)
+ if ':' in address:
+ address = '[' + address + ']'
+ tls = bool(getattr(args, 'tls_keyfile', None))
+ url = '%s://%s:%s/prompt' % ('https' if tls else 'http', address, port)
+ body = dict(prompt=prompt, prompt_id=prompt_id, extra_data=extra_data)
+ if extra_data.get('client_id') is not None:
+ body['client_id'] = extra_data['client_id']
+ message = request.Request(url, data=json.dumps(body).encode('utf-8'),
+ headers={'Content-Type': 'application/json'}, method='POST')
+ # This request belongs to our own server, even with an inherited proxy.
+ handlers = [request.ProxyHandler({})]
+ if tls:
+ context = ssl.create_default_context()
+ context.check_hostname = False
+ context.verify_mode = ssl.CERT_NONE
+ handlers.append(request.HTTPSHandler(context=context))
+ opener = request.build_opener(*handlers)
+ try:
+ with opener.open(message, timeout=30) as response:
+ response.read()
+ except error.HTTPError as failure:
+ if failure.code != 400:
+ raise
+ try:
+ value = json.loads(failure.read())
+ parts = [(value.get('error') or {}).get('message') or 'Prompt validation failed']
+ first = next(iter((value.get('node_errors') or {}).values()), None)
+ if first:
+ parts.append(json.dumps(first, ensure_ascii=False))
+ raise RuntimeError('; '.join(parts)) from None
+ except (ValueError, TypeError, AttributeError):
+ raise RuntimeError('Prompt validation failed') from None
+
+ def status(self, prompt_id):
+ queue = self.server.prompt_queue
+ running, pending = queue.get_current_queue()
+ for rows, state in ((running, 'running'), (pending, 'pending')):
+ if any(row[1] == prompt_id for row in rows):
+ return dict(state=state, error=None, output=None)
+ history = queue.get_history(prompt_id=prompt_id).get(prompt_id)
+ if history is None:
+ return dict(state='missing', error=None, output=None)
+ status = history.get('status')
+ outputs = history.get('outputs') or {}
+ output = None
+ for node in outputs.values():
+ summaries = node.get('freevideo_summary') or []
+ if summaries:
+ output = summaries[0].get('video')
+ break
+ for row in node.get('videos', node.get('images', [])):
+ if row.get('type') == 'output' and row.get('filename', '').lower().endswith('.mp4'):
+ output = str(PurePosixPath(row.get('subfolder', '')) / row['filename'])
+ break
+ if status and status.get('status_str') == 'success' or status is None and outputs:
+ return dict(state='success', error=None, output=output)
+ messages = (status or {}).get('messages', [])
+ if any(row[0] == 'execution_interrupted' for row in messages):
+ return dict(state='interrupted', error=None, output=None)
+ message = next((row[1].get('exception_message') for row in messages if row[0] == 'execution_error'), None)
+ return dict(state='error', error=message or 'Prompt execution failed', output=None)
+
+ def cancel(self, prompt_id, node):
+ from .comfy_progress import cancel_request
+ import nodes
+ return cancel_request(self.server.prompt_queue, prompt_id, node, nodes.interrupt_processing)
+
+ def join(self, record, cancelled):
+ try:
+ from .chain_join import join_outputs
+ except ImportError:
+ raise RuntimeError('Joining is not available in this version') from None
+ planned = record.get('plan')
+ blocks = chain_store.leading_blocks(record)
+ # A planned chain shows exactly the requested length: what the last block made beyond it is left out.
+ frames = planned['frames'] if planned and not planned['single'] and len(blocks) == len(record['blocks']) else None
+ return join_outputs([block['output'] for block in blocks], record['id'], cancelled,
+ frames=frames, replace=record.get('output'))
+
+
+def continuation_directions():
+ """'after' and 'before', each once FreeVideoGenerate has the input that carries it."""
+ schema = _generate_inputs()
+ return {key for key, name in CONTINUE_INPUTS.items() if name in schema}
+
+
+def continuation_available():
+ return 'after' in continuation_directions()
+
+
+def report_fields(chain):
+ def source(value):
+ if isinstance(value, str):
+ return dict(type='block', id=value)
+ return dict(type='work') if value is not None else None
+ return dict(index=chain['index'], count=chain['count'],
+ after=source(chain['after']), before=source(chain['before']))
+
+
+def block_context(server, node_id):
+ try:
+ if RUNNER is not None and server is not None:
+ prompt_id = server.last_prompt_id
+ chain = RUNNER.context(prompt_id, node_id)
+ return dict(chain, _prompt_id=prompt_id) if chain is not None else None
+ except Exception:
+ pass
+ return None
+
+
+def block_finished(chain, node_id, output, report_id, continuation=None):
+ try:
+ if RUNNER is not None and chain is not None:
+ # Capture the executing attempt, so a late callback cannot finish a retry.
+ RUNNER.finished(chain['_prompt_id'], node_id, output, report_id, continuation)
+ except Exception:
+ pass
+
+
+class FakeHost(ComfyHost):
+ """Optional CPU-only prompts for development; never touch the host queue."""
+ fake = True
+
+ def __init__(self, server, seconds=None):
+ super().__init__(server)
+ self.seconds = float(os.environ.get('FREEVIDEO_CHAIN_FAKE_SECONDS', '12')) if seconds is None else seconds
+ if not math.isfinite(self.seconds) or self.seconds < 0:
+ raise ValueError('Fake duration must be finite and nonnegative')
+ self.lock, self.closed = threading.RLock(), threading.Event()
+ self.jobs, self.runner = {}, None
+
+ def inputs(self, block_inputs):
+ return {key: block_inputs[key] for key in ('text', 'frames', 'seed')}
+
+ def join(self, record, cancelled):
+ return chain_store.leading_blocks(record)[-1]['output']
+
+ def _saved_video(self, frames):
+ from .comfy_library import _report, _video
+ import folder_paths
+ root = Path(folder_paths.get_output_directory()).resolve()
+ videos = []
+ for path in (root / 'FreeVideo').glob('*/*/video.mp4'):
+ identity = path.parent.relative_to(root / 'FreeVideo').as_posix()
+ try:
+ path = _video(root, identity)
+ info = path.stat()
+ if not path.is_file() or not info.st_size:
+ continue
+ report = _report(path)
+ count = (report.get('geometry') or {}).get('frames')
+ if 'chain_join' in report or type(count) is not int or count < frames:
+ continue
+ videos.append((info.st_mtime_ns, (Path('FreeVideo') / identity / 'video.mp4').as_posix()))
+ except (OSError, ValueError, TypeError, AttributeError):
+ continue
+ return max(videos)[1] if videos else None
+
+ def submit(self, prompt_id, prompt, extra_data):
+ chain = extra_data['freevideo_chain']
+ node = self.runner.records[chain['id']]['node']
+ job = dict(node=str(node), state='pending', error=None, output=None, cancel=threading.Event())
+ thread = threading.Thread(target=self._run, args=(prompt_id, node, chain, job),
+ name='FreeVideo fake chain block', daemon=True)
+ job['thread'] = thread
+ with self.lock:
+ self.jobs[prompt_id] = job
+ thread.start()
+
+ def _run(self, prompt_id, node, chain, job):
+ from .comfy_progress import STATE, publish
+ progress = None
+ try:
+ if self.closed.is_set() or job['cancel'].is_set():
+ return
+ with self.lock:
+ job['state'] = 'running'
+ if self.runner.context(prompt_id, node) is None:
+ return
+ progress = publish(self.server, node, {'label': 'Preparing video', 'new_request': True})
+ started = time.monotonic()
+ total = max(1, math.ceil(self.seconds / .5))
+ for done in range(total + 1):
+ used = time.monotonic() - started
+ progress = publish(self.server, node, dict(label='Sampling', phase='sampling', done=done, total=total,
+ overall=dict(status='running', estimated=True, fraction=.9 * done / total,
+ elapsed_seconds=used, remaining_seconds=max(0., self.seconds - used))))
+ if done < total and job['cancel'].wait(self.seconds / total):
+ return
+ if self.closed.is_set() or job['cancel'].is_set():
+ return
+ progress = publish(self.server, node, dict(label='Decoding video', phase='decode',
+ overall=dict(status='running', estimated=True, fraction=.95,
+ elapsed_seconds=time.monotonic() - started, remaining_seconds=0.)))
+ frames = self.runner.records[chain['id']]['blocks'][chain['index']]['inputs']['frames']
+ needed = frames - 22 if chain['after'] is not None or chain['before'] is not None else frames
+ output = self._saved_video(needed)
+ if self.closed.is_set() or job['cancel'].is_set():
+ return
+ if output is None:
+ with self.lock:
+ job.update(state='error', error='Fake generation needs a saved video with at least %s frames' % needed)
+ return
+ publish(self.server, node, dict(label='Video saved', phase='complete',
+ overall=dict(status='complete', fraction=1.)))
+ # The shape the engine reports for a continued block.
+ continuation = (dict(overlap_frames=22, new_frames=frames - 22, requested_frames=frames)
+ if chain['after'] is not None else None)
+ with self.lock:
+ self.runner.finished(prompt_id, node, output, None, continuation)
+ job.update(state='success', output=output)
+ except Exception:
+ logging.exception('[FreeVideo] Fake chain generation failed')
+ with self.lock:
+ job.update(state='error', error='Fake generation failed')
+ finally:
+ with self.lock:
+ if job['state'] in ('pending', 'running'):
+ if progress is not None and job['cancel'].is_set() and not self.closed.is_set():
+ with self.runner.lock:
+ # A late cancellation must not end a newer request on this node.
+ current = next((row for row in STATE.snapshot() if row['node'] == str(node)), {})
+ if (current.get('sequence') == progress['sequence']
+ and self.runner.context(prompt_id, node) is not None):
+ publish(self.server, node, dict(label='Generation cancelled', phase='cancelled',
+ overall=dict(status='cancelled')))
+ job['state'] = 'interrupted'
+ self.runner.wake.set()
+
+ def status(self, prompt_id):
+ with self.lock:
+ job = self.jobs.get(prompt_id, {})
+ return dict(state=job.get('state', 'missing'), error=job.get('error'), output=job.get('output'))
+
+ def cancel(self, prompt_id, node):
+ with self.lock:
+ if prompt_id in self.jobs and self.jobs[prompt_id]['node'] == str(node):
+ self.jobs[prompt_id]['cancel'].set()
+
+ def close(self):
+ self.closed.set()
+ with self.lock:
+ jobs = list(self.jobs.values())
+ for job in jobs:
+ job['cancel'].set()
+ for job in jobs:
+ if job['thread'] is not threading.current_thread():
+ job['thread'].join(timeout=2.)
+
+
+def hidden_outputs(root):
+ try:
+ root = Path(root).resolve()
+ def exists(output):
+ path = (root / output).resolve()
+ return path.is_relative_to(root) and path.is_file()
+ return RUNNER.hidden(exists) if RUNNER is not None else set()
+ except Exception:
+ return set()
+
+
+def register():
+ global RUNNER
+ from aiohttp import web
+ from server import PromptServer
+ from .comfy_bridge import installation, installation_root
+ server = PromptServer.instance
+ if server is None or getattr(server, '_freevideo_chain', False):
+ return
+ fake = os.environ.get('FREEVIDEO_CHAIN_FAKE') == '1'
+ root = installation_root() if fake else installation()[0]
+ host = FakeHost(server) if fake else ComfyHost(server)
+ if fake:
+ logging.warning('[FreeVideo] Fake background chain generation is enabled')
+ runner = ChainRunner(Path(root) / 'chains', host, estimate=None)
+ if fake:
+ host.runner = runner
+ RUNNER = runner
+ server._freevideo_chain = True
+
+ def response(value, status=200):
+ return web.json_response(value, status=status, headers={'Cache-Control': 'no-store'})
+
+ async def body(request):
+ try:
+ value = await request.json()
+ except (ValueError, TypeError):
+ raise ValueError('A JSON object is required') from None
+ if not isinstance(value, dict):
+ raise ValueError('A JSON object is required')
+ return value
+
+ @server.routes.post('/freevideo/chain/plan')
+ async def plan(request):
+ try:
+ value = await body(request)
+ return response({'plan': chain_plan.plan(
+ value.get('seconds'), value.get('single', False), value.get('max_frames'),
+ value.get('single_limit_seconds'), value.get('block_seconds'))})
+ except chain_plan.PlanError as failure:
+ return response({'error': str(failure), 'code': failure.code}, 400)
+ except ValueError as failure:
+ return response({'error': str(failure), 'code': 'invalid'}, 400)
+
+ @server.routes.post('/freevideo/chain')
+ async def create(request):
+ try:
+ value = await body(request)
+ normalized = chain_store.validate(value)
+ if not fake and os.environ.get('FREEVIDEO_CHAIN_INDEPENDENT') != '1':
+ missing = {key for row in normalized['blocks'] for key in CONTINUE_INPUTS
+ if row[key] is not None} - continuation_directions()
+ if 'after' in missing:
+ return response({'error': 'Continuing a video is not available in this version'}, 409)
+ if missing:
+ return response({'error': 'Extending backwards or filling a gap is not available in this version'}, 409)
+ return response({'chain': runner.create(value)})
+ except ChainBusy as failure:
+ return response({'error': str(failure)}, 409)
+ except chain_plan.PlanError as failure:
+ return response({'error': str(failure), 'code': failure.code}, 400)
+ except ValueError as failure:
+ return response({'error': str(failure)}, 400)
+
+ def asking(request):
+ # ?client_id=... marks each chain as this page's own or not.
+ query = getattr(request, 'query', None)
+ return query.get('client_id') if query is not None else None
+
+ @server.routes.get('/freevideo/chains')
+ async def listing(request):
+ value = {'chains': runner.list(asking(request)), 'continuation': continuation_available()}
+ if fake:
+ value['fake'] = True
+ return response(value)
+
+ @server.routes.get('/freevideo/chain/{id}')
+ async def get(request):
+ try:
+ return response({'chain': runner.get(request.match_info['id'], asking(request))})
+ except KeyError:
+ return response({'error': 'Unknown chain'}, 404)
+
+ @server.routes.post('/freevideo/chain/{id}/cancel')
+ async def cancel(request):
+ try:
+ return response({'chain': runner.cancel(request.match_info['id'])})
+ except KeyError:
+ return response({'error': 'Unknown chain'}, 404)
+
+ @server.routes.post('/freevideo/chain/{id}/resume')
+ async def resume(request):
+ try:
+ value = await body(request) if request.can_read_body else {}
+ return response({'chain': runner.resume(request.match_info['id'], value.get('client_id'))})
+ except KeyError:
+ return response({'error': 'Unknown chain'}, 404)
+ except ValueError as failure:
+ return response({'error': str(failure)}, 409)
diff --git a/freevideo_engine/comfy_editor.py b/freevideo_engine/comfy_editor.py
new file mode 100644
index 0000000..c730fed
--- /dev/null
+++ b/freevideo_engine/comfy_editor.py
@@ -0,0 +1,1197 @@
+"""Local editor records, imported previews and bounded CPU media inspection.
+
+All retained data lives under output/FreeVideo/.editor. Imports never become
+creations, and their names, contents and decoding errors are never logged.
+"""
+import asyncio
+import copy
+import hashlib
+import json
+import logging
+import math
+import os
+import queue
+import re
+import shutil
+import tempfile
+import threading
+import time
+import uuid
+from datetime import datetime, timezone
+from fractions import Fraction
+from pathlib import Path, PurePosixPath, PureWindowsPath
+from urllib.parse import unquote, urlencode, urlsplit
+
+from .comfy_library import _ID, _plain, _video
+from .system import windows
+from .editor_frames import frame_not_after, last_frame_end
+from .editor_speed import validate_clip, register_reverse
+from .editor_audio import clip_fields, track_fields
+
+FPS = 24
+MAX_IMPORT_BYTES = 8 * 1024**3
+BODY_BYTES = 8 * 1024 * 1024
+_PROJECT = re.compile(r'e-[0-9a-f]{32}')
+_IMPORT = re.compile(r'[A-Za-z0-9_-]{1,80}')
+_CLIP = re.compile(r'c[1-9][0-9]{0,8}')
+_TOKEN = re.compile(r'[A-Za-z0-9_-]{1,128}')
+_REASON = re.compile(r'[a-z_]{1,80}')
+_REF = re.compile(r'[A-Za-z0-9_-]{1,128}')
+_STATE = threading.RLock()
+_TRANSCODING = threading.Lock()
+_FAILED_IMPORTS = {} # terminal statuses awaiting writable storage
+_HEADERS = {'Cache-Control': 'no-store'}
+_LOG = logging.getLogger(__name__)
+
+
+class Conflict(ValueError):
+ def __init__(self, revision, identity=None):
+ super().__init__('Editor project has changed')
+ self.revision = revision
+ self.identity = identity
+
+
+class MissingProject(FileNotFoundError):
+ """An existing project lookup failed, rather than a later disk write."""
+
+
+class TooLarge(ValueError):
+ pass
+
+
+def _whole(value, low=0, high=2**53 - 1):
+ return type(value) in (int, float) and low <= value <= high and value == int(value)
+
+
+def _text(value, limit):
+ return isinstance(value, str) and len(value) <= limit and not any(0xd800 <= ord(c) <= 0xdfff for c in value)
+
+
+def _made(raw, out):
+ """Copy the order a version was made in and the description it was made from."""
+ if 'take' in raw:
+ if not _whole(raw['take'], 1, 10**6):
+ raise ValueError('Invalid version number')
+ out['take'] = int(raw['take'])
+ if 'made_text' in raw:
+ if not _text(raw['made_text'], 8000):
+ raise ValueError('Invalid version description')
+ out['made_text'] = raw['made_text']
+
+
+def _work(value):
+ return isinstance(value, str) and value.isascii() and _ID.fullmatch(value) is not None
+
+
+def _relative(value):
+ # Check before resolving: resolve() alone would conceal an internal link.
+ if (not isinstance(value, str) or len(value) > 1024 or not value
+ or any(ord(c) < 32 for c in value) or '\\' in value or ':' in value
+ or value.startswith('/') or any(p in ('', '.', '..') for p in value.split('/'))
+ or PureWindowsPath(value).is_absolute()):
+ raise ValueError('Invalid media path')
+ if PurePosixPath(value).suffix.lower() != '.mp4' or '.editor' in value.split('/'):
+ raise ValueError('Invalid generated video')
+ return value
+
+
+def _source(value):
+ if not isinstance(value, dict) or value.get('kind') not in ('work', 'generated', 'import'):
+ raise ValueError('Invalid source')
+ kind, identity = value['kind'], value.get('id')
+ if kind == 'work' and not _work(identity):
+ raise ValueError('Invalid creation id')
+ if kind == 'generated':
+ _relative(identity)
+ if kind == 'import' and (not isinstance(identity, str) or not _IMPORT.fullmatch(identity)):
+ raise ValueError('Invalid import id')
+ return dict(kind=kind, id=identity)
+
+
+def source_key(value):
+ value = _source(value)
+ return value['kind'] + ':' + value['id']
+
+
+def _key(key):
+ if not isinstance(key, str) or ':' not in key:
+ raise ValueError('Invalid source key')
+ kind, identity = key.split(':', 1)
+ return _source(dict(kind=kind, id=identity))
+
+
+from .editor_text import has_text_data, validate_text_project
+
+
+def validate(record):
+ if has_text_data(record):
+ return validate_text_project(record, validate)
+ """Bound the wire format; editing and generation policy belongs to the model."""
+ from .editor_picture import picture_fit
+ from .editor_picture_fields import picture_fields
+ if not isinstance(record, dict) or not _whole(record.get('version'), 1, 1):
+ raise ValueError('Invalid editor version')
+ if 'id' not in record:
+ raise ValueError('Project id missing')
+ if record.get('id') is not None and (not isinstance(record['id'], str) or not _PROJECT.fullmatch(record['id'])):
+ raise ValueError('Invalid project id')
+ if not _whole(record.get('revision')) or not _whole(record.get('serial'), 0, 999999999):
+ raise ValueError('Invalid revision or serial')
+ if record.get('id') is None and record['revision'] != 0:
+ raise ValueError('Invalid new project revision')
+ if not _whole(record.get('fps'), FPS, FPS):
+ raise ValueError('Invalid frame rate')
+ if any(not _whole(record.get(side), 2, 8192) or record[side] % 2 for side in ('width', 'height')):
+ raise ValueError('Invalid picture size')
+ if not _text(record.get('name'), 8000):
+ raise ValueError('Invalid project name')
+ settings = record.get('settings')
+ if settings is not None and not isinstance(settings, dict):
+ raise ValueError('Invalid settings')
+ # Settings are opaque JSON, preserved without interpreting the panel policy.
+ def bounded(value, depth=0):
+ if depth > 32:
+ raise ValueError('Settings are too deep')
+ if isinstance(value, dict):
+ if any(not isinstance(k, str) for k in value):
+ raise ValueError('Invalid settings')
+ for child in value.values():
+ bounded(child, depth + 1)
+ elif isinstance(value, list):
+ for child in value:
+ bounded(child, depth + 1)
+ elif value is not None and type(value) not in (str, int, float, bool):
+ raise ValueError('Invalid settings')
+ elif type(value) is float and not math.isfinite(value):
+ raise ValueError('Invalid settings')
+ bounded(settings)
+ if not _text(json.dumps(settings, ensure_ascii=False, allow_nan=False, separators=(',', ':')), 1024 * 1024):
+ raise ValueError('Settings are too large')
+ raw_tracks = record.get('tracks')
+ expected = [('v1', 'video'), ('a1', 'audio'), ('a2', 'audio')]
+ if not isinstance(raw_tracks, list) or len(raw_tracks) not in (2, 3):
+ raise ValueError('Invalid tracks')
+ tracks, seen = [], {}
+ for raw_track, (track_id, kind) in zip(raw_tracks, expected):
+ if (not isinstance(raw_track, dict) or raw_track.get('id') != track_id or raw_track.get('kind') != kind
+ or not isinstance(raw_track.get('clips'), list) or len(raw_track['clips']) > 500):
+ raise ValueError('Invalid track')
+ clips, end = [], 0
+ for raw in raw_track['clips']:
+ if not isinstance(raw, dict):
+ raise ValueError('Invalid clip')
+ if 'text_kind' in raw or 'text_style' in raw:
+ raise ValueError('Text fields require a text track')
+ identity = raw.get('id')
+ if (not isinstance(identity, str) or not _CLIP.fullmatch(identity) or identity in seen
+ or int(identity[1:]) > record['serial']):
+ raise ValueError('Invalid clip id or count')
+ for key, low in (('start', 0), ('frames', 1), ('in', 0), ('length', 1)):
+ if not _whole(raw.get(key), low, 10**7):
+ raise ValueError('Invalid clip range')
+ speed_fields = validate_clip(raw)
+ if raw['start'] < end:
+ raise ValueError('Invalid clip overlap or range')
+ end = raw['start'] + raw['frames']
+ if end > 10**7:
+ raise ValueError('Invalid clip end')
+ if 'source' not in raw:
+ raise ValueError('Source missing')
+ source = _source(raw['source']) if raw.get('source') is not None else None
+ if source is None and (raw['in'] != 0 or raw['length'] != raw['frames']):
+ raise ValueError('Invalid planned clip range')
+ pending = raw.get('pending')
+ if pending not in (None, 'draft', 'queued', 'running', 'failed', 'stopped') or source is None and pending is None:
+ raise ValueError('Invalid clip state')
+ if raw.get('reason') is not None and (not isinstance(raw['reason'], str) or not _REASON.fullmatch(raw['reason'])):
+ raise ValueError('Invalid failure reason')
+ if raw.get('reason') is not None and pending != 'failed':
+ raise ValueError('Invalid failure state')
+ for key in ('part', 'job'):
+ if raw.get(key) is not None and (not isinstance(raw[key], str) or not (_CLIP if key == 'part' else _TOKEN).fullmatch(raw[key])):
+ raise ValueError('Invalid clip ' + key)
+ if not _text(raw.get('text', ''), 8000) or type(raw.get('extend')) is not bool:
+ raise ValueError('Invalid clip description or extension')
+ link = raw.get('link')
+ if link is not None and (not isinstance(link, str) or not _CLIP.fullmatch(link) or link == identity):
+ raise ValueError('Invalid clip link')
+ versions = raw.get('versions')
+ if not isinstance(versions, list) or len(versions) > 50:
+ raise ValueError('Invalid clip versions')
+ history = []
+ for version in versions:
+ previous = _source(version)
+ if not _whole(version.get('in'), 0, 10**7) or not _whole(version.get('length'), version['in'] + 1, 10**7):
+ raise ValueError('Invalid version range')
+ previous.update({'in': int(version['in']), 'length': int(version['length'])})
+ if 'splice' in version:
+ previous['splice'] = _splice(version['splice'])
+ _made(version, previous)
+ if kind == 'video':
+ previous.update(picture_fields(version))
+ if picture_fit(version.get('fit', 'cover')) != 'cover':
+ previous['fit'] = 'contain'
+ elif 'fit' in version:
+ raise ValueError('Audio picture fit is invalid')
+ history.append(previous)
+ if len({(v['kind'], v['id']) for v in history}) != len(history):
+ raise ValueError('Duplicate versions')
+ clip = dict(id=identity, start=int(raw['start']), frames=int(raw['frames']), length=int(raw['length']),
+ source=source, link=link, text=raw.get('text', ''), part=raw.get('part'), pending=pending,
+ reason=raw.get('reason'), job=raw.get('job'), extend=raw.get('extend', source is not None and source['kind'] != 'import'),
+ versions=history, **{'in': int(raw['in'])})
+ clip.update(speed_fields)
+ clip.update(clip_fields(raw, kind))
+ if kind == 'video':
+ clip.update(picture_fields(raw))
+ if picture_fit(raw.get('fit', 'cover')) != 'cover':
+ clip['fit'] = 'contain'
+ elif 'fit' in raw:
+ raise ValueError('Audio picture fit is invalid')
+ if kind == 'video' and 'volume' in raw:
+ raise ValueError('Video volume is invalid')
+ if kind == 'audio':
+ volume = raw.get('volume')
+ if type(volume) not in (int, float) or not 0 <= volume <= 2:
+ raise ValueError('Invalid volume')
+ clip['volume'] = volume
+ if 'splice' in raw:
+ if source is None:
+ raise ValueError('Splice requires source')
+ clip['splice'] = _splice(raw['splice'])
+ if 'target_frames' in raw:
+ if not _whole(raw['target_frames'], 1, 10**7):
+ raise ValueError('Invalid target frame count')
+ clip['target_frames'] = int(raw['target_frames'])
+ # Who last wrote the description, and an outside reference (a shot id) for callers.
+ if 'text_by' in raw:
+ if raw['text_by'] not in ('user', 'agent'):
+ raise ValueError('Invalid description author')
+ clip['text_by'] = raw['text_by']
+ if 'ref' in raw:
+ if not isinstance(raw['ref'], str) or not _REF.fullmatch(raw['ref']):
+ raise ValueError('Invalid block reference')
+ clip['ref'] = raw['ref']
+ if source is None and ('take' in raw or 'made_text' in raw):
+ raise ValueError('Invalid clip versions')
+ _made(raw, clip)
+ clips.append(clip)
+ seen[identity] = (kind, clip)
+ tracks.append(dict(id=track_id, kind=kind, clips=clips, **track_fields(raw_track)))
+ for kind, clip in seen.values():
+ if clip['link'] is not None:
+ other = seen.get(clip['link'])
+ if (other is None or kind == other[0] or other[1]['link'] != clip['id']
+ or any(clip[k] != other[1][k] for k in ('start', 'frames', 'in'))):
+ raise ValueError('Invalid linked pair')
+ result = dict(version=1, id=record.get('id'), revision=int(record['revision']), name=record['name'], fps=FPS,
+ width=int(record['width']), height=int(record['height']), settings=copy.deepcopy(settings),
+ serial=int(record['serial']), tracks=tracks)
+ size_mode = record.get('size_mode', 'first')
+ if size_mode not in ('first', 'fixed'):
+ raise ValueError('Invalid size mode')
+ if size_mode == 'fixed':
+ result['size_mode'] = size_mode
+ if 'replacements' in record:
+ replacements = record['replacements']
+ if not isinstance(replacements, list) or not 1 <= len(replacements) <= 500:
+ raise ValueError('Invalid replacements')
+ transactions, parts = [], set()
+ for raw in replacements:
+ if (not isinstance(raw, dict) or not isinstance(raw.get('part'), str) or not _CLIP.fullmatch(raw['part'])
+ or raw['part'] in parts or type(raw.get('rolledBack')) is not bool):
+ raise ValueError('Invalid replacement identity')
+ parts.add(raw['part'])
+ def read(rows):
+ if (not isinstance(rows, list) or len(rows) != 2
+ or any(not isinstance(t, dict) or not t.get('clips') for t in rows)):
+ raise ValueError('Invalid replacement tracks')
+ return validate(dict(result, tracks=rows))['tracks']
+ originals, clips = read(raw.get('originals')), read(raw.get('clips'))
+ if any(not c['source'] or not c['link'] or c['source']['kind'] not in ('work', 'generated')
+ for t in originals for c in t['clips']):
+ raise ValueError('Invalid replacement originals')
+ if any(c['part'] != raw['part'] or not c['link'] for t in clips for c in t['clips']):
+ raise ValueError('Invalid replacement attempt')
+ def bounds(rows):
+ return [(t['clips'][0]['start'], t['clips'][-1]['start'] + t['clips'][-1]['frames']) for t in rows]
+ if bounds(originals) != bounds(clips):
+ raise ValueError('Invalid replacement bounds')
+ transactions.append(dict(part=raw['part'], originals=originals, clips=clips, rolledBack=raw['rolledBack']))
+ result['replacements'] = transactions
+ if len(json.dumps(result, ensure_ascii=True).encode()) > BODY_BYTES:
+ raise ValueError('Project is too large')
+ return result
+
+
+def _splice(value):
+ if not isinstance(value, dict) or not _whole(value.get('frames'), 0, 10**7) or not _whole(value.get('audio_samples')):
+ raise ValueError('Invalid splice')
+ return {k: int(value[k]) for k in ('frames', 'audio_samples')}
+
+
+def _safe(output_directory, relative):
+ root = Path(output_directory).resolve()
+ relative = PurePosixPath(relative)
+ if relative.is_absolute() or any(p in ('.', '..') for p in relative.parts):
+ raise ValueError('Invalid retained path')
+ path = root
+ for part in relative.parts:
+ path = path / part
+ if os.path.lexists(path) and not _plain(path):
+ raise ValueError('Retained path contains a link')
+ if not path.resolve().is_relative_to(root):
+ raise ValueError('Retained path is outside output')
+ return path
+
+
+def _editor_path(root, relative):
+ return _safe(root, 'FreeVideo/.editor/' + relative)
+
+
+def _project_path(root, identity):
+ if not isinstance(identity, str) or not _PROJECT.fullmatch(identity):
+ raise ValueError('Invalid project id')
+ return _editor_path(root, 'projects/' + identity + '/project.json')
+
+
+def _import_path(root, identity, filename='import.json'):
+ if not isinstance(identity, str) or not _IMPORT.fullmatch(identity):
+ raise ValueError('Invalid import id')
+ return _editor_path(root, 'imports/' + identity + '/' + filename)
+
+
+def _read_json(path, limit=BODY_BYTES):
+ with path.open('rb') as stream:
+ data = stream.read(limit + 1)
+ if len(data) > limit:
+ raise ValueError('Retained record is too large')
+ return json.loads(data)
+
+
+def _read_project(root, identity):
+ record = validate(_read_json(_project_path(root, identity), BODY_BYTES + 256))
+ if record['id'] != identity:
+ raise ValueError('Project id does not match its folder')
+ return record
+
+
+def _write(path, record):
+ temporary = None
+ try:
+ with tempfile.NamedTemporaryFile(mode='w', encoding='utf-8', errors='backslashreplace', newline='\n',
+ prefix=path.name + '.', suffix='.tmp', dir=path.parent, delete=False) as stream:
+ temporary = Path(stream.name)
+ stream.write(json.dumps(record, ensure_ascii=True, allow_nan=False) + '\n')
+ stream.flush()
+ os.fsync(stream.fileno())
+ for attempt in range(8):
+ try:
+ os.replace(temporary, path)
+ return
+ except PermissionError:
+ if not windows() or attempt == 7:
+ raise
+ time.sleep(.1 * (attempt + 1))
+ finally:
+ if temporary is not None:
+ temporary.unlink(missing_ok=True)
+
+
+def save(output_directory, record, create=None, operation=None):
+ from .comfy_library import _RELEASING
+ record = validate(record)
+ if create is not None and (not isinstance(create, str) or not re.fullmatch(r'[0-9a-f]{32}', create)):
+ raise ValueError('Invalid create operation')
+ if operation is not None and (not isinstance(operation, str) or not re.fullmatch(r'[0-9a-f]{32}', operation)):
+ raise ValueError('Invalid save operation')
+ # Bind an operation to the exact validated request, including its base revision.
+ digest = hashlib.sha256(json.dumps(record, sort_keys=True, ensure_ascii=True).encode()).hexdigest()
+ fresh = record['id'] is None
+ if fresh:
+ record['id'] = 'e-' + uuid.uuid4().hex
+ # Deletion cannot pass its reference check between lookup and publication.
+ with _RELEASING, _STATE:
+ if fresh and create is not None:
+ folder = _editor_path(output_directory, 'projects')
+ for existing in folder.iterdir() if folder.is_dir() else ():
+ if not _PROJECT.fullmatch(existing.name):
+ continue
+ receipt = _editor_path(output_directory, 'projects/' + existing.name + '/create.json')
+ if not receipt.is_file() or _read_json(receipt).get('create') != create:
+ continue
+ stored = _read_project(output_directory, existing.name)
+ content = lambda r: {**r, 'id': None, 'revision': 0}
+ if operation is None and content(stored) == content(record):
+ return stored
+ record['id'] = stored['id']
+ fresh = False
+ break
+ path = _project_path(output_directory, record['id'])
+ if fresh:
+ path.parent.parent.mkdir(parents=True, exist_ok=True)
+ staging = Path(tempfile.mkdtemp(prefix='.staging-', dir=path.parent.parent))
+ record['revision'] = 1
+ else:
+ try:
+ stored = _read_project(output_directory, record['id'])
+ except FileNotFoundError as error:
+ raise MissingProject('Saved project unavailable') from error
+ receipt = _read_json(path, BODY_BYTES + 256).get('_save', {})
+ if operation is not None and receipt.get('operation') == operation:
+ if receipt.get('digest') != digest:
+ raise ValueError('Save operation reused with different content')
+ return stored
+ if stored['revision'] != record['revision']:
+ raise Conflict(stored['revision'], stored['id'])
+ record['revision'] += 1
+ # The last receipt and the project commit in one atomic replace. One receipt
+ # suffices: clients resolve an uncertain write before sending the next one.
+ # A different writer replaces it, so a stale replay still conflicts.
+ retained = validate(record)
+ if operation is not None:
+ retained['_save'] = dict(operation=operation, digest=digest)
+ try:
+ if fresh:
+ _write(staging / 'project.json', retained)
+ if create is not None:
+ _write(staging / 'create.json', dict(create=create))
+ _project_path(output_directory, record['id'])
+ os.rename(staging, path.parent)
+ else:
+ _write(path, retained)
+ finally:
+ if fresh and staging.exists():
+ shutil.rmtree(staging)
+ return record
+
+
+def _projects(root, *, strict=False):
+ folder = _editor_path(root, 'projects')
+ if not folder.exists():
+ return []
+ records = []
+ for path in folder.iterdir():
+ if not _PROJECT.fullmatch(path.name):
+ continue
+ try:
+ if not _project_path(root, path.name).exists():
+ continue # No committed record means no references.
+ record = _read_project(root, path.name)
+ info = _project_path(root, path.name).stat()
+ records.append((info.st_mtime_ns, path.name, record, info))
+ except (OSError, ValueError, TypeError, RecursionError):
+ if strict:
+ raise ValueError('Editor references unavailable') from None
+ return sorted(records, key=lambda row: row[:2], reverse=True)
+
+
+def references(record):
+ tracks = [*record['tracks'], *(t for r in record.get('replacements', []) for t in [*r['originals'], *r['clips']])]
+ return list(dict.fromkeys(source_key(source) for track in tracks for clip in track['clips']
+ for source in [clip['source'], *clip['versions']] if source is not None))
+
+
+def reference_users(root, work):
+ """Compare actual file identities, including aliases and historical sources."""
+ folder = _video(root, work).parent
+ def identity(path):
+ info = path.stat()
+ inode = getattr(info, 'st_ino', 0)
+ return ('inode', info.st_dev, inode) if inode else ('path', os.path.normcase(os.path.realpath(path)))
+ files = {identity(_safe(root, path.relative_to(Path(root).resolve()).as_posix()))
+ for path in folder.rglob('*') if path.is_file()}
+ users = []
+ with _STATE:
+ for _, name, record, _ in _projects(root, strict=True):
+ for key in references(record):
+ kind, value = key.split(':', 1)
+ try:
+ paths = [_video(root, value)] if kind == 'work' else (
+ [_safe(root, value)] if kind == 'generated' else
+ [_import_path(root, value, file) for file in ('source.bin', 'preview.mp4', 'preview.m4a')])
+ if any(path.is_file() and identity(path) in files for path in paths):
+ users.append(record['name'] or name)
+ break
+ except FileNotFoundError:
+ continue
+ return users
+
+
+def cleanup_projects(root, now=None):
+ """Remove old uncommitted folders; corrupt committed records stay protected."""
+ now = time.time() if now is None else now
+ folder = _editor_path(root, 'projects')
+ if not folder.is_dir():
+ return
+ with _STATE:
+ for path in folder.iterdir():
+ if not (_PROJECT.fullmatch(path.name) or path.name.startswith('.staging-')):
+ continue
+ try:
+ checked = _safe(root, path.relative_to(Path(root).resolve()).as_posix())
+ if checked.is_dir() and not (checked / 'project.json').exists() and now - checked.stat().st_mtime > 3600:
+ shutil.rmtree(checked)
+ except (OSError, ValueError):
+ _LOG.warning('Editor uncommitted directory cleanup failed; continuing.')
+
+
+
+def duration(record):
+ return max((clip['start'] + clip['frames'] for track in record['tracks'] for clip in track['clips']), default=0)
+
+
+def list_projects(root):
+ rows = []
+ with _STATE:
+ records = _projects(root)
+ for _, identity, record, info in records:
+ first = next(iter(record['tracks'][0]['clips']), None)
+ cover = sources(root, [source_key(first['source'])]) if first and first['source'] else {}
+ rows.append(dict(id=identity, name=record['name'], updated_at=datetime.fromtimestamp(info.st_mtime, timezone.utc).isoformat(),
+ frames=duration(record), fps=FPS, width=record['width'], height=record['height'],
+ thumbnail=next(iter(cover.values()), {}).get('thumbnail')))
+ return rows
+
+
+def load(root, identity):
+ with _STATE:
+ record = _read_project(root, identity)
+ return dict(project=record, sources=sources(root, references(record)))
+
+
+def load_by_work(root, work):
+ if not _work(work):
+ raise ValueError('Invalid creation id')
+ with _STATE:
+ for _, identity, record, _ in _projects(root):
+ clips = record['tracks'][0]['clips']
+ if clips and clips[0]['start'] == 0 and clips[0]['source'] == dict(kind='work', id=work):
+ return load(root, identity)
+ raise FileNotFoundError('Saved project unavailable')
+
+
+def media_path(root, key):
+ source = _key(key)
+ if source['kind'] == 'work':
+ return _safe(root, 'FreeVideo/' + source['id'] + '/video.mp4')
+ if source['kind'] == 'generated':
+ return _safe(root, source['id'])
+ metadata = _read_import(root, source['id'])
+ if metadata['state'] != 'ready':
+ raise FileNotFoundError('Import preview unavailable')
+ return _import_path(root, source['id'], 'preview.mp4' if metadata['kind'] == 'video' else 'preview.m4a')
+
+
+def probe(path):
+ import av
+ from .media_encoding import clip_seconds
+ from .editor_frames import display_frame
+ with av.logging.Capture(local=True), av.open(str(path)) as container:
+ video = next(iter(container.streams.video), None)
+ audio = next(iter(container.streams.audio), None)
+ if video is None and audio is None:
+ raise ValueError('Media has no playable streams')
+ stream = video if video is not None else audio
+ seconds = clip_seconds(container, stream)
+ fps = float(video.average_rate or video.guessed_rate or FPS) if video is not None else FPS
+ frames = video.frames if video is not None else 0
+ if not frames:
+ if seconds is None or not math.isfinite(seconds) or seconds <= 0:
+ raise ValueError('Media duration unavailable')
+ frames = max(1, math.ceil(seconds * fps - 1e-6))
+ width = height = 0
+ if video is not None:
+ video.thread_count = 1
+ picture = display_frame(next(container.decode(video)))
+ width, height = (max(2, side // 2 * 2) for side in (picture.width, picture.height))
+ return dict(frames=int(frames), fps=fps, width=width,
+ height=height, has_video=video is not None,
+ has_audio=audio is not None, sample_rate=audio.rate if audio is not None else None)
+
+
+def _view(path):
+ relative = PurePosixPath(path)
+ return '/view?' + urlencode(dict(filename=relative.name, subfolder=str(relative.parent), type='output'))
+
+
+def sources(root, keys):
+ result = {}
+ for key in dict.fromkeys(keys):
+ source = _key(key)
+ relative = ('FreeVideo/' + source['id'] + '/video.mp4' if source['kind'] == 'work'
+ else source['id'] if source['kind'] == 'generated' else None)
+ info = dict(video=None, audio=None, frames=0, fps=FPS, width=0, height=0, has_video=False,
+ has_audio=False, thumbnail=None, missing=True, path=relative, sample_rate=None)
+ try:
+ path = media_path(root, key)
+ if source['kind'] in ('work', 'generated'):
+ relative = path.relative_to(Path(root).resolve()).as_posix()
+ info['path'] = relative
+ if path.stat().st_size == 0:
+ raise ValueError('Empty media')
+ if source['kind'] == 'work':
+ report = _safe(root, Path(relative).with_suffix('.request.json').as_posix())
+ if _read_json(report, 4 * 1024**2).get('success') is not True:
+ raise ValueError('Creation is incomplete')
+ media = probe(path)
+ if source['kind'] == 'import':
+ metadata = _read_import(root, source['id'])
+ media.update(preview_width=media['width'], preview_height=media['height'])
+ if metadata.get('original_size'):
+ media.update(width=metadata['width'], height=metadata['height'])
+ address = (_view(relative) if relative else '/freevideo/editor/media?' +
+ urlencode(dict(id=source['id'], file='preview')))
+ cover = None
+ if media['has_video']:
+ library_id = relative[len('FreeVideo/'):-len('/video.mp4')] if relative and relative.startswith('FreeVideo/') and relative.endswith('/video.mp4') else None
+ if source['kind'] == 'work':
+ library_id = source['id']
+ if library_id and _work(library_id):
+ # The existing endpoint requires a complete request receipt.
+ receipt = _safe(root, Path(relative).with_suffix('.request.json').as_posix())
+ _safe(root, Path(relative).with_suffix('.thumbnail.jpg').as_posix())
+ if receipt.is_file() and _read_json(receipt, 4 * 1024**2).get('success') is True:
+ cover = '/freevideo/library/thumbnail?' + urlencode(dict(id=library_id))
+ if cover is None:
+ cover = '/freevideo/editor/thumbnail?' + urlencode(dict(key=key))
+ info.update(media, video=address if media['has_video'] else None, audio=address if media['has_audio'] else None,
+ thumbnail=cover, missing=False)
+ except Exception:
+ # Missing/unreadable/linked media is a local placeholder, not a failed project load.
+ pass
+ result[key] = info
+ return result
+
+
+def _read_import(root, identity):
+ key = (str(Path(root).resolve()), identity)
+ with _STATE:
+ if key in _FAILED_IMPORTS:
+ value = _FAILED_IMPORTS[key]
+ try:
+ _write(_import_path(root, identity), value)
+ del _FAILED_IMPORTS[key]
+ except (OSError, ValueError):
+ pass
+ return copy.deepcopy(value)
+ value = _read_json(_import_path(root, identity), 64 * 1024)
+ if (not isinstance(value, dict) or value.get('id') != identity or not _text(value.get('name'), 255)
+ or value.get('kind') not in ('video', 'audio') or value.get('state') not in ('preparing', 'ready', 'failed')
+ or type(value.get('fraction')) not in (float, int) or not 0 <= value['fraction'] <= 1):
+ raise ValueError('Invalid import record')
+ # Old ready imports stored proxy dimensions. Backfill once, without changing
+ # any saved project. The lock also prevents concurrent first reads probing twice.
+ with _STATE:
+ value = _read_json(_import_path(root, identity), 64 * 1024)
+ if value['state'] == 'ready' and value['kind'] == 'video' and not value.get('original_size'):
+ original = _import_path(root, identity, 'source.bin')
+ if original.is_file():
+ try:
+ media = probe(original)
+ if media['has_video']:
+ value.update(preview_width=value.get('width'), preview_height=value.get('height'),
+ width=media['width'], height=media['height'], original_size=True)
+ _write(_import_path(root, identity), value)
+ except Exception:
+ # A legacy preview stays usable when its original cannot be read.
+ return _read_json(_import_path(root, identity), 64 * 1024)
+ return value
+
+
+def _import_update(root, identity, **fields):
+ with _STATE:
+ value = _read_import(root, identity)
+ if 'fraction' in fields:
+ fields['fraction'] = max(value['fraction'], min(1., max(0., fields['fraction'])))
+ value.update(fields)
+ try:
+ _write(_import_path(root, identity), value)
+ except (OSError, ValueError):
+ if value.get('state') == 'failed':
+ _FAILED_IMPORTS[(str(Path(root).resolve()), identity)] = copy.deepcopy(value)
+ raise
+ return value
+
+
+def list_imports(root):
+ folder = _editor_path(root, 'imports')
+ if not folder.exists():
+ return []
+ rows = []
+ with _STATE:
+ for child in folder.iterdir():
+ if not _IMPORT.fullmatch(child.name):
+ continue
+ try:
+ value = _read_import(root, child.name)
+ stamp = _import_path(root, child.name).stat().st_mtime_ns
+ fields = ('id', 'name', 'kind', 'state', 'fraction', 'reason', 'frames', 'fps', 'width', 'height',
+ 'preview_width', 'preview_height', 'has_audio')
+ row = {k: value.get(k) for k in fields}
+ for side in ('width', 'height'):
+ row['preview_' + side] = value.get('preview_' + side, value.get(side))
+ row['preview'] = '/freevideo/editor/media?' + urlencode(dict(id=child.name, file='preview')) if value['state'] == 'ready' else None
+ row['thumbnail'] = '/freevideo/editor/media?' + urlencode(dict(id=child.name, file='thumbnail')) if value['state'] == 'ready' else None
+ rows.append((stamp, child.name, row))
+ except (OSError, ValueError, TypeError):
+ continue
+ return [row for _, _, row in sorted(rows, key=lambda item: item[:2], reverse=True)]
+
+
+def _display_name(value):
+ if not isinstance(value, str) or not value or re.search(r'%(?![0-9a-fA-F]{2})', value):
+ raise ValueError('Invalid import filename')
+ try:
+ name = PureWindowsPath(unquote(value, encoding='utf-8', errors='strict')).name
+ except (ValueError, UnicodeError):
+ raise ValueError('Invalid import filename') from None
+ if not name or name in ('.', '..') or not _text(name, 255) or any(ord(c) < 32 for c in name):
+ raise ValueError('Invalid import filename')
+ return name
+
+
+async def receive(request, root):
+ if request.content_length is not None and request.content_length > MAX_IMPORT_BYTES:
+ raise TooLarge('Import exceeds 8 GiB')
+ name = _display_name(request.headers.get('X-FreeVideo-Filename'))
+ kind = 'audio' if PureWindowsPath(name).suffix.lower() in ('.wav', '.mp3', '.m4a', '.aac', '.flac', '.ogg', '.opus', '.aiff', '.aif') else 'video'
+ identity = 'i-' + uuid.uuid4().hex
+ destination = _import_path(root, identity, 'source.bin')
+ folder = destination.parent
+ await asyncio.to_thread(folder.mkdir, parents=True, exist_ok=False)
+ temporary = _import_path(root, identity, 'upload.partial')
+ stream = None
+ try:
+ stream = await asyncio.to_thread(temporary.open, 'xb')
+ size = 0
+ async for chunk in request.content.iter_chunked(256 * 1024):
+ size += len(chunk)
+ if size > MAX_IMPORT_BYTES:
+ raise TooLarge('Import exceeds 8 GiB')
+ await asyncio.to_thread(stream.write, chunk)
+ if not size:
+ raise ValueError('Import is empty')
+ await asyncio.to_thread(stream.flush)
+ await asyncio.to_thread(os.fsync, stream.fileno())
+ await asyncio.to_thread(stream.close)
+ stream = None
+ await asyncio.to_thread(os.replace, temporary, destination)
+ value = dict(id=identity, name=name, kind=kind, state='preparing', fraction=0., reason=None,
+ frames=None, fps=FPS, width=None, height=None, has_audio=False)
+ await asyncio.to_thread(_write, _import_path(root, identity), value)
+ return {key: value[key] for key in ('id', 'name', 'kind', 'state', 'fraction')}
+ except BaseException:
+ if stream is not None:
+ await asyncio.to_thread(stream.close)
+ await asyncio.to_thread(shutil.rmtree, folder)
+ raise
+
+
+def _poster(image, destination):
+ from PIL import Image
+ image.thumbnail((384, 256), Image.Resampling.LANCZOS)
+ image.convert('RGB').save(destination, format='JPEG', quality=80)
+
+
+def transcode(root, identity):
+ """Stream one video frame/audio packet at a time with software codecs only."""
+ import av
+ from PIL import Image, ImageDraw
+ from .media_encoding import clip_seconds
+ from .editor_frames import display_frame
+ original = _import_path(root, identity, 'source.bin')
+ partial = _import_path(root, identity, 'preview.partial')
+ poster = _import_path(root, identity, 'thumbnail.partial')
+ try:
+ with _TRANSCODING, av.logging.Capture(local=True), av.open(str(original)) as reader:
+ original_info = dict(width=0, height=0)
+ vin = next(iter(reader.streams.video), None)
+ ain = next(iter(reader.streams.audio), None)
+ if vin is None and ain is None:
+ raise ValueError('No media')
+ kind = 'video' if vin is not None else 'audio'
+ _import_update(root, identity, kind=kind)
+ seconds = max((clip_seconds(reader, s) or 0 for s in (vin, ain) if s is not None), default=0)
+ origin = Fraction(vin.start_time or 0) * vin.time_base if vin is not None else Fraction(ain.start_time or 0) * ain.time_base
+ with av.open(str(partial), 'w', format='mp4' if vin is not None else 'ipod', options={'movflags': 'faststart'}) as writer:
+ vout = aout = resampler = None
+ if vin is not None:
+ vin.thread_count = 1
+ if min(vin.width, vin.height) < 2 or vin.width * vin.height > 64_000_000:
+ raise ValueError('Invalid video dimensions')
+ original_info = probe(original)
+ scale = min(1., 1920 / max(original_info['width'], original_info['height']))
+ width, height = (max(2, int(side * scale) // 2 * 2) for side in (original_info['width'], original_info['height']))
+ vout = writer.add_stream('libx264', rate=FPS)
+ vout.width, vout.height, vout.pix_fmt = width, height, 'yuv420p'
+ vout.codec_context.thread_count = 2
+ vout.options = {'crf': '20', 'preset': 'fast'}
+ if ain is not None:
+ ain.thread_count = 1
+ aout = writer.add_stream('aac', rate=32000)
+ aout.layout = 'stereo'
+ aout.bit_rate = 128000
+ aout.codec_context.thread_count = 1
+ resampler = av.AudioResampler(format='fltp', layout='stereo', rate=32000)
+ next_video, previous, previous_time, previous_end = 0, None, 0., 0.
+ audio_pos, decoded_audio = None, 0
+ last_update, fraction = 0., 0.
+
+ def emit_video(until):
+ nonlocal next_video
+ while previous is not None and not frame_not_after(until, next_video):
+ frame = previous.reformat(width=width, height=height, format='yuv420p')
+ frame.pts, frame.time_base = next_video, Fraction(1, FPS)
+ for packet in vout.encode(frame):
+ writer.mux(packet)
+ next_video += 1
+
+ def emit_audio(frame):
+ nonlocal audio_pos, decoded_audio
+ if audio_pos < 0:
+ skip = min(-audio_pos, frame.samples)
+ audio_pos += skip
+ if skip == frame.samples:
+ return
+ frame = av.AudioFrame.from_ndarray(frame.to_ndarray()[:, skip:].copy(), format='fltp', layout='stereo')
+ frame.sample_rate = 32000
+ frame.pts, frame.time_base = audio_pos, Fraction(1, 32000)
+ audio_pos += frame.samples
+ decoded_audio += frame.samples
+ for packet in aout.encode(frame):
+ writer.mux(packet)
+
+ for packet in reader.demux([s for s in (vin, ain) if s is not None]):
+ for frame in packet.decode():
+ frame_time = Fraction(frame.pts) * frame.time_base - origin if frame.pts is not None else 0.
+ if packet.stream == vin:
+ picture = display_frame(frame)
+ if previous is not None:
+ emit_video(max(previous_time, frame_time))
+ else:
+ _poster(picture.to_image(), poster)
+ # Keep one scaled frame for dropping/duplicating to CFR.
+ previous = picture.reformat(width=width, height=height, format='yuv420p')
+ previous_time = max(Fraction(0), frame_time)
+ previous_end = last_frame_end(previous_time, frame, vin.average_rate or vin.guessed_rate or FPS)
+ else:
+ if audio_pos is None:
+ audio_pos = round(frame_time * 32000)
+ frame.pts = None # Normalize the retained preview clock.
+ for item in resampler.resample(frame):
+ emit_audio(item)
+ now = time.monotonic()
+ progress = min(.98, max(0., frame_time / seconds * .98)) if seconds > 0 else .5
+ if progress > fraction + .02 and now - last_update > .2:
+ _import_update(root, identity, fraction=progress)
+ last_update, fraction = now, progress
+ if vout is not None:
+ emit_video(previous_end)
+ if not next_video:
+ raise ValueError('No decoded video')
+ for packet in vout.encode():
+ writer.mux(packet)
+ if aout is not None:
+ for frame in resampler.resample(None):
+ emit_audio(frame)
+ for packet in aout.encode():
+ writer.mux(packet)
+ if not decoded_audio:
+ raise ValueError('No decoded audio')
+ if vin is None:
+ # An audio-only preview gets a neutral local poster, without text.
+ image = Image.new('RGB', (384, 216), '#18222f')
+ draw = ImageDraw.Draw(image)
+ for x in range(80, 304, 8):
+ amplitude = 10 + round(42 * abs(math.sin(x / 23)))
+ draw.line((x, 108 - amplitude, x, 108 + amplitude), fill='#8096ae', width=3)
+ _poster(image, poster)
+ target = _import_path(root, identity, 'preview.mp4' if kind == 'video' else 'preview.m4a')
+ os.replace(partial, target)
+ os.replace(poster, _import_path(root, identity, 'thumbnail.jpg'))
+ info = probe(target)
+ info.update(preview_width=info['width'], preview_height=info['height'],
+ width=original_info['width'], height=original_info['height'], original_size=True)
+ if kind == 'video':
+ info['frames'] = next_video
+ _import_update(root, identity, **info, state='ready', fraction=1., reason=None)
+ finally:
+ partial.unlink(missing_ok=True)
+ poster.unlink(missing_ok=True)
+
+
+class ImportManager:
+ """One daemon worker per server; restarted preparations are retried once."""
+ def __init__(self, root):
+ self.root = root
+ self.queue = queue.Queue()
+ self.thread = threading.Thread(target=self.run, name='freevideo-editor-import', daemon=True)
+
+ def start(self):
+ self.thread.start()
+
+ def submit(self, identity):
+ self.queue.put(identity)
+
+ def prepare(self, identity):
+ try:
+ transcode(self.root, identity)
+ except Exception:
+ try:
+ _import_update(self.root, identity, state='failed', reason='unreadable')
+ except (OSError, ValueError):
+ pass # The terminal snapshot is retained and retried by the worker/reads.
+
+ def recover(self):
+ try:
+ cleanup_projects(self.root)
+ except (OSError, ValueError):
+ _LOG.warning('Editor uncommitted directory cleanup failed; continuing.')
+ try:
+ rows = list_imports(self.root)
+ except (OSError, ValueError):
+ _LOG.warning('Editor import recovery failed; retrying later.')
+ self.recovery_pending = True
+ return
+ self.recovery_pending = False
+ for row in rows:
+ if row['state'] == 'preparing':
+ self.prepare(row['id'])
+
+ def run(self):
+ self.recover()
+ while True:
+ try:
+ identity = self.queue.get(timeout=5)
+ except queue.Empty:
+ if self.recovery_pending:
+ self.recover()
+ for root, identity in list(_FAILED_IMPORTS):
+ if root == str(Path(self.root).resolve()):
+ _read_import(self.root, identity)
+ continue
+ try:
+ if _read_import(self.root, identity)['state'] == 'preparing':
+ self.prepare(identity)
+ except (OSError, ValueError):
+ pass
+ finally:
+ self.queue.task_done()
+
+
+def _cache(root, category, key, path, extra=''):
+ info = path.stat()
+ stamp = hashlib.sha256(f'v1:{key}:{info.st_size}:{info.st_mtime_ns}:{extra}'.encode()).hexdigest()
+ return _editor_path(root, category + '/' + stamp)
+
+
+def thumbnail(root, key):
+ import av
+ path = media_path(root, key)
+ source = _key(key)
+ if source['kind'] == 'import':
+ return _import_path(root, source['id'], 'thumbnail.jpg')
+ cached = _cache(root, 'thumbnails', key, path).with_suffix('.jpg')
+ cached = _safe(root, cached.relative_to(Path(root).resolve()).as_posix())
+ if not cached.exists():
+ cached.parent.mkdir(parents=True, exist_ok=True)
+ with av.logging.Capture(local=True), av.open(str(path)) as reader:
+ stream = reader.streams.video[0]
+ stream.thread_count = 1
+ _poster(next(reader.decode(stream)).to_image(), cached)
+ return cached
+
+
+def waveform(root, key, points=200):
+ import av
+ import numpy as np
+ if not _whole(points, 1, 2000):
+ raise ValueError('Invalid waveform point count')
+ points = int(points)
+ path = media_path(root, key)
+ info = probe(path)
+ cached = _cache(root, 'waveforms', key, path, str(points)).with_suffix('.json')
+ cached = _safe(root, cached.relative_to(Path(root).resolve()).as_posix())
+ try:
+ peaks = _read_json(cached, 128 * 1024)['peaks']
+ if (len(peaks) == points and all(type(x) in (int, float) and 0 <= x <= 1 for x in peaks)):
+ return peaks
+ except (OSError, ValueError, TypeError, KeyError):
+ pass
+ peaks = np.zeros(points, dtype=np.float32)
+ if info['has_audio']:
+ with av.logging.Capture(local=True), av.open(str(path)) as reader:
+ stream = reader.streams.audio[0]
+ stream.thread_count = 1
+ from .media_encoding import clip_seconds
+ seconds = clip_seconds(reader, stream) or info['frames'] / info['fps']
+ count = max(1, math.ceil(seconds * stream.rate))
+ offset = 0
+ for frame in reader.decode(stream):
+ array = frame.to_ndarray()
+ if np.issubdtype(array.dtype, np.integer):
+ limits = np.iinfo(array.dtype)
+ if limits.min == 0:
+ middle = (limits.max + 1) / 2
+ array = (array.astype(np.float32) - middle) / middle
+ else:
+ array = array.astype(np.float32) / max(abs(limits.min), limits.max)
+ if frame.format.is_planar:
+ values = np.max(np.abs(array), axis=0)
+ else:
+ values = np.max(np.abs(array.reshape(-1, len(frame.layout.channels))), axis=1)
+ if not np.isfinite(values).all():
+ raise ValueError('Invalid decoded audio')
+ bins = np.minimum(points - 1, (np.arange(len(values), dtype=np.int64) + offset) * points // count)
+ np.maximum.at(peaks, bins, np.clip(values, 0, 1))
+ offset += len(values)
+ result = peaks.tolist()
+ try:
+ cached.parent.mkdir(parents=True, exist_ok=True)
+ _write(cached, dict(peaks=result))
+ except OSError:
+ pass # Waveforms still work on a read-only output disk.
+ return result
+
+
+def _local_page(request):
+ """Keep normal same-origin requests; reject cross-site browser requests."""
+ headers = request.headers
+ if headers.get('Sec-Fetch-Site') == 'cross-site':
+ return False
+ origin = headers.get('Origin')
+ if origin is None:
+ return True # Same-origin GET/video requests usually have no Origin.
+ try:
+ parsed = urlsplit(origin)
+ host = urlsplit('//' + request.host)
+ return (parsed.scheme in ('http', 'https') and parsed.scheme == request.scheme and not parsed.username
+ and not parsed.password and not parsed.path and not parsed.query and not parsed.fragment
+ and parsed.hostname == host.hostname
+ and (parsed.port or (443 if parsed.scheme == 'https' else 80)) == (host.port or (443 if request.scheme == 'https' else 80)))
+ except ValueError:
+ return False
+
+
+async def _body(request):
+ if request.content_length is not None and request.content_length > BODY_BYTES:
+ raise TooLarge('Project body is too large')
+ data = bytearray()
+ async for chunk in request.content.iter_chunked(64 * 1024):
+ data.extend(chunk)
+ if len(data) > BODY_BYTES:
+ raise TooLarge('Project body is too large')
+ value = json.loads(data)
+ if not isinstance(value, dict):
+ raise ValueError('Invalid editor request')
+ return value
+
+
+def register():
+ from aiohttp import web
+ import folder_paths
+ from server import PromptServer
+ server = PromptServer.instance
+ if server is None or getattr(server, '_freevideo_editor', False):
+ return
+ manager = ImportManager(folder_paths.get_output_directory())
+ server._freevideo_editor = manager
+ previews = asyncio.Semaphore(1)
+
+ def endpoint(method, path):
+ def decorate(handler):
+ async def guarded(request):
+ if not _local_page(request):
+ return web.json_response(dict(error='Local page required'), status=403, headers=_HEADERS)
+ try:
+ return await handler(request)
+ except Conflict as error:
+ return web.json_response(dict(revision=error.revision, **({'id': error.identity} if error.identity else {})), status=409, headers=_HEADERS)
+ except TooLarge:
+ return web.json_response(dict(error='Editor request is too large'), status=413, headers=_HEADERS)
+ except FileNotFoundError:
+ return web.json_response(dict(error='Editor item unavailable'), status=404, headers=_HEADERS)
+ except OSError:
+ return web.json_response(dict(saved=False, retry=True), status=503, headers=_HEADERS)
+ except (ValueError, TypeError, KeyError, RecursionError):
+ return web.json_response(dict(error='Invalid editor request'), status=400, headers=_HEADERS)
+ except Exception:
+ return web.json_response(dict(error='Editor media unavailable'), status=404, headers=_HEADERS)
+ getattr(server.routes, method)(path)(guarded)
+ return guarded
+ return decorate
+
+ def root():
+ return folder_paths.get_output_directory()
+
+ @endpoint('get', '/freevideo/editor/projects')
+ async def projects(request):
+ return web.json_response(dict(items=await asyncio.to_thread(list_projects, root())), headers=_HEADERS)
+
+ @endpoint('get', '/freevideo/editor/project')
+ async def project(request):
+ if ('id' in request.query) == ('work' in request.query):
+ raise ValueError('Provide either id or work')
+ lookup = load if 'id' in request.query else load_by_work
+ identity = request.query.get('id') if 'id' in request.query else request.query.get('work')
+ return web.json_response(await asyncio.to_thread(lookup, root(), identity), headers=_HEADERS)
+
+ @endpoint('post', '/freevideo/editor/project')
+ async def persist(request):
+ body = await _body(request)
+ try:
+ result = await asyncio.to_thread(save, root(), body.get('project'), body.get('create'), body.get('operation'))
+ except MissingProject:
+ raise
+ except OSError:
+ # A missing staging directory is a retryable write error, not 404.
+ return web.json_response(dict(saved=False, retry=True), status=503, headers=_HEADERS)
+ return web.json_response(dict(project=result), headers=_HEADERS)
+
+ @endpoint('get', '/freevideo/editor/sources')
+ async def source_lookup(request):
+ keys = request.query.getall('key', [])
+ if len(keys) > 1000:
+ raise ValueError('Too many sources')
+ return web.json_response(dict(sources=await asyncio.to_thread(sources, root(), keys)), headers=_HEADERS)
+
+ @endpoint('post', '/freevideo/editor/import')
+ async def upload(request):
+ value = await receive(request, root())
+ manager.submit(value['id'])
+ return web.json_response({'import': value}, headers=_HEADERS)
+
+ @endpoint('get', '/freevideo/editor/imports')
+ async def imports(request):
+ return web.json_response(dict(items=await asyncio.to_thread(list_imports, root())), headers=_HEADERS)
+
+ @endpoint('get', '/freevideo/editor/waveform')
+ async def peaks(request):
+ async with previews:
+ result = await asyncio.to_thread(waveform, root(), request.query.get('key'), int(request.query.get('points', '200')))
+ return web.json_response(dict(peaks=result), headers=_HEADERS)
+
+ @endpoint('get', '/freevideo/editor/thumbnail')
+ async def cover(request):
+ async with previews:
+ path = await asyncio.to_thread(thumbnail, root(), request.query.get('key'))
+ return web.FileResponse(path, headers={'Content-Type': 'image/jpeg', **_HEADERS})
+
+ @endpoint('get', '/freevideo/editor/media')
+ async def imported_media(request):
+ identity, filename = request.query.get('id'), request.query.get('file')
+ if filename not in ('preview', 'thumbnail'):
+ raise ValueError('Invalid import media')
+ value = await asyncio.to_thread(_read_import, root(), identity)
+ if value['state'] != 'ready':
+ raise FileNotFoundError('Import preview unavailable')
+ path = (media_path(root(), 'import:' + identity) if filename == 'preview'
+ else _import_path(root(), identity, 'thumbnail.jpg'))
+ if not path.is_file():
+ raise FileNotFoundError('Import preview unavailable')
+ content_type = 'image/jpeg' if filename == 'thumbnail' else 'video/mp4' if value['kind'] == 'video' else 'audio/mp4'
+ return web.FileResponse(path, headers={'Content-Type': content_type, **_HEADERS})
+
+ register_reverse(endpoint, root, server)
+ manager.start()
diff --git a/freevideo_engine/comfy_host.py b/freevideo_engine/comfy_host.py
index 69f7e7a..bdfdd91 100644
--- a/freevideo_engine/comfy_host.py
+++ b/freevideo_engine/comfy_host.py
@@ -19,6 +19,10 @@ from .monitoring import save
from .package_progress import PackageOutput
from .terminal_ui import LogProgress, TerminalUI
+# FreeVideo's nodes and Agent routes run in the ComfyUI process; its requirements
+# do not name what only they use (the editor rules engine for project and image edits).
+NODE_PACKAGES = ('quickjs==1.19.4',)
+
def prepare(root, comfy, run=None, download=False, repair=False):
root, comfy = Path(root).resolve(), Path(comfy).resolve()
@@ -150,7 +154,7 @@ def _prepare(root, comfy, machine, run, download, repair=False):
raise ValueError('ComfyUI requirements.txt is missing')
# An environment is reused only for this exact ComfyUI dependency contract.
identity = dict(comfy=str(comfy), requirements=hashlib.sha256(requirements.read_bytes()).hexdigest(),
- engine_python=machine['python'], python=sys.version.split()[0])
+ engine_python=machine['python'], python=sys.version.split()[0], nodes=list(NODE_PACKAGES))
key = hashlib.sha256(json.dumps(identity, sort_keys=True).encode()).hexdigest()[:16]
env_root = root / 'envs' / ('comfyui-' + key)
if not env_root.exists():
@@ -191,7 +195,7 @@ def _prepare(root, comfy, machine, run, download, repair=False):
reported_unknown = False
def broken_packages():
nonlocal reported_unknown
- required = dependency_closure(python, requirements, rows)
+ required = dependency_closure(python, requirements, [*rows, *NODE_PACKAGES])
found = set(incomplete(python) + damaged(python))
if required is None:
if not reported_unknown:
@@ -233,7 +237,8 @@ def _prepare(root, comfy, machine, run, download, repair=False):
'Prepare ComfyUI GPU packages')
ui.phase('Install ComfyUI packages', stage_offset + 2, stage_total)
package_install('pypi', lambda environment, _: execute(
- [uv, 'pip', 'install', '--python', python, *reinstall_arguments(packages), '-r', requirements, '-c', pins], environment, 'Install ComfyUI packages'),
+ [uv, 'pip', 'install', '--python', python, *reinstall_arguments(packages), '-r', requirements, *NODE_PACKAGES,
+ '-c', pins], environment, 'Install ComfyUI packages'),
'Install ComfyUI packages')
ui.phase('Check ComfyUI dependencies', stage_offset + 3, stage_total)
execute([uv, 'pip', 'check', '--python', python], env, 'Check ComfyUI dependencies')
diff --git a/freevideo_engine/comfy_launcher_runtime.py b/freevideo_engine/comfy_launcher_runtime.py
index d38f4f0..fe7d8c0 100644
--- a/freevideo_engine/comfy_launcher_runtime.py
+++ b/freevideo_engine/comfy_launcher_runtime.py
@@ -179,6 +179,7 @@ def host_repair_pending(python):
def managed_python(engine, comfy):
"""Find our previously completed frontend without requiring its full disk budget again."""
+ from .comfy_host import NODE_PACKAGES
engine, comfy = io_path(engine), io_path(comfy)
try:
record = json.loads((engine / 'launcher/comfy-host.json').read_text(encoding='utf-8'))
@@ -187,6 +188,8 @@ def managed_python(engine, comfy):
machine = json.loads((engine / 'machine.json').read_text(encoding='utf-8'))
if (identity['comfy'] != plain(comfy) or identity['engine_python'] != machine['python']
or identity['requirements'] != hashlib.sha256((comfy / 'requirements.txt').read_bytes()).hexdigest()
+ # Packages our nodes need beyond ComfyUI's own, added since the environment was made.
+ or identity.get('nodes', []) != list(NODE_PACKAGES)
or environment.resolve().parent != (engine / 'envs').resolve()
or python != environment / ('Scripts/python.exe' if os.name == 'nt' else 'bin/python')
or json.loads((environment / 'freevideo-host.json').read_text(encoding='utf-8')) != identity
diff --git a/freevideo_engine/comfy_library.py b/freevideo_engine/comfy_library.py
index ae3881f..869a2e5 100644
--- a/freevideo_engine/comfy_library.py
+++ b/freevideo_engine/comfy_library.py
@@ -11,6 +11,7 @@ import time
from datetime import datetime, timezone
from pathlib import Path
+from .agent import enabled as agent_enabled
from .comfy_assets import output_summary
from .runtime_alias import is_junction, checked_real_path, AliasUnavailable
from .long_paths import io_path, plain
@@ -41,6 +42,21 @@ def _report(path):
return report
+def _agent(folder):
+ """The agent job that made this run, from the small record agent requests leave in workflow.json."""
+ try:
+ with (folder / 'workflow.json').open('rb') as stream:
+ data = stream.read(64 * 1024 + 1)
+ if len(data) > 64 * 1024 or b'"freevideo_agent"' not in data:
+ return None
+ value = json.loads(data).get('freevideo_agent')
+ except (OSError, ValueError, AttributeError):
+ return None
+ if not isinstance(value, dict):
+ return None
+ return {key: str(value[key])[:120] for key in ('job', 'label', 'project', 'client') if value.get(key)}
+
+
def list_videos(output_directory, *, before=None, limit=24):
"""Return a stable newest-first page, with only relative output paths."""
if not 1 <= limit <= 48:
@@ -52,6 +68,8 @@ def list_videos(output_directory, *, before=None, limit=24):
raise ValueError('Invalid page cursor')
cursor = (int(stamp), identity)
root = Path(output_directory).resolve()
+ from .comfy_chain import hidden_outputs
+ hidden = hidden_outputs(root)
candidates = []
for path in (root / 'FreeVideo').glob('*/*/video.mp4'):
identity = path.parent.relative_to(root / 'FreeVideo').as_posix()
@@ -68,6 +86,8 @@ def list_videos(output_directory, *, before=None, limit=24):
try:
report = _report(path)
relative = Path('FreeVideo') / key[1] / 'video.mp4'
+ if relative.as_posix() in hidden:
+ continue
summary = output_summary(report, relative)
# Geometry may gain input metadata in future reports. Keep this API
# an explicit allowlist, not an export of the retained report.
@@ -80,6 +100,9 @@ def list_videos(output_directory, *, before=None, limit=24):
summary['encoder_file'].pop('path', None)
if not (root / summary['report']).is_file():
summary['report'] = None
+ agent = _agent(path.parent) if agent_enabled() else None
+ if agent:
+ summary['agent'] = agent
rows.append(dict(summary, id=key[1], bytes=info.st_size,
created_at=datetime.fromtimestamp(info.st_mtime, timezone.utc).isoformat(),
cursor=str(key[0]) + ':' + key[1]))
@@ -99,10 +122,17 @@ def list_videos(output_directory, *, before=None, limit=24):
def thumbnail(output_directory, identity):
path = _video(output_directory, identity)
- _report(path)
saved = path.with_suffix('.thumbnail.jpg')
+ root = Path(output_directory).resolve() / 'FreeVideo'
+ def check_sidecar(sidecar):
+ if sidecar.is_symlink() or not sidecar.resolve().is_relative_to(root):
+ raise ValueError('Saved thumbnail sidecar is outside the library or is a symbolic link')
+ check_sidecar(path.with_suffix('.request.json'))
+ check_sidecar(saved)
+ _report(path)
if saved.is_file() and saved.stat().st_mtime_ns >= path.stat().st_mtime_ns:
- data = saved.read_bytes()
+ with os.fdopen(os.open(saved, os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0) | getattr(os, 'O_BINARY', 0)), 'rb') as stream:
+ data = stream.read(512 * 1024 + 1)
if data.startswith(b'\xff\xd8') and len(data) <= 512 * 1024:
return data
# CPU decoding only. Grid thumbnails must not take CUDA memory from a
@@ -117,9 +147,13 @@ def thumbnail(output_directory, identity):
buffer = io.BytesIO()
image.save(buffer, format='JPEG', quality=80)
data = buffer.getvalue()
+ check_sidecar(saved)
try:
- saved.write_bytes(data)
+ with os.fdopen(os.open(saved, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | getattr(os, 'O_NOFOLLOW', 0)
+ | getattr(os, 'O_BINARY', 0), 0o666), 'wb') as stream:
+ stream.write(data)
except OSError:
+ check_sidecar(saved)
pass # A read-only output directory still supports browsing.
return data
@@ -371,6 +405,13 @@ def delete_video(output_directory, identity):
raise DeleteRefused('not-freevideo')
# Not while the startup release is deleting files in this folder.
with _RELEASING:
+ from .comfy_editor import reference_users
+ try:
+ users = reference_users(output_directory, identity)
+ except (OSError, ValueError):
+ raise DeleteRefused('editor-unavailable') from None
+ if users:
+ raise DeleteRefused('editor-in-use', users)
kept = _foreign(folder)
if kept:
raise DeleteRefused('foreign-files', kept)
diff --git a/freevideo_engine/comfy_media.py b/freevideo_engine/comfy_media.py
index f71300f..d7abd95 100644
--- a/freevideo_engine/comfy_media.py
+++ b/freevideo_engine/comfy_media.py
@@ -1,5 +1,6 @@
"""Native Comfy sockets -> retained local files, without model duplication."""
from pathlib import Path
+from .comfy_assets import REFERENCE_INPUTS
def _image(value, path):
@@ -50,9 +51,16 @@ def export(run, canvas, *, first=None, last=None, references=None, loras=None, c
connected = assets.get('_connected', {})
media.update({key: value for key, value in assets.items() if key != '_connected'})
first, last = connected.get('first'), connected.get('last')
- references = [{'kind': kind, 'value': connected[name]}
- for name, kind in (('reference', 'image'), ('reference_audio', 'audio'))
- if connected.get(name) is not None]
+ references = []
+ for name in REFERENCE_INPUTS:
+ value = connected.get(name)
+ if value is None:
+ continue
+ shape = getattr(value, 'shape', ())
+ frames = (value[index:index + 1] for index in range(shape[0])) if len(shape) == 4 and shape[0] > 1 else [value]
+ references.extend({'kind': 'image', 'value': frame} for frame in frames)
+ if connected.get('reference_audio') is not None:
+ references.append({'kind': 'audio', 'value': connected['reference_audio']})
if conditioning is not None and (first is not None or last is not None or references):
raise ValueError('Preencoded conditioning already includes media; do not connect a second set')
if references and (first is not None or last is not None):
diff --git a/freevideo_engine/comfy_nodes.py b/freevideo_engine/comfy_nodes.py
index ee144d5..d6530a4 100644
--- a/freevideo_engine/comfy_nodes.py
+++ b/freevideo_engine/comfy_nodes.py
@@ -85,6 +85,10 @@ class FreeVideoGenerate(io.ComfyNode):
def 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=''):
+ from server import PromptServer
+ from .comfy_chain import block_context, block_finished, report_fields
+ node_id = cls.hidden.unique_id
+ chain = block_context(PromptServer.instance, node_id)
from .two_pass import validate_steps
if not refine_from:
validate_steps(base_steps, refine_steps, two_pass)
@@ -95,7 +99,6 @@ class FreeVideoGenerate(io.ComfyNode):
import folder_paths
import comfy.model_management as memory
from comfy.utils import ProgressBar
- from server import PromptServer
from .comfy_progress import publish
from .encoder_prewarm import IDLE
from .resident_process import OWNER
@@ -103,7 +106,7 @@ class FreeVideoGenerate(io.ComfyNode):
stop_prestart_for_generation(PromptServer.instance)
prewarm = {}
result_reused = [False]
- node_id = cls.hidden.unique_id
+ result_report = [None]
bar = ProgressBar(base_steps + (refine_steps if two_pass and not preview else 0), node_id=node_id)
last_message = [None]
last_count = [None]
@@ -116,6 +119,8 @@ class FreeVideoGenerate(io.ComfyNode):
PromptServer.instance.send_progress_text(notice, node_id)
notice = notice + '\n' if notice else ''
def progress(message):
+ if message.get('report_id'):
+ result_report[0] = message['report_id']
if message.get('result_cache_hit'):
result_reused[0] = True
# The sampling label also serves terminal readers and can contain
@@ -168,13 +173,15 @@ class FreeVideoGenerate(io.ComfyNode):
preview=bool(preview), refine_from=refine_from or None,
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))
+ references=references, loras=loras, conditioning=conditioning, assets=media),
+ **({'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')
import json
+ measured = json.loads(report)
from .comfy_assets import output_summary, saved_video
preview = ui.PreviewVideo([saved_video(output, output_root)]).as_dict()
- preview['freevideo_summary'] = [output_summary(json.loads(report), relative)]
+ preview['freevideo_summary'] = [output_summary(measured, relative)]
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')
@@ -184,7 +191,7 @@ class FreeVideoGenerate(io.ComfyNode):
raise
publish(PromptServer.instance, node_id, {'label': 'Reused previous result' if result_reused[0] else 'Video saved', 'phase': 'complete',
'overall': {'status': 'complete', 'fraction': 1.}, 'result': preview['freevideo_summary'][0]})
- measured = json.loads(report)
+ block_finished(chain, node_id, relative.as_posix(), result_report[0], measured.get('continuation'))
from .encoder_prewarm import warm_target
target = warm_target(measured)
from .resident_process import OWNER
@@ -219,16 +226,19 @@ class FreeVideoGenerate(io.ComfyNode):
class FreeVideoMedia(io.ComfyNode):
@classmethod
def define_schema(cls):
+ from .comfy_assets import REFERENCE_INPUTS
return io.Schema(node_id='FreeVideoMedia', display_name='FreeVideo · Media', category='FreeVideo',
description='Connect IMAGE or AUDIO outputs from generation, editing or loading nodes, or upload files. '
+ 'Several reference images can be connected; uploaded references come first, then connected images from top to bottom. '
'Choose first/last frames or experimental references. Empty media means text to video.',
inputs=[io.String.Input('assets', default='[]'),
io.Image.Input('first', display_name='First frame', optional=True,
tooltip='Connect any compatible IMAGE output. Select one frame from a batch first.'),
io.Image.Input('last', display_name='Last frame', optional=True,
tooltip='Connect an IMAGE output for the last frame.'),
- io.Image.Input('reference', display_name='Reference image', optional=True,
- tooltip='One reference image; appended after uploaded references. Experimental.'),
+ *[io.Image.Input(name, display_name=f'Reference image {index}', optional=True,
+ tooltip='When one input receives several images, each counts as one reference.')
+ for index, name in enumerate(REFERENCE_INPUTS, 1)],
io.Audio.Input('reference_audio', display_name='Reference audio', optional=True,
tooltip='Voice, music or rhythm reference, up to 15 seconds. Connect a Load Audio '
'or other AUDIO output. Describe its role using <Audio 1> in the prompt. '
@@ -251,12 +261,12 @@ class FreeVideoMedia(io.ComfyNode):
return float('nan')
@classmethod
- def execute(cls, assets, first=None, last=None, reference=None, reference_audio=None):
+ def execute(cls, assets, first=None, last=None, reference=None, reference_audio=None, **images):
from .comfy_assets import resolve_assets, connect_assets
import folder_paths
return io.NodeOutput(connect_assets(resolve_assets(assets, folder_paths.get_input_directory()),
first=first, last=last, reference=reference,
- reference_audio=reference_audio))
+ reference_audio=reference_audio, **images))
class FreeVideoReference(io.ComfyNode):
diff --git a/freevideo_engine/comfy_progress.py b/freevideo_engine/comfy_progress.py
index ca977b7..fb0cd9b 100644
--- a/freevideo_engine/comfy_progress.py
+++ b/freevideo_engine/comfy_progress.py
@@ -71,7 +71,7 @@ class ProgressState:
'sampling_plan', 'bytes_per_second', 'block', 'blocks', 'elapsed_seconds', 'step_elapsed_seconds',
'estimated_step_seconds', 'remaining_seconds', 'display_fraction',
'estimated', 'uniform_remaining_steps', 'overall', 'retry', 'warning', 'kernel_cache_note',
- 'new_request', 'reset', 'result', 'report_id', 'compatibility', 'memory_tight', 'references')
+ 'new_request', 'reset', 'result', 'report_id', 'compatibility', 'memory_tight', 'references', 'chain')
value = deepcopy({key: message[key] for key in keys if key in message})
if isinstance(message.get('prediction'), dict):
# The UI only needs a history marker, not the resource forecast.
@@ -193,6 +193,13 @@ def progress_timeline(output):
def publish(server, node, message):
+ try:
+ from .comfy_chain import RUNNER
+ chain = RUNNER.progress(node, message) if RUNNER is not None else None
+ if chain is not None:
+ message = dict(message, chain=chain)
+ except Exception:
+ pass # Background scheduling must never interrupt ordinary progress.
value = STATE.publish(node, message)
if server is not None:
# Progress belongs to the running node, not to the tab that queued it.
diff --git a/freevideo_engine/comfy_service.py b/freevideo_engine/comfy_service.py
index 69a3176..881e0c6 100644
--- a/freevideo_engine/comfy_service.py
+++ b/freevideo_engine/comfy_service.py
@@ -251,7 +251,7 @@ def request(url, *, headers=None, timeout=3):
return error.code
-def start_proxy(record, *, listen, port, upstream, token_file, tls):
+def start_proxy(record, *, listen, port, upstream, token_file, tls, hop_secret=None):
"""Run the access proxy with ComfyUI's Python, which brings aiohttp."""
from . import processes
code = ("import runpy,sys;sys.path.insert(0,sys.argv.pop(1));"
@@ -261,6 +261,10 @@ def start_proxy(record, *, listen, port, upstream, token_file, tls):
if tls:
command += ['--tls-cert', str(tls[0]), '--tls-key', str(tls[1])]
env = dict(os.environ, PYTHONUTF8='1', PYTHONNOUSERSITE='1')
+ from .proxy_identity import ENV
+ env.pop(ENV, None)
+ if hop_secret:
+ env[ENV] = hop_secret
for name in ('PYTHONPATH', 'PYTHONHOME', 'VIRTUAL_ENV'):
env.pop(name, None)
log = folder(record['engine']) / 'access-proxy.log'
@@ -312,6 +316,12 @@ def serve(root, *, port=DEFAULT_PORT, listen='127.0.0.1', tls=None):
proxied = not loopback(listen)
internal = free_port() if proxied else port
controller = Controller(Path(record['source']))
+ hop_secret = secrets.token_urlsafe(32) if proxied else None
+ if proxied:
+ from .proxy_identity import ENV
+ from .comfy_launcher_runtime import isolated_environment
+ controller.child_environment = lambda: dict(
+ isolated_environment(record['engine'], record['source']), **{ENV: hop_secret})
controller.move_when_taken = False # Serve the port that was asked for, or say it is taken.
for name in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP):
previous[name] = signal.signal(name, lambda *_: (stopping.set(), controller.cancelled.set()))
@@ -341,7 +351,7 @@ def serve(root, *, port=DEFAULT_PORT, listen='127.0.0.1', tls=None):
secret = token(root)
scheme = 'https' if tls else 'http'
proxy = start_proxy(record, listen=listen, port=port, upstream=local,
- token_file=folder(root) / TOKEN, tls=tls)
+ token_file=folder(root) / TOKEN, tls=tls, hop_secret=hop_secret)
check_proxy(proxy, scheme=scheme, port=port, secret=secret)
state.update(access=dict(scheme=scheme, port=port))
save(state_file, dict(state, status='open'))
diff --git a/freevideo_engine/decode_prefetch.py b/freevideo_engine/decode_prefetch.py
index 8880752..aca8b57 100644
--- a/freevideo_engine/decode_prefetch.py
+++ b/freevideo_engine/decode_prefetch.py
@@ -7,6 +7,16 @@ The sampler starts this reader before its last two steps; the reader can still
stop immediately when the live RAM/Commit allowance is insufficient. When the
allowance covers only part of the decoder, that part is read and the loader
reads the rest itself.
+
+The allowance is live RAM beside the system reserve and, as a rule, what the
+request's RAM budget has left. A planner's estimate of that budget is spent by
+design once every layer it could afford is pinned, while RAM it did not plan
+with stays free. Then live RAM alone bounds the read, provided sampling leaves
+the drive alone: the step before read no layer from the weight files and every
+offloaded layer is pinned or held as a view in RAM. The reader then neither
+shares the drive with sampling nor displaces layers that sampling keeps in the
+file cache. An explicit capacity stays a strict bound, as it is for the RAM
+guard.
"""
import json
import os
@@ -46,18 +56,21 @@ def decoder_ranges(base):
class DecoderReadAhead:
- def __init__(self, base, *, ram_budget_bytes=None):
+ def __init__(self, base, *, ram_budget_bytes=None, budget_is_estimate=False):
self.base = base
self.ram_budget_bytes = ram_budget_bytes
+ self.budget_is_estimate = bool(budget_is_estimate)
+ self.drive_idle = False
self.cancelled = threading.Event()
self.thread = None
self.result = dict(state='not-started', read_bytes=0, elapsed_seconds=0.,
gpu_allocation_bytes=0, private_buffer_bytes=CHUNK,
scope='Decoder-only checkpoint pages; reclaimable OS cache, no GPU residency')
- def start(self):
+ def start(self, *, drive_idle=False):
if self.thread is not None:
return
+ self.drive_idle = bool(drive_idle)
if os.environ.get('FREEVIDEO_DECODE_READ_AHEAD', 'auto').lower() in ('off', '0', 'false'):
self.result.update(state='skipped', reason='Disabled by FREEVIDEO_DECODE_READ_AHEAD')
return
@@ -71,7 +84,7 @@ class DecoderReadAhead:
total = sum(hi - lo for _, spans, _ in plans for lo, hi in spans)
available, complete = available_memory()
allowance = max(0, available - 2 * GiB)
- if self.ram_budget_bytes is not None:
+ if self.ram_budget_bytes is not None and not (self.budget_is_estimate and self.drive_idle):
from .ram import ProcessMemory
from .system import memory_sample
sample = ProcessMemory().sample(os.getpid())
diff --git a/freevideo_engine/diagnostic_resources.py b/freevideo_engine/diagnostic_resources.py
index 508411c..46102be 100644
--- a/freevideo_engine/diagnostic_resources.py
+++ b/freevideo_engine/diagnostic_resources.py
@@ -259,7 +259,8 @@ def decoder_read_ahead(value):
if sampling:
result['sampling'] = numbers(sampling, ('trigger_step', 'steps_remaining',
'estimated_remaining_seconds',
- 'trigger_elapsed_seconds'))
+ 'trigger_elapsed_seconds', 'drive_reads_last_step',
+ 'drive_layers'))
return result
diff --git a/freevideo_engine/editor_audio.py b/freevideo_engine/editor_audio.py
new file mode 100644
index 0000000..d65a2af
--- /dev/null
+++ b/freevideo_engine/editor_audio.py
@@ -0,0 +1,159 @@
+"""Pure timeline audio envelopes; volume is applied by the caller to base samples."""
+import math
+import re
+
+from .editor_speed import changed, audio_changed, source_sample_start
+
+
+def clip_fields(raw, kind):
+ result = {}
+ for name in ('fade_in', 'fade_out', 'crossfade'):
+ if name in raw:
+ if kind != 'audio' or type(raw[name]) is not int or not 0 <= raw[name] <= 120:
+ raise ValueError('Invalid audio envelope')
+ result[name] = raw[name]
+ if 'detached_from' in raw:
+ value = raw['detached_from']
+ if (not isinstance(value, str) or not re.fullmatch(r'c[1-9]\d{0,8}', value)
+ or value == raw['id'] or raw.get('link')):
+ raise ValueError('Invalid detached audio')
+ result['detached_from'] = value
+ return result
+
+
+def track_fields(raw):
+ result = {}
+ for name in ('muted', 'solo', 'locked'):
+ if name in raw:
+ if type(raw[name]) is not bool:
+ raise ValueError('Invalid audio track flag')
+ result[name] = raw[name]
+ return result
+
+
+def track_audible(track, tracks):
+ return not track.get('muted') and (not any(row.get('solo') for row in tracks) or bool(track.get('solo')))
+
+
+def clip_audible(clip, track, tracks):
+ return (track_audible(track, tracks) and not (clip.get('speed_audio') == 'mute' and changed(clip))
+ and not any(row['kind'] == 'video' and row.get('muted')
+ and any(video['id'] == clip.get('link') for video in row['clips']) for row in tracks))
+
+
+def _samples(frames, rate, fps):
+ return math.floor(frames * rate / fps + .5)
+
+
+def _source_start(clip, rate, fps):
+ if audio_changed(clip):
+ return math.floor(source_sample_start(clip) * rate / 48000 + .5)
+ splice = clip.get('splice')
+ return (math.floor((splice['audio_samples'] / 32000 + (clip['in'] - splice['frames']) / fps) * rate + .5)
+ if splice else _samples(clip['in'], rate, fps))
+
+
+def crossfade_reads(track, rate=48000, fps=24):
+ """Raw extra read positions/counts at each contiguous audio junction.
+
+ Changed speed or reverse forbids extension on that side. Odd sample counts
+ place the extra sample after the junction. Source coordinates include splice.
+ """
+ result = []
+ for left, right in zip(track['clips'], track['clips'][1:]):
+ if (not left.get('source') or not right.get('source') or not right.get('crossfade')
+ or left['start'] + left['frames'] != right['start']):
+ continue
+ count = _samples(min(right['crossfade'], 120, left['frames'], right['frames']), rate, fps)
+ pre, post = count // 2, count - count // 2
+ def extend(clip):
+ return not changed(clip)
+ tail = (min(post, max(0, _samples(left['length'], rate, fps) - _source_start(left, rate, fps)
+ - _samples(left['frames'], rate, fps))) if extend(left) else 0)
+ head = min(pre, max(0, _source_start(right, rate, fps))) if extend(right) else 0
+ result.append(dict(left=left['id'], right=right['id'], boundary=_samples(right['start'], rate, fps),
+ pre=pre, post=post, left_tail=tail, right_head=head,
+ left_read_start=_source_start(left, rate, fps) + _samples(left['frames'], rate, fps),
+ right_read_start=_source_start(right, rate, fps) - head))
+ return result
+
+
+def _ramp(position, length):
+ import numpy as np
+ return (position >= 0).astype(float) if length <= 1 else np.clip(position / (length - 1), 0, 1)
+
+
+def fade_gain(clip, local, length, rate=48000, fps=24):
+ import numpy as np
+ local = np.asarray(local)
+ gain = np.ones(local.shape, dtype=np.float64)
+ if clip.get('fade_in'):
+ gain *= _ramp(local, _samples(min(120, clip['frames'] // 2, clip['fade_in']), rate, fps))
+ if clip.get('fade_out'):
+ gain *= _ramp(length - 1 - local, _samples(min(120, clip['frames'] // 2, clip['fade_out']), rate, fps))
+ return gain
+
+
+def apply_track_audio(block, block_start, track, tracks, *, rate=48000, fps=24, extras=None):
+ """Return a new planar C×N block, with the same shape and timeline origin.
+
+ Base block already has volume. extras[right_id] contains raw planar
+ left_tail/right_head arrays. Missing extras use a fade out/in at the cut.
+ Work depends on block size; no decoding, file access or whole-edit buffer.
+ """
+ import numpy as np
+ if type(block_start) is not int or block_start < 0 or not math.isfinite(rate) or rate <= 0 or not math.isfinite(fps) or fps <= 0:
+ raise ValueError('Invalid timeline audio coordinates')
+ output = np.array(block, dtype=np.float64, copy=True)
+ if output.ndim != 2:
+ raise ValueError('Expected planar audio')
+ count = output.shape[1]
+ if not track_audible(track, tracks):
+ output.fill(0)
+ return output
+ added = np.zeros_like(output)
+ plans = []
+ for raw in crossfade_reads(track, rate, fps):
+ extra = (extras or {}).get(raw['right'], {})
+ data = {}
+ for name in ('left_tail', 'right_head'):
+ value = np.asarray(extra.get(name, np.zeros((output.shape[0], 0))), dtype=np.float64)
+ if value.ndim != 2 or value.shape[0] != output.shape[0]:
+ raise ValueError('Extra read channel mismatch')
+ data[name] = value
+ plans.append(dict(raw, tail=min(raw['left_tail'], data['left_tail'].shape[1]),
+ head=min(raw['right_head'], data['right_head'].shape[1]), extra=data))
+ for clip in track['clips']:
+ start = _samples(clip['start'], rate, fps)
+ stop = _samples(clip['start'] + clip['frames'], rate, fps)
+ incoming = next((p for p in plans if p['right'] == clip['id']), None)
+ outgoing = next((p for p in plans if p['left'] == clip['id']), None)
+ lo = start - (incoming['head'] if incoming else 0)
+ hi = stop + (outgoing['tail'] if outgoing else 0)
+ audible = clip_audible(clip, track, tracks)
+ def gain(positions):
+ value = fade_gain(clip, positions - lo, hi - lo, rate, fps) if audible else np.zeros(positions.shape)
+ for plan, right in ((incoming, True), (outgoing, False)):
+ if plan:
+ if plan['head'] + plan['tail']:
+ a, b = plan['boundary'] - plan['head'], plan['boundary'] + plan['tail']
+ weight = _ramp(positions - a, b - a)
+ value *= weight if right else 1 - weight
+ else:
+ value *= (_ramp(positions - start, plan['post']) if right
+ else _ramp(stop - 1 - positions, plan['pre']))
+ return value
+ a, b = max(block_start, start), min(block_start + count, stop)
+ if b > a:
+ output[:, a - block_start:b - block_start] *= gain(np.arange(a, b))[None, :]
+ for plan, name, begin, size in ((incoming, 'right_head', lo, incoming['head'] if incoming else 0),
+ (outgoing, 'left_tail', stop, outgoing['tail'] if outgoing else 0)):
+ if not size:
+ continue
+ a, b = max(block_start, begin), min(block_start + count, begin + size)
+ if b > a:
+ data = plan['extra'][name]
+ offset = data.shape[1] - size if name == 'right_head' else 0
+ added[:, a - block_start:b - block_start] += (data[:, offset + a - begin:offset + b - begin]
+ * gain(np.arange(a, b))[None, :] * clip.get('volume', 1))
+ return output + added
diff --git a/freevideo_engine/editor_export.py b/freevideo_engine/editor_export.py
new file mode 100644
index 0000000..1797513
--- /dev/null
+++ b/freevideo_engine/editor_export.py
@@ -0,0 +1,865 @@
+"""CPU-only, bounded editor rendering and a serial background export queue.
+
+The renderer is independent of ComfyUI and the editor persistence service.
+Only the two persistence adapters below need that service at integration time.
+"""
+import asyncio
+import copy
+import errno
+import importlib
+import json
+import logging
+import math
+import os
+import re
+import threading
+import time
+import uuid
+from collections import deque
+from contextlib import ExitStack
+from datetime import datetime, timezone
+from fractions import Fraction
+from pathlib import Path
+
+from .editor_frames import display_frame, frame_not_after, last_frame_end
+from .editor_text import is_text_track, has_text_data, validate_text_project, paint_project, check_export_text, MissingGlyphs
+from . import editor_export_options
+from .editor_speed import validate_clip, changed as speed_changed, audio_changed, independent_join, VideoReader, AudioReader
+from .editor_audio import clip_fields, track_fields, clip_audible, track_audible, crossfade_reads, apply_track_audio
+
+FPS = 24
+SAMPLE_RATE = 48000
+SPLICE_RATE = 32000
+SAMPLES_PER_FRAME = SAMPLE_RATE // FPS
+FADE_SAMPLES = SAMPLE_RATE // 200 # 5 ms
+_PROJECT_ID = re.compile(r'e-[0-9a-f]{32}')
+_EXPORT_ID = re.compile(r'x-[0-9a-f]{32}')
+_IMPORT_ID = re.compile(r'[A-Za-z0-9_-]{1,80}')
+_RECORD_BYTES = 8 * 1024 * 1024
+
+
+class ExportError(Exception):
+ """A public reason code; never retain a decoder's path-bearing message."""
+ def __init__(self, reason='failed'):
+ self.reason = reason if reason in ('source_missing', 'unreadable', 'disk_full', 'failed') else 'failed'
+ super().__init__(self.reason)
+
+
+class ExportConflict(ValueError):
+ def __init__(self, revision):
+ super().__init__('Editor project has changed')
+ self.revision = revision
+
+
+class ExportCancelled(InterruptedError):
+ pass
+
+
+def _reason(error):
+ if isinstance(error, ExportError):
+ return error.reason
+ if isinstance(error, OSError) and error.errno == errno.ENOSPC:
+ return 'disk_full'
+ return 'failed'
+
+
+def _check(cancelled):
+ if cancelled and cancelled():
+ raise ExportCancelled('cancelled')
+
+
+def _whole(value, minimum=0):
+ return type(value) is int and minimum <= value <= 2**53 - 1
+
+
+def _layout(project):
+ """Bound encoder inputs; persistence/model own the full editing rules."""
+ if not isinstance(project, dict) or project.get('version') != 1 or project.get('fps') != FPS:
+ raise ExportError()
+ width, height = project.get('width'), project.get('height')
+ if any(not _whole(side, 2) or side > 8192 or side % 2 for side in (width, height)):
+ raise ExportError()
+ raw_tracks = project.get('tracks')
+ if has_text_data(project):
+ from .comfy_editor import validate
+ project = validate(project)
+ raw_tracks = [t for t in project['tracks'] if not is_text_track(t)]
+ if not isinstance(raw_tracks, list) or [t.get('id') for t in raw_tracks if isinstance(t, dict)] not in (
+ ['v1', 'a1'], ['v1', 'a1', 'a2']):
+ raise ExportError()
+ tracks, seen = {}, set()
+ for raw in raw_tracks:
+ if raw.get('kind') != ('video' if raw['id'] == 'v1' else 'audio'):
+ raise ExportError()
+ try:
+ track_fields(raw)
+ except ValueError:
+ raise ExportError() from None
+ clips = raw.get('clips')
+ if not isinstance(clips, list) or len(clips) > 10000:
+ raise ExportError()
+ end = 0
+ for clip in clips:
+ if not isinstance(clip, dict) or not isinstance(clip.get('id'), str) or clip['id'] in seen:
+ raise ExportError()
+ seen.add(clip['id'])
+ if any(not _whole(clip.get(key), 1 if key == 'frames' else 0)
+ for key in ('start', 'frames', 'in', 'length')):
+ raise ExportError()
+ validate_clip(clip, error=ExportError)
+ try:
+ clip_fields(clip, raw['kind'])
+ except ValueError:
+ raise ExportError() from None
+ if clip['start'] < end:
+ raise ExportError()
+ end = clip['start'] + clip['frames']
+ source = clip.get('source')
+ if source is not None and (not isinstance(source, dict) or source.get('kind') not in (
+ 'work', 'import', 'generated') or not isinstance(source.get('id'), str) or not source['id']):
+ raise ExportError()
+ if raw['id'] != 'v1':
+ volume = clip.get('volume', 1)
+ if type(volume) not in (int, float) or not math.isfinite(volume) or not 0 <= volume <= 2:
+ raise ExportError()
+ splice = clip.get('splice')
+ if splice is not None and (not isinstance(splice, dict) or any(
+ not _whole(splice.get(key)) for key in ('frames', 'audio_samples'))):
+ raise ExportError()
+ tracks[raw['id']] = clips
+ # Picture and sound set the length; text after them is not exported.
+ frames = max((c['start'] + c['frames'] for clips in tracks.values() for c in clips), default=0)
+ if not frames:
+ raise ExportError()
+ return width, height, frames, tracks
+
+
+def _media(resolve, clip, kind):
+ source = clip.get('source')
+ if source is None:
+ return None # Unfilled ranges render as black/silence, even while queued.
+ key = source['kind'] + ':' + source['id']
+ try:
+ value = resolve(key)
+ path = value.get(kind) if isinstance(value, dict) else None
+ if path is None or not Path(path).is_file():
+ raise ExportError('source_missing')
+ return Path(path)
+ except (FileNotFoundError, KeyError):
+ raise ExportError('source_missing') from None
+
+
+class _VideoReader:
+ """Two decoded frames, chosen by their timestamps, with backward keyframe seek."""
+ def __init__(self, path, first, width, height, cancelled, clip=None):
+ import av
+ self.clip = clip or {}
+ self.container = None
+ try:
+ self.container = av.open(str(path))
+ self.stream = self.container.streams.video[0]
+ self.stream.thread_count = 1
+ self.origin = Fraction(self.stream.start_time or 0) * self.stream.time_base
+ self.rate = self.stream.average_rate or self.stream.guessed_rate or FPS
+ desired = Fraction(first, FPS)
+ if desired > 0:
+ self.container.seek(int((self.origin + desired) / self.stream.time_base),
+ stream=self.stream, backward=True, any_frame=False)
+ self.decoder = iter(self.container.decode(self.stream))
+ self.index = 0
+ self.cancelled = cancelled
+ self.width, self.height = width, height
+ self.previous = None
+ self.following = self._next()
+ self.cached_frame = self.cached_pixels = None
+ if self.following is None:
+ raise ExportError('unreadable')
+ except BaseException as error:
+ self.close()
+ if isinstance(error, (ExportCancelled, ExportError)):
+ raise
+ raise ExportError('unreadable') from None
+
+ def _next(self):
+ _check(self.cancelled)
+ frame = next(self.decoder, None)
+ if frame is None:
+ return None
+ stamp = (Fraction(frame.pts) * frame.time_base - self.origin if frame.pts is not None
+ else Fraction(self.index, 1) / self.rate)
+ self.index += 1
+ return stamp, frame
+
+ def pixels(self, number):
+ import numpy as np
+ try:
+ desired = Fraction(number, FPS)
+ while self.following is not None and frame_not_after(self.following[0], number):
+ self.previous, self.following = self.following, self._next()
+ chosen = self.previous
+ if chosen is None or (self.following is None and desired >= last_frame_end(chosen[0], chosen[1], self.rate)):
+ raise ExportError('unreadable')
+ frame = chosen[1]
+ if frame is not self.cached_frame:
+ picture = display_frame(frame)
+ from .editor_picture import place, plan
+ # Anything but the default placement uses the shared routine: crop, flip,
+ # rotate, fit, scale, offset, and a blurred fill where the picture leaves room.
+ if not plan(self.clip, picture.width, picture.height, self.width, self.height)['legacy']:
+ self.cached_pixels = place(picture.to_ndarray(format='rgb24'), self.clip, self.width, self.height)
+ self.cached_frame = frame
+ if frame is not self.cached_frame:
+ ratio = max(self.width / picture.width, self.height / picture.height)
+ w, h = max(1, round(picture.width * ratio)), max(1, round(picture.height * ratio))
+ image = picture.reformat(width=w, height=h, format='rgb24').to_ndarray()
+ if (w, h) == (self.width, self.height):
+ self.cached_pixels = image
+ else:
+ # Odd surplus is cropped more on right/bottom (legacy cover).
+ x, y = (w - self.width) // 2, (h - self.height) // 2
+ self.cached_pixels = image[y:y + self.height, x:x + self.width]
+ self.cached_frame = frame
+ return self.cached_pixels
+ except (ExportError, ExportCancelled):
+ raise
+ except Exception:
+ raise ExportError('unreadable') from None
+
+ def close(self):
+ if self.container is not None:
+ self.container.close()
+ self.container = None
+
+
+class _AudioReader:
+ """One resampled packet at a time; timestamps preserve offsets and seek alignment."""
+ def __init__(self, path, first_sample, cancelled):
+ import av
+ self.container = None
+ try:
+ self.container = av.open(str(path))
+ self.stream = self.container.streams.audio[0]
+ self.stream.thread_count = 1
+ origin_stream = next(iter(self.container.streams.video), self.stream)
+ self.origin = Fraction(origin_stream.start_time or 0) * origin_stream.time_base
+ self.mono = len(self.stream.layout.channels) == 1
+ self.resampler = av.AudioResampler(format='fltp', layout='mono' if self.mono else 'stereo',
+ rate=SAMPLE_RATE)
+ if first_sample > SAMPLE_RATE:
+ stamp = self.origin + Fraction(first_sample, SAMPLE_RATE) - Fraction(1, 10)
+ if self.stream.duration is not None:
+ # A legal picture range may extend past the sound's end.
+ # Seek into its last packet, then let samples() pad with zero.
+ end = Fraction((self.stream.start_time or 0) + self.stream.duration) * self.stream.time_base
+ stamp = min(stamp, max(self.origin, end - Fraction(1, 10)))
+ self.container.seek(int(stamp / self.stream.time_base), stream=self.stream,
+ backward=True, any_frame=False)
+ self.cancelled = cancelled
+ self.chunks = iter(self._chunks())
+ self.chunk = next(self.chunks, None)
+ if self.chunk is None:
+ raise ExportError('unreadable')
+ except BaseException as error:
+ self.close()
+ if isinstance(error, (ExportCancelled, ExportError)):
+ raise
+ raise ExportError('unreadable') from None
+
+ def _chunks(self):
+ import numpy as np
+ fallback = 0
+ for frame in self.container.decode(self.stream):
+ _check(self.cancelled)
+ for item in self.resampler.resample(frame):
+ stamp = (round((Fraction(item.pts) * item.time_base - self.origin) * SAMPLE_RATE)
+ if item.pts is not None else fallback)
+ data = item.to_ndarray()
+ if self.mono:
+ data = np.repeat(data, 2, axis=0)
+ if not np.isfinite(data).all():
+ raise ExportError('unreadable')
+ fallback = stamp + item.samples
+ yield stamp, data
+ for item in self.resampler.resample(None):
+ _check(self.cancelled)
+ data = item.to_ndarray()
+ if self.mono:
+ data = np.repeat(data, 2, axis=0)
+ yield fallback, data
+ fallback += item.samples
+
+ def samples(self, start, count):
+ import numpy as np
+ result = np.zeros((2, count), dtype=np.float32)
+ try:
+ while self.chunk is not None:
+ stamp, data = self.chunk
+ end = stamp + data.shape[1]
+ if stamp >= start + count:
+ break
+ lo, hi = max(start, stamp), min(start + count, end)
+ if hi > lo:
+ result[:, lo - start:hi - start] = data[:, lo - stamp:hi - stamp]
+ if end > start + count:
+ break
+ self.chunk = next(self.chunks, None)
+ return result
+ except (ExportError, ExportCancelled):
+ raise
+ except Exception:
+ raise ExportError('unreadable') from None
+
+ def close(self):
+ if self.container is not None:
+ self.container.close()
+ self.container = None
+ # _chunks() captures self; clear the generator to break that cycle at
+ # every cut instead of retaining retired packets until cyclic GC runs.
+ self.chunk = self.chunks = None
+
+
+def _audio_start(clip):
+ splice = clip.get('splice')
+ seconds = (Fraction(splice['audio_samples'], SPLICE_RATE) +
+ Fraction(clip['in'] - splice['frames'], FPS) if splice else Fraction(clip['in'], FPS))
+ return round(seconds * SAMPLE_RATE)
+
+
+class _CrossfadeReads:
+ """Separate bounded pre-read buffers for junctions touching the current block."""
+ def __init__(self, track, resolve, cancelled):
+ self.track, self.resolve, self.cancelled = track, resolve, cancelled
+ self.plans = crossfade_reads(track)
+ self.clips = {clip['id']: clip for clip in track['clips']}
+ self.cache = {}
+ self.incoming = {plan['right'] for plan in self.plans}
+ self.outgoing = {plan['left'] for plan in self.plans}
+
+ def extras(self, start, count):
+ current = {plan['right']: plan for plan in self.plans
+ if plan['boundary'] - plan['pre'] < start + count
+ and plan['boundary'] + plan['post'] > start}
+ self.cache = {key: value for key, value in self.cache.items() if key in current}
+ for key, plan in current.items():
+ if key in self.cache:
+ continue
+ extra = {}
+ for side, clip_id, position in (('left_tail', plan['left'], plan['left_read_start']),
+ ('right_head', plan['right'], plan['right_read_start'])):
+ _check(self.cancelled)
+ size = min(plan[side], 5 * SAMPLE_RATE)
+ if not size:
+ continue
+ path = _media(self.resolve, self.clips[clip_id], 'audio')
+ reader = _AudioReader(path, position, self.cancelled)
+ try:
+ extra[side] = reader.samples(position, size)
+ finally:
+ reader.close()
+ self.cache[key] = extra
+ return self.cache
+
+
+
+def _audio_frame(samples, **kwargs):
+ import av
+ return av.AudioFrame.from_ndarray(samples, **kwargs)
+
+
+def _checked_target(target, root=None):
+ from .comfy_editor import _safe
+ target = Path(target).absolute()
+ root = Path(root).absolute() if root is not None else Path(target.anchor)
+ try:
+ return _safe(root, target.relative_to(root).as_posix())
+ except (ValueError, OSError):
+ raise ExportError('failed') from None
+
+
+def render(project: dict, resolve, target: Path, *, progress=None, cancelled=None, options=None):
+ """Render exactly the saved timeline, publishing atomically after encoder flush.
+
+ Resolve returns local Paths, never HTTP URLs. Memory contains at most one
+ video decoder, one main audio decoder per track, and one separate extra
+ reader at a time. Reverse RGB windows and crossfade buffers are bounded;
+ duration changes disk/time usage, not resident media storage.
+ Raises ExportError(reason) or ExportCancelled and removes owned partials.
+ Existing destinations are refused and never removed.
+ """
+ import av
+ import numpy as np
+ target = Path(target)
+ temporary = target.with_name('.editor-export-' + uuid.uuid4().hex + '.mp4')
+ published = False
+ complete = False
+ try:
+ width, height, total, tracks = _layout(project)
+ check_export_text(project)
+ settings = editor_export_options.effective(options, width, height, total)
+ width, height, total = settings.width, settings.height, settings.frames
+ if settings.only == 'sound':
+ tracks = {key: clips for key, clips in tracks.items() if key != 'v1'}
+ _check(cancelled)
+ _checked_target(target)
+ _checked_target(temporary)
+ if target.exists() or target.is_symlink():
+ raise ExportError()
+ target.parent.mkdir(parents=True, exist_ok=True)
+ _checked_target(target)
+ if progress:
+ progress(0.)
+ # Resolve each reference once, without opening all sources/decoders.
+ resolved = {}
+ for kind, clips in tracks.items():
+ for clip in clips:
+ _check(cancelled)
+ if clip.get('source'):
+ source = clip['source']
+ key = source['kind'] + ':' + source['id']
+ if key not in resolved:
+ try:
+ resolved[key] = resolve(key)
+ except (FileNotFoundError, KeyError):
+ raise ExportError('source_missing') from None
+ _media(resolved.__getitem__, clip, 'video' if kind == 'v1' else 'audio')
+ audio_tracks = {track['id']: track for track in project['tracks'] if track['kind'] == 'audio'}
+ envelopes = {key: _CrossfadeReads(track, resolved.__getitem__, cancelled)
+ for key, track in audio_tracks.items()}
+ with ExitStack() as readers, av.open(str(temporary), 'w', format=settings.container,
+ options=settings.container_options) as output:
+ video = None
+ if settings.only != 'sound':
+ video = output.add_stream('libx264', rate=FPS)
+ video.width, video.height, video.pix_fmt = width, height, 'yuv420p'
+ # High preserves the original CRF 23 / medium / yuv420p encode.
+ video.options = settings.video_options
+ video.codec_context.thread_count = 2
+ audio = output.add_stream(settings.audio_codec, rate=SAMPLE_RATE)
+ audio.layout = 'stereo'
+ audio.codec_context.time_base = Fraction(1, SAMPLE_RATE)
+ audio.codec_context.thread_count = 1
+ indices = {track: 0 for track in tracks}
+ active, decoders = {}, {}
+ readers.callback(lambda: [decoder.close() for decoder in decoders.values()])
+ black = np.zeros((height, width, 3), dtype=np.uint8) if video is not None else None
+ written = 0
+ lead_start = editor_export_options.audio_lead_start(settings.start, tracks)
+ for number in range(lead_start, settings.start + total):
+ _check(cancelled)
+ for track, clips in editor_export_options.frame_tracks(tracks, settings.start, number):
+ index = indices[track]
+ while index < len(clips) and number >= clips[index]['start'] + clips[index]['frames']:
+ index += 1
+ indices[track] = index
+ clip = clips[index] if index < len(clips) and clips[index]['start'] <= number else None
+ if clip is not active.get(track):
+ if decoders.get(track):
+ decoders.pop(track).close()
+ active[track] = clip
+ if clip is not None and (track == 'v1' or clip_audible(clip, audio_tracks[track], project['tracks'])):
+ path = _media(resolved.__getitem__, clip, 'video' if track == 'v1' else 'audio')
+ if path is not None:
+ decoder = (VideoReader(path, clip, width, height, cancelled) if track == 'v1' and speed_changed(clip)
+ else AudioReader(path, clip, cancelled) if track != 'v1' and audio_changed(clip)
+ else _VideoReader(path, clip['in'], width, height, cancelled, clip) if track == 'v1'
+ else _AudioReader(path, _audio_start(clip), cancelled))
+ decoders[track] = decoder
+ if video is not None and number >= settings.start:
+ clip = active.get('v1')
+ pixels = (decoders['v1'].pixels(clip['in'] + number - clip['start'])
+ if clip is not None and 'v1' in decoders else black)
+ # Text is placed on the timeline frame; its layout is proportional to the output size.
+ pixels = paint_project(pixels, project, number, width, height)
+ frame = av.VideoFrame.from_ndarray(pixels, format='rgb24')
+ frame.pts, frame.time_base = number - settings.start, Fraction(1, FPS)
+ for packet in video.encode(frame):
+ output.mux(packet)
+ written += 1
+ if progress:
+ progress(written / total * .99)
+ mixed = np.zeros((2, SAMPLES_PER_FRAME), dtype=np.float32)
+ for track in ('a1', 'a2'):
+ clip = active.get(track)
+ if track not in audio_tracks:
+ continue
+ track_block = np.zeros_like(mixed)
+ if clip is not None and track in decoders:
+ local = (number - clip['start']) * SAMPLES_PER_FRAME
+ samples = decoders[track].samples(_audio_start(clip) + local, SAMPLES_PER_FRAME)
+ positions = local + np.arange(SAMPLES_PER_FRAME)
+ clips = tracks[track]; index = indices[track]
+ previous = clips[index - 1] if index else None
+ following = clips[index + 1] if index + 1 < len(clips) else None
+ gain = np.ones(SAMPLES_PER_FRAME, dtype=np.float32)
+ if (not clip.get('fade_in') and clip['id'] not in envelopes[track].incoming
+ and (independent_join(previous, clip) or previous is None or not previous.get('source')
+ or previous.get('volume', 1) == 0
+ or not clip_audible(previous, audio_tracks[track], project['tracks'])
+ or previous['start'] + previous['frames'] != clip['start'])):
+ gain *= np.clip(positions / (FADE_SAMPLES - 1), 0, 1).astype(np.float32)
+ if (not clip.get('fade_out') and clip['id'] not in envelopes[track].outgoing
+ and (independent_join(clip, following) or following is None or not following.get('source')
+ or following.get('volume', 1) == 0
+ or not clip_audible(following, audio_tracks[track], project['tracks'])
+ or following['start'] != clip['start'] + clip['frames'])):
+ gain *= np.clip((clip['frames'] * SAMPLES_PER_FRAME - 1 - positions) / (FADE_SAMPLES - 1), 0, 1).astype(np.float32)
+ track_block = samples * gain[None, :] * clip.get('volume', 1)
+ extras = (envelopes[track].extras(number * SAMPLES_PER_FRAME, SAMPLES_PER_FRAME)
+ if track_audible(audio_tracks[track], project['tracks']) else None)
+ mixed += apply_track_audio(track_block, number * SAMPLES_PER_FRAME, audio_tracks[track],
+ project['tracks'], extras=extras)
+ del extras
+ np.clip(mixed, -1., 1., out=mixed)
+ if number < settings.start:
+ continue
+ samples, sample_format = editor_export_options.sound_samples(mixed, settings)
+ sound = _audio_frame(samples, format=sample_format, layout='stereo')
+ sound.sample_rate = SAMPLE_RATE
+ sound.pts, sound.time_base = (number - settings.start) * SAMPLES_PER_FRAME, Fraction(1, SAMPLE_RATE)
+ for packet in audio.encode(sound):
+ output.mux(packet)
+ if video is None and progress:
+ progress((number - settings.start + 1) / total * .99)
+ _check(cancelled)
+ for stream in (video, audio):
+ if stream is None:
+ continue
+ for packet in stream.encode(None):
+ _check(cancelled)
+ output.mux(packet)
+ if stream is video:
+ written += 1
+ if progress:
+ progress(written / total * .99)
+ _check(cancelled)
+ _checked_target(temporary)
+ with temporary.open('r+b') as stream:
+ os.fsync(stream.fileno())
+ _check(cancelled)
+ _checked_target(target)
+ temporary.replace(target)
+ published = True
+ _check(cancelled)
+ if progress:
+ progress(1.)
+ _check(cancelled)
+ complete = True
+ return target
+ except (ExportError, ExportCancelled):
+ raise
+ except Exception as error:
+ raise ExportError(_reason(error)) from None
+ finally:
+ temporary.unlink(missing_ok=True)
+ # A cancellation in the final publish window still owns this target.
+ if published and (not complete or (cancelled and cancelled())):
+ target.unlink(missing_ok=True)
+
+
+def _output_root():
+ import folder_paths
+ return Path(folder_paths.get_output_directory()).resolve()
+
+
+def _read_json(path):
+ with path.open('rb') as stream:
+ value = stream.read(_RECORD_BYTES + 1)
+ if len(value) > _RECORD_BYTES:
+ raise ValueError('Record too large')
+ return json.loads(value)
+
+
+def _contained(root, path):
+ root, path = Path(root).resolve(), Path(path).resolve()
+ if not path.is_relative_to(root):
+ raise ValueError('Invalid source')
+ return path
+
+
+def _editor_service():
+ try:
+ return importlib.import_module('.comfy_editor', __package__)
+ except ModuleNotFoundError as error:
+ if error.name != __package__ + '.comfy_editor':
+ raise
+ return None
+
+
+def load_project(identity, revision=None):
+ """Persistence seam: a saved record snapshot; no unsaved browser state."""
+ if not isinstance(identity, str) or not _PROJECT_ID.fullmatch(identity):
+ raise ValueError('Invalid project')
+ service = _editor_service()
+ output = _output_root()
+ if service is not None:
+ # Read under the persistence lock, without decoding/probing the source
+ # catalogue that load() adds for the browser.
+ with service._STATE:
+ record = service._read_project(output, identity)
+ if revision is not None and record['revision'] != revision:
+ raise ExportConflict(record['revision'])
+ return copy.deepcopy(record)
+ root = output / 'FreeVideo' / '.editor' / 'projects'
+ record = _read_json(_contained(root, root / identity / 'project.json'))
+ if revision is not None and record['revision'] != revision:
+ raise ExportConflict(record['revision'])
+ return record
+
+
+def resolve_source(key):
+ """Source seam. Local paths only; browser media URLs never reach render()."""
+ from .comfy_library import _report, _video
+ if not isinstance(key, str) or ':' not in key:
+ raise ValueError('Invalid source')
+ kind, identity = key.split(':', 1)
+ root = _output_root()
+ if kind == 'work':
+ path = _video(root, identity)
+ _report(path)
+ elif kind == 'generated':
+ relative = Path(identity)
+ if relative.is_absolute() or '\\' in identity or '..' in relative.parts:
+ raise ValueError('Invalid source')
+ service = _editor_service()
+ path = service.media_path(root, key) if service is not None else _contained(root, root / relative)
+ elif kind == 'import' and _IMPORT_ID.fullmatch(identity):
+ service = _editor_service()
+ if service is not None:
+ # The preview is readiness-checked by the server. Render the retained
+ # original so the preview's 1920 px/32 kHz limits do not reduce export.
+ preview = service.media_path(root, key)
+ original = service._import_path(root, identity, 'source.bin')
+ path = original if original.is_file() else preview
+ if path == preview:
+ logging.getLogger(__name__).warning('Editor export: original missing; using import preview (%s).', identity)
+ metadata = service._read_import(root, identity)
+ return dict(video=path if metadata['kind'] == 'video' else None,
+ audio=path if metadata['kind'] == 'audio' or metadata.get('has_audio') else None)
+ folder = _contained(root / 'FreeVideo' / '.editor' / 'imports',
+ root / 'FreeVideo' / '.editor' / 'imports' / identity)
+ metadata = _read_json(folder / 'import.json')
+ if metadata.get('state') != 'ready' or metadata.get('kind') not in ('video', 'audio'):
+ raise FileNotFoundError()
+ original = _contained(folder, folder / 'source.bin')
+ preview = _contained(folder, folder / ('preview.mp4' if metadata['kind'] == 'video' else 'preview.m4a'))
+ path = original if original.is_file() else preview
+ if path == preview:
+ logging.getLogger(__name__).warning('Editor export: original missing; using import preview (%s).', identity)
+ return dict(video=path if metadata['kind'] == 'video' else None,
+ audio=path if metadata['kind'] == 'audio' or metadata.get('has_audio') else None)
+ else:
+ raise ValueError('Invalid source')
+ if not path.is_file():
+ raise FileNotFoundError()
+ # A linked audio clip uses this same video file. The decoder checks the
+ # requested stream exists, so a broken source cannot silently turn mute.
+ return dict(video=path, audio=path)
+
+
+def _save_report(target, project, seconds, *, options=None):
+ """Completion marker after media closes; only video.mp4 enters the library."""
+ frames = _layout(project)[2]
+ report = dict(success=True, geometry=dict(width=project['width'], height=project['height'],
+ frames=frames, fps=FPS, seconds=frames / FPS), request_seconds=seconds,
+ video={}, editor_export=dict(project=project.get('id'), revision=project.get('revision'),
+ name=str(project.get('name') or '')[:200]),
+ encoding=dict(video_codec='h264', pixel_format='yuv420p', crf=23, preset='medium',
+ audio_codec='aac', sample_rate=SAMPLE_RATE, channels=2))
+ editor_export_options.report_values(report, editor_export_options.effective(
+ options, project['width'], project['height'], frames))
+ _checked_target(target)
+ path = _checked_target(target.with_suffix('.request.json'))
+ temporary = _checked_target(path.with_name(path.name + '.tmp'))
+ try:
+ with temporary.open('w', encoding='utf-8') as stream:
+ json.dump(report, stream, ensure_ascii=False)
+ stream.flush()
+ os.fsync(stream.fileno())
+ _checked_target(path)
+ temporary.replace(path)
+ finally:
+ temporary.unlink(missing_ok=True)
+
+
+class ExportQueue:
+ """One worker, FIFO, independently cancellable jobs (queued = running/0)."""
+ def __init__(self, root, *, loader=None, resolver=None, renderer=None):
+ self.root = Path(root).absolute()
+ self.loader = loader or load_project
+ self.resolver = resolver or resolve_source
+ self.renderer = renderer or render
+ self.lock = threading.RLock()
+ self.jobs = {}
+ self.pending = deque()
+ self.worker = None
+
+ @staticmethod
+ def _view(job):
+ return {**{key: job[key] for key in ('id', 'state', 'fraction', 'work', 'reason')},
+ **job['options'].status(), 'path': job.get('path'), 'url': job.get('url'),
+ 'project_id': job['project'].get('id'), 'revision': job['project'].get('revision')}
+
+ def submit(self, identity, revision=None, *, options=None):
+ if not isinstance(identity, str) or not _PROJECT_ID.fullmatch(identity):
+ raise ValueError('Invalid project')
+ if revision is not None and not _whole(revision):
+ raise ValueError('Invalid revision')
+ if self.loader is load_project:
+ project = load_project(identity, revision)
+ else:
+ project = copy.deepcopy(self.loader(identity))
+ if revision is not None and project['revision'] != revision:
+ raise ExportConflict(project['revision'])
+ try:
+ width, height, frames, _ = _layout(project)
+ except ExportError:
+ raise ValueError('Project cannot be exported') from None
+ check_export_text(project)
+ settings = editor_export_options.validate({} if options is None else options, width, height, frames)
+ job = dict(id='x-' + uuid.uuid4().hex, state='running', fraction=0., work=None, reason=None,
+ project=project, options=settings, stop=threading.Event())
+ with self.lock:
+ # Prune completed entries only; never drop queued/running jobs.
+ if len(self.jobs) >= 200:
+ for old in list(self.jobs):
+ if self.jobs[old]['state'] != 'running':
+ del self.jobs[old]
+ if len(self.jobs) < 200:
+ break
+ if len(self.jobs) >= 200:
+ raise ExportError()
+ self.jobs[job['id']] = job
+ self.pending.append(job['id'])
+ initial = self._view(job)
+ if self.worker is None:
+ self.worker = threading.Thread(target=self._run, name='freevideo-editor-export', daemon=True)
+ self.worker.start()
+ return initial
+
+ def get(self, identity):
+ if not isinstance(identity, str) or not _EXPORT_ID.fullmatch(identity):
+ raise ValueError('Invalid export')
+ with self.lock:
+ if identity not in self.jobs:
+ raise KeyError(identity)
+ return self._view(self.jobs[identity])
+
+ def cancel(self, identity):
+ with self.lock:
+ self.get(identity)
+ job = self.jobs[identity]
+ if job['state'] == 'running':
+ job['stop'].set()
+ if identity in self.pending:
+ self.pending.remove(identity)
+ job['state'] = 'cancelled'
+ return self._view(job)
+
+ def _run(self):
+ while True:
+ with self.lock:
+ if not self.pending:
+ self.worker = None
+ return
+ job = self.jobs[self.pending.popleft()]
+ if job['stop'].is_set():
+ job['state'] = 'cancelled'
+ continue
+ stamp = datetime.now(timezone.utc)
+ work = stamp.strftime('%Y-%m-%d') + '/' + uuid.uuid4().hex
+ folder = self.root / 'FreeVideo' / work
+ target = folder / job['options'].filename
+ started = time.monotonic()
+
+ def progress(fraction):
+ with self.lock:
+ job['fraction'] = max(job['fraction'], min(.99, float(fraction)))
+
+ owned = False
+ try:
+ _checked_target(target, self.root)
+ _checked_target(target.with_suffix('.request.json'), self.root)
+ owned = True
+ self.renderer(job['project'], self.resolver, target, progress=progress,
+ cancelled=job['stop'].is_set, options=job['options'])
+ _check(job['stop'].is_set)
+ # Prevent cancel from racing the completion marker/publication.
+ with self.lock:
+ _check(job['stop'].is_set)
+ _checked_target(target, self.root)
+ _save_report(target, job['project'], time.monotonic() - started, options=job['options'])
+ job.update(state='done', fraction=1., work=work if job['options'].only == 'video' else None,
+ **editor_export_options.result_file(work, job['options']))
+ except Exception as error:
+ # Only this job's UUID folder is owned by the worker.
+ for path in (target, target.with_suffix('.request.json')):
+ try:
+ if owned:
+ _checked_target(path, self.root).unlink(missing_ok=True)
+ except (OSError, ExportError):
+ pass
+ try:
+ if owned:
+ _checked_target(folder, self.root).rmdir()
+ except (OSError, ExportError):
+ pass
+ with self.lock:
+ if isinstance(error, ExportCancelled) or job['stop'].is_set():
+ job.update(state='cancelled', reason=None)
+ else:
+ job.update(state='failed', reason=_reason(error))
+
+
+def register():
+ """Register the three endpoints once on the existing ComfyUI server."""
+ from aiohttp import web
+ from server import PromptServer
+ server = PromptServer.instance
+ if server is None or getattr(server, '_freevideo_editor_export', False):
+ return
+ queue = ExportQueue(_output_root())
+ server._freevideo_editor_export = queue
+
+ def response(value):
+ return web.json_response({'export': value}, headers={'Cache-Control': 'no-store'})
+
+ @server.routes.post('/freevideo/editor/export')
+ async def start(request):
+ try:
+ body = await request.json()
+ if (not isinstance(body, dict) or not {'id', 'revision'} <= set(body)
+ or set(body) - {'id', 'revision', 'options'} or not _whole(body.get('revision'))
+ or 'options' in body and not isinstance(body['options'], dict)):
+ raise ValueError('Invalid request')
+ return response(await asyncio.to_thread(queue.submit, body['id'], body['revision'], options=body.get('options')))
+ except MissingGlyphs as error:
+ return web.json_response({'reason': 'missing_glyphs', 'items': error.items}, status=400)
+ except ExportConflict as error:
+ return web.json_response({'revision': error.revision}, status=409, headers={'Cache-Control': 'no-store'})
+ except FileNotFoundError:
+ return web.json_response({'reason': 'source_missing'}, status=404)
+ except (ValueError, TypeError, KeyError):
+ return web.json_response({'reason': 'failed'}, status=400)
+ except Exception as error:
+ return web.json_response({'reason': _reason(error)}, status=503)
+
+ @server.routes.get('/freevideo/editor/export')
+ async def status(request):
+ try:
+ return response(queue.get(request.query.get('id')))
+ except KeyError:
+ return web.json_response({'reason': 'failed'}, status=404)
+ except ValueError:
+ return web.json_response({'reason': 'failed'}, status=400)
+
+ @server.routes.post('/freevideo/editor/export/cancel')
+ async def cancel(request):
+ try:
+ body = await request.json()
+ if not isinstance(body, dict) or set(body) != {'id'}:
+ raise ValueError('Invalid request')
+ return response(queue.cancel(body['id']))
+ except KeyError:
+ return web.json_response({'reason': 'failed'}, status=404)
+ except (ValueError, TypeError):
+ return web.json_response({'reason': 'failed'}, status=400)
diff --git a/freevideo_engine/editor_export_options.py b/freevideo_engine/editor_export_options.py
new file mode 100644
index 0000000..437c17b
--- /dev/null
+++ b/freevideo_engine/editor_export_options.py
@@ -0,0 +1,126 @@
+"""Validated export settings and encoder helpers, independent of editor state."""
+from dataclasses import dataclass
+from pathlib import PurePosixPath
+from urllib.parse import urlencode
+
+
+@dataclass(frozen=True)
+class ExportOptions:
+ width: int
+ height: int
+ start: int
+ frames: int
+ only: str = 'video'
+ quality: str = 'high'
+ sound_format: str = 'm4a'
+
+ @property
+ def filename(self):
+ return 'audio.' + self.sound_format if self.only == 'sound' else 'video.mp4'
+
+ @property
+ def container(self):
+ return 'wav' if self.only == 'sound' and self.sound_format == 'wav' else 'mp4'
+
+ @property
+ def container_options(self):
+ return ({} if self.container == 'wav' else
+ {'movflags': 'use_metadata_tags+faststart', 'movie_timescale': '48000'})
+
+ @property
+ def video_options(self):
+ return {'crf': str({'high': 23, 'standard': 25, 'small': 30}[self.quality]), 'preset': 'medium'}
+
+ @property
+ def audio_codec(self):
+ return 'pcm_s16le' if self.container == 'wav' else 'aac'
+
+ def status(self):
+ return dict(width=self.width, height=self.height, frames=self.frames,
+ only=self.only, quality=self.quality if self.only == 'video' else None,
+ range=dict(start=self.start, frames=self.frames),
+ sound_format=self.sound_format if self.only == 'sound' else None)
+
+
+def validate(options, width, height, frames):
+ """Validate wire values once; the queue passes the immutable result to render."""
+ if not isinstance(options, dict) or set(options) - {'short', 'quality', 'range', 'only', 'sound_format'}:
+ raise ValueError('Invalid export options')
+ if 'short' in options and (type(options['short']) is not int
+ or not 144 <= options['short'] <= 4320 or options['short'] % 2):
+ raise ValueError('Invalid export short side')
+ for key, allowed in (('quality', ('high', 'standard', 'small')), ('only', ('sound',)),
+ ('sound_format', ('m4a', 'wav'))):
+ if key in options and (type(options[key]) is not str or options[key] not in allowed):
+ raise ValueError('Invalid export ' + key)
+ start, count = 0, frames
+ if 'range' in options:
+ span = options['range']
+ if (not isinstance(span, dict) or set(span) != {'start', 'frames'}
+ or type(span['start']) is not int or type(span['frames']) is not int
+ or span['start'] < 0 or span['frames'] < 1 or span['start'] + span['frames'] > frames):
+ raise ValueError('Invalid export range')
+ start, count = span['start'], span['frames']
+ if options.get('only') == 'sound':
+ return ExportOptions(0, 0, start, count, only='sound', sound_format=options.get('sound_format', 'm4a'))
+ output_width, output_height = width, height
+ if 'short' in options:
+ short = options['short']
+ # Nearest even long side, halfway cases up; preserve portrait orientation.
+ long = max(2, 2 * ((max(width, height) * short + min(width, height)) // (2 * min(width, height))))
+ output_width, output_height = (long, short) if width >= height else (short, long)
+ if max(output_width, output_height) > 8192:
+ raise ValueError('Export picture is too large')
+ return ExportOptions(output_width, output_height, start, count, quality=options.get('quality', 'high'))
+
+
+def effective(options, width, height, frames):
+ return options if isinstance(options, ExportOptions) else validate({} if options is None else options, width, height, frames)
+
+
+def audio_lead_start(start, tracks):
+ """Replay active clips from their original start for identical filter history.
+
+ Crossfade extras use independent readers. Envelopes keep timeline positions;
+ only the encoder input is cut. The current base has no continuation chains.
+ """
+ return min([start] + [clip['start'] for track, clips in tracks.items() if track != 'v1'
+ for clip in clips if clip['start'] <= start < clip['start'] + clip['frames']])
+
+
+def frame_tracks(tracks, start, number):
+ return tracks.items() if number >= start else ((key, clips) for key, clips in tracks.items() if key != 'v1')
+
+
+def sound_samples(mixed, options):
+ if options.container != 'wav':
+ return mixed, 'fltp'
+ import numpy as np
+ samples = np.clip(np.rint(mixed.T * 32768), -32768, 32767).astype(np.int16)
+ return np.ascontiguousarray(samples.reshape(1, -1)), 's16'
+
+
+def report_values(report, options):
+ geometry = report['geometry']
+ if (options.only == 'video' and options.quality == 'high' and options.start == 0
+ and (options.width, options.height, options.frames) ==
+ (geometry['width'], geometry['height'], geometry['frames'])):
+ return # Preserve the original default completion marker as well as media.
+ report['geometry'].update(width=options.width, height=options.height,
+ frames=options.frames, seconds=options.frames / 24)
+ if options.only == 'sound':
+ report.pop('video', None)
+ report['audio'] = dict(format=options.sound_format)
+ report['encoding'] = dict(audio_codec=options.audio_codec, sample_rate=48000, channels=2)
+ if options.container == 'wav':
+ report['encoding']['bits_per_sample'] = 16
+ else:
+ report['encoding']['crf'] = int(options.video_options['crf'])
+ report['editor_export'].update(options.status())
+
+
+def result_file(work, options):
+ """Use ComfyUI's existing output media route; audio is not a library video."""
+ path = PurePosixPath('FreeVideo') / work / options.filename
+ return dict(path=path.as_posix(), url='/view?' + urlencode(
+ dict(filename=path.name, subfolder=str(path.parent), type='output')))
diff --git a/freevideo_engine/editor_frames.py b/freevideo_engine/editor_frames.py
new file mode 100644
index 0000000..63fe413
--- /dev/null
+++ b/freevideo_engine/editor_frames.py
@@ -0,0 +1,31 @@
+"""Shared display-time rule for retained previews and original-media exports."""
+from fractions import Fraction
+
+
+def display_frame(frame):
+ """Bake the container's display rotation into pixels (PyAV does not autorotate)."""
+ rotation = frame.rotation % 360
+ if not rotation:
+ return frame
+ import av
+ import numpy as np
+ if rotation % 90 == 0:
+ pixels = np.rot90(frame.to_ndarray(format='rgb24'), rotation // 90)
+ return av.VideoFrame.from_ndarray(np.ascontiguousarray(pixels), format='rgb24')
+ return av.VideoFrame.from_image(frame.to_image().rotate(rotation, expand=True))
+
+
+def frame_not_after(timestamp, number, fps=24):
+ """Whether a decoded source frame may be displayed at timeline frame number.
+
+ Consume every frame satisfying this predicate, including duplicate PTS;
+ keep the last consumed frame until the next one is due.
+ """
+ return timestamp <= Fraction(number, fps)
+
+
+def last_frame_end(timestamp, frame, rate):
+ """Use the decoded last-frame duration; average FPS can be wrong for VFR."""
+ duration = getattr(frame, 'duration', 0)
+ return timestamp + (duration * frame.time_base if duration and frame.time_base
+ else Fraction(1, 1) / rate)
diff --git a/freevideo_engine/editor_picture.py b/freevideo_engine/editor_picture.py
new file mode 100644
index 0000000..d458958
--- /dev/null
+++ b/freevideo_engine/editor_picture.py
@@ -0,0 +1,366 @@
+"""Pure CPU picture placement, shared geometrically with web/editor_geometry.js.
+
+Coordinates are pixel *edges*. ``matrix`` maps original source edges to output
+edges (CSS a,b,c,d,e,f order). Plans contain JSON values only, are safe to mutate,
+and reuse a bounded cache keyed only by normalized picture fields and dimensions.
+No project size, decoder, filesystem, browser, or ComfyUI state is consulted.
+"""
+from copy import deepcopy
+from functools import lru_cache
+import math
+
+def _number(value, default, low, high):
+ if type(value) not in (int, float) or (type(value) is float and math.isnan(value)):
+ return default
+ return min(high, max(low, value))
+
+
+def _dimension(value):
+ if (type(value) not in (int, float) or not 1 <= value <= 2**53 - 1
+ or not math.isfinite(value) or int(value) != value):
+ raise ValueError('Picture dimensions must be positive integers')
+ return int(value)
+
+
+def _fields(clip):
+ clip = clip if isinstance(clip, dict) else {}
+ edges = [_number(clip.get('crop_' + edge), 0, 0, .9)
+ for edge in ('left', 'top', 'right', 'bottom')]
+ for a, b in ((0, 2), (1, 3)):
+ total = edges[a] + edges[b]
+ if total > .9:
+ edges[a], edges[b] = edges[a] * .9 / total, edges[b] * .9 / total
+ return (('contain' if clip.get('fit') == 'contain' else 'cover'), *edges,
+ clip.get('flip_h') is True, clip.get('flip_v') is True,
+ _number(clip.get('rotate'), 0, -180, 180),
+ _number(clip.get('scale'), 1, .1, 10),
+ _number(clip.get('offset_x'), 0, -2, 2),
+ _number(clip.get('offset_y'), 0, -2, 2))
+
+
+def _apply(matrix, point):
+ a, b, c, d, e, f = matrix
+ x, y = point
+ return [a * x + c * y + e, b * x + d * y + f]
+
+
+def _inverse(matrix):
+ return _inverse_cached(tuple(matrix))
+
+
+@lru_cache(maxsize=512)
+def _inverse_cached(matrix):
+ a, b, c, d, e, f = matrix
+ det = a * d - b * c
+ return (d / det, -b / det, -c / det, a / det,
+ (c * f - d * e) / det, (b * e - a * f) / det)
+
+
+def _clip_polygon(polygon, width, height):
+ # Sutherland-Hodgman; keep order identical to the JS implementation.
+ for axis, bound, sign in ((0, 0, 1), (0, width, -1), (1, 0, 1), (1, height, -1)):
+ result = []
+ if not polygon:
+ break
+ previous = polygon[-1]
+ before = sign * (previous[axis] - bound)
+ for point in polygon:
+ after = sign * (point[axis] - bound)
+ if (before >= 0) != (after >= 0):
+ t = before / (before - after)
+ result.append([previous[0] + t * (point[0] - previous[0]),
+ previous[1] + t * (point[1] - previous[1])])
+ if after >= 0:
+ result.append(point)
+ previous, before = point, after
+ polygon = result
+ unique = []
+ for point in polygon:
+ if not unique or max(abs(point[i] - unique[-1][i]) for i in (0, 1)) > 1e-9:
+ unique.append(point)
+ if len(unique) > 1 and max(abs(unique[0][i] - unique[-1][i]) for i in (0, 1)) <= 1e-9:
+ unique.pop()
+ return unique
+
+
+def _area(polygon):
+ if not polygon:
+ return 0
+ return abs(sum(polygon[i - 1][0] * p[1] - polygon[i - 1][1] * p[0]
+ for i, p in enumerate(polygon))) / 2
+
+
+@lru_cache(maxsize=256)
+def _build_plan(fields, sw, sh, width, height):
+ fit, left, top, right, bottom, flip_h, flip_v, angle, scale, ox, oy = fields
+ x, y = min(sw - 1, round(left * sw)), min(sh - 1, round(top * sh))
+ cw = max(1, sw - round(right * sw) - x)
+ ch = max(1, sh - round(bottom * sh) - y)
+ if angle % 90 == 0:
+ cosine, sine = ((1, 0), (0, 1), (-1, 0), (0, -1))[int(angle / 90) % 4]
+ else:
+ radians = angle * math.pi / 180
+ cosine, sine = math.cos(radians), math.sin(radians)
+ rw, rh = abs(cosine) * cw + abs(sine) * ch, abs(sine) * cw + abs(cosine) * ch
+ ratio = (max if fit == 'cover' else min)(width / rw, height / rh)
+ # Preserve legacy rounding only for the unadjusted cover. Adjusted pictures
+ # keep subpixel edges so the same clip scales proportionally across exports.
+ legacy = fields == _fields({})
+ if legacy:
+ dw, dh = max(1, round(rw * ratio)), max(1, round(rh * ratio))
+ dx, dy = -((dw - width) // 2), -((dh - height) // 2)
+ else:
+ dw, dh = rw * ratio * scale, rh * ratio * scale
+ dx, dy = (width - dw) / 2 + ox * width, (height - dh) / 2 + oy * height
+ cx, cy = dx + dw / 2, dy + dh / 2
+ sx, sy = dw / rw, dh / rh
+ fx, fy = -1 if flip_h else 1, -1 if flip_v else 1
+ a, b, c, d = sx * cosine * fx, sy * sine * fx, -sx * sine * fy, sy * cosine * fy
+ matrix = [a, b, c, d, cx - a * (x + cw / 2) - c * (y + ch / 2),
+ cy - b * (x + cw / 2) - d * (y + ch / 2)]
+ if angle % 90 == 0:
+ raster_matrix = [sx, 0, 0, sy, dx, dy]
+ else:
+ ra, rb, rc, rd = sx * cosine, sy * sine, -sx * sine, sy * cosine
+ raster_matrix = [ra, rb, rc, rd, cx - ra * cw / 2 - rc * ch / 2, cy - rb * cw / 2 - rd * ch / 2]
+ corners = [[x, y], [x + cw, y], [x + cw, y + ch], [x, y + ch]]
+ polygon = [_apply(matrix, p) for p in corners]
+ inverse = _inverse(matrix)
+ visible = [_apply(inverse, p) for p in _clip_polygon(polygon, width, height)]
+ # Suppress insignificant numerical excursions outside the crop rectangle.
+ visible = [[min(x + cw, max(x, p[0])), min(y + ch, max(y, p[1]))] for p in visible]
+ output_corners = [[0, 0], [width, 0], [width, height], [0, height]]
+ covers = all(x - 1e-7 <= p[0] <= x + cw + 1e-7 and y - 1e-7 <= p[1] <= y + ch + 1e-7
+ for p in (_apply(inverse, q) for q in output_corners))
+ cropped_fraction = min(1, max(0, 1 - _area(visible) / (sw * sh)))
+ # A one-pixel tolerance for explicit source-edge crops and output overflow.
+ loss = max(x, y, sw - x - cw, sh - y - ch,
+ -min(p[0] for p in polygon), max(p[0] for p in polygon) - width,
+ -min(p[1] for p in polygon), max(p[1] for p in polygon) - height)
+ if visible:
+ vx, vy = min(p[0] for p in visible), min(p[1] for p in visible)
+ vw, vh = max(p[0] for p in visible) - vx, max(p[1] for p in visible) - vy
+ else:
+ vx, vy, vw, vh = x, y, 0, 0
+ return dict(version=1, source=dict(width=sw, height=sh), output=dict(width=width, height=height),
+ fit=fit, crop=dict(x=x, y=y, width=cw, height=ch), flip_h=flip_h, flip_v=flip_v,
+ rotate=angle, rotated=dict(width=rw, height=rh),
+ center=dict(x=cx, y=cy), size=dict(width=dw, height=dh), matrix=matrix,
+ raster_matrix=raster_matrix, legacy=legacy,
+ covers=covers, cropped=loss > 1 + 1e-7, cropped_fraction=cropped_fraction,
+ visible=dict(x=vx, y=vy, width=vw, height=vh, polygon=visible))
+
+
+def plan(clip, source_width, source_height, width, height):
+ """Return an independently mutable JSON plan; at most 256 geometries cached.
+
+ Crop pairs over .9 are reduced proportionally; invalid types/NaN use field
+ defaults, infinities and out-of-range numbers clamp. Dimensions must be
+ positive integers. Unrelated clip fields never invalidate the geometry cache.
+ """
+ dimensions = tuple(_dimension(v) for v in (source_width, source_height, width, height))
+ return deepcopy(_build_plan(_fields(clip), *dimensions))
+
+
+def is_cropped(clip, source_width, source_height, width, height):
+ """Whether a source crop or output-edge overflow exceeds one pixel in depth."""
+ return plan(clip, source_width, source_height, width, height)['cropped']
+
+
+def _resize(pixels, width, height):
+ import av
+ import numpy as np
+ # Do not change the interpolation flag: this is editor_export._VideoReader's
+ # PyAV/libswscale default, including its rounding and RGB conversion behavior.
+ return av.VideoFrame.from_ndarray(np.ascontiguousarray(pixels), format='rgb24').reformat(
+ width=width, height=height, format='rgb24').to_ndarray()
+
+
+def _oriented(pixels, p):
+ import numpy as np
+ crop = p['crop']
+ image = pixels[crop['y']:crop['y'] + crop['height'], crop['x']:crop['x'] + crop['width']]
+ if p['flip_h']:
+ image = image[:, ::-1]
+ if p['flip_v']:
+ image = image[::-1]
+ if p['rotate'] % 90 == 0:
+ image = np.rot90(image, -int(p['rotate'] / 90))
+ return image
+
+
+def _warp(image, width, height, matrix):
+ import numpy as np
+ from PIL import Image
+ inverse = _inverse(matrix)
+ a, b, c, d, e, f = inverse
+ source = Image.fromarray(np.ascontiguousarray(image))
+ return source.transform((width, height), Image.Transform.AFFINE, (a, c, e, b, d, f),
+ resample=Image.Resampling.BILINEAR)
+
+
+@lru_cache(maxsize=16)
+def _coverage_edges(matrix, iw, ih, width, height):
+ """Exact convex-polygon/pixel-square area; only edge pixels need clipping.
+
+ Pillow's affine alpha is a point sample, causing resolution-dependent hard
+ edges. Interior pixels are cheap scanlines; work at edges is O(perimeter).
+ """
+ polygon = _clip_polygon([_apply(matrix, p) for p in ((0, 0), (iw, 0), (iw, ih), (0, ih))], width, height)
+ if len(polygon) < 3:
+ return (), ()
+ edges = list(zip(polygon, polygon[1:] + polygon[:1]))
+ spans, border = [], []
+ # Convex polygon scanline fill at pixel centers, with edge areas below.
+ for y in range(max(0, math.floor(min(p[1] for p in polygon))), min(height, math.ceil(max(p[1] for p in polygon)))):
+ cuts = [p[0] + (y + .5 - p[1]) * (q[0] - p[0]) / (q[1] - p[1])
+ for p, q in edges if min(p[1], q[1]) <= y + .5 < max(p[1], q[1])]
+ if len(cuts) >= 2:
+ start, end = max(0, math.ceil(min(cuts) - .5)), min(width, math.ceil(max(cuts) - .5))
+ spans.append((y, start, end))
+ cells = set()
+ for p, q in edges:
+ # Walk columns for shallow edges, rows for steep edges, never an AABB.
+ axis = 0 if abs(q[0] - p[0]) >= abs(q[1] - p[1]) else 1
+ other = 1 - axis
+ if p[axis] > q[axis]:
+ p, q = q, p
+ span = q[axis] - p[axis]
+ if span < 1e-12:
+ continue
+ for k in range(math.floor(p[axis]), math.floor(q[axis]) + 1):
+ v0 = p[other] + (max(k, p[axis]) - p[axis]) / span * (q[other] - p[other])
+ v1 = p[other] + (min(k + 1, q[axis]) - p[axis]) / span * (q[other] - p[other])
+ for j in range(math.floor(min(v0, v1)), math.floor(max(v0, v1)) + 1):
+ x, y = (k, j) if axis == 0 else (j, k)
+ if 0 <= x < width and 0 <= y < height:
+ cells.add((x, y))
+ for x, y in cells:
+ local = [[p[0] - x, p[1] - y] for p in polygon]
+ border.append((x, y, min(1, _area(_clip_polygon(local, 1, 1)))))
+ return tuple(spans), tuple(border)
+
+
+@lru_cache(maxsize=256)
+def _coverage_axes(a, d, e, f, iw, ih, width, height):
+ import numpy as np
+ xs, ys = np.arange(width), np.arange(height)
+ xcover = np.clip(np.minimum(xs + 1, e + a * iw) - np.maximum(xs, e), 0, 1).astype(np.float32)
+ ycover = np.clip(np.minimum(ys + 1, f + d * ih) - np.maximum(ys, f), 0, 1).astype(np.float32)
+ xcover.flags.writeable = ycover.flags.writeable = False
+ return xcover, ycover
+
+
+def _coverage(matrix, iw, ih, width, height):
+ import numpy as np
+ a, b, c, d, e, f = matrix
+ if b == 0 and c == 0:
+ xcover, ycover = _coverage_axes(a, d, e, f, iw, ih, width, height)
+ return ycover[:, None] * xcover[None, :]
+ spans, border = _coverage_edges(tuple(matrix), iw, ih, width, height)
+ mask = np.zeros((height, width), dtype=np.float32)
+ for y, start, end in spans:
+ mask[y, start:end] = 1
+ for x, y, area in border:
+ mask[y, x] = area
+ return mask
+
+
+def _edge_samples(image, matrix, xs, ys):
+ """Bilinear source colors clamped at edges for partially covered pixels."""
+ import numpy as np
+ a, b, c, d, e, f = _inverse(matrix)
+ u = np.clip(a * (xs + .5) + c * (ys + .5) + e - .5, 0, image.shape[1] - 1)
+ v = np.clip(b * (xs + .5) + d * (ys + .5) + f - .5, 0, image.shape[0] - 1)
+ x0, y0 = u.astype(np.intp), v.astype(np.intp)
+ x1, y1 = np.minimum(x0 + 1, image.shape[1] - 1), np.minimum(y0 + 1, image.shape[0] - 1)
+ fx, fy = (u - x0)[:, None], (v - y0)[:, None]
+ return ((image[y0, x0] * (1 - fx) + image[y0, x1] * fx) * (1 - fy)
+ + (image[y1, x0] * (1 - fx) + image[y1, x1] * fx) * fy)
+
+
+def _background(pixels, p):
+ """A centered, covering copy of steps 1-3; no user scale/offset on the bed.
+
+ Work at quarter width AND height (1080p full-size blur measured >30 ms).
+ For arbitrary rotations, cover the actual opaque rectangle, not its empty
+ bounding-box corners. No artificial black wedges enter the blur.
+ """
+ import numpy as np
+ from PIL import ImageFilter
+ width, height = p['output']['width'], p['output']['height']
+ bw, bh = max(1, math.ceil(width / 4)), max(1, math.ceil(height / 4))
+ image = _oriented(pixels, p)
+ ih, iw = image.shape[:2]
+ if p['rotate'] % 90 == 0:
+ ratio = max(bw / iw, bh / ih)
+ # Viewport sampling keeps memory bounded even for very thin sources.
+ matrix = [ratio, 0, 0, ratio, (bw - iw * ratio) / 2, (bh - ih * ratio) / 2]
+ else:
+ angle = p['rotate'] * math.pi / 180
+ c, s = math.cos(angle), math.sin(angle)
+ ratio = max((abs(c) * bw + abs(s) * bh) / iw,
+ (abs(s) * bw + abs(c) * bh) / ih)
+ a, b, cc, d = ratio * c, ratio * s, -ratio * s, ratio * c
+ matrix = [a, b, cc, d, bw / 2 - a * iw / 2 - cc * ih / 2,
+ bh / 2 - b * iw / 2 - d * ih / 2]
+ bed = _warp(image, bw, bh, matrix)
+ radius = min(width, height) / 20 * min(bw / width, bh / height)
+ bed = bed.filter(ImageFilter.GaussianBlur(radius))
+ # LUT darkens exactly once; a black source remains black by design.
+ # Darken the small image before upsampling to avoid another full-size pass.
+ return _resize(np.asarray(bed.point([round(i * .7) for i in range(256)] * 3)), width, height)
+
+
+def place(pixels, clip, width, height):
+ """Place H×W×3 uint8 RGB pixels; return height×width×3 uint8, without mutation.
+
+ Quarter turns transpose losslessly before resizing. Other angles compose
+ the ordered geometry into one bilinear affine sample to avoid two resamples.
+ A covered output never computes a background. RGB defaults match the old
+ export's reformat/center-crop byte for byte (native YUV decode is upstream).
+ """
+ import numpy as np
+ from PIL import Image
+ if (not isinstance(pixels, np.ndarray) or pixels.ndim != 3 or pixels.shape[2] != 3
+ or not pixels.shape[0] or not pixels.shape[1] or pixels.dtype != np.uint8):
+ raise ValueError('pixels must be a nonempty H×W×3 uint8 RGB array')
+ p = plan(clip, pixels.shape[1], pixels.shape[0], width, height)
+ width, height = p['output']['width'], p['output']['height']
+ dw, dh = p['size']['width'], p['size']['height']
+ dx, dy = p['center']['x'] - dw / 2, p['center']['y'] - dh / 2
+ image = _oriented(pixels, p)
+ quarter = p['rotate'] % 90 == 0
+ # Large user zooms sample just the viewport, avoiding a scale^2 allocation.
+ # The legacy/default path always keeps the original PyAV resize semantics.
+ legacy = p['legacy']
+ integral = all(abs(v - round(v)) < 1e-9 for v in (dw, dh, dx, dy)) and dw >= 1 and dh >= 1
+ if quarter and integral and (dw * dh <= 4 * width * height or legacy):
+ dw, dh, dx, dy = (round(v) for v in (dw, dh, dx, dy))
+ foreground = _resize(image, dw, dh)
+ if p['covers']:
+ return foreground[-dy:height - dy, -dx:width - dx].copy()
+ result = _background(pixels, p)
+ x0, y0, x1, y1 = max(0, dx), max(0, dy), min(width, dx + dw), min(height, dy + dh)
+ if x1 > x0 and y1 > y0:
+ result[y0:y1, x0:x1] = foreground[y0 - dy:y1 - dy, x0 - dx:x1 - dx]
+ return result
+ matrix = p['raster_matrix']
+ if p['covers']:
+ return np.asarray(_warp(image, width, height, matrix)).copy()
+ foreground = np.asarray(_warp(image, width, height, matrix)).copy()
+ mask = _coverage(matrix, image.shape[1], image.shape[0], width, height)
+ ys, xs = np.nonzero((mask > 0) & (mask < 1))
+ foreground[ys, xs] = np.rint(_edge_samples(image, matrix, xs, ys)).astype(np.uint8)
+ background = _background(pixels, p)
+ # Pillow blends in C without several full-size float RGB temporaries. The
+ # alpha quantization is at most half a coverage level (<= .5 RGB level).
+ alpha = Image.fromarray(np.rint(mask * 255).astype(np.uint8))
+ return np.asarray(Image.composite(Image.fromarray(foreground), Image.fromarray(background), alpha)).copy()
+
+
+# Record validation.
+def picture_fit(value):
+ if value not in ('cover', 'contain'):
+ raise ValueError('Invalid picture fit')
+ return value
diff --git a/freevideo_engine/editor_picture_fields.py b/freevideo_engine/editor_picture_fields.py
new file mode 100644
index 0000000..7f5dc57
--- /dev/null
+++ b/freevideo_engine/editor_picture_fields.py
@@ -0,0 +1,10 @@
+"""Sparse project fields using the renderer's authoritative normalization."""
+from .editor_picture import _fields
+
+PICTURE_KEYS = ('fit', 'crop_left', 'crop_top', 'crop_right', 'crop_bottom',
+ 'flip_h', 'flip_v', 'rotate', 'scale', 'offset_x', 'offset_y')
+
+
+def picture_fields(value):
+ return {key: item for key, item, default in zip(PICTURE_KEYS, _fields(value), _fields({}))
+ if item != default}
diff --git a/freevideo_engine/editor_speed.py b/freevideo_engine/editor_speed.py
new file mode 100644
index 0000000..653a489
--- /dev/null
+++ b/freevideo_engine/editor_speed.py
@@ -0,0 +1,488 @@
+"""Integer clip clocks and bounded CPU speed/reverse readers and previews."""
+import asyncio
+import math
+import os
+import threading
+import uuid
+from collections import OrderedDict
+from concurrent.futures import ThreadPoolExecutor
+from contextlib import ExitStack
+from fractions import Fraction
+from decimal import Decimal
+from pathlib import Path
+from urllib.parse import urlencode
+
+FPS = 24
+RATE = 48000
+SAMPLES_PER_FRAME = RATE // FPS
+VIDEO_CACHE_BYTES = 384 * 1024**2
+VIDEO_CACHE_FRAMES = 128
+AUDIO_BLOCK_SAMPLES = 65536
+
+
+def percent(clip):
+ return round(clip.get('speed', 1) * 100)
+
+
+def changed(clip):
+ return clip is not None and (clip.get('speed', 1) != 1 or clip.get('reverse', False))
+
+
+def audio_changed(clip):
+ return changed(clip) or bool(clip.get('speed_phase', 0))
+
+
+def source_span(clip):
+ return ((int(clip['frames']) - 1) * percent(clip) + clip.get('speed_phase', 0)) // 100 + 1
+
+
+def validate_clip(clip, *, error=ValueError):
+ """Call after ordinary range checks; return only explicitly saved fields."""
+ speed, reverse = clip.get('speed', 1), clip.get('reverse', False)
+ if (type(speed) not in (int, float) or not math.isfinite(speed) or not .25 <= speed <= 4
+ or Decimal(str(speed)) * 100 != round(speed * 100)):
+ raise error('Invalid clip speed')
+ if type(reverse) is not bool:
+ raise error('Invalid clip reverse')
+ phase = clip.get('speed_phase', 0)
+ if type(phase) is not int or not 0 <= phase <= 99:
+ raise error('Invalid speed phase')
+ if 'speed_source_frames' in clip and (type(clip['speed_source_frames']) is not int
+ or clip['speed_source_frames'] <= 0):
+ raise error('Invalid speed source frames')
+ if clip.get('speed_audio', 'follow') not in ('follow', 'mute'):
+ raise error('Invalid speed audio')
+ if int(clip['in']) + source_span(clip) > clip['length']:
+ raise error('Invalid clip source span')
+ return {key: clip[key] for key in ('speed', 'reverse', 'speed_phase', 'speed_source_frames', 'speed_audio')
+ if key in clip}
+
+
+def source_frame(clip, local):
+ k = clip['frames'] - 1 - local if clip.get('reverse', False) else local
+ return clip['in'] + (k * percent(clip) + clip.get('speed_phase', 0)) // 100
+
+
+def source_sample_start(clip):
+ return clip['in'] * SAMPLES_PER_FRAME + clip.get('speed_phase', 0) * 20
+
+
+def source_sample_count(clip):
+ # At 48 kHz / 24 fps every integer percentage is an exact sample count.
+ return clip['frames'] * 20 * percent(clip)
+
+
+def tempo_factors(speed):
+ """Use the older FFmpeg atempo range, even on builds accepting larger rates."""
+ rate, factors = Fraction(speed, 100), []
+ while rate < Fraction(1, 2):
+ factors.append(Fraction(1, 2))
+ rate *= 2
+ while rate > 2:
+ factors.append(Fraction(2))
+ rate /= 2
+ if rate != 1:
+ factors.append(rate)
+ return factors
+
+
+def independent_join(left, right):
+ return changed(left) or changed(right)
+
+
+def _file_identity(path):
+ info = path.stat()
+ return info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns, info.st_ctime_ns
+
+
+class VideoReader:
+ """Forward decode once; reverse bounded windows from a backward keyframe seek.
+
+ A long GOP is decoded in several passes. Only the current window's RGB
+ frames are retained, independently of the GOP or clip length.
+ """
+ def __init__(self, path, clip, width, height, cancelled, *, reader_factory=None):
+ from .editor_export import _VideoReader
+ self.factory = reader_factory or _VideoReader
+ self.path, self.clip = path, clip
+ self.width, self.height, self.cancelled = width, height, cancelled
+ self.capacity = max(1, min(VIDEO_CACHE_FRAMES, VIDEO_CACHE_BYTES // (width * height * 3)))
+ self.cache = {}
+ self.peak_cached_frames = self.decode_passes = 0
+ self.reader = None
+ if not clip.get('reverse', False):
+ self.reader = self.factory(path, clip['in'], width, height, cancelled, clip)
+ self.decode_passes = 1
+
+ def pixels(self, number):
+ from .editor_export import _check
+ mapped = source_frame(self.clip, number - self.clip['in'])
+ if self.reader is not None:
+ return self.reader.pixels(mapped)
+ if mapped not in self.cache:
+ self.cache.clear()
+ low = max(self.clip['in'], mapped - self.capacity + 1)
+ reader = self.factory(self.path, low, self.width, self.height, self.cancelled, self.clip)
+ try:
+ self.decode_passes += 1
+ for index in range(low, mapped + 1):
+ _check(self.cancelled)
+ # Copy also detaches a cover crop from its larger backing image.
+ self.cache[index] = reader.pixels(index).copy()
+ self.peak_cached_frames = max(self.peak_cached_frames, len(self.cache))
+ finally:
+ reader.close()
+ return self.cache[mapped]
+
+ def close(self):
+ if self.reader is not None:
+ self.reader.close()
+ self.reader = None
+ self.cache.clear()
+
+
+class AudioReader:
+ """Stream atempo, feeding reverse audio in bounded blocks from the tail."""
+ def __init__(self, path, clip, cancelled):
+ from .editor_export import _audio_start
+ self.path, self.clip, self.cancelled = path, clip, cancelled
+ # Keep the caller's old samples() clock; changed clips ignore splice.
+ self.call_origin = _audio_start(clip)
+ self.chunks = iter(self._chunks())
+ self.chunk = None
+ try:
+ self.chunk = next(self.chunks, None)
+ except BaseException:
+ self.close()
+ raise
+
+ def _input(self):
+ from .editor_export import _AudioReader, _check
+ first = source_sample_start(self.clip)
+ remaining = source_sample_count(self.clip)
+ reader = None
+ try:
+ if not self.clip.get('reverse', False):
+ reader = _AudioReader(self.path, first, self.cancelled)
+ position = first
+ while remaining:
+ _check(self.cancelled)
+ count = min(8192, remaining)
+ yield reader.samples(position, count)
+ remaining -= count
+ position += count
+ else:
+ while remaining:
+ _check(self.cancelled)
+ count = min(AUDIO_BLOCK_SAMPLES, remaining)
+ position = first + remaining - count
+ reader = _AudioReader(self.path, position, self.cancelled)
+ data = reader.samples(position, count)
+ reader.close()
+ reader = None
+ yield data[:, ::-1].copy()
+ remaining -= count
+ finally:
+ if reader is not None:
+ reader.close()
+
+ def _chunks(self):
+ import av
+ import numpy as np
+ from .editor_export import _check
+ graph = None
+ factors = tempo_factors(percent(self.clip))
+ if factors:
+ graph = av.filter.Graph()
+ graph.threads = 1
+ node = graph.add('abuffer', sample_rate=str(RATE), sample_fmt='fltp',
+ channel_layout='stereo', time_base='1/48000')
+ for factor in factors:
+ following = graph.add('atempo', str(float(factor)))
+ node.link_to(following)
+ node = following
+ # atempo may negotiate packed float; readers consume planar stereo.
+ planar = graph.add('aformat', sample_fmts='fltp', sample_rates=str(RATE), channel_layouts='stereo')
+ node.link_to(planar)
+ sink = graph.add('abuffersink')
+ planar.link_to(sink)
+ graph.configure()
+ position, native, accepted = 0, 0, 0
+ tail = np.empty((2, 0), dtype=np.float32)
+ total = self.clip['frames'] * SAMPLES_PER_FRAME
+
+ def emit(output):
+ nonlocal position, accepted, tail
+ kept = min(output.shape[1], total - accepted)
+ if kept:
+ accepted += kept
+ data = np.concatenate((tail, output[:, :kept]), axis=1)
+ count = max(0, data.shape[1] - RATE // 200)
+ tail = data[:, count:].copy()
+ if count:
+ yield position, data[:, :count]
+ position += count
+
+ def pull():
+ while True:
+ _check(self.cancelled)
+ try:
+ yield graph.pull().to_ndarray()
+ except (av.error.BlockingIOError, av.error.EOFError):
+ return
+
+ inputs = self._input()
+ try:
+ for data in inputs:
+ _check(self.cancelled)
+ if graph is None:
+ outputs = (data,)
+ else:
+ frame = av.AudioFrame.from_ndarray(data, format='fltp', layout='stereo')
+ frame.sample_rate, frame.pts, frame.time_base = RATE, native, Fraction(1, RATE)
+ native += data.shape[1]
+ graph.push(frame)
+ outputs = pull()
+ for output in outputs:
+ yield from emit(output)
+ if graph is not None:
+ # A short slow clip may not fill atempo's analysis window.
+ # Supply bounded zero context, without reading beyond its range.
+ frame = av.AudioFrame.from_ndarray(np.zeros((2, 8192), dtype=np.float32),
+ format='fltp', layout='stereo')
+ frame.sample_rate, frame.pts, frame.time_base = RATE, native, Fraction(1, RATE)
+ graph.push(frame)
+ for output in pull():
+ yield from emit(output)
+ graph.push(None)
+ for output in pull():
+ yield from emit(output)
+ # atempo's overlap rounding need not produce the exact timeline count.
+ # Fade a short filter tail before padding, avoiding an early hard cut.
+ # The renderer still applies the exact timeline's ordinary 5 ms fades.
+ if tail.shape[1]:
+ if accepted < total:
+ tail *= np.linspace(1, 0, tail.shape[1], dtype=np.float32)
+ yield position, tail
+ position += tail.shape[1]
+ while position < total:
+ _check(self.cancelled)
+ count = min(8192, total - position)
+ yield position, np.zeros((2, count), dtype=np.float32)
+ position += count
+ finally:
+ inputs.close()
+
+ def samples(self, start, count):
+ from .editor_export import _AudioReader
+ return _AudioReader.samples(self, start - self.call_origin, count)
+
+ def close(self):
+ if self.chunks is not None:
+ self.chunks.close()
+ self.chunk = self.chunks = None
+
+
+def reverse_copy(path, target, cancelled=None):
+ """Reverse the source's 24 fps display grid; encode a browser-playable copy."""
+ import av
+ from .editor_export import _check, _audio_frame, _checked_target
+ from .editor_frames import last_frame_end
+ from .media_encoding import clip_seconds
+ _check(cancelled)
+ _checked_target(path)
+ with av.open(str(path)) as source:
+ vin, ain = next(iter(source.streams.video), None), next(iter(source.streams.audio), None)
+ stream = vin or ain
+ if stream is None:
+ raise ValueError('Unplayable reverse source')
+ seconds = clip_seconds(source, stream)
+ if vin is None and (seconds is None or not math.isfinite(seconds) or seconds <= 0):
+ raise ValueError('Reverse duration unavailable')
+ length = math.ceil(seconds * FPS - 1e-6) if seconds is not None and seconds > 0 else 0
+ width = height = 0
+ if vin is not None:
+ if min(vin.width, vin.height) < 2 or vin.width * vin.height > 64_000_000:
+ raise ValueError('Invalid reverse dimensions')
+ scale = min(1., 720 / min(vin.width, vin.height), 1920 / max(vin.width, vin.height))
+ width, height = (max(2, int(side * scale) // 2 * 2) for side in (vin.width, vin.height))
+ # Some containers report only the last PTS, excluding its duration.
+ # Count the actual display grid with one decoded frame, including VFR.
+ vin.thread_count = 1
+ origin = Fraction(vin.start_time or 0) * vin.time_base
+ end = None
+ rate = vin.average_rate or vin.guessed_rate or FPS
+ for index, frame in enumerate(source.decode(vin)):
+ _check(cancelled)
+ stamp = (Fraction(frame.pts) * frame.time_base - origin if frame.pts is not None
+ else Fraction(index, 1) / rate)
+ end = last_frame_end(stamp, frame, rate)
+ if end is None or end <= 0:
+ raise ValueError('Empty reverse video')
+ length = math.ceil(end * FPS)
+ clip = dict(frames=length, length=length, speed=1, reverse=True, **{'in': 0})
+ partial = target.with_name('.reverse-' + uuid.uuid4().hex + '.mp4')
+ published = complete = False
+ try:
+ _checked_target(target)
+ _checked_target(partial)
+ target.parent.mkdir(parents=True, exist_ok=True)
+ _checked_target(partial)
+ with ExitStack() as readers, av.open(str(partial), 'w', format='mp4',
+ options={'movflags': 'faststart', 'movie_timescale': str(RATE)}) as output:
+ video = audio = pictures = sound = None
+ if width:
+ pictures = VideoReader(path, clip, width, height, cancelled)
+ readers.callback(pictures.close)
+ video = output.add_stream('libx264', rate=FPS)
+ video.width, video.height, video.pix_fmt = width, height, 'yuv420p'
+ video.options = {'crf': '18', 'preset': 'fast'}
+ video.codec_context.thread_count = 2
+ if ain is not None:
+ sound = AudioReader(path, clip, cancelled)
+ readers.callback(sound.close)
+ audio = output.add_stream('aac', rate=RATE)
+ audio.layout = 'stereo'
+ audio.codec_context.time_base = Fraction(1, RATE)
+ audio.codec_context.thread_count = 1
+ for number in range(length):
+ _check(cancelled)
+ if video is not None:
+ frame = av.VideoFrame.from_ndarray(pictures.pixels(number), format='rgb24')
+ frame.pts, frame.time_base = number, Fraction(1, FPS)
+ for packet in video.encode(frame):
+ output.mux(packet)
+ if audio is not None:
+ frame = _audio_frame(sound.samples(number * SAMPLES_PER_FRAME, SAMPLES_PER_FRAME),
+ format='fltp', layout='stereo')
+ frame.sample_rate = RATE
+ frame.pts, frame.time_base = number * SAMPLES_PER_FRAME, Fraction(1, RATE)
+ for packet in audio.encode(frame):
+ output.mux(packet)
+ for stream in (video, audio):
+ if stream is not None:
+ for packet in stream.encode(None):
+ _check(cancelled)
+ output.mux(packet)
+ _check(cancelled)
+ _checked_target(target)
+ _checked_target(partial)
+ os.replace(partial, target)
+ published = True
+ _check(cancelled)
+ complete = True
+ return dict(frames=length, fps=FPS, width=width, height=height,
+ has_video=video is not None, has_audio=audio is not None)
+ finally:
+ partial.unlink(missing_ok=True)
+ if published and not complete:
+ target.unlink(missing_ok=True)
+
+
+class ReverseCache:
+ """One worker per server, deduplicated by _cache's source file identity."""
+ def __init__(self, root):
+ self.root = root
+ self.lock = threading.RLock()
+ self.executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix='editor-reverse')
+ self.pending, self.failed = {}, OrderedDict()
+ self.closed = False
+
+ def _location(self, key):
+ from .comfy_editor import _cache, _import_path, _key, _safe, media_path
+ path = media_path(self.root, key)
+ source = _key(key)
+ if source['kind'] == 'import':
+ # Exports decode the original, rather than the lossy import preview.
+ original = _import_path(self.root, source['id'], 'source.bin')
+ if original.is_file():
+ path = original
+ if not path.is_file():
+ raise FileNotFoundError('Reverse source unavailable')
+ stamp = '24fps-v2:' + ':'.join(map(str, _file_identity(path)))
+ target = _cache(self.root, 'reverse', key, path, stamp).with_suffix('.mp4')
+ return path, _safe(self.root, target.relative_to(Path(self.root).resolve()).as_posix())
+
+ def status(self, key):
+ from .comfy_editor import probe
+ path, target = self._location(key)
+ with self.lock:
+ if self.closed:
+ return dict(state='cancelled', reason='cancelled')
+ if target in self.pending:
+ return dict(state='preparing', poll_after_ms=250)
+ if target.is_file():
+ info = probe(target)
+ address = '/freevideo/editor/reverse?' + urlencode(dict(key=key, file='preview', cache=target.stem))
+ return dict(state='ready', **info, video=address if info['has_video'] else None,
+ audio=address if info['has_audio'] else None)
+ if target in self.failed:
+ return dict(state='failed', reason=self.failed[target])
+ if len(self.pending) >= 64:
+ return dict(state='busy', poll_after_ms=1000)
+ stop = threading.Event()
+ self.pending[target] = stop
+ self.executor.submit(self._make, key, path, target, stop)
+ return dict(state='preparing', poll_after_ms=250)
+
+ def _make(self, key, path, target, stop):
+ from .editor_export import _check, _reason
+ try:
+ identity = _file_identity(path)
+ if (path, target) != self._location(key):
+ raise ValueError('Reverse source changed')
+ reverse_copy(path, target, stop.is_set)
+ _check(stop.is_set)
+ if identity != _file_identity(path) or (path, target) != self._location(key):
+ raise ValueError('Reverse source changed')
+ except BaseException as error:
+ target.unlink(missing_ok=True)
+ with self.lock:
+ self.failed[target] = 'cancelled' if stop.is_set() else _reason(error)
+ while len(self.failed) > 128:
+ self.failed.popitem(last=False)
+ finally:
+ with self.lock:
+ self.pending.pop(target, None)
+
+ def media(self, key, token=None):
+ _, target = self._location(key)
+ with self.lock:
+ if target in self.pending or not target.is_file() or token is not None and token != target.stem:
+ raise FileNotFoundError('Reverse preview unavailable')
+ return target
+
+ def close(self):
+ with self.lock:
+ self.closed = True
+ for stop in self.pending.values():
+ stop.set()
+ # Let queued workers observe cancellation and clean their owned files.
+ self.executor.shutdown(wait=True)
+
+
+def register_reverse(endpoint, root, server):
+ from aiohttp import web
+ from .comfy_editor import probe
+ cache = ReverseCache(root())
+ server._freevideo_editor_reverse = cache
+
+ @endpoint('get', '/freevideo/editor/reverse')
+ async def reverse(request):
+ key = request.query.get('key')
+ if 'file' in request.query:
+ if request.query['file'] != 'preview':
+ raise ValueError('Invalid reverse media')
+ path = await asyncio.to_thread(cache.media, key, request.query.get('cache'))
+ info = await asyncio.to_thread(probe, path)
+ content_type = 'video/mp4' if info['has_video'] else 'audio/mp4'
+ return web.FileResponse(path, headers={'Content-Type': content_type, 'Cache-Control': 'no-store'})
+ value = await asyncio.to_thread(cache.status, key)
+ status = 202 if value['state'] == 'preparing' else 503 if value['state'] == 'busy' else 200
+ return web.json_response(value, status=status, headers={'Cache-Control': 'no-store'})
+
+ async def shutdown(app):
+ await asyncio.to_thread(cache.close)
+
+ if getattr(server, 'app', None) is not None:
+ server.app.on_shutdown.append(shutdown)
diff --git a/freevideo_engine/editor_text.py b/freevideo_engine/editor_text.py
new file mode 100644
index 0000000..0872060
--- /dev/null
+++ b/freevideo_engine/editor_text.py
@@ -0,0 +1,237 @@
+"""Manual text/subtitles: bounded records and pixel-only Pillow compositing.
+
+Only shipped WOFF2s are opened. No subtitle streams, attachments, system font
+lookup, speech recognition or network access. Missing glyph checks use exactly
+web/editor_text_coverage.js, also consumed by the page.
+"""
+from functools import lru_cache
+from bisect import bisect_right
+import hashlib
+import json
+import math
+from pathlib import Path
+import re
+
+TEXT_DEFAULTS = dict(font='sans', size=64/1080, color='#ffffff', backing='outline', bold=True,
+ align='center', x=.5, y=.5, fade=False)
+SUBTITLE_DEFAULTS = dict(font='sans', size=44/1080, color='#ffffff', backing='outline', position='bottom', margin=.08)
+WEB = Path(__file__).resolve().parents[1] / 'web'
+
+
+def is_text_track(track):
+ return isinstance(track, dict) and track.get('kind') in ('text', 'subtitle')
+
+
+def has_text_data(record):
+ return isinstance(record, dict) and ('subtitle_style' in record or isinstance(record.get('tracks'), list)
+ and any(is_text_track(t) for t in record['tracks']))
+
+
+def _check(ok):
+ if not ok:
+ raise ValueError('Invalid text or subtitle')
+
+
+def clean_style(raw, kind='text'):
+ _check(isinstance(raw, dict))
+ base = SUBTITLE_DEFAULTS if kind == 'subtitle' else TEXT_DEFAULTS
+ result = {}
+ for key, value in raw.items():
+ _check(key in base)
+ if key == 'font': _check(value in ('sans', 'serif', 'kai', 'mono'))
+ elif key == 'size': _check(type(value) in (int, float) and math.isfinite(value) and 16/1080 <= value <= 200/1080)
+ elif key == 'color':
+ _check(isinstance(value, str) and re.fullmatch(r'#[0-9a-fA-F]{6}', value)); value = value.lower()
+ elif key == 'backing': _check(value in ('none', 'outline', 'box'))
+ elif key == 'align': _check(value in ('left', 'center', 'right'))
+ elif key == 'position': _check(value in ('top', 'bottom'))
+ elif key in ('bold', 'fade'): _check(type(value) is bool)
+ else: _check(type(value) in (int,float) and math.isfinite(value) and 0 <= value <= 1)
+ if value != base[key]: result[key] = value
+ return result
+
+
+def validate_text_project(raw, validate_media):
+ _check(isinstance(raw.get('tracks'), list) and len(raw['tracks']) <= 5)
+ media = {k:v for k,v in raw.items() if k != 'subtitle_style'}
+ media['tracks'] = [t for t in raw['tracks'] if not is_text_track(t)]
+ result = validate_media(media)
+ ids = {c['id'] for t in result['tracks'] for c in t['clips']}
+ kinds = set()
+ for track in filter(is_text_track, raw['tracks']):
+ kind = track['kind']
+ _check(kind not in kinds and track.get('id') == ('t1' if kind == 'text' else 's1')); kinds.add(kind)
+ _check(isinstance(track.get('clips'), list) and len(track['clips']) <= 500)
+ row = dict(id=track['id'], kind=kind, clips=[])
+ for flag in ('hidden','locked'):
+ _check(flag not in track or type(track[flag]) is bool)
+ if track.get(flag): row[flag] = True
+ end = 0
+ for c in track['clips']:
+ _check(isinstance(c,dict))
+ identity = c.get('id')
+ _check(isinstance(identity,str) and re.fullmatch(r'c[1-9]\d{0,8}', identity) and identity not in ids and int(identity[1:]) <= raw['serial']); ids.add(identity)
+ _check(all(type(c.get(k)) is int and low <= c[k] <= 10**7 for k,low in (('start',0),('frames',1))))
+ _check(c['start'] >= end and c['start']+c['frames'] <= 10**7); end=c['start']+c['frames']
+ _check(c.get('text_kind',kind) == kind)
+ text = c.get('text')
+ _check(isinstance(text,str) and len(text) <= 8000 and not re.search(r'[\x00-\x08\x0b-\x1f\x7f\ud800-\udfff]',text))
+ _check(all(c.get(k) is None for k in ('source','pending','link','part','job','reason')) and c.get('extend',False) is False
+ and ('versions' not in c or isinstance(c['versions'],list) and not c['versions']))
+ _check(type(c.get('in',0)) is int and c.get('in',0) == 0 and type(c.get('length',c['frames'])) is int and c.get('length',c['frames']) == c['frames'])
+ _check(not any(k in c for k in ('volume','fit','splice','target_frames','text_by','ref','take','made_text')))
+ clip = dict(id=identity, start=c['start'], frames=c['frames'], length=c['frames'], source=None,
+ link=None, text=text, part=None, pending=None, reason=None, job=None, extend=False, versions=[], text_kind=kind, **{'in':0})
+ _check(kind != 'subtitle' or 'text_style' not in c)
+ if kind == 'text':
+ style = clean_style(c.get('text_style',{}))
+ if style: clip['text_style'] = style
+ row['clips'].append(clip)
+ if row['clips']: result['tracks'].append(row)
+ style = clean_style(raw.get('subtitle_style',{}),'subtitle')
+ if style and any(t['kind'] == 'subtitle' for t in result['tracks']): result['subtitle_style'] = style
+ result['tracks'].sort(key=lambda t: ['v1','a1','a2','t1','s1'].index(t['id']))
+ return result
+
+
+@lru_cache(maxsize=1)
+def coverage():
+ return json.loads((WEB/'editor_text_coverage.js').read_text().removeprefix('export default ').removesuffix(';\n'))
+
+
+def missing_glyphs(text, font, bold, table):
+ """Pure, stable-order, unique missing characters for this exact face."""
+ ranges = table[font]['700' if bold else '400']['ranges']
+ def contains(cp):
+ index = bisect_right(ranges, [cp, 0x10ffff]) - 1
+ return index >= 0 and cp <= ranges[index][1]
+ return [c for c in dict.fromkeys(text) if c not in '\n\t' and not contains(ord(c))]
+
+
+def style_of(project, clip):
+ subtitle = clip['text_kind'] == 'subtitle'
+ return {**(SUBTITLE_DEFAULTS if subtitle else TEXT_DEFAULTS), **(project.get('subtitle_style',{}) if subtitle else clip.get('text_style',{}))}
+
+
+def missing_project(project):
+ result = []
+ for track in project['tracks']:
+ if not is_text_track(track) or track.get('hidden'): continue
+ for clip in track['clips']:
+ style = style_of(project,clip)
+ chars = missing_glyphs(clip['text'],style['font'],style.get('bold',False),coverage())
+ if chars: result.append(dict(id=clip['id'],chars=chars))
+ return result
+
+
+@lru_cache(maxsize=64)
+def _font(name, bold, size):
+ from PIL import ImageFont
+ entry = coverage()[name]['700' if bold else '400']
+ path = WEB/'fonts'/entry['file']
+ _verify_font(str(path),entry['sha256'])
+ return ImageFont.truetype(str(path), 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')
+
+
+def wrap_text(text, measure, width):
+ lines = []
+ for paragraph in text.replace('\t',' ').split('\n'):
+ line = ''; advance = 0
+ for char in paragraph:
+ amount = measure(char)
+ if line and advance + amount > width:
+ lines.append(line); line = ''; advance = 0
+ line += char; advance += amount
+ lines.append(line)
+ return lines
+
+
+def text_layout(text, style, kind, width, height):
+ size = max(1, math.floor(style['size']*height+.5))
+ font = _font(style['font'],style.get('bold',False),size)
+ measure = lambda c: font.getlength(c)
+ all_lines = wrap_text(text, measure, width*.86)
+ lines = all_lines[:2] if kind == 'subtitle' else all_lines
+ advances = [sum(measure(c) for c in line) for line in lines]
+ boxes = []
+ for line in lines:
+ x = 0; box = None
+ for char in line:
+ b = font.getbbox(char,anchor='ls')
+ if b[2] > b[0] and b[3] > b[1]:
+ b = (b[0]+x,b[1],b[2]+x,b[3])
+ box = b if box is None else (min(box[0],b[0]),min(box[1],b[1]),max(box[2],b[2]),max(box[3],b[3]))
+ x += measure(char)
+ boxes.append(box or (0,-size*.8,0,0))
+ line_height = size*1.2
+ top = min(b[1]+i*line_height for i,b in enumerate(boxes))
+ bottom = max(b[3]+i*line_height for i,b in enumerate(boxes))
+ stroke = max(1,math.floor(size*.06+.5)) if style['backing'] == 'outline' else 0
+ w = max(advances, default=0); h = bottom-top+2*stroke
+ x = width*(style.get('x',.5)) - w/2
+ if kind == 'subtitle':
+ y = height*style['margin'] if style['position'] == 'top' else height*(1-style['margin'])-h
+ else: y=height*style['y']-h/2
+ align=style.get('align','center')
+ positions=[(x+(w-a)*(0 if align == 'left' else 1 if align == 'right' else .5),y+stroke-top+i*line_height) for i,a in enumerate(advances)]
+ return dict(lines=lines, positions=positions, bounds=[x-stroke,y,w+2*stroke,h], over_two=len(all_lines)>2, size=size, stroke=stroke, font=font)
+
+
+def active_text(project, number):
+ result=[]
+ for kind in ('text','subtitle'):
+ for track in project['tracks']:
+ if track['kind'] != kind or track.get('hidden'): continue
+ for clip in track['clips']:
+ if clip['start'] <= number < clip['start']+clip['frames']:
+ style=style_of(project,clip)
+ opacity = min(1,(number-clip['start']+.5)/7.2,(clip['start']+clip['frames']-number-.5)/7.2) if style.get('fade') else 1
+ result.append(dict(clip,style=style,opacity=opacity))
+ return result
+
+
+def paint(pixels, entries, width, height):
+ """Pure RGB -> RGB. No entries returns the original array, byte for byte."""
+ if not entries: return pixels
+ from PIL import Image, ImageDraw
+ import numpy as np
+ result=Image.fromarray(pixels, 'RGB').convert('RGBA')
+ for clip in entries:
+ style=clip['style']; layout=text_layout(clip['text'],style,clip['text_kind'],width,height)
+ layer=Image.new('RGBA',(width,height)); draw=ImageDraw.Draw(layer)
+ x,y,w,h=layout['bounds']; size=layout['size']; opacity=clip.get('opacity',1)
+ if style['backing'] == 'box':
+ draw.rounded_rectangle((x-size*.5,y-size*.15,x+w+size*.5,y+h+size*.15),radius=size*.15,fill=(0,0,0,153))
+ # Per-character placement disables platform-specific kerning and ligatures.
+ # Outline is one translucent black layer; the opaque fill is drawn over it.
+ for line,(x,y) in zip(layout['lines'],layout['positions']):
+ for char in line:
+ if layout['stroke']:
+ draw.text((x,y),char,font=layout['font'],anchor='ls',fill=(0,0,0,217),stroke_width=layout['stroke'],stroke_fill=(0,0,0,217))
+ draw.text((x,y),char,font=layout['font'],anchor='ls',fill=style['color'])
+ x+=layout['font'].getlength(char)
+ if opacity < 1: layer.putalpha(layer.getchannel('A').point(lambda p: round(p*opacity)))
+ result=Image.alpha_composite(result,layer)
+ return np.array(result.convert('RGB'))
+
+
+def paint_project(pixels, project, number, width, height):
+ return paint(pixels,active_text(project,number),width,height)
+
+
+class MissingGlyphs(ValueError):
+ def __init__(self, items):
+ self.items = items
+ super().__init__('Text has missing glyphs')
+
+
+def check_export_text(project):
+ items = missing_project(project)
+ if items:
+ raise MissingGlyphs(items)
diff --git a/freevideo_engine/generate.py b/freevideo_engine/generate.py
index 55b42f6..fed4e8c 100644
--- a/freevideo_engine/generate.py
+++ b/freevideo_engine/generate.py
@@ -715,6 +715,7 @@ def _run(args):
selected_env = inference_environment(engine_env, selected['inference_ram_budget_gb'] * 1e9)
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),
gpu_budget_bytes=round(selected['gpu_budget_gb'] * 1e9),
gpu_reserve_bytes=selected.get('policy', {}).get('gpu_system_reserve_bytes', 0),
capacity_trial=bool(selected.get('policy', {}).get('capacity_trial')),
diff --git a/freevideo_engine/launcher_settings.py b/freevideo_engine/launcher_settings.py
index be5da6a..e765097 100644
--- a/freevideo_engine/launcher_settings.py
+++ b/freevideo_engine/launcher_settings.py
@@ -29,7 +29,7 @@ def default_language():
def sanitize(value):
value = plain_data(value) if isinstance(value, dict) else {}
result = {k: value[k] for k in TEXT if isinstance(value.get(k), str)}
- for key in ('separate', 'new_comfy', 'sampling_caches'):
+ for key in ('separate', 'new_comfy', 'sampling_caches', 'lan_access'):
if type(value.get(key)) is bool:
result[key] = value[key]
if value.get('model_method') in ('auto', 'manual', 'reuse'):
@@ -103,6 +103,11 @@ class Store:
candidates = [value for value in candidates if value]
return max(candidates, key=lambda v: v.get('saved_at_ns', 0)) if candidates else {}
+ def currently_allows(self, key):
+ """Permissions require explicit current copies; recovery preferences cannot grant access."""
+ values = [read(path) for path in self.paths]
+ return bool(values) and all(value.get(key) is True for value in values)
+
def write(self, values, language, selection=None, setup=None):
payload = sanitize(dict(values, language=language, installation=selection,
setup=setup, saved_at_ns=time.time_ns()))
diff --git a/freevideo_engine/licenses/quickjs-MIT.txt b/freevideo_engine/licenses/quickjs-MIT.txt
new file mode 100644
index 0000000..02edabc
--- /dev/null
+++ b/freevideo_engine/licenses/quickjs-MIT.txt
@@ -0,0 +1,47 @@
+QuickJS Python binding 1.19.4
+Author: Petter Strandmark (installed METADATA).
+The following is the verbatim installed dist-info LICENSE, including its copyright line.
+
+The MIT License
+
+Copyright (c) 2010-2019 Google, Inc. http://angularjs.org
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+QuickJS embedded engine
+Copyright (c) 2017-2021 Fabrice Bellard
+Copyright (c) 2017-2021 Charlie Gordon
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/freevideo_engine/licenses/runtime/THIRD_PARTY_NOTICES.txt b/freevideo_engine/licenses/runtime/THIRD_PARTY_NOTICES.txt
index 58f9ed8..7f4d984 100644
--- a/freevideo_engine/licenses/runtime/THIRD_PARTY_NOTICES.txt
+++ b/freevideo_engine/licenses/runtime/THIRD_PARTY_NOTICES.txt
@@ -175,3 +175,8 @@ TinyCC in triton-windows
python/Lib/site-packages/triton/runtime/tcc/lib/user32.def
python/Lib/site-packages/triton/runtime/tcc/libtcc.dll
python/Lib/site-packages/triton/runtime/tcc/tcc.exe
+
+QuickJS Python binding 1.19.4 and embedded QuickJS
+ License: MIT; full notices in ../quickjs-MIT.txt
+ Binding author: Petter Strandmark. Engine copyright: Fabrice Bellard and Charlie Gordon.
+ Files: python/Lib/site-packages/quickjs*, python/Lib/site-packages/_quickjs*
diff --git a/freevideo_engine/macos_encoder.py b/freevideo_engine/macos_encoder.py
index 9f195c3..2805e1b 100644
--- a/freevideo_engine/macos_encoder.py
+++ b/freevideo_engine/macos_encoder.py
@@ -14,7 +14,7 @@ import time
import types
-def nvfp4_weight(weight, dtype, device, *, rows=128):
+def nvfp4_weight(weight, dtype, device, *, rows=128, row_range=None):
"""Decode original E2M1 storage in bounded rows using FP32 scale arithmetic."""
import torch
from comfy_kitchen.float_utils import from_blocked
@@ -26,7 +26,12 @@ def nvfp4_weight(weight, dtype, device, *, rows=128):
count, columns = packed.shape[0], packed.shape[1] * 2
if columns % 16 or params.scale.numel() != 1:
raise ValueError('Invalid NVFP4 scale geometry')
- scales = from_blocked(params.block_scale, num_rows=count, num_cols=columns // 16).float()
+ if row_range is None:
+ scales = from_blocked(params.block_scale, num_rows=count, num_cols=columns // 16).float()
+ else:
+ from .backends.mps_nvfp4 import row_storage
+ packed, scales = row_storage(weight, row_range)
+ count = row_range[1] - row_range[0]
lut = torch.tensor([0., .5, 1., 1.5, 2., 3., 4., 6., -0., -.5, -1., -1.5, -2., -3., -4., -6.])
result = torch.empty((count, columns), dtype=dtype, device=device)
for start in range(0, count, rows):
@@ -37,7 +42,7 @@ def nvfp4_weight(weight, dtype, device, *, rows=128):
decoded.mul_(scales[start:start + rows, :, None]).mul_(params.scale.float())
result[start:start + rows].copy_(decoded.reshape(len(part), columns).to(dtype))
del part, indices, decoded
- return result[:params.orig_shape[0], :params.orig_shape[1]]
+ return result[:count if row_range is not None else params.orig_shape[0], :params.orig_shape[1]]
def install_weight_reader(clip, backend, checkpoint, *, decoder=nvfp4_weight):
@@ -110,6 +115,12 @@ def install_weight_reader(clip, backend, checkpoint, *, decoder=nvfp4_weight):
def progress(module, inputs, output, index=index):
print(json.dumps(dict(event='encoder_layer', completed=index + 1, total=50)), flush=True)
handles.append(layer.register_forward_hook(progress))
+ from .macos_encoder_linear import install
+ stats['projection_slices'], slice_handles = install(
+ [module for module, function in selected if function is linear], model.layers,
+ decoder=decoder, quantized_type=QuantizedTensor, backend=backend,
+ guard=guard, release=lambda: release_mapped_pages([checkpoint]), reader_stats=stats)
+ handles.extend(slice_handles)
return stats, restores, handles
@@ -188,6 +199,9 @@ def encode(prompt, output, *, root, budget_bytes=3 * 2**30, reserve_bytes=2 * 2*
model_options=dict(initial_device=torch.device('cpu'), load_device=torch.device('mps'),
offload_device=torch.device('cpu'), dtype=torch.bfloat16), disable_dynamic=True)
stats, restores, handles = install_weight_reader(clip, backend, checkpoint, decoder=decoder)
+ from .macos_encoder_attention import install
+ stats['attention'], attention_handles = install(clip)
+ handles.extend(attention_handles)
# Placement is handled by the instance reader; native tokenization,
# forward and output packing still execute through the CLIP API.
clip.load_model = lambda tokens: clip.patcher
diff --git a/freevideo_engine/macos_encoder_attention.py b/freevideo_engine/macos_encoder_attention.py
new file mode 100644
index 0000000..bb77e34
--- /dev/null
+++ b/freevideo_engine/macos_encoder_attention.py
@@ -0,0 +1,166 @@
+"""Shape-selected query slices for native FP32 H3 vision and language attention.
+
+Small calls retain the original callable, arguments and stack. Larger calls use
+the same Comfy basic kernel, complete keys and additive mask rows. No allocator
+queries, admission, OOM retries or backend changes take place here.
+"""
+import json
+
+FULL_ATTENTION_MAX_BYTES = 640 * 2**20
+# Additional explicit tensors, not an allocator reservation. The encoder streams
+# one weight at a time; its 2 GiB system reserve is OUTSIDE the 3 GiB MPS cap.
+# 256 MiB is below the tightest observed remaining allowance (~0.29 GiB).
+SLICE_WORKING_BYTES = 256 * 2**20
+
+
+def slice_plan(tokens, heads, dim, kv_heads=None):
+ """Pinned batch-one FP32 contract; include full output and both tile outputs.
+
+ GQA visits one KV head's query heads at a time, with zero-stride KV views.
+ This avoids basic's full repeat_interleave copies (191 MiB at N=3056).
+ The estimate bounds explicit tensors, not opaque Metal kernel workspace.
+ If even one row exceeds the allowance, retain one row and expose the
+ over-budget estimate; do not perform admission or enlarge the allocator cap.
+ """
+ kv_heads = heads if kv_heads is None else kv_heads
+ if min(tokens, heads, dim, kv_heads) < 1 or heads % kv_heads:
+ raise ValueError('Expected positive self-attention dimensions and divisible GQA heads')
+ group_heads = heads if heads == kv_heads else heads // kv_heads
+ groups = heads // group_heads
+ output_bytes = tokens * heads * dim * 4
+ per_row = 2 * group_heads * (tokens + dim) * 4
+ # Even if a whole GQA group fits, large calls still split the query axis.
+ rows = min((tokens + 1) // 2, max(1, (SLICE_WORKING_BYTES - output_bytes) // per_row))
+ return dict(query_rows=rows, head_groups=groups,
+ slice_working_bytes=output_bytes + rows * per_row,
+ minimum_slice_bytes=output_bytes + per_row)
+
+
+def plan(tokens, heads, dim, kv_heads=None):
+ kv_heads = heads if kv_heads is None else kv_heads
+ selected = slice_plan(tokens, heads, dim, kv_heads)
+ full_bytes = heads * tokens * tokens * 4
+ full = full_bytes <= FULL_ATTENTION_MAX_BYTES
+ if full:
+ selected.update(query_rows=tokens, head_groups=1, slice_working_bytes=None)
+ return dict(tokens=tokens, heads=heads, kv_heads=kv_heads, head_dim=dim,
+ batch=1, dtype='torch.float32', full_matrix_bytes=full_bytes,
+ mode='full' if full else 'sliced', **selected)
+
+
+def sliced_basic(q, k, v, heads, rows, basic, *, mask=None, skip_reshape=True, enable_gqa=False):
+ """Native batch-one FP32 self attention, with optional additive causal/pad mask."""
+ import torch
+ if (q.ndim != 4 or k.ndim != 4 or k.shape != v.shape or q.shape[0] != 1
+ or k.shape[0] != 1 or q.shape[1] != heads or q.shape[2:] != k.shape[2:]
+ or heads % k.shape[1] or (k.shape[1] != heads and not enable_gqa)
+ or not skip_reshape or rows < 1
+ or q.dtype != torch.float32 or k.dtype != q.dtype or v.dtype != q.dtype
+ or k.device != q.device or v.device != q.device):
+ raise ValueError('Expected native batch-one FP32 H3 self-attention tensors')
+ if torch.is_grad_enabled():
+ raise RuntimeError('Bounded encoder attention requires inference without gradients')
+ tokens, dim = q.shape[2:]
+ if mask is not None and (mask.dtype != q.dtype or mask.device != q.device
+ or mask.ndim not in (2, 4) or mask.shape[-1] != tokens
+ or mask.shape[-2] not in (1, tokens)
+ or (mask.ndim == 4 and (mask.shape[0] != 1 or mask.shape[1] not in (1, heads)))):
+ raise ValueError('Expected a native additive [N,N] or [1,1|H,1|N,N] mask')
+ output = q.new_empty((1, tokens, heads * dim))
+ kv_heads = k.shape[1]
+ group_heads = heads if kv_heads == heads else heads // kv_heads
+ for start in range(0, tokens, rows):
+ stop = min(tokens, start + rows)
+ row_mask = mask
+ if mask is not None and mask.shape[-2] != 1:
+ row_mask = mask[..., start:stop, :]
+ for head in range(0, heads, group_heads):
+ if kv_heads == heads:
+ keys, values = k, v
+ else:
+ index = head // group_heads
+ # Batch one is important: flattening [1,G,N,D] in basic keeps
+ # these broadcasts as views, rather than allocating repeated KV.
+ keys = k[:, index:index + 1].expand(1, group_heads, tokens, dim)
+ values = v[:, index:index + 1].expand_as(keys)
+ part_mask = row_mask
+ if mask is not None and mask.ndim == 4 and mask.shape[1] == heads:
+ part_mask = row_mask[:, head:head + group_heads]
+ options = dict(skip_reshape=True)
+ if mask is not None:
+ options['mask'] = part_mask
+ part = basic(q[:, head:head + group_heads, start:stop], keys, values,
+ group_heads, **options)
+ output[:, start:stop, head * dim:(head + group_heads) * dim].copy_(part)
+ if q.device.type == 'mps':
+ # Complete pending Metal work before another tile can allocate.
+ torch.mps.synchronize()
+ del part
+ return output
+
+
+def install(clip):
+ """Return shared dispatch statistics and removable instance hooks.
+
+ Counts are attempts/planned basic invocations, not successful completions.
+ Installed for text/audio-only prompts too; no vendor definitions are changed.
+ """
+ from comfy.ldm.modules.attention import attention_basic
+ transformer = clip.cond_stage_model.qwen3vl_32b.transformer
+ vision = [block.attn for block in transformer.visual.blocks]
+ language = [layer.self_attn for layer in transformer.model.layers]
+ if (not vision or not language
+ or any((m.num_heads, m.head_dim) != (16, 72) for m in vision)
+ or any((m.num_heads, m.num_kv_heads, m.head_dim) != (64, 8, 128) for m in language)):
+ raise ValueError('Expected the pinned H3 vision and language attention geometry')
+ stats = dict(full_calls=0, sliced_calls=0, slices=0, plans=[],
+ full_attention_max_bytes=FULL_ATTENTION_MAX_BYTES,
+ slice_working_bytes=SLICE_WORKING_BYTES,
+ kernel='Comfy attention_basic: einsum, scale, additive mask, softmax, einsum; FP32')
+ seen = set()
+
+ def attention(q, k, v, heads, *, mask=None, skip_reshape=False, enable_gqa=False):
+ if q.device.type != 'mps' or not skip_reshape:
+ raise ValueError('Bounded native encoder attention requires MPS and pre-shaped heads')
+ selected = plan(q.shape[2], heads, q.shape[3], k.shape[1])
+ stats['sliced_calls'] += 1
+ stats['slices'] += ((q.shape[2] + selected['query_rows'] - 1) // selected['query_rows']
+ * selected['head_groups'])
+ return sliced_basic(q, k, v, heads, selected['query_rows'], attention_basic,
+ mask=mask, skip_reshape=skip_reshape, enable_gqa=enable_gqa)
+
+ def selector(kind):
+ def select(module, args, kwargs):
+ if kwargs.get('optimized_attention') is not attention_basic:
+ return None
+ x = args[0] if args else kwargs['x' if kind == 'vision' else 'hidden_states']
+ tokens = x.shape[0] if kind == 'vision' else x.shape[1]
+ selected = plan(tokens, module.num_heads, module.head_dim,
+ module.num_heads if kind == 'vision' else module.num_kv_heads)
+ key = (kind, tokens)
+ if key not in seen:
+ seen.add(key)
+ stats['plans'].append(dict(kind=kind, **selected))
+ print(json.dumps(dict(event='encoder_' + kind + '_attention', **selected,
+ kernel=stats['kernel'])), flush=True)
+ if selected['mode'] == 'full':
+ stats['full_calls'] += 1
+ stats['slices'] += 1
+ # Preserve the exact original callable, kwargs and call stack.
+ return None
+ if kind == 'language' and (x.shape[0] != 1 or kwargs.get('past_key_value') is not None):
+ raise ValueError('Expected H3 batch-one conditioning without a KV cache')
+ return args, dict(kwargs, optimized_attention=attention)
+ return select
+
+ handles = []
+ try:
+ for modules, kind in ((vision, 'vision'), (language, 'language')):
+ select = selector(kind)
+ for module in modules:
+ handles.append(module.register_forward_pre_hook(select, with_kwargs=True))
+ except BaseException:
+ for handle in handles:
+ handle.remove()
+ raise
+ return stats, handles
diff --git a/freevideo_engine/macos_encoder_linear.py b/freevideo_engine/macos_encoder_linear.py
new file mode 100644
index 0000000..1995170
--- /dev/null
+++ b/freevideo_engine/macos_encoder_linear.py
@@ -0,0 +1,246 @@
+"""Shape-selected projection and token slices for the native Mac encoder.
+
+No allocator queries or precision changes. The 3 GiB pool's explicit tensor
+ledger reserves <1 GiB for surrounding H3 state, 256 MiB for MLP activations,
+128 MiB for a projection (including its assembled output), and 256 MiB for
+attention. These stages do not all overlap. The remaining space is headroom
+for Metal; it is not a promise about undocumented kernel/driver allocations.
+"""
+import json
+import math
+import time
+import types
+
+FULL_LINEAR_MAX_BYTES = 128 * 2**20
+LINEAR_WORKING_BYTES = 128 * 2**20
+MLP_WORKING_BYTES = 256 * 2**20
+
+
+def linear_plan(tokens, inputs, outputs, itemsize=4, *, packed_columns=None, packed_rows=None):
+ """Bound full output + decoded slab + packed/scales + slab result + bias.
+
+ Packed geometry can include padding on the input axis. A result whose full
+ output alone exceeds the budget still uses one row and reports that minimum
+ explicitly; the parent MLP's token plan avoids this for the H3 workload.
+ """
+ if min(tokens, inputs, outputs, itemsize) < 1:
+ raise ValueError('Expected positive linear dimensions')
+ columns = inputs if packed_columns is None else packed_columns
+ if columns < inputs:
+ raise ValueError('Packed columns cannot be smaller than the input')
+ output = tokens * outputs * itemsize
+ weight = (outputs if packed_rows is None else packed_rows) * columns * itemsize
+ # NVFP4 upload: 1/2 byte per value + FP32 scale per 16 values.
+ upload = 0 if packed_columns is None else columns // 2 + columns // 16 * 4
+ per_row = columns * itemsize + upload + (tokens + 1) * itemsize
+ scale = 4 if packed_columns is not None else 0
+ rows = min(outputs, max(1, (LINEAR_WORKING_BYTES - output - scale) // per_row))
+ full = weight + output <= FULL_LINEAR_MAX_BYTES
+ return dict(tokens=tokens, inputs=inputs, outputs=outputs, itemsize=itemsize,
+ decoded_weight_bytes=weight, output_bytes=output,
+ full_weight_output_bytes=weight + output,
+ mode='full' if full else 'sliced', output_rows=outputs if full else rows,
+ slice_working_bytes=None if full else output + rows * per_row + scale,
+ minimum_slice_bytes=output + per_row + scale)
+
+
+def mlp_plan(tokens, hidden, intermediate, itemsize=4):
+ """Three simultaneous intermediate arrays plus two hidden-sized row arrays.
+
+ The full assembled MLP output stays live across chunks. Linear workspace is
+ counted separately, conservatively counting some output storage twice.
+ """
+ if min(tokens, hidden, intermediate, itemsize) < 1:
+ raise ValueError('Expected positive MLP dimensions')
+ output = tokens * hidden * itemsize
+ per_row = (3 * intermediate + 2 * hidden) * itemsize
+ full = tokens * per_row <= MLP_WORKING_BYTES
+ rows = min(tokens, max(1, (MLP_WORKING_BYTES - output) // per_row))
+ return dict(tokens=tokens, hidden=hidden, intermediate=intermediate, itemsize=itemsize,
+ mode='full' if full else 'sliced', token_rows=tokens if full else rows,
+ full_activation_bytes=tokens * per_row,
+ slice_activation_bytes=None if full else output + rows * per_row,
+ minimum_slice_bytes=output + per_row)
+
+
+def sliced_linear(input, outputs, rows, load_weight, bias=None, *, synchronize=lambda: None,
+ release=lambda: None):
+ """Each output dot product uses ALL input channels; never sum partial dots."""
+ import torch
+ if torch.is_grad_enabled():
+ raise RuntimeError('Bounded encoder linear requires inference without gradients')
+ if rows < 1:
+ raise ValueError('Expected positive output row slice')
+ output = input.new_empty((*input.shape[:-1], outputs))
+ for start in range(0, outputs, rows):
+ stop = min(outputs, start + rows)
+ weight = part = local_bias = None
+ try:
+ weight = load_weight(start, stop)
+ if bias is not None:
+ local_bias = bias[start:stop].to(device=input.device, dtype=input.dtype)
+ part = torch.nn.functional.linear(input, weight, local_bias)
+ output[..., start:stop].copy_(part)
+ synchronize()
+ finally:
+ del weight, part, local_bias
+ release()
+ return output
+
+
+def sliced_mlp(input, rows, original, *, synchronize=lambda: None, release=lambda: None):
+ """Keep the native MLP/AWQ expression and dtype for each token row slice."""
+ import torch
+ if torch.is_grad_enabled():
+ raise RuntimeError('Bounded encoder MLP requires inference without gradients')
+ if input.ndim != 3 or input.shape[0] != 1 or rows < 1:
+ raise ValueError('Expected batch-one H3 MLP input and positive token rows')
+ output = torch.empty_like(input)
+ for start in range(0, input.shape[1], rows):
+ part = None
+ try:
+ part = original(input[:, start:start + rows])
+ output[:, start:start + rows].copy_(part)
+ synchronize()
+ finally:
+ del part
+ release()
+ return output
+
+
+class _Restore:
+ """Also restore an active override if execution aborts before its post hook."""
+ def __init__(self, module, attribute):
+ self.module, self.attribute = module, attribute
+ self.original = module.__dict__.get(attribute)
+
+ def remove(self):
+ if self.original is None:
+ self.module.__dict__.pop(self.attribute, None)
+ else:
+ setattr(self.module, self.attribute, self.original)
+
+
+def install(linears, layers, *, decoder, quantized_type, backend, guard, release, reader_stats):
+ """Select before the native forward looks up its projection/MLP callable.
+
+ Below the thresholds do not assign anything: the fourth-version weight
+ reader and vendor MLP function objects remain intact. MLP selection occurs
+ at the parent layer because Module reads its own forward before pre-hooks.
+ """
+ stats = dict(linear_sliced_calls=0, linear_slices=0, mlp_sliced_calls=0, mlp_slices=0,
+ plans=[], full_linear_max_bytes=FULL_LINEAR_MAX_BYTES,
+ linear_working_bytes=LINEAR_WORKING_BYTES, mlp_working_bytes=MLP_WORKING_BYTES)
+ handles, seen = [], set()
+
+ def record(kind, selected):
+ key = (kind, tuple(selected.values()))
+ if key not in seen:
+ seen.add(key)
+ stats['plans'].append(dict(kind=kind, **selected))
+ print(json.dumps(dict(event='encoder_' + kind + '_slices', **selected)), flush=True)
+
+ def install_linear(module):
+ restore = _Restore(module, 'forward_comfy_cast_weights')
+ active = False
+
+ def before(module, args, kwargs):
+ nonlocal active
+ x = args[0] if args else kwargs['input']
+ quantized = isinstance(module.weight, quantized_type)
+ columns = module.weight._qdata.shape[1] * 2 if quantized else None
+ selected = linear_plan(math.prod(x.shape[:-1]), module.in_features,
+ module.out_features, x.element_size(), packed_columns=columns,
+ packed_rows=module.weight._qdata.shape[0] if quantized else None)
+ record('linear', selected)
+ if selected['mode'] == 'full':
+ return None
+
+ def linear(module, input, *args, **kwargs):
+ import torch
+ if input.device.type != 'mps' or input.dtype != torch.float32:
+ raise ValueError('Native H3 encoder must execute FP32 operations on MPS')
+ guard()
+ source = module.weight
+ if quantized and module.quant_format != 'nvfp4':
+ raise NotImplementedError('Unsupported MPS encoder projection storage: ' + module.quant_format)
+
+ def load(start, stop):
+ tick = time.monotonic()
+ weight = (decoder(source, input.dtype, input.device, row_range=(start, stop))
+ if quantized else source[start:stop].to(device=input.device, dtype=input.dtype))
+ reader_stats['weight_decode_seconds'] += time.monotonic() - tick
+ reader_stats['largest_weight_bytes'] = max(reader_stats['largest_weight_bytes'],
+ weight.untyped_storage().nbytes())
+ stats['linear_slices'] += 1
+ return weight
+
+ def cleanup():
+ backend.empty_cache()
+ release()
+
+ stats['linear_sliced_calls'] += 1
+ result = sliced_linear(input, module.out_features, selected['output_rows'], load,
+ module.bias, synchronize=backend.synchronize, release=cleanup)
+ reader_stats['linear_calls'] += 1
+ return result
+
+ module.forward_comfy_cast_weights = types.MethodType(linear, module)
+ active = True
+
+ def after(module, args, kwargs, output):
+ nonlocal active
+ if active:
+ restore.remove()
+ active = False
+
+ handles.append(restore)
+ handles.append(module.register_forward_pre_hook(before, with_kwargs=True))
+ handles.append(module.register_forward_hook(after, with_kwargs=True, always_call=True))
+
+ def install_mlp(layer):
+ mlp = layer.mlp
+ if getattr(mlp, 'merged_mlp', False):
+ raise ValueError('Expected native H3 separate gate/up projections')
+ original = mlp.forward
+ restore = _Restore(mlp, 'forward')
+ active = False
+
+ def before(module, args, kwargs):
+ nonlocal active
+ x = args[0] if args else kwargs['x']
+ selected = mlp_plan(math.prod(x.shape[:-1]), mlp.down_proj.out_features,
+ mlp.down_proj.in_features, x.element_size())
+ record('mlp', selected)
+ if selected['mode'] == 'full':
+ return None
+
+ def forward(module, input):
+ stats['mlp_sliced_calls'] += 1
+ stats['mlp_slices'] += (input.shape[1] + selected['token_rows'] - 1) // selected['token_rows']
+ return sliced_mlp(input, selected['token_rows'], original,
+ synchronize=backend.synchronize, release=backend.empty_cache)
+
+ mlp.forward = types.MethodType(forward, mlp)
+ active = True
+
+ def after(module, args, kwargs, output):
+ nonlocal active
+ if active:
+ restore.remove()
+ active = False
+
+ handles.append(restore)
+ handles.append(layer.register_forward_pre_hook(before, with_kwargs=True))
+ handles.append(layer.register_forward_hook(after, with_kwargs=True, always_call=True))
+
+ try:
+ for module in linears:
+ install_linear(module)
+ for layer in layers:
+ install_mlp(layer)
+ except BaseException:
+ for handle in handles:
+ handle.remove()
+ raise
+ return stats, handles
diff --git a/freevideo_engine/managed.py b/freevideo_engine/managed.py
index 1ce0c27..a721d82 100644
--- a/freevideo_engine/managed.py
+++ b/freevideo_engine/managed.py
@@ -6,6 +6,7 @@ import os
from pathlib import Path
import sys
+from .agent import enabled as agent_enabled
from .bootstrap import DEFAULT_ROOT
from . import __version__
from .locking import runtime_lock, LOCK_ENV
@@ -64,7 +65,12 @@ def _main(argv=None):
' resource-history Inspect attempts and acknowledged retries\n'
' doctor Check dependencies and GPU kernels\n'
' diagnose Collect a small local report, including failed installs\n'
- ' bench Compare attention backends\n\n'
+ ' bench Compare attention backends\n'
+ + (' agent Drive a running FreeVideo through its agent API (JSON)\n'
+ ' projects Read and edit shared editor timelines (JSON)\n'
+ ' sessions Share work messages and plans with the user (JSON)\n'
+ ' mcp Serve FreeVideo to AI agents over MCP (stdio); --print-config for setup\n'
+ if agent_enabled() else '') + '\n'
'Examples:\n ./freevideo\n ./freevideo server --listen 0.0.0.0\n ./freevideo setup --plan\n'
' ./freevideo test --suite quick\n ./freevideo generate --prompt-file prompt.txt --out video.mp4\n\n'
'Use COMMAND --help for options. Windows: .\\setup.ps1 / .\\test.ps1 / .\\freevideo.ps1; Linux: ./setup.sh / ./test.sh / ./freevideo.')
@@ -81,6 +87,12 @@ def _main(argv=None):
if command == 'diagnose':
from .diagnostics import main as diagnose
return diagnose(['--root', str(args.root), *(['--config', str(args.config)] if args.config else []), *tail])
+ if command in ('agent', 'mcp', 'projects', 'sessions') and agent_enabled():
+ # Clients of the running ComfyUI: no engine lock, no engine environment.
+ from .agent.cli import main as agent
+ from .agent.mcp import main as mcp
+ return (mcp if command == 'mcp' else agent)(['--root', str(args.root),
+ *([command] if command in ('projects', 'sessions') else []), *tail])
if command == 'resource-history':
from .resource_cli import main as history
if not any(flag.split('=', 1)[0] == '--history' for flag in tail):
diff --git a/freevideo_engine/offload.py b/freevideo_engine/offload.py
index c500541..d7d4e3f 100644
--- a/freevideo_engine/offload.py
+++ b/freevideo_engine/offload.py
@@ -432,6 +432,8 @@ class LayerOffloader:
self.prefetch_wait_seconds = 0.
self.direct_read_layers = 0
self.direct_read_bytes = 0
+ self.source_layers = 0
+ self.reader_layers = 0
# The weight source outlives this pass; report only this pass's view hits.
self.host_view_hits_start = getattr(weight_source, 'host_view_hits', 0)
self.host_view_hit_bytes_start = getattr(weight_source, 'host_view_hit_bytes', 0)
@@ -577,6 +579,7 @@ class LayerOffloader:
direct = self.weight_source.stage_into(index, self.layout[index], slot.host)
counts = {}
if not direct:
+ self.reader_layers += 1
with self.weight_source.layer(index, self.layout[index]) as weights:
for _, name, dtype, offset, count, _ in self.layout[index]:
slot.host[dtype][offset:offset + count].copy_(weights[name].reshape(-1))
@@ -700,6 +703,8 @@ class LayerOffloader:
return cached, cached.copy_done
# A previous H2D transfer must finish before the CPU writes this slot.
pinned = self.pinned_layers[index]
+ if not pinned and self.weight_source is not None:
+ self.source_layers += 1
host_slot = slot
staged = self.host_prefetch and not pinned
if slot.copy_done is not None and not pinned and not staged:
@@ -732,6 +737,8 @@ class LayerOffloader:
counts[dtype] = offset + count
self.direct_read_bytes += count * slot.host[dtype].element_size()
else:
+ if self.weight_source is not None and not pinned:
+ self.reader_layers += 1
source = (self.weight_source.layer(index, self.layout[index]) if self.weight_source is not None and not pinned
else nullcontext(self.cpu[index]))
with source as weights:
@@ -803,6 +810,35 @@ class LayerOffloader:
parameter.data = self.cpu[index][name]
self.expected = (index + 1) % len(self.layers)
+ def drive_reads(self):
+ """Layers this pass has read from the weight files so far; None if unknown.
+
+ Pinned groups, cached device copies and adopted views are in memory.
+ A direct-read source counts each layer it reads from its files; a
+ layer staged through its tensor reader is one more. A source that
+ keeps no such count has every staged layer taken as a read. Pageable
+ tensors without a source may be mapped file pages, which the system
+ reads again unseen.
+ """
+ if self.weight_source is None:
+ return 0 if self.pinned_sources else None
+ counted = getattr(self.weight_source, 'read_stats', None)
+ if counted is None:
+ return self.source_layers
+ return self.reader_layers + sum(counted[name] - self.direct_reads_start.get(name, 0)
+ for name in ('kept_layers', 'passed_layers'))
+
+ def drive_layers(self):
+ """Offloaded layers neither pinned nor held as a RAM view; None if unknown.
+
+ Each use of such a layer reads its file unless a device copy is
+ cached, and a cached copy can be released between steps.
+ """
+ if self.weight_source is None:
+ return 0 if self.pinned_sources else None
+ views = getattr(self.weight_source, 'host_views', None) or {}
+ return sum(not pinned and index not in views for index, pinned in enumerate(self.pinned_layers))
+
def stats(self):
self.copy_stream.synchronize()
return {'prefetch': self.prefetch, 'slots': len(self.slots),
diff --git a/freevideo_engine/policy.py b/freevideo_engine/policy.py
index 00b4834..b2bdceb 100644
--- a/freevideo_engine/policy.py
+++ b/freevideo_engine/policy.py
@@ -1477,8 +1477,13 @@ def choose(hardware: Hardware, *, vram_gib=None, ram_gib=None, attention='auto',
# autocast casts to on each call. On an RTX PRO 6000 a 1344x768x243
# decode measured 19.2 s without it and 15.4 s with it, 4.2 GiB lower,
# bit-identical; Hopper and Ampere cast the same way.
+ # Windows Ampere takes the same values, so it uses the cache as well. Its
+ # half-size blocks also let 8 and 12 GB cards keep more of the decoder on
+ # the GPU: at a 7.13 GB limit, 1344x768x243 keeps 27 blocks instead of 13,
+ # and decoded in 15.3 s instead of 24.6 s on the RTX PRO 6000, with peaks
+ # of 4.65 and 4.67 GiB reserved.
decoder_linear_cache = (hardware.system == 'Linux'
- or (hardware.architecture in ('ada', 'blackwell-rtx')
+ or (hardware.architecture in ('ampere', 'ada', 'blackwell-rtx')
and hardware.system == 'Windows'))
# Temporal streaming bounds the live clip workspace, so use spare VRAM for
# the repeatedly-read decoder blocks before spending RAM on host copies. At
diff --git a/freevideo_engine/progress_timeline.py b/freevideo_engine/progress_timeline.py
index bc755be..64b7af7 100644
--- a/freevideo_engine/progress_timeline.py
+++ b/freevideo_engine/progress_timeline.py
@@ -289,7 +289,7 @@ WARNINGS = frozenset((
SEGMENT_KEYS = ('phase', 'stage', 'timing_phase', 'label_key')
ENUMS = dict(phase=PHASES, stage=STAGES, timing_phase=TIMING_PHASES,
label_key=LABEL_KEYS, unit=UNITS, warning=WARNINGS)
-OVERALL_ENUMS = dict(status=STATUSES)
+OVERALL_ENUMS = dict(status=STATUSES, remaining_source=frozenset(('local', 'similar', 'measured', 'other')))
RETRY_ENUMS = dict(kind=RETRY_KINDS, failed_phase=PHASES)
COUNTERS = frozenset(('done', 'total', 'block', 'blocks', 'reference_trimmed'))
FLAGS = frozenset(('low_memory', 'kernel_cache_note', 'estimated', 'new_request', 'reset', 'result'))
@@ -348,7 +348,7 @@ def _fields(value, *, strict=False, nested=None):
(nested is None and (key in COUNTERS or key in FLAGS or key in SECONDS or key in FRACTIONS
or key in ('t', 'bytes_per_second', 'overall', 'retry'))) or
(nested == 'overall' and (key in OVERALL_SECONDS or key in OVERALL_FRACTIONS
- or key in ('estimated', 'sampling_time_weighted'))) or
+ or key in ('estimated', 'sampling_time_weighted', 'at_ceiling'))) or
(nested == 'retry' and key in ('attempt', 'max_attempts', 'reuse_sampling')))
if not known:
# Heartbeat and the bridge's extra overall fields are intentionally omitted.
@@ -369,8 +369,9 @@ def _fields(value, *, strict=False, nested=None):
raise ValueError('Invalid progress mapping')
result[key], count = _fields(raw, strict=strict, nested=key)
errors += count
- elif (nested is None and key in FLAGS) or key in ('estimated', 'reuse_sampling', 'sampling_time_weighted'):
- if (strict or key == 'sampling_time_weighted') and type(raw) is not bool:
+ elif (nested is None and key in FLAGS) or key in ('estimated', 'reuse_sampling', 'sampling_time_weighted',
+ 'at_ceiling'):
+ if (strict or key in ('sampling_time_weighted', 'at_ceiling')) and type(raw) is not bool:
raise ValueError('Invalid progress flag')
result[key] = bool(raw)
elif (nested is None and key in COUNTERS) or key in ('attempt', 'max_attempts'):
diff --git a/freevideo_engine/prompt_vlm/rules.py b/freevideo_engine/prompt_vlm/rules.py
index ffb8d86..7b6c5ce 100644
--- a/freevideo_engine/prompt_vlm/rules.py
+++ b/freevideo_engine/prompt_vlm/rules.py
@@ -290,3 +290,115 @@ def user_text(value):
text += '\n\nSpoken lines to keep verbatim inside <d>[Language] ...</d>:\n' + '\n'.join(
'- [%s] %s' % (language(line), line) for line in lines)
return text
+
+
+ASK_SYSTEM = """You are a precise visual assistant for video production. The user supplies images
+labelled <Image 1>, <Image 2>, etc. in the order given, then a question about them. Answer the
+question directly and concretely from what is actually visible: subjects, faces, clothing,
+colours, setting, framing, camera angle, lighting, motion cues and any visible text. Say plainly
+when something is not visible or cannot be determined from the images; never invent details.
+Answer in the language of the question unless it asks for another language."""
+ASK_JSON = ('Return only one valid JSON value that answers the question. No markdown fences, '
+ 'no commentary before or after it.')
+ASK_JSON_RETRY = ('Your previous reply was not valid JSON. Return only the corrected JSON value, '
+ 'with no markdown fences or commentary.')
+
+
+def ask_request(value):
+ """Questions about images for agents; images are ComfyUI input files."""
+ if not isinstance(value, dict) or set(value) - {'questions', 'format', 'max_tokens', 'system', 'mode'}:
+ raise ValueError('invalid_request')
+ if value.get('mode', 'ask') != 'ask':
+ raise ValueError('invalid_request')
+ questions = value.get('questions')
+ if not isinstance(questions, list) or not 1 <= len(questions) <= 8:
+ raise ValueError('invalid_request')
+ answer_format = value.get('format', 'text')
+ if answer_format not in ('text', 'json'):
+ raise ValueError('invalid_request')
+ max_tokens = value.get('max_tokens', 600)
+ if type(max_tokens) is not int or not 16 <= max_tokens <= 1500:
+ raise ValueError('invalid_request')
+ system = value.get('system')
+ if system is not None and (not isinstance(system, str) or not system.strip() or len(system) > 4000):
+ raise ValueError('invalid_prompt')
+ rows, total = [], 0
+ for question in questions:
+ if not isinstance(question, dict) or set(question) - {'text', 'images'}:
+ raise ValueError('invalid_request')
+ text, images = question.get('text'), question.get('images', [])
+ if not isinstance(text, str) or not text.strip() or len(text) > 8000:
+ raise ValueError('invalid_prompt')
+ if not isinstance(images, list) or len(images) > 16:
+ raise ValueError('too_many_images')
+ selected = []
+ for image in images:
+ if (not isinstance(image, dict) or set(image) - {'file', 'label'}
+ or not isinstance(image.get('file'), str) or not image['file']):
+ raise ValueError('unsupported_media')
+ label = image.get('label')
+ if label is not None and (not isinstance(label, str) or len(label) > 80):
+ raise ValueError('invalid_request')
+ # One line: a label cannot add instructions after its image.
+ label = ' '.join(label.split()) if label else ''
+ selected.append(dict(file=image['file'], **({'label': label} if label else {})))
+ total += len(selected)
+ rows.append(dict(text=text, images=selected))
+ if total > 24:
+ raise ValueError('too_many_images')
+ return dict(mode='ask', questions=rows, format=answer_format, max_tokens=max_tokens,
+ system=system.strip() if system else None)
+
+
+def ask_instruction(value):
+ system = value.get('system') or ASK_SYSTEM
+ return system + ('\n' + ASK_JSON if value['format'] == 'json' else '')
+
+
+def image_tokens(count):
+ """Vision tokens per image, so up to 16 frames fit the input limit."""
+ return max(64, min(512, 4800 // max(1, count)))
+
+
+def parse_json(text):
+ """The JSON value in a reply, tolerating fences or a short preface."""
+ if not isinstance(text, str):
+ raise ValueError('invalid_json')
+ text = text.strip()
+ if text.startswith('```'):
+ lines = text.splitlines()[1:]
+ if lines and lines[-1].strip().startswith('```'):
+ lines = lines[:-1]
+ text = '\n'.join(lines).strip()
+ import json
+ try:
+ return text, json.loads(text)
+ except ValueError:
+ pass
+ starts = [index for index in (text.find('{'), text.find('[')) if index >= 0]
+ if starts:
+ start = min(starts)
+ end = text.rfind('}' if text[start] == '{' else ']')
+ if end > start:
+ try:
+ return text[start:end + 1], json.loads(text[start:end + 1])
+ except ValueError:
+ pass
+ raise ValueError('invalid_json')
+
+
+ANSWER_KEYS = {'text', 'json', 'tokens', 'seconds', 'error', 'truncated', 'retried'}
+
+
+def validate_answers(answers, value):
+ """Worker output shape for an ask job: one answer per question, in order."""
+ if not isinstance(answers, list) or len(answers) != len(value['questions']):
+ raise ValueError('invalid_output')
+ for answer in answers:
+ if not isinstance(answer, dict) or set(answer) - ANSWER_KEYS or not isinstance(answer.get('text', ''), str):
+ raise ValueError('invalid_output')
+ if 'error' not in answer and not answer.get('text', '').strip():
+ raise ValueError('invalid_output')
+ if 'error' in answer and answer['error'] not in ('invalid_json', 'context_length'):
+ raise ValueError('invalid_output')
+ return answers
diff --git a/freevideo_engine/prompt_vlm/service.py b/freevideo_engine/prompt_vlm/service.py
index 90e9250..540be61 100644
--- a/freevideo_engine/prompt_vlm/service.py
+++ b/freevideo_engine/prompt_vlm/service.py
@@ -1,4 +1,4 @@
-"""Optional rewrite jobs; prompts stay in memory and never enter job reports."""
+"""Optional rewrite and ask jobs; prompts, questions and answers stay in memory, never in job reports."""
import atexit
import json
import os
@@ -262,7 +262,7 @@ class Service:
def start(self, action, value):
received_epoch = time.time()
- if action not in ('install', 'rewrite'):
+ if action not in ('install', 'rewrite', 'ask'):
raise ValueError('invalid_request')
if self.busy():
raise ValueError('busy')
@@ -270,6 +270,10 @@ class Service:
if action == 'install':
if value.get('accept_download') is not True:
raise ValueError('consent_required')
+ elif action == 'ask':
+ if not assets.ready(root):
+ raise ValueError('model_missing')
+ value = self.ask_images(rules.ask_request(value))
else:
if not assets.ready(root):
raise ValueError('model_missing')
@@ -286,8 +290,8 @@ class Service:
with self.mutex:
if self.busy():
raise ValueError('busy')
- if action == 'rewrite':
- self.prestart_ticket += 1 # Invalidate pending imports before the rewrite starts.
+ if action in ('rewrite', 'ask'):
+ self.prestart_ticket += 1 # Invalidate pending imports before the worker starts.
self.key = secrets.token_urlsafe(24)
self.stop.clear()
self.result_expires = 0.
@@ -299,12 +303,29 @@ class Service:
self.thread.start()
return dict(job=self.key)
+ def ask_images(self, value):
+ """Resolve every question's images inside ComfyUI input; images only."""
+ from ..comfy_assets import resolve_assets, media_kind
+ rows = [image for question in value['questions'] for image in question['images']]
+ if not rows:
+ return value
+ resolved = resolve_assets(json.dumps([dict(file=row['file'], role='reference') for row in rows]),
+ self.input_directory())
+ paths = iter(row['path'] for row in resolved['references'])
+ for question in value['questions']:
+ for image in question['images']:
+ image['path'] = next(paths)
+ if media_kind(image['path']) != 'image':
+ raise ValueError('unsupported_media')
+ return value
+
def status(self, key):
if not isinstance(key, str) or not self.key or not secrets.compare_digest(key, self.key):
raise ValueError('unknown_job')
with self.mutex:
if self.result_expires and time.monotonic() > self.result_expires:
self.state.pop('text', None)
+ self.state.pop('answers', None)
self.state.update(phase='failed', error='expired')
row = dict(self.state)
# The browser may immediately queue video work or the next rewrite.
@@ -312,6 +333,7 @@ class Service:
if self.busy() and row.get('phase') in ('complete', 'failed', 'cancelled'):
row['phase'] = 'finishing'
row.pop('text', None)
+ row.pop('answers', None)
return row
def cancel(self, key):
@@ -335,7 +357,7 @@ class Service:
try:
from ..background_compile import COMPILE
COMPILE.stop()
- if action == 'rewrite':
+ if action in ('rewrite', 'ask'):
from ..resident_process import OWNER
if OWNER.active:
raise BlockingIOError('busy')
@@ -357,10 +379,11 @@ class Service:
except Exception as error:
known = {'disk_space', 'ram_space', 'rewrite_failed', 'worker_exit', 'timeout', 'worker_cleanup_failed'}
self.progress(dict(phase='failed', error=str(error) if str(error) in known
- else 'download_failed' if action == 'install' else 'rewrite_failed',
+ else 'download_failed' if action == 'install'
+ else 'ask_failed' if action == 'ask' else 'rewrite_failed',
exception=type(error).__name__))
finally:
- if action == 'rewrite':
+ if action in ('rewrite', 'ask'):
self.stop_prestart(self.prewarm_state.get('reason', 'none'))
if self.stop.is_set():
self.progress(dict(phase='cancelled'))
@@ -495,7 +518,7 @@ class Service:
if row.get('phase') in ('complete', 'failed'):
result.update(row)
result_received_at[:] = [time.monotonic()]
- elif row.get('phase') in ('loading', 'rewriting'):
+ elif row.get('phase') in ('loading', 'rewriting', 'answering'):
self.progress(row)
try:
writer.start()
@@ -527,7 +550,10 @@ class Service:
if session.reader.is_alive() or not result or child.returncode and result.get('phase') == 'complete':
raise RuntimeError('worker_exit')
if result.get('phase') == 'complete':
- rules.validate_output(result.get('text'), value)
+ if value.get('mode') == 'ask':
+ rules.validate_answers(result.get('answers'), value)
+ else:
+ rules.validate_output(result.get('text'), value)
self.progress(dict(result, worker_returncode=child.returncode))
finally:
releasing = result_received_at[0] if result_received_at else time.monotonic()
@@ -600,12 +626,14 @@ def register():
if not secrets.compare_digest(request.headers.get('X-FreeVideo-Prompt', ''), token):
return web.json_response(dict(error='reload'), status=403)
try:
- if request.content_length and request.content_length > 128 * 1024:
+ name = request.match_info['action']
+ # Ask jobs carry up to eight questions; rewrite keeps its smaller limit.
+ limit = (512 if name == 'ask' else 128) * 1024
+ if request.content_length and request.content_length > limit:
raise ValueError('invalid_request')
value = await request.json()
if not isinstance(value, dict):
raise ValueError('invalid_request')
- name = request.match_info['action']
if name == 'status':
result = service.status(value.get('job'))
elif name == 'cancel':
diff --git a/freevideo_engine/prompt_vlm/worker.py b/freevideo_engine/prompt_vlm/worker.py
index 15c8b9d..9ba4264 100644
--- a/freevideo_engine/prompt_vlm/worker.py
+++ b/freevideo_engine/prompt_vlm/worker.py
@@ -1,4 +1,4 @@
-"""One rewrite job per process: model, CUDA context and private commit die together."""
+"""One rewrite or ask job per process: model, CUDA context and private commit die together."""
import json
import os
from pathlib import Path
@@ -127,7 +127,8 @@ def failure(error, mode='rewrite'):
"""
allowed = {'ram_space', 'image_size', 'context_length', 'invalid_output'}
message = str(error)
- code = message if message in allowed else 'out_of_memory' if 'out of memory' in message.lower() else 'rewrite_failed'
+ fallback = 'ask_failed' if mode == 'ask' else 'rewrite_failed'
+ code = message if message in allowed else 'out_of_memory' if 'out of memory' in message.lower() else fallback
frames = [dict(module=Path(f.filename).name, function=f.name, line=f.lineno)
for f in traceback.extract_tb(error.__traceback__)]
return dict(error=code, exception=type(error).__name__, error_details=frames)
@@ -195,6 +196,14 @@ def kv_positions(input_tokens):
return input_tokens + 2 * OUTPUT_TOKENS + 256
+def reserved_tokens(stats):
+ """Prompt length to reserve KV space for; a batch of questions runs one at a time."""
+ tokens = stats.get('input_tokens', 6500)
+ if isinstance(tokens, list):
+ tokens = max((t for t in tokens if t <= 6500), default=6500)
+ return tokens
+
+
def kv_bytes(stored, input_tokens):
keys = [row for name, row in stored.items() if name.endswith('self_attn.k_proj.weight')]
per_token = 2 * len(keys) * (keys[0]['shape'][0] if keys else 0) * 2 # K and V, bf16
@@ -240,7 +249,7 @@ def load_model(folder, torch, stats, checkpoint):
# When the layers do not all fit, keep activation/KV space and the
# desktop outside the budget for the layers that stay on the GPU.
weight_budget = min(9 * 2**30, max(0, free - 2 * 2**30))
- kv = kv_bytes(shapes, stats.get('input_tokens', 6500))
+ kv = kv_bytes(shapes, reserved_tokens(stats))
stats.update(gpu_allocator_budget_bytes=free, gpu_weight_budget_bytes=weight_budget, gpu_kv_reserve_bytes=kv)
resident = placement(weights, int8.saved_bytes(shapes), kv, free)
stats['ram_required_bytes'] = RESIDENT_RAM if resident else MAPPED_RAM
@@ -253,7 +262,7 @@ def load_model(folder, torch, stats, checkpoint):
from .load import resident as load_resident
model = load_resident(folder, torch, 'cuda:0', resident)
mapping, device = {'': 0}, 'cuda:0'
- stats.update(weights=resident, kv_positions=kv_positions(stats.get('input_tokens', 6500)))
+ stats.update(weights=resident, kv_positions=kv_positions(reserved_tokens(stats)))
else:
import psutil
from transformers import Qwen3VLForConditionalGeneration
@@ -307,6 +316,8 @@ def generate(torch, model, inputs, max_new_tokens, started, on_token):
def run(folder, value, *, stats=None):
stats = {} if stats is None else stats
+ if value.get('mode') == 'ask':
+ return ask(folder, value, stats)
return rewrite(folder, value, stats)
@@ -373,6 +384,97 @@ def rewrite(folder, value, stats):
emit(phase='complete', text=rewritten, diagnostics=dict(stats))
+def ask(folder, value, stats):
+ """Answer each question with one loaded model; answers leave only via stdout."""
+ from .rules import ask_instruction, image_tokens, parse_json, ASK_JSON_RETRY
+ questions = value['questions']
+ stats.update(stage='imports', pid=os.getpid(), mode='ask', question_count=len(questions),
+ image_count=sum(len(q['images']) for q in questions), format=value['format'],
+ max_tokens=value['max_tokens'], custom_system=bool(value.get('system')),
+ dtype='bfloat16', attention='sdpa', kv_cache='dynamic', backend='transformers',
+ accelerations=[], persistent_model=False)
+ torch, checkpoint = begin(stats)
+ from transformers import AutoProcessor
+ checkpoint('preprocess')
+ preparing = time.monotonic()
+ processor = AutoProcessor.from_pretrained(folder, local_files_only=True, trust_remote_code=False)
+ system = ask_instruction(value)
+ images = {}
+ prepared = []
+ for question in questions:
+ content = []
+ for index, row in enumerate(question['images'], 1):
+ if row['path'] not in images:
+ images[row['path']] = open_image(row['path'])
+ label = f' ({row["label"]})' if row.get('label') else ''
+ content.extend([{'type': 'text', 'text': f'<Image {index}>{label}'},
+ {'type': 'image', 'image': images[row['path']]}])
+ content.append({'type': 'text', 'text': question['text']})
+ messages = [{'role': 'system', 'content': system}, {'role': 'user', 'content': content}]
+ pixels = image_tokens(len(question['images'])) * 32 * 32
+ inputs = tokenize(processor, messages, pixels)
+ prepared.append((messages, pixels, inputs if inputs.input_ids.shape[-1] <= 6500 else None,
+ int(inputs.input_ids.shape[-1])))
+ stats.update(input_tokens=[row[3] for row in prepared], preprocess_seconds=time.monotonic() - preparing)
+ answers = [None] * len(questions)
+ timings = [dict(input_tokens=row[3]) for row in prepared]
+ for index, row in enumerate(prepared):
+ if row[2] is None:
+ answers[index] = dict(error='context_length', text='', tokens=0, seconds=0.)
+ timings[index].update(error='context_length')
+ if all(answer is not None for answer in answers):
+ raise ValueError('context_length')
+ model, device = load_model(folder, torch, stats, checkpoint)
+ loaded = time.monotonic()
+ stats['answer_timings'] = timings
+ checkpoint('prefill', 'answering', answered=0, questions=len(questions))
+ for index, (messages, pixels, inputs, _) in enumerate(prepared):
+ if inputs is None:
+ continue
+ started = time.monotonic()
+ shown = [0.]
+ def on_token(timing):
+ timings[index].update(timing)
+ if time.monotonic() - shown[0] > .5:
+ checkpoint('decode', 'answering', answered=index, questions=len(questions))
+ shown[0] = time.monotonic()
+ ids, _ = generate(torch, model, inputs.to(device), value['max_tokens'], started, on_token)
+ text = processor.decode(ids, skip_special_tokens=True).strip()
+ answer = dict(text=text, tokens=len(ids))
+ if len(ids) >= value['max_tokens']:
+ answer['truncated'] = True
+ if value['format'] == 'json':
+ try:
+ answer['text'], answer['json'] = parse_json(text)
+ except ValueError:
+ # One correction turn with the same images; the model sees its reply.
+ retry = messages + [{'role': 'assistant', 'content': text},
+ {'role': 'user', 'content': ASK_JSON_RETRY}]
+ answer['retried'] = True
+ retry_inputs = tokenize(processor, retry, pixels)
+ if retry_inputs.input_ids.shape[-1] > 6500:
+ answer['error'] = 'invalid_json'
+ else:
+ ids, _ = generate(torch, model, retry_inputs.to(device), value['max_tokens'],
+ time.monotonic(), lambda timing: None)
+ text = processor.decode(ids, skip_special_tokens=True).strip()
+ answer.update(text=text, tokens=answer['tokens'] + len(ids))
+ if len(ids) >= value['max_tokens']:
+ answer['truncated'] = True
+ try:
+ answer['text'], answer['json'] = parse_json(text)
+ except ValueError:
+ answer['error'] = 'invalid_json'
+ answer['seconds'] = time.monotonic() - started
+ answers[index] = answer
+ timings[index].update(seconds=answer['seconds'], output_tokens=answer['tokens'],
+ truncated=bool(answer.get('truncated')), retried=bool(answer.get('retried')),
+ **({'error': answer['error']} if 'error' in answer else {}))
+ checkpoint('decode', 'answering', answered=index + 1, questions=len(questions))
+ stats.update(answer_seconds=time.monotonic() - loaded, stage='complete')
+ emit(phase='complete', answers=answers, diagnostics=dict(stats))
+
+
def main():
stats = {}
value = {}
diff --git a/freevideo_engine/proxy_identity.py b/freevideo_engine/proxy_identity.py
new file mode 100644
index 0000000..a6eb9f1
--- /dev/null
+++ b/freevideo_engine/proxy_identity.py
@@ -0,0 +1,34 @@
+"""Ephemeral identity of the product proxy's hop to the local backend.
+
+The service supplies a fresh secret to its two children, never to arguments,
+settings, receipts or logs. An unconfigured standalone proxy fails closed for
+Agent endpoints. Ordinary forwarding headers never establish trust.
+"""
+import hmac
+from functools import lru_cache
+
+ENV = 'FREEVIDEO_PROXY_HOP_SECRET'
+HEADER = 'X-FreeVideo-Proxy-Hop'
+PEER = 'X-FreeVideo-Proxy-Peer'
+ORIGIN = 'X-FreeVideo-Proxy-Origin'
+
+
+@lru_cache(maxsize=1)
+def app_key():
+ from aiohttp import web
+ return web.AppKey('freevideo_proxy_hop_secret', str)
+
+
+def headers(request, secret):
+ peer = request.transport.get_extra_info('peername') if request.transport else None
+ socket = request.transport.get_extra_info('sockname') if request.transport else None
+ host = ('[%s]' if ':' in socket[0] else '%s') % socket[0] if socket else ''
+ origin = '%s://%s:%d' % (request.scheme, host, socket[1]) if socket else ''
+ return [(HEADER, secret or 'unconfigured'), (PEER, str(peer[0]) if peer else ''), (ORIGIN, origin)]
+
+
+def trusted(request):
+ app = getattr(request, 'app', None)
+ secret = app.get(app_key(), '') if app is not None else ''
+ offered = request.headers.get(HEADER, '')
+ return bool(secret and offered) and hmac.compare_digest(secret.encode(), offered.encode())
diff --git a/freevideo_engine/release_notes.json b/freevideo_engine/release_notes.json
index 804c244..8b17a06 100644
--- a/freevideo_engine/release_notes.json
+++ b/freevideo_engine/release_notes.json
@@ -10,7 +10,7 @@
"On Windows, the first video at the Max quality level, or at some custom step counts, no longer downloads about 26 GB of extra model files.",
"A generation interrupted once no longer slows down later generations. The compatibility level is raised automatically only after two interruptions in a row or a graphics card error, and goes back down after three generations complete normally.",
"Closing FreeVideo during a generation now cancels it instead of counting as an interruption. While the compatibility level is raised automatically, the progress says so and shows how many more completed generations are needed before it speeds up.",
- "The creation panel has a new Available sizes and lengths row under Frame & duration. It opens a map of the picture sizes and lengths that can be generated; hovering shows the estimated time, and clicking fills in the size and length. Not shown on Mac."
+ "The creation panel has a new Available sizes and lengths row under Frame & duration. It opens a map of the picture sizes and lengths that can be generated; hovering shows the estimated time, and clicking fills in the size and length."
]
},
"zh": {
@@ -22,7 +22,7 @@
"在 Windows 上第一次用“极致”档(以及部分自定义步数)生成时,不再额外下载约 26 GB 的模型文件。",
"生成被意外中断一次后,之后的生成不再因此变慢:只有连续两次中断或显卡报错,才会自动提高兼容档位;之后连续三次正常完成,档位会自动调回。",
"生成过程中关掉 FreeVideo,现在会取消这次生成,不算作中断;兼容档位被自动提高时,生成进度上会说明这一点,并显示再完成几次后会加快。",
- "创作面板“画幅与时长”下面新增“可生成范围”:展开是一张图,显示可以生成的画面大小和时长;鼠标移到图上会显示预计用时,点击图中的位置会填入对应的大小和时长。Mac 上不显示。"
+ "创作面板“画幅与时长”下面新增“可生成范围”:展开是一张图,显示可以生成的画面大小和时长;鼠标移到图上会显示预计用时,点击图中的位置会填入对应的大小和时长。"
]
},
"history": [
diff --git a/freevideo_engine/runtime.py b/freevideo_engine/runtime.py
index 1ad0f92..fb04071 100644
--- a/freevideo_engine/runtime.py
+++ b/freevideo_engine/runtime.py
@@ -602,7 +602,16 @@ class Engine:
prefetch_step = max(1, active_steps - 2)
prefetch_timing = dict(trigger_step=None, steps_remaining=None,
estimated_remaining_seconds=None,
- trigger_elapsed_seconds=None)
+ trigger_elapsed_seconds=None,
+ drive_reads_last_step=None, drive_layers=None)
+ # Layers the step just completed read from the weight files, and
+ # offloaded layers that still depend on those files; both unknown
+ # until this pass completes a step. Sampling leaves the drive to the
+ # reader only when both are zero: a layer served by a cached device
+ # copy goes back to its file once that copy is released.
+ self.step_drive_reads = self.drive_layers = None
+ self.drive_idle = False
+ drive_reads = [0]
def trigger_prefetch():
if final_step_callback is None or prefetch_timing['trigger_step'] is not None:
@@ -616,12 +625,19 @@ class Engine:
steps_remaining=remaining,
estimated_remaining_seconds=(average * remaining
if average is not None else None),
- trigger_elapsed_seconds=time.perf_counter() - started)
+ trigger_elapsed_seconds=time.perf_counter() - started,
+ drive_reads_last_step=self.step_drive_reads, drive_layers=self.drive_layers)
final_step_callback()
class StepTimes(list):
def append(self, value):
super().append(value)
+ count = getattr(offloader, 'drive_reads', None)
+ total = count() if count is not None else None
+ if total is None:
+ owner.step_drive_reads = None
+ else:
+ owner.step_drive_reads, drive_reads[0] = total - drive_reads[0], total
cached = offloader.cached_bytes() if budget_refresh is not None else 0
peak = owner.device_backend.max_memory_reserved()
if budget_refresh is not None:
@@ -678,6 +694,10 @@ class Engine:
allow_growth=len(self) + 1 < active_steps)
if owner.config.get('residual_offload'):
residual_steps.append(dict(owner.transformer._freevideo_residual_stats))
+ # After the cache changes above: what the remaining steps need.
+ waiting = getattr(offloader, 'drive_layers', None)
+ owner.drive_layers = waiting() if waiting is not None else None
+ owner.drive_idle = owner.step_drive_reads == 0 and owner.drive_layers == 0
progress.complete(value)
if step_callback is not None:
step_callback(value)
diff --git a/freevideo_engine/support_report.py b/freevideo_engine/support_report.py
index 244655e..87b21c1 100644
--- a/freevideo_engine/support_report.py
+++ b/freevideo_engine/support_report.py
@@ -45,6 +45,7 @@ def code_identity():
'backends/mps_delta.py', 'backends/mps_features.py', 'backends/mps_qk.py',
'backends/mps_mlx_attention.py', 'backends/mps_vae_encode.py', 'backends/mps_modulation.py',
'macos_compute.py', 'macos_decode_tiles.py',
+ 'macos_encoder_attention.py', 'macos_encoder_linear.py',
'macos_memory.py', 'macos_conditions.py', 'macos_process_memory.py',
'attention.py', 'refine.py', 'reference_sampler.py', 'adaln.py', 'latent_upscale.py',
'media_encoding.py', 'media_conditioning.py', 'encoder_checkpoint.py', 'system.py')
diff --git a/freevideo_engine/two_pass.py b/freevideo_engine/two_pass.py
index dc94171..67435be 100644
--- a/freevideo_engine/two_pass.py
+++ b/freevideo_engine/two_pass.py
@@ -128,10 +128,45 @@ def checkpoint_path():
return earlier if earlier.is_file() and not installed.is_file() else installed
+def verified_checkpoint(path):
+ """Whether setup's ledger of verified models covers this copy, unchanged since.
+
+ Every two-pass request used to hash the whole checkpoint before sampling:
+ one more full read of the file, which the upscaler then read again. The
+ ledger keeps the identity of each file whose content was hashed; a copy
+ it does not know yet is hashed once here and recorded. An unreadable
+ ledger is left alone and the caller hashes as before.
+ """
+ from .paths import data_root
+ import json
+ ledger = data_root() / 'verified-models.json'
+ try:
+ stamps = json.loads(ledger.read_text(encoding='utf-8')) if ledger.is_file() else {}
+ except (OSError, ValueError):
+ return False
+ if not isinstance(stamps, dict):
+ return False
+ from . import provision
+ # Setup records a file under its resolved folder and its own name.
+ try:
+ key = path.parent.resolve() / path.name
+ recorded = stamps.get(str(key))
+ if not provision.verified(key, dict(bytes=UPSCALER['bytes'], sha256=UPSCALER['sha256']), stamps):
+ return False
+ if stamps.get(str(key)) != recorded:
+ from .monitoring import save
+ save(ledger, stamps)
+ except OSError:
+ return False
+ return True
+
+
def ensure_checkpoint():
"""Also upgrade existing installations lazily; retain invalid local files."""
from .network import download, model_urls
path = checkpoint_path()
+ if verified_checkpoint(path):
+ return path
network = {}
from .paths import data_root
import json
diff --git a/freevideo_engine/worker.py b/freevideo_engine/worker.py
index 2d0bdaa..da00c2e 100644
--- a/freevideo_engine/worker.py
+++ b/freevideo_engine/worker.py
@@ -203,10 +203,14 @@ def generate(request, resident=None):
from .resident_models import gpu_bytes
foreign_sample_bytes = max(0, torch.cuda.memory_allocated() - gpu_bytes(engine))
from .decode_prefetch import DecoderReadAhead
- decode_read_ahead = DecoderReadAhead(engine.base, ram_budget_bytes=request.get('ram_budget_bytes'))
+ decode_read_ahead = DecoderReadAhead(engine.base, ram_budget_bytes=request.get('ram_budget_bytes'),
+ budget_is_estimate=request.get('ram_budget_is_estimate') is True)
decoder_cached = resident is not None and 'video_vae' in resident.entries
if decoder_cached:
decode_read_ahead.result.update(state='skipped', reason='Video VAE is already resident on the GPU')
+ def read_decoder_ahead():
+ # Every offloaded layer in memory and none read in the last step.
+ decode_read_ahead.start(drive_idle=getattr(engine, 'drive_idle', False) is True)
from .sampling_memory import SamplingMemory
memory_diagnostics = SamplingMemory(torch, Path(request['output']).with_suffix('.sampling-memory.json')).start()
def sample_finalize_phase(name):
@@ -402,7 +406,7 @@ def generate(request, resident=None):
sampled = dict(first, sampling_plan=sampling_plan, sampling_passes=[dict(first)],
step_seconds=list(first['step_seconds']), sample_seconds=first['sample_seconds'])
if not decoder_cached:
- decode_read_ahead.start()
+ read_decoder_ahead()
else:
metrics['sample_stage'] = 'refine'
save(request['metrics'], metrics)
@@ -420,7 +424,7 @@ def generate(request, resident=None):
latents, audio, second = engine.sample(request['conditioning'], restart_seed,
**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 decode_read_ahead.start,
+ final_step_callback=None if decoder_cached else read_decoder_ahead,
step_callback=memory_diagnostics.complete, sampling_complete_callback=refined_complete,
progress_offset=sampling_plan['base_steps'], progress_total=sampling_plan['total_steps'],
gpu_reserve_bytes=request.get('gpu_reserve_bytes', 0),
@@ -430,7 +434,7 @@ def generate(request, resident=None):
else:
latents, audio, sampled = engine.sample(request['conditioning'], request['seed'],
frames=canvas.get('frames', 243), width=canvas.get('width', 1344), height=canvas.get('height', 768),
- final_step_callback=None if decoder_cached else decode_read_ahead.start,
+ final_step_callback=None if decoder_cached else read_decoder_ahead,
step_callback=memory_diagnostics.complete, sampling_complete_callback=sampling_complete,
gpu_reserve_bytes=request.get('gpu_reserve_bytes', 0),
budget_refresh=refresh_budget if live_budget is not None else None)
diff --git a/pyproject.toml b/pyproject.toml
index 74c62c1..0eea88c 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -9,7 +9,7 @@ description = "FreeVideo video and audio generation with automatic GPU and memor
requires-python = ">=3.12,<3.13"
readme = "README.md"
license = "Apache-2.0"
-dependencies = ["psutil>=6", "safetensors>=0.8.0", "numpy>=2", "pillow>=11", "av>=14"]
+dependencies = ["psutil>=6", "safetensors>=0.8.0", "numpy>=2", "pillow>=11", "av>=14", "quickjs==1.19.4"]
[project.optional-dependencies]
launcher = ["PySide6-Essentials==6.11.2"]
@@ -19,7 +19,7 @@ runtime = [
"transformers==5.15.0", "accelerate==1.14.0", "peft==0.20.0",
"safetensors==0.8.0", "huggingface_hub==1.30.0", "hf-xet==1.6.1a0",
"omegaconf==2.3.1", "pyyaml==6.0.3", "einops==0.8.2",
- "numpy==2.5.2", "pillow==12.3.0", "av==18.1.0", "tqdm",
+ "numpy==2.5.2", "pillow==12.3.0", "av==18.1.0", "quickjs==1.19.4", "tqdm",
"importlib_metadata>=8", "requests[socks]>=2.32", "httpx[socks]>=0.28",
"modelscope-hub==0.4.2"
]
diff --git a/scripts/test_freevideo_entry.mjs b/scripts/test_freevideo_entry.mjs
index fd77dc8..bede18c 100644
--- a/scripts/test_freevideo_entry.mjs
+++ b/scripts/test_freevideo_entry.mjs
@@ -3,6 +3,7 @@ import {readFile} from 'node:fs/promises';
import test from 'node:test';
import {outputDownloadURL} from '../web/output_download.js';
import {regenerateResult, upscaleResult} from '../web/studio_queue.js';
+import {referenceInputs} from '../web/prompt_references.js';
class Element {
constructor(tag) {
@@ -24,7 +25,7 @@ class Element {
test('main browser entry registers both views and preserves node hooks', async t => {
const extensions = [], opened = [], installed = [], events = new EventTarget();
- let refreshed = 0, compatibilityChecks = 0, updateChecks = 0;
+ let refreshed = 0, compatibilityChecks = 0, updateChecks = 0, rememberedView = null;
let progressView, progressOptions, realProgressFactory;
const app = {
registerExtension(extension) { extensions.push(extension); },
@@ -33,7 +34,7 @@ test('main browser entry registers both views and preserves node hooks', async t
const api = Object.assign(events, {apiURL: value => value});
const document = {head: new Element('head'), createElement: tag => new Element(tag)};
const dependencies = {
- app, api, outputDownloadURL, regenerateResult, upscaleResult,
+ app, api, outputDownloadURL, regenerateResult, upscaleResult, referenceInputs,
createErrorPanel: () => ({element: new Element('error'), show() {}, clear() {}}),
errorText: value => String(value),
openStudio: node => opened.push(node),
@@ -58,7 +59,7 @@ test('main browser entry registers both views and preserves node hooks', async t
notifyCompatibility: async () => { compatibilityChecks++; },
startUpdateChecks: () => { updateChecks++; },
installNavigation: callback => installed.push(callback),
- refreshNavigation: () => refreshed++, preferredView: () => null,
+ refreshNavigation: () => refreshed++, preferredView: () => rememberedView,
attachReferencePicker() {}, referenceItems: () => [], syncReferencePrompt() {},
shareButton: () => new Element('button'), reportFileName: () => 'FreeVideo-report-20261008-101530.json',
rememberPromptDraft() {}, savePromptDraft: async () => false, openImageEditor: async () => null, icon: () => '',
@@ -75,6 +76,7 @@ test('main browser entry registers both views and preserves node hooks', async t
}
try {
let source = await readFile(new URL('../web/freevideo.js', import.meta.url), 'utf8');
+ source = source.replace("import { openEditorView } from './editor_entry.js';", 'const openEditorView = (...args) => globalThis.__freevideoEntryTest.openEditorView?.(...args);');
source = source
.replace("import { createErrorPanel, errorText } from './error_panel.js';", 'const {createErrorPanel,errorText} = globalThis.__freevideoEntryTest;')
.replace('import { app } from "../../scripts/app.js";', 'const {app} = globalThis.__freevideoEntryTest;')
@@ -84,7 +86,7 @@ test('main browser entry registers both views and preserves node hooks', async t
.replace("import { createProgressConnection } from './progress_connection.js';", 'const {createProgressConnection} = globalThis.__freevideoEntryTest;')
.replace("import { notifyCompatibility } from './compatibility.js';", 'const {notifyCompatibility} = globalThis.__freevideoEntryTest;')
.replace("import { startUpdateChecks } from './updates.js';", 'const {startUpdateChecks} = globalThis.__freevideoEntryTest;')
- .replace("import { attachReferencePicker, referenceItems, syncReferencePrompt } from './prompt_references.js';", 'const {attachReferencePicker,referenceItems,syncReferencePrompt} = globalThis.__freevideoEntryTest;')
+ .replace("import { attachReferencePicker, referenceItems, syncReferencePrompt, referenceInputs } from './prompt_references.js';", 'const {attachReferencePicker,referenceItems,syncReferencePrompt,referenceInputs} = globalThis.__freevideoEntryTest;')
.replace("import { outputDownloadURL } from './output_download.js';", 'const {outputDownloadURL} = globalThis.__freevideoEntryTest;')
.replace("import { shareButton } from './share.js';", 'const {shareButton} = globalThis.__freevideoEntryTest;')
.replace("import { reportFileName } from './report_issue.js';", 'const {reportFileName} = globalThis.__freevideoEntryTest;')
@@ -137,6 +139,21 @@ test('main browser entry registers both views and preserves node hooks', async t
node.buttons[0].callback();
extension.afterConfigureGraph();
assert.deepEqual(opened, [node, node]);
+ rememberedView = 'editor';
+ const restored = [];
+ dependencies.openEditorView = (value, options) => restored.push({node:value, studio:options.studio});
+ extension.afterConfigureGraph();
+ assert.equal(restored[0].node, node);
+ assert.ok(restored[0].studio, 'restore opens the studio before the editor');
+ dependencies.openEditorView = () => { throw new Error('editor unavailable'); };
+ const oldError = console.error; console.error = () => {};
+ try { extension.afterConfigureGraph(); } finally { console.error = oldError; }
+ assert.equal(opened.at(-1), node, 'editor failure leaves the restored studio available');
+ assert.ok(window.__freevideoHealth.some(row => row.where === 'editor'));
+ rememberedView = 'nodes';
+ const count = opened.length; extension.afterConfigureGraph();
+ assert.equal(opened.length, count, 'remembered Nodes does not open either dialog');
+ rememberedView = null;
assert.ok(refreshed >= 2);
node.freevideoShowProgress({phase: 'load'});
// A node already tall enough lays its widgets out again, so the panel grows.
@@ -279,9 +296,9 @@ test('main browser entry registers both views and preserves node hooks', async t
await audioPicker.onchange();
assert.deepEqual(JSON.parse(media.widgets[0].value), [{file: 'voice.wav', role: 'reference', enabled: true}]);
assert.equal(media.isUploading, false);
- media.inputs = [{name: 'first', link: 1}]; media.onConnectionsChange();
+ media.inputs = [{name: 'first', link: 1}]; media.onConnectionsChange(); await Promise.resolve();
assert.match(note.textContent, /Choose keyframes or references/);
- media.widgets[0].value = '[]'; media.inputs = []; media.onConnectionsChange();
+ media.widgets[0].value = '[]'; media.inputs = []; media.onConnectionsChange(); await Promise.resolve();
assert.equal(audioHelp.hidden, true);
assert.match(mode.textContent, /Text to video/);
const imageRole = toolbar.children.find(e => e.tag === 'select');
diff --git a/web/agent_activity.css b/web/agent_activity.css
new file mode 100644
index 0000000..ee777e9
--- /dev/null
+++ b/web/agent_activity.css
@@ -0,0 +1,50 @@
+/* Agent activity: a quiet header pill, and a sheet listing the agents' jobs. */
+.fv-studio .fv-agent-pill,.fv-agent-pill{min-height:0;display:inline-flex;align-items:center;gap:8px;height:var(--fv-h-sm);padding:0 12px 0 10px;border:1px solid var(--fv-border);border-radius:999px;background:var(--fv-card);color:var(--fv-ink);font:inherit;font-size:var(--fv-micro);font-weight:var(--fv-medium);white-space:nowrap;cursor:pointer;transition:background var(--fv-quick) var(--fv-ease),border-color var(--fv-quick) var(--fv-ease)}
+.fv-studio .fv-agent-pill:hover{background:var(--fv-hover);border-color:var(--fv-sheen)}
+.fv-studio .fv-agent-pill[aria-expanded=true]{background:var(--fv-selected);border-color:var(--fv-accent-dim)}
+.fv-agent-pill[hidden]{display:none}
+.fv-agent-dot{width:8px;height:8px;border-radius:50%;background:var(--fv-muted);flex:none}
+.fv-agent-pill[data-state=running] .fv-agent-dot{background:var(--fv-accent);box-shadow:0 0 0 0 color-mix(in srgb,var(--fv-accent) 60%,transparent);animation:fv-agent-pulse 1.6s var(--fv-ease-out) infinite}
+.fv-agent-pill[data-state=waiting] .fv-agent-dot{background:var(--fv-warning)}
+.fv-agent-pill[data-state=done] .fv-agent-dot{background:var(--fv-success)}
+.fv-agent-pill[data-state=failed] .fv-agent-dot{background:var(--fv-danger)}
+.fv-agent-label{font-variant-numeric:tabular-nums}
+@keyframes fv-agent-pulse{70%{box-shadow:0 0 0 7px transparent}100%{box-shadow:0 0 0 0 transparent}}
+@media (prefers-reduced-motion:reduce){.fv-agent-pill[data-state=running] .fv-agent-dot{animation:none}}
+
+.fv-agent-panel{position:absolute;z-index:20;top:72px;right:24px;width:min(400px,calc(100% - 32px));max-height:min(560px,calc(100% - 96px));display:flex;flex-direction:column;background:var(--fv-raised);border:1px solid var(--fv-border);border-radius:var(--fv-r-md);box-shadow:0 18px 48px rgb(0 0 0/.45);color:var(--fv-ink);overflow:hidden;animation:fv-agent-in var(--fv-base) var(--fv-ease-out)}
+.fv-agent-panel[hidden]{display:none}
+@keyframes fv-agent-in{from{opacity:0;transform:translateY(-6px)}}
+.fv-agent-panel header{padding:16px 18px 12px;border-bottom:1px solid var(--fv-border)}
+.fv-agent-panel h2{margin:0;font-size:var(--fv-strong);font-weight:var(--fv-semibold)}
+.fv-agent-panel header p{margin:6px 0 0;font-size:var(--fv-micro);line-height:1.5;color:var(--fv-muted);text-wrap:balance}
+.fv-agent-panel ol{list-style:none;margin:0;padding:6px;overflow:auto;display:grid;gap:2px}
+.fv-agent-job{display:grid;grid-template-columns:20px minmax(0,1fr);gap:12px;padding:12px;border-radius:var(--fv-r-sm)}
+.fv-agent-job:hover{background:var(--fv-hover)}
+.fv-agent-glyph{width:20px;height:20px;margin-top:1px;fill:none;stroke:var(--fv-muted);stroke-width:1.6;stroke-linecap:round;stroke-linejoin:round}
+.fv-agent-job[data-status=running] .fv-agent-glyph{stroke:var(--fv-accent)}
+.fv-agent-job[data-status=succeeded] .fv-agent-glyph{stroke:var(--fv-success)}
+.fv-agent-job[data-status=failed] .fv-agent-glyph{stroke:var(--fv-danger)}
+.fv-agent-body{min-width:0;display:grid;gap:7px}
+.fv-agent-head{display:flex;align-items:baseline;justify-content:space-between;gap:12px}
+.fv-agent-head strong{font-size:var(--fv-body);font-weight:var(--fv-medium);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
+.fv-agent-state{flex:none;font-size:var(--fv-micro);color:var(--fv-muted)}
+.fv-agent-job[data-status=running] .fv-agent-state{color:var(--fv-accent)}
+.fv-agent-job[data-status=succeeded] .fv-agent-state{color:var(--fv-success)}
+.fv-agent-job[data-status=failed] .fv-agent-state{color:var(--fv-danger)}
+.fv-agent-bar{height:4px;border-radius:2px;background:var(--fv-border);overflow:hidden}
+.fv-agent-bar i{display:block;height:100%;background:linear-gradient(90deg,var(--fv-accent),var(--fv-accent-ramp));transform-origin:left;transition:transform var(--fv-slow) var(--fv-ease)}
+.fv-agent-foot{display:flex;align-items:center;gap:6px}
+.fv-agent-meta{flex:1;min-width:0;margin:0;font-size:var(--fv-micro);line-height:1.45;color:var(--fv-muted);overflow-wrap:anywhere}
+.fv-studio .fv-agent-foot :is(button,a),.fv-agent-foot :is(button,a){min-height:0;flex:none;display:inline-flex;align-items:center;height:24px;padding:0 9px;border-radius:var(--fv-r-sm);border:1px solid var(--fv-border);background:transparent;color:var(--fv-ink);font:inherit;font-size:var(--fv-micro);text-decoration:none;cursor:pointer}
+.fv-studio .fv-agent-foot :is(button,a):hover{background:var(--fv-hover)}
+.fv-studio .fv-agent-stop:hover{border-color:var(--fv-danger);color:var(--fv-danger)}
+.fv-agent-foot button:disabled{opacity:.5;cursor:default}
+.fv-agent-divider{padding:12px 12px 4px;font-size:var(--fv-micro);color:var(--fv-disabled);letter-spacing:.02em}
+@media(max-width:680px){.fv-agent-pill{padding:0 9px 0 8px}.fv-agent-panel{right:16px;top:64px}}
+/* The pill shares the header with the centred view switch. Below 1050px it keeps only "Agent" and the percentage;
+ below 820px the switch takes its own row while the pill shows, as it already does below 480px. */
+@media(max-width:1050px){.fv-agent-pill :is(.fv-agent-state-text,.fv-agent-more){display:none}}
+@media(max-width:820px){.fv-studio .fv-header:has(>.fv-view-switch):has(.fv-agent-pill:not([hidden])){height:auto;min-height:98px;grid-template-columns:1fr auto;padding-block:10px}.fv-studio .fv-header:has(.fv-agent-pill:not([hidden]))>.fv-view-switch{grid-column:1/-1;grid-row:2;justify-self:center}.fv-studio .fv-header:has(.fv-agent-pill:not([hidden]))>.fv-header-actions{grid-column:2;grid-row:1}}
+@media(max-width:480px){.fv-agent-panel{top:104px;left:16px;right:16px;width:auto}}
+.fv-agent-panel:focus{outline:none}
diff --git a/web/agent_activity.js b/web/agent_activity.js
new file mode 100644
index 0000000..d495006
--- /dev/null
+++ b/web/agent_activity.js
@@ -0,0 +1,204 @@
+import {agentPost} from './agent_session.js';
+// What agents connected to this FreeVideo are doing. Their requests share the
+// studio's queue, so people can see them, follow progress and stop them.
+const css = document.createElement('link'); css.rel = 'stylesheet'; css.href = new URL('./agent_activity.css', import.meta.url).href; document.head.append(css);
+
+const KINDS = {
+ generate: ['Generating', '生成中', 'M4 7h11a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9a2 2 0 0 1 2-2zm13 4 5-3v8l-5-3'],
+ assemble: ['Assembling', '拼接中', 'M3 6h7v12H3zM14 6h7v12h-7zM10 12h4'],
+ vlm: ['Reviewing', '审看中', 'M2 12s4-7 10-7 10 7 10 7-4 7-10 7S2 12 2 12zm10 3a3 3 0 1 0 0-6 3 3 0 0 0 0 6z'],
+ enhance: ['Writing prompt', '润色提示词', 'M4 20l4-1 10-10-3-3L5 16zM14 7l3 3M18 3l1 2 2 1-2 1-1 2-1-2-2-1 2-1z'],
+};
+const NAMES = {generate: ['Video', '视频'], assemble: ['Sequence', '成片'], vlm: ['Review', '审看'], enhance: ['Prompt', '提示词']};
+
+// Short reasons for the failures people can act on; the engine's own message stays in the tooltip.
+const REASONS = {
+ out_of_memory: ['Out of memory', '显存或内存不足'],
+ insufficient_memory: ['Not enough memory for this video', '显存或内存不够生成这段视频'],
+ interrupted: ['ComfyUI restarted during this job', 'ComfyUI 中途重启'],
+ lost: ['Ended without a result', '没有返回结果'],
+ dependency_failed: ['An earlier step did not succeed', '前序任务未成功'],
+};
+
+function el(tag, cls, text) { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; }
+function glyph(path) {
+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
+ svg.setAttribute('viewBox', '0 0 24 24'); svg.setAttribute('aria-hidden', 'true'); svg.classList.add('fv-agent-glyph');
+ const p = document.createElementNS('http://www.w3.org/2000/svg', 'path'); p.setAttribute('d', path); svg.append(p);
+ return svg;
+}
+const seconds = (s, t) => t(`${Math.max(1, Math.round(s))} s`, `${Math.max(1, Math.round(s))} 秒`);
+// The engine's phases in the reader's language.
+function phaseText(p, t) {
+ const step = p.step;
+ if (p.phase === 'sampling' && step?.total) return t(`Sampling ${step.done} / ${step.total}`, `采样 ${step.done} / ${step.total}`);
+ return {encoding: t('Reading prompt and media', '编码提示词与素材'), load: t('Loading the model', '加载模型'),
+ decode: t('Saving video and audio', '保存视频与音频'), starting: t('Starting', '启动中'),
+ loading: t('Loading the VLM', '加载视觉模型'), answering: t('Answering', '回答中'), rewriting: t('Writing', '改写中'),
+ assembling: t('Joining clips', '拼接片段'), 'preparing images': t('Preparing images', '准备图片'),
+ finishing: t('Finishing', '收尾中')}[p.phase] || '';
+}
+
+export function createAgentActivity(t, api, host, {interval = [1500, 8000]} = {}) {
+ const element = el('button', 'fv-agent-pill'); element.type = 'button'; element.hidden = true;
+ element.setAttribute('aria-haspopup', 'dialog'); element.setAttribute('aria-expanded', 'false');
+ const dot = el('span', 'fv-agent-dot'), label = el('span', 'fv-agent-label');
+ element.append(dot, label);
+ const panel = el('section', 'fv-agent-panel'); panel.hidden = true; panel.setAttribute('role', 'dialog'); panel.tabIndex = -1;
+ panel.setAttribute('aria-label', t('Agent jobs', 'Agent 任务'));
+ host.append(panel);
+ let data = {active: 0, jobs: []}, timer = null, disposed = false, failures = 0;
+
+ function status(job) {
+ const [en, zh] = KINDS[job.kind] || KINDS.generate;
+ if (job.status === 'running') return t(en, zh);
+ if (job.status === 'queued') return job.progress?.queue_position
+ ? t(`In queue · #${job.progress.queue_position}`, `排队 · 第 ${job.progress.queue_position} 位`) : t('Queued', '排队中');
+ if (job.status === 'waiting') return job.waiting_for ? t('Waiting for earlier steps', '等待前序任务') : t('Waiting for the GPU', '等待显卡');
+ return {succeeded: t('Done', '已完成'), failed: t('Failed', '失败'), cancelled: t('Cancelled', '已取消')}[job.status] || job.status;
+ }
+ function title(job) {
+ const name = NAMES[job.kind] || NAMES.generate;
+ return job.label || (t(name[0], name[1]) + (job.take ? ' · ' + t(`Take ${job.take}`, `第 ${job.take} 条`) : ''));
+ }
+ function row(job) {
+ const item = el('li', 'fv-agent-job'); item.dataset.status = job.status; item.dataset.job = job.id;
+ item.append(glyph((KINDS[job.kind] || KINDS.generate)[2]));
+ const body = el('div', 'fv-agent-body');
+ const head = el('div', 'fv-agent-head');
+ head.append(el('strong', null, title(job)), el('span', 'fv-agent-state', status(job)));
+ body.append(head);
+ const p = job.progress || {};
+ if (job.status === 'running' || job.status === 'queued') {
+ const bar = el('div', 'fv-agent-bar'), fill = el('i');
+ const fraction = Math.max(0, Math.min(1, Number(p.fraction) || 0));
+ fill.style.transform = `scaleX(${job.status === 'queued' ? 0 : Math.max(.02, fraction)})`;
+ bar.append(fill); bar.setAttribute('role', 'progressbar'); bar.setAttribute('aria-valuemin', '0');
+ bar.setAttribute('aria-valuemax', '100'); bar.setAttribute('aria-valuenow', String(Math.round(fraction * 100)));
+ body.append(bar);
+ }
+ const meta = [];
+ if (job.status === 'running' && phaseText(p, t)) meta.push(phaseText(p, t));
+ if (job.status === 'running' && p.remaining_seconds > 0) meta.push(t(`about ${seconds(p.remaining_seconds, t)} left`, `约剩 ${seconds(p.remaining_seconds, t)}`));
+ const reason = job.status === 'failed' && REASONS[job.error?.code];
+ if (reason) meta.push(t(...reason));
+ else if (job.error?.message && job.status === 'failed') meta.push(job.error.message);
+ if (job.project) meta.push(job.project);
+ if (job.client) meta.push(job.client);
+ const foot = el('div', 'fv-agent-foot');
+ const details = el('p', 'fv-agent-meta', meta.join(' · '));
+ if (reason && job.error?.message) details.title = job.error.message;
+ foot.append(details);
+ if (['waiting', 'queued', 'running'].includes(job.status)) {
+ const stop = el('button', 'fv-agent-stop', t('Stop', '停止')); stop.type = 'button';
+ stop.setAttribute('aria-label', t('Stop ', '停止 ') + title(job));
+ stop.onclick = async () => {
+ stop.disabled = true;
+ try {
+ await agentPost(api, '/freevideo/agent/activity/cancel', {id: job.id});
+ } finally { poll(); }
+ };
+ foot.append(stop);
+ }
+ if (job.video) {
+ const open = el('a', 'fv-agent-open', t('Open', '打开'));
+ open.href = api.apiURL ? api.apiURL(job.video) : job.video; open.target = '_blank'; open.rel = 'noopener';
+ open.setAttribute('aria-label', t('Open video of ', '打开视频:') + title(job));
+ foot.append(open);
+ }
+ body.append(foot);
+ item.append(body);
+ return item;
+ }
+ function renderPanel() {
+ // Keep keyboard focus on the same control across a refresh.
+ const focused = panel.contains(document.activeElement) ? document.activeElement : null;
+ const key = focused && [focused.closest('[data-job]')?.dataset.job, focused.className];
+ panel.replaceChildren();
+ const header = el('header');
+ header.append(el('h2', null, t('Agent jobs', 'Agent 任务')),
+ el('p', null, t('Requests from AI agents connected to FreeVideo. They share the queue with your videos.',
+ '已连接的 AI Agent 提交的任务,与您的生成共用同一个队列。')));
+ // Running first, then the rest in the order they will run; finished ones after, newest first.
+ const rank = {running: 0, queued: 1, waiting: 2};
+ const active = data.jobs.filter(j => j.status in rank)
+ .sort((a, b) => rank[a.status] - rank[b.status] || String(a.created_at).localeCompare(String(b.created_at)));
+ const done = data.jobs.filter(j => !(j.status in rank))
+ .sort((a, b) => String(b.finished_at).localeCompare(String(a.finished_at)));
+ const list = el('ol');
+ for (const job of active) list.append(row(job));
+ if (done.length) {
+ const divider = el('li', 'fv-agent-divider', t('Last 30 minutes', '最近 30 分钟'));
+ divider.setAttribute('role', 'presentation');
+ list.append(divider);
+ for (const job of done) list.append(row(job));
+ }
+ panel.append(header, list);
+ if (key) (panel.querySelector(`[data-job="${key[0]}"] .${key[1].split(' ')[0]}`) || panel).focus?.();
+ }
+ function render() {
+ const jobs = data.jobs || [];
+ element.hidden = !jobs.length;
+ if (!jobs.length) { setOpen(false); return; }
+ const running = jobs.find(j => j.status === 'running'), active = data.active || 0;
+ element.dataset.state = running ? 'running' : active ? 'waiting' : jobs.some(j => j.status === 'failed') ? 'failed' : 'done';
+ // Narrow headers keep only "Agent" and the percentage, so the wordmark keeps its room.
+ let state, percent = '', more = '';
+ if (running) {
+ const fraction = Number(running.progress?.fraction);
+ state = t(KINDS[running.kind]?.[0] || 'Working', KINDS[running.kind]?.[1] || '进行中');
+ if (Number.isFinite(fraction) && fraction > 0) percent = ` ${Math.round(fraction * 100)}%`;
+ if (active > 1) more = ` · +${active - 1}`;
+ } else if (active) state = t(`${active} waiting`, `${active} 个等待中`);
+ else state = t('Done', '已完成');
+ label.replaceChildren('Agent', el('span', 'fv-agent-state-text', ' · ' + state), percent, el('span', 'fv-agent-more', more));
+ element.setAttribute('aria-label', label.textContent);
+ element.title = t('Jobs from AI agents', '来自 AI Agent 的任务');
+ if (!panel.hidden) renderPanel();
+ }
+ function setOpen(open) {
+ panel.hidden = !open; element.setAttribute('aria-expanded', String(open));
+ if (open) renderPanel();
+ }
+ element.onclick = () => setOpen(panel.hidden);
+ const outside = event => { if (!panel.hidden && !panel.contains(event.target) && !element.contains(event.target)) setOpen(false); };
+ // Escape closes the list, not the workspace: the dialog's own cancel follows the keydown.
+ let swallow = false;
+ const escape = event => { if (event.key === 'Escape' && !panel.hidden) { event.stopPropagation(); event.preventDefault(); swallow = true; setOpen(false); element.focus(); } };
+ const cancel = event => { if (swallow) { event.preventDefault(); swallow = false; } };
+ const settle = () => { swallow = false; };
+ // On the document: after a re-render focus can sit outside the workspace.
+ host.addEventListener('pointerdown', outside, true);
+ document.addEventListener('keydown', escape, true);
+ host.addEventListener('cancel', cancel);
+ document.addEventListener('keyup', settle, true);
+ let on = false;
+ async function poll() {
+ clearTimeout(timer); timer = null;
+ if (disposed || !on) return;
+ try {
+ const response = await api.fetchApi('/freevideo/agent/activity', {cache: 'no-store'});
+ if (response.ok) { data = await response.json(); failures = 0; }
+ else failures++;
+ } catch { failures++; }
+ if (disposed) return;
+ render();
+ // Fast while agents work; slow when idle or when an older FreeVideo has no activity route.
+ const wait = data.active ? interval[0] : interval[1] * Math.min(4, 1 + failures);
+ timer = setTimeout(poll, document.hidden ? Math.max(wait, interval[1]) : wait);
+ }
+ // Agent features can be off in this FreeVideo: ask once, and stay out of sight unless they are on.
+ (async () => {
+ try {
+ const response = await api.fetchApi('/freevideo/agent', {cache: 'no-store'});
+ on = response.ok && (await response.json()).enabled === true;
+ } catch { on = false; }
+ poll();
+ })();
+ return {element, panel, refresh: poll, dispose() {
+ disposed = true; clearTimeout(timer);
+ host.removeEventListener('pointerdown', outside, true); document.removeEventListener('keydown', escape, true);
+ host.removeEventListener('cancel', cancel); document.removeEventListener('keyup', settle, true);
+ panel.remove();
+ }};
+}
diff --git a/web/agent_connect.css b/web/agent_connect.css
new file mode 100644
index 0000000..ea8c04d
--- /dev/null
+++ b/web/agent_connect.css
@@ -0,0 +1,19 @@
+/* Settings · AI agents: copyable commands, a few facts, and a guarded token reset. */
+.fv-setup .fv-agent-connect-body,.fv-setup .fv-agent-connect-content{display:grid;gap:12px}
+.fv-setup .fv-agent-connect-body{padding-top:10px}
+.fv-setup .fv-agent-connect-body>p{margin:0;text-wrap:balance}
+.fv-setup .fv-agent-connect-content>p:empty{display:none}
+.fv-setup .fv-agent-copy{display:grid;gap:6px;min-width:0}
+.fv-setup .fv-agent-copy-head{display:flex;align-items:center;justify-content:space-between;gap:12px;font-size:var(--fv-micro);color:var(--fv-muted)}
+.fv-setup .fv-agent-copy-head button{min-height:26px;padding:0 10px;font-size:var(--fv-micro)}
+.fv-setup .fv-agent-copy :is(code,pre){display:block;margin:0;padding:10px 12px;border:1px solid var(--fv-border);border-radius:var(--fv-r-sm);background:var(--fv-bg);color:var(--fv-ink);font:12px/1.55 ui-monospace,monospace;white-space:pre-wrap;overflow-wrap:anywhere;user-select:all}
+.fv-setup .fv-agent-copy-block pre{max-height:220px;overflow:auto;user-select:text}
+.fv-setup .fv-agent-facts{display:grid;grid-template-columns:max-content minmax(0,1fr);gap:6px 16px;margin:0;font-size:var(--fv-micro)}
+.fv-setup .fv-agent-facts dt{color:var(--fv-muted)}
+.fv-setup .fv-agent-facts dd{margin:0;overflow-wrap:anywhere}
+.fv-setup .fv-agent-actions{align-items:center}
+.fv-setup .fv-agent-actions a{color:var(--fv-accent);font-size:var(--fv-body)}
+.fv-setup .fv-agent-confirm{display:flex;flex-wrap:wrap;align-items:center;gap:8px;padding:10px 12px;border:1px solid var(--fv-border);border-radius:var(--fv-r-sm);background:var(--fv-raised);font-size:var(--fv-micro)}
+.fv-setup .fv-agent-confirm span{flex:1 1 220px;color:var(--fv-muted)}
+.fv-setup .fv-agent-confirm .fv-danger{border-color:var(--fv-danger);color:var(--fv-danger)}
+.fv-setup .fv-agent-connect[hidden]{display:none}
diff --git a/web/agent_connect.js b/web/agent_connect.js
new file mode 100644
index 0000000..eedd94e
--- /dev/null
+++ b/web/agent_connect.js
@@ -0,0 +1,116 @@
+import {agentPost} from './agent_session.js';
+// Settings section: connect an AI agent (Claude Code, Cursor, scripts) to this FreeVideo.
+const css = document.createElement('link'); css.rel = 'stylesheet'; css.href = new URL('./agent_connect.css', import.meta.url).href; document.head.append(css);
+
+const DOCS = 'https://github.com/FlashML-org/FreeVideo/blob/main/docs/AGENTS.md';
+const DOCS_ZH = 'https://github.com/FlashML-org/FreeVideo/blob/main/docs/zh-CN/AGENTS.md';
+
+function el(tag, cls, text) { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; }
+
+function ago(iso, t) {
+ const seconds = Math.max(0, (Date.now() - Date.parse(iso)) / 1000);
+ if (!Number.isFinite(seconds)) return '';
+ if (seconds < 90) return t('just now', '刚刚');
+ if (seconds < 5400) return t(`${Math.round(seconds / 60)} min ago`, `${Math.round(seconds / 60)} 分钟前`);
+ if (seconds < 129600) return t(`${Math.round(seconds / 3600)} h ago`, `${Math.round(seconds / 3600)} 小时前`);
+ return t(`${Math.round(seconds / 86400)} days ago`, `${Math.round(seconds / 86400)} 天前`);
+}
+
+// A command or snippet with a Copy button; falls back to selecting the text.
+function copyable(t, label, text, {block = false} = {}) {
+ const wrap = el('div', 'fv-agent-copy' + (block ? ' fv-agent-copy-block' : ''));
+ const head = el('div', 'fv-agent-copy-head');
+ const code = el(block ? 'pre' : 'code', null, text);
+ const button = el('button', null, t('Copy', '复制')); button.type = 'button';
+ button.setAttribute('aria-label', t('Copy ', '复制') + label);
+ button.onclick = async () => {
+ try { await navigator.clipboard.writeText(text); button.textContent = t('Copied', '已复制'); }
+ catch {
+ const range = document.createRange(); range.selectNodeContents(code);
+ const selection = getSelection(); selection.removeAllRanges(); selection.addRange(range);
+ button.textContent = t('Selected', '已选中');
+ }
+ setTimeout(() => { button.textContent = t('Copy', '复制'); }, 1600);
+ };
+ head.append(el('span', null, label), button);
+ wrap.append(head, code);
+ return wrap;
+}
+
+export function agentConnect(t, api) {
+ const section = el('details', 'fv-agent-connect');
+ // Agent features can be off in this FreeVideo: the section appears only when they are on.
+ section.hidden = true;
+ (async () => {
+ let on = false;
+ try {
+ const response = await api.fetchApi('/freevideo/agent', {cache: 'no-store'});
+ on = response.ok && (await response.json()).enabled === true;
+ } catch { on = false; }
+ if (on) section.hidden = false;
+ else section.remove();
+ })();
+ section.append(el('summary', null, t('AI agents', 'AI Agent 接入')));
+ const body = el('div', 'fv-agent-connect-body');
+ body.append(el('p', 'fv-muted', t('Let Claude Code, Cursor and other AI agents generate, review and edit with FreeVideo on this computer. Their jobs share the queue with yours and appear at the top of the creative workspace.',
+ '让 Claude Code、Cursor 等 AI Agent 在这台电脑上用 FreeVideo 生成、审片和剪辑。它们的任务与您的生成共用队列,并显示在创作面板顶部。')));
+ const content = el('div', 'fv-agent-connect-content'); content.setAttribute('aria-live', 'polite');
+ content.append(el('p', 'fv-muted', t('Loading…', '正在读取…')));
+ body.append(content);
+ section.append(body);
+ let loaded = false;
+
+ async function load() {
+ let value;
+ try {
+ const response = await api.fetchApi('/freevideo/agent/connect', {cache: 'no-store'});
+ value = await response.json();
+ if (!response.ok) throw new Error(value?.error?.message || response.statusText);
+ } catch (error) {
+ content.replaceChildren(el('p', 'fv-failure', t('Agent connection is unavailable: ', '无法读取 Agent 接入信息:') + error.message));
+ return;
+ }
+ loaded = true;
+ content.replaceChildren();
+ content.append(copyable(t, 'Claude Code', value.claude_code),
+ copyable(t, t('Claude Desktop, Cursor (mcpServers)', 'Claude Desktop、Cursor(mcpServers)'), JSON.stringify(value.mcp_json, null, 2), {block: true}));
+ if (value.cli) content.append(copyable(t, t('Command line', '命令行'), value.cli));
+ const facts = el('dl', 'fv-agent-facts');
+ const fact = (name, text) => { facts.append(el('dt', null, name), el('dd', null, text)); };
+ fact(t('HTTP API', 'HTTP 接口'), value.api);
+ fact(t('Token', '令牌'), value.token_from_environment
+ ? t('Set by FREEVIDEO_AGENT_TOKEN', '由环境变量 FREEVIDEO_AGENT_TOKEN 指定')
+ : value.token_file);
+ fact(t('Recent agents', '最近连接的 Agent'), value.agents?.length
+ ? value.agents.map(a => `${a.client} · ${ago(a.last_seen, t)}`).join(',')
+ : t('None yet', '暂无'));
+ content.append(facts);
+ const actions = el('div', 'fv-actions fv-agent-actions');
+ const docs = el('a', null, t('Agent guide ↗', 'Agent 使用说明 ↗'));
+ docs.href = t(DOCS, DOCS_ZH); docs.target = '_blank'; docs.rel = 'noopener noreferrer';
+ const reset = el('button', null, t('Reset token', '重置令牌')); reset.type = 'button';
+ reset.hidden = !!value.token_from_environment;
+ const confirm = el('div', 'fv-agent-confirm'); confirm.hidden = true; confirm.setAttribute('role', 'group');
+ const yes = el('button', 'fv-danger', t('Reset', '重置')); yes.type = 'button';
+ const no = el('button', null, t('Keep', '保留')); no.type = 'button';
+ confirm.append(el('span', null, t('Connected agents will need the new token; MCP servers read it again when they restart.',
+ '已连接的 Agent 需要改用新令牌;MCP 服务重启后会自动读取。')), yes, no);
+ const status = el('p', 'fv-muted'); status.setAttribute('role', 'status');
+ reset.onclick = () => { confirm.hidden = false; reset.hidden = true; no.focus(); };
+ no.onclick = () => { confirm.hidden = true; reset.hidden = false; reset.focus(); };
+ yes.onclick = async () => {
+ yes.disabled = true;
+ try {
+ const response = await agentPost(api, '/freevideo/agent/connect/reset', {});
+ if (!response.ok) throw new Error(response.statusText);
+ status.textContent = t('A new token was created. The old one no longer works.', '已生成新令牌,旧令牌已失效。');
+ } catch (error) {
+ status.className = 'fv-failure'; status.textContent = error.message;
+ } finally { yes.disabled = false; confirm.hidden = true; reset.hidden = false; }
+ };
+ actions.append(docs, reset);
+ content.append(actions, confirm, status);
+ }
+ section.addEventListener('toggle', () => { if (section.open && !loaded) load(); });
+ return section;
+}
diff --git a/web/agent_session.js b/web/agent_session.js
new file mode 100644
index 0000000..97e2cb2
--- /dev/null
+++ b/web/agent_session.js
@@ -0,0 +1,28 @@
+// Page-only control authorization. The Agent bearer token never enters the page.
+const sessions = new WeakMap();
+export async function agentHeaders(api) {
+ let pending = sessions.get(api);
+ if (!pending) {
+ pending = api.fetchApi('/freevideo/agent/session', {cache: 'no-store', credentials: 'same-origin'})
+ .then(async response => {
+ if (!response.ok) throw new Error('Agent page session unavailable');
+ const value = await response.json();
+ return {'X-FreeVideo-CSRF': value.csrf};
+ });
+ sessions.set(api, pending);
+ pending.catch(() => sessions.delete(api));
+ }
+ return pending;
+}
+
+// A restarted FreeVideo forgets page sessions: fetch a new one once and repeat.
+export async function agentPost(api, path, body) {
+ for (let attempt = 0; ; attempt++) {
+ const response = await api.fetchApi(path, {method: 'POST',
+ headers: {'Content-Type': 'application/json', ...await agentHeaders(api)}, body: JSON.stringify(body)});
+ if (response.status !== 403 || attempt) return response;
+ const value = await response.clone().json().catch(() => null);
+ if (value?.error?.code !== 'page_session_required') return response;
+ sessions.delete(api);
+ }
+}
diff --git a/web/dialog_keys.js b/web/dialog_keys.js
new file mode 100644
index 0000000..abb78b1
--- /dev/null
+++ b/web/dialog_keys.js
@@ -0,0 +1,87 @@
+const keyEvents = ['keydown', 'keypress', 'keyup', 'copy', 'cut', 'paste'];
+const localKeys = new WeakMap();
+const isolatedDialogs = new Set();
+export const topDialog = () => Array.from(document.querySelectorAll('dialog[open]')).at(-1);
+
+// Document capture shortcuts run before controls inside a modal. Route the
+// original event locally, keeping its browser default and trusted state intact.
+export function isolateDialogKeys(element, route) {
+ const stray = event => {
+ if (!element.open) return;
+ const inside = element.contains(event.target);
+ // Tab can leave focus on body while another modal is still above us.
+ // Keep its native cancel default, but don't send a stray key to the host.
+ const upper = topDialog();
+ if (upper && upper !== element) {
+ if (isolatedDialogs.has(upper)) return;
+ event.stopImmediatePropagation();
+ routeDialogKey(event, upper);
+ return;
+ }
+ event.stopImmediatePropagation();
+ route(event, inside);
+ };
+ isolatedDialogs.add(element);
+ for (const type of keyEvents) window.addEventListener(type, stray, true);
+ return () => {
+ isolatedDialogs.delete(element);
+ for (const type of keyEvents) window.removeEventListener(type, stray, true);
+ };
+}
+
+// Register local handlers for both normal DOM delivery and captured modal keys.
+export function listenDialogKey(target, type, handler, options) {
+ let listeners = localKeys.get(target);
+ if (!listeners) { listeners = []; localKeys.set(target, listeners); }
+ const row = {type, handler, capture: options === true || Boolean(options?.capture)};
+ listeners.push(row); target.addEventListener(type, handler, options);
+ return () => {
+ target.removeEventListener(type, handler, options);
+ const index = listeners.indexOf(row); if (index >= 0) listeners.splice(index, 1);
+ };
+}
+
+export function routeDialogKey(event, element) {
+ if (!element.contains(event.target)) return;
+ const path = [];
+ for (let target = event.target; target; target = target.parentNode) {
+ path.push(target); if (target === element) break;
+ }
+ let current, phase, stopped = false, immediate = false;
+ // The window gate has stopped native propagation. Local propagation still
+ // needs its own flags, currentTarget and phase for nested control handlers.
+ const local = new Proxy(event, {
+ get(target, name) {
+ if (name === 'currentTarget') return current;
+ if (name === 'eventPhase') return phase;
+ if (name === 'cancelBubble') return stopped;
+ if (name === 'stopPropagation') return () => { stopped = true; };
+ if (name === 'stopImmediatePropagation') return () => { stopped = immediate = true; };
+ const value = Reflect.get(target, name, target);
+ return typeof value === 'function' ? value.bind(target) : value;
+ },
+ set(target, name, value) {
+ if (name === 'cancelBubble') { if (value) stopped = true; return true; }
+ return Reflect.set(target, name, value, target);
+ },
+ });
+ const deliver = (target, capture) => {
+ current = target; phase = target === event.target ? 2 : capture ? 1 : 3;
+ if (!capture && target['on' + event.type]?.call(target, local) === false) event.preventDefault();
+ for (const row of [...localKeys.get(target) || []]) {
+ if (immediate) break;
+ if (row.type === event.type && row.capture === capture) row.handler.call(target, local);
+ }
+ };
+ for (const target of [...path].reverse()) { deliver(target, true); if (stopped) return; }
+ for (const target of path) { deliver(target, false); if (stopped) break; }
+ // Built-in media controls listen inside a browser-owned shadow tree, which
+ // the window gate cannot reach. Keep their focused Space action local too.
+ const media = event.target;
+ if (event.type === 'keydown' && event.key === ' ' && !event.defaultPrevented
+ && !event.ctrlKey && !event.metaKey && !event.altKey
+ && media.controls && ['VIDEO', 'AUDIO'].includes(media.tagName)) {
+ event.preventDefault();
+ if (!event.repeat) { if (media.paused) media.play().catch(() => {}); else media.pause(); }
+ }
+}
diff --git a/web/editor.css b/web/editor.css
new file mode 100644
index 0000000..84a0fe2
--- /dev/null
+++ b/web/editor.css
@@ -0,0 +1,142 @@
+/* Share the studio shell and header geometry; only the editor rows differ. */
+.fv-studio.fv-editor{display:grid;grid-template-columns:264px minmax(0,1fr);grid-template-rows:auto minmax(272px,1fr) 40px 56px 40px minmax(var(--fv-ed-tracks-min,174px),clamp(174px,calc(100dvh - 704px),236px));animation:none}
+@media(min-width:1280px){.fv-studio.fv-editor[data-adjust-available=true]{grid-template-columns:264px minmax(0,1fr) 264px}}
+.fv-editor *{box-sizing:border-box}
+.fv-editor [hidden]{display:none!important}
+/* Starting style also covers regions inserted while the stylesheet is loading.
+ Removing pending has no transition, so readiness restores full opacity immediately. */
+.fv-editor .fv-ed-pending{opacity:.4;transition:opacity .15s ease .6s}
+@starting-style{.fv-editor .fv-ed-pending{opacity:1}}
+/* Override the studio-wide motion reset only to retain the delay, with no fade. */
+@media (prefers-reduced-motion:reduce){.fv-editor .fv-ed-pending{transition:opacity 0s linear .6s!important}}
+.fv-editor button:where(:not(.fv-header button)){height:36px;min-height:0;border-radius:var(--fv-r-sm);font:500 13px/1.4 var(--fv-font);white-space:nowrap}
+.fv-editor .fv-header{grid-column:1/-1;position:relative;z-index:6}
+.fv-editor>:not(.fv-header){font-size:13px;line-height:1.4}
+.fv-editor .fv-brand{position:relative}.fv-editor .fv-brand>.fv-wordmark{flex-shrink:0}
+.fv-editor .fv-header-actions{min-width:0;height:100%}.fv-editor .fv-header-actions>button,.fv-editor .fv-ed-export-box>button{flex:none}
+.fv-editor .fv-ed-name{font-size:15px;font-weight:600;background:transparent;border-color:transparent;min-width:0;max-width:320px;flex:1;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;text-align:left;justify-content:flex-start}
+.fv-editor .fv-ed-icon{height:32px;width:32px;min-height:32px;flex:none;padding:0;font-size:22px;background:transparent;border-color:transparent}
+.fv-ed-glyph{width:16px;height:16px;flex:none;fill:none;stroke:currentColor;stroke-width:1.4;stroke-linecap:round;stroke-linejoin:round}.fv-ed-name>span{overflow:hidden;text-overflow:ellipsis}
+.fv-ed-export-box{height:100%;display:flex;gap:12px;align-items:center;min-width:0}
+.fv-ed-export-hint{max-height:100%;overflow:auto;font-size:12px;color:var(--fv-muted)}
+.fv-ed-save-warning{max-height:100%;overflow:auto;font-size:12px;color:var(--fv-danger);min-width:0}.fv-ed-save-warning:not([hidden])+.fv-ed-export-hint{display:none}
+.fv-editor .fv-ed-library{grid-column:1;grid-row:2/4;border-right:1px solid var(--fv-border);padding:12px;overflow:auto;min-height:0;scrollbar-width:thin;scrollbar-color:var(--fv-border) transparent}
+.fv-editor .fv-ed-tabs{height:32px;width:100%;display:flex;margin-bottom:12px}
+.fv-editor .fv-ed-tabs button{flex:1;height:26px;min-height:26px;padding:0 8px;border-color:transparent;border-radius:6px;background:transparent;color:var(--fv-muted);font-size:12px}
+.fv-editor .fv-ed-tabs button[aria-selected=true]{background:var(--fv-raised);color:var(--fv-ink)}
+.fv-ed-search,.fv-ed-description,.fv-ed-rename{font:13px var(--fv-font);color:var(--fv-ink);background:var(--fv-bg);border:1px solid var(--fv-border);border-radius:8px;height:36px;min-width:0;padding:0 10px}
+.fv-ed-library-tools{display:flex;align-items:center;gap:8px;margin-bottom:12px}
+.fv-ed-search{width:0;flex:1}
+.fv-editor .fv-ed-library-import{flex:none;padding:0 10px}
+.fv-ed-library-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}
+.fv-ed-source-card{position:relative;min-width:0}
+.fv-editor .fv-ed-source{display:block;height:auto;padding:0;border:0;border-radius:6px;overflow:hidden;background:var(--fv-card);width:100%;cursor:grab}
+.fv-ed-source-picture{aspect-ratio:16/9;position:relative;display:grid;place-items:center;overflow:hidden}
+.fv-ed-source-picture img{width:100%;height:100%;object-fit:cover}
+.fv-ed-source-time,.fv-ed-source-used{position:absolute;right:4px;bottom:4px;border-radius:3px;background:#0009;padding:1px 4px;color:#fff;font-size:11px;font-variant-numeric:tabular-nums}
+.fv-ed-source-used{right:auto;left:4px}
+.fv-editor .fv-ed-source-add{position:absolute;top:4px;right:4px;width:24px;height:24px;min-height:24px;padding:0;border:0;border-radius:3px;background:#0009;color:#fff;font-size:18px;line-height:24px;opacity:0;pointer-events:none;cursor:pointer}
+.fv-ed-source-card:hover .fv-ed-source-add:not(:disabled),.fv-ed-source-card:focus-within .fv-ed-source-add:not(:disabled){opacity:1;pointer-events:auto}
+.fv-ed-source-preparing{font-size:12px;color:var(--fv-muted);padding:6px;white-space:normal}
+.fv-ed-audio-icon{font-size:26px;color:var(--fv-muted)}
+.fv-editor .fv-ed-import{width:100%;height:auto;aspect-ratio:16/9;border:1px dashed var(--fv-border);border-radius:6px;background:transparent;color:var(--fv-muted);padding:0}
+.fv-ed-library-message{font-size:12px;color:var(--fv-muted);line-height:1.6}
+.fv-editor .fv-ed-preview{grid-column:2;grid-row:2;min-width:0;min-height:0;display:grid;place-items:center;padding:16px;overflow:hidden;background:var(--fv-bg);container-type:size}
+.fv-ed-picture{position:relative;width:min(100cqw,calc(100cqh * var(--fv-ed-width,16) / var(--fv-ed-height,9)));aspect-ratio:var(--fv-ed-width,16)/var(--fv-ed-height,9);background:#000;border-radius:8px;overflow:hidden}
+.fv-ed-picture[data-empty=true]{background:var(--fv-card);border:1px dashed color-mix(in srgb,var(--fv-ink) 28%,transparent)}
+.fv-ed-empty-preview{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;color:var(--fv-muted);font-size:13px;text-align:center;padding:16px}
+.fv-ed-empty-preview svg{width:24px;height:24px;flex:none;fill:none;stroke:currentColor;stroke-width:1.4;stroke-linecap:round;stroke-linejoin:round}
+.fv-editor .fv-ed-preview-close{position:absolute;top:8px;right:8px;width:28px;height:28px;padding:0;z-index:2;background:var(--fv-card);border:1px solid var(--fv-border);color:var(--fv-muted)}
+.fv-ed-preview-close svg{width:16px;height:16px;fill:none;stroke:currentColor;stroke-width:1.4;stroke-linecap:round}
+.fv-editor .fv-ed-play:disabled{opacity:.4}
+.fv-editor:has(.fv-ed-track-row[data-track=a2]){--fv-ed-tracks-min:220px}
+.fv-editor .fv-ed-track-view{height:100%}
+.fv-ed-picture>video{position:absolute;width:100%;height:100%;inset:0;object-fit:contain;opacity:0;pointer-events:none}
+.fv-ed-picture>video.fv-ed-visible{opacity:1}
+.fv-ed-picture>video.fv-ed-source-preview{opacity:1;pointer-events:auto;object-fit:contain}
+.fv-ed-picture>audio{display:none}
+.fv-ed-picture>audio.fv-ed-source-preview{display:block;position:absolute;bottom:0;left:0;width:100%}
+.fv-ed-transport{grid-column:2;grid-row:3;display:flex;align-items:center;justify-content:center;gap:12px}
+.fv-editor .fv-ed-play{width:36px;height:36px;border-radius:50%;padding:0;background:transparent}
+.fv-ed-time{font-size:13px;font-variant-numeric:tabular-nums;font-family:ui-monospace,monospace;min-width:100px}
+.fv-ed-genbar{grid-column:1/-1;grid-row:4;display:flex;align-items:center;gap:12px;padding:0 16px;border-top:1px solid var(--fv-border);border-bottom:1px solid var(--fv-border);background:var(--fv-card);min-width:0}
+.fv-ed-genbar .fv-ed-description{width:auto}
+.fv-ed-clip[data-state=running] .fv-block-progress.fv-ed-block-progress{display:grid}
+.fv-ed-gen-hint{font-size:13px;color:var(--fv-muted);flex:1;min-width:0}
+.fv-ed-description{flex:1;width:0}
+.fv-ed-description:disabled{opacity:.4}
+.fv-editor .fv-ed-gen-target{height:36px;align-items:center}
+.fv-editor .fv-ed-gen-target button{height:30px;box-shadow:none}
+.fv-editor .fv-ed-genbar>button{flex:none}
+.fv-ed-tracks{grid-column:1/-1;grid-row:6;min-width:0;overflow:hidden}
+.fv-editor .fv-ed-clip{height:100%;padding:0;border-radius:8px;display:block}
+.fv-editor .fv-ed-playhead-handle{height:12px;min-height:0;width:11px;padding:0;border:0;background:var(--fv-ink);border-radius:0}
+.fv-editor .fv-ed-toolbar .fv-ed-track-zoom button{height:32px;width:32px;padding:0;background:transparent;border:0;color:var(--fv-muted)}
+.fv-editor .fv-ed-toolbar .fv-ed-track-zoom .fv-ed-fit{width:auto;padding:0 8px;font-size:13px}
+.fv-editor .fv-ed-track-head{flex-direction:row;gap:4px}.fv-editor .fv-ed-track-head svg{width:14px;height:14px}
+.fv-editor .fv-ed-waveform{fill:none;stroke:color-mix(in srgb,var(--fv-accent) 55%,transparent);stroke-width:1;stroke-linecap:round}
+.fv-editor .fv-ed-waveform path{fill:none}
+.fv-ed-basic-progress{position:absolute;inset:0}.fv-ed-basic-water{position:absolute;bottom:0;left:0;right:0;background:linear-gradient(color-mix(in srgb,var(--fv-accent) 26%,transparent),color-mix(in srgb,var(--fv-accent) 46%,transparent));border-top:1.5px solid var(--fv-accent)}
+.fv-ed-basic-progress[data-state=waiting]{border:1px dashed color-mix(in srgb,var(--fv-ink) 28%,transparent);border-radius:inherit;background:color-mix(in srgb,var(--fv-ink) 3%,transparent)}
+.fv-ed-basic-percent{position:absolute;inset:0;display:grid;place-items:center;font-size:13px;font-weight:600;font-variant-numeric:tabular-nums}.fv-ed-clip[data-track^=a] .fv-ed-basic-percent{display:none}
+.fv-ed-toolbar{grid-column:1/-1;grid-row:5;display:flex;align-items:center;gap:12px;height:40px;padding:0 16px;border-top:1px solid var(--fv-border);min-width:0;position:relative;z-index:7}
+.fv-ed-tool-group{display:flex;align-items:center;gap:4px;position:relative;flex:none}
+.fv-ed-tool-group+.fv-ed-tool-group:before{content:"";width:1px;height:16px;background:var(--fv-border);margin-right:8px}
+.fv-editor .fv-ed-toolbar button{display:inline-flex;align-items:center;justify-content:center;gap:6px;height:32px;padding:0 8px;background:transparent;border-color:transparent;font-size:13px}
+.fv-editor .fv-ed-toolbar .fv-ed-icon{width:32px;padding:0}
+.fv-editor .fv-ed-toolbar button:disabled{opacity:.4}
+.fv-ed-toolbar>.fv-ed-zoom{margin-left:auto;flex:none}
+.fv-ed-toolbar .fv-ed-track-zoom{position:static;height:32px}
+.fv-ed-toolbar .fv-ed-zoom-slider{width:64px}
+/* The tracks' basic fallback rises from the bottom; Blake supplies the waves. */
+.fv-editor .fv-ed-progress-fill{width:100%;height:calc(var(--fv-ed-progress)*100%);inset:auto 0 0}
+.fv-ed-drawer-toggle{display:none!important}
+.fv-ed-name-menu{position:absolute;top:100%;left:0;width:300px;max-width:calc(100vw - 32px);padding:6px;background:var(--fv-card);border:1px solid var(--fv-border);border-radius:8px;z-index:8;display:flex;flex-direction:column;gap:0;font:13px var(--fv-font)}
+/* Rows look like the right-click menu (editor_menu.css). */
+.fv-editor .fv-ed-name-menu button{display:block;flex-shrink:0;width:100%;height:32px;padding:0 10px;border:0;border-radius:4px;background:transparent;color:var(--fv-ink);font:inherit;line-height:32px;text-align:left;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
+.fv-editor .fv-ed-name-menu button:not(:disabled):hover,.fv-editor .fv-ed-name-menu button:focus-visible{background:color-mix(in srgb,var(--fv-accent) 12%,transparent);outline:1px solid var(--fv-accent);outline-offset:-1px}
+.fv-editor .fv-ed-name-menu button:disabled{opacity:.4;cursor:not-allowed}
+.fv-ed-name-menu [role=separator]{flex:none;height:1px;margin:5px 4px;background:var(--fv-border)}
+.fv-ed-rename{width:100%;margin-bottom:4px}
+.fv-ed-notice{position:absolute;bottom:340px;right:16px;max-width:min(560px,calc(100vw - 32px));border:1px solid var(--fv-border);background:var(--fv-card);padding:10px 14px;border-radius:8px;z-index:9;color:var(--fv-ink)}
+@media(max-width:680px){
+ .fv-studio.fv-editor{grid-template-columns:minmax(0,1fr);grid-template-rows:auto minmax(180px,1fr) 40px auto 40px 236px;overflow:hidden}
+ .fv-editor .fv-header{overflow-x:auto}
+ .fv-editor .fv-ed-name{font-size:13px;max-width:112px;flex:1;padding:0 2px}
+ .fv-editor .fv-ed-icon{width:28px;flex:none;font-size:20px}
+ .fv-ed-export-box{gap:4px}
+ .fv-ed-export-hint{display:none}
+ .fv-editor .fv-ed-export-box>button{padding:0 8px;font-size:12px}
+ .fv-editor .fv-ed-drawer-toggle{display:inline-flex!important}
+ .fv-editor .fv-ed-library{display:none;position:absolute;top:52px;bottom:0;left:0;width:264px;max-width:90vw;z-index:7;background:var(--fv-bg)}
+ .fv-editor .fv-ed-library[data-open=true]{display:block}
+ .fv-editor .fv-ed-preview{grid-column:1;grid-row:2;padding:16px}
+ .fv-ed-transport{grid-column:1;grid-row:3}
+ .fv-ed-tracks{grid-column:1;grid-row:6}
+ .fv-ed-toolbar{grid-column:1;grid-row:5;padding:0 12px;gap:8px;overflow-x:auto}
+ .fv-ed-genbar{grid-column:1;grid-row:4;min-height:56px;gap:8px;padding:10px 12px;flex-wrap:wrap}
+ .fv-ed-description{width:100%;flex:1 1 100%}
+ .fv-editor .fv-ed-genbar>button{margin-left:auto;max-width:100%;font-size:12px}
+ .fv-ed-name-menu{position:fixed;top:120px;left:8px}
+ .fv-ed-notice{top:60px;bottom:auto;pointer-events:none}
+ .fv-ed-save-warning{position:absolute;top:60px;left:8px;right:8px;border:1px solid var(--fv-border);background:var(--fv-card);padding:8px 12px;border-radius:8px;z-index:9}
+}
+
+.fv-ed-name-menu{max-height:calc(100dvh - 72px);overflow-y:auto}
+.fv-ed-volume-popover{position:absolute;top:calc(100% + 8px);left:0;display:flex;align-items:center;gap:8px;padding:10px 12px;border:1px solid var(--fv-border);border-radius:8px;background:var(--fv-card);white-space:nowrap;z-index:8}
+.fv-ed-volume{width:90px}.fv-ed-volume-value{font-variant-numeric:tabular-nums;font-size:12px;min-width:34px}
+
+/* Keep the editor's controls visible instead of clipping them at phone widths. */
+@media(max-width:480px){
+ .fv-studio.fv-editor{grid-template-rows:auto minmax(128px,1fr) 40px auto auto 236px}
+ .fv-studio.fv-editor .fv-header:has(.fv-view-switch){grid-template-columns:minmax(0,1fr) auto}
+ .fv-ed-toolbar{display:grid;grid-template-columns:auto minmax(0,1fr);height:auto;gap:4px 8px;padding:4px 12px;overflow:visible}
+ .fv-ed-toolbar>.fv-ed-tool-group:nth-child(2){grid-column:2;grid-row:1/3;flex-wrap:wrap;align-self:start;min-width:0}
+ .fv-ed-toolbar>.fv-ed-tool-group:nth-child(3){grid-column:1;grid-row:2}
+ .fv-ed-toolbar .fv-ed-tool-group+.fv-ed-tool-group:before{display:none}
+ .fv-ed-toolbar>.fv-ed-zoom{grid-column:1/-1;grid-row:3;justify-self:end;margin-left:0}
+ .fv-editor .fv-ed-track-view{--fv-ed-head-width:104px}
+ .fv-editor .fv-ed-playhead-handle{left:0}
+ .fv-editor .fv-ed-library{grid-area:auto;top:116px;bottom:0;z-index:8}
+ .fv-editor:has(.fv-ed-library[data-open=true]) .fv-ed-drawer-toggle{position:fixed;top:128px;right:20px;z-index:9}
+}
diff --git a/web/editor.js b/web/editor.js
new file mode 100644
index 0000000..4972a2e
--- /dev/null
+++ b/web/editor.js
@@ -0,0 +1,813 @@
+import {createEditorText} from './editor_text.js';
+import {isText} from './editor_text_model.js';
+import {viewSwitch, viewChanged} from './view_navigation.js';
+import {wordmark} from './wordmark.js';
+import {openSetup} from './setup.js';
+import * as model from './editor_model.js';
+import {createEditorState} from './editor_state.js';
+import {createEditorStore, sourceKey, mediaURL} from './editor_store.js';
+import {generationSize} from './editor_generation.js';
+import {createEditorLibrary} from './editor_library.js';
+import {createEditorPlayer} from './editor_player.js';
+import {createAdjustPanel, row} from './editor_adjust.js';
+import {createAdjustPicture} from './editor_adjust_picture.js';
+import {pictureSession} from './editor_picture_session.js';
+import {createPictureTools} from './editor_frame.js';
+import {openExportDialog} from './editor_export_dialog.js';
+import {createEditorGenbar, loadEditorComponents, editorBlockStates, blockMessages} from './editor_genbar.js';
+import {createProgressConnection} from './progress_connection.js';
+import {createSelectionActions, deletionStatus, isMultiple, isTyping, playheadIds, removableGaps, removeGaps} from './editor_select.js';
+import {isolateDialogKeys, topDialog} from './dialog_keys.js';
+import {createBlockNotes, describedTrack} from './editor_notes.js';
+const editorStyles = Promise.all(['editor.css', 'editor_tracks.css', 'editor_frame.css', 'editor_adjust.css', 'editor_adjust_picture.css', 'editor_preview_picture.css', 'editor_select.css', 'editor_menu.css', 'editor_text.css', 'editor_notes.css'].map(name => {
+ const style = document.createElement('link'); style.rel = 'stylesheet'; style.href = new URL(name, import.meta.url).href;
+ const ready = 'sheet' in style ? new Promise(resolve => { style.onload = style.onerror = resolve; }) : Promise.resolve();
+ document.head.append(style); return ready;
+}));
+const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; };
+const language = () => new URLSearchParams(location.search).get('freevideo_lang') || navigator.language;
+const icon = path => { const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); svg.setAttribute('viewBox', '0 0 16 16'); svg.setAttribute('aria-hidden', 'true'); svg.classList.add('fv-ed-glyph'); const line = document.createElementNS(svg.namespaceURI, 'path'); line.setAttribute('d', path); svg.append(line); return svg; };
+function basicBlockProgress(clipId, clipElement) {
+ const element = el('div', 'fv-ed-basic-progress'), water = el('div', 'fv-ed-basic-water'), percent = el('span', 'fv-ed-basic-percent');
+ element.append(water, percent);
+ let level = 0, run = null;
+ return {element, update(value) {
+ if (value.run && value.run !== run) { level = 0; run = value.run; }
+ element.dataset.state = value.state;
+ const fraction = level = value.state === 'waiting' ? 0 : Math.max(level, Math.max(0, Math.min(1, value.fraction || 0))); water.style.height = `${fraction * 100}%`;
+ percent.textContent = `${Math.floor(fraction * 100 + 1e-8)}%`; percent.hidden = value.state !== 'generating' || clipElement.dataset.track !== 'v1' || clipElement.getBoundingClientRect().width < 44;
+ water.hidden = value.state !== 'generating';
+ }, dispose() { element.remove(); }};
+}
+let opened, lastDraft = null;
+const editorViews = new Map(), viewPrefix = 'fv-editor-view:';
+
+// A pending ComfyUI node listens on document, including above sibling dialogs
+// and during native library drags. Suspend the canvas, preserving its placement
+// state and handlers so returning to Nodes can finish the same gesture.
+export function suspendCanvasPointer(canvas) {
+ if (!canvas) return () => {};
+ const saved = [];
+ for (const name of ['processMouseMove', 'processMouseDown', 'processMouseUp', 'processMouseWheel', 'processMouseCancel']) {
+ if (typeof canvas[name] !== 'function') continue;
+ const descriptor = Object.getOwnPropertyDescriptor(canvas, name), blocked = () => {};
+ saved.push({name, descriptor, blocked}); canvas[name] = blocked;
+ }
+ const pan = canvas._autoPan;
+ pan?.stop();
+ return () => {
+ for (const {name, descriptor, blocked} of saved) if (canvas[name] === blocked) {
+ if (descriptor) Object.defineProperty(canvas, name, descriptor);
+ else delete canvas[name];
+ }
+ if (pan && canvas._autoPan === pan && canvas.state?.ghostNodeId != null) pan.start();
+ };
+}
+
+// `components` replaces the optional progress module (see loadEditorComponents).
+export function openEditor({api, app, from = null, panel = {}, components: given = undefined, onView = view => viewChanged(view)}) {
+ if (opened) { opened.element.focus(); return opened; }
+ const t = (en, zh) => String(language()).toLowerCase().startsWith('zh') ? zh : en;
+ const returnFocus = document.activeElement;
+ const even = value => Math.max(2, Math.floor(value / 2) * 2);
+ const initial = () => model.emptyProject({width: even(panel.width || 1344), height: even(panel.height || 768), settings: panel.settings || null,
+ name: t('Untitled edit', '未命名剪辑')});
+ const state = createEditorState(initial());
+ const resumeCanvasPointer = suspendCanvasPointer(app?.canvas);
+ const element = el('dialog', 'fv-studio fv-editor'); element.setAttribute('aria-label', t('Edit', '剪辑视图')); element.tabIndex = -1;
+ const listeners = [];
+ const listen = (type, handler) => { element.addEventListener(type, handler); listeners.push(() => element.removeEventListener(type, handler)); };
+ // Keep editor mouse events from ComfyUI's document bubble handlers (ghost-node placement).
+ for (const type of ['pointermove', 'mousemove', 'pointerdown', 'pointerup', 'mousedown', 'mouseup', 'click', 'dblclick', 'wheel', 'contextmenu'])
+ listen(type, event => event.stopPropagation());
+ const top = el('header', 'fv-header fv-ed-top'), libraryHost = el('aside', 'fv-ed-library'), preview = el('section', 'fv-ed-preview'),
+ transport = el('div', 'fv-ed-transport'), genHost = el('div', 'fv-ed-genbar'), tracksHost = el('div', 'fv-ed-tracks'), zoomHost = el('div', 'fv-ed-zoom');
+ const adjustHost = el('aside', 'fv-ed-adjust-host');
+ const button = (label, action, cls = '') => { const value = el('button', cls, label); value.type = 'button'; value.onclick = action; return value; };
+ const navigation = viewSwitch('editor', () => handle.switchView('studio'), () => handle.switchView('nodes'), () => {});
+ for (const control of navigation.querySelectorAll('button')) control.removeAttribute('title');
+ const brand = el('div', 'fv-brand');
+ const headerActions = el('div', 'fv-header-actions');
+ const title = button('', () => menu.hidden ? showMenu() : menu.hidden = true, 'fv-ed-name'); title.setAttribute('aria-haspopup', 'menu');
+ const drawer = button(t('Media', '素材'), () => { libraryHost.dataset.open = libraryHost.dataset.open !== 'true'; drawer.setAttribute('aria-expanded', libraryHost.dataset.open); }, 'fv-ed-drawer-toggle');
+ drawer.setAttribute('aria-expanded', 'false');
+ const exportBox = el('div', 'fv-ed-export-box'), exportHint = el('span', 'fv-ed-export-hint'), exportButton = button(t('Export', '导出'), async () => {
+ try {
+ if (exportStatus?.state === 'done' && exportMatches()) { await actions.export(); return; }
+ const options = await openExportDialog({parent: element, state, sources: store.sources, t, onError: error});
+ if (options && !disposed) await actions.export(options);
+ } catch (value) { error(value); }
+ }, 'fv-primary');
+ const exportCancel = button('', () => store.cancelExport(exportStatus.id).catch(error)); exportCancel.hidden = true; exportCancel.append(icon('m4 4 8 8M12 4l-8 8')); exportCancel.setAttribute('aria-label', t('Cancel', '取消'));
+ exportBox.append(exportHint, exportButton, exportCancel); brand.append(wordmark(), title);
+ headerActions.append(exportBox, button(t('Settings', '设置'), openSetup, 'fv-quiet'));
+ top.append(brand, navigation, headerActions);
+ const menu = el('div', 'fv-ed-name-menu'); menu.hidden = true; menu.setAttribute('role', 'menu');
+ const saveWarning = el('span', 'fv-ed-save-warning'); saveWarning.hidden = true; saveWarning.setAttribute('role', 'status'); exportBox.prepend(saveWarning);
+ const notice = el('div', 'fv-ed-notice'); notice.hidden = true; notice.setAttribute('role', 'status');
+ transport.append(drawer);
+ brand.append(menu);
+ element.append(top, libraryHost, preview, transport, genHost, tracksHost, zoomHost, notice);
+ element.append(adjustHost);
+ tracksHost.inert = genHost.inert = true; title.disabled = true;
+ // CSS delays the pending indication; fast opens stay at full opacity.
+ tracksHost.classList.add('fv-ed-pending'); genHost.classList.add('fv-ed-pending');
+ let discardOnSwitch = false, initialSelection = null;
+ let viewKey = null, viewReady = false;
+ let library = null, closing = false, closePromise = null, exportSnapshot = null, lastSeed = null, projectEpoch = 0;
+ let disposed = false, suppressSave = false, savedContent = '', initializing = true, tracks = null, genbar = null, exportStatus = null, pointerEditing = false, deferredStamp = null;
+ let capability = {maxSeconds: 15, maxFollowSeconds: 15, maxRequestFrames: null, estimate: () => null}, generationBusy = false, switching = false, generationDone = null, finishGeneration = null;
+ let noticeTimer = null, stopExport = null, mostRecentJob = null;
+ const jobWatchers = new Map(), progress = new Map(), jobStatuses = new Map(), runProgress = new Map();
+ let blockStates = null, progressObserver = null, progressConnection = null;
+ function barJob(job) {
+ const latest = [...runProgress.values()].filter(message => message.chain.id === job.id)
+ .sort((a, b) => (a.received_at || 0) - (b.received_at || 0)).at(-1);
+ return latest ? {...job, chainProgress: latest.chain} : job;
+ }
+ function paintJob(job) {
+ const messages = blockMessages([...runProgress.values()].filter(message => message.chain.id === job.id),
+ message => panel.progressSnapshot?.(message));
+ const values = editorBlockStates(job, messages, blockStates);
+ for (const block of job.blocks || []) {
+ const clip = model.attemptClip(state.record, block.id); if (!clip || clip.job !== job.id) continue;
+ const value = {...values[block.id], run: `${job.id}:${block.prompt_id || block.attempts || 0}`};
+ for (const pair of model.pair(state.record, block.id)) { progress.set(pair.id, value); tracks?.setProgress(pair.id, value); }
+ }
+ }
+ function receiveProgress(message) {
+ if (disposed || !message.chain?.id || !message.chain.block) return false;
+ const job = jobStatuses.get(message.chain.id);
+ if (!job || String(job.node ?? panel.node?.id ?? panel.node ?? message.node) !== String(message.node)) return false;
+ const block = job.blocks?.find(block => block.id === message.chain.block);
+ if (!block || !model.attemptClip(state.record, block.id)) return false;
+ const key = `${job.id}:${block.id}`, previous = runProgress.get(key);
+ // A resumed attempt has a new prompt_id. Never replay the cancelled run.
+ if (message.prompt_id && block.prompt_id && message.prompt_id !== block.prompt_id) return false;
+ if (previous?.prompt_id === message.prompt_id && previous?.stream_id === message.stream_id
+ && Number.isFinite(previous?.sequence) && previous.sequence >= message.sequence) return true;
+ runProgress.set(key, message); paintJob(job);
+ if (mostRecentJob === job.id) genbar?.update(barJob(job));
+ return true;
+ }
+ const content = record => JSON.stringify({...record, id: null, revision: 0});
+ function notify(text) { if (disposed) return; notice.textContent = text; notice.hidden = false; clearTimeout(noticeTimer); noticeTimer = setTimeout(() => { notice.hidden = true; }, 9000); }
+ function error(value) {
+ const code = value?.code || value?.message;
+ if (code === 'unsupported') { genbar?.update(null); return; }
+ if (['busy', 'locked', 'text', 'audio_full', 'overlap', 'range'].includes(code)) {
+ if (['locked', 'audio_full', 'overlap', 'range'].includes(code)) tracks?.flashBlocked?.(value.displayFrame);
+ return;
+ }
+ notify(t('Could not complete. Try again.', '没有完成,请重试'));
+ }
+ const store = createEditorStore(api, {t, notify});
+ const queue = store.createSaveQueue({get record() { return state.record; },
+ adopt(value) {
+ if (pointerEditing) { deferredStamp = value; return; }
+ if (!value.nameSuffix && state.record.id === value.id && state.record.revision === value.revision) return;
+ suppressSave = true; try { state.adopt(value); } finally { suppressSave = false; }
+ },
+ }, {onStatus: () => {
+ if (!queue.dirty) { discardOnSwitch = false; saveWarning.hidden = true; }
+ }});
+ const player = createEditorPlayer(preview, transport, {state, sources: store.sources, api, t, preservePreview: () => initializing});
+ function selectionClips(selection = state.selection) {
+ if (selection?.kind !== 'clip') return [];
+ return state.record.tracks[0].clips.filter(clip => selection.ids.includes(clip.id) || selection.ids.includes(clip.link));
+ }
+ function selectionRange(selection = state.selection) {
+ if (!selection) return null;
+ if (selection.kind === 'range' || selection.kind === 'gap') return {start: selection.start, frames: selection.frames, ...(selection.parts ? {parts: selection.parts} : {})};
+ const clips = selectionClips(selection); if (!clips.length) return null;
+ const start = Math.min(...clips.map(clip => clip.start));
+ return {start, frames: Math.max(...clips.map(clip => clip.start + clip.frames)) - start};
+ }
+ const jobActive = () => generationBusy || [...jobStatuses.values()].some(job => ['queued', 'running', 'cancelling'].includes(job.state));
+ function completeSources() {
+ return store.getSources(model.references(state.record).map(sourceKey)).then(() => { player.refresh(); tracks?.refresh?.(); });
+ }
+ const exportMatches = () => exportSnapshot && exportSnapshot.id === state.record.id && exportSnapshot.revision === state.record.revision && exportSnapshot.content === content(state.record);
+ function updateTop() {
+ title.replaceChildren(el('span', '', state.record.name || new Date().toLocaleDateString()), icon('m4 6 4 4 4-4')); title.title = state.record.name;
+ exportButton.classList.toggle('fv-primary', !!model.exportFrames(state.record) && !state.selection && !jobActive() && !exportStatus);
+ if (exportStatus?.state === 'done') exportButton.textContent = exportMatches() ? t('View', '查看') : t('Export', '导出');
+ exportButton.disabled = initializing || !model.exportFrames(state.record) || switching || ['running', 'queued'].includes(exportStatus?.state);
+ exportButton.title = '';
+ }
+ async function snapshot() {
+ let value = panel.snapshot ? structuredClone(await panel.snapshot()) : structuredClone(await app.graphToPrompt());
+ if (value.output) {
+ const node = String(panel.node?.id || panel.node || Object.keys(value.output).find(id => value.output[id].class_type === 'FreeVideoGenerate') || '');
+ value = {node, prompt: value.output, extra_data: {extra_pnginfo: {workflow: value.workflow || {}}}};
+ }
+ if (!value.node || !value.prompt?.[value.node]) throw new Error('missing_node');
+ const inputs = value.prompt[value.node].inputs;
+ Object.assign(inputs, state.record.settings || {}, capability.generationSize || generationSize(state.record));
+ // Tonight's new content uses text. References remain in the creative panel.
+ delete inputs.media; delete inputs.continue_from; delete inputs.continue_to;
+ return {node: String(value.node), prompt: value.prompt, ...(value.extra_data ? {extra_data: value.extra_data} : {}), ...(api.clientId ? {client_id: api.clientId} : {})};
+ }
+ function pinStoppedJob(record, ids, job) {
+ return model.settle(record, ids.filter(id => model.attemptClip(record, id)?.job === job), 'stopped');
+ }
+ async function deliverChain(job) {
+ if (disposed || !job) return false;
+ const previous = jobStatuses.get(job.id);
+ if (Number.isFinite(previous?.updated) && job.updated < previous.updated)
+ return ['queued', 'running', 'cancelling'].includes(previous.state);
+ mostRecentJob = job.id; jobStatuses.set(job.id, job); paintJob(job);
+ const completed = new Set();
+ for (const block of job.blocks || []) {
+ const clip = model.attemptClip(state.record, block.id); if (!clip || clip.job !== job.id) continue;
+ if (block.state === 'done' && block.output) {
+ if (['queued', 'running'].includes(clip.pending) || !previous?.blocks?.some(old => old.state === 'done' && old.output === block.output))
+ completed.add(block.output);
+ const source = {kind: 'generated', id: block.output};
+ await store.getSources([sourceKey(source)]); if (disposed) return false;
+ if (model.attemptClip(state.record, block.id)?.job !== job.id) continue;
+ const metadata = store.sources.get(sourceKey(source));
+ const result = {job: job.id, source, frames: metadata?.frames || block.inputs?.frames,
+ width: metadata?.width, height: metadata?.height,
+ skip_frames: block.skip_frames || 0, skip_audio_samples: block.skip_audio_samples || 0};
+ try {
+ if (!metadata || metadata.missing) throw new model.EditError('source');
+ // settle intentionally skips incompatible undo snapshots.
+ // Validate the current clip first so a bad receipt is visible.
+ model.fill(state.record, block.id, result);
+ state.settle(record => model.fill(record, block.id, result));
+ } catch (value) {
+ if (!(value instanceof model.EditError)) throw value;
+ state.settle(record => model.fail(record, block.id, 'result_mismatch', job.id));
+ error(value);
+ }
+ } else if (block.state === 'failed') {
+ const reason = /^[a-z_]{1,80}$/.test(block.error || '') ? block.error : 'generation_failed';
+ state.settle(record => model.fail(record, block.id, reason, job.id));
+ } else if (['cancelled', 'interrupted'].includes(block.state) || (['cancelled', 'interrupted', 'failed'].includes(job.state) && block.state === 'pending')) {
+ state.settle(record => pinStoppedJob(record, [block.id], job.id));
+ } else if (block.state === 'running' && clip.pending !== 'running') state.settle(record => model.settle(record, [block.id], 'running'));
+ }
+ genbar?.update(barJob(job)); updateTop(); updateTransport();
+ const active = ['queued', 'running', 'cancelling'].includes(job.state);
+ if (completed.size || (!active && previous?.state !== job.state) || (job.output && job.output !== previous?.output))
+ library?.refresh({outputs: job.output ? [job.output] : [...completed]});
+ if (!active) jobWatchers.delete(job.id);
+ return active;
+ }
+ function watchJob(id) {
+ if (disposed) return;
+ if (!jobWatchers.has(id)) jobWatchers.set(id, store.watchChain(id, deliverChain));
+ }
+ function recoverJobs() {
+ for (const id of new Set(state.record.tracks[0].clips.map(clip => clip.job).filter(Boolean))) watchJob(id);
+ }
+ function rememberView() {
+ if (!viewReady) return;
+ const key = state.record.id || viewKey;
+ const value = {selection: state.selection, text: genbar.getText(), playhead: state.playhead,
+ zoom: state.zoom, scrollLeft: tracks?.getScrollLeft() || 0};
+ editorViews.set(key, value);
+ try {
+ localStorage.setItem(viewPrefix + key, JSON.stringify({selection: value.selection, text: value.text}));
+ if (state.record.id) localStorage.setItem('fv-editor-last', key);
+ } catch {}
+ // An untouched edit belongs to this tab until it has a saved identity.
+ lastDraft = !state.record.id && state.record.tracks.every(track => !track.clips.length) ? key : null;
+ try {
+ if (lastDraft) globalThis.sessionStorage?.setItem('fv-editor-draft', lastDraft);
+ else globalThis.sessionStorage?.removeItem('fv-editor-draft');
+ } catch {}
+ }
+ async function replaceProject(record, key = null) {
+ rememberView(); viewReady = false;
+ viewKey = record.id || key || 'draft:' + (globalThis.crypto?.randomUUID?.() || `${Date.now()}-${Math.random()}`);
+ let remembered = editorViews.get(viewKey);
+ if (!remembered) try { remembered = JSON.parse(localStorage.getItem(viewPrefix + viewKey)); } catch {}
+ initialSelection = null;
+ projectEpoch++;
+ player.pause(); for (const stop of jobWatchers.values()) stop(); jobWatchers.clear(); jobStatuses.clear(); progress.clear(); runProgress.clear(); progressConnection?.reset();
+ mostRecentJob = null; genbar?.update(null); queue.reset(record); stopExport?.(); stopExport = null; exportStatus = exportSnapshot = null; exportButton.textContent = t('Export', '导出');
+ suppressSave = true; try { state.replace(record); savedContent = content(record); } finally { suppressSave = false; }
+ const width = tracksHost.clientWidth - 104; if (width > 0) state.setZoom(width / 90);
+ tracks?.setScrollLeft(0);
+ // An empty edit opens with one part's length selected at the start, ready to generate.
+ const selectInitial = () => { initialSelection = state.select({kind: 'range', start: 0,
+ frames: Math.round(Math.min(15, capability.maxSeconds ?? 15) * model.FPS), tracks: ['v1', 'a1']}); };
+ const epoch = projectEpoch;
+ let pointer = null;
+ const rememberPointer = event => { if (event.isTrusted) pointer = event; };
+ // Once the pointer has left the tracks there is no hint to refresh there.
+ const leftTracks = () => { pointer = null; };
+ tracksHost.addEventListener('pointermove', rememberPointer, true); tracksHost.addEventListener('pointerleave', leftTracks);
+ const forgetPointer = () => { tracksHost.removeEventListener('pointermove', rememberPointer, true); tracksHost.removeEventListener('pointerleave', leftTracks); };
+ listeners.push(forgetPointer);
+ // Explicit parts are the existing persisted marker for manual borders.
+ // Keep them even if a later response lowers the limit; maxRequestFrames
+ // still checks the real request before submission.
+ const keepManualParts = value => ({...value,
+ get maxSeconds() { return Math.max(value.maxSeconds, (state.selection?.parts?.[0] || 0) / model.FPS); },
+ get maxFollowSeconds() { return Math.max(value.maxFollowSeconds, ...((state.selection?.parts || []).map(count => count / model.FPS))); }});
+ capability = keepManualParts(store.capabilities(record, value => {
+ if (disposed || epoch !== projectEpoch) return;
+ capability = keepManualParts(value); tracks?.refresh?.();
+ pictureTools.update();
+ if (initialSelection && state.selection === initialSelection) selectInitial();
+ genbar?.update(mostRecentJob ? barJob(jobStatuses.get(mostRecentJob)) : null);
+ // Refresh the active gesture's existing hint through the track pointer handler.
+ if (pointer) tracks?.element.dispatchEvent(new PointerEvent('pointermove', {pointerId: pointer.pointerId,
+ clientX: pointer.clientX, clientY: pointer.clientY, buttons: pointer.buttons, bubbles: true}));
+ forgetPointer();
+ })); if (disposed) return;
+ // A restored edit remains usable offline with its existing placeholders.
+ await completeSources().catch(error); if (disposed) return; recoverJobs();
+ state.restoreView(remembered);
+ if (!state.selection && state.record.tracks.every(track => !track.clips.length)) selectInitial();
+ genbar?.setText(typeof remembered?.text === 'string' ? remembered.text : '');
+ tracks?.setScrollLeft(remembered?.scrollLeft);
+ viewReady = true; updateTransport();
+ }
+ async function switchProject(id) {
+ if (switching) return; switching = true; updateTop();
+ try {
+ await queue.flush();
+ if (queue.dirty) { return; }
+ const record = id ? await store.load(id) : initial();
+ if (!disposed && record) { await replaceProject(record); if (!id) { queue.enqueue(state.record); } menu.hidden = true; }
+ } catch (value) { error(value); }
+ finally { switching = false; updateTop(); }
+ }
+ async function showMenu() {
+ menu.replaceChildren(); menu.hidden = false; title.setAttribute('aria-expanded', 'true');
+ const name = el('input', 'fv-ed-rename'); name.value = state.record.name; name.setAttribute('aria-label', t('Edit name', '修改名字'));
+ const commit = () => { if (name.value.trim()) state.apply(t('Rename', '改名'), record => model.rename(record, name.value.trim())); };
+ name.onchange = commit; name.onkeydown = event => { if (event.key === 'Enter' && !event.isComposing && event.keyCode !== 229) {
+ event.preventDefault(); commit(); menu.hidden = true; title.setAttribute('aria-expanded', 'false'); title.focus();
+ } };
+ const fresh = button(t('New', '新建'), () => switchProject(null)); fresh.setAttribute('role', 'menuitem');
+ menu.append(name, fresh);
+ pictureTools.appendMenu(menu);
+ try {
+ // The current edit is already named in the box at the top.
+ const rows = (await store.projects()).filter(row => row.id !== state.record.id); if (disposed || menu.hidden) return;
+ if (rows.length) { const line = el('div'); line.setAttribute('role', 'separator'); menu.append(line); }
+ for (const row of rows) { const item = button(row.name || new Date(row.updated_at).toLocaleDateString(), () => switchProject(row.id), 'fv-ed-project'); item.setAttribute('role', 'menuitem'); item.title = item.textContent; menu.append(item); }
+ } catch (value) { error(value); }
+ name.focus(); name.select();
+ }
+ const actions = {
+ error, editError: error, notify, sources: store.sources, waveform: key => store.waveform(key), mediaURL: value => mediaURL(api, value),
+ togglePlay: () => player.toggle(),
+ pause: () => player.pause(),
+ async previewSource(source) {
+ if (closing || disposed) return;
+ const cached = store.sources.get(sourceKey(source));
+ if (!initializing || (!cached?.video && !cached?.audio)) await store.getSources([sourceKey(source)]);
+ if (!closing && !disposed) player.previewSource(source);
+ },
+ generationLimits: () => ({maxSeconds: capability.maxSeconds, maxFollowSeconds: capability.maxFollowSeconds}),
+ gestureStart({selectionGesture = false} = {}) {
+ pointerEditing = true;
+ if (selectionGesture && !menu.hidden) menu.hidden = true;
+ },
+ gestureEnd() { releaseStamp(); },
+ insertSource(value, {loadMetadata = false} = {}) {
+ // Early library double-clicks/Enter must target the restored edit.
+ if (initializing) return handle.ready.then(() => {
+ if (!initializing && !closing && !disposed) return actions.insertSource(value, {loadMetadata});
+ });
+ if (loadMetadata) {
+ const epoch = projectEpoch;
+ return store.getSources([sourceKey(value.source)]).then(() => {
+ if (!closing && !disposed && epoch === projectEpoch) return actions.insertSource(value);
+ });
+ }
+ const metadata = store.sources.get(sourceKey(value.source));
+ try { state.apply(t('Insert source', '放入素材'), record => model.insertSource(record, {
+ ...value, width: metadata?.width ?? value.width, height: metadata?.height ?? value.height,
+ at: value.at ?? model.duration(record)}), {clearRange: state.selection !== initialSelection});
+ return {ok: true};
+ } catch (valueError) {
+ if (!(valueError instanceof model.EditError)) throw valueError;
+ valueError.displayFrame = value.at ?? model.duration(state.record); error(valueError);
+ return {ok: false, reason: valueError.code};
+ }
+ },
+ reasonText: code => code === 'gpu_memory' ? t('Not enough graphics memory', '显存不够') : t('Could not generate', '没能生成'),
+ supportedSelection() {
+ if (state.selection?.kind === 'clip' && state.selection.ids.some(id => isText(model.find(state.record, id)))) return false;
+ const range = selectionRange(); if (!range) return false;
+ if (state.selection.kind === 'range' && !['v1', 'a1'].every(id => state.selection.tracks.includes(id))) return false;
+ if (state.selection.kind === 'gap' && state.selection.track !== 'v1') return false;
+ try {
+ const selected = selectionClips();
+ if (selected.length && selected.every(clip => clip.pending && !clip.source))
+ model.prepare(state.record, selected.map(clip => clip.id));
+ else model.planRange(state.record, {...range, target: 'both'});
+ return true;
+ }
+ catch (value) { if (value instanceof model.EditError) return value.code === 'busy'; throw value; }
+ },
+ canGenerate(text) {
+ if (!actions.supportedSelection() || jobActive()) return false;
+ const range = selectionRange();
+ const before = state.record.tracks[0].clips.find(clip => clip.start + clip.frames === range.start && clip.source && clip.extend && clip.in + clip.frames === clip.length);
+ return !!text.trim() || !!before;
+ },
+ previewRange: selection => genbar?.preview(selection),
+ async estimate(selection) {
+ const range = selectionRange(selection); if (!range) return null;
+ let seconds = 0;
+ for (const count of model.rangeParts(state.record, {...range, ...capability})) { const value = capability.estimate(count); if (value == null) return null; seconds += value; }
+ return seconds;
+ },
+ async generate({target = 'both', text = '', label = t('Generate', '生成')} = {}) {
+ if (target !== 'both' || !actions.supportedSelection()) throw new model.EditError('unsupported');
+ if (!actions.canGenerate(text)) throw new model.EditError('text');
+ generationBusy = true; updateTop(); updateTransport();
+ generationDone = new Promise(resolve => { finishGeneration = resolve; });
+ let ids = [], prepared = null;
+ const epoch = projectEpoch, range = selectionRange(), selectedIds = selectionClips().map(clip => clip.id);
+ try {
+ const frozen = await snapshot(); if (epoch !== projectEpoch || closing || disposed) return;
+ state.apply(label, record => {
+ const selected = selectedIds.map(id => model.find(record, id)).filter(Boolean), alreadyPlanned = selected.length && selected.every(clip => !clip.source && clip.pending && !['queued', 'running'].includes(clip.pending));
+ let next = alreadyPlanned ? model.startAttempt(record, selected.map(clip => clip.id), text) : model.planRange(record, {...range, target: 'both', text, maxSeconds: capability.maxSeconds, maxFollowSeconds: capability.maxFollowSeconds});
+ if (!record.tracks[0].clips.length && text.trim()) next = model.rename(next, model.truncateText(text.trim(), 40));
+ ids = next.tracks[0].clips.filter(clip => clip.start >= range.start && clip.start < range.start + range.frames && clip.pending && !['queued', 'running'].includes(clip.pending)).map(clip => clip.id);
+ return model.prepare(next, ids);
+ }, {checkpoint: true});
+ prepared = state.record;
+ state.select({kind: 'clip', ids}); await completeSources();
+ const paths = Object.fromEntries([...store.sources].map(([key, value]) => [key, value.path]));
+ const request = model.generationRequest(prepared, ids, {text, paths});
+ const tooLong = request.blocks.filter(block => capability.maxRequestFrames != null && block.frames > capability.maxRequestFrames);
+ if (tooLong.length) {
+ state.settle(record => tooLong.reduce((next, block) => model.fail(next, block.id, 'too_long', null), record));
+ return;
+ }
+ const values = new Uint32Array(1);
+ if (globalThis.crypto?.getRandomValues) crypto.getRandomValues(values); else values[0] = Math.floor(Math.random() * 2 ** 32);
+ const seed = values[0] === lastSeed ? (values[0] + 1) >>> 0 : values[0]; lastSeed = seed;
+ const blocks = request.blocks.map(({before, ...block}, i) => ({...block, seed: seed + i}));
+ const job = await store.startChain({...frozen, blocks});
+ if (!job?.id) throw new Error('chain_missing');
+ if (epoch !== projectEpoch) return;
+ state.settle(record => model.assignJob(record, ids, job.id, {prepared}));
+ queue.enqueue(state.record);
+ mostRecentJob = job.id; jobStatuses.set(job.id, job); genbar.update(job); watchJob(job.id);
+ } catch (value) {
+ if (ids.length && epoch === projectEpoch) state.settle(record => model.settle(record, ids, 'draft'));
+ throw value;
+ } finally { if (disposed && ids.length) queue.enqueue(state.record); generationBusy = false; finishGeneration?.(); generationDone = null; finishGeneration = null; updateTop(); updateTransport(); }
+ },
+ async cancel() { const id = mostRecentJob; if (id) await deliverChain(await store.chainAction(id, 'cancel')); },
+ async resume() {
+ const epoch = projectEpoch;
+ const id = mostRecentJob || selectionClips().find(clip => clip.job)?.job; if (!id) return;
+ const job = await store.chainAction(id, 'resume'); if (epoch !== projectEpoch || disposed) return;
+ for (const block of job?.blocks || []) if (block.state !== 'done') runProgress.delete(`${id}:${block.id}`);
+ const ids = state.record.tracks[0].clips.filter(clip => clip.job === id && clip.pending).map(clip => clip.id);
+ state.settle(record => model.settle(record, ids, 'queued')); if (job) { await deliverChain(job); watchJob(id); }
+ },
+ async retry(id) { state.select({kind: 'clip', ids: [id]}); const clip = model.find(state.record, id); if (clip.job) { mostRecentJob = clip.job; await actions.resume(); } else await actions.generate({text: clip.text || panel.text || ''}); },
+ async export(options) {
+ if (['running', 'queued'].includes(exportStatus?.state)) return;
+ if (exportStatus?.state === 'done' && exportMatches()) { await viewExport(exportStatus); return; }
+ if (!await textTools.beforeExport()) return;
+ await queue.flush();
+ if (queue.dirty) { return; }
+ if (!state.record.id) return;
+ exportSnapshot = {id: state.record.id, revision: state.record.revision, content: content(state.record)};
+ for (let attempt = 0; ; attempt++) {
+ try { exportStatus = await store.export(state.record.id, state.record.revision, options); break; }
+ catch (value) {
+ if (value.status !== 409 || attempt >= 2) throw value;
+ queue.enqueue(state.record); await queue.flush();
+ if (queue.dirty) return;
+ exportSnapshot = {id: state.record.id, revision: state.record.revision, content: content(state.record)};
+ }
+ }
+ if (!exportStatus) return;
+ updateExport(exportStatus); stopExport?.();
+ stopExport = store.watchExport(exportStatus.id, updateExport);
+ },
+ };
+ async function viewExport(value) {
+ // A sound-only export is not a work: it opens as a file the browser plays and can save.
+ if (value.only === 'sound') { if (value.url) window.open(mediaURL(api, value.url), '_blank', 'noopener'); return; }
+ const module = await import('./library.js');
+ module.openLibrary(t, {selectedWork: value.work});
+ }
+ function updateExport(value) {
+ if (!value) return false;
+ if (exportSnapshot) exportSnapshot = {...exportSnapshot, id: value.project_id, revision: value.revision};
+ exportStatus = value; const running = value.state === 'running' || value.state === 'queued';
+ if (disposed) { if (!running) window.FreeVideoNotifyTaskDone?.({kind: 'export', id: value.id, ok: value.state === 'done'}); return running; }
+ exportButton.textContent = running ? t(`Export ${Math.round(value.fraction * 100)}%`, `导出 ${Math.round(value.fraction * 100)}%`) : value.state === 'done' && exportMatches() ? t('View', '查看') : t('Export', '导出');
+ exportCancel.hidden = !running; exportButton.disabled = running; exportButton.classList.remove('fv-primary');
+ if (!running) {
+ if (value.state === 'failed') notify(t('Export did not finish', '导出没有完成'));
+ window.FreeVideoNotifyTaskDone?.({kind: 'export', id: value.id, ok: value.state === 'done'});
+ }
+ return running;
+ }
+
+ genbar = createEditorGenbar(genHost, {state, t, actions, text: ''});
+ const adjust = createAdjustPanel(adjustHost, {state, t, actions});
+ const pictureEdit = pictureSession(state, t);
+ const notes = createBlockNotes({state, t, actions}); actions.blockNote = notes.decorate; actions.describedTrack = describedTrack;
+ adjust.register('video', createAdjustPicture({state, sources: store.sources, t, player, notes}));
+ const toolbar = el('div', 'fv-ed-toolbar'); toolbar.setAttribute('role', 'toolbar'); toolbar.setAttribute('aria-label', t('Track tools', '轨道工具')); toolbar.inert = true; toolbar.classList.add('fv-ed-pending');
+ const historyTools = el('div', 'fv-ed-tool-group'), editTools = el('div', 'fv-ed-tool-group');
+ const toolButton = (label, path, action, cls, iconOnly = false) => {
+ const control = button('', action, cls); control.append(icon(path));
+ control.classList.add('fv-ed-icon');
+ control.setAttribute('aria-label', label); return control;
+ };
+ const toolUndo = toolButton(t('Undo', '撤销'), 'M5 4 2 7l3 3M2 7h7a4 4 0 0 1 0 8', () => state.undo(), 'fv-ed-undo fv-ed-icon', true);
+ const toolRedo = toolButton(t('Redo', '重做'), 'm11 4 3 3-3 3M14 7H7a4 4 0 0 0 0 8', () => state.redo(), 'fv-ed-redo fv-ed-icon', true);
+ const split = toolButton(t('Split', '剪开'), 'M6 5l8 8M6 11l8-8M6 4a2 2 0 1 1-4 0 2 2 0 0 1 4 0M6 12a2 2 0 1 1-4 0 2 2 0 0 1 4 0',
+ () => selectionActions.run('b'), 'fv-ed-split');
+ const remove = toolButton(t('Delete', '删除'), 'M2 4h12M6 4V2h4v2M4 4l1 10h6l1-10M7 6v5M9 6v5',
+ () => selectionActions.run('delete'), 'fv-ed-delete');
+ const closeGap = toolButton(t('Remove gaps', '移除空隙'), 'M1 3v10M15 3v10M3 8h4m-2-2 2 2-2 2M13 8H9m2-2-2 2 2 2',
+ () => selectionActions.run('gaps'), 'fv-ed-close-gap');
+ const volume = el('input', 'fv-ed-volume'), volumeLabel = el('span', 'fv-ed-volume-value');
+ volume.type = 'range'; volume.min = '0'; volume.max = '200'; volume.step = '1'; volume.value = '100';
+ volume.setAttribute('aria-label', t('Volume', '音量'));
+ const previous = toolButton(t('Previous version', '上一版'), 'M3 6V2M3 6h4M3 6a5 5 0 1 1-1 5M8 5v3l2 2', () => {
+ const clip = selectedContent().find(clip => clip.versions.length);
+ if (clip) try { state.apply(t('Previous version', '上一版'), record => model.restoreVersion(record, clip.id, 0)); } catch (value) { error(value); }
+ }, 'fv-ed-previous');
+ adjust.register('audio', {render: host => host.append(row(t('Volume', '音量'), volume, volumeLabel))});
+ historyTools.append(toolUndo, toolRedo); editTools.append(split, remove, closeGap, previous);
+ const pictureTools = createPictureTools({state, sources: store.sources, t, capabilities: () => capability, error});
+ toolbar.append(historyTools, editTools, zoomHost); element.insertBefore(toolbar, tracksHost);
+ toolbar.append(adjust.toggleButton);
+ const textTools = createEditorText({element, state, t, actions, adjust, player, toolbar, exportBox, tracksHost});
+ let volumeEditing = false;
+ function selectedContent() {
+ const selection = state.selection;
+ if (!selection) return [];
+ if (selection.kind === 'clip') return state.record.tracks.flatMap(track => track.clips).filter(clip => selection.ids.includes(clip.id));
+ return state.record.tracks.filter(track => selection.tracks?.includes(track.id) || track.id === selection.track).flatMap(track => track.clips)
+ .filter(clip => clip.start >= selection.start && clip.start + clip.frames <= selection.start + selection.frames);
+ }
+ const isBusy = clip => ['queued', 'running'].includes(clip.pending);
+ function splitIds() {
+ return playheadIds(state.record, state.selection, state.playhead).filter(id => {
+ const clip = model.find(state.record, id); return state.playhead > clip.start && state.playhead < clip.start + clip.frames;
+ });
+ }
+ const modifier = /Mac|iPhone|iPad/i.test(navigator.userAgentData?.platform || navigator.platform || '') ? '⌘' : 'Ctrl';
+ function updateSplit() {
+ const ids = splitIds(); split.disabled = !ids.length || ids.some(id => model.pair(state.record, id).some(isBusy));
+ split.title = t('Split', '剪开') + ` ${modifier}+B`;
+ }
+ function updateZoom() {
+ const zoomBar = zoomHost.querySelector('.fv-ed-track-zoom'), slider = zoomBar?.querySelector('input');
+ if (slider) {
+ const controls = zoomBar.querySelectorAll('button');
+ controls[0].disabled = state.zoom <= Number(slider.min); controls[1].disabled = state.zoom >= Number(slider.max);
+ controls[2].disabled = !model.duration(state.record) && state.selection?.kind !== 'range';
+ controls[0].title = '';
+ controls[1].title = '';
+ controls[2].title = t('Fit all', '看全部');
+ }
+ }
+ function updateTransport() {
+ const clips = selectedContent(), busy = clips.some(isBusy), audio = jobActive() || busy ? [] : clips.filter(clip => clip.volume !== undefined && clip.source);
+ toolUndo.disabled = !state.canUndo; toolRedo.disabled = !state.canRedo;
+ toolUndo.title = t('Undo', '撤销') + ` ${modifier}+Z`;
+ toolRedo.title = t('Redo', '重做') + ` ${modifier}+Shift+Z`;
+ updateSplit();
+ remove.disabled = !deletionStatus(state.record, state.selection).ok;
+ remove.title = t('Delete Delete', '删除 Delete');
+ const gaps = removableGaps(state.record, state.selection); closeGap.disabled = !gaps.length || !removeGaps(state.record, state.selection).removed;
+ closeGap.title = t('Remove gaps Delete', '移除空隙 Delete');
+ volume.disabled = !audio.length;
+ if (!volumeEditing) volume.value = String(Math.round((audio[0]?.volume ?? 1) * 100));
+ volumeLabel.textContent = volume.value + '%';
+ const multiple = isMultiple(state.record, clips.map(clip => clip.id));
+ previous.disabled = busy || multiple || !clips.some(clip => clip.versions.length);
+ previous.title = t('Previous version', '上一版');
+ updateZoom();
+ }
+ volume.oninput = () => { volumeEditing = true; for (const clip of selectedContent().filter(clip => clip.volume !== undefined)) player.previewVolume(clip.id, Number(volume.value) / 100); volumeLabel.textContent = volume.value + '%'; };
+ volume.onchange = () => {
+ const ids = selectedContent().filter(clip => clip.volume !== undefined).map(clip => clip.id), value = Number(volume.value) / 100;
+ volumeEditing = false;
+ try { state.apply(t('Volume', '音量'), record => ids.reduce((next, id) => model.setVolume(next, id, value), record)); }
+ catch (value) { error(value); }
+ finally { player.clearVolumePreview(); updateTransport(); }
+ };
+ updateTransport();
+ const stopSources = store.subscribeSources(() => { player.refresh(); tracks?.refresh?.(); pictureTools.update(); updateTop(); });
+ let capabilitySize = `${state.record.width}x${state.record.height}`;
+ const unsubscribe = state.subscribe(event => {
+ if (event.type === 'record') {
+ const size = `${state.record.width}x${state.record.height}`;
+ if (!initializing && size !== capabilitySize) {
+ capabilitySize = size;
+ capability = store.capabilities(state.record, value => {
+ capability = value; pictureTools.update(); tracks?.refresh?.(); genbar?.update(null);
+ });
+ }
+ if (initialSelection && state.selection === initialSelection && state.record.tracks.some(track => track.clips.some(clip => clip.source))) state.select(null);
+ const next = content(state.record);
+ if (!suppressSave && !initializing && next !== savedContent && exportStatus?.state === 'done') { exportStatus = null; exportButton.textContent = t('Export', '导出'); }
+ if (!suppressSave && !initializing && next !== savedContent) { savedContent = next; queue.enqueue(state.record); }
+ completeSources().catch(error); recoverJobs();
+ }
+ if (event.type === 'selection') { if (state.selection !== initialSelection) initialSelection = null; }
+ if (event.type === 'record' || event.type === 'selection') { updateTop(); updateTransport(); pictureTools.update(); }
+ else if (event.type === 'playhead') updateSplit();
+ else if (event.type === 'zoom') updateZoom();
+ });
+ function dismissPopup(event) {
+ if (tracks?.menu.dismiss(event)) return true;
+ if (tracks?.dismissPopup(event)) return true;
+ if (pictureEdit.keyboard(event)) return true;
+ if (adjust.dismiss(event)) return true;
+ if (menu.hidden) return false;
+ event.preventDefault(); event.stopPropagation();
+ if (!menu.hidden) { menu.hidden = true; title.setAttribute('aria-expanded', 'false'); title.focus(); }
+ return true;
+ }
+ const selectionActions = createSelectionActions({state, t, actions});
+ actions.editSelection = key => selectionActions.run(key);
+ actions.setSnapping = enabled => tracks.setSnapping(enabled);
+ actions.seekPlayhead = frame => tracks.seekPlayhead(frame);
+ function keyboard(event) {
+ if (event.isComposing || event.keyCode === 229) return;
+ if (!initializing && textTools.keyboard(event)) return;
+ if (pictureEdit.keyboard(event)) return;
+ if (event.key.toLowerCase() === 'escape' && dismissPopup(event)) return;
+ if (event.target.closest('.fv-ed-adjust') && event.key.toLowerCase() !== 'escape'
+ && !((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 'z')) return;
+ // Track gestures have their own keyboard handler (including Escape rollback).
+ if (event.target.closest('.fv-ed-tracks')) return;
+ event.stopPropagation();
+ const typing = isTyping(event.target) && !(event.target.type === 'range' && (event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 'z');
+ const key = event.key.toLowerCase(), mod = event.ctrlKey || event.metaKey;
+ if (key === 'escape') { event.preventDefault(); state.select(null, {history: true}); menu.hidden = true; libraryHost.dataset.open = 'false'; return; }
+ if (typing || initializing) return;
+ if (selectionActions.keyboard(event)) return;
+ if (!mod && !event.altKey && (key === 'arrowup' || key === 'arrowdown' || (key === 'z' && event.shiftKey))) { tracks?.keyboard(event); return; }
+ if (key === ' ') { event.preventDefault(); player.toggle(); }
+ else if (key === 'arrowleft' || key === 'arrowright') { event.preventDefault(); state.seek(Math.max(0, state.playhead + (key === 'arrowright' ? 1 : -1))); }
+ else if (mod && key === 'z') { event.preventDefault(); event.shiftKey ? state.redo() : state.undo(); }
+ }
+ listen('keydown', keyboard); listen('keyup', event => event.stopPropagation());
+ listen('cancel', event => {
+ if (event.target !== element) return;
+ event.preventDefault();
+ if (topDialog() === element && !dismissPopup(event)) state.select(null, {history: true});
+ });
+ const stopKeys = isolateDialogKeys(element, (event, inside) => {
+ if (event.type !== 'keydown') return;
+ if (event.isComposing || event.keyCode === 229) return;
+ if (event.key.toLowerCase() === 'escape') {
+ if (dismissPopup(event)) return;
+ if (tracks?.cancelGesture()) { event.preventDefault(); return; }
+ if (document.fullscreenElement) { event.preventDefault(); document.exitFullscreen().catch(() => {}); return; }
+ }
+ if (inside) {
+ // Preserve the input/library controls' own handlers before shortcuts.
+ for (let target = event.target; target && target !== element; target = target.parentNode) {
+ if (target.onkeydown?.(event) === false) event.preventDefault();
+ if (event.defaultPrevented) return;
+ }
+ if (event.target.closest('.fv-ed-tracks')) { if (!textTools.keyboard(event)) tracks?.keyboard(event); return; }
+ }
+ keyboard(event);
+ });
+ const releaseStamp = () => {
+ pointerEditing = false;
+ if (deferredStamp) {
+ const value = deferredStamp; deferredStamp = null;
+ suppressSave = true; try { state.adopt(value); } finally { suppressSave = false; }
+ }
+ };
+ listen('dragover', event => { if ([...event.dataTransfer.types].includes('Files')) { event.preventDefault(); event.dataTransfer.dropEffect = 'copy'; } });
+ listen('drop', event => { if (event.dataTransfer.files.length) { event.preventDefault(); event.stopPropagation(); library?.importFiles([...event.dataTransfer.files]); } });
+ listen('pointerdown', event => {
+ if (!menu.hidden && !menu.contains(event.target) && event.target !== title) menu.hidden = true;
+ });
+ const leaving = () => { player.pause(); rememberView(); if (queue.dirty) queue.flush(); };
+ window.addEventListener('pagehide', leaving);
+ const handle = {element, state, actions, store, adjust,
+ async switchView(view) {
+ if (closing || disposed || view === 'editor') return;
+ if (await handle.close() !== false) await onView(view);
+ },
+ async close() {
+ if (closePromise) return closePromise;
+ textTools.flush();
+ closing = true; element.inert = true; player.pause();
+ closePromise = (async () => {
+ await handle.ready;
+ if (generationDone) await generationDone;
+ releaseStamp(); await queue.flush();
+ if (queue.dirty && !queue.locallyRetained && !discardOnSwitch) {
+ discardOnSwitch = true; closing = false; element.inert = false; closePromise = null;
+ saveWarning.textContent = t('Not saved yet. Switching again will lose recent changes.', '还没保存好,再切换会丢掉最近的改动');
+ saveWarning.hidden = false; return false;
+ }
+ rememberView(); disposed = true; player.dispose();
+ textTools.dispose(); adjust.dispose(); notes.dispose(); pictureEdit.dispose();
+ listeners.splice(0).forEach(remove => remove());
+ for (const node of [element, ...element.querySelectorAll('*')]) for (const name of ['onclick', 'ondblclick', 'oninput', 'onchange', 'onkeydown', 'ondragstart']) node[name] = null;
+ unsubscribe(); stopSources(); library?.dispose(); genbar.dispose(); tracks?.dispose(); stopExport?.();
+ progressConnection?.stop(); progressObserver?.disconnect(); runProgress.clear();
+ stopKeys();
+ resumeCanvasPointer();
+ window.removeEventListener('pagehide', leaving); clearTimeout(noticeTimer);
+ for (const stop of jobWatchers.values()) stop(); jobWatchers.clear();
+ queue.dispose({discard: discardOnSwitch}); store.dispose(); if (element.open) element.close(); element.replaceChildren(); element.remove(); if (opened === handle) opened = null;
+ if (returnFocus?.isConnected) returnFocus.focus({preventScroll: true});
+ })();
+ return closePromise;
+ },
+ };
+ library = createEditorLibrary(libraryHost, {store, t, actions, state});
+ opened = handle; document.body.append(element); element.showModal(); viewChanged('editor'); navigation.querySelector('[data-view=editor]').focus();
+ handle.ready = (async () => {
+ const componentsReady = Promise.allSettled([import('./editor_tracks.js'), given || loadEditorComponents()]);
+ await editorStyles; if (closing || disposed) return;
+ let record = null, key = null;
+ try {
+ await store.recoverOutbox(); if (closing || disposed) return;
+ if (from?.work) {
+ const work = from.work;
+ const id = work.id || work.video?.replace(/^FreeVideo\//, '').replace(/\/video\.mp4$/, '');
+ record = await store.byWork(id);
+ if (!record) {
+ const key = `work:${id}`; await store.getSources([key]); const metadata = store.sources.get(key), g = work.geometry || {};
+ record = model.emptyProject({width: even(metadata?.width || g.width || panel.width || 1344), height: even(metadata?.height || g.height || panel.height || 768),
+ settings: panel.settings || null, name: t('Untitled edit', '未命名剪辑')});
+ record = model.insertSource(record, {source: {kind: 'work', id}, frames: metadata?.frames || g.frames || Math.round((g.seconds || 15) * 24),
+ hasVideo: true, hasAudio: metadata?.has_audio ?? work.has_audio !== false, at: 0});
+ if (!metadata) store.cache({[key]: {video: mediaURL(api, work.video), audio: mediaURL(api, work.video), frames: g.frames,
+ has_video: true, has_audio: true, path: work.video, missing: false, thumbnail: '/freevideo/library/thumbnail?' + new URLSearchParams({id})}});
+ }
+ } else {
+ let id; try { id = localStorage.getItem('fv-editor-last'); } catch {}
+ let draft; try { draft = globalThis.sessionStorage?.getItem('fv-editor-draft'); } catch { draft = lastDraft; }
+ if (draft?.startsWith('draft:')) key = draft;
+ else if (id) { record = await store.load(id); if (record) key = id; }
+ }
+ } catch (value) { error(value); }
+ if (closing || disposed) return;
+ try {
+ await replaceProject(record || state.record, key);
+ if (from?.work && !state.record.id) queue.enqueue(state.record);
+ } catch (value) { error(value); }
+ if (closing || disposed) return;
+ initializing = false; savedContent = content(state.record);
+ genHost.inert = false; genHost.classList.remove('fv-ed-pending');
+ updateTop(); updateTransport();
+ const [trackResult, componentResult] = await componentsReady; if (closing || disposed) return;
+ // Optional progress components may fail without taking the tracks with them.
+ if (componentResult.status === 'rejected') error(componentResult.reason);
+ if (trackResult.status === 'rejected') throw trackResult.reason;
+ const module = trackResult.value, components = componentResult.status === 'fulfilled' ? componentResult.value : {};
+ blockStates = components.blocks?.blockStates || null;
+ let blockProgress = basicBlockProgress;
+ if (components.blocks?.createBlockProgress) blockProgress = (id, clipElement) => {
+ const component = components.blocks.createBlockProgress({t, showPercent: clipElement.dataset.track === 'v1'});
+ let run = null;
+ return {element: component.element, update(value) {
+ if (value.run && value.run !== run) { component.update({state: 'waiting', fraction: 0}); run = value.run; }
+ component.element.dataset.run = run;
+ component.update(value);
+ }, dispose: () => component.destroy()};
+ };
+ tracks = module.createTracks(tracksHost, {state, sources: store.sources, t, actions, blockProgress});
+ listeners.push(notes.attach(tracks.element));
+ if (api.addEventListener && api.removeEventListener) {
+ progressConnection = createProgressConnection(api, receiveProgress); progressConnection.start();
+ }
+ if (panel.progressElement && typeof MutationObserver !== 'undefined') {
+ progressObserver = new MutationObserver(() => { for (const job of jobStatuses.values()) paintJob(job); });
+ progressObserver.observe(panel.progressElement, {subtree: true, childList: true, characterData: true, attributes: true, attributeFilter: ['aria-valuenow', 'hidden']});
+ }
+ const bar = tracks.element.querySelector('.fv-ed-track-zoom');
+ if (bar) {
+ zoomHost.append(bar);
+ for (const control of bar.querySelectorAll('button')) control.title = control.getAttribute('aria-label') || control.textContent;
+ }
+ for (const [id, value] of progress) tracks.setProgress(id, value);
+ tracks.setScrollLeft(editorViews.get(viewKey)?.scrollLeft);
+ })().catch(error).finally(() => {
+ // Every exit (including close and partial failure) settles readiness.
+ // After a completed start the saved baseline is already set; edits made since must stay unsaved.
+ if (initializing) { initializing = false; savedContent = content(state.record); }
+ title.disabled = false; genHost.inert = toolbar.inert = false;
+ tracksHost.inert = !tracks;
+ for (const host of [tracksHost, genHost, toolbar]) host.classList.remove('fv-ed-pending');
+ if (!closing && !disposed) { updateTop(); updateTransport(); }
+ });
+ updateTop(); return handle;
+}
diff --git a/web/editor_actions.js b/web/editor_actions.js
new file mode 100644
index 0000000..4c03c0e
--- /dev/null
+++ b/web/editor_actions.js
@@ -0,0 +1,94 @@
+// Shared selection actions (record is a parsed editor_model project):
+// linkedIds (record, ids) <-> linked picture/audio selection
+// splitAt (record, ids, frame, {by}) <-> Split (B)
+// trimAt (record, ids, frame, edge, {by}) <-> Trim before/after (Q/W)
+// removeParts (record, ids) <-> Delete / Backspace / Cut
+// removeGaps (record, gap|null) <-> Remove gaps / Delete a gap
+// duplicateParts (record, ids) <-> Duplicate (D)
+// copyTo (record, ids, at) <-> Copy + Paste at the playhead
+// moveParts (record, ids, {frames, track}) <-> release a group drag
+// Frames are integer timeline frames; move frames are a relative delta, clamped
+// at zero like a group drag. Tracks stay fixed: null keeps all original lanes;
+// an explicit track must be an original lane of the group. No snapping here.
+// A cut by the user (the default) takes the block from the agent; by: 'agent' keeps its mark.
+import * as model from './editor_model.js';
+import {assertUnlocked} from './editor_text_model.js';
+import {copyContent, pasteContent, playheadTargets, removableGaps} from './editor_room.js';
+
+const end = clip => clip.start + clip.frames;
+const codes = new Set(['busy', 'locked', 'audio_full', 'overlap', 'range', 'text']);
+const check = ok => { if (!ok) throw new model.EditError('range'); };
+// Low-level model/clipboard validation has additional codes. This API exposes
+// only the shared editing codes, without changing the page clipboard contract.
+function edit(run) {
+ try { return run(); }
+ catch (error) {
+ if (!(error instanceof model.EditError) || codes.has(error.code)) throw error;
+ throw new model.EditError('range');
+ }
+}
+function frameNumber(frame) { check(Number.isSafeInteger(frame) && frame >= 0 && frame <= 1e7); }
+export function linkedIds(record, ids) {
+ check(Array.isArray(ids) && ids.every(id => typeof id === 'string'));
+ return [...model.linkedIds(record, ids)];
+}
+function cutTargets(record, ids, frame) {
+ frameNumber(frame);
+ const targets = playheadTargets(record, linkedIds(record, ids), frame);
+ check(targets.length);
+ assertUnlocked(record, linkedIds(record, targets));
+ return targets;
+}
+export function splitAt(record, ids, frame, {by = 'user'} = {}) {
+ return edit(() => cutTargets(record, ids, frame).reduce((next, id) => model.split(next, id, frame, {by}), record));
+}
+export function trimAt(record, ids, frame, edge, {by = 'user'} = {}) {
+ check(['start', 'end'].includes(edge));
+ return edit(() => cutTargets(record, ids, frame).reduce((next, id) => model.trim(next, id, edge, frame, {minimumFrames: 1, by}), record));
+}
+export function removeParts(record, ids) {
+ return edit(() => model.remove(record, linkedIds(record, ids)));
+}
+export function removeGaps(record, gap) {
+ if (gap !== null) {
+ check(gap && record.tracks.some(track => track.id === gap.track));
+ frameNumber(gap.start);
+ }
+ const skipped = []; let removed = 0;
+ // Right to left keeps skipped timestamps relative to the input project.
+ for (const item of removableGaps(record, gap && {...gap, kind: 'gap'}).reverse()) {
+ try { record = edit(() => model.closeGap(record, item.track, item.start)); removed++; }
+ catch (error) {
+ if (!(error instanceof model.EditError) || !['busy', 'locked', 'overlap'].includes(error.code)) throw error;
+ skipped.push({start: item.start, track: error.track ?? item.track, code: error.code});
+ }
+ }
+ return {record, removed, skipped: skipped.reverse()};
+}
+function contentFor(record, ids) {
+ ids = linkedIds(record, ids);
+ return edit(() => {
+ try { return copyContent(record, ids); }
+ catch (error) {
+ if (error instanceof model.EditError && error.code === 'not_generated'
+ && ids.some(id => ['queued', 'running'].includes(model.find(record, id)?.pending))) throw new model.EditError('busy');
+ throw error;
+ }
+ });
+}
+export function duplicateParts(record, ids) {
+ ids = linkedIds(record, ids);
+ const content = contentFor(record, ids);
+ const at = Math.max(...record.tracks.flatMap(track => track.clips).filter(clip => ids.includes(clip.id)).map(end));
+ return edit(() => pasteContent(record, content, at));
+}
+export function copyTo(record, ids, at) {
+ frameNumber(at);
+ return edit(() => pasteContent(record, contentFor(record, ids), at));
+}
+export function moveParts(record, ids, offset) {
+ check(offset && Number.isSafeInteger(offset.frames));
+ ids = linkedIds(record, ids);
+ if (offset.track != null) check(record.tracks.some(track => track.id === offset.track && track.clips.some(clip => ids.includes(clip.id))));
+ return edit(() => model.moveTogether(record, ids, offset.frames));
+}
diff --git a/web/editor_adjust.css b/web/editor_adjust.css
new file mode 100644
index 0000000..eb40976
--- /dev/null
+++ b/web/editor_adjust.css
@@ -0,0 +1,35 @@
+.fv-editor .fv-ed-adjust-host{grid-column:2;grid-row:2/4;justify-self:end;width:264px;min-height:0;overflow:auto;padding:12px;border-left:1px solid var(--fv-border);background:var(--fv-bg);z-index:8;scrollbar-width:thin;scrollbar-color:var(--fv-border) transparent}
+.fv-editor .fv-ed-library{background:var(--fv-bg)}
+.fv-ed-adjust{min-width:0}
+.fv-ed-adjust-status{margin:0 0 12px;color:var(--fv-muted);font-size:13px;line-height:1.6}
+.fv-ed-adjust-controls{border:0;padding:0;margin:0;min-width:0;display:flex;flex-direction:column;gap:12px}
+.fv-ed-adjust-row{display:flex;align-items:center;gap:8px;min-width:0}
+.fv-ed-adjust-label{flex:none;font-size:13px}
+.fv-ed-adjust-row-controls{display:flex;align-items:center;justify-content:flex-end;gap:6px;flex:1;min-width:0}
+.fv-ed-adjust-slider{display:flex;align-items:center;gap:8px;flex:1;min-width:0}
+.fv-ed-adjust-slider input{width:0;min-width:0;flex:1;accent-color:var(--fv-accent)}
+.fv-ed-adjust-slider output{font-size:12px;font-variant-numeric:tabular-nums;min-width:36px;text-align:right}
+.fv-ed-adjust-number{flex:1;min-width:0}
+.fv-editor .fv-ed-adjust-number input{width:100%;height:32px;padding:4px 8px;border-radius:var(--fv-r-sm);font-size:13px;font-variant-numeric:tabular-nums}
+.fv-editor .fv-ed-adjust-button{height:32px;padding:0 8px}
+.fv-editor .fv-ed-adjust-segmented{width:100%;min-width:0}
+.fv-editor .fv-ed-adjust-segmented button{flex:1;padding:0 6px}
+.fv-editor .fv-ed-adjust-segmented button[aria-pressed=true]{background:var(--fv-raised);color:var(--fv-ink)}
+.fv-ed-adjust-toggle-control{display:flex;align-items:center;gap:8px;font-size:13px;cursor:pointer}
+.fv-ed-adjust-toggle-control input{accent-color:var(--fv-accent);width:15px;height:15px;margin:0}
+.fv-ed-adjust-controls:disabled :is(.fv-ed-adjust-label,output,.fv-ed-adjust-toggle-control span){opacity:.4}
+.fv-ed-adjust-controls :is(button,input):disabled{opacity:.4;cursor:default}
+.fv-editor .fv-ed-toolbar .fv-ed-adjust-toggle{flex:none}
+@media(min-width:1280px){.fv-editor .fv-ed-adjust-host{grid-column:3}}
+@media(max-width:1279px){
+ /* The drawer overlays its grid cell. Reserve picture space while open so it
+ stays centered in the visible preview, without moving any lower rows. */
+ .fv-editor[data-adjust-open=true] .fv-ed-preview,.fv-editor[data-adjust-open=true] .fv-ed-transport{margin-right:264px}
+}
+@media(max-width:680px){.fv-editor .fv-ed-adjust-host{grid-column:1}}
+@media(min-width:681px) and (max-width:800px){
+ .fv-editor[data-adjust-available=true] .fv-ed-toolbar{gap:4px}
+ .fv-editor[data-adjust-available=true] .fv-ed-toolbar button{padding-left:4px;padding-right:4px}
+ .fv-editor[data-adjust-available=true] .fv-ed-toolbar .fv-ed-zoom-slider{width:40px}
+ .fv-editor[data-adjust-available=true] .fv-ed-toolbar .fv-ed-previous span{display:none}
+}
diff --git a/web/editor_adjust.js b/web/editor_adjust.js
new file mode 100644
index 0000000..ed90610
--- /dev/null
+++ b/web/editor_adjust.js
@@ -0,0 +1,245 @@
+import {editorIcon} from './editor_icons.js';
+import {isText} from './editor_text_model.js';
+import {listenDialogKey} from './dialog_keys.js';
+// Shared adjustment shell. Tab owners keep their controls and editing policy here.
+const el = (tag, cls, text) => {
+ const node = document.createElement(tag);
+ if (cls) node.className = cls;
+ if (text != null) node.textContent = text;
+ return node;
+};
+const kinds = ['video', 'audio', 'speed', 'text', 'subtitle'];
+let serial = 0;
+
+// The existing editor action error and the adjustment controls share this copy.
+export const busyReason = t => t('Cancel generation before changing this part.', '先取消生成,再改这一段。');
+export function disabledReason(context, {needs, single = false} = {}) {
+ const {t} = context;
+ if (context.busy) return busyReason(t);
+ if (!context.single && !context.multiple) return t('Select a part first', '先选中一段');
+ if (single && context.multiple) return t('Only for a single part', '只能对单独一段调整');
+ if (needs === 'video' && !context.hasVideo) return t('This part has no video', '这一段没有画面');
+ if (needs === 'audio' && !context.hasAudio) return t('This part has no audio', '这一段没有声音');
+ return '';
+}
+
+function selectedContext(state, t, actions) {
+ const record = state.record, selection = state.selection;
+ const all = record.tracks.flatMap(track => track.clips.map(clip => ({...clip, track})));
+ const ids = new Set(selection?.kind === 'clip' ? selection.ids : []);
+ // Accept either half or both halves, including selection from another task.
+ for (const clip of all) if (ids.has(clip.id) || ids.has(clip.link)) {
+ ids.add(clip.id); if (clip.link) ids.add(clip.link);
+ }
+ const clips = all.filter(clip => ids.has(clip.id));
+ const seen = new Set(), parts = [];
+ for (const clip of clips) {
+ if ((!clip.source && !isText(clip)) || seen.has(clip.id)) continue;
+ parts.push(clip); seen.add(clip.id); if (clip.link) seen.add(clip.link);
+ }
+ const busy = clips.some(clip => ['queued', 'running'].includes(clip.pending)) ||
+ (record.replacements || []).some(tx => tx.originals.some(track => track.clips.some(clip => ids.has(clip.id))) &&
+ tx.clips.some(track => track.clips.some(clip => ['queued', 'running'].includes(clip.pending))));
+ return {clips, single: parts.length === 1, multiple: parts.length > 1,
+ hasVideo: clips.some(clip => clip.source && clip.track.kind === 'video'),
+ hasAudio: clips.some(clip => clip.source && clip.track.kind === 'audio'),
+ busy, record, t, state, actions, count: parts.length};
+}
+export function createAdjustPanel(host, {state, t, actions}) {
+ const shell = host.closest('.fv-editor'), uid = `fv-ed-adjust-${++serial}`;
+ host.classList.add('fv-ed-adjust-host');
+ const element = el('section', 'fv-ed-adjust'); element.id = uid;
+ element.setAttribute('aria-label', t('Adjust', '调整'));
+ const tabs = el('div', 'fv-ed-tabs fv-pass-mode'); tabs.setAttribute('role', 'tablist');
+ tabs.setAttribute('aria-label', t('Adjust', '调整'));
+ const status = el('p', 'fv-ed-adjust-status'); status.setAttribute('role', 'status');
+ const buttons = new Map(), panes = new Map(), entries = new Map();
+ const toggleButton = button('', {onClick: () => overlay ? close({restoreFocus: true}) : open()});
+ toggleButton.append(editorIcon('adjust')); toggleButton.setAttribute('aria-label', t('Adjust', '调整')); toggleButton.title = t('Adjust', '调整');
+ toggleButton.classList.add('fv-ed-adjust-toggle'); toggleButton.setAttribute('aria-controls', uid);
+ const labels = {video: t('Video', '画面'), audio: t('Audio', '声音'), speed: t('Speed', '速度'), text: t('Text', '文字'), subtitle: t('Subtitles', '字幕')};
+ for (const kind of kinds) {
+ const tab = button(labels[kind], {onClick: () => activate(kind)});
+ tab.id = `${uid}-${kind}-tab`; tab.dataset.adjustTab = kind;
+ tab.setAttribute('role', 'tab'); tab.setAttribute('aria-controls', `${uid}-${kind}`);
+ const pane = el('div', 'fv-ed-adjust-pane'); pane.id = `${uid}-${kind}`;
+ pane.setAttribute('role', 'tabpanel'); pane.setAttribute('aria-labelledby', tab.id);
+ const controls = el('fieldset', 'fv-ed-adjust-controls');
+ pane.append(controls); panes.set(kind, {pane, controls});
+ buttons.set(kind, tab); tabs.append(tab);
+ }
+ element.append(tabs, status, ...[...panes.values()].map(value => value.pane)); host.append(element);
+ const media = window.matchMedia?.('(min-width: 1280px)');
+ let narrow = media ? !media.matches : false, overlay = false, active = 'video', disposed = false;
+ let context = selectedContext(state, t, actions);
+ function renderActive() {
+ if (host.hidden) return;
+ const entry = entries.get(active);
+ if (entry && !entry.rendered) {
+ entry.rendered = true;
+ entry.component.render(panes.get(active).controls, context);
+ entry.component.update?.(context);
+ }
+ }
+ function paint() {
+ if (disposed) return;
+ const textKind = context.clips.length && context.clips.every(isText) ? context.clips[0].text_kind : null;
+ // Text and subtitle pages show alone for their own parts; the others only once registered.
+ const available = (textKind ? [textKind] : kinds.slice(0, 3)).filter(kind => entries.has(kind));
+ if (!available.includes(active)) active = available[0];
+ if (!available.length) overlay = false;
+ host.hidden = !available.length || (narrow && !overlay); toggleButton.hidden = !available.length || !narrow;
+ toggleButton.setAttribute('aria-expanded', String(narrow && overlay));
+ if (shell) { shell.dataset.adjustOpen = String(narrow && overlay); shell.dataset.adjustAvailable = String(!!available.length); }
+ status.textContent = context.multiple ? t(`${context.count} parts selected`, `已选 ${context.count} 段`) : '';
+ status.hidden = !context.multiple;
+ for (const kind of kinds) {
+ const tab = buttons.get(kind), {pane, controls} = panes.get(kind);
+ tab.hidden = !available.includes(kind);
+ tab.setAttribute('aria-selected', String(kind === active)); tab.tabIndex = kind === active ? 0 : -1;
+ pane.hidden = kind !== active;
+ const reason = textKind ? (context.clips.some(c => c.track.locked) ? 'locked' : '') : disabledReason(context, {needs: kind === 'speed' ? undefined : kind});
+ controls.disabled = !!reason; controls.title = '';
+ }
+ renderActive();
+ }
+ function activate(kind) { if (!disposed && entries.has(kind)) { if (active !== kind) entries.get(active)?.component.deactivate?.(); active = kind; paint(); } }
+ tabs.onkeydown = event => {
+ const directions = {ArrowLeft: -1, ArrowRight: 1};
+ if (!(event.key in directions) && event.key !== 'Home' && event.key !== 'End') return;
+ const available = kinds.filter(kind => entries.has(kind));
+ if (!available.length) return;
+ event.preventDefault(); event.stopPropagation();
+ const visible = kinds.filter(k => !buttons.get(k).hidden);
+ const index = event.key === 'Home' ? 0 : event.key === 'End' ? visible.length - 1
+ : (visible.indexOf(active) + directions[event.key] + visible.length) % visible.length;
+ activate(visible[index]); buttons.get(active).focus();
+ };
+ function update() {
+ if (disposed) return;
+ context = selectedContext(state, t, actions);
+ // Already rendered tabs stay current while hidden; unvisited tabs stay lazy.
+ const rendered = [...entries.values()].filter(entry => entry.rendered);
+ paint();
+ for (const entry of rendered) entry.component.update?.(context);
+ }
+ function register(kind, component) {
+ if (!kinds.includes(kind) || typeof component?.render !== 'function') throw new TypeError('Invalid adjustment tab');
+ if (disposed) throw new Error('Adjustment panel is disposed');
+ const previous = entries.get(kind); previous?.component.dispose?.();
+ panes.get(kind).controls.replaceChildren();
+ const entry = {component, rendered: false}; entries.set(kind, entry); paint();
+ // Optional unregister is useful when a separately loaded module goes away.
+ return () => {
+ if (disposed || entries.get(kind) !== entry) return;
+ const focused = buttons.get(kind) === document.activeElement || panes.get(kind).pane.contains(document.activeElement);
+ entries.delete(kind); component.dispose?.(); panes.get(kind).controls.replaceChildren(); paint();
+ if (focused && active && !host.hidden) buttons.get(active).focus();
+ };
+ }
+ function open() {
+ if (disposed || !entries.size) return;
+ if (narrow) overlay = true;
+ // Text and subtitle pages are always registered but only shown for their own parts.
+ paint(); if (active) buttons.get(active).focus();
+ }
+ function close({restoreFocus = false} = {}) {
+ if (disposed || !narrow || !overlay) return;
+ overlay = false; paint(); if (restoreFocus) toggleButton.focus();
+ }
+ function dismiss(event) {
+ if (!narrow || !overlay || disposed) return false;
+ event.preventDefault(); event.stopPropagation(); close({restoreFocus: true}); return true;
+ }
+ const outside = event => {
+ if (overlay && event.target.closest('.fv-ed-preview')) return;
+ if (overlay && !host.contains(event.target) && !toggleButton.contains(event.target)) close();
+ };
+ const escape = event => { if (event.key === 'Escape') dismiss(event); };
+ const resize = () => {
+ const focused = host.contains(document.activeElement);
+ narrow = !media.matches; overlay = false; paint();
+ if (narrow && focused && entries.size) toggleButton.focus();
+ else if (!narrow && document.activeElement === toggleButton) buttons.get(active)?.focus();
+ };
+ document.addEventListener('pointerdown', outside, true);
+ const stopEscape = listenDialogKey(document, 'keydown', escape);
+ media?.addEventListener('change', resize);
+ const unsubscribe = state.subscribe(event => { if (event.type === 'record' || event.type === 'selection') update(); });
+ paint();
+ function dispose() {
+ if (disposed) return;
+ disposed = true; unsubscribe();
+ document.removeEventListener('pointerdown', outside, true); stopEscape();
+ media?.removeEventListener('change', resize);
+ tabs.onkeydown = null; for (const tab of buttons.values()) tab.dispose(); toggleButton.dispose();
+ for (const entry of entries.values()) entry.component.dispose?.(); entries.clear();
+ if (shell) { delete shell.dataset.adjustOpen; delete shell.dataset.adjustAvailable; }
+ element.remove(); toggleButton.remove(); host.hidden = true;
+ }
+ return {element, register, update, dispose, open, close, disabledReason, toggleButton, dismiss};
+}
+
+// Builders return DOM nodes; owners set .value/.disabled/.title during update.
+export function row(label, ...controls) {
+ const element = el('div', 'fv-ed-adjust-row'), text = el('span', 'fv-ed-adjust-label', label);
+ const group = el('div', 'fv-ed-adjust-row-controls'); group.append(...controls); element.append(text, group);
+ group.setAttribute('role', 'group'); group.setAttribute('aria-label', label);
+ for (const control of controls) {
+ const inputs = control.matches('input') ? [control] : control.querySelectorAll('input');
+ for (const input of inputs) if (!input.getAttribute('aria-label')) input.setAttribute('aria-label', label);
+ }
+ return element;
+}
+function numeric(type, {min, max, step = 1, value = 0, format = String, onInput, onChange, title = '', label} = {}) {
+ const element = el('span', `fv-ed-adjust-${type}`), input = el('input'), output = el('output');
+ input.type = type === 'slider' ? 'range' : 'number'; input.step = String(step);
+ if (min != null) input.min = String(min); if (max != null) input.max = String(max);
+ element.title = title; if (label) input.setAttribute('aria-label', label);
+ const refresh = () => { output.textContent = format(Number(input.value)); };
+ let committed;
+ Object.defineProperties(element, {
+ value: {get: () => Number(input.value), set: value => { input.value = String(value); committed = Number(input.value); refresh(); }},
+ disabled: {get: () => input.disabled, set: value => { input.disabled = !!value; }},
+ });
+ element.input = input; element.output = output; element.value = value;
+ input.oninput = () => { refresh(); if (input.value !== '' && Number.isFinite(Number(input.value))) onInput?.(Number(input.value)); };
+ input.onchange = () => {
+ if (input.value === '' || !Number.isFinite(Number(input.value)) || input.validity?.valid === false) { input.value = String(committed); refresh(); return; }
+ const next = Number(input.value); refresh();
+ if (next !== committed) { committed = next; onChange?.(next); }
+ };
+ element.append(input); if (type === 'slider') element.append(output);
+ element.dispose = () => { input.oninput = input.onchange = null; };
+ return element;
+}
+export const slider = options => numeric('slider', options);
+export const number = options => numeric('number', options);
+export function button(label, {onClick, title = ''} = {}) {
+ const element = el('button', 'fv-ed-adjust-button', label); element.type = 'button'; element.title = title;
+ element.onclick = onClick; element.dispose = () => { element.onclick = null; }; return element;
+}
+export function segmented(options, {value, onChange} = {}) {
+ const element = el('div', 'fv-pass-mode fv-ed-adjust-segmented'); element.setAttribute('role', 'group');
+ let current = value;
+ const buttons = options.map(option => button(option.label, {onClick: () => {
+ if (current === option.value) return;
+ element.value = option.value; onChange?.(option.value);
+ }}));
+ const paint = () => buttons.forEach((control, index) => control.setAttribute('aria-pressed', String(options[index].value === current)));
+ Object.defineProperties(element, {
+ value: {get: () => current, set: value => { current = value; paint(); }},
+ disabled: {get: () => buttons.every(control => control.disabled), set: value => buttons.forEach(control => { control.disabled = !!value; })},
+ });
+ element.append(...buttons); paint(); element.dispose = () => buttons.forEach(control => control.dispose()); return element;
+}
+export function toggle(label, {value = false, onChange} = {}) {
+ const element = el('label', 'fv-ed-adjust-toggle-control'), input = el('input'); input.type = 'checkbox'; input.checked = !!value;
+ const text = el('span', '', label); element.append(input, text); input.setAttribute('aria-label', label);
+ Object.defineProperties(element, {
+ value: {get: () => input.checked, set: value => { input.checked = !!value; }},
+ disabled: {get: () => input.disabled, set: value => { input.disabled = !!value; }},
+ });
+ input.onchange = () => onChange?.(input.checked); element.input = input;
+ element.dispose = () => { input.onchange = null; }; return element;
+}
diff --git a/web/editor_adjust_picture.css b/web/editor_adjust_picture.css
new file mode 100644
index 0000000..07ef526
--- /dev/null
+++ b/web/editor_adjust_picture.css
@@ -0,0 +1,21 @@
+.fv-ed-adjust-picture .fv-ed-adjust-slider{flex:1.2}
+.fv-ed-adjust-picture .fv-ed-adjust-slider output[hidden]{display:none}
+.fv-ed-adjust-picture .fv-ed-adjust-row:has(.fv-ed-adjust-segmented){flex-direction:column;align-items:stretch}
+.fv-ed-adjust-picture .fv-ed-adjust-row:has(.fv-ed-adjust-segmented) .fv-ed-adjust-row-controls{width:100%}
+.fv-ed-adjust-picture .fv-ed-adjust-row:has(button) .fv-ed-adjust-row-controls{justify-content:stretch}
+.fv-ed-adjust-picture .fv-ed-adjust-row button{flex:1;font-size:11px;padding:0 4px;white-space:normal;line-height:1.15}
+.fv-ed-adjust-picture button[aria-pressed=true]{color:var(--fv-accent);border-color:var(--fv-accent)}
+.fv-ed-adjust-picture .fv-ed-adjust-row[hidden],.fv-ed-adjust-picture button[hidden]{display:none}
+/* Leave a visible picture and its handles alongside the drawer on phones. */
+@media(max-width:560px){
+ .fv-editor[data-adjust-open=true] .fv-ed-preview,.fv-editor[data-adjust-open=true] .fv-ed-transport{margin-right:220px}
+ .fv-editor .fv-ed-adjust-host{width:220px}
+}
+
+.fv-ed-adjust-picture .fv-ed-adjust-number{display:flex;align-items:center;gap:3px}
+.fv-ed-adjust-picture .fv-ed-adjust-number[data-axis]:before{content:attr(data-axis);font-size:11px;color:var(--fv-muted)}
+.fv-ed-adjust-picture .fv-ed-adjust-number[data-unit]:after{content:attr(data-unit);font-size:11px;color:var(--fv-muted)}
+.fv-ed-adjust-picture .fv-ed-adjust-number input{min-width:0;padding:4px}
+
+.fv-ed-picture-input-error{margin:0;color:var(--fv-warning);font-size:12px}
+.fv-ed-picture-input-error[hidden]{display:none}
diff --git a/web/editor_adjust_picture.js b/web/editor_adjust_picture.js
new file mode 100644
index 0000000..08ca6d9
--- /dev/null
+++ b/web/editor_adjust_picture.js
@@ -0,0 +1,123 @@
+import {row, slider, number, button, disabledReason} from './editor_adjust.js';
+import {PICTURE_DEFAULTS, pictureFields} from './editor_picture_fields.js';
+import {pictureSession} from './editor_picture_session.js';
+export const scaleFromSlider = value => Math.abs(value) < .025 ? 1 : 10 ** value;
+export const quarterTurn = (angle, delta) => ((angle + delta + 540) % 360) - 180;
+export function createAdjustPicture({state, sources, t, player, notes = null}) {
+ const session = pictureSession(state, t), widgets = [], numbers = {};
+ let visibilityObserver, inputError, invalidClip;
+ let context, container, clip, scale, reset, crop, cropActions, flips, scaleDrag = null;
+ const keep = node => { if (node.tagName === 'BUTTON') node.setAttribute('aria-label', node.textContent); widgets.push(node); return node; };
+ const change = fields => { if (clip && !container.disabled) session.change(clip.id, fields); };
+ const numeric = (key, label, min, max, factor = 1, suffix = '') => {
+ const control = keep(number({min, max, step: 'any', label: label + suffix,
+ onChange: value => { if (!control.input.dataset.editClip || control.input.dataset.editClip === clip?.id) change({[key]: value / factor}); }}));
+ control.input.dataset.pictureField = key;
+ const input = control.input.oninput, commit = control.input.onchange;
+ const remember = () => { control.input.dataset.editing = 'true'; control.input.dataset.editClip ||= clip?.id || ''; };
+ const clearError = () => { if (inputError) inputError.hidden = true; invalidClip = null; control.input.removeAttribute('aria-invalid'); };
+ const submit = event => {
+ if (control.input.dataset.editClip === clip?.id && (control.input.value === '' || !Number.isFinite(Number(control.input.value))
+ || Number(control.input.value) < min || Number(control.input.value) > max)) {
+ inputError.textContent = t(`${label}: enter a number from ${min} to ${max}${suffix}.`, `${label}:请输入 ${min} 到 ${max}${suffix} 之间的数值。`);
+ inputError.hidden = false; invalidClip = clip?.id; control.input.setAttribute('aria-invalid', 'true'); return;
+ }
+ clearError();
+ // Native number inputs also emit change for spinner/arrow steps. Q13
+ // commits only at blur/Enter, keeping the text's native undo intact.
+ control.input.dataset.editing = 'false'; commit(event);
+ delete control.input.dataset.editClip; update();
+ };
+ control.input.oninput = event => { clearError(); remember(); input(event); };
+ control.input.onchange = () => {};
+ control.input.onblur = submit;
+ if (suffix) control.dataset.unit = suffix.trim();
+ if (key.startsWith('offset_')) control.dataset.axis = key.endsWith('x') ? 'X' : 'Y';
+ control.input.onkeydown = event => {
+ if (event.isComposing || event.keyCode === 229) { event.stopPropagation(); return; }
+ if (event.key === 'Enter') { event.preventDefault(); event.stopPropagation(); submit(event); return; }
+ if (event.key === 'Escape' && !session.draft) {
+ event.preventDefault(); event.stopPropagation();
+ clearError(); control.input.dataset.editing = 'false'; delete control.input.dataset.editClip; update(); return;
+ }
+ if (!['ArrowUp', 'ArrowDown'].includes(event.key)) return;
+ event.preventDefault(); event.stopPropagation(); clearError(); remember();
+ control.input.value = String(Math.min(max, Math.max(min, Number(control.input.value) + (event.key === 'ArrowUp' ? 1 : -1) * (event.shiftKey ? 10 : 1))));
+ input(event);
+ };
+ numbers[key] = {control, factor}; return control;
+ };
+ function update(ctx = context) {
+ if (!ctx || !container) return; context = ctx;
+ notes?.update(ctx);
+ clip = ctx.clips.find(c => c.track.kind === 'video' && c.source);
+ const seen = new Set(); let count = 0;
+ for (const item of ctx.clips) { if (!seen.has(item.id)) count++; seen.add(item.id); if (item.link) seen.add(item.link); }
+ const reason = disabledReason({...ctx, multiple: ctx.multiple || count > 1}, {needs: 'video', single: true}) || session.editReason(clip);
+ if (container.disabled !== !!reason) container.disabled = !!reason; container.title = '';
+ if (inputError && invalidClip !== clip?.id) { inputError.hidden = true; invalidClip = null; }
+ const current = {...PICTURE_DEFAULTS, ...session.clip(clip)};
+ for (const [key, {control, factor}] of Object.entries(numbers)) {
+ if (document.activeElement !== control.input || control.input.dataset.editing !== 'true' || control.input.dataset.editClip !== clip?.id || session.draft) { control.value = Number((current[key] * factor).toFixed(4)); control.input.removeAttribute('aria-invalid'); }
+ }
+ if (session.draft?.mode !== 'slider') scale.value = Math.log10(current.scale);
+ scale.input.setAttribute('aria-valuetext', `${Math.round(current.scale * 100)}%`);
+ flips.forEach(([key, control]) => control.setAttribute('aria-pressed', String(current[key])));
+ cropActions.hidden = session.draft?.mode !== 'crop'; crop.setAttribute('aria-pressed', String(!cropActions.hidden));
+ reset.hidden = !clip || !Object.keys(pictureFields({...current, fit: 'cover'})).length;
+ }
+ const dragScale = event => {
+ if (!scaleDrag || event.pointerId !== scaleDrag.pointer) return;
+ const value = Math.max(-1, Math.min(1, (event.clientX-scaleDrag.left-8) / Math.max(1,scaleDrag.width-16) * 2-1));
+ scale.input.value = String(value); session.preview({scale: scaleFromSlider(value)});
+ };
+ const endScale = event => {
+ if (!scaleDrag || event.pointerId !== scaleDrag.pointer) return;
+ scaleDrag = null; event.type === 'pointercancel' ? session.cancel() : session.commit();
+ };
+ window.addEventListener('pointermove', dragScale, true); window.addEventListener('pointerup', endScale, true); window.addEventListener('pointercancel', endScale, true);
+ const unsubscribe = session.subscribe(() => { if (!session.draft) scaleDrag = null; update(); });
+ return {
+ render(host, ctx) {
+ container = host; context = ctx; host.classList.add('fv-ed-adjust-picture');
+ // The description stays editable on blocks the picture controls cannot change yet (drafts).
+ if (notes) host.parentNode.insertBefore(notes.element, host);
+ // Observe the shell's existing visibility contract without changing its
+ // lifecycle API (the shell is owned by the adjustment-panel task).
+ const pane = host.closest('[role=tabpanel]'), panel = host.closest('.fv-ed-adjust-host');
+ const visibility = () => session.setPanelOpen(!pane?.hidden && !panel?.hidden);
+ visibilityObserver = typeof MutationObserver === 'function' ? new MutationObserver(visibility) : null;
+ for (const node of [pane, panel]) if (node) visibilityObserver?.observe(node, {attributes: true, attributeFilter: ['hidden']});
+ // Fill or Fit lives only in the switch at the preview's top left (one place per function).
+ scale = keep(slider({min: -1, max: 1, step: .001, value: 0, label: t('Scale', '缩放'),
+ onInput: value => { if (!clip) return; session.begin(clip.id, 'slider'); session.preview({scale: scaleFromSlider(value)}); },
+ onChange: () => session.commit()}));
+ scale.input.dataset.pictureField = 'scale-slider'; scale.output.hidden = true;
+ scale.input.onpointerdown = event => {
+ if (event.button !== 0 || !clip || container.disabled) return;
+ event.preventDefault(); scale.input.focus();
+ const rect = scale.input.getBoundingClientRect(); session.begin(clip.id, 'slider');
+ scaleDrag = {pointer:event.pointerId,left:rect.left,width:rect.width};
+ scale.input.setPointerCapture?.(event.pointerId); dragScale(event);
+ };
+ const scaleNumber = numeric('scale', t('Scale', '缩放'), 10, 1000, 100, ' %');
+ const position = row(t('Position', '位置'), numeric('offset_x', 'X', -200, 200, 100, ' %'), numeric('offset_y', 'Y', -200, 200, 100, ' %'));
+ for (const [key, label] of [['offset_x', 'X %'], ['offset_y', 'Y %']]) numbers[key].control.input.title = label;
+ const turns = row('', ...[-90, 90].map(delta => keep(button(delta < 0 ? t('Rotate left 90°', '左转 90°') : t('Rotate right 90°', '右转 90°'),
+ {onClick: () => change({rotate: quarterTurn(clip?.rotate || 0, delta)})}))));
+ flips = [['flip_h', t('Flip horizontally', '水平翻转')], ['flip_v', t('Flip vertically', '垂直翻转')]].map(([key, label]) => {
+ const b = keep(button(label, {onClick: () => change({[key]: !clip?.[key]})})); b.dataset.pictureField = key; b.setAttribute('aria-pressed', 'false'); return [key, b];
+ });
+ crop = keep(button(t('Crop', '裁剪'), {onClick: () => { if (clip) { player?.pause(); session.begin(clip.id, 'crop'); } }})); crop.classList.add('fv-ed-picture-crop');
+ cropActions = row('', keep(button(t('Done', '完成'), {onClick: () => session.commit()})), keep(button(t('Cancel', '取消'), {onClick: () => session.cancel()})));
+ cropActions.classList.add('fv-ed-picture-crop-actions');
+ reset = keep(button(t('Reset', '恢复原样'), {onClick: () => change({...PICTURE_DEFAULTS, fit: clip?.fit || 'cover'})})); reset.classList.add('fv-ed-picture-reset');
+ inputError = document.createElement('p'); inputError.className = 'fv-ed-picture-input-error'; inputError.setAttribute('role', 'status'); inputError.hidden = true;
+ host.append(row(t('Scale', '缩放'), scale, scaleNumber), position,
+ row(t('Rotation', '旋转'), numeric('rotate', t('Rotation', '旋转'), -180, 180, 1, ' °')), turns,
+ row('', ...flips.map(([, b]) => b)), crop, cropActions, inputError, reset);
+ visibility();
+ }, update, deactivate: () => session.setPanelOpen(false),
+ dispose() { visibilityObserver?.disconnect(); session.setPanelOpen(false); unsubscribe(); window.removeEventListener('pointermove', dragScale, true); window.removeEventListener('pointerup', endScale, true); window.removeEventListener('pointercancel', endScale, true); if (scale) scale.input.onpointerdown = null; for (const w of widgets) { if(w.input) {w.input.onkeydown = null; w.input.onblur = null;} w.dispose(); } },
+ };
+}
diff --git a/web/editor_entry.js b/web/editor_entry.js
new file mode 100644
index 0000000..d6ae04f
--- /dev/null
+++ b/web/editor_entry.js
@@ -0,0 +1,37 @@
+// The existing views call these small adapters; editor logic stays in editor.js.
+import {openEditor} from './editor.js';
+import {api} from '../../scripts/api.js';
+import {app} from '../../scripts/app.js';
+import {openStudio, showNodes} from './studio.js';
+import {viewChanged} from './view_navigation.js';
+function editorPanel(node) {
+ const values = Object.fromEntries((node.widgets || []).filter(widget => widget.name).map(widget => [widget.name, widget.value]));
+ return {node: node.id, width: values.width, height: values.height, text: values.text || '', settings: Object.fromEntries(Object.entries({
+ two_pass: values.two_pass, base_steps: values.base_steps, refine_steps: values.refine_steps,
+ seed: values.seed, sampling_effort: values.sampling_effort}).filter(([, value]) => value !== undefined)),
+ async snapshot() {
+ if (node.freevideoEditorLooping?.()) throw new Error('loop_active');
+ const value = structuredClone(await app.graphToPrompt());
+ return {node: String(node.id), prompt: value.output, extra_data: {extra_pnginfo: {workflow: value.workflow || {}}}};
+ }};
+}
+export function openEditorView(node, {studio} = {}) {
+ studio?.querySelectorAll('video,audio').forEach(media => media.pause());
+ const panel = editorPanel(node);
+ const progressElement = studio?.querySelector('.fv-generation-progress');
+ if (progressElement) {
+ panel.progressElement = progressElement;
+ panel.progressSnapshot = message => {
+ if (node.freevideoProgress?.chain?.id !== message.chain?.id || node.freevideoProgress?.chain?.block !== message.chain?.block || progressElement.hidden) return null;
+ const number = progressElement.querySelector('.fv-generation-count')?.textContent?.match(/(\d+)%/);
+ return number ? {percent: Number(number[1])} : {percent: 0};
+ };
+ }
+ const handle = openEditor({api, app, panel, onView(view) {
+ if (view === 'nodes') showNodes(node, studio);
+ else if (studio?.open) viewChanged('studio', node);
+ else openStudio(node);
+ }});
+ viewChanged('editor', node);
+ return handle;
+}
diff --git a/web/editor_export_dialog.css b/web/editor_export_dialog.css
new file mode 100644
index 0000000..a4d50f5
--- /dev/null
+++ b/web/editor_export_dialog.css
@@ -0,0 +1,28 @@
+.fv-ed-export-dialog{box-sizing:border-box;position:fixed;inset:0;margin:auto;width:480px;max-width:calc(100vw - 32px);height:fit-content;max-height:calc(100dvh - 32px);overflow:auto;padding:24px;border:1px solid var(--fv-border);border-radius:var(--fv-r-lg);background:var(--fv-card);color:var(--fv-ink);font:13px/1.6 var(--fv-font);box-shadow:0 24px 80px #0006}
+.fv-ed-export-dialog::backdrop{background:#070a0db8}
+.fv-ed-export-dialog h2{margin:0 0 24px;font-size:20px;line-height:1.4;font-weight:600}
+.fv-ed-export-rows{display:flex;flex-direction:column;gap:16px}
+.fv-ed-export-row{display:grid;grid-template-columns:68px minmax(0,1fr);align-items:center;gap:12px;min-width:0}
+.fv-ed-export-label{color:var(--fv-muted)}
+.fv-ed-export-format{display:block;grid-column:2}
+.fv-ed-export-segments{display:flex;min-width:0;padding:3px;gap:2px;border:1px solid var(--fv-border);border-radius:10px;background:var(--fv-bg)}
+.fv-ed-export-dialog .fv-ed-export-segments button{flex:1;min-width:0;height:auto;min-height:28px;padding:4px 5px;border:0;border-radius:7px;background:transparent;color:var(--fv-muted);font-size:12px;line-height:1.4;white-space:normal;overflow-wrap:normal}
+.fv-ed-export-dialog .fv-ed-export-segments button[aria-pressed=true]{background:var(--fv-raised);color:var(--fv-ink);font-weight:600}
+.fv-ed-export-dialog .fv-ed-export-segments button:hover:not(:disabled){background:var(--fv-hover)}
+.fv-ed-export-notices{border-top:1px solid var(--fv-border);padding-top:20px;margin-top:24px;font-size:12px}
+.fv-ed-export-notices p{margin:0}
+.fv-ed-export-crop{color:var(--fv-warning)}
+.fv-ed-export-gap,.fv-ed-export-pending{color:var(--fv-muted)}
+.fv-ed-export-links{display:flex;flex-wrap:wrap;gap:16px;margin:8px 0}
+.fv-ed-export-dialog .fv-ed-export-links button{height:auto;min-height:24px;padding:0;border:0;background:transparent;color:var(--fv-accent);font-size:12px}
+.fv-ed-export-footer{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px;margin-top:24px}
+.fv-ed-export-summary{color:var(--fv-muted);font-size:12px;font-variant-numeric:tabular-nums}
+.fv-ed-export-buttons{display:flex;gap:8px;margin-left:auto}
+.fv-ed-export-dialog .fv-ed-export-buttons button{padding:7px 14px}
+@media(max-width:520px){
+ .fv-ed-export-dialog{padding:20px}
+ .fv-ed-export-row{grid-template-columns:1fr;gap:6px}
+ .fv-ed-export-format{grid-column:1}
+ .fv-ed-export-rows{gap:12px}
+ .fv-ed-export-dialog .fv-ed-export-segments button{min-height:32px}
+}
diff --git a/web/editor_export_dialog.js b/web/editor_export_dialog.js
new file mode 100644
index 0000000..412ec50
--- /dev/null
+++ b/web/editor_export_dialog.js
@@ -0,0 +1,196 @@
+import * as model from './editor_model.js';
+import {clipPictureSize, differentPictureShape} from './editor_frame.js';
+import {transportTime} from './editor_player.js';
+import {isolateDialogKeys, listenDialogKey, routeDialogKey} from './dialog_keys.js';
+
+export const EXPORT_SETTINGS_KEY = 'freevideo.editor.export-settings';
+const defaults = {short: null, quality: 'high', range: 'whole', only: null, sound_format: 'm4a'};
+const active = new WeakSet();
+const style = document.createElement('link');
+style.rel = 'stylesheet'; style.href = new URL('editor_export_dialog.css', import.meta.url).href;
+const stylesReady = 'sheet' in style ? new Promise(resolve => { style.onload = style.onerror = resolve; }) : Promise.resolve();
+document.head.append(style);
+const el = (tag, cls, text) => {
+ const value = document.createElement(tag); value.className = cls;
+ if (text != null) value.textContent = text;
+ return value;
+};
+
+export function exportSizes(record) {
+ const short = Math.min(record.width, record.height);
+ return [{short: null, width: record.width, height: record.height}, ...[1080, 720, 480].filter(n => n < short).map(n => ({
+ short: n, width: Math.floor(record.width * n / short / 2) * 2, height: Math.floor(record.height * n / short / 2) * 2,
+ }))];
+}
+
+// Q14: a drawn range or a gap is its own span; selected parts run from the earliest start to the latest end.
+export function exportRange(record, selection) {
+ let from, to;
+ if (['range', 'gap'].includes(selection?.kind)) { from = selection.start; to = selection.start + selection.frames; }
+ else if (selection?.kind === 'clip') {
+ const ids = model.linkedIds(record, selection.ids), parts = record.tracks.flatMap(track => track.clips).filter(clip => ids.has(clip.id));
+ if (!parts.length) return null;
+ from = Math.min(...parts.map(clip => clip.start)); to = Math.max(...parts.map(clip => clip.start + clip.frames));
+ } else return null;
+ const start = Math.max(0, from), end = Math.min(model.exportFrames(record), to);
+ return Number.isSafeInteger(start) && Number.isSafeInteger(end) && end > start ? {start, frames: end - start} : null;
+}
+
+function settings(record, selection, value) {
+ value = value && typeof value === 'object' ? value : {};
+ return {
+ short: exportSizes(record).some(size => size.short === value.short) ? value.short : defaults.short,
+ quality: ['high', 'standard', 'small'].includes(value.quality) ? value.quality : defaults.quality,
+ range: value.range === 'selected' && exportRange(record, selection) ? 'selected' : 'whole',
+ only: value.only === 'sound' ? 'sound' : null,
+ sound_format: value.sound_format === 'wav' ? 'wav' : 'm4a',
+ };
+}
+
+export function exportOptions(record, selection, value) {
+ const clean = settings(record, selection, value), options = {};
+ if (clean.only === 'sound') { options.only = 'sound'; options.sound_format = clean.sound_format; }
+ else {
+ if (clean.quality !== 'high') options.quality = clean.quality;
+ if (clean.short != null) options.short = clean.short;
+ }
+ if (clean.range === 'selected') options.range = exportRange(record, selection);
+ return options;
+}
+
+const overlapping = (clip, range) => !range || clip.start < range.start + range.frames && clip.start + clip.frames > range.start;
+// Q16: sound-only needs some sound in the range.
+export const hasSound = (record, range) => record.tracks.some(track => track.kind === 'audio'
+ && track.clips.some(clip => clip.source && clip.volume !== 0 && overlapping(clip, range)));
+// Q15: seconds of picture still generating with no earlier version; they export as black.
+export function generatingSeconds(record, range) {
+ const start = range?.start ?? 0, stop = range ? range.start + range.frames : model.exportFrames(record);
+ const frames = record.tracks[0].clips.filter(clip => !clip.source && ['queued', 'running'].includes(clip.pending))
+ .reduce((sum, clip) => sum + Math.max(0, Math.min(stop, clip.start + clip.frames) - Math.max(start, clip.start)), 0);
+ return Math.ceil(frames / model.FPS);
+}
+function croppedParts(record, sources, range) {
+ return record.tracks[0].clips.filter(clip => clip.fit !== 'contain'
+ && (!range || clip.start < range.start + range.frames && clip.start + clip.frames > range.start)
+ && differentPictureShape(clipPictureSize(clip, sources), record));
+}
+
+export async function openExportDialog({parent, state, sources, t = en => en, onError = () => {}}) {
+ // Only the first trigger owns confirmation, even while the stylesheet loads.
+ if (active.has(parent)) return null;
+ let resolve;
+ const result = new Promise(done => { resolve = done; });
+ active.add(parent);
+ await stylesReady;
+ if (!parent.isConnected || !parent.open) { active.delete(parent); resolve(null); return result; }
+ let saved;
+ try { saved = JSON.parse(localStorage.getItem(EXPORT_SETTINGS_KEY)); } catch { /* Private browsing or old data. */ }
+ const value = settings(state.record, state.selection, saved), returnFocus = document.activeElement;
+ const dialog = el('dialog', 'fv-ed-export-dialog');
+ dialog.setAttribute('aria-label', t('Export', '导出'));
+ const heading = el('h2', '', t('Export', '导出')), rows = el('div', 'fv-ed-export-rows');
+ const notices = el('div', 'fv-ed-export-notices');
+ const links = el('div', 'fv-ed-export-links'), footer = el('div', 'fv-ed-export-footer');
+ const summary = el('span', 'fv-ed-export-summary'), buttons = el('div', 'fv-ed-export-buttons');
+ const button = (label, action, cls = '') => {
+ const node = el('button', cls, label); node.type = 'button'; node.onclick = action; return node;
+ };
+ const groups = [];
+ function group(name, label, choices, host = rows) {
+ const row = el('div', 'fv-ed-export-row'), title = el('span', 'fv-ed-export-label', label);
+ const controls = el('div', 'fv-ed-export-segments');
+ controls.setAttribute('role', 'group'); controls.setAttribute('aria-label', label); controls.dataset.option = name;
+ for (const [choice, text] of choices) {
+ const node = button(text, () => { value[name] = choice; update(); });
+ node.dataset.value = String(choice ?? 'same'); controls.append(node);
+ }
+ row.append(title, controls); host.append(row); groups.push({name, row, controls, choices});
+ return row;
+ }
+ group('short', t('Frame size', '画面大小'), exportSizes(state.record).map(size => [size.short,
+ size.short == null ? t('Same as the edit', '与剪辑相同') : `${size.width} × ${size.height}`]));
+ group('quality', t('Quality', '画质'), [['high', t('High', '高')], ['standard', t('Standard', '标准')], ['small', t('Small file', '省空间')]]);
+ group('range', t('Range', '范围'), [['whole', t('Whole edit', '整条')], ['selected', t('Selected range', '选中的范围')]]);
+ const contentRow = group('only', t('Content', '内容'), [[null, t('Video and audio', '画面和声音')], ['sound', t('Audio only', '只声音')]]);
+ const formatRow = group('sound_format', t('Audio only', '只声音'), [['m4a', 'M4A'], ['wav', 'WAV']], contentRow);
+ formatRow.classList.add('fv-ed-export-format'); formatRow.querySelector('.fv-ed-export-label').hidden = true;
+ const selectedRange = () => value.range === 'selected' ? exportRange(state.record, state.selection) : null;
+ const affected = () => croppedParts(state.record, sources, selectedRange());
+ const review = button(t('Review them', '逐段查看'), () => {
+ const parts = affected(), ids = state.selection?.ids || [], index = parts.findIndex(c => ids.includes(c.id));
+ const clip = parts[(index + 1) % parts.length];
+ close(null);
+ if (clip) { state.select({kind: 'clip', ids: [clip.id]}); state.seek(clip.start); }
+ });
+ const fit = button(t('Fit all', '全部完整显示'), () => {
+ try { state.apply(t('Fit all', '全部完整显示'), record => affected().reduce((r, clip) => model.setPictureFit(r, clip.id, 'contain'), record)); }
+ catch (error) { onError(error); }
+ update();
+ });
+ const pending = el('p', 'fv-ed-export-pending');
+ links.append(review, fit); notices.append(pending, links);
+ const cancel = button(t('Cancel', '取消'), () => close(null), 'fv-ed-export-cancel');
+ const confirm = button(t('Export', '导出'), () => {
+ try { localStorage.setItem(EXPORT_SETTINGS_KEY, JSON.stringify(value)); } catch { /* Export still works without storage. */ }
+ close(exportOptions(state.record, state.selection, value));
+ }, 'fv-primary fv-ed-export-confirm');
+ buttons.append(cancel, confirm); footer.append(summary, buttons); dialog.append(heading, rows, notices, footer);
+ function update() {
+ if (!exportRange(state.record, state.selection)) value.range = 'whole';
+ const audible = hasSound(state.record, selectedRange());
+ if (!audible) value.only = null;
+ const sound = value.only === 'sound';
+ for (const {name, controls, choices} of groups) [...controls.children].forEach((node, i) => {
+ node.setAttribute('aria-pressed', String(value[name] === choices[i][0]));
+ node.disabled = sound && ['short', 'quality'].includes(name)
+ || name === 'range' && choices[i][0] === 'selected' && !exportRange(state.record, state.selection)
+ || name === 'only' && choices[i][0] === 'sound' && !audible;
+ });
+ formatRow.hidden = !sound;
+ const range = selectedRange(), parts = affected(), n = parts.length;
+ const seconds = sound ? 0 : generatingSeconds(state.record, range);
+ pending.hidden = !seconds;
+ pending.textContent = t(`${seconds} s still generating; that part exports as black.`, `有 ${seconds} 秒还在生成,导出后这部分是黑屏`);
+ links.hidden = sound || !n; notices.hidden = links.hidden && pending.hidden;
+ fit.disabled = parts.some(clip => ['queued', 'running'].includes(clip.pending));
+ const size = exportSizes(state.record).find(size => size.short === value.short) || state.record;
+ // Same rounding as the player's total, so one edit never reads 0:31 there and 0:32 here.
+ const total = model.exportFrames(state.record), part = range && !(range.start === 0 && range.frames === total);
+ const time = part ? `${transportTime(range.start)} – ${transportTime(range.start + range.frames)}` : transportTime(total);
+ summary.textContent = `${time} · ${sound ? value.sound_format.toUpperCase() : `${size.width} × ${size.height}`}`;
+ }
+ let closed = false;
+ const cleanups = [];
+ function close(options) {
+ if (closed) return;
+ closed = true; cleanups.splice(0).forEach(stop => stop());
+ if (dialog.open) dialog.close(); dialog.remove(); active.delete(parent);
+ if (returnFocus?.isConnected) returnFocus.focus({preventScroll: true});
+ resolve(options);
+ }
+ cleanups.push(listenDialogKey(dialog, 'keydown', event => {
+ if (event.key === 'Escape') { event.preventDefault(); close(null); }
+ else if (event.key === 'Tab') {
+ event.preventDefault();
+ const focusable = [...dialog.querySelectorAll('button')].filter(node => !node.disabled && !node.closest('[hidden]'));
+ const current = focusable.indexOf(document.activeElement);
+ focusable[(current + (event.shiftKey ? -1 : 1) + focusable.length) % focusable.length]?.focus();
+ }
+ }));
+ dialog.oncancel = event => { event.preventDefault(); event.stopPropagation(); close(null); };
+ dialog.onclose = () => close(null);
+ // Parent and host capture shortcuts must route to this modal before the editor.
+ cleanups.push(isolateDialogKeys(dialog, event => routeDialogKey(event, dialog)));
+ const parentClosed = () => close(null);
+ parent.addEventListener('close', parentClosed);
+ cleanups.push(() => parent.removeEventListener('close', parentClosed), state.subscribe(update));
+ // Pointer events stay inside the modal; names stay literal for the shared key-listener guard.
+ const stop = event => event.stopPropagation();
+ dialog.addEventListener('pointermove', stop); dialog.addEventListener('mousemove', stop);
+ dialog.addEventListener('pointerdown', stop); dialog.addEventListener('pointerup', stop);
+ dialog.addEventListener('mousedown', stop); dialog.addEventListener('mouseup', stop);
+ dialog.addEventListener('click', stop); dialog.addEventListener('dblclick', stop);
+ dialog.addEventListener('wheel', stop); dialog.addEventListener('contextmenu', stop);
+ parent.append(dialog); update(); dialog.showModal(); confirm.focus();
+ return result;
+}
diff --git a/web/editor_frame.css b/web/editor_frame.css
new file mode 100644
index 0000000..c1a580e
--- /dev/null
+++ b/web/editor_frame.css
@@ -0,0 +1,32 @@
+/* Keep the preview row height. Visible tools reserve 30px + an 8px gap
+ above the picture; the remaining area retains the existing 16px inset. */
+.fv-editor .fv-ed-preview{position:relative}
+.fv-editor .fv-ed-preview:has(>.fv-ed-picture-tools:not([hidden])){padding-top:54px}
+.fv-ed-picture{height:min(100cqh,calc(100cqw * var(--fv-ed-height,9) / var(--fv-ed-width,16)));transition:width 150ms ease,height 150ms ease}
+.fv-ed-picture[data-playing=true]{transition:none}
+@media(prefers-reduced-motion:reduce){.fv-ed-picture{transition:none}}
+.fv-ed-crop-shade{position:absolute;inset:0;pointer-events:none;z-index:2}
+.fv-ed-crop-shade>div{position:absolute;background:rgba(0,0,0,.65)}
+.fv-ed-crop-top{top:0;left:0;right:0}.fv-ed-crop-bottom{bottom:0;left:0;right:0}
+.fv-ed-crop-left{left:0;top:0;bottom:0}.fv-ed-crop-right{right:0;top:0;bottom:0}
+.fv-ed-picture-tools{position:absolute;top:16px;left:16px;z-index:3;display:flex;width:max-content;gap:2px;padding:2px;border:1px solid var(--fv-border);border-radius:6px;background:var(--fv-bg)}
+.fv-editor .fv-ed-picture-tools button{flex:none;height:24px;padding:0 7px;border:0;border-radius:4px;background:transparent;color:var(--fv-muted);font-size:11px;white-space:nowrap}
+.fv-editor .fv-ed-picture-tools button[aria-pressed=true]{background:var(--fv-raised);color:var(--fv-ink)}
+.fv-ed-clip{container-type:inline-size}
+.fv-ed-picture-badge{position:absolute;right:8px;top:5px;max-width:calc(100% - 12px);height:22px;display:flex;align-items:center;gap:3px;padding:2px 4px;border:1px solid var(--fv-warning);border-radius:4px;background:var(--fv-bg);color:var(--fv-warning);z-index:5;white-space:nowrap;font-size:11px;line-height:16px}
+.fv-ed-picture-badge svg{width:14px;height:14px;flex:none;stroke:currentColor;stroke-width:1.3;fill:none}
+.fv-ed-picture-badge[data-fit=contain]{border-color:var(--fv-muted);color:var(--fv-muted)}
+@container(max-width:84px){.fv-ed-picture-badge[data-fit=contain] .fv-ed-picture-badge-label{display:none}}
+@container(max-width:64px){.fv-ed-picture-badge-label{display:none}.fv-ed-picture-badge{right:3px;padding:2px}}
+.fv-ed-picture-size-menu{display:flex;flex-direction:column}
+/* Options sit indented under 画面大小; the chosen one carries a check. */
+.fv-editor .fv-ed-picture-size-menu button{padding:0 10px 0 14px}
+.fv-ed-picture-size-menu button:before{content:'';display:inline-block;width:12px;flex:none;margin-right:8px;color:var(--fv-accent)}
+.fv-ed-picture-size-menu button[aria-checked=true]:before{content:'✓'}
+.fv-ed-export-hint{display:block;white-space:nowrap;line-height:16px}
+.fv-editor .fv-ed-crop-notice{display:inline-flex;align-items:center;gap:6px;height:auto;min-height:0;padding:0;border:0;background:transparent;color:var(--fv-muted);font-size:12px;line-height:16px;text-align:left}
+.fv-ed-crop-notice:before{content:'';width:5px;height:5px;border-radius:50%;background:var(--fv-warning);flex:none}
+.fv-editor .fv-ed-crop-notice:hover{color:var(--fv-ink)}
+.fv-ed-gap-notice{display:inline;white-space:pre}
+.fv-editor .fv-ed-picture-size-menu button{display:flex;align-items:center;justify-content:flex-start}
+.fv-ed-picture-size-detail{margin-left:auto;padding-left:16px;color:var(--fv-muted);font-variant-numeric:tabular-nums}
diff --git a/web/editor_frame.js b/web/editor_frame.js
new file mode 100644
index 0000000..915e682
--- /dev/null
+++ b/web/editor_frame.js
@@ -0,0 +1,134 @@
+// Resolution presentation; source dimensions remain authoritative for preview.
+import * as model from './editor_model.js';
+import {frameShapes, frameSize} from './frame_sizes.js';
+import {plan} from './editor_geometry.js';
+import {pictureSession} from './editor_picture_session.js';
+const key = source => source && `${source.kind}:${source.id}`;
+const info = (sources, source) => typeof sources === 'function' ? sources(key(source)) : sources.get?.(key(source)) || sources[key(source)];
+export const validPictureSize = size => Number.isSafeInteger(size?.width) && Number.isSafeInteger(size?.height) && size.width >= 2 && size.height >= 2;
+export function clipPictureSize(clip, sources) {
+ const value = clip?.source && info(sources, clip.source);
+ return value && !value.missing && validPictureSize(value) ? {width: value.width, height: value.height} : null;
+}
+// Threshold is the total surplus on either axis in output pixels, before rounding.
+export function differentPictureShape(size, project) {
+ if (!validPictureSize(size) || !validPictureSize(project)) return false;
+ const scale = Math.max(project.width / size.width, project.height / size.height);
+ return Math.max(size.width * scale - project.width, size.height * scale - project.height) > 1 + 1e-7;
+}
+// Shared with the future adjustment panel. The caller chooses the actual video part.
+export const clipHasDifferentShape = (clip, record, sources) => differentPictureShape(clipPictureSize(clip, sources), record);
+export function changePictureFit(state, clip, fit, t) {
+ if (clip && (clip.fit || 'cover') !== fit)
+ state.apply(t('Frame size', '画面大小'), record => model.setPictureFit(record, clip.id, fit));
+}
+export const croppedParts = (record, sources) => record.tracks[0].clips.filter(clip => clip.fit !== 'contain' && clipHasDifferentShape(clip, record, sources));
+const create = (tag, cls, text) => {
+ const e = document.createElement(tag); e.className = cls;
+ if (text != null) e.textContent = text; return e;
+};
+const button = (label, action, cls) => { const e = create('button', cls, label); e.type = 'button'; e.onclick = action; return e; };
+export function updatePictureBadge(node, clip, record, size, t) {
+ let badge = node.querySelector('.fv-ed-picture-badge');
+ const show = differentPictureShape(size, record);
+ if (!badge && show) {
+ badge = create('span', 'fv-ed-picture-badge');
+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
+ svg.setAttribute('viewBox', '0 0 16 16'); svg.setAttribute('aria-hidden', 'true');
+ const path = document.createElementNS(svg.namespaceURI, 'path');
+ svg.append(path); badge.append(svg); node.append(badge);
+ }
+ if (badge) {
+ badge.hidden = !show; badge.dataset.fit = clip.fit || 'cover'; badge.setAttribute('aria-label', clip.fit === 'contain' ? t('Fit', '完整显示') : t('Filled', '已铺满'));
+ badge.querySelector('path').setAttribute('d', clip.fit === 'contain' ? 'M2 2h12v12H2zM2 5h12M2 11h12' : 'M5 1v10h10M1 5h10v10M7 7h2v2H7z');
+ }
+}
+export function createPictureGuide(host, frame, {state, t}) {
+ host.append(frame);
+ const shade = create('div', 'fv-ed-crop-shade'); shade.setAttribute('aria-hidden', 'true');
+ const bands = ['top', 'bottom', 'left', 'right'].map(side => create('div', `fv-ed-crop-${side}`)); shade.append(...bands);
+ const tools = create('div', 'fv-ed-picture-tools'); tools.setAttribute('role', 'group'); tools.setAttribute('aria-label', t('Export frame', '导出画面'));
+ let current = null, view = null;
+ const session = pictureSession(state, t);
+ const fill = button(t('Fill', '铺满'), () => changePictureFit(state, current, 'cover', t), 'fv-ed-picture-fill');
+ const fit = button(t('Fit', '完整显示'), () => changePictureFit(state, current, 'contain', t), 'fv-ed-picture-fit');
+ tools.append(fill, fit); frame.append(shade); host.append(tools);
+ function updateTools() {
+ if (!view) { tools.hidden = true; return; }
+ const {size, record, clip, preview} = view;
+ const adjusted = session.clip(clip);
+ // Keep the cropped/rotated shape and live crop visibility rules after
+ // moving the switch out of the picture, which no longer owns its tools.
+ const rotated = clip?.source && validPictureSize(size) ? plan(adjusted, size.width, size.height, record.width, record.height).rotated : size;
+ tools.hidden = !!preview || !clip?.source || session.draft?.mode === 'crop'
+ || !differentPictureShape({width: Math.round(rotated.width), height: Math.round(rotated.height)}, record);
+ }
+ const unsubscribe = session.subscribe(updateTools);
+ updateTools();
+ return {update({size, record, clip, preview, playing}) {
+ current = clip; view = {size, record, clip, preview};
+ const show = !preview && !!clip?.source && differentPictureShape(size, record);
+ const ratio = size.width / size.height, target = record.width / record.height;
+ frame.style.setProperty('--fv-ed-width', String(size.width)); frame.style.setProperty('--fv-ed-height', String(size.height));
+ frame.dataset.playing = String(!!playing);
+ updateTools(); shade.hidden = !show || clip?.fit === 'contain';
+ fill.setAttribute('aria-pressed', String(clip?.fit !== 'contain')); fit.setAttribute('aria-pressed', String(clip?.fit === 'contain'));
+ const x = (1 - Math.min(1, target / ratio)) * 50, y = (1 - Math.min(1, ratio / target)) * 50;
+ bands[0].style.height = bands[1].style.height = `${y}%`;
+ bands[2].style.width = bands[3].style.width = `${x}%`;
+ }, dispose() { unsubscribe(); tools.remove(); frame.remove(); }};
+}
+const evenSize = size => validPictureSize(size) && size.width <= 8193 && size.height <= 8193
+ ? {width: Math.floor(size.width / 2) * 2, height: Math.floor(size.height / 2) * 2} : null;
+export function creationPictureSizes(record, capabilities, t) {
+ // Use the available pixel tier nearest this edit, with exactly studio's rounding.
+ const sizes = (capabilities?.sizes || []).filter(validPictureSize);
+ const tier = sizes.reduce((best, size) => !best || Math.abs(size.width * size.height - record.width * record.height)
+ < Math.abs(best.width * best.height - record.width * record.height) ? size : best, null);
+ return frameShapes(t).map(([id, label, ratio]) => {
+ const size = tier && frameSize(tier.pixels || tier.width * tier.height / 1024 ** 2, ratio);
+ return {id, label, size: size && size.width >= 256 && size.height >= 256 && size.width <= 4096 && size.height <= 4096 ? size : null};
+ });
+}
+export function createPictureTools({state, sources, t, capabilities, error}) {
+ const selected = () => {
+ const ids = state.selection?.kind === 'clip' ? state.selection.ids : [];
+ const clips = state.record.tracks[0].clips.filter(c => ids.includes(c.id));
+ // Audio-only selection and selection of more than one logical part are disabled.
+ return clips.length === 1 && ids.every(id => id === clips[0].id || id === clips[0].link) ? clips[0] : null;
+ };
+ let menuPanel = null, menuToggle = null;
+ function renderMenu() {
+ if (!menuPanel) return;
+ menuToggle.textContent = t('Frame size', '画面大小');
+ menuPanel.replaceChildren();
+ const firstClip = state.record.tracks[0].clips.find(c => c.source);
+ const first = evenSize(clipPictureSize(firstClip, sources)), current = evenSize(clipPictureSize(selected(), sources));
+ const shapes = creationPictureSizes(state.record, capabilities(), t);
+ const matches = size => size && size.width === state.record.width && size.height === state.record.height;
+ const matchedShape = shapes.find(row => matches(row.size));
+ const addSize = (size, label, cls, mode, checked, detail = '') => {
+ const item = button(label, () => { if (!size) return; try {
+ if (!matches(size) || state.record.size_mode !== mode)
+ state.apply(t('Frame size', '画面大小'), r => model.setPictureSize(r, size.width, size.height, mode));
+ renderMenu();
+ } catch (value) { error(value); } }, cls);
+ if (detail) item.append(create('span', 'fv-ed-picture-size-detail', detail));
+ item.disabled = !size; item.setAttribute('role', 'menuitemradio'); item.setAttribute('aria-checked', String(checked));
+ menuPanel.append(item);
+ };
+ const firstLabel = t('Match the first part', '跟随第一段');
+ addSize(first || (!firstClip ? state.record : null), `${firstLabel}${t(' (', '(')}${(first || state.record).width} × ${(first || state.record).height}${t(')', ')')}`,
+ 'fv-ed-picture-first', 'first', state.record.size_mode !== 'fixed');
+ addSize(current, t('Match the selected part', '跟随选中的一段'), 'fv-ed-picture-match', 'fixed', state.record.size_mode === 'fixed' && !matchedShape);
+ for (const row of shapes) addSize(row.size, row.label, 'fv-ed-picture-size-option', 'fixed', state.record.size_mode === 'fixed' && matchedShape === row,
+ row.size ? `${row.size.width} × ${row.size.height}` : '');
+ }
+ return {update: renderMenu, appendMenu(menu) {
+ menuToggle = button('', () => { menuPanel.hidden = !menuPanel.hidden; menuToggle.setAttribute('aria-expanded', String(!menuPanel.hidden)); renderMenu(); }, 'fv-ed-picture-size-toggle');
+ menuToggle.setAttribute('role', 'menuitem'); menuToggle.setAttribute('aria-expanded', 'false');
+ menuPanel = create('div', 'fv-ed-picture-size-menu'); menuPanel.hidden = true; menuPanel.setAttribute('role', 'menu');
+ menuPanel.setAttribute('aria-label', t('Frame size', '画面大小'));
+ menu.append(menuToggle, menuPanel); renderMenu();
+ }};
+}
diff --git a/web/editor_genbar.js b/web/editor_genbar.js
new file mode 100644
index 0000000..c17e012
--- /dev/null
+++ b/web/editor_genbar.js
@@ -0,0 +1,103 @@
+// The editor owns its generation controls; progress can use the optional component.
+const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; };
+export const timeEstimate = (seconds, t) => seconds == null ? '' : seconds < 60
+ ? t(`about ${Math.max(1, Math.ceil(seconds))} s`, `约 ${Math.max(1, Math.ceil(seconds))} 秒`)
+ : t(`about ${Math.ceil(seconds / 60)} minutes`, `约 ${Math.ceil(seconds / 60)} 分钟`);
+export function createEditorGenbar(host, {state, t, actions, text = ''}) {
+ const hint = el('span', 'fv-ed-gen-hint');
+ const input = el('input', 'fv-ed-description'); input.type = 'text'; input.value = text;
+ const generate = el('button', 'fv-ed-generate'), cancel = el('button', null, t('Cancel', '取消')), resume = el('button', null, t('Continue', '继续'));
+ for (const button of [generate, cancel, resume]) button.type = 'button';
+ host.append(hint, input, generate, cancel, resume);
+ let status = null, serial = 0, disposed = false, submitting = false, previewSelection = null, estimateCache = null;
+ async function render() {
+ if (disposed) return;
+ const current = ++serial, selection = previewSelection || state.selection;
+ const busy = submitting || ['queued', 'running', 'cancelling'].includes(status?.state);
+ const stopped = ['failed', 'cancelled', 'interrupted'].includes(status?.state);
+ const selected = !!selection && (!!previewSelection || (actions.supportedSelection?.() ?? true));
+ host.dataset.mode = busy ? 'running' : selected ? 'selected' : 'idle';
+ hint.hidden = !busy; input.hidden = generate.hidden = busy;
+ input.disabled = !selected || busy;
+ input.placeholder = selected ? t('Describe this part', '描述这一段')
+ : '';
+ input.setAttribute('aria-label', t('Description', '描述'));
+ generate.classList.toggle('fv-primary', selected && !busy);
+ cancel.hidden = !busy; resume.hidden = !stopped;
+ if (busy) {
+ const blocks = status?.blocks || [], done = blocks.filter(block => block.state === 'done').length;
+ const number = Math.min(blocks.length || 1, Math.max(done, status?.chainProgress?.index || 0) + 1), count = blocks.length || 1;
+ const remaining = status?.chainProgress?.overall?.remaining_seconds ?? (blocks.every(block => Number.isFinite(block.remaining_seconds)) ? blocks.reduce((sum, block) => sum + block.remaining_seconds, 0) : null);
+ hint.textContent = t(`Part ${number}/${count}`, `第 ${number}/${count} 段`)
+ + (remaining != null ? ' · ' + timeEstimate(remaining, t) : '');
+ }
+ generate.textContent = t('Generate', '生成');
+ generate.disabled = busy || !!previewSelection || !selected || !actions.canGenerate?.(input.value);
+ generate.title = '';
+ if (selected && !busy) {
+ const key = JSON.stringify(selection);
+ if (estimateCache?.key === key) generate.textContent += estimateCache.label;
+ const seconds = await actions.estimate(selection);
+ if (disposed || current !== serial) return;
+ const label = seconds == null ? '' : ' · ' + timeEstimate(seconds, t);
+ estimateCache = {key, label};
+ generate.textContent = t('Generate', '生成') + label;
+ }
+ }
+ input.oninput = () => { state.setRangeText(input.value); render(); };
+ generate.onclick = async () => {
+ submitting = true; render();
+ try { await actions.generate({target: 'both', text: input.value}); }
+ catch (error) { actions.error(error); }
+ finally { submitting = false; render(); }
+ };
+ cancel.onclick = () => actions.cancel().catch(actions.error);
+ resume.onclick = () => actions.resume().catch(actions.error);
+ const unsubscribe = state.subscribe(event => {
+ if (event.type === 'selection' && state.selection?.kind === 'range') {
+ if (state.rangeText === null) state.setRangeText(input.value);
+ else if (input.value !== state.rangeText) input.value = state.rangeText;
+ }
+ if (event.type === 'selection' && state.selection?.kind === 'clip') {
+ const selected = state.record.tracks.flatMap(track => track.clips).find(clip => state.selection.ids.includes(clip.id) && clip.pending);
+ // A part with no description of its own keeps what is typed, as a new range does.
+ if (selected?.text) input.value = selected.text;
+ }
+ if (event.type === 'selection' || event.type === 'record') render();
+ });
+ render();
+ return {element: host, getText() { return input.value; }, update(value) { status = value; render(); }, preview(selection) { previewSelection = selection; render(); }, setText(value) { input.value = value || ''; state.setRangeText(input.value); render(); },
+ dispose() { disposed = true; ++serial; unsubscribe(); }};
+}
+
+// A missing optional module leaves the editor's existing progress in place.
+export async function loadEditorComponents(load = path => import(path)) {
+ const results = await Promise.allSettled([load('./block_progress.js')]);
+ return {blocks: results[0].status === 'fulfilled' ? results[0].value : null};
+}
+
+// What a part's progress reads from each message: Studio's displayed percentage while it
+// shows this part, never a stage's own fraction (one loading step or one pass), which
+// read as the part's showed a part still generating as finished.
+export function blockMessages(messages, snapshot = () => null) {
+ return messages.map(message => {
+ const part = {...message}, shown = snapshot(message); delete part.display_fraction;
+ return shown ? {...part, ...shown} : part;
+ });
+}
+export function editorBlockStates(job, messages = [], resolve = null) {
+ if (resolve) return resolve(job, messages);
+ const states = {pending: 'waiting', queued: 'waiting', running: 'generating', done: 'done',
+ failed: 'failed', cancelled: 'stopped', interrupted: 'stopped'};
+ return Object.fromEntries((job.blocks || []).map(block => {
+ const live = messages.find(message => message.chain?.id === job.id && message.chain?.block === block.id);
+ const running = block.state === 'running' || block.state === 'queued';
+ const fraction = block.state === 'done' ? 1 : running && live
+ ? Number.isFinite(live.percent) ? live.percent / 100 : live.bar ?? live.overall?.fraction ?? block.fraction
+ : block.fraction;
+ return [block.id, {state: running && live ? 'generating' : states[block.state] || 'waiting',
+ fraction: Math.max(0, Math.min(1, fraction || 0)),
+ remainingSeconds: running && live ? live.remaining_seconds ?? live.overall?.remaining_seconds ?? block.remaining_seconds ?? null
+ : block.remaining_seconds ?? null}];
+ }));
+}
diff --git a/web/editor_generation.js b/web/editor_generation.js
new file mode 100644
index 0000000..65512c2
--- /dev/null
+++ b/web/editor_generation.js
@@ -0,0 +1,15 @@
+const valid = size => [size?.width, size?.height].every(side => Number.isSafeInteger(side) && side >= 256 && side <= 4096 && side % 32 === 0);
+// Keep editing/export dimensions independent of the creation panel's preset
+// range (up to 2 MP). Capability estimates must use the same size as the request.
+export function generationSize(project, sizes = []) {
+ const {width, height} = project, area = width * height, ratio = width / height;
+ if (valid(project) && area <= 2 * 1024 ** 2) return {width, height};
+ let candidates = (sizes || []).filter(valid);
+ if (!candidates.length) {
+ for (let w = 256; w <= 4096; w += 32)
+ for (let h = 256; h <= 4096 && w * h <= 2 * 1024 ** 2; h += 32) candidates.push({width: w, height: h});
+ }
+ candidates = [...candidates].sort((a, b) => Math.abs(Math.log(a.width / a.height / ratio)) - Math.abs(Math.log(b.width / b.height / ratio))
+ || Math.abs(a.width * a.height - area) - Math.abs(b.width * b.height - area));
+ return {width: candidates[0].width, height: candidates[0].height};
+}
diff --git a/web/editor_geometry.js b/web/editor_geometry.js
new file mode 100644
index 0000000..a281bd8
--- /dev/null
+++ b/web/editor_geometry.js
@@ -0,0 +1,147 @@
+// Pure counterpart of freevideo_engine/editor_picture.py; no DOM or project state.
+// Coordinates are pixel edges; matrix uses CSS [a,b,c,d,e,f] order.
+const cache = new Map();
+const number = (v, fallback, low, high) => typeof v !== 'number' || Number.isNaN(v)
+ ? fallback : Math.min(high, Math.max(low, v));
+const dimension = v => {
+ if (!Number.isSafeInteger(v) || v < 1) throw new RangeError('Picture dimensions must be positive integers');
+ return v;
+};
+// Math.round differs from Python round at exact half-integers (including -0.5).
+function round(v) {
+ const low = Math.floor(v), part = v - low;
+ return part === .5 ? (low % 2 === 0 ? low : low + 1) : Math.floor(v + .5);
+}
+function fields(clip) {
+ clip = clip && typeof clip === 'object' && !Array.isArray(clip) ? clip : {};
+ const edges = ['left', 'top', 'right', 'bottom'].map(edge => number(clip[`crop_${edge}`], 0, 0, .9));
+ for (const [a, b] of [[0, 2], [1, 3]]) {
+ const total = edges[a] + edges[b];
+ if (total > .9) [edges[a], edges[b]] = [edges[a] * .9 / total, edges[b] * .9 / total];
+ }
+ return [clip.fit === 'contain' ? 'contain' : 'cover', ...edges,
+ clip.flip_h === true, clip.flip_v === true, number(clip.rotate, 0, -180, 180),
+ number(clip.scale, 1, .1, 10), number(clip.offset_x, 0, -2, 2), number(clip.offset_y, 0, -2, 2)];
+}
+function apply(m, [x, y]) {
+ const [a, b, c, d, e, f] = m;
+ return [a * x + c * y + e, b * x + d * y + f];
+}
+function inverse(m) {
+ const [a, b, c, d, e, f] = m, det = a * d - b * c;
+ return [d / det, -b / det, -c / det, a / det, (c * f - d * e) / det, (b * e - a * f) / det];
+}
+function clipPolygon(polygon, width, height) {
+ for (const [axis, bound, sign] of [[0, 0, 1], [0, width, -1], [1, 0, 1], [1, height, -1]]) {
+ const result = [];
+ if (!polygon.length) break;
+ let previous = polygon.at(-1), before = sign * (previous[axis] - bound);
+ for (const point of polygon) {
+ const after = sign * (point[axis] - bound);
+ if ((before >= 0) !== (after >= 0)) {
+ const t = before / (before - after);
+ result.push([previous[0] + t * (point[0] - previous[0]), previous[1] + t * (point[1] - previous[1])]);
+ }
+ if (after >= 0) result.push(point);
+ [previous, before] = [point, after];
+ }
+ polygon = result;
+ }
+ const unique = [];
+ for (const p of polygon) {
+ if (!unique.length || Math.max(...p.map((v, i) => Math.abs(v - unique.at(-1)[i]))) > 1e-9) unique.push(p);
+ }
+ if (unique.length > 1 && Math.max(...unique[0].map((v, i) => Math.abs(v - unique.at(-1)[i]))) <= 1e-9) unique.pop();
+ return unique;
+}
+function area(polygon) {
+ return Math.abs(polygon.reduce((sum, p, i) => {
+ const prev = polygon[(i + polygon.length - 1) % polygon.length];
+ return sum + prev[0] * p[1] - prev[1] * p[0];
+ }, 0)) / 2;
+}
+function build(f, sw, sh, width, height) {
+ const [fit, left, top, right, bottom, flip_h, flip_v, angle, scale, ox, oy] = f;
+ const x = Math.min(sw - 1, round(left * sw)), y = Math.min(sh - 1, round(top * sh));
+ const cw = Math.max(1, sw - round(right * sw) - x), ch = Math.max(1, sh - round(bottom * sh) - y);
+ const [cosine, sine] = angle % 90 === 0
+ ? [[1, 0], [0, 1], [-1, 0], [0, -1]][((angle / 90) % 4 + 4) % 4]
+ : [Math.cos(angle * Math.PI / 180), Math.sin(angle * Math.PI / 180)];
+ const rw = Math.abs(cosine) * cw + Math.abs(sine) * ch;
+ const rh = Math.abs(sine) * cw + Math.abs(cosine) * ch;
+ const ratio = (fit === 'cover' ? Math.max : Math.min)(width / rw, height / rh);
+ const legacy = JSON.stringify(f) === JSON.stringify(fields({}));
+ const dw = legacy ? Math.max(1, round(rw * ratio)) : rw * ratio * scale;
+ const dh = legacy ? Math.max(1, round(rh * ratio)) : rh * ratio * scale;
+ const dx = legacy ? -Math.floor((dw - width) / 2) : (width - dw) / 2 + ox * width;
+ const dy = legacy ? -Math.floor((dh - height) / 2) : (height - dh) / 2 + oy * height;
+ const cx = dx + dw / 2, cy = dy + dh / 2, sx = dw / rw, sy = dh / rh;
+ const fx = flip_h ? -1 : 1, fy = flip_v ? -1 : 1;
+ const a = sx * cosine * fx, b = sy * sine * fx, c = -sx * sine * fy, d = sy * cosine * fy;
+ const matrix = [a, b, c, d, cx - a * (x + cw / 2) - c * (y + ch / 2), cy - b * (x + cw / 2) - d * (y + ch / 2)];
+ const ra = sx * cosine, rb = sy * sine, rc = -sx * sine, rd = sy * cosine;
+ const raster_matrix = angle % 90 === 0 ? [sx, 0, 0, sy, dx, dy]
+ : [ra, rb, rc, rd, cx - ra * cw / 2 - rc * ch / 2, cy - rb * cw / 2 - rd * ch / 2];
+ const polygon = [[x, y], [x + cw, y], [x + cw, y + ch], [x, y + ch]].map(p => apply(matrix, p));
+ const inv = inverse(matrix);
+ const visible = clipPolygon(polygon, width, height).map(p => apply(inv, p))
+ .map(p => [Math.min(x + cw, Math.max(x, p[0])), Math.min(y + ch, Math.max(y, p[1]))]);
+ const covers = [[0, 0], [width, 0], [width, height], [0, height]].map(p => apply(inv, p))
+ .every(p => p[0] >= x - 1e-7 && p[0] <= x + cw + 1e-7 && p[1] >= y - 1e-7 && p[1] <= y + ch + 1e-7);
+ const cropped_fraction = Math.min(1, Math.max(0, 1 - area(visible) / (sw * sh)));
+ const loss = Math.max(x, y, sw - x - cw, sh - y - ch,
+ -Math.min(...polygon.map(p => p[0])), Math.max(...polygon.map(p => p[0])) - width,
+ -Math.min(...polygon.map(p => p[1])), Math.max(...polygon.map(p => p[1])) - height);
+ const vx = visible.length ? Math.min(...visible.map(p => p[0])) : x;
+ const vy = visible.length ? Math.min(...visible.map(p => p[1])) : y;
+ const vw = visible.length ? Math.max(...visible.map(p => p[0])) - vx : 0;
+ const vh = visible.length ? Math.max(...visible.map(p => p[1])) - vy : 0;
+ return {version: 1, source: {width: sw, height: sh}, output: {width, height}, fit,
+ crop: {x, y, width: cw, height: ch}, flip_h, flip_v, rotate: angle,
+ rotated: {width: rw, height: rh}, center: {x: cx, y: cy}, size: {width: dw, height: dh}, matrix, raster_matrix, legacy,
+ covers, cropped: loss > 1 + 1e-7, cropped_fraction,
+ visible: {x: vx, y: vy, width: vw, height: vh, polygon: visible}};
+}
+
+/** Independently mutable JSON plan. Normalized fields and sizes key a 256-entry LRU. */
+export function plan(clip, sourceWidth, sourceHeight, width, height) {
+ const sizes = [sourceWidth, sourceHeight, width, height].map(dimension), f = fields(clip);
+ const key = JSON.stringify([f, ...sizes]);
+ let result = cache.get(key);
+ if (result) cache.delete(key);
+ else result = build(f, ...sizes);
+ cache.set(key, result);
+ if (cache.size > 256) cache.delete(cache.keys().next().value);
+ return JSON.parse(JSON.stringify(result));
+}
+
+/** More than one source pixel of explicit crop, or output pixel of overflow. */
+export function isCropped(clip, sourceWidth, sourceHeight, width, height) {
+ return plan(clip, sourceWidth, sourceHeight, width, height).cropped;
+}
+
+/** Styles for a video inside a positioned, overflow:hidden output viewport.
+ * Uses standard clip-path:inset + 2D matrix (Chromium and Safari); no
+ * object-view-box. Apply all returned styles. The element keeps its natural
+ * source dimensions, so inset distances are source pixels before transform.
+ * This helper doesn't draw a background: Iris's contain preview has none.
+ */
+export function cssTransform(p, boxWidth, boxHeight) {
+ if (![boxWidth, boxHeight].every(v => Number.isFinite(v) && v > 0)) throw new RangeError('Invalid preview size');
+ const sx = boxWidth / p.output.width, sy = boxHeight / p.output.height;
+ const [a, b, c, d, e, f] = p.matrix, crop = p.crop;
+ const right = p.source.width - crop.x - crop.width, bottom = p.source.height - crop.y - crop.height;
+ return {position: 'absolute', left: '0px', top: '0px', width: `${p.source.width}px`, height: `${p.source.height}px`,
+ maxWidth: 'none', maxHeight: 'none', objectFit: 'fill', transformOrigin: '0 0',
+ transform: `matrix(${[a * sx, b * sy, c * sx, d * sy, e * sx, f * sy].join(',')})`,
+ clipPath: `inset(${crop.y}px ${right}px ${bottom}px ${crop.x}px)`};
+}
+
+/** Original-source pixel rectangle enclosing all retained pixels, with exact
+ * polygon for rotated cuts. Use polygon to dim the outside in the full-source
+ * preview; a rectangle alone cannot represent arbitrary-angle export crops.
+ * An empty polygon means the foreground is entirely outside the export.
+ */
+export function visibleRect(p) {
+ return JSON.parse(JSON.stringify(p.visible));
+}
diff --git a/web/editor_icons.js b/web/editor_icons.js
new file mode 100644
index 0000000..4bdb51f
--- /dev/null
+++ b/web/editor_icons.js
@@ -0,0 +1,13 @@
+// Small, shared presentation glyphs. Accessible names belong to their controls.
+const paths = {
+ adjust: 'M3 1v14M8 1v14M13 1v14M1 5h4M6 11h4M11 5h4',
+ fit: 'M1 6V1h5M10 1h5v5M15 10v5h-5M6 15H1v-5',
+ check: 'm3 8 3 3 7-7',
+};
+export function editorIcon(name) {
+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
+ svg.setAttribute('viewBox', '0 0 16 16'); svg.setAttribute('aria-hidden', 'true');
+ svg.classList.add('fv-ed-glyph');
+ const path = document.createElementNS(svg.namespaceURI, 'path');
+ path.setAttribute('d', paths[name]); svg.append(path); return svg;
+}
diff --git a/web/editor_library.js b/web/editor_library.js
new file mode 100644
index 0000000..83b3c61
--- /dev/null
+++ b/web/editor_library.js
@@ -0,0 +1,193 @@
+import {editorIcon} from './editor_icons.js';
+import {sourceKey} from './editor_store.js';
+const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; };
+const stamp = frames => { const seconds = Math.floor((frames || 0) / 24); return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`; };
+const FORMATS = 'MP4, MOV, WebM, MKV, M4V, WAV, MP3, FLAC, OGG, M4A, AAC, Opus';
+export function createEditorLibrary(host, {store, t, actions, state}) {
+ const tabs = el('div', 'fv-ed-tabs fv-pass-mode'); tabs.setAttribute('role', 'tablist');
+ const works = el('button', null, t('Creations', '作品')), imports = el('button', null, t('Imported', '已导入'));
+ for (const tab of [works, imports]) { tab.type = 'button'; tab.setAttribute('role', 'tab'); tabs.append(tab); }
+ const search = el('input', 'fv-ed-search'); search.type = 'search'; search.placeholder = t('Search', '搜索'); search.setAttribute('aria-label', search.placeholder);
+ const searchTools = el('div', 'fv-ed-library-tools'), importButton = el('button', 'fv-ed-library-import', t('Import', '导入'));
+ importButton.type = 'button'; searchTools.append(search, importButton);
+ const grid = el('div', 'fv-ed-library-grid'); grid.setAttribute('role', 'tabpanel');
+ const message = el('p', 'fv-ed-library-message'); message.setAttribute('role', 'status');
+ const file = el('input'); file.type = 'file'; file.multiple = true; file.hidden = true;
+ file.accept = '.mp4,.mov,.webm,.mkv,.m4v,.wav,.mp3,.flac,.ogg,.m4a,.aac,.opus';
+ importButton.onclick = () => file.click();
+ host.append(tabs, searchTools, grid, message, file);
+ let tab = 'work', rows = [], imported = [], next = null, disposed = false, loading = false;
+ let listRead = Promise.resolve(), refreshTask = null, retryTimer = null, finishRetry = null, refreshAgain = false;
+ const expectedOutputs = new Set();
+ const uploading = new Map(), recentImports = new Map();
+ function metadata(row, kind) {
+ const g = row.geometry || row, cached = store.sources.get(`${kind}:${row.id}`);
+ return {frames: cached?.frames || Math.round(g.frames || (g.seconds || 0) * (g.fps || 24)), hasVideo: cached?.has_video ?? (kind === 'work' || row.kind === 'video'),
+ hasAudio: cached?.has_audio ?? (kind === 'work' ? row.has_audio !== false : row.has_audio === true || row.kind === 'audio')};
+ }
+ // The "+" puts a video after the last picture and a sound at the play position;
+ // a double click leaves the place to the page, which appends.
+ async function add(row, kind, plus = false) {
+ const source = {kind, id: row.id}, key = sourceKey(source), playhead = state?.playhead;
+ await store.getSources([key]);
+ if (disposed) return;
+ const value = store.sources.get(key), fallback = metadata(row, kind), hasVideo = value?.has_video ?? fallback.hasVideo;
+ const pictures = state?.record.tracks.find(track => track.id === 'v1')?.clips || [];
+ const at = !plus || !state ? undefined : hasVideo ? Math.max(0, ...pictures.map(clip => clip.start + clip.frames)) : playhead;
+ await actions.insertSource({source, at, frames: value?.frames || fallback.frames,
+ hasVideo, hasAudio: value?.has_audio ?? fallback.hasAudio});
+ }
+ function card(row, kind) {
+ const container = el('div', 'fv-ed-source-card');
+ const button = el('button', 'fv-ed-source'); button.type = 'button'; button.dataset.key = `${kind}:${row.id}`;
+ const ready = kind === 'work' || row.state === 'ready';
+ const label = row.name || row.text || new Date(row.created_at).toLocaleDateString();
+ button.setAttribute('aria-label', label); button.draggable = ready; button.disabled = !ready;
+ const picture = el('div', 'fv-ed-source-picture');
+ const url = kind === 'work' ? (store.sources.get(`work:${row.id}`)?.thumbnail
+ || '/freevideo/library/thumbnail?' + new URLSearchParams({id: row.id})) : row.thumbnail;
+ if (url) { const image = el('img'); image.src = actions.mediaURL(url); image.alt = ''; image.loading = 'lazy'; image.onerror = () => { image.hidden = true; }; picture.append(image); }
+ else if (row.kind === 'audio') picture.append(el('span', 'fv-ed-audio-icon', '♫'));
+ if (ready) picture.append(el('span', 'fv-ed-source-time', stamp(metadata(row, kind).frames)));
+ else if (row.state === 'failed') {
+ picture.append(el('span', 'fv-ed-source-preparing', t('Cannot open', '打不开')));
+ } else picture.append(el('span', 'fv-ed-source-preparing', `${Math.round((row.fraction || 0) * 100)}%`));
+ button.append(picture);
+ const used = el('span', 'fv-ed-source-used'); used.append(editorIcon('check')); used.setAttribute('aria-label', t('Used', '已用')); used.hidden = true; picture.append(used);
+ button.ondblclick = () => add(row, kind).catch(actions.error);
+ button.onkeydown = event => { if (event.key === 'Enter') { event.preventDefault(); add(row, kind).catch(actions.error); } };
+ button.ondragstart = event => {
+ if (!ready) { event.preventDefault(); return; }
+ const value = metadata(row, kind), key = `${kind}:${row.id}`;
+ event.dataTransfer.effectAllowed = 'copy';
+ event.dataTransfer.setData('application/x-freevideo-source', JSON.stringify({key, ...value}));
+ store.getSources([key]).catch(actions.error);
+ };
+ // Single click previews the source; double click also inserts it.
+ button.onclick = () => { if (ready) Promise.resolve().then(() => actions.previewSource?.({kind, id: row.id})).catch(actions.error); };
+ const plus = el('button', 'fv-ed-source-add', '+'); plus.type = 'button'; plus.disabled = !ready;
+ plus.setAttribute('aria-label', `${t('Add to the tracks', '加到轨道上')}: ${label}`);
+ const insert = event => { event.preventDefault(); event.stopPropagation(); if (ready && !(event.detail > 1)) add(row, kind, true).catch(actions.error); };
+ plus.onclick = insert;
+ plus.ondblclick = event => { event.preventDefault(); event.stopPropagation(); };
+ plus.onkeydown = event => { if (event.key === 'Enter' || event.key === ' ') insert(event); };
+ container.append(button, plus);
+ return container;
+ }
+ function updateUsed() {
+ const keys = new Set((state?.record.tracks || []).flatMap(track => track.clips)
+ .filter(clip => clip.source).map(clip => sourceKey(clip.source)));
+ for (const button of grid.querySelectorAll('.fv-ed-source')) button.querySelector('.fv-ed-source-used').hidden = !keys.has(button.dataset.key);
+ }
+ function render() {
+ if (disposed) return;
+ const scroll = host.scrollTop || 0, top = host.getBoundingClientRect().top;
+ const anchor = scroll > 0 ? [...grid.querySelectorAll('.fv-ed-source')].find(node => node.getBoundingClientRect().bottom > top) : null;
+ const anchorTop = anchor?.getBoundingClientRect().top;
+ works.setAttribute('aria-selected', String(tab === 'work')); imports.setAttribute('aria-selected', String(tab === 'import'));
+ works.setAttribute('aria-pressed', String(tab === 'work')); imports.setAttribute('aria-pressed', String(tab === 'import'));
+ search.hidden = tab !== 'work';
+ grid.replaceChildren();
+ if (tab === 'import') {
+ const add = el('button', 'fv-ed-import', t('Import', '导入')); add.type = 'button'; add.onclick = () => file.click(); grid.append(add);
+ }
+ const term = search.value.trim().toLocaleLowerCase();
+ const shown = tab === 'work' ? rows.filter(row => row.video && (!term || [row.name, row.text, row.created_at, row.id].some(value => String(value || '').toLocaleLowerCase().includes(term)))) : [...imported, ...uploading.values()];
+ for (const row of shown) grid.append(card(row, tab));
+ updateUsed();
+ message.textContent = ''; // Empty states stay silent.
+ for (const row of shown) if (row.state === 'failed') message.textContent = t('This file cannot be opened. Supported formats: ', '这个文件打不开。支持的格式:') + FORMATS;
+ if (scroll > 0) {
+ const replacement = anchor && [...grid.querySelectorAll('.fv-ed-source')].find(node => node.dataset.key === anchor.dataset.key);
+ host.scrollTop = replacement ? scroll + replacement.getBoundingClientRect().top - anchorTop : scroll;
+ }
+ }
+ function load(append = false, merge = false) {
+ const read = listRead.then(async () => {
+ if (disposed || (append && !next)) return null;
+ loading = true; let succeeded = false;
+ try {
+ const value = await store.works(append ? next : null); if (disposed) return null;
+ const items = value.items || [], ids = new Set(items.map(row => row.id));
+ if (merge && rows.length) {
+ // The returned prefix is authoritative, including removals after a
+ // joined result hides its inputs. Keep already loaded older pages.
+ const covered = value.next ? rows.reduce((end, row, i) => ids.has(row.id) ? i + 1 : end, 0) : rows.length;
+ rows = [...items, ...rows.slice(covered).filter(row => !ids.has(row.id))];
+ if (!value.next) next = null;
+ } else {
+ rows = append ? [...rows, ...items.filter(row => !rows.some(old => old.id === row.id))] : items;
+ next = value.next;
+ }
+ succeeded = true; render();
+ store.getSources(items.filter(row => row.video).map(row => `work:${row.id}`)).then(render).catch(value => { if (!disposed) actions.error(value); });
+ return value;
+ } catch (error) { if (!disposed) actions.error(error); return null; }
+ finally { loading = false; if (succeeded) scheduleMore(); }
+ });
+ listRead = read; return read;
+ }
+ function refresh({outputs = []} = {}) {
+ if (disposed) return Promise.resolve();
+ outputs.forEach(output => expectedOutputs.add(output)); refreshAgain = true;
+ if (refreshTask) return refreshTask;
+ refreshTask = (async () => {
+ while (refreshAgain && !disposed) {
+ refreshAgain = false;
+ const expected = [...expectedOutputs]; expectedOutputs.clear();
+ for (let attempt = 0; attempt < 4 && !disposed; attempt++) {
+ const value = await load(false, true);
+ if (value && expected.every(output => value.items?.some(row => row.video === output))) break;
+ if (attempt === 3) break;
+ await new Promise(resolve => {
+ finishRetry = resolve;
+ retryTimer = setTimeout(() => { retryTimer = null; finishRetry = null; resolve(); }, [250, 750, 1500][attempt]);
+ });
+ }
+ }
+ })().finally(() => { refreshTask = null; });
+ return refreshTask;
+ }
+ function choose(value) { tab = value; render(); scheduleMore(); }
+ works.onclick = () => choose('work'); imports.onclick = () => choose('import');
+ tabs.onkeydown = event => { if (['ArrowLeft', 'ArrowRight'].includes(event.key)) { event.preventDefault(); choose(tab === 'work' ? 'import' : 'work'); (tab === 'work' ? works : imports).focus(); } };
+ search.oninput = () => { render(); scheduleMore(); };
+ let moreFrame = null, pagePending = false;
+ function scheduleMore() {
+ if (disposed || !next || tab !== 'work' || moreFrame != null) return;
+ moreFrame = requestAnimationFrame(() => { moreFrame = null; loadMore(); });
+ }
+ function loadMore() {
+ if (disposed || tab !== 'work' || loading || pagePending || !next) return;
+ if (!search.value && !(host.clientHeight > 0 && host.scrollTop + host.clientHeight >= host.scrollHeight - 2)) return;
+ pagePending = true;
+ load(true).finally(() => { pagePending = false; });
+ }
+ host.addEventListener('scroll', scheduleMore, {passive: true});
+ const resize = new ResizeObserver(scheduleMore); resize.observe(host);
+ async function importFiles(files) {
+ choose('import');
+ for (const value of files) {
+ if (disposed) break;
+ const id = 'upload-' + Math.random(), row = {id, name: value.name, kind: value.type.startsWith('audio') ? 'audio' : 'video', state: 'preparing', fraction: 0};
+ uploading.set(id, row); render();
+ try {
+ const item = await store.upload(value, fraction => { row.fraction = fraction; render(); });
+ if (item && !disposed) {
+ recentImports.set(item.id, item);
+ imported = [item, ...imported.filter(existing => existing.id !== item.id)];
+ }
+ } catch { actions.notify(t('This file cannot be opened. Supported formats: ', '这个文件打不开。支持的格式:') + FORMATS); }
+ finally { uploading.delete(id); render(); }
+ }
+ }
+ file.onchange = () => { importFiles([...file.files]); file.value = ''; };
+ const stop = store.watchImports(items => {
+ for (const item of items) recentImports.delete(item.id);
+ // A list request started before an upload may finish after it.
+ imported = [...recentImports.values(), ...items]; render();
+ });
+ const stopUsed = state?.subscribe(event => { if (event.type === 'record') updateUsed(); });
+ render(); load();
+ return {element: host, importFiles, refresh, dispose() { disposed = true; host.removeEventListener('scroll', scheduleMore); resize.disconnect(); cancelAnimationFrame(moreFrame); stop(); stopUsed?.(); clearTimeout(retryTimer); finishRetry?.(); }};
+}
diff --git a/web/editor_menu.css b/web/editor_menu.css
new file mode 100644
index 0000000..39620fc
--- /dev/null
+++ b/web/editor_menu.css
@@ -0,0 +1,9 @@
+.fv-ed-context-menu{position:fixed;z-index:30;min-width:220px;max-width:calc(100vw - 16px);max-height:calc(100dvh - 16px);overflow:auto;padding:6px;background:var(--fv-card);color:var(--fv-ink);border:1px solid var(--fv-border);border-radius:8px;font:13px var(--fv-font)}
+.fv-ed-context-menu[hidden]{display:none}
+.fv-ed-context-menu .fv-ed-menu-count{padding:6px 10px;color:var(--fv-muted);font-size:12px}
+.fv-ed-context-menu [role=separator]{height:1px;margin:5px 4px;background:var(--fv-border)}
+.fv-editor .fv-ed-context-menu button{display:flex;align-items:center;justify-content:space-between;gap:32px;width:100%;height:32px;padding:0 10px;border:0;border-radius:4px;background:transparent;color:var(--fv-ink);font:inherit;text-align:left;white-space:nowrap}
+.fv-ed-menu-shortcut{color:var(--fv-muted);font-size:12px}
+.fv-editor .fv-ed-context-menu button:hover,.fv-editor .fv-ed-context-menu button:focus-visible{background:color-mix(in srgb,var(--fv-accent) 12%,transparent);outline:1px solid var(--fv-accent);outline-offset:-1px}
+.fv-editor .fv-ed-context-menu button[aria-disabled=true]{opacity:.4;cursor:not-allowed}
+@media(forced-colors:active){.fv-ed-context-menu button[aria-disabled=true]{color:GrayText;opacity:1}}
diff --git a/web/editor_menu.js b/web/editor_menu.js
new file mode 100644
index 0000000..52f6efc
--- /dev/null
+++ b/web/editor_menu.js
@@ -0,0 +1,163 @@
+// Track menus share the selection commands; they never choose an edit's landing position.
+import * as model from './editor_model.js';
+import {clickSelection, createSelectionActions, isTyping, selectedIds, playheadIds} from './editor_select.js';
+
+const registered = new Set();
+// Groups appear in first-registration order; matching groups stay together.
+// Built-ins use 'edit' and 'split'. Return the disposer when unloading an extension.
+// label/shortcut accept a string or (context) => string, so extensions can use context.t.
+export function registerMenuItem(item) {
+ if (!['part', 'empty'].includes(item.where) || item.group == null || !item.label || typeof item.run !== 'function')
+ throw new TypeError('Menu items require where, group, label and run');
+ const entry = {...item}; registered.add(entry);
+ return () => registered.delete(entry);
+}
+
+export function menuContext({state, commands, t = en => en, actions = {}, clip = null, frame = state.playhead, track = null,
+ platform = globalThis.navigator?.userAgentData?.platform || globalThis.navigator?.platform || ''}) {
+ const ids = selectedIds(state.record, state.selection), seen = new Set();
+ let count = 0;
+ for (const id of ids) if (!seen.has(id)) {
+ count++;
+ for (const member of model.pair(state.record, id)) seen.add(member.id);
+ }
+ return {where: clip ? 'part' : 'empty', clip, ids, count, frame, track, state, record: state.record,
+ playhead: state.playhead, commands, actions, t, modifier: /Mac|iPhone|iPad/i.test(platform) ? '⌘' : 'Ctrl'};
+}
+
+export function menuItems(context) {
+ const {record, ids, clip, playhead, commands, t, modifier} = context;
+ const busy = item => ['queued', 'running'].includes(item.pending);
+ const members = ids.map(id => model.find(record, id)).filter(Boolean);
+ const generating = members.some(busy);
+ const copyable = members.some(item => model.pair(record, item.id).every(member => member.source && !busy(member)));
+ const command = (key, label, shortcut, enabled = true, group = 'edit') =>
+ ({group, label, shortcut, enabled, run: () => commands.run(key)});
+ const splitTargets = playheadIds(record, context.state.selection, playhead).map(id => model.find(record, id));
+ const splitBusy = splitTargets.some(item => model.pair(record, item.id).some(busy));
+ const canSplit = splitTargets.some(item => playhead > item.start && playhead < item.start + item.frames);
+ const items = context.where === 'part' ? [
+ command('c', t('Copy', '复制'), `${modifier}+C`, copyable),
+ command('x', t('Cut', '剪切'), `${modifier}+X`, copyable && !generating),
+ command('d', t('Duplicate', '创建副本'), `${modifier}+D`, copyable),
+ command('delete', t('Delete', '删除'), 'Delete', !generating),
+ command('b', t('Split', '剪开'), `${modifier}+B`, !splitBusy && canSplit, 'split'),
+ ] : [
+ command('v', t('Paste', '粘贴'), `${modifier}+V`, commands.canPaste()),
+ command('a', t('Select all', '全选'), `${modifier}+A`, record.tracks.some(track => track.clips.length)),
+ ];
+ const value = field => typeof field === 'function' ? field(context) : field;
+ for (const item of registered) if (item.where === context.where) items.push({...item,
+ label: value(item.label), shortcut: value(item.shortcut) || '', enabled: item.enabled ? !!item.enabled(context) : true,
+ run: () => item.run(context)});
+ const groups = new Map();
+ for (const item of items) {
+ if (!groups.has(item.group)) groups.set(item.group, []);
+ groups.get(item.group).push(item);
+ }
+ return [...groups.values()].flat();
+}
+
+export function createTrackMenu(host, {state, t = en => en, actions = {}, hitTest, frameAt, trackAt, clipboard,
+ choose = id => state.select(clickSelection(state.record, state.selection, id))} = {}) {
+ const commands = createSelectionActions({state, t, actions, ...(clipboard ? {clipboard} : {})});
+ const element = document.createElement('div');
+ element.className = 'fv-ed-context-menu'; element.hidden = true; element.tabIndex = -1;
+ element.setAttribute('role', 'menu'); host.append(element);
+ let buttons = [], context = null, returnFocus = null;
+ const listeners = [];
+ function close(restore = false) {
+ if (element.hidden) return false;
+ element.hidden = true; context = null;
+ if (restore) (returnFocus?.isConnected && host.contains(returnFocus) ? returnFocus : host).focus({preventScroll: true});
+ buttons.forEach(button => { button.onclick = null; }); buttons = []; element.replaceChildren();
+ return true;
+ }
+ function dismiss(event) {
+ if (element.hidden) return false;
+ event.preventDefault(); event.stopPropagation(); close(true); return true;
+ }
+ function keyboard(event) {
+ if (element.hidden || isTyping(event.target)) return false;
+ const key = event.key.toLowerCase();
+ event.preventDefault(); event.stopPropagation();
+ if (key === 'escape' || key === 'tab') close(true);
+ else if (['arrowup', 'arrowdown', 'home', 'end'].includes(key)) {
+ const index = buttons.indexOf(document.activeElement);
+ const next = key === 'home' ? 0 : key === 'end' ? buttons.length - 1
+ : (index + (key === 'arrowup' ? -1 : 1) + buttons.length) % buttons.length;
+ buttons[next]?.focus({preventScroll: true});
+ } else if (key === 'enter' || key === ' ') buttons.find(button => button === document.activeElement)?.onclick();
+ return true;
+ }
+ // The editor's captured keyboard gate calls control onkeydown handlers.
+ element.onkeydown = keyboard;
+ const stop = event => event.stopPropagation();
+ const contextMenu = event => {
+ if (isTyping(event.target)) return;
+ event.preventDefault(); event.stopPropagation();
+ if (element.contains(event.target)) return;
+ close();
+ const clip = hitTest(event).item?.clip || null;
+ if (clip && !selectedIds(state.record, state.selection).includes(clip.id))
+ choose(clip.id);
+ context = menuContext({state, commands, actions, t, clip, frame: frameAt(event), track: trackAt(event)});
+ returnFocus = document.activeElement;
+ if (context.where === 'part' && context.count > 1) {
+ const heading = document.createElement('div'); heading.className = 'fv-ed-menu-count';
+ heading.textContent = t(`${context.count} parts selected`, `已选 ${context.count} 段`); element.append(heading);
+ element.setAttribute('aria-label', heading.textContent);
+ } else element.removeAttribute('aria-label');
+ let previousGroup;
+ for (const item of menuItems(context)) {
+ if (previousGroup !== undefined && item.group !== previousGroup) {
+ const separator = document.createElement('div'); separator.setAttribute('role', 'separator'); element.append(separator);
+ }
+ previousGroup = item.group;
+ const button = document.createElement('button'); button.type = 'button'; button.tabIndex = -1;
+ button.setAttribute('role', 'menuitem'); button.setAttribute('aria-disabled', String(!item.enabled));
+ const label = document.createElement('span'), shortcut = document.createElement('span');
+ label.className = 'fv-ed-menu-label'; label.textContent = item.label;
+ shortcut.className = 'fv-ed-menu-shortcut'; shortcut.textContent = item.shortcut;
+ button.append(label, shortcut);
+ // Keep disabled items discoverable without explanatory tooltips.
+ button.onclick = () => {
+ if (!item.enabled) return;
+ close(true);
+ try { item.run(); } catch (error) { commands.report(error); }
+ };
+ buttons.push(button); element.append(button);
+ }
+ element.hidden = false;
+ const bounds = element.getBoundingClientRect();
+ const width = window.innerWidth || document.documentElement?.clientWidth || 1440;
+ const height = window.innerHeight || document.documentElement?.clientHeight || 900;
+ element.style.left = `${Math.max(8, Math.min(event.clientX, width - bounds.width - 8))}px`;
+ element.style.top = `${Math.max(8, Math.min(event.clientY, height - bounds.height - 8))}px`;
+ (buttons[0] || element).focus({preventScroll: true});
+ };
+ const outside = event => { if (!element.contains(event.target)) close(); }, closeMenu = () => close();
+ // Event names stay literal so the shared key-listener guard can read every registration.
+ element.addEventListener('pointerdown', stop); element.addEventListener('click', stop);
+ host.addEventListener('contextmenu', contextMenu); host.addEventListener('scroll', outside, true);
+ document.addEventListener('pointerdown', outside, true);
+ window.addEventListener('blur', closeMenu); window.addEventListener('resize', closeMenu);
+ listeners.push(() => {
+ element.removeEventListener('pointerdown', stop); element.removeEventListener('click', stop);
+ host.removeEventListener('contextmenu', contextMenu); host.removeEventListener('scroll', outside, true);
+ document.removeEventListener('pointerdown', outside, true);
+ window.removeEventListener('blur', closeMenu); window.removeEventListener('resize', closeMenu);
+ });
+ const unsubscribe = state.subscribe(event => {
+ // Autosave acknowledgements replace the record just to adopt identity/revision.
+ // Keep the menu usable while that happens; actual edits invalidate its actions.
+ if (event.type === 'record' && context) {
+ const content = ({id, revision, ...value}) => JSON.stringify(value);
+ if (content(context.record) === content(state.record)) { context.record = state.record; return; }
+ }
+ if (['record', 'selection', 'playhead', 'zoom'].includes(event.type)) close(element.contains(document.activeElement));
+ });
+ return {element, keyboard, dismiss, dispose() {
+ close(); unsubscribe(); listeners.forEach(remove => remove()); element.onkeydown = null; element.remove();
+ }};
+}
diff --git a/web/editor_model.js b/web/editor_model.js
new file mode 100644
index 0000000..d8223eb
--- /dev/null
+++ b/web/editor_model.js
@@ -0,0 +1,941 @@
+import {hasTextData, readTextProject, isText, trimText, assertUnlocked, changeText} from './editor_text_model.js';
+// Immutable editor records and frame arithmetic; usable without a browser.
+import {pictureFields, pictureEditor} from './editor_picture_fields.js';
+export const VERSION = 1;
+export const FPS = 24;
+export const RULES = Object.freeze({maxSeconds: 15, singleSeconds: 30, minSeconds: 2, tailSeconds: 5,
+ step: 17, first: 5, overlap: 22,
+ maxTracks: 3, maxClips: 500, maxText: 8000});
+// Slice and bound user text by Unicode code points, never UTF-16 halves.
+export const truncateText = (text, limit) => Array.from(text).slice(0, limit).join('');
+export const copyName = (name, suffix) => truncateText(name, RULES.maxText - Array.from(suffix).length) + suffix;
+const validText = text => typeof text === 'string' && Array.from(text).length <= RULES.maxText
+ && !Array.from(text).some(c => c.length === 1 && c.charCodeAt(0) >= 0xd800 && c.charCodeAt(0) <= 0xdfff);
+export class EditError extends Error {
+ constructor(code, message = code) { super(message); this.name = 'EditError'; this.code = code; }
+}
+const reject = (code, message) => { throw new EditError(code, message); };
+const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
+const whole = (value, low = 0, high = 1e7) => Number.isSafeInteger(value) && value >= low && value <= high;
+const check = (yes, code = 'invalid', message = code) => { if (!yes) reject(code, message); };
+const ID = /^c[1-9]\d{0,8}$/;
+// Who last wrote a block's description (its note on the timeline), and an outside reference (a shot id).
+const TEXT_BY = ['user', 'agent'], REF = /^[A-Za-z0-9_-]{1,128}$/;
+const WORK = /^\d{4}-\d{2}-\d{2}\/[0-9a-f]{32}$/;
+const PENDING = [null, 'draft', 'queued', 'running', 'failed', 'stopped'];
+const key = source => `${source.kind}:${source.id}`;
+const all = record => record.tracks.flatMap(track => track.clips);
+const trackOf = (record, id) => record.tracks.find(track => track.clips.some(clip => clip.id === id));
+const trackBy = (record, id) => { const track = record.tracks.find(track => track.id === id); check(track, 'track'); return track; };
+const end = clip => clip.start + clip.frames;
+const overlaps = (clip, start, frames) => clip.start < start + frames && end(clip) > start;
+const busy = clips => check(!clips.some(clip => ['queued', 'running'].includes(clip.pending)), 'busy');
+function frozen(value) {
+ if (value && typeof value === 'object') { Object.values(value).forEach(frozen); Object.freeze(value); }
+ return value;
+}
+function jsonData(value, depth = 0) {
+ check(depth <= 32, 'invalid', 'settings too deep');
+ if (value === null || typeof value === 'string' || typeof value === 'boolean') return value;
+ if (typeof value === 'number') { check(Number.isFinite(value)); return value; }
+ check(Array.isArray(value) || (object(value) && [null, Object.prototype].includes(Object.getPrototypeOf(value))));
+ if (Array.isArray(value)) return value.map(item => jsonData(item, depth + 1));
+ return Object.fromEntries(Object.entries(value).map(([name, item]) => [name, jsonData(item, depth + 1)]));
+}
+function sourceData(value) {
+ check(object(value) && ['work', 'import', 'generated'].includes(value.kind), 'source');
+ check(typeof value.id === 'string' && value.id.length > 0 && value.id.length <= 1024, 'source');
+ if (value.kind === 'work') check(WORK.test(value.id), 'source');
+ else if (value.kind === 'import') check(/^[A-Za-z0-9_-]{1,80}$/.test(value.id), 'source');
+ else check(!value.id.includes(':') && value.id.toLowerCase().endsWith('.mp4') && !value.id.split('/').includes('.editor'), 'source');
+ if (value.kind !== 'work') check(!/[\\\x00-\x1f]/.test(value.id) && !value.id.startsWith('/') && !/^[A-Za-z]:/.test(value.id)
+ && value.id.split('/').every(part => part && part !== '.' && part !== '..'), 'source');
+ return {kind: value.kind, id: value.id};
+}
+function pictureFit(value) {
+ check(value === undefined || value === 'cover' || value === 'contain', 'fit');
+ return value ?? 'cover';
+}
+// Follow only the transition from no real video to a first real video.
+function followFirstSize(record, width, height) {
+ if (record.size_mode !== 'fixed' && !trackBy(record, 'v1').clips.some(clip => clip.source)
+ && whole(width, 2, 8193) && whole(height, 2, 8193)) {
+ record.width = Math.floor(width / 2) * 2; record.height = Math.floor(height / 2) * 2;
+ }
+}
+// The order a version was made in (1, 2, 3 …) and the description it was made from.
+function madeFields(value, result) {
+ if (value.take !== undefined) { check(whole(value.take, 1, 1e6), 'versions'); result.take = value.take; }
+ if (value.made_text !== undefined) { check(validText(value.made_text), 'text'); result.made_text = value.made_text; }
+}
+function versionData(value, kind) {
+ const source = sourceData(value);
+ check(whole(value.in) && whole(value.length, value.in + 1), 'range');
+ const result = {...source, in: value.in, length: value.length};
+ // Old splice offsets must survive a version switch as well as a save.
+ if (value.splice !== undefined) result.splice = spliceData(value.splice);
+ madeFields(value, result);
+ if (kind === 'video') { Object.assign(result, pictureFields(value)); result.fit = pictureFit(value.fit); }
+ else check(value.fit === undefined, 'fit');
+ return result;
+}
+function spliceData(value) {
+ check(object(value) && whole(value.frames) && whole(value.audio_samples, 0, Number.MAX_SAFE_INTEGER), 'range');
+ return {frames: value.frames, audio_samples: value.audio_samples};
+}
+export function emptyProject({width = 1344, height = 768, settings = null, name = ''} = {}) {
+ return parse({version: VERSION, id: null, revision: 0, name, fps: FPS, width, height,
+ settings, serial: 0, tracks: [{id: 'v1', kind: 'video', clips: []}, {id: 'a1', kind: 'audio', clips: []}]});
+}
+export function addAudioTrack(record) {
+ const next = serialize(record);
+ check(!next.tracks.some(track => track.id === 'a2'), 'track');
+ next.tracks.push({id: 'a2', kind: 'audio', clips: []});
+ return parse(next);
+}
+export function removeAudioTrack(record) {
+ const next = serialize(record), track = trackBy(next, 'a2');
+ busy(track.clips);
+ const removed = new Set(track.clips.map(clip => clip.id));
+ next.tracks = next.tracks.filter(track => track.id !== 'a2');
+ for (const clip of all(next)) if (removed.has(clip.link)) clip.link = null;
+ return parse(next);
+}
+export function parse(value) {
+ check(object(value), 'invalid', 'not a project');
+ if (hasTextData(value)) return readTextProject(value, parse);
+ check(value.version === VERSION, 'version');
+ check(value.id === null || (typeof value.id === 'string' && /^e-[0-9a-f]{32}$/.test(value.id)), 'id');
+ check((value.id !== null || value.revision === 0) && whole(value.revision, 0, Number.MAX_SAFE_INTEGER) && whole(value.serial, 0, 999999999), 'invalid');
+ check(validText(value.name), 'text');
+ check(value.fps === FPS, 'fps');
+ check(whole(value.width, 2, 8192) && whole(value.height, 2, 8192)
+ && value.width % 2 === 0 && value.height % 2 === 0, 'size');
+ check(value.settings === null || object(value.settings), 'settings');
+ const settings = jsonData(value.settings);
+ check(JSON.stringify(settings).length <= 1024 * 1024, 'settings');
+ check(Array.isArray(value.tracks) && value.tracks.length >= 2 && value.tracks.length <= RULES.maxTracks, 'track');
+ const ids = new Set();
+ const tracks = value.tracks.map((raw, index) => {
+ const id = ['v1', 'a1', 'a2'][index], kind = index === 0 ? 'video' : 'audio';
+ check(object(raw) && raw.id === id && raw.kind === kind, 'track');
+ check(Array.isArray(raw.clips) && raw.clips.length <= RULES.maxClips, 'track');
+ let boundary = 0;
+ const clips = raw.clips.map(item => {
+ check(object(item) && typeof item.id === 'string' && ID.test(item.id)
+ && !ids.has(item.id) && Number(item.id.slice(1)) <= value.serial, 'id');
+ ids.add(item.id);
+ check(item.text_kind === undefined && item.text_style === undefined, 'text');
+ check(whole(item.start) && whole(item.frames, 1) && whole(item.in)
+ && whole(item.length, item.in + item.frames) && whole(item.start + item.frames), 'range');
+ check(item.start >= boundary, 'overlap'); boundary = end(item);
+ const source = item.source === null ? null : sourceData(item.source);
+ const pending = item.pending ?? null;
+ check(PENDING.includes(pending) && (source !== null || pending !== null), 'pending');
+ check(source !== null || (item.in === 0 && item.length === item.frames), 'range');
+ const link = item.link ?? null, part = item.part ?? null, job = item.job ?? null, reason = item.reason ?? null;
+ check(link === null || (typeof link === 'string' && ID.test(link) && link !== item.id), 'link');
+ check(part === null || (typeof part === 'string' && ID.test(part)), 'part');
+ check(job === null || (typeof job === 'string' && /^[A-Za-z0-9_-]{1,128}$/.test(job)), 'job');
+ check(reason === null || (typeof reason === 'string' && /^[a-z_]{1,80}$/.test(reason)), 'reason');
+ check(pending === 'failed' || reason === null, 'reason');
+ const text = item.text ?? '';
+ check(validText(text), 'text');
+ check(typeof item.extend === 'boolean', 'extend');
+ check(Array.isArray(item.versions) && item.versions.length <= 50, 'versions');
+ const versions = item.versions.map(value => versionData(value, kind)), versionKeys = versions.map(key);
+ check(new Set(versionKeys).size === versions.length, 'versions');
+ const clip = {id: item.id, start: item.start, frames: item.frames, in: item.in, length: item.length,
+ source, link, text, part, pending, reason, job, extend: item.extend, versions};
+ if (kind === 'video') { Object.assign(clip, pictureFields(item)); clip.fit = pictureFit(item.fit); }
+ else check(item.fit === undefined, 'fit');
+ if (kind === 'audio') { check(typeof item.volume === 'number' && Number.isFinite(item.volume) && item.volume >= 0 && item.volume <= 2, 'volume'); clip.volume = item.volume; }
+ else check(item.volume === undefined, 'volume');
+ if (item.splice !== undefined) { check(source !== null, 'range'); clip.splice = spliceData(item.splice); }
+ // Persist the user's targets so prepare is idempotent after reload.
+ if (item.target_frames !== undefined) { check(whole(item.target_frames, 1), 'range'); clip.target_frames = item.target_frames; }
+ // Who last wrote the description, and an outside reference (a shot id) for callers.
+ if (item.text_by !== undefined) { check(TEXT_BY.includes(item.text_by), 'text'); clip.text_by = item.text_by; }
+ if (item.ref !== undefined) { check(typeof item.ref === 'string' && REF.test(item.ref), 'ref'); clip.ref = item.ref; }
+ check(source !== null || (item.take === undefined && item.made_text === undefined), 'versions'); madeFields(item, clip);
+ return clip;
+ });
+ return {id, kind, clips};
+ });
+ const byId = new Map(tracks.flatMap(track => track.clips.map(clip => [clip.id, {clip, track}])));
+ for (const {clip, track} of byId.values()) if (clip.link) {
+ const mate = byId.get(clip.link);
+ check(mate && mate.clip.link === clip.id && mate.track.kind !== track.kind, 'link');
+ check(mate.clip.start === clip.start && mate.clip.frames === clip.frames && mate.clip.in === clip.in, 'link');
+ }
+ const result = {version: VERSION, id: value.id, revision: value.revision, name: value.name, fps: FPS,
+ width: value.width, height: value.height, settings, serial: value.serial, tracks};
+ check(value.size_mode === undefined || value.size_mode === 'first' || value.size_mode === 'fixed', 'size_mode');
+ result.size_mode = value.size_mode ?? 'first';
+ if (value.replacements !== undefined) {
+ check(Array.isArray(value.replacements) && value.replacements.length > 0 && value.replacements.length <= RULES.maxClips, 'invalid');
+ const parts = new Set();
+ result.replacements = value.replacements.map(raw => {
+ check(object(raw) && ID.test(raw.part) && !parts.has(raw.part) && typeof raw.rolledBack === 'boolean', 'invalid'); parts.add(raw.part);
+ const read = rows => {
+ check(Array.isArray(rows) && rows.length === 2 && rows.every(t => object(t) && Array.isArray(t.clips) && t.clips.length), 'invalid');
+ return parse({...result, tracks: rows, replacements: undefined}).tracks;
+ };
+ const originals = read(raw.originals), clips = read(raw.clips);
+ check(originals.every(t => t.clips.every(c => c.source && c.link && ['work', 'generated'].includes(c.source.kind))), 'invalid');
+ check(clips.every(t => t.clips.every(c => c.part === raw.part && c.link)), 'invalid');
+ const bounds = rows => rows.map(t => [t.clips[0].start, end(t.clips.at(-1))]);
+ check(JSON.stringify(bounds(originals)) === JSON.stringify(bounds(clips)), 'invalid');
+ return {part: raw.part, originals, clips, rolledBack: raw.rolledBack};
+ });
+ }
+ return frozen(result);
+}
+export function serialize(record) {
+ const value = JSON.parse(JSON.stringify(parse(record)));
+ if (value.size_mode === 'first') delete value.size_mode;
+ for (const tracks of [value.tracks, ...(value.replacements || []).flatMap(tx => [tx.originals, tx.clips])])
+ for (const clip of tracks[0].clips) for (const item of [clip, ...clip.versions])
+ if (item.fit === 'cover') delete item.fit;
+ return value;
+}
+export const duration = record => Math.max(0, ...all(record).map(end));
+// An export runs as long as the picture and sound; text after them is not exported.
+export const exportFrames = record => Math.max(0, ...record.tracks.filter(track => ['video', 'audio'].includes(track.kind)).flatMap(track => track.clips).map(end));
+export const find = (record, id) => all(record).find(clip => clip.id === id) ?? null;
+// A failed replacement displays its original timeline while retaining receipts
+// for every block of the same resumable attempt, including subdivided blocks.
+export const attemptClip = (record, id) => record.replacements?.flatMap(r => r.clips.flatMap(t => t.clips)).find(c => c.id === id) ?? find(record, id);
+export function pair(record, id) {
+ const clip = find(record, id);
+ return clip ? all(record).filter(item => item.id === id || item.id === clip.link) : [];
+}
+export function gaps(record, trackId) {
+ const result = [], track = trackBy(record, trackId); let start = 0;
+ for (const clip of track.clips) { if (clip.start > start) result.push({kind: 'gap', track: trackId, start, frames: clip.start - start}); start = end(clip); }
+ if (start < duration(record)) result.push({kind: 'gap', track: trackId, start, frames: duration(record) - start});
+ return result;
+}
+export function at(record, frame) {
+ check(whole(frame), 'range');
+ return Object.fromEntries(record.tracks.map(track => {
+ const clip = track.clips.find(item => overlaps(item, frame, 1));
+ return [track.id, clip ? {clip, frame: clip.in + frame - clip.start} : null];
+ }));
+}
+export function snapPoints(record, exceptIds = []) {
+ const excluded = linkedIds(record, exceptIds);
+ return [...new Set([0, ...all(record).filter(clip => !excluded.has(clip.id)).flatMap(clip => [clip.start, end(clip)])])].sort((a, b) => a - b);
+}
+// A selection is not stored content. Every clip on its occupied tracks counts,
+// including queued/running work and placeholders left after a failed attempt.
+export function rangeOccupied(record, {start, frames, tracks}) {
+ return record.tracks.some(track => tracks.includes(track.id) && track.clips.some(clip => overlaps(clip, start, frames)));
+}
+export function references(record) {
+ const result = new Map();
+ const clips = [...all(record), ...(record.replacements || []).flatMap(r => [...r.originals, ...r.clips].flatMap(t => t.clips))];
+ for (const clip of clips) for (const source of [clip.source, ...clip.versions]) if (source) result.set(key(source), {kind: source.kind, id: source.id});
+ return [...result.values()];
+}
+export const clipState = clip => ['queued', 'running'].includes(clip.pending) ? 'running'
+ : clip.pending === 'failed' ? 'failed' : clip.source || isText(clip) ? 'done' : 'planned';
+export const emptyFrames = record => duration(record) - trackBy(record, 'v1').clips.filter(clip => clip.source).reduce((sum, clip) => sum + clip.frames, 0);
+export const secondsLabel = frames => { check(whole(frames), 'range'); return String(Math.round(frames / FPS)); };
+const copy = record => JSON.parse(JSON.stringify(parse(record)));
+function finish(record) {
+ for (const track of record.tracks) track.clips.sort((a, b) => a.start - b.start);
+ // Track presence is an edit in its own right, including an empty a2.
+ if (record.replacements) {
+ record.replacements = record.replacements.filter(tx => {
+ if (tx.rolledBack) {
+ // Reordering and volume edits keep the attempt attached to its media.
+ for (const row of tx.originals) {
+ const positions = row.clips.map(old => ({old, visible: find(record, old.id)}));
+ for (const clip of tx.clips.find(t => t.id === row.id).clips) {
+ const owner = positions.find(({old}) => clip.start >= old.start && end(clip) <= end(old));
+ if (!owner?.visible) continue;
+ clip.start += owner.visible.start - owner.old.start;
+ if (row.kind === 'audio') clip.volume = owner.visible.volume;
+ }
+ for (const {old, visible} of positions) if (visible) {
+ old.start = visible.start;
+ if (row.kind === 'audio') old.volume = visible.volume;
+ }
+ }
+ for (const row of [...tx.originals, ...tx.clips]) row.clips.sort((a, b) => a.start - b.start);
+ const job = tx.clips.flatMap(t => t.clips).find(c => c.job)?.job ?? null;
+ const media = c => [c.start, c.frames, c.in, c.length, c.link, c.source, c.versions, c.splice];
+ return tx.originals.every(t => t.clips.every(c => { const visible = find(record, c.id); return visible?.part === tx.part && visible.pending && visible.job === job && JSON.stringify(media(visible)) === JSON.stringify(media(c)); }));
+ }
+ tx.clips = record.tracks.slice(0, 2).map(t => ({...t, clips: t.clips.filter(c => c.part === tx.part)}));
+ return tx.clips.every(t => t.clips.length) && tx.clips.some(t => t.clips.some(c => c.pending));
+ });
+ if (!record.replacements.length) delete record.replacements;
+ }
+ return parse(record);
+}
+function materialize(record, tx, rows) {
+ const ids = new Set([...tx.originals, ...tx.clips].flatMap(t => t.clips.map(c => c.id)));
+ for (const t of rows) trackBy(record, t.id).clips = [...trackBy(record, t.id).clips.filter(c => !ids.has(c.id)), ...structuredClone(t.clips)].sort((a,b) => a.start-b.start);
+}
+function activate(record, id) {
+ const next = copy(record), tx = next.replacements?.find(r => [...r.originals, ...r.clips].some(t => t.clips.some(c => c.id === id)));
+ if (tx?.rolledBack) { materialize(next, tx, tx.clips); tx.rolledBack = false; }
+ return next;
+}
+function rollback(record, id, pending, reason = null) {
+ const next = copy(record), tx = next.replacements?.find(r => r.clips.some(t => t.clips.some(c => c.id === id)));
+ if (!tx) return record;
+ const job = tx.clips.flatMap(t => t.clips).find(c => c.job)?.job ?? null, text = tx.clips[0].clips[0].text;
+ materialize(next, tx, tx.originals);
+ for (const t of tx.originals) for (const old of t.clips) Object.assign(find(next, old.id), {part: tx.part, job, pending, reason, text});
+ tx.rolledBack = true;
+ return finish(next);
+}
+function audioTrack(record, id = 'a1') {
+ if (!record.tracks.some(track => track.id === id)) record.tracks.push({id, kind: 'audio', clips: []});
+ return trackBy(record, id);
+}
+const freshId = record => `c${++record.serial}`;
+function newClip(record, track, {source = null, start, frames, part = null, text = ''}) {
+ const clip = {id: freshId(record), start, frames, in: 0, length: frames, source, link: null,
+ text, part, pending: source ? null : 'draft', reason: null, job: null,
+ extend: source ? source.kind !== 'import' : true, versions: []};
+ if (track.kind === 'audio') clip.volume = 1;
+ track.clips.push(clip); return clip;
+}
+function clearPlan(clip) { delete clip.target_frames; }
+// The description of a block (what it shows: the note on the timeline that regenerating uses), and who wrote it.
+// A linked pair shares it; a part being generated keeps the one it was started with.
+export function describe(record, ids, text, {by = 'user'} = {}) {
+ check(typeof text === 'string' && validText(text.trim()) && TEXT_BY.includes(by), 'text');
+ return onBlocks(record, ids, clip => written(clip, text.trim(), by), true);
+}
+// An outside reference kept with the block (for example a shot id); an empty value removes it.
+export function setRef(record, ids, ref) {
+ check(typeof ref === 'string' && (!ref || REF.test(ref)), 'ref');
+ return onBlocks(record, ids, clip => { if (ref) clip.ref = ref; else delete clip.ref; }, false);
+}
+// Only an agent's description is marked; no mark means the user wrote it, as in every earlier edit.
+function written(clip, text, by) { clip.text = text; if (text && by === 'agent') clip.text_by = by; else delete clip.text_by; }
+function onBlocks(record, ids, change, refuseBusy) {
+ check(Array.isArray(ids) && ids.length > 0 && ids.every(id => typeof id === 'string'), 'id');
+ for (const id of ids) check(find(record, id), 'missing');
+ const selected = linkedIds(record, ids), clips = all(record).filter(clip => selected.has(clip.id));
+ check(!clips.some(isText), 'text'); assertUnlocked(record, [...selected]); if (refuseBusy) busy(clips);
+ const next = copy(record); for (const clip of all(next)) if (selected.has(clip.id)) change(clip);
+ return finish(next);
+}
+export function linkedIds(record, ids) {
+ check(Array.isArray(ids) && ids.every(id => typeof id === 'string'), 'id');
+ const clips = new Map(all(record).map((clip, index) => [clip.id, {clip, index}]));
+ return new Set(ids.flatMap(id => {
+ const item = clips.get(id), mate = clips.get(item?.clip.link);
+ return !item ? [] : !mate ? [id] : item.index < mate.index ? [id, mate.clip.id] : [mate.clip.id, id];
+ }));
+}
+function shift(record, from, delta, excluded = new Set()) {
+ for (const clip of all(record)) if (clip.start >= from && !excluded.has(clip.id)) clip.start += delta;
+ // Keep retry/rollback receipts at the same position as the visible content.
+ for (const tx of record.replacements || []) for (const row of [...tx.originals, ...tx.clips])
+ for (const clip of row.clips) if (clip.start >= from && !excluded.has(clip.id)) clip.start += delta;
+}
+export function insertionAt(record, trackId, start) {
+ check(whole(start), 'range');
+ const hit = trackBy(record, trackId).clips.find(clip => clip.start < start && end(clip) > start);
+ return hit ? end(hit) : start;
+}
+// Measure the gap only on the occupied tracks, then move the same suffix on
+// every track. Earlier-starting content, including crossing music, stays put.
+export function roomAt(record, from, frames, {tracks = record.tracks.map(t => t.id), excluded = []} = {}) {
+ check(whole(from) && whole(frames), 'range');
+ tracks = new Set(tracks); excluded = new Set(excluded);
+ const later = all(record).filter(clip => clip.start >= from && !excluded.has(clip.id));
+ const gap = Math.min(...later.filter(clip => tracks.has(trackOf(record, clip.id).id)).map(clip => clip.start - from));
+ const shift = Math.max(0, frames - gap);
+ const locked = shift > 0 && later.some(clip => trackOf(record, clip.id).locked);
+ return {shift, limit: from + gap, blocked: locked || shift > 0 && later.some(clip => ['queued', 'running'].includes(clip.pending)),
+ ...(locked ? {code: 'locked'} : {})};
+}
+function applyRoom(record, from, frames, {excluded = [], ...options} = {}) {
+ const room = roomAt(record, from, frames, {...options, excluded});
+ check(!room.blocked, room.code || 'busy');
+ if (room.shift) {
+ excluded = new Set(excluded);
+ shift(record, from, room.shift, excluded);
+ }
+}
+export function makeRoom(record, from, frames, options) {
+ const room = roomAt(record, from, frames, options); check(!room.blocked, room.code || 'busy');
+ const next = copy(record); applyRoom(next, from, frames, options); return finish(next);
+}
+function rightEdgeOptions(record, id, {generating = false, frames = 0} = {}) {
+ const selected = pair(record, id); check(selected.length, 'missing');
+ const tracks = new Set(selected.map(clip => trackOf(record, clip.id).id));
+ if (generating) tracks.add(sourceAudioTrack(copy(record), end(selected[0]), frames, true).id);
+ return {from: end(selected[0]), tracks, excluded: selected.map(clip => clip.id)};
+}
+export function rightEdgeRoom(record, id, frames, options) {
+ const {from, ...roomOptions} = rightEdgeOptions(record, id, {...options, frames});
+ return roomAt(record, from, frames, roomOptions);
+}
+function makeRightEdgeRoom(record, id, frames, options) {
+ const {from, ...roomOptions} = rightEdgeOptions(record, id, {...options, frames});
+ applyRoom(record, from, frames, roomOptions);
+}
+function sourceAudioTrack(record, start, frames, allowRoom = false) {
+ // Keep a free lane when possible; otherwise only later starts can yield.
+ if (allowRoom) try { return sourceAudioTrack(record, start, frames); } catch (error) { if (error.code !== 'audio_full') throw error; }
+ for (const id of ['a1', 'a2']) {
+ const track = record.tracks.find(row => row.id === id);
+ if (!track || !track.clips.some(clip => (!allowRoom || clip.start < start) && overlaps(clip, start, frames))) return audioTrack(record, id);
+ }
+ throw new EditError('audio_full');
+}
+export function insertSource(record, {source, frames, hasVideo, hasAudio, width, height, at: position = 0}) {
+ source = sourceData(source); check(whole(frames, 1) && whole(position), 'range');
+ check(typeof hasVideo === 'boolean' && typeof hasAudio === 'boolean' && (hasVideo || hasAudio), 'source');
+ const next = copy(record);
+ if (hasVideo) followFirstSize(next, width, height);
+ let track = trackBy(next, hasVideo ? 'v1' : 'a1');
+ if (!hasVideo && track.clips.some(clip => overlaps(clip, position, frames))) track = audioTrack(next, 'a2');
+ const start = insertionAt(next, track.id, position);
+ const available = hasVideo && hasAudio ? copy(makeRoom(next, start, frames, {tracks: [track.id]})) : null;
+ const sound = available ? audioTrack(next, sourceAudioTrack(available, start, frames, true).id) : null;
+ applyRoom(next, start, frames, {tracks: [track.id, ...(sound ? [sound.id] : [])]});
+ const primary = newClip(next, track, {source, frames, start});
+ if (hasVideo && hasAudio) {
+ const mate = newClip(next, sound, {source, frames, start});
+ primary.link = mate.id; mate.link = primary.id;
+ }
+ return finish(next);
+}
+export function move(record, id, start) {
+ if (isText(find(record, id))) return changeText(record, id, {start});
+ check(whole(start), 'range'); const selected = pair(record, id); check(selected.length, 'missing'); busy(selected);
+ const next = copy(record), ids = new Set(selected.map(clip => clip.id));
+ const clips = all(next).filter(clip => ids.has(clip.id)), primary = clips[0], track = trackOf(next, primary.id);
+ for (const row of next.tracks) row.clips = row.clips.filter(clip => !ids.has(clip.id));
+ start = insertionAt(next, track.id, start);
+ const sound = track.kind === 'video' && clips.find(clip => trackOf(record, clip.id).kind === 'audio');
+ const available = sound ? makeRoom(next, start, primary.frames, {tracks: [track.id]}) : null;
+ const soundTrack = sound ? sourceAudioTrack(available, start, primary.frames, true).id : null;
+ applyRoom(next, start, primary.frames, {tracks: [track.id, ...(soundTrack ? [soundTrack] : [])], excluded: ids});
+ for (const clip of clips) { clip.start = start; (clip === sound ? audioTrack(next, soundTrack) : trackBy(next, trackOf(record, clip.id).id)).clips.push(clip); }
+ return finish(next);
+}
+// A selected group keeps its gaps and tracks; validation rejects occupied landings.
+export function moveTogether(record, ids, delta) {
+ assertUnlocked(record, ids);
+ check(Number.isSafeInteger(delta), 'range');
+ const selected = linkedIds(record, ids), clips = all(record).filter(clip => selected.has(clip.id));
+ check(clips.length && ids.every(id => selected.has(id)), 'missing'); busy(clips);
+ delta = Math.max(delta, -Math.min(...clips.map(clip => clip.start)));
+ const next = copy(record);
+ for (const clip of all(next)) if (selected.has(clip.id)) clip.start += delta;
+ return finish(next);
+}
+function detachAttempt(record, ids) {
+ const selected = new Set(ids);
+ // Geometry/version edits detach only the affected source ranges.
+ if (record.replacements) {
+ record.replacements = record.replacements.filter(tx => {
+ if (!tx.originals.some(t => t.clips.some(c => selected.has(c.id)))) return true;
+ for (const row of tx.originals) {
+ const removed = row.clips.filter(c => selected.has(c.id));
+ tx.clips.find(t => t.id === row.id).clips = tx.clips.find(t => t.id === row.id).clips
+ .filter(c => !removed.some(old => c.start >= old.start && end(c) <= end(old)));
+ row.clips = row.clips.filter(c => !selected.has(c.id));
+ }
+ if (tx.originals.some(t => !t.clips.length)) return false;
+ if (tx.clips.some(t => t.clips.some(c => c.pending))) return true;
+ materialize(record, tx, tx.clips); return false;
+ });
+ if (!record.replacements.length) delete record.replacements;
+ }
+ for (const clip of all(record)) if (selected.has(clip.id) && clip.job) {
+ clip.job = clip.reason = clip.part = null; clip.pending = clip.source ? null : 'draft'; clearPlan(clip);
+ }
+}
+export function trim(record, id, edge, frame, {minimumFrames = FPS, by = 'user'} = {}) {
+ if (isText(find(record, id))) { check(['start', 'end'].includes(edge) && whole(frame), 'range'); return trimText(record, id, edge, frame); }
+ check(['start', 'end'].includes(edge) && whole(frame) && whole(minimumFrames, 1) && TEXT_BY.includes(by), 'range');
+ const clips = pair(record, id); check(clips.length, 'missing'); busy(clips);
+ const primary = clips[0], minimum = Math.min(minimumFrames, primary.frames);
+ const delta = edge === 'start' ? Math.min(primary.frames - minimum, Math.max(-Math.min(...clips.map(clip => clip.in)), frame - primary.start))
+ : Math.max(minimum - primary.frames, Math.min(Math.min(...clips.map(clip => clip.length - clip.in - clip.frames)), frame - end(primary)));
+ const next = copy(record);
+ if (delta) detachAttempt(next, clips.map(c => c.id));
+ if (edge === 'end' && delta > 0) makeRightEdgeRoom(next, id, delta);
+ for (const clip of all(next).filter(clip => clips.some(item => item.id === clip.id))) {
+ if (edge === 'start') {
+ clip.start += delta; clip.in += delta; clip.frames -= delta;
+ clip.versions = clip.versions.map(version => ({...version, in: Math.max(0, version.in + delta)}))
+ .filter(version => version.in < version.length);
+ }
+ else clip.frames += delta;
+ if (!clip.source) { clip.in = 0; clip.length = clip.frames; }
+ if (delta) touchedBy(clip, by);
+ clearPlan(clip);
+ }
+ return finish(next);
+}
+export function split(record, id, frame, {by = 'user'} = {}) {
+ assertUnlocked(record, [id]);
+ check(whole(frame) && TEXT_BY.includes(by), 'range'); const clips = pair(record, id); check(clips.length, 'missing'); busy(clips);
+ const primary = clips[0]; check(frame >= primary.start && frame <= end(primary), 'range');
+ if (frame === primary.start || frame === end(primary)) return parse(record);
+ const next = copy(record), left = frame - primary.start, rights = [];
+ detachAttempt(next, clips.map(c => c.id));
+ for (const old of clips) {
+ const clip = find(next, old.id); touchedBy(clip, by);
+ const right = structuredClone(clip); right.id = freshId(next); right.start = frame; right.frames -= left; right.in += left;
+ clip.frames = left; clearPlan(clip); clearPlan(right);
+ if (!clip.source) { clip.in = right.in = 0; clip.length = clip.frames; right.length = right.frames; }
+ right.versions = right.versions.map(version => ({...version, in: version.in + left}));
+ for (const item of [clip, right]) item.versions = item.versions.filter(version => version.in < version.length);
+ trackOf(next, clip.id).clips.push(right); rights.push(right);
+ }
+ if (rights.length === 2) { rights[0].link = rights[1].id; rights[1].link = rights[0].id; }
+ return finish(next);
+}
+export function remove(record, ids) {
+ assertUnlocked(record, ids);
+ check(Array.isArray(ids), 'id'); const selected = linkedIds(record, ids);
+ busy(all(record).filter(clip => selected.has(clip.id)));
+ const next = copy(record); for (const track of next.tracks) track.clips = track.clips.filter(clip => !selected.has(clip.id));
+ return finish(next);
+}
+export function closeGap(record, trackId, frame) {
+ assertUnlocked(record, trackBy(record, trackId).clips.map(c => c.id));
+ check(whole(frame), 'range');
+ const gap = gaps(record, trackId).find(item => frame >= item.start && frame < item.start + item.frames);
+ if (!gap) return parse(record);
+ const from = gap.start + gap.frames;
+ for (const track of record.tracks) {
+ const moving = track.clips.filter(clip => clip.start >= from), fixed = track.clips.filter(clip => clip.start < from);
+ const code = moving.some(clip => ['queued', 'running'].includes(clip.pending)) ? 'busy'
+ : moving.length && track.locked ? 'locked'
+ : moving.some(clip => fixed.some(other => overlaps(other, clip.start - gap.frames, clip.frames))) ? 'overlap' : null;
+ if (code) { const error = new EditError(code); error.track = track.id; throw error; }
+ }
+ const next = copy(record); shift(next, from, -gap.frames); return finish(next);
+}
+export function setVolume(record, id, volume) {
+ const next = copy(record), track = trackOf(next, id); check(track, 'missing'); check(track.kind === 'audio', 'track');
+ find(next, id).volume = volume;
+ for (const tx of next.replacements || []) if (tx.rolledBack) {
+ const old = tx.originals.flatMap(t => t.clips).find(c => c.id === id);
+ if (old) { old.volume = volume; for (const t of tx.clips) if (t.kind === 'audio') for (const c of t.clips) if (c.start >= old.start && end(c) <= end(old)) c.volume = volume; }
+ }
+ return finish(next);
+}
+export const rename = (record, name) => finish({...copy(record), name});
+export const setPictureSize = (record, width, height, size_mode = 'fixed') => finish({...copy(record), width, height, size_mode});
+export const setPicture = pictureEditor({copy, trackBy, check, pictureFit, finish});
+export const setPictureFit = (record, id, fit) => setPicture(record, id, {fit: pictureFit(fit)});
+
+function segmentLengths(frames, maxSeconds = RULES.maxSeconds, maxFollowSeconds = maxSeconds) {
+ check(typeof maxSeconds === 'number' && Number.isFinite(maxSeconds) && maxSeconds >= RULES.minSeconds, 'range');
+ check(typeof maxFollowSeconds === 'number' && Number.isFinite(maxFollowSeconds) && maxFollowSeconds >= RULES.minSeconds, 'range');
+ const max = Math.floor(Math.min(RULES.maxSeconds, maxSeconds)) * FPS, follow = Math.floor(Math.min(RULES.maxSeconds, maxFollowSeconds)) * FPS, lengths = [];
+ let left = Math.max(RULES.minSeconds, Math.round(frames / FPS)) * FPS;
+ // Up to half a minute is one generation wherever this device makes it in one;
+ // anything longer, or beyond the device, goes in parts of a quarter minute.
+ if (left <= Math.floor(Math.min(RULES.singleSeconds, maxSeconds)) * FPS) return [left];
+ check(left <= RULES.maxClips * max, 'range');
+ while (left) { const length = Math.min(left, lengths.length ? follow : max); lengths.push(length); left -= length; }
+ const last = lengths.length - 1;
+ if (last > 0 && lengths[last] < Math.min(follow, RULES.tailSeconds * FPS)) {
+ const both = lengths[last - 1] + lengths[last]; lengths[last - 1] = Math.min(last === 1 ? max : follow, Math.max(both - follow, Math.ceil(both / 2 / FPS) * FPS)); lengths[last] = both - lengths[last - 1];
+ }
+ return lengths;
+}
+function oldVersion(clip) {
+ return {...clip.source, in: clip.in, length: clip.length, ...pictureFields(clip), ...(clip.splice ? {splice: clip.splice} : {}),
+ ...(clip.take ? {take: clip.take} : {}), ...(clip.made_text !== undefined ? {made_text: clip.made_text} : {})};
+}
+// Saved edits from before version numbers count their versions newest first.
+function numberTakes(clip) {
+ const items = [...clip.versions].reverse(); if (clip.source) items.push(clip);
+ if (!items.every(item => item.take)) items.forEach((item, index) => { item.take = index + 1; });
+ return items.reduce((most, item) => Math.max(most, item.take), 0);
+}
+// A part's versions in the order they were made; index -1 is the one in use.
+export function takes(clip) {
+ const items = clip.versions.map((version, index) => ({index, take: version.take,
+ usable: version.in + clip.frames <= version.length})).reverse();
+ if (clip.source) items.push({index: -1, take: clip.take, usable: true});
+ if (items.every(item => item.take)) items.sort((a, b) => a.take - b.take);
+ return items.map(({index, usable}, n) => ({index, number: n + 1, usable}));
+}
+// The description was changed after the version in use was made from it.
+export const describedSince = clip => !!clip.source && clip.made_text !== undefined && clip.text !== clip.made_text;
+// A user's own cut or version choice means an agent leaves the part alone.
+function touchedBy(clip, by) { if (by === 'user') delete clip.text_by; }
+function remember(clip, source = null) {
+ const versions = clip.source ? [oldVersion(clip), ...clip.versions] : clip.versions;
+ const seen = new Set();
+ clip.versions = versions.filter(version => {
+ const identity = key(version); if (identity === (source && key(source)) || seen.has(identity)) return false;
+ seen.add(identity); return true;
+ }).slice(0, 50);
+}
+// The lengths one range is generated in, as planRange lays them out on empty tracks.
+export const partLengths = (frames, {maxSeconds = RULES.maxSeconds, maxFollowSeconds = maxSeconds} = {}) => segmentLengths(frames, maxSeconds, maxFollowSeconds);
+// Manual boundaries use device limits, not the automatic fifteen-second preference.
+export function rangeParts(record, {start, frames, parts, maxSeconds = RULES.maxSeconds, maxFollowSeconds = maxSeconds}) {
+ const before = trackBy(record, 'v1').clips.find(clip => end(clip) === start && clip.source && clip.extend && clip.in + clip.frames === clip.length);
+ const first = before ? maxFollowSeconds : maxSeconds;
+ const valid = Array.isArray(parts) && parts.length > 0 && parts.length <= RULES.maxClips
+ && parts.every((count, i) => whole(count, RULES.minSeconds * FPS) && count % FPS === 0
+ && count <= Math.floor(i ? maxFollowSeconds : first) * FPS)
+ && parts.reduce((sum, count) => sum + count, 0) === frames;
+ return valid ? [...parts] : partLengths(frames, {maxSeconds: first, maxFollowSeconds});
+}
+export function adjustPartBoundary(parts, index, leftFrames, {maxSeconds = RULES.maxSeconds, maxFollowSeconds = maxSeconds} = {}) {
+ check(Array.isArray(parts) && whole(index) && index < parts.length - 1 && Number.isFinite(leftFrames), 'range');
+ check(parts.every(count => whole(count, RULES.minSeconds * FPS) && count % FPS === 0), 'range');
+ const minimum = RULES.minSeconds * FPS, total = parts[index] + parts[index + 1];
+ const leftMax = Math.floor(index ? maxFollowSeconds : maxSeconds) * FPS, rightMax = Math.floor(maxFollowSeconds) * FPS;
+ const low = Math.max(minimum, total - rightMax), high = Math.min(leftMax, total - minimum);
+ check(Number.isFinite(low) && Number.isFinite(high) && low <= high, 'range');
+ const desired = Math.round(leftFrames / FPS) * FPS, left = Math.max(low, Math.min(high, desired));
+ const result = [...parts]; result[index] = left; result[index + 1] = total - left;
+ return {parts: result, limited: desired >= leftMax && left === leftMax ? leftMax / FPS
+ : total - desired >= rightMax && total - left === rightMax ? rightMax / FPS : null};
+}
+export function resizePlannedBoundary(record, leftId, rightId, frame, limits = {}) {
+ const left = find(record, leftId), right = find(record, rightId);
+ check(left && right && trackOf(record, leftId) === trackOf(record, rightId) && end(left) === right.start
+ && left.part && left.part === right.part, 'range');
+ const members = [...pair(record, leftId), ...pair(record, rightId)]; busy(members);
+ check(members.every(clip => clip.pending && !clip.source), 'unsupported');
+ const preceding = trackOf(record, leftId).clips.some(clip => end(clip) === left.start
+ && ((clip.part === left.part && clip.pending) || (clip.source && clip.extend && clip.in + clip.frames === clip.length)));
+ const maxSeconds = limits.maxSeconds ?? RULES.maxSeconds, maxFollowSeconds = limits.maxFollowSeconds ?? maxSeconds;
+ const result = adjustPartBoundary([left.frames, right.frames], 0, frame - left.start,
+ {maxSeconds: preceding ? maxFollowSeconds : maxSeconds, maxFollowSeconds});
+ const next = copy(record); detachAttempt(next, members.map(clip => clip.id));
+ for (const old of members) find(next, old.id).part = left.part;
+ for (const clip of pair(next, leftId)) { clip.frames = clip.length = result.parts[0]; clearPlan(clip); }
+ for (const clip of pair(next, rightId)) { clip.start = left.start + result.parts[0]; clip.frames = clip.length = result.parts[1]; clearPlan(clip); }
+ return finish(next);
+}
+export function resizePlanned(record, id, edge, frame, limits = {}) {
+ check(['start', 'end'].includes(edge) && whole(frame), 'range');
+ const members = pair(record, id); check(members.length, 'missing'); busy(members);
+ check(members.every(clip => clip.pending && !clip.source), 'unsupported');
+ const primary = members[0], minimum = RULES.minSeconds * FPS;
+ const neighbors = members.flatMap(clip => trackOf(record, clip.id).clips.filter(other => other.id !== clip.id));
+ const low = Math.max(0, ...neighbors.filter(clip => end(clip) <= primary.start).map(end));
+ const high = Math.min(1e7, ...neighbors.filter(clip => clip.start >= end(primary)).map(clip => clip.start));
+ const position = Math.round(frame / FPS) * FPS;
+ const start = edge === 'start' ? Math.max(low, Math.min(end(primary) - minimum, position)) : primary.start;
+ const stop = edge === 'end' ? Math.min(high, Math.max(start + minimum, position)) : end(primary);
+ let next = copy(record); detachAttempt(next, members.map(clip => clip.id));
+ const part = primary.part || freshId(next);
+ for (const clip of pair(next, id)) { clip.start = start; clip.frames = clip.length = stop - start; clip.part = part; clearPlan(clip); }
+ next = finish(next);
+ const lengths = rangeParts(next, {start, frames: stop - start, ...limits});
+ let positionAt = start, currentId = id;
+ for (const count of lengths.slice(0, -1)) {
+ positionAt += count; next = split(next, currentId, positionAt);
+ currentId = trackOf(next, id).clips.find(clip => clip.start === positionAt).id;
+ }
+ return next;
+}
+export function planRange(record, {start, frames, parts, target = 'both', text = '', by = 'user', maxSeconds = RULES.maxSeconds, maxFollowSeconds = maxSeconds}) {
+ check(TEXT_BY.includes(by), 'text');
+ check(whole(start) && whole(frames, 1), 'range'); check(['both', 'video', 'audio'].includes(target), 'target');
+ check(validText(text), 'text');
+ check(typeof maxSeconds === 'number' && Number.isFinite(maxSeconds) && maxSeconds >= RULES.minSeconds, 'range');
+ check(target === 'both', 'unsupported');
+ if (!record.tracks.some(track => track.clips.some(clip => overlaps(clip, start, frames)))) frames = Math.max(RULES.minSeconds, Math.round(frames / FPS)) * FPS;
+ const videoHits = trackBy(record, 'v1').clips.filter(clip => overlaps(clip, start, frames));
+ const audioHits = trackBy(record, 'a1').clips.filter(clip => overlaps(clip, start, frames));
+ const otherHits = record.tracks.find(track => track.id === 'a2')?.clips.filter(clip => overlaps(clip, start, frames)) || [];
+ const hits = [...videoHits, ...audioHits];
+ if (hits.length || otherHits.length) {
+ check(hits.length > 0, 'unsupported');
+ check(videoHits.length && audioHits.length === videoHits.length, 'unsupported');
+ let boundary = start;
+ for (const clip of videoHits) {
+ const mate = find(record, clip.link);
+ check(clip.start === boundary && end(clip) <= start + frames && mate && audioHits.includes(mate)
+ && (!!clip.source === !!mate.source) && (!clip.source || ['work', 'generated'].includes(clip.source.kind))
+ && (!mate.source || ['work', 'generated'].includes(mate.source.kind)), 'unsupported');
+ boundary = end(clip);
+ }
+ check(boundary === start + frames, 'unsupported');
+ }
+ const continuesAt = position => trackBy(record, 'v1').clips.some(clip => end(clip) === position && clip.source && clip.extend && clip.in + clip.frames === clip.length);
+ const firstMaximum = continuesAt(start) ? maxFollowSeconds : maxSeconds;
+ let next = copy(record);
+ const originals = videoHits.length && videoHits.every(c => c.source) ? record.tracks.slice(0, 2).map(t => ({...t, clips: t.clips.filter(c => overlaps(c, start, frames))})) : null;
+ // A new attempt replaces an abandoned transaction over the same originals.
+ if (next.replacements) { next.replacements = next.replacements.filter(tx => !tx.originals.some(t => t.clips.some(c => hits.some(hit => hit.id === c.id)))); if (!next.replacements.length) delete next.replacements; }
+ const targetTracks = target === 'both' ? ['v1', 'a1'] : [target === 'video' ? 'v1' : 'a1'];
+ const affected = () => targetTracks.flatMap(track => trackBy(next, track).clips.filter(clip => overlaps(clip, start, frames)));
+ // A completed segment may be 362 rather than 360 frames. Selecting that
+ // entire segment must not round off two frames and become a partial edit.
+ if (!affected().length) frames = Math.max(RULES.minSeconds, Math.round(frames / FPS)) * FPS;
+
+ let touched = affected();
+ busy(touched);
+ check(touched.every(clip => clip.start >= start && end(clip) <= start + frames), 'range');
+ // Re-generation preserves existing editable boundaries and playable media.
+ // Only the currently unproved single-track linked replacement is refused.
+ check(target === 'both' || !touched.some(clip => clip.link), 'unsupported');
+ if (target === 'audio') check(trackBy(next, 'v1').clips.some(clip => clip.source && clip.start <= start && end(clip) >= start + frames), 'range');
+ // A long imported/work clip is split into playable source slices before
+ // being replaced. Allow the small grid excess of an already prepared clip.
+ const maximum = Math.floor(Math.min(firstMaximum, RULES.maxSeconds)) * FPS;
+ const handled = new Set();
+ for (const old of touched) {
+ if (handled.has(old.id)) continue;
+ pair(next, old.id).forEach(clip => handled.add(clip.id));
+ if (old.frames <= maximum + RULES.step - 1) continue;
+ const lengths = segmentLengths(old.frames, old.start === start ? firstMaximum : maxFollowSeconds, maxFollowSeconds);
+ lengths[lengths.length - 1] += old.frames - lengths.reduce((sum, count) => sum + count, 0);
+ let id = old.id, position = old.start;
+ for (const count of lengths.slice(0, -1)) {
+ position += count;
+ next = copy(split(finish(next), id, position, {by}));
+ id = trackBy(next, trackOf(record, old.id).id).clips.find(clip => clip.start === position).id;
+ }
+ }
+ touched = affected();
+ const boundaries = [...new Set([start, start + frames, ...touched.flatMap(clip => [clip.start, end(clip)])])].sort((a, b) => a - b);
+ const part = freshId(next);
+ for (const clip of touched) {
+ clip.pending = 'draft'; clip.reason = clip.job = null; written(clip, text, by); clip.part = part; clearPlan(clip);
+ }
+ for (let i = 0; i < boundaries.length - 1; i++) {
+ const from = boundaries[i], length = boundaries[i + 1] - from;
+ const missing = targetTracks.filter(track => !trackBy(next, track).clips.some(clip => clip.start === from && clip.frames === length));
+ if (!missing.length) continue;
+ const occupied = targetTracks.some(track => trackBy(next, track).clips.some(clip => clip.start === from && clip.frames === length));
+ const lengths = occupied ? [length] : rangeParts(record, {start: from, frames: length,
+ parts: from === start && length === frames ? parts : undefined,
+ maxSeconds: from === start ? firstMaximum : maxFollowSeconds, maxFollowSeconds});
+ // Keep exact sub-second boundaries beside existing material.
+ lengths[lengths.length - 1] += length - lengths.reduce((sum, count) => sum + count, 0);
+ check(lengths.every(count => count > 0), 'range');
+ let position = from;
+ for (const count of lengths) {
+ check(count <= from + length - position, 'range');
+ const added = missing.map(track => newClip(next, trackBy(next, track), {start: position, frames: count, text, part}));
+ for (const clip of added) written(clip, text, by);
+ if (target === 'both') {
+ const video = added.find(clip => trackOf(next, clip.id).id === 'v1') ?? trackBy(next, 'v1').clips.find(clip => clip.start === position && clip.frames === count);
+ const audio = added.find(clip => trackOf(next, clip.id).id === 'a1') ?? trackBy(next, 'a1').clips.find(clip => clip.start === position && clip.frames === count);
+ check(video && audio && (!video.link || video.link === audio.id) && (!audio.link || audio.link === video.id), 'range');
+ // A missing counterpart uses the same old source slice. Its
+ // absent media stream remains silent/black, and both in-points
+ // stay identical while the old content is still playable.
+ if (added.length === 1) {
+ const placeholder = added[0], mate = placeholder === video ? audio : video;
+ placeholder.source = mate.source; placeholder.in = mate.in; placeholder.length = mate.length;
+ placeholder.extend = mate.extend; placeholder.versions = structuredClone(mate.versions);
+ if (mate.splice) placeholder.splice = {...mate.splice};
+ }
+ video.link = audio.id; audio.link = video.id;
+ }
+ position += count;
+ }
+ }
+ if (originals) {
+ const clips = next.tracks.slice(0, 2).map(t => ({...t, clips: t.clips.filter(c => c.part === part)}));
+ next.replacements = [...(next.replacements || []), {part, originals: structuredClone(originals), clips: structuredClone(clips), rolledBack: false}];
+ }
+ return finish(next);
+}
+export function extendClip(record, id, frames, {maxSeconds = RULES.maxSeconds, maxFollowSeconds = maxSeconds} = {}) {
+ check(whole(frames, 1), 'range'); const selected = pair(record, id); check(selected.length, 'missing'); busy(selected);
+ const clip = selected[0]; check(clip.extend && clip.source && trackOf(record, clip.id).id === 'v1', 'unsupported');
+ // frames is total growth beyond the current visible edge. Restore retained
+ // media immediately, then plan only the part beyond the actual source end.
+ const spare = Math.min(...selected.map(member => member.length - member.in - member.frames));
+ const reveal = Math.min(spare, frames);
+ if (frames <= spare) return trim(record, id, 'end', end(clip) + reveal);
+ const count = Math.max(RULES.minSeconds, Math.round((frames - spare) / FPS)) * FPS;
+ // One shift measured from the original visible edge, including restored media.
+ const room = copy(record); makeRightEdgeRoom(room, id, reveal + count, {generating: true});
+ const restored = trim(finish(room), id, 'end', end(clip) + reveal);
+ const start = end(find(restored, clip.id));
+ // A continuation adds a new pair; crossing sound on either lane is not a
+ // replacement. Plan in an empty record, then put the sound in the free lane.
+ const next = copy(restored), sound = sourceAudioTrack(next, start, count);
+ const parts = rangeParts(restored, {start, frames: count, maxSeconds, maxFollowSeconds});
+ const planned = planRange({...emptyProject(restored), serial: next.serial},
+ {start, frames: count, parts, target: 'both', text: clip.text, maxSeconds: maxFollowSeconds, maxFollowSeconds});
+ trackBy(next, 'v1').clips.push(...planned.tracks[0].clips);
+ sound.clips.push(...planned.tracks[1].clips);
+ next.serial = planned.serial;
+ return finish(next);
+}
+function generationClips(record, ids) {
+ check(Array.isArray(ids) && ids.length > 0 && new Set(ids).size === ids.length, 'range');
+ const selected = linkedIds(record, ids);
+ check(ids.every(id => find(record, id)), 'missing');
+ const clips = trackBy(record, 'v1').clips.filter(clip => selected.has(clip.id));
+ check(clips.length > 0 && [...selected].every(id => clips.some(clip => clip.id === id || clip.link === id)), 'unsupported');
+ check(clips.every(clip => clip.pending !== null), 'range');
+ check(clips.every((clip, i) => i === 0 || end(clips[i - 1]) === clip.start), 'range');
+ return clips;
+}
+const netFrames = (frames, continues) => continues ? Math.max(34, Math.ceil(frames / RULES.step) * RULES.step)
+ : Math.max(39, RULES.first + Math.ceil((frames - RULES.first) / RULES.step) * RULES.step);
+function generationPlan(record, clips) {
+ const first = clips[0], before = trackBy(record, 'v1').clips.find(clip => end(clip) === first.start && clip.source && clip.extend && clip.in + clip.frames === clip.length);
+ const replacing = clips.some(clip => clip.source);
+ // Revealing a predecessor's hidden tail reduces the new visible range.
+ const credit = clips.every(clip => clip.target_frames !== undefined && !clip.source)
+ ? clips.reduce((sum, clip) => sum + clip.target_frames - clip.frames, 0) : 0;
+ let ideal = 0, real = credit;
+ return clips.map((clip, index) => {
+ const target_frames = clip.target_frames ?? clip.frames; ideal += target_frames;
+ // Existing playback bounds and fill's visible length are invariant.
+ // A replacement may therefore need one more grid step than a draft.
+ const continues = index > 0 || !!before;
+ const net_frames = netFrames(Math.max(ideal - real, replacing ? clip.frames : 0), continues); real += net_frames;
+ const frames = replacing ? clip.frames : index === clips.length - 1 ? ideal - (real - net_frames) : net_frames;
+ check(frames >= 1, 'range');
+ return {clip, before: index ? clips[index - 1] : before ?? null, target_frames, net_frames,
+ request_frames: net_frames + (continues ? RULES.overlap : 0), frames};
+ });
+}
+export function prepare(record, ids) {
+ const clips = generationClips(record, ids); busy(clips);
+ const next = copy(record);
+ const replacing = clips.some(clip => clip.source);
+ if (!replacing && clips.every(clip => clip.target_frames === undefined)) {
+ const before = trackBy(next, 'v1').clips.find(clip => end(clip) === clips[0].start && clip.source && clip.extend);
+ if (before) {
+ const members = pair(next, before.id);
+ const spare = Math.min(...members.map(clip => clip.length - clip.in - clip.frames));
+ const first = find(next, clips[0].id);
+ // Leave at least one visible frame in every planned segment.
+ const credit = spare < first.frames ? spare : 0;
+ if (credit) {
+ busy(members);
+ for (const clip of members) clip.frames += credit;
+ for (const old of clips) for (const clip of pair(next, old.id)) clip.target_frames = old.frames;
+ for (const clip of pair(next, first.id)) { clip.start += credit; clip.frames -= credit; clip.length = clip.frames; }
+ }
+ }
+ }
+ const selected = generationClips(finish(next), ids), plan = generationPlan(next, selected);
+ let position = selected[0].start;
+ for (const row of plan) {
+ const members = pair(next, row.clip.id);
+ // While replacing existing media, retain its visible bounds until fill.
+ for (const clip of members) {
+ clip.target_frames = row.target_frames;
+ if (!replacing) { clip.start = position; clip.frames = row.frames; clip.length = row.frames; }
+ }
+ position += row.frames;
+ }
+ return finish(next);
+}
+export function generationRequest(record, ids, {text, paths = {}} = {}) {
+ check(object(paths), 'source');
+ if (text !== undefined) check(validText(text), 'text');
+ const clips = generationClips(record, ids), rows = generationPlan(record, clips), plan = {}, blocks = [];
+ for (const row of rows) {
+ let after = null;
+ if (row.before) {
+ if (clips.some(clip => clip.id === row.before.id)) after = row.before.id;
+ else { const path = paths[key(row.before.source)]; check(typeof path === 'string' && path.length > 0, 'source', 'missing source path'); after = {work: sourceData({kind: 'generated', id: path}).id}; }
+ }
+ blocks.push({id: row.clip.id, part: row.clip.part ?? row.clip.id, after, before: null, text: text ?? row.clip.text, frames: row.request_frames});
+ plan[row.clip.id] = {target_frames: row.target_frames, net_frames: row.net_frames, request_frames: row.request_frames, audio: row.clip.link};
+ }
+ return frozen({blocks, plan});
+}
+function update(record, ids, change) {
+ const next = copy(record), selected = linkedIds(next, ids);
+ for (const clip of all(next)) if (selected.has(clip.id)) change(clip);
+ return finish(next);
+}
+export function startAttempt(record, ids, text, {by = 'user'} = {}) {
+ check(validText(text) && TEXT_BY.includes(by), 'text');
+ const next = copy(record), part = freshId(next), selected = linkedIds(next, ids);
+ busy(all(next).filter(clip => selected.has(clip.id)));
+ for (const clip of all(next)) if (selected.has(clip.id)) { written(clip, text, by); clip.part = part; clip.pending = 'draft'; clip.reason = clip.job = null; }
+ return finish(next);
+}
+export function assignJob(record, ids, job, {prepared = record} = {}) {
+ check(typeof job === 'string' && /^[A-Za-z0-9_-]{1,128}$/.test(job), 'job');
+ return update(record, ids, clip => {
+ const expected = find(prepared, clip.id);
+ if (clip.pending === 'draft' && clip.job === null && clip.target_frames !== undefined
+ && expected && expected.part === clip.part && expected.target_frames === clip.target_frames) {
+ clip.job = job; clip.pending = 'queued'; clip.reason = null;
+ }
+ });
+}
+export function fill(record, id, {source, frames, width, height, skip_frames = 0, skip_audio_samples = 0, job = null}) {
+ if (!attemptClip(record, id) || attemptClip(record, id).job !== job) return parse(record);
+ const wasRolledBack = record.replacements?.find(tx => tx.rolledBack && tx.clips.some(t => t.clips.some(c => c.id === id)));
+ const active = activate(record, id);
+ source = sourceData(source); check(whole(frames, 1) && whole(skip_frames) && whole(skip_audio_samples, 0, Number.MAX_SAFE_INTEGER), 'range');
+ check(pair(active, id).every(clip => clip.job === job), 'job');
+ check(pair(active, id).every(clip => skip_frames + clip.frames <= frames), 'range');
+ const sized = copy(active);
+ if (pair(active, id).some(clip => trackBy(active, 'v1').clips.includes(clip))) followFirstSize(sized, width, height);
+ const next = update(sized, [id], clip => {
+ const take = numberTakes(clip) + 1;
+ remember(clip, source); clip.source = source; clip.in = skip_frames; clip.length = frames; clip.take = take;
+ if (clip.text) clip.made_text = clip.text; else delete clip.made_text;
+ clip.pending = clip.reason = clip.job = null; clip.extend = source.kind !== 'import';
+ delete clip.splice;
+ if (skip_frames || skip_audio_samples) clip.splice = {frames: skip_frames, audio_samples: skip_audio_samples};
+ clearPlan(clip);
+ });
+ const transaction = next.replacements?.find(tx => tx.clips.some(t => t.clips.some(c => c.id === id)));
+ if (!transaction) return next;
+ const visible = wasRolledBack ? find(record, wasRolledBack.originals[0].clips[0].id)
+ : transaction.clips.flatMap(t => t.clips).find(c => c.pending);
+ // Publish all replacement blocks together. Until then playback/export keep
+ // the original media, even after an earlier block has finished.
+ return rollback(next, id, visible.pending, visible.reason);
+}
+export function fail(record, id, reason, job = null) {
+ check(typeof reason === 'string' && /^[a-z_]{1,80}$/.test(reason), 'reason');
+ if (!attemptClip(record, id)?.pending || attemptClip(record, id).job !== job) return parse(record);
+ const next = update(activate(record, id), [id], clip => { if (clip.pending !== null && clip.job === job) { clip.pending = 'failed'; clip.reason = reason; } });
+ return rollback(next, id, 'failed', reason);
+}
+export function settle(record, ids, pending = 'stopped') {
+ check(['draft', 'queued', 'running', 'failed', 'stopped'].includes(pending), 'pending');
+ let active = record, selected = [...ids];
+ for (const tx of record.replacements || []) if (tx.rolledBack && tx.originals.some(t => t.clips.some(c => ids.includes(c.id))) && ['queued', 'draft'].includes(pending)) selected.push(...tx.clips.flatMap(t => t.clips.filter(c => c.pending).map(c => c.id)));
+ for (const id of selected) active = activate(active, id);
+ let next = update(active, [...new Set(selected)], clip => { if (clip.pending !== null) { clip.pending = pending; clip.reason = null; if (pending === 'draft') clip.job = null; } });
+ if (['stopped', 'failed', 'draft', 'queued', 'running'].includes(pending)) for (const id of selected) next = rollback(next, id, pending);
+ return next;
+}
+export function dropPlanned(record, ids) {
+ const selected = linkedIds(record, ids), next = copy(record);
+ busy(all(record).filter(clip => selected.has(clip.id) && !clip.source));
+ for (const track of next.tracks) track.clips = track.clips.filter(clip => !selected.has(clip.id) || clip.source || (clip.link && find(record, clip.link).source));
+ return finish(next);
+}
+export function restoreVersion(record, id, index, {by = 'user'} = {}) {
+ check(whole(index, 0, 49) && TEXT_BY.includes(by), 'range'); const clips = pair(record, id); check(clips.length, 'missing'); busy(clips);
+ const next = copy(record);
+ detachAttempt(next, clips.map(c => c.id));
+ for (const old of clips) {
+ const clip = find(next, old.id); numberTakes(clip);
+ const version = clip.versions[index]; check(version && version.in + clip.frames <= version.length, 'range');
+ remember(clip, version); clip.source = {kind: version.kind, id: version.id}; clip.in = version.in; clip.length = version.length;
+ delete clip.take; delete clip.made_text; madeFields(version, clip); touchedBy(clip, by);
+ // Placement belongs to this timeline part, including when its media changes.
+ clip.pending = clip.reason = clip.job = null; clip.extend = version.kind !== 'import'; clearPlan(clip);
+ delete clip.splice; if (version.splice) clip.splice = version.splice;
+ }
+ return finish(next);
+}
diff --git a/web/editor_notes.css b/web/editor_notes.css
new file mode 100644
index 0000000..e61a006
--- /dev/null
+++ b/web/editor_notes.css
@@ -0,0 +1,24 @@
+/* Block descriptions (Iris 10-11): the Picture page's 说明 / 重新生成 / 版本 rows and the strip on timeline blocks. */
+.fv-ed-notes{display:flex;flex-direction:column;gap:6px;margin-bottom:12px;min-width:0}
+.fv-ed-notes-head{display:flex;align-items:center;justify-content:space-between;gap:8px;min-width:0}
+.fv-editor .fv-ed-notes-again{display:inline-flex;align-items:center;gap:4px;height:26px;padding:0 8px;font-size:12px}
+.fv-ed-notes-again .fv-ed-glyph{width:12px;height:12px}
+.fv-editor .fv-ed-notes-again:disabled{opacity:.4}
+.fv-editor .fv-ed-notes-text{display:block;height:auto;box-sizing:border-box;width:100%;min-height:34px;max-height:94px;padding:6px 10px;resize:none;overflow-y:auto;font:13px/20px var(--fv-font);color:var(--fv-ink);background:var(--fv-bg);border:1px solid var(--fv-border);border-radius:8px}
+.fv-editor .fv-ed-notes-text:focus-visible{outline:1px solid var(--fv-accent);outline-offset:-1px;border-color:var(--fv-accent)}
+.fv-editor .fv-ed-notes-text:disabled{opacity:.4}
+.fv-ed-notes-versions{display:flex;flex-direction:column;gap:6px;margin-top:6px}
+.fv-editor .fv-ed-notes-picker button{height:30px}
+.fv-editor .fv-ed-notes-picker button:disabled{opacity:.4}
+/* Timeline: the strip sits under the pictures, one shade darker than the track. */
+.fv-ed-clip[data-noted=true] .fv-ed-clip-media{bottom:22px}
+.fv-ed-note{position:absolute;left:0;right:0;bottom:0;z-index:1;height:22px;padding:0 8px;overflow:hidden;background:var(--fv-bg);color:var(--fv-ink);font:12px/22px var(--fv-font);text-align:left;text-overflow:ellipsis;white-space:nowrap}
+/* Block numbers take the top-left corner, so planned lengths move right beside them. */
+.fv-ed-track-view:has(.fv-ed-track-row[data-noted=true]) .fv-ed-planned-label{left:24px}
+.fv-ed-block-number{position:absolute;left:6px;top:4px;z-index:2;color:#fff;font:700 11px/1 var(--fv-font);text-shadow:0 1px 2px rgba(0,0,0,.85);pointer-events:none}
+.fv-ed-user-mark{position:absolute;right:4px;top:4px;z-index:2;display:grid;place-items:center;width:16px;height:16px;border-radius:4px;background:rgba(0,0,0,.55);color:#fff;pointer-events:none}
+.fv-ed-user-mark .fv-ed-glyph{width:11px;height:11px}
+.fv-ed-clip:has(.fv-ed-picture-badge:not([hidden])) .fv-ed-user-mark{right:auto;left:22px}
+.fv-ed-note-tip{position:absolute;z-index:10;max-width:360px;padding:6px 8px;background:var(--fv-card);color:var(--fv-ink);border:1px solid var(--fv-border);border-radius:6px;font-size:12px;line-height:1.5;white-space:pre-wrap;overflow-wrap:anywhere;pointer-events:none;box-shadow:0 4px 12px rgba(0,0,0,.35)}
+.fv-editor .fv-ed-note-input{position:absolute;top:64px;z-index:5;box-sizing:border-box;height:22px;min-height:0;margin:0;padding:0 8px;font:12px/20px var(--fv-font);color:var(--fv-ink);background:var(--fv-bg);border:1px solid var(--fv-accent);border-radius:0 0 8px 8px;outline:none;box-shadow:none}
+.fv-editor .fv-ed-note-input:focus,.fv-editor .fv-ed-note-input:focus-visible{outline:none;border-color:var(--fv-accent)}
diff --git a/web/editor_notes.js b/web/editor_notes.js
new file mode 100644
index 0000000..6d1e6b4
--- /dev/null
+++ b/web/editor_notes.js
@@ -0,0 +1,165 @@
+import * as model from './editor_model.js';
+import {button, segmented} from './editor_adjust.js';
+import {isText} from './editor_text_model.js';
+// A block's description (Iris 10-11): what the block shows and what 重新生成 uses.
+// The timeline shows its first line under the pictures; the Picture page edits it.
+const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; };
+function glyph(d) {
+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
+ svg.setAttribute('viewBox', '0 0 16 16'); svg.setAttribute('aria-hidden', 'true'); svg.classList.add('fv-ed-glyph');
+ const path = document.createElementNS(svg.namespaceURI, 'path'); path.setAttribute('d', d); svg.append(path); return svg;
+}
+const AGAIN = 'M13.5 2.5v3.5H10M13.2 6A5.5 5.5 0 1 0 13.5 9.5', PENCIL = 'M10.5 2.5l3 3-8 8h-3v-3z';
+const generating = clip => ['queued', 'running'].includes(clip?.pending);
+const firstLine = text => (text || '').trim().split('\n')[0];
+// Only the picture track grows a description strip, and only once one block has a description.
+export const describedTrack = track => track.kind === 'video' && track.clips.some(clip => !isText(clip) && clip.text?.trim());
+const agentWrote = record => record.tracks.some(track => track.clips.some(clip => clip.text_by === 'agent'));
+// Status words appear only in the hover tip and the panels (Iris 10-11).
+export function blockStatus(clip, t, fraction = 0) {
+ if (clip.pending === 'running') return t(`Generating ${Math.round(fraction * 100)}%`, `生成中 ${Math.round(fraction * 100)}%`);
+ if (clip.pending === 'stopped') return t('Stopped', '已停止');
+ if (clip.pending === 'failed') return t('Unfinished', '未完成');
+ if (clip.pending) return t('Not generated', '未生成');
+ const current = model.takes(clip).find(take => take.index === -1);
+ return model.takes(clip).length > 1 ? t(`Version ${current.number}`, `第 ${current.number} 版`) : '';
+}
+let serial = 0;
+export function createBlockNotes({state, t, actions}) {
+ const element = el('div', 'fv-ed-notes'), head = el('div', 'fv-ed-notes-head');
+ const label = el('label', 'fv-ed-adjust-label', t('Description', '说明'));
+ const again = button(t('Regenerate', '重新生成'), {onClick: () => regenerate()}); again.classList.add('fv-ed-notes-again'); again.prepend(glyph(AGAIN));
+ const box = el('textarea', 'fv-ed-notes-text'); box.id = `fv-ed-notes-${++serial}`; box.rows = 1; label.htmlFor = box.id;
+ const versions = el('div', 'fv-ed-notes-versions'), versionsLabel = el('span', 'fv-ed-adjust-label', t('Version', '版本'));
+ head.append(label, again); element.append(head, box, versions);
+ let block = null, editing = null, picker = null, pickerKey = null, context = null;
+ const grow = () => { box.style.height = 'auto'; if (box.scrollHeight) box.style.height = `${box.scrollHeight + 2}px`; };
+ function selectedBlock() {
+ const ids = state.selection?.kind === 'clip' ? state.selection.ids : [];
+ const first = ids.length ? model.find(state.record, ids[0]) : null;
+ if (!first || isText(first)) return null;
+ const pair = model.pair(state.record, first.id);
+ if (!ids.every(id => pair.some(clip => clip.id === id))) return null;
+ return state.record.tracks[0].clips.find(clip => pair.some(item => item.id === clip.id)) || pair[0];
+ }
+ function save(id, text) {
+ const clip = model.find(state.record, id); text = text.trim();
+ if (!clip || text === clip.text) return;
+ try { state.apply(t('Edit description', '修改说明'), record => model.describe(record, [id], text)); } catch (value) { actions.editError?.(value); }
+ }
+ function commit() { const id = editing; editing = null; if (id) save(id, box.value); }
+ box.oninput = () => { editing ||= block?.id || null; grow(); };
+ box.onblur = commit;
+ box.onkeydown = event => {
+ if (event.isComposing || event.keyCode === 229) return;
+ if (event.key === 'Enter' && (event.ctrlKey || event.metaKey)) { event.preventDefault(); commit(); update(); }
+ else if (event.key === 'Escape' && editing) { event.preventDefault(); event.stopPropagation(); editing = null; update(); }
+ };
+ async function regenerate() {
+ commit(); const clip = block && model.find(state.record, block.id);
+ if (!clip?.text.trim()) return;
+ try { await actions.generate({text: clip.text, label: t('Regenerate', '重新生成')}); } catch (value) { actions.editError?.(value); }
+ }
+ function choose(index) {
+ const id = block?.id; if (!id) return;
+ try { state.apply(t('Switch version', '换版本'), record => model.restoreVersion(record, id, index)); } catch (value) { actions.editError?.(value); }
+ }
+ function paintVersions(off) {
+ const list = block?.source ? model.takes(block) : [];
+ versions.hidden = list.length <= 1;
+ const key = list.map(take => `${take.index}:${take.number}`).join();
+ if (key !== pickerKey) {
+ picker?.dispose(); pickerKey = key;
+ picker = segmented(list.map(take => ({value: take.index, label: String(take.number)})), {value: -1, onChange: choose});
+ picker.classList.add('fv-ed-notes-picker');
+ versions.replaceChildren(versionsLabel, picker);
+ }
+ [...picker.children].forEach((control, index) => {
+ control.setAttribute('aria-label', t(`Version ${list[index].number}`, `第 ${list[index].number} 版`));
+ control.disabled = off || !list[index].usable;
+ });
+ picker.value = -1;
+ }
+ function update(ctx = context) {
+ context = ctx;
+ const next = selectedBlock();
+ if (editing && next?.id !== editing) commit();
+ block = next;
+ const off = !block || !!ctx?.busy || generating(block);
+ box.disabled = off;
+ if (document.activeElement !== box || editing !== block?.id) { box.value = block?.text || ''; grow(); }
+ again.disabled = off || !block.text.trim() || !actions.canGenerate?.(block.text);
+ // Blue once the description no longer matches the one the version in use was made from.
+ again.classList.toggle('fv-primary', !again.disabled && model.describedSince(block));
+ paintVersions(off);
+ }
+ // Timeline blocks: description strip, block number, and the pencil on the user's own blocks.
+ const items = new Map();
+ let tip = null, tipTimer = 0, inline = null;
+ const hideTip = () => { clearTimeout(tipTimer); if (tip) tip.hidden = true; };
+ function showTip(item) {
+ const view = item.element.closest('.fv-ed-track-view'), clip = item.clip; if (!view || !item.element.isConnected) return;
+ const fraction = Number(item.element.style.getPropertyValue('--fv-ed-progress')) || 0;
+ const text = [clip.text.trim(), blockStatus(clip, t, fraction)].filter(Boolean).join(' · ');
+ if (!text) return;
+ if (!tip) { tip = el('div', 'fv-ed-note-tip'); tip.setAttribute('role', 'tooltip'); }
+ if (tip.parentElement !== view) view.append(tip);
+ tip.textContent = text; tip.hidden = false;
+ const bounds = view.getBoundingClientRect(), strip = item.note.getBoundingClientRect();
+ tip.style.left = `${Math.max(8, Math.min(strip.left - bounds.left, bounds.width - tip.offsetWidth - 8))}px`;
+ tip.style.top = `${Math.max(4, strip.top - bounds.top - tip.offsetHeight - 6)}px`;
+ }
+ function decorate(item, {noted, index, record}) {
+ if (!item.note) {
+ item.note = el('span', 'fv-ed-note'); item.number = el('span', 'fv-ed-block-number'); item.mark = el('span', 'fv-ed-user-mark');
+ item.mark.append(glyph(PENCIL)); item.element.append(item.note, item.number, item.mark);
+ item.note.addEventListener('pointerenter', () => { hideTip(); tipTimer = setTimeout(() => showTip(item), 500); });
+ item.note.addEventListener('pointerleave', hideTip);
+ }
+ items.set(item.clip.id, item);
+ item.element.dataset.noted = String(noted);
+ item.note.hidden = item.number.hidden = !noted;
+ item.note.textContent = firstLine(item.clip.text); item.number.textContent = String(index + 1);
+ // The pencil marks blocks an agent leaves alone; a project nobody else wrote in has none.
+ item.mark.hidden = !agentWrote(record) || !!item.clip.text_by;
+ }
+ function stripAt(event) {
+ for (const item of items.values()) {
+ if (!item.element.isConnected || item.note.hidden) continue;
+ const r = item.note.getBoundingClientRect();
+ if (event.clientX >= r.left && event.clientX <= r.right && event.clientY >= r.top && event.clientY <= r.bottom) return item;
+ }
+ return null;
+ }
+ function closeInline() { inline?.remove(); inline = null; }
+ // Pressing a block captures the pointer on the timeline, so double-clicks arrive there.
+ function editInPlace(event) {
+ const item = stripAt(event); if (!item) return false;
+ const clip = model.find(state.record, item.clip.id);
+ if (!clip || model.pair(state.record, clip.id).some(generating)) return false;
+ event.preventDefault(); hideTip(); closeInline();
+ if (clip.text.trim().includes('\n')) { box.focus(); return true; }
+ const input = inline = el('input', 'fv-ed-note-input'); input.value = clip.text; input.setAttribute('aria-label', t('Description', '说明'));
+ input.style.left = item.element.style.left; input.style.width = item.element.style.width;
+ let done = false;
+ const finish = keep => { if (done) return; done = true; const text = input.value; closeInline(); if (keep) save(clip.id, text); };
+ input.onkeydown = key => {
+ if (key.isComposing || key.keyCode === 229) return;
+ if (key.key === 'Enter') { key.preventDefault(); finish(true); }
+ else if (key.key === 'Escape') { key.preventDefault(); key.stopPropagation(); finish(false); }
+ };
+ input.onblur = () => finish(true);
+ item.element.parentNode.append(input); input.focus(); input.select();
+ return true;
+ }
+ function attach(view) {
+ const dblclick = event => editInPlace(event);
+ view.addEventListener('dblclick', dblclick); view.addEventListener('pointerdown', hideTip, true);
+ return () => { view.removeEventListener('dblclick', dblclick); view.removeEventListener('pointerdown', hideTip, true); };
+ }
+ function dispose() {
+ hideTip(); tip?.remove(); closeInline(); picker?.dispose(); again.dispose();
+ box.oninput = box.onblur = box.onkeydown = null; items.clear(); element.remove();
+ }
+ return {element, update, decorate, attach, dispose};
+}
diff --git a/web/editor_picture_fields.js b/web/editor_picture_fields.js
new file mode 100644
index 0000000..a8c7a9c
--- /dev/null
+++ b/web/editor_picture_fields.js
@@ -0,0 +1,40 @@
+// Sparse wire fields; normalization matches editor_geometry/editor_picture._fields.
+export const PICTURE_DEFAULTS = Object.freeze({fit: 'cover', crop_left: 0, crop_top: 0, crop_right: 0, crop_bottom: 0,
+ flip_h: false, flip_v: false, rotate: 0, scale: 1, offset_x: 0, offset_y: 0});
+export function pictureFields(value = {}) {
+ value = value && typeof value === 'object' ? value : {};
+ const result = {fit: value.fit === 'contain' ? 'contain' : 'cover'};
+ for (const [key, fallback] of Object.entries(PICTURE_DEFAULTS)) {
+ if (key === 'fit') continue;
+ const v = value[key], [low, high] = key.startsWith('crop_') ? [0, .9] : key === 'scale' ? [.1, 10] : key === 'rotate' ? [-180, 180] : [-2, 2];
+ result[key] = typeof fallback === 'boolean' ? v === true : typeof v !== 'number' || Number.isNaN(v) ? fallback : Math.min(high, Math.max(low, v));
+ }
+ for (const [a, b] of [['crop_left', 'crop_right'], ['crop_top', 'crop_bottom']]) {
+ const sum = result[a] + result[b];
+ if (sum > .9) { result[a] = result[a] * .9 / sum; result[b] = result[b] * .9 / sum; }
+ }
+ return Object.fromEntries(Object.entries(result).filter(([k, v]) => v !== PICTURE_DEFAULTS[k]));
+}
+export function replacePicture(target, fields) {
+ for (const key of Object.keys(PICTURE_DEFAULTS)) delete target[key];
+ Object.assign(target, pictureFields(fields));
+ return target;
+}
+
+// The existing immutable model supplies its validation and transaction finish.
+export function pictureEditor({copy, trackBy, check, pictureFit, finish}) {
+ const end = clip => clip.start + clip.frames;
+ return function (record, id, fields) {
+ check(fields !== null && typeof fields === 'object' && !Array.isArray(fields), 'invalid');
+ const next = copy(record), clip = trackBy(next, 'v1').clips.find(c => c.id === id);
+ check(clip && clip.source, 'missing');
+ if (fields.fit !== undefined) pictureFit(fields.fit);
+ replacePicture(clip, {...clip, ...fields});
+ for (const tx of next.replacements || []) if (tx.rolledBack) {
+ const old = tx.originals[0].clips.find(c => c.id === id);
+ if (old) { replacePicture(old, clip); for (const c of tx.clips[0].clips)
+ if (c.start >= old.start && end(c) <= end(old)) replacePicture(c, clip); }
+ }
+ return finish(next);
+ };
+}
diff --git a/web/editor_picture_session.js b/web/editor_picture_session.js
new file mode 100644
index 0000000..80cb13c
--- /dev/null
+++ b/web/editor_picture_session.js
@@ -0,0 +1,67 @@
+// One ephemeral transaction shared by controls and preview; never saved in records.
+import {find, setPicture} from './editor_model.js';
+import {PICTURE_DEFAULTS, pictureFields} from './editor_picture_fields.js';
+const sessions = new WeakMap();
+export function pictureSession(state, t) {
+ if (sessions.has(state)) return sessions.get(state);
+ let draft = null, panelOpen = false; const listeners = new Set();
+ const emit = () => { for (const listener of listeners) listener(); };
+ const cancel = () => { if (draft) { draft = null; emit(); } };
+ const session = {
+ get draft() { return draft; },
+ get panelOpen() { return panelOpen; },
+ setPanelOpen(value) {
+ if (panelOpen === value) return;
+ panelOpen = value;
+ if (!value) cancel();
+ emit();
+ },
+ selected() {
+ const ids = state.selection?.kind === 'clip' ? state.selection.ids : [];
+ return state.record.tracks[0].clips.find(c => c.source && ids.includes(c.id)
+ && ids.every(id => id === c.id || id === c.link)) || null;
+ },
+ output(clip) { return !!clip && (panelOpen && session.selected()?.id === clip.id || draft?.id === clip.id); },
+ previewRow(row, position) {
+ const clip = panelOpen ? session.selected() : draft && find(state.record, draft.id);
+ return clip ? {clip, frame: clip.in + Math.max(0, Math.min(clip.frames - 1, position - clip.start))} : row;
+ },
+ editReason(clip) {
+ if (!clip?.source) return t('This part has no video', '这一段没有画面');
+ const ids = [clip.id, clip.link].filter(Boolean);
+ const tracks = state.record.tracks.filter(track => track.clips.some(c => ids.includes(c.id)));
+ if (tracks.some(track => track.clips.some(c => ids.includes(c.id) && ['queued', 'running'].includes(c.pending)))
+ || state.record.replacements?.some(tx => tx.originals.some(track => track.clips.some(c => ids.includes(c.id)))
+ && tx.clips.some(track => track.clips.some(c => ['queued', 'running'].includes(c.pending)))))
+ return t('Cancel generation before changing this part.', '先取消生成,再改这一段。');
+ return tracks.some(track => track.locked) ? t('Unlock the track before changing this part.', '先解锁轨道,再改这一段。') : '';
+ },
+ canEdit(clip) { return !session.editReason(clip); },
+ clip(clip) { return draft && draft.id === clip?.id ? {...clip, ...PICTURE_DEFAULTS, ...draft.fields} : clip; },
+ begin(id, mode = 'adjust') {
+ if (draft?.id === id && draft.mode === mode) return;
+ cancel(); const clip = find(state.record, id);
+ if (session.canEdit(clip)) { draft = {id, mode, original: pictureFields(clip), fields: pictureFields(clip), baseline: JSON.stringify(clip), size: [state.record.width, state.record.height].join(',')}; emit(); }
+ },
+ preview(fields) { if (draft) { draft.fields = pictureFields({...PICTURE_DEFAULTS, ...draft.fields, ...fields}); emit(); } },
+ commit() {
+ if (!draft) return;
+ const {id, fields} = draft; draft = null;
+ if (session.canEdit(find(state.record, id))) state.apply(t('Video', '画面'), r => setPicture(r, id, {...PICTURE_DEFAULTS, ...fields})); emit();
+ },
+ cancel,
+ change(id, fields) { cancel(); if (!session.canEdit(find(state.record, id))) return; state.apply(t('Video', '画面'), r => setPicture(r, id, fields)); },
+ keyboard(event) {
+ const input = event.target?.closest?.('.fv-ed-adjust-picture') && event.target?.tagName === 'INPUT';
+ if ((event.isComposing || event.keyCode === 229) && (draft || input)) { event.stopPropagation(); return true; }
+ if (event.key === 'Escape' && input && event.target.type !== 'range' && !draft) { event.target.onkeydown?.(event); return true; }
+ if (!draft || !['Escape', 'Enter'].includes(event.key)) return false;
+ if (event.key === 'Enter' && draft.mode !== 'crop') return false;
+ event.preventDefault(); event.stopPropagation(); event.key === 'Escape' ? cancel() : session.commit(); return true;
+ },
+ subscribe(listener) { listeners.add(listener); return () => listeners.delete(listener); },
+ dispose() { cancel(); unsubscribe(); listeners.clear(); sessions.delete(state); },
+ };
+ const unsubscribe = state.subscribe(event => { if ((event.type === 'selection' || (event.type === 'playhead' && draft?.mode !== 'slider')) || (event.type === 'record' && draft && (!session.canEdit(find(state.record, draft.id)) || draft.baseline !== JSON.stringify(find(state.record, draft.id)) || draft.size !== [state.record.width, state.record.height].join(',')))) cancel(); });
+ sessions.set(state, session); return session;
+}
diff --git a/web/editor_player.js b/web/editor_player.js
new file mode 100644
index 0000000..e21cbb8
--- /dev/null
+++ b/web/editor_player.js
@@ -0,0 +1,183 @@
+import {isText} from './editor_text_model.js';
+import * as model from './editor_model.js';
+import {pictureSession} from './editor_picture_session.js';
+import {createPreviewPicture} from './editor_preview_picture.js';
+import {sourceKey, mediaURL} from './editor_store.js';
+import {clipPictureSize, createPictureGuide} from './editor_frame.js';
+const el = (tag, cls) => { const e = document.createElement(tag); if (cls) e.className = cls; return e; };
+export function audioSeconds(clip, sourceFrame) {
+ // The chain receipt counts samples at 32 kHz, even if the media is 48 kHz.
+ return clip.splice ? clip.splice.audio_samples / 32000 + (sourceFrame - clip.splice.frames) / 24 : sourceFrame / 24;
+}
+export const transportTime = frames => {
+ const seconds = Math.floor(Math.max(0, frames) / 24);
+ return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`;
+};
+export function createEditorPlayer(host, transport, {state, sources, api, t, preservePreview = () => false}) {
+ const frame = el('div', 'fv-ed-picture'); frame.setAttribute('aria-label', t('Video preview', '视频预览'));
+ const empty = el('div', 'fv-ed-empty-preview'), pictureIcon = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
+ pictureIcon.setAttribute('viewBox', '0 0 24 24'); pictureIcon.setAttribute('aria-hidden', 'true');
+ const picturePath = document.createElementNS(pictureIcon.namespaceURI, 'path');
+ picturePath.setAttribute('d', 'M3 4h18v16H3zM3 16l5-6 5 6 3-4 5 6M15 8h.01'); pictureIcon.append(picturePath);
+ empty.append(pictureIcon); frame.append(empty);
+ const closePreview = el('button', 'fv-ed-preview-close'); closePreview.type = 'button'; closePreview.hidden = true;
+ closePreview.setAttribute('aria-label', t('Close preview', '关闭预览'));
+ const closeIcon = document.createElementNS(pictureIcon.namespaceURI, 'svg'), closePath = document.createElementNS(pictureIcon.namespaceURI, 'path');
+ closeIcon.setAttribute('viewBox', '0 0 16 16'); closeIcon.setAttribute('aria-hidden', 'true'); closePath.setAttribute('d', 'm4 4 8 8M12 4l-8 8'); closeIcon.append(closePath); closePreview.append(closeIcon); frame.append(closePreview);
+ const videos = [el('video'), el('video')]; videos.forEach(video => { video.playsInline = true; video.preload = 'auto'; video.controls = false; video.setAttribute('aria-hidden', 'true'); frame.append(video); });
+ const audio = [el('audio'), el('audio')]; audio.forEach(value => { value.preload = 'auto'; frame.append(value); });
+ const pictureGuide = createPictureGuide(host, frame, {state, t});
+ const pictureEdit = pictureSession(state, t);
+ const picturePreview = createPreviewPicture(host, frame, {state, t});
+ const playButton = el('button', 'fv-ed-play'); playButton.type = 'button'; playButton.title = t('Space', '空格');
+ const time = el('span', 'fv-ed-time'); time.setAttribute('aria-live', 'off'); transport.append(playButton, time);
+ let active = 0, clipId = null, playing = false, disposed = false, raf = null, clockStart = 0, frameStart = 0, ticking = false, preview = null, previewSize = null, previewProject = null;
+ let audioContext = null, textRenderer = null;
+ const gains = new WeakMap(), volumePreview = new Map();
+ const clipVolume = clip => volumePreview.get(clip?.id) ?? clip?.volume ?? 1;
+ function volume(media, value) {
+ // HTMLMediaElement stops at 1. A GainNode implements the record's 0–2 range.
+ if (value > 1 || gains.has(media)) {
+ try {
+ audioContext ||= new (window.AudioContext || window.webkitAudioContext)();
+ if (!gains.has(media)) { const source = audioContext.createMediaElementSource(media), gain = audioContext.createGain(); source.connect(gain); gain.connect(audioContext.destination); gains.set(media, gain); }
+ media.volume = 1; gains.get(media).gain.value = value; if (playing) audioContext.resume().catch(() => {}); return;
+ } catch { /* Browser without Web Audio: retain sound up to unity. */ }
+ }
+ media.volume = Math.min(1, Math.max(0, value));
+ }
+ function seekMedia(media, url, seconds, running, gain = 1) {
+ const changed = media.dataset.source !== url;
+ if (changed) { media.pause(); media.dataset.source = url; media.src = url; media.load(); }
+ media._editorTime = Math.max(0, seconds); media._editorRunning = running;
+ volume(media, gain);
+ if (media.readyState >= 1 && (changed || !running || Math.abs(media.currentTime - seconds) > .08)) {
+ try { media.currentTime = Math.max(0, seconds); } catch {}
+ }
+ if (running) { if (media.paused) media.play().catch(() => {}); } else media.pause();
+ }
+ function stopMedia(media) { media.pause(); media._editorRunning = false; }
+ for (const media of [...videos, ...audio]) {
+ media.onloadedmetadata = () => { if (disposed) return; try { media.currentTime = media._editorTime || 0; } catch {} if (media._editorRunning) media.play().catch(() => {}); };
+ }
+ function located(record, position) {
+ // The model owns which content covers the frame. Normalize its query rows.
+ const value = model.at(record, position);
+ const rows = Array.isArray(value) ? value : Object.entries(value || {}).map(([track, row]) => ({track, ...row}));
+ const result = new Map();
+ for (const row of rows) {
+ if (!row) continue;
+ const track = row.track?.id || row.track || row.trackId;
+ const clip = row.clip || (row.id ? row : null);
+ if (clip) result.set(track, {clip, frame: row.frame ?? row.sourceFrame ?? clip.in + position - clip.start});
+ }
+ return result;
+ }
+ function render() {
+ if (disposed) return;
+ // The total is what export writes (picture and sound); text past it is not exported.
+ const record = state.record, position = state.playhead, total = model.exportFrames(record);
+ const hasContent = record.tracks.some(track => track.clips.some(clip => clip.source || isText(clip)));
+ empty.hidden = hasContent || preview?.tagName === 'VIDEO'; frame.dataset.empty = String(!empty.hidden);
+ playButton.disabled = !total || !hasContent;
+ time.textContent = `${transportTime(position)} / ${transportTime(total)}`;
+ if (playButton.dataset.playing !== String(playing)) {
+ playButton.dataset.playing = String(playing);
+ const glyph = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); glyph.setAttribute('viewBox', '0 0 16 16'); glyph.setAttribute('aria-hidden', 'true'); glyph.style.width = glyph.style.height = '16px';
+ const path = document.createElementNS(glyph.namespaceURI, 'path'); path.setAttribute('d', playing ? 'M4 3h3v10H4zM9 3h3v10H9z' : 'm5 3 8 5-8 5z'); path.setAttribute('fill', 'currentColor'); glyph.append(path); playButton.replaceChildren(glyph);
+ }
+ playButton.setAttribute('aria-label', playing ? t('Pause', '暂停') : t('Play', '播放'));
+ const shown = Math.min(position, Math.max(0, model.duration(record) - 1));
+ const map = located(record, shown), videoRow = pictureEdit.previewRow(map.get('v1'), shown), clip = videoRow?.clip;
+ const source = clip?.source && sources.get(sourceKey(clip.source));
+ const hasPicture = !!source?.video && !source.missing;
+ const fallbackSize = record.size_mode === 'fixed' || record.tracks[0].clips.some(c => c.source) ? record : {width: 1344, height: 768};
+ pictureGuide.update({size: previewSize || (hasPicture && clipPictureSize(clip, sources)) || fallbackSize, record, clip,
+ preview: !!preview, playing});
+ if (!hasPicture) {
+ clipId = null; videos.forEach(video => { video.classList.remove('fv-ed-visible'); stopMedia(video); });
+ } else if (clipId !== clip.id) {
+ const url = mediaURL(api, source.video);
+ if (videos[1 - active].dataset.source === url) active = 1 - active;
+ clipId = clip.id;
+ }
+ const linked = hasPicture ? [...map.values()].find(row => row.clip.id === clip.link) : null;
+ const separate = !!linked?.clip.splice || !hasPicture;
+ if (hasPicture) {
+ const video = videos[active]; video.muted = !linked || separate;
+ seekMedia(video, mediaURL(api, source.video), (videoRow.frame + (playing ? 0 : .5)) / 24, playing && map.get('v1')?.clip.id === clip.id, clipVolume(linked?.clip));
+ videos.forEach((value, index) => { value.classList.toggle('fv-ed-visible', index === active); if (index !== active) stopMedia(value); });
+ }
+ picturePreview.update({clip: hasPicture ? clip : null, size: hasPicture && clipPictureSize(clip, sources), video: videos[active], preview: !!preview, playing});
+ let slot = 0;
+ for (const [track, row] of map) {
+ if (isText(row.clip) || track === 'v1' || (hasPicture && row.clip.link === clip.id && !separate)) continue;
+ const metadata = sources.get(sourceKey(row.clip.source));
+ if (!metadata || metadata.missing || slot >= audio.length) continue;
+ const url = mediaURL(api, metadata.audio); if (!url) continue;
+ seekMedia(audio[slot++], url, audioSeconds(row.clip, row.frame), playing, clipVolume(row.clip));
+ }
+ while (slot < audio.length) stopMedia(audio[slot++]);
+ const next = record.tracks[0].clips.find(value => value.start >= (clip ? clip.start + clip.frames : position) && value.source);
+ const metadata = next && sources.get(sourceKey(next.source));
+ if (metadata?.video && !metadata.missing) {
+ const idle = videos[1 - active]; idle.muted = true;
+ if (idle.dataset.source !== mediaURL(api, metadata.video)) seekMedia(idle, mediaURL(api, metadata.video), next.in / 24, false);
+ }
+ textRenderer?.();
+ }
+ function tick(now) {
+ if (!playing || disposed) return;
+ const total = model.exportFrames(state.record), position = frameStart + Math.max(0, Math.floor((now - clockStart) * 24 / 1000)), last = Math.max(0, total - 1);
+ ticking = true; state.seek(Math.min(position, last)); ticking = false; render();
+ if (position >= total) { pause(); return; }
+ raf = requestAnimationFrame(tick);
+ }
+ const pictureLayout = record => JSON.stringify([record.width, record.height, record.tracks, record.replacements]);
+ function clearPreview() { if (preview) { preview.onended = null; preview.pause(); preview.removeAttribute('src'); preview.load(); preview.remove(); preview = null; } previewSize = previewProject = null; closePreview.hidden = true; }
+ closePreview.onclick = () => { clearPreview(); render(); };
+ function play() {
+ if (disposed || playing || playButton.disabled) return;
+ clearPreview(); if (state.playhead >= Math.max(0, model.exportFrames(state.record) - 1)) state.seek(0);
+ playing = true; clockStart = performance.now(); frameStart = state.playhead; render(); raf = requestAnimationFrame(tick);
+ }
+ function pause() { playing = false; cancelAnimationFrame(raf); [...videos, ...audio].forEach(stopMedia); render(); }
+ playButton.onclick = () => playing ? pause() : play();
+ const unsubscribe = state.subscribe(event => {
+ if (event.type === 'selection') { if (pictureEdit.panelOpen && pictureEdit.selected()) clearPreview(); render(); return; }
+ if (event.type !== 'playhead' && event.type !== 'record') return;
+ if (preview && preservePreview()) previewProject = pictureLayout(state.record);
+ else if (event.type === 'playhead' || previewProject !== pictureLayout(state.record)) clearPreview();
+ if (playing && !ticking) { clockStart = performance.now(); frameStart = state.playhead; }
+ render();
+ });
+ const stopPictureEdit = pictureEdit.subscribe(() => {
+ // Draft geometry updates in picturePreview; only a changed preview part
+ // needs media routing, otherwise slider/crop movement would re-seek video.
+ const row = pictureEdit.previewRow(located(state.record, state.playhead).get('v1'), state.playhead);
+ if (preview && pictureEdit.panelOpen && pictureEdit.selected()) { clearPreview(); render(); }
+ else if ((row?.clip.id || null) !== clipId) render();
+ });
+ render();
+ return {element: frame, picturePreview, play, pause, toggle: () => playing ? pause() : play(), refresh: render,
+ clearPreview() { clearPreview(); render(); },
+ get playing() { return playing; },
+ setTextRenderer(callback) { textRenderer = callback; },
+ previewVolume(id, value) { volumePreview.set(id, value); render(); },
+ clearVolumePreview() { volumePreview.clear(); render(); },
+ async previewSource(source) {
+ if (disposed) return;
+ const previousSize = previewSize || {width: state.record.width, height: state.record.height};
+ pause(); clearPreview(); const metadata = sources.get(sourceKey(source)); if (!metadata?.video && !metadata?.audio) { render(); return; }
+ preview = el(metadata.video ? 'video' : 'audio', 'fv-ed-source-preview'); preview.controls = true; preview.playsInline = true;
+ if (metadata.video && Number.isFinite(metadata.width) && Number.isFinite(metadata.height) && metadata.width >= 2 && metadata.height >= 2)
+ previewSize = {width: metadata.width, height: metadata.height};
+ else if (!metadata.video) previewSize = previousSize;
+ previewProject = pictureLayout(state.record);
+ preview.onended = () => { clearPreview(); render(); };
+ preview.src = mediaURL(api, metadata.video || metadata.audio); frame.append(preview); closePreview.hidden = false; render(); preview.play().catch(() => {});
+ },
+ dispose() { disposed = true; playing = false; cancelAnimationFrame(raf); unsubscribe(); stopPictureEdit(); clearPreview();
+ [...videos, ...audio].forEach(media => { media.pause(); media.onloadedmetadata = null; media.removeAttribute('src'); delete media.dataset.source; media.load(); media.remove(); }); playButton.onclick = closePreview.onclick = null; picturePreview.dispose(); pictureGuide.dispose(); audioContext?.close().catch(() => {}); },
+ };
+}
diff --git a/web/editor_preview_picture.css b/web/editor_preview_picture.css
new file mode 100644
index 0000000..390ae1e
--- /dev/null
+++ b/web/editor_preview_picture.css
@@ -0,0 +1,18 @@
+.fv-editor .fv-ed-preview{position:relative}
+.fv-ed-picture.fv-ed-picture-adjusted{overflow:visible;background:var(--fv-bg);border-radius:8px}
+.fv-ed-picture.fv-ed-picture-adjusted[data-picture-mode=output]{transition:none}
+.fv-ed-picture-bed{position:absolute;inset:0;width:100%;height:100%;pointer-events:none}
+.fv-ed-picture-outside{position:absolute;inset:0;width:100%;height:100%;pointer-events:none;opacity:.35}
+.fv-ed-picture-shade{position:absolute;inset:0;width:100%;height:100%;pointer-events:none;z-index:2;fill:rgba(0,0,0,.65)}
+.fv-ed-picture-handles{position:absolute;inset:0;pointer-events:none;z-index:5}
+.fv-editor .fv-ed-picture-handle{position:absolute;width:22px;height:22px;min-height:0;padding:0;transform:translate(-50%,-50%);background:transparent;border:0;border-radius:2px;pointer-events:auto;touch-action:none;cursor:nwse-resize}
+.fv-ed-picture-handle:after{content:'';display:block;position:absolute;inset:7px;background:var(--fv-accent);border:1px solid var(--fv-ink);border-radius:2px}
+.fv-ed-picture-handle[data-corner=ne],.fv-ed-picture-handle[data-corner=sw]{cursor:nesw-resize}
+.fv-ed-picture-crop-box{position:absolute;inset:0;z-index:4;pointer-events:none}
+.fv-ed-picture-crop-guide{position:absolute;inset:0;width:100%;height:100%;overflow:visible;fill:transparent;stroke:var(--fv-ink);stroke-width:1;pointer-events:none}
+.fv-ed-picture-crop-guide path{pointer-events:all;touch-action:none;cursor:move}
+.fv-ed-picture-crop-box [data-crop-edge=n],.fv-ed-picture-crop-box [data-crop-edge=s]{cursor:ns-resize}
+.fv-ed-picture-crop-box [data-crop-edge=e],.fv-ed-picture-crop-box [data-crop-edge=w]{cursor:ew-resize}
+.fv-ed-picture-snap-x,.fv-ed-picture-snap-y{position:absolute;background:var(--fv-accent);pointer-events:none;z-index:6}
+.fv-ed-picture-snap-x{top:0;height:100%;width:1px}.fv-ed-picture-snap-y{left:0;width:100%;height:1px}
+.fv-ed-picture [hidden],.fv-ed-preview>.fv-ed-picture-outside[hidden]{display:none}
diff --git a/web/editor_preview_picture.js b/web/editor_preview_picture.js
new file mode 100644
index 0000000..2472f03
--- /dev/null
+++ b/web/editor_preview_picture.js
@@ -0,0 +1,275 @@
+import {plan, cssTransform, visibleRect} from './editor_geometry.js';
+import {differentPictureShape} from './editor_frame.js';
+import {PICTURE_DEFAULTS} from './editor_picture_fields.js';
+import {pictureSession} from './editor_picture_session.js';
+const metrics = new WeakMap();
+export function previewPictureTimings(state, reset = false) {
+ const value = metrics.get(state) || {draw: [], layout: []};
+ const result = {draw: [...value.draw], layout: [...value.layout]};
+ if (reset) { value.draw.length = 0; value.layout.length = 0; }
+ return result;
+}
+const el = (tag, cls) => { const e = document.createElement(tag); e.className = cls; return e; };
+const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
+const point = (m, x, y) => [m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5]];
+const corners = p => { const c = p.crop; return [[c.x,c.y],[c.x+c.width,c.y],[c.x+c.width,c.y+c.height],[c.x,c.y+c.height]].map(([x,y]) => point(p.matrix,x,y)); };
+// Q12: inspection follows the playhead in full; editing always uses output
+// coordinates, including a neutral clip and the crop transaction. Fit shows
+// what export writes: the edit's frame, the whole picture, a blurred fill.
+export function previewPictureFrame(clip, p, mode, editing = false) {
+ return editing || clip?.fit === 'contain' || ['move', 'scale', 'crop'].includes(mode)
+ ? {mode: 'output', ...p.output} : {mode: 'source', ...p.rotated};
+}
+// Clip source-pixel corners against the output without changing the frozen
+// transform used while cropping. Return source coordinates for CSS clip-path.
+export function picturePolygon(p) {
+ let polygon = corners(p);
+ for (const [axis, bound, sign] of [[0,0,1],[0,p.output.width,-1],[1,0,1],[1,p.output.height,-1]]) {
+ const next = [];
+ for (let i=0; i<polygon.length; i++) {
+ const a=polygon[i], b=polygon[(i+1)%polygon.length], da=sign*(a[axis]-bound), db=sign*(b[axis]-bound);
+ if (da>=0) next.push(a);
+ if ((da>=0)!==(db>=0)) { const t=da/(da-db); next.push(a.map((v,j)=>v+t*(b[j]-v))); }
+ }
+ polygon=next;
+ }
+ const [a,b,c,d,e,f]=p.matrix, det=a*d-b*c;
+ return polygon.map(([x,y])=>[(d*(x-e)-c*(y-f))/det,(-b*(x-e)+a*(y-f))/det]);
+}
+export function snapPicturePosition(value, size, output, pixels, threshold = 6) {
+ const candidates = [{value:0,line:.5}, {value:(size/output-1)/2,line:0}, {value:(1-size/output)/2,line:1}];
+ const closest = candidates.reduce((a,b) => Math.abs(b.value-value) < Math.abs(a.value-value) ? b : a);
+ return Math.abs(closest.value-value) * pixels <= threshold ? closest : {value, line: null};
+}
+export function createPreviewPicture(host, frame, {state, t}) {
+ const session = pictureSession(state, t);
+ const bed = el('canvas', 'fv-ed-picture-bed'), outside = el('canvas', 'fv-ed-picture-outside');
+ const small = document.createElement('canvas'), padded = document.createElement('canvas');
+ const shade = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); shade.classList.add('fv-ed-picture-shade');
+ for (const node of [bed, outside, shade]) node.setAttribute('aria-hidden', 'true');
+ const shadePath = document.createElementNS(shade.namespaceURI, 'path'); shadePath.setAttribute('fill-rule', 'evenodd'); shade.append(shadePath);
+ const handles = el('div', 'fv-ed-picture-handles'), cropBox = el('div', 'fv-ed-picture-crop-box');
+ const cropGuide = document.createElementNS(shade.namespaceURI, 'svg');
+ cropGuide.classList.add('fv-ed-picture-crop-guide');
+ const cropPath = document.createElementNS(shade.namespaceURI, 'path'); cropGuide.append(cropPath); cropBox.append(cropGuide);
+ cropPath.onpointerdown = e => start(e, 'crop', 'move');
+ const lines = [el('div', 'fv-ed-picture-snap-x'), el('div', 'fv-ed-picture-snap-y')];
+ const buttons = [], cropButtons = [];
+ for (const direction of ['nw','ne','se','sw']) {
+ const b = el('button', 'fv-ed-picture-handle'); b.type = 'button'; b.dataset.corner = direction;
+ b.setAttribute('aria-label', `${t('Scale', '缩放')} ${direction.toUpperCase()}`); b.onpointerdown = e => start(e, 'scale', direction);
+ b.onkeydown = e => { if (['ArrowUp','ArrowDown'].includes(e.key) && current?.clip) { e.preventDefault(); session.change(current.clip.id, {scale: (current.clip.scale ?? 1) + (e.key === 'ArrowUp' ? 1 : -1) * (e.shiftKey ? .1 : .01)}); } };
+ handles.append(b); buttons.push(b);
+ }
+ for (const direction of ['n','e','s','w','nw','ne','se','sw']) {
+ const b = el('button', 'fv-ed-picture-handle'); b.type = 'button'; b.dataset.cropEdge = direction;
+ b.setAttribute('aria-label', `${t('Crop', '裁剪')} ${direction.toUpperCase()}`); b.onpointerdown = e => start(e, 'crop', direction);
+ b.onkeydown = e => {
+ if (!['ArrowUp','ArrowDown','ArrowLeft','ArrowRight'].includes(e.key)) return; e.preventDefault();
+ const step = (e.shiftKey ? 10 : 1), dx = e.key === 'ArrowRight' ? step : e.key === 'ArrowLeft' ? -step : 0, dy = e.key === 'ArrowDown' ? step : e.key === 'ArrowUp' ? -step : 0;
+ session.preview(cropFields(session.clip(current.clip), direction, dx / current.size.width, dy / current.size.height, current.size));
+ };
+ cropBox.append(b); cropButtons.push(b);
+ }
+
+ frame.prepend(bed); frame.append(shade, handles, cropBox, ...lines); host.append(outside);
+ let current = null, layout = null, gesture = null, key = '', disposed = false, observedVideo = null, videoCallback = null;
+ let followFrame = 0;
+ const samples = [], layouts = []; metrics.set(state, {draw: samples, layout: layouts});
+ const recordTime = (list, start) => { list.push(performance.now()-start); if(list.length>240)list.shift(); };
+ // No part under the playhead (a gap, or past the end) is never the selected one.
+ const isSelected = clip => !!clip && state.selection?.kind === 'clip' && state.selection.ids.includes(clip.id)
+ && state.selection.ids.every(id => id === clip.id || id === clip.link);
+ const editable = clip => isSelected(clip) && session.canEdit(clip);
+ function reset() {
+ for (const node of [bed, outside, shade, handles, cropBox, ...lines]) node.hidden = true;
+ shade.style.display = 'none';
+ frame.classList.remove('fv-ed-picture-adjusted'); layout = null; key = '';
+ frame.querySelectorAll('video').forEach(v => { if (!v.matches('.fv-ed-source-preview')) v.removeAttribute('style'); });
+ }
+ function watch(video) {
+ if (observedVideo === video) return;
+ if (observedVideo) { observedVideo.cancelVideoFrameCallback?.(videoCallback); observedVideo.removeEventListener('seeked', draw); observedVideo.removeEventListener('loadeddata', draw); }
+ observedVideo = video;
+ if (video) {
+ video.addEventListener('seeked', draw); video.addEventListener('loadeddata', draw);
+ const next = () => { if (disposed || observedVideo !== video) return; draw(); videoCallback = video.requestVideoFrameCallback?.(next); };
+ videoCallback = video.requestVideoFrameCallback?.(next);
+ }
+ }
+ function update(value = current, force = false) {
+ const started = performance.now();
+ current = value;
+ if (!value?.clip || !value.size || value.preview || !value.video) { if (session.draft?.mode === 'crop') session.cancel(); watch(null); reset(); return; }
+ if (value.playing && session.draft && session.draft.mode !== 'slider') session.cancel();
+ watch(value.video);
+ const clip = {...PICTURE_DEFAULTS, ...session.clip(value.clip)}, record = state.record;
+ const cropping = session.draft?.mode === 'crop' && session.draft.id === clip.id;
+ let p = plan(clip, value.size.width, value.size.height, record.width, record.height);
+ if (cropping) {
+ const original = plan(session.draft.original, value.size.width, value.size.height, record.width, record.height);
+ p = {...original, crop: p.crop, covers: false};
+ }
+ const policy = previewPictureFrame(clip, p, session.draft?.mode, session.output(clip));
+ frame.dataset.pictureMode = policy.mode;
+ frame.classList.add('fv-ed-picture-adjusted');
+ frame.style.setProperty('--fv-ed-width', String(policy.width)); frame.style.setProperty('--fv-ed-height', String(policy.height));
+ const rect = frame.getBoundingClientRect(), hostRect = host.getBoundingClientRect();
+ // The frame eases to a new shape over 150 ms; keep the picture and handles on it each frame until it settles.
+ if (!followFrame && frame.getAnimations?.().some(a => a.playState === 'running' || a.pending))
+ followFrame = requestAnimationFrame(() => { followFrame = 0; if (!disposed) update(current, true); });
+ const oldShade = frame.querySelector('.fv-ed-crop-shade');
+ const traditional = policy.mode === 'source' && !clip.rotate && !clip.flip_h && !clip.flip_v && !clip.crop_left && !clip.crop_top && !clip.crop_right && !clip.crop_bottom;
+ const different = differentPictureShape({width:Math.round(p.rotated.width),height:Math.round(p.rotated.height)}, record);
+ if (oldShade) oldShade.hidden = !traditional || !different || clip.fit === 'contain';
+ // The Fill/Fit switch sits on the preview area (editor_frame.js shows or hides it); here it only turns gray while the part cannot change.
+ const tools = host.querySelector('.fv-ed-picture-tools');
+ if (tools) for (const button of tools.querySelectorAll('button')) button.disabled = !session.canEdit(clip);
+ const nextKey = JSON.stringify([clip, policy, rect.width, rect.height, hostRect.width, hostRect.height, isSelected(clip), value.playing]);
+ if (!force && nextKey === key) { recordTime(layouts, started); return; } key = nextKey;
+ let view = p;
+ if (policy.mode === 'source') {
+ view = {...p, output: {...p.size}, matrix: [...p.matrix]};
+ view.matrix[4] -= p.center.x - p.size.width / 2; view.matrix[5] -= p.center.y - p.size.height / 2;
+ }
+ const bw = rect.width, bh = rect.height;
+ if (bw <= 0 || bh <= 0) return;
+ const sx = bw / view.output.width, sy = bh / view.output.height;
+ const m = view.matrix.map((v,i) => v * (i % 2 ? sy : sx));
+ Object.assign(value.video.style, cssTransform(view, bw, bh));
+ if (traditional) value.video.style.objectFit = 'contain';
+ value.video.style.borderRadius = traditional ? `${8/sx}px / ${8/sy}px` : '0';
+ if (view.crop.x === 0 && view.crop.y === 0 && view.crop.width === view.source.width && view.crop.height === view.source.height) value.video.style.clipPath = 'none';
+ if (policy.mode === 'output') {
+ const polygon = cropping ? picturePolygon(p) : visibleRect(p).polygon;
+ value.video.style.clipPath = polygon.length ? `polygon(${polygon.map(([x,y])=>`${x}px ${y}px`).join(',')})` : 'inset(100%)';
+ }
+ // Existing guide keeps the fit switch; its axis-only shade is replaced here.
+ layout = {p, view, policy, clip, bw, bh, m, left: rect.left-hostRect.left, top: rect.top-hostRect.top, hw: hostRect.width, hh: hostRect.height};
+ shade.hidden = traditional || policy.mode !== 'source' || clip.fit === 'contain';
+ shade.style.display = shade.hidden ? 'none' : '';
+ shade.setAttribute('viewBox', `0 0 ${bw} ${bh}`);
+ const path = polygon => polygon.length ? `M${polygon.map(([x,y])=>`${x},${y}`).join('L')}Z` : '';
+ const c = view.crop;
+ const outer = [[c.x,c.y],[c.x+c.width,c.y],[c.x+c.width,c.y+c.height],[c.x,c.y+c.height]].map(([x,y])=>point(m,x,y));
+ const inner = visibleRect(p).polygon.map(([x,y])=>point(m,x,y));
+ shadePath.setAttribute('d', path(outer)+path(inner));
+ handles.hidden = !editable(clip) || value.playing || cropping;
+ const pts = corners(view).map(([x,y])=>[x*sx,y*sy]);
+ buttons.forEach((b,i) => { b.style.left = `${clamp(pts[i][0], -layout.left+12, layout.hw-layout.left-12)}px`; b.style.top = `${clamp(pts[i][1], -layout.top+12, layout.hh-layout.top-12)}px`; });
+ cropBox.hidden = !cropping;
+ if (cropping) {
+ cropGuide.setAttribute('viewBox', `0 0 ${bw} ${bh}`);
+ const c = view.crop, at = (x,y) => point(m,c.x+c.width*x,c.y+c.height*y);
+ cropPath.setAttribute('d', path([at(0,0),at(1,0),at(1,1),at(0,1)]) + [1/3,2/3].map(v =>
+ `M${at(v,0).join(',')}L${at(v,1).join(',')}M${at(0,v).join(',')}L${at(1,v).join(',')}`).join(''));
+ cropButtons.forEach(b => {
+ const edge=b.dataset.cropEdge, [x,y]=at(edge.includes('w')?0:edge.includes('e')?1:.5,edge.includes('n')?0:edge.includes('s')?1:.5);
+ b.style.left=`${clamp(x,-layout.left+12,layout.hw-layout.left-12)}px`;
+ b.style.top=`${clamp(y,-layout.top+12,layout.hh-layout.top-12)}px`;
+ });
+ }
+ bed.hidden = cropping || policy.mode !== 'output' || p.covers;
+ outside.hidden = policy.mode !== 'output' || !isSelected(clip);
+ draw(); recordTime(layouts, started);
+ }
+ function sourceDraw(ctx, matrix, video, p) {
+ const c = p.crop; ctx.setTransform(...matrix);
+ ctx.drawImage(video,c.x,c.y,c.width,c.height,c.x,c.y,c.width,c.height);
+ ctx.resetTransform();
+ }
+ function draw() {
+ if (!layout || !current?.video || current.video.readyState < 2 || !current.video.videoWidth || !current.video.videoHeight || (bed.hidden && outside.hidden)) return;
+ const start = performance.now(), {p, bw, bh, m, left, top, hw, hh} = layout, video = current.video;
+ const cropping = session.draft?.mode === 'crop';
+ if (!bed.hidden) {
+ const w = Math.max(1, Math.ceil(bw/4)), h = Math.max(1, Math.ceil(bh/4));
+ if (small.width !== w || small.height !== h) { small.width=w; small.height=h; }
+ const ctx = small.getContext('2d'), c=p.crop, angle=p.rotate*Math.PI/180, co=Math.abs(Math.cos(angle)), si=Math.abs(Math.sin(angle));
+ const ratio = Math.max((co*w+si*h)/c.width,(si*w+co*h)/c.height);
+ // Normalize the renderer's oriented basis, then cover the opaque
+ // rectangle. The bed has no user-scale cap (important for thin crops).
+ const [a,b,cc,d] = p.matrix, xscale=ratio/Math.hypot(a,b), yscale=ratio/Math.hypot(cc,d);
+ const matrix=[a*xscale,b*xscale,cc*yscale,d*yscale,0,0], cx=c.x+c.width/2,cy=c.y+c.height/2;
+ matrix[4]=w/2-matrix[0]*cx-matrix[2]*cy;matrix[5]=h/2-matrix[1]*cx-matrix[3]*cy;
+ ctx.clearRect(0,0,w,h); sourceDraw(ctx,matrix,video,p);
+ // Extend border pixels before blur: no transparent/black halo.
+ const radius=Math.min(bw,bh)/20/4, pad=Math.ceil(radius*3), pw=w+2*pad, ph=h+2*pad;
+ if (padded.width!==pw || padded.height!==ph) { padded.width=pw; padded.height=ph; }
+ const pc=padded.getContext('2d'); pc.clearRect(0,0,pw,ph); pc.drawImage(small,pad,pad);
+ pc.drawImage(small,0,0,w,1,pad,0,w,pad); pc.drawImage(small,0,h-1,w,1,pad,pad+h,w,pad);
+ pc.drawImage(padded,pad,0,1,ph,0,0,pad,ph); pc.drawImage(padded,pad+w-1,0,1,ph,pad+w,0,pad,ph);
+ if (bed.width!==w || bed.height!==h) { bed.width=w; bed.height=h; }
+ const bc=bed.getContext('2d'); bc.clearRect(0,0,w,h); bc.filter=`blur(${radius}px) brightness(0.7)`; bc.drawImage(padded,-pad,-pad); bc.filter='none';
+ }
+ if (!outside.hidden) {
+ const w=Math.ceil(hw), h=Math.ceil(hh);
+ if (outside.width!==w || outside.height!==h) { outside.width=w; outside.height=h; }
+ const ctx=outside.getContext('2d'); ctx.clearRect(0,0,w,h); ctx.save();
+ ctx.beginPath();ctx.rect(0,0,w,h);
+ if (cropping) {
+ const polygon=picturePolygon(p).map(([x,y])=>point(m,x,y));
+ if (polygon.length) { ctx.moveTo(polygon[0][0]+left,polygon[0][1]+top); for (const [x,y] of polygon.slice(1)) ctx.lineTo(x+left,y+top); ctx.closePath(); }
+ } else ctx.rect(left,top,bw,bh);
+ ctx.clip('evenodd');
+ const transform=[...m];transform[4]+=left;transform[5]+=top;
+ sourceDraw(ctx,transform,video,cropping ? {...p,crop:{x:0,y:0,...p.source}} : p);ctx.restore();
+ }
+ recordTime(samples, start);
+ }
+ function cropFields(base, edge, dx, dy, size) {
+ const f={...PICTURE_DEFAULTS,...base};
+ if(edge==='move') {
+ dx=clamp(dx,-f.crop_left,f.crop_right);dy=clamp(dy,-f.crop_top,f.crop_bottom);
+ f.crop_left+=dx;f.crop_right-=dx;f.crop_top+=dy;f.crop_bottom-=dy;
+ } else {
+ const xMax=Math.min(.9,1-1/size.width), yMax=Math.min(.9,1-1/size.height);
+ if(edge.includes('w')) f.crop_left=clamp(f.crop_left+dx,0,xMax-f.crop_right);
+ if(edge.includes('e')) f.crop_right=clamp(f.crop_right-dx,0,xMax-f.crop_left);
+ if(edge.includes('n')) f.crop_top=clamp(f.crop_top+dy,0,yMax-f.crop_bottom);
+ if(edge.includes('s')) f.crop_bottom=clamp(f.crop_bottom-dy,0,yMax-f.crop_top);
+ }
+ return Object.fromEntries(['left','right','top','bottom'].map(k=>['crop_'+k,f['crop_'+k]]));
+ }
+ function start(event, mode, edge) {
+ if (event.button!==0 || !current || current.playing || !editable(current.clip)) return;
+ event.preventDefault();event.stopPropagation();
+ const base={...PICTURE_DEFAULTS,...session.clip(current.clip)};
+ session.begin(current.clip.id,mode); update(current,true);
+ const r=frame.getBoundingClientRect();
+ gesture={mode,edge,base,x:event.clientX,y:event.clientY,rect:r,m:layout.m,p:layout.p,pointer:event.pointerId,target:event.currentTarget};
+ gesture.target.setPointerCapture?.(event.pointerId);
+ }
+ const down = event => { if(!event.target.closest('button') && session.draft?.mode!=='crop') start(event,'move'); };
+ const move = event => {
+ if(!gesture || event.pointerId!==gesture.pointer) return;
+ const g=gesture, dx=(event.clientX-g.x)/g.rect.width, dy=(event.clientY-g.y)/g.rect.height;
+ if(g.mode==='crop') {
+ const [a,b,c,d]=g.m, det=a*d-b*c, px=event.clientX-g.x, py=event.clientY-g.y;
+ session.preview(cropFields(g.base,g.edge,(d*px-c*py)/det/current.size.width,(-b*px+a*py)/det/current.size.height,current.size));
+ }
+ else if(g.mode==='move') {
+ const x=snapPicturePosition(g.base.offset_x+dx,g.p.size.width,g.p.output.width,g.rect.width);
+ const y=snapPicturePosition(g.base.offset_y+dy,g.p.size.height,g.p.output.height,g.rect.height);
+ session.preview({offset_x:x.value,offset_y:y.value});
+ lines[0].hidden=x.line===null; lines[1].hidden=y.line===null;
+ lines[0].style.left=`${x.line*100}%`;lines[1].style.top=`${y.line*100}%`;
+ } else {
+ const cx=g.rect.left+g.rect.width*(.5+g.base.offset_x),cy=g.rect.top+g.rect.height*(.5+g.base.offset_y);
+ const initial=Math.hypot(g.x-cx,g.y-cy), now=Math.hypot(event.clientX-cx,event.clientY-cy);
+ let scale=clamp(g.base.scale*now/Math.max(1,initial),.1,10);if(Math.abs(scale-1)<.025) scale=1;
+ session.preview({scale});
+ }
+ };
+ const end = event => {
+ if(!gesture || event.pointerId!==gesture.pointer) return;
+ const mode=gesture.mode;gesture=null;lines.forEach(l=>l.hidden=true);
+ if(event.type==='pointercancel') session.cancel();else if(mode!=='crop') session.commit();
+ };
+ window.addEventListener('blur', session.cancel);
+ frame.addEventListener('pointerdown',down);window.addEventListener('pointermove',move, true);window.addEventListener('pointerup',end, true);window.addEventListener('pointercancel',end, true);
+ const unsubscribe=session.subscribe(()=>{if(!session.draft){gesture=null;lines.forEach(l=>l.hidden=true);}update(current,true);});
+ const observer=typeof ResizeObserver==='function'?new ResizeObserver(()=>update(current,true)):null;observer?.observe(frame);observer?.observe(host);
+ reset();
+ return {update, get timings(){return [...samples];}, dispose(){disposed=true;cancelAnimationFrame(followFrame);window.removeEventListener('blur',session.cancel);metrics.delete(state);watch(null);unsubscribe();observer?.disconnect();frame.removeEventListener('pointerdown',down);window.removeEventListener('pointermove',move, true);window.removeEventListener('pointerup',end, true);window.removeEventListener('pointercancel',end, true);[bed,outside,shade,handles,cropBox,...lines].forEach(n=>n.remove());}};
+}
diff --git a/web/editor_room.js b/web/editor_room.js
new file mode 100644
index 0000000..935fa0f
--- /dev/null
+++ b/web/editor_room.js
@@ -0,0 +1,142 @@
+// Shared copy and placement rules; the model owns gap/suffix/rollback arithmetic.
+import * as model from './editor_model.js';
+import {isText, assertUnlocked} from './editor_text_model.js';
+import {EditError, insertionAt, makeRoom} from './editor_model.js';
+
+const end = clip => clip.start + clip.frames;
+const busy = clip => ['queued', 'running'].includes(clip.pending);
+const all = record => record.tracks.flatMap(track => track.clips);
+
+export function pasteRoom(record, entries, at, placeAudio) {
+ const video = entries.some(item => item.kind === 'video');
+ for (const {clip} of entries) clip.start += at;
+ // Text alone stays where it is pasted; landing on existing text refuses the whole paste (pasteContent).
+ if (!entries.some(item => ['video', 'audio'].includes(item.kind))) return record;
+ // Preserve an available audio lane before considering a displaced suffix.
+ try { placeAudio(record, entries); } catch (error) { if (error.code !== 'overlap') throw error; }
+ const anchor = video ? 'v1' : entries[0].track;
+ const start = record.tracks.some(track => track.id === anchor) ? insertionAt(record, anchor, at) : at;
+ for (const {clip} of entries) clip.start += start - at;
+ const frames = Math.max(...entries.map(({clip}) => clip.start + clip.frames)) - start;
+ const pictureRoom = makeRoom(record, start, frames, {tracks: video ? ['v1'] : []});
+ try { placeAudio(pictureRoom, entries); return pictureRoom; } catch (error) {
+ if (error.code !== 'overlap') throw error;
+ // Crossing content is fixed. Later content can yield, but cannot force
+ // a third audio lane or displace a crossing soundtrack.
+ try { placeAudio({...record, tracks: record.tracks.map(track => ({...track,
+ clips: track.clips.filter(clip => clip.start < start)}))}, entries); }
+ catch (error) { if (error.code === 'overlap') throw new EditError('audio_full'); throw error; }
+ }
+ const tracks = entries.map(item => item.kind === 'video' ? 'v1' : item.track);
+ const next = makeRoom(record, start, frames, {tracks});
+ placeAudio(next, entries);
+ return next;
+}
+
+export function copyContent(record, ids) {
+ const wanted = model.linkedIds(record, ids), byId = new Map(all(record).map(clip => [clip.id, clip]));
+ const eligible = clip => (clip?.source || isText(clip)) && !busy(clip);
+ const clips = record.tracks.flatMap(track => track.clips.filter(clip => wanted.has(clip.id)
+ && eligible(clip) && (!clip.link || eligible(byId.get(clip.link)))).map(clip => ({track: track.id, kind: track.kind, clip: structuredClone(clip)})));
+ if (!clips.length) throw new model.EditError('not_generated');
+ const start = Math.min(...clips.map(item => item.clip.start));
+ for (const {clip} of clips) {
+ clip.start -= start; clip.versions = []; clip.pending = clip.reason = clip.job = null;
+ // A shot reference names one part; a copy keeps its description and version origin but not the reference.
+ delete clip.target_frames; delete clip.ref;
+ }
+ return {clips};
+}
+// Two audio lanes are a two-colour interval graph. Fixed existing intervals
+// constrain the colour; free components prefer their original lanes. This also
+// handles a long copied interval whose shorter companion must change lanes.
+export function placeAudio(record, entries) {
+ const nodes = record.tracks.filter(track => track.kind === 'audio').flatMap(track => track.clips.map(clip =>
+ ({clip, preferred: track.id === 'a1' ? 0 : 1, fixed: true, neighbors: []})));
+ nodes.push(...entries.filter(item => item.kind === 'audio').map(item =>
+ ({clip: item.clip, preferred: item.track === 'a1' ? 0 : 1, item, neighbors: []})));
+ nodes.sort((a, b) => a.clip.start - b.clip.start);
+ let active = [];
+ for (const node of nodes) {
+ active = active.filter(other => end(other.clip) > node.clip.start);
+ if (active.length > 1) throw new model.EditError('overlap');
+ for (const other of active) { node.neighbors.push(other); other.neighbors.push(node); }
+ active.push(node);
+ }
+ for (const root of nodes) {
+ if (root.colour !== undefined) continue;
+ root.colour = 0;
+ const component = [root]; let required = null;
+ for (let i = 0; i < component.length; i++) {
+ const node = component[i];
+ if (node.fixed) {
+ const flip = node.colour ^ node.preferred;
+ if (required !== null && required !== flip) throw new model.EditError('overlap');
+ required = flip;
+ }
+ for (const other of node.neighbors) if (other.colour === undefined) { other.colour = 1 - node.colour; component.push(other); }
+ }
+ const preference = component.reduce((sum, node) => sum + (node.colour === node.preferred ? 1 : -1), 0);
+ const flip = required ?? (preference < 0 ? 1 : 0);
+ for (const node of component) if (node.item) node.item.track = (node.colour ^ flip) ? 'a2' : 'a1';
+ }
+}
+export function pasteContent(record, content, at) {
+ if (!content?.clips.length) throw new model.EditError('clipboard_empty');
+ if (!Number.isSafeInteger(at) || at < 0) throw new model.EditError('range');
+ const entries = structuredClone(content.clips), ids = new Map(), parts = new Map();
+ const next = model.serialize(pasteRoom(record, entries, at, placeAudio));
+ for (const {clip} of entries) ids.set(clip.id, `c${++next.serial}`);
+ for (const item of entries) {
+ const clip = item.clip;
+ clip.id = ids.get(clip.id); clip.link = ids.get(clip.link) ?? null;
+ if (clip.part) { if (!parts.has(clip.part)) parts.set(clip.part, `c${++next.serial}`); clip.part = parts.get(clip.part); }
+ if (item.kind === 'video') item.track = 'v1';
+ let track = next.tracks.find(track => track.id === item.track);
+ if (!track) { track = {id: item.track, kind: item.kind, clips: []}; next.tracks.push(track); }
+ assertUnlocked(next, track.clips.map(c => c.id));
+ if (isText(clip) && track.clips.some(other => other.start < end(clip) && end(other) > clip.start)) throw new EditError('overlap');
+ track.clips.push(clip);
+ }
+ next.tracks.sort((a,b) => ['v1','a1','a2','t1','s1'].indexOf(a.id) - ['v1','a1','a2','t1','s1'].indexOf(b.id));
+ next.tracks.forEach(track => track.clips.sort((a, b) => a.start - b.start));
+ return {record: model.parse(next), ids: [...ids.values()], end: Math.max(...entries.map(item => end(item.clip)))};
+}
+
+// Q3: a range not generated yet is copied as itself; it pastes back as a range with its description,
+// landing like other content (after a part under the playhead; later content yields).
+export function copyRange(selection, text) {
+ return {range: {frames: selection.frames, tracks: [...selection.tracks], ...(selection.parts ? {parts: [...selection.parts]} : {}), text: text ?? ''}};
+}
+export function pasteRange(record, copied, at) {
+ if (!Number.isSafeInteger(at) || at < 0) throw new EditError('range');
+ const present = copied.tracks.filter(id => record.tracks.some(track => track.id === id));
+ const tracks = present.length ? present : ['v1', 'a1'], anchor = tracks.includes('v1') ? 'v1' : tracks[0];
+ const start = insertionAt(record, anchor, at);
+ return {record: makeRoom(record, start, copied.frames, {tracks}),
+ range: {kind: 'range', start, frames: copied.frames, tracks, ...(copied.parts ? {parts: [...copied.parts]} : {})}};
+}
+
+export function playheadTargets(record, ids, frame) {
+ const selected = new Set([...model.linkedIds(record, ids)]), crosses = clip => clip.start < frame && end(clip) > frame;
+ let candidates = all(record).filter(clip => selected.has(clip.id) && crosses(clip));
+ if (!candidates.length) {
+ const rows = record.tracks.filter(track => ['video', 'audio'].includes(track.kind));
+ const hit = rows.find(track => track.clips.some(crosses))?.clips.find(crosses);
+ candidates = hit ? [hit] : [];
+ }
+ const handled = new Set();
+ return candidates.filter(clip => {
+ if (handled.has(clip.id)) return false;
+ model.pair(record, clip.id).forEach(member => handled.add(member.id)); return true;
+ }).map(clip => clip.id);
+}
+
+export function removableGaps(record, value) {
+ const track = value?.kind === 'gap' ? record.tracks.find(track => track.id === value.track)
+ : record.tracks.find(track => track.kind === 'video' && track.clips.length)
+ || record.tracks.find(track => track.kind === 'audio' && track.clips.length);
+ if (!track) return [];
+ return model.gaps(record, track.id).filter(gap => track.clips.some(clip => clip.start >= end(gap))
+ && (value?.kind !== 'gap' || gap.start === value.start)).map(gap => ({...gap, track: track.id}));
+}
diff --git a/web/editor_select.css b/web/editor_select.css
new file mode 100644
index 0000000..aabde6e
--- /dev/null
+++ b/web/editor_select.css
@@ -0,0 +1,15 @@
+/* Individual outlines make non-contiguous selections visible on every track. */
+.fv-ed-track-view .fv-ed-clip[aria-selected=true]{outline:2px solid var(--fv-accent);outline-offset:-2px}
+.fv-ed-track-view[data-multiselect=true] .fv-ed-selection:not(.fv-ed-range):not(.fv-ed-gap){display:none}
+.fv-ed-marquee{position:absolute;z-index:8;border:1px solid var(--fv-accent);background:color-mix(in srgb,var(--fv-accent) 12%,transparent);pointer-events:none}
+.fv-ed-marquee-outlines{position:absolute;inset:0;z-index:8;pointer-events:none}
+.fv-ed-marquee-item{position:absolute;border:2px solid var(--fv-accent);border-radius:8px}
+.fv-ed-group-guide{position:absolute;top:24px;bottom:0;width:1px;background:var(--fv-accent);z-index:8;pointer-events:none}
+.fv-ed-group-label{position:absolute;z-index:10;padding:4px 7px;background:var(--fv-card);color:var(--fv-ink);border:1px solid var(--fv-border);border-radius:6px;font-size:12px;white-space:nowrap;pointer-events:none}
+.fv-ed-group-layer{position:absolute;inset:0;z-index:7;opacity:.85;pointer-events:none;will-change:transform}
+.fv-ed-group-layer .fv-ed-clip{pointer-events:auto;cursor:grabbing}
+.fv-ed-track-view .fv-ed-cannot-drop{cursor:not-allowed}
+.fv-ed-track-view .fv-ed-cannot-drop::after{content:"";position:absolute;inset:0;border:2px solid var(--fv-danger);border-radius:inherit;pointer-events:none;z-index:5;background:repeating-linear-gradient(135deg,transparent 0 6px,color-mix(in srgb,var(--fv-danger) 28%,transparent) 6px 9px)}
+.fv-ed-track-view[data-select-gesture=box] .fv-ed-selection{display:none}
+.fv-ed-track-view[data-select-blocked=true] .fv-ed-group-label{color:var(--fv-warning);border-color:var(--fv-warning)}
+@media(forced-colors:active){.fv-ed-marquee{border-color:Highlight}.fv-ed-clip[aria-selected=true]{outline-color:Highlight}.fv-ed-cannot-drop::after{border-style:dashed!important}}
diff --git a/web/editor_select.js b/web/editor_select.js
new file mode 100644
index 0000000..c77f668
--- /dev/null
+++ b/web/editor_select.js
@@ -0,0 +1,302 @@
+// Selection, page-local clipboard and group gestures. No system clipboard access.
+import * as model from './editor_model.js';
+import * as actionsModel from './editor_actions.js';
+import {copyContent, pasteContent, copyRange, pasteRange, playheadTargets, removableGaps as findGaps} from './editor_room.js';
+export {copyContent, pasteContent} from './editor_room.js';
+
+const end = clip => clip.start + clip.frames;
+const busy = clip => ['queued', 'running'].includes(clip.pending);
+const all = record => record.tracks.flatMap(track => track.clips);
+const selection = ids => ids.length ? {kind: 'clip', ids} : null;
+// Parts on a locked track cannot be selected by any gesture, Select all included.
+const lockedIds = record => new Set(record.tracks.filter(track => track.locked).flatMap(track => track.clips.map(clip => clip.id)));
+export const isTyping = target => !!(target.isContentEditable || target.closest?.('input, textarea, select, [contenteditable="true"], [contenteditable=""], [contenteditable="plaintext-only"]'));
+export const selectedIds = (record, value) => actionsModel.linkedIds(record, value?.kind === 'clip' ? value.ids : []);
+export function isMultiple(record, ids) {
+ const members = all(record).filter(clip => ids.includes(clip.id)), seen = new Set();
+ let count = 0;
+ for (const clip of members) if (!seen.has(clip.id)) { count++; seen.add(clip.id); seen.add(clip.link); }
+ return count > 1;
+}
+export function clickSelection(record, current, id, {toggle = false, shift = false} = {}) {
+ const clip = model.find(record, id);
+ if (!clip) return null;
+ if (lockedIds(record).has(id)) return current;
+ if (toggle || shift) {
+ const ids = new Set(selectedIds(record, current)), pair = [...model.linkedIds(record, [id])];
+ const remove = ids.has(id);
+ for (const member of pair) remove ? ids.delete(member) : ids.add(member);
+ return selection([...ids]);
+ }
+ return selection([...model.linkedIds(record, [id])]);
+}
+export function rectangleSelection(record, rectangles, box) {
+ const locked = lockedIds(record), ids = rectangles.filter(item => !locked.has(item.id) && item.left <= box.right && item.right >= box.left
+ && item.top <= box.bottom && item.bottom >= box.top).map(item => item.id);
+ return selection([...model.linkedIds(record, ids)]);
+}
+export function playheadIds(record, value, frame) {
+ return playheadTargets(record, selectedIds(record, value), frame);
+}
+export function splitSelection(record, value, frame) {
+ // Keep the page helper's boundary no-op; commands check targets first.
+ return playheadIds(record, value, frame).length ? actionsModel.splitAt(record, selectedIds(record, value), frame) : record;
+}
+export function trimSelection(record, value, frame, edge) {
+ return playheadIds(record, value, frame).length ? actionsModel.trimAt(record, selectedIds(record, value), frame, edge) : record;
+}
+export function removableGaps(record, value) {
+ return findGaps(record, value?.kind === 'gap' ? value : null);
+}
+export function removeGaps(record, value) {
+ return actionsModel.removeGaps(record, value?.kind === 'gap' ? value : null);
+}
+// Share protection between the toolbar, keyboard and external commands.
+export function deletionStatus(record, value) {
+ if (!value) return {ok: false, reason: 'selection'};
+ if (value.kind === 'gap') {
+ const result = removeGaps(record, value);
+ return result.removed ? {ok: true} : {ok: false, reason: result.skipped[0]?.code || 'no_gap'};
+ }
+ const ids = new Set(selectedIds(record, value));
+ const members = value.kind === 'range' ? record.tracks.filter(track => value.tracks.includes(track.id))
+ .flatMap(track => track.clips.filter(clip => clip.start < end(value) && end(clip) > value.start))
+ : all(record).filter(clip => ids.has(clip.id));
+ return members.some(clip => model.pair(record, clip.id).some(busy))
+ ? {ok: false, reason: 'busy'} : {ok: true};
+}
+export function createClipboard() {
+ let value = null;
+ return {read: () => value && structuredClone(value), write: content => { value = structuredClone(content); }};
+}
+const pageClipboard = createClipboard();
+export function createSelectionActions({state, t = en => en, actions = {}, clipboard = pageClipboard}) {
+ function report(error) {
+ if (!(error instanceof model.EditError)) throw error;
+ if (error.code === 'not_generated' && actions.notify) actions.notify(t('Not generated yet', '还没生成'));
+ else if (error.code !== 'clipboard_empty') actions.editError?.(error);
+ return {ok: false, reason: error.code};
+ }
+ function run(key) {
+ try {
+ const ids = selectedIds(state.record, state.selection);
+ if (key === 'a') { const locked = lockedIds(state.record); state.select(selection(all(state.record).filter(clip => !locked.has(clip.id)).map(clip => clip.id))); return {ok: true}; }
+ if (['b', 'q', 'w'].includes(key) && !playheadIds(state.record, state.selection, state.playhead).length) {
+ return {ok: false, reason: 'playhead'};
+ }
+ if (key === 'b') { state.apply(t('Split', '剪开'), record => actionsModel.splitAt(record, ids, state.playhead)); return {ok: true}; }
+ if (key === 'q' || key === 'w') {
+ state.apply(key === 'q' ? t('Trim before playhead', '裁掉前面') : t('Trim after playhead', '裁掉后面'),
+ record => actionsModel.trimAt(record, ids, state.playhead, key === 'q' ? 'start' : 'end')); return {ok: true};
+ }
+ if (key === 'gaps' || (['delete', 'backspace'].includes(key) && state.selection?.kind === 'gap')) {
+ const result = actionsModel.removeGaps(state.record, state.selection?.kind === 'gap' ? state.selection : null);
+ state.apply(t('Remove gaps', '移除空隙'), () => result.record,
+ result.removed && state.selection?.kind === 'gap' ? {selectionAfter: null} : {});
+ return {ok: !!result.removed, ...(result.removed ? {} : {reason: result.skipped[0]?.code || 'no_gap'}), removed: result.removed, skipped: result.skipped};
+ }
+ if (key === 'delete' || key === 'backspace') {
+ const status = deletionStatus(state.record, state.selection);
+ if (!status.ok) return status.reason === 'busy' ? report(new model.EditError(status.reason)) : status;
+ if (ids.length) state.apply(t('Delete', '删除'), record => actionsModel.removeParts(record, ids), {selectionAfter: null});
+ else if (state.selection?.kind === 'range') state.select(null, {history: true});
+ return {ok: true};
+ }
+ if ((key === 'c' || key === 'x') && state.selection?.kind === 'range') {
+ clipboard.write(copyRange(state.selection, state.rangeText));
+ if (key === 'x') state.select(null, {history: true});
+ return {ok: true};
+ }
+ const copied = key === 'v' ? clipboard.read() : null;
+ if (copied?.range) {
+ const pasted = pasteRange(state.record, copied.range, state.playhead), label = t('Paste', '粘贴');
+ if (JSON.stringify(pasted.record) !== JSON.stringify(state.record)) state.apply(label, () => pasted.record, {selectionAfter: pasted.range, rangeText: copied.range.text});
+ else state.select(pasted.range, {history: true, text: copied.range.text});
+ state.seek(pasted.range.start + pasted.range.frames); return {ok: true};
+ }
+ if (key === 'c' || key === 'x') {
+ const content = copyContent(state.record, ids);
+ if (key === 'x') state.apply(t('Cut', '剪切'), record => actionsModel.removeParts(record, ids), {selectionAfter: null});
+ clipboard.write(content); return {ok: true};
+ }
+ // Preserve the page clipboard's existing eligibility/error behavior.
+ if (key === 'd') copyContent(state.record, ids);
+ const pasted = key === 'd' ? actionsModel.duplicateParts(state.record, ids)
+ : pasteContent(state.record, copied, state.playhead);
+ state.apply(key === 'd' ? t('Duplicate', '创建副本') : t('Paste', '粘贴'), () => pasted.record, {selectionAfter: selection(pasted.ids)});
+ state.seek(pasted.end); return {ok: true};
+ } catch (error) { return report(error); }
+ }
+ return {run, report, canPaste: () => !!(clipboard.read()?.clips?.length || clipboard.read()?.range), keyboard(event) {
+ if (event.defaultPrevented || event.isComposing || event.keyCode === 229 || isTyping(event.target) || event.altKey) return false;
+ const key = event.key.toLowerCase(), command = (event.ctrlKey || event.metaKey) && !event.shiftKey && ['a', 'c', 'x', 'v', 'd', 'b'].includes(key);
+ const deleting = ['delete', 'backspace'].includes(key) && ['clip', 'gap', 'range'].includes(state.selection?.kind);
+ const trimming = !event.ctrlKey && !event.metaKey && !event.shiftKey && ['q', 'w'].includes(key);
+ if (!command && !deleting && !trimming) return false;
+ event.preventDefault(); event.stopPropagation(); run(key); return true;
+ }};
+}
+
+// Build once per drag; each preview checks ordered intervals without cloning a
+// project, dispatching selection events, or rebuilding clip DOM.
+export function prepareMove(record, ids) {
+ const selected = model.linkedIds(record, ids), members = all(record).filter(clip => selected.has(clip.id));
+ const rows = record.tracks.map(track => ({moving: track.clips.filter(clip => selected.has(clip.id)), others: track.clips.filter(clip => !selected.has(clip.id))}));
+ const start = Math.min(...members.map(clip => clip.start)), stop = Math.max(...members.map(end));
+ return {ids: [...selected], start, end: stop, members, preview(delta) {
+ delta = Math.max(-start, delta);
+ let code = members.some(busy) ? 'busy' : null;
+ for (const {moving, others} of rows) {
+ let i = 0;
+ for (const clip of moving) {
+ while (i < others.length && end(others[i]) <= clip.start + delta) i++;
+ if (others[i]?.start < end(clip) + delta) code ||= 'overlap';
+ }
+ }
+ return {delta, code};
+ }};
+}
+
+export function createSelectionGestures({state, element, content, scroll, clips, rows, hitTest, snap, t, actions, renderSelection}) {
+ const commands = createSelectionActions({state, t, actions});
+ const make = className => { const node = document.createElement('div'); node.className = className; node.hidden = true; content.append(node); return node; };
+ const marquee = make('fv-ed-marquee'), guide = make('fv-ed-group-guide'), outlines = make('fv-ed-marquee-outlines');
+ const label = document.createElement('div'); label.className = 'fv-ed-group-label'; label.hidden = true; label.setAttribute('role', 'status'); element.append(label);
+ let anchor = null, gesture = null, raf = null, lastEvent = null;
+ const pixels = frame => frame * state.zoom / model.FPS;
+ const point = event => { const bounds = content.getBoundingClientRect(); return {x: event.clientX - bounds.left, y: event.clientY - bounds.top}; };
+ const paint = ids => {
+ const selected = new Set(ids);
+ for (const [id, item] of clips) {
+ const value = selected.has(id);
+ if ((item.element.getAttribute('aria-selected') === 'true') !== value) item.element.setAttribute('aria-selected', String(value));
+ }
+ };
+ function choose(id, event = {}) {
+ const previousAnchor = anchor;
+ const next = clickSelection(state.record, state.selection, id, {toggle: event.ctrlKey || event.metaKey, shift: event.shiftKey, anchor});
+ state.select(next); anchor = next?.ids.includes(id) ? id : next?.ids.includes(previousAnchor) ? previousAnchor : next?.ids.at(-1) ?? null;
+ }
+ function consume(event) { event.preventDefault(); event.stopImmediatePropagation(); }
+ // Q2: a box drawn with Ctrl or Cmd adds to the selection; otherwise it replaces it.
+ const adding = g => g.modifiers.ctrlKey || g.modifiers.metaKey;
+ function begin(event) {
+ if (event.button !== 0 || !event.isPrimary || gesture || event.target.closest('.fv-ed-ruler, .fv-ed-playhead-handle, .fv-ed-track-zoom, .fv-ed-clip-popover, .fv-ed-track-heads')) return false;
+ const hit = hitTest(event), p = point(event), id = hit.item?.clip.id;
+ if (id && lockedIds(state.record).has(id)) return false;
+ const inScroll = scroll.contains(event.target), bottom = Math.max(...[...rows.values()].map(row => row.top + row.height));
+ const below = inScroll && p.y > bottom;
+ const modified = event.ctrlKey || event.metaKey || event.shiftKey;
+ const ids = selectedIds(state.record, state.selection);
+ const group = id && ids.includes(id) && isMultiple(state.record, ids) && !hit.edge && !hit.neighbor;
+ if (id && !modified && !group) { anchor = id; return false; }
+ const box = !id && inScroll && (event.shiftKey || below);
+ if (!box && !(id && (modified || group))) return false;
+ consume(event); element.focus({preventScroll: true}); actions.gestureStart?.({selectionGesture: true});
+ gesture = {pointer: event.pointerId, record: state.record, previous: state.selection, start: p, x: event.clientX, y: event.clientY, moved: false,
+ type: box ? 'box' : modified ? 'click' : 'move', id, modifiers: {ctrlKey: event.ctrlKey, metaKey: event.metaKey, shiftKey: event.shiftKey}};
+ if (box) {
+ gesture.rectangles = [...clips].map(([id, item]) => ({id, left: pixels(item.clip.start), right: pixels(item.clip.start) + Math.max(2, pixels(item.clip.frames)), top: rows.get(item.track).top, bottom: rows.get(item.track).top + rows.get(item.track).height}));
+ // Preview lightweight outlines; changing selection attributes on
+ // hundreds of media subtrees would recalculate their SVG styles.
+ gesture.outlines = new Map(gesture.rectangles.map(rect => {
+ const node = document.createElement('div'); node.className = 'fv-ed-marquee-item'; node.hidden = true;
+ Object.assign(node.style, {left: `${rect.left}px`, top: `${rect.top}px`, width: `${rect.right - rect.left}px`, height: `${rect.bottom - rect.top}px`});
+ return [rect.id, node];
+ }));
+ outlines.replaceChildren(...gesture.outlines.values());
+ } else if (gesture.type === 'click') choose(id, gesture.modifiers);
+ else {
+ gesture.plan = prepareMove(state.record, ids); gesture.points = [0, state.playhead, ...model.snapPoints(state.record, ids)]; anchor = id;
+ // Move one layer per track, not hundreds of SVG waveforms. Existing
+ // clip nodes are reparented once and restored when the gesture ends.
+ gesture.layers = [];
+ for (const [track, row] of rows) {
+ const members = ids.map(id => clips.get(id)).filter(item => item.track === track);
+ if (!members.length) continue;
+ const node = document.createElement('div'); node.className = 'fv-ed-group-layer';
+ const children = [...row.element.children]; row.element.append(node);
+ members.forEach(item => node.append(item.element)); gesture.layers.push({node, row: row.element, children});
+ }
+ }
+ element.dataset.selectGesture = gesture.type; element.setPointerCapture(event.pointerId); return true;
+ }
+ function update(event) {
+ const g = gesture;
+ if (!g) return;
+ const p = point(event), bounds = element.getBoundingClientRect();
+ g.moved ||= Math.hypot(event.clientX - g.x, event.clientY - g.y) >= 4;
+ if (!g.moved || g.type === 'click') return;
+ if (g.type === 'box') {
+ const box = {left: Math.max(0, Math.min(g.start.x, p.x)), right: Math.max(g.start.x, p.x), top: Math.min(g.start.y, p.y), bottom: Math.max(g.start.y, p.y)};
+ Object.assign(marquee.style, {left: `${box.left}px`, top: `${box.top}px`, width: `${box.right - box.left}px`, height: `${box.bottom - box.top}px`}); marquee.hidden = false;
+ if (!g.previewing) { paint([]); g.previewing = true; outlines.hidden = false; }
+ const inside = rectangleSelection(g.record, g.rectangles, box)?.ids || [];
+ g.selected = adding(g) ? [...new Set([...selectedIds(g.record, g.previous), ...inside])] : inside;
+ const previewIds = new Set(g.selected);
+ for (const [id, node] of g.outlines) if (node.hidden === previewIds.has(id)) node.hidden = !previewIds.has(id);
+ } else {
+ const clip = clips.get(g.id).clip, desired = clip.start + Math.round((p.x - g.start.x) * model.FPS / state.zoom);
+ const points = [...g.points, ...[desired, desired + clip.frames].map(frame => Math.round(frame / (5 * model.FPS)) * 5 * model.FPS)];
+ const aligned = snap(Math.max(0, desired), points, state.zoom, {offsets: [0, clip.frames]});
+ const result = g.plan.preview(aligned.frame - clip.start); g.result = result;
+ if (result.code === 'busy') {
+ if (!g.warned) { g.warned = true; commands.report(new model.EditError('busy')); }
+ return;
+ }
+ guide.hidden = aligned.guide == null || result.delta !== aligned.frame - clip.start;
+ guide.style.left = `${pixels(aligned.guide ?? 0)}px`;
+ for (const layer of g.layers) layer.node.style.transform = `translateX(${pixels(result.delta)}px)`;
+ if (g.blocked !== !!result.code && (result.code || g.blocked)) for (const member of g.plan.members)
+ clips.get(member.id).element.classList.toggle('fv-ed-cannot-drop', !!result.code);
+ if (g.blocked !== !!result.code) element.dataset.selectBlocked = String(!!result.code);
+ g.blocked = !!result.code;
+ label.hidden = !!result.code;
+ label.textContent = result.code ? ''
+ : t(`${Math.round((g.plan.start + result.delta) / model.FPS)} – ${Math.round((g.plan.end + result.delta) / model.FPS)} seconds`, `${Math.round((g.plan.start + result.delta) / model.FPS)} – ${Math.round((g.plan.end + result.delta) / model.FPS)} 秒`);
+ label.style.left = `${Math.max(8, Math.min(bounds.width - 220, event.clientX - bounds.left + 14))}px`;
+ label.style.top = `${Math.max(26, Math.min(bounds.height - 32, event.clientY - bounds.top + 14))}px`; label.hidden = !!result.code;
+ }
+ }
+ function tick() {
+ raf = null;
+ if (!gesture || !lastEvent) return;
+ update(lastEvent);
+ if (gesture.moved && gesture.type !== 'click') {
+ const bounds = scroll.getBoundingClientRect(), x = lastEvent.clientX;
+ const speed = x < bounds.left + 28 ? -12 : x > bounds.right - 28 ? 12 : 0;
+ if (speed) { const before = scroll.scrollLeft; scroll.scrollLeft += speed; if (before !== scroll.scrollLeft) raf = requestAnimationFrame(tick); }
+ }
+ }
+ function finish(event, cancel = false) {
+ if (!gesture || (event && gesture.pointer !== event.pointerId)) return false;
+ if (event) consume(event);
+ if (!cancel && event) update(event);
+ const g = gesture; gesture = null; lastEvent = null; cancelAnimationFrame(raf); raf = null;
+ for (const layer of g.layers || []) { layer.children.forEach(node => layer.row.append(node)); layer.node.remove(); }
+ for (const item of clips.values()) if (item.element.className.includes('fv-ed-cannot-drop')) item.element.classList.remove('fv-ed-cannot-drop');
+ marquee.hidden = guide.hidden = label.hidden = outlines.hidden = true; outlines.replaceChildren(); delete element.dataset.selectGesture; delete element.dataset.selectBlocked;
+ if (element.hasPointerCapture(g.pointer)) element.releasePointerCapture(g.pointer);
+ try {
+ if (cancel) state.select(g.previous);
+ else if (g.type === 'box') { const ids = g.selected || (adding(g) ? selectedIds(g.record, g.previous) : []); state.select(selection(ids), {history: true}); anchor = ids.at(-1) ?? null; }
+ else if (g.type === 'move' && !g.moved) choose(g.id);
+ else if (g.type === 'move' && g.result && !g.result.code) state.apply(t('Move', '移动'), record => actionsModel.moveParts(record, g.plan.ids, {frames: g.result.delta, track: null}));
+ } catch (error) { commands.report(error); }
+ finally { paint(selectedIds(state.record, state.selection)); renderSelection(); actions.gestureEnd?.(); }
+ return true;
+ }
+ const stop = state.subscribe(event => {
+ if (gesture && (event.type === 'zoom' || (event.type === 'record' && state.record !== gesture.record))) finish(null, true);
+ if (event.type === 'selection' && state.selection?.kind !== 'clip') anchor = null;
+ });
+ return {begin, choose,
+ move(event) { if (!gesture) return false; if (gesture.pointer === event.pointerId) { consume(event); lastEvent = event; if (!raf) raf = requestAnimationFrame(tick); } return true; },
+ finish,
+ keyboard(event) {
+ if (gesture) { consume(event); if (event.key.toLowerCase() === 'escape') finish(null, true); return true; }
+ return commands.keyboard(event);
+ },
+ dispose() { finish(null, true); stop(); marquee.remove(); guide.remove(); label.remove(); outlines.remove(); },
+ };
+}
diff --git a/web/editor_state.js b/web/editor_state.js
new file mode 100644
index 0000000..d37e59b
--- /dev/null
+++ b/web/editor_state.js
@@ -0,0 +1,129 @@
+// One bounded history holds record edits and committed range gestures.
+// Generation results update record snapshots; ranges never change the record.
+import {parse, EditError, duration, linkedIds, find, copyName, planRange} from './editor_model.js';
+const freeze = value => {
+ if (value && typeof value === 'object') { Object.values(value).forEach(freeze); Object.freeze(value); }
+ return value;
+};
+const validFrame = value => Number.isSafeInteger(value) && value >= 0 && value <= 1e7;
+export function createEditorState(record, {limit = 200} = {}) {
+ if (!Number.isSafeInteger(limit) || limit < 0 || limit > 10000) throw new EditError('range');
+ let current = parse(record), selection = null, rangeDraft = null, playhead = 0, zoom = 12;
+ let maxSerial = current.serial;
+ const retainSerial = record => { maxSerial = Math.max(maxSerial, record.serial); return record.serial < maxSerial ? parse({...record, serial: maxSerial}) : record; };
+ let undo = [], redo = []; const listeners = new Set();
+ const remember = entry => { undo = limit ? [...undo, entry].slice(-limit) : []; redo = []; };
+ const selected = () => ({selection, rangeDraft});
+ const restore = value => { selection = value.selection; rangeDraft = value.rangeDraft; };
+ const emit = (type, label) => {
+ const event = Object.freeze({type, ...(label === undefined ? {} : {label})});
+ for (const listener of [...listeners]) listener(event);
+ };
+ function normalized(value, project = current) {
+ if (value === null) return null;
+ if (!value || typeof value !== 'object') throw new EditError('selection');
+ if (value.kind === 'clip') {
+ const available = new Set(project.tracks.flatMap(track => track.clips.map(clip => clip.id)));
+ if (!Array.isArray(value.ids) || !value.ids.length || value.ids.some(id => typeof id !== 'string' || !available.has(id))) throw new EditError('selection');
+ return freeze({kind: 'clip', ids: [...linkedIds(project, value.ids)]});
+ }
+ if (!['gap', 'range'].includes(value.kind) || !validFrame(value.start) || !validFrame(value.frames) || value.frames < 1 || !validFrame(value.start + value.frames)) throw new EditError('selection');
+ const tracks = value.kind === 'gap' ? [value.track] : value.tracks;
+ if (!Array.isArray(tracks) || !tracks.length || new Set(tracks).size !== tracks.length || tracks.some(id => !project.tracks.some(track => track.id === id))) throw new EditError('selection');
+ if (value.kind === 'range' && value.parts !== undefined && (!Array.isArray(value.parts) || !value.parts.length || value.parts.length > 500
+ || value.parts.some(count => !validFrame(count) || count < 48 || count % 24 !== 0)
+ || value.parts.reduce((sum, count) => sum + count, 0) !== value.frames)) throw new EditError('selection');
+ return freeze(value.kind === 'gap' ? {kind: 'gap', track: value.track, start: value.start, frames: value.frames}
+ : {kind: 'range', start: value.start, frames: value.frames, tracks: [...tracks], ...(value.parts === undefined ? {} : {parts: [...value.parts]})});
+ }
+ function reconcile() {
+ if (selection?.kind === 'clip') {
+ const ids = selection.ids.filter(id => find(current, id));
+ const value = ids.length ? normalized({kind: 'clip', ids}) : null;
+ if (JSON.stringify(selection) !== JSON.stringify(value)) { selection = value; emit('selection'); }
+ } else if (selection && (selection.kind === 'gap' ? !current.tracks.some(track => track.id === selection.track)
+ : selection.tracks.some(id => !current.tracks.some(track => track.id === id)))) { selection = null; emit('selection'); }
+ if (playhead > duration(current)) { playhead = duration(current); emit('playhead'); }
+ }
+ function travel(from, to, side) {
+ if (!from.length) return current;
+ const entry = from.pop();
+ to.push(entry.record ? {...entry, record: current} : entry);
+ if (entry.record) current = retainSerial(entry.record);
+ if (entry[side]) restore(entry[side]);
+ if (entry.record) emit('record', entry.label);
+ reconcile();
+ if (entry[side]) emit('selection', entry.label);
+ return current;
+ }
+ const session = {
+ get record() { return current; }, get selection() { return selection; }, get playhead() { return playhead; }, get zoom() { return zoom; },
+ // Text belongs to the range draft, not to a gesture: typing keeps its native undo.
+ get rangeText() { return selection?.kind === 'range' ? rangeDraft?.text ?? null : null; },
+ get canUndo() { return undo.length > 0; }, get canRedo() { return redo.length > 0; },
+ apply(label, change, {clearRange = false, checkpoint = false, selectionAfter, rangeText = null} = {}) {
+ const next = retainSerial(parse(change(current))); // Validate before touching history or UI state.
+ if (JSON.stringify(next) === JSON.stringify(current)) return current;
+ const cleared = clearRange && selection?.kind === 'range';
+ const selectionChanged = cleared || selectionAfter !== undefined;
+ const entry = {record: current, label, ...(selectionChanged ? {before: selected(), after: {selection: normalized(selectionAfter ?? null, next), rangeDraft: selectionAfter?.kind === 'range' && typeof rangeText === 'string' ? {text: rangeText} : null}} : {})};
+ // Generation is a barrier: older full-record snapshots must not remove it.
+ if (checkpoint) { undo = []; redo = []; } else remember(entry);
+ if (selectionChanged) restore(entry.after);
+ current = next; emit('record', label); reconcile();
+ if (selectionChanged) emit('selection');
+ return current;
+ },
+ undo() { return travel(undo, redo, 'before'); },
+ redo() { return travel(redo, undo, 'after'); },
+ settle(change) {
+ const attempt = record => { try { return retainSerial(parse(change(record))); } catch (error) { if (error instanceof EditError) return record; throw error; } };
+ const update = entry => entry.record ? {...entry, record: attempt(entry.record)} : entry;
+ const next = retainSerial(parse(change(current))), nextUndo = undo.map(update), nextRedo = redo.map(update);
+ const changed = JSON.stringify(next) !== JSON.stringify(current);
+ current = next; undo = nextUndo; redo = nextRedo;
+ if (changed) { emit('record'); reconcile(); } return current;
+ },
+ replace(record) { const next = parse(record); maxSerial = next.serial; current = next; undo = []; redo = []; selection = null; rangeDraft = null; playhead = 0; emit('record'); emit('selection'); emit('playhead'); return current; },
+ restoreView(value) {
+ // View drafts are untrusted and may refer to content changed elsewhere.
+ let next = null;
+ try {
+ next = normalized(value?.selection ?? null);
+ if (next && next.kind !== 'clip') {
+ const tracks = next.kind === 'gap' ? [next.track] : next.tracks;
+ if (current.tracks.some(track => (next.kind === 'range' || tracks.includes(track.id)) && track.clips.some(clip =>
+ clip.start < next.start + next.frames && clip.start + clip.frames > next.start))) {
+ if (next.kind === 'gap') next = null;
+ else planRange(current, next); // Validate an existing-content range without applying it.
+ }
+ }
+ } catch { next = null; }
+ session.select(next);
+ if (validFrame(value?.playhead)) session.seek(value.playhead);
+ if (typeof value?.zoom === 'number' && Number.isFinite(value.zoom) && value.zoom > 0) session.setZoom(value.zoom);
+ },
+ adopt({id, revision, nameSuffix}) {
+ const stamp = record => parse({...record, id, revision, ...(nameSuffix ? {name: copyName(record.name, nameSuffix)} : {})});
+ const update = entry => entry.record ? {...entry, record: stamp(entry.record)} : entry;
+ const next = stamp(current), nextUndo = undo.map(update), nextRedo = redo.map(update);
+ current = next; undo = nextUndo; redo = nextRedo; emit('record'); return current;
+ },
+ // A pasted range brings its own description (text); otherwise a range keeps the one being typed.
+ select(value, {history = false, text} = {}) {
+ const next = normalized(value);
+ if (JSON.stringify(next) !== JSON.stringify(selection) || (next?.kind === 'range' && typeof text === 'string')) {
+ const before = selected(), after = {selection: next, rangeDraft: next?.kind === 'range'
+ ? typeof text === 'string' ? {text} : selection?.kind === 'range' ? rangeDraft : {text: null} : null};
+ if (history && (selection?.kind === 'range' || next?.kind === 'range')) remember({before, after});
+ restore(after); emit('selection');
+ }
+ return selection;
+ },
+ setRangeText(value) { if (typeof value !== 'string') throw new EditError('text'); if (selection?.kind === 'range') rangeDraft.text = value; },
+ seek(frame) { if (!validFrame(frame)) throw new EditError('range'); const next = Math.min(frame, Math.max(duration(current), selection?.kind === 'range' ? selection.start + selection.frames : 0)); if (next !== playhead) { playhead = next; emit('playhead'); } return playhead; },
+ setZoom(value) { if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) throw new EditError('range'); if (value !== zoom) { zoom = value; emit('zoom'); } return zoom; },
+ subscribe(listener) { if (typeof listener !== 'function') throw new EditError('listener'); listeners.add(listener); return () => listeners.delete(listener); },
+ };
+ return Object.freeze(session);
+}
diff --git a/web/editor_store.js b/web/editor_store.js
new file mode 100644
index 0000000..28d057b
--- /dev/null
+++ b/web/editor_store.js
@@ -0,0 +1,475 @@
+import {copyName} from './editor_model.js';
+import {generationSize} from './editor_generation.js';
+// HTTP and scheduling live here; records and editing stay in the data modules.
+const clockDefault = {now: () => Date.now(), setTimeout: (fn, ms) => setTimeout(fn, ms), clearTimeout: id => clearTimeout(id)};
+const copy = value => structuredClone(value);
+const memoryProjects = new Map();
+const fakeJobs = new Map();
+const fakeSources = new Map();
+const errorFor = response => Object.assign(new Error('editor_request'), {status: response.status});
+const post = value => ({method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(value)});
+export const sourceKey = source => source ? `${source.kind}:${source.id}` : null;
+export const chainRoute = (id, action) => '/freevideo/chain' + (id ? '/' + encodeURIComponent(id) : '') + (action ? '/' + action : '');
+
+// Debounce from the first edit, rather than postponing indefinitely while dragging.
+// Writes are serialized; a response supplies metadata to the next snapshot only.
+const savedContent = record => JSON.stringify({...record, id: null, revision: 0});
+const OUTBOX = 'fv-editor-outbox';
+const operationId = () => globalThis.crypto?.randomUUID?.().replaceAll('-', '') || Array.from({length: 32}, () => Math.floor(Math.random() * 16).toString(16)).join('');
+const lockName = session => OUTBOX + ':' + session;
+function holdSession(session = operationId()) {
+ let release = () => {}; const owner = {session, held: !globalThis.navigator?.locks};
+ let ready = Promise.resolve();
+ if (globalThis.navigator?.locks) {
+ ready = new Promise(resolve => {
+ navigator.locks.request(lockName(session), () => { owner.held = true; resolve(); return new Promise(done => { release = done; }); });
+ });
+ }
+ return Object.assign(owner, {ready, dispose: () => ready.then(() => release())});
+}
+function outbox() {
+ const rows = [];
+ try {
+ for (let i = 0; i < localStorage.length; i++) {
+ const key = localStorage.key(i);
+ if (!key?.startsWith(OUTBOX + ':')) continue;
+ try { const entry = JSON.parse(localStorage.getItem(key)); if (entry?.session && entry.project) rows.push([key, entry]); } catch {}
+ }
+ // Preserve pending records written by the previous page version.
+ const legacy = JSON.parse(localStorage.getItem(OUTBOX) || '{}');
+ for (const [key, entry] of Object.entries(legacy)) if (entry?.project) rows.push([key, {...entry, legacy: true}]);
+ } catch {}
+ return rows;
+}
+function saveOutbox(session, entry) {
+ if (typeof localStorage === 'undefined') return false;
+ try {
+ if (entry) {
+ if (new TextEncoder().encode(JSON.stringify(entry.project)).length > 2 * 1024 * 1024) {
+ console.info('[FreeVideo editor] Record exceeds 2 MB; outbox skipped.'); return false;
+ }
+ localStorage.setItem(lockName(session), JSON.stringify(entry));
+ } else localStorage.removeItem(lockName(session));
+ return true;
+ } catch { console.info('[FreeVideo editor] Local outbox unavailable.'); return false; }
+}
+export function createSaveQueue({write, read, onSaved = () => {}, onConflict = () => {}, onCopied = () => {},
+ onMemory = () => {}, onError = () => {}, onStatus = () => {}, clock = clockDefault, delay = 600,
+ initial = null, getRecord = null, copySuffix = ' (copy)', session = null, create = null, attempt: resumedAttempt = null}) {
+ const owner = session || holdSession();
+ let pending = null, inFlight = null, timer = null, heartbeat = null, meta = null, retry = 0, disposed = false;
+ let memory = false, memoryNoticed = false, lastSaved = initial && copy(initial), failed = false, copied = false, retained = false;
+ let createOperation = create || (initial?.id ? null : operationId());
+ let attempt = resumedAttempt && copy(resumedAttempt);
+ const localKey = owner.session;
+ function retain(record) {
+ if (!owner.held) { owner.ready.then(() => { if (!disposed && (pending || attempt || inFlight)) retain({...((getRecord?.() || pending) ?? record), ...(meta || {})}); }); return false; }
+ retained = saveOutbox(localKey, {session: localKey, id: record.id, project: copy(record), baseline: lastSaved, create: createOperation, attempt: copy(attempt), updated_at: clock.now()});
+ if (heartbeat === null && !disposed) heartbeat = clock.setTimeout(() => {
+ heartbeat = null;
+ if (pending || attempt || inFlight) retain({...((getRecord?.() || pending) ?? record), ...(meta || {})});
+ }, 10000);
+ return retained;
+ }
+ function schedule(ms) {
+ if (disposed || timer !== null) return;
+ timer = clock.setTimeout(() => { timer = null; drain(); }, ms);
+ }
+ async function drain() {
+ if (disposed || inFlight || (!pending && !attempt)) return inFlight;
+ if (!attempt) { attempt = {operation: operationId(), project: {...pending, ...(meta || {})}}; pending = null; }
+ const sent = attempt.project, body = copy(sent); failed = false;
+ if (!body.id) createOperation ||= operationId();
+ retain(pending || body);
+ inFlight = (async () => {
+ await owner.ready;
+ try {
+ if (disposed) return;
+ if (memory) { attempt = null; onSaved(body, true, localKey); return; }
+ const response = await write(body, createOperation, attempt.operation);
+ if (disposed) return;
+ if (response.status === 404) {
+ attempt = null; memory = true;
+ if (!memoryNoticed) { memoryNoticed = true; onMemory(); }
+ onSaved(body, true, localKey); return;
+ }
+ if (response.status === 409) {
+ const conflict = await response.json();
+ const remote = await read(body.id || conflict.id);
+ if (disposed) return;
+ if (!remote) throw errorFor(response);
+ const latest = copy(getRecord?.() || pending || sent);
+ if (lastSaved && savedContent(remote) === savedContent(lastSaved)) {
+ meta = {id: remote.id, revision: remote.revision};
+ } else {
+ meta = {id: null, revision: 0}; createOperation = operationId();
+ latest.name = copyName(latest.name, copySuffix);
+ onConflict({...latest, ...meta}, copySuffix);
+ copied = true;
+ }
+ attempt = null; pending = {...latest, ...meta}; retain(pending); retry = 0; return;
+ }
+ if (!response.ok) throw errorFor(response);
+ const saved = (await response.json()).project;
+ if (disposed) return;
+ attempt = null;
+ if (pending && savedContent(pending) === savedContent(sent)) pending = null;
+ meta = {id: saved.id, revision: saved.revision}; retry = 0; lastSaved = copy(saved);
+ onSaved(saved, false);
+ if (copied) { copied = false; onCopied(saved); }
+ if (pending) retain({...pending, ...meta});
+ else { saveOutbox(localKey, null); retained = false; clock.clearTimeout(heartbeat); heartbeat = null; }
+ } catch (error) {
+ failed = true;
+ if (!disposed) {
+ retain({...(pending || sent), ...(meta || {})});
+ schedule(Math.min(30000, 1000 * 2 ** retry++)); onError(error);
+ }
+ }
+ })().finally(() => {
+ inFlight = null; onStatus();
+ if ((pending || attempt) && timer === null && !disposed && !failed) drain();
+ });
+ return inFlight;
+ }
+ return {
+ enqueue(record) { if (!disposed) { pending = copy(record); if (!record.id) createOperation ||= operationId(); retain({...pending, ...(meta || {})}); schedule(delay); } },
+ async flush() {
+ clock.clearTimeout(timer); timer = null;
+ if (inFlight) await inFlight;
+ clock.clearTimeout(timer); timer = null;
+ while ((pending || attempt) && !disposed) {
+ await drain();
+ if (failed) break;
+ if (inFlight) await inFlight;
+ clock.clearTimeout(timer); timer = null;
+ }
+ },
+ reset(record = null, recovery = null) {
+ pending = recovery ? copy(recovery.project) : null; attempt = recovery?.attempt ? copy(recovery.attempt) : null;
+ meta = null; retry = 0; copied = false; retained = false; lastSaved = copy(recovery ? recovery.baseline : record);
+ createOperation = recovery?.create || (record?.id ? null : operationId());
+ clock.clearTimeout(timer); timer = null; clock.clearTimeout(heartbeat); heartbeat = null;
+ if (pending || attempt) { retain(pending || attempt.project); schedule(delay); } else saveOutbox(localKey, null);
+ },
+ get recovery() { return {project: copy({...(pending || attempt?.project), ...(meta || {})}), baseline: copy(lastSaved), create: createOperation, attempt: copy(attempt)}; },
+ dispose({discard = false} = {}) { disposed = true; clock.clearTimeout(timer); timer = null; clock.clearTimeout(heartbeat); heartbeat = null; if (discard) saveOutbox(localKey, null); if (!session) owner.dispose(); },
+ get dirty() { return !!pending || !!attempt || !!inFlight; },
+ get locallyRetained() { return retained; },
+ };
+}
+
+// No overlapping polls and no delivery after disposal, including a slow response.
+export function createPoller(read, deliver, {clock = clockDefault, interval = 2000, onError = () => {}} = {}) {
+ let active = true, timer = null, running = null;
+ async function poll() {
+ if (!active || running) return running;
+ running = (async () => {
+ try { const value = await read(); if (active && await deliver(value) === false) active = false; }
+ catch (error) { if (active) onError(error); }
+ })().finally(() => {
+ running = null;
+ if (active) timer = clock.setTimeout(() => { timer = null; poll(); }, interval);
+ });
+ return running;
+ }
+ poll();
+ return {poll, dispose() { active = false; clock.clearTimeout(timer); }};
+}
+
+export function interpolate(points, seconds) {
+ const rows = points.filter(([x, y]) => Number.isFinite(x) && Number.isFinite(y) && y >= 0).sort((a, b) => a[0] - b[0]);
+ if (!rows.length) return null;
+ if (rows.length === 1) return rows[0][1];
+ let i = rows.findIndex(([x]) => x >= seconds);
+ if (i < 1) i = seconds <= rows[0][0] ? 1 : rows.length - 1;
+ const [a, b] = [rows[i - 1], rows[i]];
+ return b[0] === a[0] ? b[1] : Math.max(0, a[1] + (seconds - a[0]) * (b[1] - a[1]) / (b[0] - a[0]));
+}
+// The reply groups its numbers by quality level. An edit keeps the panel's steps,
+// not a level's name, so the level is the one those steps describe (as the
+// creative panel's range view picks it); other steps have no numbers.
+function capabilityTier(reply, settings) {
+ const tiers = reply.tiers;
+ if (!tiers || typeof tiers !== 'object') return reply;
+ if (tiers[settings?.tier]) return tiers[settings.tier];
+ const steps = Number(settings?.base_steps), twoPass = !!settings?.two_pass;
+ return Object.values(tiers).find(tier => tier.steps === steps && tier.two_pass === twoPass
+ && (!twoPass || Number(settings?.refine_steps) === 3)) || {};
+}
+export function capabilityPoints(reply, {width, height, settings = {}}) {
+ const tier = capabilityTier(reply, settings);
+ const i = reply.sizes?.findIndex(size => size.width === width && size.height === height) ?? -1;
+ const max = Array.isArray(tier.max_seconds) ? tier.max_seconds[i] : tier.max_seconds;
+ const known = Array.isArray(tier.max_frames) ? tier.max_frames[i] : tier.max_frames;
+ const maxRequestFrames = Number.isSafeInteger(known) && known >= 0 ? known
+ : Number.isFinite(max) ? Math.max(39, 5 + 17 * Math.ceil((24 * max - 5) / 17)) : null;
+ const longest = continues => {
+ if (maxRequestFrames === null) return 15;
+ for (let seconds = 30; seconds >= 2; seconds--) {
+ const frames = continues ? 17 * Math.ceil(seconds * 24 / 17) + 22 : Math.max(39, 5 + 17 * Math.ceil((seconds * 24 - 5) / 17));
+ if (frames <= maxRequestFrames) return seconds;
+ }
+ return 2; // The final request check reports too_long when even 2s cannot fit.
+ };
+ const estimates = i >= 0 && Array.isArray(tier.estimate_seconds?.[i]) ? tier.estimate_seconds[i] : tier.estimate_seconds;
+ const lengths = reply.lengths || reply.seconds || [5, 10, 15];
+ return {maxSeconds: longest(false), maxFollowSeconds: longest(true), maxRequestFrames,
+ points: lengths.map((length, j) => [Number(length.seconds ?? length),
+ Array.isArray(estimates) ? estimates[j] : estimates?.[length.seconds ?? length]])};
+}
+export function mediaURL(api, value) {
+ if (!value) return null;
+ if (/^(?:https?:|blob:|data:|\/)/.test(value)) return api.apiURL?.(value) || value;
+ const i = value.lastIndexOf('/');
+ const path = '/view?' + new URLSearchParams({filename: value.slice(i + 1), subfolder: value.slice(0, Math.max(0, i)), type: 'output'});
+ return api.apiURL?.(path) || path;
+}
+
+export function createEditorStore(api, {t = en => en, notify = () => {}, clock = clockDefault, pollMs = 2000} = {}) {
+ const sources = new Map(), sourceReads = new Map(), watchers = new Set(), pollers = new Set(), once = new Set();
+ let recovered = null, capabilityPoll = null;
+ let disposed = false; const uploads = new Set();
+ const session = holdSession();
+ const notice = (key, en, zh) => { if (!once.has(key)) { once.add(key); notify(t(en, zh)); } };
+ const request = (path, options) => api.fetchApi(path, options);
+ async function json(path, options, fallback = null) {
+ const response = await request(path, options);
+ if (response.status === 404) return fallback;
+ if (!response.ok) throw errorFor(response);
+ return response.json();
+ }
+ function cache(values) {
+ for (const [key, value] of Object.entries(values || {})) sources.set(key, value);
+ if (!disposed) for (const fn of watchers) fn();
+ }
+ async function load(query) {
+ // Finish the retained edit before allowing a different project to replace it.
+ if (recovered) return copy(recovered.project);
+ const value = await json('/freevideo/editor/project?' + new URLSearchParams(query));
+ if (value?.project) { cache(value.sources); return value.project; }
+ if (query.id) return copy(memoryProjects.get(query.id) || (query.id === 'memory' ? memoryProjects.get('memory') : null));
+ return copy([...memoryProjects.values()].find(record => record.tracks[0].clips[0]?.source?.id === query.work) || null);
+ }
+ function watch(read, deliver) {
+ const poller = createPoller(read, deliver, {clock, interval: pollMs}); pollers.add(poller);
+ return () => { poller.dispose(); pollers.delete(poller); };
+ }
+ function fakeEnabled() { try { return localStorage.getItem('fv-editor-fake') === '1'; } catch { return false; } }
+ function persistFake(job) {
+ fakeJobs.set(job.id, copy(job));
+ try { localStorage.setItem('fv-editor-job:' + job.id, JSON.stringify(job)); } catch {}
+ }
+ function fakeJob(id) {
+ if (fakeJobs.has(id)) return fakeJobs.get(id);
+ try { const value = JSON.parse(localStorage.getItem('fv-editor-job:' + id)); if (value) fakeJobs.set(id, value); return value; } catch { return null; }
+ }
+ function fakeState(id) {
+ const job = fakeJob(id); if (!job) return null;
+ let elapsed = job.elapsed + (job.active ? clock.now() - job.started : 0);
+ let failed = false;
+ const blocks = job.blocks.map(block => {
+ const fraction = Math.max(0, Math.min(1, elapsed / 4000)); elapsed -= 4000;
+ const material = job.materials.find(row => (row.geometry?.frames || row.frames || 0) >= block.frames);
+ let state = fraction === 1 ? 'done' : fraction > 0 ? 'running' : 'pending';
+ if (failed || (!job.active && state !== 'done')) state = 'cancelled';
+ const error = !material ? 'no_material' : block.text.startsWith('!fail') ? 'gpu_memory' : null;
+ if (error && fraction > 0 && !failed) { state = 'failed'; failed = true; }
+ const output = state === 'done' ? material?.video : null;
+ if (output) {
+ const metadata = {...material.geometry, _fallback: true, video: mediaURL(api, output), audio: mediaURL(api, output),
+ path: output, has_video: true, has_audio: true, sample_rate: 32000, missing: false,
+ thumbnail: api.apiURL?.('/freevideo/library/thumbnail?' + new URLSearchParams({id: material.id}))};
+ fakeSources.set('generated:' + output, metadata); sources.set('generated:' + output, metadata);
+ }
+ return {...block, state, fraction: state === 'done' ? 1 : fraction, inputs: {frames: block.frames}, output,
+ skip_frames: block.after ? 22 : 0, skip_audio_samples: block.after ? 29333 : 0,
+ remaining_seconds: Math.ceil((1 - fraction) * 4), error};
+ });
+ return {id, state: failed ? 'failed' : blocks.every(b => b.state === 'done') ? 'done' : job.active ? 'running' : 'cancelled', blocks};
+ }
+ async function startFake(payload) {
+ const rows = await json('/freevideo/library?limit=48', undefined, {items: []});
+ const id = 'fake-' + (globalThis.crypto?.randomUUID?.() || clock.now() + '-' + Math.random());
+ persistFake({id, blocks: copy(payload.blocks), materials: rows.items || [], elapsed: 0, started: clock.now(), active: true});
+ return fakeState(id);
+ }
+ const store = {
+ sources, cache,
+ async recoverOutbox() {
+ await session.ready;
+ for (const [key, entry] of outbox()) {
+ if (entry.session === session.session) continue;
+ const recover = async () => {
+ // Re-read after claiming; another recovering page may have finished.
+ if (!entry.legacy && localStorage.getItem(key) !== JSON.stringify(entry)) return;
+ const q = createSaveQueue({clock, initial: entry.baseline, create: entry.create, attempt: entry.attempt,
+ session: {session: entry.session || operationId(), held: true, ready: Promise.resolve()},
+ copySuffix: t(' (copy)', '(副本)'), read: id => store.load(id),
+ write: (record, create, operation) => request('/freevideo/editor/project', post({project: record, operation, ...(create ? {create} : {})})),
+ onSaved: (record, memory, local) => { if (memory) memoryProjects.set(local, copy(record)); try { localStorage.setItem('fv-editor-last', record.id || local); } catch {} },
+ onCopied: () => notice('conflict', 'This edit changed elsewhere. Your changes here were saved as a copy.', '这条剪辑在别处改过,这里的改动已存为副本')});
+ try {
+ q.enqueue(entry.project); await q.flush();
+ if (q.dirty) {
+ // Transfer the unresolved request and latest edit to this live
+ // session before releasing the abandoned session's lock.
+ const value = {...q.recovery, session: session.session, updated_at: clock.now()};
+ if (!saveOutbox(session.session, value)) return;
+ recovered = value;
+ if (!entry.legacy) localStorage.removeItem(key);
+ try { localStorage.setItem('fv-editor-last', value.project.id || session.session); } catch {}
+ }
+ if (entry.legacy && (!q.dirty || recovered)) {
+ const rows = JSON.parse(localStorage.getItem(OUTBOX) || '{}');
+ if (JSON.stringify(rows[key]) === JSON.stringify({...entry, legacy: undefined})) { delete rows[key]; localStorage.setItem(OUTBOX, JSON.stringify(rows)); }
+ }
+ } finally { q.dispose(); }
+ };
+ if (globalThis.navigator?.locks && entry.session) {
+ await navigator.locks.request(lockName(entry.session), {ifAvailable: true}, lock => lock ? recover() : undefined);
+ } else if (clock.now() - (entry.updated_at || 0) > 60000) await recover();
+ if (recovered) break;
+ }
+ }, load: id => load({id}), byWork: work => load({work}),
+ async projects() {
+ const value = await json('/freevideo/editor/projects', undefined, {items: []});
+ return value.items || [];
+ },
+ createSaveQueue(state, {onStatus = () => {}} = {}) {
+ const queue = createSaveQueue({clock, session, onStatus, initial: state.record, getRecord: () => state.record, copySuffix: t(' (copy)', '(副本)'), write: (record, create, operation) => { const options = post({project: record, operation, ...(create ? {create} : {})}); return request('/freevideo/editor/project', {...options, keepalive: new TextEncoder().encode(options.body).length < 60000}); },
+ read: id => store.load(id),
+ onSaved: (record, memory, local) => {
+ memoryProjects.set(record.id || local, copy({...state.record, id: record.id, revision: record.revision}));
+ state.adopt({id: record.id, revision: record.revision});
+ try { localStorage.setItem('fv-editor-last', record.id || local); } catch {}
+ if (memory) memoryProjects.set(record.id || local, copy(state.record));
+ },
+ onConflict: (record, nameSuffix) => { state.adopt({id: null, revision: 0, nameSuffix}); },
+ onCopied: () => notice('conflict', 'This edit changed elsewhere. Your changes here were saved as a copy.', '这条剪辑在别处改过,这里的改动已存为副本'),
+ onMemory: () => notice('memory', 'Changes are kept in this page. Restart after updating to save them to disk.', '改动暂存在这个页面里,更新后重启即可保存到磁盘。'),
+ // Automatic retries stay quiet; switching away while unsaved warns in editor.js.
+ onError: () => {}});
+ const reset = queue.reset;
+ queue.reset = record => { const entry = recovered; recovered = null; reset(record, entry); };
+ return queue;
+ },
+ async getSources(keys, {refresh = false} = {}) {
+ const missing = [...new Set(keys)].filter(key => refresh || !sources.has(key) || sources.get(key)._fallback);
+ if (!missing.length) return sources;
+ const signature = missing.slice().sort().join('\n');
+ if (!sourceReads.has(signature)) {
+ const query = new URLSearchParams(); missing.forEach(key => query.append('key', key));
+ sourceReads.set(signature, (async () => {
+ const value = await json('/freevideo/editor/sources?' + query, undefined, {sources: {}});
+ cache(value.sources);
+ for (const key of missing) if (fakeSources.has(key) && (!sources.has(key) || sources.get(key).missing)) sources.set(key, fakeSources.get(key));
+ })().finally(() => sourceReads.delete(signature)));
+ }
+ await sourceReads.get(signature); return sources;
+ },
+ subscribeSources(fn) { watchers.add(fn); return () => watchers.delete(fn); },
+ async waveform(key, points = 200) {
+ return (await json('/freevideo/editor/waveform?' + new URLSearchParams({key, points}), undefined, {peaks: []})).peaks || [];
+ },
+ async works(before = null) {
+ const query = new URLSearchParams({limit: '24'}); if (before) query.set('before', before);
+ const value = await json('/freevideo/library?' + query, {cache: 'no-store'}, {items: [], next: null});
+ const fallback = {};
+ for (const row of value.items || []) if (row.video && row.id && !sources.has(`work:${row.id}`)) {
+ fallback[`work:${row.id}`] = {...row.geometry, _fallback: true, video: mediaURL(api, row.video), audio: mediaURL(api, row.video),
+ has_video: true, has_audio: row.has_audio !== false, path: row.video, missing: false,
+ thumbnail: api.apiURL?.('/freevideo/library/thumbnail?' + new URLSearchParams({id: row.id})) || '/freevideo/library/thumbnail?' + new URLSearchParams({id: row.id})};
+ }
+ if (Object.keys(fallback).length) cache(fallback);
+ return value;
+ },
+ async imports() { return (await json('/freevideo/editor/imports', undefined, {items: []})).items || []; },
+ watchImports(fn) { return watch(() => store.imports(), items => { fn(items); return true; }); },
+ upload(file, progress = () => {}) {
+ if (disposed) return Promise.reject(new Error('editor_closed'));
+ return new Promise((resolve, reject) => {
+ const xhr = new XMLHttpRequest();
+ const release = () => { uploads.delete(upload); xhr.onload = xhr.onerror = null; xhr.upload.onprogress = null; };
+ const upload = {xhr, release, reject}; uploads.add(upload);
+ xhr.open('POST', api.apiURL?.('/freevideo/editor/import') || '/freevideo/editor/import');
+ xhr.setRequestHeader('X-FreeVideo-Filename', encodeURIComponent(file.name));
+ xhr.setRequestHeader('Content-Type', 'application/octet-stream');
+ xhr.upload.onprogress = event => { if (event.lengthComputable) progress(event.loaded / event.total); };
+ xhr.onload = () => {
+ release();
+ if (xhr.status === 404) { notice('import', 'Import is unavailable until you restart after updating.', '更新后重启即可导入素材。'); resolve(null); return; }
+ if (xhr.status < 200 || xhr.status >= 300) { reject(errorFor(xhr)); return; }
+ try { resolve(JSON.parse(xhr.responseText).import); } catch (error) { reject(error); }
+ };
+ xhr.onerror = () => { release(); reject(new Error('import_failed')); };
+ try { xhr.send(file); } catch (error) { release(); reject(error); }
+ });
+ },
+ capabilities(options, onReady = () => {}) {
+ capabilityPoll?.dispose();
+ const size = generationSize(options);
+ const fallback = {maxSeconds: 15, maxFollowSeconds: 15, maxRequestFrames: null, estimate: () => null, generationSize: size};
+ if (disposed) return fallback;
+ const started = clock.now();
+ let active = true, timer = null;
+ const controller = new AbortController();
+ const poller = {dispose() {
+ active = false; clock.clearTimeout(timer); controller.abort(); pollers.delete(poller);
+ }};
+ capabilityPoll = poller; pollers.add(poller);
+ async function read() {
+ try {
+ const reply = await json('/freevideo/capabilities?' + new URLSearchParams(size), {signal: controller.signal});
+ if (!active || disposed) return;
+ if (reply?.status === 'computing') {
+ const seconds = Number(reply.retry_after_seconds);
+ const delay = clock.now() - started >= 60000 ? 10000
+ : Number.isFinite(seconds) && seconds > 0 ? Math.max(1000, Math.min(60000, seconds * 1000)) : 1000;
+ timer = clock.setTimeout(() => { timer = null; read(); }, delay);
+ return;
+ }
+ if (!reply || (reply.status && reply.status !== 'ready')) { poller.dispose(); return; }
+ // Advertised presets must not change the size we just asked
+ // about: both estimates and the final request use this size.
+ const value = capabilityPoints(reply, {...options, ...size});
+ const ready = {maxSeconds: value.maxSeconds, maxFollowSeconds: value.maxFollowSeconds, maxRequestFrames: value.maxRequestFrames,
+ sizes: reply.sizes, generationSize: size,
+ estimate: frames => interpolate(value.points, frames / 24)};
+ onReady(ready); poller.dispose();
+ } catch { if (active) poller.dispose(); }
+ }
+ // The first HTTP response can itself be slow. Editing starts with
+ // these limits; only the callback publishes a measured capability.
+ read(); return fallback;
+ },
+ async startChain(payload) {
+ if (fakeEnabled()) return startFake(payload);
+ const value = await json(chainRoute(), post(payload));
+ if (!value) { console.info('[FreeVideo editor] Chain endpoint absent; using the local fake generator.'); return startFake(payload); }
+ return value.chain;
+ },
+ async chain(id) { return id.startsWith('fake-') ? fakeState(id) : (await json(chainRoute(id)))?.chain || null; },
+ watchChain(id, fn) { return watch(() => store.chain(id), fn); },
+ async chainAction(id, action) {
+ if (id.startsWith('fake-')) {
+ const job = fakeJob(id); if (!job) return null;
+ if (action === 'cancel' && job.active) { job.elapsed += clock.now() - job.started; job.active = false; }
+ if (action === 'resume' && !job.active) { job.started = clock.now(); job.active = true; }
+ persistFake(job); return fakeState(id);
+ }
+ const payload = action === 'resume' && api.clientId ? {client_id: api.clientId} : {};
+ return (await json(chainRoute(id, action), post(payload)))?.chain || null;
+ },
+ async export(id, revision, options) {
+ const value = await json('/freevideo/editor/export', post({id, revision, ...(options && Object.keys(options).length ? {options} : {})}));
+ if (!value) notice('export', 'Export is unavailable until you restart after updating.', '更新后重启即可导出。');
+ return value?.export || null;
+ },
+ watchExport(id, fn) { return watch(async () => (await json('/freevideo/editor/export?' + new URLSearchParams({id})))?.export || null, fn); },
+ cancelExport: id => json('/freevideo/editor/export/cancel', post({id})),
+ dispose() { disposed = true; session.dispose(); for (const poller of pollers) poller.dispose(); pollers.clear(); watchers.clear();
+ for (const upload of [...uploads]) { upload.release(); upload.xhr.abort(); upload.reject(new Error('editor_closed')); } },
+ };
+ return store;
+}
diff --git a/web/editor_text.css b/web/editor_text.css
new file mode 100644
index 0000000..c978544
--- /dev/null
+++ b/web/editor_text.css
@@ -0,0 +1,46 @@
+.fv-ed-text-canvas{position:absolute;inset:0;width:100%;height:100%;pointer-events:none;z-index:1}
+.fv-ed-picture[data-text-selected=true]>.fv-ed-crop-shade,.fv-ed-picture[data-text-selected=true]>.fv-ed-picture-tools{display:none}
+.fv-ed-text-handles{position:absolute;inset:0;pointer-events:none;z-index:4}
+.fv-ed-text-box{position:absolute;border:1px solid var(--fv-accent);pointer-events:auto;cursor:move;touch-action:none;min-width:8px;min-height:8px}
+.fv-ed-text-corner{position:absolute;width:7px;height:7px;background:var(--fv-accent);border:1px solid var(--fv-bg);pointer-events:auto}
+.fv-ed-text-corner[data-corner=tl]{left:-4px;top:-4px;cursor:nwse-resize}.fv-ed-text-corner[data-corner=tr]{right:-4px;top:-4px;cursor:nesw-resize}.fv-ed-text-corner[data-corner=bl]{left:-4px;bottom:-4px;cursor:nesw-resize}.fv-ed-text-corner[data-corner=br]{right:-4px;bottom:-4px;cursor:nwse-resize}
+.fv-ed-text-guide{position:absolute;background:var(--fv-accent);pointer-events:none}.fv-ed-text-guide.x{top:0;bottom:0;width:1px}.fv-ed-text-guide.y{left:0;right:0;height:1px}
+.fv-editor textarea.fv-ed-inline-text{position:absolute;pointer-events:auto;resize:none;min-height:48px;padding:6px;border:1px solid var(--fv-accent);border-radius:2px;background:rgba(0,0,0,.65);line-height:1.2;z-index:5}
+.fv-editor textarea.fv-ed-text-content{width:100%;resize:vertical;min-height:64px;font-size:13px;padding:6px;line-height:1.5}
+.fv-ed-text-colors{display:flex;flex-wrap:wrap;gap:4px;justify-content:flex-end}
+.fv-editor .fv-ed-text-colors button{height:20px;width:20px;padding:0;border-radius:3px;border:1px solid var(--fv-border)}
+.fv-editor .fv-ed-text-colors button.fv-ed-text-custom{width:auto;padding:0 5px;font-size:11px}
+.fv-editor .fv-ed-text-colors input{width:25px;height:22px;padding:0;border:0}
+.fv-editor .fv-ed-text-font{width:100%;max-width:166px;height:30px;background:var(--fv-card);color:var(--fv-ink);border:1px solid var(--fv-border);border-radius:4px}
+.fv-ed-text-warning{color:var(--fv-warning);font-size:12px;line-height:1.5;overflow-wrap:anywhere;margin:0}
+.fv-ed-subtitle-style-title{font-size:13px;font-weight:600}.fv-ed-adjust-controls hr{width:100%;border:0;border-top:1px solid var(--fv-border);margin:0}
+.fv-ed-text-label{padding:0 10px;display:flex;align-items:center;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-size:12px;line-height:32px;color:var(--fv-ink)}
+.fv-ed-clip[data-text-kind]{background:color-mix(in srgb,var(--fv-accent) 16%,var(--fv-card));border-color:color-mix(in srgb,var(--fv-accent) 35%,var(--fv-border))}
+.fv-ed-text-overflow{position:absolute;right:3px;top:2px;padding:1px 3px;border:1px solid var(--fv-warning);border-radius:3px;background:var(--fv-bg);color:var(--fv-warning);font-size:10px}
+.fv-ed-track-head[data-text-track=true]{padding-left:8px;padding-right:4px}.fv-ed-text-track-controls{margin-left:auto;display:flex;gap:2px}
+.fv-editor .fv-ed-text-track-controls button{padding:0;width:20px;height:22px;min-width:0;opacity:.5}.fv-editor .fv-ed-text-track-controls button[aria-pressed=true]{opacity:1;color:var(--fv-accent)}
+.fv-ed-track-row[data-hidden=true] .fv-ed-clip{opacity:.45}.fv-ed-track-row[data-locked=true] .fv-ed-clip{cursor:not-allowed}
+.fv-ed-track-row[data-locked=true]{background-image:repeating-linear-gradient(135deg,color-mix(in srgb,var(--fv-ink) 8%,transparent) 0 2px,transparent 2px 8px)}
+.fv-ed-clip[data-past=true]{-webkit-mask-image:linear-gradient(to right,#000 var(--fv-ed-past,0),rgb(0 0 0/.3) var(--fv-ed-past,0));mask-image:linear-gradient(to right,#000 var(--fv-ed-past,0),rgb(0 0 0/.3) var(--fv-ed-past,0))}
+.fv-editor .fv-ed-text-buttons{gap:4px}.fv-editor .fv-ed-text-buttons button{display:inline-flex;gap:5px;padding:0 7px;height:28px}.fv-ed-text-icon{font-size:11px;font-weight:700;opacity:.7}
+.fv-editor .fv-ed-text-notice{color:var(--fv-warning);background:none;border:0;height:auto;max-width:260px;font-size:11px;white-space:normal;text-align:left;line-height:1.4}
+.fv-ed-text-menu{position:absolute;z-index:20;min-width:230px;padding:4px;background:var(--fv-card);border:1px solid var(--fv-border);border-radius:6px;box-shadow:0 6px 30px #0008}
+.fv-editor .fv-ed-text-menu button{display:flex;justify-content:space-between;width:100%;height:32px;padding:4px 8px;border:0;background:none;text-align:left}.fv-ed-text-menu kbd{color:var(--fv-muted);margin-left:18px;font:11px inherit}
+.fv-ed-text-export-dialog{inset:0;margin:auto;max-width:480px;width:calc(100% - 40px);height:auto;padding:24px;border:1px solid var(--fv-border);border-radius:8px;background:var(--fv-bg);color:var(--fv-ink)}
+.fv-ed-text-export-dialog p{line-height:1.6;overflow-wrap:anywhere;color:var(--fv-warning)}
+.fv-editor[data-text-tracks="1"]{--fv-ed-tracks-min:220px}
+.fv-editor[data-text-tracks="2"]{--fv-ed-tracks-min:266px}
+.fv-editor[data-text-tracks="2"][data-text-audio2=true]{--fv-ed-tracks-min:312px}
+
+.fv-editor textarea.fv-ed-text-content{height:68px;min-height:68px}
+.fv-ed-adjust-pane[data-text-controls=true] .fv-ed-adjust-slider output{display:none}
+.fv-ed-adjust-pane[data-text-controls=true] .fv-ed-adjust-number{flex:0 0 62px}
+.fv-editor[data-text-tracks="1"] .fv-ed-track-view,.fv-editor[data-text-tracks="2"] .fv-ed-track-view{--fv-ed-head-width:148px}
+.fv-ed-track-head[data-text-track=true]>span:first-of-type{white-space:nowrap}
+.fv-ed-track-head[data-text-track=true]>svg{display:none}
+
+.fv-ed-text-notice{display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:2;overflow:hidden;cursor:pointer}
+@media(max-width:480px){
+ .fv-editor .fv-ed-toolbar>.fv-ed-text-buttons{grid-column:1/-1;grid-row:4;justify-self:start}
+ .fv-editor .fv-ed-toolbar>.fv-ed-adjust-toggle{grid-column:1/-1;grid-row:4;justify-self:end;width:auto}
+}
diff --git a/web/editor_text.js b/web/editor_text.js
new file mode 100644
index 0000000..6dfd39a
--- /dev/null
+++ b/web/editor_text.js
@@ -0,0 +1,278 @@
+// Text UI owns its controls, preview overlays and secondary menus. Timeline
+// editing remains in editor_tracks/model/select and the shared history.
+import * as model from './editor_model.js';
+import {FONT_KEYS} from './fonts.js';
+import {row, button, slider, number, segmented, toggle} from './editor_adjust.js';
+import {isText, isTextTrack, addText, changeText, changeSubtitleStyle, styleOf, activeText, setTextTrack, parseSRT, importSRT, defaults} from './editor_text_model.js';
+import {loadCoverage, loadTextFonts, textFontStack, missingGlyphs, missingHint, overTwoHint, textLayout, drawText} from './editor_text_layout.js';
+import {createSelectionActions, isTyping} from './editor_select.js';
+import {plan} from './editor_geometry.js';
+import {isolateDialogKeys} from './dialog_keys.js';
+const el=(tag,cls,text)=>{const e=document.createElement(tag);if(cls)e.className=cls;if(text!=null)e.textContent=text;return e;};
+const clamp=(v,lo,hi)=>Math.max(lo,Math.min(hi,v));
+export function createEditorText({element,state,t,actions,adjust,player,toolbar,exportBox,tracksHost}) {
+ const frame=player.element, canvas=el('canvas','fv-ed-text-canvas'), boundsLayer=el('div','fv-ed-text-handles');
+ canvas.setAttribute('aria-hidden','true'); frame.append(canvas,boundsLayer);
+ const ctx=canvas.getContext?.('2d'), measureCanvas=el('canvas'), metrics=measureCanvas.getContext?.('2d');
+ const buttons=el('div','fv-ed-tool-group fv-ed-text-buttons');
+ // Icons only on the toolbar; the name lives in the label and hover.
+ const textButton=button('',{onClick:()=>add('text')}), subtitleButton=button('',{onClick:()=>add('subtitle')});
+ textButton.classList.add('fv-ed-add-text'); subtitleButton.classList.add('fv-ed-add-subtitle');
+ textButton.append(el('span','fv-ed-text-icon','T')); subtitleButton.append(el('span','fv-ed-text-icon','CC'));
+ textButton.setAttribute('aria-label',t('Text','文字')); subtitleButton.setAttribute('aria-label',t('Subtitles','字幕'));
+ textButton.title=t('Text T','文字 T'); subtitleButton.title=t('Subtitles','字幕');
+ buttons.append(textButton,subtitleButton);
+ const marker=toolbar.querySelector('.fv-ed-marker, .fv-ed-add-marker');
+ if(marker) marker.after(buttons); else toolbar.insertBefore(buttons,toolbar.querySelector('.fv-ed-zoom'));
+ const notice=el('span');notice.setAttribute('role','button');notice.tabIndex=0;notice.onclick=()=>jumpMissing();notice.onkeydown=e=>{if(['Enter',' '].includes(e.key)){e.preventDefault();jumpMissing();}}; notice.classList.add('fv-ed-text-notice'); notice.hidden=true; exportBox.prepend(notice);
+ const menu=el('div','fv-ed-text-menu'); menu.hidden=true; menu.setAttribute('role','menu'); element.append(menu);
+ const names={sans:t('Sans','黑体'),serif:t('Serif','宋体'),kai:t('Kai','楷体'),mono:t('Mono','等宽')};
+ let disposed=false,ready=false,table=null,loadError=false,draft=null,lastStyle={},editing=null,drag=null,raf=null,layouts=new Map(),mapped={x:0,y:0,w:1,h:1};
+ const panels=new Map(), commands=createSelectionActions({state,t,actions});
+ const selected=()=>state.selection?.kind==='clip' && state.selection.ids.length===1 ? model.find(state.record,state.selection.ids[0]) : null;
+ const record=()=>draft?.record||state.record;
+ const selectedText=()=>{const c=selected();return isText(c)?c:null;};
+ // Refusals only flash red, as on the other tracks; anything else asks to try again.
+ const report=e=>actions.editError?.(e);
+ const locked=c=>state.record.tracks.some(row=>row.locked && row.clips.some(v=>v.id===c?.id));
+ function apply(label,change) { draft=null;try{state.apply(label,change);return true;}catch(e){report(e);render();return false;} }
+ function modifyStyle(changes,preview=false) {
+ const c=selectedText();if(!c)return;
+ const change=r=>c.text_kind==='subtitle' ? changeSubtitleStyle(r,changes) : changeText(r,c.id,{text_style:{...c.text_style,...changes}});
+ if(preview){try{draft={record:change(state.record),change};render();}catch(e){report(e);}return;}
+ if(apply(t('Style','样式'),change) && c.text_kind==='text') lastStyle={...styleOf(state.record,model.find(state.record,c.id))};
+ }
+ function updateContent(c,value,preview=false) {
+ const change=r=>changeText(r,c.id,{text:value});
+ if(preview){try{draft={record:change(state.record),change};render();updateWarnings();}catch(e){report(e);}return;}
+ apply(t('Content','内容'),change);
+ }
+ function commitDraft(){if(draft){const change=draft.change;apply(t('Text','文字'),change);const c=selectedText();if(c?.text_kind==='text')lastStyle={...styleOf(state.record,c)};}}
+ function add(kind,at=state.playhead){
+ commitDraft(); finishInline(); player.pause();
+ const text='';
+ let id;
+ if(!apply(kind==='text'?t('Text','文字'):t('Subtitles','字幕'),r=>{const next=addText(r,{kind,at,text,style:{...lastStyle,x:.5,y:.5}});id=`c${next.serial}`;return next;}))return;
+ state.select({kind:'clip',ids:[id]});state.seek(at);adjust.open();
+ if(kind==='text') startInline(id,true);
+ else {const content=panels.get(kind)?.content;content?.focus();content?.select();}
+ }
+ actions.addText=(kind,at)=>add(kind,at);
+ function buildPanel(host,kind){
+ host.closest('.fv-ed-adjust-pane').dataset.textControls='true';
+ const content=el('textarea','fv-ed-text-content');content.rows=3;content.maxLength=16000;content.setAttribute('aria-label',t('Content','内容'));
+ const warning=el('p','fv-ed-text-warning');warning.setAttribute('role','status');warning.hidden=true;
+ const overflow=el('p','fv-ed-text-warning');overflow.hidden=true;overflow.textContent=overTwoHint(t);
+ host.append(row(t('Content','内容'),content),warning,overflow);
+ const duration=number({min:1/24,max:1e7/24,step:1/24,label:t('Duration','时长'),onChange:v=>{const c=selectedText();if(c)apply(t('Duration','时长'),r=>changeText(r,c.id,{frames:Math.max(1,Math.round(v*24))}));}});
+ const durationRow=row(t('Duration','时长'),duration);
+ if(kind==='subtitle')host.append(durationRow,el('hr'),el('strong','fv-ed-subtitle-style-title',t('Style for all subtitles','全部字幕的样式')));
+ const font=el('select','fv-ed-text-font');font.setAttribute('aria-label',t('Font','字体'));
+ for(const key of FONT_KEYS){const option=el('option','',names[key]);option.value=key;option.style.fontFamily=textFontStack(key);font.append(option);}
+ font.onchange=()=>modifyStyle({font:font.value});host.append(row(t('Font','字体'),font));
+ const sizeNumber=number({min:16,max:200,step:1,label:t('Size','大小'),onChange:v=>modifyStyle({size:v/1080})});
+ const size=slider({min:16,max:200,value:kind==='text'?64:44,onInput:v=>{sizeNumber.value=Math.round(v);modifyStyle({size:v/1080},true);},onChange:v=>modifyStyle({size:v/1080})});
+ host.append(row(t('Size','大小'),size,sizeNumber));
+ const colors=el('div','fv-ed-text-colors');
+ for(const [color,en,zh] of [['#ffffff','White','白'],['#000000','Black','黑'],['#ffff00','Yellow','黄'],['#ff0000','Red','红'],['#0080ff','Blue','蓝'],['#00c853','Green','绿']]){
+ const swatch=button('',{onClick:()=>modifyStyle({color})});swatch.style.backgroundColor=color;swatch.title=t(en,zh);swatch.setAttribute('aria-label',t(en,zh));swatch.dataset.color=color;colors.append(swatch);
+ }
+ const custom=el('input');custom.type='color';custom.setAttribute('aria-label',t('Custom','自定'));custom.title=t('Custom','自定');custom.oninput=()=>modifyStyle({color:custom.value},true);custom.onchange=()=>modifyStyle({color:custom.value});
+ const customButton=button(t('Custom','自定'),{onClick:()=>custom.click()});customButton.classList.add('fv-ed-text-custom');custom.hidden=true;
+ colors.append(customButton,custom);host.append(row(t('Color','颜色'),colors));
+ const backing=segmented([['none','None','无'],['outline','Outline','描边'],['box','Box','底色']].map(([value,en,zh])=>({value,label:t(en,zh)})),{onChange:backing=>modifyStyle({backing})});
+ host.append(row(t('Backing','衬底'),backing));
+ let bold,align,fade;
+ if(kind==='text'){
+ bold=toggle(t('Bold','加粗'),{onChange:bold=>modifyStyle({bold})});host.append(bold);
+ align=segmented([['left','Left','左'],['center','Center','中'],['right','Right','右']].map(([value,en,zh])=>({value,label:t(en,zh)})),{onChange:align=>modifyStyle({align})});host.append(row(t('Align','对齐'),align));
+ }
+ const positions=kind==='text'?[[.15,'Top','上'],[.5,'Middle','中'],[.85,'Bottom','下']]:[['bottom','Bottom','下'],['top','Top','上']];
+ const position=segmented(positions.map(([value,en,zh])=>({value,label:t(en,zh)})),{onChange:value=>modifyStyle(kind==='text'?{x:.5,y:value}:{position:value,margin:.08})});host.append(row(t('Position','位置'),position));
+ if(kind==='text'){
+ host.append(durationRow);fade=toggle(t('Fade in and out','淡入淡出'),{onChange:fade=>modifyStyle({fade})});host.append(fade);
+ host.append(button(t('Reset style','恢复默认样式'),{onClick:()=>{const c=selectedText();if(c)apply(t('Reset style','恢复默认样式'),r=>changeText(r,c.id,{text_style:{}}));lastStyle={};}}));
+ }else{
+ 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));}};host.append(importButton,file);
+ }
+ content.oninput=()=>{const c=selectedText();if(c)updateContent(c,content.value,true);};content.onchange=commitDraft;
+ content.onkeydown=e=>{
+ e.stopPropagation();
+ if(e.key==='Escape'){e.preventDefault();commitDraft();content.blur();}
+ else if(kind==='subtitle' && e.key==='Enter' && !e.shiftKey && !e.isComposing){e.preventDefault();const c=selectedText();commitDraft();if(c)add('subtitle',c.start+c.frames);}
+ };
+ panels.set(kind,{content,warning,overflow,font,size,sizeNumber,custom,backing,bold,align,position,duration,fade,host});
+ updatePanel(kind);
+ }
+ function updatePanel(kind){
+ const p=panels.get(kind),c=selectedText();if(!p||!c||c.text_kind!==kind)return;
+ p.host.disabled=locked(c);
+ const s=styleOf(state.record,c);if(document.activeElement!==p.content)p.content.value=c.text;
+ p.font.value=s.font;p.font.style.fontFamily=textFontStack(s.font);
+ if(!draft){p.size.value=s.size*1080;p.sizeNumber.value=Math.round(s.size*1080);p.custom.value=s.color;}
+ p.backing.value=s.backing;p.position.value=kind==='text'?s.y:s.position;p.duration.value=c.frames/24;
+ if(p.bold){p.bold.value=s.bold;p.align.value=s.align;p.fade.value=s.fade;}
+ updateWarnings();
+ }
+ for(const kind of ['text','subtitle'])adjust.register(kind,{render:host=>buildPanel(host,kind),update:()=>updatePanel(kind)});
+ function projectMissing(r){
+ if(!table)return [];
+ return r.tracks.filter(track=>isTextTrack(track)&&!track.hidden).flatMap(track=>track.clips.map(c=>{const s=styleOf(r,c);return {id:c.id,chars:missingGlyphs(c.text,s.font,!!s.bold,table)};})).filter(v=>v.chars.length);
+ }
+ function updateWarnings(){
+ const r=record(),c=selectedText(),s=c&&styleOf(r,model.find(r,c.id));
+ const missing=projectMissing(r),chars=[...new Set(missing.flatMap(r=>r.chars))];
+ notice.hidden=!chars.length&&!loadError;notice.textContent=loadError?t('Text fonts could not be loaded','文字字体没能加载'):missingHint(chars,t);notice.title=notice.textContent;
+ for(const [kind,p]of panels){
+ if(c?.text_kind!==kind)continue;
+ const entry=model.find(r,c.id),absent=table?missingGlyphs(entry.text,s.font,!!s.bold,table):[];
+ p.warning.hidden=!absent.length&&!loadError;p.warning.textContent=loadError?t('Text fonts could not be loaded','文字字体没能加载'):missingHint(absent,t);
+ p.overflow.hidden=kind!=='subtitle'||!ready||!metrics||!textLayout(metrics,entry.text,s,kind,r.width,r.height).overTwo;
+ }
+ }
+ function jumpMissing(){const first=projectMissing(state.record)[0];if(first){const c=model.find(state.record,first.id);state.select({kind:'clip',ids:[c.id]});state.seek(c.start);adjust.open();}}
+ function updateClip(item,r){
+ const c=item.clip;item.media.hidden=false;item.media.textContent=c.text.replaceAll('\n',' ');item.media.classList.add('fv-ed-text-label');item.element.dataset.textKind=c.text_kind;
+ // Text after the picture and sound is not exported; that part is drawn faint.
+ const stop=model.exportFrames(r),past=Math.max(0,Math.min(c.frames,c.start+c.frames-stop));
+ if(past){item.element.dataset.past='true';item.element.style.setProperty('--fv-ed-past',`${(c.frames-past)/c.frames*100}%`);}else{delete item.element.dataset.past;item.element.style.removeProperty('--fv-ed-past');}
+ let badge=item.element.querySelector('.fv-ed-text-overflow');
+ const over=ready&&metrics&&c.text_kind==='subtitle'&&textLayout(metrics,c.text,styleOf(r,c),'subtitle',r.width,r.height).overTwo;
+ if(over&&!badge){badge=el('span','fv-ed-text-overflow','⚠\uFE0E');badge.setAttribute('aria-label',overTwoHint(t));item.element.append(badge);}
+ if(badge){badge.hidden=!over;badge.title=overTwoHint(t);}
+ item.element.title=over?overTwoHint(t):c.text;
+ }
+ actions.textClip=updateClip;
+ // Track switches stay out of undo (Q9); earlier snapshots get the same switch.
+ function switchTrack(id,flag){
+ const value=!state.record.tracks.find(v=>v.id===id)?.[flag];
+ try{state.settle(r=>setTextTrack(r,id,flag,value));}catch(e){report(e);render();}
+ }
+ actions.textTrack=(row,track)=>{
+ if(!isTextTrack(track))return;
+ row.element.dataset.hidden=String(!!track.hidden);row.element.dataset.locked=String(!!track.locked);row.head.dataset.textTrack='true';
+ let controls=row.head.querySelector('.fv-ed-text-track-controls');
+ if(!controls){controls=el('span','fv-ed-text-track-controls');for(const [flag,en,zh,glyph]of [['hidden','Hide','隐藏','◉'],['locked','Lock','锁定','▣']]){
+ const b=button(glyph,{onClick:()=>switchTrack(track.id,flag)});b.dataset.flag=flag;b.setAttribute('aria-label',t(en,zh));b.onpointerdown=e=>e.stopPropagation();controls.append(b);
+ }row.head.append(controls);}
+ for(const b of controls.children){b.setAttribute('aria-pressed',String(!!track[b.dataset.flag]));b.title=b.getAttribute('aria-label');}
+ };
+ function textEntries(){return activeText(record(),state.playhead);}
+ function frameMap(){
+ const r=record(),c=selectedText(),hasSelection=!!c;
+ const sw=Number(frame.style.getPropertyValue('--fv-ed-width'))||r.width,sh=Number(frame.style.getPropertyValue('--fv-ed-height'))||r.height;
+ if(hasSelection){frame.style.setProperty('--fv-ed-width',String(r.width));frame.style.setProperty('--fv-ed-height',String(r.height));return {x:0,y:0,w:r.width,h:r.height,cw:r.width,ch:r.height};}
+ const video=model.at(r,state.playhead).v1?.clip;
+ const scale=(video?.fit==='contain'?Math.max:Math.min)(sw/r.width,sh/r.height);
+ return {x:(sw-r.width*scale)/2,y:(sh-r.height*scale)/2,w:r.width*scale,h:r.height*scale,cw:sw,ch:sh};
+ }
+ function paintPicture(r){
+ ctx.fillStyle='#000';ctx.fillRect(0,0,r.width,r.height);
+ const video=frame.querySelector('video.fv-ed-visible');if(!video||video.readyState<2)return;
+ const clip=model.at(r,state.playhead).v1?.clip||{},w=video.videoWidth,h=video.videoHeight;if(!w||!h)return;
+ const p=plan(clip,w,h,r.width,r.height),background=plan({...clip,fit:'cover',scale:1.05,offset_x:0,offset_y:0},w,h,r.width,r.height);
+ ctx.save();ctx.filter=`blur(${Math.max(1,r.height*.025)}px)`;ctx.transform(...background.matrix);const b=background.crop;ctx.drawImage(video,b.x,b.y,b.width,b.height,b.x,b.y,b.width,b.height);ctx.restore();
+ ctx.save();ctx.transform(...p.matrix);const {x,y,width:cw,height:ch}=p.crop;ctx.drawImage(video,x,y,cw,ch,x,y,cw,ch);ctx.restore();
+ }
+ function render(){
+ if(disposed||!ctx)return;
+ const count=String(record().tracks.filter(isTextTrack).length),audio2=String(record().tracks.some(t=>t.id==='a2'));
+ if(element.dataset.textTracks!==count)element.dataset.textTracks=count;
+ if(element.dataset.textAudio2!==audio2)element.dataset.textAudio2=audio2;
+ if(!ready&&record().tracks.some(isTextTrack))ensureFonts();
+ const entries=textEntries(),c=selectedText(),r=record(),sourcePreview=frame.querySelector('.fv-ed-source-preview');
+ canvas.hidden=!ready||(!entries.length&&!c)||!!sourcePreview;
+ frame.dataset.textSelected=String(!!c&&!sourcePreview);
+ if(canvas.hidden){boundsLayer.replaceChildren();return;}
+ mapped=frameMap();const {x,y,w,h,cw,ch}=mapped;
+ if(canvas.width!==cw)canvas.width=cw;if(canvas.height!==ch)canvas.height=ch;ctx.clearRect(0,0,cw,ch);
+ if(c)paintPicture(r);
+ ctx.save();ctx.translate(x,y);ctx.scale(w/r.width,h/r.height);layouts=new Map();
+ for(const entry of entries){const l=entry.id===editing?.id ? textLayout(ctx,entry.text,entry.style,entry.text_kind,r.width,r.height) : drawText(ctx,entry,r.width,r.height);layouts.set(entry.id,l);}
+ ctx.restore();
+ if(editing && layouts.has(editing.id)){const [ix,iy,iw,ih]=layouts.get(editing.id).bounds;Object.assign(editing.input.style,{left:`${clamp((ix/r.width*100)-2,0,78)}%`,top:`${clamp(iy/r.height*100,0,80)}%`,width:`${Math.max(20,Math.min(90,iw/r.width*100+4))}%`,height:`${Math.max(18,ih/r.height*100+8)}%`});}
+ if(!editing&&!drag)renderBounds(c);
+ if(player.playing&&!raf)raf=requestAnimationFrame(()=>{raf=null;render();});
+ }
+ function renderBounds(c){
+ if(!c||player.playing||locked(c)||!layouts.has(c.id)){boundsLayer.replaceChildren();return;}
+ const r=record(),[x,y,w,h]=layouts.get(c.id).bounds;
+ let box=boundsLayer.querySelector('.fv-ed-text-box');
+ const fresh=!box||box.dataset.clip!==c.id;
+ if(fresh){boundsLayer.replaceChildren();box=el('div','fv-ed-text-box');box.dataset.clip=c.id;}
+ Object.assign(box.style,{left:`${x/r.width*100}%`,top:`${y/r.height*100}%`,width:`${Math.max(w,8)/r.width*100}%`,height:`${Math.max(h,8)/r.height*100}%`});
+ box.setAttribute('aria-label',t('Drag to move; double-click to edit','拖动移动,双击改内容'));box.onpointerdown=e=>beginDrag(e,c);
+ if(fresh&&c.text_kind==='text')for(const corner of ['tl','tr','bl','br']){const handle=el('span','fv-ed-text-corner');handle.dataset.corner=corner;box.append(handle);}
+ if(fresh)boundsLayer.append(box);
+ }
+ function startInline(id,selectAll=false){
+ if(!ready){ensureFonts().then(()=>{if(ready&&!disposed&&selectedText()?.id===id)startInline(id,selectAll);});return;}
+ finishInline();const c=model.find(state.record,id);if(!c||locked(c))return;player.pause();render();
+ const input=el('textarea','fv-ed-inline-text');input.value=c.text;input.rows=Math.max(2,c.text.split('\n').length);input.setAttribute('aria-label',t('Content','内容'));
+ const s=styleOf(state.record,c),r=state.record,[x,y,w,h]=layouts.get(id)?.bounds||[r.width*.25,r.height*.4,r.width*.5,r.height*.2];
+ Object.assign(input.style,{left:`${clamp(x/r.width*100,0,80)}%`,top:`${clamp(y/r.height*100,0,80)}%`,width:`${Math.max(20,Math.min(86,w/r.width*100+4))}%`,height:`${Math.max(18,h/r.height*100+8)}%`,fontFamily:textFontStack(s.font),fontSize:`${s.size*frame.getBoundingClientRect().height}px`,fontWeight:s.bold?'700':'400',textAlign:s.align,color:s.color});
+ editing={id,input};boundsLayer.replaceChildren(input);
+ input.oninput=()=>updateContent(c,input.value,true);
+ input.onkeydown=e=>{e.stopPropagation();if(e.key==='Escape'){e.preventDefault();finishInline();} };input.onkeyup=e=>e.stopPropagation();
+ input.onblur=()=>finishInline();render();input.focus();if(selectAll)input.select();
+ }
+ function finishInline(){if(!editing)return;const old=editing;editing=null;old.input.onblur=null;const c=model.find(state.record,old.id);if(c&&c.text!==old.input.value)updateContent(c,old.input.value);else commitDraft();old.input.remove();render();}
+ function guide(axis,value){const line=el('span','fv-ed-text-guide '+axis);line.style[axis==='x'?'left':'top']=`${value*100}%`;boundsLayer.append(line);}
+ function beginDrag(e,c){
+ if(e.button!==0||locked(c)||editing)return;e.preventDefault();e.stopPropagation();
+ const s=styleOf(state.record,c),rect=frame.getBoundingClientRect();drag={id:c.id,kind:c.text_kind,style:s,rect,x:e.clientX,y:e.clientY,corner:e.target.dataset.corner,pointer:e.pointerId};
+ boundsLayer.setPointerCapture(e.pointerId);actions.gestureStart?.();
+ }
+ boundsLayer.onpointermove=e=>{
+ if(!drag||drag.pointer!==e.pointerId)return;e.preventDefault();const d=drag,dx=(e.clientX-d.x)/d.rect.width,dy=(e.clientY-d.y)/d.rect.height;
+ boundsLayer.querySelectorAll('.fv-ed-text-guide').forEach(n=>n.remove());let change;
+ if(d.corner){const horizontal=dx*(d.corner.includes('r')?1:-1),vertical=dy*(d.corner.includes('b')?1:-1);change={size:clamp(d.style.size*(1+3*(Math.abs(horizontal)>Math.abs(vertical)?horizontal:vertical)),16/1080,200/1080)};}
+ else if(d.kind==='subtitle'){change={margin:clamp(d.style.margin+(d.style.position==='bottom'?-dy:dy),0,1)};}
+ else{change={x:clamp(d.style.x+dx,0,1),y:clamp(d.style.y+dy,0,1)};const l=layouts.get(d.id);for(const axis of ['x','y']){
+ const half=(l?.bounds[axis==='x'?2:3]||0)/(axis==='x'?state.record.width:state.record.height)/2;
+ for(const [target,line]of [[.5,.5],[.05+half,.05],[.95-half,.95]])if(Math.abs(change[axis]-target)*(axis==='x'?d.rect.width:d.rect.height)<6){change[axis]=target;guide(axis,line);break;}
+ }}
+ modifyStyle(change,true);
+ const box=boundsLayer.querySelector('.fv-ed-text-box'),l=layouts.get(d.id);if(box&&l){const [x,y,w,h]=l.bounds;Object.assign(box.style,{left:`${x/state.record.width*100}%`,top:`${y/state.record.height*100}%`,width:`${w/state.record.width*100}%`,height:`${h/state.record.height*100}%`});}
+ };
+ const endDrag=(e,cancel=false)=>{if(!drag)return;const d=drag;drag=null;if(boundsLayer.hasPointerCapture?.(d.pointer))boundsLayer.releasePointerCapture(d.pointer);if(cancel)draft=null;else commitDraft();actions.gestureEnd?.();render();};
+ boundsLayer.onpointerup=e=>endDrag(e);boundsLayer.onpointercancel=e=>endDrag(e,true);boundsLayer.onlostpointercapture=e=>{if(drag)endDrag(e,true);};
+ // Pressing the box captures the pointer on this layer, so clicks land here: a double-click is placed by where it falls.
+ boundsLayer.ondblclick=e=>{const box=boundsLayer.querySelector('.fv-ed-text-box'),c=box&&model.find(state.record,box.dataset.clip);if(!c)return;
+ const r=box.getBoundingClientRect();if(e.clientX<r.left||e.clientX>r.right||e.clientY<r.top||e.clientY>r.bottom)return;
+ e.preventDefault();if(c.text_kind==='text')startInline(c.id);else panels.get('subtitle')?.content.focus();};
+ function contextMenu(e){
+ const c=e.target.closest('[data-clip]'),entry=c&&model.find(state.record,c.dataset.clip);
+ if(!tracksHost.contains(e.target)||!isText(entry))return;e.preventDefault();e.stopPropagation();commitDraft();
+ state.select({kind:'clip',ids:[entry.id]});
+ menu.replaceChildren();const addItem=(label,key,run)=>{const b=button(label,{onClick:()=>{menu.hidden=true;run();}});b.setAttribute('role','menuitem');if(key)b.append(el('kbd','',key));menu.append(b);};
+ for(const [key,en,zh,kbd]of [['c','Copy','复制','Ctrl/Cmd+C'],['x','Cut','剪切','Ctrl/Cmd+X'],['d','Duplicate','创建副本','Ctrl/Cmd+D'],['delete','Delete','删除','Delete'],['b','Split','剪开','Ctrl/Cmd+B']])addItem(t(en,zh),kbd,()=>commands.run(key));
+ const rect=element.getBoundingClientRect();Object.assign(menu.style,{left:`${Math.min(e.clientX-rect.left,rect.width-240)}px`,top:`${Math.min(e.clientY-rect.top,rect.height-220)}px`});menu.hidden=false;
+ }
+ tracksHost.addEventListener('contextmenu',contextMenu);
+ const outside=e=>{if(!menu.contains(e.target))menu.hidden=true;};element.addEventListener('pointerdown',outside);
+ const unsubscribe=state.subscribe(event=>{if(['record','selection','playhead'].includes(event.type)){if(editing&&selectedText()?.id!==editing.id)finishInline();if(event.type==='record'&&draft){try{draft={...draft,record:draft.change(state.record)};}catch{draft=null;}}render();updateWarnings();}});
+ player.setTextRenderer?.(render);
+ const resize=typeof ResizeObserver==='function'?new ResizeObserver(()=>render()):null;resize?.observe(frame);
+ const seeked=()=>render();frame.addEventListener('seeked',seeked,true);frame.addEventListener('loadeddata',seeked,true);
+ let fontReady=null;
+ function ensureFonts(){return fontReady ||= ctx&&typeof FontFace!=='undefined'?Promise.all([loadTextFonts(),loadCoverage()]).then(([,value])=>{table=value;ready=true;render();updateWarnings();for(const node of tracksHost.querySelectorAll('.fv-ed-clip[data-text-kind]')){const c=model.find(state.record,node.dataset.clip);if(c)updateClip({clip:c,element:node,media:node.querySelector('.fv-ed-clip-media')},state.record);}}).catch(()=>{loadError=true;updateWarnings();}):Promise.resolve();}
+ if(state.record.tracks.some(isTextTrack))ensureFonts();
+ async function beforeExport(){
+ if(!state.record.tracks.some(isTextTrack))return true;finishInline();commitDraft();await ensureFonts();
+ const chars=[...new Set(projectMissing(state.record).flatMap(r=>r.chars))];if(!chars.length&&!loadError)return true;
+ const dialog=el('dialog','fv-studio fv-ed-text-export-dialog'),title=el('h3','',t('Export','导出')),message=el('p','',loadError?t('Text fonts could not be loaded','文字字体没能加载'):missingHint(chars,t));
+ const close=button(t('Back to edit','返回修改'),{onClick:()=>dialog.close()});dialog.append(title,message,close);document.body.append(dialog);
+ const stop=isolateDialogKeys(dialog,(e)=>{if(e.type==='keydown'&&e.key==='Escape'){e.preventDefault();dialog.close();}else if(e.type==='keydown'&&e.key==='Enter'){e.preventDefault();dialog.close();}});
+ dialog.onclose=()=>{stop();dialog.remove();jumpMissing();};dialog.showModal();close.focus();return false;
+ }
+ return {get ready(){return ensureFonts();},beforeExport,flush(){finishInline();commitDraft();},keyboard(e){
+ if(isTyping(e.target)||e.ctrlKey||e.metaKey||e.altKey||e.isComposing)return false;
+ if(e.key.toLowerCase()==='t'){e.preventDefault();e.stopPropagation();add('text');return true;}
+ if(e.key==='Escape'&&(drag||!menu.hidden)){e.preventDefault();if(drag)endDrag(e,true);menu.hidden=true;return true;}return false;
+ },dispose(){disposed=true;player.setTextRenderer?.(null);unsubscribe();resize?.disconnect();cancelAnimationFrame(raf);tracksHost.removeEventListener('contextmenu',contextMenu);element.removeEventListener('pointerdown',outside);frame.removeEventListener('seeked',seeked,true);frame.removeEventListener('loadeddata',seeked,true);canvas.remove();boundsLayer.remove();buttons.remove();notice.remove();menu.remove();}};
+}
diff --git a/web/editor_text_coverage.js b/web/editor_text_coverage.js
new file mode 100644
index 0000000..fe49c32
--- /dev/null
+++ b/web/editor_text_coverage.js
@@ -0,0 +1 @@
+export default {"sans":{"400":{"file":"FreeVideoSansSC-Regular.woff2","sha256":"a5ee784e85b96fc696467d9ec6319bf7bfe8542848b241908cbcc27f57bf679b","ranges":[[32,126],[160,259],[272,275],[282,283],[296,299],[323,324],[327,328],[332,335],[338,339],[360,365],[462,462],[464,464],[466,466],[468,468],[470,470],[472,472],[474,474],[476,476],[711,711],[713,713],[913,929],[931,937],[945,961],[963,969],[1025,1025],[1040,1103],[1105,1105],[8194,8195],[8208,8214],[8216,8218],[8220,8222],[8224,8226],[8229,8231],[8240,8240],[8242,8243],[8245,8245],[8249,8252],[8258,8258],[8263,8265],[8273,8273],[8451,8451],[8470,8470],[8544,8555],[8592,8601],[8632,8633],[8644,8646],[8651,8652],[8656,8656],[8658,8658],[8660,8660],[8678,8681],[8693,8693],[8712,8712],[8715,8715],[8719,8719],[8721,8721],[8730,8730],[8733,8734],[8736,8736],[8741,8741],[8743,8747],[8750,8750],[8756,8759],[8765,8765],[8773,8773],[8776,8776],[8780,8780],[8800,8801],[8804,8805],[8814,8815],[8857,8857],[8869,8869],[8978,8978],[9312,9547],[9632,9643],[9649,9651],[9654,9655],[9660,9661],[9664,9665],[9670,9671],[9673,9676],[9678,9683],[9698,9702],[9711,9711],[9728,9731],[9733,9734],[9737,9737],[9742,9743],[9750,9751],[9756,9759],[9775,9775],[9792,9794],[9824,9839],[9842,9853],[9888,9888],[9917,9918],[12288,12351],[12353,12438],[12441,12543],[12549,12585],[12832,12841],[13383,13383],[13386,13386],[13678,13678],[13838,13838],[13901,13901],[13912,13912],[13926,13926],[14019,14019],[14042,14042],[14073,14073],[14275,14275],[14343,14343],[14355,14355],[14616,14616],[14660,14660],[14800,14801],[14815,14815],[15088,15088],[15114,15114],[15118,15118],[15130,15130],[15182,15182],[15189,15189],[15294,15294],[15360,15360],[15559,15559],[15576,15576],[15578,15578],[15636,15636],[15696,15696],[15794,15794],[15878,15878],[15884,15884],[16004,16004],[16108,16108],[16207,16207],[16352,16352],[16470,16470],[16558,16558],[16581,16581],[16590,16590],[16735,16735],[17209,17209],[17283,17283],[17302,17302],[17373,17373],[17377,17377],[17394,17394],[17411,17411],[17622,17622],[17627,17627],[17640,17640],[17643,17644],[17878,17878],[17883,17883],[17898,17898],[17908,17908],[18211,18211],[18265,18265],[18618,18618],[18620,18620],[18648,18648],[18813,18813],[18819,18819],[19615,19616],[19618,19618],[19731,19737],[19886,19886],[19968,19969],[19971,19971],[19975,19985],[19987,19990],[19992,19998],[20002,20002],[20004,20005],[20007,20008],[20010,20013],[20016,20016],[20018,20018],[20020,20020],[20022,20022],[20024,20027],[20029,20031],[20034,20035],[20037,20037],[20039,20041],[20043,20048],[20050,20052],[20054,20054],[20056,20057],[20060,20065],[20070,20070],[20073,20073],[20080,20081],[20083,20083],[20088,20088],[20094,20094],[20102,20102],[20104,20105],[20107,20111],[20113,20117],[20120,20120],[20122,20123],[20127,20130],[20132,20137],[20139,20142],[20146,20147],[20149,20150],[20152,20155],[20159,20167],[20169,20171],[20173,20174],[20177,20177],[20179,20185],[20189,20191],[20193,20193],[20195,20197],[20200,20200],[20202,20204],[20208,20208],[20210,20211],[20213,20215],[20219,20219],[20221,20221],[20223,20223],[20225,20225],[20232,20235],[20237,20241],[20247,20251],[20254,20256],[20258,20263],[20266,20267],[20269,20269],[20271,20272],[20274,20274],[20276,20276],[20278,20278],[20280,20280],[20282,20282],[20284,20286],[20289,20289],[20291,20291],[20294,20294],[20301,20305],[20307,20307],[20309,20320],[20323,20325],[20327,20327],[20329,20329],[20332,20332],[20335,20336],[20339,20340],[20342,20342],[20344,20344],[20346,20351],[20353,20356],[20360,20361],[20363,20363],[20365,20365],[20367,20367],[20369,20369],[20372,20372],[20375,20376],[20379,20379],[20381,20381],[20384,20384],[20387,20387],[20389,20394],[20396,20396],[20398,20399],[20404,20405],[20409,20409],[20415,20415],[20419,20421],[20426,20426],[20429,20433],[20439,20442],[20444,20447],[20449,20449],[20451,20451],[20454,20454],[20456,20459],[20461,20463],[20465,20465],[20467,20467],[20469,20470],[20472,20472],[20474,20474],[20478,20478],[20492,20493],[20495,20495],[20498,20501],[20504,20506],[20508,20508],[20510,20511],[20513,20513],[20517,20522],[20524,20526],[20532,20532],[20538,20540],[20542,20542],[20545,20545],[20547,20547],[20551,20552],[20556,20556],[20558,20559],[20563,20563],[20565,20565],[20570,20570],[20572,20572],[20577,20577],[20581,20581],[20588,20589],[20592,20592],[20594,20594],[20598,20599],[20603,20603],[20606,20608],[20611,20611],[20613,20613],[20616,20617],[20621,20621],[20626,20626],[20629,20629],[20643,20643],[20645,20645],[20647,20649],[20652,20652],[20658,20658],[20666,20667],[20679,20679],[20686,20687],[20692,20692],[20694,20694],[20698,20698],[20710,20711],[20716,20718],[20720,20720],[20723,20723],[20725,20725],[20731,20731],[20742,20743],[20747,20747],[20754,20754],[20769,20769],[20774,20774],[20787,20788],[20799,20801],[20803,20806],[20808,20809],[20811,20811],[20813,20813],[20817,20817],[20820,20822],[20826,20826],[20828,20828],[20834,20834],[20837,20837],[20840,20840],[20843,20846],[20848,20849],[20851,20857],[20859,20861],[20864,20866],[20869,20869],[20872,20873],[20876,20877],[20879,20879],[20882,20882],[20884,20887],[20889,20889],[20891,20892],[20896,20896],[20898,20898],[20900,20901],[20907,20908],[20910,20915],[20917,20919],[20923,20925],[20928,20928],[20932,20932],[20934,20935],[20937,20937],[20939,20940],[20943,20943],[20945,20945],[20947,20947],[20952,20952],[20955,20955],[20957,20957],[20960,20961],[20964,20964],[20971,20971],[20973,20973],[20975,20976],[20979,20979],[20981,20982],[20984,20989],[20991,20995],[20998,21000],[21002,21002],[21005,21006],[21009,21010],[21014,21019],[21021,21021],[21024,21024],[21028,21028],[21032,21033],[21035,21038],[21040,21040],[21043,21043],[21046,21051],[21053,21053],[21055,21059],[21061,21061],[21066,21069],[21072,21073],[21076,21078],[21084,21084],[21086,21087],[21089,21089],[21093,21093],[21095,21095],[21097,21098],[21103,21103],[21106,21106],[21117,21117],[21119,21119],[21121,21122],[21124,21124],[21128,21128],[21136,21136],[21139,21139],[21147,21147],[21149,21155],[21160,21165],[21169,21171],[21180,21180],[21182,21183],[21187,21187],[21191,21191],[21193,21193],[21195,21195],[21197,21197],[21200,21200],[21202,21202],[21204,21204],[21206,21206],[21208,21208],[21210,21210],[21215,21216],[21220,21220],[21232,21232],[21241,21242],[21246,21248],[21253,21254],[21256,21256],[21261,21261],[21263,21264],[21269,21271],[21273,21274],[21276,21277],[21280,21281],[21283,21283],[21286,21286],[21290,21290],[21294,21294],[21305,21308],[21310,21311],[21313,21313],[21315,21315],[21317,21317],[21319,21322],[21326,21327],[21329,21331],[21333,21335],[21338,21338],[21340,21340],[21342,21348],[21350,21351],[21353,21353],[21355,21356],[21358,21361],[21363,21365],[21367,21368],[21370,21370],[21375,21375],[21378,21378],[21380,21382],[21385,21385],[21387,21389],[21397,21398],[21400,21400],[21402,21402],[21405,21405],[21407,21407],[21410,21411],[21413,21414],[21416,21417],[21422,21422],[21430,21430],[21435,21435],[21438,21439],[21441,21442],[21446,21453],[21457,21457],[21460,21467],[21471,21472],[21475,21478],[21480,21491],[21493,21497],[21499,21501],[21505,21505],[21507,21508],[21510,21510],[21512,21514],[21516,21523],[21525,21527],[21531,21531],[21533,21537],[21539,21539],[21542,21545],[21547,21551],[21553,21554],[21556,21557],[21560,21561],[21563,21566],[21568,21568],[21571,21571],[21574,21576],[21578,21579],[21584,21584],[21586,21593],[21595,21596],[21602,21604],[21606,21606],[21608,21608],[21617,21619],[21621,21624],[21627,21629],[21632,21632],[21634,21634],[21636,21636],[21638,21639],[21641,21641],[21643,21648],[21650,21650],[21652,21654],[21657,21659],[21661,21661],[21665,21665],[21667,21677],[21679,21679],[21681,21681],[21683,21684],[21688,21688],[21690,21691],[21693,21693],[21695,21700],[21702,21705],[21708,21717],[21719,21719],[21721,21722],[21724,21727],[21730,21730],[21733,21738],[21741,21742],[21745,21747],[21754,21754],[21756,21757],[21759,21759],[21761,21761],[21766,21767],[21769,21769],[21775,21777],[21780,21780],[21787,21787],[21789,21789],[21792,21792],[21794,21796],[21799,21799],[21802,21802],[21804,21804],[21806,21809],[21811,21811],[21813,21813],[21815,21815],[21820,21820],[21822,21823],[21825,21825],[21827,21828],[21830,21830],[21833,21834],[21840,21840],[21845,21846],[21852,21852],[21857,21857],[21860,21863],[21866,21870],[21872,21872],[21876,21880],[21883,21884],[21886,21886],[21888,21892],[21894,21899],[21903,21903],[21905,21905],[21908,21908],[21912,21913],[21916,21917],[21919,21919],[21924,21924],[21927,21927],[21937,21937],[21939,21939],[21941,21941],[21943,21943],[21945,21945],[21947,21947],[21949,21950],[21956,21957],[21961,21961],[21964,21965],[21968,21972],[21974,21974],[21980,21983],[21985,21985],[21987,21990],[21992,21992],[21994,21996],[21999,21999],[22002,22003],[22005,22005],[22007,22007],[22013,22014],[22016,22017],[22024,22025],[22028,22028],[22030,22031],[22040,22040],[22042,22043],[22046,22047],[22049,22049],[22051,22052],[22055,22055],[22060,22061],[22065,22066],[22068,22068],[22070,22070],[22073,22073],[22075,22075],[22079,22080],[22082,22082],[22087,22087],[22092,22094],[22100,22100],[22103,22105],[22108,22108],[22114,22114],[22116,22116],[22120,22124],[22129,22129],[22134,22134],[22139,22140],[22148,22150],[22158,22159],[22163,22163],[22170,22170],[22179,22179],[22189,22189],[22191,22191],[22199,22199],[22204,22204],[22218,22218],[22228,22228],[22231,22231],[22234,22235],[22237,22242],[22244,22244],[22251,22251],[22253,22253],[22256,22257],[22260,22261],[22263,22263],[22265,22266],[22269,22271],[22275,22276],[22278,22278],[22280,22282],[22284,22284],[22288,22288],[22297,22297],[22300,22300],[22303,22303],[22306,22307],[22312,22320],[22322,22323],[22329,22331],[22334,22334],[22336,22336],[22338,22338],[22343,22343],[22345,22354],[22359,22359],[22362,22369],[22372,22374],[22376,22381],[22383,22384],[22387,22387],[22390,22391],[22395,22397],[22402,22406],[22408,22408],[22411,22415],[22418,22419],[22421,22421],[22425,22427],[22430,22436],[22438,22439],[22441,22441],[22443,22443],[22445,22447],[22449,22450],[22452,22453],[22456,22456],[22458,22458],[22462,22463],[22466,22467],[22470,22471],[22475,22476],[22478,22479],[22482,22482],[22484,22485],[22487,22490],[22493,22493],[22495,22496],[22500,22500],[22506,22507],[22509,22509],[22511,22511],[22516,22517],[22520,22522],[22524,22525],[22528,22528],[22530,22531],[22534,22535],[22537,22537],[22539,22542],[22544,22545],[22549,22549],[22553,22553],[22558,22558],[22560,22561],[22564,22564],[22567,22568],[22570,22570],[22576,22576],[22578,22578],[22581,22581],[22588,22590],[22596,22598],[22604,22605],[22609,22609],[22612,22612],[22616,22616],[22621,22622],[22629,22629],[22635,22636],[22641,22641],[22654,22654],[22656,22657],[22659,22659],[22661,22661],[22664,22665],[22672,22672],[22674,22675],[22677,22677],[22680,22682],[22686,22687],[22689,22689],[22691,22691],[22694,22694],[22696,22697],[22716,22716],[22721,22721],[22725,22725],[22737,22737],[22741,22741],[22756,22756],[22763,22764],[22766,22766],[22768,22768],[22771,22771],[22774,22774],[22776,22777],[22786,22786],[22788,22788],[22791,22791],[22797,22797],[22799,22800],[22804,22806],[22809,22810],[22812,22812],[22815,22815],[22820,22821],[22823,22823],[22825,22831],[22833,22833],[22836,22836],[22839,22842],[22844,22844],[22849,22850],[22852,22852],[22855,22857],[22859,22859],[22862,22863],[22865,22865],[22867,22872],[22874,22874],[22880,22882],[22885,22885],[22893,22893],[22899,22900],[22902,22902],[22904,22905],[22909,22909],[22913,22916],[22918,22920],[22922,22922],[22925,22925],[22930,22931],[22934,22937],[22942,22942],[22947,22949],[22951,22955],[22957,22959],[22962,22962],[22969,22969],[22971,22971],[22974,22974],[22982,22982],[22984,22984],[22986,22987],[22992,22996],[22999,23000],[23002,23002],[23004,23006],[23011,23013],[23016,23016],[23020,23020],[23022,23022],[23025,23025],[23030,23030],[23033,23033],[23035,23035],[23037,23037],[23039,23041],[23043,23049],[23052,23052],[23057,23057],[23059,23059],[23064,23064],[23068,23068],[23071,23072],[23075,23075],[23077,23077],[23081,23081],[23089,23090],[23092,23094],[23100,23100],[23104,23104],[23110,23110],[23113,23114],[23116,23117],[23125,23125],[23128,23128],[23130,23130],[23134,23134],[23136,23136],[23138,23138],[23140,23140],[23143,23143],[23146,23147],[23155,23159],[23162,23164],[23167,23167],[23170,23170],[23172,23172],[23174,23174],[23186,23187],[23190,23190],[23194,23195],[23198,23198],[23210,23210],[23213,23213],[23217,23219],[23221,23221],[23224,23224],[23230,23230],[23233,23234],[23236,23236],[23241,23241],[23244,23244],[23250,23250],[23252,23254],[23256,23256],[23258,23258],[23260,23260],[23264,23265],[23267,23267],[23270,23270],[23273,23275],[23277,23277],[23281,23281],[23293,23293],[23305,23305],[23318,23319],[23323,23323],[23333,23333],[23340,23340],[23346,23346],[23348,23348],[23351,23351],[23359,23360],[23365,23365],[23376,23377],[23379,23389],[23391,23391],[23394,23398],[23401,23402],[23404,23404],[23408,23409],[23411,23411],[23413,23413],[23418,23418],[23421,23421],[23424,23425],[23427,23429],[23431,23433],[23435,23436],[23439,23439],[23443,23443],[23445,23445],[23447,23454],[23456,23463],[23466,23468],[23472,23472],[23475,23478],[23480,23481],[23485,23487],[23489,23490],[23492,23495],[23500,23500],[23504,23504],[23506,23507],[23517,23519],[23521,23521],[23524,23525],[23528,23528],[23534,23534],[23536,23536],[23544,23548],[23551,23551],[23553,23553],[23556,23556],[23558,23558],[23561,23562],[23567,23567],[23569,23569],[23572,23574],[23576,23576],[23578,23578],[23580,23581],[23586,23586],[23588,23589],[23591,23592],[23594,23594],[23596,23596],[23601,23601],[23604,23604],[23608,23619],[23621,23621],[23624,23627],[23630,23633],[23637,23637],[23641,23641],[23646,23646],[23648,23649],[23651,23651],[23653,23654],[23662,23663],[23665,23665],[23673,23674],[23676,23676],[23678,23679],[23681,23682],[23688,23688],[23690,23690],[23692,23693],[23696,23697],[23700,23700],[23702,23708],[23710,23710],[23712,23712],[23714,23715],[23720,23721],[23723,23725],[23729,23729],[23731,23731],[23733,23733],[23735,23736],[23741,23741],[23743,23743],[23745,23748],[23755,23755],[23762,23762],[23767,23769],[23771,23771],[23777,23777],[23779,23784],[23786,23786],[23789,23789],[23792,23793],[23803,23803],[23807,23812],[23814,23815],[23820,23820],[23822,23822],[23826,23826],[23828,23828],[23830,23830],[23834,23835],[23838,23839],[23841,23841],[23844,23844],[23846,23847],[23849,23849],[23853,23854],[23860,23860],[23862,23862],[23869,23871],[23873,23873],[23877,23877],[23879,23879],[23882,23884],[23886,23886],[23894,23894],[23896,23896],[23898,23899],[23901,23901],[23913,23913],[23915,23916],[23919,23919],[23922,23922],[23924,23924],[23938,23938],[23941,23941],[23949,23949],[23954,23955],[23961,23961],[23965,23965],[23967,23967],[23974,23974],[23986,23986],[23991,23991],[24005,24005],[24007,24007],[24009,24009],[24013,24013],[24027,24027],[24029,24030],[24033,24034],[24037,24041],[24043,24043],[24046,24047],[24049,24052],[24055,24055],[24061,24062],[24065,24067],[24069,24070],[24072,24072],[24076,24076],[24079,24081],[24084,24086],[24088,24093],[24097,24097],[24102,24104],[24109,24110],[24113,24113],[24119,24120],[24123,24125],[24130,24130],[24132,24133],[24140,24140],[24148,24150],[24155,24155],[24158,24158],[24161,24162],[24170,24170],[24178,24180],[24182,24182],[24184,24184],[24186,24189],[24191,24192],[24196,24196],[24198,24199],[24202,24203],[24207,24209],[24211,24215],[24217,24218],[24220,24220],[24222,24224],[24228,24231],[24237,24237],[24241,24241],[24243,24243],[24245,24249],[24252,24252],[24254,24254],[24262,24262],[24265,24267],[24273,24275],[24278,24278],[24281,24281],[24283,24283],[24296,24296],[24298,24298],[24308,24308],[24310,24311],[24314,24314],[24318,24324],[24326,24328],[24330,24331],[24335,24335],[24337,24337],[24339,24339],[24341,24341],[24343,24344],[24347,24347],[24351,24352],[24354,24354],[24357,24362],[24365,24365],[24367,24367],[24369,24369],[24374,24374],[24376,24378],[24380,24380],[24384,24384],[24400,24400],[24402,24403],[24405,24408],[24413,24413],[24415,24415],[24417,24418],[24420,24420],[24422,24423],[24425,24426],[24428,24429],[24432,24433],[24435,24435],[24439,24439],[24441,24441],[24443,24444],[24448,24450],[24452,24453],[24455,24460],[24464,24464],[24466,24466],[24469,24469],[24471,24473],[24475,24476],[24481,24481],[24488,24488],[24490,24490],[24493,24494],[24501,24501],[24503,24503],[24508,24509],[24515,24518],[24521,24521],[24524,24525],[24527,24530],[24534,24537],[24541,24542],[24544,24545],[24548,24548],[24551,24551],[24554,24555],[24557,24558],[24561,24561],[24563,24563],[24565,24565],[24568,24568],[24570,24571],[24573,24582],[24586,24586],[24589,24591],[24594,24594],[24596,24598],[24601,24601],[24603,24605],[24608,24609],[24613,24619],[24623,24623],[24629,24629],[24635,24636],[24639,24639],[24641,24643],[24651,24651],[24653,24653],[24656,24656],[24658,24661],[24665,24666],[24669,24669],[24674,24676],[24679,24685],[24687,24688],[24691,24691],[24694,24694],[24696,24701],[24703,24703],[24707,24708],[24710,24710],[24712,24713],[24716,24717],[24722,24722],[24724,24724],[24726,24726],[24730,24731],[24733,24733],[24735,24736],[24738,24739],[24742,24742],[24744,24744],[24747,24749],[24751,24754],[24756,24756],[24760,24760],[24763,24764],[24773,24775],[24778,24779],[24782,24782],[24785,24785],[24788,24789],[24792,24797],[24799,24800],[24806,24809],[24811,24816],[24819,24820],[24822,24822],[24825,24826],[24832,24833],[24835,24835],[24838,24838],[24840,24841],[24845,24848],[24852,24853],[24858,24858],[24863,24864],[24867,24868],[24870,24871],[24875,24875],[24877,24877],[24895,24895],[24902,24902],[24904,24904],[24906,24906],[24908,24908],[24910,24910],[24913,24913],[24917,24917],[24925,24925],[24930,24930],[24933,24933],[24935,24936],[24940,24941],[24944,24944],[24949,24949],[24951,24951],[24971,24971],[24974,24974],[24980,24981],[24985,24985],[24989,24989],[24999,25001],[25004,25005],[25015,25015],[25018,25018],[25022,25022],[25026,25026],[25032,25032],[25034,25035],[25041,25042],[25044,25044],[25062,25062],[25077,25077],[25087,25087],[25094,25094],[25096,25096],[25098,25106],[25109,25112],[25114,25115],[25119,25119],[25121,25125],[25130,25130],[25132,25134],[25139,25140],[25143,25143],[25149,25155],[25157,25166],[25169,25172],[25176,25176],[25179,25179],[25182,25182],[25187,25187],[25190,25191],[25193,25200],[25203,25203],[25206,25206],[25209,25210],[25212,25216],[25219,25220],[25225,25226],[25233,25240],[25242,25243],[25247,25250],[25252,25253],[25256,25256],[25259,25260],[25265,25265],[25269,25269],[25273,25273],[25275,25277],[25279,25279],[25282,25290],[25292,25294],[25296,25296],[25298,25300],[25302,25308],[25311,25311],[25314,25321],[25324,25327],[25329,25329],[25331,25332],[25334,25335],[25340,25343],[25345,25346],[25351,25353],[25358,25358],[25361,25361],[25363,25363],[25366,25366],[25370,25371],[25373,25382],[25384,25384],[25386,25387],[25391,25391],[25394,25394],[25401,25402],[25405,25405],[25410,25411],[25413,25414],[25417,25417],[25419,25424],[25429,25429],[25438,25439],[25441,25443],[25447,25447],[25449,25449],[25453,25455],[25457,25457],[25462,25463],[25466,25467],[25469,25469],[25472,25472],[25474,25474],[25479,25482],[25484,25484],[25486,25488],[25490,25490],[25494,25494],[25496,25496],[25502,25502],[25504,25504],[25506,25507],[25509,25509],[25511,25514],[25516,25518],[25520,25520],[25523,25524],[25527,25528],[25530,25530],[25532,25532],[25534,25534],[25540,25540],[25542,25542],[25545,25545],[25549,25552],[25554,25554],[25557,25558],[25566,25566],[25568,25569],[25571,25571],[25577,25578],[25581,25581],[25586,25588],[25590,25590],[25592,25592],[25597,25597],[25599,25602],[25605,25605],[25611,25612],[25615,25616],[25618,25620],[25627,25628],[25630,25630],[25632,25633],[25638,25638],[25642,25642],[25644,25645],[25652,25652],[25658,25658],[25661,25661],[25663,25663],[25665,25665],[25668,25672],[25674,25674],[25679,25679],[25682,25682],[25684,25684],[25688,25688],[25691,25691],[25694,25694],[25703,25703],[25705,25705],[25709,25709],[25716,25716],[25720,25722],[25725,25725],[25730,25730],[25732,25733],[25735,25735],[25745,25746],[25749,25750],[25753,25753],[25758,25758],[25764,25764],[25769,25769],[25772,25774],[25776,25776],[25781,25781],[25783,25784],[25786,25786],[25788,25788],[25792,25792],[25794,25794],[25797,25797],[25805,25806],[25808,25808],[25810,25810],[25815,25816],[25822,25822],[25826,25826],[25828,25828],[25830,25830],[25855,25856],[25865,25865],[25874,25874],[25880,25880],[25893,25893],[25899,25899],[25902,25903],[25908,25910],[25912,25913],[25915,25915],[25917,25919],[25925,25925],[25928,25929],[25932,25932],[25935,25935],[25937,25937],[25940,25942],[25945,25945],[25947,25947],[25949,25950],[25954,25955],[25958,25958],[25961,25961],[25963,25964],[25968,25968],[25970,25970],[25972,25972],[25975,25975],[25991,25991],[25995,25996],[26000,26001],[26003,26003],[26007,26007],[26009,26009],[26011,26013],[26015,26017],[26020,26021],[26023,26023],[26025,26025],[26027,26027],[26029,26029],[26031,26032],[26038,26038],[26041,26041],[26044,26045],[26049,26049],[26051,26054],[26059,26060],[26062,26064],[26066,26066],[26070,26071],[26078,26078],[26080,26080],[26082,26082],[26085,26089],[26092,26097],[26100,26104],[26106,26107],[26111,26112],[26114,26116],[26118,26122],[26124,26124],[26126,26127],[26130,26133],[26137,26137],[26141,26141],[26143,26145],[26147,26149],[26151,26152],[26154,26155],[26157,26157],[26159,26159],[26161,26161],[26163,26166],[26170,26170],[26172,26174],[26177,26177],[26179,26179],[26181,26181],[26186,26188],[26191,26192],[26194,26199],[26201,26202],[26206,26207],[26209,26210],[26212,26212],[26214,26214],[26216,26216],[26218,26219],[26222,26225],[26228,26228],[26230,26231],[26234,26234],[26238,26238],[26242,26242],[26244,26245],[26247,26247],[26252,26252],[26257,26257],[26261,26263],[26269,26269],[26279,26280],[26286,26286],[26290,26290],[26292,26294],[26297,26297],[26302,26303],[26312,26312],[26316,26316],[26329,26329],[26331,26333],[26342,26342],[26345,26345],[26352,26352],[26354,26356],[26359,26359],[26361,26361],[26364,26364],[26366,26368],[26376,26379],[26381,26381],[26383,26384],[26387,26389],[26391,26391],[26395,26395],[26397,26397],[26399,26399],[26406,26406],[26408,26408],[26410,26413],[26415,26415],[26417,26417],[26419,26421],[26424,26424],[26426,26426],[26429,26429],[26432,26432],[26434,26436],[26438,26438],[26440,26441],[26444,26444],[26446,26449],[26451,26451],[26453,26454],[26457,26457],[26460,26460],[26462,26465],[26469,26469],[26471,26474],[26477,26477],[26479,26480],[26482,26483],[26485,26485],[26487,26487],[26491,26492],[26494,26495],[26497,26497],[26500,26501],[26503,26503],[26505,26505],[26507,26507],[26509,26509],[26512,26512],[26517,26517],[26519,26520],[26522,26522],[26524,26526],[26530,26531],[26533,26533],[26535,26536],[26538,26539],[26541,26541],[26543,26544],[26546,26547],[26549,26553],[26561,26561],[26563,26564],[26568,26568],[26570,26570],[26575,26580],[26582,26582],[26584,26586],[26588,26590],[26592,26592],[26594,26594],[26597,26597],[26601,26601],[26604,26604],[26607,26609],[26611,26612],[26615,26615],[26621,26621],[26623,26624],[26629,26629],[26631,26636],[26638,26643],[26646,26647],[26653,26653],[26655,26655],[26657,26657],[26665,26666],[26674,26676],[26679,26681],[26683,26686],[26688,26694],[26696,26698],[26700,26700],[26702,26702],[26704,26705],[26707,26709],[26720,26729],[26731,26731],[26735,26735],[26738,26738],[26740,26740],[26742,26743],[26745,26745],[26753,26753],[26755,26755],[26757,26758],[26764,26764],[26767,26767],[26771,26771],[26775,26775],[26784,26784],[26786,26787],[26790,26792],[26797,26797],[26799,26800],[26803,26805],[26812,26818],[26825,26825],[26827,26827],[26829,26829],[26832,26832],[26834,26835],[26837,26837],[26840,26840],[26842,26842],[26848,26848],[26851,26852],[26856,26856],[26858,26860],[26862,26862],[26864,26865],[26869,26869],[26873,26877],[26880,26881],[26885,26886],[26891,26891],[26893,26894],[26896,26899],[26911,26912],[26916,26916],[26922,26922],[26925,26925],[26928,26928],[26932,26932],[26936,26937],[26941,26941],[26943,26943],[26946,26946],[26962,26962],[26964,26964],[26967,26967],[26969,26970],[26973,26974],[26976,26976],[26979,26979],[26982,26982],[26985,26987],[26990,26991],[26993,26993],[26999,27001],[27004,27004],[27008,27008],[27010,27017],[27021,27021],[27025,27025],[27028,27030],[27032,27032],[27035,27036],[27047,27048],[27051,27051],[27053,27053],[27056,27057],[27060,27060],[27063,27063],[27067,27067],[27073,27073],[27075,27075],[27082,27082],[27084,27084],[27086,27086],[27088,27088],[27092,27092],[27098,27100],[27103,27104],[27117,27117],[27121,27122],[27133,27133],[27135,27135],[27146,27146],[27159,27160],[27167,27167],[27169,27169],[27176,27176],[27178,27178],[27183,27183],[27185,27185],[27189,27189],[27197,27198],[27204,27204],[27207,27207],[27216,27217],[27224,27225],[27227,27227],[27230,27230],[27233,27233],[27237,27238],[27249,27249],[27257,27257],[27260,27260],[27264,27264],[27268,27268],[27278,27278],[27280,27281],[27287,27287],[27294,27294],[27296,27296],[27305,27305],[27307,27308],[27334,27334],[27394,27394],[27424,27428],[27431,27431],[27442,27442],[27447,27451],[27454,27454],[27459,27459],[27461,27463],[27465,27465],[27468,27468],[27481,27481],[27490,27495],[27498,27498],[27513,27513],[27515,27516],[27521,27524],[27526,27527],[27529,27531],[27533,27533],[27538,27539],[27542,27542],[27546,27547],[27553,27553],[27555,27555],[27562,27562],[27571,27573],[27575,27575],[27583,27583],[27585,27586],[27589,27589],[27595,27597],[27599,27600],[27602,27607],[27609,27609],[27611,27611],[27617,27617],[27626,27627],[27631,27631],[27635,27635],[27637,27637],[27641,27641],[27645,27645],[27653,27655],[27661,27661],[27663,27665],[27667,27670],[27672,27675],[27679,27679],[27681,27682],[27684,27684],[27686,27690],[27694,27696],[27698,27698],[27700,27701],[27704,27704],[27709,27714],[27718,27723],[27728,27728],[27732,27733],[27735,27735],[27739,27745],[27748,27748],[27751,27755],[27757,27757],[27760,27760],[27762,27762],[27764,27764],[27766,27766],[27769,27769],[27773,27774],[27777,27785],[27788,27788],[27791,27792],[27795,27796],[27800,27803],[27807,27807],[27809,27809],[27811,27819],[27821,27822],[27825,27827],[27832,27839],[27842,27845],[27847,27847],[27849,27850],[27852,27852],[27856,27856],[27859,27863],[27865,27868],[27870,27870],[27872,27875],[27877,27877],[27880,27880],[27882,27883],[27886,27889],[27891,27891],[27893,27896],[27898,27902],[27905,27905],[27908,27908],[27911,27912],[27915,27916],[27918,27918],[27921,27923],[27927,27931],[27934,27934],[27938,27939],[27941,27941],[27943,27944],[27946,27947],[27949,27950],[27953,27957],[27960,27967],[27969,27969],[27971,27971],[27973,27979],[27981,27989],[27993,27996],[27998,28001],[28003,28003],[28005,28006],[28009,28010],[28012,28016],[28018,28018],[28020,28020],[28023,28024],[28028,28028],[28034,28034],[28036,28037],[28040,28041],[28044,28046],[28048,28049],[28051,28053],[28056,28056],[28059,28059],[28061,28068],[28070,28075],[28078,28079],[28082,28082],[28084,28085],[28088,28088],[28095,28096],[28100,28103],[28107,28108],[28111,28111],[28113,28113],[28118,28118],[28120,28121],[28124,28129],[28132,28132],[28134,28134],[28139,28140],[28142,28143],[28145,28145],[28147,28148],[28151,28151],[28153,28153],[28155,28156],[28165,28165],[28170,28170],[28172,28174],[28176,28177],[28180,28180],[28182,28183],[28186,28186],[28189,28189],[28191,28193],[28195,28197],[28201,28201],[28203,28203],[28205,28205],[28207,28208],[28210,28210],[28212,28212],[28216,28216],[28218,28218],[28220,28220],[28227,28228],[28233,28233],[28237,28238],[28241,28241],[28243,28244],[28246,28246],[28248,28248],[28251,28253],[28255,28255],[28259,28259],[28267,28267],[28270,28270],[28274,28274],[28276,28276],[28286,28287],[28289,28289],[28291,28291],[28293,28295],[28297,28297],[28301,28301],[28303,28304],[28312,28312],[28314,28314],[28316,28316],[28318,28320],[28322,28322],[28325,28327],[28330,28330],[28335,28335],[28337,28338],[28340,28343],[28345,28347],[28349,28349],[28353,28355],[28358,28359],[28361,28361],[28363,28363],[28365,28365],[28367,28367],[28369,28369],[28371,28373],[28375,28376],[28378,28378],[28382,28386],[28388,28395],[28404,28404],[28409,28409],[28418,28418],[28422,28422],[28424,28425],[28427,28427],[28431,28431],[28435,28438],[28448,28448],[28452,28452],[28454,28454],[28457,28459],[28461,28461],[28463,28463],[28465,28465],[28467,28468],[28470,28471],[28473,28473],[28475,28476],[28478,28478],[28486,28487],[28491,28491],[28493,28493],[28495,28495],[28502,28502],[28504,28504],[28508,28508],[28510,28511],[28514,28514],[28518,28518],[28521,28521],[28525,28526],[28530,28530],[28532,28533],[28536,28536],[28538,28538],[28540,28542],[28546,28546],[28548,28548],[28552,28553],[28556,28558],[28571,28572],[28577,28577],[28581,28581],[28583,28583],[28586,28586],[28589,28589],[28595,28596],[28598,28598],[28601,28601],[28604,28605],[28608,28608],[28610,28610],[28617,28617],[28619,28619],[28625,28626],[28638,28638],[28640,28641],[28649,28649],[28654,28655],[28684,28685],[28689,28689],[28692,28692],[28698,28699],[28707,28707],[28721,28721],[28725,28725],[28729,28729],[28732,28732],[28744,28744],[28748,28748],[28751,28751],[28766,28766],[28779,28781],[28783,28784],[28789,28790],[28792,28792],[28796,28796],[28798,28800],[28805,28806],[28809,28810],[28812,28812],[28814,28814],[28818,28818],[28820,28822],[28824,28825],[28828,28829],[28831,28831],[28835,28835],[28843,28847],[28849,28849],[28851,28851],[28855,28857],[28859,28861],[28864,28867],[28872,28872],[28874,28874],[28884,28884],[28888,28889],[28891,28893],[28895,28896],[28900,28900],[28902,28905],[28907,28909],[28911,28911],[28918,28919],[28921,28923],[28925,28925],[28934,28934],[28937,28938],[28940,28940],[28944,28944],[28947,28947],[28949,28954],[28956,28956],[28958,28958],[28966,28966],[28975,28977],[28982,28982],[28993,28993],[28995,28995],[28997,28997],[29002,29004],[29006,29006],[29011,29011],[29020,29020],[29022,29023],[29028,29028],[29030,29032],[29038,29038],[29042,29044],[29048,29048],[29050,29050],[29053,29053],[29060,29060],[29063,29063],[29066,29066],[29071,29071],[29076,29076],[29080,29081],[29083,29084],[29087,29088],[29093,29093],[29096,29096],[29100,29100],[29107,29107],[29109,29109],[29113,29113],[29115,29115],[29123,29123],[29130,29131],[29134,29135],[29140,29141],[29146,29146],[29152,29152],[29157,29157],[29159,29159],[29166,29166],[29177,29177],[29190,29191],[29204,29204],[29210,29210],[29213,29213],[29215,29215],[29224,29224],[29226,29226],[29228,29228],[29232,29233],[29237,29241],[29243,29243],[29245,29245],[29247,29247],[29249,29250],[29255,29256],[29260,29261],[29266,29266],[29270,29270],[29273,29275],[29277,29277],[29279,29279],[29281,29282],[29284,29287],[29289,29289],[29294,29295],[29298,29298],[29301,29301],[29305,29307],[29310,29313],[29316,29316],[29319,29319],[29322,29323],[29325,29325],[29327,29327],[29330,29330],[29343,29343],[29352,29352],[29356,29357],[29359,29360],[29364,29364],[29366,29369],[29377,29380],[29384,29385],[29389,29390],[29392,29392],[29394,29394],[29399,29399],[29401,29401],[29405,29406],[29408,29409],[29416,29417],[29420,29428],[29431,29432],[29434,29436],[29441,29441],[29443,29444],[29447,29447],[29450,29450],[29454,29454],[29459,29459],[29461,29463],[29467,29470],[29473,29474],[29477,29477],[29481,29484],[29486,29489],[29492,29492],[29495,29498],[29502,29503],[29517,29517],[29520,29520],[29522,29522],[29527,29527],[29536,29536],[29548,29549],[29551,29551],[29556,29556],[29566,29566],[29571,29572],[29575,29575],[29577,29577],[29579,29579],[29582,29582],[29585,29587],[29589,29590],[29592,29595],[29598,29602],[29604,29606],[29609,29609],[29611,29611],[29613,29619],[29622,29623],[29625,29628],[29631,29632],[29634,29634],[29637,29637],[29639,29645],[29647,29650],[29653,29654],[29657,29657],[29659,29659],[29661,29662],[29664,29664],[29666,29667],[29669,29671],[29673,29675],[29677,29677],[29680,29680],[29682,29682],[29685,29685],[29687,29690],[29693,29693],[29696,29696],[29699,29706],[29710,29712],[29716,29716],[29722,29723],[29727,29727],[29729,29730],[29732,29734],[29736,29736],[29738,29744],[29746,29750],[29756,29756],[29760,29766],[29777,29777],[29779,29783],[29785,29791],[29794,29794],[29799,29800],[29804,29805],[29808,29809],[29811,29811],[29814,29815],[29822,29822],[29824,29825],[29827,29827],[29830,29832],[29835,29835],[29838,29838],[29840,29840],[29842,29842],[29848,29848],[29852,29852],[29854,29856],[29861,29861],[29863,29866],[29868,29868],[29870,29870],[29873,29874],[29882,29882],[29888,29888],[29906,29906],[29910,29910],[29912,29912],[29916,29916],[29918,29918],[29920,29920],[29922,29924],[29926,29926],[29934,29935],[29940,29940],[29942,29943],[29947,29947],[29951,29951],[29956,29956],[29965,29965],[29967,29967],[29969,29969],[29971,29971],[29975,29978],[29980,29980],[29983,29983],[29985,29985],[29989,29990],[29992,29997],[29999,30003],[30005,30005],[30007,30008],[30010,30011],[30014,30014],[30016,30016],[30021,30021],[30024,30024],[30027,30028],[30030,30031],[30036,30036],[30038,30038],[30041,30044],[30052,30054],[30058,30058],[30060,30060],[30063,30063],[30066,30066],[30068,30068],[30072,30073],[30079,30079],[30081,30081],[30083,30083],[30086,30086],[30091,30091],[30093,30093],[30095,30098],[30100,30100],[30102,30103],[30105,30106],[30109,30109],[30111,30117],[30123,30133],[30136,30137],[30140,30142],[30146,30149],[30151,30154],[30157,30157],[30162,30166],[30168,30168],[30171,30171],[30174,30174],[30178,30180],[30182,30184],[30186,30187],[30192,30193],[30196,30196],[30201,30201],[30204,30204],[30207,30209],[30211,30211],[30213,30214],[30218,30218],[30220,30220],[30224,30224],[30229,30229],[30231,30233],[30235,30235],[30239,30240],[30242,30242],[30244,30246],[30249,30251],[30253,30253],[30256,30256],[30259,30261],[30264,30264],[30268,30268],[30270,30272],[30275,30275],[30284,30285],[30292,30292],[30294,30295],[30300,30300],[30302,30302],[30307,30307],[30315,30315],[30319,30319],[30328,30328],[30331,30331],[30333,30335],[30338,30338],[30340,30340],[30342,30344],[30347,30347],[30350,30350],[30353,30353],[30355,30355],[30357,30358],[30361,30361],[30363,30363],[30366,30366],[30372,30372],[30374,30374],[30381,30382],[30385,30386],[30388,30388],[30399,30399],[30402,30402],[30405,30406],[30408,30410],[30413,30418],[30420,30420],[30422,30424],[30427,30427],[30431,30431],[30437,30438],[30446,30447],[30449,30450],[30452,30452],[30455,30457],[30460,30460],[30462,30462],[30465,30465],[30468,30468],[30471,30475],[30477,30477],[30489,30490],[30495,30496],[30498,30498],[30502,30502],[30504,30505],[30508,30509],[30511,30511],[30517,30520],[30522,30522],[30524,30524],[30528,30529],[30531,30532],[30535,30535],[30542,30542],[30544,30545],[30554,30555],[30561,30563],[30565,30566],[30568,30568],[30571,30572],[30585,30585],[30589,30592],[30596,30597],[30603,30606],[30609,30610],[30623,30624],[30626,30626],[30629,30629],[30631,30631],[30633,30637],[30640,30640],[30643,30643],[30645,30645],[30651,30651],[30653,30653],[30655,30655],[30669,30669],[30679,30679],[30683,30684],[30686,30686],[30690,30691],[30693,30693],[30695,30695],[30697,30697],[30699,30702],[30704,30704],[30707,30707],[30710,30710],[30712,30712],[30715,30722],[30724,30724],[30726,30726],[30729,30729],[30732,30733],[30737,30738],[30740,30740],[30742,30744],[30746,30746],[30748,30749],[30751,30752],[30755,30755],[30757,30759],[30761,30761],[30763,30766],[30768,30768],[30772,30773],[30775,30780],[30782,30782],[30784,30785],[30789,30789],[30791,30791],[30794,30794],[30796,30798],[30800,30800],[30802,30802],[30804,30807],[30809,30810],[30813,30813],[30826,30830],[30839,30839],[30844,30844],[30847,30847],[30851,30851],[30855,30857],[30860,30863],[30865,30865],[30867,30867],[30871,30872],[30874,30876],[30879,30879],[30881,30881],[30883,30883],[30885,30885],[30887,30888],[30896,30900],[30902,30902],[30905,30905],[30910,30910],[30913,30913],[30917,30917],[30921,30923],[30927,30928],[30932,30933],[30937,30937],[30940,30940],[30945,30945],[30952,30952],[30956,30956],[30962,30962],[30964,30964],[30967,30967],[30969,30971],[30977,30977],[30981,30981],[30988,30988],[30995,30995],[31006,31006],[31012,31012],[31028,31029],[31034,31036],[31038,31038],[31040,31041],[31043,31043],[31046,31051],[31054,31056],[31059,31059],[31061,31063],[31066,31072],[31074,31074],[31077,31077],[31079,31080],[31085,31085],[31087,31087],[31090,31090],[31095,31096],[31098,31098],[31100,31100],[31102,31102],[31104,31105],[31108,31109],[31114,31115],[31119,31119],[31122,31122],[31124,31124],[31128,31128],[31130,31131],[31140,31140],[31143,31143],[31155,31155],[31161,31163],[31165,31166],[31168,31169],[31171,31171],[31174,31174],[31177,31177],[31179,31179],[31181,31181],[31185,31186],[31189,31189],[31192,31192],[31199,31199],[31203,31204],[31206,31207],[31209,31209],[31211,31213],[31215,31216],[31224,31224],[31227,31227],[31229,31230],[31232,31232],[31234,31235],[31238,31238],[31243,31246],[31249,31249],[31252,31252],[31255,31255],[31257,31258],[31262,31262],[31264,31264],[31267,31267],[31283,31283],[31287,31287],[31289,31289],[31291,31293],[31295,31295],[31300,31300],[31302,31302],[31313,31313],[31319,31319],[31321,31321],[31324,31324],[31327,31327],[31344,31344],[31348,31348],[31350,31354],[31359,31361],[31363,31366],[31368,31368],[31370,31370],[31373,31374],[31377,31378],[31381,31384],[31388,31389],[31391,31392],[31395,31395],[31397,31398],[31400,31400],[31404,31405],[31411,31411],[31416,31416],[31423,31423],[31435,31435],[31441,31441],[31446,31446],[31448,31449],[31454,31456],[31459,31459],[31461,31462],[31467,31467],[31469,31469],[31471,31471],[31481,31482],[31485,31485],[31487,31487],[31491,31492],[31494,31494],[31496,31496],[31498,31499],[31503,31503],[31505,31505],[31508,31509],[31513,31513],[31515,31515],[31518,31518],[31520,31520],[31524,31526],[31528,31528],[31530,31532],[31534,31535],[31537,31537],[31539,31539],[31544,31544],[31546,31546],[31548,31548],[31550,31550],[31552,31552],[31557,31557],[31559,31559],[31561,31561],[31563,31564],[31567,31570],[31572,31572],[31574,31574],[31576,31576],[31578,31581],[31584,31584],[31586,31586],[31588,31590],[31598,31598],[31601,31602],[31605,31607],[31609,31609],[31611,31612],[31614,31614],[31616,31616],[31621,31621],[31629,31629],[31632,31632],[31635,31639],[31644,31645],[31649,31650],[31654,31661],[31665,31665],[31668,31668],[31672,31672],[31681,31681],[31686,31687],[31692,31692],[31697,31697],[31699,31699],[31705,31706],[31709,31709],[31713,31713],[31717,31718],[31722,31722],[31726,31727],[31729,31729],[31735,31735],[31740,31740],[31742,31742],[31747,31747],[31751,31751],[31753,31753],[31755,31756],[31759,31759],[31765,31766],[31773,31773],[31775,31776],[31782,31783],[31786,31786],[31792,31792],[31800,31800],[31807,31809],[31821,31821],[31845,31845],[31859,31860],[31867,31869],[31881,31881],[31889,31890],[31893,31893],[31895,31896],[31900,31903],[31906,31906],[31908,31909],[31914,31914],[31918,31918],[31921,31923],[31929,31929],[31932,31935],[31937,31937],[31941,31941],[31943,31944],[31946,31946],[31948,31949],[31954,31954],[31957,31959],[31961,31961],[31964,31964],[31967,31968],[31976,31976],[31983,31983],[31989,31989],[31992,31992],[31995,31995],[32010,32010],[32032,32032],[32034,32034],[32039,32039],[32043,32043],[32047,32047],[32092,32092],[32110,32110],[32119,32119],[32166,32166],[32174,32174],[32288,32288],[32290,32290],[32315,32315],[32321,32321],[32324,32324],[32327,32327],[32386,32386],[32411,32411],[32415,32491],[32493,32566],[32568,32568],[32570,32570],[32578,32578],[32580,32581],[32589,32589],[32592,32593],[32596,32597],[32599,32600],[32602,32602],[32607,32607],[32609,32610],[32616,32618],[32622,32622],[32625,32626],[32628,32628],[32630,32630],[32633,32633],[32637,32638],[32641,32641],[32650,32650],[32652,32652],[32654,32654],[32657,32657],[32659,32662],[32666,32666],[32669,32671],[32673,32673],[32676,32676],[32679,32679],[32687,32690],[32696,32697],[32700,32701],[32703,32707],[32709,32709],[32712,32712],[32714,32714],[32716,32716],[32718,32718],[32724,32725],[32728,32731],[32735,32737],[32741,32742],[32745,32745],[32750,32753],[32755,32755],[32759,32759],[32763,32764],[32766,32766],[32768,32769],[32771,32775],[32779,32781],[32783,32786],[32788,32793],[32796,32796],[32800,32800],[32802,32802],[32804,32810],[32816,32817],[32819,32819],[32821,32824],[32827,32827],[32829,32829],[32831,32831],[32834,32835],[32838,32838],[32842,32845],[32850,32850],[32852,32852],[32856,32856],[32858,32858],[32873,32874],[32881,32881],[32895,32896],[32899,32900],[32902,32903],[32905,32905],[32907,32908],[32915,32915],[32918,32918],[32920,32920],[32922,32925],[32927,32930],[32932,32933],[32937,32939],[32941,32943],[32945,32946],[32948,32948],[32951,32952],[32954,32954],[32956,32964],[32966,32966],[32968,32968],[32972,32974],[32982,32983],[32985,32990],[32992,32993],[32995,32997],[32999,33005],[33007,33012],[33014,33014],[33016,33016],[33018,33018],[33020,33021],[33026,33026],[33030,33030],[33033,33034],[33037,33044],[33046,33046],[33048,33048],[33050,33050],[33054,33055],[33065,33065],[33068,33068],[33071,33071],[33073,33074],[33078,33078],[33080,33080],[33086,33087],[33094,33094],[33096,33096],[33098,33100],[33104,33109],[33112,33114],[33120,33120],[33125,33125],[33127,33129],[33133,33137],[33140,33140],[33145,33152],[33154,33154],[33160,33160],[33162,33162],[33167,33167],[33169,33169],[33176,33177],[33179,33181],[33187,33187],[33190,33190],[33192,33192],[33194,33194],[33203,33203],[33210,33211],[33216,33219],[33222,33222],[33226,33226],[33228,33228],[33233,33233],[33244,33244],[33251,33251],[33255,33255],[33258,33258],[33260,33261],[33267,33268],[33275,33276],[33278,33278],[33280,33282],[33284,33286],[33292,33293],[33296,33296],[33298,33298],[33300,33300],[33307,33308],[33310,33315],[33317,33317],[33320,33320],[33322,33325],[33327,33337],[33339,33339],[33342,33342],[33348,33349],[33351,33351],[33353,33353],[33355,33355],[33358,33359],[33368,33368],[33370,33370],[33375,33375],[33384,33384],[33390,33392],[33394,33396],[33401,33402],[33405,33407],[33410,33412],[33416,33416],[33418,33419],[33421,33423],[33425,33426],[33431,33433],[33436,33437],[33439,33441],[33443,33446],[33448,33457],[33459,33460],[33463,33465],[33468,33470],[33473,33473],[33476,33476],[33479,33487],[33489,33493],[33495,33496],[33499,33500],[33502,33505],[33507,33511],[33515,33515],[33519,33519],[33521,33521],[33524,33524],[33527,33527],[33529,33529],[33531,33531],[33534,33534],[33536,33545],[33547,33548],[33550,33551],[33553,33553],[33555,33557],[33559,33559],[33562,33565],[33575,33576],[33579,33581],[33583,33583],[33585,33585],[33587,33590],[33592,33594],[33596,33597],[33600,33601],[33603,33604],[33606,33607],[33609,33609],[33615,33620],[33622,33622],[33625,33628],[33630,33633],[33635,33647],[33655,33656],[33659,33661],[33669,33670],[33673,33673],[33678,33678],[33682,33683],[33688,33689],[33691,33694],[33696,33696],[33704,33707],[33712,33716],[33718,33722],[33724,33725],[33727,33730],[33733,33733],[33735,33735],[33737,33738],[33740,33741],[33743,33743],[33748,33748],[33750,33750],[33752,33752],[33756,33757],[33759,33761],[33765,33765],[33769,33770],[33776,33778],[33784,33785],[33788,33789],[33793,33793],[33795,33796],[33798,33798],[33803,33807],[33809,33809],[33816,33816],[33818,33818],[33820,33821],[33827,33833],[33841,33841],[33843,33843],[33848,33849],[33852,33853],[33862,33862],[33870,33870],[33873,33873],[33878,33879],[33881,33884],[33889,33889],[33891,33891],[33897,33897],[33899,33901],[33904,33905],[33907,33910],[33912,33912],[33914,33914],[33922,33922],[33924,33924],[33927,33929],[33931,33932],[33934,33934],[33936,33936],[33943,33943],[33945,33945],[33948,33948],[33951,33951],[33953,33953],[33960,33960],[33967,33967],[33969,33970],[33972,33972],[33976,33979],[33981,33981],[33983,33983],[33985,33986],[33988,33988],[33991,33991],[33993,33994],[33997,33997],[33999,34001],[34003,34003],[34006,34006],[34013,34013],[34015,34016],[34018,34019],[34021,34022],[34028,34028],[34032,34032],[34044,34044],[34047,34048],[34051,34051],[34056,34056],[34058,34058],[34060,34060],[34065,34065],[34067,34067],[34071,34071],[34074,34074],[34079,34079],[34081,34081],[34091,34092],[34103,34109],[34115,34115],[34120,34122],[34134,34135],[34137,34137],[34142,34142],[34148,34148],[34152,34152],[34160,34160],[34162,34162],[34164,34164],[34169,34171],[34174,34174],[34177,34177],[34180,34181],[34183,34183],[34191,34191],[34203,34204],[34210,34210],[34212,34212],[34216,34216],[34218,34218],[34222,34224],[34227,34227],[34231,34233],[34239,34239],[34241,34241],[34249,34249],[34255,34256],[34259,34259],[34261,34261],[34268,34268],[34271,34272],[34276,34276],[34278,34278],[34280,34281],[34299,34299],[34303,34303],[34309,34309],[34321,34321],[34326,34326],[34328,34328],[34343,34343],[34345,34345],[34360,34360],[34364,34364],[34381,34388],[34394,34394],[34398,34398],[34402,34402],[34404,34404],[34411,34412],[34414,34414],[34417,34417],[34423,34434],[34436,34436],[34438,34438],[34442,34445],[34451,34451],[34453,34453],[34460,34461],[34467,34468],[34471,34474],[34476,34476],[34479,34482],[34484,34486],[34490,34490],[34496,34496],[34499,34500],[34502,34503],[34505,34507],[34510,34513],[34516,34516],[34520,34521],[34523,34523],[34526,34527],[34532,34532],[34537,34537],[34541,34542],[34544,34548],[34552,34553],[34558,34558],[34560,34560],[34562,34563],[34567,34570],[34573,34574],[34576,34576],[34578,34579],[34581,34581],[34583,34584],[34586,34586],[34588,34588],[34590,34590],[34593,34595],[34597,34597],[34601,34601],[34606,34606],[34609,34609],[34612,34612],[34615,34615],[34619,34619],[34622,34623],[34631,34633],[34636,34636],[34638,34638],[34643,34643],[34647,34649],[34656,34656],[34659,34661],[34670,34670],[34672,34672],[34674,34674],[34676,34676],[34678,34678],[34683,34686],[34690,34691],[34693,34693],[34696,34696],[34699,34699],[34701,34701],[34707,34707],[34711,34711],[34719,34720],[34723,34723],[34728,34728],[34731,34733],[34735,34735],[34737,34737],[34739,34739],[34741,34741],[34746,34746],[34749,34749],[34752,34752],[34758,34758],[34762,34763],[34767,34767],[34769,34771],[34779,34779],[34784,34784],[34789,34789],[34794,34795],[34798,34798],[34809,34809],[34814,34814],[34819,34819],[34826,34827],[34835,34835],[34837,34838],[34843,34843],[34849,34850],[34866,34866],[34873,34873],[34876,34876],[34880,34880],[34883,34885],[34892,34894],[34898,34898],[34900,34900],[34903,34903],[34905,34905],[34912,34917],[34920,34921],[34923,34924],[34926,34926],[34928,34928],[34930,34930],[34935,34935],[34941,34943],[34945,34946],[34948,34950],[34952,34952],[34955,34955],[34957,34957],[34962,34962],[34966,34967],[34972,34972],[34978,34978],[34980,34980],[34986,34987],[34989,34989],[34991,34991],[34993,34993],[34999,34999],[35004,35004],[35009,35010],[35013,35014],[35016,35017],[35022,35022],[35026,35026],[35028,35029],[35032,35033],[35035,35035],[35039,35039],[35042,35045],[35048,35048],[35056,35057],[35059,35060],[35064,35065],[35068,35068],[35070,35070],[35074,35074],[35082,35082],[35088,35088],[35090,35091],[35093,35093],[35097,35099],[35103,35103],[35105,35105],[35109,35109],[35114,35115],[35119,35120],[35124,35124],[35126,35126],[35137,35137],[35140,35140],[35157,35157],[35162,35162],[35164,35164],[35166,35167],[35174,35174],[35179,35179],[35195,35195],[35199,35199],[35201,35201],[35203,35203],[35206,35206],[35265,35276],[35278,35282],[35286,35286],[35290,35290],[35292,35292],[35294,35295],[35299,35299],[35301,35302],[35307,35307],[35309,35309],[35311,35311],[35313,35313],[35315,35315],[35327,35328],[35332,35332],[35335,35335],[35354,35354],[35390,35390],[35400,35400],[35423,35423],[35449,35449],[35465,35466],[35475,35475],[35591,35591],[35622,35622],[35686,35686],[35692,35692],[35744,35755],[35757,35817],[35819,35848],[35850,35895],[35900,35900],[35903,35903],[35905,35905],[35910,35911],[35913,35913],[35916,35916],[35925,35925],[35930,35930],[35937,35938],[35944,35944],[35946,35947],[35950,35950],[35955,35955],[35960,35962],[35970,35970],[35973,35974],[35977,35978],[35980,35980],[35988,35988],[35992,35992],[36125,36127],[36129,36196],[36198,36199],[36202,36203],[36205,36205],[36208,36208],[36211,36215],[36225,36225],[36228,36229],[36234,36235],[36241,36241],[36244,36244],[36255,36255],[36259,36259],[36271,36271],[36273,36273],[36275,36277],[36280,36280],[36282,36282],[36284,36284],[36286,36287],[36290,36292],[36294,36294],[36299,36300],[36302,36305],[36310,36311],[36314,36315],[36317,36319],[36323,36324],[36328,36328],[36330,36332],[36335,36335],[36337,36337],[36339,36339],[36341,36347],[36349,36349],[36357,36357],[36361,36362],[36364,36364],[36367,36367],[36370,36370],[36372,36372],[36381,36383],[36386,36387],[36390,36390],[36393,36394],[36396,36396],[36398,36399],[36401,36401],[36405,36406],[36409,36410],[36413,36413],[36416,36418],[36420,36421],[36423,36427],[36432,36434],[36441,36442],[36444,36444],[36450,36450],[36454,36454],[36457,36457],[36460,36461],[36463,36464],[36466,36466],[36468,36468],[36470,36470],[36476,36479],[36481,36481],[36485,36485],[36487,36487],[36495,36496],[36500,36500],[36508,36508],[36510,36510],[36523,36524],[36527,36527],[36530,36530],[36538,36538],[36558,36558],[36710,36764],[36766,36767],[36771,36771],[36776,36777],[36779,36779],[36784,36785],[36790,36790],[36793,36793],[36797,36799],[36801,36802],[36804,36805],[36807,36808],[36814,36814],[36816,36817],[36819,36821],[36824,36825],[36827,36831],[36834,36834],[36836,36838],[36840,36843],[36845,36846],[36848,36848],[36851,36851],[36855,36858],[36861,36861],[36864,36870],[36873,36875],[36877,36877],[36879,36882],[36884,36884],[36886,36887],[36890,36891],[36893,36898],[36902,36902],[36909,36911],[36916,36918],[36920,36920],[36923,36924],[36926,36926],[36929,36930],[36932,36932],[36934,36935],[36941,36941],[36943,36947],[36951,36952],[36955,36955],[36962,36963],[36965,36965],[36968,36968],[36973,36974],[36980,36981],[36985,36985],[36989,36989],[36991,36992],[36994,36995],[37000,37000],[37003,37003],[37009,37009],[37011,37011],[37013,37013],[37015,37017],[37019,37019],[37021,37021],[37024,37027],[37030,37030],[37032,37032],[37034,37034],[37036,37036],[37038,37046],[37048,37051],[37053,37055],[37057,37057],[37059,37061],[37063,37064],[37066,37066],[37070,37073],[37075,37075],[37079,37079],[37082,37085],[37089,37090],[37092,37092],[37094,37096],[37098,37099],[37101,37101],[37103,37103],[37108,37108],[37112,37112],[37117,37120],[37122,37125],[37132,37132],[37137,37137],[37143,37146],[37148,37148],[37150,37150],[37152,37152],[37154,37155],[37163,37163],[37167,37167],[37169,37169],[37177,37177],[37186,37187],[37189,37190],[37193,37200],[37202,37202],[37207,37207],[37210,37210],[37213,37214],[37217,37222],[37225,37226],[37228,37228],[37230,37234],[37236,37242],[37245,37247],[37253,37253],[37255,37255],[37257,37257],[37259,37261],[37264,37266],[37274,37275],[37282,37283],[37288,37288],[37290,37290],[37293,37295],[37300,37301],[37306,37306],[37310,37310],[37319,37319],[37321,37322],[37324,37329],[37340,37340],[37492,37492],[37518,37518],[37550,37550],[37574,37574],[37576,37576],[37694,37694],[37738,37738],[37775,37775],[37834,37834],[37846,37846],[37950,37950],[37995,37995],[38021,38032],[38034,38086],[38088,38098],[38101,38117],[38119,38175],[38177,38262],[38271,38271],[38376,38379],[38381,38418],[38420,38426],[38428,38429],[38431,38431],[38433,38434],[38442,38442],[38446,38446],[38449,38454],[38459,38461],[38463,38464],[38466,38466],[38468,38473],[38475,38478],[38480,38481],[38484,38485],[38491,38491],[38494,38495],[38497,38498],[38500,38500],[38503,38506],[38508,38508],[38514,38514],[38516,38519],[38531,38531],[38533,38534],[38536,38536],[38539,38539],[38541,38541],[38543,38544],[38548,38548],[38551,38553],[38556,38556],[38567,38567],[38569,38569],[38576,38576],[38579,38579],[38582,38582],[38585,38586],[38588,38590],[38592,38593],[38596,38599],[38601,38602],[38604,38607],[38610,38610],[38613,38613],[38624,38624],[38632,38634],[38639,38639],[38641,38641],[38643,38643],[38646,38647],[38649,38649],[38654,38654],[38656,38657],[38660,38665],[38669,38671],[38675,38675],[38678,38678],[38684,38684],[38686,38686],[38696,38696],[38698,38698],[38701,38701],[38704,38704],[38706,38706],[38712,38713],[38718,38718],[38738,38739],[38742,38742],[38745,38745],[38747,38747],[38750,38750],[38752,38754],[38757,38757],[38761,38761],[38764,38764],[38768,38768],[38771,38772],[38774,38774],[38776,38776],[38778,38778],[38780,38781],[38783,38783],[38785,38785],[38789,38789],[38795,38795],[38797,38797],[38801,38802],[38804,38804],[38808,38808],[38816,38817],[38819,38819],[38823,38824],[38827,38831],[38834,38836],[38850,38850],[38886,38893],[38899,38899],[38901,38902],[39029,39057],[39059,39060],[39062,39074],[39076,39079],[39118,39125],[39127,39130],[39134,39135],[39143,39144],[39181,39181],[39184,39184],[39214,39214],[39252,39253],[39267,39267],[39269,39269],[39271,39293],[39295,39297],[39299,39309],[39311,39321],[39325,39326],[39333,39333],[39335,39336],[39532,39571],[39573,39592],[39600,39601],[39606,39608],[39610,39610],[39612,39612],[39616,39619],[39621,39621],[39627,39628],[39630,39630],[39633,39633],[39635,39635],[39640,39640],[39647,39647],[39649,39650],[39654,39654],[39659,39659],[39661,39661],[39663,39663],[39673,39673],[39675,39675],[39677,39677],[39683,39683],[39688,39688],[39695,39695],[39698,39699],[39704,39704],[39711,39711],[39715,39715],[39727,39727],[39730,39730],[39734,39735],[39739,39740],[39745,39753],[39755,39755],[39757,39757],[39759,39759],[39761,39761],[39764,39764],[40060,40067],[40069,40082],[40084,40164],[40479,40499],[40501,40530],[40532,40548],[40550,40564],[40574,40576],[40578,40578],[40583,40584],[40587,40587],[40593,40595],[40598,40598],[40605,40605],[40607,40607],[40614,40614],[40628,40628],[40632,40633],[40635,40635],[40637,40638],[40644,40644],[40647,40647],[40649,40649],[40653,40655],[40657,40657],[40660,40660],[40664,40664],[40667,40669],[40671,40674],[40677,40677],[40679,40679],[40681,40682],[40687,40687],[40697,40697],[40699,40700],[40702,40702],[40715,40715],[40717,40718],[40720,40720],[40722,40723],[40727,40727],[40729,40729],[40736,40736],[40738,40738],[40745,40745],[40747,40748],[40751,40751],[40753,40753],[40759,40759],[40761,40761],[40763,40763],[40765,40766],[40769,40769],[40772,40772],[40775,40775],[40777,40777],[40784,40785],[40831,40844],[40857,40859],[40863,40864],[40866,40866],[40909,40911],[65072,65103],[65281,65470],[65474,65479],[65482,65487],[65490,65495],[65498,65500],[65504,65510],[65512,65518],[131428,131428],[132726,132726],[134352,134352],[136090,136090],[136211,136211],[144843,144843],[146583,146584],[146979,146979],[149979,149979],[150141,150141],[150217,150217],[152882,152882],[152930,152930],[153000,153000],[155351,155351],[156193,156193],[156813,156813],[157302,157302],[157564,157564],[158556,158556],[158753,158753],[163833,163833],[164872,164872],[165496,165496],[165525,165525],[165856,165856],[166729,166729],[166983,166983],[166991,166991],[166993,166993],[166996,166996],[167577,167577],[171902,171902],[171907,171907],[171916,171916],[174045,174045],[174331,174331],[174359,174359],[174640,174640],[174646,174646],[174680,174680],[176034,176034],[176423,176424],[176439,176440],[176621,176621],[176896,176896],[176995,176995],[177007,177007],[177010,177010],[177021,177021],[177156,177156],[177168,177168],[177171,177171],[177249,177249],[177383,177383],[177391,177391],[177398,177398],[177401,177401],[177421,177422],[177462,177462],[177582,177583],[177587,177587],[177639,177639],[177652,177652],[177692,177693],[177702,177704],[177706,177706],[177708,177708],[177813,177814],[177837,177837],[177901,177901],[178089,178089],[178117,178117],[178150,178150],[178169,178169],[178172,178172],[178182,178182],[178186,178186],[178204,178204],[178360,178360],[178887,178887],[179039,179039],[179042,179042],[179068,179068],[179075,179075],[179227,179227],[179575,179575],[179591,179591],[179703,179703],[179753,179753],[180265,180266],[180393,180393],[180426,180426],[180693,180693],[180697,180697],[180729,180729],[180860,180860],[180872,180872],[180900,180900],[181015,181015],[181083,181083],[181089,181089],[181092,181092],[181384,181384],[181396,181396],[181399,181399],[181570,181570],[181779,181779],[181784,181784],[181793,181793],[181801,181801],[181803,181805],[181807,181807],[181826,181826],[181834,181835],[182060,182060],[182063,182063],[182175,182175],[182209,182209],[182269,182269],[182489,182489],[182494,182494],[182497,182497],[182515,182515],[182535,182535],[182538,182538],[182557,182557],[182786,182786],[182798,182798],[182909,182909],[182953,182953],[183081,183081],[183085,183086],[183089,183089],[183096,183097],[183099,183099],[183103,183103],[183105,183105],[183114,183114],[183118,183118],[183130,183131],[183140,183140],[183145,183145],[183148,183148],[183151,183151],[183155,183155],[183158,183158],[183160,183160],[183164,183164],[183217,183217],[183231,183232],[183246,183246],[183382,183382],[183391,183391],[183541,183542],[183549,183549],[183551,183551],[183554,183555],[183562,183562],[183691,183691],[183693,183693],[183695,183696],[183711,183712],[183720,183720],[183725,183726],[183765,183765],[183832,183832],[183834,183834],[183843,183843],[183846,183846],[183850,183850],[183932,183932],[183944,183944],[183955,183955]]},"700":{"file":"FreeVideoSansSC-Bold.woff2","sha256":"df97f7da0b8568ea7fa3f09814b93f97ffcbeb07044b6b2c0c8f98402d3b2b68","ranges":[[32,126],[160,259],[272,275],[282,283],[296,299],[323,324],[327,328],[332,335],[338,339],[360,365],[462,462],[464,464],[466,466],[468,468],[470,470],[472,472],[474,474],[476,476],[711,711],[713,713],[913,929],[931,937],[945,961],[963,969],[1025,1025],[1040,1103],[1105,1105],[8194,8195],[8208,8214],[8216,8218],[8220,8222],[8224,8226],[8229,8231],[8240,8240],[8242,8243],[8245,8245],[8249,8252],[8258,8258],[8263,8265],[8273,8273],[8451,8451],[8470,8470],[8544,8555],[8592,8601],[8632,8633],[8644,8646],[8651,8652],[8656,8656],[8658,8658],[8660,8660],[8678,8681],[8693,8693],[8712,8712],[8715,8715],[8719,8719],[8721,8721],[8730,8730],[8733,8734],[8736,8736],[8741,8741],[8743,8747],[8750,8750],[8756,8759],[8765,8765],[8773,8773],[8776,8776],[8780,8780],[8800,8801],[8804,8805],[8814,8815],[8857,8857],[8869,8869],[8978,8978],[9312,9547],[9632,9643],[9649,9651],[9654,9655],[9660,9661],[9664,9665],[9670,9671],[9673,9676],[9678,9683],[9698,9702],[9711,9711],[9728,9731],[9733,9734],[9737,9737],[9742,9743],[9750,9751],[9756,9759],[9775,9775],[9792,9794],[9824,9839],[9842,9853],[9888,9888],[9917,9918],[12288,12351],[12353,12438],[12441,12543],[12549,12585],[12832,12841],[13383,13383],[13386,13386],[13678,13678],[13838,13838],[13901,13901],[13912,13912],[13926,13926],[14019,14019],[14042,14042],[14073,14073],[14275,14275],[14343,14343],[14355,14355],[14616,14616],[14660,14660],[14800,14801],[14815,14815],[15088,15088],[15114,15114],[15118,15118],[15130,15130],[15182,15182],[15189,15189],[15294,15294],[15360,15360],[15559,15559],[15576,15576],[15578,15578],[15636,15636],[15696,15696],[15794,15794],[15878,15878],[15884,15884],[16004,16004],[16108,16108],[16207,16207],[16352,16352],[16470,16470],[16558,16558],[16581,16581],[16590,16590],[16735,16735],[17209,17209],[17283,17283],[17302,17302],[17373,17373],[17377,17377],[17394,17394],[17411,17411],[17622,17622],[17627,17627],[17640,17640],[17643,17644],[17878,17878],[17883,17883],[17898,17898],[17908,17908],[18211,18211],[18265,18265],[18618,18618],[18620,18620],[18648,18648],[18813,18813],[18819,18819],[19615,19616],[19618,19618],[19731,19737],[19886,19886],[19968,19969],[19971,19971],[19975,19985],[19987,19990],[19992,19998],[20002,20002],[20004,20005],[20007,20008],[20010,20013],[20016,20016],[20018,20018],[20020,20020],[20022,20022],[20024,20027],[20029,20031],[20034,20035],[20037,20037],[20039,20041],[20043,20048],[20050,20052],[20054,20054],[20056,20057],[20060,20065],[20070,20070],[20073,20073],[20080,20081],[20083,20083],[20088,20088],[20094,20094],[20102,20102],[20104,20105],[20107,20111],[20113,20117],[20120,20120],[20122,20123],[20127,20130],[20132,20137],[20139,20142],[20146,20147],[20149,20150],[20152,20155],[20159,20167],[20169,20171],[20173,20174],[20177,20177],[20179,20185],[20189,20191],[20193,20193],[20195,20197],[20200,20200],[20202,20204],[20208,20208],[20210,20211],[20213,20215],[20219,20219],[20221,20221],[20223,20223],[20225,20225],[20232,20235],[20237,20241],[20247,20251],[20254,20256],[20258,20263],[20266,20267],[20269,20269],[20271,20272],[20274,20274],[20276,20276],[20278,20278],[20280,20280],[20282,20282],[20284,20286],[20289,20289],[20291,20291],[20294,20294],[20301,20305],[20307,20307],[20309,20320],[20323,20325],[20327,20327],[20329,20329],[20332,20332],[20335,20336],[20339,20340],[20342,20342],[20344,20344],[20346,20351],[20353,20356],[20360,20361],[20363,20363],[20365,20365],[20367,20367],[20369,20369],[20372,20372],[20375,20376],[20379,20379],[20381,20381],[20384,20384],[20387,20387],[20389,20394],[20396,20396],[20398,20399],[20404,20405],[20409,20409],[20415,20415],[20419,20421],[20426,20426],[20429,20433],[20439,20442],[20444,20447],[20449,20449],[20451,20451],[20454,20454],[20456,20459],[20461,20463],[20465,20465],[20467,20467],[20469,20470],[20472,20472],[20474,20474],[20478,20478],[20492,20493],[20495,20495],[20498,20501],[20504,20506],[20508,20508],[20510,20511],[20513,20513],[20517,20522],[20524,20526],[20532,20532],[20538,20540],[20542,20542],[20545,20545],[20547,20547],[20551,20552],[20556,20556],[20558,20559],[20563,20563],[20565,20565],[20570,20570],[20572,20572],[20577,20577],[20581,20581],[20588,20589],[20592,20592],[20594,20594],[20598,20599],[20603,20603],[20606,20608],[20611,20611],[20613,20613],[20616,20617],[20621,20621],[20626,20626],[20629,20629],[20643,20643],[20645,20645],[20647,20649],[20652,20652],[20658,20658],[20666,20667],[20679,20679],[20686,20687],[20692,20692],[20694,20694],[20698,20698],[20710,20711],[20716,20718],[20720,20720],[20723,20723],[20725,20725],[20731,20731],[20742,20743],[20747,20747],[20754,20754],[20769,20769],[20774,20774],[20787,20788],[20799,20801],[20803,20806],[20808,20809],[20811,20811],[20813,20813],[20817,20817],[20820,20822],[20826,20826],[20828,20828],[20834,20834],[20837,20837],[20840,20840],[20843,20846],[20848,20849],[20851,20857],[20859,20861],[20864,20866],[20869,20869],[20872,20873],[20876,20877],[20879,20879],[20882,20882],[20884,20887],[20889,20889],[20891,20892],[20896,20896],[20898,20898],[20900,20901],[20907,20908],[20910,20915],[20917,20919],[20923,20925],[20928,20928],[20932,20932],[20934,20935],[20937,20937],[20939,20940],[20943,20943],[20945,20945],[20947,20947],[20952,20952],[20955,20955],[20957,20957],[20960,20961],[20964,20964],[20971,20971],[20973,20973],[20975,20976],[20979,20979],[20981,20982],[20984,20989],[20991,20995],[20998,21000],[21002,21002],[21005,21006],[21009,21010],[21014,21019],[21021,21021],[21024,21024],[21028,21028],[21032,21033],[21035,21038],[21040,21040],[21043,21043],[21046,21051],[21053,21053],[21055,21059],[21061,21061],[21066,21069],[21072,21073],[21076,21078],[21084,21084],[21086,21087],[21089,21089],[21093,21093],[21095,21095],[21097,21098],[21103,21103],[21106,21106],[21117,21117],[21119,21119],[21121,21122],[21124,21124],[21128,21128],[21136,21136],[21139,21139],[21147,21147],[21149,21155],[21160,21165],[21169,21171],[21180,21180],[21182,21183],[21187,21187],[21191,21191],[21193,21193],[21195,21195],[21197,21197],[21200,21200],[21202,21202],[21204,21204],[21206,21206],[21208,21208],[21210,21210],[21215,21216],[21220,21220],[21232,21232],[21241,21242],[21246,21248],[21253,21254],[21256,21256],[21261,21261],[21263,21264],[21269,21271],[21273,21274],[21276,21277],[21280,21281],[21283,21283],[21286,21286],[21290,21290],[21294,21294],[21305,21308],[21310,21311],[21313,21313],[21315,21315],[21317,21317],[21319,21322],[21326,21327],[21329,21331],[21333,21335],[21338,21338],[21340,21340],[21342,21348],[21350,21351],[21353,21353],[21355,21356],[21358,21361],[21363,21365],[21367,21368],[21370,21370],[21375,21375],[21378,21378],[21380,21382],[21385,21385],[21387,21389],[21397,21398],[21400,21400],[21402,21402],[21405,21405],[21407,21407],[21410,21411],[21413,21414],[21416,21417],[21422,21422],[21430,21430],[21435,21435],[21438,21439],[21441,21442],[21446,21453],[21457,21457],[21460,21467],[21471,21472],[21475,21478],[21480,21491],[21493,21497],[21499,21501],[21505,21505],[21507,21508],[21510,21510],[21512,21514],[21516,21523],[21525,21527],[21531,21531],[21533,21537],[21539,21539],[21542,21545],[21547,21551],[21553,21554],[21556,21557],[21560,21561],[21563,21566],[21568,21568],[21571,21571],[21574,21576],[21578,21579],[21584,21584],[21586,21593],[21595,21596],[21602,21604],[21606,21606],[21608,21608],[21617,21619],[21621,21624],[21627,21629],[21632,21632],[21634,21634],[21636,21636],[21638,21639],[21641,21641],[21643,21648],[21650,21650],[21652,21654],[21657,21659],[21661,21661],[21665,21665],[21667,21677],[21679,21679],[21681,21681],[21683,21684],[21688,21688],[21690,21691],[21693,21693],[21695,21700],[21702,21705],[21708,21717],[21719,21719],[21721,21722],[21724,21727],[21730,21730],[21733,21738],[21741,21742],[21745,21747],[21754,21754],[21756,21757],[21759,21759],[21761,21761],[21766,21767],[21769,21769],[21775,21777],[21780,21780],[21787,21787],[21789,21789],[21792,21792],[21794,21796],[21799,21799],[21802,21802],[21804,21804],[21806,21809],[21811,21811],[21813,21813],[21815,21815],[21820,21820],[21822,21823],[21825,21825],[21827,21828],[21830,21830],[21833,21834],[21840,21840],[21845,21846],[21852,21852],[21857,21857],[21860,21863],[21866,21870],[21872,21872],[21876,21880],[21883,21884],[21886,21886],[21888,21892],[21894,21899],[21903,21903],[21905,21905],[21908,21908],[21912,21913],[21916,21917],[21919,21919],[21924,21924],[21927,21927],[21937,21937],[21939,21939],[21941,21941],[21943,21943],[21945,21945],[21947,21947],[21949,21950],[21956,21957],[21961,21961],[21964,21965],[21968,21972],[21974,21974],[21980,21983],[21985,21985],[21987,21990],[21992,21992],[21994,21996],[21999,21999],[22002,22003],[22005,22005],[22007,22007],[22013,22014],[22016,22017],[22024,22025],[22028,22028],[22030,22031],[22040,22040],[22042,22043],[22046,22047],[22049,22049],[22051,22052],[22055,22055],[22060,22061],[22065,22066],[22068,22068],[22070,22070],[22073,22073],[22075,22075],[22079,22080],[22082,22082],[22087,22087],[22092,22094],[22100,22100],[22103,22105],[22108,22108],[22114,22114],[22116,22116],[22120,22124],[22129,22129],[22134,22134],[22139,22140],[22148,22150],[22158,22159],[22163,22163],[22170,22170],[22179,22179],[22189,22189],[22191,22191],[22199,22199],[22204,22204],[22218,22218],[22228,22228],[22231,22231],[22234,22235],[22237,22242],[22244,22244],[22251,22251],[22253,22253],[22256,22257],[22260,22261],[22263,22263],[22265,22266],[22269,22271],[22275,22276],[22278,22278],[22280,22282],[22284,22284],[22288,22288],[22297,22297],[22300,22300],[22303,22303],[22306,22307],[22312,22320],[22322,22323],[22329,22331],[22334,22334],[22336,22336],[22338,22338],[22343,22343],[22345,22354],[22359,22359],[22362,22369],[22372,22374],[22376,22381],[22383,22384],[22387,22387],[22390,22391],[22395,22397],[22402,22406],[22408,22408],[22411,22415],[22418,22419],[22421,22421],[22425,22427],[22430,22436],[22438,22439],[22441,22441],[22443,22443],[22445,22447],[22449,22450],[22452,22453],[22456,22456],[22458,22458],[22462,22463],[22466,22467],[22470,22471],[22475,22476],[22478,22479],[22482,22482],[22484,22485],[22487,22490],[22493,22493],[22495,22496],[22500,22500],[22506,22507],[22509,22509],[22511,22511],[22516,22517],[22520,22522],[22524,22525],[22528,22528],[22530,22531],[22534,22535],[22537,22537],[22539,22542],[22544,22545],[22549,22549],[22553,22553],[22558,22558],[22560,22561],[22564,22564],[22567,22568],[22570,22570],[22576,22576],[22578,22578],[22581,22581],[22588,22590],[22596,22598],[22604,22605],[22609,22609],[22612,22612],[22616,22616],[22621,22622],[22629,22629],[22635,22636],[22641,22641],[22654,22654],[22656,22657],[22659,22659],[22661,22661],[22664,22665],[22672,22672],[22674,22675],[22677,22677],[22680,22682],[22686,22687],[22689,22689],[22691,22691],[22694,22694],[22696,22697],[22716,22716],[22721,22721],[22725,22725],[22737,22737],[22741,22741],[22756,22756],[22763,22764],[22766,22766],[22768,22768],[22771,22771],[22774,22774],[22776,22777],[22786,22786],[22788,22788],[22791,22791],[22797,22797],[22799,22800],[22804,22806],[22809,22810],[22812,22812],[22815,22815],[22820,22821],[22823,22823],[22825,22831],[22833,22833],[22836,22836],[22839,22842],[22844,22844],[22849,22850],[22852,22852],[22855,22857],[22859,22859],[22862,22863],[22865,22865],[22867,22872],[22874,22874],[22880,22882],[22885,22885],[22893,22893],[22899,22900],[22902,22902],[22904,22905],[22909,22909],[22913,22916],[22918,22920],[22922,22922],[22925,22925],[22930,22931],[22934,22937],[22942,22942],[22947,22949],[22951,22955],[22957,22959],[22962,22962],[22969,22969],[22971,22971],[22974,22974],[22982,22982],[22984,22984],[22986,22987],[22992,22996],[22999,23000],[23002,23002],[23004,23006],[23011,23013],[23016,23016],[23020,23020],[23022,23022],[23025,23025],[23030,23030],[23033,23033],[23035,23035],[23037,23037],[23039,23041],[23043,23049],[23052,23052],[23057,23057],[23059,23059],[23064,23064],[23068,23068],[23071,23072],[23075,23075],[23077,23077],[23081,23081],[23089,23090],[23092,23094],[23100,23100],[23104,23104],[23110,23110],[23113,23114],[23116,23117],[23125,23125],[23128,23128],[23130,23130],[23134,23134],[23136,23136],[23138,23138],[23140,23140],[23143,23143],[23146,23147],[23155,23159],[23162,23164],[23167,23167],[23170,23170],[23172,23172],[23174,23174],[23186,23187],[23190,23190],[23194,23195],[23198,23198],[23210,23210],[23213,23213],[23217,23219],[23221,23221],[23224,23224],[23230,23230],[23233,23234],[23236,23236],[23241,23241],[23244,23244],[23250,23250],[23252,23254],[23256,23256],[23258,23258],[23260,23260],[23264,23265],[23267,23267],[23270,23270],[23273,23275],[23277,23277],[23281,23281],[23293,23293],[23305,23305],[23318,23319],[23323,23323],[23333,23333],[23340,23340],[23346,23346],[23348,23348],[23351,23351],[23359,23360],[23365,23365],[23376,23377],[23379,23389],[23391,23391],[23394,23398],[23401,23402],[23404,23404],[23408,23409],[23411,23411],[23413,23413],[23418,23418],[23421,23421],[23424,23425],[23427,23429],[23431,23433],[23435,23436],[23439,23439],[23443,23443],[23445,23445],[23447,23454],[23456,23463],[23466,23468],[23472,23472],[23475,23478],[23480,23481],[23485,23487],[23489,23490],[23492,23495],[23500,23500],[23504,23504],[23506,23507],[23517,23519],[23521,23521],[23524,23525],[23528,23528],[23534,23534],[23536,23536],[23544,23548],[23551,23551],[23553,23553],[23556,23556],[23558,23558],[23561,23562],[23567,23567],[23569,23569],[23572,23574],[23576,23576],[23578,23578],[23580,23581],[23586,23586],[23588,23589],[23591,23592],[23594,23594],[23596,23596],[23601,23601],[23604,23604],[23608,23619],[23621,23621],[23624,23627],[23630,23633],[23637,23637],[23641,23641],[23646,23646],[23648,23649],[23651,23651],[23653,23654],[23662,23663],[23665,23665],[23673,23674],[23676,23676],[23678,23679],[23681,23682],[23688,23688],[23690,23690],[23692,23693],[23696,23697],[23700,23700],[23702,23708],[23710,23710],[23712,23712],[23714,23715],[23720,23721],[23723,23725],[23729,23729],[23731,23731],[23733,23733],[23735,23736],[23741,23741],[23743,23743],[23745,23748],[23755,23755],[23762,23762],[23767,23769],[23771,23771],[23777,23777],[23779,23784],[23786,23786],[23789,23789],[23792,23793],[23803,23803],[23807,23812],[23814,23815],[23820,23820],[23822,23822],[23826,23826],[23828,23828],[23830,23830],[23834,23835],[23838,23839],[23841,23841],[23844,23844],[23846,23847],[23849,23849],[23853,23854],[23860,23860],[23862,23862],[23869,23871],[23873,23873],[23877,23877],[23879,23879],[23882,23884],[23886,23886],[23894,23894],[23896,23896],[23898,23899],[23901,23901],[23913,23913],[23915,23916],[23919,23919],[23922,23922],[23924,23924],[23938,23938],[23941,23941],[23949,23949],[23954,23955],[23961,23961],[23965,23965],[23967,23967],[23974,23974],[23986,23986],[23991,23991],[24005,24005],[24007,24007],[24009,24009],[24013,24013],[24027,24027],[24029,24030],[24033,24034],[24037,24041],[24043,24043],[24046,24047],[24049,24052],[24055,24055],[24061,24062],[24065,24067],[24069,24070],[24072,24072],[24076,24076],[24079,24081],[24084,24086],[24088,24093],[24097,24097],[24102,24104],[24109,24110],[24113,24113],[24119,24120],[24123,24125],[24130,24130],[24132,24133],[24140,24140],[24148,24150],[24155,24155],[24158,24158],[24161,24162],[24170,24170],[24178,24180],[24182,24182],[24184,24184],[24186,24189],[24191,24192],[24196,24196],[24198,24199],[24202,24203],[24207,24209],[24211,24215],[24217,24218],[24220,24220],[24222,24224],[24228,24231],[24237,24237],[24241,24241],[24243,24243],[24245,24249],[24252,24252],[24254,24254],[24262,24262],[24265,24267],[24273,24275],[24278,24278],[24281,24281],[24283,24283],[24296,24296],[24298,24298],[24308,24308],[24310,24311],[24314,24314],[24318,24324],[24326,24328],[24330,24331],[24335,24335],[24337,24337],[24339,24339],[24341,24341],[24343,24344],[24347,24347],[24351,24352],[24354,24354],[24357,24362],[24365,24365],[24367,24367],[24369,24369],[24374,24374],[24376,24378],[24380,24380],[24384,24384],[24400,24400],[24402,24403],[24405,24408],[24413,24413],[24415,24415],[24417,24418],[24420,24420],[24422,24423],[24425,24426],[24428,24429],[24432,24433],[24435,24435],[24439,24439],[24441,24441],[24443,24444],[24448,24450],[24452,24453],[24455,24460],[24464,24464],[24466,24466],[24469,24469],[24471,24473],[24475,24476],[24481,24481],[24488,24488],[24490,24490],[24493,24494],[24501,24501],[24503,24503],[24508,24509],[24515,24518],[24521,24521],[24524,24525],[24527,24530],[24534,24537],[24541,24542],[24544,24545],[24548,24548],[24551,24551],[24554,24555],[24557,24558],[24561,24561],[24563,24563],[24565,24565],[24568,24568],[24570,24571],[24573,24582],[24586,24586],[24589,24591],[24594,24594],[24596,24598],[24601,24601],[24603,24605],[24608,24609],[24613,24619],[24623,24623],[24629,24629],[24635,24636],[24639,24639],[24641,24643],[24651,24651],[24653,24653],[24656,24656],[24658,24661],[24665,24666],[24669,24669],[24674,24676],[24679,24685],[24687,24688],[24691,24691],[24694,24694],[24696,24701],[24703,24703],[24707,24708],[24710,24710],[24712,24713],[24716,24717],[24722,24722],[24724,24724],[24726,24726],[24730,24731],[24733,24733],[24735,24736],[24738,24739],[24742,24742],[24744,24744],[24747,24749],[24751,24754],[24756,24756],[24760,24760],[24763,24764],[24773,24775],[24778,24779],[24782,24782],[24785,24785],[24788,24789],[24792,24797],[24799,24800],[24806,24809],[24811,24816],[24819,24820],[24822,24822],[24825,24826],[24832,24833],[24835,24835],[24838,24838],[24840,24841],[24845,24848],[24852,24853],[24858,24858],[24863,24864],[24867,24868],[24870,24871],[24875,24875],[24877,24877],[24895,24895],[24902,24902],[24904,24904],[24906,24906],[24908,24908],[24910,24910],[24913,24913],[24917,24917],[24925,24925],[24930,24930],[24933,24933],[24935,24936],[24940,24941],[24944,24944],[24949,24949],[24951,24951],[24971,24971],[24974,24974],[24980,24981],[24985,24985],[24989,24989],[24999,25001],[25004,25005],[25015,25015],[25018,25018],[25022,25022],[25026,25026],[25032,25032],[25034,25035],[25041,25042],[25044,25044],[25062,25062],[25077,25077],[25087,25087],[25094,25094],[25096,25096],[25098,25106],[25109,25112],[25114,25115],[25119,25119],[25121,25125],[25130,25130],[25132,25134],[25139,25140],[25143,25143],[25149,25155],[25157,25166],[25169,25172],[25176,25176],[25179,25179],[25182,25182],[25187,25187],[25190,25191],[25193,25200],[25203,25203],[25206,25206],[25209,25210],[25212,25216],[25219,25220],[25225,25226],[25233,25240],[25242,25243],[25247,25250],[25252,25253],[25256,25256],[25259,25260],[25265,25265],[25269,25269],[25273,25273],[25275,25277],[25279,25279],[25282,25290],[25292,25294],[25296,25296],[25298,25300],[25302,25308],[25311,25311],[25314,25321],[25324,25327],[25329,25329],[25331,25332],[25334,25335],[25340,25343],[25345,25346],[25351,25353],[25358,25358],[25361,25361],[25363,25363],[25366,25366],[25370,25371],[25373,25382],[25384,25384],[25386,25387],[25391,25391],[25394,25394],[25401,25402],[25405,25405],[25410,25411],[25413,25414],[25417,25417],[25419,25424],[25429,25429],[25438,25439],[25441,25443],[25447,25447],[25449,25449],[25453,25455],[25457,25457],[25462,25463],[25466,25467],[25469,25469],[25472,25472],[25474,25474],[25479,25482],[25484,25484],[25486,25488],[25490,25490],[25494,25494],[25496,25496],[25502,25502],[25504,25504],[25506,25507],[25509,25509],[25511,25514],[25516,25518],[25520,25520],[25523,25524],[25527,25528],[25530,25530],[25532,25532],[25534,25534],[25540,25540],[25542,25542],[25545,25545],[25549,25552],[25554,25554],[25557,25558],[25566,25566],[25568,25569],[25571,25571],[25577,25578],[25581,25581],[25586,25588],[25590,25590],[25592,25592],[25597,25597],[25599,25602],[25605,25605],[25611,25612],[25615,25616],[25618,25620],[25627,25628],[25630,25630],[25632,25633],[25638,25638],[25642,25642],[25644,25645],[25652,25652],[25658,25658],[25661,25661],[25663,25663],[25665,25665],[25668,25672],[25674,25674],[25679,25679],[25682,25682],[25684,25684],[25688,25688],[25691,25691],[25694,25694],[25703,25703],[25705,25705],[25709,25709],[25716,25716],[25720,25722],[25725,25725],[25730,25730],[25732,25733],[25735,25735],[25745,25746],[25749,25750],[25753,25753],[25758,25758],[25764,25764],[25769,25769],[25772,25774],[25776,25776],[25781,25781],[25783,25784],[25786,25786],[25788,25788],[25792,25792],[25794,25794],[25797,25797],[25805,25806],[25808,25808],[25810,25810],[25815,25816],[25822,25822],[25826,25826],[25828,25828],[25830,25830],[25855,25856],[25865,25865],[25874,25874],[25880,25880],[25893,25893],[25899,25899],[25902,25903],[25908,25910],[25912,25913],[25915,25915],[25917,25919],[25925,25925],[25928,25929],[25932,25932],[25935,25935],[25937,25937],[25940,25942],[25945,25945],[25947,25947],[25949,25950],[25954,25955],[25958,25958],[25961,25961],[25963,25964],[25968,25968],[25970,25970],[25972,25972],[25975,25975],[25991,25991],[25995,25996],[26000,26001],[26003,26003],[26007,26007],[26009,26009],[26011,26013],[26015,26017],[26020,26021],[26023,26023],[26025,26025],[26027,26027],[26029,26029],[26031,26032],[26038,26038],[26041,26041],[26044,26045],[26049,26049],[26051,26054],[26059,26060],[26062,26064],[26066,26066],[26070,26071],[26078,26078],[26080,26080],[26082,26082],[26085,26089],[26092,26097],[26100,26104],[26106,26107],[26111,26112],[26114,26116],[26118,26122],[26124,26124],[26126,26127],[26130,26133],[26137,26137],[26141,26141],[26143,26145],[26147,26149],[26151,26152],[26154,26155],[26157,26157],[26159,26159],[26161,26161],[26163,26166],[26170,26170],[26172,26174],[26177,26177],[26179,26179],[26181,26181],[26186,26188],[26191,26192],[26194,26199],[26201,26202],[26206,26207],[26209,26210],[26212,26212],[26214,26214],[26216,26216],[26218,26219],[26222,26225],[26228,26228],[26230,26231],[26234,26234],[26238,26238],[26242,26242],[26244,26245],[26247,26247],[26252,26252],[26257,26257],[26261,26263],[26269,26269],[26279,26280],[26286,26286],[26290,26290],[26292,26294],[26297,26297],[26302,26303],[26312,26312],[26316,26316],[26329,26329],[26331,26333],[26342,26342],[26345,26345],[26352,26352],[26354,26356],[26359,26359],[26361,26361],[26364,26364],[26366,26368],[26376,26379],[26381,26381],[26383,26384],[26387,26389],[26391,26391],[26395,26395],[26397,26397],[26399,26399],[26406,26406],[26408,26408],[26410,26413],[26415,26415],[26417,26417],[26419,26421],[26424,26424],[26426,26426],[26429,26429],[26432,26432],[26434,26436],[26438,26438],[26440,26441],[26444,26444],[26446,26449],[26451,26451],[26453,26454],[26457,26457],[26460,26460],[26462,26465],[26469,26469],[26471,26474],[26477,26477],[26479,26480],[26482,26483],[26485,26485],[26487,26487],[26491,26492],[26494,26495],[26497,26497],[26500,26501],[26503,26503],[26505,26505],[26507,26507],[26509,26509],[26512,26512],[26517,26517],[26519,26520],[26522,26522],[26524,26526],[26530,26531],[26533,26533],[26535,26536],[26538,26539],[26541,26541],[26543,26544],[26546,26547],[26549,26553],[26561,26561],[26563,26564],[26568,26568],[26570,26570],[26575,26580],[26582,26582],[26584,26586],[26588,26590],[26592,26592],[26594,26594],[26597,26597],[26601,26601],[26604,26604],[26607,26609],[26611,26612],[26615,26615],[26621,26621],[26623,26624],[26629,26629],[26631,26636],[26638,26643],[26646,26647],[26653,26653],[26655,26655],[26657,26657],[26665,26666],[26674,26676],[26679,26681],[26683,26686],[26688,26694],[26696,26698],[26700,26700],[26702,26702],[26704,26705],[26707,26709],[26720,26729],[26731,26731],[26735,26735],[26738,26738],[26740,26740],[26742,26743],[26745,26745],[26753,26753],[26755,26755],[26757,26758],[26764,26764],[26767,26767],[26771,26771],[26775,26775],[26784,26784],[26786,26787],[26790,26792],[26797,26797],[26799,26800],[26803,26805],[26812,26818],[26825,26825],[26827,26827],[26829,26829],[26832,26832],[26834,26835],[26837,26837],[26840,26840],[26842,26842],[26848,26848],[26851,26852],[26856,26856],[26858,26860],[26862,26862],[26864,26865],[26869,26869],[26873,26877],[26880,26881],[26885,26886],[26891,26891],[26893,26894],[26896,26899],[26911,26912],[26916,26916],[26922,26922],[26925,26925],[26928,26928],[26932,26932],[26936,26937],[26941,26941],[26943,26943],[26946,26946],[26962,26962],[26964,26964],[26967,26967],[26969,26970],[26973,26974],[26976,26976],[26979,26979],[26982,26982],[26985,26987],[26990,26991],[26993,26993],[26999,27001],[27004,27004],[27008,27008],[27010,27017],[27021,27021],[27025,27025],[27028,27030],[27032,27032],[27035,27036],[27047,27048],[27051,27051],[27053,27053],[27056,27057],[27060,27060],[27063,27063],[27067,27067],[27073,27073],[27075,27075],[27082,27082],[27084,27084],[27086,27086],[27088,27088],[27092,27092],[27098,27100],[27103,27104],[27117,27117],[27121,27122],[27133,27133],[27135,27135],[27146,27146],[27159,27160],[27167,27167],[27169,27169],[27176,27176],[27178,27178],[27183,27183],[27185,27185],[27189,27189],[27197,27198],[27204,27204],[27207,27207],[27216,27217],[27224,27225],[27227,27227],[27230,27230],[27233,27233],[27237,27238],[27249,27249],[27257,27257],[27260,27260],[27264,27264],[27268,27268],[27278,27278],[27280,27281],[27287,27287],[27294,27294],[27296,27296],[27305,27305],[27307,27308],[27334,27334],[27394,27394],[27424,27428],[27431,27431],[27442,27442],[27447,27451],[27454,27454],[27459,27459],[27461,27463],[27465,27465],[27468,27468],[27481,27481],[27490,27495],[27498,27498],[27513,27513],[27515,27516],[27521,27524],[27526,27527],[27529,27531],[27533,27533],[27538,27539],[27542,27542],[27546,27547],[27553,27553],[27555,27555],[27562,27562],[27571,27573],[27575,27575],[27583,27583],[27585,27586],[27589,27589],[27595,27597],[27599,27600],[27602,27607],[27609,27609],[27611,27611],[27617,27617],[27626,27627],[27631,27631],[27635,27635],[27637,27637],[27641,27641],[27645,27645],[27653,27655],[27661,27661],[27663,27665],[27667,27670],[27672,27675],[27679,27679],[27681,27682],[27684,27684],[27686,27690],[27694,27696],[27698,27698],[27700,27701],[27704,27704],[27709,27714],[27718,27723],[27728,27728],[27732,27733],[27735,27735],[27739,27745],[27748,27748],[27751,27755],[27757,27757],[27760,27760],[27762,27762],[27764,27764],[27766,27766],[27769,27769],[27773,27774],[27777,27785],[27788,27788],[27791,27792],[27795,27796],[27800,27803],[27807,27807],[27809,27809],[27811,27819],[27821,27822],[27825,27827],[27832,27839],[27842,27845],[27847,27847],[27849,27850],[27852,27852],[27856,27856],[27859,27863],[27865,27868],[27870,27870],[27872,27875],[27877,27877],[27880,27880],[27882,27883],[27886,27889],[27891,27891],[27893,27896],[27898,27902],[27905,27905],[27908,27908],[27911,27912],[27915,27916],[27918,27918],[27921,27923],[27927,27931],[27934,27934],[27938,27939],[27941,27941],[27943,27944],[27946,27947],[27949,27950],[27953,27957],[27960,27967],[27969,27969],[27971,27971],[27973,27979],[27981,27989],[27993,27996],[27998,28001],[28003,28003],[28005,28006],[28009,28010],[28012,28016],[28018,28018],[28020,28020],[28023,28024],[28028,28028],[28034,28034],[28036,28037],[28040,28041],[28044,28046],[28048,28049],[28051,28053],[28056,28056],[28059,28059],[28061,28068],[28070,28075],[28078,28079],[28082,28082],[28084,28085],[28088,28088],[28095,28096],[28100,28103],[28107,28108],[28111,28111],[28113,28113],[28118,28118],[28120,28121],[28124,28129],[28132,28132],[28134,28134],[28139,28140],[28142,28143],[28145,28145],[28147,28148],[28151,28151],[28153,28153],[28155,28156],[28165,28165],[28170,28170],[28172,28174],[28176,28177],[28180,28180],[28182,28183],[28186,28186],[28189,28189],[28191,28193],[28195,28197],[28201,28201],[28203,28203],[28205,28205],[28207,28208],[28210,28210],[28212,28212],[28216,28216],[28218,28218],[28220,28220],[28227,28228],[28233,28233],[28237,28238],[28241,28241],[28243,28244],[28246,28246],[28248,28248],[28251,28253],[28255,28255],[28259,28259],[28267,28267],[28270,28270],[28274,28274],[28276,28276],[28286,28287],[28289,28289],[28291,28291],[28293,28295],[28297,28297],[28301,28301],[28303,28304],[28312,28312],[28314,28314],[28316,28316],[28318,28320],[28322,28322],[28325,28327],[28330,28330],[28335,28335],[28337,28338],[28340,28343],[28345,28347],[28349,28349],[28353,28355],[28358,28359],[28361,28361],[28363,28363],[28365,28365],[28367,28367],[28369,28369],[28371,28373],[28375,28376],[28378,28378],[28382,28386],[28388,28395],[28404,28404],[28409,28409],[28418,28418],[28422,28422],[28424,28425],[28427,28427],[28431,28431],[28435,28438],[28448,28448],[28452,28452],[28454,28454],[28457,28459],[28461,28461],[28463,28463],[28465,28465],[28467,28468],[28470,28471],[28473,28473],[28475,28476],[28478,28478],[28486,28487],[28491,28491],[28493,28493],[28495,28495],[28502,28502],[28504,28504],[28508,28508],[28510,28511],[28514,28514],[28518,28518],[28521,28521],[28525,28526],[28530,28530],[28532,28533],[28536,28536],[28538,28538],[28540,28542],[28546,28546],[28548,28548],[28552,28553],[28556,28558],[28571,28572],[28577,28577],[28581,28581],[28583,28583],[28586,28586],[28589,28589],[28595,28596],[28598,28598],[28601,28601],[28604,28605],[28608,28608],[28610,28610],[28617,28617],[28619,28619],[28625,28626],[28638,28638],[28640,28641],[28649,28649],[28654,28655],[28684,28685],[28689,28689],[28692,28692],[28698,28699],[28707,28707],[28721,28721],[28725,28725],[28729,28729],[28732,28732],[28744,28744],[28748,28748],[28751,28751],[28766,28766],[28779,28781],[28783,28784],[28789,28790],[28792,28792],[28796,28796],[28798,28800],[28805,28806],[28809,28810],[28812,28812],[28814,28814],[28818,28818],[28820,28822],[28824,28825],[28828,28829],[28831,28831],[28835,28835],[28843,28847],[28849,28849],[28851,28851],[28855,28857],[28859,28861],[28864,28867],[28872,28872],[28874,28874],[28884,28884],[28888,28889],[28891,28893],[28895,28896],[28900,28900],[28902,28905],[28907,28909],[28911,28911],[28918,28919],[28921,28923],[28925,28925],[28934,28934],[28937,28938],[28940,28940],[28944,28944],[28947,28947],[28949,28954],[28956,28956],[28958,28958],[28966,28966],[28975,28977],[28982,28982],[28993,28993],[28995,28995],[28997,28997],[29002,29004],[29006,29006],[29011,29011],[29020,29020],[29022,29023],[29028,29028],[29030,29032],[29038,29038],[29042,29044],[29048,29048],[29050,29050],[29053,29053],[29060,29060],[29063,29063],[29066,29066],[29071,29071],[29076,29076],[29080,29081],[29083,29084],[29087,29088],[29093,29093],[29096,29096],[29100,29100],[29107,29107],[29109,29109],[29113,29113],[29115,29115],[29123,29123],[29130,29131],[29134,29135],[29140,29141],[29146,29146],[29152,29152],[29157,29157],[29159,29159],[29166,29166],[29177,29177],[29190,29191],[29204,29204],[29210,29210],[29213,29213],[29215,29215],[29224,29224],[29226,29226],[29228,29228],[29232,29233],[29237,29241],[29243,29243],[29245,29245],[29247,29247],[29249,29250],[29255,29256],[29260,29261],[29266,29266],[29270,29270],[29273,29275],[29277,29277],[29279,29279],[29281,29282],[29284,29287],[29289,29289],[29294,29295],[29298,29298],[29301,29301],[29305,29307],[29310,29313],[29316,29316],[29319,29319],[29322,29323],[29325,29325],[29327,29327],[29330,29330],[29343,29343],[29352,29352],[29356,29357],[29359,29360],[29364,29364],[29366,29369],[29377,29380],[29384,29385],[29389,29390],[29392,29392],[29394,29394],[29399,29399],[29401,29401],[29405,29406],[29408,29409],[29416,29417],[29420,29428],[29431,29432],[29434,29436],[29441,29441],[29443,29444],[29447,29447],[29450,29450],[29454,29454],[29459,29459],[29461,29463],[29467,29470],[29473,29474],[29477,29477],[29481,29484],[29486,29489],[29492,29492],[29495,29498],[29502,29503],[29517,29517],[29520,29520],[29522,29522],[29527,29527],[29536,29536],[29548,29549],[29551,29551],[29556,29556],[29566,29566],[29571,29572],[29575,29575],[29577,29577],[29579,29579],[29582,29582],[29585,29587],[29589,29590],[29592,29595],[29598,29602],[29604,29606],[29609,29609],[29611,29611],[29613,29619],[29622,29623],[29625,29628],[29631,29632],[29634,29634],[29637,29637],[29639,29645],[29647,29650],[29653,29654],[29657,29657],[29659,29659],[29661,29662],[29664,29664],[29666,29667],[29669,29671],[29673,29675],[29677,29677],[29680,29680],[29682,29682],[29685,29685],[29687,29690],[29693,29693],[29696,29696],[29699,29706],[29710,29712],[29716,29716],[29722,29723],[29727,29727],[29729,29730],[29732,29734],[29736,29736],[29738,29744],[29746,29750],[29756,29756],[29760,29766],[29777,29777],[29779,29783],[29785,29791],[29794,29794],[29799,29800],[29804,29805],[29808,29809],[29811,29811],[29814,29815],[29822,29822],[29824,29825],[29827,29827],[29830,29832],[29835,29835],[29838,29838],[29840,29840],[29842,29842],[29848,29848],[29852,29852],[29854,29856],[29861,29861],[29863,29866],[29868,29868],[29870,29870],[29873,29874],[29882,29882],[29888,29888],[29906,29906],[29910,29910],[29912,29912],[29916,29916],[29918,29918],[29920,29920],[29922,29924],[29926,29926],[29934,29935],[29940,29940],[29942,29943],[29947,29947],[29951,29951],[29956,29956],[29965,29965],[29967,29967],[29969,29969],[29971,29971],[29975,29978],[29980,29980],[29983,29983],[29985,29985],[29989,29990],[29992,29997],[29999,30003],[30005,30005],[30007,30008],[30010,30011],[30014,30014],[30016,30016],[30021,30021],[30024,30024],[30027,30028],[30030,30031],[30036,30036],[30038,30038],[30041,30044],[30052,30054],[30058,30058],[30060,30060],[30063,30063],[30066,30066],[30068,30068],[30072,30073],[30079,30079],[30081,30081],[30083,30083],[30086,30086],[30091,30091],[30093,30093],[30095,30098],[30100,30100],[30102,30103],[30105,30106],[30109,30109],[30111,30117],[30123,30133],[30136,30137],[30140,30142],[30146,30149],[30151,30154],[30157,30157],[30162,30166],[30168,30168],[30171,30171],[30174,30174],[30178,30180],[30182,30184],[30186,30187],[30192,30193],[30196,30196],[30201,30201],[30204,30204],[30207,30209],[30211,30211],[30213,30214],[30218,30218],[30220,30220],[30224,30224],[30229,30229],[30231,30233],[30235,30235],[30239,30240],[30242,30242],[30244,30246],[30249,30251],[30253,30253],[30256,30256],[30259,30261],[30264,30264],[30268,30268],[30270,30272],[30275,30275],[30284,30285],[30292,30292],[30294,30295],[30300,30300],[30302,30302],[30307,30307],[30315,30315],[30319,30319],[30328,30328],[30331,30331],[30333,30335],[30338,30338],[30340,30340],[30342,30344],[30347,30347],[30350,30350],[30353,30353],[30355,30355],[30357,30358],[30361,30361],[30363,30363],[30366,30366],[30372,30372],[30374,30374],[30381,30382],[30385,30386],[30388,30388],[30399,30399],[30402,30402],[30405,30406],[30408,30410],[30413,30418],[30420,30420],[30422,30424],[30427,30427],[30431,30431],[30437,30438],[30446,30447],[30449,30450],[30452,30452],[30455,30457],[30460,30460],[30462,30462],[30465,30465],[30468,30468],[30471,30475],[30477,30477],[30489,30490],[30495,30496],[30498,30498],[30502,30502],[30504,30505],[30508,30509],[30511,30511],[30517,30520],[30522,30522],[30524,30524],[30528,30529],[30531,30532],[30535,30535],[30542,30542],[30544,30545],[30554,30555],[30561,30563],[30565,30566],[30568,30568],[30571,30572],[30585,30585],[30589,30592],[30596,30597],[30603,30606],[30609,30610],[30623,30624],[30626,30626],[30629,30629],[30631,30631],[30633,30637],[30640,30640],[30643,30643],[30645,30645],[30651,30651],[30653,30653],[30655,30655],[30669,30669],[30679,30679],[30683,30684],[30686,30686],[30690,30691],[30693,30693],[30695,30695],[30697,30697],[30699,30702],[30704,30704],[30707,30707],[30710,30710],[30712,30712],[30715,30722],[30724,30724],[30726,30726],[30729,30729],[30732,30733],[30737,30738],[30740,30740],[30742,30744],[30746,30746],[30748,30749],[30751,30752],[30755,30755],[30757,30759],[30761,30761],[30763,30766],[30768,30768],[30772,30773],[30775,30780],[30782,30782],[30784,30785],[30789,30789],[30791,30791],[30794,30794],[30796,30798],[30800,30800],[30802,30802],[30804,30807],[30809,30810],[30813,30813],[30826,30830],[30839,30839],[30844,30844],[30847,30847],[30851,30851],[30855,30857],[30860,30863],[30865,30865],[30867,30867],[30871,30872],[30874,30876],[30879,30879],[30881,30881],[30883,30883],[30885,30885],[30887,30888],[30896,30900],[30902,30902],[30905,30905],[30910,30910],[30913,30913],[30917,30917],[30921,30923],[30927,30928],[30932,30933],[30937,30937],[30940,30940],[30945,30945],[30952,30952],[30956,30956],[30962,30962],[30964,30964],[30967,30967],[30969,30971],[30977,30977],[30981,30981],[30988,30988],[30995,30995],[31006,31006],[31012,31012],[31028,31029],[31034,31036],[31038,31038],[31040,31041],[31043,31043],[31046,31051],[31054,31056],[31059,31059],[31061,31063],[31066,31072],[31074,31074],[31077,31077],[31079,31080],[31085,31085],[31087,31087],[31090,31090],[31095,31096],[31098,31098],[31100,31100],[31102,31102],[31104,31105],[31108,31109],[31114,31115],[31119,31119],[31122,31122],[31124,31124],[31128,31128],[31130,31131],[31140,31140],[31143,31143],[31155,31155],[31161,31163],[31165,31166],[31168,31169],[31171,31171],[31174,31174],[31177,31177],[31179,31179],[31181,31181],[31185,31186],[31189,31189],[31192,31192],[31199,31199],[31203,31204],[31206,31207],[31209,31209],[31211,31213],[31215,31216],[31224,31224],[31227,31227],[31229,31230],[31232,31232],[31234,31235],[31238,31238],[31243,31246],[31249,31249],[31252,31252],[31255,31255],[31257,31258],[31262,31262],[31264,31264],[31267,31267],[31283,31283],[31287,31287],[31289,31289],[31291,31293],[31295,31295],[31300,31300],[31302,31302],[31313,31313],[31319,31319],[31321,31321],[31324,31324],[31327,31327],[31344,31344],[31348,31348],[31350,31354],[31359,31361],[31363,31366],[31368,31368],[31370,31370],[31373,31374],[31377,31378],[31381,31384],[31388,31389],[31391,31392],[31395,31395],[31397,31398],[31400,31400],[31404,31405],[31411,31411],[31416,31416],[31423,31423],[31435,31435],[31441,31441],[31446,31446],[31448,31449],[31454,31456],[31459,31459],[31461,31462],[31467,31467],[31469,31469],[31471,31471],[31481,31482],[31485,31485],[31487,31487],[31491,31492],[31494,31494],[31496,31496],[31498,31499],[31503,31503],[31505,31505],[31508,31509],[31513,31513],[31515,31515],[31518,31518],[31520,31520],[31524,31526],[31528,31528],[31530,31532],[31534,31535],[31537,31537],[31539,31539],[31544,31544],[31546,31546],[31548,31548],[31550,31550],[31552,31552],[31557,31557],[31559,31559],[31561,31561],[31563,31564],[31567,31570],[31572,31572],[31574,31574],[31576,31576],[31578,31581],[31584,31584],[31586,31586],[31588,31590],[31598,31598],[31601,31602],[31605,31607],[31609,31609],[31611,31612],[31614,31614],[31616,31616],[31621,31621],[31629,31629],[31632,31632],[31635,31639],[31644,31645],[31649,31650],[31654,31661],[31665,31665],[31668,31668],[31672,31672],[31681,31681],[31686,31687],[31692,31692],[31697,31697],[31699,31699],[31705,31706],[31709,31709],[31713,31713],[31717,31718],[31722,31722],[31726,31727],[31729,31729],[31735,31735],[31740,31740],[31742,31742],[31747,31747],[31751,31751],[31753,31753],[31755,31756],[31759,31759],[31765,31766],[31773,31773],[31775,31776],[31782,31783],[31786,31786],[31792,31792],[31800,31800],[31807,31809],[31821,31821],[31845,31845],[31859,31860],[31867,31869],[31881,31881],[31889,31890],[31893,31893],[31895,31896],[31900,31903],[31906,31906],[31908,31909],[31914,31914],[31918,31918],[31921,31923],[31929,31929],[31932,31935],[31937,31937],[31941,31941],[31943,31944],[31946,31946],[31948,31949],[31954,31954],[31957,31959],[31961,31961],[31964,31964],[31967,31968],[31976,31976],[31983,31983],[31989,31989],[31992,31992],[31995,31995],[32010,32010],[32032,32032],[32034,32034],[32039,32039],[32043,32043],[32047,32047],[32092,32092],[32110,32110],[32119,32119],[32166,32166],[32174,32174],[32288,32288],[32290,32290],[32315,32315],[32321,32321],[32324,32324],[32327,32327],[32386,32386],[32411,32411],[32415,32491],[32493,32566],[32568,32568],[32570,32570],[32578,32578],[32580,32581],[32589,32589],[32592,32593],[32596,32597],[32599,32600],[32602,32602],[32607,32607],[32609,32610],[32616,32618],[32622,32622],[32625,32626],[32628,32628],[32630,32630],[32633,32633],[32637,32638],[32641,32641],[32650,32650],[32652,32652],[32654,32654],[32657,32657],[32659,32662],[32666,32666],[32669,32671],[32673,32673],[32676,32676],[32679,32679],[32687,32690],[32696,32697],[32700,32701],[32703,32707],[32709,32709],[32712,32712],[32714,32714],[32716,32716],[32718,32718],[32724,32725],[32728,32731],[32735,32737],[32741,32742],[32745,32745],[32750,32753],[32755,32755],[32759,32759],[32763,32764],[32766,32766],[32768,32769],[32771,32775],[32779,32781],[32783,32786],[32788,32793],[32796,32796],[32800,32800],[32802,32802],[32804,32810],[32816,32817],[32819,32819],[32821,32824],[32827,32827],[32829,32829],[32831,32831],[32834,32835],[32838,32838],[32842,32845],[32850,32850],[32852,32852],[32856,32856],[32858,32858],[32873,32874],[32881,32881],[32895,32896],[32899,32900],[32902,32903],[32905,32905],[32907,32908],[32915,32915],[32918,32918],[32920,32920],[32922,32925],[32927,32930],[32932,32933],[32937,32939],[32941,32943],[32945,32946],[32948,32948],[32951,32952],[32954,32954],[32956,32964],[32966,32966],[32968,32968],[32972,32974],[32982,32983],[32985,32990],[32992,32993],[32995,32997],[32999,33005],[33007,33012],[33014,33014],[33016,33016],[33018,33018],[33020,33021],[33026,33026],[33030,33030],[33033,33034],[33037,33044],[33046,33046],[33048,33048],[33050,33050],[33054,33055],[33065,33065],[33068,33068],[33071,33071],[33073,33074],[33078,33078],[33080,33080],[33086,33087],[33094,33094],[33096,33096],[33098,33100],[33104,33109],[33112,33114],[33120,33120],[33125,33125],[33127,33129],[33133,33137],[33140,33140],[33145,33152],[33154,33154],[33160,33160],[33162,33162],[33167,33167],[33169,33169],[33176,33177],[33179,33181],[33187,33187],[33190,33190],[33192,33192],[33194,33194],[33203,33203],[33210,33211],[33216,33219],[33222,33222],[33226,33226],[33228,33228],[33233,33233],[33244,33244],[33251,33251],[33255,33255],[33258,33258],[33260,33261],[33267,33268],[33275,33276],[33278,33278],[33280,33282],[33284,33286],[33292,33293],[33296,33296],[33298,33298],[33300,33300],[33307,33308],[33310,33315],[33317,33317],[33320,33320],[33322,33325],[33327,33337],[33339,33339],[33342,33342],[33348,33349],[33351,33351],[33353,33353],[33355,33355],[33358,33359],[33368,33368],[33370,33370],[33375,33375],[33384,33384],[33390,33392],[33394,33396],[33401,33402],[33405,33407],[33410,33412],[33416,33416],[33418,33419],[33421,33423],[33425,33426],[33431,33433],[33436,33437],[33439,33441],[33443,33446],[33448,33457],[33459,33460],[33463,33465],[33468,33470],[33473,33473],[33476,33476],[33479,33487],[33489,33493],[33495,33496],[33499,33500],[33502,33505],[33507,33511],[33515,33515],[33519,33519],[33521,33521],[33524,33524],[33527,33527],[33529,33529],[33531,33531],[33534,33534],[33536,33545],[33547,33548],[33550,33551],[33553,33553],[33555,33557],[33559,33559],[33562,33565],[33575,33576],[33579,33581],[33583,33583],[33585,33585],[33587,33590],[33592,33594],[33596,33597],[33600,33601],[33603,33604],[33606,33607],[33609,33609],[33615,33620],[33622,33622],[33625,33628],[33630,33633],[33635,33647],[33655,33656],[33659,33661],[33669,33670],[33673,33673],[33678,33678],[33682,33683],[33688,33689],[33691,33694],[33696,33696],[33704,33707],[33712,33716],[33718,33722],[33724,33725],[33727,33730],[33733,33733],[33735,33735],[33737,33738],[33740,33741],[33743,33743],[33748,33748],[33750,33750],[33752,33752],[33756,33757],[33759,33761],[33765,33765],[33769,33770],[33776,33778],[33784,33785],[33788,33789],[33793,33793],[33795,33796],[33798,33798],[33803,33807],[33809,33809],[33816,33816],[33818,33818],[33820,33821],[33827,33833],[33841,33841],[33843,33843],[33848,33849],[33852,33853],[33862,33862],[33870,33870],[33873,33873],[33878,33879],[33881,33884],[33889,33889],[33891,33891],[33897,33897],[33899,33901],[33904,33905],[33907,33910],[33912,33912],[33914,33914],[33922,33922],[33924,33924],[33927,33929],[33931,33932],[33934,33934],[33936,33936],[33943,33943],[33945,33945],[33948,33948],[33951,33951],[33953,33953],[33960,33960],[33967,33967],[33969,33970],[33972,33972],[33976,33979],[33981,33981],[33983,33983],[33985,33986],[33988,33988],[33991,33991],[33993,33994],[33997,33997],[33999,34001],[34003,34003],[34006,34006],[34013,34013],[34015,34016],[34018,34019],[34021,34022],[34028,34028],[34032,34032],[34044,34044],[34047,34048],[34051,34051],[34056,34056],[34058,34058],[34060,34060],[34065,34065],[34067,34067],[34071,34071],[34074,34074],[34079,34079],[34081,34081],[34091,34092],[34103,34109],[34115,34115],[34120,34122],[34134,34135],[34137,34137],[34142,34142],[34148,34148],[34152,34152],[34160,34160],[34162,34162],[34164,34164],[34169,34171],[34174,34174],[34177,34177],[34180,34181],[34183,34183],[34191,34191],[34203,34204],[34210,34210],[34212,34212],[34216,34216],[34218,34218],[34222,34224],[34227,34227],[34231,34233],[34239,34239],[34241,34241],[34249,34249],[34255,34256],[34259,34259],[34261,34261],[34268,34268],[34271,34272],[34276,34276],[34278,34278],[34280,34281],[34299,34299],[34303,34303],[34309,34309],[34321,34321],[34326,34326],[34328,34328],[34343,34343],[34345,34345],[34360,34360],[34364,34364],[34381,34388],[34394,34394],[34398,34398],[34402,34402],[34404,34404],[34411,34412],[34414,34414],[34417,34417],[34423,34434],[34436,34436],[34438,34438],[34442,34445],[34451,34451],[34453,34453],[34460,34461],[34467,34468],[34471,34474],[34476,34476],[34479,34482],[34484,34486],[34490,34490],[34496,34496],[34499,34500],[34502,34503],[34505,34507],[34510,34513],[34516,34516],[34520,34521],[34523,34523],[34526,34527],[34532,34532],[34537,34537],[34541,34542],[34544,34548],[34552,34553],[34558,34558],[34560,34560],[34562,34563],[34567,34570],[34573,34574],[34576,34576],[34578,34579],[34581,34581],[34583,34584],[34586,34586],[34588,34588],[34590,34590],[34593,34595],[34597,34597],[34601,34601],[34606,34606],[34609,34609],[34612,34612],[34615,34615],[34619,34619],[34622,34623],[34631,34633],[34636,34636],[34638,34638],[34643,34643],[34647,34649],[34656,34656],[34659,34661],[34670,34670],[34672,34672],[34674,34674],[34676,34676],[34678,34678],[34683,34686],[34690,34691],[34693,34693],[34696,34696],[34699,34699],[34701,34701],[34707,34707],[34711,34711],[34719,34720],[34723,34723],[34728,34728],[34731,34733],[34735,34735],[34737,34737],[34739,34739],[34741,34741],[34746,34746],[34749,34749],[34752,34752],[34758,34758],[34762,34763],[34767,34767],[34769,34771],[34779,34779],[34784,34784],[34789,34789],[34794,34795],[34798,34798],[34809,34809],[34814,34814],[34819,34819],[34826,34827],[34835,34835],[34837,34838],[34843,34843],[34849,34850],[34866,34866],[34873,34873],[34876,34876],[34880,34880],[34883,34885],[34892,34894],[34898,34898],[34900,34900],[34903,34903],[34905,34905],[34912,34917],[34920,34921],[34923,34924],[34926,34926],[34928,34928],[34930,34930],[34935,34935],[34941,34943],[34945,34946],[34948,34950],[34952,34952],[34955,34955],[34957,34957],[34962,34962],[34966,34967],[34972,34972],[34978,34978],[34980,34980],[34986,34987],[34989,34989],[34991,34991],[34993,34993],[34999,34999],[35004,35004],[35009,35010],[35013,35014],[35016,35017],[35022,35022],[35026,35026],[35028,35029],[35032,35033],[35035,35035],[35039,35039],[35042,35045],[35048,35048],[35056,35057],[35059,35060],[35064,35065],[35068,35068],[35070,35070],[35074,35074],[35082,35082],[35088,35088],[35090,35091],[35093,35093],[35097,35099],[35103,35103],[35105,35105],[35109,35109],[35114,35115],[35119,35120],[35124,35124],[35126,35126],[35137,35137],[35140,35140],[35157,35157],[35162,35162],[35164,35164],[35166,35167],[35174,35174],[35179,35179],[35195,35195],[35199,35199],[35201,35201],[35203,35203],[35206,35206],[35265,35276],[35278,35282],[35286,35286],[35290,35290],[35292,35292],[35294,35295],[35299,35299],[35301,35302],[35307,35307],[35309,35309],[35311,35311],[35313,35313],[35315,35315],[35327,35328],[35332,35332],[35335,35335],[35354,35354],[35390,35390],[35400,35400],[35423,35423],[35449,35449],[35465,35466],[35475,35475],[35591,35591],[35622,35622],[35686,35686],[35692,35692],[35744,35755],[35757,35817],[35819,35848],[35850,35895],[35900,35900],[35903,35903],[35905,35905],[35910,35911],[35913,35913],[35916,35916],[35925,35925],[35930,35930],[35937,35938],[35944,35944],[35946,35947],[35950,35950],[35955,35955],[35960,35962],[35970,35970],[35973,35974],[35977,35978],[35980,35980],[35988,35988],[35992,35992],[36125,36127],[36129,36196],[36198,36199],[36202,36203],[36205,36205],[36208,36208],[36211,36215],[36225,36225],[36228,36229],[36234,36235],[36241,36241],[36244,36244],[36255,36255],[36259,36259],[36271,36271],[36273,36273],[36275,36277],[36280,36280],[36282,36282],[36284,36284],[36286,36287],[36290,36292],[36294,36294],[36299,36300],[36302,36305],[36310,36311],[36314,36315],[36317,36319],[36323,36324],[36328,36328],[36330,36332],[36335,36335],[36337,36337],[36339,36339],[36341,36347],[36349,36349],[36357,36357],[36361,36362],[36364,36364],[36367,36367],[36370,36370],[36372,36372],[36381,36383],[36386,36387],[36390,36390],[36393,36394],[36396,36396],[36398,36399],[36401,36401],[36405,36406],[36409,36410],[36413,36413],[36416,36418],[36420,36421],[36423,36427],[36432,36434],[36441,36442],[36444,36444],[36450,36450],[36454,36454],[36457,36457],[36460,36461],[36463,36464],[36466,36466],[36468,36468],[36470,36470],[36476,36479],[36481,36481],[36485,36485],[36487,36487],[36495,36496],[36500,36500],[36508,36508],[36510,36510],[36523,36524],[36527,36527],[36530,36530],[36538,36538],[36558,36558],[36710,36764],[36766,36767],[36771,36771],[36776,36777],[36779,36779],[36784,36785],[36790,36790],[36793,36793],[36797,36799],[36801,36802],[36804,36805],[36807,36808],[36814,36814],[36816,36817],[36819,36821],[36824,36825],[36827,36831],[36834,36834],[36836,36838],[36840,36843],[36845,36846],[36848,36848],[36851,36851],[36855,36858],[36861,36861],[36864,36870],[36873,36875],[36877,36877],[36879,36882],[36884,36884],[36886,36887],[36890,36891],[36893,36898],[36902,36902],[36909,36911],[36916,36918],[36920,36920],[36923,36924],[36926,36926],[36929,36930],[36932,36932],[36934,36935],[36941,36941],[36943,36947],[36951,36952],[36955,36955],[36962,36963],[36965,36965],[36968,36968],[36973,36974],[36980,36981],[36985,36985],[36989,36989],[36991,36992],[36994,36995],[37000,37000],[37003,37003],[37009,37009],[37011,37011],[37013,37013],[37015,37017],[37019,37019],[37021,37021],[37024,37027],[37030,37030],[37032,37032],[37034,37034],[37036,37036],[37038,37046],[37048,37051],[37053,37055],[37057,37057],[37059,37061],[37063,37064],[37066,37066],[37070,37073],[37075,37075],[37079,37079],[37082,37085],[37089,37090],[37092,37092],[37094,37096],[37098,37099],[37101,37101],[37103,37103],[37108,37108],[37112,37112],[37117,37120],[37122,37125],[37132,37132],[37137,37137],[37143,37146],[37148,37148],[37150,37150],[37152,37152],[37154,37155],[37163,37163],[37167,37167],[37169,37169],[37177,37177],[37186,37187],[37189,37190],[37193,37200],[37202,37202],[37207,37207],[37210,37210],[37213,37214],[37217,37222],[37225,37226],[37228,37228],[37230,37234],[37236,37242],[37245,37247],[37253,37253],[37255,37255],[37257,37257],[37259,37261],[37264,37266],[37274,37275],[37282,37283],[37288,37288],[37290,37290],[37293,37295],[37300,37301],[37306,37306],[37310,37310],[37319,37319],[37321,37322],[37324,37329],[37340,37340],[37492,37492],[37518,37518],[37550,37550],[37574,37574],[37576,37576],[37694,37694],[37738,37738],[37775,37775],[37834,37834],[37846,37846],[37950,37950],[37995,37995],[38021,38032],[38034,38086],[38088,38098],[38101,38117],[38119,38175],[38177,38262],[38271,38271],[38376,38379],[38381,38418],[38420,38426],[38428,38429],[38431,38431],[38433,38434],[38442,38442],[38446,38446],[38449,38454],[38459,38461],[38463,38464],[38466,38466],[38468,38473],[38475,38478],[38480,38481],[38484,38485],[38491,38491],[38494,38495],[38497,38498],[38500,38500],[38503,38506],[38508,38508],[38514,38514],[38516,38519],[38531,38531],[38533,38534],[38536,38536],[38539,38539],[38541,38541],[38543,38544],[38548,38548],[38551,38553],[38556,38556],[38567,38567],[38569,38569],[38576,38576],[38579,38579],[38582,38582],[38585,38586],[38588,38590],[38592,38593],[38596,38599],[38601,38602],[38604,38607],[38610,38610],[38613,38613],[38624,38624],[38632,38634],[38639,38639],[38641,38641],[38643,38643],[38646,38647],[38649,38649],[38654,38654],[38656,38657],[38660,38665],[38669,38671],[38675,38675],[38678,38678],[38684,38684],[38686,38686],[38696,38696],[38698,38698],[38701,38701],[38704,38704],[38706,38706],[38712,38713],[38718,38718],[38738,38739],[38742,38742],[38745,38745],[38747,38747],[38750,38750],[38752,38754],[38757,38757],[38761,38761],[38764,38764],[38768,38768],[38771,38772],[38774,38774],[38776,38776],[38778,38778],[38780,38781],[38783,38783],[38785,38785],[38789,38789],[38795,38795],[38797,38797],[38801,38802],[38804,38804],[38808,38808],[38816,38817],[38819,38819],[38823,38824],[38827,38831],[38834,38836],[38850,38850],[38886,38893],[38899,38899],[38901,38902],[39029,39057],[39059,39060],[39062,39074],[39076,39079],[39118,39125],[39127,39130],[39134,39135],[39143,39144],[39181,39181],[39184,39184],[39214,39214],[39252,39253],[39267,39267],[39269,39269],[39271,39293],[39295,39297],[39299,39309],[39311,39321],[39325,39326],[39333,39333],[39335,39336],[39532,39571],[39573,39592],[39600,39601],[39606,39608],[39610,39610],[39612,39612],[39616,39619],[39621,39621],[39627,39628],[39630,39630],[39633,39633],[39635,39635],[39640,39640],[39647,39647],[39649,39650],[39654,39654],[39659,39659],[39661,39661],[39663,39663],[39673,39673],[39675,39675],[39677,39677],[39683,39683],[39688,39688],[39695,39695],[39698,39699],[39704,39704],[39711,39711],[39715,39715],[39727,39727],[39730,39730],[39734,39735],[39739,39740],[39745,39753],[39755,39755],[39757,39757],[39759,39759],[39761,39761],[39764,39764],[40060,40067],[40069,40082],[40084,40164],[40479,40499],[40501,40530],[40532,40548],[40550,40564],[40574,40576],[40578,40578],[40583,40584],[40587,40587],[40593,40595],[40598,40598],[40605,40605],[40607,40607],[40614,40614],[40628,40628],[40632,40633],[40635,40635],[40637,40638],[40644,40644],[40647,40647],[40649,40649],[40653,40655],[40657,40657],[40660,40660],[40664,40664],[40667,40669],[40671,40674],[40677,40677],[40679,40679],[40681,40682],[40687,40687],[40697,40697],[40699,40700],[40702,40702],[40715,40715],[40717,40718],[40720,40720],[40722,40723],[40727,40727],[40729,40729],[40736,40736],[40738,40738],[40745,40745],[40747,40748],[40751,40751],[40753,40753],[40759,40759],[40761,40761],[40763,40763],[40765,40766],[40769,40769],[40772,40772],[40775,40775],[40777,40777],[40784,40785],[40831,40844],[40857,40859],[40863,40864],[40866,40866],[40909,40911],[65072,65103],[65281,65470],[65474,65479],[65482,65487],[65490,65495],[65498,65500],[65504,65510],[65512,65518],[131428,131428],[132726,132726],[134352,134352],[136090,136090],[136211,136211],[144843,144843],[146583,146584],[146979,146979],[149979,149979],[150141,150141],[150217,150217],[152882,152882],[152930,152930],[153000,153000],[155351,155351],[156193,156193],[156813,156813],[157302,157302],[157564,157564],[158556,158556],[158753,158753],[163833,163833],[164872,164872],[165496,165496],[165525,165525],[165856,165856],[166729,166729],[166983,166983],[166991,166991],[166993,166993],[166996,166996],[167577,167577],[171902,171902],[171907,171907],[171916,171916],[174045,174045],[174331,174331],[174359,174359],[174640,174640],[174646,174646],[174680,174680],[176034,176034],[176423,176424],[176439,176440],[176621,176621],[176896,176896],[176995,176995],[177007,177007],[177010,177010],[177021,177021],[177156,177156],[177168,177168],[177171,177171],[177249,177249],[177383,177383],[177391,177391],[177398,177398],[177401,177401],[177421,177422],[177462,177462],[177582,177583],[177587,177587],[177639,177639],[177652,177652],[177692,177693],[177702,177704],[177706,177706],[177708,177708],[177813,177814],[177837,177837],[177901,177901],[178089,178089],[178117,178117],[178150,178150],[178169,178169],[178172,178172],[178182,178182],[178186,178186],[178204,178204],[178360,178360],[178887,178887],[179039,179039],[179042,179042],[179068,179068],[179075,179075],[179227,179227],[179575,179575],[179591,179591],[179703,179703],[179753,179753],[180265,180266],[180393,180393],[180426,180426],[180693,180693],[180697,180697],[180729,180729],[180860,180860],[180872,180872],[180900,180900],[181015,181015],[181083,181083],[181089,181089],[181092,181092],[181384,181384],[181396,181396],[181399,181399],[181570,181570],[181779,181779],[181784,181784],[181793,181793],[181801,181801],[181803,181805],[181807,181807],[181826,181826],[181834,181835],[182060,182060],[182063,182063],[182175,182175],[182209,182209],[182269,182269],[182489,182489],[182494,182494],[182497,182497],[182515,182515],[182535,182535],[182538,182538],[182557,182557],[182786,182786],[182798,182798],[182909,182909],[182953,182953],[183081,183081],[183085,183086],[183089,183089],[183096,183097],[183099,183099],[183103,183103],[183105,183105],[183114,183114],[183118,183118],[183130,183131],[183140,183140],[183145,183145],[183148,183148],[183151,183151],[183155,183155],[183158,183158],[183160,183160],[183164,183164],[183217,183217],[183231,183232],[183246,183246],[183382,183382],[183391,183391],[183541,183542],[183549,183549],[183551,183551],[183554,183555],[183562,183562],[183691,183691],[183693,183693],[183695,183696],[183711,183712],[183720,183720],[183725,183726],[183765,183765],[183832,183832],[183834,183834],[183843,183843],[183846,183846],[183850,183850],[183932,183932],[183944,183944],[183955,183955]]}},"serif":{"400":{"file":"FreeVideoSerifSC-Regular.woff2","sha256":"875e3d0f1cebdf50d023330f53250a192864c3fa5e00c9814a15ef8a1a09c635","ranges":[[32,126],[160,259],[272,275],[282,283],[296,299],[323,324],[327,328],[332,335],[338,339],[360,365],[462,462],[464,464],[466,466],[468,468],[470,470],[472,472],[474,474],[476,476],[711,711],[713,713],[913,929],[931,937],[945,961],[963,969],[1025,1025],[1040,1103],[1105,1105],[8194,8195],[8208,8214],[8216,8218],[8220,8222],[8224,8226],[8229,8231],[8240,8240],[8242,8243],[8245,8245],[8249,8252],[8258,8258],[8263,8265],[8273,8273],[8451,8451],[8470,8470],[8544,8555],[8592,8601],[8632,8633],[8644,8646],[8651,8652],[8656,8656],[8658,8658],[8660,8660],[8678,8681],[8693,8693],[8712,8712],[8715,8715],[8719,8719],[8721,8721],[8730,8730],[8733,8734],[8736,8736],[8741,8741],[8743,8747],[8750,8750],[8756,8759],[8765,8765],[8773,8773],[8776,8776],[8780,8780],[8800,8801],[8804,8805],[8814,8815],[8857,8857],[8869,8869],[8978,8978],[9312,9547],[9632,9643],[9649,9651],[9654,9655],[9660,9661],[9664,9665],[9670,9671],[9673,9676],[9678,9683],[9698,9702],[9711,9711],[9728,9731],[9733,9734],[9737,9737],[9742,9743],[9750,9751],[9756,9759],[9775,9775],[9792,9794],[9824,9839],[9842,9853],[9888,9888],[9917,9918],[12288,12351],[12353,12438],[12441,12543],[12549,12585],[12832,12841],[13383,13383],[13386,13386],[13678,13678],[13838,13838],[13901,13901],[13912,13912],[13926,13926],[14019,14019],[14042,14042],[14073,14073],[14275,14275],[14343,14343],[14355,14355],[14616,14616],[14660,14660],[14800,14801],[14815,14815],[15088,15088],[15114,15114],[15118,15118],[15130,15130],[15182,15182],[15189,15189],[15294,15294],[15360,15360],[15559,15559],[15576,15576],[15578,15578],[15636,15636],[15696,15696],[15794,15794],[15878,15878],[15884,15884],[16004,16004],[16108,16108],[16207,16207],[16352,16352],[16470,16470],[16558,16558],[16581,16581],[16590,16590],[16735,16735],[17209,17209],[17283,17283],[17302,17302],[17373,17373],[17377,17377],[17394,17394],[17411,17411],[17622,17622],[17627,17627],[17640,17640],[17643,17644],[17878,17878],[17883,17883],[17898,17898],[17908,17908],[18211,18211],[18265,18265],[18618,18618],[18620,18620],[18648,18648],[18813,18813],[18819,18819],[19615,19616],[19618,19618],[19731,19737],[19886,19886],[19968,19969],[19971,19971],[19975,19985],[19987,19990],[19992,19998],[20002,20002],[20004,20005],[20007,20008],[20010,20013],[20016,20016],[20018,20018],[20020,20020],[20022,20022],[20024,20027],[20029,20031],[20034,20035],[20037,20037],[20039,20041],[20043,20048],[20050,20052],[20054,20054],[20056,20057],[20060,20065],[20070,20070],[20073,20073],[20080,20081],[20083,20083],[20088,20088],[20094,20094],[20102,20102],[20104,20105],[20107,20111],[20113,20117],[20120,20120],[20122,20123],[20127,20130],[20132,20137],[20139,20142],[20146,20147],[20149,20150],[20152,20155],[20159,20167],[20169,20171],[20173,20174],[20177,20177],[20179,20185],[20189,20191],[20193,20193],[20195,20197],[20200,20200],[20202,20204],[20208,20208],[20210,20211],[20213,20215],[20219,20219],[20221,20221],[20223,20223],[20225,20225],[20232,20235],[20237,20241],[20247,20251],[20254,20256],[20258,20263],[20266,20267],[20269,20269],[20271,20272],[20274,20274],[20276,20276],[20278,20278],[20280,20280],[20282,20282],[20284,20286],[20289,20289],[20291,20291],[20294,20294],[20301,20305],[20307,20307],[20309,20320],[20323,20325],[20327,20327],[20329,20329],[20332,20332],[20335,20336],[20339,20340],[20342,20342],[20344,20344],[20346,20351],[20353,20356],[20360,20361],[20363,20363],[20365,20365],[20367,20367],[20369,20369],[20372,20372],[20375,20376],[20379,20379],[20381,20381],[20384,20384],[20387,20387],[20389,20394],[20396,20396],[20398,20399],[20404,20405],[20409,20409],[20415,20415],[20419,20421],[20426,20426],[20429,20433],[20439,20442],[20444,20447],[20449,20449],[20451,20451],[20454,20454],[20456,20459],[20461,20463],[20465,20465],[20467,20467],[20469,20470],[20472,20472],[20474,20474],[20478,20478],[20492,20493],[20495,20495],[20498,20501],[20504,20506],[20508,20508],[20510,20511],[20513,20513],[20517,20522],[20524,20526],[20532,20532],[20538,20540],[20542,20542],[20545,20545],[20547,20547],[20551,20552],[20556,20556],[20558,20559],[20563,20563],[20565,20565],[20570,20570],[20572,20572],[20577,20577],[20581,20581],[20588,20589],[20592,20592],[20594,20594],[20598,20599],[20603,20603],[20606,20608],[20611,20611],[20613,20613],[20616,20617],[20621,20621],[20626,20626],[20629,20629],[20643,20643],[20645,20645],[20647,20649],[20652,20652],[20658,20658],[20666,20667],[20679,20679],[20686,20687],[20692,20692],[20694,20694],[20698,20698],[20710,20711],[20716,20718],[20720,20720],[20723,20723],[20725,20725],[20731,20731],[20742,20743],[20747,20747],[20754,20754],[20769,20769],[20774,20774],[20787,20788],[20799,20801],[20803,20806],[20808,20809],[20811,20811],[20813,20813],[20817,20817],[20820,20822],[20826,20826],[20828,20828],[20834,20834],[20837,20837],[20840,20840],[20843,20846],[20848,20849],[20851,20857],[20859,20861],[20864,20866],[20869,20869],[20872,20873],[20876,20877],[20879,20879],[20882,20882],[20884,20887],[20889,20889],[20891,20892],[20896,20896],[20898,20898],[20900,20901],[20907,20908],[20910,20915],[20917,20919],[20923,20925],[20928,20928],[20932,20932],[20934,20935],[20937,20937],[20939,20940],[20943,20943],[20945,20945],[20947,20947],[20952,20952],[20955,20955],[20957,20957],[20960,20961],[20964,20964],[20971,20971],[20973,20973],[20975,20976],[20979,20979],[20981,20982],[20984,20989],[20991,20995],[20998,21000],[21002,21002],[21005,21006],[21009,21010],[21014,21019],[21021,21021],[21024,21024],[21028,21028],[21032,21033],[21035,21038],[21040,21040],[21043,21043],[21046,21051],[21053,21053],[21055,21059],[21061,21061],[21066,21069],[21072,21073],[21076,21078],[21084,21084],[21086,21087],[21089,21089],[21093,21093],[21095,21095],[21097,21098],[21103,21103],[21106,21106],[21117,21117],[21119,21119],[21121,21122],[21124,21124],[21128,21128],[21136,21136],[21139,21139],[21147,21147],[21149,21155],[21160,21165],[21169,21171],[21180,21180],[21182,21183],[21187,21187],[21191,21191],[21193,21193],[21195,21195],[21197,21197],[21200,21200],[21202,21202],[21204,21204],[21206,21206],[21208,21208],[21210,21210],[21215,21216],[21220,21220],[21232,21232],[21241,21242],[21246,21248],[21253,21254],[21256,21256],[21261,21261],[21263,21264],[21269,21271],[21273,21274],[21276,21277],[21280,21281],[21283,21283],[21286,21286],[21290,21290],[21294,21294],[21305,21308],[21310,21311],[21313,21313],[21315,21315],[21317,21317],[21319,21322],[21326,21327],[21329,21331],[21333,21335],[21338,21338],[21340,21340],[21342,21348],[21350,21351],[21353,21353],[21355,21356],[21358,21361],[21363,21365],[21367,21368],[21370,21370],[21375,21375],[21378,21378],[21380,21382],[21385,21385],[21387,21389],[21397,21398],[21400,21400],[21402,21402],[21405,21405],[21407,21407],[21410,21411],[21413,21414],[21416,21417],[21422,21422],[21430,21430],[21435,21435],[21438,21439],[21441,21442],[21446,21453],[21457,21457],[21460,21467],[21471,21472],[21475,21478],[21480,21491],[21493,21497],[21499,21501],[21505,21505],[21507,21508],[21510,21510],[21512,21514],[21516,21523],[21525,21527],[21531,21531],[21533,21537],[21539,21539],[21542,21545],[21547,21551],[21553,21554],[21556,21557],[21560,21561],[21563,21566],[21568,21568],[21571,21571],[21574,21576],[21578,21579],[21584,21584],[21586,21593],[21595,21596],[21602,21604],[21606,21606],[21608,21608],[21617,21619],[21621,21624],[21627,21629],[21632,21632],[21634,21634],[21636,21636],[21638,21639],[21641,21641],[21643,21648],[21650,21650],[21652,21654],[21657,21659],[21661,21661],[21665,21665],[21667,21677],[21679,21679],[21681,21681],[21683,21684],[21688,21688],[21690,21691],[21693,21693],[21695,21700],[21702,21705],[21708,21717],[21719,21719],[21721,21722],[21724,21727],[21730,21730],[21733,21738],[21741,21742],[21745,21747],[21754,21754],[21756,21757],[21759,21759],[21761,21761],[21766,21767],[21769,21769],[21775,21777],[21780,21780],[21787,21787],[21789,21789],[21792,21792],[21794,21796],[21799,21799],[21802,21802],[21804,21804],[21806,21809],[21811,21811],[21813,21813],[21815,21815],[21820,21820],[21822,21823],[21825,21825],[21827,21828],[21830,21830],[21833,21834],[21840,21840],[21845,21846],[21852,21852],[21857,21857],[21860,21863],[21866,21870],[21872,21872],[21876,21880],[21883,21884],[21886,21886],[21888,21892],[21894,21899],[21903,21903],[21905,21905],[21908,21908],[21912,21913],[21916,21917],[21919,21919],[21924,21924],[21927,21927],[21937,21937],[21939,21939],[21941,21941],[21943,21943],[21945,21945],[21947,21947],[21949,21950],[21956,21957],[21961,21961],[21964,21965],[21968,21972],[21974,21974],[21980,21983],[21985,21985],[21987,21990],[21992,21992],[21994,21996],[21999,21999],[22002,22003],[22005,22005],[22007,22007],[22013,22014],[22016,22017],[22024,22025],[22028,22028],[22030,22031],[22040,22040],[22042,22043],[22046,22047],[22049,22049],[22051,22052],[22055,22055],[22060,22061],[22065,22066],[22068,22068],[22070,22070],[22073,22073],[22075,22075],[22079,22080],[22082,22082],[22087,22087],[22092,22094],[22100,22100],[22103,22105],[22108,22108],[22114,22114],[22116,22116],[22120,22124],[22129,22129],[22134,22134],[22139,22140],[22148,22150],[22158,22159],[22163,22163],[22170,22170],[22179,22179],[22189,22189],[22191,22191],[22199,22199],[22204,22204],[22218,22218],[22228,22228],[22231,22231],[22234,22235],[22237,22242],[22244,22244],[22251,22251],[22253,22253],[22256,22257],[22260,22261],[22263,22263],[22265,22266],[22269,22271],[22275,22276],[22278,22278],[22280,22282],[22284,22284],[22288,22288],[22297,22297],[22300,22300],[22303,22303],[22306,22307],[22312,22320],[22322,22323],[22329,22331],[22334,22334],[22336,22336],[22338,22338],[22343,22343],[22345,22354],[22359,22359],[22362,22369],[22372,22374],[22376,22381],[22383,22384],[22387,22387],[22390,22391],[22395,22397],[22402,22406],[22408,22408],[22411,22415],[22418,22419],[22421,22421],[22425,22427],[22430,22436],[22438,22439],[22441,22441],[22443,22443],[22445,22447],[22449,22450],[22452,22453],[22456,22456],[22458,22458],[22462,22463],[22466,22467],[22470,22471],[22475,22476],[22478,22479],[22482,22482],[22484,22485],[22487,22490],[22493,22493],[22495,22496],[22500,22500],[22506,22507],[22509,22509],[22511,22511],[22516,22517],[22520,22522],[22524,22525],[22528,22528],[22530,22531],[22534,22535],[22537,22537],[22539,22542],[22544,22545],[22549,22549],[22553,22553],[22558,22558],[22560,22561],[22564,22564],[22567,22568],[22570,22570],[22576,22576],[22578,22578],[22581,22581],[22588,22590],[22596,22598],[22604,22605],[22609,22609],[22612,22612],[22616,22616],[22621,22622],[22629,22629],[22635,22636],[22641,22641],[22654,22654],[22656,22657],[22659,22659],[22661,22661],[22664,22665],[22672,22672],[22674,22675],[22677,22677],[22680,22682],[22686,22687],[22689,22689],[22691,22691],[22694,22694],[22696,22697],[22716,22716],[22721,22721],[22725,22725],[22737,22737],[22741,22741],[22756,22756],[22763,22764],[22766,22766],[22768,22768],[22771,22771],[22774,22774],[22776,22777],[22786,22786],[22788,22788],[22791,22791],[22797,22797],[22799,22800],[22804,22806],[22809,22810],[22812,22812],[22815,22815],[22820,22821],[22823,22823],[22825,22831],[22833,22833],[22836,22836],[22839,22842],[22844,22844],[22849,22850],[22852,22852],[22855,22857],[22859,22859],[22862,22863],[22865,22865],[22867,22872],[22874,22874],[22880,22882],[22885,22885],[22893,22893],[22899,22900],[22902,22902],[22904,22905],[22909,22909],[22913,22916],[22918,22920],[22922,22922],[22925,22925],[22930,22931],[22934,22937],[22942,22942],[22947,22949],[22951,22955],[22957,22959],[22962,22962],[22969,22969],[22971,22971],[22974,22974],[22982,22982],[22984,22984],[22986,22987],[22992,22996],[22999,23000],[23002,23002],[23004,23006],[23011,23013],[23016,23016],[23020,23020],[23022,23022],[23025,23025],[23030,23030],[23033,23033],[23035,23035],[23037,23037],[23039,23041],[23043,23049],[23052,23052],[23057,23057],[23059,23059],[23064,23064],[23068,23068],[23071,23072],[23075,23075],[23077,23077],[23081,23081],[23089,23090],[23092,23094],[23100,23100],[23104,23104],[23110,23110],[23113,23114],[23116,23117],[23125,23125],[23128,23128],[23130,23130],[23134,23134],[23136,23136],[23138,23138],[23140,23140],[23143,23143],[23146,23147],[23155,23159],[23162,23164],[23167,23167],[23170,23170],[23172,23172],[23174,23174],[23186,23187],[23190,23190],[23194,23195],[23198,23198],[23210,23210],[23213,23213],[23217,23219],[23221,23221],[23224,23224],[23230,23230],[23233,23234],[23236,23236],[23241,23241],[23244,23244],[23250,23250],[23252,23254],[23256,23256],[23258,23258],[23260,23260],[23264,23265],[23267,23267],[23270,23270],[23273,23275],[23277,23277],[23281,23281],[23293,23293],[23305,23305],[23318,23319],[23323,23323],[23333,23333],[23340,23340],[23346,23346],[23348,23348],[23351,23351],[23359,23360],[23365,23365],[23376,23377],[23379,23389],[23391,23391],[23394,23398],[23401,23402],[23404,23404],[23408,23409],[23411,23411],[23413,23413],[23418,23418],[23421,23421],[23424,23425],[23427,23429],[23431,23433],[23435,23436],[23439,23439],[23443,23443],[23445,23445],[23447,23454],[23456,23463],[23466,23468],[23472,23472],[23475,23478],[23480,23481],[23485,23487],[23489,23490],[23492,23495],[23500,23500],[23504,23504],[23506,23507],[23517,23519],[23521,23521],[23524,23525],[23528,23528],[23534,23534],[23536,23536],[23544,23548],[23551,23551],[23553,23553],[23556,23556],[23558,23558],[23561,23562],[23567,23567],[23569,23569],[23572,23574],[23576,23576],[23578,23578],[23580,23581],[23586,23586],[23588,23589],[23591,23592],[23594,23594],[23596,23596],[23601,23601],[23604,23604],[23608,23619],[23621,23621],[23624,23627],[23630,23633],[23637,23637],[23641,23641],[23646,23646],[23648,23649],[23651,23651],[23653,23654],[23662,23663],[23665,23665],[23673,23674],[23676,23676],[23678,23679],[23681,23682],[23688,23688],[23690,23690],[23692,23693],[23696,23697],[23700,23700],[23702,23708],[23710,23710],[23712,23712],[23714,23715],[23720,23721],[23723,23725],[23729,23729],[23731,23731],[23733,23733],[23735,23736],[23741,23741],[23743,23743],[23745,23748],[23755,23755],[23762,23762],[23767,23769],[23771,23771],[23777,23777],[23779,23784],[23786,23786],[23789,23789],[23792,23793],[23803,23803],[23807,23812],[23814,23815],[23820,23820],[23822,23822],[23826,23826],[23828,23828],[23830,23830],[23834,23835],[23838,23839],[23841,23841],[23844,23844],[23846,23847],[23849,23849],[23853,23854],[23860,23860],[23862,23862],[23869,23871],[23873,23873],[23877,23877],[23879,23879],[23882,23884],[23886,23886],[23894,23894],[23896,23896],[23898,23899],[23901,23901],[23913,23913],[23915,23916],[23919,23919],[23922,23922],[23924,23924],[23938,23938],[23941,23941],[23949,23949],[23954,23955],[23961,23961],[23965,23965],[23967,23967],[23974,23974],[23986,23986],[23991,23991],[24005,24005],[24007,24007],[24009,24009],[24013,24013],[24027,24027],[24029,24030],[24033,24034],[24037,24041],[24043,24043],[24046,24047],[24049,24052],[24055,24055],[24061,24062],[24065,24067],[24069,24070],[24072,24072],[24076,24076],[24079,24081],[24084,24086],[24088,24093],[24097,24097],[24102,24104],[24109,24110],[24113,24113],[24119,24120],[24123,24125],[24130,24130],[24132,24133],[24140,24140],[24148,24150],[24155,24155],[24158,24158],[24161,24162],[24170,24170],[24178,24180],[24182,24182],[24184,24184],[24186,24189],[24191,24192],[24196,24196],[24198,24199],[24202,24203],[24207,24209],[24211,24215],[24217,24218],[24220,24220],[24222,24224],[24228,24231],[24237,24237],[24241,24241],[24243,24243],[24245,24249],[24252,24252],[24254,24254],[24262,24262],[24265,24267],[24273,24275],[24278,24278],[24281,24281],[24283,24283],[24296,24296],[24298,24298],[24308,24308],[24310,24311],[24314,24314],[24318,24324],[24326,24328],[24330,24331],[24335,24335],[24337,24337],[24339,24339],[24341,24341],[24343,24344],[24347,24347],[24351,24352],[24354,24354],[24357,24362],[24365,24365],[24367,24367],[24369,24369],[24374,24374],[24376,24378],[24380,24380],[24384,24384],[24400,24400],[24402,24403],[24405,24408],[24413,24413],[24415,24415],[24417,24418],[24420,24420],[24422,24423],[24425,24426],[24428,24429],[24432,24433],[24435,24435],[24439,24439],[24441,24441],[24443,24444],[24448,24450],[24452,24453],[24455,24460],[24464,24464],[24466,24466],[24469,24469],[24471,24473],[24475,24476],[24481,24481],[24488,24488],[24490,24490],[24493,24494],[24501,24501],[24503,24503],[24508,24509],[24515,24518],[24521,24521],[24524,24525],[24527,24530],[24534,24537],[24541,24542],[24544,24545],[24548,24548],[24551,24551],[24554,24555],[24557,24558],[24561,24561],[24563,24563],[24565,24565],[24568,24568],[24570,24571],[24573,24582],[24586,24586],[24589,24591],[24594,24594],[24596,24598],[24601,24601],[24603,24605],[24608,24609],[24613,24619],[24623,24623],[24629,24629],[24635,24636],[24639,24639],[24641,24643],[24651,24651],[24653,24653],[24656,24656],[24658,24661],[24665,24666],[24669,24669],[24674,24676],[24679,24685],[24687,24688],[24691,24691],[24694,24694],[24696,24701],[24703,24703],[24707,24708],[24710,24710],[24712,24713],[24716,24717],[24722,24722],[24724,24724],[24726,24726],[24730,24731],[24733,24733],[24735,24736],[24738,24739],[24742,24742],[24744,24744],[24747,24749],[24751,24754],[24756,24756],[24760,24760],[24763,24764],[24773,24775],[24778,24779],[24782,24782],[24785,24785],[24788,24789],[24792,24797],[24799,24800],[24806,24809],[24811,24816],[24819,24820],[24822,24822],[24825,24826],[24832,24833],[24835,24835],[24838,24838],[24840,24841],[24845,24848],[24852,24853],[24858,24858],[24863,24864],[24867,24868],[24870,24871],[24875,24875],[24877,24877],[24895,24895],[24902,24902],[24904,24904],[24906,24906],[24908,24908],[24910,24910],[24913,24913],[24917,24917],[24925,24925],[24930,24930],[24933,24933],[24935,24936],[24940,24941],[24944,24944],[24949,24949],[24951,24951],[24971,24971],[24974,24974],[24980,24981],[24985,24985],[24989,24989],[24999,25001],[25004,25005],[25015,25015],[25018,25018],[25022,25022],[25026,25026],[25032,25032],[25034,25035],[25041,25042],[25044,25044],[25062,25062],[25077,25077],[25087,25087],[25094,25094],[25096,25096],[25098,25106],[25109,25112],[25114,25115],[25119,25119],[25121,25125],[25130,25130],[25132,25134],[25139,25140],[25143,25143],[25149,25155],[25157,25166],[25169,25172],[25176,25176],[25179,25179],[25182,25182],[25187,25187],[25190,25191],[25193,25200],[25203,25203],[25206,25206],[25209,25210],[25212,25216],[25219,25220],[25225,25226],[25233,25240],[25242,25243],[25247,25250],[25252,25253],[25256,25256],[25259,25260],[25265,25265],[25269,25269],[25273,25273],[25275,25277],[25279,25279],[25282,25290],[25292,25294],[25296,25296],[25298,25300],[25302,25308],[25311,25311],[25314,25321],[25324,25327],[25329,25329],[25331,25332],[25334,25335],[25340,25343],[25345,25346],[25351,25353],[25358,25358],[25361,25361],[25363,25363],[25366,25366],[25370,25371],[25373,25382],[25384,25384],[25386,25387],[25391,25391],[25394,25394],[25401,25402],[25405,25405],[25410,25411],[25413,25414],[25417,25417],[25419,25424],[25429,25429],[25438,25439],[25441,25443],[25447,25447],[25449,25449],[25453,25455],[25457,25457],[25462,25463],[25466,25467],[25469,25469],[25472,25472],[25474,25474],[25479,25482],[25484,25484],[25486,25488],[25490,25490],[25494,25494],[25496,25496],[25502,25502],[25504,25504],[25506,25507],[25509,25509],[25511,25514],[25516,25518],[25520,25520],[25523,25524],[25527,25528],[25530,25530],[25532,25532],[25534,25534],[25540,25540],[25542,25542],[25545,25545],[25549,25552],[25554,25554],[25557,25558],[25566,25566],[25568,25569],[25571,25571],[25577,25578],[25581,25581],[25586,25588],[25590,25590],[25592,25592],[25597,25597],[25599,25602],[25605,25605],[25611,25612],[25615,25616],[25618,25620],[25627,25628],[25630,25630],[25632,25633],[25638,25638],[25642,25642],[25644,25645],[25652,25652],[25658,25658],[25661,25661],[25663,25663],[25665,25665],[25668,25672],[25674,25674],[25679,25679],[25682,25682],[25684,25684],[25688,25688],[25691,25691],[25694,25694],[25703,25703],[25705,25705],[25709,25709],[25716,25716],[25720,25722],[25725,25725],[25730,25730],[25732,25733],[25735,25735],[25745,25746],[25749,25750],[25753,25753],[25758,25758],[25764,25764],[25769,25769],[25772,25774],[25776,25776],[25781,25781],[25783,25784],[25786,25786],[25788,25788],[25792,25792],[25794,25794],[25797,25797],[25805,25806],[25808,25808],[25810,25810],[25815,25816],[25822,25822],[25826,25826],[25828,25828],[25830,25830],[25855,25856],[25865,25865],[25874,25874],[25880,25880],[25893,25893],[25899,25899],[25902,25903],[25908,25910],[25912,25913],[25915,25915],[25917,25919],[25925,25925],[25928,25929],[25932,25932],[25935,25935],[25937,25937],[25940,25942],[25945,25945],[25947,25947],[25949,25950],[25954,25955],[25958,25958],[25961,25961],[25963,25964],[25968,25968],[25970,25970],[25972,25972],[25975,25975],[25991,25991],[25995,25996],[26000,26001],[26003,26003],[26007,26007],[26009,26009],[26011,26013],[26015,26017],[26020,26021],[26023,26023],[26025,26025],[26027,26027],[26029,26029],[26031,26032],[26038,26038],[26041,26041],[26044,26045],[26049,26049],[26051,26054],[26059,26060],[26062,26064],[26066,26066],[26070,26071],[26078,26078],[26080,26080],[26082,26082],[26085,26089],[26092,26097],[26100,26104],[26106,26107],[26111,26112],[26114,26116],[26118,26122],[26124,26124],[26126,26127],[26130,26133],[26137,26137],[26141,26141],[26143,26145],[26147,26149],[26151,26152],[26154,26155],[26157,26157],[26159,26159],[26161,26161],[26163,26166],[26170,26170],[26172,26174],[26177,26177],[26179,26179],[26181,26181],[26186,26188],[26191,26192],[26194,26199],[26201,26202],[26206,26207],[26209,26210],[26212,26212],[26214,26214],[26216,26216],[26218,26219],[26222,26225],[26228,26228],[26230,26231],[26234,26234],[26238,26238],[26242,26242],[26244,26245],[26247,26247],[26252,26252],[26257,26257],[26261,26263],[26269,26269],[26279,26280],[26286,26286],[26290,26290],[26292,26294],[26297,26297],[26302,26303],[26312,26312],[26316,26316],[26329,26329],[26331,26333],[26342,26342],[26345,26345],[26352,26352],[26354,26356],[26359,26359],[26361,26361],[26364,26364],[26366,26368],[26376,26379],[26381,26381],[26383,26384],[26387,26389],[26391,26391],[26395,26395],[26397,26397],[26399,26399],[26406,26406],[26408,26408],[26410,26413],[26415,26415],[26417,26417],[26419,26421],[26424,26424],[26426,26426],[26429,26429],[26432,26432],[26434,26436],[26438,26438],[26440,26441],[26444,26444],[26446,26449],[26451,26451],[26453,26454],[26457,26457],[26460,26460],[26462,26465],[26469,26469],[26471,26474],[26477,26477],[26479,26480],[26482,26483],[26485,26485],[26487,26487],[26491,26492],[26494,26495],[26497,26497],[26500,26501],[26503,26503],[26505,26505],[26507,26507],[26509,26509],[26512,26512],[26517,26517],[26519,26520],[26522,26522],[26524,26526],[26530,26531],[26533,26533],[26535,26536],[26538,26539],[26541,26541],[26543,26544],[26546,26547],[26549,26553],[26561,26561],[26563,26564],[26568,26568],[26570,26570],[26575,26580],[26582,26582],[26584,26586],[26588,26590],[26592,26592],[26594,26594],[26597,26597],[26601,26601],[26604,26604],[26607,26609],[26611,26612],[26615,26615],[26621,26621],[26623,26624],[26629,26629],[26631,26636],[26638,26643],[26646,26647],[26653,26653],[26655,26655],[26657,26657],[26665,26666],[26674,26676],[26679,26681],[26683,26686],[26688,26694],[26696,26698],[26700,26700],[26702,26702],[26704,26705],[26707,26709],[26720,26729],[26731,26731],[26735,26735],[26738,26738],[26740,26740],[26742,26743],[26745,26745],[26753,26753],[26755,26755],[26757,26758],[26764,26764],[26767,26767],[26771,26771],[26775,26775],[26784,26784],[26786,26787],[26790,26792],[26797,26797],[26799,26800],[26803,26805],[26812,26818],[26825,26825],[26827,26827],[26829,26829],[26832,26832],[26834,26835],[26837,26837],[26840,26840],[26842,26842],[26848,26848],[26851,26852],[26856,26856],[26858,26860],[26862,26862],[26864,26865],[26869,26869],[26873,26877],[26880,26881],[26885,26886],[26891,26891],[26893,26894],[26896,26899],[26911,26912],[26916,26916],[26922,26922],[26925,26925],[26928,26928],[26932,26932],[26936,26937],[26941,26941],[26943,26943],[26946,26946],[26962,26962],[26964,26964],[26967,26967],[26969,26970],[26973,26974],[26976,26976],[26979,26979],[26982,26982],[26985,26987],[26990,26991],[26993,26993],[26999,27001],[27004,27004],[27008,27008],[27010,27017],[27021,27021],[27025,27025],[27028,27030],[27032,27032],[27035,27036],[27047,27048],[27051,27051],[27053,27053],[27056,27057],[27060,27060],[27063,27063],[27067,27067],[27073,27073],[27075,27075],[27082,27082],[27084,27084],[27086,27086],[27088,27088],[27092,27092],[27098,27100],[27103,27104],[27117,27117],[27121,27122],[27133,27133],[27135,27135],[27146,27146],[27159,27160],[27167,27167],[27169,27169],[27176,27176],[27178,27178],[27183,27183],[27185,27185],[27189,27189],[27197,27198],[27204,27204],[27207,27207],[27216,27217],[27224,27225],[27227,27227],[27230,27230],[27233,27233],[27237,27238],[27249,27249],[27257,27257],[27260,27260],[27264,27264],[27268,27268],[27278,27278],[27280,27281],[27287,27287],[27294,27294],[27296,27296],[27305,27305],[27307,27308],[27334,27334],[27394,27394],[27424,27428],[27431,27431],[27442,27442],[27447,27451],[27454,27454],[27459,27459],[27461,27463],[27465,27465],[27468,27468],[27481,27481],[27490,27495],[27498,27498],[27513,27513],[27515,27516],[27521,27524],[27526,27527],[27529,27531],[27533,27533],[27538,27539],[27542,27542],[27546,27547],[27553,27553],[27555,27555],[27562,27562],[27571,27573],[27575,27575],[27583,27583],[27585,27586],[27589,27589],[27595,27597],[27599,27600],[27602,27607],[27609,27609],[27611,27611],[27617,27617],[27626,27627],[27631,27631],[27635,27635],[27637,27637],[27641,27641],[27645,27645],[27653,27655],[27661,27661],[27663,27665],[27667,27670],[27672,27675],[27679,27679],[27681,27682],[27684,27684],[27686,27690],[27694,27696],[27698,27698],[27700,27701],[27704,27704],[27709,27714],[27718,27723],[27728,27728],[27732,27733],[27735,27735],[27739,27745],[27748,27748],[27751,27755],[27757,27757],[27760,27760],[27762,27762],[27764,27764],[27766,27766],[27769,27769],[27773,27774],[27777,27785],[27788,27788],[27791,27792],[27795,27796],[27800,27803],[27807,27807],[27809,27809],[27811,27819],[27821,27822],[27825,27827],[27832,27839],[27842,27845],[27847,27847],[27849,27850],[27852,27852],[27856,27856],[27859,27863],[27865,27868],[27870,27870],[27872,27875],[27877,27877],[27880,27880],[27882,27883],[27886,27889],[27891,27891],[27893,27896],[27898,27902],[27905,27905],[27908,27908],[27911,27912],[27915,27916],[27918,27918],[27921,27923],[27927,27931],[27934,27934],[27938,27939],[27941,27941],[27943,27944],[27946,27947],[27949,27950],[27953,27957],[27960,27967],[27969,27969],[27971,27971],[27973,27979],[27981,27989],[27993,27996],[27998,28001],[28003,28003],[28005,28006],[28009,28010],[28012,28016],[28018,28018],[28020,28020],[28023,28024],[28028,28028],[28034,28034],[28036,28037],[28040,28041],[28044,28046],[28048,28049],[28051,28053],[28056,28056],[28059,28059],[28061,28068],[28070,28075],[28078,28079],[28082,28082],[28084,28085],[28088,28088],[28095,28096],[28100,28103],[28107,28108],[28111,28111],[28113,28113],[28118,28118],[28120,28121],[28124,28129],[28132,28132],[28134,28134],[28139,28140],[28142,28143],[28145,28145],[28147,28148],[28151,28151],[28153,28153],[28155,28156],[28165,28165],[28170,28170],[28172,28174],[28176,28177],[28180,28180],[28182,28183],[28186,28186],[28189,28189],[28191,28193],[28195,28197],[28201,28201],[28203,28203],[28205,28205],[28207,28208],[28210,28210],[28212,28212],[28216,28216],[28218,28218],[28220,28220],[28227,28228],[28233,28233],[28237,28238],[28241,28241],[28243,28244],[28246,28246],[28248,28248],[28251,28253],[28255,28255],[28259,28259],[28267,28267],[28270,28270],[28274,28274],[28276,28276],[28286,28287],[28289,28289],[28291,28291],[28293,28295],[28297,28297],[28301,28301],[28303,28304],[28312,28312],[28314,28314],[28316,28316],[28318,28320],[28322,28322],[28325,28327],[28330,28330],[28335,28335],[28337,28338],[28340,28343],[28345,28347],[28349,28349],[28353,28355],[28358,28359],[28361,28361],[28363,28363],[28365,28365],[28367,28367],[28369,28369],[28371,28373],[28375,28376],[28378,28378],[28382,28386],[28388,28395],[28404,28404],[28409,28409],[28418,28418],[28422,28422],[28424,28425],[28427,28427],[28431,28431],[28435,28438],[28448,28448],[28452,28452],[28454,28454],[28457,28459],[28461,28461],[28463,28463],[28465,28465],[28467,28468],[28470,28471],[28473,28473],[28475,28476],[28478,28478],[28486,28487],[28491,28491],[28493,28493],[28495,28495],[28502,28502],[28504,28504],[28508,28508],[28510,28511],[28514,28514],[28518,28518],[28521,28521],[28525,28526],[28530,28530],[28532,28533],[28536,28536],[28538,28538],[28540,28542],[28546,28546],[28548,28548],[28552,28553],[28556,28558],[28571,28572],[28577,28577],[28581,28581],[28583,28583],[28586,28586],[28589,28589],[28595,28596],[28598,28598],[28601,28601],[28604,28605],[28608,28608],[28610,28610],[28617,28617],[28619,28619],[28625,28626],[28638,28638],[28640,28641],[28649,28649],[28654,28655],[28684,28685],[28689,28689],[28692,28692],[28698,28699],[28707,28707],[28721,28721],[28725,28725],[28729,28729],[28732,28732],[28744,28744],[28748,28748],[28751,28751],[28766,28766],[28779,28781],[28783,28784],[28789,28790],[28792,28792],[28796,28796],[28798,28800],[28805,28806],[28809,28810],[28812,28812],[28814,28814],[28818,28818],[28820,28822],[28824,28825],[28828,28829],[28831,28831],[28835,28835],[28843,28847],[28849,28849],[28851,28851],[28855,28857],[28859,28861],[28864,28867],[28872,28872],[28874,28874],[28884,28884],[28888,28889],[28891,28893],[28895,28896],[28900,28900],[28902,28905],[28907,28909],[28911,28911],[28918,28919],[28921,28923],[28925,28925],[28934,28934],[28937,28938],[28940,28940],[28944,28944],[28947,28947],[28949,28954],[28956,28956],[28958,28958],[28966,28966],[28975,28977],[28982,28982],[28993,28993],[28995,28995],[28997,28997],[29002,29004],[29006,29006],[29011,29011],[29020,29020],[29022,29023],[29028,29028],[29030,29032],[29038,29038],[29042,29044],[29048,29048],[29050,29050],[29053,29053],[29060,29060],[29063,29063],[29066,29066],[29071,29071],[29076,29076],[29080,29081],[29083,29084],[29087,29088],[29093,29093],[29096,29096],[29100,29100],[29107,29107],[29109,29109],[29113,29113],[29115,29115],[29123,29123],[29130,29131],[29134,29135],[29140,29141],[29146,29146],[29152,29152],[29157,29157],[29159,29159],[29166,29166],[29177,29177],[29190,29191],[29204,29204],[29210,29210],[29213,29213],[29215,29215],[29224,29224],[29226,29226],[29228,29228],[29232,29233],[29237,29241],[29243,29243],[29245,29245],[29247,29247],[29249,29250],[29255,29256],[29260,29261],[29266,29266],[29270,29270],[29273,29275],[29277,29277],[29279,29279],[29281,29282],[29284,29287],[29289,29289],[29294,29295],[29298,29298],[29301,29301],[29305,29307],[29310,29313],[29316,29316],[29319,29319],[29322,29323],[29325,29325],[29327,29327],[29330,29330],[29343,29343],[29352,29352],[29356,29357],[29359,29360],[29364,29364],[29366,29369],[29377,29380],[29384,29385],[29389,29390],[29392,29392],[29394,29394],[29399,29399],[29401,29401],[29405,29406],[29408,29409],[29416,29417],[29420,29428],[29431,29432],[29434,29436],[29441,29441],[29443,29444],[29447,29447],[29450,29450],[29454,29454],[29459,29459],[29461,29463],[29467,29470],[29473,29474],[29477,29477],[29481,29484],[29486,29489],[29492,29492],[29495,29498],[29502,29503],[29517,29517],[29520,29520],[29522,29522],[29527,29527],[29536,29536],[29548,29549],[29551,29551],[29556,29556],[29566,29566],[29571,29572],[29575,29575],[29577,29577],[29579,29579],[29582,29582],[29585,29587],[29589,29590],[29592,29595],[29598,29602],[29604,29606],[29609,29609],[29611,29611],[29613,29619],[29622,29623],[29625,29628],[29631,29632],[29634,29634],[29637,29637],[29639,29645],[29647,29650],[29653,29654],[29657,29657],[29659,29659],[29661,29662],[29664,29664],[29666,29667],[29669,29671],[29673,29675],[29677,29677],[29680,29680],[29682,29682],[29685,29685],[29687,29690],[29693,29693],[29696,29696],[29699,29706],[29710,29712],[29716,29716],[29722,29723],[29727,29727],[29729,29730],[29732,29734],[29736,29736],[29738,29744],[29746,29750],[29756,29756],[29760,29766],[29777,29777],[29779,29783],[29785,29791],[29794,29794],[29799,29800],[29804,29805],[29808,29809],[29811,29811],[29814,29815],[29822,29822],[29824,29825],[29827,29827],[29830,29832],[29835,29835],[29838,29838],[29840,29840],[29842,29842],[29848,29848],[29852,29852],[29854,29856],[29861,29861],[29863,29866],[29868,29868],[29870,29870],[29873,29874],[29882,29882],[29888,29888],[29906,29906],[29910,29910],[29912,29912],[29916,29916],[29918,29918],[29920,29920],[29922,29924],[29926,29926],[29934,29935],[29940,29940],[29942,29943],[29947,29947],[29951,29951],[29956,29956],[29965,29965],[29967,29967],[29969,29969],[29971,29971],[29975,29978],[29980,29980],[29983,29983],[29985,29985],[29989,29990],[29992,29997],[29999,30003],[30005,30005],[30007,30008],[30010,30011],[30014,30014],[30016,30016],[30021,30021],[30024,30024],[30027,30028],[30030,30031],[30036,30036],[30038,30038],[30041,30044],[30052,30054],[30058,30058],[30060,30060],[30063,30063],[30066,30066],[30068,30068],[30072,30073],[30079,30079],[30081,30081],[30083,30083],[30086,30086],[30091,30091],[30093,30093],[30095,30098],[30100,30100],[30102,30103],[30105,30106],[30109,30109],[30111,30117],[30123,30133],[30136,30137],[30140,30142],[30146,30149],[30151,30154],[30157,30157],[30162,30166],[30168,30168],[30171,30171],[30174,30174],[30178,30180],[30182,30184],[30186,30187],[30192,30193],[30196,30196],[30201,30201],[30204,30204],[30207,30209],[30211,30211],[30213,30214],[30218,30218],[30220,30220],[30224,30224],[30229,30229],[30231,30233],[30235,30235],[30239,30240],[30242,30242],[30244,30246],[30249,30251],[30253,30253],[30256,30256],[30259,30261],[30264,30264],[30268,30268],[30270,30272],[30275,30275],[30284,30285],[30292,30292],[30294,30295],[30300,30300],[30302,30302],[30307,30307],[30315,30315],[30319,30319],[30328,30328],[30331,30331],[30333,30335],[30338,30338],[30340,30340],[30342,30344],[30347,30347],[30350,30350],[30353,30353],[30355,30355],[30357,30358],[30361,30361],[30363,30363],[30366,30366],[30372,30372],[30374,30374],[30381,30382],[30385,30386],[30388,30388],[30399,30399],[30402,30402],[30405,30406],[30408,30410],[30413,30418],[30420,30420],[30422,30424],[30427,30427],[30431,30431],[30437,30438],[30446,30447],[30449,30450],[30452,30452],[30455,30457],[30460,30460],[30462,30462],[30465,30465],[30468,30468],[30471,30475],[30477,30477],[30489,30490],[30495,30496],[30498,30498],[30502,30502],[30504,30505],[30508,30509],[30511,30511],[30517,30520],[30522,30522],[30524,30524],[30528,30529],[30531,30532],[30535,30535],[30542,30542],[30544,30545],[30554,30555],[30561,30563],[30565,30566],[30568,30568],[30571,30572],[30585,30585],[30589,30592],[30596,30597],[30603,30606],[30609,30610],[30623,30624],[30626,30626],[30629,30629],[30631,30631],[30633,30637],[30640,30640],[30643,30643],[30645,30645],[30651,30651],[30653,30653],[30655,30655],[30669,30669],[30679,30679],[30683,30684],[30686,30686],[30690,30691],[30693,30693],[30695,30695],[30697,30697],[30699,30702],[30704,30704],[30707,30707],[30710,30710],[30712,30712],[30715,30722],[30724,30724],[30726,30726],[30729,30729],[30732,30733],[30737,30738],[30740,30740],[30742,30744],[30746,30746],[30748,30749],[30751,30752],[30755,30755],[30757,30759],[30761,30761],[30763,30766],[30768,30768],[30772,30773],[30775,30780],[30782,30782],[30784,30785],[30789,30789],[30791,30791],[30794,30794],[30796,30798],[30800,30800],[30802,30802],[30804,30807],[30809,30810],[30813,30813],[30826,30830],[30839,30839],[30844,30844],[30847,30847],[30851,30851],[30855,30857],[30860,30863],[30865,30865],[30867,30867],[30871,30872],[30874,30876],[30879,30879],[30881,30881],[30883,30883],[30885,30885],[30887,30888],[30896,30900],[30902,30902],[30905,30905],[30910,30910],[30913,30913],[30917,30917],[30921,30923],[30927,30928],[30932,30933],[30937,30937],[30940,30940],[30945,30945],[30952,30952],[30956,30956],[30962,30962],[30964,30964],[30967,30967],[30969,30971],[30977,30977],[30981,30981],[30988,30988],[30995,30995],[31006,31006],[31012,31012],[31028,31029],[31034,31036],[31038,31038],[31040,31041],[31043,31043],[31046,31051],[31054,31056],[31059,31059],[31061,31063],[31066,31072],[31074,31074],[31077,31077],[31079,31080],[31085,31085],[31087,31087],[31090,31090],[31095,31096],[31098,31098],[31100,31100],[31102,31102],[31104,31105],[31108,31109],[31114,31115],[31119,31119],[31122,31122],[31124,31124],[31128,31128],[31130,31131],[31140,31140],[31143,31143],[31155,31155],[31161,31163],[31165,31166],[31168,31169],[31171,31171],[31174,31174],[31177,31177],[31179,31179],[31181,31181],[31185,31186],[31189,31189],[31192,31192],[31199,31199],[31203,31204],[31206,31207],[31209,31209],[31211,31213],[31215,31216],[31224,31224],[31227,31227],[31229,31230],[31232,31232],[31234,31235],[31238,31238],[31243,31246],[31249,31249],[31252,31252],[31255,31255],[31257,31258],[31262,31262],[31264,31264],[31267,31267],[31283,31283],[31287,31287],[31289,31289],[31291,31293],[31295,31295],[31300,31300],[31302,31302],[31313,31313],[31319,31319],[31321,31321],[31324,31324],[31327,31327],[31344,31344],[31348,31348],[31350,31354],[31359,31361],[31363,31366],[31368,31368],[31370,31370],[31373,31374],[31377,31378],[31381,31384],[31388,31389],[31391,31392],[31395,31395],[31397,31398],[31400,31400],[31404,31405],[31411,31411],[31416,31416],[31423,31423],[31435,31435],[31441,31441],[31446,31446],[31448,31449],[31454,31456],[31459,31459],[31461,31462],[31467,31467],[31469,31469],[31471,31471],[31481,31482],[31485,31485],[31487,31487],[31491,31492],[31494,31494],[31496,31496],[31498,31499],[31503,31503],[31505,31505],[31508,31509],[31513,31513],[31515,31515],[31518,31518],[31520,31520],[31524,31526],[31528,31528],[31530,31532],[31534,31535],[31537,31537],[31539,31539],[31544,31544],[31546,31546],[31548,31548],[31550,31550],[31552,31552],[31557,31557],[31559,31559],[31561,31561],[31563,31564],[31567,31570],[31572,31572],[31574,31574],[31576,31576],[31578,31581],[31584,31584],[31586,31586],[31588,31590],[31598,31598],[31601,31602],[31605,31607],[31609,31609],[31611,31612],[31614,31614],[31616,31616],[31621,31621],[31629,31629],[31632,31632],[31635,31639],[31644,31645],[31649,31650],[31654,31661],[31665,31665],[31668,31668],[31672,31672],[31681,31681],[31686,31687],[31692,31692],[31697,31697],[31699,31699],[31705,31706],[31709,31709],[31713,31713],[31717,31718],[31722,31722],[31726,31727],[31729,31729],[31735,31735],[31740,31740],[31742,31742],[31747,31747],[31751,31751],[31753,31753],[31755,31756],[31759,31759],[31765,31766],[31773,31773],[31775,31776],[31782,31783],[31786,31786],[31792,31792],[31800,31800],[31807,31809],[31821,31821],[31845,31845],[31859,31860],[31867,31869],[31881,31881],[31889,31890],[31893,31893],[31895,31896],[31900,31903],[31906,31906],[31908,31909],[31914,31914],[31918,31918],[31921,31923],[31929,31929],[31932,31935],[31937,31937],[31941,31941],[31943,31944],[31946,31946],[31948,31949],[31954,31954],[31957,31959],[31961,31961],[31964,31964],[31967,31968],[31976,31976],[31983,31983],[31989,31989],[31992,31992],[31995,31995],[32010,32010],[32032,32032],[32034,32034],[32039,32039],[32043,32043],[32047,32047],[32092,32092],[32110,32110],[32119,32119],[32166,32166],[32174,32174],[32288,32288],[32290,32290],[32315,32315],[32321,32321],[32324,32324],[32327,32327],[32386,32386],[32411,32411],[32415,32491],[32493,32566],[32568,32568],[32570,32570],[32578,32578],[32580,32581],[32589,32589],[32592,32593],[32596,32597],[32599,32600],[32602,32602],[32607,32607],[32609,32610],[32616,32618],[32622,32622],[32625,32626],[32628,32628],[32630,32630],[32633,32633],[32637,32638],[32641,32641],[32650,32650],[32652,32652],[32654,32654],[32657,32657],[32659,32662],[32666,32666],[32669,32671],[32673,32673],[32676,32676],[32679,32679],[32687,32690],[32696,32697],[32700,32701],[32703,32707],[32709,32709],[32712,32712],[32714,32714],[32716,32716],[32718,32718],[32724,32725],[32728,32731],[32735,32737],[32741,32742],[32745,32745],[32750,32753],[32755,32755],[32759,32759],[32763,32764],[32766,32766],[32768,32769],[32771,32775],[32779,32781],[32783,32786],[32788,32793],[32796,32796],[32800,32800],[32802,32802],[32804,32810],[32816,32817],[32819,32819],[32821,32824],[32827,32827],[32829,32829],[32831,32831],[32834,32835],[32838,32838],[32842,32845],[32850,32850],[32852,32852],[32856,32856],[32858,32858],[32873,32874],[32881,32881],[32895,32896],[32899,32900],[32902,32903],[32905,32905],[32907,32908],[32915,32915],[32918,32918],[32920,32920],[32922,32925],[32927,32930],[32932,32933],[32937,32939],[32941,32943],[32945,32946],[32948,32948],[32951,32952],[32954,32954],[32956,32964],[32966,32966],[32968,32968],[32972,32974],[32982,32983],[32985,32990],[32992,32993],[32995,32997],[32999,33005],[33007,33012],[33014,33014],[33016,33016],[33018,33018],[33020,33021],[33026,33026],[33030,33030],[33033,33034],[33037,33044],[33046,33046],[33048,33048],[33050,33050],[33054,33055],[33065,33065],[33068,33068],[33071,33071],[33073,33074],[33078,33078],[33080,33080],[33086,33087],[33094,33094],[33096,33096],[33098,33100],[33104,33109],[33112,33114],[33120,33120],[33125,33125],[33127,33129],[33133,33137],[33140,33140],[33145,33152],[33154,33154],[33160,33160],[33162,33162],[33167,33167],[33169,33169],[33176,33177],[33179,33181],[33187,33187],[33190,33190],[33192,33192],[33194,33194],[33203,33203],[33210,33211],[33216,33219],[33222,33222],[33226,33226],[33228,33228],[33233,33233],[33244,33244],[33251,33251],[33255,33255],[33258,33258],[33260,33261],[33267,33268],[33275,33276],[33278,33278],[33280,33282],[33284,33286],[33292,33293],[33296,33296],[33298,33298],[33300,33300],[33307,33308],[33310,33315],[33317,33317],[33320,33320],[33322,33325],[33327,33337],[33339,33339],[33342,33342],[33348,33349],[33351,33351],[33353,33353],[33355,33355],[33358,33359],[33368,33368],[33370,33370],[33375,33375],[33384,33384],[33390,33392],[33394,33396],[33401,33402],[33405,33407],[33410,33412],[33416,33416],[33418,33419],[33421,33423],[33425,33426],[33431,33433],[33436,33437],[33439,33441],[33443,33446],[33448,33457],[33459,33460],[33463,33465],[33468,33470],[33473,33473],[33476,33476],[33479,33487],[33489,33493],[33495,33496],[33499,33500],[33502,33505],[33507,33511],[33515,33515],[33519,33519],[33521,33521],[33524,33524],[33527,33527],[33529,33529],[33531,33531],[33534,33534],[33536,33545],[33547,33548],[33550,33551],[33553,33553],[33555,33557],[33559,33559],[33562,33565],[33575,33576],[33579,33581],[33583,33583],[33585,33585],[33587,33590],[33592,33594],[33596,33597],[33600,33601],[33603,33604],[33606,33607],[33609,33609],[33615,33620],[33622,33622],[33625,33628],[33630,33633],[33635,33647],[33655,33656],[33659,33661],[33669,33670],[33673,33673],[33678,33678],[33682,33683],[33688,33689],[33691,33694],[33696,33696],[33704,33707],[33712,33716],[33718,33722],[33724,33725],[33727,33730],[33733,33733],[33735,33735],[33737,33738],[33740,33741],[33743,33743],[33748,33748],[33750,33750],[33752,33752],[33756,33757],[33759,33761],[33765,33765],[33769,33770],[33776,33778],[33784,33785],[33788,33789],[33793,33793],[33795,33796],[33798,33798],[33803,33807],[33809,33809],[33816,33816],[33818,33818],[33820,33821],[33827,33833],[33841,33841],[33843,33843],[33848,33849],[33852,33853],[33862,33862],[33870,33870],[33873,33873],[33878,33879],[33881,33884],[33889,33889],[33891,33891],[33897,33897],[33899,33901],[33904,33905],[33907,33910],[33912,33912],[33914,33914],[33922,33922],[33924,33924],[33927,33929],[33931,33932],[33934,33934],[33936,33936],[33943,33943],[33945,33945],[33948,33948],[33951,33951],[33953,33953],[33960,33960],[33967,33967],[33969,33970],[33972,33972],[33976,33979],[33981,33981],[33983,33983],[33985,33986],[33988,33988],[33991,33991],[33993,33994],[33997,33997],[33999,34001],[34003,34003],[34006,34006],[34013,34013],[34015,34016],[34018,34019],[34021,34022],[34028,34028],[34032,34032],[34044,34044],[34047,34048],[34051,34051],[34056,34056],[34058,34058],[34060,34060],[34065,34065],[34067,34067],[34071,34071],[34074,34074],[34079,34079],[34081,34081],[34091,34092],[34103,34109],[34115,34115],[34120,34122],[34134,34135],[34137,34137],[34142,34142],[34148,34148],[34152,34152],[34160,34160],[34162,34162],[34164,34164],[34169,34171],[34174,34174],[34177,34177],[34180,34181],[34183,34183],[34191,34191],[34203,34204],[34210,34210],[34212,34212],[34216,34216],[34218,34218],[34222,34224],[34227,34227],[34231,34233],[34239,34239],[34241,34241],[34249,34249],[34255,34256],[34259,34259],[34261,34261],[34268,34268],[34271,34272],[34276,34276],[34278,34278],[34280,34281],[34299,34299],[34303,34303],[34309,34309],[34321,34321],[34326,34326],[34328,34328],[34343,34343],[34345,34345],[34360,34360],[34364,34364],[34381,34388],[34394,34394],[34398,34398],[34402,34402],[34404,34404],[34411,34412],[34414,34414],[34417,34417],[34423,34434],[34436,34436],[34438,34438],[34442,34445],[34451,34451],[34453,34453],[34460,34461],[34467,34468],[34471,34474],[34476,34476],[34479,34482],[34484,34486],[34490,34490],[34496,34496],[34499,34500],[34502,34503],[34505,34507],[34510,34513],[34516,34516],[34520,34521],[34523,34523],[34526,34527],[34532,34532],[34537,34537],[34541,34542],[34544,34548],[34552,34553],[34558,34558],[34560,34560],[34562,34563],[34567,34570],[34573,34574],[34576,34576],[34578,34579],[34581,34581],[34583,34584],[34586,34586],[34588,34588],[34590,34590],[34593,34595],[34597,34597],[34601,34601],[34606,34606],[34609,34609],[34612,34612],[34615,34615],[34619,34619],[34622,34623],[34631,34633],[34636,34636],[34638,34638],[34643,34643],[34647,34649],[34656,34656],[34659,34661],[34670,34670],[34672,34672],[34674,34674],[34676,34676],[34678,34678],[34683,34686],[34690,34691],[34693,34693],[34696,34696],[34699,34699],[34701,34701],[34707,34707],[34711,34711],[34719,34720],[34723,34723],[34728,34728],[34731,34733],[34735,34735],[34737,34737],[34739,34739],[34741,34741],[34746,34746],[34749,34749],[34752,34752],[34758,34758],[34762,34763],[34767,34767],[34769,34771],[34779,34779],[34784,34784],[34789,34789],[34794,34795],[34798,34798],[34809,34809],[34814,34814],[34819,34819],[34826,34827],[34835,34835],[34837,34838],[34843,34843],[34849,34850],[34866,34866],[34873,34873],[34876,34876],[34880,34880],[34883,34885],[34892,34894],[34898,34898],[34900,34900],[34903,34903],[34905,34905],[34912,34917],[34920,34921],[34923,34924],[34926,34926],[34928,34928],[34930,34930],[34935,34935],[34941,34943],[34945,34946],[34948,34950],[34952,34952],[34955,34955],[34957,34957],[34962,34962],[34966,34967],[34972,34972],[34978,34978],[34980,34980],[34986,34987],[34989,34989],[34991,34991],[34993,34993],[34999,34999],[35004,35004],[35009,35010],[35013,35014],[35016,35017],[35022,35022],[35026,35026],[35028,35029],[35032,35033],[35035,35035],[35039,35039],[35042,35045],[35048,35048],[35056,35057],[35059,35060],[35064,35065],[35068,35068],[35070,35070],[35074,35074],[35082,35082],[35088,35088],[35090,35091],[35093,35093],[35097,35099],[35103,35103],[35105,35105],[35109,35109],[35114,35115],[35119,35120],[35124,35124],[35126,35126],[35137,35137],[35140,35140],[35157,35157],[35162,35162],[35164,35164],[35166,35167],[35174,35174],[35179,35179],[35195,35195],[35199,35199],[35201,35201],[35203,35203],[35206,35206],[35265,35276],[35278,35282],[35286,35286],[35290,35290],[35292,35292],[35294,35295],[35299,35299],[35301,35302],[35307,35307],[35309,35309],[35311,35311],[35313,35313],[35315,35315],[35327,35328],[35332,35332],[35335,35335],[35354,35354],[35390,35390],[35400,35400],[35423,35423],[35449,35449],[35465,35466],[35475,35475],[35591,35591],[35622,35622],[35686,35686],[35692,35692],[35744,35755],[35757,35817],[35819,35848],[35850,35895],[35900,35900],[35903,35903],[35905,35905],[35910,35911],[35913,35913],[35916,35916],[35925,35925],[35930,35930],[35937,35938],[35944,35944],[35946,35947],[35950,35950],[35955,35955],[35960,35962],[35970,35970],[35973,35974],[35977,35978],[35980,35980],[35988,35988],[35992,35992],[36125,36127],[36129,36196],[36198,36199],[36202,36203],[36205,36205],[36208,36208],[36211,36215],[36225,36225],[36228,36229],[36234,36235],[36241,36241],[36244,36244],[36255,36255],[36259,36259],[36271,36271],[36273,36273],[36275,36277],[36280,36280],[36282,36282],[36284,36284],[36286,36287],[36290,36292],[36294,36294],[36299,36300],[36302,36305],[36310,36311],[36314,36315],[36317,36319],[36323,36324],[36328,36328],[36330,36332],[36335,36335],[36337,36337],[36339,36339],[36341,36347],[36349,36349],[36357,36357],[36361,36362],[36364,36364],[36367,36367],[36370,36370],[36372,36372],[36381,36383],[36386,36387],[36390,36390],[36393,36394],[36396,36396],[36398,36399],[36401,36401],[36405,36406],[36409,36410],[36413,36413],[36416,36418],[36420,36421],[36423,36427],[36432,36434],[36441,36442],[36444,36444],[36450,36450],[36454,36454],[36457,36457],[36460,36461],[36463,36464],[36466,36466],[36468,36468],[36470,36470],[36476,36479],[36481,36481],[36485,36485],[36487,36487],[36495,36496],[36500,36500],[36508,36508],[36510,36510],[36523,36524],[36527,36527],[36530,36530],[36538,36538],[36558,36558],[36710,36764],[36766,36767],[36771,36771],[36776,36777],[36779,36779],[36784,36785],[36790,36790],[36793,36793],[36797,36799],[36801,36802],[36804,36805],[36807,36808],[36814,36814],[36816,36817],[36819,36821],[36824,36825],[36827,36831],[36834,36834],[36836,36838],[36840,36843],[36845,36846],[36848,36848],[36851,36851],[36855,36858],[36861,36861],[36864,36870],[36873,36875],[36877,36877],[36879,36882],[36884,36884],[36886,36887],[36890,36891],[36893,36898],[36902,36902],[36909,36911],[36916,36918],[36920,36920],[36923,36924],[36926,36926],[36929,36930],[36932,36932],[36934,36935],[36941,36941],[36943,36947],[36951,36952],[36955,36955],[36962,36963],[36965,36965],[36968,36968],[36973,36974],[36980,36981],[36985,36985],[36989,36989],[36991,36992],[36994,36995],[37000,37000],[37003,37003],[37009,37009],[37011,37011],[37013,37013],[37015,37017],[37019,37019],[37021,37021],[37024,37027],[37030,37030],[37032,37032],[37034,37034],[37036,37036],[37038,37046],[37048,37051],[37053,37055],[37057,37057],[37059,37061],[37063,37064],[37066,37066],[37070,37073],[37075,37075],[37079,37079],[37082,37085],[37089,37090],[37092,37092],[37094,37096],[37098,37099],[37101,37101],[37103,37103],[37108,37108],[37112,37112],[37117,37120],[37122,37125],[37132,37132],[37137,37137],[37143,37146],[37148,37148],[37150,37150],[37152,37152],[37154,37155],[37163,37163],[37167,37167],[37169,37169],[37177,37177],[37186,37187],[37189,37190],[37193,37200],[37202,37202],[37207,37207],[37210,37210],[37213,37214],[37217,37222],[37225,37226],[37228,37228],[37230,37234],[37236,37242],[37245,37247],[37253,37253],[37255,37255],[37257,37257],[37259,37261],[37264,37266],[37274,37275],[37282,37283],[37288,37288],[37290,37290],[37293,37295],[37300,37301],[37306,37306],[37310,37310],[37319,37319],[37321,37322],[37324,37329],[37340,37340],[37492,37492],[37518,37518],[37550,37550],[37574,37574],[37576,37576],[37694,37694],[37738,37738],[37775,37775],[37834,37834],[37846,37846],[37950,37950],[37995,37995],[38021,38032],[38034,38086],[38088,38098],[38101,38117],[38119,38175],[38177,38262],[38271,38271],[38376,38379],[38381,38418],[38420,38426],[38428,38429],[38431,38431],[38433,38434],[38442,38442],[38446,38446],[38449,38454],[38459,38461],[38463,38464],[38466,38466],[38468,38473],[38475,38478],[38480,38481],[38484,38485],[38491,38491],[38494,38495],[38497,38498],[38500,38500],[38503,38506],[38508,38508],[38514,38514],[38516,38519],[38531,38531],[38533,38534],[38536,38536],[38539,38539],[38541,38541],[38543,38544],[38548,38548],[38551,38553],[38556,38556],[38567,38567],[38569,38569],[38576,38576],[38579,38579],[38582,38582],[38585,38586],[38588,38590],[38592,38593],[38596,38599],[38601,38602],[38604,38607],[38610,38610],[38613,38613],[38624,38624],[38632,38634],[38639,38639],[38641,38641],[38643,38643],[38646,38647],[38649,38649],[38654,38654],[38656,38657],[38660,38665],[38669,38671],[38675,38675],[38678,38678],[38684,38684],[38686,38686],[38696,38696],[38698,38698],[38701,38701],[38704,38704],[38706,38706],[38712,38713],[38718,38718],[38738,38739],[38742,38742],[38745,38745],[38747,38747],[38750,38750],[38752,38754],[38757,38757],[38761,38761],[38764,38764],[38768,38768],[38771,38772],[38774,38774],[38776,38776],[38778,38778],[38780,38781],[38783,38783],[38785,38785],[38789,38789],[38795,38795],[38797,38797],[38801,38802],[38804,38804],[38808,38808],[38816,38817],[38819,38819],[38823,38824],[38827,38831],[38834,38836],[38850,38850],[38886,38893],[38899,38899],[38901,38902],[39029,39057],[39059,39060],[39062,39074],[39076,39079],[39118,39125],[39127,39130],[39134,39135],[39143,39144],[39181,39181],[39184,39184],[39214,39214],[39252,39253],[39267,39267],[39269,39269],[39271,39293],[39295,39297],[39299,39309],[39311,39321],[39325,39326],[39333,39333],[39335,39336],[39532,39571],[39573,39592],[39600,39601],[39606,39608],[39610,39610],[39612,39612],[39616,39619],[39621,39621],[39627,39628],[39630,39630],[39633,39633],[39635,39635],[39640,39640],[39647,39647],[39649,39650],[39654,39654],[39659,39659],[39661,39661],[39663,39663],[39673,39673],[39675,39675],[39677,39677],[39683,39683],[39688,39688],[39695,39695],[39698,39699],[39704,39704],[39711,39711],[39715,39715],[39727,39727],[39730,39730],[39734,39735],[39739,39740],[39745,39753],[39755,39755],[39757,39757],[39759,39759],[39761,39761],[39764,39764],[40060,40067],[40069,40082],[40084,40164],[40479,40499],[40501,40530],[40532,40548],[40550,40564],[40574,40576],[40578,40578],[40583,40584],[40587,40587],[40593,40595],[40598,40598],[40605,40605],[40607,40607],[40614,40614],[40628,40628],[40632,40633],[40635,40635],[40637,40638],[40644,40644],[40647,40647],[40649,40649],[40653,40655],[40657,40657],[40660,40660],[40664,40664],[40667,40669],[40671,40674],[40677,40677],[40679,40679],[40681,40682],[40687,40687],[40697,40697],[40699,40700],[40702,40702],[40715,40715],[40717,40718],[40720,40720],[40722,40723],[40727,40727],[40729,40729],[40736,40736],[40738,40738],[40745,40745],[40747,40748],[40751,40751],[40753,40753],[40759,40759],[40761,40761],[40763,40763],[40765,40766],[40769,40769],[40772,40772],[40775,40775],[40777,40777],[40784,40785],[40831,40844],[40857,40859],[40863,40864],[40866,40866],[40909,40911],[65072,65103],[65281,65470],[65474,65479],[65482,65487],[65490,65495],[65498,65500],[65504,65510],[65512,65518],[131428,131428],[132726,132726],[134352,134352],[136090,136090],[136211,136211],[144843,144843],[146583,146584],[146979,146979],[149979,149979],[150141,150141],[150217,150217],[152882,152882],[152930,152930],[153000,153000],[155351,155351],[156193,156193],[156813,156813],[157302,157302],[157564,157564],[158556,158556],[158753,158753],[163833,163833],[164872,164872],[165496,165496],[165525,165525],[165856,165856],[166729,166729],[166983,166983],[166991,166991],[166993,166993],[166996,166996],[167577,167577],[171902,171902],[171907,171907],[171916,171916],[174045,174045],[174331,174331],[174359,174359],[174640,174640],[174646,174646],[174680,174680],[176034,176034],[176423,176424],[176439,176440],[176621,176621],[176896,176896],[176995,176995],[177007,177007],[177010,177010],[177021,177021],[177156,177156],[177168,177168],[177171,177171],[177249,177249],[177383,177383],[177391,177391],[177398,177398],[177401,177401],[177421,177422],[177462,177462],[177582,177583],[177587,177587],[177639,177639],[177652,177652],[177692,177693],[177702,177704],[177706,177706],[177708,177708],[177813,177814],[177837,177837],[177901,177901],[178089,178089],[178117,178117],[178150,178150],[178169,178169],[178172,178172],[178182,178182],[178186,178186],[178204,178204],[178360,178360],[178887,178887],[179039,179039],[179042,179042],[179068,179068],[179075,179075],[179227,179227],[179575,179575],[179591,179591],[179703,179703],[179753,179753],[180265,180266],[180393,180393],[180426,180426],[180693,180693],[180697,180697],[180729,180729],[180860,180860],[180872,180872],[180900,180900],[181015,181015],[181083,181083],[181089,181089],[181092,181092],[181384,181384],[181396,181396],[181399,181399],[181570,181570],[181779,181779],[181784,181784],[181793,181793],[181801,181801],[181803,181805],[181807,181807],[181826,181826],[181834,181835],[182060,182060],[182063,182063],[182175,182175],[182209,182209],[182269,182269],[182489,182489],[182494,182494],[182497,182497],[182515,182515],[182535,182535],[182538,182538],[182557,182557],[182786,182786],[182798,182798],[182909,182909],[182953,182953],[183081,183081],[183085,183086],[183089,183089],[183096,183097],[183099,183099],[183103,183103],[183105,183105],[183114,183114],[183118,183118],[183130,183131],[183140,183140],[183145,183145],[183148,183148],[183151,183151],[183155,183155],[183158,183158],[183160,183160],[183164,183164],[183217,183217],[183231,183232],[183246,183246],[183382,183382],[183391,183391],[183541,183542],[183549,183549],[183551,183551],[183554,183555],[183562,183562],[183691,183691],[183693,183693],[183695,183696],[183711,183712],[183720,183720],[183725,183726],[183765,183765],[183832,183832],[183834,183834],[183843,183843],[183846,183846],[183850,183850],[183932,183932],[183944,183944],[183955,183955]]},"700":{"file":"FreeVideoSerifSC-Bold.woff2","sha256":"bd3071e6c48cb293f6b406975cf1eddcfa5990cf06f24e347a2f6d507ffe5157","ranges":[[32,126],[160,259],[272,275],[282,283],[296,299],[323,324],[327,328],[332,335],[338,339],[360,365],[462,462],[464,464],[466,466],[468,468],[470,470],[472,472],[474,474],[476,476],[711,711],[713,713],[913,929],[931,937],[945,961],[963,969],[1025,1025],[1040,1103],[1105,1105],[8194,8195],[8208,8214],[8216,8218],[8220,8222],[8224,8226],[8229,8231],[8240,8240],[8242,8243],[8245,8245],[8249,8252],[8258,8258],[8263,8265],[8273,8273],[8451,8451],[8470,8470],[8544,8555],[8592,8601],[8632,8633],[8644,8646],[8651,8652],[8656,8656],[8658,8658],[8660,8660],[8678,8681],[8693,8693],[8712,8712],[8715,8715],[8719,8719],[8721,8721],[8730,8730],[8733,8734],[8736,8736],[8741,8741],[8743,8747],[8750,8750],[8756,8759],[8765,8765],[8773,8773],[8776,8776],[8780,8780],[8800,8801],[8804,8805],[8814,8815],[8857,8857],[8869,8869],[8978,8978],[9312,9547],[9632,9643],[9649,9651],[9654,9655],[9660,9661],[9664,9665],[9670,9671],[9673,9676],[9678,9683],[9698,9702],[9711,9711],[9728,9731],[9733,9734],[9737,9737],[9742,9743],[9750,9751],[9756,9759],[9775,9775],[9792,9794],[9824,9839],[9842,9853],[9888,9888],[9917,9918],[12288,12351],[12353,12438],[12441,12543],[12549,12585],[12832,12841],[13383,13383],[13386,13386],[13678,13678],[13838,13838],[13901,13901],[13912,13912],[13926,13926],[14019,14019],[14042,14042],[14073,14073],[14275,14275],[14343,14343],[14355,14355],[14616,14616],[14660,14660],[14800,14801],[14815,14815],[15088,15088],[15114,15114],[15118,15118],[15130,15130],[15182,15182],[15189,15189],[15294,15294],[15360,15360],[15559,15559],[15576,15576],[15578,15578],[15636,15636],[15696,15696],[15794,15794],[15878,15878],[15884,15884],[16004,16004],[16108,16108],[16207,16207],[16352,16352],[16470,16470],[16558,16558],[16581,16581],[16590,16590],[16735,16735],[17209,17209],[17283,17283],[17302,17302],[17373,17373],[17377,17377],[17394,17394],[17411,17411],[17622,17622],[17627,17627],[17640,17640],[17643,17644],[17878,17878],[17883,17883],[17898,17898],[17908,17908],[18211,18211],[18265,18265],[18618,18618],[18620,18620],[18648,18648],[18813,18813],[18819,18819],[19615,19616],[19618,19618],[19731,19737],[19886,19886],[19968,19969],[19971,19971],[19975,19985],[19987,19990],[19992,19998],[20002,20002],[20004,20005],[20007,20008],[20010,20013],[20016,20016],[20018,20018],[20020,20020],[20022,20022],[20024,20027],[20029,20031],[20034,20035],[20037,20037],[20039,20041],[20043,20048],[20050,20052],[20054,20054],[20056,20057],[20060,20065],[20070,20070],[20073,20073],[20080,20081],[20083,20083],[20088,20088],[20094,20094],[20102,20102],[20104,20105],[20107,20111],[20113,20117],[20120,20120],[20122,20123],[20127,20130],[20132,20137],[20139,20142],[20146,20147],[20149,20150],[20152,20155],[20159,20167],[20169,20171],[20173,20174],[20177,20177],[20179,20185],[20189,20191],[20193,20193],[20195,20197],[20200,20200],[20202,20204],[20208,20208],[20210,20211],[20213,20215],[20219,20219],[20221,20221],[20223,20223],[20225,20225],[20232,20235],[20237,20241],[20247,20251],[20254,20256],[20258,20263],[20266,20267],[20269,20269],[20271,20272],[20274,20274],[20276,20276],[20278,20278],[20280,20280],[20282,20282],[20284,20286],[20289,20289],[20291,20291],[20294,20294],[20301,20305],[20307,20307],[20309,20320],[20323,20325],[20327,20327],[20329,20329],[20332,20332],[20335,20336],[20339,20340],[20342,20342],[20344,20344],[20346,20351],[20353,20356],[20360,20361],[20363,20363],[20365,20365],[20367,20367],[20369,20369],[20372,20372],[20375,20376],[20379,20379],[20381,20381],[20384,20384],[20387,20387],[20389,20394],[20396,20396],[20398,20399],[20404,20405],[20409,20409],[20415,20415],[20419,20421],[20426,20426],[20429,20433],[20439,20442],[20444,20447],[20449,20449],[20451,20451],[20454,20454],[20456,20459],[20461,20463],[20465,20465],[20467,20467],[20469,20470],[20472,20472],[20474,20474],[20478,20478],[20492,20493],[20495,20495],[20498,20501],[20504,20506],[20508,20508],[20510,20511],[20513,20513],[20517,20522],[20524,20526],[20532,20532],[20538,20540],[20542,20542],[20545,20545],[20547,20547],[20551,20552],[20556,20556],[20558,20559],[20563,20563],[20565,20565],[20570,20570],[20572,20572],[20577,20577],[20581,20581],[20588,20589],[20592,20592],[20594,20594],[20598,20599],[20603,20603],[20606,20608],[20611,20611],[20613,20613],[20616,20617],[20621,20621],[20626,20626],[20629,20629],[20643,20643],[20645,20645],[20647,20649],[20652,20652],[20658,20658],[20666,20667],[20679,20679],[20686,20687],[20692,20692],[20694,20694],[20698,20698],[20710,20711],[20716,20718],[20720,20720],[20723,20723],[20725,20725],[20731,20731],[20742,20743],[20747,20747],[20754,20754],[20769,20769],[20774,20774],[20787,20788],[20799,20801],[20803,20806],[20808,20809],[20811,20811],[20813,20813],[20817,20817],[20820,20822],[20826,20826],[20828,20828],[20834,20834],[20837,20837],[20840,20840],[20843,20846],[20848,20849],[20851,20857],[20859,20861],[20864,20866],[20869,20869],[20872,20873],[20876,20877],[20879,20879],[20882,20882],[20884,20887],[20889,20889],[20891,20892],[20896,20896],[20898,20898],[20900,20901],[20907,20908],[20910,20915],[20917,20919],[20923,20925],[20928,20928],[20932,20932],[20934,20935],[20937,20937],[20939,20940],[20943,20943],[20945,20945],[20947,20947],[20952,20952],[20955,20955],[20957,20957],[20960,20961],[20964,20964],[20971,20971],[20973,20973],[20975,20976],[20979,20979],[20981,20982],[20984,20989],[20991,20995],[20998,21000],[21002,21002],[21005,21006],[21009,21010],[21014,21019],[21021,21021],[21024,21024],[21028,21028],[21032,21033],[21035,21038],[21040,21040],[21043,21043],[21046,21051],[21053,21053],[21055,21059],[21061,21061],[21066,21069],[21072,21073],[21076,21078],[21084,21084],[21086,21087],[21089,21089],[21093,21093],[21095,21095],[21097,21098],[21103,21103],[21106,21106],[21117,21117],[21119,21119],[21121,21122],[21124,21124],[21128,21128],[21136,21136],[21139,21139],[21147,21147],[21149,21155],[21160,21165],[21169,21171],[21180,21180],[21182,21183],[21187,21187],[21191,21191],[21193,21193],[21195,21195],[21197,21197],[21200,21200],[21202,21202],[21204,21204],[21206,21206],[21208,21208],[21210,21210],[21215,21216],[21220,21220],[21232,21232],[21241,21242],[21246,21248],[21253,21254],[21256,21256],[21261,21261],[21263,21264],[21269,21271],[21273,21274],[21276,21277],[21280,21281],[21283,21283],[21286,21286],[21290,21290],[21294,21294],[21305,21308],[21310,21311],[21313,21313],[21315,21315],[21317,21317],[21319,21322],[21326,21327],[21329,21331],[21333,21335],[21338,21338],[21340,21340],[21342,21348],[21350,21351],[21353,21353],[21355,21356],[21358,21361],[21363,21365],[21367,21368],[21370,21370],[21375,21375],[21378,21378],[21380,21382],[21385,21385],[21387,21389],[21397,21398],[21400,21400],[21402,21402],[21405,21405],[21407,21407],[21410,21411],[21413,21414],[21416,21417],[21422,21422],[21430,21430],[21435,21435],[21438,21439],[21441,21442],[21446,21453],[21457,21457],[21460,21467],[21471,21472],[21475,21478],[21480,21491],[21493,21497],[21499,21501],[21505,21505],[21507,21508],[21510,21510],[21512,21514],[21516,21523],[21525,21527],[21531,21531],[21533,21537],[21539,21539],[21542,21545],[21547,21551],[21553,21554],[21556,21557],[21560,21561],[21563,21566],[21568,21568],[21571,21571],[21574,21576],[21578,21579],[21584,21584],[21586,21593],[21595,21596],[21602,21604],[21606,21606],[21608,21608],[21617,21619],[21621,21624],[21627,21629],[21632,21632],[21634,21634],[21636,21636],[21638,21639],[21641,21641],[21643,21648],[21650,21650],[21652,21654],[21657,21659],[21661,21661],[21665,21665],[21667,21677],[21679,21679],[21681,21681],[21683,21684],[21688,21688],[21690,21691],[21693,21693],[21695,21700],[21702,21705],[21708,21717],[21719,21719],[21721,21722],[21724,21727],[21730,21730],[21733,21738],[21741,21742],[21745,21747],[21754,21754],[21756,21757],[21759,21759],[21761,21761],[21766,21767],[21769,21769],[21775,21777],[21780,21780],[21787,21787],[21789,21789],[21792,21792],[21794,21796],[21799,21799],[21802,21802],[21804,21804],[21806,21809],[21811,21811],[21813,21813],[21815,21815],[21820,21820],[21822,21823],[21825,21825],[21827,21828],[21830,21830],[21833,21834],[21840,21840],[21845,21846],[21852,21852],[21857,21857],[21860,21863],[21866,21870],[21872,21872],[21876,21880],[21883,21884],[21886,21886],[21888,21892],[21894,21899],[21903,21903],[21905,21905],[21908,21908],[21912,21913],[21916,21917],[21919,21919],[21924,21924],[21927,21927],[21937,21937],[21939,21939],[21941,21941],[21943,21943],[21945,21945],[21947,21947],[21949,21950],[21956,21957],[21961,21961],[21964,21965],[21968,21972],[21974,21974],[21980,21983],[21985,21985],[21987,21990],[21992,21992],[21994,21996],[21999,21999],[22002,22003],[22005,22005],[22007,22007],[22013,22014],[22016,22017],[22024,22025],[22028,22028],[22030,22031],[22040,22040],[22042,22043],[22046,22047],[22049,22049],[22051,22052],[22055,22055],[22060,22061],[22065,22066],[22068,22068],[22070,22070],[22073,22073],[22075,22075],[22079,22080],[22082,22082],[22087,22087],[22092,22094],[22100,22100],[22103,22105],[22108,22108],[22114,22114],[22116,22116],[22120,22124],[22129,22129],[22134,22134],[22139,22140],[22148,22150],[22158,22159],[22163,22163],[22170,22170],[22179,22179],[22189,22189],[22191,22191],[22199,22199],[22204,22204],[22218,22218],[22228,22228],[22231,22231],[22234,22235],[22237,22242],[22244,22244],[22251,22251],[22253,22253],[22256,22257],[22260,22261],[22263,22263],[22265,22266],[22269,22271],[22275,22276],[22278,22278],[22280,22282],[22284,22284],[22288,22288],[22297,22297],[22300,22300],[22303,22303],[22306,22307],[22312,22320],[22322,22323],[22329,22331],[22334,22334],[22336,22336],[22338,22338],[22343,22343],[22345,22354],[22359,22359],[22362,22369],[22372,22374],[22376,22381],[22383,22384],[22387,22387],[22390,22391],[22395,22397],[22402,22406],[22408,22408],[22411,22415],[22418,22419],[22421,22421],[22425,22427],[22430,22436],[22438,22439],[22441,22441],[22443,22443],[22445,22447],[22449,22450],[22452,22453],[22456,22456],[22458,22458],[22462,22463],[22466,22467],[22470,22471],[22475,22476],[22478,22479],[22482,22482],[22484,22485],[22487,22490],[22493,22493],[22495,22496],[22500,22500],[22506,22507],[22509,22509],[22511,22511],[22516,22517],[22520,22522],[22524,22525],[22528,22528],[22530,22531],[22534,22535],[22537,22537],[22539,22542],[22544,22545],[22549,22549],[22553,22553],[22558,22558],[22560,22561],[22564,22564],[22567,22568],[22570,22570],[22576,22576],[22578,22578],[22581,22581],[22588,22590],[22596,22598],[22604,22605],[22609,22609],[22612,22612],[22616,22616],[22621,22622],[22629,22629],[22635,22636],[22641,22641],[22654,22654],[22656,22657],[22659,22659],[22661,22661],[22664,22665],[22672,22672],[22674,22675],[22677,22677],[22680,22682],[22686,22687],[22689,22689],[22691,22691],[22694,22694],[22696,22697],[22716,22716],[22721,22721],[22725,22725],[22737,22737],[22741,22741],[22756,22756],[22763,22764],[22766,22766],[22768,22768],[22771,22771],[22774,22774],[22776,22777],[22786,22786],[22788,22788],[22791,22791],[22797,22797],[22799,22800],[22804,22806],[22809,22810],[22812,22812],[22815,22815],[22820,22821],[22823,22823],[22825,22831],[22833,22833],[22836,22836],[22839,22842],[22844,22844],[22849,22850],[22852,22852],[22855,22857],[22859,22859],[22862,22863],[22865,22865],[22867,22872],[22874,22874],[22880,22882],[22885,22885],[22893,22893],[22899,22900],[22902,22902],[22904,22905],[22909,22909],[22913,22916],[22918,22920],[22922,22922],[22925,22925],[22930,22931],[22934,22937],[22942,22942],[22947,22949],[22951,22955],[22957,22959],[22962,22962],[22969,22969],[22971,22971],[22974,22974],[22982,22982],[22984,22984],[22986,22987],[22992,22996],[22999,23000],[23002,23002],[23004,23006],[23011,23013],[23016,23016],[23020,23020],[23022,23022],[23025,23025],[23030,23030],[23033,23033],[23035,23035],[23037,23037],[23039,23041],[23043,23049],[23052,23052],[23057,23057],[23059,23059],[23064,23064],[23068,23068],[23071,23072],[23075,23075],[23077,23077],[23081,23081],[23089,23090],[23092,23094],[23100,23100],[23104,23104],[23110,23110],[23113,23114],[23116,23117],[23125,23125],[23128,23128],[23130,23130],[23134,23134],[23136,23136],[23138,23138],[23140,23140],[23143,23143],[23146,23147],[23155,23159],[23162,23164],[23167,23167],[23170,23170],[23172,23172],[23174,23174],[23186,23187],[23190,23190],[23194,23195],[23198,23198],[23210,23210],[23213,23213],[23217,23219],[23221,23221],[23224,23224],[23230,23230],[23233,23234],[23236,23236],[23241,23241],[23244,23244],[23250,23250],[23252,23254],[23256,23256],[23258,23258],[23260,23260],[23264,23265],[23267,23267],[23270,23270],[23273,23275],[23277,23277],[23281,23281],[23293,23293],[23305,23305],[23318,23319],[23323,23323],[23333,23333],[23340,23340],[23346,23346],[23348,23348],[23351,23351],[23359,23360],[23365,23365],[23376,23377],[23379,23389],[23391,23391],[23394,23398],[23401,23402],[23404,23404],[23408,23409],[23411,23411],[23413,23413],[23418,23418],[23421,23421],[23424,23425],[23427,23429],[23431,23433],[23435,23436],[23439,23439],[23443,23443],[23445,23445],[23447,23454],[23456,23463],[23466,23468],[23472,23472],[23475,23478],[23480,23481],[23485,23487],[23489,23490],[23492,23495],[23500,23500],[23504,23504],[23506,23507],[23517,23519],[23521,23521],[23524,23525],[23528,23528],[23534,23534],[23536,23536],[23544,23548],[23551,23551],[23553,23553],[23556,23556],[23558,23558],[23561,23562],[23567,23567],[23569,23569],[23572,23574],[23576,23576],[23578,23578],[23580,23581],[23586,23586],[23588,23589],[23591,23592],[23594,23594],[23596,23596],[23601,23601],[23604,23604],[23608,23619],[23621,23621],[23624,23627],[23630,23633],[23637,23637],[23641,23641],[23646,23646],[23648,23649],[23651,23651],[23653,23654],[23662,23663],[23665,23665],[23673,23674],[23676,23676],[23678,23679],[23681,23682],[23688,23688],[23690,23690],[23692,23693],[23696,23697],[23700,23700],[23702,23708],[23710,23710],[23712,23712],[23714,23715],[23720,23721],[23723,23725],[23729,23729],[23731,23731],[23733,23733],[23735,23736],[23741,23741],[23743,23743],[23745,23748],[23755,23755],[23762,23762],[23767,23769],[23771,23771],[23777,23777],[23779,23784],[23786,23786],[23789,23789],[23792,23793],[23803,23803],[23807,23812],[23814,23815],[23820,23820],[23822,23822],[23826,23826],[23828,23828],[23830,23830],[23834,23835],[23838,23839],[23841,23841],[23844,23844],[23846,23847],[23849,23849],[23853,23854],[23860,23860],[23862,23862],[23869,23871],[23873,23873],[23877,23877],[23879,23879],[23882,23884],[23886,23886],[23894,23894],[23896,23896],[23898,23899],[23901,23901],[23913,23913],[23915,23916],[23919,23919],[23922,23922],[23924,23924],[23938,23938],[23941,23941],[23949,23949],[23954,23955],[23961,23961],[23965,23965],[23967,23967],[23974,23974],[23986,23986],[23991,23991],[24005,24005],[24007,24007],[24009,24009],[24013,24013],[24027,24027],[24029,24030],[24033,24034],[24037,24041],[24043,24043],[24046,24047],[24049,24052],[24055,24055],[24061,24062],[24065,24067],[24069,24070],[24072,24072],[24076,24076],[24079,24081],[24084,24086],[24088,24093],[24097,24097],[24102,24104],[24109,24110],[24113,24113],[24119,24120],[24123,24125],[24130,24130],[24132,24133],[24140,24140],[24148,24150],[24155,24155],[24158,24158],[24161,24162],[24170,24170],[24178,24180],[24182,24182],[24184,24184],[24186,24189],[24191,24192],[24196,24196],[24198,24199],[24202,24203],[24207,24209],[24211,24215],[24217,24218],[24220,24220],[24222,24224],[24228,24231],[24237,24237],[24241,24241],[24243,24243],[24245,24249],[24252,24252],[24254,24254],[24262,24262],[24265,24267],[24273,24275],[24278,24278],[24281,24281],[24283,24283],[24296,24296],[24298,24298],[24308,24308],[24310,24311],[24314,24314],[24318,24324],[24326,24328],[24330,24331],[24335,24335],[24337,24337],[24339,24339],[24341,24341],[24343,24344],[24347,24347],[24351,24352],[24354,24354],[24357,24362],[24365,24365],[24367,24367],[24369,24369],[24374,24374],[24376,24378],[24380,24380],[24384,24384],[24400,24400],[24402,24403],[24405,24408],[24413,24413],[24415,24415],[24417,24418],[24420,24420],[24422,24423],[24425,24426],[24428,24429],[24432,24433],[24435,24435],[24439,24439],[24441,24441],[24443,24444],[24448,24450],[24452,24453],[24455,24460],[24464,24464],[24466,24466],[24469,24469],[24471,24473],[24475,24476],[24481,24481],[24488,24488],[24490,24490],[24493,24494],[24501,24501],[24503,24503],[24508,24509],[24515,24518],[24521,24521],[24524,24525],[24527,24530],[24534,24537],[24541,24542],[24544,24545],[24548,24548],[24551,24551],[24554,24555],[24557,24558],[24561,24561],[24563,24563],[24565,24565],[24568,24568],[24570,24571],[24573,24582],[24586,24586],[24589,24591],[24594,24594],[24596,24598],[24601,24601],[24603,24605],[24608,24609],[24613,24619],[24623,24623],[24629,24629],[24635,24636],[24639,24639],[24641,24643],[24651,24651],[24653,24653],[24656,24656],[24658,24661],[24665,24666],[24669,24669],[24674,24676],[24679,24685],[24687,24688],[24691,24691],[24694,24694],[24696,24701],[24703,24703],[24707,24708],[24710,24710],[24712,24713],[24716,24717],[24722,24722],[24724,24724],[24726,24726],[24730,24731],[24733,24733],[24735,24736],[24738,24739],[24742,24742],[24744,24744],[24747,24749],[24751,24754],[24756,24756],[24760,24760],[24763,24764],[24773,24775],[24778,24779],[24782,24782],[24785,24785],[24788,24789],[24792,24797],[24799,24800],[24806,24809],[24811,24816],[24819,24820],[24822,24822],[24825,24826],[24832,24833],[24835,24835],[24838,24838],[24840,24841],[24845,24848],[24852,24853],[24858,24858],[24863,24864],[24867,24868],[24870,24871],[24875,24875],[24877,24877],[24895,24895],[24902,24902],[24904,24904],[24906,24906],[24908,24908],[24910,24910],[24913,24913],[24917,24917],[24925,24925],[24930,24930],[24933,24933],[24935,24936],[24940,24941],[24944,24944],[24949,24949],[24951,24951],[24971,24971],[24974,24974],[24980,24981],[24985,24985],[24989,24989],[24999,25001],[25004,25005],[25015,25015],[25018,25018],[25022,25022],[25026,25026],[25032,25032],[25034,25035],[25041,25042],[25044,25044],[25062,25062],[25077,25077],[25087,25087],[25094,25094],[25096,25096],[25098,25106],[25109,25112],[25114,25115],[25119,25119],[25121,25125],[25130,25130],[25132,25134],[25139,25140],[25143,25143],[25149,25155],[25157,25166],[25169,25172],[25176,25176],[25179,25179],[25182,25182],[25187,25187],[25190,25191],[25193,25200],[25203,25203],[25206,25206],[25209,25210],[25212,25216],[25219,25220],[25225,25226],[25233,25240],[25242,25243],[25247,25250],[25252,25253],[25256,25256],[25259,25260],[25265,25265],[25269,25269],[25273,25273],[25275,25277],[25279,25279],[25282,25290],[25292,25294],[25296,25296],[25298,25300],[25302,25308],[25311,25311],[25314,25321],[25324,25327],[25329,25329],[25331,25332],[25334,25335],[25340,25343],[25345,25346],[25351,25353],[25358,25358],[25361,25361],[25363,25363],[25366,25366],[25370,25371],[25373,25382],[25384,25384],[25386,25387],[25391,25391],[25394,25394],[25401,25402],[25405,25405],[25410,25411],[25413,25414],[25417,25417],[25419,25424],[25429,25429],[25438,25439],[25441,25443],[25447,25447],[25449,25449],[25453,25455],[25457,25457],[25462,25463],[25466,25467],[25469,25469],[25472,25472],[25474,25474],[25479,25482],[25484,25484],[25486,25488],[25490,25490],[25494,25494],[25496,25496],[25502,25502],[25504,25504],[25506,25507],[25509,25509],[25511,25514],[25516,25518],[25520,25520],[25523,25524],[25527,25528],[25530,25530],[25532,25532],[25534,25534],[25540,25540],[25542,25542],[25545,25545],[25549,25552],[25554,25554],[25557,25558],[25566,25566],[25568,25569],[25571,25571],[25577,25578],[25581,25581],[25586,25588],[25590,25590],[25592,25592],[25597,25597],[25599,25602],[25605,25605],[25611,25612],[25615,25616],[25618,25620],[25627,25628],[25630,25630],[25632,25633],[25638,25638],[25642,25642],[25644,25645],[25652,25652],[25658,25658],[25661,25661],[25663,25663],[25665,25665],[25668,25672],[25674,25674],[25679,25679],[25682,25682],[25684,25684],[25688,25688],[25691,25691],[25694,25694],[25703,25703],[25705,25705],[25709,25709],[25716,25716],[25720,25722],[25725,25725],[25730,25730],[25732,25733],[25735,25735],[25745,25746],[25749,25750],[25753,25753],[25758,25758],[25764,25764],[25769,25769],[25772,25774],[25776,25776],[25781,25781],[25783,25784],[25786,25786],[25788,25788],[25792,25792],[25794,25794],[25797,25797],[25805,25806],[25808,25808],[25810,25810],[25815,25816],[25822,25822],[25826,25826],[25828,25828],[25830,25830],[25855,25856],[25865,25865],[25874,25874],[25880,25880],[25893,25893],[25899,25899],[25902,25903],[25908,25910],[25912,25913],[25915,25915],[25917,25919],[25925,25925],[25928,25929],[25932,25932],[25935,25935],[25937,25937],[25940,25942],[25945,25945],[25947,25947],[25949,25950],[25954,25955],[25958,25958],[25961,25961],[25963,25964],[25968,25968],[25970,25970],[25972,25972],[25975,25975],[25991,25991],[25995,25996],[26000,26001],[26003,26003],[26007,26007],[26009,26009],[26011,26013],[26015,26017],[26020,26021],[26023,26023],[26025,26025],[26027,26027],[26029,26029],[26031,26032],[26038,26038],[26041,26041],[26044,26045],[26049,26049],[26051,26054],[26059,26060],[26062,26064],[26066,26066],[26070,26071],[26078,26078],[26080,26080],[26082,26082],[26085,26089],[26092,26097],[26100,26104],[26106,26107],[26111,26112],[26114,26116],[26118,26122],[26124,26124],[26126,26127],[26130,26133],[26137,26137],[26141,26141],[26143,26145],[26147,26149],[26151,26152],[26154,26155],[26157,26157],[26159,26159],[26161,26161],[26163,26166],[26170,26170],[26172,26174],[26177,26177],[26179,26179],[26181,26181],[26186,26188],[26191,26192],[26194,26199],[26201,26202],[26206,26207],[26209,26210],[26212,26212],[26214,26214],[26216,26216],[26218,26219],[26222,26225],[26228,26228],[26230,26231],[26234,26234],[26238,26238],[26242,26242],[26244,26245],[26247,26247],[26252,26252],[26257,26257],[26261,26263],[26269,26269],[26279,26280],[26286,26286],[26290,26290],[26292,26294],[26297,26297],[26302,26303],[26312,26312],[26316,26316],[26329,26329],[26331,26333],[26342,26342],[26345,26345],[26352,26352],[26354,26356],[26359,26359],[26361,26361],[26364,26364],[26366,26368],[26376,26379],[26381,26381],[26383,26384],[26387,26389],[26391,26391],[26395,26395],[26397,26397],[26399,26399],[26406,26406],[26408,26408],[26410,26413],[26415,26415],[26417,26417],[26419,26421],[26424,26424],[26426,26426],[26429,26429],[26432,26432],[26434,26436],[26438,26438],[26440,26441],[26444,26444],[26446,26449],[26451,26451],[26453,26454],[26457,26457],[26460,26460],[26462,26465],[26469,26469],[26471,26474],[26477,26477],[26479,26480],[26482,26483],[26485,26485],[26487,26487],[26491,26492],[26494,26495],[26497,26497],[26500,26501],[26503,26503],[26505,26505],[26507,26507],[26509,26509],[26512,26512],[26517,26517],[26519,26520],[26522,26522],[26524,26526],[26530,26531],[26533,26533],[26535,26536],[26538,26539],[26541,26541],[26543,26544],[26546,26547],[26549,26553],[26561,26561],[26563,26564],[26568,26568],[26570,26570],[26575,26580],[26582,26582],[26584,26586],[26588,26590],[26592,26592],[26594,26594],[26597,26597],[26601,26601],[26604,26604],[26607,26609],[26611,26612],[26615,26615],[26621,26621],[26623,26624],[26629,26629],[26631,26636],[26638,26643],[26646,26647],[26653,26653],[26655,26655],[26657,26657],[26665,26666],[26674,26676],[26679,26681],[26683,26686],[26688,26694],[26696,26698],[26700,26700],[26702,26702],[26704,26705],[26707,26709],[26720,26729],[26731,26731],[26735,26735],[26738,26738],[26740,26740],[26742,26743],[26745,26745],[26753,26753],[26755,26755],[26757,26758],[26764,26764],[26767,26767],[26771,26771],[26775,26775],[26784,26784],[26786,26787],[26790,26792],[26797,26797],[26799,26800],[26803,26805],[26812,26818],[26825,26825],[26827,26827],[26829,26829],[26832,26832],[26834,26835],[26837,26837],[26840,26840],[26842,26842],[26848,26848],[26851,26852],[26856,26856],[26858,26860],[26862,26862],[26864,26865],[26869,26869],[26873,26877],[26880,26881],[26885,26886],[26891,26891],[26893,26894],[26896,26899],[26911,26912],[26916,26916],[26922,26922],[26925,26925],[26928,26928],[26932,26932],[26936,26937],[26941,26941],[26943,26943],[26946,26946],[26962,26962],[26964,26964],[26967,26967],[26969,26970],[26973,26974],[26976,26976],[26979,26979],[26982,26982],[26985,26987],[26990,26991],[26993,26993],[26999,27001],[27004,27004],[27008,27008],[27010,27017],[27021,27021],[27025,27025],[27028,27030],[27032,27032],[27035,27036],[27047,27048],[27051,27051],[27053,27053],[27056,27057],[27060,27060],[27063,27063],[27067,27067],[27073,27073],[27075,27075],[27082,27082],[27084,27084],[27086,27086],[27088,27088],[27092,27092],[27098,27100],[27103,27104],[27117,27117],[27121,27122],[27133,27133],[27135,27135],[27146,27146],[27159,27160],[27167,27167],[27169,27169],[27176,27176],[27178,27178],[27183,27183],[27185,27185],[27189,27189],[27197,27198],[27204,27204],[27207,27207],[27216,27217],[27224,27225],[27227,27227],[27230,27230],[27233,27233],[27237,27238],[27249,27249],[27257,27257],[27260,27260],[27264,27264],[27268,27268],[27278,27278],[27280,27281],[27287,27287],[27294,27294],[27296,27296],[27305,27305],[27307,27308],[27334,27334],[27394,27394],[27424,27428],[27431,27431],[27442,27442],[27447,27451],[27454,27454],[27459,27459],[27461,27463],[27465,27465],[27468,27468],[27481,27481],[27490,27495],[27498,27498],[27513,27513],[27515,27516],[27521,27524],[27526,27527],[27529,27531],[27533,27533],[27538,27539],[27542,27542],[27546,27547],[27553,27553],[27555,27555],[27562,27562],[27571,27573],[27575,27575],[27583,27583],[27585,27586],[27589,27589],[27595,27597],[27599,27600],[27602,27607],[27609,27609],[27611,27611],[27617,27617],[27626,27627],[27631,27631],[27635,27635],[27637,27637],[27641,27641],[27645,27645],[27653,27655],[27661,27661],[27663,27665],[27667,27670],[27672,27675],[27679,27679],[27681,27682],[27684,27684],[27686,27690],[27694,27696],[27698,27698],[27700,27701],[27704,27704],[27709,27714],[27718,27723],[27728,27728],[27732,27733],[27735,27735],[27739,27745],[27748,27748],[27751,27755],[27757,27757],[27760,27760],[27762,27762],[27764,27764],[27766,27766],[27769,27769],[27773,27774],[27777,27785],[27788,27788],[27791,27792],[27795,27796],[27800,27803],[27807,27807],[27809,27809],[27811,27819],[27821,27822],[27825,27827],[27832,27839],[27842,27845],[27847,27847],[27849,27850],[27852,27852],[27856,27856],[27859,27863],[27865,27868],[27870,27870],[27872,27875],[27877,27877],[27880,27880],[27882,27883],[27886,27889],[27891,27891],[27893,27896],[27898,27902],[27905,27905],[27908,27908],[27911,27912],[27915,27916],[27918,27918],[27921,27923],[27927,27931],[27934,27934],[27938,27939],[27941,27941],[27943,27944],[27946,27947],[27949,27950],[27953,27957],[27960,27967],[27969,27969],[27971,27971],[27973,27979],[27981,27989],[27993,27996],[27998,28001],[28003,28003],[28005,28006],[28009,28010],[28012,28016],[28018,28018],[28020,28020],[28023,28024],[28028,28028],[28034,28034],[28036,28037],[28040,28041],[28044,28046],[28048,28049],[28051,28053],[28056,28056],[28059,28059],[28061,28068],[28070,28075],[28078,28079],[28082,28082],[28084,28085],[28088,28088],[28095,28096],[28100,28103],[28107,28108],[28111,28111],[28113,28113],[28118,28118],[28120,28121],[28124,28129],[28132,28132],[28134,28134],[28139,28140],[28142,28143],[28145,28145],[28147,28148],[28151,28151],[28153,28153],[28155,28156],[28165,28165],[28170,28170],[28172,28174],[28176,28177],[28180,28180],[28182,28183],[28186,28186],[28189,28189],[28191,28193],[28195,28197],[28201,28201],[28203,28203],[28205,28205],[28207,28208],[28210,28210],[28212,28212],[28216,28216],[28218,28218],[28220,28220],[28227,28228],[28233,28233],[28237,28238],[28241,28241],[28243,28244],[28246,28246],[28248,28248],[28251,28253],[28255,28255],[28259,28259],[28267,28267],[28270,28270],[28274,28274],[28276,28276],[28286,28287],[28289,28289],[28291,28291],[28293,28295],[28297,28297],[28301,28301],[28303,28304],[28312,28312],[28314,28314],[28316,28316],[28318,28320],[28322,28322],[28325,28327],[28330,28330],[28335,28335],[28337,28338],[28340,28343],[28345,28347],[28349,28349],[28353,28355],[28358,28359],[28361,28361],[28363,28363],[28365,28365],[28367,28367],[28369,28369],[28371,28373],[28375,28376],[28378,28378],[28382,28386],[28388,28395],[28404,28404],[28409,28409],[28418,28418],[28422,28422],[28424,28425],[28427,28427],[28431,28431],[28435,28438],[28448,28448],[28452,28452],[28454,28454],[28457,28459],[28461,28461],[28463,28463],[28465,28465],[28467,28468],[28470,28471],[28473,28473],[28475,28476],[28478,28478],[28486,28487],[28491,28491],[28493,28493],[28495,28495],[28502,28502],[28504,28504],[28508,28508],[28510,28511],[28514,28514],[28518,28518],[28521,28521],[28525,28526],[28530,28530],[28532,28533],[28536,28536],[28538,28538],[28540,28542],[28546,28546],[28548,28548],[28552,28553],[28556,28558],[28571,28572],[28577,28577],[28581,28581],[28583,28583],[28586,28586],[28589,28589],[28595,28596],[28598,28598],[28601,28601],[28604,28605],[28608,28608],[28610,28610],[28617,28617],[28619,28619],[28625,28626],[28638,28638],[28640,28641],[28649,28649],[28654,28655],[28684,28685],[28689,28689],[28692,28692],[28698,28699],[28707,28707],[28721,28721],[28725,28725],[28729,28729],[28732,28732],[28744,28744],[28748,28748],[28751,28751],[28766,28766],[28779,28781],[28783,28784],[28789,28790],[28792,28792],[28796,28796],[28798,28800],[28805,28806],[28809,28810],[28812,28812],[28814,28814],[28818,28818],[28820,28822],[28824,28825],[28828,28829],[28831,28831],[28835,28835],[28843,28847],[28849,28849],[28851,28851],[28855,28857],[28859,28861],[28864,28867],[28872,28872],[28874,28874],[28884,28884],[28888,28889],[28891,28893],[28895,28896],[28900,28900],[28902,28905],[28907,28909],[28911,28911],[28918,28919],[28921,28923],[28925,28925],[28934,28934],[28937,28938],[28940,28940],[28944,28944],[28947,28947],[28949,28954],[28956,28956],[28958,28958],[28966,28966],[28975,28977],[28982,28982],[28993,28993],[28995,28995],[28997,28997],[29002,29004],[29006,29006],[29011,29011],[29020,29020],[29022,29023],[29028,29028],[29030,29032],[29038,29038],[29042,29044],[29048,29048],[29050,29050],[29053,29053],[29060,29060],[29063,29063],[29066,29066],[29071,29071],[29076,29076],[29080,29081],[29083,29084],[29087,29088],[29093,29093],[29096,29096],[29100,29100],[29107,29107],[29109,29109],[29113,29113],[29115,29115],[29123,29123],[29130,29131],[29134,29135],[29140,29141],[29146,29146],[29152,29152],[29157,29157],[29159,29159],[29166,29166],[29177,29177],[29190,29191],[29204,29204],[29210,29210],[29213,29213],[29215,29215],[29224,29224],[29226,29226],[29228,29228],[29232,29233],[29237,29241],[29243,29243],[29245,29245],[29247,29247],[29249,29250],[29255,29256],[29260,29261],[29266,29266],[29270,29270],[29273,29275],[29277,29277],[29279,29279],[29281,29282],[29284,29287],[29289,29289],[29294,29295],[29298,29298],[29301,29301],[29305,29307],[29310,29313],[29316,29316],[29319,29319],[29322,29323],[29325,29325],[29327,29327],[29330,29330],[29343,29343],[29352,29352],[29356,29357],[29359,29360],[29364,29364],[29366,29369],[29377,29380],[29384,29385],[29389,29390],[29392,29392],[29394,29394],[29399,29399],[29401,29401],[29405,29406],[29408,29409],[29416,29417],[29420,29428],[29431,29432],[29434,29436],[29441,29441],[29443,29444],[29447,29447],[29450,29450],[29454,29454],[29459,29459],[29461,29463],[29467,29470],[29473,29474],[29477,29477],[29481,29484],[29486,29489],[29492,29492],[29495,29498],[29502,29503],[29517,29517],[29520,29520],[29522,29522],[29527,29527],[29536,29536],[29548,29549],[29551,29551],[29556,29556],[29566,29566],[29571,29572],[29575,29575],[29577,29577],[29579,29579],[29582,29582],[29585,29587],[29589,29590],[29592,29595],[29598,29602],[29604,29606],[29609,29609],[29611,29611],[29613,29619],[29622,29623],[29625,29628],[29631,29632],[29634,29634],[29637,29637],[29639,29645],[29647,29650],[29653,29654],[29657,29657],[29659,29659],[29661,29662],[29664,29664],[29666,29667],[29669,29671],[29673,29675],[29677,29677],[29680,29680],[29682,29682],[29685,29685],[29687,29690],[29693,29693],[29696,29696],[29699,29706],[29710,29712],[29716,29716],[29722,29723],[29727,29727],[29729,29730],[29732,29734],[29736,29736],[29738,29744],[29746,29750],[29756,29756],[29760,29766],[29777,29777],[29779,29783],[29785,29791],[29794,29794],[29799,29800],[29804,29805],[29808,29809],[29811,29811],[29814,29815],[29822,29822],[29824,29825],[29827,29827],[29830,29832],[29835,29835],[29838,29838],[29840,29840],[29842,29842],[29848,29848],[29852,29852],[29854,29856],[29861,29861],[29863,29866],[29868,29868],[29870,29870],[29873,29874],[29882,29882],[29888,29888],[29906,29906],[29910,29910],[29912,29912],[29916,29916],[29918,29918],[29920,29920],[29922,29924],[29926,29926],[29934,29935],[29940,29940],[29942,29943],[29947,29947],[29951,29951],[29956,29956],[29965,29965],[29967,29967],[29969,29969],[29971,29971],[29975,29978],[29980,29980],[29983,29983],[29985,29985],[29989,29990],[29992,29997],[29999,30003],[30005,30005],[30007,30008],[30010,30011],[30014,30014],[30016,30016],[30021,30021],[30024,30024],[30027,30028],[30030,30031],[30036,30036],[30038,30038],[30041,30044],[30052,30054],[30058,30058],[30060,30060],[30063,30063],[30066,30066],[30068,30068],[30072,30073],[30079,30079],[30081,30081],[30083,30083],[30086,30086],[30091,30091],[30093,30093],[30095,30098],[30100,30100],[30102,30103],[30105,30106],[30109,30109],[30111,30117],[30123,30133],[30136,30137],[30140,30142],[30146,30149],[30151,30154],[30157,30157],[30162,30166],[30168,30168],[30171,30171],[30174,30174],[30178,30180],[30182,30184],[30186,30187],[30192,30193],[30196,30196],[30201,30201],[30204,30204],[30207,30209],[30211,30211],[30213,30214],[30218,30218],[30220,30220],[30224,30224],[30229,30229],[30231,30233],[30235,30235],[30239,30240],[30242,30242],[30244,30246],[30249,30251],[30253,30253],[30256,30256],[30259,30261],[30264,30264],[30268,30268],[30270,30272],[30275,30275],[30284,30285],[30292,30292],[30294,30295],[30300,30300],[30302,30302],[30307,30307],[30315,30315],[30319,30319],[30328,30328],[30331,30331],[30333,30335],[30338,30338],[30340,30340],[30342,30344],[30347,30347],[30350,30350],[30353,30353],[30355,30355],[30357,30358],[30361,30361],[30363,30363],[30366,30366],[30372,30372],[30374,30374],[30381,30382],[30385,30386],[30388,30388],[30399,30399],[30402,30402],[30405,30406],[30408,30410],[30413,30418],[30420,30420],[30422,30424],[30427,30427],[30431,30431],[30437,30438],[30446,30447],[30449,30450],[30452,30452],[30455,30457],[30460,30460],[30462,30462],[30465,30465],[30468,30468],[30471,30475],[30477,30477],[30489,30490],[30495,30496],[30498,30498],[30502,30502],[30504,30505],[30508,30509],[30511,30511],[30517,30520],[30522,30522],[30524,30524],[30528,30529],[30531,30532],[30535,30535],[30542,30542],[30544,30545],[30554,30555],[30561,30563],[30565,30566],[30568,30568],[30571,30572],[30585,30585],[30589,30592],[30596,30597],[30603,30606],[30609,30610],[30623,30624],[30626,30626],[30629,30629],[30631,30631],[30633,30637],[30640,30640],[30643,30643],[30645,30645],[30651,30651],[30653,30653],[30655,30655],[30669,30669],[30679,30679],[30683,30684],[30686,30686],[30690,30691],[30693,30693],[30695,30695],[30697,30697],[30699,30702],[30704,30704],[30707,30707],[30710,30710],[30712,30712],[30715,30722],[30724,30724],[30726,30726],[30729,30729],[30732,30733],[30737,30738],[30740,30740],[30742,30744],[30746,30746],[30748,30749],[30751,30752],[30755,30755],[30757,30759],[30761,30761],[30763,30766],[30768,30768],[30772,30773],[30775,30780],[30782,30782],[30784,30785],[30789,30789],[30791,30791],[30794,30794],[30796,30798],[30800,30800],[30802,30802],[30804,30807],[30809,30810],[30813,30813],[30826,30830],[30839,30839],[30844,30844],[30847,30847],[30851,30851],[30855,30857],[30860,30863],[30865,30865],[30867,30867],[30871,30872],[30874,30876],[30879,30879],[30881,30881],[30883,30883],[30885,30885],[30887,30888],[30896,30900],[30902,30902],[30905,30905],[30910,30910],[30913,30913],[30917,30917],[30921,30923],[30927,30928],[30932,30933],[30937,30937],[30940,30940],[30945,30945],[30952,30952],[30956,30956],[30962,30962],[30964,30964],[30967,30967],[30969,30971],[30977,30977],[30981,30981],[30988,30988],[30995,30995],[31006,31006],[31012,31012],[31028,31029],[31034,31036],[31038,31038],[31040,31041],[31043,31043],[31046,31051],[31054,31056],[31059,31059],[31061,31063],[31066,31072],[31074,31074],[31077,31077],[31079,31080],[31085,31085],[31087,31087],[31090,31090],[31095,31096],[31098,31098],[31100,31100],[31102,31102],[31104,31105],[31108,31109],[31114,31115],[31119,31119],[31122,31122],[31124,31124],[31128,31128],[31130,31131],[31140,31140],[31143,31143],[31155,31155],[31161,31163],[31165,31166],[31168,31169],[31171,31171],[31174,31174],[31177,31177],[31179,31179],[31181,31181],[31185,31186],[31189,31189],[31192,31192],[31199,31199],[31203,31204],[31206,31207],[31209,31209],[31211,31213],[31215,31216],[31224,31224],[31227,31227],[31229,31230],[31232,31232],[31234,31235],[31238,31238],[31243,31246],[31249,31249],[31252,31252],[31255,31255],[31257,31258],[31262,31262],[31264,31264],[31267,31267],[31283,31283],[31287,31287],[31289,31289],[31291,31293],[31295,31295],[31300,31300],[31302,31302],[31313,31313],[31319,31319],[31321,31321],[31324,31324],[31327,31327],[31344,31344],[31348,31348],[31350,31354],[31359,31361],[31363,31366],[31368,31368],[31370,31370],[31373,31374],[31377,31378],[31381,31384],[31388,31389],[31391,31392],[31395,31395],[31397,31398],[31400,31400],[31404,31405],[31411,31411],[31416,31416],[31423,31423],[31435,31435],[31441,31441],[31446,31446],[31448,31449],[31454,31456],[31459,31459],[31461,31462],[31467,31467],[31469,31469],[31471,31471],[31481,31482],[31485,31485],[31487,31487],[31491,31492],[31494,31494],[31496,31496],[31498,31499],[31503,31503],[31505,31505],[31508,31509],[31513,31513],[31515,31515],[31518,31518],[31520,31520],[31524,31526],[31528,31528],[31530,31532],[31534,31535],[31537,31537],[31539,31539],[31544,31544],[31546,31546],[31548,31548],[31550,31550],[31552,31552],[31557,31557],[31559,31559],[31561,31561],[31563,31564],[31567,31570],[31572,31572],[31574,31574],[31576,31576],[31578,31581],[31584,31584],[31586,31586],[31588,31590],[31598,31598],[31601,31602],[31605,31607],[31609,31609],[31611,31612],[31614,31614],[31616,31616],[31621,31621],[31629,31629],[31632,31632],[31635,31639],[31644,31645],[31649,31650],[31654,31661],[31665,31665],[31668,31668],[31672,31672],[31681,31681],[31686,31687],[31692,31692],[31697,31697],[31699,31699],[31705,31706],[31709,31709],[31713,31713],[31717,31718],[31722,31722],[31726,31727],[31729,31729],[31735,31735],[31740,31740],[31742,31742],[31747,31747],[31751,31751],[31753,31753],[31755,31756],[31759,31759],[31765,31766],[31773,31773],[31775,31776],[31782,31783],[31786,31786],[31792,31792],[31800,31800],[31807,31809],[31821,31821],[31845,31845],[31859,31860],[31867,31869],[31881,31881],[31889,31890],[31893,31893],[31895,31896],[31900,31903],[31906,31906],[31908,31909],[31914,31914],[31918,31918],[31921,31923],[31929,31929],[31932,31935],[31937,31937],[31941,31941],[31943,31944],[31946,31946],[31948,31949],[31954,31954],[31957,31959],[31961,31961],[31964,31964],[31967,31968],[31976,31976],[31983,31983],[31989,31989],[31992,31992],[31995,31995],[32010,32010],[32032,32032],[32034,32034],[32039,32039],[32043,32043],[32047,32047],[32092,32092],[32110,32110],[32119,32119],[32166,32166],[32174,32174],[32288,32288],[32290,32290],[32315,32315],[32321,32321],[32324,32324],[32327,32327],[32386,32386],[32411,32411],[32415,32491],[32493,32566],[32568,32568],[32570,32570],[32578,32578],[32580,32581],[32589,32589],[32592,32593],[32596,32597],[32599,32600],[32602,32602],[32607,32607],[32609,32610],[32616,32618],[32622,32622],[32625,32626],[32628,32628],[32630,32630],[32633,32633],[32637,32638],[32641,32641],[32650,32650],[32652,32652],[32654,32654],[32657,32657],[32659,32662],[32666,32666],[32669,32671],[32673,32673],[32676,32676],[32679,32679],[32687,32690],[32696,32697],[32700,32701],[32703,32707],[32709,32709],[32712,32712],[32714,32714],[32716,32716],[32718,32718],[32724,32725],[32728,32731],[32735,32737],[32741,32742],[32745,32745],[32750,32753],[32755,32755],[32759,32759],[32763,32764],[32766,32766],[32768,32769],[32771,32775],[32779,32781],[32783,32786],[32788,32793],[32796,32796],[32800,32800],[32802,32802],[32804,32810],[32816,32817],[32819,32819],[32821,32824],[32827,32827],[32829,32829],[32831,32831],[32834,32835],[32838,32838],[32842,32845],[32850,32850],[32852,32852],[32856,32856],[32858,32858],[32873,32874],[32881,32881],[32895,32896],[32899,32900],[32902,32903],[32905,32905],[32907,32908],[32915,32915],[32918,32918],[32920,32920],[32922,32925],[32927,32930],[32932,32933],[32937,32939],[32941,32943],[32945,32946],[32948,32948],[32951,32952],[32954,32954],[32956,32964],[32966,32966],[32968,32968],[32972,32974],[32982,32983],[32985,32990],[32992,32993],[32995,32997],[32999,33005],[33007,33012],[33014,33014],[33016,33016],[33018,33018],[33020,33021],[33026,33026],[33030,33030],[33033,33034],[33037,33044],[33046,33046],[33048,33048],[33050,33050],[33054,33055],[33065,33065],[33068,33068],[33071,33071],[33073,33074],[33078,33078],[33080,33080],[33086,33087],[33094,33094],[33096,33096],[33098,33100],[33104,33109],[33112,33114],[33120,33120],[33125,33125],[33127,33129],[33133,33137],[33140,33140],[33145,33152],[33154,33154],[33160,33160],[33162,33162],[33167,33167],[33169,33169],[33176,33177],[33179,33181],[33187,33187],[33190,33190],[33192,33192],[33194,33194],[33203,33203],[33210,33211],[33216,33219],[33222,33222],[33226,33226],[33228,33228],[33233,33233],[33244,33244],[33251,33251],[33255,33255],[33258,33258],[33260,33261],[33267,33268],[33275,33276],[33278,33278],[33280,33282],[33284,33286],[33292,33293],[33296,33296],[33298,33298],[33300,33300],[33307,33308],[33310,33315],[33317,33317],[33320,33320],[33322,33325],[33327,33337],[33339,33339],[33342,33342],[33348,33349],[33351,33351],[33353,33353],[33355,33355],[33358,33359],[33368,33368],[33370,33370],[33375,33375],[33384,33384],[33390,33392],[33394,33396],[33401,33402],[33405,33407],[33410,33412],[33416,33416],[33418,33419],[33421,33423],[33425,33426],[33431,33433],[33436,33437],[33439,33441],[33443,33446],[33448,33457],[33459,33460],[33463,33465],[33468,33470],[33473,33473],[33476,33476],[33479,33487],[33489,33493],[33495,33496],[33499,33500],[33502,33505],[33507,33511],[33515,33515],[33519,33519],[33521,33521],[33524,33524],[33527,33527],[33529,33529],[33531,33531],[33534,33534],[33536,33545],[33547,33548],[33550,33551],[33553,33553],[33555,33557],[33559,33559],[33562,33565],[33575,33576],[33579,33581],[33583,33583],[33585,33585],[33587,33590],[33592,33594],[33596,33597],[33600,33601],[33603,33604],[33606,33607],[33609,33609],[33615,33620],[33622,33622],[33625,33628],[33630,33633],[33635,33647],[33655,33656],[33659,33661],[33669,33670],[33673,33673],[33678,33678],[33682,33683],[33688,33689],[33691,33694],[33696,33696],[33704,33707],[33712,33716],[33718,33722],[33724,33725],[33727,33730],[33733,33733],[33735,33735],[33737,33738],[33740,33741],[33743,33743],[33748,33748],[33750,33750],[33752,33752],[33756,33757],[33759,33761],[33765,33765],[33769,33770],[33776,33778],[33784,33785],[33788,33789],[33793,33793],[33795,33796],[33798,33798],[33803,33807],[33809,33809],[33816,33816],[33818,33818],[33820,33821],[33827,33833],[33841,33841],[33843,33843],[33848,33849],[33852,33853],[33862,33862],[33870,33870],[33873,33873],[33878,33879],[33881,33884],[33889,33889],[33891,33891],[33897,33897],[33899,33901],[33904,33905],[33907,33910],[33912,33912],[33914,33914],[33922,33922],[33924,33924],[33927,33929],[33931,33932],[33934,33934],[33936,33936],[33943,33943],[33945,33945],[33948,33948],[33951,33951],[33953,33953],[33960,33960],[33967,33967],[33969,33970],[33972,33972],[33976,33979],[33981,33981],[33983,33983],[33985,33986],[33988,33988],[33991,33991],[33993,33994],[33997,33997],[33999,34001],[34003,34003],[34006,34006],[34013,34013],[34015,34016],[34018,34019],[34021,34022],[34028,34028],[34032,34032],[34044,34044],[34047,34048],[34051,34051],[34056,34056],[34058,34058],[34060,34060],[34065,34065],[34067,34067],[34071,34071],[34074,34074],[34079,34079],[34081,34081],[34091,34092],[34103,34109],[34115,34115],[34120,34122],[34134,34135],[34137,34137],[34142,34142],[34148,34148],[34152,34152],[34160,34160],[34162,34162],[34164,34164],[34169,34171],[34174,34174],[34177,34177],[34180,34181],[34183,34183],[34191,34191],[34203,34204],[34210,34210],[34212,34212],[34216,34216],[34218,34218],[34222,34224],[34227,34227],[34231,34233],[34239,34239],[34241,34241],[34249,34249],[34255,34256],[34259,34259],[34261,34261],[34268,34268],[34271,34272],[34276,34276],[34278,34278],[34280,34281],[34299,34299],[34303,34303],[34309,34309],[34321,34321],[34326,34326],[34328,34328],[34343,34343],[34345,34345],[34360,34360],[34364,34364],[34381,34388],[34394,34394],[34398,34398],[34402,34402],[34404,34404],[34411,34412],[34414,34414],[34417,34417],[34423,34434],[34436,34436],[34438,34438],[34442,34445],[34451,34451],[34453,34453],[34460,34461],[34467,34468],[34471,34474],[34476,34476],[34479,34482],[34484,34486],[34490,34490],[34496,34496],[34499,34500],[34502,34503],[34505,34507],[34510,34513],[34516,34516],[34520,34521],[34523,34523],[34526,34527],[34532,34532],[34537,34537],[34541,34542],[34544,34548],[34552,34553],[34558,34558],[34560,34560],[34562,34563],[34567,34570],[34573,34574],[34576,34576],[34578,34579],[34581,34581],[34583,34584],[34586,34586],[34588,34588],[34590,34590],[34593,34595],[34597,34597],[34601,34601],[34606,34606],[34609,34609],[34612,34612],[34615,34615],[34619,34619],[34622,34623],[34631,34633],[34636,34636],[34638,34638],[34643,34643],[34647,34649],[34656,34656],[34659,34661],[34670,34670],[34672,34672],[34674,34674],[34676,34676],[34678,34678],[34683,34686],[34690,34691],[34693,34693],[34696,34696],[34699,34699],[34701,34701],[34707,34707],[34711,34711],[34719,34720],[34723,34723],[34728,34728],[34731,34733],[34735,34735],[34737,34737],[34739,34739],[34741,34741],[34746,34746],[34749,34749],[34752,34752],[34758,34758],[34762,34763],[34767,34767],[34769,34771],[34779,34779],[34784,34784],[34789,34789],[34794,34795],[34798,34798],[34809,34809],[34814,34814],[34819,34819],[34826,34827],[34835,34835],[34837,34838],[34843,34843],[34849,34850],[34866,34866],[34873,34873],[34876,34876],[34880,34880],[34883,34885],[34892,34894],[34898,34898],[34900,34900],[34903,34903],[34905,34905],[34912,34917],[34920,34921],[34923,34924],[34926,34926],[34928,34928],[34930,34930],[34935,34935],[34941,34943],[34945,34946],[34948,34950],[34952,34952],[34955,34955],[34957,34957],[34962,34962],[34966,34967],[34972,34972],[34978,34978],[34980,34980],[34986,34987],[34989,34989],[34991,34991],[34993,34993],[34999,34999],[35004,35004],[35009,35010],[35013,35014],[35016,35017],[35022,35022],[35026,35026],[35028,35029],[35032,35033],[35035,35035],[35039,35039],[35042,35045],[35048,35048],[35056,35057],[35059,35060],[35064,35065],[35068,35068],[35070,35070],[35074,35074],[35082,35082],[35088,35088],[35090,35091],[35093,35093],[35097,35099],[35103,35103],[35105,35105],[35109,35109],[35114,35115],[35119,35120],[35124,35124],[35126,35126],[35137,35137],[35140,35140],[35157,35157],[35162,35162],[35164,35164],[35166,35167],[35174,35174],[35179,35179],[35195,35195],[35199,35199],[35201,35201],[35203,35203],[35206,35206],[35265,35276],[35278,35282],[35286,35286],[35290,35290],[35292,35292],[35294,35295],[35299,35299],[35301,35302],[35307,35307],[35309,35309],[35311,35311],[35313,35313],[35315,35315],[35327,35328],[35332,35332],[35335,35335],[35354,35354],[35390,35390],[35400,35400],[35423,35423],[35449,35449],[35465,35466],[35475,35475],[35591,35591],[35622,35622],[35686,35686],[35692,35692],[35744,35755],[35757,35817],[35819,35848],[35850,35895],[35900,35900],[35903,35903],[35905,35905],[35910,35911],[35913,35913],[35916,35916],[35925,35925],[35930,35930],[35937,35938],[35944,35944],[35946,35947],[35950,35950],[35955,35955],[35960,35962],[35970,35970],[35973,35974],[35977,35978],[35980,35980],[35988,35988],[35992,35992],[36125,36127],[36129,36196],[36198,36199],[36202,36203],[36205,36205],[36208,36208],[36211,36215],[36225,36225],[36228,36229],[36234,36235],[36241,36241],[36244,36244],[36255,36255],[36259,36259],[36271,36271],[36273,36273],[36275,36277],[36280,36280],[36282,36282],[36284,36284],[36286,36287],[36290,36292],[36294,36294],[36299,36300],[36302,36305],[36310,36311],[36314,36315],[36317,36319],[36323,36324],[36328,36328],[36330,36332],[36335,36335],[36337,36337],[36339,36339],[36341,36347],[36349,36349],[36357,36357],[36361,36362],[36364,36364],[36367,36367],[36370,36370],[36372,36372],[36381,36383],[36386,36387],[36390,36390],[36393,36394],[36396,36396],[36398,36399],[36401,36401],[36405,36406],[36409,36410],[36413,36413],[36416,36418],[36420,36421],[36423,36427],[36432,36434],[36441,36442],[36444,36444],[36450,36450],[36454,36454],[36457,36457],[36460,36461],[36463,36464],[36466,36466],[36468,36468],[36470,36470],[36476,36479],[36481,36481],[36485,36485],[36487,36487],[36495,36496],[36500,36500],[36508,36508],[36510,36510],[36523,36524],[36527,36527],[36530,36530],[36538,36538],[36558,36558],[36710,36764],[36766,36767],[36771,36771],[36776,36777],[36779,36779],[36784,36785],[36790,36790],[36793,36793],[36797,36799],[36801,36802],[36804,36805],[36807,36808],[36814,36814],[36816,36817],[36819,36821],[36824,36825],[36827,36831],[36834,36834],[36836,36838],[36840,36843],[36845,36846],[36848,36848],[36851,36851],[36855,36858],[36861,36861],[36864,36870],[36873,36875],[36877,36877],[36879,36882],[36884,36884],[36886,36887],[36890,36891],[36893,36898],[36902,36902],[36909,36911],[36916,36918],[36920,36920],[36923,36924],[36926,36926],[36929,36930],[36932,36932],[36934,36935],[36941,36941],[36943,36947],[36951,36952],[36955,36955],[36962,36963],[36965,36965],[36968,36968],[36973,36974],[36980,36981],[36985,36985],[36989,36989],[36991,36992],[36994,36995],[37000,37000],[37003,37003],[37009,37009],[37011,37011],[37013,37013],[37015,37017],[37019,37019],[37021,37021],[37024,37027],[37030,37030],[37032,37032],[37034,37034],[37036,37036],[37038,37046],[37048,37051],[37053,37055],[37057,37057],[37059,37061],[37063,37064],[37066,37066],[37070,37073],[37075,37075],[37079,37079],[37082,37085],[37089,37090],[37092,37092],[37094,37096],[37098,37099],[37101,37101],[37103,37103],[37108,37108],[37112,37112],[37117,37120],[37122,37125],[37132,37132],[37137,37137],[37143,37146],[37148,37148],[37150,37150],[37152,37152],[37154,37155],[37163,37163],[37167,37167],[37169,37169],[37177,37177],[37186,37187],[37189,37190],[37193,37200],[37202,37202],[37207,37207],[37210,37210],[37213,37214],[37217,37222],[37225,37226],[37228,37228],[37230,37234],[37236,37242],[37245,37247],[37253,37253],[37255,37255],[37257,37257],[37259,37261],[37264,37266],[37274,37275],[37282,37283],[37288,37288],[37290,37290],[37293,37295],[37300,37301],[37306,37306],[37310,37310],[37319,37319],[37321,37322],[37324,37329],[37340,37340],[37492,37492],[37518,37518],[37550,37550],[37574,37574],[37576,37576],[37694,37694],[37738,37738],[37775,37775],[37834,37834],[37846,37846],[37950,37950],[37995,37995],[38021,38032],[38034,38086],[38088,38098],[38101,38117],[38119,38175],[38177,38262],[38271,38271],[38376,38379],[38381,38418],[38420,38426],[38428,38429],[38431,38431],[38433,38434],[38442,38442],[38446,38446],[38449,38454],[38459,38461],[38463,38464],[38466,38466],[38468,38473],[38475,38478],[38480,38481],[38484,38485],[38491,38491],[38494,38495],[38497,38498],[38500,38500],[38503,38506],[38508,38508],[38514,38514],[38516,38519],[38531,38531],[38533,38534],[38536,38536],[38539,38539],[38541,38541],[38543,38544],[38548,38548],[38551,38553],[38556,38556],[38567,38567],[38569,38569],[38576,38576],[38579,38579],[38582,38582],[38585,38586],[38588,38590],[38592,38593],[38596,38599],[38601,38602],[38604,38607],[38610,38610],[38613,38613],[38624,38624],[38632,38634],[38639,38639],[38641,38641],[38643,38643],[38646,38647],[38649,38649],[38654,38654],[38656,38657],[38660,38665],[38669,38671],[38675,38675],[38678,38678],[38684,38684],[38686,38686],[38696,38696],[38698,38698],[38701,38701],[38704,38704],[38706,38706],[38712,38713],[38718,38718],[38738,38739],[38742,38742],[38745,38745],[38747,38747],[38750,38750],[38752,38754],[38757,38757],[38761,38761],[38764,38764],[38768,38768],[38771,38772],[38774,38774],[38776,38776],[38778,38778],[38780,38781],[38783,38783],[38785,38785],[38789,38789],[38795,38795],[38797,38797],[38801,38802],[38804,38804],[38808,38808],[38816,38817],[38819,38819],[38823,38824],[38827,38831],[38834,38836],[38850,38850],[38886,38893],[38899,38899],[38901,38902],[39029,39057],[39059,39060],[39062,39074],[39076,39079],[39118,39125],[39127,39130],[39134,39135],[39143,39144],[39181,39181],[39184,39184],[39214,39214],[39252,39253],[39267,39267],[39269,39269],[39271,39293],[39295,39297],[39299,39309],[39311,39321],[39325,39326],[39333,39333],[39335,39336],[39532,39571],[39573,39592],[39600,39601],[39606,39608],[39610,39610],[39612,39612],[39616,39619],[39621,39621],[39627,39628],[39630,39630],[39633,39633],[39635,39635],[39640,39640],[39647,39647],[39649,39650],[39654,39654],[39659,39659],[39661,39661],[39663,39663],[39673,39673],[39675,39675],[39677,39677],[39683,39683],[39688,39688],[39695,39695],[39698,39699],[39704,39704],[39711,39711],[39715,39715],[39727,39727],[39730,39730],[39734,39735],[39739,39740],[39745,39753],[39755,39755],[39757,39757],[39759,39759],[39761,39761],[39764,39764],[40060,40067],[40069,40082],[40084,40164],[40479,40499],[40501,40530],[40532,40548],[40550,40564],[40574,40576],[40578,40578],[40583,40584],[40587,40587],[40593,40595],[40598,40598],[40605,40605],[40607,40607],[40614,40614],[40628,40628],[40632,40633],[40635,40635],[40637,40638],[40644,40644],[40647,40647],[40649,40649],[40653,40655],[40657,40657],[40660,40660],[40664,40664],[40667,40669],[40671,40674],[40677,40677],[40679,40679],[40681,40682],[40687,40687],[40697,40697],[40699,40700],[40702,40702],[40715,40715],[40717,40718],[40720,40720],[40722,40723],[40727,40727],[40729,40729],[40736,40736],[40738,40738],[40745,40745],[40747,40748],[40751,40751],[40753,40753],[40759,40759],[40761,40761],[40763,40763],[40765,40766],[40769,40769],[40772,40772],[40775,40775],[40777,40777],[40784,40785],[40831,40844],[40857,40859],[40863,40864],[40866,40866],[40909,40911],[65072,65103],[65281,65470],[65474,65479],[65482,65487],[65490,65495],[65498,65500],[65504,65510],[65512,65518],[131428,131428],[132726,132726],[134352,134352],[136090,136090],[136211,136211],[144843,144843],[146583,146584],[146979,146979],[149979,149979],[150141,150141],[150217,150217],[152882,152882],[152930,152930],[153000,153000],[155351,155351],[156193,156193],[156813,156813],[157302,157302],[157564,157564],[158556,158556],[158753,158753],[163833,163833],[164872,164872],[165496,165496],[165525,165525],[165856,165856],[166729,166729],[166983,166983],[166991,166991],[166993,166993],[166996,166996],[167577,167577],[171902,171902],[171907,171907],[171916,171916],[174045,174045],[174331,174331],[174359,174359],[174640,174640],[174646,174646],[174680,174680],[176034,176034],[176423,176424],[176439,176440],[176621,176621],[176896,176896],[176995,176995],[177007,177007],[177010,177010],[177021,177021],[177156,177156],[177168,177168],[177171,177171],[177249,177249],[177383,177383],[177391,177391],[177398,177398],[177401,177401],[177421,177422],[177462,177462],[177582,177583],[177587,177587],[177639,177639],[177652,177652],[177692,177693],[177702,177704],[177706,177706],[177708,177708],[177813,177814],[177837,177837],[177901,177901],[178089,178089],[178117,178117],[178150,178150],[178169,178169],[178172,178172],[178182,178182],[178186,178186],[178204,178204],[178360,178360],[178887,178887],[179039,179039],[179042,179042],[179068,179068],[179075,179075],[179227,179227],[179575,179575],[179591,179591],[179703,179703],[179753,179753],[180265,180266],[180393,180393],[180426,180426],[180693,180693],[180697,180697],[180729,180729],[180860,180860],[180872,180872],[180900,180900],[181015,181015],[181083,181083],[181089,181089],[181092,181092],[181384,181384],[181396,181396],[181399,181399],[181570,181570],[181779,181779],[181784,181784],[181793,181793],[181801,181801],[181803,181805],[181807,181807],[181826,181826],[181834,181835],[182060,182060],[182063,182063],[182175,182175],[182209,182209],[182269,182269],[182489,182489],[182494,182494],[182497,182497],[182515,182515],[182535,182535],[182538,182538],[182557,182557],[182786,182786],[182798,182798],[182909,182909],[182953,182953],[183081,183081],[183085,183086],[183089,183089],[183096,183097],[183099,183099],[183103,183103],[183105,183105],[183114,183114],[183118,183118],[183130,183131],[183140,183140],[183145,183145],[183148,183148],[183151,183151],[183155,183155],[183158,183158],[183160,183160],[183164,183164],[183217,183217],[183231,183232],[183246,183246],[183382,183382],[183391,183391],[183541,183542],[183549,183549],[183551,183551],[183554,183555],[183562,183562],[183691,183691],[183693,183693],[183695,183696],[183711,183712],[183720,183720],[183725,183726],[183765,183765],[183832,183832],[183834,183834],[183843,183843],[183846,183846],[183850,183850],[183932,183932],[183944,183944],[183955,183955]]}},"kai":{"400":{"file":"FreeVideoKaiSC-Regular.woff2","sha256":"8aa35afa43963b660dd3840466813d21222f0ce804dee9ad64bec2cac14e49d2","ranges":[[32,126],[160,172],[174,383],[462,462],[464,464],[466,466],[468,468],[470,470],[472,472],[474,474],[476,476],[711,711],[713,713],[913,929],[931,937],[945,961],[963,969],[1025,1025],[1040,1103],[1105,1105],[8192,8203],[8208,8214],[8216,8226],[8229,8231],[8240,8247],[8249,8255],[8258,8258],[8260,8260],[8263,8265],[8273,8274],[8282,8282],[8285,8285],[8451,8451],[8470,8470],[8544,8555],[8592,8601],[8630,8633],[8644,8646],[8651,8656],[8658,8658],[8660,8660],[8678,8682],[8693,8693],[8712,8712],[8715,8715],[8719,8719],[8721,8721],[8730,8730],[8733,8734],[8736,8736],[8741,8741],[8743,8747],[8750,8750],[8756,8759],[8764,8765],[8773,8773],[8776,8776],[8780,8780],[8800,8801],[8804,8805],[8814,8815],[8857,8857],[8869,8869],[8978,8978],[9312,9547],[9632,9643],[9649,9651],[9654,9655],[9660,9661],[9664,9665],[9670,9671],[9673,9676],[9678,9683],[9698,9702],[9711,9711],[9723,9724],[9728,9731],[9733,9734],[9737,9737],[9742,9746],[9750,9751],[9756,9759],[9775,9783],[9792,9794],[9824,9839],[9842,9853],[9862,9871],[9888,9888],[9898,9899],[9917,9918],[9931,9931],[9956,9959],[12288,12333],[12336,12336],[12339,12351],[12353,12438],[12441,12543],[12549,12585],[12832,12841],[13383,13383],[13386,13386],[13678,13678],[13838,13838],[13901,13901],[13912,13912],[13926,13926],[14019,14019],[14042,14042],[14073,14073],[14275,14275],[14343,14343],[14355,14355],[14616,14616],[14660,14660],[14800,14801],[14815,14815],[15088,15088],[15114,15114],[15118,15118],[15130,15130],[15182,15182],[15189,15189],[15294,15294],[15360,15360],[15559,15559],[15576,15576],[15578,15578],[15636,15636],[15696,15696],[15794,15794],[15878,15878],[15884,15884],[16004,16004],[16108,16108],[16207,16207],[16352,16352],[16470,16470],[16558,16558],[16581,16581],[16590,16590],[16735,16735],[17209,17209],[17283,17283],[17302,17302],[17373,17373],[17377,17377],[17394,17394],[17411,17411],[17622,17622],[17627,17627],[17640,17640],[17643,17644],[17878,17878],[17883,17883],[17898,17898],[17908,17908],[18211,18211],[18265,18265],[18618,18618],[18620,18620],[18648,18648],[18813,18813],[18819,18819],[19615,19616],[19618,19618],[19731,19737],[19886,19886],[19968,19969],[19971,19971],[19975,19985],[19987,19990],[19992,19998],[20002,20002],[20004,20005],[20007,20008],[20010,20013],[20016,20016],[20018,20018],[20020,20020],[20022,20022],[20024,20027],[20029,20031],[20034,20035],[20037,20037],[20039,20041],[20043,20048],[20050,20052],[20054,20054],[20056,20057],[20060,20065],[20070,20070],[20073,20073],[20080,20081],[20083,20083],[20088,20088],[20094,20094],[20102,20102],[20104,20105],[20107,20111],[20113,20117],[20120,20120],[20122,20123],[20127,20130],[20132,20137],[20139,20142],[20146,20147],[20149,20150],[20152,20155],[20159,20167],[20169,20171],[20173,20174],[20177,20177],[20179,20185],[20189,20191],[20193,20193],[20195,20197],[20200,20200],[20202,20204],[20208,20208],[20210,20211],[20213,20215],[20219,20219],[20221,20221],[20223,20223],[20225,20225],[20232,20235],[20237,20241],[20247,20251],[20254,20256],[20258,20263],[20266,20267],[20269,20269],[20271,20272],[20274,20274],[20276,20276],[20278,20278],[20280,20280],[20282,20282],[20284,20286],[20289,20289],[20291,20291],[20294,20294],[20301,20305],[20307,20307],[20309,20320],[20323,20325],[20327,20327],[20329,20329],[20332,20332],[20335,20336],[20339,20340],[20342,20342],[20344,20344],[20346,20351],[20353,20356],[20360,20361],[20363,20363],[20365,20365],[20367,20367],[20369,20369],[20372,20372],[20375,20376],[20379,20379],[20381,20381],[20384,20384],[20387,20387],[20389,20394],[20396,20396],[20398,20399],[20404,20405],[20409,20409],[20415,20415],[20419,20421],[20426,20426],[20429,20433],[20439,20442],[20444,20447],[20449,20449],[20451,20451],[20454,20454],[20456,20459],[20461,20463],[20465,20465],[20467,20467],[20469,20470],[20472,20472],[20474,20474],[20478,20478],[20492,20493],[20495,20495],[20498,20501],[20504,20506],[20508,20508],[20510,20511],[20513,20513],[20517,20522],[20524,20526],[20532,20532],[20538,20540],[20542,20542],[20545,20545],[20547,20547],[20551,20552],[20556,20556],[20558,20559],[20563,20563],[20565,20565],[20570,20570],[20572,20572],[20577,20577],[20581,20581],[20588,20589],[20592,20592],[20594,20594],[20598,20599],[20603,20603],[20606,20608],[20611,20611],[20613,20613],[20616,20617],[20621,20621],[20626,20626],[20629,20629],[20643,20643],[20645,20645],[20647,20649],[20652,20652],[20658,20658],[20666,20667],[20679,20679],[20686,20687],[20692,20692],[20694,20694],[20698,20698],[20710,20711],[20716,20718],[20720,20720],[20723,20723],[20725,20725],[20731,20731],[20742,20743],[20747,20747],[20754,20754],[20769,20769],[20774,20774],[20787,20788],[20799,20801],[20803,20806],[20808,20809],[20811,20811],[20813,20813],[20817,20817],[20820,20822],[20826,20826],[20828,20828],[20834,20834],[20837,20837],[20840,20840],[20843,20846],[20848,20849],[20851,20857],[20859,20861],[20864,20866],[20869,20869],[20872,20873],[20876,20877],[20879,20879],[20882,20882],[20884,20887],[20889,20889],[20891,20892],[20896,20896],[20898,20898],[20900,20901],[20907,20908],[20910,20915],[20917,20919],[20923,20925],[20928,20928],[20932,20932],[20934,20935],[20937,20937],[20939,20940],[20943,20943],[20945,20945],[20947,20947],[20952,20952],[20955,20955],[20957,20957],[20960,20961],[20964,20964],[20971,20971],[20973,20973],[20975,20976],[20979,20979],[20981,20982],[20984,20989],[20991,20995],[20998,21000],[21002,21002],[21005,21006],[21009,21010],[21014,21019],[21021,21021],[21024,21024],[21028,21028],[21032,21033],[21035,21038],[21040,21040],[21043,21043],[21046,21051],[21053,21053],[21055,21059],[21061,21061],[21066,21069],[21072,21073],[21076,21078],[21084,21084],[21086,21087],[21089,21089],[21093,21093],[21095,21095],[21097,21098],[21103,21103],[21106,21106],[21117,21117],[21119,21119],[21121,21122],[21124,21124],[21128,21128],[21136,21136],[21139,21139],[21147,21147],[21149,21155],[21160,21165],[21169,21171],[21180,21180],[21182,21183],[21187,21187],[21191,21191],[21193,21193],[21195,21195],[21197,21197],[21200,21200],[21202,21202],[21204,21204],[21206,21206],[21208,21208],[21210,21210],[21215,21216],[21220,21220],[21232,21232],[21241,21242],[21246,21248],[21253,21254],[21256,21256],[21261,21261],[21263,21264],[21269,21271],[21273,21274],[21276,21277],[21280,21281],[21283,21283],[21286,21286],[21290,21290],[21294,21294],[21305,21308],[21310,21311],[21313,21313],[21315,21315],[21317,21317],[21319,21322],[21326,21327],[21329,21331],[21333,21335],[21338,21338],[21340,21340],[21342,21348],[21350,21351],[21353,21353],[21355,21356],[21358,21361],[21363,21365],[21367,21368],[21370,21370],[21375,21375],[21378,21378],[21380,21382],[21385,21385],[21387,21389],[21397,21398],[21400,21400],[21402,21402],[21405,21405],[21407,21407],[21410,21411],[21413,21414],[21416,21417],[21422,21422],[21430,21430],[21435,21435],[21438,21439],[21441,21442],[21446,21453],[21457,21457],[21460,21467],[21471,21472],[21475,21478],[21480,21491],[21493,21497],[21499,21501],[21505,21505],[21507,21508],[21510,21510],[21512,21514],[21516,21523],[21525,21527],[21531,21531],[21533,21537],[21539,21539],[21542,21545],[21547,21551],[21553,21554],[21556,21557],[21560,21561],[21563,21566],[21568,21568],[21571,21571],[21574,21576],[21578,21579],[21584,21584],[21586,21593],[21595,21596],[21602,21604],[21606,21606],[21608,21608],[21617,21619],[21621,21624],[21627,21629],[21632,21632],[21634,21634],[21636,21636],[21638,21639],[21641,21641],[21643,21648],[21650,21650],[21652,21654],[21657,21659],[21661,21661],[21665,21665],[21667,21677],[21679,21679],[21681,21681],[21683,21684],[21688,21688],[21690,21691],[21693,21693],[21695,21700],[21702,21705],[21708,21717],[21719,21719],[21721,21722],[21724,21727],[21730,21730],[21733,21738],[21741,21742],[21745,21747],[21754,21754],[21756,21757],[21759,21759],[21761,21761],[21766,21767],[21769,21769],[21775,21777],[21780,21780],[21787,21787],[21789,21789],[21792,21792],[21794,21796],[21799,21799],[21802,21802],[21804,21804],[21806,21809],[21811,21811],[21813,21813],[21815,21815],[21820,21820],[21822,21823],[21825,21825],[21827,21828],[21830,21830],[21833,21834],[21840,21840],[21845,21846],[21852,21852],[21857,21857],[21860,21863],[21866,21870],[21872,21872],[21876,21880],[21883,21884],[21886,21886],[21888,21892],[21894,21899],[21903,21903],[21905,21905],[21908,21908],[21912,21913],[21916,21917],[21919,21919],[21924,21924],[21927,21927],[21937,21937],[21939,21939],[21941,21941],[21943,21943],[21945,21945],[21947,21947],[21949,21950],[21956,21957],[21961,21961],[21964,21965],[21968,21972],[21974,21974],[21980,21983],[21985,21985],[21987,21990],[21992,21992],[21994,21996],[21999,21999],[22002,22003],[22005,22005],[22007,22007],[22013,22014],[22016,22017],[22024,22025],[22028,22028],[22030,22031],[22040,22040],[22042,22043],[22046,22047],[22049,22049],[22051,22052],[22055,22055],[22060,22061],[22065,22066],[22068,22068],[22070,22070],[22073,22073],[22075,22075],[22079,22080],[22082,22082],[22087,22087],[22092,22094],[22100,22100],[22103,22105],[22108,22108],[22114,22114],[22116,22116],[22120,22124],[22129,22129],[22134,22134],[22139,22140],[22148,22150],[22158,22159],[22163,22163],[22170,22170],[22179,22179],[22189,22189],[22191,22191],[22199,22199],[22204,22204],[22218,22218],[22228,22228],[22231,22231],[22234,22235],[22237,22242],[22244,22244],[22251,22251],[22253,22253],[22256,22257],[22260,22261],[22263,22263],[22265,22266],[22269,22271],[22275,22276],[22278,22278],[22280,22282],[22284,22284],[22288,22288],[22297,22297],[22300,22300],[22303,22303],[22306,22307],[22312,22320],[22322,22323],[22329,22331],[22334,22334],[22336,22336],[22338,22338],[22343,22343],[22345,22354],[22359,22359],[22362,22369],[22372,22374],[22376,22381],[22383,22384],[22387,22387],[22390,22391],[22395,22397],[22402,22406],[22408,22408],[22411,22415],[22418,22419],[22421,22421],[22425,22427],[22430,22436],[22438,22439],[22441,22441],[22443,22443],[22445,22447],[22449,22450],[22452,22453],[22456,22456],[22458,22458],[22462,22463],[22466,22467],[22470,22471],[22475,22476],[22478,22479],[22482,22482],[22484,22485],[22487,22490],[22493,22493],[22495,22496],[22500,22500],[22506,22507],[22509,22509],[22511,22511],[22516,22517],[22520,22522],[22524,22525],[22528,22528],[22530,22531],[22534,22535],[22537,22537],[22539,22542],[22544,22545],[22549,22549],[22553,22553],[22558,22558],[22560,22561],[22564,22564],[22567,22568],[22570,22570],[22576,22576],[22578,22578],[22581,22581],[22588,22590],[22596,22598],[22604,22605],[22609,22609],[22612,22612],[22616,22616],[22621,22622],[22629,22629],[22635,22636],[22641,22641],[22654,22654],[22656,22657],[22659,22659],[22661,22661],[22664,22665],[22672,22672],[22674,22675],[22677,22677],[22680,22682],[22686,22687],[22689,22689],[22691,22691],[22694,22694],[22696,22697],[22716,22716],[22721,22721],[22725,22725],[22737,22737],[22741,22741],[22756,22756],[22763,22764],[22766,22766],[22768,22768],[22771,22771],[22774,22774],[22776,22777],[22786,22786],[22788,22788],[22791,22791],[22797,22797],[22799,22800],[22804,22806],[22809,22810],[22812,22812],[22815,22815],[22820,22821],[22823,22823],[22825,22831],[22833,22833],[22836,22836],[22839,22842],[22844,22844],[22849,22850],[22852,22852],[22855,22857],[22859,22859],[22862,22863],[22865,22865],[22867,22872],[22874,22874],[22880,22882],[22885,22885],[22893,22893],[22899,22900],[22902,22902],[22904,22905],[22909,22909],[22913,22916],[22918,22920],[22922,22922],[22925,22925],[22930,22931],[22934,22937],[22942,22942],[22947,22949],[22951,22955],[22957,22959],[22962,22962],[22969,22969],[22971,22971],[22974,22974],[22982,22982],[22984,22984],[22986,22987],[22992,22996],[22999,23000],[23002,23002],[23004,23006],[23011,23013],[23016,23016],[23020,23020],[23022,23022],[23025,23025],[23030,23030],[23033,23033],[23035,23035],[23037,23037],[23039,23041],[23043,23049],[23052,23052],[23057,23057],[23059,23059],[23064,23064],[23068,23068],[23071,23072],[23075,23075],[23077,23077],[23081,23081],[23089,23090],[23092,23094],[23100,23100],[23104,23104],[23110,23110],[23113,23114],[23116,23117],[23125,23125],[23128,23128],[23130,23130],[23134,23134],[23136,23136],[23138,23138],[23140,23140],[23143,23143],[23146,23147],[23155,23159],[23162,23164],[23167,23167],[23170,23170],[23172,23172],[23174,23174],[23186,23187],[23190,23190],[23194,23195],[23198,23198],[23210,23210],[23213,23213],[23217,23219],[23221,23221],[23224,23224],[23230,23230],[23233,23234],[23236,23236],[23241,23241],[23244,23244],[23250,23250],[23252,23254],[23256,23256],[23258,23258],[23260,23260],[23264,23265],[23267,23267],[23270,23270],[23273,23275],[23277,23277],[23281,23281],[23293,23293],[23305,23305],[23318,23319],[23323,23323],[23333,23333],[23340,23340],[23346,23346],[23348,23348],[23351,23351],[23359,23360],[23365,23365],[23376,23377],[23379,23389],[23391,23391],[23394,23398],[23401,23402],[23404,23404],[23408,23409],[23411,23411],[23413,23413],[23418,23418],[23421,23421],[23424,23425],[23427,23429],[23431,23433],[23435,23436],[23439,23439],[23443,23443],[23445,23445],[23447,23454],[23456,23463],[23466,23468],[23472,23472],[23475,23478],[23480,23481],[23485,23487],[23489,23490],[23492,23495],[23500,23500],[23504,23504],[23506,23507],[23517,23519],[23521,23521],[23524,23525],[23528,23528],[23534,23534],[23536,23536],[23544,23548],[23551,23551],[23553,23553],[23556,23556],[23558,23558],[23561,23562],[23567,23567],[23569,23569],[23572,23574],[23576,23576],[23578,23578],[23580,23581],[23586,23586],[23588,23589],[23591,23592],[23594,23594],[23596,23596],[23601,23601],[23604,23604],[23608,23619],[23621,23621],[23624,23627],[23630,23633],[23637,23637],[23641,23641],[23646,23646],[23648,23649],[23651,23651],[23653,23654],[23662,23663],[23665,23665],[23673,23674],[23676,23676],[23678,23679],[23681,23682],[23688,23688],[23690,23690],[23692,23693],[23696,23697],[23700,23700],[23702,23708],[23710,23710],[23712,23712],[23714,23715],[23720,23721],[23723,23725],[23729,23729],[23731,23731],[23733,23733],[23735,23736],[23741,23741],[23743,23743],[23745,23748],[23755,23755],[23762,23762],[23767,23769],[23771,23771],[23777,23777],[23779,23784],[23786,23786],[23789,23789],[23792,23793],[23803,23803],[23807,23812],[23814,23815],[23820,23820],[23822,23822],[23826,23826],[23828,23828],[23830,23830],[23834,23835],[23838,23839],[23841,23841],[23844,23844],[23846,23847],[23849,23849],[23853,23854],[23860,23860],[23862,23862],[23869,23871],[23873,23873],[23877,23877],[23879,23879],[23882,23884],[23886,23886],[23894,23894],[23896,23896],[23898,23899],[23901,23901],[23913,23913],[23915,23916],[23919,23919],[23922,23922],[23924,23924],[23938,23938],[23941,23941],[23949,23949],[23954,23955],[23961,23961],[23965,23965],[23967,23967],[23974,23974],[23986,23986],[23991,23991],[24005,24005],[24007,24007],[24009,24009],[24013,24013],[24027,24027],[24029,24030],[24033,24034],[24037,24041],[24043,24043],[24046,24047],[24049,24052],[24055,24055],[24061,24062],[24065,24067],[24069,24070],[24072,24072],[24076,24076],[24079,24081],[24084,24086],[24088,24093],[24097,24097],[24102,24104],[24109,24110],[24113,24113],[24119,24120],[24123,24125],[24130,24130],[24132,24133],[24140,24140],[24148,24150],[24155,24155],[24158,24158],[24161,24162],[24170,24170],[24178,24180],[24182,24182],[24184,24184],[24186,24189],[24191,24192],[24196,24196],[24198,24199],[24202,24203],[24207,24209],[24211,24215],[24217,24218],[24220,24220],[24222,24224],[24228,24231],[24237,24237],[24241,24241],[24243,24243],[24245,24249],[24252,24252],[24254,24254],[24262,24262],[24265,24267],[24273,24275],[24278,24278],[24281,24281],[24283,24283],[24296,24296],[24298,24298],[24308,24308],[24310,24311],[24314,24314],[24318,24324],[24326,24328],[24330,24331],[24335,24335],[24337,24337],[24339,24339],[24341,24341],[24343,24344],[24347,24347],[24351,24352],[24354,24354],[24357,24362],[24365,24365],[24367,24367],[24369,24369],[24374,24374],[24376,24378],[24380,24380],[24384,24384],[24400,24400],[24402,24403],[24405,24408],[24413,24413],[24415,24415],[24417,24418],[24420,24420],[24422,24423],[24425,24426],[24428,24429],[24432,24433],[24435,24435],[24439,24439],[24441,24441],[24443,24444],[24448,24450],[24452,24453],[24455,24460],[24464,24464],[24466,24466],[24469,24469],[24471,24473],[24475,24476],[24481,24481],[24488,24488],[24490,24490],[24493,24494],[24501,24501],[24503,24503],[24508,24509],[24515,24518],[24521,24521],[24524,24525],[24527,24530],[24534,24537],[24541,24542],[24544,24545],[24548,24548],[24551,24551],[24554,24555],[24557,24558],[24561,24561],[24563,24563],[24565,24565],[24568,24568],[24570,24571],[24573,24582],[24586,24586],[24589,24591],[24594,24594],[24596,24598],[24601,24601],[24603,24605],[24608,24609],[24613,24619],[24623,24623],[24629,24629],[24635,24636],[24639,24639],[24641,24643],[24651,24651],[24653,24653],[24656,24656],[24658,24661],[24665,24666],[24669,24669],[24674,24676],[24679,24685],[24687,24688],[24691,24691],[24694,24694],[24696,24701],[24703,24703],[24707,24708],[24710,24710],[24712,24713],[24716,24717],[24722,24722],[24724,24724],[24726,24726],[24730,24731],[24733,24733],[24735,24736],[24738,24739],[24742,24742],[24744,24744],[24747,24749],[24751,24754],[24756,24756],[24760,24760],[24763,24764],[24773,24775],[24778,24779],[24782,24782],[24785,24785],[24788,24789],[24792,24797],[24799,24800],[24806,24809],[24811,24816],[24819,24820],[24822,24822],[24825,24826],[24832,24833],[24835,24835],[24838,24838],[24840,24841],[24845,24848],[24852,24853],[24858,24858],[24863,24864],[24867,24868],[24870,24871],[24875,24875],[24877,24877],[24895,24895],[24902,24902],[24904,24904],[24906,24906],[24908,24908],[24910,24910],[24913,24913],[24917,24917],[24925,24925],[24930,24930],[24933,24933],[24935,24936],[24940,24941],[24944,24944],[24949,24949],[24951,24951],[24971,24971],[24974,24974],[24980,24981],[24985,24985],[24989,24989],[24999,25001],[25004,25005],[25015,25015],[25018,25018],[25022,25022],[25026,25026],[25032,25032],[25034,25035],[25041,25042],[25044,25044],[25062,25062],[25077,25077],[25087,25087],[25094,25094],[25096,25096],[25098,25106],[25109,25112],[25114,25115],[25119,25119],[25121,25125],[25130,25130],[25132,25134],[25139,25140],[25143,25143],[25149,25155],[25157,25166],[25169,25172],[25176,25176],[25179,25179],[25182,25182],[25187,25187],[25190,25191],[25193,25200],[25203,25203],[25206,25206],[25209,25210],[25212,25216],[25219,25220],[25225,25226],[25233,25240],[25242,25243],[25247,25250],[25252,25253],[25256,25256],[25259,25260],[25265,25265],[25269,25269],[25273,25273],[25275,25277],[25279,25279],[25282,25290],[25292,25294],[25296,25296],[25298,25300],[25302,25308],[25311,25311],[25314,25321],[25324,25327],[25329,25329],[25331,25332],[25334,25335],[25340,25343],[25345,25346],[25351,25353],[25358,25358],[25361,25361],[25363,25363],[25366,25366],[25370,25371],[25373,25382],[25384,25384],[25386,25387],[25391,25391],[25394,25394],[25401,25402],[25405,25405],[25410,25411],[25413,25414],[25417,25417],[25419,25424],[25429,25429],[25438,25439],[25441,25443],[25447,25447],[25449,25449],[25453,25455],[25457,25457],[25462,25463],[25466,25467],[25469,25469],[25472,25472],[25474,25474],[25479,25482],[25484,25484],[25486,25488],[25490,25490],[25494,25494],[25496,25496],[25502,25502],[25504,25504],[25506,25507],[25509,25509],[25511,25514],[25516,25518],[25520,25520],[25523,25524],[25527,25528],[25530,25530],[25532,25532],[25534,25534],[25540,25540],[25542,25542],[25545,25545],[25549,25552],[25554,25554],[25557,25558],[25566,25566],[25568,25569],[25571,25571],[25577,25578],[25581,25581],[25586,25588],[25590,25590],[25592,25592],[25597,25597],[25599,25602],[25605,25605],[25611,25612],[25615,25616],[25618,25620],[25627,25628],[25630,25630],[25632,25633],[25638,25638],[25642,25642],[25644,25645],[25652,25652],[25658,25658],[25661,25661],[25663,25663],[25665,25665],[25668,25672],[25674,25674],[25679,25679],[25682,25682],[25684,25684],[25688,25688],[25691,25691],[25694,25694],[25703,25703],[25705,25705],[25709,25709],[25716,25716],[25720,25722],[25725,25725],[25730,25730],[25732,25733],[25735,25735],[25745,25746],[25749,25750],[25753,25753],[25758,25758],[25764,25764],[25769,25769],[25772,25774],[25776,25776],[25781,25781],[25783,25784],[25786,25786],[25788,25788],[25792,25792],[25794,25794],[25797,25797],[25805,25806],[25808,25808],[25810,25810],[25815,25816],[25822,25822],[25826,25826],[25828,25828],[25830,25830],[25855,25856],[25865,25865],[25874,25874],[25880,25880],[25893,25893],[25899,25899],[25902,25903],[25908,25910],[25912,25913],[25915,25915],[25917,25919],[25925,25925],[25928,25929],[25932,25932],[25935,25935],[25937,25937],[25940,25942],[25945,25945],[25947,25947],[25949,25950],[25954,25955],[25958,25958],[25961,25961],[25963,25964],[25968,25968],[25970,25970],[25972,25972],[25975,25975],[25991,25991],[25995,25996],[26000,26001],[26003,26003],[26007,26007],[26009,26009],[26011,26013],[26015,26017],[26020,26021],[26023,26023],[26025,26025],[26027,26027],[26029,26029],[26031,26032],[26038,26038],[26041,26041],[26044,26045],[26049,26049],[26051,26054],[26059,26060],[26062,26064],[26066,26066],[26070,26071],[26078,26078],[26080,26080],[26082,26082],[26085,26089],[26092,26097],[26100,26104],[26106,26107],[26111,26112],[26114,26116],[26118,26122],[26124,26124],[26126,26127],[26130,26133],[26137,26137],[26141,26141],[26143,26145],[26147,26149],[26151,26152],[26154,26155],[26157,26157],[26159,26159],[26161,26161],[26163,26166],[26170,26170],[26172,26174],[26177,26177],[26179,26179],[26181,26181],[26186,26188],[26191,26192],[26194,26199],[26201,26202],[26206,26207],[26209,26210],[26212,26212],[26214,26214],[26216,26216],[26218,26219],[26222,26225],[26228,26228],[26230,26231],[26234,26234],[26238,26238],[26242,26242],[26244,26245],[26247,26247],[26252,26252],[26257,26257],[26261,26263],[26269,26269],[26279,26280],[26286,26286],[26290,26290],[26292,26294],[26297,26297],[26302,26303],[26312,26312],[26316,26316],[26329,26329],[26331,26333],[26342,26342],[26345,26345],[26352,26352],[26354,26356],[26359,26359],[26361,26361],[26364,26364],[26366,26368],[26376,26379],[26381,26381],[26383,26384],[26387,26389],[26391,26391],[26395,26395],[26397,26397],[26399,26399],[26406,26406],[26408,26408],[26410,26413],[26415,26415],[26417,26417],[26419,26421],[26424,26424],[26426,26426],[26429,26429],[26432,26432],[26434,26436],[26438,26438],[26440,26441],[26444,26444],[26446,26449],[26451,26451],[26453,26454],[26457,26457],[26460,26460],[26462,26465],[26469,26469],[26471,26474],[26477,26477],[26479,26480],[26482,26483],[26485,26485],[26487,26487],[26491,26492],[26494,26495],[26497,26497],[26500,26501],[26503,26503],[26505,26505],[26507,26507],[26509,26509],[26512,26512],[26517,26517],[26519,26520],[26522,26522],[26524,26526],[26530,26531],[26533,26533],[26535,26536],[26538,26539],[26541,26541],[26543,26544],[26546,26547],[26549,26553],[26561,26561],[26563,26564],[26568,26568],[26570,26570],[26575,26580],[26582,26582],[26584,26586],[26588,26590],[26592,26592],[26594,26594],[26597,26597],[26601,26601],[26604,26604],[26607,26609],[26611,26612],[26615,26615],[26621,26621],[26623,26624],[26629,26629],[26631,26636],[26638,26643],[26646,26647],[26653,26653],[26655,26655],[26657,26657],[26665,26666],[26674,26676],[26679,26681],[26683,26686],[26688,26694],[26696,26698],[26700,26700],[26702,26702],[26704,26705],[26707,26709],[26720,26729],[26731,26731],[26735,26735],[26738,26738],[26740,26740],[26742,26743],[26745,26745],[26753,26753],[26755,26755],[26757,26758],[26764,26764],[26767,26767],[26771,26771],[26775,26775],[26784,26784],[26786,26787],[26790,26792],[26797,26797],[26799,26800],[26803,26805],[26812,26818],[26825,26825],[26827,26827],[26829,26829],[26832,26832],[26834,26835],[26837,26837],[26840,26840],[26842,26842],[26848,26848],[26851,26852],[26856,26856],[26858,26860],[26862,26862],[26864,26865],[26869,26869],[26873,26877],[26880,26881],[26885,26886],[26891,26891],[26893,26894],[26896,26899],[26911,26912],[26916,26916],[26922,26922],[26925,26925],[26928,26928],[26932,26932],[26936,26937],[26941,26941],[26943,26943],[26946,26946],[26962,26962],[26964,26964],[26967,26967],[26969,26970],[26973,26974],[26976,26976],[26979,26979],[26982,26982],[26985,26987],[26990,26991],[26993,26993],[26999,27001],[27004,27004],[27008,27008],[27010,27017],[27021,27021],[27025,27025],[27028,27030],[27032,27032],[27035,27036],[27047,27048],[27051,27051],[27053,27053],[27056,27057],[27060,27060],[27063,27063],[27067,27067],[27073,27073],[27075,27075],[27082,27082],[27084,27084],[27086,27086],[27088,27088],[27092,27092],[27098,27100],[27103,27104],[27117,27117],[27121,27122],[27133,27133],[27135,27135],[27146,27146],[27159,27160],[27167,27167],[27169,27169],[27176,27176],[27178,27178],[27183,27183],[27185,27185],[27189,27189],[27197,27198],[27204,27204],[27207,27207],[27216,27217],[27224,27225],[27227,27227],[27230,27230],[27233,27233],[27237,27238],[27249,27249],[27257,27257],[27260,27260],[27264,27264],[27268,27268],[27278,27278],[27280,27281],[27287,27287],[27294,27294],[27296,27296],[27305,27305],[27307,27308],[27334,27334],[27394,27394],[27424,27428],[27431,27431],[27442,27442],[27447,27451],[27454,27454],[27459,27459],[27461,27463],[27465,27465],[27468,27468],[27481,27481],[27490,27495],[27498,27498],[27513,27513],[27515,27516],[27521,27524],[27526,27527],[27529,27531],[27533,27533],[27538,27539],[27542,27542],[27546,27547],[27553,27553],[27555,27555],[27562,27562],[27571,27573],[27575,27575],[27583,27583],[27585,27586],[27589,27589],[27595,27597],[27599,27600],[27602,27607],[27609,27609],[27611,27611],[27617,27617],[27626,27627],[27631,27631],[27635,27635],[27637,27637],[27641,27641],[27645,27645],[27653,27655],[27661,27661],[27663,27665],[27667,27670],[27672,27675],[27679,27679],[27681,27682],[27684,27684],[27686,27690],[27694,27696],[27698,27698],[27700,27701],[27704,27704],[27709,27714],[27718,27723],[27728,27728],[27732,27733],[27735,27735],[27739,27745],[27748,27748],[27751,27755],[27757,27757],[27760,27760],[27762,27762],[27764,27764],[27766,27766],[27769,27769],[27773,27774],[27777,27785],[27788,27788],[27791,27792],[27795,27796],[27800,27803],[27807,27807],[27809,27809],[27811,27819],[27821,27822],[27825,27827],[27832,27839],[27842,27845],[27847,27847],[27849,27850],[27852,27852],[27856,27856],[27859,27863],[27865,27868],[27870,27870],[27872,27875],[27877,27877],[27880,27880],[27882,27883],[27886,27889],[27891,27891],[27893,27896],[27898,27902],[27905,27905],[27908,27908],[27911,27912],[27915,27916],[27918,27918],[27921,27923],[27927,27931],[27934,27934],[27938,27939],[27941,27941],[27943,27944],[27946,27947],[27949,27950],[27953,27957],[27960,27967],[27969,27969],[27971,27971],[27973,27979],[27981,27989],[27993,27996],[27998,28001],[28003,28003],[28005,28006],[28009,28010],[28012,28016],[28018,28018],[28020,28020],[28023,28024],[28028,28028],[28034,28034],[28036,28037],[28040,28041],[28044,28046],[28048,28049],[28051,28053],[28056,28056],[28059,28059],[28061,28068],[28070,28075],[28078,28079],[28082,28082],[28084,28085],[28088,28088],[28095,28096],[28100,28103],[28107,28108],[28111,28111],[28113,28113],[28118,28118],[28120,28121],[28124,28129],[28132,28132],[28134,28134],[28139,28140],[28142,28143],[28145,28145],[28147,28148],[28151,28151],[28153,28153],[28155,28156],[28165,28165],[28170,28170],[28172,28174],[28176,28177],[28180,28180],[28182,28183],[28186,28186],[28189,28189],[28191,28193],[28195,28197],[28201,28201],[28203,28203],[28205,28205],[28207,28208],[28210,28210],[28212,28212],[28216,28216],[28218,28218],[28220,28220],[28227,28228],[28233,28233],[28237,28238],[28241,28241],[28243,28244],[28246,28246],[28248,28248],[28251,28253],[28255,28255],[28259,28259],[28267,28267],[28270,28270],[28274,28274],[28276,28276],[28286,28287],[28289,28289],[28291,28291],[28293,28295],[28297,28297],[28301,28301],[28303,28304],[28312,28312],[28314,28314],[28316,28316],[28318,28320],[28322,28322],[28325,28327],[28330,28330],[28335,28335],[28337,28338],[28340,28343],[28345,28347],[28349,28349],[28353,28355],[28358,28359],[28361,28361],[28363,28363],[28365,28365],[28367,28367],[28369,28369],[28371,28373],[28375,28376],[28378,28378],[28382,28386],[28388,28395],[28404,28404],[28409,28409],[28418,28418],[28422,28422],[28424,28425],[28427,28427],[28431,28431],[28435,28438],[28448,28448],[28452,28452],[28454,28454],[28457,28459],[28461,28461],[28463,28463],[28465,28465],[28467,28468],[28470,28471],[28473,28473],[28475,28476],[28478,28478],[28486,28487],[28491,28491],[28493,28493],[28495,28495],[28502,28502],[28504,28504],[28508,28508],[28510,28511],[28514,28514],[28518,28518],[28521,28521],[28525,28526],[28530,28530],[28532,28533],[28536,28536],[28538,28538],[28540,28542],[28546,28546],[28548,28548],[28552,28553],[28556,28558],[28571,28572],[28577,28577],[28581,28581],[28583,28583],[28586,28586],[28589,28589],[28595,28596],[28598,28598],[28601,28601],[28604,28605],[28608,28608],[28610,28610],[28617,28617],[28619,28619],[28625,28626],[28638,28638],[28640,28641],[28649,28649],[28654,28655],[28684,28685],[28689,28689],[28692,28692],[28698,28699],[28707,28707],[28721,28721],[28725,28725],[28729,28729],[28732,28732],[28744,28744],[28748,28748],[28751,28751],[28766,28766],[28779,28781],[28783,28784],[28789,28790],[28792,28792],[28796,28796],[28798,28800],[28805,28806],[28809,28810],[28812,28812],[28814,28814],[28818,28818],[28820,28822],[28824,28825],[28828,28829],[28831,28831],[28835,28835],[28843,28847],[28849,28849],[28851,28851],[28855,28857],[28859,28861],[28864,28867],[28872,28872],[28874,28874],[28884,28884],[28888,28889],[28891,28893],[28895,28896],[28900,28900],[28902,28905],[28907,28909],[28911,28911],[28918,28919],[28921,28923],[28925,28925],[28934,28934],[28937,28938],[28940,28940],[28944,28944],[28947,28947],[28949,28954],[28956,28956],[28958,28958],[28966,28966],[28975,28977],[28982,28982],[28993,28993],[28995,28995],[28997,28997],[29002,29004],[29006,29006],[29011,29011],[29020,29020],[29022,29023],[29028,29028],[29030,29032],[29038,29038],[29042,29044],[29048,29048],[29050,29050],[29053,29053],[29060,29060],[29063,29063],[29066,29066],[29071,29071],[29076,29076],[29080,29081],[29083,29084],[29087,29088],[29093,29093],[29096,29096],[29100,29100],[29107,29107],[29109,29109],[29113,29113],[29115,29115],[29123,29123],[29130,29131],[29134,29135],[29140,29141],[29146,29146],[29152,29152],[29157,29157],[29159,29159],[29166,29166],[29177,29177],[29190,29191],[29204,29204],[29210,29210],[29213,29213],[29215,29215],[29224,29224],[29226,29226],[29228,29228],[29232,29233],[29237,29241],[29243,29243],[29245,29245],[29247,29247],[29249,29250],[29255,29256],[29260,29261],[29266,29266],[29270,29270],[29273,29275],[29277,29277],[29279,29279],[29281,29282],[29284,29287],[29289,29289],[29294,29295],[29298,29298],[29301,29301],[29305,29307],[29310,29313],[29316,29316],[29319,29319],[29322,29323],[29325,29325],[29327,29327],[29330,29330],[29343,29343],[29352,29352],[29356,29357],[29359,29360],[29364,29364],[29366,29369],[29377,29380],[29384,29385],[29389,29390],[29392,29392],[29394,29394],[29399,29399],[29401,29401],[29405,29406],[29408,29409],[29416,29417],[29420,29428],[29431,29432],[29434,29436],[29441,29441],[29443,29444],[29447,29447],[29450,29450],[29454,29454],[29459,29459],[29461,29463],[29467,29470],[29473,29474],[29477,29477],[29481,29484],[29486,29489],[29492,29492],[29495,29498],[29502,29503],[29517,29517],[29520,29520],[29522,29522],[29527,29527],[29536,29536],[29548,29549],[29551,29551],[29556,29556],[29566,29566],[29571,29572],[29575,29575],[29577,29577],[29579,29579],[29582,29582],[29585,29587],[29589,29590],[29592,29595],[29598,29602],[29604,29606],[29609,29609],[29611,29611],[29613,29619],[29622,29623],[29625,29628],[29631,29632],[29634,29634],[29637,29637],[29639,29645],[29647,29650],[29653,29654],[29657,29657],[29659,29659],[29661,29662],[29664,29664],[29666,29667],[29669,29671],[29673,29675],[29677,29677],[29680,29680],[29682,29682],[29685,29685],[29687,29690],[29693,29693],[29696,29696],[29699,29706],[29710,29712],[29716,29716],[29722,29723],[29727,29727],[29729,29730],[29732,29734],[29736,29736],[29738,29744],[29746,29750],[29756,29756],[29760,29766],[29777,29777],[29779,29783],[29785,29791],[29794,29794],[29799,29800],[29804,29805],[29808,29809],[29811,29811],[29814,29815],[29822,29822],[29824,29825],[29827,29827],[29830,29832],[29835,29835],[29838,29838],[29840,29840],[29842,29842],[29848,29848],[29852,29852],[29854,29856],[29861,29861],[29863,29866],[29868,29868],[29870,29870],[29873,29874],[29882,29882],[29888,29888],[29906,29906],[29910,29910],[29912,29912],[29916,29916],[29918,29918],[29920,29920],[29922,29924],[29926,29926],[29934,29935],[29940,29940],[29942,29943],[29947,29947],[29951,29951],[29956,29956],[29965,29965],[29967,29967],[29969,29969],[29971,29971],[29975,29978],[29980,29980],[29983,29983],[29985,29985],[29989,29990],[29992,29997],[29999,30003],[30005,30005],[30007,30008],[30010,30011],[30014,30014],[30016,30016],[30021,30021],[30024,30024],[30027,30028],[30030,30031],[30036,30036],[30038,30038],[30041,30044],[30052,30054],[30058,30058],[30060,30060],[30063,30063],[30066,30066],[30068,30068],[30072,30073],[30079,30079],[30081,30081],[30083,30083],[30086,30086],[30091,30091],[30093,30093],[30095,30098],[30100,30100],[30102,30103],[30105,30106],[30109,30109],[30111,30117],[30123,30133],[30136,30137],[30140,30142],[30146,30149],[30151,30154],[30157,30157],[30162,30166],[30168,30168],[30171,30171],[30174,30174],[30178,30180],[30182,30184],[30186,30187],[30192,30193],[30196,30196],[30201,30201],[30204,30204],[30207,30209],[30211,30211],[30213,30214],[30218,30218],[30220,30220],[30224,30224],[30229,30229],[30231,30233],[30235,30235],[30239,30240],[30242,30242],[30244,30246],[30249,30251],[30253,30253],[30256,30256],[30259,30261],[30264,30264],[30268,30268],[30270,30272],[30275,30275],[30284,30285],[30292,30292],[30294,30295],[30300,30300],[30302,30302],[30307,30307],[30315,30315],[30319,30319],[30328,30328],[30331,30331],[30333,30335],[30338,30338],[30340,30340],[30342,30344],[30347,30347],[30350,30350],[30353,30353],[30355,30355],[30357,30358],[30361,30361],[30363,30363],[30366,30366],[30372,30372],[30374,30374],[30381,30382],[30385,30386],[30388,30388],[30399,30399],[30402,30402],[30405,30406],[30408,30410],[30413,30418],[30420,30420],[30422,30424],[30427,30427],[30431,30431],[30437,30438],[30446,30447],[30449,30450],[30452,30452],[30455,30457],[30460,30460],[30462,30462],[30465,30465],[30468,30468],[30471,30475],[30477,30477],[30489,30490],[30495,30496],[30498,30498],[30502,30502],[30504,30505],[30508,30509],[30511,30511],[30517,30520],[30522,30522],[30524,30524],[30528,30529],[30531,30532],[30535,30535],[30542,30542],[30544,30545],[30554,30555],[30561,30563],[30565,30566],[30568,30568],[30571,30572],[30585,30585],[30589,30592],[30596,30597],[30603,30606],[30609,30610],[30623,30624],[30626,30626],[30629,30629],[30631,30631],[30633,30637],[30640,30640],[30643,30643],[30645,30645],[30651,30651],[30653,30653],[30655,30655],[30669,30669],[30679,30679],[30683,30684],[30686,30686],[30690,30691],[30693,30693],[30695,30695],[30697,30697],[30699,30702],[30704,30704],[30707,30707],[30710,30710],[30712,30712],[30715,30722],[30724,30724],[30726,30726],[30729,30729],[30732,30733],[30737,30738],[30740,30740],[30742,30744],[30746,30746],[30748,30749],[30751,30752],[30755,30755],[30757,30759],[30761,30761],[30763,30766],[30768,30768],[30772,30773],[30775,30780],[30782,30782],[30784,30785],[30789,30789],[30791,30791],[30794,30794],[30796,30798],[30800,30800],[30802,30802],[30804,30807],[30809,30810],[30813,30813],[30826,30830],[30839,30839],[30844,30844],[30847,30847],[30851,30851],[30855,30857],[30860,30863],[30865,30865],[30867,30867],[30871,30872],[30874,30876],[30879,30879],[30881,30881],[30883,30883],[30885,30885],[30887,30888],[30896,30900],[30902,30902],[30905,30905],[30910,30910],[30913,30913],[30917,30917],[30921,30923],[30927,30928],[30932,30933],[30937,30937],[30940,30940],[30945,30945],[30952,30952],[30956,30956],[30962,30962],[30964,30964],[30967,30967],[30969,30971],[30977,30977],[30981,30981],[30988,30988],[30995,30995],[31006,31006],[31012,31012],[31028,31029],[31034,31036],[31038,31038],[31040,31041],[31043,31043],[31046,31051],[31054,31056],[31059,31059],[31061,31063],[31066,31072],[31074,31074],[31077,31077],[31079,31080],[31085,31085],[31087,31087],[31090,31090],[31095,31096],[31098,31098],[31100,31100],[31102,31102],[31104,31105],[31108,31109],[31114,31115],[31119,31119],[31122,31122],[31124,31124],[31128,31128],[31130,31131],[31140,31140],[31143,31143],[31155,31155],[31161,31163],[31165,31166],[31168,31169],[31171,31171],[31174,31174],[31177,31177],[31179,31179],[31181,31181],[31185,31186],[31189,31189],[31192,31192],[31199,31199],[31203,31204],[31206,31207],[31209,31209],[31211,31213],[31215,31216],[31224,31224],[31227,31227],[31229,31230],[31232,31232],[31234,31235],[31238,31238],[31243,31246],[31249,31249],[31252,31252],[31255,31255],[31257,31258],[31262,31262],[31264,31264],[31267,31267],[31283,31283],[31287,31287],[31289,31289],[31291,31293],[31295,31295],[31300,31300],[31302,31302],[31313,31313],[31319,31319],[31321,31321],[31324,31324],[31327,31327],[31344,31344],[31348,31348],[31350,31354],[31359,31361],[31363,31366],[31368,31368],[31370,31370],[31373,31374],[31377,31378],[31381,31384],[31388,31389],[31391,31392],[31395,31395],[31397,31398],[31400,31400],[31404,31405],[31411,31411],[31416,31416],[31423,31423],[31435,31435],[31441,31441],[31446,31446],[31448,31449],[31454,31456],[31459,31459],[31461,31462],[31467,31467],[31469,31469],[31471,31471],[31481,31482],[31485,31485],[31487,31487],[31491,31492],[31494,31494],[31496,31496],[31498,31499],[31503,31503],[31505,31505],[31508,31509],[31513,31513],[31515,31515],[31518,31518],[31520,31520],[31524,31526],[31528,31528],[31530,31532],[31534,31535],[31537,31537],[31539,31539],[31544,31544],[31546,31546],[31548,31548],[31550,31550],[31552,31552],[31557,31557],[31559,31559],[31561,31561],[31563,31564],[31567,31570],[31572,31572],[31574,31574],[31576,31576],[31578,31581],[31584,31584],[31586,31586],[31588,31590],[31598,31598],[31601,31602],[31605,31607],[31609,31609],[31611,31612],[31614,31614],[31616,31616],[31621,31621],[31629,31629],[31632,31632],[31635,31639],[31644,31645],[31649,31650],[31654,31661],[31665,31665],[31668,31668],[31672,31672],[31681,31681],[31686,31687],[31692,31692],[31697,31697],[31699,31699],[31705,31706],[31709,31709],[31713,31713],[31717,31718],[31722,31722],[31726,31727],[31729,31729],[31735,31735],[31740,31740],[31742,31742],[31747,31747],[31751,31751],[31753,31753],[31755,31756],[31759,31759],[31765,31766],[31773,31773],[31775,31776],[31782,31783],[31786,31786],[31792,31792],[31800,31800],[31807,31809],[31821,31821],[31845,31845],[31859,31860],[31867,31869],[31881,31881],[31889,31890],[31893,31893],[31895,31896],[31900,31903],[31906,31906],[31908,31909],[31914,31914],[31918,31918],[31921,31923],[31929,31929],[31932,31935],[31937,31937],[31941,31941],[31943,31944],[31946,31946],[31948,31949],[31954,31954],[31957,31959],[31961,31961],[31964,31964],[31967,31968],[31976,31976],[31983,31983],[31989,31989],[31992,31992],[31995,31995],[32010,32010],[32032,32032],[32034,32034],[32039,32039],[32043,32043],[32047,32047],[32092,32092],[32110,32110],[32119,32119],[32166,32166],[32174,32174],[32288,32288],[32290,32290],[32315,32315],[32321,32321],[32324,32324],[32327,32327],[32386,32386],[32411,32411],[32415,32491],[32493,32566],[32568,32568],[32570,32570],[32578,32578],[32580,32581],[32589,32589],[32592,32593],[32596,32597],[32599,32600],[32602,32602],[32607,32607],[32609,32610],[32616,32618],[32622,32622],[32625,32626],[32628,32628],[32630,32630],[32633,32633],[32637,32638],[32641,32641],[32650,32650],[32652,32652],[32654,32654],[32657,32657],[32659,32662],[32666,32666],[32669,32671],[32673,32673],[32676,32676],[32679,32679],[32687,32690],[32696,32697],[32700,32701],[32703,32707],[32709,32709],[32712,32712],[32714,32714],[32716,32716],[32718,32718],[32724,32725],[32728,32731],[32735,32737],[32741,32742],[32745,32745],[32750,32753],[32755,32755],[32759,32759],[32763,32764],[32766,32766],[32768,32769],[32771,32775],[32779,32781],[32783,32786],[32788,32793],[32796,32796],[32800,32800],[32802,32802],[32804,32810],[32816,32817],[32819,32819],[32821,32824],[32827,32827],[32829,32829],[32831,32831],[32834,32835],[32838,32838],[32842,32845],[32850,32850],[32852,32852],[32856,32856],[32858,32858],[32873,32874],[32881,32881],[32895,32896],[32899,32900],[32902,32903],[32905,32905],[32907,32908],[32915,32915],[32918,32918],[32920,32920],[32922,32925],[32927,32930],[32932,32933],[32937,32939],[32941,32943],[32945,32946],[32948,32948],[32951,32952],[32954,32954],[32956,32964],[32966,32966],[32968,32968],[32972,32974],[32982,32983],[32985,32990],[32992,32993],[32995,32997],[32999,33005],[33007,33012],[33014,33014],[33016,33016],[33018,33018],[33020,33021],[33026,33026],[33030,33030],[33033,33034],[33037,33044],[33046,33046],[33048,33048],[33050,33050],[33054,33055],[33065,33065],[33068,33068],[33071,33071],[33073,33074],[33078,33078],[33080,33080],[33086,33087],[33094,33094],[33096,33096],[33098,33100],[33104,33109],[33112,33114],[33120,33120],[33125,33125],[33127,33129],[33133,33137],[33140,33140],[33145,33152],[33154,33154],[33160,33160],[33162,33162],[33167,33167],[33169,33169],[33176,33177],[33179,33181],[33187,33187],[33190,33190],[33192,33192],[33194,33194],[33203,33203],[33210,33211],[33216,33219],[33222,33222],[33226,33226],[33228,33228],[33233,33233],[33244,33244],[33251,33251],[33255,33255],[33258,33258],[33260,33261],[33267,33268],[33275,33276],[33278,33278],[33280,33282],[33284,33286],[33292,33293],[33296,33296],[33298,33298],[33300,33300],[33307,33308],[33310,33315],[33317,33317],[33320,33320],[33322,33325],[33327,33337],[33339,33339],[33342,33342],[33348,33349],[33351,33351],[33353,33353],[33355,33355],[33358,33359],[33368,33368],[33370,33370],[33375,33375],[33384,33384],[33390,33392],[33394,33396],[33401,33402],[33405,33407],[33410,33412],[33416,33416],[33418,33419],[33421,33423],[33425,33426],[33431,33433],[33436,33437],[33439,33441],[33443,33446],[33448,33457],[33459,33460],[33463,33465],[33468,33470],[33473,33473],[33476,33476],[33479,33487],[33489,33493],[33495,33496],[33499,33500],[33502,33505],[33507,33511],[33515,33515],[33519,33519],[33521,33521],[33524,33524],[33527,33527],[33529,33529],[33531,33531],[33534,33534],[33536,33545],[33547,33548],[33550,33551],[33553,33553],[33555,33557],[33559,33559],[33562,33565],[33575,33576],[33579,33581],[33583,33583],[33585,33585],[33587,33590],[33592,33594],[33596,33597],[33600,33601],[33603,33604],[33606,33607],[33609,33609],[33615,33620],[33622,33622],[33625,33628],[33630,33633],[33635,33647],[33655,33656],[33659,33661],[33669,33670],[33673,33673],[33678,33678],[33682,33683],[33688,33689],[33691,33694],[33696,33696],[33704,33707],[33712,33716],[33718,33722],[33724,33725],[33727,33730],[33733,33733],[33735,33735],[33737,33738],[33740,33741],[33743,33743],[33748,33748],[33750,33750],[33752,33752],[33756,33757],[33759,33761],[33765,33765],[33769,33770],[33776,33778],[33784,33785],[33788,33789],[33793,33793],[33795,33796],[33798,33798],[33803,33807],[33809,33809],[33816,33816],[33818,33818],[33820,33821],[33827,33833],[33841,33841],[33843,33843],[33848,33849],[33852,33853],[33862,33862],[33870,33870],[33873,33873],[33878,33879],[33881,33884],[33889,33889],[33891,33891],[33897,33897],[33899,33901],[33904,33905],[33907,33910],[33912,33912],[33914,33914],[33922,33922],[33924,33924],[33927,33929],[33931,33932],[33934,33934],[33936,33936],[33943,33943],[33945,33945],[33948,33948],[33951,33951],[33953,33953],[33960,33960],[33967,33967],[33969,33970],[33972,33972],[33976,33979],[33981,33981],[33983,33983],[33985,33986],[33988,33988],[33991,33991],[33993,33994],[33997,33997],[33999,34001],[34003,34003],[34006,34006],[34013,34013],[34015,34016],[34018,34019],[34021,34022],[34028,34028],[34032,34032],[34044,34044],[34047,34048],[34051,34051],[34056,34056],[34058,34058],[34060,34060],[34065,34065],[34067,34067],[34071,34071],[34074,34074],[34079,34079],[34081,34081],[34091,34092],[34103,34109],[34115,34115],[34120,34122],[34134,34135],[34137,34137],[34142,34142],[34148,34148],[34152,34152],[34160,34160],[34162,34162],[34164,34164],[34169,34171],[34174,34174],[34177,34177],[34180,34181],[34183,34183],[34191,34191],[34203,34204],[34210,34210],[34212,34212],[34216,34216],[34218,34218],[34222,34224],[34227,34227],[34231,34233],[34239,34239],[34241,34241],[34249,34249],[34255,34256],[34259,34259],[34261,34261],[34268,34268],[34271,34272],[34276,34276],[34278,34278],[34280,34281],[34299,34299],[34303,34303],[34309,34309],[34321,34321],[34326,34326],[34328,34328],[34343,34343],[34345,34345],[34360,34360],[34364,34364],[34381,34388],[34394,34394],[34398,34398],[34402,34402],[34404,34404],[34411,34412],[34414,34414],[34417,34417],[34423,34434],[34436,34436],[34438,34438],[34442,34445],[34451,34451],[34453,34453],[34460,34461],[34467,34468],[34471,34474],[34476,34476],[34479,34482],[34484,34486],[34490,34490],[34496,34496],[34499,34500],[34502,34503],[34505,34507],[34510,34513],[34516,34516],[34520,34521],[34523,34523],[34526,34527],[34532,34532],[34537,34537],[34541,34542],[34544,34548],[34552,34553],[34558,34558],[34560,34560],[34562,34563],[34567,34570],[34573,34574],[34576,34576],[34578,34579],[34581,34581],[34583,34584],[34586,34586],[34588,34588],[34590,34590],[34593,34595],[34597,34597],[34601,34601],[34606,34606],[34609,34609],[34612,34612],[34615,34615],[34619,34619],[34622,34623],[34631,34633],[34636,34636],[34638,34638],[34643,34643],[34647,34649],[34656,34656],[34659,34661],[34670,34670],[34672,34672],[34674,34674],[34676,34676],[34678,34678],[34683,34686],[34690,34691],[34693,34693],[34696,34696],[34699,34699],[34701,34701],[34707,34707],[34711,34711],[34719,34720],[34723,34723],[34728,34728],[34731,34733],[34735,34735],[34737,34737],[34739,34739],[34741,34741],[34746,34746],[34749,34749],[34752,34752],[34758,34758],[34762,34763],[34767,34767],[34769,34771],[34779,34779],[34784,34784],[34789,34789],[34794,34795],[34798,34798],[34809,34809],[34814,34814],[34819,34819],[34826,34827],[34835,34835],[34837,34838],[34843,34843],[34849,34850],[34866,34866],[34873,34873],[34876,34876],[34880,34880],[34883,34885],[34892,34894],[34898,34898],[34900,34900],[34903,34903],[34905,34905],[34912,34917],[34920,34921],[34923,34924],[34926,34926],[34928,34928],[34930,34930],[34935,34935],[34941,34943],[34945,34946],[34948,34950],[34952,34952],[34955,34955],[34957,34957],[34962,34962],[34966,34967],[34972,34972],[34978,34978],[34980,34980],[34986,34987],[34989,34989],[34991,34991],[34993,34993],[34999,34999],[35004,35004],[35009,35010],[35013,35014],[35016,35017],[35022,35022],[35026,35026],[35028,35029],[35032,35033],[35035,35035],[35039,35039],[35042,35045],[35048,35048],[35056,35057],[35059,35060],[35064,35065],[35068,35068],[35070,35070],[35074,35074],[35082,35082],[35088,35088],[35090,35091],[35093,35093],[35097,35099],[35103,35103],[35105,35105],[35109,35109],[35114,35115],[35119,35120],[35124,35124],[35126,35126],[35137,35137],[35140,35140],[35157,35157],[35162,35162],[35164,35164],[35166,35167],[35174,35174],[35179,35179],[35195,35195],[35199,35199],[35201,35201],[35203,35203],[35206,35206],[35265,35276],[35278,35282],[35286,35286],[35290,35290],[35292,35292],[35294,35295],[35299,35299],[35301,35302],[35307,35307],[35309,35309],[35311,35311],[35313,35313],[35315,35315],[35327,35328],[35332,35332],[35335,35335],[35354,35354],[35390,35390],[35400,35400],[35423,35423],[35449,35449],[35465,35466],[35475,35475],[35591,35591],[35622,35622],[35686,35686],[35692,35692],[35744,35755],[35757,35817],[35819,35848],[35850,35895],[35900,35900],[35903,35903],[35905,35905],[35910,35911],[35913,35913],[35916,35916],[35925,35925],[35930,35930],[35937,35938],[35944,35944],[35946,35947],[35950,35950],[35955,35955],[35960,35962],[35970,35970],[35973,35974],[35977,35978],[35980,35980],[35988,35988],[35992,35992],[36125,36127],[36129,36196],[36198,36199],[36202,36203],[36205,36205],[36208,36208],[36211,36215],[36225,36225],[36228,36229],[36234,36235],[36241,36241],[36244,36244],[36255,36255],[36259,36259],[36271,36271],[36273,36273],[36275,36277],[36280,36280],[36282,36282],[36284,36284],[36286,36287],[36290,36292],[36294,36294],[36299,36300],[36302,36305],[36310,36311],[36314,36315],[36317,36319],[36323,36324],[36328,36328],[36330,36332],[36335,36335],[36337,36337],[36339,36339],[36341,36347],[36349,36349],[36357,36357],[36361,36362],[36364,36364],[36367,36367],[36370,36370],[36372,36372],[36381,36383],[36386,36387],[36390,36390],[36393,36394],[36396,36396],[36398,36399],[36401,36401],[36405,36406],[36409,36410],[36413,36413],[36416,36418],[36420,36421],[36423,36427],[36432,36434],[36441,36442],[36444,36444],[36450,36450],[36454,36454],[36457,36457],[36460,36461],[36463,36464],[36466,36466],[36468,36468],[36470,36470],[36476,36479],[36481,36481],[36485,36485],[36487,36487],[36495,36496],[36500,36500],[36508,36508],[36510,36510],[36523,36524],[36527,36527],[36530,36530],[36538,36538],[36558,36558],[36710,36764],[36766,36767],[36771,36771],[36776,36777],[36779,36779],[36784,36785],[36790,36790],[36793,36793],[36797,36799],[36801,36802],[36804,36805],[36807,36808],[36814,36814],[36816,36817],[36819,36821],[36824,36825],[36827,36831],[36834,36834],[36836,36838],[36840,36843],[36845,36846],[36848,36848],[36851,36851],[36855,36858],[36861,36861],[36864,36870],[36873,36875],[36877,36877],[36879,36882],[36884,36884],[36886,36887],[36890,36891],[36893,36898],[36902,36902],[36909,36911],[36916,36918],[36920,36920],[36923,36924],[36926,36926],[36929,36930],[36932,36932],[36934,36935],[36941,36941],[36943,36947],[36951,36952],[36955,36955],[36962,36963],[36965,36965],[36968,36968],[36973,36974],[36980,36981],[36985,36985],[36989,36989],[36991,36992],[36994,36995],[37000,37000],[37003,37003],[37009,37009],[37011,37011],[37013,37013],[37015,37017],[37019,37019],[37021,37021],[37024,37027],[37030,37030],[37032,37032],[37034,37034],[37036,37036],[37038,37046],[37048,37051],[37053,37055],[37057,37057],[37059,37061],[37063,37064],[37066,37066],[37070,37073],[37075,37075],[37079,37079],[37082,37085],[37089,37090],[37092,37092],[37094,37096],[37098,37099],[37101,37101],[37103,37103],[37108,37108],[37112,37112],[37117,37120],[37122,37125],[37132,37132],[37137,37137],[37143,37146],[37148,37148],[37150,37150],[37152,37152],[37154,37155],[37163,37163],[37167,37167],[37169,37169],[37177,37177],[37186,37187],[37189,37190],[37193,37200],[37202,37202],[37207,37207],[37210,37210],[37213,37214],[37217,37222],[37225,37226],[37228,37228],[37230,37234],[37236,37242],[37245,37247],[37253,37253],[37255,37255],[37257,37257],[37259,37261],[37264,37266],[37274,37275],[37282,37283],[37288,37288],[37290,37290],[37293,37295],[37300,37301],[37306,37306],[37310,37310],[37319,37319],[37321,37322],[37324,37329],[37340,37340],[37492,37492],[37518,37518],[37550,37550],[37574,37574],[37576,37576],[37694,37694],[37738,37738],[37775,37775],[37834,37834],[37846,37846],[37950,37950],[37995,37995],[38021,38032],[38034,38086],[38088,38098],[38101,38117],[38119,38175],[38177,38262],[38271,38271],[38376,38379],[38381,38418],[38420,38426],[38428,38429],[38431,38431],[38433,38434],[38442,38442],[38446,38446],[38449,38454],[38459,38461],[38463,38464],[38466,38466],[38468,38473],[38475,38478],[38480,38481],[38484,38485],[38491,38491],[38494,38495],[38497,38498],[38500,38500],[38503,38506],[38508,38508],[38514,38514],[38516,38519],[38531,38531],[38533,38534],[38536,38536],[38539,38539],[38541,38541],[38543,38544],[38548,38548],[38551,38553],[38556,38556],[38567,38567],[38569,38569],[38576,38576],[38579,38579],[38582,38582],[38585,38586],[38588,38590],[38592,38593],[38596,38599],[38601,38602],[38604,38607],[38610,38610],[38613,38613],[38624,38624],[38632,38634],[38639,38639],[38641,38641],[38643,38643],[38646,38647],[38649,38649],[38654,38654],[38656,38657],[38660,38665],[38669,38671],[38675,38675],[38678,38678],[38684,38684],[38686,38686],[38696,38696],[38698,38698],[38701,38701],[38704,38704],[38706,38706],[38712,38713],[38718,38718],[38738,38739],[38742,38742],[38745,38745],[38747,38747],[38750,38750],[38752,38754],[38757,38757],[38761,38761],[38764,38764],[38768,38768],[38771,38772],[38774,38774],[38776,38776],[38778,38778],[38780,38781],[38783,38783],[38785,38785],[38789,38789],[38795,38795],[38797,38797],[38801,38802],[38804,38804],[38808,38808],[38816,38817],[38819,38819],[38823,38824],[38827,38831],[38834,38836],[38850,38850],[38886,38893],[38899,38899],[38901,38902],[39029,39057],[39059,39060],[39062,39074],[39076,39079],[39118,39125],[39127,39130],[39134,39135],[39143,39144],[39181,39181],[39184,39184],[39214,39214],[39252,39253],[39267,39267],[39269,39269],[39271,39293],[39295,39297],[39299,39309],[39311,39321],[39325,39326],[39333,39333],[39335,39336],[39532,39571],[39573,39592],[39600,39601],[39606,39608],[39610,39610],[39612,39612],[39616,39619],[39621,39621],[39627,39628],[39630,39630],[39633,39633],[39635,39635],[39640,39640],[39647,39647],[39649,39650],[39654,39654],[39659,39659],[39661,39661],[39663,39663],[39673,39673],[39675,39675],[39677,39677],[39683,39683],[39688,39688],[39695,39695],[39698,39699],[39704,39704],[39711,39711],[39715,39715],[39727,39727],[39730,39730],[39734,39735],[39739,39740],[39745,39753],[39755,39755],[39757,39757],[39759,39759],[39761,39761],[39764,39764],[40060,40067],[40069,40082],[40084,40164],[40479,40499],[40501,40530],[40532,40548],[40550,40564],[40574,40576],[40578,40578],[40583,40584],[40587,40587],[40593,40595],[40598,40598],[40605,40605],[40607,40607],[40614,40614],[40628,40628],[40632,40633],[40635,40635],[40637,40638],[40644,40644],[40647,40647],[40649,40649],[40653,40655],[40657,40657],[40660,40660],[40664,40664],[40667,40669],[40671,40674],[40677,40677],[40679,40679],[40681,40682],[40687,40687],[40697,40697],[40699,40700],[40702,40702],[40715,40715],[40717,40718],[40720,40720],[40722,40723],[40727,40727],[40729,40729],[40736,40736],[40738,40738],[40745,40745],[40747,40748],[40751,40751],[40753,40753],[40759,40759],[40761,40761],[40763,40763],[40765,40766],[40769,40769],[40772,40772],[40775,40775],[40777,40777],[40784,40785],[40831,40844],[40857,40859],[40863,40864],[40866,40866],[40909,40911],[65072,65103],[65281,65470],[65474,65479],[65482,65487],[65490,65495],[65498,65500],[65504,65510],[65512,65518],[131428,131428],[132726,132726],[134352,134352],[136090,136090],[136211,136211],[144843,144843],[146583,146584],[146979,146979],[149979,149979],[150141,150141],[150217,150217],[152882,152882],[152930,152930],[153000,153000],[155351,155351],[156193,156193],[156813,156813],[157302,157302],[157564,157564],[158556,158556],[158753,158753],[163833,163833],[164872,164872],[165496,165496],[165525,165525],[165856,165856],[166729,166729],[166983,166983],[166991,166991],[166993,166993],[166996,166996],[167577,167577],[171902,171902],[171907,171907],[171916,171916],[174045,174045],[174331,174331],[174359,174359],[174640,174640],[174646,174646],[174680,174680],[176034,176034],[176423,176424],[176439,176440],[176621,176621],[176896,176896],[176995,176995],[177007,177007],[177010,177010],[177021,177021],[177156,177156],[177168,177168],[177171,177171],[177249,177249],[177383,177383],[177391,177391],[177398,177398],[177401,177401],[177421,177422],[177462,177462],[177582,177583],[177587,177587],[177639,177639],[177652,177652],[177692,177693],[177702,177704],[177706,177706],[177708,177708],[177813,177814],[177837,177837],[177901,177901],[178089,178089],[178117,178117],[178150,178150],[178169,178169],[178172,178172],[178182,178182],[178186,178186],[178204,178204],[178360,178360],[178887,178887],[179039,179039],[179042,179042],[179068,179068],[179075,179075],[179227,179227],[179575,179575],[179591,179591],[179703,179703],[179753,179753],[180265,180266],[180393,180393],[180426,180426],[180693,180693],[180697,180697],[180729,180729],[180860,180860],[180872,180872],[180900,180900],[181015,181015],[181083,181083],[181089,181089],[181092,181092],[181384,181384],[181396,181396],[181399,181399],[181570,181570],[181779,181779],[181784,181784],[181793,181793],[181801,181801],[181803,181805],[181807,181807],[181826,181826],[181834,181835],[182060,182060],[182063,182063],[182175,182175],[182209,182209],[182269,182269],[182489,182489],[182494,182494],[182497,182497],[182515,182515],[182535,182535],[182538,182538],[182557,182557],[182786,182786],[182798,182798],[182909,182909],[182953,182953],[183081,183081],[183085,183086],[183089,183089],[183096,183097],[183099,183099],[183103,183103],[183105,183105],[183114,183114],[183118,183118],[183130,183131],[183140,183140],[183145,183145],[183148,183148],[183151,183151],[183155,183155],[183158,183158],[183160,183160],[183164,183164],[183217,183217],[183231,183232],[183246,183246],[183382,183382],[183391,183391],[183541,183542],[183549,183549],[183551,183551],[183554,183555],[183562,183562],[183691,183691],[183693,183693],[183695,183696],[183711,183712],[183720,183720],[183725,183726],[183765,183765],[183832,183832],[183834,183834],[183843,183843],[183846,183846],[183850,183850],[183932,183932],[183944,183944],[183955,183955]]},"700":{"file":"FreeVideoKaiSC-Medium.woff2","sha256":"fb84533d155484c8838229cd50175d4141104d504fe68e6847b7de5e3ba4d72f","ranges":[[32,126],[160,172],[174,383],[462,462],[464,464],[466,466],[468,468],[470,470],[472,472],[474,474],[476,476],[711,711],[713,713],[913,929],[931,937],[945,961],[963,969],[1025,1025],[1040,1103],[1105,1105],[8192,8203],[8208,8214],[8216,8226],[8229,8231],[8240,8247],[8249,8255],[8258,8258],[8260,8260],[8263,8265],[8273,8274],[8282,8282],[8285,8285],[8451,8451],[8470,8470],[8544,8555],[8592,8601],[8630,8633],[8644,8646],[8651,8656],[8658,8658],[8660,8660],[8678,8682],[8693,8693],[8712,8712],[8715,8715],[8719,8719],[8721,8721],[8730,8730],[8733,8734],[8736,8736],[8741,8741],[8743,8747],[8750,8750],[8756,8759],[8764,8765],[8773,8773],[8776,8776],[8780,8780],[8800,8801],[8804,8805],[8814,8815],[8857,8857],[8869,8869],[8978,8978],[9312,9547],[9632,9643],[9649,9651],[9654,9655],[9660,9661],[9664,9665],[9670,9671],[9673,9676],[9678,9683],[9698,9702],[9711,9711],[9723,9724],[9728,9731],[9733,9734],[9737,9737],[9742,9746],[9750,9751],[9756,9759],[9775,9783],[9792,9794],[9824,9839],[9842,9853],[9862,9871],[9888,9888],[9898,9899],[9917,9918],[9931,9931],[9956,9959],[12288,12333],[12336,12336],[12339,12351],[12353,12438],[12441,12543],[12549,12585],[12832,12841],[13383,13383],[13386,13386],[13678,13678],[13838,13838],[13901,13901],[13912,13912],[13926,13926],[14019,14019],[14042,14042],[14073,14073],[14275,14275],[14343,14343],[14355,14355],[14616,14616],[14660,14660],[14800,14801],[14815,14815],[15088,15088],[15114,15114],[15118,15118],[15130,15130],[15182,15182],[15189,15189],[15294,15294],[15360,15360],[15559,15559],[15576,15576],[15578,15578],[15636,15636],[15696,15696],[15794,15794],[15878,15878],[15884,15884],[16004,16004],[16108,16108],[16207,16207],[16352,16352],[16470,16470],[16558,16558],[16581,16581],[16590,16590],[16735,16735],[17209,17209],[17283,17283],[17302,17302],[17373,17373],[17377,17377],[17394,17394],[17411,17411],[17622,17622],[17627,17627],[17640,17640],[17643,17644],[17878,17878],[17883,17883],[17898,17898],[17908,17908],[18211,18211],[18265,18265],[18618,18618],[18620,18620],[18648,18648],[18813,18813],[18819,18819],[19615,19616],[19618,19618],[19731,19737],[19886,19886],[19968,19969],[19971,19971],[19975,19985],[19987,19990],[19992,19998],[20002,20002],[20004,20005],[20007,20008],[20010,20013],[20016,20016],[20018,20018],[20020,20020],[20022,20022],[20024,20027],[20029,20031],[20034,20035],[20037,20037],[20039,20041],[20043,20048],[20050,20052],[20054,20054],[20056,20057],[20060,20065],[20070,20070],[20073,20073],[20080,20081],[20083,20083],[20088,20088],[20094,20094],[20102,20102],[20104,20105],[20107,20111],[20113,20117],[20120,20120],[20122,20123],[20127,20130],[20132,20137],[20139,20142],[20146,20147],[20149,20150],[20152,20155],[20159,20167],[20169,20171],[20173,20174],[20177,20177],[20179,20185],[20189,20191],[20193,20193],[20195,20197],[20200,20200],[20202,20204],[20208,20208],[20210,20211],[20213,20215],[20219,20219],[20221,20221],[20223,20223],[20225,20225],[20232,20235],[20237,20241],[20247,20251],[20254,20256],[20258,20263],[20266,20267],[20269,20269],[20271,20272],[20274,20274],[20276,20276],[20278,20278],[20280,20280],[20282,20282],[20284,20286],[20289,20289],[20291,20291],[20294,20294],[20301,20305],[20307,20307],[20309,20320],[20323,20325],[20327,20327],[20329,20329],[20332,20332],[20335,20336],[20339,20340],[20342,20342],[20344,20344],[20346,20351],[20353,20356],[20360,20361],[20363,20363],[20365,20365],[20367,20367],[20369,20369],[20372,20372],[20375,20376],[20379,20379],[20381,20381],[20384,20384],[20387,20387],[20389,20394],[20396,20396],[20398,20399],[20404,20405],[20409,20409],[20415,20415],[20419,20421],[20426,20426],[20429,20433],[20439,20442],[20444,20447],[20449,20449],[20451,20451],[20454,20454],[20456,20459],[20461,20463],[20465,20465],[20467,20467],[20469,20470],[20472,20472],[20474,20474],[20478,20478],[20492,20493],[20495,20495],[20498,20501],[20504,20506],[20508,20508],[20510,20511],[20513,20513],[20517,20522],[20524,20526],[20532,20532],[20538,20540],[20542,20542],[20545,20545],[20547,20547],[20551,20552],[20556,20556],[20558,20559],[20563,20563],[20565,20565],[20570,20570],[20572,20572],[20577,20577],[20581,20581],[20588,20589],[20592,20592],[20594,20594],[20598,20599],[20603,20603],[20606,20608],[20611,20611],[20613,20613],[20616,20617],[20621,20621],[20626,20626],[20629,20629],[20643,20643],[20645,20645],[20647,20649],[20652,20652],[20658,20658],[20666,20667],[20679,20679],[20686,20687],[20692,20692],[20694,20694],[20698,20698],[20710,20711],[20716,20718],[20720,20720],[20723,20723],[20725,20725],[20731,20731],[20742,20743],[20747,20747],[20754,20754],[20769,20769],[20774,20774],[20787,20788],[20799,20801],[20803,20806],[20808,20809],[20811,20811],[20813,20813],[20817,20817],[20820,20822],[20826,20826],[20828,20828],[20834,20834],[20837,20837],[20840,20840],[20843,20846],[20848,20849],[20851,20857],[20859,20861],[20864,20866],[20869,20869],[20872,20873],[20876,20877],[20879,20879],[20882,20882],[20884,20887],[20889,20889],[20891,20892],[20896,20896],[20898,20898],[20900,20901],[20907,20908],[20910,20915],[20917,20919],[20923,20925],[20928,20928],[20932,20932],[20934,20935],[20937,20937],[20939,20940],[20943,20943],[20945,20945],[20947,20947],[20952,20952],[20955,20955],[20957,20957],[20960,20961],[20964,20964],[20971,20971],[20973,20973],[20975,20976],[20979,20979],[20981,20982],[20984,20989],[20991,20995],[20998,21000],[21002,21002],[21005,21006],[21009,21010],[21014,21019],[21021,21021],[21024,21024],[21028,21028],[21032,21033],[21035,21038],[21040,21040],[21043,21043],[21046,21051],[21053,21053],[21055,21059],[21061,21061],[21066,21069],[21072,21073],[21076,21078],[21084,21084],[21086,21087],[21089,21089],[21093,21093],[21095,21095],[21097,21098],[21103,21103],[21106,21106],[21117,21117],[21119,21119],[21121,21122],[21124,21124],[21128,21128],[21136,21136],[21139,21139],[21147,21147],[21149,21155],[21160,21165],[21169,21171],[21180,21180],[21182,21183],[21187,21187],[21191,21191],[21193,21193],[21195,21195],[21197,21197],[21200,21200],[21202,21202],[21204,21204],[21206,21206],[21208,21208],[21210,21210],[21215,21216],[21220,21220],[21232,21232],[21241,21242],[21246,21248],[21253,21254],[21256,21256],[21261,21261],[21263,21264],[21269,21271],[21273,21274],[21276,21277],[21280,21281],[21283,21283],[21286,21286],[21290,21290],[21294,21294],[21305,21308],[21310,21311],[21313,21313],[21315,21315],[21317,21317],[21319,21322],[21326,21327],[21329,21331],[21333,21335],[21338,21338],[21340,21340],[21342,21348],[21350,21351],[21353,21353],[21355,21356],[21358,21361],[21363,21365],[21367,21368],[21370,21370],[21375,21375],[21378,21378],[21380,21382],[21385,21385],[21387,21389],[21397,21398],[21400,21400],[21402,21402],[21405,21405],[21407,21407],[21410,21411],[21413,21414],[21416,21417],[21422,21422],[21430,21430],[21435,21435],[21438,21439],[21441,21442],[21446,21453],[21457,21457],[21460,21467],[21471,21472],[21475,21478],[21480,21491],[21493,21497],[21499,21501],[21505,21505],[21507,21508],[21510,21510],[21512,21514],[21516,21523],[21525,21527],[21531,21531],[21533,21537],[21539,21539],[21542,21545],[21547,21551],[21553,21554],[21556,21557],[21560,21561],[21563,21566],[21568,21568],[21571,21571],[21574,21576],[21578,21579],[21584,21584],[21586,21593],[21595,21596],[21602,21604],[21606,21606],[21608,21608],[21617,21619],[21621,21624],[21627,21629],[21632,21632],[21634,21634],[21636,21636],[21638,21639],[21641,21641],[21643,21648],[21650,21650],[21652,21654],[21657,21659],[21661,21661],[21665,21665],[21667,21677],[21679,21679],[21681,21681],[21683,21684],[21688,21688],[21690,21691],[21693,21693],[21695,21700],[21702,21705],[21708,21717],[21719,21719],[21721,21722],[21724,21727],[21730,21730],[21733,21738],[21741,21742],[21745,21747],[21754,21754],[21756,21757],[21759,21759],[21761,21761],[21766,21767],[21769,21769],[21775,21777],[21780,21780],[21787,21787],[21789,21789],[21792,21792],[21794,21796],[21799,21799],[21802,21802],[21804,21804],[21806,21809],[21811,21811],[21813,21813],[21815,21815],[21820,21820],[21822,21823],[21825,21825],[21827,21828],[21830,21830],[21833,21834],[21840,21840],[21845,21846],[21852,21852],[21857,21857],[21860,21863],[21866,21870],[21872,21872],[21876,21880],[21883,21884],[21886,21886],[21888,21892],[21894,21899],[21903,21903],[21905,21905],[21908,21908],[21912,21913],[21916,21917],[21919,21919],[21924,21924],[21927,21927],[21937,21937],[21939,21939],[21941,21941],[21943,21943],[21945,21945],[21947,21947],[21949,21950],[21956,21957],[21961,21961],[21964,21965],[21968,21972],[21974,21974],[21980,21983],[21985,21985],[21987,21990],[21992,21992],[21994,21996],[21999,21999],[22002,22003],[22005,22005],[22007,22007],[22013,22014],[22016,22017],[22024,22025],[22028,22028],[22030,22031],[22040,22040],[22042,22043],[22046,22047],[22049,22049],[22051,22052],[22055,22055],[22060,22061],[22065,22066],[22068,22068],[22070,22070],[22073,22073],[22075,22075],[22079,22080],[22082,22082],[22087,22087],[22092,22094],[22100,22100],[22103,22105],[22108,22108],[22114,22114],[22116,22116],[22120,22124],[22129,22129],[22134,22134],[22139,22140],[22148,22150],[22158,22159],[22163,22163],[22170,22170],[22179,22179],[22189,22189],[22191,22191],[22199,22199],[22204,22204],[22218,22218],[22228,22228],[22231,22231],[22234,22235],[22237,22242],[22244,22244],[22251,22251],[22253,22253],[22256,22257],[22260,22261],[22263,22263],[22265,22266],[22269,22271],[22275,22276],[22278,22278],[22280,22282],[22284,22284],[22288,22288],[22297,22297],[22300,22300],[22303,22303],[22306,22307],[22312,22320],[22322,22323],[22329,22331],[22334,22334],[22336,22336],[22338,22338],[22343,22343],[22345,22354],[22359,22359],[22362,22369],[22372,22374],[22376,22381],[22383,22384],[22387,22387],[22390,22391],[22395,22397],[22402,22406],[22408,22408],[22411,22415],[22418,22419],[22421,22421],[22425,22427],[22430,22436],[22438,22439],[22441,22441],[22443,22443],[22445,22447],[22449,22450],[22452,22453],[22456,22456],[22458,22458],[22462,22463],[22466,22467],[22470,22471],[22475,22476],[22478,22479],[22482,22482],[22484,22485],[22487,22490],[22493,22493],[22495,22496],[22500,22500],[22506,22507],[22509,22509],[22511,22511],[22516,22517],[22520,22522],[22524,22525],[22528,22528],[22530,22531],[22534,22535],[22537,22537],[22539,22542],[22544,22545],[22549,22549],[22553,22553],[22558,22558],[22560,22561],[22564,22564],[22567,22568],[22570,22570],[22576,22576],[22578,22578],[22581,22581],[22588,22590],[22596,22598],[22604,22605],[22609,22609],[22612,22612],[22616,22616],[22621,22622],[22629,22629],[22635,22636],[22641,22641],[22654,22654],[22656,22657],[22659,22659],[22661,22661],[22664,22665],[22672,22672],[22674,22675],[22677,22677],[22680,22682],[22686,22687],[22689,22689],[22691,22691],[22694,22694],[22696,22697],[22716,22716],[22721,22721],[22725,22725],[22737,22737],[22741,22741],[22756,22756],[22763,22764],[22766,22766],[22768,22768],[22771,22771],[22774,22774],[22776,22777],[22786,22786],[22788,22788],[22791,22791],[22797,22797],[22799,22800],[22804,22806],[22809,22810],[22812,22812],[22815,22815],[22820,22821],[22823,22823],[22825,22831],[22833,22833],[22836,22836],[22839,22842],[22844,22844],[22849,22850],[22852,22852],[22855,22857],[22859,22859],[22862,22863],[22865,22865],[22867,22872],[22874,22874],[22880,22882],[22885,22885],[22893,22893],[22899,22900],[22902,22902],[22904,22905],[22909,22909],[22913,22916],[22918,22920],[22922,22922],[22925,22925],[22930,22931],[22934,22937],[22942,22942],[22947,22949],[22951,22955],[22957,22959],[22962,22962],[22969,22969],[22971,22971],[22974,22974],[22982,22982],[22984,22984],[22986,22987],[22992,22996],[22999,23000],[23002,23002],[23004,23006],[23011,23013],[23016,23016],[23020,23020],[23022,23022],[23025,23025],[23030,23030],[23033,23033],[23035,23035],[23037,23037],[23039,23041],[23043,23049],[23052,23052],[23057,23057],[23059,23059],[23064,23064],[23068,23068],[23071,23072],[23075,23075],[23077,23077],[23081,23081],[23089,23090],[23092,23094],[23100,23100],[23104,23104],[23110,23110],[23113,23114],[23116,23117],[23125,23125],[23128,23128],[23130,23130],[23134,23134],[23136,23136],[23138,23138],[23140,23140],[23143,23143],[23146,23147],[23155,23159],[23162,23164],[23167,23167],[23170,23170],[23172,23172],[23174,23174],[23186,23187],[23190,23190],[23194,23195],[23198,23198],[23210,23210],[23213,23213],[23217,23219],[23221,23221],[23224,23224],[23230,23230],[23233,23234],[23236,23236],[23241,23241],[23244,23244],[23250,23250],[23252,23254],[23256,23256],[23258,23258],[23260,23260],[23264,23265],[23267,23267],[23270,23270],[23273,23275],[23277,23277],[23281,23281],[23293,23293],[23305,23305],[23318,23319],[23323,23323],[23333,23333],[23340,23340],[23346,23346],[23348,23348],[23351,23351],[23359,23360],[23365,23365],[23376,23377],[23379,23389],[23391,23391],[23394,23398],[23401,23402],[23404,23404],[23408,23409],[23411,23411],[23413,23413],[23418,23418],[23421,23421],[23424,23425],[23427,23429],[23431,23433],[23435,23436],[23439,23439],[23443,23443],[23445,23445],[23447,23454],[23456,23463],[23466,23468],[23472,23472],[23475,23478],[23480,23481],[23485,23487],[23489,23490],[23492,23495],[23500,23500],[23504,23504],[23506,23507],[23517,23519],[23521,23521],[23524,23525],[23528,23528],[23534,23534],[23536,23536],[23544,23548],[23551,23551],[23553,23553],[23556,23556],[23558,23558],[23561,23562],[23567,23567],[23569,23569],[23572,23574],[23576,23576],[23578,23578],[23580,23581],[23586,23586],[23588,23589],[23591,23592],[23594,23594],[23596,23596],[23601,23601],[23604,23604],[23608,23619],[23621,23621],[23624,23627],[23630,23633],[23637,23637],[23641,23641],[23646,23646],[23648,23649],[23651,23651],[23653,23654],[23662,23663],[23665,23665],[23673,23674],[23676,23676],[23678,23679],[23681,23682],[23688,23688],[23690,23690],[23692,23693],[23696,23697],[23700,23700],[23702,23708],[23710,23710],[23712,23712],[23714,23715],[23720,23721],[23723,23725],[23729,23729],[23731,23731],[23733,23733],[23735,23736],[23741,23741],[23743,23743],[23745,23748],[23755,23755],[23762,23762],[23767,23769],[23771,23771],[23777,23777],[23779,23784],[23786,23786],[23789,23789],[23792,23793],[23803,23803],[23807,23812],[23814,23815],[23820,23820],[23822,23822],[23826,23826],[23828,23828],[23830,23830],[23834,23835],[23838,23839],[23841,23841],[23844,23844],[23846,23847],[23849,23849],[23853,23854],[23860,23860],[23862,23862],[23869,23871],[23873,23873],[23877,23877],[23879,23879],[23882,23884],[23886,23886],[23894,23894],[23896,23896],[23898,23899],[23901,23901],[23913,23913],[23915,23916],[23919,23919],[23922,23922],[23924,23924],[23938,23938],[23941,23941],[23949,23949],[23954,23955],[23961,23961],[23965,23965],[23967,23967],[23974,23974],[23986,23986],[23991,23991],[24005,24005],[24007,24007],[24009,24009],[24013,24013],[24027,24027],[24029,24030],[24033,24034],[24037,24041],[24043,24043],[24046,24047],[24049,24052],[24055,24055],[24061,24062],[24065,24067],[24069,24070],[24072,24072],[24076,24076],[24079,24081],[24084,24086],[24088,24093],[24097,24097],[24102,24104],[24109,24110],[24113,24113],[24119,24120],[24123,24125],[24130,24130],[24132,24133],[24140,24140],[24148,24150],[24155,24155],[24158,24158],[24161,24162],[24170,24170],[24178,24180],[24182,24182],[24184,24184],[24186,24189],[24191,24192],[24196,24196],[24198,24199],[24202,24203],[24207,24209],[24211,24215],[24217,24218],[24220,24220],[24222,24224],[24228,24231],[24237,24237],[24241,24241],[24243,24243],[24245,24249],[24252,24252],[24254,24254],[24262,24262],[24265,24267],[24273,24275],[24278,24278],[24281,24281],[24283,24283],[24296,24296],[24298,24298],[24308,24308],[24310,24311],[24314,24314],[24318,24324],[24326,24328],[24330,24331],[24335,24335],[24337,24337],[24339,24339],[24341,24341],[24343,24344],[24347,24347],[24351,24352],[24354,24354],[24357,24362],[24365,24365],[24367,24367],[24369,24369],[24374,24374],[24376,24378],[24380,24380],[24384,24384],[24400,24400],[24402,24403],[24405,24408],[24413,24413],[24415,24415],[24417,24418],[24420,24420],[24422,24423],[24425,24426],[24428,24429],[24432,24433],[24435,24435],[24439,24439],[24441,24441],[24443,24444],[24448,24450],[24452,24453],[24455,24460],[24464,24464],[24466,24466],[24469,24469],[24471,24473],[24475,24476],[24481,24481],[24488,24488],[24490,24490],[24493,24494],[24501,24501],[24503,24503],[24508,24509],[24515,24518],[24521,24521],[24524,24525],[24527,24530],[24534,24537],[24541,24542],[24544,24545],[24548,24548],[24551,24551],[24554,24555],[24557,24558],[24561,24561],[24563,24563],[24565,24565],[24568,24568],[24570,24571],[24573,24582],[24586,24586],[24589,24591],[24594,24594],[24596,24598],[24601,24601],[24603,24605],[24608,24609],[24613,24619],[24623,24623],[24629,24629],[24635,24636],[24639,24639],[24641,24643],[24651,24651],[24653,24653],[24656,24656],[24658,24661],[24665,24666],[24669,24669],[24674,24676],[24679,24685],[24687,24688],[24691,24691],[24694,24694],[24696,24701],[24703,24703],[24707,24708],[24710,24710],[24712,24713],[24716,24717],[24722,24722],[24724,24724],[24726,24726],[24730,24731],[24733,24733],[24735,24736],[24738,24739],[24742,24742],[24744,24744],[24747,24749],[24751,24754],[24756,24756],[24760,24760],[24763,24764],[24773,24775],[24778,24779],[24782,24782],[24785,24785],[24788,24789],[24792,24797],[24799,24800],[24806,24809],[24811,24816],[24819,24820],[24822,24822],[24825,24826],[24832,24833],[24835,24835],[24838,24838],[24840,24841],[24845,24848],[24852,24853],[24858,24858],[24863,24864],[24867,24868],[24870,24871],[24875,24875],[24877,24877],[24895,24895],[24902,24902],[24904,24904],[24906,24906],[24908,24908],[24910,24910],[24913,24913],[24917,24917],[24925,24925],[24930,24930],[24933,24933],[24935,24936],[24940,24941],[24944,24944],[24949,24949],[24951,24951],[24971,24971],[24974,24974],[24980,24981],[24985,24985],[24989,24989],[24999,25001],[25004,25005],[25015,25015],[25018,25018],[25022,25022],[25026,25026],[25032,25032],[25034,25035],[25041,25042],[25044,25044],[25062,25062],[25077,25077],[25087,25087],[25094,25094],[25096,25096],[25098,25106],[25109,25112],[25114,25115],[25119,25119],[25121,25125],[25130,25130],[25132,25134],[25139,25140],[25143,25143],[25149,25155],[25157,25166],[25169,25172],[25176,25176],[25179,25179],[25182,25182],[25187,25187],[25190,25191],[25193,25200],[25203,25203],[25206,25206],[25209,25210],[25212,25216],[25219,25220],[25225,25226],[25233,25240],[25242,25243],[25247,25250],[25252,25253],[25256,25256],[25259,25260],[25265,25265],[25269,25269],[25273,25273],[25275,25277],[25279,25279],[25282,25290],[25292,25294],[25296,25296],[25298,25300],[25302,25308],[25311,25311],[25314,25321],[25324,25327],[25329,25329],[25331,25332],[25334,25335],[25340,25343],[25345,25346],[25351,25353],[25358,25358],[25361,25361],[25363,25363],[25366,25366],[25370,25371],[25373,25382],[25384,25384],[25386,25387],[25391,25391],[25394,25394],[25401,25402],[25405,25405],[25410,25411],[25413,25414],[25417,25417],[25419,25424],[25429,25429],[25438,25439],[25441,25443],[25447,25447],[25449,25449],[25453,25455],[25457,25457],[25462,25463],[25466,25467],[25469,25469],[25472,25472],[25474,25474],[25479,25482],[25484,25484],[25486,25488],[25490,25490],[25494,25494],[25496,25496],[25502,25502],[25504,25504],[25506,25507],[25509,25509],[25511,25514],[25516,25518],[25520,25520],[25523,25524],[25527,25528],[25530,25530],[25532,25532],[25534,25534],[25540,25540],[25542,25542],[25545,25545],[25549,25552],[25554,25554],[25557,25558],[25566,25566],[25568,25569],[25571,25571],[25577,25578],[25581,25581],[25586,25588],[25590,25590],[25592,25592],[25597,25597],[25599,25602],[25605,25605],[25611,25612],[25615,25616],[25618,25620],[25627,25628],[25630,25630],[25632,25633],[25638,25638],[25642,25642],[25644,25645],[25652,25652],[25658,25658],[25661,25661],[25663,25663],[25665,25665],[25668,25672],[25674,25674],[25679,25679],[25682,25682],[25684,25684],[25688,25688],[25691,25691],[25694,25694],[25703,25703],[25705,25705],[25709,25709],[25716,25716],[25720,25722],[25725,25725],[25730,25730],[25732,25733],[25735,25735],[25745,25746],[25749,25750],[25753,25753],[25758,25758],[25764,25764],[25769,25769],[25772,25774],[25776,25776],[25781,25781],[25783,25784],[25786,25786],[25788,25788],[25792,25792],[25794,25794],[25797,25797],[25805,25806],[25808,25808],[25810,25810],[25815,25816],[25822,25822],[25826,25826],[25828,25828],[25830,25830],[25855,25856],[25865,25865],[25874,25874],[25880,25880],[25893,25893],[25899,25899],[25902,25903],[25908,25910],[25912,25913],[25915,25915],[25917,25919],[25925,25925],[25928,25929],[25932,25932],[25935,25935],[25937,25937],[25940,25942],[25945,25945],[25947,25947],[25949,25950],[25954,25955],[25958,25958],[25961,25961],[25963,25964],[25968,25968],[25970,25970],[25972,25972],[25975,25975],[25991,25991],[25995,25996],[26000,26001],[26003,26003],[26007,26007],[26009,26009],[26011,26013],[26015,26017],[26020,26021],[26023,26023],[26025,26025],[26027,26027],[26029,26029],[26031,26032],[26038,26038],[26041,26041],[26044,26045],[26049,26049],[26051,26054],[26059,26060],[26062,26064],[26066,26066],[26070,26071],[26078,26078],[26080,26080],[26082,26082],[26085,26089],[26092,26097],[26100,26104],[26106,26107],[26111,26112],[26114,26116],[26118,26122],[26124,26124],[26126,26127],[26130,26133],[26137,26137],[26141,26141],[26143,26145],[26147,26149],[26151,26152],[26154,26155],[26157,26157],[26159,26159],[26161,26161],[26163,26166],[26170,26170],[26172,26174],[26177,26177],[26179,26179],[26181,26181],[26186,26188],[26191,26192],[26194,26199],[26201,26202],[26206,26207],[26209,26210],[26212,26212],[26214,26214],[26216,26216],[26218,26219],[26222,26225],[26228,26228],[26230,26231],[26234,26234],[26238,26238],[26242,26242],[26244,26245],[26247,26247],[26252,26252],[26257,26257],[26261,26263],[26269,26269],[26279,26280],[26286,26286],[26290,26290],[26292,26294],[26297,26297],[26302,26303],[26312,26312],[26316,26316],[26329,26329],[26331,26333],[26342,26342],[26345,26345],[26352,26352],[26354,26356],[26359,26359],[26361,26361],[26364,26364],[26366,26368],[26376,26379],[26381,26381],[26383,26384],[26387,26389],[26391,26391],[26395,26395],[26397,26397],[26399,26399],[26406,26406],[26408,26408],[26410,26413],[26415,26415],[26417,26417],[26419,26421],[26424,26424],[26426,26426],[26429,26429],[26432,26432],[26434,26436],[26438,26438],[26440,26441],[26444,26444],[26446,26449],[26451,26451],[26453,26454],[26457,26457],[26460,26460],[26462,26465],[26469,26469],[26471,26474],[26477,26477],[26479,26480],[26482,26483],[26485,26485],[26487,26487],[26491,26492],[26494,26495],[26497,26497],[26500,26501],[26503,26503],[26505,26505],[26507,26507],[26509,26509],[26512,26512],[26517,26517],[26519,26520],[26522,26522],[26524,26526],[26530,26531],[26533,26533],[26535,26536],[26538,26539],[26541,26541],[26543,26544],[26546,26547],[26549,26553],[26561,26561],[26563,26564],[26568,26568],[26570,26570],[26575,26580],[26582,26582],[26584,26586],[26588,26590],[26592,26592],[26594,26594],[26597,26597],[26601,26601],[26604,26604],[26607,26609],[26611,26612],[26615,26615],[26621,26621],[26623,26624],[26629,26629],[26631,26636],[26638,26643],[26646,26647],[26653,26653],[26655,26655],[26657,26657],[26665,26666],[26674,26676],[26679,26681],[26683,26686],[26688,26694],[26696,26698],[26700,26700],[26702,26702],[26704,26705],[26707,26709],[26720,26729],[26731,26731],[26735,26735],[26738,26738],[26740,26740],[26742,26743],[26745,26745],[26753,26753],[26755,26755],[26757,26758],[26764,26764],[26767,26767],[26771,26771],[26775,26775],[26784,26784],[26786,26787],[26790,26792],[26797,26797],[26799,26800],[26803,26805],[26812,26818],[26825,26825],[26827,26827],[26829,26829],[26832,26832],[26834,26835],[26837,26837],[26840,26840],[26842,26842],[26848,26848],[26851,26852],[26856,26856],[26858,26860],[26862,26862],[26864,26865],[26869,26869],[26873,26877],[26880,26881],[26885,26886],[26891,26891],[26893,26894],[26896,26899],[26911,26912],[26916,26916],[26922,26922],[26925,26925],[26928,26928],[26932,26932],[26936,26937],[26941,26941],[26943,26943],[26946,26946],[26962,26962],[26964,26964],[26967,26967],[26969,26970],[26973,26974],[26976,26976],[26979,26979],[26982,26982],[26985,26987],[26990,26991],[26993,26993],[26999,27001],[27004,27004],[27008,27008],[27010,27017],[27021,27021],[27025,27025],[27028,27030],[27032,27032],[27035,27036],[27047,27048],[27051,27051],[27053,27053],[27056,27057],[27060,27060],[27063,27063],[27067,27067],[27073,27073],[27075,27075],[27082,27082],[27084,27084],[27086,27086],[27088,27088],[27092,27092],[27098,27100],[27103,27104],[27117,27117],[27121,27122],[27133,27133],[27135,27135],[27146,27146],[27159,27160],[27167,27167],[27169,27169],[27176,27176],[27178,27178],[27183,27183],[27185,27185],[27189,27189],[27197,27198],[27204,27204],[27207,27207],[27216,27217],[27224,27225],[27227,27227],[27230,27230],[27233,27233],[27237,27238],[27249,27249],[27257,27257],[27260,27260],[27264,27264],[27268,27268],[27278,27278],[27280,27281],[27287,27287],[27294,27294],[27296,27296],[27305,27305],[27307,27308],[27334,27334],[27394,27394],[27424,27428],[27431,27431],[27442,27442],[27447,27451],[27454,27454],[27459,27459],[27461,27463],[27465,27465],[27468,27468],[27481,27481],[27490,27495],[27498,27498],[27513,27513],[27515,27516],[27521,27524],[27526,27527],[27529,27531],[27533,27533],[27538,27539],[27542,27542],[27546,27547],[27553,27553],[27555,27555],[27562,27562],[27571,27573],[27575,27575],[27583,27583],[27585,27586],[27589,27589],[27595,27597],[27599,27600],[27602,27607],[27609,27609],[27611,27611],[27617,27617],[27626,27627],[27631,27631],[27635,27635],[27637,27637],[27641,27641],[27645,27645],[27653,27655],[27661,27661],[27663,27665],[27667,27670],[27672,27675],[27679,27679],[27681,27682],[27684,27684],[27686,27690],[27694,27696],[27698,27698],[27700,27701],[27704,27704],[27709,27714],[27718,27723],[27728,27728],[27732,27733],[27735,27735],[27739,27745],[27748,27748],[27751,27755],[27757,27757],[27760,27760],[27762,27762],[27764,27764],[27766,27766],[27769,27769],[27773,27774],[27777,27785],[27788,27788],[27791,27792],[27795,27796],[27800,27803],[27807,27807],[27809,27809],[27811,27819],[27821,27822],[27825,27827],[27832,27839],[27842,27845],[27847,27847],[27849,27850],[27852,27852],[27856,27856],[27859,27863],[27865,27868],[27870,27870],[27872,27875],[27877,27877],[27880,27880],[27882,27883],[27886,27889],[27891,27891],[27893,27896],[27898,27902],[27905,27905],[27908,27908],[27911,27912],[27915,27916],[27918,27918],[27921,27923],[27927,27931],[27934,27934],[27938,27939],[27941,27941],[27943,27944],[27946,27947],[27949,27950],[27953,27957],[27960,27967],[27969,27969],[27971,27971],[27973,27979],[27981,27989],[27993,27996],[27998,28001],[28003,28003],[28005,28006],[28009,28010],[28012,28016],[28018,28018],[28020,28020],[28023,28024],[28028,28028],[28034,28034],[28036,28037],[28040,28041],[28044,28046],[28048,28049],[28051,28053],[28056,28056],[28059,28059],[28061,28068],[28070,28075],[28078,28079],[28082,28082],[28084,28085],[28088,28088],[28095,28096],[28100,28103],[28107,28108],[28111,28111],[28113,28113],[28118,28118],[28120,28121],[28124,28129],[28132,28132],[28134,28134],[28139,28140],[28142,28143],[28145,28145],[28147,28148],[28151,28151],[28153,28153],[28155,28156],[28165,28165],[28170,28170],[28172,28174],[28176,28177],[28180,28180],[28182,28183],[28186,28186],[28189,28189],[28191,28193],[28195,28197],[28201,28201],[28203,28203],[28205,28205],[28207,28208],[28210,28210],[28212,28212],[28216,28216],[28218,28218],[28220,28220],[28227,28228],[28233,28233],[28237,28238],[28241,28241],[28243,28244],[28246,28246],[28248,28248],[28251,28253],[28255,28255],[28259,28259],[28267,28267],[28270,28270],[28274,28274],[28276,28276],[28286,28287],[28289,28289],[28291,28291],[28293,28295],[28297,28297],[28301,28301],[28303,28304],[28312,28312],[28314,28314],[28316,28316],[28318,28320],[28322,28322],[28325,28327],[28330,28330],[28335,28335],[28337,28338],[28340,28343],[28345,28347],[28349,28349],[28353,28355],[28358,28359],[28361,28361],[28363,28363],[28365,28365],[28367,28367],[28369,28369],[28371,28373],[28375,28376],[28378,28378],[28382,28386],[28388,28395],[28404,28404],[28409,28409],[28418,28418],[28422,28422],[28424,28425],[28427,28427],[28431,28431],[28435,28438],[28448,28448],[28452,28452],[28454,28454],[28457,28459],[28461,28461],[28463,28463],[28465,28465],[28467,28468],[28470,28471],[28473,28473],[28475,28476],[28478,28478],[28486,28487],[28491,28491],[28493,28493],[28495,28495],[28502,28502],[28504,28504],[28508,28508],[28510,28511],[28514,28514],[28518,28518],[28521,28521],[28525,28526],[28530,28530],[28532,28533],[28536,28536],[28538,28538],[28540,28542],[28546,28546],[28548,28548],[28552,28553],[28556,28558],[28571,28572],[28577,28577],[28581,28581],[28583,28583],[28586,28586],[28589,28589],[28595,28596],[28598,28598],[28601,28601],[28604,28605],[28608,28608],[28610,28610],[28617,28617],[28619,28619],[28625,28626],[28638,28638],[28640,28641],[28649,28649],[28654,28655],[28684,28685],[28689,28689],[28692,28692],[28698,28699],[28707,28707],[28721,28721],[28725,28725],[28729,28729],[28732,28732],[28744,28744],[28748,28748],[28751,28751],[28766,28766],[28779,28781],[28783,28784],[28789,28790],[28792,28792],[28796,28796],[28798,28800],[28805,28806],[28809,28810],[28812,28812],[28814,28814],[28818,28818],[28820,28822],[28824,28825],[28828,28829],[28831,28831],[28835,28835],[28843,28847],[28849,28849],[28851,28851],[28855,28857],[28859,28861],[28864,28867],[28872,28872],[28874,28874],[28884,28884],[28888,28889],[28891,28893],[28895,28896],[28900,28900],[28902,28905],[28907,28909],[28911,28911],[28918,28919],[28921,28923],[28925,28925],[28934,28934],[28937,28938],[28940,28940],[28944,28944],[28947,28947],[28949,28954],[28956,28956],[28958,28958],[28966,28966],[28975,28977],[28982,28982],[28993,28993],[28995,28995],[28997,28997],[29002,29004],[29006,29006],[29011,29011],[29020,29020],[29022,29023],[29028,29028],[29030,29032],[29038,29038],[29042,29044],[29048,29048],[29050,29050],[29053,29053],[29060,29060],[29063,29063],[29066,29066],[29071,29071],[29076,29076],[29080,29081],[29083,29084],[29087,29088],[29093,29093],[29096,29096],[29100,29100],[29107,29107],[29109,29109],[29113,29113],[29115,29115],[29123,29123],[29130,29131],[29134,29135],[29140,29141],[29146,29146],[29152,29152],[29157,29157],[29159,29159],[29166,29166],[29177,29177],[29190,29191],[29204,29204],[29210,29210],[29213,29213],[29215,29215],[29224,29224],[29226,29226],[29228,29228],[29232,29233],[29237,29241],[29243,29243],[29245,29245],[29247,29247],[29249,29250],[29255,29256],[29260,29261],[29266,29266],[29270,29270],[29273,29275],[29277,29277],[29279,29279],[29281,29282],[29284,29287],[29289,29289],[29294,29295],[29298,29298],[29301,29301],[29305,29307],[29310,29313],[29316,29316],[29319,29319],[29322,29323],[29325,29325],[29327,29327],[29330,29330],[29343,29343],[29352,29352],[29356,29357],[29359,29360],[29364,29364],[29366,29369],[29377,29380],[29384,29385],[29389,29390],[29392,29392],[29394,29394],[29399,29399],[29401,29401],[29405,29406],[29408,29409],[29416,29417],[29420,29428],[29431,29432],[29434,29436],[29441,29441],[29443,29444],[29447,29447],[29450,29450],[29454,29454],[29459,29459],[29461,29463],[29467,29470],[29473,29474],[29477,29477],[29481,29484],[29486,29489],[29492,29492],[29495,29498],[29502,29503],[29517,29517],[29520,29520],[29522,29522],[29527,29527],[29536,29536],[29548,29549],[29551,29551],[29556,29556],[29566,29566],[29571,29572],[29575,29575],[29577,29577],[29579,29579],[29582,29582],[29585,29587],[29589,29590],[29592,29595],[29598,29602],[29604,29606],[29609,29609],[29611,29611],[29613,29619],[29622,29623],[29625,29628],[29631,29632],[29634,29634],[29637,29637],[29639,29645],[29647,29650],[29653,29654],[29657,29657],[29659,29659],[29661,29662],[29664,29664],[29666,29667],[29669,29671],[29673,29675],[29677,29677],[29680,29680],[29682,29682],[29685,29685],[29687,29690],[29693,29693],[29696,29696],[29699,29706],[29710,29712],[29716,29716],[29722,29723],[29727,29727],[29729,29730],[29732,29734],[29736,29736],[29738,29744],[29746,29750],[29756,29756],[29760,29766],[29777,29777],[29779,29783],[29785,29791],[29794,29794],[29799,29800],[29804,29805],[29808,29809],[29811,29811],[29814,29815],[29822,29822],[29824,29825],[29827,29827],[29830,29832],[29835,29835],[29838,29838],[29840,29840],[29842,29842],[29848,29848],[29852,29852],[29854,29856],[29861,29861],[29863,29866],[29868,29868],[29870,29870],[29873,29874],[29882,29882],[29888,29888],[29906,29906],[29910,29910],[29912,29912],[29916,29916],[29918,29918],[29920,29920],[29922,29924],[29926,29926],[29934,29935],[29940,29940],[29942,29943],[29947,29947],[29951,29951],[29956,29956],[29965,29965],[29967,29967],[29969,29969],[29971,29971],[29975,29978],[29980,29980],[29983,29983],[29985,29985],[29989,29990],[29992,29997],[29999,30003],[30005,30005],[30007,30008],[30010,30011],[30014,30014],[30016,30016],[30021,30021],[30024,30024],[30027,30028],[30030,30031],[30036,30036],[30038,30038],[30041,30044],[30052,30054],[30058,30058],[30060,30060],[30063,30063],[30066,30066],[30068,30068],[30072,30073],[30079,30079],[30081,30081],[30083,30083],[30086,30086],[30091,30091],[30093,30093],[30095,30098],[30100,30100],[30102,30103],[30105,30106],[30109,30109],[30111,30117],[30123,30133],[30136,30137],[30140,30142],[30146,30149],[30151,30154],[30157,30157],[30162,30166],[30168,30168],[30171,30171],[30174,30174],[30178,30180],[30182,30184],[30186,30187],[30192,30193],[30196,30196],[30201,30201],[30204,30204],[30207,30209],[30211,30211],[30213,30214],[30218,30218],[30220,30220],[30224,30224],[30229,30229],[30231,30233],[30235,30235],[30239,30240],[30242,30242],[30244,30246],[30249,30251],[30253,30253],[30256,30256],[30259,30261],[30264,30264],[30268,30268],[30270,30272],[30275,30275],[30284,30285],[30292,30292],[30294,30295],[30300,30300],[30302,30302],[30307,30307],[30315,30315],[30319,30319],[30328,30328],[30331,30331],[30333,30335],[30338,30338],[30340,30340],[30342,30344],[30347,30347],[30350,30350],[30353,30353],[30355,30355],[30357,30358],[30361,30361],[30363,30363],[30366,30366],[30372,30372],[30374,30374],[30381,30382],[30385,30386],[30388,30388],[30399,30399],[30402,30402],[30405,30406],[30408,30410],[30413,30418],[30420,30420],[30422,30424],[30427,30427],[30431,30431],[30437,30438],[30446,30447],[30449,30450],[30452,30452],[30455,30457],[30460,30460],[30462,30462],[30465,30465],[30468,30468],[30471,30475],[30477,30477],[30489,30490],[30495,30496],[30498,30498],[30502,30502],[30504,30505],[30508,30509],[30511,30511],[30517,30520],[30522,30522],[30524,30524],[30528,30529],[30531,30532],[30535,30535],[30542,30542],[30544,30545],[30554,30555],[30561,30563],[30565,30566],[30568,30568],[30571,30572],[30585,30585],[30589,30592],[30596,30597],[30603,30606],[30609,30610],[30623,30624],[30626,30626],[30629,30629],[30631,30631],[30633,30637],[30640,30640],[30643,30643],[30645,30645],[30651,30651],[30653,30653],[30655,30655],[30669,30669],[30679,30679],[30683,30684],[30686,30686],[30690,30691],[30693,30693],[30695,30695],[30697,30697],[30699,30702],[30704,30704],[30707,30707],[30710,30710],[30712,30712],[30715,30722],[30724,30724],[30726,30726],[30729,30729],[30732,30733],[30737,30738],[30740,30740],[30742,30744],[30746,30746],[30748,30749],[30751,30752],[30755,30755],[30757,30759],[30761,30761],[30763,30766],[30768,30768],[30772,30773],[30775,30780],[30782,30782],[30784,30785],[30789,30789],[30791,30791],[30794,30794],[30796,30798],[30800,30800],[30802,30802],[30804,30807],[30809,30810],[30813,30813],[30826,30830],[30839,30839],[30844,30844],[30847,30847],[30851,30851],[30855,30857],[30860,30863],[30865,30865],[30867,30867],[30871,30872],[30874,30876],[30879,30879],[30881,30881],[30883,30883],[30885,30885],[30887,30888],[30896,30900],[30902,30902],[30905,30905],[30910,30910],[30913,30913],[30917,30917],[30921,30923],[30927,30928],[30932,30933],[30937,30937],[30940,30940],[30945,30945],[30952,30952],[30956,30956],[30962,30962],[30964,30964],[30967,30967],[30969,30971],[30977,30977],[30981,30981],[30988,30988],[30995,30995],[31006,31006],[31012,31012],[31028,31029],[31034,31036],[31038,31038],[31040,31041],[31043,31043],[31046,31051],[31054,31056],[31059,31059],[31061,31063],[31066,31072],[31074,31074],[31077,31077],[31079,31080],[31085,31085],[31087,31087],[31090,31090],[31095,31096],[31098,31098],[31100,31100],[31102,31102],[31104,31105],[31108,31109],[31114,31115],[31119,31119],[31122,31122],[31124,31124],[31128,31128],[31130,31131],[31140,31140],[31143,31143],[31155,31155],[31161,31163],[31165,31166],[31168,31169],[31171,31171],[31174,31174],[31177,31177],[31179,31179],[31181,31181],[31185,31186],[31189,31189],[31192,31192],[31199,31199],[31203,31204],[31206,31207],[31209,31209],[31211,31213],[31215,31216],[31224,31224],[31227,31227],[31229,31230],[31232,31232],[31234,31235],[31238,31238],[31243,31246],[31249,31249],[31252,31252],[31255,31255],[31257,31258],[31262,31262],[31264,31264],[31267,31267],[31283,31283],[31287,31287],[31289,31289],[31291,31293],[31295,31295],[31300,31300],[31302,31302],[31313,31313],[31319,31319],[31321,31321],[31324,31324],[31327,31327],[31344,31344],[31348,31348],[31350,31354],[31359,31361],[31363,31366],[31368,31368],[31370,31370],[31373,31374],[31377,31378],[31381,31384],[31388,31389],[31391,31392],[31395,31395],[31397,31398],[31400,31400],[31404,31405],[31411,31411],[31416,31416],[31423,31423],[31435,31435],[31441,31441],[31446,31446],[31448,31449],[31454,31456],[31459,31459],[31461,31462],[31467,31467],[31469,31469],[31471,31471],[31481,31482],[31485,31485],[31487,31487],[31491,31492],[31494,31494],[31496,31496],[31498,31499],[31503,31503],[31505,31505],[31508,31509],[31513,31513],[31515,31515],[31518,31518],[31520,31520],[31524,31526],[31528,31528],[31530,31532],[31534,31535],[31537,31537],[31539,31539],[31544,31544],[31546,31546],[31548,31548],[31550,31550],[31552,31552],[31557,31557],[31559,31559],[31561,31561],[31563,31564],[31567,31570],[31572,31572],[31574,31574],[31576,31576],[31578,31581],[31584,31584],[31586,31586],[31588,31590],[31598,31598],[31601,31602],[31605,31607],[31609,31609],[31611,31612],[31614,31614],[31616,31616],[31621,31621],[31629,31629],[31632,31632],[31635,31639],[31644,31645],[31649,31650],[31654,31661],[31665,31665],[31668,31668],[31672,31672],[31681,31681],[31686,31687],[31692,31692],[31697,31697],[31699,31699],[31705,31706],[31709,31709],[31713,31713],[31717,31718],[31722,31722],[31726,31727],[31729,31729],[31735,31735],[31740,31740],[31742,31742],[31747,31747],[31751,31751],[31753,31753],[31755,31756],[31759,31759],[31765,31766],[31773,31773],[31775,31776],[31782,31783],[31786,31786],[31792,31792],[31800,31800],[31807,31809],[31821,31821],[31845,31845],[31859,31860],[31867,31869],[31881,31881],[31889,31890],[31893,31893],[31895,31896],[31900,31903],[31906,31906],[31908,31909],[31914,31914],[31918,31918],[31921,31923],[31929,31929],[31932,31935],[31937,31937],[31941,31941],[31943,31944],[31946,31946],[31948,31949],[31954,31954],[31957,31959],[31961,31961],[31964,31964],[31967,31968],[31976,31976],[31983,31983],[31989,31989],[31992,31992],[31995,31995],[32010,32010],[32032,32032],[32034,32034],[32039,32039],[32043,32043],[32047,32047],[32092,32092],[32110,32110],[32119,32119],[32166,32166],[32174,32174],[32288,32288],[32290,32290],[32315,32315],[32321,32321],[32324,32324],[32327,32327],[32386,32386],[32411,32411],[32415,32491],[32493,32566],[32568,32568],[32570,32570],[32578,32578],[32580,32581],[32589,32589],[32592,32593],[32596,32597],[32599,32600],[32602,32602],[32607,32607],[32609,32610],[32616,32618],[32622,32622],[32625,32626],[32628,32628],[32630,32630],[32633,32633],[32637,32638],[32641,32641],[32650,32650],[32652,32652],[32654,32654],[32657,32657],[32659,32662],[32666,32666],[32669,32671],[32673,32673],[32676,32676],[32679,32679],[32687,32690],[32696,32697],[32700,32701],[32703,32707],[32709,32709],[32712,32712],[32714,32714],[32716,32716],[32718,32718],[32724,32725],[32728,32731],[32735,32737],[32741,32742],[32745,32745],[32750,32753],[32755,32755],[32759,32759],[32763,32764],[32766,32766],[32768,32769],[32771,32775],[32779,32781],[32783,32786],[32788,32793],[32796,32796],[32800,32800],[32802,32802],[32804,32810],[32816,32817],[32819,32819],[32821,32824],[32827,32827],[32829,32829],[32831,32831],[32834,32835],[32838,32838],[32842,32845],[32850,32850],[32852,32852],[32856,32856],[32858,32858],[32873,32874],[32881,32881],[32895,32896],[32899,32900],[32902,32903],[32905,32905],[32907,32908],[32915,32915],[32918,32918],[32920,32920],[32922,32925],[32927,32930],[32932,32933],[32937,32939],[32941,32943],[32945,32946],[32948,32948],[32951,32952],[32954,32954],[32956,32964],[32966,32966],[32968,32968],[32972,32974],[32982,32983],[32985,32990],[32992,32993],[32995,32997],[32999,33005],[33007,33012],[33014,33014],[33016,33016],[33018,33018],[33020,33021],[33026,33026],[33030,33030],[33033,33034],[33037,33044],[33046,33046],[33048,33048],[33050,33050],[33054,33055],[33065,33065],[33068,33068],[33071,33071],[33073,33074],[33078,33078],[33080,33080],[33086,33087],[33094,33094],[33096,33096],[33098,33100],[33104,33109],[33112,33114],[33120,33120],[33125,33125],[33127,33129],[33133,33137],[33140,33140],[33145,33152],[33154,33154],[33160,33160],[33162,33162],[33167,33167],[33169,33169],[33176,33177],[33179,33181],[33187,33187],[33190,33190],[33192,33192],[33194,33194],[33203,33203],[33210,33211],[33216,33219],[33222,33222],[33226,33226],[33228,33228],[33233,33233],[33244,33244],[33251,33251],[33255,33255],[33258,33258],[33260,33261],[33267,33268],[33275,33276],[33278,33278],[33280,33282],[33284,33286],[33292,33293],[33296,33296],[33298,33298],[33300,33300],[33307,33308],[33310,33315],[33317,33317],[33320,33320],[33322,33325],[33327,33337],[33339,33339],[33342,33342],[33348,33349],[33351,33351],[33353,33353],[33355,33355],[33358,33359],[33368,33368],[33370,33370],[33375,33375],[33384,33384],[33390,33392],[33394,33396],[33401,33402],[33405,33407],[33410,33412],[33416,33416],[33418,33419],[33421,33423],[33425,33426],[33431,33433],[33436,33437],[33439,33441],[33443,33446],[33448,33457],[33459,33460],[33463,33465],[33468,33470],[33473,33473],[33476,33476],[33479,33487],[33489,33493],[33495,33496],[33499,33500],[33502,33505],[33507,33511],[33515,33515],[33519,33519],[33521,33521],[33524,33524],[33527,33527],[33529,33529],[33531,33531],[33534,33534],[33536,33545],[33547,33548],[33550,33551],[33553,33553],[33555,33557],[33559,33559],[33562,33565],[33575,33576],[33579,33581],[33583,33583],[33585,33585],[33587,33590],[33592,33594],[33596,33597],[33600,33601],[33603,33604],[33606,33607],[33609,33609],[33615,33620],[33622,33622],[33625,33628],[33630,33633],[33635,33647],[33655,33656],[33659,33661],[33669,33670],[33673,33673],[33678,33678],[33682,33683],[33688,33689],[33691,33694],[33696,33696],[33704,33707],[33712,33716],[33718,33722],[33724,33725],[33727,33730],[33733,33733],[33735,33735],[33737,33738],[33740,33741],[33743,33743],[33748,33748],[33750,33750],[33752,33752],[33756,33757],[33759,33761],[33765,33765],[33769,33770],[33776,33778],[33784,33785],[33788,33789],[33793,33793],[33795,33796],[33798,33798],[33803,33807],[33809,33809],[33816,33816],[33818,33818],[33820,33821],[33827,33833],[33841,33841],[33843,33843],[33848,33849],[33852,33853],[33862,33862],[33870,33870],[33873,33873],[33878,33879],[33881,33884],[33889,33889],[33891,33891],[33897,33897],[33899,33901],[33904,33905],[33907,33910],[33912,33912],[33914,33914],[33922,33922],[33924,33924],[33927,33929],[33931,33932],[33934,33934],[33936,33936],[33943,33943],[33945,33945],[33948,33948],[33951,33951],[33953,33953],[33960,33960],[33967,33967],[33969,33970],[33972,33972],[33976,33979],[33981,33981],[33983,33983],[33985,33986],[33988,33988],[33991,33991],[33993,33994],[33997,33997],[33999,34001],[34003,34003],[34006,34006],[34013,34013],[34015,34016],[34018,34019],[34021,34022],[34028,34028],[34032,34032],[34044,34044],[34047,34048],[34051,34051],[34056,34056],[34058,34058],[34060,34060],[34065,34065],[34067,34067],[34071,34071],[34074,34074],[34079,34079],[34081,34081],[34091,34092],[34103,34109],[34115,34115],[34120,34122],[34134,34135],[34137,34137],[34142,34142],[34148,34148],[34152,34152],[34160,34160],[34162,34162],[34164,34164],[34169,34171],[34174,34174],[34177,34177],[34180,34181],[34183,34183],[34191,34191],[34203,34204],[34210,34210],[34212,34212],[34216,34216],[34218,34218],[34222,34224],[34227,34227],[34231,34233],[34239,34239],[34241,34241],[34249,34249],[34255,34256],[34259,34259],[34261,34261],[34268,34268],[34271,34272],[34276,34276],[34278,34278],[34280,34281],[34299,34299],[34303,34303],[34309,34309],[34321,34321],[34326,34326],[34328,34328],[34343,34343],[34345,34345],[34360,34360],[34364,34364],[34381,34388],[34394,34394],[34398,34398],[34402,34402],[34404,34404],[34411,34412],[34414,34414],[34417,34417],[34423,34434],[34436,34436],[34438,34438],[34442,34445],[34451,34451],[34453,34453],[34460,34461],[34467,34468],[34471,34474],[34476,34476],[34479,34482],[34484,34486],[34490,34490],[34496,34496],[34499,34500],[34502,34503],[34505,34507],[34510,34513],[34516,34516],[34520,34521],[34523,34523],[34526,34527],[34532,34532],[34537,34537],[34541,34542],[34544,34548],[34552,34553],[34558,34558],[34560,34560],[34562,34563],[34567,34570],[34573,34574],[34576,34576],[34578,34579],[34581,34581],[34583,34584],[34586,34586],[34588,34588],[34590,34590],[34593,34595],[34597,34597],[34601,34601],[34606,34606],[34609,34609],[34612,34612],[34615,34615],[34619,34619],[34622,34623],[34631,34633],[34636,34636],[34638,34638],[34643,34643],[34647,34649],[34656,34656],[34659,34661],[34670,34670],[34672,34672],[34674,34674],[34676,34676],[34678,34678],[34683,34686],[34690,34691],[34693,34693],[34696,34696],[34699,34699],[34701,34701],[34707,34707],[34711,34711],[34719,34720],[34723,34723],[34728,34728],[34731,34733],[34735,34735],[34737,34737],[34739,34739],[34741,34741],[34746,34746],[34749,34749],[34752,34752],[34758,34758],[34762,34763],[34767,34767],[34769,34771],[34779,34779],[34784,34784],[34789,34789],[34794,34795],[34798,34798],[34809,34809],[34814,34814],[34819,34819],[34826,34827],[34835,34835],[34837,34838],[34843,34843],[34849,34850],[34866,34866],[34873,34873],[34876,34876],[34880,34880],[34883,34885],[34892,34894],[34898,34898],[34900,34900],[34903,34903],[34905,34905],[34912,34917],[34920,34921],[34923,34924],[34926,34926],[34928,34928],[34930,34930],[34935,34935],[34941,34943],[34945,34946],[34948,34950],[34952,34952],[34955,34955],[34957,34957],[34962,34962],[34966,34967],[34972,34972],[34978,34978],[34980,34980],[34986,34987],[34989,34989],[34991,34991],[34993,34993],[34999,34999],[35004,35004],[35009,35010],[35013,35014],[35016,35017],[35022,35022],[35026,35026],[35028,35029],[35032,35033],[35035,35035],[35039,35039],[35042,35045],[35048,35048],[35056,35057],[35059,35060],[35064,35065],[35068,35068],[35070,35070],[35074,35074],[35082,35082],[35088,35088],[35090,35091],[35093,35093],[35097,35099],[35103,35103],[35105,35105],[35109,35109],[35114,35115],[35119,35120],[35124,35124],[35126,35126],[35137,35137],[35140,35140],[35157,35157],[35162,35162],[35164,35164],[35166,35167],[35174,35174],[35179,35179],[35195,35195],[35199,35199],[35201,35201],[35203,35203],[35206,35206],[35265,35276],[35278,35282],[35286,35286],[35290,35290],[35292,35292],[35294,35295],[35299,35299],[35301,35302],[35307,35307],[35309,35309],[35311,35311],[35313,35313],[35315,35315],[35327,35328],[35332,35332],[35335,35335],[35354,35354],[35390,35390],[35400,35400],[35423,35423],[35449,35449],[35465,35466],[35475,35475],[35591,35591],[35622,35622],[35686,35686],[35692,35692],[35744,35755],[35757,35817],[35819,35848],[35850,35895],[35900,35900],[35903,35903],[35905,35905],[35910,35911],[35913,35913],[35916,35916],[35925,35925],[35930,35930],[35937,35938],[35944,35944],[35946,35947],[35950,35950],[35955,35955],[35960,35962],[35970,35970],[35973,35974],[35977,35978],[35980,35980],[35988,35988],[35992,35992],[36125,36127],[36129,36196],[36198,36199],[36202,36203],[36205,36205],[36208,36208],[36211,36215],[36225,36225],[36228,36229],[36234,36235],[36241,36241],[36244,36244],[36255,36255],[36259,36259],[36271,36271],[36273,36273],[36275,36277],[36280,36280],[36282,36282],[36284,36284],[36286,36287],[36290,36292],[36294,36294],[36299,36300],[36302,36305],[36310,36311],[36314,36315],[36317,36319],[36323,36324],[36328,36328],[36330,36332],[36335,36335],[36337,36337],[36339,36339],[36341,36347],[36349,36349],[36357,36357],[36361,36362],[36364,36364],[36367,36367],[36370,36370],[36372,36372],[36381,36383],[36386,36387],[36390,36390],[36393,36394],[36396,36396],[36398,36399],[36401,36401],[36405,36406],[36409,36410],[36413,36413],[36416,36418],[36420,36421],[36423,36427],[36432,36434],[36441,36442],[36444,36444],[36450,36450],[36454,36454],[36457,36457],[36460,36461],[36463,36464],[36466,36466],[36468,36468],[36470,36470],[36476,36479],[36481,36481],[36485,36485],[36487,36487],[36495,36496],[36500,36500],[36508,36508],[36510,36510],[36523,36524],[36527,36527],[36530,36530],[36538,36538],[36558,36558],[36710,36764],[36766,36767],[36771,36771],[36776,36777],[36779,36779],[36784,36785],[36790,36790],[36793,36793],[36797,36799],[36801,36802],[36804,36805],[36807,36808],[36814,36814],[36816,36817],[36819,36821],[36824,36825],[36827,36831],[36834,36834],[36836,36838],[36840,36843],[36845,36846],[36848,36848],[36851,36851],[36855,36858],[36861,36861],[36864,36870],[36873,36875],[36877,36877],[36879,36882],[36884,36884],[36886,36887],[36890,36891],[36893,36898],[36902,36902],[36909,36911],[36916,36918],[36920,36920],[36923,36924],[36926,36926],[36929,36930],[36932,36932],[36934,36935],[36941,36941],[36943,36947],[36951,36952],[36955,36955],[36962,36963],[36965,36965],[36968,36968],[36973,36974],[36980,36981],[36985,36985],[36989,36989],[36991,36992],[36994,36995],[37000,37000],[37003,37003],[37009,37009],[37011,37011],[37013,37013],[37015,37017],[37019,37019],[37021,37021],[37024,37027],[37030,37030],[37032,37032],[37034,37034],[37036,37036],[37038,37046],[37048,37051],[37053,37055],[37057,37057],[37059,37061],[37063,37064],[37066,37066],[37070,37073],[37075,37075],[37079,37079],[37082,37085],[37089,37090],[37092,37092],[37094,37096],[37098,37099],[37101,37101],[37103,37103],[37108,37108],[37112,37112],[37117,37120],[37122,37125],[37132,37132],[37137,37137],[37143,37146],[37148,37148],[37150,37150],[37152,37152],[37154,37155],[37163,37163],[37167,37167],[37169,37169],[37177,37177],[37186,37187],[37189,37190],[37193,37200],[37202,37202],[37207,37207],[37210,37210],[37213,37214],[37217,37222],[37225,37226],[37228,37228],[37230,37234],[37236,37242],[37245,37247],[37253,37253],[37255,37255],[37257,37257],[37259,37261],[37264,37266],[37274,37275],[37282,37283],[37288,37288],[37290,37290],[37293,37295],[37300,37301],[37306,37306],[37310,37310],[37319,37319],[37321,37322],[37324,37329],[37340,37340],[37492,37492],[37518,37518],[37550,37550],[37574,37574],[37576,37576],[37694,37694],[37738,37738],[37775,37775],[37834,37834],[37846,37846],[37950,37950],[37995,37995],[38021,38032],[38034,38086],[38088,38098],[38101,38117],[38119,38175],[38177,38262],[38271,38271],[38376,38379],[38381,38418],[38420,38426],[38428,38429],[38431,38431],[38433,38434],[38442,38442],[38446,38446],[38449,38454],[38459,38461],[38463,38464],[38466,38466],[38468,38473],[38475,38478],[38480,38481],[38484,38485],[38491,38491],[38494,38495],[38497,38498],[38500,38500],[38503,38506],[38508,38508],[38514,38514],[38516,38519],[38531,38531],[38533,38534],[38536,38536],[38539,38539],[38541,38541],[38543,38544],[38548,38548],[38551,38553],[38556,38556],[38567,38567],[38569,38569],[38576,38576],[38579,38579],[38582,38582],[38585,38586],[38588,38590],[38592,38593],[38596,38599],[38601,38602],[38604,38607],[38610,38610],[38613,38613],[38624,38624],[38632,38634],[38639,38639],[38641,38641],[38643,38643],[38646,38647],[38649,38649],[38654,38654],[38656,38657],[38660,38665],[38669,38671],[38675,38675],[38678,38678],[38684,38684],[38686,38686],[38696,38696],[38698,38698],[38701,38701],[38704,38704],[38706,38706],[38712,38713],[38718,38718],[38738,38739],[38742,38742],[38745,38745],[38747,38747],[38750,38750],[38752,38754],[38757,38757],[38761,38761],[38764,38764],[38768,38768],[38771,38772],[38774,38774],[38776,38776],[38778,38778],[38780,38781],[38783,38783],[38785,38785],[38789,38789],[38795,38795],[38797,38797],[38801,38802],[38804,38804],[38808,38808],[38816,38817],[38819,38819],[38823,38824],[38827,38831],[38834,38836],[38850,38850],[38886,38893],[38899,38899],[38901,38902],[39029,39057],[39059,39060],[39062,39074],[39076,39079],[39118,39125],[39127,39130],[39134,39135],[39143,39144],[39181,39181],[39184,39184],[39214,39214],[39252,39253],[39267,39267],[39269,39269],[39271,39293],[39295,39297],[39299,39309],[39311,39321],[39325,39326],[39333,39333],[39335,39336],[39532,39571],[39573,39592],[39600,39601],[39606,39608],[39610,39610],[39612,39612],[39616,39619],[39621,39621],[39627,39628],[39630,39630],[39633,39633],[39635,39635],[39640,39640],[39647,39647],[39649,39650],[39654,39654],[39659,39659],[39661,39661],[39663,39663],[39673,39673],[39675,39675],[39677,39677],[39683,39683],[39688,39688],[39695,39695],[39698,39699],[39704,39704],[39711,39711],[39715,39715],[39727,39727],[39730,39730],[39734,39735],[39739,39740],[39745,39753],[39755,39755],[39757,39757],[39759,39759],[39761,39761],[39764,39764],[40060,40067],[40069,40082],[40084,40164],[40479,40499],[40501,40530],[40532,40548],[40550,40564],[40574,40576],[40578,40578],[40583,40584],[40587,40587],[40593,40595],[40598,40598],[40605,40605],[40607,40607],[40614,40614],[40628,40628],[40632,40633],[40635,40635],[40637,40638],[40644,40644],[40647,40647],[40649,40649],[40653,40655],[40657,40657],[40660,40660],[40664,40664],[40667,40669],[40671,40674],[40677,40677],[40679,40679],[40681,40682],[40687,40687],[40697,40697],[40699,40700],[40702,40702],[40715,40715],[40717,40718],[40720,40720],[40722,40723],[40727,40727],[40729,40729],[40736,40736],[40738,40738],[40745,40745],[40747,40748],[40751,40751],[40753,40753],[40759,40759],[40761,40761],[40763,40763],[40765,40766],[40769,40769],[40772,40772],[40775,40775],[40777,40777],[40784,40785],[40831,40844],[40857,40859],[40863,40864],[40866,40866],[40909,40911],[65072,65103],[65281,65470],[65474,65479],[65482,65487],[65490,65495],[65498,65500],[65504,65510],[65512,65518],[131428,131428],[132726,132726],[134352,134352],[136090,136090],[136211,136211],[144843,144843],[146583,146584],[146979,146979],[149979,149979],[150141,150141],[150217,150217],[152882,152882],[152930,152930],[153000,153000],[155351,155351],[156193,156193],[156813,156813],[157302,157302],[157564,157564],[158556,158556],[158753,158753],[163833,163833],[164872,164872],[165496,165496],[165525,165525],[165856,165856],[166729,166729],[166983,166983],[166991,166991],[166993,166993],[166996,166996],[167577,167577],[171902,171902],[171907,171907],[171916,171916],[174045,174045],[174331,174331],[174359,174359],[174640,174640],[174646,174646],[174680,174680],[176034,176034],[176423,176424],[176439,176440],[176621,176621],[176896,176896],[176995,176995],[177007,177007],[177010,177010],[177021,177021],[177156,177156],[177168,177168],[177171,177171],[177249,177249],[177383,177383],[177391,177391],[177398,177398],[177401,177401],[177421,177422],[177462,177462],[177582,177583],[177587,177587],[177639,177639],[177652,177652],[177692,177693],[177702,177704],[177706,177706],[177708,177708],[177813,177814],[177837,177837],[177901,177901],[178089,178089],[178117,178117],[178150,178150],[178169,178169],[178172,178172],[178182,178182],[178186,178186],[178204,178204],[178360,178360],[178887,178887],[179039,179039],[179042,179042],[179068,179068],[179075,179075],[179227,179227],[179575,179575],[179591,179591],[179703,179703],[179753,179753],[180265,180266],[180393,180393],[180426,180426],[180693,180693],[180697,180697],[180729,180729],[180860,180860],[180872,180872],[180900,180900],[181015,181015],[181083,181083],[181089,181089],[181092,181092],[181384,181384],[181396,181396],[181399,181399],[181570,181570],[181779,181779],[181784,181784],[181793,181793],[181801,181801],[181803,181805],[181807,181807],[181826,181826],[181834,181835],[182060,182060],[182063,182063],[182175,182175],[182209,182209],[182269,182269],[182489,182489],[182494,182494],[182497,182497],[182515,182515],[182535,182535],[182538,182538],[182557,182557],[182786,182786],[182798,182798],[182909,182909],[182953,182953],[183081,183081],[183085,183086],[183089,183089],[183096,183097],[183099,183099],[183103,183103],[183105,183105],[183114,183114],[183118,183118],[183130,183131],[183140,183140],[183145,183145],[183148,183148],[183151,183151],[183155,183155],[183158,183158],[183160,183160],[183164,183164],[183217,183217],[183231,183232],[183246,183246],[183382,183382],[183391,183391],[183541,183542],[183549,183549],[183551,183551],[183554,183555],[183562,183562],[183691,183691],[183693,183693],[183695,183696],[183711,183712],[183720,183720],[183725,183726],[183765,183765],[183832,183832],[183834,183834],[183843,183843],[183846,183846],[183850,183850],[183932,183932],[183944,183944],[183955,183955]]}},"mono":{"400":{"file":"FreeVideoMonoSC-Regular.woff2","sha256":"3dfbb59675c86ea8a8306ec779b49ba85e85acc4d89d8eae3b92cdf22be11876","ranges":[[32,126],[160,259],[272,275],[282,283],[296,299],[323,324],[327,328],[332,335],[338,339],[360,365],[462,462],[464,464],[466,466],[468,468],[470,470],[472,472],[474,474],[476,476],[711,711],[713,713],[913,929],[931,937],[945,961],[963,969],[1025,1025],[1040,1103],[1105,1105],[8194,8195],[8208,8214],[8216,8218],[8220,8222],[8224,8226],[8229,8231],[8240,8240],[8242,8243],[8245,8245],[8249,8252],[8258,8258],[8263,8265],[8273,8273],[8451,8451],[8470,8470],[8544,8555],[8592,8601],[8632,8633],[8644,8646],[8651,8652],[8656,8656],[8658,8658],[8660,8660],[8678,8681],[8693,8693],[8712,8712],[8715,8715],[8719,8719],[8721,8721],[8730,8730],[8733,8734],[8736,8736],[8741,8741],[8743,8747],[8750,8750],[8756,8759],[8765,8765],[8773,8773],[8776,8776],[8780,8780],[8800,8801],[8804,8805],[8814,8815],[8857,8857],[8869,8869],[8978,8978],[9312,9547],[9632,9643],[9649,9651],[9654,9655],[9660,9661],[9664,9665],[9670,9671],[9673,9676],[9678,9683],[9698,9702],[9711,9711],[9728,9731],[9733,9734],[9737,9737],[9742,9743],[9750,9751],[9756,9759],[9775,9775],[9792,9794],[9824,9839],[9842,9853],[9888,9888],[9917,9918],[12288,12351],[12353,12438],[12441,12543],[12549,12585],[12832,12841],[13383,13383],[13386,13386],[13678,13678],[13838,13838],[13901,13901],[13912,13912],[13926,13926],[14019,14019],[14042,14042],[14073,14073],[14275,14275],[14343,14343],[14355,14355],[14616,14616],[14660,14660],[14800,14801],[14815,14815],[15088,15088],[15114,15114],[15118,15118],[15130,15130],[15182,15182],[15189,15189],[15294,15294],[15360,15360],[15559,15559],[15576,15576],[15578,15578],[15636,15636],[15696,15696],[15794,15794],[15878,15878],[15884,15884],[16004,16004],[16108,16108],[16207,16207],[16352,16352],[16470,16470],[16558,16558],[16581,16581],[16590,16590],[16735,16735],[17209,17209],[17283,17283],[17302,17302],[17373,17373],[17377,17377],[17394,17394],[17411,17411],[17622,17622],[17627,17627],[17640,17640],[17643,17644],[17878,17878],[17883,17883],[17898,17898],[17908,17908],[18211,18211],[18265,18265],[18618,18618],[18620,18620],[18648,18648],[18813,18813],[18819,18819],[19615,19616],[19618,19618],[19731,19737],[19886,19886],[19968,19969],[19971,19971],[19975,19985],[19987,19990],[19992,19998],[20002,20002],[20004,20005],[20007,20008],[20010,20013],[20016,20016],[20018,20018],[20020,20020],[20022,20022],[20024,20027],[20029,20031],[20034,20035],[20037,20037],[20039,20041],[20043,20048],[20050,20052],[20054,20054],[20056,20057],[20060,20065],[20070,20070],[20073,20073],[20080,20081],[20083,20083],[20088,20088],[20094,20094],[20102,20102],[20104,20105],[20107,20111],[20113,20117],[20120,20120],[20122,20123],[20127,20130],[20132,20137],[20139,20142],[20146,20147],[20149,20150],[20152,20155],[20159,20167],[20169,20171],[20173,20174],[20177,20177],[20179,20185],[20189,20191],[20193,20193],[20195,20197],[20200,20200],[20202,20204],[20208,20208],[20210,20211],[20213,20215],[20219,20219],[20221,20221],[20223,20223],[20225,20225],[20232,20235],[20237,20241],[20247,20251],[20254,20256],[20258,20263],[20266,20267],[20269,20269],[20271,20272],[20274,20274],[20276,20276],[20278,20278],[20280,20280],[20282,20282],[20284,20286],[20289,20289],[20291,20291],[20294,20294],[20301,20305],[20307,20307],[20309,20320],[20323,20325],[20327,20327],[20329,20329],[20332,20332],[20335,20336],[20339,20340],[20342,20342],[20344,20344],[20346,20351],[20353,20356],[20360,20361],[20363,20363],[20365,20365],[20367,20367],[20369,20369],[20372,20372],[20375,20376],[20379,20379],[20381,20381],[20384,20384],[20387,20387],[20389,20394],[20396,20396],[20398,20399],[20404,20405],[20409,20409],[20415,20415],[20419,20421],[20426,20426],[20429,20433],[20439,20442],[20444,20447],[20449,20449],[20451,20451],[20454,20454],[20456,20459],[20461,20463],[20465,20465],[20467,20467],[20469,20470],[20472,20472],[20474,20474],[20478,20478],[20492,20493],[20495,20495],[20498,20501],[20504,20506],[20508,20508],[20510,20511],[20513,20513],[20517,20522],[20524,20526],[20532,20532],[20538,20540],[20542,20542],[20545,20545],[20547,20547],[20551,20552],[20556,20556],[20558,20559],[20563,20563],[20565,20565],[20570,20570],[20572,20572],[20577,20577],[20581,20581],[20588,20589],[20592,20592],[20594,20594],[20598,20599],[20603,20603],[20606,20608],[20611,20611],[20613,20613],[20616,20617],[20621,20621],[20626,20626],[20629,20629],[20643,20643],[20645,20645],[20647,20649],[20652,20652],[20658,20658],[20666,20667],[20679,20679],[20686,20687],[20692,20692],[20694,20694],[20698,20698],[20710,20711],[20716,20718],[20720,20720],[20723,20723],[20725,20725],[20731,20731],[20742,20743],[20747,20747],[20754,20754],[20769,20769],[20774,20774],[20787,20788],[20799,20801],[20803,20806],[20808,20809],[20811,20811],[20813,20813],[20817,20817],[20820,20822],[20826,20826],[20828,20828],[20834,20834],[20837,20837],[20840,20840],[20843,20846],[20848,20849],[20851,20857],[20859,20861],[20864,20866],[20869,20869],[20872,20873],[20876,20877],[20879,20879],[20882,20882],[20884,20887],[20889,20889],[20891,20892],[20896,20896],[20898,20898],[20900,20901],[20907,20908],[20910,20915],[20917,20919],[20923,20925],[20928,20928],[20932,20932],[20934,20935],[20937,20937],[20939,20940],[20943,20943],[20945,20945],[20947,20947],[20952,20952],[20955,20955],[20957,20957],[20960,20961],[20964,20964],[20971,20971],[20973,20973],[20975,20976],[20979,20979],[20981,20982],[20984,20989],[20991,20995],[20998,21000],[21002,21002],[21005,21006],[21009,21010],[21014,21019],[21021,21021],[21024,21024],[21028,21028],[21032,21033],[21035,21038],[21040,21040],[21043,21043],[21046,21051],[21053,21053],[21055,21059],[21061,21061],[21066,21069],[21072,21073],[21076,21078],[21084,21084],[21086,21087],[21089,21089],[21093,21093],[21095,21095],[21097,21098],[21103,21103],[21106,21106],[21117,21117],[21119,21119],[21121,21122],[21124,21124],[21128,21128],[21136,21136],[21139,21139],[21147,21147],[21149,21155],[21160,21165],[21169,21171],[21180,21180],[21182,21183],[21187,21187],[21191,21191],[21193,21193],[21195,21195],[21197,21197],[21200,21200],[21202,21202],[21204,21204],[21206,21206],[21208,21208],[21210,21210],[21215,21216],[21220,21220],[21232,21232],[21241,21242],[21246,21248],[21253,21254],[21256,21256],[21261,21261],[21263,21264],[21269,21271],[21273,21274],[21276,21277],[21280,21281],[21283,21283],[21286,21286],[21290,21290],[21294,21294],[21305,21308],[21310,21311],[21313,21313],[21315,21315],[21317,21317],[21319,21322],[21326,21327],[21329,21331],[21333,21335],[21338,21338],[21340,21340],[21342,21348],[21350,21351],[21353,21353],[21355,21356],[21358,21361],[21363,21365],[21367,21368],[21370,21370],[21375,21375],[21378,21378],[21380,21382],[21385,21385],[21387,21389],[21397,21398],[21400,21400],[21402,21402],[21405,21405],[21407,21407],[21410,21411],[21413,21414],[21416,21417],[21422,21422],[21430,21430],[21435,21435],[21438,21439],[21441,21442],[21446,21453],[21457,21457],[21460,21467],[21471,21472],[21475,21478],[21480,21491],[21493,21497],[21499,21501],[21505,21505],[21507,21508],[21510,21510],[21512,21514],[21516,21523],[21525,21527],[21531,21531],[21533,21537],[21539,21539],[21542,21545],[21547,21551],[21553,21554],[21556,21557],[21560,21561],[21563,21566],[21568,21568],[21571,21571],[21574,21576],[21578,21579],[21584,21584],[21586,21593],[21595,21596],[21602,21604],[21606,21606],[21608,21608],[21617,21619],[21621,21624],[21627,21629],[21632,21632],[21634,21634],[21636,21636],[21638,21639],[21641,21641],[21643,21648],[21650,21650],[21652,21654],[21657,21659],[21661,21661],[21665,21665],[21667,21677],[21679,21679],[21681,21681],[21683,21684],[21688,21688],[21690,21691],[21693,21693],[21695,21700],[21702,21705],[21708,21717],[21719,21719],[21721,21722],[21724,21727],[21730,21730],[21733,21738],[21741,21742],[21745,21747],[21754,21754],[21756,21757],[21759,21759],[21761,21761],[21766,21767],[21769,21769],[21775,21777],[21780,21780],[21787,21787],[21789,21789],[21792,21792],[21794,21796],[21799,21799],[21802,21802],[21804,21804],[21806,21809],[21811,21811],[21813,21813],[21815,21815],[21820,21820],[21822,21823],[21825,21825],[21827,21828],[21830,21830],[21833,21834],[21840,21840],[21845,21846],[21852,21852],[21857,21857],[21860,21863],[21866,21870],[21872,21872],[21876,21880],[21883,21884],[21886,21886],[21888,21892],[21894,21899],[21903,21903],[21905,21905],[21908,21908],[21912,21913],[21916,21917],[21919,21919],[21924,21924],[21927,21927],[21937,21937],[21939,21939],[21941,21941],[21943,21943],[21945,21945],[21947,21947],[21949,21950],[21956,21957],[21961,21961],[21964,21965],[21968,21972],[21974,21974],[21980,21983],[21985,21985],[21987,21990],[21992,21992],[21994,21996],[21999,21999],[22002,22003],[22005,22005],[22007,22007],[22013,22014],[22016,22017],[22024,22025],[22028,22028],[22030,22031],[22040,22040],[22042,22043],[22046,22047],[22049,22049],[22051,22052],[22055,22055],[22060,22061],[22065,22066],[22068,22068],[22070,22070],[22073,22073],[22075,22075],[22079,22080],[22082,22082],[22087,22087],[22092,22094],[22100,22100],[22103,22105],[22108,22108],[22114,22114],[22116,22116],[22120,22124],[22129,22129],[22134,22134],[22139,22140],[22148,22150],[22158,22159],[22163,22163],[22170,22170],[22179,22179],[22189,22189],[22191,22191],[22199,22199],[22204,22204],[22218,22218],[22228,22228],[22231,22231],[22234,22235],[22237,22242],[22244,22244],[22251,22251],[22253,22253],[22256,22257],[22260,22261],[22263,22263],[22265,22266],[22269,22271],[22275,22276],[22278,22278],[22280,22282],[22284,22284],[22288,22288],[22297,22297],[22300,22300],[22303,22303],[22306,22307],[22312,22320],[22322,22323],[22329,22331],[22334,22334],[22336,22336],[22338,22338],[22343,22343],[22345,22354],[22359,22359],[22362,22369],[22372,22374],[22376,22381],[22383,22384],[22387,22387],[22390,22391],[22395,22397],[22402,22406],[22408,22408],[22411,22415],[22418,22419],[22421,22421],[22425,22427],[22430,22436],[22438,22439],[22441,22441],[22443,22443],[22445,22447],[22449,22450],[22452,22453],[22456,22456],[22458,22458],[22462,22463],[22466,22467],[22470,22471],[22475,22476],[22478,22479],[22482,22482],[22484,22485],[22487,22490],[22493,22493],[22495,22496],[22500,22500],[22506,22507],[22509,22509],[22511,22511],[22516,22517],[22520,22522],[22524,22525],[22528,22528],[22530,22531],[22534,22535],[22537,22537],[22539,22542],[22544,22545],[22549,22549],[22553,22553],[22558,22558],[22560,22561],[22564,22564],[22567,22568],[22570,22570],[22576,22576],[22578,22578],[22581,22581],[22588,22590],[22596,22598],[22604,22605],[22609,22609],[22612,22612],[22616,22616],[22621,22622],[22629,22629],[22635,22636],[22641,22641],[22654,22654],[22656,22657],[22659,22659],[22661,22661],[22664,22665],[22672,22672],[22674,22675],[22677,22677],[22680,22682],[22686,22687],[22689,22689],[22691,22691],[22694,22694],[22696,22697],[22716,22716],[22721,22721],[22725,22725],[22737,22737],[22741,22741],[22756,22756],[22763,22764],[22766,22766],[22768,22768],[22771,22771],[22774,22774],[22776,22777],[22786,22786],[22788,22788],[22791,22791],[22797,22797],[22799,22800],[22804,22806],[22809,22810],[22812,22812],[22815,22815],[22820,22821],[22823,22823],[22825,22831],[22833,22833],[22836,22836],[22839,22842],[22844,22844],[22849,22850],[22852,22852],[22855,22857],[22859,22859],[22862,22863],[22865,22865],[22867,22872],[22874,22874],[22880,22882],[22885,22885],[22893,22893],[22899,22900],[22902,22902],[22904,22905],[22909,22909],[22913,22916],[22918,22920],[22922,22922],[22925,22925],[22930,22931],[22934,22937],[22942,22942],[22947,22949],[22951,22955],[22957,22959],[22962,22962],[22969,22969],[22971,22971],[22974,22974],[22982,22982],[22984,22984],[22986,22987],[22992,22996],[22999,23000],[23002,23002],[23004,23006],[23011,23013],[23016,23016],[23020,23020],[23022,23022],[23025,23025],[23030,23030],[23033,23033],[23035,23035],[23037,23037],[23039,23041],[23043,23049],[23052,23052],[23057,23057],[23059,23059],[23064,23064],[23068,23068],[23071,23072],[23075,23075],[23077,23077],[23081,23081],[23089,23090],[23092,23094],[23100,23100],[23104,23104],[23110,23110],[23113,23114],[23116,23117],[23125,23125],[23128,23128],[23130,23130],[23134,23134],[23136,23136],[23138,23138],[23140,23140],[23143,23143],[23146,23147],[23155,23159],[23162,23164],[23167,23167],[23170,23170],[23172,23172],[23174,23174],[23186,23187],[23190,23190],[23194,23195],[23198,23198],[23210,23210],[23213,23213],[23217,23219],[23221,23221],[23224,23224],[23230,23230],[23233,23234],[23236,23236],[23241,23241],[23244,23244],[23250,23250],[23252,23254],[23256,23256],[23258,23258],[23260,23260],[23264,23265],[23267,23267],[23270,23270],[23273,23275],[23277,23277],[23281,23281],[23293,23293],[23305,23305],[23318,23319],[23323,23323],[23333,23333],[23340,23340],[23346,23346],[23348,23348],[23351,23351],[23359,23360],[23365,23365],[23376,23377],[23379,23389],[23391,23391],[23394,23398],[23401,23402],[23404,23404],[23408,23409],[23411,23411],[23413,23413],[23418,23418],[23421,23421],[23424,23425],[23427,23429],[23431,23433],[23435,23436],[23439,23439],[23443,23443],[23445,23445],[23447,23454],[23456,23463],[23466,23468],[23472,23472],[23475,23478],[23480,23481],[23485,23487],[23489,23490],[23492,23495],[23500,23500],[23504,23504],[23506,23507],[23517,23519],[23521,23521],[23524,23525],[23528,23528],[23534,23534],[23536,23536],[23544,23548],[23551,23551],[23553,23553],[23556,23556],[23558,23558],[23561,23562],[23567,23567],[23569,23569],[23572,23574],[23576,23576],[23578,23578],[23580,23581],[23586,23586],[23588,23589],[23591,23592],[23594,23594],[23596,23596],[23601,23601],[23604,23604],[23608,23619],[23621,23621],[23624,23627],[23630,23633],[23637,23637],[23641,23641],[23646,23646],[23648,23649],[23651,23651],[23653,23654],[23662,23663],[23665,23665],[23673,23674],[23676,23676],[23678,23679],[23681,23682],[23688,23688],[23690,23690],[23692,23693],[23696,23697],[23700,23700],[23702,23708],[23710,23710],[23712,23712],[23714,23715],[23720,23721],[23723,23725],[23729,23729],[23731,23731],[23733,23733],[23735,23736],[23741,23741],[23743,23743],[23745,23748],[23755,23755],[23762,23762],[23767,23769],[23771,23771],[23777,23777],[23779,23784],[23786,23786],[23789,23789],[23792,23793],[23803,23803],[23807,23812],[23814,23815],[23820,23820],[23822,23822],[23826,23826],[23828,23828],[23830,23830],[23834,23835],[23838,23839],[23841,23841],[23844,23844],[23846,23847],[23849,23849],[23853,23854],[23860,23860],[23862,23862],[23869,23871],[23873,23873],[23877,23877],[23879,23879],[23882,23884],[23886,23886],[23894,23894],[23896,23896],[23898,23899],[23901,23901],[23913,23913],[23915,23916],[23919,23919],[23922,23922],[23924,23924],[23938,23938],[23941,23941],[23949,23949],[23954,23955],[23961,23961],[23965,23965],[23967,23967],[23974,23974],[23986,23986],[23991,23991],[24005,24005],[24007,24007],[24009,24009],[24013,24013],[24027,24027],[24029,24030],[24033,24034],[24037,24041],[24043,24043],[24046,24047],[24049,24052],[24055,24055],[24061,24062],[24065,24067],[24069,24070],[24072,24072],[24076,24076],[24079,24081],[24084,24086],[24088,24093],[24097,24097],[24102,24104],[24109,24110],[24113,24113],[24119,24120],[24123,24125],[24130,24130],[24132,24133],[24140,24140],[24148,24150],[24155,24155],[24158,24158],[24161,24162],[24170,24170],[24178,24180],[24182,24182],[24184,24184],[24186,24189],[24191,24192],[24196,24196],[24198,24199],[24202,24203],[24207,24209],[24211,24215],[24217,24218],[24220,24220],[24222,24224],[24228,24231],[24237,24237],[24241,24241],[24243,24243],[24245,24249],[24252,24252],[24254,24254],[24262,24262],[24265,24267],[24273,24275],[24278,24278],[24281,24281],[24283,24283],[24296,24296],[24298,24298],[24308,24308],[24310,24311],[24314,24314],[24318,24324],[24326,24328],[24330,24331],[24335,24335],[24337,24337],[24339,24339],[24341,24341],[24343,24344],[24347,24347],[24351,24352],[24354,24354],[24357,24362],[24365,24365],[24367,24367],[24369,24369],[24374,24374],[24376,24378],[24380,24380],[24384,24384],[24400,24400],[24402,24403],[24405,24408],[24413,24413],[24415,24415],[24417,24418],[24420,24420],[24422,24423],[24425,24426],[24428,24429],[24432,24433],[24435,24435],[24439,24439],[24441,24441],[24443,24444],[24448,24450],[24452,24453],[24455,24460],[24464,24464],[24466,24466],[24469,24469],[24471,24473],[24475,24476],[24481,24481],[24488,24488],[24490,24490],[24493,24494],[24501,24501],[24503,24503],[24508,24509],[24515,24518],[24521,24521],[24524,24525],[24527,24530],[24534,24537],[24541,24542],[24544,24545],[24548,24548],[24551,24551],[24554,24555],[24557,24558],[24561,24561],[24563,24563],[24565,24565],[24568,24568],[24570,24571],[24573,24582],[24586,24586],[24589,24591],[24594,24594],[24596,24598],[24601,24601],[24603,24605],[24608,24609],[24613,24619],[24623,24623],[24629,24629],[24635,24636],[24639,24639],[24641,24643],[24651,24651],[24653,24653],[24656,24656],[24658,24661],[24665,24666],[24669,24669],[24674,24676],[24679,24685],[24687,24688],[24691,24691],[24694,24694],[24696,24701],[24703,24703],[24707,24708],[24710,24710],[24712,24713],[24716,24717],[24722,24722],[24724,24724],[24726,24726],[24730,24731],[24733,24733],[24735,24736],[24738,24739],[24742,24742],[24744,24744],[24747,24749],[24751,24754],[24756,24756],[24760,24760],[24763,24764],[24773,24775],[24778,24779],[24782,24782],[24785,24785],[24788,24789],[24792,24797],[24799,24800],[24806,24809],[24811,24816],[24819,24820],[24822,24822],[24825,24826],[24832,24833],[24835,24835],[24838,24838],[24840,24841],[24845,24848],[24852,24853],[24858,24858],[24863,24864],[24867,24868],[24870,24871],[24875,24875],[24877,24877],[24895,24895],[24902,24902],[24904,24904],[24906,24906],[24908,24908],[24910,24910],[24913,24913],[24917,24917],[24925,24925],[24930,24930],[24933,24933],[24935,24936],[24940,24941],[24944,24944],[24949,24949],[24951,24951],[24971,24971],[24974,24974],[24980,24981],[24985,24985],[24989,24989],[24999,25001],[25004,25005],[25015,25015],[25018,25018],[25022,25022],[25026,25026],[25032,25032],[25034,25035],[25041,25042],[25044,25044],[25062,25062],[25077,25077],[25087,25087],[25094,25094],[25096,25096],[25098,25106],[25109,25112],[25114,25115],[25119,25119],[25121,25125],[25130,25130],[25132,25134],[25139,25140],[25143,25143],[25149,25155],[25157,25166],[25169,25172],[25176,25176],[25179,25179],[25182,25182],[25187,25187],[25190,25191],[25193,25200],[25203,25203],[25206,25206],[25209,25210],[25212,25216],[25219,25220],[25225,25226],[25233,25240],[25242,25243],[25247,25250],[25252,25253],[25256,25256],[25259,25260],[25265,25265],[25269,25269],[25273,25273],[25275,25277],[25279,25279],[25282,25290],[25292,25294],[25296,25296],[25298,25300],[25302,25308],[25311,25311],[25314,25321],[25324,25327],[25329,25329],[25331,25332],[25334,25335],[25340,25343],[25345,25346],[25351,25353],[25358,25358],[25361,25361],[25363,25363],[25366,25366],[25370,25371],[25373,25382],[25384,25384],[25386,25387],[25391,25391],[25394,25394],[25401,25402],[25405,25405],[25410,25411],[25413,25414],[25417,25417],[25419,25424],[25429,25429],[25438,25439],[25441,25443],[25447,25447],[25449,25449],[25453,25455],[25457,25457],[25462,25463],[25466,25467],[25469,25469],[25472,25472],[25474,25474],[25479,25482],[25484,25484],[25486,25488],[25490,25490],[25494,25494],[25496,25496],[25502,25502],[25504,25504],[25506,25507],[25509,25509],[25511,25514],[25516,25518],[25520,25520],[25523,25524],[25527,25528],[25530,25530],[25532,25532],[25534,25534],[25540,25540],[25542,25542],[25545,25545],[25549,25552],[25554,25554],[25557,25558],[25566,25566],[25568,25569],[25571,25571],[25577,25578],[25581,25581],[25586,25588],[25590,25590],[25592,25592],[25597,25597],[25599,25602],[25605,25605],[25611,25612],[25615,25616],[25618,25620],[25627,25628],[25630,25630],[25632,25633],[25638,25638],[25642,25642],[25644,25645],[25652,25652],[25658,25658],[25661,25661],[25663,25663],[25665,25665],[25668,25672],[25674,25674],[25679,25679],[25682,25682],[25684,25684],[25688,25688],[25691,25691],[25694,25694],[25703,25703],[25705,25705],[25709,25709],[25716,25716],[25720,25722],[25725,25725],[25730,25730],[25732,25733],[25735,25735],[25745,25746],[25749,25750],[25753,25753],[25758,25758],[25764,25764],[25769,25769],[25772,25774],[25776,25776],[25781,25781],[25783,25784],[25786,25786],[25788,25788],[25792,25792],[25794,25794],[25797,25797],[25805,25806],[25808,25808],[25810,25810],[25815,25816],[25822,25822],[25826,25826],[25828,25828],[25830,25830],[25855,25856],[25865,25865],[25874,25874],[25880,25880],[25893,25893],[25899,25899],[25902,25903],[25908,25910],[25912,25913],[25915,25915],[25917,25919],[25925,25925],[25928,25929],[25932,25932],[25935,25935],[25937,25937],[25940,25942],[25945,25945],[25947,25947],[25949,25950],[25954,25955],[25958,25958],[25961,25961],[25963,25964],[25968,25968],[25970,25970],[25972,25972],[25975,25975],[25991,25991],[25995,25996],[26000,26001],[26003,26003],[26007,26007],[26009,26009],[26011,26013],[26015,26017],[26020,26021],[26023,26023],[26025,26025],[26027,26027],[26029,26029],[26031,26032],[26038,26038],[26041,26041],[26044,26045],[26049,26049],[26051,26054],[26059,26060],[26062,26064],[26066,26066],[26070,26071],[26078,26078],[26080,26080],[26082,26082],[26085,26089],[26092,26097],[26100,26104],[26106,26107],[26111,26112],[26114,26116],[26118,26122],[26124,26124],[26126,26127],[26130,26133],[26137,26137],[26141,26141],[26143,26145],[26147,26149],[26151,26152],[26154,26155],[26157,26157],[26159,26159],[26161,26161],[26163,26166],[26170,26170],[26172,26174],[26177,26177],[26179,26179],[26181,26181],[26186,26188],[26191,26192],[26194,26199],[26201,26202],[26206,26207],[26209,26210],[26212,26212],[26214,26214],[26216,26216],[26218,26219],[26222,26225],[26228,26228],[26230,26231],[26234,26234],[26238,26238],[26242,26242],[26244,26245],[26247,26247],[26252,26252],[26257,26257],[26261,26263],[26269,26269],[26279,26280],[26286,26286],[26290,26290],[26292,26294],[26297,26297],[26302,26303],[26312,26312],[26316,26316],[26329,26329],[26331,26333],[26342,26342],[26345,26345],[26352,26352],[26354,26356],[26359,26359],[26361,26361],[26364,26364],[26366,26368],[26376,26379],[26381,26381],[26383,26384],[26387,26389],[26391,26391],[26395,26395],[26397,26397],[26399,26399],[26406,26406],[26408,26408],[26410,26413],[26415,26415],[26417,26417],[26419,26421],[26424,26424],[26426,26426],[26429,26429],[26432,26432],[26434,26436],[26438,26438],[26440,26441],[26444,26444],[26446,26449],[26451,26451],[26453,26454],[26457,26457],[26460,26460],[26462,26465],[26469,26469],[26471,26474],[26477,26477],[26479,26480],[26482,26483],[26485,26485],[26487,26487],[26491,26492],[26494,26495],[26497,26497],[26500,26501],[26503,26503],[26505,26505],[26507,26507],[26509,26509],[26512,26512],[26517,26517],[26519,26520],[26522,26522],[26524,26526],[26530,26531],[26533,26533],[26535,26536],[26538,26539],[26541,26541],[26543,26544],[26546,26547],[26549,26553],[26561,26561],[26563,26564],[26568,26568],[26570,26570],[26575,26580],[26582,26582],[26584,26586],[26588,26590],[26592,26592],[26594,26594],[26597,26597],[26601,26601],[26604,26604],[26607,26609],[26611,26612],[26615,26615],[26621,26621],[26623,26624],[26629,26629],[26631,26636],[26638,26643],[26646,26647],[26653,26653],[26655,26655],[26657,26657],[26665,26666],[26674,26676],[26679,26681],[26683,26686],[26688,26694],[26696,26698],[26700,26700],[26702,26702],[26704,26705],[26707,26709],[26720,26729],[26731,26731],[26735,26735],[26738,26738],[26740,26740],[26742,26743],[26745,26745],[26753,26753],[26755,26755],[26757,26758],[26764,26764],[26767,26767],[26771,26771],[26775,26775],[26784,26784],[26786,26787],[26790,26792],[26797,26797],[26799,26800],[26803,26805],[26812,26818],[26825,26825],[26827,26827],[26829,26829],[26832,26832],[26834,26835],[26837,26837],[26840,26840],[26842,26842],[26848,26848],[26851,26852],[26856,26856],[26858,26860],[26862,26862],[26864,26865],[26869,26869],[26873,26877],[26880,26881],[26885,26886],[26891,26891],[26893,26894],[26896,26899],[26911,26912],[26916,26916],[26922,26922],[26925,26925],[26928,26928],[26932,26932],[26936,26937],[26941,26941],[26943,26943],[26946,26946],[26962,26962],[26964,26964],[26967,26967],[26969,26970],[26973,26974],[26976,26976],[26979,26979],[26982,26982],[26985,26987],[26990,26991],[26993,26993],[26999,27001],[27004,27004],[27008,27008],[27010,27017],[27021,27021],[27025,27025],[27028,27030],[27032,27032],[27035,27036],[27047,27048],[27051,27051],[27053,27053],[27056,27057],[27060,27060],[27063,27063],[27067,27067],[27073,27073],[27075,27075],[27082,27082],[27084,27084],[27086,27086],[27088,27088],[27092,27092],[27098,27100],[27103,27104],[27117,27117],[27121,27122],[27133,27133],[27135,27135],[27146,27146],[27159,27160],[27167,27167],[27169,27169],[27176,27176],[27178,27178],[27183,27183],[27185,27185],[27189,27189],[27197,27198],[27204,27204],[27207,27207],[27216,27217],[27224,27225],[27227,27227],[27230,27230],[27233,27233],[27237,27238],[27249,27249],[27257,27257],[27260,27260],[27264,27264],[27268,27268],[27278,27278],[27280,27281],[27287,27287],[27294,27294],[27296,27296],[27305,27305],[27307,27308],[27334,27334],[27394,27394],[27424,27428],[27431,27431],[27442,27442],[27447,27451],[27454,27454],[27459,27459],[27461,27463],[27465,27465],[27468,27468],[27481,27481],[27490,27495],[27498,27498],[27513,27513],[27515,27516],[27521,27524],[27526,27527],[27529,27531],[27533,27533],[27538,27539],[27542,27542],[27546,27547],[27553,27553],[27555,27555],[27562,27562],[27571,27573],[27575,27575],[27583,27583],[27585,27586],[27589,27589],[27595,27597],[27599,27600],[27602,27607],[27609,27609],[27611,27611],[27617,27617],[27626,27627],[27631,27631],[27635,27635],[27637,27637],[27641,27641],[27645,27645],[27653,27655],[27661,27661],[27663,27665],[27667,27670],[27672,27675],[27679,27679],[27681,27682],[27684,27684],[27686,27690],[27694,27696],[27698,27698],[27700,27701],[27704,27704],[27709,27714],[27718,27723],[27728,27728],[27732,27733],[27735,27735],[27739,27745],[27748,27748],[27751,27755],[27757,27757],[27760,27760],[27762,27762],[27764,27764],[27766,27766],[27769,27769],[27773,27774],[27777,27785],[27788,27788],[27791,27792],[27795,27796],[27800,27803],[27807,27807],[27809,27809],[27811,27819],[27821,27822],[27825,27827],[27832,27839],[27842,27845],[27847,27847],[27849,27850],[27852,27852],[27856,27856],[27859,27863],[27865,27868],[27870,27870],[27872,27875],[27877,27877],[27880,27880],[27882,27883],[27886,27889],[27891,27891],[27893,27896],[27898,27902],[27905,27905],[27908,27908],[27911,27912],[27915,27916],[27918,27918],[27921,27923],[27927,27931],[27934,27934],[27938,27939],[27941,27941],[27943,27944],[27946,27947],[27949,27950],[27953,27957],[27960,27967],[27969,27969],[27971,27971],[27973,27979],[27981,27989],[27993,27996],[27998,28001],[28003,28003],[28005,28006],[28009,28010],[28012,28016],[28018,28018],[28020,28020],[28023,28024],[28028,28028],[28034,28034],[28036,28037],[28040,28041],[28044,28046],[28048,28049],[28051,28053],[28056,28056],[28059,28059],[28061,28068],[28070,28075],[28078,28079],[28082,28082],[28084,28085],[28088,28088],[28095,28096],[28100,28103],[28107,28108],[28111,28111],[28113,28113],[28118,28118],[28120,28121],[28124,28129],[28132,28132],[28134,28134],[28139,28140],[28142,28143],[28145,28145],[28147,28148],[28151,28151],[28153,28153],[28155,28156],[28165,28165],[28170,28170],[28172,28174],[28176,28177],[28180,28180],[28182,28183],[28186,28186],[28189,28189],[28191,28193],[28195,28197],[28201,28201],[28203,28203],[28205,28205],[28207,28208],[28210,28210],[28212,28212],[28216,28216],[28218,28218],[28220,28220],[28227,28228],[28233,28233],[28237,28238],[28241,28241],[28243,28244],[28246,28246],[28248,28248],[28251,28253],[28255,28255],[28259,28259],[28267,28267],[28270,28270],[28274,28274],[28276,28276],[28286,28287],[28289,28289],[28291,28291],[28293,28295],[28297,28297],[28301,28301],[28303,28304],[28312,28312],[28314,28314],[28316,28316],[28318,28320],[28322,28322],[28325,28327],[28330,28330],[28335,28335],[28337,28338],[28340,28343],[28345,28347],[28349,28349],[28353,28355],[28358,28359],[28361,28361],[28363,28363],[28365,28365],[28367,28367],[28369,28369],[28371,28373],[28375,28376],[28378,28378],[28382,28386],[28388,28395],[28404,28404],[28409,28409],[28418,28418],[28422,28422],[28424,28425],[28427,28427],[28431,28431],[28435,28438],[28448,28448],[28452,28452],[28454,28454],[28457,28459],[28461,28461],[28463,28463],[28465,28465],[28467,28468],[28470,28471],[28473,28473],[28475,28476],[28478,28478],[28486,28487],[28491,28491],[28493,28493],[28495,28495],[28502,28502],[28504,28504],[28508,28508],[28510,28511],[28514,28514],[28518,28518],[28521,28521],[28525,28526],[28530,28530],[28532,28533],[28536,28536],[28538,28538],[28540,28542],[28546,28546],[28548,28548],[28552,28553],[28556,28558],[28571,28572],[28577,28577],[28581,28581],[28583,28583],[28586,28586],[28589,28589],[28595,28596],[28598,28598],[28601,28601],[28604,28605],[28608,28608],[28610,28610],[28617,28617],[28619,28619],[28625,28626],[28638,28638],[28640,28641],[28649,28649],[28654,28655],[28684,28685],[28689,28689],[28692,28692],[28698,28699],[28707,28707],[28721,28721],[28725,28725],[28729,28729],[28732,28732],[28744,28744],[28748,28748],[28751,28751],[28766,28766],[28779,28781],[28783,28784],[28789,28790],[28792,28792],[28796,28796],[28798,28800],[28805,28806],[28809,28810],[28812,28812],[28814,28814],[28818,28818],[28820,28822],[28824,28825],[28828,28829],[28831,28831],[28835,28835],[28843,28847],[28849,28849],[28851,28851],[28855,28857],[28859,28861],[28864,28867],[28872,28872],[28874,28874],[28884,28884],[28888,28889],[28891,28893],[28895,28896],[28900,28900],[28902,28905],[28907,28909],[28911,28911],[28918,28919],[28921,28923],[28925,28925],[28934,28934],[28937,28938],[28940,28940],[28944,28944],[28947,28947],[28949,28954],[28956,28956],[28958,28958],[28966,28966],[28975,28977],[28982,28982],[28993,28993],[28995,28995],[28997,28997],[29002,29004],[29006,29006],[29011,29011],[29020,29020],[29022,29023],[29028,29028],[29030,29032],[29038,29038],[29042,29044],[29048,29048],[29050,29050],[29053,29053],[29060,29060],[29063,29063],[29066,29066],[29071,29071],[29076,29076],[29080,29081],[29083,29084],[29087,29088],[29093,29093],[29096,29096],[29100,29100],[29107,29107],[29109,29109],[29113,29113],[29115,29115],[29123,29123],[29130,29131],[29134,29135],[29140,29141],[29146,29146],[29152,29152],[29157,29157],[29159,29159],[29166,29166],[29177,29177],[29190,29191],[29204,29204],[29210,29210],[29213,29213],[29215,29215],[29224,29224],[29226,29226],[29228,29228],[29232,29233],[29237,29241],[29243,29243],[29245,29245],[29247,29247],[29249,29250],[29255,29256],[29260,29261],[29266,29266],[29270,29270],[29273,29275],[29277,29277],[29279,29279],[29281,29282],[29284,29287],[29289,29289],[29294,29295],[29298,29298],[29301,29301],[29305,29307],[29310,29313],[29316,29316],[29319,29319],[29322,29323],[29325,29325],[29327,29327],[29330,29330],[29343,29343],[29352,29352],[29356,29357],[29359,29360],[29364,29364],[29366,29369],[29377,29380],[29384,29385],[29389,29390],[29392,29392],[29394,29394],[29399,29399],[29401,29401],[29405,29406],[29408,29409],[29416,29417],[29420,29428],[29431,29432],[29434,29436],[29441,29441],[29443,29444],[29447,29447],[29450,29450],[29454,29454],[29459,29459],[29461,29463],[29467,29470],[29473,29474],[29477,29477],[29481,29484],[29486,29489],[29492,29492],[29495,29498],[29502,29503],[29517,29517],[29520,29520],[29522,29522],[29527,29527],[29536,29536],[29548,29549],[29551,29551],[29556,29556],[29566,29566],[29571,29572],[29575,29575],[29577,29577],[29579,29579],[29582,29582],[29585,29587],[29589,29590],[29592,29595],[29598,29602],[29604,29606],[29609,29609],[29611,29611],[29613,29619],[29622,29623],[29625,29628],[29631,29632],[29634,29634],[29637,29637],[29639,29645],[29647,29650],[29653,29654],[29657,29657],[29659,29659],[29661,29662],[29664,29664],[29666,29667],[29669,29671],[29673,29675],[29677,29677],[29680,29680],[29682,29682],[29685,29685],[29687,29690],[29693,29693],[29696,29696],[29699,29706],[29710,29712],[29716,29716],[29722,29723],[29727,29727],[29729,29730],[29732,29734],[29736,29736],[29738,29744],[29746,29750],[29756,29756],[29760,29766],[29777,29777],[29779,29783],[29785,29791],[29794,29794],[29799,29800],[29804,29805],[29808,29809],[29811,29811],[29814,29815],[29822,29822],[29824,29825],[29827,29827],[29830,29832],[29835,29835],[29838,29838],[29840,29840],[29842,29842],[29848,29848],[29852,29852],[29854,29856],[29861,29861],[29863,29866],[29868,29868],[29870,29870],[29873,29874],[29882,29882],[29888,29888],[29906,29906],[29910,29910],[29912,29912],[29916,29916],[29918,29918],[29920,29920],[29922,29924],[29926,29926],[29934,29935],[29940,29940],[29942,29943],[29947,29947],[29951,29951],[29956,29956],[29965,29965],[29967,29967],[29969,29969],[29971,29971],[29975,29978],[29980,29980],[29983,29983],[29985,29985],[29989,29990],[29992,29997],[29999,30003],[30005,30005],[30007,30008],[30010,30011],[30014,30014],[30016,30016],[30021,30021],[30024,30024],[30027,30028],[30030,30031],[30036,30036],[30038,30038],[30041,30044],[30052,30054],[30058,30058],[30060,30060],[30063,30063],[30066,30066],[30068,30068],[30072,30073],[30079,30079],[30081,30081],[30083,30083],[30086,30086],[30091,30091],[30093,30093],[30095,30098],[30100,30100],[30102,30103],[30105,30106],[30109,30109],[30111,30117],[30123,30133],[30136,30137],[30140,30142],[30146,30149],[30151,30154],[30157,30157],[30162,30166],[30168,30168],[30171,30171],[30174,30174],[30178,30180],[30182,30184],[30186,30187],[30192,30193],[30196,30196],[30201,30201],[30204,30204],[30207,30209],[30211,30211],[30213,30214],[30218,30218],[30220,30220],[30224,30224],[30229,30229],[30231,30233],[30235,30235],[30239,30240],[30242,30242],[30244,30246],[30249,30251],[30253,30253],[30256,30256],[30259,30261],[30264,30264],[30268,30268],[30270,30272],[30275,30275],[30284,30285],[30292,30292],[30294,30295],[30300,30300],[30302,30302],[30307,30307],[30315,30315],[30319,30319],[30328,30328],[30331,30331],[30333,30335],[30338,30338],[30340,30340],[30342,30344],[30347,30347],[30350,30350],[30353,30353],[30355,30355],[30357,30358],[30361,30361],[30363,30363],[30366,30366],[30372,30372],[30374,30374],[30381,30382],[30385,30386],[30388,30388],[30399,30399],[30402,30402],[30405,30406],[30408,30410],[30413,30418],[30420,30420],[30422,30424],[30427,30427],[30431,30431],[30437,30438],[30446,30447],[30449,30450],[30452,30452],[30455,30457],[30460,30460],[30462,30462],[30465,30465],[30468,30468],[30471,30475],[30477,30477],[30489,30490],[30495,30496],[30498,30498],[30502,30502],[30504,30505],[30508,30509],[30511,30511],[30517,30520],[30522,30522],[30524,30524],[30528,30529],[30531,30532],[30535,30535],[30542,30542],[30544,30545],[30554,30555],[30561,30563],[30565,30566],[30568,30568],[30571,30572],[30585,30585],[30589,30592],[30596,30597],[30603,30606],[30609,30610],[30623,30624],[30626,30626],[30629,30629],[30631,30631],[30633,30637],[30640,30640],[30643,30643],[30645,30645],[30651,30651],[30653,30653],[30655,30655],[30669,30669],[30679,30679],[30683,30684],[30686,30686],[30690,30691],[30693,30693],[30695,30695],[30697,30697],[30699,30702],[30704,30704],[30707,30707],[30710,30710],[30712,30712],[30715,30722],[30724,30724],[30726,30726],[30729,30729],[30732,30733],[30737,30738],[30740,30740],[30742,30744],[30746,30746],[30748,30749],[30751,30752],[30755,30755],[30757,30759],[30761,30761],[30763,30766],[30768,30768],[30772,30773],[30775,30780],[30782,30782],[30784,30785],[30789,30789],[30791,30791],[30794,30794],[30796,30798],[30800,30800],[30802,30802],[30804,30807],[30809,30810],[30813,30813],[30826,30830],[30839,30839],[30844,30844],[30847,30847],[30851,30851],[30855,30857],[30860,30863],[30865,30865],[30867,30867],[30871,30872],[30874,30876],[30879,30879],[30881,30881],[30883,30883],[30885,30885],[30887,30888],[30896,30900],[30902,30902],[30905,30905],[30910,30910],[30913,30913],[30917,30917],[30921,30923],[30927,30928],[30932,30933],[30937,30937],[30940,30940],[30945,30945],[30952,30952],[30956,30956],[30962,30962],[30964,30964],[30967,30967],[30969,30971],[30977,30977],[30981,30981],[30988,30988],[30995,30995],[31006,31006],[31012,31012],[31028,31029],[31034,31036],[31038,31038],[31040,31041],[31043,31043],[31046,31051],[31054,31056],[31059,31059],[31061,31063],[31066,31072],[31074,31074],[31077,31077],[31079,31080],[31085,31085],[31087,31087],[31090,31090],[31095,31096],[31098,31098],[31100,31100],[31102,31102],[31104,31105],[31108,31109],[31114,31115],[31119,31119],[31122,31122],[31124,31124],[31128,31128],[31130,31131],[31140,31140],[31143,31143],[31155,31155],[31161,31163],[31165,31166],[31168,31169],[31171,31171],[31174,31174],[31177,31177],[31179,31179],[31181,31181],[31185,31186],[31189,31189],[31192,31192],[31199,31199],[31203,31204],[31206,31207],[31209,31209],[31211,31213],[31215,31216],[31224,31224],[31227,31227],[31229,31230],[31232,31232],[31234,31235],[31238,31238],[31243,31246],[31249,31249],[31252,31252],[31255,31255],[31257,31258],[31262,31262],[31264,31264],[31267,31267],[31283,31283],[31287,31287],[31289,31289],[31291,31293],[31295,31295],[31300,31300],[31302,31302],[31313,31313],[31319,31319],[31321,31321],[31324,31324],[31327,31327],[31344,31344],[31348,31348],[31350,31354],[31359,31361],[31363,31366],[31368,31368],[31370,31370],[31373,31374],[31377,31378],[31381,31384],[31388,31389],[31391,31392],[31395,31395],[31397,31398],[31400,31400],[31404,31405],[31411,31411],[31416,31416],[31423,31423],[31435,31435],[31441,31441],[31446,31446],[31448,31449],[31454,31456],[31459,31459],[31461,31462],[31467,31467],[31469,31469],[31471,31471],[31481,31482],[31485,31485],[31487,31487],[31491,31492],[31494,31494],[31496,31496],[31498,31499],[31503,31503],[31505,31505],[31508,31509],[31513,31513],[31515,31515],[31518,31518],[31520,31520],[31524,31526],[31528,31528],[31530,31532],[31534,31535],[31537,31537],[31539,31539],[31544,31544],[31546,31546],[31548,31548],[31550,31550],[31552,31552],[31557,31557],[31559,31559],[31561,31561],[31563,31564],[31567,31570],[31572,31572],[31574,31574],[31576,31576],[31578,31581],[31584,31584],[31586,31586],[31588,31590],[31598,31598],[31601,31602],[31605,31607],[31609,31609],[31611,31612],[31614,31614],[31616,31616],[31621,31621],[31629,31629],[31632,31632],[31635,31639],[31644,31645],[31649,31650],[31654,31661],[31665,31665],[31668,31668],[31672,31672],[31681,31681],[31686,31687],[31692,31692],[31697,31697],[31699,31699],[31705,31706],[31709,31709],[31713,31713],[31717,31718],[31722,31722],[31726,31727],[31729,31729],[31735,31735],[31740,31740],[31742,31742],[31747,31747],[31751,31751],[31753,31753],[31755,31756],[31759,31759],[31765,31766],[31773,31773],[31775,31776],[31782,31783],[31786,31786],[31792,31792],[31800,31800],[31807,31809],[31821,31821],[31845,31845],[31859,31860],[31867,31869],[31881,31881],[31889,31890],[31893,31893],[31895,31896],[31900,31903],[31906,31906],[31908,31909],[31914,31914],[31918,31918],[31921,31923],[31929,31929],[31932,31935],[31937,31937],[31941,31941],[31943,31944],[31946,31946],[31948,31949],[31954,31954],[31957,31959],[31961,31961],[31964,31964],[31967,31968],[31976,31976],[31983,31983],[31989,31989],[31992,31992],[31995,31995],[32010,32010],[32032,32032],[32034,32034],[32039,32039],[32043,32043],[32047,32047],[32092,32092],[32110,32110],[32119,32119],[32166,32166],[32174,32174],[32288,32288],[32290,32290],[32315,32315],[32321,32321],[32324,32324],[32327,32327],[32386,32386],[32411,32411],[32415,32491],[32493,32566],[32568,32568],[32570,32570],[32578,32578],[32580,32581],[32589,32589],[32592,32593],[32596,32597],[32599,32600],[32602,32602],[32607,32607],[32609,32610],[32616,32618],[32622,32622],[32625,32626],[32628,32628],[32630,32630],[32633,32633],[32637,32638],[32641,32641],[32650,32650],[32652,32652],[32654,32654],[32657,32657],[32659,32662],[32666,32666],[32669,32671],[32673,32673],[32676,32676],[32679,32679],[32687,32690],[32696,32697],[32700,32701],[32703,32707],[32709,32709],[32712,32712],[32714,32714],[32716,32716],[32718,32718],[32724,32725],[32728,32731],[32735,32737],[32741,32742],[32745,32745],[32750,32753],[32755,32755],[32759,32759],[32763,32764],[32766,32766],[32768,32769],[32771,32775],[32779,32781],[32783,32786],[32788,32793],[32796,32796],[32800,32800],[32802,32802],[32804,32810],[32816,32817],[32819,32819],[32821,32824],[32827,32827],[32829,32829],[32831,32831],[32834,32835],[32838,32838],[32842,32845],[32850,32850],[32852,32852],[32856,32856],[32858,32858],[32873,32874],[32881,32881],[32895,32896],[32899,32900],[32902,32903],[32905,32905],[32907,32908],[32915,32915],[32918,32918],[32920,32920],[32922,32925],[32927,32930],[32932,32933],[32937,32939],[32941,32943],[32945,32946],[32948,32948],[32951,32952],[32954,32954],[32956,32964],[32966,32966],[32968,32968],[32972,32974],[32982,32983],[32985,32990],[32992,32993],[32995,32997],[32999,33005],[33007,33012],[33014,33014],[33016,33016],[33018,33018],[33020,33021],[33026,33026],[33030,33030],[33033,33034],[33037,33044],[33046,33046],[33048,33048],[33050,33050],[33054,33055],[33065,33065],[33068,33068],[33071,33071],[33073,33074],[33078,33078],[33080,33080],[33086,33087],[33094,33094],[33096,33096],[33098,33100],[33104,33109],[33112,33114],[33120,33120],[33125,33125],[33127,33129],[33133,33137],[33140,33140],[33145,33152],[33154,33154],[33160,33160],[33162,33162],[33167,33167],[33169,33169],[33176,33177],[33179,33181],[33187,33187],[33190,33190],[33192,33192],[33194,33194],[33203,33203],[33210,33211],[33216,33219],[33222,33222],[33226,33226],[33228,33228],[33233,33233],[33244,33244],[33251,33251],[33255,33255],[33258,33258],[33260,33261],[33267,33268],[33275,33276],[33278,33278],[33280,33282],[33284,33286],[33292,33293],[33296,33296],[33298,33298],[33300,33300],[33307,33308],[33310,33315],[33317,33317],[33320,33320],[33322,33325],[33327,33337],[33339,33339],[33342,33342],[33348,33349],[33351,33351],[33353,33353],[33355,33355],[33358,33359],[33368,33368],[33370,33370],[33375,33375],[33384,33384],[33390,33392],[33394,33396],[33401,33402],[33405,33407],[33410,33412],[33416,33416],[33418,33419],[33421,33423],[33425,33426],[33431,33433],[33436,33437],[33439,33441],[33443,33446],[33448,33457],[33459,33460],[33463,33465],[33468,33470],[33473,33473],[33476,33476],[33479,33487],[33489,33493],[33495,33496],[33499,33500],[33502,33505],[33507,33511],[33515,33515],[33519,33519],[33521,33521],[33524,33524],[33527,33527],[33529,33529],[33531,33531],[33534,33534],[33536,33545],[33547,33548],[33550,33551],[33553,33553],[33555,33557],[33559,33559],[33562,33565],[33575,33576],[33579,33581],[33583,33583],[33585,33585],[33587,33590],[33592,33594],[33596,33597],[33600,33601],[33603,33604],[33606,33607],[33609,33609],[33615,33620],[33622,33622],[33625,33628],[33630,33633],[33635,33647],[33655,33656],[33659,33661],[33669,33670],[33673,33673],[33678,33678],[33682,33683],[33688,33689],[33691,33694],[33696,33696],[33704,33707],[33712,33716],[33718,33722],[33724,33725],[33727,33730],[33733,33733],[33735,33735],[33737,33738],[33740,33741],[33743,33743],[33748,33748],[33750,33750],[33752,33752],[33756,33757],[33759,33761],[33765,33765],[33769,33770],[33776,33778],[33784,33785],[33788,33789],[33793,33793],[33795,33796],[33798,33798],[33803,33807],[33809,33809],[33816,33816],[33818,33818],[33820,33821],[33827,33833],[33841,33841],[33843,33843],[33848,33849],[33852,33853],[33862,33862],[33870,33870],[33873,33873],[33878,33879],[33881,33884],[33889,33889],[33891,33891],[33897,33897],[33899,33901],[33904,33905],[33907,33910],[33912,33912],[33914,33914],[33922,33922],[33924,33924],[33927,33929],[33931,33932],[33934,33934],[33936,33936],[33943,33943],[33945,33945],[33948,33948],[33951,33951],[33953,33953],[33960,33960],[33967,33967],[33969,33970],[33972,33972],[33976,33979],[33981,33981],[33983,33983],[33985,33986],[33988,33988],[33991,33991],[33993,33994],[33997,33997],[33999,34001],[34003,34003],[34006,34006],[34013,34013],[34015,34016],[34018,34019],[34021,34022],[34028,34028],[34032,34032],[34044,34044],[34047,34048],[34051,34051],[34056,34056],[34058,34058],[34060,34060],[34065,34065],[34067,34067],[34071,34071],[34074,34074],[34079,34079],[34081,34081],[34091,34092],[34103,34109],[34115,34115],[34120,34122],[34134,34135],[34137,34137],[34142,34142],[34148,34148],[34152,34152],[34160,34160],[34162,34162],[34164,34164],[34169,34171],[34174,34174],[34177,34177],[34180,34181],[34183,34183],[34191,34191],[34203,34204],[34210,34210],[34212,34212],[34216,34216],[34218,34218],[34222,34224],[34227,34227],[34231,34233],[34239,34239],[34241,34241],[34249,34249],[34255,34256],[34259,34259],[34261,34261],[34268,34268],[34271,34272],[34276,34276],[34278,34278],[34280,34281],[34299,34299],[34303,34303],[34309,34309],[34321,34321],[34326,34326],[34328,34328],[34343,34343],[34345,34345],[34360,34360],[34364,34364],[34381,34388],[34394,34394],[34398,34398],[34402,34402],[34404,34404],[34411,34412],[34414,34414],[34417,34417],[34423,34434],[34436,34436],[34438,34438],[34442,34445],[34451,34451],[34453,34453],[34460,34461],[34467,34468],[34471,34474],[34476,34476],[34479,34482],[34484,34486],[34490,34490],[34496,34496],[34499,34500],[34502,34503],[34505,34507],[34510,34513],[34516,34516],[34520,34521],[34523,34523],[34526,34527],[34532,34532],[34537,34537],[34541,34542],[34544,34548],[34552,34553],[34558,34558],[34560,34560],[34562,34563],[34567,34570],[34573,34574],[34576,34576],[34578,34579],[34581,34581],[34583,34584],[34586,34586],[34588,34588],[34590,34590],[34593,34595],[34597,34597],[34601,34601],[34606,34606],[34609,34609],[34612,34612],[34615,34615],[34619,34619],[34622,34623],[34631,34633],[34636,34636],[34638,34638],[34643,34643],[34647,34649],[34656,34656],[34659,34661],[34670,34670],[34672,34672],[34674,34674],[34676,34676],[34678,34678],[34683,34686],[34690,34691],[34693,34693],[34696,34696],[34699,34699],[34701,34701],[34707,34707],[34711,34711],[34719,34720],[34723,34723],[34728,34728],[34731,34733],[34735,34735],[34737,34737],[34739,34739],[34741,34741],[34746,34746],[34749,34749],[34752,34752],[34758,34758],[34762,34763],[34767,34767],[34769,34771],[34779,34779],[34784,34784],[34789,34789],[34794,34795],[34798,34798],[34809,34809],[34814,34814],[34819,34819],[34826,34827],[34835,34835],[34837,34838],[34843,34843],[34849,34850],[34866,34866],[34873,34873],[34876,34876],[34880,34880],[34883,34885],[34892,34894],[34898,34898],[34900,34900],[34903,34903],[34905,34905],[34912,34917],[34920,34921],[34923,34924],[34926,34926],[34928,34928],[34930,34930],[34935,34935],[34941,34943],[34945,34946],[34948,34950],[34952,34952],[34955,34955],[34957,34957],[34962,34962],[34966,34967],[34972,34972],[34978,34978],[34980,34980],[34986,34987],[34989,34989],[34991,34991],[34993,34993],[34999,34999],[35004,35004],[35009,35010],[35013,35014],[35016,35017],[35022,35022],[35026,35026],[35028,35029],[35032,35033],[35035,35035],[35039,35039],[35042,35045],[35048,35048],[35056,35057],[35059,35060],[35064,35065],[35068,35068],[35070,35070],[35074,35074],[35082,35082],[35088,35088],[35090,35091],[35093,35093],[35097,35099],[35103,35103],[35105,35105],[35109,35109],[35114,35115],[35119,35120],[35124,35124],[35126,35126],[35137,35137],[35140,35140],[35157,35157],[35162,35162],[35164,35164],[35166,35167],[35174,35174],[35179,35179],[35195,35195],[35199,35199],[35201,35201],[35203,35203],[35206,35206],[35265,35276],[35278,35282],[35286,35286],[35290,35290],[35292,35292],[35294,35295],[35299,35299],[35301,35302],[35307,35307],[35309,35309],[35311,35311],[35313,35313],[35315,35315],[35327,35328],[35332,35332],[35335,35335],[35354,35354],[35390,35390],[35400,35400],[35423,35423],[35449,35449],[35465,35466],[35475,35475],[35591,35591],[35622,35622],[35686,35686],[35692,35692],[35744,35755],[35757,35817],[35819,35848],[35850,35895],[35900,35900],[35903,35903],[35905,35905],[35910,35911],[35913,35913],[35916,35916],[35925,35925],[35930,35930],[35937,35938],[35944,35944],[35946,35947],[35950,35950],[35955,35955],[35960,35962],[35970,35970],[35973,35974],[35977,35978],[35980,35980],[35988,35988],[35992,35992],[36125,36127],[36129,36196],[36198,36199],[36202,36203],[36205,36205],[36208,36208],[36211,36215],[36225,36225],[36228,36229],[36234,36235],[36241,36241],[36244,36244],[36255,36255],[36259,36259],[36271,36271],[36273,36273],[36275,36277],[36280,36280],[36282,36282],[36284,36284],[36286,36287],[36290,36292],[36294,36294],[36299,36300],[36302,36305],[36310,36311],[36314,36315],[36317,36319],[36323,36324],[36328,36328],[36330,36332],[36335,36335],[36337,36337],[36339,36339],[36341,36347],[36349,36349],[36357,36357],[36361,36362],[36364,36364],[36367,36367],[36370,36370],[36372,36372],[36381,36383],[36386,36387],[36390,36390],[36393,36394],[36396,36396],[36398,36399],[36401,36401],[36405,36406],[36409,36410],[36413,36413],[36416,36418],[36420,36421],[36423,36427],[36432,36434],[36441,36442],[36444,36444],[36450,36450],[36454,36454],[36457,36457],[36460,36461],[36463,36464],[36466,36466],[36468,36468],[36470,36470],[36476,36479],[36481,36481],[36485,36485],[36487,36487],[36495,36496],[36500,36500],[36508,36508],[36510,36510],[36523,36524],[36527,36527],[36530,36530],[36538,36538],[36558,36558],[36710,36764],[36766,36767],[36771,36771],[36776,36777],[36779,36779],[36784,36785],[36790,36790],[36793,36793],[36797,36799],[36801,36802],[36804,36805],[36807,36808],[36814,36814],[36816,36817],[36819,36821],[36824,36825],[36827,36831],[36834,36834],[36836,36838],[36840,36843],[36845,36846],[36848,36848],[36851,36851],[36855,36858],[36861,36861],[36864,36870],[36873,36875],[36877,36877],[36879,36882],[36884,36884],[36886,36887],[36890,36891],[36893,36898],[36902,36902],[36909,36911],[36916,36918],[36920,36920],[36923,36924],[36926,36926],[36929,36930],[36932,36932],[36934,36935],[36941,36941],[36943,36947],[36951,36952],[36955,36955],[36962,36963],[36965,36965],[36968,36968],[36973,36974],[36980,36981],[36985,36985],[36989,36989],[36991,36992],[36994,36995],[37000,37000],[37003,37003],[37009,37009],[37011,37011],[37013,37013],[37015,37017],[37019,37019],[37021,37021],[37024,37027],[37030,37030],[37032,37032],[37034,37034],[37036,37036],[37038,37046],[37048,37051],[37053,37055],[37057,37057],[37059,37061],[37063,37064],[37066,37066],[37070,37073],[37075,37075],[37079,37079],[37082,37085],[37089,37090],[37092,37092],[37094,37096],[37098,37099],[37101,37101],[37103,37103],[37108,37108],[37112,37112],[37117,37120],[37122,37125],[37132,37132],[37137,37137],[37143,37146],[37148,37148],[37150,37150],[37152,37152],[37154,37155],[37163,37163],[37167,37167],[37169,37169],[37177,37177],[37186,37187],[37189,37190],[37193,37200],[37202,37202],[37207,37207],[37210,37210],[37213,37214],[37217,37222],[37225,37226],[37228,37228],[37230,37234],[37236,37242],[37245,37247],[37253,37253],[37255,37255],[37257,37257],[37259,37261],[37264,37266],[37274,37275],[37282,37283],[37288,37288],[37290,37290],[37293,37295],[37300,37301],[37306,37306],[37310,37310],[37319,37319],[37321,37322],[37324,37329],[37340,37340],[37492,37492],[37518,37518],[37550,37550],[37574,37574],[37576,37576],[37694,37694],[37738,37738],[37775,37775],[37834,37834],[37846,37846],[37950,37950],[37995,37995],[38021,38032],[38034,38086],[38088,38098],[38101,38117],[38119,38175],[38177,38262],[38271,38271],[38376,38379],[38381,38418],[38420,38426],[38428,38429],[38431,38431],[38433,38434],[38442,38442],[38446,38446],[38449,38454],[38459,38461],[38463,38464],[38466,38466],[38468,38473],[38475,38478],[38480,38481],[38484,38485],[38491,38491],[38494,38495],[38497,38498],[38500,38500],[38503,38506],[38508,38508],[38514,38514],[38516,38519],[38531,38531],[38533,38534],[38536,38536],[38539,38539],[38541,38541],[38543,38544],[38548,38548],[38551,38553],[38556,38556],[38567,38567],[38569,38569],[38576,38576],[38579,38579],[38582,38582],[38585,38586],[38588,38590],[38592,38593],[38596,38599],[38601,38602],[38604,38607],[38610,38610],[38613,38613],[38624,38624],[38632,38634],[38639,38639],[38641,38641],[38643,38643],[38646,38647],[38649,38649],[38654,38654],[38656,38657],[38660,38665],[38669,38671],[38675,38675],[38678,38678],[38684,38684],[38686,38686],[38696,38696],[38698,38698],[38701,38701],[38704,38704],[38706,38706],[38712,38713],[38718,38718],[38738,38739],[38742,38742],[38745,38745],[38747,38747],[38750,38750],[38752,38754],[38757,38757],[38761,38761],[38764,38764],[38768,38768],[38771,38772],[38774,38774],[38776,38776],[38778,38778],[38780,38781],[38783,38783],[38785,38785],[38789,38789],[38795,38795],[38797,38797],[38801,38802],[38804,38804],[38808,38808],[38816,38817],[38819,38819],[38823,38824],[38827,38831],[38834,38836],[38850,38850],[38886,38893],[38899,38899],[38901,38902],[39029,39057],[39059,39060],[39062,39074],[39076,39079],[39118,39125],[39127,39130],[39134,39135],[39143,39144],[39181,39181],[39184,39184],[39214,39214],[39252,39253],[39267,39267],[39269,39269],[39271,39293],[39295,39297],[39299,39309],[39311,39321],[39325,39326],[39333,39333],[39335,39336],[39532,39571],[39573,39592],[39600,39601],[39606,39608],[39610,39610],[39612,39612],[39616,39619],[39621,39621],[39627,39628],[39630,39630],[39633,39633],[39635,39635],[39640,39640],[39647,39647],[39649,39650],[39654,39654],[39659,39659],[39661,39661],[39663,39663],[39673,39673],[39675,39675],[39677,39677],[39683,39683],[39688,39688],[39695,39695],[39698,39699],[39704,39704],[39711,39711],[39715,39715],[39727,39727],[39730,39730],[39734,39735],[39739,39740],[39745,39753],[39755,39755],[39757,39757],[39759,39759],[39761,39761],[39764,39764],[40060,40067],[40069,40082],[40084,40164],[40479,40499],[40501,40530],[40532,40548],[40550,40564],[40574,40576],[40578,40578],[40583,40584],[40587,40587],[40593,40595],[40598,40598],[40605,40605],[40607,40607],[40614,40614],[40628,40628],[40632,40633],[40635,40635],[40637,40638],[40644,40644],[40647,40647],[40649,40649],[40653,40655],[40657,40657],[40660,40660],[40664,40664],[40667,40669],[40671,40674],[40677,40677],[40679,40679],[40681,40682],[40687,40687],[40697,40697],[40699,40700],[40702,40702],[40715,40715],[40717,40718],[40720,40720],[40722,40723],[40727,40727],[40729,40729],[40736,40736],[40738,40738],[40745,40745],[40747,40748],[40751,40751],[40753,40753],[40759,40759],[40761,40761],[40763,40763],[40765,40766],[40769,40769],[40772,40772],[40775,40775],[40777,40777],[40784,40785],[40831,40844],[40857,40859],[40863,40864],[40866,40866],[40909,40911],[65072,65103],[65281,65470],[65474,65479],[65482,65487],[65490,65495],[65498,65500],[65504,65510],[65512,65518],[131428,131428],[132726,132726],[134352,134352],[136090,136090],[136211,136211],[144843,144843],[146583,146584],[146979,146979],[149979,149979],[150141,150141],[150217,150217],[152882,152882],[152930,152930],[153000,153000],[155351,155351],[156193,156193],[156813,156813],[157302,157302],[157564,157564],[158556,158556],[158753,158753],[163833,163833],[164872,164872],[165496,165496],[165525,165525],[165856,165856],[166729,166729],[166983,166983],[166991,166991],[166993,166993],[166996,166996],[167577,167577],[171902,171902],[171907,171907],[171916,171916],[174045,174045],[174331,174331],[174359,174359],[174640,174640],[174646,174646],[174680,174680],[176034,176034],[176423,176424],[176439,176440],[176621,176621],[176896,176896],[176995,176995],[177007,177007],[177010,177010],[177021,177021],[177156,177156],[177168,177168],[177171,177171],[177249,177249],[177383,177383],[177391,177391],[177398,177398],[177401,177401],[177421,177422],[177462,177462],[177582,177583],[177587,177587],[177639,177639],[177652,177652],[177692,177693],[177702,177704],[177706,177706],[177708,177708],[177813,177814],[177837,177837],[177901,177901],[178089,178089],[178117,178117],[178150,178150],[178169,178169],[178172,178172],[178182,178182],[178186,178186],[178204,178204],[178360,178360],[178887,178887],[179039,179039],[179042,179042],[179068,179068],[179075,179075],[179227,179227],[179575,179575],[179591,179591],[179703,179703],[179753,179753],[180265,180266],[180393,180393],[180426,180426],[180693,180693],[180697,180697],[180729,180729],[180860,180860],[180872,180872],[180900,180900],[181015,181015],[181083,181083],[181089,181089],[181092,181092],[181384,181384],[181396,181396],[181399,181399],[181570,181570],[181779,181779],[181784,181784],[181793,181793],[181801,181801],[181803,181805],[181807,181807],[181826,181826],[181834,181835],[182060,182060],[182063,182063],[182175,182175],[182209,182209],[182269,182269],[182489,182489],[182494,182494],[182497,182497],[182515,182515],[182535,182535],[182538,182538],[182557,182557],[182786,182786],[182798,182798],[182909,182909],[182953,182953],[183081,183081],[183085,183086],[183089,183089],[183096,183097],[183099,183099],[183103,183103],[183105,183105],[183114,183114],[183118,183118],[183130,183131],[183140,183140],[183145,183145],[183148,183148],[183151,183151],[183155,183155],[183158,183158],[183160,183160],[183164,183164],[183217,183217],[183231,183232],[183246,183246],[183382,183382],[183391,183391],[183541,183542],[183549,183549],[183551,183551],[183554,183555],[183562,183562],[183691,183691],[183693,183693],[183695,183696],[183711,183712],[183720,183720],[183725,183726],[183765,183765],[183832,183832],[183834,183834],[183843,183843],[183846,183846],[183850,183850],[183932,183932],[183944,183944],[183955,183955]]},"700":{"file":"FreeVideoMonoSC-Bold.woff2","sha256":"025fa8ae8c43366db71540a47af60a9a14e78ce04d4c9d26fc443f25b289ada3","ranges":[[32,126],[160,259],[272,275],[282,283],[296,299],[323,324],[327,328],[332,335],[338,339],[360,365],[462,462],[464,464],[466,466],[468,468],[470,470],[472,472],[474,474],[476,476],[711,711],[713,713],[913,929],[931,937],[945,961],[963,969],[1025,1025],[1040,1103],[1105,1105],[8194,8195],[8208,8214],[8216,8218],[8220,8222],[8224,8226],[8229,8231],[8240,8240],[8242,8243],[8245,8245],[8249,8252],[8258,8258],[8263,8265],[8273,8273],[8451,8451],[8470,8470],[8544,8555],[8592,8601],[8632,8633],[8644,8646],[8651,8652],[8656,8656],[8658,8658],[8660,8660],[8678,8681],[8693,8693],[8712,8712],[8715,8715],[8719,8719],[8721,8721],[8730,8730],[8733,8734],[8736,8736],[8741,8741],[8743,8747],[8750,8750],[8756,8759],[8765,8765],[8773,8773],[8776,8776],[8780,8780],[8800,8801],[8804,8805],[8814,8815],[8857,8857],[8869,8869],[8978,8978],[9312,9547],[9632,9643],[9649,9651],[9654,9655],[9660,9661],[9664,9665],[9670,9671],[9673,9676],[9678,9683],[9698,9702],[9711,9711],[9728,9731],[9733,9734],[9737,9737],[9742,9743],[9750,9751],[9756,9759],[9775,9775],[9792,9794],[9824,9839],[9842,9853],[9888,9888],[9917,9918],[12288,12351],[12353,12438],[12441,12543],[12549,12585],[12832,12841],[13383,13383],[13386,13386],[13678,13678],[13838,13838],[13901,13901],[13912,13912],[13926,13926],[14019,14019],[14042,14042],[14073,14073],[14275,14275],[14343,14343],[14355,14355],[14616,14616],[14660,14660],[14800,14801],[14815,14815],[15088,15088],[15114,15114],[15118,15118],[15130,15130],[15182,15182],[15189,15189],[15294,15294],[15360,15360],[15559,15559],[15576,15576],[15578,15578],[15636,15636],[15696,15696],[15794,15794],[15878,15878],[15884,15884],[16004,16004],[16108,16108],[16207,16207],[16352,16352],[16470,16470],[16558,16558],[16581,16581],[16590,16590],[16735,16735],[17209,17209],[17283,17283],[17302,17302],[17373,17373],[17377,17377],[17394,17394],[17411,17411],[17622,17622],[17627,17627],[17640,17640],[17643,17644],[17878,17878],[17883,17883],[17898,17898],[17908,17908],[18211,18211],[18265,18265],[18618,18618],[18620,18620],[18648,18648],[18813,18813],[18819,18819],[19615,19616],[19618,19618],[19731,19737],[19886,19886],[19968,19969],[19971,19971],[19975,19985],[19987,19990],[19992,19998],[20002,20002],[20004,20005],[20007,20008],[20010,20013],[20016,20016],[20018,20018],[20020,20020],[20022,20022],[20024,20027],[20029,20031],[20034,20035],[20037,20037],[20039,20041],[20043,20048],[20050,20052],[20054,20054],[20056,20057],[20060,20065],[20070,20070],[20073,20073],[20080,20081],[20083,20083],[20088,20088],[20094,20094],[20102,20102],[20104,20105],[20107,20111],[20113,20117],[20120,20120],[20122,20123],[20127,20130],[20132,20137],[20139,20142],[20146,20147],[20149,20150],[20152,20155],[20159,20167],[20169,20171],[20173,20174],[20177,20177],[20179,20185],[20189,20191],[20193,20193],[20195,20197],[20200,20200],[20202,20204],[20208,20208],[20210,20211],[20213,20215],[20219,20219],[20221,20221],[20223,20223],[20225,20225],[20232,20235],[20237,20241],[20247,20251],[20254,20256],[20258,20263],[20266,20267],[20269,20269],[20271,20272],[20274,20274],[20276,20276],[20278,20278],[20280,20280],[20282,20282],[20284,20286],[20289,20289],[20291,20291],[20294,20294],[20301,20305],[20307,20307],[20309,20320],[20323,20325],[20327,20327],[20329,20329],[20332,20332],[20335,20336],[20339,20340],[20342,20342],[20344,20344],[20346,20351],[20353,20356],[20360,20361],[20363,20363],[20365,20365],[20367,20367],[20369,20369],[20372,20372],[20375,20376],[20379,20379],[20381,20381],[20384,20384],[20387,20387],[20389,20394],[20396,20396],[20398,20399],[20404,20405],[20409,20409],[20415,20415],[20419,20421],[20426,20426],[20429,20433],[20439,20442],[20444,20447],[20449,20449],[20451,20451],[20454,20454],[20456,20459],[20461,20463],[20465,20465],[20467,20467],[20469,20470],[20472,20472],[20474,20474],[20478,20478],[20492,20493],[20495,20495],[20498,20501],[20504,20506],[20508,20508],[20510,20511],[20513,20513],[20517,20522],[20524,20526],[20532,20532],[20538,20540],[20542,20542],[20545,20545],[20547,20547],[20551,20552],[20556,20556],[20558,20559],[20563,20563],[20565,20565],[20570,20570],[20572,20572],[20577,20577],[20581,20581],[20588,20589],[20592,20592],[20594,20594],[20598,20599],[20603,20603],[20606,20608],[20611,20611],[20613,20613],[20616,20617],[20621,20621],[20626,20626],[20629,20629],[20643,20643],[20645,20645],[20647,20649],[20652,20652],[20658,20658],[20666,20667],[20679,20679],[20686,20687],[20692,20692],[20694,20694],[20698,20698],[20710,20711],[20716,20718],[20720,20720],[20723,20723],[20725,20725],[20731,20731],[20742,20743],[20747,20747],[20754,20754],[20769,20769],[20774,20774],[20787,20788],[20799,20801],[20803,20806],[20808,20809],[20811,20811],[20813,20813],[20817,20817],[20820,20822],[20826,20826],[20828,20828],[20834,20834],[20837,20837],[20840,20840],[20843,20846],[20848,20849],[20851,20857],[20859,20861],[20864,20866],[20869,20869],[20872,20873],[20876,20877],[20879,20879],[20882,20882],[20884,20887],[20889,20889],[20891,20892],[20896,20896],[20898,20898],[20900,20901],[20907,20908],[20910,20915],[20917,20919],[20923,20925],[20928,20928],[20932,20932],[20934,20935],[20937,20937],[20939,20940],[20943,20943],[20945,20945],[20947,20947],[20952,20952],[20955,20955],[20957,20957],[20960,20961],[20964,20964],[20971,20971],[20973,20973],[20975,20976],[20979,20979],[20981,20982],[20984,20989],[20991,20995],[20998,21000],[21002,21002],[21005,21006],[21009,21010],[21014,21019],[21021,21021],[21024,21024],[21028,21028],[21032,21033],[21035,21038],[21040,21040],[21043,21043],[21046,21051],[21053,21053],[21055,21059],[21061,21061],[21066,21069],[21072,21073],[21076,21078],[21084,21084],[21086,21087],[21089,21089],[21093,21093],[21095,21095],[21097,21098],[21103,21103],[21106,21106],[21117,21117],[21119,21119],[21121,21122],[21124,21124],[21128,21128],[21136,21136],[21139,21139],[21147,21147],[21149,21155],[21160,21165],[21169,21171],[21180,21180],[21182,21183],[21187,21187],[21191,21191],[21193,21193],[21195,21195],[21197,21197],[21200,21200],[21202,21202],[21204,21204],[21206,21206],[21208,21208],[21210,21210],[21215,21216],[21220,21220],[21232,21232],[21241,21242],[21246,21248],[21253,21254],[21256,21256],[21261,21261],[21263,21264],[21269,21271],[21273,21274],[21276,21277],[21280,21281],[21283,21283],[21286,21286],[21290,21290],[21294,21294],[21305,21308],[21310,21311],[21313,21313],[21315,21315],[21317,21317],[21319,21322],[21326,21327],[21329,21331],[21333,21335],[21338,21338],[21340,21340],[21342,21348],[21350,21351],[21353,21353],[21355,21356],[21358,21361],[21363,21365],[21367,21368],[21370,21370],[21375,21375],[21378,21378],[21380,21382],[21385,21385],[21387,21389],[21397,21398],[21400,21400],[21402,21402],[21405,21405],[21407,21407],[21410,21411],[21413,21414],[21416,21417],[21422,21422],[21430,21430],[21435,21435],[21438,21439],[21441,21442],[21446,21453],[21457,21457],[21460,21467],[21471,21472],[21475,21478],[21480,21491],[21493,21497],[21499,21501],[21505,21505],[21507,21508],[21510,21510],[21512,21514],[21516,21523],[21525,21527],[21531,21531],[21533,21537],[21539,21539],[21542,21545],[21547,21551],[21553,21554],[21556,21557],[21560,21561],[21563,21566],[21568,21568],[21571,21571],[21574,21576],[21578,21579],[21584,21584],[21586,21593],[21595,21596],[21602,21604],[21606,21606],[21608,21608],[21617,21619],[21621,21624],[21627,21629],[21632,21632],[21634,21634],[21636,21636],[21638,21639],[21641,21641],[21643,21648],[21650,21650],[21652,21654],[21657,21659],[21661,21661],[21665,21665],[21667,21677],[21679,21679],[21681,21681],[21683,21684],[21688,21688],[21690,21691],[21693,21693],[21695,21700],[21702,21705],[21708,21717],[21719,21719],[21721,21722],[21724,21727],[21730,21730],[21733,21738],[21741,21742],[21745,21747],[21754,21754],[21756,21757],[21759,21759],[21761,21761],[21766,21767],[21769,21769],[21775,21777],[21780,21780],[21787,21787],[21789,21789],[21792,21792],[21794,21796],[21799,21799],[21802,21802],[21804,21804],[21806,21809],[21811,21811],[21813,21813],[21815,21815],[21820,21820],[21822,21823],[21825,21825],[21827,21828],[21830,21830],[21833,21834],[21840,21840],[21845,21846],[21852,21852],[21857,21857],[21860,21863],[21866,21870],[21872,21872],[21876,21880],[21883,21884],[21886,21886],[21888,21892],[21894,21899],[21903,21903],[21905,21905],[21908,21908],[21912,21913],[21916,21917],[21919,21919],[21924,21924],[21927,21927],[21937,21937],[21939,21939],[21941,21941],[21943,21943],[21945,21945],[21947,21947],[21949,21950],[21956,21957],[21961,21961],[21964,21965],[21968,21972],[21974,21974],[21980,21983],[21985,21985],[21987,21990],[21992,21992],[21994,21996],[21999,21999],[22002,22003],[22005,22005],[22007,22007],[22013,22014],[22016,22017],[22024,22025],[22028,22028],[22030,22031],[22040,22040],[22042,22043],[22046,22047],[22049,22049],[22051,22052],[22055,22055],[22060,22061],[22065,22066],[22068,22068],[22070,22070],[22073,22073],[22075,22075],[22079,22080],[22082,22082],[22087,22087],[22092,22094],[22100,22100],[22103,22105],[22108,22108],[22114,22114],[22116,22116],[22120,22124],[22129,22129],[22134,22134],[22139,22140],[22148,22150],[22158,22159],[22163,22163],[22170,22170],[22179,22179],[22189,22189],[22191,22191],[22199,22199],[22204,22204],[22218,22218],[22228,22228],[22231,22231],[22234,22235],[22237,22242],[22244,22244],[22251,22251],[22253,22253],[22256,22257],[22260,22261],[22263,22263],[22265,22266],[22269,22271],[22275,22276],[22278,22278],[22280,22282],[22284,22284],[22288,22288],[22297,22297],[22300,22300],[22303,22303],[22306,22307],[22312,22320],[22322,22323],[22329,22331],[22334,22334],[22336,22336],[22338,22338],[22343,22343],[22345,22354],[22359,22359],[22362,22369],[22372,22374],[22376,22381],[22383,22384],[22387,22387],[22390,22391],[22395,22397],[22402,22406],[22408,22408],[22411,22415],[22418,22419],[22421,22421],[22425,22427],[22430,22436],[22438,22439],[22441,22441],[22443,22443],[22445,22447],[22449,22450],[22452,22453],[22456,22456],[22458,22458],[22462,22463],[22466,22467],[22470,22471],[22475,22476],[22478,22479],[22482,22482],[22484,22485],[22487,22490],[22493,22493],[22495,22496],[22500,22500],[22506,22507],[22509,22509],[22511,22511],[22516,22517],[22520,22522],[22524,22525],[22528,22528],[22530,22531],[22534,22535],[22537,22537],[22539,22542],[22544,22545],[22549,22549],[22553,22553],[22558,22558],[22560,22561],[22564,22564],[22567,22568],[22570,22570],[22576,22576],[22578,22578],[22581,22581],[22588,22590],[22596,22598],[22604,22605],[22609,22609],[22612,22612],[22616,22616],[22621,22622],[22629,22629],[22635,22636],[22641,22641],[22654,22654],[22656,22657],[22659,22659],[22661,22661],[22664,22665],[22672,22672],[22674,22675],[22677,22677],[22680,22682],[22686,22687],[22689,22689],[22691,22691],[22694,22694],[22696,22697],[22716,22716],[22721,22721],[22725,22725],[22737,22737],[22741,22741],[22756,22756],[22763,22764],[22766,22766],[22768,22768],[22771,22771],[22774,22774],[22776,22777],[22786,22786],[22788,22788],[22791,22791],[22797,22797],[22799,22800],[22804,22806],[22809,22810],[22812,22812],[22815,22815],[22820,22821],[22823,22823],[22825,22831],[22833,22833],[22836,22836],[22839,22842],[22844,22844],[22849,22850],[22852,22852],[22855,22857],[22859,22859],[22862,22863],[22865,22865],[22867,22872],[22874,22874],[22880,22882],[22885,22885],[22893,22893],[22899,22900],[22902,22902],[22904,22905],[22909,22909],[22913,22916],[22918,22920],[22922,22922],[22925,22925],[22930,22931],[22934,22937],[22942,22942],[22947,22949],[22951,22955],[22957,22959],[22962,22962],[22969,22969],[22971,22971],[22974,22974],[22982,22982],[22984,22984],[22986,22987],[22992,22996],[22999,23000],[23002,23002],[23004,23006],[23011,23013],[23016,23016],[23020,23020],[23022,23022],[23025,23025],[23030,23030],[23033,23033],[23035,23035],[23037,23037],[23039,23041],[23043,23049],[23052,23052],[23057,23057],[23059,23059],[23064,23064],[23068,23068],[23071,23072],[23075,23075],[23077,23077],[23081,23081],[23089,23090],[23092,23094],[23100,23100],[23104,23104],[23110,23110],[23113,23114],[23116,23117],[23125,23125],[23128,23128],[23130,23130],[23134,23134],[23136,23136],[23138,23138],[23140,23140],[23143,23143],[23146,23147],[23155,23159],[23162,23164],[23167,23167],[23170,23170],[23172,23172],[23174,23174],[23186,23187],[23190,23190],[23194,23195],[23198,23198],[23210,23210],[23213,23213],[23217,23219],[23221,23221],[23224,23224],[23230,23230],[23233,23234],[23236,23236],[23241,23241],[23244,23244],[23250,23250],[23252,23254],[23256,23256],[23258,23258],[23260,23260],[23264,23265],[23267,23267],[23270,23270],[23273,23275],[23277,23277],[23281,23281],[23293,23293],[23305,23305],[23318,23319],[23323,23323],[23333,23333],[23340,23340],[23346,23346],[23348,23348],[23351,23351],[23359,23360],[23365,23365],[23376,23377],[23379,23389],[23391,23391],[23394,23398],[23401,23402],[23404,23404],[23408,23409],[23411,23411],[23413,23413],[23418,23418],[23421,23421],[23424,23425],[23427,23429],[23431,23433],[23435,23436],[23439,23439],[23443,23443],[23445,23445],[23447,23454],[23456,23463],[23466,23468],[23472,23472],[23475,23478],[23480,23481],[23485,23487],[23489,23490],[23492,23495],[23500,23500],[23504,23504],[23506,23507],[23517,23519],[23521,23521],[23524,23525],[23528,23528],[23534,23534],[23536,23536],[23544,23548],[23551,23551],[23553,23553],[23556,23556],[23558,23558],[23561,23562],[23567,23567],[23569,23569],[23572,23574],[23576,23576],[23578,23578],[23580,23581],[23586,23586],[23588,23589],[23591,23592],[23594,23594],[23596,23596],[23601,23601],[23604,23604],[23608,23619],[23621,23621],[23624,23627],[23630,23633],[23637,23637],[23641,23641],[23646,23646],[23648,23649],[23651,23651],[23653,23654],[23662,23663],[23665,23665],[23673,23674],[23676,23676],[23678,23679],[23681,23682],[23688,23688],[23690,23690],[23692,23693],[23696,23697],[23700,23700],[23702,23708],[23710,23710],[23712,23712],[23714,23715],[23720,23721],[23723,23725],[23729,23729],[23731,23731],[23733,23733],[23735,23736],[23741,23741],[23743,23743],[23745,23748],[23755,23755],[23762,23762],[23767,23769],[23771,23771],[23777,23777],[23779,23784],[23786,23786],[23789,23789],[23792,23793],[23803,23803],[23807,23812],[23814,23815],[23820,23820],[23822,23822],[23826,23826],[23828,23828],[23830,23830],[23834,23835],[23838,23839],[23841,23841],[23844,23844],[23846,23847],[23849,23849],[23853,23854],[23860,23860],[23862,23862],[23869,23871],[23873,23873],[23877,23877],[23879,23879],[23882,23884],[23886,23886],[23894,23894],[23896,23896],[23898,23899],[23901,23901],[23913,23913],[23915,23916],[23919,23919],[23922,23922],[23924,23924],[23938,23938],[23941,23941],[23949,23949],[23954,23955],[23961,23961],[23965,23965],[23967,23967],[23974,23974],[23986,23986],[23991,23991],[24005,24005],[24007,24007],[24009,24009],[24013,24013],[24027,24027],[24029,24030],[24033,24034],[24037,24041],[24043,24043],[24046,24047],[24049,24052],[24055,24055],[24061,24062],[24065,24067],[24069,24070],[24072,24072],[24076,24076],[24079,24081],[24084,24086],[24088,24093],[24097,24097],[24102,24104],[24109,24110],[24113,24113],[24119,24120],[24123,24125],[24130,24130],[24132,24133],[24140,24140],[24148,24150],[24155,24155],[24158,24158],[24161,24162],[24170,24170],[24178,24180],[24182,24182],[24184,24184],[24186,24189],[24191,24192],[24196,24196],[24198,24199],[24202,24203],[24207,24209],[24211,24215],[24217,24218],[24220,24220],[24222,24224],[24228,24231],[24237,24237],[24241,24241],[24243,24243],[24245,24249],[24252,24252],[24254,24254],[24262,24262],[24265,24267],[24273,24275],[24278,24278],[24281,24281],[24283,24283],[24296,24296],[24298,24298],[24308,24308],[24310,24311],[24314,24314],[24318,24324],[24326,24328],[24330,24331],[24335,24335],[24337,24337],[24339,24339],[24341,24341],[24343,24344],[24347,24347],[24351,24352],[24354,24354],[24357,24362],[24365,24365],[24367,24367],[24369,24369],[24374,24374],[24376,24378],[24380,24380],[24384,24384],[24400,24400],[24402,24403],[24405,24408],[24413,24413],[24415,24415],[24417,24418],[24420,24420],[24422,24423],[24425,24426],[24428,24429],[24432,24433],[24435,24435],[24439,24439],[24441,24441],[24443,24444],[24448,24450],[24452,24453],[24455,24460],[24464,24464],[24466,24466],[24469,24469],[24471,24473],[24475,24476],[24481,24481],[24488,24488],[24490,24490],[24493,24494],[24501,24501],[24503,24503],[24508,24509],[24515,24518],[24521,24521],[24524,24525],[24527,24530],[24534,24537],[24541,24542],[24544,24545],[24548,24548],[24551,24551],[24554,24555],[24557,24558],[24561,24561],[24563,24563],[24565,24565],[24568,24568],[24570,24571],[24573,24582],[24586,24586],[24589,24591],[24594,24594],[24596,24598],[24601,24601],[24603,24605],[24608,24609],[24613,24619],[24623,24623],[24629,24629],[24635,24636],[24639,24639],[24641,24643],[24651,24651],[24653,24653],[24656,24656],[24658,24661],[24665,24666],[24669,24669],[24674,24676],[24679,24685],[24687,24688],[24691,24691],[24694,24694],[24696,24701],[24703,24703],[24707,24708],[24710,24710],[24712,24713],[24716,24717],[24722,24722],[24724,24724],[24726,24726],[24730,24731],[24733,24733],[24735,24736],[24738,24739],[24742,24742],[24744,24744],[24747,24749],[24751,24754],[24756,24756],[24760,24760],[24763,24764],[24773,24775],[24778,24779],[24782,24782],[24785,24785],[24788,24789],[24792,24797],[24799,24800],[24806,24809],[24811,24816],[24819,24820],[24822,24822],[24825,24826],[24832,24833],[24835,24835],[24838,24838],[24840,24841],[24845,24848],[24852,24853],[24858,24858],[24863,24864],[24867,24868],[24870,24871],[24875,24875],[24877,24877],[24895,24895],[24902,24902],[24904,24904],[24906,24906],[24908,24908],[24910,24910],[24913,24913],[24917,24917],[24925,24925],[24930,24930],[24933,24933],[24935,24936],[24940,24941],[24944,24944],[24949,24949],[24951,24951],[24971,24971],[24974,24974],[24980,24981],[24985,24985],[24989,24989],[24999,25001],[25004,25005],[25015,25015],[25018,25018],[25022,25022],[25026,25026],[25032,25032],[25034,25035],[25041,25042],[25044,25044],[25062,25062],[25077,25077],[25087,25087],[25094,25094],[25096,25096],[25098,25106],[25109,25112],[25114,25115],[25119,25119],[25121,25125],[25130,25130],[25132,25134],[25139,25140],[25143,25143],[25149,25155],[25157,25166],[25169,25172],[25176,25176],[25179,25179],[25182,25182],[25187,25187],[25190,25191],[25193,25200],[25203,25203],[25206,25206],[25209,25210],[25212,25216],[25219,25220],[25225,25226],[25233,25240],[25242,25243],[25247,25250],[25252,25253],[25256,25256],[25259,25260],[25265,25265],[25269,25269],[25273,25273],[25275,25277],[25279,25279],[25282,25290],[25292,25294],[25296,25296],[25298,25300],[25302,25308],[25311,25311],[25314,25321],[25324,25327],[25329,25329],[25331,25332],[25334,25335],[25340,25343],[25345,25346],[25351,25353],[25358,25358],[25361,25361],[25363,25363],[25366,25366],[25370,25371],[25373,25382],[25384,25384],[25386,25387],[25391,25391],[25394,25394],[25401,25402],[25405,25405],[25410,25411],[25413,25414],[25417,25417],[25419,25424],[25429,25429],[25438,25439],[25441,25443],[25447,25447],[25449,25449],[25453,25455],[25457,25457],[25462,25463],[25466,25467],[25469,25469],[25472,25472],[25474,25474],[25479,25482],[25484,25484],[25486,25488],[25490,25490],[25494,25494],[25496,25496],[25502,25502],[25504,25504],[25506,25507],[25509,25509],[25511,25514],[25516,25518],[25520,25520],[25523,25524],[25527,25528],[25530,25530],[25532,25532],[25534,25534],[25540,25540],[25542,25542],[25545,25545],[25549,25552],[25554,25554],[25557,25558],[25566,25566],[25568,25569],[25571,25571],[25577,25578],[25581,25581],[25586,25588],[25590,25590],[25592,25592],[25597,25597],[25599,25602],[25605,25605],[25611,25612],[25615,25616],[25618,25620],[25627,25628],[25630,25630],[25632,25633],[25638,25638],[25642,25642],[25644,25645],[25652,25652],[25658,25658],[25661,25661],[25663,25663],[25665,25665],[25668,25672],[25674,25674],[25679,25679],[25682,25682],[25684,25684],[25688,25688],[25691,25691],[25694,25694],[25703,25703],[25705,25705],[25709,25709],[25716,25716],[25720,25722],[25725,25725],[25730,25730],[25732,25733],[25735,25735],[25745,25746],[25749,25750],[25753,25753],[25758,25758],[25764,25764],[25769,25769],[25772,25774],[25776,25776],[25781,25781],[25783,25784],[25786,25786],[25788,25788],[25792,25792],[25794,25794],[25797,25797],[25805,25806],[25808,25808],[25810,25810],[25815,25816],[25822,25822],[25826,25826],[25828,25828],[25830,25830],[25855,25856],[25865,25865],[25874,25874],[25880,25880],[25893,25893],[25899,25899],[25902,25903],[25908,25910],[25912,25913],[25915,25915],[25917,25919],[25925,25925],[25928,25929],[25932,25932],[25935,25935],[25937,25937],[25940,25942],[25945,25945],[25947,25947],[25949,25950],[25954,25955],[25958,25958],[25961,25961],[25963,25964],[25968,25968],[25970,25970],[25972,25972],[25975,25975],[25991,25991],[25995,25996],[26000,26001],[26003,26003],[26007,26007],[26009,26009],[26011,26013],[26015,26017],[26020,26021],[26023,26023],[26025,26025],[26027,26027],[26029,26029],[26031,26032],[26038,26038],[26041,26041],[26044,26045],[26049,26049],[26051,26054],[26059,26060],[26062,26064],[26066,26066],[26070,26071],[26078,26078],[26080,26080],[26082,26082],[26085,26089],[26092,26097],[26100,26104],[26106,26107],[26111,26112],[26114,26116],[26118,26122],[26124,26124],[26126,26127],[26130,26133],[26137,26137],[26141,26141],[26143,26145],[26147,26149],[26151,26152],[26154,26155],[26157,26157],[26159,26159],[26161,26161],[26163,26166],[26170,26170],[26172,26174],[26177,26177],[26179,26179],[26181,26181],[26186,26188],[26191,26192],[26194,26199],[26201,26202],[26206,26207],[26209,26210],[26212,26212],[26214,26214],[26216,26216],[26218,26219],[26222,26225],[26228,26228],[26230,26231],[26234,26234],[26238,26238],[26242,26242],[26244,26245],[26247,26247],[26252,26252],[26257,26257],[26261,26263],[26269,26269],[26279,26280],[26286,26286],[26290,26290],[26292,26294],[26297,26297],[26302,26303],[26312,26312],[26316,26316],[26329,26329],[26331,26333],[26342,26342],[26345,26345],[26352,26352],[26354,26356],[26359,26359],[26361,26361],[26364,26364],[26366,26368],[26376,26379],[26381,26381],[26383,26384],[26387,26389],[26391,26391],[26395,26395],[26397,26397],[26399,26399],[26406,26406],[26408,26408],[26410,26413],[26415,26415],[26417,26417],[26419,26421],[26424,26424],[26426,26426],[26429,26429],[26432,26432],[26434,26436],[26438,26438],[26440,26441],[26444,26444],[26446,26449],[26451,26451],[26453,26454],[26457,26457],[26460,26460],[26462,26465],[26469,26469],[26471,26474],[26477,26477],[26479,26480],[26482,26483],[26485,26485],[26487,26487],[26491,26492],[26494,26495],[26497,26497],[26500,26501],[26503,26503],[26505,26505],[26507,26507],[26509,26509],[26512,26512],[26517,26517],[26519,26520],[26522,26522],[26524,26526],[26530,26531],[26533,26533],[26535,26536],[26538,26539],[26541,26541],[26543,26544],[26546,26547],[26549,26553],[26561,26561],[26563,26564],[26568,26568],[26570,26570],[26575,26580],[26582,26582],[26584,26586],[26588,26590],[26592,26592],[26594,26594],[26597,26597],[26601,26601],[26604,26604],[26607,26609],[26611,26612],[26615,26615],[26621,26621],[26623,26624],[26629,26629],[26631,26636],[26638,26643],[26646,26647],[26653,26653],[26655,26655],[26657,26657],[26665,26666],[26674,26676],[26679,26681],[26683,26686],[26688,26694],[26696,26698],[26700,26700],[26702,26702],[26704,26705],[26707,26709],[26720,26729],[26731,26731],[26735,26735],[26738,26738],[26740,26740],[26742,26743],[26745,26745],[26753,26753],[26755,26755],[26757,26758],[26764,26764],[26767,26767],[26771,26771],[26775,26775],[26784,26784],[26786,26787],[26790,26792],[26797,26797],[26799,26800],[26803,26805],[26812,26818],[26825,26825],[26827,26827],[26829,26829],[26832,26832],[26834,26835],[26837,26837],[26840,26840],[26842,26842],[26848,26848],[26851,26852],[26856,26856],[26858,26860],[26862,26862],[26864,26865],[26869,26869],[26873,26877],[26880,26881],[26885,26886],[26891,26891],[26893,26894],[26896,26899],[26911,26912],[26916,26916],[26922,26922],[26925,26925],[26928,26928],[26932,26932],[26936,26937],[26941,26941],[26943,26943],[26946,26946],[26962,26962],[26964,26964],[26967,26967],[26969,26970],[26973,26974],[26976,26976],[26979,26979],[26982,26982],[26985,26987],[26990,26991],[26993,26993],[26999,27001],[27004,27004],[27008,27008],[27010,27017],[27021,27021],[27025,27025],[27028,27030],[27032,27032],[27035,27036],[27047,27048],[27051,27051],[27053,27053],[27056,27057],[27060,27060],[27063,27063],[27067,27067],[27073,27073],[27075,27075],[27082,27082],[27084,27084],[27086,27086],[27088,27088],[27092,27092],[27098,27100],[27103,27104],[27117,27117],[27121,27122],[27133,27133],[27135,27135],[27146,27146],[27159,27160],[27167,27167],[27169,27169],[27176,27176],[27178,27178],[27183,27183],[27185,27185],[27189,27189],[27197,27198],[27204,27204],[27207,27207],[27216,27217],[27224,27225],[27227,27227],[27230,27230],[27233,27233],[27237,27238],[27249,27249],[27257,27257],[27260,27260],[27264,27264],[27268,27268],[27278,27278],[27280,27281],[27287,27287],[27294,27294],[27296,27296],[27305,27305],[27307,27308],[27334,27334],[27394,27394],[27424,27428],[27431,27431],[27442,27442],[27447,27451],[27454,27454],[27459,27459],[27461,27463],[27465,27465],[27468,27468],[27481,27481],[27490,27495],[27498,27498],[27513,27513],[27515,27516],[27521,27524],[27526,27527],[27529,27531],[27533,27533],[27538,27539],[27542,27542],[27546,27547],[27553,27553],[27555,27555],[27562,27562],[27571,27573],[27575,27575],[27583,27583],[27585,27586],[27589,27589],[27595,27597],[27599,27600],[27602,27607],[27609,27609],[27611,27611],[27617,27617],[27626,27627],[27631,27631],[27635,27635],[27637,27637],[27641,27641],[27645,27645],[27653,27655],[27661,27661],[27663,27665],[27667,27670],[27672,27675],[27679,27679],[27681,27682],[27684,27684],[27686,27690],[27694,27696],[27698,27698],[27700,27701],[27704,27704],[27709,27714],[27718,27723],[27728,27728],[27732,27733],[27735,27735],[27739,27745],[27748,27748],[27751,27755],[27757,27757],[27760,27760],[27762,27762],[27764,27764],[27766,27766],[27769,27769],[27773,27774],[27777,27785],[27788,27788],[27791,27792],[27795,27796],[27800,27803],[27807,27807],[27809,27809],[27811,27819],[27821,27822],[27825,27827],[27832,27839],[27842,27845],[27847,27847],[27849,27850],[27852,27852],[27856,27856],[27859,27863],[27865,27868],[27870,27870],[27872,27875],[27877,27877],[27880,27880],[27882,27883],[27886,27889],[27891,27891],[27893,27896],[27898,27902],[27905,27905],[27908,27908],[27911,27912],[27915,27916],[27918,27918],[27921,27923],[27927,27931],[27934,27934],[27938,27939],[27941,27941],[27943,27944],[27946,27947],[27949,27950],[27953,27957],[27960,27967],[27969,27969],[27971,27971],[27973,27979],[27981,27989],[27993,27996],[27998,28001],[28003,28003],[28005,28006],[28009,28010],[28012,28016],[28018,28018],[28020,28020],[28023,28024],[28028,28028],[28034,28034],[28036,28037],[28040,28041],[28044,28046],[28048,28049],[28051,28053],[28056,28056],[28059,28059],[28061,28068],[28070,28075],[28078,28079],[28082,28082],[28084,28085],[28088,28088],[28095,28096],[28100,28103],[28107,28108],[28111,28111],[28113,28113],[28118,28118],[28120,28121],[28124,28129],[28132,28132],[28134,28134],[28139,28140],[28142,28143],[28145,28145],[28147,28148],[28151,28151],[28153,28153],[28155,28156],[28165,28165],[28170,28170],[28172,28174],[28176,28177],[28180,28180],[28182,28183],[28186,28186],[28189,28189],[28191,28193],[28195,28197],[28201,28201],[28203,28203],[28205,28205],[28207,28208],[28210,28210],[28212,28212],[28216,28216],[28218,28218],[28220,28220],[28227,28228],[28233,28233],[28237,28238],[28241,28241],[28243,28244],[28246,28246],[28248,28248],[28251,28253],[28255,28255],[28259,28259],[28267,28267],[28270,28270],[28274,28274],[28276,28276],[28286,28287],[28289,28289],[28291,28291],[28293,28295],[28297,28297],[28301,28301],[28303,28304],[28312,28312],[28314,28314],[28316,28316],[28318,28320],[28322,28322],[28325,28327],[28330,28330],[28335,28335],[28337,28338],[28340,28343],[28345,28347],[28349,28349],[28353,28355],[28358,28359],[28361,28361],[28363,28363],[28365,28365],[28367,28367],[28369,28369],[28371,28373],[28375,28376],[28378,28378],[28382,28386],[28388,28395],[28404,28404],[28409,28409],[28418,28418],[28422,28422],[28424,28425],[28427,28427],[28431,28431],[28435,28438],[28448,28448],[28452,28452],[28454,28454],[28457,28459],[28461,28461],[28463,28463],[28465,28465],[28467,28468],[28470,28471],[28473,28473],[28475,28476],[28478,28478],[28486,28487],[28491,28491],[28493,28493],[28495,28495],[28502,28502],[28504,28504],[28508,28508],[28510,28511],[28514,28514],[28518,28518],[28521,28521],[28525,28526],[28530,28530],[28532,28533],[28536,28536],[28538,28538],[28540,28542],[28546,28546],[28548,28548],[28552,28553],[28556,28558],[28571,28572],[28577,28577],[28581,28581],[28583,28583],[28586,28586],[28589,28589],[28595,28596],[28598,28598],[28601,28601],[28604,28605],[28608,28608],[28610,28610],[28617,28617],[28619,28619],[28625,28626],[28638,28638],[28640,28641],[28649,28649],[28654,28655],[28684,28685],[28689,28689],[28692,28692],[28698,28699],[28707,28707],[28721,28721],[28725,28725],[28729,28729],[28732,28732],[28744,28744],[28748,28748],[28751,28751],[28766,28766],[28779,28781],[28783,28784],[28789,28790],[28792,28792],[28796,28796],[28798,28800],[28805,28806],[28809,28810],[28812,28812],[28814,28814],[28818,28818],[28820,28822],[28824,28825],[28828,28829],[28831,28831],[28835,28835],[28843,28847],[28849,28849],[28851,28851],[28855,28857],[28859,28861],[28864,28867],[28872,28872],[28874,28874],[28884,28884],[28888,28889],[28891,28893],[28895,28896],[28900,28900],[28902,28905],[28907,28909],[28911,28911],[28918,28919],[28921,28923],[28925,28925],[28934,28934],[28937,28938],[28940,28940],[28944,28944],[28947,28947],[28949,28954],[28956,28956],[28958,28958],[28966,28966],[28975,28977],[28982,28982],[28993,28993],[28995,28995],[28997,28997],[29002,29004],[29006,29006],[29011,29011],[29020,29020],[29022,29023],[29028,29028],[29030,29032],[29038,29038],[29042,29044],[29048,29048],[29050,29050],[29053,29053],[29060,29060],[29063,29063],[29066,29066],[29071,29071],[29076,29076],[29080,29081],[29083,29084],[29087,29088],[29093,29093],[29096,29096],[29100,29100],[29107,29107],[29109,29109],[29113,29113],[29115,29115],[29123,29123],[29130,29131],[29134,29135],[29140,29141],[29146,29146],[29152,29152],[29157,29157],[29159,29159],[29166,29166],[29177,29177],[29190,29191],[29204,29204],[29210,29210],[29213,29213],[29215,29215],[29224,29224],[29226,29226],[29228,29228],[29232,29233],[29237,29241],[29243,29243],[29245,29245],[29247,29247],[29249,29250],[29255,29256],[29260,29261],[29266,29266],[29270,29270],[29273,29275],[29277,29277],[29279,29279],[29281,29282],[29284,29287],[29289,29289],[29294,29295],[29298,29298],[29301,29301],[29305,29307],[29310,29313],[29316,29316],[29319,29319],[29322,29323],[29325,29325],[29327,29327],[29330,29330],[29343,29343],[29352,29352],[29356,29357],[29359,29360],[29364,29364],[29366,29369],[29377,29380],[29384,29385],[29389,29390],[29392,29392],[29394,29394],[29399,29399],[29401,29401],[29405,29406],[29408,29409],[29416,29417],[29420,29428],[29431,29432],[29434,29436],[29441,29441],[29443,29444],[29447,29447],[29450,29450],[29454,29454],[29459,29459],[29461,29463],[29467,29470],[29473,29474],[29477,29477],[29481,29484],[29486,29489],[29492,29492],[29495,29498],[29502,29503],[29517,29517],[29520,29520],[29522,29522],[29527,29527],[29536,29536],[29548,29549],[29551,29551],[29556,29556],[29566,29566],[29571,29572],[29575,29575],[29577,29577],[29579,29579],[29582,29582],[29585,29587],[29589,29590],[29592,29595],[29598,29602],[29604,29606],[29609,29609],[29611,29611],[29613,29619],[29622,29623],[29625,29628],[29631,29632],[29634,29634],[29637,29637],[29639,29645],[29647,29650],[29653,29654],[29657,29657],[29659,29659],[29661,29662],[29664,29664],[29666,29667],[29669,29671],[29673,29675],[29677,29677],[29680,29680],[29682,29682],[29685,29685],[29687,29690],[29693,29693],[29696,29696],[29699,29706],[29710,29712],[29716,29716],[29722,29723],[29727,29727],[29729,29730],[29732,29734],[29736,29736],[29738,29744],[29746,29750],[29756,29756],[29760,29766],[29777,29777],[29779,29783],[29785,29791],[29794,29794],[29799,29800],[29804,29805],[29808,29809],[29811,29811],[29814,29815],[29822,29822],[29824,29825],[29827,29827],[29830,29832],[29835,29835],[29838,29838],[29840,29840],[29842,29842],[29848,29848],[29852,29852],[29854,29856],[29861,29861],[29863,29866],[29868,29868],[29870,29870],[29873,29874],[29882,29882],[29888,29888],[29906,29906],[29910,29910],[29912,29912],[29916,29916],[29918,29918],[29920,29920],[29922,29924],[29926,29926],[29934,29935],[29940,29940],[29942,29943],[29947,29947],[29951,29951],[29956,29956],[29965,29965],[29967,29967],[29969,29969],[29971,29971],[29975,29978],[29980,29980],[29983,29983],[29985,29985],[29989,29990],[29992,29997],[29999,30003],[30005,30005],[30007,30008],[30010,30011],[30014,30014],[30016,30016],[30021,30021],[30024,30024],[30027,30028],[30030,30031],[30036,30036],[30038,30038],[30041,30044],[30052,30054],[30058,30058],[30060,30060],[30063,30063],[30066,30066],[30068,30068],[30072,30073],[30079,30079],[30081,30081],[30083,30083],[30086,30086],[30091,30091],[30093,30093],[30095,30098],[30100,30100],[30102,30103],[30105,30106],[30109,30109],[30111,30117],[30123,30133],[30136,30137],[30140,30142],[30146,30149],[30151,30154],[30157,30157],[30162,30166],[30168,30168],[30171,30171],[30174,30174],[30178,30180],[30182,30184],[30186,30187],[30192,30193],[30196,30196],[30201,30201],[30204,30204],[30207,30209],[30211,30211],[30213,30214],[30218,30218],[30220,30220],[30224,30224],[30229,30229],[30231,30233],[30235,30235],[30239,30240],[30242,30242],[30244,30246],[30249,30251],[30253,30253],[30256,30256],[30259,30261],[30264,30264],[30268,30268],[30270,30272],[30275,30275],[30284,30285],[30292,30292],[30294,30295],[30300,30300],[30302,30302],[30307,30307],[30315,30315],[30319,30319],[30328,30328],[30331,30331],[30333,30335],[30338,30338],[30340,30340],[30342,30344],[30347,30347],[30350,30350],[30353,30353],[30355,30355],[30357,30358],[30361,30361],[30363,30363],[30366,30366],[30372,30372],[30374,30374],[30381,30382],[30385,30386],[30388,30388],[30399,30399],[30402,30402],[30405,30406],[30408,30410],[30413,30418],[30420,30420],[30422,30424],[30427,30427],[30431,30431],[30437,30438],[30446,30447],[30449,30450],[30452,30452],[30455,30457],[30460,30460],[30462,30462],[30465,30465],[30468,30468],[30471,30475],[30477,30477],[30489,30490],[30495,30496],[30498,30498],[30502,30502],[30504,30505],[30508,30509],[30511,30511],[30517,30520],[30522,30522],[30524,30524],[30528,30529],[30531,30532],[30535,30535],[30542,30542],[30544,30545],[30554,30555],[30561,30563],[30565,30566],[30568,30568],[30571,30572],[30585,30585],[30589,30592],[30596,30597],[30603,30606],[30609,30610],[30623,30624],[30626,30626],[30629,30629],[30631,30631],[30633,30637],[30640,30640],[30643,30643],[30645,30645],[30651,30651],[30653,30653],[30655,30655],[30669,30669],[30679,30679],[30683,30684],[30686,30686],[30690,30691],[30693,30693],[30695,30695],[30697,30697],[30699,30702],[30704,30704],[30707,30707],[30710,30710],[30712,30712],[30715,30722],[30724,30724],[30726,30726],[30729,30729],[30732,30733],[30737,30738],[30740,30740],[30742,30744],[30746,30746],[30748,30749],[30751,30752],[30755,30755],[30757,30759],[30761,30761],[30763,30766],[30768,30768],[30772,30773],[30775,30780],[30782,30782],[30784,30785],[30789,30789],[30791,30791],[30794,30794],[30796,30798],[30800,30800],[30802,30802],[30804,30807],[30809,30810],[30813,30813],[30826,30830],[30839,30839],[30844,30844],[30847,30847],[30851,30851],[30855,30857],[30860,30863],[30865,30865],[30867,30867],[30871,30872],[30874,30876],[30879,30879],[30881,30881],[30883,30883],[30885,30885],[30887,30888],[30896,30900],[30902,30902],[30905,30905],[30910,30910],[30913,30913],[30917,30917],[30921,30923],[30927,30928],[30932,30933],[30937,30937],[30940,30940],[30945,30945],[30952,30952],[30956,30956],[30962,30962],[30964,30964],[30967,30967],[30969,30971],[30977,30977],[30981,30981],[30988,30988],[30995,30995],[31006,31006],[31012,31012],[31028,31029],[31034,31036],[31038,31038],[31040,31041],[31043,31043],[31046,31051],[31054,31056],[31059,31059],[31061,31063],[31066,31072],[31074,31074],[31077,31077],[31079,31080],[31085,31085],[31087,31087],[31090,31090],[31095,31096],[31098,31098],[31100,31100],[31102,31102],[31104,31105],[31108,31109],[31114,31115],[31119,31119],[31122,31122],[31124,31124],[31128,31128],[31130,31131],[31140,31140],[31143,31143],[31155,31155],[31161,31163],[31165,31166],[31168,31169],[31171,31171],[31174,31174],[31177,31177],[31179,31179],[31181,31181],[31185,31186],[31189,31189],[31192,31192],[31199,31199],[31203,31204],[31206,31207],[31209,31209],[31211,31213],[31215,31216],[31224,31224],[31227,31227],[31229,31230],[31232,31232],[31234,31235],[31238,31238],[31243,31246],[31249,31249],[31252,31252],[31255,31255],[31257,31258],[31262,31262],[31264,31264],[31267,31267],[31283,31283],[31287,31287],[31289,31289],[31291,31293],[31295,31295],[31300,31300],[31302,31302],[31313,31313],[31319,31319],[31321,31321],[31324,31324],[31327,31327],[31344,31344],[31348,31348],[31350,31354],[31359,31361],[31363,31366],[31368,31368],[31370,31370],[31373,31374],[31377,31378],[31381,31384],[31388,31389],[31391,31392],[31395,31395],[31397,31398],[31400,31400],[31404,31405],[31411,31411],[31416,31416],[31423,31423],[31435,31435],[31441,31441],[31446,31446],[31448,31449],[31454,31456],[31459,31459],[31461,31462],[31467,31467],[31469,31469],[31471,31471],[31481,31482],[31485,31485],[31487,31487],[31491,31492],[31494,31494],[31496,31496],[31498,31499],[31503,31503],[31505,31505],[31508,31509],[31513,31513],[31515,31515],[31518,31518],[31520,31520],[31524,31526],[31528,31528],[31530,31532],[31534,31535],[31537,31537],[31539,31539],[31544,31544],[31546,31546],[31548,31548],[31550,31550],[31552,31552],[31557,31557],[31559,31559],[31561,31561],[31563,31564],[31567,31570],[31572,31572],[31574,31574],[31576,31576],[31578,31581],[31584,31584],[31586,31586],[31588,31590],[31598,31598],[31601,31602],[31605,31607],[31609,31609],[31611,31612],[31614,31614],[31616,31616],[31621,31621],[31629,31629],[31632,31632],[31635,31639],[31644,31645],[31649,31650],[31654,31661],[31665,31665],[31668,31668],[31672,31672],[31681,31681],[31686,31687],[31692,31692],[31697,31697],[31699,31699],[31705,31706],[31709,31709],[31713,31713],[31717,31718],[31722,31722],[31726,31727],[31729,31729],[31735,31735],[31740,31740],[31742,31742],[31747,31747],[31751,31751],[31753,31753],[31755,31756],[31759,31759],[31765,31766],[31773,31773],[31775,31776],[31782,31783],[31786,31786],[31792,31792],[31800,31800],[31807,31809],[31821,31821],[31845,31845],[31859,31860],[31867,31869],[31881,31881],[31889,31890],[31893,31893],[31895,31896],[31900,31903],[31906,31906],[31908,31909],[31914,31914],[31918,31918],[31921,31923],[31929,31929],[31932,31935],[31937,31937],[31941,31941],[31943,31944],[31946,31946],[31948,31949],[31954,31954],[31957,31959],[31961,31961],[31964,31964],[31967,31968],[31976,31976],[31983,31983],[31989,31989],[31992,31992],[31995,31995],[32010,32010],[32032,32032],[32034,32034],[32039,32039],[32043,32043],[32047,32047],[32092,32092],[32110,32110],[32119,32119],[32166,32166],[32174,32174],[32288,32288],[32290,32290],[32315,32315],[32321,32321],[32324,32324],[32327,32327],[32386,32386],[32411,32411],[32415,32491],[32493,32566],[32568,32568],[32570,32570],[32578,32578],[32580,32581],[32589,32589],[32592,32593],[32596,32597],[32599,32600],[32602,32602],[32607,32607],[32609,32610],[32616,32618],[32622,32622],[32625,32626],[32628,32628],[32630,32630],[32633,32633],[32637,32638],[32641,32641],[32650,32650],[32652,32652],[32654,32654],[32657,32657],[32659,32662],[32666,32666],[32669,32671],[32673,32673],[32676,32676],[32679,32679],[32687,32690],[32696,32697],[32700,32701],[32703,32707],[32709,32709],[32712,32712],[32714,32714],[32716,32716],[32718,32718],[32724,32725],[32728,32731],[32735,32737],[32741,32742],[32745,32745],[32750,32753],[32755,32755],[32759,32759],[32763,32764],[32766,32766],[32768,32769],[32771,32775],[32779,32781],[32783,32786],[32788,32793],[32796,32796],[32800,32800],[32802,32802],[32804,32810],[32816,32817],[32819,32819],[32821,32824],[32827,32827],[32829,32829],[32831,32831],[32834,32835],[32838,32838],[32842,32845],[32850,32850],[32852,32852],[32856,32856],[32858,32858],[32873,32874],[32881,32881],[32895,32896],[32899,32900],[32902,32903],[32905,32905],[32907,32908],[32915,32915],[32918,32918],[32920,32920],[32922,32925],[32927,32930],[32932,32933],[32937,32939],[32941,32943],[32945,32946],[32948,32948],[32951,32952],[32954,32954],[32956,32964],[32966,32966],[32968,32968],[32972,32974],[32982,32983],[32985,32990],[32992,32993],[32995,32997],[32999,33005],[33007,33012],[33014,33014],[33016,33016],[33018,33018],[33020,33021],[33026,33026],[33030,33030],[33033,33034],[33037,33044],[33046,33046],[33048,33048],[33050,33050],[33054,33055],[33065,33065],[33068,33068],[33071,33071],[33073,33074],[33078,33078],[33080,33080],[33086,33087],[33094,33094],[33096,33096],[33098,33100],[33104,33109],[33112,33114],[33120,33120],[33125,33125],[33127,33129],[33133,33137],[33140,33140],[33145,33152],[33154,33154],[33160,33160],[33162,33162],[33167,33167],[33169,33169],[33176,33177],[33179,33181],[33187,33187],[33190,33190],[33192,33192],[33194,33194],[33203,33203],[33210,33211],[33216,33219],[33222,33222],[33226,33226],[33228,33228],[33233,33233],[33244,33244],[33251,33251],[33255,33255],[33258,33258],[33260,33261],[33267,33268],[33275,33276],[33278,33278],[33280,33282],[33284,33286],[33292,33293],[33296,33296],[33298,33298],[33300,33300],[33307,33308],[33310,33315],[33317,33317],[33320,33320],[33322,33325],[33327,33337],[33339,33339],[33342,33342],[33348,33349],[33351,33351],[33353,33353],[33355,33355],[33358,33359],[33368,33368],[33370,33370],[33375,33375],[33384,33384],[33390,33392],[33394,33396],[33401,33402],[33405,33407],[33410,33412],[33416,33416],[33418,33419],[33421,33423],[33425,33426],[33431,33433],[33436,33437],[33439,33441],[33443,33446],[33448,33457],[33459,33460],[33463,33465],[33468,33470],[33473,33473],[33476,33476],[33479,33487],[33489,33493],[33495,33496],[33499,33500],[33502,33505],[33507,33511],[33515,33515],[33519,33519],[33521,33521],[33524,33524],[33527,33527],[33529,33529],[33531,33531],[33534,33534],[33536,33545],[33547,33548],[33550,33551],[33553,33553],[33555,33557],[33559,33559],[33562,33565],[33575,33576],[33579,33581],[33583,33583],[33585,33585],[33587,33590],[33592,33594],[33596,33597],[33600,33601],[33603,33604],[33606,33607],[33609,33609],[33615,33620],[33622,33622],[33625,33628],[33630,33633],[33635,33647],[33655,33656],[33659,33661],[33669,33670],[33673,33673],[33678,33678],[33682,33683],[33688,33689],[33691,33694],[33696,33696],[33704,33707],[33712,33716],[33718,33722],[33724,33725],[33727,33730],[33733,33733],[33735,33735],[33737,33738],[33740,33741],[33743,33743],[33748,33748],[33750,33750],[33752,33752],[33756,33757],[33759,33761],[33765,33765],[33769,33770],[33776,33778],[33784,33785],[33788,33789],[33793,33793],[33795,33796],[33798,33798],[33803,33807],[33809,33809],[33816,33816],[33818,33818],[33820,33821],[33827,33833],[33841,33841],[33843,33843],[33848,33849],[33852,33853],[33862,33862],[33870,33870],[33873,33873],[33878,33879],[33881,33884],[33889,33889],[33891,33891],[33897,33897],[33899,33901],[33904,33905],[33907,33910],[33912,33912],[33914,33914],[33922,33922],[33924,33924],[33927,33929],[33931,33932],[33934,33934],[33936,33936],[33943,33943],[33945,33945],[33948,33948],[33951,33951],[33953,33953],[33960,33960],[33967,33967],[33969,33970],[33972,33972],[33976,33979],[33981,33981],[33983,33983],[33985,33986],[33988,33988],[33991,33991],[33993,33994],[33997,33997],[33999,34001],[34003,34003],[34006,34006],[34013,34013],[34015,34016],[34018,34019],[34021,34022],[34028,34028],[34032,34032],[34044,34044],[34047,34048],[34051,34051],[34056,34056],[34058,34058],[34060,34060],[34065,34065],[34067,34067],[34071,34071],[34074,34074],[34079,34079],[34081,34081],[34091,34092],[34103,34109],[34115,34115],[34120,34122],[34134,34135],[34137,34137],[34142,34142],[34148,34148],[34152,34152],[34160,34160],[34162,34162],[34164,34164],[34169,34171],[34174,34174],[34177,34177],[34180,34181],[34183,34183],[34191,34191],[34203,34204],[34210,34210],[34212,34212],[34216,34216],[34218,34218],[34222,34224],[34227,34227],[34231,34233],[34239,34239],[34241,34241],[34249,34249],[34255,34256],[34259,34259],[34261,34261],[34268,34268],[34271,34272],[34276,34276],[34278,34278],[34280,34281],[34299,34299],[34303,34303],[34309,34309],[34321,34321],[34326,34326],[34328,34328],[34343,34343],[34345,34345],[34360,34360],[34364,34364],[34381,34388],[34394,34394],[34398,34398],[34402,34402],[34404,34404],[34411,34412],[34414,34414],[34417,34417],[34423,34434],[34436,34436],[34438,34438],[34442,34445],[34451,34451],[34453,34453],[34460,34461],[34467,34468],[34471,34474],[34476,34476],[34479,34482],[34484,34486],[34490,34490],[34496,34496],[34499,34500],[34502,34503],[34505,34507],[34510,34513],[34516,34516],[34520,34521],[34523,34523],[34526,34527],[34532,34532],[34537,34537],[34541,34542],[34544,34548],[34552,34553],[34558,34558],[34560,34560],[34562,34563],[34567,34570],[34573,34574],[34576,34576],[34578,34579],[34581,34581],[34583,34584],[34586,34586],[34588,34588],[34590,34590],[34593,34595],[34597,34597],[34601,34601],[34606,34606],[34609,34609],[34612,34612],[34615,34615],[34619,34619],[34622,34623],[34631,34633],[34636,34636],[34638,34638],[34643,34643],[34647,34649],[34656,34656],[34659,34661],[34670,34670],[34672,34672],[34674,34674],[34676,34676],[34678,34678],[34683,34686],[34690,34691],[34693,34693],[34696,34696],[34699,34699],[34701,34701],[34707,34707],[34711,34711],[34719,34720],[34723,34723],[34728,34728],[34731,34733],[34735,34735],[34737,34737],[34739,34739],[34741,34741],[34746,34746],[34749,34749],[34752,34752],[34758,34758],[34762,34763],[34767,34767],[34769,34771],[34779,34779],[34784,34784],[34789,34789],[34794,34795],[34798,34798],[34809,34809],[34814,34814],[34819,34819],[34826,34827],[34835,34835],[34837,34838],[34843,34843],[34849,34850],[34866,34866],[34873,34873],[34876,34876],[34880,34880],[34883,34885],[34892,34894],[34898,34898],[34900,34900],[34903,34903],[34905,34905],[34912,34917],[34920,34921],[34923,34924],[34926,34926],[34928,34928],[34930,34930],[34935,34935],[34941,34943],[34945,34946],[34948,34950],[34952,34952],[34955,34955],[34957,34957],[34962,34962],[34966,34967],[34972,34972],[34978,34978],[34980,34980],[34986,34987],[34989,34989],[34991,34991],[34993,34993],[34999,34999],[35004,35004],[35009,35010],[35013,35014],[35016,35017],[35022,35022],[35026,35026],[35028,35029],[35032,35033],[35035,35035],[35039,35039],[35042,35045],[35048,35048],[35056,35057],[35059,35060],[35064,35065],[35068,35068],[35070,35070],[35074,35074],[35082,35082],[35088,35088],[35090,35091],[35093,35093],[35097,35099],[35103,35103],[35105,35105],[35109,35109],[35114,35115],[35119,35120],[35124,35124],[35126,35126],[35137,35137],[35140,35140],[35157,35157],[35162,35162],[35164,35164],[35166,35167],[35174,35174],[35179,35179],[35195,35195],[35199,35199],[35201,35201],[35203,35203],[35206,35206],[35265,35276],[35278,35282],[35286,35286],[35290,35290],[35292,35292],[35294,35295],[35299,35299],[35301,35302],[35307,35307],[35309,35309],[35311,35311],[35313,35313],[35315,35315],[35327,35328],[35332,35332],[35335,35335],[35354,35354],[35390,35390],[35400,35400],[35423,35423],[35449,35449],[35465,35466],[35475,35475],[35591,35591],[35622,35622],[35686,35686],[35692,35692],[35744,35755],[35757,35817],[35819,35848],[35850,35895],[35900,35900],[35903,35903],[35905,35905],[35910,35911],[35913,35913],[35916,35916],[35925,35925],[35930,35930],[35937,35938],[35944,35944],[35946,35947],[35950,35950],[35955,35955],[35960,35962],[35970,35970],[35973,35974],[35977,35978],[35980,35980],[35988,35988],[35992,35992],[36125,36127],[36129,36196],[36198,36199],[36202,36203],[36205,36205],[36208,36208],[36211,36215],[36225,36225],[36228,36229],[36234,36235],[36241,36241],[36244,36244],[36255,36255],[36259,36259],[36271,36271],[36273,36273],[36275,36277],[36280,36280],[36282,36282],[36284,36284],[36286,36287],[36290,36292],[36294,36294],[36299,36300],[36302,36305],[36310,36311],[36314,36315],[36317,36319],[36323,36324],[36328,36328],[36330,36332],[36335,36335],[36337,36337],[36339,36339],[36341,36347],[36349,36349],[36357,36357],[36361,36362],[36364,36364],[36367,36367],[36370,36370],[36372,36372],[36381,36383],[36386,36387],[36390,36390],[36393,36394],[36396,36396],[36398,36399],[36401,36401],[36405,36406],[36409,36410],[36413,36413],[36416,36418],[36420,36421],[36423,36427],[36432,36434],[36441,36442],[36444,36444],[36450,36450],[36454,36454],[36457,36457],[36460,36461],[36463,36464],[36466,36466],[36468,36468],[36470,36470],[36476,36479],[36481,36481],[36485,36485],[36487,36487],[36495,36496],[36500,36500],[36508,36508],[36510,36510],[36523,36524],[36527,36527],[36530,36530],[36538,36538],[36558,36558],[36710,36764],[36766,36767],[36771,36771],[36776,36777],[36779,36779],[36784,36785],[36790,36790],[36793,36793],[36797,36799],[36801,36802],[36804,36805],[36807,36808],[36814,36814],[36816,36817],[36819,36821],[36824,36825],[36827,36831],[36834,36834],[36836,36838],[36840,36843],[36845,36846],[36848,36848],[36851,36851],[36855,36858],[36861,36861],[36864,36870],[36873,36875],[36877,36877],[36879,36882],[36884,36884],[36886,36887],[36890,36891],[36893,36898],[36902,36902],[36909,36911],[36916,36918],[36920,36920],[36923,36924],[36926,36926],[36929,36930],[36932,36932],[36934,36935],[36941,36941],[36943,36947],[36951,36952],[36955,36955],[36962,36963],[36965,36965],[36968,36968],[36973,36974],[36980,36981],[36985,36985],[36989,36989],[36991,36992],[36994,36995],[37000,37000],[37003,37003],[37009,37009],[37011,37011],[37013,37013],[37015,37017],[37019,37019],[37021,37021],[37024,37027],[37030,37030],[37032,37032],[37034,37034],[37036,37036],[37038,37046],[37048,37051],[37053,37055],[37057,37057],[37059,37061],[37063,37064],[37066,37066],[37070,37073],[37075,37075],[37079,37079],[37082,37085],[37089,37090],[37092,37092],[37094,37096],[37098,37099],[37101,37101],[37103,37103],[37108,37108],[37112,37112],[37117,37120],[37122,37125],[37132,37132],[37137,37137],[37143,37146],[37148,37148],[37150,37150],[37152,37152],[37154,37155],[37163,37163],[37167,37167],[37169,37169],[37177,37177],[37186,37187],[37189,37190],[37193,37200],[37202,37202],[37207,37207],[37210,37210],[37213,37214],[37217,37222],[37225,37226],[37228,37228],[37230,37234],[37236,37242],[37245,37247],[37253,37253],[37255,37255],[37257,37257],[37259,37261],[37264,37266],[37274,37275],[37282,37283],[37288,37288],[37290,37290],[37293,37295],[37300,37301],[37306,37306],[37310,37310],[37319,37319],[37321,37322],[37324,37329],[37340,37340],[37492,37492],[37518,37518],[37550,37550],[37574,37574],[37576,37576],[37694,37694],[37738,37738],[37775,37775],[37834,37834],[37846,37846],[37950,37950],[37995,37995],[38021,38032],[38034,38086],[38088,38098],[38101,38117],[38119,38175],[38177,38262],[38271,38271],[38376,38379],[38381,38418],[38420,38426],[38428,38429],[38431,38431],[38433,38434],[38442,38442],[38446,38446],[38449,38454],[38459,38461],[38463,38464],[38466,38466],[38468,38473],[38475,38478],[38480,38481],[38484,38485],[38491,38491],[38494,38495],[38497,38498],[38500,38500],[38503,38506],[38508,38508],[38514,38514],[38516,38519],[38531,38531],[38533,38534],[38536,38536],[38539,38539],[38541,38541],[38543,38544],[38548,38548],[38551,38553],[38556,38556],[38567,38567],[38569,38569],[38576,38576],[38579,38579],[38582,38582],[38585,38586],[38588,38590],[38592,38593],[38596,38599],[38601,38602],[38604,38607],[38610,38610],[38613,38613],[38624,38624],[38632,38634],[38639,38639],[38641,38641],[38643,38643],[38646,38647],[38649,38649],[38654,38654],[38656,38657],[38660,38665],[38669,38671],[38675,38675],[38678,38678],[38684,38684],[38686,38686],[38696,38696],[38698,38698],[38701,38701],[38704,38704],[38706,38706],[38712,38713],[38718,38718],[38738,38739],[38742,38742],[38745,38745],[38747,38747],[38750,38750],[38752,38754],[38757,38757],[38761,38761],[38764,38764],[38768,38768],[38771,38772],[38774,38774],[38776,38776],[38778,38778],[38780,38781],[38783,38783],[38785,38785],[38789,38789],[38795,38795],[38797,38797],[38801,38802],[38804,38804],[38808,38808],[38816,38817],[38819,38819],[38823,38824],[38827,38831],[38834,38836],[38850,38850],[38886,38893],[38899,38899],[38901,38902],[39029,39057],[39059,39060],[39062,39074],[39076,39079],[39118,39125],[39127,39130],[39134,39135],[39143,39144],[39181,39181],[39184,39184],[39214,39214],[39252,39253],[39267,39267],[39269,39269],[39271,39293],[39295,39297],[39299,39309],[39311,39321],[39325,39326],[39333,39333],[39335,39336],[39532,39571],[39573,39592],[39600,39601],[39606,39608],[39610,39610],[39612,39612],[39616,39619],[39621,39621],[39627,39628],[39630,39630],[39633,39633],[39635,39635],[39640,39640],[39647,39647],[39649,39650],[39654,39654],[39659,39659],[39661,39661],[39663,39663],[39673,39673],[39675,39675],[39677,39677],[39683,39683],[39688,39688],[39695,39695],[39698,39699],[39704,39704],[39711,39711],[39715,39715],[39727,39727],[39730,39730],[39734,39735],[39739,39740],[39745,39753],[39755,39755],[39757,39757],[39759,39759],[39761,39761],[39764,39764],[40060,40067],[40069,40082],[40084,40164],[40479,40499],[40501,40530],[40532,40548],[40550,40564],[40574,40576],[40578,40578],[40583,40584],[40587,40587],[40593,40595],[40598,40598],[40605,40605],[40607,40607],[40614,40614],[40628,40628],[40632,40633],[40635,40635],[40637,40638],[40644,40644],[40647,40647],[40649,40649],[40653,40655],[40657,40657],[40660,40660],[40664,40664],[40667,40669],[40671,40674],[40677,40677],[40679,40679],[40681,40682],[40687,40687],[40697,40697],[40699,40700],[40702,40702],[40715,40715],[40717,40718],[40720,40720],[40722,40723],[40727,40727],[40729,40729],[40736,40736],[40738,40738],[40745,40745],[40747,40748],[40751,40751],[40753,40753],[40759,40759],[40761,40761],[40763,40763],[40765,40766],[40769,40769],[40772,40772],[40775,40775],[40777,40777],[40784,40785],[40831,40844],[40857,40859],[40863,40864],[40866,40866],[40909,40911],[65072,65103],[65281,65470],[65474,65479],[65482,65487],[65490,65495],[65498,65500],[65504,65510],[65512,65518],[131428,131428],[132726,132726],[134352,134352],[136090,136090],[136211,136211],[144843,144843],[146583,146584],[146979,146979],[149979,149979],[150141,150141],[150217,150217],[152882,152882],[152930,152930],[153000,153000],[155351,155351],[156193,156193],[156813,156813],[157302,157302],[157564,157564],[158556,158556],[158753,158753],[163833,163833],[164872,164872],[165496,165496],[165525,165525],[165856,165856],[166729,166729],[166983,166983],[166991,166991],[166993,166993],[166996,166996],[167577,167577],[171902,171902],[171907,171907],[171916,171916],[174045,174045],[174331,174331],[174359,174359],[174640,174640],[174646,174646],[174680,174680],[176034,176034],[176423,176424],[176439,176440],[176621,176621],[176896,176896],[176995,176995],[177007,177007],[177010,177010],[177021,177021],[177156,177156],[177168,177168],[177171,177171],[177249,177249],[177383,177383],[177391,177391],[177398,177398],[177401,177401],[177421,177422],[177462,177462],[177582,177583],[177587,177587],[177639,177639],[177652,177652],[177692,177693],[177702,177704],[177706,177706],[177708,177708],[177813,177814],[177837,177837],[177901,177901],[178089,178089],[178117,178117],[178150,178150],[178169,178169],[178172,178172],[178182,178182],[178186,178186],[178204,178204],[178360,178360],[178887,178887],[179039,179039],[179042,179042],[179068,179068],[179075,179075],[179227,179227],[179575,179575],[179591,179591],[179703,179703],[179753,179753],[180265,180266],[180393,180393],[180426,180426],[180693,180693],[180697,180697],[180729,180729],[180860,180860],[180872,180872],[180900,180900],[181015,181015],[181083,181083],[181089,181089],[181092,181092],[181384,181384],[181396,181396],[181399,181399],[181570,181570],[181779,181779],[181784,181784],[181793,181793],[181801,181801],[181803,181805],[181807,181807],[181826,181826],[181834,181835],[182060,182060],[182063,182063],[182175,182175],[182209,182209],[182269,182269],[182489,182489],[182494,182494],[182497,182497],[182515,182515],[182535,182535],[182538,182538],[182557,182557],[182786,182786],[182798,182798],[182909,182909],[182953,182953],[183081,183081],[183085,183086],[183089,183089],[183096,183097],[183099,183099],[183103,183103],[183105,183105],[183114,183114],[183118,183118],[183130,183131],[183140,183140],[183145,183145],[183148,183148],[183151,183151],[183155,183155],[183158,183158],[183160,183160],[183164,183164],[183217,183217],[183231,183232],[183246,183246],[183382,183382],[183391,183391],[183541,183542],[183549,183549],[183551,183551],[183554,183555],[183562,183562],[183691,183691],[183693,183693],[183695,183696],[183711,183712],[183720,183720],[183725,183726],[183765,183765],[183832,183832],[183834,183834],[183843,183843],[183846,183846],[183850,183850],[183932,183932],[183944,183944],[183955,183955]]}}};
diff --git a/web/editor_text_layout.js b/web/editor_text_layout.js
new file mode 100644
index 0000000..2d5a960
--- /dev/null
+++ b/web/editor_text_layout.js
@@ -0,0 +1,69 @@
+// Canvas/Pillow use the same wrapping, baseline and backing geometry.
+import {fontCSS, fontStack, loadFonts, FONT_KEYS} from './fonts.js';
+let tablePromise;
+export function loadCoverage() {
+ return tablePromise ||= import('./editor_text_coverage.js').then(module => module.default).catch(e => { tablePromise=null; throw e; });
+}
+export const loadTextFonts = () => loadFonts(FONT_KEYS.flatMap(k => [[k,400],[k,700]]));
+// Text and subtitles never borrow another family: a missing character shows the box, as export refuses it.
+export const textFontStack = name => fontStack(name, {alone: true});
+export function missingGlyphs(text, font, bold, table) {
+ const ranges=table[font][bold ? '700' : '400'].ranges;
+ const contains=cp=>{let lo=0,hi=ranges.length;while(lo<hi){const mid=(lo+hi)>>>1;if(ranges[mid][0]<=cp)lo=mid+1;else hi=mid;}return lo>0&&cp<=ranges[lo-1][1];};
+ return [...new Set(Array.from(text))].filter(c => !['\n','\t'].includes(c) && !contains(c.codePointAt(0)));
+}
+export function wrapText(text, measure, width) {
+ const lines=[];
+ for (const paragraph of text.replaceAll('\t',' ').split('\n')) {
+ let line='', advance=0;
+ for (const char of paragraph) {
+ const amount=measure(char);
+ if (line && advance+amount>width) { lines.push(line); line=''; advance=0; }
+ line+=char; advance+=amount;
+ }
+ lines.push(line);
+ }
+ return lines;
+}
+export function textLayout(ctx,text,style,kind,width,height) {
+ const size=Math.max(1,Math.round(style.size*height));
+ ctx.font=fontCSS(style.font, style.bold ? 700 : 400, size, {alone: true});
+ ctx.textBaseline='alphabetic'; ctx.textAlign='left'; ctx.fontKerning='none';
+ const metric=c=>ctx.measureText(c), measure=c=>metric(c).width;
+ const allLines=wrapText(text,measure,width*.86), lines=kind==='subtitle' ? allLines.slice(0,2) : allLines;
+ const advances=lines.map(line=>Array.from(line).reduce((x,c)=>x+measure(c),0));
+ const boxes=lines.map(line=>{
+ let x=0,box=null;
+ for(const char of line) {
+ const m=metric(char), b=[x-m.actualBoundingBoxLeft,-m.actualBoundingBoxAscent,x+m.actualBoundingBoxRight,m.actualBoundingBoxDescent];
+ if(b[2]>b[0] && b[3]>b[1]) box=box ? [Math.min(box[0],b[0]),Math.min(box[1],b[1]),Math.max(box[2],b[2]),Math.max(box[3],b[3])] : b;
+ x+=m.width;
+ }
+ return box || [0,-size*.8,0,0];
+ });
+ const top=Math.min(...boxes.map((b,i)=>b[1]+i*size*1.2)), bottom=Math.max(...boxes.map((b,i)=>b[3]+i*size*1.2));
+ const stroke=style.backing==='outline' ? Math.max(1,Math.round(size*.06)) : 0;
+ const w=Math.max(...advances,0), h=bottom-top+stroke*2, x=width*(style.x??.5)-w/2;
+ const y=kind==='subtitle' ? style.position==='top' ? height*style.margin : height*(1-style.margin)-h : height*style.y-h/2;
+ const align=style.align||'center';
+ return {lines,size,stroke,overTwo:allLines.length>2,bounds:[x-stroke,y,w+2*stroke,h],positions:advances.map((a,i)=>[x+(w-a)*(align==='left'?0:align==='right'?1:.5),y+stroke-top+i*size*1.2])};
+}
+export function drawText(ctx,entry,width,height) {
+ const style=entry.style, layout=textLayout(ctx,entry.text,style,entry.text_kind,width,height);
+ ctx.save(); ctx.globalAlpha=entry.opacity??1;
+ const [x,y,w,h]=layout.bounds,size=layout.size;
+ if(style.backing==='box') {
+ ctx.fillStyle='rgba(0,0,0,.6)'; ctx.beginPath(); ctx.roundRect(x-size*.5,y-size*.15,w+size,h+size*.3,size*.15); ctx.fill();
+ }
+ ctx.lineWidth=layout.stroke*2; ctx.lineJoin='round';
+ for(let i=0;i<layout.lines.length;i++) {
+ let [x,y]=layout.positions[i];
+ for(const char of layout.lines[i]) {
+ if(layout.stroke) { ctx.strokeStyle='rgba(0,0,0,.85)'; ctx.strokeText(char,x,y); }
+ ctx.fillStyle=style.color; ctx.fillText(char,x,y); x+=ctx.measureText(char).width;
+ }
+ }
+ ctx.restore(); return layout;
+}
+export const overTwoHint=t=>t('Over two lines','超过两行');
+export const missingHint=(chars,t)=>chars.length ? t(`This font is missing: ${chars.join(' ')}`,`这款字体缺少:${chars.join(' ')}`) : '';
diff --git a/web/editor_text_model.js b/web/editor_text_model.js
new file mode 100644
index 0000000..ccd5b01
--- /dev/null
+++ b/web/editor_text_model.js
@@ -0,0 +1,120 @@
+// Text records use the ordinary clip envelope so timeline gestures/history stay shared.
+// Media lanes keep their on-disk order; displayTracks puts overlays above them.
+import * as model from './editor_model.js';
+export const TEXT_LIMIT = 8000;
+export const TEXT_DEFAULTS = Object.freeze({font: 'sans', size: 64 / 1080, color: '#ffffff', backing: 'outline', bold: true, align: 'center', x: .5, y: .5, fade: false});
+export const SUBTITLE_DEFAULTS = Object.freeze({font: 'sans', size: 44 / 1080, color: '#ffffff', backing: 'outline', position: 'bottom', margin: .08});
+export const isText = clip => ['text', 'subtitle'].includes(clip?.text_kind);
+export const isTextTrack = track => ['text', 'subtitle'].includes(track?.kind);
+export const hasTextData = record => record?.subtitle_style !== undefined || record?.tracks?.some(isTextTrack);
+export const displayTracks = record => [...record.tracks.filter(t => t.kind === 'subtitle'), ...record.tracks.filter(t => t.kind === 'text'), ...record.tracks.filter(t => !isTextTrack(t))];
+export const defaults = kind => kind === 'subtitle' ? SUBTITLE_DEFAULTS : TEXT_DEFAULTS;
+export const styleOf = (record, clip) => ({...defaults(clip.text_kind), ...(clip.text_kind === 'subtitle' ? record.subtitle_style : clip.text_style)});
+const check = (ok, code = 'text') => { if (!ok) throw new model.EditError(code); };
+const object = v => !!v && typeof v === 'object' && !Array.isArray(v);
+const whole = (v, low = 0) => Number.isSafeInteger(v) && v >= low && v <= 1e7;
+export function cleanStyle(raw = {}, kind = 'text') {
+ check(object(raw)); const base = defaults(kind), result = {};
+ for (const [key, value] of Object.entries(raw)) {
+ check(Object.hasOwn(base, key));
+ if (key === 'font') check(['sans', 'serif', 'kai', 'mono'].includes(value));
+ else if (key === 'size') check(typeof value === 'number' && Number.isFinite(value) && value >= 16 / 1080 && value <= 200 / 1080);
+ else if (key === 'color') check(typeof value === 'string' && /^#[0-9a-fA-F]{6}$/.test(value));
+ else if (key === 'backing') check(['none', 'outline', 'box'].includes(value));
+ else if (key === 'align') check(['left', 'center', 'right'].includes(value));
+ else if (key === 'position') check(['top', 'bottom'].includes(value));
+ else if (key === 'bold' || key === 'fade') check(typeof value === 'boolean');
+ else check(typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 1);
+ const normalized = key === 'color' ? value.toLowerCase() : value;
+ if (normalized !== base[key]) result[key] = normalized;
+ }
+ return result;
+}
+const freeze = value => { if (value && typeof value === 'object') { Object.values(value).forEach(freeze); Object.freeze(value); } return value; };
+export function readTextProject(raw, parseMedia) {
+ check(Array.isArray(raw.tracks) && raw.tracks.length <= 5, 'track');
+ const media = {...raw, tracks: raw.tracks.filter(t => !isTextTrack(t))}; delete media.subtitle_style;
+ const result = structuredClone(parseMedia(media)), ids = new Set(result.tracks.flatMap(t => t.clips.map(c => c.id))), seen = new Set();
+ for (const track of raw.tracks.filter(isTextTrack)) {
+ check(!seen.has(track.kind) && track.id === (track.kind === 'text' ? 't1' : 's1'), 'track'); seen.add(track.kind);
+ check(Array.isArray(track.clips) && track.clips.length <= 500, 'track');
+ const row = {id: track.id, kind: track.kind, clips: []};
+ for (const flag of ['hidden', 'locked']) { check(track[flag] === undefined || typeof track[flag] === 'boolean'); if (track[flag]) row[flag] = true; }
+ let end = 0;
+ for (const c of track.clips) {
+ check(object(c) && typeof c.id === 'string' && /^c[1-9]\d{0,8}$/.test(c.id) && !ids.has(c.id) && Number(c.id.slice(1)) <= raw.serial, 'id'); ids.add(c.id);
+ check(whole(c.start) && whole(c.frames, 1) && whole(c.start + c.frames), 'range'); check(c.start >= end, 'overlap'); end = c.start + c.frames;
+ check(c.text_kind === undefined || c.text_kind === track.kind);
+ check(typeof c.text === 'string' && Array.from(c.text).length <= TEXT_LIMIT && !/[\u0000-\u0008\u000b-\u001f\u007f\ud800-\udfff]/u.test(c.text));
+ check(['source','pending','link','part','job','reason'].every(k => c[k] == null) && (c.extend === undefined || c.extend === false) && (c.versions === undefined || (Array.isArray(c.versions) && c.versions.length === 0)));
+ check((c.in === undefined || c.in === 0) && (c.length === undefined || c.length === c.frames));
+ check(!['volume', 'fit', 'splice', 'target_frames', 'text_by', 'ref', 'take', 'made_text'].some(k => c[k] !== undefined));
+ const clip = {id: c.id, start: c.start, frames: c.frames, in: 0, length: c.frames, source: null, link: null,
+ text: c.text, part: null, pending: null, reason: null, job: null, extend: false, versions: [], text_kind: track.kind};
+ check(track.kind !== 'subtitle' || c.text_style === undefined);
+ if (track.kind === 'text') { const style = cleanStyle(c.text_style); if (Object.keys(style).length) clip.text_style = style; }
+ row.clips.push(clip);
+ }
+ if (row.clips.length) result.tracks.push(row);
+ }
+ const style = cleanStyle(raw.subtitle_style, 'subtitle');
+ if (Object.keys(style).length && result.tracks.some(t => t.kind === 'subtitle')) result.subtitle_style = style;
+ result.tracks.sort((a,b) => ['v1','a1','a2','t1','s1'].indexOf(a.id) - ['v1','a1','a2','t1','s1'].indexOf(b.id));
+ return freeze(result);
+}
+export function assertUnlocked(record, ids) {
+ check(!record.tracks.some(t => t.locked && t.clips.some(c => ids.includes(c.id))), 'locked');
+}
+export function addText(record, {kind = 'text', at = 0, text = '', style, frames = kind === 'subtitle' ? 48 : 72} = {}) {
+ check(['text', 'subtitle'].includes(kind));
+ const next = model.serialize(record); let row = next.tracks.find(t => t.kind === kind);
+ check(!row?.locked, 'locked');
+ if (!row) { row = {id: kind === 'text' ? 't1' : 's1', kind, clips: []}; next.tracks.push(row); }
+ row.clips.push({id: `c${++next.serial}`, start: at, frames, text, ...(style && kind === 'text' ? {text_style: style} : {})});
+ row.clips.sort((a,b) => a.start-b.start); return model.parse(next);
+}
+export function changeText(record, id, changes) {
+ assertUnlocked(record, [id]); const next = model.serialize(record), c = model.find(next, id); check(isText(c), 'missing');
+ check(Object.keys(changes).every(k => ['text','start','frames','text_style'].includes(k)));
+ Object.assign(c, changes); c.length = c.frames;
+ next.tracks.forEach(t => t.clips.sort((a,b) => a.start-b.start)); return model.parse(next);
+}
+export function changeSubtitleStyle(record, changes) {
+ assertUnlocked(record, record.tracks.filter(t => t.kind === 'subtitle').flatMap(t => t.clips.map(c => c.id)));
+ return model.parse({...record, subtitle_style: cleanStyle({...record.subtitle_style, ...changes}, 'subtitle')});
+}
+export function trimText(record, id, edge, frame) {
+ const clip = model.find(record,id), end = clip.start + clip.frames, minimum = Math.min(24, clip.frames);
+ const start = edge === 'start' ? Math.max(0, Math.min(end - minimum, frame)) : clip.start;
+ const stop = edge === 'end' ? Math.max(start + minimum, frame) : end;
+ return changeText(record, id, {start, frames: stop-start});
+}
+export function setTextTrack(record, id, flag, value) {
+ check(['hidden','locked'].includes(flag) && typeof value === 'boolean');
+ const next = model.serialize(record), track = next.tracks.find(t => t.id === id); check(isTextTrack(track), 'track');
+ track[flag] = value; return model.parse(next);
+}
+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) {
+ 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'};
+ });
+}
+// An import replaces every subtitle already there, in one edit that one undo reverses.
+export function importSRT(record, text) {
+ const entries = parseSRT(text), next = model.serialize(record);
+ let row = next.tracks.find(t => t.kind === 'subtitle'); check(!row?.locked, 'locked');
+ if (!row) { row = {id: 's1', kind: 'subtitle', clips: []}; next.tracks.push(row); }
+ row.clips = entries.map(entry => ({id: `c${++next.serial}`, start: entry.at, frames: entry.frames, text: entry.text}));
+ return model.parse(next);
+}
diff --git a/web/editor_tracks.css b/web/editor_tracks.css
new file mode 100644
index 0000000..efd73dd
--- /dev/null
+++ b/web/editor_tracks.css
@@ -0,0 +1,96 @@
+.fv-ed-track-view{position:relative;box-sizing:border-box;height:236px;min-width:0;overflow:hidden;background:var(--fv-bg);color:var(--fv-ink);font:13px/1.4 var(--fv-font,system-ui);--fv-ed-head-width:104px}
+.fv-ed-track-view *{box-sizing:border-box}
+.fv-ed-track-view button,.fv-ed-track-view input{font:inherit;color:inherit}
+.fv-ed-track-view button{appearance:none}
+.fv-ed-track-view:focus-visible{outline:none}
+.fv-ed-track-view :focus-visible{outline:2px solid var(--fv-accent);outline-offset:2px}
+.fv-ed-track-heads{position:absolute;inset:0 auto 40px 0;width:var(--fv-ed-head-width);border-right:1px solid var(--fv-border);z-index:2;background:var(--fv-bg)}
+.fv-ed-track-view:where(:has(.fv-ed-track-row[data-track=a2])){height:260px}
+.fv-editor .fv-ed-track-heads,.fv-editor .fv-ed-track-scroll{bottom:0}
+.fv-ed-track-view .fv-ed-add-audio{position:absolute;left:0;width:100%;height:28px;padding:0 4px;border:0;border-radius:0;background:transparent;color:var(--fv-muted);font:400 13px/1.4 var(--fv-font,system-ui);text-align:center;white-space:nowrap;overflow:hidden;cursor:pointer}
+.fv-ed-track-view .fv-ed-add-audio:hover:not(:disabled){color:var(--fv-ink)}
+.fv-ed-track-view .fv-ed-add-audio:disabled{opacity:.4;cursor:default}
+.fv-ed-track-view .fv-ed-track-head{position:absolute;left:0;width:100%;display:flex;align-items:center;justify-content:center;gap:6px;font-size:13px;color:var(--fv-ink)}
+.fv-ed-track-view .fv-ed-track-head svg{width:16px;height:16px;flex:none;fill:none;stroke:currentColor;stroke-width:1.4;stroke-linejoin:round;stroke-linecap:round}
+.fv-ed-track-scroll{position:absolute;left:var(--fv-ed-head-width);top:0;right:0;bottom:40px;overflow-x:auto;overflow-y:hidden;scrollbar-width:thin;scrollbar-color:var(--fv-border) transparent;overscroll-behavior:contain}
+.fv-ed-track-content{position:relative;min-height:134px;touch-action:none;user-select:none}
+.fv-ed-ruler{position:absolute;left:0;top:0;right:0;height:24px;overflow:hidden;border-bottom:1px solid var(--fv-border);cursor:crosshair;touch-action:none}
+.fv-ed-tick{position:absolute;bottom:0;height:5px;border-left:1px solid var(--fv-border);pointer-events:none}
+.fv-ed-tick-major{height:8px}
+.fv-ed-tick-major span{position:absolute;left:4px;bottom:6px;white-space:nowrap;font-size:11px;color:var(--fv-muted);font-variant-numeric:tabular-nums}
+.fv-ed-track-row{position:absolute;left:0;right:0;background:var(--fv-card);border-radius:8px}
+.fv-ed-track-row::before{content:"";position:absolute;inset:0;border:1px solid var(--fv-border);border-radius:inherit;pointer-events:none}
+.fv-ed-track-empty{position:sticky;left:0;max-width:100%;height:100%;display:flex;align-items:center;justify-content:center;padding:0 16px;overflow:hidden;white-space:nowrap;font-size:13px;color:var(--fv-muted);pointer-events:none;opacity:1;transition:opacity 150ms ease}
+.fv-ed-track-empty.fv-ed-hint-obscured{opacity:0}
+@media(prefers-reduced-motion:reduce){.fv-ed-track-empty{transition:none}}
+.fv-ed-clip{position:absolute;top:0;height:100%;display:block;padding:0;margin:0;min-width:0;overflow:hidden;border:0;border-radius:8px;background:var(--fv-card);cursor:grab;touch-action:none;isolation:isolate;--fv-ed-progress:0}
+.fv-ed-clip.fv-ed-joined-left{border-top-left-radius:0;border-bottom-left-radius:0}
+.fv-ed-clip.fv-ed-joined-left[data-state=planned],.fv-ed-clip.fv-ed-joined-left[data-state=failed]{border-left-width:0}
+.fv-ed-clip.fv-ed-joined-right{border-top-right-radius:0;border-bottom-right-radius:0;border-right:1px solid var(--fv-border)}
+.fv-ed-clip-media,.fv-ed-progress-fill,.fv-ed-block-progress{position:absolute;inset:0;pointer-events:none}
+.fv-ed-clip-media{background-repeat:repeat-x;background-position:left center;background-size:auto 100%}
+.fv-ed-waveform{width:100%;height:100%;display:block;stroke:color-mix(in srgb,var(--fv-accent) 55%,transparent);stroke-width:1;fill:none}
+.fv-ed-clip[data-state=planned]{border:1px dashed color-mix(in srgb,var(--fv-ink) 28%,transparent);background:color-mix(in srgb,var(--fv-ink) 3%,transparent)}
+.fv-ed-clip[data-state=running]{background:var(--fv-card)}
+.fv-ed-progress-fill{display:none;right:auto;width:calc(var(--fv-ed-progress) * 100%);background:color-mix(in srgb,var(--fv-accent) 55%,transparent)}
+.fv-ed-clip[data-state=running] .fv-ed-progress-fill:not([hidden]){display:block}
+.fv-ed-block-progress{display:none}
+.fv-ed-clip[data-state=running] .fv-ed-block-progress{display:block}
+.fv-ed-clip[data-state=failed]{border:1px solid color-mix(in srgb,var(--fv-warning) 60%,transparent);background:color-mix(in srgb,var(--fv-warning) 12%,transparent);cursor:grab}
+.fv-ed-clip-status{position:absolute;left:10px;right:4px;top:50%;transform:translateY(-50%);display:flex;align-items:center;gap:4px;font-size:12px;white-space:nowrap;overflow:hidden;color:var(--fv-warning);pointer-events:none}
+.fv-ed-clip-status svg{width:12px;height:12px;flex:none;fill:none;stroke:currentColor;stroke-width:1.5;stroke-linecap:round}
+.fv-ed-clip[data-busy=true]{cursor:default}
+.fv-ed-trim-handle{position:absolute;top:50%;width:4px;height:20px;border-radius:2px;transform:translateY(-50%);background:var(--fv-accent);cursor:ew-resize;z-index:2;opacity:0;pointer-events:auto}
+.fv-ed-trim-start{left:-2px}
+.fv-ed-trim-end{right:-2px}
+.fv-ed-clip[data-busy=true] .fv-ed-trim-handle{display:none}
+.fv-ed-clip.fv-ed-dragging,.fv-ed-selection.fv-ed-dragging{opacity:.85;z-index:4;cursor:grabbing}
+.fv-ed-track-overlays{position:absolute;inset:0;pointer-events:none;z-index:5}
+.fv-ed-selection{position:absolute;border:2px solid var(--fv-accent);border-radius:8px}
+.fv-ed-selection.fv-ed-range,.fv-ed-selection.fv-ed-planned-selection,.fv-ed-gesture-preview{position:absolute;border:1.5px dashed var(--fv-accent);border-radius:8px;background:color-mix(in srgb,var(--fv-accent) 8%,transparent)}
+.fv-ed-selection.fv-ed-gap{border:1.5px dashed var(--fv-accent);background:color-mix(in srgb,var(--fv-accent) 8%,transparent)}
+.fv-ed-range-border{position:absolute;top:0;bottom:0;border-left:1px dashed var(--fv-accent);cursor:ew-resize;pointer-events:auto}
+.fv-ed-range-border:before{content:"";position:absolute;top:0;bottom:0;left:-6px;width:12px}
+.fv-ed-boundary-handle{position:absolute;left:-2px;top:50%;transform:translateY(-50%);width:4px;height:14px;border-radius:2px;background:var(--fv-accent);opacity:0}
+.fv-ed-range-border:hover .fv-ed-boundary-handle,.fv-ed-range-border[data-limited=true] .fv-ed-boundary-handle{opacity:1}
+.fv-ed-range-border[data-limited=true]{border-color:var(--fv-warning)}
+.fv-ed-range-border[data-limited=true] .fv-ed-boundary-handle{background:var(--fv-warning)}
+.fv-ed-snap-line,.fv-ed-insertion-line{position:absolute;top:24px;bottom:0;width:1px;background:var(--fv-accent)}
+.fv-ed-insertion-line{width:2px;background:var(--fv-ink)}
+.fv-ed-insertion-line:before{content:"";position:absolute;top:-3px;left:-3px;width:8px;height:6px;background:inherit;clip-path:polygon(0 0,100% 0,50% 100%)}
+.fv-ed-playhead{position:absolute;top:18px;width:1px;background:var(--fv-ink);z-index:6;pointer-events:none}
+.fv-ed-playhead-handle{position:absolute;left:-4px;top:0;width:9px;height:8px;padding:0;border:0;border-radius:2px;background:var(--fv-ink);cursor:ew-resize;pointer-events:auto;touch-action:none}
+.fv-ed-track-zoom{position:absolute;right:12px;bottom:8px;display:flex;align-items:center;gap:4px;height:28px}
+.fv-ed-track-zoom button{display:grid;place-items:center;height:28px;min-width:24px;padding:0 3px;border:0;border-radius:6px;background:transparent;color:var(--fv-muted);cursor:pointer}
+.fv-ed-track-zoom button:hover{background:var(--fv-card);color:var(--fv-ink)}
+.fv-ed-zoom-slider{width:64px;height:24px;margin:0;accent-color:var(--fv-accent);cursor:pointer}
+.fv-ed-track-zoom .fv-ed-fit{padding:0 7px;white-space:nowrap;font-size:12px;margin-left:4px}
+.fv-ed-drag-label{position:absolute;z-index:9;padding:4px 7px;background:var(--fv-card);color:var(--fv-ink);border:1px solid var(--fv-border);border-radius:6px;font-size:12px;white-space:pre;line-height:1.5;pointer-events:none}
+.fv-ed-clip-popover{position:absolute;z-index:10;width:240px;max-width:calc(100% - 16px);padding:10px;border:1px solid var(--fv-border);border-radius:8px;background:var(--fv-card)}
+.fv-ed-clip-popover p{margin:0 0 8px;font-size:13px}
+.fv-ed-clip-popover button{min-height:32px;padding:4px 10px;border:1px solid var(--fv-border);border-radius:8px;background:var(--fv-raised);cursor:pointer}
+.fv-ed-track-view [hidden]{display:none!important}
+@media(max-width:520px){.fv-ed-track-view{--fv-ed-head-width:32px}.fv-ed-track-head span{display:none}.fv-ed-track-zoom{right:8px}.fv-ed-clip-status{left:5px;font-size:11px}}
+@media(forced-colors:active){.fv-ed-clip,.fv-ed-selection,.fv-ed-gesture-preview{border-color:Highlight}.fv-ed-playhead,.fv-ed-snap-line{background:CanvasText}}
+
+/* Gesture affordances; track slots and heads are owned by the track layout. */
+.fv-ed-selection.fv-ed-range{pointer-events:auto;cursor:grab}
+.fv-ed-selection .fv-ed-trim-handle{opacity:1}
+.fv-ed-clip[data-state=planned],.fv-ed-clip[data-state=failed]{overflow:visible}
+.fv-ed-clip[data-state=planned]:hover{border-color:color-mix(in srgb,var(--fv-ink) 45%,transparent)}
+.fv-ed-clip:not([data-busy=true]):hover .fv-ed-trim-handle{opacity:1;background:color-mix(in srgb,var(--fv-ink) 45%,transparent)}
+.fv-ed-clip[aria-selected=true] .fv-ed-trim-handle{opacity:1;background:var(--fv-accent)}
+.fv-ed-planned-label{position:absolute;top:6px;left:8px;right:4px;font-size:12px;color:var(--fv-muted);text-align:left;white-space:nowrap;overflow:hidden;pointer-events:none}
+.fv-ed-selection .fv-ed-planned-label,.fv-ed-clip[aria-selected=true] .fv-ed-planned-label{color:var(--fv-ink)}
+.fv-ed-track-view[data-cursor=ew-resize] .fv-ed-track-content,.fv-ed-track-view[data-cursor=ew-resize] .fv-ed-track-content *{cursor:ew-resize}
+.fv-ed-track-view[data-cursor=grabbing] .fv-ed-track-content,.fv-ed-track-view[data-cursor=grabbing] .fv-ed-track-content *{cursor:grabbing}
+
+.fv-ed-clip[aria-selected=true][data-state=planned] .fv-ed-trim-handle,.fv-ed-clip[aria-selected=true][data-state=failed] .fv-ed-trim-handle{opacity:0}
+
+.fv-ed-selection.fv-ed-range-blocked{border-color:var(--fv-danger);background:color-mix(in srgb,var(--fv-danger) 8%,transparent);cursor:not-allowed}
+.fv-ed-insertion-line.fv-ed-blocked-insertion{background:var(--fv-danger)}
+.fv-ed-selection.fv-ed-range-blocked .fv-ed-range-border{border-color:var(--fv-danger)}
+.fv-ed-selection.fv-ed-range-blocked .fv-ed-trim-handle,.fv-ed-selection.fv-ed-range-blocked .fv-ed-boundary-handle{background:var(--fv-danger)}
+.fv-ed-selection.fv-ed-range-blocked .fv-ed-planned-label{color:var(--fv-danger)}
+.fv-ed-track-view[data-cursor=not-allowed] .fv-ed-track-content,.fv-ed-track-view[data-cursor=not-allowed] .fv-ed-track-content *{cursor:not-allowed}
+.fv-ed-clip.fv-ed-tiny{z-index:3;border-radius:0}
diff --git a/web/editor_tracks.js b/web/editor_tracks.js
new file mode 100644
index 0000000..02ca4f8
--- /dev/null
+++ b/web/editor_tracks.js
@@ -0,0 +1,1106 @@
+import {editorIcon} from './editor_icons.js';
+import {displayTracks, isText, isTextTrack} from './editor_text_model.js';
+// Pointer gestures translate coordinates into model calls; the model owns edits.
+// These exports deliberately have no DOM dependencies, so input arithmetic can
+// be checked in Node with the same code that runs in the browser.
+import * as model from './editor_model.js';
+import {timeEstimate} from './editor_genbar.js';
+import {clipPictureSize, updatePictureBadge} from './editor_frame.js';
+import {createSelectionGestures, isMultiple, isTyping} from './editor_select.js';
+import {createTrackMenu} from './editor_menu.js';
+
+export const SOURCE_TYPE = 'application/x-freevideo-source';
+export const SNAP_DISTANCE = 8;
+export const frameToPixels = (frame, zoom, fps = model.FPS) => frame * zoom / fps;
+export const pixelsToFrame = (pixels, zoom, fps = model.FPS) => Math.round(pixels * fps / zoom);
+
+export function snapFrame(frame, points, zoom, {offsets = [0], distance = SNAP_DISTANCE, enabled = true} = {}) {
+ if (!enabled) return {frame: Math.max(0, frame), guide: null};
+ let best = null, delta = Infinity;
+ for (const point of points) for (const offset of offsets) {
+ const difference = point - (frame + offset);
+ const pixels = Math.abs(frameToPixels(difference, zoom));
+ if (pixels <= distance + 1e-9 && pixels < delta && frame + difference >= 0) {
+ delta = pixels; best = {frame: frame + difference, guide: point};
+ }
+ }
+ return best || {frame: Math.max(0, frame), guide: null};
+}
+
+export function insertionPoint(clips, frame, exceptIds = []) {
+ const except = new Set(exceptIds);
+ const hit = clips.find(clip => !except.has(clip.id) && frame >= clip.start && frame < clip.start + clip.frames);
+ if (!hit) return {frame: Math.max(0, frame), hit: null, edge: null};
+ const edge = frame === hit.start ? 'start' : 'end';
+ return {frame: edge === 'start' ? hit.start : hit.start + hit.frames, hit: hit.id, edge};
+}
+
+export function rangeParameters(anchor, frame, tracks = ['v1', 'a1'], fps = model.FPS) {
+ const first = Math.max(0, Math.round(anchor / fps) * fps);
+ const last = Math.max(0, Math.round(frame / fps) * fps);
+ const start = Math.min(first, last);
+ return {kind: 'range', start, frames: Math.max(2 * fps, Math.abs(last - first)), tracks: [...tracks]};
+}
+
+export function moveParameters(clip, anchor, frame, points, zoom) {
+ const desired = Math.max(0, clip.start + frame - anchor);
+ return snapFrame(desired, points, zoom, {offsets: [0, clip.frames]});
+}
+
+export function rangeMoveParameters(record, range, anchor, frame, points, zoom, {enabled = true} = {}) {
+ const desired = Math.max(0, range.start + frame - anchor);
+ const occupied = start => model.rangeOccupied(record, {...range, start});
+ if (!enabled) return {frame: desired, guide: null, blocked: occupied(desired)};
+ const aligned = moveParameters(range, anchor, frame, points, zoom);
+ if (occupied(desired)) {
+ // Prefer a free, flush content edge over an unrelated grid/playhead snap.
+ let best = null, distance = Infinity;
+ for (const track of record.tracks.filter(track => range.tracks.includes(track.id))) for (const clip of track.clips) {
+ for (const [start, guide] of [[clip.start - range.frames, clip.start], [clip.start + clip.frames, clip.start + clip.frames]]) {
+ const pixels = Math.abs(frameToPixels(start - desired, zoom));
+ if (start >= 0 && pixels <= SNAP_DISTANCE && pixels < distance && !occupied(start)) {
+ best = {frame: start, guide, blocked: false}; distance = pixels;
+ }
+ }
+ }
+ return best || {frame: desired, guide: null, blocked: true};
+ }
+ // Snapping must not pull an otherwise free range into existing content.
+ return occupied(aligned.frame) ? {frame: desired, guide: null, blocked: false} : {...aligned, blocked: false};
+}
+
+// Classification uses the source tail only to decide which gesture to preview.
+// trim/extendClip still validate the requested edit (including pairs and limits).
+export function edgeParameters(clip, edge, frame, points, zoom) {
+ const snapped = snapFrame(frame, points, zoom);
+ if (clip.pending && !clip.source) return {kind: 'planned', edge, frame: snapped.frame, guide: snapped.guide};
+ const sourceEnd = clip.start + clip.length - clip.in;
+ if (edge === 'end' && clip.extend && snapped.frame > sourceEnd) {
+ const extra = Math.max(2 * model.FPS, Math.round((snapped.frame - sourceEnd) / model.FPS) * model.FPS);
+ return {kind: 'extend', frame: sourceEnd, frames: extra, guide: snapped.guide};
+ }
+ return {kind: 'trim', edge, frame: snapped.frame, guide: snapped.guide};
+}
+
+export function sourcePayload(value) {
+ try {
+ const payload = typeof value === 'string' ? JSON.parse(value) : value;
+ if (!payload || typeof payload.key !== 'string' || !Number.isSafeInteger(payload.frames) || payload.frames <= 0
+ || typeof payload.hasVideo !== 'boolean' || typeof payload.hasAudio !== 'boolean'
+ || !(payload.hasVideo || payload.hasAudio)) return null;
+ const separator = payload.key.indexOf(':');
+ if (separator < 1) return null;
+ const kind = payload.key.slice(0, separator), id = payload.key.slice(separator + 1);
+ if (!['work', 'import', 'generated'].includes(kind) || !id) return null;
+ return {source: {kind, id}, frames: payload.frames, hasVideo: payload.hasVideo, hasAudio: payload.hasAudio};
+ } catch { return null; }
+}
+
+export function tickSpacing(zoom) {
+ // Keep the specified 5/15-second rhythm, doubling only when labels collide.
+ const factor = 2 ** Math.max(0, Math.ceil(Math.log2(52 / (15 * zoom))));
+ return {minor: 5 * factor, major: 15 * factor};
+}
+
+export function hitEdge(position, width) {
+ if (position < -6 || position > width + 6) return null;
+ const reach = Math.min(6, width / 4);
+ return position <= reach ? 'start' : position >= width - reach ? 'end' : null;
+}
+
+const clock = frame => {
+ const seconds = Math.max(0, Math.floor(frame / model.FPS));
+ return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`;
+};
+const sourceKey = clip => clip.source ? `${clip.source.kind}:${clip.source.id}` : null;
+const busy = clip => ['queued', 'running'].includes(clip.pending);
+const clamp = (value, low, high) => Math.min(high, Math.max(low, value));
+const mountedStates = new WeakSet();
+const create = (tag, className, text) => {
+ const element = document.createElement(tag);
+ element.className = className;
+ if (text != null) element.textContent = text;
+ return element;
+};
+const icon = kind => {
+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
+ svg.setAttribute('viewBox', '0 0 20 20'); svg.setAttribute('aria-hidden', 'true');
+ const path = document.createElementNS(svg.namespaceURI, 'path');
+ path.setAttribute('d', kind === 'video' ? 'M2 4h16v12H2z M4 13l4-5 4 4 2-2 3 4'
+ : kind === 'warning' ? 'M10 2a8 8 0 1 0 0 16a8 8 0 0 0 0-16 M10 6v5 M10 14v.1'
+ : 'M2 8h4l4-4v12l-4-4H2z M13 6c4 2 4 6 0 8 M13 9c1 1 1 1 0 2');
+ svg.append(path); return svg;
+};
+
+export function createTracks(host, {state, sources = {}, t = en => en, actions = {}, blockProgress} = {}) {
+ const element = create('section', 'fv-ed-track-view');
+ element.tabIndex = 0; element.setAttribute('role', 'region');
+ element.setAttribute('aria-label', t('Editing tracks', '剪辑轨道'));
+ const heads = create('div', 'fv-ed-track-heads');
+ const addAudio = create('button', 'fv-ed-add-audio', t('+ Audio track', '+ 声音轨'));
+ addAudio.type = 'button'; heads.append(addAudio);
+ const scroll = create('div', 'fv-ed-track-scroll');
+ const content = create('div', 'fv-ed-track-content');
+ const ruler = create('div', 'fv-ed-ruler');
+ ruler.setAttribute('aria-label', t('Time', '时间'));
+ const overlays = create('div', 'fv-ed-track-overlays');
+ const selectionBox = create('div', 'fv-ed-selection');
+ const previewBox = create('div', 'fv-ed-gesture-preview');
+ const guide = create('div', 'fv-ed-snap-line');
+ const insertion = create('div', 'fv-ed-insertion-line');
+ const playhead = create('div', 'fv-ed-playhead');
+ const handle = create('button', 'fv-ed-playhead-handle');
+ handle.type = 'button'; handle.setAttribute('aria-label', t('Play position', '播放位置'));
+ playhead.append(handle);
+ const plannedLines = create('div', 'fv-ed-planned-borders');
+ overlays.append(plannedLines, selectionBox, previewBox, guide, insertion);
+ content.append(ruler, overlays, playhead); scroll.append(content);
+ const tooltip = create('div', 'fv-ed-drag-label');
+ tooltip.hidden = true; tooltip.setAttribute('role', 'status');
+ const popover = create('div', 'fv-ed-clip-popover'); popover.hidden = true;
+ const zoomBar = create('div', 'fv-ed-track-zoom fv-ed-zoom');
+ const zoomOut = create('button', '', '−'), zoomIn = create('button', '', '+');
+ zoomOut.type = zoomIn.type = 'button';
+ zoomOut.setAttribute('aria-label', t('Zoom out', '缩小'));
+ zoomIn.setAttribute('aria-label', t('Zoom in', '放大'));
+ const slider = create('input', 'fv-ed-zoom-slider');
+ slider.type = 'range'; slider.min = '1'; slider.max = '160'; slider.step = '.1';
+ slider.setAttribute('aria-label', t('Track zoom', '轨道缩放'));
+ const fit = create('button', 'fv-ed-fit'); fit.type = 'button'; fit.append(editorIcon('fit')); fit.setAttribute('aria-label', t('Fit all', '看全部')); fit.title = t('Fit all', '看全部');
+ zoomBar.append(zoomOut, slider, zoomIn, fit);
+ element.append(heads, scroll, zoomBar, tooltip, popover); host.append(element);
+
+ const rows = new Map(), clips = new Map(), progresses = new Map(), waveforms = new Map();
+ let disposed = false, gesture = null, pointerFrame = null, pointerEvent = null;
+ let previewSelection = null, selected = new Set(), estimateToken = 0, estimateTimer = null;
+ let autoFrame = null, dragX = 0, cachedPoints = [], cachedPlan = '', plannedBorders = [];
+ let contentWidth = 0, lastRuler = '', dropPoint = null, draggedSource = null, dropPreviewKey = '';
+ const listeners = [];
+ function on(target, type, listener, options) {
+ target.addEventListener(type, listener, options);
+ listeners.push(() => target.removeEventListener(type, listener, options));
+ }
+ const locate = id => clips.get(id);
+ const pairIds = id => {
+ const clip = locate(id)?.clip;
+ return clip ? [id, ...(clip.link && locate(clip.link) ? [clip.link] : [])] : [];
+ };
+ const selectedIds = selection => new Set(selection?.kind === 'clip' ? selection.ids.flatMap(pairIds) : []);
+ const pixels = frame => frameToPixels(frame, state.zoom);
+ const frameAt = event => Math.max(0, pixelsToFrame(event.clientX - content.getBoundingClientRect().left, state.zoom));
+ const trackAt = event => event.target.closest?.('[data-track]')?.dataset.track || 'v1';
+ const sourceInfo = key => typeof sources === 'function' ? sources(key) : sources.get?.(key) || sources[key];
+ let snapping = true;
+ const snap = (frame, points, zoom, options = {}) => snapFrame(frame, points, zoom, {...options, enabled: snapping});
+ const allPoints = except => snapping ? [...new Set([0, state.playhead, ...model.snapPoints(state.record, except)])] : [];
+ const seekPlayhead = frame => {
+ if (!Number.isSafeInteger(frame) || frame < 0) return {ok: false, reason: 'range'};
+ const at = snap(frame, model.snapPoints(state.record, []), state.zoom).frame;
+ return {ok: true, frame: state.seek(at)};
+ };
+ const selectGestures = createSelectionGestures({state, element, content, scroll, clips, rows,
+ hitTest: pointerHit, snap, t, actions, renderSelection});
+ function attempt(label, change, options) {
+ try { state.apply(label, change, options); return true; }
+ catch (error) {
+ if (!(error instanceof model.EditError)) throw error;
+ actions.editError?.(error); return false;
+ }
+ }
+ function position(node, start, frames) {
+ node.style.left = `${pixels(start)}px`; node.style.width = `${Math.max(2, pixels(frames))}px`;
+ }
+ function geometry(tracks) {
+ const visible = tracks.map(id => rows.get(id)).filter(Boolean);
+ const top = Math.min(...visible.map(row => row.top));
+ const bottom = Math.max(...visible.map(row => row.top + row.height));
+ return {top, height: bottom - top};
+ }
+ function box(node, selection) {
+ node.hidden = !selection;
+ if (!selection) return;
+ const shape = geometry(selection.tracks);
+ position(node, selection.start, selection.frames);
+ node.style.top = `${shape.top}px`; node.style.height = `${shape.height}px`;
+ }
+ function selectionShape(selection) {
+ if (!selection) return null;
+ if (selection.kind === 'range') return selection;
+ if (selection.kind === 'gap') return {...selection, tracks: [selection.track]};
+ const items = [...selectedIds(selection)].map(locate).filter(Boolean);
+ if (!items.length) return null;
+ const start = Math.min(...items.map(item => item.clip.start));
+ const end = Math.max(...items.map(item => item.clip.start + item.clip.frames));
+ return {start, frames: end - start, tracks: [...new Set(items.map(item => item.track))]};
+ }
+ function rangeParts(selection, record = state.record) {
+ return model.rangeParts(record, {...selection, ...actions.generationLimits?.()});
+ }
+ function boundaryLine(frame, index) {
+ const line = create('span', 'fv-ed-range-border');
+ line.style.left = `${pixels(frame)}px`; line.dataset.boundary = String(index);
+ line.append(create('span', 'fv-ed-boundary-handle'));
+ return line;
+ }
+ function borders(node, selection, plan = selection, record = state.record) {
+ const key = JSON.stringify([selection, plan, actions.generationLimits?.()]);
+ if (key !== cachedPlan) {
+ cachedPlan = key; plannedBorders = [];
+ if (selection) try {
+ let frame = plan.start;
+ for (const count of rangeParts(plan, record).slice(0, -1)) {
+ frame += count;
+ if (frame > selection.start && frame < selection.start + selection.frames) plannedBorders.push(frame);
+ }
+ } catch (error) { if (!(error instanceof model.EditError)) throw error; }
+ }
+ node.replaceChildren(...plannedBorders.map((frame, index) => boundaryLine(frame - selection.start, index)));
+ }
+ function handles(node) {
+ for (const edge of ['start', 'end']) {
+ const handle = create('span', `fv-ed-trim-handle fv-ed-trim-${edge}`); handle.dataset.edge = edge; node.append(handle);
+ }
+ }
+ function plannedNeighbor(item) {
+ if (!item || item.clip.source || !item.clip.pending || model.pair(state.record, item.clip.id).some(busy)
+ || !item.clip.part || item.clip.frames % model.FPS) return null;
+ const next = [...clips.values()].find(other => other.track === item.track && other.clip.start === item.clip.start + item.clip.frames
+ && other.clip.part === item.clip.part && !other.clip.source && other.clip.pending && other.clip.frames % model.FPS === 0
+ && !model.pair(state.record, other.clip.id).some(busy));
+ return next || null;
+ }
+ function renderEmptyHints() {
+ const selection = previewSelection || state.selection;
+ const range = selection?.kind === 'range' ? selection : null;
+ const bounds = range ? selectionBox.getBoundingClientRect() : null;
+ for (const [id, row] of rows) {
+ if (row.empty.hidden || !row.empty.firstChild) continue;
+ // Measure the text, not its full-width sticky centering container.
+ const textRange = document.createRange();
+ textRange.selectNodeContents(row.empty);
+ const text = textRange.getBoundingClientRect();
+ const obscured = range?.tracks.includes(id)
+ && bounds.left <= text.right + 12
+ && bounds.right >= text.left - 12;
+ row.empty.classList.toggle('fv-ed-hint-obscured', !!obscured);
+ }
+ }
+ function renderSelection() {
+ const next = selectedIds(state.selection);
+ for (const id of new Set([...selected, ...next])) locate(id)?.element.setAttribute('aria-selected', String(next.has(id)));
+ selected = next;
+ element.dataset.multiselect = String(isMultiple(state.record, [...next]));
+ const selection = previewSelection || state.selection;
+ const shape = selectionShape(selection);
+ const pending = selection?.kind === 'clip' && [...next].every(id => locate(id)?.clip.pending && !busy(locate(id).clip));
+ selectionBox.title = '';
+ selectionBox.classList.toggle('fv-ed-range', selection?.kind === 'range');
+ selectionBox.classList.toggle('fv-ed-planned-selection', !!pending);
+ selectionBox.classList.toggle('fv-ed-gap', selection?.kind === 'gap');
+ selectionBox.classList.toggle('fv-ed-dragging', !!gesture?.moved && gesture.type === 'rangeMove');
+ selectionBox.classList.toggle('fv-ed-range-blocked', !!previewSelection && gesture?.type === 'rangeMove' && gesture.rangeBlocked);
+ box(selectionBox, shape);
+ if (selection?.kind === 'range') borders(selectionBox, shape);
+ else selectionBox.replaceChildren();
+ if (selection?.kind === 'range' || pending) handles(selectionBox);
+ if (selection?.kind === 'range') {
+ const width = pixels(shape.frames), seconds = Math.round(shape.frames / model.FPS);
+ const label = create('span', 'fv-ed-planned-label', t(`${seconds} s`, `${seconds} 秒`));
+ label.hidden = width < 44; selectionBox.append(label);
+ if (label.scrollWidth > label.clientWidth) label.textContent = t(`${seconds} s`, `${seconds} 秒`);
+ }
+ plannedLines.replaceChildren();
+ for (const item of clips.values()) {
+ if (model.clipState(item.clip) === 'planned') {
+ let label = item.element.querySelector('.fv-ed-planned-label');
+ if (!label) { label = create('span', 'fv-ed-planned-label'); item.element.append(label); }
+ const width = pixels(item.clip.frames), seconds = Math.round(item.clip.frames / model.FPS);
+ label.hidden = width < 44;
+ label.textContent = t(`${seconds} s`, `${seconds} 秒`);
+ if (label.scrollWidth > label.clientWidth) label.textContent = t(`${seconds} s`, `${seconds} 秒`);
+ } else item.element.querySelector('.fv-ed-planned-label')?.remove();
+ const neighbor = item.track === 'v1' && plannedNeighbor(item);
+ if (neighbor) {
+ const line = boundaryLine(item.clip.start + item.clip.frames, item.clip.id);
+ const shape = geometry(pairIds(item.clip.id).map(id => locate(id).track));
+ line.style.top = `${shape.top}px`; line.style.height = `${shape.height}px`; line.style.bottom = 'auto';
+ line.dataset.left = item.clip.id; line.dataset.right = neighbor.clip.id; plannedLines.append(line);
+ }
+ }
+ renderEmptyHints();
+ }
+ function renderPlayhead() {
+ playhead.style.left = `${pixels(state.playhead)}px`;
+ handle.setAttribute('aria-label', `${t('Play position', '播放位置')}, ${clock(state.playhead)}`);
+ }
+ function renderRuler() {
+ const {minor, major} = tickSpacing(state.zoom);
+ // Render visible marks plus one screen of overscan, even for long edits.
+ const low = Math.max(0, Math.floor(scroll.scrollLeft / state.zoom / major) * major);
+ const high = Math.ceil((scroll.scrollLeft + scroll.clientWidth * 2) / state.zoom / minor) * minor;
+ const key = `${state.zoom}/${low}/${high}`;
+ if (key === lastRuler) return; lastRuler = key;
+ const marks = [];
+ for (let second = low; second <= high; second += minor) {
+ const tick = create('span', 'fv-ed-tick'); tick.style.left = `${second * state.zoom}px`;
+ if (second % major === 0) {
+ tick.classList.add('fv-ed-tick-major'); tick.append(create('span', '', clock(second * model.FPS)));
+ }
+ marks.push(tick);
+ }
+ ruler.replaceChildren(...marks);
+ }
+ function layout() {
+ // Defer the initial 90-second view until a detached shell is mounted.
+ if (!mountedStates.has(state) && scroll.clientWidth) {
+ mountedStates.add(state);
+ if (state.zoom === 12) state.setZoom(scroll.clientWidth / 90);
+ }
+ const duration = Math.max(model.duration(state.record), state.selection?.kind === 'range' ? state.selection.start + state.selection.frames : 0);
+ contentWidth = Math.max(scroll.clientWidth, pixels(duration + 30 * model.FPS));
+ content.style.width = `${contentWidth}px`;
+ for (const row of rows.values()) row.empty.style.width = `${scroll.clientWidth}px`;
+ for (const item of clips.values()) {
+ position(item.element, item.clip.start, item.clip.frames);
+ item.element.classList.toggle('fv-ed-tiny', pixels(item.clip.frames) < 2);
+ item.status.hidden = pixels(item.clip.frames) < 24;
+ }
+ renderRuler(); renderSelection(); renderPlayhead(); slider.value = String(state.zoom);
+ }
+ function waveform(item, key) {
+ const viewKey = `${key}/${item.clip.in}/${item.clip.frames}/${item.clip.length}`;
+ if (item.waveKey === viewKey) return; item.waveKey = viewKey;
+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
+ svg.classList.add('fv-ed-waveform'); svg.setAttribute('viewBox', '0 0 200 40');
+ svg.setAttribute('preserveAspectRatio', 'none'); svg.setAttribute('aria-hidden', 'true');
+ const path = document.createElementNS(svg.namespaceURI, 'path'); svg.append(path); item.media.replaceChildren(svg);
+ const draw = peaks => {
+ if (disposed || item.waveKey !== viewKey) return;
+ if (!peaks?.length) { path.setAttribute('d', 'M0 20H200'); return; }
+ const from = Math.floor(item.clip.in / item.clip.length * peaks.length);
+ const to = Math.max(from + 1, Math.ceil((item.clip.in + item.clip.frames) / item.clip.length * peaks.length));
+ peaks = peaks.slice(from, to);
+ const stride = 200 / peaks.length;
+ path.setAttribute('d', peaks.map((value, i) => {
+ const height = Math.max(.5, clamp(Number(value) || 0, 0, 1) * 17);
+ return `M${(i + .5) * stride} ${20 - height}v${height * 2}`;
+ }).join(' '));
+ };
+ draw([]);
+ if (key && actions.waveform) {
+ if (!waveforms.has(key)) waveforms.set(key, Promise.resolve().then(() => actions.waveform(key)).catch(() => []));
+ waveforms.get(key).then(draw);
+ }
+ }
+ function makeClip(clip, track) {
+ const node = create('button', 'fv-ed-clip'); node.type = 'button'; node.dataset.clip = clip.id;
+ node.dataset.track = track.id; node.dataset.state = model.clipState(clip);
+ const media = create('span', 'fv-ed-clip-media');
+ const fill = create('span', 'fv-ed-progress-fill');
+ const status = create('span', 'fv-ed-clip-status');
+ const left = create('span', 'fv-ed-trim-handle fv-ed-trim-start'); left.dataset.edge = 'start';
+ const right = create('span', 'fv-ed-trim-handle fv-ed-trim-end'); right.dataset.edge = 'end';
+ node.append(media, fill, status, left, right);
+ const item = {element: node, media, fill, status, clip, kind: track.kind, component: null, waveKey: undefined};
+ if (blockProgress && !isText(clip)) {
+ item.component = blockProgress(clip.id, node);
+ item.component.element.classList.add('fv-ed-block-progress'); node.append(item.component.element);
+ fill.hidden = true;
+ }
+ return item;
+ }
+ function updateProgress(item) {
+ const value = progresses.get(item.clip.id) || {state: item.clip.pending === 'queued' ? 'waiting'
+ : busy(item.clip) ? 'generating' : model.clipState(item.clip) === 'done' ? 'done'
+ : item.clip.pending === 'stopped' ? 'stopped' : model.clipState(item.clip) === 'failed' ? 'failed' : 'waiting',
+ fraction: 0, remainingSeconds: null};
+ item.element.style.setProperty('--fv-ed-progress', String(clamp(Number(value.fraction) || 0, 0, 1)));
+ item.component?.update(value);
+ }
+ function renderRecord() {
+ selectGestures.finish(null, true);
+ cachedPlan = ''; popover.hidden = true;
+ const record = state.record, retained = new Set(), tracks = displayTracks(record);
+ const twoAudio = tracks.some(track => track.id === 'a2');
+ let top = 24;
+ for (const track of tracks) {
+ const name = track.kind === 'text' ? t('Text', '文字') : track.kind === 'subtitle' ? t('Subtitles', '字幕') : track.kind === 'video' ? t('Video', '画面') : twoAudio
+ ? t(`Audio ${track.id === 'a1' ? 1 : 2}`, `声音 ${track.id === 'a1' ? 1 : 2}`) : t('Audio', '声音');
+ let row = rows.get(track.id);
+ if (!row) {
+ const node = create('div', 'fv-ed-track-row'); node.dataset.track = track.id;
+ const empty = create('div', 'fv-ed-track-empty');
+ node.append(empty);
+ const head = create('div', 'fv-ed-track-head'); head.dataset.track = track.id;
+ head.title = name; head.append(icon(track.kind), create('span', '', name));
+ heads.append(head); content.insertBefore(node, overlays);
+ row = {element: node, head, empty}; rows.set(track.id, row);
+ }
+ row.head.title = name; row.head.querySelector('span').textContent = name;
+ row.empty.hidden = track.clips.length > 0;
+ // A picture track with any block description grows a strip for it under the pictures.
+ const noted = !!actions.describedTrack?.(track); row.element.dataset.noted = String(noted);
+ row.top = top; row.height = track.kind === 'video' ? 64 + (noted ? 22 : 0) : 40;
+ row.element.style.top = row.head.style.top = `${top}px`;
+ row.element.style.height = row.head.style.height = `${row.height}px`;
+ row.element.setAttribute('aria-label', name);
+ actions.textTrack?.(row, track);
+ top += row.height + 6;
+ let previous = null;
+ track.clips.forEach((clip, index) => {
+ retained.add(clip.id);
+ let item = clips.get(clip.id);
+ // Clip ids are local to a project. Opening another project can
+ // reuse an id for a different media kind (and progress layout).
+ if (item && item.kind !== track.kind) { item.waveKey = undefined; item.component?.dispose(); item.element.remove(); item = null; }
+ if (!item) { item = makeClip(clip, track); clips.set(clip.id, item); row.element.append(item.element); }
+ item.clip = clip; item.track = track.id;
+ item.element.classList.toggle('fv-ed-tiny', pixels(clip.frames) < 2);
+ // Commits reorder only displaced buttons for sensible Tab order;
+ // pointermove never enters this reconciliation path.
+ const next = previous ? previous.nextElementSibling : row.element.firstElementChild;
+ if (next !== item.element) row.element.insertBefore(item.element, next);
+ previous = item.element;
+ const visual = model.clipState(clip), key = sourceKey(clip);
+ item.element.dataset.state = visual; item.element.dataset.track = track.id;
+ item.element.dataset.busy = String(busy(clip)); item.element.dataset.extend = String(clip.extend && !busy(clip));
+ item.element.classList.toggle('fv-ed-joined-left', track.clips[index - 1]?.start + track.clips[index - 1]?.frames === clip.start);
+ item.element.classList.toggle('fv-ed-joined-right', track.clips[index + 1]?.start === clip.start + clip.frames);
+ if (visual === 'failed' && track.kind === 'video') item.status.replaceChildren(icon('warning'));
+ else item.status.replaceChildren();
+ const status = {planned: t('Not generated yet', '还没生成'), running: t('Generating', '正在生成'),
+ done: t('Complete', '完成'), failed: t('Unsuccessful', '没成功')}[visual];
+ const seconds = Math.round(clip.frames / model.FPS);
+ item.element.title = '';
+ item.element.setAttribute('aria-label', t(`${name}, clip ${index + 1}, ${seconds} s, ${status}`,
+ `${name},第 ${index + 1} 段,${seconds} 秒,${status}`));
+ // Pending replacements can retain their old media; state styling
+ // overlays it until the model reports that the new media is done.
+ item.media.hidden = visual !== 'done';
+ if (track.kind === 'video') {
+ updatePictureBadge(item.element, clip, record, clipPictureSize(clip, sources), t);
+ actions.blockNote?.(item, {noted, index, record});
+ const thumbnail = sourceInfo(key)?.thumbnail;
+ item.media.style.backgroundImage = thumbnail ? `url(${JSON.stringify(thumbnail)})` : '';
+ } else if (isText(clip)) actions.textClip?.(item, record);
+ else waveform(item, key);
+ updateProgress(item);
+ });
+ }
+ for (const [id, row] of rows) if (!tracks.some(track => track.id === id)) { row.element.remove(); row.head.remove(); rows.delete(id); }
+ for (const [id, item] of clips) if (!retained.has(id)) { item.component?.dispose(); item.element.remove(); clips.delete(id); progresses.delete(id); }
+ heads.append(addAudio);
+ addAudio.style.top = `${top}px`; addAudio.disabled = tracks.find(track => track.id === 'a2')?.clips.some(busy) || false;
+ addAudio.textContent = twoAudio ? t('− Audio track', '- 声音轨') : t('+ Audio track', '+ 声音轨');
+ addAudio.title = '';
+ addAudio.setAttribute('aria-label', addAudio.textContent);
+ content.style.height = `${top - 6}px`; playhead.style.height = `${top - 24}px`;
+ layout();
+ if (gesture?.type === 'move' && pointerEvent) updatePointer(pointerEvent);
+ }
+ function showGuide(frame) { guide.hidden = frame == null; if (frame != null) guide.style.left = `${pixels(frame)}px`; }
+ function showInsertion(frame) { insertion.hidden = frame == null; if (frame != null) insertion.style.left = `${pixels(frame)}px`; }
+ function hint(selection, event, extended = false, moving = false, limited = null) {
+ const token = ++estimateToken; clearTimeout(estimateTimer);
+ if (gesture?.type.startsWith('range')) actions.previewRange?.(selection);
+ const seconds = Math.round(selection.frames / model.FPS);
+ let count = 1;
+ try { count = rangeParts(selection).length; } catch (error) { if (!(error instanceof model.EditError)) throw error; }
+ const label = limited != null ? t(`Max ${limited} s`, `最长 ${limited} 秒`)
+ : moving ? `${clock(selection.start)} – ${clock(selection.start + selection.frames)}`
+ : t(`${extended ? '+' : ''}${seconds} s`, `${extended ? '+' : ''}${seconds} 秒`);
+ tooltip.textContent = label; tooltip.hidden = false;
+ const bounds = element.getBoundingClientRect();
+ tooltip.style.left = `${clamp(event.clientX - bounds.left + 14, 8, Math.max(8, bounds.width - 300))}px`;
+ tooltip.style.top = `${clamp(event.clientY - bounds.top + 14, 26, bounds.height - 32)}px`;
+ if (!isText(gesture?.clip) && actions.estimate && !moving && limited == null) estimateTimer = setTimeout(() => {
+ Promise.resolve().then(() => actions.estimate(selection)).then(value => {
+ if (disposed || token !== estimateToken || value == null || !Number.isFinite(value)) return;
+ tooltip.textContent = `${label} · ${timeEstimate(value, t)}`;
+ }).catch(() => {});
+ }, 120);
+ }
+ function clearPreview() {
+ previewSelection = null; previewBox.hidden = true; guide.hidden = true; insertion.hidden = true;
+ actions.previewRange?.(null);
+ tooltip.hidden = true; plannedLines.hidden = false; cachedPlan = ''; clearTimeout(estimateTimer); estimateToken++;
+ for (const id of [...(gesture?.ids || []), ...(gesture?.rightPreviewIds || [])]) {
+ const item = locate(id);
+ if (item) { item.element.classList.remove('fv-ed-dragging'); position(item.element, item.clip.start, item.clip.frames); }
+ }
+ delete element.dataset.cursor; selectionBox.classList.remove('fv-ed-dragging', 'fv-ed-cannot-drop');
+ plannedLines.querySelectorAll('[data-limited]').forEach(line => line.removeAttribute('data-limited'));
+ renderSelection();
+ }
+ function failedPopover(item) {
+ const reason = create('p', '', actions.reasonText?.(item.clip.reason) || t('Could not generate', '没能生成'));
+ const retry = create('button', '', t('Retry', '重试')); retry.type = 'button';
+ retry.onclick = () => { popover.hidden = true;
+ Promise.resolve().then(() => actions.retry?.(item.clip.id)).catch(error => actions.editError?.(error)); };
+ popover.replaceChildren(reason, retry); popover.hidden = false;
+ const bounds = element.getBoundingClientRect(), clipBounds = item.element.getBoundingClientRect();
+ popover.style.left = `${clamp(clipBounds.left - bounds.left, 8, Math.max(8, bounds.width - 248))}px`;
+ popover.style.top = `${Math.min(clipBounds.bottom - bounds.top + 4, bounds.height - 96)}px`;
+ }
+ function clickSelection(event) {
+ if (event.range) return;
+ const id = event.clipId || event.target.closest?.('.fv-ed-clip')?.dataset.clip;
+ if (id) {
+ selectGestures.choose(id, event);
+ const item = locate(id); if (model.clipState(item.clip) === 'failed') failedPopover(item);
+ return;
+ }
+ const track = event.target.closest?.('.fv-ed-track-row')?.dataset.track;
+ const frame = frameAt(event);
+ const gap = track && model.gaps(state.record, track).find(item => frame >= item.start && frame < item.start + item.frames);
+ state.select(gap ? {kind: 'gap', track, start: gap.start, frames: gap.frames} : null, {history: true});
+ }
+ // Coordinate hit testing includes the outside of an edge and works when the
+ // transparent selection outline, or a child label, is the pointer target.
+ function pointerHit(event) {
+ const bounds = content.getBoundingClientRect(), y = event.clientY - bounds.top, x = event.clientX - bounds.left;
+ const track = [...rows].find(([, row]) => y >= row.top && y <= row.top + row.height)?.[0];
+ const selection = state.selection;
+ const planned = selection?.kind === 'range' ? state.record.tracks[0].clips.filter(clip =>
+ clip.start >= selection.start && clip.start + clip.frames <= selection.start + selection.frames) : [];
+ const materialized = planned.length && planned[0].start === selection.start
+ && planned.at(-1).start + planned.at(-1).frames === selection.start + selection.frames
+ && planned.every((clip, i) => clip.pending && !clip.source && (!i || planned[i - 1].start + planned[i - 1].frames === clip.start));
+ if (selection?.kind === 'range' && !materialized) {
+ const shape = geometry(selection.tracks), position = x - pixels(selection.start), width = pixels(selection.frames);
+ if (y >= shape.top && y <= shape.top + shape.height && position >= -6 && position <= width + 6) {
+ const edge = hitEdge(position, width);
+ if (edge) return {range: selection, edge, track};
+ let at = 0;
+ const parts = rangeParts(selection);
+ for (let i = 0; i < parts.length - 1; i++) {
+ at += parts[i];
+ if (Math.abs(position - pixels(at)) <= Math.min(6, pixels(Math.min(parts[i], parts[i + 1])) / 4)) return {range: selection, boundary: i, parts, track};
+ }
+ return {range: selection, track};
+ }
+ }
+ const candidates = [...clips.values()].filter(item => item.track === track);
+ // Shared planned boundaries take precedence over the two outer handles.
+ for (const item of candidates) {
+ const neighbor = plannedNeighbor(item), at = item.clip.start + item.clip.frames;
+ if (neighbor && Math.abs(x - pixels(at)) <= Math.min(6, pixels(Math.min(item.clip.frames, neighbor.clip.frames)) / 4)) {
+ const primary = item.track === 'a1' && item.clip.link ? locate(item.clip.link) : item;
+ return {item: primary, neighbor: plannedNeighbor(primary), track: primary.track};
+ }
+ }
+ const pointed = candidates.find(item => item.clip.id === event.target.closest?.('.fv-ed-clip')?.dataset.clip);
+ // Expanded tiny parts need DOM priority; ordinary shared edges keep the
+ // left part's precedence even when the next handle overlaps.
+ const direct = (pointed && pixels(pointed.clip.frames) < 2 ? pointed : null)
+ || candidates.find(item => x >= pixels(item.clip.start) && x <= pixels(item.clip.start) + Math.max(2, pixels(item.clip.frames)));
+ const item = direct || candidates.find(item => hitEdge(x - pixels(item.clip.start), Math.max(2, pixels(item.clip.frames))));
+ return {item, track, edge: item ? hitEdge(x - pixels(item.clip.start), Math.max(2, pixels(item.clip.frames))) : null};
+ }
+ function startPointer(event) {
+ if (event.button !== 0 || !event.isPrimary || gesture || isTyping(event.target) || event.target.closest('.fv-ed-track-zoom, .fv-ed-clip-popover')) return;
+ if (selectGestures.begin(event)) { popover.hidden = true; return; }
+ const seeking = event.target.closest('.fv-ed-ruler, .fv-ed-playhead-handle');
+ const hit = seeking ? {} : pointerHit(event);
+ if (!seeking && !hit.track && !hit.range) return;
+ event.preventDefault(); event.stopPropagation(); element.focus({preventScroll: true}); popover.hidden = true;
+ const {item, edge, range, neighbor, boundary, parts} = hit, id = item?.clip.id;
+ const anchor = frameAt(event), track = hit.track || trackAt(event);
+ if (state.record.tracks.find(t => t.id === track)?.locked) { flashBlocked(anchor); return; }
+ if (!item && isTextTrack(state.record.tracks.find(t => t.id === track))) { state.seek(anchor); state.select(null); return; }
+ actions.gestureStart?.();
+ gesture = {pointer: event.pointerId, x: event.clientX, y: event.clientY, anchor, track, target: event.target, moved: false,
+ type: seeking ? 'seek' : range ? boundary != null ? 'rangeBoundary' : edge ? 'rangeEdge' : 'rangeMove'
+ : neighbor ? 'plannedBoundary' : item ? edge ? 'edge' : 'move' : 'range', id, edge, range, boundary, parts, neighbor,
+ clip: item ? {...item.clip, length: Math.min(...model.pair(state.record, id).map(clip => clip.length))} : null,
+ ids: item ? [...pairIds(id), ...(neighbor ? pairIds(neighbor.clip.id) : [])] : [], previousSelection: state.selection, previousPlayhead: state.playhead};
+ cachedPoints = seeking ? model.snapPoints(state.record, []) : allPoints(gesture.ids);
+ if (item) state.select({kind: 'clip', ids: [id]});
+ if (item && model.pair(state.record, id).some(busy)) { gesture.type = 'click'; gesture.blocked = true; }
+ if (gesture.type === 'move') gesture.members = gesture.ids.map(id => locate(id).clip);
+ if (seeking) seekPlayhead(anchor);
+ element.dataset.cursor = ['move', 'rangeMove'].includes(gesture.type) ? 'grabbing' : gesture.type === 'click' ? 'default' : 'ew-resize';
+ element.setPointerCapture(event.pointerId);
+ }
+ function dragPoints(frame, length = 0) {
+ if (!snapping) return [];
+ const grid = 5 * model.FPS, points = [...cachedPoints];
+ for (const value of [frame, frame + length]) points.push(Math.round(value / grid) * grid);
+ return points;
+ }
+ function boundaryLimits(start, part = null) {
+ const limits = actions.generationLimits?.() || {}, maxSeconds = limits.maxSeconds ?? model.RULES.maxSeconds;
+ const maxFollowSeconds = limits.maxFollowSeconds ?? maxSeconds;
+ const before = state.record.tracks[0].clips.some(clip => clip.start + clip.frames === start
+ && ((part && clip.part === part && clip.pending) || (clip.source && clip.extend && clip.in + clip.frames === clip.length)));
+ return {maxSeconds: before ? maxFollowSeconds : maxSeconds, maxFollowSeconds};
+ }
+ function updatePointer(event) {
+ if (!gesture || gesture.pointer !== event.pointerId) return;
+ const frame = frameAt(event); dragX = event.clientX;
+ gesture.moved ||= Math.hypot(event.clientX - gesture.x, event.clientY - gesture.y) >= 4;
+ if (gesture.blocked && gesture.moved && !gesture.warned) {
+ gesture.warned = true; actions.editError?.(new model.EditError('busy'));
+ }
+ if (gesture.type === 'seek') {
+ seekPlayhead(frame); return;
+ }
+ if (!gesture.moved || gesture.type === 'click') return;
+ if (gesture.type === 'rangeBoundary' || gesture.type === 'plannedBoundary') {
+ const isRange = gesture.type === 'rangeBoundary';
+ const parts = isRange ? gesture.parts : [gesture.clip.frames, gesture.neighbor.clip.frames];
+ const index = isRange ? gesture.boundary : 0, start = isRange ? gesture.range.start : gesture.clip.start;
+ const from = start + parts.slice(0, index).reduce((sum, count) => sum + count, 0);
+ const result = model.adjustPartBoundary(parts, index, frame - from, boundaryLimits(start, gesture.clip?.part));
+ gesture.result = {...result, frame: from + result.parts[index]};
+ if (isRange) {
+ gesture.selection = {...gesture.range, parts: result.parts}; previewSelection = gesture.selection; renderSelection();
+ selectionBox.querySelectorAll('.fv-ed-range-border')[index]?.setAttribute('data-limited', String(result.limited != null));
+ } else {
+ const preview = model.resizePlannedBoundary(state.record, gesture.id, gesture.neighbor.clip.id, gesture.result.frame, actions.generationLimits?.());
+ for (const id of gesture.ids) { const clip = model.find(preview, id); position(locate(id).element, clip.start, clip.frames); }
+ const line = plannedLines.querySelector(`[data-left="${gesture.id}"]`);
+ if (line) { line.style.left = `${pixels(gesture.result.frame)}px`; line.setAttribute('data-limited', String(result.limited != null)); }
+ box(selectionBox, {start, frames: result.parts[0], tracks: pairIds(gesture.id).map(id => locate(id).track)});
+ }
+ hint(isRange ? gesture.selection : {start, frames: parts.reduce((a, b) => a + b, 0)}, event, false, false, result.limited);
+ } else if (gesture.type === 'rangeMove' || gesture.type === 'rangeEdge') {
+ const original = gesture.range;
+ let aligned;
+ if (gesture.type === 'rangeMove') {
+ const desired = original.start + frame - gesture.anchor;
+ aligned = rangeMoveParameters(state.record, original, gesture.anchor, frame, dragPoints(desired, original.frames), state.zoom, {enabled: snapping});
+ gesture.rangeBlocked = aligned.blocked;
+ element.dataset.cursor = aligned.blocked ? 'not-allowed' : 'grabbing';
+ gesture.selection = {...original, start: aligned.frame};
+ } else {
+ aligned = snap(frame, dragPoints(frame), state.zoom);
+ const end = original.start + original.frames, at = Math.round(aligned.frame / model.FPS) * model.FPS;
+ const start = gesture.edge === 'start' ? Math.min(end - 2 * model.FPS, at) : original.start;
+ const stop = gesture.edge === 'end' ? Math.max(start + 2 * model.FPS, at) : end;
+ gesture.selection = {kind: 'range', start, frames: stop - start, tracks: original.tracks};
+ }
+ previewSelection = gesture.selection; showGuide(aligned.guide); renderSelection();
+ hint(gesture.selection, event, false, gesture.type === 'rangeMove');
+ if (gesture.type === 'rangeMove' && gesture.rangeBlocked) tooltip.hidden = true;
+ } else if (gesture.type === 'range') {
+ const aligned = snap(frame, cachedPoints, state.zoom);
+ gesture.selection = rangeParameters(gesture.anchor, aligned.frame);
+ previewSelection = gesture.selection; showGuide(aligned.guide);
+ renderSelection(); hint(gesture.selection, event);
+ } else if (gesture.type === 'move') {
+ plannedLines.hidden = true;
+ const desired = gesture.clip.start + frame - gesture.anchor;
+ const result = moveParameters(gesture.clip, gesture.anchor, frame, dragPoints(desired, gesture.clip.frames), state.zoom);
+ gesture.result = result;
+ const track = state.record.tracks.find(row => row.id === gesture.track);
+ const drop = isText(gesture.clip) ? {hit: false} : insertionPoint(track.clips, result.frame, gesture.ids);
+ showInsertion(drop.hit ? drop.frame : null); showGuide(result.guide);
+ for (const id of gesture.rightPreviewIds || []) {
+ const item = locate(id); if (item) position(item.element, item.clip.start, item.clip.frames);
+ }
+ gesture.rightPreviewIds = [];
+ let preview, error, shifted = 0;
+ try { preview = model.move(state.record, gesture.id, result.frame); }
+ catch (caught) { if (!(caught instanceof model.EditError)) throw caught; error = caught; }
+ if (preview) for (const row of preview.tracks) for (const clip of row.clips) {
+ const item = locate(clip.id);
+ if (!gesture.ids.includes(clip.id) && clip.start !== item.clip.start) {
+ position(item.element, clip.start, clip.frames); gesture.rightPreviewIds.push(clip.id);
+ shifted = Math.max(shifted, clip.start - item.clip.start);
+ }
+ }
+ const landing = preview ? model.find(preview, gesture.id).start : result.frame;
+ element.dataset.cursor = error ? 'not-allowed' : 'grabbing';
+ for (const id of gesture.ids) {
+ const item = locate(id); item.element.classList.add('fv-ed-dragging'); position(item.element, landing, item.clip.frames);
+ }
+ box(selectionBox, {start: landing, frames: gesture.clip.frames, tracks: gesture.ids.map(id => locate(id).track)});
+ hint({start: landing, frames: gesture.clip.frames}, event, false, true);
+ selectionBox.classList.toggle('fv-ed-cannot-drop', !!error);
+ if (error) tooltip.hidden = true;
+ } else if (gesture.type === 'edge') {
+ let result = edgeParameters(gesture.clip, gesture.edge, frame, cachedPoints, state.zoom);
+ if (result.kind === 'planned') {
+ let preview;
+ try { preview = model.resizePlanned(state.record, gesture.id, gesture.edge, result.frame, actions.generationLimits?.()); }
+ catch (error) { if (!(error instanceof model.EditError)) throw error; return; }
+ const clip = model.find(preview, gesture.id);
+ const end = Math.max(...preview.tracks.find(row => row.id === gesture.track).clips
+ .filter(c => c.id === gesture.id || !clips.has(c.id)).map(c => c.start + c.frames));
+ gesture.result = result;
+ const selection = {kind: 'range', start: clip.start, frames: end - clip.start, tracks: gesture.ids.map(id => locate(id).track)};
+ for (const id of gesture.ids) position(locate(id).element, selection.start, selection.frames);
+ box(selectionBox, selection); borders(selectionBox, selection); handles(selectionBox); hint(selection, event); showGuide(result.guide);
+ return;
+ }
+ const originalEnd = gesture.clip.start + gesture.clip.frames;
+ const edit = value => value.kind === 'extend'
+ ? model.extendClip(state.record, gesture.id, value.frame - originalEnd + value.frames, actions.generationLimits?.() || {})
+ : model.trim(state.record, gesture.id, gesture.edge, value.frame);
+ let preview, blocked = false;
+ try {
+ preview = edit(result);
+ } catch (error) {
+ if (!(error instanceof model.EditError)) throw error;
+ // A text part stays as it is while blocked; release flashes it red, with no words.
+ if (isText(gesture.clip)) { gesture.result = result; tooltip.hidden = true; return; }
+ // A blocked left edge keeps the part as it is while dragging; release reports why.
+ if (gesture.edge !== 'end') preview = state.record;
+ else {
+ if (error.code !== 'busy') return;
+ const growth = result.frame - originalEnd + (result.kind === 'extend' ? result.frames : 0);
+ const room = model.rightEdgeRoom(state.record, gesture.id, Math.max(0, growth), {generating: result.kind === 'extend'});
+ if (!room.blocked) return;
+ blocked = true;
+ result = edgeParameters(gesture.clip, 'end', room.limit, [], state.zoom);
+ if (result.kind === 'extend') {
+ result.frames = Math.floor((room.limit - result.frame) / model.FPS) * model.FPS;
+ if (result.frames < model.RULES.minSeconds * model.FPS) result = {kind: 'trim', edge: 'end', frame: result.frame, guide: null};
+ }
+ preview = edit(result);
+ }
+ }
+ for (const id of gesture.rightPreviewIds || []) {
+ const item = locate(id); if (item) position(item.element, item.clip.start, item.clip.frames);
+ }
+ gesture.rightPreviewIds = [];
+ let shifted = 0;
+ for (const track of preview.tracks) for (const clip of track.clips) {
+ const item = locate(clip.id); if (!item) continue;
+ if (clip.start !== item.clip.start || clip.frames !== item.clip.frames) {
+ position(item.element, clip.start, clip.frames); gesture.rightPreviewIds.push(clip.id);
+ if (!gesture.ids.includes(clip.id)) shifted = Math.max(shifted, clip.start - item.clip.start);
+ }
+ }
+ for (const line of plannedLines.querySelectorAll('[data-left]')) {
+ const clip = model.find(preview, line.dataset.left);
+ if (clip) line.style.left = `${pixels(clip.start + clip.frames)}px`;
+ }
+ gesture.result = result; showGuide(result.guide);
+ const tracks = gesture.ids.map(id => locate(id).track);
+ if (result.kind === 'extend') {
+ for (const id of gesture.ids) position(locate(id).element, gesture.clip.start, result.frame - gesture.clip.start);
+ const selection = {kind: 'range', start: result.frame, frames: result.frames, tracks};
+ const start = gesture.clip.start + gesture.clip.frames;
+ const plan = {...selection, start, frames: result.frame - start + result.frames};
+ box(previewBox, selection); borders(previewBox, selection, plan, model.emptyProject(state.record)); hint(selection, event, true);
+ box(selectionBox, {start: gesture.clip.start, frames: result.frame - gesture.clip.start, tracks});
+ } else {
+ previewBox.hidden = true; tooltip.hidden = true;
+ const clip = model.find(preview, gesture.id);
+ for (const id of gesture.ids) position(locate(id).element, clip.start, clip.frames);
+ box(selectionBox, {start: clip.start, frames: clip.frames, tracks});
+ hint({start: clip.start, frames: clip.frames}, event);
+ }
+ const growth = model.find(preview, gesture.id).start + model.find(preview, gesture.id).frames - originalEnd
+ + (result.kind === 'extend' ? result.frames : 0);
+ if (gesture.edge === 'end' && (growth > 0 || blocked)) {
+ clearTimeout(estimateTimer); estimateToken++;
+ tooltip.textContent = blocked ? '' : t(`+${Math.round(growth / model.FPS)} s`, `+${Math.round(growth / model.FPS)} 秒`);
+ tooltip.hidden = !!blocked;
+ selectionBox.classList.toggle('fv-ed-cannot-drop', !!blocked);
+ }
+ }
+ }
+ function stopPointer(event, cancel = false) {
+ if (!gesture || (event && gesture.pointer !== event.pointerId)) return;
+ cancelAnimationFrame(pointerFrame); pointerFrame = null; pointerEvent = null;
+ if (!cancel && event) updatePointer(event);
+ const finished = gesture; clearPreview(); gesture = null; selectionBox.classList.remove('fv-ed-dragging'); stopAutoScroll();
+ if (element.hasPointerCapture(finished.pointer)) element.releasePointerCapture(finished.pointer);
+ try {
+ if (cancel) { state.select(finished.previousSelection); if (finished.type === 'seek') state.seek(finished.previousPlayhead); return; }
+ if (finished.type === 'seek') return;
+ if (!finished.moved || finished.type === 'click') {
+ clickSelection({target: finished.target, clientX: event.clientX, range: finished.range, clipId: finished.id}); return;
+ }
+ if (finished.type === 'rangeMove' && finished.rangeBlocked) return;
+ if (['range', 'rangeMove', 'rangeEdge', 'rangeBoundary'].includes(finished.type)) { state.select(finished.selection, {history: true}); return; }
+ const result = finished.result;
+ if (!result) return;
+ if (finished.type === 'move') attempt(t('Move', '移动'), record => model.move(record, finished.id, result.frame));
+ else if (finished.type === 'plannedBoundary') attempt(t('Resize parts', '调整段长'), record => model.resizePlannedBoundary(record, finished.id, finished.neighbor.clip.id, result.frame, actions.generationLimits?.()));
+ else if (result.kind === 'planned') attempt(t('Resize', '改长短'), record => model.resizePlanned(record, finished.id, finished.edge, result.frame, actions.generationLimits?.()));
+ else if (result.kind === 'extend') {
+ const frames = result.frame - finished.clip.start - finished.clip.frames + result.frames;
+ let next = null;
+ try { next = model.extendClip(state.record, finished.id, frames, actions.generationLimits?.() || {}); }
+ catch (error) { if (!(error instanceof model.EditError)) throw error; actions.editError?.(error); }
+ if (next) {
+ // The new parts stay selected through undo and redo, so Generate stays usable.
+ const clip = model.find(next, finished.id), start = clip.start + clip.frames;
+ const ids = next.tracks[0].clips.filter(c => c.pending === 'draft' && c.start >= start && c.start < start + result.frames)
+ .flatMap(c => model.pair(next, c.id).map(member => member.id));
+ attempt(t('Extend', '拉长'), () => next, ids.length ? {selectionAfter: {kind: 'clip', ids}} : undefined);
+ }
+ } else attempt(t('Trim', '裁短'), record => model.trim(record, finished.id, finished.edge, result.frame));
+ renderSelection();
+ } finally { actions.gestureEnd?.(); }
+ }
+ function stopAutoScroll() { cancelAnimationFrame(autoFrame); autoFrame = null; }
+ function autoScroll() {
+ autoFrame = null;
+ if (!gesture?.moved || gesture.type === 'click') return;
+ const bounds = scroll.getBoundingClientRect();
+ const speed = dragX < bounds.left + 28 ? -12 : dragX > bounds.right - 28 ? 12 : 0;
+ if (speed) {
+ const old = scroll.scrollLeft; scroll.scrollLeft += speed;
+ if (scroll.scrollLeft !== old && pointerEvent) updatePointer(pointerEvent);
+ }
+ autoFrame = requestAnimationFrame(autoScroll);
+ }
+ function pointerMove(event) {
+ if (selectGestures.move(event)) return;
+ if (!gesture) {
+ const hit = pointerHit(event);
+ element.dataset.cursor = hit.item && busy(hit.item.clip) ? 'default' : hit.edge || hit.boundary != null || hit.neighbor ? 'ew-resize'
+ : hit.item || hit.range ? 'grab' : 'default';
+ return;
+ }
+ if (!gesture || gesture.pointer !== event.pointerId) return;
+ event.preventDefault(); event.stopPropagation(); pointerEvent = event;
+ if (!pointerFrame) pointerFrame = requestAnimationFrame(() => { pointerFrame = null; updatePointer(pointerEvent); });
+ if (!autoFrame) autoFrame = requestAnimationFrame(autoScroll);
+ }
+ function dismissPopup(event) {
+ if (popover.hidden) return false;
+ event.preventDefault(); event.stopPropagation(); popover.hidden = true; return true;
+ }
+ function keyboard(event) {
+ if (event.isComposing || event.keyCode === 229) return;
+ if (menu.keyboard(event)) return;
+ if (event.key.toLowerCase() === 'escape' && dismissPopup(event)) return;
+ if (isTyping(event.target) || event.target.closest('.fv-ed-library')) { event.stopPropagation(); return; }
+ event.stopPropagation();
+ if (!gesture && selectGestures.keyboard(event)) return;
+ const key = event.key.toLowerCase(), modifier = event.ctrlKey || event.metaKey;
+ if (key === 'escape') { event.preventDefault(); if (gesture) stopPointer(null, true); else { state.select(null, {history: true}); popover.hidden = true; } }
+ else if (gesture) { event.preventDefault(); }
+ else if (key === ' ' && !modifier) { event.preventDefault(); actions.togglePlay?.(); }
+ else if (key === 'arrowleft' || key === 'arrowright') { event.preventDefault(); state.seek(Math.max(0, state.playhead + (key === 'arrowleft' ? -1 : 1))); }
+ else if ((key === 'arrowup' || key === 'arrowdown') && !modifier && !event.altKey) {
+ event.preventDefault(); actions.pause?.();
+ const points = model.snapPoints(state.record), range = state.selection;
+ if (range?.kind === 'range') {
+ points.push(range.start, range.start + range.frames);
+ let boundary = range.start;
+ try { for (const count of rangeParts(range).slice(0, -1)) { boundary += count; points.push(boundary); } }
+ catch (error) { if (!(error instanceof model.EditError)) throw error; }
+ }
+ const ordered = [...new Set([0, model.duration(state.record), ...points])].sort((a, b) => a - b);
+ const target = key === 'arrowup' ? ordered.findLast(point => point < state.playhead) : ordered.find(point => point > state.playhead);
+ if (target != null) state.seek(target);
+ if (range?.kind === 'range') layout();
+ const x = pixels(state.playhead);
+ if (x < scroll.scrollLeft) scroll.scrollLeft = x;
+ else if (x > scroll.scrollLeft + scroll.clientWidth) scroll.scrollLeft = x - scroll.clientWidth;
+ }
+ else if (modifier && key === 'z') { event.preventDefault(); event.shiftKey ? state.redo() : state.undo(); }
+ else if (key === 'z' && event.shiftKey && !event.altKey) { event.preventDefault(); fitAll(); }
+ else if ((key === 'enter' || key === ' ') && event.target.matches('.fv-ed-clip')) { event.preventDefault(); clickSelection({target: event.target}); }
+ }
+ let sourcePreview = null;
+ function clearSourcePreview() {
+ if (!sourcePreview) return;
+ sourcePreview.nodes.forEach(node => node.remove());
+ if (sourcePreview.restore) {
+ if (sourcePreview.record === state.record) sourcePreview.restore();
+ else renderRecord();
+ }
+ sourcePreview = null; tooltip.hidden = true;
+ }
+ function previewSourcePlacement(record) {
+ const nodes = [], added = record.tracks.flatMap(track => track.clips
+ .filter(clip => !clips.has(clip.id)).map(clip => ({track: track.id, clip})));
+ sourcePreview = {record: state.record, nodes};
+ if (added.some(item => item.track === 'a2') && !rows.has('a2')) {
+ const first = rows.get('a1'), top = first.top + first.height + 6;
+ const row = create('div', 'fv-ed-track-row'); row.dataset.track = 'a2'; row.dataset.preview = 'true';
+ const head = create('div', 'fv-ed-track-head'); head.dataset.track = 'a2'; head.dataset.preview = 'true';
+ const name = t('Audio 2', '声音 2'); head.title = name; head.append(icon('audio'), create('span', '', name));
+ row.setAttribute('aria-label', name);
+ row.style.top = head.style.top = `${top}px`; row.style.height = head.style.height = '40px';
+ const oldName = first.head.title, oldTop = addAudio.style.top, oldHeight = content.style.height, oldPlayhead = playhead.style.height;
+ sourcePreview.restore = () => {
+ first.head.title = oldName; first.head.querySelector('span').textContent = oldName;
+ addAudio.style.top = oldTop; content.style.height = oldHeight; playhead.style.height = oldPlayhead;
+ };
+ first.head.title = t('Audio 1', '声音 1'); first.head.querySelector('span').textContent = first.head.title;
+ addAudio.style.top = `${top + 46}px`; content.style.height = `${top + 40}px`; playhead.style.height = `${top + 22}px`;
+ heads.insertBefore(head, addAudio); content.insertBefore(row, overlays); nodes.push(head, row);
+ }
+ for (const {track, clip} of added) {
+ const node = create('div', 'fv-ed-gesture-preview fv-ed-source-placement'); node.dataset.track = track;
+ const row = rows.get(track), top = row?.top ?? rows.get('a1').top + rows.get('a1').height + 6;
+ node.style.top = `${top}px`; node.style.height = `${row?.height ?? 40}px`;
+ position(node, clip.start, clip.frames); overlays.append(node); nodes.push(node);
+ }
+ return added;
+ }
+ function dropOver(event) {
+ if (!Array.from(event.dataTransfer?.types || []).includes(SOURCE_TYPE)) return;
+ event.preventDefault(); event.stopPropagation(); event.dataTransfer.dropEffect = 'copy';
+ const frame = snap(frameAt(event), allPoints([]), state.zoom);
+ const key = `${frame.frame}/${state.zoom}/${draggedSource ? JSON.stringify(draggedSource) : trackAt(event)}`;
+ if (key !== dropPreviewKey || sourcePreview?.record !== state.record) {
+ clearSourcePreview();
+ dropPreviewKey = key;
+ if (draggedSource) try {
+ const preview = model.insertSource(state.record, {...draggedSource, at: frame.frame});
+ const added = previewSourcePlacement(preview), sound = added.find(item => item.track !== 'v1');
+ const name = sound ? preview.tracks.length === 3
+ ? t(`Audio ${sound.track === 'a1' ? 1 : 2}`, `声音 ${sound.track === 'a1' ? 1 : 2}`) : t('Audio', '声音') : '';
+ dropPoint = {frame: added[0].clip.start, label: `${clock(added[0].clip.start)} – ${clock(added[0].clip.start + draggedSource.frames)}${name ? ` · ${name}` : ''}`};
+ } catch (error) {
+ if (!(error instanceof model.EditError)) throw error;
+ sourcePreview = {record: state.record, nodes: []};
+ dropPoint = {frame: frame.frame, error, label: null};
+ }
+ else {
+ const track = state.record.tracks.find(row => row.id === trackAt(event));
+ dropPoint = insertionPoint(track?.clips || [], frame.frame);
+ }
+ }
+ event.dataTransfer.dropEffect = dropPoint.error ? 'none' : 'copy';
+ showInsertion(dropPoint.frame); insertion.classList.toggle('fv-ed-blocked-insertion', !!dropPoint.error); showGuide(frame.guide);
+ tooltip.hidden = !dropPoint.label;
+ if (dropPoint.label) {
+ tooltip.textContent = dropPoint.label;
+ const bounds = element.getBoundingClientRect();
+ tooltip.style.left = `${clamp(event.clientX - bounds.left + 14, 8, Math.max(8, bounds.width - 300))}px`;
+ tooltip.style.top = `${clamp(event.clientY - bounds.top + 14, 26, bounds.height - 32)}px`;
+ }
+ }
+ function dropSource(event) {
+ clearSourcePreview();
+ const payload = sourcePayload(event.dataTransfer?.getData(SOURCE_TYPE));
+ if (!payload) { showInsertion(null); showGuide(null); return; }
+ event.preventDefault(); event.stopPropagation();
+ // Use the pointer position; the model chooses the audio track and shifts
+ // following clips. The insertion line is an indication, not an edit.
+ const at = snap(frameAt(event), allPoints([]), state.zoom).frame;
+ if (actions.insertSource) Promise.resolve(actions.insertSource({...payload, at}, {loadMetadata: true})).catch(error => actions.editError?.(error));
+ else attempt(t('Insert source', '放入素材'), record => model.insertSource(record, {...payload, at}), {clearRange: true});
+ showInsertion(null); showGuide(null); dropPoint = null; dropPreviewKey = ''; draggedSource = null;
+ }
+ function zoom(value, anchor = scroll.clientWidth / 2) {
+ const center = (scroll.scrollLeft + anchor) / state.zoom;
+ state.setZoom(clamp(value, Number(slider.min), Number(slider.max)));
+ scroll.scrollLeft = Math.max(0, center * state.zoom - anchor);
+ }
+ function fitAll() {
+ if (fit.disabled) return;
+ const rangeEnd = state.selection?.kind === 'range' ? state.selection.start + state.selection.frames : 0;
+ zoom(scroll.clientWidth / Math.max(2, Math.max(model.duration(state.record), rangeEnd) / model.FPS)); scroll.scrollLeft = 0;
+ }
+ function wheel(event) {
+ if (!event.ctrlKey && !event.metaKey) return;
+ event.preventDefault(); event.stopPropagation();
+ const unit = event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? scroll.clientWidth : 1;
+ const delta = (event.deltaY || event.deltaX || 0) * unit;
+ const anchor = clamp(event.clientX - scroll.getBoundingClientRect().left, 0, scroll.clientWidth);
+ zoom(state.zoom * Math.exp(-clamp(delta, -600, 600) * .002), anchor);
+ }
+ on(addAudio, 'pointerdown', event => event.stopPropagation());
+ const activateAudio = event => {
+ event.stopPropagation();
+ if (!addAudio.disabled) {
+ const removing = state.record.tracks.some(track => track.id === 'a2');
+ attempt(removing ? t('Remove Audio 2', '移除声音 2') : t('Add audio track', '添加声音轨'),
+ removing ? record => {
+ const next = model.removeAudioTrack(record), selection = state.selection;
+ // Record subscribers must not see a gap on a removed track.
+ if (selection?.kind === 'gap' && selection.track === 'a2') state.select(null);
+ else if (selection?.kind === 'range' && selection.tracks.includes('a2')) {
+ const tracks = selection.tracks.filter(id => id !== 'a2');
+ state.select(tracks.length ? {...selection, tracks} : null);
+ }
+ return next;
+ } : model.addAudioTrack);
+ }
+ };
+ // The shell also routes captured keys through control onkeydown handlers.
+ addAudio.onkeydown = event => {
+ if ((event.key === ' ' || event.key === 'Enter') && !event.ctrlKey && !event.metaKey && !event.altKey) {
+ event.preventDefault(); activateAudio(event);
+ }
+ };
+ on(addAudio, 'click', activateAudio);
+ on(element, 'pointerdown', startPointer); on(element, 'pointermove', pointerMove);
+ const menu = createTrackMenu(element, {state, t, actions, hitTest: pointerHit, frameAt, trackAt, choose: id => selectGestures.choose(id)});
+ on(element, 'pointerup', event => { if (selectGestures.finish(event)) return; event.stopPropagation(); stopPointer(event); });
+ on(element, 'pointercancel', event => { if (!selectGestures.finish(event, true)) stopPointer(event, true); });
+ on(element, 'lostpointercapture', event => { selectGestures.finish(event, true); if (gesture?.pointer === event.pointerId) stopPointer(event, true); });
+ on(element, 'keydown', keyboard); on(element, 'keyup', event => event.stopPropagation());
+ on(element, 'click', event => {
+ event.stopPropagation();
+ // Native keyboard/assistive activation has no preceding pointer gesture.
+ if (event.detail === 0 && event.target.closest('.fv-ed-clip')) clickSelection(event);
+ });
+ on(scroll, 'scroll', renderRuler, {passive: true});
+ on(scroll, 'scroll', renderEmptyHints, {passive: true});
+ on(scroll, 'wheel', wheel, {passive: false});
+ on(scroll, 'dragover', dropOver); on(scroll, 'drop', dropSource);
+ on(document, 'dragstart', event => {
+ clearSourcePreview();
+ draggedSource = sourcePayload(event.dataTransfer?.getData(SOURCE_TYPE)); dropPreviewKey = '';
+ });
+ on(document, 'dragend', () => { clearSourcePreview(); draggedSource = null; dropPreviewKey = ''; showInsertion(null); showGuide(null); });
+ on(scroll, 'dragleave', event => { if (!scroll.contains(event.relatedTarget)) { clearSourcePreview(); dropPreviewKey = ''; showInsertion(null); showGuide(null); } });
+ on(zoomOut, 'click', () => zoom(state.zoom / 1.25)); on(zoomIn, 'click', () => zoom(state.zoom * 1.25));
+ on(slider, 'input', () => zoom(Number(slider.value)));
+ on(fit, 'click', fitAll);
+ const unsubscribe = state.subscribe(event => {
+ if (event.type === 'record') {
+ // Status updates elsewhere must not cancel an unchanged moving pair.
+ if (gesture && !(gesture.type === 'move' && gesture.members.every(clip =>
+ JSON.stringify(model.find(state.record, clip.id)) === JSON.stringify(clip)))) stopPointer(null, true);
+ if (gesture) cachedPoints = allPoints(gesture.ids);
+ renderRecord();
+ } else if (event.type === 'selection') renderSelection();
+ else if (event.type === 'playhead') renderPlayhead();
+ else if (event.type === 'zoom') { if (gesture) stopPointer(null, true); layout(); }
+ });
+ const observer = new ResizeObserver(layout); observer.observe(scroll);
+ selectionBox.hidden = previewBox.hidden = guide.hidden = insertion.hidden = true;
+ renderRecord();
+ let blockedTimer = null, blockedIds = [];
+ function flashBlocked(frame = state.playhead) {
+ clearTimeout(blockedTimer);
+ for (const id of blockedIds) locate(id)?.element.classList.remove('fv-ed-cannot-drop');
+ for (const id of selected) locate(id)?.element.classList.add('fv-ed-cannot-drop');
+ blockedIds = [...selected];
+ showInsertion(frame); insertion.classList.add('fv-ed-blocked-insertion');
+ blockedTimer = setTimeout(() => {
+ for (const id of blockedIds) locate(id)?.element.classList.remove('fv-ed-cannot-drop');
+ blockedIds = [];
+ showInsertion(null); insertion.classList.remove('fv-ed-blocked-insertion');
+ }, 700);
+ }
+ return {element, keyboard, menu, dismissPopup, flashBlocked, seekPlayhead,
+ setSnapping(enabled) {
+ if (typeof enabled !== 'boolean') return {ok: false, reason: 'snapping'};
+ snapping = enabled; cachedPoints = allPoints(gesture?.ids || []);
+ return {ok: true, enabled};
+ },
+ refresh() { if (!disposed) renderRecord(); },
+ cancelGesture() { if (selectGestures.finish(null, true)) return true; if (!gesture) return false; stopPointer(null, true); return true; },
+ getScrollLeft() { return scroll.scrollLeft; },
+ setScrollLeft(value) { if (Number.isFinite(value) && value >= 0) { scroll.scrollLeft = value; renderRuler(); } },
+ setProgress(clipId, value) {
+ if (disposed) return;
+ const normalized = typeof value === 'number' ? {state: 'generating', fraction: value, remainingSeconds: null} : value;
+ for (const id of pairIds(clipId)) { progresses.set(id, normalized); const item = locate(id); if (item) updateProgress(item); }
+ },
+ dispose() {
+ if (disposed) return;
+ if (gesture) stopPointer(null, true);
+ selectGestures.dispose();
+ menu.dispose();
+ disposed = true; clearTimeout(blockedTimer); unsubscribe(); observer.disconnect(); listeners.forEach(remove => remove());
+ addAudio.onkeydown = null;
+ cancelAnimationFrame(pointerFrame); stopAutoScroll(); clearTimeout(estimateTimer); estimateToken++;
+ clips.forEach(item => item.component?.dispose()); element.remove();
+ }};
+}
diff --git a/web/fonts.js b/web/fonts.js
index 44789b1..3830863 100644
--- a/web/fonts.js
+++ b/web/fonts.js
@@ -20,13 +20,14 @@ const key = name => FAMILIES[name] ? name : 'sans';
export const fontWeight = weight => Number(weight) >= 550 ? 700 : 400;
export function fontFamily(name) { return FAMILIES[key(name)].family; }
// The CSS font list for a family: itself, the sans for what it lacks, then the box.
-export function fontStack(name) {
+// Alone, the family goes straight to the box, so what it lacks shows as missing.
+export function fontStack(name, {alone = false} = {}) {
const k = key(name), names = [FAMILIES[k].family];
- if (k !== 'sans') names.push(FAMILIES.sans.family);
+ if (k !== 'sans' && !alone) names.push(FAMILIES.sans.family);
names.push(BOX.family);
return names.map(family => `"${family}"`).join(',');
}
-export const fontCSS = (name, weight, size) => `${fontWeight(weight)} ${size}px ${fontStack(name)}`;
+export const fontCSS = (name, weight, size, options) => `${fontWeight(weight)} ${size}px ${fontStack(name, options)}`;
const faces = new Map(), ready = new Set();
function face(family, file, weight, descriptor = String(weight)) {
diff --git a/web/frame_sizes.js b/web/frame_sizes.js
new file mode 100644
index 0000000..6322ebf
--- /dev/null
+++ b/web/frame_sizes.js
@@ -0,0 +1,11 @@
+// Shared creation/editor aspect names and the creation panel's 32-pixel sizing.
+export const frameShapes = t => [
+ ['16:9', t('Landscape', '横屏'), 16 / 9],
+ ['9:16', t('Portrait', '竖屏'), 9 / 16],
+ ['1:1', t('Square', '方形'), 1],
+];
+export function frameSize(pixels, ratio) {
+ const total = pixels * 1024 ** 2;
+ return {width: Math.round(Math.sqrt(total * ratio) / 32) * 32,
+ height: Math.round(Math.sqrt(total / ratio) / 32) * 32};
+}
diff --git a/web/freevideo.js b/web/freevideo.js
index fbe79a9..1dae408 100644
--- a/web/freevideo.js
+++ b/web/freevideo.js
@@ -1,13 +1,14 @@
import { createErrorPanel, errorText } from './error_panel.js';
import { app } from "../../scripts/app.js";
import { api } from "../../scripts/api.js";
+import { openEditorView } from './editor_entry.js';
import { openStudio, loraPanel, loraWarning, promptGuide } from "./studio.js";
import { createGenerationProgress, referenceTrimText, thermalText, encoderFileText, encoderFilePath } from './generation_progress.js';
import { createProgressConnection } from './progress_connection.js';
import { notifyCompatibility } from './compatibility.js';
import { startUpdateChecks } from './updates.js';
import { installNavigation, refreshNavigation, preferredView } from './view_navigation.js';
-import { attachReferencePicker, referenceItems, syncReferencePrompt } from './prompt_references.js';
+import { attachReferencePicker, referenceItems, syncReferencePrompt, referenceInputs } from './prompt_references.js';
import { outputDownloadURL } from './output_download.js';
import { shareButton } from './share.js';
import { reportFileName } from './report_issue.js';
@@ -65,6 +66,37 @@ function mediaKind(name) {
throw new Error(text("Choose an image, video or audio file", "请选择图片、视频或音频文件"));
}
+const referenceHelp = () => text('When one input receives several images, each counts as one reference.', '一个接口接入多张图片时,每张各算一个参考素材。');
+// Input names stay English like every other node's; the panel's chips are translated.
+const referenceSocket = index => `Reference image ${index + 1}`;
+const referenceLabel = index => text(`Reference image ${index + 1}`, `参考图片 ${index + 1}`);
+
+function syncReferenceSockets(node) {
+ if (!node.inputs || !node.addInput) return;
+ const last = referenceInputs.reduce((at, name, index) => node.inputs.find(i => i.name === name)?.link != null ? index : at, -1);
+ const count = Math.min(8, last + 2);
+ for (let index = node.inputs.length - 1; index >= 0; index--) {
+ const position = referenceInputs.indexOf(node.inputs[index].name);
+ if (position >= count && node.inputs[index].link == null) node.removeInput(index);
+ }
+ for (let index = 0; index < count; index++) {
+ const name = referenceInputs[index];
+ if (!node.inputs.some(i => i.name === name)) node.addInput(name, 'IMAGE', {shape: node.inputs.find(i => i.name === 'reference')?.shape});
+ const input = node.inputs.find(i => i.name === name);
+ input.label = referenceSocket(index); input.tooltip = referenceHelp();
+ }
+ const images = referenceInputs.map(name => node.inputs.find(i => i.name === name)).filter(Boolean);
+ const others = node.inputs.filter(i => !referenceInputs.includes(i.name));
+ const audio = others.findIndex(i => i.name === 'reference_audio');
+ const at = audio < 0 ? others.length : audio;
+ node.inputs.splice(0, node.inputs.length, ...others.slice(0, at), ...images, ...others.slice(at));
+ node.inputs.forEach((input, index) => {
+ const link = node.graph?.links?.get?.(input.link) ?? node.graph?.links?.[input.link];
+ if (link) link.target_slot = index;
+ });
+ node.setDirtyCanvas?.(true, true);
+}
+
function mediaPanel(node, mount = null) {
const serialized = node.widgets.find(w => w.name === "assets");
serialized.type = "hidden";
@@ -117,17 +149,28 @@ function mediaPanel(node, mount = null) {
const result = await response.json(); if (!response.ok) throw new Error(result.error || response.statusText);
return result;
}
+ // An agent's edit leaves its editor document beside the picture: open that, so people continue its layers.
+ async function agentEdit(file) {
+ if (!file.startsWith('freevideo/agent/') || mediaKind(file) !== 'image') return null;
+ try {
+ const response = await fetch(viewURL(file.replace(/\.[^./]+$/, '.edit.json')), {cache: 'no-store'});
+ if (!response.ok) return null;
+ const doc = await response.json(), base = doc?.version === 2 && doc.layers?.find(l => l.id === 'base');
+ return base?.src ? {edit: doc, source: base.src} : null;
+ } catch { return null; }
+ }
async function editImage(file, tool = null) {
if (node.isUploading) return;
const original = read().find(row => row.file === file);
if (!original) return;
- const source = original.source || original.file;
+ const agent = original.edit ? null : await agentEdit(original.file);
+ const source = original.source || agent?.source || original.file;
// Other pictures in this panel can be placed on the image as layers.
const library = read().filter(row => row.file !== file && mediaKind(row.file) === 'image')
.map(row => ({file: row.file, label: (row.source || row.file).split('/').pop()}));
let outcome;
try {
- outcome = await openImageEditor({source, name: source, target: videoSize(), edit: original.edit || null, role: original.role,
+ outcome = await openImageEditor({source, name: source, target: videoSize(), edit: original.edit || agent?.edit || null, role: original.role,
t: text, resolve: viewURL, upload: uploadOne, library, tool});
} catch (error) { message(text('The image could not be opened for editing.', '这张图片无法打开编辑。'), true); return; }
if (!outcome) return;
@@ -170,12 +213,12 @@ function mediaPanel(node, mount = null) {
const first = active.filter(row => row.role === "first").length + Number(linked('first'));
const last = active.filter(row => row.role === "last").length + Number(linked('last'));
const audioRefs = active.filter(row => row.role === 'reference' && mediaKind(row.file) === 'audio').length + Number(linked('reference_audio'));
- const refs = active.filter(row => row.role === "reference").length + Number(linked('reference')) + Number(linked('reference_audio'));
+ const refs = active.filter(row => row.role === "reference").length + referenceInputs.filter(linked).length + Number(linked('reference_audio'));
audioHelp.hidden = !audioRefs;
audioHelp.textContent = text('Use <Audio 1>, <Audio 2>, … in your prompt to guide the generated voice, music or rhythm. A clip is cut to the generated length, up to 15 seconds. Set accompanying images to Reference.',
'在提示词中用 <Audio 1>、<Audio 2> 等标签引导生成的音色、音乐或节奏。片段只取与生成视频等长的部分,最长 15 秒;搭配的图片请选择“参考”用途。');
connections.replaceChildren();
- for (const [name, label] of [['first', text('First frame', '首帧')], ['last', text('Last frame', '尾帧')], ['reference', text('Reference image', '参考图像')], ['reference_audio', text('Reference audio', '参考音频')]]) {
+ for (const [name, label] of [['first', text('First frame', '首帧')], ['last', text('Last frame', '尾帧')], ...referenceInputs.map((name, index) => [name, referenceLabel(index)]), ['reference_audio', text('Reference audio', '参考音频')]]) {
if (!linked(name)) continue;
const link = node.graph?.links[node.inputs.find(i => i.name === name).link];
const source = link && node.graph?.getNodeById(link.origin_id);
@@ -183,8 +226,8 @@ function mediaPanel(node, mount = null) {
chip.title = source?.title || source?.type || label; connections.append(chip);
}
mode.textContent = refs ? text("Reference video · experimental", "参考生成 · 实验性") : first && last ? text("First + last frame", "首尾帧生成") : first ? text("Image to video", "图生视频") : last ? text("Last frame to video", "尾帧生成") : text("Text to video · media is optional", "文生视频 · 素材可留空");
- message(refs && (first || last) ? text("Choose keyframes or references. Disable unused cards.", "首尾帧与参考模式不能混用,请关闭本次不用的素材。") : first > 1 || last > 1 ? text("Keep only one first frame and one last frame enabled.", "首帧和尾帧各只能启用一张图片。") : text("Connect IMAGE / AUDIO outputs on the left, or drop / paste files here.", "可连接左侧 IMAGE / AUDIO 输入,或拖入、粘贴文件。"), Boolean(refs && (first || last) || first > 1 || last > 1));
- if (!rows.length && !connections.childElementCount) cards.append(el("div", text("Connect an image / audio node or upload files.\nLeave empty for text to video.", "连接图像/音频节点或上传文件。\n留空即可文生视频。"), "fv-empty"));
+ message(refs > 32 ? text(`There are ${refs} references and the limit is 32. Remove some before generating.`, `参考素材有 ${refs} 个,超过了 32 个的上限,请减少后再生成。`) : refs && (first || last) ? text("Choose keyframes or references. Disable unused cards.", "首尾帧与参考模式不能混用,请关闭本次不用的素材。") : first > 1 || last > 1 ? text("Keep only one first frame and one last frame enabled.", "首帧和尾帧各只能启用一张图片。") : text("Connect IMAGE / AUDIO outputs on the left, or drop / paste files here.", "可连接左侧 IMAGE / AUDIO 输入,或拖入、粘贴文件。"), Boolean(refs > 32 || refs && (first || last) || first > 1 || last > 1));
+ if (!rows.length && !connections.childElementCount) cards.append(el("div", text("Leave empty for text to video.", "留空则为文生视频。"), "fv-empty"));
if (!rows.length && connections.childElementCount) cards.append(el('div', text('Media will come from the connected nodes.\nNo upload is needed.', '素材由已连接的节点提供。\n无需上传文件。'), 'fv-connected-card'));
rows.forEach((row, index) => {
const card = el("div", undefined, "fv-card"); card.dataset.enabled = String(row.enabled !== false);
@@ -282,10 +325,10 @@ function mediaPanel(node, mount = null) {
const removed = node.onRemoved;
node.onRemoved = function (...args) { dispose(); return removed?.apply(this, args); };
const configure = node.onConfigure;
- node.onConfigure = function (...args) { const result = configure?.apply(this, args); render(); return result; };
+ node.onConfigure = function (...args) { const result = configure?.apply(this, args); queueMicrotask(() => { syncReferenceSockets(node); render(); }); return result; };
const connectionChanged = node.onConnectionsChange;
- node.onConnectionsChange = function (...args) { const result = connectionChanged?.apply(this, args); update(read()); return result; };
- node.setSize([460, 460]); render();
+ node.onConnectionsChange = function (...args) { const result = connectionChanged?.apply(this, args); queueMicrotask(() => { syncReferenceSockets(node); update(read()); }); return result; };
+ syncReferenceSockets(node); node.setSize([460, 460]); render();
}
function resultPanel(node) {
@@ -503,7 +546,7 @@ window.addEventListener('freevideo-media', () => syncPrompts());
// health.js names what failed; files loaded before it queue their reports.
const health = item => (window.__freevideoHealth ||= []).push(item);
function showStudio(node) {
- try { openStudio(node); } catch (error) { console.error('FreeVideo workspace:', error); health({type: 'error', where: 'studio', error}); }
+ try { return openStudio(node); } catch (error) { console.error('FreeVideo workspace:', error); health({type: 'error', where: 'studio', error}); }
}
const progressConnection = createProgressConnection(api, message => {
@@ -530,6 +573,14 @@ app.registerExtension({
await notifyCompatibility();
},
async beforeRegisterNodeDef(nodeType, nodeData) {
+ if (nodeData.name === 'FreeVideoMedia') {
+ nodeData.description = text(nodeData.description,
+ '连接图片、音频或上传文件。可以连接多张参考图片,上传的素材排在前面,连接的图片按从上到下的顺序排在后面。选择首尾帧或实验性参考生成,留空则为文生视频。');
+ for (const name of referenceInputs) {
+ const input = nodeData.input?.optional?.[name];
+ if (input) { input[1].tooltip = referenceHelp(); input[1].display_name = referenceSocket(referenceInputs.indexOf(name)); }
+ }
+ }
if (nodeData.name === 'FreeVideoReference') {
const connected = nodeType.prototype.onConnectionsChange;
nodeType.prototype.onConnectionsChange = function (...args) { const result = connected?.apply(this, args); queueMicrotask(syncPrompts); return result; };
@@ -593,9 +644,16 @@ app.registerExtension({
progressConnection.reset();
progressConnection.refresh();
refreshNavigation();
- if (app.graph?.extra?.freevideo_studio && preferredView() !== 'nodes') {
+ const rememberedView = preferredView();
+ if ((app.graph?.extra?.freevideo_studio || rememberedView === 'editor') && rememberedView !== 'nodes') {
const node = app.graph._nodes.find(n => n.comfyClass === 'FreeVideoGenerate' || n.type === 'FreeVideoGenerate');
- if (node) requestAnimationFrame(() => showStudio(node));
+ if (node) requestAnimationFrame(() => {
+ const studio = showStudio(node);
+ if (studio && rememberedView === 'editor') {
+ try { openEditorView(node, {studio}); }
+ catch (error) { console.error('FreeVideo edit view:', error); health({type: 'error', where: 'editor', error}); }
+ }
+ });
}
},
onNodeOutputsUpdated(outputs) {
diff --git a/web/health.js b/web/health.js
index 43de1d9..04746f7 100644
--- a/web/health.js
+++ b/web/health.js
@@ -13,10 +13,11 @@ const t = (en, zh) => cn ? zh : en;
// launcher.js removes this flag during setup; read it before that.
const launchVisit = query.get('freevideo') === 'launch';
// Every script this folder ships; a test keeps the list in step with web/*.js.
-export const MODULES = ['browser_extension.js', 'capability_view.js', 'compatibility.js', 'error_panel.js', 'fonts.js', 'freevideo.js', 'generation_progress.js',
- 'health.js', 'image_editor.js', 'image_editor_engine.js', 'launcher.js', 'library.js', 'motion.js', 'output_download.js', 'port_notice.js', 'preview_scene.js',
+export const MODULES = ['agent_activity.js', 'agent_connect.js', 'agent_session.js', 'browser_extension.js', 'capability_view.js', 'compatibility.js', 'error_panel.js', 'fonts.js', 'freevideo.js', 'generation_progress.js',
+ 'editor.js', 'editor_actions.js', 'editor_adjust.js', 'editor_adjust_picture.js', 'editor_picture_fields.js', 'editor_picture_session.js', 'editor_preview_picture.js', 'editor_entry.js', 'editor_export_dialog.js', 'editor_genbar.js', 'editor_geometry.js', 'editor_library.js', 'editor_menu.js', 'editor_model.js', 'editor_frame.js', 'editor_player.js', 'editor_room.js', 'editor_select.js', 'editor_state.js', 'editor_store.js', 'editor_tracks.js', 'editor_generation.js',
+ 'editor_text_coverage.js', 'editor_text.js', 'editor_text_model.js', 'editor_text_layout.js', 'editor_notes.js', 'editor_icons.js', 'dialog_keys.js', 'frame_sizes.js', 'health.js', 'image_commands.js', 'image_editor.js', 'image_editor_engine.js', 'launcher.js', 'library.js', 'motion.js', 'output_download.js', 'port_notice.js', 'preview_scene.js',
'progress_connection.js', 'prompt_draft.js', 'prompt_enhance.js', 'prompt_references.js', 'report_issue.js', 'studio_recent.js',
- 'result_actions.js', 'sampling_effort.js', 'setup.js', 'share.js', 'studio.js', 'studio_queue.js', 'studio_size.js',
+ 'result_actions.js', 'sampling_effort.js', 'setup.js', 'share.js', 'share_layout.js', 'studio.js', 'studio_queue.js', 'studio_size.js',
'toolbar_position.js', 'updates.js', 'view_navigation.js', 'wordmark.js'];
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
// A file the browser failed to load stays failed for the page's lifetime even
@@ -350,7 +351,8 @@ function sheetLoaded(name) {
function workspaceProblem(app) {
// Scripts that never started are already named by the load check.
if (!window.FreeVideoUI?.ready || !hasGenerate(app.graph)) return null;
- const studio = document.querySelector('dialog.fv-studio[open]');
+ // The editor shares the studio shell; either view replaces the floating toolbar.
+ const studio = document.querySelector('dialog.fv-editor[open]') || document.querySelector('dialog.fv-studio[open]');
if (studio) return onScreen(studio) ? null
: {text: t('The creative workspace is open but cannot be seen on the page.', '创作面板已经打开,但页面上看不到。'), advice: 'reload'};
const bar = document.querySelector('.fv-view-navigation');
diff --git a/web/image_commands.js b/web/image_commands.js
new file mode 100644
index 0000000..639ccad
--- /dev/null
+++ b/web/image_commands.js
@@ -0,0 +1,273 @@
+// Immutable document commands shared by the editor and DOM-free hosts.
+// Names and text metrics belong to the caller; rendering stays in the engine.
+import {BLENDS, uid, emptyAdjust, orientedSize, orientMatrix, canvasRect, paintLayer, rasterKinds,
+ resizeDocument, scaleSelection} from './image_editor_engine.js';
+
+export class ImageEditError extends Error {
+ constructor(code, message) { super(message); this.name = 'ImageEditError'; this.code = code; }
+}
+const fail = (code, message) => { throw new ImageEditError(code, message); };
+const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));
+const finite = v => typeof v === 'number' && Number.isFinite(v);
+const positive = v => finite(v) && v > 0;
+const dimensions = (w, h) => { if (!positive(w) || !positive(h)) fail('range', 'Invalid dimensions'); };
+function layerOf(doc, id) {
+ const layer = doc.layers.find(l => l.id === id);
+ if (!layer) fail('not_found', 'Layer not found');
+ return layer;
+}
+function pixelLayer(doc, id) {
+ const layer = layerOf(doc, id);
+ if (!rasterKinds.has(layer.kind)) fail('not_pixel_layer', 'An image or paint layer is required');
+ return layer;
+}
+const replace = (doc, id, patch) => ({...doc, layers: doc.layers.map(l => l.id === id ? {...l, ...patch} : l)});
+const requireSelection = selection => { if (!selection) fail('no_selection', 'A selection is required'); };
+function fields(patch, allowed) {
+ if (!patch || typeof patch !== 'object' || Array.isArray(patch)) fail('unsupported', 'Expected a property object');
+ if (Object.keys(patch).some(key => !allowed.includes(key))) fail('unsupported', 'Unsupported property');
+}
+
+export function commitStep({history, future}, next, limit = 80) {
+ if (!Number.isInteger(limit) || limit < 1) fail('range', 'Invalid history limit');
+ const last = history[history.length - 1];
+ if (next === last || (last && JSON.stringify(next) === JSON.stringify(last))) return {history, future, doc: last};
+ return {history: [...history, next].slice(-limit), future: [], doc: next};
+}
+function travel({history, future, doc = history[history.length - 1], selection = null}, direction) {
+ if (direction < 0 ? history.length <= 1 : !future.length) fail('range', 'No history step available');
+ const nextHistory = direction < 0 ? history.slice(0, -1) : [...history, future[future.length - 1]];
+ const nextFuture = direction < 0 ? [...future, history[history.length - 1]] : future.slice(0, -1);
+ let next = nextHistory[nextHistory.length - 1];
+ if (!next.layers.some(l => l.id === next.active)) next = {...next, active: next.layers[next.layers.length - 1].id};
+ const sx = next.width / doc.width, sy = next.height / doc.height;
+ return {history: nextHistory, future: nextFuture, doc: next,
+ selection: sx === 1 && sy === 1 ? selection : scaleSelection(selection, sx, sy), scale: {sx, sy}};
+}
+export function undoStep(state) { return travel(state, -1); }
+export function redoStep(state) { return travel(state, 1); }
+
+export function insertLayer(doc, layer) {
+ const index = doc.layers.findIndex(l => l.id === doc.active);
+ if (index < 0) fail('not_found', 'Active layer not found');
+ if (doc.layers.some(l => l.id === layer.id)) fail('unsupported', 'Duplicate layer id');
+ const layers = [...doc.layers]; layers.splice(index + 1, 0, layer);
+ return {...doc, layers, active: layer.id};
+}
+export function addPaintLayer(doc, name) { return insertLayer(doc, paintLayer(doc, name)); }
+function upright(doc, w, h, angle = 0) {
+ return {w, h, rotation: (doc.flipX !== doc.flipY ? -angle : angle) - doc.rotate, flipX: doc.flipX, flipY: doc.flipY};
+}
+function centre(doc, point) {
+ const p = orientMatrix(doc).inverse().transformPoint(new DOMPoint(...point));
+ return [p.x, p.y];
+}
+function newLayer(doc, kind, name, point, w, h, angle = 0) {
+ return {id: uid('l'), kind, name, visible: true, locked: false, opacity: 1, blend: 'source-over',
+ cx: point[0], cy: point[1], ...upright(doc, w, h, angle), ops: [], mask: null, adjust: emptyAdjust()};
+}
+export function addImageLayer(doc, {src, nw, nh, name}) {
+ dimensions(nw, nh);
+ const r = canvasRect(doc), point = centre(doc, [r.x + r.w / 2, r.y + r.h / 2]);
+ // Preserve the editor's .66 fit factor (rather than changing it to 2/3).
+ const s = Math.min(1, r.w * .66 / nw, r.h * .66 / nh);
+ return insertLayer(doc, {...newLayer(doc, 'image', name, point, nw * s, nh * s), src, nw, nh});
+}
+export function duplicateLayer(doc, id, name) {
+ return insertLayer(doc, {...layerOf(doc, id), id: uid('l'), locked: false, name});
+}
+export function deleteLayer(doc, id) {
+ const layer = layerOf(doc, id);
+ if (layer.locked) fail('locked', 'Layer is locked');
+ if (doc.layers.length === 1) fail('range', 'Cannot delete the last layer');
+ const index = doc.layers.findIndex(l => l.id === id), layers = doc.layers.filter(l => l.id !== id);
+ return {...doc, layers, active: layers[Math.max(0, index - 1)].id};
+}
+export function moveLayer(doc, id, delta) {
+ layerOf(doc, id);
+ const index = doc.layers.findIndex(l => l.id === id), to = index + delta;
+ if (!Number.isInteger(delta) || index < 1 || to < 1 || to >= doc.layers.length) fail('range', 'Layer move out of range');
+ const layers = [...doc.layers]; [layers[index], layers[to]] = [layers[to], layers[index]];
+ return {...doc, layers};
+}
+export function setActive(doc, id) { layerOf(doc, id); return {...doc, active: id}; }
+export function renameLayer(doc, id, name) { layerOf(doc, id); return replace(doc, id, {name}); }
+export function setLayer(doc, id, patch) {
+ layerOf(doc, id);
+ fields(patch, ['visible', 'locked', 'opacity', 'blend', 'adjust']);
+ for (const key of ['visible', 'locked']) if (key in patch && typeof patch[key] !== 'boolean') fail('unsupported', 'Expected a boolean');
+ if ('opacity' in patch && (!finite(patch.opacity) || patch.opacity < 0 || patch.opacity > 1)) fail('range', 'Invalid opacity');
+ if ('blend' in patch && !BLENDS.includes(patch.blend)) fail('unsupported', 'Unsupported blend');
+ if ('adjust' in patch) {
+ fields(patch.adjust, Object.keys(emptyAdjust()));
+ for (const [key, v] of Object.entries(patch.adjust)) {
+ const lo = ['sharpen', 'blur', 'noise'].includes(key) ? 0 : key === 'hue' ? -180 : -100;
+ if (!finite(v) || v < lo || v > (key === 'hue' ? 180 : 100)) fail('range', 'Invalid adjustment');
+ }
+ }
+ return replace(doc, id, patch);
+}
+export function toggleMask(doc, id, selection) {
+ // Any layer can drop a mask it has; only image and paint layers get a new one.
+ if (layerOf(doc, id).mask) return {doc: replace(doc, id, {mask: null}), maskTarget: false, selectionUsed: false};
+ pixelLayer(doc, id);
+ return {doc: replace(doc, id, {mask: {ops: selection ? [{id: uid('o'), type: 'fromSelection', selection}] : []}}),
+ maskTarget: true, selectionUsed: !!selection};
+}
+
+const ratios = {'16:9': 16 / 9, '9:16': 9 / 16, '1:1': 1, '4:3': 4 / 3, '3:4': 3 / 4};
+function aspectOf(id, r, target) {
+ if (id === 'video') { if (target) dimensions(target.width, target.height); return target ? target.width / target.height : null; }
+ if (id === 'original') return r.w / r.h;
+ if (id === 'free') return null;
+ if (!Object.keys(ratios).includes(id)) fail('unsupported', 'Unsupported ratio');
+ return ratios[id];
+}
+function fitRect(aspect, r) {
+ let w = r.w, h = r.w / aspect;
+ if (h > r.h) { h = r.h; w = h * aspect; }
+ return {x: r.x + (r.w - w) / 2, y: r.y + (r.h - h) / 2, w, h};
+}
+export function setRatio(doc, ratioId, target = null) {
+ const r = canvasRect(doc), aspect = aspectOf(ratioId, r, target);
+ let crop = {...doc.crop};
+ if (aspect) {
+ const fitted = fitRect(aspect, r), cx = crop.x + crop.w / 2, cy = crop.y + crop.h / 2;
+ crop = {...fitted, x: clamp(cx - fitted.w / 2, r.x, r.x + r.w - fitted.w), y: clamp(cy - fitted.h / 2, r.y, r.y + r.h - fitted.h)};
+ }
+ return {...doc, ratio: ratioId, crop};
+}
+export function turn(doc, op, target = null) {
+ if (!['cw', 'ccw', 'flipX', 'flipY'].includes(op)) fail('unsupported', 'Unsupported turn');
+ const before = canvasRect(doc), next = {...doc}, e = doc.extend;
+ if (op === 'cw' || op === 'ccw') {
+ const mirrored = doc.flipX !== doc.flipY;
+ next.rotate = (doc.rotate + ((op === 'cw') !== mirrored ? 90 : 270)) % 360;
+ next.extend = op === 'cw' ? {...e, l: e.b, t: e.l, r: e.t, b: e.r} : {...e, l: e.t, t: e.r, r: e.b, b: e.l};
+ } else {
+ next[op] = !doc[op];
+ next.extend = op === 'flipX' ? {...e, l: e.r, r: e.l} : {...e, t: e.b, b: e.t};
+ }
+ const map = ([x, y]) => {
+ const u = (x - before.x) / before.w, v = (y - before.y) / before.h;
+ return op === 'cw' ? [1 - v, u] : op === 'ccw' ? [v, 1 - u] : op === 'flipX' ? [1 - u, v] : [u, 1 - v];
+ };
+ const after = canvasRect(next), c = doc.crop, a = map([c.x, c.y]), b = map([c.x + c.w, c.y + c.h]);
+ let crop = {x: after.x + Math.min(a[0], b[0]) * after.w, y: after.y + Math.min(a[1], b[1]) * after.h,
+ w: Math.abs(a[0] - b[0]) * after.w, h: Math.abs(a[1] - b[1]) * after.h};
+ if ((op === 'cw' || op === 'ccw') && doc.ratio !== 'free') {
+ const aspect = aspectOf(doc.ratio, after, target);
+ if (aspect) crop = fitRect(aspect, after);
+ }
+ return {...next, crop};
+}
+export function padToVideo(doc, target, color) {
+ if (!target) fail('unsupported', 'A video target is required');
+ dimensions(target.width, target.height);
+ const [ow, oh] = orientedSize(doc), aspect = target.width / target.height;
+ let l = 0, r = 0, t = 0, b = 0;
+ if (ow / oh < aspect) { const extra = Math.round(oh * aspect - ow); l = Math.floor(extra / 2); r = extra - l; }
+ else { const extra = Math.round(ow / aspect - oh); t = Math.floor(extra / 2); b = extra - t; }
+ const next = {...doc, extend: {l, t, r, b, color}, ratio: 'video'};
+ return {...next, crop: canvasRect(next)};
+}
+export function setCanvas(doc, extend) {
+ // The old dialog applies numeric values directly; its HTML min/max are not
+ // application guards. Preserve that policy when the resulting canvas fits.
+ if (['l', 't', 'r', 'b'].some(k => !finite(extend[k]))) fail('range', 'Invalid canvas extension');
+ const next = {...doc, extend: {...extend}};
+ const crop = canvasRect(next); dimensions(crop.w, crop.h);
+ return {...next, crop, ratio: 'free'};
+}
+export function imageSizeCheck(doc, w, h, target = null) {
+ // target affects UI advice, never whether a size is allowed.
+ if (![w, h].every(v => Number.isInteger(v) && v >= 1 && v <= 20000)) return {allowed: false, reason: 'dimensions'};
+ if (Math.max(w / doc.crop.w, h / doc.crop.h) > 2 + 1e-9) return {allowed: false, reason: 'enlargement'};
+ if (w * h > 64e6) return {allowed: false, reason: 'pixels'};
+ if (w === Math.round(doc.crop.w) && h === Math.round(doc.crop.h)) return {allowed: false, reason: 'unchanged'};
+ return {allowed: true, reason: null};
+}
+export function resizeImage(doc, w, h, keep = true, measure) {
+ const check = imageSizeCheck(doc, w, h);
+ if (!check.allowed) fail('range', check.reason);
+ if (doc.layers.some(l => l.kind === 'text') && typeof measure !== 'function') fail('unsupported', 'Text measurement is required');
+ return resizeDocument(doc, w, h, keep, measure);
+}
+// Crop drag constraints are pure too; the UI keeps pointer anchoring and preview.
+export function normalizeCrop(doc, crop, ratioId = doc.ratio, target = null) {
+ if (![crop.x, crop.y, crop.w, crop.h].every(finite)) fail('range', 'Invalid crop');
+ const r = canvasRect(doc), a = aspectOf(ratioId, r, target);
+ let {x, y, w, h} = crop;
+ w = clamp(w, 8, r.w); h = clamp(h, 8, r.h);
+ if (a) { if (w / h > a) w = h * a; else h = w / a; if (w > r.w) { w = r.w; h = w / a; } if (h > r.h) { h = r.h; w = h * a; } }
+ return {x: clamp(x, r.x, r.x + r.w - w), y: clamp(y, r.y, r.y + r.h - h), w, h};
+}
+
+export function addPart(selection, part, mode) {
+ if (!['replace', 'add', 'subtract', 'intersect'].includes(mode)) fail('unsupported', 'Unsupported selection mode');
+ if (mode === 'replace' || !selection) return {parts: [{...part, mode: 'replace'}], feather: part.feather || 0, invert: false};
+ return {...selection, parts: [...selection.parts, {...part, mode}]};
+}
+export function selectAll() { return {parts: [{shape: 'all', mode: 'replace'}], feather: 0, invert: false}; }
+export function invertSelection(selection) { return selection ? {...selection, invert: !selection.invert} : {...selectAll(), invert: true}; }
+export function pushOp(doc, layerId, op) {
+ const layer = pixelLayer(doc, layerId), entry = {id: uid('o'), ...op};
+ const mask = layer.mask && (op.tool === 'hide' || op.tool === 'reveal');
+ if (layer.locked && !mask) fail('locked', 'Layer is locked');
+ return replace(doc, layerId, mask ? {mask: {ops: [...layer.mask.ops, entry]}} : {ops: [...layer.ops, entry]});
+}
+export function fillSelection(doc, id, color, selection) { return pushOp(doc, id, {type: 'fill', color, selection}); }
+export function clearSelection(doc, id, selection) {
+ pixelLayer(doc, id); requireSelection(selection);
+ return pushOp(doc, id, {type: 'clear', selection});
+}
+export function copyToLayer(doc, id, selection, name) {
+ const layer = pixelLayer(doc, id);
+ const copy = {...layer, id: uid('l'), locked: false, src: null, name, ops: [], mask: null,
+ copyOf: {layer: layer.id, upto: layer.ops.length, selection}, adjust: {...layer.adjust}};
+ return insertLayer(doc, copy);
+}
+export function maskFromSelection(doc, id, selection) {
+ pixelLayer(doc, id); requireSelection(selection);
+ return replace(doc, id, {mask: {ops: [{id: uid('o'), type: 'fromSelection', selection}]}});
+}
+
+function measured(text, measure) {
+ if (typeof measure !== 'function') fail('unsupported', 'Text measurement is required');
+ const size = measure(text); dimensions(size.nw, size.nh); return size;
+}
+export function addTextLayer(doc, {position, name, text}, measure) {
+ if (!position?.every(finite) || position.length !== 2) fail('range', 'Invalid text position');
+ if (!positive(text.size)) fail('range', 'Invalid text size');
+ const {nw, nh} = measured(text, measure);
+ return insertLayer(doc, {...newLayer(doc, 'text', name, position, nw, nh), nw, nh, text: {...text}});
+}
+export function updateText(doc, id, patch, measure) {
+ const l = layerOf(doc, id);
+ if (l.kind !== 'text') fail('unsupported', 'A text layer is required');
+ fields(patch, ['content', 'font', 'weight', 'size', 'color', 'align', 'shadow', 'outline', 'lineHeight']);
+ if ('size' in patch && (!positive(patch.size) || patch.size < 6 || patch.size > 2000)) fail('range', 'Invalid text size');
+ if ('lineHeight' in patch && !positive(patch.lineHeight)) fail('range', 'Invalid line height');
+ const text = {...l.text, ...patch}, size = measured(text, measure);
+ const sx = l.w / l.nw, sy = l.h / l.nh;
+ return replace(doc, id, {text, ...size, w: size.nw * sx, h: size.nh * sy});
+}
+export function addShapeLayer(doc, {from, to, shape, name}) {
+ if (from?.length !== 2 || to?.length !== 2 || ![...from, ...to].every(finite)) fail('range', 'Invalid shape points');
+ if (!['rect', 'ellipse', 'line'].includes(shape.type)) fail('unsupported', 'Unsupported shape');
+ if (!positive(shape.width)) fail('range', 'Invalid stroke width');
+ const dx = to[0] - from[0], dy = to[1] - from[1], point = centre(doc, [(from[0] + to[0]) / 2, (from[1] + to[1]) / 2]);
+ const line = shape.type === 'line', w = line ? Math.hypot(dx, dy) : Math.max(4, Math.abs(dx)), h = line ? Math.max(shape.width * 2, 8) : Math.max(4, Math.abs(dy));
+ dimensions(w, h);
+ const angle = line ? Math.atan2(dy, dx) * 180 / Math.PI : 0;
+ return insertLayer(doc, {...newLayer(doc, 'shape', name, point, w, h, angle),
+ nw: Math.max(1, Math.round(w)), nh: Math.max(1, Math.round(h)), shape: {...shape}});
+}
+export function updateShape(doc, id, patch) {
+ const l = layerOf(doc, id);
+ if (l.kind !== 'shape') fail('unsupported', 'A shape layer is required');
+ fields(patch, ['fill', 'stroke', 'width', 'radius']);
+ if ('width' in patch && (!finite(patch.width) || patch.width < 1 || patch.width > 400)) fail('range', 'Invalid stroke width');
+ if ('radius' in patch && (!finite(patch.radius) || patch.radius < 0 || patch.radius > 2000)) fail('range', 'Invalid corner radius');
+ return replace(doc, id, {shape: {...l.shape, ...patch}});
+}
diff --git a/web/image_editor.js b/web/image_editor.js
index 299817c..b5d7ab1 100644
--- a/web/image_editor.js
+++ b/web/image_editor.js
@@ -3,8 +3,9 @@
// FreeVideo's own look. The original file is never changed: saving renders a
// new image and keeps the document, so the next visit starts from the original
// with every layer and step in place. Closing frees every canvas it made.
-import {BLENDS, uid, emptyAdjust, migrate, orientedSize, orientMatrix, canvasRect, layerMatrix, resizeDocument, scaleSelection,
- paintLayer, rasterKinds, measureText, Renderer} from './image_editor_engine.js';
+import {BLENDS, emptyAdjust, migrate, orientedSize, orientMatrix, canvasRect, layerMatrix, scaleSelection,
+ rasterKinds, measureText, Renderer} from './image_editor_engine.js';
+import * as commands from './image_commands.js';
import {FONT_KEYS, fontStack, fontLoaded, loadFont, loadFonts} from './fonts.js';
const css = document.createElement('link');
@@ -132,7 +133,7 @@ export async function openImageEditor({source, name, target = null, edit = null,
doc = {...doc, layers: doc.layers.map(l => l.id === 'base' ? {...l, name: t('Original', '原图')} : l)};
if (fresh && target && role !== 'reference') {
// A keyframe becomes the first or last frame of the video: start from its shape.
- doc = {...doc, ratio: 'video', crop: fitRect(target.width / target.height, canvasRect(doc))};
+ doc = 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)]);
@@ -259,12 +260,6 @@ export async function openImageEditor({source, name, target = null, edit = null,
const box = stage.getBoundingClientRect(), sx = stage.clientWidth / (box.width || 1), sy = stage.clientHeight / (box.height || 1);
return [(event.clientX - box.left) * sx, (event.clientY - box.top) * sy];
};
- function fitRect(aspect, r) {
- if (!aspect) return {...r};
- let w = r.w, h = r.w / aspect;
- if (h > r.h) { h = r.h; w = h * aspect; }
- return {x: r.x + (r.w - w) / 2, y: r.y + (r.h - h) / 2, w, h};
- }
const active = () => doc.layers.find(l => l.id === doc.active) || doc.layers[0];
const replaceLayer = (id, patch) => ({...doc, layers: doc.layers.map(l => l.id === id ? {...l, ...(typeof patch === 'function' ? patch(l) : patch)} : l)});
// A new layer that reads upright on screen whatever the canvas orientation;
@@ -279,24 +274,20 @@ export async function openImageEditor({source, name, target = null, edit = null,
// ----- history ------------------------------------------------------------------
// panels: true redraws the side panels and options; 'layers' only the layer list.
function commit(next, panels = true) {
- // The same state twice (a slider that reports its change again) is one step.
- const last = history[history.length - 1];
- if (next !== last && JSON.stringify(next) === JSON.stringify(last)) { doc = last; refresh(panels); return; }
- doc = next;
- if (next === last) { refresh(panels); return; }
- history.push(doc); if (history.length > HISTORY) history.shift();
- future = [];
+ ({history, future, doc} = commands.commitStep({history, future}, next, HISTORY));
refresh(panels);
}
// A step being dragged: drawn, not yet in the history.
function preview(next) { doc = next; refresh(false); }
function step(direction) {
- const before = doc;
- if (direction < 0 && history.length > 1) { future.push(history.pop()); doc = history[history.length - 1]; }
- else if (direction > 0 && future.length) { history.push(future.pop()); doc = history[history.length - 1]; }
- else return;
- followSize(before, doc);
- if (!doc.layers.some(l => l.id === doc.active)) doc = {...doc, active: doc.layers[doc.layers.length - 1].id};
+ if (direction < 0 ? history.length <= 1 : !future.length) return;
+ const next = (direction < 0 ? commands.undoStep : commands.redoStep)({history, future, doc, selection});
+ ({history, future, doc, selection} = next);
+ const {sx, sy} = next.scale;
+ if (sx !== 1 || sy !== 1) {
+ antsEdge = null;
+ if (opts.clone.source) opts.clone.source = [opts.clone.source[0] * sx, opts.clone.source[1] * sy];
+ }
if (maskTarget && !active().mask) maskTarget = false;
refresh(true);
}
@@ -593,10 +584,10 @@ export async function openImageEditor({source, name, target = null, edit = null,
el('span', layer.name || '', 'fv-ie-props-name'));
props.append(head);
const opacity = slider('fv-ie-opacity', t('Opacity', '不透明度'), 0, 100, 1, Math.round(layer.opacity * 100),
- v => preview(replaceLayer(layer.id, {opacity: v / 100})), v => commit(replaceLayer(layer.id, {opacity: v / 100})), '%');
+ v => preview(commands.setLayer(doc, layer.id, {opacity: v / 100})), v => commit(commands.setLayer(doc, layer.id, {opacity: v / 100})), '%');
const blend = el('select', null, 'fv-ie-select'); blend.id = 'fv-ie-blend';
for (const [value, text] of Object.entries(blendNames())) { const o = el('option', text); o.value = value; blend.append(o); }
- blend.value = layer.blend || 'source-over'; blend.onchange = () => commit(replaceLayer(layer.id, {blend: blend.value}));
+ blend.value = layer.blend || 'source-over'; blend.onchange = () => commit(commands.setLayer(doc, layer.id, {blend: blend.value}));
const basics = el('div', null, 'fv-ie-basics'); basics.append(opacity.row, field(t('Blend', '混合'), blend));
props.append(basics);
if (layer.kind === 'text') props.append(textProps(layer));
@@ -620,13 +611,13 @@ export async function openImageEditor({source, name, target = null, edit = null,
g.append(summary);
for (const [key, text] of items) {
const positive = ['sharpen', 'blur', 'noise'].includes(key), range = key === 'hue' ? 180 : 100;
- const set = v => l => ({adjust: {...(l.adjust || emptyAdjust()), [key]: v}});
+ const set = v => ({adjust: {...(doc.layers.find(l => l.id === layer.id).adjust || emptyAdjust()), [key]: v}});
g.append(slider(`fv-ie-${key}`, text, positive ? 0 : -range, range, 1, layer.adjust?.[key] || 0,
- v => preview(replaceLayer(layer.id, set(v))), v => commit(replaceLayer(layer.id, set(v)))).row);
+ v => preview(commands.setLayer(doc, layer.id, set(v))), v => commit(commands.setLayer(doc, layer.id, set(v)))).row);
}
box.append(g);
}
- box.append(button(t('Reset adjustments', '重置调整'), null, () => commit(replaceLayer(layer.id, {adjust: emptyAdjust()})), 'fv-ie-button fv-ie-quiet'));
+ box.append(button(t('Reset adjustments', '重置调整'), null, () => commit(commands.setLayer(doc, layer.id, {adjust: emptyAdjust()})), 'fv-ie-button fv-ie-quiet'));
return box;
}
const openGroups = new Set(['light']);
@@ -679,10 +670,7 @@ export async function openImageEditor({source, name, target = null, edit = null,
}
if (dialog.open && doc.layers.some(l => l.id === id)) commit(updateText(id, patch));
}
- function updateText(id, patch) {
- return replaceLayer(id, l => { const text = {...l.text, ...patch}; const size = measureText(text);
- const sx = l.w / l.nw, sy = l.h / l.nh; return {text, ...size, w: size.nw * sx, h: size.nh * sy}; });
- }
+ function updateText(id, patch) { return commands.updateText(doc, id, patch, measureText); }
function commitText(panels = true) {
if (!textEditing) return;
textEditing = false;
@@ -690,7 +678,7 @@ export async function openImageEditor({source, name, target = null, edit = null,
}
function shapeProps(layer) {
const box = el('div', null, 'fv-ie-fields'), s = layer.shape;
- const update = patch => commit(replaceLayer(layer.id, l => ({shape: {...l.shape, ...patch}})));
+ const update = patch => commit(commands.updateShape(doc, layer.id, patch));
const colourRow = (key, text, fallback) => {
const input = el('input'); input.type = 'color'; input.id = `fv-ie-shape-${key}`; input.value = s[key] || fallback;
const on = el('input'); on.type = 'checkbox'; on.checked = !!s[key]; on.setAttribute('aria-label', text);
@@ -738,7 +726,7 @@ export async function openImageEditor({source, name, target = null, edit = null,
const row = el('li', null, 'fv-ie-layer'); row.dataset.id = l.id;
row.setAttribute('aria-selected', String(l.id === doc.active));
const eye = iconButton(l.visible ? 'eye' : 'eyeOff', l.visible ? t('Hide layer', '隐藏图层') : t('Show layer', '显示图层'),
- e => { e.stopPropagation(); commit(replaceLayer(l.id, {visible: !l.visible})); }, 'fv-ie-eye');
+ e => { e.stopPropagation(); commit(commands.setLayer(doc, l.id, {visible: !l.visible})); }, 'fv-ie-eye');
const thumb = el('canvas', null, 'fv-ie-thumb'); thumb.width = 48; thumb.height = 34; drawThumb(thumb, l);
const name = el('span', l.name || t('Layer', '图层'), 'fv-ie-layer-name');
name.title = t('Double-click to rename', '双击重命名');
@@ -777,38 +765,29 @@ export async function openImageEditor({source, name, target = null, edit = null,
// Choosing a layer is not a step of its own: it rides on the current one.
function setActive(id) {
if (doc.active === id) return;
- doc = {...doc, active: id};
- if (history[history.length - 1].active !== id) history[history.length - 1] = {...history[history.length - 1], active: id};
+ doc = commands.setActive(doc, id);
+ if (history[history.length - 1].active !== id) history = [...history.slice(0, -1), commands.setActive(history[history.length - 1], id)];
draw(); controls(); showHint();
}
function renameLayer(layer, node) {
const input = el('input', null, 'fv-ie-rename'); input.value = layer.name; input.setAttribute('aria-label', t('Layer name', '图层名称'));
node.replaceWith(input); input.focus(); input.select();
let done = false;
- const finishRename = keep => { if (done) return; done = true; if (keep && input.value.trim() && input.value.trim() !== layer.name) commit(replaceLayer(layer.id, {name: input.value.trim()})); else renderLayers(); };
+ const finishRename = keep => { if (done) return; done = true; if (keep && input.value.trim() && input.value.trim() !== layer.name) commit(commands.renameLayer(doc, layer.id, input.value.trim())); else renderLayers(); };
input.onkeydown = e => { e.stopPropagation(); if (e.key === 'Enter') finishRename(true); if (e.key === 'Escape') { e.preventDefault(); finishRename(false); } };
input.onblur = () => finishRename(true);
input.onclick = e => e.stopPropagation();
}
- function insertLayer(layer, base = doc) {
- const index = base.layers.findIndex(l => l.id === base.active);
- const layers = [...base.layers]; layers.splice(index + 1, 0, layer);
- maskTarget = false;
- commit({...base, layers, active: layer.id});
- }
+ function commitInserted(next) { maskTarget = false; commit(next); }
function addPaintLayer() {
const n = doc.layers.filter(l => l.kind === 'paint').length + 1;
- insertLayer(paintLayer(doc, t(`Paint ${n}`, `绘画 ${n}`)));
+ commitInserted(commands.addPaintLayer(doc, t(`Paint ${n}`, `绘画 ${n}`)));
}
async function addImageLayer(file, label) {
try {
const img = await renderer.image(file); renderer.images.get(file).value = img;
- const r = rect(), centre = toD([r.x + r.w / 2, r.y + r.h / 2]);
- // Fit inside two thirds of the canvas, upright on screen.
- const s = Math.min(1, r.w * .66 / img.naturalWidth, r.h * .66 / img.naturalHeight);
- insertLayer({id: uid('l'), kind: 'image', name: label || file.split('/').pop(), src: file, visible: true, locked: false, opacity: 1, blend: 'source-over',
- cx: centre[0], cy: centre[1], ...upright(img.naturalWidth * s, img.naturalHeight * s), nw: img.naturalWidth, nh: img.naturalHeight,
- ops: [], mask: null, adjust: emptyAdjust()});
+ commitInserted(commands.addImageLayer(doc, {src: file, nw: img.naturalWidth, nh: img.naturalHeight,
+ name: label || file.split('/').pop()}));
select('move');
} catch { message(t('The image could not be added.', '图片无法添加。')); }
}
@@ -821,28 +800,25 @@ export async function openImageEditor({source, name, target = null, edit = null,
};
function duplicateLayer() {
const layer = active();
- insertLayer({...layer, id: uid('l'), locked: false, name: t(`${layer.name} copy`, `${layer.name} 副本`)});
+ commitInserted(commands.duplicateLayer(doc, layer.id, t(`${layer.name} copy`, `${layer.name} 副本`)));
}
function deleteLayer() {
const layer = active(); if (layer.locked) return;
- const index = doc.layers.findIndex(l => l.id === layer.id);
- const layers = doc.layers.filter(l => l.id !== layer.id);
maskTarget = false;
- commit({...doc, layers, active: layers[Math.max(0, index - 1)].id});
+ commit(commands.deleteLayer(doc, layer.id));
}
function moveLayer(delta) {
const index = doc.layers.findIndex(l => l.id === doc.active), to = index + delta;
if (index < 1 || to < 1 || to >= doc.layers.length) return;
- const layers = [...doc.layers]; [layers[index], layers[to]] = [layers[to], layers[index]];
- commit({...doc, layers});
+ commit(commands.moveLayer(doc, doc.active, delta));
}
function toggleMask() {
const layer = active();
- if (layer.mask) { maskTarget = false; commit(replaceLayer(layer.id, {mask: null})); return; }
- if (!rasterKinds.has(layer.kind)) return;
- maskTarget = true;
- commit(replaceLayer(layer.id, {mask: {ops: selection ? [{id: uid('o'), type: 'fromSelection', selection}] : []}}));
- if (selection) deselect();
+ if (!layer.mask && !rasterKinds.has(layer.kind)) return;
+ const next = commands.toggleMask(doc, layer.id, selection);
+ maskTarget = next.maskTarget;
+ commit(next.doc);
+ if (next.selectionUsed) deselect();
}
// ----- canvas: shape, orientation, size ----------------------------------------------
@@ -851,49 +827,10 @@ export async function openImageEditor({source, name, target = null, edit = null,
if (id === 'original') return r.w / r.h;
return RATIOS.find(x => x[0] === id)?.[1] || null;
}
- function setRatio(id) {
- const r = rect(), aspect = aspectOf(id, r);
- let crop = {...doc.crop};
- if (aspect) {
- const fitted = fitRect(aspect, r), cx = crop.x + crop.w / 2, cy = crop.y + crop.h / 2;
- crop = {...fitted, x: clamp(cx - fitted.w / 2, r.x, r.x + r.w - fitted.w), y: clamp(cy - fitted.h / 2, r.y, r.y + r.h - fitted.h)};
- }
- commit({...doc, ratio: id, crop});
- }
- function turn(op) {
- const before = canvasRect(doc), next = {...doc}, e = doc.extend;
- if (op === 'cw' || op === 'ccw') {
- const mirrored = doc.flipX !== doc.flipY;
- next.rotate = (doc.rotate + ((op === 'cw') !== mirrored ? 90 : 270)) % 360;
- next.extend = op === 'cw' ? {...e, l: e.b, t: e.l, r: e.t, b: e.r} : {...e, l: e.t, t: e.r, r: e.b, b: e.l};
- } else {
- next[op] = !doc[op];
- next.extend = op === 'flipX' ? {...e, l: e.r, r: e.l} : {...e, t: e.b, b: e.t};
- }
- // The crop follows the picture.
- const map = ([x, y]) => {
- const u = (x - before.x) / before.w, v = (y - before.y) / before.h;
- return op === 'cw' ? [1 - v, u] : op === 'ccw' ? [v, 1 - u] : op === 'flipX' ? [1 - u, v] : [u, 1 - v];
- };
- const after = canvasRect(next), c = doc.crop, a = map([c.x, c.y]), b = map([c.x + c.w, c.y + c.h]);
- let crop = {x: after.x + Math.min(a[0], b[0]) * after.w, y: after.y + Math.min(a[1], b[1]) * after.h,
- w: Math.abs(a[0] - b[0]) * after.w, h: Math.abs(a[1] - b[1]) * after.h};
- if ((op === 'cw' || op === 'ccw') && doc.ratio !== 'free') {
- const aspect = aspectOf(doc.ratio, after);
- if (aspect) crop = fitRect(aspect, after);
- }
- commit({...next, crop});
- }
+ function setRatio(id) { commit(commands.setRatio(doc, id, target)); }
+ function turn(op) { commit(commands.turn(doc, op, target)); }
// Pad (never crop) to the video's shape with the background colour.
- function padToVideo() {
- const [ow, oh] = orientedSize(doc), aspect = target.width / target.height;
- // Whole pixels in total, split between the two sides.
- let l = 0, r = 0, tp = 0, b = 0;
- if (ow / oh < aspect) { const extra = Math.round(oh * aspect - ow); l = Math.floor(extra / 2); r = extra - l; }
- else { const extra = Math.round(ow / aspect - oh); tp = Math.floor(extra / 2); b = extra - tp; }
- const next = {...doc, extend: {l, t: tp, r, b, color: bg}, ratio: 'video'};
- commit({...next, crop: canvasRect(next)});
- }
+ function padToVideo() { commit(commands.padToVideo(doc, target, bg)); }
function canvasDialog() {
stage.querySelector('.fv-ie-popover')?.remove();
const box = el('div', null, 'fv-ie-popover');
@@ -907,8 +844,8 @@ export async function openImageEditor({source, name, target = null, edit = null,
const buttons = el('div', null, 'fv-ie-row fv-ie-end');
buttons.append(button(t('Cancel', '取消'), null, () => box.remove()), button(t('Apply', '应用'), null, () => {
const extend = {l: +inputs.l.value || 0, t: +inputs.t.value || 0, r: +inputs.r.value || 0, b: +inputs.b.value || 0, color: color.value};
- const next = {...doc, extend}; box.remove();
- commit({...next, crop: canvasRect(next), ratio: 'free'});
+ const next = commands.setCanvas(doc, extend); box.remove();
+ commit(next);
}, 'fv-ie-button fv-ie-primary'));
box.append(el('h3', t('Canvas size', '画布大小')), el('p', t(`The picture is ${ow} × ${oh} px. Add space on each side:`, `画面 ${ow} × ${oh} 像素,在四周补充空间:`), 'fv-ie-opt-note'),
grid, field(t('Fill color', '补边颜色'), color), buttons);
@@ -982,11 +919,12 @@ export async function openImageEditor({source, name, target = null, edit = null,
// How big against the original; verb is the Chinese 缩到 or 放大到.
const share = verb => same ? t(`${pct(k)} of the original`, `${verb}原来的 ${pct(k)}`)
: t(`Width ${pct(kx)} and height ${pct(ky)} of the original`, `宽为原来的 ${pct(kx)}、高为原来的 ${pct(ky)}`);
- let text, warn = false, allowed = true;
- if (!valid(w) || !valid(h)) { text = t('Enter whole numbers from 1 to 20000.', '请输入 1 到 20000 的整数。'); warn = true; allowed = false; }
- else if (k > 2 + 1e-9) { text = t('You can enlarge up to 200% of the original.', '最多放大到原来的 200%。'); warn = true; allowed = false; }
- else if (w * h > 64e6) { text = t('Up to 64 megapixels; reduce the width or height.', '最多 6400 万像素,请减小宽或高。'); warn = true; allowed = false; }
- else if (w === now[0] && h === now[1]) { text = t('The same size as now.', '和现在一样大。'); allowed = false; }
+ let text, warn = false;
+ const {allowed, reason} = commands.imageSizeCheck(doc, w, h, target);
+ if (reason === 'dimensions') { text = t('Enter whole numbers from 1 to 20000.', '请输入 1 到 20000 的整数。'); warn = true; }
+ else if (reason === 'enlargement') { text = t('You can enlarge up to 200% of the original.', '最多放大到原来的 200%。'); warn = true; }
+ else if (reason === 'pixels') { text = t('Up to 64 megapixels; reduce the width or height.', '最多 6400 万像素,请减小宽或高。'); warn = true; }
+ else if (reason === 'unchanged') { text = t('The same size as now.', '和现在一样大。'); }
else if (kx > 1 + 1e-9 || ky > 1 + 1e-9) {
text = t(`${share()}; enlarging makes the picture softer.`, `${share('放大到')},画面会变模糊。`); warn = true;
} else if (target && presets[0][2] && w === presets[0][2][0] && h === presets[0][2][1]) {
@@ -1002,7 +940,7 @@ export async function openImageEditor({source, name, target = null, edit = null,
}
function apply() {
if (ok.disabled) return;
- const next = resizeDocument(doc, number(width), number(height), keep || same);
+ const next = commands.resizeImage(doc, number(width), number(height), keep || same, measureText);
followSize(doc, next);
box.remove(); stage.focus();
commit(next);
@@ -1019,15 +957,14 @@ export async function openImageEditor({source, name, target = null, edit = null,
// ----- selections ---------------------------------------------------------------------
function addPart(part, mode) {
- if (mode === 'replace' || !selection) selection = {parts: [{...part, mode: 'replace'}], feather: part.feather || 0, invert: false};
- else selection = {...selection, parts: [...selection.parts, {...part, mode}]};
+ selection = commands.addPart(selection, part, mode);
antsEdge = null; renderOptions(); draw();
}
- function selectAll() { selection = {parts: [{shape: 'all', mode: 'replace'}], feather: 0, invert: false}; antsEdge = null; renderOptions(); draw(); }
+ function selectAll() { selection = commands.selectAll(); antsEdge = null; renderOptions(); draw(); }
function deselectQuiet() { selection = null; antsEdge = null; }
function deselect() { deselectQuiet(); renderOptions(); draw(); }
function invertSelection() {
- selection = selection ? {...selection, invert: !selection.invert} : {parts: [{shape: 'all', mode: 'replace'}], feather: 0, invert: true};
+ selection = commands.invertSelection(selection);
antsEdge = null; renderOptions(); draw();
}
function pixelLayer() {
@@ -1035,25 +972,34 @@ export async function openImageEditor({source, name, target = null, edit = null,
if (!rasterKinds.has(layer.kind)) { message(t('Pick an image or paint layer first.', '请先选择图片图层或绘画图层。')); return null; }
return layer;
}
+ // The original UI's lock protects deletion and transforms, but permits retouching
+ // the base pixels. Keep that behaviour while the shared API enforces pixel locks.
+ function pixelCommand(base, id, command) {
+ const layer = base.layers.find(l => l.id === id);
+ if (!layer?.locked) return command(base);
+ const next = command(commands.setLayer(base, id, {locked: false}));
+ return commands.setLayer(next, id, {locked: true});
+ }
function pushOp(layer, op, base = doc) {
- const entry = {id: uid('o'), ...op};
- doc = base;
- // Only the brush and eraser paint a mask (hide / reveal); every other tool works on pixels.
- if (layer.mask && (op.tool === 'hide' || op.tool === 'reveal')) commit(replaceLayer(layer.id, l => ({mask: {ops: [...l.mask.ops, entry]}})));
- else commit(replaceLayer(layer.id, l => ({ops: [...l.ops, entry]})));
- }
- function fillSelection(color = fg) { const layer = pixelLayer(); if (layer) pushOp(layer, {type: 'fill', color, selection}); }
- function clearSelection() { const layer = pixelLayer(); if (layer && selection) pushOp(layer, {type: 'clear', selection}); }
+ commit(pixelCommand(base, layer.id, d => commands.pushOp(d, layer.id, op)));
+ }
+ function fillSelection(color = fg) {
+ const layer = pixelLayer();
+ if (layer) commit(pixelCommand(doc, layer.id, d => commands.fillSelection(d, layer.id, color, selection)));
+ }
+ function clearSelection() {
+ const layer = pixelLayer();
+ if (layer && selection) commit(pixelCommand(doc, layer.id, d => commands.clearSelection(d, layer.id, selection)));
+ }
function copyToLayer() {
const layer = pixelLayer(); if (!layer) return;
- const copy = {...layer, id: uid('l'), locked: false, src: null, name: t(`${layer.name} part`, `${layer.name} 局部`), ops: [], mask: null,
- copyOf: {layer: layer.id, upto: layer.ops.length, selection}, adjust: {...layer.adjust}};
- deselectQuiet(); insertLayer(copy); select('move');
+ const next = commands.copyToLayer(doc, layer.id, selection, t(`${layer.name} part`, `${layer.name} 局部`));
+ deselectQuiet(); commitInserted(next); select('move');
}
function maskFromSelection() {
const layer = pixelLayer(); if (!layer || !selection) return;
maskTarget = true;
- commit(replaceLayer(layer.id, {mask: {ops: [{id: uid('o'), type: 'fromSelection', selection}]}}));
+ commit(commands.maskFromSelection(doc, layer.id, selection));
deselect();
}
@@ -1152,13 +1098,11 @@ export async function openImageEditor({source, name, target = null, edit = null,
if ((tool === 'brush' || tool === 'gradient') && (!rasterKinds.has(layer.kind) || (layer.locked && !maskTarget))) {
// Paint goes on a layer of its own above the picture, so it can be erased or hidden alone.
const reuse = tool === 'brush' && [...doc.layers].reverse().find(l => l.kind === 'paint' && l.visible);
- if (reuse) { target = reuse; base = {...doc, active: reuse.id}; }
+ if (reuse) { target = reuse; base = commands.setActive(doc, reuse.id); }
else {
const n = doc.layers.filter(l => l.kind === 'paint').length + 1;
- target = paintLayer(doc, tool === 'gradient' ? t('Gradient', '渐变') : t(`Paint ${n}`, `绘画 ${n}`));
- const index = doc.layers.findIndex(l => l.id === doc.active);
- const layers = [...doc.layers]; layers.splice(index + 1, 0, target);
- base = {...doc, layers, active: target.id};
+ base = commands.addPaintLayer(doc, tool === 'gradient' ? t('Gradient', '渐变') : t(`Paint ${n}`, `绘画 ${n}`));
+ target = base.layers.find(l => l.id === base.active);
}
} else if (!rasterKinds.has(layer.kind)) { message(t('Pick an image or paint layer to work on its pixels.', '请选择图片图层或绘画图层再处理像素。')); return null; }
if (tool === 'gradient') {
@@ -1273,14 +1217,9 @@ export async function openImageEditor({source, name, target = null, edit = null,
return {...dragBox(o, (a, b) => {
const width = opts.shape.width, dx = b[0] - a[0], dy = b[1] - a[1];
if (Math.hypot(dx, dy) * layout.k < 4) return;
- const centre = toD([(a[0] + b[0]) / 2, (a[1] + b[1]) / 2]);
- let w, h, angle = 0;
- if (kind === 'line') { w = Math.hypot(dx, dy); h = Math.max(width * 2, 8); angle = Math.atan2(dy, dx) * 180 / Math.PI; }
- else { w = Math.max(4, Math.abs(dx)); h = Math.max(4, Math.abs(dy)); }
const shape = {type: kind, fill: kind === 'line' ? null : fg, stroke: kind === 'line' ? fg : null, width, radius: 0};
- insertLayer({id: uid('l'), kind: 'shape', name: {rect: t('Rectangle', '矩形'), ellipse: t('Ellipse', '椭圆'), line: t('Line', '直线')}[kind],
- visible: true, locked: false, opacity: 1, blend: 'source-over', cx: centre[0], cy: centre[1], ...upright(w, h, angle),
- nw: Math.max(1, Math.round(w)), nh: Math.max(1, Math.round(h)), shape, ops: [], mask: null, adjust: emptyAdjust()});
+ commitInserted(commands.addShapeLayer(doc, {from: a, to: b, shape,
+ name: {rect: t('Rectangle', '矩形'), ellipse: t('Ellipse', '椭圆'), line: t('Line', '直线')}[kind]}));
}, kind === 'ellipse'), ...(kind === 'line' ? {preview: null} : {})};
}
function cropGesture(event, o) {
@@ -1290,12 +1229,7 @@ export async function openImageEditor({source, name, target = null, edit = null,
const kind = handle ? 'resize' : inside ? 'move' : 'new';
const ratio = kind === 'new' && doc.ratio === 'original' ? 'free' : doc.ratio;
const aspect = () => aspectOf(ratio, r);
- const limit = c => {
- let {x, y, w, h} = c; const a = aspect();
- w = clamp(w, 8, r.w); h = clamp(h, 8, r.h);
- if (a) { if (w / h > a) w = h * a; else h = w / a; if (w > r.w) { w = r.w; h = w / a; } if (h > r.h) { h = r.h; w = h * a; } }
- return {x: clamp(x, r.x, r.x + r.w - w), y: clamp(y, r.y, r.y + r.h - h), w, h};
- };
+ const limit = c => commands.normalizeCrop(doc, c, ratio, target);
return {
move(p) {
const q = toO(...p);
@@ -1389,9 +1323,7 @@ export async function openImageEditor({source, name, target = null, edit = null,
const size = Math.max(16, Math.round(Math.min(doc.width, doc.height) / 12));
const text = {content: t('Text', '文字'), font: opts.text.font, size, color: fg, weight: opts.text.weight, align: opts.text.align,
shadow: opts.text.shadow, outline: opts.text.outline, lineHeight: 1.25};
- const {nw, nh} = measureText(text);
- insertLayer({id: uid('l'), kind: 'text', name: t('Text', '文字'), visible: true, locked: false, opacity: 1, blend: 'source-over',
- cx: d[0], cy: d[1], ...upright(nw, nh), nw, nh, text, ops: [], mask: null, adjust: emptyAdjust()});
+ commitInserted(commands.addTextLayer(doc, {position: d, name: t('Text', '文字'), text}, measureText));
requestAnimationFrame(() => { textArea?.focus(); textArea?.select(); });
}
diff --git a/web/image_editor_engine.js b/web/image_editor_engine.js
index 024eabe..ab23308 100644
--- a/web/image_editor_engine.js
+++ b/web/image_editor_engine.js
@@ -146,8 +146,9 @@ export function scaleSelection(selection, sx, sy) {
// stay sharp and editable. A layer's own edits are fractions of it and follow by themselves.
// keep (proportions locked): the same scale both ways, just enough to fill width × height, and
// the fraction of a pixel left over is cut from the right and bottom. Otherwise each way scales
-// on its own: pictures and shapes stretch, text keeps its shape. The text fonts must be loaded.
-export function resizeDocument(doc, width, height, keep = true) {
+// on its own: pictures and shapes stretch, text keeps its shape. The text fonts must be loaded
+// for the default measure callback; DOM-free callers supply their own text metrics.
+export function resizeDocument(doc, width, height, keep = true, measure = measureText) {
const c = doc.crop;
let kx = width / c.w, ky = height / c.h;
if (keep) kx = ky = Math.max(kx, ky);
@@ -168,7 +169,7 @@ export function resizeDocument(doc, width, height, keep = true) {
if (l.mask) next.mask = {...l.mask, ops: scaleOps(l.mask.ops)};
if (l.copyOf?.selection) next.copyOf = {...l.copyOf, selection: scaleSelection(l.copyOf.selection, sx, sy)};
if (l.kind === 'text') {
- const text = {...l.text, size: Math.max(1, Math.round(l.text.size * k * 10) / 10)}, size = measureText(text);
+ const text = {...l.text, size: Math.max(1, Math.round(l.text.size * k * 10) / 10)}, size = measure(text);
return {...next, text, ...size, w: size.nw * l.w / l.nw, h: size.nh * l.h / l.nh};
}
if (l.kind === 'shape') {
diff --git a/web/library.css b/web/library.css
index 99486d3..b61a2c6 100644
--- a/web/library.css
+++ b/web/library.css
@@ -43,3 +43,4 @@
.fv-library .fv-library-picture .fv-preview-badge{top:6px;left:6px;padding:1px 8px;font-size:10px}
.fv-library .fv-library-notice{min-height:0;margin:6px 0 0;text-align:center}
.fv-library .fv-library-notice:empty{display:none}
+.fv-library .fv-library-picture .fv-agent-badge{position:absolute;top:6px;right:6px;padding:1px 8px;border-radius:999px;font-size:10px;font-weight:var(--fv-medium);color:var(--fv-ink);background:color-mix(in srgb,var(--fv-bg) 72%,transparent);border:1px solid color-mix(in srgb,var(--fv-accent) 55%,transparent);backdrop-filter:blur(4px)}
diff --git a/web/library.js b/web/library.js
index e3725ec..2942c17 100644
--- a/web/library.js
+++ b/web/library.js
@@ -85,8 +85,8 @@ async function workflowBackfill(collection, t) {
}
// ``upscale`` queues the second pass of a first-pass preview (the studio's node).
-export function openLibrary(t, {upscale = null} = {}) {
- if (opened?.open) { opened.focus(); return; }
+export function openLibrary(t, {upscale = null, selectedWork = null} = {}) {
+ if (opened?.open) { if (selectedWork) opened.close(); else { opened.focus(); return; } }
const dialog = el('dialog', null, 'fv-studio fv-library'); opened = dialog;
dialog.setAttribute('aria-label', t('Your creations', '我的作品'));
const header = el('header', null, 'fv-library-header');
@@ -198,6 +198,8 @@ export function openLibrary(t, {upscale = null} = {}) {
if (!disposed && selected === row.video) mountPlayer(row);
throw new Error(error.message === 'foreign-files'
? 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 === '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.', '无法删除这条作品。'));
}
@@ -232,7 +234,13 @@ export function openLibrary(t, {upscale = null} = {}) {
image.onerror = () => { image.hidden = true; };
picture.append(image);
if (row.preview) picture.append(el('span', t('First-pass preview', '一采预览'), 'fv-preview-badge'));
- card.append(picture, el('span', timestamp(row)), el('small', dimensions(row)));
+ // Made by an AI agent: say so, with the name the agent gave the shot.
+ if (row.agent) {
+ const badge = el('span', 'Agent', 'fv-agent-badge');
+ badge.title = [row.agent.label, row.agent.project, row.agent.client].filter(Boolean).join(' · ');
+ picture.append(badge);
+ }
+ card.append(picture, el('span', row.agent?.label || timestamp(row)), el('small', row.agent?.label ? timestamp(row) : dimensions(row)));
cards.set(row.video, card); first ? grid.prepend(card) : grid.append(card); thumbnails.observe(image);
}
async function load(appendPage) {
@@ -252,6 +260,7 @@ export function openLibrary(t, {upscale = null} = {}) {
if (!narrow.matches && rows.size) select(rows.values().next().value, false);
else dialog.dataset.detail = 'false';
} else select(rows.get(selected), false);
+ if (selectedWork) { const row = [...rows.values()].find(row => row.id === selectedWork || row.video === selectedWork); if (row) { select(row); selectedWork = null; } else if (next) queueMicrotask(() => load(true)); }
} catch (error) { if (!disposed && error.name !== 'AbortError') message.textContent = error.message; }
finally { if (!disposed) { loading = false; refresh.disabled = more.disabled = false; } }
}
diff --git a/web/prompt_references.js b/web/prompt_references.js
index 9865929..160ec1c 100644
--- a/web/prompt_references.js
+++ b/web/prompt_references.js
@@ -3,6 +3,7 @@ const titles = {image: 'Picture', video: 'Video', audio: 'Audio'};
const widget = (node, name) => node?.widgets?.find(w => w.name === name);
const linkFor = (node, name) => node?.graph?.links?.[node.inputs?.find(i => i.name === name)?.link];
const sourceFor = (node, name) => node?.graph?.getNodeById(linkFor(node, name)?.origin_id);
+export const referenceInputs = ['reference', ...Array.from({length: 7}, (_, i) => `reference_${i + 2}`)];
export function referenceKind(file) {
const ext = String(file).split('.').pop().toLowerCase();
return ['png','jpg','jpeg','webp','bmp','tif','tiff'].includes(ext) ? 'image'
@@ -41,7 +42,7 @@ export function referenceItems(node) {
if (item && anchors[name]) throw new Error('invalid_media');
if (item) anchors[name] = item;
}
- for (const [name, kind] of [['reference','image'],['reference_audio','audio']]) {
+ for (const [name, kind] of [...referenceInputs.map(name => [name, 'image']), ['reference_audio','audio']]) {
const item = connected(media, name, kind); if (item) refs.push(item);
}
} else {
diff --git a/web/setup.js b/web/setup.js
index 723225e..e7db796 100644
--- a/web/setup.js
+++ b/web/setup.js
@@ -2,6 +2,7 @@ import { api } from "../../scripts/api.js";
import { wordmark } from './wordmark.js';
import { openCompatibility } from './compatibility.js';
import { animateDetails, closeDialog } from './motion.js';
+import { agentConnect } from './agent_connect.js';
const css = document.createElement('link');
css.rel = 'stylesheet'; css.href = new URL('./setup.css', import.meta.url).href;
@@ -147,7 +148,7 @@ export async function openSetup() {
// Why Install / repair is unavailable, so it never looks like a broken button.
const blocked = note(""); blocked.classList.add("fv-setup-why"); blocked.setAttribute("aria-live", "polite"); blocked.hidden = true;
installation.append(blocked);
- dialog.append(heading, installation, downloads, advanced);
+ dialog.append(heading, installation, downloads, agentConnect(t, api), advanced);
const motions = [...dialog.querySelectorAll('details')].map(animateDetails);
dialog.addEventListener('cancel', e => { e.preventDefault(); closeDialog(dialog); });
document.body.append(dialog); dialog.showModal();
diff --git a/web/share.js b/web/share.js
index f82b342..c4f6248 100644
--- a/web/share.js
+++ b/web/share.js
@@ -2,6 +2,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 {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);
const el=(tag,cls,text)=>{const e=document.createElement(tag);if(cls)e.className=cls;if(text)e.textContent=text;return e;};
@@ -30,11 +31,6 @@ let opened;
// 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)]);
-export function shareLayout(width,height) {
- const w=width>=height?1200:900, scale=w/width, footer=w>=1000?148:200;
- const h=Math.round(Math.min(1800,height*scale)/2)*2, artWidth=Math.round(h*width/height/2)*2;
- return {width:w,height:h+footer,rect:[Math.floor((w-artWidth)/2),0,artWidth,h],footer};
-}
export function drawShareCard(canvas,frame,logo,record,t) {
const g=record.geometry||{}, shape=shareLayout(g.width||frame?.naturalWidth||1344,g.height||frame?.naturalHeight||768);
diff --git a/web/share_layout.js b/web/share_layout.js
new file mode 100644
index 0000000..ee172c4
--- /dev/null
+++ b/web/share_layout.js
@@ -0,0 +1,8 @@
+// Sharing card geometry: 1200 wide for landscape videos and 900 for portrait ones. The picture keeps
+// the video's shape in even sizes and stays inside the card, as the server requires.
+export function shareLayout(width,height) {
+ const w=width>=height?1200:900, scale=w/width, footer=w>=1000?148:200;
+ let h=Math.round(Math.min(1800,height*scale)/2)*2, artWidth;
+ while((artWidth=Math.round(h*width/height/2)*2)>w)h-=2;
+ return {width:w,height:h+footer,rect:[Math.floor((w-artWidth)/2),0,artWidth,h],footer};
+}
diff --git a/web/studio.js b/web/studio.js
index c3a097e..8113173 100644
--- a/web/studio.js
+++ b/web/studio.js
@@ -12,13 +12,16 @@ import { createPreviewScene } from './preview_scene.js?v=20260929-swell';
import { animateDetails, closeDialog } from './motion.js';
import { openLibrary } from './library.js';
import { createRecentVideos } from './studio_recent.js';
+import { createAgentActivity } from './agent_activity.js';
import { createStudioQueue, randomSeed } from './studio_queue.js';
-import { attachReferencePicker, referenceItems, syncReferencePrompt } from './prompt_references.js';
+import { attachReferencePicker, referenceItems, syncReferencePrompt, referenceInputs } from './prompt_references.js';
import { createSamplingEffort } from './sampling_effort.js';
import { resultActions, previewBadge } from './result_actions.js';
import { createPromptEnhancer } from './prompt_enhance.js';
import { rememberPromptDraft } from './prompt_draft.js';
-import { canvasDimensions, imageSizeSelection } from './studio_size.js';
+import { openEditorView } from './editor_entry.js';
+import { frameShapes, frameSize } from './frame_sizes.js';
+import { imageSizeSelection } from './studio_size.js';
import { createCapabilityView } from './capability_view.js';
const languageOverride = typeof location !== 'undefined'
@@ -121,32 +124,38 @@ export function loraPanel(node, panel) {
}
let current;
+// Both top bars use the same exit and canvas fit.
+export function showNodes(node, dialog = null) {
+ if (dialog?.open) closeDialog(dialog);
+ viewChanged('nodes', node);
+ // Fit the graph in the visible canvas; never rewrite users' node positions.
+ const nodes = node.graph?._nodes || [], canvas = app.canvas?.canvas;
+ if (!nodes.length || !canvas) return;
+ const left = Math.min(...nodes.map(n => n.pos[0])), top = Math.min(...nodes.map(n => n.pos[1] - 32));
+ const width = Math.max(...nodes.map(n => n.pos[0] + n.size[0])) - left;
+ const height = Math.max(...nodes.map(n => n.pos[1] + n.size[1])) - top;
+ const scale = Math.min(1, (canvas.clientWidth - 96) / width, (canvas.clientHeight - 96) / height);
+ if (scale > 0) {
+ app.canvas.ds.scale = scale;
+ app.canvas.ds.offset = [-left + (canvas.clientWidth / scale - width) / 2, -top + (canvas.clientHeight / scale - height) / 2];
+ app.canvas.setDirty(true, true);
+ }
+}
+
const studioQueues = new WeakMap();
export function openStudio(node) {
- if (current?.node === node && current.dialog.open) { current.dialog.focus(); return; }
+ if (current?.node === node && current.dialog.open) { current.dialog.focus(); viewChanged('studio', node); return current.dialog; }
current?.dialog.close();
const dialog = el('dialog', null, 'fv-studio'); dialog.setAttribute('aria-label', t('FreeVideo creative workspace', 'FreeVideo 创作面板'));
current = {node, dialog}; const cleanup = [];
const header = el('header', null, 'fv-header'), brand = el('div', null, 'fv-brand');
brand.append(wordmark());
const tools = el('div', null, 'fv-header-actions');
+ const agents = createAgentActivity(t, api, dialog); tools.append(agents.element); cleanup.push(agents.dispose);
const versionInfo = createVersionInfo(cn); tools.append(versionInfo.element); cleanup.push(versionInfo.dispose);
tools.append(button(t('Settings', '设置'), openSetup, 'fv-quiet'));
- const navigation = viewSwitch('studio', () => {}, () => {
- closeDialog(dialog);
- // Fit the graph in the visible canvas; never rewrite users' node positions.
- const nodes = node.graph?._nodes || [], canvas = app.canvas?.canvas;
- if (!nodes.length || !canvas) return;
- const left = Math.min(...nodes.map(n => n.pos[0])), top = Math.min(...nodes.map(n => n.pos[1] - 32));
- const width = Math.max(...nodes.map(n => n.pos[0] + n.size[0])) - left;
- const height = Math.max(...nodes.map(n => n.pos[1] + n.size[1])) - top;
- const scale = Math.min(1, (canvas.clientWidth - 96) / width, (canvas.clientHeight - 96) / height);
- if (scale > 0) {
- app.canvas.ds.scale = scale;
- app.canvas.ds.offset = [-left + (canvas.clientWidth / scale - width) / 2, -top + (canvas.clientHeight / scale - height) / 2];
- app.canvas.setDirty(true, true);
- }
- });
+ const navigation = viewSwitch('studio', () => {}, () => showNodes(node, dialog),
+ () => openEditorView(node, {studio: dialog}));
header.append(brand, navigation, tools);
const body = el('div', null, 'fv-body'), controls = el('div', null, 'fv-controls'), output = el('div', null, 'fv-preview-column');
dialog.append(header, body); body.append(controls, output);
@@ -283,7 +292,7 @@ export function openStudio(node) {
cleanup.push(() => { clearTimeout(effortEstimateTimer); effortEstimateRequest?.abort(); });
const mediaNode = upstream(node, 'media');
const [mediaDetails, mediaMount] = expand(t('Media', '素材'));
- if (mediaNode?.freevideoCreateMediaEditor) { cleanup.push(mediaNode.freevideoCreateMediaEditor(mediaMount)); mediaDetails.open = JSON.parse(value(mediaNode, 'assets') || '[]').some(r => r.enabled !== false) || mediaNode.inputs?.some(input => ['first', 'last', 'reference', 'reference_audio'].includes(input.name) && input.link != null); }
+ if (mediaNode?.freevideoCreateMediaEditor) { cleanup.push(mediaNode.freevideoCreateMediaEditor(mediaMount)); mediaDetails.open = JSON.parse(value(mediaNode, 'assets') || '[]').some(r => r.enabled !== false) || mediaNode.inputs?.some(input => ['first', 'last', ...referenceInputs, 'reference_audio'].includes(input.name) && input.link != null); }
else mediaMount.append(el('p', t('Connect a FreeVideo Media panel in node view to upload here.', '在节点视图连接 FreeVideo 素材面板,即可在这里上传。'), 'fv-legacy'));
const loraNode = upstream(node, 'loras');
if (loraNode) {
@@ -423,7 +432,8 @@ export function openStudio(node) {
seedFields.append(field(t('Seed', '种子'), seed), field(t('After generation', '生成后'), mode)); advanced.append(seedFields);
const previewHead = el('div', null, 'fv-preview-head'); previewHead.append(el('strong', t('Preview', '预览')));
const previewCaption = el('span'), previewTools = el('div', null, 'fv-preview-tools');
- previewTools.append(previewCaption, button(t('Creations', '作品'), () => {
+ previewTools.append(previewCaption);
+ previewTools.append(button(t('Creations', '作品'), () => {
stage.querySelector('video')?.pause(); openLibrary(t, {upscale: value => node.freevideoUpscaleResult(value)});
})); previewHead.append(previewTools); output.append(previewHead);
const previewSpace = el('div', null, 'fv-preview-space'); output.append(previewSpace);
@@ -603,6 +613,7 @@ export function openStudio(node) {
},
}));
const queueController = studioQueues.get(node);
+ node.freevideoEditorLooping = () => queueController.state().looping;
if (!node.freevideoQueueCleanup) {
node.freevideoQueueCleanup = true;
const removed = node.onRemoved;
@@ -795,7 +806,7 @@ export function openStudio(node) {
}
function applySize() {
if (dimensionsLinked) return;
- const [w, h] = canvasDimensions(pixels, ratio);
+ const {width: w, height: h} = frameSize(pixels, ratio);
if (w < 256 || h < 256 || w > 4096 || h > 4096) throw new Error(t('This aspect ratio and pixel count exceed the supported dimensions. Use custom dimensions.', '该比例与像素数超出尺寸范围,请使用自定义宽高。'));
set(node, 'width', w); set(node, 'height', h); node.properties.freevideo_aspect = selected; node.properties.freevideo_pixels = pixels; updateCanvas();
}
@@ -809,7 +820,7 @@ export function openStudio(node) {
if (disposed || !image.naturalWidth || !image.naturalHeight) return;
if (selected === 'input') { ratio = image.naturalWidth / image.naturalHeight; applySize(); }
}
- for (const [id, label, r] of [['16:9', t('Landscape', '横屏'), 16 / 9], ['9:16', t('Portrait', '竖屏'), 9 / 16], ['1:1', t('Square', '方形'), 1], ['input', t('Match image', '跟随图片'), null]]) {
+ for (const [id, label, r] of [...frameShapes(t), ['input', t('Match image', '跟随图片'), null]]) {
const b = button('', async () => { const previous = selected; try { selected = id; pixels = Number(mp.value); if (id === 'input') await inputRatio(true); else { ratio = r; applySize(); } status.textContent = ''; status.dataset.error = 'false'; } catch (error) { selected = previous; updateCanvas(); status.dataset.error = 'true'; status.textContent = error.message; } }, 'fv-shape');
b.dataset.ratio = id; b.setAttribute('aria-label', label); b.disabled = dimensionsLinked;
b.append(el('span', null, 'fv-shape-icon'), el('span', label)); shapes.append(b);
@@ -890,5 +901,6 @@ export function openStudio(node) {
if (!disposed && !busy && !result && saved) showResult(saved);
}
}).catch(() => {});
- requestAnimationFrame(() => generate.focus({preventScroll: true}));
+ requestAnimationFrame(() => { if (!document.querySelector('dialog.fv-editor[open]')) generate.focus({preventScroll: true}); });
+ return dialog;
}
diff --git a/web/view_navigation.css b/web/view_navigation.css
index 5fffdef..4317746 100644
--- a/web/view_navigation.css
+++ b/web/view_navigation.css
@@ -9,7 +9,7 @@
.fv-view-guide::before{content:'i';flex:none;display:grid;place-items:center;width:18px;height:18px;border-radius:50%;background:var(--fv-accent);color:var(--fv-bg);font:600 11px/1 Georgia,serif}
.fv-view-guide>span{flex:1}
.fv-view-guide button{flex:none;color:var(--fv-accent);padding:4px 8px;font-weight:var(--fv-semibold)}.fv-view-guide button:hover{background:#ffffff0f}.fv-view-navigation .fv-view-settings{font-size:12px;padding:6px}
-.fv-studio .fv-header:has(.fv-view-switch){grid-template-columns:1fr auto 1fr}.fv-studio .fv-header>.fv-header-actions{justify-self:end}.fv-studio .fv-view-switch button{padding:5px 14px;min-height:var(--fv-h-sm)}
+.fv-studio .fv-header:has(.fv-view-switch){grid-template-columns:1fr auto 1fr}.fv-studio .fv-header>.fv-header-actions{justify-self:end;min-width:0}.fv-studio .fv-view-switch button{padding:5px 14px;min-height:var(--fv-h-sm)}
@media(max-width:680px){.fv-view-navigation{top:68px;max-width:calc(100vw - 16px)}.fv-view-row{gap:6px}.fv-view-row>.fv-wordmark{width:90px}.fv-view-switch button{padding:7px 10px}.fv-studio .fv-header:has(.fv-view-switch){grid-template-columns:1fr auto 1fr;gap:8px}.fv-studio .fv-header:has(.fv-view-switch) .fv-wordmark{width:90px}.fv-studio .fv-view-switch{justify-self:center}.fv-studio .fv-view-switch button{padding:6px 9px}}
.fv-view-navigation{animation:fv-panel-enter .25s ease}
@@ -23,3 +23,11 @@ html.fv-toolbar-dragging,html.fv-toolbar-dragging *{cursor:grabbing!important;us
.fv-view-row{position:relative}.fv-view-grip{position:absolute;left:-14px;top:50%;translate:0 -50%;width:8px;height:12px;opacity:0;pointer-events:none;color:var(--fv-muted);transition:opacity .2s,color .2s;background:radial-gradient(circle,currentColor 1.1px,transparent 1.5px) 0 0/4px 4px}
.fv-view-navigation:hover .fv-view-grip{opacity:.75}.fv-view-navigation.fv-dragging .fv-view-grip{opacity:1;color:var(--fv-ink)}@media(hover:none){.fv-view-grip{opacity:.5}}
@media(max-width:480px){.fv-view-navigation .fv-version-info{display:none}}
+
+/* Reserve the selected label's width so bold English text cannot move the switch. */
+.fv-view-switch button,.fv-studio .fv-view-switch button{display:grid;gap:0}
+.fv-view-switch button>span,.fv-view-switch button::after{grid-area:1/1}
+.fv-view-switch button::after{content:attr(data-label);font-weight:var(--fv-semibold);visibility:hidden;pointer-events:none}
+
+/* A long export hint must not enlarge the shared header's internal grid row. */
+@media(min-width:681px){.fv-studio .fv-header:has(.fv-view-switch){grid-template-rows:minmax(0,1fr)}}
diff --git a/web/view_navigation.js b/web/view_navigation.js
index d6c7534..bda0cb3 100644
--- a/web/view_navigation.js
+++ b/web/view_navigation.js
@@ -26,12 +26,17 @@ export function viewChanged(view, node) {
refreshNavigation();
}
-export function viewSwitch(view, onStudio, onNodes) {
+export function viewSwitch(view, onStudio, onNodes, onEditor) {
const group = document.createElement('div'); group.className = 'fv-view-switch';
group.setAttribute('role', 'group'); group.setAttribute('aria-label', t('FreeVideo view', 'FreeVideo 视图'));
- for (const [id, label, action] of [['studio', t('Create', '创作面板'), onStudio], ['nodes', t('Nodes', '节点视图'), onNodes]]) {
+ for (const [id, label, action] of [['studio', t('Create', '创作面板'), onStudio], ['nodes', t('Nodes', '节点视图'), onNodes], ['editor', t('Edit', '剪辑视图'), onEditor]]) {
const button = document.createElement('button'); button.type = 'button';
- button.textContent = label; button.dataset.view = id;
+ const text = document.createElement('span'); text.textContent = label; button.append(text);
+ button.dataset.label = label; button.dataset.view = id;
+ button.title = {studio: t('Describe a video and generate it', '写一句描述,生成一段视频'),
+ nodes: t('Build and adjust the workflow as a node graph', '用节点图搭建和调整工作流'),
+ editor: t('Join several video and audio parts into one video', '把多段画面和声音接成一条视频')}[id];
+ if (id === 'editor') button.dataset.fvGuide = 'longer';
button.setAttribute('aria-pressed', String(view === id)); button.onclick = action;
group.append(button);
}
@@ -42,7 +47,7 @@ export function refreshNavigation() {
if (!toolbar) return;
const nodes = (app.graph?._nodes || []).filter(n => n.comfyClass === 'FreeVideoGenerate' || n.type === 'FreeVideoGenerate');
if (!nodes.includes(selected)) selected = nodes[0];
- toolbar.hidden = !selected || currentView === 'studio';
+ toolbar.hidden = !selected || currentView !== 'nodes';
for (const button of toolbar.querySelectorAll('[data-view]')) {
button.setAttribute('aria-pressed', String(button.dataset.view === currentView));
}
@@ -57,19 +62,20 @@ export function installNavigation(openStudio) {
// The whole bar drags like a window; these dots say so on hover.
const grip = document.createElement('span'); grip.className = 'fv-view-grip'; grip.setAttribute('aria-hidden', 'true');
const brand = wordmark();
- const choose = () => {
+ const choose = action => {
const focused = Object.values(app.canvas?.selected_nodes || {}).find(n => n.comfyClass === 'FreeVideoGenerate' || n.type === 'FreeVideoGenerate');
- refreshNavigation(); if (focused || selected) open(focused || selected);
+ refreshNavigation(); if (focused || selected) return action(focused || selected);
};
const settings = document.createElement('button'); settings.type = 'button';
settings.textContent = t('Settings', '设置'); settings.className = 'fv-view-settings'; settings.onclick = openSetup;
- row.append(grip, brand, viewSwitch('nodes', choose, () => {}), createVersionInfo(cn).element, settings); toolbar.append(row);
+ row.append(grip, brand, viewSwitch('nodes', () => choose(open), () => {}, () => choose(node =>
+ import('./editor_entry.js').then(({openEditorView}) => openEditorView(node)))), createVersionInfo(cn).element, settings); toolbar.append(row);
let shown = false;
try { shown = localStorage.getItem('freevideo.view-guide') === '1'; } catch { /* Show once this session. */ }
if (!shown) {
const guide = document.createElement('div'); guide.className = 'fv-view-guide';
const text = document.createElement('span');
- text.textContent = t('Create here, connect tools in Nodes. Switching keeps your inputs and results.', '在创作面板生成,在节点视图连接工具。切换会保留输入和结果。');
+ text.textContent = t('Switching views keeps the content of each view.', '切换视图时,各视图的内容都会保留。');
const dismiss = document.createElement('button'); dismiss.type = 'button'; dismiss.textContent = t('Got it', '知道了');
dismiss.onclick = () => {
try { localStorage.setItem('freevideo.view-guide', '1'); } catch {}
@@ -98,7 +104,7 @@ export function installNavigation(openStudio) {
// health.js asks for this before it reports the toolbar missing. A
// workspace removed without closing must not keep the toolbar hidden.
globalThis.window?.addEventListener('freevideo-navigation-refresh', () => {
- if (currentView === 'studio' && !document.querySelector('dialog.fv-studio[open]')) currentView = 'nodes';
+ if (currentView !== 'nodes' && !document.querySelector('dialog.fv-studio[open]')) currentView = 'nodes';
refreshNavigation();
});
}