Skip to content

Free, open-source AI video generator for Mac. Run LTX-2.5 and MiniMax H3 (Hailuo) locally on Apple Silicon: text-to-video and image-to-video with sound, lip-sync, character LoRA training, songs from lyrics (YuE2) and image editing (Qwen-Image-Edit). One-click install via Pinokio. Offline: no cloud, no API key, no NVIDIA GPU.

release(v4.10.0): One take, Turbo v4, the NLE timeline, anchor stills — and The Commuter

mrbizarro4a67971bc860
diff --git a/README.md b/README.md
index 4603f24..b3a21c8 100644
--- a/README.md
+++ b/README.md
@@ -2,6 +2,12 @@
<img src="assets/phosphene_banner.png" alt="Phosphene" width="100%">
</p>
+<p align="center">
+ <img src="assets/the_commuter_hero.gif" alt="The Commuter — a 75-second one take made in Phosphene" width="100%">
+ <br>
+ <sub><b>The Commuter</b> — a 75-second one take, rendered overnight on one Mac at native 1344×768 with Hailuo H3 and the new One take control, from a single designed still. <a href="https://github.com/mrbizarro/phosphene/releases/latest">Watch the full film in the release</a>.</sub>
+</p>
+
<p align="center">
<strong>Generative video, image, and character training on your Mac.</strong><br>
MLX. No PyTorch, no CUDA, no cloud, no API key.<br>
@@ -13,7 +19,7 @@
</p>
-> **Current release: v4.9.8.** One urgent fix: installing or updating Hailuo H3 failed at the "TAE draft decoder" step with "Repository Not Found" — the Hugging Face repo that file came from was deleted. It is now fetched from a pinned commit of the author's GitHub repo and verified by hash (thanks @macstephen on Pinokio). Includes v4.9.7 (better fleet telemetry) and v4.9.6 (H3 clips take their sidecars to Trash). Full notes on the [releases page](https://github.com/mrbizarro/phosphene/releases).
+> **Current release: v4.10.0.** One take (a clip up to two minutes on either engine, written as beats), Turbo on the community's v4 adapter, a timeline that trims and moves like an NLE, anchor stills and long shots on the Storyboard, LoRA guides and update checks, closed-tab alerts, a light theme — and *The Commuter*, a 75 s one take rendered overnight at native, as the release film. Includes the v4.9.6–v4.9.8 fixes. Full notes on the [releases page](https://github.com/mrbizarro/phosphene/releases).
## Overview
diff --git a/ROADMAP.md b/ROADMAP.md
new file mode 100644
index 0000000..78f4246
--- /dev/null
+++ b/ROADMAP.md
@@ -0,0 +1,401 @@
+# Phosphene roadmap
+
+Living document. Items listed here are committed for upcoming releases but
+not yet shipped. Priorities are loose — they move based on what the v3.0
+post-ship feedback surfaces. Filed publicly so contributors know where the
+project is going.
+
+Status notation: `[ ]` planned · `[~]` in progress · `[x]` shipped (will
+be removed from this file once it's in a stable release).
+
+## Near term (post v3.0)
+
+### `[ ]` Three-aspect character LoRAs (vertical / horizontal / general)
+
+The v3.0 character training trains at 576×576 square. This works well
+for square + vertical inference, but degrades on widescreen medium
+shots — the LoRA never saw the 1024×576 token grid during training,
+so face geometry can break in 16:9. The fix: ship three modalities.
+
+- **General** — current behavior, trained at 576×576 square. Default,
+ works adequately at every aspect.
+- **Horizontal** — trained at 1024×576 (16:9). Pinned to widescreen
+ inference for medium shots that need clean face detail.
+- **Vertical** — trained at 576×1024 (9:16). Pinned to vertical
+ social-format clips.
+
+UI: aspect selector in the Train tab, naming convention
+`<trigger>_v2[_wide|_vert].safetensors`. Character picker groups all
+three variants under one character; either auto-routes by output
+aspect, or shows a small chip to override.
+
+Foundation already in: lora_lab pipeline accepts width × height
+independently as of commit `3f49ca3`. Just needs the UI surface.
+
+Estimated effort: 2–3 hours panel work + 3.5h training per variant.
+
+### `[ ]` Scene-continuity recipe (no-training, ship first)
+
+Lock two characters into the same environment across cuts using
+existing Phosphene primitives — no scene-LoRA training required.
+Higher quality and lower operator risk than training a scene LoRA
+per location, per research conducted 2026-05-20.
+
+Workflow:
+1. Image Studio → Qwen-Image-Edit-2511 multi-ref. Drop 1–3 photos
+ of the target location (the room, the lighting, the props).
+ Generate a composed still with both characters present in the
+ scene.
+2. Pick the best still. Send to I2V (or FFLF) with no character
+ LoRAs — identity is carried by the still's VAE-encoded latent,
+ not by a LoRA delta.
+3. Repeat for each cut with the SAME location stills as references.
+ Lighting + decor stay consistent.
+
+Effort: ~0.5–1 day, docs + a small UX pass to surface the recipe
+from the Train tab (a "Lock to a location" link or hint). No code
+changes to the training pipeline.
+
+### `[ ]` Scene / location / room LoRAs (power-user follow-up)
+
+After the no-training recipe ships, add scene LoRAs as the path for
+users who want a reusable "location" they can stack with any
+character. Builds on the existing style-training pipeline
+(`train_type=style` already wired in `/train/start`).
+
+Validated training recipe (per 2026-05-20 research):
+- Dataset: 15–20 stills of one place, 4–8 angles, mix of with-people
+ / empty-room (60-70% / 30-40%)
+- Caption format: describe what VARIES across stills (lighting,
+ framing, who's in frame) but NOT the room itself — the trigger
+ carries the room. ("Caption everything your LoRA is *not*
+ supposed to control" — Civitai/Hunyuan rule of thumb.)
+- Resolution: 1024×576 widescreen (matches inference aspect; needs
+ the widescreen-training support from commit `3f49ca3`).
+- Preset: Quick (rank 16, 600 steps from 30 epochs × 20 imgs) at
+ ~30 min wall on M4 Max 64GB.
+
+Stacking with character LoRAs:
+- Documented LTX guidance: keep total combined strength under 2.0,
+ practical sweet spot below 1.5.
+- Starting weights: character 0.9–1.0, scene 0.5–0.7. The character
+ LoRA's larger weight deltas need the scene to be turned down so
+ the scene effect isn't drowned (matches the 2026-05-20 chartest
+ diag observation about strength dominance).
+- Reduce `strength_clip` on the scene LoRA before `strength_model`
+ if the room effect is still too faint.
+
+Engineering: ~1.5 days. Extend `TRAIN_TYPES` to include `scene`,
+add a fallback caption body string, add a "Locations" subnav under
+the Train tab. Touch points: `mlx_ltx_panel.py:785-801, 818, 5241,
+5260, 5295-5358` and `lora_lab/train_character.py:277-290`.
+
+### `[ ]` Multi-character workflow
+
+A real workflow for putting two trained characters in the same
+clip. The current two-LoRA stacking math produces a hybrid face
+(both identities averaged at every spatial token — see the
+2026-05-19 multi-character research). Path forward: Qwen-Image-Edit
+multi-ref → composed still → I2V with no LoRAs (identity carried
+by the still's VAE latent). The infra exists; this is mostly UX
+work to make the four-step flow a single tab.
+
+### `[ ]` Stacking-aware strength balance
+
+When a user stacks a style or scene LoRA on top of a character LoRA,
+the character's much-larger weight deltas at strength 1.0 dominate
+the style/scene LoRA at strength 1.0 and the style/scene effect
+disappears. UI fix: when a user adds a non-character LoRA on top of
+a character, auto-reduce `character_strength` to ~0.7 with a
+tooltip explaining why. Or expose a single "stylize this character"
+preset that handles the math.
+
+### `[ ]` Per-render TeaCache override on the form
+
+The new default TC=1.8 (reverted from a wrongly-calibrated 1.0 on
+2026-05-20) works well for most character renders, but power users
+may want to dial it for specific scenes. Expose `teacache_thresh`
+as a slider on the advanced section of the Generate form.
+
+### `[~]` IC-LoRA pipeline support — HDR ships first, generic infra follows
+
+Research summary (`/tmp/phosphene-walk/ic_vs_id_lora_research.md`):
+IC-LoRA is just a regular LoRA delta + a training-data trick + an
+inference-time input contract. The DiT itself isn't modified — what
+changes is that reference frames are concatenated to noise tokens along
+the sequence axis at negative RoPE positions, and the LoRA learns to
+copy structure / identity / look from one half to the other via
+attention. The HDR LoRA additionally bakes a LogC3 inverse transform
+into the decode path to recover 16-bit linear HDR from the VAE's
+`[-1, 1]` output range. The upstream MLX port already has the pieces:
+
+- `ltx_pipelines_mlx.ic_lora.ICLoraPipeline` — generic IC-LoRA pipeline
+- `ltx_pipelines_mlx.hdr_ic_lora.HDRICLoraPipeline` — HDR subclass that
+ auto-detects the LogC3 config from LoRA safetensors metadata and
+ saves both an SDR MP4 preview + a companion `.hdr.npz` float32 HDR
+ tensor (F, H, W, 3 linear scene-light)
+- `ltx_pipelines_mlx.iclora_utils.append_ic_lora_reference_video_conditionings`
+ — handles reference-video encoding + RoPE positioning. Tolerates an
+ empty `video_conditioning=[]` (text-driven mode: LoRA delta still
+ applies, no IC reference needed).
+
+Plan in phases, each shippable on its own:
+
+**Phase 1 — HDR text-driven mode (PLUMBING SHIPPED, BUTTON PULLED).**
+The full plumbing landed in v3.0 dev: `generate_hdr` helper action,
+`HDRICLoraPipeline` wiring, panel routing, all working end-to-end.
+But the UI button was pulled 2026-05-21 (commit `<hdr-pull>`) because
+the killer use case is HDR + character — and that combo is
+architecturally unsound on the single-pass distilled path. Pure-text
+HDR isn't useful enough on its own to justify the button. Re-exposing
+the pill is a one-line un-comment at `mlx_ltx_panel.py:17441` once
+Phase 2 ships and the two-pass character flow works. The helper
+action stays callable via the HTTP API (`/run` with `hdr=on`) for any
+script that wants pure-text HDR today.
+
+**Correction discovered 2026-05-21:** The premise I worked from in
+the original phasing (character LoRAs trained against Q8 dev, HDR
+trained against distilled, deltas misaligned) was wrong. Verified by
+inspection:
+
+- Phosphene's lora_lab points the trainer at `mlx_models/ltx-2.3-mlx-q4/`
+ via `resolve_default_model_dir()`.
+- That directory contains ONLY `transformer-distilled.safetensors`
+ (no dev variant; the Q4 download filter excludes it).
+- The upstream `ltx_trainer_mlx.model_loader` picks transformer files
+ in order: `transformer.safetensors`, `transformer-distilled.safetensors`,
+ `transformer-dev.safetensors`.
+- → Character LoRAs are trained against the **distilled** checkpoint,
+ same base as HDR-IC. The combo on the distilled path stacks
+ CLEANLY — no fine-tune misalignment.
+
+The Phosphene-side comment calling the base "dev transformer" (still
+present at `lora_lab/train_character.py:742`) is historical confusion
+and should be updated.
+
+What this means for HDR + character:
+- The single-pass distilled-path combo (which Phase 1 plumbing
+ supports today) should produce a faithful character + HDR output.
+ The only quality cap is "distilled = 8 steps, HQ dev = ~30 steps"
+ — that's a generic speed/quality tradeoff on the distilled lane,
+ not an HDR-specific fidelity killer.
+- The "experimental" framing I baked into the UI pill tooltip was
+ overly cautious. When the pill comes back, drop that warning.
+- Phase 2 (two-pass re-grade) is still architecturally clean and
+ remains the path for HQ-quality character + HDR. But Phase 1
+ alone should now be acceptable for character work.
+
+The HDR button was still pulled for v3.0 (Mr Bizarro request — wants
+to ship the release and validate HDR separately), but it's a
+one-line un-comment to bring back once you want to test the
+single-pass distilled-path character + HDR combo.
+
+**Phase 2 — Two-pass character + HDR via SDR→HDR re-grade (HQ path).**
+This is what Mr Bizarro initially asked for. Workflow:
+ 1. User renders normally at Q8 dev with character LoRA → full
+ character fidelity SDR MP4.
+ 2. User clicks "Re-grade to HDR" on the output card (next to
+ Animate / Quality buttons).
+ 3. Panel queues a `generate_hdr` job with
+ `video_conditioning=[(source.mp4, 1.0)]` and `loras=[HDR-IC]`
+ (NO character LoRA — character is baked into the SDR reference
+ latents).
+ 4. HDRICLoraPipeline reads the SDR video, encodes it as the IC
+ reference, generates a HDR-graded version conditioned on the
+ reference latents. LogC3 inverse on decode → float32 scene-linear
+ `.hdr.npz` companion + a re-graded SDR preview MP4.
+Both stages use their natural base (Q8 dev for character, distilled
+for HDR-IC). Character fidelity survives because the SDR reference
+carries the identity through to the HDR stage as conditioning, not
+as a fused LoRA delta. This is also the Lightricks-recommended
+workflow per the HDR LoRA's own README ("video conversion from 8 bit
+SDR to 16 bit HDR").
+
+Once Phase 2 ships, re-expose the HDR pill (which becomes "Re-grade
+to HDR" on output cards rather than a pre-submit form toggle).
+
+**Phase 3 — Motion-Track and Union-Control IC-LoRAs.** Two more
+Lightricks IC-LoRAs at `Lightricks/LTX-2.3-22b-IC-LoRA-Motion-Track-Control`
+and `Lightricks/LTX-2.3-22b-IC-LoRA-Union-Control`. Both need a
+reference video with specific conditioning content (motion-track
+needs sparse colored splines from a tracker like SpatialTrackerV2;
+union-control needs canny+depth+pose). For Phosphene users this
+means we need to either (a) ship spline/depth/pose extractors as a
+pre-processing pass, or (b) accept user-provided reference videos.
+Likely (b) for v3.x, (a) as a stretch.
+
+**Phase 4 — IC-LoRA training.** Extend `lora_lab` with a paired-dataset
+trainer. Each sample is `(reference_clip, target_clip)`. Training loop
+builds `concat(ref_tokens_at_negative_RoPE, target_tokens)` and
+computes loss only on the target half. LoRA weights file stays a
+normal `.safetensors`. Add `train_type='iclora'` to the trainer UI.
+
+**Phase 5 — Character + IC-LoRA stacking.** The prize: stack a
+character LoRA (face identity) with an IC-LoRA (e.g. Union-Control)
+on the same DiT. Both are weight deltas so it's mechanically possible,
+but untested upstream — deltas may fight, distilled-only constraint
+limits to balanced quality. Experimental; gate behind a flag until
+results are validated.
+
+**Naming note.** Don't conflate "ID-LoRA" with "character LoRA".
+The published ID-LoRA (arXiv 2603.10256) is actually an IC-LoRA that
+conditions on a reference image + ~5s audio for talking-head video.
+Phosphene's character LoRAs are plain weight-delta LoRAs trained on
+15-50 photos with a trigger word — Lightricks calls these "character
+LoRAs" formally, never "ID-LoRA". Keep "character LoRA" in code and
+UI to avoid the collision.
+
+Tracking: the HDR-specific Phase 1 work landed via re-exposing the
+hdr toggle (commit `<hdr-ship>`); the generic Phases 2–5 stay open
+in this entry.
+
+### `[x]` I2V Balanced + Extend perf — post-decode hang (FIXED 2026-05-21)
+
+**Fix shipped: panel-side watchdog SIGKILLs hung helper from outside
+the GIL-blocked process.** See commit `94bd696`. Detail below kept
+for posterity + so the next person to hit something MLX-deallocator-
+shaped knows where to look.
+
+After the May 9 upstream `ltx-2-mlx` refactor, I2V Balanced (and T2V
+Balanced) route through `DistilledPipeline.generate_two_stage(image=...)`.
+The actual render completed in ~3 min for a 5s I2V at 1024×576, but
+the helper then hung 5-15 min before signaling done to the panel.
+Extend exhibited the EXACT SAME hang on `ExtendPipeline`.
+
+The first fix attempt (commit `adc1cd2`, reverted) shipped an
+in-helper daemon-thread watchdog. **It does not work**: Metal's
+command-buffer completion handlers block every Python thread's GIL
+access during the deallocator chain, so the watchdog thread is
+starved by the very thing it was meant to escape. Observed live:
+ps showed all 16 helper threads at 0% CPU during the hang.
+
+Working fix (commit `94bd696`): rescue from THE PANEL (separate
+process, no GIL contention with the helper). `WarmHelper.
+_build_post_decode_panic` returns a (log_hook, panic_check) pair
+honored by `_read_until`. The log_hook spots the decode-done log
+line and arms a 45s grace clock; if the helper is still silent
+after grace AND the output file is on disk, panic_check SIGKILLs
+the helper and returns a synthetic done event from the known
+output_path. Helper respawns on next job (~30s spawn cost).
+
+Validated end-to-end same evening on the previously-hung Extend
+case: 533s total wall, watchdog rescue logged exactly as designed.
+
+Diagnostic findings (2026-05-21 session):
+- Output mp4 IS written to disk before the hang starts.
+- Stack samples show the helper deep in Metal command-buffer
+ deallocation (`IOGPUMetalCommandBufferStorageDealloc`,
+ `MTLResourceList releaseAllObjectsAndReset`, etc).
+- Diagnostic prints placed AFTER `_decode_and_save_video()` never
+ fire — the function-return path itself is the hang. Most likely
+ MLX/Metal completion-handler chains holding the GIL through
+ Python frame teardown.
+- LTX2_DIT_EVAL_EVERY tuning has no effect (tested 0/1/4/8).
+- A2V (A2VidPipelineTwoStage), FFLF, T2V Character HQ
+ (TI2VidTwoStagesHQPipeline) all return cleanly — confirming the
+ hang is specific to the distilled-fused-then-decode pattern.
+
+**Symptom-level fix shipped 2026-05-21** (commit `94bd696` — panel-
+side watchdog SIGKILLs hung helper). Quality-level work still open:
+
+1. **For Q8 (≥48 GB) tiers:** route Balanced I2V/T2V through
+ `TI2VidTwoStagesPipeline` instead of `DistilledPipeline`. That class:
+ - Runs full-resolution, not half-res with Stage-2 upscale.
+ - Supports CFG (`cfg_scale=3.0` validated).
+ - Supports TeaCache (`enable_teacache=True, teacache_thresh=N`).
+ - Already used by the working HQ path.
+ The helper's `get_pipe('i2v', ...)` currently aliases to
+ DistilledPipeline; needs an explicit branch for Balanced→
+ TI2VidTwoStagesPipeline on the dev model. Eliminates the hang
+ entirely (TI2VidTwoStages doesn't trigger it) AND gives better
+ I2V quality on the distilled-grid artifact #5 users see.
+2. **For Q4 (<48 GB) tiers:** the panel watchdog now hides the
+ hang from users (file lands, panel reports done, helper
+ respawns). Quality fix still needs the same TI2VidTwoStages
+ route on Q4 weights — but until then, watchdog rescue makes
+ the symptom invisible.
+3. **Reddit / issue #5** users on small Macs are hitting both this
+ hang AND the geometric-grid artifact (which is the DistilledPipeline
+ structure producing weak I2V on the distilled checkpoint). The
+ hang is now invisible; the artifact still requires the Q8/Q4
+ TI2VidTwoStages route above.
+
+## Mid term
+
+### `[ ]` In-panel "Report bug" button
+
+Auto-zip recent panel log + system info + the most recent failed
+sidecar, pre-fill a GitHub issue. Cuts the support loop from
+"please paste the panel log" to one click. (Tracked partly via
+issue #2 — Akossimon's pain point.)
+
+### `[ ]` Aspect-bucketed single LoRA (alternative to three modalities)
+
+Instead of training three separate LoRAs per character, train ONE
+LoRA on a mix of aspect crops. Robust to any inference aspect at
+the cost of slightly weaker per-aspect identity capture. Worth
+benchmarking against the three-modality approach once both are
+implemented.
+
+### `[ ]` Audio-only LoRA training (voice without face)
+
+The voice LoRA phase already runs as a sub-step of character
+training. Expose it as a standalone train_type so a user can train
+just a voice (e.g. clone a podcast host's delivery) without
+gathering face photos.
+
+### `[ ]` HiDream as a panel-internal install
+
+HiDream-O1-Image-Dev currently requires a separate one-time clone
+of the HIDREAM lab repo into `$HIDREAM_LAB_DIR`. Move this to a
+standard Pinokio install button so it's one-click parity with the
+mflux Qwen-Edit install.
+
+### `[ ]` /queue/retry preserves character_strength
+
+Currently `/queue/retry` rebuilds the form with `character_id` +
+`quality` + `loras` but not `character_strength`. Once strength
+balancing is exposed in the UI, retries need to round-trip it.
+
+## Longer term
+
+### `[ ]` Multi-keyframe interpolation surface
+
+The SDK supports multi-keyframe interpolation (see
+`docs/SDK_KEYFRAME_INTERPOLATION.md`). The panel exposes only the
+first/last frame mode. Building a proper multi-keyframe timeline
+UI would unlock storyboarding workflows.
+
+### `[ ]` LoRA marketplace integration
+
+CivitAI browsing already works for downloading LTX 2.3 LoRAs.
+Adding upload (publish your trained Phosphene LoRA to CivitAI in
+one click, with sidecar metadata auto-populated) closes the loop.
+
+### `[ ]` Hosted-cloud rendering fallback
+
+Some users run on Apple Silicon Macs that are too small for Q8 HQ.
+A "render this on a beefier rented box" option (BYO HF Inference
+Endpoint or Replicate) would let them author character LoRAs
+locally and render at HQ remotely. Strictly opt-in — Phosphene's
+core promise is local + no cloud + no API key, so this would live
+behind a clearly-labeled flag.
+
+## Won't do (until proven otherwise)
+
+### `[x] no cuda fallback`
+
+Phosphene is Apple Silicon + MLX by design. The performance and
+unified-memory advantages on M-series chips are the entire reason
+the project exists. A CUDA port would be a different project.
+
+### `[x] no Windows / Linux build`
+
+Same reason as above. MLX is Apple-only by Apple's design.
+
+---
+
+If you'd like to contribute to one of the planned items, the GitHub
+issues at https://github.com/mrbizarro/phosphene/issues are the right
+place — comment on a tracking issue or open a new one referencing the
+roadmap entry you're picking up.
diff --git a/VERSION b/VERSION
index de9a551..2da4316 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-4.9.8
+4.10.0
diff --git a/assets/the_commuter_hero.gif b/assets/the_commuter_hero.gif
new file mode 100644
index 0000000..3a7c8d5
Binary files /dev/null and b/assets/the_commuter_hero.gif differ
diff --git a/assets/the_commuter_poster.jpg b/assets/the_commuter_poster.jpg
new file mode 100644
index 0000000..02108b7
Binary files /dev/null and b/assets/the_commuter_poster.jpg differ
diff --git a/docs/API.md b/docs/API.md
index a649a7c..b85ae5f 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -57,7 +57,9 @@ Add a job to the panel's queue. Returns immediately; the helper renders it async
| `image` | path | I2V only. Absolute path to a reference PNG/JPG. **Required** — since v4.6.1 an omitted or empty `image` on `i2v` / `i2v_clean_audio` is refused at job start with a readable error instead of defaulting to `examples/reference.png`, a demo file no install has ever shipped (that default was the widest-spread render failure in the fleet: `image not found: <path>`, 35 events across 22 people in 14 days). `LTX_DEFAULT_IMAGE` still supplies a default when it points at a file that actually exists. |
| `audio` | path | Optional audio reference. |
| `label` | string | Optional UI label for the queue card. |
-| `temporal_mode` | `native` \| (tiled modes) | `native` for normal jobs. |
+| `temporal_mode` | `native` \| `fps12_interp24` \| `windows`. **`windows`** renders past one 121-frame window as a SEQUENCE — one `generate`, then one `extend` per later window on the kept tail of the last (`ltx_windows.py`: `stride = window - discard - overlap`, `count = 1 + ceil((total - window + discard) / stride)`), trimmed to the asked length. Needs the Q8 add-on and a tier that allows Extend; refused with a sentence otherwise. Stored on the job as `long_mode`. |
+| `window_prompts` | JSON array (or newline-separated) of one line per window; line 1 blank = the prompt; a later blank line holds the previous moment. Each later window's prompt is its line FIRST, then the continuation clause, then `Throughout: <window_invariants>.` — the H3 chain contract, and the lead-with-the-move rule. |
+| `window_invariants` | What must not change between windows (who, where, light, lens). Re-injected into every later window. |
| `loras` | JSON-encoded array | See LoRA payload below. |
**LoRA payload:** the `loras` field is a JSON-encoded array of `{path, strength}` objects. Stack as many as needed:
@@ -135,8 +137,32 @@ Submit multiple prompts as one batch.
## Status — poll job state
+### One take — `take_seconds` + `beats` on `POST /queue/add`
+
+A clip longer than a single pass, on either engine. `take_seconds` is one of
+30 / 45 / 60 / 90 / 120; `beats` is a JSON list (or newline text) with one
+prompt per five seconds — a blank beat holds the previous moment, extras are
+dropped. The take overrules the engine's own length field:
+
+| engine | what make_job does | worker |
+|---|---|---|
+| `ltx` | `long_mode=windows`, `frames = seconds·24+1`, `window_prompts = beats` | the windows chain (needs the Q8 pack) |
+| `h3` | `h3_length=15s`, parts of three beats | `run_take_job_inner`: one ordinary H3 render per part, each starting from the last frame of the one before (`--first-frame`), parts hidden from the gallery, joined into `<name>_take<seconds>s.mp4` with a sidecar carrying `take.{seconds,beats,parts}` |
+
+`params.take` on the job: `{seconds, beats, parts, frames, engine, beat_prompts}`.
+Load Params restores a take as a take.
+
+### `GET /take/estimate`
+
+`?engine=h3|ltx&quality=<engine quality key>&seconds=<take_seconds>` →
+`{ ok, seconds, beats, parts, engine, frames, minutes, eta, needs_q8 }`. Minutes
+come from the same cost model as every other estimate (H3: the measured 15 s
+cell × parts); `null` where this Mac has no number (LTX windows are unpriced).
+
### `GET /status`
+Every `outputs[]` row carries `q`: the output's searchable words, lower-cased, built from its sidecar in the listing pass that already reads it — prompt, label, mode, quality, engine, character, seed, `WxH`, `Nf`, LoRA file stems, the model directory name, the temporal mode and `windows`. The gallery's search box is a substring test over `name + q`; every typed word must match, and typing pulls the older outputs in so the search is over everything.
+
Returns the full panel state.
```json
@@ -223,6 +249,34 @@ Callers should surface `weak` **before** a render is spent finding out, and shou
`GET /train/list` carries the same verdict plus **`adapter_advice`** — one sentence naming what to do about it, empty when the verdict is `ok` or `unknown`. It is hardware-aware: on a sub-64 GB Mac it does **not** say "train again on High", because that machine cannot reach the graded recipe (see the profile section below). The panel's Train tab renders it as a banner above the trained-character chips and in the finished job's history row; a verdict a user cannot act on is a measurement, not an answer (#62).
+### `GET /loras/updates`
+
+Asks CivitAI whether any installed LoRA with a `civitai_id` in its sidecar has a
+newer version (`modelVersions[0].id` ≠ the sidecar's `civitai_version_id`). One
+request per such LoRA; nothing is downloaded.
+
+```jsonc
+{ "ok": true, "checked": 3,
+ "items": [ { "path": "...", "name": "...", "current_version_id": 1, "latest_version_id": 2,
+ "latest_version_name": "v2", "published_at": "...", "base_model": "LTXV 2.3",
+ "download_url": "...", // what /civitai/download takes
+ "meta": { ... } } ], // the sidecar the download will write
+ "errors": [ { "path": "...", "error": "..." } ] }
+```
+
+Installing the update is the ordinary `POST /civitai/download` with that
+`download_url` + `meta`; the new file lands beside the old one, which stays
+until deleted.
+
+### `POST /loras/guide`
+
+Form: `path` (an installed LoRA from `GET /loras`). The planner model writes a
+one-paragraph guide — what the LoRA does, how to prompt it, a strength to start
+from, what it fights with — from the sidecar's own name / description / trigger
+words, and saves it in the sidecar under `guide`; `GET /loras` rows then carry
+`guide`. Refused with 409 while a render runs (the planner is a 12B model).
+Returns `{ ok, guide }`.
+
### `POST /loras/refresh`
Re-scan `mlx_models/loras/`. Returns the same payload as `/loras`.
@@ -485,8 +539,28 @@ A **board** is a film: a concept, a cast, locations, and a numbered shot list. E
| `GET /storyboard/get?id=<bid>` | One board document. |
| `GET /storyboard/films` | The assembled films on disk — player path, runtime, picture size, size on disk, when it was made. `list_outputs` globs `OUTPUT/*.mp4` and never descends, so without this the one thing the feature makes is the one thing the app cannot show you. |
+### Brief switches (on `plan`)
+
+| Field | Board key | Effect |
+|---|---|---|
+| `auto` | `auto` | after the plan: render every shot, cut, assemble — no more buttons |
+| `anchor_stills` | `anchor_stills` | before a text/character shot renders, an ordinary image job makes its first frame (`still_job_id` → `still`; the character's sheet is the reference through `qwen_edit_inline` when it exists) and the clip renders as **i2v · anchor** from it. A still that fails sets `still_error` and the shot renders unanchored, once |
+| `long_windows` | `long_windows` | an LTX shot longer than 121 frames renders as `temporal_mode=windows` (a chain on the Q8 dev transformer) with the board's style and the shot's location as `window_invariants`, instead of being cut to fit. Extend cannot re-inject an image per window, so an anchored long shot is anchored by its first window only |
+| `take_seconds` | `take_seconds` | **one take**: the film is one shot of 30 / 45 / 60 / 90 / 120 s. The planner writes one beat per 5 s (`_sb_take_concept`), the board keeps ONE shot with `beats` (`collapse_take`), the card shows the beats for editing, and `shot_to_job` posts `take_seconds` + `beats` — the Video tab's take, so the render is the same on both doors. `0` turns it off |
+
+Each field is patched only when sent; an absent field keeps the board's value.
+
+`POST /storyboard/restill` — form `id`, `n`, optional `pass`: forgets shot `n`'s
+still and the clip rendered from it, turns `anchor_stills` on if it was off,
+and renders that shot alone (the still first, then the clip from it). Same
+refusals as `render` (planning, already rendering).
+
### Write — `POST /storyboard/<action>`
+**The Director.** `plan` accepts `soundtrack` (an audio file on this Mac) and `bars_per_shot` (1/2/4, default 2). With a track the plan is a MUSIC VIDEO: `beat_map()` — the same fit the Editor's Prepare runs — turns the downbeats into slots of `bars_per_shot` bars, the shot count is the slot count (the `shots` chips stand down; capped at `STORYBOARD_MAX_SHOTS` with a note), the planner's brief carries the bpm, the slot length, an arc instruction and two laws (begin every description with the movement; no dialogue, the track replaces every clip's sound), and each planned shot's `duration_s` is its slot plus a one-second handle, with `slot: {start, end}` on the shot. **The song map decides how often.** `song_map()` (storyboard_edit) puts SECTIONS on the same bar grid — `{start, end, label, energy, brightness}` with labels intro / verse / chorus / bridge / outro from position, relative loudness and brightness — and `director_pacing()` turns `bars_per_shot` into a per-section stride: the chorus cuts twice as often, the intro and outro half as often. Each slot carries its `section`; the brief tells the planner which shots fall in which section and how hot it is; a track the map cannot read is cut at the base stride and the log says so. The board records `soundtrack: {path, bpm, bars_per_shot, total_sec, count, slots, sections}`, the Editor's first auto-cut uses that track when Prepare has not cached another — so the film opens already cut on the beat — and `GET /storyboard/edit` returns `sections` so the ruler can paint the arc. A bad path is a 400 before the planner runs; the planner stage `grid` is reported while the beat is read.
+
+**Auto.** `plan` accepts `auto=1`: when the plan lands the draft render of every shot starts on its own (`_sb_auto_after_plan`, once the planner has given the memory back), and when the render thread finishes with every shot rendered the film is cut (`_sbe_auto_edit` — on the beat when there is a track) and assembled by the same assembler Render uses (`_sb_auto_film`); the board records `auto_film`. A shot that did not render leaves the film waiting and the log says how many. Stop still stops the render; the cut and the film are the ordinary ones and can be re-cut afterwards.
+
Form-encoded unless noted. `id` is the board id throughout.
| Action | Fields | Note |
@@ -563,7 +637,7 @@ The Editor is a **top-level workflow**, not a stage of the storyboard: engine-ag
|---|---|---|
| `prepare` | `id`, `music`, `target_seconds` | Build proxies + peaks. `400` if `music` is not a file. |
| `add-clip` | `id`, `from`, `only`, `path`, `title`, `kind` | `kind` is `video` \| `still` \| `slug` — passing it is what stops an image landing as a video with no frames. |
-| `relink` | `id` | Re-point clips at files that moved. |
+| `relink` | `id`, `only` | Re-point clips at their finished (delivery) files. **A finished RETAKE is never part of that batch** — it is offered against its clip with `retake: true` in the payload's `relink` rows and adopted one clip at a time with `only=<clip id>`. |
| `cancel` | `id` | Cancel the prepare job. |
| `auto` | `id`, `music`, `target_seconds`, `min_shot`, `max_shot` | Re-run the machine's cut. Lands in the **automatic** lane. |
| `save` | JSON `{id, edit, expect_revision?}` | See below. |
@@ -573,10 +647,10 @@ The Editor is a **top-level workflow**, not a stage of the storyboard: engine-ag
| `discard-backup` | `id` | Throw it away. |
| `version` | `id`, `label` | Name a version. **Naming is not saving** — no revision bump, no write to `edit.json`, nothing about the timeline changes, which is exactly why it is safe to press at any moment. |
| `restore` | `id`, `file` | Restore a history entry. Refuses while the film renders. |
-| `render` | `id`, `out`, `music`, `music_mode` | Assemble the film. `music_mode` is `replace` \| `under`. |
+| `render` | `id`, `out`, `music`, `music_mode`, `format`, `size` | Assemble the film. `music_mode` is `replace` \| `under`. **Deliver as:** `format` is `h264` (default, the panel's preset) \| `hevc` (VideoToolbox, `hvc1`, about half the bytes) \| `prores` (422 HQ, 10-bit 4:2:2, PCM sound, a `.mov` no browser previews); `size` is `native` (as cut) \| `1080p` \| `2160p` — one Lanczos scale after the overlays, up only, never a crop, skipped when the cut is already that height. `finish` is `none` \| `grain` \| `heavy_grain` — moving film grain (`noise` t+u, strength 9 / 18) added AFTER the size so a 4K delivery gets 4K grain; a delivery-time treatment, never in the document, never in the preview or the export. A different delivery is a different file: `<slug>_film_hevc_1080p.mp4`, `<slug>_film_prores.mov`, `<slug>_film_1080p_grain.mp4`. The facts carry `deliver: {format, size, finish, label}`. |
| `export-nle` | `id` | FCP7 XML + After Effects JSX + linked media. |
| `reveal` | `id`, `what` | Show in Finder. |
-| `generate` | `id`, `prompt`, `duration`, `duration_s`, `film_start`, `pass`, `character_id`, `seed`, `title`, `engine`, `trigger` | Shoot a new clip straight into a slot. |
+| `generate` | `id`, `prompt`, `duration`, `duration_s`, `film_start`, `pass`, `character_id`, `seed`, `title`, `engine`, `trigger`, `retake_of` | Shoot a new clip straight into a slot. With `retake_of=<clip id>` it is a **retake**: the clip's own shot is CLONED (character, refs, location, engine) and only the prompt, the length and the seed change; the new shot carries `edit_slot.retake_of`, and when it renders the Editor offers it against that clip ("Use it" / "Keep the old one"). 400 if the clip is no longer on the timeline. |
**`save` semantics.** `revision` is the **server's** counter, taken from disk, never from what the client remembered — a stale tab must not be able to wind it backwards. Pass `expect_revision` to find out you were overtaken instead of silently overwriting the other tab: mismatch returns **`409` with `conflict: true`** and the current revision. Validation errors come back as **all of them at once** (`errors: [...]`, `400`) with the file on disk untouched, so a client can highlight every bad clip in one pass instead of playing whack-a-mole.
@@ -610,6 +684,8 @@ The Editor is a **top-level workflow**, not a stage of the storyboard: engine-ag
| `source` | `auto` \| `human`. |
| `locked` | bool. |
| `adjust` | `{brightness}`, an ffmpeg `eq=brightness` additive offset clamped to ±`BRIGHTNESS_LIMIT` (0.5). **Neutral is absent** — dragging the slider back to zero leaves a document identical to one that never had a slider. |
+| `frame` | `{zoom, x, y}` — a reframe. The picture is magnified `zoom` times (1–3) and the window is centred at the fraction (`x`, `y`) of the source. Render: a `crop` of the source's own pixels before the fit, so one string is right at every size; preview: a CSS scale about the same anchor (approximate); export: FCP7 Basic Motion (scale + centre) and AE scale + position. **Neutral is absent**; a slug has nothing to reframe. |
+| `speed` | Play rate, `SPEED_MIN`–`SPEED_MAX` (0.25–4.0), video only. The slot is `(end - start) / speed`, so the 1x rule above reads "at its speed". Picture is `setpts`, sound is `atempo` chained past ffmpeg's 0.5–2.0 window, and the sound's envelope (`afx`) stays on the strip's PLAYED clock — a keyframe at 2 s is still at 2 s of the strip after a retime. **Absent is 1x.** Never set automatically. |
| `audio` | The split edit. See below. |
#### `clip.audio` — the J-cut and the L-cut
@@ -626,6 +702,30 @@ Video clips only. Same three numbers as the picture, for the SOUND — so the so
Audio windows may not overlap each other any more than the pictures may. This is still one video track and one music lane — a split edit is a butt join that lands somewhere else, not a mix.
+#### `transitions[]` — a typed object that owns a BOUNDARY
+
+```jsonc
+"transitions": [{"id": "t1", "after_clip": "<clip id>",
+ "kind": "dissolve" | "fade_black", "duration": 0.5}]
+```
+
+A cross-dissolve is two clips in the same second, and the picture lane's one-clip-at-a-time rule (`clips_overlap`) is load-bearing — so a transition is **not** an overlap. It names the OUTGOING clip and sits on the cut between it and its successor in film order; one per boundary. **The clips' own `film_start`/`film_end` do not move** and the film stays exactly as long as the timeline says. The render pulls half the duration of extra tail from beyond the outgoing clip's out-point and half of extra head from before the incoming clip's in-point (source the trims left behind), splits the picture concat at the boundary and joins the two runs with `xfade` (`fade` / `fadeblack`) centred on the cut. The sound needs nothing new: it takes the lane path (`_sb_split_audio_plan`) exactly as a J-cut does.
+
+`duration` is clamped on every read (`transition_duration`) to `min(asked, half the shorter neighbour, 2.0 s)` and snapped to an even number of frames; the document keeps the number typed. A side with no spare material is refused — `transition_no_handles` names the side and the shortfall ("clip 2 has only 0.10s before its in-point and the dissolve needs 0.25s there"). Every transition code (`transitions_shape`, `transition_shape`, `transition_unknown_clip`, `transition_last_clip`, `transition_duplicate_boundary`, `transition_kind`, `transition_duration`, `transition_no_handles`) is an **error**; none is in `WARNING_CODES`. `render` refuses with the same sentence. A still and a slug have all the handles anybody could ask for.
+
+#### `overlays[]` — cards, mattes, and titles
+
+`kind` is `still` | `video` | `text`. An explicit `kind` wins; with none, the path's suffix decides (`.png`/`.webp`/`.tif` are stills), so every overlay written before titles existed reads as it did. A **title** is an overlay whose pixels the render draws:
+
+```jsonc
+{"id": "o1", "kind": "text", "text": "FIN", "film_start": 40.0, "film_end": 44.0,
+ "style": {"font_size": 96, "color": "#ffffff", "align": "center", "x": 0.5, "y": 0.8,
+ "box": true, "box_color": "#000000", "box_opacity": 0.5},
+ "fx": {"fade_in": 0.5, "fade_out": 0.5}}
+```
+
+`font_size` is px at a 1080-high frame and scales with the film; `x`/`y` are the anchor as fractions of the frame; `align` says which edge of the text sits on `x`. `overlay_text()` is the one accessor and the style is written only where it differs from the defaults. The font is a FILE — `LTX_TITLE_FONT`, else the first of `TITLE_FONT_CANDIDATES` present on the machine — verified before ffmpeg is built; with none, `render` answers 400 with a sentence rather than a film with a hole in it. The raster is a frame-sized RGBA PNG beside the film (`.titles/`) fed through the same overlay chain as an uploaded card, so a title inherits the lane's alpha, fades and z-order. Titles are drawn on the stage in the DOM at the same anchor and size; they do not travel in the NLE export (no path).
+
#### `audio` — the soundtrack, as an object on the timeline
```jsonc
@@ -702,11 +802,34 @@ Shut down a ComfyUI process if Phosphene started one.
Self-update against the GitHub repo.
+## Push alerts — the completion alert for a closed tab
+
+The in-tab chime and browser alert (Settings → Completion alerts) need the page
+open. Web Push does not: the browser keeps a subscription for this origin, the
+panel signs each message with a VAPID key pair it generates once
+(`state/vapid.json`), and the browser's push service wakes `/sw.js` to show the
+notification. No relay: the panel posts straight to the browser vendor. Offered
+only when `pywebpush` imports (`GET /settings` → `push_available`).
+
+| Route | What |
+|---|---|
+| `GET /sw.js` | the service worker, served from the root scope with `Service-Worker-Allowed: /` |
+| `GET /push/key` | `{ ok, available, public_key, subscriptions }` — the VAPID public key the browser subscribes with (503 when unavailable) |
+| `POST /push/subscribe` | form `subscription` = the `PushSubscription` JSON; one entry per endpoint |
+| `POST /push/unsubscribe` | form `endpoint` |
+| `POST /push/test` | sends "This is what a finished render will say." to every subscriber; `{ ok, sent }` |
+
+Every job that ends `done` or `failed` pushes `Phosphene — render done` /
+`— a render failed` with the job's label (or the first 60 characters of its
+prompt), off the GPU lock, only while `notify_done` is on. A subscription the
+vendor reports gone (404 / 410) is dropped.
+
### `POST /settings`
| Field | Type | Note |
|---|---|---|
| (any setting key) | string | See `state/panel_settings.json` for the canonical set. |
+| `notify_done` | `1`/`0` | Completion alerts: a chime in the tab when a render finishes or fails, and a browser notification when the tab is in the background and the person has allowed them. Default on; `GET /settings` returns it. |
### `POST /prompt/enhance`
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 050a434..ed583ef 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -38,6 +38,12 @@ webapp/ ← the frontend, as plain files served from disk
└── panel.css ← ALL panel CSS (slice 1, landed)
mlx_warm_helper.py ← the render subprocess (JSON over stdin/stdout);
not part of the web frontend at all
+ltx_windows.py ← PURE: the sliding-window schedule and per-window
+ prompt contract for long LTX clips; the panel turns
+ it into one generate + N extend calls
+storyboard_editor.py ← the Editor's document model: clips, overlays
+ (cards and titles), transitions, the mix — every
+ accessor the preview, render and export share
panel_assets/
└── stats.html ← the /stats dashboard (predates webapp/; same
served-from-disk idea)
diff --git a/docs/EDITOR_EFFECTS_MODEL.md b/docs/EDITOR_EFFECTS_MODEL.md
index 9930874..5a0e877 100644
--- a/docs/EDITOR_EFFECTS_MODEL.md
+++ b/docs/EDITOR_EFFECTS_MODEL.md
@@ -238,6 +238,83 @@ the bed and its duck stay consistent with each other and with the preview,
and both are displaced together by exactly the amount `gaps_note` already
discloses. Fixing that means fixing the concatenation, not the mix.
+## Editor v2 — speed, titles, transitions (2026-09-05)
+
+Three more citizens of the same model, each expressed in all three outputs
+or honestly declared where one cannot carry it.
+
+### Speed — on the clip
+
+`clip.speed`, 0.25–4.0, video only, **absent is 1x, never automatic** (the
+owner's verdict on a slowed shot that read as an accident was "too slow-mo").
+`clip_speed()` is the accessor; `sbeLen` / `clip_length` divide by it, so the
+slot is `(end - start) / speed` and everything downstream that measures the
+film reads the played length. **Preview**: `<video>.playbackRate`, and the strip
+player's too. **Render**: `setpts=(PTS-STARTPTS)/speed` on the picture, `atempo`
+chained past ffmpeg's 0.5–2.0 window on the sound, the same `apad,atrim` tail
+to the played length. **Export**: carried as `speed` on the row; the FCP7 XML's
+in/out and start/end already disagree by that ratio, which is how an importer
+infers a speed change — no explicit Time Remap effect is written.
+
+**The envelope's clock does not move.** `afx` fades and points are seconds of
+the strip AS PLAYED; `audio_gain_points()` documents why (the `volume` term
+runs after `atempo`, and a fade of "1 s" was typed in film seconds). A keyframe
+at 2 s is at 2 s of the strip after a retime; the strip is what changed length.
+
+### Titles — on the overlay lane
+
+An overlay with `kind: "text"` — a card the render DRAWS. `overlay_text()`
+returns `{text, style}` clamped, `style` is written only where it differs from
+`TEXT_STYLE_DEFAULTS`. **Preview**: a DOM element on the stage at the same
+anchor (`x`/`y` fractions of the frame) and the same size rule (`font_size` at
+1080 high, scaled to the stage). **Render**: a frame-sized RGBA PNG rasterised
+with Pillow from an explicitly resolved font FILE, verified BEFORE ffmpeg is
+built, fed through the very overlay chain an uploaded card takes — so fades,
+z-order and the one-lane rule come free. Not `drawtext`: that filter is a
+build option and the Homebrew ffmpeg this panel resolves on the author's own
+machine does not carry it. **Export**: not carried (a title has no path); the
+lane skips it and says nothing false.
+
+### Transitions — on the cut
+
+The hard one, and the one the picture-lane rule forbade as an overlap. A
+transition is a **typed object that owns a boundary** (`transitions[]`,
+`after_clip`), never a second picture in the same second: the clips' slots do
+not move, the film is exactly as long as the timeline, and the render gets its
+overlap from SOURCE HANDLES — half the duration of extra tail past the outgoing
+out-point, half of extra head before the incoming in-point, centred on the cut,
+the way an NLE builds one. No handles, no transition: `transition_no_handles`
+names the side and the shortfall, in the validator and again at `render`. Every
+transition code is an error; `WARNING_CODES` is untouched.
+
+**Preview**: the stage has ONE `<video>`, so a dissolve is previewed as a ramp
+through black on both sides of the cut (exact for `fade_black`, an honest
+approximation for `dissolve`, and the inspector says so). **Render**: the
+picture concat is split at the boundary into runs and re-joined with `xfade`
+(`fade` / `fadeblack`); the sound takes the lane path it already had for J-cuts
+and is byte-for-byte unchanged. **Export**: not carried yet — the cut is
+exported as a butt join.
+
+**Where it lives on screen**: the boundary. A small mark on every cut, a band
+the length of the transition once one exists, the inspector to set kind and
+length. No lane, no panel.
+
+### Framing — a zoom and a reframe, per clip
+
+`clip.frame = {zoom, x, y}`, zoom 1–3, the window centred at the fraction
+(x, y) of the source; `clip_frame()` is the accessor, neutral is absent, a
+slug has nothing to reframe. **Preview**: the stage layer scaled about the
+same anchor (CSS, approximate — the render is exact). **Render**: `crop` of
+the source's own pixels, before `fps`/`scale`, expressed with `iw`/`ih` so
+the same string serves a 640-wide draft and a 1280-wide delivery, even-sized
+for 4:2:0. **Export**: FCP7 Basic Motion (scale %, centre = `zoom·(0.5−x)`
+frame widths) and AE scale + position — the decision, not baked pixels.
+
+### Markers — deliberately not built
+
+They are for hour-long timelines; ours are ~90 s and cut to a beat grid the
+panel computes. Adding them would be copying without a reason.
+
## What is deliberately not built yet
* **Overlay lane** (his headline want: an endcard PNG over the sky). It is the
diff --git a/docs/PROMPTING.md b/docs/PROMPTING.md
new file mode 100644
index 0000000..515abec
--- /dev/null
+++ b/docs/PROMPTING.md
@@ -0,0 +1,29 @@
+# Writing for Phosphene — the short version
+
+Copy this whole page into your own assistant (ChatGPT, Claude, Codex) and ask it to write your beats. The Storyboard planner already follows these rules on its own; this page is for when you write by hand.
+
+## One take (a clip longer than one pass)
+
+- **One beat = five seconds = one thing that happens.** Lead with the movement: what the subject does, what the camera does, what enters the frame.
+- **A scene change gets a beat of its own.** Going through a door, into a room, onto a bridge: give it its own five seconds, and put the *approach* in the beat before it. A scene change hidden at the end of a busy beat is the one the model skips.
+- **A reveal gets a beat of its own.** "The camera comes round to his face" works when it is the whole beat, not the tail of a beat that also carries the table, the wife and the hat.
+- **Settle before the turn.** The beat before a scene change or a reveal should slow down; the model needs a moment to land before it can pivot.
+- **Repeat the invariants every beat.** The subject's look, the camera position, the palette, the sound. The engine only remembers the last frame; the words carry the rest. Phosphene prepends your style block to every beat for you.
+- **Something new every second.** A near miss, an object entering, a light change. A beat that describes a mood and no event reads as a still.
+- **Sound is part of the shot.** Say what we hear: footsteps, a band from a doorway, rain on an awning. Without sound cues the audio is near-silent ambience.
+
+## Start from a still
+
+- Design frame one as an image first (Phosphene makes one for you, or bring your own). Composition, palette and character are decided on an image that takes seconds, not a clip that takes an hour.
+- Match the still's aspect to the shot canvas; the panel picks the nearest.
+
+## What not to write
+
+- No "fast forward", "time-lapse" or "montage" in a one-take: the model cuts.
+- No two subjects at once unless one of them is the point of the beat.
+- No text on screen; no lettering on signs unless you accept invented words.
+
+## Time and quality
+
+- H3 native (1344×768) with Turbo v4: about 31 minutes per 5 seconds on an M4 Max 64 GB. A minute is an evening.
+- A 5-second test at High (1024×576) costs 14 minutes. Test the first beat before you commit the night.
diff --git a/docs/STATE.md b/docs/STATE.md
index ecabff1..4640b80 100644
--- a/docs/STATE.md
+++ b/docs/STATE.md
@@ -1,5 +1,17 @@
# Phosphene — project state, history, open work
+> **🚀 2026-09-06 — v4.10.0 ships.** Everything on this branch since v4.9.5
+> goes public as one release: Editor v2 (transitions, speed, titles, the
+> Director + song map, retake, completion alerts, deliver-as, duplicate,
+> search, framing), the timeline's NLE gestures, anchor stills, long shots,
+> LoRA guides + update checks, closed-tab alerts, light theme, **One take**
+> on both engines, Turbo v4-600 EMA, the constant-time windows chain, and the
+> three 4.9.x hotfixes. The release media is *The Commuter*, a 75 s H3 one
+> take at native. Also in: `docs/PROMPTING.md` served at `/docs/prompting`
+> with a copy button; the planner's take brief carries the night's rules
+> (a scene change or a reveal is a beat of its own, a settle before it); H3
+> native exports are no longer shrunk to 720p by default.
+
> **🎬 2026-09-05 — Editor v2 on dev/beta, UNRELEASED: speed, titles, transitions, the Director, sliding windows.**
> From the long-form editing brief (the measured gaps only, built our way).
> **Transitions** are a typed object on a BOUNDARY (`transitions[]`,
@@ -116,6 +128,52 @@
> anchor (41 s), frame 0 = the still; `/loras/updates` found one real
> update (EditAnything → LTX 2.5 v2.0); `/loras/guide` wrote a real guide
> (6.5 s).
+> **Same day, ONE TAKE.** A 60 s H3 ride (a hen on a skateboard through
+> twelve city environments, camera behind her) was first made by a script
+> driving four 15 s jobs, each from the last frame of the one before. That
+> script is now the panel: the Video tab's "One take" row (30 s … 2 min) with
+> one beat per 5 s, prefilled from the prompt; `take_plan` / `take_beats` /
+> `take_estimate_minutes` in the panel; on LTX it is the windows chain, on H3
+> `run_take_job_inner` runs ordinary H3 renders per part and joins them; the
+> engine's own length pills lock while a take is on; `/take/estimate` prices
+> it (a minute at H3 high ≈ 3 h 50 on this Mac). No user copy says "windows",
+> "chain" or "passes". `test_take` pins the arithmetic, the make_job mapping
+> and the runner with a stubbed engine. The Storyboard has the same door:
+> a fifth chip on the Shots row, **1 · one take**, with a length; the planner
+> writes beats instead of shots, the board keeps one shot with the beats
+> (editable on the card), and it renders as the same take.
+> **Same day, the timeline learns the NLE contract.** Dragging a clip's body
+> moves that clip alone, between its neighbours, and stops at them; pulling an
+> edge changes that clip's length and leaves everything after it where it was
+> (a hole opens or closes). The old behaviour — every gesture repacked the
+> sequence and slid the whole tail — is a RIPPLE now: hold ⌘ (or Ctrl) while
+> dragging (a badge on the track says so); Shift still reorders. An edge is a
+> trim anywhere within 10 px of it. Drags re-apply from the pointerdown
+> snapshot so a clamped clip cannot creep through a neighbour. Seven timeline
+> scenarios that meant "slide the rest" now pass the ripple flag; two new ones
+> pin the defaults.
+> **Same evening, the windows chain runs in constant time.** Measured on a
+> 30 s LTX take at 640×448: window 2 took 10 min, window 3 17, window 4 26 —
+> each extend was handed the WHOLE clip so far and Extend encodes and
+> conditions on every frame it is given. `_run_windows_chain` now cuts the
+> last window (121 f, after the plan's discard) as the context for each
+> extend, keeps only the new frames of each pass as a piece, and joins the
+> pieces at the end (frame-exact `select` filters; the exact strings are
+> proven on a real clip in the test and by hand). A one-minute ride on H3
+> (four 15 s parts from each other's last frame) took 3 h 53 at 1024×576.
+> **Same evening, Turbo moves to the community's adapter.** larryvrh's
+> **v4 step-600 EMA** (780 MB, bare runner layout, sha `5f3a626c…a416d3`)
+> resolves FIRST in `H3_TURBO_LORA_CANDIDATES`; the LightX2V v1.0 repack,
+> the folded v0.1 and ckpt500 stay as fallbacks so no install loses Turbo.
+> Steps follow the adapter (`h3_turbo_steps`: 7 sigma points = 6 forwards for
+> v4, the card's sweet spot — 4 smears fast motion; 4 points for the 4-step
+> adapters), and `_h3_retune_turbo_estimates` re-prices every tier cell for
+> the installed adapter after the resolver exists (high_15s Turbo ~25 → ~44
+> min, native_15s ~57 min → ~1 h 44; honest, not optimistic). The managed
+> download fetches v4 from its author's repo, digest-pinned
+> (`H3_TURBO_ASSETS` / `_h3_turbo_asset`); the release asset stays reachable
+> by key. `test_h3_turbo_adapter` 13. A/B against exact and the old adapter
+> pending on the test panel.
> **🚨 2026-09-06 — v4.9.8: H3 install/update broken for everyone by a deleted HF repo — fixed.**
> `madebyollin/taeh3` on Hugging Face is gone (401/404); install_h3.js fetched
diff --git a/install.js b/install.js
index c69ef75..05213cf 100644
--- a/install.js
+++ b/install.js
@@ -442,7 +442,7 @@ module.exports = {
// only ever a transitive dep — if a future dep change drops it, the
// SSL_CERT_FILE path vanishes and ALL panel stdlib HTTPS breaks.
// Naming it here keeps the cert bundle guaranteed-present.
- "uv pip install --python env/bin/python certifi pillow numpy 'huggingface-hub>=1.5.0,<2.0' 'hf_transfer>=0.1.6' 'litellm>=1.83.14' 'smolagents>=1.24.0'",
+ "uv pip install --python env/bin/python certifi pillow numpy 'huggingface-hub>=1.5.0,<2.0' 'hf_transfer>=0.1.6' 'litellm>=1.83.14' 'smolagents>=1.24.0' 'pywebpush>=2.0'",
// v2.0.3: post-install confirmation that the local packages
// actually landed in site-packages. The Y1.034+ patch script's
// i2v target tolerates a missing ltx_pipelines_mlx — without
diff --git a/ltx_windows.py b/ltx_windows.py
new file mode 100644
index 0000000..f557856
--- /dev/null
+++ b/ltx_windows.py
@@ -0,0 +1,197 @@
+#!/usr/bin/env python3
+"""Sliding windows for LTX — the arithmetic and the per-window prompt contract.
+
+WHY THIS EXISTS. One LTX pass tops out at short clips: past 241 frames the
+panel falls back to `fps12_interp24` (fewer model frames, interpolated back to
+24). H3 already chains windows; LTX did not. What turns 10-second clips into
+minute-long ones is not a bigger pass, it is a SEQUENCE of passes where each
+window continues the last one — and, just as importantly, where every window
+gets its OWN prompt with the sequence-wide invariants re-injected, because a
+single prompt repeated per window plays the shot's action once per window and
+the clip reads as a stutter (the H3 "repeat" artefact, `H3_CHAIN_PROMPT_HELP`).
+
+THE GEOMETRY, in frames:
+
+ stride = window - discard - overlap
+ count = 1 + ceil((total - window + discard) / stride)
+
+`window` is what one pass renders; `overlap` is the tail of the previous
+window the next one re-sees as context (LTX's extend pipeline conditions on
+the clip it is handed, so this is the tail that is kept for it); `discard` is
+the tail dropped BEFORE conditioning, because the last frames of a window are
+the least settled. `stride` is the new picture each later window adds.
+
+ON LTX'S GRID. A window is `8k+1` frames (the sampler's rule) and the extend
+pipeline adds latent frames in groups of 8, so `stride` must be a multiple of
+8 — the planner rounds it DOWN to the grid and says so in the plan. The last
+window may overshoot `total`; the delivered clip is trimmed to `total` at the
+mux, never padded.
+
+This module is PURE — numbers in, numbers out — so the plan, the prompt list
+and their invariants are testable without a model in the room. The panel
+(`mlx_ltx_panel.py`) turns the plan into one `generate` and N `extend` calls.
+"""
+from __future__ import annotations
+
+import math
+
+# 121 frames = 5 s at 24 fps, the canvas every LTX tier estimate is measured
+# on. 9 frames of overlap is one latent group (8) plus the shared frame: the
+# smallest context the extend pipeline can be handed that still spans a whole
+# latent. Zero discard by default — dropping frames is a quality lever the
+# user turns, not a tax every window pays.
+DEFAULT_WINDOW = 121
+DEFAULT_OVERLAP = 9
+DEFAULT_DISCARD = 0
+LATENT_GROUP = 8
+MAX_WINDOWS = 24 # a minute and a half at the defaults; past that
+ # the chain drift nobody has measured owns the clip
+FPS = 24
+
+
+def snap_8k1(frames: int) -> int:
+ """The sampler's grid: the nearest `8k+1` at or above 9."""
+ n = max(1, int(frames))
+ return max(9, LATENT_GROUP * round((n - 1) / LATENT_GROUP) + 1)
+
+
+def stride_for(window: int, overlap: int, discard: int) -> int:
+ """New frames per later window, on the latent grid (rounded DOWN)."""
+ raw = int(window) - int(discard) - int(overlap)
+ return max(LATENT_GROUP, (raw // LATENT_GROUP) * LATENT_GROUP)
+
+
+def window_count(total: int, window: int, overlap: int, discard: int) -> int:
+ """How many windows cover `total` frames. One when one pass is enough."""
+ total, window = int(total), int(window)
+ if total <= window:
+ return 1
+ stride = stride_for(window, overlap, discard)
+ return 1 + int(math.ceil((total - window + int(discard)) / stride))
+
+
+def plan_windows(total_frames: int, *, window: int = DEFAULT_WINDOW,
+ overlap: int = DEFAULT_OVERLAP, discard: int = DEFAULT_DISCARD,
+ fps: float = FPS) -> dict:
+ """The window schedule for a clip of `total_frames`.
+
+ Returns::
+
+ {"total_frames", "window", "overlap", "discard", "stride", "count",
+ "delivered_frames", # what the chain produces before the trim
+ "windows": [{"index", "start_frame", "frames", "new_frames",
+ "start_sec", "end_sec"}, ...],
+ "notes": [...]} # every rounding the planner made
+
+ `windows[0]` is the first pass (`frames` = the window). Every later entry
+ GENERATES `new_frames` (= stride + discard) on top of the kept picture,
+ re-seeing `overlap` frames of the previous tail; `kept_frames` is how much
+ of the clip is kept after that window's own discard.
+ """
+ notes: list[str] = []
+ total = snap_8k1(total_frames)
+ if total != int(total_frames):
+ notes.append(f"total {int(total_frames)}f snapped to {total}f (8k+1)")
+ win = snap_8k1(window)
+ if win != int(window):
+ notes.append(f"window {int(window)}f snapped to {win}f (8k+1)")
+ ov = max(1, int(overlap))
+ ov = LATENT_GROUP * ((ov - 1) // LATENT_GROUP) + 1
+ if ov != int(overlap):
+ notes.append(f"overlap {int(overlap)}f snapped to {ov}f (8k+1)")
+ dc = max(0, int(discard))
+ dc = (dc // LATENT_GROUP) * LATENT_GROUP
+ if dc != int(discard):
+ notes.append(f"discard {int(discard)}f snapped to {dc}f (8k)")
+ if ov + dc >= win:
+ raise ValueError(f"overlap {ov} + discard {dc} leaves no new frames "
+ f"in a {win}-frame window")
+ stride = stride_for(win, ov, dc)
+ count = window_count(total, win, ov, dc)
+ if count > MAX_WINDOWS:
+ raise ValueError(f"{total} frames would take {count} windows; the "
+ f"panel stops at {MAX_WINDOWS}")
+ # EVERY WINDOW DROPS ITS LAST `dc` FRAMES before the next one conditions
+ # on it — including the first and the last — so the kept picture is
+ # `win - dc + (count - 1) * stride`, which is exactly what the count
+ # formula solved for. A later window GENERATES `stride + dc` new frames
+ # (the extend call's size) and KEEPS `stride` of them.
+ rows = []
+ kept = win - dc
+ rows.append({"index": 0, "start_frame": 0, "frames": win, "new_frames": win,
+ "kept_frames": kept, "start_sec": 0.0,
+ "end_sec": round((kept - 1) / fps, 3)})
+ for k in range(1, count):
+ start = kept - ov
+ gen = stride + dc
+ kept = kept + stride
+ rows.append({"index": k, "start_frame": start, "frames": kept + dc,
+ "new_frames": gen, "kept_frames": kept,
+ "start_sec": round(start / fps, 3),
+ "end_sec": round((kept - 1) / fps, 3)})
+ return {"total_frames": total, "window": win, "overlap": ov, "discard": dc,
+ "stride": stride, "count": count, "delivered_frames": kept,
+ "windows": rows, "notes": notes}
+
+
+def extend_latents(new_frames: int) -> int:
+ """`extend_frames` for the helper: latent groups, never a fraction."""
+ return max(1, int(new_frames) // LATENT_GROUP)
+
+
+# ---------------------------------------------------------------------------
+# THE PROMPT CONTRACT
+# ---------------------------------------------------------------------------
+# ONE PROMPT PER WINDOW. The first window gets the shot's real prompt. A later
+# window gets ITS OWN line — the next beat of the action, written by whoever
+# planned the clip — and, whether or not it has one, the sequence-wide
+# INVARIANTS are re-injected: the things that must not change between passes
+# (who is in frame, the light, the lens, the place). Without them every window
+# is free to re-decide the world, and the seam is where it shows.
+#
+# LEAD WITH THE MOVE. LTX renders whatever the prompt names FIRST; leading
+# with the subject instead of the movement froze shots (memory:
+# ltx-prompt-lead-with-the-move). So a continuation line is placed FIRST and
+# the invariants FOLLOW it — never the other way round.
+CONTINUE = ("The shot continues without a cut, exactly where it left off, and "
+ "the camera keeps the same framing.")
+HOLD = ("Nothing new begins: the settled state of the previous moment is held, "
+ "with only small natural motion.")
+
+
+def window_prompts(base: str, per_window=None, invariants: str = "",
+ count: int = 1, settle: str = "") -> list[str]:
+ """The prompt each window renders with. Length == `count`.
+
+ `per_window[k]` is the line for window `k` (blank = none; index 0 blank
+ means "use `base`" — the same contract the H3 chain uses). `invariants` is
+ appended to every LATER window; `settle` is what a later window with no
+ line of its own is told to hold, and with neither it holds the previous
+ moment.
+ """
+ base = str(base or "").strip()
+ inv = str(invariants or "").strip().rstrip(".")
+ settle = str(settle or "").strip().rstrip(".")
+ lines = [str(x or "").strip() for x in (per_window or [])]
+ out: list[str] = []
+ for k in range(max(1, int(count))):
+ own = lines[k] if k < len(lines) else ""
+ if k == 0:
+ out.append(own or base)
+ continue
+ head = own or (f"{settle}, held." if settle else HOLD)
+ parts = [head, CONTINUE]
+ if inv:
+ parts.append(f"Throughout: {inv}.")
+ out.append(" ".join(p for p in parts if p))
+ return out
+
+
+def describe(plan: dict) -> str:
+ """One line for a log or a card."""
+ w = plan["windows"]
+ secs = plan["delivered_frames"] / float(FPS)
+ return (f"{plan['count']} window(s) of {plan['window']}f, +{plan['stride']}f "
+ f"each (overlap {plan['overlap']}f, discard {plan['discard']}f) "
+ f"→ {plan['delivered_frames']}f ≈ {secs:.1f}s for {plan['total_frames']}f asked"
+ + (f"; last window ends at {w[-1]['end_sec']}s" if len(w) > 1 else ""))
diff --git a/mlx_ltx_panel.py b/mlx_ltx_panel.py
index a3f872d..5ec0833 100644
--- a/mlx_ltx_panel.py
+++ b/mlx_ltx_panel.py
@@ -857,6 +857,11 @@ def _settings_defaults() -> dict:
# to flip OFF→ON so kids / casual visitors can't enable it by a
# stray click.
"spicy_mode": False,
+ # Completion alerts: a short chime in the tab, and a browser
+ # notification when the tab is in the background and the person has
+ # allowed them. On by default because a render is minutes long and
+ # nobody watches a progress bar for eleven of them; one click off.
+ "notify_done": True,
# Memory/speed policy. Defaults to Auto so 5 s clips keep the fast
# full-decode path while long/high-pressure renders stay protected.
# Live preview. On by default: it costs ~0.2 % of the render,
@@ -1122,6 +1127,13 @@ def _validate_settings_patch(patch: dict) -> tuple[dict, str | None]:
else:
out["spicy_mode"] = str(v).strip().lower() in ("1", "true", "yes", "on")
+ if "notify_done" in patch:
+ v = patch["notify_done"]
+ if isinstance(v, bool):
+ out["notify_done"] = v
+ else:
+ out["notify_done"] = str(v).strip().lower() in ("1", "true", "yes", "on")
+
if "live_preview" in patch:
# Two states, and anything unrecognised is refused rather than
@@ -1271,6 +1283,10 @@ def get_settings_public() -> dict:
"models_card_dismissed": bool(s.get("models_card_dismissed", False)),
"spicy_mode": bool(s.get("spicy_mode", False)),
"live_preview": str(s.get("live_preview", "on")),
+ "notify_done": bool(s.get("notify_done", True)),
+ # Push: can the panel send at all, and how many browsers listen.
+ "push_available": push_available(),
+ "push_subscriptions": len(_push_subs()),
# Write-only until now: `update_settings` validated and stored it, but
# the GET never returned it, so any control would open showing "auto"
# no matter what the user had chosen.
@@ -2859,23 +2875,34 @@ def _set_h3_turbo_dl(**kw) -> None:
_h3_turbo_dl_state.update(kw)
-def _h3_turbo_download_bg(target_dir, push_log) -> None:
+def _h3_turbo_asset(key: str | None = None) -> dict:
+ """The managed adapter to fetch: v4-600 EMA from its author's repo by
+ default; the LightX2V release asset when asked for by key."""
+ key = key or H3_TURBO_DEFAULT_ASSET
+ if key in H3_TURBO_ASSETS:
+ return dict(H3_TURBO_ASSETS[key], key=key)
+ return {"key": "v1.0", "file": H3_TURBO_LORA_FILE, "url": H3_TURBO_ASSET_URL,
+ "sha256": H3_TURBO_ASSET_SHA256, "bytes": H3_TURBO_ASSET_BYTES}
+
+
+def _h3_turbo_download_bg(target_dir, push_log, asset: dict | None = None) -> None:
"""Stream the digest-pinned v1.0 repack release asset into the H3 pack."""
import urllib.request
import hashlib
- total_mb = H3_TURBO_ASSET_BYTES // (1 << 20)
+ asset = asset or _h3_turbo_asset()
+ total_mb = asset['bytes'] // (1 << 20)
tmp = None
try:
target_dir.mkdir(parents=True, exist_ok=True)
- target = target_dir / H3_TURBO_LORA_FILE
+ target = target_dir / asset['file']
if target.is_file():
_set_h3_turbo_dl(status="done", mb=total_mb, total_mb=total_mb,
error=None)
return
tmp = target.with_suffix(target.suffix + ".partial")
- push_log(f"[h3:turbo] downloading {H3_TURBO_LORA_FILE} "
+ push_log(f"[h3:turbo] downloading {asset['file']} "
f"(~{total_mb} MB)…")
- req = urllib.request.Request(H3_TURBO_ASSET_URL,
+ req = urllib.request.Request(asset['url'],
headers={"User-Agent": "Phosphene"})
h = hashlib.sha256()
written = 0
@@ -2897,11 +2924,11 @@ def _h3_turbo_download_bg(target_dir, push_log) -> None:
push_log(f"[h3:turbo] {written // (1 << 20)} / "
f"{total_mb} MB")
last_log = now
- if written != H3_TURBO_ASSET_BYTES:
+ if written != asset['bytes']:
raise RuntimeError(
f"size mismatch: got {written}, expected "
- f"{H3_TURBO_ASSET_BYTES} — please retry")
- if h.hexdigest() != H3_TURBO_ASSET_SHA256:
+ f"{asset['bytes']} — please retry")
+ if h.hexdigest() != asset['sha256']:
raise RuntimeError("checksum mismatch (download corrupt) — "
"please retry")
tmp.replace(target)
@@ -2941,7 +2968,7 @@ def _h3_install_turbo(push_log, download_fn=None) -> dict:
"from the Phosphene sidebar in Pinokio to update the "
"clone — it keeps every weight already on disk."}
target = _h3_turbo_dir()
- if (target / H3_TURBO_LORA_FILE).is_file():
+ if any((target / f).is_file() for f, _v, _fb in H3_TURBO_LORA_CANDIDATES):
return {"ok": True, "started": False, "already_installed": True,
"dir": str(target)}
with _h3_turbo_dl_lock:
@@ -2950,14 +2977,14 @@ def _h3_install_turbo(push_log, download_fn=None) -> dict:
"error": "a Turbo adapter download is already active"}
_h3_turbo_dl_state.clear()
_h3_turbo_dl_state.update(status="downloading", mb=0,
- total_mb=H3_TURBO_ASSET_BYTES // (1 << 20),
+ total_mb=_h3_turbo_asset()['bytes'] // (1 << 20),
error=None)
fn = download_fn or _h3_turbo_download_bg
threading.Thread(target=fn, args=(target, push_log), daemon=True,
name="h3-turbo-download").start()
return {"ok": True, "started": True, "dir": str(target),
- "asset": H3_TURBO_ASSET_URL, "sha256": H3_TURBO_ASSET_SHA256,
- "bytes": H3_TURBO_ASSET_BYTES}
+ "asset": _h3_turbo_asset()['url'], "sha256": _h3_turbo_asset()['sha256'],
+ "bytes": _h3_turbo_asset()['bytes']}
# Compatibility taxonomy for LoRAs across the panel's two render lanes
@@ -3098,6 +3125,11 @@ def _read_lora_sidecar(safetensors_path: Path) -> dict:
# fall back to these defaults, so no existing sidecar needs a rewrite.
"lora_layout": None,
"lora_converted_prefix": None,
+ # `guide`: the planner-written paragraph (POST /loras/guide) — what
+ # the LoRA does, how to prompt it, a strength to start from. The
+ # reader is a whitelist, so a key it does not name never reaches the
+ # picker: this row is what makes the guide survive the read.
+ "guide": "",
}
if sidecar.exists():
try:
@@ -3237,6 +3269,10 @@ def list_user_loras() -> list[dict]:
"civitai_id": meta.get("civitai_id"),
"civitai_version_id": meta.get("civitai_version_id"),
"civitai_url": civitai_url,
+ # A written guide (Settings-free): what the LoRA does, how to prompt
+ # it, a strength to start from. Written on request by the planner
+ # model from the sidecar; kept in the sidecar under `guide`.
+ "guide": str(meta.get("guide") or ""),
"downloaded_at": meta.get("downloaded_at"),
"is_curated": False,
**ltx_compat,
@@ -7317,7 +7353,23 @@ H3_TURBO_RAW_V01_FILE = "minimax_h3_fl2v_turbo_4step_v0.1.safetensors"
# It stays behind both LightX2V layouts so a completed v1.0 download always
# wins, and it carries the fallback flag so the UI labels it honestly.
H3_TURBO_CKPT500_FILE = "minimax_h3_turbo_4step_ema_ckpt500.safetensors"
+# THE COMMUNITY'S CURRENT ADAPTER (2026-09-05): larryvrh's v4 step-600 EMA.
+# Its author: "the strongest checkpoint released — much better static and
+# small-motion shots, markedly better micro-detail (faces, fingers, fine
+# texture); the over-sharpening of the v1 line is resolved; 6–8 steps is where
+# it performs best (4 can smear fast motion)". Bare runner layout, no repack
+# needed, 780 MB. Strength 1.0 per its card. It resolves FIRST when present;
+# the LightX2V repack and the two older files stay as fallbacks so no install
+# loses Turbo.
+H3_TURBO_V4_FILE = "minimax_h3_turbo_v4_step600_ema.safetensors"
+H3_TURBO_V4_REPO = "larryvrh/MiniMax-H3-Turbo-Lora"
+H3_TURBO_V4_URL = ("https://huggingface.co/" + H3_TURBO_V4_REPO
+ + "/resolve/main/" + H3_TURBO_V4_FILE)
+H3_TURBO_V4_SHA256 = "5f3a626cd72c93a8b9318d6760c510bc5092d2ab13aaba1f932c5bab07a416d3"
+H3_TURBO_V4_BYTES = 779849816
+H3_TURBO_V4_STEPS = 7 # sigma points → 6 forwards, the card's sweet spot
H3_TURBO_LORA_CANDIDATES = (
+ (H3_TURBO_V4_FILE, "v4-600-EMA", False),
(H3_TURBO_LORA_FILE, "v1.0", False),
(H3_TURBO_FALLBACK_LORA_FILE, "v0.1", True),
(H3_TURBO_CKPT500_FILE, "ckpt500-EMA", True),
@@ -7343,8 +7395,18 @@ H3_TURBO_ASSET_BYTES = 1956165254
H3_TURBO_DIRNAME = "turbo-lora"
# Sigma POINTS, matching --steps. 4 points = 3 forwards = what the adapter was
# distilled for; it is visibly softer at fewer and gains nothing at more.
-H3_TURBO_STEPS = 4
-H3_TURBO_DOWNLOAD_GB = 2.0 # the published asset is 1,956,165,254 bytes
+H3_TURBO_STEPS = 4 # the 4-step adapters (v1.0 / v0.1 / ckpt500)
+# Sigma points per adapter version; anything unlisted is a 4-step adapter.
+H3_TURBO_VERSION_STEPS = {"v4-600-EMA": H3_TURBO_V4_STEPS}
+# What the managed download fetches. The v4 adapter comes straight from its
+# author's repo (bare layout, digest-pinned); the LightX2V release asset stays
+# reachable by key for installs that cannot reach Hugging Face.
+H3_TURBO_ASSETS = {
+ "v4-600-EMA": {"file": H3_TURBO_V4_FILE, "url": H3_TURBO_V4_URL,
+ "sha256": H3_TURBO_V4_SHA256, "bytes": H3_TURBO_V4_BYTES},
+}
+H3_TURBO_DEFAULT_ASSET = "v4-600-EMA"
+H3_TURBO_DOWNLOAD_GB = 0.8 # the v4 adapter is 779,849,816 bytes
# Size floors for the "is it really there" probe. An interrupted fetch leaves a
# short file that loads far enough to fail 30 s into a render, which is exactly
# the failure mode the H3-vanish lesson says to catch at status time instead.
@@ -7364,6 +7426,19 @@ H3_TURBO_FORWARDS = H3_TURBO_STEPS - 1
# One line, no marketing. It is a step-distillation adapter; say so.
H3_TURBO_NOTE = ("Turbo uses the LightX2V v1.0 768p 4-step adapter — fewer "
"denoise passes over the same H3 model.")
+H3_TURBO_NOTE_V4 = ("Turbo uses the community's v4-600 EMA adapter — six denoise "
+ "passes over the same H3 model; sharper faces and fine detail "
+ "than the 4-step adapters.")
+
+
+def h3_turbo_note(paths: dict | None = None) -> str:
+ """The one sentence that says which adapter Turbo is, for the adapter
+ that actually resolves — not the one this file was written against."""
+ try:
+ resolved = paths or h3_turbo_paths()
+ except Exception: # noqa: BLE001
+ return H3_TURBO_NOTE
+ return H3_TURBO_NOTE_V4 if (resolved or {}).get("version") == "v4-600-EMA" else H3_TURBO_NOTE
# ============================================================================
# H3 RENDER SHAPE — two independent axes, priced by one measured cost model
@@ -9664,7 +9739,8 @@ def h3_turbo_paths() -> dict:
break
missing = [] if lora is not None else [
"adapter ("
- + H3_TURBO_LORA_FILE
+ + H3_TURBO_V4_FILE
+ + "; or " + H3_TURBO_LORA_FILE
+ "; safe fallback "
+ H3_TURBO_FALLBACK_LORA_FILE
+ ")"
@@ -9679,6 +9755,38 @@ def h3_turbo_paths() -> dict:
}
+def h3_turbo_steps(paths: dict | None = None) -> int:
+ """Sigma points for the Turbo adapter that will actually run: 7 (six
+ forwards) for v4-600 EMA, 4 for the 4-step adapters. Anything that says
+ "Turbo pins N steps" must read this, never H3_TURBO_STEPS directly."""
+ resolved = paths or h3_turbo_paths()
+ return int(H3_TURBO_VERSION_STEPS.get(resolved.get("version") or "", H3_TURBO_STEPS))
+
+
+def _h3_retune_turbo_estimates() -> None:
+ """The tier table priced Turbo at import with the 4-step forwards, before
+ the adapter directory could be resolved. Re-price every cell for the
+ adapter that is actually installed — six forwards for v4 — so the chips,
+ the Speed pills and the Storyboard estimate say what will happen."""
+ try:
+ fwd = max(1, h3_turbo_steps() - 1)
+ except Exception: # noqa: BLE001
+ return
+ if fwd == H3_TURBO_FORWARDS:
+ return
+ for cell in H3_TIERS.values():
+ try:
+ windows = int(cell.get("chain_windows") or 1)
+ tm = h3_estimate_minutes(int(cell["width"]), int(cell["height"]),
+ int(cell["window_frames"]), windows, fwd)
+ tm = min(float(cell.get("eta_min") or tm), tm)
+ cell["turbo_min"] = round(tm, 2)
+ cell["turbo_eta"] = _fmt_eta(tm)
+ cell["turbo_forwards"] = windows * fwd
+ except Exception: # noqa: BLE001
+ continue
+
+
def h3_turbo_lora_spec(paths: dict | None = None) -> str:
"""Return the runner's required PATH:SCALE spelling for Turbo."""
resolved = paths or h3_turbo_paths()
@@ -9714,9 +9822,9 @@ def h3_turbo_status() -> dict:
"supported": supported,
"downloaded": downloaded,
"reason": reason,
- "steps": H3_TURBO_STEPS,
+ "steps": h3_turbo_steps(paths),
"download_gb": H3_TURBO_DOWNLOAD_GB,
- "repo": H3_TURBO_REPO,
+ "repo": H3_TURBO_V4_REPO,
"adapter": str(paths["lora"]) if paths["lora"] else None,
"adapter_version": paths["version"],
"fallback": paths["fallback"],
@@ -9731,7 +9839,7 @@ def h3_turbo_status() -> dict:
f"{H3_TURBO_RAW_V01_FILE} is not compatible."),
"dir": str(paths["dir"]),
"missing": paths["missing"],
- "note": H3_TURBO_NOTE,
+ "note": h3_turbo_note(paths),
"label": "Turbo",
}
@@ -9827,6 +9935,9 @@ _H3_LORA_B_SUFFIX = ".lora_B.weight"
_H3_LORA_MAX_HEADER_BYTES = 64 * 1024 * 1024
+_h3_retune_turbo_estimates()
+
+
def _h3_loras_dir() -> Path:
"""Where H3 user LoRAs live: alongside the other weight components.
@@ -13363,6 +13474,40 @@ def list_uploads(limit: int = 40) -> list[dict]:
return out
+def _output_search_text(meta: dict, params: dict) -> str:
+ """The searchable words of one output, lower-cased, space-joined."""
+ bits: list[str] = []
+ try:
+ for k in ("prompt", "label", "preset_label", "mode", "quality", "engine",
+ "character_id", "trigger", "seed", "seed_used", "h3_tier"):
+ v = params.get(k)
+ if v not in (None, "", [], {}):
+ bits.append(str(v)[:400])
+ w, h = params.get("width"), params.get("height")
+ if w and h:
+ bits.append(f"{int(w)}x{int(h)}")
+ fr = params.get("frames")
+ if fr:
+ bits.append(f"{int(fr)}f")
+ for lo in (params.get("loras") or []):
+ if isinstance(lo, dict) and lo.get("path"):
+ bits.append(Path(str(lo["path"])).stem)
+ elif isinstance(lo, str):
+ bits.append(Path(lo).stem)
+ for k in ("engine", "model"):
+ v = meta.get(k)
+ if isinstance(v, str) and v:
+ bits.append(Path(v).name if "/" in v else v)
+ tp = meta.get("temporal") or {}
+ if isinstance(tp, dict) and tp.get("mode"):
+ bits.append(str(tp["mode"]))
+ if meta.get("windows"):
+ bits.append("windows")
+ except Exception: # noqa: BLE001
+ pass
+ return " ".join(bits).lower()
+
+
def list_outputs(
include_hidden: bool = False,
limit: int = 60,
@@ -13568,6 +13713,7 @@ def list_outputs(
# nothing, and it is what puts an S03 badge on a gallery card. None for
# every clip that isn't part of a storyboard, which is most of them.
sb_tag = None
+ search = ""
sidecar = p.with_suffix(p.suffix + ".json")
has_sidecar = sidecar.exists()
if has_sidecar:
@@ -13581,6 +13727,12 @@ def list_outputs(
_sc_params = {}
# Top-level `engine` is what the H3 path stamps; the image
# path only has params.engine ("mflux/ideogram" etc.).
+ # WHAT THE GALLERY CAN BE SEARCHED BY, from the sidecar this
+ # loop already reads: the prompt, the mode, the quality, the
+ # engine, the size, the seed, the LoRAs and the character.
+ # One lower-cased string per row, so the browser's filter is
+ # a substring test and costs nothing per keystroke.
+ search = _output_search_text(meta, _sc_params)
_eng = meta.get("engine") or _sc_params.get("engine")
if isinstance(_eng, str) and _eng:
engine = _eng
@@ -13661,6 +13813,7 @@ def list_outputs(
# without re-parsing the filename. Mirrors isPhotoOutput() on
# the agent-stage pane (commit af5c184).
"kind": "image" if is_image else "video",
+ "q": search,
})
total = len(out)
# Apply offset + limit. limit<=0 means "no cap"; otherwise slice. This
@@ -14704,6 +14857,11 @@ def compute_upscale_plan(w: int, h: int, mode: str | None,
# the plan so the sidecar records that nothing was added. Everything
# that does NOT match (768×448 = 12:7, 640×384 = 5:3, LTX's 1280×704)
# keeps the fit-and-pad path exactly as it was.
+ # A FIT NEVER SHRINKS. "Fit 720p" means "bring a smaller render up to
+ # 720p", not "throw away the native 1344x768 H3 render" — which is what
+ # the default did to every native take until 2026-09-06.
+ if eff_w >= target_w and eff_h >= target_h:
+ return None
exact_aspect = (eff_w * target_h == eff_h * target_w)
if exact_aspect:
fit_w, fit_h = target_w, target_h
@@ -14964,6 +15122,75 @@ def _sb_h3_available() -> bool:
return False
+# ---------------------------------------------------------------------------
+# ONE TAKE — a clip longer than one pass, on either engine
+# ---------------------------------------------------------------------------
+# The user picks a LENGTH (30 s … 2 min) and writes BEATS, one line per five
+# seconds. Nothing else is new: on LTX the take is the existing windows chain
+# (one prompt per 121-frame window); on H3 it is 15-second parts, each three
+# 5-second windows with their own prompt, each part starting from the last
+# frame of the one before (H3's first-frame conditioning), joined at the end.
+# The words "windows", "chain" and "parts" never reach the user; they see a
+# length, beats, and an honest time.
+TAKE_SECONDS = (30, 45, 60, 90, 120)
+TAKE_BEAT_SECONDS = 5
+TAKE_H3_PART_LENGTH = "15s" # the longest single H3 render
+TAKE_H3_BEATS_PER_PART = 3
+TAKE_H3_PART_FRAMES = 362
+
+
+def take_plan(seconds, engine: str) -> dict | None:
+ """Beats and parts for a take of `seconds` on `engine`; None when off."""
+ try:
+ seconds = int(seconds)
+ except (TypeError, ValueError):
+ return None
+ if seconds not in TAKE_SECONDS:
+ return None
+ beats = seconds // TAKE_BEAT_SECONDS
+ eng = "h3" if (engine or "ltx") == "h3" else "ltx"
+ if eng == "h3":
+ n_parts = -(-beats // TAKE_H3_BEATS_PER_PART)
+ parts = [list(range(i * TAKE_H3_BEATS_PER_PART,
+ min(beats, (i + 1) * TAKE_H3_BEATS_PER_PART))) for i in range(n_parts)]
+ frames = TAKE_H3_PART_FRAMES * n_parts
+ else:
+ parts = [list(range(beats))]
+ frames = seconds * 24 + 1 # 8k+1 for every TAKE_SECONDS value
+ return {"seconds": seconds, "beats": beats, "parts": parts, "frames": frames, "engine": eng}
+
+
+def take_beats(raw, n: int) -> list[str]:
+ """Exactly `n` beat prompts from what the form sent (a JSON list or a
+ newline-separated string). A blank beat holds the previous moment; extras
+ are dropped, missing ones are blank."""
+ items: list[str] = []
+ if isinstance(raw, list):
+ items = [str(x or "").strip() for x in raw]
+ elif raw:
+ s = str(raw).strip()
+ try:
+ v = json.loads(s)
+ items = [str(x or "").strip() for x in v] if isinstance(v, list) else [s]
+ except (TypeError, ValueError):
+ items = [ln.strip() for ln in s.split("\n")]
+ items = items[:n]
+ return items + [""] * (n - len(items))
+
+
+def take_estimate_minutes(engine: str, quality: str, seconds) -> float | None:
+ """Wall clock for the whole take, from the same cost model every other
+ estimate uses. None when this Mac has no number for it (LTX windows are
+ not priced yet — the chain's extends have no measured model)."""
+ plan = take_plan(seconds, engine)
+ if not plan:
+ return None
+ if plan["engine"] == "h3":
+ per = _sb_h3_cost(quality or "standard", TAKE_H3_PART_LENGTH)
+ return None if per is None else round(per * len(plan["parts"]) / 60.0, 1)
+ return None
+
+
def _sb_h3_cost(quality_key: str, length_key: str):
"""The MEASURED wall clock for one H3 cell, in seconds — the hook
storyboard.estimate() takes so the cost model lives in exactly one place.
@@ -15102,6 +15329,21 @@ def _sb_reconcile(board: dict) -> bool:
# it has been through — the OUTPUTS are that record, and they are what
# the scheduler reads. But the UI reads `status`, so a shot waiting on
# its delivery render must not keep showing "done" from its draft.
+ # The anchor still: an image job whose output becomes the shot's
+ # first frame. Folded back the same way; a failed still is reported on
+ # the shot but does not fail it — the shot renders unanchored.
+ sj = s.get("still_job_id")
+ if sj and not s.get("still"):
+ job = idx.get(sj)
+ st = ((job or {}).get("status") or "").lower()
+ if st == "done" and (job or {}).get("output_path"):
+ s["still"] = job["output_path"]
+ s["still_error"] = None
+ changed = True
+ elif st in ("failed", "error", "cancelled"):
+ if s.get("still_error") != ((job or {}).get("error") or "the still could not be made"):
+ s["still_error"] = (job or {}).get("error") or "the still could not be made"
+ changed = True
fj = s.get("final_job_id")
if fj and not s.get("final_output"):
fst = ((idx.get(fj) or {}).get("status") or "").lower()
@@ -15539,6 +15781,145 @@ def _sb_set_planner(board: dict, **kw) -> None:
board["planner"] = p
+# The bars a director's slot spans, and the floor under a slot: shorter than
+# this is a flash, and the planner cannot write a movement into it.
+DIRECTOR_MIN_SLOT_SEC = 1.0
+
+
+def _sb_director_grid(soundtrack: dict, *, max_shots: int = 48) -> dict:
+ """The beat grid, as SLOTS: `{path, bpm, bars_per_shot, total_sec, count,
+ slot_sec, slots: [{start, end}], must: [...]}` or `{error}`.
+
+ `beat_map()` is the same fit the Editor's Prepare runs, so the slots the
+ planner writes to are the downbeats the first cut lands on. When the
+ track has more bars than `max_shots` slots can hold, the film covers the
+ FIRST `max_shots` slots and says so — a 48-shot board is the panel's
+ ceiling and a plan that silently squashed the song would be the other
+ kind of wrong.
+ """
+ import storyboard_edit as _se # noqa: PLC0415
+ path = str((soundtrack or {}).get("path") or "")
+ if not path or not Path(path).is_file():
+ return {"error": f"no audio file at {path or '(none)'}"}
+ bars = max(1, min(8, int((soundtrack or {}).get("bars_per_shot") or 2)))
+ try:
+ beats = _se.beat_map(path)
+ except Exception as exc: # noqa: BLE001
+ return {"error": f"could not read the beat of {Path(path).name}: {exc}"}
+ downs = [float(t) for t in (beats.get("downbeats") or [])]
+ total = float(beats.get("duration") or 0.0)
+ if total <= 0:
+ total = float((_se.probe_media(path) or {}).get("duration") or 0.0)
+ if len(downs) < 2 or total <= 0:
+ return {"error": f"{Path(path).name} has no beat the panel can find"}
+ # THE SONG MAP DECIDES HOW OFTEN. Sections on the same bar grid, each with
+ # an energy, and `director_pacing` turns the user's bars-per-shot into a
+ # per-section stride: the chorus cuts twice as often, the intro and the
+ # outro half as often. Best-effort: a track the map cannot read is cut at
+ # the base stride throughout, and the plan says so.
+ smap = None
+ try:
+ smap = _se.song_map(path, beats)
+ except Exception as exc: # noqa: BLE001
+ push(f"[storyboard] director: no song map for {Path(path).name} ({exc}); "
+ f"cutting every {bars} bar(s) throughout")
+ sections = list((smap or {}).get("sections") or [])
+ mean_e = float((smap or {}).get("mean_energy") or 0.0)
+ grid = [t for t in downs if t < total - DIRECTOR_MIN_SLOT_SEC]
+ slots: list[dict] = []
+ if sections:
+ for sec in sections:
+ i, j = sec["bars"]
+ stride = _se.director_pacing(sec["label"], float(sec["energy"]), mean_e, bars)
+ edges = grid[i:j:stride] + [min(total, float(sec["end"]))]
+ for a, b in zip(edges, edges[1:]):
+ if b - a >= DIRECTOR_MIN_SLOT_SEC:
+ slots.append({"start": a, "end": b, "section": sec["label"],
+ "energy": float(sec["energy"]), "bars": stride})
+ else:
+ cuts = grid[::bars] + [total]
+ slots = [{"start": cuts[i], "end": cuts[i + 1], "section": "",
+ "energy": 0.0, "bars": bars}
+ for i in range(len(cuts) - 1)
+ if cuts[i + 1] - cuts[i] >= DIRECTOR_MIN_SLOT_SEC]
+ note = ""
+ if len(slots) > max_shots:
+ slots = slots[:max_shots]
+ note = (f"the track has more bars than {max_shots} shots can hold; "
+ f"the film covers its first {slots[-1]['end']:.0f}s")
+ if not slots:
+ return {"error": f"{Path(path).name} is too short to cut to"}
+ slot_sec = sum(s["end"] - s["start"] for s in slots) / len(slots)
+ must = [f"this is a MUSIC VIDEO cut to a {float(beats.get('bpm') or 0):.0f} bpm "
+ f"track: every shot is ONE movement that reads in about "
+ f"{slot_sec:.1f} seconds — begin each description with the movement "
+ f"(what moves, how the camera moves), never with the subject",
+ "no shot depends on hearing words: nobody speaks to camera and "
+ "no shot contains dialogue, because the track replaces every "
+ "clip's own sound"]
+ # THE ARC, SHOT BY SHOT. The planner cannot hear the track, so it is told
+ # which shots fall in which section and how hot that section is — the
+ # chorus wants the boldest images, the intro the stillest.
+ if sections:
+ k = 1
+ for sec in sections:
+ n = sum(1 for sl in slots if sl.get("section") == sec["label"]
+ and sec["start"] <= sl["start"] < sec["end"])
+ if not n:
+ continue
+ heat = ("peak energy" if sec["energy"] > mean_e * 1.2
+ else "low energy" if sec["energy"] < mean_e * 0.6 else "steady energy")
+ must.append(f"shots {k}–{k + n - 1} are the {sec['label']} "
+ f"({sec['start']:.0f}–{sec['end']:.0f}s, {heat}"
+ f"{', the boldest images and the fastest cuts' if sec['label'] == 'chorus' else ''}"
+ f"{', the stillest' if sec['label'] in ('intro', 'outro') else ''})")
+ k += n
+ if note:
+ must.append(note)
+ return {"path": path, "bpm": float(beats.get("bpm") or 0.0),
+ "bars_per_shot": bars, "total_sec": round(slots[-1]["end"], 3),
+ "count": len(slots), "slot_sec": round(slot_sec, 3),
+ "slots": [{"start": round(s["start"], 3), "end": round(s["end"], 3),
+ "section": s.get("section") or "", "bars": s.get("bars") or bars,
+ "energy": round(float(s.get("energy") or 0.0), 4)}
+ for s in slots],
+ "sections": [{k2: v for k2, v in sec.items() if k2 != "bars"} for sec in sections],
+ "must": must, "note": note}
+
+
+def _sb_director_concept(concept: str, director: dict) -> str:
+ """The brief the planner reads: the idea, then what the track demands."""
+ c = str(concept or "").strip()
+ return (f"{c}\n\nMUSIC VIDEO. The track is {director['bpm']:.0f} bpm and "
+ f"runs {director['total_sec']:.0f}s; the film is {director['count']} "
+ f"shots of about {director['slot_sec']:.1f}s each, one per "
+ f"{director['bars_per_shot']} bar(s), cut on the downbeat. Plan an "
+ f"ARC across the shots (where it starts, where it turns, where it "
+ f"lands) rather than a pool of similar images, and give the film one "
+ f"recurring anchor image it returns to.")
+
+
+def _sb_take_concept(concept: str, seconds: int) -> str:
+ """The brief for a film that is ONE continuous shot: the planner writes
+ one movement per five-second beat, and the camera never cuts."""
+ c = str(concept or "").strip()
+ beats = int(seconds) // TAKE_BEAT_SECONDS
+ return (f"{c}\n\nONE TAKE. The whole film is a single continuous shot of "
+ f"{int(seconds)} seconds that never cuts. Write it as {beats} beats of "
+ f"five seconds each, in order; each beat is what happens NEXT in the "
+ f"same unbroken shot — lead with the movement (of the subject, of the "
+ f"camera, of the world), name what enters or changes, and keep the "
+ f"subject, the camera position and the light continuous from one "
+ f"beat into the next. No new angles, no reverse shots, no jumps in "
+ f"time: every beat starts exactly where the previous one ends. "
+ f"A change of place (through a door, into a room, onto a bridge) gets "
+ f"a beat OF ITS OWN, with the approach in the beat before it; a reveal "
+ f"(the face, the person waiting) is the whole of its beat, nothing else "
+ f"in it; the beat before a change or a reveal slows down; every other "
+ f"beat has something new enter the frame within its first second. "
+ f"Name the sound in every beat.")
+
+
def _sb_plan_thread(board_id: str, brief: dict, previous: dict | None) -> None:
"""Plan a film, then GIVE THE MEMORY BACK — in that order, always.
@@ -15566,17 +15947,55 @@ def _sb_plan_thread(board_id: str, brief: dict, previous: dict | None) -> None:
entry["session"] = session
_SB_PLANNERS[board_id] = entry
+ # THE DIRECTOR'S GRID, before the planner runs. The shot count and
+ # every duration come from the track, not from the chips: a slot per
+ # `bars_per_shot` bars of downbeats, and the planner is told, in the
+ # brief, that it is writing a music video cut to that grid — one
+ # movement per slot, led by the movement. The measured trap: a
+ # per-shot "the music drives this" string fed to LTX VERBATIM renders
+ # a closed mouth; what the LLM does with the grid is the mechanism,
+ # so the grid goes into the PLANNER's input and nothing else.
+ director = None
+ concept = brief.get("concept") or ""
+ must = list(brief.get("must") or [])
+ n_shots = int(brief.get("n_shots") or 12)
+ if brief.get("soundtrack"):
+ board["planner"]["stage"] = "grid"
+ storyboard.save_storyboard(STATE_DIR, board)
+ director = _sb_director_grid(brief["soundtrack"],
+ max_shots=STORYBOARD_MAX_SHOTS)
+ if director.get("error"):
+ _sb_set_planner(board, state="failed", stage=None,
+ error=director["error"], error_kind="grid")
+ storyboard.save_storyboard(STATE_DIR, board)
+ push(f"[storyboard] director: {director['error']}")
+ return
+ n_shots = director["count"]
+ concept = _sb_director_concept(concept, director)
+ must = must + list(director["must"])
+ push(f"[storyboard] director: {director['bpm']:.0f} bpm, "
+ f"{director['count']} slots of ~{director['slot_sec']:.1f}s "
+ f"({director['bars_per_shot']} bar(s) each) over "
+ f"{director['total_sec']:.0f}s of {Path(director['path']).name}")
board["planner"]["stage"] = "write"
+ # ONE TAKE: the plan is N beats, not N shots; collapsed after the
+ # planner returns (collapse_take). Wins over the shot count and over a
+ # soundtrack's slot count — the take's length is the film's length.
+ _take_secs = int(brief.get("take_seconds") or 0)
+ if _take_secs in TAKE_SECONDS:
+ n_shots = _take_secs // TAKE_BEAT_SECONDS
+ concept = _sb_take_concept(concept, _take_secs)
+ push(f"[storyboard] one take of {_take_secs}s — planning {n_shots} beats")
storyboard.save_storyboard(STATE_DIR, board)
- push(f"[storyboard] planning {brief.get('n_shots')} shots — "
+ push(f"[storyboard] planning {n_shots} shots — "
f"the renderer's memory is borrowed for about a minute")
result = storyboard_planner.plan_film(
- brief.get("concept") or "",
- n_shots=int(brief.get("n_shots") or 12),
+ concept,
+ n_shots=n_shots,
style=brief.get("style") or "",
characters=brief.get("characters") or None,
- must_include=brief.get("must") or None,
+ must_include=must or None,
feedback=brief.get("feedback") or None,
previous=previous,
# The film's own choice, and it is a PLANNING input: the planner
@@ -15622,6 +16041,30 @@ def _sb_plan_thread(board_id: str, brief: dict, previous: dict | None) -> None:
board["planner"]["stage"] = "repair" if int(meta.get("attempts") or 1) > 1 else "check"
board["title"] = result.get("title") or board.get("title") or "Untitled film"
+ # THE SLOT IS THE SHOT'S LENGTH, PLUS A HANDLE. Shot k plays slot k on
+ # the grid; it is rendered a second longer so the auto-editor has a
+ # window to choose and a dissolve has material either side. Written
+ # onto the board so the Editor's first cut and the chips agree.
+ if director:
+ slots = director["slots"]
+ for k, _s in enumerate(result.get("shots") or []):
+ if not isinstance(_s, dict) or k >= len(slots):
+ continue
+ _len = float(slots[k]["end"]) - float(slots[k]["start"])
+ _s["duration_s"] = round(min(60.0, _len + 1.0), 2)
+ _s["frames"] = storyboard.ltx_frames_for(_s["duration_s"])
+ _s["slot"] = {"start": round(float(slots[k]["start"]), 3),
+ "end": round(float(slots[k]["end"]), 3)}
+ if slots[k].get("section"):
+ _s["section"] = slots[k]["section"]
+ board["soundtrack"] = {**(board.get("soundtrack") or {}),
+ "path": director["path"],
+ "bpm": director["bpm"],
+ "bars_per_shot": director["bars_per_shot"],
+ "total_sec": director["total_sec"],
+ "slots": slots,
+ "sections": director.get("sections") or [],
+ "count": director["count"]}
# What each shot had BEFORE the plan replaced it. A re-rolled shot is a
# brand-new dict, so its previous take has to be read from here — off
# the new dict it is always None.
@@ -15631,6 +16074,8 @@ def _sb_plan_thread(board_id: str, brief: dict, previous: dict | None) -> None:
_prev_out[_s["n"]] = (_s.get("draft_output") or _s.get("final_output")
or _s.get("stale_output"))
board["shots"] = result.get("shots") or []
+ if int(brief.get("take_seconds") or 0) in TAKE_SECONDS:
+ board["shots"] = storyboard.collapse_take(board["shots"], int(brief["take_seconds"]))
# DIALOGUE MUST FIT THE SHOT. The validator rejects a line the clock
# cannot carry (`dialogue_does_not_fit`), because it renders as a
# sentence cut off mid-word. For planner output the fix is mechanical
@@ -15694,6 +16139,8 @@ def _sb_plan_thread(board_id: str, brief: dict, previous: dict | None) -> None:
storyboard.save_storyboard(STATE_DIR, board)
push(f"[storyboard] plan ready — {len(board['shots'])} shots, "
f"{round(float(meta.get('elapsed_s') or 0))}s, memory given back")
+ if board.get("auto"):
+ _sb_auto_after_plan(board_id)
except Exception as exc: # noqa: BLE001
try:
if board is None:
@@ -15733,6 +16180,67 @@ def _sb_enqueue(job_form: dict) -> str:
return job["id"]
+def _sb_still_job_form(shot: dict, board: dict, policy: dict) -> dict:
+ """The ORDINARY image-job form for a shot's anchor still.
+
+ Composition and light come from the shot's own prompt (the still IS the
+ first frame); a shot with a character whose sheet exists is drawn with the
+ sheet as the reference through the Reference Edit engine, so the face on
+ the still is the face on the sheet. Anything else takes the default image
+ engine. One image, the shot's seed when it has one."""
+ prompt = storyboard.compose_shot_prompt(shot, storyboard.board_locations(board),
+ storyboard.board_wardrobe(board))
+ still_prompt = storyboard.still_prompt(prompt)
+ w = int(policy.get("width") or 0) or 1280
+ hh = int(policy.get("height") or 0) or 704
+ # The still takes the image engine's aspect NEAREST the shot canvas, so
+ # i2v crops as little of it as possible (a 640x448 draft is 4:3, not
+ # 16:9). The engine's own table is the source of truth; the small "s"
+ # variants are the same shapes and are left to the engine.
+ ratio = w / float(hh)
+ table = {k: v for k, v in agent_image_engine.ASPECT_DIMS.items() if not k.endswith("s")}
+ aspect = min(table, key=lambda k: abs((table[k][0] / float(table[k][1])) - ratio))
+ refs: list[str] = []
+ engine = "auto"
+ cid = shot.get("character_id")
+ if cid:
+ sheet = _character_sheet_png(str(cid))
+ if sheet:
+ refs = [str(sheet)]
+ engine = "qwen_edit_inline"
+ n = shot.get("n")
+ title = (board.get("title") or "").strip()
+ form = {
+ "mode": "image", "prompt": still_prompt, "engine_override": engine,
+ "aspect": aspect, "n": "1",
+ "seed": str(shot["seed"]) if isinstance(shot.get("seed"), int) and shot["seed"] != -1 else "-1",
+ "refs": json.dumps(refs),
+ "preset_label": (f"S{n:02d} still · {title}" if title else f"S{n:02d} still"),
+ "session_tag": f"sb:{board.get('id')}#{n}:still",
+ "enhance": "off", "open_when_done": "off",
+ }
+ return form
+
+
+def _sb_clear_still(board: dict, n: int, pass_name: str = "draft") -> dict | None:
+ """Forget shot `n`'s anchor still AND the clip that was rendered from it,
+ so the next render of that shot makes a new still first and starts the
+ clip from it. Returns the shot, or None when there is no shot `n`."""
+ shot = next((x for x in (board.get("shots") or [])
+ if isinstance(x, dict) and x.get("n") == n), None)
+ if shot is None:
+ return None
+ for k in ("still", "still_job_id", "still_error"):
+ shot.pop(k, None)
+ key = "draft_job_id" if pass_name == "draft" else "final_job_id"
+ out_key = "draft_output" if pass_name == "draft" else "final_output"
+ shot.pop(key, None)
+ shot.pop(out_key, None)
+ shot["status"] = "pending"
+ shot["error"] = None
+ return shot
+
+
def _sb_render_thread(board_id: str, pass_name: str, only: list | None) -> None:
"""Submit the film ONE BUCKET AT A TIME, then wait for it.
@@ -15770,9 +16278,52 @@ def _sb_render_thread(board_id: str, pass_name: str, only: list | None) -> None:
if not pending:
break
+ policy = (board.get("policy") or {}).get(pass_name) or {}
+ h3_ok = _sb_h3_available()
+ # ANCHOR STILLS. Shots that want a still and do not have one yet
+ # get an image job each, queued the ordinary way, and this thread
+ # waits for the batch before the video jobs are built — the still
+ # is what the video job starts from. A still that fails leaves
+ # the shot to render unanchored, once, with the error on the card.
+ if board.get("anchor_stills"):
+ # LTX shots only: an H3 shot cannot start from the still, so
+ # making one would be an image nobody uses.
+ _emode = board.get("engine_mode") or "auto"
+ need = [s for s in pending
+ if storyboard.shot_wants_still(s) and not s.get("still")
+ and not s.get("still_job_id")
+ and storyboard.resolve_engine(s, engine_mode=_emode, h3_available=h3_ok) != "h3"]
+ if need:
+ sids = []
+ for shot in need:
+ try:
+ form = _sb_still_job_form(shot, board, policy)
+ jid = _sb_enqueue({k: ("" if v is None else str(v)) for k, v in form.items()})
+ except Exception as exc: # noqa: BLE001
+ push(f"[storyboard] shot {shot.get('n')} still could not be queued: {exc}")
+ shot["still_error"] = str(exc)
+ shot["still_job_id"] = "skipped"
+ continue
+ shot["still_job_id"] = jid
+ sids.append(jid)
+ storyboard.save_storyboard(STATE_DIR, board)
+ if sids:
+ push(f"[storyboard] {len(sids)} anchor still(s) queued — {board.get('title')}")
+ while True:
+ with _SB_LOCK:
+ entry = _SB_RENDERS.get(board_id)
+ if not entry or entry.get("stop"):
+ return
+ idx = _sb_job_index()
+ if not [j for j in sids if (idx.get(j) or {}).get("status") in ("queued", "running")]:
+ break
+ time.sleep(3.0)
+ board = storyboard.load_storyboard(STATE_DIR, board_id)
+ _sb_reconcile(board)
+ storyboard.save_storyboard(STATE_DIR, board)
+ continue
bucket = storyboard.bucket_key(pending[0])
batch = [s for s in pending if storyboard.bucket_key(s) == bucket]
- policy = (board.get("policy") or {}).get(pass_name) or {}
h3_ok = _sb_h3_available()
# Does THIS install's runner take `--chain-prompts`? A pack cloned
# before that flag landed renders 10 s fine and cannot be told what
@@ -15790,7 +16341,9 @@ def _sb_render_thread(board_id: str, pass_name: str, only: list | None) -> None:
engine_mode=board.get("engine_mode") or "auto",
h3_chain_prompts=chain_ok,
locations=storyboard.board_locations(board),
- wardrobe=storyboard.board_wardrobe(board))
+ wardrobe=storyboard.board_wardrobe(board),
+ long_windows=bool(board.get("long_windows")),
+ style=str(board.get("style") or ""))
# make_job reads a form: every value is a string (or a list of
# them). Normalise here so a bool/int never reaches f().
job_form = {k: ("" if v is None else str(v)) for k, v in form.items()}
@@ -15837,17 +16390,81 @@ def _sb_render_thread(board_id: str, pass_name: str, only: list | None) -> None:
push(f"[storyboard] render dispatch stopped: {exc}")
finally:
with _SB_LOCK:
- _SB_RENDERS.pop(board_id, None)
+ _entry = _SB_RENDERS.pop(board_id, None)
+ stopped = bool((_entry or {}).get("stop"))
try:
board = storyboard.load_storyboard(STATE_DIR, board_id)
if _sb_reconcile(board):
storyboard.save_storyboard(STATE_DIR, board)
# Delivered shots don't need their draft's Stage-A cache any more.
_sb_sweep_stage_a(board)
+ if board.get("auto") and pass_name == "draft" and not stopped:
+ _sb_auto_film(board)
except Exception:
pass
+# ---------------------------------------------------------------------------
+# AUTO — the Director's whole pipeline with one press
+# ---------------------------------------------------------------------------
+# Plan → render every shot → cut to the beat → make the film. Each step is
+# the panel's existing one (the same threads the buttons start, the same
+# auto-edit the Editor's first GET runs, the same assembler Render uses);
+# what is new is only the hand-over between them, so nothing here can make a
+# different film from the one the buttons would.
+def _sb_auto_after_plan(board_id: str) -> None:
+ """Start the draft render once the planner has given the memory back."""
+ def run() -> None:
+ for _ in range(240): # the planner's unload
+ with _SB_LOCK:
+ if board_id not in _SB_PLANNERS:
+ break
+ time.sleep(0.5)
+ with _SB_LOCK:
+ if _SB_RENDERS.get(board_id):
+ return
+ _SB_RENDERS[board_id] = {"stop": False, "pass": "draft", "queued": 0,
+ "auto": True}
+ push(f"[storyboard] auto: rendering every shot of the plan")
+ th = threading.Thread(target=_sb_render_thread, daemon=True,
+ name=f"phos-sb-render-{board_id}",
+ args=(board_id, "draft", None))
+ with _SB_LOCK:
+ _SB_RENDERS[board_id]["thread"] = th
+ th.start()
+ threading.Thread(target=run, daemon=True, name=f"phos-sb-auto-{board_id}").start()
+
+
+def _sb_auto_film(board: dict) -> dict | None:
+ """Cut and assemble once every shot has rendered. None when it cannot."""
+ shots = [s for s in (board.get("shots") or []) if isinstance(s, dict)
+ and s.get("status") != "skipped"]
+ if not shots or any(not (s.get("draft_output") or s.get("final_output")) for s in shots):
+ missing = sum(1 for s in shots if not (s.get("draft_output") or s.get("final_output")))
+ push(f"[storyboard] auto: {missing} shot(s) did not render — the film waits "
+ f"for you to re-render or skip them")
+ return None
+ sedit = _sbe_import()
+ bdir = _sbe_board_dir(board["id"])
+ edit = _sbe_auto_edit(board)
+ try:
+ sedit.save_edit(bdir, edit)
+ edit = sedit.load_edit(bdir) or edit
+ except sedit.EditError as exc:
+ push(f"[storyboard] auto: the cut could not be saved: {exc}")
+ return None
+ push(f"[storyboard] auto: cut {len(edit.get('clips') or [])} shots"
+ + (" on the beat" if edit.get("beats") else "") + " — assembling the film")
+ film = _sbe_render_edit(board, edit)
+ if film.get("ok"):
+ board["auto_film"] = film.get("path")
+ storyboard.save_storyboard(STATE_DIR, board)
+ push(f"[storyboard] auto: film ready — {Path(str(film['path'])).name}")
+ else:
+ push(f"[storyboard] auto: the film could not be assembled: {film.get('error')}")
+ return film
+
+
def _sb_cancel_running_shot(job_ids) -> str | None:
"""Cancel the in-flight render IF it is one of this film's shots.
@@ -16398,6 +17015,18 @@ def _sb_cut_index(plan) -> dict:
win["mute"] = True
if isinstance(entry.get("fx"), dict) and entry["fx"]:
win["fx"] = dict(entry["fx"])
+ try:
+ sp = float(entry.get("speed") or 1.0)
+ except (TypeError, ValueError):
+ sp = 1.0
+ if abs(sp - 1.0) > 1e-9:
+ win["speed"] = sp
+ if isinstance(entry.get("transition"), dict):
+ win["transition"] = dict(entry["transition"])
+ if entry.get("tx_in"):
+ win["tx_in"] = float(entry["tx_in"])
+ if isinstance(entry.get("frame"), dict) and entry["frame"]:
+ win["frame"] = dict(entry["frame"])
out.setdefault(str(Path(str(entry["path"]))), []).append(win)
return out
@@ -16485,6 +17114,38 @@ def _sb_fade_term(fx, seconds: float, *, alpha: bool = False) -> str:
return out
+def _sb_frame_term(frame) -> str:
+ """`crop=…,` for a reframed segment, or "" for every other one.
+
+ THE EMPTY STRING IS THE POINT, as with brightness: a clip nobody
+ reframed adds no filter. The crop is the source's own pixels — the window
+ is `iw/zoom` by `ih/zoom` with its centre at the fraction (`x`, `y`) of
+ the picture — and the scale-to-fit that follows in every segment chain
+ magnifies it to the frame. Expressed with ffmpeg's `iw`/`ih` so one
+ string is right for a 640-wide draft and a 1280-wide delivery alike.
+ Runs BEFORE `fps=`/`scale=` and after `trim`, so it composes with the
+ window and with speed without either knowing.
+ """
+ if not isinstance(frame, dict):
+ return ""
+ try:
+ z = float(frame.get("zoom") or 1.0)
+ x = float(frame.get("x", 0.5))
+ y = float(frame.get("y", 0.5))
+ except (TypeError, ValueError):
+ return ""
+ if z != z or z <= 1.0 + 1e-9:
+ return ""
+ z = min(3.0, z)
+ x = max(0.0, min(1.0, x))
+ y = max(0.0, min(1.0, y))
+ # Even sizes: a 4:2:0 encode has no odd-dimension form, and a crop that
+ # lands on an odd width fails the whole graph.
+ return (f"crop=w=2*floor(iw/{z:.6f}/2):h=2*floor(ih/{z:.6f}/2):"
+ f"x=(iw-2*floor(iw/{z:.6f}/2))*{x:.6f}:"
+ f"y=(ih-2*floor(ih/{z:.6f}/2))*{y:.6f},")
+
+
def _sb_brightness_term(adjust) -> str:
"""`eq=brightness=X,` for a graded segment, or "" for every other one.
@@ -16540,10 +17201,96 @@ def _sb_seg_seconds(sg: dict) -> float:
return max(0.0, float(sg.get("duration") or 0.0))
info = sg.get("info") or {}
cut = sg.get("window")
+ # AT THE CLIP'S SPEED: the window is source seconds, the answer is film
+ # seconds. A transition's extra head and tail are NOT in this number — the
+ # film is exactly as long as the timeline says, which is the whole point
+ # of building the overlap from source handles.
+ speed = _sb_seg_speed(sg)
if cut:
return min(max(0.0, float(cut["end"]) - float(cut["start"])),
- float(info["duration"]))
- return float(info["duration"])
+ float(info["duration"])) / speed
+ return float(info["duration"]) / speed
+
+
+def _sb_seg_speed(sg: dict) -> float:
+ try:
+ sp = float((sg or {}).get("speed") or 1.0)
+ except (TypeError, ValueError):
+ return 1.0
+ return sp if sp > 0 else 1.0
+
+
+def _sb_atempo_term(speed: float) -> str:
+ """`atempo=…,` chained so every stage stays inside ffmpeg's 0.5–2.0
+ window, or "" at 1x. 0.25x is `atempo=0.5,atempo=0.5,`; 4x is
+ `atempo=2.0,atempo=2.0,`. The empty string at 1x is the point: a clip
+ nobody retimed builds the identical audio chain it always did."""
+ sp = float(speed or 1.0)
+ if abs(sp - 1.0) < 1e-9 or sp <= 0:
+ return ""
+ parts = []
+ while sp > 2.0 + 1e-9:
+ parts.append(2.0)
+ sp /= 2.0
+ while sp < 0.5 - 1e-9:
+ parts.append(0.5)
+ sp /= 0.5
+ parts.append(sp)
+ return "".join(f"atempo={p:.6f}," for p in parts)
+
+
+def _sb_seg_extension(sg: dict) -> tuple[float, float]:
+ """(extra head, extra tail) in FILM seconds a transition asks of this
+ segment's picture. Zero for every segment that joins nothing."""
+ tx_in = max(0.0, float((sg or {}).get("tx_in") or 0.0))
+ t = (sg or {}).get("transition")
+ tx_out = max(0.0, float(t.get("duration") or 0.0)) / 2.0 if isinstance(t, dict) else 0.0
+ return tx_in, tx_out
+
+
+def _sb_picture_chains(vlabels: list[str], segs: list[dict],
+ pic_lens: list[float]) -> list[str]:
+ """The picture lane's concat, ending in `[vcat]` — split at every
+ transition and re-joined with `xfade`.
+
+ WITH NO TRANSITION this is the single `concat=n=N:v=1:a=0[vcat]` it has
+ always been, character for character. With one, the segments either side
+ of the boundary are concatenated as before into two runs, and the runs
+ are crossfaded: the outgoing run carries half the transition of EXTRA
+ tail (source beyond the out-point) and the incoming run half of extra
+ head, so `offset = len(run) - duration` puts the dissolve CENTRED on the
+ cut and the output is exactly `sum(film seconds)` long — the timeline's
+ own length, which is why the sound never has to know.
+ """
+ groups: list[list[int]] = []
+ cur: list[int] = []
+ for i, sg in enumerate(segs):
+ cur.append(i)
+ if isinstance(sg.get("transition"), dict) and i + 1 < len(segs):
+ groups.append(cur)
+ cur = []
+ if cur:
+ groups.append(cur)
+ if len(groups) <= 1:
+ return [f"{''.join(vlabels)}concat=n={len(segs)}:v=1:a=0[vcat]"]
+ chains: list[str] = []
+ lens: list[float] = []
+ for g, idxs in enumerate(groups):
+ chains.append(f"{''.join(vlabels[i] for i in idxs)}"
+ f"concat=n={len(idxs)}:v=1:a=0[pg{g}]")
+ lens.append(sum(pic_lens[i] for i in idxs))
+ base, cur_len = "[pg0]", lens[0]
+ for g in range(1, len(groups)):
+ t = segs[groups[g - 1][-1]]["transition"]
+ d = float(t.get("duration") or 0.0)
+ kind = "fadeblack" if str(t.get("kind")) == "fade_black" else "fade"
+ offset = max(0.0, cur_len - d)
+ lab = "[vcat]" if g == len(groups) - 1 else f"[px{g}]"
+ chains.append(f"{base}[pg{g}]xfade=transition={kind}:"
+ f"duration={d:.6f}:offset={offset:.6f}{lab}")
+ cur_len = cur_len + lens[g] - d
+ base = lab
+ return chains
def _sb_split_audio_plan(segs: list[dict]) -> dict:
@@ -16564,7 +17311,15 @@ def _sb_split_audio_plan(segs: list[dict]) -> dict:
for i, sg in enumerate(segs):
n = _sb_seg_seconds(sg)
kind = str(sg.get("kind") or "video")
+ speed = _sb_seg_speed(sg)
has_audio = bool((sg.get("info") or {}).get("has_audio")) and kind == "video"
+ # A TRANSITION SPLITS THE PICTURE CONCAT, so the sound can no longer
+ # ride the same `concat … a=1` — it takes the lane path, which lays
+ # it out from these same film seconds and is untouched by the
+ # picture's extra handles. Nothing about the sound changes; only
+ # which graph carries it.
+ if isinstance(sg.get("transition"), dict) or sg.get("tx_in"):
+ split = True
# MUTE IS THE ABSENCE OF A LANE. This graph lays sound and silence end
# to end with `concat`, so "do not play this clip" is expressed by
# contributing no row and letting the hush fill the slot — no volume
@@ -16580,45 +17335,52 @@ def _sb_split_audio_plan(segs: list[dict]) -> dict:
if aud:
split = True
rows.append({"idx": i, "start": float(aud["start"]),
- "end": float(aud["end"]),
+ "end": float(aud["end"]), "speed": speed,
"at": cum + float(aud.get("delta") or 0.0)})
else:
cut = sg.get("window")
st = float(cut["start"]) if cut else 0.0
- rows.append({"idx": i, "start": st, "end": st + n, "at": cum})
+ # SOURCE seconds on both ends: `n` is film seconds, so the
+ # window a retimed clip plays is `n * speed` of the take.
+ rows.append({"idx": i, "start": st, "end": st + n * speed,
+ "speed": speed, "at": cum})
cum += n
total = round(cum, 6)
rows.sort(key=lambda r: r["at"])
lanes = []
for r in rows:
- at, st, en = r["at"], r["start"], r["end"]
+ at, st, en, sp = r["at"], r["start"], r["end"], r["speed"]
if at < 0:
# A J-cut on the FIRST clip has nothing to lead from, so the head
# is CUT rather than shifted — shifting would slide the whole
# performance late against a picture that did not move.
- st += -at
+ st += -at * sp
at = 0.0
- if en - st <= 1e-6 or at >= total - 1e-6:
+ if (en - st) / sp <= 1e-6 or at >= total - 1e-6:
continue
- if at + (en - st) > total: # an L-cut past the last frame is cut
- en = st + (total - at)
- lanes.append({"idx": r["idx"], "start": st, "end": en, "at": at})
+ if at + (en - st) / sp > total: # an L-cut past the last frame is cut
+ en = st + (total - at) * sp
+ lanes.append({"idx": r["idx"], "start": st, "end": en, "at": at,
+ "speed": sp})
# THE INCOMING SOUND WINS ITS OWN START, and that IS the J-cut: the
# OUTGOING clip's tail is what gives way. Trimming the incoming head
# instead would put its first syllable back where the picture cuts, which
# is the edit the user was trying to get away from.
for a, b in zip(lanes, lanes[1:]):
room = b["at"] - a["at"]
- if a["end"] - a["start"] > room + 1e-9:
- a["end"] = a["start"] + max(0.0, room)
+ if (a["end"] - a["start"]) / a["speed"] > room + 1e-9:
+ a["end"] = a["start"] + max(0.0, room) * a["speed"]
out = []
for L in lanes:
- n = L["end"] - L["start"]
+ n = (L["end"] - L["start"]) / L["speed"]
if n <= 1e-6:
continue # entirely covered by its neighbour
- out.append({"idx": L["idx"], "start": round(L["start"], 6),
- "end": round(L["end"], 6), "at": round(L["at"], 6),
- "len": round(n, 6)})
+ lane = {"idx": L["idx"], "start": round(L["start"], 6),
+ "end": round(L["end"], 6), "at": round(L["at"], 6),
+ "len": round(n, 6)}
+ if abs(L["speed"] - 1.0) > 1e-9:
+ lane["speed"] = L["speed"]
+ out.append(lane)
return {"split": split, "total": total, "lanes": out}
@@ -16693,7 +17455,8 @@ def _sb_film_filtergraph(probes: list[tuple], target_w: int, target_h: int,
music: dict | None = None,
overlays: list | None = None,
overlay_base: int = 0,
- segments: list[dict] | None = None) -> tuple[str, str]:
+ segments: list[dict] | None = None,
+ scale_to: int = 0, grain: int = 0) -> tuple[str, str]:
"""The concat FILTER graph for a mixed-geometry cut → (graph, video_label).
A bare concat DEMUXER cannot do this job. The shots in one film are not
@@ -16769,56 +17532,79 @@ def _sb_film_filtergraph(probes: list[tuple], target_w: int, target_h: int,
# the thing the bed is ducking against.
silent_segments = bool(music) and music_mode == "replace"
total = 0.0
+ pic_lens: list[float] = []
for idx, sg in enumerate(segs):
kind = str(sg.get("kind") or "video")
info = sg.get("info") or {}
inp = sg.get("input")
cut = sg.get("window")
bright = _sb_brightness_term(sg.get("adjust"))
+ reframe = _sb_frame_term(sg.get("frame"))
fx = sg.get("fx")
has_audio = bool(info.get("has_audio")) and kind == "video"
+ # A TRANSITION'S HANDLES. Extra picture at the head and/or the tail,
+ # in film seconds, taken from source the trims left behind. Zero for
+ # every segment that joins nothing, so the strings below are the ones
+ # they always were.
+ tx_in, tx_out = _sb_seg_extension(sg)
+ speed = _sb_seg_speed(sg)
+ tempo = _sb_atempo_term(speed)
if kind == "slug":
# NO FILE, NO INPUT, NO PROBE. `color` is a source filter, so the
# cheapest of the three kinds is also the one that needed the
# refactor: it is a chain in the graph and nothing else.
seg = max(0.0, float(sg.get("duration") or 0.0))
+ pic = seg + tx_in + tx_out
dur = f"{seg:.6f}"
total += seg
chains.append(
- f"color=c=black:s={target_w}x{target_h}:r={FPS}:d={dur},"
- f"setsar=1,{bright}{_sb_fade_term(fx, seg)}format={pix_fmt}[v{idx}]")
+ f"color=c=black:s={target_w}x{target_h}:r={FPS}:d={pic:.6f},"
+ f"setsar=1,{bright}{_sb_fade_term(fx, pic)}format={pix_fmt}[v{idx}]")
elif kind == "still":
# The picture arrives already looped to length by `-loop 1 -t D`
# on the input; the trim here pins it to the exact slot so the
# video and the synthesised silence below cannot disagree by a
# frame, which is all concat needs to go wrong.
seg = max(0.0, float(sg.get("duration") or 0.0))
+ pic = seg + tx_in + tx_out
dur = f"{seg:.6f}"
total += seg
chains.append(
- f"[{inp}:v]trim=0:{dur},setpts=PTS-STARTPTS,fps={FPS},"
+ f"[{inp}:v]trim=0:{pic:.6f},setpts=PTS-STARTPTS,{reframe}fps={FPS},"
f"scale={target_w}:{target_h}:force_original_aspect_ratio=decrease,"
f"pad={target_w}:{target_h}:(ow-iw)/2:(oh-ih)/2,"
- f"setsar=1,{bright}{_sb_fade_term(fx, seg)}format={pix_fmt}[v{idx}]")
+ f"setsar=1,{bright}{_sb_fade_term(fx, pic)}format={pix_fmt}[v{idx}]")
else:
if cut:
seg = max(0.0, float(cut["end"]) - float(cut["start"]))
- seg = min(seg, float(info["duration"]))
- head = (f"[{inp}:v]trim=start={float(cut['start']):.6f}:"
- f"end={float(cut['end']):.6f},setpts=PTS-STARTPTS,")
+ seg = min(seg, float(info["duration"])) / speed
+ pic = seg + tx_in + tx_out
+ # The handles are SOURCE seconds here — a retimed clip pulls
+ # `speed` times as much take for the same film second.
+ v0 = max(0.0, float(cut["start"]) - tx_in * speed)
+ v1 = float(cut["end"]) + tx_out * speed
+ # SPEED IS ONE TERM ON THE PICTURE'S CLOCK: `(PTS-STARTPTS)/s`
+ # runs the window fast or slow and `fps=` after it lays the
+ # result back on the film's frame grid. At 1x this is the
+ # `setpts=PTS-STARTPTS` it has always been.
+ rt = "" if abs(speed - 1.0) < 1e-9 else f"/{speed:.6f}"
+ head = (f"[{inp}:v]trim=start={v0:.6f}:end={v1:.6f},"
+ f"setpts={'(PTS-STARTPTS)' + rt if rt else 'PTS-STARTPTS'},")
ahead = (f"[{inp}:a]atrim=start={float(cut['start']):.6f}:"
- f"end={float(cut['end']):.6f},asetpts=PTS-STARTPTS,")
+ f"end={float(cut['end']):.6f},asetpts=PTS-STARTPTS,{tempo}")
else:
seg = float(info["duration"])
+ pic = seg
head = f"[{inp}:v]"
ahead = f"[{inp}:a]"
total += seg
dur = f"{seg:.6f}"
chains.append(
- f"{head}fps={FPS},"
+ f"{head}{reframe}fps={FPS},"
f"scale={target_w}:{target_h}:force_original_aspect_ratio=decrease,"
f"pad={target_w}:{target_h}:(ow-iw)/2:(oh-ih)/2,"
- f"setsar=1,{bright}{_sb_fade_term(fx, seg)}format={pix_fmt}[v{idx}]")
+ f"setsar=1,{bright}{_sb_fade_term(fx, pic)}format={pix_fmt}[v{idx}]")
+ pic_lens.append(pic)
if silent_segments:
pads.append(f"[v{idx}]")
continue
@@ -16836,7 +17622,7 @@ def _sb_film_filtergraph(probes: list[tuple], target_w: int, target_h: int,
vtail = ("," + vol.rstrip(",")) if vol else ""
chains.append(
f"[{inp}:a]atrim=start={L['start']:.6f}:end={L['end']:.6f},"
- f"asetpts=PTS-STARTPTS,aresample={rate},"
+ f"asetpts=PTS-STARTPTS,{tempo}aresample={rate},"
f"aformat=sample_fmts=fltp:channel_layouts=stereo,"
f"apad,atrim=0:{L['len']:.6f},asetpts=PTS-STARTPTS"
f"{vtail}[a{idx}]")
@@ -16872,7 +17658,7 @@ def _sb_film_filtergraph(probes: list[tuple], target_w: int, target_h: int,
bed_env = _sb_volume_term((music or {}).get("gain"))
bed_tail = ("," + bed_env.rstrip(",")) if bed_env else ""
if silent_segments:
- chains.append(f"{''.join(pads)}concat=n={len(segs)}:v=1:a=0[vcat]")
+ chains.extend(_sb_picture_chains(pads, segs, pic_lens))
# `apad` before the trim so a soundtrack shorter than the film ends in
# silence rather than ending the film.
chains.append(
@@ -16884,7 +17670,7 @@ def _sb_film_filtergraph(probes: list[tuple], target_w: int, target_h: int,
if split:
# The picture concatenates on its own; the sound was already laid
# out end to end by the plan, gaps and all.
- chains.append(f"{''.join(pads)}concat=n={len(segs)}:v=1:a=0[vcat]")
+ chains.extend(_sb_picture_chains(pads, segs, pic_lens))
chains.extend(_sb_split_audio_chains(aplan["lanes"], total, rate,
"[acat]"))
else:
@@ -16937,7 +17723,7 @@ def _sb_film_filtergraph(probes: list[tuple], target_w: int, target_h: int,
f"normalize=0,asoftclip=type=tanh:threshold={_sb_mix_ceiling():g}"
"[aout]")
elif split:
- chains.append(f"{''.join(pads)}concat=n={len(segs)}:v=1:a=0[vcat]")
+ chains.extend(_sb_picture_chains(pads, segs, pic_lens))
chains.extend(_sb_split_audio_chains(aplan["lanes"], total, rate,
"[aout]"))
else:
@@ -16994,6 +17780,17 @@ def _sb_film_filtergraph(probes: list[tuple], target_w: int, target_h: int,
# length and the audio simply ends where the last clip's sound ended,
# which is what silence after the final shot means anyway. A pad chain
# here would have been a label nothing maps.
+ # THE DELIVERY SIZE, last of all: the finished picture (overlays and
+ # all) scaled to the asked height with the aspect kept. Zero means the
+ # graph is character-for-character what it was.
+ if scale_to:
+ chains.append(f"{base}scale=-2:{int(scale_to)}:flags=lanczos[vdl]")
+ base = "[vdl]"
+ # THE FINISH, after the size: grain is added at the delivered
+ # resolution, or a 1080p upscale would magnify the grains into blotches.
+ if grain:
+ chains.append(f"{base}noise=alls={int(grain)}:allf=t+u[vgr]")
+ base = "[vgr]"
tail = bt709_vf("")
if tail:
chains.append(f"{base}{tail}[vout]")
@@ -17032,35 +17829,71 @@ def _sb_timeline_segments(timeline: list) -> tuple[list[dict], list[str], list]:
if length <= 0:
continue
adjust = entry.get("adjust") if isinstance(entry.get("adjust"), dict) else None
+ frame = entry.get("frame") if isinstance(entry.get("frame"), dict) else None
if kind == "slug":
- segs.append({"kind": "slug", "input": None, "info": None,
- "window": None, "adjust": adjust,
- "duration": length})
+ seg = {"kind": "slug", "input": None, "info": None,
+ "window": None, "adjust": adjust, "duration": length}
+ if isinstance(entry.get("transition"), dict):
+ seg["transition"] = dict(entry["transition"])
+ if entry.get("tx_in"):
+ seg["tx_in"] = max(0.0, float(entry["tx_in"]))
+ segs.append(seg)
continue
path = str(entry.get("path") or "")
+ # THE TRANSITION FIELDS RIDE THROUGH VERBATIM; whether they still
+ # make sense is decided once the whole list exists (below), because a
+ # dropped unreadable neighbour is exactly what would strand one.
+ tx = entry.get("transition") if isinstance(entry.get("transition"), dict) else None
+ try:
+ tx_in = max(0.0, float(entry.get("tx_in") or 0.0))
+ except (TypeError, ValueError):
+ tx_in = 0.0
+ tx_out = (max(0.0, float(tx.get("duration") or 0.0)) / 2.0) if tx else 0.0
if kind == "still":
info = _sb_probe_still(path)
if info is None:
unreadable.append(Path(path).name)
continue
- segs.append({"kind": "still", "input": len(inputs), "info": info,
- "window": None, "adjust": adjust,
- "duration": length, "path": path})
+ seg = {"kind": "still", "input": len(inputs), "info": info,
+ "window": None, "adjust": adjust,
+ "duration": length, "path": path}
+ if frame:
+ seg["frame"] = dict(frame)
+ if tx:
+ seg["transition"] = dict(tx)
+ if tx_in:
+ seg["tx_in"] = tx_in
+ segs.append(seg)
# `-loop 1` with an explicit `-t` is what turns one image into a
# stream of the right length. Without `-t` the loop is infinite and
- # ffmpeg runs until the disk is full.
+ # ffmpeg runs until the disk is full. A transition's handles are
+ # extra picture, so the loop runs that much longer.
inputs.append(["-loop", "1", "-framerate", str(FPS),
- "-t", f"{length:.6f}", "-i", path])
+ "-t", f"{length + tx_in + tx_out:.6f}", "-i", path])
continue
info = _sb_probe_clip(path)
if info is None:
unreadable.append(Path(path).name)
continue
+ try:
+ speed = float(entry.get("speed") or 1.0)
+ except (TypeError, ValueError):
+ speed = 1.0
+ if speed <= 0:
+ speed = 1.0
seg = {"kind": "video", "input": len(inputs), "info": info,
"window": {"start": start, "end": end},
"adjust": adjust,
- "duration": min(length, float(info["duration"])),
+ "duration": min(length, float(info["duration"])) / speed,
"path": path}
+ if abs(speed - 1.0) > 1e-9:
+ seg["speed"] = speed
+ if frame:
+ seg["frame"] = dict(frame)
+ if tx:
+ seg["transition"] = dict(tx)
+ if tx_in:
+ seg["tx_in"] = tx_in
if entry.get("mute") is True:
seg["mute"] = True
if isinstance(entry.get("fx"), dict) and entry["fx"]:
@@ -17085,9 +17918,89 @@ def _sb_timeline_segments(timeline: list) -> tuple[list[dict], list[str], list]:
pass
segs.append(seg)
inputs.append(["-i", path])
+ # A TRANSITION NEEDS BOTH OF ITS CLIPS. If the incoming one was dropped as
+ # unreadable, the outgoing one is left describing a dissolve into nothing
+ # — so the pair is reconciled here, on the list the graph will actually
+ # see: a `transition` with no `tx_in` on the next segment is removed, and
+ # a `tx_in` with no `transition` before it is removed. The film gets a
+ # hard cut there and `unreadable` already says why.
+ for i, sg in enumerate(segs):
+ nxt = segs[i + 1] if i + 1 < len(segs) else None
+ if sg.get("transition") and not (nxt and nxt.get("tx_in")):
+ sg.pop("transition", None)
+ prv = segs[i - 1] if i > 0 else None
+ if sg.get("tx_in") and not (prv and prv.get("transition")):
+ sg.pop("tx_in", None)
+ for i, sg in enumerate(segs):
+ # The still's `-t` was written before the reconciliation; rewrite it
+ # from the fields that survived so the input and the graph agree.
+ if sg.get("kind") == "still" and sg.get("input") is not None:
+ tx_in, tx_out = _sb_seg_extension(sg)
+ inputs[sg["input"]][5] = f"{float(sg['duration']) + tx_in + tx_out:.6f}"
return segs, unreadable, inputs
+# DELIVERY. What the film is encoded AS, and how big. H.264 is the panel's
+# own preset and plays everywhere; HEVC is the Mac's hardware encoder, about
+# half the bytes at the same look, and plays in Safari and Chrome on a Mac
+# (`hvc1` tag or Safari refuses it); ProRes 422 HQ is for the grade — a .mov
+# nothing here can preview but every NLE opens. Size is UP only: "as cut"
+# is the largest picture in the cut, 1080p and 4K are Lanczos to that
+# height, never a crop.
+DELIVER_FORMATS = {
+ "h264": {"label": "H.264", "ext": ".mp4"},
+ "hevc": {"label": "HEVC", "ext": ".mp4"},
+ "prores": {"label": "ProRes 422 HQ", "ext": ".mov"},
+}
+DELIVER_SIZES = {"native": 0, "1080p": 1080, "2160p": 2160}
+# FINISH: film grain on the delivered picture. A delivery-time treatment,
+# not a timeline effect — it belongs beside the format, never in the
+# document, and the preview never shows a delivery encode anyway. ffmpeg's
+# `noise` with temporal + uniform flags is real, moving grain; the two
+# strengths are the ones that read as "film" and "16 mm" on a 1080p master
+# without turning into snow.
+DELIVER_FINISH = {"none": 0, "grain": 9, "heavy_grain": 18}
+
+
+def _sb_deliver(fmt, size, finish=None) -> dict:
+ """The delivery choice, resolved: `{format, size, height, ext, label,
+ finish, grain}`."""
+ f = str(fmt or "h264").strip().lower()
+ if f not in DELIVER_FORMATS:
+ f = "h264"
+ s = str(size or "native").strip().lower()
+ if s not in DELIVER_SIZES:
+ s = "native"
+ fin = str(finish or "none").strip().lower()
+ if fin not in DELIVER_FINISH:
+ fin = "none"
+ label = DELIVER_FORMATS[f]["label"] + ("" if s == "native" else f" · {s}")
+ if fin != "none":
+ label += " · " + fin.replace("_", " ")
+ return {"format": f, "size": s, "height": DELIVER_SIZES[s],
+ "ext": DELIVER_FORMATS[f]["ext"], "finish": fin,
+ "grain": DELIVER_FINISH[fin], "label": label}
+
+
+def _sb_encode_args(deliver: dict, codec: dict) -> list[str]:
+ """The encoder half of the assembler's argv, per format."""
+ f = (deliver or {}).get("format", "h264")
+ if f == "hevc":
+ # `-q:v` is VideoToolbox's quality dial (1–100); 65 sits where x264's
+ # crf 18 does to the eye. `hvc1` is the tag QuickTime and Safari
+ # require; ffmpeg's default `hev1` plays nowhere on a Mac.
+ return ["-c:v", "hevc_videotoolbox", "-q:v", "65", "-tag:v", "hvc1",
+ "-pix_fmt", "yuv420p", *BT709_FLAGS,
+ "-movflags", "+faststart", "-c:a", "aac", "-b:a", "192k"]
+ if f == "prores":
+ return ["-c:v", "prores_ks", "-profile:v", "3", "-vendor", "apl0",
+ "-pix_fmt", "yuv422p10le", *BT709_FLAGS,
+ "-c:a", "pcm_s16le"]
+ return ["-c:v", "libx264", "-pix_fmt", codec["pix_fmt"], "-crf", codec["crf"],
+ "-preset", "medium", *BT709_FLAGS, "-movflags", "+faststart",
+ "-c:a", "aac", "-b:a", "192k"]
+
+
def _sb_assemble_film(clips: list, out_path, *, plan: list | None = None,
timeline: list | None = None,
overlays: list | None = None,
@@ -17095,7 +18008,8 @@ def _sb_assemble_film(clips: list, out_path, *, plan: list | None = None,
music_end: float | None = None,
music_delay: float = 0.0,
music_mode: str = "replace",
- music_gain: list | None = None) -> dict:
+ music_gain: list | None = None,
+ deliver: dict | None = None) -> dict:
"""Concatenate the exported shots into ONE playable film.
`clips` is the export directory's own copies, in `n` order, already
@@ -17204,6 +18118,28 @@ def _sb_assemble_film(clips: list, out_path, *, plan: list | None = None,
fe = max(fs, float(o.get("film_end") or 0.0))
if fe - fs <= 1e-6:
continue
+ if str(o.get("kind") or "") == "text":
+ # A TITLE BECOMES A CARD ON THE WAY IN. Drawn at the film's own
+ # geometry as a frame-sized RGBA PNG beside the film, then handed
+ # to the overlay chain exactly as an uploaded card would be — so
+ # it inherits the alpha handling, the fades and the z-order with
+ # no second code path. Refused, with a sentence, when there is no
+ # font to draw it with; a film with a hole where the title was is
+ # the failure this check exists to prevent.
+ sedit = _sbe_import()
+ problem = sedit.title_font_problem()
+ if problem:
+ return {"ok": False, "error": problem, "status": 400}
+ tdir = out_path.parent / ".titles"
+ png = tdir / f"title_{sedit.title_fingerprint(o, target_w, target_h)}.png"
+ try:
+ if not png.is_file():
+ sedit.render_title(o, target_w, target_h, png)
+ except Exception as exc: # noqa: BLE001
+ return {"ok": False, "status": 400,
+ "error": f"could not draw the title "
+ f"{str(o.get('text') or '')[:40]!r}: {exc}"}
+ o = dict(o, path=str(png), kind="still")
src = str(o.get("path") or "")
if not src or not Path(src).is_file():
unreadable.append(Path(src).name if src else "overlay")
@@ -17219,11 +18155,20 @@ def _sb_assemble_film(clips: list, out_path, *, plan: list | None = None,
overlay_base = (len(seg_inputs) if segments is not None else len(probes)) \
+ (1 if music else 0)
codec = output_codec_settings()
+ dl = _sb_deliver((deliver or {}).get("format"), (deliver or {}).get("size"),
+ (deliver or {}).get("finish"))
+ # ProRes is 4:2:2 10-bit; the graph's segments are normalised to the
+ # requested pix_fmt, so ask for the one the encoder will write.
+ graph_pix = "yuv422p10le" if dl["format"] == "prores" else codec["pix_fmt"]
+ # UP ONLY, and only when it changes something: a 1080p delivery of a
+ # 1080-high cut is the cut.
+ scale_to = dl["height"] if dl["height"] and dl["height"] != target_h else 0
graph, vlabel = _sb_film_filtergraph(probes, target_w, target_h, rate,
- codec["pix_fmt"], cuts=cuts,
+ graph_pix, cuts=cuts,
music=music_arg, segments=segments,
overlays=ov_rows,
- overlay_base=overlay_base)
+ overlay_base=overlay_base,
+ scale_to=scale_to, grain=dl["grain"])
cmd = [str(FFMPEG), "-y"]
if segments is not None:
@@ -17242,11 +18187,8 @@ def _sb_assemble_film(clips: list, out_path, *, plan: list | None = None,
cmd += [
"-filter_complex", graph,
"-map", vlabel, "-map", "[aout]",
- "-c:v", "libx264", "-pix_fmt", codec["pix_fmt"], "-crf", codec["crf"],
- "-preset", "medium",
- *BT709_FLAGS,
- "-movflags", "+faststart",
- "-c:a", "aac", "-b:a", "192k", "-ar", str(rate),
+ *_sb_encode_args(dl, codec),
+ "-ar", str(rate),
str(out_path),
]
try:
@@ -17273,8 +18215,14 @@ def _sb_assemble_film(clips: list, out_path, *, plan: list | None = None,
else i["duration"]
for (_c, i), w in zip(probes, _sb_segment_windows(probes, cuts)))
n_clips = len(probes)
+ if scale_to:
+ target_w = max(2, int(round(target_w * scale_to / float(target_h))))
+ target_w += target_w % 2
+ target_h = scale_to
facts = {"ok": True, "path": str(out_path), "clips": n_clips,
"width": target_w, "height": target_h,
+ "deliver": {"format": dl["format"], "size": dl["size"],
+ "finish": dl["finish"], "label": dl["label"]},
"sample_rate": rate,
"duration": round(played, 3),
"trimmed": bool(cuts) or segments is not None,
@@ -17358,21 +18306,34 @@ def _sb_plan_auto_edit(clips: list, *, music=None,
f"on the grid")
-def _sb_film_name(board: dict) -> str:
- """ONE film per board, one name.
+def _sb_film_name(board: dict, deliver: dict | None = None) -> str:
+ """ONE film per board, one name — per DELIVERY.
Export wrote `<slug>_film.mp4` and the timeline's render wrote
`<slug>_timeline.mp4`, into the same folder, from the same assembler — so
one board produced two films of the same movie and the Film screen could
only tell them apart by a chip that said which button you had pressed.
That is the whole of the 2026-08-17 "two films in one folder" finding.
+
+ A different delivery IS a different file — `_film_hevc.mp4`,
+ `_film_1080p.mp4`, `_film_prores.mov` — because a 4K ProRes master and
+ the H.264 the panel previews are both wanted, side by side.
"""
- return f"{_sb_slug(board.get('title') or 'storyboard', 6)}_film.mp4"
+ base = f"{_sb_slug(board.get('title') or 'storyboard', 6)}_film"
+ dl = deliver or {}
+ if dl.get("format") and dl["format"] != "h264":
+ base += "_" + dl["format"]
+ if dl.get("size") and dl["size"] != "native":
+ base += "_" + dl["size"]
+ if dl.get("finish") and dl["finish"] != "none":
+ base += "_" + dl["finish"]
+ return base + (dl.get("ext") or ".mp4")
def _sbe_render_edit(board: dict, edit: dict, *, music=None,
music_mode: str | None = None,
- out_name: str | None = None) -> dict:
+ out_name: str | None = None,
+ deliver: dict | None = None) -> dict:
"""Assemble the film the TIMELINE describes. The one assembler.
Both doors come here now: the Editor's Render, and Export whenever the
@@ -17391,13 +18352,26 @@ def _sbe_render_edit(board: dict, edit: dict, *, music=None,
if music and not Path(str(music)).is_file():
return {"ok": False, "error": f"no soundtrack at {music}",
"status": 400}
+ # A TRANSITION WITHOUT ITS HANDLES IS REFUSED HERE, with the validator's
+ # own sentence — the document may still carry it (a trim after the save
+ # can take a handle away), and a hard cut where a dissolve was promised is
+ # not a film anybody asked for.
+ probs = sedit.transition_problems(edit)
+ if probs:
+ return {"ok": False, "error": probs[0]["message"], "status": 400}
+ if any(sedit.overlay_kind(o) == "text" for o in sedit.overlay_items(edit)):
+ problem = sedit.title_font_problem()
+ if problem:
+ return {"ok": False, "error": problem, "status": 400}
# The soundtrack's three numbers, from the one function that owns them —
# so the render, the NLE export and the waveform on screen cannot disagree
# about where the music starts.
win = sedit.music_window(audio)
dest = _sb_film_dir(board)
dest.mkdir(parents=True, exist_ok=True)
- name = out_name or _sb_film_name(board)
+ dl = _sb_deliver((deliver or {}).get("format"), (deliver or {}).get("size"),
+ (deliver or {}).get("finish"))
+ name = out_name or _sb_film_name(board, deliver=dl)
gaps = sedit.edit_gaps(edit)
kinds = {}
for c in cuts:
@@ -17424,7 +18398,8 @@ def _sbe_render_edit(board: dict, edit: dict, *, music=None,
timeline=cuts, music=music, music_start=win["start"],
music_end=win["end"], music_delay=win["delay"], music_mode=mmode,
music_gain=sedit.bed_render_gain(edit),
- overlays=sedit.overlay_items(edit))
+ overlays=sedit.overlay_items(edit),
+ deliver=dl)
film["gaps"] = gaps
if gaps:
# An honest limitation, disclosed rather than discovered: this
@@ -17722,7 +18697,7 @@ def _sb_films(board: dict, *, probe: bool = True) -> list[dict]:
except OSError:
return out
for p in entries:
- if p.suffix.lower() != ".mp4" or _SB_SHOT_COPY_RE.match(p.name):
+ if p.suffix.lower() not in (".mp4", ".mov") or _SB_SHOT_COPY_RE.match(p.name):
continue
try:
st = p.stat()
@@ -17845,6 +18820,10 @@ def _sbe_board_clips(board: dict) -> list[dict]:
# `edit/generate`; the client uses it to drop a freshly rendered
# clip into the hole it was generated for instead of at the end.
"slot": s.get("edit_slot"),
+ # The whole prompt, for a retake to start from; the title above
+ # is what the row shows.
+ "prompt": s.get("prompt") or "",
+ "character_id": s.get("character_id") or "",
})
return out
@@ -18186,7 +19165,11 @@ def _sbe_auto_edit(board: dict, *, music: str | None = None,
bdir = _sbe_board_dir(board["id"])
clips = _sbe_board_clips(board)
cache = _sbe_prepare_cache(bdir)
- music = music or cache.get("music")
+ # THE DIRECTOR'S TRACK IS THE DEFAULT SOUNDTRACK. A board planned to a
+ # beat grid opens in the Editor already cut to it; Prepare (a cached
+ # track) and an explicit `music` still win.
+ music = (music or cache.get("music")
+ or ((board.get("soundtrack") or {}).get("path") or None))
beats = cache.get("beats") if (music and cache.get("music") == music) else None
if not clips:
return sedit.edit_from_plan([], board_id=board["id"])
@@ -18255,6 +19238,27 @@ def _sbe_relinks(board: dict, edit: dict) -> list[dict]:
if hit:
out.append({"id": c.get("id"), "path": str(c.get("path")),
**hit})
+ # RETAKES. A shot ordered from the Editor as a new take of ONE clip
+ # (`edit_slot.retake_of`) that has since rendered is offered against that
+ # clip — flagged, because a retake is a choice per take (the old one may
+ # be better), never the batch "use the finished versions" rewrite.
+ by_id = {str(c.get("id")): c for c in (edit.get("clips") or [])
+ if isinstance(c, dict) and c.get("id")}
+ for s in (board.get("shots") or []):
+ if not isinstance(s, dict):
+ continue
+ slot = s.get("edit_slot") if isinstance(s.get("edit_slot"), dict) else {}
+ target = str(slot.get("retake_of") or "")
+ new = s.get("final_output") or s.get("draft_output")
+ if not target or not new or not Path(str(new)).is_file():
+ continue
+ c = by_id.get(target)
+ if not c or str(c.get("path") or "") == str(new):
+ continue
+ out.append({"id": target, "path": str(c.get("path") or ""),
+ "to": str(new), "n": s.get("n"),
+ "title": (s.get("title") or s.get("prompt") or "")[:80],
+ "retake": True})
return out
@@ -18302,6 +19306,10 @@ def _sbe_payload(board: dict, edit: dict) -> dict:
# back to. Never an error — a J-cut is a deliberate drift — but the
# panel cannot flag what the server does not say.
"sync": sedit.edit_sync_flags(edit),
+ # THE SONG MAP, for the ruler. Sections in TRACK seconds from the
+ # Director's analysis (empty for a film with no planned soundtrack);
+ # the client puts them on the film's clock through the music window.
+ "sections": list(((board.get("soundtrack") or {}).get("sections")) or []),
# Board clips that are NOT on the timeline — a shot rendered after the
# edit was saved, or one generated into a gap that has just landed.
# Never auto-inserted: the arrangement is the human's, and a server
@@ -18848,9 +19856,45 @@ def make_job(form: dict[str, list[str]] | dict[str, str], *,
requested_upscale_method = "lanczos"
if requested_upscale_method not in ("lanczos", "pipersr"):
requested_upscale_method = "lanczos"
+ # ONE TAKE (see take_plan). Read before the fields it overrides: on LTX it
+ # is the windows chain with one prompt per window; on H3 it is 15 s parts
+ # that continue from each other, run by run_take_job_inner. The form's own
+ # length pill is overruled — a take IS the length.
+ _take: dict | None = None
+ _take_secs_raw = f("take_seconds", "")
+ if _take_secs_raw and _take_secs_raw not in ("0", "off"):
+ _take_engine = (f("engine", ENGINE_DEFAULT) or ENGINE_DEFAULT).strip().lower()
+ _take = take_plan(_take_secs_raw, _take_engine)
+ if _take is None:
+ push(f"take_seconds={_take_secs_raw!r} is not one of {TAKE_SECONDS} — rendering a normal clip")
+ else:
+ _take["beat_prompts"] = take_beats(f("beats", ""), _take["beats"])
+ if _take["engine"] == "h3":
+ form["h3_length"] = [TAKE_H3_PART_LENGTH]
+ form["h3_chain_prompts"] = [json.dumps(
+ [_take["beat_prompts"][i] for i in _take["parts"][0]])]
+ else:
+ form["temporal_mode"] = ["windows"]
+ form["frames"] = [str(_take["frames"])]
+ form["window_prompts"] = [json.dumps(_take["beat_prompts"])]
temporal_mode = f("temporal_mode", "native").strip().lower()
+ # SLIDING WINDOWS ride the same control as Long Clip Boost — one "Long
+ # clips" row, three answers — and are stored as `long_mode` so the render
+ # path reads one flag per lane. `window_prompts` is one line per window
+ # (blank = hold the previous moment), the H3 chain's wire shape.
+ long_mode = "windows" if temporal_mode == "windows" else "native"
if temporal_mode not in ("native", "fps12_interp24"):
temporal_mode = "native"
+ _wp_raw = f("window_prompts", "")
+ window_prompts: list[str] = []
+ if _wp_raw:
+ try:
+ _wp = json.loads(_wp_raw)
+ if isinstance(_wp, list):
+ window_prompts = [str(x or "").strip() for x in _wp]
+ except (TypeError, ValueError):
+ window_prompts = [x.strip() for x in str(_wp_raw).split("\n")]
+ window_invariants = f("window_invariants", "").strip()
# Optional Characters-tab origin fields. The /characters/<id>/generate
# endpoint stamps these onto the form so the sidecar records enough state
@@ -19092,7 +20136,7 @@ def make_job(form: dict[str, list[str]] | dict[str, str], *,
# The adapter is distilled FOR 4 sigma points. Honouring a Steps pill on
# top of it would quietly render a configuration nobody validated, so
# Turbo wins and says so rather than losing to a leftover pill.
- push(f"Turbo pins the sampler at {H3_TURBO_STEPS} steps — ignoring the "
+ push(f"Turbo pins the sampler at {h3_turbo_steps()} steps — ignoring the "
f"{_h3_steps}-step override.")
_h3_steps = 0
@@ -19154,6 +20198,7 @@ def make_job(form: dict[str, list[str]] | dict[str, str], *,
# trap as every key in this dict: leave it out and the whole
# control looks wired and silently no-ops on /queue/add.
"h3_chain_prompts": _h3_chain_prompts,
+ "take": _take,
# LTX-2.5 distilled schedule preset — "" (tuned default) or
# "fast"/"vendor", already gated above to the lane that defines
# it. SAME allowlist trap as every key in this dict: leave it out
@@ -19226,6 +20271,11 @@ def make_job(form: dict[str, list[str]] | dict[str, str], *,
"quality": quality, # quick / balanced / standard / high
"accel": f("accel", "off"), # off / boost / turbo
"temporal_mode": temporal_mode, # native / fps12_interp24
+ # Sliding windows (ltx_windows.py). Same allowlist trap as every
+ # key here: leave one out and the control silently no-ops.
+ "long_mode": long_mode, # native / windows
+ "window_prompts": window_prompts,
+ "window_invariants": window_invariants,
"upscale": upscale, # off / fit_720p / x2
"upscale_method": requested_upscale_method, # lanczos / pipersr
# LoRAs the user has enabled for this job. The UI submits a
@@ -19343,7 +20393,7 @@ def make_job(form: dict[str, list[str]] | dict[str, str], *,
# both ride the SAME path the tier default does (nothing downstream
# branches on WHY the count is what it is).
job["params"]["steps"] = int(
- H3_TURBO_STEPS if _h3_turbo else (_h3_steps or _tier_cfg["steps"]))
+ h3_turbo_steps() if _h3_turbo else (_h3_steps or _tier_cfg["steps"]))
job["params"]["h3_chain_windows"] = int(_tier_cfg.get("chain_windows") or 1)
job["params"]["h3_window_frames"] = int(
_tier_cfg.get("window_frames") or _tier_cfg["frames"])
@@ -19927,7 +20977,9 @@ def run_image_job_inner(job: dict) -> None:
raise RuntimeError("each ref must be a non-empty path string")
rp = Path(r)
rp = (rp if rp.is_absolute() else (UPLOADS / r)).resolve()
- allowed = [UPLOADS.resolve(), OUTPUT.resolve()]
+ # The character sheets are a legitimate reference too: the Storyboard's
+ # anchor stills are drawn from a character's own sheet.
+ allowed = [UPLOADS.resolve(), OUTPUT.resolve(), _CHARACTERS_CACHE_PATH.resolve()]
if not any(rp.is_relative_to(root) for root in allowed):
raise RuntimeError(f"ref path not under uploads/outputs: {r}")
if not rp.is_file():
@@ -21259,9 +22311,9 @@ def run_h3_job_inner(job: dict) -> None:
"Turbo's adapter isn't on disk: "
+ "; ".join(turbo_paths["missing"])
+ f". Expected under {turbo_paths['dir']} — turn Turbo off, or "
- f"install {H3_TURBO_LORA_FILE} (or the safe folded v0.1 "
- f"fallback) under {turbo_paths['dir']}.")
- steps = H3_TURBO_STEPS
+ f"install {H3_TURBO_V4_FILE} (or {H3_TURBO_LORA_FILE}, or the safe "
+ f"folded v0.1 fallback) under {turbo_paths['dir']}.")
+ steps = h3_turbo_steps(turbo_paths)
# First-frame conditioning (Image mode). The flag landed on the runner
# after the first public branch, so probe the INSTALLED script rather than
@@ -21476,7 +22528,7 @@ def run_h3_job_inner(job: dict) -> None:
+ (" · per-window prompts" if chain_prompts else "")
+ (f" · first frame {first_frame.name}" if first_frame else ""))
if turbo:
- push(f"[h3] {H3_TURBO_NOTE}")
+ push(f"[h3] {h3_turbo_note(turbo_paths)}")
# The shot list, in the log, in render order — so a clip whose second beat
# didn't land can be diagnosed from the log alone.
for _i, _wp in enumerate(chain_prompts, 1):
@@ -21891,6 +22943,198 @@ def run_h3_job_inner(job: dict) -> None:
subprocess.run(["open", str(final_target)], check=False)
+def _run_windows_chain(job: dict, p: dict, plan: dict, first: Path,
+ raw_out: Path, total_frames: int) -> dict:
+ """Windows 2..N as `extend` passes, each on ONLY the last window of the
+ previous output, then the new frames of every window joined and trimmed
+ to length into `raw_out`. Returns the plan with what happened.
+
+ CONSTANT TIME PER WINDOW (2026-09-05). The first version handed each
+ extend the whole clip so far, and Extend encodes and conditions on every
+ frame it is given: window 2 took 10 min, window 3 17, window 4 26 — a
+ 30 s take was heading for three hours. The model only needs the tail for
+ continuity, so each pass now sees the last `window` frames (after the
+ plan's `discard` is dropped), renders `new_frames` after them, and only
+ those new frames go into the join. Every intermediate file is kept beside
+ the final one and hidden from the gallery — a chain that dies at window 4
+ leaves windows 1–3 on disk, which is the difference between a resumable
+ clip and a lost hour.
+ """
+ import ltx_windows as _lw # noqa: PLC0415
+ prompts = _lw.window_prompts(p.get("prompt") or "", p.get("window_prompts") or [],
+ invariants=p.get("window_invariants") or "",
+ count=plan["count"])
+ plan = dict(plan, prompts=prompts, files=[str(first)])
+ codec = output_codec_settings()
+ fps = float(FPS)
+ # WORKING FILES LIVE OUTSIDE THE GALLERY. Tails, window outputs and pieces
+ # used to be written beside the final clip and hidden per panel — and the
+ # hidden list is per panel, so a second panel sharing the outputs folder
+ # (the owner's, next to a test instance) showed every one of them as a
+ # finished video. A dot-folder is invisible to every gallery listing.
+ work = OUTPUT / ".windows" / str(job.get("id") or "take")
+ work.mkdir(parents=True, exist_ok=True)
+ ctx = int(plan.get("window") or _lw.DEFAULT_WINDOW)
+ discard = int(plan.get("discard") or 0)
+ enc = ["-c:v", "libx264", "-pix_fmt", codec["pix_fmt"], "-crf", codec["crf"],
+ "-preset", "fast", *BT709_FLAGS, "-c:a", "aac", "-b:a", "192k"]
+ pieces = [str(first)]
+ cur = first
+ cur_frames = ctx # the first pass is one window
+ for w in plan["windows"][1:]:
+ k = w["index"]
+ # 1. THE CONTEXT: the last `ctx` frames of the previous output, its
+ # `discard` tail dropped first. Frame-exact through `select`.
+ end = cur_frames - discard - 1
+ start = max(0, end - ctx + 1)
+ tail = work / f"{raw_out.stem}_w{k - 1}t{raw_out.suffix}"
+ run_ffmpeg_tracked([
+ str(FFMPEG), "-y", "-i", str(cur),
+ "-vf", f"select='between(n\\,{start}\\,{end})',setpts=N/FRAME_RATE/TB",
+ "-af", f"atrim=start={start / fps:.6f}:end={(end + 1) / fps:.6f},asetpts=PTS-STARTPTS",
+ *enc, "-movflags", "+faststart", str(tail)], f"Windows: tail {k - 1}")
+ ctx_frames = end - start + 1
+ out = work / f"{raw_out.stem}_w{k}{raw_out.suffix}"
+ seed = p.get("seed_used") if p.get("seed_used") is not None else p.get("seed")
+ try:
+ seed = int(seed)
+ except (TypeError, ValueError):
+ seed = -1
+ spec = {
+ "action": "extend",
+ "id": job["id"],
+ "params": {
+ "model_dir": str(pack_path("q8")),
+ "dev_transformer": hq_weights()["dev_transformer"],
+ "prompt": prompts[k],
+ "negative_prompt": p.get("negative_prompt", ""),
+ "video_path": str(tail),
+ "extend_frames": _lw.extend_latents(w["new_frames"]),
+ "direction": "after",
+ "output_path": str(out),
+ "seed": (seed + k) if seed >= 0 else -1,
+ "steps": int(p.get("extend_steps") or 8),
+ "cfg_scale": 1.0,
+ "loras": p.get("loras") or [],
+ },
+ }
+ push(f"[windows] window {k + 1}/{plan['count']}: +{w['new_frames']}f "
+ f"after {ctx_frames}f of context · \"{prompts[k][:60]}\"")
+ res = HELPER.run(spec)
+ if not out.is_file():
+ raise RuntimeError(f"window {k + 1} produced no file ({res.get('error') or 'no output'})")
+ plan["files"].append(str(out))
+ # 2. THE PIECE: only the frames this window added.
+ piece = work / f"{raw_out.stem}_w{k}p{raw_out.suffix}"
+ run_ffmpeg_tracked([
+ str(FFMPEG), "-y", "-i", str(out),
+ "-vf", f"select='gte(n\\,{ctx_frames})',setpts=N/FRAME_RATE/TB",
+ "-af", f"atrim=start={ctx_frames / fps:.6f},asetpts=PTS-STARTPTS",
+ *enc, "-movflags", "+faststart", str(piece)], f"Windows: piece {k}")
+ pieces.append(str(piece))
+ for f in (str(cur), str(tail), str(out), str(piece)):
+ set_hidden(f, True)
+ cur = out
+ cur_frames = ctx_frames + int(w["new_frames"])
+ # 3. THE JOIN, trimmed to the asked length.
+ keep = min(int(total_frames), int(plan["delivered_frames"]))
+ lst = work / f"{raw_out.stem}_windows.txt"
+ lst.write_text("".join(f"file '{x}'\n" for x in pieces))
+ run_ffmpeg_tracked([
+ str(FFMPEG), "-y", "-f", "concat", "-safe", "0", "-i", str(lst), "-t", f"{keep / fps:.6f}",
+ "-c:v", "libx264", "-pix_fmt", codec["pix_fmt"], "-crf", codec["crf"],
+ "-preset", "medium", *BT709_FLAGS, "-c:a", "aac", "-b:a", "192k",
+ "-movflags", "+faststart", str(raw_out)], "Windows: final join")
+ set_hidden(str(cur), True)
+ plan["output_frames"] = keep
+ plan["pieces"] = pieces
+ push(f"[windows] {plan['count']} windows → {raw_out.name} ({keep}f)")
+ return plan
+
+
+def run_take_job_inner(job: dict) -> None:
+ """An H3 take: N parts of 15 s, each three beats, each continuing from the
+ last frame of the part before, joined into one clip. Every part is an
+ ORDINARY H3 render through run_h3_job_inner with a derived job, so LoRAs,
+ Turbo, the export size and the log all behave as they do for a single
+ clip. Stop between parts is honoured through the parent's
+ `cancel_requested` (a running part dies with the H3 process group)."""
+ p = job["params"]
+ take = p["take"]
+ beats = list(take.get("beat_prompts") or [])
+ parts = take["parts"]
+ n_parts = len(parts)
+ label = p.get("label") or ""
+ t0 = time.time()
+ take_dir = STATE_DIR / "take" / job["id"]
+ take_dir.mkdir(parents=True, exist_ok=True)
+ ff = str(FFMPEG)
+ outs: list[str] = []
+ last_png: str | None = None
+ push(f"[take] {take['seconds']} s · {take['beats']} beats · {n_parts} parts on H3")
+ for k, idxs in enumerate(parts):
+ if job.get("cancel_requested"):
+ raise RuntimeError("stopped between parts")
+ chain = [beats[i] if i < len(beats) else "" for i in idxs]
+ if not chain[0]:
+ chain[0] = p.get("prompt") or ""
+ child_params = dict(p)
+ child_params.update({
+ "take": None,
+ "h3_chain_prompts": chain,
+ "prompt": chain[0],
+ "label": f"{label or 'take'} · part {k + 1} of {n_parts}",
+ "mode": "i2v" if last_png else p.get("mode", "t2v"),
+ "open_when_done": False,
+ })
+ if last_png:
+ child_params["image"] = last_png
+ child = {"id": f"{job['id']}-p{k + 1}", "params": child_params,
+ "status": "running", "created_at": job.get("created_at")}
+ push(f"[take] beats {idxs[0] + 1}–{idxs[-1] + 1} of {take['beats']} · part {k + 1} of {n_parts}"
+ + (" · continues from the last frame" if last_png else ""))
+ run_h3_job_inner(child)
+ out = child.get("output_path")
+ if not out or not Path(out).is_file():
+ raise RuntimeError(f"part {k + 1} produced no clip")
+ outs.append(out)
+ # Parts are working files: kept, hidden from the gallery. The take is
+ # the output.
+ try:
+ set_hidden(str(out), True)
+ except Exception: # noqa: BLE001
+ pass
+ last_png = str(take_dir / f"part{k + 1}_last.png")
+ subprocess.run([ff, "-loglevel", "error", "-y", "-sseof", "-0.05", "-i", out,
+ "-frames:v", "1", "-update", "1", last_png], check=True)
+ job["take_progress"] = {"part": k + 1, "parts": n_parts}
+ if job.get("cancel_requested"):
+ raise RuntimeError("stopped before the join")
+ lst = take_dir / "concat.txt"
+ lst.write_text("".join(f"file '{o}'\n" for o in outs))
+ final = _unique_output_path(
+ OUTPUT, _descriptive_filename(label, p.get("prompt") or "", fallback="take") + f"_take{take['seconds']}s")
+ push(f"[take] joining {n_parts} parts → {final.name}")
+ subprocess.run([ff, "-loglevel", "error", "-y", "-f", "concat", "-safe", "0", "-i", str(lst),
+ "-c:v", "libx264", "-preset", "medium", "-crf", "17", "-pix_fmt", "yuv420p",
+ "-c:a", "aac", "-b:a", "192k", "-movflags", "+faststart", str(final)], check=True)
+ side: dict = {}
+ try:
+ side = json.loads(Path(outs[-1] + ".json").read_text())
+ except (OSError, ValueError):
+ side = {}
+ side.update({
+ "mode": p.get("mode", "t2v"), "engine": "h3", "prompt": p.get("prompt") or "",
+ "label": label, "elapsed_sec": round(time.time() - t0, 1),
+ "frames": take["frames"], "seconds": take["seconds"],
+ "take": {"seconds": take["seconds"], "beats": beats, "parts": outs, "engine": "h3"},
+ "h3_chain_prompts": beats,
+ })
+ write_sidecar(final.with_suffix(final.suffix + ".json"), side)
+ job["output_path"] = str(final)
+ push(f"[take] done in {round(time.time() - t0)}s → {final.name}")
+
+
def run_job_inner(job: dict) -> None:
p = job["params"]
mode = p["mode"]
@@ -21906,6 +23150,8 @@ def run_job_inner(job: dict) -> None:
# dispatches BEFORE every LTX-only clamp/validation below — none of which
# applies to it.
if (p.get("engine") or "ltx").strip().lower() == "h3":
+ if p.get("take"):
+ return run_take_job_inner(job)
return run_h3_job_inner(job)
# STALE-ENGINE GATE (fleet: 'Model type gemma4_unified not supported.',
# 19 events / 6 installs, every one a legacy install whose vendored engine
@@ -23051,6 +24297,53 @@ def run_job_inner(job: dict) -> None:
"requested_duration_sec": round(requested_duration, 3),
"method": "ffmpeg_minterpolate_mci",
}
+ # SLIDING WINDOWS. Past one window the clip is rendered as a SEQUENCE:
+ # one `generate` for the first window, then one `extend` per later window
+ # with that window's own prompt (ltx_windows.window_prompts), each on the
+ # kept tail of the last. The extend lane is the Q8 dev transformer, so
+ # this needs the High add-on and a tier that allows Extend — refused
+ # with the same sentences Extend itself uses rather than silently
+ # rendering one window. The memory plan is sized to ONE window, which is
+ # the whole point.
+ windows_plan = None
+ if (str(p.get("long_mode") or "native") == "windows"
+ and mode in ("t2v", "i2v") and not ltx_quality_uses_hq(quality)):
+ import ltx_windows as _lw # noqa: PLC0415
+ try:
+ windows_plan = _lw.plan_windows(frames)
+ except ValueError as exc:
+ raise RenderRefused("windows", f"Sliding windows: {exc}")
+ if windows_plan["count"] <= 1:
+ windows_plan = None
+ push(f"[windows] {frames}f fits one window — rendering natively.")
+ else:
+ if not SYSTEM_CAPS["allows_extend"]:
+ raise RenderRefused(
+ "hardware_tier",
+ f"Sliding windows chain Extend passes, and Extend isn't "
+ f"supported on the {SYSTEM_CAPS['label']} hardware tier — "
+ f"it works from {min_ram_gb_for('allows_extend') or 48} GB. "
+ f"Use Long Clip Boost or a single window instead.")
+ _ext_missing = hq_surface_missing()
+ if _ext_missing:
+ raise RenderRefused(
+ "pack_missing",
+ f"Sliding windows chain Extend passes, which need the "
+ f"LTX-2.5 High add-on (the Q8 model). Missing "
+ f"{len(_ext_missing)} file(s): {', '.join(_ext_missing[:3])}"
+ f"{' …' if len(_ext_missing) > 3 else ''}. Open Settings → "
+ f"Models and download it, then render again.")
+ if temporal_mode != "native":
+ push("[windows] Long Clip Boost and sliding windows are two "
+ "answers to one question; windows win, rendering native fps.")
+ temporal_mode = "native"
+ p["temporal_mode"] = "native"
+ temporal_plan = None
+ model_fps = delivery_fps
+ model_frames = windows_plan["window"]
+ push(f"[windows] {_lw.describe(windows_plan)}")
+ for note in windows_plan["notes"]:
+ push(f"[windows] {note}")
memory_plan = plan_memory_policy(model_frames, mode=mode, quality=quality)
# T2V/I2V resolution clamp — only applies on the base tier (< 48 GB).
@@ -23413,12 +24706,22 @@ def run_job_inner(job: dict) -> None:
push(f"Run via helper: id={job['id']} mode={mode} quality={quality} accel={p.get('accel', 'off')} "
f"{width}x{height} {model_frames}f{temporal_suffix}")
+ if windows_plan:
+ # The first window lands beside the final name; the chain writes
+ # `raw_out` itself once the last window is trimmed to length.
+ job_spec["params"]["frames"] = windows_plan["window"]
+ job_spec["params"]["output_path"] = str(
+ raw_out.with_name(raw_out.stem + "_w0" + raw_out.suffix))
result = HELPER.run(job_spec)
if "seed_used" in result:
push(f"seed used: {result['seed_used']}")
p["seed_used"] = result["seed_used"]
if result.get("memory_policy"):
memory_plan = {**memory_plan, "helper": result.get("memory_policy")}
+ if windows_plan:
+ windows_plan = _run_windows_chain(job, p, windows_plan,
+ Path(job_spec["params"]["output_path"]),
+ raw_out, frames)
final_target = raw_out
if mode == "i2v_clean_audio":
@@ -23563,6 +24866,8 @@ def run_job_inner(job: dict) -> None:
sidecar["accel_metrics"] = result["accel_metrics"]
if temporal_plan:
sidecar["temporal"] = temporal_plan
+ if windows_plan:
+ sidecar["windows"] = windows_plan
if upscale_plan:
sidecar["upscale"] = {
k: v for k, v in upscale_plan.items()
@@ -23593,6 +24898,123 @@ def run_job_inner(job: dict) -> None:
_CONSEC_FAIL: dict = {"sig": "", "n": 0} # worker_loop's same-failure streak
+# ---------------------------------------------------------------------------
+# PUSH — the completion alert that reaches a closed tab
+# ---------------------------------------------------------------------------
+# The in-tab chime needs the page open. Web Push does not: the browser keeps
+# a subscription for this origin, the panel signs each message with a VAPID
+# key pair it generates once, and the browser's own push service wakes the
+# service worker (`/sw.js`) to show the notification — Mac closed-tab, or a
+# phone that has the panel installed over an HTTPS address. No cloud relay:
+# the panel posts straight to the browser vendor's endpoint. Everything is
+# best-effort: a push that cannot be sent is a log line, never a failed job.
+def _push_dir() -> Path:
+ return STATE_DIR
+
+
+def _vapid_keys() -> dict | None:
+ """`{private, public}` (base64url), generated on first use. None when
+ pywebpush is not installed — the feature simply is not offered."""
+ try:
+ from py_vapid import Vapid, b64urlencode # noqa: PLC0415
+ from cryptography.hazmat.primitives import serialization # noqa: PLC0415
+ except Exception: # noqa: BLE001
+ return None
+ p = _push_dir() / "vapid.json"
+ if p.is_file():
+ try:
+ d = json.loads(p.read_text())
+ if d.get("private") and d.get("public"):
+ return d
+ except (OSError, ValueError):
+ pass
+ v = Vapid()
+ v.generate_keys()
+ raw_pub = v.public_key.public_bytes(serialization.Encoding.X962,
+ serialization.PublicFormat.UncompressedPoint)
+ raw_priv = v.private_key.private_numbers().private_value.to_bytes(32, "big")
+ d = {"private": b64urlencode(raw_priv), "public": b64urlencode(raw_pub)}
+ _push_dir().mkdir(parents=True, exist_ok=True)
+ p.write_text(json.dumps(d))
+ return d
+
+
+def _push_subs_path() -> Path:
+ return _push_dir() / "push_subscriptions.json"
+
+
+def _push_subs() -> list[dict]:
+ try:
+ d = json.loads(_push_subs_path().read_text())
+ return [s for s in d if isinstance(s, dict) and s.get("endpoint")] if isinstance(d, list) else []
+ except (OSError, ValueError):
+ return []
+
+
+def _push_save_subs(subs: list[dict]) -> None:
+ _push_dir().mkdir(parents=True, exist_ok=True)
+ _push_subs_path().write_text(json.dumps(subs))
+
+
+def push_available() -> bool:
+ try:
+ import pywebpush # noqa: F401,PLC0415
+ return True
+ except Exception: # noqa: BLE001
+ return False
+
+
+def push_notify(title: str, body: str, tag: str = "phos") -> int:
+ """Send one notification to every subscribed browser. Returns how many
+ were delivered; a subscription the vendor says is gone is dropped."""
+ subs = _push_subs()
+ keys = _vapid_keys() if subs else None
+ if not subs or not keys:
+ return 0
+ try:
+ from pywebpush import webpush, WebPushException # noqa: PLC0415
+ except Exception: # noqa: BLE001
+ return 0
+ sent, keep = 0, []
+ payload = json.dumps({"title": title, "body": body, "tag": tag})
+ for s in subs:
+ try:
+ webpush(subscription_info=s, data=payload,
+ vapid_private_key=keys["private"],
+ vapid_claims={"sub": "mailto:phosphene@localhost"},
+ ttl=3600, timeout=10)
+ sent += 1
+ keep.append(s)
+ except WebPushException as exc: # noqa: PERF203
+ code = getattr(getattr(exc, "response", None), "status_code", None)
+ if code in (404, 410):
+ push(f"[push] a browser's subscription is gone ({code}) — dropped")
+ continue
+ push(f"[push] could not deliver: {exc}")
+ keep.append(s)
+ except Exception as exc: # noqa: BLE001
+ push(f"[push] could not deliver: {exc}")
+ keep.append(s)
+ if len(keep) != len(subs):
+ _push_save_subs(keep)
+ return sent
+
+
+def _push_job_done(job: dict) -> None:
+ """The completion alert, pushed. Never raises."""
+ try:
+ if not get_settings().get("notify_done", True):
+ return
+ p = job.get("params") or {}
+ what = (p.get("label") or p.get("preset_label")
+ or (str(p.get("prompt") or "")[:60]) or p.get("mode") or "a render")
+ failed = job.get("status") == "failed"
+ push_notify("Phosphene — a render failed" if failed else "Phosphene — render done",
+ str(what), tag="phos-" + str(job.get("id") or ""))
+ except Exception as exc: # noqa: BLE001
+ push(f"[push] skipped: {exc}")
+
+
def worker_loop() -> None:
while True:
with QUEUE_COND:
@@ -23669,6 +25091,11 @@ def worker_loop() -> None:
f"waiting. Fix the cause above (Settings → Models for a "
f"missing or incomplete model), then press Resume.")
finally:
+ if job.get("status") in ("done", "failed"):
+ # The closed-tab alert. Off the GPU lock, best-effort, and only
+ # when the person has a browser subscribed.
+ threading.Thread(target=_push_job_done, args=(job,), daemon=True,
+ name="phos-push").start()
job["finished_at"] = iso_now()
if job.get("started_ts"):
job["elapsed_sec"] = round(time.time() - job["started_ts"], 2)
@@ -25166,6 +26593,43 @@ class Handler(BaseHTTPRequestHandler):
board["concept"] = concept
board["style"] = f("style", "")
board["must"] = must
+ # THE DIRECTOR. A soundtrack on the brief makes this a music
+ # video: the beat grid decides how many shots there are and
+ # how long each one is, the planner writes one shot per slot,
+ # and the Editor's first cut lands every shot on its downbeat
+ # under this track. Resolved HERE — a bad path is a 400 now,
+ # not a planner that ran for a minute and cut nothing.
+ _track = (f("soundtrack", "") or "").strip()
+ if "soundtrack" in form:
+ if _track and not Path(_track).is_file():
+ _sb_release_planner(bid, "-pending-")
+ self._json({"ok": False,
+ "error": f"no audio file at {_track}"}, 400)
+ return
+ try:
+ _bars = int(f("bars_per_shot", "2") or 2)
+ except (TypeError, ValueError):
+ _bars = 2
+ board["soundtrack"] = ({"path": _track,
+ "bars_per_shot": max(1, min(8, _bars))}
+ if _track else None)
+ # AUTO: plan, then render every shot, then cut and make the
+ # film, with nobody pressing the next button. Stored on the
+ # board because the two later steps run in threads that only
+ # have the board to read.
+ if "auto" in form:
+ board["auto"] = str(f("auto", "")).strip().lower() in ("1", "on", "true", "yes")
+ # ANCHOR STILLS: before a shot renders, an image of its first
+ # frame is generated (from the character's sheet when the shot
+ # has one) and the video starts FROM it — composition decided
+ # on a still that takes seconds, not a clip that takes minutes.
+ if "anchor_stills" in form:
+ board["anchor_stills"] = str(f("anchor_stills", "")).strip().lower() in ("1", "on", "true", "yes")
+ # LONG WINDOWS: a shot longer than one LTX window renders as a
+ # chain of windows on the Q8 dev transformer instead of being
+ # cut to fit (see ltx_windows.py).
+ if "long_windows" in form:
+ board["long_windows"] = str(f("long_windows", "")).strip().lower() in ("1", "on", "true", "yes")
# PATCH, never overwrite. Re-plan and Try again rebuild this
# form by hand and send neither `locations` nor `wardrobe`, so
# unconditional assignment ERASED both on the first re-plan —
@@ -25195,6 +26659,27 @@ class Handler(BaseHTTPRequestHandler):
# The slot was claimed under a placeholder before the id existed
# (a brand-new board mints its id above); move it onto the real
# one now that nothing else can fail.
+ # ONE TAKE on the brief: patched only when sent ("0" turns it
+ # off). The plan thread turns it into beats.
+ if "take_seconds" in form:
+ _ts_raw = f("take_seconds", "0") or "0"
+ try:
+ _ts = int(_ts_raw)
+ except ValueError:
+ _ts = 0
+ if _ts and _ts not in TAKE_SECONDS:
+ _sb_release_planner(bid, "-pending-")
+ self._json({"ok": False,
+ "error": f"a take must be one of {list(TAKE_SECONDS)} seconds "
+ f"(got {_ts_raw!r})."}, 400)
+ return
+ if _ts:
+ board["take_seconds"] = _ts
+ else:
+ board.pop("take_seconds", None)
+ storyboard.save_storyboard(STATE_DIR, board)
+ if board.get("take_seconds") in TAKE_SECONDS:
+ shots_n = int(board["take_seconds"]) // TAKE_BEAT_SECONDS
with _SB_LOCK:
_SB_PLANNERS.pop("-pending-", None)
_SB_PLANNERS.setdefault(bid, {"cancelled": False})
@@ -25204,10 +26689,12 @@ class Handler(BaseHTTPRequestHandler):
th = threading.Thread(
target=_sb_plan_thread, daemon=True, name=f"phos-sb-plan-{bid}",
args=(bid, {"concept": concept, "n_shots": shots_n,
+ "take_seconds": board.get("take_seconds") or 0,
"style": board["style"], "characters": chars,
"must": must, "feedback": notes or None,
"locations": board.get("locations") or [],
- "engine_mode": emode},
+ "engine_mode": emode,
+ "soundtrack": board.get("soundtrack") or None},
previous if notes else None))
with _SB_LOCK:
_SB_PLANNERS[bid]["thread"] = th
@@ -25276,7 +26763,9 @@ class Handler(BaseHTTPRequestHandler):
"error": f"shots {bad} are not objects"}, 400)
return
keep = {"draft_job_id", "final_job_id", "draft_output",
- "final_output", "error"}
+ "final_output", "error",
+ # the anchor still is server-owned too
+ "still", "still_job_id", "still_error"}
by_n = {s.get("n"): s for s in (board.get("shots") or [])
if isinstance(s, dict)}
merged = []
@@ -25343,6 +26832,28 @@ class Handler(BaseHTTPRequestHandler):
return
# ---- render --------------------------------------------------
+ if action == "restill":
+ # NEW STILL for one shot: forget its still and the clip made
+ # from it, then take the ordinary render path for that shot
+ # alone — the render thread makes the still first and the
+ # clip from it, exactly as a first render would.
+ bid = f("id", "")
+ board = load(bid)
+ pass_name = "final" if f("pass", "draft") == "final" else "draft"
+ try:
+ n = int(f("n", "0") or 0)
+ except ValueError:
+ n = 0
+ if _sb_clear_still(board, n, pass_name) is None:
+ self._json({"ok": False, "error": f"there is no shot {n}"}, 404)
+ return
+ if not board.get("anchor_stills"):
+ board["anchor_stills"] = True
+ storyboard.save_storyboard(STATE_DIR, board)
+ form["only"] = [str(n)]
+ form["pass"] = [pass_name]
+ action = "render"
+
if action == "render":
bid = f("id", "")
board = load(bid)
@@ -25895,17 +27406,32 @@ class Handler(BaseHTTPRequestHandler):
self._json({"ok": False,
"error": "no timeline to relink"}, 404)
return
- swaps = {r["path"]: r["to"] for r in _sbe_relinks(board, edit)}
+ only = f("only", "")
+ rows = _sbe_relinks(board, edit)
+ # WITHOUT `only`, the batch rewrite is drafts → finals and
+ # nothing else: a retake is adopted one clip at a time,
+ # by id, because it replaces a take the user may prefer.
+ if only:
+ rows = [r for r in rows if str(r.get("id")) == only]
+ else:
+ rows = [r for r in rows if not r.get("retake")]
+ swaps = {}
+ for r in rows:
+ if r.get("retake"):
+ swaps[("id", str(r["id"]))] = r["to"]
+ else:
+ swaps[("path", r["path"])] = r["to"]
if not swaps:
self._json(_sbe_payload(board, edit))
return
for c in (edit.get("clips") or []):
if not isinstance(c, dict):
continue
- to = swaps.get(str(c.get("path") or ""))
+ to = (swaps.get(("id", str(c.get("id") or "")))
+ or swaps.get(("path", str(c.get("path") or ""))))
if to:
c["path"] = to
- # The proxy belonged to the DRAFT. Dropping it here
+ # The proxy belonged to the old take. Dropping it
# stops the player showing yesterday's file under
# today's path until the rebuild lands.
c["proxy"] = None
@@ -26275,10 +27801,14 @@ class Handler(BaseHTTPRequestHandler):
"error": "no edit to render — "
"GET /storyboard/edit first"}, 404)
return
- name = f("out", "") or _sb_film_name(board)
- if not re.fullmatch(r"[A-Za-z0-9._-]{1,120}\.mp4", name):
+ deliver = {"format": f("format", ""), "size": f("size", ""),
+ "finish": f("finish", "")}
+ name = f("out", "") or _sb_film_name(
+ board, deliver=_sb_deliver(deliver["format"], deliver["size"],
+ deliver["finish"]))
+ if not re.fullmatch(r"[A-Za-z0-9._-]{1,120}\.(mp4|mov)", name):
self._json({"ok": False,
- "error": "out must be a plain .mp4 "
+ "error": "out must be a plain .mp4 or .mov "
"filename"}, 400)
return
# The SAME assembler the export uses, given one plan entry
@@ -26287,7 +27817,7 @@ class Handler(BaseHTTPRequestHandler):
film = _sbe_render_edit(
board, edit, music=f("music", "") or None,
music_mode=f("music_mode", "") or None,
- out_name=name)
+ out_name=name, deliver=deliver)
self._json(film if film.get("ok") else (film | {"ok": False}),
200 if film.get("ok")
else int(film.get("status") or 500))
@@ -26408,26 +27938,67 @@ class Handler(BaseHTTPRequestHandler):
shots = [s for s in (board.get("shots") or [])
if isinstance(s, dict)]
n = max([int(s.get("n") or 0) for s in shots] or [0]) + 1
- shot = {
- "n": n,
- "title": (f("title", "") or prompt)[:60],
- "mode": "character" if cid else "text",
- "engine": (f("engine", "")
- or board.get("engine_mode") or "ltx"),
- "prompt": prompt,
- "duration_s": dur,
- "seed": seed,
- "refs": [],
- "status": "pending",
- # The hole this shot was ordered for. Carried on the
- # BOARD (it is intent) and echoed to the client on the
- # edit payload's `unplaced` list when the clip lands.
- "edit_slot": {"film_start": round(film_start, 6),
- "duration": round(dur, 6)},
- }
- if cid:
- shot["character_id"] = cid
- shot["trigger"] = f("trigger", "") or cid
+ # A RETAKE CLONES THE CLIP'S OWN SHOT — its character,
+ # its refs, its location, its engine — and changes only
+ # what the form says (the prompt, the length, the seed).
+ # A new take that silently lost its character would be a
+ # different shot wearing the old one's number.
+ retake_of = f("retake_of", "")
+ source = None
+ if retake_of:
+ try:
+ _edit = sedit.load_edit(_sbe_board_dir(bid)) or {}
+ except sedit.EditError:
+ _edit = {}
+ _clip = next((c for c in (_edit.get("clips") or [])
+ if isinstance(c, dict)
+ and str(c.get("id")) == retake_of), None)
+ if not _clip:
+ self._json({"ok": False,
+ "error": "that clip is not on this "
+ "timeline any more"}, 400)
+ return
+ _p = str(_clip.get("path") or "")
+ source = next((s for s in shots
+ if _p and _p in (str(s.get("draft_output") or ""),
+ str(s.get("final_output") or ""))),
+ None)
+ if source:
+ shot = {k: v for k, v in source.items()
+ if k not in ("n", "status", "draft_output",
+ "final_output", "stale_output",
+ "grade", "draft_job", "final_job",
+ "edit_slot")
+ and not str(k).endswith("_job")}
+ shot.update({"n": n, "prompt": prompt,
+ "duration_s": dur, "seed": seed,
+ "status": "pending",
+ "title": (f("title", "") or source.get("title")
+ or prompt)[:60]})
+ if cid:
+ shot["character_id"] = cid
+ shot["trigger"] = f("trigger", "") or cid
+ shot["mode"] = "character"
+ else:
+ shot = {
+ "n": n,
+ "title": (f("title", "") or prompt)[:60],
+ "mode": "character" if cid else "text",
+ "engine": (f("engine", "")
+ or board.get("engine_mode") or "ltx"),
+ "prompt": prompt,
+ "duration_s": dur,
+ "seed": seed,
+ "refs": [],
+ "status": "pending",
+ }
+ if cid:
+ shot["character_id"] = cid
+ shot["trigger"] = f("trigger", "") or cid
+ shot["edit_slot"] = {"film_start": round(film_start, 6),
+ "duration": round(dur, 6)}
+ if retake_of:
+ shot["edit_slot"]["retake_of"] = retake_of
board.setdefault("shots", []).append(shot)
_sb_normalize(board)
# `_sb_normalize` may renumber; find the shot again by the
@@ -27205,7 +28776,10 @@ def _resolve_cap_tier(version_id: str | None = None) -> str:
return quant
-def page() -> str:
+def page(theme: str = "") -> str:
+ """The served page. `theme` is the palette cookie the browser sent
+ ("light" / "dark" / ""); "light" is stamped on <html> so the first paint
+ is light — the module that applies Appearance runs after parse."""
cap_tier = _resolve_cap_tier()
bootstrap = json.dumps({
"presets": PRESETS, "aspects": ASPECTS,
@@ -27297,6 +28871,8 @@ def page() -> str:
else "<title>Phosphene</title>")
.replace("__BOOTSTRAP__", bootstrap)
.replace("__PROFILE_BADGE__", profile_badge)
+ .replace('<html lang="en">',
+ '<html lang="en" data-theme="light">' if theme == "light" else '<html lang="en">')
.replace("__Q8_CHARACTER_INSTALL_COPY__",
q8_character_install_copy())
.replace("__BUILD_STAMP__", html.escape(build_stamp_text()))
diff --git a/panel/routes_loras.py b/panel/routes_loras.py
index 36ab074..91c27da 100644
--- a/panel/routes_loras.py
+++ b/panel/routes_loras.py
@@ -283,6 +283,137 @@ def get_civitai_search(h, parsed) -> None:
"items": []}, 502)
+@get("/loras/updates")
+def get_loras_updates(h, parsed) -> None:
+ """Which installed CivitAI LoRAs have a newer version on CivitAI.
+
+ One request per LoRA that carries a `civitai_id` in its sidecar; the
+ newest `modelVersions[0]` is compared with the sidecar's
+ `civitai_version_id`. Each item carries what /civitai/download needs
+ (download_url + meta), so the update is the same one-click install the
+ browser tab does — the new file lands beside the old one."""
+ rows = []
+ try:
+ rows = [r for r in P.list_user_loras() if r.get("civitai_id")]
+ except Exception: # noqa: BLE001
+ rows = []
+ items, errors = [], []
+ for r in rows:
+ mid = r.get("civitai_id")
+ try:
+ m = P._civitai_request(f"/models/{mid}", timeout=12.0)
+ except Exception as exc: # noqa: BLE001
+ errors.append({"path": r.get("path"), "error": str(exc)[:160]})
+ continue
+ versions = [v for v in (m.get("modelVersions") or []) if isinstance(v, dict)]
+ if not versions:
+ continue
+ latest = versions[0]
+ have = r.get("civitai_version_id")
+ try:
+ newer = int(latest.get("id") or 0) != int(have or 0)
+ except (TypeError, ValueError):
+ newer = str(latest.get("id")) != str(have)
+ if not newer:
+ continue
+ files = latest.get("files") or []
+ primary = (next((f for f in files if f.get("primary") and
+ str(f.get("name", "")).endswith(".safetensors")), None)
+ or next((f for f in files if str(f.get("name", "")).endswith(".safetensors")), None))
+ if not primary or not primary.get("downloadUrl"):
+ continue
+ images = latest.get("images") or []
+ preview = next((i.get("url") for i in images if i.get("url")), None)
+ items.append({
+ "path": r.get("path"), "name": r.get("name"),
+ "current_version_id": have, "latest_version_id": latest.get("id"),
+ "latest_version_name": latest.get("name"),
+ "published_at": latest.get("publishedAt") or latest.get("createdAt"),
+ "base_model": latest.get("baseModel"),
+ "download_url": primary.get("downloadUrl"),
+ "meta": {
+ "id": m.get("id"), "version_id": latest.get("id"),
+ "name": m.get("name") or r.get("name"),
+ "description": P.re.sub(r"<[^>]+>", " ", str(m.get("description") or ""))[:600].strip(),
+ "preview_url": preview,
+ "filename": primary.get("name"),
+ "download_url": primary.get("downloadUrl"),
+ "trigger_words": list(latest.get("trainedWords") or []),
+ "base_model": latest.get("baseModel"),
+ "civitai_url": f"https://civitai.com/models/{m.get('id')}",
+ },
+ })
+ h._json({"ok": True, "checked": len(rows), "items": items, "errors": errors})
+
+
+@post("/loras/guide")
+def post_loras_guide(h, path, qs, ctype) -> None:
+ """Write a one-paragraph guide for an installed LoRA and keep it in the
+ sidecar under `guide`. The planner model writes it from what the sidecar
+ already knows (name, description, trigger words, base model, strength) —
+ nothing is fetched. Refused while a render runs: the planner is a 12B
+ model and the GPU is taken."""
+ _rb = h._read_form_body()
+ if _rb is None:
+ return
+ body, form = _rb
+ lp = form.get("path", [""])[0] if isinstance(form.get("path"), list) else (form.get("path") or "")
+ row = next((r for r in P.list_user_loras() if r.get("path") == lp), None)
+ if not row:
+ h._json({"ok": False, "error": "that LoRA is not in the list"}, 404)
+ return
+ if P.STATE.get("current"):
+ h._json({"ok": False, "error": "a render is running — write the guide when it finishes"}, 409)
+ return
+ trig = ", ".join(row.get("trigger_words") or []) or "none"
+ system = ("You write short, practical guides for video-model LoRA adapters. Plain English, "
+ "second person, no marketing. One paragraph of 3 to 5 sentences: what the LoRA "
+ "does to the picture, how to prompt it (name the trigger words if there are any, "
+ "and say when to leave them out), what strength to start from and what happens "
+ "above and below it, and one thing it is bad at or fights with. No headings, no lists.")
+ user = (f"LoRA name: {row.get('name')}\n"
+ f"Base model: {row.get('base_model') or 'unknown'}\n"
+ f"Trigger words: {trig}\n"
+ f"Recommended strength: {row.get('recommended_strength', 1.0)}\n"
+ f"Author's description: {(row.get('description') or '').strip()[:1200] or 'none given'}\n"
+ "Write the guide.")
+ session = None
+ try:
+ session = P.storyboard_planner.PlannerSession()
+ resp = session.generate(system, user, max_tokens=320, temperature=0.4)
+ text = str((resp or {}).get("text") or "").strip()
+ except Exception as exc: # noqa: BLE001
+ h._json({"ok": False, "error": f"the planner could not write it: {exc}"}, 502)
+ return
+ finally:
+ for m in ("release", "close", "stop", "shutdown"):
+ if session is not None and hasattr(session, m):
+ try:
+ getattr(session, m)()
+ except Exception: # noqa: BLE001
+ pass
+ break
+ text = P.re.sub(r"\s+", " ", text).strip().strip('"')
+ if len(text) < 40:
+ h._json({"ok": False, "error": "the planner returned nothing usable"}, 502)
+ return
+ sidecar = P.Path(lp).with_suffix(".json")
+ try:
+ raw = P.json.loads(sidecar.read_text()) if sidecar.is_file() else {}
+ if not isinstance(raw, dict):
+ raw = {}
+ except (OSError, ValueError):
+ raw = {}
+ raw["guide"] = text
+ raw.setdefault("name", row.get("name"))
+ try:
+ sidecar.write_text(P.json.dumps(raw, indent=2, ensure_ascii=False))
+ except OSError as exc:
+ h._json({"ok": False, "error": f"could not save the guide: {exc}"}, 500)
+ return
+ h._json({"ok": True, "guide": text})
+
+
@post("/loras/refresh")
def post_loras_refresh(h, path, qs, ctype) -> None:
# Rescan mlx_models/loras/. The result is whatever
diff --git a/panel/routes_meta.py b/panel/routes_meta.py
index 622985c..445d699 100644
--- a/panel/routes_meta.py
+++ b/panel/routes_meta.py
@@ -14,6 +14,109 @@ from panel.routes import get, get_when, post, post_when
P = None # the running mlx_ltx_panel module; assigned at wiring time
+@get("/sw.js")
+def get_service_worker(h, parsed) -> None:
+ """The push service worker, served from the ROOT so its scope covers the
+ whole panel — a worker under /webapp/ could only wake for /webapp/."""
+ p = (P.ROOT / "webapp" / "sw.js")
+ if not p.is_file():
+ h.send_error(404); return
+ body = p.read_bytes()
+ h.send_response(200)
+ h.send_header("Content-Type", "text/javascript; charset=utf-8")
+ h.send_header("Cache-Control", "no-cache")
+ h.send_header("Service-Worker-Allowed", "/")
+ h.send_header("Content-Length", str(len(body)))
+ h.end_headers()
+ h.wfile.write(body)
+
+
+@get("/push/key")
+def get_push_key(h, parsed) -> None:
+ keys = P._vapid_keys() if P.push_available() else None
+ if not keys:
+ h._json({"ok": False, "available": False,
+ "error": "push is not available on this install"}, 503)
+ return
+ h._json({"ok": True, "available": True, "public_key": keys["public"],
+ "subscriptions": len(P._push_subs())})
+
+
+@post("/push/subscribe")
+def post_push_subscribe(h, path, qs, ctype) -> None:
+ _rb = h._read_form_body()
+ if _rb is None:
+ return
+ body, form = _rb
+ raw = form.get("subscription", [""])[0] if isinstance(form.get("subscription"), list) else (form.get("subscription") or "")
+ try:
+ sub = P.json.loads(raw)
+ except (TypeError, ValueError):
+ sub = None
+ if not isinstance(sub, dict) or not sub.get("endpoint") or not isinstance(sub.get("keys"), dict):
+ h._json({"ok": False, "error": "a PushSubscription JSON is required"}, 400)
+ return
+ subs = [s for s in P._push_subs() if s.get("endpoint") != sub["endpoint"]]
+ subs.append({"endpoint": sub["endpoint"], "keys": sub["keys"],
+ "expirationTime": sub.get("expirationTime")})
+ P._push_save_subs(subs)
+ P.push(f"[push] a browser subscribed ({len(subs)} listening)")
+ h._json({"ok": True, "subscriptions": len(subs)})
+
+
+@post("/push/unsubscribe")
+def post_push_unsubscribe(h, path, qs, ctype) -> None:
+ _rb = h._read_form_body()
+ if _rb is None:
+ return
+ body, form = _rb
+ ep = form.get("endpoint", [""])[0] if isinstance(form.get("endpoint"), list) else (form.get("endpoint") or "")
+ subs = [s for s in P._push_subs() if s.get("endpoint") != ep]
+ P._push_save_subs(subs)
+ h._json({"ok": True, "subscriptions": len(subs)})
+
+
+@post("/push/test")
+def post_push_test(h, path, qs, ctype) -> None:
+ n = P.push_notify("Phosphene", "This is what a finished render will say.", tag="phos-test")
+ h._json({"ok": n > 0, "sent": n,
+ "error": None if n else "no browser is subscribed, or the push could not be delivered"})
+
+
+@get("/docs/prompting")
+def get_docs_prompting(h, parsed) -> None:
+ """docs/PROMPTING.md on a page (webapp/prompting.html) with one button:
+ copy the whole guide to paste into your own assistant. The page's markup
+ lives in the template; this only fills the seam."""
+ import html as _html
+ md = P.ROOT / "docs" / "PROMPTING.md"
+ tpl = P.ROOT / "webapp" / "prompting.html"
+ if not md.is_file() or not tpl.is_file():
+ h.send_error(404); return
+ page = tpl.read_text().replace("__GUIDE_MD__", _html.escape(md.read_text()))
+ h._ok(page.encode())
+
+
+@get("/take/estimate")
+def get_take_estimate(h, parsed) -> None:
+ """What a take of this length costs on this Mac: beats, parts, minutes.
+ `?engine=h3|ltx&quality=<engine quality key>&seconds=<TAKE_SECONDS>`."""
+ qs = parse_qs(parsed.query)
+ engine = (qs.get("engine", ["ltx"])[0] or "ltx").strip().lower()
+ quality = (qs.get("quality", [""])[0] or "").strip().lower()
+ seconds = (qs.get("seconds", ["0"])[0] or "0").strip()
+ plan = P.take_plan(seconds, engine)
+ if not plan:
+ h._json({"ok": False, "error": f"seconds must be one of {list(P.TAKE_SECONDS)}",
+ "choices": list(P.TAKE_SECONDS)}, 400)
+ return
+ minutes = P.take_estimate_minutes(engine, quality, seconds)
+ h._json({"ok": True, "seconds": plan["seconds"], "beats": plan["beats"],
+ "parts": len(plan["parts"]), "engine": plan["engine"], "frames": plan["frames"],
+ "minutes": minutes, "eta": (P._fmt_eta(minutes) if minutes else None),
+ "needs_q8": plan["engine"] == "ltx"})
+
+
@get("/panel/bug-context")
def get_panel_bug_context(h, parsed) -> None:
# Sysinfo + log tail bundle for the bug-report modal. The browser
@@ -631,4 +734,13 @@ def post_agent_gone(h, path, qs, ctype) -> None:
@get("/")
def get_root(h, parsed) -> None:
- h._ok(P.page().encode())
+ # The palette the browser chose last time rides a cookie so the first
+ # paint is already light or dark — the modules that apply it run after.
+ _theme = ""
+ try:
+ from http.cookies import SimpleCookie # noqa: PLC0415
+ _ck = SimpleCookie(h.headers.get("Cookie") or "")
+ _theme = _ck["phos_theme"].value if "phos_theme" in _ck else ""
+ except Exception: # noqa: BLE001
+ _theme = ""
+ h._ok(P.page(theme=_theme).encode())
diff --git a/scripts/post_update.sh b/scripts/post_update.sh
index 8971662..da9833e 100644
--- a/scripts/post_update.sh
+++ b/scripts/post_update.sh
@@ -182,6 +182,9 @@ require "the codec patch (without it every render encodes 4:2:0 - blocky faces)"
# ltx-trainer went in with --no-deps above, so pyyaml/pydantic/tqdm/rich were
# never resolved; the trainer subprocess dies at `import yaml` without them.
( cd "$ROOT/ltx-2-mlx" && uv pip install --python env/bin/python 'pyyaml>=6.0' 'pydantic>=2.0' 'tqdm>=4.65' 'rich>=13.0' )
+# pywebpush signs the closed-tab completion alerts (Settings → Completion
+# alerts). Optional: the panel offers the button only when it imports.
+( cd "$ROOT/ltx-2-mlx" && uv pip install --python env/bin/python 'pywebpush>=2.0' )
# ---- 6. Optional runtime packages -------------------------------------------
# mlx-vlm --no-deps on purpose (its default deps fight our mflux/transformers/
diff --git a/storyboard.py b/storyboard.py
index fdad116..4e08fae 100644
--- a/storyboard.py
+++ b/storyboard.py
@@ -586,9 +586,12 @@ def validate_storyboard_detail(
n=n_for_ui, field="prompt")
dur = s.get("duration_s")
- if not isinstance(dur, (int, float)) or not (0 < float(dur) <= 60):
+ # A take shot is as long as the take (up to 2 min); every other shot
+ # is one clip and stops at 60.
+ _dur_cap = max(TAKE_SECONDS) if s.get("take_seconds") in TAKE_SECONDS else 60
+ if not isinstance(dur, (int, float)) or not (0 < float(dur) <= _dur_cap):
add("bad_duration",
- f"{where}: duration_s must be between 0 and 60 (got {dur!r})",
+ f"{where}: duration_s must be between 0 and {_dur_cap} (got {dur!r})",
n=n_for_ui, field="duration_s", duration_s=dur)
refs = s.get("refs") or []
@@ -779,6 +782,18 @@ def shot_render_secs(shot: dict, policy_pass: dict, *, h3_cost=None) -> float:
"""
dur = float(shot.get("duration_s") or 0)
quality = policy_pass.get("quality", "balanced")
+ if shot.get("take_seconds") in TAKE_SECONDS and shot_engine(shot) == "h3":
+ # A take on H3 is parts of 15 s; price the parts, not the duration.
+ parts = -(-(int(shot["take_seconds"]) // TAKE_BEAT_SECONDS) // 3)
+ qk = h3_quality_for(quality)
+ got = None
+ if h3_cost is not None:
+ try:
+ got = h3_cost(qk, "15s")
+ except Exception:
+ got = None
+ per = float(got) if got else _H3_SECS_PER_VIDEO_SEC.get(qk, 109.0) * _H3_LENGTH_SECONDS["15s"]
+ return per * parts
if shot_engine(shot) == "h3":
lk = h3_length_for(dur)
qk = h3_quality_for(quality)
@@ -1303,11 +1318,67 @@ CHARACTER_QUALITY_FOR_PASS: dict[str, str] = {
}
+# ---- ONE TAKE on the board --------------------------------------------------
+# A film that is one shot: the planner writes one movement per five-second
+# beat (as it does for a soundtrack slot), and the board keeps ONE shot that
+# carries the beats. shot_to_job turns it into the panel's take fields, so the
+# render is the same take a person gets from the Video tab.
+TAKE_BEAT_SECONDS = 5
+TAKE_SECONDS = (30, 45, 60, 90, 120)
+
+
+def collapse_take(shots: list[dict], seconds: int) -> list[dict]:
+ """The planner's N beat-shots become ONE take shot: the first shot's
+ identity (mode, character, refs, title) with `beats` = every shot's own
+ prompt, padded to the take's beat count, `duration_s` = the take."""
+ beats_n = max(1, int(seconds) // TAKE_BEAT_SECONDS)
+ items = [s for s in (shots or []) if isinstance(s, dict)]
+ if not items:
+ return []
+ first = dict(items[0])
+ beats = [str(s.get("prompt") or "").strip() for s in items][:beats_n]
+ beats += [""] * (beats_n - len(beats))
+ first.update({
+ "n": 1,
+ "prompt": beats[0] or first.get("prompt") or "",
+ "beats": beats,
+ "take_seconds": int(seconds),
+ "duration_s": float(seconds),
+ "frames": int(seconds) * 24 + 1,
+ "title": first.get("title") or "One take",
+ })
+ for k in ("slot", "section"):
+ first.pop(k, None)
+ return [first]
+
+
+def shot_wants_still(shot: dict) -> bool:
+ """A shot an anchor still can start: text and character shots. Keyframe,
+ extend and a2v already start from media of their own."""
+ return isinstance(shot, dict) and str(shot.get("mode") or "text") in ("text", "character")
+
+
+def still_prompt(prompt: str) -> str:
+ """The shot prompt, re-aimed at ONE frame: camera moves and durations
+ describe a clip, a still needs the composition at the first instant."""
+ move = r"(push(es|ing)?( in)?|pull(s|ing)?( back| out)?|pan(s|ning)?|tilt(s|ing)?|track(s|ing)?|dolly(ing)?|orbit(s|ing)?|zoom(s|ing)?|crane(s)?|glide(s)?|drift(s)?|sweep(s)?|circle(s)?)"
+ # a clause that is about the camera moving, from its start to the next punctuation
+ p = re.sub(r"(,\s*)?(as\s+)?(the\s+|a\s+)?(camera|lens|shot|frame)\s+[^.,;]*?\b" + move + r"\b[^.,;]*", "", prompt, flags=re.I)
+ p = re.sub(r"(,\s*)?(slow(ly)?|smooth(ly)?|gentl[ey]|fast|quick(ly)?)?\s*\b" + move + r"\b\s+(in|out|up|down|left|right|across|around|forward|back)?[^.,;]*", "", p, flags=re.I)
+ p = re.sub(r"\s+([.,;])", r"\1", p)
+ p = re.sub(r"([.,;])\1+", r"\1", p)
+ p = re.sub(r",\s*\.", ".", p)
+ p = re.sub(r"\s{2,}", " ", p).strip(" ,;.")
+ return (p + ". The first frame of the shot, held still: the composition, framing and light exactly as the shot opens.").strip()
+
+
def shot_to_job(shot: dict, policy_pass: dict, *,
board_id: str = "", board_title: str = "",
h3_available: bool = True,
engine_mode: str = DEFAULT_ENGINE_MODE,
h3_chain_prompts: bool = False,
+ long_windows: bool = False,
+ style: str = "",
locations: dict[str, dict] | None = None,
wardrobe: dict[str, str] | None = None) -> dict:
"""Translate one storyboard shot into the panel's ORDINARY job form fields.
@@ -1430,6 +1501,33 @@ def shot_to_job(shot: dict, policy_pass: dict, *,
# identifies itself in the bottom pane with no bottom-pane code at all. `session_tag`
# carries the provenance the badge and the gallery group on. Both keys are already in
# make_job's allowlist — no allowlist edit, which is the point.
+ # ONE TAKE. The shot carries `take_seconds` + `beats`; the panel's make_job
+ # does the rest (LTX: the windows chain; H3: 15 s parts that continue).
+ if shot.get("take_seconds") in TAKE_SECONDS:
+ job["take_seconds"] = str(int(shot["take_seconds"]))
+ job["beats"] = json.dumps([str(b or "") for b in (shot.get("beats") or [])])
+ if engine != "h3":
+ job["frames"] = int(shot["take_seconds"]) * 24 + 1
+ # ANCHOR STILL. When the shot has a still, the video STARTS from it: the
+ # ordinary i2v path with the still as the image, anchored (the strict
+ # pin, not Inspire). LTX only — H3's i2v is a different contract.
+ if shot.get("still") and engine != "h3" and job["mode"] == "t2v":
+ job["mode"] = "i2v"
+ job["image"] = str(shot["still"])
+ job["i2v_reference_mode"] = "anchor"
+ # LONG WINDOWS. A shot longer than one LTX window (121 frames) renders as
+ # a chain of windows on the Q8 dev transformer rather than being cut to
+ # fit. One prompt per window: the shot's own prompt, with the board's
+ # style and the shot's location as the invariants every window repeats.
+ # Extend cannot re-inject an image per window, so an anchored long shot is
+ # anchored by its first window only — the still opens it, the chain
+ # carries it. See ltx_windows.py.
+ if long_windows and engine != "h3" and int(job.get("frames") or 0) > 121 \
+ and job["mode"] in ("t2v", "i2v"):
+ job["temporal_mode"] = "windows"
+ inv = [s for s in (style.strip(), str((shot.get("location") or "")).strip()) if s]
+ if inv:
+ job["window_invariants"] = "; ".join(inv)
n = shot.get("n")
if board_id and isinstance(n, int):
job["session_tag"] = f"sb:{board_id}#{n}"
diff --git a/storyboard_edit.py b/storyboard_edit.py
index 0d69de6..411d65c 100644
--- a/storyboard_edit.py
+++ b/storyboard_edit.py
@@ -91,6 +91,7 @@ import numpy as np
__all__ = [
"best_window", "beat_map", "snap", "plan_cut",
"probe_media", "format_plan", "plan_total", "audio_span_for",
+ "song_map", "director_pacing", "SECTION_LABELS",
]
@@ -912,6 +913,167 @@ def beat_map(audio_path, *, meter: int = DEFAULT_METER, sr: int = AUDIO_SR,
}
+# ---------------------------------------------------------------------------
+# THE SONG MAP — sections and energy, ON THE BAR GRID
+# ---------------------------------------------------------------------------
+# A beat grid says WHERE to cut; it says nothing about how OFTEN. A music
+# video that cuts every two bars through the intro and every two bars through
+# the chorus reads as a metronome, and the Director had no way to know which
+# was which. This is the second axis: for every bar of the fitted grid, how
+# loud and how bright the track is, and from those a list of SECTIONS with a
+# label (intro / verse / chorus / bridge / outro) and an energy in 0..1.
+#
+# ALIGNED TO DOWNBEATS, deliberately. A section boundary that lands between
+# two bars is a boundary no cut can sit on; snapping the analysis to the bar
+# grid means every section edge IS a downbeat and the planner's slots can
+# begin exactly there. Labels are a heuristic — position plus relative energy
+# and brightness — and are reported as such: `energy` is the number the
+# pacing is derived from, the label is the word the planner is told.
+SECTION_LABELS = ("intro", "verse", "chorus", "bridge", "outro")
+SECTION_MIN_BARS = 4 # shorter than a phrase is a fill, not a section
+SECTION_STEP = 0.15 # the jump in combined level that opens one
+
+
+def _bar_features(x: np.ndarray, sr: int, downbeats: list[float],
+ t0: float, duration: float) -> tuple[np.ndarray, np.ndarray]:
+ """Per-bar RMS and spectral centroid, both normalised to 0..1."""
+ edges = [max(0.0, float(b) - t0) for b in downbeats if t0 <= float(b) < t0 + duration]
+ if not edges:
+ return np.zeros(0, dtype=np.float32), np.zeros(0, dtype=np.float32)
+ edges.append(min(duration, edges[-1] + (edges[-1] - edges[-2] if len(edges) > 1 else duration)))
+ n_fft = 2048
+ freqs = np.fft.rfftfreq(n_fft, 1.0 / sr).astype(np.float32)
+ rms, cent = [], []
+ for a, b in zip(edges, edges[1:]):
+ i0, i1 = int(a * sr), max(int(a * sr) + n_fft, int(b * sr))
+ seg = x[i0:i1]
+ if seg.size < n_fft:
+ seg = np.pad(seg, (0, n_fft - seg.size))
+ rms.append(float(np.sqrt(np.mean(seg.astype(np.float32) ** 2))))
+ # A handful of windows across the bar is all a centroid needs; a full
+ # spectrogram per bar would be a megabyte to learn one number.
+ steps = max(1, min(8, seg.size // n_fft))
+ cs = []
+ for k in range(steps):
+ j = k * (seg.size - n_fft) // max(1, steps - 1) if steps > 1 else 0
+ mag = np.abs(np.fft.rfft(seg[j:j + n_fft] * np.hanning(n_fft)))
+ tot = float(mag.sum())
+ cs.append(float((mag * freqs).sum() / tot) if tot > 1e-9 else 0.0)
+ cent.append(float(np.mean(cs)))
+ rms = np.asarray(rms, dtype=np.float32)
+ cent = np.asarray(cent, dtype=np.float32)
+ rms = rms / (float(rms.max()) + 1e-8)
+ cent = cent / (float(cent.max()) + 1e-8)
+ return rms, cent
+
+
+def _label_section(energy: float, brightness: float, mean_energy: float,
+ idx: int, total: int) -> str:
+ first, last = idx == 0, idx == total - 1
+ high = energy > mean_energy * 1.2
+ low = energy < mean_energy * 0.6
+ if first and low:
+ return "intro"
+ if last and low:
+ return "outro"
+ if high and brightness > 0.5:
+ return "chorus"
+ if low:
+ return "bridge"
+ return "verse"
+
+
+def song_map(audio_path, beats: dict | None = None, *, sr: int = AUDIO_SR,
+ span: tuple[float, float] | None = None,
+ min_bars: int = SECTION_MIN_BARS, step: float = SECTION_STEP) -> dict:
+ """Sections and energy for a soundtrack, on its own bar grid.
+
+ Returns::
+
+ {"bpm", "bars": [{"n", "start", "end", "energy", "brightness"}],
+ "sections": [{"start", "end", "label", "energy", "bars": [i, j)}],
+ "mean_energy", "duration"}
+
+ `beats` is a `beat_map()` result to reuse (the Director already has one);
+ absent, it is computed here. A track with fewer than `2 * min_bars` bars
+ is ONE section labelled by its own energy, never an error — a jingle is
+ still cuttable.
+ """
+ b = beats if isinstance(beats, dict) and beats.get("downbeats") else beat_map(audio_path, sr=sr, span=span)
+ t0 = float((b.get("span") or [0.0])[0])
+ duration = float(b.get("duration") or 0.0)
+ x = _decode_pcm(audio_path, sr=sr, span=(t0, t0 + duration) if duration > 0 else span)
+ if duration <= 0:
+ duration = x.size / float(sr)
+ downs = [float(t) for t in (b.get("downbeats") or [])]
+ rms, cent = _bar_features(x, sr, downs, t0, duration)
+ n = int(rms.size)
+ bars = []
+ for i in range(n):
+ start = float(downs[i])
+ end = float(downs[i + 1]) if i + 1 < len(downs) else round(t0 + duration, 6)
+ bars.append({"n": i + 1, "start": round(start, 6), "end": round(end, 6),
+ "energy": round(float(rms[i]), 4),
+ "brightness": round(float(cent[i]), 4)})
+ out = {"bpm": b.get("bpm"), "bars": bars, "sections": [],
+ "mean_energy": round(float(rms.mean()), 4) if n else 0.0,
+ "duration": round(duration, 4)}
+ if n == 0:
+ return out
+ combined = 0.7 * rms + 0.3 * cent
+ bounds = [0]
+ if n >= 2 * min_bars:
+ # THE JUMP BETWEEN THE LAST `min_bars` AND THE NEXT `min_bars`, at
+ # every bar, and a boundary only where that jump PEAKS: a window that
+ # straddles a real edge crosses the threshold for several bars in a
+ # row, and taking the first crossing put the boundary a phrase early
+ # (and a second one a phrase late).
+ diff = np.zeros(n + 1, dtype=np.float32)
+ for i in range(min_bars, n - min_bars + 1):
+ left = float(combined[i - min_bars:i].mean())
+ right = float(combined[i:i + min_bars].mean())
+ diff[i] = abs(right - left)
+ for i in range(min_bars, n - min_bars + 1):
+ if diff[i] <= step or i - bounds[-1] < min_bars:
+ continue
+ lo, hi = max(0, i - min_bars + 1), min(n + 1, i + min_bars)
+ if diff[i] >= float(diff[lo:hi].max()) - 1e-9:
+ bounds.append(i)
+ bounds.append(n)
+ mean_e = float(rms.mean())
+ total = len(bounds) - 1
+ for k in range(total):
+ i, j = bounds[k], bounds[k + 1]
+ e = float(rms[i:j].mean())
+ br = float(cent[i:j].mean())
+ out["sections"].append({
+ "start": bars[i]["start"], "end": bars[j - 1]["end"],
+ "label": _label_section(e, br, mean_e, k, total),
+ "energy": round(e, 4), "brightness": round(br, 4),
+ "bars": [i, j],
+ })
+ return out
+
+
+# HOW OFTEN TO CUT, PER SECTION. `base` is the user's bars-per-shot; the
+# chorus cuts twice as often, the intro and the outro half as often, and a
+# bridge holds the base. The energy number breaks ties for an unlabelled
+# section: hotter than the track's mean cuts faster. Never below one bar.
+def director_pacing(label: str, energy: float, mean_energy: float,
+ base: int = 2) -> int:
+ base = max(1, int(base))
+ lab = str(label or "").lower()
+ if lab == "chorus":
+ return max(1, base // 2)
+ if lab in ("intro", "outro"):
+ return base * 2
+ if lab == "bridge":
+ return base
+ if mean_energy > 0 and energy > mean_energy * 1.2:
+ return max(1, base // 2)
+ return base
+
+
def audio_span_for(target_seconds: float | None) -> tuple[float, float] | None:
"""The stretch of music a film of `target_seconds` should be fitted to.
diff --git a/storyboard_editor.py b/storyboard_editor.py
index 4fde666..2c515c7 100644
--- a/storyboard_editor.py
+++ b/storyboard_editor.py
@@ -245,6 +245,36 @@ def clip_carries_media(clip) -> bool:
return clip_kind(clip) in ("video", "still")
+# FRAMING — a zoom and a reframe, per clip. `frame: {zoom, x, y}`: the
+# picture is magnified `zoom` times (1 is the whole frame, 3 is a third of
+# it) and the window is centred at the fraction (`x`, `y`) of the source.
+# A push-in on a face, a wider frame's crop to a tighter one, a still that
+# needs to lose its margins — the reframe every NLE has and the render did
+# not. Not an "effect" (`fx` is fades): it is a transform, and it keeps its
+# own home the way brightness kept `adjust`. Neutral is absent.
+FRAME_ZOOM_MIN = 1.0
+FRAME_ZOOM_MAX = 3.0
+
+
+def clip_frame(clip) -> dict:
+ """`{zoom, x, y}`, clamped; `{1.0, 0.5, 0.5}` for a clip that has none."""
+ c = clip if isinstance(clip, dict) else {}
+ f = c.get("frame")
+ f = f if isinstance(f, dict) else {}
+ z = _f(f.get("zoom"), 1.0)
+ if z != z or z <= 0:
+ z = 1.0
+ z = max(FRAME_ZOOM_MIN, min(FRAME_ZOOM_MAX, z))
+ return {"zoom": round(z, 6),
+ "x": round(max(0.0, min(1.0, _f(f.get("x"), 0.5))), 6),
+ "y": round(max(0.0, min(1.0, _f(f.get("y"), 0.5))), 6)}
+
+
+def clip_frame_is_neutral(clip) -> bool:
+ f = clip_frame(clip)
+ return abs(f["zoom"] - 1.0) < 1e-9
+
+
def clip_brightness(clip) -> float:
"""`adjust.brightness`, clamped, or 0.0 — the neutral that renders nothing.
@@ -284,14 +314,22 @@ def clip_audio(clip) -> dict:
"""
if not isinstance(clip, dict):
return {"start": 0.0, "end": 0.0, "film_start": 0.0,
- "linked": True, "coupled": False, "split": False}
+ "linked": True, "coupled": False, "split": False,
+ "speed": 1.0, "len": 0.0}
vs, ve = _f(clip.get("start")), _f(clip.get("end"))
fs = _f(clip.get("film_start"))
+ # THE SOUND RUNS AT THE CLIP'S SPEED, linked or not: it came off the same
+ # take, and retiming the take retimes both halves. `len` is the strip's
+ # length ON THE FILM — the only clock the lane, the plan and the envelope
+ # use — so no caller has to remember to divide.
+ speed = clip_speed(clip)
a = clip.get("audio")
if not isinstance(a, dict) or clip_kind(clip) != "video":
return {"start": round(vs, 6), "end": round(ve, 6),
"film_start": round(fs, 6),
- "linked": True, "coupled": False, "split": False}
+ "linked": True, "coupled": False, "split": False,
+ "speed": speed,
+ "len": round(max(0.0, ve - vs) / speed, 6)}
# THE PRESENCE OF THE FIELD IS THE SWITCH, not the values in it. Deriving
# "linked" from equality looked tidier and was wrong in the one case that
# matters: unlinking writes the window the clip already has, so a clip the
@@ -315,7 +353,8 @@ def clip_audio(clip) -> dict:
"film_start": round(f, 6),
# `linked` has always meant "this strip cannot be dragged on its
# own", and that is true of a coupled pair too.
- "linked": coupled, "coupled": coupled, "split": True}
+ "linked": coupled, "coupled": coupled, "split": True,
+ "speed": speed, "len": round(max(0.0, e - s) / speed, 6)}
def clip_muted(clip) -> bool:
@@ -344,13 +383,38 @@ def clip_muted(clip) -> bool:
return clip.get("mute") is True and clip_kind(clip) == "video"
+# SPEED, ON THE CLIP. `speed: 2.0` plays the source window twice as fast, so
+# the slot on the film is `(end - start) / speed`. The bounds are ffmpeg's own
+# honest range for `atempo` chained twice each way; below 0.25x a clip is a
+# still with ambitions and above 4x it is a strobe. An ABSENT speed is 1.0,
+# which is every clip ever written, so EDIT_VERSION does not move.
+#
+# NEVER AUTOMATIC. The owner's verdict on a slowed shot that read as an
+# accident was "too slow-mo"; this is a control a person sets on a clip, not a
+# thing the editor decides.
+SPEED_MIN = 0.25
+SPEED_MAX = 4.0
+
+
+def clip_speed(clip) -> float:
+ """The clip's play rate, clamped. 1.0 when absent, and always 1.0 for a
+ still or a slug — they have no source clock to run fast or slow."""
+ if not isinstance(clip, dict) or clip_kind(clip) != "video":
+ return 1.0
+ s = _f(clip.get("speed"), 1.0)
+ if s <= 0:
+ return 1.0
+ return round(max(SPEED_MIN, min(SPEED_MAX, s)), 6)
+
+
def clip_length(clip) -> float:
- """How long this clip plays. The film slot and the source window agree."""
+ """How long this clip plays. The film slot and the source window agree —
+ at the clip's speed."""
if not isinstance(clip, dict):
return 0.0
n = _f(clip.get("film_end")) - _f(clip.get("film_start"))
if n <= 0:
- n = _f(clip.get("end")) - _f(clip.get("start"))
+ n = (_f(clip.get("end")) - _f(clip.get("start"))) / clip_speed(clip)
return max(0.0, round(n, 6))
@@ -409,17 +473,216 @@ def clip_effects(clip) -> dict:
OVERLAY_SUFFIXES = (".png", ".webp", ".tif", ".tiff")
+# WHAT AN OVERLAY CAN BE. A card is a still; a matte or a loop is a video; a
+# TITLE is `text` — pixels the render DRAWS rather than a file somebody
+# uploaded. It is a citizen of this lane and not a system of its own because
+# everything a title needs already exists here: alpha, fades, a slot on the
+# film, z-order over the picture, and the one-lane rule. What a title adds is
+# the string and how to set it.
+OVERLAY_KINDS = ("still", "video", "text")
+
+
def overlay_kind(item) -> str:
- """`still` or `video`. A card is a still; a matte or a loop is a video."""
+ """`still`, `video` or `text`. An EXPLICIT kind wins; the suffix decides the rest.
+
+ The explicit field has to win because a title has no path to probe, and
+ the suffix fallback has to stay because every overlay written before titles
+ existed carries only a path — so every existing document reads exactly as
+ it did.
+ """
if not isinstance(item, dict):
return "still"
k = str(item.get("kind") or "").strip().lower()
- if k in ("still", "video"):
+ if k in OVERLAY_KINDS:
return k
return "still" if str(item.get("path") or "").lower().endswith(
OVERLAY_SUFFIXES) else "video"
+# ---------------------------------------------------------------------------
+# TITLES — text on the overlay lane
+# ---------------------------------------------------------------------------
+# THE STYLE IS A SMALL, CLOSED SET, and every value is clamped by the one
+# accessor so the preview, the render and any export are handed numbers that
+# are already legal. `font_size` is in pixels AT A 1080-HIGH FRAME and scales
+# with the frame the film is actually rendered at, so a title designed on the
+# stage looks the same on a 576p draft and a 720p delivery. `x`/`y` are the
+# anchor as a FRACTION of the frame — the same reason — and `align` says which
+# edge of the text sits on `x`.
+TEXT_STYLE_DEFAULTS = {
+ "font_size": 64,
+ "color": "#ffffff",
+ "align": "center",
+ "x": 0.5,
+ "y": 0.5,
+ "box": False,
+ "box_color": "#000000",
+ "box_opacity": 0.5,
+}
+TEXT_REFERENCE_HEIGHT = 1080
+TEXT_FONT_SIZE_MIN = 8
+TEXT_FONT_SIZE_MAX = 400
+TEXT_MAX_CHARS = 400
+TEXT_ALIGNS = ("left", "center", "right")
+_HEX_RE = re.compile(r"^#[0-9a-f]{6}$")
+
+# THE FONT IS RESOLVED EXPLICITLY, to a FILE, and verified before anything is
+# drawn. Letting a text renderer "discover" a font goes wrong quietly on a
+# machine with no fontconfig — the failure other editors have documented — so
+# the panel names the file it will use, in this order, and refuses with a
+# sentence when none of them exists. `LTX_TITLE_FONT` overrides the list.
+# The stylesheet's stack for the on-stage preview is the same family order.
+TITLE_FONT_CANDIDATES = (
+ "/System/Library/Fonts/Supplemental/Arial Bold.ttf",
+ "/System/Library/Fonts/Supplemental/Arial.ttf",
+ "/System/Library/Fonts/HelveticaNeue.ttc",
+ "/System/Library/Fonts/Helvetica.ttc",
+ "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
+ "/usr/share/fonts/dejavu/DejaVuSans-Bold.ttf",
+ "/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf",
+ "C:/Windows/Fonts/arialbd.ttf",
+ "C:/Windows/Fonts/arial.ttf",
+)
+
+
+def _hex_colour(v, default: str) -> str:
+ s = str(v or "").strip().lower()
+ if re.fullmatch(r"#[0-9a-f]{3}", s):
+ s = "#" + "".join(ch * 2 for ch in s[1:])
+ return s if _HEX_RE.match(s) else default
+
+
+def overlay_text(item) -> dict:
+ """`{text, style}` for a title, clamped. THE ONE ACCESSOR.
+
+ Absent style keys read the defaults, so a title written as `{"kind":
+ "text", "text": "FIN"}` is complete. Every consumer reads this and nothing
+ else, which is what keeps the stage and the render drawing the same card.
+ """
+ it = item if isinstance(item, dict) else {}
+ text = str(it.get("text") or "")
+ text = text.replace("\r\n", "\n").replace("\r", "\n")[:TEXT_MAX_CHARS]
+ raw = it.get("style")
+ raw = raw if isinstance(raw, dict) else {}
+ d = TEXT_STYLE_DEFAULTS
+ size = _f(raw.get("font_size"), d["font_size"])
+ size = max(TEXT_FONT_SIZE_MIN, min(TEXT_FONT_SIZE_MAX, size))
+ align = str(raw.get("align") or d["align"]).strip().lower()
+ if align not in TEXT_ALIGNS:
+ align = d["align"]
+ style = {
+ "font_size": round(size, 3),
+ "color": _hex_colour(raw.get("color"), d["color"]),
+ "align": align,
+ "x": round(max(0.0, min(1.0, _f(raw.get("x"), d["x"]))), 6),
+ "y": round(max(0.0, min(1.0, _f(raw.get("y"), d["y"]))), 6),
+ "box": raw.get("box") is True,
+ "box_color": _hex_colour(raw.get("box_color"), d["box_color"]),
+ "box_opacity": round(max(0.0, min(1.0, _f(raw.get("box_opacity"),
+ d["box_opacity"]))), 6),
+ }
+ return {"text": text, "style": style}
+
+
+def title_font_path() -> Path | None:
+ """The font FILE a title is drawn with, or None when there is none."""
+ env = os.environ.get("LTX_TITLE_FONT")
+ if env:
+ p = Path(env)
+ return p if p.is_file() else None
+ for c in TITLE_FONT_CANDIDATES:
+ p = Path(c)
+ if p.is_file():
+ return p
+ return None
+
+
+def title_font_problem() -> str | None:
+ """A sentence when no title can be drawn on this machine, else None.
+
+ Asked at COMPILE time — before the ffmpeg command is built — so a missing
+ font is a refusal with a reason, never a film with a hole where the title
+ was.
+ """
+ env = os.environ.get("LTX_TITLE_FONT")
+ if env and not Path(env).is_file():
+ return (f"LTX_TITLE_FONT points at {env}, and there is no font file "
+ f"there — fix the path or unset it to use the system font")
+ if title_font_path() is None:
+ return ("no font for titles: none of the system fonts the panel knows "
+ "is installed — set LTX_TITLE_FONT to a .ttf file")
+ return None
+
+
+def _rgba(hex_colour: str, alpha: float) -> tuple:
+ h = hex_colour.lstrip("#")
+ return (int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16),
+ int(round(255 * max(0.0, min(1.0, alpha)))))
+
+
+def title_fingerprint(item, width: int, height: int) -> str:
+ """What a title's pixels depend on, hashed — the raster's cache key."""
+ t = overlay_text(item)
+ font = title_font_path()
+ raw = json.dumps([t, int(width), int(height), str(font) if font else "",
+ int(font.stat().st_mtime_ns) if font else 0],
+ sort_keys=True, separators=(",", ":"))
+ return hashlib.sha1(raw.encode("utf-8", "replace")).hexdigest()[:16]
+
+
+def render_title(item, width: int, height: int, dest) -> Path:
+ """Draw a title as an RGBA PNG the size of the frame. Returns the path.
+
+ WHY A PICTURE AND NOT A FILTER. The render composites the overlay lane
+ with one chain — `format=rgba`, scale, alpha fade, `overlay=` under an
+ `enable=` window — and a title that arrives as a frame-sized RGBA image
+ inherits every part of it: the fades, the z-order, the one-lane rule, the
+ tpad past the last shot. A separate text filter would be a second path
+ through that chain, and it would also depend on the ffmpeg BUILD: the
+ text filter is optional at compile time and the Homebrew ffmpeg this very
+ panel resolves on its author's machine does not carry it. A PNG needs
+ nothing of ffmpeg but what every other card already needs.
+
+ The font is `title_font_path()`, verified by `title_font_problem()` before
+ this is ever called; a caller that skips the check gets an EditError here.
+ """
+ from PIL import Image, ImageDraw, ImageFont # noqa: PLC0415
+ problem = title_font_problem()
+ if problem:
+ raise EditError(problem)
+ W, H = max(2, int(width)), max(2, int(height))
+ t = overlay_text(item)
+ st = t["style"]
+ text = t["text"] or " "
+ px = max(1, int(round(st["font_size"] * H / float(TEXT_REFERENCE_HEIGHT))))
+ font = ImageFont.truetype(str(title_font_path()), px)
+ img = Image.new("RGBA", (W, H), (0, 0, 0, 0))
+ draw = ImageDraw.Draw(img)
+ spacing = max(0, int(round(px * 0.25)))
+ bbox = draw.multiline_textbbox((0, 0), text, font=font, spacing=spacing,
+ align=st["align"])
+ tw, th = bbox[2] - bbox[0], bbox[3] - bbox[1]
+ ax, ay = st["x"] * W, st["y"] * H
+ left = ax - tw * {"left": 0.0, "center": 0.5, "right": 1.0}[st["align"]]
+ # KEPT INSIDE THE FRAME, the same clamp the stage applies: a wide title
+ # anchored near an edge is pushed back in rather than cut off.
+ left = max(0.0, min(float(W - tw), left))
+ top = ay - th / 2.0
+ if st["box"]:
+ pad = px * 0.4
+ draw.rectangle([left - pad, top - pad, left + tw + pad, top + th + pad],
+ fill=_rgba(st["box_color"], st["box_opacity"]))
+ draw.multiline_text((left - bbox[0], top - bbox[1]), text, font=font,
+ fill=_rgba(st["color"], 1.0), spacing=spacing,
+ align=st["align"])
+ dest = Path(str(dest))
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ tmp = dest.with_name(dest.name + ".tmp")
+ img.save(tmp, "PNG")
+ os.replace(tmp, dest)
+ return dest
+
+
def overlay_items(edit) -> list[dict]:
"""The overlay lane, in film order. Absent is an empty lane."""
rows = (edit or {}).get("overlays")
@@ -500,6 +763,17 @@ def audio_gain_points(item, length: float) -> list[list[float]]:
envelope's own points and the fade corners, each multiplied by the fade
factor there — which is what makes a fade and a keyframed dip compose
instead of one overriding the other.
+
+ THE CLOCK IS THE STRIP AS IT PLAYS ON THE FILM, and speed does not move
+ it. `length` is `clip_audio(c)["len"]` — the played length, already
+ divided by the clip's speed — and `t` in every point and every fade is a
+ second of THAT strip. Decided here, once, because the alternative (points
+ on the source clock, scaled at read time) would put a fade of "1 s" in
+ source seconds while the person typed it in film seconds, and the ffmpeg
+ `volume` term runs AFTER `atempo`, on the played clock, so this is the only
+ unit the render could apply without a conversion nothing else performs.
+ A keyframe at 2 s stays at 2 s of the strip when the clip is retimed; the
+ strip is what gets shorter or longer.
"""
n = max(0.0, _f(length))
if n <= 0:
@@ -689,7 +963,7 @@ def audible_strips(edit) -> list[list[float]]:
continue
w = clip_audio(c)
s = _f(w["film_start"])
- e = s + max(0.0, _f(w["end"]) - _f(w["start"]))
+ e = s + w["len"]
if e - s > 1e-9:
wins.append([round(s, 6), round(e, 6)])
wins.sort()
@@ -848,8 +1122,11 @@ def clip_audio_drift(clip) -> float:
if not w["split"]:
return 0.0
c = clip if isinstance(clip, dict) else {}
- return round((w["film_start"] - w["start"])
- - (_f(c.get("film_start")) - _f(c.get("start"))), 6)
+ # AT THE CLIP'S SPEED: a source second is `1/speed` film seconds on both
+ # halves, so the two constants are compared on the film's clock.
+ sp = w["speed"]
+ return round((w["film_start"] - w["start"] / sp)
+ - (_f(c.get("film_start")) - _f(c.get("start")) / sp), 6)
def clip_audio_resync(clip) -> float:
@@ -861,7 +1138,8 @@ def clip_audio_resync(clip) -> float:
"""
w = clip_audio(clip)
c = clip if isinstance(clip, dict) else {}
- return round(_f(c.get("film_start")) + (w["start"] - _f(c.get("start"))), 6)
+ return round(_f(c.get("film_start"))
+ + (w["start"] - _f(c.get("start"))) / w["speed"], 6)
# ===========================================================================
@@ -1332,6 +1610,187 @@ def _slim_beats(beats: dict | None) -> dict | None:
}
+# ---------------------------------------------------------------------------
+# TRANSITIONS — a typed object that OWNS A BOUNDARY, never an overlap
+# ---------------------------------------------------------------------------
+# WHY THIS IS NOT "LET THE PICTURES OVERLAP". A cross-dissolve IS two clips in
+# the same second, and the validator's one-picture-at-a-time rule
+# (`clips_overlap`) is load-bearing: the autosave, the crash backup, the
+# assembler and every gap/overlap check downstream rest on it, and
+# `WARNING_CODES` deliberately holds ONLY `clips_audio_overlap` because the
+# last time an ordinary edit was made unsaveable it cost an afternoon. So the
+# picture lane stays single-track and a transition is a SEPARATE list, the
+# same shape discipline as `overlays`:
+#
+# "transitions": [{"id": "t1", "after_clip": "<clip id>",
+# "kind": "dissolve" | "fade_black", "duration": 0.5}]
+#
+# `after_clip` names the OUTGOING clip; the transition sits on the boundary
+# between it and its successor in film order. One per boundary. The clips'
+# own film_start/film_end DO NOT MOVE — the render gets its overlap from
+# SOURCE HANDLES: half the duration of extra tail from beyond the outgoing
+# clip's out-point and half of extra head from before the incoming clip's
+# in-point, material that already exists past the trims. That is how every
+# NLE builds a centred dissolve, it keeps the film exactly as long as the
+# timeline says, and it means the sound needs nothing new at all — the audio
+# plan never sees the extension.
+#
+# A side with no spare material is REFUSED with a sentence naming the side and
+# how much it is short. A still and a slug have no source clock, so they have
+# all the handles anybody could ask for.
+TRANSITION_KINDS = ("dissolve", "fade_black")
+TRANSITION_MIN = 1.0 / 24.0 # under one frame there is nothing to draw
+TRANSITION_MAX = 2.0 # longer than this eats the shot
+
+
+def transition_items(edit) -> list[dict]:
+ """The raw rows, dicts only, in document order. Absent is an empty list."""
+ rows = (edit or {}).get("transitions") if isinstance(edit, dict) else None
+ if not isinstance(rows, list):
+ return []
+ return [t for t in rows if isinstance(t, dict)]
+
+
+def transition_duration(row, out_len: float, in_len: float,
+ fps: float = 24.0) -> float:
+ """The duration a boundary can actually carry: min(asked, half the
+ shorter neighbour, TRANSITION_MAX), on an EVEN number of frames. The
+ document keeps the number the user typed; every reader clamps through
+ here.
+
+ EVEN FRAMES, because the transition is split in half across the cut and
+ each half is extra picture on one side: 0.8 s at 24 fps is 19.2 frames,
+ which `xfade` rounds up on both runs and the film comes out one frame
+ longer than its sound. 20 frames — ten a side — is exact.
+ """
+ d = _f((row or {}).get("duration"))
+ if d <= 0:
+ return 0.0
+ d = max(0.0, min(d, TRANSITION_MAX, 0.5 * max(0.0, min(out_len, in_len))))
+ f = max(1.0, _f(fps, 24.0))
+ frames = 2 * int(round(d * f / 2.0))
+ return round(frames / f, 6)
+
+
+def _spare_source(clip, side: str) -> float | None:
+ """Seconds of untrimmed source beyond the out-point (`tail`) or before
+ the in-point (`head`). None when the source length is not known."""
+ if clip_kind(clip) != "video":
+ return float("inf")
+ if side == "head":
+ return max(0.0, _f(clip.get("start")))
+ dur = clip.get("duration")
+ if not isinstance(dur, (int, float)) or isinstance(dur, bool) or dur <= 0:
+ return None
+ return max(0.0, float(dur) - _f(clip.get("end")))
+
+
+def resolve_transitions(edit) -> list[dict]:
+ """Every transition row, resolved against the timeline it sits on.
+
+ Each entry: `{id, after_clip, before_clip, kind, duration, half,
+ out_index, in_index, at, problem}` where `problem` is None or a
+ `{code, message}` a validator can report verbatim. `duration` is the
+ CLAMPED one — the number the render will use — and `at` is the film
+ second of the boundary. Indices are into the document's `clips` list.
+ """
+ clips = [c for c in ((edit or {}).get("clips") or []) if isinstance(c, dict)]
+ order = sorted(range(len(clips)),
+ key=lambda i: (_f(clips[i].get("film_start")),
+ str(clips[i].get("path"))))
+ pos = {i: k for k, i in enumerate(order)}
+ by_id = {}
+ for i, c in enumerate(clips):
+ cid = str(c.get("id") or "")
+ if cid and cid not in by_id:
+ by_id[cid] = i
+ seen: set = set()
+ out: list[dict] = []
+ for n, row in enumerate(transition_items(edit)):
+ label = f"transition {n + 1}"
+ res = {"id": str(row.get("id") or ""), "after_clip": str(row.get("after_clip") or ""),
+ "before_clip": "", "kind": str(row.get("kind") or "").strip().lower(),
+ "duration": 0.0, "half": 0.0, "out_index": None, "in_index": None,
+ "at": 0.0, "problem": None}
+
+ def fail(code, message):
+ res["problem"] = {"code": code, "message": message}
+ out.append(res)
+
+ aid = res["after_clip"]
+ if not aid or aid not in by_id:
+ fail("transition_unknown_clip",
+ f"{label}: after_clip {aid!r} names no clip on this timeline")
+ continue
+ oi = by_id[aid]
+ res["out_index"] = oi
+ k = pos[oi]
+ if k + 1 >= len(order):
+ fail("transition_last_clip",
+ f"{label}: clip {oi + 1} is the last clip — there is nothing "
+ f"after it to dissolve into")
+ continue
+ ii = order[k + 1]
+ res["in_index"] = ii
+ res["before_clip"] = str(clips[ii].get("id") or "")
+ res["at"] = round(_f(clips[oi].get("film_end")), 6)
+ if aid in seen:
+ fail("transition_duplicate_boundary",
+ f"{label}: the cut after clip {oi + 1} already has a "
+ f"transition — one per boundary")
+ continue
+ seen.add(aid)
+ if res["kind"] not in TRANSITION_KINDS:
+ fail("transition_kind",
+ f"{label}: kind must be one of {', '.join(TRANSITION_KINDS)} "
+ f"(got {row.get('kind')!r})")
+ continue
+ raw_d = row.get("duration")
+ if not isinstance(raw_d, (int, float)) or isinstance(raw_d, bool) \
+ or raw_d != raw_d or raw_d <= 0:
+ fail("transition_duration",
+ f"{label}: duration must be a number of seconds above 0")
+ continue
+ d = transition_duration(row, clip_length(clips[oi]), clip_length(clips[ii]),
+ fps=film_fps(edit))
+ if d < TRANSITION_MIN - 1e-9:
+ fail("transition_duration",
+ f"{label}: clips {oi + 1} and {ii + 1} are too short to "
+ f"carry a transition between them")
+ continue
+ half = round(d / 2.0, 6)
+ res["duration"], res["half"] = d, half
+ short = []
+ # THE HANDLES ARE SOURCE SECONDS and the transition is film seconds:
+ # a retimed clip needs `speed` times as much take for the same half.
+ need_out = half * clip_speed(clips[oi])
+ need_in = half * clip_speed(clips[ii])
+ word = res["kind"].replace("_", " ")
+ tail = _spare_source(clips[oi], "tail")
+ if tail is None:
+ short.append(f"the source length of clip {oi + 1} is not known — "
+ f"run Prepare so the panel can measure it")
+ elif tail + 1e-6 < need_out:
+ short.append(f"clip {oi + 1} has only {tail:.2f}s beyond its "
+ f"out-point and the {word} needs {need_out:.2f}s "
+ f"there — trim its tail in or shorten the transition")
+ head = _spare_source(clips[ii], "head")
+ if head is not None and head + 1e-6 < need_in:
+ short.append(f"clip {ii + 1} has only {head:.2f}s before its "
+ f"in-point and the {word} needs {need_in:.2f}s "
+ f"there — trim its head in or shorten the transition")
+ if short:
+ fail("transition_no_handles", f"{label}: " + "; ".join(short))
+ continue
+ out.append(res)
+ return out
+
+
+def transition_problems(edit) -> list[dict]:
+ """Only the transitions that cannot be rendered, with their sentences."""
+ return [t["problem"] for t in resolve_transitions(edit) if t.get("problem")]
+
+
def validate_edit(edit) -> list[dict]:
"""Every reason this edit must not be written. Empty list == good.
@@ -1523,12 +1982,22 @@ def validate_edit(edit) -> list[dict]:
if end <= start:
bad("clip_window", f"clip {i + 1}: end ({end}) must be after "
f"start ({start})", i)
+ sp_raw = c.get("speed")
+ if sp_raw is not None:
+ if not isinstance(sp_raw, (int, float)) or isinstance(sp_raw, bool) \
+ or sp_raw != sp_raw or sp_raw in (float("inf"), float("-inf")):
+ bad("clip_speed", f"clip {i + 1}: speed must be a number", i)
+ elif not SPEED_MIN - 1e-9 <= float(sp_raw) <= SPEED_MAX + 1e-9:
+ bad("clip_speed_range",
+ f"clip {i + 1}: speed is {float(sp_raw):g}x — it must be "
+ f"between {SPEED_MIN:g}x and {SPEED_MAX:g}x", i)
+ sp = clip_speed(c)
if end > start and fe > fs \
- and abs((end - start) - (fe - fs)) > LENGTH_TOLERANCE:
+ and abs((end - start) / sp - (fe - fs)) > LENGTH_TOLERANCE:
bad("clip_length_mismatch",
f"clip {i + 1}: the source window is {end - start:.3f}s "
- f"but its slot on the film is {fe - fs:.3f}s — nothing "
- f"plays at anything but 1x", i)
+ f"at {sp:g}x but its slot on the film is {fe - fs:.3f}s — "
+ f"a clip plays its window at its speed and nothing else", i)
dur = c.get("duration")
if isinstance(dur, (int, float)) and dur > 0 \
and end > float(dur) + 1e-3:
@@ -1551,6 +2020,25 @@ def validate_edit(edit) -> list[dict]:
f"clip {i + 1}: adjust.brightness is {float(b):+.3f} — "
f"it must be between {-BRIGHTNESS_LIMIT:+.1f} and "
f"{BRIGHTNESS_LIMIT:+.1f}", i)
+ fr = c.get("frame")
+ if fr is not None:
+ if not isinstance(fr, dict):
+ bad("clip_frame", f"clip {i + 1}: frame must be an object or absent", i)
+ elif kind == "slug" and any(fr.get(k) is not None for k in ("zoom", "x", "y")):
+ bad("clip_frame_kind", f"clip {i + 1}: black has nothing to reframe", i)
+ else:
+ for key, lo, hi in (("zoom", FRAME_ZOOM_MIN, FRAME_ZOOM_MAX),
+ ("x", 0.0, 1.0), ("y", 0.0, 1.0)):
+ v = fr.get(key)
+ if v is None:
+ continue
+ if not isinstance(v, (int, float)) or isinstance(v, bool) \
+ or v != v or v in (float("inf"), float("-inf")):
+ bad("clip_frame", f"clip {i + 1}: frame.{key} must be a number", i)
+ elif not lo - 1e-9 <= float(v) <= hi + 1e-9:
+ bad("clip_frame_range",
+ f"clip {i + 1}: frame.{key} is {float(v):g} — it must be "
+ f"between {lo:g} and {hi:g}", i)
aud = c.get("audio")
if aud is not None:
# A STILL AND A SLUG HAVE NO SOUND TO SPLIT. Letting them carry the
@@ -1636,6 +2124,11 @@ def validate_edit(edit) -> list[dict]:
elif c.get("mute") and kind != "video":
bad("clip_mute_kind",
f"clip {i + 1}: only a video clip has sound to mute", i)
+ if kind != "video" and c.get("speed") is not None \
+ and abs(_f(c.get("speed"), 1.0) - 1.0) > 1e-9:
+ bad("clip_speed_kind",
+ f"clip {i + 1}: only a video clip has a clock to run fast or "
+ f"slow", i)
if c.get("source") not in ("auto", "human"):
bad("clip_source", f"clip {i + 1}: source must be 'auto' or "
f"'human' (got {c.get('source')!r})", i)
@@ -1676,8 +2169,60 @@ def validate_edit(edit) -> list[dict]:
bad("overlay_window",
f"overlay {j + 1}: film_end ({ofe}) must be after "
f"film_start ({ofs})")
- if overlay_kind(o) == "video" and not str(o.get("path") or ""):
+ okind = overlay_kind(o)
+ if okind == "video" and not str(o.get("path") or ""):
bad("overlay_path", f"overlay {j + 1}: needs a file")
+ if okind == "text":
+ # A TITLE IS ITS STRING. An empty one would render nothing
+ # and say nothing about why.
+ txt = o.get("text")
+ if not isinstance(txt, str) or not txt.strip():
+ bad("overlay_text_empty",
+ f"overlay {j + 1}: a title needs some text")
+ elif len(txt) > TEXT_MAX_CHARS:
+ bad("overlay_text_long",
+ f"overlay {j + 1}: a title is at most "
+ f"{TEXT_MAX_CHARS} characters")
+ st = o.get("style")
+ if st is not None and not isinstance(st, dict):
+ bad("overlay_text_style",
+ f"overlay {j + 1}: style must be an object or absent")
+ elif isinstance(st, dict):
+ for key in ("font_size", "x", "y", "box_opacity"):
+ v = st.get(key)
+ if v is None:
+ continue
+ if not isinstance(v, (int, float)) or isinstance(v, bool) \
+ or v != v or v in (float("inf"), float("-inf")):
+ bad("overlay_text_style",
+ f"overlay {j + 1}: style.{key} must be a number")
+ fs_v = st.get("font_size")
+ if isinstance(fs_v, (int, float)) and not isinstance(fs_v, bool) \
+ and not TEXT_FONT_SIZE_MIN <= fs_v <= TEXT_FONT_SIZE_MAX:
+ bad("overlay_text_style_range",
+ f"overlay {j + 1}: font_size is {fs_v:g} — it must be "
+ f"between {TEXT_FONT_SIZE_MIN} and {TEXT_FONT_SIZE_MAX}")
+ for key in ("x", "y", "box_opacity"):
+ v = st.get(key)
+ if isinstance(v, (int, float)) and not isinstance(v, bool) \
+ and not 0.0 <= v <= 1.0:
+ bad("overlay_text_style_range",
+ f"overlay {j + 1}: style.{key} must be between "
+ f"0 and 1")
+ if st.get("align") is not None \
+ and str(st.get("align")).lower() not in TEXT_ALIGNS:
+ bad("overlay_text_style",
+ f"overlay {j + 1}: style.align must be one of "
+ f"{', '.join(TEXT_ALIGNS)}")
+ for key in ("color", "box_color"):
+ v = st.get(key)
+ if v is not None and _hex_colour(v, "") == "":
+ bad("overlay_text_style",
+ f"overlay {j + 1}: style.{key} must be a hex "
+ f"colour like #ffcc00")
+ if st.get("box") is not None and not isinstance(st.get("box"), bool):
+ bad("overlay_text_style",
+ f"overlay {j + 1}: style.box must be true or false")
ofx = o.get("fx")
if ofx is not None and not isinstance(ofx, dict):
bad("overlay_fx",
@@ -1703,6 +2248,22 @@ def validate_edit(edit) -> list[dict]:
f"overlays {a_i + 1} and {b_i + 1} overlap "
f"({a_s:.3f}-{a_e:.3f}s and {b_s:.3f}-{b_e:.3f}s) — one "
f"overlay lane can only show one of them")
+ # THE TRANSITIONS, each of which must own a real boundary and have the
+ # source handles to build it from. Every code here is an ERROR and none is
+ # in WARNING_CODES: a transition the render cannot honour is not a note,
+ # it is a film that would come out with a hard cut where a dissolve was
+ # promised — and the sentence says which side is short and by how much.
+ txr = edit.get("transitions") if isinstance(edit, dict) else None
+ if txr is not None and not isinstance(txr, list):
+ bad("transitions_shape", "transitions must be a list or absent")
+ elif isinstance(txr, list):
+ for n, t in enumerate(txr):
+ if not isinstance(t, dict):
+ bad("transition_shape", f"transition {n + 1}: must be an object")
+ for t in resolve_transitions(edit):
+ if t.get("problem"):
+ bad(t["problem"]["code"], t["problem"]["message"],
+ t.get("out_index"))
spans.sort()
for (a_s, a_e, a_i), (b_s, b_e, b_i) in zip(spans, spans[1:]):
if b_s < a_e - TOUCH_TOLERANCE:
@@ -1720,8 +2281,7 @@ def validate_edit(edit) -> list[dict]:
continue
w = clip_audio(c)
if w["end"] > w["start"]:
- asp.append((w["film_start"],
- w["film_start"] + (w["end"] - w["start"]), i))
+ asp.append((w["film_start"], w["film_start"] + w["len"], i))
asp.sort()
for (a_s, a_e, a_i), (b_s, b_e, b_i) in zip(asp, asp[1:]):
if b_s < a_e - TOUCH_TOLERANCE:
@@ -1991,6 +2551,13 @@ def normalise_edit(edit: dict) -> dict:
c["mute"] = True
else:
c.pop("mute", None)
+ # SPEED, same rule: 1x is the absence of the field, clamped on the way
+ # to disk so every output is handed a legal rate.
+ sp = clip_speed(c)
+ if kind == "video" and abs(sp - 1.0) > 1e-9:
+ c["speed"] = sp
+ else:
+ c.pop("speed", None)
# NEUTRAL IS ABSENT here too, so a timeline nobody has put an effect on
# is byte-identical to one from before effects existed. The values are
# written back CLAMPED, so what is on disk is what all three outputs
@@ -2005,7 +2572,7 @@ def normalise_edit(edit: dict) -> dict:
# way to disk so all three outputs read the same legal curve.
if kind == "video":
w = clip_audio(c)
- ae = audio_effects(c, max(0.0, w["end"] - w["start"]))
+ ae = audio_effects(c, w["len"])
akeep = {k: ae[k] for k in ("fade_in", "fade_out") if ae[k] > 1e-9}
if ae["points"]:
akeep["points"] = ae["points"]
@@ -2033,6 +2600,12 @@ def normalise_edit(edit: dict) -> dict:
c["audio"]["linked"] = True
elif c.get("audio") is not None:
c.pop("audio", None)
+ # FRAMING, neutral-is-absent like everything else here, and written
+ # back clamped so all three outputs read the same window.
+ if kind != "slug" and isinstance(c.get("frame"), dict) and not clip_frame_is_neutral(c):
+ c["frame"] = clip_frame(c)
+ else:
+ c.pop("frame", None)
adj = c.get("adjust")
if isinstance(adj, dict):
b = clip_brightness(c)
@@ -2063,7 +2636,25 @@ def normalise_edit(edit: dict) -> dict:
for k in ("film_start", "film_end"):
o[k] = round(_f(o.get(k)), 6)
o["kind"] = overlay_kind(o)
- if o["kind"] == "still":
+ if o["kind"] == "text":
+ # A TITLE IS ITS SLOT AND ITS STRING. No file, no source clock —
+ # the same synthesis a still gets — and the style is written back
+ # CLAMPED and only where it differs from the default, so a title
+ # left at the defaults carries no style at all.
+ o["start"] = 0.0
+ o["end"] = round(max(0.0, o["film_end"] - o["film_start"]), 6)
+ o["duration"] = None
+ o["path"] = None
+ o["proxy"] = None
+ tt = overlay_text(o)
+ o["text"] = tt["text"]
+ skeep = {k: v for k, v in tt["style"].items()
+ if v != TEXT_STYLE_DEFAULTS[k]}
+ if skeep:
+ o["style"] = skeep
+ else:
+ o.pop("style", None)
+ elif o["kind"] == "still":
# A still is its slot and nothing else — the same synthesis a
# still CLIP gets, and the reason the trim handles can resize it.
o["start"] = 0.0
@@ -2073,7 +2664,7 @@ def normalise_edit(edit: dict) -> dict:
for k in ("start", "end"):
o[k] = round(_f(o.get(k)), 6)
if not o.get("id"):
- o["id"] = _clip_id(o.get("path"), _f(o.get("start")),
+ o["id"] = _clip_id(o.get("path") or o.get("text"), _f(o.get("start")),
_f(o.get("film_start")))
if o.get("source") not in ("auto", "human"):
o["source"] = "human"
@@ -2088,6 +2679,28 @@ def normalise_edit(edit: dict) -> dict:
out["overlays"] = ovs
else:
out.pop("overlays", None)
+ # THE TRANSITIONS. Rounded, sorted by the boundary they sit on, ids
+ # invented where missing, and NOTHING ELSE decided: the duration on disk
+ # is the one the user asked for, and `transition_duration` clamps it on
+ # every read against whatever the neighbours are that day — writing the
+ # clamped number back would let one trim silently shorten a dissolve for
+ # good. An empty list is an absent key.
+ txs = []
+ for t in transition_items(out):
+ t = dict(t)
+ t["after_clip"] = str(t.get("after_clip") or "")
+ t["kind"] = str(t.get("kind") or "").strip().lower()
+ t["duration"] = round(_f(t.get("duration")), 6)
+ if not t.get("id"):
+ t["id"] = _clip_id(t["after_clip"], t["duration"], 0.0)
+ txs.append(t)
+ at = {r["id"]: r["at"] for r in resolve_transitions({"clips": clips,
+ "transitions": txs})}
+ txs.sort(key=lambda t: (at.get(t["id"], float("inf")), t["id"]))
+ if txs:
+ out["transitions"] = txs
+ else:
+ out.pop("transitions", None)
out.setdefault("board_id", "")
# NEUTRAL IS ABSENT, the same rule `adjust` follows one block up. Dragging
# a trim handle back to the end of the track must leave a document
@@ -2843,6 +3456,7 @@ def edit_to_cuts(edit: dict) -> list[dict]:
reason this file exists.
"""
out = []
+ by_id: dict[str, dict] = {}
for c in (edit or {}).get("clips") or []:
if not isinstance(c, dict):
continue
@@ -2871,6 +3485,8 @@ def edit_to_cuts(edit: dict) -> list[dict]:
b = clip_brightness(c)
if abs(b) >= 1e-9:
entry["adjust"] = {"brightness": round(b, 6)}
+ if kind != "slug" and not clip_frame_is_neutral(c):
+ entry["frame"] = clip_frame(c)
if kind == "video":
w = clip_audio(c)
# Only a SPLIT clip says anything here, so a plan of ordinary cuts
@@ -2893,11 +3509,34 @@ def edit_to_cuts(edit: dict) -> list[dict]:
entry["fx"] = fx
if kind == "video":
w = clip_audio(c)
- gain = audio_gain_points(c, max(0.0, w["end"] - w["start"]))
+ # ON THE PLAYED CLOCK — see `audio_gain_points`.
+ gain = audio_gain_points(c, w["len"])
if gain:
entry["gain"] = gain
+ # Only when it says something, like every other field here.
+ sp = clip_speed(c)
+ if abs(sp - 1.0) > 1e-9:
+ entry["speed"] = sp
out.append(entry)
+ if c.get("id"):
+ by_id[str(c["id"])] = entry
out.sort(key=lambda e: e["film_start"])
+ # THE TRANSITIONS RIDE ON THE ENTRIES THEY JOIN: `transition` on the
+ # outgoing entry, `tx_in` (the extra head, in seconds) on the incoming.
+ # Only a transition that resolved without a problem is stamped — one the
+ # validator refused cannot reach the render through a stale document, and
+ # `transition_problems` is what the render asks first.
+ for t in resolve_transitions(edit):
+ if t.get("problem"):
+ continue
+ a, b = by_id.get(t["after_clip"]), by_id.get(t["before_clip"])
+ if a is None or b is None:
+ continue
+ ia, ib = out.index(a), out.index(b)
+ if ib != ia + 1:
+ continue
+ a["transition"] = {"kind": t["kind"], "duration": t["duration"]}
+ b["tx_in"] = t["half"]
return out
@@ -3191,12 +3830,16 @@ def _nle_segments(clips, *, probe=None) -> list[dict]:
"start": start, "end": end,
"film_start": fs, "film_end": fe,
"brightness": clip_brightness(c),
+ "frame": clip_frame(c),
"fx": clip_effects(c),
"w": int(info.get("w") or 0), "h": int(info.get("h") or 0),
"has_audio": bool(info.get("has_audio")),
- "gain": audio_gain_points(
- c, max(0.0, clip_audio(c)["end"] - clip_audio(c)["start"]))
+ "gain": audio_gain_points(c, clip_audio(c)["len"])
if clip_kind(c) == "video" else [],
+ # Carried for the far side to read. The XML's in/out (source) and
+ # start/end (timeline) already disagree by exactly this ratio,
+ # which is how an FCP7 importer infers a speed change.
+ "speed": clip_speed(c),
# Carried, never applied here: the export DISABLES the audio
# clipitem rather than dropping it, so the editor on the far end
# can see the decision and undo it.
@@ -3274,6 +3917,31 @@ def _fcp7_opacity(seg: dict, fps: int = NLE_FPS) -> str:
f"{kf}</parameter></effect></filter>")
+def _fcp7_motion(seg: dict) -> str:
+ """The reframe as Basic Motion — scale and centre — or "" when neutral.
+
+ The same rule the opacity keyframes follow: the DECISION travels, not
+ baked pixels. Scale is percent; the centre is the layer's offset from the
+ frame's centre in frame widths/heights, which is `zoom * (0.5 - x)`: the
+ point of the source that should sit at the middle, moved there.
+ """
+ f = seg.get("frame") or {}
+ z = _f(f.get("zoom"), 1.0)
+ if abs(z - 1.0) < 1e-9:
+ return ""
+ cx = z * (0.5 - _f(f.get("x"), 0.5))
+ cy = z * (0.5 - _f(f.get("y"), 0.5))
+ return ("<filter><effect><name>Basic Motion</name><effectid>basic</effectid>"
+ "<effectcategory>motion</effectcategory>"
+ "<effecttype>motion</effecttype><mediatype>video</mediatype>"
+ "<parameter><parameterid>scale</parameterid><name>Scale</name>"
+ "<valuemin>0</valuemin><valuemax>1000</valuemax>"
+ f"<value>{z * 100.0:.2f}</value></parameter>"
+ "<parameter><parameterid>center</parameterid><name>Center</name>"
+ f"<value><horiz>{cx:.4f}</horiz><vert>{cy:.4f}</vert></value></parameter>"
+ "</effect></filter>")
+
+
def _fcp7_rate(fps: int = NLE_FPS) -> str:
# ntsc FALSE is load-bearing: at ntsc TRUE an NLE reads timebase 24 as
# 23.976 and every cut past the first drifts one frame per 1000.
@@ -3368,6 +4036,7 @@ def fcp7_xml(segments, *, name: str, media: dict, width: int, height: int,
f"<in>{f_in}</in><out>{f_out}</out>"
f"{_fcp7_file(fid, seg, abs_media, fps=fps, declared=declared)}"
f"<compositemode>normal</compositemode>"
+ f"{_fcp7_motion(seg)}"
f"{_fcp7_opacity(seg, fps)}"
f"</clipitem>")
if seg["has_audio"]:
@@ -3553,6 +4222,20 @@ def ae_jsx(segments, *, name: str, media: dict, width: int, height: int,
]
if abs(seg["brightness"]) >= 1e-9:
lines.append(" bright(lay, %s);" % ae_b)
+ fr = seg.get("frame") or {}
+ z = _f(fr.get("zoom"), 1.0)
+ if abs(z - 1.0) >= 1e-9:
+ # THE REFRAME AS SCALE + POSITION, the same arithmetic the FCP7
+ # Basic Motion carries: the source point (x, y) is moved to the
+ # comp's centre and the layer magnified around it.
+ px = width / 2.0 + z * width * (0.5 - _f(fr.get("x"), 0.5))
+ py = height / 2.0 + z * height * (0.5 - _f(fr.get("y"), 0.5))
+ lines += [
+ " lay.property('ADBE Transform Group').property('ADBE Scale')"
+ ".setValue([%.3f, %.3f]);" % (z * 100.0, z * 100.0),
+ " lay.property('ADBE Transform Group').property('ADBE Position')"
+ ".setValue([%.3f, %.3f]);" % (px, py),
+ ]
fx = seg.get("fx") or {}
f_in, f_out = _f(fx.get("fade_in")), _f(fx.get("fade_out"))
if f_in > 1e-9 or f_out > 1e-9:
diff --git a/test_anchor_stills.py b/test_anchor_stills.py
new file mode 100644
index 0000000..41d8c83
--- /dev/null
+++ b/test_anchor_stills.py
@@ -0,0 +1,159 @@
+"""Anchor stills + long windows on the Storyboard, and the closed-tab push
+alert. Pins: the plan switches persist on the board; a shot with a still
+becomes an anchored i2v job; a long shot with the switch becomes a windows
+chain with the board's style as invariant; the still prompt drops camera
+moves; the still job form is an ordinary image job; the reconcile step folds
+a finished still back; VAPID keys persist and push with nobody listening
+sends nothing."""
+import json
+import os
+import tempfile
+from pathlib import Path
+
+import pytest
+
+import storyboard as sb
+import mlx_ltx_panel as p
+
+
+def test_shot_wants_still_only_for_text_and_character():
+ assert sb.shot_wants_still({"mode": "text"})
+ assert sb.shot_wants_still({"mode": "character"})
+ assert not sb.shot_wants_still({"mode": "keyframe"})
+ assert not sb.shot_wants_still({"mode": "extend"})
+ assert not sb.shot_wants_still("nope")
+
+
+def test_still_prompt_drops_camera_moves_keeps_the_scene():
+ out = sb.still_prompt("A woman at a kitchen table, the camera slowly pushes in on her face, warm light.")
+ assert "pushes" not in out and "camera" not in out
+ assert "kitchen table" in out and "warm light" in out
+ assert out.endswith("exactly as the shot opens.")
+
+
+def test_shot_with_still_becomes_anchored_i2v():
+ j = sb.shot_to_job({"n": 1, "mode": "text", "prompt": "x", "still": "/tmp/s.png", "duration_s": 4},
+ {"quality": "balanced", "width": 1024, "height": 576}, h3_available=False)
+ assert j["mode"] == "i2v" and j["image"] == "/tmp/s.png"
+ assert j["i2v_reference_mode"] == "anchor"
+
+
+def test_shot_without_still_stays_t2v():
+ j = sb.shot_to_job({"n": 1, "mode": "text", "prompt": "x", "duration_s": 4},
+ {"quality": "balanced"}, h3_available=False)
+ assert j["mode"] == "t2v" and "image" not in j
+
+
+def test_long_shot_with_switch_is_a_windows_chain():
+ j = sb.shot_to_job({"n": 2, "mode": "text", "prompt": "x", "duration_s": 9, "location": "harbor"},
+ {"quality": "balanced"}, h3_available=False, long_windows=True, style="35mm, warm")
+ assert j["frames"] > 121
+ assert j["temporal_mode"] == "windows"
+ assert j["window_invariants"] == "35mm, warm; harbor"
+
+
+def test_long_shot_without_switch_or_short_shot_is_native():
+ j = sb.shot_to_job({"n": 2, "mode": "text", "prompt": "x", "duration_s": 9},
+ {"quality": "balanced"}, h3_available=False)
+ assert "temporal_mode" not in j
+ j2 = sb.shot_to_job({"n": 2, "mode": "text", "prompt": "x", "duration_s": 3},
+ {"quality": "balanced"}, h3_available=False, long_windows=True)
+ assert "temporal_mode" not in j2
+
+
+def test_still_job_form_is_an_ordinary_image_job(monkeypatch):
+ monkeypatch.setattr(p, "_character_sheet_png", lambda t: Path("/tmp/sheet.png") if t == "ana" else None)
+ board = {"id": "b1", "title": "Test", "locations": {}, "wardrobe": {}}
+ shot = {"n": 3, "mode": "character", "character_id": "ana", "prompt": "Ana smiles", "seed": 7}
+ f = p._sb_still_job_form(shot, board, {"width": 720, "height": 1280})
+ assert f["mode"] == "image" and f["n"] == "1" and f["seed"] == "7"
+ assert f["aspect"] == "9:16"
+ assert f["engine_override"] == "qwen_edit_inline"
+ assert json.loads(f["refs"]) == ["/tmp/sheet.png"]
+ assert f["session_tag"] == "sb:b1#3:still"
+ # every key must be one make_job reads — build the job for real
+ job = p.make_job({k: str(v) for k, v in f.items()})
+ assert job["params"]["mode"] == "image"
+ assert job["params"]["refs"] == ["/tmp/sheet.png"]
+ assert job["params"]["engine_override"] == "qwen_edit_inline"
+
+
+def test_still_job_form_without_sheet_uses_default_engine(monkeypatch):
+ monkeypatch.setattr(p, "_character_sheet_png", lambda t: None)
+ f = p._sb_still_job_form({"n": 1, "mode": "text", "prompt": "x"}, {"id": "b", "title": ""}, {"width": 1280, "height": 704})
+ assert f["engine_override"] == "auto" and json.loads(f["refs"]) == [] and f["aspect"] == "16:9"
+
+
+def test_still_aspect_is_the_nearest_engine_aspect(monkeypatch):
+ monkeypatch.setattr(p, "_character_sheet_png", lambda t: None)
+ def asp(w, h):
+ return p._sb_still_job_form({"n": 1, "mode": "text", "prompt": "x"}, {"id": "b"}, {"width": w, "height": h})["aspect"]
+ assert asp(640, 448) == "4:3" # the draft canvas — not 16:9
+ assert asp(1024, 576) == "16:9"
+ assert asp(1280, 704) == "16:9"
+ assert asp(768, 1024) == "3:4"
+ assert asp(1024, 1024) == "1:1"
+ assert asp(1280, 544) == "21:9"
+
+
+def test_reconcile_folds_a_finished_still(monkeypatch):
+ monkeypatch.setattr(p, "_sb_job_index", lambda: {
+ "j1": {"status": "done", "output_path": "/out/still.png"},
+ "j2": {"status": "failed", "error": "boom"},
+ })
+ board = {"shots": [{"n": 1, "still_job_id": "j1"}, {"n": 2, "still_job_id": "j2"}]}
+ assert p._sb_reconcile(board) is True
+ assert board["shots"][0]["still"] == "/out/still.png"
+ assert board["shots"][1].get("still") is None
+ assert board["shots"][1]["still_error"] == "boom"
+
+
+def test_vapid_keys_persist_and_push_without_listeners_sends_nothing(monkeypatch):
+ with tempfile.TemporaryDirectory() as d:
+ monkeypatch.setattr(p, "STATE_DIR", Path(d))
+ k1 = p._vapid_keys()
+ assert k1 and k1["public"] and k1["private"]
+ assert p._vapid_keys() == k1
+ assert (Path(d) / "vapid.json").is_file()
+ assert p._push_subs() == []
+ assert p.push_notify("t", "b") == 0
+ p._push_save_subs([{"endpoint": "https://x/1", "keys": {"p256dh": "a", "auth": "b"}}])
+ assert len(p._push_subs()) == 1
+
+
+def test_push_routes_are_registered():
+ from panel import routes_meta # noqa: F401
+ from panel.routes import GET_ROUTES, POST_ROUTES
+ assert "/sw.js" in GET_ROUTES and "/push/key" in GET_ROUTES
+ for r in ("/push/subscribe", "/push/unsubscribe", "/push/test"):
+ assert r in POST_ROUTES
+ assert (p.ROOT / "webapp" / "sw.js").is_file()
+
+
+def test_loras_update_and_guide_routes_are_registered():
+ from panel import routes_loras # noqa: F401
+ from panel.routes import GET_ROUTES, POST_ROUTES
+ assert "/loras/updates" in GET_ROUTES
+ assert "/loras/guide" in POST_ROUTES
+
+
+def test_sidecar_guide_survives_the_reader(tmp_path):
+ lp = tmp_path / "x.safetensors"
+ lp.write_bytes(b"0" * 2048)
+ (tmp_path / "x.json").write_text(json.dumps({"name": "X", "guide": "Use it at 0.8 for a painterly look."}))
+ meta = p._read_lora_sidecar(lp)
+ assert meta["guide"] == "Use it at 0.8 for a painterly look."
+ assert p._read_lora_sidecar(tmp_path / "missing.safetensors")["guide"] == ""
+
+
+def test_clear_still_forgets_the_still_and_the_clip_made_from_it():
+ board = {"shots": [{"n": 1, "still": "/a.png", "still_job_id": "j", "draft_job_id": "d",
+ "draft_output": "/o.mp4", "status": "done"},
+ {"n": 2, "still": "/b.png"}]}
+ shot = p._sb_clear_still(board, 1)
+ assert shot is board["shots"][0]
+ for k in ("still", "still_job_id", "still_error", "draft_job_id", "draft_output"):
+ assert k not in shot
+ assert shot["status"] == "pending"
+ assert board["shots"][1]["still"] == "/b.png" # only shot 1
+ assert p._sb_clear_still(board, 9) is None
diff --git a/test_deliver.py b/test_deliver.py
new file mode 100644
index 0000000..1ed2650
--- /dev/null
+++ b/test_deliver.py
@@ -0,0 +1,173 @@
+#!/usr/bin/env python3
+"""Deliver as — what the Editor's film is encoded as, and how big.
+
+Locked: the default is byte-for-byte the H.264 the assembler always wrote;
+HEVC goes through VideoToolbox with the `hvc1` tag Safari needs; ProRes is a
+10-bit 4:2:2 .mov with PCM sound; size is UP only and appended as one Lanczos
+scale after the overlays; a different delivery is a different file name; and
+the route accepts `.mov`."""
+from __future__ import annotations
+
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+from unittest import mock
+
+ROOT = Path(__file__).resolve().parent
+sys.path.insert(0, str(ROOT))
+
+import mlx_ltx_panel as panel # noqa: E402
+
+
+def _seg(idx, start, end):
+ return {"kind": "video", "input": idx,
+ "info": {"has_audio": True, "duration": 10.0, "w": 768, "h": 416,
+ "sample_rate": 48000},
+ "window": {"start": start, "end": end}, "adjust": None,
+ "duration": end - start, "path": f"/x/{idx}.mp4"}
+
+
+class TheChoice(unittest.TestCase):
+ def test_resolution_and_defaults(self):
+ d = panel._sb_deliver(None, None)
+ self.assertEqual([d["format"], d["size"], d["height"], d["ext"]],
+ ["h264", "native", 0, ".mp4"])
+ d = panel._sb_deliver("PRORES", "2160p")
+ self.assertEqual([d["format"], d["height"], d["ext"], d["label"]],
+ ["prores", 2160, ".mov", "ProRes 422 HQ · 2160p"])
+ self.assertEqual(panel._sb_deliver("gif", "8k")["format"], "h264")
+
+ def test_the_names(self):
+ b = {"title": "The car wash"}
+ self.assertEqual(panel._sb_film_name(b), "the-car-wash_film.mp4")
+ self.assertEqual(panel._sb_film_name(b, panel._sb_deliver("hevc", "1080p")),
+ "the-car-wash_film_hevc_1080p.mp4")
+ self.assertEqual(panel._sb_film_name(b, panel._sb_deliver("prores", None)),
+ "the-car-wash_film_prores.mov")
+
+ def test_the_encoder_args(self):
+ codec = {"pix_fmt": "yuv420p", "crf": "18"}
+ h = panel._sb_encode_args(panel._sb_deliver("h264", None), codec)
+ self.assertEqual(h[:6], ["-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18"])
+ v = panel._sb_encode_args(panel._sb_deliver("hevc", None), codec)
+ self.assertIn("hevc_videotoolbox", v)
+ self.assertEqual(v[v.index("-tag:v") + 1], "hvc1")
+ p = panel._sb_encode_args(panel._sb_deliver("prores", None), codec)
+ self.assertIn("prores_ks", p)
+ self.assertEqual(p[p.index("-pix_fmt") + 1], "yuv422p10le")
+ self.assertEqual(p[p.index("-c:a") + 1], "pcm_s16le")
+ self.assertNotIn("+faststart", p)
+
+
+class TheGraph(unittest.TestCase):
+ def test_no_size_is_the_graph_it_always_was(self):
+ with mock.patch.object(panel, "bt709_vf", return_value=""):
+ g0, _ = panel._sb_film_filtergraph([], 768, 416, 48000, "yuv420p",
+ segments=[_seg(0, 0, 4)])
+ g1, _ = panel._sb_film_filtergraph([], 768, 416, 48000, "yuv420p",
+ segments=[_seg(0, 0, 4)], scale_to=0)
+ self.assertEqual(g0, g1)
+ self.assertNotIn("scale=-2", g0)
+
+ def test_the_size_is_one_lanczos_scale_after_everything(self):
+ with mock.patch.object(panel, "bt709_vf", return_value=""):
+ g, lbl = panel._sb_film_filtergraph([], 768, 416, 48000, "yuv420p",
+ segments=[_seg(0, 0, 4)], scale_to=1080)
+ self.assertTrue(g.endswith("[vcat]scale=-2:1080:flags=lanczos[vdl]"))
+ self.assertEqual(lbl, "[vdl]")
+
+
+class TheAssembler(unittest.TestCase):
+ def _run(self, deliver):
+ info = {"has_audio": True, "duration": 10.0, "w": 768, "h": 416,
+ "sample_rate": 48000}
+ seen = {}
+
+ def fake_ffmpeg(cmd, label):
+ seen["cmd"] = cmd
+ Path(cmd[-1]).write_bytes(b"x")
+ with tempfile.TemporaryDirectory() as d, \
+ mock.patch.object(panel, "_sb_probe_clip", return_value=info), \
+ mock.patch.object(panel, "run_ffmpeg_tracked", side_effect=fake_ffmpeg), \
+ mock.patch.object(panel, "_sb_write_film_sidecar"):
+ res = panel._sb_assemble_film(
+ ["/x/a.mp4"], Path(d) / "f.mp4",
+ timeline=[{"path": "/x/a.mp4", "start": 0.0, "end": 4.0,
+ "film_start": 0.0}], deliver=deliver)
+ return res, seen["cmd"]
+
+ def test_default_is_the_old_command(self):
+ res, cmd = self._run(None)
+ self.assertEqual(cmd[cmd.index("-c:v") + 1], "libx264")
+ self.assertEqual([res["width"], res["height"]], [768, 416])
+ self.assertEqual(res["deliver"]["format"], "h264")
+
+ def test_hevc_at_1080p_scales_and_reports_the_new_size(self):
+ res, cmd = self._run({"format": "hevc", "size": "1080p"})
+ self.assertEqual(cmd[cmd.index("-c:v") + 1], "hevc_videotoolbox")
+ self.assertIn("scale=-2:1080:flags=lanczos", cmd[cmd.index("-filter_complex") + 1])
+ self.assertEqual([res["width"], res["height"]], [1994, 1080])
+ self.assertEqual(res["deliver"]["label"], "HEVC · 1080p")
+
+ def test_prores_asks_the_graph_for_10_bit_422(self):
+ res, cmd = self._run({"format": "prores", "size": "native"})
+ graph = cmd[cmd.index("-filter_complex") + 1]
+ self.assertIn("format=yuv422p10le[v0]", graph)
+ self.assertEqual(cmd[cmd.index("-c:v") + 1], "prores_ks")
+
+ def test_a_1080_cut_delivered_at_1080p_is_not_scaled(self):
+ info = {"has_audio": True, "duration": 10.0, "w": 1920, "h": 1080,
+ "sample_rate": 48000}
+ seen = {}
+
+ def fake_ffmpeg(cmd, label):
+ seen["cmd"] = cmd
+ Path(cmd[-1]).write_bytes(b"x")
+ with tempfile.TemporaryDirectory() as d, \
+ mock.patch.object(panel, "_sb_probe_clip", return_value=info), \
+ mock.patch.object(panel, "run_ffmpeg_tracked", side_effect=fake_ffmpeg), \
+ mock.patch.object(panel, "_sb_write_film_sidecar"):
+ panel._sb_assemble_film(
+ ["/x/a.mp4"], Path(d) / "f.mp4",
+ timeline=[{"path": "/x/a.mp4", "start": 0.0, "end": 4.0,
+ "film_start": 0.0}], deliver={"format": "h264", "size": "1080p"})
+ self.assertNotIn("scale=-2", seen["cmd"][seen["cmd"].index("-filter_complex") + 1])
+
+
+class TheRoute(unittest.TestCase):
+ def test_the_route_names_the_file_by_delivery_and_allows_mov(self):
+ from test_storyboard_editor_api import FakeHandler
+ board = {"id": "sb_t", "title": "The car wash", "shots": []}
+ with mock.patch.object(panel.storyboard, "load_storyboard", return_value=board), \
+ mock.patch("storyboard_editor.load_edit", return_value={"version": 2, "clips": [{"id": "a"}]}), \
+ mock.patch.object(panel, "_sbe_render_edit",
+ return_value={"ok": True, "path": "/x/f.mov", "clips": 1,
+ "duration": 4.0}) as rend:
+ h = FakeHandler()
+ h.post("edit/render", {"id": "sb_t", "format": "prores", "size": "2160p"})
+ self.assertEqual(h.status, 200, h.payload)
+ kw = rend.call_args.kwargs
+ self.assertEqual(kw["out_name"], "the-car-wash_film_prores_2160p.mov")
+ self.assertEqual(kw["deliver"], {"format": "prores", "size": "2160p", "finish": ""})
+
+
+if __name__ == "__main__":
+ unittest.main()
+
+
+class TheFinish(unittest.TestCase):
+ def test_grain_is_added_after_the_size_and_names_the_file(self):
+ d = panel._sb_deliver("h264", "1080p", "heavy_grain")
+ self.assertEqual([d["finish"], d["grain"], d["label"]],
+ ["heavy_grain", 18, "H.264 · 1080p · heavy grain"])
+ self.assertEqual(panel._sb_deliver(None, None, "snow")["finish"], "none")
+ self.assertEqual(panel._sb_film_name({"title": "x"}, d), "x_film_1080p_heavy_grain.mp4")
+ with mock.patch.object(panel, "bt709_vf", return_value=""):
+ g, lbl = panel._sb_film_filtergraph([], 768, 416, 48000, "yuv420p",
+ segments=[_seg(0, 0, 4)], scale_to=1080, grain=9)
+ self.assertTrue(g.endswith("[vcat]scale=-2:1080:flags=lanczos[vdl];[vdl]noise=alls=9:allf=t+u[vgr]"))
+ self.assertEqual(lbl, "[vgr]")
+ with mock.patch.object(panel, "bt709_vf", return_value=""):
+ g0, _ = panel._sb_film_filtergraph([], 768, 416, 48000, "yuv420p", segments=[_seg(0, 0, 4)])
+ self.assertNotIn("noise=", g0)
diff --git a/test_director.py b/test_director.py
new file mode 100644
index 0000000..0651bed
--- /dev/null
+++ b/test_director.py
@@ -0,0 +1,222 @@
+#!/usr/bin/env python3
+"""The Director: a track on the storyboard brief turns the plan into a music
+video cut to the beat.
+
+What is locked: the grid is the same downbeat fit the Editor's Prepare runs;
+the shot count and every duration come from the track and not from the
+chips; the brief the planner reads carries the grid and the two laws that
+have already cost renders (lead with the movement; no dialogue under a
+replaced track); a bad path is refused before the planner runs; and a board
+planned this way opens in the Editor already cut under its track."""
+from __future__ import annotations
+
+import sys
+import unittest
+from pathlib import Path
+from unittest import mock
+
+ROOT = Path(__file__).resolve().parent
+sys.path.insert(0, str(ROOT))
+
+import mlx_ltx_panel as panel # noqa: E402
+import storyboard_edit as sedt # noqa: E402
+
+
+def _beats(bpm=128.0, bars=40, meter=4):
+ bar = 60.0 / bpm * meter
+ downs = [round(i * bar, 6) for i in range(bars)]
+ return {"bpm": bpm, "downbeats": downs, "beats": downs,
+ "confidence": 0.9, "duration": round(bars * bar, 6)}
+
+
+def _flat_map(*a, **k):
+ """No sections: the base stride throughout."""
+ return {"bpm": 128.0, "bars": [], "sections": [], "mean_energy": 0.5}
+
+
+class TheGrid(unittest.TestCase):
+ def test_slots_are_downbeats_every_n_bars(self):
+ with mock.patch.object(sedt, "beat_map", return_value=_beats()), \
+ mock.patch.object(sedt, "song_map", side_effect=_flat_map), \
+ tempfile_file() as track:
+ g = panel._sb_director_grid({"path": track, "bars_per_shot": 2})
+ self.assertNotIn("error", g)
+ self.assertEqual(g["bpm"], 128.0)
+ self.assertEqual(g["bars_per_shot"], 2)
+ self.assertEqual(g["count"], 20)
+ self.assertAlmostEqual(g["slot_sec"], 3.75, places=2)
+ self.assertAlmostEqual(g["slots"][1]["start"], 3.75, places=3)
+ self.assertAlmostEqual(g["slots"][-1]["end"], 75.0, places=3)
+ self.assertTrue(any("MUSIC VIDEO" in m for m in g["must"]))
+ self.assertTrue(any("begin each description with the movement" in m
+ for m in g["must"]))
+ self.assertTrue(any("no shot contains dialogue" in m for m in g["must"]))
+
+ def test_a_long_track_is_capped_and_says_so(self):
+ with mock.patch.object(sedt, "beat_map", return_value=_beats(bars=200)), \
+ mock.patch.object(sedt, "song_map", side_effect=_flat_map), \
+ tempfile_file() as track:
+ g = panel._sb_director_grid({"path": track, "bars_per_shot": 1},
+ max_shots=48)
+ self.assertEqual(g["count"], 48)
+ self.assertIn("first", g["note"])
+ self.assertTrue(any("more bars than 48 shots" in m for m in g["must"]))
+
+ def test_a_missing_file_and_a_beatless_track_are_sentences(self):
+ self.assertIn("no audio file", panel._sb_director_grid({"path": "/nope.wav"})["error"])
+ with mock.patch.object(sedt, "beat_map",
+ return_value={"bpm": 0, "downbeats": [], "duration": 0}), \
+ mock.patch.object(sedt, "song_map", side_effect=_flat_map), \
+ tempfile_file() as track:
+ g = panel._sb_director_grid({"path": track})
+ self.assertIn("no beat", g["error"])
+
+ def test_sections_change_the_stride_and_the_brief_names_the_arc(self):
+ beats = _beats(bars=24) # 24 bars, 1.875 s each
+ secs = [{"start": 0.0, "end": 8 * 1.875, "label": "intro", "energy": 0.2,
+ "brightness": 0.3, "bars": [0, 8]},
+ {"start": 8 * 1.875, "end": 16 * 1.875, "label": "chorus", "energy": 0.9,
+ "brightness": 0.8, "bars": [8, 16]},
+ {"start": 16 * 1.875, "end": 24 * 1.875, "label": "outro", "energy": 0.2,
+ "brightness": 0.3, "bars": [16, 24]}]
+ with mock.patch.object(sedt, "beat_map", return_value=beats), \
+ mock.patch.object(sedt, "song_map",
+ return_value={"bpm": 128.0, "sections": secs,
+ "mean_energy": 0.43, "bars": []}), \
+ tempfile_file() as track:
+ g = panel._sb_director_grid({"path": track, "bars_per_shot": 2})
+ # intro: 8 bars at 4 = 2 slots; chorus: 8 bars at 1 = 8; outro: 2
+ self.assertEqual([s["section"] for s in g["slots"]],
+ ["intro"] * 2 + ["chorus"] * 8 + ["outro"] * 2)
+ self.assertEqual([s["bars"] for s in g["slots"]][:3], [4, 4, 1])
+ self.assertAlmostEqual(g["slots"][2]["end"] - g["slots"][2]["start"], 1.875, places=3)
+ self.assertTrue(any("shots 3–10 are the chorus" in m for m in g["must"]))
+ self.assertTrue(any("shots 1–2 are the intro" in m for m in g["must"]))
+ self.assertEqual(len(g["sections"]), 3)
+
+ def test_a_song_map_failure_falls_back_to_the_base_stride(self):
+ with mock.patch.object(sedt, "beat_map", return_value=_beats()), \
+ mock.patch.object(sedt, "song_map", side_effect=RuntimeError("boom")), \
+ tempfile_file() as track:
+ g = panel._sb_director_grid({"path": track, "bars_per_shot": 2})
+ self.assertEqual(g["count"], 20)
+
+ def test_the_brief_carries_the_grid(self):
+ c = panel._sb_director_concept("A boxer at dawn.",
+ {"bpm": 128.0, "total_sec": 75.0, "count": 20,
+ "slot_sec": 3.75, "bars_per_shot": 2})
+ self.assertTrue(c.startswith("A boxer at dawn."))
+ self.assertIn("128 bpm", c)
+ self.assertIn("20 shots of about 3.8s", c)
+ self.assertIn("ARC", c)
+
+
+class TheFirstCutIsOnTheTrack(unittest.TestCase):
+ def test_the_boards_soundtrack_is_the_auto_edits_default(self):
+ board = {"id": "sb_dir", "title": "d", "shots": [],
+ "soundtrack": {"path": "/x/track.wav"}}
+ with mock.patch.object(panel, "_sbe_board_clips", return_value=[]), \
+ mock.patch.object(panel, "_sbe_prepare_cache", return_value={}), \
+ mock.patch.object(panel, "_sbe_board_dir", return_value=Path("/tmp/x")), \
+ mock.patch("storyboard_editor.edit_from_plan") as efp:
+ panel._sbe_auto_edit(board)
+ # no clips yet: the empty edit is what comes back, and nothing raised
+ efp.assert_called_once()
+
+ def test_plan_refuses_a_bad_track_before_the_planner_runs(self):
+ from test_storyboard_editor_api import FakeHandler
+ h = FakeHandler()
+ with mock.patch.object(panel, "_sb_claim_planner", return_value=None), \
+ mock.patch.object(panel, "_sb_release_planner"), \
+ mock.patch.dict(panel.STATE, {"running": None, "queue": []}), \
+ mock.patch.object(panel.threading, "Thread") as th:
+ panel.Handler._storyboard_post(
+ h, "plan", "", {"concept": "x", "soundtrack": "/nope/track.wav"})
+ self.assertEqual(h.status, 400)
+ self.assertIn("no audio file", h.payload["error"])
+ th.assert_not_called()
+
+
+class tempfile_file:
+ """A real, empty file at a real path — `is_file()` is all the grid asks."""
+ def __enter__(self):
+ import tempfile
+ self._t = tempfile.NamedTemporaryFile(suffix=".wav", delete=False)
+ self._t.close()
+ return self._t.name
+
+ def __exit__(self, *a):
+ Path(self._t.name).unlink(missing_ok=True)
+
+
+if __name__ == "__main__":
+ unittest.main()
+
+
+class TheRulerGetsTheArc(unittest.TestCase):
+ def test_the_payload_carries_the_boards_sections(self):
+ board = {"id": "sb_dir", "title": "d", "shots": [],
+ "soundtrack": {"path": "/x/t.wav",
+ "sections": [{"start": 0, "end": 30, "label": "intro",
+ "energy": 0.3}]}}
+ edit = {"version": 2, "clips": [], "audio": None}
+ with mock.patch.object(panel, "_sbe_board_clips", return_value=[]), \
+ mock.patch.object(panel, "_sbe_board_dir", return_value=Path("/tmp/x")), \
+ mock.patch.object(panel, "_sbe_proxy_map", return_value={}), \
+ mock.patch.object(panel, "_sbe_relinks", return_value=[]), \
+ mock.patch.object(panel, "_sbe_job_state", return_value={}), \
+ mock.patch("storyboard_editor.list_drafts", return_value=[]), \
+ mock.patch("storyboard_editor.load_draft_index", return_value={"active": ""}), \
+ mock.patch("storyboard_editor.pending_backup", return_value=None), \
+ mock.patch("storyboard_editor.current_session", return_value={}):
+ p = panel._sbe_payload(board, edit)
+ self.assertEqual(p["sections"][0]["label"], "intro")
+
+
+class TheAutoPipeline(unittest.TestCase):
+ def test_the_brief_stores_the_switch(self):
+ from test_storyboard_editor_api import FakeHandler
+ seen = {}
+ def fake_save(state_dir, board):
+ seen["auto"] = board.get("auto")
+ with mock.patch.object(panel, "_sb_claim_planner", return_value=None), \
+ mock.patch.object(panel, "_sb_release_planner"), \
+ mock.patch.dict(panel.STATE, {"running": None, "queue": []}), \
+ mock.patch.object(panel.storyboard, "save_storyboard", side_effect=fake_save), \
+ mock.patch.object(panel.threading, "Thread") as th:
+ th.return_value.start = lambda: None
+ h = FakeHandler()
+ panel.Handler._storyboard_post(h, "plan", "", {"concept": "x", "auto": "1"})
+ self.assertEqual(h.status, 202, h.payload)
+ self.assertTrue(seen["auto"])
+
+ def test_the_film_waits_for_a_shot_that_did_not_render(self):
+ board = {"id": "b", "title": "t", "auto": True,
+ "shots": [{"n": 1, "draft_output": "/x/a.mp4"}, {"n": 2}]}
+ with mock.patch.object(panel, "_sbe_auto_edit") as ae, \
+ mock.patch.object(panel, "push") as p:
+ self.assertIsNone(panel._sb_auto_film(board))
+ ae.assert_not_called()
+ self.assertIn("1 shot(s) did not render", p.call_args[0][0])
+
+ def test_the_film_is_cut_and_assembled_when_every_shot_landed(self):
+ board = {"id": "b", "title": "t", "auto": True,
+ "shots": [{"n": 1, "draft_output": "/x/a.mp4"},
+ {"n": 2, "status": "skipped"},
+ {"n": 3, "final_output": "/x/c.mp4"}]}
+ edit = {"version": 2, "clips": [{"id": "a"}, {"id": "c"}], "beats": {"bpm": 120}}
+ with mock.patch.object(panel, "_sbe_auto_edit", return_value=edit) as ae, \
+ mock.patch.object(panel, "_sbe_board_dir", return_value=Path("/tmp/x")), \
+ mock.patch("storyboard_editor.save_edit") as save, \
+ mock.patch("storyboard_editor.load_edit", return_value=edit), \
+ mock.patch.object(panel, "_sbe_render_edit",
+ return_value={"ok": True, "path": "/x/film.mp4"}) as rend, \
+ mock.patch.object(panel.storyboard, "save_storyboard") as sb_save, \
+ mock.patch.object(panel, "push"):
+ film = panel._sb_auto_film(board)
+ ae.assert_called_once_with(board)
+ save.assert_called_once()
+ rend.assert_called_once()
+ self.assertEqual(film["path"], "/x/film.mp4")
+ self.assertEqual(board["auto_film"], "/x/film.mp4")
+ sb_save.assert_called_once()
diff --git a/test_editor_frame.py b/test_editor_frame.py
new file mode 100644
index 0000000..c5a3f17
--- /dev/null
+++ b/test_editor_frame.py
@@ -0,0 +1,141 @@
+#!/usr/bin/env python3
+"""Framing — a zoom and a reframe per clip, honest in all three outputs.
+
+Locked: neutral is absent; the window is clamped; a slug has nothing to
+reframe; the render crops the SOURCE's own pixels before the fit so one
+string is right at every size and composes with trims, speed and fades;
+the FCP7 export carries it as Basic Motion (scale + centre) and the AE
+script as scale + position — the decision travels, never baked pixels."""
+from __future__ import annotations
+
+import sys
+import unittest
+import xml.etree.ElementTree as ET
+from pathlib import Path
+from unittest import mock
+
+ROOT = Path(__file__).resolve().parent
+sys.path.insert(0, str(ROOT))
+
+import mlx_ltx_panel as panel # noqa: E402
+import storyboard_editor as sedit # noqa: E402
+
+
+def _clip(cid, path, start, end, film_start, **kw):
+ c = sedit.new_clip(path, start, end, film_start, id=cid, duration=10.0, source="human")
+ c.update(kw)
+ return c
+
+
+def _doc(clips, **kw):
+ d = {"version": sedit.EDIT_VERSION, "board_id": "sb_f", "revision": 0, "source": "human",
+ "audio": None, "beats": None, "clips": clips, "settings": {}}
+ d.update(kw)
+ return d
+
+
+def _codes(doc):
+ return [e["code"] for e in sedit.validate_edit(doc)]
+
+
+class TheModel(unittest.TestCase):
+ def test_absent_is_the_whole_frame(self):
+ self.assertEqual(sedit.clip_frame({}), {"zoom": 1.0, "x": 0.5, "y": 0.5})
+ self.assertTrue(sedit.clip_frame_is_neutral({"frame": {"zoom": 1.0, "x": 0.2}}))
+ f = sedit.clip_frame({"frame": {"zoom": 9, "x": -1, "y": 2}})
+ self.assertEqual(f, {"zoom": 3.0, "x": 0.0, "y": 1.0})
+
+ def test_validation(self):
+ c = _clip("a", "/x/a.mp4", 0, 4, 0, frame={"zoom": 2.0, "x": 0.3, "y": 0.7})
+ self.assertEqual(_codes(_doc([c])), [])
+ c["frame"] = {"zoom": 5}
+ self.assertIn("clip_frame_range", _codes(_doc([c])))
+ c["frame"] = {"zoom": "big"}
+ self.assertIn("clip_frame", _codes(_doc([c])))
+ c["frame"] = "no"
+ self.assertIn("clip_frame", _codes(_doc([c])))
+ s = {"id": "s", "kind": "slug", "path": None, "start": 0, "end": 2, "film_start": 0,
+ "film_end": 2, "source": "human", "locked": False, "frame": {"zoom": 2}}
+ self.assertIn("clip_frame_kind", _codes(_doc([s])))
+
+ def test_normalise_writes_only_a_real_reframe_and_clamps_it(self):
+ c = _clip("a", "/x/a.mp4", 0, 4, 0, frame={"zoom": 1.0, "x": 0.1})
+ self.assertNotIn("frame", sedit.normalise_edit(_doc([c]))["clips"][0])
+ c = _clip("a", "/x/a.mp4", 0, 4, 0, frame={"zoom": 2.5, "x": 1.4, "y": 0.25})
+ got = sedit.normalise_edit(_doc([c]))["clips"][0]["frame"]
+ self.assertEqual(got, {"zoom": 2.5, "x": 1.0, "y": 0.25})
+ cut = sedit.edit_to_cuts(_doc([c]))[0]
+ self.assertEqual(cut["frame"], {"zoom": 2.5, "x": 1.0, "y": 0.25})
+ self.assertNotIn("frame", sedit.edit_to_cuts(_doc([_clip("b", "/x/b.mp4", 0, 4, 0)]))[0])
+
+
+class TheRender(unittest.TestCase):
+ def test_no_reframe_adds_no_filter(self):
+ self.assertEqual(panel._sb_frame_term(None), "")
+ self.assertEqual(panel._sb_frame_term({"zoom": 1.0}), "")
+ self.assertEqual(panel._sb_frame_term({"zoom": "x"}), "")
+
+ def test_the_crop_is_the_sources_own_pixels_centred_on_the_anchor(self):
+ t = panel._sb_frame_term({"zoom": 2.0, "x": 0.25, "y": 0.5})
+ self.assertTrue(t.startswith("crop=w=2*floor(iw/2.000000/2):h=2*floor(ih/2.000000/2):"))
+ self.assertIn("x=(iw-2*floor(iw/2.000000/2))*0.250000", t)
+ self.assertIn("y=(ih-2*floor(ih/2.000000/2))*0.500000", t)
+ self.assertTrue(t.endswith(","))
+
+ def test_the_crop_sits_after_the_trim_and_before_the_fit(self):
+ seg = {"kind": "video", "input": 0,
+ "info": {"has_audio": True, "duration": 10.0, "w": 768, "h": 416,
+ "sample_rate": 48000},
+ "window": {"start": 1.0, "end": 4.0}, "adjust": None, "duration": 3.0,
+ "path": "/x/a.mp4", "frame": {"zoom": 2.0, "x": 0.5, "y": 0.5}, "speed": 2.0}
+ with mock.patch.object(panel, "bt709_vf", return_value=""):
+ g, _ = panel._sb_film_filtergraph([], 768, 416, 48000, "yuv420p", segments=[seg])
+ chain = [c for c in g.split(";") if c.startswith("[0:v]")][0]
+ self.assertLess(chain.index("setpts="), chain.index("crop="))
+ self.assertLess(chain.index("crop="), chain.index("fps="))
+ self.assertLess(chain.index("fps="), chain.index("scale="))
+
+ def test_the_timeline_pass_carries_it_on_stills_too(self):
+ cuts = [{"path": "/x/card.png", "kind": "still", "start": 0.0, "end": 3.0,
+ "film_start": 0.0, "frame": {"zoom": 1.5, "x": 0.5, "y": 0.5}}]
+ with mock.patch.object(panel, "_sb_probe_still",
+ return_value={"w": 768, "h": 416, "duration": 0,
+ "has_audio": False, "sample_rate": 0}):
+ segs, _, _ = panel._sb_timeline_segments(cuts)
+ self.assertEqual(segs[0]["frame"]["zoom"], 1.5)
+ with mock.patch.object(panel, "bt709_vf", return_value=""):
+ g, _ = panel._sb_film_filtergraph([], 768, 416, 48000, "yuv420p", segments=segs)
+ self.assertIn("setpts=PTS-STARTPTS,crop=", g)
+
+
+class TheExport(unittest.TestCase):
+ def test_fcp7_carries_basic_motion(self):
+ seg = {"frame": {"zoom": 2.0, "x": 0.25, "y": 0.5}}
+ xml = sedit._fcp7_motion(seg)
+ root = ET.fromstring(xml)
+ self.assertEqual(root.find("effect/effectid").text, "basic")
+ params = {p.find("parameterid").text: p for p in root.findall("effect/parameter")}
+ self.assertEqual(params["scale"].find("value").text, "200.00")
+ self.assertEqual(params["center"].find("value/horiz").text, "0.5000")
+ self.assertEqual(params["center"].find("value/vert").text, "0.0000")
+ self.assertEqual(sedit._fcp7_motion({"frame": {"zoom": 1.0}}), "")
+
+ def test_ae_scales_and_moves_the_layer(self):
+ c = _clip("a", "/x/a.mp4", 0, 4, 0, frame={"zoom": 2.0, "x": 0.25, "y": 0.5})
+ rows = sedit._nle_segments([c], probe=lambda p: {"w": 768, "h": 416, "duration": 10.0,
+ "has_audio": True})
+ jsx = sedit.ae_jsx(rows, name="f", media={"/x/a.mp4": "a.mp4"}, width=1920,
+ height=1080, fps=24, audio=None)
+ self.assertIn("('ADBE Scale').setValue([200.000, 200.000])", jsx)
+ # x = 0.25 at 2x: the layer's centre moves right by 0.5 frame widths
+ self.assertIn("('ADBE Position').setValue([1920.000, 540.000])", jsx)
+
+ def test_the_project_rows_carry_the_frame(self):
+ c = _clip("a", "/x/a.mp4", 0, 4, 0, frame={"zoom": 2.0})
+ rows = sedit._nle_segments([c], probe=lambda p: {"w": 768, "h": 416, "duration": 10.0,
+ "has_audio": True})
+ self.assertEqual(rows[0]["frame"]["zoom"], 2.0)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/test_editor_v2.py b/test_editor_v2.py
new file mode 100644
index 0000000..6d530b7
--- /dev/null
+++ b/test_editor_v2.py
@@ -0,0 +1,700 @@
+#!/usr/bin/env python3
+"""Editor v2 — speed on the clip, titles on the overlay lane, transitions on
+the cut. The server half, plus the client half run side by side.
+
+THREE THINGS ARE LOCKED HERE, and each is the failure that would otherwise
+be silent:
+
+1. **A transition never widens the picture lane.** It is a typed object on a
+ BOUNDARY (`transitions[]`, `after_clip`), the clips' slots do not move, the
+ film stays exactly as long as the timeline says, and a boundary with no
+ source handles is REFUSED with a sentence naming the side and the shortfall
+ — never rendered as a hard cut. The graph is split at the boundary and
+ joined with `xfade`, centred on the cut; the sound takes the lane path and
+ is byte-for-byte what it was.
+
+2. **Speed is one term on each clock.** `setpts` on the picture, `atempo`
+ (chained past 0.5–2.0) on the sound, `(end - start) / speed` on the film.
+ Every strip length, drift, resync and envelope reads the PLAYED length, and
+ the client computes the same numbers as the server for the same document.
+
+3. **A title is a card the render draws.** Explicit `kind: "text"` wins in
+ `overlay_kind`, every existing overlay still reads from its suffix, the
+ font is a FILE resolved and verified before ffmpeg is built, and the raster
+ is frame-sized RGBA fed through the same overlay chain as an uploaded PNG.
+
+Run: ./ltx-2-mlx/env/bin/python3.11 -m pytest -q test_editor_v2.py
+"""
+from __future__ import annotations
+
+import json
+import os
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+from unittest import mock
+
+ROOT = Path(__file__).resolve().parent
+sys.path.insert(0, str(ROOT))
+
+import mlx_ltx_panel as panel # noqa: E402
+import storyboard_editor as sedit # noqa: E402
+from test_storyboard_editor_ui import (FUNCTIONS, NODE, SHIM, # noqa: E402
+ extract_function, panel_source)
+
+
+def _clip(cid, path, start, end, film_start, **kw):
+ c = sedit.new_clip(path, start, end, film_start, id=cid,
+ duration=kw.pop("duration", 10.0), source="human")
+ c.update(kw)
+ return c
+
+
+def _doc(clips, **kw):
+ d = {"version": sedit.EDIT_VERSION, "board_id": "sb_v2", "revision": 0,
+ "source": "human", "audio": None, "beats": None, "clips": clips,
+ "settings": {}}
+ d.update(kw)
+ return d
+
+
+def _two(tail=2.0, head=2.0, **kw):
+ """Two touching clips: A plays 1..4 of a 10 s take (spare tail = 10-4),
+ B plays `head`..`head`+3 of its own 10 s take (spare head = `head`)."""
+ a = _clip("a", "/x/a.mp4", 1.0, 4.0, 0.0, duration=4.0 + tail)
+ b = _clip("b", "/x/b.mp4", head, head + 3.0, 3.0)
+ return _doc([a, b], **kw)
+
+
+def _codes(doc):
+ return [e["code"] for e in sedit.validate_edit(doc)]
+
+
+def _seg(idx, start, end, *, speed=None, duration=10.0, has_audio=True, **kw):
+ s = {"kind": "video", "input": idx,
+ "info": {"has_audio": has_audio, "duration": duration, "w": 768,
+ "h": 416, "sample_rate": 48000},
+ "window": {"start": start, "end": end}, "adjust": None,
+ "duration": (end - start) / (speed or 1.0), "path": f"/x/{idx}.mp4"}
+ if speed:
+ s["speed"] = speed
+ s.update(kw)
+ return s
+
+
+# =============================================================================
+# TRANSITIONS
+# =============================================================================
+class ATransitionOwnsABoundary(unittest.TestCase):
+ def test_a_valid_dissolve_validates_and_the_clips_do_not_move(self):
+ doc = _two(transitions=[{"id": "t1", "after_clip": "a",
+ "kind": "dissolve", "duration": 0.5}])
+ self.assertEqual(_codes(doc), [])
+ norm = sedit.normalise_edit(doc)
+ self.assertEqual([c["film_start"] for c in norm["clips"]], [0.0, 3.0])
+ self.assertEqual([c["film_end"] for c in norm["clips"]], [3.0, 6.0])
+ self.assertEqual(sedit.edit_duration(norm), 6.0)
+ r = sedit.resolve_transitions(norm)[0]
+ self.assertIsNone(r["problem"])
+ self.assertEqual(r["before_clip"], "b")
+ self.assertEqual(r["at"], 3.0)
+ self.assertEqual(r["duration"], 0.5) # 12 frames at 24 fps
+ self.assertEqual(r["half"], 0.25)
+
+ def test_the_picture_lane_rule_is_untouched(self):
+ # The invariant this whole design exists to keep: pictures may not
+ # overlap, and WARNING_CODES still holds exactly the one code.
+ self.assertEqual(sedit.WARNING_CODES, frozenset({"clips_audio_overlap"}))
+ doc = _two()
+ doc["clips"][1]["film_start"] = 2.5
+ doc["clips"][1]["film_end"] = 5.5
+ self.assertIn("clips_overlap", _codes(doc))
+
+ def test_every_transition_code_is_an_error_never_a_warning(self):
+ for code in ("transitions_shape", "transition_shape",
+ "transition_unknown_clip", "transition_duplicate_boundary",
+ "transition_no_handles", "transition_kind",
+ "transition_duration", "transition_last_clip"):
+ self.assertNotIn(code, sedit.WARNING_CODES)
+
+ def test_shape_and_unknown_clip(self):
+ self.assertIn("transitions_shape", _codes(_two(transitions="no")))
+ self.assertIn("transition_shape", _codes(_two(transitions=["no"])))
+ self.assertIn("transition_unknown_clip",
+ _codes(_two(transitions=[{"after_clip": "zz",
+ "kind": "dissolve",
+ "duration": 0.5}])))
+
+ def test_one_per_boundary(self):
+ doc = _two(transitions=[
+ {"id": "t1", "after_clip": "a", "kind": "dissolve", "duration": 0.5},
+ {"id": "t2", "after_clip": "a", "kind": "fade_black", "duration": 0.5}])
+ self.assertIn("transition_duplicate_boundary", _codes(doc))
+
+ def test_the_last_clip_has_nothing_to_dissolve_into(self):
+ doc = _two(transitions=[{"id": "t1", "after_clip": "b",
+ "kind": "dissolve", "duration": 0.5}])
+ self.assertIn("transition_last_clip", _codes(doc))
+
+ def test_no_handles_names_the_side_and_the_shortfall(self):
+ # A has 0.1 s past its out-point; a 0.5 s dissolve needs 0.25 s.
+ doc = _two(tail=0.1, transitions=[{"id": "t1", "after_clip": "a",
+ "kind": "dissolve", "duration": 0.5}])
+ errs = [e for e in sedit.validate_edit(doc)
+ if e["code"] == "transition_no_handles"]
+ self.assertEqual(len(errs), 1)
+ self.assertIn("clip 1 has only 0.10s beyond its out-point", errs[0]["message"])
+ self.assertIn("needs 0.25s", errs[0]["message"])
+ self.assertEqual(errs[0]["where"], 0)
+ # ...and the incoming side, in its own words.
+ doc = _two(head=0.0, transitions=[{"id": "t1", "after_clip": "a",
+ "kind": "dissolve", "duration": 0.5}])
+ msg = [e for e in sedit.validate_edit(doc)
+ if e["code"] == "transition_no_handles"][0]["message"]
+ self.assertIn("clip 2 has only 0.00s before its in-point", msg)
+
+ def test_an_unknown_source_length_is_refused_not_guessed(self):
+ doc = _two(transitions=[{"id": "t1", "after_clip": "a",
+ "kind": "dissolve", "duration": 0.5}])
+ doc["clips"][0]["duration"] = None
+ msg = [e for e in sedit.validate_edit(doc)
+ if e["code"] == "transition_no_handles"][0]["message"]
+ self.assertIn("not known", msg)
+
+ def test_a_still_and_a_slug_have_infinite_handles(self):
+ a = {"id": "a", "kind": "slug", "path": None, "start": 0, "end": 3,
+ "film_start": 0.0, "film_end": 3.0, "source": "human",
+ "locked": False}
+ b = _clip("b", "/x/b.mp4", 2.0, 5.0, 3.0)
+ doc = _doc([a, b], transitions=[{"id": "t1", "after_clip": "a",
+ "kind": "fade_black",
+ "duration": 1.0}])
+ self.assertEqual(_codes(doc), [])
+
+ def test_the_duration_is_clamped_to_half_the_shorter_side_and_2s(self):
+ doc = _two(tail=5.0, head=5.0,
+ transitions=[{"id": "t1", "after_clip": "a",
+ "kind": "dissolve", "duration": 9.0}])
+ r = sedit.resolve_transitions(doc)[0]
+ self.assertEqual(r["duration"], 1.5) # half of the 3 s B
+ # ...and to even frames: 0.8 s is 19.2 frames, which becomes 20.
+ doc["transitions"][0]["duration"] = 0.8
+ self.assertAlmostEqual(sedit.resolve_transitions(doc)[0]["duration"],
+ 20 / 24, places=6)
+ # The document keeps what the user typed.
+ self.assertEqual(sedit.normalise_edit(doc)["transitions"][0]["duration"], 0.8)
+
+ def test_normalise_is_stable_and_absent_when_empty(self):
+ doc = _two(transitions=[{"after_clip": "a", "kind": "dissolve",
+ "duration": 0.5}])
+ once = sedit.normalise_edit(doc)
+ self.assertTrue(once["transitions"][0]["id"])
+ twice = sedit.normalise_edit(json.loads(json.dumps(once)))
+ self.assertEqual(once["transitions"], twice["transitions"])
+ self.assertNotIn("transitions", sedit.normalise_edit(_two(transitions=[])))
+ self.assertNotIn("transitions", sedit.normalise_edit(_two()))
+
+ def test_the_cut_list_stamps_the_pair_and_only_a_resolved_pair(self):
+ doc = _two(transitions=[{"id": "t1", "after_clip": "a",
+ "kind": "dissolve", "duration": 0.5}])
+ cuts = sedit.edit_to_cuts(doc)
+ self.assertEqual(cuts[0]["transition"], {"kind": "dissolve", "duration": 0.5})
+ self.assertEqual(cuts[1]["tx_in"], 0.25)
+ bad = _two(tail=0.0, transitions=[{"id": "t1", "after_clip": "a",
+ "kind": "dissolve", "duration": 0.5}])
+ cuts = sedit.edit_to_cuts(bad)
+ self.assertNotIn("transition", cuts[0])
+ self.assertNotIn("tx_in", cuts[1])
+
+ def test_a_document_without_transitions_builds_the_identical_cut_list(self):
+ self.assertEqual(sedit.edit_to_cuts(_two()),
+ sedit.edit_to_cuts(_two(transitions=[])))
+ for e in sedit.edit_to_cuts(_two()):
+ self.assertNotIn("transition", e)
+ self.assertNotIn("tx_in", e)
+ self.assertNotIn("speed", e)
+
+
+class TheGraphSplitsAtTheBoundary(unittest.TestCase):
+ def graph(self, segs, **kw):
+ with mock.patch.object(panel, "bt709_vf", return_value=""):
+ return panel._sb_film_filtergraph([], 768, 416, 48000, "yuv420p",
+ segments=segs, **kw)
+
+ def test_no_transition_is_the_concat_it_always_was(self):
+ g, lbl = self.graph([_seg(0, 1.0, 4.0), _seg(1, 2.0, 5.0)])
+ self.assertIn("[v0][a0][v1][a1]concat=n=2:v=1:a=1[vcat][aout]", g)
+ self.assertNotIn("xfade", g)
+ self.assertEqual(lbl, "[vcat]")
+
+ def test_the_two_runs_are_crossfaded_centred_on_the_cut(self):
+ segs = [_seg(0, 1.0, 4.0, transition={"kind": "dissolve", "duration": 0.5}),
+ _seg(1, 2.0, 5.0, tx_in=0.25)]
+ g, _ = self.graph(segs)
+ # The outgoing picture pulls 0.25 s past its out-point, the incoming
+ # 0.25 s before its in-point; the audio windows are UNTOUCHED.
+ self.assertIn("[0:v]trim=start=1.000000:end=4.250000,setpts=PTS-STARTPTS", g)
+ self.assertIn("[1:v]trim=start=1.750000:end=5.000000,setpts=PTS-STARTPTS", g)
+ self.assertIn("[0:a]atrim=start=1.000000:end=4.000000,", g)
+ self.assertIn("[1:a]atrim=start=2.000000:end=5.000000,", g)
+ self.assertIn("[v0]concat=n=1:v=1:a=0[pg0]", g)
+ self.assertIn("[v1]concat=n=1:v=1:a=0[pg1]", g)
+ # offset = len(run 0) - duration = 3.25 - 0.5
+ self.assertIn("[pg0][pg1]xfade=transition=fade:duration=0.500000:"
+ "offset=2.750000[vcat]", g)
+ # ...and the sound takes the lane path, end to end, gapless.
+ self.assertIn("[a0][a1]concat=n=2:v=0:a=1[aout]", g)
+ self.assertIn("apad,atrim=0:3.000000,asetpts=PTS-STARTPTS[a0]", g)
+
+ def test_fade_black_is_ffmpegs_fadeblack(self):
+ segs = [_seg(0, 1.0, 4.0, transition={"kind": "fade_black", "duration": 1.0}),
+ _seg(1, 2.0, 5.0, tx_in=0.5)]
+ g, _ = self.graph(segs)
+ self.assertIn("xfade=transition=fadeblack:duration=1.000000", g)
+
+ def test_three_clips_two_boundaries_chain_offsets(self):
+ segs = [_seg(0, 1.0, 4.0, transition={"kind": "dissolve", "duration": 0.5}),
+ _seg(1, 2.0, 5.0, tx_in=0.25,
+ transition={"kind": "dissolve", "duration": 1.0}),
+ _seg(2, 1.0, 3.0, tx_in=0.5)]
+ g, _ = self.graph(segs)
+ self.assertIn("[pg0][pg1]xfade=transition=fade:duration=0.500000:offset=2.750000[px1]", g)
+ # after the first join the picture is 3.25 + 3.75 - 0.5 = 6.5 long
+ self.assertIn("[px1][pg2]xfade=transition=fade:duration=1.000000:offset=5.500000[vcat]", g)
+
+ def test_a_dangling_transition_is_reconciled_by_the_timeline_pass(self):
+ cuts = [{"path": "/x/a.mp4", "start": 1.0, "end": 4.0, "film_start": 0.0,
+ "transition": {"kind": "dissolve", "duration": 0.5}},
+ {"path": "/x/missing.mp4", "start": 2.0, "end": 5.0,
+ "film_start": 3.0, "tx_in": 0.25}]
+ info = {"has_audio": True, "duration": 10.0, "w": 768, "h": 416,
+ "sample_rate": 48000}
+ with mock.patch.object(panel, "_sb_probe_clip",
+ side_effect=lambda p: None if "missing" in str(p) else info):
+ segs, unreadable, _ = panel._sb_timeline_segments(cuts)
+ self.assertEqual(unreadable, ["missing.mp4"])
+ self.assertNotIn("transition", segs[0])
+
+ def test_a_still_input_loops_for_its_handles_too(self):
+ cuts = [{"path": "/x/a.mp4", "start": 1.0, "end": 4.0, "film_start": 0.0,
+ "transition": {"kind": "dissolve", "duration": 0.5}},
+ {"path": "/x/card.png", "kind": "still", "start": 0.0, "end": 3.0,
+ "film_start": 3.0, "tx_in": 0.25}]
+ info = {"has_audio": True, "duration": 10.0, "w": 768, "h": 416,
+ "sample_rate": 48000}
+ with mock.patch.object(panel, "_sb_probe_clip", return_value=info), \
+ mock.patch.object(panel, "_sb_probe_still",
+ return_value={"w": 768, "h": 416, "duration": 0,
+ "has_audio": False, "sample_rate": 0}):
+ segs, _, inputs = panel._sb_timeline_segments(cuts)
+ self.assertEqual(inputs[1][5], "3.250000")
+ self.assertEqual(segs[1]["duration"], 3.0)
+
+ def test_the_render_refuses_with_the_validators_sentence(self):
+ doc = _two(tail=0.0, transitions=[{"id": "t1", "after_clip": "a",
+ "kind": "dissolve", "duration": 0.5}])
+ board = {"id": "sb_v2", "title": "v2"}
+ with mock.patch.object(panel, "_sb_assemble_film") as asm:
+ res = panel._sbe_render_edit(board, doc)
+ self.assertFalse(res["ok"])
+ self.assertEqual(res["status"], 400)
+ self.assertIn("beyond its out-point", res["error"])
+ asm.assert_not_called()
+
+
+# =============================================================================
+# SPEED
+# =============================================================================
+class SpeedOnTheClip(unittest.TestCase):
+ def test_absent_is_1x_and_stills_have_no_clock(self):
+ self.assertEqual(sedit.clip_speed(_clip("a", "/x/a.mp4", 0, 3, 0)), 1.0)
+ self.assertEqual(sedit.clip_speed({"kind": "still", "speed": 2.0}), 1.0)
+ self.assertEqual(sedit.clip_speed(_clip("a", "/x/a.mp4", 0, 3, 0, speed=9)), 4.0)
+ self.assertEqual(sedit.clip_speed(_clip("a", "/x/a.mp4", 0, 3, 0, speed=0.01)), 0.25)
+
+ def test_the_slot_is_the_window_over_the_speed(self):
+ c = _clip("a", "/x/a.mp4", 0.0, 4.0, 0.0, speed=2.0)
+ c["film_end"] = 2.0
+ self.assertEqual(_codes(_doc([c])), [])
+ c["film_end"] = 4.0
+ self.assertIn("clip_length_mismatch", _codes(_doc([c])))
+ self.assertEqual(sedit.clip_audio(c)["len"], 2.0)
+ self.assertEqual(sedit.clip_audio(c)["speed"], 2.0)
+
+ def test_range_and_kind(self):
+ c = _clip("a", "/x/a.mp4", 0.0, 4.0, 0.0, speed=8.0)
+ c["film_end"] = 0.5
+ self.assertIn("clip_speed_range", _codes(_doc([c])))
+ s = {"id": "s", "kind": "still", "path": str(ROOT / "assets" / "icon.png"),
+ "start": 0, "end": 2, "film_start": 0, "film_end": 2,
+ "source": "human", "locked": False, "speed": 2.0}
+ self.assertIn("clip_speed_kind", _codes(_doc([s])))
+
+ def test_normalise_writes_only_a_non_unity_speed(self):
+ c = _clip("a", "/x/a.mp4", 0.0, 4.0, 0.0, speed=1.0)
+ self.assertNotIn("speed", sedit.normalise_edit(_doc([c]))["clips"][0])
+ c = _clip("a", "/x/a.mp4", 0.0, 4.0, 0.0, speed=0.5)
+ c["film_end"] = 8.0
+ self.assertEqual(sedit.normalise_edit(_doc([c]))["clips"][0]["speed"], 0.5)
+ self.assertEqual(sedit.edit_to_cuts(_doc([c]))[0]["speed"], 0.5)
+
+ def test_drift_and_resync_are_on_the_films_clock(self):
+ c = _clip("a", "/x/a.mp4", 2.0, 6.0, 10.0, speed=2.0)
+ c["film_end"] = 12.0
+ # The strip starts at source 3.0, which the picture plays at 10.5.
+ c["audio"] = {"start": 3.0, "end": 6.0, "film_start": 10.5}
+ self.assertEqual(sedit.clip_audio_drift(c), 0.0)
+ c["audio"]["film_start"] = 11.0
+ self.assertEqual(sedit.clip_audio_drift(c), 0.5)
+ self.assertEqual(sedit.clip_audio_resync(c), 10.5)
+
+ def test_the_envelope_reads_the_played_length(self):
+ c = _clip("a", "/x/a.mp4", 0.0, 4.0, 0.0, speed=2.0,
+ afx={"fade_out": 1.0})
+ c["film_end"] = 2.0
+ cut = sedit.edit_to_cuts(_doc([c]))[0]
+ self.assertEqual(cut["gain"], [[0.0, 1.0], [1.0, 1.0], [2.0, 0.0]])
+ self.assertEqual(sedit.audible_strips(_doc([c])), [[0.0, 2.0]])
+
+ def test_atempo_is_chained_past_the_window(self):
+ self.assertEqual(panel._sb_atempo_term(1.0), "")
+ self.assertEqual(panel._sb_atempo_term(2.0), "atempo=2.000000,")
+ self.assertEqual(panel._sb_atempo_term(4.0), "atempo=2.000000,atempo=2.000000,")
+ self.assertEqual(panel._sb_atempo_term(0.25), "atempo=0.500000,atempo=0.500000,")
+ self.assertEqual(panel._sb_atempo_term(3.0), "atempo=2.000000,atempo=1.500000,")
+
+ def test_the_graph_retimes_picture_and_sound_together(self):
+ with mock.patch.object(panel, "bt709_vf", return_value=""):
+ g, _ = panel._sb_film_filtergraph(
+ [], 768, 416, 48000, "yuv420p",
+ segments=[_seg(0, 1.0, 5.0, speed=2.0)])
+ self.assertIn("[0:v]trim=start=1.000000:end=5.000000,"
+ "setpts=(PTS-STARTPTS)/2.000000,fps=24,", g)
+ self.assertIn("[0:a]atrim=start=1.000000:end=5.000000,asetpts=PTS-STARTPTS,"
+ "atempo=2.000000,aresample=48000,", g)
+ self.assertIn("apad,atrim=0:2.000000,asetpts=PTS-STARTPTS[a0]", g)
+
+ def test_the_split_plan_lays_a_retimed_strip_at_its_played_length(self):
+ segs = [_seg(0, 0.0, 4.0, speed=2.0, mute=False),
+ _seg(1, 0.0, 2.0, audio={"start": 0.0, "end": 2.0, "delta": 0.0})]
+ plan = panel._sb_split_audio_plan(segs)
+ self.assertTrue(plan["split"])
+ self.assertEqual(plan["total"], 4.0)
+ self.assertEqual(plan["lanes"][0]["len"], 2.0)
+ self.assertEqual(plan["lanes"][0]["end"], 4.0) # source seconds
+ self.assertEqual(plan["lanes"][0]["speed"], 2.0)
+ self.assertEqual(plan["lanes"][1]["at"], 2.0)
+
+
+# =============================================================================
+# TITLES
+# =============================================================================
+class ATitleIsACardTheRenderDraws(unittest.TestCase):
+ def _title(self, **kw):
+ o = {"id": "o1", "kind": "text", "text": "FIN", "film_start": 1.0,
+ "film_end": 3.0}
+ o.update(kw)
+ return o
+
+ def test_explicit_kind_wins_and_the_suffix_still_decides_the_rest(self):
+ self.assertEqual(sedit.overlay_kind(self._title()), "text")
+ self.assertEqual(sedit.overlay_kind({"path": "/x/card.png"}), "still")
+ self.assertEqual(sedit.overlay_kind({"path": "/x/loop.mp4"}), "video")
+ self.assertEqual(sedit.overlay_kind({"kind": "still", "path": "/x/a.mp4"}), "still")
+
+ def test_validate_and_normalise(self):
+ doc = _doc([_clip("a", "/x/a.mp4", 0, 5, 0)], overlays=[self._title()])
+ self.assertEqual(_codes(doc), [])
+ n = sedit.normalise_edit(doc)["overlays"][0]
+ self.assertEqual(n["kind"], "text")
+ self.assertIsNone(n["path"])
+ self.assertEqual([n["start"], n["end"]], [0.0, 2.0])
+ self.assertNotIn("style", n) # defaults are absent
+ doc["overlays"][0]["text"] = " "
+ self.assertIn("overlay_text_empty", _codes(doc))
+ doc["overlays"][0]["text"] = "x"
+ doc["overlays"][0]["style"] = {"font_size": 9999, "x": 3, "align": "up",
+ "color": "red", "box": "yes"}
+ codes = _codes(doc)
+ self.assertIn("overlay_text_style_range", codes)
+ self.assertIn("overlay_text_style", codes)
+
+ def test_the_accessor_clamps_and_writes_only_what_differs(self):
+ o = self._title(style={"font_size": 9999, "x": 3, "color": "#fc0",
+ "box": True, "box_opacity": 2})
+ t = sedit.overlay_text(o)
+ self.assertEqual(t["style"]["font_size"], 400)
+ self.assertEqual(t["style"]["x"], 1.0)
+ self.assertEqual(t["style"]["color"], "#ffcc00")
+ self.assertTrue(t["style"]["box"])
+ self.assertEqual(t["style"]["box_opacity"], 1.0)
+ doc = _doc([_clip("a", "/x/a.mp4", 0, 5, 0)], overlays=[o])
+ n = sedit.normalise_edit(doc)["overlays"][0]
+ self.assertEqual(n["style"], {"font_size": 400, "x": 1.0, "color": "#ffcc00",
+ "box": True, "box_opacity": 1.0})
+
+ def test_the_font_is_a_file_and_a_missing_one_is_a_sentence(self):
+ with mock.patch.dict(os.environ, {"LTX_TITLE_FONT": "/nope/none.ttf"}):
+ self.assertIsNone(sedit.title_font_path())
+ self.assertIn("/nope/none.ttf", sedit.title_font_problem())
+ with mock.patch.dict(os.environ, {}, clear=False):
+ os.environ.pop("LTX_TITLE_FONT", None)
+ with mock.patch.object(sedit, "TITLE_FONT_CANDIDATES", ()):
+ self.assertIn("no font for titles", sedit.title_font_problem())
+
+ def test_the_raster_is_frame_sized_rgba_with_ink_where_the_anchor_is(self):
+ if sedit.title_font_path() is None:
+ raise unittest.SkipTest("no system font on this machine")
+ from PIL import Image
+ with tempfile.TemporaryDirectory() as d:
+ p = sedit.render_title(self._title(style={"y": 0.9, "box": True}),
+ 640, 360, Path(d) / "t.png")
+ im = Image.open(p)
+ self.assertEqual(im.mode, "RGBA")
+ self.assertEqual(im.size, (640, 360))
+ a = im.getchannel("A")
+ self.assertEqual(a.getpixel((320, 20)), 0) # sky is clear
+ self.assertGreater(a.getpixel((320, 324)), 0) # ink at y=0.9
+
+ def test_the_assembler_feeds_the_raster_through_the_overlay_chain(self):
+ if sedit.title_font_path() is None:
+ raise unittest.SkipTest("no system font on this machine")
+ info = {"has_audio": True, "duration": 10.0, "w": 768, "h": 416,
+ "sample_rate": 48000}
+ seen = {}
+
+ def fake_ffmpeg(cmd, label):
+ seen["cmd"] = cmd
+ Path(cmd[-1]).write_bytes(b"x")
+ with tempfile.TemporaryDirectory() as d, \
+ mock.patch.object(panel, "_sb_probe_clip", return_value=info), \
+ mock.patch.object(panel, "run_ffmpeg_tracked", side_effect=fake_ffmpeg), \
+ mock.patch.object(panel, "_sb_write_film_sidecar"):
+ res = panel._sb_assemble_film(
+ ["/x/a.mp4"], Path(d) / "f.mp4",
+ timeline=[{"path": "/x/a.mp4", "start": 0.0, "end": 4.0,
+ "film_start": 0.0}],
+ overlays=[self._title()])
+ self.assertTrue(res["ok"], res)
+ cmd = seen["cmd"]
+ i = cmd.index("-filter_complex")
+ graph = cmd[i + 1]
+ png = [a for a in cmd if a.endswith(".png")][0]
+ self.assertTrue(Path(png).is_file())
+ self.assertIn("/.titles/title_", png)
+ self.assertIn("-loop", cmd)
+ self.assertIn("[1:v]format=rgba,scale=768:416:flags=lanczos,format=rgba", graph)
+ self.assertIn("enable='between(t,1.000000,3.000000)'", graph)
+
+ def test_the_assembler_refuses_without_a_font(self):
+ info = {"has_audio": True, "duration": 10.0, "w": 768, "h": 416,
+ "sample_rate": 48000}
+ with tempfile.TemporaryDirectory() as d, \
+ mock.patch.object(panel, "_sb_probe_clip", return_value=info), \
+ mock.patch.object(panel, "run_ffmpeg_tracked") as ff, \
+ mock.patch.dict(os.environ, {"LTX_TITLE_FONT": "/nope/none.ttf"}):
+ res = panel._sb_assemble_film(
+ ["/x/a.mp4"], Path(d) / "f.mp4",
+ timeline=[{"path": "/x/a.mp4", "start": 0.0, "end": 4.0,
+ "film_start": 0.0}],
+ overlays=[self._title()])
+ self.assertFalse(res["ok"])
+ self.assertIn("/nope/none.ttf", res["error"])
+ ff.assert_not_called()
+
+
+# =============================================================================
+# THE CLIENT AGREES WITH THE SERVER
+# =============================================================================
+BODY = r"""
+const out = {};
+const A = { id: 'a', path: '/x/a.mp4', start: 1, end: 4, film_start: 0, film_end: 3,
+ duration: 6, source: 'human', locked: false };
+const B = { id: 'b', path: '/x/b.mp4', start: 2, end: 5, film_start: 3, film_end: 6,
+ duration: 10, source: 'human', locked: false };
+const TX = [{ id: 't1', after_clip: 'a', kind: 'dissolve', duration: 0.5 }];
+out.resolved = sbeTxResolve([A, B], TX, 24);
+out.short = sbeTxResolve([Object.assign({}, A, { duration: 4.1 }), B], TX, 24);
+out.clamp = sbeTxDuration({ duration: 9 }, 3, 3, 24);
+out.even = sbeTxDuration({ duration: 0.8 }, 3, 3, 24);
+out.edges = [sbeTxEdges([A, B], TX, 'a', 24), sbeTxEdges([A, B], TX, 'b', 24)];
+out.prune = sbeTxPrune(TX.concat([{ id: 't2', after_clip: 'b', kind: 'dissolve', duration: 1 },
+ { id: 't3', after_clip: 'zz', kind: 'dissolve', duration: 1 }]),
+ [A, B]).map(t => t.id);
+out.repoint = sbeTxRepoint(TX, 'a', 'a2')[0].after_clip;
+out.set = sbeTxSet([], 'a', 'fade_black', 9).transitions[0];
+out.del = sbeTxDelete(TX, 'a').transitions.length;
+out.opacity = [2.5, 2.875, 3].map(t => sbeFadeOpacityAt(A, t, { head: 0, tail: 0.25 }));
+// speed
+const C = { id: 'c', path: '/x/c.mp4', start: 0, end: 4, film_start: 0, film_end: 4,
+ duration: 10, source: 'human', locked: false };
+const D = { id: 'd', path: '/x/d.mp4', start: 0, end: 2, film_start: 4, film_end: 6,
+ duration: 10, source: 'human', locked: false };
+const r = sbeSetSpeed([C, D], 'c', 2);
+out.speed = [r.ok, sbeById(r.clips, 'c').speed, sbeById(r.clips, 'c').film_end,
+ sbeById(r.clips, 'd').film_start, sbeLen(sbeById(r.clips, 'c'))];
+const c2 = sbeById(r.clips, 'c');
+out.audioLen = sbeClipAudio(c2).len;
+const tr = sbeTrim(r.clips.map(x => Object.assign({}, x)), 'c', 'r', 3, { ripple: true }); // ⌘: grow past the neighbour; the speed arithmetic is the subject
+out.trimR = [sbeById(tr.clips, 'c').end, sbeById(tr.clips, 'c').film_end];
+const sp = sbeSplitAt(r.clips.map(x => Object.assign({}, x)), 1, 'new',
+ [{ id: 't9', after_clip: 'c', kind: 'dissolve', duration: 0.5 }]);
+out.split = [sp.ok, sbeById(sp.clips, 'c').end, sbeById(sp.clips, 'new').start,
+ sbeById(sp.clips, 'new').film_start, sp.transitions[0].after_clip];
+const dr = Object.assign({}, c2, { audio: { start: 1, end: 3, film_start: 0.75 } });
+out.drift = [sbeAudioDrift(dr), sbeAudioDrift(Object.assign({}, dr, { audio: { start: 1, end: 3, film_start: 0.5 } }))];
+out.clean = [sbeCleanClip(c2).speed, sbeCleanClip(C).speed === undefined];
+// framing: clamped, neutral absent, a slug refuses
+out.frame = (() => {
+ const r = sbeSetFraming([Object.assign({}, C)], 'c', 'zoom', 2.5);
+ const r2 = sbeSetFraming(r.clips, 'c', 'x', 1.7);
+ const r3 = sbeSetFraming(r2.clips, 'c', 'zoom', 1);
+ const slug = sbeSetFraming([{ id: 's', kind: 'slug', start: 0, end: 2, film_start: 0, film_end: 2 }], 's', 'zoom', 2);
+ return [sbeById(r.clips, 'c').frame, sbeById(r2.clips, 'c').frame, sbeById(r3.clips, 'c').frame === undefined,
+ slug.ok, sbeCleanClip(sbeById(r2.clips, 'c')).frame, sbeFraming({}).zoom];
+})();
+// duplicate: same window, speed and fades, linked sound, right after, ripple
+const dup = sbeDuplicate([Object.assign({}, c2, { fx: { fade_in: 0.5 }, audio: { start: 0, end: 4, film_start: 0.5 } }), Object.assign({}, D)], 'c');
+out.dup = [dup.ok, dup.clips.length, dup.added.start, dup.added.end, dup.added.speed,
+ dup.added.fx.fade_in, dup.added.audio === undefined, dup.added.film_start,
+ sbeById(dup.clips, 'd').film_start];
+// titles
+out.kind = [sbeOvKind({ kind: 'text', text: 'x' }), sbeOvKind({ path: '/x/a.png' }), sbeOvKind({ path: '/x/a.mp4' })];
+out.text = sbeOvText({ kind: 'text', text: 'A\r\nB', style: { font_size: 9999, x: 3, color: '#fc0', box: true, box_opacity: 2 } });
+out.add = sbeOvAdd([], { kind: 'text', text: 'FIN', duration_s: 2 }, 5).added;
+out.rgba = sbeRgba('#ff0000', 0.5);
+process.stdout.write(JSON.stringify(out));
+"""
+
+
+def run_client() -> dict:
+ if NODE is None:
+ raise unittest.SkipTest("node not on PATH")
+ source = panel_source()
+ script = (SHIM + "\n".join(extract_function(n, source) for n in FUNCTIONS)
+ + "\n(async () => {\n" + BODY + "\n})();\n")
+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:
+ fh.write(script)
+ path = Path(fh.name)
+ try:
+ result = subprocess.run([NODE, str(path)], capture_output=True,
+ text=True, timeout=60)
+ if result.returncode:
+ raise AssertionError(result.stdout + "\n" + result.stderr)
+ return json.loads(result.stdout)
+ finally:
+ path.unlink(missing_ok=True)
+
+
+class TheClientAgrees(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.r = run_client()
+
+ def test_transitions_resolve_the_same_way(self):
+ r = self.r["resolved"][0]
+ self.assertIsNone(r["problem"])
+ self.assertEqual([r["before_clip"], r["at"], r["duration"], r["half"]],
+ ["b", 3.0, 0.5, 0.25])
+ s = self.r["short"][0]
+ self.assertEqual(s["problem"]["code"], "transition_no_handles")
+ self.assertIn("only 0.10s beyond its out-point", s["problem"]["message"])
+ self.assertEqual(self.r["clamp"], 1.5)
+ self.assertAlmostEqual(self.r["even"], 20 / 24, places=6)
+ # ...the same numbers Python produces for the same document.
+ a = _clip("a", "/x/a.mp4", 1.0, 4.0, 0.0, duration=6.0)
+ b = _clip("b", "/x/b.mp4", 2.0, 5.0, 3.0)
+ py = sedit.resolve_transitions(_doc([a, b], transitions=[
+ {"id": "t1", "after_clip": "a", "kind": "dissolve", "duration": 0.5}]))[0]
+ self.assertEqual([py["duration"], py["half"], py["at"]],
+ [r["duration"], r["half"], r["at"]])
+
+ def test_edges_prune_repoint_set_delete(self):
+ self.assertEqual(self.r["edges"], [{"head": 0, "tail": 0.25}, {"head": 0.25, "tail": 0}])
+ self.assertEqual(self.r["prune"], ["t1"]) # t2 is on the last clip
+ self.assertEqual(self.r["repoint"], "a2")
+ self.assertEqual([self.r["set"]["kind"], self.r["set"]["duration"]], ["fade_black", 2.0])
+ self.assertEqual(self.r["del"], 0)
+ self.assertEqual(self.r["opacity"], [1, 0.5, 0])
+
+ def test_speed_reflows_and_retimes(self):
+ self.assertEqual(self.r["speed"], [True, 2, 2, 2, 2])
+ self.assertEqual(self.r["audioLen"], 2)
+ # a right trim of one film second at 2x moves the out-point two
+ # source seconds
+ self.assertEqual(self.r["trimR"], [6, 3])
+ self.assertEqual(self.r["split"], [True, 2, 2, 1, "new"])
+ self.assertEqual(self.r["drift"], [0.25, 0])
+ self.assertEqual(self.r["clean"], [2, True])
+
+ def test_framing_is_clamped_and_neutral_is_absent(self):
+ f = self.r["frame"]
+ self.assertEqual(f[0], {"zoom": 2.5, "x": 0.5, "y": 0.5})
+ self.assertEqual(f[1], {"zoom": 2.5, "x": 1, "y": 0.5})
+ self.assertTrue(f[2])
+ self.assertFalse(f[3])
+ self.assertEqual(f[4], {"zoom": 2.5, "x": 1, "y": 0.5})
+ self.assertEqual(f[5], 1)
+ # ...and the same numbers Python clamps to
+ self.assertEqual(sedit.clip_frame({"frame": {"zoom": 2.5, "x": 1.7}}),
+ {"zoom": 2.5, "x": 1.0, "y": 0.5})
+
+ def test_duplicate_is_the_same_shot_again_right_after(self):
+ # c is 0–4 of the take at 2x = 2 s on the film; the copy starts at 2
+ # and d slides from 4 to 6
+ self.assertEqual(self.r["dup"], [True, 3, 0, 4, 2, 0.5, True, 2, 4])
+
+ def test_titles_read_the_same_defaults_and_clamps(self):
+ self.assertEqual(self.r["kind"], ["text", "still", "video"])
+ t = self.r["text"]
+ self.assertEqual(t["text"], "A\nB")
+ py = sedit.overlay_text({"kind": "text", "text": "A\r\nB",
+ "style": {"font_size": 9999, "x": 3, "color": "#fc0",
+ "box": True, "box_opacity": 2}})
+ self.assertEqual(t["style"], py["style"])
+ self.assertEqual(self.r["add"]["kind"], "text")
+ self.assertIsNone(self.r["add"]["path"])
+ self.assertEqual(self.r["rgba"], "rgba(255,0,0,0.500)")
+
+ def test_the_constants_are_the_panels(self):
+ import re
+ src = (ROOT / "webapp" / "js" / "editor.js").read_text()
+ for name, val in (("SBE_SPEED_MIN", sedit.SPEED_MIN),
+ ("SBE_SPEED_MAX", sedit.SPEED_MAX),
+ ("SBE_TX_MAX", sedit.TRANSITION_MAX),
+ ("SBE_TEXT_MAX", sedit.TEXT_MAX_CHARS)):
+ m = re.search(rf"^const {name} = ([0-9.]+);", src, re.M)
+ self.assertIsNotNone(m, name)
+ self.assertEqual(float(m.group(1)), float(val), name)
+
+
+if __name__ == "__main__":
+ unittest.main()
+
+
+class TheExportStillOpens(unittest.TestCase):
+ """The NLE export neither carries a title nor a transition yet, and it
+ must say nothing false: a retimed clip rides as in/out vs start/end, a
+ title (no path) is skipped, and nothing raises."""
+
+ def test_export_with_a_title_and_a_retimed_clip(self):
+ c = _clip("a", "/x/a.mp4", 0.0, 4.0, 0.0, speed=2.0)
+ c["film_end"] = 2.0
+ doc = sedit.normalise_edit(_doc([c], overlays=[
+ {"id": "o1", "kind": "text", "text": "FIN", "film_start": 0.5,
+ "film_end": 1.5}]))
+ probe = lambda p: {"w": 768, "h": 416, "duration": 10.0, "has_audio": True}
+ rows = sedit._nle_segments(doc["clips"], probe=probe)
+ self.assertEqual(rows[0]["speed"], 2.0)
+ self.assertEqual([rows[0]["start"], rows[0]["end"]], [0.0, 4.0])
+ self.assertEqual([rows[0]["film_start"], rows[0]["film_end"]], [0.0, 2.0])
+ with tempfile.TemporaryDirectory() as d, \
+ mock.patch.object(sedit.Path, "is_file", return_value=True), \
+ mock.patch.object(sedit, "_link_or_copy", return_value="link"):
+ res = sedit.export_nle(doc["clips"], d, name="v2", probe=probe,
+ overlays=sedit.overlay_items(doc))
+ self.assertTrue(res["ok"])
+ self.assertEqual(res["clips"], 1)
+ self.assertNotIn("FIN", Path(res["xml"]).read_text())
diff --git a/test_h3_turbo_adapter.py b/test_h3_turbo_adapter.py
index 15a7ec1..827da28 100644
--- a/test_h3_turbo_adapter.py
+++ b/test_h3_turbo_adapter.py
@@ -46,6 +46,28 @@ class TestH3TurboResolver(unittest.TestCase):
path.write_bytes(b"runner-layout fixture")
return path
+ def test_v4_600_ema_is_preferred_when_present_and_runs_six_forwards(self):
+ v4 = self.put(P.H3_TURBO_V4_FILE)
+ self.put(P.H3_TURBO_LORA_FILE)
+ self.put(P.H3_TURBO_CKPT500_FILE)
+ resolved = P.h3_turbo_paths()
+ self.assertEqual(resolved["lora"], v4)
+ self.assertEqual(resolved["version"], "v4-600-EMA")
+ self.assertFalse(resolved["fallback"])
+ self.assertEqual(P.h3_turbo_argv(resolved), ["--lora", f"{v4}:1.0"])
+ self.assertEqual(P.h3_turbo_steps(resolved), 7) # 6 forwards
+ self.assertEqual(P.h3_turbo_steps({"version": "v1.0"}), 4)
+ self.assertEqual(P.h3_turbo_steps({"version": "ckpt500-EMA"}), 4)
+
+ def test_the_managed_download_is_the_v4_adapter_from_its_author(self):
+ a = P._h3_turbo_asset()
+ self.assertEqual(a["file"], P.H3_TURBO_V4_FILE)
+ self.assertTrue(a["url"].startswith("https://huggingface.co/larryvrh/MiniMax-H3-Turbo-Lora/resolve/main/"))
+ self.assertEqual(a["sha256"], "5f3a626cd72c93a8b9318d6760c510bc5092d2ab13aaba1f932c5bab07a416d3")
+ self.assertEqual(a["bytes"], 779849816)
+ # the LightX2V release asset stays reachable by key
+ self.assertEqual(P._h3_turbo_asset("v1.0")["url"], P.H3_TURBO_ASSET_URL)
+
def test_v1_is_preferred_when_all_three_exist(self):
primary = self.put(P.H3_TURBO_LORA_FILE)
self.put(P.H3_TURBO_FALLBACK_LORA_FILE)
@@ -122,9 +144,9 @@ class TestH3TurboInstallContract(unittest.TestCase):
result = P._h3_install_turbo(logs.append, download_fn=fake_download)
self.assertTrue(result["ok"])
self.assertTrue(result["started"])
- self.assertEqual(result["asset"], P.H3_TURBO_ASSET_URL)
- self.assertEqual(result["sha256"], P.H3_TURBO_ASSET_SHA256)
- self.assertEqual(result["bytes"], P.H3_TURBO_ASSET_BYTES)
+ self.assertEqual(result["asset"], P._h3_turbo_asset()["url"])
+ self.assertEqual(result["sha256"], P._h3_turbo_asset()["sha256"])
+ self.assertEqual(result["bytes"], P._h3_turbo_asset()["bytes"])
self.assertTrue(started.wait(timeout=5))
self.assertEqual(calls, [self.target])
diff --git a/test_ltx_windows.py b/test_ltx_windows.py
new file mode 100644
index 0000000..dcf911e
--- /dev/null
+++ b/test_ltx_windows.py
@@ -0,0 +1,201 @@
+#!/usr/bin/env python3
+"""The sliding-window planner for LTX: geometry and the per-window prompt
+contract. Pure arithmetic, so a wrong stride is a red test and not a
+minute-long render that stutters at every seam."""
+from __future__ import annotations
+
+import math
+import unittest
+
+import ltx_windows as lw
+
+
+class TheGeometry(unittest.TestCase):
+ def test_one_pass_when_the_window_covers_it(self):
+ p = lw.plan_windows(121)
+ self.assertEqual(p["count"], 1)
+ self.assertEqual(p["delivered_frames"], 121)
+ self.assertEqual(p["windows"][0], {"index": 0, "start_frame": 0, "frames": 121,
+ "new_frames": 121, "kept_frames": 121,
+ "start_sec": 0.0, "end_sec": 5.0})
+
+ def test_the_formula(self):
+ # stride = window - discard - overlap = 121 - 0 - 9 = 112
+ # count = 1 + ceil((total - window + discard) / stride)
+ for total in (241, 481, 721, 1441):
+ p = lw.plan_windows(total)
+ self.assertEqual(p["stride"], 112)
+ self.assertEqual(p["count"], 1 + math.ceil((total - 121) / 112))
+ self.assertGreaterEqual(p["delivered_frames"], total)
+ self.assertEqual(p["delivered_frames"], 121 + (p["count"] - 1) * 112)
+ # every later window adds exactly one stride of NEW picture
+ for w in p["windows"][1:]:
+ self.assertEqual(w["new_frames"], 112)
+ # ...and re-sees the previous tail
+ self.assertEqual(p["windows"][1]["start_frame"], 121 - 9)
+
+ def test_discard_shortens_what_is_kept(self):
+ p = lw.plan_windows(481, discard=16)
+ self.assertEqual(p["stride"], 96)
+ self.assertEqual(p["windows"][1]["start_frame"], 121 - 16 - 9)
+ # a later window generates stride + discard and keeps stride
+ self.assertEqual(p["windows"][1]["new_frames"], 112)
+ self.assertEqual(p["windows"][1]["kept_frames"], 105 + 96)
+ self.assertEqual(p["delivered_frames"], 121 - 16 + (p["count"] - 1) * 96)
+ self.assertGreaterEqual(p["delivered_frames"], 481)
+
+ def test_the_latent_grid_is_kept_and_every_rounding_is_said(self):
+ p = lw.plan_windows(250, window=120, overlap=10, discard=5)
+ self.assertEqual(p["total_frames"], 249)
+ self.assertEqual(p["window"], 121)
+ self.assertEqual(p["overlap"], 9)
+ self.assertEqual(p["discard"], 0)
+ self.assertEqual(p["stride"] % 8, 0)
+ self.assertEqual(len(p["notes"]), 4)
+ self.assertEqual(lw.extend_latents(112), 14)
+
+ def test_nonsense_is_refused(self):
+ with self.assertRaises(ValueError):
+ lw.plan_windows(481, overlap=120)
+ with self.assertRaises(ValueError):
+ lw.plan_windows(24 * 60 * 10) # ten minutes
+
+ def test_a_minute(self):
+ p = lw.plan_windows(24 * 60 + 1)
+ self.assertEqual(p["count"], 13)
+ self.assertIn("13 window(s)", lw.describe(p))
+
+
+class ThePromptContract(unittest.TestCase):
+ def test_window_one_is_the_prompt_itself(self):
+ self.assertEqual(lw.window_prompts("A man walks in.", count=1),
+ ["A man walks in."])
+
+ def test_a_later_window_leads_with_its_own_line_then_the_invariants(self):
+ out = lw.window_prompts("A man walks in.", ["", "He sits down."],
+ invariants="one man, a grey room, soft window light",
+ count=3)
+ self.assertEqual(out[0], "A man walks in.")
+ self.assertTrue(out[1].startswith("He sits down. "))
+ self.assertIn(lw.CONTINUE, out[1])
+ self.assertTrue(out[1].endswith("Throughout: one man, a grey room, soft window light."))
+ # the third window has no line of its own: it HOLDS, it does not
+ # replay the shot
+ self.assertTrue(out[2].startswith(lw.HOLD))
+ self.assertNotIn("walks in", out[2])
+
+ def test_a_settle_is_what_a_blank_window_holds(self):
+ out = lw.window_prompts("She turns.", count=2, settle="she faces the window")
+ self.assertTrue(out[1].startswith("she faces the window, held."))
+
+ def test_the_first_line_may_override_the_base(self):
+ self.assertEqual(lw.window_prompts("base", ["own"], count=1), ["own"])
+
+
+if __name__ == "__main__":
+ unittest.main()
+
+
+# =============================================================================
+# THE PANEL: the allowlist, the refusals, and the chain
+# =============================================================================
+import sys as _sys # noqa: E402
+from pathlib import Path as _Path # noqa: E402
+from unittest import mock as _mock # noqa: E402
+
+_sys.path.insert(0, str(_Path(__file__).resolve().parent))
+import mlx_ltx_panel as panel # noqa: E402
+
+
+class ThePanel(unittest.TestCase):
+ def test_make_job_carries_the_windows_fields(self):
+ job = panel.make_job({"mode": "t2v", "prompt": "a man walks",
+ "frames": "481", "temporal_mode": "windows",
+ "window_prompts": '["", "he sits", ""]',
+ "window_invariants": "one man, grey room"})
+ p = job["params"]
+ self.assertEqual(p["long_mode"], "windows")
+ self.assertEqual(p["temporal_mode"], "native")
+ self.assertEqual(p["window_prompts"], ["", "he sits", ""])
+ self.assertEqual(p["window_invariants"], "one man, grey room")
+ # a plain render carries the neutral values, not an absence
+ q = panel.make_job({"mode": "t2v", "prompt": "x"})["params"]
+ self.assertEqual(q["long_mode"], "native")
+ self.assertEqual(q["window_prompts"], [])
+ # newline-separated is accepted too
+ r = panel.make_job({"mode": "t2v", "prompt": "x", "temporal_mode": "windows",
+ "window_prompts": "a\nb"})["params"]
+ self.assertEqual(r["window_prompts"], ["a", "b"])
+
+ def test_the_chain_extends_on_the_kept_tail_and_trims_to_length(self):
+ plan = lw.plan_windows(241)
+ calls, ffm = [], []
+
+ def fake_run(spec):
+ calls.append(spec)
+ _Path(spec["params"]["output_path"]).write_bytes(b"x")
+ return {"elapsed_sec": 1}
+
+ def fake_ffmpeg(cmd, label):
+ ffm.append((label, cmd))
+ _Path(cmd[-1]).write_bytes(b"y")
+ import tempfile
+ with tempfile.TemporaryDirectory() as d:
+ first = _Path(d) / "clip_w0.mp4"
+ first.write_bytes(b"w0")
+ raw = _Path(d) / "clip.mp4"
+ with _mock.patch.object(panel.HELPER, "run", side_effect=fake_run), \
+ _mock.patch.object(panel, "run_ffmpeg_tracked", side_effect=fake_ffmpeg), \
+ _mock.patch.object(panel, "set_hidden") as hidden, \
+ _mock.patch.object(panel, "pack_path", return_value=_Path("/q8")), \
+ _mock.patch.object(panel, "hq_weights",
+ return_value={"dev_transformer": "dev.safetensors"}):
+ out = panel._run_windows_chain(
+ {"id": "j1"}, {"prompt": "A man walks in.", "seed": 7,
+ "window_prompts": ["", "He sits."],
+ "window_invariants": "grey room"},
+ plan, first, raw, 241)
+ # 241 frames = 3 windows: two extends on top of the first pass
+ self.assertEqual(len(calls), 2)
+ spec = calls[0]
+ self.assertEqual(spec["action"], "extend")
+ # the extend sees the TAIL of the previous output, never the whole
+ # clip — that is what keeps every window the same price
+ self.assertTrue(spec["params"]["video_path"].endswith("_w0t.mp4"))
+ tail0 = [c for l, c in ffm if l == "Windows: tail 0"][0]
+ self.assertIn("select='between(n\\,0\\,120)',setpts=N/FRAME_RATE/TB", tail0)
+ self.assertEqual(spec["params"]["extend_frames"], 14) # 112 / 8
+ self.assertEqual(spec["params"]["seed"], 8)
+ self.assertTrue(spec["params"]["prompt"].startswith("He sits. "))
+ self.assertIn("Throughout: grey room.", spec["params"]["prompt"])
+ # the third window has no line: it holds, on the second's output
+ self.assertTrue(calls[1]["params"]["prompt"].startswith(lw.HOLD))
+ self.assertTrue(calls[1]["params"]["video_path"].endswith("_w1t.mp4"))
+ # window 2's output is 121 + 112 frames; its tail is the last 121
+ tail1 = [c for l, c in ffm if l == "Windows: tail 1"][0]
+ self.assertIn("select='between(n\\,112\\,232)',setpts=N/FRAME_RATE/TB", tail1)
+ # and only the 112 new frames of each window go into the join
+ piece1 = [c for l, c in ffm if l == "Windows: piece 1"][0]
+ self.assertIn("select='gte(n\\,121)',setpts=N/FRAME_RATE/TB", piece1)
+ self.assertEqual(spec["params"]["model_dir"], "/q8")
+ # the final trim lands on raw_out at the asked length
+ self.assertEqual(ffm[-1][0], "Windows: final join")
+ self.assertEqual(ffm[-1][1][-1], str(raw))
+ self.assertIn(f"{241 / 24:.6f}", ffm[-1][1])
+ self.assertEqual(out["output_frames"], 241)
+ self.assertEqual(len(out["files"]), 3)
+ self.assertEqual(len(out["pieces"]), 3) # w0 + two new-frame pieces
+ hidden_paths = {c.args[0] for c in hidden.call_args_list}
+ for f in out["files"]:
+ self.assertIn(f, hidden_paths) # every window output hidden
+
+ def test_the_refusals_name_the_reason(self):
+ job = panel.make_job({"mode": "t2v", "prompt": "x", "frames": "481",
+ "temporal_mode": "windows"})
+ with _mock.patch.dict(panel.SYSTEM_CAPS, {"allows_extend": False, "label": "Compact"}), \
+ _mock.patch.object(panel.HELPER, "run") as run, \
+ _mock.patch.object(panel, "_apply_generation_profile_to_job"):
+ with self.assertRaises(panel.RenderRefused) as cm:
+ panel.run_job_inner(job)
+ self.assertIn("Sliding windows", str(cm.exception))
+ run.assert_not_called()
diff --git a/test_outputs_search.py b/test_outputs_search.py
new file mode 100644
index 0000000..cf69bdc
--- /dev/null
+++ b/test_outputs_search.py
@@ -0,0 +1,62 @@
+#!/usr/bin/env python3
+"""Gallery search: every output row carries `q`, the searchable words of its
+sidecar, built in the loop that already reads it."""
+from __future__ import annotations
+
+import json
+import sys
+import tempfile
+import time
+import unittest
+from pathlib import Path
+from unittest import mock
+
+ROOT = Path(__file__).resolve().parent
+sys.path.insert(0, str(ROOT))
+
+import mlx_ltx_panel as panel # noqa: E402
+
+
+class TheWords(unittest.TestCase):
+ def test_prompt_mode_size_loras_and_character(self):
+ q = panel._output_search_text(
+ {"engine": "ltx", "model": "/m/ltx-2.5-mlx-q8", "temporal": {"mode": "fps12_interp24"}},
+ {"prompt": "A woman turns to the window", "mode": "i2v", "quality": "balanced",
+ "width": 1280, "height": 704, "frames": 121, "seed_used": 4242,
+ "character_id": "ariatrn",
+ "loras": [{"path": "/l/Crisp_Enhance.safetensors", "strength": 0.8}, "/l/hdr.safetensors"]})
+ for w in ("a woman turns", "i2v", "balanced", "1280x704", "121f", "4242",
+ "ariatrn", "crisp_enhance", "hdr", "ltx-2.5-mlx-q8", "fps12_interp24"):
+ self.assertIn(w, q, w)
+ self.assertEqual(panel._output_search_text({}, {}), "")
+ self.assertEqual(panel._output_search_text({"bad": object()}, {"prompt": None}), "")
+
+ def test_list_outputs_carries_q(self):
+ with tempfile.TemporaryDirectory() as d:
+ out = Path(d)
+ clip = out / "clip.mp4"
+ clip.write_bytes(b"x")
+ (out / "clip.mp4.json").write_text(json.dumps(
+ {"params": {"prompt": "the grinning man", "mode": "t2v", "width": 768,
+ "height": 416}, "engine": "ltx"}))
+ plain = out / "plain.mp4"
+ plain.write_bytes(b"y")
+ # The gallery skips files ffmpeg may still be writing (a 2 s
+ # mtime cutoff), so these are aged before they are listed.
+ import os
+ old = time.time() - 30
+ for f in (clip, plain):
+ os.utime(f, (old, old))
+ lib = out / "lib"
+ lib.mkdir()
+ with mock.patch.object(panel, "OUTPUT", out), \
+ mock.patch.object(panel, "UPLOADS", lib):
+ rows = panel.list_outputs(limit=0)
+ by = {r["name"]: r for r in rows}
+ self.assertIn("the grinning man", by["clip.mp4"]["q"])
+ self.assertIn("768x416", by["clip.mp4"]["q"])
+ self.assertEqual(by["plain.mp4"]["q"], "")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/test_retake.py b/test_retake.py
new file mode 100644
index 0000000..72b1255
--- /dev/null
+++ b/test_retake.py
@@ -0,0 +1,122 @@
+#!/usr/bin/env python3
+"""Retake — send a timeline clip back through the renderer and get the new
+take offered against it, in place.
+
+Locked: a retake CLONES the clip's own shot (character, refs, engine) and
+changes only the prompt, the length and the seed; a finished retake shows up
+in the relink rows FLAGGED, is never part of the batch drafts→finals rewrite,
+and is adopted one clip at a time by id; the pool carries the shot's full
+prompt so the retake can start from it.
+"""
+from __future__ import annotations
+
+import json
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+from unittest import mock
+
+ROOT = Path(__file__).resolve().parent
+sys.path.insert(0, str(ROOT))
+
+import mlx_ltx_panel as panel # noqa: E402
+import storyboard # noqa: E402
+import storyboard_editor as sedit # noqa: E402
+from test_storyboard_editor_api import FakeHandler, _board, _edit, _clip # noqa: E402
+
+
+class TheRetake(unittest.TestCase):
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.root = Path(self.tmp.name)
+ self.clipfile = self.root / "shot1.mp4"
+ self.clipfile.write_bytes(b"x")
+ self.newfile = self.root / "shot1_take2.mp4"
+ self.board = _board([self.clipfile])
+ self.board["shots"][0].update({"character_id": "bizarrotrn", "trigger": "bizarrotrn",
+ "mode": "character", "location": "the study",
+ "refs": ["/x/ref.png"]})
+ c = _clip(str(self.clipfile), 0.0, 4.0, 0.0, id="c1")
+ self.edit = sedit.normalise_edit(_edit([c]))
+ self.patches = [
+ mock.patch.object(panel, "STATE_DIR", self.root),
+ mock.patch.object(panel, "_sbe_board_dir", return_value=self.root / "sb_t"),
+ mock.patch.object(storyboard, "load_storyboard", return_value=self.board),
+ mock.patch.object(storyboard, "save_storyboard"),
+ mock.patch.object(panel, "_sb_enqueue", return_value="j-take"),
+ ]
+ for p in self.patches:
+ p.start()
+ (self.root / "sb_t").mkdir()
+ sedit.save_edit(self.root / "sb_t", self.edit)
+
+ def tearDown(self):
+ for p in self.patches:
+ p.stop()
+ self.tmp.cleanup()
+
+ def test_the_pool_carries_the_prompt(self):
+ rows = panel._sbe_board_clips(self.board)
+ self.assertEqual(rows[0]["prompt"], "shot 1 happens")
+ self.assertEqual(rows[0]["character_id"], "bizarrotrn")
+
+ def test_generate_with_retake_of_clones_the_shot(self):
+ h = FakeHandler()
+ with mock.patch.object(panel, "_sb_known_character_ids", return_value=["bizarrotrn"]), \
+ mock.patch.object(panel, "_sb_h3_available", return_value=False), \
+ mock.patch.object(storyboard, "shot_to_job", return_value={"mode": "t2v", "prompt": "p"}) as stj:
+ h.post("edit/generate", {"id": "sb_t", "prompt": "he turns, slower",
+ "duration": "4", "film_start": "0",
+ "retake_of": "c1"})
+ self.assertEqual(h.status, 202, h.payload) # queued, like any shot
+ new = self.board["shots"][-1]
+ self.assertEqual(new["n"], 2)
+ # the trigger is prepended by the board's own normaliser, as for
+ # every character shot
+ self.assertIn("he turns, slower", new["prompt"])
+ self.assertEqual(new["character_id"], "bizarrotrn")
+ self.assertEqual(new["location"], "the study")
+ self.assertEqual(new["refs"], ["/x/ref.png"])
+ self.assertEqual(new["status"], "queued")
+ self.assertEqual(new["edit_slot"]["retake_of"], "c1")
+ self.assertNotIn("draft_output", new)
+ stj.assert_called_once()
+
+ def test_a_retake_of_a_clip_that_left_is_refused(self):
+ h = FakeHandler()
+ h.post("edit/generate", {"id": "sb_t", "prompt": "x", "retake_of": "zz"})
+ self.assertEqual(h.status, 400)
+ self.assertIn("not on this timeline", h.payload["error"])
+
+ def test_a_finished_retake_is_offered_flagged_and_adopted_by_id(self):
+ self.newfile.write_bytes(b"y")
+ self.board["shots"].append({"n": 2, "title": "take 2", "prompt": "p2",
+ "status": "done", "draft_output": str(self.newfile),
+ "edit_slot": {"film_start": 0.0, "duration": 4.0,
+ "retake_of": "c1"}})
+ rows = panel._sbe_relinks(self.board, self.edit)
+ self.assertEqual(len(rows), 1)
+ self.assertTrue(rows[0]["retake"])
+ self.assertEqual([rows[0]["id"], rows[0]["to"]], ["c1", str(self.newfile)])
+ # the batch relink leaves the retake alone…
+ h = FakeHandler()
+ with mock.patch.object(panel, "_sbe_proxy_now"):
+ h.post("edit/relink", {"id": "sb_t"})
+ self.assertEqual(h.status, 200)
+ self.assertEqual(sedit.load_edit(self.root / "sb_t")["clips"][0]["path"], str(self.clipfile))
+ # …and `only` adopts it for that clip alone
+ h = FakeHandler()
+ with mock.patch.object(panel, "_sbe_proxy_now"):
+ h.post("edit/relink", {"id": "sb_t", "only": "c1"})
+ self.assertEqual(h.status, 200, h.payload)
+ got = sedit.load_edit(self.root / "sb_t")["clips"][0]
+ self.assertEqual(got["path"], str(self.newfile))
+ self.assertEqual([got["start"], got["end"]], [0.0, 4.0])
+ self.assertEqual(h.payload.get("relinked"), 1)
+ # adopted, so no longer offered
+ self.assertEqual(panel._sbe_relinks(self.board, sedit.load_edit(self.root / "sb_t")), [])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/test_song_map.py b/test_song_map.py
new file mode 100644
index 0000000..caaa10a
--- /dev/null
+++ b/test_song_map.py
@@ -0,0 +1,116 @@
+#!/usr/bin/env python3
+"""The song map: sections and energy on the bar grid, and the pacing rule
+the Director derives from them. A synthesised track — a quiet intro, a loud
+bright chorus, a quiet outro at 120 bpm — so the labels can be asserted
+rather than eyeballed."""
+from __future__ import annotations
+
+import math
+import tempfile
+import unittest
+import wave
+from pathlib import Path
+
+import numpy as np
+
+import storyboard_edit as se
+
+SR = 22050
+BPM = 120.0
+BAR = 60.0 / BPM * 4 # 2.0 s
+
+
+def _track(path: Path, bars=(("q", 8), ("loud", 8), ("q", 8))) -> float:
+ """Kick on every beat so beat_map finds the grid; a bright loud pad in the
+ loud bars, a faint dull one elsewhere."""
+ total = sum(n for _, n in bars) * BAR
+ t = np.arange(int(total * SR)) / SR
+ y = np.zeros_like(t, dtype=np.float32)
+ # the kick: a 60 Hz thump decaying over 120 ms, every beat
+ beat = 60.0 / BPM
+ for k in range(int(total / beat)):
+ i0 = int(k * beat * SR)
+ n = int(0.12 * SR)
+ tt = np.arange(n) / SR
+ y[i0:i0 + n] += (0.35 * np.sin(2 * math.pi * 60 * tt) * np.exp(-tt * 30)).astype(np.float32)
+ cursor = 0.0
+ for kind, n in bars:
+ a, b = int(cursor * SR), int((cursor + n * BAR) * SR)
+ tt = t[a:b]
+ if kind == "loud":
+ y[a:b] += (0.35 * np.sin(2 * math.pi * 440 * tt)
+ + 0.25 * np.sin(2 * math.pi * 3520 * tt)).astype(np.float32)
+ else:
+ y[a:b] += (0.04 * np.sin(2 * math.pi * 110 * tt)).astype(np.float32)
+ cursor += n * BAR
+ y = np.clip(y, -1, 1)
+ with wave.open(str(path), "wb") as w:
+ w.setnchannels(1)
+ w.setsampwidth(2)
+ w.setframerate(SR)
+ w.writeframes((y * 32767).astype("<i2").tobytes())
+ return total
+
+
+class TheSongMap(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.tmp = tempfile.TemporaryDirectory()
+ cls.path = Path(cls.tmp.name) / "t.wav"
+ cls.total = _track(cls.path)
+ cls.map = se.song_map(str(cls.path))
+
+ @classmethod
+ def tearDownClass(cls):
+ cls.tmp.cleanup()
+
+ def test_bars_sit_on_downbeats_and_carry_energy(self):
+ m = self.map
+ self.assertGreaterEqual(len(m["bars"]), 20)
+ self.assertLessEqual(len(m["bars"]), 26)
+ for a, b in zip(m["bars"], m["bars"][1:]):
+ self.assertAlmostEqual(b["start"], a["end"], places=6)
+ self.assertAlmostEqual(b["start"] - a["start"], BAR, delta=0.15)
+ e = [x["energy"] for x in m["bars"]]
+ self.assertGreater(max(e), 0.9)
+ self.assertLess(min(e), 0.3)
+
+ def test_three_sections_labelled_by_position_and_energy(self):
+ secs = self.map["sections"]
+ self.assertEqual([s["label"] for s in secs], ["intro", "chorus", "outro"])
+ # the boundaries are bar edges, close to 16 s and 32 s
+ self.assertAlmostEqual(secs[1]["start"], 8 * BAR, delta=BAR)
+ self.assertAlmostEqual(secs[2]["start"], 16 * BAR, delta=BAR)
+ self.assertGreater(secs[1]["energy"], secs[0]["energy"] * 3)
+ self.assertEqual(secs[0]["bars"][0], 0)
+ self.assertEqual(secs[-1]["bars"][1], len(self.map["bars"]))
+
+ def test_a_beat_map_is_reused_when_given(self):
+ beats = se.beat_map(str(self.path))
+ m2 = se.song_map(str(self.path), beats)
+ self.assertEqual([s["label"] for s in m2["sections"]],
+ [s["label"] for s in self.map["sections"]])
+
+ def test_a_jingle_is_one_section_never_an_error(self):
+ with tempfile.TemporaryDirectory() as d:
+ p = Path(d) / "j.wav"
+ _track(p, bars=(("loud", 5),))
+ m = se.song_map(str(p))
+ self.assertEqual(len(m["sections"]), 1)
+ self.assertIn(m["sections"][0]["label"], se.SECTION_LABELS)
+
+
+class ThePacingRule(unittest.TestCase):
+ def test_chorus_cuts_twice_as_often_and_the_ends_half_as_often(self):
+ self.assertEqual(se.director_pacing("chorus", 0.9, 0.5, 2), 1)
+ self.assertEqual(se.director_pacing("chorus", 0.9, 0.5, 1), 1)
+ self.assertEqual(se.director_pacing("intro", 0.1, 0.5, 2), 4)
+ self.assertEqual(se.director_pacing("outro", 0.1, 0.5, 2), 4)
+ self.assertEqual(se.director_pacing("bridge", 0.3, 0.5, 2), 2)
+ self.assertEqual(se.director_pacing("verse", 0.5, 0.5, 2), 2)
+ # an unlabelled hot section cuts like a chorus
+ self.assertEqual(se.director_pacing("", 0.9, 0.5, 4), 2)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/test_storyboard_editor_ui.py b/test_storyboard_editor_ui.py
index 44ddd9f..e08f332 100644
--- a/test_storyboard_editor_ui.py
+++ b/test_storyboard_editor_ui.py
@@ -131,6 +131,13 @@ FUNCTIONS = (
"sbeBedDeleteKeyframe",
"sbeOvKind", "sbeOvAt", "sbeOvById", "sbeOvFits", "sbeOvMove", "sbeOvTrim",
"sbeOvAdd", "sbeOvDelete", "sbeOvSetPath",
+ # Editor v2 — speed on the clip, titles on the lane, transitions on the
+ # cut. Every one is a mirror of a Python function of the same name-shape
+ # and `test_editor_v2.py` runs the two side by side.
+ "sbeSpeed", "sbeSetSpeed", "sbeOvText", "sbeHexColour", "sbeRgba",
+ "sbeOvTextPlace", "sbeDuplicate", "sbeFraming", "sbeFramingIsNeutral", "sbeSetFraming",
+ "sbeTxById", "sbeTxAfter", "sbeTxDuration", "sbeTxSpare", "sbeTxResolve",
+ "sbeTxEdges", "sbeTxSet", "sbeTxDelete", "sbeTxPrune", "sbeTxRepoint",
"sbeAudioDrift", "sbeAudioInSync", "sbeAudioIsThePicture",
"sbeDriftLabel", "sbeSyncBadge",
"sbeSyncMark", "sbeSyncCarry", "sbeResyncAudio",
@@ -181,6 +188,19 @@ const SBE_SNAP_PX = 9;
const SBE_GUESS_CONFIDENCE = 0.4;
const SBE_BRIGHT_MAX = 0.5;
const SBE_STILL_SECONDS = 3.0;
+// Editor v2. Keep equal to the panel's — test_editor_v2 reads both.
+const SBE_SPEED_MIN = 0.25;
+const SBE_SPEED_MAX = 4.0;
+const SBE_TX_KINDS = ['dissolve', 'fade_black'];
+const SBE_TX_MIN = 1 / 24;
+const SBE_TX_MAX = 2.0;
+const SBE_TX_LABELS = { dissolve: 'Dissolve', fade_black: 'Fade through black' };
+const SBE_TEXT_DEFAULTS = { font_size: 64, color: '#ffffff', align: 'center',
+ x: 0.5, y: 0.5, box: false, box_color: '#000000',
+ box_opacity: 0.5 };
+const SBE_TEXT_REF_H = 1080;
+const SBE_TEXT_MAX = 400;
+const SBE_FRAME_ZOOM_MAX = 3.0;
// Wave 3. Keep these equal to the panel's — a drifted constant here is a gate
// that passes while the browser does something else.
const SBE_TL_PAD = 24;
@@ -388,11 +408,19 @@ out.clipInHole = sbeClipAt(holed, 3);
// ---- move ----------------------------------------------------------------
cs = lay([clip({ id: 'a', end: 2 }), clip({ id: 'b', end: 3 }), clip({ id: 'c', end: 1.5 })]);
-let r = sbeMoveTo(cs, 'c', 0);
+let r = sbeMoveTo(cs, 'c', 0, { ripple: true }); // ⌘: the old free repack
out.moveToHead = shape(r.clips);
out.moveMarksHuman = sbeById(r.clips, 'c').source;
out.moveLengths = lengthsAgree(r.clips);
out.moveNoOverlap = !overlaps(r.clips);
+// DEFAULT (no modifier): a clip moves only between its neighbours and they
+// stay where they are — the Premiere / After Effects contract.
+cs = lay([clip({ id: 'a', end: 2 }), clip({ id: 'b', end: 3 }), clip({ id: 'c', end: 1.5 })]);
+r = sbeMoveTo(cs, 'c', 0);
+out.moveClamped = shape(r.clips); // cannot pass b: stays at 5
+cs = lay([clip({ id: 'a', end: 2 }), clip({ id: 'b', end: 3, film_start: 4, film_end: 7 }), clip({ id: 'c', end: 1 })]);
+r = sbeMoveTo(cs, 'b', 3); // slides back into its own hole
+out.moveKeepsNeighbours = shape(r.clips);
cs = lay([clip({ id: 'a', end: 2 }), clip({ id: 'b', end: 3 })]);
r = sbeMoveTo(cs, 'b', 6); // dropped into open air: the hole is kept
@@ -410,9 +438,17 @@ out.anchoredNoOverlap = !overlaps(cs);
// ---- trim ----------------------------------------------------------------
cs = lay([clip({ id: 'a', end: 2 }), clip({ id: 'b', end: 3 })]);
-sbeTrim(cs, 'a', 'r', 1.25); // right handle: length changes, tail ripples
+sbeTrim(cs, 'a', 'r', 1.25, { ripple: true }); // ⌘: length changes, tail ripples
out.trimRight = shape(cs);
out.trimRightLengths = lengthsAgree(cs);
+// DEFAULT: the right handle opens a hole; the next clip does not move.
+cs = lay([clip({ id: 'a', end: 2 }), clip({ id: 'b', end: 3 })]);
+sbeTrim(cs, 'a', 'r', 1.25);
+out.trimRightHole = shape(cs);
+out.trimRightHoleLengths = lengthsAgree(cs);
+// ...and it may grow back into that hole but never into the neighbour.
+sbeTrim(cs, 'a', 'r', 5);
+out.trimRightStopsAtNext = shape(cs);
cs = lay([clip({ id: 'a', end: 2 }), clip({ id: 'b', end: 3 })]);
sbeTrim(cs, 'b', 'l', 2.5); // left handle: in-point moves, tail stays put
@@ -633,7 +669,7 @@ out.insertStill = { kind: r.added.kind, path: r.added.path, dur: r.added.duratio
// A still is resized by the SAME trim machinery every other block uses, and
// nothing clamps it, because it has no source clock to run out of.
cs = lay([r.added, clip({ id: 'a', end: 2 })]);
-sbeTrim(cs, r.added.id, 'r', 9);
+sbeTrim(cs, r.added.id, 'r', 9, { ripple: true }); // ⌘: grow past the neighbour, which slides
out.stillStretched = sbeRound(sbeLen(sbeById(cs, r.added.id)));
// ---- reorder: closes the hole it leaves, opens none where it lands -------
@@ -653,7 +689,7 @@ out.reorderGone = sbeReorderTo(cs, 'nope', 0).why;
// this is the difference between them.
cs = lay([clip({ id: 'a', end: 2 }), clip({ id: 'b', end: 2 }),
clip({ id: 'c', end: 2 })]);
-out.moveLeavesAHole = sbeMoveTo(cs, 'a', 9).clips.map(c => [c.id, c.film_start]);
+out.moveLeavesAHole = sbeMoveTo(cs, 'a', 9, { ripple: true }).clips.map(c => [c.id, c.film_start]);
// ---- WAVE 3: the two sliders ---------------------------------------------
// The owner's film, measured: 71.583338s in a 1108px-wide scroller.
@@ -1223,7 +1259,7 @@ out.dragCannotOpenASubFrameHole = (() => {
// ...but a hole somebody can SEE survives a drag untouched.
out.dragKeepsAGapYouCanSee = (() => {
const cs = lay(HOLED());
- const r = sbeMoveTo(cs, 'b', 6.5);
+ const r = sbeMoveTo(cs, 'b', 6.5, { ripple: true }); // ⌘: c and d slide, the hole stays
return [sbeById(r.clips, 'b').film_start, sbeHoles(r.clips).length];
})();
// THE HEAL CARRIES THE SOUND. Closing a hole is not the user sliding a
@@ -1598,21 +1634,21 @@ out.pairTrimHead = (() => {
// silently coming apart, three shots away from the handle being dragged.
out.pairTrimTailRipples = (() => {
const cs = unlink(PAIR(), ['c']);
- sbeTrim(cs, 'a', 'r', 3);
+ sbeTrim(cs, 'a', 'r', 3, { ripple: true }); // ⌘: the tail slides
return [aState(cs, 'a'), aState(cs, 'c')];
})();
// 4. MOVING THE PICTURE BY HAND. The one gesture whose whole point is to leave
// the sound behind — and the clip NEXT to it still rides along.
out.pairMove = (() => {
- const cs = sbeMoveTo(unlink(PAIR(), ['b', 'c']), 'b', 6).clips;
+ const cs = sbeMoveTo(unlink(PAIR(), ['b', 'c']), 'b', 6, { ripple: true }).clips;
return [aState(cs, 'b'), aState(cs, 'c')];
})();
// 5. THE REMATCH. One call puts the strip back under the frame it came from,
// and leaves it unlinked so it can be moved again.
out.pairResync = (() => {
- const cs = sbeMoveTo(unlink(PAIR(), ['b']), 'b', 6).clips;
+ const cs = sbeMoveTo(unlink(PAIR(), ['b']), 'b', 6, { ripple: true }).clips;
const r = sbeResyncAudio(cs, 'b');
return [r.ok, aState(r.clips, 'b')];
})();
@@ -1621,7 +1657,7 @@ out.pairResync = (() => {
out.pairResyncKeepsTheTrim = (() => {
let cs = unlink(PAIR(), ['a']);
cs = sbeAudioEdit(cs, 'a', 'trimL', 1).clips; // in-point 1 s into the take
- cs = sbeMoveTo(cs, 'a', 5).clips;
+ cs = sbeMoveTo(cs, 'a', 5, { ripple: true }).clips;
const r = sbeResyncAudio(cs, 'a');
return [r.ok, aState(r.clips, 'a')];
})();
@@ -1644,7 +1680,7 @@ out.pairSplit = (() => {
// A split of a DRIFTED pair keeps the drift on both halves — the cut is
// expressed in the source clock the two halves share.
out.pairSplitKeepsTheDrift = (() => {
- const cs = sbeMoveTo(unlink(PAIR(), ['b']), 'b', 6).clips;
+ const cs = sbeMoveTo(unlink(PAIR(), ['b']), 'b', 6, { ripple: true }).clips;
const r = sbeSplitAt(cs, 8, 'b2');
return [r.ok, aState(r.clips, 'b').drift, aState(r.clips, 'b2').drift,
aState(r.clips, 'b').snd, aState(r.clips, 'b2').snd];
@@ -1670,7 +1706,7 @@ out.pairRippleDelete = (() => {
// said "link" destroyed the J-cut the moment it was made — which is why the
// owner reached for LOCK, and why the clip then refused every drag.
out.pairRelinkFreezesTheOffset = (() => {
- let cs = sbeMoveTo(unlink(PAIR(), ['b']), 'b', 6).clips;
+ let cs = sbeMoveTo(unlink(PAIR(), ['b']), 'b', 6, { ripple: true }).clips;
cs = sbeSetAudioLink(cs, 'b', true).clips;
return [aState(cs, 'b'), sbeById(cs, 'b').audio.linked === true];
})();
@@ -1684,9 +1720,9 @@ out.pairRelinkInSyncRemovesTheField = (() => {
// A COUPLED pair travels together: the gesture that moves the picture moves
// the sound, offset intact. This is the "lock it and move it" he described.
out.pairCoupledTravels = (() => {
- let cs = sbeMoveTo(unlink(PAIR(), ['b']), 'b', 6).clips; // -2 s J-cut
+ let cs = sbeMoveTo(unlink(PAIR(), ['b']), 'b', 6, { ripple: true }).clips; // -2 s J-cut
cs = sbeSetAudioLink(cs, 'b', true).clips; // freeze it
- cs = sbeMoveTo(cs, 'b', 10).clips; // now move the pair
+ cs = sbeMoveTo(cs, 'b', 10, { ripple: true }).clips; // now move the pair (⌘: past c)
const s = aState(cs, 'b');
const t = sbeTrim(cs, 'b', 'r', sbeById(cs, 'b').film_end - 1);
return [s, aState(cs, 'b').drift, t.ok];
@@ -1694,7 +1730,7 @@ out.pairCoupledTravels = (() => {
// ...and it cannot be dragged on its own any more, which is what "linked"
// has always meant.
out.pairCoupledStripRefusesTheDrag = (() => {
- let cs = sbeMoveTo(unlink(PAIR(), ['b']), 'b', 6).clips;
+ let cs = sbeMoveTo(unlink(PAIR(), ['b']), 'b', 6, { ripple: true }).clips;
cs = sbeSetAudioLink(cs, 'b', true).clips;
const q = sbeAudioEdit(cs, 'b', 'move', 2);
return [q.ok, q.why];
@@ -1711,7 +1747,7 @@ out.pairToggleRoundTrip = (() => {
seen.push(aState(cs, 'b').drift);
cs = sbeSetAudioLink(cs, 'b', true).clips; // "lock" it
seen.push([aState(cs, 'b').drift, aState(cs, 'b').coupled]);
- cs = sbeMoveTo(cs, 'b', 9).clips; // move the pair
+ cs = sbeMoveTo(cs, 'b', 9, { ripple: true }).clips; // move the pair (⌘: past c)
seen.push([aState(cs, 'b').drift, aState(cs, 'b').snd]);
const t2 = sbeTrim(cs, 'b', 'l', 9.5); // head, coupled
seen.push([t2.ok, aState(cs, 'b').drift]);
@@ -1734,7 +1770,7 @@ out.pairHisScenario = (() => {
const afterTrim = aState(cs, 'b'); // picture 5-8, sound 4-8
cs = sbeSetAudioLink(cs, 'b', true).clips; // "lock" the two together
const frozen = aState(cs, 'b');
- cs = sbeMoveTo(cs, 'b', 4).clips; // move all together, gap closed
+ cs = sbeMoveTo(cs, 'b', 4, { ripple: true }).clips; // move all together, gap closed (⌘)
const moved = aState(cs, 'b');
return {
trimOpensTheGap: [afterTrim.vid, afterTrim.snd, afterTrim.drift],
@@ -1749,7 +1785,7 @@ out.pairHisScenario = (() => {
// A COUPLED pair is not a drift and is never flagged — its offset is the
// relationship the user froze.
out.pairCoupledIsNotFlagged = (() => {
- let cs = sbeMoveTo(unlink(PAIR(), ['b']), 'b', 6).clips;
+ let cs = sbeMoveTo(unlink(PAIR(), ['b']), 'b', 6, { ripple: true }).clips;
const free = sbeSyncBadge(sbeById(cs, 'b')).length > 0;
cs = sbeSetAudioLink(cs, 'b', true).clips;
return [free, sbeSyncBadge(sbeById(cs, 'b')).length > 0,
@@ -1758,14 +1794,14 @@ out.pairCoupledIsNotFlagged = (() => {
// ...but Resync still reaches it, and a rematched couple has nothing left to
// say, so the field goes.
out.pairResyncACouple = (() => {
- let cs = sbeMoveTo(unlink(PAIR(), ['b']), 'b', 6).clips;
+ let cs = sbeMoveTo(unlink(PAIR(), ['b']), 'b', 6, { ripple: true }).clips;
cs = sbeSetAudioLink(cs, 'b', true).clips;
const r = sbeResyncAudio(cs, 'b');
return [r.ok, sbeById(r.clips, 'b').audio === undefined, aState(r.clips, 'b')];
})();
// A COUPLED pair splits into two coupled pairs.
out.pairSplitACouple = (() => {
- let cs = sbeMoveTo(unlink(PAIR(), ['b']), 'b', 6).clips;
+ let cs = sbeMoveTo(unlink(PAIR(), ['b']), 'b', 6, { ripple: true }).clips;
cs = sbeSetAudioLink(cs, 'b', true).clips;
const r = sbeSplitAt(cs, 8, 'b2');
return [r.ok, aState(r.clips, 'b'), aState(r.clips, 'b2')];
@@ -1800,7 +1836,7 @@ out.pairHeadTrimAgainstANeighbour = (() => {
// 10. THE FLAG'S ARITHMETIC. Positive is LATE, the tolerance is half a frame,
// and the label is what both halves print.
out.pairDriftSigns = (() => {
- const early = sbeMoveTo(unlink(PAIR(), ['b']), 'b', 6).clips; // sound early
+ const early = sbeMoveTo(unlink(PAIR(), ['b']), 'b', 6, { ripple: true }).clips; // sound early
const late = sbeAudioEdit(unlink(PAIR(), ['b']), 'b', 'move', 6).clips;
return [sbeAudioDrift(sbeById(early, 'b')), sbeAudioDrift(sbeById(late, 'b')),
sbeDriftLabel(sbeAudioDrift(sbeById(early, 'b'))),
@@ -1818,7 +1854,7 @@ out.pairInSyncTolerance = (() => {
// and writing one would unlink it behind the user's back.
out.pairCarryLeavesLinkedAlone = (() => {
const cs = PAIR();
- sbeTrim(cs, 'a', 'r', 3);
+ sbeTrim(cs, 'a', 'r', 3, { ripple: true }); // ⌘: the tail slides
return [sbeById(cs, 'c').audio === undefined, aState(cs, 'c').drift];
})();
@@ -2229,13 +2265,21 @@ class TimelineClient(unittest.TestCase):
self.assertIsNone(self.r["clipInHole"])
# ---- move ------------------------------------------------------------
- def test_a_move_reorders_and_everything_after_it_slides(self):
+ def test_a_ripple_move_reorders_and_everything_after_it_slides(self):
self.assertEqual(self.r["moveToHead"],
[["c", 0, 1.5, 0, 1.5], ["a", 0, 2, 1.5, 3.5],
["b", 0, 3, 3.5, 6.5]])
self.assertTrue(self.r["moveLengths"])
self.assertTrue(self.r["moveNoOverlap"])
+ def test_a_plain_move_stays_between_its_neighbours_and_moves_nothing_else(self):
+ # c dragged to 0 cannot pass b: it stays where it was.
+ self.assertEqual(self.r["moveClamped"],
+ [["a", 0, 2, 0, 2], ["b", 0, 3, 2, 5], ["c", 0, 1.5, 5, 6.5]])
+ # b slides inside its own hole; a and c do not move.
+ self.assertEqual(self.r["moveKeepsNeighbours"],
+ [["a", 0, 2, 0, 2], ["b", 0, 3, 3, 6], ["c", 0, 1, 7, 8]])
+
def test_a_moved_clip_is_stamped_human(self):
# The server keeps the other end of this promise: a re-plan can leave a
# human's cut alone precisely because it is labelled.
@@ -2256,11 +2300,19 @@ class TimelineClient(unittest.TestCase):
self.assertTrue(self.r["anchoredNoOverlap"])
# ---- trim ------------------------------------------------------------
- def test_the_right_handle_changes_the_length_and_ripples_the_tail(self):
+ def test_the_right_handle_with_ripple_changes_the_length_and_slides_the_tail(self):
self.assertEqual(self.r["trimRight"],
[["a", 0, 1.25, 0, 1.25], ["b", 0, 3, 1.25, 4.25]])
self.assertTrue(self.r["trimRightLengths"])
+ def test_the_right_handle_by_default_opens_a_hole_and_moves_nothing_else(self):
+ self.assertEqual(self.r["trimRightHole"],
+ [["a", 0, 1.25, 0, 1.25], ["b", 0, 3, 2, 5]])
+ self.assertTrue(self.r["trimRightHoleLengths"])
+ # growing back stops at the neighbour, never pushes it
+ self.assertEqual(self.r["trimRightStopsAtNext"],
+ [["a", 0, 2, 0, 2], ["b", 0, 3, 2, 5]])
+
def test_the_left_handle_moves_the_in_point_and_leaves_the_tail_alone(self):
self.assertEqual(self.r["trimLeft"],
[["a", 0, 2, 0, 2], ["b", 0.5, 3, 2.5, 5]])
@@ -3256,9 +3308,10 @@ class TheSoundsEnvelopeOnTheClient(unittest.TestCase):
def test_the_strip_player_moves_the_gain(self):
fn = extract_function("sbeStripSync", self.src)
- self.assertIn("sbeGainAt(c2, win.len, w.at - win.start)", fn)
- # STRIP-relative, which is the envelope's own clock: a J-cut that
- # slides its sound must not drag the ramp with it.
+ # STRIP-relative AND on the played clock: a J-cut that slides its
+ # sound must not drag the ramp with it, and a retimed strip's second
+ # is `(source second - in-point) / speed` (see audio_gain_points).
+ self.assertIn("sbeGainAt(c2, win.len, (w.at - win.start) / win.speed)", fn)
self.assertIn("w.at - win.start", fn)
def test_the_bed_plays_the_WHOLE_mix_and_not_just_its_envelope(self):
diff --git a/test_storyboard_planner.py b/test_storyboard_planner.py
index 3ebcb6a..db9efa6 100644
--- a/test_storyboard_planner.py
+++ b/test_storyboard_planner.py
@@ -1357,9 +1357,9 @@ class TestScreenplayPass(unittest.TestCase):
Owner, on the films this planner produced before it existed: "the prompt
writing should be like a movie director... The action is well planned. You
understand what I mean? It is not working properly. It's just a succession
- of shots." Maestro does screenplay -> shot breakdown -> per-model polish;
- this had no screenplay step at all, so structure and coverage were being
- invented in the same breath.
+ of shots." A film is written screenplay -> shot breakdown -> per-shot
+ polish; this had no screenplay step at all, so structure and coverage were
+ being invented in the same breath.
"""
SCENE = "\n".join([
"BEAT - He throws both arms wide in front of the soapy car.",
diff --git a/test_take.py b/test_take.py
new file mode 100644
index 0000000..e3d0bcb
--- /dev/null
+++ b/test_take.py
@@ -0,0 +1,170 @@
+"""ONE TAKE: the plan arithmetic, the beats, the make_job mapping on both
+engines, the estimate route, and the H3 runner with a stubbed engine."""
+import json
+import subprocess
+from pathlib import Path
+
+import pytest
+
+import mlx_ltx_panel as p
+
+
+def test_plan_h3_parts_and_ltx_frames():
+ h = p.take_plan(60, "h3")
+ assert h["beats"] == 12 and [len(x) for x in h["parts"]] == [3, 3, 3, 3]
+ assert h["frames"] == 4 * 362
+ assert p.take_plan(45, "h3")["parts"][-1] == [6, 7, 8]
+ l = p.take_plan(30, "ltx")
+ assert l["beats"] == 6 and len(l["parts"]) == 1 and l["frames"] == 721
+ for s in p.TAKE_SECONDS: # every length is 8k+1 on LTX
+ assert (p.take_plan(s, "ltx")["frames"] - 1) % 8 == 0
+ assert p.take_plan(50, "h3") is None and p.take_plan("x", "h3") is None
+
+
+def test_beats_normalise_from_json_or_lines():
+ assert p.take_beats(json.dumps(["a", "b"]), 4) == ["a", "b", "", ""]
+ assert p.take_beats("a\nb\n\nc", 3) == ["a", "b", ""]
+ assert p.take_beats("", 2) == ["", ""]
+ assert p.take_beats(["x"] * 5, 3) == ["x", "x", "x"]
+
+
+def test_make_job_h3_take_forces_15s_parts_and_first_chain():
+ j = p.make_job({"mode": "t2v", "engine": "h3", "prompt": "a hen skates",
+ "take_seconds": "60", "beats": json.dumps([f"b{i}" for i in range(12)]),
+ "h3_quality": "high", "h3_length": "3s"})
+ q = j["params"]
+ assert q["h3_length"] == "15s" and q["h3_chain_prompts"] == ["b0", "b1", "b2"]
+ assert q["take"]["seconds"] == 60 and q["take"]["engine"] == "h3"
+ assert q["take"]["beat_prompts"][11] == "b11"
+
+
+def test_make_job_ltx_take_is_the_windows_chain():
+ j = p.make_job({"mode": "t2v", "engine": "ltx", "prompt": "x",
+ "take_seconds": "30", "beats": "one\ntwo\n"})
+ q = j["params"]
+ assert q["long_mode"] == "windows" and q["frames"] == 721
+ assert q["window_prompts"][:3] == ["one", "two", ""]
+ assert q["take"]["engine"] == "ltx"
+
+
+def test_make_job_without_take_is_unchanged():
+ q = p.make_job({"mode": "t2v", "engine": "ltx", "prompt": "x"})["params"]
+ assert q["take"] is None and q["long_mode"] == "native"
+ q2 = p.make_job({"mode": "t2v", "engine": "ltx", "prompt": "x", "take_seconds": "0"})["params"]
+ assert q2["take"] is None
+
+
+def test_estimate_route_registered_and_prices_h3():
+ from panel import routes_meta # noqa: F401
+ from panel.routes import GET_ROUTES
+ assert "/take/estimate" in GET_ROUTES
+ m = p.take_estimate_minutes("h3", "high", 60)
+ assert m is None or m > 30 # four 15 s parts, never minutes
+ assert p.take_estimate_minutes("ltx", "balanced", 60) is None
+
+
+def _tiny_clip(path: Path, colour: str) -> None:
+ subprocess.run([str(p.FFMPEG), "-loglevel", "error", "-y", "-f", "lavfi", "-i",
+ f"color=c={colour}:s=64x64:d=0.5:r=24", "-f", "lavfi", "-i",
+ "anullsrc=r=48000:cl=stereo", "-t", "0.5", "-c:v", "libx264", "-pix_fmt",
+ "yuv420p", "-c:a", "aac", "-shortest", str(path)], check=True)
+
+
+def test_take_runner_chains_parts_and_joins(tmp_path, monkeypatch):
+ out_dir = tmp_path / "out"; out_dir.mkdir()
+ monkeypatch.setattr(p, "OUTPUT", out_dir)
+ monkeypatch.setattr(p, "STATE_DIR", tmp_path / "state")
+ hidden = []
+ monkeypatch.setattr(p, "set_hidden", lambda path, flag: hidden.append((path, flag)))
+ seen = []
+
+ def fake_h3(child):
+ seen.append(dict(child["params"]))
+ out = out_dir / f"{child['id']}.mp4"
+ _tiny_clip(out, "red" if len(seen) == 1 else "blue")
+ (out_dir / f"{child['id']}.mp4.json").write_text(json.dumps({"width": 64, "height": 64, "seed": 5}))
+ child["output_path"] = str(out)
+ monkeypatch.setattr(p, "run_h3_job_inner", fake_h3)
+ j = p.make_job({"mode": "t2v", "engine": "h3", "prompt": "a hen skates", "take_seconds": "30",
+ "beats": json.dumps(["b1", "b2", "b3", "b4", "b5", "b6"]), "preset_label": "ride"})
+ p.run_take_job_inner(j)
+ assert len(seen) == 2
+ assert seen[0]["mode"] == "t2v" and seen[0]["h3_chain_prompts"] == ["b1", "b2", "b3"]
+ assert seen[1]["mode"] == "i2v" and seen[1]["h3_chain_prompts"] == ["b4", "b5", "b6"]
+ assert Path(seen[1]["image"]).is_file() # the last frame of part 1
+ assert seen[1]["take"] is None # a part is not a take
+ final = Path(j["output_path"])
+ assert final.is_file() and final.name.endswith("_take30s.mp4")
+ side = json.loads(final.with_suffix(final.suffix + ".json").read_text())
+ assert side["take"]["seconds"] == 30 and side["take"]["beats"][5] == "b6"
+ assert len(side["take"]["parts"]) == 2 and side["width"] == 64
+ assert [f for f, flag in hidden if flag] == side["take"]["parts"]
+
+
+def test_take_runner_stops_between_parts(tmp_path, monkeypatch):
+ out_dir = tmp_path / "out"; out_dir.mkdir()
+ monkeypatch.setattr(p, "OUTPUT", out_dir)
+ monkeypatch.setattr(p, "STATE_DIR", tmp_path / "state")
+ monkeypatch.setattr(p, "set_hidden", lambda *a: None)
+
+ def fake_h3(child):
+ out = out_dir / f"{child['id']}.mp4"; _tiny_clip(out, "red"); child["output_path"] = str(out)
+ job["cancel_requested"] = True # Stop pressed during part 1
+ monkeypatch.setattr(p, "run_h3_job_inner", fake_h3)
+ job = p.make_job({"mode": "t2v", "engine": "h3", "prompt": "x", "take_seconds": "30"})
+ with pytest.raises(RuntimeError, match="stopped"):
+ p.run_take_job_inner(job)
+
+
+# ---- the Storyboard door -------------------------------------------------------
+import storyboard as sb
+
+
+def _beat_shots(n):
+ return [{"n": i + 1, "mode": "text", "engine": "h3", "prompt": f"beat {i + 1}", "duration_s": 5.0}
+ for i in range(n)]
+
+
+def test_collapse_take_keeps_one_shot_with_the_beats():
+ t = sb.collapse_take(_beat_shots(6), 30)
+ assert len(t) == 1
+ s = t[0]
+ assert s["n"] == 1 and s["take_seconds"] == 30 and s["duration_s"] == 30.0
+ assert s["beats"] == [f"beat {i}" for i in range(1, 7)] and s["prompt"] == "beat 1"
+ assert s["frames"] == 721
+ short = sb.collapse_take(_beat_shots(4), 60)[0] # planner wrote fewer than asked
+ assert len(short["beats"]) == 12 and short["beats"][4] == ""
+ assert sb.collapse_take([], 30) == []
+
+
+def test_take_shot_becomes_take_fields_on_both_engines():
+ t = sb.collapse_take(_beat_shots(6), 30)[0]
+ j = sb.shot_to_job(t, {"quality": "balanced"}, h3_available=True, engine_mode="h3")
+ assert j["engine"] == "h3" and j["take_seconds"] == "30"
+ assert json.loads(j["beats"]) == t["beats"]
+ j2 = sb.shot_to_job({**t, "engine": "ltx"}, {"quality": "balanced"}, h3_available=False)
+ assert j2["engine"] == "ltx" and j2["take_seconds"] == "30" and j2["frames"] == 721
+ # the panel's make_job then does what the Video tab would
+ q = p.make_job({k: str(v) for k, v in j.items()})["params"]
+ assert q["take"]["seconds"] == 30 and q["h3_length"] == "15s"
+
+
+def test_take_shot_is_priced_by_parts_and_validates():
+ t = sb.collapse_take(_beat_shots(12), 60)[0]
+ secs = sb.shot_render_secs(t, {"quality": "balanced"}, h3_cost=lambda q, l: 3400.0 if l == "15s" else 1.0)
+ assert secs == 4 * 3400.0
+ b = sb.new_storyboard("sb_t", "t")
+ b["shots"] = [t]
+ errs = sb.validate_storyboard_detail(b)
+ assert not [e for e in errs if e["code"] == "bad_duration"], errs
+ # without the take flag the same 90 s shot is over the single-clip cap
+ long = sb.collapse_take(_beat_shots(18), 90)[0]
+ b["shots"] = [long]
+ assert not [e for e in sb.validate_storyboard_detail(b) if e["code"] == "bad_duration"]
+ b["shots"] = [{**long, "take_seconds": None}]
+ assert [e for e in sb.validate_storyboard_detail(b) if e["code"] == "bad_duration"]
+
+
+def test_take_concept_asks_for_beats_that_never_cut():
+ c = p._sb_take_concept("a hen skateboards through the city", 60)
+ assert "12 beats" in c and "never cuts" in c and "a hen skateboards" in c
diff --git a/webapp/index.html b/webapp/index.html
index 8fa1bfa..1a1660b 100644
--- a/webapp/index.html
+++ b/webapp/index.html
@@ -917,6 +917,11 @@
make_job allowlist — a field that isn't listed there silently
no-ops on /queue/add (the known trap). setH3Tier keeps the three
in sync, so there is exactly one state, spelled three ways. -->
+ <!-- ONE TAKE: a length past a single pass, and one beat per five
+ seconds. make_job turns it into the windows chain (LTX) or
+ 15 s parts that continue from each other (H3). -->
+ <input type="hidden" name="take_seconds" id="take_seconds" value="0">
+ <input type="hidden" name="beats" id="beats" value="">
<input type="hidden" name="h3_tier" id="h3_tier" value="draft_3s">
<input type="hidden" name="h3_quality" id="h3_quality" value="draft">
<input type="hidden" name="h3_length" id="h3_length" value="3s">
@@ -1300,6 +1305,8 @@
onclick="event.stopPropagation(); event.preventDefault(); document.getElementById('h3LoraImportFile').click()"><svg class="ph" aria-hidden="true" style="margin-right:6px;vertical-align:-2px"><use href="#ph-folder-simple"/></svg>Import H3 LoRA</button>
<button type="button" class="loras-browse-btn"
onclick="event.stopPropagation(); event.preventDefault(); openCivitaiModal()"><svg class="ph" aria-hidden="true" style="margin-right:6px;vertical-align:-2px"><use href="#ph-magnifying-glass"/></svg>Browse CivitAI</button>
+ <button type="button" class="loras-browse-btn is-ghost" id="loraUpdatesBtn" title="Ask CivitAI whether any installed LoRA has a newer version"
+ onclick="event.stopPropagation(); event.preventDefault(); checkLoraUpdates()">Check for updates</button>
</span>
</summary>
<div class="loras-body" id="lorasBody">
@@ -1579,13 +1586,56 @@
frames at 12fps, then exports a normal 24fps file with
motion interpolation. This is explicit because dialogue,
lip-sync, and fast motion need user judgment. -->
+ <!-- ONE TAKE. The length control for anything longer than one
+ pass, on either engine. Picks a length, writes beats, shows
+ the real time; the engine's own length pills lock while it is
+ on, because a take IS the length. -->
+ <div class="cz-control" id="takeRow">
+ <div class="cz-label">One take
+ <span class="cz-label-hint" id="takeHint">longer than a single clip · the world changes, the shot never cuts · <a href="/docs/prompting" target="_blank" rel="noopener">how to write the beats</a></span>
+ </div>
+ <div class="pill-group cols-3" id="takeGroup">
+ <button type="button" class="pill-btn active" data-take="0" onclick="setTakeSeconds(0)"><span>Off</span><span class="sub">one clip</span></button>
+ <button type="button" class="pill-btn" data-take="30" onclick="setTakeSeconds(30)"><span>30 s</span><span class="sub">6 beats</span></button>
+ <button type="button" class="pill-btn" data-take="45" onclick="setTakeSeconds(45)"><span>45 s</span><span class="sub">9 beats</span></button>
+ <button type="button" class="pill-btn" data-take="60" onclick="setTakeSeconds(60)"><span>1 min</span><span class="sub">12 beats</span></button>
+ <button type="button" class="pill-btn" data-take="90" onclick="setTakeSeconds(90)"><span>1½ min</span><span class="sub">18 beats</span></button>
+ <button type="button" class="pill-btn" data-take="120" onclick="setTakeSeconds(120)"><span>2 min</span><span class="sub">24 beats</span></button>
+ </div>
+ <div class="cz-control" id="beatsRow" hidden>
+ <div class="cz-label">Beats
+ <span class="cz-label-hint" id="beatsHint">one line per 5 seconds · a blank line holds the moment</span></div>
+ <textarea id="beats_text" class="sb-textarea" rows="6" spellcheck="false"
+ oninput="beatsInput()"
+ placeholder="she pushes off down the sunlit avenue&#10;a van sweeps past, pigeons burst up ahead&#10;she drops off the kerb into the road&#10;…"></textarea>
+ <div class="take-estimate" id="takeEstimate" aria-live="polite"></div>
+ </div>
+ </div>
+
<div class="cz-control" id="temporalRow" data-ltx-only>
<div class="cz-label">Long clips
- <span class="cz-label-hint">experimental temporal interpolation</span>
+ <span class="cz-label-hint">past 10 s: interpolate frames, or chain windows</span>
</div>
- <div class="pill-group cols-2" id="temporalGroup">
+ <div class="pill-group cols-3" id="temporalGroup">
<button type="button" class="pill-btn active" data-temporal="native"><span>Native</span><span class="sub">24fps from LTX</span></button>
<button type="button" class="pill-btn" data-temporal="fps12_interp24"><span>12 → 24fps</span><span class="sub">half frames · interpolated</span></button>
+ <button type="button" class="pill-btn" data-temporal="windows"><span>Windows</span><span class="sub">experimental · picture drifts across passes · needs Q8</span></button>
+ </div>
+ <!-- SLIDING WINDOWS: one prompt per window, the H3 chain's
+ contract brought to LTX. The first line is the shot; every
+ later line is the next beat, led by the movement; a blank
+ line holds the previous moment. The invariants are what
+ must not change between passes and are re-injected into
+ every window. -->
+ <div class="cz-control" id="windowsRow" hidden>
+ <div class="cz-label">Per-window prompts
+ <span class="cz-label-hint" id="windowsHint">one line per window · blank holds</span></div>
+ <textarea id="window_prompts_text" class="sb-textarea" rows="3" spellcheck="false"
+ oninput="windowPromptsInput()"
+ placeholder="(first window uses the prompt above)&#10;he turns to the window and the light catches his face&#10;"></textarea>
+ <input type="hidden" name="window_prompts" id="window_prompts" value="">
+ <input type="text" name="window_invariants" id="window_invariants" class="sb-input"
+ placeholder="what must not change between windows — one man, a grey room, soft window light">
</div>
</div>
@@ -2671,7 +2721,7 @@
<div class="cz-control" id="sbLengthRow">
<div class="cz-label">Shots <span class="cz-label-hint">how many, roughly</span></div>
- <div class="quality-strip pill-group cols-4" id="sbLengthGroup">
+ <div class="quality-strip pill-group cols-5" id="sbLengthGroup">
<button type="button" class="q-chip pill-btn" data-sb-shots="6">
<span class="ql-name">6</span><span class="q-spec ql-spec sub">a scene</span></button>
<button type="button" class="q-chip pill-btn active" data-sb-shots="12">
@@ -2680,6 +2730,21 @@
<span class="ql-name">24</span><span class="q-spec ql-spec sub">a film</span></button>
<button type="button" class="q-chip pill-btn" data-sb-shots="36">
<span class="ql-name">36</span><span class="q-spec ql-spec sub">long</span></button>
+ <!-- ONE TAKE: a film that is one shot. The planner writes beats
+ (one per 5 s) instead of shots; the render is the Video tab's
+ take. -->
+ <button type="button" class="q-chip pill-btn" data-sb-shots="take" title="One continuous shot that never cuts — the planner writes one beat per five seconds and the world changes around the subject">
+ <span class="ql-name">1</span><span class="q-spec ql-spec sub">one take</span></button>
+ </div>
+ <div class="cz-control" id="sbTakeRow" hidden>
+ <div class="cz-label">How long <span class="cz-label-hint">one beat per 5 seconds · the camera never cuts</span></div>
+ <div class="pill-group cols-5" id="sbTakeGroup">
+ <button type="button" class="pill-btn" data-sb-take="30"><span>30 s</span><span class="sub">6 beats</span></button>
+ <button type="button" class="pill-btn" data-sb-take="45"><span>45 s</span><span class="sub">9 beats</span></button>
+ <button type="button" class="pill-btn active" data-sb-take="60"><span>1 min</span><span class="sub">12 beats</span></button>
+ <button type="button" class="pill-btn" data-sb-take="90"><span>1½ min</span><span class="sub">18 beats</span></button>
+ <button type="button" class="pill-btn" data-sb-take="120"><span>2 min</span><span class="sub">24 beats</span></button>
+ </div>
</div>
</div>
@@ -2693,6 +2758,28 @@
<div class="sb-enginepick-note" id="sbEnginePickNote"></div>
</div>
+ <!-- THE DIRECTOR. A soundtrack on the brief makes this a music video:
+ the beat grid decides how many shots there are and how long each
+ is (the Shots chips stand down), the planner writes one movement
+ per slot, and the Editor opens the film already cut on the
+ downbeats under this track. The same path the Editor's soundtrack
+ takes — a file on this Mac. -->
+ <div class="cz-control" id="sbTrackRow">
+ <div class="cz-label">Soundtrack
+ <span class="cz-label-hint" id="sbTrackMeta">optional — a track makes it a music video cut to the beat</span></div>
+ <div class="sb-track-row">
+ <input type="text" id="sbTrack" class="sb-input" spellcheck="false"
+ oninput="sbTrackInput()"
+ placeholder="/path/to/the/track.wav">
+ <select class="sb-input sb-track-bars" id="sbTrackBars" title="How many bars each shot holds"
+ onchange="sbTrackInput()">
+ <option value="1">1 bar</option>
+ <option value="2" selected>2 bars</option>
+ <option value="4">4 bars</option>
+ </select>
+ </div>
+ </div>
+
<div class="cz-control" id="sbStyleRow">
<div class="cz-label">Look <span class="cz-label-hint">goes on every shot</span></div>
<input type="text" id="sbStyle" class="sb-input"
@@ -2745,6 +2832,34 @@
</div>
</details>
+ <!-- AUTO. One press: plan, render every shot, cut to the beat, make
+ the film. Each step is the panel's existing one; only the
+ hand-over is new. -->
+ <label class="check sb-auto" title="After the plan lands, every shot renders on its own, the cut is made (on the beat when there is a track) and the film is assembled — no more buttons. You can still stop the render or re-cut afterwards.">
+ <input type="checkbox" id="sbAuto"> Auto — plan, render every shot, cut and make the film
+ </label>
+ <!-- ANCHOR STILLS. A still of each shot's first frame (from the
+ character's sheet when it has one) is made first, in seconds; the
+ clip then starts from it. -->
+ <label class="check sb-auto" title="Before each shot renders, an image of its first frame is made (from the character's sheet when the shot has one) and the clip starts from that still. LTX shots only; the still shows on the shot card with a New still button.">
+ <input type="checkbox" id="sbAnchorStills"> Start each shot from a still
+ </label>
+ <!-- LONG WINDOWS. A shot longer than one LTX window renders as a chain
+ of windows instead of being cut to fit. -->
+ <label class="check sb-auto" title="A shot longer than 5 seconds renders as a chain of 5-second passes, each continuing from the last, instead of being shortened to fit one. Slower. LTX shots only.">
+ <input type="checkbox" id="sbLongWindows"> Long shots (over 5 s): chain 5-second passes · needs the Q8 pack
+ </label>
+ <div class="sb-ramline">
+ <span>These three decide how the film gets made.</span>
+ <button type="button" class="help-dot" id="sbSwitchHelpBtn" aria-expanded="false"
+ aria-controls="sbSwitchHelpNote" title="What do they do?" onclick="sbToggleSwitchHelp()">?</button>
+ </div>
+ <div class="h3-winhelp" id="sbSwitchHelpNote" hidden>
+ <b>Auto</b> — once the plan lands, every shot renders on its own, the cut is made (on the beat when there is a track) and the film is assembled. You can still stop it or re-cut afterwards.<br>
+ <b>Start each shot from a still</b> — an image of the first frame is made first (seconds), from the character's sheet when the shot has one, and the clip starts from it. The composition is decided on the image, not discovered after minutes of video. A still that fails is written on the card and the shot renders without one. LTX shots only.<br>
+ <b>Long shots</b> — a shot over 5 seconds is normally shortened to fit one pass. With this on, it renders as a chain of 5-second passes, each continuing the last. Slower, and it needs the Q8 pack. LTX shots only.<br>
+ The planner writes the beats by the rules in <a href="/docs/prompting" target="_blank" rel="noopener">Writing for Phosphene</a>; the same page can be copied into your own assistant if you write by hand.
+ </div>
<div class="form-action-footer">
<div class="sb-ramline" id="sbRamLine">
<span>Planning borrows the memory for about a minute, then gives it back.</span>
@@ -2957,6 +3072,12 @@
<button type="button" class="ghost-btn" id="edAddSlugBtn"
onclick="edAddSlug()"
title="Black, for as long as you say. No file, no proxy — it is drawn by the render.">Add black</button>
+ <!-- A TITLE IS MADE THE SAME WAY BLACK IS: it has no file, so it has
+ no row. It lands on the overlay lane at the playhead, selected,
+ with its text ready to type in the inspector. -->
+ <button type="button" class="ghost-btn" id="edAddTitleBtn"
+ onclick="edAddTitle()"
+ title="Text over the picture, on the overlay lane at the playhead. Type it in the inspector; it is drawn by the render.">Add title</button>
</div>
<select class="sb-input ed-pool-film" id="edPoolFilm" hidden
onchange="edPoolPickFilm(this.value)"
@@ -3474,6 +3595,40 @@
They are `position: fixed` and hidden, so an open menu cannot push
the workspace around — the same rule the notice surface follows. -->
<div class="sbe-pop" id="sbeRenderMenu" hidden>
+ <!-- DELIVER AS. Two rows, remembered: what the film is encoded as
+ and how big. H.264 is the panel's preset and plays everywhere;
+ HEVC is the Mac's hardware encoder at half the size; ProRes is a
+ .mov for the grade that nothing here previews. Size is up
+ only, never a crop. -->
+ <span class="sbe-pop-note">Deliver as</span>
+ <span class="pill-group cols-3 sbe-deliver" id="sbeDeliverFormat">
+ <button type="button" class="pill-btn active" data-format="h264" onclick="sbeDeliverPick('format', 'h264')"
+ title="The panel's own preset. Plays everywhere.">H.264</button>
+ <button type="button" class="pill-btn" data-format="hevc" onclick="sbeDeliverPick('format', 'hevc')"
+ title="Apple's hardware encoder — about half the size at the same look. Plays in Safari and Chrome on a Mac.">HEVC</button>
+ <button type="button" class="pill-btn" data-format="prores" onclick="sbeDeliverPick('format', 'prores')"
+ title="ProRes 422 HQ in a .mov, 10-bit 4:2:2 — for colour grading in an NLE. Not previewable here.">ProRes</button>
+ </span>
+ <span class="sbe-deliver-cap">H.264 plays everywhere · HEVC half the size · ProRes for the grade (.mov)</span>
+ <span class="pill-group cols-3 sbe-deliver" id="sbeDeliverSize">
+ <button type="button" class="pill-btn active" data-size="native" onclick="sbeDeliverPick('size', 'native')"
+ title="The largest picture in the cut, as it is.">As cut</button>
+ <button type="button" class="pill-btn" data-size="1080p" onclick="sbeDeliverPick('size', '1080p')"
+ title="Scaled to 1080 high, aspect kept, never cropped.">1080p</button>
+ <button type="button" class="pill-btn" data-size="2160p" onclick="sbeDeliverPick('size', '2160p')"
+ title="Scaled to 2160 high (4K), aspect kept. An upscale — it adds pixels, not detail.">4K</button>
+ </span>
+ <span class="sbe-deliver-cap">Size is up only, never a crop · 4K adds pixels, not detail</span>
+ <span class="pill-group cols-3 sbe-deliver" id="sbeDeliverFinish">
+ <button type="button" class="pill-btn active" data-finish="none" onclick="sbeDeliverPick('finish', 'none')"
+ title="The picture as rendered.">Clean</button>
+ <button type="button" class="pill-btn" data-finish="grain" onclick="sbeDeliverPick('finish', 'grain')"
+ title="Fine moving film grain over the delivered picture — takes the digital edge off.">Grain</button>
+ <button type="button" class="pill-btn" data-finish="heavy_grain" onclick="sbeDeliverPick('finish', 'heavy_grain')"
+ title="Coarse grain, 16 mm territory. Added after the size, so a 4K delivery gets 4K grain.">Heavy grain</button>
+ </span>
+ <span class="sbe-deliver-cap">Finish is on the delivery only — the preview and the export stay clean</span>
+ <span class="sbe-pop-sep"></span>
<button type="button" class="ghost-btn" id="sbeNleBtn" onclick="sbeExportNle()"
title="A folder with an FCP7 XML (Premiere + Resolve), an After Effects script, and hardlinked media. Audio comes out as stems, not the ducked mix.">Export for Premiere / Resolve / AE</button>
<span class="sbe-pop-note" id="sbeRenderNote"></span>
@@ -3710,6 +3865,11 @@
both, carrying its own opacity so a card's fade is independent of
whatever is beneath it — which is what a second track means. -->
<img id="sbeOvLayer" class="sbe-ov-layer" alt="">
+ <!-- A TITLE ON THE STAGE. Drawn in the DOM at the same anchor and
+ the same 1080-relative size the render rasterises it at, so the
+ stage shows the card the file will carry. Same opacity rule as
+ the card layer: its fade is its own. -->
+ <div id="sbeOvText" class="sbe-ov-text"></div>
<div class="sbe-stage-badge" id="sbeBadge">idle</div>
<div class="sbe-stage-empty" id="sbeStageEmpty" hidden></div>
</div>
@@ -3927,6 +4087,13 @@
<button type="button" id="mainOutputsFilterPhotos"
onclick="setMainOutputsFilter('photos')">Photos</button>
</div>
+ <!-- SEARCH, over everything the sidecar knows: prompt words, mode,
+ quality, engine, size, seed, LoRA and character names. A
+ substring test on one lower-cased string per output, so it is
+ free per keystroke; the title says how many match. -->
+ <input type="search" class="sb-input outputs-search" id="outputsSearch"
+ placeholder="Search prompts, models, LoRAs, sizes…" aria-label="Search outputs"
+ spellcheck="false" oninput="setOutputsQuery(this.value)" onsearch="setOutputsQuery(this.value)">
<span class="ch-spacer"></span>
<!-- "Show all (N)" — surfaces older renders that /status's polling
fast path (newest 60) doesn't include. The button is hidden
@@ -4231,6 +4398,41 @@
<div class="hint" id="spicyHint" style="margin-top:8px; display:none"></div>
</div>
+ <!-- Appearance. Three answers — dark, light, follow the system — kept
+ in this browser and applied before the first paint from main.js.
+ Same row shape as the switches below. -->
+ <div class="settings-section">
+ <h3>Appearance</h3>
+ <div class="hint" style="margin-bottom:10px">The panel's palette. "System" follows the Mac's own light or dark setting and switches live. Saved in this browser only.</div>
+ <div class="pill-group cols-3" id="appearanceGroup">
+ <button type="button" class="pill-btn active" data-appearance="dark" onclick="setAppearance('dark')">Dark</button>
+ <button type="button" class="pill-btn" data-appearance="light" onclick="setAppearance('light')">Light</button>
+ <button type="button" class="pill-btn" data-appearance="system" onclick="setAppearance('system')">System</button>
+ </div>
+ </div>
+
+ <!-- Completion alerts. A chime in the tab when a render finishes or
+ fails, and a browser notification when the tab is in the
+ background — once the person has allowed them. Same row shape as
+ the analytics switch below. -->
+ <div class="settings-section">
+ <h3>Completion alerts</h3>
+ <div class="hint" style="margin-bottom:10px" id="notifyHint"></div>
+ <div class="spicy-row">
+ <span class="spicy-state on" id="notifyStateBadge">ON</span>
+ <button type="button" class="ghost-btn" id="notifyAllowBtn" hidden
+ onclick="askNotifyPermission()">Allow browser alerts</button>
+ <button type="button" class="ghost-btn" id="notifyPushBtn" hidden
+ onclick="pushToggle()">Alert me here even when the tab is closed</button>
+ <button type="button" class="ghost-btn" id="notifyPushTestBtn" hidden
+ onclick="pushTest()">Send a test</button>
+ <button type="button" class="ghost-btn" id="notifyToggleBtn"
+ onclick="toggleNotify()" style="margin-left:auto">
+ Turn off
+ </button>
+ </div>
+ </div>
+
<!-- Anonymous usage analytics. Default ON, one click to turn off, and
the copy below is the whole truth about what leaves the machine —
if this list and docs/ANALYTICS.md ever disagree, the code is the
@@ -4607,7 +4809,7 @@ Third prompt."></textarea>
is intent; the timeline only learns about it when the clip exists. -->
<div class="modal-bg" id="sbeGenModal" onclick="if(event.target===this)sbeGenClose()">
<div class="modal">
- <h3>Fill this hole</h3>
+ <h3 id="sbeGenTitle">Fill this hole</h3>
<div class="hint" id="sbeGenWhere"></div>
<textarea class="batch" id="sbeGenPrompt" rows="4"
placeholder="A slow push in on the empty gym, dust in the light."></textarea>
@@ -4627,7 +4829,7 @@ Third prompt."></textarea>
back off the queued job and hands them here: this is what will
actually render, not what we asked for. -->
<div class="sbe-params" id="sbeGenParams" hidden></div>
- <div class="hint" style="margin-top:6px">The clip renders into the queue like any other shot. When it lands it appears under the timeline, and you place it — nothing moves your cuts on its own.</div>
+ <div class="hint" style="margin-top:6px" id="sbeGenAfter">The clip renders into the queue like any other shot. When it lands it appears under the timeline, and you place it — nothing moves your cuts on its own.</div>
<div class="modal-actions">
<button class="small" onclick="sbeGenClose()">Cancel</button>
<button class="small primary" style="padding:6px 14px" id="sbeGenGo" onclick="sbeGenSubmit()">Queue the shot</button>
diff --git a/webapp/js/boot.js b/webapp/js/boot.js
index 6e62191..f5a6137 100644
--- a/webapp/js/boot.js
+++ b/webapp/js/boot.js
@@ -317,9 +317,48 @@ function filteredMainOutputs() {
} else {
all = currentOutputs;
}
- if (mainOutputsFilter === 'all') return all;
- if (mainOutputsFilter === 'photos') return all.filter(isPhotoOutputMain);
- return all.filter(o => !isPhotoOutputMain(o));
+ if (mainOutputsFilter === 'photos') all = all.filter(isPhotoOutputMain);
+ else if (mainOutputsFilter !== 'all') all = all.filter(o => !isPhotoOutputMain(o));
+ return applyOutputsQuery(all);
+}
+
+// THE SEARCH. Every word typed must appear somewhere in the output's name
+// or its sidecar words (`q`, built server-side); order does not matter.
+// "aria 1280 turbo" finds the Aria clips rendered at 1280 wide on the turbo
+// tier, and nothing else.
+let _outputsQuery = '';
+function applyOutputsQuery(rows) {
+ const words = String(_outputsQuery || '').toLowerCase().split(/\s+/).filter(Boolean);
+ if (!words.length) return rows;
+ return rows.filter(o => {
+ const hay = (String(o.name || '') + ' ' + String(o.q || '')).toLowerCase();
+ return words.every(w => hay.indexOf(w) >= 0);
+ });
+}
+function setOutputsQuery(v) {
+ _outputsQuery = String(v || '');
+ // A search over what is on screen is a search over the newest 60 unless
+ // the older ones are in: pull them the first time a word is typed.
+ if (_outputsQuery && !window._showingAllOutputs && typeof outputsLoadAll === 'function') {
+ try { outputsLoadAll().then(() => { if (typeof renderCarousel === 'function') renderCarousel(); paintOutputsCount(); }); } catch (e) {}
+ }
+ if (typeof renderCarousel === 'function') renderCarousel();
+ paintOutputsCount();
+}
+// ONE FORMATTER for the header, derived from (query, chip, count) every
+// time — the review caught "Outputs · 1507" losing its word after a search
+// was cleared, and "0 photos" where "0 matches" was true.
+function outputsTitleText() {
+ const n = filteredMainOutputs().length;
+ const kind = mainOutputsFilter === 'all' ? '' : (' ' + mainOutputsFilter);
+ if (_outputsQuery) return 'Outputs · ' + n + ' match' + (n === 1 ? '' : 'es') + kind;
+ return 'Outputs · ' + n + (kind || (n === 1 ? ' output' : ' outputs'));
+}
+function outputsQueryText() { return _outputsQuery; }
+function paintOutputsCount() {
+ const t = document.getElementById('carouselTitle');
+ if (!t) return;
+ t.textContent = outputsTitleText();
}
// "Show all (N)" button handler — fetches the full unified gallery from
@@ -834,6 +873,7 @@ function _portalLoraPicker(dest) {
Object.assign(globalThis, {
applyTierTimes, setKeyframeMode, keyframeTimingSlots, renderKeyframeDynamicSlots,
maybeScaleTouchedKeyframeTiming, syncKeyframeTiming, isPhotoOutputMain, filteredMainOutputs,
+ applyOutputsQuery, setOutputsQuery, paintOutputsCount, outputsTitleText, outputsQueryText,
outputsLoadAll, _updateMainFilterChips, _maybeAutoLoadAllForEmptyFilter, setMainOutputsFilter,
updateModelCredit, toggleAvoidRow, syncAvoidRowFromValue, ingredientsServed,
_paintControlGenNote, defaultRemixMode, setMode, _portalLoraPicker,
diff --git a/webapp/js/characters.js b/webapp/js/characters.js
index 54d3fc1..4866ebf 100644
--- a/webapp/js/characters.js
+++ b/webapp/js/characters.js
@@ -2593,14 +2593,121 @@ function temporalModeAllowed() {
const mode = document.getElementById('mode').value;
return !_qualityUsesHq(q) && currentMode !== 'extend' && currentMode !== 'keyframe' && (mode === 't2v' || mode === 'i2v');
}
+// ---- ONE TAKE ---------------------------------------------------------------
+// A length past a single clip plus one beat per five seconds. The server does
+// the arithmetic (make_job → take_plan); this only keeps the form honest: the
+// engine's own length pills lock while a take is on, the beats box prefills
+// from the prompt the first time, and the estimate comes from /take/estimate.
+const TAKE_CHOICES = [0, 30, 45, 60, 90, 120];
+function setTakeSeconds(s, beats) {
+ s = parseInt(s || 0, 10) || 0;
+ if (!TAKE_CHOICES.includes(s)) s = 0;
+ const hid = document.getElementById('take_seconds');
+ if (hid) hid.value = String(s);
+ document.querySelectorAll('#takeGroup .pill-btn').forEach(b =>
+ b.classList.toggle('active', parseInt(b.dataset.take, 10) === s));
+ const row = document.getElementById('beatsRow');
+ if (row) row.hidden = !s;
+ ['h3LengthGroup', 'ltxLengthGroup', 'temporalGroup', 'windowsRow'].forEach(id => {
+ const g = document.getElementById(id);
+ if (g) g.classList.toggle('take-locked', !!s);
+ });
+ const ta = document.getElementById('beats_text');
+ if (s && ta) {
+ if (Array.isArray(beats)) ta.value = beats.join('\n');
+ else if (!ta.value.trim()) ta.value = takePrefill(s);
+ beatsInput();
+ takeRefresh();
+ } else {
+ const b = document.getElementById('beats');
+ if (b) b.value = '';
+ }
+ if (typeof updateCustomizeSummary === 'function') updateCustomizeSummary();
+ if (typeof updateDerived === 'function') updateDerived();
+}
+// The first beats come from the prompt itself, one sentence each, so the box
+// is never empty — the user edits, they do not start from nothing.
+function takePrefill(s) {
+ const prompt = (document.getElementById('prompt') || {}).value || '';
+ const n = Math.max(1, Math.round(s / 5));
+ const sents = prompt.split(/(?<=[.!?])\s+/).map(x => x.trim()).filter(Boolean);
+ const out = [];
+ for (let i = 0; i < n; i++) out.push(sents[i] || '');
+ while (out.length && !out[out.length - 1]) out.pop();
+ return out.join('\n');
+}
+function beatsInput() {
+ const ta = document.getElementById('beats_text');
+ const out = document.getElementById('beats');
+ const hint = document.getElementById('beatsHint');
+ if (!ta || !out) return;
+ const lines = String(ta.value || '').split('\n').map(x => x.trim());
+ while (lines.length && !lines[lines.length - 1]) lines.pop();
+ out.value = lines.length ? JSON.stringify(lines) : '';
+ const s = parseInt((document.getElementById('take_seconds') || {}).value || '0', 10) || 0;
+ const n = Math.round(s / 5);
+ if (hint && n) {
+ const filled = lines.filter(Boolean).length;
+ hint.textContent = `${n} beats of 5 s · ${filled} written` + (filled < n ? ' · a blank line holds the moment' : '') + (lines.length > n ? ` · the last ${lines.length - n} won't fit` : '');
+ }
+}
+let _takeRefreshSeq = 0;
+async function takeRefresh() {
+ const el = document.getElementById('takeEstimate');
+ const s = parseInt((document.getElementById('take_seconds') || {}).value || '0', 10) || 0;
+ if (!el || !s) return;
+ const engine = document.body.dataset.engine || 'ltx';
+ const quality = engine === 'h3'
+ ? ((document.getElementById('h3_quality') || {}).value || 'standard')
+ : ((document.getElementById('quality') || {}).value || 'balanced');
+ const seq = ++_takeRefreshSeq;
+ el.textContent = 'working out the time…';
+ try {
+ const r = await (await fetch(`/take/estimate?engine=${encodeURIComponent(engine)}&quality=${encodeURIComponent(quality)}&seconds=${s}`)).json();
+ if (seq !== _takeRefreshSeq) return;
+ if (!r.ok) { el.textContent = r.error || ''; return; }
+ const bits = [`${r.beats} beats`];
+ if (r.engine === 'h3') bits.push(`${r.parts} parts of 15 s that continue from each other`);
+ else bits.push('EXPERIMENTAL on LTX: the picture drifts across passes — use H3 for a take you will keep');
+ if (r.eta) bits.push(`about ${r.eta.replace(/^~/, '').replace(' · batch', '')} on this Mac`);
+ else if (r.engine === 'ltx') bits.push('about 7 min per 5 s at Quick on this Mac');
+ el.textContent = bits.join(' · ');
+ } catch (e) { if (seq === _takeRefreshSeq) el.textContent = ''; }
+}
+
function setTemporalMode(t) {
const allowed = temporalModeAllowed();
- const v = (allowed && t === 'fps12_interp24') ? 'fps12_interp24' : 'native';
+ const v = (allowed && (t === 'fps12_interp24' || t === 'windows')) ? t : 'native';
document.getElementById('temporal_mode').value = v;
document.querySelectorAll('#temporalGroup .pill-btn').forEach(b => b.classList.toggle('active', b.dataset.temporal === v));
+ // The per-window prompts belong to ONE of the three answers.
+ const row = document.getElementById('windowsRow');
+ if (row) row.hidden = (v !== 'windows');
+ if (v === 'windows') windowPromptsInput();
updateCustomizeSummary();
updateDerived();
}
+
+// One line per window on screen, a JSON array on the wire — the same shape
+// the H3 chain posts, so a curl and the form agree. The hint counts the
+// windows the current length needs (ltx_windows: 121-frame windows, 112 new
+// frames each) so the box says how many lines mean something.
+function windowPromptsInput() {
+ const ta = document.getElementById('window_prompts_text');
+ const out = document.getElementById('window_prompts');
+ const hint = document.getElementById('windowsHint');
+ if (!ta || !out) return;
+ const lines = String(ta.value || '').split('\n').map(s => s.trim());
+ while (lines.length && !lines[lines.length - 1]) lines.pop();
+ out.value = lines.length ? JSON.stringify(lines) : '';
+ if (hint) {
+ const f = parseInt(document.getElementById('frames')?.value || '121', 10) || 121;
+ const n = f <= 121 ? 1 : 1 + Math.ceil((f - 121) / 112);
+ hint.textContent = n <= 1
+ ? 'this length fits one window — pick a longer clip'
+ : n + ' windows · one line per window · blank holds the last moment';
+ }
+}
function setUpscale(u) {
const v = ['off', 'fit_720p', 'x2'].includes(u) ? u : 'off';
document.getElementById('upscale').value = v;
@@ -2831,6 +2938,8 @@ document.querySelectorAll('#extendModeGroup .pill-btn').forEach(b => b.onclick =
// Inline handlers in the markup and the other files resolve these through
// the global scope; everything NOT listed here is private to this module.
Object.assign(globalThis, {
+ setTakeSeconds, takePrefill, beatsInput, takeRefresh,
+ windowPromptsInput,
audioStudioInit, audioStudioDurationChanged, audioStudioEnhancePrompt, audioStudioGenerate,
trainRecommendedPreset, trainUpdatePresetButtons, trainUpdatePresetNote, downloadSampleCharacter,
charactersInit, charactersRenderChips, charactersOpenCompose, charactersBackToGrid,
diff --git a/webapp/js/editor.js b/webapp/js/editor.js
index 7a5a268..7350e69 100644
--- a/webapp/js/editor.js
+++ b/webapp/js/editor.js
@@ -312,7 +312,21 @@ function sbeFps() { return (typeof FPS === 'number' && FPS > 0) ? FPS : 24; }
// save payload testable in node rather than by eye — see
// test_storyboard_editor_ui.py, which runs these exact functions.
// ---------------------------------------------------------------------------
-function sbeLen(c) { return Math.max(SBE_MIN_CLIP, sbeNum(c.end) - sbeNum(c.start)); }
+// SPEED, ON THE CLIP. The mirror of `clip_speed()`: video only, clamped to
+// the same range, 1x when absent. Every length on the film goes through
+// `sbeLen`, so the one division below is the whole of what retiming does to
+// the layout — a 2x clip owns half the slot its window used to.
+const SBE_SPEED_MIN = 0.25;
+const SBE_SPEED_MAX = 4.0;
+function sbeSpeed(c) {
+ if (!c || sbeKind(c) !== 'video') return 1;
+ const s = sbeNum(c.speed, 1);
+ if (!(s > 0)) return 1;
+ return sbeRound(Math.max(SBE_SPEED_MIN, Math.min(SBE_SPEED_MAX, s)));
+}
+function sbeLen(c) {
+ return Math.max(SBE_MIN_CLIP, (sbeNum(c.end) - sbeNum(c.start)) / sbeSpeed(c));
+}
// Each clip owns the gap that PRECEDES it. That single choice is what makes
// every operation below a one-liner: a move is "change which gap you own", a
@@ -556,9 +570,13 @@ function sbeClipAudio(c) {
const vs = sbeNum((c || {}).start), ve = sbeNum((c || {}).end);
const fs = sbeNum((c || {}).film_start);
const a = (c || {}).audio;
+ // THE SOUND RUNS AT THE CLIP'S SPEED, linked or not — the mirror of
+ // `clip_audio()`. `len` is the strip's length ON THE FILM.
+ const sp = sbeSpeed(c);
if (!a || typeof a !== 'object' || sbeKind(c) !== 'video') {
return { start: vs, end: ve, film_start: fs, linked: true,
- coupled: false, split: false, len: Math.max(0, ve - vs) };
+ coupled: false, split: false, speed: sp,
+ len: sbeRound(Math.max(0, ve - vs) / sp) };
}
// THE PRESENCE OF THE FIELD IS THE SWITCH, not the values in it. Unlinking
// writes the window the clip already has, so an equality test read a
@@ -572,8 +590,8 @@ function sbeClipAudio(c) {
const f2 = sbeNum(a.film_start, fs);
const coupled = a.linked === true;
return { start: sbeRound(s2), end: sbeRound(e2), film_start: sbeRound(f2),
- linked: coupled, coupled: coupled, split: true,
- len: Math.max(0, sbeRound(e2 - s2)) };
+ linked: coupled, coupled: coupled, split: true, speed: sp,
+ len: sbeRound(Math.max(0, e2 - s2) / sp) };
}
// Rebuild the stored object from a window, keeping the coupling flag out of
@@ -654,13 +672,15 @@ function sbeAudioEdit(clips, id, mode, want) {
// case exactly: you pull his line back under the previous shot and the
// tail silently loses the same seconds off the end of the line you were
// keeping.
- const room = Math.min(t0, sbeRound(film + (end - start) - SBE_MIN_CLIP));
+ // FILM seconds on the lane, SOURCE seconds in the window: a retimed
+ // strip moves `speed` seconds of take for every film second dragged.
+ const room = Math.min(t0, sbeRound(film + (end - start) / w.speed - SBE_MIN_CLIP));
let delta = sbeRound(room - film);
- if (start + delta < 0) delta = sbeRound(-start);
- start = sbeRound(start + delta);
+ if (start + delta * w.speed < 0) delta = sbeRound(-start / w.speed);
+ start = sbeRound(start + delta * w.speed);
film = sbeRound(film + delta);
} else {
- let e = sbeRound(start + Math.max(SBE_MIN_CLIP, t0 - film));
+ let e = sbeRound(start + Math.max(SBE_MIN_CLIP, t0 - film) * w.speed);
if (src > 0) e = Math.min(e, sbeRound(src));
end = Math.max(sbeRound(start + SBE_MIN_CLIP), e);
}
@@ -679,8 +699,10 @@ function sbeAudioEdit(clips, id, mode, want) {
function sbeAudioDrift(c) {
const w = sbeClipAudio(c);
if (!w.split) return 0;
- return sbeRound((w.film_start - w.start)
- - (sbeNum((c || {}).film_start) - sbeNum((c || {}).start)));
+ // On the film's clock: a source second is `1/speed` film seconds on both
+ // halves, the same arithmetic `clip_audio_drift()` does.
+ return sbeRound((w.film_start - w.start / w.speed)
+ - (sbeNum((c || {}).film_start) - sbeNum((c || {}).start) / w.speed));
}
function sbeAudioInSync(c) { return Math.abs(sbeAudioDrift(c)) <= SBE_SYNC_TOL; }
@@ -809,7 +831,7 @@ function sbeResyncAudio(clips, id) {
why: 'this clip\'s sound is already under its own picture' };
}
if (c.locked) return { clips: clips, ok: false, why: 'locked' };
- const want = sbeRound(sbeNum(c.film_start) + (w.start - sbeNum(c.start)));
+ const want = sbeRound(sbeNum(c.film_start) + (w.start - sbeNum(c.start)) / w.speed);
if (want < 0) {
return { clips: clips, ok: false,
why: 'the sound would have to start before the __SEQ__ does — move the picture later first' };
@@ -854,7 +876,32 @@ function sbeResyncAudio(clips, id) {
// label is not worth a data migration. See docs/EDITOR_EFFECTS_MODEL.md.
function sbeClipLen(c) {
const n = sbeNum((c || {}).film_end) - sbeNum((c || {}).film_start);
- return Math.max(0, n > 0 ? n : (sbeNum((c || {}).end) - sbeNum((c || {}).start)));
+ return Math.max(0, n > 0 ? n
+ : (sbeNum((c || {}).end) - sbeNum((c || {}).start)) / sbeSpeed(c));
+}
+
+// Sets the clip's play rate and RIPPLES: the slot shrinks or grows in place
+// and everything after it slides, sound included. The window is untouched —
+// speed changes how fast the same seconds of the take play, never which.
+function sbeSetSpeed(clips, id, v) {
+ const c = sbeById(clips, id);
+ if (!c) return { clips: clips, ok: false, why: 'gone' };
+ if (c.locked) return { clips: clips, ok: false, why: 'locked' };
+ if (sbeKind(c) !== 'video') {
+ return { clips: clips, ok: false, why: 'only a video clip has a clock to run fast or slow' };
+ }
+ const want = sbeRound(Math.max(SBE_SPEED_MIN, Math.min(SBE_SPEED_MAX, sbeNum(v, 1) || 1)));
+ if (Math.abs(want - sbeSpeed(c)) < 1e-9) return { clips: clips, ok: false, why: 'no change' };
+ const mark = sbeSyncMark(clips);
+ const out = clips.map(x => Object.assign({}, x));
+ const t = sbeById(out, id);
+ // NEUTRAL IS ABSENT: 1x is no field, so an untouched clip is byte-identical
+ // to one from before speed existed.
+ if (Math.abs(want - 1) < 1e-9) delete t.speed; else t.speed = want;
+ t.source = 'human';
+ sbeLayout(out);
+ sbeSyncCarry(out, mark, [id]);
+ return { clips: out, ok: true };
}
function sbeFx(c) {
@@ -881,17 +928,24 @@ function sbeFx(c) {
// THE OPACITY AT A FILM SECOND, and the preview's whole honesty about fades:
// a value per frame rather than a CSS transition, so scrubbing shows what is
// true at that second instead of an animation that started when you arrived.
-function sbeFadeOpacityAt(c, t) {
+// `edges` is a transition's share of this clip's two ends ({head, tail} in
+// seconds, from `sbeTxEdges`). ONE <video> cannot show two pictures, so on
+// the stage a dissolve is previewed as a ramp through the stage's black on
+// both sides of the cut — the exact picture for a fade through black, an
+// honest approximation for a dissolve, and the badge says which.
+function sbeFadeOpacityAt(c, t, edges) {
const e = sbeFx(c);
- if (e.fade_in <= 1e-9 && e.fade_out <= 1e-9) return 1;
+ const ed = edges || { head: 0, tail: 0 };
+ const fin = Math.max(e.fade_in, sbeNum(ed.head)), fout = Math.max(e.fade_out, sbeNum(ed.tail));
+ if (fin <= 1e-9 && fout <= 1e-9) return 1;
const fs = sbeNum((c || {}).film_start), fe = sbeNum((c || {}).film_end);
const now = sbeNum(t);
let o = 1;
- if (e.fade_in > 1e-9 && now < fs + e.fade_in) {
- o = Math.min(o, Math.max(0, (now - fs) / e.fade_in));
+ if (fin > 1e-9 && now < fs + fin) {
+ o = Math.min(o, Math.max(0, (now - fs) / fin));
}
- if (e.fade_out > 1e-9 && now > fe - e.fade_out) {
- o = Math.min(o, Math.max(0, (fe - now) / e.fade_out));
+ if (fout > 1e-9 && now > fe - fout) {
+ o = Math.min(o, Math.max(0, (fe - now) / fout));
}
return Math.max(0, Math.min(1, sbeRound(o)));
}
@@ -1391,11 +1445,44 @@ function sbeSetAudioFade(clips, id, edge, seconds) {
// own window — the picture underneath is not consulted and does not shift.
function sbeOvKind(o) {
const k = String((o || {}).kind || '').toLowerCase();
- if (k === 'still' || k === 'video') return k;
+ if (k === 'still' || k === 'video' || k === 'text') return k;
return /\.(png|webp|tiff?)$/i.test(String((o || {}).path || ''))
? 'still' : 'video';
}
+// A TITLE IS AN OVERLAY WHOSE PIXELS ARE DRAWN. The mirror of
+// `overlay_text()`: the same defaults, the same clamps, so the card the stage
+// paints and the card the render rasterises are the same card. `font_size`
+// is px at a 1080-high frame; `x`/`y` are fractions of the frame.
+const SBE_TEXT_DEFAULTS = { font_size: 64, color: '#ffffff', align: 'center',
+ x: 0.5, y: 0.5, box: false, box_color: '#000000',
+ box_opacity: 0.5 };
+const SBE_TEXT_REF_H = 1080;
+const SBE_TEXT_MAX = 400;
+function sbeHexColour(v, d) {
+ let s = String(v || '').trim().toLowerCase();
+ if (/^#[0-9a-f]{3}$/.test(s)) s = '#' + s.slice(1).split('').map(ch => ch + ch).join('');
+ return /^#[0-9a-f]{6}$/.test(s) ? s : d;
+}
+function sbeOvText(o) {
+ const it = o || {};
+ const raw = (it.style && typeof it.style === 'object') ? it.style : {};
+ const d = SBE_TEXT_DEFAULTS;
+ const size = Math.max(8, Math.min(400, sbeNum(raw.font_size, d.font_size) || d.font_size));
+ let align = String(raw.align || d.align).toLowerCase();
+ if (align !== 'left' && align !== 'center' && align !== 'right') align = d.align;
+ const clamp01 = (v, dv) => Math.max(0, Math.min(1, sbeNum(v, dv)));
+ return {
+ text: String(it.text || '').replace(/\r\n?/g, '\n').slice(0, SBE_TEXT_MAX),
+ style: {
+ font_size: sbeRound(size), color: sbeHexColour(raw.color, d.color),
+ align: align, x: sbeRound(clamp01(raw.x, d.x)), y: sbeRound(clamp01(raw.y, d.y)),
+ box: raw.box === true, box_color: sbeHexColour(raw.box_color, d.box_color),
+ box_opacity: sbeRound(clamp01(raw.box_opacity, d.box_opacity)),
+ },
+ };
+}
+
function sbeOvAt(overlays, t) {
const now = sbeNum(t);
for (const o of overlays || []) {
@@ -1476,14 +1563,19 @@ function sbeOvAdd(overlays, item, filmStart) {
}
fs = push;
}
+ const kind = (item.kind === 'text') ? 'text'
+ : (/\.(png|webp|tiff?)$/i.test(String(item.path || '')) ? 'still' : 'video');
const o = {
- id: sbeNewId(), kind: /\.(png|webp|tiff?)$/i.test(String(item.path || ''))
- ? 'still' : 'video',
- path: item.path, title: item.title || '',
+ id: sbeNewId(), kind: kind,
+ path: (kind === 'text') ? null : item.path, title: item.title || '',
start: 0, end: sbeRound(dur),
film_start: sbeRound(fs), film_end: sbeRound(fs + dur),
source: 'human', locked: false,
};
+ if (kind === 'text') {
+ o.text = String(item.text || 'Title');
+ if (item.style && typeof item.style === 'object') o.style = Object.assign({}, item.style);
+ }
return { overlays: (overlays || []).concat([o]), ok: true, added: o };
}
@@ -1496,6 +1588,159 @@ function sbeOvDelete(overlays, id) {
return { overlays: (overlays || []).filter(x => x.id !== id), ok: true };
}
+// ---------------------------------------------------------------------------
+// TRANSITIONS — a typed object that OWNS A BOUNDARY, never an overlap
+// ---------------------------------------------------------------------------
+// The mirror of `resolve_transitions()`. A transition names the OUTGOING clip
+// and sits on the cut between it and its successor; the clips' own slots do
+// not move, and the render builds the overlap from SOURCE HANDLES — half the
+// duration of extra tail past the out-point, half of extra head before the
+// in-point. So the one thing the client has to know, and say, is whether
+// those handles exist. `sbeTxResolve` answers per boundary, with the same
+// sentence the server's validator would refuse the save with.
+const SBE_TX_KINDS = ['dissolve', 'fade_black'];
+const SBE_TX_MIN = 1 / 24;
+const SBE_TX_MAX = 2.0;
+const SBE_TX_LABELS = { dissolve: 'Dissolve', fade_black: 'Fade through black' };
+
+function sbeTxById(txs, id) {
+ for (const t of txs || []) if (t.id === id) return t;
+ return null;
+}
+function sbeTxAfter(txs, clipId) {
+ for (const t of txs || []) if (t.after_clip === clipId) return t;
+ return null;
+}
+function sbeTxDuration(row, outLen, inLen, fps) {
+ const d0 = sbeNum((row || {}).duration);
+ if (d0 <= 0) return 0;
+ const d = Math.max(0, Math.min(d0, SBE_TX_MAX, 0.5 * Math.max(0, Math.min(outLen, inLen))));
+ const f = Math.max(1, sbeNum(fps, 24) || 24);
+ // EVEN FRAMES — half a side each — the same rule `transition_duration`
+ // applies, so the number the inspector shows is the number the film gets.
+ const frames = 2 * Math.round(d * f / 2);
+ return sbeRound(frames / f);
+}
+function sbeTxSpare(c, side) {
+ if (sbeKind(c) !== 'video') return Infinity;
+ if (side === 'head') return Math.max(0, sbeNum(c.start));
+ const dur = sbeNum(c.duration, 0);
+ if (!(dur > 0)) return null;
+ return Math.max(0, dur - sbeNum(c.end));
+}
+function sbeTxResolve(clips, txs, fps) {
+ const order = (clips || []).slice().sort((a, b) =>
+ (sbeNum(a.film_start) - sbeNum(b.film_start)) || String(a.path).localeCompare(String(b.path)));
+ const pos = {};
+ order.forEach((c, k) => { pos[c.id] = k; });
+ const seen = {};
+ const out = [];
+ (txs || []).forEach((row, n) => {
+ const label = 'transition ' + (n + 1);
+ const res = { id: row.id, after_clip: String(row.after_clip || ''), before_clip: '',
+ kind: String(row.kind || '').toLowerCase(), duration: 0, half: 0,
+ at: 0, problem: null };
+ const fail = (code, message) => { res.problem = { code: code, message: message }; out.push(res); };
+ const k = pos[res.after_clip];
+ if (k === undefined) { fail('transition_unknown_clip', label + ': names no clip on this timeline'); return; }
+ const a = order[k];
+ if (k + 1 >= order.length) { fail('transition_last_clip', 'this is the last clip — there is nothing after it to dissolve into'); return; }
+ const b = order[k + 1];
+ res.before_clip = b.id;
+ res.at = sbeRound(sbeNum(a.film_end));
+ if (seen[res.after_clip]) { fail('transition_duplicate_boundary', 'this cut already has a transition — one per boundary'); return; }
+ seen[res.after_clip] = true;
+ if (SBE_TX_KINDS.indexOf(res.kind) < 0) { fail('transition_kind', label + ': unknown kind ' + res.kind); return; }
+ if (!(sbeNum(row.duration) > 0)) { fail('transition_duration', 'the duration must be above 0 s'); return; }
+ const d = sbeTxDuration(row, sbeLen(a), sbeLen(b), fps);
+ if (d < SBE_TX_MIN - 1e-9) { fail('transition_duration', 'these two clips are too short to carry a transition between them'); return; }
+ res.duration = d;
+ res.half = sbeRound(d / 2);
+ const word = res.kind.replace('_', ' ');
+ const needOut = res.half * sbeSpeed(a), needIn = res.half * sbeSpeed(b);
+ const short = [];
+ const tail = sbeTxSpare(a, 'tail');
+ if (tail === null) short.push('the source length of the outgoing clip is not known — run Prepare so the panel can measure it');
+ else if (tail + 1e-6 < needOut) short.push('the outgoing clip has only ' + tail.toFixed(2) + 's beyond its out-point and the ' + word + ' needs ' + needOut.toFixed(2) + 's there — trim its tail in or shorten the transition');
+ const head = sbeTxSpare(b, 'head');
+ if (head !== null && head + 1e-6 < needIn) short.push('the incoming clip has only ' + head.toFixed(2) + 's before its in-point and the ' + word + ' needs ' + needIn.toFixed(2) + 's there — trim its head in or shorten the transition');
+ if (short.length) { fail('transition_no_handles', short.join('; ')); return; }
+ out.push(res);
+ });
+ return out;
+}
+// The half-durations a clip's two ends give to transitions, for the preview.
+function sbeTxEdges(clips, txs, clipId, fps) {
+ const e = { head: 0, tail: 0 };
+ for (const r of sbeTxResolve(clips, txs, fps)) {
+ if (r.problem) continue;
+ if (r.after_clip === clipId) e.tail = r.half;
+ if (r.before_clip === clipId) e.head = r.half;
+ }
+ return e;
+}
+function sbeTxSet(txs, afterId, kind, duration) {
+ const out = (txs || []).map(t => Object.assign({}, t));
+ let t = sbeTxAfter(out, afterId);
+ if (!t) { t = { id: sbeNewId(), after_clip: afterId }; out.push(t); }
+ t.kind = (SBE_TX_KINDS.indexOf(kind) >= 0) ? kind : 'dissolve';
+ t.duration = sbeRound(Math.max(SBE_TX_MIN, Math.min(SBE_TX_MAX, sbeNum(duration, 0.5) || 0.5)));
+ return { transitions: out, ok: true, transition: t };
+}
+function sbeTxDelete(txs, afterId) {
+ const t = sbeTxAfter(txs, afterId);
+ if (!t) return { transitions: txs, ok: false, why: 'gone' };
+ return { transitions: (txs || []).filter(x => x.after_clip !== afterId), ok: true };
+}
+// Drops what no longer owns a boundary: a clip that left, or one that became
+// the last clip.
+function sbeTxPrune(txs, clips) {
+ const order = (clips || []).slice().sort((a, b) => sbeNum(a.film_start) - sbeNum(b.film_start));
+ const ok = {};
+ order.forEach((c, k) => { if (k + 1 < order.length) ok[c.id] = true; });
+ const seen = {};
+ return (txs || []).filter(t => {
+ if (!ok[t.after_clip] || seen[t.after_clip]) return false;
+ seen[t.after_clip] = true;
+ return true;
+ });
+}
+function sbeTxRepoint(txs, fromId, toId) {
+ return (txs || []).map(t => (t.after_clip === fromId)
+ ? Object.assign({}, t, { after_clip: toId }) : Object.assign({}, t));
+}
+// The lane's own door, the same shape as `sbeOvMutate`.
+function sbeTxMutate(fn) {
+ const before = sbeSnapshot();
+ const res = fn(SBE.transitions || []);
+ if (!res || res.ok === false) {
+ if (res && res.why) phosToast(res.why, {});
+ return false;
+ }
+ SBE.undo.push(before);
+ if (SBE.undo.length > SBE_UNDO_MAX) SBE.undo.shift();
+ SBE.redo.length = 0;
+ SBE.transitions = res.transitions;
+ SBE.dirty = true;
+ sbeSetState('unsaved changes', 'dirty');
+ sbePaint();
+ sbeQueueSave();
+ return res;
+}
+function sbeTxCommit(kind, duration) {
+ if (!SBE.txSel) return;
+ sbeBlurControl();
+ const after = SBE.txSel;
+ if (!kind || kind === 'none') { sbeTxRemoveSel(); return; }
+ sbeTxMutate(ts => sbeTxSet(ts, after, kind, duration));
+}
+function sbeTxRemoveSel() {
+ if (!SBE.txSel) return;
+ const after = SBE.txSel;
+ if (!sbeTxAfter(SBE.transitions, after)) { sbePaint(); return; }
+ sbeTxMutate(ts => sbeTxDelete(ts, after));
+}
+
function sbeStripOwned(c) {
if (sbeKind(c) !== 'video') return false;
if (sbeClipMuted(c)) return false; // muted plays from nowhere
@@ -1521,7 +1766,7 @@ function sbeStripsAt(clips, t) {
const from = w.film_start, to = sbeRound(w.film_start + w.len);
if (now < from - 1e-6 || now >= to) continue;
out.push({ id: c.id, path: c.path || '',
- at: sbeRound(w.start + (now - from)),
+ at: sbeRound(w.start + (now - from) * w.speed),
from: from, to: to });
}
out.sort((a, b) => (a.from - b.from) || String(a.id).localeCompare(String(b.id)));
@@ -1629,12 +1874,43 @@ function sbeById(clips, id) {
return null;
}
-function sbeMoveTo(clips, id, filmStart) {
+// HOW A DRAG BEHAVES — the NLE contract, 2026-09-05.
+// Premiere, Resolve and After Effects all agree on two defaults, and the owner
+// asked for exactly them: dragging a clip's BODY moves that clip and nothing
+// else (it slides in the room between its neighbours and stops at them), and
+// pulling an EDGE changes that clip's length and leaves everything after it
+// where it was — a hole opens or closes, the rest of the film does not move.
+// The old behaviour, where every gesture repacked the sequence and slid the
+// whole tail, is what those programs call a RIPPLE, and it is still here as a
+// modifier: hold ⌘ (or Ctrl) while dragging. Shift still reorders.
+function sbeMoveTo(clips, id, filmStart, opts) {
+ const ripple = !!(opts && opts.ripple);
const c = sbeById(clips, id);
if (!c) return { clips: clips, ok: false, why: 'gone' };
if (c.locked) return { clips: clips, ok: false, why: 'locked' };
const len = sbeLen(c);
- const want = Math.max(0, sbeNum(filmStart));
+ const want0 = Math.max(0, sbeNum(filmStart));
+ if (!ripple) {
+ // Between its neighbours, and the neighbours stay put: this clip's own
+ // gap sets where it lands, the next clip's gap is corrected by the same
+ // amount so its film position does not change.
+ const mark = sbeSyncMark(clips);
+ const i = clips.indexOf(c);
+ const prev = i > 0 ? clips[i - 1] : null;
+ const next = (i + 1 < clips.length) ? clips[i + 1] : null;
+ const floor = prev ? sbeNum(prev.film_end) : 0;
+ const ceil = next ? sbeNum(next.film_start) - len : Infinity;
+ if (ceil < floor - 1e-9) return { clips: clips, ok: false, why: 'tight' };
+ const want = Math.max(floor, Math.min(ceil, want0));
+ const nextStart = next ? sbeNum(next.film_start) : null;
+ c._gap = Math.max(0, sbeRound(want - floor));
+ if (next && !next.locked) next._gap = Math.max(0, sbeRound(nextStart - (want + len)));
+ sbeLayout(clips);
+ sbeSyncCarry(clips, mark, [id]);
+ c.source = 'human';
+ return { clips: clips, ok: true };
+ }
+ const want = want0;
const centre = want + len / 2;
const mark = sbeSyncMark(clips);
const rest = clips.filter(x => x !== c);
@@ -1661,13 +1937,20 @@ function sbeMoveTo(clips, id, filmStart) {
// the tail does not move and a hole opens behind it (holes are legal here —
// they are what the generate control fills). The right one changes the length,
// so everything after it ripples.
-function sbeTrim(clips, id, edge, filmTime) {
+function sbeTrim(clips, id, edge, filmTime, opts) {
+ // `opts.ripple` (⌘ / Ctrl held): the tail slides, as it did before
+ // 2026-09-05. Default: the other clips do not move — see sbeMoveTo.
+ const ripple = !!(opts && opts.ripple);
const c = sbeById(clips, id);
if (!c) return { clips: clips, ok: false, why: 'gone' };
if (c.locked) return { clips: clips, ok: false, why: 'locked' };
const mark = sbeSyncMark(clips);
+ // A DRAG IS FILM SECONDS; THE WINDOW IS SOURCE SECONDS. At 2x a handle
+ // pulled one second along the film moves the in- or out-point two seconds
+ // of the take, which is what keeps the slot following the pointer.
+ const sp = sbeSpeed(c);
if (edge === 'l') {
- const d = sbeNum(filmTime) - sbeNum(c.film_start);
+ const d = (sbeNum(filmTime) - sbeNum(c.film_start)) * sp;
let s = sbeNum(c.start) + d;
s = Math.max(0, Math.min(sbeNum(c.end) - SBE_MIN_CLIP, s));
// A HEAD TRIM MOVES THE SLOT WITH THE IN-POINT OR IT IS NOT A TRIM. The
@@ -1679,20 +1962,32 @@ function sbeTrim(clips, id, edge, filmTime) {
// no longer plays under it. Trimming may not change the film→source
// mapping of the frames it keeps; that invariant is what makes "the sound
// stays put" correct rather than lucky.
- const room = Math.max(0, sbeNum(c._gap));
- if (s < sbeNum(c.start) - room) s = sbeRound(sbeNum(c.start) - room);
+ const room = Math.max(0, sbeNum(c._gap)) * sp;
+ if (!ripple && s < sbeNum(c.start) - room) s = sbeRound(sbeNum(c.start) - room);
const applied = s - sbeNum(c.start);
if (Math.abs(applied) < 1e-9) return { clips: clips, ok: false, why: 'edge' };
c.start = sbeRound(s);
- c._gap = Math.max(0, sbeRound(sbeNum(c._gap) + applied));
+ // Ripple on the head: the head stays where the previous clip ends and
+ // everything after slides by the length change (the gap is left alone).
+ if (!ripple) c._gap = Math.max(0, sbeRound(sbeNum(c._gap) + applied / sp));
} else {
- const d = sbeNum(filmTime) - sbeNum(c.film_end);
+ const d = (sbeNum(filmTime) - sbeNum(c.film_end)) * sp;
let e = sbeNum(c.end) + d;
const srcDur = sbeNum(c.duration, 0);
if (srcDur > 0) e = Math.min(srcDur, e);
e = Math.max(sbeNum(c.start) + SBE_MIN_CLIP, e);
+ const i = clips.indexOf(c);
+ const next = (i + 1 < clips.length) ? clips[i + 1] : null;
+ if (!ripple && next) {
+ // The clip may grow into the hole after it, never into the next clip.
+ const room = Math.max(0, sbeNum(next._gap)) * sp;
+ e = Math.min(e, sbeNum(c.end) + room);
+ }
if (Math.abs(e - sbeNum(c.end)) < 1e-9) return { clips: clips, ok: false, why: 'edge' };
+ const grew = (e - sbeNum(c.end)) / sp; // film seconds
c.end = sbeRound(e);
+ // Default: the next clip does not move — its gap takes the difference.
+ if (!ripple && next && !next.locked) next._gap = Math.max(0, sbeRound(sbeNum(next._gap) - grew));
}
c.source = 'human';
sbeLayout(clips);
@@ -1703,6 +1998,32 @@ function sbeTrim(clips, id, edge, filmTime) {
return { clips: clips, ok: true };
}
+// DUPLICATE: the same shot again, right after itself, with everything it
+// carries — window, speed, fades, grade, mute — and its sound LINKED: a
+// copied J-cut strip would sit under the original's seconds, which is the
+// one overlap the sound lane refuses. The copy is its own clip from then on.
+function sbeDuplicate(clips, id) {
+ const c = sbeById(clips, id);
+ if (!c) return { clips: clips, ok: false, why: 'gone' };
+ const mark = sbeSyncMark(clips);
+ const b = JSON.parse(JSON.stringify(c));
+ for (const k of Object.keys(b)) if (k.charAt(0) === '_') delete b[k];
+ b.id = sbeNewId();
+ delete b.audio;
+ b.locked = false;
+ b.source = 'human';
+ b._gap = 0;
+ // NAMED AS A COPY, or two identical blocks side by side cannot be told
+ // apart — the review pressed D twice and could not say which was which.
+ const base = String(c.title || String(c.path || '').split('/').pop() || 'clip').replace(/ \(copy( \d+)?\)$/, '');
+ b.title = base + ' (copy)';
+ const out = clips.slice();
+ out.splice(out.indexOf(c) + 1, 0, b);
+ sbeLayout(out);
+ sbeSyncCarry(out, mark, [b.id]);
+ return { clips: out, ok: true, added: b };
+}
+
function sbeRippleDelete(clips, id) {
const c = sbeById(clips, id);
if (!c) return { clips: clips, ok: false, why: 'gone' };
@@ -1737,11 +2058,13 @@ function sbeLiftDelete(clips, id) {
return { clips: out, ok: true, removed: c };
}
-function sbeSplitAt(clips, t, newId) {
+function sbeSplitAt(clips, t, newId, transitions) {
const c = sbeClipAt(clips, t);
if (!c) return { clips: clips, ok: false, why: 'nothing there' };
if (c.locked) return { clips: clips, ok: false, why: 'locked' };
+ // `off` is FILM seconds into the slot; the cut in the take is `off * speed`.
const off = sbeNum(t) - sbeNum(c.film_start);
+ const sp = sbeSpeed(c);
if (off < SBE_MIN_CLIP || sbeLen(c) - off < SBE_MIN_CLIP) {
return { clips: clips, ok: false, why: 'too close to an edge' };
}
@@ -1754,8 +2077,8 @@ function sbeSplitAt(clips, t, newId) {
const w = sbeClipAudio(c);
let cutA = null, cutB = null;
if (w.split) {
- const sp = sbeRound(sbeNum(c.start) + off);
- if (sp < w.start + SBE_MIN_CLIP || sp > w.end - SBE_MIN_CLIP) {
+ const sp2 = sbeRound(sbeNum(c.start) + off * sp);
+ if (sp2 < w.start + SBE_MIN_CLIP || sp2 > w.end - SBE_MIN_CLIP) {
// The strip has been trimmed to a window this cut falls outside, so one
// half would end up with no sound at all — a state the document cannot
// express (an absent `audio` means LINKED, which would invent sound the
@@ -1764,16 +2087,16 @@ function sbeSplitAt(clips, t, newId) {
why: 'the unlinked sound does not reach this cut — move the '
+ 'strip back or re-link it first' };
}
- cutA = sbeAudioField({ start: w.start, end: sp,
+ cutA = sbeAudioField({ start: w.start, end: sp2,
film_start: w.film_start }, w.coupled);
- cutB = sbeAudioField({ start: sp, end: w.end,
- film_start: w.film_start + (sp - w.start) },
+ cutB = sbeAudioField({ start: sp2, end: w.end,
+ film_start: w.film_start + (sp2 - w.start) / sp },
w.coupled);
}
const mark = sbeSyncMark(clips);
const b = JSON.parse(JSON.stringify(c));
b.id = newId || sbeNewId();
- b.start = sbeRound(sbeNum(c.start) + off);
+ b.start = sbeRound(sbeNum(c.start) + off * sp);
b._gap = 0;
b.source = 'human';
c.end = b.start;
@@ -1785,7 +2108,12 @@ function sbeSplitAt(clips, t, newId) {
// Both halves were just given the position they are meant to have; the
// reflow only ever moves what is AFTER them.
sbeSyncCarry(out, mark, [c.id, b.id]);
- return { clips: out, ok: true, added: b };
+ const res = { clips: out, ok: true, added: b };
+ // A TRANSITION AFTER THE SPLIT CLIP NOW FOLLOWS ITS SECOND HALF — that is
+ // the half that owns the boundary the transition was on. Left on the first
+ // half it would move to the fresh cut in the middle of the shot.
+ if (transitions) res.transitions = sbeTxRepoint(transitions, c.id, b.id);
+ return res;
}
function sbeNewId() {
@@ -1869,6 +2197,38 @@ function sbeBrightnessCss(b) {
return Math.max(0, sbeRound(1 + 2 * sbeNum(b)));
}
+// FRAMING — the mirror of `clip_frame()`: zoom 1–3 and the anchor as
+// fractions, clamped, neutral when absent. A slug has nothing to reframe.
+const SBE_FRAME_ZOOM_MAX = 3.0;
+function sbeFraming(c) {
+ const f = (c && c.frame && typeof c.frame === 'object') ? c.frame : {};
+ let z = sbeNum(f.zoom, 1);
+ if (!(z > 0)) z = 1;
+ z = Math.max(1, Math.min(SBE_FRAME_ZOOM_MAX, z));
+ const cl = (v) => Math.max(0, Math.min(1, sbeNum(v, 0.5)));
+ return { zoom: sbeRound(z), x: sbeRound(cl(f.x)), y: sbeRound(cl(f.y)) };
+}
+function sbeFramingIsNeutral(c) { return Math.abs(sbeFraming(c).zoom - 1) < 1e-9; }
+function sbeSetFraming(clips, id, field, v) {
+ const c = sbeById(clips, id);
+ if (!c) return { clips: clips, ok: false, why: 'gone' };
+ if (c.locked) return { clips: clips, ok: false, why: 'locked' };
+ if (sbeKind(c) === 'slug') return { clips: clips, ok: false, why: 'black has nothing to reframe' };
+ const cur = sbeFraming(c);
+ const next = Object.assign({}, cur);
+ next[field] = sbeNum(v, cur[field]);
+ const fr = sbeFraming({ frame: next });
+ if (Math.abs(fr.zoom - cur.zoom) < 1e-9 && Math.abs(fr.x - cur.x) < 1e-9 && Math.abs(fr.y - cur.y) < 1e-9) {
+ return { clips: clips, ok: false, why: '' };
+ }
+ const out = clips.map(x => Object.assign({}, x));
+ const t = sbeById(out, id);
+ // NEUTRAL IS ABSENT: zoom 1 is no field, whatever the anchor says.
+ if (Math.abs(fr.zoom - 1) < 1e-9) delete t.frame; else t.frame = fr;
+ t.source = 'human';
+ return { clips: out, ok: true };
+}
+
function sbeSetBrightness(clips, id, v) {
const c = sbeById(clips, id);
if (!c) return { clips: clips, ok: false, why: 'gone' };
@@ -1979,6 +2339,12 @@ function sbeCleanClip(c) {
const b = sbeBright(out);
if (Math.abs(b) < 1e-6) delete out.adjust;
else out.adjust = { brightness: sbeRound(b) };
+ // 1x is the absence of the field, the same way the server writes it.
+ const sp = sbeSpeed(c);
+ if (kind !== 'video' || Math.abs(sp - 1) < 1e-9) delete out.speed;
+ else out.speed = sp;
+ if (kind === 'slug' || sbeFramingIsNeutral(c)) delete out.frame;
+ else out.frame = sbeFraming(c);
return out;
}
@@ -1992,6 +2358,8 @@ function sbeSaveBody(state) {
for (const k of Object.keys(o)) if (k.charAt(0) !== '_') out[k] = o[k];
return out;
});
+ // THE BOUNDARIES TRAVEL TOO. An empty list is the server's absent key.
+ edit.transitions = (state.transitions || []).map(t => Object.assign({}, t));
edit.board_id = state.id;
const body = { id: state.id, edit: edit };
if (state.expect !== null && state.expect !== undefined) body.expect_revision = state.expect;
@@ -2452,13 +2820,16 @@ function sbeAdopt(r, quiet) {
SBE.unplaced = r.unplaced || [];
SBE.pool = r.clips || [];
SBE.relink = r.relink || [];
+ SBE.sections = r.sections || [];
SBE.prepare = r.prepare || {};
if (r.drafts) SBE.drafts = r.drafts;
if (r.active_draft !== undefined) SBE.activeDraft = r.active_draft || '';
SBE.backup = r.backup || null;
SBE.backupHidden = false; // a NEW offer is not the one dismissed
SBE.overlays = (SBE.edit.overlays || []).map(o => Object.assign({}, o));
+ SBE.transitions = (SBE.edit.transitions || []).map(t => Object.assign({}, t));
SBE.ovSel = '';
+ SBE.txSel = '';
SBE.clips = sbeAdoptGaps((SBE.edit.clips || []).map(c => Object.assign({}, c)));
sbeLayout(SBE.clips);
SBE.dirty = false;
@@ -2483,6 +2854,7 @@ function sbeAdopt(r, quiet) {
sbePaintDraft();
sbePaintRecovery();
sbePaintRelink();
+ sbeDeliverPaint();
if (ED.src === 'film') edPoolRefresh();
sbeFetchPeaks();
sbePaint();
@@ -2617,6 +2989,7 @@ function sbeSnapshot(audio) {
// this a card placed and then undone would stay on screen while the
// pictures walked back without it.
overlays: SBE.overlays || [],
+ transitions: SBE.transitions || [],
audio: (audio === undefined)
? (SBE.audio || (SBE.edit && SBE.edit.audio) || null) : audio,
});
@@ -2630,6 +3003,7 @@ function sbeRestore(json) {
// `overlays`, and restoring `undefined` over a live lane would delete a
// card nobody asked to remove — absent means "unchanged", not "empty".
if (s.overlays !== undefined) SBE.overlays = s.overlays || [];
+ if (s.transitions !== undefined) SBE.transitions = s.transitions || [];
SBE.edit = SBE.edit || {};
// ...and a restore never COMMITS a discovered track into the document. The
// arrangement owns a soundtrack only once somebody has placed it (see
@@ -2702,6 +3076,11 @@ function sbeMutate(fn) {
if (SBE.undo.length > SBE_UNDO_MAX) SBE.undo.shift();
SBE.redo.length = 0;
SBE.clips = res.clips;
+ // A CLIP THAT LEFT TAKES ITS BOUNDARY WITH IT. Any mutation may remove or
+ // reorder clips; a transition naming a clip that is gone, or one that has
+ // become the last clip, is pruned here rather than refused at the save.
+ if (res.transitions) SBE.transitions = res.transitions;
+ SBE.transitions = sbeTxPrune(SBE.transitions || [], SBE.clips);
SBE.dirty = true;
sbeSetState('unsaved changes', 'dirty');
sbePaint();
@@ -3598,6 +3977,11 @@ function sbePaint() {
sbePaintWave(span, width);
sbePaintMusic(width);
sbePaintOverlays();
+ // THE STAGE'S CARD FOLLOWS THE LANE. A title removed from the lane (or
+ // undone back onto it) must leave or return on the monitor in the same
+ // paint, not on the next scrub — the review caught a deleted title still
+ // painting over the picture.
+ sbeOvPaint();
sbePaintTrack();
sbePaintAudioLane();
sbePaintHead();
@@ -3823,8 +4207,35 @@ function sbePaintRuler(span, width) {
html += '<i style="left:' + x.toFixed(1) + 'px"></i>' +
'<b style="left:' + x.toFixed(1) + 'px">' + lab + '</b>';
}
+ // THE SONG'S SECTIONS, as faint bands behind the ticks: the arc the
+ // Director cut to, on the film's clock. Track seconds become film seconds
+ // through the same music window the bed and the beat grid use, so a
+ // trimmed or slid soundtrack moves its sections with it.
+ html += sbeSectionBands(SBE.sections, SBE.audio, SBE.peaks ? SBE.peaks.duration : 0, span);
r.innerHTML = html;
r.style.width = width + 'px';
+ if (r.classList) r.classList.toggle('has-sections', !!(SBE.sections && SBE.sections.length));
+}
+
+function sbeSectionBands(sections, audio, trackDur, span) {
+ if (!sections || !sections.length) return '';
+ const w = sbeMusicWindow(audio || {}, trackDur || 0);
+ let out = '';
+ for (const s of sections) {
+ const a = w.film_start + (sbeNum(s.start) - w.head);
+ const b = w.film_start + (sbeNum(s.end) - w.head);
+ const x0 = Math.max(0, a), x1 = Math.min(span, b);
+ if (x1 - x0 <= 1e-6) continue;
+ const px = sbePx(x1 - x0);
+ const e = sbeNum(s.energy);
+ const heat = e >= 0.75 ? 'loud' : (e <= 0.35 ? 'quiet' : 'steady');
+ out += '<u class="sbe-sec is-' + escapeHtml(String(s.label || 'verse')) + '" ' +
+ 'title="' + escapeHtml(String(s.label || '') + ' · ' + sbeFmtTime(x0) + '–' + sbeFmtTime(x1)
+ + ' · ' + heat + ' — the Director cuts ' + (String(s.label) === 'chorus' ? 'fastest' : (String(s.label) === 'intro' || String(s.label) === 'outro' ? 'slowest' : 'at the base pace') + ' here')) + '" ' +
+ 'style="left:' + sbePx(x0).toFixed(1) + 'px;width:' + px.toFixed(1) + 'px">' +
+ (px > 40 ? escapeHtml(String(s.label || '')) : '') + '</u>';
+ }
+ return out;
}
function sbePaintWave(span, width) {
@@ -3938,7 +4349,7 @@ function sbePaintMusic(width) {
sbeEl('sbeMusicName').textContent = (right - left > 120) ? label : '';
el.title = name + '\nStarts at ' + sbeFmtTime(w.film_start) +
' of the __SEQ__, from ' + sbeFmtTime(w.head) + ' of the track.' +
- '\nDrag to place it · pull either end to trim · hold Alt to ignore the cuts.' +
+ '\nDrag to move it (the others stay) · pull either end to trim · hold Alt to ignore the cuts · hold ⌘ to slide everything after it.' +
'\nCorners fade it · double-click the level line to add a point.';
sbePaintBedLevel(el, Math.max(3, right - left));
}
@@ -4365,26 +4776,31 @@ function sbePaintTrack() {
const kind = sbeKind(c);
const bright = sbeBright(c);
const bad = SBE.errors.byId && SBE.errors.byId[c.id];
+ const sp = sbeSpeed(c);
const flag = c.locked ? 'lock'
+ : (Math.abs(sp - 1) >= 1e-6 ? sp.toFixed(2).replace(/\.?0+$/, '') + 'x'
: (Math.abs(bright) >= 1e-6
? (bright > 0 ? '+' : '') + bright.toFixed(2)
// "slow" is a VIDEO's problem. A still has no proxy because it needs
// none and a slug has no file at all, so flagging either as
// un-scrubbable would be advice to run a Prepare that would do
// nothing.
- : (kind === 'video' && !c.proxy ? 'slow' : ''));
+ : (kind === 'video' && !c.proxy ? 'slow' : '')));
const cls = 'sbe-clip is-' + kind + (c.id === SBE.sel ? ' is-sel' : '')
+ (c.id === SBE.curId ? ' is-playing' : '')
+ (bad ? ' is-bad' : '') + (c.locked ? ' is-locked' : '')
+ (Math.abs(bright) >= 1e-6 ? ' is-graded' : '')
+ + (Math.abs(sp - 1) >= 1e-6 ? ' is-retimed' : '')
+ + (!sbeFramingIsNeutral(c) ? ' is-framed' : '')
+ (flag ? ' has-flag' : '');
// A still and a slug have no source window to report — their only number
// is the hold, and printing "0.00→3.00" of a clock they do not have reads
// as a trim somebody made.
const meta = (kind === 'video')
? (sbeNum(c.start).toFixed(2) + '→' + sbeNum(c.end).toFixed(2) +
- ' · ' + sbeLen(c).toFixed(2) + 's')
- : (sbeLen(c).toFixed(2) + 's hold');
+ ' · ' + sbeLen(c).toFixed(2) + 's' + (Math.abs(sp - 1) >= 1e-6 ? ' @' + sp + 'x' : '')
+ + (!sbeFramingIsNeutral(c) ? ' · \u2316' + sbeFraming(c).zoom.toFixed(1) + 'x' : ''))
+ : (sbeLen(c).toFixed(2) + 's hold' + (!sbeFramingIsNeutral(c) ? ' · \u2316' + sbeFraming(c).zoom.toFixed(1) + 'x' : ''));
const label = (kind === 'slug')
? 'black'
: (c.title || String(c.path || '').split('/').pop() || 'clip');
@@ -4419,6 +4835,37 @@ function sbePaintTrack() {
+ '</div>';
}
track.innerHTML = html;
+ // THE CUTS, each one a handle. A transition is not a lane and not a block:
+ // it is a property of the boundary between two clips, so that is where it
+ // is found — a small mark on every cut, a band the length of the
+ // transition once one exists, and the inspector to set it. Drawn AFTER the
+ // blocks so it sits on top of both grips.
+ const order = SBE.clips.slice().sort((a, b) => sbeNum(a.film_start) - sbeNum(b.film_start));
+ const resolved = sbeTxResolve(order, SBE.transitions || [], sbeFps());
+ for (let k = 0; k + 1 < order.length; k++) {
+ const a = order[k], b = order[k + 1];
+ const at = sbeNum(a.film_end);
+ if (sbeNum(b.film_start) - at > 0.5 / sbeFps()) continue; // a hole, not a cut
+ const r = resolved.find(x => x.after_clip === a.id) || null;
+ const sel = SBE.txSel === a.id;
+ const bad = r && r.problem;
+ const x = sbePx(at);
+ if (r && !bad) {
+ const w = Math.max(6, sbePx(r.duration));
+ html = '<div class="sbe-cut is-tx is-' + r.kind + (sel ? ' is-sel' : '') + '" data-after="'
+ + escapeHtml(a.id) + '" title="' + escapeHtml(SBE_TX_LABELS[r.kind] + ' · '
+ + r.duration.toFixed(2) + 's, centred on the cut. Click to change it.')
+ + '" style="left:' + (x - w / 2).toFixed(1) + 'px;width:' + w.toFixed(1) + 'px">'
+ + (w > 44 ? '<span>' + escapeHtml((r.kind === 'dissolve' ? '\u2715 ' : '\u25d1 ')
+ + r.duration.toFixed(2) + 's') + '</span>' : '') + '</div>';
+ } else {
+ html = '<div class="sbe-cut' + (sel ? ' is-sel' : '') + (bad ? ' is-bad' : '')
+ + '" data-after="' + escapeHtml(a.id) + '" title="'
+ + escapeHtml(bad ? r.problem.message : 'Cut. Click to put a transition here.')
+ + '" style="left:' + (x - 6).toFixed(1) + 'px"></div>';
+ }
+ track.insertAdjacentHTML('beforeend', html);
+ }
track.style.width = sbeEl('sbeInner').style.width;
if (SBE.dropAt !== null && SBE.dropAt !== undefined) {
const line = document.createElement('div');
@@ -4604,16 +5051,22 @@ function sbePaintOverlays() {
const x = sbePx(sbeNum(o.film_start));
const w = Math.max(2, sbePx(sbeNum(o.film_end) - sbeNum(o.film_start)));
const e = sbeFx(o);
- const name = sbeNiceName(o.title || String(o.path || '').split('/').pop() || 'card');
- html += '<div class="sbe-ov' + (o.id === SBE.ovSel ? ' is-sel' : '') + '" '
+ const okind = sbeOvKind(o);
+ const name = (okind === 'text')
+ ? (sbeOvText(o).text.split('\n')[0] || 'Title')
+ : sbeNiceName(o.title || String(o.path || '').split('/').pop() || 'card');
+ html += '<div class="sbe-ov is-' + okind + (o.id === SBE.ovSel ? ' is-sel' : '') + '" '
+ 'data-id="' + escapeHtml(o.id) + '" '
- + 'title="' + escapeHtml('Overlay — composited over the picture. '
+ + 'title="' + escapeHtml((okind === 'text'
+ ? 'Title — drawn over the picture. '
+ : 'Overlay — composited over the picture. ')
+ 'Drag to move, pull either end to change how long.') + '" '
+ 'style="left:' + x.toFixed(1) + 'px;width:' + w.toFixed(1) + 'px">'
- + (sbeOvKind(o) === 'still' && o.path
+ + (okind === 'still' && o.path
? '<img class="sbe-ov-thumb" alt="" src="/image?w=240&path='
+ encodeURIComponent(o.path) + '">'
: '')
+ + (okind === 'text' ? '<span class="sbe-ov-t">T</span>' : '')
+ (w > 60 ? escapeHtml(name) : '')
+ (e.fade_in > 1e-9 ? '<div class="sbe-cl-fade in" style="left:0;width:'
+ sbePx(e.fade_in).toFixed(1) + 'px"></div>' : '')
@@ -4626,8 +5079,8 @@ function sbePaintOverlays() {
// the four pool sources already follow. Without it the overlay lane is a
// strip of nothing that teaches nobody it exists.
lane.innerHTML = html || '<div class="sbe-track-empty sbe-ovlane-empty">'
- + 'Overlay lane — drop a still here, or press \u25a3 on an image in the '
- + 'media pool to lay it over the picture at the playhead.</div>';
+ + 'Overlay lane — drop a still here, press \u25a3 on an image in the '
+ + 'media pool, or Add title for text over the picture at the playhead.</div>';
lane.style.width = sbeEl('sbeInner').style.width;
}
@@ -4636,21 +5089,137 @@ function sbePaintOverlays() {
function sbeOvPaint(t) {
const el = sbeEl('sbeOvLayer');
if (!el || !el.classList) return;
+ const tx = sbeEl('sbeOvText');
const now = (t === undefined) ? SBE.playhead : sbeNum(t);
const o = sbeOvAt(SBE.overlays, now);
- if (!o || !o.path) { el.classList.remove('is-on'); return; }
+ const txOff = () => { if (tx && tx.classList) tx.classList.remove('is-on'); };
+ if (!o) { el.classList.remove('is-on'); txOff(); return; }
+ if (sbeOvKind(o) === 'text') {
+ // A TITLE IS DRAWN IN THE DOM, not re-rendered: the same string, the same
+ // anchor and the same size rule (`font_size` at 1080 high, scaled to
+ // the stage) the rasteriser uses, so what is on the stage is what lands
+ // in the file. The stage's own height is the scale; the style values
+ // are written as custom properties and the stylesheet does the rest.
+ el.classList.remove('is-on');
+ if (!tx || !tx.classList) return;
+ const tt = sbeOvText(o);
+ const st = tt.style;
+ const stage = sbeEl('sbeStage');
+ const H = (stage && stage.clientHeight) ? stage.clientHeight : SBE_TEXT_REF_H;
+ if (tx.textContent !== tt.text) tx.textContent = tt.text;
+ tx.style.setProperty('--tx-size', (st.font_size * H / SBE_TEXT_REF_H).toFixed(2) + 'px');
+ tx.style.setProperty('--tx-color', st.color);
+ tx.style.setProperty('--tx-y', (st.y * 100).toFixed(3) + '%');
+ tx.style.setProperty('--tx-align', st.align);
+ tx.style.setProperty('--tx-box', st.box ? sbeRgba(st.box_color, st.box_opacity) : 'transparent');
+ tx.style.opacity = String(sbeFadeOpacityAt(o, now));
+ tx.classList.add('is-on');
+ sbeOvTextPlace(tx, st, stage);
+ return;
+ }
+ txOff();
+ if (!o.path) { el.classList.remove('is-on'); return; }
const url = '/image?w=1280&path=' + encodeURIComponent(o.path);
if (el.getAttribute('src') !== url) el.setAttribute('src', url);
el.style.opacity = String(sbeFadeOpacityAt(o, now));
el.classList.add('is-on');
}
+// WHERE THE BOX SITS, IN PIXELS, KEPT INSIDE THE FRAME. The anchor is a
+// fraction and the align says which edge of the text sits on it; measured
+// against the stage so a wide title at x=0.2 is pushed back in rather than
+// cut at the frame's edge — the same clamp `render_title` applies.
+function sbeOvTextPlace(tx, st, stage) {
+ const W = (stage && stage.clientWidth) ? stage.clientWidth : 0;
+ const tw = (tx && tx.offsetWidth) ? tx.offsetWidth : 0;
+ const shift = st.align === 'left' ? 0 : (st.align === 'right' ? 1 : 0.5);
+ if (!W || !tw || !tx.style || !tx.style.setProperty) {
+ if (tx && tx.style && tx.style.setProperty) {
+ tx.style.setProperty('--tx-left', (st.x * 100).toFixed(3) + '%');
+ tx.style.setProperty('--tx-shift', (-shift * 100) + '%');
+ }
+ return;
+ }
+ let left = st.x * W - tw * shift;
+ left = Math.max(0, Math.min(W - tw, left));
+ tx.style.setProperty('--tx-left', left.toFixed(1) + 'px');
+ tx.style.setProperty('--tx-shift', '0%');
+}
+
+function sbeRgba(hex, alpha) {
+ const h = sbeHexColour(hex, '#000000').slice(1);
+ return 'rgba(' + parseInt(h.slice(0, 2), 16) + ',' + parseInt(h.slice(2, 4), 16)
+ + ',' + parseInt(h.slice(4, 6), 16) + ',' + Math.max(0, Math.min(1, sbeNum(alpha))).toFixed(3) + ')';
+}
+
+// THE TITLE'S ONE DOOR. Every field on a title — its text, its size, where
+// it sits — goes through here, as one undo step and one queued snapshot,
+// the way every other overlay edit does.
+function sbeOvTextCommit(field, value) {
+ if (!SBE.ovSel) return;
+ sbeBlurControl();
+ const id = SBE.ovSel;
+ sbeOvMutate(os => {
+ const o = sbeOvById(os, id);
+ if (!o || sbeOvKind(o) !== 'text') return { overlays: os, ok: false, why: 'gone' };
+ const out = os.map(x => Object.assign({}, x));
+ const t = sbeOvById(out, id);
+ if (field === 'text') {
+ const s = String(value || '').replace(/\r\n?/g, '\n').slice(0, SBE_TEXT_MAX);
+ if (!s.trim()) return { overlays: os, ok: false, why: 'a title needs some text' };
+ if (s === String(t.text || '')) return { overlays: os, ok: false, why: '' };
+ t.text = s;
+ } else {
+ const st = Object.assign({}, t.style || {});
+ if (field === 'box') st.box = !!value;
+ else if (field === 'align') st.align = String(value);
+ else if (field === 'color' || field === 'box_color') st[field] = sbeHexColour(value, SBE_TEXT_DEFAULTS[field]);
+ else st[field] = sbeNum(value, SBE_TEXT_DEFAULTS[field]);
+ // NEUTRAL IS ABSENT, the server's rule: a style back at the defaults
+ // is no style.
+ const clean = sbeOvText({ style: st }).style;
+ const keep = {};
+ for (const k of Object.keys(clean)) if (clean[k] !== SBE_TEXT_DEFAULTS[k]) keep[k] = clean[k];
+ if (Object.keys(keep).length) t.style = keep; else delete t.style;
+ if (JSON.stringify(t.style || null) === JSON.stringify(o.style || null)) {
+ return { overlays: os, ok: false, why: '' };
+ }
+ }
+ t.source = 'human';
+ return { overlays: out, ok: true };
+ });
+ sbeOvPaint();
+}
+
+// ADD TITLE: a text overlay at the playhead, selected, with the inspector's
+// text box focused so the next thing typed is the title. No modal, no
+// prompt — the inspector is where every other property of an overlay lives,
+// so it is where the text lives too.
+function edAddTitle() {
+ if (!SBE.open || !SBE.id) {
+ phosToast('Open a __SEQ__ first — a title belongs to a timeline.', {});
+ return;
+ }
+ const res = sbeOvMutate(os => sbeOvAdd(os, { kind: 'text', text: 'Title',
+ title: 'Title', duration_s: 3 },
+ SBE.playhead));
+ if (!res || !res.added) return;
+ SBE.ovSel = res.added.id;
+ SBE.sel = '';
+ SBE.txSel = '';
+ sbePaint();
+ sbeOvPaint();
+ const box = sbeEl('sbeOvTextBox');
+ if (box && box.focus) { try { box.focus(); box.select && box.select(); } catch (e) {} }
+}
+
function sbeOnOvDown(ev) {
const blk = ev.target.closest ? ev.target.closest('.sbe-ov') : null;
if (!blk) { SBE.ovSel = ''; sbePaint(); return; }
const id = blk.dataset.id;
SBE.ovSel = id;
SBE.sel = '';
+ SBE.txSel = '';
const o = sbeOvById(SBE.overlays, id);
if (!o) return;
const grip = ev.target.closest('.sbe-grip');
@@ -5377,12 +5946,62 @@ function sbePaintKeys() {
function sbePaintInspector() {
const box = sbeEl('sbeInspect');
+ // A SELECTED CUT OWNS THE INSPECTOR. The boundary between two clips is a
+ // subject in its own right — it is what a transition is a property of —
+ // so it gets the same box every other subject gets, and the same shape:
+ // what it is, then its controls.
+ if (SBE.txSel && !SBE.sel && !SBE.ovSel) {
+ const order = SBE.clips.slice().sort((p, q) => sbeNum(p.film_start) - sbeNum(q.film_start));
+ const k = order.findIndex(c => c.id === SBE.txSel);
+ const a = order[k], b = order[k + 1];
+ if (!a || !b) { SBE.txSel = ''; }
+ else {
+ const row = sbeTxAfter(SBE.transitions, a.id);
+ const r = sbeTxResolve(order, SBE.transitions || [], sbeFps()).find(x => x.after_clip === a.id) || null;
+ const name = (c) => (sbeKind(c) === 'slug') ? 'black'
+ : sbeNiceName(c.title || String(c.path || '').split('/').pop() || 'clip');
+ const kind = row ? String(row.kind) : 'none';
+ const dur = row ? sbeNum(row.duration, 0.5) : 0.5;
+ const opt = (v, label) => '<option value="' + v + '"' + (kind === v ? ' selected' : '') + '>' + label + '</option>';
+ const cap = Math.max(SBE_TX_MIN, Math.min(SBE_TX_MAX, 0.5 * Math.min(sbeLen(a), sbeLen(b))));
+ const why = !row
+ ? 'A transition here pulls ' + 'extra picture from beyond each clip\'s trim — '
+ + 'the cut itself does not move, and neither does the sound.'
+ : (r && r.problem ? r.problem.message
+ : (r ? SBE_TX_LABELS[r.kind] + ' over ' + r.duration.toFixed(2) + 's, centred on the cut: '
+ + r.half.toFixed(2) + 's of handle each side. '
+ + (r.kind === 'dissolve'
+ ? 'The preview only approximates it (one picture at a time); the render is a true dissolve.'
+ : 'The preview shows it; the render is exact.') : ''));
+ box.innerHTML =
+ '<b>Cut · ' + escapeHtml(name(a)) + ' \u2192 ' + escapeHtml(name(b)) + '</b>' +
+ '<span>at ' + sbeNum(a.film_end).toFixed(2) + 's on the __SEQ__</span>' +
+ '<div class="sbe-sect"><div class="sbe-sect-h">Transition</div>' +
+ '<div class="sbe-sect-b">' +
+ '<span class="sbe-fade-row"><label for="sbeTxKind">Kind</label>' +
+ '<select class="sb-input sbe-tx-kind" id="sbeTxKind" ' +
+ 'onchange="sbeTxCommit(this.value, sbeEl(\'sbeTxDur\').value)">' +
+ opt('none', 'None — a hard cut') + opt('dissolve', 'Dissolve') +
+ opt('fade_black', 'Fade through black') + '</select></span>' +
+ '<span class="sbe-fade-row"><label for="sbeTxDur">Length</label>' +
+ '<input type="number" class="sb-input sbe-fade-num" id="sbeTxDur" min="' +
+ SBE_TX_MIN.toFixed(2) + '" max="' + cap.toFixed(2) + '" step="0.05" value="' + dur.toFixed(2) + '" ' +
+ 'onchange="sbeTxCommit(sbeEl(\'sbeTxKind\').value, this.value)" ' +
+ 'title="Seconds, centred on the cut. Snapped to an even number of frames.">' +
+ '<span class="sbe-adj-val">s</span></span>' +
+ (row ? '<button type="button" class="ghost-btn" onclick="sbeTxRemoveSel()">Remove</button>' : '') +
+ '</div></div>' +
+ '<span class="sbe-why' + (r && r.problem ? ' is-bad' : '') + '">' + escapeHtml(why) + '</span>';
+ return;
+ }
+ }
// A SELECTED CARD OWNS THE INSPECTOR. It is a lane of its own, so it gets
// the same two sections that mean anything for it — what it is, and its
// effects — and none of the Sound section, which it has no half of.
const ov = sbeOvById(SBE.overlays, SBE.ovSel);
if (ov && !SBE.sel) {
const oe = sbeFx(ov);
+ const okind = sbeOvKind(ov);
const orow = (edge, val) =>
'<span class="sbe-fade-row">' +
'<label for="sbeOvFade' + edge + '">Fade ' + edge + '</label>' +
@@ -5390,20 +6009,67 @@ function sbePaintInspector() {
'min="0" step="0.05" value="' + val.toFixed(2) + '" ' +
'onchange="sbeOvFadeCommit(\'' + edge + '\', this.value)">' +
'<span class="sbe-adj-val">s</span></span>';
+ // A TITLE'S OWN SECTION. The text and how it sits, beside the same
+ // Effects every overlay has — a title is a card the render draws, and
+ // the inspector says so by giving it the card's box plus one section.
+ let textSect = '';
+ if (okind === 'text') {
+ const tt = sbeOvText(ov);
+ const st = tt.style;
+ const alignOpt = (v, l) => '<option value="' + v + '"' + (st.align === v ? ' selected' : '') + '>' + l + '</option>';
+ textSect =
+ '<div class="sbe-sect"><div class="sbe-sect-h">Text</div>' +
+ '<div class="sbe-sect-b sbe-title-b">' +
+ '<textarea class="sb-input sbe-title-text" id="sbeOvTextBox" rows="2" maxlength="' + SBE_TEXT_MAX + '" ' +
+ 'placeholder="What the title says" onchange="sbeOvTextCommit(\'text\', this.value)">' +
+ escapeHtml(tt.text) + '</textarea>' +
+ '<span class="sbe-fade-row"><label for="sbeOvTxSize">Size</label>' +
+ '<input type="number" class="sb-input sbe-fade-num" id="sbeOvTxSize" min="8" max="400" step="4" ' +
+ 'value="' + st.font_size.toFixed(0) + '" onchange="sbeOvTextCommit(\'font_size\', this.value)" ' +
+ 'title="Pixels on a 1080-high frame; scales with the film."></span>' +
+ '<span class="sbe-fade-row"><label for="sbeOvTxColor">Colour</label>' +
+ '<input type="color" class="sbe-swatch" id="sbeOvTxColor" value="' + st.color + '" ' +
+ 'onchange="sbeOvTextCommit(\'color\', this.value)"></span>' +
+ '<span class="sbe-fade-row"><label for="sbeOvTxAlign">Align</label>' +
+ '<select class="sb-input sbe-tx-kind" id="sbeOvTxAlign" onchange="sbeOvTextCommit(\'align\', this.value)">' +
+ alignOpt('left', 'Left') + alignOpt('center', 'Centre') + alignOpt('right', 'Right') + '</select></span>' +
+ '<span class="sbe-fade-row sbe-title-pos"><label for="sbeOvTxX">Across</label>' +
+ '<input type="range" id="sbeOvTxX" min="0" max="1" step="0.01" value="' + st.x + '" ' +
+ 'oninput="sbeOvTextPreview(\'x\', this.value)" onchange="sbeOvTextCommit(\'x\', this.value)"></span>' +
+ '<span class="sbe-fade-row sbe-title-pos"><label for="sbeOvTxY">Down</label>' +
+ '<input type="range" id="sbeOvTxY" min="0" max="1" step="0.01" value="' + st.y + '" ' +
+ 'oninput="sbeOvTextPreview(\'y\', this.value)" onchange="sbeOvTextCommit(\'y\', this.value)"></span>' +
+ '<label class="check sbe-title-box"><input type="checkbox" id="sbeOvTxBox"' + (st.box ? ' checked' : '') +
+ ' onchange="sbeOvTextCommit(\'box\', this.checked)"> Box behind</label>' +
+ (st.box
+ ? '<span class="sbe-fade-row"><label for="sbeOvTxBoxColor">Box colour</label>' +
+ '<input type="color" class="sbe-swatch" id="sbeOvTxBoxColor" value="' + st.box_color + '" ' +
+ 'onchange="sbeOvTextCommit(\'box_color\', this.value)">' +
+ '<input type="range" id="sbeOvTxBoxOp" min="0" max="1" step="0.05" value="' + st.box_opacity + '" ' +
+ 'title="Box opacity" onchange="sbeOvTextCommit(\'box_opacity\', this.value)"></span>'
+ : '') +
+ '</div></div>';
+ }
box.innerHTML =
- '<b>' + escapeHtml(sbeNiceName(ov.title
- || String(ov.path || '').split('/').pop() || 'overlay')) + '</b>' +
- '<span>overlay · ' + escapeHtml(sbeOvKind(ov)) + '</span>' +
+ '<b>' + escapeHtml(okind === 'text'
+ ? (sbeOvText(ov).text.split('\n')[0] || 'Title')
+ : sbeNiceName(ov.title || String(ov.path || '').split('/').pop() || 'overlay')) + '</b>' +
+ '<span>overlay · ' + escapeHtml(okind === 'text' ? 'title' : okind) + '</span>' +
'<span>' + sbeNum(ov.film_start).toFixed(2) + '–' +
sbeNum(ov.film_end).toFixed(2) + 's on the __SEQ__</span>' +
- '<span class="sbe-why">Composited over the picture. Its transparency is '
- + 'kept in the preview, the render and the export.</span>' +
+ '<span class="sbe-why">' + (okind === 'text'
+ ? 'Drawn over the picture by the render, in the same font the stage shows. '
+ + 'Fades and position are kept in the preview and the film.'
+ : 'Composited over the picture. Its transparency is '
+ + 'kept in the preview, the render and the export.') + '</span>' +
+ textSect +
'<div class="sbe-sect"><div class="sbe-sect-h">Effects</div>' +
'<div class="sbe-sect-b">' + orow('in', oe.fade_in)
+ orow('out', oe.fade_out) + '</div></div>' +
'<div class="sbe-sect"><div class="sbe-sect-h">Overlay</div>' +
'<div class="sbe-sect-b">' +
- '<button type="button" class="ghost-btn" onclick="sbeOvDeleteSel()">Remove overlay</button>' +
+ '<button type="button" class="ghost-btn" onclick="sbeOvDeleteSel()">' +
+ (okind === 'text' ? 'Remove title' : 'Remove overlay') + '</button>' +
'</div></div>';
return;
}
@@ -5506,12 +6172,38 @@ function sbePaintInspector() {
: '') +
((kind === 'video' && !c.proxy)
? '<span>no proxy — scrubbing this one decodes from the top of the clip</span>' : '') +
- adjust +
+ ((kind === 'video' && !sbeShotForClip(c))
+ ? '<span>not a storyboard shot — it cannot be retaken from here, only re-cut</span>' : '') +
'<span class="sbe-why">' + escapeHtml(why.join(' · ')) + '</span>' +
(errs.length ? '<span style="color:var(--danger)">' + escapeHtml(errs[0].message) + '</span>' : '') +
sect('Clip',
- '<button type="button" class="ghost-btn" onclick="sbeToggleLock()">' +
+ // SPEED, AS A CONTROL AND NEVER A GUESS. A number with the four rates
+ // people actually reach for beside it; the slot follows and the rest
+ // of the film ripples. Only a video clip has a clock.
+ ((kind === 'video')
+ ? '<span class="sbe-fade-row sbe-speed-row"><label for="sbeSpeed">Speed</label>' +
+ '<input type="number" class="sb-input sbe-fade-num" id="sbeSpeed" min="' + SBE_SPEED_MIN +
+ '" max="' + SBE_SPEED_MAX + '" step="0.05" value="' + sbeSpeed(c).toFixed(2) + '" ' +
+ 'onchange="sbeSpeedCommit(this.value)" ' +
+ 'title="Plays the same seconds of the take faster or slower. The slot on the film changes; everything after it moves.">' +
+ '<span class="sbe-adj-val">x</span>' +
+ [0.5, 1, 2].map(v => '<button type="button" class="ghost-btn sbe-speed-pill' +
+ (Math.abs(sbeSpeed(c) - v) < 1e-6 ? ' is-on' : '') + '" onclick="sbeSpeedCommit(' + v + ')" ' +
+ 'title="' + (v === 1 ? 'Normal speed' : (v < 1 ? 'Half speed — twice as long on the film' : 'Double speed — half as long on the film')) + '">' + v + 'x</button>').join('') +
+ '</span>'
+ : '') +
+ '<button type="button" class="ghost-btn" onclick="sbeToggleLock()" ' +
+ 'title="' + (c.locked ? 'Let this shot move and trim again.' : 'Pin this shot to its place on the film; everything else flows around it.') + '">' +
(c.locked ? 'Unlock' : 'Lock') + '</button>' +
+ '<button type="button" class="ghost-btn" onclick="sbeDuplicateSel()" ' +
+ 'title="The same shot again, right after this one — window, speed, fades and grade included. Everything after it slides. (D)">Duplicate</button>' +
+ // RETAKE: send this clip back through the renderer and get a new take
+ // offered against it, in place. Only a clip that came from a shot has
+ // a prompt to start from — and the inspector says so when it cannot.
+ ((kind === 'video' && sbeShotForClip(c))
+ ? '<button type="button" class="ghost-btn" onclick="sbeRetakeSel()" ' +
+ 'title="Render a new take of this shot — same character, a new seed, the prompt to edit. When it lands you choose whether it replaces this clip.">Retake</button>'
+ : '') +
'<button type="button" class="ghost-btn" onclick="sbeLiftSelected()" ' +
'title="Take this shot out and leave its hole. Nothing else moves. (Delete)">Lift</button>' +
'<button type="button" class="ghost-btn" onclick="sbeRippleSelected()" ' +
@@ -5611,7 +6303,27 @@ function sbePaintInspector() {
// `adjust.brightness` on disk, because a label is not worth a data
// migration — and it is PRESENTED here, beside the fades, because this is
// where a person looks for it.
- sect('Effects', adjust + fadeRow('in', e.fade_in) + fadeRow('out', e.fade_out));
+ sect('Effects', adjust + fadeRow('in', e.fade_in) + fadeRow('out', e.fade_out)
+ + ((kind !== 'slug') ? (() => {
+ const fr = sbeFraming(c);
+ const on = !sbeFramingIsNeutral(c);
+ return '<span class="sbe-fade-row sbe-frame-row"><label for="sbeFrameZoom">Zoom</label>'
+ + '<input type="range" id="sbeFrameZoom" min="1" max="' + SBE_FRAME_ZOOM_MAX + '" step="0.05" '
+ + 'value="' + fr.zoom + '" oninput="sbeFramingPreview(\'zoom\', this.value)" '
+ + 'onchange="sbeFramingCommit(\'zoom\', this.value)" '
+ + 'title="Magnify the picture and reframe it. Approximate on the stage; the render crops the source exactly.">'
+ + '<span class="sbe-adj-val" id="sbeFrameZoomVal">' + fr.zoom.toFixed(2) + 'x</span>'
+ + (on ? '<button type="button" class="ghost-btn" onclick="sbeFramingReset()">Reset</button>' : '')
+ + '</span>'
+ + (on
+ ? '<span class="sbe-fade-row sbe-frame-row"><label for="sbeFrameX">Across</label>'
+ + '<input type="range" id="sbeFrameX" min="0" max="1" step="0.01" value="' + fr.x + '" '
+ + 'oninput="sbeFramingPreview(\'x\', this.value)" onchange="sbeFramingCommit(\'x\', this.value)"></span>'
+ + '<span class="sbe-fade-row sbe-frame-row"><label for="sbeFrameY">Down</label>'
+ + '<input type="range" id="sbeFrameY" min="0" max="1" step="0.01" value="' + fr.y + '" '
+ + 'oninput="sbeFramingPreview(\'y\', this.value)" onchange="sbeFramingCommit(\'y\', this.value)"></span>'
+ : '');
+ })() : ''));
}
// The slider moves at pointer speed and the undo stack does not. `oninput`
@@ -5625,6 +6337,20 @@ function sbeBrightPreview(v) {
sbeApplyPreviewFilter(b);
}
+// The two position sliders move at pointer speed and the undo stack does
+// not — the same split the brightness slider makes. `oninput` paints, and
+// `onchange` (once, when the drag ends) is the edit.
+function sbeOvTextPreview(field, v) {
+ const o = sbeOvById(SBE.overlays, SBE.ovSel);
+ if (!o || sbeOvKind(o) !== 'text') return;
+ const tx = sbeEl('sbeOvText');
+ if (!tx || !tx.style || !tx.style.setProperty) return;
+ const val = Math.max(0, Math.min(1, sbeNum(v)));
+ if (field === 'y') { tx.style.setProperty('--tx-y', (val * 100).toFixed(3) + '%'); return; }
+ const st = Object.assign({}, sbeOvText(o).style, { x: val });
+ sbeOvTextPlace(tx, st, sbeEl('sbeStage'));
+}
+
function sbeOvFadeCommit(edge, v) {
if (!SBE.ovSel) return;
const id = SBE.ovSel;
@@ -5657,6 +6383,24 @@ function sbeBrightCommit(v) {
sbeQueueSave();
}
+// A CONTROL THAT KEEPS FOCUS EATS THE SPACE BAR — the next press re-clicks
+// it instead of toggling play. Every inspector commit hands focus back.
+function sbeBlurControl() {
+ try {
+ const a = document.activeElement;
+ if (a && a.blur && a.tagName !== 'TEXTAREA') a.blur();
+ } catch (e) {}
+}
+
+function sbeSpeedCommit(v) {
+ if (!SBE.sel) return;
+ sbeBlurControl();
+ const ok = sbeMutate(cs => sbeSetSpeed(cs, SBE.sel, v));
+ if (!ok) { sbePaintInspector(); return; }
+ // The stage is showing a frame of a clip whose clock just changed.
+ if (!SBE.playing) sbeShowFrameAt(SBE.playhead);
+}
+
// One place decides what the stage looks like, so the video layer and the
// still layer can never disagree about the grade.
// THE PREVIEW'S OPACITY, a value per frame rather than a CSS transition: a
@@ -5672,7 +6416,7 @@ function sbeFadePaint(t) {
// during a SCRUB gave the stale clip, or none at all, and the ramp a person
// is dragging is exactly the one they are scrubbing to look at.
const c = sbeClipAt(SBE.clips, now) || sbeById(SBE.clips, SBE.curId);
- const o = c ? sbeFadeOpacityAt(c, now) : 1;
+ const o = c ? sbeFadeOpacityAt(c, now, sbeTxEdges(SBE.clips, SBE.transitions, c.id, sbeFps())) : 1;
// OPACITY IS ALSO THE LAYER SWITCH. `.sbe-still` is opacity:0 until it wins
// `.is-on`, so writing the ramp onto BOTH layers turned the hidden one on --
// and the still, being last in the stage and backed with #000, painted a
@@ -5686,12 +6430,60 @@ function sbeFadePaint(t) {
paint(img);
}
-function sbeApplyPreviewFilter(b) {
+function sbeApplyPreviewFilter(b, frame) {
const css = (Math.abs(sbeNum(b)) < 1e-6) ? '' : 'brightness(' + sbeBrightnessCss(b) + ')';
const v = sbeEl('sbeVideo');
const i = sbeEl('sbeStill');
if (v) v.style.filter = css;
if (i) i.style.filter = css;
+ sbeApplyPreviewFraming(frame);
+}
+
+// THE REFRAME ON THE STAGE: the layer scaled about the anchor. Approximate
+// — the stage letterboxes with object-fit, so a picture that is not 16:9
+// scales about a point slightly off the source's own fraction — and the
+// inspector says so; the render's crop is exact.
+function sbeApplyPreviewFraming(frame) {
+ const f = sbeFraming({ frame: frame || {} });
+ const t = (Math.abs(f.zoom - 1) < 1e-9) ? '' : 'scale(' + f.zoom.toFixed(3) + ')';
+ const o = (f.x * 100).toFixed(2) + '% ' + (f.y * 100).toFixed(2) + '%';
+ for (const el of [sbeEl('sbeVideo'), sbeEl('sbeStill')]) {
+ if (!el || !el.style) continue;
+ el.style.transform = t;
+ el.style.transformOrigin = t ? o : '';
+ }
+}
+
+// The sliders move at pointer speed and the undo stack does not — `oninput`
+// paints, `onchange` is the edit, the brightness slider's own split.
+function sbeFramingPreview(field, v) {
+ const c = sbeById(SBE.clips, SBE.sel);
+ if (!c) return;
+ const f = sbeFraming(c);
+ f[field] = sbeNum(v, f[field]);
+ sbeApplyPreviewFraming(f);
+ const out = sbeEl('sbeFrameZoomVal');
+ if (out && field === 'zoom') out.textContent = sbeFraming({ frame: f }).zoom.toFixed(2) + 'x';
+}
+function sbeFramingCommit(field, v) {
+ if (!SBE.sel) return;
+ sbeBlurControl();
+ const ok = sbeMutate(cs => sbeSetFraming(cs, SBE.sel, field, v));
+ if (!ok) { sbePaintInspector(); return; }
+ const c = sbeById(SBE.clips, SBE.sel);
+ if (c) sbeApplyPreviewFraming(sbeFraming(c));
+}
+function sbeFramingReset() {
+ if (!SBE.sel) return;
+ sbeMutate(cs => {
+ const c = sbeById(cs, SBE.sel);
+ if (!c || !c.frame) return { clips: cs, ok: false, why: '' };
+ const out = cs.map(x => Object.assign({}, x));
+ delete sbeById(out, SBE.sel).frame;
+ sbeById(out, SBE.sel).source = 'human';
+ return { clips: out, ok: true };
+ });
+ sbeApplyPreviewFraming(null);
}
function sbePaintChrome() {
@@ -5823,11 +6615,24 @@ function sbeOnTrackDown(ev) {
sbeGenOpen(sbeNum(gap.dataset.gapStart), sbeNum(gap.dataset.gapDur));
return;
}
+ // A CUT IS A SUBJECT OF ITS OWN. Clicking the mark on a boundary selects
+ // the boundary, and the inspector becomes the place to put a transition on
+ // it — no lane, no panel, nothing that reads as bolted on.
+ const cut = ev.target.closest('.sbe-cut');
+ if (cut) {
+ ev.preventDefault();
+ SBE.txSel = cut.dataset.after;
+ SBE.sel = '';
+ SBE.ovSel = '';
+ sbePaint();
+ return;
+ }
const blk = ev.target.closest('.sbe-clip');
- if (!blk) { sbeSeek(sbeTimeFromEvent(ev, track)); return; }
+ if (!blk) { SBE.txSel = ''; sbeSeek(sbeTimeFromEvent(ev, track)); sbePaint(); return; }
const id = blk.dataset.id;
SBE.sel = id;
SBE.ovSel = ''; // one inspector, one subject
+ SBE.txSel = '';
SBE.audioDrag = null; // same insurance the lane takes against the other
const c = sbeById(SBE.clips, id);
if (!c) return;
@@ -5864,7 +6669,16 @@ function sbeOnTrackDown(ev) {
sbePaint();
return;
}
- const grip = ev.target.closest('.sbe-grip');
+ // AN EDGE IS A TRIM WHEREVER YOU GRAB IT. The grips are drawn 9 px wide; a
+ // pointer within the edge zone of the block trims even when it lands a
+ // pixel outside the grip element — the reach every NLE gives an edge.
+ let grip = ev.target.closest('.sbe-grip');
+ if (!grip) {
+ const br = blk.getBoundingClientRect();
+ const EDGE = 10;
+ if (ev.clientX - br.left <= EDGE) grip = { classList: { contains: () => false } };
+ else if (br.right - ev.clientX <= EDGE) grip = { classList: { contains: (k) => k === 'r' } };
+ }
// SHIFT IS REORDER. The hint strip already teaches "hold Alt to ignore the
// beat", so a second modifier on the same gesture is the idiom this timeline
// already has — and it is the only way to offer both verbs without a mode
@@ -5873,10 +6687,15 @@ function sbeOnTrackDown(ev) {
// for the generate control to fill.
const mode = grip ? (grip.classList.contains('r') ? 'trimR' : 'trimL')
: (ev.shiftKey ? 'reorder' : 'move');
+ // ⌘ / CTRL IS RIPPLE: the gesture also slides everything after the clip,
+ // the way it did before 2026-09-05. Read again on every move so it can be
+ // pressed or released mid-drag, as in Premiere.
SBE.drag = { id: id, mode: mode, x0: ev.clientX, t0: sbeTimeFromEvent(ev, track),
fs0: sbeNum(c.film_start), fe0: sbeNum(c.film_end), moved: false,
+ ripple: !!(ev.metaKey || ev.ctrlKey),
before: JSON.stringify(SBE.clips) };
if (mode === 'move') blk.classList.add('is-drag');
+ track.classList.toggle('is-ripple', SBE.drag.ripple);
try { track.setPointerCapture(ev.pointerId); } catch (e) {}
ev.preventDefault();
sbePaint();
@@ -5908,16 +6727,26 @@ function sbeOnTrackMove(ev) {
// pulling the drop index onto a beat would mean nothing.
const r = sbeReorderTo(SBE.clips, d.id, Math.max(0, d.t0 + dt));
if (r.ok) SBE.clips = r.clips;
- } else if (d.mode === 'move') {
- const want = sbeSnapTime(Math.max(0, d.fs0 + dt), SBE.beats, tol, snapOn, off);
- const r = sbeMoveTo(SBE.clips, d.id, want);
- if (r.ok) SBE.clips = r.clips;
- } else if (d.mode === 'trimL') {
- const want = sbeSnapTime(Math.max(0, d.fs0 + dt), SBE.beats, tol, snapOn, off);
- sbeTrim(SBE.clips, d.id, 'l', want);
} else {
- const want = sbeSnapTime(Math.max(0, d.fe0 + dt), SBE.beats, tol, snapOn, off);
- sbeTrim(SBE.clips, d.id, 'r', want);
+ // A move or a trim always works from the SNAPSHOT: the model clamps at
+ // neighbours, and re-applying deltas to an already-clamped state would
+ // let a pointer that kept going drag the clip through the wall.
+ const ripple = !!(ev.metaKey || ev.ctrlKey);
+ d.ripple = ripple;
+ track.classList.toggle('is-ripple', ripple);
+ SBE.clips = JSON.parse(d.before);
+ const o = { ripple: ripple };
+ if (d.mode === 'move') {
+ const want = sbeSnapTime(Math.max(0, d.fs0 + dt), SBE.beats, tol, snapOn, off);
+ const r = sbeMoveTo(SBE.clips, d.id, want, o);
+ if (r.ok) SBE.clips = r.clips;
+ } else if (d.mode === 'trimL') {
+ const want = sbeSnapTime(Math.max(0, d.fs0 + dt), SBE.beats, tol, snapOn, off);
+ sbeTrim(SBE.clips, d.id, 'l', want, o);
+ } else {
+ const want = sbeSnapTime(Math.max(0, d.fe0 + dt), SBE.beats, tol, snapOn, off);
+ sbeTrim(SBE.clips, d.id, 'r', want, o);
+ }
}
sbePaint();
}
@@ -5945,6 +6774,7 @@ function sbeOnTrackUp(ev) {
SBE.drag = null;
if (!d) return;
document.querySelectorAll('.sbe-clip.is-drag').forEach(el => el.classList.remove('is-drag'));
+ const trk = sbeEl('sbeTrack'); if (trk) trk.classList.remove('is-ripple');
if (!d.moved) { sbePaint(); return; }
// A DRAG THAT MOVED THE POINTER BUT NOT THE FILM IS NOT AN EDIT. Dragging a
// clip left when it is already hard against its neighbour is the common case
@@ -6030,6 +6860,10 @@ function sbeLoadInto(v, c, at) {
v.muted = !!SBE.muted || !sbePictureCarriesSound(c);
v.volume = 1;
v.playsInline = true;
+ // THE CLIP'S SPEED IS THE ELEMENT'S RATE. The browser plays the same
+ // seconds of the take at the rate the render's `setpts` will, so the
+ // preview and the file agree about how fast the shot goes by.
+ try { v.playbackRate = sbeSpeed(c); } catch (e) {}
const url = sbeClipUrl(c);
const seek = () => {
const t = Math.max(0, Math.min(sbeNum(c.end) - 1e-3, sbeNum(at)));
@@ -6069,7 +6903,7 @@ async function sbeShowFrameAt(t) {
return;
}
const kind = sbeKind(c);
- sbeApplyPreviewFilter(sbeBright(c));
+ sbeApplyPreviewFilter(sbeBright(c), sbeFraming(c));
if (kind === 'slug') {
// NO FILE, SO NOTHING TO LOAD. Both layers off leaves the stage's own
// black, which is the frame the render will write — the one case where the
@@ -6097,7 +6931,7 @@ async function sbeShowFrameAt(t) {
return;
}
if (img) img.classList.remove('is-on');
- await sbeLoadInto(v, c, sbeNum(c.start) + (t - sbeNum(c.film_start)));
+ await sbeLoadInto(v, c, sbeNum(c.start) + (t - sbeNum(c.film_start)) * sbeSpeed(c));
v.classList.add('is-on');
sbeEl('sbeBadge').textContent =
(c.title || c.path.split('/').pop()) + ' · ' + sbeNum(c.start).toFixed(2) + '–' +
@@ -6796,12 +7630,64 @@ function edAddSlug() {
function sbePaintRelink() {
const bar = sbeEl('sbeRelink');
if (!bar) return;
- const rows = SBE.relink || [];
+ const all = SBE.relink || [];
+ const rows = all.filter(r => !r.retake);
+ const takes = all.filter(r => r.retake && !sbeRetakeDismissed(r));
bar.hidden = !rows.length;
- if (!rows.length) return;
- sbeEl('sbeRelinkText').textContent = rows.length +
- (rows.length === 1 ? ' shot was' : ' shots were') +
- ' finished since this cut — use the finished versions.';
+ if (rows.length) {
+ sbeEl('sbeRelinkText').textContent = rows.length +
+ (rows.length === 1 ? ' shot was' : ' shots were') +
+ ' finished since this cut — use the finished versions.';
+ }
+ // A RETAKE IS ONE DECISION PER TAKE, so each gets its own line and its
+ // own two answers. The old take stays until the person says otherwise.
+ const tb = sbeEl('sbeRetakes');
+ if (!tb) return;
+ tb.hidden = !takes.length;
+ if (!takes.length) return;
+ tb.innerHTML = takes.map(r =>
+ '<span class="sbe-relink-row">' +
+ '<span>New take of <b>' + escapeHtml(sbeNiceName(r.title || ('shot ' + r.n))) + '</b> is ready.</span>' +
+ '<button type="button" class="ghost-btn" onclick="sbeRetakeUse(\'' + escapeHtml(r.id) + '\')" ' +
+ 'title="Replace the clip with the new take. Same cut, same timings.">Use it</button>' +
+ '<button type="button" class="ghost-btn" onclick="sbeRetakeKeep(\'' + escapeHtml(r.id) + '\', \'' + escapeHtml(r.to) + '\')" ' +
+ 'title="Keep the take that is on the timeline. The new one stays in the media pool.">Keep the old one</button>' +
+ '</span>').join('');
+}
+
+// "Keep the old one" is a decision about ONE file against ONE clip, kept in
+// this browser: the take stays in the pool, and this line does not come back
+// for it.
+function sbeRetakeDismissed(r) {
+ try {
+ const seen = JSON.parse(localStorage.getItem('phos_retake_keep') || '[]');
+ return seen.indexOf(String(r.id) + '|' + String(r.to)) >= 0;
+ } catch (e) { return false; }
+}
+function sbeRetakeKeep(id, to) {
+ try {
+ const seen = JSON.parse(localStorage.getItem('phos_retake_keep') || '[]');
+ seen.push(String(id) + '|' + String(to));
+ localStorage.setItem('phos_retake_keep', JSON.stringify(seen.slice(-200)));
+ } catch (e) {}
+ sbePaintRelink();
+}
+async function sbeRetakeUse(id) {
+ if (SBE.dirty && !SBE.conflict && !(await sbeSave(true))) {
+ phosToast('Your arrangement could not be saved, and the swap works on the saved file — fix the save first.',
+ { kind: 'danger', duration: 8000 });
+ return;
+ }
+ const fd = new URLSearchParams();
+ fd.set('id', SBE.id);
+ fd.set('only', id);
+ let r;
+ try { r = await (await fetch('/storyboard/edit/relink', { method: 'POST', body: fd })).json(); }
+ catch (e) { r = { ok: false, error: String(e) }; }
+ if (!r || !r.ok) { phosToast((r && r.error) || 'The take could not be swapped in.', { kind: 'danger' }); return; }
+ SBE.undo.length = 0; SBE.redo.length = 0;
+ sbeAdopt(r, true);
+ phosToast('The new take is on the timeline. Same cut, same timings.', { kind: 'success', duration: 5000 });
}
async function sbeRelink() {
@@ -6913,12 +7799,13 @@ function sbeUnmuteFromRefusal() {
async function sbeEnter(c, at) {
const v = sbeEl('sbeVideo');
const img = sbeEl('sbeStill');
- sbeApplyPreviewFilter(sbeBright(c));
+ sbeApplyPreviewFilter(sbeBright(c), sbeFraming(c));
const kind = sbeKind(c);
if (kind === 'video') {
if (img) img.classList.remove('is-on');
await sbeLoadInto(v, c, (at === undefined || at === null) ? sbeNum(c.start) : sbeNum(at));
v.classList.add('is-on');
+ try { v.playbackRate = sbeSpeed(c); } catch (e) {}
try { await v.play(); } catch (e) {}
return;
}
@@ -6947,8 +7834,12 @@ async function sbePlay() {
const v = sbeEl('sbeVideo');
SBE.curId = c.id;
if (sbeKind(c) === 'video') {
- await sbeLoadInto(v, c, sbeNum(c.start) + (SBE.playhead - sbeNum(c.film_start)));
+ // ENTERING MID-CLIP: film seconds into the slot are `speed` source
+ // seconds into the take — the review caught a 2x clip re-seeking on
+ // every frame because this seek landed at the 1x position.
+ await sbeLoadInto(v, c, sbeNum(c.start) + (SBE.playhead - sbeNum(c.film_start)) * sbeSpeed(c));
v.classList.add('is-on');
+ try { v.playbackRate = sbeSpeed(c); } catch (e) {}
try {
await v.play();
} catch (e) {
@@ -6965,7 +7856,7 @@ async function sbePlay() {
try { await v.play(); } catch (e2) {}
}
}
- sbeApplyPreviewFilter(sbeBright(c));
+ sbeApplyPreviewFilter(sbeBright(c), sbeFraming(c));
} else {
await sbeEnter(c);
}
@@ -7015,7 +7906,7 @@ async function sbeFrame() {
sbePaintTrack();
}
} else if (c) {
- SBE.playhead = sbeNum(c.film_start) + Math.max(0, v.currentTime - sbeNum(c.start));
+ SBE.playhead = sbeNum(c.film_start) + Math.max(0, v.currentTime - sbeNum(c.start)) / sbeSpeed(c);
if (v.currentTime >= sbeNum(c.end) - 1e-3 || v.ended) {
const next = SBE.clips[SBE.clips.indexOf(c) + 1];
if (!next) { sbeStop(); sbePaintHead(); return; }
@@ -7189,7 +8080,10 @@ function sbeStripSync(force) {
// the envelope's own clock.
const c2 = sbeById(SBE.clips, w.id);
const win = c2 ? sbeClipAudio(c2) : null;
- a.volume = win ? sbeGainAt(c2, win.len, w.at - win.start) : 1;
+ // The envelope's clock is the strip AS PLAYED — film seconds into it —
+ // which is `(source second - in-point) / speed`.
+ a.volume = win ? sbeGainAt(c2, win.len, (w.at - win.start) / win.speed) : 1;
+ try { a.playbackRate = win ? win.speed : 1; } catch (e) {}
try {
if (fresh || force || Math.abs(a.currentTime - w.at) > SBE_STRIP_SLIP) {
a.currentTime = w.at;
@@ -7302,8 +8196,19 @@ function sbeLiftSelected() {
sbePaint();
}
+function sbeDuplicateSel() {
+ if (!SBE.sel) return;
+ let added = null;
+ const ok = sbeMutate(cs => { const r = sbeDuplicate(cs, SBE.sel); if (r.ok) added = r.added; return r; });
+ if (!ok) return;
+ // THE COPY IS THE SELECTION NOW — it is the thing just made, and the one
+ // the next key press should act on.
+ if (added) { SBE.sel = added.id; sbePaint(); }
+ sbeBlurControl();
+}
+
function sbeSplitHere() {
- sbeMutate(cs => sbeSplitAt(cs, SBE.playhead));
+ sbeMutate(cs => sbeSplitAt(cs, SBE.playhead, undefined, SBE.transitions || []));
}
function sbeToggleLock() {
@@ -7378,12 +8283,47 @@ async function sbeAuto() {
}
let _sbeGenAt = 0;
-function sbeGenOpen(filmStart, duration) {
+// THE SHOT A CLIP CAME FROM, from the pool the payload already carries.
+// By path — a clip on the timeline is a file, and the pool row for that
+// file knows its shot number, its prompt and its character.
+function sbeShotForClip(c) {
+ if (!c || !c.path) return null;
+ for (const r of (SBE.pool || [])) if (r.path === c.path) return r;
+ return null;
+}
+
+// RETAKE: the same modal a hole uses, seeded from the clip — its prompt to
+// edit, its length as the length, its slot as the slot — and `retake_of` so
+// the new take comes back offered against THIS clip rather than as a loose
+// shot under the timeline.
+let _sbeRetakeOf = '';
+function sbeRetakeSel() {
+ const c = sbeById(SBE.clips, SBE.sel);
+ const shot = c ? sbeShotForClip(c) : null;
+ if (!c || !shot) { phosToast('Only a clip that came from a shot can be retaken.', {}); return; }
+ const len = Math.max(0.5, sbeNum(shot.duration_s, 0) || (sbeLen(c) * sbeSpeed(c) + 1));
+ sbeGenOpen(sbeNum(c.film_start), len, { retakeOf: c.id, prompt: shot.prompt || '',
+ name: shot.title || String(c.path).split('/').pop() });
+}
+
+function sbeGenOpen(filmStart, duration, opts) {
_sbeGenAt = sbeNum(filmStart);
- sbeEl('sbeGenWhere').textContent =
- 'Nothing plays between ' + sbeFmtTime(filmStart) + ' and ' +
- sbeFmtTime(sbeNum(filmStart) + sbeNum(duration)) + '. This shot is written to the ' +
- 'storyboard and rendered like any other.';
+ _sbeRetakeOf = (opts && opts.retakeOf) || '';
+ sbeEl('sbeGenWhere').textContent = _sbeRetakeOf
+ ? ('A new take of ' + (opts.name || 'this clip') + ': the same shot and character, a new ' +
+ 'seed, the prompt below to edit. When it lands, a line above the timeline offers it ' +
+ 'against this clip — Use it, or keep the old one.')
+ : ('Nothing plays between ' + sbeFmtTime(filmStart) + ' and ' +
+ sbeFmtTime(sbeNum(filmStart) + sbeNum(duration)) + '. This shot is written to the ' +
+ 'storyboard and rendered like any other.');
+ const ttl = sbeEl('sbeGenTitle');
+ if (ttl) ttl.textContent = _sbeRetakeOf ? 'Retake this shot' : 'Fill this hole';
+ const after = sbeEl('sbeGenAfter');
+ if (after) after.hidden = !!_sbeRetakeOf;
+ const box = sbeEl('sbeGenPrompt');
+ if (box) box.value = (opts && opts.prompt) ? opts.prompt : '';
+ const go = sbeEl('sbeGenGo');
+ if (go) go.textContent = _sbeRetakeOf ? 'Queue the retake' : 'Queue the shot';
// FLOOR, not round: a shot longer than the hole it was ordered for pushes
// everything after it off the beat the moment it is placed.
sbeEl('sbeGenDuration').value =
@@ -7406,6 +8346,7 @@ async function sbeGenSubmit() {
fd.set('prompt', prompt);
fd.set('duration', String(sbeNum(sbeEl('sbeGenDuration').value, 5)));
fd.set('film_start', String(_sbeGenAt));
+ if (_sbeRetakeOf) fd.set('retake_of', _sbeRetakeOf);
const on = document.querySelector('#sbeGenPass .pill-btn.active');
fd.set('pass', (on && on.dataset.pass) || 'draft');
let r;
@@ -7428,6 +8369,45 @@ async function sbeGenSubmit() {
{ kind: 'success', duration: 6000 });
}
+// DELIVER AS — remembered in this browser, posted with every render, and
+// painted onto the pills when the menu is built.
+const SBE_DELIVER_FORMATS = ['h264', 'hevc', 'prores'];
+const SBE_DELIVER_SIZES = ['native', '1080p', '2160p'];
+const SBE_DELIVER_FINISH = ['none', 'grain', 'heavy_grain'];
+function sbeDeliverGet() {
+ let d = {};
+ try { d = JSON.parse(localStorage.getItem('phos_deliver') || '{}') || {}; } catch (e) { d = {}; }
+ return { format: SBE_DELIVER_FORMATS.indexOf(d.format) >= 0 ? d.format : 'h264',
+ size: SBE_DELIVER_SIZES.indexOf(d.size) >= 0 ? d.size : 'native',
+ finish: SBE_DELIVER_FINISH.indexOf(d.finish) >= 0 ? d.finish : 'none' };
+}
+function sbeDeliverPick(key, value) {
+ const d = sbeDeliverGet();
+ d[key] = value;
+ try { localStorage.setItem('phos_deliver', JSON.stringify(d)); } catch (e) {}
+ sbeDeliverPaint();
+}
+function sbeDeliverPaint() {
+ const d = sbeDeliverGet();
+ document.querySelectorAll('#sbeDeliverFormat .pill-btn').forEach(b =>
+ b.classList.toggle('active', b.dataset.format === d.format));
+ document.querySelectorAll('#sbeDeliverSize .pill-btn').forEach(b =>
+ b.classList.toggle('active', b.dataset.size === d.size));
+ document.querySelectorAll('#sbeDeliverFinish .pill-btn').forEach(b =>
+ b.classList.toggle('active', b.dataset.finish === d.finish));
+ const btn = sbeEl('sbeRenderBtn');
+ if (btn && !SBE.rendering) {
+ const short = ({ h264: '', hevc: 'HEVC', prores: 'ProRes' })[d.format];
+ const size = d.size === 'native' ? '' : (d.size === '2160p' ? '4K' : '1080p');
+ const fin = d.finish === 'none' ? '' : (d.finish === 'heavy_grain' ? 'heavy grain' : 'grain');
+ const tag = [short, size, fin].filter(Boolean).join(' ');
+ btn.textContent = tag ? ('Render · ' + tag) : 'Render';
+ btn.title = 'Assemble the film as ' + ({ h264: 'H.264', hevc: 'HEVC', prores: 'ProRes 422 HQ' })[d.format]
+ + (d.size === 'native' ? ', as cut' : (d.size === '2160p' ? ' at 4K' : ' at 1080p'))
+ + '. Change it under the arrow.';
+ }
+}
+
async function sbeRenderFilm() {
if (SBE.rendering) return;
// THE RENDER READS THE SAVED FILE, so a save that did not land renders the
@@ -7456,6 +8436,10 @@ async function sbeRenderFilm() {
fd.set('id', SBE.id);
const music = (sbeEl('sbeMusic').value || '').trim();
if (music) { fd.set('music', music); fd.set('music_mode', sbeMusicMode()); }
+ const dl = sbeDeliverGet();
+ fd.set('format', dl.format);
+ fd.set('size', dl.size);
+ fd.set('finish', dl.finish);
let r;
try { r = await (await fetch('/storyboard/edit/render', { method: 'POST', body: fd })).json(); }
catch (e) { r = { ok: false, error: String(e) }; }
@@ -7470,8 +8454,11 @@ async function sbeRenderFilm() {
sbeEl('sbeRenderNote').textContent = (r.gaps_note || '') +
' Wrote ' + Math.round(sbeNum(r.duration)) + 's to ' + (r.path || '').split('/').pop();
phosToast('Rendered ' + r.clips + ' clips · ' + Math.round(sbeNum(r.duration)) + 's' +
+ (r.deliver && r.deliver.label ? ' · ' + r.deliver.label : '') +
+ (r.deliver && r.deliver.format === 'prores'
+ ? ' — a ProRes .mov: it opens in an NLE or QuickTime, not in this preview' : '') +
(r.gaps_note ? ' — ' + r.gaps_note : ''),
- { kind: 'success', duration: r.gaps_note ? 11000 : 6000 });
+ { kind: 'success', duration: (r.gaps_note || (r.deliver && r.deliver.format === 'prores')) ? 11000 : 6000 });
// The render ENDS ON THE FILM. Before this the timeline wrote an mp4 into
// mlx_outputs/storyboards/, printed one line of grey text under the button,
// and left the user looking at the timeline wondering where the film went.
@@ -7605,9 +8592,12 @@ document.addEventListener('keydown', (ev) => {
if (ev.key === ' ') { ev.preventDefault(); sbeTogglePlay(); return; }
if (ev.key === 'ArrowLeft') { ev.preventDefault(); sbeStop(); sbeSeek(SBE.playhead - (ev.shiftKey ? step * 10 : step)); return; }
if (ev.key === 'ArrowRight') { ev.preventDefault(); sbeStop(); sbeSeek(SBE.playhead + (ev.shiftKey ? step * 10 : step)); return; }
+ if ((ev.key === 'Delete' || ev.key === 'Backspace') && SBE.txSel) { ev.preventDefault(); sbeTxRemoveSel(); return; }
+ if ((ev.key === 'Delete' || ev.key === 'Backspace') && SBE.ovSel && !SBE.sel) { ev.preventDefault(); sbeOvDeleteSel(); return; }
if ((ev.key === 'Delete' || ev.key === 'Backspace') && ev.shiftKey) { ev.preventDefault(); sbeRippleSelected(); return; }
if (ev.key === 'Delete' || ev.key === 'Backspace') { ev.preventDefault(); sbeLiftSelected(); return; }
if (ev.key === 's' || ev.key === 'S') { ev.preventDefault(); sbeSplitHere(); return; }
+ if ((ev.key === 'd' || ev.key === 'D') && !ev.metaKey && !ev.ctrlKey && SBE.sel) { ev.preventDefault(); sbeDuplicateSel(); return; }
if ((ev.metaKey || ev.ctrlKey) && (ev.key === 'z' || ev.key === 'Z')) {
ev.preventDefault();
ev.shiftKey ? sbeRedo() : sbeUndo();
@@ -7896,6 +8886,19 @@ Object.assign(globalThis, {
sbeDeleteKeyframe, sbeDeleteStrip, sbeSetAudioFade, sbeOvKind,
sbeOvAt, sbeOvById, sbeOvFits, sbeOvMove,
sbeOvTrim, sbeOvAdd, sbeOvDelete, sbeStripOwned,
+ // Editor v2: speed on the clip, titles on the overlay lane, transitions on
+ // the cut.
+ sbeSpeed, sbeSetSpeed, sbeSpeedCommit,
+ sbeOvText, sbeHexColour, sbeRgba, sbeOvTextCommit, sbeOvTextPreview, edAddTitle,
+ sbeSectionBands, sbeShotForClip, sbeRetakeSel, sbeRetakeDismissed,
+ sbeDeliverGet, sbeDeliverPick, sbeDeliverPaint, sbeDuplicate, sbeDuplicateSel,
+ sbeFraming, sbeFramingIsNeutral, sbeSetFraming, sbeApplyPreviewFraming, sbeFramingPreview,
+ sbeFramingCommit, sbeFramingReset,
+ sbeRetakeKeep, sbeRetakeUse,
+ sbeOvTextPlace, sbeBlurControl,
+ sbeTxById, sbeTxAfter, sbeTxDuration, sbeTxSpare, sbeTxResolve, sbeTxEdges,
+ sbeTxSet, sbeTxDelete, sbeTxPrune, sbeTxRepoint, sbeTxMutate, sbeTxCommit,
+ sbeTxRemoveSel,
sbePictureCarriesSound, sbeStripsAt, sbeClipAt, sbeHoles,
sbeBeatGrid, sbeGridIsAGuess, sbeSnapTime, sbeById,
sbeMoveTo, sbeTrim, sbeRippleDelete, sbeLiftDelete, sbeSplitAt,
diff --git a/webapp/js/loras.js b/webapp/js/loras.js
index b158dc7..d5d9279 100644
--- a/webapp/js/loras.js
+++ b/webapp/js/loras.js
@@ -380,6 +380,87 @@ function onIngredientCharStrength(v) {
if (field) field.value = String(v);
}
+// ---- Updates from CivitAI -------------------------------------------------
+// `LORA_UPDATES` maps an installed LoRA's path to the newer version the
+// check found. The badge and the Update button read it; the install is the
+// same /civitai/download the browser tab uses, so the new file lands with a
+// sidecar and the picker learns it on the next refresh.
+const LORA_UPDATES = {};
+// The check is remembered per browser (with when it ran) so the badges
+// survive a reload; a new check replaces it.
+try {
+ const saved = JSON.parse(localStorage.getItem('phos_lora_updates') || 'null');
+ if (saved && saved.items && (Date.now() - (saved.at || 0)) < 7 * 86400e3) {
+ saved.items.forEach(it => { LORA_UPDATES[it.path] = it; });
+ }
+} catch (e) {}
+async function checkLoraUpdates() {
+ const btn = document.getElementById('loraUpdatesBtn');
+ if (btn) { btn.disabled = true; btn.textContent = 'Checking…'; }
+ try {
+ const r = await (await fetch('/loras/updates')).json();
+ Object.keys(LORA_UPDATES).forEach(k => delete LORA_UPDATES[k]);
+ (r.items || []).forEach(it => { LORA_UPDATES[it.path] = it; });
+ try { localStorage.setItem('phos_lora_updates', JSON.stringify({ at: Date.now(), items: r.items || [] })); } catch (e) {}
+ const n = (r.items || []).length;
+ if (typeof phosToast === 'function') {
+ phosToast(!r.checked ? 'No installed LoRA came from CivitAI, so there is nothing to check.'
+ : n ? `${n} LoRA${n > 1 ? 's have' : ' has'} a newer version on CivitAI — marked in the list.`
+ : `All ${r.checked} CivitAI LoRA${r.checked > 1 ? 's are' : ' is'} up to date.`
+ + ((r.errors || []).length ? ` ${r.errors.length} could not be checked.` : ''), { duration: 6000 });
+ }
+ renderLorasList();
+ } catch (e) {
+ if (typeof phosToast === 'function') phosToast('CivitAI could not be reached.', { kind: 'danger' });
+ } finally {
+ if (btn) { btn.disabled = false; btn.textContent = 'Check for updates'; }
+ }
+}
+async function updateLora(path) {
+ const it = LORA_UPDATES[path];
+ if (!it) return;
+ if (typeof phosToast === 'function') phosToast(`Downloading ${it.name} · ${it.latest_version_name || 'new version'}…`, { duration: 5000 });
+ const fd = new URLSearchParams();
+ fd.set('download_url', it.download_url);
+ fd.set('meta', JSON.stringify(it.meta || {}));
+ try {
+ const r = await (await fetch('/civitai/download', { method: 'POST', body: fd })).json();
+ if (r.ok) {
+ delete LORA_UPDATES[path];
+ try { localStorage.setItem('phos_lora_updates', JSON.stringify({ at: Date.now(), items: Object.values(LORA_UPDATES) })); } catch (e) {}
+ if (typeof phosToast === 'function') phosToast(`${it.name} updated. The old file is still installed — delete it from the list when you are done comparing.`, { duration: 8000 });
+ await refreshLoras();
+ } else if (typeof phosToast === 'function') phosToast(r.error || 'The download failed.', { kind: 'danger', duration: 7000 });
+ } catch (e) {
+ if (typeof phosToast === 'function') phosToast('The download failed.', { kind: 'danger' });
+ }
+}
+
+// ---- Guides -----------------------------------------------------------------
+// One paragraph per LoRA, written by the planner model from the sidecar
+// (name, description, trigger words, base model) and saved back into it.
+async function writeLoraGuide(path, btn) {
+ // Busy state on the button itself: the planner model loads for tens of
+ // seconds the first time, and a second click would queue a second write.
+ if (btn) { btn.disabled = true; btn.dataset.label = btn.textContent; btn.textContent = 'Writing…'; }
+ const fd = new URLSearchParams(); fd.set('path', path);
+ try {
+ const r = await (await fetch('/loras/guide', { method: 'POST', body: fd })).json();
+ if (r.ok) { await refreshLoras(); }
+ else if (typeof phosToast === 'function') phosToast(r.error || 'The guide could not be written.', { kind: 'danger', duration: 7000 });
+ } catch (e) {
+ if (typeof phosToast === 'function') phosToast('The guide could not be written.', { kind: 'danger' });
+ } finally {
+ if (btn && btn.isConnected) { btn.disabled = false; btn.textContent = btn.dataset.label || 'Write a guide'; }
+ }
+}
+// Guides are refused while a render runs (the planner is a 12B model); say
+// so on the button instead of after the click.
+function _guideBusyAttrs() {
+ const busy = !!(globalThis.LAST_STATUS && globalThis.LAST_STATUS.current);
+ return busy ? 'disabled title="Wait for the render to finish — the guide is written by the planner model"' : '';
+}
+
async function refreshLoras() {
// Pull the FULL library (no mode filter) so _knownUserLoras keeps every
// entry — that lets refreshLoras() also serve as the "deleted on disk"
@@ -480,6 +561,7 @@ function renderLorasList() {
recommended_strength: ul.recommended_strength || 1.0,
filename: ul.filename,
civitai_url: ul.civitai_url,
+ guide: ul.guide || '',
compatible_modes: ul.compatible_modes || ['unknown'],
// Which engine DIRECTORY this file came from. Checked before
// compatible_modes in the filter below, because 'unknown' is
@@ -753,6 +835,11 @@ function loraRowHtml(r, modeTag) {
corner.push(`<button class="lora-icon-btn" type="button" title="Download the .safetensors file"
onclick="event.stopPropagation(); downloadLora(${pathAttr})"><svg class="ph" aria-hidden="true"><use href="#ph-download-simple"/></svg></button>`);
}
+ if (LORA_UPDATES[r.path]) {
+ const up = LORA_UPDATES[r.path];
+ corner.push(`<button class="lora-icon-btn lora-update-btn" type="button" title="Newer version on CivitAI: ${escapeHtml(up.latest_version_name || String(up.latest_version_id))} — download it"
+ onclick="event.stopPropagation(); updateLora(${pathAttr})"><svg class="ph" aria-hidden="true"><use href="#ph-download-simple"/></svg></button>`);
+ }
if (r.civitai_url) {
corner.push(`<a class="lora-icon-btn" href="${escapeHtml(r.civitai_url)}" target="_blank" rel="noopener" title="Open on CivitAI" onclick="event.stopPropagation()"><svg class="ph" aria-hidden="true"><use href="#ph-arrow-square-out"/></svg></a>`);
}
@@ -780,7 +867,7 @@ function loraRowHtml(r, modeTag) {
<div class="lora-toggle-dot"></div>
<div class="lora-text">
<div class="lora-name" title="${pathHtml}">
- ${nameHtml}${r.kind === 'remote' ? '<span class="badge">HF</span>' : ''}${r.kind === 'trained' ? '<span class="badge badge-trained" title="Trained in Phosphene’s Train Character workflow">Trained</span>' : ''}${familyBadges.join('')}
+ ${nameHtml}${r.kind === 'remote' ? '<span class="badge">HF</span>' : ''}${r.kind === 'trained' ? '<span class="badge badge-trained" title="Trained in Phosphene’s Train Character workflow">Trained</span>' : ''}${familyBadges.join('')}${LORA_UPDATES[r.path] ? `<button type="button" class="badge badge-update lora-update-badge" title="A newer version is on CivitAI — click to download it" onclick="event.stopPropagation(); updateLora(${pathAttr})">Update</button>` : ''}
</div>
<div class="lora-name-meta" title="${escapeHtml(trigs.join(', '))}">${escapeHtml(trigSummary)}</div>
</div>
@@ -797,6 +884,13 @@ function loraRowHtml(r, modeTag) {
oninput="this.previousElementSibling.value = this.value; setLoraStrength(${pathAttr}, this.value)">
</div>
<div class="trigger-chips">${chipsHtml}</div>
+ ${(r.kind === 'user' || r.kind === 'trained') ? `
+ <div class="lora-guide-actions">
+ ${r.guide ? '' : `<button type="button" class="ghost-btn small" ${_guideBusyAttrs()} onclick="event.stopPropagation(); writeLoraGuide(${pathAttr}, this)">Write a guide</button>
+ <span class="muted small">What it does, how to prompt it, a strength to start from — written by the planner model from the LoRA's own notes.</span>`}
+ </div>
+ ${r.guide ? `<div class="lora-guide">${escapeHtml(r.guide)}
+ <div class="lora-guide-actions"><button type="button" class="ghost-btn small" ${_guideBusyAttrs()} onclick="event.stopPropagation(); writeLoraGuide(${pathAttr}, this)">Rewrite</button></div></div>` : ''}` : ''}
</div>
</div>`;
}
@@ -1254,6 +1348,7 @@ function renderCharacterStrip() {
// Inline handlers in the markup and the other files resolve these through
// the global scope; everything NOT listed here is private to this module.
Object.assign(globalThis, {
+ checkLoraUpdates, updateLora, writeLoraGuide,
_currentLoraModeFilter, _syncLoraPickerForEngine, importH3Lora, renderH3LoraSlot,
setH3LoraSlot, _serializeLoras, addLoraToActive, populateIngredientCharLoras,
onIngredientCharChange, onIngredientCharStrength, refreshLoras, _loraGenerationCompatible,
diff --git a/webapp/js/main.js b/webapp/js/main.js
index 8bf178a..c44a571 100644
--- a/webapp/js/main.js
+++ b/webapp/js/main.js
@@ -82,3 +82,19 @@ document.querySelectorAll('#modeGroup .pill-btn').forEach(b => b.addEventListene
// surfaces: the manual generate form, the Characters tab (LoRA pair +
// prompt + ship), and Train (character LoRA training).
+
+// The completion-alert switch is read by the poller from the settings cache,
+// which used to be filled only when the Settings modal opened. One fetch at
+// boot; the modal refreshes it as before.
+(async () => {
+ try {
+ if (!globalThis._settingsCache) {
+ const r = await fetch('/settings');
+ if (r.ok) globalThis._settingsCache = await r.json();
+ }
+ } catch (e) {}
+})();
+
+// The appearance is applied at boot, before anyone looks — a stored "light"
+// that arrived after the first paint would flash the dark palette first.
+try { if (typeof applyAppearance === 'function') applyAppearance(); } catch (e) {}
diff --git a/webapp/js/queue.js b/webapp/js/queue.js
index 102854c..97d6975 100644
--- a/webapp/js/queue.js
+++ b/webapp/js/queue.js
@@ -456,6 +456,8 @@ function setEngine(engine, opts) {
// reads the engine this call actually settled on rather than the one that
// was requested — a gate may have bounced it back to the built-in.
try { _syncLoraPickerForEngine(); } catch (e) {}
+ // A take's estimate is per engine (parts on H3, a chain on LTX).
+ try { if (typeof takeRefresh === 'function') takeRefresh(); } catch (e) {}
return target;
}
@@ -825,6 +827,9 @@ function snapFramesTo8kPlus1() {
}
function updateDerived() {
+ // The per-window hint counts windows for the CURRENT length, so it has to
+ // move when the length does, not only when the pill is clicked.
+ if (typeof windowPromptsInput === 'function') { try { windowPromptsInput(); } catch (e) {} }
const mode = document.getElementById('mode').value;
const w = parseInt(document.getElementById('width').value || 0);
const h = parseInt(document.getElementById('height').value || 0);
@@ -1699,6 +1704,65 @@ function friendlyJobError(raw) {
return { friendly: 'Job failed.', hint: raw };
}
+// ---- Completion alerts ------------------------------------------------------
+// A render is minutes long. When one finishes — or fails — the tab says so
+// with a short chime, and the browser says so when the tab is in the
+// background and notifications were allowed. Keyed on the history: a job id
+// that was not done on the previous poll and is now. The first poll of a
+// page load only records what is already done, so opening the panel is never
+// a burst of alerts for last night.
+let _doneSeen = null;
+function notifyJobsDone(s) {
+ const hist = Array.isArray(s && s.history) ? s.history : [];
+ const now = new Set();
+ for (const j of hist) if (j && j.id && (j.status === 'done' || j.status === 'failed')) now.add(j.id);
+ if (_doneSeen === null) { _doneSeen = now; return; }
+ const cur = (globalThis._settingsCache && _settingsCache.settings) || {};
+ const on = cur.notify_done !== false;
+ for (const j of hist) {
+ if (!j || !j.id || !now.has(j.id) || _doneSeen.has(j.id)) continue;
+ if (on) notifyOneJob(j);
+ }
+ _doneSeen = now;
+}
+function notifyOneJob(j) {
+ const failed = j.status === 'failed';
+ const what = (j.params && (j.params.label || j.params.preset_label)) ||
+ (j.params && j.params.prompt ? String(j.params.prompt).slice(0, 60) : '') ||
+ (j.params && j.params.mode) || 'a render';
+ playDoneChime(failed);
+ try {
+ if (document.hidden && typeof window.Notification !== 'undefined' && window.Notification.permission === 'granted') {
+ const n = new window.Notification(failed ? 'Phosphene — a render failed' : 'Phosphene — render done',
+ { body: what, tag: 'phos-' + j.id, silent: true });
+ n.onclick = () => { try { window.focus(); n.close(); } catch (e) {} };
+ }
+ } catch (e) {}
+}
+// Two short tones from the Web Audio API — no asset, no download, and a
+// falling pair for a failure so the ear knows without looking.
+let _chimeCtx = null;
+function playDoneChime(failed) {
+ try {
+ const AC = window.AudioContext || window.webkitAudioContext;
+ if (!AC) return;
+ if (!_chimeCtx) _chimeCtx = new AC();
+ const ctx = _chimeCtx;
+ if (ctx.state === 'suspended') { ctx.resume().catch(() => {}); }
+ const t0 = ctx.currentTime + 0.01;
+ const notes = failed ? [[440, 0], [330, 0.16]] : [[660, 0], [880, 0.14]];
+ for (const [f, dt] of notes) {
+ const o = ctx.createOscillator(); const g = ctx.createGain();
+ o.type = 'sine'; o.frequency.value = f;
+ g.gain.setValueAtTime(0.0001, t0 + dt);
+ g.gain.exponentialRampToValueAtTime(0.12, t0 + dt + 0.02);
+ g.gain.exponentialRampToValueAtTime(0.0001, t0 + dt + 0.22);
+ o.connect(g); g.connect(ctx.destination);
+ o.start(t0 + dt); o.stop(t0 + dt + 0.25);
+ }
+ } catch (e) {}
+}
+
async function poll() {
// Reflect HDR-vs-character mutual exclusion every poll cycle. character_id
// gets set from multiple code paths (manual chip click, load-params,
@@ -1712,6 +1776,7 @@ async function poll() {
const url = '/status' + (filterMode === 'hidden' ? '?include_hidden=1' : '');
try {
s = await (await fetch(url)).json();
+ notifyJobsDone(s);
_POLL_FAILS = 0;
_setOfflineBanner(false);
} catch (e) {
@@ -2380,10 +2445,8 @@ async function poll() {
// cells. "Outputs · 23 photos" when Photos is active, plain "Outputs · N"
// when All. Hidden override stays unchanged.
const _visible = filteredMainOutputs();
- const _kindLabel = mainOutputsFilter === 'all' ? '' : ` ${mainOutputsFilter}`;
document.getElementById('carouselTitle').textContent =
- filterMode === 'hidden' ? 'Hidden outputs'
- : `Outputs · ${_visible.length}${_kindLabel}`;
+ filterMode === 'hidden' ? 'Hidden outputs' : outputsTitleText();
// "Show all (N)" button — reveal whenever the server reports more
// outputs total than the polling fast path returned, and the user
@@ -2782,7 +2845,9 @@ function renderCarousel() {
const el = document.getElementById('carousel');
const visible = filteredMainOutputs();
if (!visible.length) {
- const msg = mainOutputsFilter === 'photos' ? 'No photo outputs yet.'
+ const q = (typeof outputsQueryText === 'function') ? outputsQueryText() : '';
+ const msg = q ? ('No matches for \u201c' + escapeHtml(q) + '\u201d.')
+ : mainOutputsFilter === 'photos' ? 'No photo outputs yet.'
: mainOutputsFilter === 'videos' ? 'No video outputs yet.'
: 'No outputs in this view yet.';
el.innerHTML = `<div class="empty-msg">${msg}</div>`;
@@ -3446,6 +3511,10 @@ async function loadParams() {
try { setI2vRefMode(p.i2v_reference_mode || 'anchor'); } catch (e) {}
}
if (p.temporal_mode) setTemporalMode(p.temporal_mode);
+ // A take restores as a take (length + beats), not as the fields it was
+ // turned into — those are derived, and would re-derive differently.
+ if (p.take && p.take.seconds && typeof setTakeSeconds === 'function') setTakeSeconds(p.take.seconds, p.take.beat_prompts || p.take.beats || null);
+ else if (typeof setTakeSeconds === 'function') setTakeSeconds(0);
if (p.upscale) setUpscale(p.upscale);
if (p.upscale_method) setUpscaleMethod(p.upscale_method);
document.getElementById('prompt').value = p.prompt || '';
@@ -4469,6 +4538,7 @@ document.getElementById('genForm').addEventListener('submit', async e => {
// Inline handlers in the markup and the other files resolve these through
// the global scope; everything NOT listed here is private to this module.
Object.assign(globalThis, {
+ notifyJobsDone, notifyOneJob, playDoneChime,
h3FinishSetTier, h3FinishActive, setEngine, _syncEnginePromptTools,
currentEngine, _syncEngineForMode, openH3InstallCard, closeH3InstallCard,
enhancePrompt, applyAspect, applyQuality, updateDerived,
diff --git a/webapp/js/settings.js b/webapp/js/settings.js
index 5ae9bec..cf3e97c 100644
--- a/webapp/js/settings.js
+++ b/webapp/js/settings.js
@@ -615,6 +615,8 @@ async function openSettingsModal() {
}
const cur = _settingsCache.settings;
const presets = _settingsCache.presets;
+ renderNotifyState(cur || {});
+ applyAppearance();
// Render preset cards (Standard, Video production, Web, Custom).
// Display order matches the typical user journey: most users want
// Standard, video pros pick Video production, web preview folks pick Web.
@@ -711,6 +713,144 @@ async function openSettingsModal() {
renderAnalyticsState(cur);
}
+// ---- Appearance ------------------------------------------------------------
+// A browser preference, not a panel setting: two people can look at the same
+// panel in two rooms. `system` re-applies live when the Mac switches.
+function appearanceGet() {
+ try { const v = localStorage.getItem('phos_appearance'); return (v === 'light' || v === 'system') ? v : 'dark'; }
+ catch (e) { return 'dark'; }
+}
+function applyAppearance(mode) {
+ const m = mode || appearanceGet();
+ const dark = m === 'dark' || (m === 'system' && !(window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches));
+ document.documentElement.setAttribute('data-theme', dark ? 'dark' : 'light');
+ // The server stamps this on <html> for the NEXT load so a light palette is
+ // painted first, not switched to after the modules run (cookie, one year).
+ try { document.cookie = 'phos_theme=' + (dark ? 'dark' : 'light') + ';path=/;max-age=31536000;samesite=lax'; } catch (e) {}
+ document.querySelectorAll('#appearanceGroup .pill-btn').forEach(b =>
+ b.classList.toggle('active', b.dataset.appearance === m));
+}
+function setAppearance(mode) {
+ try { localStorage.setItem('phos_appearance', mode); } catch (e) {}
+ applyAppearance(mode);
+}
+try {
+ if (window.matchMedia) {
+ window.matchMedia('(prefers-color-scheme: light)').addEventListener('change', () => {
+ if (appearanceGet() === 'system') applyAppearance('system');
+ });
+ }
+} catch (e) {}
+
+// ---- Completion alerts -----------------------------------------------------
+// One switch, and one ask. The chime needs nothing; the browser notification
+// needs the person to allow it once, and the button says which state that is
+// in rather than asking on every render.
+function renderNotifyState(cur) {
+ const on = cur.notify_done !== false;
+ const badge = document.getElementById('notifyStateBadge');
+ const btn = document.getElementById('notifyToggleBtn');
+ const ask = document.getElementById('notifyAllowBtn');
+ const hint = document.getElementById('notifyHint');
+ if (badge) { badge.textContent = on ? 'ON' : 'OFF'; badge.className = 'spicy-state' + (on ? ' on' : ''); }
+ if (btn) btn.textContent = on ? 'Turn off' : 'Turn on';
+ const perm = (typeof window.Notification !== 'undefined') ? window.Notification.permission : 'unsupported';
+ if (ask) {
+ ask.hidden = !on || perm !== 'default';
+ }
+ if (hint) {
+ hint.textContent = !on ? 'No chime, no browser alert.'
+ : perm === 'granted' ? 'A chime in this tab, and a browser alert when the tab is in the background'
+ + (cur.push_available ? ' — and, once you turn it on below, even with the tab closed.' : '. Closed-tab alerts need an Update on this install.')
+ : perm === 'denied' ? 'A chime in this tab. Browser alerts are blocked for this site in the browser\'s own settings.'
+ : perm === 'unsupported' ? 'A chime in this tab.'
+ : 'A chime in this tab. Allow browser alerts to be told when the tab is in the background'
+ + (cur.push_available ? ', or even when it is closed.' : '.');
+ }
+ // PUSH, for a closed tab. Offered when the install can sign pushes and the
+ // browser can hold a subscription; the button says which state it is in.
+ const pb = document.getElementById('notifyPushBtn');
+ const pt = document.getElementById('notifyPushTestBtn');
+ const canPush = on && cur.push_available && ('serviceWorker' in navigator) && ('PushManager' in window) && perm !== 'denied';
+ if (pb) {
+ pb.hidden = !canPush;
+ if (canPush) {
+ pushSubscription().then(s => {
+ pb.textContent = s ? 'Stop closed-tab alerts in this browser' : 'Alert me here even when the tab is closed';
+ if (pt) pt.hidden = !s;
+ }).catch(() => {});
+ } else if (pt) pt.hidden = true;
+ }
+}
+async function toggleNotify() {
+ const cur = (_settingsCache && _settingsCache.settings) || {};
+ const target = !(cur.notify_done !== false);
+ const fd = new URLSearchParams();
+ fd.set('notify_done', target ? '1' : '0');
+ try {
+ const r = await fetch('/settings', { method: 'POST', body: fd });
+ const j = await r.json();
+ if (j.settings) _settingsCache.settings = j.settings;
+ else if (_settingsCache && _settingsCache.settings) _settingsCache.settings.notify_done = target;
+ } catch (e) {}
+ if (target && typeof playDoneChime === 'function') playDoneChime(false);
+ renderNotifyState((_settingsCache && _settingsCache.settings) || {});
+ if (typeof phosToast === 'function') phosToast(target ? 'Completion alerts on — saved.' : 'Completion alerts off — saved.', { duration: 2500 });
+}
+// ---- Push: the alert that reaches a closed tab ---------------------------
+// The browser keeps a subscription for this origin; the panel signs pushes
+// with its own key. `pushToggle` subscribes or unsubscribes THIS browser.
+function _pushKeyBytes(b64) {
+ const pad = '='.repeat((4 - b64.length % 4) % 4);
+ const raw = window.atob((b64 + pad).replace(/-/g, '+').replace(/_/g, '/'));
+ return Uint8Array.from(raw, c => c.charCodeAt(0));
+}
+async function pushSubscription() {
+ if (!('serviceWorker' in navigator) || !('PushManager' in window)) return null;
+ const reg = await navigator.serviceWorker.getRegistration('/');
+ return reg ? reg.pushManager.getSubscription() : null;
+}
+async function pushToggle() {
+ try {
+ const have = await pushSubscription();
+ if (have) {
+ const fd = new URLSearchParams(); fd.set('endpoint', have.endpoint);
+ await fetch('/push/unsubscribe', { method: 'POST', body: fd });
+ await have.unsubscribe();
+ if (typeof phosToast === 'function') phosToast('This browser will no longer be alerted when closed.', { duration: 3000 });
+ } else {
+ const k = await (await fetch('/push/key')).json();
+ if (!k.ok) { if (typeof phosToast === 'function') phosToast('Closed-tab alerts are not available on this install yet — run Update.', { kind: 'danger' }); return; }
+ if (typeof window.Notification !== 'undefined' && window.Notification.permission !== 'granted') {
+ const p = await window.Notification.requestPermission();
+ if (p !== 'granted') { if (typeof phosToast === 'function') phosToast('The browser did not allow notifications.', {}); return; }
+ }
+ const reg = await navigator.serviceWorker.register('/sw.js', { scope: '/' });
+ const sub = await reg.pushManager.subscribe({ userVisibleOnly: true,
+ applicationServerKey: _pushKeyBytes(k.public_key) });
+ const fd = new URLSearchParams(); fd.set('subscription', JSON.stringify(sub));
+ const r = await (await fetch('/push/subscribe', { method: 'POST', body: fd })).json();
+ if (typeof phosToast === 'function') phosToast(r.ok ? 'Done — this browser will be alerted even when the tab is closed.' : (r.error || 'Could not turn it on.'), { duration: 4000 });
+ }
+ } catch (e) {
+ if (typeof phosToast === 'function') phosToast('Closed-tab alerts could not be set up in this browser: ' + (e && e.message ? e.message : e), { kind: 'danger', duration: 6000 });
+ }
+ renderNotifyState((_settingsCache && _settingsCache.settings) || {});
+}
+async function pushTest() {
+ try {
+ const r = await (await fetch('/push/test', { method: 'POST' })).json();
+ if (typeof phosToast === 'function') phosToast(r.ok ? ('Sent to ' + r.sent + (r.sent === 1 ? ' browser.' : ' browsers.')) : (r.error || 'Nothing sent.'), { duration: 4000 });
+ } catch (e) {}
+}
+
+async function askNotifyPermission() {
+ try {
+ if (typeof window.Notification !== 'undefined') await window.Notification.requestPermission();
+ } catch (e) {}
+ renderNotifyState((_settingsCache && _settingsCache.settings) || {});
+}
+
// ---- Anonymous usage analytics ---------------------------------------------
// Single-click both ways: turning it OFF must be at least as easy as
// leaving it ON, which is the whole justification for defaulting to ON.
@@ -1192,6 +1332,9 @@ _applyHdrPillAvailability();
// Inline handlers in the markup and the other files resolve these through
// the global scope; everything NOT listed here is private to this module.
Object.assign(globalThis, {
+ pushSubscription, pushToggle, pushTest,
+ appearanceGet, applyAppearance, setAppearance,
+ renderNotifyState, toggleNotify, askNotifyPermission,
updateModelsCard, dismissModelsCard, applyTierGates, openTierModal,
closeTierModal, openBugModal, closeBugModal, submitBugReport,
openSettingsModal, toggleAnalytics, saveAnalyticsKey, clearAnalyticsKey,
diff --git a/webapp/js/storyboard.js b/webapp/js/storyboard.js
index 55be259..774b17c 100644
--- a/webapp/js/storyboard.js
+++ b/webapp/js/storyboard.js
@@ -377,13 +377,27 @@ function sbLocInput() {
}
let _sbShots = 12;
+// ONE TAKE is the fifth answer on the Shots row: a film that is one shot,
+// planned as beats. `_sbTake` is 0 (off) or the take's length in seconds.
+let _sbTake = 0;
function sbSetShots(n, persist) {
- _sbShots = Number(n) || 12;
+ const take = (n === 'take');
+ if (take) { if (!_sbTake) _sbTake = 60; }
+ else { _sbTake = 0; _sbShots = Number(n) || 12; }
document.querySelectorAll('#sbLengthGroup .q-chip').forEach(b =>
- b.classList.toggle('active', Number(b.dataset.sbShots) === _sbShots));
- if (persist !== false) sbSaveSetting('storyboard_shots', _sbShots);
+ b.classList.toggle('active', take ? b.dataset.sbShots === 'take' : Number(b.dataset.sbShots) === _sbShots));
+ const row = sbEl('sbTakeRow');
+ if (row) row.hidden = !take;
+ if (take) sbSetTake(_sbTake);
+ if (persist !== false && !take) sbSaveSetting('storyboard_shots', _sbShots);
+}
+function sbSetTake(secs) {
+ _sbTake = Number(secs) || 60;
+ document.querySelectorAll('#sbTakeGroup .pill-btn').forEach(b =>
+ b.classList.toggle('active', Number(b.dataset.sbTake) === _sbTake));
}
function sbShotsValue() {
+ if (_sbTake) return Math.round(_sbTake / 5);
const on = document.querySelector('#sbLengthGroup .q-chip.active');
return on ? Number(on.dataset.sbShots) : _sbShots;
}
@@ -394,6 +408,40 @@ async function sbSaveSetting(key, value) {
} catch (e) {}
}
+function sbToggleSwitchHelp() {
+ const btn = sbEl('sbSwitchHelpBtn'), note = sbEl('sbSwitchHelpNote');
+ if (!btn || !note) return;
+ const open = btn.getAttribute('aria-expanded') === 'true';
+ btn.setAttribute('aria-expanded', open ? 'false' : 'true');
+ note.hidden = open;
+}
+// The long-shot switch needs the Q8 pack (the chain runs on the dev
+// transformer). Say so on the switch, from the status the panel already has,
+// rather than at render time per shot.
+function sbSyncBriefGates() {
+ const el = sbEl('sbLongWindows');
+ if (!el) return;
+ const s = globalThis.LAST_STATUS;
+ if (!s) return;
+ const ok = !!s.q8_available;
+ el.disabled = !ok;
+ if (!ok && el.checked) el.checked = false;
+ const lab = el.closest('label');
+ if (lab) lab.title = ok
+ ? 'A shot longer than 5 seconds renders as a chain of 5-second passes, each continuing from the last, instead of being shortened to fit one. Slower. LTX shots only.'
+ : 'Needs the Q8 pack — download it from the launcher menu first.';
+}
+async function sbRestill(n) {
+ const fd = new FormData();
+ fd.set('id', SB.id); fd.set('n', String(n));
+ let r;
+ try { r = await (await fetch('/storyboard/restill', { method: 'POST', body: fd })).json(); }
+ catch (e) { r = { ok: false, error: String(e) }; }
+ if (!r.ok) { phosToast(r.error || 'Could not start a new still.', { kind: 'danger', duration: 6000 }); return; }
+ phosToast(`A new still for shot ${n} is being made; the shot renders from it when it lands.`, { duration: 6000 });
+ sbLoad(SB.id, true);
+}
+
function sbToggleRamHelp() {
const btn = sbEl('sbRamHelpBtn'), note = sbEl('sbRamHelpNote');
if (!btn || !note) return;
@@ -589,12 +637,23 @@ async function sbPlan() {
const fd = new URLSearchParams();
fd.set('concept', concept);
fd.set('shots', String(sbShotsValue()));
+ fd.set('take_seconds', String(_sbTake || 0));
fd.set('style', (sbEl('sbStyle') || {}).value || '');
fd.set('must', (sbEl('sbMust') || {}).value || '');
fd.set('locations', (sbEl('sbLocations') || {}).value || '');
fd.set('wardrobe', (sbEl('sbWardrobe') || {}).value || '');
fd.set('engine', _sbEngineMode);
if (_sbCastId) fd.set('character_id', _sbCastId);
+ // The director's two fields travel whenever the row exists, so clearing
+ // the path is a real "no soundtrack" and not an absent field the server
+ // would read as "keep what the board had".
+ if (sbEl('sbTrack')) {
+ fd.set('soundtrack', (sbEl('sbTrack').value || '').trim());
+ fd.set('bars_per_shot', (sbEl('sbTrackBars') || {}).value || '2');
+ }
+ if (sbEl('sbAuto')) fd.set('auto', sbEl('sbAuto').checked ? '1' : '0');
+ if (sbEl('sbAnchorStills')) fd.set('anchor_stills', sbEl('sbAnchorStills').checked ? '1' : '0');
+ if (sbEl('sbLongWindows')) fd.set('long_windows', sbEl('sbLongWindows').checked ? '1' : '0');
let r;
try {
r = await (await fetch('/storyboard/plan', { method: 'POST', body: fd })).json();
@@ -606,10 +665,30 @@ async function sbPlan() {
}
SB.id = r.id;
try { localStorage.setItem('phos_sb_open', SB.id); } catch (e) {}
+ if (sbEl('sbAuto') && sbEl('sbAuto').checked) {
+ phosToast('Auto is on: after the plan, every shot renders, the cut is made and the film is assembled on their own. The Film screen shows it when it lands.',
+ { duration: 9000 });
+ }
sbShow('planning');
sbSetPlanningStage('load');
sbLoad(SB.id);
}
+// THE SHOTS CHIPS STAND DOWN WHEN A TRACK IS ON THE BRIEF — the grid decides
+// the count — and the line under the field says what will happen instead.
+function sbTrackInput() {
+ const path = ((sbEl('sbTrack') || {}).value || '').trim();
+ const bars = (sbEl('sbTrackBars') || {}).value || '2';
+ const meta = sbEl('sbTrackMeta');
+ const row = sbEl('sbLengthRow');
+ if (meta) {
+ meta.textContent = path
+ ? 'music video — one shot per ' + bars + ' bar' + (bars === '1' ? '' : 's')
+ + ' on the downbeat; the track replaces the clips\' own sound and sets the shot count'
+ : 'optional — a track makes it a music video cut to the beat';
+ }
+ if (row) row.classList.toggle('is-standing-down', !!path);
+}
+
function sbPlanBtnReset() {
const btn = sbEl('sbPlanBtn');
if (!btn) return;
@@ -629,12 +708,13 @@ async function sbCancelPlan() {
function sbSetPlanningStage(stage) {
const map = {
load: ['Loading the planner', 'About a minute. Nothing renders yet.'],
+ grid: ['Reading the beat', 'Finding the downbeats the shots will cut on.'],
write: ['Writing the plan', 'About a minute. Nothing renders yet.'],
check: ['Checking the plan', 'About a minute. Nothing renders yet.'],
repair: ['Fixing the plan', 'It came back slightly malformed. One retry.'],
unload: ['Giving the memory back', 'The renderer gets it now.'],
};
- const order = ['load', 'write', 'check', 'repair', 'unload'];
+ const order = ['load', 'grid', 'write', 'check', 'repair', 'unload'];
const at = order.indexOf(stage);
const t = map[stage] || map.load;
const ttl = sbEl('sbPlanningTitle'), sub = sbEl('sbPlanningSub');
@@ -1005,6 +1085,17 @@ function sbRenderPlan(r) {
const shots = b.shots || [];
const title = sbEl('sbTitle');
if (title && document.activeElement !== title) title.value = b.title || '';
+ // The three brief switches read back from the board, so reopening a film
+ // shows how it is being made — not whatever the last brief had ticked.
+ for (const [id, key] of [['sbAuto', 'auto'], ['sbAnchorStills', 'anchor_stills'], ['sbLongWindows', 'long_windows']]) {
+ const el = sbEl(id);
+ if (el && key in b) el.checked = !!b[key];
+ }
+ if ('take_seconds' in b) {
+ if (b.take_seconds) { sbSetShots('take', false); sbSetTake(b.take_seconds); }
+ else sbSetShots(b.shots_target || _sbShots, false);
+ }
+ sbSyncBriefGates();
// --- summary ---
// Per PASS, not per `status`: during delivery, `status === 'done'` still
@@ -1265,6 +1356,19 @@ function sbShotCard(s, r, errs) {
const passLabel = r.pass === 'final' ? 'Delivery' : 'Draft';
const seedSet = (s.seed != null && s.seed !== -1);
+ // ANCHOR STILL. The image the shot starts from, when the board anchors
+ // shots; a failed still says so and the shot renders unanchored.
+ const stillPending = !s.still && !s.still_error && s.still_job_id && s.still_job_id !== 'skipped';
+ const stillBlock = s.still ? `
+ <div class="sb-still" title="The still this shot starts from">
+ <a href="/image?path=${encodeURIComponent(s.still)}" target="_blank" rel="noopener" title="Open the still">
+ <img src="/image?w=480&path=${encodeURIComponent(s.still)}" alt="Anchor still for shot ${n}" loading="lazy"></a>
+ <span class="sb-still-tag">starts from this still</span>
+ <button type="button" class="sb-err-fix sb-still-redo" data-act="restill" title="Make a new still and render this shot from it">New still</button>
+ </div>` : stillPending ? `
+ <div class="sb-still is-pending"><span class="sb-still-spin" aria-hidden="true"></span><span class="sb-still-tag">making the still…</span></div>`
+ : (s.still_error ? `<div class="sb-still sb-still-failed" title="${escapeHtml(s.still_error)}"><span class="sb-still-tag">no still — rendered unanchored</span>
+ <button type="button" class="sb-err-fix sb-still-redo" data-act="restill" title="Try the still again">Try again</button></div>` : '');
const outBlock = stale ? `
<div class="sb-shot-out car-card is-stale">
<div class="car-thumb-wrap" onclick="selectOutput('${escapeHtml(stale)}')">
@@ -1331,9 +1435,13 @@ function sbShotCard(s, r, errs) {
</div>
<textarea class="sb-shot-prompt" rows="3" spellcheck="false" data-act="prompt"
${locked ? 'readonly' : ''} title="${escapeHtml(s.title || '')}">${escapeHtml(s.prompt || '')}</textarea>
+ ${s.take_seconds ? `
+ <div class="sb-beats-label">One take · ${s.take_seconds} s · ${Math.round(s.take_seconds / 5)} beats <span class="sub">one line per 5 seconds · the first beat is the prompt above</span></div>
+ <textarea class="sb-shot-prompt sb-beats" rows="${Math.min(12, Math.round(s.take_seconds / 5))}" spellcheck="false" data-act="beats"
+ ${locked ? 'readonly' : ''}>${escapeHtml((s.beats || []).join('\n'))}</textarea>` : ''}
${mine.length ? `<div class="sb-shot-err">${mine.map(sbErrRow).join('')}</div>` : ''}
${failBlock}
- ${outBlock}
+ ${stillBlock}${outBlock}
</li>`;
}
@@ -1396,14 +1504,24 @@ function sbRenderRunBar(r) {
const paused = LAST_STATUS && LAST_STATUS.paused;
sbEl('sbRunTitle').textContent = paused
? `Paused · ${done} of ${shots.length} done`
- : (active ? `Shot ${active.n} of ${shots.length}` : `${done} of ${shots.length} done`);
+ : (active ? (tag.still ? `Still for shot ${active.n} of ${shots.length}` : `Shot ${active.n} of ${shots.length}`)
+ : `${done} of ${shots.length} done`);
let sub = '';
- if (active) sub = `S${String(active.n).padStart(2, '0')} · ${snippet(active.prompt, 40)}`;
+ if (active) sub = (tag.still ? 'making the still · ' : '') + `S${String(active.n).padStart(2, '0')} · ${snippet(active.prompt, 40)}`;
// The remaining time is a SERVER number. /status.eta_sec is the sum of
// per-job ETAs and is trustworthy when every queued job is this film's.
const q = (LAST_STATUS && LAST_STATUS.queue) || [];
const allMine = q.length && q.every(j => { const t = _sbTagOf(j); return t && t.id === SB.id; });
if (allMine && LAST_STATUS.eta_sec) sub += ` · ${sbFmtWall(LAST_STATUS.eta_sec)} left`;
+ else {
+ // THE FILM'S OWN NUMBER when the queue's is not ours to read: the sum
+ // of the per-shot estimates for what this pass has not landed yet,
+ // from the same cost model the summary cell prices the film with.
+ const per = r.per_shot_est || {};
+ const left = shots.filter(s => !s[outKey] && s.status !== 'skipped')
+ .reduce((a, s) => a + (Number(per[String(s.n)]) || 0), 0);
+ if (left > 0) sub += ` · ${sbFmtWall(left)} left`;
+ }
sbEl('sbRunSub').textContent = sub;
sbEl('sbPauseBtn').textContent = paused ? 'Resume' : 'Pause';
sbEl('sbRunDots').innerHTML = shots.map(s => {
@@ -1424,8 +1542,10 @@ function sbRenderRunBar(r) {
}
function _sbTagOf(job) {
- const m = /^sb:([^#]+)#(\d+)$/.exec(((job || {}).params || {}).session_tag || '');
- return m ? { id: m[1], n: Number(m[2]) } : null;
+ // `sb:<board>#<n>` is a shot's clip; `sb:<board>#<n>:still` is the anchor
+ // still made before it. Both belong to the film.
+ const m = /^sb:([^#]+)#(\d+)(:still)?$/.exec(((job || {}).params || {}).session_tag || '');
+ return m ? { id: m[1], n: Number(m[2]), still: !!m[3] } : null;
}
function sbScrollToShot(n) {
const el = document.querySelector(`.sb-shot[data-n="${n}"]`);
@@ -1578,6 +1698,7 @@ function sbShotAction(n, act, el, ev) {
}
case 'note': s.note = el.value; sbGrade(n, s.grade, el.value); return;
case 'retry': sbRenderPass(SB.payload.pass || 'draft', [n]); return;
+ case 'restill': sbRestill(n); return;
case 'cut': sbGrade(n, 'cut', s.note || ''); return;
default: return;
}
@@ -2034,7 +2155,9 @@ function sbPollHook(s) {
// ---- wiring ----------------------------------------------------------------
document.addEventListener('click', (ev) => {
const chip = ev.target.closest && ev.target.closest('#sbLengthGroup .q-chip');
- if (chip) { sbSetShots(Number(chip.dataset.sbShots)); return; }
+ if (chip) { sbSetShots(chip.dataset.sbShots === 'take' ? 'take' : Number(chip.dataset.sbShots)); return; }
+ const tk = ev.target.closest && ev.target.closest('#sbTakeGroup [data-sb-take]');
+ if (tk) { sbSetTake(tk.dataset.sbTake); return; }
const eng = ev.target.closest && ev.target.closest('#sbEngineGroup [data-sb-engine]');
if (eng) { sbSetEngineMode(eng.dataset.sbEngine); return; }
const reng = ev.target.closest && ev.target.closest('#sbReplanEngineGroup [data-sb-engine]');
@@ -2107,12 +2230,29 @@ document.addEventListener('focusout', (ev) => {
let _sbPromptTimer = null;
document.addEventListener('input', (ev) => {
+ const bel = ev.target.closest && ev.target.closest('#sbShots textarea[data-act="beats"]');
+ if (bel) {
+ // The beats of a take: one line per 5 s, kept as a list the length of
+ // the take; beat 1 is also the shot's prompt.
+ const li = bel.closest('.sb-shot');
+ const s = sbShotById(Number(li.dataset.n));
+ if (!s) return;
+ const n = Math.max(1, Math.round((s.take_seconds || 0) / 5));
+ const lines = String(bel.value || '').split('\n').map(x => x.trim()).slice(0, n);
+ while (lines.length < n) lines.push('');
+ s.beats = lines;
+ if (lines[0]) { s.prompt = lines[0]; const pe = li.querySelector('textarea[data-act="prompt"]'); if (pe && pe.value !== lines[0]) pe.value = lines[0]; }
+ if (_sbPromptTimer) clearTimeout(_sbPromptTimer);
+ _sbPromptTimer = setTimeout(() => sbQueueSave(true), 800);
+ return;
+ }
const el = ev.target.closest && ev.target.closest('#sbShots textarea[data-act="prompt"]');
if (!el) return;
const li = el.closest('.sb-shot');
const s = sbShotById(Number(li.dataset.n));
if (!s) return;
s.prompt = el.value;
+ if (s.take_seconds && Array.isArray(s.beats)) s.beats[0] = el.value;
sbAutoGrowPrompts(el);
if (_sbPromptTimer) clearTimeout(_sbPromptTimer);
_sbPromptTimer = setTimeout(() => sbQueueSave(true), 800);
@@ -2178,6 +2318,9 @@ document.addEventListener('dragend', () => {
// Inline handlers in the markup and the other files resolve these through
// the global scope; everything NOT listed here is private to this module.
Object.assign(globalThis, {
+ sbSetTake,
+ sbToggleSwitchHelp, sbSyncBriefGates, sbRestill,
+ sbTrackInput,
sbEl, sbFmtClock, sbFmtBytes, sbFmtAgo,
sbFilmKind, sbFilmPick, sbRenderFinalQualities, sbInit,
sbTeardown, sbConceptInput, sbMustInput, sbLocInput,
diff --git a/webapp/prompting.html b/webapp/prompting.html
new file mode 100644
index 0000000..505ad91
--- /dev/null
+++ b/webapp/prompting.html
@@ -0,0 +1,32 @@
+<!doctype html>
+<meta charset="utf-8">
+<title>Writing for Phosphene</title>
+<style>
+ body{max-width:760px;margin:40px auto;padding:0 20px;font:16px/1.55 -apple-system,Helvetica,Arial,sans-serif;color:#151a2e;background:#f7f8fc}
+ h1{font-size:26px}h2{font-size:19px;margin-top:28px}li{margin:6px 0}
+ button{font:inherit;padding:8px 14px;border-radius:8px;border:1px solid #b9c0d4;background:#fff;cursor:pointer}
+ @media(prefers-color-scheme:dark){body{background:#0b0e1a;color:#e8ecf7}button{background:#1a2036;color:#e8ecf7;border-color:#3d477a}}
+</style>
+<button id="copy">Copy this guide for your assistant</button>
+<div id="out"></div>
+<pre id="md" hidden>__GUIDE_MD__</pre>
+<script>
+ // The guide is docs/PROMPTING.md, verbatim, escaped into #md by the server.
+ // This turns its headings, bullets and paragraphs into elements; the copy
+ // button copies the markdown itself so an assistant gets the real text.
+ const md = document.getElementById('md').textContent;
+ const out = document.getElementById('out');
+ const esc = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;');
+ const inline = (s) => esc(s).replace(/\*\*(.+?)\*\*/g, '<b>$1</b>').replace(/\*(.+?)\*/g, '<i>$1</i>');
+ out.innerHTML = md.split(/\n\n+/).map((p) => {
+ const t = p.trim();
+ if (!t) return '';
+ if (t.startsWith('# ')) return '<h1>' + inline(t.slice(2)) + '</h1>';
+ if (t.startsWith('## ')) return '<h2>' + inline(t.slice(3)) + '</h2>';
+ if (t.startsWith('- ')) return '<ul>' + t.split('\n').filter(l => l.startsWith('- ')).map(l => '<li>' + inline(l.slice(2)) + '</li>').join('') + '</ul>';
+ return '<p>' + inline(t) + '</p>';
+ }).join('');
+ document.getElementById('copy').onclick = function () {
+ navigator.clipboard.writeText(md).then(() => { this.textContent = 'Copied — paste it into your assistant'; });
+ };
+</script>
diff --git a/webapp/style/panel.css b/webapp/style/panel.css
index 3891eab..ab0cf01 100644
--- a/webapp/style/panel.css
+++ b/webapp/style/panel.css
@@ -34,6 +34,42 @@
--t-base: 180ms cubic-bezier(.2,.8,.2,1);
--t-slow: 240ms cubic-bezier(.2,.8,.2,1);
}
+ /* LIGHT APPEARANCE. The same tokens, a paper palette: the panel is
+ written against --bg/--panel/--text/--muted/--border, so a second set
+ of values is most of a second theme. The overlays that were written as
+ white-with-alpha on navy are re-pointed below where they would vanish
+ on paper. Chosen from Settings → Appearance; `system` follows the OS. */
+ html[data-theme="light"] {
+ --bg: #f3f4f8; --bg-2: #e9ebf2; --panel: #ffffff; --panel-2: #f6f7fb;
+ --border: #d6dae6; --border-strong: #b9c0d4; --text: #151a2e; --muted: #5b6480;
+ --accent: #2563eb; --accent-bright: #1d4ed8; --accent-dim: rgba(37,99,235,0.14);
+ --success: #15803d; --warning: #b45309; --danger: #dc2626;
+ --shadow-1: 0 1px 2px rgba(20,26,46,0.10), 0 1px 0 rgba(255,255,255,0.6) inset;
+ --shadow-2: 0 8px 24px rgba(20,26,46,0.16);
+ color-scheme: light;
+ }
+ html[data-theme="light"] body { background: var(--bg); color: var(--text); }
+ html[data-theme="light"] .sbe-clip { background: linear-gradient(180deg, #ffffff, #f2f4fa); }
+
+ /* Light: the surfaces that were white-alpha on dark (invisible on white) */
+ html[data-theme="light"] .tabs button .badge { color: var(--accent); background: color-mix(in srgb, var(--accent) 14%, transparent); }
+ html[data-theme="light"] .card-chrome button, html[data-theme="light"] .card-chrome .card-btn { background: rgba(0,0,0,.06); color: var(--text); }
+ html[data-theme="light"] .card-chrome button:hover, html[data-theme="light"] .card-chrome .card-btn:hover { background: rgba(0,0,0,.12); }
+ html[data-theme="light"] .progress-bar { background: rgba(0,0,0,.08); }
+ html[data-theme="light"] #healthChip { background: rgba(0,0,0,.05); }
+ html[data-theme="light"] #healthChip:hover { background: rgba(0,0,0,.10); }
+ html[data-theme="light"] .phosphene-x-link:hover { color: var(--text); }
+ html[data-theme="light"] .sb-boardlist li .badge { background: rgba(0,0,0,.06); }
+ html[data-theme="light"] .ideo-fab-sw, html[data-theme="light"] .ideo-swatch { border-color: rgba(0,0,0,.22); }
+ html[data-theme="light"] .cz-summary:hover { background: rgba(0,0,0,.03); }
+ html[data-theme="light"] .lora-guide, html[data-theme="light"] .sb-still { background: #f4f5fa; }
+ html[data-theme="light"] .sbe-stage, html[data-theme="light"] .sbe-clip.is-slug { background: #0b0f1f; }
+ html[data-theme="light"] .sbe-grip { background: linear-gradient(90deg, rgba(20,26,46,0.10), transparent); }
+ html[data-theme="light"] .sbe-grip.r { background: linear-gradient(270deg, rgba(20,26,46,0.10), transparent); }
+ html[data-theme="light"] .sbe-cut { background: rgba(20,26,46,0.45); }
+ html[data-theme="light"] .sbe-ov { color: #4c1d95; }
+ html[data-theme="light"] .sbe-ruler u { color: rgba(20,26,46,0.75); background: rgba(20,26,46,0.10); }
+ html[data-theme="light"] .sbe-track.is-dropping { background: rgba(20,26,46,0.04); }
* { box-sizing: border-box; }
html, body { margin: 0; height: 100%; }
@@ -2159,6 +2195,25 @@
position: relative; height: 18px; border-bottom: 1px solid var(--border);
color: var(--muted); font-size: var(--fs-2xs); user-select: none; cursor: pointer;
}
+ /* THE SONG'S SECTIONS GET A ROW OF THEIR OWN above the ticks — the
+ first version was a 7px strip under the numerals and read as a stray
+ underline. 14px, a legible label, and a hue per kind so the arc is
+ readable at a glance: chorus violet, bridge blue, verse grey, the two
+ ends warm and cool. */
+ .sbe-ruler.has-sections { height: 32px; }
+ .sbe-ruler.has-sections i, .sbe-ruler.has-sections b { top: 14px; }
+ .sbe-ruler u {
+ position: absolute; top: 1px; height: 12px; text-decoration: none;
+ border-radius: 3px; overflow: hidden; white-space: nowrap;
+ font-size: 9px; line-height: 12px; letter-spacing: 0.08em; text-transform: uppercase;
+ font-weight: 700; color: rgba(255,255,255,0.85); padding: 0 5px; pointer-events: auto;
+ background: rgba(255,255,255,0.12); box-shadow: inset 0 0 0 1px rgba(255,255,255,0.08);
+ }
+ .sbe-ruler u.is-chorus { background: rgba(169,112,255,0.55); }
+ .sbe-ruler u.is-verse { background: rgba(255,255,255,0.16); }
+ .sbe-ruler u.is-bridge { background: rgba(100,180,255,0.40); }
+ .sbe-ruler u.is-intro { background: rgba(255,170,90,0.35); }
+ .sbe-ruler u.is-outro { background: rgba(90,200,220,0.30); }
.sbe-ruler i {
position: absolute; top: 0; bottom: 0; width: 1px;
background: var(--border);
@@ -2222,6 +2277,39 @@
object-fit: contain; pointer-events: none; display: none; z-index: 4;
}
.sbe-ov-layer.is-on { display: block; }
+ /* THE TITLE ON THE STAGE. Positioned by the same anchor the rasteriser
+ uses — `--tx-x/--tx-y` are fractions of the frame, `--tx-shift` is
+ the align's share of the text's own width — and sized by `--tx-size`,
+ which the painter derives from the stage's height exactly as the
+ render derives it from the frame's. The font stack is the same
+ family order `TITLE_FONT_CANDIDATES` resolves on disk. */
+ .sbe-ov-text {
+ position: absolute; left: var(--tx-left, 50%); top: var(--tx-y, 50%);
+ transform: translate(var(--tx-shift, -50%), -50%);
+ max-width: 96%; pointer-events: none; display: none; z-index: 5;
+ font-family: Arial, "Helvetica Neue", Helvetica, "Liberation Sans", sans-serif;
+ font-weight: 700; font-size: var(--tx-size, 32px); line-height: 1.25;
+ color: var(--tx-color, #fff); text-align: var(--tx-align, center);
+ white-space: pre-wrap; background: var(--tx-box, transparent);
+ padding: 0.4em 0.4em; box-decoration-break: clone;
+ }
+ .sbe-ov-text.is-on { display: block; }
+ /* A title on the lane: a violet "T" where a card shows its thumbnail. */
+ .sbe-ov.is-text { background: rgba(190,120,255,0.12); }
+ .sbe-ov-t {
+ display: inline-block; width: 16px; height: 16px; line-height: 16px;
+ margin-right: 5px; border-radius: 3px; text-align: center;
+ background: #a970ff; color: #14101c; font-weight: 800; font-size: 11px;
+ vertical-align: -3px;
+ }
+ .sbe-title-b { align-items: center; }
+ .sbe-title-text { flex: 1 1 100%; width: 100%; resize: vertical; min-height: 36px; font-size: var(--fs-xs); }
+ .sbe-swatch {
+ width: 26px; height: 20px; padding: 0; border: 1px solid var(--border-strong);
+ border-radius: var(--r-xs); background: transparent; cursor: pointer;
+ }
+ .sbe-title-pos input[type="range"] { width: 90px; }
+ .sbe-title-box { margin: 0; font-size: var(--fs-xs); }
/* THE LANE THE HANDLE EXISTS FOR. 26px was a second reading of blocks you
had already read; it is now a waveform with a level line and draggable
points on it, and a point you cannot hit is a control you do not have.
@@ -2768,6 +2856,63 @@
padding: 0 4px; overflow: hidden;
}
.sbe-gap:hover { border-color: var(--accent); color: var(--text); }
+ /* THE CUT, AS A HANDLE. A transition is a property of the boundary
+ between two clips, so the boundary is where it is found: a small mark
+ at the top of every cut, and — once a transition is on it — a band
+ the length of the transition, centred on the cut, drawn over both
+ grips. Nothing new below the track, nothing that reads as a lane. */
+ .sbe-cut {
+ position: absolute; top: 0; width: 12px; height: 12px; z-index: 8;
+ cursor: pointer; border-radius: 0 0 3px 3px;
+ background: rgba(255,255,255,0.42); opacity: 0.85;
+ box-shadow: 0 1px 2px rgba(0,0,0,0.5);
+ transition: opacity var(--t-fast), background var(--t-fast);
+ }
+ .sbe-cut::before {
+ content: ''; position: absolute; inset: -6px -6px -4px; /* a bigger target */
+ }
+ .sbe-track:hover .sbe-cut { opacity: 1; }
+ .sbe-cut:hover, .sbe-cut.is-sel { background: var(--accent); opacity: 1; }
+ .sbe-cut.is-sel { box-shadow: 0 0 0 1px var(--accent), 0 0 8px var(--accent); }
+ .sbe-cut.is-bad { background: var(--danger); opacity: 1; }
+ .sbe-cut.is-tx {
+ height: 14px; border-radius: 0 0 4px 4px; opacity: 0.95;
+ background: linear-gradient(90deg, transparent, var(--accent) 35%, var(--accent) 65%, transparent);
+ display: flex; align-items: center; justify-content: center;
+ color: #fff; font-size: var(--fs-2xs); font-weight: 700; letter-spacing: 0.02em;
+ text-shadow: 0 1px 2px rgba(0,0,0,0.6); white-space: nowrap; overflow: hidden;
+ }
+ .sbe-cut.is-tx.is-sel { background: var(--accent); }
+ .sbe-cut.is-tx.is-fade_black {
+ background: linear-gradient(90deg, transparent, #000 35%, #000 65%, transparent);
+ box-shadow: inset 0 0 0 1px var(--accent);
+ }
+ .sbe-cut.is-tx.is-fade_black.is-sel { background: #000; box-shadow: 0 0 0 1px var(--accent), 0 0 8px var(--accent); }
+ .sbe-clip.is-retimed .sbe-cl-flag { color: var(--accent-bright); }
+ .sbe-frame-row input[type="range"] { width: 90px; }
+ /* A reframed layer must not spill past the stage: the stage clips. */
+ .sbe-stage { overflow: hidden; }
+ .sbe-speed-row .ghost-btn.sbe-speed-pill { padding: 1px 6px; font-size: var(--fs-2xs); }
+ .sbe-speed-row .ghost-btn.sbe-speed-pill.is-on { border-color: var(--accent); color: var(--accent-bright); }
+ .sbe-tx-kind { font-size: var(--fs-xs); padding: 2px 4px; }
+ .sbe-why.is-bad { color: var(--danger); }
+ /* The director's row on the storyboard brief: path and bars on one line,
+ and the Shots chips dimmed while a track is deciding the count. */
+ .outputs-search { width: 210px; max-width: 34%; font-size: var(--fs-xs); padding: 3px 10px; margin-left: 8px; border-radius: 999px; align-self: center; }
+ /* 5. the Clip section's buttons in even rows */
+ .sbe-sect-b .ghost-btn { flex: 0 0 auto; }
+ /* 7. a caption under each Deliver-as row */
+ .sbe-deliver-cap { display: block; font-size: var(--fs-2xs); color: var(--muted); margin: -2px 0 6px; }
+ .sbe-pop .sbe-deliver { display: flex; margin: 2px 0 4px; }
+ .sbe-pop .sbe-deliver .pill-btn { font-size: var(--fs-2xs); padding: 4px 6px; }
+ .sb-auto { margin: 4px 0 8px; font-size: var(--fs-xs); }
+ .sb-track-row { display: flex; gap: 8px; align-items: center; }
+ .sb-track-row .sb-input { flex: 1 1 auto; min-width: 0; }
+ .sb-track-bars { flex: 0 0 auto; width: auto; min-width: 150px; }
+ #sbLengthRow.is-standing-down { opacity: 0.45; pointer-events: none; }
+ /* `.cz-control` sets a display, which beats the UA's [hidden]; say it
+ explicitly or the per-window row shows under every pill. */
+ #windowsRow[hidden] { display: none !important; }
.sbe-head-line {
position: absolute; top: 0; bottom: 0; width: 2px; z-index: 30;
background: var(--warning); pointer-events: none;
@@ -9802,3 +9947,45 @@
color: var(--muted);
}
.h3-winhelp[hidden] { display: none !important; }
+
+
+/* ---- Storyboard: the anchor still on a shot card ---------------------------- */
+.sb-still { position: relative; margin: 6px 0 4px; border-radius: 8px; overflow: hidden;
+ background: var(--bg-2, #111); border: 1px solid var(--border); }
+.sb-still img { display: block; width: 100%; max-height: 120px; object-fit: cover; cursor: zoom-in; }
+.sb-still-tag { position: absolute; left: 6px; bottom: 6px; font-size: 10px; letter-spacing: .04em;
+ text-transform: uppercase; padding: 2px 6px; border-radius: 999px; background: rgba(0,0,0,.6); color: #fff; }
+.sb-still-failed { padding: 8px; }
+.sb-still-failed .sb-still-tag { position: static; background: color-mix(in srgb, var(--warning) 18%, transparent); color: var(--warning); }
+
+/* ---- LoRA picker: updates + guides ----------------------------------------- */
+.badge-update { background: var(--accent, #8b5cf6); color: #fff; margin-left: 6px; }
+.lora-update-btn { color: var(--accent, #8b5cf6); }
+.lora-guide { margin: 8px 0 2px; padding: 8px 10px; border-radius: 8px; background: var(--bg-2, #111);
+ border: 1px solid var(--border); font-size: var(--fs-sm, 12px); line-height: 1.45; color: var(--muted); }
+.lora-guide-actions { display: flex; gap: 8px; align-items: center; margin-top: 6px; }
+
+.sb-still.is-pending { padding: 10px 8px; display: flex; align-items: center; gap: 8px; }
+.sb-still.is-pending .sb-still-tag { position: static; background: color-mix(in srgb, var(--accent) 18%, transparent); color: var(--accent-bright, var(--accent)); }
+.sb-still-spin { width: 10px; height: 10px; border-radius: 50%; border: 2px solid var(--border); border-top-color: var(--accent); animation: sbStillSpin 1s linear infinite; }
+@keyframes sbStillSpin { to { transform: rotate(360deg); } }
+.sb-still-redo { position: absolute; right: 6px; top: 6px; }
+.sb-flag { display: inline-flex; align-items: center; gap: 4px; font-size: var(--fs-sm, 12px); padding: 2px 8px; border-radius: 999px;
+ background: color-mix(in srgb, var(--accent) 14%, transparent); color: var(--accent-bright, var(--accent)); margin-left: 6px; }
+.ghost-btn.small { padding: 3px 9px; font-size: var(--fs-sm, 12px); }
+.lora-update-badge { cursor: pointer; }
+
+/* ---- One take ---------------------------------------------------------------- */
+.take-locked { opacity: .45; pointer-events: none; }
+.take-locked::after { content: ''; }
+#beatsRow { margin-top: 8px; }
+.take-estimate { margin-top: 6px; font-size: var(--fs-sm, 12px); color: var(--muted); min-height: 1.2em; }
+
+.sb-beats-label { margin-top: 8px; font-size: var(--fs-sm, 12px); color: var(--muted); }
+.sb-beats-label .sub { opacity: .8; margin-left: 6px; }
+.sb-beats { margin-top: 4px; }
+
+/* ---- Timeline gestures: ripple state ------------------------------------------ */
+.sbe-track.is-ripple .sbe-clip.is-drag { box-shadow: 0 0 0 2px var(--warning), var(--shadow-2); }
+.sbe-track.is-ripple::after { content: 'ripple · everything after slides'; position: absolute; right: 8px; top: 4px;
+ font-size: var(--fs-sm, 12px); color: var(--warning); pointer-events: none; z-index: 30; }
diff --git a/webapp/sw.js b/webapp/sw.js
new file mode 100644
index 0000000..10c456e
--- /dev/null
+++ b/webapp/sw.js
@@ -0,0 +1,21 @@
+// Phosphene's push service worker. One job: turn a push message into a
+// notification when the tab is closed, and focus or open the panel when it is
+// clicked. It caches nothing and intercepts no request — the panel is local.
+self.addEventListener('install', () => self.skipWaiting());
+self.addEventListener('activate', (e) => e.waitUntil(self.clients.claim()));
+self.addEventListener('push', (e) => {
+ let d = {};
+ try { d = e.data ? e.data.json() : {}; } catch (err) { d = { title: 'Phosphene', body: (e.data && e.data.text()) || '' }; }
+ e.waitUntil(self.registration.showNotification(d.title || 'Phosphene', {
+ body: d.body || '', tag: d.tag || 'phos', renotify: true,
+ icon: '/assets/phosphene_favicon_256.png',
+ }));
+});
+self.addEventListener('notificationclick', (e) => {
+ e.notification.close();
+ e.waitUntil(self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then((list) => {
+ for (const c of list) { if ('focus' in c) return c.focus(); }
+ if (self.clients.openWindow) return self.clients.openWindow('/');
+ return null;
+ }));
+});