diff --git a/.claude/skills/formcut-skillset/sub-skills/engine-architect/references/engine-map.md b/.claude/skills/formcut-skillset/sub-skills/engine-architect/references/engine-map.md index 63d3bfa5..e4f21a09 100644 --- a/.claude/skills/formcut-skillset/sub-skills/engine-architect/references/engine-map.md +++ b/.claude/skills/formcut-skillset/sub-skills/engine-architect/references/engine-map.md @@ -80,6 +80,7 @@ The rest is written by hand. | transcribe.py | /api/transcribe | 2 | | tts.py | /api/tts | 3 | | upscale.py | /api/media | 2 | +| vfx_link.py | /api/vfx-link | 3 | | voice_app.py | /api/speech/app | 4 | | webhooks.py | /api/webhooks | 5 | | window_key.py | /api/window | 3 | @@ -134,6 +135,7 @@ the automation transports. - `package_registry.py` - `paths.py` - `peer_process.py` +- `pin_edit.py` - `pixel_effects.py` - `planar.py` - `planar_bench.py` diff --git a/.claude/skills/formcut-skillset/sub-skills/interface-architect/references/interface-map.md b/.claude/skills/formcut-skillset/sub-skills/interface-architect/references/interface-map.md index 505d128d..75b6ee4c 100644 --- a/.claude/skills/formcut-skillset/sub-skills/interface-architect/references/interface-map.md +++ b/.claude/skills/formcut-skillset/sub-skills/interface-architect/references/interface-map.md @@ -49,6 +49,7 @@ The module list and the engine commands are generated from `frontend/src` by - `engine/media.ts` - `engine/motion.ts` - `engine/persistence.ts` +- `engine/pin-edit.ts` - `engine/project.ts` - `engine/rates.ts` - `engine/seed.ts` @@ -95,6 +96,7 @@ The module list and the engine commands are generated from `frontend/src` by - `ui/menu-fit.ts` - `ui/missing-media.ts` - `ui/mode-popout.ts` +- `ui/pin-corners.ts` - `ui/planar-workspace.ts` - `ui/preset-grid.ts` - `ui/preview-manipulation.ts` @@ -120,6 +122,7 @@ The module list and the engine commands are generated from `frontend/src` by - `ui/track-keyframes.ts` - `ui/tracking.ts` - `ui/upscale-dialog.ts` +- `ui/vfx-link.ts` - `ui/viewer.ts` - `ui/webhooks-settings.ts` - `ui/work-area.ts` @@ -151,6 +154,7 @@ and a UI module that mutates state directly is a defect. - `clip.mask-track` - `clip.move` - `clip.mute` +- `clip.pinCorner` - `clip.planar` - `clip.planarMatte` - `clip.planarModule` @@ -184,6 +188,7 @@ and a UI module that mutates state directly is a defect. - `history.redo` - `history.undo` - `media.relink` +- `media.replace` - `project.background` - `project.load` - `project.rename` diff --git a/.docs/wiki/Architecture.md b/.docs/wiki/Architecture.md index 3de07c67..ea3ac089 100644 --- a/.docs/wiki/Architecture.md +++ b/.docs/wiki/Architecture.md @@ -191,7 +191,15 @@ reference or settings change starts a fresh track. Frames are read at full size forwards). Every estimate is checked as sound before use (finite, the plane's box still convex and the same way round, a twentieth to twenty times its area); a step that fails anywhere gives the prediction with no confidence, and twelve frames running near zero end the job there with -`lost` in its result, the frames before kept. The job reports `frame` and `confidence` as it goes. GET +`lost` in its result, the frames before kept. That is the default, When the track is lost: Stop; a layer's setting +`lost: "hold"` (Hold last position, 2.24.0) instead keeps the last confident position for those twelve frames and every +faint one after them until the plane is found again, marks them in the store's `held` (read back as `held`, the +frame numbers) and reports `held` in the result; the tracker's prediction is held there too, so the plane can be +found where it went out of sight. The choice is not part of what a track depends on, so changing it keeps the frames +tracked. Perspective, left unset, is on for a layer drawn as one four-cornered polygon (a screen, a sign, a pin +target) and off otherwise, so an API or MCP caller gets the same default as the workspace; a frame where a lower model +holds under 0.6 of its points is refitted in perspective from the same point pairs and kept when that holds at least +0.2 more of them (`planar.promote`), marked in `promoted`. The job reports `frame` and `confidence` as it goes. GET /api/planar/media/ gives a media file's frame rate, size and count; GET /api/planar/frame/?index=&width= one frame as a JPEG. @@ -207,6 +215,29 @@ a confidence strip under the scrubber. Shapes and the surface are kept in the re a tracked layer's shapes or settings starts its track afresh, asked first. Done keeps the layers on the clip (`clip.planar`, a project command with undo); the per-frame tracks stay the engine's. +Hand edits of an applied corner pin (2.24.0, `backend/app/pin_edit.py` and its twin `frontend/src/engine/pin-edit.ts`): +with Edit corners on in the inspector's Track section, the selected clip's pin shows its four corners on the preview +(`ui/pin-corners.ts`); one dragged is written into the pin's sample on that frame, or a new sample there when none is +within half a frame, so the frames either side keep their tracked corners. The pin keeps the value each moved corner +replaced (`cornerPin.edits`: t, corner, was); a double-click on a moved corner puts it back. A move that would fold +or cross the four corners is refused, since a pin draws only a convex quadrilateral. In the window it is the +`clip.pinCorner` command (one undo step); through `project.edit`, and so the MCP server's `formcut_edit`, it is +`clip.pin-corner` {clipId, t, corner, x, y} or {clipId, t, corner, reset: true}. A mesh pin is shaped in the Track +workspace instead. + +A FormVFX live comp as a clip (2.24.0, `backend/app/vfx_link.py`, `ui/vfx-link.ts`): a `.fvxlink` (FormVFX's +`formvfx.link/1` descriptor) imported into the media bin is a video item whose file is the descriptor and whose record +carries `link`. The renderer asks FormVFX for each frame (GET /api/link/frame.png with `x-formvfx-local: 1`, on the +comp's own frame grid), so preview and export stay one renderer, and both export graphs leave such a clip to the +frame path. FormVFX is found on loopback only (FORMVFX_URL, else FormVFX's own engine.json, else 127.0.0.1:8250), with +no proxy from the environment and no redirect followed; the URL templates in a descriptor are never used. A link's +project must be an absolute path on this computer to a FormVFX project file that is there at import (no share, URL +scheme or `..`, its links followed and checked); later it is sent only as it then resolves, else FormVFX is given the +project id alone. With FormVFX +closed the clip is unreadable and says so, as a missing file does. Render and replace (POST /api/vfx-link//render, +a job) reads every frame and the sound and writes ProRes 4444 with PCM sound through formcut's own ffmpeg, a separate +program, ingests it, and the window points the project's clips at it (`media.replace`, one undo step). + AdjustTrack (P4): a layer's reference points remove its track's drift, as Mocha's do. Each point has a master frame and its place there; the raw track carries it to every other frame. Where the person puts it back on its feature on a frame, that frame keys its correction (the place less where the track carried it); the master frame's correction is diff --git a/.docs/wiki/Automation.md b/.docs/wiki/Automation.md index 4b682707..affc42f4 100644 --- a/.docs/wiki/Automation.md +++ b/.docs/wiki/Automation.md @@ -56,6 +56,9 @@ WebSocket `/api/rpc/ws` sends the same JSON objects over a loopback connection. ### v0.56.0 `project.edit` adds `clips.split`, `clip.rejoin`, `clip.freeze-insert`, `clip.reattach`; magnetic tracks settle after each batch; `clip_properties` includes `reversed` and `audioStream` (which of the media's audio streams a clip plays); per-timeline formats apply to `project.export`. +### v2.24.0 +`project.edit` adds `clip.pin-corner`: one corner of a clip's applied corner pin moved on one frame, `{"op": "clip.pin-corner", "clipId": "...", "t": 1.2, "corner": 2, "x": 0.71, "y": 0.83}` (t in the clip's own seconds, corner 0 to 3 from the top left clockwise, x and y as fractions of the canvas), or put back with `"reset": true` in place of x and y. It is one undo step like any edit, refuses a clip with no pin, a mesh pin, and a move that would fold or cross the four corners, and reaches agents through the MCP server's `formcut_edit`. + ### v0.57.0 Title styles ride `clip.text` patches like any other style field, so the full property set is scriptable; `/api/presets/titles` lists the built-ins. diff --git a/README.md b/README.md index 338cb2fe..15d8dc70 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@

- version v2.23.0 + version v2.24.0 TypeScript and Vite Python FastAPI macOS, Windows, Linux diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index aef827e1..9046d9d3 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -2,6 +2,38 @@ Reasoning behind engine changes, newest first. +## 2.24.0 · perspective by default for four-cornered layers, a perspective refit when a lower model fails (`app/planar.py` `promote`, `PlanarTracker.hold`, `promoted`; `app/planar_api.py` `four_cornered`, `_settings`, `_tidy`) + +- **Why.** A synthetic screen benchmark with exact corners (six clips, 1280 by 720, 120 frames) found the tracker's default, Perspective off, fits a similarity, which cannot follow a screen as it tilts: 10 to 60 px of mean corner error, and on the clip whose corners leave the frame the twelve-faint-frames rule ended the track at frame 43. With Perspective on, every clip tracked under 0.3 px mean. +- **Default.** `_settings(raw, layer)`: Perspective left unset (absent or null) is on for a layer drawn as one four-cornered polygon in add mode (`four_cornered`: no curve kind, no Bezier handles), off otherwise; what the person chose is kept. The route passes the layer, so an RPC or MCP caller gets the workspace's default. The track's signature is unchanged (the layer's own settings, as before), so an existing track is not started afresh by the new default; it carries on in perspective from where it stopped. +- **Refit.** In `_refine`, each pass's fit in the layer's model is checked: below perspective and holding under 0.6 of the points, the same LK pairs are fitted in perspective (`promote`), and that fit is used when it holds at least 0.2 more of them. The step marks the frame (`tracker.promoted`, either pass), the job keeps it in the store's `promoted` and the read returns it. +- **Seen.** The benchmark against this tree (FormCut's own runner from the bench, pointed at it), mean and max corner error in px, old default then the new default: pan, turn and tilt 27.46 / 109.2 to 0.031 / 0.27; 3.5x zoom 10.38 / 72.9 to 0.19 / 1.16; hand over the screen 26.95 / 103.9 to 0.039 / 0.41; glossy screen under changing light 26.17 / 120.4 to 0.30 / 2.27; corners leaving the frame 60.27 (lost at frame 43) to 0.084 / 0.84 with nothing lost; blur and noise 34.16 / 124.8 to 0.11 / 0.51. A similarity kept on purpose, with the refit, came to 0.50 to 1.81 px mean on five clips and 16.6 px on the glossy one. `tests/test_planar_perspective_default.py`: a 30-frame tilting plane tracks at 21.5 px mean on the old code and under 1 px now; a similarity run gives 0.34 px with the refit (23 frames promoted) and 22.3 px without. + +## 2.24.0 · When the track is lost: Hold last position (`app/planar_api.py` the track job; `app/planar.py` `PlanarTracker.hold`) + +- **Why.** A plane that leaves the shot for a moment (a hand across a screen, a turn away) ended the track: twelve frames under 0.05 confidence stop the job there. That stays the default, Stop. The layer's setting `lost: "hold"` keeps the track going. +- **Hold.** When the twelfth faint frame arrives, it and the eleven before it are rewritten with the last confident frame's homography and marked held; every faint frame after that is held too, until a step is confident again. The tracker's prediction is set to the held place (`hold`), so it looks for the plane where it went out of sight rather than carrying its last motion on. Held frames are kept in the store's `held`, cleared when a frame is tracked afresh, filled from either side (green screens), or cleared by DELETE; the read returns them and the job's result says how many. +- **Signature.** `lost` is left out of what a track depends on, so switching between Stop and Hold keeps the frames already tracked. A layer with no `lost` has exactly the signature it had before. `_tidy` writes `held` and `promoted` only when they hold something, so a Stop track's file has the same keys as before. +- **Seen.** `tests/test_planar_hold.py` on 12 frames of a plane then 24 of noise: Stop still ends with `lost` between frames 11 and 14 and no held frames; Hold runs to frame 35 with a single held run to the end at the last good matrix, at least 22 frames held. + +## 2.24.0 · hand edits of an applied corner pin (`app/pin_edit.py` new; `app/automation.py` `clip.pin-corner`) + +- **Why.** An applied pin is a track of timed samples; a corner the track put a few pixels off could only be fixed by AdjustTrack and applying again. Now one corner can be moved on one frame and kept in the pin. +- **The edit.** `edit_corner(pin, t, corner, x, y, fps)` writes the corner into the sample within half a frame of t, or a new sample at t (the others interpolated as `renderer.pin_at` draws them), so the frames either side keep their tracked corners. A fixed pin moves its point. `edits` keeps, per frame and corner, the value it replaced, once; `reset_corner` puts that back and drops the record. A move that would fold or cross the quadrilateral is refused (a pin draws only a convex one: a folded quad sent the warp through infinity and flooded the canvas when tried), so is a mesh pin, a corner outside 0 to 3 and a point more than four canvas widths off. Pure functions; `frontend/src/engine/pin-edit.ts` is the window's twin and the test runs both. +- **Surface.** `project.edit` op `clip.pin-corner` {clipId, t, corner, x, y} or {..., reset: true}, listed in `capabilities`, so agents reach it through `formcut_edit`; one undo step. +- **Seen.** `tests/test_pin_edit.py`: 14 tests, among them the edit through `project.edit`, reset and undo, the renderer drawing the moved corner on its frame and the tracked one on the next, and the engine and the window giving the same pin for five edits in Node 25.8. + +## 2.24.0 · a FormVFX live comp as a clip (`app/vfx_link.py` new; `features.py`; `renderer.py` `_linked_frame`; `audio_render.py` `_live_sound`; `fast_export.py`, `fast_layers.py`; `media.py` `refuse_live`; `clip_visuals.py`) + +- **Why.** FormVFX serves a composition as a live clip (Export Live Link Clip writes a `.fvxlink`; GET /api/link/info, /frame.png and /audio answer it) and FormCut had no consumer. Read from nodemode-dev/formVFX `backend/app/engine/link.py` and `routers/link.py`: format `formvfx.link/1`; the link routes need only `x-formvfx-local: 1` on loopback (their POST render needs FormVFX's own window key, so Render and replace is done here). +- **Import.** POST /api/vfx-link/import {link} or {path}: the descriptor is parsed keeping only the project, its id, the comp's id and name, size, rate and length (each bounded: sides 16 to 8192, 1 to 240 fps, up to 24 hours, so a downloaded file cannot size a render that fills the disk); its URL templates are dropped. The item is kind video, its file `.fvxlink` holding the parsed descriptor, its record `link`, `source: "formvfx-link"`, and the comp's facts from FormVFX when it answers (else the descriptor's), with a thumbnail from FormVFX. A path must be a regular `.fvxlink` file, read to 64 KB at most. +- **What a link may name.** A descriptor is often a downloaded file, and FormVFX opens the project a link names. Its `project` must be an absolute path on this computer to a FormVFX project file (`.fvxproj`, `.ecproj`, `.ecprojx`): a UNC or `//` share, any URL scheme (`smb:`, `file:`), a relative path, a `..` segment, control characters or another kind of file is refused at import with a sentence saying which. At import the file must be there, its links followed and the target checked the same way. On every request the project is sent only as it resolves then; when it has gone (moved or renamed) only the project id is sent, and FormVFX matches that against its open and recent projects, as its own relinking does. The project id and a comp id are FormVFX's tokens (letters, digits, `_ . : -`, up to 128), a comp name has no control characters. +- **Where FormVFX is.** FORMVFX_URL, else FormVFX's engine.json (FORMVFX_DATA_DIR or ~/Formvfx), else 127.0.0.1:8250; anything but plain http on 127.0.0.1, localhost or ::1 with a port is passed over. httpx with `trust_env=False`, no redirects followed (a 3xx is refused), replies read to a cap (a frame to its raw RGBA size, sound to 64 MB), a frame larger than the size asked for refused, PIL's decompression-bomb error caught. +- **Frames and sound.** The renderer asks for the frame on the comp's own grid at the exact rate, held at the last frame past the comp's end, the last four kept per renderer; FormVFX closed makes the clip unreadable with what to do, as a missing file does. The mix takes the clip's sound from FormVFX from its source in (silence while FormVFX is closed). Both export graphs, the filmstrip, peaks, the source monitor frame, scenes, stabilising, proxies, reversing, freeze and detach refuse a live comp by name (409) rather than hand its JSON to ffmpeg. +- **Render and replace.** POST /api/vfx-link//render, a job: every frame and the sound (asked in 30 s chunks, padded with silence to the exact length) written by formcut's own ffmpeg, a separate program, as ProRes 4444 with its alpha and PCM sound; the job's `media` is the ingested movie, `renderedFrom` naming the live item. A failure removes the partial file and adds nothing. +- **Seen.** `tests/test_vfx_link.py`, 36 tests against a stand-in answering FormVFX's routes: the descriptor kept and refused; eight project paths refused (two shares, smb and file URLs, relative, `..`, not a project file, a newline) and three comps; a missing project file and one that is a link to a text file refused, and a project moved after import asked for by its id alone; six refused addresses and engine.json; import with FormVFX's facts and a thumbnail, the header on every request; frames 0, 3 and 7 read back by their colour; FormVFX closed; a redirect and an HTML reply refused; both export graphs refusing; Render and replace giving a 64 by 36 ProRes of 12 frames with stereo sound, each frame's colour exact, and with FormVFX closed failing with nothing added. Not run: a real FormVFX. +- **Not done.** No MCP tool for the import (an agent can call the routes); the filmstrip and waveform of a live clip are not drawn until it is rendered; a retimed or reversed live clip plays its picture through the renderer but its sound at speed 1. + ## 2.23.0 · ComfyUI through the FormBridge pack (`app/formbridge.py` new; `main.py` import and include) - **Why.** The Comfy-FormBridge-Suite README named formcut as one of its apps, and formcut had no client. The pack runs in the person's own ComfyUI and answers contract 1 under `/formbridge/v1`; this module is written from that contract. diff --git a/backend/app/audio_render.py b/backend/app/audio_render.py index 0ba6c8f2..387591c4 100644 --- a/backend/app/audio_render.py +++ b/backend/app/audio_render.py @@ -100,6 +100,27 @@ def filter_audio(samples: np.ndarray, chain: str, cancelled=lambda: False) -> np return np.frombuffer(output, " np.ndarray | None: + """A FormVFX live comp's sound for a clip, from its source in for the clip's length (at its own speed: a retimed + live clip is rendered and replaced first); silence while FormVFX is closed, as its picture then says. None for + any other media.""" + from fastapi import HTTPException + + from .media import _find + from .vfx_link import LinkUnavailable, audio_span, link_of + + try: + link = link_of(_find(str(clip["mediaId"]))) + except HTTPException: + return None + if link is None: + return None + try: + return audio_span(link, float(clip.get("sourceIn") or 0), duration, cancelled) + except LinkUnavailable: + return np.zeros((max(0, round(duration * RATE)), 2), np.float32) + + def mix_audio(project: dict, cancelled=lambda: False) -> np.ndarray: """The project's stereo mix at RATE; a timeline clip contributes its own timeline's mix.""" total = math.ceil(project["duration"] * RATE) @@ -122,18 +143,20 @@ def mix_audio(project: dict, cancelled=lambda: False) -> np.ndarray: else: if clip["kind"] not in ("video", "audio") or not clip.get("mediaId"): continue - if clip.get("reversed"): - candidate = reversed_path(clip["mediaId"]) - if not candidate.is_file(): - raise ValueError("Reversed copy is not prepared yet") - paths = [candidate] - else: - paths = list(MEDIA_DIR.glob(f"{clip['mediaId']}.*")) - if not paths: - raise ValueError("Audio media is missing") - if not any(s.get("codec_type") == "audio" for s in _ffprobe(paths[0]).get("streams", [])): - continue - samples = processed_clip_audio(clip, paths[0], cancelled) + samples = _live_sound(clip, duration, cancelled) # a FormVFX live comp's sound, from FormVFX + if samples is None: + if clip.get("reversed"): + candidate = reversed_path(clip["mediaId"]) + if not candidate.is_file(): + raise ValueError("Reversed copy is not prepared yet") + paths = [candidate] + else: + paths = list(MEDIA_DIR.glob(f"{clip['mediaId']}.*")) + if not paths: + raise ValueError("Audio media is missing") + if not any(s.get("codec_type") == "audio" for s in _ffprobe(paths[0]).get("streams", [])): + continue + samples = processed_clip_audio(clip, paths[0], cancelled) count = min(len(samples), int(duration * RATE)) samples = samples[:count] * clip_envelope(clip, count)[:, None] pan = max(-1, min(1, float(clip.get("pan", 0)))) diff --git a/backend/app/automation.py b/backend/app/automation.py index cdcb6ec2..980bd9e5 100644 --- a/backend/app/automation.py +++ b/backend/app/automation.py @@ -410,6 +410,17 @@ def apply_edit(project: dict, command: dict): if not isinstance(points, list) or not points: raise ValueError("A speed curve needs points") clip["speedCurve"] = [{"t": float(p["t"]), "speed": float(p["speed"])} for p in points] + elif operation == "clip.pin-corner": + # a hand edit of an applied corner pin: one corner on the frame at t (the clip's own seconds), or reset + from .pin_edit import edit_corner, reset_corner + + pin = located[1].get("cornerPin") if located else None + fps = float(timeline.get("fps") or project.get("fps") or 30) + corner, t = command.get("corner"), float(command.get("t") or 0) + if command.get("reset"): + located[1]["cornerPin"] = reset_corner(pin, t, corner, fps) + else: + located[1]["cornerPin"] = edit_corner(pin, t, corner, command.get("x"), command.get("y"), fps) elif operation == "clip.animations": if not located: raise ValueError("Clip not found") @@ -928,6 +939,7 @@ def measure(job_id, report, cancelled): "timeline.sync-angles", "clip.speed-curve", "clip.animations", + "clip.pin-corner", "clip.scenes", "track.add", "track.remove", diff --git a/backend/app/clip_visuals.py b/backend/app/clip_visuals.py index 4f672621..ed1209ad 100644 --- a/backend/app/clip_visuals.py +++ b/backend/app/clip_visuals.py @@ -15,7 +15,7 @@ from fastapi import APIRouter, HTTPException, Query from fastapi.responses import FileResponse -from .media import MEDIA_DIR, _find +from .media import MEDIA_DIR, _find, refuse_live from .paths import DATA_DIR router = APIRouter(prefix="/api/media", tags=["clip visuals"]) @@ -44,7 +44,7 @@ def _source(media_id: str) -> Path: @router.get("/{media_id}/peaks") def get_peaks(media_id: str) -> FileResponse: - item = _find(media_id) + item = refuse_live(_find(media_id)) if item["kind"] not in ("audio", "video"): raise HTTPException(status_code=422, detail="this media has no audio to measure") cache = PEAK_DIR / f"{media_id}-{BUCKETS}.json" @@ -59,7 +59,7 @@ def get_peaks(media_id: str) -> FileResponse: @router.get("/{media_id}/filmstrip") def get_filmstrip(media_id: str, frames: int = Query(STRIP_FRAMES, ge=4, le=120)) -> FileResponse: - item = _find(media_id) + item = refuse_live(_find(media_id)) if item["kind"] not in ("video", "image"): raise HTTPException(status_code=422, detail="this media has no frames to strip") cache = STRIP_DIR / f"{media_id}-{frames}.jpg" diff --git a/backend/app/fast_export.py b/backend/app/fast_export.py index 0af0b5ff..0c10952c 100644 --- a/backend/app/fast_export.py +++ b/backend/app/fast_export.py @@ -30,6 +30,7 @@ from .render_document import flatten from .renderer import DEFAULTS from .timing import source_time +from .vfx_link import is_live from .video_source import VideoSource MOTION = ("scale", "posX", "posY", "rotation", "opacity") @@ -107,6 +108,8 @@ def _plain(clip: dict) -> str | None: return f"a {clip.get('kind')} clip" if not clip.get("mediaId"): return "a clip without media" + if is_live(str(clip["mediaId"])): + return "a FormVFX live comp" # its frames come from FormVFX, not a file ffmpeg can open # X7: the graph feeds the file to ffmpeg untouched, which would skip the # tone map; PQ and HLG go to the frame path, whose decode pipe maps them, # and so does a wide-gamut or SD-tagged source the pipe converts. diff --git a/backend/app/fast_layers.py b/backend/app/fast_layers.py index e68d21e8..ddeadce6 100644 --- a/backend/app/fast_layers.py +++ b/backend/app/fast_layers.py @@ -103,6 +103,8 @@ def _refuse(clip: dict) -> str | None: return f"a {clip.get('kind')} clip" if not clip.get("mediaId"): return "a clip without media" + if fast_export.is_live(str(clip["mediaId"])): + return "a FormVFX live comp" # its frames come from FormVFX, not a file ffmpeg can open for key in fast_export.ABSENT: if key not in ALLOWED and clip.get(key): return key diff --git a/backend/app/features.py b/backend/app/features.py index c4af7744..4929f60f 100644 --- a/backend/app/features.py +++ b/backend/app/features.py @@ -20,6 +20,7 @@ from .render_stream import router as playback from .storage import router as storage from .templates import router as templates +from .vfx_link import router as vfx_link router = APIRouter() for module in ( @@ -43,5 +44,6 @@ recovery, extensions, notices, + vfx_link, ): router.include_router(module) diff --git a/backend/app/main.py b/backend/app/main.py index 6144a21c..c6f24f90 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -39,7 +39,7 @@ prefer_bundled() -APP_VERSION = "2.23.0" +APP_VERSION = "2.24.0" app = FastAPI(title="formcut engine", version=APP_VERSION) diff --git a/backend/app/media.py b/backend/app/media.py index 7b6faded..7c12d384 100644 --- a/backend/app/media.py +++ b/backend/app/media.py @@ -427,6 +427,13 @@ def _find(media_id: str) -> dict: return found +def refuse_live(record: dict) -> dict: + """A FormVFX live comp (vfx_link.py) has no file of its own to decode: what reads the file refuses it by name.""" + if isinstance(record.get("link"), dict): + raise HTTPException(status_code=409, detail="this is a FormVFX live comp: Render and replace it first to use it here") + return record + + @router.get("/{media_id}/thumb") def get_thumb(media_id: str) -> FileResponse: _find(media_id) @@ -453,7 +460,7 @@ def get_frame(media_id: str, t: float = 0.0, width: int = 640): import cv2 from fastapi.responses import Response - item = _find(media_id) + item = refuse_live(_find(media_id)) matches = list(MEDIA_DIR.glob(f"{media_id}.*")) if not matches: raise HTTPException(status_code=404, detail="file missing") @@ -833,7 +840,7 @@ def cutout_preview(media_id: str, body: dict) -> dict: @router.get("/{media_id}/scenes") def media_scenes(media_id: str, sensitivity: float = 0.5, minimum: float = 1.0) -> dict: """B5: where the shots change, so a long clip can become short ones.""" - record = _find(media_id) + record = refuse_live(_find(media_id)) if record["kind"] != "video": raise HTTPException(status_code=400, detail="only video media has scenes") matches = list(MEDIA_DIR.glob(f"{media_id}.*")) @@ -852,7 +859,7 @@ def motion_status(media_id: str) -> dict: @router.post("/{media_id}/motion", status_code=202) def analyse_motion(media_id: str) -> dict: - record = _find(media_id) + record = refuse_live(_find(media_id)) if record["kind"] != "video": raise HTTPException(status_code=400, detail="only video media can be stabilised") matches = list(MEDIA_DIR.glob(f"{media_id}.*")) @@ -874,7 +881,7 @@ def proxy_status(media_id: str) -> dict: @router.post("/{media_id}/proxy", status_code=202) def build_media_proxy(media_id: str, size: int | None = None) -> dict: - record = _find(media_id) + record = refuse_live(_find(media_id)) if record["kind"] != "video": raise HTTPException(status_code=400, detail="only video media can have a proxy") size = proxies.chosen_size() if size is None else size @@ -894,7 +901,7 @@ def delete_media_proxy(media_id: str) -> None: @router.post("/{media_id}/reverse", status_code=202) def reverse_media(media_id: str) -> dict: - record = _find(media_id) + record = refuse_live(_find(media_id)) if record["kind"] != "video": raise HTTPException(status_code=400, detail="only video media can be reversed") matches = list(MEDIA_DIR.glob(f"{media_id}.*")) @@ -916,7 +923,7 @@ def operation(job_id, report, cancelled): @router.post("/{media_id}/freeze", status_code=201) def freeze_frame(media_id: str, body: FreezeBody) -> dict: - record = _find(media_id) + record = refuse_live(_find(media_id)) if record["kind"] != "video": raise HTTPException(status_code=400, detail="only video media has frames to freeze") matches = list(MEDIA_DIR.glob(f"{media_id}.*")) @@ -945,7 +952,7 @@ def freeze_frame(media_id: str, body: FreezeBody) -> dict: @router.post("/{media_id}/detach", status_code=201) def detach_audio(media_id: str) -> dict: - record = _find(media_id) + record = refuse_live(_find(media_id)) if record["kind"] != "video": raise HTTPException(status_code=400, detail="only video media has audio to detach") matches = list(MEDIA_DIR.glob(f"{media_id}.*")) diff --git a/backend/app/pin_edit.py b/backend/app/pin_edit.py new file mode 100644 index 00000000..59827ced --- /dev/null +++ b/backend/app/pin_edit.py @@ -0,0 +1,127 @@ +"""Hand edits of an applied corner pin: one corner moved on one frame. + +A pin is four fixed corners or a track of samples (renderer.pin_at reads both). Moving a corner on a frame writes it +into the pin itself: into the sample on that frame, or a new sample there when the track has none within half a +frame, so the frames either side keep their tracked corners. The pin keeps, per moved corner and frame, the value it +replaced (`edits`: t, corner, was), so the edit can be reset and the interface can show what was moved by hand. + +Pure functions over the pin's dict: the pin given is never changed. The window's twin is +frontend/src/engine/pin-edit.ts; tests/test_pin_edit.py runs both and compares them. +""" + +from __future__ import annotations + +import bisect +import copy +import math + +REACH = 4.0 # how far off the canvas a corner may go, in canvas widths and heights +FOLDED = "the four corners would fold or cross there; move this corner less far" + + +def _check(pin: object, corner: int) -> dict: + if not isinstance(pin, dict) or not isinstance(pin.get("points"), list): + raise ValueError("that clip has no corner pin: apply a track as a corner pin first") + if pin.get("mesh"): + raise ValueError("a mesh pin is shaped in the Track workspace, not by its four corners") + if not isinstance(corner, int) or isinstance(corner, bool) or not 0 <= corner <= 3: + raise ValueError("corner is 0 (top left), 1 (top right), 2 (bottom right) or 3 (bottom left)") + return pin + + +def _point(x: float, y: float) -> tuple[float, float]: + try: + x, y = float(x), float(y) + except (TypeError, ValueError): + raise ValueError("a corner's x and y are finite numbers") from None + if not (math.isfinite(x) and math.isfinite(y)): + raise ValueError("a corner's x and y are finite numbers") + if not (-REACH <= x <= 1 + REACH and -REACH <= y <= 1 + REACH): + raise ValueError(f"a corner stays within {REACH:g} canvas widths of the canvas") + return round(x, 6), round(y, 6) + + +def _convex(flat: list[float]) -> bool: + """Whether four corners (eight numbers, in order around) make a convex quadrilateral, the only kind a corner pin + can draw: a folded or crossed one sends part of the picture through infinity, and the warp floods the canvas.""" + signs = set() + for k in range(4): + ax, ay = flat[2 * k], flat[2 * k + 1] + bx, by = flat[(2 * k + 2) % 8], flat[(2 * k + 3) % 8] + cx, cy = flat[(2 * k + 4) % 8], flat[(2 * k + 5) % 8] + cross = (bx - ax) * (cy - by) - (by - ay) * (cx - bx) + if abs(cross) < 1e-9: + return False + signs.add(cross > 0) + return len(signs) == 1 + + +def _sample(pin: dict, local: float, fps: float, insert: bool) -> tuple[dict, int | None]: + """The pin (a copy) and the index of its sample on the frame at local seconds; with insert, one is made there + (the corners interpolated as the renderer would draw them) when the track has none within half a frame.""" + from .renderer import pin_at + + out = copy.deepcopy(pin) + times = out["times"] + reach = 0.5 / max(1e-6, float(fps)) + 1e-9 + nearest = min(range(len(times)), key=lambda i: abs(float(times[i]) - local), default=None) + if nearest is not None and abs(float(times[nearest]) - local) <= reach: + return out, nearest + if not insert: + return out, None + corners = pin_at({"cornerPin": pin}, local) + if corners is None: + raise ValueError("that clip's corner pin cannot be read at that time") + at = bisect.bisect_left([float(t) for t in times], local) + out["times"] = [*times[:at], round(local, 6), *times[at:]] + out["points"] = [*out["points"][:at], [round(v, 6) for xy in corners for v in xy], *out["points"][at:]] + return out, at + + +def edit_corner(pin: object, local: float, corner: int, x: float, y: float, fps: float) -> dict: + """The pin with one corner at (x, y), canvas fractions, on the frame at local seconds (the clip's own time).""" + pin = _check(pin, corner) + x, y = _point(x, y) + edits = list(pin.get("edits") or []) + if not pin.get("times"): + out = copy.deepcopy(pin) + was = list(out["points"][corner]) + out["points"][corner] = [x, y] + if not _convex([float(v) for xy in out["points"] for v in xy]): + raise ValueError(FOLDED) + if not any(e.get("corner") == corner and "t" not in e for e in edits): + edits.append({"corner": corner, "was": was}) + return {**out, "edits": edits} + out, index = _sample(pin, float(local), fps, insert=True) + flat = list(out["points"][index]) + was = [flat[2 * corner], flat[2 * corner + 1]] + flat[2 * corner], flat[2 * corner + 1] = x, y + if not _convex([float(v) for v in flat]): + raise ValueError(FOLDED) + out["points"][index] = flat + t = round(float(out["times"][index]), 6) + if not any(e.get("t") == t and e.get("corner") == corner for e in edits): + edits.append({"t": t, "corner": corner, "was": was}) + return {**out, "edits": sorted(edits, key=lambda e: (e.get("t", -1.0), e["corner"]))} + + +def reset_corner(pin: object, local: float, corner: int, fps: float) -> dict: + """The pin with a hand-moved corner on the frame at local seconds put back where the track had it.""" + pin = _check(pin, corner) + edits = list(pin.get("edits") or []) + if not pin.get("times"): + record = next((e for e in edits if e.get("corner") == corner and "t" not in e), None) + out = copy.deepcopy(pin) + if record is not None: + out["points"][corner] = list(record["was"]) + else: + out, index = _sample(pin, float(local), fps, insert=False) + t = round(float(out["times"][index]), 6) if index is not None else None + record = next((e for e in edits if t is not None and e.get("t") == t and e.get("corner") == corner), None) + if record is not None: + flat = list(out["points"][index]) + flat[2 * corner], flat[2 * corner + 1] = record["was"] + out["points"][index] = flat + rest = [e for e in edits if e is not record] + out.pop("edits", None) + return {**out, "edits": rest} if rest else out diff --git a/backend/app/planar.py b/backend/app/planar.py index 39a4a1c9..59095871 100644 --- a/backend/app/planar.py +++ b/backend/app/planar.py @@ -116,6 +116,31 @@ def fit(model: str, a: np.ndarray, b: np.ndarray, threshold: float = 1.0) -> tup return _scale_shift(a[best_in], b[best_in], model), best_in +PROMOTE_BELOW = 0.6 # a lower model holding less than this share of the points is refitted in perspective +PROMOTE_GAIN = 0.2 # and the perspective fit is kept when it holds at least this much more of them + + +def promote( + model: str, a: np.ndarray, b: np.ndarray, share: float | None = None, total: int | None = None, threshold: float = 1.0 +) -> tuple[np.ndarray, np.ndarray] | None: + """The same point pairs fitted in perspective, when the chosen model is below it and holds under PROMOTE_BELOW of + the points (share, of total; fitted here when not given) and the perspective fit holds at least PROMOTE_GAIN more: + (its matrix, its inliers). None otherwise. A plane seen at an angle that a similarity cannot follow (a screen + tilting) is fitted for that frame by what it is, rather than left drifting until the track is lost.""" + if model == "perspective": + return None + count = max(1, total if total is not None else len(np.asarray(a).reshape(-1, 2))) + if share is None: + low, low_in = fit(model, a, b, threshold) + share = float(low_in.sum()) / count if low is not None else 0.0 + if share >= PROMOTE_BELOW: + return None + high, high_in = fit("perspective", a, b, threshold) + if high is None or float(high_in.sum()) / count < share + PROMOTE_GAIN: + return None + return high, high_in + + def _scale_shift(a: np.ndarray, b: np.ndarray, model: str) -> np.ndarray | None: if model == "translation": d = np.median(b - a, axis=0) @@ -265,6 +290,8 @@ def __init__(self, reference_frame: np.ndarray, matte: np.ndarray, settings: Set self.ref_to_origin = np.eye(3) # the current reference's place in the first reference's frame self.history: list[np.ndarray] = [np.eye(3)] # the last homographies, origin to frame, for the prediction self.refreshes = 0 + self.promoted = False # the last step's fit was taken up to perspective (promote), for the track to mark + self._promoted_now = False # the picture the tracker reads: one channel, blurred as asked def _pick_channel(self, frame: np.ndarray, matte: np.ndarray) -> int | None: @@ -341,6 +368,7 @@ def _refine(self, gray: np.ndarray, start: np.ndarray, exclude: np.ndarray | Non fitted and composed. Returns reference to frame, and the share of points that held.""" ref = self.ref pts = ref.points + self._promoted_now = False # set when this frame's fit was taken up to perspective (promote) if len(pts) < 8: return start, 0.0 if exclude is not None: @@ -416,7 +444,12 @@ def _refine(self, gray: np.ndarray, start: np.ndarray, exclude: np.ndarray | Non ok = (ok1.ravel() == 1) & (ok2.ravel() == 1) & (np.linalg.norm((returned - local).reshape(-1, 2), axis=1) < 0.5) if ok.sum() < 8: break - residual, inliers = fit(self.model, local[ok].reshape(-1, 2), moved[ok].reshape(-1, 2), threshold=1.0) + pairs = local[ok].reshape(-1, 2), moved[ok].reshape(-1, 2) + residual, inliers = fit(self.model, *pairs, threshold=1.0) + share = float(inliers.sum()) / max(1, len(local)) if residual is not None else 0.0 + better = promote(self.model, *pairs, share=share, total=len(local)) + if better is not None: + residual, inliers = better if residual is None: break # residual maps reference-box points to the back-warped picture's points; back(x) = frame(h shift x) @@ -426,12 +459,19 @@ def _refine(self, gray: np.ndarray, start: np.ndarray, exclude: np.ndarray | Non break h = composed held = float(inliers.sum()) / max(1, len(local)) + self._promoted_now = self._promoted_now or better is not None # either pass taken up marks the frame return h, held + def hold(self, h: np.ndarray) -> None: + """The plane held where it was last seen (When the track is lost: Hold): the next prediction starts there, + with no motion carried on, so the plane can be found again where it went out of sight.""" + self.history = [np.asarray(h, float)] + def step(self, frame: np.ndarray, exclude: np.ndarray | None = None) -> tuple[np.ndarray, float]: """A step that cannot be made (the numbers of a lost plane failing somewhere) gives the prediction with no confidence rather than an error: in the owner's first run of the workspace a lost plane stopped the whole job with "Singular matrix".""" + self.promoted = False try: return self._step(frame, exclude) except (np.linalg.LinAlgError, cv2.error, ValueError, FloatingPointError, ZeroDivisionError): @@ -452,6 +492,7 @@ def _step(self, frame: np.ndarray, exclude: np.ndarray | None = None) -> tuple[n local_guess = guess @ self.ref_to_origin rough = self._rough(gray, local_guess) if self.settings.motion == "large" else local_guess local, held = self._refine(gray, rough, exclude) + self.promoted = self._promoted_now if self.settings.motion == "large" and rough is not local_guess: # the rough match and the prediction disagree by more than a pixel at the plane's corners: refine from both # and keep the one more of the points agree with (a faint surface's rough match can mislead the refinement) @@ -461,6 +502,7 @@ def _step(self, frame: np.ndarray, exclude: np.ndarray | None = None) -> tuple[n again, again_held = self._refine(gray, local_guess, exclude) if again_held > held + 0.02: local, held = again, again_held + self.promoted = self._promoted_now result = local @ to_ref result = result / result[2, 2] self.history = [*self.history, result][-3:] diff --git a/backend/app/planar_api.py b/backend/app/planar_api.py index af9a97ba..7ba674a1 100644 --- a/backend/app/planar_api.py +++ b/backend/app/planar_api.py @@ -68,8 +68,26 @@ class TrackBody(BaseModel): above: list[Layer] = Field(default_factory=list, max_length=32) # layers in front, excluding what they cover -def _settings(raw: dict) -> Settings: - raw = {k: v for k, v in raw.items() if k not in ("screen", "matte")} # read by the job itself (track_layer) +def four_cornered(layer: Layer) -> bool: + """A layer drawn as one four-cornered polygon: a screen, a sign, a corner-pin target.""" + shapes = [s for s in layer.shapes if s.mode == "add"] + return ( + len(shapes) == 1 and len(layer.shapes) == 1 and shapes[0].kind == "polygon" and not shapes[0].handles and len(shapes[0].points) == 4 + ) + + +def _settings(raw: dict, layer: Layer | None = None) -> Settings: + """A layer's track settings. Perspective is on by default for a four-cornered layer (four_cornered): a plane seen + at an angle, which a similarity cannot follow as it tilts (on synthetic screen clips with exact corners, 25 to 35 + px of mean error against under one with Perspective on). What the person chose is kept.""" + if layer is not None and raw.get("perspective") is None and four_cornered(layer): + raw = {**raw, "perspective": True} + elif raw.get("perspective") is None and "perspective" in raw: + raw = {k: v for k, v in raw.items() if k != "perspective"} + lost = raw.get("lost", "stop") + if lost not in (None, "stop", "hold"): + raise HTTPException(400, "lost is stop or hold: what the track does when the plane is lost") + raw = {k: v for k, v in raw.items() if k not in ("screen", "matte", "lost")} # read by the job itself (track_layer) allowed = set(Settings.__dataclass_fields__) unknown = set(raw) - allowed if unknown: @@ -84,7 +102,9 @@ def _signature(layer: Layer, media_id: str) -> str: """What a track depends on: the media, the shapes, the reference frame and the settings.""" # (a point's feather is the matte's, not the tracker's: softening an edge does not start a track afresh) shapes = [{k: v for k, v in s.model_dump().items() if k != "feather"} for s in layer.shapes] - raw = json.dumps([media_id, shapes, round(layer.reference, 6), layer.settings], sort_keys=True) + # (nor is what to do when the plane is lost: the frames tracked before it hold either way) + settings = {k: v for k, v in layer.settings.items() if k != "lost"} + raw = json.dumps([media_id, shapes, round(layer.reference, 6), settings], sort_keys=True) return hashlib.sha256(raw.encode()).hexdigest()[:16] @@ -99,6 +119,12 @@ def _load(layer_id: str) -> dict: return data if isinstance(data, dict) else {} +def _tidy(data: dict) -> dict: + """A track as written: its held and promoted marks only when it has any, so a track with neither is stored as + it was before they existed.""" + return {k: v for k, v in data.items() if v or k not in ("held", "promoted")} + + def _video(media_id: str) -> tuple[Path, float, int, int, int]: """The media's file, frame rate, size and frame count.""" from .media import _ffprobe, media_path @@ -274,7 +300,7 @@ def track_layer(body: TrackBody) -> dict: from .planar import PlanarTracker path_of = _path(body.layer.id) - settings = _settings(body.layer.settings) + settings = _settings(body.layer.settings, body.layer) for layer in body.above: _path(layer.id) source, fps, width, height, count = _video(body.media_id) @@ -352,6 +378,10 @@ def step(self, picture, exclude=None): else: tracker = PlanarTracker(frame, matte, settings) done, faint, lost = 0, 0, None + hold = body.layer.settings.get("lost") == "hold" + held = data.setdefault("held", {}) # frame -> 1: a lost frame given the last good position (Hold) + promoted = data.setdefault("promoted", {}) # frame -> 1: fitted in perspective above the layer's model + good_h, run = np.eye(3), [] # the last confident step's homography; the faint frames since it report(0.0, f"Tracking from frame {first}") for index, frame in frames: if cancelled(): @@ -368,21 +398,42 @@ def step(self, picture, exclude=None): # a plane lost: twelve frames running with almost no confidence end the track there, what came # before it kept (Mocha drifts on; stopping says where it went wrong) faint = faint + 1 if confidence < 0.05 and settings.motion != "manual" else 0 - if faint >= 12: + run = [*run, index] if faint else [] + if not faint: + good_h = h + if hold and faint >= 12: + # When the track is lost: Hold. The twelve faint frames and every one after them until the plane + # is found again keep the last good position, marked held; the tracker looks for it there + h = good_h + held_full = (good_h @ start_h) / (good_h @ start_h)[2, 2] + for again in run[:-1] if faint == 12 else []: + data["frames"][str(again)] = held_full.ravel().round(9).tolist() + held[str(again)] = 1 + held[str(index)] = 1 + if hasattr(tracker, "hold"): + tracker.hold(good_h) + elif faint >= 12: way = 1 if last >= first else -1 lost = index - 11 * way # the first of the twelve, in the order tracked for drop in range(min(lost, index), max(lost, index) + 1): data["frames"].pop(str(drop), None) data["confidence"].pop(str(drop), None) + promoted.pop(str(drop), None) done -= 11 break full = h @ start_h # reference to frame: the frame tracked from, then on from it full = full / full[2, 2] data["frames"][str(index)] = full.ravel().round(9).tolist() data["confidence"][str(index)] = round(confidence, 3) + if not (hold and faint >= 12): + held.pop(str(index), None) # tracked afresh: no longer held + if getattr(tracker, "promoted", False) and not (hold and faint >= 12): + promoted[str(index)] = 1 + else: + promoted.pop(str(index), None) done += 1 if done % 12 == 0: - write_json(path_of, data) + write_json(path_of, _tidy(data)) report( done / max(1, total), f"Frame {index} of {count}, confidence {confidence:.2f}", @@ -423,9 +474,12 @@ def step(self, picture, exclude=None): full = rel @ start_h data["frames"][str(gap)] = (full / full[2, 2]).ravel().round(9).tolist() data["confidence"][str(gap)] = 0.5 + held.pop(str(gap), None) # filled from the frames either side, not held _readjust(data) # the reference points' corrections carried onto the frames just tracked - write_json(path_of, data) + write_json(path_of, _tidy(data)) out = {"layer": body.layer.id, "tracked": done, "from": first, "to": first + (done if last >= first else -done)} + if hold: + out["held"] = sum(1 for k in held if int(k) in range(min(first, last), max(first, last) + 1)) return {**out, "lost": lost} if lost is not None else out finally: lock.release() @@ -659,6 +713,8 @@ def read_track(layer_id: str, surface: str = "") -> dict: "frames": [int(i) for i in order], "matrices": [data["frames"][i] for i in order], "confidence": [data["confidence"].get(i, 0.0) for i in order], + "held": [int(i) for i in order if i in (data.get("held") or {})], # lost frames kept at the last good position + "promoted": [int(i) for i in order if i in (data.get("promoted") or {})], # frames refitted in perspective } adjusted = data.get("adjusted") or {} if adjusted: @@ -692,6 +748,8 @@ def clear_track(layer_id: str, start: int | None = None, stop: int | None = None for i in gone: data["frames"].pop(i, None) data["confidence"].pop(i, None) + (data.get("held") or {}).pop(i, None) + (data.get("promoted") or {}).pop(i, None) write_json(path, data) return {"cleared": len(gone)} diff --git a/backend/app/renderer.py b/backend/app/renderer.py index 5e45131f..d5213eb0 100644 --- a/backend/app/renderer.py +++ b/backend/app/renderer.py @@ -25,6 +25,7 @@ from .render_document import flatten, nested_project, validate_document from .stabilise import apply as stabilise_frame from .timing import animation_at, effect_params_at, fade_at, property_at, source_time +from .vfx_link import link_of from .video_source import acquire, recycle @@ -1141,6 +1142,9 @@ def media_frame(self, clip: dict, time: float, planes: bool = False) -> np.ndarr if not hasattr(self, "_media_known"): self._media_known = {} self._media_known[media_id] = known + live = link_of(known[0]) + if live is not None: + return self._linked_frame(clip, known[0], live, time) if clip.get("reversed"): candidate = reversed_path(media_id) if not candidate.is_file(): @@ -1249,6 +1253,33 @@ def media_frame(self, clip: dict, time: float, planes: bool = False) -> np.ndarr self.decode_scale[media_id] = max(result.shape[0], result.shape[1]) / native return self._noted(result if result is frame else apply_crop(result, clip)) + def _linked_frame(self, clip: dict, record: dict, link: dict, time: float) -> np.ndarray: + """A FormVFX live comp's frame (vfx_link): asked of FormVFX on the comp's own frame grid, the last few kept for + this renderer. With FormVFX closed the clip is unreadable and says what to do, as a missing file does.""" + from .vfx_link import LinkUnavailable, frame_rgba, rate_of + + fps = rate_of(record, link) + index = max(0, int(time * fps + 1e-7)) + if float(record.get("duration") or 0) > 0: + # past the comp's end (a clip held or stretched beyond it) its last frame holds, as a file's does + index = min(index, max(0, round(float(record["duration"]) * fps) - 1)) + native = max(int(record.get("width") or 0), int(record.get("height") or 0)) or 1920 + side = min(native, self.decode_limit) if self.decode_limit else native + if not hasattr(self, "_linked"): + self._linked: dict[tuple, np.ndarray] = {} + key = (record.get("id"), index, side) + if key not in self._linked: + try: + picture = frame_rgba(link, index / fps, side) + except LinkUnavailable as exc: + raise MediaUnreadable(record.get("name") or clip.get("label") or str(record.get("id")), str(exc)) from exc + while len(self._linked) >= 4: + self._linked.pop(next(iter(self._linked))) + self._linked[key] = picture + picture = self._linked[key] + self.decode_scale[record.get("id")] = max(picture.shape[0], picture.shape[1]) / native + return apply_crop(picture.copy(), clip) + def scaled_effects(self, effects: list[dict], clip: dict) -> list[dict]: """Pixel-measured parameters follow the resolution actually decoded. diff --git a/backend/app/vfx_link.py b/backend/app/vfx_link.py new file mode 100644 index 00000000..a2e69c4d --- /dev/null +++ b/backend/app/vfx_link.py @@ -0,0 +1,522 @@ +"""A FormVFX live comp as a clip: a `.fvxlink` in the media library, its frames from FormVFX's Live Link. + +FormVFX (nodemode-dev/formVFX, backend/app/engine/link.py and routers/link.py) writes a `.fvxlink` descriptor for a +composition: format `formvfx.link/1`, the project's path and id, the comp's id and name, its size, rate and length. +While FormVFX runs it serves the comp at GET /api/link/info, /api/link/frame.png and /api/link/audio, each needing +the `x-formvfx-local: 1` header and nothing else (those reads need no window key), on loopback. + +Here a descriptor becomes a video item in the media library (its file `.fvxlink`, its record carrying `link`). +The renderer asks FormVFX for each frame (frame_rgba), so preview and export stay one renderer; with FormVFX closed +the clip is unreadable and says why, as a missing file does. Render and replace (POST /api/vfx-link//render) reads +every frame and the sound and writes a normal movie with formcut's own ffmpeg, a separate program as always, then +the window points the project's clips at it, so a project never depends on FormVFX running. + +The network rules: only FormVFX's own fixed routes are called, never an address or URL template from a descriptor; the +address is loopback http only (FORMVFX_URL, else FormVFX's engine.json, else its default 127.0.0.1:8250); no proxy +from the environment, no redirects followed, and each reply's size and type are checked before use. +""" + +from __future__ import annotations + +import contextlib +import io +import json +import math +import os +import re +import subprocess +import tempfile +import uuid +from pathlib import Path, PurePosixPath, PureWindowsPath +from urllib.parse import urlsplit + +import httpx +import numpy as np +from fastapi import APIRouter, HTTPException +from pydantic import BaseModel + +from . import jobs + +router = APIRouter(prefix="/api/vfx-link", tags=["vfx-link"]) + +FORMAT = "formvfx.link/" +READS = 1 # the descriptor format this build reads (formvfx.link/1) +SUFFIX = ".fvxlink" +DEFAULT = "http://127.0.0.1:8250" # FormVFX's own default (core/config.py BACKEND_PORT) +LOCAL_HEADER = {"x-formvfx-local": "1"} +LOOPBACK = ("127.0.0.1", "localhost", "::1") +MAX_FRAME = 256 * 1024 * 1024 # bytes a frame reply may carry (an 8192 px RGBA PNG at worst) +MAX_AUDIO = 64 * 1024 * 1024 # bytes a sound reply may carry (FormVFX's own cap is 600 s a request) +MAX_DESCRIPTOR = 64 * 1024 +AUDIO_RATE, AUDIO_CHUNK = 48000, 30.0 + + +class LinkUnavailable(RuntimeError): + """FormVFX did not answer, or answered with something formcut cannot use; the message says what to do.""" + + +# ---- the descriptor ---- + + +def _text(value: object, limit: int) -> str | None: + if value is None or value == "": + return None + if not isinstance(value, str | int) or isinstance(value, bool) or len(str(value)) > limit or "\x00" in str(value): + raise ValueError + return str(value) + + +PROJECT_EXT = (".fvxproj", ".ecproj", ".ecprojx") # FormVFX's own project files (engine/link.py PROJECT_EXT) +_TOKEN = re.compile(r"^[A-Za-z0-9_.:-]{1,128}$") # a project id or a comp id as FormVFX writes them +_SCHEME = re.compile(r"^[A-Za-z][A-Za-z0-9+.-]+:") # smb:, file:, http: (a drive letter has one letter only) +_CONTROL = re.compile(r"[\x00-\x1f\x7f]") + + +def project_shape(value: str) -> str: + """A link's project path as formcut will forward it: absolute and on this computer (no UNC or network share, + no URL scheme, no `..`), naming a FormVFX project file. Raises ValueError naming what is wrong. Whether the file + is there is asked when it is used (project_file).""" + text = value.strip() + if _CONTROL.search(text): + raise ValueError("the link's project path holds control characters") + if text.startswith(("\\\\", "//")) or _SCHEME.match(text): + raise ValueError("the link's project is on a network share or behind a URL; formcut forwards only a project on this computer") + if not (PurePosixPath(text).is_absolute() or PureWindowsPath(text).is_absolute()) or PureWindowsPath(text).drive.startswith("\\\\"): + raise ValueError("the link's project path is not absolute; export the link again from FormVFX") + if ".." in PurePosixPath(text.replace("\\", "/")).parts: + raise ValueError("the link's project path climbs out of its folder (..)") + if not text.lower().endswith(PROJECT_EXT): + raise ValueError("the link's project is not a FormVFX project file (.fvxproj)") + return text + + +def project_file(link: dict) -> str | None: + """The link's project file as it is now, its links followed: the resolved path when it is still a FormVFX + project file on this computer, else None (FormVFX then finds the project by its id, as it does when a project is + moved).""" + raw = link.get("project") + if not raw: + return None + try: + real = Path(project_shape(str(raw))).expanduser().resolve(strict=True) + project_shape(str(real)) # where a link points is checked as the path itself was + except (OSError, ValueError, RuntimeError): + return None + return str(real) if real.is_file() else None + + +SIDES, RATES, LENGTH = (16, 8192), (1.0, 240.0), (0.01, 24 * 3600.0) # what a comp's size, rate and length may be + + +def _number(value: object, bounds: tuple[float, float]) -> float | None: + """A positive finite number inside bounds, else None: a descriptor is often a downloaded file, and a rate of 1e-300 + or a width of 1e9 would otherwise size a render that fills the disk or the memory.""" + try: + number = float(value) if value is not None else None + except (TypeError, ValueError): + return None + return number if number is not None and math.isfinite(number) and bounds[0] <= number <= bounds[1] else None + + +def _side(value: object) -> int | None: + number = _number(value, SIDES) + return int(number) if number else None + + +def parse(descriptor: object) -> dict: + """A `.fvxlink` descriptor read as FormVFX writes it, keeping only the fields formcut uses (its URL templates are + dropped: formcut calls FormVFX's own routes). Raises ValueError naming what is wrong.""" + if not isinstance(descriptor, dict) or not str(descriptor.get("format") or "").startswith(FORMAT): + raise ValueError("this is not a FormVFX Live Link file (its format should be formvfx.link/1)") + try: + major = int(str(descriptor["format"])[len(FORMAT) :].split(".")[0]) + except ValueError: + raise ValueError("this is not a FormVFX Live Link file (its format should be formvfx.link/1)") from None + if major > READS: + raise ValueError( + f"this link was written by a newer FormVFX ({descriptor.get('formvfx') or descriptor['format']}); update formcut to open it" + ) + comp = descriptor.get("comp") if isinstance(descriptor.get("comp"), dict) else {} + try: + project, project_id = _text(descriptor.get("project"), 4096), _text(descriptor.get("projectId"), 128) + except ValueError: + raise ValueError("the link's project is not a path formcut can pass on") from None + if project is not None: + project = project_shape(project) + if project_id is not None and not _TOKEN.match(project_id): + raise ValueError("the link's project id is not one FormVFX writes") + try: + comp_id, comp_name = _text(comp.get("id"), 128), _text(comp.get("name"), 512) + except ValueError: + raise ValueError("the link's comp is not one formcut can name") from None + if (comp_id is not None and not _TOKEN.match(comp_id)) or (comp_name is not None and _CONTROL.search(comp_name)): + raise ValueError("the link's comp is not one formcut can name") + if not project and not project_id: + raise ValueError("the link names no project: export it again from FormVFX after saving the project") + if comp_id is None and comp_name is None: + raise ValueError("the link names no comp: export it again from FormVFX") + return { + "format": f"{FORMAT}{major}", + "formvfx": str(descriptor["formvfx"])[:64] if isinstance(descriptor.get("formvfx"), str) else None, + "project": project, + "projectId": project_id, + "comp": {"id": comp.get("id") if comp_id is not None else None, "name": comp_name}, + "width": _side(descriptor.get("width")), + "height": _side(descriptor.get("height")), + "frameRate": _number(descriptor.get("frameRate"), RATES), + "duration": _number(descriptor.get("duration"), LENGTH), + } + + +# ---- where FormVFX runs: loopback only ---- + + +def _loopback(url: object) -> str | None: + """The address as scheme://host:port when it is plain http on this computer with a port and nothing else.""" + if not isinstance(url, str): + return None + try: + parts = urlsplit(url.strip().rstrip("/")) + port = parts.port + except ValueError: + return None + if parts.scheme != "http" or parts.hostname not in LOOPBACK or not port or parts.username or parts.password: + return None + if parts.path or parts.query or parts.fragment: + return None + host = f"[{parts.hostname}]" if ":" in parts.hostname else parts.hostname + return f"http://{host}:{port}" + + +def _formvfx_data() -> Path: + raw = os.environ.get("FORMVFX_DATA_DIR", "").strip() + return Path(raw).expanduser() if raw else Path.home() / "Formvfx" + + +def base() -> str: + """Where FormVFX answers: FORMVFX_URL, else the address FormVFX records in its engine.json, else its default; + anything that is not loopback http is passed over.""" + given = _loopback(os.environ.get("FORMVFX_URL", "")) + if given: + return given + with contextlib.suppress(OSError, ValueError, AttributeError): + recorded = _loopback(json.loads((_formvfx_data() / "engine.json").read_text(encoding="utf-8")).get("url")) + if recorded: + return recorded + return DEFAULT + + +def _client(timeout: float = 20.0) -> httpx.Client: + return httpx.Client( + base_url=base(), headers=LOCAL_HEADER, trust_env=False, follow_redirects=False, timeout=httpx.Timeout(timeout, connect=2.0) + ) + + +def _query(link: dict) -> dict: + """What FormVFX is told: the project file only as it resolves now on this computer (project_file), else only the + project's id, which FormVFX matches against the open project and its recent ones; and the comp.""" + comp = link.get("comp") or {} + pairs = {"project": project_file(link), "projectId": link.get("projectId"), "comp": comp.get("id"), "compName": comp.get("name")} + query = {k: str(v) for k, v in pairs.items() if v not in (None, "")} + if "project" not in query and "projectId" not in query: + raise LinkUnavailable("the linked FormVFX project is not on this computer any more, and the link has no project id to find it by") + return query + + +def _get(path: str, params: dict, limit: int, timeout: float = 20.0) -> bytes: + """One of FormVFX's link routes: its reply's body, read up to limit bytes.""" + where = base() + try: + with _client(timeout) as client, client.stream("GET", path, params=params) as reply: + status = reply.status_code + if 300 <= status < 400: + raise LinkUnavailable(f"FormVFX at {where} answered with a redirect, which formcut does not follow") + body = bytearray() + for chunk in reply.iter_bytes(): + body += chunk + if len(body) > limit: + raise LinkUnavailable("FormVFX's reply was larger than a frame or a stretch of sound can be") + except httpx.HTTPError as exc: + raise LinkUnavailable( + f"FormVFX is not answering at {where}: open FormVFX with the linked project, or Render and replace this clip" + ) from exc + if status >= 400: + try: + detail = str(json.loads(bytes(body)).get("detail") or "")[:300] + except (ValueError, AttributeError): + detail = "" + raise LinkUnavailable(f"FormVFX could not serve the linked comp: {detail or f'error {status}'}") + return bytes(body) + + +def info(link: dict) -> dict: + """The comp as FormVFX serves it now: id, name, width, height, frameRate, duration.""" + try: + data = json.loads(_get("/api/link/info", _query(link), MAX_DESCRIPTOR, timeout=10.0)) + except ValueError: + raise LinkUnavailable("FormVFX's answer about the comp could not be read") from None + comp = data.get("comp") if isinstance(data, dict) and isinstance(data.get("comp"), dict) else None + if comp is None: + raise LinkUnavailable("FormVFX's answer about the comp could not be read") + return comp + + +def frame_png(link: dict, seconds: float, max_side: int) -> bytes: + side = max(16, min(8192, int(max_side))) + params = {**_query(link), "time": f"{max(0.0, float(seconds)):.9f}", "max": str(side)} + body = _get("/api/link/frame.png", params, min(MAX_FRAME, 4 * side * side + (1 << 20))) # no more than raw RGBA + if not body.startswith(b"\x89PNG\r\n\x1a\n"): + raise LinkUnavailable("FormVFX's frame was not a picture") + return body + + +def frame_rgba(link: dict, seconds: float, max_side: int) -> np.ndarray: + """The comp's frame at a time as an RGBA array.""" + from PIL import Image + + side = max(16, min(8192, int(max_side))) + try: + with Image.open(io.BytesIO(frame_png(link, seconds, side))) as picture: + if max(picture.size) > side: # FormVFX fits a frame inside the side asked for; anything larger is refused + raise LinkUnavailable("FormVFX's frame was larger than the size asked for") + return np.array(picture.convert("RGBA")) + except (OSError, ValueError, Image.DecompressionBombError) as exc: + raise LinkUnavailable("FormVFX's frame was not a picture formcut could read") from exc + + +def audio_pcm(link: dict, start: float, seconds: float) -> np.ndarray: + """The comp's sound from start for seconds: float32 stereo at AUDIO_RATE, (samples, 2).""" + params = {**_query(link), "start": f"{start:.9f}", "seconds": f"{seconds:.9f}", "rate": str(AUDIO_RATE)} + body = _get("/api/link/audio", params, MAX_AUDIO) + if len(body) < 44 or body[:4] != b"RIFF" or body[8:12] != b"WAVE": + raise LinkUnavailable("FormVFX's sound was not a WAV file") + at = body.find(b"data", 12) + if at < 0: + raise LinkUnavailable("FormVFX's sound had no samples") + pcm = body[at + 8 :] + usable = len(pcm) // 8 * 8 + return np.frombuffer(pcm[:usable], " np.ndarray: + """The comp's sound over a span, asked in chunks FormVFX takes and padded with silence to the exact length, so a + comp whose sound is shorter than its picture still fills the span: (round(seconds * AUDIO_RATE), 2).""" + want = max(0, round(seconds * AUDIO_RATE)) + out = np.zeros((want, 2), np.float32) + at = 0 + while at < want: + if cancelled(): + raise InterruptedError("Cancelled") + take = min(round(AUDIO_CHUNK * AUDIO_RATE), want - at) + got = audio_pcm(link, start + at / AUDIO_RATE, take / AUDIO_RATE)[:take] + out[at : at + len(got)] = got + at += take + return out + + +def rate_of(record: dict, link: dict) -> float: + """The comp's exact frame rate (the record's `fps` is rounded for display: 29.970 against 30000/1001 drifts a frame + every half minute).""" + for value in (record.get("frameRate"), link.get("frameRate"), record.get("fps")): + rate = _number(value, RATES) + if rate: + return rate + return 30.0 + + +def link_of(record: dict) -> dict | None: + """A media record's live link, when it is one.""" + link = record.get("link") if isinstance(record, dict) else None + return link if isinstance(link, dict) and str(link.get("format") or "").startswith(FORMAT) else None + + +def is_live(media_id: str) -> bool: + from .media import _find + + try: + return link_of(_find(media_id)) is not None + except HTTPException: + return False + + +# ---- the routes ---- + + +class ImportBody(BaseModel): + link: dict | None = None # the descriptor itself (the window reads a chosen file) + path: str | None = None # or a .fvxlink file on this computer (the desktop's own file dialog) + name: str | None = None + + +def _read_descriptor(path: str) -> tuple[dict, str]: + given = Path(path).expanduser() + if given.suffix.lower() != SUFFIX: + raise HTTPException(422, "choose a .fvxlink file, which FormVFX writes with Export Live Link Clip") + try: + file = given.resolve(strict=True) + if not file.is_file(): # not a device, a pipe or a folder behind the name + raise HTTPException(422, "that .fvxlink is not a file") + with file.open("rb") as handle: + raw = handle.read(MAX_DESCRIPTOR + 1) + if len(raw) > MAX_DESCRIPTOR: + raise HTTPException(422, "that .fvxlink is larger than a Live Link file can be") + return json.loads(raw.decode("utf-8")), given.stem + except (OSError, ValueError): + raise HTTPException(422, "that .fvxlink could not be read as a Live Link file") from None + + +def _thumbnail(media_id: str, link: dict, duration: float, width: int) -> bool: + from .media import THUMB_DIR + + with contextlib.suppress(LinkUnavailable, OSError, ValueError): + from PIL import Image + + picture = Image.fromarray(frame_rgba(link, min(1.0, duration / 2), 320)).convert("RGB") + picture.thumbnail((320, 320 * 4)) + THUMB_DIR.mkdir(parents=True, exist_ok=True) + picture.save(THUMB_DIR / f"{media_id}.jpg", "JPEG", quality=85) + return True + return False + + +@router.post("/import", status_code=201) +def import_link(body: ImportBody) -> dict: + """A `.fvxlink` (its descriptor, or its path) as a video item in the media library. FormVFX need not be running: + the size, rate and length then come from the descriptor, and the item is read from FormVFX when it runs.""" + from . import media + + if body.link is None and not body.path: + raise HTTPException(422, "send the link (the .fvxlink's contents) or the path of a .fvxlink") + raw, stem = (body.link, "") if body.link is not None else _read_descriptor(str(body.path)) + try: + link = parse(raw) + except ValueError as exc: + raise HTTPException(422, str(exc)) from None + if link["project"] and project_file(link) is None: + # imported, a link names a project file that is there: a missing one (or one whose links lead elsewhere) is + # refused rather than left for FormVFX to search for + raise HTTPException(422, "the link's FormVFX project file is not there; open the project in FormVFX and export the link again") + comp = {} + with contextlib.suppress(LinkUnavailable): + comp = info(link) + width = _side(comp.get("width")) or link["width"] or 1920 + height = _side(comp.get("height")) or link["height"] or 1080 + fps = float(_number(comp.get("frameRate"), RATES) or link["frameRate"] or 30.0) + duration = float(_number(comp.get("duration"), LENGTH) or link["duration"] or 5.0) + name = (body.name or stem or f"{link['comp'].get('name') or 'Comp'}").removesuffix(SUFFIX)[:200] + media_id = uuid.uuid4().hex + media.MEDIA_DIR.mkdir(parents=True, exist_ok=True) + stored = media.MEDIA_DIR / f"{media_id}{SUFFIX}" + stored.write_text(json.dumps(link, indent=2), encoding="utf-8") + item = { + "id": media_id, + "name": name, + "kind": "video", + "size": stored.stat().st_size, + "thumb": _thumbnail(media_id, link, duration, width), + "duration": round(duration, 3), + "width": width, + "height": height, + "fps": round(fps, 3), + "frameRate": fps, # exact, for the frame grid and Render and replace (rate_of) + "source": "formvfx-link", + "link": link, + } + with media._lock: + items = [entry for entry in media._read() if entry.get("id") != media_id] + media._write([*items, item]) + return item + + +def _record(media_id: str) -> tuple[dict, dict]: + from .media import _find + + record = _find(media_id) + link = link_of(record) + if link is None: + raise HTTPException(404, "that media is not a FormVFX live link") + return record, link + + +@router.get("/{media_id}") +def link_status(media_id: str) -> dict: + """Whether FormVFX is serving the linked comp now, and the comp as it serves it.""" + _, link = _record(media_id) + try: + return {"running": True, "comp": info(link), "address": base(), "link": link} + except LinkUnavailable as exc: + return {"running": False, "message": str(exc), "address": base(), "link": link} + + +def _encode(record: dict, link: dict, out: Path, report, cancelled) -> int: + """Every frame and the sound of the linked comp written to out (ProRes 4444 with its alpha, PCM sound) by + formcut's ffmpeg, a separate program. Returns the frame count.""" + from .tools import ffmpeg + + # bounded again here, whatever the record says (it is a file in the data folder) + fps = rate_of(record, link) + width, height = _side(record.get("width")) or 1920, _side(record.get("height")) or 1080 + count = max(1, round(float(_number(record.get("duration"), LENGTH) or 1.0) * fps)) + with tempfile.TemporaryDirectory(prefix="formcut-vfx-") as scratch: + sound = Path(scratch) / "sound.f32" + sound.write_bytes(np.ascontiguousarray(audio_span(link, 0.0, count / fps, cancelled), " dict: + """The linked comp rendered to a normal movie in the media library, as a job; its result names the new item + (`media`), and the window then points the project's clips at it (media.replace, one undo step).""" + record, link = _record(media_id) + + def operation(job_id, report, cancelled): + from .media import ingest_path + from .paths import DATA_DIR + + info(link) # FormVFX answers, or the job ends here with what to do + out = DATA_DIR / "renders" / f"formvfx-{job_id}.mov" + out.parent.mkdir(parents=True, exist_ok=True) + try: + frames = _encode(record, link, out, report, cancelled) + except BaseException: + out.unlink(missing_ok=True) + raise + name = f"{record.get('name') or 'FormVFX comp'} (rendered).mov" + made = ingest_path(out, name, {"source": "formvfx-render", "renderedFrom": media_id}) + return {"media": made, "frames": frames} + + return jobs.submit("formvfx-render", operation) diff --git a/form-functions.json b/form-functions.json index 85cb5eb9..64918d7b 100644 --- a/form-functions.json +++ b/form-functions.json @@ -2,7 +2,7 @@ "format": "form-functions", "format_version": 1, "app": "formcut", - "app_version": "2.23.0", + "app_version": "2.24.0", "functions": [ { "id": "transcribe", diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md index 94a63992..db0dd23c 100644 --- a/frontend/HASHOUT_LOG.md +++ b/frontend/HASHOUT_LOG.md @@ -2,6 +2,26 @@ Reasoning behind interface changes, newest first. +## 2.24.0 · Edit corners on an applied pin (`ui/pin-corners.ts` new, `engine/pin-edit.ts` new; `engine/project.ts` `clip.pinCorner`; `ui/render-preview.ts` the mount; `ui/inspector-pane.ts`, `ui/tracking.ts` the toggle; `styles/creator.css`, `styles/app.css`) + +- **Where it is.** The inspector's Track section has Edit corners, shown only while the selected clip has a corner pin that is not a mesh. The inspector is built once at boot, so the button is always mounted and `tracking.ts` shows or hides it on `clips` and `clip-selection`; the pin's other buttons there (Remove, motion blur, matching) are still written from the selection at boot and so do not appear for a clip chosen later, which is left for the owner. +- **The grips.** `.preview-pin` sits over the stage at `--z-handles`, absolutely placed in percent of the stage (the canvas's own box), built once and patched: an outline polygon and four grips at the pin's corners on the current frame, read with the renderer's own interpolation. A drag moves the grip live and dispatches `clip.pinCorner` once on release (one undo step); a corner moved by hand on this frame is filled with the accent; a double-click puts it back. A move that would fold or cross the corners is checked before dispatch and said in a toast. The transform handles are hidden while the grips are on (`.stage[data-pin="on"]`), as they are for crop. +- **Strings.** Eight phrases in every language: the button, its hint, the grip hint, the four corner names and the fold message. +- **Seen.** `frontend/tests/window/test_pin_link_controls.py` in Chromium: the button hidden with nothing chosen and shown for the pinned clip; turning the grips on and off adds 0 to the layout shift; the bottom right grip on the pin's corner within 3 px; dragged 30 by 20 px it moves and is marked, and Ctrl or Cmd+Z puts it back within 2 px. + +## 2.24.0 · Track workspace: When the track is lost, and Perspective by default (`ui/planar-workspace.ts` `DEFAULTS`, `fourCornered`, `paintSettings`, the settings change handler, `loadTrack`, `paintStrip`, `render`) + +- **When the track is lost.** A select in the track settings: Stop (the default; nothing is written) or Hold last position (`settings.lost = "hold"`). Changing it does not ask to start the track afresh, since the engine leaves it out of the track's signature. A finished track with held frames says how many. +- **Confidence strip.** Held frames are drawn over in `--ink-faint` across the bar, frames the engine refitted in perspective as a 2 px line in `--cue` along its top; its title explains the colours. The strip's own green, amber and red are the existing literals. +- **Perspective.** `perspective` left out of `DEFAULTS`: a new layer leaves it unset, the engine decides (four corners: on), and the box shows that, kept in step in `render` as the shapes change; ticking or unticking it sets it for good. +- **Seen.** In Chromium: a rectangle drawn shows Perspective ticked, the select offers Stop and Hold last position with Stop chosen, and Hold is taken without a prompt. + +## 2.24.0 · a FormVFX live comp in the bin (`ui/vfx-link.ts` new; `ui/media-pane.ts` import and the card; `ui/timeline-pane.ts`; `engine/project.ts` `media.replace`; `engine/media.ts`) + +- **Import.** The Import chip takes a `.fvxlink`: through the system dialog its path goes to the engine, through the browser's file input its contents do. Other files go the way they always have. +- **The card.** A live comp's card says Live from FormVFX in its badge and has Render and replace where a video's proxy button is; proxy, upscale and posting are left off until it is rendered. Render and replace runs the job, shows its progress in the badge, then `media.replace` points every clip on the comp at the new movie, one undo step (unlike `media.relink`, which keeps no history). A failure says so in the badge, with the engine's reason as its title. +- **Seen.** In Chromium with FormVFX's address on a closed port: the card's badge and button, no proxy or post button, and Render and replace ending in "Render and replace failed" with FormVFX named in the title, no console error from it. + ## 2.23.0 · Studio, ComfyUI (`ui/comfyui-page.ts` new; `ui/studio-tools.ts` the tab, the empty section, the mount after `reconcileOptions`, `showPage`; `i18n/language-pack.ts`, `text.ts`; `public/locales/ar`, `fa`, `he`, `hr`) - **Where it is.** A ComfyUI tab beside Local models, with the grid icon. Its section is empty in the Studio markup and filled once by `mountComfyPage`, which keeps studio-tools.ts from growing and owns its own `data-cf-*` names. diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 1a145e4a..e18cb9a9 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "formcut-frontend", - "version": "2.23.0", + "version": "2.24.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "formcut-frontend", - "version": "2.23.0", + "version": "2.24.0", "dependencies": { "@huggingface/transformers": "^4.3.0", "@xterm/addon-fit": "0.11.0", diff --git a/frontend/package.json b/frontend/package.json index 84f19266..347279b3 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "formcut-frontend", - "version": "2.23.0", + "version": "2.24.0", "private": true, "type": "module", "scripts": { diff --git a/frontend/public/locales/ar.json b/frontend/public/locales/ar.json index dcc70e57..52efa0d6 100644 --- a/frontend/public/locales/ar.json +++ b/frontend/public/locales/ar.json @@ -1962,5 +1962,24 @@ "media.timelines": "المخططات الزمنية: ضع مخططًا زمنيًا آخر من هذا المشروع على هذا المخطط كمقطع واحد عند رأس التشغيل", "save.sync": "مزامنة", "save.sync.hint": "تُنسخ حزمة هذا المشروع مع كل حفظ إلى مجلد يحمله عميل المزامنة الخاص بك؛ formcut لا يرفع شيئًا.", - "save.syncfolder": "مجلد المزامنة" + "save.syncfolder": "مجلد المزامنة", + "pin.edit": "تحرير الزوايا", + "pin.editHint": "يعرض زوايا التثبيت الأربع في المعاينة لتحريك إحداها في هذا الإطار", + "pin.gripHint": "اسحب لتحريكها في هذا الإطار، وانقر نقرًا مزدوجًا لإعادتها", + "pin.corner.tl": "الزاوية العلوية اليسرى", + "pin.corner.tr": "الزاوية العلوية اليمنى", + "pin.corner.br": "الزاوية السفلية اليمنى", + "pin.corner.bl": "الزاوية السفلية اليسرى", + "planar.lostMode": "عند فقدان التتبع", + "planar.lostMode.stop": "إيقاف", + "planar.lostMode.hold": "الإبقاء على آخر موضع", + "planar.heldFrames": "إطارات أُبقيت على آخر موضع:", + "planar.stripLegend": "الثقة في كل إطار: الأخضر جيدة، والكهرماني متوسطة، والأحمر ضعيفة؛ الرمادي أُبقي على آخر موضع؛ وخط في الأعلى يعني مطابقة بالمنظور", + "vfxlink.live": "مباشر من FormVFX", + "vfxlink.render": "تصيير واستبدال", + "vfxlink.rendering": "جارٍ التصيير من FormVFX", + "vfxlink.replaced": "تم التصيير والاستبدال", + "vfxlink.failed": "فشل التصيير والاستبدال", + "vfxlink.unreadable": "تعذّرت قراءة ملف .fvxlink هذا", + "pin.folded": "لا يمكن وضع تلك الزاوية هناك: ستنطوي الزوايا الأربع أو تتقاطع" } diff --git a/frontend/public/locales/fa.json b/frontend/public/locales/fa.json index f7c7e9d1..14dea234 100644 --- a/frontend/public/locales/fa.json +++ b/frontend/public/locales/fa.json @@ -1962,5 +1962,24 @@ "media.timelines": "خط‌های زمانی: خط زمانی دیگری از این پروژه را به‌صورت یک کلیپ در نشانگر پخش روی این خط زمانی بگذارید", "save.sync": "همگام‌سازی", "save.sync.hint": "بستهٔ این پروژه با هر ذخیره به پوشه‌ای می‌رود که کلاینت همگام‌سازی خودت آن را می‌برد؛ formcut چیزی آپلود نمی‌کند.", - "save.syncfolder": "پوشهٔ همگام‌سازی" + "save.syncfolder": "پوشهٔ همگام‌سازی", + "pin.edit": "ویرایش گوشه‌ها", + "pin.editHint": "چهار گوشهٔ سنجاق را در پیش‌نمایش نشان می‌دهد تا یکی را در این فریم جابه‌جا کنید", + "pin.gripHint": "برای جابه‌جایی در این فریم بکشید؛ برای برگرداندن دوبار کلیک کنید", + "pin.corner.tl": "گوشهٔ بالا چپ", + "pin.corner.tr": "گوشهٔ بالا راست", + "pin.corner.br": "گوشهٔ پایین راست", + "pin.corner.bl": "گوشهٔ پایین چپ", + "planar.lostMode": "وقتی ردیابی از دست برود", + "planar.lostMode.stop": "توقف", + "planar.lostMode.hold": "نگه‌داشتن آخرین موقعیت", + "planar.heldFrames": "فریم‌های نگه‌داشته در آخرین موقعیت:", + "planar.stripLegend": "اطمینان در هر فریم: سبز خوب، کهربایی متوسط، قرمز ضعیف؛ خاکستری در آخرین موقعیت نگه داشته شده؛ خطی در بالا با پرسپکتیو برازش شده", + "vfxlink.live": "زنده از FormVFX", + "vfxlink.render": "رندر و جایگزینی", + "vfxlink.rendering": "در حال رندر از FormVFX", + "vfxlink.replaced": "رندر و جایگزین شد", + "vfxlink.failed": "رندر و جایگزینی ناموفق بود", + "vfxlink.unreadable": "آن فایل .fvxlink خوانده نشد", + "pin.folded": "آن گوشه نمی‌تواند آنجا برود: چهار گوشه تا می‌خورند یا از هم می‌گذرند" } diff --git a/frontend/public/locales/he.json b/frontend/public/locales/he.json index 2ddde2f5..cc2f23b6 100644 --- a/frontend/public/locales/he.json +++ b/frontend/public/locales/he.json @@ -1962,5 +1962,24 @@ "media.timelines": "צירי זמן: הניחו ציר זמן אחר של הפרויקט הזה על הציר הזה כקליפ אחד, בראש הניגון", "save.sync": "סנכרון", "save.sync.hint": "חבילת הפרויקט נשמרת בכל שמירה לתיקייה שלקוח הסנכרון שלך נושא; formcut לא מעלה דבר.", - "save.syncfolder": "תיקיית סנכרון" + "save.syncfolder": "תיקיית סנכרון", + "pin.edit": "עריכת פינות", + "pin.editHint": "מציג את ארבע פינות ההצמדה בתצוגה המקדימה כדי להזיז אחת מהן בפריים הזה", + "pin.gripHint": "גררו כדי להזיז אותה בפריים הזה; לחיצה כפולה מחזירה אותה", + "pin.corner.tl": "פינה שמאלית עליונה", + "pin.corner.tr": "פינה ימנית עליונה", + "pin.corner.br": "פינה ימנית תחתונה", + "pin.corner.bl": "פינה שמאלית תחתונה", + "planar.lostMode": "כשהמעקב אובד", + "planar.lostMode.stop": "עצירה", + "planar.lostMode.hold": "החזקת המיקום האחרון", + "planar.heldFrames": "פריימים שהוחזקו במיקום האחרון:", + "planar.stripLegend": "ביטחון בכל פריים: ירוק טוב, ענבר בינוני, אדום חלש; אפור הוחזק במיקום האחרון; קו למעלה הותאם בפרספקטיבה", + "vfxlink.live": "חי מ-FormVFX", + "vfxlink.render": "רינדור והחלפה", + "vfxlink.rendering": "מרנדר מ-FormVFX", + "vfxlink.replaced": "רונדר והוחלף", + "vfxlink.failed": "הרינדור וההחלפה נכשלו", + "vfxlink.unreadable": "לא ניתן היה לקרוא את קובץ ה-.fvxlink", + "pin.folded": "הפינה הזו לא יכולה להיות שם: ארבע הפינות יתקפלו או יחצו זו את זו" } diff --git a/frontend/public/locales/hr.json b/frontend/public/locales/hr.json index 19975677..18b6fb6f 100644 --- a/frontend/public/locales/hr.json +++ b/frontend/public/locales/hr.json @@ -1962,5 +1962,24 @@ "media.timelines": "Vremenske crte: postavite drugu vremensku crtu ovog projekta na ovu kao jedan isječak, na glavi reprodukcije", "save.sync": "Sinkronizacija", "save.sync.hint": "Paket ovog projekta pri svakom spremanju odlazi u mapu koju nosi tvoj vlastiti klijent za sinkronizaciju; formcut ništa ne prenosi.", - "save.syncfolder": "Mapa za sinkronizaciju" + "save.syncfolder": "Mapa za sinkronizaciju", + "pin.edit": "Uredi kutove", + "pin.editHint": "Prikazuje četiri kuta pribadače u pregledu kako biste jedan pomaknuli u ovom kadru", + "pin.gripHint": "Povucite da ga pomaknete u ovom kadru; dvostruki klik ga vraća", + "pin.corner.tl": "Gornji lijevi kut", + "pin.corner.tr": "Gornji desni kut", + "pin.corner.br": "Donji desni kut", + "pin.corner.bl": "Donji lijevi kut", + "planar.lostMode": "Kad se praćenje izgubi", + "planar.lostMode.stop": "Zaustavi", + "planar.lostMode.hold": "Zadrži zadnji položaj", + "planar.heldFrames": "Kadrovi zadržani na zadnjem položaju:", + "planar.stripLegend": "Pouzdanost po kadru: zeleno dobra, jantarno srednja, crveno slaba; sivo zadržano na zadnjem položaju; crta pri vrhu prilagođeno u perspektivi", + "vfxlink.live": "Uživo iz FormVFX-a", + "vfxlink.render": "Renderiraj i zamijeni", + "vfxlink.rendering": "Renderiranje iz FormVFX-a", + "vfxlink.replaced": "Renderirano i zamijenjeno", + "vfxlink.failed": "Renderiranje i zamjena nisu uspjeli", + "vfxlink.unreadable": "Tu datoteku .fvxlink nije moguće pročitati", + "pin.folded": "Taj kut ne može ići tamo: četiri bi se kuta presavila ili prekrižila" } diff --git a/frontend/src/engine/media.ts b/frontend/src/engine/media.ts index 91de8710..86a48fbb 100644 --- a/frontend/src/engine/media.ts +++ b/frontend/src/engine/media.ts @@ -23,6 +23,11 @@ export interface MediaItem { chroma?: string; /** The camera Log the file names in its metadata, offered in the Color section, never applied unasked. */ inputColourSuggestion?: InputColour; + /** A FormVFX live comp (vfx_link.py): its frames come from FormVFX while it runs; source is "formvfx-link". */ + link?: { project?: string | null; comp?: { id?: unknown; name?: string | null } }; + source?: string; + /** A movie rendered from a live comp names the item it was rendered from. */ + renderedFrom?: string; } type BinListener = (items: MediaItem[], added?: MediaItem) => void; diff --git a/frontend/src/engine/pin-edit.ts b/frontend/src/engine/pin-edit.ts new file mode 100644 index 00000000..2e438937 --- /dev/null +++ b/frontend/src/engine/pin-edit.ts @@ -0,0 +1,125 @@ +// Hand edits of an applied corner pin: one corner moved on one frame. The engine's twin is backend/app/pin_edit.py +// (project.edit's clip.pin-corner); tests/test_pin_edit.py runs both and compares them, so keep them in step. +// A pin is four fixed corners or a track of samples timed in the clip's own seconds. A moved corner is written into the +// sample on that frame, or a new sample there when none is within half a frame, so the frames either side keep their +// tracked corners. `edits` keeps the value each moved corner replaced, so it can be reset. + +export interface PinEdit { t?: number; corner: number; was: number[] } +export interface EditablePin { points: number[][]; times?: number[]; edits?: PinEdit[]; mesh?: unknown; [key: string]: unknown } + +const REACH = 4; +const FOLDED = "the four corners would fold or cross there; move this corner less far"; +const round6 = (v: number) => Math.round(v * 1e6) / 1e6; + +function check(pin: EditablePin | null | undefined, corner: number): EditablePin { + if (!pin || !Array.isArray(pin.points)) throw new Error("that clip has no corner pin: apply a track as a corner pin first"); + if (pin.mesh) throw new Error("a mesh pin is shaped in the Track workspace, not by its four corners"); + if (!Number.isInteger(corner) || corner < 0 || corner > 3) throw new Error("corner is 0 (top left), 1 (top right), 2 (bottom right) or 3 (bottom left)"); + return pin; +} + +/** Whether four corners in order around make a convex quadrilateral, the only kind a corner pin can draw. */ +function convex(flat: number[]): boolean { + const signs = new Set(); + for (let k = 0; k < 4; k++) { + const [ax, ay] = [flat[2 * k], flat[2 * k + 1]], [bx, by] = [flat[(2 * k + 2) % 8], flat[(2 * k + 3) % 8]], [cx, cy] = [flat[(2 * k + 4) % 8], flat[(2 * k + 5) % 8]]; + const cross = (bx - ax) * (cy - by) - (by - ay) * (cx - bx); + if (Math.abs(cross) < 1e-9) return false; + signs.add(cross > 0); + } + return signs.size === 1; +} + +function point(x: number, y: number): [number, number] { + if (!Number.isFinite(x) || !Number.isFinite(y)) throw new Error("a corner's x and y are finite numbers"); + if (x < -REACH || x > 1 + REACH || y < -REACH || y > 1 + REACH) throw new Error(`a corner stays within ${REACH} canvas widths of the canvas`); + return [round6(x), round6(y)]; +} + +/** The pin's corners at a local time, as the renderer reads them (renderer.pin_at): eight numbers, or null. */ +export function pinCornersAt(pin: EditablePin, local: number): number[] | null { + const { points, times } = pin; + if (!times || !times.length) return points.length === 4 ? points.flatMap((p) => [p[0], p[1]]) : null; + if (times.length !== points.length) return null; + if (local <= times[0]) return [...points[0]]; + if (local >= times[times.length - 1]) return [...points[points.length - 1]]; + let i = 0; + while (i + 1 < times.length && times[i + 1] <= local) i++; + const t0 = times[i], t1 = times[i + 1], f = t1 > t0 ? (local - t0) / (t1 - t0) : 0; + return points[i].map((a, k) => a + (points[i + 1][k] - a) * f); +} + +function sample(pin: EditablePin, local: number, fps: number, insert: boolean): { out: EditablePin; index: number | null } { + const out = structuredClone(pin) as EditablePin; + const times = out.times!; + const reach = 0.5 / Math.max(1e-6, fps) + 1e-9; + let nearest: number | null = null; + times.forEach((t, i) => { if (nearest === null || Math.abs(t - local) < Math.abs(times[nearest] - local)) nearest = i; }); + if (nearest !== null && Math.abs(times[nearest] - local) <= reach) return { out, index: nearest }; + if (!insert) return { out, index: null }; + const corners = pinCornersAt(pin, local); + if (!corners) throw new Error("that clip's corner pin cannot be read at that time"); + let at = 0; + while (at < times.length && times[at] < local) at++; + out.times = [...times.slice(0, at), round6(local), ...times.slice(at)]; + out.points = [...out.points.slice(0, at), corners.map(round6), ...out.points.slice(at)]; + return { out, index: at }; +} + +/** The pin with one corner at (x, y), canvas fractions, on the frame at local seconds; the pin given is not changed. */ +export function editPinCorner(pin: EditablePin | null | undefined, local: number, corner: number, x: number, y: number, fps: number): EditablePin { + const base = check(pin, corner); + const [px, py] = point(x, y); + const edits = [...(base.edits ?? [])]; + if (!base.times || !base.times.length) { + const out = structuredClone(base) as EditablePin; + const was = [...out.points[corner]]; + out.points[corner] = [px, py]; + if (!convex(out.points.flatMap((p) => [p[0], p[1]]))) throw new Error(FOLDED); + if (!edits.some((e) => e.corner === corner && e.t === undefined)) edits.push({ corner, was }); + return { ...out, edits }; + } + const { out, index } = sample(base, local, fps, true); + const flat = [...out.points[index!]]; + const was = [flat[2 * corner], flat[2 * corner + 1]]; + flat[2 * corner] = px; + flat[2 * corner + 1] = py; + if (!convex(flat)) throw new Error(FOLDED); + out.points[index!] = flat; + const t = round6(out.times![index!]); + if (!edits.some((e) => e.t === t && e.corner === corner)) edits.push({ t, corner, was }); + edits.sort((a, b) => (a.t ?? -1) - (b.t ?? -1) || a.corner - b.corner); + return { ...out, edits }; +} + +/** The pin with a hand-moved corner on the frame at local seconds put back where the track had it. */ +export function resetPinCorner(pin: EditablePin | null | undefined, local: number, corner: number, fps: number): EditablePin { + const base = check(pin, corner); + const edits = [...(base.edits ?? [])]; + let out: EditablePin, record: PinEdit | undefined; + if (!base.times || !base.times.length) { + record = edits.find((e) => e.corner === corner && e.t === undefined); + out = structuredClone(base) as EditablePin; + if (record) out.points[corner] = [...record.was]; + } else { + const found = sample(base, local, fps, false); + out = found.out; + const t = found.index !== null ? round6(out.times![found.index]) : null; + record = edits.find((e) => t !== null && e.t === t && e.corner === corner); + if (record && found.index !== null) { + const flat = [...out.points[found.index]]; + flat[2 * corner] = record.was[0]; + flat[2 * corner + 1] = record.was[1]; + out.points[found.index] = flat; + } + } + const rest = edits.filter((e) => e !== record); + delete out.edits; + return rest.length ? { ...out, edits: rest } : out; +} + +/** Whether a corner of the pin was moved by hand on the frame at local seconds. */ +export function pinCornerEdited(pin: EditablePin, local: number, corner: number, fps: number): boolean { + const reach = 0.5 / Math.max(1e-6, fps) + 1e-9; + return (pin.edits ?? []).some((e) => e.corner === corner && (e.t === undefined || Math.abs(e.t - local) <= reach)); +} diff --git a/frontend/src/engine/project.ts b/frontend/src/engine/project.ts index b1bcbd13..730d77cb 100644 --- a/frontend/src/engine/project.ts +++ b/frontend/src/engine/project.ts @@ -13,6 +13,7 @@ import { sourceDelta, sourceTime, shiftedCurve, retimedKeys } from "./timing"; import { CREATOR_COMMANDS, creatorCommand } from "./creator-commands"; import { cycleKeyframeInterp, removeKeyframeProp, upsertKeyframe } from "./keyframes"; import { apply, diff, deltaSize, type Delta } from "./json-delta"; +import { editPinCorner, resetPinCorner, type EditablePin } from "./pin-edit"; type DocumentSlice = Pick; const HISTORY_LIMIT = 200; @@ -394,6 +395,25 @@ export class ProjectEngine { this.emit("clips"); break; } + case "clip.pinCorner": { + // a hand edit of an applied corner pin: one corner on the frame at t (the clip's own seconds), or reset; + // the engine's project.edit does the same as clip.pin-corner (pin-edit.ts and pin_edit.py are twins) + const p = payload as { clipId: string; t: number; corner: number; x?: number; y?: number; reset?: boolean }; + const found = this.findClip(p.clipId); + if (!found?.clip.cornerPin) break; + let next: Clip["cornerPin"]; + try { + const pin = found.clip.cornerPin as EditablePin; + next = (p.reset ? resetPinCorner(pin, p.t, p.corner, s.fps) : editPinCorner(pin, p.t, p.corner, p.x ?? NaN, p.y ?? NaN, s.fps)) as Clip["cornerPin"]; + } catch { + break; // the interface only sends edits it has checked; a refused one changes nothing + } + this.pushHistory(); + found.clip.cornerPin = next; + s.saved = false; + this.emit("clips"); + break; + } case "clip.planar": { // the Track workspace's layers on the clip, kept with the project (the tracks themselves are the engine's) const p = payload as { clipId: string; planar: import("./types").ClipPlanar | null }; @@ -1346,6 +1366,21 @@ export class ProjectEngine { this.emit("clips"); break; } + case "media.replace": { + // the clips on one media item put on another, one undo step (Render and replace of a FormVFX live comp) + const map = payload as Record; + const uses = s.timelines.some((timeline) => timeline.tracks.some((track) => track.clips.some((clip) => clip.mediaId && map[clip.mediaId]))); + if (!uses) break; + this.pushHistory(); + for (const timeline of s.timelines) { + for (const track of timeline.tracks) { + for (const clip of track.clips) if (clip.mediaId && map[clip.mediaId]) clip.mediaId = map[clip.mediaId]; + } + } + s.saved = false; + this.emit("clips"); + break; + } case "project.saved": { const record = typeof payload === "string" ? { id: payload, revision: s.revision, unchanged: true } : payload as { id: string; revision: number; unchanged: boolean }; s.projectId = record.id; diff --git a/frontend/src/engine/types.ts b/frontend/src/engine/types.ts index 769d1481..f15fbf68 100644 --- a/frontend/src/engine/types.ts +++ b/frontend/src/engine/types.ts @@ -173,7 +173,8 @@ export interface Clip { planar?: ClipPlanar; // a corner pin: the clip's image corners onto four canvas points (fractions), fixed or as a track of samples timed in // the clip's local seconds (from a planar layer's surface, P3); its place, size and turn give way to it - cornerPin?: { points: number[][]; times?: number[]; motionBlur?: MotionBlur; match?: { light?: boolean; grain?: boolean; blur?: boolean }; mesh?: { cols: number; rows: number; times: number[]; points: number[][][] } }; + // edits: corners moved by hand on a frame (clip.pinCorner), each with the tracked value it replaced, for a reset + cornerPin?: { points: number[][]; times?: number[]; edits?: Array<{ t?: number; corner: number; was: number[] }>; motionBlur?: MotionBlur; match?: { light?: boolean; grain?: boolean; blur?: boolean }; mesh?: { cols: number; rows: number; times: number[]; points: number[][][] } }; // the clip's own planar layers as its matte (Mocha's Apply Matte, P3): their shapes carried by their tracks planarMatte?: { layers: string[]; feather: number; invert: boolean; motionBlur?: MotionBlur }; planarStabilize?: { layer: string }; diff --git a/frontend/src/i18n/de.json b/frontend/src/i18n/de.json index 93ce3175..2c478b5e 100644 --- a/frontend/src/i18n/de.json +++ b/frontend/src/i18n/de.json @@ -1551,5 +1551,24 @@ "media.timelines": "Zeitleisten: eine andere Zeitleiste dieses Projekts als einen Clip auf diese setzen, an der Abspielposition", "save.sync": "Synchronisieren", "save.sync.hint": "Das Paket dieses Projekts folgt jedem Speichern in einen Ordner, den dein eigener Sync-Client trägt; formcut lädt nichts hoch.", - "save.syncfolder": "Sync-Ordner" + "save.syncfolder": "Sync-Ordner", + "pin.edit": "Ecken bearbeiten", + "pin.editHint": "Zeigt die vier Eckpunkte in der Vorschau, um einen in diesem Bild zu verschieben", + "pin.gripHint": "Ziehen, um ihn in diesem Bild zu verschieben; Doppelklick setzt ihn zurück", + "pin.corner.tl": "Ecke oben links", + "pin.corner.tr": "Ecke oben rechts", + "pin.corner.br": "Ecke unten rechts", + "pin.corner.bl": "Ecke unten links", + "planar.lostMode": "Wenn das Tracking verloren geht", + "planar.lostMode.stop": "Anhalten", + "planar.lostMode.hold": "Letzte Position halten", + "planar.heldFrames": "Bilder an der letzten Position gehalten:", + "planar.stripLegend": "Zuverlässigkeit je Bild: grün gut, gelb mittel, rot schwach; grau an der letzten Position gehalten; eine Linie oben in Perspektive angepasst", + "vfxlink.live": "Live aus FormVFX", + "vfxlink.render": "Rendern und ersetzen", + "vfxlink.rendering": "Wird aus FormVFX gerendert", + "vfxlink.replaced": "Gerendert und ersetzt", + "vfxlink.failed": "Rendern und Ersetzen fehlgeschlagen", + "vfxlink.unreadable": "Diese .fvxlink-Datei konnte nicht gelesen werden", + "pin.folded": "Diese Ecke kann nicht dorthin: Die vier Ecken würden sich falten oder kreuzen" } diff --git a/frontend/src/i18n/en.json b/frontend/src/i18n/en.json index 873a327c..2821ee39 100644 --- a/frontend/src/i18n/en.json +++ b/frontend/src/i18n/en.json @@ -1551,5 +1551,24 @@ "media.timelines": "Timelines: place another timeline of this project on this one as a single clip, at the playhead", "save.sync": "Sync", "save.sync.hint": "This project's package follows every save into a folder your own sync client carries; nothing is uploaded by formcut.", - "save.syncfolder": "Sync folder" + "save.syncfolder": "Sync folder", + "pin.edit": "Edit corners", + "pin.editHint": "Show the pin's four corners on the preview to move one on this frame", + "pin.gripHint": "Drag to move it on this frame; double-click to put it back", + "pin.corner.tl": "Top left corner", + "pin.corner.tr": "Top right corner", + "pin.corner.br": "Bottom right corner", + "pin.corner.bl": "Bottom left corner", + "planar.lostMode": "When the track is lost", + "planar.lostMode.stop": "Stop", + "planar.lostMode.hold": "Hold last position", + "planar.heldFrames": "Frames held at the last position:", + "planar.stripLegend": "Confidence on each frame: green good, amber fair, red poor; grey held at the last position; a line along the top fitted in perspective", + "vfxlink.live": "Live from FormVFX", + "vfxlink.render": "Render and replace", + "vfxlink.rendering": "Rendering from FormVFX", + "vfxlink.replaced": "Rendered and replaced", + "vfxlink.failed": "Render and replace failed", + "vfxlink.unreadable": "That .fvxlink could not be read", + "pin.folded": "That corner cannot go there: the four corners would fold or cross" } diff --git a/frontend/src/i18n/es.json b/frontend/src/i18n/es.json index dd6b69dd..d8e5fabb 100644 --- a/frontend/src/i18n/es.json +++ b/frontend/src/i18n/es.json @@ -1551,5 +1551,24 @@ "media.timelines": "Líneas de tiempo: coloca otra línea de tiempo de este proyecto sobre esta como un solo clip, en el cabezal", "save.sync": "Sync", "save.sync.hint": "This project's package follows every save into a folder your own sync client carries; nothing is uploaded by formcut.", - "save.syncfolder": "Sync folder" + "save.syncfolder": "Sync folder", + "pin.edit": "Editar esquinas", + "pin.editHint": "Muestra las cuatro esquinas del anclaje en la vista previa para mover una en este fotograma", + "pin.gripHint": "Arrastra para moverla en este fotograma; doble clic para devolverla", + "pin.corner.tl": "Esquina superior izquierda", + "pin.corner.tr": "Esquina superior derecha", + "pin.corner.br": "Esquina inferior derecha", + "pin.corner.bl": "Esquina inferior izquierda", + "planar.lostMode": "Si se pierde el seguimiento", + "planar.lostMode.stop": "Detener", + "planar.lostMode.hold": "Mantener la última posición", + "planar.heldFrames": "Fotogramas mantenidos en la última posición:", + "planar.stripLegend": "Confianza en cada fotograma: verde buena, ámbar regular, rojo baja; gris mantenido en la última posición; una línea arriba, ajustado en perspectiva", + "vfxlink.live": "En vivo desde FormVFX", + "vfxlink.render": "Renderizar y reemplazar", + "vfxlink.rendering": "Renderizando desde FormVFX", + "vfxlink.replaced": "Renderizado y reemplazado", + "vfxlink.failed": "Falló renderizar y reemplazar", + "vfxlink.unreadable": "No se pudo leer ese .fvxlink", + "pin.folded": "Esa esquina no puede ir ahí: las cuatro esquinas se plegarían o se cruzarían" } diff --git a/frontend/src/i18n/language-pack.ts b/frontend/src/i18n/language-pack.ts index a3d6da28..78b3674c 100644 --- a/frontend/src/i18n/language-pack.ts +++ b/frontend/src/i18n/language-pack.ts @@ -1605,7 +1605,25 @@ The file says it was shot in {name}.|Le fichier indique un tournage en {name}.|I Use it|L'utiliser|Usalo|使用する|사용|Usar|Использовать|Kullan|使用|使用 LUT interpolation|Interpolation de la LUT|Interpolazione LUT|LUT 補間|LUT 보간|Interpolação de LUT|Интерполяция LUT|LUT enterpolasyonu|LUT 插值|LUT 插值 Trilinear|Trilinéaire|Trilineare|トライリニア|삼선형|Trilinear|Трилинейная|Üç doğrusal|三线性|三線性 -Tetrahedral|Tétraédrique|Tetraedrica|テトラヘドラル|사면체|Tetraédrica|Тетраэдрическая|Dört yüzlü|四面体|四面體`; +Tetrahedral|Tétraédrique|Tetraedrica|テトラヘドラル|사면체|Tetraédrica|Тетраэдрическая|Dört yüzlü|四面体|四面體 +Edit corners|Modifier les coins|Modifica angoli|角を編集|모서리 편집|Editar cantos|Изменить углы|Köşeleri düzenle|编辑角点|編輯角點 +Show the pin's four corners on the preview to move one on this frame|Affiche les quatre coins de l'épinglage dans l'aperçu pour en déplacer un sur cette image|Mostra i quattro angoli del vincolo nell'anteprima per spostarne uno in questo fotogramma|プレビューにピンの4つの角を表示し、このフレームで1つを動かします|미리보기에 핀의 네 모서리를 표시해 이 프레임에서 하나를 옮깁니다|Mostra os quatro cantos do alfinete na prévia para mover um neste quadro|Показывает четыре угла привязки в просмотре, чтобы сдвинуть один на этом кадре|Bu karede birini taşımak için iğnenin dört köşesini önizlemede gösterir|在预览中显示四个角点,以便在此帧移动其中一个|在預覽中顯示四個角點,以便在此影格移動其中一個 +Drag to move it on this frame; double-click to put it back|Faites glisser pour le déplacer sur cette image ; double-cliquez pour le remettre|Trascina per spostarlo in questo fotogramma; doppio clic per riportarlo|ドラッグでこのフレームで移動、ダブルクリックで元に戻します|드래그하면 이 프레임에서 옮기고, 두 번 클릭하면 되돌립니다|Arraste para movê-lo neste quadro; clique duas vezes para devolvê-lo|Перетащите, чтобы сдвинуть его на этом кадре; двойной щелчок возвращает его|Bu karede taşımak için sürükleyin; geri koymak için çift tıklayın|拖动可在此帧移动;双击可恢复|拖曳可在此影格移動;按兩下可還原 +Top left corner|Coin supérieur gauche|Angolo in alto a sinistra|左上の角|왼쪽 위 모서리|Canto superior esquerdo|Левый верхний угол|Sol üst köşe|左上角|左上角 +Top right corner|Coin supérieur droit|Angolo in alto a destra|右上の角|오른쪽 위 모서리|Canto superior direito|Правый верхний угол|Sağ üst köşe|右上角|右上角 +Bottom right corner|Coin inférieur droit|Angolo in basso a destra|右下の角|오른쪽 아래 모서리|Canto inferior direito|Правый нижний угол|Sağ alt köşe|右下角|右下角 +Bottom left corner|Coin inférieur gauche|Angolo in basso a sinistra|左下の角|왼쪽 아래 모서리|Canto inferior esquerdo|Левый нижний угол|Sol alt köşe|左下角|左下角 +When the track is lost|Quand le suivi est perdu|Quando il tracciamento si perde|トラックを見失ったとき|트래킹을 잃으면|Quando o rastreamento se perde|Если трекинг потерян|İzleme kaybolduğunda|跟踪丢失时|追蹤遺失時 +Hold last position|Garder la dernière position|Mantieni l'ultima posizione|最後の位置を保持|마지막 위치 유지|Manter a última posição|Держать последнее положение|Son konumu koru|保持最后位置|保持最後位置 +Frames held at the last position:|Images gardées à la dernière position :|Fotogrammi mantenuti nell'ultima posizione:|最後の位置で保持したフレーム:|마지막 위치로 유지한 프레임:|Quadros mantidos na última posição:|Кадры, удержанные в последнем положении:|Son konumda tutulan kareler:|保持在最后位置的帧:|保持在最後位置的影格: +Confidence on each frame: green good, amber fair, red poor; grey held at the last position; a line along the top fitted in perspective|Confiance par image : vert bonne, ambre moyenne, rouge faible ; gris gardé à la dernière position ; une ligne en haut ajusté en perspective|Affidabilità per fotogramma: verde buona, ambra media, rosso scarsa; grigio mantenuto nell'ultima posizione; una linea in alto adattato in prospettiva|各フレームの信頼度: 緑は良好、琥珀は中程度、赤は低い。灰色は最後の位置で保持。上端の線は透視で当てはめ|프레임별 신뢰도: 초록은 좋음, 호박색은 보통, 빨강은 낮음. 회색은 마지막 위치로 유지, 위쪽 선은 원근으로 맞춤|Confiança em cada quadro: verde boa, âmbar média, vermelho fraca; cinza mantido na última posição; uma linha no topo ajustado em perspectiva|Надёжность на каждом кадре: зелёный хорошая, янтарный средняя, красный низкая; серый удержан в последнем положении; линия сверху подогнано в перспективе|Her karede güven: yeşil iyi, kehribar orta, kırmızı zayıf; gri son konumda tutuldu; üstteki çizgi perspektifle uyduruldu|每帧的置信度:绿色良好,琥珀色一般,红色较差;灰色为保持在最后位置;顶部线条为透视拟合|每個影格的信賴度:綠色良好,琥珀色普通,紅色較差;灰色為保持在最後位置;頂部線條為透視擬合 +Live from FormVFX|En direct depuis FormVFX|Dal vivo da FormVFX|FormVFX からライブ|FormVFX 라이브|Ao vivo do FormVFX|Вживую из FormVFX|FormVFX'ten canlı|来自 FormVFX 的实时画面|來自 FormVFX 的即時畫面 +Render and replace|Rendre et remplacer|Renderizza e sostituisci|レンダリングして置き換え|렌더링 후 교체|Renderizar e substituir|Отрисовать и заменить|İşle ve değiştir|渲染并替换|算圖並取代 +Rendering from FormVFX|Rendu depuis FormVFX|Rendering da FormVFX|FormVFX からレンダリング中|FormVFX에서 렌더링 중|Renderizando do FormVFX|Отрисовка из FormVFX|FormVFX'ten işleniyor|正在从 FormVFX 渲染|正在從 FormVFX 算圖 +Rendered and replaced|Rendu et remplacé|Renderizzato e sostituito|レンダリングして置き換えました|렌더링 후 교체했습니다|Renderizado e substituído|Отрисовано и заменено|İşlendi ve değiştirildi|已渲染并替换|已算圖並取代 +Render and replace failed|Échec du rendu et du remplacement|Rendering e sostituzione non riusciti|レンダリングと置き換えに失敗しました|렌더링 후 교체에 실패했습니다|Falha ao renderizar e substituir|Не удалось отрисовать и заменить|İşleme ve değiştirme başarısız|渲染并替换失败|算圖並取代失敗 +That .fvxlink could not be read|Impossible de lire ce .fvxlink|Impossibile leggere quel .fvxlink|その .fvxlink を読み込めませんでした|해당 .fvxlink를 읽을 수 없습니다|Não foi possível ler esse .fvxlink|Не удалось прочитать этот .fvxlink|Bu .fvxlink okunamadı|无法读取该 .fvxlink|無法讀取該 .fvxlink +That corner cannot go there: the four corners would fold or cross|Ce coin ne peut pas aller là : les quatre coins se replieraient ou se croiseraient|Quell'angolo non può andare lì: i quattro angoli si piegherebbero o si incrocerebbero|その角はそこに置けません。4つの角が折れるか交差します|그 모서리는 거기에 둘 수 없습니다. 네 모서리가 접히거나 교차합니다|Esse canto não pode ir ali: os quatro cantos se dobrariam ou se cruzariam|Этот угол нельзя поставить туда: четыре угла сложатся или пересекутся|O köşe oraya gidemez: dört köşe katlanır ya da kesişir|该角点不能放在那里:四个角点会折叠或交叉|該角點不能放在那裡:四個角點會折疊或交叉`; export const PHRASES: Record> = Object.fromEntries(codes.map(c => [c, {}])); for (const row of rows.split("\n")) { const [source, ...values] = row.split("|"); diff --git a/frontend/src/styles/app.css b/frontend/src/styles/app.css index ecf6d98b..654f9595 100644 --- a/frontend/src/styles/app.css +++ b/frontend/src/styles/app.css @@ -453,6 +453,7 @@ input[type="range"], input[type="checkbox"], input[type="radio"], input[type="co border-radius: var(--radius-s); color: var(--ink-soft); } +.tool-chip[hidden] { display: none; } .tool-chip:hover { background: var(--control); color: var(--ink); } .tool-chip[disabled] { color: var(--ink-faint); cursor: default; } .tool-chip[disabled]:hover { background: none; } @@ -1203,11 +1204,11 @@ input[type="range"], input[type="checkbox"], input[type="radio"], input[type="co .proxy-badge[data-state="ready"] { color: var(--cue); } .proxy-badge[data-state="failed"], .proxy-badge[data-state="stale"] { color: var(--warn, #e0806a); } .proxy-badge[hidden] { display: none; } -.bin-proxy { position: absolute; top: 32px; left: 4px; display: inline-grid; place-items: center; width: 24px; height: 24px; padding: 0; border: 0; border-radius: var(--radius-s); background: var(--veil); color: var(--ink); opacity: 0; cursor: pointer; transition: opacity 0.15s ease; } -.bin-card:hover .bin-proxy, .bin-proxy:focus-visible { opacity: 1; } -.bin-proxy:disabled { cursor: default; color: var(--ink-faint); } -.bin-proxy svg { width: 13px; height: 13px; } -@media (hover: none) { .bin-proxy { opacity: 1; } } +.bin-proxy, .bin-vfx-render { position: absolute; top: 32px; left: 4px; display: inline-grid; place-items: center; width: 24px; height: 24px; padding: 0; border: 0; border-radius: var(--radius-s); background: var(--veil); color: var(--ink); opacity: 0; cursor: pointer; transition: opacity 0.15s ease; } +.bin-card:hover .bin-proxy, .bin-proxy:focus-visible, .bin-card:hover .bin-vfx-render, .bin-vfx-render:focus-visible { opacity: 1; } +.bin-proxy:disabled, .bin-vfx-render:disabled { cursor: default; color: var(--ink-faint); } +.bin-proxy svg, .bin-vfx-render svg { width: 13px; height: 13px; } +@media (hover: none) { .bin-proxy, .bin-vfx-render { opacity: 1; } } /* Right-to-left support. diff --git a/frontend/src/styles/creator.css b/frontend/src/styles/creator.css index 3f901acd..4fab3632 100644 --- a/frontend/src/styles/creator.css +++ b/frontend/src/styles/creator.css @@ -98,10 +98,20 @@ .preview-crop { position: absolute; transform: translate(-50%, -50%); border: 1px dashed var(--ink-faint); z-index: var(--z-handles); } .preview-crop[hidden] { display: none; } .crop-window { position: absolute; border: 1.5px solid var(--cue); outline: 4000px solid var(--veil); pointer-events: none; } +/* hand edits of an applied corner pin (pin-corners.ts): an outline and four grips over the stage, absolutely placed so + showing them moves nothing; a corner moved by hand on this frame is ringed in the accent's ink */ +.preview-pin { position: absolute; inset: 0; z-index: var(--z-handles); pointer-events: none; } +.preview-pin[hidden] { display: none; } +.pin-outline { position: absolute; inset: 0; width: 100%; height: 100%; overflow: visible; } +.pin-outline polygon { fill: none; stroke: var(--cue); stroke-width: 1.5px; vector-effect: non-scaling-stroke; } +.pin-grip { position: absolute; width: 14px; height: 14px; padding: 0; background: var(--on-cue); border: 2px solid var(--cue); border-radius: 50%; transform: translate(-50%, -50%); pointer-events: auto; cursor: move; touch-action: none; } +.pin-grip.is-edited { background: var(--cue); box-shadow: 0 0 0 2px var(--on-cue); } +.pin-grip:disabled { cursor: not-allowed; opacity: 0.5; } .crop-grip { position: absolute; width: 12px; height: 12px; padding: 0; background: var(--cue); border: 1px solid var(--on-cue); border-radius: 50%; transform: translate(-50%, -50%); } .grip-left, .grip-right { cursor: ew-resize; } .grip-top, .grip-bottom { cursor: ns-resize; } .stage[data-crop="on"] .preview-selection { display: none; } +.stage[data-pin="on"] .preview-selection { display: none; } .preview-guides { position: absolute; inset: 0; pointer-events: none; z-index: var(--z-handles); } .preview-guides[hidden] { display: none; } .guide-line { position: absolute; background: var(--guide); } diff --git a/frontend/src/ui/inspector-pane.ts b/frontend/src/ui/inspector-pane.ts index a4936f65..0786c8dc 100644 --- a/frontend/src/ui/inspector-pane.ts +++ b/frontend/src/ui/inspector-pane.ts @@ -59,6 +59,7 @@ export function buildInspectorPane(engine: ProjectEngine, bin: MediaBin): HTMLEl const sel = selectedTransform(engine); const selected = engine.snapshot.selectedClipId ? engine.findClip(engine.snapshot.selectedClipId)?.clip : undefined; const pinned = !!selected?.cornerPin; + const pinEditing = document.querySelector(".stage")?.dataset.pin === "on"; const matted = !!selected?.planarMatte; const heldOut = !!selected?.key?.holdout?.length; const el = document.createElement("section"); @@ -224,6 +225,7 @@ export function buildInspectorPane(engine: ProjectEngine, bin: MediaBin): HTMLEl ${matted ? `` : ""} ${matted ? `` : ""} ${pinned ? `` : ""} + ${selected?.planarStabilize || selected?.planarReorient || selected?.lens ? `` : ""} ${selected?.lens ? `` : ""} ${pinned ? `` : ""} diff --git a/frontend/src/ui/media-pane.ts b/frontend/src/ui/media-pane.ts index 3df6d52e..5b6d0f58 100644 --- a/frontend/src/ui/media-pane.ts +++ b/frontend/src/ui/media-pane.ts @@ -21,6 +21,7 @@ import { openUpscale } from "./upscale-dialog"; import { openTikTok } from "./tiktok-dialog"; import { openInstagram } from "./instagram"; import { openCloudBrowser } from "./cloud"; +import { importLinkFile, importLinkPaths, isLinkFile, renderAndReplace } from "./vfx-link"; import { compact } from "./compact"; import { buildDevicesView } from "./devices-view"; import { buildBrowserView } from "./browser-view"; @@ -228,7 +229,7 @@ export function buildMediaPane(bin: MediaBin, engine: ProjectEngine): HTMLElemen + accept="video/*,audio/*,image/*,.fvxlink" />

-
+
${t("planar.dopeSheet")}
${t("planar.curves")}
@@ -260,6 +267,9 @@ export function openPlanarWorkspace(engine: ProjectEngine, clipId: string): void // ---- drawing the frame and its overlays ---- function render(): void { if (!media) return; + // Perspective left unset follows the layer's shapes (four corners: on), so its box is kept in step as they change + const perspective = $("settings").querySelector('[data-key="perspective"]'), shown = layer(); + if (perspective && shown && shown.settings.perspective == null && perspective.checked !== fourCornered(shown)) perspective.checked = fourCornered(shown); const { width: W, height: H } = media; svg.setAttribute("viewBox", `0 0 ${W} ${H}`); let out = ""; @@ -389,6 +399,13 @@ export function openPlanarWorkspace(engine: ProjectEngine, clipId: string): void g.fillStyle = c >= 0.6 ? "#3fb950" : c >= 0.3 ? "#ffae2b" : "#ff475a"; g.fillRect(((i - first) / span) * canvas.width, 0, Math.max(1, canvas.width / span), canvas.height); } + // held frames (Hold, the plane lost) in the faint ink across the whole bar; frames refitted in perspective as a + // line in the accent along its top + const width = Math.max(1, canvas.width / span); + g.fillStyle = token("--ink-faint"); + for (const i of tr.held) g.fillRect(((i - first) / span) * canvas.width, 0, width, canvas.height); + g.fillStyle = token("--cue"); + for (const i of tr.promoted) g.fillRect(((i - first) / span) * canvas.width, 0, width, 2); } // ---- layers ---- @@ -507,7 +524,7 @@ export function openPlanarWorkspace(engine: ProjectEngine, clipId: string): void function paintSettings(): void { const l = layer(), box = $("settings"); if (!l) { box.innerHTML = ""; return; } - const s = { ...DEFAULTS, ...l.settings } as Record; + const s = { ...DEFAULTS, ...l.settings, perspective: l.settings.perspective ?? fourCornered(l) } as Record; const num = (key: string, step: number, min: number, max: number, autoable = false) => ``; box.innerHTML = `
${t("planar.trackSettings")}
${t("planar.link")}
@@ -518,6 +535,7 @@ export function openPlanarWorkspace(engine: ProjectEngine, clipId: string): void
${t("planar.minPixels")}${num("min_pixels", 1, 1, 100, true)}
${t("planar.smoothing")}${num("smoothing", 0.5, 0, 10)}
${t("planar.motionMode")}
+
${t("planar.lostMode")}
${t("planar.search")}${num("search_x", 1, 0, 2000, true)}${num("search_y", 1, 0, 2000, true)}
${t("planar.angle")}${num("angle", 1, 0, 90)}
${t("planar.zoom")}${num("zoom", 1, 0, 100)}
`; @@ -541,6 +559,14 @@ export function openPlanarWorkspace(engine: ProjectEngine, clipId: string): void return; } if (!l || !key) return; + if (key === "lost") { + // what the track does when the plane is lost changes no frame already tracked, so the track is kept + const rest = { ...l.settings }; + delete rest.lost; + l.settings = input.value === "hold" ? { ...rest, lost: "hold" } : rest; + changed = true; + return; + } if (!(await invalidate(l))) { paintSettings(); return; } const value = input.type === "checkbox" ? input.checked : input.type === "number" ? (input.value === "" ? null : Number(input.value)) : key === "screen" ? input.value || null : input.value; l.settings = { ...DEFAULTS, ...l.settings, [key]: value }; @@ -808,11 +834,13 @@ export function openPlanarWorkspace(engine: ProjectEngine, clipId: string): void async function loadTrack(l: PlanarLayer): Promise { const reply = await fetch(`/api/planar/track/${l.id}`); if (!reply.ok) { tracks.delete(l.id); return; } - const data = await reply.json() as { frames: number[]; matrices: number[][]; confidence: number[]; adjusted?: number[][] }; + const data = await reply.json() as { frames: number[]; matrices: number[][]; confidence: number[]; adjusted?: number[][]; held?: number[]; promoted?: number[] }; tracks.set(l.id, { frames: new Map(data.frames.map((f, i) => [f, data.matrices[i]])), confidence: new Map(data.frames.map((f, i) => [f, data.confidence[i]])), adjusted: new Map((data.adjusted ?? []).map((m, i) => [data.frames[i], m])), + held: new Set(data.held ?? []), + promoted: new Set(data.promoted ?? []), }); } const loadTracks = () => Promise.all(layers.map((l) => loadTrack(l))); @@ -849,6 +877,7 @@ export function openPlanarWorkspace(engine: ProjectEngine, clipId: string): void if (status.status === "error") say(status.error ?? t("planar.failed")); else if (status.status === "cancelled") say(`${t("planar.stopped")} ${frame}`); // its frames are kept else if (typeof status.result?.lost === "number") say(`${t("planar.lost")} ${status.result.lost}`); + else if (status.result?.held) say(`${t("planar.tracked")} ${status.result?.tracked ?? 0}. ${t("planar.heldFrames")} ${status.result.held}`); else say(`${t("planar.tracked")} ${status.result?.tracked ?? 0}`); if (typeof status.result?.to === "number") showFrame(status.result.to); break; diff --git a/frontend/src/ui/render-preview.ts b/frontend/src/ui/render-preview.ts index c98c0a38..813e1d85 100644 --- a/frontend/src/ui/render-preview.ts +++ b/frontend/src/ui/render-preview.ts @@ -1,5 +1,6 @@ import { text } from "../i18n/text"; import { previewManipulation } from "./preview-manipulation"; +import { pinCorners } from "./pin-corners"; import type { ProjectEngine } from "../engine/project"; import { rateLabel } from "../engine/rates"; import { formatTimecode } from "../engine/project"; @@ -240,6 +241,7 @@ export function buildPreviewPane(engine: ProjectEngine, bin: MediaBin): HTMLElem if (wrap) new ResizeObserver(() => sizeStage()).observe(wrap); sizeStage(); previewManipulation(stage, engine, bin); + pinCorners(stage, engine); invalidate(); return element; } diff --git a/frontend/src/ui/timeline-pane.ts b/frontend/src/ui/timeline-pane.ts index e93d6252..d47f9342 100644 --- a/frontend/src/ui/timeline-pane.ts +++ b/frontend/src/ui/timeline-pane.ts @@ -337,7 +337,7 @@ export function buildTimelinePane(engine: ProjectEngine, bin: MediaBin): HTMLEle start: Math.round(start * 10) / 10, duration: Math.max(item.duration, 0.5), mediaId: item.id, - filmstrip: item.kind === "video", + filmstrip: item.kind === "video" && !item.link, // a live comp has no file to strip until rendered }; engine.dispatch("clip.add", { trackIndex, clip }); }); diff --git a/frontend/src/ui/tracking.ts b/frontend/src/ui/tracking.ts index 72637513..f1ae3bbd 100644 --- a/frontend/src/ui/tracking.ts +++ b/frontend/src/ui/tracking.ts @@ -28,6 +28,25 @@ export function installTracking(root: HTMLElement, engine: ProjectEngine): void const id = engine.snapshot.selectedClipId; if (id) engine.dispatch("clip.cornerPin", { clipId: id, cornerPin: null }); }); + // Edit corners: the pin's four corners as grips on the preview, each movable on the current frame (pin-corners.ts). + // The inspector is built once, so the button is always mounted and shown only for a clip with a corner pin + const pinEdit = root.querySelector('[data-ref="pin-edit"]'); + const showPinEdit = () => { + const id = engine.snapshot.selectedClipId, pin = id ? engine.findClip(id)?.clip.cornerPin : undefined; + const hidden = !pin || !!pin.mesh; + if (pinEdit && pinEdit.hidden !== hidden) pinEdit.hidden = hidden; + }; + engine.subscribe((_state, event) => { if (event === "clips" || event === "clip-selection") showPinEdit(); }); + showPinEdit(); + pinEdit?.addEventListener("click", (event) => { + const stage = document.querySelector(".stage"), button = event.currentTarget as HTMLElement; + if (!stage) return; + const on = stage.dataset.pin !== "on"; + if (on) stage.dataset.pin = "on"; else delete stage.dataset.pin; + button.classList.toggle("is-on", on); + button.setAttribute("aria-pressed", String(on)); + stage.dispatchEvent(new CustomEvent("formcut:pin-mode")); + }); for (const button of root.querySelectorAll('[data-ref="pin-match"]')) { button.addEventListener("click", () => { const id = engine.snapshot.selectedClipId, pin = id ? engine.findClip(id)?.clip.cornerPin : undefined; diff --git a/frontend/src/ui/vfx-link.ts b/frontend/src/ui/vfx-link.ts new file mode 100644 index 00000000..8524bdcb --- /dev/null +++ b/frontend/src/ui/vfx-link.ts @@ -0,0 +1,39 @@ +// A FormVFX live comp as a clip (backend/app/vfx_link.py): a .fvxlink imported into the media bin plays its frames +// from FormVFX while FormVFX runs; Render and replace writes it to a normal movie and points the project's clips at +// that (media.replace, one undo step), so the project no longer needs FormVFX running. +import type { ProjectEngine } from "../engine/project"; +import type { MediaBin, MediaItem } from "../engine/media"; +import { api, waitJob } from "../engine/api"; +import { t } from "../i18n"; + +export const isLinkFile = (name: string): boolean => name.toLowerCase().endsWith(".fvxlink"); + +/** A .fvxlink chosen in the browser: its contents sent to the engine. */ +export async function importLinkFile(file: File, bin: MediaBin): Promise { + let link: unknown; + try { + link = JSON.parse(await file.text()); + } catch { + throw new Error(t("vfxlink.unreadable")); + } + await api("/api/vfx-link/import", { link, name: file.name }); + await bin.load(); +} + +/** .fvxlink files chosen in the system's own dialog: the engine reads each where it is. */ +export async function importLinkPaths(paths: string[], bin: MediaBin): Promise { + for (const path of paths) await api("/api/vfx-link/import", { path }); + await bin.load(); +} + +/** Render the live comp to a movie, then every clip on it uses the movie instead. */ +export async function renderAndReplace(item: MediaItem, engine: ProjectEngine, bin: MediaBin, say: (text: string) => void): Promise { + say(t("vfxlink.rendering")); + const started = await api<{ job_id: string }>(`/api/vfx-link/${item.id}/render`, {}); + const result = await waitJob(started.job_id, (text) => say(`${t("vfxlink.rendering")} ${text.replace(/^[^:]*:\s*/, "")}`)); + const made = result?.media as MediaItem | undefined; + if (!made?.id) throw new Error(t("vfxlink.failed")); + await bin.load(); + engine.dispatch("media.replace", { [item.id]: made.id }); + say(t("vfxlink.replaced")); +} diff --git a/frontend/tests/window/test_pin_link_controls.py b/frontend/tests/window/test_pin_link_controls.py new file mode 100644 index 00000000..595fb952 --- /dev/null +++ b/frontend/tests/window/test_pin_link_controls.py @@ -0,0 +1,209 @@ +"""The built window, driven as a person would, for 2.24.0's three controls, each read back from the page or the engine: + +- Edit corners on a clip with an applied corner pin shows its four corners on the preview; a corner dragged is marked + as moved by hand on that frame, and undo puts it back. Turning the grips on and off shifts no layout. +- The Track workspace's "When the track is lost" choice offers Stop (the default) and Hold last position. +- A FormVFX Live Link file in the bin says it is live, offers Render and replace instead of a proxy, and with FormVFX + closed the render fails in words on the card rather than in the console. + +The engine is the one test_window.py starts, on an empty data folder, with FORMVFX_URL pointed at a closed port so +a FormVFX running on this computer is never reached. +""" + +import json +import shutil +import socket +import subprocess + +import pytest +from test_window import CLS_PROBE, engine # noqa: F401 - the fixture, shared with the smoke test + +pytestmark = pytest.mark.skipif(not shutil.which("ffmpeg"), reason="needs ffmpeg to make a clip") +TIMEOUT = 60_000 +FPS = 25 +SQUARE = [0.2, 0.2, 0.8, 0.2, 0.8, 0.8, 0.2, 0.8] +LINK = { + "format": "formvfx.link/1", + "formvfx": "0.40.0", + "project": "/projects/promo.fvxproj", + "projectId": "p-1", + "comp": {"id": 1, "name": "Lower third"}, + "width": 320, + "height": 180, + "frameRate": 25, + "duration": 2.0, +} + + +@pytest.fixture(autouse=True, scope="module") +def no_formvfx(tmp_path_factory): + """FormVFX's address for the engine: a port nothing listens on.""" + import os + + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + port = s.getsockname()[1] + before = {k: os.environ.get(k) for k in ("FORMVFX_URL", "FORMVFX_DATA_DIR")} + os.environ["FORMVFX_URL"] = f"http://127.0.0.1:{port}" + os.environ["FORMVFX_DATA_DIR"] = str(tmp_path_factory.mktemp("formvfx-data")) + yield + for key, value in before.items(): + if value is None: + os.environ.pop(key, None) + else: + os.environ[key] = value + + +@pytest.fixture(scope="module") +def clip(tmp_path_factory): + path = tmp_path_factory.mktemp("pin-link") / "clip.mp4" + command = [ + "ffmpeg", + "-v", + "error", + "-y", + "-f", + "lavfi", + "-i", + f"testsrc2=size=320x180:rate={FPS}:duration=2", + "-c:v", + "mpeg4", + str(path), + ] + subprocess.run(command, check=True) + return path + + +@pytest.fixture +def window(engine, clip, tmp_path): # noqa: F811 - the imported fixture + from playwright.sync_api import sync_playwright + + errors = [] + with sync_playwright() as p: + claim = p.request.new_context(base_url=engine, extra_http_headers={"x-formcut-local": "1"}) + key = claim.post("/api/window/key").json()["key"] + claim.dispose() + api = p.request.new_context(base_url=engine, extra_http_headers={"x-formcut-local": "1", "x-formcut-window-key": key}) + uploaded = api.post("/api/media", multipart={"file": {"name": "clip.mp4", "mimeType": "video/mp4", "buffer": clip.read_bytes()}}) + assert uploaded.ok, uploaded.text() + media_id = uploaded.json()["id"] + pin = {"times": [0.0, 1 / FPS, 2 / FPS], "points": [SQUARE, SQUARE, SQUARE]} + video = {"id": "plate", "kind": "video", "label": "plate", "start": 0, "duration": 2, "mediaId": media_id, "cornerPin": pin} + project = { + "title": "pinned", + "width": 320, + "height": 180, + "fps": FPS, + "activeTimeline": 0, + "timelines": [{"id": "t1", "name": "Timeline 1", "tracks": [{"id": "v1", "name": "Video", "clips": [video]}]}], + } + made = api.post( + "/api/rpc", data=json.dumps({"jsonrpc": "2.0", "id": 1, "method": "project.create", "params": {"project": project}}) + ) + assert made.ok and "result" in made.json(), made.text() + saved = tmp_path / "promo.fvxproj" # the linked project is a file on this computer, as an import needs + saved.write_text('{"uid": "p-1"}') + linked = api.post( + "/api/vfx-link/import", + data=json.dumps({"link": {**LINK, "project": str(saved)}, "name": "promo - Lower third"}), + headers={"content-type": "application/json"}, + ) + assert linked.status == 201, linked.text() + browser = p.chromium.launch() + page = browser.new_page(viewport={"width": 1440, "height": 900}) + page.add_init_script(CLS_PROBE) + page.on("pageerror", lambda e: errors.append(str(e))) + page.on("console", lambda m: errors.append(m.text) if m.type == "error" else None) + page.add_init_script(f"sessionStorage.setItem('formcut-window-key', {key!r})") + page.goto(engine + "/", wait_until="load", timeout=120_000) + page.click(".mode-ask [data-later]", timeout=TIMEOUT) + page.click(f'[data-open-project="{made.json()["result"]["id"]}"]', timeout=TIMEOUT) + page.wait_for_function("() => document.querySelector('.start-overlay').hidden", timeout=TIMEOUT) + yield page, linked.json(), errors + browser.close() + api.dispose() + + +def _show_track_section(page): + page.locator(".clip.k-video").first.click() + page.wait_for_selector('[data-ref="planar-btn"]', state="attached", timeout=TIMEOUT) + for tab in ("animation", "adjust", "speed", "repair"): + if page.locator('[data-ref="planar-btn"]').first.is_visible(): + break + page.locator(f'[data-tab="{tab}"]').first.click() + page.wait_for_timeout(300) + + +def test_a_corner_of_an_applied_pin_is_dragged_on_one_frame_and_undone(window): + page, _, errors = window + button = page.locator('[data-ref="pin-edit"]') + assert button.get_attribute("hidden") is not None # no clip chosen: nothing to edit + _show_track_section(page) + assert button.is_visible() and button.text_content() == "Edit corners" + page.wait_for_timeout(500) + before = page.evaluate("window.__cls") + button.click() + page.wait_for_selector(".preview-pin:not([hidden]) .pin-grip", timeout=TIMEOUT) + page.wait_for_timeout(300) + assert page.evaluate("window.__cls") == before, page.evaluate("window.__shifts") # turning it on moves nothing + assert page.locator(".preview-pin .pin-grip").count() == 4 + grip = page.locator('.preview-pin .pin-grip[data-corner="2"]') + stage = page.locator(".stage").bounding_box() + box = grip.bounding_box() + assert abs(box["x"] + box["width"] / 2 - (stage["x"] + stage["width"] * 0.8)) < 3 # on the pin's bottom right + page.mouse.move(box["x"] + box["width"] / 2, box["y"] + box["height"] / 2) + page.mouse.down() + page.mouse.move(box["x"] - 30, box["y"] - 20, steps=6) + page.mouse.up() + page.wait_for_function("() => document.querySelector('.pin-grip[data-corner=\"2\"]').classList.contains('is-edited')", timeout=TIMEOUT) + moved = grip.bounding_box() + assert moved["x"] < box["x"] - 20 and moved["y"] < box["y"] - 10 + page.keyboard.press("ControlOrMeta+z") + page.wait_for_function("() => !document.querySelector('.pin-grip[data-corner=\"2\"]').classList.contains('is-edited')", timeout=TIMEOUT) + back = grip.bounding_box() + assert abs(back["x"] - box["x"]) < 2 and abs(back["y"] - box["y"]) < 2 + still = page.evaluate("window.__cls") + button.click() + page.wait_for_selector(".preview-pin", state="hidden", timeout=TIMEOUT) + assert page.evaluate("window.__cls") == still + assert not errors, errors + + +def test_the_track_workspace_offers_stop_or_hold_when_the_track_is_lost(window): + page, _, errors = window + _show_track_section(page) + page.click('[data-ref="planar-btn"]') + page.wait_for_selector(".pw", timeout=TIMEOUT) + page.click('.pw [data-tool="rect"]') + svg = page.locator(".pw [data-ref=svg]").bounding_box() + page.mouse.move(svg["x"] + svg["width"] * 0.3, svg["y"] + svg["height"] * 0.3) + page.mouse.down() + page.mouse.move(svg["x"] + svg["width"] * 0.7, svg["y"] + svg["height"] * 0.7, steps=4) + page.mouse.up() + lost = page.locator('.pw [data-key="lost"]') + lost.wait_for(timeout=TIMEOUT) + assert lost.input_value() == "stop" + assert page.eval_on_selector_all('.pw [data-key="lost"] option', "els => els.map(e => e.textContent)") == ["Stop", "Hold last position"] + assert page.locator('.pw [data-key="perspective"]').is_checked() # a rectangle is four corners: perspective by default + lost.select_option("hold") + assert lost.input_value() == "hold" + assert "held at the last position" in (page.locator(".pw [data-ref=strip]").get_attribute("title") or "") + assert not errors, errors + + +def test_a_live_link_says_so_and_render_and_replace_fails_in_words_with_formvfx_closed(window): + page, item, errors = window + page.click('[data-tab="Media"]', timeout=TIMEOUT) + card = page.locator(f'.bin-card[data-media="{item["id"]}"]') + card.wait_for(timeout=TIMEOUT) + assert card.locator(f'[data-vfx-link="{item["id"]}"]').text_content() == "Live from FormVFX" + assert card.locator(".bin-proxy").count() == 0 and card.locator(".bin-post").count() == 0 + render = card.locator(".bin-vfx-render") + assert render.get_attribute("title") == "Render and replace" + card.hover() + render.click() + page.wait_for_function( + f"() => document.querySelector('[data-vfx-link=\"{item['id']}\"]').textContent === 'Render and replace failed'", timeout=TIMEOUT + ) + assert "FormVFX" in (card.locator(f'[data-vfx-link="{item["id"]}"]').get_attribute("title") or "") + assert not [e for e in errors if "vfx" in e.lower() or "pin" in e.lower()], errors diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index c147a52e..6bcfb84d 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -878,7 +878,7 @@ dependencies = [ [[package]] name = "formcut" -version = "2.23.0" +version = "2.24.0" dependencies = [ "objc2", "objc2-app-kit", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index b8c1a4f8..9d51d8da 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "formcut" -version = "2.23.0" +version = "2.24.0" edition = "2021" [build-dependencies] diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 1f6cf5e4..c0da9398 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "FormCut", - "version": "2.23.0", + "version": "2.24.0", "identifier": "app.formcut.desktop", "build": { "frontendDist": "../frontend/dist" diff --git a/tests/test_pin_edit.py b/tests/test_pin_edit.py new file mode 100644 index 00000000..b0f276f5 --- /dev/null +++ b/tests/test_pin_edit.py @@ -0,0 +1,200 @@ +"""Hand edits of an applied corner pin (2.24.0): one corner of a pin moved on one frame, kept in the clip's own pin so a +render, a save and an undo all carry it; the tracked value it replaced is kept beside it so the edit can be reset. +The engine's edit (backend/app/pin_edit.py, `clip.pin-corner` through project.edit and the MCP server's formcut_edit) +and the window's twin (frontend/src/engine/pin-edit.ts, run here in Node) give the same pin for the same edit.""" + +from __future__ import annotations + +import json +import os +import shutil +import subprocess + +import pytest +from app import automation +from app.pin_edit import edit_corner, reset_corner +from app.renderer import pin_at +from conftest import ROOT + +FPS = 30.0 +TRACKED = { + "times": [0.0, 1 / FPS, 2 / FPS], + "points": [ + [0.1, 0.1, 0.9, 0.1, 0.9, 0.9, 0.1, 0.9], + [0.2, 0.1, 0.9, 0.1, 0.9, 0.9, 0.1, 0.9], + [0.3, 0.1, 0.9, 0.1, 0.9, 0.9, 0.1, 0.9], + ], +} + + +def test_a_corner_moved_on_a_tracked_frame_changes_that_frame_only(): + pin = edit_corner(TRACKED, 1 / FPS, 2, 0.8, 0.95, FPS) + assert pin["points"][1][4:6] == [0.8, 0.95] + assert pin["points"][0] == TRACKED["points"][0] and pin["points"][2] == TRACKED["points"][2] + assert pin["edits"] == [{"t": round(1 / FPS, 6), "corner": 2, "was": [0.9, 0.9]}] + assert pin_at({"cornerPin": pin}, 1 / FPS)[2] == pytest.approx((0.8, 0.95)) + assert TRACKED["points"][1][4:6] == [0.9, 0.9] # the pin given is not changed + + +def test_a_frame_between_samples_gets_its_own_sample(): + half = 0.5 / FPS + pin = edit_corner(TRACKED, half, 0, 0.0, 0.0, FPS * 4) # at 120 fps, a quarter of the way is its own frame + assert pin["times"] == [0.0, round(half, 6), 1 / FPS, 2 / FPS] + assert pin["points"][1][0:2] == [0.0, 0.0] and pin["points"][1][2:] == pytest.approx(TRACKED["points"][0][2:]) + assert pin["edits"][0]["was"] == pytest.approx([0.15, 0.1]) + + +def test_a_second_move_keeps_the_first_tracked_value_and_reset_puts_it_back(): + once = edit_corner(TRACKED, 2 / FPS, 1, 0.85, 0.15, FPS) + twice = edit_corner(once, 2 / FPS, 1, 0.88, 0.12, FPS) + assert twice["edits"] == [{"t": round(2 / FPS, 6), "corner": 1, "was": [0.9, 0.1]}] + back = reset_corner(twice, 2 / FPS, 1, FPS) + assert back["points"] == TRACKED["points"] and "edits" not in back + + +def test_a_fixed_pin_moves_its_corner(): + fixed = {"points": [[0, 0], [1, 0], [1, 1], [0, 1]]} + pin = edit_corner(fixed, 3.0, 3, 0.05, 0.9, FPS) + assert pin["points"] == [[0, 0], [1, 0], [1, 1], [0.05, 0.9]] and pin["edits"] == [{"corner": 3, "was": [0, 1]}] + assert reset_corner(pin, 0.0, 3, FPS)["points"] == fixed["points"] + + +@pytest.mark.parametrize( + ("pin", "corner", "point", "why"), + [ + (TRACKED, 4, (0.5, 0.5), "corner"), + (TRACKED, 0, (float("nan"), 0.5), "finite"), + (TRACKED, 0, (50.0, 0.5), "canvas"), + (TRACKED, 2, (0.5, 0.5), "fold"), + (TRACKED, 2, (0.2, 0.2), "fold"), + ({**TRACKED, "mesh": {"cols": 2, "rows": 2, "times": [0], "points": [[[0, 0]] * 9]}}, 0, (0.5, 0.5), "mesh"), + (None, 0, (0.5, 0.5), "corner pin"), + ], +) +def test_bad_edits_are_named(pin, corner, point, why): + with pytest.raises(ValueError, match=why): + edit_corner(pin, 0.0, corner, point[0], point[1], FPS) + + +def _project_with_pin(): + clip = {"id": "insert", "kind": "image", "label": "insert", "start": 2.0, "duration": 2.0, "cornerPin": TRACKED} + project = { + "title": "pin", + "width": 640, + "height": 360, + "fps": FPS, + "activeTimeline": 0, + "timelines": [{"id": "t", "name": "T", "tracks": [{"id": "v", "name": "Video", "clips": [clip]}]}], + } + return automation.dispatch("project.create", {"project": project}) + + +def test_the_edit_goes_through_project_edit_and_undoes(): + created = _project_with_pin() + assert "clip.pin-corner" in automation.dispatch("capabilities", {})["edit_commands"] + command = {"op": "clip.pin-corner", "clipId": "insert", "t": 1 / FPS, "corner": 2, "x": 0.8, "y": 0.95} + edited = automation.dispatch("project.edit", {"id": created["id"], "revision": created["revision"], "commands": [command]}) + pin = automation.dispatch("project.get", {"id": created["id"]})["timelines"][0]["tracks"][0]["clips"][0]["cornerPin"] + assert pin["points"][1][4:6] == [0.8, 0.95] and pin["edits"][0]["corner"] == 2 + reset = {"op": "clip.pin-corner", "clipId": "insert", "t": 1 / FPS, "corner": 2, "reset": True} + automation.dispatch("project.edit", {"id": created["id"], "revision": edited["revision"], "commands": [reset]}) + pin = automation.dispatch("project.get", {"id": created["id"]})["timelines"][0]["tracks"][0]["clips"][0]["cornerPin"] + assert pin["points"] == TRACKED["points"] + automation.dispatch("project.undo", {"id": created["id"]}) + pin = automation.dispatch("project.get", {"id": created["id"]})["timelines"][0]["tracks"][0]["clips"][0]["cornerPin"] + assert pin["points"][1][4:6] == [0.8, 0.95] + with pytest.raises(ValueError, match="corner pin"): + bare = {"op": "clip.pin-corner", "clipId": "nothing", "t": 0, "corner": 0, "x": 0, "y": 0} + current = automation.dispatch("project.get", {"id": created["id"]})["revision"] + automation.dispatch("project.edit", {"id": created["id"], "revision": current, "commands": [bare]}) + + +def test_an_edited_pin_renders_where_it_was_moved(tmp_path): + """The renderer reads the edited sample: the picture's bottom right corner is drawn where it was dragged, and the + frames either side of the edit are drawn as they were tracked.""" + from app.media import ingest_path + from app.renderer import FrameRenderer + from PIL import Image + + picture = tmp_path / "red.png" + Image.new("RGB", (200, 100), (230, 20, 20)).save(picture) + item = ingest_path(picture, "red.png") + square = [0.1, 0.1, 0.9, 0.1, 0.9, 0.9, 0.1, 0.9] + tracked = {"times": [0.0, 1 / FPS, 2 / FPS], "points": [square, square, square]} + pin = edit_corner(tracked, 1 / FPS, 2, 0.6, 0.6, FPS) + clip = {"id": "c1", "kind": "image", "label": "red", "start": 0, "duration": 2, "mediaId": item["id"], "cornerPin": pin} + project = {"width": 320, "height": 180, "fps": FPS, "activeTimeline": 0, "timelines": [{"tracks": [{"clips": [clip]}]}]} + renderer = FrameRenderer(project, 320) + try: + edited, after = renderer.frame(1 / FPS), renderer.frame(2 / FPS) + finally: + renderer.close() + red = lambda frame, x, y: frame[int(180 * y), int(320 * x), 0] > 180 and frame[int(180 * y), int(320 * x), 1] < 80 # noqa: E731 + assert not red(edited, 0.8, 0.8) and red(edited, 0.3, 0.3) # the corner pulled in to the middle + assert red(after, 0.8, 0.8) # the next frame keeps its tracked corner + + +NODE_RUN = """ +import { editPinCorner, resetPinCorner } from %s; +const cases = JSON.parse(process.argv[1]); +const out = cases.map(([pin, t, c, x, y, fps, reset]) => { try { return reset ? resetPinCorner(pin, t, c, fps) : editPinCorner(pin, t, c, x, y, fps); } catch (e) { return { error: String(e.message) }; } }); +console.log(JSON.stringify(out)); +""" + + +# Node by name, or FORMCUT_NODE: the suite takes a folder off PATH when it holds an agent program (conftest.py), which +# on a Mac with Homebrew is also where node is +NODE = os.environ.get("FORMCUT_NODE") or shutil.which("node") + + +def _node_strips_types() -> bool: + if NODE is None: + return False + try: + major, minor = ( + int(v) + for v in subprocess.run([NODE, "-p", "process.versions.node"], capture_output=True, text=True, check=False).stdout.split(".")[ + :2 + ] + ) + except ValueError: + return False + return (major, minor) >= (22, 6) + + +@pytest.mark.skipif(not _node_strips_types(), reason="needs Node 22.6 or newer to run TypeScript") +def test_the_window_makes_the_same_pin_as_the_engine(): + source = (ROOT / "frontend" / "src" / "engine" / "pin-edit.ts").as_uri() + fixed = {"points": [[0, 0], [1, 0], [1, 1], [0, 1]]} + cases = [ + [TRACKED, 1 / FPS, 2, 0.8, 0.95, FPS, False], + [TRACKED, 0.5 / FPS, 0, 0.0, 0.0, FPS * 4, False], + [edit_corner(TRACKED, 2 / FPS, 1, 0.85, 0.15, FPS), 2 / FPS, 1, 0, 0, FPS, True], + [fixed, 3.0, 3, 0.05, 0.9, FPS, False], + [TRACKED, 0.0, 4, 0.5, 0.5, FPS, False], + [TRACKED, 0.0, 2, 0.5, 0.5, FPS, False], + ] + run = subprocess.run( + [ + NODE, + "--experimental-strip-types", + "--no-warnings", + "--input-type=module", + "-e", + NODE_RUN % json.dumps(source), + json.dumps(cases), + ], + capture_output=True, + text=True, + check=True, + ) + window = json.loads(run.stdout) + engine = [ + edit_corner(TRACKED, 1 / FPS, 2, 0.8, 0.95, FPS), + edit_corner(TRACKED, 0.5 / FPS, 0, 0.0, 0.0, FPS * 4), + reset_corner(edit_corner(TRACKED, 2 / FPS, 1, 0.85, 0.15, FPS), 2 / FPS, 1, FPS), + edit_corner(fixed, 3.0, 3, 0.05, 0.9, FPS), + ] + for mine, theirs in zip(engine, window[:4], strict=True): + assert json.dumps(theirs, sort_keys=True) == json.dumps(mine, sort_keys=True) or theirs == pytest.approx(mine) + assert "corner" in window[4]["error"] and "fold" in window[5]["error"] diff --git a/tests/test_pin_link_strings.py b/tests/test_pin_link_strings.py new file mode 100644 index 00000000..55b63b23 --- /dev/null +++ b/tests/test_pin_link_strings.py @@ -0,0 +1,57 @@ +"""Every string 2.24.0's three controls show is a locale key in every language formcut keeps: en, es and de, the four +shipped locale files (ar, fa, he, hr), and the language pack's nine (a row by the English text); and the modules +that show them use those keys, not English literals.""" + +from __future__ import annotations + +import json +import re + +from conftest import ROOT + +I18N = ROOT / "frontend" / "src" / "i18n" +KEYS = { + "pin.edit", + "pin.editHint", + "pin.gripHint", + "pin.folded", + "pin.corner.tl", + "pin.corner.tr", + "pin.corner.br", + "pin.corner.bl", + "planar.lostMode", + "planar.lostMode.stop", + "planar.lostMode.hold", + "planar.heldFrames", + "planar.stripLegend", + "vfxlink.live", + "vfxlink.render", + "vfxlink.rendering", + "vfxlink.replaced", + "vfxlink.failed", + "vfxlink.unreadable", +} + + +def test_every_new_string_is_in_every_language(): + english = json.loads((I18N / "en.json").read_text(encoding="utf-8")) + for path in ( + I18N / "es.json", + I18N / "de.json", + *(ROOT / "frontend" / "public" / "locales" / f"{c}.json" for c in ("ar", "fa", "he", "hr")), + ): + other = json.loads(path.read_text(encoding="utf-8")) + assert set(other) >= KEYS, (path.name, sorted(KEYS - set(other))) + assert all(other[k] and other[k] != english[k] for k in KEYS if k != "planar.lostMode.stop" or path.name != "en.json"), path.name + pack = (I18N / "language-pack.ts").read_text(encoding="utf-8") + missing = [k for k in KEYS if f"\n{english[k]}|" not in pack] + assert not missing, missing + + +def test_the_modules_use_the_keys(): + ui = ROOT / "frontend" / "src" / "ui" + used = set() + for name in ("pin-corners.ts", "tracking.ts", "inspector-pane.ts", "planar-workspace.ts", "vfx-link.ts", "media-pane.ts"): + used |= set(re.findall(r't\("((?:pin|planar|vfxlink)\.[A-Za-z.]+)"\)', (ui / name).read_text(encoding="utf-8"))) + used |= {f"pin.corner.{c}" for c in ("tl", "tr", "br", "bl")} | {f"planar.lostMode.{m}" for m in ("stop", "hold")} + assert used >= KEYS, sorted(KEYS - used) diff --git a/tests/test_planar_hold.py b/tests/test_planar_hold.py new file mode 100644 index 00000000..917b56d2 --- /dev/null +++ b/tests/test_planar_hold.py @@ -0,0 +1,140 @@ +"""When the track is lost (2.24.0): Stop, the default, ends the track where the plane went, as it always has; Hold keeps +the last good position for the lost frames and marks them held, so a plane that leaves the shot for a moment does not +end the track. The setting is not part of what a track depends on, so changing it keeps the frames already tracked.""" + +from __future__ import annotations + +import subprocess +import time + +import numpy as np +import pytest +from app import planar_bench +from app.main import app +from fastapi.testclient import TestClient + +GOOD, GONE = 12, 24 + + +def _client(): + return TestClient(app, base_url="http://127.0.0.1:8123", headers={"x-formcut-local": "1"}) + + +def _finish(client, job_id): + for _ in range(1500): + status = client.get(f"/api/jobs/{job_id}").json() + if status["status"] not in ("queued", "running"): + return status + time.sleep(0.02) + return status + + +@pytest.fixture(scope="module") +def vanishing(tmp_path_factory): + """Twelve frames of a tracked plane, then twenty-four of noise: (media id, true corners, size).""" + from app.media import ingest_path + + s = planar_bench.Scenario(**{**planar_bench.SCENARIOS["moderate"].__dict__, "frames": GOOD}) + frames, truth, _ = planar_bench.shot(s) + rng = np.random.default_rng(5) + frames += [(rng.random((s.height, s.width, 3)) * 255).astype(np.uint8) for _ in range(GONE)] + path = tmp_path_factory.mktemp("hold") / "gone.mkv" + size = f"{s.width}x{s.height}" + command = ["ffmpeg", "-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "bgr24", "-s", size, "-r", "30", "-i", "-"] + encode = subprocess.Popen([*command, "-c:v", "ffv1", "-pix_fmt", "bgr0", str(path)], stdin=subprocess.PIPE) + for frame in frames: + encode.stdin.write(frame.tobytes()) + encode.stdin.close() + assert encode.wait() == 0 + return ingest_path(path, "gone.mkv")["id"], truth, (s.width, s.height) + + +def _layer(truth, size, layer_id, lost=None): + c = truth[0] + centre = c.mean(0) + points = ((c - centre) * 0.92 + centre) / size + settings = {"perspective": True} if lost is None else {"perspective": True, "lost": lost} + return {"id": layer_id, "shapes": [{"points": points.round(6).tolist()}], "reference": 0.0, "settings": settings} + + +def _track(client, media_id, layer, stop=GOOD + GONE - 1): + job = client.post("/api/planar/track", json={"media_id": media_id, "layer": layer, "start": 0, "stop": stop / 30}) + assert job.status_code == 202, job.text + return _finish(client, job.json()["job_id"]) + + +def test_stop_is_the_default_and_still_ends_the_track_where_the_plane_went(vanishing): + media_id, truth, size = vanishing + client = _client() + done = _track(client, media_id, _layer(truth, size, "stop-default")) + assert done["status"] == "done" and "lost" in done["result"] and "held" not in done["result"], done + read = client.get("/api/planar/track/stop-default").json() + assert max(read["frames"]) < done["result"]["lost"] + assert read.get("held", []) == [] + + +def test_hold_keeps_the_last_good_position_through_the_lost_frames_and_marks_them(vanishing): + media_id, truth, size = vanishing + client = _client() + done = _track(client, media_id, _layer(truth, size, "held-layer", lost="hold")) + assert done["status"] == "done", done + assert "lost" not in done["result"], done["result"] # the track ran to the end it was asked for + assert done["result"]["to"] == GOOD + GONE - 1 and done["result"]["held"] >= GONE - 2, done["result"] + read = client.get("/api/planar/track/held-layer").json() + assert read["frames"] == list(range(GOOD + GONE)) + held = read["held"] + assert held == sorted(held) and held == list(range(held[0], GOOD + GONE)), held # one run, to the end + assert held[0] >= GOOD - 2, held # the plane was there for its first twelve frames + first = read["frames"].index(held[0]) + good = np.array(read["matrices"][first - 1]) + for i in held: + assert np.allclose(read["matrices"][read["frames"].index(i)], good), i # the last good position, unchanged + for i in read["frames"][:first]: + assert i not in held + + +def test_the_setting_does_not_start_a_track_afresh_and_a_bad_value_is_named(vanishing): + media_id, truth, size = vanishing + client = _client() + _track(client, media_id, _layer(truth, size, "switched"), stop=6) + before = client.get("/api/planar/track/switched").json() + assert before["frames"] == list(range(7)) + # a frame on, now with Hold: the seven frames already tracked are kept, so the next starts from frame 6 + done = _track(client, media_id, {**_layer(truth, size, "switched", lost="hold")}, stop=6) + assert done["status"] == "done" + job = client.post( + "/api/planar/track", + json={"media_id": media_id, "layer": _layer(truth, size, "switched", lost="hold"), "start": 6 / 30, "stop": 8 / 30}, + ) + assert job.status_code == 202, job.text + assert _finish(client, job.json()["job_id"])["status"] == "done" + assert client.get("/api/planar/track/switched").json()["frames"] == list(range(9)) + bad = client.post( + "/api/planar/track", json={"media_id": media_id, "layer": _layer(truth, size, "bad", lost="drift"), "start": 0, "stop": 0.1} + ) + assert bad.status_code == 400 and "lost" in bad.json()["detail"] + + +def test_clearing_a_range_clears_its_held_marks(vanishing): + media_id, truth, size = vanishing + client = _client() + _track(client, media_id, _layer(truth, size, "cleared", lost="hold")) + held = client.get("/api/planar/track/cleared").json()["held"] + assert held + client.delete("/api/planar/track/cleared", params={"start": held[0], "stop": GOOD + GONE}) + read = client.get("/api/planar/track/cleared").json() + assert read["held"] == [] and max(read["frames"]) < held[0] + + +def test_the_tracker_holds_its_prediction_where_it_is_told(): + from app.planar import PlanarTracker, Settings + + rng = np.random.default_rng(3) + first = (rng.random((180, 320, 3)) * 255).astype(np.uint8) + matte = np.zeros((180, 320), np.uint8) + matte[40:140, 80:240] = 255 + tracker = PlanarTracker(first, matte, Settings(perspective=True, motion="manual")) + there = np.array([[1, 0, 7], [0, 1, -3], [0, 0, 1]], float) + tracker.hold(there) + h, _ = tracker.step(first) + assert np.allclose(h, there) # manual motion steps by the prediction, which now starts from the held place diff --git a/tests/test_planar_perspective_default.py b/tests/test_planar_perspective_default.py new file mode 100644 index 00000000..91ffa576 --- /dev/null +++ b/tests/test_planar_perspective_default.py @@ -0,0 +1,195 @@ +"""A four-corner surface tracks in perspective by default (2.24.0), and a frame the chosen model cannot hold is refitted +in perspective. + +A screen or a corner-pin target is a plane seen at an angle, and a similarity (move, turn, scale) cannot follow its +corners as it tilts: on synthetic screen clips with exact corners, the old default (Perspective off) left 25 to 35 px +of mean error on a tilting screen, against well under a pixel with Perspective on. A layer drawn as four corners now +tracks in perspective unless the person chose otherwise; any other shape keeps the old default. A frame where a lower +model holds under 0.6 of its points is refitted in perspective from the same point pairs, kept when that holds at +least 0.2 more of them, and marked.""" + +from __future__ import annotations + +import math +import subprocess +import time + +import cv2 +import numpy as np +import pytest +from app.main import app +from fastapi.testclient import TestClient + +W, H, FRAMES, F = 640, 360, 30, 600.0 +PLANE_W, PLANE_H = 300, 200 + + +def _texture(seed: int = 4) -> np.ndarray: + """A photo-like texture: soft colour fields with shapes and fine detail, so the plane has points to follow.""" + rng = np.random.default_rng(seed) + img = np.zeros((PLANE_H, PLANE_W, 3), np.float32) + amp = 1.0 + for octave in range(5): + cells = 4 * 2**octave + small = rng.standard_normal((max(2, PLANE_H * cells // PLANE_W), cells, 3)).astype(np.float32) + img += amp * cv2.resize(small, (PLANE_W, PLANE_H), interpolation=cv2.INTER_CUBIC) + amp *= 0.6 + img = (img - img.min()) / max(1e-6, img.max() - img.min()) + canvas = (60 + 150 * img).astype(np.uint8) + for _ in range(30): + colour = tuple(int(c) for c in rng.integers(20, 240, 3)) + centre = (int(rng.integers(0, PLANE_W)), int(rng.integers(0, PLANE_H))) + cv2.circle(canvas, centre, int(rng.integers(4, 30)), colour, -1, cv2.LINE_AA) + return cv2.GaussianBlur(canvas, (0, 0), 0.8) + + +def _homography(yaw: float, pitch: float, roll: float, tx: float, ty: float) -> np.ndarray: + """Plane texture pixels to frame pixels for a plane turned by yaw, pitch and roll (degrees) before a pinhole.""" + y, p, r = (math.radians(a) for a in (yaw, pitch, roll)) + ry = np.array([[math.cos(y), 0, math.sin(y)], [0, 1, 0], [-math.sin(y), 0, math.cos(y)]]) + rx = np.array([[1, 0, 0], [0, math.cos(p), -math.sin(p)], [0, math.sin(p), math.cos(p)]]) + rz = np.array([[math.cos(r), -math.sin(r), 0], [math.sin(r), math.cos(r), 0], [0, 0, 1]]) + rot = rz @ rx @ ry + k = np.array([[F, 0, W / 2], [0, F, H / 2], [0, 0, 1]]) + centre = np.array([[1, 0, -PLANE_W / 2], [0, 1, -PLANE_H / 2], [0, 0, 1]], float) + h = k @ np.column_stack([rot[:, 0], rot[:, 1], [tx, ty, F]]) @ centre + return h / h[2, 2] + + +def tilting_plane() -> tuple[list[np.ndarray], list[np.ndarray]]: + """A textured plane that swings from facing left and down to facing right and up, over a grey ground: + (frames, its four true corners per frame, top left first).""" + texture = _texture() + ground = np.full((H, W, 3), 90, np.uint8) + corners = np.array([[0, 0], [PLANE_W, 0], [PLANE_W, PLANE_H], [0, PLANE_H]], float).reshape(-1, 1, 2) + frames, truth = [], [] + for i in range(FRAMES): + s = 0.5 - 0.5 * math.cos(math.pi * i / (FRAMES - 1)) + h = _homography(-28 + 56 * s, 18 - 36 * s, -5 + 12 * s, -40 + 80 * s, 10 - 20 * s) + plane = cv2.warpPerspective(texture, h, (W, H), flags=cv2.INTER_LINEAR) + alpha = cv2.warpPerspective(np.ones((PLANE_H, PLANE_W), np.float32), h, (W, H), flags=cv2.INTER_LINEAR)[..., None] + frames.append((ground * (1 - alpha) + plane * alpha).astype(np.uint8)) + truth.append(cv2.perspectiveTransform(corners, h).reshape(4, 2)) + return frames, truth + + +@pytest.fixture(scope="module") +def tilting(tmp_path_factory): + from app.media import ingest_path + + frames, truth = tilting_plane() + path = tmp_path_factory.mktemp("tilt") / "tilt.mkv" + command = ["ffmpeg", "-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "bgr24", "-s", f"{W}x{H}", "-r", "30", "-i", "-"] + encode = subprocess.Popen([*command, "-c:v", "ffv1", "-pix_fmt", "bgr0", str(path)], stdin=subprocess.PIPE) + for frame in frames: + encode.stdin.write(frame.tobytes()) + encode.stdin.close() + assert encode.wait() == 0 + return ingest_path(path, "tilt.mkv")["id"], frames, truth + + +def _finish(client, job_id): + for _ in range(3000): + status = client.get(f"/api/jobs/{job_id}").json() + if status["status"] not in ("queued", "running"): + return status + time.sleep(0.02) + return status + + +def _quad_layer(truth, layer_id, settings): + c = truth[0] + centre = c.mean(0) + points = ((c - centre) * 0.9 + centre) / (W, H) # four corners just inside the plane's own + return {"id": layer_id, "shapes": [{"points": points.round(6).tolist()}], "reference": 0.0, "settings": settings} + + +def _mean_error(client, layer_id, truth) -> float: + surface = ",".join(f"{v:.6f}" for v in (truth[0] / (W, H)).ravel()) + data = client.get(f"/api/planar/track/{layer_id}", params={"surface": surface}).json() + corners = np.array(data["corners"]) * (W, H) + assert data["frames"] == list(range(FRAMES)), data["frames"] + return float(np.mean([np.linalg.norm(corners[k] - truth[i], axis=1).mean() for k, i in enumerate(data["frames"])])) + + +def _track(client, media_id, layer): + job = client.post("/api/planar/track", json={"media_id": media_id, "layer": layer, "start": 0, "stop": (FRAMES - 1) / 30}) + assert job.status_code == 202, job.text + done = _finish(client, job.json()["job_id"]) + assert done["status"] == "done", done + return done + + +def test_a_four_corner_layer_tracks_a_tilting_plane_in_perspective_by_default(tilting): + media_id, _, truth = tilting + client = TestClient(app, base_url="http://127.0.0.1:8123", headers={"x-formcut-local": "1"}) + _track(client, media_id, _quad_layer(truth, "quad-default", {})) # nothing chosen: the default + error = _mean_error(client, "quad-default", truth) + assert error < 1.0, error + + +def test_the_persons_own_choice_is_kept(): + from app.planar_api import Layer, _settings + + four = [[0.1, 0.1], [0.9, 0.1], [0.9, 0.9], [0.1, 0.9]] + many = [[0.5 + 0.3 * math.cos(a), 0.5 + 0.3 * math.sin(a)] for a in np.linspace(0, 2 * math.pi, 12, endpoint=False)] + + def layer(points, settings, kind="polygon"): + return Layer(id="x", shapes=[{"points": points, "kind": kind}], reference=0.0, settings=settings) + + assert _settings(layer(four, {}).settings, layer(four, {})).perspective is True + assert _settings(layer(four, {"perspective": False}).settings, layer(four, {"perspective": False})).perspective is False + assert _settings(layer(many, {}).settings, layer(many, {})).perspective is False # an ellipse keeps the old default + assert _settings(layer(four, {}, "xspline").settings, layer(four, {}, "xspline")).perspective is False # a curve + + +def _similarity_run(frames, truth) -> tuple[list[bool], list[float]]: + from app.planar import PlanarTracker, Settings + + matte = np.zeros((H, W), np.uint8) + c = truth[0] + centre = c.mean(0) + cv2.fillPoly(matte, [np.round((c - centre) * 0.9 + centre).astype(np.int32)], 255) + tracker = PlanarTracker(frames[0], matte, Settings()) # a similarity: Perspective off + assert tracker.model == "similarity" + promoted, errors = [], [] + for i in range(1, FRAMES): + h, _ = tracker.step(frames[i]) + promoted.append(tracker.promoted) + corners = cv2.perspectiveTransform(truth[0].reshape(-1, 1, 2), h).reshape(4, 2) + errors.append(float(np.linalg.norm(corners - truth[i], axis=1).mean())) + return promoted, errors + + +def test_a_frame_a_similarity_cannot_hold_is_refitted_in_perspective_and_marked(tilting, monkeypatch): + """The unit: a tracker told to use a similarity, on the tilting plane. The frames whose points a similarity cannot + hold are refitted in perspective and marked, and the corners stay on the plane; with the fallback switched off the + same run drifts off it.""" + from app import planar + + _, frames, truth = tilting + promoted, errors = _similarity_run(frames, truth) + assert any(promoted), promoted + assert np.mean(errors) < 2.0, errors + monkeypatch.setattr(planar, "PROMOTE_BELOW", 0.0) # never refitted: the similarity alone + never, drifted = _similarity_run(frames, truth) + assert not any(never) + assert np.mean(drifted) > 3 * np.mean(errors) and np.mean(drifted) > 5.0, (np.mean(drifted), np.mean(errors)) + + +def test_the_fallback_is_kept_only_when_it_holds_more_of_the_points(): + """Point pairs a similarity describes exactly are never refitted; pairs only a perspective describes are.""" + from app.planar import promote + + rng = np.random.default_rng(1) + a = rng.uniform(0, 200, (200, 2)).astype(np.float32) + turn = np.array([[0.98, -0.17, 4.0], [0.17, 0.98, -3.0], [0, 0, 1]]) + b = cv2.perspectiveTransform(a.reshape(-1, 1, 2).astype(np.float64), turn).reshape(-1, 2).astype(np.float32) + assert promote("similarity", a, b) is None # it already holds every point + tilt = np.array([[1.0, 0.05, 2.0], [0.02, 1.0, 1.0], [0.0012, 0.0009, 1]]) + b = cv2.perspectiveTransform(a.reshape(-1, 1, 2).astype(np.float64), tilt).reshape(-1, 2).astype(np.float32) + fitted = promote("similarity", a, b) + assert fitted is not None + h, inliers = fitted + assert inliers.mean() > 0.95 and np.allclose(h, tilt, atol=1e-3) + assert promote("perspective", a, b) is None # nothing above perspective to go to diff --git a/tests/test_vfx_link.py b/tests/test_vfx_link.py new file mode 100644 index 00000000..22be956b --- /dev/null +++ b/tests/test_vfx_link.py @@ -0,0 +1,418 @@ +"""A FormVFX live comp as a clip (2.24.0): a `.fvxlink` imported into the media library plays its frames from FormVFX's +Live Link while FormVFX runs, and Render and replace makes it a normal media file, so a project never depends on +FormVFX running. + +The stand-in below answers FormVFX's Live Link routes as nodemode-dev/formVFX serves them (backend/app/routers/link.py: +GET /api/link/info, /api/link/frame.png and /api/link/audio, each refused without the `x-formvfx-local: 1` header, and +GET /api/health), on loopback. Each frame is one flat colour whose red channel counts the frame, so the frame a +clip shows at a time can be read back from its pixels.""" + +from __future__ import annotations + +import io +import json +import struct +import subprocess +import threading +import time +import typing +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from urllib.parse import parse_qs, urlsplit + +import numpy as np +import pytest +from PIL import Image + +RATE, WIDTH, HEIGHT, DURATION = 24.0, 64, 36, 0.5 +DESCRIPTOR = { + "format": "formvfx.link/1", + "formvfx": "0.40.0", + "project": "/projects/promo.fvxproj", + "projectId": "p-123", + "comp": {"id": 3, "name": "Title & lower third"}, + "width": WIDTH, + "height": HEIGHT, + "frameRate": RATE, + "duration": DURATION, + "frames": "/api/link/frame.png?project={project}&projectId={projectId}&comp={comp}&compName={compName}&time={seconds}", + "audio": "/api/link/audio?project={project}&projectId={projectId}&comp={comp}&compName={compName}&start={seconds}&seconds={length}", + "check": "/api/link/check", + "render": "/api/link/render", +} + + +class StandIn(BaseHTTPRequestHandler): + requests: typing.ClassVar[list[dict]] = [] + mode = "ok" + + def log_message(self, *args): + pass + + def _send(self, status: int, body: bytes, kind: str, headers: dict | None = None) -> None: + self.send_response(status) + self.send_header("content-type", kind) + self.send_header("content-length", str(len(body))) + for key, value in (headers or {}).items(): + self.send_header(key, value) + self.end_headers() + self.wfile.write(body) + + def do_GET(self): + url = urlsplit(self.path) + query = {k: v[0] for k, v in parse_qs(url.query).items()} + StandIn.requests.append({"path": url.path, "query": query, "local": self.headers.get("x-formvfx-local")}) + if url.path == "/api/health": + return self._send(200, b'{"status":"ok"}', "application/json") + if self.headers.get("x-formvfx-local") != "1": + return self._send(403, b'{"detail":"send the x-formvfx-local: 1 header"}', "application/json") + if StandIn.mode == "redirect": + return self._send(307, b"", "text/plain", {"location": "http://example.com/frame.png"}) + if url.path == "/api/link/info": + comp = {"id": 3, "name": "Title & lower third", "width": WIDTH, "height": HEIGHT, "frameRate": RATE, "duration": DURATION} + body = {"format": "formvfx.link/1", "formvfx": "0.40.0", "project": query.get("project"), "live": True, "comp": comp} + return self._send(200, json.dumps(body).encode(), "application/json") + if url.path == "/api/link/frame.png": + if StandIn.mode == "html": + return self._send(200, b"not a picture", "image/png") + index = int(float(query["time"]) * RATE + 1e-6) + picture = Image.new("RGBA", (WIDTH, HEIGHT), (10 * index, 200, 40, 255)) + out = io.BytesIO() + picture.save(out, "PNG") + return self._send(200, out.getvalue(), "image/png", {"x-width": str(WIDTH), "x-height": str(HEIGHT)}) + if url.path == "/api/link/audio": + rate, seconds = int(query.get("rate", 48000)), float(query["seconds"]) + pcm = np.full((int(rate * seconds), 2), 0.25, "