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.
Python ai-filmmakingai-videoai-video-generatorapple-siliconhailuoimage-to-videolip-synclocal-ailora-trainingltx-2ltx-2-5ltx-videomacosminimax-h3mlxmusic-generationoffline-aipinokiotext-to-videovideo-generation
release(v4.16.0): the Music Studio, and more than 70 fixes
mrbizarro712879b6a057
diff --git a/.gitignore b/.gitignoreindex df7864e..ea62870 100644--- a/.gitignore+++ b/.gitignore@@ -151,3 +151,12 @@ node_modules/# YuE2 engine checkout; weights live in the shared mlx_models tree.yue2-mlx/+mlx_models/yue2-cover/+state_studio/+# 2026-09-20: `yue2-mlx/` and `node_modules/` ignore a DIRECTORY, not a symlink of the+# same name. An agent worktree carried symlinks to the real trees, `git add -A`+# committed them, and the merge replaced the real engine checkout + venv with a+# self-referential link. Same trap as ltx-2-mlx above — ignore both spellings.+yue2-mlx+node_modules+diff --git a/README.md b/README.mdindex 08a7daa..725b5a9 100644--- a/README.md+++ b/README.md@@ -19,7 +19,7 @@</p>-> **Current release: v4.15.4.** **Security fix: the image preview endpoint served files it should not have.** The local address Phosphene uses to show images could be asked for other files in its own folders, including the settings file that holds your saved Hugging Face, CivitAI and PostHog keys. It now serves image files only. Nothing leaves your Mac unless another program on it, or someone who can reach the panel over your network, asks for it; if you have ever exposed the panel beyond this Mac, rotate those keys. Press Update in Pinokio, then restart. Full notes on the [releases page](https://github.com/mrbizarro/Phosphene/releases).+> **Current release: v4.16.0.** **The Music Studio, and more than 70 fixes.** A song is now something you keep working on: every song keeps what made it, so you can make a new take, re-roll the sound, put a new style on the same score, cover it or edit the score; a Song card shows the sheet music and lyrics; the Audio view is a song list with a player bar; the composer writes lyrics, edits them section by section, and turns one description into a song (Simple mode); a Voice & style LoRA picker and a music-video planner come with it. The same release fixes more than 70 bugs, most of them found by a review of seven user flows: Editor saves that dropped transitions, LoRAs that Extend, FFLF and Q4 Audio to Video ignored, Stop that did not stop, downloads that Cancel restarted, an Update that could not rebuild an empty engine, and more. Hailuo H3 decodes video in FP16 by default (same picture, about 14% faster decode). Press Update in Pinokio, then restart. Full notes on the [releases page](https://github.com/mrbizarro/Phosphene/releases).## Overview@@ -197,30 +197,38 @@ cd phosphenegit clone https://github.com/dgrauet/ltx-2-mlx.git ltx-2-mlxcd ltx-2-mlxgit remote add fork https://github.com/mrbizarro/ltx-2-mlx.git-git fetch fork +refs/tags/v0.14.19+ltx25.6:refs/tags/v0.14.19+ltx25.6-git checkout v0.14.19+ltx25.6+git fetch fork +refs/tags/v0.14.19+ltx25.7:refs/tags/v0.14.19+ltx25.7+git checkout v0.14.19+ltx25.7cd ..# 2. Create the Python 3.11 venv inside ltx-2-mlx (uv-managed).+# Every install below uses the `uv` on your PATH — `--seed` puts pip,+# setuptools and wheel into the venv, not uv, so there is no env/bin/uv.cd ltx-2-mlxuv venv --python 3.11 --seed env# 3. Install the MLX pipeline + trainer packages. Pin mlx to 0.31.1 —-# 0.31.2 attenuates the LTX vocoder by 22 dB.-./env/bin/uv pip install --python env/bin/python \- 'mlx==0.31.1' 'mlx-lm==0.31.1' 'mlx-metal==0.31.1'+# 0.31.2 attenuates the LTX vocoder by 22 dB — and cap transformers below+# 5.13.0, which breaks every generation. Both on the same resolve.+uv pip install --python env/bin/python \+ 'mlx==0.31.1' 'mlx-lm==0.31.1' 'mlx-metal==0.31.1' 'transformers>=5.0.0,<5.13.0'# --build-constraints pins hatchling below 1.32, which rejects upstream's# `readme = "../../README.md"` and fails metadata generation. See-# pip-build-constraints.txt.-./env/bin/uv pip install --python env/bin/python \+# pip-build-constraints.txt. The first pass resolves the packages'+# dependencies (mlx-arsenal among them); the second replaces the editable+# workspace links it leaves with real copies, which the codec patch needs.+uv pip install --python env/bin/python \--build-constraints ../pip-build-constraints.txt \./packages/ltx-core-mlx ./packages/ltx-pipelines-mlx ./packages/ltx-trainer-./env/bin/uv pip install --python env/bin/python \+uv pip install --python env/bin/python --reinstall --no-deps \+ --build-constraints ../pip-build-constraints.txt \+ ./packages/ltx-core-mlx ./packages/ltx-pipelines-mlx ./packages/ltx-trainer+uv pip install --python env/bin/python \pyyaml pydantic tqdm rich# mlx-vlm powers Gemma 3 auto-caption. --no-deps so it doesn't drag mlx-lm past 0.31.1.-./env/bin/uv pip install --python env/bin/python --no-deps 'mlx-vlm==0.4.4'+uv pip install --python env/bin/python --no-deps 'mlx-vlm==0.4.4'# Agent + downloader + hub pin range.-./env/bin/pip install pillow numpy 'huggingface-hub>=1.5.0,<2.0' \+uv pip install --python env/bin/python pillow numpy 'huggingface-hub>=1.5.0,<2.0' \'hf_transfer>=0.1.6' 'litellm>=1.83.14' 'smolagents>=1.24.0'cd ..@@ -239,8 +247,9 @@ cd .../ltx-2-mlx/env/bin/python3.11 scripts/fetch_pack_release.py --repo-key q8_25# 6. (Optional) Image tab — install mflux + apply the FBCache patch.-./ltx-2-mlx/env/bin/pip install 'mflux==0.18.0'-./ltx-2-mlx/env/bin/pip install --force-reinstall --no-deps 'mflux==0.18.0'+uv pip install --python ltx-2-mlx/env/bin/python 'mflux==0.18.0'+uv pip install --python ltx-2-mlx/env/bin/python --reinstall --no-deps 'mflux==0.18.0'+uv pip install --python ltx-2-mlx/env/bin/python 'mlx-teacache==0.4.1'./ltx-2-mlx/env/bin/python3.11 patch_mflux_fbcache.py# 7. (Optional) HiDream — separate one-time clone for the photoreal engine.@@ -252,7 +261,7 @@ cd .../ltx-2-mlx/env/bin/python3.11 mlx_ltx_panel.py```-About the version pins: `mlx 0.31.2` attenuates the LTX vocoder by 22 dB. Stay on 0.31.1. `ltx-2-mlx` is pinned to the fork **tag** `v0.14.19+ltx25.6` (`mrbizarro/ltx-2-mlx`, commit `0b74258`) — v0.14.19 plus the LTX-2.5 port, because upstream has no 2.5 branch. A tag, not a bare SHA: a force-push upstream would strand every install with an un-fetchable pin and a dead Update button. The installed packages report `0.14.19+ltx25.6` and `_LTX_EXPECTED_VERSION` must match that string exactly, or every render logs a VERSION SKEW warning. `scripts/pinokio/ltx_checkout.sh` holds the pin and `node scripts/check_ltx_pin.js` enforces the agreement. `mflux 0.18.0` is the version `patch_mflux_fbcache.py` is line-targeted against, and it is pinned TOGETHER with mlx — mflux declares its own mlx range, so installing it with deps after pinning mlx can silently move mlx (`node scripts/check_post_update.js` fails if either moves alone). `hatchling<1.32` (in `pip-build-constraints.txt`) is a *build-time* pin: 1.32 rejects the `readme = "../../README.md"` that all three upstream packages declare, which fails the wheel build on every tag.+About the version pins: `mlx 0.31.2` attenuates the LTX vocoder by 22 dB. Stay on 0.31.1. `ltx-2-mlx` is pinned to the fork **tag** `v0.14.19+ltx25.7` (`mrbizarro/ltx-2-mlx`, commit `bf419b6`) — v0.14.19 plus the LTX-2.5 port, because upstream has no 2.5 branch. A tag, not a bare SHA: a force-push upstream would strand every install with an un-fetchable pin and a dead Update button. The installed packages report `0.14.19+ltx25.7` and `_LTX_EXPECTED_VERSION` must match that string exactly, or every render logs a VERSION SKEW warning. `scripts/pinokio/ltx_checkout.sh` holds the pin and `node scripts/check_ltx_pin.js` enforces the agreement. `mflux 0.18.0` is the version `patch_mflux_fbcache.py` is line-targeted against, and it is pinned TOGETHER with mlx — mflux declares its own mlx range, so installing it with deps after pinning mlx can silently move mlx (`node scripts/check_post_update.js` fails if either moves alone). `hatchling<1.32` (in `pip-build-constraints.txt`) is a *build-time* pin: 1.32 rejects the `readme = "../../README.md"` that all three upstream packages declare, which fails the wheel build on every tag.## Interfacediff --git a/VERSION b/VERSIONindex 614749c..ecbc3b0 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-4.15.4+4.16.0diff --git a/docs/MUSIC_ENGINE.md b/docs/MUSIC_ENGINE.mdindex 210e78e..b04cbf7 100644--- a/docs/MUSIC_ENGINE.md+++ b/docs/MUSIC_ENGINE.md@@ -95,6 +95,7 @@ lockfile with `uv sync --frozen --no-dev`; music is torch-free.| Weights | `mlx_models/yue2/` | `LTX_MUSIC_MODELS` || Phosphene runner | `scripts/music/yue2_run.py` | owned by the panel || Engine revision | `scripts/music/engine_pin.txt` | change only after validation |+| LoRA pack | `mlx_models/yue2-loras/` | `LTX_MUSIC_LORAS` |Set root overrides in Pinokio's `ENVIRONMENT` file; the menu and panel readthe same names. The engine directory is ignored by git. Install clones@@ -146,7 +147,8 @@ Carry the morning home`[Pre-Chorus]`, `[Bridge]` and `[Outro]` are also section markers. A sectionwith no words is instrumental. Style is prose: genre, instruments, singer,language and tempo in one description. The Instrumental pill keeps the-lyrics text in the browser but sends none of it; it passes `--instrumental`.+lyrics text in the browser but sends none of it; it passes `--instrumental`+(see **LoRA inference**, below, for the two recipes that flag selects).Score modes are **Melody + chords** (`full`, default), **Melody only**(`melody`) and **No score** (`off`). YuE2 writes a sheet-music plan before@@ -154,6 +156,578 @@ the song. Draft maps to 8 synthesis steps; Final maps to 32 (default).Seed -1 chooses a random seed. All seven `music_*` fields survive theform-urlencoded queue path and are persisted in the job.+## Music Studio — the song as a thing you come back to++Every song YuE2 writes keeps its **artifacts** — the plan (the ABC score and+the tokenised prompt), the semantic tokens, the latents and the solver noise —+under `state/music/<job-id>/`. That folder is what makes a song something you+can return to rather than a file you got once. Nothing in it is shown in the+gallery; the song's sidecar names it, and the studio reads the sidecar.++### Three tasks, one form++| Task | What happens | Needs |+|---|---|---|+| **Write a song** | style + lyrics → plan → song | the music pack |+| **Cover a song** | a recording is transcribed to a score (SheetSage2), then that score is realised under *your* style and lyrics | the pack + the 2.8 GB cover models |+| **Get the score** | transcription only — the recording's sheet music, no song | the cover models |++**Write lyrics** asks the local Gemma 3 (the same model the prompt enhancer+uses) for section-tagged lyrics from a one-line concept, in the exact format+YuE2 reads: `[Verse]`, `[Chorus]`, one sung line per row, a bare tag for an+instrumental passage. It is a draft to edit, not a result.++### The Song card++Under the player, for songs only: the title, the style, badges (cover, new+take, re-rolled, restyled, instrumental, cut at max length), the **sheet music+drawn from the score** (abcjs, vendored), the lyrics, and where the song came+from. And four ways to get another song from it:++| Verb | Restarts from | Keeps | Changes | Cost |+|---|---|---|---|---|+| **New take** | the saved plan | score, words, style | the performance (semantic stage re-run with a new seed) | a song minus the planning |+| **Re-roll the sound** | the saved semantic tokens | score, words, style, *the performance* | the recording of it (new solver noise through the NAR and the decoder) | roughly a third of a song |+| **New style on this score** | the saved `score.abc` | the score | the words and the style, taken from the composer | a full song minus the planning |+| **Cover it** | the audio itself | the tune, as heard | everything else | transcription + a song |++**Edit the score** opens the ABC in a text box; *Preview* redraws it, *Render+this score* queues a song from the edited text under the composer's style and+lyrics (or the song's own, if the boxes are empty). The edited ABC is written+under `state/music/edits/` and the worker refuses any other path.++A song made before v4.16 has no artifacts, and its buttons say so instead of+failing after a click. Every variation names its parent in the sidecar+(`lineage.parent`, `lineage.variation`) and is filed beside it as+`<parent>_take.wav`, `<parent>_sound.wav`, `<parent>_restyle.wav`.++### Advanced++- **Takes** — queue N songs from one form, each with its own seed (a fixed seed applies to the first only).+- **Text guidance** (`cfg_scale`) — 1.0 is the engine's default and is sent as *unset*, so a sidecar reading `null` means "the default was used".+- **Precision** — `bf16` / `8bit` / `4bit` for the composer weights. Every song so far shipped on 8-bit; bf16 needs roughly 8 GB more memory.+- **Voice & style LoRA** — adapters from `mlx_models/yue2-loras/` (and your own from its `user/` folder), each with its own 0–1.5 strength. See **LoRA inference**.++### Routes++`POST /music/variation` (`path`, `kind` ∈ take/sound/restyle, optional `style`,+`lyrics`, `seed`, `quality`, `title`), `GET /music/lora/status`,+`POST /music/lora/fetch`, `POST /music/transcribe` (`path`,+`task`), `GET /music/score?path=…` or `?job=…`, `POST /music/score/render`+(`path`, `abc`, …), `POST /music/lyrics` (`concept`, `style`, `seconds`,+`language`). All of them take output paths, never state paths, and refuse+anything that is not one of this panel's songs.++## LoRA inference++The engine has no adapter code, and the engine directory is replaced on every+sync, so Phosphene's LoRA support lives in **`scripts/music/yue2_lora.py`** and+is applied to the models `lyra` hands back. Nothing is merged into the base+weights: the AR model runs 8-bit by default, and merging would mean either+BF16-only (5 GB more resident) or a dequantise/requantise per song. The+arithmetic is the published one — `y = W x + strength · B (A x)`, `lora_A:+[rank, in]`, `lora_B: [out, rank]`, BF16, no alpha unless the file carries one.++**How it attaches without renaming anything.** `lyra.nar.load_nar()` validates+the shared AR model by walking `tree_flatten(ar_model.parameters())` and+demanding the exact upstream tensor names. A wrapper module holding the+original linear as a child would rename all 196 of them and the acoustic model+would refuse to load. So the projection object is kept and its **class** is+swapped for a generated subclass that adds the delta after the base call; the+matrices hang off the instance through `object.__setattr__`, the way `lyra`+itself keeps runtime constants off the parameter tree. Quantised bases work+unchanged and removal is one `__class__` assignment back.++`LoRARuntime` wraps `YuE2Pipeline._load_model`, which is the only hook that+sees all three models a song uses — the planning AR, the BF16 conditioning AR+built for the acoustic stage, and the acoustic model itself, which is loaded+halfway through the song.++| Mode | AR/NAR deltas | Decoder `vae2llm` / `llm2vae` |+|---|---|---|+| `joint` (default) | added at strength | untouched, even when the file carries them |+| `separate` | added at strength | REPLACED by a convex blend of every separate companion, weighted by strength |++A separate NAR file is a complete decoder companion, not an independent style+delta: summing several would double the shared decoder adaptation, so their+relative strengths form a convex blend. `nar_lora_joint_v9` *does* ship full+`vae2llm`/`llm2vae` tensors; in `joint` mode they are read, ignored, and the+sidecar records `decoder_io_ignored: true`.++Key spellings accepted: the Mothersuperior `layers.{i}.….lora_A` layout, an+optional `model.` prefix, PEFT / AI-Toolkit `base_model.model.` prefixes,+`.lora_A.weight` and `.lora_A.default.weight`, kohya `lora_down` / `lora_up`,+and `.A` / `.B`. A PEFT `alpha` scalar is folded into B as `alpha / rank`.++### The pack++`scripts/pinokio/music_lora_fetch.py` downloads two pinned adapters and the+real-audio tokenizer head into `mlx_models/yue2-loras/` (~300 MB, CC BY-NC 4.0,+checksummed, a `NOTICE` beside them). It is **not** part of+`MUSIC_INSTALL_STEPS`: a user who never asks for an instrumental never pays+for it.++| File | Repo · revision | What |+|---|---|---|+| `ar_lora_inst_v3abc.bf16.safetensors` | `Mothersuperior/YuE2-instrumental-cot-full-loras` · `947f2f4b` | AR · rank 64 · 196 targets |+| `nar_lora_joint_v9.bf16.safetensors` | `Mothersuperior/yue2-mothersuperior-realaudio-tokenizer-v4` · `e2e63d85` | acoustic · rank 32 · 196 targets + decoder I/O |+| `tokenizer/tokenizer_head_joint_v9.bf16.safetensors` | same repo · `e2e63d85` | the real-audio tokenizer head, 85.6 MB |+| `tokenizer/sem_nbr_{cos,idx}.npy` | same repo · `e2e63d85` | training-side neighbour tables, not read at inference |++The head lives under `tokenizer/` on purpose: `pack_adapters()` globs the root+and `user/`, so a head beside the adapters would be offered in the studio's+LoRA picker as if it were one. `lora_problems()` still speaks only about the+adapters, so an installed pack is not declared broken by a new optional+download; `head_problems()` is its own gate and `--check` reports both.++**Usable and whole are two questions** (Codex review, 2026-09-22).+`lora_problems()` answers the first — can the picker offer these adapters —+and `pack_problems()` answers the second: is there anything left to download,+head included. `POST /music/lora/fetch` gates on the second, so an+interrupted run can be finished from the UI. A pinned file counts only at its+pinned SIZE; the SHA-256 is checked by the download, which copies to a+`.partial` sibling and `os.replace`s it into place only once it passes, so a+name on disk is always a verified file. `--check --deep` hashes them anyway.++`mlx_models/yue2-loras/user/` is scanned for any `*.safetensors`, so a+community or AI-Toolkit adapter is usable the moment it is copied in. The+picker is a directory listing; there is no registry to register with.++```sh+ltx-2-mlx/env/bin/python scripts/pinokio/music_lora_fetch.py --root mlx_models/yue2-loras --check+yue2-mlx/.venv/bin/python scripts/music/yue2_lora.py <file.safetensors> # inspect one+```++### Instrumental, the two recipes++`--instrumental` picks its recipe from one fact: whether the AR adapter is on+disk.++- **With the pack** — Maestro's recipe. The instrumental AR adapter at+ strength 1.0, `cot=full` forced, the lyrics replaced by `[instrumental]`+ (bare section tags, optionally timed — `[chorus 0:15-0:40]` — pass through+ lowercased; anything else becomes `[instrumental]`, because sung prose fed+ to this adapter is what produces a vocal-like track), other LoRAs paused,+ stock acoustic decoder.+- **Without it** — the tag skeleton that shipped in v4.16, which was validated+ by ear. A queued song never fails because an optional download is missing.++The sidecar records which one ran, under `instrumental_recipe`.++### Measured++Four 30-second songs on an M4 Max 64 GB, 8-bit AR, Final (32 steps), one arm+per pair carrying the adapter, everything else — prompt, seed, steps,+precision — held fixed. Vocal content is the RMS of demucs `htdemucs_ft`'s+vocals stem relative to the mix RMS.++**Does the instrumental adapter remove the singing?** Yes — but only where+there was singing to remove. On an instrumental *prompt* the base model+already writes no vocal line, so that pair cannot discriminate (both stems are+silence at ~-67 dB). On a prompt that names a singer, with `[instrumental]` as+the lyrics and the seed held, the difference is the whole point:++| Pair · seed | Arm | vocals RMS | vocals ÷ mix | dB vs mix | vocal peak |+|---|---|---|---|---|---|+| vocal prompt · 909090 | AR adapter @1.0 | 0.000237 | 0.0012 | **-58.53** | 0.002 |+| vocal prompt · 909090 | none | 0.068147 | 0.3489 | **-9.15** | 0.682 |+| instrumental prompt · 424242 | AR adapter @1.0 | 0.000031 | 0.0003 | -69.66 | 0.0009 |+| instrumental prompt · 424242 | none | 0.000024 | 0.0005 | -66.29 | 0.0003 |++**49.4 dB** less vocal content at the same seed and the same words.++**`nar_lora_joint_v9` on a sung song** (same seed, same lyrics): it loads,+synthesises and decodes cleanly, and it changes the audio (different SHA-256),+but the vocal share barely moves — 0.4888 with, 0.5000 without (-6.22 dB vs+-6.02 dB). Expected: it was trained beside `tokenizer_head_joint_v9`, and+without that head it is reading a token dialect it was not adapted to.++**What an adapter costs.** Per-stage, from the sidecars:++| Stage | Base | With adapter | Delta |+|---|---|---|---|+| AR score planning | 112.5 tok/s | 93.4 tok/s | -17% |+| AR semantic | 114.0 tok/s | 95.4 tok/s | -16% |+| Acoustic (NAR adapter) | 13.36 s | 14.96 s | +12% |+| MLX peak | 10.48 GiB | 10.61 GiB (AR) / 10.55 GiB (NAR) | +0.13 / +0.07 |++Wall-clock per song is dominated by how long a score the planner writes, not+by the adapter: the four 30-second songs ran 29.4 s to 63.5 s, and the longest+was a *base* arm whose score came out three times longer.++### Flags and wiring++Runner: `--lora PATH[:STRENGTH]` (repeatable), `--lora-mode joint|separate`,+`--lora-trigger WORD` (repeatable, added to the style once), `--lora-dir`.+Panel: `music_loras` on the form is `id:strength` pairs, each resolved inside+the LoRA folder before a job exists — a form can name a file, never a path.+`GET /music/lora/status` and `POST /music/lora/fetch` mirror the cover pack's+pair, and `/status.music.loras` carries the same block for the first paint.+The studio shows a **Voice & style LoRA** section (multi-select, 0–1.5+strength each) and a one-line download affordance under the Instrumental pill.++### What is not done++- **`separate` bundles are implemented but untested against a real artist+ bundle** — none is published. The decoder-blend arithmetic is covered by+ tests, not by audio.+- **The `_comfyui` adapter layout** (block-diagonal fused qkv / gate_up) is+ not read. The plain layout is.++## The real-audio tokenizer head — YuE2 can listen now++YuE2 writes from words. `tokenizer_head_joint_v9` is the piece that lets a+REAL recording in: an 8-layer transformer that reads MERT-v2-FullSong features+and predicts YuE2's own 32768-way semantic codes. `scripts/music/+yue2_tokenizer.py` is the MLX port. Two things follow from it — a recording can+be re-synthesised through YuE2's decoder, and a recording can be the prefix a+new song continues from.++### The architecture, and where every number came from++`Linear(1024→512)` · learned `pos [1,512,512]` · 8 × `TransformerEncoderLayer(+512, 8 heads, ffn 2048, norm_first, gelu)` · `LayerNorm(512)` ·+`Linear(512→32768)`. 103 BF16 tensors.++None of the preprocessing is guessed. Mothersuperior's `prep_real.py` and+`joint_v6.py` were fetched and read first, and every step below is theirs:++| Stage | What runs |+|---|---|+| audio | mono, 24 kHz, float32; `scipy.signal.resample_poly` by default (what `prep_real.py` used), ffmpeg as the fallback and the `--resampler ffmpeg` alternative — the metadata records which one ran |+| chunking | 30 s chunks; a chunk under 1 s is dropped; each encoded on its own, so MERT attention never crosses a chunk boundary |+| features | `hidden_states[20]`, concatenated in time order, linearly resampled to `round(seconds × 25)` and rounded through float16 — the head was trained on fp16-stored features |+| norm | per **track**, per channel: `(x − mean) / (std + 1e-5)`, numpy's population std, before any windowing |+| window | 512 frames, the learned `pos` sliced (never interpolated) for a short tail |+| tiling | hop 256; a final window pulled back to the end of the track; each window contributes its centre, trimming 128 frames off every interior edge |+| decode | plain `argmax` — no neighbour smoothing; the `sem_nbr_*` tables the repo ships are a training loss (`soft_ce`), not an inference step |++### The two things a port gets silently wrong++Both have identical shapes whether they are right or wrong, so both were+settled numerically rather than argued.++**The fused q,k,v projection.** PyTorch stores one `in_proj_weight [1536,512]`+whose row blocks are q, then k, then v. Any permutation loads without+complaint. Against a torch `TransformerEncoderLayer` built from these exact+tensors, on one random 512-frame window in FP32:++| split order | max-abs-diff |+|---|---|+| **q,k,v** | **3.910e-05** (relative 3.40e-06, argmax agreement 1.0000) |+| q,v,k / k,q,v / k,v,q / v,q,k / v,k,q | 15.6 / 17.5 / 15.2 / 16.0 / 15.1 |++A 137-frame window gives 3.076e-05, so the `pos` slice is right too.++**The MERT layer.** The head's metadata says "layer 20". transformers collects+a hidden state only AFTER each conformer block — `MERT2Model._encode()` appends+inside the loop and never appends the pre-layer subsampled embedding — so+`hidden_states[20]` is the output of `layers[20]`. `lyra.mert`'s `layer_weights`+vector is one entry LONGER (25 for 24 blocks) because its index 0 IS that+pre-layer embedding. The one-hot goes at **21**. Against the real HF model on+2 s of audio:++| `layer_weights` index | max-abs-diff vs `hidden_states[20]` |+|---|---|+| 19 | 7.3160 |+| 20 | 12.180 |+| **21** | **1.135e-04** (relative 3.75e-06) |+| 22 | 19.839 |++Code statistics do **not** separate these: layer 19 produces 594 unique codes+with repeat 0.072, layer 20 produces 565 with repeat 0.087. Both look healthy.+Only the reference comparison decides it.++### Precision and the resampler, measured++FP32 throughout, rather than the training-time `torch.autocast` bfloat16:+more accurate and reproducible. On 30 s of a real recording the two paths+agree on **97.07 %** of frames, and polyphase-vs-ffmpeg resampling on+**94.67 %**. Layer 19 instead of 20 agrees on 25.33 % — a different song.++### The round trip++```sh+yue2-mlx/.venv/bin/python scripts/music/yue2_tokenizer.py encode SONG.mp3 \+ --start 60 --seconds 30 --out codes.npy \+ --roundtrip out.wav --model-dir mlx_models/yue2/generator \+ --vae-dir mlx_models/yue2/vae --seed 4242 \+ [--lora mlx_models/yue2-loras/nar_lora_joint_v9.bf16.safetensors --lora-mode joint]+```++`encode` alone writes `codes.npy` (int32, 25 per second) and a sidecar with the+head identity, the feature summary and the code statistics. `--roundtrip` also+synthesises them through the NAR and the VAE decoder and measures the result+against the SAME excerpt of the original.++Measured on seconds 60–90 of a real recording, seed 4242, 32 ODE steps:++| Arm | log-mel | chroma r | synthesis | MLX peak |+|---|---|---|---|---|+| stock decoder | **7.935 dB** | **0.8832** | 13.50 s | 10.48 GiB |+| `nar_lora_joint_v9`, `joint` | **7.861 dB** | 0.8171 | 14.76 s | 10.55 GiB |+| `nar_lora_joint_v9`, `separate` | 10.389 dB | 0.8314 | 14.76 s | 10.55 GiB |++The controls are what make those numbers mean something:++| Control | log-mel | chroma r |+|---|---|---|+| the excerpt against itself | 0.000 dB | 1.0000 |+| a DIFFERENT 30 s of the same record | 13.399 dB | 0.7020 |+| white noise at the same level | 26.283 dB | 0.1844 |+| silence | 101.507 dB | — |++So the round trip lands well inside "the same passage" and nowhere near "a+different passage of the same song". `joint` is a hair closer spectrally than+the stock decoder and a little further away harmonically; `separate` — which+replaces the decoder's `vae2llm`/`llm2vae` outright — is clearly worse here,+which is what Maestro's own semantics predict for a file that is not an artist+bundle. The encode itself is **2.96 s for 30 s** of audio.++Code statistics for that excerpt: 750 frames, 565 unique codes, top code+0.9 % of frames, repeat 0.087, mean run 1.09 — a live stream, not a collapsed+one.++### `--audio-prompt`: a song that continues a recording++```sh+yue2-mlx/.venv/bin/python scripts/music/yue2_run.py ... \+ --audio-prompt TAKE.wav --audio-prompt-seconds 10 [--audio-prompt-start 60] \+ --lora-dir mlx_models/yue2-loras+```++The recording's first seconds become codes; the codes are appended to the+request prefix as ordinary codec tokens, so the AR model prefills on them+exactly as it would on its own output and writes on from there. The codes stay+at the head of the token stream; the plan keeps its canonical prefix, which is+what `synthesize()` validates against the request. Listening happens **before**+the generator is built and the MERT frontend is dropped afterwards — same+order, same reason, as the cover path.++Two honest edges: the repetition-penalty window and the minimum-length counter+both restart at the boundary, because `generate_tokens()` takes no prior+history. The model sees the prompt; the sampler does not.++Measured, 10 s prompt, `cot=off`, seed 4242, budget 30 s:++| | audio | wall | ended naturally | chroma r vs the prompt |+|---|---|---|---|---|+| with the prompt | 39.52 s (250 prompt + 738 written) | 37.59 s (3.96 s listening) | yes | **0.5827** |+| same seed, no prompt | 30.00 s | 30.18 s | no (hit the budget) | 0.1011 |++The prompted song's first 10 s reconstruct the source — 10.503 dB log-mel,+chroma 0.8752, against 13.399 dB / 0.702 for a different excerpt. The two+generated token streams agree on **0.14 %** of frames: it is a different song,+not a perturbed one. MLX peak 10.48 GiB on both arms.++The sidecar records `audio_prompt`: path, seconds, start, frames, head version+and sha256, MERT layer, resampler, code statistics, listening time and how many+frames the model wrote.++### What is not done here++- **No panel surface.** This is runner-and-CLI only; the studio has no+ "continue this recording" control yet.+- **Instance norm is per track, so the same seconds encode differently+ depending on what they were cut out of** — the same 10 s scored inside a 30 s+ track agrees with its standalone encode on 34.40 % of frames. That is+ faithful to the training recipe, and it means a prompt should be cut once and+ reused, not re-derived from different excerpts.+- **`sem_nbr_cos.npy` / `sem_nbr_idx.npy` are downloaded but unused.** They are+ the training soft-CE neighbour tables.+- **No training.** Adapting the head to a voice is the Maestro "My Music" road+ and is not implemented; see `docs/STATE.md` for the estimate.++## Train a voice++```sh+yue2-mlx/.venv/bin/python scripts/music/yue2_train_voice.py \+ --recordings RECORDINGS/ --lyrics LYRICS/ --trigger myvoice \+ --out runs/myvoice --style "the style every window trains with" \+ --reg-pack minted_regularizer_pack.pt \+ --steps 400 --rank 32 --lr 1e-4 --dialect direct+```++Out come `runs/myvoice/myvoice.safetensors` and `myvoice.json`. Drop both in+`mlx_models/yue2-loras/user/` (or pass `--install`) and the studio's LoRA+picker offers it; on the runner it is+`--lora myvoice.safetensors:1.0 --lora-trigger myvoice`.++**What is being trained.** An AR-branch LoRA, all 196 projections, one rank —+the same objective as Mothersuperior's `ar_lora.py` and Maestro's+`artist_training.py`. The recordings become YuE2 semantic codes through+`tokenizer_head_joint_v9`, and the AR model is taught to *write* that code+stream from style + lyrics:++```+sequence = token_prefixes(SongRequest(style, lyrics, …)) + [code + CODEC_OFFSET …]+loss = cross-entropy on the CODE TAIL ONLY+```++The prefix comes from the engine's own `token_prefixes`, so training sees the+byte-identical thing inference builds. **No conversion step anywhere** — this+is the whole reason it does not sound robotic. A voice converter resynthesises+a stranger's performance frame by frame and inherits their phrasing, vibrato+onset and consonant attack (`notes/yue2/MAESTRO_VOICE_STUDY.md` §4); this+model sings its own performance.++### Windows, and why the lyrics are sliced++A recording is cut into `--window-seconds` windows (default 20.48 s = Maestro's+512 frames) at `--hop-seconds`, and **each window gets the lyrics that were+sung inside it**. That is not a detail. If the prefix carries the whole song's+words while the codes are one slice of it, the pair is a lie: the model learns+"this style → this singer's codes" and never learns "these words → these+sounds", so it reproduces trained fragments instead of pronouncing new lyrics.++Timings come from a `<stem>.lines.json` sidecar beside the recording —+`{"lines": [{"text": …, "onset": seconds, "end": seconds, "section": "[Verse]"}]}`+— which is what a forced aligner or a whisper pass with word timestamps+produces. Without one, the sheet is cut by the window's share of the+recording, which is cruder but still keeps each prefix roughly honest about+its own codes. A window whose lyrics cannot be located trains on an empty+lyric block rather than on somebody else's line.++The trainer is pure: it never runs demucs, whisper or SheetSage2. Sidecars come+in from outside, and `--emit-windows DIR` writes the window audio so those+tools can be pointed at exactly the seconds each window trains on.++### Two dialects++| `--dialect` | prefix | generate with |+|---|---|---|+| `direct` (default) | `cot="off"` — no score | `--mode off` |+| `score` | `cot="melody"`, with the window's real ABC score inside the prefix | `--mode melody --abc-file SCORE.abc` |++`SongRequest` refuses `abc` with `cot="off"`, so a `direct` voice cannot be+driven by a score in Direct mode. It **can** be driven by one in `--mode+melody`, and measured, that is the best way to use it (see below) — the claim+in `MAESTRO_VOICE_STUDY.md` §6.1 that the two are mutually exclusive is a+Maestro UI convention, not an engine constraint. The `score` dialect trains the+prefix the model will actually be given. To build it, transcribe each window+first:++```sh+python scripts/music/yue2_train_voice.py --recordings SONG.wav --out runs/x \+ --emit-windows windows/+for w in windows/*.wav; do+ python scripts/music/yue2_run.py --model-dir … --vae-dir … \+ --transcribe-only --source-audio "$w" --cover-task melody-vocal \+ --cover-seconds 21 --transcription-cache mlx_models/yue2-cover \+ --output "scores/$(basename "$w" .wav).abc"+done+python scripts/music/yue2_train_voice.py … --dialect score --scores scores/+```++### The regulariser++`--reg-pack` is Maestro's pinned `minted_regularizer_pack.pt` (101.9 MB, codes+only): base-dialect songs mixed against the artist at `--artist-fraction`, so+the AR stays inside YuE2's own dialect instead of drifting somewhere the+decoder cannot follow. `--reg-cache` writes a converted `.npz` on first use, so+a machine without torch can still train. Without it the trainer says so and+carries on; the held-out minted cross-entropy in the log is how you check the+drift.++### The sidecar++`<name>.json` records the trigger, the dialect and the generation flags that+match it, the base model and its upstream commit, steps / rank / lr / seed /+window geometry, a fingerprint of the training data, how many windows carried+lyrics and how many carried a score, and the whole loss curve.++### Measured: strength is not optional, and neither is the window++One recording (≈6 min of a separated vocal), 35 windows, rank 32, lr 1e-4, 400+steps, 21.8 min on an M4 Max. Scored on lyrics the model had never seen, by+whisper on the take's full mix: how many of 8 planted words are heard, and word+error rate against the sheet. `sim` is resemblyzer cosine against two reference+passages by the same singer.++| | strength 1.0 | strength 0.7 |+|---|---|---|+| whole-song lyrics, random code window | 0/8, WER 1.000 | 4/8, WER **1.000** |+| **per-window lyrics** | 0/8, WER 0.896 | **8/8, WER 0.214** |++The base model scores 7/8 at WER 0.325, so the best cell is **more accurate at+the given words than the stock model**, at voice similarity 0.8205 against+stock's 0.7718.++Both ingredients matter and neither substitutes for the other. At strength 1.0+the adapter overrides the lyric conditioning completely and nothing is+pronounced, whichever way it was trained. At 0.7 the whole-song recipe sings+*more* words (243 vs 180) and still scores WER 1.000 — it has learned to sing,+not to sing what it is given. 0.5 is too far the other way: lyrics survive but+the voice does not (sim 0.7272, register −6.25 st).++**So: apply a trained voice at about 0.7**, and treat 1.0 as the setting that+silences the lyrics. The number is one recording deep — re-measure on yours.++### Measured: give it a score++With a supplied score (`--mode melody --abc-file`), the same `direct`-dialect+adapter at strength 1.0 does better than it ever does in Direct mode:++| same score, same lyrics, same seed | voice sim | register | in-tune folded | in-tune absolute | robot words |+|---|---|---|---|---|---|+| stock, no LoRA | 0.7302 | −9.15 st | 96.1 % | **1.3 %** | 7/8 |+| trained voice @1.0 | **0.8161** | +2.65 st | 83.1 % | **76.6 %** | **6/8** |++Read the two octave columns. Stock follows the written pitch classes almost+perfectly while singing them **an octave down** — 1.3 % of notes land in the+written octave. The trained voice sings the score in the octave it is written+in (76.6 %), because the voice it learned lives there. And it holds 6/8 lyrics+and 0.8161 voice similarity *at the same time*, which Direct mode never manages+at full strength. A supplied score anchors the melody, which leaves the lyric+conditioning intact.++### Measured: the `score` dialect, and the octave it learned++Trained on 13 windows whose prefixes carried SheetSage2's `melody-vocal`+transcription of the same seconds, then handed the same score as above:++| same score, lyrics, seed | voice sim | register | in-tune folded | in-tune absolute | robot words |+|---|---|---|---|---|---|+| `direct` voice @1.0 (above) | **0.8161** | +2.65 st | 83.1 % | **76.6 %** | 6/8 |+| `score` voice, step 100 | 0.7774 | −9.35 st | **97.4 %** | 3.9 % | 5/8 |+| `score` voice, step 400 | 0.8004 | −11.15 st | 76.6 % | 1.3 % | 6/8 |++**It follows the pitch classes and drops the octave**, like the stock voice+does — and the cause is measurable. SheetSage2 writes the melody **+12.7 st+above what was sung** (median over the 13 windows; 9 of them sit at +12.1 to++12.9). Every training pair therefore said "a written note means sing it an+octave lower", and a score written at pitch is then sung an octave down.++So **today the `direct` dialect under a score is the better recipe**, and+`--dialect score` should not be used on SheetSage2 transcriptions as they come.+The fix is mechanical and not yet in the trainer: transpose each window's score+down to the octave that was sung (or estimate the written-vs-sung offset per+window and correct it) before training. The `score` curve also memorises far+faster — artist CE 0.021 at step 400 against the `direct` run's 0.753 — because+a unique score in each prefix is a near-perfect key to that window's codes; it+needs more windows than one recording gives.++### What this can and cannot do++- **Can**: move vocal identity a long way from a prompt alone, with no+ converter in the chain, and keep the singer's register.+- **Can**: pronounce lyrics it has never seen more accurately than the base+ model — at strength ~0.7, trained on windows whose prefixes told the truth+ about their codes. At 1.0 it pronounces nothing.+- **Can**: follow a supplied score, in the written octave, better than the+ stock voice does.+- **Cannot yet**: train usefully in the `score` dialect on raw SheetSage2+ transcriptions — they are written an octave above what was sung (above).+- **Cannot**: be trusted to generalise from one song. Maestro wants 2–50 songs+ and at least one held out; one track gives a memorisation check, not a+ generalisation check.+- **Cannot**: change timbre the way the expensive half of Maestro's recipe+ does. That is head + NAR adaptation with a decoded-waveform loss, and it+ needs an MLX VAE *encoder*, a differentiable NAR path and the unpublished+ minted anchor corpus — see `docs/STATE.md`.+- **No panel surface.** CLI plus the LoRA picker; the studio has no training+ screen.+## Outputs and the video handoffThe runner writes **48 kHz stereo PCM-24 WAV** and its `.wav.json` sidecar.@@ -162,10 +736,179 @@ The info panel shows style, lyrics, seed, actual length, natural endingversus the ceiling, and the ABC score. The sidecar also records the job id,engine pin and weight-source revisions. Delete/Trash carries it with the WAV.-**Drive video** loads a song into the existing Audio → Video workflow and-switches to that mode. It does not submit a render. Its normal video memory-and model requirements still apply. Settings → Storage can remove the music-weights; doing so hides Compose and leaves Drive video available.+**Music video** loads a song into the Music video pane and switches to that+mode. It does not submit a render. Settings → Storage can remove the music+weights; doing so hides Compose and leaves Music video available.++## Music video — the song and the pictures++The Audio tab's second mode turns a song plus a set of tagged pictures into a+storyboard. The song is dropped in or picked from the library; each picture+carries a role — **Singer** (filmed singing), **Instrument** and **Room**+(B-roll) — and an optional line of its own; one "Look" line goes on every+shot.++`POST /music/video/plan` reads the beat (`storyboard_edit.beat_map`), works+out the song's sections, and writes an ordinary storyboard board.++**Where the song's structure comes from — strongest first, and each rung is+only reached when the one above it is silent:**++| Rung | Field | What it is |+|---|---|---|+| 1 | `sections` | A JSON list of `{start, end, kind: vocal\|instrumental, label?}` in seconds — the structure somebody **measured**. Sorted, gaps closed, clamped to the song, and the first section is always pulled to 0:00 (the film plays from 0:00, so a later start would put every mouth on the wrong words). Overlaps, a missing `kind` and an end before its start are refused by name. |+| 2 | `lyrics` / `score_abc` | The same two texts a YuE2 sidecar carries, in the request — for a song that was re-cut, or whose sidecar belongs to an earlier take. |+| 3 | the sidecar | A YuE2 song's sections are arithmetic rather than analysis: `score_abc` carries `M:`/`Q:` headers and `% section` comments, so bars × tempo is the boundary and the lyrics' bracket tags say which sections anybody sings in. |+| 4 | the classifier | A song from anywhere else is split into 8-bar downbeat phrases and classified on its 1–4 kHz band energy. |++Vocal sections become **singing shots** — mode `a2v`, alternating Singer+pictures, `frames` the largest LTX cell inside a 10–20 s window, and+`audio_start_time` set to that shot's own place in the song. Everything else+becomes **B-roll** — a still with a slow move on it, 3–7 s, cut on the+downbeats. The shots tile the song with no gaps, and every length is the one+that will really render (a frame count on the 8k+1 grid), so the clip placed+at 1:42 in the finished film is the clip that was rendered against 1:42 of+the song.++**The duration axis is the panel's table cut down to the delivery canvas.**+`LTX_LENGTHS` marks the 20 s / 481-frame cell as Quick-only (640×480 holds;+1024×576 dies around frame 454, issue #46), and the plan route reads the+board's final pass — Settings → `storyboard_final_quality`, `standard` out of+the box — so at Standard the longest planned shot is 10 s and a note says+why. The quality used is echoed back as `quality` and stored on the board.+Before this, a long vocal section produced 481-frame a2v shots on a Standard+board: an hour of render each, none of which could finish.++**Casting the B-roll.** Each picture may carry `use` and `weight` beside its+`role` and `prompt`:++* `"use": "open"` takes the film's **first** B-roll shot, `"close"` its+ **last**, and `"any"` (the default) takes its turn in the rotation. Several+ of each are placed in the order given, so the last picture pinned `close` is+ the last shot of the film. A pin moves who is in frame and nothing about the+ clock — durations, `film_start` and every `audio_start_time` are untouched.+* `"weight": 1..20` (default 1) buys a picture that many turns in the+ rotation, spread rather than clumped: everybody once, then everybody with+ weight ≥ 2 again, and so on.++**Casting the singing.** The rotation alternates so the angle changes; which+picture **leads** it is decided by face size. A picture may carry+`"face_frac": 0..1` — how much of the frame the face fills — and the biggest+measured face opens the rotation, because a singing shot is a close-up and a+mouth at a quarter of the frame is mush where at half of it it is legible.+The number is never invented from the picture: the cheap proxies (aspect+ratio, short side) cannot tell a 1:1 crop of a face from a 1:1 crop of a+room, so a picture nobody measured keeps the place it was given rather than+being sorted by a made-up value. (The panel's captioner already looks at+every upload and is where this can be filled in later.) **A pin always+wins** — a `use` pin or a per-shot image pin is the caller saying which+picture goes where, and the face rule does not overrule it.++**A picture for one shot.** A `shots` row may carry `"image"` beside (or+instead of) its `prompt`: `[{"n": 7, "image": "/…/panel_uploads/face2.png"}]`+recasts that one shot. Same containment rule as everything else, and like the+`use` pins it moves who is in frame and nothing about the clock. A pin naming+a picture that is not in the cast is a note, not a refusal.++**A line for one shot.** `shots` is either `[{"n": 24, "prompt": "…"}]` or+`{"24": "…"}` and replaces the direction of that shot alone — the picture's+own `prompt` stays the default everywhere else it is cast, which is what lets+the last shot say "the stage lights slowly fading down to black" while the+same wide is used three times earlier without a fade. Each shot row comes+back with `prompt_override` so a caller re-planning can see which lines it+already owns. A line written for a shot number the plan does not have is a+note, not a refusal.++Every path a picture or a song takes in is the same containment rule the+whole panel uses — it resolves inside the outputs folder or the uploads+folder, or it is not used — and the refusal now names both folders and+`POST /upload` (multipart, field `image` or `audio`), which returns the path+to use.++From there it is an ordinary board: Render all, re-roll a shot, edit the+prompts. **Film with the song** (`POST /music/video/film`) exports it with+the song as the bed in `replace` mode — every clip's own audio is dropped and+the song plays unbroken, which the lip-sync survives because each singing+shot was rendered against its own segment of that file. The auto-editor is+off there on purpose: the board's cuts are already on the grid, and a second+pass over them would slide the singing shots off their own words.++### The a2v lane — what makes a mouth actually move++Three things decide whether a singing shot lip-syncs, and only one of them is+the sampler. The numbers below were measured on ONE shot at one seed with the+image, the audio window and the prompt held fixed, scored as the per-second+correlation between the inner-lip aperture and the vocal-band energy of the+same audio (`~/AI/projects/phosphene/notes/yue2/MAESTRO_LIPSYNC_STUDY.md`).++**1. Audio guidance has a different meaning on each lane, and the panel's old+default switched it off.** The Q4 distilled pipeline multiplies the audio+tokens by `audio_conditioning_scale`, so **1.0 is the identity — audio fully+on**. The Q8 two-stage pipeline has no such parameter at all: the helper+reroutes the slider onto the stage-1 guider's `modality_scale`, whose term is+`(value - 1) × (cond - uncond)`, so **1.0 makes it exactly zero** and the+vendored engine's own default is **3.0**. The panel stamped 1.0 on every a2v+job, so every Q8 a2v clip rendered at the default had audio guidance off in+all but name: **-0.065**, which is *worse* than the same clip scored against+deliberately wrong audio. At 3.0, nothing else changed: **+0.128**, and+positive seconds rose from 44% to 67%.++The form no longer sends a number unless you move the slider — it starts on+**Auto** and the panel fills in the lane's own default at queue time, which is+the only place that knows which pipeline will run (including the Q8→Q4+fallback when the Q8 files are missing). A value you set is passed through+untouched on both lanes, so a saved job or board keeps exactly what it had.++**2. The model should listen to the vocal, not the band.** Drums, bass and+guitar reach the audio encoder as energy that can be read as syllables, so the+model hedges — the mouth moves a little, all the time, on everything.+Conditioning on a separated vocal stem was the only candidate with a positive+zero-lag correlation (**+0.156**) and **doubled** how much the mouth moved.++Two fields, both optional: `audio_stem` names a stem you already have, and+`audio_stem_auto` asks the panel to make one with demucs. Whichever is used,+**the original song is muxed back over the finished clip** — the video stream+is copied, not re-encoded — so nothing the audience hears changes. The+separation is cached by path + size + mtime, so a twelve-shot film separates+once. demucs is an OPTIONAL extra (`scripts/pinokio/a2v_stems_deps.sh`, into+the engine venv); without it the auto option degrades to the full mix with a+note naming the installer, and never fails a queued job. `POST+/music/video/plan` takes `vocal_stem` and rides it onto every singing shot.++**3. The prompt must not say that nothing moves.** LTX reads a stillness word+as "nothing in the scene moves" — *including the singer's lips* — and returns+a freeze frame with a closed mouth. The planner used to write two of them+mechanically on every shot ("the frame never moves - no pan, no push-in, no+reframing" and "with no new movement of any kind"), and `storyboard.py`+*skipped* prompt validation for a2v, so the audio-driven mode got less+checking than every other one. The law now lives in `storyboard.py`, where+both planners and the validator read the same copy:++* a stillness phrase on an a2v shot is a **blocking validation error**, with+ the phrase named;+* a clause about the **camera** is deleted on the way out (an audio-driven+ shot does not want a restraint sentence at all) and a clause about a+ **person** is rewritten in place so it keeps its subject;+* the creative direction is capped at **40 words** — more set-dressing makes+ a more static clip and buries the vocal verb — and the cap falls on the+ direction only, never on the face law or the style;+* a literal sync contract is appended **last, after every polish pass**, so a+ re-roll or an enhance cannot paraphrase it away: *"The singer lip-syncs+ every vocal syllable to the supplied soundtrack…"* — "lip-syncs" rather+ than "sings", because a generic vocal verb is read as unconstrained+ performance;+* a window with **no vocal in it** (read off the sections) gets the opposite+ contract instead — *"the mouth stays at rest with relaxed closed lips"* —+ because saying nothing is not neutral: the model keeps the mouth working+ through an instrumental bar.++`compose_shot_prompt` is the last line of defence: every shot passes through+it on the way to a render, so a board planned before this law existed still+reaches the model with the contract on it.++The planner is `music_video.py`, pure and panel-free; the tests are+`test_music_video.py`, `test_music_video_routes.py`,+`test_music_video_minshot.py` and `test_a2v_sync_fixes.py`.## License and attribution@@ -179,6 +922,13 @@ The Compose footer credits Multimodal Art Projection and vanch007.## Validation and troubleshooting+`test_yue2_lora.py` covers the adapter contract: one canonical spelling for+every key layout, shape validation against the model that will run it, the+wrapper's arithmetic against `W x + s·B(A x)` written out by hand on a plain+*and* a quantised base, the parameter tree surviving a wrap unchanged (the+`load_nar` guard), `joint` vs `separate` decoder I/O, the instrumental recipe,+and the form → argv round trip. It loads no weights.+`test_music_engine.py` covers status, pack checks, the real HTTP handler'sform parsing, argv/provenance, progress, WAV MIME/ranges/gallery/Trash,process ownership, and an unchanged Video engine switcher. It uses fake@@ -197,3 +947,14 @@ this integration. A passing fake-pack test does not validate song quality.- **GPU busy:** the refusal names a lock file. Let that job finish; if nothingis running, the lock was left by a command-line job and can be deleted.- **Stopped:** no partial WAV is published; the next job starts a fresh child.++### When another render holds the GPU++A song queued while a command-line job holds `/tmp/phosphene_gpu.lock` (or the lab's+`.gpu_lock` directory) no longer fails with "Retry when it has finished": it waits in+the queue with the phase **Waiting for the GPU**, Stop ends the wait, and only a wait+longer than `PHOSPHENE_MUSIC_GPU_WAIT_S` (default 3600 s) refuses, naming the lock.+By default the panel only reads these locks. A panel that shares the machine with+command-line GPU jobs can set `PHOSPHENE_MUSIC_TAKES_GPU_LOCK=1`: it then creates the+file lock atomically while a song renders, so those jobs queue behind it, and removes+only the lock it wrote.diff --git a/docs/STATE.md b/docs/STATE.mdindex 9154034..c9eeda5 100644--- a/docs/STATE.md+++ b/docs/STATE.md@@ -1,3 +1,5 @@+> **🎼 2026-09-24 — v4.16.0: the Music Studio line goes public, with the 4.16.0 review fixes.** Codex reviewed seven flows of beta `cdca462` (install, jobs, LTX, H3, storyboard/editor, music, UI): 69 findings, fixed on three branches (`fix416-jobs` 17, `fix416-editor` 25 incl. one extra editor bug, `fix416-install` 27 + the FP16 flag; JOB-05 = INST-07), each with a test that fails before its fix. Integrated as `int-4160` on beta `33dd394` (after the 4.15.4 merge-back). **Conflicts:** only the UI-01 pair (`panel/routes_files.py`, `test_image_route_scope.py`), resolved to the 4.15.4 version (wider raster allowlist, never svg) keeping fix416-install's trash (UI-05) change; mlx_ltx_panel.py, queue.js, characters.js and image_engine.py auto-merged. **One Codex pass on the combined diff** (gpt-6-astra, high, read-only): 2×P2, both fixed — Load Params on a pre-4.15.2 a2v clip restored the legacy float 1.0 as an explicit "1" (audio guidance off on Q8; now reopens as Auto, `test_review_416_ltx.py`), and an incomplete FLAT H3 weights tree (LTX_H3_MODELS) was skipped by Install/Repair forever (now `h3_fetch_weights` in `h3_roots.sh` stops with an `error:` naming the missing parts; install_h3.js dispatch 16 chars). **Fleet fix:** "The reference image can't be read (ModuleNotFoundError)" was a half-installed engine venv (panel cannot import PIL), not a bad picture — 6 H3 i2v failures, one 4.15.2 install; `h3_reference_image_error()` now gives ENGINE_ENV_REPAIR (venv_broken). **H3 FP16 decode ON by default** after the release A/B through the panel (High 5 s Turbo, seed 42, runner 7919020): decode 90.1 → 77.4 s, peak 10.7 → 9.5 GiB, no visible difference (RGB PSNR 42 dB through the h264 exports; mean |Δ| 1.4/255). **LTX-03 verified on the GPU:** FFLF (Q8 dev, 768×384/49f) and Q4 A2V (Compact tier, 512×256/49f) with Pixar_Toon attach 576/576 modules and change the clip (PSNR vs no-LoRA 30.3 / 25.4 dB); a repeat no-LoRA A2V is bit-identical (inf), so the LoRA cache key releases the adapter. **Tests:** full root pytest in one process = the same suite-order pollution as beta/main (route tests pass alone, fail after an earlier test rebinds panel globals; beta/main shows it on test_routes/test_uploads/test_room_tone, int adds test_trash_collisions/test_version_pull_route — all pass per file); `release_gates.sh --fast` int 143/4/2 vs beta/main 119/4/2 with the identical 4 environmental FAILs (assert_registry 152/17 and assert_schedules 40/5 need packs + the bizarrotrn character, test_yue2_train_voice needs yue2 weights, scripts/test_pack_release no-mirror case). PostHog: the 403 a fixer saw was an endpoint the query key has no scope for; HogQL queries with it return 200. **Skipped-by-fast gates run separately:** test_storyboard_editor_ui 466 passed; check_output_codec PASS on the FFLF render. **From zero:** fresh clone of the release commit + install.js code steps in a Pinokio-shaped env (miniforge PATH, MPS fallback + fast-math set, no SSL/SSH/PYTHONPATH), booted the start.js way → /version 4.16.0 not dirty, UI 200, no traceback, /image refuses the settings file, a render with no weights fails naming the missing pack. **Update path:** a 4.15.4 install cloned from a local stand-in for public main, then 4.16.0 published there and update.js run → fast-forward, 4 steps rc 0, no `error:` line, VERSION 4.16.0, /status integrity OK. **INST-03:** env replaced by an empty `uv venv --seed` (boot WARNs "has a Python but no packages"); Update again → post_update rebuilt it, `import ltx_core_mlx, ltx_pipelines_mlx, mlx, mlx_arsenal` OK, boot clean; Repair (install.js code steps) rebuilds it too. **Found on the way, NOT fixed (mirror, not code):** the weights-ltx25-v1 release asset `LICENSE-LTX-2.x-Community-License.md` was overwritten on 2026-09-06 by the ic_upscale_x2 publish (34545 B, sha a6622b0e…); q4_25/q8_25/hq_25/gemma4_25 manifests expect 30938 B (4e7dd26d…), so every mirror fetch of those packs ends "1 file FAILED" + a WARN, though every weight file verifies and the pack reads ready.+> **🔒 2026-09-24 — v4.15.4: /image serves images only (security hotfix, Codex UI-01).** `panel/routes_files.py get_image` resolved the path and checked it sat under OUTPUT / UPLOADS / STATE_DIR — and served ANY file there. STATE_DIR holds `panel_settings.json` (HF token, CivitAI key, PostHog keys, which `/settings` never returns), so a local process, another local user, or anyone reaching a LAN-exposed/proxied panel could read them with one GET. A cross-origin web page could trigger the request but not read the response (no CORS headers). Fix: `IMAGE_ROUTE_EXTS` (png/jpg/jpeg/jpe/jfif/webp/gif + bmp/tif/tiff/avif/heic/heif, because the pickers accept `image/*`; **never svg** — same-origin script) checked right after the root check, before the file is opened, so the thumbnail path (w=) cannot fall back to serving the original either. Fixed first on beta branch fix416-install (f0a380a, image set widened here), ported alone onto public 4.15.3. Test `test_image_route_scope.py` (settings/queue/fleet/no-extension files 403 with and without w=, sidecar JSON in outputs/uploads 403, png/JPG/bmp/tiff still 200 from every root, svg 403, /etc/hosts 403); fails 3/6 on 4.15.3. Other path routes re-checked: /file is OUTPUT-only, /sidecar is media-suffix-gated OUTPUT/UPLOADS, /loras/download is .safetensors under the loras dir. One Codex pass (gpt-6-astra, read-only): leak closed (symlink/case/trailing-dot/double-ext/thumbnail fallback all checked); P3 .jfif/.jpe uploads would have 403d -> added; 2xP2 need a planted symlink in the thumb cache or next to an output (attacker already has file write as the user) -> not a boundary, left.> **🩹 2026-09-24 — v4.15.3: Hailuo H3 on a 36-59 GB Mac, said plainly; public pinokio.js identity.** A Japanese user with a 48 GB Mac wrote on X: "Since it requires 64 GB, I couldn't even install it [H3] from the UI." Every GATE on 4.15.2 would have let that Mac install and render H3 (pinokio.js `H3_MIN_BYTES` 36e9, `h3_preflight.sh` 36e9, panel `H3_MIN_RAM_GB_Q8` 36, Q8 lane peak 25.63 GiB). Reproduced against 59d733d with a fake `sysctl` answering hw.memsize=51539607552 (48.0 GiB) on PATH, panel booted the Pinokio way: `/status.h3` = capable true, available false, needs_q8_dit true, reason not_installed — and **`size_note` = "~75 GB · needs 64 GB unified memory"**, a literal unchanged since v3.4.0 (0ef1a98) that every earlier 46→36 sweep missed. That line sits under the pitch on the H3 install card (engine switcher + the Settings card's "How to enable H3" + the Models row). Second half of the dead end: the card says "click Install Hailuo H3 in the Pinokio sidebar", and while the panel runs pinokio.js returns the Open Panel menu, which had **no H3 entry** — it existed only with the panel stopped. Third: the Settings card and `ram_note` told a Mac that never installed H3 "its low-RAM engine isn't built yet … no extra download". Fourth: a 36-59 GB Mac holding the weights but not the Q8 build was told to click "Install Hailuo H3", which pinokio.js hides once `h3_ready`. **Fixes:** `h3_size_note()` from the constants ("needs 36 GB+ … 60 GB+ also unlocks the full bf16 engine"); `h3_ram_verdict()` splits the band by `h3_paths()` the same way pinokio.js picks its one H3 entry (nothing complete → Install, weights_ok but venv/runner missing → Repair, all present but no Q8 pack → Build; all keep "on its reduced-RAM lane" so `_analytics_refusal_reason` still says h3_ram); `H3_INSTALL_MENU_TEXT` / `H3_REPAIR_MENU_TEXT` / `H3_BUILD_MENU_TEXT` quoted verbatim by pinokio.js; pinokio.js `h3Offer()` puts Install/Repair/"Build Hailuo H3 compact engine (weights kept — no re-download)" in the running AND stopped menus (build entry = h3_ready && no h3-dit-q8 pack && totalmem < 60e9); install card adds "This Mac runs it." on the q8 lane and says the entry is there while the panel runs; Settings card is an offer (download icon, no warn) unless reason is missing_q8_dit; repair card uses ram_note when missing_q8_dit (its missing-list is empty). `h3_build_q8.sh` now waits (30 s polls, 60 min cap, fail-open) while `state/panel_queue.json` has a `current` job and a panel process exists, before the quantizer and before the fresh-process `load_dit` validation — both load the whole ~20 GB Q8 DiT, and the install is now reachable mid-session (residual: a render started DURING the ~1-2 min validation is not blocked). One Codex pass (codex-cli 0.155.1, read-only): 2×P2 — the build sentence could name a Build entry the menu doesn't show when the venv/runner is broken (fixed: menu-aligned sentences + test), and install-while-rendering could stack ~20 GB on a render (fixed: the wait above). Docs: README memory row, H3_ENGINE.md bands 46→36, troubleshooting #h3-compact, preflight "LTX-2.3" → "LTX". **BETA identity:** public pinokio.js carried `title: "Phosphene BETA"` + "[BETA — unreleased builds … port 8199]" since **v4.8.2 (4e1dde6, 2026-09-01)** — the beta checkout's local edit got committed to dev and rode every promote. On Pinokio 8.2.0 users did NOT see it in the sidebar: `kernel/api meta()` and the server's folder view overlay pinokio.json's title/description (Object.assign(pinokio.js, pinokio_meta.json, pinokio.json)), and public pinokio.json says "Phosphene"; it was latent text (app search index, raw file, any Pinokio without the overlay). Restored "Phosphene" / "[MAC ONLY] …". The beta install's sidebar name comes from its own skip-worktree **pinokio.json** ("Phosphene BETA"), which nothing upstream touches. **Beta checkout note:** phosphene-dev.git has pinokio.js skip-worktree; ANY upstream pinokio.js change aborts a pull there ("Please commit your changes or stash them") — already true for the pending 3-commit ff (4.15.2 changed pinokio.js). Its working pinokio.js holds nothing local any more, so at the next panel restart: `git update-index --no-skip-worktree pinokio.js && git checkout -- pinokio.js && git merge --ff-only beta/main` (leave pinokio.json and start.js skip-worktree). New test `test_h3_48gb_install_path.py` (16: panel sentences at 48 GiB both ways, verbatim menu strings, node-evaluated pinokio.js menus on a fake installed root at 32/48/64 GB running and stopped, public identity, preflight at 48 GB via fake sysctl). Fleet read (PostHog, since 09-22): 94/132 active installs on 4.15.2, failure rate 7.8%; 48 GB is not blocked in data — H3 on 24/60 active 48 GB installs, 203 H3 renders / 1 failure; the reporter is a pre-install drop-off analytics cannot see. Open from fleet: new-install "engine venv has a Python but no packages" rose 1.8% → 7.5% (5/67; two M5 Max 128 GB never recovered) — cause not reproduced; oversized a2v on 8 GB not refused (Metal watchdog). Issues: 7 open, none an in-reach bug (#62 retrain still owed; #61/#78/#48 await reporters; #24/#63/#83 features). UI is English-only; the reporter is Japanese — noted, no i18n built.@@ -16,6 +18,133 @@>> **The metric, honestly.** On the study's scorer (mouth aperture vs vocal-band envelope, per-second, best lag) the old default scores **−0.065** and 4.15.2 scores **+0.128**, exactly as the study found. But the study's negative control does not hold for music. It scored the clip against the song shifted +3 s, and at ~143 BPM two bars are 3.34 s, inside the ±0.4 s lag search. Scored that way, the new clip gets **+0.366**. The proper null scores each clip against **every** 10.05 s window of the song. Against that null, neither number is distinguishable from chance on one 10 s clip. Full mix: old −0.065 vs null +0.077±0.091 (z −1.55), new +0.128 vs +0.118±0.095 (z +0.10). Demucs vocal stem: old −0.088 (z −1.43), new +0.175 (z +0.56). The direction holds, but the proof is the mechanism (a zero guidance term) and the owner's eye, not this number. A lip-sync metric that can prove itself needs more clips or a SyncNet-class model.>+> **Dev side (not in the public entry).** Public 59d733d is merged back here, so `git log dev..origin/main` is empty; dev's own copy of the a2v changes, with the stem seam, prompt rules and face casting, is kept, and 2cc4b3a ports the legacy-job rule, the finite guard and the sidecar record onto it. In `phosphene-dev.git`, `pinokio.js` and `start.js` are marked `skip-worktree`. The `pinokio.js` edit is now committed with the same content, so its flag can be cleared (`git update-index --no-skip-worktree pinokio.js`) when that checkout is fast-forwarded. `start.js` keeps its flag: its `LTX_H3_*` paths are local-only and must never be committed. The lip-sync study's `+3 s` negative control is superseded by the permutation null above.+>+> **🎤 2026-09-22 — A TRAINED VOICE THAT SINGS THE WORDS YOU GIVE IT (`scripts/music/yue2_train_voice.py`, UNRELEASED).** The previous round's AR LoRA moved vocal identity a long way (sim 0.846 vs 0.657 control) but pronounced **none** of a set of unseen lyrics — 0/8 planted words, whisper word-error **1.000** — and the study concluded a trained voice and a supplied ABC score were mutually exclusive. Both findings are now superseded by measurement.+>+> **F1, new lyrics: 0/8 → 8/8, word error 1.000 → 0.214.** Two causes, and neither alone is enough. (1) **The training pair was a lie.** The prototype put the WHOLE song's lyrics in the prefix against a RANDOM 2048-token window of the track's codes; those describe different seconds, so the model could only learn "this style, this singer → codes" and never which words made which sounds. Recordings are now cut into 20.48 s windows (Maestro's 512 frames) and each window carries the lines whisper located inside it. (2) **The adapter was being driven at 1.0.** At full strength it overrides the base model's lyric conditioning completely — 0/8 either way it is trained. The 2×2, same seed, same unseen sheet, Direct mode: whole-song lyrics @1.0 **0/8 / WER 1.000**, whole-song @0.7 **4/8 / WER 1.000**, windowed @1.0 **0/8 / WER 0.896**, windowed **@0.7 8/8 / WER 0.214**. The stock model scores 7/8 at WER 0.325, so the best cell is **more accurate at the given words than the base model**, at voice similarity **0.8205** against stock's 0.7718 and a register within a semitone of the target. The WER column is what separates the two recipes: at 0.7 the whole-song adapter sings MORE words (243 vs 180) and still scores 1.000 — it learned to sing, not to sing what it is given. 0.5 is too far the other way (lyrics survive, voice does not: 0.7272, register −6.25 st).+>+> **F2 was a false premise, and disproving it produced the best take of the run.** `MAESTRO_VOICE_STUDY.md` §6.1 recorded that a real-audio-dialect LoRA forces Direct generation. That is a Maestro **UI** convention: `SongRequest.__post_init__` refuses `abc` only when `cot == "off"`, and `--mode melody` is not that — our runner has no such guard either. Handed the unplugged score directly, the direct-dialect voice sings it: **in-tune (octave-folded) 83.1 %, and in the WRITTEN octave 76.6 %**, against the stock voice's 96.1 % folded but **1.3 %** absolute — stock drops the whole melody an octave (175.5 Hz, −9.15 st), which is the problem the r3 round spent its effort transposing around. All 77 notes judged on both. The trained voice holds **6/8 lyrics and 0.8161 voice similarity at the same time**, which Direct mode never manages at full strength: a supplied score anchors the melody, leaving the lyric conditioning intact. **The shipped advice is therefore: use a trained voice WITH a score.**+>+> **The training curve says it generalises rather than memorises.** 35 windows, 400 steps, 21.8 min: artist CE 5.534 → 0.753, where the prototype's single memorised sequence was at **0.077** by the same step. Held-out minted CE moved 3.780 → 3.803 across the whole run, so the adapter never leaves YuE2's dialect — given a minted prefix it still predicts minted codes as well as it ever did. What breaks at full strength is generation under the trigger, not the dialect.+>+> **Shipped**: `scripts/music/yue2_train_voice.py` — `--recordings --lyrics --trigger --out [--steps --rank --lr --dialect direct|score --reg-pack]`, sequences built by the engine's own `token_prefixes` so training sees the byte-identical prefix inference builds, cross-entropy on the code tail only, Maestro's minted pack mixed in at `--artist-fraction` (`--reg-cache` converts it once so a machine without torch can train), output in the layout `yue2_lora.read_adapter` already reads plus a sidecar carrying the trigger, dialect, matching generation flags, base commit, data fingerprint and loss curve. The trainer is pure — no demucs, whisper or SheetSage2 in process; `--emit-windows` writes the window audio so those tools can be aimed at exactly the seconds each window trains on. Commits `23aabb9` `96ec533`. Gate: `test_yue2_train_voice.py test_yue2_lora.py test_yue2_tokenizer.py` — **118 passed**.+>+> **Two process scars, both now fixed in the scripts.** The overnight run produced nothing: it waited 59 minutes for the GPU, won the lock at 21:50 and died one line later because `gpu2.sh` had been rewritten at 20:51 **while a copy of it was executing** — bash reads a script incrementally by byte offset, so the running process resumed inside the new file. Never edit a file a running process is executing; write a new one. And the lock take is now `set -o noclobber` (atomic O_EXCL) rather than `[ ! -e ] && echo >`, which had already lost a race to another agent at 20:49 and left two GPU jobs briefly overlapping; the release now refuses to delete a lock it does not own.+>+> **The `score` dialect, measured — and why it loses.** Trained on 13 windows whose prefixes carried SheetSage2's `melody-vocal` transcription of the same seconds, then given the same test score: step 100 **97.4 % folded / 3.9 % absolute**, step 400 **76.6 % / 1.3 %**, registers −9.35 and −11.15 st — it follows the pitch classes and drops the octave, exactly as stock does. The cause is measured, not guessed: SheetSage2 writes the melody **+12.7 st above what was sung** (median over the 13 windows; 9 of them at +12.1 to +12.9), so every training pair taught "a written note means sing it an octave lower", while the test score is written at pitch (median MIDI 65 against the singer's 62.2). The `direct` voice under a score stays the recipe to use; the fix — transpose each training score to the sung octave, or calibrate the offset per window — is not in the trainer yet. The `score` curve also memorises far faster (artist CE **0.021** at step 400 vs the `direct` run's 0.753), because a unique score per prefix is a near-perfect key to that window's codes. Untested hypothesis worth one experiment: if YuE2's own pretraining scores share this octave convention, it would explain why the STOCK model drops a written score an octave too — the thing r3 compensated for with a −12 st transposition.+>+> **Not done**: no panel surface (CLI + the LoRA picker's `user/` folder); one recording only, so no held-out generalisation check (Maestro wants 2–50 songs and one held out); timbre still untouched — that is head + NAR adaptation and still needs an MLX VAE encoder, a differentiable NAR path and the unpublished minted anchor corpus.+> **🎤 2026-09-22 — THE A2V LANE WAS NOT LIP-SYNCING, AND THE BIGGEST REASON WAS A DEFAULT (branch `a2v-sync-fixes`, UNRELEASED).** The owner's verdict on the first real singing shot was that the mouth was not on the words. It is now a measurement, not an opinion: on one shot with the image, the 10.05 s audio window, the prompt and the seed held fixed, the per-second correlation between the inner-lip aperture (mediapipe FaceMesh 13/14, normalised by inter-ocular distance) and the 300–3400 Hz vocal-band envelope was **−0.065** — *worse* than the same clip scored against deliberately wrong audio (−0.054). Four fixes, all measured or structural, none of them the sampler.+>+> **The default meant OFF on one of the two lanes.** One slider, two pipelines, opposite meanings at the same number: Q4 distilled multiplies the audio tokens by `audio_conditioning_scale`, so 1.0 is the identity and the audio is fully on; the Q8 two-stage pipeline has no such parameter at all, so the helper reroutes the slider onto the stage-1 guider's `modality_scale`, whose term is `(value − 1) × (cond − uncond)` — **1.0 makes it exactly zero**, and the vendored engine's own default is 3.0. The panel stamped 1.0 on every a2v job, so every Q8 a2v clip ever rendered at the default had audio guidance switched off in all but name. At 3.0, nothing else changed: **−0.065 → +0.128**, positive seconds 44% → 67%. `make_job` no longer fabricates a number; a blank means "the lane's engine default" and `a2v_audio_scale()` resolves it in the one place that knows which pipeline is about to run, including the Q8→Q4 fallback. An explicit value passes through untouched on both lanes. The slider starts on **Auto** and sends nothing until it is dragged.+>+> **The model was listening to the band.** Drums, bass and guitar reach the audio encoder as energy that can be read as syllables, so it hedges — the mouth moves a little, all the time, on everything. A demucs vocal stem as the conditioning waveform was the only candidate with a positive zero-lag correlation (**+0.156**) and **doubled** the mouth movement (`mouth_std` 0.131 against 0.065). `audio_stem` / `audio_stem_auto` split what the model LISTENS to from what the clip PLAYS, and the original song is muxed back over the finished clip with the video stream copied. demucs is an optional extra (`scripts/pinokio/a2v_stems_deps.sh`, engine venv, written but not run); with it missing the auto option degrades to the full mix with a note naming the installer and never fails a queued job. Separation is cached by path+size+mtime, so a twelve-shot film separates once. `POST /music/video/plan` takes `vocal_stem`.+>+> **Our own planners were writing the lip-sync killer, mechanically, on every shot.** LTX reads a stillness word as "nothing in the scene moves" — including the singer's lips. `storyboard_planner._CAMERA_SENTENCES["static"]` is *"the frame never moves - no pan, no push-in, no reframing"* and the settle law adds *"with no new movement of any kind"*; `storyboard.py` then **skipped** prompt validation for a2v, so the audio-driven mode got less checking than every other one. The law moved into `storyboard.py` so both planners and the validator read one copy: stillness on an a2v shot is a blocking error with the phrase named, a clause about the CAMERA is deleted while a clause about a PERSON is rewritten in place ("she stands still at the microphone, singing" → "she stands steady at the microphone, singing"), the direction is capped at 40 words, and the literal sync contract is appended LAST so no polish pass can paraphrase it away. A window with no vocal in it gets "relaxed closed lips" instead. `compose_shot_prompt` applies it at render time as well, uncapped, so a board planned before the law still reaches the model with the contract on it. `still` as an adverb is deliberately not matched — this list blocks a render, and "the coffee is still hot" must not.+>+> **The biggest face leads the singing.** Face-tight framing did not move the correlation metric (the metric rewards timing, not readability) but it is the most perceptually convincing clip: 100% face detection and the highest mouth articulation of the non-stem candidates, because a mouth is legible at 46% of the frame and mush at 23%. A picture may carry `face_frac` and the biggest measured face opens the rotation. The number is never invented — aspect and short-side cannot tell a 1:1 crop of a face from a 1:1 crop of a room — so an unmeasured picture keeps its given place. A `use` pin or the new per-shot `shot_images` pin wins outright, and moves who is in frame and nothing about the clock.+>+> Commits `f3a77d0` `dd49675` `68da47c` `09ac13e`. Gate: `test_music_video.py test_music_video_routes.py test_storyboard.py test_storyboard_film.py test_routes.py test_no_duplicate_defs.py test_panel_assets.py test_a2v_sync_fixes.py` — **349 passed**, plus `test_a2v_audio_adhesion.py test_storyboard_planner.py` and `node scripts/lint_webapp.mjs` clean. **No GPU was used**: every number above is from the earlier study run, and nothing here was re-rendered.+>+> **Not done, deliberately:** demucs is not installed and the installer script has not been run; there is no panel control for the stem yet (the fields are on the job and on the plan route, the Audio tab has no picker); `face_frac` has no producer yet — the captioner is where it should come from.++> **🎬 2026-09-21 — WHAT THE FIRST REAL MUSIC VIDEO HAD TO BE PLANNED AROUND BY HAND (branch `music-video-fixes`, UNRELEASED).** A whole film went through `/music/video/plan` for the first time, and everything the operator had to do in a scratch script instead of in the panel is a gap. Five of them, closed.+>+> **The bug.** `cells_from_lengths()` read the SECONDS of every `LTX_LENGTHS` row and ignored the row's `qualities` column, so the 20 s / 481-frame cell — offered at Quick alone, because 640×480 holds it and 1024×576 dies around frame 454 (issue #46) — was on the duration axis of a board whose delivery pass is Standard. A long vocal section therefore planned 481-frame **a2v** shots, the most expensive shot this engine makes, none of which can finish on that canvas. The axis is now cut to the pass that DELIVERS the film (`storyboard_final_quality`, `standard` out of the box), in two places that cannot disagree: `cells_from_lengths(lengths, quality=…)` filters the panel's own table, and `plan_music_video(quality=…)` re-applies the restriction to whatever cells it is handed — because the caller who passes a hand-written axis is exactly the caller who can pass a dead cell. `quality` defaults to `standard`, so an unqualified plan is the conservative one. A dropped cell is a note in plain words, and the quality used is echoed back and stored on the board.+>+> **The song's structure is a parameter now.** `song_sections()` reads a score when there is one and guesses from band energy when there is not; neither could know that the first 8.5 seconds are held on an empty stage on purpose, or where a line really lands on a take that was *sung* rather than written. The first film's sections were typed against measured whisper onsets in a scratch script. `POST /music/video/plan` takes `sections` (JSON `{start, end, kind, label?}`), and `lyrics` / `score_abc` as alternatives to the sidecar. Precedence, each rung reached only when the one above is silent: explicit `sections` > form lyrics/score > sidecar > classifier. `given_sections()` sorts, closes gaps, clamps to the song, refuses overlaps and a missing `kind` by name — and always pulls the first section to 0:00, because the film plays from 0:00 with the song under it and a cursor starting at 8.5 s would render every mouth 8.5 s off its words.+>+> **B-roll casting was a blind round-robin**, so the picture the film opens and closes on was cast by accident and the operator re-cast twelve shots by index. A picture now carries `use` (`open` = the first B-roll shot, `close` = the last, `any`) and `weight` (1–20, spread across the rotation in passes rather than clumped), and `shots` carries a per-SHOT prompt override — `[{"n": 24, "prompt": "…"}]` or `{"24": "…"}` — so the last shot can say "the stage lights slowly fading down to black" while the same wide is used three times earlier without a fade. The pins are a post-pass: which shot is "last" is not known until the tiling is done, and a pin moves who is in frame and **nothing** about the clock (durations, `film_start` and every `audio_start_time` are byte-identical with and without pins, asserted).+>+> **The refusal says where files go.** Containment is unchanged — a form field naming a file resolves inside the outputs folder or the uploads folder or it is not used — but "picture 3 is not a file this panel has" now names both folders and `POST /upload` (multipart, field `image`/`audio`), which already existed; no second upload route was added, and a test asserts the route the error points at is a route this panel has.+>+> Gate: `test_music_video.py test_music_video_routes.py test_music_video_minshot.py test_routes.py` — **96 passed** (60 before). No JS changed. Docs: the music-video section of `docs/MUSIC_ENGINE.md` now carries the precedence table and every new field.++> **🎧 2026-09-21 — YuE2 CAN LISTEN: the real-audio tokenizer head, ported (branch `yue2-tokenizer`, UNRELEASED).** The previous entry ends by naming what was deliberately left out — `tokenizer_head_joint_v9`, the thing `nar_lora_joint_v9` was trained beside. It is in. A real recording now becomes YuE2 semantic codes on this Mac, which unlocks a round trip (recording → codes → YuE2's own decoder → audio) and a **continuation** (a song written on from a real take's codes). Owner: *"the tokenizer is out, so it can be trained… do an even better implementation."*+>+> **Nothing about the preprocessing was guessed.** Mothersuperior's `prep_real.py` and `joint_v6.py` were fetched from the release repo and read before a line was written, and every step is theirs: 30-second chunks encoded independently, `hidden_states[20]` concatenated and linearly resampled to `round(seconds × 25)`, rounded through **float16** because that is the precision the head was trained on, instance-normalised **per track** with numpy's population std, 512-frame windows with the learned `pos` sliced rather than interpolated, hop 256 with 128 frames trimmed off every interior edge, and plain `argmax` — the `sem_nbr_*` tables the repo ships are a training soft-CE loss, not an inference step, and they are pinned but unused.+>+> **The two things a port gets silently wrong, both settled against a reference instead of argued.** (1) The fused q,k,v projection: PyTorch's `in_proj_weight [1536,512]` is q,k,v by rows and **every permutation loads without complaint**. Against a torch `TransformerEncoderLayer` built from these exact tensors, q,k,v gives **max-abs-diff 3.910e-05** on a 512-frame window (relative 3.40e-06, argmax agreement 1.0000) and the five wrong permutations give 15.1–17.5. (2) The MERT layer: transformers collects a hidden state only AFTER each conformer block, so `hidden_states[20]` is the output of `layers[20]`, while `lyra.mert`'s `layer_weights` vector is one entry longer because index 0 is the pre-layer embedding — **the one-hot goes at 21**. Against the real HF model: index 21 reproduces `hidden_states[20]` to **1.135e-04**; 19, 20 and 22 are off by 7.3, 12.2 and 19.8. Code statistics do NOT separate them (layer 19 looks just as healthy — 594 unique, repeat 0.072), which is exactly why the reference run mattered.+>+> **The round trip, with controls.** 30 s of a real record (seconds 60–90), seed 4242, 32 ODE steps, measured against the SAME excerpt: stock decoder **7.935 dB** log-mel / chroma **0.8832**; `nar_lora_joint_v9` in `joint` **7.861 dB** / 0.8171; in `separate` 10.389 dB / 0.8314. The controls are what make those numbers mean something: the excerpt against itself is 0.000 dB / 1.0000, a **different** 30 s of the same record is 13.399 dB / 0.702, white noise at the same level 26.283 dB / 0.184, silence 101.5 dB. So the round trip lands inside "the same passage" and nowhere near "a different passage". Encode cost: **2.96 s for 30 s**. Synthesis 13.5–14.8 s, MLX peak 10.48–10.55 GiB. Codes for that excerpt: 750 frames, 565 unique, top code 0.9 %, repeat 0.087, mean run 1.09.+>+> **`--audio-prompt` on the runner.** The recording's first seconds become codes; the codes join the request prefix as ordinary codec tokens, so the AR model prefills on them exactly as on its own output. The codes stay at the head of the token stream and the plan keeps its canonical prefix, which is what `synthesize()` validates against the request. Listening happens before the generator is built and the MERT frontend is dropped after — same order and the same reason as the cover path (2.5 GB beside 10 GB is the memory guard). Measured at seed 4242, `cot=off`, 10 s prompt: **39.52 s of audio in 37.59 s wall** (3.96 s of it listening), ended naturally, against 30.00 s in 30.18 s for the same seed with no prompt (which hit the budget instead). The prompted song's first 10 s reconstruct the source — **10.503 dB / chroma 0.8752** — and its generated tail tracks the prompt's harmony at **chroma 0.5827** against **0.1011** unprompted. The two generated token streams agree on **0.14 %** of frames: a different song, not a perturbed one.+>+> **Two honest edges, in the docstring and the docs.** The repetition-penalty window and the minimum-length counter both restart at the continuation boundary, because `generate_tokens()` takes no prior history — the model sees the prompt, the sampler does not. And instance norm is per track, so the same seconds encode differently depending on what they were cut out of: the same 10 s scored inside a 30 s track agrees with its standalone encode on **34.40 %** of frames. That is faithful to the recipe; it means a prompt is cut once and reused.+>+> **The pack.** The head and the two `sem_nbr` tables go into `mlx_models/yue2-loras/**tokenizer/**` — under a subdirectory on purpose, because `pack_adapters()` globs the root and `user/` and a head beside the adapters would appear in the studio's LoRA picker as if it were one. `lora_problems()` still speaks only about adapters, so an installed pack is not declared broken by a new optional download; `head_problems()` is its own gate. FP32 throughout rather than the training-time bf16 autocast — the two agree on 97.07 % of frames, and polyphase-vs-ffmpeg resampling on 94.67 %.+>+> Commits `76480f3` `eab2b03` `2149d6a` `f0f5810`. Gates: `test_yue2_tokenizer.py` **54 passed** (and `test_yue2_lora.py` 32), `release_gates.sh --fast` **117 PASS / 2 FAIL / 2 SKIP** — both failures pre-existing and unrelated: `test_engine_env_fault` asserts a `site-packages/ltx_pipelines_mlx` string that is absent from `pinokio.js` at the branch base too, and `assert_registry` fails because this worktree has no LTX-2.3 weight pack on disk.+>+> **Not done, deliberately:** no panel surface (runner and CLI only — the studio has no "continue this recording" control); no training. **What training would need on MLX**, estimate only: (a) an **MLX Oobleck VAE encoder** — the weights are already on disk (218 `encoder.*` tensors in `mlx_models/yue2/vae/model.safetensors`) but `lyra/vae.py` is decoder-only, and without it `lat.npy` cannot be made on this Mac at all; (b) a **differentiable NAR path** — `joint_v6` backprops the flow loss through the acoustic branch while the 28-layer AR runs no-grad to build the KV cache, so `lyra.ar`/`lyra.nar` need a BF16 training twin (MLX has what it takes: `mx.grad` works through `mx.fast.scaled_dot_product_attention` and `mx.checkpoint` exists, but `StaticKVCache` and the quantised projections are inference shapes); (c) the **minted anchor corpus** — 4,000 YuE2-corpus tracks with `semantic.npy`, `latent.npy` and `request.json` feed the head's soft-CE every step and are what keep it inside YuE2's dialect; they are not published, and head training on a handful of real tracks without them should be expected to drift. The audio-domain loss additionally needs a differentiable log-mel + multi-resolution STFT through the frozen decoder, which is `mx.fft` plus a mel filterbank (there is no torchaudio here). Rough shape of the work: (a) 1–2 days, (b) 3–5 days, (c) unresolved without upstream data. The head itself is small (~45 M parameters) and would not be the bottleneck.++> **🎛️ 2026-09-21 — LoRA INFERENCE FOR YuE2, AND INSTRUMENTAL BECOMES A MECHANISM (branch `yue2-lora`, UNRELEASED).** The owner's standing bar: *"nothing you can do in Comfy that you cannot do in Phosphene"*. Maestro v2.3.0 had shipped YuE2 LoRA inference and an Instrumental mode built on Mothersuperior's AR adapter; our MLX engine had no adapter code at all, and Instrumental was a prompt convention — a skeleton of bracket tags plus "instrumental, no vocals" in the style.+>+> **Where the code had to live.** `lyra` is installed from a pinned SHA by `music_sync.sh`, so anything written inside `yue2-mlx/` dies on the next sync. The adapter code is ours: `scripts/music/yue2_lora.py`, applied to the models `lyra` hands back. `y = W x + strength · B (A x)`, BF16, at inference, never merged — the AR model runs 8-bit here and a merge would mean BF16-only (5 GB more resident) or a dequantise/requantise per song.+>+> **The one thing that was not obvious.** A wrapper *module* holding the original linear as a child renames every parameter (`…q_proj.weight` → `…q_proj.base.weight`), and `lyra.nar.load_nar()` validates the shared AR model by walking `tree_flatten(parameters())` against the exact upstream names — so the acoustic model would refuse to load halfway through the first song. The projection object is kept and its **class** is swapped for a generated subclass; the matrices hang off the instance through `object.__setattr__`, the pattern `lyra` itself uses. Parameter tree identical, `QuantizedLinear` unchanged, removal is one `__class__` assignment. `LoRARuntime` wraps `_load_model`, the only hook that sees the planning AR, the BF16 conditioning AR *and* the acoustic model built mid-song.+>+> **Modes, Maestro's semantics.** `joint` adds deltas and leaves the decoder projections alone even when the file carries them (`nar_lora_joint_v9` does; the sidecar records `decoder_io_ignored`). `separate` treats the acoustic file as a complete decoder companion and replaces `vae2llm`/`llm2vae` with a **convex blend** across companions — summing them doubles the shared decoder adaptation. Key spellings read: Mothersuperior, `model.`, PEFT/AI-Toolkit `base_model.model.`, `.lora_A.weight`/`.default.weight`, kohya `lora_down/up`, `.A`/`.B`; a PEFT `alpha` folds into B as `alpha/rank`. **The brief's own note that the AR file is MLP-only was wrong** — the header says 392 tensors: 28 layers × `self_attn.{q,k,v,o}` + `mlp.{gate,up,down}`, rank 64, 196 targets.+>+> **Instrumental is two recipes now, and one file decides which.** With the pack: the adapter at 1.0, `cot=full` forced, `[instrumental]` (or bare, optionally timed section tags) in place of words, other LoRAs paused, stock decoder. Without it: the v4.16 skeleton that was validated by ear. A queued song never fails on a missing optional download.+>+> **Proven with audio, not claims.** Four 30-second songs plus a UI job, same seed per pair, only the adapter differing, vocal content measured as demucs `htdemucs_ft` vocal-stem RMS over mix RMS. On a prompt that names a singer with `[instrumental]` as the lyrics: **-9.15 dB without the adapter, -58.53 dB with it — 49.4 dB less voice at the same seed.** On an *instrumental* prompt the pair proves nothing and is reported as such (both arms ≈ -67 dB; the base model already wrote no vocal line, so there was nothing to remove). `nar_lora_joint_v9` loads, synthesises and decodes cleanly and changes the audio, but barely moves the vocal share (0.4888 vs 0.5000) — it was trained beside `tokenizer_head_joint_v9`, which is not ported. Cost per adapter: **-17 %** AR planning throughput, **-16 %** AR semantic, **+12 %** acoustic, **+0.13 GiB** MLX peak. Wall-clock is dominated by how long a score the planner writes, not by the adapter.+>+> **End to end through the UI** on a test panel (`:8474`, isolated state/outputs, Pinokio-style env, stopped by PID): Instrumental on, 30 s, Draft → job `j-1a0c2b270ef-002` done in **39.6 s**, sidecar carrying `instrumental_recipe: mothersuperior-ar-lora` and the adapter's sha256, Song card badged `instrumental · lora` and `ar lora inst v3abc 1.00`, score engraved. That output measures **-56.81 dB** of vocal content. One honest artefact first: the *first* click failed instantly with the GPU-lock refusal, because this session was holding both locks for its own measurements — the refusal did its job and named the lock.+>+> **The pack** (`scripts/pinokio/music_lora_fetch.py`, opt-in, ~210 MB, checksummed, `NOTICE` beside it, `user/` scanned for anything dropped in) and the studio's **Voice & style LoRA** picker, plus a one-line download affordance under the Instrumental pill. `GET /music/lora/status`, `POST /music/lora/fetch`. Commits `f1b1584` `32f7ab8` `318a919` `8cf1fd3` `08578ae`. Gates: `test_yue2_lora.py` 32 passed (wrapper arithmetic checked against hand-written `W x + s·B(A x)` on a plain *and* a quantised base; a wrap renames no parameter), and the touched suites green.+>+> **Not done, deliberately:** the tokenizer head (`tokenizer_head_joint_v9`: 8-layer encoder, d=512, MERT layer-20 features at 25 Hz → 32768 codes — phase 2, the port plan is in the PM hub notes); `separate` bundles have tests but no real artist bundle to hear; the `_comfyui` block-diagonal fused layout is not read.++> **🔍 2026-09-20 (late) — THE BIG REVIEW: Codex, one pass, eleven findings, all fixed (`1fdc030`).** The owner: *"have codex do one big review after finish to find biggest bugs."* Codex CLI 0.155.1 (gpt-6-astra, xhigh), `codex exec -s read-only` with the brief in `/tmp/codex_review_prompt2.md` and the diff named as `git diff review-base...HEAD` (branch `review-base` = the public v4.15.1 tag; `codex exec review --base` refuses a custom prompt). It reproduced four of them in memory before reporting. Ranked as it ranked them:+>+> - **P1** every cover failed *after* publishing its song — the transcription work folder sat inside the artifacts folder and `save_artifacts()` insists on an empty one. Beside it now.+> - **P1** a sub-second B-roll scrap became a 1 s shot in the board writer while every singing shot after it kept its planned offset (singer at 11.08 s, words from 10.42 s). The planner folds scraps into the previous B-roll shot and never writes under `MIN_SHOT_S`; `test_music_video_minshot.py` walks the cursor.+> - **P1** the lyrics / section / Simple routes ran the warm helper without `_GPU_LOCK` — a queued music job kills the helper mid-rewrite, a rewrite mid-render spawns a second MLX model beside YuE2. `_helper_run()` takes the lock with a 3 s timeout and says so.+> - **P1** a cover's source path was not an exact-string secret, so `error_signature` carried `"<path> unreleased demo.wav"`. It is, with `music_parent` and `music_abc_path`.+> - **P2** Update's `uv sync` removed the cover's libraries while readiness stayed green (the extra is on every sync); the beat map's own ffmpeg resolver did not know Pinokio's folders (the planner is imported lazily and pointed at the panel's ffmpeg — which also takes numpy off the boot path); a 4-bit pill for weights the pack does not ship; Write after Cover still submitting the recording; grandchildren missing from the library; a section rewrite landing on the wrong index.+>+> Gates after: 323 passed across the touched suites, lint clean, dry-run 56/56 — checked on their real exit codes this time.++> **🎬 2026-09-20 (evening) — TWO OPUS AGENTS, MERGED: the lyrics editor + Simple mode, and the Music Video pipeline (UNRELEASED, dev).** The owner: *"use Opus agents and get it where it needs to be"* and *"I give it all the images, and then it creates a compelling video out of them."* Each agent worked in its own worktree from the briefs in the PM hub (`notes/yue2/STUDIO_DESIGN.md`, `notes/yue2/MUSIC_VIDEO_BRIEF.md`); I validated each against the real engines they could not reach, then merged.+>+> **Studio UI (`dfb35a8` `15f4d08` `3b69b0e`, + `71d4c69`).** The lyrics are sections now — label pill, lines, count, per-section **Rewrite** (`/music/lyrics/section`, a `section` param on the helper's `write_lyrics`), reorder, delete, `+ section`, a Sections/Text toggle that re-parses on blur, `#musicLyrics` still the one source of truth. **Simple mode**: one description → `/music/simple` → the helper's new `write_song` action returns `{title, style, lyrics}` from one strict-JSON Gemma call, shown in the Custom fields before anything renders. Verified live: 11 s for a title, a style line and full tagged lyrics; a chorus rewritten in four fresh lines. The agent could only stub Gemma, and the first real call came back numbered — `[Verse 1]` — so `music_tags.py` normalises every lyrics path to YuE2's bare tags (Hook → Chorus, Solo → Instrumental, unknown left alone), with tests. The agent also found `cz-section`/`cz-sum` had never had CSS: Cover a song and Advanced had shipped as bare `<details>`.+>+> **Music Video (`fa0c620` `ae44e99` `6be668b`).** `music_video.py`: `song_sections()` reads a YuE2 song's sections as arithmetic — bars × tempo from the score's `M:`/`Q:` and the lyrics' tags say who sings — and falls back to 8-bar downbeat phrases + a band-energy vocal classifier for a foreign recording; `plan_music_video()` turns vocal sections into a2v singing shots (alternating Singer pictures, the largest LTX cell inside 10–20 s) and everything else into 3–7 s i2v B-roll cut on downbeats, **with the film as the cursor** so every `audio_start_time` is the second that will actually be playing under that clip. The plan is an ordinary storyboard board. Routes `/music/video/plan` and `/music/video/film` (song = the bed, `replace` mode). Two real bugs found in the storyboard on the way: **`shot_to_job` never carried `audio`/`audio_start_time`/`image` for an a2v shot** (an a2v shot on a board enqueued as a silent t2v), and **`_sb_export` dropped `music`/`music_mode` in the whole-clip branch** (a soundtrack accepted at the door, a film written without it). One deliberate deviation from the brief: the film route leaves `auto_edit` OFF by default, because `plan_cut` snaps cuts backwards and the accumulated shift slides a2v clips off their own words — the board is already on the grid. Drive video became **Music video** (song, pictures with roles, one Look line, Plan the video → the board opens in Storyboard, Film with the song); the single-clip form is a collapsed "One shot" underneath.+>+> **The merge went wrong twice, both mine.** (1) The two worktrees had symlinks to the real `yue2-mlx`, `node_modules`, `ltx-2-mlx`, `mlx_models` so tests could run; `.gitignore` had `yue2-mlx/` and `node_modules/` with a trailing slash, which ignores a directory and not a symlink — the Music Video agent's `git add -A` committed two of them, and the merge **replaced the real engine checkout + venv and node_modules with self-referential links** (git treats ignored trees as expendable). Rebuilt from the installer's own scripts, both spellings ignored now, memory written (`feedback_agent_worktree_symlinks`). (2) Both agents appended routes to `panel/routes_music.py`; keeping conflict hunks in order interleaved one block inside the other's function — it compiled and 19 route tests failed. Rebuilt as studio-ui's file + music-video's additions. And the gates had been chained through `| tail`, so a red merge reached beta; `0783af5` repairs all of it.+>+> **First end-to-end music video: DONE.** `lights-on-unplugged_film.mp4`, 45.0 s, 8 clips at 1024×576, the song as the bed (h264 + aac 44.999 s). Timings on the M4 Max at the board's "standard" quality: B-roll i2v shots 61–167 s each, the 10 s a2v singing shot **1160 s** — lip-sync is the expensive part, and it is one shot in eight. Frames pulled at 8 s (the room B-roll) and 36 s (the singing close-up, mouth open on the verse) confirm the plan's placement. Nothing was hand-edited. Pictures came from mflux (the singer at an upright with a vintage mic, piano hands with rings, a candlelit room with a guitar on a stand).+>+> **Bohemian Rhapsody, the honest arc.** First attempt (instrumental test) came back with a female voice singing syllables: YuE2 has no instrumental switch — a supplied score with a *Vocal* voice is something to sing, and the mix transcription blends piano and voice into one line. Measured, not guessed: same key Bb, 73 vs 71 BPM, sung-line pitch classes 1.00 vs the source — the notes were the song's, the sound was not. Second pass, per the owner ("get it as close as you can, correct lyrics, I don't care how"): **words** — a local speech model (mlx-whisper large-v3-turbo) on his own mp3, 155 words over 0–151 s, sections at the two breaths (51.5 s, 105.5 s); cross-checked against an online copy (0.90 sequence agreement) and the online text used for the render, never printed; **score** — a `melody-vocal` transcription (the sung line only, 74 lines, Bb, 71); **style** — male operatic tenor, Unplugged; two Final takes at 2:29 / 2:27, both ended naturally; and a true instrumental from the score with the Vocal voice stripped (16 Ins lines, 0 vocal — it ended itself at 1:05). **The voice**: YuE2 cannot clone; the lever is Seed-VC (voice-lab, setting B) on the cover's demucs-separated vocal against Freddie's own demucs-isolated vocal (the solo ballad passage 56–70 s), remixed over the cover's accompaniment — runner at `/tmp/freddie_convert.sh` for now; belongs in the studio as a "Voice" step once judged by ear.++> **First end-to-end music video was rendering as this was first written**: three mflux pictures (a singer at an upright with a vintage mic, piano hands with rings, a small candlelit room with a guitar on a stand), "Lights On" (45 s), plan → 8 shots (7 B-roll, 1 singing at 31.9 s) → render → film with the song. Result in the next entry.++> **🎼 2026-09-20 — MUSIC STUDIO: the song is the unit now, not the file (UNRELEASED, dev).** The owner's brief: *"take it as far as possible... like motherfucking Suno, the Phosphene Music Studio... think about what we are missing in terms of its fractured structure, what tools we can give."* What was fractured: Compose was a form that dropped a WAV into the gallery and forgot everything about it. What the engine could already do and nobody exposed: keep the plan, the tokens, the latents and the noise, and restart from any of them.+>+> **Every song keeps its artifacts** (`state/music/<job-id>/`) and the sidecar names the folder. That single decision is what every verb below stands on. Proven end to end on a spare port, all timed on the M4 Max against a 45-second Draft song:+>+> - **New take** — same score, same words, a new performance. `SymbolicPlan.load` → `replace(request, seed=new)` → the semantic stage again. **21 s.**+> - **Re-roll the sound** — same performance, a new recording of it. `load_artifacts` → fresh solver noise → NAR + decoder only. **12 s** — a quarter of the song. This is the cheap variation nobody else has, because nobody else keeps the tokens.+> - **New style on this score** — the saved `score.abc` as `--abc-file` under the composer's new style and lyrics.+> - **Cover it** — loads the song as the source in Cover a song.+> - **Get the score** — transcription only, a queue job filed under `state/music/scores/`, fetched by job id. **7.5 s** for a 30 s excerpt.+> - **Write lyrics** — a `write_lyrics` action on the warm helper: the resident Gemma 3, a lyricist system prompt written around YuE2's own format (bracket tags, one line per row, a bare tag is instrumental, `[Verse]` not `[Verse 2]`). **9 s**, and the chorus came back the same each time it returned.+> - **Edit the score** — the ABC in a textbox, *Preview* redraws it, *Render this score* queues it. The edited text is written under `state/music/edits/` and the worker refuses any path outside that tree.+>+> **The Song card** (`#songCard`, `webapp/js/music.js`) sits under the player for songs only: title, style, badges (cover / new take / re-rolled / restyled / instrumental / cut at max length), **sheet music engraved by abcjs** (vendored, MIT, `webapp/vendor/abcjs/` — a score has to render with the network off) with key · meter · BPM read off the header, the lyrics with their tags, the lineage link back to the parent, and the four verbs. A song that kept nothing (made before this) gets its buttons disabled with the reason on hover, not a refusal after a click. Gallery cards read like songs: the title, and a chip for what it is.+>+> **The composer became a studio:** three task chips (Write / Cover / Get the score), a title, a concept box with *Write lyrics*, section-tag chips that insert at the caret, **Takes** (N songs from one form, each its own seed), and an Advanced section for what the engine always had — `cfg_scale` (1.0 sent as unset so the sidecar's `null` stays truthful), precision bf16/8bit/4bit.+>+> **Routes** (`panel/routes_music.py`): `/music/variation`, `/music/transcribe`, `/music/score`, `/music/score/render`, `/music/lyrics`. Every one takes OUTPUT paths, never state paths, and `_song_output()` accepts only a file inside the outputs folder carrying a music sidecar. **Lineage** lands in the sidecar (`lineage.parent`, `lineage.variation`) and `list_outputs` attaches a `music` block per song (title, variation, parent, has_score, has_artifacts) so the card's first paint needs no second request. Variation ETAs scale the song estimate (sound ×0.35, take ×0.9).+>+> Two things the lint gate caught on the way: `musicCoverInstall` was never published to the page in the cover commit (an unclickable install button), and the GET handler signature is `(h, parsed)`, not the POST one. 21 new tests + the earlier 14. Docs: `docs/MUSIC_ENGINE.md` gained a Music Studio section.+>+> **Same day, second pass — the Library.** The owner: *"the user interface is really, really far away from something I will be proud of... study Suno pretty well... learn from their best experience."* Studied (help center, release notes to Aug 2026, two walkthroughs) and written up in the PM hub as `notes/yue2/STUDIO_DESIGN.md` — what to keep (a list, cover art on every song, one ⋯ menu carrying every verb, families nested like versions, a persistent player with a real waveform, the lyrics as a document), what not to (two clips per generation as a default cost on a Mac; a social feed), and what only we have (the score). Shipped from it: **the Audio filter renders a song list, not a grid** (`renderSongList`: cover art deterministic from a hash of title+style, title, style chips, duration, badges, a play button, a ⋯ menu — Play / Open / New take / Re-roll / New style / Cover / Edit the score / Show in Finder / Delete, with the impossible ones disabled and the reason on hover); takes nest one level under their parent; **the player surface shows a hero** (cover, title, style, length) instead of a black box with a stock control; and **a sticky player bar** at the bottom of the outputs column — one `<audio>` for every song, prev/next through the list, and a waveform decoded once per song (480 peaks, cached) with the played part in the accent, click to seek. The score pane is capped at 380 px so a long sheet never buries the library.+>+> **Still ahead, in value order** (the plan in the PM hub, `notes/yue2/BEST_IMPLEMENTATION_PLAN.md`): LoRA at inference — the engine has no LoRA code and ComfyUI does, with community adapters ready (`Mothersuperior/YuE2-instrumental-cot-full-loras`); the real-audio tokenizer for true continuation; in-app LoRA training on lora_lab (ComfyUI's is NAR-only and its users report no audible effect — the bar is low); stems; music ↔ storyboard beat-aware cutting.+> **🔧 2026-09-20 — v4.15.1: the fleet's own bug list, fixed. Five faults, every one of them found in the data rather than reported.** The owner's instruction was "check fleet, github and pinokio and solve all bugs, ship fixes together with analytics improvements". GitHub and Pinokio turned out to be almost clean — every open bug thread there is already fixed and waiting on a reporter to confirm (the H3 Q8 SIGKILL in 4.12.2, the dead `madebyollin/taeh3` repo in 4.12.x, the YuE2 MPS flags in 4.14.3, the 48 GB bf16 pick in 4.12.4). **The fleet was not clean**, and nobody had filed any of this.>> - **ffmpeg was never where we looked.** Five installs across 4.5.0 → 4.15.0 finished a render and failed the export with "ffmpeg not found on PATH". Every engine spawn has prepended `FFMPEG_BIN` to the child's PATH for months — the miss was one level up: `_resolve_ffmpeg()` knew `pinokio/bin/ffmpeg-env` and nothing else, while **Pinokio's own bootstrap installs `ffmpeg=8.1.2` into its conda prefix** (`bin/miniforge/bin`) and unpacks a private Homebrew beside it. Proven on this Mac: that binary is sitting at `~/pinokio/bin/miniforge/bin/ffmpeg`, 443 KB, dated August. Now searched, along with `bin/miniconda/bin` and `bin/homebrew/bin`; **ffprobe resolves independently** instead of assuming the sibling path exists (the fleet's bare "ffprobe failed:", 3 installs); and a boot warning names every folder that was searched.@@ -3847,3 +3976,12 @@ Issue prefixes are `HAI-NN` because of the team constraint. Active:6. Last 5 commits on dev: `git log --oneline -5 dev`If you find on-disk state contradicts this doc (paths moved, commits diverged), surface that to Mr Bizarro before working around it. Updating this doc at session-end is part of the loop.++## 2026-09-21 night — Robot Freddie Unplugged (private experiment, PM hub notes)++State lives in `~/AI/projects/phosphene/notes/yue2/` (briefs `ROBOT_*`, `OVERNIGHT_2026_09_21_FILM.md`,+studies `MAESTRO_VOICE_STUDY.md`, `GROOVE_STUDY.md`, `MAESTRO_LIPSYNC_STUDY.md` when it lands) and in+memory. Code on dev today: LoRA inference + Instrumental (709a176), tokenizer head + `--audio-prompt`+(ac785db), `--lora-trigger` tests (40f0a5e), music-video planner fixes (601e723) — all pushed to beta,+nothing to public main. Studio test panel :8473 runs dev 601e723 from this checkout (PID `/tmp/studio_pid.txt`).+Overnight agents (song v3, lip-sync A/B, H3 draft film) write only named files into prod `mlx_outputs`.diff --git a/image_engine.py b/image_engine.pyindex 203c864..59559d1 100644--- a/image_engine.py+++ b/image_engine.py@@ -250,9 +250,44 @@ class ImageJobCancelled(RuntimeError):"""+# Set by the panel: "has Stop been pressed for the queue job this thread is+# running?" None outside the panel (tests, scripts) = never cancelled.+_CANCEL_CHECK = None++def _register_active_proc(proc) -> None:+ """Publish a fresh Popen where /stop looks, then honour a Stop that came+ first.++ THE ORDER IS THE FIX (same shape as the panel's _register_job_pgid). Stop+ sets the job's cancel flag and then reads this registry; this adds to the+ registry and then reads the flag. Whichever runs first, the other sees it:+ Stop finds the process and kills it, or this finds the flag and kills the+ process itself. Before, a Stop during the image job's preflight found no+ process to kill, and the engine started anyway and published its image."""with _ACTIVE_PROC_LOCK:_ACTIVE_PROCS.add(proc)+ check = _CANCEL_CHECK+ try:+ cancelled = bool(check and check())+ except Exception: # noqa: BLE001+ cancelled = False+ if cancelled:+ import os+ import signal+ try:+ os.killpg(os.getpgid(proc.pid), signal.SIGKILL)+ except (ProcessLookupError, PermissionError, OSError):+ try:+ proc.kill()+ except Exception: # noqa: BLE001+ pass+ try:+ proc.wait(timeout=5)+ except Exception: # noqa: BLE001+ pass+ _unregister_active_proc(proc)+ raise ImageJobCancelled("image engine stopped before it started (Stop)")def _unregister_active_proc(proc) -> None:@@ -867,6 +902,15 @@ def _generate_mflux(prompt: str, n: int, width: int, height: int,eff_guidance = (config.mflux_guidanceif config.mflux_guidance is not Noneelse fam_defaults["guidance"])+ # A LIGHTNING ADAPTER RUNS AT GUIDANCE 1.0, whatever the family default.+ # Lightning is a step distillation trained without CFG; the qwen_edit+ # family default (4.0) is the 40-step Quality recipe's true-CFG. Reference+ # Edit Fast, the dataclass default and the auto-promotion all carry the+ # Lightning LoRA with guidance unset, so they sent `--guidance 4.0`+ # (Codex UI-03, 2026-09-24). An explicit mflux_guidance still wins.+ if (config.mflux_guidance is None+ and any("lightning" in str(lp).lower() for lp in (config.mflux_lora_paths or []))):+ eff_guidance = 1.0# Build the seed list. mflux's CLI loops `for seed in args.seed`# AFTER loading the model exactly once, so passing all seeds atdiff --git a/install_h3.js b/install_h3.jsindex 37c8fdd..ad56705 100644--- a/install_h3.js+++ b/install_h3.js@@ -44,6 +44,10 @@// Published as a NEW branch: the histories diverged, and force-moving a// branch users' installs already track is how updates break mid-clone.const H3_BRANCH = "codex/h3-engine-v2"+// Every step that works inside the checkout starts here: resolve the roots the+// panel uses (LTX_H3_ROOT / LTX_H3_MODELS), then enter the checkout. See+// scripts/pinokio/h3_roots.sh.+const RH3 = ". scripts/pinokio/h3_roots.sh && cd \"$H3_CHECKOUT\" && "module.exports = {requires: { bundle: "ai" },@@ -84,12 +88,19 @@ module.exports = {// ---- Clone the engine --------------------------------------------------// Guarded: `git clone` into an existing directory fails and would abort// the whole install on a re-run / resume.+ //+ // EVERY STEP BELOW RESOLVES ITS ROOTS THROUGH scripts/pinokio/h3_roots.sh —+ // LTX_H3_ROOT / LTX_H3_MODELS, the overrides the panel and the sidebar+ // already honour. The steps used to hardcode `minimax-h3-mlx` and+ // `{{cwd}}/mlx_models/hailuo-h3`, so on a relocated install Repair fixed a+ // second checkout the panel never uses and could fetch ~75 GB of duplicate+ // weights (Codex INST-09). Hence no `path:` and no `when: exists(...)`:+ // both can only name the default location.{- when: "{{!exists('minimax-h3-mlx/.git')}}",method: "shell.run",params: {message: [- "git clone --branch " + H3_BRANCH + " https://github.com/mrbizarro/minimax-h3-mlx.git minimax-h3-mlx"+ ". scripts/pinokio/h3_roots.sh && { [ -d \"$H3_CHECKOUT/.git\" ] || git clone --branch " + H3_BRANCH + " https://github.com/mrbizarro/minimax-h3-mlx.git \"$H3_CHECKOUT\"; }"]}},@@ -131,13 +142,12 @@ module.exports = {{method: "shell.run",params: {- path: "minimax-h3-mlx",message: [// The pin itself lives in scripts/pinokio/h3_checkout.sh (#74: Update// must make the same move; one literal, two callers). H3_BRANCH above// is only the fresh-clone branch and must match it.- "bash ../scripts/pinokio/h3_checkout.sh \"$(pwd)\"",- "git rev-parse --short HEAD"+ RH3 + "bash \"$APP_ROOT/scripts/pinokio/h3_checkout.sh\" \"$(pwd)\"",+ RH3 + "git rev-parse --short HEAD"]}},@@ -171,20 +181,9 @@ module.exports = {{method: "shell.run",params: {- path: "minimax-h3-mlx",message: [- "echo '=== H3 venv check ==='",- [- "if .venv/bin/python -c 'import sys' >/dev/null 2>&1; then",- " echo 'H3 venv healthy - reusing it'",- "else",- " echo 'H3 venv missing or broken (dangling interpreter) - rebuilding, no weights are re-downloaded'",- " which uv && uv --version || echo 'uv NOT FOUND'",- " rm -rf .venv",- " uv venv --python 3.11 --seed .venv",- " .venv/bin/python --version || echo 'venv python NOT executable'",- "fi",- ].join("\n")+ // The body is scripts/pinokio/h3_venv.sh (it was a 372-char dispatch).+ RH3 + "bash \"$APP_ROOT/scripts/pinokio/h3_venv.sh\""]}},@@ -192,11 +191,10 @@ module.exports = {{method: "shell.run",params: {- path: "minimax-h3-mlx",message: ["echo '=== H3 dependencies ==='",- "uv pip install --python .venv/bin/python -r requirements.txt",- ".venv/bin/python -c \"import mlx.core as mx, numpy, PIL; print('H3 deps OK')\""+ RH3 + "uv pip install --python .venv/bin/python -r requirements.txt",+ RH3 + ".venv/bin/python -c \"import mlx.core as mx, numpy, PIL; print('H3 deps OK')\""]}},@@ -223,13 +221,17 @@ module.exports = {{method: "shell.run",params: {- path: "minimax-h3-mlx",env: {HF_HOME: "{{cwd}}/cache/HF_HOME",HF_XET_HIGH_PERFORMANCE: "1"},message: [- ".venv/bin/python scripts/download_selected.py --root '{{cwd}}/mlx_models/hailuo-h3'"+ // A FLAT tree (see h3_roots.sh) cannot be written by this downloader+ // — it appends models/ — so it is left alone instead of duplicated.+ // An INCOMPLETE flat tree stops the install with the missing paths+ // ("error:" is what Pinokio 8.2.0 stops on) instead of skipping it+ // (h3_fetch_weights in h3_roots.sh; kept out of line for the width).+ RH3 + "h3_fetch_weights"]}},@@ -258,9 +260,8 @@ module.exports = {{method: "shell.run",params: {- path: "minimax-h3-mlx",message: [- ".venv/bin/python '{{cwd}}/scripts/fetch_h3_turbo.py' --dir '{{cwd}}/mlx_models/hailuo-h3/models/turbo-lora' || echo 'TURBO FETCH FAILED - panel offers a one-click retry'"+ RH3 + ".venv/bin/python \"$APP_ROOT/scripts/fetch_h3_turbo.py\" --dir \"$H3_LAYOUT/turbo-lora\" || echo 'TURBO FETCH FAILED - panel offers a one-click retry'"]}},@@ -276,19 +277,18 @@ module.exports = {{method: "shell.run",params: {- path: "minimax-h3-mlx",env: {HF_HOME: "{{cwd}}/cache/HF_HOME",HF_XET_HIGH_PERFORMANCE: "1"},message: [- "mkdir -p '{{cwd}}/mlx_models/hailuo-h3/models/tae'",+ RH3 + "mkdir -p \"$H3_LAYOUT/tae\"",// The HF repo this used to come from (madebyollin/taeh3) was deleted// in 2026-09 and every H3 install died here with "Repository Not// Found" (Pinokio, @macstephen). The script fetches the same bytes// from a pinned commit of the author's GitHub repo, verifies the// sha256, and keeps HF as a fallback.- ".venv/bin/python ../scripts/pinokio/h3_fetch_tae.py '{{cwd}}/mlx_models/hailuo-h3/models/tae/taeh3.safetensors'"+ RH3 + ".venv/bin/python \"$APP_ROOT/scripts/pinokio/h3_fetch_tae.py\" \"$H3_LAYOUT/tae/taeh3.safetensors\""]}},@@ -312,12 +312,11 @@ module.exports = {{method: "shell.run",params: {- path: "minimax-h3-mlx",// 3.8.3: body moved to scripts/pinokio/h3_build_q8.sh (595-char- // dispatch). {{cwd}} is substituted in the MESSAGE, so the app root- // is passed as $1 rather than written into the script.+ // dispatch). The app root is passed as $1; h3_roots.sh has exported+ // LTX_H3_MODELS as an absolute path, which the build reads.message: [- "bash ../scripts/pinokio/h3_build_q8.sh '{{cwd}}'"+ RH3 + "bash \"$APP_ROOT/scripts/pinokio/h3_build_q8.sh\" \"$APP_ROOT\""]}},diff --git a/mlx_ltx_panel.py b/mlx_ltx_panel.pyindex bacf3b3..5382747 100644--- a/mlx_ltx_panel.py+++ b/mlx_ltx_panel.py@@ -217,10 +217,14 @@ def engine_env_fault() -> str:# in the fleet view, and "fetch" belongs to download_failed (checked against# the live classifier, not guessed). The phrase that has to survive is "venv",# which is how venv_broken finds it.+#+# "Stop Phosphene first" because the entry only appears once the panel is+# stopped — the repair reinstalls into the venv this process holds open. The+# running sidebar says the same (INST-05).ENGINE_ENV_REPAIR = (- "Fix it from the Pinokio sidebar: \"Repair Phosphene engine (models "- "kept)\" rebuilds the venv and keeps every model you have. Update works too. "- "Renders cannot run until it is repaired."+ "Fix it from the Pinokio sidebar: Stop Phosphene, then click \"Repair "+ "Phosphene engine (models kept)\" — it rebuilds the venv and keeps every "+ "model you have. Update works too. Renders cannot run until it is repaired.")if not HELPER_PYTHON.is_file():@@ -997,6 +1001,13 @@ def _settings_defaults() -> dict:# never changes the result, and it is what makes Stop early# possible at all."live_preview": "on",+ # H3 FP16 VAE decode — ON since 4.16.0. See h3_vae_fp16_decode().+ # Measured 2026-09-23 on a real 1152x640/124f latent: decode 105.1 s ->+ # 90.2 s (-14 %), peak 11.1 -> 8.0 GiB, PSNR 72.8 dB against the float32+ # decode (perf/vae-2026-09-23). The release A/B (2026-09-24, High 5 s+ # Turbo, seed 42, through the panel): 90.1 s -> 77.4 s, peak 10.7 ->+ # 9.5 GiB, no visible difference on any frame.+ "h3_vae_fp16": True,# ---- Update banner + the one-time star ask -------------------------# `update_banner_dismissed` holds the VERSION the user dismissed, not a# boolean: dismissing 4.1.1 must not silence the banner for 4.2.0. The@@ -1331,6 +1342,12 @@ def _validate_settings_patch(patch: dict) -> tuple[dict, str | None]:return {}, f"unknown h3_dit: {v} (auto | bf16 | q8)"out["h3_dit"] = v+ # ---- H3 FP16 VAE decode (on by default since 4.16.0) ----------------+ if "h3_vae_fp16" in patch:+ _v = patch["h3_vae_fp16"]+ out["h3_vae_fp16"] = (_v.strip().lower() in ("1", "true", "yes", "on")+ if isinstance(_v, str) else bool(_v))+# ---- Anonymous usage analytics -------------------------------------# Additive only: three user-settable fields. `analytics_install_id`,# `analytics_last_packs` and `analytics_disclosed` are deliberately NOT@@ -1447,6 +1464,7 @@ def get_settings_public() -> dict:# the GET never returned it, so any control would open showing "auto"# no matter what the user had chosen."h3_dit": str(s.get("h3_dit", "auto") or "auto"),+ "h3_vae_fp16": bool(s.get("h3_vae_fp16", True)),"update_banner_dismissed": str(s.get("update_banner_dismissed", "") or ""),"star_prompt_done": bool(s.get("star_prompt_done", False)),"broadcast_seen_ids": list(s.get("broadcast_seen_ids") or []),@@ -1480,13 +1498,13 @@ def _settings_file_stamp() -> tuple[int, int] | None:_SETTINGS_STAMP: tuple[int, int] | None = _settings_file_stamp()-def _settings_reload_if_changed() -> None:+def _settings_reload_if_changed(force: bool = False) -> None:"""Under _SETTINGS_LOCK. Re-read panel_settings.json when another processwrote it — two panels share one state dir on a dev box (the drivesymlink), and a second panel's boot or Settings save must be visible here."""global _SETTINGS_STAMPstamp = _settings_file_stamp()- if stamp == _SETTINGS_STAMP:+ if stamp == _SETTINGS_STAMP and not force:returntry:with SETTINGS_FILE.open("r") as fh:@@ -1511,10 +1529,34 @@ def _settings_write_delta(delta: dict) -> None:write. Merging the delta onto the file as it is now means a stale copy canonly change the keys it is actually setting."""global _SETTINGS_STAMP- _settings_reload_if_changed()- _SETTINGS.update(delta)- _save_settings(_SETTINGS)- _SETTINGS_STAMP = _settings_file_stamp()+ # ACROSS PROCESSES, TOO (Codex UI-04, 2026-09-24). _SETTINGS_LOCK is a+ # thread lock: two panels on one state dir could both read the old file,+ # and the later writer's merge — made on its stale copy — reverted the+ # other's freshly saved key. An flock on a sibling lock file makes+ # read-merge-replace one transaction between processes, and the reload+ # is FORCED once it is held (an mtime/size stamp can miss a same-size+ # write inside one clock tick). Fail-open: a filesystem without flock+ # keeps the old, single-process behaviour rather than refusing to save.+ import fcntl+ lock_fh = None+ try:+ lock_fh = open(SETTINGS_FILE.with_name(".panel_settings.lock"), "a")+ fcntl.flock(lock_fh.fileno(), fcntl.LOCK_EX)+ except OSError:+ if lock_fh is not None:+ lock_fh.close()+ lock_fh = None+ try:+ _settings_reload_if_changed(force=lock_fh is not None)+ _SETTINGS.update(delta)+ _save_settings(_SETTINGS)+ _SETTINGS_STAMP = _settings_file_stamp()+ finally:+ if lock_fh is not None:+ try:+ fcntl.flock(lock_fh.fileno(), fcntl.LOCK_UN)+ finally:+ lock_fh.close()def get_settings() -> dict:@@ -3040,12 +3082,9 @@ def _train_install_dev_transformer(push_log) -> dict:proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,text=True, errors="replace", bufsize=1, env=env, start_new_session=True)- with DOWNLOAD_LOCK:- DOWNLOAD["proc"] = proc- try:- DOWNLOAD["pgid"] = os.getpgid(proc.pid)- except ProcessLookupError:- DOWNLOAD["pgid"] = None+ if not _download_register(proc):+ push_log("[hf] dev transformer download cancelled.")+ returnbuf = ""assert proc.stdout is not Nonewhile True:@@ -3077,6 +3116,7 @@ def _train_install_dev_transformer(push_log) -> dict:DOWNLOAD["last_line"] = ""DOWNLOAD["proc"] = NoneDOWNLOAD["pgid"] = None+ DOWNLOAD["cancelled"] = Falsethreading.Thread(target=_runner, daemon=True, name="hf-dev-download").start()return {"ok": True, "started": True, "repo_id": repo_id,@@ -4857,7 +4897,19 @@ def parse_loras_from_form(form: dict) -> list[dict]:# Clamp; LoRA strengths beyond ±2 are usually nonsense and risk# numerical issues during fusion.strength = max(-2.0, min(2.0, strength))- out.append({"path": path, "strength": strength})+ entry = {"path": path, "strength": strength}+ # REPLAY PROVENANCE (Codex H3-03). Load Params / Finish restore an old+ # recipe's strengths verbatim and tag each with the recipe's own+ # h3_lora_scale_v (0 = written before the stamp existed). make_job+ # stamps the CURRENT version on every H3 job, so without this an old+ # automatic 0.5 read as a deliberate modern choice and the dispatch+ # migration left the scale applied twice. Only an integer survives.+ if "scale_v" in item:+ try:+ entry["scale_v"] = int(item.get("scale_v") or 0)+ except (TypeError, ValueError):+ entry["scale_v"] = 0+ out.append(entry)return out@@ -5333,6 +5385,22 @@ def ltx_floor_canvas(width, height) -> tuple[int, int]:max(64, (int(height) // 64) * 64))+def ltx_fit_canvas(width, height, max_dim: int) -> tuple[int, int]:+ """Fit a canvas under a hardware cap: ONE scale factor for both sides so+ the long side is at most `max_dim` (0 = no cap), then ltx_floor_canvas.++ Every hardware clamp goes through here. The A2V clamp capped each side on+ its own, so a 1280x704 canvas under a 768 cap became a near-square+ 768x704 (LTX-06); the tier, keyframe and compact-profile clamps scaled+ proportionally but rounded to /32, undoing make_job's /64 floor and+ recording dimensions the two-stage engine does not deliver (LTX-10)."""+ w, h = float(width), float(height)+ if max_dim and max(w, h) > max_dim:+ scale = max_dim / max(w, h)+ w, h = w * scale, h * scale+ return ltx_floor_canvas(w, h)++def ltx_model_dir(quant: str, version_id: str | None = None) -> str:"""Pack directory for a job spec, with the fallback the IC-LoRA / HDRsites hand-rolled four times: if the pack directory isn't on disk, hand@@ -6486,9 +6554,37 @@ DOWNLOAD: dict = {"last_line": "", # most recent hf output line for UI display"proc": None,"pgid": None,+ # Set by /models/cancel, cleared when the worker releases the slot. The+ # worker used to read "still active?" as "not cancelled" — but Cancel never+ # cleared `active` (the slot stays held until the worker's own cleanup), so+ # a cancelled attempt looked like a failed one and was RETRIED, and a+ # cancel during backoff did nothing at all (Codex INST-07 / JOB-05).+ "cancelled": False,}+def _download_register(proc) -> bool:+ """Publish a freshly spawned downloader so Cancel can reach it.++ False when a cancel landed first — in the window between Popen and here the+ cancel had no process to signal — in which case the new process group is+ killed on the spot and the caller must stop."""+ with DOWNLOAD_LOCK:+ DOWNLOAD["proc"] = proc+ try:+ DOWNLOAD["pgid"] = os.getpgid(proc.pid)+ except ProcessLookupError:+ DOWNLOAD["pgid"] = None+ cancelled = DOWNLOAD.get("cancelled")+ if cancelled:+ _kill_active_download()+ try:+ proc.wait(timeout=10)+ except Exception:+ pass+ return not cancelled++def _download_thread(repo: dict) -> None:"""Run `hf download <repo_id> --local-dir <repo.local_dir>` and streamstdout/stderr line-by-line into STATE['log']. Sets DOWNLOAD["active"]@@ -6575,7 +6671,7 @@ def _download_thread(repo: dict) -> None:try:for attempt in range(1, max_attempts + 1):with DOWNLOAD_LOCK:- if not DOWNLOAD["active"]:+ if not DOWNLOAD["active"] or DOWNLOAD["cancelled"]:push(f"[{dl_tag}] {dl_label} cancelled before attempt {attempt}.")breakif attempt > 1:@@ -6593,12 +6689,9 @@ def _download_thread(repo: dict) -> None:except Exception as exc:push(f"[{dl_tag}] failed to spawn the downloader: {exc}")break- with DOWNLOAD_LOCK:- DOWNLOAD["proc"] = proc- try:- DOWNLOAD["pgid"] = os.getpgid(proc.pid)- except ProcessLookupError:- DOWNLOAD["pgid"] = None+ if not _download_register(proc):+ push(f"[{dl_tag}] {dl_label} cancelled.")+ break# Stream every line. hf emits a tqdm progress bar with carriage# returns; we split on \r as well as \n so progress updates show# up live in the panel log instead of being buffered until done.@@ -6623,17 +6716,18 @@ def _download_thread(repo: dict) -> None:push(f"[{dl_tag}] {dl_label} downloaded successfully.")breakwith DOWNLOAD_LOCK:- still_active = DOWNLOAD["active"]- if not still_active:+ cancelled = DOWNLOAD["cancelled"] or not DOWNLOAD["active"]+ if cancelled:push(f"[{dl_tag}] {dl_label} cancelled (exit {rc}).")breakif attempt < max_attempts:push(f"[{dl_tag}] {dl_label} attempt {attempt} failed (exit {rc}). Retrying in {backoff_sec}s — the downloader resumes from where it stopped.")- # Sleep in 1-second slices so a cancel during backoff is responsive.+ # Sleep in 1-second slices so a cancel during backoff is+ # responsive; the check at the top of the loop then stops it.for _ in range(backoff_sec):time.sleep(1)with DOWNLOAD_LOCK:- if not DOWNLOAD["active"]:+ if DOWNLOAD["cancelled"]:breakbackoff_sec = min(backoff_sec * 2, 60) # 5 → 10 → 20s cap by attempt 3else:@@ -6649,6 +6743,7 @@ def _download_thread(repo: dict) -> None:DOWNLOAD["last_line"] = ""DOWNLOAD["proc"] = NoneDOWNLOAD["pgid"] = None+ DOWNLOAD["cancelled"] = Falsedef _kill_active_download() -> None:@@ -7207,16 +7302,18 @@ def _hf_lora_download(repo_id: str, filename: str, meta: dict) -> dict:loras_dir.mkdir(parents=True, exist_ok=True)shutil.move(got, target)layout_info = {"layout": None, "converted": False, "prefix": ""}+ strength = float(meta.get("recommended_strength") or 1.0)if lane == "h3":try:layout_info = _h3_lora_prepare(target)except Exception as exc: # noqa: BLE001push(f"[huggingface] layout probe failed: {exc}")+ strength = _h3_lora_browser_strength(target, meta, "huggingface")sidecar = target.with_suffix(".json")data = {"name": meta.get("name") or target.stem, "description": meta.get("description") or "","trigger_words": list(meta.get("trigger_words") or []),- "recommended_strength": float(meta.get("recommended_strength") or 1.0),+ "recommended_strength": strength,"preview_url": meta.get("preview_url"), "preview_type": meta.get("preview_type"),"base_model": meta.get("base_model") or ("MiniMax H3" if lane == "h3" else "LTXV 2.3"),"source": "huggingface", "hf_repo": repo_id,@@ -7369,6 +7466,8 @@ def _civitai_download(download_url: str, meta: dict) -> dict:passpush(f"[civitai] refused {target.name}: {exc}")raise RuntimeError(str(exc)) from exc+ strength = (_h3_lora_browser_strength(target, meta, "civitai") if lane == "h3"+ else float(meta.get("recommended_strength") or 1.0))# Write the sidecar — kept tolerant of meta gaps so a partial# payload still produces a usable picker entry.sidecar = target.with_suffix(".json")@@ -7377,7 +7476,7 @@ def _civitai_download(download_url: str, meta: dict) -> dict:"description": meta.get("description") or "","trigger_words": (list(meta.get("trigger_words") or [])or list(layout_info.get("trigger_words") or [])),- "recommended_strength": float(meta.get("recommended_strength") or 1.0),+ "recommended_strength": strength,"preview_url": meta.get("preview_url"),"base_model": (meta.get("base_model")or ("MiniMax H3" if lane == "h3" else "LTXV 2.3")),@@ -9736,6 +9835,18 @@ def live_preview_dir(job_id: str) -> Path:return STATE_DIR / "live" / _safe_job_id(job_id)+def live_preview_job_id(job: dict | None) -> str:+ """Whose preview folder the queue job's live preview is in right now.++ A One Shot renders its parts as child jobs (`<id>-p1`, `-p1r`, …), and+ each part's helper writes its preview under ITS id, while the queue — and+ so /status and Stop early — only knows the parent. The take runner+ publishes the active part as `preview_id` (LTX-09); every reader resolves+ through here, so an ordinary job (no preview_id) is unchanged."""+ job = job or {}+ return str(job.get("preview_id") or job.get("id") or "")++def _live_preview_params(job: dict, p: dict) -> dict:"""The three job-spec keys that turn the preview on, or {}.@@ -10465,11 +10576,34 @@ def h3_available() -> bool:return not h3_paths()["missing"]+def _h3_q8_shards_complete(d: Path) -> bool:+ """Every shard the pack's index names is on disk and non-empty.++ The docstring below always said "all shards"; the code asked for ANY+ `model-*.safetensors`, so a pack missing four of five shards unlocked H3,+ was dispatched, and hid the Build action that would have fixed it (Codex+ H3-04). The index is what h3_build_q8.sh checks too. A pack with no index+ predates it and keeps the old rule rather than being declared broken."""+ idx = d / "model.safetensors.index.json"+ if not idx.is_file():+ return any(d.glob("model-*.safetensors"))+ try:+ names = set((json.loads(idx.read_text(encoding="utf-8")).get("weight_map") or {}).values())+ except (OSError, ValueError, AttributeError):+ return False+ try:+ return bool(names) and all((d / n).is_file() and (d / n).stat().st_size > 0+ for n in names)+ except OSError:+ return False++def _h3_q8_dit_dir() -> Path | None:"""The quantized DiT pack, if present: config + quant recipe + all shards."""for root in _h3_model_roots():d = root / H3_DIT_Q8_DIRNAME- if (d / "config.json").is_file() and (d / "quant_config.json").is_file() and any(d.glob("model-*.safetensors")):+ if (d / "config.json").is_file() and (d / "quant_config.json").is_file() \+ and _h3_q8_shards_complete(d):return dreturn None@@ -10669,6 +10803,56 @@ def h3_ram_verdict() -> dict:_H3_FLAG_CACHE: dict[str, bool] = {}+def h3_reference_image_error(src: Path) -> str:+ """"" when H3 Image mode can read `src`, else the sentence to show.++ Two different faults used to share one sentence. A file PIL cannot parse+ is the user's to fix ("export it as a JPEG or PNG"). But a PANEL that+ cannot import PIL at all is a half-installed engine venv — fleet 4.15.2,+ one 128 GB Mac, six H3 Image renders in a row told to re-export a+ perfectly good picture ("The reference image can't be read+ (ModuleNotFoundError)") while its venv had no packages. That one is+ ENGINE_ENV_REPAIR's, and the word "venv" files it under venv_broken."""+ try:+ from PIL import Image as _PilImg+ except ImportError as exc:+ return (f"The engine venv is not usable: it cannot load Pillow "+ f"({exc.__class__.__name__}), so no image can be read. "+ + ENGINE_ENV_REPAIR)+ try:+ with _PilImg.open(src):+ pass+ except Exception as exc:+ return (f"The reference image can't be read ({exc.__class__.__name__}). "+ "Export it as a JPEG or PNG and try again.")+ return ""+++def h3_vae_fp16_decode() -> bool:+ """Should the H3 runner decode video in FP16? ON unless turned off.++ The ViT decoder's weights are FP16 in the compact checkpoint, but the+ runner hands it FLOAT32 latents and MLX promotes the arithmetic to float32.+ The runner's `--vae-dtype float16` (minimax-h3-mlx 6bbed80, or+ H3_VAE_DTYPE) runs it at the reference's FP16 autocast precision with the+ RMS/QK norms kept float32. Measured 2026-09-23 on a real 1152x640/124f+ latent: decode 105.1 s -> 90.2 s, peak 11.1 -> 8.0 GiB, PSNR 72.8 dB+ (max abs 0.33 in VAE units, so not bit-exact). The 4.16.0 release A/B+ through the panel (High 5 s Turbo, seed 42, 1024x576/124f): decode 90.1 s+ -> 77.4 s, peak 10.7 -> 9.5 GiB, no visible difference (RGB PSNR 42 dB+ measured through the two h264 exports, i.e. below the encoder's own+ noise), so the default flipped to on.++ `PHOSPHENE_H3_VAE_FP16=1|0` (Pinokio ENVIRONMENT) overrides the+ `h3_vae_fp16` setting either way."""+ forced = (os.environ.get("PHOSPHENE_H3_VAE_FP16") or "").strip().lower()+ if forced in ("1", "true", "yes", "on"):+ return True+ if forced in ("0", "false", "no", "off"):+ return False+ return bool(get_settings().get("h3_vae_fp16", True))++def _h3_runner_has_flag(flag: str) -> bool:"""Whether the INSTALLED runner accepts `flag`.@@ -11359,10 +11543,22 @@ def _h3_lora_import_name(filename: str) -> str:claiming `../../etc/x.safetensors` reduces to `x.safetensors` before thecharacter filter ever runs."""raw_name = Path(str(filename or "")).name- safe_name = re.sub(r"[^A-Za-z0-9._-]+", "_", raw_name).strip("._")- if not safe_name or not safe_name.lower().endswith(".safetensors"):+ # THE EXTENSION IS CHECKED ON THE ORIGINAL, THE STEM SANITISED ALONE.+ # Sanitising the whole name first turned `日本語.safetensors` into+ # `_.safetensors` and `.strip("._")` then ate the stem AND the dot, leaving+ # `safetensors` — refused as "wrong extension" (Codex H3-05). A stem with+ # nothing ASCII left gets a stable name derived from the original, so two+ # such files do not collide.+ if not raw_name.lower().endswith(".safetensors"):raise ValueError("choose a .safetensors H3 LoRA file")- return safe_name+ raw_stem = raw_name[: -len(".safetensors")]+ stem = re.sub(r"[^A-Za-z0-9._-]+", "_", raw_stem).strip("._")+ if not stem:+ if not raw_stem.strip():+ raise ValueError("choose a .safetensors H3 LoRA file")+ import hashlib+ stem = "lora_" + hashlib.sha1(raw_stem.encode("utf-8")).hexdigest()[:10]+ return stem + ".safetensors"def import_h3_lora_staged(filename: str, fill, *, size_hint: int = 0) -> dict:@@ -11888,6 +12084,30 @@ def _h3_lora_scale_report(path: Path, header: dict, buf_start: int) -> dict:f"ambiguous — starting at 1.0")}+def _h3_lora_browser_strength(path: Path, meta: dict, tag: str) -> float:+ """recommended_strength for an adapter installed from the HF / CivitAI browser.++ The upload importer always wrote the file's own alpha/rank scale into the+ sidecar; both browser installers wrote the listing's number or 1.0, and+ `_h3_lora_prepare` folds only MIXED ratios. So a uniform alpha 8 / rank 128+ adapter installed from a browser was recommended at 1.0 — 16x too strong,+ because the runner applies no alpha — while the same file uploaded got+ 0.0625 (Codex H3-01, 2026-09-24). A listing's own strength is the+ publisher's multiplier on an alpha-applying loader, so it multiplies the+ training scale rather than replacing it. Never refuses: a header this+ cannot read keeps the listing's number."""+ listed = float(meta.get("recommended_strength") or 1.0)+ try:+ header, buf_start = _safetensors_header(path)+ scale = _h3_lora_scale_report(path, header, buf_start)+ except Exception as exc: # noqa: BLE001+ push(f"[{tag}] could not read the adapter's scale: {exc}")+ return listed+ if scale.get("evidence"):+ push(f"[{tag}] {path.name}: {scale['evidence']}")+ return listed * float(scale["strength"])++def _h3_lora_validate_for_import(path: Path) -> dict:"""The extra scrutiny an UPLOADED adapter gets, on top of `_h3_lora_prepare`.@@ -12230,7 +12450,11 @@ def _h3_lora_migrate_strength(path: Path, strength: float, params: dict) -> floabefore = _h3_lora_migrate_sidecar(path)if before is None or not math.isclose(strength, before, abs_tol=1e-4):return strength- if params.get("h3_lora_scale_v"):+ try:+ _scale_v = int(params.get("h3_lora_scale_v") or 0)+ except (TypeError, ValueError):+ _scale_v = 0+ if _scale_v >= H3_LORA_SCALE_VERSION:push(f"[h3:lora] note: {path.name} is picked at {strength:g}, its old "f"recommended strength. The file now carries that scale itself and "f"reads as trained at 1.0 — {strength:g} renders it weaker.")@@ -13078,6 +13302,17 @@ MUSIC_SECONDS_PER_AUDIO_SECOND = {"draft": 0.43, "final": 0.93}MUSIC_ROOT = ROOT / Path(os.environ.get("LTX_MUSIC_ROOT", "yue2-mlx")).expanduser()MUSIC_MODELS = ROOT / Path(os.environ.get("LTX_MUSIC_MODELS", "mlx_models/yue2")).expanduser()MUSIC_RUNNER = ROOT / "scripts/music/yue2_run.py"+# The two transcription models that turn a real recording into a score. A+# SEPARATE, OPTIONAL ~2.8 GB beside the 10 GB music pack: writing a song from a+# prompt never touches them, and covering one cannot happen without them.+MUSIC_COVER_MODELS = ROOT / Path(+ os.environ.get("LTX_MUSIC_COVER_MODELS", "mlx_models/yue2-cover")).expanduser()+# The LoRA pack: ~210 MB of adapters, opt-in like the cover models. The+# Instrumental toggle upgrades itself the moment this is on disk (see+# scripts/music/yue2_lora.py), and `user/` inside it is scanned for anything+# the owner drops in — a community or AI-Toolkit adapter needs no install step.+MUSIC_LORAS = ROOT / Path(+ os.environ.get("LTX_MUSIC_LORAS", "mlx_models/yue2-loras")).expanduser()MUSIC_ENGINE_PIN = (ROOT / "scripts/music/engine_pin.txt").read_text().strip()# Env vars the music runner must NEVER inherit — see music_child_env().MUSIC_ENV_STRIP = ("PYTORCH_ENABLE_MPS_FALLBACK", "PYTORCH_MPS_FAST_MATH")@@ -13087,6 +13322,15 @@ MUSIC_ENV_STRIP = ("PYTORCH_ENABLE_MPS_FALLBACK", "PYTORCH_MPS_FAST_MATH")# is what makes a stale or raced lock impossible on this side.MUSIC_GPU_DIR_LOCK = Path.home() / "AI/projects/hailuo-mlx/.gpu_lock"MUSIC_GPU_FILE_LOCK = Path("/tmp/phosphene_gpu.lock")+# A music job WAITS for an external lock instead of refusing: the lab's command-line+# jobs hold these for minutes, and "Retry when it has finished" asked a person to+# poll by hand. The wait is capped, shows as its own phase, and Stop ends it.+MUSIC_GPU_WAIT_MAX_S = float(os.environ.get("PHOSPHENE_MUSIC_GPU_WAIT_S", "3600") or 3600)+MUSIC_GPU_POLL_S = 0.5+# Opt-in, off by default: a panel that shares the machine with command-line GPU+# jobs (a dev/test panel) can HOLD the file lock while a song renders, so those+# jobs queue behind it. A user's panel never writes the shared lock unless told to.+MUSIC_TAKES_GPU_LOCK = os.environ.get("PHOSPHENE_MUSIC_TAKES_GPU_LOCK", "") == "1"def _music_python() -> Path | None:@@ -13124,6 +13368,231 @@ def music_paths() -> dict:"repairable": weights_ok and bool(missing)}+MUSIC_ARTIFACTS = STATE_DIR / "music"+++def music_artifacts_dir(job_id: str) -> Path:+ """Where a job's plan/tokens/latents live. The runner insists on an empty+ folder, so a retried job id gets a fresh one rather than a refusal."""+ base = MUSIC_ARTIFACTS / _safe_job_id(job_id)+ d, n = base, 2+ while d.exists() and any(d.iterdir()):+ d = base.with_name(f"{base.name}_{n}")+ n += 1+ return d+++def music_artifacts_for(output_path: str | Path | None) -> Path | None:+ """The artifact folder a finished song was made with, or None.++ Read from the song's sidecar (the runner records `artifacts`), then+ checked for the one file that proves it is complete. Nothing is guessed+ from a filename — a song is varied from what it actually kept."""+ if not output_path:+ return None+ try:+ side = Path(str(output_path) + ".json")+ meta = json.loads(side.read_text())+ d = Path(str(meta.get("artifacts") or ""))+ return d if d.is_dir() and (d / "result.json").is_file() else None+ except (OSError, ValueError):+ return None+++def music_cover_status() -> dict:+ """Can this install cover a recording, and if not, what is missing.++ Kept separate from music_status()'s own readiness because the answers are+ independent: the music pack alone writes songs from prompts, and this pack+ alone is useless. The Compose card reads both."""+ try:+ from scripts.pinokio.music_cover_fetch import COVER_BYTES, cover_problems+ missing = cover_problems(MUSIC_COVER_MODELS)+ return {"ready": not missing, "missing": missing,+ "root": str(MUSIC_COVER_MODELS), "bytes": COVER_BYTES,+ # THE DOWNLOAD'S OWN STATE RIDES ON EVERY POLL (M6-09). It was+ # kept here and read by nothing: the card said "this runs in+ # the background" on the 202 and then, on the next status+ # tick, offered Download again — a failed fetch never said so.+ "fetch": music_cover_fetch_state()}+ except Exception as exc: # noqa: BLE001+ return {"ready": False, "missing": [str(exc)],+ "root": str(MUSIC_COVER_MODELS), "bytes": 0,+ "fetch": music_cover_fetch_state()}+++_MUSIC_COVER_FETCH = {"running": False, "line": "", "error": ""}+++def music_cover_fetch_state() -> dict:+ return dict(_MUSIC_COVER_FETCH)+++def music_cover_fetch_start() -> tuple[int, dict]:+ """Download the two transcription models in the background.++ Deliberately NOT part of MUSIC_INSTALL_STEPS: that sequence is the engine+ itself and a user who never covers anything should never pay for this. Two+ files, ~2.8 GB, resumable by construction — the fetcher keeps whatever is+ already on disk."""+ if _MUSIC_COVER_FETCH["running"]:+ return 409, {"error": "the cover models are already downloading"}+ if music_cover_status()["ready"]:+ return 200, {"ok": True, "ready": True}++ def run():+ _MUSIC_COVER_FETCH.update(running=True, line="starting", error="")+ try:+ python = _music_python() or sys.executable+ # TWO STEPS, and the first one is the easy thing to forget.+ # `lyra.transcription` imports mir_eval / mido / pretty_midi at+ # module import time, and the venv is built with `uv sync --frozen+ # --no-dev`, which installs no extras — so a venv that writes songs+ # perfectly raises ModuleNotFoundError the instant a cover starts.+ # Found by running one end to end, not by reading the manifest.+ steps = (+ ("the transcription libraries",+ ["bash", str(ROOT / "scripts/pinokio/music_cover_deps.sh"),+ str(MUSIC_ROOT)], _music_install_env()),+ ("the transcription models",+ [str(python), str(ROOT / "scripts/pinokio/music_cover_fetch.py"),+ "--root", str(MUSIC_COVER_MODELS)], music_child_env()),+ )+ rc = 0+ for label, cmd, env in steps:+ _MUSIC_COVER_FETCH["line"] = f"installing {label}"+ push(f"[cover] installing {label}")+ proc = subprocess.Popen(+ cmd, cwd=str(ROOT), env=env, stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT, text=True, errors="replace", bufsize=1)+ for line in proc.stdout or ():+ line = line.strip()+ if line:+ _MUSIC_COVER_FETCH["line"] = line[:200]+ push(line)+ rc = proc.wait()+ if rc != 0:+ _MUSIC_COVER_FETCH["error"] = f"{label} failed (exit {rc})"+ break+ except Exception as exc: # noqa: BLE001+ _MUSIC_COVER_FETCH["error"] = f"{type(exc).__name__}: {exc}"+ finally:+ _MUSIC_COVER_FETCH["running"] = False++ threading.Thread(target=run, name="music-cover-fetch", daemon=True).start()+ return 202, {"ok": True, "started": True}+++def music_lora_status() -> dict:+ """What the LoRA picker can offer, and what a download would cost.++ Two independent answers again: the pinned pack may be missing while the+ owner's own `user/` folder already holds adapters, and a user LoRA is+ usable on its own. `ready` means the two pinned ADAPTERS are usable;+ `adapters` is everything pickable right now.++ `complete` is the third answer and the one the Download button needs:+ whether anything is still left to fetch, the tokenizer head included. They+ were one answer, so a pack whose head never arrived — or whose adapter+ arrived truncated — was "ready" and could never be repaired from the UI+ (Codex review, 2026-09-22)."""+ try:+ from scripts.pinokio.music_lora_fetch import (LORA_BYTES, lora_problems,+ pack_adapters, pack_problems)+ missing = lora_problems(MUSIC_LORAS)+ incomplete = pack_problems(MUSIC_LORAS)+ adapters = pack_adapters(MUSIC_LORAS)+ return {"ready": not missing, "complete": not incomplete,+ "missing": missing, "incomplete": incomplete,+ "root": str(MUSIC_LORAS),+ "bytes": LORA_BYTES, "adapters": adapters,+ "instrumental_ready": any(a["instrumental"] for a in adapters),+ "fetch": music_lora_fetch_state()} # see music_cover_status+ except Exception as exc: # noqa: BLE001+ return {"ready": False, "complete": False, "missing": [str(exc)],+ "incomplete": [str(exc)], "root": str(MUSIC_LORAS),+ "bytes": 0, "adapters": [], "instrumental_ready": False,+ "fetch": music_lora_fetch_state()}+++_MUSIC_LORA_FETCH = {"running": False, "line": "", "error": ""}+++def music_lora_fetch_state() -> dict:+ return dict(_MUSIC_LORA_FETCH)+++def music_lora_fetch_start() -> tuple[int, dict]:+ """Download the two pinned adapters in the background (~210 MB).++ Same shape as the cover pack and for the same reason: it is not part of+ MUSIC_INSTALL_STEPS, because a user who never asks for an instrumental+ should never pay for it. Checksummed, so a half-written file from a+ dropped connection is replaced rather than trusted — and the gate below is+ `complete`, not `ready`: a run that stops after the adapters and before+ the tokenizer head has left work to do, and the button has to be able to+ finish it (Codex review, 2026-09-22). The fetcher skips every file that is+ already the pinned file, so pressing it again resumes rather than+ re-downloads."""+ if _MUSIC_LORA_FETCH["running"]:+ return 409, {"error": "the music LoRAs are already downloading"}+ if music_lora_status()["complete"]:+ return 200, {"ok": True, "ready": True}++ def run():+ _MUSIC_LORA_FETCH.update(running=True, line="starting", error="")+ try:+ python = _music_python() or sys.executable+ cmd = [str(python), str(ROOT / "scripts/pinokio/music_lora_fetch.py"),+ "--root", str(MUSIC_LORAS)]+ proc = subprocess.Popen(+ cmd, cwd=str(ROOT), env=music_child_env(), stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT, text=True, errors="replace", bufsize=1)+ for line in proc.stdout or ():+ line = line.strip()+ if line:+ _MUSIC_LORA_FETCH["line"] = line[:200]+ push(line)+ if proc.wait() != 0:+ _MUSIC_LORA_FETCH["error"] = f"the music LoRAs failed (exit {proc.returncode})"+ except Exception as exc: # noqa: BLE001+ _MUSIC_LORA_FETCH["error"] = f"{type(exc).__name__}: {exc}"+ finally:+ _MUSIC_LORA_FETCH["running"] = False++ threading.Thread(target=run, name="music-lora-fetch", daemon=True).start()+ return 202, {"ok": True, "started": True}+++def music_lora_picks(raw) -> list[dict]:+ """Form value -> [{id, strength, path}], with every pick resolved INSIDE+ the LoRA folder. A form can name a file; it can never name a path.++ `parse_field`, not `parse_picks`: `raw` comes straight off `parse_qs`,+ which wraps the studio's ONE comma-separated field in a list. Read as a+ list of specs, two picked adapters became one filename nobody has and+ both were dropped (Codex review, 2026-09-22). A job's own saved params+ arrive here too, already normalised, and `parse_field` passes those+ through unsplit."""+ try:+ from scripts.pinokio.music_lora_fetch import (adapter_meta, parse_field,+ resolve_in_pack)+ except Exception: # noqa: BLE001+ return []+ picks = []+ for identifier, strength in parse_field(raw):+ try:+ path = resolve_in_pack(MUSIC_LORAS, identifier)+ except (OSError, ValueError):+ continue # a pick we cannot resolve is simply not used+ # A TRAINED VOICE CARRIES ITS OWN INSTRUCTIONS (M6-04): the trigger the+ # runner adds to the style, and the dialect make_job holds the Score+ # setting to. Read from the adapter's sidecar, never from the form.+ picks.append({"id": identifier, "strength": strength, "path": str(path),+ **adapter_meta(path)})+ return picks++def music_estimate(quality: str, seconds: int) -> dict:"""A fit to the M4 Max receipts above, scaled by chip. Never a measurement:songs usually end before Max length, and cold first loads are unmeasured."""@@ -13137,6 +13606,8 @@ def music_status() -> dict:"weights_ok", "runner_ok", "venv_ok", "venv_broken")},"capable": music_capable(), "available": not paths["missing"],"installed": not paths["missing"], "min_ram_gb": MUSIC_MIN_RAM_GB,+ "cover": music_cover_status(),+ "loras": music_lora_status(),"eta_measured": False,"estimates": {q: {str(n): music_estimate(q, n) for n in range(30, 361, 15)}for q in MUSIC_QUALITY_STEPS}}@@ -13386,13 +13857,63 @@ def music_params(form: dict) -> dict:except (TypeError, ValueError):return defaultinstrumental = value("music_instrumental").lower() in ("1", "true", "yes", "on")+ lora_mode = value("music_lora_mode", "joint")quality = value("music_quality", "final")mode = value("music_mode", "full")+ cover_task = value("music_cover_task", "melody-full")+ source = normalize_pasted_path(value("music_source_audio"))+ variation = value("music_variation")+ task = value("music_task")+ precision = value("music_precision", "8bit")+ try:+ cfg = float(value("music_cfg_scale", "")) if value("music_cfg_scale") else None+ cfg = None if cfg is None or not (0.0 <= cfg <= 20.0) else cfg+ except ValueError:+ cfg = Nonereturn {"mode": "music", "engine": "music",+ # THE STUDIO'S LINEAGE FIELDS. `music_parent` is the output path of+ # the song this one comes from; `music_variation` says how:+ # take same score and words, a new performance+ # sound same performance, a new recording of it+ # restyle the saved score under new words or style+ # cover the tune read off a recording (music_source_audio)+ # score transcription only — no song+ # The worker turns the parent path into the artifact folder to+ # restart from; the form never names a state directory.+ "music_title": value("music_title")[:120],+ "music_parent": normalize_pasted_path(value("music_parent")),+ "music_variation": (variation if variation in+ ("take", "sound", "restyle", "score") else ""),+ "music_cfg_scale": cfg,+ "music_precision": precision if precision in ("bf16", "8bit", "4bit") else "8bit",+ # An EDITED score. The studio writes the user's ABC into the+ # artifacts tree and names it here; the worker refuses anything+ # outside that tree, so a form field can never point the runner+ # at an arbitrary file.+ "music_abc_path": normalize_pasted_path(value("music_abc_path")),+ # COVER. A path here changes the job's whole shape: the score comes+ # off a record instead of out of the planner, and the task decides+ # the planning mode (full transcription needs full planning). The+ # engine validates both again — this is the panel's copy of the+ # rule so a bad form never reaches a 10-minute job.+ "music_source_audio": source,+ "music_cover_task": (cover_task if cover_task in+ ("full", "melody-full", "melody-vocal") else "melody-full"),+ # The composer's TASK, as chosen — "" from a caller that predates+ # it (the variation routes, a replayed job). make_job refuses a+ # cover with no recording on this, not on the path alone.+ "music_task": task if task in ("write", "cover", "score") else "","music_lyrics": "" if instrumental else value("music_lyrics"),"music_style": value("music_style"),"music_mode": mode if mode in ("full", "melody", "off") else "full","music_instrumental": instrumental,+ # VOICE / STYLE LoRAs. The form posts `id:strength` pairs; every id+ # is resolved against the LoRA folder HERE, so a pick that is not a+ # file inside it simply does not exist by the time a job is built.+ # Instrumental pauses them, the way Maestro's does — its own AR+ # adapter is the recipe and a second AR delta would fight it.+ "music_loras": [] if instrumental else music_lora_picks(form.get("music_loras")),+ "music_lora_mode": (lora_mode if lora_mode in ("joint", "separate") else "joint"),"music_max_seconds": max(8, min(360, integer("music_max_seconds", 240))),"music_seed": max(-1, min(2**32 - 1, integer("music_seed", -1))),"music_quality": quality if quality in MUSIC_QUALITY_STEPS else "final"}@@ -13404,8 +13925,13 @@ def music_argv(job: dict, paths: dict, output: Path) -> list[str]:sources = json.loads((MUSIC_MODELS / "pack_source.json").read_text())["sources"]except (OSError, ValueError, KeyError):sources = {} # Manual packs have unknown provenance; never invent it.+ artifacts = music_artifacts_dir(job["id"])provenance = {"job_id": job["id"], "engine": "music", "engine_pin": MUSIC_ENGINE_PIN,- "pack_sources": sources, "params": p}+ "pack_sources": sources, "params": p,+ "artifacts": str(artifacts),+ # Lineage as the gallery reads it: which song, varied how.+ "lineage": ({"parent": p["music_parent"], "variation": p["music_variation"]}+ if p.get("music_parent") or p.get("music_variation") else None)}args = [str(paths["python"]), str(paths["runner"]),"--model-dir", str(paths["generator"]), "--vae-dir", str(paths["vae"]),"--output", str(output), "--sidecar", str(output) + ".json",@@ -13413,9 +13939,53 @@ def music_argv(job: dict, paths: dict, output: Path) -> list[str]:"--style", p["music_style"], "--lyrics", p["music_lyrics"],"--mode", p["music_mode"], "--steps", str(MUSIC_QUALITY_STEPS[p["music_quality"]]),"--max-seconds", str(p["music_max_seconds"]), "--seed", str(p["music_seed"]),- "--precision", "8bit"]+ "--precision", p.get("music_precision") or "8bit"]+ if p.get("music_title"):+ args += ["--title", p["music_title"]]+ if p.get("music_cfg_scale") is not None:+ args += ["--cfg-scale", str(p["music_cfg_scale"])]+ # Every song keeps its artifacts — plan, tokens, latents, noise — because+ # they are what every variation restarts from. One folder per job under+ # state/, never under the outputs the user sees. A song made before this+ # existed has no folder and the studio says so instead of failing.+ args += ["--artifacts", str(artifacts)]+ variation = p.get("music_variation") or ""+ parent_dir = music_artifacts_for(p.get("music_parent")) if p.get("music_parent") else None+ if variation in ("take", "sound"):+ if parent_dir is None:+ raise RuntimeError("That song has no saved artifacts to vary — songs made "+ "before v4.16 cannot be varied; compose it again first.")+ args += ["--from-artifacts", str(parent_dir), "--variation", variation]+ elif variation == "restyle":+ if parent_dir is None or not (parent_dir / "score.abc").is_file():+ raise RuntimeError("That song has no saved score to restyle.")+ args += ["--abc-file", str(parent_dir / "score.abc")]+ elif variation == "score":+ args.append("--transcribe-only")+ if p.get("music_abc_path") and not variation:+ abc_path = Path(p["music_abc_path"]).resolve()+ if not abc_path.is_relative_to(MUSIC_ARTIFACTS.resolve()) or not abc_path.is_file():+ raise RuntimeError("An edited score has to come from the studio's own editor.")+ args += ["--abc-file", str(abc_path)]if p["music_instrumental"]:args.append("--instrumental")+ # The LoRA folder always goes along: with --instrumental the runner reads+ # its AR adapter from there, and without it the flag is inert.+ args += ["--lora-dir", str(MUSIC_LORAS)]+ if p.get("music_loras"):+ args += ["--lora-mode", p.get("music_lora_mode") or "joint"]+ for pick in p["music_loras"]:+ args += ["--lora", f"{pick['path']}:{pick['strength']:g}"]+ # The runner pairs `--lora-trigger` with `--lora` BY POSITION, so once+ # any pick has a trigger every pick gets one ("" = none).+ if any(pick.get("trigger") for pick in p["music_loras"]):+ for pick in p["music_loras"]:+ args += ["--lora-trigger", str(pick.get("trigger") or "")]+ if p.get("music_source_audio"):+ args += ["--source-audio", p["music_source_audio"],+ "--cover-task", p["music_cover_task"],+ "--transcription-model", str(MUSIC_COVER_MODELS / "sheetsage2"),+ "--transcription-base-model", str(MUSIC_COVER_MODELS / "mert2")]return args@@ -13438,6 +14008,12 @@ def music_child_env(base: dict | None = None) -> dict:if k not in MUSIC_ENV_STRIP}env["PYTHONUNBUFFERED"] = "1"env["MLX_ENABLE_TF32"] = "0"+ # Cover decodes the source recording by SHELLING OUT TO ffmpeg+ # (lyra/transcription/pipeline.py builds an ffmpeg argv and reads f32le off+ # its stdout). Pinokio's bundled binary is not on the default PATH, which+ # is the same trap that cost five installs their exports in 4.15.1 — so the+ # music child gets the resolved one prepended, exactly like the H3 spawn.+ env["PATH"] = f"{FFMPEG_BIN}:{env.get('PATH', '')}"return env@@ -13511,6 +14087,55 @@ def _music_external_gpu_lock() -> Path | None:return None+def _music_wait_for_gpu(job: dict) -> str | None:+ """Wait until no external GPU lock is held, then return a release token.++ Never refuses while the wait is short: the job shows a "waiting for the GPU"+ phase naming the lock, Stop ends the wait, and only a wait past+ MUSIC_GPU_WAIT_MAX_S refuses (a lock nobody releases is usually stale).+ With MUSIC_TAKES_GPU_LOCK the file lock is then created atomically+ (O_EXCL) and the returned token lets the job remove ONLY its own lock;+ otherwise nothing is written and the token is None."""+ started = time.time()+ while True:+ held = _music_external_gpu_lock()+ if held is None and MUSIC_TAKES_GPU_LOCK:+ token = f"{os.getpid()} phosphene-panel-music {job.get('id', '')}\n"+ try:+ fd = os.open(str(MUSIC_GPU_FILE_LOCK), os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644)+ except FileExistsError:+ held = MUSIC_GPU_FILE_LOCK # lost the race to a command-line job; keep waiting+ else:+ with os.fdopen(fd, "w") as fh:+ fh.write(token)+ return token+ if held is None:+ return None+ if job.get("cancel_requested"):+ raise JobStopped("Music stopped")+ waited = time.time() - started+ if waited > MUSIC_GPU_WAIT_MAX_S:+ raise RenderRefused(+ "gpu_busy",+ f"The GPU was in use by another render for {waited / 60:.0f} min (lock {held}). "+ f"If nothing is rendering, that lock was left behind by a command-line job — delete it and retry.")+ with LOCK:+ job["progress"] = {"phase": "waiting", "pct": 0, "elapsed_sec": waited,+ "phase_label": f"Waiting for the GPU — another render holds {held.name}"}+ time.sleep(MUSIC_GPU_POLL_S)+++def _music_release_gpu(token: str | None) -> None:+ """Remove the file lock only if it is still the one this job wrote."""+ if not token:+ return+ try:+ if MUSIC_GPU_FILE_LOCK.read_text(errors="replace") == token:+ MUSIC_GPU_FILE_LOCK.unlink()+ except OSError:+ pass++def _stop_music_proc(grace: float = 8.0, pgid: int | None = None) -> None:"""SIGTERM a music runner group, SIGKILL it after `grace` if it is still thecurrent one. Callers that decided to stop a SPECIFIC job pass its pgid, read@@ -13553,14 +14178,15 @@ def run_music_job_inner(job: dict) -> None:if paths["repairable"]:raise RuntimeError(f"The YuE2 weights are on disk but the engine needs repair — missing: {missing}. Open Audio → Compose and click 'Repair music engine' (or use the Phosphene sidebar in Pinokio) — it is idempotent and skips every weight already on disk, so this is a couple of minutes, NOT an 11 GB download.")raise RuntimeError(f"The music engine isn't installed — missing: {missing}. Open Audio → Compose and click 'Install music engine' (or use the Phosphene sidebar in Pinokio) — ~11 GB, resumable.")- if not p["music_style"] and not p["music_lyrics"] and not p["music_instrumental"]:+ if (not p["music_style"] and not p["music_lyrics"] and not p["music_instrumental"]+ and p["music_variation"] not in ("take", "sound", "score")):raise RenderRefused("music_input", "Give it something to work with — lyrics, a style description, or both.")- held = _music_external_gpu_lock()- if held is not None:- raise RenderRefused(- "gpu_busy",- f"The GPU is in use by another render (lock {held}). Retry music when it has finished. "- f"If nothing is rendering, that lock was left behind by a command-line job — delete it and retry.")+ if p["music_variation"] == "score" and not p["music_source_audio"]:+ raise RenderRefused("music_input", "Getting the score needs a recording to listen to.")+ if p["music_source_audio"] and not music_cover_status()["ready"]:+ raise RenderRefused("pack_missing", "Covering a song needs the two transcription models "+ "(~2.8 GB). Download them from Music Studio - Cover a song.")+ gpu_token = _music_wait_for_gpu(job)proc = Noneoutput = Nonetry:@@ -13569,8 +14195,22 @@ def run_music_job_inner(job: dict) -> None:if job.get("cancel_requested"):raise JobStopped("Music stopped")OUTPUT.mkdir(parents=True, exist_ok=True)- slug = _sb_slug(p["music_style"] or p["music_lyrics"] or "instrumental")- output = _unique_output_path(OUTPUT, f"music_{time.strftime('%Y%m%d_%H%M%S')}_{slug}", ext=".wav")+ variation = p.get("music_variation") or ""+ parent = Path(p["music_parent"]) if p.get("music_parent") else None+ if variation == "score":+ # A transcription is not a song: it lives beside the artifacts, out+ # of the gallery, and the studio fetches it by job id.+ scores = MUSIC_ARTIFACTS / "scores"+ scores.mkdir(parents=True, exist_ok=True)+ slug = _sb_slug(Path(p["music_source_audio"]).stem)+ output = _unique_output_path(scores, f"score_{time.strftime('%Y%m%d_%H%M%S')}_{slug}", ext=".abc")+ elif variation and parent is not None:+ # "<parent>_take", "<parent>_sound", "<parent>_restyle": the family+ # reads off the filenames, and the sidecar carries the exact link.+ output = _unique_output_path(OUTPUT, f"{parent.stem}_{variation}", ext=".wav")+ else:+ slug = _sb_slug(p["music_title"] or p["music_style"] or p["music_lyrics"] or "instrumental")+ output = _unique_output_path(OUTPUT, f"music_{time.strftime('%Y%m%d_%H%M%S')}_{slug}", ext=".wav")job["raw_path"] = str(output)cmd = music_argv(job, paths, output)job["command"] = shlex.join(cmd)@@ -13597,10 +14237,14 @@ def run_music_job_inner(job: dict) -> None:if parsed:progress = parsedelapsed = time.time() - t0- parsed.update(elapsed_sec=elapsed,- eta_sec=music_estimate(p["music_quality"], p["music_max_seconds"])["eta_sec"],- remaining_sec=max(0, music_estimate(p["music_quality"], p["music_max_seconds"])["eta_sec"] - elapsed),- eta_measured=False)+ # A re-recording skips planning and the whole semantic stage —+ # the NAR and the decoder are roughly a third of a song's time.+ # A take skips only the planning. Scale the whole-song estimate+ # rather than inventing a second table.+ _eta_scale = {"sound": 0.35, "take": 0.9}.get(p.get("music_variation") or "", 1.0)+ _eta = music_estimate(p["music_quality"], p["music_max_seconds"])["eta_sec"] * _eta_scale+ parsed.update(elapsed_sec=elapsed, eta_sec=_eta,+ remaining_sec=max(0, _eta - elapsed), eta_measured=False)with LOCK:job["progress"] = parsedrc = proc.wait()@@ -13617,7 +14261,8 @@ def run_music_job_inner(job: dict) -> None:if rc != 0:raise RuntimeError(f"YuE2 exited with code {rc}: " + " · ".join(tail))if not output.is_file() or not Path(str(output) + ".json").is_file():- raise RuntimeError("YuE2 finished without the WAV and its sidecar. See the log.")+ what = "the score" if variation == "score" else "the WAV"+ raise RuntimeError(f"YuE2 finished without {what} and its sidecar. See the log.")job["output_path"] = str(output)finally:if proc is not None:@@ -13636,6 +14281,7 @@ def run_music_job_inner(job: dict) -> None:STATE["pid"] = NoneSTATE["music_pgid"] = None_proc_guard_clear("music")+ _music_release_gpu(gpu_token)ENGINE_DEFAULT = "ltx"@@ -14581,7 +15227,11 @@ def _analytics_job_secrets(job: dict) -> list:out = []for k in ("prompt", "negative_prompt", "image", "audio", "output","first_frame", "last_frame", "character", "train_job_id",- "music_lyrics", "music_style"):+ "music_lyrics", "music_style",+ # A cover's source recording and a song's parent are the user's+ # file names; the path regex strips the directory and left the+ # basename standing ("<path> unreleased demo.wav" — Codex).+ "music_source_audio", "music_parent", "music_abc_path"):v = p.get(k)if isinstance(v, str) and v.strip():out.append(v.strip())@@ -14589,7 +15239,46 @@ def _analytics_job_secrets(job: dict) -> list:v = (job or {}).get(k)if isinstance(v, str) and v.strip():out.append(v.strip())- return out+ # EVERY PATH-SHAPED STRING, WHEREVER IT SITS (Codex UI-02, 2026-09-24). The+ # scalar list above missed the image job's `refs` array, LoRA stacks and any+ # future list field; and the path regex stops at whitespace, so+ # "ref image not found: /Volumes/Photos/Private Client Portrait.png" went+ # out as "<path> Client Portrait.png". Each path is redacted whole, as its+ # resolved form, and as its bare filename (errors often quote only that).+ def _paths(v, depth=0):+ if depth > 4:+ return+ if isinstance(v, str):+ t = v.strip()+ if t and ("/" in t or "\\" in t):+ out.append(t)+ name = Path(t).name+ if name:+ out.append(name)+ try:+ out.append(str(Path(t).expanduser().resolve()))+ except (OSError, RuntimeError, ValueError):+ pass+ elif isinstance(v, dict):+ for x in v.values():+ _paths(x, depth + 1)+ elif isinstance(v, (list, tuple)):+ for x in v:+ _paths(x, depth + 1)+ _paths(p)+ # The install's own roots: a space anywhere in them ("…/My Apps/…") also+ # stops the path regex half-way, leaving the tail of the directory behind.+ # Only those — a root without whitespace is already caught by the regex,+ # and redacting it here would re-key every fleet fingerprint that quotes it.+ for base in (ROOT, OUTPUT, UPLOADS, STATE_DIR):+ try:+ for cand in (str(base), str(Path(base).resolve())):+ if any(ch.isspace() for ch in cand):+ out.append(cand)+ except (OSError, RuntimeError, ValueError):+ pass+ # Longest first, so a whole path is redacted before its own filename is.+ return sorted({x for x in out if x}, key=len, reverse=True)# ---- Schema v2 render-event vocabulary (spec: analytics_spec_2026-08-11) ---@@ -15592,17 +16281,6 @@ def _usage_report(force: bool = False) -> dict:return _usage_attach_local(local)-def _scale_dims_to_max(width: int, height: int, max_dim: int,- *, align: int = 32) -> tuple[int, int]:- """Scale dimensions down to max_dim while preserving aspect and alignment."""- if max_dim <= 0 or max(width, height) <= max_dim:- return width, height- scale = max_dim / float(max(width, height))- new_w = max(align, int(round((width * scale) / align)) * align)- new_h = max(align, int(round((height * scale) / align)) * align)- return new_w, new_h--def _apply_generation_profile_to_job(job: dict) -> None:"""Clamp new video jobs for the active generation profile.@@ -15643,7 +16321,8 @@ def _apply_generation_profile_to_job(job: dict) -> None:# tier is still an HQ tier.if not ltx_quality_uses_hq(quality):max_dim = int(profile.get("max_dim") or 0)- new_w, new_h = _scale_dims_to_max(width, height, max_dim)+ new_w, new_h = (ltx_fit_canvas(width, height, max_dim)+ if max_dim and max(width, height) > max_dim else (width, height))if (new_w, new_h) != (width, height):params["width"], params["height"] = new_w, new_hnew_notes.append(f"resolution {width}x{height} -> {new_w}x{new_h}")@@ -16312,6 +16991,12 @@ def list_uploads(limit: int = 40) -> list[dict]:try:if not p.is_file() or p.suffix.lower() not in exts:continue+ # Dot-files are the panel's own: H3 writes a fitted first frame per+ # job as `.h3_<job>_firstframe_<w>x<h>.png`. Listed, 24 H3 renders+ # pushed every real upload out of this strip, and picking one of+ # them re-used an already-cropped frame (Codex H3-06).+ if p.name.startswith("."):+ continuefiles.append((p, p.stat().st_mtime, p.stat().st_size))except OSError:continue@@ -16338,6 +17023,15 @@ def _output_search_text(meta: dict, params: dict) -> str:"""The searchable words of one output, lower-cased, space-joined."""bits: list[str] = []try:+ # TWO SIDECAR SHAPES. Video sidecars nest the recipe under `params`;+ # Image Studio's write prompt / seed / width / height at the TOP level+ # and often no params at all — so an image could not be found by its+ # own prompt, seed or size (Codex UI-07). Top-level fields fill in+ # whatever params does not carry; params wins where both exist.+ params = dict(params or {})+ for k in ("prompt", "seed", "seed_used", "width", "height", "mode", "label"):+ if params.get(k) in (None, "", [], {}) and meta.get(k) not in (None, "", [], {}):+ params[k] = meta.get(k)for k in ("prompt", "label", "preset_label", "mode", "quality", "engine","character_id", "trigger", "seed", "seed_used", "h3_tier"):v = params.get(k)@@ -16575,6 +17269,7 @@ def list_outputs(# every clip that isn't part of a storyboard, which is most of them.sb_tag = Nonesearch = ""+ music_meta = Nonesidecar = p.with_suffix(p.suffix + ".json")has_sidecar = sidecar.exists()if has_sidecar:@@ -16585,6 +17280,36 @@ def list_outputs(elapsed_sec = float(v)if p.suffix.lower() == ".wav":clip_sec = meta.get("audio_seconds")+ if meta.get("engine") == "music":+ # What the Song card needs without a second request:+ # the family link, whether a variation is possible+ # (artifacts kept), and whether there is sheet music+ # to draw. The score text itself is fetched on demand.+ _lin = meta.get("lineage") if isinstance(meta.get("lineage"), dict) else {}+ _art = str(meta.get("artifacts") or "")+ music_meta = {+ "title": meta.get("title") or "",+ "style": meta.get("style") or "",+ "instrumental": bool(meta.get("instrumental")),+ "mode": meta.get("mode"),+ "seed": meta.get("seed"),+ "variation": (meta.get("variation") or {}).get("kind")+ if isinstance(meta.get("variation"), dict) else+ (_lin.get("variation") or None),+ "parent": _lin.get("parent") or None,+ "cover": bool(meta.get("cover")),+ "has_score": bool(meta.get("score_abc")),+ "has_artifacts": bool(_art) and (Path(_art) / "result.json").is_file(),+ "ended_naturally": meta.get("ended_naturally"),+ # Which adapters made this song, for the card's+ # badge. Names and strengths only — the list is+ # rebuilt per output on every gallery poll.+ "loras": [{"name": a.get("file"), "strength": a.get("strength")}+ for a in ((meta.get("lora") or {}).get("adapters") or [])+ if isinstance(a, dict)],+ "instrumental_recipe": (meta.get("instrumental_recipe") or {}).get("recipe")+ if isinstance(meta.get("instrumental_recipe"), dict) else None,+ }_sc_params = meta.get("params")if not isinstance(_sc_params, dict):_sc_params = {}@@ -16671,6 +17396,8 @@ def list_outputs(# back to the film it belongs to — and invisible for every clip# that isn't part of one."sb": sb_tag,+ # Music Studio's song facts, None for everything that is not a song.+ "music": music_meta,"hidden": is_hidden,# 'kind' lets the right-pane viewer + filter chips branch# without re-parsing the filename. Mirrors isPhotoOutput() on@@ -16694,15 +17421,81 @@ def list_outputs(return sliced-def write_sidecar(path: Path, payload: dict) -> None:+SIDECAR_WARNING = ("The clip was saved, but its settings record ({name}) could not "+ "be written: {exc}. Load Params, Finish and re-render need it. "+ "Free some disk space — the panel writes it again before the "+ "next render starts, without rendering anything.")+++def write_sidecar(path: Path, payload: dict) -> bool:+ """Write a clip's sidecar. Returns False when it could not be written.++ A FAILED WRITE USED TO BE A LOG LINE. Every caller goes straight on to+ publish the clip, the worker files the job as done, and the log is wiped+ when the next job starts — so a full disk produced a "done" render with+ no prompt/seed/settings record and nothing on screen saying so, and Load+ Params / Finish on it failed later with no explanation. The failure now+ lands on the queue job as a `warning` (the history row shows it) and the+ payload is kept on the job, so retry_pending_sidecars() can write it once+ there is space again — the video itself is never re-rendered for it."""try:atomic_write_text(path, json.dumps(payload, indent=2))+ return Trueexcept Exception as exc:push(f"Sidecar write failed: {exc}")+ job = _thread_job()+ if job is not None:+ with LOCK:+ job["warning"] = SIDECAR_WARNING.format(name=Path(path).name, exc=exc)+ # Only a filesystem failure is worth retrying, and only a+ # payload that serializes can ride in the persisted queue.+ if isinstance(exc, OSError):+ job.setdefault("sidecar_pending", []).append(+ {"path": str(path), "payload": payload})+ return False+++def retry_pending_sidecars() -> int:+ """Write the sidecars a full disk kept from finished jobs. Returns how+ many landed. Never raises; a job whose writes all succeed loses its+ sidecar warning."""+ with LOCK:+ jobs = [j for j in STATE["history"] if j.get("sidecar_pending")]+ written = 0+ for job in jobs:+ left = []+ for item in list(job.get("sidecar_pending") or []):+ try:+ atomic_write_text(Path(item["path"]), json.dumps(item["payload"], indent=2))+ written += 1+ except Exception: # noqa: BLE001+ left.append(item)+ with LOCK:+ if left:+ job["sidecar_pending"] = left+ else:+ job.pop("sidecar_pending", None)+ if str(job.get("warning") or "").startswith(SIDECAR_WARNING[:30]):+ job.pop("warning", None)+ if written:+ push(f"Wrote {written} settings record(s) the disk had no room for earlier.")+ return written# ---- queue persistence -------------------------------------------------------+# LAST WRITER WINS WAS THE WRONG RULE. Two callers (a route adding a job, the+# worker finishing one) could each snapshot under LOCK and then race to the+# write, so an OLDER snapshot could replace a newer one: an acknowledged job+# vanished at the next restart, or a finished one came back and rendered+# again. atomic_write_text stops a torn file, not a stale one. Each snapshot+# now takes a sequence number under LOCK, and the write is skipped when a+# newer one has already landed. The persist lock is never held while waiting+# for LOCK, so a caller that persists from inside LOCK cannot deadlock it.+_QUEUE_PERSIST_LOCK = threading.Lock()+_QUEUE_PERSIST_SEQ = {"taken": 0, "written": 0}++def persist_queue() -> None:with LOCK:snapshot = {@@ -16711,10 +17504,23 @@ def persist_queue() -> None:"history": [_strip_for_disk(j) for j in STATE["history"][:HISTORY_PERSIST_LIMIT]],"paused": STATE["paused"],}- try:- atomic_write_text(QUEUE_FILE, json.dumps(snapshot, indent=2))- except Exception as exc:- push(f"Queue persist failed: {exc}")+ # Serialized here too: the job dicts are shallow copies, and their+ # nested params can still be mutated once LOCK is released.+ try:+ text = json.dumps(snapshot, indent=2)+ except Exception as exc: # noqa: BLE001+ push(f"Queue persist failed: {exc}")+ return+ _QUEUE_PERSIST_SEQ["taken"] += 1+ seq = _QUEUE_PERSIST_SEQ["taken"]+ with _QUEUE_PERSIST_LOCK:+ if seq < _QUEUE_PERSIST_SEQ["written"]:+ return+ try:+ atomic_write_text(QUEUE_FILE, text)+ _QUEUE_PERSIST_SEQ["written"] = seq+ except Exception as exc:+ push(f"Queue persist failed: {exc}")def _strip_for_disk(job: dict) -> dict:@@ -16923,36 +17729,49 @@ class WarmHelper:# so _read_until's line buffer starts clean for this process.self._read_carry = b""self._boot_tail.clear()- ready = self._read_until(["ready", "error", "exit"], timeout=120,- collect_tail=self._boot_tail)- if not ready or ready.get("event") != "ready":- raise RuntimeError(_helper_start_failure(ready, self._boot_tail))- # v3.0.7 (P2): keep the version + model fields for /status.- self.ready_info = {- k: ready.get(k) for k in (- "ltx_version", "ltx_version_expected", "ltx_version_match",- "model", "gemma", "low_memory", "low_ram_stream",- "mlx_version", "mlx_metal_version", "chip", "macos",- # THIS ALLOWLIST IS THE SEAM. A key the helper emits and- # this tuple does not name is dropped here, silently, and- # every downstream reader sees None — which is exactly how- # a capability the helper knew about never reached the UI.- "live_preview_supported",- "gemma4_tower_supported",- )- }- _vtag = ""- if ready.get("ltx_version") is not None:- _vtag = (f" · ltx-2-mlx={ready.get('ltx_version')}"- + ("" if ready.get("ltx_version_match") else " SKEW"))- # Self-documenting env on the ready line — mlx + chip are the data we- # need on mosaic / garbled-output reports (an MLX numerical bug per- # chip/mlx, not a crash). ASCII only (emoji here can break stdout).- _env = (f" · mlx={ready.get('mlx_version')}" if ready.get("mlx_version") else "")- if ready.get("chip"):- _env += f" · {ready.get('chip')}"- push(f"helper ready · model={ready.get('model')} · "- f"low_memory={ready.get('low_memory')}{_vtag}{_env}")+ proc = self.proc+ # THE HANDSHAKE RUNS OUTSIDE self.lock. It can take the full 120 s on a+ # slow or stalled start, and kill() needs this lock to send its signal,+ # so Stop pressed while the first render's helper was still importing+ # blocked behind it for up to two minutes (JOB-08). run_lock (held by+ # our caller) still serializes starts; a kill() that lands now closes+ # the pipe, the read returns, and the identity check below refuses the+ # helper it no longer owns.+ ready = self._read_until(["ready", "error", "exit"], timeout=120,+ collect_tail=self._boot_tail)+ with self.lock:+ stopped = self.proc is not proc # kill() cleared it+ if stopped:+ _raise_if_cancelled(_thread_job(), "the helper finished starting")+ raise RuntimeError("the warm helper was stopped while it was starting")+ if not ready or ready.get("event") != "ready":+ raise RuntimeError(_helper_start_failure(ready, self._boot_tail))+ # v3.0.7 (P2): keep the version + model fields for /status.+ self.ready_info = {+ k: ready.get(k) for k in (+ "ltx_version", "ltx_version_expected", "ltx_version_match",+ "model", "gemma", "low_memory", "low_ram_stream",+ "mlx_version", "mlx_metal_version", "chip", "macos",+ # THIS ALLOWLIST IS THE SEAM. A key the helper emits and+ # this tuple does not name is dropped here, silently, and+ # every downstream reader sees None — which is exactly how+ # a capability the helper knew about never reached the UI.+ "live_preview_supported",+ "gemma4_tower_supported",+ )+ }+ _vtag = ""+ if ready.get("ltx_version") is not None:+ _vtag = (f" · ltx-2-mlx={ready.get('ltx_version')}"+ + ("" if ready.get("ltx_version_match") else " SKEW"))+ # Self-documenting env on the ready line — mlx + chip are the data we+ # need on mosaic / garbled-output reports (an MLX numerical bug per+ # chip/mlx, not a crash). ASCII only (emoji here can break stdout).+ _env = (f" · mlx={ready.get('mlx_version')}" if ready.get("mlx_version") else "")+ if ready.get("chip"):+ _env += f" · {ready.get('chip')}"+ push(f"helper ready · model={ready.get('model')} · "+ f"low_memory={ready.get('low_memory')}{_vtag}{_env}")def _read_until(self, target_events: list[str], timeout: float | None = None,log_hook: callable | None = None,@@ -17857,6 +18676,15 @@ def _raise_if_cancelled(job: dict | None, before: str) -> None:raise JobCancelled(f"Stopped before {before}.")+def _image_job_cancelled() -> bool:+ """image_engine's cancellation hook: Stop was pressed for the queue job+ this thread runs. Inline /image/generate runs outside the queue -> False."""+ return _cancel_requested(_thread_job())+++agent_image_engine._CANCEL_CHECK = _image_job_cancelled++def _register_job_pgid(key: str, pgid: int, job: dict | None = None) -> None:"""Publish a freshly spawned process group where Stop looks for it.@@ -18945,6 +19773,18 @@ def _sb_reconcile(board: dict) -> bool:for s in (board.get("shots") or []):if not isinstance(s, dict):continue+ # A CUT IS THE USER'S, NOT THE QUEUE'S (SB5-10). `status: "skipped"`+ # is what scheduling and export read, and the queue history still+ # holds the finished draft job of a shot cut after it rendered — so+ # every poll turned the cut shot back into "done", and it returned to+ # the delivery pass and the exported film with its grade still+ # reading Cut. Outputs still fold (a job that lands after the cut is+ # kept for an un-cut); the status never moves off "skipped", and a+ # board an earlier build already revived is put back.+ cut = s.get("status") == "skipped" or s.get("grade") == "cut"+ if cut and s.get("status") != "skipped":+ s["status"] = "skipped"+ changed = Truefor key, out_key in (("draft_job_id", "draft_output"),("final_job_id", "final_output")):jid = s.get(key)@@ -18961,6 +19801,8 @@ def _sb_reconcile(board: dict) -> bool:if s.get(out_key) != job["output_path"]:s[out_key] = job["output_path"]changed = True+ if cut:+ continueif s.get("status") != "done":s["status"] = "done"s["error"] = None@@ -18970,6 +19812,8 @@ def _sb_reconcile(board: dict) -> bool:if isinstance(seed, int):s["seed"] = seedchanged = True+ elif cut:+ continueelif st in ("failed", "error", "cancelled"):if s.get("status") != "failed":s["status"] = "failed"@@ -19005,7 +19849,7 @@ def _sb_reconcile(board: dict) -> bool:s["still_error"] = (job or {}).get("error") or "the still could not be made"changed = Truefj = s.get("final_job_id")- if fj and not s.get("final_output"):+ if fj and not s.get("final_output") and not cut:fst = ((idx.get(fj) or {}).get("status") or "").lower()if fst in ("queued", "running"):want = "rendering" if fst == "running" else "queued"@@ -19015,6 +19859,19 @@ def _sb_reconcile(board: dict) -> bool:return changed+def _sb_new_id(seed: str = "") -> str:+ """A fresh board id: `sb_<date>_<6 hex>`.++ ONE minter, because the shape is a prefix `_sb_all_summaries`, the board+ folder and the `sb:<id>#<n>` session tag all read, and it was written out+ twice with different seeds. `seed` only stirs the hash — the collision+ guard is the clock, not the concept.+ """+ return "sb_%s_%s" % (+ time.strftime("%Y%m%d"),+ hashlib.sha1((str(seed) + str(time.time())).encode()).hexdigest()[:6])++def _sb_normalize(board: dict) -> dict:"""Make a board internally consistent before it is validated or saved.@@ -19935,6 +20792,14 @@ def _sb_render_thread(board_id: str, pass_name: str, only: list | None) -> None:key = "draft_job_id" if pass_name == "draft" else "final_job_id"out_key = "draft_output" if pass_name == "draft" else "final_output"queued_total = 0+ # ONE ATTEMPT PER SHOT PER RENDER (SB5-08). A shot whose job could not be+ # queued, or whose job failed, is still "pending" by every test below —+ # it has no output — so it was chosen again on the very next round: an+ # enqueue refusal became a tight loop rewriting the board and the log,+ # and a failing engine re-spent the render indefinitely while every later+ # bucket waited. It stays failed, with its error on the card, until the+ # user presses Render (or Retry) again, which is a new run.+ attempted: set = set()try:while True:with _SB_LOCK:@@ -19956,6 +20821,7 @@ def _sb_render_thread(board_id: str, pass_name: str, only: list | None) -> None:# A shot already carrying a live job id for this pass is in flight.pending = [s for s in pendingif s.get("status") not in ("queued", "rendering") or not s.get(key)]+ pending = [s for s in pending if s.get("n") not in attempted]if not pending:break@@ -19977,6 +20843,10 @@ def _sb_render_thread(board_id: str, pass_name: str, only: list | None) -> None:if need:sids = []for shot in need:+ # Stop can land while this loop runs: queue nothing+ # more once it has (SB5-09).+ if _sb_stopping(board_id):+ breaktry: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()})@@ -19987,6 +20857,15 @@ def _sb_render_thread(board_id: str, pass_name: str, only: list | None) -> None:continueshot["still_job_id"] = jidsids.append(jid)+ if sids and _sb_stopping(board_id):+ # Stop read the board before these ids were saved, so+ # it could not withdraw them: this thread does.+ _sb_withdraw_jobs(sids)+ for shot in need:+ if shot.get("still_job_id") in sids:+ shot.pop("still_job_id", None)+ storyboard.save_storyboard(STATE_DIR, board)+ returnstoryboard.save_storyboard(STATE_DIR, board)if sids:push(f"[storyboard] {len(sids)} anchor still(s) queued — {board.get('title')}")@@ -20015,6 +20894,9 @@ def _sb_render_thread(board_id: str, pass_name: str, only: list | None) -> None:chain_ok = Falseids = []for shot in batch:+ if _sb_stopping(board_id):+ break+ attempted.add(shot.get("n"))form = storyboard.shot_to_job(shot, policy,board_id=board_id, board_title=board.get("title") or "",@@ -20041,6 +20923,16 @@ def _sb_render_thread(board_id: str, pass_name: str, only: list | None) -> None:shot["error"] = Noneids.append(jid)queued_total += 1+ if ids and _sb_stopping(board_id):+ # Same race as the stills: these ids were never on disk for+ # Stop to find.+ _sb_withdraw_jobs(ids)+ for shot in batch:+ if shot.get(key) in ids:+ shot.pop(key, None)+ shot["status"] = "pending"+ storyboard.save_storyboard(STATE_DIR, board)+ returnstoryboard.save_storyboard(STATE_DIR, board)with _SB_LOCK:entry = _SB_RENDERS.get(board_id)@@ -20082,6 +20974,20 @@ def _sb_render_thread(board_id: str, pass_name: str, only: list | None) -> None:_sb_lipsync_gate(board_id, batch, key, out_key, policy, h3_ok, chain_ok, _wait)except Exception as exc: # noqa: BLE001push(f"[storyboard] lip-sync gate skipped: {type(exc).__name__}: {exc}")+ # The run is over. Say which shots it could not make, in the words+ # the card uses, rather than going round again.+ try:+ _fb = storyboard.load_storyboard(STATE_DIR, board_id)+ failed = [s for s in (_fb.get("shots") or [])+ if isinstance(s, dict) and s.get("n") in attempted+ and s.get("status") == "failed"]+ if failed:+ push(f"[storyboard] {len(failed)} shot(s) failed and were not "+ f"retried ({', '.join('S%02d' % (s.get('n') or 0) for s in failed)})"+ f" — fix the cause and press Render again: "+ f"{(failed[0].get('error') or 'no error recorded')[:160]}")+ except Exception: # noqa: BLE001+ passexcept Exception as exc: # noqa: BLE001push(f"[storyboard] render dispatch stopped: {exc}")finally:@@ -20161,6 +21067,32 @@ def _sb_auto_film(board: dict) -> dict | None:return film+def _sb_stopping(board_id: str) -> bool:+ """Has Stop been pressed on this film's render (or has it gone away)?"""+ with _SB_LOCK:+ entry = _SB_RENDERS.get(board_id)+ return not entry or bool(entry.get("stop"))+++def _sb_withdraw_jobs(job_ids) -> tuple[int, str | None]:+ """Take this film's jobs back out of the queue, and cancel the one running.++ ONLY these ids — through the same path removeJob(id) uses, never+ /queue/clear, because another feature's jobs may be in there. Returns+ (how many were removed from the queue, the id of the cancelled job).+ """+ mine = {j for j in (job_ids or ()) if j}+ if not mine:+ return 0, None+ with QUEUE_COND:+ before = len(STATE["queue"])+ STATE["queue"] = [j for j in STATE["queue"] if j.get("id") not in mine]+ removed = before - len(STATE["queue"])+ QUEUE_COND.notify_all()+ persist_queue()+ return removed, _sb_cancel_running_shot(mine)++def _sb_cancel_running_shot(job_ids) -> str | None:"""Cancel the in-flight render IF it is one of this film's shots.@@ -20279,18 +21211,126 @@ def _sb_slug(text: str, words: int = 5) -> str:return "-".join(parts[:words]) or "shot"+#: The file that says which board a film folder belongs to.+_SB_FILM_OWNER = ".phosphene-board"+++def _sb_film_base(board: dict) -> str:+ """`<created-date>_<slug>` — the folder name this function used to BE."""+ title = board.get("title") or "storyboard"+ day = time.strftime("%Y-%m-%d",+ time.localtime(board.get("created_at") or time.time()))+ return f"{day}_{_sb_slug(title, 6)}"+++def _sb_film_owner(d: Path) -> str | None:+ """Which board a film folder says it belongs to, or None if it says nothing.++ The marker first (written by every film written since 4.16), then the+ `storyboard.json` an Export has always dropped beside its films.+ """+ try:+ v = (Path(d) / _SB_FILM_OWNER).read_text(encoding="utf-8").strip()+ if v:+ return v+ except OSError:+ pass+ try:+ data = json.loads((Path(d) / "storyboard.json").read_text(encoding="utf-8"))+ v = str((data or {}).get("id") or "").strip() if isinstance(data, dict) else ""+ if v:+ return v+ except (OSError, ValueError):+ pass+ return None+++_SB_HEIRS: dict = {"key": None, "map": {}}+++def _sb_legacy_film_heir(base: str) -> str | None:+ """The board an UNMARKED old-style folder belongs to: the oldest board+ whose date and title give that folder name. It made the folder first;+ every later board with the same name was writing into somebody else's.++ CACHED, because the board list's two-second poll asks this for every+ board whose old folder carries no marker: one pass over the boards per+ change of the boards folder (a board made or deleted), and at most every+ 30 s for a rename, instead of one pass per board per poll."""+ root = Path(STATE_DIR) / "storyboards"+ try:+ stamp = root.stat().st_mtime_ns+ except OSError:+ stamp = 0+ key = (str(root), stamp, int(time.time() // 30))+ if _SB_HEIRS["key"] != key:+ try:+ rows = storyboard.list_storyboards(STATE_DIR)+ except Exception: # noqa: BLE001+ rows = []+ heirs: dict = {}+ for r in sorted(rows, key=lambda r: (r.get("created_at") or 0,+ str(r.get("id") or ""))):+ heirs.setdefault(_sb_film_base(r), str(r.get("id") or "") or None)+ _SB_HEIRS.update(key=key, map=heirs)+ return _SB_HEIRS["map"].get(base)++def _sb_film_dir(board: dict) -> Path:"""The ONE folder a board's finished films and shot copies land in.Three call sites computed this by hand — Export, `reveal`, and thetimeline's render — which is three chances for a film to be writtensomewhere the screen that shows films does not look. One function, one- convention: `<OUTPUT>/storyboards/<created-date>_<slug>/`.+ convention: `<OUTPUT>/storyboards/<created-date>_<slug>_<board>/`.++ THE BOARD IS IN THE NAME (SB5-05). It used to be date + title slug alone,+ so two boards made the same day with the same title — or the same first+ six words, or any two titles in Japanese, which slug to "shot" — shared+ one folder, one film name and `-y`: each export overwrote the other's+ film, shot copies and manifests, and both Film screens listed the pair.++ MIGRATION, without moving a file: a board whose old-style folder is+ already on disk keeps it while the folder is its own — it says so (the+ marker, or an Export's storyboard.json), or it says nothing and this is+ the oldest board with that name. Every other board gets its own folder."""- title = board.get("title") or "storyboard"- day = time.strftime("%Y-%m-%d",- time.localtime(board.get("created_at") or time.time()))- return OUTPUT / "storyboards" / f"{day}_{_sb_slug(title, 6)}"+ base = _sb_film_base(board)+ root = OUTPUT / "storyboards"+ bid = str(board.get("id") or "")+ legacy = root / base+ if legacy.is_dir():+ owner = _sb_film_owner(legacy)+ if owner is None:+ owner = _sb_legacy_film_heir(base) or bid+ if owner == bid:+ return legacy+ if not bid:+ return legacy+ # The six hex digits are what makes a minted id unique (the date is+ # already in the name); anything else is kept whole.+ m = re.fullmatch(r"sb_\d{8}_([0-9a-f]+)", bid)+ tag = m.group(1) if m else (re.sub(r"[^A-Za-z0-9-]+", "-", bid).strip("-")+ or hashlib.sha1(bid.encode()).hexdigest()[:8])+ return root / f"{base}_{tag}"+++def _sb_film_dir_for_write(board: dict) -> Path:+ """`_sb_film_dir`, created, and marked as this board's.++ Every writer goes through here, so a folder that holds a film also says+ whose film it is — which is what lets the next board with the same name+ be told apart without guessing.+ """+ d = _sb_film_dir(board)+ d.mkdir(parents=True, exist_ok=True)+ bid = str(board.get("id") or "")+ if bid and _sb_film_owner(d) is None:+ try:+ (d / _SB_FILM_OWNER).write_text(bid + "\n", encoding="utf-8")+ except OSError:+ pass+ return ddef _sb_display_path(p) -> str:@@ -21634,9 +22674,17 @@ def _sb_timeline_segments(timeline: list) -> tuple[list[dict], list[str], list]:continueadjust = entry.get("adjust") if isinstance(entry.get("adjust"), dict) else Noneframe = entry.get("frame") if isinstance(entry.get("frame"), dict) else None+ # PICTURE EFFECTS BELONG TO EVERY KIND (SB5-13). `edit_to_cuts` writes+ # `fx` on a still and a slug exactly as on a video clip, and the graph+ # reads `sg["fx"]` for all three — but only the video branch below+ # copied it, so a faded still previewed its fade and rendered a hard+ # cut in and out.+ fx = dict(entry["fx"]) if isinstance(entry.get("fx"), dict) and entry["fx"] else Noneif kind == "slug":seg = {"kind": "slug", "input": None, "info": None,"window": None, "adjust": adjust, "duration": length}+ if fx:+ seg["fx"] = fxif isinstance(entry.get("transition"), dict):seg["transition"] = dict(entry["transition"])if entry.get("tx_in"):@@ -21661,6 +22709,8 @@ def _sb_timeline_segments(timeline: list) -> tuple[list[dict], list[str], list]:seg = {"kind": "still", "input": len(inputs), "info": info,"window": None, "adjust": adjust,"duration": length, "path": path}+ if fx:+ seg["fx"] = fxif frame:seg["frame"] = dict(frame)if tx:@@ -21700,8 +22750,8 @@ def _sb_timeline_segments(timeline: list) -> tuple[list[dict], list[str], list]:seg["tx_in"] = tx_inif entry.get("mute") is True:seg["mute"] = True- if isinstance(entry.get("fx"), dict) and entry["fx"]:- seg["fx"] = dict(entry["fx"])+ if fx:+ seg["fx"] = fxif entry.get("gain"):seg["gain"] = [list(pt) for pt in entry["gain"]]if entry.get("lane") == 2:@@ -22006,25 +23056,44 @@ def _sb_assemble_film(clips: list, out_path, *, plan: list | None = None,# only is not decoded for a picture nothing maps.for row in strip_rows:cmd += ["-vn", "-i", str(row["path"])]+ # NEVER ENCODE OVER THE LAST GOOD FILM (SB5-06). There is one film name+ # per board and delivery (`_sb_film_name`), so a re-render targets the+ # file that already worked — and the failure branch below used to unlink+ # it. A cancelled, crashed or disk-full re-render cost the user the film+ # they already had. The encode goes to a hidden sibling (same folder, so+ # the rename is atomic; same extension, so ffmpeg picks the same muxer)+ # and only a finished, non-empty file replaces the old one.+ part = out_path.with_name(+ f".{out_path.stem}.part-{os.urandom(4).hex()}{out_path.suffix}")cmd += ["-filter_complex", graph,"-map", vlabel, "-map", "[aout]",*_sb_encode_args(dl, codec),"-ar", str(rate),- str(out_path),+ str(part),]++ def _drop_part() -> None:+ try:+ part.unlink()+ except OSError:+ pass+try:run_ffmpeg_tracked(cmd, "Storyboard film")except Exception as exc: # noqa: BLE001# A half-written mp4 is worse than none — it looks like a finished film- # in Finder and plays for two seconds.- try:- out_path.unlink()- except OSError:- pass+ # in Finder and plays for two seconds. Only OUR half goes.+ _drop_part()return {"ok": False, "error": f"ffmpeg could not assemble the film: {exc}"}- if not out_path.is_file() or out_path.stat().st_size == 0:+ if not part.is_file() or part.stat().st_size == 0:+ _drop_part()return {"ok": False, "error": "ffmpeg exited cleanly but wrote no film"}+ try:+ os.replace(part, out_path)+ except OSError as exc:+ _drop_part()+ return {"ok": False, "error": f"the film could not be put in place: {exc}"}# The SAME per-occurrence consumption the graph just did, so the reported# duration and the film agree even when one source is used twice — and, on# the timeline path, even when some of what played was never a file.@@ -22199,8 +23268,7 @@ def _sbe_render_edit(board: dict, edit: dict, *, music=None,# 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)+ dest = _sb_film_dir_for_write(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)@@ -22287,8 +23355,7 @@ def _sb_export(board: dict, *, auto_edit: bool = False, music=None,the manifest, never a failed export."""title = board.get("title") or "storyboard"- dest = _sb_film_dir(board)- dest.mkdir(parents=True, exist_ok=True)+ dest = _sb_film_dir_for_write(board)rows, cut, files = [], [], []cut_list: list = [] # the copies, in `n` orderfor s in sorted((board.get("shots") or []), key=lambda x: x.get("n") or 0):@@ -22360,11 +23427,26 @@ def _sb_export(board: dict, *, auto_edit: bool = False, music=None,# The default call is the call that always was — same arguments,# same argv, same bytes out. The auto-edit only ever ADDS kwargs,# and only when it actually produced a plan.+ # `music` AND `music_mode` on BOTH calls. The auto-edit branch+ # passed the soundtrack and dropped the mode, so a caller asking+ # for `replace` got whatever the assembler defaulted to; the+ # whole-clip branch passed NEITHER, so `_sb_export(music=...)`+ # with auto_edit off silently produced a film with no soundtrack+ # in it at all. Both are the same bug — a soundtrack that was+ # accepted at the door and dropped on the way to ffmpeg — and it+ # is the whole-clip path a music video wants: its shots are+ # already cut to the grid, so re-cutting them here would slide+ # every a2v clip off the seconds of the song it was rendered+ # against. With `music=None` (every caller that predates this)+ # `_sb_assemble_film` builds the identical graph it always did.if plan:film = _sb_assemble_film(cut_list, dest / film_name,- plan=plan, music=music)+ plan=plan, music=music,+ music_mode=music_mode or "replace")else:- film = _sb_assemble_film(cut_list, dest / film_name)+ film = _sb_assemble_film(cut_list, dest / film_name,+ music=music,+ music_mode=music_mode or "replace")except Exception as exc: # noqa: BLE001film = {"ok": False, "error": f"{type(exc).__name__}: {exc}"}if film.get("ok"):@@ -22542,6 +23624,10 @@ def _sb_films(board: dict, *, probe: bool = True) -> list[dict]:for p in entries:if p.suffix.lower() not in (".mp4", ".mov") or _SB_SHOT_COPY_RE.match(p.name):continue+ # A hidden name is an encode still in progress (`_sb_assemble_film`+ # writes `.<film>.part-<hex>.mp4` and renames it when it is whole).+ if p.name.startswith("."):+ continuetry:st = p.stat()except OSError:@@ -23080,6 +24166,7 @@ def _sbe_add_sound(board: dict, path: str) -> dict:dest = srcimported = Falseif not src.is_relative_to(OUTPUT.resolve()):+ _sb_film_dir_for_write(board) # a write claims the foldersdir = _sbe_sound_dir(board)sdir.mkdir(parents=True, exist_ok=True)dest = sdir / re.sub(r"[^A-Za-z0-9._-]+", "_", src.name)@@ -23112,6 +24199,9 @@ def _sbe_room_tone(board: dict, *, variant: str = "film", seed: int = 1,the timeline the user is looking at, which may be ahead of the saved one.Only files that exist are read. CPU and about a second; no GPU, no queue."""import room_tone as rt # noqa: PLC0415+ # THE PANEL'S OWN ffmpeg (M6-08): room_tone's search does not know the+ # Pinokio tool folders this process resolved at boot.+ rt.FFMPEG = str(FFMPEG)if variant not in rt.variant_ids():return {"ok": False, "status": 400, "error": f"unknown room tone: {variant}"}rows = []@@ -23127,6 +24217,7 @@ def _sbe_room_tone(board: dict, *, variant: str = "film", seed: int = 1,if pth and en > st and Path(pth).is_file():rows.append({"path": pth, "start": st, "end": en})t0 = time.time()+ _sb_film_dir_for_write(board) # a write claims the folderfacts = rt.make_bed(_sbe_room_tone_dir(board), variant=variant, seed=seed,film_len=film_len, clips=rows, strict=strict)if not facts.get("path"):@@ -23221,6 +24312,9 @@ def _sbe_auto_edit(board: dict, *, music: str | None = None,import storyboard_edit as _se # noqa: PLC0415bdir = _sbe_board_dir(board["id"])clips = _sbe_board_clips(board)+ mv = board.get("music_video") if isinstance(board.get("music_video"), dict) else None+ if mv and mv.get("song") and clips and not music:+ return _sbe_music_video_edit(board, clips, mv, sedit, _se, bdir)cache = _sbe_prepare_cache(bdir)# 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@@ -23266,6 +24360,67 @@ def _sbe_auto_edit(board: dict, *, music: str | None = None,return edit+def _sbe_music_video_edit(board: dict, clips: list, block: dict, sedit, _se,+ bdir: Path) -> dict:+ """A music video's first timeline is its PLAN, with the SONG under it.++ THE EDITOR HANDOFF LOST THE SONG (SB5-12). The planner keeps the master+ track at `board["music_video"]["song"]`, which `_sbe_auto_edit` never+ read: a music-video board opened in the Editor was cut by `plan_cut` with+ no audio — every shot trimmed to its "best window", the whole film slid+ off the frames the planner laid out — and carried no soundtrack, so its+ Render played each clip's own audio (B-roll had none of the song). The+ edit it wrote is also what `/music/video/film` renders from afterwards+ ("the timeline wins"), so opening the Editor once broke that route too.++ So no re-cutting: every shot sits at the film second the planner gave it+ (`music_video.film_start`), whole, trimmed only if the file is shorter+ than planned — each a2v shot was rendered against exactly that stretch+ of the song, so moving it is moving the mouth off the words. The song is+ the bed in `replace` mode at the neutral mix (unity, no duck), the same+ master `/music/video/film` lays down. No room tone: under a replaced mix+ it would be noise on top of the song.+ """+ by_n = {s.get("n"): s for s in (board.get("shots") or []) if isinstance(s, dict)}+ plan = []+ cursor = 0.0+ for c in clips:+ shot = by_n.get(c.get("n")) or {}+ mvs = shot.get("music_video") if isinstance(shot.get("music_video"), dict) else {}+ try:+ fs = float(mvs["film_start"])+ want = max(0.0, float(mvs["film_end"]) - fs)+ except (KeyError, TypeError, ValueError):+ fs = cursor+ want = max(0.0, float(c.get("duration_s") or 0.0))+ fs = max(fs, cursor) # never overlap the shot before it+ dur = (_se.probe_media(c["path"]) or {}).get("duration")+ length = min(want, float(dur)) if dur else want+ if length <= 0:+ continue+ plan.append({"path": c["path"], "n": c.get("n"), "start": 0.0,+ "end": round(length, 6), "film_start": round(fs, 6),+ "window": {"source_duration": dur},+ "notes": ["placed where the music-video plan put it"]})+ cursor = fs + length+ song = str(block.get("song") or "")+ audio = None+ if song and Path(song).is_file():+ peaks = sedit.load_peaks(bdir)+ dur = (peaks or {}).get("duration")+ if dur is None:+ dur = (_se.probe_media(song) or {}).get("duration")+ audio = {"path": song, "offset": 0.0,+ "peaks": "peaks.json" if peaks else None,+ "duration": dur, "mode": "replace"}+ return sedit.edit_from_plan(+ plan, board_id=board["id"], audio=audio, beats=None,+ proxies=_sbe_proxy_map(bdir, clips, sedit),+ labels={c["path"]: f"S{(c.get('n') or 0):02d} · {c['title']}"+ for c in clips},+ settings={"music_video": True})++def _sbe_relinks(board: dict, edit: dict) -> list[dict]:"""Timeline clips still pointing at a draft whose delivery now exists.@@ -23406,6 +24561,32 @@ class CharacterRequestError(ValueError):"""A character request cannot preserve the face + voice contract."""+class MusicRequestError(CharacterRequestError):+ """A song request that would render something other than what was asked.++ A subclass so every door that already answers a CharacterRequestError+ with a polite 400 (/queue/add among them) answers this one too."""+++def music_lora_unresolved(raw) -> list[str]:+ """Picked adapter ids that do not resolve inside the LoRA folder.++ `music_lora_picks` drops such a pick in silence — right for a sidecar+ replay of a deleted file, wrong for a request: a song rendered without the+ voice whose row was ticked is a song nobody asked for (M6-05)."""+ try:+ from scripts.pinokio.music_lora_fetch import parse_field, resolve_in_pack+ except Exception: # noqa: BLE001+ return []+ bad = []+ for identifier, _strength in parse_field(raw):+ try:+ resolve_in_pack(MUSIC_LORAS, identifier)+ except (OSError, ValueError):+ bad.append(identifier)+ return bad++def _engine_would_be_h3(requested: str, mode: str) -> bool:"""Would a job asking for this engine ACTUALLY render on H3?@@ -23773,8 +24954,10 @@ def _helper_start_failure(ready: dict | None, tail) -> str:# make_job that names a file belongs here — the alternative is another# "<thing> not found: '<quoted path>'" in the fleet.PASTED_PATH_FIELDS = (- "image", "audio", "video_path", "restore_video_path", "upscale_source_path",+ "image", "audio", "audio_stem", "video_path", "restore_video_path",+ "upscale_source_path","control_video_path", "start_image", "end_image", "ingredient_char_lora",+ "music_source_audio",)@@ -23802,6 +24985,201 @@ PASTED_PATH_FIELDS = (A2V_AUDIO_SCALE_ON = {"q8": 3.0, "q4": 1.0}+# --- A2V LENGTH ON A COMPACT MAC ---------------------------------------------+# Fleet 2026-09-24: 30-second Audio → Video renders on 8 GB Macs died in the+# Metal GPU watchdog instead of being refused. Nothing stood in their way: the+# slider goes to 30 s, the compact generation profile's temporal mitigation is+# T2V/I2V only, and Long Clip Boost (12 fps → 24) is not an a2v path — so an+# a2v job asks the model for every native frame it was given.+#+# The cap is not a new number. `_select_generation_profile` already says that+# past `auto_temporal_after_frames` (241, the "10s" cell of LTX_LENGTHS) native+# 24 fps puts a 48 GB Mac into MLX swap thrash — it was put there by a real one+# — and T2V/I2V are reshaped to Long Clip Boost at that point. A Compact-tier+# Mac has less memory than that 48 GB Mac, and a2v carries the audio stream on+# top, with no 12 fps path to fall back to. So on the Compact tier an a2v+# render past that frame count is refused up front, with the way through it:+# consecutive clips, each on its own offset into the song. The two escape+# hatches that lift the profile's cap (LTX_GENERATION_PROFILE=full, a+# high/pro LTX_TIER_OVERRIDE) lift this one too.+def a2v_max_frames() -> int:+ """Longest a2v render (frames) this Mac is allowed; 0 means uncapped."""+ if SYSTEM_TIER != "base":+ return 0+ profile = GENERATION_PROFILE or {}+ if not profile.get("compact"):+ return 0+ return max(0, int(profile.get("auto_temporal_after_frames") or 0))+++def a2v_length_refusal(frames: int, cap: int) -> str:+ cap_s = int(round(_frames_to_model_duration(cap)))+ asked_s = round(_frames_to_model_duration(frames), 1)+ return (+ f"Audio → Video is limited to {cap_s} s per clip on the "+ f"{SYSTEM_CAPS['label']} hardware tier: {asked_s:g} s ({frames} frames) "+ f"outgrows this Mac's {SYSTEM_RAM_GB:.0f} GB of unified memory, and "+ f"macOS stops a render that size partway through (a GPU timeout). "+ f"Render the song as {cap_s} s clips instead — set Start at to 0, "+ f"{cap_s}, {2 * cap_s} … — and join them in the Editor. Full-length "+ f"clips work from {TIER_MIN_RAM_GB['standard']} GB.")+++# --- THE VOCAL-STEM SEAM ----------------------------------------------------+# What the model LISTENS TO and what the clip PLAYS are two different files.+#+# Drums, bass and guitar reach the audio encoder as energy the model can read+# as syllables, so it hedges: it opens the mouth a little, all the time, on+# everything. Conditioning on a separated vocal stem removes that noise, and+# the ORIGINAL song is muxed back over the finished clip, so nothing the+# audience hears has changed. Measured on one shot (see the lip-sync study):+# the stem is the only candidate with a positive zero-lag correlation, and its+# mouth movement is DOUBLE every other candidate's - with the band removed+# from the conditioning waveform the model stops hedging and articulates.+#+# `audio_stem` names a stem the caller already has (the music-video route+# passes one for the whole film). `audio_stem_auto` asks the panel to make one+# with demucs, and is allowed to fail: a missing optional tool becomes a NOTE,+# never a refused render.+A2V_STEM_DIR = "a2v_stems"+A2V_STEM_TIMEOUT_S = 900+A2V_STEM_MISSING_NOTE = (+ "Auto vocal stem is on but demucs is not installed, so this clip was "+ "conditioned on the full mix. Install the stems extra from the Pinokio "+ "sidebar (scripts/pinokio/a2v_stems_deps.sh) to separate the vocal."+)+++def _resolve_demucs() -> Path | None:+ """The demucs executable this panel may use, or None.++ ONLY TOOLS AN INSTALL SCRIPT CAN PROVIDE. The engine venv's own bin comes+ first - that is where `scripts/pinokio/a2v_stems_deps.sh` puts it - then+ the ordinary resolver (env override, PATH, Pinokio's tool folders,+ Homebrew). Some other project's virtualenv on this Mac is not a dependency+ of Phosphene and must never become one by accident, which is why nothing+ here reaches outside those.++ `_resolve_tool` returns a LAST-RESORT path that need not exist, so the+ result is checked before it is believed: a separator that is not there has+ to read as "not installed" at plan time, never as a command that dies+ twenty minutes into a render.+ """+ beside = HELPER_PYTHON.parent / "demucs"+ if beside.is_file():+ return beside+ cand = _resolve_tool("demucs", "PHOSPHENE_DEMUCS")+ return cand if cand.is_file() else None+++def _a2v_stem_cache_path(audio_src: str) -> Path:+ """Where this song's separated vocal lives. Keyed by path + size + mtime,+ so a 12-shot music video separates ONCE and every shot after the first is+ free, while an edited file is separated again."""+ src = Path(audio_src)+ try:+ st = src.stat()+ key = f"{src.resolve()}|{st.st_size}|{int(st.st_mtime)}"+ except OSError:+ key = str(src)+ digest = hashlib.sha1(key.encode("utf-8", "replace")).hexdigest()[:16]+ return STATE_DIR / A2V_STEM_DIR / digest / "vocals.wav"+++def _a2v_separate_vocals(audio_src: str, demucs: Path) -> Path:+ """Separate the vocal out of `audio_src` with demucs. Cached; raises on+ failure so the caller can turn it into a note.++ TRACKED, because Stop has to reach it. Separation is minutes of CPU at the+ front of a render, and a bare `subprocess.run` is invisible to+ `stop_current_job`: pressing Stop killed the helper and left demucs+ grinding on, with the queue held by a job the user had already cancelled,+ until it finished or the 900 s timeout fired (Codex review, 2026-09-22).+ `run_tracked_subprocess` registers the child's process group under the key+ Stop already kills, refuses to start after Stop, and raises `JobCancelled`+ when Stop ended it — which is NOT a separation failure and must not be+ turned into one. It also states the text-mode trio itself, including+ `errors="replace"`: a strict UTF-8 decode of another program's output+ would end the render with a codec error no user could act on, and demucs+ prints a progress bar (the fleet has 42 of those from ffmpeg alone).+ """+ cached = _a2v_stem_cache_path(audio_src)+ if cached.is_file() and cached.stat().st_size > 0:+ return cached+ work = cached.parent / "work"+ work.mkdir(parents=True, exist_ok=True)+ try:+ proc = run_tracked_subprocess(+ [str(demucs), "--two-stems=vocals", "-o", str(work), str(audio_src)],+ pgid_key="mux_pgid", label="the vocal separation",+ job=_thread_job(), timeout=A2V_STEM_TIMEOUT_S)+ if proc.returncode != 0:+ tail = (proc.stderr or proc.stdout or "").strip().splitlines()[-1:]+ raise RuntimeError(f"demucs failed: {tail[0] if tail else 'no output'}")+ found = sorted(work.rglob("vocals.*"))+ if not found:+ raise RuntimeError("demucs wrote no vocals stem")+ cached.parent.mkdir(parents=True, exist_ok=True)+ shutil.move(str(found[0]), str(cached))+ finally:+ # Including on Stop: a killed separation leaves half a model's output+ # behind, and the next attempt must not find it.+ shutil.rmtree(work, ignore_errors=True)+ return cached+++def a2v_conditioning_audio(params: dict, audio_src: str) -> tuple[str, str]:+ """(the waveform the model listens to, a note for the user).++ The note is empty when there is nothing to say. An explicit `audio_stem`+ that is not a file RAISES - it is a typo in something the caller wrote,+ and silently rendering the full mix would hide it. `audio_stem_auto` never+ raises: the optional tool is optional.+ """+ stem = str(params.get("audio_stem") or "").strip()+ if stem:+ if not Path(stem).is_file():+ raise RuntimeError(f"vocal stem not found: {stem}")+ return stem, ""+ want_auto = str(params.get("audio_stem_auto") or "").strip().lower() \+ in ("1", "true", "on", "yes")+ if not want_auto:+ return audio_src, ""+ demucs = _resolve_demucs()+ if demucs is None:+ return audio_src, A2V_STEM_MISSING_NOTE+ try:+ return str(_a2v_separate_vocals(audio_src, demucs)), ""+ except JobCancelled:+ # The user stopped the job. That is not a tool that failed, and+ # degrading to the full mix here would start a twenty-minute render+ # of a clip nobody asked for any more.+ raise+ except Exception as exc: # noqa: BLE001+ return audio_src, (f"Could not separate the vocal ({exc}), so this "+ f"clip was conditioned on the full mix.")+++def a2v_mux_original_audio(video: Path, audio_src: str, *,+ start: float, duration: float) -> None:+ """Put the ORIGINAL song back over a clip rendered against a stem.++ The pipeline muxes whatever it listened to, so a stem-conditioned clip+ comes back playing an a-cappella. The video stream is COPIED, never+ re-encoded: this is a container edit, not a second render, and re-encoding+ here would cost quality the render already paid for.+ """+ tmp = video.with_suffix(video.suffix + ".mux.mp4")+ cmd = [str(FFMPEG), "-y", "-i", str(video),+ "-ss", f"{max(0.0, float(start)):.4f}", "-i", str(audio_src),+ "-map", "0:v:0", "-map", "1:a:0", "-c:v", "copy",+ "-af", f"apad,atrim=0:{duration},asetpts=PTS-STARTPTS",+ "-c:a", "aac", "-b:a", "192k",+ "-movflags", "+faststart", "-t", f"{duration}", str(tmp)]+ run_ffmpeg_tracked(cmd, "Stem mux")+ os.replace(str(tmp), str(video))++def a2v_audio_scale(raw, *, q8: bool) -> float:"""The audio-guidance value for this lane: `raw` when it names one, elsethe lane's engine default.@@ -23863,6 +25241,34 @@ def make_job(form: dict[str, list[str]] | dict[str, str], *,mode_in = f("mode", "t2v")if mode_in == "music" or f("engine") == "music":params = music_params(form)+ # REFUSE WHAT WOULD RENDER SOMETHING ELSE, before it is queued.+ if params["music_task"] == "cover":+ src = params["music_source_audio"]+ if not src:+ raise MusicRequestError(+ "Cover needs a recording — pick or paste the one to cover.")+ if not Path(src).is_file():+ raise MusicRequestError(f"There is no recording at {src}.")+ if not params["music_instrumental"]:+ missing = music_lora_unresolved(form.get("music_loras"))+ if missing:+ raise MusicRequestError(+ "These picked LoRAs are not in the music LoRA folder, so the "+ "song would be made without them: " + ", ".join(missing))+ # A TRAINED VOICE IS TRAINED IN ONE DIALECT (M6-04). A `direct`+ # voice never saw a score in its prefix and the engine refuses a+ # score with `--mode off`; a `score` voice was trained with one.+ # Rendering either the other way is a degraded voice nobody chose.+ for pick in params["music_loras"]:+ name = Path(str(pick.get("id") or "")).name+ if pick.get("dialect") == "direct" and params["music_mode"] != "off":+ raise MusicRequestError(+ f"The voice {name} was trained without a score — set "+ f"Score to “No score” to sing with it.")+ if pick.get("dialect") == "score" and params["music_mode"] == "off":+ raise MusicRequestError(+ f"The voice {name} was trained with a score — choose "+ f"“Melody only” or “Melody + chords” to sing with it.")params["prompt"] = params["music_style"] or params["music_lyrics"] or "Instrumental"params["label"] = params["prompt"][:80]return {"id": _new_job_id(), "status": "queued", "queued_at": iso_now(),@@ -24630,6 +26036,13 @@ def make_job(form: dict[str, list[str]] | dict[str, str], *,# default_reference_image() for why this used to be a phantom."image": f("image", default_reference_image()),"audio": f("audio", str(AUDIO_DEFAULT)),+ # A2V VOCAL STEM. What the model LISTENS to, when it should not be+ # the same file the clip plays: `audio_stem` names a separated+ # vocal and `audio_stem_auto` asks the panel to make one with+ # demucs. Both live here or they silently no-op on /queue/add —+ # the make_job allowlist trap this file warns about throughout.+ "audio_stem": f("audio_stem", ""),+ "audio_stem_auto": f("audio_stem_auto", ""),# extend mode params"video_path": f("video_path", ""),# restore (Colorize) mode — the B&W source clip to colorize. MUST@@ -25504,6 +26917,12 @@ def run_image_job_inner(job: dict) -> None:# circuits before the subprocess even spawns). Bypass with# PHOSPHENE_SKIP_PREFLIGHT=1._preflight_image_job(cfg, engine_override=engine_override)+ # STOP DURING PREFLIGHT. Preflight can unload the helper and wait for+ # memory to settle, and a Stop pressed then found no image process to+ # kill; the engine started anyway and the job was filed done. Checked+ # here, and again by the engine the moment it registers its process+ # (image_engine._register_active_proc -> _image_job_cancelled).+ _raise_if_cancelled(job, "the image engine started")# Same date-bucketed + per-request output dir scheme as /image/generate# so the library reader (and any downstream consumer) sees one shape.@@ -25567,6 +26986,9 @@ def run_image_job_inner(job: dict) -> None:raisefinally:_IMG_STUDIO_LOCK.release()+ # A Stop that landed as the engine exited cleanly is still a Stop: the+ # worker must not file an acknowledged cancellation as done.+ _raise_if_cancelled(job, "the image was published")elapsed = round(time.time() - t0, 2)# Record the observed wall time so /image/engine_status can override@@ -27110,8 +28532,15 @@ def run_h3_job_inner(job: dict) -> None:_stack_layouts = []for _i, (_pp, _ps) in enumerate(_picked):_stack_layouts.append(_h3_lora_prepare(_pp).get("layout"))- # After prepare, so a file folded just now is recognised too.- _new = _h3_lora_migrate_strength(_pp, _ps, p)+ # After prepare, so a file folded just now is recognised too. An+ # entry replayed from an older recipe carries that recipe's own+ # scale version (parse_loras_from_form), which outranks the stamp+ # make_job put on the job as a whole.+ _entry_i = _picked_entries[_i] if isinstance(_picked_entries[_i], dict) else {}+ _mig_params = ({**p, "h3_lora_scale_v": _entry_i["scale_v"]}+ if "scale_v" in _entry_i else p)+ _new = _h3_lora_migrate_strength(_pp, _ps, _mig_params)+ _entry_i.pop("scale_v", None)if _new != _ps and isinstance(_picked_entries[_i], dict):# Into the recipe as well — THIS entry only (a stack may list# the same file twice at different strengths): the sidecar@@ -27241,15 +28670,9 @@ def run_h3_job_inner(job: dict) -> None:# Reject unreadable images before the H3 subprocess starts — the runner# also uses PIL and crashes with PIL.UnidentifiedImageError there instead# of a useful message (fleet: 4 installs, v4.12.2).- try:- from PIL import Image as _PilImg- with _PilImg.open(Path(src)):- pass- except Exception as _pil_err:- raise RuntimeError(- f"The reference image can't be read ({_pil_err.__class__.__name__}). "- "Export it as a JPEG or PNG and try again."- ) from None+ _ref_err = h3_reference_image_error(Path(src))+ if _ref_err:+ raise RuntimeError(_ref_err) from Noneif not h3_supports_first_frame():raise RuntimeError("Image mode conditions on a first frame: "@@ -27484,6 +28907,20 @@ def run_h3_job_inner(job: dict) -> None:# Pinokio's bundled binary is not on the default PATH.env["PATH"] = f"{FFMPEG_BIN}:{env.get('PATH', '')}"env["PYTHONUNBUFFERED"] = "1"+ # FP16 VAE decode — the default (h3_vae_fp16_decode()). Passed as the runner's+ # own flag so the argv says what ran; a runner that predates the flag+ # would reject it, so that case is said out loud instead of passed.+ _vae_fp16 = False+ if h3_vae_fp16_decode():+ if _h3_runner_has_flag("--vae-dtype"):+ cmd += ["--vae-dtype", "float16"]+ p["h3_vae_dtype"] = "float16"+ _vae_fp16 = True+ else:+ push("[h3] This H3 runner predates the faster FP16 video decode — "+ "decoding in float32 (same picture, a little slower). Press "+ "Update in Pinokio, or \"Update Hailuo H3 runner\" in the "+ "sidebar, to get it.")push(f"[h3] {tier['label']} · {width}×{height} · {frames}f · "f"{steps} sigma points ({steps - 1} forwards) · seed {seed}"@@ -27494,6 +28931,7 @@ def run_h3_job_inner(job: dict) -> None:+ (f" · LoRA {user_lora.name} @ {user_lora_strength:g}"if (user_lora is not None and not turbo) else "")+ (" · fast draft decode (TAE)" if tae_used else "")+ + (" · FP16 VAE decode" if _vae_fp16 else "")+ (" · live preview" if h3_preview_on else "")+ (f" · {chain_windows} chained windows of {window_frames}f"if chain_windows > 1 else "")@@ -27843,8 +29281,10 @@ def run_h3_job_inner(job: dict) -> None:if upscale_plan:codec = job_codecexport_preset = os.environ.get("LTX_UPSCALE_PRESET", "medium")- upscaled_out = OUTPUT / (- f"{out_path.stem}_{upscale_plan['tag']}{out_path.suffix}")+ # Unique, like every native output: `ffmpeg -y` on a bare+ # "<stem>_<tag>" replaced an earlier render that already had it.+ upscaled_out = _unique_output_path(+ OUTPUT, f"{out_path.stem}_{upscale_plan['tag']}", out_path.suffix)run_ffmpeg_tracked([str(FFMPEG), "-y", "-i", str(out_path),"-vf", bt709_vf(upscale_plan["vf"]),@@ -28029,6 +29469,15 @@ def run_h3_job_inner(job: dict) -> None:subprocess.run(["open", str(final_target)], check=False)+def ffconcat_line(path) -> str:+ """One `file` directive for ffmpeg's concat demuxer, quoted so any path+ survives it. Inside single quotes the demuxer allows no escapes, so an+ apostrophe closes the quote, is escaped, and reopens it ('\\''). A bare+ f"file '{x}'" broke on "/Volumes/Artist's Drive/…": every window rendered,+ then the final join could not open its pieces (LTX-07)."""+ return "file '" + str(path).replace("'", "'\\''") + "'\n"++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@@ -28125,7 +29574,7 @@ def _run_windows_chain(job: dict, p: dict, plan: dict, first: Path,# 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))+ lst.write_text("".join(ffconcat_line(x) for x in pieces), encoding="utf-8")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"],@@ -28175,7 +29624,23 @@ def _gemma4_tower_supported() -> bool | None:return res-def _join_take_parts(ff: str, parts: list[str], final: Path, fps: float = 24.0) -> None:+def _take_ffmpeg(cmd: list[str], label: str, job: dict | None) -> None:+ """A One Shot ffmpeg step that Stop can end (LTX-01).++ These ran as bare `subprocess.run(check=True)`: no process group Stop+ knew about, so Stop during the final join waited for the whole encode,+ and the take was then published and filed done. Registered under+ `mux_pgid` like every other post-process; raises JobCancelled when Stop+ ended it and RuntimeError on any other non-zero exit (check=True)."""+ r = run_tracked_subprocess(cmd, pgid_key="mux_pgid", label=label, job=job)+ if r.returncode != 0:+ tail = (r.stderr or r.stdout or "").strip()[-300:]+ raise RuntimeError(f"{label} failed (ffmpeg exit {r.returncode})"+ + (f": {tail}" if tail else ""))+++def _join_take_parts(ff: str, parts: list[str], final: Path, fps: float = 24.0,+ job: dict | None = None) -> None:"""Join the parts of a one-shot take with the sound locked to the picture.Every part's audio comes out of the model a few hundredths of a second@@ -28187,9 +29652,10 @@ def _join_take_parts(ff: str, parts: list[str], final: Path, fps: float = 24.0)shorter than its picture is padded with silence to the same length."""n = len(parts)if n == 1:- subprocess.run([ff, "-loglevel", "error", "-y", "-i", parts[0],- "-c:v", "libx264", "-preset", "medium", "-crf", "17", "-pix_fmt", "yuv420p",- "-c:a", "aac", "-b:a", "192k", "-movflags", "+faststart", str(final)], check=True)+ _take_ffmpeg([ff, "-loglevel", "error", "-y", "-i", parts[0],+ "-c:v", "libx264", "-preset", "medium", "-crf", "17", "-pix_fmt", "yuv420p",+ "-c:a", "aac", "-b:a", "192k", "-movflags", "+faststart", str(final)],+ "One Shot join", job)returncmd = [ff, "-loglevel", "error", "-y"]graph = []@@ -28206,7 +29672,17 @@ def _join_take_parts(ff: str, parts: list[str], final: Path, fps: float = 24.0)cmd += ["-filter_complex", ";".join(graph), "-map", "[v]", "-map", "[a]","-c:v", "libx264", "-preset", "medium", "-crf", "17", "-pix_fmt", "yuv420p","-c:a", "aac", "-b:a", "192k", "-movflags", "+faststart", str(final)]- subprocess.run(cmd, check=True)+ _take_ffmpeg(cmd, "One Shot join", job)+++def _take_preview_follows(job: dict, child: dict | None) -> None:+ """Point the take's live preview (status + Stop early) at the part now+ rendering, or at nothing. See live_preview_job_id."""+ with LOCK:+ if child is None:+ job.pop("preview_id", None)+ else:+ job["preview_id"] = child["id"]def run_take_job_inner(job: dict) -> None:@@ -28233,6 +29709,7 @@ def run_take_job_inner(job: dict) -> None:take_dir.mkdir(parents=True, exist_ok=True)ff = str(FFMPEG)outs: list[str] = []+ rendered_out = ""tail_wav: str | None = None # speech handoff: the previous part's last word, mixed over this part's headlast_png: str | None = None# The continuity lock: "" when the user switched it off (then blank beats@@ -28302,6 +29779,7 @@ def run_take_job_inner(job: dict) -> None:"started_ts": time.time()}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 ""))+ _take_preview_follows(job, child)render_part(child)out = child.get("output_path")if not out or not Path(out).is_file():@@ -28323,6 +29801,7 @@ def run_take_job_inner(job: dict) -> None:retry = {"id": f"{job['id']}-p{k + 1}r", "params": retry_params,"status": "running", "created_at": job.get("created_at"),"started_ts": time.time()}+ _take_preview_follows(job, retry)render_part(retry)out2 = retry.get("output_path")d2 = take_drift(out2) if out2 and Path(out2).is_file() else {"delta": 9.0}@@ -28367,6 +29846,7 @@ def run_take_job_inner(job: dict) -> None:ls_retry = {"id": f"{job['id']}-p{k + 1}l" + (str(attempt) if attempt > 1 else ""),"params": ls_params, "status": "running","created_at": job.get("created_at"), "started_ts": time.time()}+ _take_preview_follows(job, ls_retry)render_part(ls_retry)out3 = ls_retry.get("output_path")ls2 = take_lipsync_score(out3) if out3 and Path(out3).is_file() else None@@ -28386,6 +29866,7 @@ def run_take_job_inner(job: dict) -> None:passjob.setdefault("take_lipsync", []).append(ls)outs.append(out)+ rendered_out = out # the part as rendered — the one with a sidecar# Parts are working files: kept, hidden from the gallery. The one shot# is the output.try:@@ -28397,10 +29878,10 @@ def run_take_job_inner(job: dict) -> None:# silence (a J-cut): its sound tail is mixed onto the head of this# clip, at level, before this clip is cut or anchored.led = str(take_dir / f"part{k + 1}_lead.mp4")- subprocess.run([ff, "-loglevel", "error", "-y", "-i", out, "-i", tail_wav,- "-filter_complex", "[1:a]apad[t];[0:a][t]amix=inputs=2:duration=first:normalize=0[a]",- "-map", "0:v", "-map", "[a]", "-c:v", "copy", "-c:a", "aac", "-b:a", "192k", led],- check=True)+ _take_ffmpeg([ff, "-loglevel", "error", "-y", "-i", out, "-i", tail_wav,+ "-filter_complex", "[1:a]apad[t];[0:a][t]amix=inputs=2:duration=first:normalize=0[a]",+ "-map", "0:v", "-map", "[a]", "-c:v", "copy", "-c:a", "aac", "-b:a", "192k", led],+ "One Shot speech handoff", job)outs[-1] = ledout = ledtail_wav = None@@ -28420,49 +29901,74 @@ def run_take_job_inner(job: dict) -> None:dur = 0.0if dur and 0.5 < cut < end <= dur:trimmed = str(take_dir / f"part{k + 1}_speech.mp4")- subprocess.run([ff, "-loglevel", "error", "-y", "-i", out, "-t", f"{cut:.3f}",- "-c:v", "libx264", "-preset", "medium", "-crf", "17", "-pix_fmt", "yuv420p",- "-c:a", "aac", "-b:a", "192k", trimmed], check=True)+ _take_ffmpeg([ff, "-loglevel", "error", "-y", "-i", out, "-t", f"{cut:.3f}",+ "-c:v", "libx264", "-preset", "medium", "-crf", "17", "-pix_fmt", "yuv420p",+ "-c:a", "aac", "-b:a", "192k", trimmed],+ "One Shot speech handoff", job)tail = str(take_dir / f"part{k + 1}_tail.wav")- subprocess.run([ff, "-loglevel", "error", "-y", "-ss", f"{cut:.3f}", "-to", f"{end:.3f}",- "-i", out, "-vn", "-c:a", "pcm_s16le", tail], check=True)+ _take_ffmpeg([ff, "-loglevel", "error", "-y", "-ss", f"{cut:.3f}", "-to", f"{end:.3f}",+ "-i", out, "-vn", "-c:a", "pcm_s16le", tail],+ "One Shot speech handoff", job)push(f"[take] part {k + 1}: hands off at {cut:.1f} s on a talking frame; the last word "f"finishes over the next part ({dur - end:.1f} s of silent tail dropped)")outs[-1] = trimmedout = trimmedtail_wav = taillast_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)+ _take_ffmpeg([ff, "-loglevel", "error", "-y", "-sseof", "-0.05", "-i", out,+ "-frames:v", "1", "-update", "1", last_png], "One Shot handoff frame", job)job["take_progress"] = {"part": k + 1, "parts": n_parts}+ _take_preview_follows(job, None) # the join has no previewif 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))+ lst.write_text("".join(ffconcat_line(o) for o in outs), encoding="utf-8")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}")- _join_take_parts(ff, outs, final)+ _join_take_parts(ff, outs, final, job=job)+ # Stop during the join ends it (JobCancelled above); a Stop that lands as+ # the encode finishes must not be published and filed done either.+ _raise_if_cancelled(job, "the one shot was published")+ # THE TAKE'S SIDECAR IS THE TAKE'S, NOT ITS LAST PART'S (LTX-02). The+ # technical fields (canvas, seed, model) still come from the last part as+ # rendered — outs[-1] can be a speech-handoff remux with no sidecar of its+ # own, which is why the rendered file is tracked separately. But Load+ # Params reads `params`, and that used to be the last part's: a short i2v+ # of the final beats on a handoff frame, so reopening a One Shot restored+ # a different, smaller render. `params` is now the parent job's own+ # intent with the full take block, and every output field names the take.side: dict = {}try:- side = json.loads(Path(outs[-1] + ".json").read_text())+ side = json.loads(Path((rendered_out or outs[-1]) + ".json").read_text())except (OSError, ValueError):side = {}+ take_block = {"seconds": take["seconds"], "beats": beats, "parts": outs, "engine": engine,+ "beats_per_part": take.get("beats_per_part")+ or (TAKE_H3_BEATS_PER_PART if engine == "h3" else TAKE_LTX_BEATS_PER_PART),+ "part_frames": take.get("part_frames"),+ "light_lock": lock, "retake": retake_allowed,+ "camera": take.get("camera") or "",+ "handoff": take.get("handoff") or "last"}side.update({+ "output": str(final), "raw_output": str(final), "native_output": str(final),"mode": p.get("mode", "t2v"), "engine": engine, "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": engine,- "beats_per_part": take.get("beats_per_part")- or (TAKE_H3_BEATS_PER_PART if engine == "h3" else TAKE_LTX_BEATS_PER_PART),- "part_frames": take.get("part_frames"),- "light_lock": lock, "retake": retake_allowed,- "camera": take.get("camera") or "",- "handoff": take.get("handoff") or "last"},+ "take": take_block,"temporal_mode": "native", "long_mode": "native", "window_prompts": [],+ "queue_id": job["id"], "started": job.get("started_at"),+ "params": {**p, "take": {**(p.get("take") or {}), **take_block},+ "image": first_image or None,+ "temporal_mode": "native", "long_mode": "native",+ "window_prompts": []},})+ if isinstance(side.get("upscale"), dict):+ # Its `source` named the last part's native file, not this take.+ side["upscale"] = {k: v for k, v in side["upscale"].items() if k != "source"}if engine == "h3":side["h3_chain_prompts"] = beats+ side["params"]["h3_chain_prompts"] = beats# The last part's sidecar names ITS image — a handoff frame in the state# dir. The one shot's own image is the user's anchor, or nothing.if first_image:@@ -28709,6 +30215,11 @@ def run_job_inner(job: dict) -> None:"seed": p["seed"],"steps": steps,"cfg_scale": cfg_scale,+ # The helper's extend lane attaches these (as the sliding-+ # windows chain already relied on); this request never sent+ # them, so a selected LoRA was dropped while the sidecar+ # listed it (LTX-03).+ "loras": list(p.get("loras") or []),},}push(f"Extend via helper: id={job['id']} src={Path(src).name} +{p['extend_frames']}f · "@@ -29529,12 +31040,9 @@ def run_job_inner(job: dict) -> None:# during the upscale + VAE-encoder reload). On standard tier we# clamp to 768; on high tier we go to 1024; pro tier has no clamp.kf_max = tier_max_dim("keyframe")- KF_ALIGN = 32req_w, req_h = p["width"], p["height"]if kf_max and max(req_w, req_h) > kf_max:- scale = kf_max / max(req_w, req_h)- width = max(KF_ALIGN, int(round(req_w * scale / KF_ALIGN)) * KF_ALIGN)- height = max(KF_ALIGN, int(round(req_h * scale / KF_ALIGN)) * KF_ALIGN)+ width, height = ltx_fit_canvas(req_w, req_h, kf_max)push(f"Keyframe: clamping {req_w}×{req_h} → {width}×{height} "f"({SYSTEM_CAPS['label']} tier — {kf_max} max-side keeps "@@ -29603,6 +31111,8 @@ def run_job_inner(job: dict) -> None:"cfg_scale": 3.0,"memory_policy": memory_plan["effective"],"vae_full_decode_max_frames": memory_plan["full_decode_max_frames"],+ # Attached by get_kf_pipe (LTX-03: never sent before).+ "loras": list(p.get("loras") or []),},}push(f"Run KEYFRAME via helper: id={job['id']} {width}x{height} {frames}f · Q8 two-stage (stage1=20)")@@ -29660,16 +31170,34 @@ def run_job_inner(job: dict) -> None:model_dir = str(pack_path("q4"))default_stage1 = 8default_stage2 = 3+ # Before any preparation: a refusal costs nothing (a2v_max_frames).+ _a2v_cap = a2v_max_frames()+ if _a2v_cap and int(p["frames"]) > _a2v_cap:+ raise RenderRefused("hardware_tier",+ a2v_length_refusal(int(p["frames"]), _a2v_cap))ltx_pack_preflight("q8" if uses_q8 else "q4", "Audio to Video")audio_src = (p.get("audio") or "").strip()if not audio_src or not Path(audio_src).exists():raise RuntimeError(f"audio file not found: {audio_src}")+ # THE TWO AUDIO FILES. `cond_audio` is what the model listens to and+ # `audio_src` is what the finished clip plays; they are the same file+ # unless a vocal stem was asked for.+ cond_audio, stem_note = a2v_conditioning_audio(p, audio_src)+ if stem_note:+ push(f"[a2v] {stem_note}")width, height = int(p["width"]), int(p["height"])- # Clamp resolution by tier cap (no-op when tier_max_dim returns 0).+ # Clamp resolution by tier cap (no-op when tier_max_dim returns 0):+ # proportionally, on the /64 grid, and recorded on the job, so the+ # helper, the sidecar and the history all name the canvas that+ # rendered (LTX-06 — it used to cap each side on its own and keep+ # the requested size in the metadata).max_dim = tier_max_dim("t2v")- if max_dim:- width = min(width, max_dim)- height = min(height, max_dim)+ if max_dim and max(width, height) > max_dim:+ new_w, new_h = ltx_fit_canvas(width, height, max_dim)+ push(f"A2V: clamping {width}×{height} → {new_w}×{new_h} "+ f"({SYSTEM_CAPS['label']} tier, {max_dim} max side).")+ width, height = new_w, new_h+ p["width"], p["height"] = width, heightframes = int(p["frames"])desc_stem = _descriptive_filename(p.get("label") or "", p.get("prompt") or "", fallback="a2v"@@ -29714,7 +31242,7 @@ def run_job_inner(job: dict) -> None:"prompt": p["prompt"],"negative_prompt": p.get("negative_prompt", ""),"output_path": str(out_path),- "audio_path": audio_src,+ "audio_path": cond_audio,"image": ref_image_path,"height": height,"width": width,@@ -29731,10 +31259,13 @@ def run_job_inner(job: dict) -> None:# the key was absent (#46)."audio_start_time": max(0.0, float(p.get("audio_start_time", 0.0) or 0.0)),}+ # Both lanes attach the stack. Only Q8 used to receive it, so the+ # same selection silently vanished when this Mac (or a missing High+ # add-on) put the render on the Q4 distilled lane (LTX-03).+ a2v_params["loras"] = a2v_lorasif uses_q8:a2v_params["cfg_scale"] = float(p.get("cfg_scale", 3.0))a2v_params["stg_scale"] = float(p.get("stg_scale", 1.0))- a2v_params["loras"] = a2v_lorasjob_spec = {"action": action, "id": job["id"], "params": a2v_params}# Only mention the offset when it is actually non-zero — a "start=0.00s"# on every line would be noise, but when it IS set the log is the only@@ -29752,7 +31283,8 @@ def run_job_inner(job: dict) -> None:push(f"Run A2V ({'Q8' if uses_q8 else 'Q4-distilled'}) via helper: "f"id={job['id']} {width}x{height} {frames}f · "- f"audio={Path(audio_src).name}"+ f"audio={Path(cond_audio).name}"+ f"{' (stem; the song is muxed back)' if cond_audio != audio_src else ''}"f"{' image=' + Path(ref_image_path).name if ref_image_path else ''}"f" scale={a2v_params['audio_conditioning_scale']}{_scale_note}"f"{_start_note}"@@ -29761,9 +31293,32 @@ def run_job_inner(job: dict) -> None:if "seed_used" in result:push(f"seed used: {result['seed_used']}")p["seed_used"] = result["seed_used"]+ # The pipeline muxed whatever it listened to. When that was a stem the+ # clip is playing an a-cappella, so the original goes back over it —+ # video stream copied, same seconds of the song the shot was rendered+ # against (Maestro's seam: condition on the stem, deliver the record).+ if cond_audio != audio_src:+ try:+ a2v_mux_original_audio(+ out_path, audio_src,+ start=a2v_params["audio_start_time"],+ duration=video_duration(frames))+ push("[a2v] the original song was muxed back over the clip")+ except JobCancelled:+ # Stop during the remux. What is on disk is the clip the model+ # sang against - it plays the a-cappella until this step puts+ # the record back - so a cancelled remux may not be filed as a+ # finished take (Codex review, 2026-09-22).+ push("[a2v] stopped before the original song was muxed back")+ raise+ except Exception as exc: # noqa: BLE001+ push(f"[a2v] could not mux the original song back ({exc}) — "+ f"this clip plays the vocal stem")sidecar = {"output": str(out_path), "raw_output": str(out_path),"params": {**p, "command": action, "audio": audio_src,+ "audio_conditioning": cond_audio,+ "audio_stem_used": cond_audio != audio_src,"image": ref_image_path},# The number the engine actually ran with. `params` keeps what# the caller sent — blank when the slider was on Auto — so a@@ -29945,9 +31500,7 @@ def run_job_inner(job: dict) -> None:# Standard / high / pro tiers pass full user-requested W×H through.t2v_max = tier_max_dim("t2v" if mode == "t2v" else "i2v")if t2v_max and max(width, height) > t2v_max:- scale = t2v_max / max(width, height)- new_w = max(32, (int(round(width * scale)) // 32) * 32)- new_h = max(32, (int(round(height * scale)) // 32) * 32)+ new_w, new_h = ltx_fit_canvas(width, height, t2v_max)push(f"{mode.upper()}: clamping {width}×{height} → {new_w}×{new_h} "f"({SYSTEM_CAPS['label']} tier — keeps you out of swap)."@@ -30308,6 +31861,17 @@ def run_job_inner(job: dict) -> None:# while the take was still forming (the chain never removed it).# The chain writes `raw_out` itself once the last window is trimmed.job_spec["params"]["frames"] = windows_plan["window"]+ # WINDOW 1 RENDERS ITS OWN LINE (LTX-08). The prompt list was only+ # resolved inside _run_windows_chain, AFTER this pass, which then+ # started at window 2 — so an opening line that differed from the+ # main prompt was saved as prompts[0] and never rendered. Resolved+ # here from the same inputs (window_prompts is a pure function), so+ # this pass, the chain and the sidecar name the same list.+ import ltx_windows as _lw # noqa: PLC0415+ job_spec["params"]["prompt"] = _lw.window_prompts(+ p.get("prompt") or "", p.get("window_prompts") or [],+ invariants=p.get("window_invariants") or "",+ count=windows_plan["count"])[0]_w0_dir = OUTPUT / ".windows" / str(job.get("id") or "take")_w0_dir.mkdir(parents=True, exist_ok=True)job_spec["params"]["output_path"] = str(_w0_dir / (raw_out.stem + "_w0" + raw_out.suffix))@@ -30400,9 +31964,13 @@ def run_job_inner(job: dict) -> None:upscale_method = (p.get("upscale_method", "lanczos") or "lanczos").strip().lower()if upscale_method == "model":upscale_method = "pipersr"- upscaled_out = OUTPUT / (- f"{final_target.stem}_{upscale_plan['tag']}{final_target.suffix}"- )+ # UNIQUE, like the native path above it. The bare "<stem>_<tag>" name+ # collided with any earlier output that already carried it — a+ # "scene_720p" render, or a "scene" render's own export — and the+ # `ffmpeg -y` below then overwrote that video, and write_sidecar its+ # record: somebody else's clip and its provenance, gone (JOB-01).+ upscaled_out = _unique_output_path(+ OUTPUT, f"{final_target.stem}_{upscale_plan['tag']}", final_target.suffix)if upscale_method == "pipersr":push("Sharp upscale: PiperSR/CoreML 2× pass, then ffmpeg fit/export.")run_pipersr_tracked(@@ -30614,12 +32182,56 @@ def _push_job_done(job: dict) -> None:push(f"[push] skipped: {exc}")+def _external_build_hold() -> str:+ """Why the worker must not start a job right now, or "".++ scripts/pinokio/h3_build_q8.sh loads the ~20 GB compact H3 engine from a+ Pinokio shell, outside this process, and the sidebar offers it while the+ panel runs. It used to wait only for the job already running, so the next+ queued render started beside that load on a 36-59 GB Mac (Codex H3-02).+ The build now writes STATE_DIR/h3_build.lock for its whole duration. A+ lock whose pid is gone (the build was killed past its trap) or that is+ older than four hours holds nothing: a stale file must never wedge the+ queue."""+ lock = STATE_DIR / "h3_build.lock"+ try:+ raw = lock.read_text(encoding="utf-8")+ age = time.time() - lock.stat().st_mtime+ except OSError:+ return ""+ if age > 4 * 3600:+ return ""+ try:+ rec = json.loads(raw)+ pid = int(rec.get("pid") or 0)+ except (ValueError, TypeError, AttributeError):+ rec, pid = {}, 0+ if pid > 0:+ try:+ os.kill(pid, 0)+ except ProcessLookupError:+ return ""+ except OSError:+ pass+ return str(rec.get("what") or "an engine build")++def worker_loop() -> None:+ held_note = ""while True:with QUEUE_COND:- while not STATE["queue"] or STATE["paused"]:+ while True:if not STATE["queue"] and not STATE["current"]:caffeinate_off()+ if STATE["queue"] and not STATE["paused"]:+ hold = _external_build_hold()+ if not hold:+ held_note = ""+ break+ if hold != held_note:+ held_note = hold+ push(f"Queue held: {hold} is loading a large model. "+ f"The next render starts when it finishes.")QUEUE_COND.wait(timeout=2)job = STATE["queue"].pop(0)job["status"] = "running"@@ -30630,6 +32242,9 @@ def worker_loop() -> None:STATE["log"] = []caffeinate_on()persist_queue()+ # A settings record a full disk kept from an earlier job (write_sidecar)+ # is written now, before this render can fill the disk again.+ retry_pending_sidecars()# The funnel's last rung, recorded where every path converges: eight# call sites append to the queue, exactly one worker takes from it.# "They pressed Render at least once" is the difference between an@@ -30955,6 +32570,7 @@ def _auto_promote_image_engine_kind("lightx2v/Qwen-Image-Edit-2511-Lightning:Qwen-Image-Edit-2511-Lightning-4steps-V1.0-bf16.safetensors"]overrides["mflux_lora_scales"] = [1.0]+ overrides["mflux_guidance"] = 1.0 # Lightning recipe (UI-03)return agent_image_engine.ImageEngineConfig(**{**cur.__dict__, **overrides})@@ -31045,6 +32661,9 @@ def _build_image_engine_config("lightx2v/Qwen-Image-Edit-2511-Lightning:Qwen-Image-Edit-2511-Lightning-4steps-V1.0-bf16.safetensors"],mflux_lora_scales=[1.0],+ # Lightning is distilled without CFG: 1.0, not the family's 4.0+ # (Codex UI-03 — this preset sent --guidance 4.0).+ mflux_guidance=1.0,)if engine_override == "qwen_edit_inline":# Qwen MEDIUM — 8-step Q6, no LoRA, no CFG. Sits between Fast's@@ -31650,14 +33269,15 @@ from panel import routes_loras as _routes_lorasfrom panel import routes_meta as _routes_metafrom panel import routes_oneshot as _routes_oneshotfrom panel import routes_models as _routes_models+from panel import routes_music as _routes_musicfrom panel import routes_queue as _routes_queuefrom panel import routes_storyboard as _routes_storyboardfrom panel import routes_stats as _routes_statsfrom panel import routes_train as _routes_trainfor _routes_mod in (_routes_characters, _routes_files, _routes_image,- _routes_loras, _routes_meta, _routes_models, _routes_oneshot,- _routes_queue, _routes_stats, _routes_storyboard,+ _routes_loras, _routes_meta, _routes_models, _routes_music,+ _routes_oneshot, _routes_queue, _routes_stats, _routes_storyboard,_routes_train):_routes_mod.P = sys.modules[__name__]@@ -32082,8 +33702,23 @@ class Handler(BaseHTTPRequestHandler):# THE MACHINE'S OWN CUT. It lands in the automatic lane so a# user walking back through his work meets his decisions# first, not the auto-editor's.- sedit.save_edit(bdir, edit, origin="auto")+ #+ # AND ONLY OVER NOTHING. The analysis above decodes every clip+ # and can take a while; a second tab (or an API client) that+ # finished its own first load and saved a cut by hand in that+ # window used to be overwritten by this unguarded write. So+ # it is a compare-and-swap against "no file": if somebody got+ # there first, their document is the answer (SB5-07).+ sedit.save_edit(bdir, edit, origin="auto", expect=0)edit = sedit.load_edit(bdir)+ except sedit.EditConflict:+ fresh = False+ try:+ edit = sedit.load_edit(bdir)+ except sedit.EditError as exc:+ self._json({"ok": False, "error": str(exc),+ "corrupt": True}, 500)+ return Trueexcept sedit.EditError as exc:self._json({"ok": False,"error": f"auto-edit refused: {exc}"}, 500)@@ -32148,10 +33783,7 @@ class Handler(BaseHTTPRequestHandler):except Exception:bid = ""if not bid:- bid = "sb_%s_%s" % (time.strftime("%Y%m%d"),- hashlib.sha1(- (concept + str(time.time())).encode()- ).hexdigest()[:6])+ bid = _sb_new_id(concept)board = storyboard.new_storyboard(bid, "Planning…")# new_storyboard() hands back storyboard.DEFAULT_POLICY —# 1024x576 delivery, no tier clamp, and not the user's saved@@ -32534,28 +34166,36 @@ class Handler(BaseHTTPRequestHandler):# Remove ONLY this board's queued jobs, through the same code# path removeJob(id) uses. Never /queue/clear — another# feature's jobs may be in there.+ #+ # THE ANCHOR STILLS ARE THIS FILM'S JOBS TOO (SB5-09). They+ # were left out, so a Stop during the still batch left every+ # image job queued and the running one on the GPU while the+ # screen said the film had stopped.mine = set()+ stills = set()for s in (board.get("shots") or []):if not isinstance(s, dict):continuefor k in ("draft_job_id", "final_job_id"):if s.get(k):mine.add(s[k])- removed = 0- with QUEUE_COND:- before = len(STATE["queue"])- STATE["queue"] = [j for j in STATE["queue"] if j.get("id") not in mine]- removed = before - len(STATE["queue"])- QUEUE_COND.notify_all()- persist_queue()+ sj = s.get("still_job_id")+ if sj and sj != "skipped" and not s.get("still"):+ mine.add(sj)+ stills.add(sj)# ...and cancel the shot ALREADY RENDERING, through the panel's# own /stop path. Dropping the queue alone left an H3 shot# burning the GPU for another 20 minutes after the user had# been told the film stopped.- cancelled = _sb_cancel_running_shot(mine)+ removed, cancelled = _sb_withdraw_jobs(mine)for s in (board.get("shots") or []):if isinstance(s, dict) and s.get("status") in ("queued",):s["status"] = "pending"+ # A withdrawn still is owed again: without this the next+ # Render would skip it ("already has a still job") and+ # render the shot unanchored.+ if isinstance(s, dict) and s.get("still_job_id") in stills:+ s.pop("still_job_id", None)# The cancelled shot is deliberately NOT rewritten here. The# worker is still unwinding the kill; its job goes terminal a# moment later and _sb_reconcile() folds that verdict onto the@@ -32629,8 +34269,7 @@ class Handler(BaseHTTPRequestHandler):meta = {}params = meta.get("params") or {}if bid in ("", "new"):- bid = "sb_%s_%s" % (time.strftime("%Y%m%d"),- hashlib.sha1(str(time.time()).encode()).hexdigest()[:6])+ bid = _sb_new_id()board = storyboard.new_storyboard(bid, "Untitled film")board["policy"] = _sb_policy_for(get_settings().get("storyboard_draft_quality", "quick"),@@ -33156,6 +34795,26 @@ class Handler(BaseHTTPRequestHandler):current = {}on_disk = int(current.get("revision") or 0)expect = payload.get("expect_revision")+ # WHICH DRAFT the client believes it is saving. Revisions+ # restart per draft, so the revision alone let a stale tab+ # save draft A's arrangement into a just-duplicated draft+ # B (SB5-04). Absent or empty = a client that predates the+ # field: unchecked, as before.+ want_draft = payload.get("draft")+ want_draft = (want_draft.strip()+ if isinstance(want_draft, str) else "") or None+ if want_draft:+ active = sedit.load_draft_index(+ _sbe_board_dir(bid))["active"]+ if want_draft != active:+ self._json({"ok": False, "conflict": True,+ "draft_conflict": True,+ "active_draft": active,+ "revision": on_disk,+ "error": f"this film is on the draft "+ f"{active!r} now, not "+ f"{want_draft!r}"}, 409)+ returnif expect is not None and int(expect) != on_disk:self._json({"ok": False, "conflict": True,"revision": on_disk,@@ -33194,15 +34853,18 @@ class Handler(BaseHTTPRequestHandler):f"{on_disk} (last write wins)")try:sedit.save_edit(_sbe_board_dir(bid), incoming,- expect=expect)+ expect=expect, expect_draft=want_draft)except sedit.EditConflict as exc:# THE RACE, CAUGHT AT THE WRITE. Same body the# sequential case produces, because to the tab that# lost it is the same event: somebody else is ahead,# your arrangement is still on your screen.- self._json({"ok": False, "conflict": True,- "revision": exc.revision,- "error": str(exc)}, 409)+ out = {"ok": False, "conflict": True,+ "revision": exc.revision, "error": str(exc)}+ if exc.draft:+ out.update(draft_conflict=True,+ active_draft=exc.draft)+ self._json(out, 409)returnexcept sedit.EditError as exc:self._json({"ok": False, "error": str(exc)}, 400)@@ -33463,8 +35125,7 @@ class Handler(BaseHTTPRequestHandler):"error": "there is no timeline to ""export"}, 404)return- dest = _sb_film_dir(board)- dest.mkdir(parents=True, exist_ok=True)+ dest = _sb_film_dir_for_write(board)audio = edit.get("audio") or Noneif audio and not Path(str(audio.get("path") or "")).is_file():audio = None@@ -34188,7 +35849,7 @@ def _preview_progress(current: dict | None, remaining: float | None,trap — the user aborts a take that was going to be fine."""if not current:return {}- d = live_preview_dir(current.get("id") or "")+ d = live_preview_dir(live_preview_job_id(current))try:st = json.loads((d / "status.json").read_text())except (OSError, ValueError):@@ -34272,7 +35933,7 @@ def _h3_preview_progress(current: dict | None) -> dict:"""if not current or not h3_live_preview_ready():return {}- d = live_preview_dir(current.get("id") or "")+ d = live_preview_dir(live_preview_job_id(current))status_path = d / "status.json"try:st = json.loads(status_path.read_text())@@ -34437,6 +36098,9 @@ def page(theme: str = "") -> str:"train_min_images": TRAIN_MIN_IMAGES,"train_max_images": TRAIN_MAX_IMAGES,"generation_profile": GENERATION_PROFILE,+ # The longest a2v render this Mac accepts (0 = uncapped); the Audio+ # tab warns against the same number the worker refuses on.+ "a2v_max_frames": a2v_max_frames(),# Hardware-aware time estimates for the Quality pills. The pill HTML# ships with the Comfortable-tier defaults; on boot we rewrite the# subtext using the active tier's quality_times. Compact users seediff --git a/mlx_warm_helper.py b/mlx_warm_helper.pyindex 3e6d3ad..41b3b58 100644--- a/mlx_warm_helper.py+++ b/mlx_warm_helper.py@@ -24,6 +24,8 @@ import mathimport osimport randomimport sys++import music_tags as _music_tags # bare section tags, the way YuE2 reads themimport threadingimport timeimport traceback@@ -472,6 +474,7 @@ _a2v_lora_key: tuple | None = None # LoRA fingerprint for current A2V cache_a2v_weight_key: tuple[str, str] | None = None # (dev_transformer, distilled_lora) names_a2v_distilled_pipe = None # A2VidDistilledPipeline (Q4 distilled, no CFG)_a2v_distilled_model_dir = None+_a2v_distilled_lora_key: tuple | None = None_pipe_lock = threading.Lock()@@ -1874,10 +1877,12 @@ def get_hq_pipe(model_dir: str, loras: list[dict] | None = None,_kf_pipe = None_kf_model_dir = None_kf_weight_key: tuple[str, str] | None = None+_kf_lora_key: tuple | None = Nonedef get_kf_pipe(model_dir: str, dev_transformer: str | None = None,- distilled_lora: str | None = None):+ distilled_lora: str | None = None,+ loras: list[dict] | None = None):"""Returns the KeyframeInterpolationPipeline lazily.Keyframe REQUIRES explicit dev_transformer + distilled_lora at init time.@@ -1889,8 +1894,13 @@ def get_kf_pipe(model_dir: str, dev_transformer: str | None = None,filename carries its alpha/rank and that number changes with thegeneration (2.3: 384, 2.5: 450). The literals remain as the fallback so acaller that does not name them behaves exactly as before.++ User LoRAs ride the same `_pending_loras` hook as A2V's two-stage pipe (the+ same TI2VidTwoStagesPipeline base); they were never passed here, so an+ FFLF render with a style LoRA selected rendered without it while its+ sidecar listed it. The cache is keyed on the set so a change rebuilds."""- global _kf_pipe, _kf_model_dir, _kf_weight_key+ global _kf_pipe, _kf_model_dir, _kf_weight_key, _kf_lora_keyfrom ltx_pipelines_mlx.keyframe_interpolation import KeyframeInterpolationPipeline# Install the same runtime patches that get_pipe / get_hq_pipe / get_a2v_pipe@@ -1906,9 +1916,18 @@ def get_kf_pipe(model_dir: str, dev_transformer: str | None = None,dev_name = dev_transformer or "transformer-dev.safetensors"lora_name = distilled_lora or "ltx-2.3-22b-distilled-lora-384.safetensors"weight_key = (dev_name, lora_name)+ fp = _lora_fingerprint(loras)with _pipe_lock:release_pipelines(keep_kind="keyframe")- if _kf_pipe is None or _kf_model_dir != model_dir or _kf_weight_key != weight_key:+ if (_kf_pipe is None or _kf_model_dir != model_dir or _kf_weight_key != weight_key+ or _kf_lora_key != fp):+ if _kf_pipe is not None:+ _kf_pipe = None+ try:+ from ltx_core_mlx.utils.memory import aggressive_cleanup as _ac+ _ac()+ except Exception: # noqa: BLE001+ passemit({"event": "log", "line": f"Loading Keyframe pipeline (Q8 dev model — {model_dir})..."})_kf_pipe = KeyframeInterpolationPipeline(model_dir=model_dir,@@ -1918,8 +1937,10 @@ def get_kf_pipe(model_dir: str, dev_transformer: str | None = None,distilled_lora=lora_name,distilled_lora_strength=1.0,)+ _attach_loras(_kf_pipe, loras)_kf_model_dir = model_dir_kf_weight_key = weight_key+ _kf_lora_key = fpreturn _kf_pipe@@ -1994,13 +2015,19 @@ def get_a2v_pipe(model_dir: str, loras: list[dict] | None = None,return _a2v_pipe-def get_a2v_distilled_pipe(model_dir: str):+def get_a2v_distilled_pipe(model_dir: str, loras: list[dict] | None = None):"""Returns A2VidDistilledPipeline lazily.Q4-compatible distilled pipeline — no dev transformer, no CFG, 8+3 steps.Cached on model_dir so switching between Q4 and Q8 paths rebuilds.++ User LoRAs attach through `_pending_loras`, which its load() honours via+ the native `_load_transformer_with_optional_streaming` — the same route+ as a Q4 t2v render. They used to be dropped by the panel on this lane+ only, so the same selection changed meaning when Q8 fell back to Q4. The+ cache is keyed on the set (and the streaming decision it implies)."""- global _a2v_distilled_pipe, _a2v_distilled_model_dir+ global _a2v_distilled_pipe, _a2v_distilled_model_dir, _a2v_distilled_lora_keytry:from a2vid_distilled import A2VidDistilledPipelineexcept ModuleNotFoundError:@@ -2016,19 +2043,29 @@ def get_a2v_distilled_pipe(model_dir: str):_ac = lambda: Nonewith _pipe_lock:release_pipelines(keep_kind="a2v_distilled")- if _a2v_distilled_pipe is None or _a2v_distilled_model_dir != model_dir:+ fp = _lora_fingerprint(loras)+ if (_a2v_distilled_pipe is None or _a2v_distilled_model_dir != model_dir+ or _a2v_distilled_lora_key != fp):if _a2v_distilled_pipe is not None:- emit({"event": "log", "line": "model_dir changed; reloading A2V distilled pipeline."})+ why = ("LoRA set changed" if _a2v_distilled_model_dir == model_dir+ else "model_dir changed")+ emit({"event": "log", "line": f"{why}; reloading A2V distilled pipeline."})_a2v_distilled_pipe = None_ac()emit({"event": "log","line": f"Loading A2V distilled pipeline (Q4 — {model_dir})..."})- _a2v_distilled_pipe = A2VidDistilledPipeline(+ # Streams like the t2v/i2v/extend constructors on a small Mac;+ # a job with adapters keeps the unfused branch (_stream_for).+ _a2v_distilled_pipe = _construct_pipeline(+ A2VidDistilledPipeline,model_dir=model_dir,gemma_model_id=GEMMA_PATH,low_memory=LOW_MEMORY,+ low_ram_streaming=_stream_for(loras),)+ _attach_loras(_a2v_distilled_pipe, loras)_a2v_distilled_model_dir = model_dir+ _a2v_distilled_lora_key = fpreturn _a2v_distilled_pipe@@ -3733,7 +3770,8 @@ for line in sys.__stdin__:pipe = get_kf_pipe(model_dir,dev_transformer=p.get("dev_transformer"),- distilled_lora=p.get("distilled_lora"))+ distilled_lora=p.get("distilled_lora"),+ loras=p.get("loras") or [])# Y1.037: short-clip VAE-streaming opt-out (Keyframe path)._apply_vae_streaming_decision(num_frames)kwargs = dict(@@ -3940,7 +3978,7 @@ for line in sys.__stdin__:if not os.path.exists(audio_path):raise RuntimeError(f"audio file not found: {audio_path}")num_frames = int(p["frames"])- pipe = get_a2v_distilled_pipe(model_dir)+ pipe = get_a2v_distilled_pipe(model_dir, loras=p.get("loras") or [])_apply_vae_streaming_decision(num_frames)kwargs = dict(prompt=p["prompt"],@@ -4306,6 +4344,206 @@ for line in sys.__stdin__:_is_busy = Falsecontinue+ if action == "write_lyrics":+ # MUSIC STUDIO: Gemma writes lyrics from a concept. The same resident+ # Gemma 3 the enhancer uses, the same `_enhance` chat call underneath —+ # only the system prompt differs, and it is written around what YuE2+ # actually reads: bracketed section tags, one sung line per row, a tag+ # with nothing under it is an instrumental passage. The model is told+ # the style so the words fit the tempo and the register, and told the+ # target length so a 90-second song does not arrive with six verses.+ #+ # With `section` set it rewrites ONE section of a song the user already+ # has: the editor sends the label and that section's current lines, and+ # what comes back is the lines ALONE — no tag, no other sections —+ # because the editor owns the tag and drops the answer straight back+ # into the box it came from.+ job_id = msg.get("id", "?")+ p = msg.get("params", {}) or {}+ concept = (p.get("concept") or "").strip()+ style = (p.get("style") or "").strip()+ seconds = int(p.get("seconds") or 150)+ language = (p.get("language") or "").strip()+ section = (p.get("section") or "").strip().strip("[]")+ lines_in = (p.get("lines") or "").strip()+ seed = int(p.get("seed", 10))+ # A section rewrite can stand on the lines alone ("make this better"),+ # so the concept is only mandatory when there is nothing else to go on.+ if not concept and not (section and lines_in):+ emit({"event": "error", "id": job_id, "error": "empty concept"})+ continue+ _is_busy = True+ try:+ t0 = time.time()+ _mlx_mem_reset_run()+ lm = get_gemma_lm()+ verses = 2 if seconds < 120 else 3 if seconds < 210 else 4+ # The half of the brief that is about the words rather than the+ # shape — true whether we are writing the whole song or one part.+ craft = [+ "STYLE:",+ "- Concrete images over abstractions. No clichés about hearts on fire,",+ " broken wings, or the night sky unless the user asked for them.",+ "- The chorus is the hook: repeatable, memorable, the same words each",+ " time it returns.",+ "- Rhyme when it lands naturally; never force a rhyme with a weak line.",+ f"- Match this musical style: {style}." if style else "- Fit a contemporary song.",+ f"- Write in {language}." if language else "- Write in the language of the concept.",+ ]+ if section:+ system = "\n".join([+ "You are a professional lyricist reworking ONE section of a song.",+ f"Rewrite the [{section}] section. Nothing else in the song changes.",+ "",+ "FORMAT — follow exactly:",+ "- Output the sung lines only, one per row. No section tag, no square",+ " brackets, no title, no commentary, no quotation marks.",+ "- Short lines: 4 to 9 words. Keep about as many lines as you were",+ " given; one or two either way is fine.",+ "",+ *craft,+ ])+ user = "\n".join(x for x in [+ f"Concept: {concept}" if concept else "",+ f"The [{section}] section as it stands:",+ lines_in or "(empty — write it from nothing)",+ ] if x)+ else:+ system = "\n".join([+ "You are a professional lyricist writing for a song generator.",+ "Write complete, singable lyrics for the concept the user gives you.",+ "",+ "FORMAT — follow exactly, the generator parses it:",+ "- Section tags on their own line in square brackets: [Intro], [Verse],",+ " [Pre-Chorus], [Chorus], [Bridge], [Outro]. Use [Verse] and [Chorus]",+ " as the tag text every time (no numbering like [Verse 2]).",+ "- Under each tag, the sung lines, one per row. Short lines: 4 to 9 words.",+ "- A tag with NO lines under it is an instrumental passage. Use that for",+ " [Intro] and [Outro] unless the concept calls for words there.",+ f"- Length: about {verses} verses, a chorus that returns after each,",+ " optionally one bridge. Nothing else.",+ "",+ *craft,+ "",+ "OUTPUT: only the lyrics with their tags. No title, no commentary,",+ "no quotation marks, no explanation before or after.",+ ])+ user = f"Concept: {concept}"+ messages = [{"role": "system", "content": system},+ {"role": "user", "content": user}]+ text = lm._enhance(messages, max_new_tokens=300 if section else 700, seed=seed)+ # Strip a code fence or a leading title if the model added one.+ lines = [ln.rstrip() for ln in text.strip().splitlines()]+ lines = [ln for ln in lines if not ln.strip().startswith("```")]+ if section:+ # The editor owns the tag; one in the answer would end up+ # doubled in the box the answer lands in.+ lines = [ln for ln in lines+ if not (ln.strip().startswith("[") and ln.strip().endswith("]"))]+ while lines and not lines[0].strip():+ lines.pop(0)+ else:+ while lines and not lines[0].strip().startswith("["):+ lines.pop(0)+ lyrics = _music_tags.normalize_section_tags("\n".join(lines).strip())+ _last_activity = time.time()+ emit({"event": "done", "id": job_id, "lyrics": lyrics,+ "elapsed_sec": round(time.time() - t0, 2)})+ except Exception as exc:+ _last_activity = time.time()+ emit({"event": "error", "id": job_id, "error": str(exc), "trace": traceback.format_exc()})+ finally:+ _is_busy = False+ continue++ if action == "write_song":+ # MUSIC STUDIO, Simple mode: one description in, the whole brief out.+ # YuE2 reads two things — a style SENTENCE (language, genre, the+ # instruments, who sings and how, the tempo) and tagged lyrics — and a+ # person describing a song says all of it in one breath. One Gemma call+ # splits that breath into the two fields plus a title, and it answers+ # with a JSON object so the split is the model's job rather than a+ # regex's on this side: lyrics are multi-line, and every other+ # separator we could ask for is a character a lyric may contain.+ job_id = msg.get("id", "?")+ p = msg.get("params", {}) or {}+ description = (p.get("description") or "").strip()+ instrumental = bool(p.get("instrumental"))+ seconds = int(p.get("seconds") or 150)+ seed = int(p.get("seed", 10))+ if not description:+ emit({"event": "error", "id": job_id, "error": "empty description"})+ continue+ _is_busy = True+ try:+ t0 = time.time()+ _mlx_mem_reset_run()+ lm = get_gemma_lm()+ verses = 2 if seconds < 120 else 3 if seconds < 210 else 4+ words = [+ 'lyrics: the words with their section tags, as ONE JSON string with',+ ' \\n between lines. Tags alone on a line in square brackets:',+ ' [Intro], [Verse], [Pre-Chorus], [Chorus], [Bridge], [Outro] — that',+ ' exact text, never numbered. Under each tag the sung lines, one per',+ ' row, 4 to 9 words each. A tag with no lines under it is an',+ f' instrumental passage. About {verses} verses and a chorus that',+ ' returns after each of them.',+ ] if not instrumental else [+ 'lyrics: "" — an empty string. This one has no singing at all, so',+ ' the style sentence carries the whole song.',+ ]+ system = "\n".join([+ "You are a music producer turning one sentence from a client into the",+ "two things a song generator reads.",+ "",+ "Answer with ONE JSON object and nothing else — no code fence, no",+ "commentary before or after:",+ '{"title": "...", "style": "...", "lyrics": "..."}',+ "",+ "title: two to five words. No quotation marks inside it.",+ "style: ONE sentence of prose, not a list of fields — the language, the",+ " genre, the lead instruments, who sings and how, and the tempo in BPM.",+ ' Like: "English, warm piano pop, expressive female voice, acoustic',+ ' piano, light drums, 88 BPM".',+ *words,+ "",+ "Take what the client gave you and fill in the rest as a producer would:",+ "concrete images over abstractions, a chorus that is the hook, rhyme",+ "only where it lands. Write in the language the client used unless they",+ "asked for another.",+ ])+ messages = [{"role": "system", "content": system},+ {"role": "user", "content": description}]+ text = lm._enhance(messages, max_new_tokens=900, seed=seed)+ # The object, however it is wrapped. A fence, a "Sure — here you+ # go", a trailing note: all of it lives outside the braces.+ i, j = text.find("{"), text.rfind("}")+ data = json.loads(text[i:j + 1]) if i >= 0 and j > i else {}+ if not isinstance(data, dict):+ raise ValueError("the model did not answer with a JSON object")+ style = str(data.get("style") or "").strip()+ title = str(data.get("title") or "").strip().strip('"')+ lyrics = "" if instrumental else str(data.get("lyrics") or "").strip()+ if lyrics:+ # Same rule as write_lyrics: anything before the first tag is a+ # title or an apology, and the generator would sing it.+ lines = [ln.rstrip() for ln in lyrics.splitlines()]+ while lines and not lines[0].strip().startswith("["):+ lines.pop(0)+ lyrics = "\n".join(lines).strip()+ if not style:+ raise ValueError("the model returned no style")+ _last_activity = time.time()+ emit({"event": "done", "id": job_id, "title": title, "style": style,+ "lyrics": _music_tags.normalize_section_tags(lyrics),+ "elapsed_sec": round(time.time() - t0, 2)})+ except Exception as exc:+ _last_activity = time.time()+ emit({"event": "error", "id": job_id, "error": str(exc), "trace": traceback.format_exc()})+ finally:+ _is_busy = False+ continue+if action == "enhance_prompt":# Gemma-driven prompt rewriting. Same model file as the pipeline's# text encoder, but loaded as a `GemmaLanguageModel` (the wrapperdiff --git a/music_tags.py b/music_tags.pynew file mode 100644index 0000000..3bc2309--- /dev/null+++ b/music_tags.py@@ -0,0 +1,34 @@+"""Section tags the way YuE2 reads them.++Gemma numbers its sections — "[Verse 1]", "[Chorus 2]" — no matter how the+prompt asks, and it invents "[Hook]" and "[Solo]". YuE2's lyrics protocol reads+BARE tags, and the studio's label pills are a closed list of them. So every+lyrics-producing path normalises once, deterministically, here — rather than+hoping the next model version obeys a prompt.+"""+from __future__ import annotations++import re++CANON = ("Intro", "Verse", "Pre-Chorus", "Chorus", "Bridge", "Instrumental", "Outro")+_ALIASES = {+ "intro": "Intro", "verse": "Verse", "prechorus": "Pre-Chorus", "chorus": "Chorus",+ "refrain": "Chorus", "hook": "Chorus", "bridge": "Bridge", "instrumental": "Instrumental",+ "interlude": "Instrumental", "solo": "Instrumental", "break": "Instrumental",+ "outro": "Outro", "ending": "Outro", "coda": "Outro",+}+_TAG_RX = re.compile(r"^[ \t]*\[[ \t]*([A-Za-z][A-Za-z \-]*?)[ \t]*\d*[ \t]*\][ \t]*$", re.MULTILINE)+++def canonical_tag(name: str) -> str | None:+ """"Pre-Chorus 2" -> "Pre-Chorus"; "hook" -> "Chorus"; unknown -> None."""+ key = re.sub(r"[^a-z]", "", (name or "").lower())+ return _ALIASES.get(key)+++def normalize_section_tags(text: str) -> str:+ """Rewrite every tag line to its bare canonical form; leave lines alone."""+ def fix(m):+ canon = canonical_tag(m.group(1))+ return f"[{canon}]" if canon else m.group(0)+ return _TAG_RX.sub(fix, text or "")diff --git a/music_video.py b/music_video.pynew file mode 100644index 0000000..8ef57c5--- /dev/null+++ b/music_video.py@@ -0,0 +1,1260 @@+"""Music video — a song and a set of pictures become a shot list.++THE WHOLE IDEA IS THAT THE SONG IS THE CLOCK. Everything the panel needs to+shoot a music video already exists: `a2v` renders a singing clip from one+picture and one stretch of a waveform (`audio_start_time`), `i2v` renders+B-roll from a still, `storyboard_edit.beat_map` says where the bars are, and+the storyboard machinery renders, reconciles and assembles a list of shots.+What was missing is the thing in between — a plan that says WHICH second of+the song each picture is looking at.++Two pure functions, in the order the pipeline runs them:++ `song_sections` — the song's own structure: vocal stretches and+ instrumental ones, in seconds.+ `plan_music_video` — those sections plus the cast of pictures, as a+ storyboard board the existing render/film path runs.++PURE ON PURPOSE. Nothing here imports the panel, touches the queue, or writes+a file: the planner is the part that has to be right before an hour of GPU+time is spent, so it must be testable with a synthetic WAV and no weights.+`storyboard` (stdlib-only) is imported for the frame grid; `storyboard_edit`+and numpy are imported lazily inside the one function that analyses audio, the+same way the panel defers them, so a caller that only plans pays for neither.++THE ONE INVARIANT, and every number below exists to keep it: the shots TILE+THE SONG, in order, with no gaps and no overlaps, and a singing shot's+`audio_start_time` is its own start in that tiling. Concatenate the rendered+clips, lay the song underneath from 0:00, and every mouth is on its own words.+That is why `film_start` is accumulated from the FRAME-EXACT durations rather+than from the section boundaries: a frame count lands on LTX's 8k+1 grid, so+a 4.30 s B-roll shot is really 4.375 s, and a planner that ignored the 75 ms+would have the last singing shot of a three-minute song lip-syncing to the+wrong line.+"""+from __future__ import annotations++import math+import re++import storyboard++# ---------------------------------------------------------------------------+# THE CAST — what a picture is for+# ---------------------------------------------------------------------------+#: Closed vocabulary. A Singer picture is a face that can be filmed singing+#: (a2v); Instrument and Room are B-roll (i2v). Three words, because the user+#: is tagging photographs on a drop area, not writing a shot list.+ROLES = ("singer", "instrument", "room")++#: Where a B-roll picture is pinned, if anywhere. "open" is the film's first+#: B-roll shot and "close" its last — the two slots a person actually has an+#: opinion about, because they are the ones an audience reads as a decision.+#: Everything else is "any" and takes its turn in the weighted rotation.+USES = ("open", "close", "any")++#: A picture's share of the rotation. Capped because a weight is a hint about+#: taste and a four-figure one is a typo that would build a ring of that many+#: entries.+MAX_WEIGHT = 20++#: The line each role contributes to a prompt, per what the shot is doing.+#: Plain English, no jargon: these get pasted in front of the user's one+#: "Look" line and the result has to read like a direction, not a config.+ROLE_LINES = {+ ("singer", "singing"): "close-up, singing to camera",+ # A Singer picture can still be B-roll — when there is nothing else to cut+ # to, or in the instrumental. It must NOT say "singing" there: the mouth+ # has no waveform driving it on an i2v shot.+ ("singer", "broll"): "close-up, still, eyes down between lines",+ ("instrument", "broll"): "hands on the piano keys, slow push-in",+ ("room", "broll"): "wide, small room, warm light",+}++# ---------------------------------------------------------------------------+# THE DURATION AXIS+# ---------------------------------------------------------------------------+#: The LTX length cells as (seconds, frames), longest first.+#:+#: THE PANEL OWNS THE REAL TABLE (`LTX_LENGTHS`) and the routes hand it in via+#: `cells_from_lengths()`, so at runtime there is exactly one source of truth.+#: This default exists because this module must plan with no panel in the+#: process (a unit test, a CLI, a machine with no weights) — and it states only+#: the SECONDS: the frame count is derived by `storyboard.ltx_frames_for`, the+#: same function `shot_to_job` uses, so the two cannot disagree about a cell.+#: `test_music_video.py` pins this tuple against the panel's own table.+LTX_CELL_SECONDS = (20, 10, 7, 5, 3)+LTX_CELLS = tuple((s, storyboard.ltx_frames_for(s)) for s in LTX_CELL_SECONDS)++#: A cell that is NOT available on every canvas, and the qualities it is.+#:+#: This mirrors the `qualities` column of the panel's own `LTX_LENGTHS`, and+#: `test_music_video.py` pins the two together. It exists because the cell set+#: is only half the duration axis: 20 s / 481 frames renders at 640×480 and+#: DIES AROUND FRAME 454 on the standard 1024×576 canvas (issue #46), so the+#: panel offers it on Quick alone. A planner that read the seconds and ignored+#: this column wrote 481-frame a2v shots onto a board whose delivery pass is+#: Standard — an hour of render per shot that cannot finish.+LTX_CELL_QUALITIES = {20: ("quick",)}++#: The pass a plan is made for when the caller does not name one. The board's+#: FINAL pass is what delivers the film and the panel ships it as "standard",+#: so an unqualified plan is planned for that canvas — the conservative half+#: of the choice, because a cell that is missing costs a cut and a cell that+#: cannot render costs the shot.+DEFAULT_QUALITY = "standard"++# The shortest shot the board will keep as planned (see plan_music_video).+MIN_SHOT_S = 1.0+FPS = storyboard.LTX_FPS++#: A vocal stretch is filmed in windows this long; a B-roll shot is this long.+#: The singing window's floor is what makes a singing shot worth its render —+#: below ten seconds the cut rate reads as a montage, not a performance.+SINGING_WINDOW = (10, 20)+BROLL_WINDOW = (3, 7)++#: Phrase length when the song has no score to read: eight bars is the unit+#: nearly all of this material is written in, and a phrase that straddles a+#: real section edge is fixed by the energy classifier, not by the grid.+PHRASE_BARS = 8++#: The band a voice lives in, and how much of the track's energy has to be in+#: it before a phrase counts as sung. Deliberately crude — it decides whether+#: a stretch gets a face or a piano, and a wrong call costs one shot, not the+#: film. The threshold is a ratio so it is level-independent.+VOCAL_BAND_HZ = (1000.0, 4000.0)+VOCAL_BAND_RATIO = 0.18+++class MusicVideoError(Exception):+ """Raised when a song or a cast cannot be planned. Message is user-facing."""+++# ---------------------------------------------------------------------------+# PART A — the song's own structure+# ---------------------------------------------------------------------------+# A YuE2 song knows more about itself than any analyser could work out: the+# sidecar carries the LYRICS (bracket tags, a bare tag meaning instrumental)+# and the SCORE (`M:` meter, `Q:` tempo, `% section` comments, bars between+# pipes). Bars times tempo is the section boundary, exactly, with no signal+# processing at all. Everything below the score path is the fallback for a+# song that came from anywhere else.++_ABC_SECTION_RE = re.compile(r"^%(?!%)\s*(.+?)\s*$")+_ABC_VOICE_RE = re.compile(r"^V:\s*(\S+)")+_ABC_MULTIREST_RE = re.compile(r"^Z(\d*)$")+_LYRIC_TAG_RE = re.compile(r"^\s*\[([^\]]+)\]\s*$")+++def _tempo_seconds_per_bar(headers: dict) -> float | None:+ """Seconds per bar from an ABC header block, or None when it cannot say.++ `M:` is the meter as a fraction of a whole note per bar; `Q:` is a note+ length and how many of them fit in a minute (`Q:1/4=128`), or a bare+ number meaning quarter notes per minute. Both forms appear in the wild and+ YuE2 writes the first.+ """+ meter = str(headers.get("M") or "").strip()+ tempo = str(headers.get("Q") or "").strip()+ if not meter or not tempo:+ return None+ try:+ if meter.upper() in ("C", "C|"):+ num, den = (4, 4) if meter.upper() == "C" else (2, 2)+ else:+ num, den = (int(x) for x in meter.split("/", 1))+ quarters_per_bar = 4.0 * num / den+ except (ValueError, ZeroDivisionError):+ return None+ try:+ if "=" in tempo:+ note, per_min = tempo.split("=", 1)+ a, b = (int(x) for x in note.strip().split("/", 1))+ per_min = float(per_min)+ # One of those notes lasts 60/per_min seconds; a quarter is 1/4 of+ # a whole note, the note is a/b of one.+ sec_per_quarter = (60.0 / per_min) * (b / (4.0 * a))+ else:+ sec_per_quarter = 60.0 / float(tempo)+ except (ValueError, ZeroDivisionError):+ return None+ if not (sec_per_quarter > 0) or not (quarters_per_bar > 0):+ return None+ return quarters_per_bar * sec_per_quarter+++def _count_bars(line: str) -> int:+ """Bars on one ABC music line, multi-measure rests expanded.++ `Z4|` is four bars of silence written as one token — the Ins staff is full+ of them — so counting pipes alone undercounts a section by most of it.+ """+ n = 0+ for tok in line.split("|"):+ tok = tok.strip()+ if not tok:+ continue+ m = _ABC_MULTIREST_RE.match(tok)+ n += int(m.group(1) or 1) if m else 1+ return n+++def score_sections(score_abc: str) -> tuple[list[dict], float | None]:+ """The score's own sections — `([{name, bars}], seconds_per_bar)`.++ Bars are counted PER VOICE and the longest voice wins: the two staves+ carry the same bars, but either one can be written sparsely (the melody as+ rests, the accompaniment as `Z8`), and the longer count is the one that is+ complete. A score with no `%` comments comes back as one unnamed section+ holding every bar, which is still a usable total.+ """+ headers: dict[str, str] = {}+ sections: list[dict] = []+ cur_name, cur_voice = "", ""+ per_voice: dict[str, int] = {}+ in_body = False++ def close() -> None:+ if per_voice:+ sections.append({"name": cur_name, "bars": max(per_voice.values())})+ per_voice.clear()++ for raw in str(score_abc or "").splitlines():+ line = raw.strip()+ if not line:+ continue+ if not in_body:+ m = re.match(r"^([A-Za-z]):\s*(.*)$", line)+ if m and len(m.group(1)) == 1:+ headers.setdefault(m.group(1), m.group(2).strip())+ # K: is the last header line in ABC — the body starts after it.+ if m.group(1) == "K":+ in_body = True+ continue+ continue+ sm = _ABC_SECTION_RE.match(line)+ if sm:+ close()+ cur_name, cur_voice = sm.group(1).strip().lower(), ""+ continue+ vm = _ABC_VOICE_RE.match(line)+ if vm:+ cur_voice = vm.group(1)+ continue+ if line.startswith(("%", "w:", "W:")):+ continue+ per_voice[cur_voice] = per_voice.get(cur_voice, 0) + _count_bars(line)+ close()+ return ([s for s in sections if s["bars"] > 0],+ _tempo_seconds_per_bar(headers))+++def lyric_sections(lyrics: str) -> list[dict]:+ """The lyrics' section tags in order — `[{name, vocal}]`.++ YuE2's own format: a bracket tag opens a section and the lines under it are+ what is sung there. A BARE TAG — nothing but the next tag after it — is how+ the format spells "instrumental", so `vocal` is simply "did anybody write+ words here".+ """+ out: list[dict] = []+ for raw in str(lyrics or "").splitlines():+ m = _LYRIC_TAG_RE.match(raw)+ if m:+ name = m.group(1).strip().lower()+ # "[Verse 2]" and "[Verse]" are the same kind of place.+ out.append({"name": re.sub(r"\s*\d+$", "", name), "vocal": False})+ elif raw.strip() and out:+ out[-1]["vocal"] = True+ return out+++def tempo_disagreement(beats, score_abc, *, meter: int = 4,+ tolerance: float = 0.06) -> str | None:+ """A sentence when the score's written tempo and the audio's disagree.++ THE SCORE IS A PLAN AND THE AUDIO IS A PERFORMANCE, and YuE2 does not+ promise they land on the same tempo — the `Q:` header is what the composer+ wrote, the beat map is what came out of the vocoder. When the two agree,+ section boundaries derived from bars are exact to the millisecond. When+ they do not, they are still the best structure anybody has (the ORDER and+ the RELATIVE lengths of the sections are right either way) and the times+ stretch or squash. That is worth a sentence on screen, never a refusal.++ An octave apart — 64 against 128 — is a beat tracker counting half bars,+ not a disagreement about the music, so it does not earn the sentence.+ """+ rows, sec_per_bar = score_sections(score_abc or "")+ measured = float((beats or {}).get("bpm") or 0.0)+ if not rows or not sec_per_bar or measured <= 0:+ return None+ written = 60.0 * int((beats or {}).get("meter") or meter) / sec_per_bar+ for octave in (1.0, 2.0, 0.5, 4.0, 0.25):+ if abs(measured / (written * octave) - 1.0) <= tolerance:+ return None+ return (f"The score says {written:.0f} BPM and the recording measures "+ f"{measured:.0f} — the sections are in the right order and the "+ f"right proportions, but their times are stretched to fit.")+++def _decode(audio_path, sr: int, span):+ import storyboard_edit as sedit # noqa: PLC0415+ return sedit._decode_pcm(audio_path, sr=sr, span=span)+++def _vocal_ratio(x, sr: int, t0: float, start: float, end: float) -> float:+ """Energy in the voice band over total energy, for one stretch.++ One rfft per stretch, not per frame: this answers a yes/no question about a+ section that is seconds long, and a spectrogram would be a megabyte spent+ on one number. Rectangular window, because the ratio of two band sums is+ barely affected by leakage at this resolution.+ """+ import numpy as np # noqa: PLC0415+ i0 = max(0, int((start - t0) * sr))+ i1 = min(x.size, int((end - t0) * sr))+ seg = x[i0:i1]+ if seg.size < sr // 8:+ return 0.0+ mag = np.abs(np.fft.rfft(seg.astype(np.float32)))+ freqs = np.fft.rfftfreq(seg.size, 1.0 / sr)+ total = float((mag ** 2).sum())+ if total <= 1e-12:+ return 0.0+ lo, hi = VOCAL_BAND_HZ+ band = float((mag[(freqs >= lo) & (freqs < hi)] ** 2).sum())+ return band / total+++def song_sections(audio_path, *, lyrics=None, score_abc=None,+ beats=None, span=None, meter: int = 4,+ phrase_bars: int = PHRASE_BARS,+ vocal_ratio: float = VOCAL_BAND_RATIO) -> list[dict]:+ """The song's sections — `[{start, end, kind, name, source}]`.++ `kind` is "vocal" or "instrumental"; `start`/`end` are seconds into the+ file; `source` says which evidence produced the boundary ("score" or+ "phrase") so a reader can tell a fact from a heuristic.++ TWO PATHS, and the difference is what the caller knows about the song:++ * a YuE2 song hands in its sidecar's `lyrics` and `score_abc`, and the+ boundaries are ARITHMETIC — the score's bars times the tempo in its own+ `Q:`/`M:` headers, with the lyrics' tags saying which of those sections+ anybody sings in. No analysis, no threshold, no chance of being wrong+ about where the chorus is;+ * anything else is split into `phrase_bars`-bar phrases on the beat map's+ downbeats and classified by how much of each phrase's energy sits in+ the 1–4 kHz band. Crude and honest: a wrong call costs one shot.++ The score's bar count regularly OUTRUNS THE AUDIO — YuE2 writes a full+ arrangement and then the generation is cut at the user's max length+ (`truncated.semantic`) — so every section is clamped to the real duration+ and any section that starts past the end is dropped. The first section is+ pulled to 0.0 and the last pushed to the end of the file, because a music+ video that starts 300 ms late plays the song against the wrong pictures+ from the first bar.+ """+ import storyboard_edit as sedit # noqa: PLC0415+ bm = beats if isinstance(beats, dict) and beats.get("downbeats") else \+ sedit.beat_map(audio_path, meter=meter, span=span)+ t0 = float((bm.get("span") or [0.0])[0])+ duration = float(bm.get("duration") or 0.0)+ if duration <= 0:+ raise MusicVideoError("that song has no length to plan against")+ end_t = t0 + duration+ downbeats = [float(t) for t in (bm.get("downbeats") or [])]+ bar = float(bm.get("period") or 0.0) * int(bm.get("meter") or meter)++ rows: list[dict] = []+ score_rows, sec_per_bar = score_sections(score_abc or "")+ tags = lyric_sections(lyrics or "")++ if score_rows and sec_per_bar:+ # The score orders the film; the lyrics say who sings in it. A score+ # section whose name no tag claims (YuE2 adds its own intro and outro)+ # is instrumental by construction — nobody wrote it any words.+ pending = list(tags)+ cursor = t0+ for row in score_rows:+ length = row["bars"] * sec_per_bar+ name = row["name"]+ kind = "instrumental"+ for i, tag in enumerate(pending):+ if tag["name"] == name:+ kind = "vocal" if tag["vocal"] else "instrumental"+ del pending[:i + 1]+ break+ rows.append({"start": cursor, "end": cursor + length,+ "kind": kind, "name": name, "source": "score"})+ cursor += length+ if not tags:+ # A score with no lyrics beside it still has no idea who sings.+ rows = _classify(rows, audio_path, t0, duration, vocal_ratio)+ elif score_rows and tags:+ # Bars we cannot convert to seconds: share the run out over the tags.+ rows = _even_sections(tags, t0, duration)+ else:+ rows = _phrase_sections(downbeats, t0, duration, phrase_bars, bar)+ rows = _classify(rows, audio_path, t0, duration, vocal_ratio)++ # ---- the boundaries land where a cut can land ----------------------+ out: list[dict] = []+ for r in rows:+ start = max(t0, float(r["start"]))+ stop = min(end_t, float(r["end"]))+ if r["source"] == "score" and downbeats and bar > 0:+ start = sedit.snap(start, downbeats, bar / 2.0)+ stop = sedit.snap(stop, downbeats, bar / 2.0)+ start, stop = max(t0, start), min(end_t, stop)+ if stop - start < 1e-3:+ continue+ if out:+ start = out[-1]["end"] # no gaps, ever+ if stop - start < 1e-3:+ continue+ out.append({"start": round(start, 6), "end": round(stop, 6),+ "kind": r["kind"], "name": r["name"],+ "source": r["source"]})+ if not out:+ raise MusicVideoError("that song is too short to cut into sections")+ out[0]["start"] = round(t0, 6)+ out[-1]["end"] = round(end_t, 6)+ return out+++def given_sections(rows, *, duration: float,+ start: float = 0.0) -> tuple[list[dict], list[str]]:+ """The structure the CALLER wrote down -> `(sections, notes)`.++ THE PERSON WITH THE SONG KNOWS MORE THAN ANY ANALYSER. `song_sections`+ reads a score when there is one and guesses from band energy when there+ is not; neither can know that the first 8.5 seconds are held on an empty+ stage on purpose, or where a line really lands on a take that was sung+ rather than written. The first real film was planned by hand-writing this+ list against measured vocal onsets, so it is a parameter now.++ One row is `{start, end, kind: vocal|instrumental, label?}` in seconds.+ Raises `MusicVideoError` — message user-facing — when the list cannot be+ used at all; everything it can fix quietly it fixes and says so in `notes`.++ THE FIRST SECTION IS PULLED TO THE START OF THE SONG, always. The film+ plays from 0:00 with the song laid underneath from 0:00, so a plan whose+ cursor began at 8.5 s would render every singing shot against a second of+ the song that is 8.5 s later than the one it will be played under. A+ caller who wants to open on silence writes an instrumental section there.+ """+ if not isinstance(rows, list) or not rows:+ raise MusicVideoError(+ "the sections must be a list with at least one section in it")+ out: list[dict] = []+ for i, r in enumerate(rows, start=1):+ if not isinstance(r, dict):+ raise MusicVideoError(f"section {i} is not an object")+ try:+ s, e = float(r["start"]), float(r["end"])+ except (KeyError, TypeError, ValueError):+ raise MusicVideoError(+ f"section {i} needs a start and an end, in seconds") from None+ kind = str(r.get("kind") or "").strip().lower()+ if kind not in ("vocal", "instrumental"):+ raise MusicVideoError(+ f"section {i}: kind {r.get('kind')!r} must be vocal or "+ f"instrumental")+ if not (e > s):+ raise MusicVideoError(+ f"section {i} ends at {e:g} s, which is not after its start "+ f"at {s:g} s")+ name = str(r.get("label") or r.get("name") or kind).strip()+ out.append({"start": s, "end": e, "kind": kind, "name": name,+ "source": "given"})+ out.sort(key=lambda r: r["start"])+ for a, b in zip(out, out[1:]):+ if b["start"] < a["end"] - 1e-6:+ raise MusicVideoError(+ f"two sections overlap: {_clock(a['start'])}–{_clock(a['end'])} "+ f"and {_clock(b['start'])}–{_clock(b['end'])}")++ notes: list[str] = []+ end_t = start + float(duration or 0.0) if duration and duration > 0 else None+ kept: list[dict] = []+ for r in out:+ s = max(start, float(r["start"]))+ e = float(r["end"]) if end_t is None else min(end_t, float(r["end"]))+ if kept:+ s = kept[-1]["end"] # no gaps, ever — as song_sections+ if e - s < 1e-3:+ continue+ kept.append({**r, "start": round(s, 6), "end": round(e, 6)})+ if not kept:+ raise MusicVideoError("none of those sections lands inside the song")+ if kept[0]["start"] > start + 1e-3:+ notes.append(+ f"The first section began at {_clock(kept[0]['start'])} and was "+ f"pulled back to the start of the song — the film plays from 0:00, "+ f"so a section that starts later would put every mouth on the "+ f"wrong words.")+ kept[0]["start"] = round(start, 6)+ if end_t is not None and kept[-1]["end"] < end_t - 0.5:+ notes.append(+ f"Your sections stop at {_clock(kept[-1]['end'])} and the song "+ f"runs to {_clock(end_t)}, so the last "+ f"{end_t - kept[-1]['end']:.0f} s of it has no shots.")+ return kept, notes+++def _even_sections(tags: list[dict], t0: float, duration: float) -> list[dict]:+ """One section per lyrics tag, the run time shared out evenly."""+ n = max(1, len(tags))+ step = duration / n+ return [{"start": t0 + i * step, "end": t0 + (i + 1) * step,+ "kind": "vocal" if t["vocal"] else "instrumental",+ "name": t["name"], "source": "phrase"}+ for i, t in enumerate(tags)]+++def _phrase_sections(downbeats: list[float], t0: float, duration: float,+ phrase_bars: int, bar: float) -> list[dict]:+ """`phrase_bars`-bar phrases on the downbeat grid, covering the whole file.++ Falls back to a clock-based split when there are too few downbeats to make+ a phrase — a song the beat tracker could not read is still a song, and a+ plan on an even grid beats a refusal.+ """+ edges = [t for t in downbeats if t0 - 1e-6 <= t <= t0 + duration + 1e-6]+ if len(edges) <= phrase_bars:+ step = bar * phrase_bars if bar > 0 else 15.0+ n = max(1, int(round(duration / step)))+ step = duration / n+ return [{"start": t0 + i * step, "end": t0 + (i + 1) * step,+ "kind": "vocal", "name": f"phrase {i + 1}", "source": "phrase"}+ for i in range(n)]+ rows = []+ for i in range(0, len(edges) - 1, phrase_bars):+ start = edges[i]+ j = min(i + phrase_bars, len(edges) - 1)+ end = edges[j] if j > i else t0 + duration+ rows.append({"start": start, "end": end, "kind": "vocal",+ "name": f"phrase {len(rows) + 1}", "source": "phrase"})+ if rows:+ rows[0]["start"] = t0+ rows[-1]["end"] = t0 + duration+ return rows+++def _classify(rows: list[dict], audio_path, t0: float, duration: float,+ threshold: float) -> list[dict]:+ """Stamp `kind` on every row from the voice-band energy ratio.++ One decode for the whole file, one rfft per row. A stretch whose ratio sits+ below the track's own median as well as below the absolute threshold is+ instrumental; the median makes the call relative to THIS mix, so a bright+ production does not come out all-vocal and a muddy one all-instrumental.+ """+ if not rows:+ return rows+ try:+ x = _decode(audio_path, 16000, (t0, t0 + duration))+ except Exception: # noqa: BLE001+ # No decoder, no opinion — everything sung is the generous guess, and+ # the planner's own "no singer picture" note covers the other side.+ for r in rows:+ r["kind"] = "vocal"+ return rows+ ratios = [_vocal_ratio(x, 16000, t0, r["start"], r["end"]) for r in rows]+ live = sorted(v for v in ratios if v > 0)+ median = live[len(live) // 2] if live else 0.0+ for r, v in zip(rows, ratios):+ r["kind"] = "vocal" if (v >= threshold and v >= median * 0.85) \+ else "instrumental"+ r["vocal_ratio"] = round(v, 4)+ return rows+++# ---------------------------------------------------------------------------+# PART B — the shot list+# ---------------------------------------------------------------------------++def cells_from_lengths(lengths, quality=None) -> tuple:+ """The panel's `LTX_LENGTHS` table as (seconds, frames), longest first.++ The routes call this so the planner's duration axis IS the panel's, with+ the table stated once. A dict, not the module, because this file does not+ import the panel.++ `quality` is the pass the film will really render at. A row that names+ `qualities` is offered on THOSE qualities only — see `LTX_CELL_QUALITIES`+ — and is dropped here for any other. `None` means "no quality stated" and+ hands the table back whole; the safety net in that case is+ `plan_music_video`, which applies the same restriction from its own+ default rather than trusting whatever cells it was given.+ """+ q = str(quality).strip().lower() if quality is not None else None+ rows = []+ for l in (lengths or {}).values():+ if not (l.get("seconds") and l.get("frames")):+ continue+ allowed = tuple(str(a).strip().lower()+ for a in (l.get("qualities") or ()))+ if q is not None and allowed and q not in allowed:+ continue+ rows.append((int(l["seconds"]), int(l["frames"])))+ return tuple(sorted(set(rows), key=lambda r: -r[0])) or LTX_CELLS+++def _cells_for_quality(cells, quality) -> tuple[tuple, tuple]:+ """`(kept, dropped)` — the cells this quality's canvas can really render.++ Applied to WHATEVER cells the caller handed in, not only to the ones this+ module derived: the caller that passes its own axis is exactly the caller+ that can pass a cell the canvas cannot hold (a hand-written tuple, a+ table from an older panel), and dropping it here is the difference+ between a cut and a dead render.+ """+ q = str(quality or "").strip().lower()+ if not q:+ return tuple(cells), ()+ kept, dropped = [], []+ for cell in cells:+ allowed = LTX_CELL_QUALITIES.get(int(cell[0]))+ (kept if (not allowed or q in allowed) else dropped).append(tuple(cell))+ # Every cell restricted is a table nobody can plan against; keep the axis+ # rather than refuse, and let the note below say what happened.+ return (tuple(kept) or tuple(cells)), tuple(dropped)+++def _cell_for(seconds: float, cells) -> tuple | None:+ """The largest cell that fits inside `seconds`, or None."""+ for s, f in cells:+ if s <= seconds + 1e-6:+ return (s, f)+ return None+++def _frames_for(seconds: float) -> int:+ return storyboard.ltx_frames_for(seconds)+++def _clock(seconds: float) -> str:+ total = int(round(max(0.0, seconds)))+ return f"{total // 60}:{total % 60:02d}"+++def _with_style(line: str, style: str) -> str:+ """One direction plus the film's look, the one way it is ever joined."""+ line = str(line or "").strip()+ style = str(style or "").strip().rstrip(".")+ return f"{line}, {style}" if style else line+++def _prompt_for(image: dict, kind: str, style: str, *,+ silent: bool = False) -> str:+ """The shot's direction: the picture's own line, then the film's look.++ An image carries `prompt` when the user typed one for it, and that REPLACES+ the role line rather than joining it — somebody who wrote "he leans back+ and laughs" meant that instead of "close-up, singing to camera", not as+ well as.++ A SINGING SHOT GOES THROUGH THE A2V LAW on the way out (`storyboard`+ owns it, so the validator and both planners cannot disagree): stillness+ words are scrubbed, the direction is capped, and the literal sync+ contract is appended LAST so a user's own line cannot paraphrase it away.+ `silent=True` swaps that contract for the relaxed-closed-lips one.+ """+ line = (str(image.get("prompt") or "").strip()+ or ROLE_LINES.get((image.get("role"), kind))+ or ROLE_LINES[("room", "broll")])+ return _sing_prompt(_with_style(line, style), kind, silent=silent)+++def _sing_prompt(text: str, kind: str, *, silent: bool = False) -> str:+ """One direction, put through the a2v law when the shot is audio-driven.++ B-roll is untouched: an i2v shot has no waveform, so a contract about+ syllables would be a sentence about a sound that is not there.+ """+ if kind != "singing":+ return text+ return storyboard.a2v_prompt(text, silent=silent)+++def slice_is_silent(sections, t0: float, t1: float) -> bool:+ """True when nothing in `t0..t1` is a vocal stretch, as far as the+ sections know.++ A window with no singing in it is NOT the same as saying nothing: left+ alone the model keeps the mouth working through an instrumental bar. The+ threshold is deliberately low — a fifth of the shot overlapping a vocal+ section is enough to call it a singing window, because a mouth that sings+ slightly too long reads far better than one that stops mid-line.+ """+ span = max(1e-6, float(t1) - float(t0))+ vocal = 0.0+ for row in (sections or []):+ if str(row.get("kind") or "").strip().lower() != "vocal":+ continue+ lo = max(float(t0), float(row.get("start") or 0.0))+ hi = min(float(t1), float(row.get("end") or 0.0))+ if hi > lo:+ vocal += hi - lo+ return (vocal / span) < 0.2+++def _shot_prompts(raw) -> dict[int, str]:+ """`{shot number: direction}` from whatever the caller handed in.++ The per-IMAGE `prompt` is a default that follows the picture into every+ shot it is cast in; this is a line for ONE shot. The last shot of the+ first real film had to say "the stage lights slowly fading down to black"+ and the same picture is used three times earlier, where a fade would be+ wrong — so the override has to be per shot or it is not an override.+ """+ out: dict[int, str] = {}+ for key, value in dict(raw or {}).items():+ try:+ n = int(key)+ except (TypeError, ValueError):+ continue+ text = str(value or "").strip()+ if n >= 1 and text:+ out[n] = text+ return out+++def plan_music_video(sections, images, *, style: str, bpm_grid,+ singing_window=SINGING_WINDOW,+ broll_window=BROLL_WINDOW,+ cells=None, quality: str = DEFAULT_QUALITY,+ shot_prompts=None, shot_images=None,+ title: str = "Music video",+ song: str = "", board_id: str = "",+ vocal_stem: str = "") -> dict:+ """Sections plus pictures -> a storyboard board that shoots a music video.++ Returns::++ {"board": {...}, # the storyboard schema, shots and all+ "shots": [...], # board["shots"], for a caller's reply+ "summary": "14 shots · 6 singing · 8 B-roll · 3:20",+ "notes": ["..."], # what the plan could not do, in words+ "film_seconds": 200.04}++ HOW IT DECIDES. A vocal section is filled with SINGING SHOTS — mode `a2v`,+ one Singer picture each, alternating so the angle changes, `audio_start_time`+ set to that shot's own place in the song, and `frames` the largest LTX cell+ that fits the singing window. Whatever is left of the section, and every+ instrumental section, becomes B-ROLL — a still with a slow move on it,+ 3–7 seconds, cut on the downbeats.++ THE CURSOR IS THE FILM, not the section list. Every shot's length is the+ one it will really render (a frame count on the 8k+1 grid), and the next+ shot starts where the last one ended, so `audio_start_time` is always the+ second of the song that will be playing under that clip once the shots are+ concatenated and the song is laid underneath. Section boundaries are the+ TARGET the cursor steers towards; when the frame grid overshoots one by+ 20 ms the next section absorbs it, and nothing downstream ever has to know.++ `cells` is the panel's duration axis (`cells_from_lengths`); absent, the+ module's own `LTX_CELLS` — same numbers, derived the same way. `quality`+ is the pass the film will be delivered at, and the axis is cut down to+ what that canvas can really render before a single shot is emitted.++ CASTING B-ROLL. The rotation is weighted (`weight` on a picture, default+ 1) and two slots can be pinned by hand: a picture whose `use` is "open"+ takes the first B-roll shot and one whose `use` is "close" takes the last,+ in the order they were given. `shot_prompts` is `{shot number: line}` and+ replaces that ONE shot's direction, the picture's own `prompt` staying the+ default everywhere else it is cast.++ CASTING THE SINGING. The rotation alternates so the angle changes. Which+ picture LEADS it is decided by face size when the caller has not said+ otherwise: a picture may carry `face_frac` (how much of the frame the face+ fills, 0..1) and the biggest measured face goes first, because a singing+ shot is a close-up and a mouth at a quarter of the frame is mush. A `use`+ pin or a `shot_images` pin is the caller saying which picture goes where,+ and it wins outright.++ `shot_images` is `{shot number: path}` and replaces who is in THAT ONE+ shot, leaving its frames, its `film_start` and its `audio_start_time`+ exactly where the tiling put them. It BEATS the `use` pins: naming a shot+ is the exact decision and "opens the film" is the coarse one, so an+ explicitly pinned shot is reserved and the open/close pictures take the+ B-roll shots around it.++ `vocal_stem` is a pre-separated vocal of the SAME song, and it rides on+ every singing shot as `audio_stem`: the model conditions on it, the panel+ muxes the original back, and the timing is untouched (the stem is the+ whole song, so a shot's `audio_start_time` means the same second in both).+ """+ cells = tuple(cells or LTX_CELLS)+ cells, cells_dropped = _cells_for_quality(cells, quality)+ overrides = _shot_prompts(shot_prompts)+ sing_min, sing_max = (float(x) for x in singing_window)+ broll_min, broll_max = (float(x) for x in broll_window)+ grid = [float(t) for t in ((bpm_grid or {}).get("downbeats") or [])]+ bar = float((bpm_grid or {}).get("period") or 0.0) \+ * int((bpm_grid or {}).get("meter") or 4)++ cast = _cast(images)+ notes: list[str] = []+ if cells_dropped:+ longest = max(int(s) for s, _ in cells_dropped)+ allowed = ", ".join(LTX_CELL_QUALITIES.get(longest, ()))+ notes.append(+ f"The {longest} s shot length is only offered at "+ f"{allowed or 'a smaller canvas'} and this film is planned for "+ f"{quality}, so the longest shot here is "+ f"{max(int(s) for s, _ in cells)} s.")+ image_pins, pin_notes = _shot_images(shot_images, cast)+ notes.extend(pin_notes)+ singers = [i for i in cast if i["role"] == "singer"]+ # WHO LEADS THE SINGING. Only when the caller has not said: a `use` pin or+ # a per-shot image pin is a decision, and this rule does not overrule one.+ singers, order_notes = _singer_order(+ singers,+ pinned=bool(image_pins) or any(i.get("use") in ("open", "close")+ for i in singers))+ notes.extend(order_notes)+ broll_pool = [i for i in cast if i["role"] in ("instrument", "room")]+ if not cast:+ raise MusicVideoError("a music video needs at least one picture")+ if not singers:+ notes.append("No picture is tagged Singer, so nobody sings on camera — "+ "every section became B-roll.")+ if not broll_pool:+ # Only faces. They can still carry the instrumental; they just must not+ # be asked to sing there (see ROLE_LINES).+ broll_pool = list(cast)+ if singers:+ notes.append("No Instrument or Room picture, so the B-roll is cut "+ "from the Singer pictures held still.")++ rows = [r for r in (sections or []) if float(r["end"]) > float(r["start"])]+ if not rows:+ raise MusicVideoError("that song has no sections to shoot")++ ring = _broll_ring(broll_pool)+ shots: list[dict] = []+ cursor = float(rows[0]["start"])+ singer_turn = 0+ broll_turn = 0++ def emit(image: dict, kind: str, frames: int, section: dict) -> None:+ nonlocal cursor+ dur = frames / float(FPS)+ n = len(shots) + 1+ # A picture pinned to THIS shot replaces the rotation's pick, and+ # nothing about the tiling moves: a pin is a casting decision.+ image = image_pins.get(n) or image+ line = overrides.get(n)+ # WHETHER THERE IS A VOICE IN THIS WINDOW, as far as the sections+ # know. A singing shot is normally cut inside a vocal stretch, but a+ # caller who hands in their own `sections` can place one anywhere, and+ # the frame grid can carry the tail of one past a boundary.+ silent = kind == "singing" and slice_is_silent(rows, cursor, cursor + dur)+ shot = {+ "n": n,+ "title": f"S{n:02d} {kind}",+ # The board's vocabulary is `storyboard.VALID_MODES`. A singing+ # shot is `a2v` there and in the panel; B-roll is `text` WITH A+ # STILL, which `shot_to_job` already turns into an anchored i2v —+ # the existing path, not a second one. `panel_mode` below is what+ # will really run, written down so a reader of the plan does not+ # have to know that rule.+ "mode": "a2v" if kind == "singing" else "text",+ "engine": "ltx",+ "prompt": _sing_prompt(_with_style(line, style), kind,+ silent=silent) if line+ else _prompt_for(image, kind, style, silent=silent),+ "duration_s": round(dur, 4),+ "seed": -1,+ "refs": [],+ "still": image["path"],+ "status": "pending",+ "music_video": {+ "kind": kind,+ "role": image["role"],+ "image": image["path"],+ "frames": frames,+ "film_start": round(cursor, 4),+ "film_end": round(cursor + dur, 4),+ "section": section.get("name") or "",+ "section_kind": section.get("kind") or "",+ "panel_mode": "a2v" if kind == "singing" else "i2v",+ },+ }+ if line:+ shot["music_video"]["prompt_override"] = True+ if kind == "singing":+ shot["audio"] = str(song)+ # WHAT THE MOUTH LISTENS TO. The band is noise to the audio+ # encoder - it reads drums and guitar as syllables and the model+ # hedges, opening the mouth a little on everything. A separated+ # vocal conditions the shot and the panel muxes the original song+ # back over the render, so the film still plays the record.+ if vocal_stem:+ shot["audio_stem"] = str(vocal_stem)+ # THE WHOLE POINT. The clip is rendered against the song from+ # exactly the second it will be playing at in the finished film.+ shot["audio_start_time"] = round(cursor, 4)+ shots.append(shot)+ cursor += dur++ for sec in rows:+ target = float(sec["end"])+ if sec.get("kind") == "vocal" and singers:+ while target - cursor >= sing_min - 1e-6:+ cell = _cell_for(min(sing_max, target - cursor), cells)+ if cell is None:+ break+ emit(singers[singer_turn % len(singers)], "singing",+ cell[1], sec)+ singer_turn += 1+ for span in _broll_spans(cursor, target, window=(broll_min, broll_max),+ grid=grid, bar=bar):+ # NO SHOT SHORTER THAN A SECOND. The board writer normalises every+ # shot to at least 1 s, so a 0.375 s scrap here became a 1.04 s+ # shot there — and every singing shot after it slid off its own+ # words by the difference (Codex review, 2026-09-20). A scrap is+ # folded into the B-roll shot before it; only when there is none+ # does it become a one-second shot of its own.+ if span < MIN_SHOT_S - 1e-6 and shots and shots[-1]["music_video"]["kind"] == "broll":+ last = shots[-1]+ old_dur = last["music_video"]["frames"] / float(FPS)+ frames = _frames_for(old_dur + span)+ new_dur = frames / float(FPS)+ last["music_video"]["frames"] = frames+ last["duration_s"] = round(new_dur, 4)+ last["music_video"]["film_end"] = round(last["music_video"]["film_start"] + new_dur, 4)+ cursor += new_dur - old_dur+ continue+ frames = max(_frames_for(max(span, MIN_SHOT_S)), _frames_for(MIN_SHOT_S))+ emit(ring[broll_turn % len(ring)], "broll", frames, sec)+ broll_turn += 1++ if not shots:+ raise MusicVideoError("that song is too short to make a shot out of")++ # The pins are a POST-PASS on purpose: "close" means the last B-roll shot+ # of the film, and which shot that is is not known until the last section+ # has been tiled. Nothing about the tiling moves — only who is in frame.+ notes.extend(_pin_broll(shots, broll_pool, style, overrides,+ reserved=set(image_pins)))+ orphans = [i["path"] for i in cast+ if i.get("use") in ("open", "close")+ and not any(i is b for b in broll_pool)]+ if orphans:+ notes.append(+ f"{len(orphans)} picture(s) asked to open or close the film but "+ f"are cast as Singer, and the pins only place B-roll: "+ f"{', '.join(orphans)}.")+ unused_pins = sorted(set(image_pins) - {int(s["n"]) for s in shots})+ if unused_pins:+ notes.append(+ f"This plan has {len(shots)} shots, so the picture(s) pinned to "+ f"shot {', '.join(str(n) for n in unused_pins)} were not used.")+ unused = sorted(set(overrides) - {int(s["n"]) for s in shots})+ if unused:+ notes.append(+ f"This plan has {len(shots)} shots, so the line(s) written for "+ f"shot {', '.join(str(n) for n in unused)} were not used.")++ n_sing = sum(1 for s in shots if s["music_video"]["kind"] == "singing")+ n_broll = len(shots) - n_sing+ film = sum(float(s["duration_s"]) for s in shots)+ summary = (f"{len(shots)} shots · {n_sing} singing · {n_broll} B-roll · "+ f"{_clock(film)}")++ board = storyboard.new_storyboard(+ board_id or "", title or "Music video", shots=shots)+ # Every shot is LTX: a2v only exists there, and a board that let H3 take a+ # B-roll shot would put a soundtrack-less 5 s cell where a 4.3 s one was+ # planned and slide every singing shot after it off its own words.+ board["engine_mode"] = "ltx"+ board["style"] = str(style or "")+ board["music_video"] = {+ "song": str(song),+ "vocal_stem": str(vocal_stem or ""),+ "images": cast,+ "style": str(style or ""),+ "summary": summary,+ "film_seconds": round(film, 4),+ "sections": [dict(r) for r in rows],+ "notes": notes,+ }+ return {"board": board, "shots": shots, "summary": summary,+ "notes": notes, "film_seconds": round(film, 4)}+++def _cast(images) -> list[dict]:+ """The pictures, cleaned: `[{path, role, prompt, use, weight}]`, in order.++ An unknown role is not an error and not silently a Singer — a picture whose+ tag got lost is B-roll, which is the choice that cannot put a still mouth+ in front of a vocal line. `use` and `weight` are the same shape of+ forgiveness: an unreadable pin is "any" and an unreadable weight is 1,+ because a mistyped hint is a picture in the wrong slot, never a refused film.+ """+ out = []+ for im in (images or []):+ if not isinstance(im, dict):+ continue+ path = str(im.get("path") or "").strip()+ if not path:+ continue+ role = str(im.get("role") or "").strip().lower()+ if role not in ROLES:+ role = "room"+ use = str(im.get("use") or "any").strip().lower()+ if use not in USES:+ use = "any"+ try:+ weight = int(float(im.get("weight") or 1))+ except (TypeError, ValueError):+ weight = 1+ out.append({"path": path, "role": role,+ "prompt": str(im.get("prompt") or "").strip(),+ "use": use, "weight": max(1, min(weight, MAX_WEIGHT)),+ "face_frac": _face_frac(im.get("face_frac"))})+ return out+++def _face_frac(raw) -> float | None:+ """How much of the picture the face fills, 0..1, or None when nobody+ measured it.++ NOT GUESSED FROM THE PICTURE. The obvious cheap proxy - aspect ratio, or+ the short side - is worthless here: a 1:1 crop of a wide room and a 1:1+ crop of a face are the same number, and a portrait-shaped photograph of a+ band is portrait-shaped. So the measurement is a value the CALLER passes,+ and a picture nobody measured keeps its place in the order rather than+ being sorted by a number that was invented for it. The panel's captioner+ already looks at every uploaded picture and is where this can be filled in+ later; until then it is an optional field on the cast.+ """+ if raw in (None, ""):+ return None+ try:+ value = float(raw)+ except (TypeError, ValueError):+ return None+ if value != value or value <= 0: # NaN, 0, negative+ return None+ return min(1.0, value)+++def _singer_order(singers: list[dict], pinned: bool) -> tuple[list[dict], list[str]]:+ """The singing rotation, biggest face first. Returns (order, notes).++ A singing shot is a CLOSE-UP by default (`ROLE_LINES`), and at 23% of the+ frame a mouth is mush while at 46% it is legible - the difference between+ a lip-sync you believe and one you squint at. So when the caller has said+ nothing about which picture goes where, the measured faces lead.++ THE CALLER'S ORDER WINS whenever there is one. A `use` pin or a per-shot+ image pin is somebody saying which picture they want where, and a rule+ about face size is not entitled to overrule it.+ """+ if pinned or len(singers) < 2:+ return list(singers), []+ rated = [i for i in singers if i.get("face_frac") is not None]+ if not rated:+ return list(singers), []+ order = sorted(+ enumerate(singers),+ key=lambda pair: (0 if pair[1].get("face_frac") is not None else 1,+ -(pair[1].get("face_frac") or 0.0), pair[0]))+ order = [im for _, im in order]+ if order == list(singers):+ return order, []+ lead = order[0]+ note = (f"The singing shots lead on {lead['path']}, the biggest face of "+ f"the {len(rated)} measured ({(lead['face_frac'] or 0) * 100:.0f}% "+ f"of the frame) - a close-up reads at that size and does not at a "+ f"quarter of it.")+ unrated = len(singers) - len(rated)+ if unrated:+ note += (f" {unrated} Singer picture(s) carry no face measurement and "+ f"follow in the order they were given.")+ return order, [note]+++def _shot_images(raw, cast: list[dict]) -> tuple[dict[int, dict], list[str]]:+ """`{shot number: the cast picture pinned to it}` plus notes.++ The per-shot twin of `_shot_prompts`: a line is one kind of decision about+ one shot and WHO IS IN IT is the other. A path that is not in the cast is+ a note rather than a refusal, for the same reason an unreadable weight is+ not - a mistyped hint is a picture in the wrong slot, never a refused film.+ """+ by_path = {im["path"]: im for im in cast}+ out: dict[int, dict] = {}+ notes: list[str] = []+ missing: list[str] = []+ for key, value in dict(raw or {}).items():+ try:+ n = int(key)+ except (TypeError, ValueError):+ continue+ path = str(value or "").strip()+ if n < 1 or not path:+ continue+ if path in by_path:+ out[n] = by_path[path]+ else:+ missing.append(path)+ if missing:+ notes.append(+ f"{len(missing)} picture(s) were pinned to a shot but are not in "+ f"this film's cast, so the rotation kept those shots: "+ f"{', '.join(sorted(set(missing)))}.")+ return out, notes+++def _broll_ring(pool: list[dict]) -> list[dict]:+ """The B-roll rotation, `weight` copies of each picture, SPREAD not clumped.++ A blind round-robin gives every picture the same share, which is wrong+ whenever one of them is the film's own image and the rest are cutaways.+ The ring is built in passes — everybody once, then everybody with weight+ ≥ 2 again, and so on — so a weight-3 picture comes round three times as+ often without ever appearing three times in a row.+ """+ if not pool:+ return []+ top = max(int(i.get("weight") or 1) for i in pool)+ ring = [im for k in range(max(1, top)) for im in pool+ if int(im.get("weight") or 1) > k]+ return ring or list(pool)+++def _recast(shot: dict, image: dict, style: str, overrides: dict) -> None:+ """Put a different picture in an already-planned B-roll shot.++ Everything about the TILING is left alone — frames, film_start, film_end,+ the section it belongs to — because the song is the clock and a pin is a+ casting decision, not a timing one.+ """+ block = shot["music_video"]+ shot["still"] = image["path"]+ block["image"] = image["path"]+ block["role"] = image["role"]+ line = overrides.get(int(shot["n"]))+ shot["prompt"] = (_with_style(line, style) if line+ else _prompt_for(image, "broll", style))+++def _pin_broll(shots: list[dict], pool: list[dict], style: str,+ overrides: dict, reserved: set[int] | None = None) -> list[str]:+ """Place the `use: open` / `use: close` pictures. Returns notes.++ `reserved` is the shot NUMBERS a caller pinned a picture to by hand. They+ are not slots this pass may fill: `emit()` already cast them, and recasting+ them here meant the later, coarser decision ("something opens the film")+ quietly overruled the earlier, exact one ("B is in shot 1") — the pin the+ caller wrote was worth nothing (Codex review, 2026-09-22).+ """+ reserved = reserved or set()+ slots = [i for i, s in enumerate(shots)+ if s["music_video"]["kind"] == "broll"+ and int(s["n"]) not in reserved]+ opens = [im for im in pool if im.get("use") == "open"]+ closes = [im for im in pool if im.get("use") == "close"]+ if not (opens or closes):+ return []+ held = sorted(int(s["n"]) for s in shots+ if s["music_video"]["kind"] == "broll"+ and int(s["n"]) in reserved)+ if not slots:+ return [f"Every B-roll shot in this film was pinned to a picture by "+ f"hand (shot {', '.join(str(n) for n in held)}), so there was "+ f"no slot left to open or close on."] if held else [+ "Every shot in this film is a singing shot, so there was no "+ "B-roll slot to open or close on."]+ notes = []+ if held:+ notes.append(+ f"Shot {', '.join(str(n) for n in held)} was pinned to a picture "+ f"by hand, so the open/close pins went to the B-roll shots around "+ f"it.")+ if len(opens) + len(closes) > len(slots):+ notes.append(+ f"{len(opens) + len(closes)} pictures are pinned to open or close "+ f"but this film has only {len(slots)} B-roll shots, so the ones "+ f"that did not fit were left in the rotation.")+ taken: set[int] = set()+ for k, im in enumerate(opens):+ if k >= len(slots):+ break+ _recast(shots[slots[k]], im, style, overrides)+ taken.add(slots[k])+ # Reversed, so the LAST picture pinned "close" is the last shot of the film.+ for k, im in enumerate(reversed(closes)):+ j = slots[len(slots) - 1 - k]+ if k >= len(slots) or j in taken:+ break+ _recast(shots[j], im, style, overrides)+ taken.add(j)+ return notes+++def _broll_spans(t0: float, t1: float, *, window, grid, bar) -> list[float]:+ """Split `t0..t1` into B-roll shot lengths, cut on the downbeats.++ Returns LENGTHS, not boundaries, because the caller's cursor is the truth+ and a boundary computed here would be stale the moment a frame count+ rounded. The count is whatever gets closest to the middle of the window+ while keeping every shot inside it; the last shot takes the remainder so+ the section closes exactly where it was asked to.+ """+ lo, hi = window+ length = t1 - t0+ if length <= 1e-6:+ return []+ if length < lo - 1e-6:+ # A scrap at the end of a section. One short shot beats a hole: a gap+ # in the tiling is a gap between the song and the picture.+ return [length]+ n = max(1, int(round(length / ((lo + hi) / 2.0))))+ n = max(n, int(math.ceil(length / hi - 1e-9)))+ n = min(n, max(1, int(length // lo)))+ spans: list[float] = []+ cursor = t0+ for k in range(1, n + 1):+ if k == n:+ spans.append(t1 - cursor)+ break+ want = t0 + length * k / n+ end = _snap_between(want, grid, bar / 2.0 if bar > 0 else 0.0,+ cursor + lo, min(cursor + hi, t1 - lo * (n - k)))+ spans.append(end - cursor)+ cursor = end+ return [s for s in spans if s > 1e-6]+++def _snap_between(t: float, grid, tol: float, lo: float, hi: float) -> float:+ """Nearest grid point to `t` inside `[lo, hi]` and within `tol`, else `t`.++ A local copy of the planner's own snapping rather than a call into+ `storyboard_edit`: this module must plan without the audio machinery, and+ the rule is four lines. `storyboard_edit._snap_in_range` is the one used on+ the finished clips, where the constraints are different (a cut may not+ outrun its source) and the answer may legitimately be "no beat here".+ """+ if hi < lo:+ # Infeasible only if the caller mis-counted its own shots; `_broll_spans`+ # proves it cannot, so this is a guard, not a policy.+ return t+ t = max(lo, min(t, hi))+ if not grid or tol <= 0:+ return t+ best, dist = None, None+ for g in grid:+ if g < lo - 1e-9 or g > hi + 1e-9 or abs(g - t) > tol:+ continue+ d = abs(g - t)+ if dist is None or d < dist:+ best, dist = float(g), d+ return best if best is not None else tdiff --git a/panel/routes_files.py b/panel/routes_files.pyindex d4f7f87..8e4c72a 100644--- a/panel/routes_files.py+++ b/panel/routes_files.py@@ -376,6 +376,31 @@ def get_library_images(h, parsed) -> None:# from disk. Containment check identical to /output/hide so the# endpoint can't be tricked into deleting arbitrary paths. Used# by the per-card × button in the Outputs gallery.+def _reserve_trash_name(trash_dir, c, ts: str):+ """A Trash destination nobody else holds, CLAIMED before the move.++ The old rule checked only the plain name and fell back to one+ timestamp-suffixed name without checking that one: same-seed image+ batches share basenames (`cand_42_mflux.png`), so a second deletion in the+ same second — two tabs, or two batches — picked the same suffixed name+ and the move silently replaced the first trashed image (Codex UI-05).+ Each candidate is created with O_EXCL, so a concurrent request cannot pick+ it too; the move then lands on our empty placeholder."""+ names = [c.name, f"{c.stem}-{ts}{c.suffix}"]+ names += [f"{c.stem}-{ts}-{n}{c.suffix}" for n in range(2, 1000)]+ for name in names:+ dest = trash_dir / name+ if dest.exists() or dest.is_symlink():+ continue+ try:+ fd = P.os.open(str(dest), P.os.O_WRONLY | P.os.O_CREAT | P.os.O_EXCL, 0o600)+ except FileExistsError:+ continue+ P.os.close(fd)+ return dest+ raise OSError(f"no free name in the Trash for {c.name}")++@post("/output/delete")def post_output_delete(h, path, qs, ctype) -> None:_rb = h._read_form_body()@@ -524,13 +549,18 @@ def post_output_delete(h, path, qs, ctype) -> None:trashed = []ts = P.time.strftime("%Y%m%d-%H%M%S")for c in candidates:- dest = trash_dir / c.name- if dest.exists():- dest = trash_dir / f"{c.stem}-{ts}{c.suffix}"+ try:+ dest = _reserve_trash_name(trash_dir, c, ts)+ except OSError as e:+ h._json({"error": f"move to Trash failed: {e}"}, 500); returntry:P.shutil.move(str(c), str(dest))trashed.append(str(dest))except OSError as e:+ try:+ dest.unlink() # our empty placeholder, never a user file+ except OSError:+ passh._json({"error": f"move to Trash failed: {e}"}, 500); return# Drop every trashed-original from HIDDEN_PATHS so we don't# leak orphan entries into panel_hidden.json. The nativediff --git a/panel/routes_meta.py b/panel/routes_meta.pyindex 6bda4b3..fa04efa 100644--- a/panel/routes_meta.py+++ b/panel/routes_meta.py@@ -457,6 +457,26 @@ def post_version_pull(h, path, qs, ctype) -> None:raise RuntimeError((fetch_proc.stdout + fetch_proc.stderr).decode("utf-8", "replace").strip()or f"git fetch exited {fetch_proc.returncode}")+ # Step 1b: THE OBSTRUCTION GUARD — the sidebar Update's, run on the+ # fetched origin/main, before anything can move the tree. `status+ # -uno` above is blind to untracked and ignored files, and both+ # moves below destroy them: `pull --ff-only` silently overwrites an+ # IGNORED file where upstream now tracks one, and the reset+ # overwrites untracked ones too (Codex INST-01, 2026-09-24).+ guard = P.ROOT / "scripts" / "pinokio" / "update_obstruction_guard.sh"+ if not guard.is_file():+ raise RuntimeError(+ "scripts/pinokio/update_obstruction_guard.sh is missing - "+ "not updating. Nothing was changed or deleted; use the "+ "Pinokio Update instead.")+ guard_proc = P.subprocess.run(+ ["bash", str(guard), "origin/main"],+ cwd=str(P.ROOT), capture_output=True, timeout=60,+ )+ if guard_proc.returncode != 0:+ raise RuntimeError(+ (guard_proc.stdout + guard_proc.stderr).decode("utf-8", "replace").strip()+ or "untracked or ignored files are in the way - nothing deleted")# Step 2: try a fast-forward pull. Happy path for fresh installs# whose local history lines up with origin/main.pull_proc = P.subprocess.run(@@ -470,7 +490,25 @@ def post_version_pull(h, path, qs, ctype) -> None:# origin/main. Guards above already proved this is safe# (clean tree + on main + nothing ahead), so the reset just# snaps the diverged history back to upstream.+ #+ # ONLY ON PROVEN DIVERGENCE. Every other refusal — the commonest is+ # git's own "untracked working tree files would be overwritten" —+ # used to take this branch too and reset over the file git had just+ # protected (INST-01). The pre-fetch `ahead` check was against the+ # OLD origin/main, so it cannot prove anything here; count again+ # against the fetched one. Zero means history did not diverge,+ # whatever made the pull fail: stop and report git's message.if pull_proc.returncode != 0:+ ahead_after = (P._git_capture(+ ["rev-list", "--count", "origin/main..HEAD"]) or "0").strip()+ try:+ ahead_after_n = int(ahead_after)+ except ValueError:+ ahead_after_n = 0+ if ahead_after_n <= 0:+ raise RuntimeError(+ f"update blocked - history has NOT diverged, so nothing "+ f"was reset or deleted.\n{pull_out}")reset_proc = P.subprocess.run(["git", "-C", str(P.ROOT), "reset", "--hard", "origin/main"],capture_output=True, timeout=30,@@ -504,10 +542,18 @@ def post_version_pull(h, path, qs, ctype) -> None:# them without the full Update ships new code onto old# dependencies (review 2026-09-02)."scripts/post_update.sh", "scripts/check_post_update.js",+ # The wheel-build pin both installers read, and the YuE2+ # engine SHA: only the full Update runs music_checkout.sh, so+ # a pin-only pull used to say "Stop/Start is enough" and left+ # new runner code on the old engine (Codex INST-12).+ "pip-build-constraints.txt", "scripts/music/engine_pin.txt",)for line in diff_out.splitlines():if (line in deps_signals or line.startswith("ltx-2-mlx/")- or line.startswith("scripts/pinokio/")):+ or line.startswith("scripts/pinokio/")+ # install_h3.js / install_music.js / install_qwen.js …+ # carry their engines' pins the same way install.js does.+ or (line.startswith("install") and line.endswith(".js"))):deps_touched = Truebreakdiff --git a/panel/routes_models.py b/panel/routes_models.pyindex 66e4030..fa3450e 100644--- a/panel/routes_models.py+++ b/panel/routes_models.py@@ -166,9 +166,15 @@ def post_models_remove(h, path, qs, ctype) -> None:@post("/models/cancel")def post_models_cancel(h, path, qs, ctype) -> None:# Best-effort kill — the next status poll will see active=False.+ # `cancelled` is what stops the worker's retry loop (INST-07): killing the+ # process alone made the attempt look failed and the worker started the+ # next one. The slot itself stays held until the worker releases it, so a+ # new download cannot start and be wiped by the old worker's cleanup.with P.DOWNLOAD_LOCK:was_active = P.DOWNLOAD["active"]rid = P.DOWNLOAD.get("repo_id")+ if was_active:+ P.DOWNLOAD["cancelled"] = Trueif not was_active:h._json({"error": "no active download"}, 404); returnP._kill_active_download()@@ -229,6 +235,26 @@ def post_models_repair(h, path, qs, ctype) -> None:"note": f"no corrupt files detected for {key!r}"}); returnif P.HF_BIN is None and (repo.get("mirror") or {}).get("kind") != "github-release":h._json({"error": "hf binary not found. Reinstall Phosphene."}, 500); return+ # CLAIM THE SLOT FIRST, delete second. This deleted the files and only+ # then found another download running — answering 409 "Wait or Cancel"+ # with nothing started to replace what it had just removed (Codex INST-11).+ with P.DOWNLOAD_LOCK:+ if P.DOWNLOAD["active"]:+ h._json({"error": f"another download is in progress: "+ f"{P.DOWNLOAD['repo_id']}. Wait or Cancel."}, 409); return+ P.DOWNLOAD["active"] = True+ P.DOWNLOAD["key"] = key+ P.DOWNLOAD["repo_id"] = repo["repo_id"]+ P.DOWNLOAD["started_ts"] = P.time.time()+ P.DOWNLOAD["last_line"] = "repairing…"+ # The deep-check findings for this repo are CONSUMED by this repair. They+ # carry no file identity, so left in place a second Repair — after this+ # one had fetched good copies — would delete the now-valid files again.+ # A fresh deep check re-finds anything still wrong.+ with P._DEEP_VERIFY_LOCK:+ _dv = P._DEEP_VERIFY.get("result")+ if isinstance(_dv, dict) and _dv.get("bad"):+ _dv["bad"] = [b for b in _dv["bad"] if b.get("repo") != key]target = P.Q8_LOCAL_PATH if key == "q8" else (P.ROOT / repo["local_dir"])deleted = []for fname in bad:@@ -240,15 +266,6 @@ def post_models_repair(h, path, qs, ctype) -> None:deleted.append(fname)except OSError:pass- with P.DOWNLOAD_LOCK:- if P.DOWNLOAD["active"]:- h._json({"error": f"another download is in progress: "- f"{P.DOWNLOAD['repo_id']}. Wait or Cancel."}, 409); return- P.DOWNLOAD["active"] = True- P.DOWNLOAD["key"] = key- P.DOWNLOAD["repo_id"] = repo["repo_id"]- P.DOWNLOAD["started_ts"] = P.time.time()- P.DOWNLOAD["last_line"] = "repairing…"with P._INTEGRITY_LOCK: # bust the cache so the next scan re-checksP._INTEGRITY_CACHE["ts"] = 0.0P.push(f"[repair] {key}: deleted {len(deleted)} corrupt/partial file(s) "@@ -271,6 +288,31 @@ def post_music_install(h, path, qs, ctype) -> None:h._json(payload, code); return+@post("/music/cover/install")+def post_music_cover_install(h, path, qs, ctype) -> None:+ # The opt-in ~2.8 GB that lets YuE2 read a score off a real recording.+ # Separate from /music/install because the engine works without it.+ code, payload = P.music_cover_fetch_start()+ h._json(payload, code); return+++@get("/music/lora/status")+def get_music_lora_status(h, parsed) -> None:+ # What the Voice / style picker can offer right now, plus whatever the+ # background download is doing. /status carries the same block for the+ # first paint; this route is what the picker polls while fetching.+ h._json({**P.music_lora_status(), "fetch": P.music_lora_fetch_state()}); return+++@post("/music/lora/fetch")+def post_music_lora_fetch(h, path, qs, ctype) -> None:+ # The opt-in ~210 MB that makes Instrumental a real adapter instead of a+ # prompt convention. Separate from /music/install: the engine writes songs+ # without it, and a user who never asks for one never pays for it.+ code, payload = P.music_lora_fetch_start()+ h._json(payload, code); return++@post("/music/install/stop")def post_music_install_stop(h, path, qs, ctype) -> None:if not P.music_install_stop():diff --git a/panel/routes_music.py b/panel/routes_music.pynew file mode 100644index 0000000..74e48cf--- /dev/null+++ b/panel/routes_music.py@@ -0,0 +1,821 @@+"""Music Studio routes — the song as a first-class thing.++Every song YuE2 writes keeps its artifacts (plan, tokens, latents, noise),+which is what makes a song something you can come back to rather than a file+you got once. These routes are the verbs on it:++ /music/variation queue a new take, a re-recording, or a restyle of a song+ /music/transcribe listen to a recording and write out its score, no song+ /music/score the sheet music (ABC) and the facts behind one output+ /music/score/render render an EDITED score as a new song+ /music/lyrics Gemma writes lyrics from a concept, in YuE2's own format+ /music/lyrics/section Gemma rewrites ONE section of the lyrics in place+ /music/simple one description in, a whole brief out (Simple mode)++Same shape as the other route modules: `h` is the handler, `P` the panel.+"""+from __future__ import annotations++import json+import time+import uuid+from pathlib import Path+from urllib.parse import parse_qs++from panel.routes import get, post++# `storyboard_edit` (the beat map) pulls in numpy at import time. The panel+# boots without numpy on purpose — a machine that never plans a music video+# must never fail to serve the UI because of one — so both imports are lazy,+# inside the routes that need them (Codex review, 2026-09-20).+music_video = None+storyboard_edit = None+++def _planner():+ """The planner and the beat map, imported on first use, with the beat+ map's ffmpeg pointed at the one the panel resolved — storyboard_edit has a+ resolver of its own that does not know Pinokio's tool folders."""+ global music_video, storyboard_edit+ if music_video is None:+ import music_video as _mv+ import storyboard_edit as _se+ _se.FFMPEG = P.FFMPEG+ if hasattr(_se, "FFPROBE"):+ _se.FFPROBE = P.FFPROBE+ music_video, storyboard_edit = _mv, _se+ return music_video, storyboard_edit+++def _helper_run(spec: dict, timeout: float):+ """The warm helper is the LTX process; the queue kills it when a music or+ H3 job starts, and a lyrics request that lands mid-render would spawn a+ second MLX model beside YuE2. Take the GPU lock like every other GPU+ user — briefly, and say so instead of blocking the browser for a whole+ render when it is taken."""+ if not P._GPU_LOCK.acquire(timeout=3.0):+ raise RuntimeError("A render is using the GPU right now — try again when it finishes.")+ try:+ return P.HELPER.run(spec, timeout=timeout)+ finally:+ P._GPU_LOCK.release()++P = None # the running mlx_ltx_panel module; assigned at wiring time++VARIATIONS = ("take", "sound", "restyle")+++def _one(form, key, default=""):+ v = form.get(key, [default])+ v = v[0] if isinstance(v, list) else v+ return (v if v is not None else default)+++def _sidecar(path: str) -> dict | None:+ try:+ return json.loads(Path(str(path) + ".json").read_text())+ except (OSError, ValueError):+ return None+++def _song_output(path: str) -> Path | None:+ """The output the request names, only if it is one of ours.++ A form field naming a file is a form field naming a file: it is accepted+ when it resolves inside the outputs folder and carries a music sidecar,+ and refused otherwise — never used to read anything else."""+ try:+ p = Path(path).resolve()+ except (OSError, ValueError):+ return None+ if not p.is_relative_to(P.OUTPUT.resolve()) or not p.is_file():+ return None+ meta = _sidecar(str(p))+ if not isinstance(meta, dict) or meta.get("engine") != "music":+ return None+ return p+++def _parent_picks(params: dict) -> list[dict]:+ """The parent's adapters as `[{id, strength}]`, for a form.++ Back through the form as ids and strengths, never as resolved paths:+ `music_params` re-resolves every id inside the LoRA folder, so a sidecar+ can name an adapter and still cannot name a file outside it. JSON rather+ than the browser's `id:strength,…` because an id is a filename and a+ filename may contain a comma."""+ return [{"id": str(pick["id"]).strip(), "strength": pick.get("strength", 1.0)}+ for pick in (params.get("music_loras") or [])+ if isinstance(pick, dict) and str(pick.get("id") or "").strip()]+++def _queue(form: dict) -> dict:+ job = P.make_job(form)+ with P.QUEUE_COND:+ P.STATE["queue"].append(job)+ P.QUEUE_COND.notify_all()+ P.persist_queue()+ return job+++@post("/music/variation")+def post_music_variation(h, path, qs, ctype) -> None:+ _rb = h._read_form_body()+ if _rb is None:+ return+ _body, form = _rb+ kind = _one(form, "kind").strip()+ if kind not in VARIATIONS:+ h._json({"error": f"kind must be one of {', '.join(VARIATIONS)}"}, 400); return+ parent = _song_output(_one(form, "path"))+ if parent is None:+ h._json({"error": "that is not one of this panel's songs"}, 404); return+ meta = _sidecar(str(parent)) or {}+ if kind in ("take", "sound") and P.music_artifacts_for(parent) is None:+ h._json({"error": "That song kept no artifacts, so it cannot be varied. "+ "Songs made before v4.16 need composing again first."}, 409); return+ if kind == "restyle" and not meta.get("score_abc"):+ h._json({"error": "That song has no score to restyle (it was written with No score)."}, 409); return+ # A take or a re-recording keeps the parent's words and style — the runner+ # reads them off the saved plan and ignores the form — so the label, the+ # ETA and the gallery all still say what the song is. A restyle takes the+ # NEW style/lyrics from the form.+ style = _one(form, "style").strip() if kind == "restyle" else (meta.get("style") or "")+ lyrics = _one(form, "lyrics") if kind == "restyle" else (meta.get("lyrics") or "")+ if kind == "restyle" and not style and not lyrics.strip():+ h._json({"error": "A restyle needs a new style, new lyrics, or both."}, 400); return+ params = meta.get("params") if isinstance(meta.get("params"), dict) else {}+ quality = _one(form, "quality") or params.get("music_quality") or "final"+ seconds = _one(form, "max_seconds") or params.get("music_max_seconds") or 240+ job_form = {+ "mode": ["music"], "engine": ["music"],+ "music_style": [style], "music_lyrics": [lyrics],+ "music_mode": [str(meta.get("mode") or "full")],+ "music_instrumental": ["on" if meta.get("instrumental") else "off"],+ "music_quality": [str(quality)], "music_max_seconds": [str(seconds)],+ "music_seed": [_one(form, "seed", "-1") or "-1"],+ "music_title": [_one(form, "title") or (meta.get("title") or "")],+ "music_parent": [str(parent)], "music_variation": [kind],+ "music_precision": [str(params.get("music_precision") or "8bit")],+ # THE ADAPTERS ARE PART OF THE SONG. A take is the same singer singing+ # it again and a re-roll is the same performance recorded again, so a+ # variation that dropped the parent's picks handed back a voice the+ # user never chose, and a sound re-roll lost the acoustic adapter that+ # made the recording sound the way it does (Codex review, 2026-09-22).+ # The mode travels with them: `separate` also swaps the decoder's I/O+ # projections, so a variation without it is a different recipe.+ "music_lora_mode": [str(params.get("music_lora_mode") or "joint")],+ }+ picks = _parent_picks(params)+ if picks:+ job_form["music_loras"] = [json.dumps(picks)]+ try:+ job = _queue(job_form)+ except P.MusicRequestError as exc:+ # The parent's adapter is gone from the LoRA folder: say so rather+ # than make the variation with a different singer.+ h._json({"error": str(exc)}, 409); return+ P.push(f"[music] {kind} of {parent.name} queued as {job['id']}")+ h._json({"ok": True, "id": job["id"], "kind": kind, "parent": str(parent)})+++@post("/music/transcribe")+def post_music_transcribe(h, path, qs, ctype) -> None:+ """Get the score of a recording. A queue job like any other so it never+ races a render for the GPU; the result is fetched by job id."""+ _rb = h._read_form_body()+ if _rb is None:+ return+ _body, form = _rb+ source = P.normalize_pasted_path(_one(form, "path"))+ if not source or not Path(source).is_file():+ h._json({"error": "pick a recording first"}, 400); return+ if not P.music_cover_status()["ready"]:+ h._json({"error": "the transcription models are not installed yet"}, 409); return+ task = _one(form, "task") or "melody-full"+ job = _queue({+ "mode": ["music"], "engine": ["music"],+ "music_style": ["score"], "music_lyrics": [""],+ "music_source_audio": [source], "music_cover_task": [task],+ "music_variation": ["score"], "music_title": [_one(form, "title") or Path(source).stem],+ "music_max_seconds": ["360"], "music_quality": ["draft"],+ })+ h._json({"ok": True, "id": job["id"]})+++@get("/music/score")+def get_music_score(h, parsed) -> None:+ """The sheet music and the song facts behind an output — or behind a+ finished transcription job, by id. (GET handlers take the parsed URL;+ POST handlers take the body — see panel/routes.py.)"""+ q = parse_qs(parsed.query or "")+ job_id = (q.get("job", [""])[0] or "").strip()+ out = (q.get("path", [""])[0] or "").strip()+ meta = None+ if job_id:+ with P.LOCK:+ hist = [j for j in (P.STATE.get("history") or []) if j.get("id") == job_id]+ if not hist:+ h._json({"error": "no such job"}, 404); return+ j = hist[0]+ if j.get("status") != "done" or not j.get("output_path"):+ h._json({"status": j.get("status"), "error": j.get("error")}); return+ meta = _sidecar(j["output_path"])+ out = j["output_path"]+ else:+ p = _song_output(out)+ if p is None:+ h._json({"error": "that is not one of this panel's songs"}, 404); return+ meta = _sidecar(str(p))+ if not isinstance(meta, dict):+ h._json({"error": "no sidecar"}, 404); return+ lineage = meta.get("lineage") if isinstance(meta.get("lineage"), dict) else {}+ h._json({+ "path": out,+ "title": meta.get("title") or "",+ "style": meta.get("style") or "",+ "lyrics": meta.get("lyrics") or "",+ "mode": meta.get("mode"),+ "seed": meta.get("seed"),+ "abc": meta.get("score_abc") or "",+ "cover": meta.get("cover"),+ "variation": (meta.get("variation") or {}).get("kind") if isinstance(meta.get("variation"), dict) else lineage.get("variation"),+ "parent": lineage.get("parent"),+ "has_artifacts": P.music_artifacts_for(out) is not None,+ "audio_seconds": meta.get("audio_seconds"),+ "ended_naturally": meta.get("ended_naturally"),+ "lora": meta.get("lora"),+ "instrumental_recipe": meta.get("instrumental_recipe"),+ })+++@post("/music/score/render")+def post_music_score_render(h, path, qs, ctype) -> None:+ """Render an EDITED score. The text is written into the studio's own+ tree and the job points there; the worker refuses any other path."""+ _rb = h._read_form_body()+ if _rb is None:+ return+ _body, form = _rb+ abc = _one(form, "abc")+ if not abc.strip() or "K:" not in abc:+ h._json({"error": "that does not look like an ABC score (no K: key line)"}, 400); return+ parent = _song_output(_one(form, "path"))+ meta = (_sidecar(str(parent)) or {}) if parent else {}+ style = _one(form, "style").strip() or (meta.get("style") or "")+ lyrics = _one(form, "lyrics")+ if not lyrics.strip():+ lyrics = meta.get("lyrics") or ""+ edits = P.MUSIC_ARTIFACTS / "edits"+ edits.mkdir(parents=True, exist_ok=True)+ # ONE FILE PER REQUEST (M6-06). The name was the parent's stem and the+ # second, and the write overwrote: two edits of one song queued in the+ # same second (two tabs, or a busy queue) both pointed at one file, and+ # the first job sang the second one's notes. Exclusive creation with a+ # random tail cannot hand two jobs the same path.+ stem = (parent.stem if parent else "score") + time.strftime("_%Y%m%d_%H%M%S")+ while True:+ abc_path = edits / f"{stem}_{uuid.uuid4().hex[:8]}.abc"+ try:+ with open(abc_path, "x", encoding="utf-8") as fh:+ fh.write(abc)+ break+ except FileExistsError:+ continue+ mode = str(meta.get("mode") or "full")+ params = meta.get("params") if isinstance(meta.get("params"), dict) else {}+ job_form = {+ "mode": ["music"], "engine": ["music"],+ "music_style": [style], "music_lyrics": [lyrics],+ "music_mode": [mode if mode in ("full", "melody") else "full"],+ "music_quality": [_one(form, "quality") or str(params.get("music_quality") or "final")],+ # THE SLIDER ON SCREEN, THEN THE PARENT'S (M6-01). This read only the+ # parent's saved limit, so a song made at 3:00 re-rendered at 3:00+ # whatever Max length said.+ "music_max_seconds": [_one(form, "max_seconds")+ or str(params.get("music_max_seconds") or 240)],+ "music_seed": [_one(form, "seed", "-1") or "-1"],+ "music_title": [_one(form, "title") or (meta.get("title") or "")],+ "music_abc_path": [str(abc_path)],+ "music_parent": [str(parent) if parent else ""],+ # THE REST OF THE SONG'S RECIPE (M6-03). An edited score is the same+ # song with other notes: it keeps its singer (the adapters, their+ # strengths and mode), Instrumental, the guidance and the precision.+ # Without them `music_params` filled in no adapters, vocals on, joint,+ # the default guidance and 8-bit — a different singer and sound+ # nobody chose, from a note change.+ "music_instrumental": ["on" if meta.get("instrumental") else "off"],+ "music_lora_mode": [str(params.get("music_lora_mode") or "joint")],+ "music_precision": [str(params.get("music_precision") or "8bit")],+ }+ if params.get("music_cfg_scale") is not None:+ job_form["music_cfg_scale"] = [str(params["music_cfg_scale"])]+ picks = _parent_picks(params)+ if picks:+ job_form["music_loras"] = [json.dumps(picks)]+ try:+ job = _queue(job_form)+ except P.MusicRequestError as exc:+ h._json({"error": str(exc)}, 409); return+ h._json({"ok": True, "id": job["id"], "abc_path": str(abc_path)})+++@post("/music/lyrics")+def post_music_lyrics(h, path, qs, ctype) -> None:+ """Gemma writes lyrics from a concept, in the format YuE2 reads."""+ _rb = h._read_form_body()+ if _rb is None:+ return+ _body, form = _rb+ concept = _one(form, "concept").strip()+ if not concept:+ h._json({"error": "say what the song is about"}, 400); return+ try:+ seconds = int(float(_one(form, "seconds", "150") or 150))+ except ValueError:+ seconds = 150+ P.push(f"[lyrics] {concept[:80]}")+ try:+ result = _helper_run({+ "action": "write_lyrics", "id": f"lyr-{int(time.time() * 1000)}",+ "params": {"concept": concept, "style": _one(form, "style").strip(),+ "seconds": seconds, "language": _one(form, "language").strip(),+ "seed": int(_one(form, "seed", "10") or 10)},+ }, timeout=P.PROMPT_ENHANCE_TIMEOUT)+ except Exception as exc: # noqa: BLE001+ P.push(f"[lyrics] failed: {exc}")+ h._json({"error": str(exc)}, 500); return+ lyrics = result.get("lyrics") if isinstance(result, dict) else None+ if not isinstance(lyrics, str) or not lyrics.strip():+ h._json({"error": (result or {}).get("error") or "Gemma returned nothing usable"}, 500); return+ h._json({"ok": True, "lyrics": lyrics, "elapsed_sec": result.get("elapsed_sec")})+++@post("/music/lyrics/section")+def post_music_lyrics_section(h, path, qs, ctype) -> None:+ """Gemma rewrites ONE section of the lyrics.++ The same action and the same resident model as /music/lyrics — what+ differs is that the editor sends the label and the lines it already has,+ and gets back the LINES alone. The tag never travels: the editor owns it,+ and a tag in the answer would land doubled in the box it came from."""+ _rb = h._read_form_body()+ if _rb is None:+ return+ _body, form = _rb+ section = _one(form, "section").strip().strip("[]") or "Verse"+ lines = _one(form, "lines")+ concept = _one(form, "concept").strip()+ # A rewrite can stand on the lines alone; with neither there is nothing+ # to go on, and that is worth saying before the model loads.+ if not concept and not lines.strip():+ h._json({"error": "say what the song is about, or write a line in this "+ "section first"}, 400); return+ try:+ seconds = int(float(_one(form, "seconds", "150") or 150))+ except ValueError:+ seconds = 150+ P.push(f"[lyrics] rewriting [{section}]")+ try:+ result = _helper_run({+ "action": "write_lyrics", "id": f"lyrsec-{int(time.time() * 1000)}",+ "params": {"concept": concept, "style": _one(form, "style").strip(),+ "seconds": seconds, "language": _one(form, "language").strip(),+ "section": section, "lines": lines,+ "seed": int(_one(form, "seed", "10") or 10)},+ }, timeout=P.PROMPT_ENHANCE_TIMEOUT)+ except Exception as exc: # noqa: BLE001+ P.push(f"[lyrics] section failed: {exc}")+ h._json({"error": str(exc)}, 500); return+ out = result.get("lyrics") if isinstance(result, dict) else None+ if not isinstance(out, str) or not out.strip():+ h._json({"error": (result or {}).get("error") or "Gemma returned nothing usable"}, 500); return+ h._json({"ok": True, "section": section, "lines": out,+ "elapsed_sec": result.get("elapsed_sec")})+++@post("/music/simple")+def post_music_simple(h, path, qs, ctype) -> None:+ """Simple mode: one description, and Gemma writes the brief.++ It renders NOTHING. What comes back fills the Custom fields — title,+ style, the lyrics editor — and the person reads it before pressing+ Compose themselves, because a song is minutes of this Mac's GPU and a+ brief nobody read is the expensive way to find that out."""+ _rb = h._read_form_body()+ if _rb is None:+ return+ _body, form = _rb+ description = _one(form, "description").strip()+ if not description:+ h._json({"error": "say what the song should be"}, 400); return+ instrumental = _one(form, "instrumental").strip().lower() in ("on", "1", "true", "yes")+ try:+ seconds = int(float(_one(form, "seconds", "150") or 150))+ except ValueError:+ seconds = 150+ P.push(f"[song] {description[:80]}")+ try:+ result = _helper_run({+ "action": "write_song", "id": f"song-{int(time.time() * 1000)}",+ "params": {"description": description, "instrumental": instrumental,+ "seconds": seconds, "seed": int(_one(form, "seed", "10") or 10)},+ }, timeout=P.PROMPT_ENHANCE_TIMEOUT)+ except Exception as exc: # noqa: BLE001+ P.push(f"[song] failed: {exc}")+ h._json({"error": str(exc)}, 500); return+ style = (result or {}).get("style") if isinstance(result, dict) else None+ if not isinstance(style, str) or not style.strip():+ h._json({"error": (result or {}).get("error") or "Gemma returned nothing usable"}, 500); return+ # Instrumental is the caller's decision, not the model's: it is echoed back+ # so the form and the brief cannot disagree about whether anyone sings.+ h._json({"ok": True, "title": result.get("title") or "", "style": style,+ "lyrics": "" if instrumental else (result.get("lyrics") or ""),+ "instrumental": instrumental, "elapsed_sec": result.get("elapsed_sec")})+++# ===========================================================================+# MUSIC VIDEO — the song and the pictures become a film+# ===========================================================================+# Two verbs. `/music/video/plan` turns a song plus a set of tagged pictures+# into an ordinary storyboard board, which is where it stops: the shot list is+# then rendered, re-rolled and edited by the machinery every other board uses,+# because a music video that could only be shot one way would be a dead end+# the first time somebody wanted shot 7 again. `/music/video/film` is the+# assembly, and the only thing it adds to Export is that the SONG is the bed.+#+# `music_video.py` holds every decision either route makes and imports nothing+# from here — see its docstring. These two functions are the door: they check+# that the paths came from this panel, hand the plan to the board writer the+# storyboard already has, and answer in JSON.++ROLES = ("singer", "instrument", "room") # music_video.ROLES, stated here so the import can stay lazy+USES = ("open", "close", "any") # music_video.USES, same reason+MAX_WEIGHT = 20 # music_video.MAX_WEIGHT, same reason+++def _where_to_put_files() -> str:+ """The second half of every containment refusal.++ The rule itself is not negotiable — a form field naming a file is a form+ field naming a file — but "that is not a file this panel has" is a dead+ end unless it also says where a file BECOMES one. Both answers, because+ the person is sometimes at a terminal and sometimes at the browser."""+ return (f"Pictures and songs have to live in this panel's uploads folder "+ f"({P.UPLOADS}) or its outputs folder ({P.OUTPUT}) — copy the file "+ f"there, drop it on the pane, or send it to POST /upload "+ f"(multipart, field 'image' or 'audio') and use the path that "+ f"comes back.")+++def _panel_file(path: str) -> Path | None:+ """A file this panel made or was given, or None.++ THE CONTAINMENT RULE, the same one `_song_output` applies to songs and for+ the same reason: a form field naming a file is a form field naming a file.+ It resolves inside the outputs folder or the uploads folder, or it is not+ used. Wider than `_song_output` on purpose — an uploaded song and a+ dropped photograph carry no sidecar and never will.+ """+ raw = P.normalize_pasted_path(str(path or "").strip())+ if not raw:+ return None+ try:+ p = Path(raw).resolve()+ except (OSError, ValueError):+ return None+ if not p.is_file():+ return None+ for root in (P.OUTPUT, P.UPLOADS):+ try:+ if p.is_relative_to(Path(root).resolve()):+ return p+ except (OSError, ValueError):+ continue+ return None+++def _music_video_images(raw: str) -> tuple[list, str]:+ """The cast, checked -> (images, error). Every path, every role, every pin."""+ try:+ rows = json.loads(raw or "[]")+ except ValueError as exc:+ return [], f"the pictures are not readable JSON: {exc}"+ if not isinstance(rows, list) or not rows:+ return [], "drop at least one picture first"+ out = []+ for i, row in enumerate(rows, start=1):+ if not isinstance(row, dict):+ return [], f"picture {i} is not an object"+ p = _panel_file(row.get("path"))+ if p is None:+ return [], (f"picture {i} is not a file this panel has "+ f"({row.get('path')!r}). {_where_to_put_files()}")+ role = str(row.get("role") or "").strip().lower()+ if role not in ROLES:+ return [], (f"picture {i}: role {row.get('role')!r} must be one "+ f"of {', '.join(ROLES)}")+ use = str(row.get("use") or "any").strip().lower()+ if use not in USES:+ return [], (f"picture {i}: use {row.get('use')!r} must be one of "+ f"{', '.join(USES)}")+ raw_weight = row.get("weight")+ try:+ weight = int(float(raw_weight)) if raw_weight not in (None, "") else 1+ except (TypeError, ValueError):+ return [], (f"picture {i}: weight {raw_weight!r} must be a whole "+ f"number between 1 and {MAX_WEIGHT}")+ if not (1 <= weight <= MAX_WEIGHT):+ return [], (f"picture {i}: weight {weight} is outside 1–"+ f"{MAX_WEIGHT}")+ # HOW MUCH OF THE PICTURE THE FACE FILLS, 0..1, optional. It decides+ # which Singer leads the close-up rotation and nothing else, so a+ # value that is not a number is a picture with no measurement rather+ # than a refused film - `music_video._face_frac` is the one parser.+ face_frac = row.get("face_frac")+ if face_frac not in (None, ""):+ try:+ face_frac = float(face_frac)+ except (TypeError, ValueError):+ return [], (f"picture {i}: face_frac {row.get('face_frac')!r} "+ f"must be a number between 0 and 1")+ if not (0 < face_frac <= 1):+ return [], (f"picture {i}: face_frac {face_frac} is outside "+ f"0-1 (it is the share of the frame the face fills)")+ out.append({"path": str(p), "role": role,+ "prompt": str(row.get("prompt") or "").strip(),+ "use": use, "weight": weight,+ "face_frac": face_frac if face_frac not in (None, "") else None})+ return out, ""+++def _music_video_shot_prompts(raw: str) -> tuple[dict, str]:+ """`shots` -> ({shot number: line}, error).++ Two spellings, because both are natural: a list of `{"n": 24, "prompt":+ "…"}` (what a caller building from the plan's own shot rows writes) and a+ plain `{"24": "…"}` map (what a person editing JSON by hand writes).+ """+ raw = (raw or "").strip()+ if not raw:+ return {}, ""+ try:+ data = json.loads(raw)+ except ValueError as exc:+ return {}, f"the shot prompts are not readable JSON: {exc}"+ if isinstance(data, dict):+ rows = [{"n": k, "prompt": v} for k, v in data.items()]+ elif isinstance(data, list):+ rows = data+ else:+ return {}, "the shot prompts must be a list or an object"+ out: dict[int, str] = {}+ for i, row in enumerate(rows, start=1):+ if not isinstance(row, dict):+ return {}, f"shot prompt {i} is not an object"+ try:+ n = int(row.get("n"))+ except (TypeError, ValueError):+ return {}, (f"shot prompt {i}: {row.get('n')!r} is not a shot "+ f"number")+ if n < 1:+ return {}, f"shot prompt {i}: shot numbers start at 1"+ line = str(row.get("prompt") or "").strip()+ if not line:+ # A row may pin the PICTURE instead of the line (see+ # `_music_video_shot_images`), so "no prompt" is only empty when+ # the row says nothing at all.+ if str(row.get("image") or "").strip():+ continue+ return {}, f"shot {n}: the prompt is empty"+ out[n] = line+ return out, ""+++def _music_video_shot_images(raw) -> tuple[dict, str]:+ """`shots` -> ({shot number: path}, error).++ The per-shot twin of `_music_video_shot_prompts`, reading the same blob:+ a row may carry a line, a picture, or both. Same containment rule as every+ other path in this file.+ """+ raw = (raw or "").strip()+ if not raw:+ return {}, ""+ try:+ data = json.loads(raw)+ except ValueError as exc:+ return {}, f"the shot prompts are not readable JSON: {exc}"+ rows = data if isinstance(data, list) else []+ out: dict[int, str] = {}+ for i, row in enumerate(rows, start=1):+ if not isinstance(row, dict):+ return {}, f"shot prompt {i} is not an object"+ path = str(row.get("image") or "").strip()+ if not path:+ continue+ try:+ n = int(row.get("n"))+ except (TypeError, ValueError):+ return {}, (f"shot prompt {i}: {row.get('n')!r} is not a shot "+ f"number")+ if n < 1:+ return {}, f"shot prompt {i}: shot numbers start at 1"+ pinned = _panel_file(path)+ if pinned is None:+ return {}, (f"shot {n}: the picture {path!r} is not a file this "+ f"panel has. {_where_to_put_files()}")+ out[n] = str(pinned)+ return out, ""+++def _shot_rows(shots: list) -> list:+ """The shot list as the browser wants it — flat, no board nesting."""+ rows = []+ for s in shots:+ block = s.get("music_video") or {}+ rows.append({+ "n": s.get("n"), "title": s.get("title"),+ "mode": block.get("panel_mode") or s.get("mode"),+ "kind": block.get("kind"), "role": block.get("role"),+ "image": block.get("image"), "frames": block.get("frames"),+ "duration_s": s.get("duration_s"),+ "film_start": block.get("film_start"),+ "audio_start_time": s.get("audio_start_time"),+ "section": block.get("section"),+ "prompt": s.get("prompt"),+ # So a caller re-planning with `shots` can see which lines it+ # already owns and which are still the picture's default.+ "prompt_override": bool(block.get("prompt_override")),+ })+ return rows+++@post("/music/video/plan")+def post_music_video_plan(h, path, qs, ctype) -> None:+ """Song + pictures -> a storyboard board, and the shot list to show.++ WHAT THE CALLER MAY SAY ABOUT THE SONG, strongest first: `sections` (a+ JSON list of `{start, end, kind, label?}` in seconds — the structure+ somebody measured), then `lyrics` / `score_abc` in the form, then the+ song's own sidecar, then the band-energy classifier. Each rung is only+ reached when the one above it is silent, because every rung down is one+ more thing being guessed.+ """+ mv = music_video+ _rb = h._read_form_body()+ if _rb is None:+ return+ _body, form = _rb+ song = _panel_file(_one(form, "song"))+ if song is None:+ h._json({"error": "pick a song from the library, or drop one in. "+ + _where_to_put_files()}, 400)+ return+ images, err = _music_video_images(_one(form, "images"))+ if err:+ h._json({"error": err}, 400); return+ shot_prompts, err = _music_video_shot_prompts(_one(form, "shots"))+ if err:+ h._json({"error": err}, 400); return+ shot_images, err = _music_video_shot_images(_one(form, "shots"))+ if err:+ h._json({"error": err}, 400); return+ style = _one(form, "style").strip()+ # A PRE-SEPARATED VOCAL OF THE SAME SONG, optional. It conditions every+ # singing shot and never reaches the audience: the panel muxes the+ # original song back over each rendered clip. Same containment rule as+ # the song and the pictures - outputs folder or uploads folder, or it is+ # not used.+ vocal_stem_raw = _one(form, "vocal_stem").strip()+ vocal_stem = _panel_file(vocal_stem_raw) if vocal_stem_raw else None+ if vocal_stem_raw and vocal_stem is None:+ h._json({"error": f"the vocal stem is not a file this panel has "+ f"({vocal_stem_raw!r}). {_where_to_put_files()}"}, 400)+ return+ title = _one(form, "title").strip() or (_sidecar(str(song)) or {}).get("title") \+ or song.stem+ meta = _sidecar(str(song)) or {}+ sections_raw = _one(form, "sections").strip()+ lyrics = _one(form, "lyrics")+ score_abc = _one(form, "score_abc")+ # The pass that DELIVERS the film decides the duration axis: the draft+ # pass is a look at the cut, the final pass is the film, and a cell the+ # final canvas cannot render is a shot that dies after an hour.+ quality = str(P.get_settings().get("storyboard_final_quality", "standard")+ or "standard")++ notes = []+ # ONE beat map, read here and handed to both callees. The grid is the+ # expensive part of the whole request (an ffmpeg decode plus an+ # autocorrelation) and both `song_sections` and `plan_music_video` need+ # the same one — two would be two answers about where the bars are.+ try:+ mv, sedit = _planner()+ beats = sedit.beat_map(str(song))+ except Exception as exc: # noqa: BLE001+ h._json({"error": f"could not read the beat of that song: {exc}"}, 400)+ return+ try:+ if sections_raw:+ try:+ rows = json.loads(sections_raw)+ except ValueError as exc:+ h._json({"error": f"the sections are not readable JSON: {exc}"},+ 400)+ return+ sections, given = mv.given_sections(+ rows, duration=float(beats.get("duration") or 0.0),+ start=float((beats.get("span") or [0.0])[0]))+ notes.extend(given)+ else:+ sections = mv.song_sections(+ str(song),+ lyrics=lyrics if lyrics.strip() else meta.get("lyrics"),+ score_abc=score_abc if score_abc.strip() else meta.get("score_abc"),+ beats=beats)+ note = mv.tempo_disagreement(+ beats, (score_abc if score_abc.strip() else meta.get("score_abc")) or "")+ if note:+ notes.append(note)+ # THE DURATION AXIS COMES FROM THE PANEL, not from the planner's own+ # copy: `LTX_LENGTHS` is the table the sampler and `shot_to_job` read,+ # and a cell that exists in one place and not the other is a render+ # that fails after the plan looked fine. It is cut to the delivery+ # QUALITY too — the table's own `qualities` column says the 20 s cell+ # is Quick-only, and a 481-frame a2v shot on the standard 1024×576+ # canvas dies around frame 454.+ out = mv.plan_music_video(+ sections, images, style=style, bpm_grid=beats, song=str(song),+ title=title, board_id=P._sb_new_id(title), quality=quality,+ shot_prompts=shot_prompts, shot_images=shot_images,+ vocal_stem=str(vocal_stem) if vocal_stem else "",+ cells=mv.cells_from_lengths(P.LTX_LENGTHS, quality=quality))+ except mv.MusicVideoError as exc:+ h._json({"error": str(exc)}, 400); return+ except Exception as exc: # noqa: BLE001+ h._json({"error": f"could not plan that video: {exc}"}, 500); return++ board = out["board"]+ # The pass policy is the user's saved Quality, exactly as a planned film+ # gets it — `new_storyboard` hands back the module default, which ignores+ # this machine's canvas cap.+ board["policy"] = P._sb_policy_for(+ P.get_settings().get("storyboard_draft_quality", "quick"),+ P.get_settings().get("storyboard_final_quality", "standard"))+ board["music_video"]["notes"] = list(out["notes"]) + notes+ board["music_video"]["quality"] = quality+ P._sb_normalize(board)+ P.storyboard.save_storyboard(P.STATE_DIR, board)+ P.push(f"[music video] {out['summary']} — {title}")+ h._json({"ok": True, "board_id": board["id"], "title": title,+ "summary": out["summary"], "quality": quality,+ "vocal_stem": str(vocal_stem) if vocal_stem else "",+ "notes": board["music_video"]["notes"],+ "film_seconds": out["film_seconds"],+ "sections": out["board"]["music_video"]["sections"],+ "shots": _shot_rows(out["shots"])})+++@post("/music/video/film")+def post_music_video_film(h, path, qs, ctype) -> None:+ """Assemble the board into one film with the SONG as the bed.++ `music_mode="replace"` is the whole point: every a2v clip's own audio is+ thrown away and the song plays alone, so the master is continuous. The+ lip-sync survives that because each singing shot was rendered against its+ own `audio_start_time` segment of this very file — the mouths are already+ on these words.++ THE AUTO-EDITOR IS OFF BY DEFAULT HERE, and this is the one place the+ music-video lane deliberately differs from Export. `plan_cut` snaps every+ cut BACKWARDS onto the nearest downbeat within half a bar and the cursor+ carries the shortfall forward, so on a board whose shots are fixed LTX+ cells it walks the film earlier and earlier — and every a2v clip after the+ first drift slides off the seconds of the song it was rendered against.+ The board is already cut to the grid (`plan_music_video` put every+ boundary there); a second editor can only take that away. `auto_edit=on`+ is accepted for anyone who wants the trimming anyway and knows the cost.+ """+ _rb = h._read_form_body()+ if _rb is None:+ return+ _body, form = _rb+ try:+ board = P.storyboard.load_storyboard(P.STATE_DIR, _one(form, "board_id").strip())+ except Exception as exc: # noqa: BLE001+ h._json({"error": str(exc)}, 404); return+ block = board.get("music_video") if isinstance(board.get("music_video"), dict) else None+ if not block:+ h._json({"error": "that film was not planned as a music video, so "+ "there is no song to lay under it"}, 409)+ return+ song = _panel_file(block.get("song"))+ if song is None:+ h._json({"error": f"the song is no longer at {block.get('song')!r}"},+ 404)+ return+ auto = _one(form, "auto_edit") in ("1", "true", "on", "yes")+ P._analytics_feature("music_video_film")+ h._json(P._sb_export(board, auto_edit=auto, music=str(song),+ music_mode="replace"))diff --git a/panel/routes_queue.py b/panel/routes_queue.pyindex 579b762..d70a14c 100644--- a/panel/routes_queue.py+++ b/panel/routes_queue.py@@ -501,6 +501,16 @@ def post_prompt_enhance(h, path, qs, ctype) -> None:preserve_tokens = sorted(preserve_set)P.push(f"[enhance] {mode}: {user_prompt[:80]}…"+ (f" preserve={preserve_tokens}" if preserve_tokens else ""))+ # THE GPU GATE, like every other GPU user (routes_music._helper_run). The+ # queue unloads the LTX helper before an H3 or music render; an Enhance+ # click mid-render respawned it and loaded Gemma beside that engine — two+ # models on a Mac sized for one. The worker holds _GPU_LOCK for a whole+ # job, so during any render this answers "busy" at once instead of+ # queueing behind it until the enhance timeout.+ if not P._GPU_LOCK.acquire(timeout=3.0):+ P.push("[enhance] skipped: a render is using the GPU")+ h._json({"error": "A render is using the GPU right now — Enhance "+ "works again when it finishes."}, 409); returntry:result = P.HELPER.run({"action": "enhance_prompt",@@ -511,6 +521,8 @@ def post_prompt_enhance(h, path, qs, ctype) -> None:except Exception as exc:P.push(f"[enhance] failed: {exc}")h._json({"error": str(exc)}, 500); return+ finally:+ P._GPU_LOCK.release()# A malformed terminal helper event must still become JSON. Before# this guard, None/non-string values raised after the only try/except# in the lane and BaseHTTPRequestHandler closed the socket empty.@@ -610,9 +622,11 @@ def post_stop(h, path, qs, ctype) -> None:with P.LOCK:cur = P.STATE.get("current")job_id = (cur or {}).get("id")+ # A One Shot's preview lives under the PART rendering now.+ preview_id = P.live_preview_job_id(cur) if cur else ""if not job_id:h._json({"error": "nothing is rendering"}, 404); return- d = P.live_preview_dir(job_id)+ d = P.live_preview_dir(preview_id)if not d.is_dir():h._json({"error": "this render has no live preview to stop ""through — use Cancel."}, 409); returndiff --git a/pinokio.js b/pinokio.jsindex 0e18995..8a9fbf7 100644--- a/pinokio.js+++ b/pinokio.js@@ -91,16 +91,34 @@ function loadRequired(installRoot) {// shipped behaviour.const ENV_KEYS = ["LTX_MODEL_VERSION", "LTX_H3_ROOT", "LTX_H3_MODELS", "LTX_MUSIC_ROOT", "LTX_MUSIC_MODELS"]+//+// THE SAME GRAMMAR PINOKIO USES. The launcher reads this file with+// dotenv.parse (Pinokio 8.2.0 kernel/util.js parse_env), so the shell, the+// panel and the installers see `LTX_MUSIC_ROOT=/Volumes/Media Drive/YuE` as+// the whole path. This parser took `(\S+)` and silently dropped any value+// with a space — quoted or not — so the sidebar probed the default location+// and offered a fresh install of an engine that was installed, or the wrong+// repair (Codex INST-13, 2026-09-24). DOTENV_LINE is dotenv's own line rule,+// copied rather than required: pinokio.js runs in Pinokio's node, where the+// app's node_modules are not on the resolution path. Last assignment wins,+// as in dotenv.+const DOTENV_LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg+function readEnvironment(installRoot) {const out = {}try {const envPath = path.join(installRoot, "ENVIRONMENT")if (!fs.existsSync(envPath)) return out- const text = fs.readFileSync(envPath, "utf8")- .split("\n").filter(l => !/^\s*#/.test(l)).join("\n")- for (const key of ENV_KEYS) {- const m = text.match(new RegExp("^\\s*" + key + "\\s*=\\s*(\\S+)\\s*$", "m"))- if (m) out[key] = m[1].replace(/^["']|["']$/g, "")+ const text = fs.readFileSync(envPath, "utf8").replace(/\r\n?/g, "\n")+ let m+ DOTENV_LINE.lastIndex = 0+ while ((m = DOTENV_LINE.exec(text)) !== null) {+ if (!ENV_KEYS.includes(m[1])) continue+ const value = (m[2] || "").trim().replace(/^(['"`])([\s\S]*)\1$/, "$2")+ // Pinokio drops an empty value rather than setting it (skill §1), so+ // an empty one leaves the caller on its default here too.+ if (value) out[m[1]] = value+ else delete out[m[1]]}} catch (e) { /* unreadable ENVIRONMENT: every caller keeps its default */ }return out@@ -323,13 +341,23 @@ module.exports = {// the weights are complete `h3_ready` is true — so the only entry left was// "Update Hailuo H3 runner", while the panel told the user to click an// "Install Hailuo H3" that was no longer there. Same markers as the panel's- // _h3_q8_dit_dir(): config + quant recipe + at least one shard.+ // _h3_q8_dit_dir(): config + quant recipe + EVERY shard the index names+ // (non-empty). "At least one shard" let a pack missing four of five read as+ // built, hiding the Build entry that repairs it (Codex H3-04). A pack with+ // no index predates it and keeps the one-shard rule.const h3_q8 = (capH3.model_roots || []).some(root => {try {const dir = h3Path(root + "/h3-dit-q8")- return fs.existsSync(path.join(dir, "config.json"))- && fs.existsSync(path.join(dir, "quant_config.json"))- && fs.readdirSync(dir).some(n => /^model-.*\.safetensors$/.test(n))+ if (!fs.existsSync(path.join(dir, "config.json"))+ || !fs.existsSync(path.join(dir, "quant_config.json"))) return false+ const idx = path.join(dir, "model.safetensors.index.json")+ if (!fs.existsSync(idx)) {+ return fs.readdirSync(dir).some(n => /^model-.*\.safetensors$/.test(n))+ }+ const names = [...new Set(Object.values(JSON.parse(fs.readFileSync(idx, "utf8")).weight_map || {}))]+ return names.length > 0 && names.every(n => {+ try { const st = fs.statSync(path.join(dir, n)); return st.isFile() && st.size > 0 } catch (e) { return false }+ })} catch (e) { return false }})let h3_small = false@@ -455,6 +483,17 @@ module.exports = {// marker: pip writes it last.const ltx_pkg = onDisk("ltx-2-mlx/env/lib/python3.11/site-packages/ltx_pipelines_mlx")const ltx_repair = env_ready && (!ltx_python || !ltx_pkg)+ // WHILE THE PANEL RUNS, the repair cannot be offered directly: install.js+ // reinstalls into the venv the running panel (and its image engine) holds+ // open. But the panel's render error names this sidebar entry, and both+ // running menus used to hide it — the user was sent to a button that did+ // not exist exactly when they needed it (Codex INST-05, 2026-09-24). So the+ // running menu says what to do instead, and opens the terminal whose Stop+ // button is the first half of it.+ const ltxRepairWhileRunning = () => ltx_repair ? [{+ icon: "fa-solid fa-screwdriver-wrench",+ text: "Engine needs repair — Stop the panel, then click Repair Phosphene engine (models kept)",+ href: "start.js" }] : []const pushLtxRepair = (m) => {if (ltx_repair) {m.push({ icon: "fa-solid fa-screwdriver-wrench",@@ -585,6 +624,7 @@ module.exports = {if (local && local.url) {return [{ default: true, icon: "fa-solid fa-rocket", text: "Open Panel", href: local.url },+ ...ltxRepairWhileRunning(),{ icon: "fa-solid fa-terminal", text: "Terminal", href: "start.js" },{ icon: "fa-solid fa-film", text: "Outputs", href: "mlx_outputs?fs=true" },{ icon: "fa-solid fa-cube", text: "Models", href: "mlx_models?fs=true" },@@ -597,19 +637,26 @@ module.exports = {...h3Offer(),]}- return [{ default: true, icon: "fa-solid fa-terminal", text: "Terminal", href: "start.js" }, ...musicMenu(), ...h3Offer()]+ return [{ default: true, icon: "fa-solid fa-terminal", text: "Terminal", href: "start.js" }, ...ltxRepairWhileRunning(), ...musicMenu(), ...h3Offer()]}// Healthy install — Start path.- const baseMenu = [- { default: true, icon: "fa-solid fa-power-off", text: "Start", href: "start.js" },+ //+ // UNLESS THE ENGINE IS BROKEN. `default: true` auto-runs Start, which boots+ // a panel that cannot render and — see ltxRepairWhileRunning — used to hide+ // the repair the moment it came up (INST-05). So a broken engine gets no+ // auto-run at all: Repair goes FIRST, without `default` (auto-running+ // install.js after a failed attempt is the respawn loop documented at+ // install_attempted), and Start stays available below it for anyone who+ // wants the panel anyway.+ const baseMenu = []+ if (ltx_repair) pushLtxRepair(baseMenu)+ baseMenu.push(+ { default: !ltx_repair, icon: "fa-solid fa-power-off", text: "Start", href: "start.js" },{ icon: "fa-solid fa-film", text: "Outputs", href: "mlx_outputs?fs=true" },{ icon: "fa-solid fa-cube", text: "Models", href: "mlx_models?fs=true" },{ icon: "fa-solid fa-image", text: "Uploads", href: "panel_uploads?fs=true" },- ]- // Right under Start, because it is what the user reaches for when Start does- // nothing: base models and clone intact, interpreter gone. See ltx_repair.- pushLtxRepair(baseMenu)+ )if (!q8_ready) {// ~30 GB and what it actually buys on 2.5: trained characters and voices.// High additionally needs the separate 29.5 GB add-on, which is offereddiff --git a/room_tone.py b/room_tone.pyindex 89ae22f..ac34371 100644--- a/room_tone.py+++ b/room_tone.py@@ -318,8 +318,20 @@ def _synth(db: np.ndarray, rng, p: dict) -> np.ndarray:# ---------------------------------------------------------------------------# FROM THIS FILM# ---------------------------------------------------------------------------+#: The ffmpeg the PANEL resolved, set by the panel before it asks for a bed.+#: The panel finds Pinokio's bundled tool folders, which need not be on this+#: process's PATH; this module's own search below does not know them, so on+#: such a Mac "From this film" could not decode a single clip (M6-08).+FFMPEG: str | None = None+++class DecoderMissing(RuntimeError):+ """ffmpeg could not be STARTED. Not the same fact as a clip with no quiet+ sound, and it must not be reported as one."""++def _ffmpeg() -> str:- for c in (os.environ.get("PHOSPHENE_FFMPEG"), shutil.which("ffmpeg"),+ for c in (FFMPEG, os.environ.get("PHOSPHENE_FFMPEG"), shutil.which("ffmpeg"),"/opt/homebrew/bin/ffmpeg", "/usr/local/bin/ffmpeg"):if c and Path(c).exists():return c@@ -337,7 +349,9 @@ def decode_window(path, start: float, end: float, sr: int = SR) -> np.ndarray:"-ar", str(sr), "-f", "s16le", "-acodec", "pcm_s16le", "-"]try:r = subprocess.run(cmd, capture_output=True, timeout=300)- except (OSError, subprocess.SubprocessError):+ except OSError as exc:+ raise DecoderMissing(f"ffmpeg could not be started ({cmd[0]}: {exc})") from exc+ except subprocess.SubprocessError:return np.zeros(0, dtype=np.float32)if r.returncode != 0:return np.zeros(0, dtype=np.float32)@@ -393,6 +407,9 @@ def film_shape(clips, decoder=None) -> dict:seen.add(key)try:x = dec(path, float(c.get("start") or 0.0), float(c.get("end") or 0.0))+ except DecoderMissing as exc:+ # No decoder is no decoder for every clip: stop, and say so.+ return {"db": None, "quiet_s": 0.0, "clips_used": 0, "error": str(exc)}except Exception: # noqa: BLE001continuepsd, secs = quiet_spectrum(x)@@ -427,12 +444,16 @@ def build_loop(variant: str = DEFAULT_VARIANT, seed: int = 1, clips=None,n = LOOP_S * SRfreqs = np.fft.rfftfreq(n, 1.0 / SR)used, fallback, quiet, nclips = variant, "", 0.0, 0+ decoder_error = ""if variant == "film":shape = film_shape(clips, decoder)+ decoder_error = shape.get("error") or ""quiet, nclips = shape["quiet_s"], shape["clips_used"]if shape["db"] is None or quiet < MIN_QUIET_S:used = FALLBACK_VARIANT- fallback = (f"only {quiet:.1f} s of quiet sound in the clips"+ fallback = (f"the clips' sound could not be read — {shape['error']}"+ if shape.get("error")+ else f"only {quiet:.1f} s of quiet sound in the clips"if nclips else "no clip with usable quiet sound")else:wf = np.fft.rfftfreq(WIN, 1.0 / SR)@@ -453,7 +474,8 @@ def build_loop(variant: str = DEFAULT_VARIANT, seed: int = 1, clips=None,loop = (loop * g).astype(np.float32)ref = round(lufs + 20 * math.log10(g), 2)return {"loop": loop, "ref_lufs": ref, "peak": round(peak, 4), "variant": used,- "fallback": fallback, "quiet_s": quiet, "clips_used": nclips}+ "fallback": fallback, "quiet_s": quiet, "clips_used": nclips,+ "decoder_error": decoder_error}def tile(loop: np.ndarray, seconds: float) -> np.ndarray:@@ -546,7 +568,10 @@ def make_bed(dest_dir, *, variant: str = DEFAULT_VARIANT, seed: int = 1,"label": variant_label(res["variant"]), "seed": seed,"fallback": res["fallback"], "quiet_s": res["quiet_s"],"clips_used": res["clips_used"]}- meta.write_text(json.dumps(facts, indent=1), encoding="utf-8")+ # A bed that fell back because the DECODER could not run is not a fact+ # about these clips — do not let the cache answer for them next time.+ if not res.get("decoder_error"):+ meta.write_text(json.dumps(facts, indent=1), encoding="utf-8")facts["reused"] = Falsereturn factsdiff --git a/scripts/check_ltx_pin.js b/scripts/check_ltx_pin.jsindex f0afbaa..0ae5848 100644--- a/scripts/check_ltx_pin.js+++ b/scripts/check_ltx_pin.js@@ -273,13 +273,16 @@ function probe(scenario) {fs.appendFileSync(path.join(clone, ".git", "info", "exclude"), "\nscratch/\n")}git(clone, ["commit", "-q", "--allow-empty", "-m", "local"])- } else if (scenario === "ignored_exact") {+ } else if (scenario === "ignored_exact" || scenario === "ignored_exact_ff") {+ // _ff: NO local commit. `git merge --ff-only` treats an ignored file as+ // expendable and overwrites it without a word, so the guard has to stop+ // the run before the merge, not only before the reset.fs.writeFileSync(path.join(up, "ignored.txt"), "upstream\n")git(up, ["add", "ignored.txt"]); git(up, ["commit", "-qm", "add ignored"])fs.appendFileSync(path.join(clone, ".git", "info", "exclude"), "\nignored.txt\n")fs.writeFileSync(path.join(clone, "ignored.txt"), "MINE\n")protectedPath = "ignored.txt"- git(clone, ["commit", "-q", "--allow-empty", "-m", "local"])+ if (scenario === "ignored_exact") git(clone, ["commit", "-q", "--allow-empty", "-m", "local"])} else if (scenario === "dir_contains_nothing_conflicting"|| scenario === "ignored_dir_contains_nothing_conflicting"|| scenario === "deep_dir_contains_nothing_conflicting") {@@ -327,13 +330,28 @@ function probe(scenario) {execFileSync("which", ["git"]).toString().trim() + ' "$@"\n')fs.chmodSync(path.join(bin, "git"), 0o755)- const script = updateDispatches()- .map((m, i) => `(\n${m}\n)\nrc=$?; [ $rc -eq 0 ] || exit $rc\n`).join("")- const r = spawnSync("bash", ["-c", script], {- cwd: clone, encoding: "utf8",- env: Object.assign({}, G.env, { PATH: bin + ":" + process.env.PATH }),- })- const outText = (r.stdout || "") + (r.stderr || "")+ // PINOKIO'S STEP SEMANTICS, NOT A SHELL'S. This used to join the dispatches+ // with `rc=$?; [ $rc -eq 0 ] || exit $rc`, a guarantee the real launcher+ // does not give: Pinokio 8.2.0 (kernel/shells.js, the default `on` handlers)+ // stops a run only when a step's OUTPUT matches /error:/i or /errno /i, and+ // ignores its exit status. So a guard that printed "FATAL: ... obstruct+ // Update" and exited 1 was followed by the converge step anyway, which+ // reset over the very file the guard had refused to touch (Codex INST-02,+ // 2026-09-24) — while this gate, holding a stricter launcher, passed.+ // Each dispatch runs as its own shell, and the run continues unless the+ // output trips one of those two patterns.+ let outText = "", code = 0+ for (const m of updateDispatches()) {+ const r = spawnSync("bash", ["-c", m], {+ cwd: clone, encoding: "utf8",+ env: Object.assign({}, G.env, { PATH: bin + ":" + process.env.PATH }),+ })+ const o = (r.stdout || "") + (r.stderr || "")+ outText += o+ code = r.status+ if (/error:/i.test(o) || /errno /i.test(o)) break+ }+ const r = { status: code }const protectedValue = fs.existsSync(path.join(clone, protectedPath))&& fs.statSync(path.join(clone, protectedPath)).isFile()? fs.readFileSync(path.join(clone, protectedPath), "utf8").trim() : null@@ -373,6 +391,7 @@ if (probesRan) {["file_blocks_directory", "untracked FILE obstructing an upstream DIRECTORY"],["directory_blocks_file", "untracked DIRECTORY obstructing an upstream FILE"],["ignored_exact", "ignored exact-path obstruction"],+ ["ignored_exact_ff", "ignored exact-path obstruction, no divergence (ff-only would overwrite it)"],["ignored_file_blocks_directory", "ignored FILE obstructing an upstream DIRECTORY"],["ignored_directory_blocks_file", "ignored child beneath an upstream FILE"],]) {diff --git a/scripts/check_post_update.js b/scripts/check_post_update.jsindex fc0d909..cb62588 100644--- a/scripts/check_post_update.js+++ b/scripts/check_post_update.js@@ -149,6 +149,32 @@ for (const [label, re] of mustRequire) {}}+// --- 2d. THE VENDORED PACKAGES' DEPENDENCIES ARE RESOLVED, NOT ASSUMED -------+// The reinstall is --no-deps, which is right for moving the runtime and wrong+// as the ONLY install: on a venv step 0 just rebuilt, nothing installed what+// the packages declare, `mlx-arsenal` above all (core and pipelines import+// `mlx_arsenal.diffusion`; nothing else depends on it). Every Update then+// repeated the same dependency-free install and the import-gate "repair" did+// too — an install that Update could never fix (Codex INST-03, 2026-09-24).+// Reproduced 2026-09-24 in a fresh uv venv: the old sequence ends in+// `No module named 'mlx_arsenal'`; with the dependency pass it imports.+{+ const vendoredLines = code.filter((l) => /\.\/packages\/ltx-core-mlx/.test(l.t))+ const depPass = vendoredLines.find((l) => /uv pip install/.test(l.t) && !/--no-deps/.test(l.t))+ if (!depPass) {+ failures.push("no dependency-resolving install of the vendored packages — the --no-deps reinstall alone leaves a rebuilt venv without mlx-arsenal (INST-03).")+ } else {+ if (depPass.n > reinstall) failures.push(`the vendored dependency pass (line ${depPass.n}) runs AFTER the --no-deps reinstall (line ${reinstall}) — it would re-link the packages editable and leave them that way.`)+ if (!/^require\s/.test(depPass.t.trim())) failures.push(`the vendored dependency pass (line ${depPass.n}) is not wrapped in \`require\`.`)+ if (!/mlx==0\.31\.1/.test(depPass.t) || !/transformers>=5\.0\.0,<5\.13\.0/.test(depPass.t)) failures.push(`the vendored dependency pass (line ${depPass.n}) does not carry the mlx pin and the transformers cap on the same resolve — the solver could move either.`)+ else console.log(` ok vendored dependencies resolved (line ${depPass.n}) before the --no-deps reinstall, pins on the same resolve`)+ }+ const gate = code.find((l) => /import ltx_core_mlx, ltx_pipelines_mlx, mlx/.test(l.t))+ if (gate && !/mlx_arsenal/.test(gate.t)) failures.push("the import gate does not import mlx_arsenal — the package roots import without it, so the gate passes an engine that cannot render.")+ const repair = code.filter((l) => gate && l.n < gate.n && l.n > reinstall && /uv pip install --python env\/bin\/python/.test(l.t))+ if (gate && !repair.some((l) => !/--reinstall|--no-deps/.test(l.t))) failures.push("the import-gate repair only reinstalls --no-deps — it cannot install a missing dependency, so it fails the same way every time.")+}+// --- 3. THE mlx PIN AND THE mflux PIN ARE ONE DECISION -----------------------// Step 2 pins mlx. Step 7 installs mflux WITH deps (the resolving call, there// so a fresh install gets mflux's transitive set). mflux declares its OWN mlxdiff --git a/scripts/fetch_pack_release.py b/scripts/fetch_pack_release.pyindex 802dc3f..8f7a586 100644--- a/scripts/fetch_pack_release.py+++ b/scripts/fetch_pack_release.py@@ -297,11 +297,21 @@ def assemble_file(name: str, spec: dict, dest_dir: Path, mirror: dict,_write_progress(partial, idx + 1)size = partial.stat().st_size- if size != want_bytes:- raise RuntimeError(f"{name}: assembled {size} bytes, manifest declares {want_bytes}")- got = sha256_file(partial)+ got = sha256_file(partial) if size == want_bytes else Noneif got != want_sha:- raise RuntimeError(f"{name}: assembled sha256 {got[:12]}… != manifest {want_sha[:12]}…")+ # DISCARD THE ASSEMBLY, not just the attempt. Every shard verified on+ # its way in, so a bad whole means bytes ALREADY in the partial went bad+ # (a disk error, a copy of a half-synced tree) — and the progress+ # sidecar only checks length. Kept, it made every retry skip the same+ # shards and fail the same hash forever (Codex INST-08). Dropped, the+ # next run refetches this one file; verified files are untouched.+ partial.unlink(missing_ok=True)+ _progress_path(partial).unlink(missing_ok=True)+ if got is None:+ raise RuntimeError(f"{name}: assembled {size} bytes, manifest declares "+ f"{want_bytes} — discarded; the next run refetches it")+ raise RuntimeError(f"{name}: assembled sha256 {got[:12]}… != manifest "+ f"{want_sha[:12]}… — discarded; the next run refetches it")partial.replace(target)_progress_path(partial).unlink(missing_ok=True)log(f"[fetch] {name} — {size >> 20} MB, sha256 verified")diff --git a/scripts/music/yue2_lora.py b/scripts/music/yue2_lora.pynew file mode 100644index 0000000..c1e90a8--- /dev/null+++ b/scripts/music/yue2_lora.py@@ -0,0 +1,596 @@+#!/usr/bin/env python3+"""LoRA inference for the YuE2 MLX engine — Phosphene's own code, not the engine's.++The vendored engine (`lyra`, from vanch007/mlx-Yue) has no adapter support and+is installed from a pinned SHA by `scripts/pinokio/music_sync.sh`, so anything+written inside `yue2-mlx/` is lost on the next sync. This module therefore+lives in OUR repo and works on the models `lyra` hands back, from the runner.++WHAT AN ADAPTER IS HERE+-----------------------+`y = W x + strength · B (A x)`, with `lora_A: [rank, in]` and `lora_B: [out,+rank]`, in BF16, applied at inference and never merged into the base weights.+Not merging is the point: the AR model runs 8-bit by default in Phosphene, and+a merge would either force BF16 (5 GB more resident) or dequantise-requantise+a 3B model per song. A wrapper costs two small matmuls per projection.++HOW IT ATTACHES WITHOUT RENAMING ANYTHING+-----------------------------------------+`nar.load_nar()` validates the shared AR model by walking+`tree_flatten(ar_model.parameters())` and demanding the exact upstream names+(`model.layers.0.self_attn.q_proj.weight`, ...). A wrapper module holding the+original linear as a child would rename every one of them to `...q_proj.base.+weight` and the acoustic model would refuse to load. So the projection object+is kept and its CLASS is swapped for a generated subclass that adds the delta+after the base call; the adapter matrices hang off the instance through+`object.__setattr__`, the way `lyra` itself keeps runtime constants off the+parameter tree. The parameter tree comes out byte-identical, quantised bases+work unchanged, and removal is one `__class__` assignment back.++MODES (Maestro's semantics, replicated)+---------------------------------------+* `joint` — the AR and NAR deltas are ordinary additive LoRAs. The decoder+ I/O projections are NOT touched, even when the file carries them+ (`nar_lora_joint_v9` does; we ignore them and say so).+* `separate`— an artist bundle whose NAR file is a complete decoder companion:+ the deltas still add, and `vae2llm` / `llm2vae` are REPLACED by a+ convex blend of every separate companion, weighted by strength.+ Summing them would double the shared decoder adaptation.++Key spellings accepted: the Mothersuperior `layers.{i}...lora_A` layout, an+optional `model.` prefix, PEFT / AI-Toolkit `base_model.model.` prefixes,+`.lora_A.weight` / `.lora_A.default.weight` spellings, kohya `lora_down` /+`lora_up`, and Maestro's own `.A` / `.B`. A PEFT `alpha` scalar, when present,+is folded into B as `alpha / rank` (the trap that flattened the first H3 LoRA+imports); files without one scale by strength alone, as Mothersuperior's do.+"""+from __future__ import annotations++from dataclasses import dataclass, field+import json+from pathlib import Path+import re+import sys++import mlx.core as mx++# The pack layout (which files, which revisions, how a pick is spelled) is+# STDLIB-ONLY and lives beside the fetcher, because the panel imports it at+# boot to draw the picker and must not pull MLX onto that path. One definition,+# two processes.+sys.path.insert(0, str(Path(__file__).resolve().parents[2]))+from scripts.pinokio.music_lora_fetch import ( # noqa: E402+ INSTRUMENTAL_ADAPTER, JOINT_NAR_ADAPTER, MAX_STRENGTH, USER_SUBDIR,+ pack_adapters, parse_field, parse_picks, parse_spec, resolve_in_pack,+ sha256_of,+ validate_strength,+)++__all__ = [+ "Adapter", "LoRARuntime", "apply_adapters", "branch_of", "check_against",+ "describe_stack", "instrumental_lyrics", "instrumental_recipe", "is_adapted",+ "linear_shape", "load_stack", "normalize_key", "read_adapter",+ "remove_adapters", "style_with_triggers",+ "INSTRUMENTAL_ADAPTER", "JOINT_NAR_ADAPTER", "MAX_STRENGTH", "USER_SUBDIR",+ "pack_adapters", "parse_field", "parse_picks", "parse_spec",+ "resolve_in_pack", "sha256_of",+ "validate_strength",+]++#: One rank ceiling, same as Maestro's. Anything outside this is not a YuE2 LoRA.+MAX_RANK = 128+#: Which attention / MLP container each branch keeps its projections in.+BRANCH_GROUPS = {"ar": ("self_attn", "mlp"), "nar": ("nar_self_attn", "nar_mlp")}+ATTN_PROJECTIONS = ("q_proj", "k_proj", "v_proj", "o_proj")+MLP_PROJECTIONS = ("gate_proj", "up_proj", "down_proj")+#: The acoustic decoder's input/output projections — full weights, not deltas.+IO_MODULES = ("vae2llm", "llm2vae")+MODES = ("joint", "separate")++_ADAPTER_ATTR = "_phosphene_lora"+_ORIGINAL_CLASS_ATTR = "_phosphene_lora_base_class"+_lora_classes: dict[type, type] = {}+++# ---------------------------------------------------------------- key mapping++_PREFIXES = ("base_model.model.model.", "base_model.model.", "base_model.",+ "transformer.", "model.")+# Longest first: `.lora_A.default.weight` must not be eaten by `.lora_A.weight`.+_SUFFIXES = (+ (".lora_A.default.weight", ".lora_A"), (".lora_B.default.weight", ".lora_B"),+ (".lora_A.weight", ".lora_A"), (".lora_B.weight", ".lora_B"),+ (".lora_down.weight", ".lora_A"), (".lora_up.weight", ".lora_B"),+ (".lora_down", ".lora_A"), (".lora_up", ".lora_B"),+ (".A", ".lora_A"), (".B", ".lora_B"),+)+_TARGET_RE = re.compile(+ r"^layers\.(\d+)\.(self_attn|mlp|nar_self_attn|nar_mlp)\."+ r"(q_proj|k_proj|v_proj|o_proj|gate_proj|up_proj|down_proj)$")+++def normalize_key(key: str) -> str:+ """One spelling for the half-dozen an adapter file may arrive in."""+ key = str(key)+ for prefix in _PREFIXES:+ if key.startswith(prefix):+ key = key[len(prefix):]+ break+ for suffix, canonical in _SUFFIXES:+ if key.endswith(suffix):+ return key[: -len(suffix)] + canonical+ return key+++def _describe(name: str) -> tuple[int, str, str] | None:+ match = _TARGET_RE.match(name)+ if match is None:+ return None+ return int(match.group(1)), match.group(2), match.group(3)+++def branch_of(names) -> str:+ """`nar` when the file targets the acoustic branch, `ar` otherwise."""+ for name in names:+ described = _describe(name.rsplit(".", 1)[0]) if name.endswith((".lora_A", ".lora_B")) else None+ if described is not None and described[1].startswith("nar_"):+ return "nar"+ return "ar"+++# ------------------------------------------------------------------- loading++@dataclass+class Adapter:+ """One adapter file, read and checked, ready to hang on a model."""++ path: Path+ branch: str+ strength: float+ mode: str+ rank: int+ deltas: dict[str, tuple[mx.array, mx.array]]+ io: dict[str, mx.array] = field(default_factory=dict)+ trigger: str = ""+ sha256: str = ""+ ignored_io: bool = False++ @property+ def name(self) -> str:+ return self.path.name++ def summary(self) -> dict:+ """What the sidecar records: enough to reproduce, nothing heavy."""+ return {"file": self.name, "path": str(self.path), "branch": self.branch,+ "strength": round(float(self.strength), 4), "mode": self.mode,+ "rank": self.rank, "targets": len(self.deltas),+ "decoder_io": bool(self.io), "decoder_io_ignored": self.ignored_io,+ "trigger": self.trigger, "sha256": self.sha256}+++def read_adapter(path, *, strength: float = 1.0, mode: str = "joint",+ trigger: str = "", with_sha: bool = False) -> Adapter:+ """Read one `.safetensors` adapter into BF16 deltas, or say exactly why not."""+ path = Path(path).expanduser()+ if not path.is_file():+ raise FileNotFoundError(f"No LoRA at {path}")+ if path.suffix.lower() != ".safetensors":+ raise ValueError(f"{path.name}: a YuE2 LoRA is a .safetensors file")+ if mode not in MODES:+ raise ValueError(f"Unsupported LoRA mode {mode!r}; use {' or '.join(MODES)}")+ strength = validate_strength(strength)+ raw = mx.load(str(path))+ if not isinstance(raw, dict) or not raw:+ raise ValueError(f"{path.name}: no named tensors")++ tensors: dict[str, mx.array] = {}+ for key, value in raw.items():+ canonical = normalize_key(key)+ if canonical in tensors:+ raise ValueError(f"{path.name}: two tensors map to {canonical!r}")+ tensors[canonical] = value+ branch = branch_of(tensors)++ pairs: dict[str, list] = {}+ alphas: dict[str, float] = {}+ io: dict[str, mx.array] = {}+ unexpected: list[str] = []+ for name, value in tensors.items():+ stem, _, leaf = name.rpartition(".")+ if leaf in ("lora_A", "lora_B") and _describe(stem) is not None:+ pairs.setdefault(stem, [None, None])[0 if leaf == "lora_A" else 1] = value+ elif leaf == "alpha" and _describe(stem) is not None:+ alphas[stem] = float(value.reshape(-1)[0].item())+ elif stem in IO_MODULES and leaf in ("weight", "bias"):+ io[name] = value+ else:+ unexpected.append(name)+ if unexpected:+ raise ValueError(f"{path.name}: unsupported tensor targets: "+ f"{', '.join(sorted(unexpected)[:5])}")+ if not pairs:+ raise ValueError(f"{path.name}: no LoRA matrices for the AR or acoustic branch")++ ranks: set[int] = set()+ deltas: dict[str, tuple[mx.array, mx.array]] = {}+ for target in sorted(pairs):+ a, b = pairs[target]+ if a is None or b is None:+ raise ValueError(f"{path.name}: {target} is missing its "+ f"{'lora_A' if a is None else 'lora_B'} half")+ if a.ndim != 2 or b.ndim != 2 or b.shape[1] != a.shape[0]:+ raise ValueError(f"{path.name}: {target} is not a [rank,in]/[out,rank] pair")+ rank = int(a.shape[0])+ if not 1 <= rank <= MAX_RANK:+ raise ValueError(f"{path.name}: rank {rank} is outside 1–{MAX_RANK}")+ if not (mx.issubdtype(a.dtype, mx.floating) and mx.issubdtype(b.dtype, mx.floating)):+ raise ValueError(f"{path.name}: {target} is not floating point")+ ranks.add(rank)+ a, b = a.astype(mx.bfloat16), b.astype(mx.bfloat16)+ if target in alphas:+ # PEFT / AI-Toolkit exports carry the scale separately. Folding it+ # here keeps "strength 1.0" meaning the adapter as it was trained.+ b = (b.astype(mx.float32) * (alphas[target] / rank)).astype(mx.bfloat16)+ deltas[target] = (a, b)+ if len(ranks) != 1:+ raise ValueError(f"{path.name}: one rank per adapter, found {sorted(ranks)}")+ for name, value in io.items():+ io[name] = value.astype(mx.bfloat16)+ if io and set(io) != {f"{m}.{k}" for m in IO_MODULES for k in ("weight", "bias")}:+ raise ValueError(f"{path.name}: an incomplete decoder companion "+ f"({', '.join(sorted(io))})")+ if branch == "ar" and io:+ raise ValueError(f"{path.name}: decoder projections belong to an acoustic adapter")++ arrays = [x for pair in deltas.values() for x in pair] + list(io.values())+ mx.eval(arrays)+ for array in arrays:+ if not bool(mx.isfinite(array).all()):+ raise ValueError(f"{path.name}: adapter weights contain non-finite values")++ ignored = bool(io) and mode == "joint"+ return Adapter(path=path, branch=branch, strength=strength, mode=mode,+ rank=ranks.pop(), deltas=deltas, io={} if ignored else io,+ trigger=str(trigger or "").strip(),+ sha256=sha256_of(path) if with_sha else "",+ ignored_io=ignored)+++# ------------------------------------------------------------------ applying++def _lora_class(base: type) -> type:+ """A subclass of the projection's own class that adds the deltas."""+ if base in _lora_classes:+ return _lora_classes[base]++ class _LoRAProjection(base): # type: ignore[misc]+ def __call__(self, x, *args, **kwargs):+ out = super().__call__(x, *args, **kwargs)+ for a, b, scale in object.__getattribute__(self, _ADAPTER_ATTR):+ delta = (x.astype(a.dtype) @ a.T) @ b.T+ out = out + delta.astype(out.dtype) * scale+ return out++ _LoRAProjection.__name__ = f"LoRA{base.__name__}"+ _LoRAProjection.__qualname__ = _LoRAProjection.__name__+ _lora_classes[base] = _LoRAProjection+ return _LoRAProjection+++def _projection_slots(model, branch: str) -> dict[str, tuple[object, str]]:+ """`layers.{i}.{group}.{proj}` → (owning module, attribute name)."""+ if branch not in BRANCH_GROUPS:+ raise ValueError(f"branch must be one of {', '.join(BRANCH_GROUPS)}")+ attn_name, mlp_name = BRANCH_GROUPS[branch]+ backbone = getattr(model, "model", None)+ layers = getattr(backbone, "layers", None)+ if layers is None:+ raise TypeError("This model has no transformer layers to adapt")+ slots: dict[str, tuple[object, str]] = {}+ for index, layer in enumerate(layers):+ for group, projections in ((attn_name, ATTN_PROJECTIONS),+ (mlp_name, MLP_PROJECTIONS)):+ container = getattr(layer, group, None)+ if container is None:+ continue+ for projection in projections:+ if hasattr(container, projection):+ slots[f"layers.{index}.{group}.{projection}"] = (container, projection)+ return slots+++def linear_shape(module) -> tuple[int, int]:+ """(out_features, in_features) for a plain or a quantised linear."""+ weight = module.weight+ out = int(weight.shape[0])+ scales = module.get("scales") if hasattr(module, "get") else None+ if scales is not None:+ return out, int(scales.shape[1]) * int(module.group_size)+ return out, int(weight.shape[1])+++def check_against(adapter: Adapter, model) -> list[str]:+ """Shape-check every delta against the model that will run it."""+ slots = _projection_slots(model, adapter.branch)+ problems: list[str] = []+ for target, (a, b) in adapter.deltas.items():+ slot = slots.get(target)+ if slot is None:+ problems.append(f"{target} is not a projection of this model")+ continue+ out_features, in_features = linear_shape(getattr(slot[0], slot[1]))+ if int(a.shape[1]) != in_features or int(b.shape[0]) != out_features:+ problems.append(+ f"{target} expects [rank,{in_features}]/[{out_features},rank], "+ f"got {tuple(a.shape)}/{tuple(b.shape)}")+ if adapter.io:+ for name, value in adapter.io.items():+ module = getattr(model, name.split(".")[0], None)+ reference = None if module is None else module.get(name.split(".")[1])+ if reference is None:+ problems.append(f"{name} has no counterpart on this model")+ elif tuple(value.shape) != tuple(reference.shape):+ problems.append(f"{name} is {tuple(value.shape)}, "+ f"expected {tuple(reference.shape)}")+ return problems+++def apply_adapters(model, branch: str, adapters) -> int:+ """Hang every adapter for `branch` on `model`. Returns projections wrapped.++ Idempotent per model: applying twice replaces the stack rather than+ doubling it, so a pipeline that reloads a model mid-song cannot drift.+ """+ adapters = [a for a in adapters if a.branch == branch and a.strength > 0]+ remove_adapters(model)+ if not adapters:+ return 0+ for adapter in adapters:+ problems = check_against(adapter, model)+ if problems:+ raise ValueError(f"{adapter.name}: " + "; ".join(problems[:3]))++ stacks: dict[str, list] = {}+ for adapter in adapters:+ for target, (a, b) in adapter.deltas.items():+ stacks.setdefault(target, []).append((a, b, float(adapter.strength)))++ slots = _projection_slots(model, branch)+ for target, stack in stacks.items():+ container, attribute = slots[target]+ module = getattr(container, attribute)+ object.__setattr__(module, _ORIGINAL_CLASS_ATTR, type(module))+ object.__setattr__(module, _ADAPTER_ATTR, tuple(stack))+ module.__class__ = _lora_class(type(module))++ # A complete decoder companion is not a delta: the separate bundles blend+ # their I/O projections by relative strength, and replace the base ones.+ companions = [a for a in adapters if a.mode == "separate" and a.io]+ if companions:+ total = sum(a.strength for a in companions)+ blended: dict[str, mx.array] = {}+ for adapter in companions:+ share = (adapter.strength / total) if total else (1.0 / len(companions))+ for name, value in adapter.io.items():+ scaled = value.astype(mx.float32) * share+ blended[name] = scaled if name not in blended else blended[name] + scaled+ for name, value in blended.items():+ module_name, leaf = name.split(".")+ module = getattr(model, module_name)+ original = getattr(model, "_phosphene_lora_io", None)+ if original is None:+ original = {}+ object.__setattr__(model, "_phosphene_lora_io", original)+ original.setdefault(name, module[leaf])+ module[leaf] = value.astype(mx.bfloat16)+ mx.eval([getattr(model, m)[k] for m in IO_MODULES for k in ("weight", "bias")])+ return len(stacks)+++def remove_adapters(model) -> int:+ """Put every adapted projection (and any replaced decoder I/O) back."""+ restored = 0+ for branch in BRANCH_GROUPS:+ try:+ slots = _projection_slots(model, branch)+ except TypeError:+ return restored+ for container, attribute in slots.values():+ module = getattr(container, attribute)+ original = getattr(module, _ORIGINAL_CLASS_ATTR, None)+ if original is None:+ continue+ module.__class__ = original+ object.__delattr__(module, _ORIGINAL_CLASS_ATTR)+ object.__delattr__(module, _ADAPTER_ATTR)+ restored += 1+ saved = getattr(model, "_phosphene_lora_io", None)+ if saved:+ for name, value in saved.items():+ module_name, leaf = name.split(".")+ getattr(model, module_name)[leaf] = value+ object.__delattr__(model, "_phosphene_lora_io")+ return restored+++def is_adapted(model) -> bool:+ try:+ slots = _projection_slots(model, "ar")+ slots.update(_projection_slots(model, "nar"))+ except TypeError:+ return False+ return any(hasattr(getattr(c, a), _ORIGINAL_CLASS_ATTR) for c, a in slots.values())+++# ------------------------------------------------------- pipeline attachment++class LoRARuntime:+ """Keeps a pipeline's models adapted across its own lazy reloads.++ `YuE2Pipeline._load_model()` builds the AR model for planning, a second+ BF16 AR for acoustic conditioning, and the acoustic model itself — each on+ first use, and the 8-bit path drops and rebuilds them mid-song. Wrapping+ that one method is the only hook that sees every model the song will use.+ """++ def __init__(self, adapters):+ self.adapters = list(adapters)+ self._pipeline = None+ self._original = None+ self._applied: dict[int, int] = {}++ @property+ def active(self) -> bool:+ return bool(self.adapters)++ def summary(self) -> list[dict]:+ return [a.summary() for a in self.adapters]++ def attach(self, pipeline):+ if not self.adapters:+ return self+ if self._pipeline is not None:+ raise RuntimeError("This LoRA runtime is already attached")+ self._pipeline, self._original = pipeline, pipeline._load_model++ def load_model(for_nar=False):+ model = self._original(for_nar=for_nar)+ self.refresh()+ return model++ pipeline._load_model = load_model+ return self++ def refresh(self) -> None:+ """Apply the stack to whichever models the pipeline holds right now."""+ pipeline = self._pipeline+ if pipeline is None:+ return+ for attribute, branch in (("_ar", "ar"), ("_bf16_ar", "ar"), ("_nar", "nar")):+ model = getattr(pipeline, attribute, None)+ if model is None:+ continue+ token = id(model)+ if self._applied.get(token) == len(self.adapters) and is_adapted(model):+ continue+ count = apply_adapters(model, branch, self.adapters)+ if count:+ self._applied[token] = len(self.adapters)++ def detach(self) -> None:+ pipeline, self._pipeline = self._pipeline, None+ if pipeline is None:+ return+ pipeline._load_model = self._original+ self._original = None+ for attribute in ("_ar", "_bf16_ar", "_nar"):+ model = getattr(pipeline, attribute, None)+ if model is not None:+ remove_adapters(model)+ self._applied.clear()++ def __enter__(self):+ return self++ def __exit__(self, *exc):+ self.detach()+ return False+++# --------------------------------------------------------- instrumental mode++#: Maestro's own prompt. A bare `[instrumental]` lets the model pick sections.+INSTRUMENTAL_PROMPT = "[instrumental]"+INSTRUMENTAL_COT = "full"+_SECTION_RE = re.compile(+ r"\[(intro|verse|pre-chorus|chorus|bridge|outro)(?: (\d+):([0-5]\d)-(\d+):([0-5]\d))?\]",+ re.IGNORECASE)+++def instrumental_lyrics(lyrics) -> str:+ """Bare section tags survive; anything else becomes `[instrumental]`.++ Sung prose fed to this adapter is what produces a vocal-like track, so the+ three caption forms Maestro accepts are the only ones that pass through.+ """+ lines = str(lyrics or "").strip().splitlines()+ plan: list[str] = []+ previous_end = 0+ for line in lines:+ if not line.strip():+ continue+ match = _SECTION_RE.fullmatch(line.strip())+ if match is None:+ return INSTRUMENTAL_PROMPT+ tag, start_min, start_sec, end_min, end_sec = match.groups()+ if start_min is not None:+ start = int(start_min) * 60 + int(start_sec)+ end = int(end_min) * 60 + int(end_sec)+ if start < previous_end or end <= start:+ return INSTRUMENTAL_PROMPT+ previous_end = end+ plan.append(line.strip().lower())+ return "\n".join(plan) or INSTRUMENTAL_PROMPT+++def instrumental_recipe(lora_root, lyrics="") -> dict:+ """Maestro's recipe: the AR adapter at 1.0, full score planning, stock decoder.++ Returns the pieces the runner applies; `adapter` is None when the pack is+ not downloaded, and the caller falls back to the prompt-only instrumental+ that shipped in v4.16 rather than failing a queued song.+ """+ adapter = None+ if lora_root is not None:+ candidate = Path(lora_root).expanduser() / INSTRUMENTAL_ADAPTER+ if candidate.is_file():+ adapter = candidate+ return {"adapter": adapter, "strength": 1.0, "cot": INSTRUMENTAL_COT,+ "lyrics": instrumental_lyrics(lyrics) if adapter else None,+ "decoder": "stock", "pauses_other_loras": True}+++def style_with_triggers(style: str, adapters) -> str:+ """Add each adapter's training trigger to the style prompt once."""+ style = str(style or "")+ folded = style.casefold()+ missing: list[str] = []+ for adapter in adapters:+ trigger = (adapter.trigger or "").strip()+ if trigger and trigger.casefold() not in folded and \+ trigger.casefold() not in {m.casefold() for m in missing}:+ missing.append(trigger)+ if not missing:+ return style+ return ", ".join([*missing, style] if style else missing)+++def load_stack(specs, *, mode="joint", triggers=(), with_sha=True) -> list[Adapter]:+ """`[(path, strength), ...]` → checked adapters, in the order given."""+ triggers = list(triggers)+ adapters = []+ for index, (path, strength) in enumerate(specs):+ adapters.append(read_adapter(+ path, strength=strength, mode=mode, with_sha=with_sha,+ trigger=triggers[index] if index < len(triggers) else ""))+ return adapters+++def describe_stack(adapters, *, instrumental=None) -> dict:+ """The sidecar block. Says what ran, at what strength, from which file."""+ return {"adapters": [a.summary() for a in adapters],+ "modes": sorted({a.mode for a in adapters}),+ "branches": sorted({a.branch for a in adapters}),+ "triggers": [a.trigger for a in adapters if a.trigger],+ "instrumental": instrumental}+++if __name__ == "__main__": # pragma: no cover+ import argparse++ parser = argparse.ArgumentParser(description="Inspect a YuE2 LoRA file.")+ parser.add_argument("path", type=Path, nargs="+")+ parsed = parser.parse_args()+ for one in parsed.path:+ adapter = read_adapter(one, with_sha=True)+ print(json.dumps(adapter.summary(), indent=2))diff --git a/scripts/music/yue2_run.py b/scripts/music/yue2_run.pyindex 999d299..b3d1270 100644--- a/scripts/music/yue2_run.py+++ b/scripts/music/yue2_run.py@@ -28,6 +28,7 @@ import argparseimport jsonimport osimport platform+import shutilimport signalimport sysimport threading@@ -58,9 +59,76 @@ def parse_args(argv=None):p.add_argument("--lyrics", default=None)p.add_argument("--lyrics-file", type=Path, default=None)p.add_argument("--abc-file", type=Path, default=None, help="supplied ABC score (full/melody only)")+ # COVER: a real recording in, a new song out. The transcriber (SheetSage2 ++ # MERT-v2) writes an ABC score of the source, and that score becomes the+ # plan the generator realises under a NEW style and NEW lyrics. It is the+ # same road as --abc-file, with the score read off a record instead of+ # typed.+ p.add_argument("--source-audio", type=Path, default=None,+ help="cover this recording: transcribe it, then render the score")+ p.add_argument("--cover-task", choices=("full", "melody-full", "melody-vocal"),+ default="melody-full",+ help="full = melody+chords+accompaniment, melody-full = melody+chords "+ "from the mix, melody-vocal = the sung line only")+ p.add_argument("--transcription-model", default="m-a-p/SheetSage2")+ p.add_argument("--transcription-base-model", default="m-a-p/MERT-v2-FullSong")+ p.add_argument("--transcription-cache", type=Path, default=None,+ help="local HF cache holding the two transcription models")+ p.add_argument("--cover-seconds", type=float, default=None,+ help="transcribe only the first N seconds of the source")+ # VARIATIONS. A song's artifact folder holds its plan (the score and the+ # tokenised prefix), its semantic tokens, its latents and its noise. Each+ # is a place to restart from, and each restart is a different kind of+ # "again":+ # take — same score, same words, a NEW PERFORMANCE: the semantic stage+ # is re-run from the saved plan with a new seed. Costs a full+ # song minus the planning.+ # sound — same performance, a NEW RECORDING of it: the saved semantic+ # tokens are re-synthesised with fresh solver noise and decoded.+ # Costs the NAR + VAE only — a fraction of a song.+ # (A "restyle" — same score, new words or style — is --abc-file pointed at+ # the saved score.abc; the panel builds that one itself.)+ p.add_argument("--from-artifacts", type=Path, default=None,+ help="a song's artifact folder to vary")+ p.add_argument("--variation", choices=("take", "sound"), default=None)+ # SCORE ONLY: listen to a recording and write out its ABC score, no song.+ p.add_argument("--transcribe-only", action="store_true",+ help="with --source-audio: write the score and stop")+ p.add_argument("--title", default="", help="carried into the sidecar only")p.add_argument("--mode", choices=("full", "melody", "off"), default="full")p.add_argument("--instrumental", action="store_true",- help="no vocal line: lyrics become bare section tags (see INSTRUMENTAL_LYRICS)")+ help="no vocal line. With the LoRA pack installed this is Maestro's "+ "recipe — the instrumental AR adapter at 1.0, full score planning, "+ "'[instrumental]' in place of words; without it, bare section tags")+ # ---- LoRA ---------------------------------------------------------------+ # Adapters are applied to the loaded MLX models at inference and never+ # merged: the AR model runs 8-bit here, and a merge would cost either 5 GB+ # more resident weights or a dequantise/requantise per song.+ p.add_argument("--lora", action="append", default=[], metavar="PATH[:STRENGTH]",+ help="a YuE2 adapter to run, repeatable; strength 0–1.5, default 1.0")+ p.add_argument("--lora-mode", choices=("joint", "separate"), default="joint",+ help="joint: additive deltas only (Mothersuperior's nar_lora_joint_*). "+ "separate: an artist bundle whose acoustic file also REPLACES the "+ "decoder's vae2llm/llm2vae, blended across bundles by strength")+ p.add_argument("--lora-trigger", action="append", default=[], metavar="WORD",+ help="training trigger for the matching --lora, added to the style once")+ p.add_argument("--lora-dir", type=Path, default=None,+ help="the LoRA pack folder; --instrumental reads its AR adapter from here")+ # ---- AUDIO PROMPT -------------------------------------------------------+ # Continue a REAL recording. The tokenizer head turns its first seconds+ # into YuE2 semantic codes; those codes become the prefix the song is+ # written from, so the model hears the take rather than reading about it.+ p.add_argument("--audio-prompt", type=Path, default=None,+ help="continue this recording: tokenise it and use its codes as the "+ "semantic prefix")+ p.add_argument("--audio-prompt-seconds", type=float, default=10.0,+ help="how much of the recording to hear (default 10 s)")+ p.add_argument("--audio-prompt-start", type=float, default=0.0,+ help="where in the recording to start listening")+ p.add_argument("--audio-prompt-head", type=Path, default=None,+ help="the tokenizer head (default: the LoRA pack's tokenizer/ folder)")+ p.add_argument("--mert-dir", type=Path, default=None,+ help="MERT-v2-FullSong checkpoint for the audio prompt")p.add_argument("--seed", type=int, default=-1)p.add_argument("--max-seconds", type=float, default=MAX_SECONDS)p.add_argument("--steps", type=int, default=32, help="flow-matching midpoint steps (32 = reference)")@@ -129,27 +197,93 @@ def relax_guard():def main(argv=None):args = parse_args(argv)t0 = time.perf_counter()+ os.environ.setdefault("MLX_ENABLE_TF32", "0")+ # lyra/pipeline.py rejects these PyTorch MPS vars (it's an MLX runtime; fallback+ # paths are not validated). Strip them if the parent env (e.g. Pinokio) set them.+ # Settled here, at the top, because the LoRA module imports MLX while the+ # request is still being read — long before the pipeline is built.+ os.environ.pop("PYTORCH_ENABLE_MPS_FALLBACK", None)+ os.environ.pop("PYTORCH_MPS_FAST_MATH", None)out = args.output.expanduser().resolve()- if out.suffix.lower() not in (".wav", ".flac"):- say("error", "output must end in .wav or .flac")+ want = (".abc",) if args.transcribe_only else (".wav", ".flac")+ if out.suffix.lower() not in want:+ say("error", f"output must end in {' or '.join(want)}")+ return 2+ if args.transcribe_only and not args.source_audio:+ say("error", "--transcribe-only needs --source-audio")return 2+ if (args.variation is None) != (args.from_artifacts is None):+ say("error", "--variation and --from-artifacts go together")+ return 2+ if args.from_artifacts is not None and not (args.from_artifacts / "result.json").is_file():+ say("error", f"no saved song at {args.from_artifacts} — only songs made with "+ f"artifacts kept can be varied")+ return 2+ if args.audio_prompt is not None:+ if args.variation is not None or args.transcribe_only:+ say("error", "--audio-prompt is for writing a new song, not for a variation "+ "or a transcription")+ return 2+ if not args.audio_prompt.expanduser().is_file():+ say("error", f"audio prompt not found: {args.audio_prompt}")+ return 2+ if not 1.0 <= float(args.audio_prompt_seconds) <= 60.0:+ say("error", "--audio-prompt-seconds must be between 1 and 60")+ return 2if args.lyrics_file is not None:lyrics = args.lyrics_file.read_text(encoding="utf-8")else:lyrics = args.lyrics or ""style = (args.style or "").strip()lyrics = lyrics.replace("\r\n", "\n").strip("\n")+ sys.path.insert(0, str(Path(__file__).resolve().parent))+ import yue2_lora++ # ---- INSTRUMENTAL -------------------------------------------------------+ # Two recipes, and which one runs depends only on whether the 140 MB AR+ # adapter is on disk. With it: Maestro's — adapter at 1.0, full score+ # planning, `[instrumental]` (or the author's bare section tags) in place+ # of words, other LoRAs paused, stock acoustic decoder. Without it: the+ # tag skeleton that shipped in v4.16, which was validated by ear. A queued+ # song must never fail because an optional download is missing.+ lora_specs = [yue2_lora.parse_spec(spec) for spec in (args.lora or [])]+ instrumental_info = Noneif args.instrumental:- lyrics = INSTRUMENTAL_LYRICS+ recipe = yue2_lora.instrumental_recipe(args.lora_dir, lyrics)+ if recipe["adapter"] is not None:+ lyrics = recipe["lyrics"]+ args.mode = recipe["cot"]+ paused = [str(path) for path, _ in lora_specs]+ lora_specs = [(recipe["adapter"], recipe["strength"])]+ instrumental_info = {"recipe": "mothersuperior-ar-lora",+ "adapter": recipe["adapter"].name,+ "strength": recipe["strength"], "cot": recipe["cot"],+ "decoder": recipe["decoder"], "paused_loras": paused}+ else:+ lyrics = INSTRUMENTAL_LYRICS+ instrumental_info = {"recipe": "section-tags", "adapter": None,+ "reason": "the instrumental LoRA is not installed"}if "instrumental" not in style.lower():style = f"{style}, {INSTRUMENTAL_STYLE}" if style else INSTRUMENTAL_STYLE- if not style and not lyrics.strip():+ if not style and not lyrics.strip() and args.variation is None and not args.transcribe_only:say("error", "Give it something to work with — lyrics, a style description, or both.")return 2abc = args.abc_file.read_text(encoding="utf-8") if args.abc_file else Noneif abc is not None and args.mode == "off":say("error", "a supplied score needs mode full or melody")return 2+ cover_source = args.source_audio.expanduser() if args.source_audio else None+ if cover_source is not None:+ if abc is not None:+ say("error", "a cover reads its score off the recording — drop the ABC file")+ return 2+ if not cover_source.is_file():+ say("error", f"source song not found: {cover_source}")+ return 2+ # The transcription task decides the planning mode, exactly as upstream's+ # own cover command does: a full transcription can only be realised by+ # full planning, a melody-only one by melody planning.+ args.mode = "full" if args.cover_task == "full" else "melody"seed = args.seed if args.seed is not None and args.seed >= 0 else int.from_bytes(os.urandom(4), "little")max_seconds = max(8.0, min(float(args.max_seconds), float(MAX_SECONDS)))max_tokens = int(round(max_seconds * TOKENS_PER_SECOND))@@ -164,11 +298,6 @@ def main(argv=None):signal.signal(signal.SIGTERM, on_signal)signal.signal(signal.SIGINT, on_signal)- os.environ.setdefault("MLX_ENABLE_TF32", "0")- # lyra/pipeline.py rejects these PyTorch MPS vars (it's an MLX runtime; fallback- # paths are not validated). Strip them if the parent env (e.g. Pinokio) set them.- os.environ.pop("PYTORCH_ENABLE_MPS_FALLBACK", None)- os.environ.pop("PYTORCH_MPS_FAST_MATH", None)say("stage", "loading")import mlx.core as mxfrom yue2.protocol import GenerationConfig@@ -176,6 +305,136 @@ def main(argv=None):guard = relax_guard()budget = args.memory_budget_gib or default_budget_gib()++ # ---- COVER: transcribe first, and let go of the transcriber -----------+ # Order is the whole trick. SheetSage2 + MERT-v2 is ~2.8 GB of weights and+ # YuE2 is ~10 GB; on a 24 GB Mac the two together are the difference+ # between a song and the memory guard. Upstream's own cover command does+ # the same thing — transcribe inside the guard, collect, clear the Metal+ # cache, and only then build the generator — so the two never coexist.+ cover_info = None+ if cover_source is not None:+ import gc++ from lyra.measure import GPUExecution+ from lyra.transcription.pipeline import transcribe++ say("stage", "listening")+ # BESIDE the artifacts folder, never inside it: save_artifacts() insists on+ # an empty directory, and a transcription placed inside it made every+ # cover fail AFTER the song was published (Codex review, 2026-09-20).+ base = args.artifacts.parent if args.artifacts is not None else out.parent+ work = base / ((args.artifacts.name if args.artifacts is not None else out.stem) + ".transcription")+ if work.exists() and any(work.iterdir()):+ shutil.rmtree(work)+ try:+ with GPUExecution(memory_budget_gib=budget):+ transcription = transcribe(+ cover_source, work,+ model_path=args.transcription_model,+ base_model=args.transcription_base_model,+ cache_dir=str(args.transcription_cache) if args.transcription_cache else None,+ offline=args.transcription_cache is not None,+ task=args.cover_task,+ max_seconds=args.cover_seconds,+ cancelled=stop.is_set,+ )+ except InterruptedError:+ say("error", "stopped")+ return 130+ except MemoryError as exc:+ say("error", f"memory guard: {exc}")+ return 3+ except FileNotFoundError as exc:+ # The two transcription models are a separate, optional download.+ # Say which thing is missing rather than surfacing a cache path.+ say("error", f"the cover models are not installed yet ({exc}). "+ f"Install them from Compose - Cover a song.")+ return 2+ gc.collect()+ mx.clear_cache()+ if transcription.get("status") != "complete" or transcription.get("truncated"):+ say("error", "the transcription came out incomplete — try a shorter "+ "excerpt with --cover-seconds, or a cleaner recording")+ return 2+ abc = (work / "score.abc").read_text(encoding="utf-8")+ cover_info = {"source_sha256": transcription.get("source_audio_sha256"),+ "task": args.cover_task,+ "seconds_read": args.cover_seconds,+ "artifacts": str(work)}+ if args.transcribe_only:+ # "Get the score": the recording's sheet music, nothing rendered.+ # Same sidecar shape as a song so the gallery reads it the same+ # way — minus everything about audio that was never made.+ out.parent.mkdir(parents=True, exist_ok=True)+ out.write_text(abc, encoding="utf-8")+ side = args.sidecar or out.with_name(out.name + ".json")+ side.write_text(json.dumps({+ "engine": "music", "kind": "score", "title": args.title,+ "score_abc": abc, "cover": cover_info, "source": str(cover_source),+ "wall_seconds": round(time.perf_counter() - t0, 2),+ "runner": f"phosphene yue2_run v{RUNNER_VERSION}",+ **(json.loads(args.extra_json) if args.extra_json else {}),+ }, indent=2, ensure_ascii=False, default=str), encoding="utf-8")+ say("done", "0.00", str(out))+ return 0+ say("stage", "covering")+ # ---- AUDIO PROMPT: listen first, then let the listener go ---------------+ # Same order, and the same reason, as the cover path above: MERT-v2 is+ # ~2.5 GB of weights and YuE2 is ~10 GB. Tokenise inside the guard, drop+ # the frontend, clear the Metal cache, and only then build the generator.+ audio_prompt_codes = None+ audio_prompt_info = None+ if args.audio_prompt is not None:+ import gc++ from lyra.measure import GPUExecution+ import yue2_tokenizer++ say("stage", "listening")+ head_file = args.audio_prompt_head or yue2_tokenizer.head_path(+ args.lora_dir or (Path(__file__).resolve().parents[2] / "mlx_models" / "yue2-loras"))+ listen_started = time.perf_counter()+ try:+ with GPUExecution(memory_budget_gib=budget):+ audio_prompt_codes, prompt_meta = yue2_tokenizer.encode_codes(+ args.audio_prompt, head_file=head_file, mert_dir=args.mert_dir,+ start=float(args.audio_prompt_start),+ seconds=float(args.audio_prompt_seconds),+ cancelled=stop.is_set,+ on_stage=lambda text: say("listen", text))+ except InterruptedError:+ say("error", "stopped")+ return 130+ except MemoryError as exc:+ say("error", f"memory guard: {exc}")+ return 3+ except FileNotFoundError as exc:+ say("error", f"the real-audio tokenizer head is not installed yet ({exc}). "+ f"Fetch the LoRA pack to get it.")+ return 2+ except (OSError, ValueError, RuntimeError) as exc:+ say("error", f"could not listen to the audio prompt: {exc}")+ return 2+ gc.collect()+ mx.clear_cache()+ audio_prompt_info = {+ "path": str(args.audio_prompt.expanduser()),+ "seconds": float(args.audio_prompt_seconds),+ "start_seconds": float(args.audio_prompt_start),+ "frames": int(len(audio_prompt_codes)),+ "head": prompt_meta["head"].get("version"),+ "head_file": Path(head_file).name,+ "head_sha256": prompt_meta["head"].get("sha256"),+ "mert_layer": prompt_meta["features"]["mert_layer"],+ "resampler": prompt_meta["features"]["resampler"],+ "statistics": prompt_meta["statistics"],+ "listen_seconds": round(time.perf_counter() - listen_started, 2),+ }+ say("stage", f"heard {audio_prompt_info['frames']} codes "+ f"({audio_prompt_info['frames'] / TOKENS_PER_SECOND:.1f} s) in "+ f"{audio_prompt_info['listen_seconds']:.2f}s")+counts = {"abc": 0, "semantic": 0}last = {"t": 0.0}@@ -189,6 +448,26 @@ def main(argv=None):else:say("song", f"{counts['semantic']}/{max_tokens}")+ # ---- LORA STACK ---------------------------------------------------------+ # Read and shape-checked BEFORE the pipeline is built, so a bad adapter+ # costs a second rather than ten minutes. Applied through a wrapper on+ # `_load_model`, which is the only hook that sees all three models a song+ # uses (the planning AR, the BF16 conditioning AR, and the acoustic model+ # built halfway through).+ adapters = []+ if lora_specs:+ try:+ adapters = yue2_lora.load_stack(+ lora_specs, mode=args.lora_mode, triggers=args.lora_trigger)+ except (OSError, ValueError) as exc:+ say("error", f"{exc}")+ return 2+ for adapter in adapters:+ say("stage", f"lora {adapter.name} · {adapter.branch} · rank {adapter.rank} "+ f"· strength {adapter.strength:g}")+ style = yue2_lora.style_with_triggers(style, adapters)+ lora_runtime = yue2_lora.LoRARuntime(adapters)+config = GenerationConfig(ode_steps=int(args.steps))pipe = YuE2Pipeline(args.model_dir, args.vae_dir, precision=args.precision, generation_config=config,@@ -218,18 +497,110 @@ def main(argv=None):return _orig_decode(self, *a, on_progress=report, **kw)_vae.OobleckDecoder.decode = decode_with_progress+ lora_runtime.attach(pipe)peak = {"gib": 0.0}try:with pipe:- say("stage", "planning" if args.mode != "off" and abc is None else "writing")- kw = dict(style=style, lyrics=lyrics, cot=args.mode, seed=seed,- semantic_sampling=semantic_sampling, cancelled=stop.is_set,- on_token=on_token)- if abc is not None:- kw["abc"] = abc- if args.cfg_scale is not None:- kw["cfg_scale"] = float(args.cfg_scale)- result = pipe(**kw)+ variation_info = None+ if args.variation is not None:+ from dataclasses import replace++ from lyra.pipeline import SongResult, initial_noise+ from yue2.storage import identity++ if args.variation == "take":+ # Same score, same words — a new performance. The saved plan+ # carries the tokenised prefix (style, lyrics, mode) and the+ # score IDs; only the request seed changes, and the seed is+ # not part of the prefix, so the plan stays valid as-is.+ from yue2.pipeline import SymbolicPlan+ plan = SymbolicPlan.load(args.from_artifacts)+ plan = replace(plan, request=replace(plan.request, seed=seed))+ style, lyrics, abc = plan.request.style, plan.request.lyrics, plan.abc+ args.mode = plan.request.cot+ say("stage", "writing")+ semantic = pipe.generate_semantic(plan, sampling=semantic_sampling,+ cancelled=stop.is_set, on_token=on_token)+ noise_seed = seed+ else:+ # Same performance — a new recording of it. The semantic+ # tokens are the song; fresh solver noise through the NAR+ # and the decoder is a different take on how it SOUNDS.+ # This is the cheap one: no planning, no semantic stage.+ from lyra.artifacts import load_artifacts+ saved = load_artifacts(args.from_artifacts)+ semantic = saved.semantic+ plan = semantic.plan+ style, lyrics, abc = plan.request.style, plan.request.lyrics, plan.abc+ args.mode = plan.request.cot+ seed = plan.request.seed # the song's own seed, unchanged+ noise_seed = int.from_bytes(os.urandom(4), "little") if args.seed < 0 else args.seed+ say("stage", "recording")+ noise = initial_noise(len(semantic.tokens), noise_seed)+ latents = pipe.synthesize(semantic, noise=noise, cancelled=stop.is_set)+ audio = pipe.decode(latents, cancelled=stop.is_set)+ cfg = pipe.effective_config(plan.request, semantic_sampling=semantic_sampling)+ stamp = identity({"request": plan.request.to_dict(), "config": cfg,+ "weights": pipe.weights})+ timing = {"abc": plan.timing, "semantic": semantic.timing,+ "load": dict(pipe.load_timing)}+ result = SongResult(audio, 48000, semantic, latents, cfg, pipe.weights,+ timing, stamp, noise)+ variation_info = {"kind": args.variation, "from": str(args.from_artifacts),+ "noise_seed": noise_seed}+ elif audio_prompt_codes is not None:+ # ---- CONTINUATION ------------------------------------------+ # `pipe()` plans, writes and synthesises in one call and has no+ # seam for a prefix, so the three stages are run in the open+ # here — the same sequence, with the recording's codes joined+ # to the request prefix before the semantic stage and kept at+ # the head of the token stream afterwards.+ from lyra.pipeline import SongResult, initial_noise+ from yue2.storage import identity++ import yue2_tokenizer++ request_kw = {"cot": args.mode, "seed": seed}+ if abc is not None:+ request_kw["abc"] = abc+ if args.cfg_scale is not None:+ request_kw["cfg_scale"] = float(args.cfg_scale)+ request = pipe._request(style, lyrics, **request_kw)+ cfg = pipe.effective_config(request, semantic_sampling=semantic_sampling)+ stamp = identity({"request": request.to_dict(), "config": cfg,+ "weights": pipe.weights})+ started = time.perf_counter()+ say("stage", "planning" if args.mode != "off" and abc is None else "writing")+ plan = pipe.plan(request=request, cancelled=stop.is_set, on_token=on_token)+ say("stage", "continuing")+ semantic = yue2_tokenizer.continue_from_codes(+ pipe, plan, audio_prompt_codes, sampling=semantic_sampling,+ cancelled=stop.is_set, on_token=on_token)+ noise = initial_noise(len(semantic.tokens), request.seed)+ nar_started = time.perf_counter()+ latents = pipe.synthesize(semantic, noise=noise, cancelled=stop.is_set)+ nar_seconds = time.perf_counter() - nar_started+ vae_started = time.perf_counter()+ audio = pipe.decode(latents, cancelled=stop.is_set)+ timing = {"abc": plan.timing, "semantic": semantic.timing,+ "nar_seconds": nar_seconds,+ "vae_seconds": time.perf_counter() - vae_started,+ "load": dict(pipe.load_timing),+ "e2e_seconds": time.perf_counter() - started}+ result = SongResult(audio, 48000, semantic, latents, cfg, pipe.weights,+ timing, stamp, noise)+ audio_prompt_info["generated_frames"] = (+ len(semantic.tokens) - len(audio_prompt_codes))+ else:+ say("stage", "planning" if args.mode != "off" and abc is None else "writing")+ kw = dict(style=style, lyrics=lyrics, cot=args.mode, seed=seed,+ semantic_sampling=semantic_sampling, cancelled=stop.is_set,+ on_token=on_token)+ if abc is not None:+ kw["abc"] = abc+ if args.cfg_scale is not None:+ kw["cfg_scale"] = float(args.cfg_scale)+ result = pipe(**kw)# The port checks cancellation before each decode tile, not after# the last one: a Stop that lands there must not publish a song.if stop.is_set():@@ -270,7 +641,14 @@ def main(argv=None):"lyrics": lyrics,"mode": args.mode,"instrumental": bool(args.instrumental),+ "instrumental_recipe": instrumental_info,+ "lora": yue2_lora.describe_stack(adapters, instrumental=instrumental_info)+ if adapters else None,"abc_supplied": abc is not None,+ "cover": cover_info,+ "audio_prompt": audio_prompt_info,+ "variation": variation_info,+ "title": args.title,"score_abc": result.abc,"seed": seed,"steps": int(args.steps),diff --git a/scripts/music/yue2_tokenizer.py b/scripts/music/yue2_tokenizer.pynew file mode 100644index 0000000..97dd741--- /dev/null+++ b/scripts/music/yue2_tokenizer.py@@ -0,0 +1,917 @@+#!/usr/bin/env python3+"""The real-audio tokenizer head for the YuE2 MLX engine — a recording in, YuE2+semantic codes out.++YuE2 writes songs from words. It has never been able to *listen*: there was no+way to put a real recording in front of it. Mothersuperior trained the missing+piece — `tokenizer_head_joint_v9`, an 8-layer transformer that reads MERT-v2-+FullSong features and predicts YuE2's own 32768-way semantic codes — and shipped+it beside the acoustic adapter it was trained with (`nar_lora_joint_v9`, already+in Phosphene's pack). This module is that head in MLX. With it a recording can+be re-synthesised through YuE2's decoder, and — the part that matters — used as+the semantic PREFIX a new song continues from.++WHERE THE PREPROCESSING COMES FROM+----------------------------------+Not guessed. Every number below is read out of Mothersuperior's own scripts in+the release repo (`scripts/prep_real.py` for the features, `scripts/joint_v6.py`+for the normalisation, the window and the inference-time tiling):++ audio ffmpeg/soundfile → mono, 24 kHz, float32+ chunking 30 s chunks (720 000 samples); a chunk shorter than 1 s is dropped;+ each chunk is encoded on its own, so MERT attention never crosses a+ chunk boundary (`prep_real.mert_l20`)+ features MERT-v2-FullSong `hidden_states[20]`, concatenated in time order,+ then linearly resampled to `round(seconds * 25)` frames and STORED+ AS FLOAT16 — the head was trained on fp16-rounded features, so the+ rounding is kept rather than skipped+ norm per-TRACK, per-channel instance norm `(x - mean) / (std + 1e-5)`,+ over the whole recording, before any windowing+ (`joint_v6.instnorm`; numpy std, population, not Bessel-corrected)+ window 512 frames with the learned `pos` embedding added+ tiling hop 256; a final window is pulled back to end-of-track; each+ window contributes its centre, trimming 128 frames off every+ interior edge (`joint_v6.predict`)+ decode plain argmax over 32768 logits — no neighbour smoothing, even+ though the repo ships the neighbour tables (they are a TRAINING+ loss, `soft_ce`)++WHICH MERT LAYER, EXACTLY+-------------------------+The head's metadata says "layer 20". In transformers, `output_hidden_states`+for MERT2 collects ONLY the conformer block outputs — `_encode()` appends after+each `layer`, and never appends the pre-layer subsampled embedding. So+`hidden_states[20]` is the output of `layers[20]`, the 21st block. `lyra.mert`'s+`layer_weights` vector is one entry LONGER (25 for 24 blocks) because index 0 is+that pre-layer embedding. The one-hot therefore goes at index **21**, not 20.+`MERT_LAYER` below is the transformers index; `_mixer_weights()` does the +1,+and `--mert-layer` moves it for anyone who wants to re-check.++PRECISION+---------+The checkpoint is BF16. Mothersuperior runs the head under `torch.autocast`+bfloat16 and takes `.float().argmax(-1)`. This port promotes the weights to+FP32 and runs the encoder in FP32: the same opmath policy `lyra` uses for the+AR attention (`_source_sdpa`), more accurate than the training-time path, and+reproducible across machines. `--dtype bfloat16` runs the narrow path for+comparison.++WHAT IS OURS AND WHAT IS THE ENGINE'S+-------------------------------------+`lyra` is installed from a pinned SHA by `scripts/pinokio/music_sync.sh`, so+nothing may be written inside `yue2-mlx/`. This module lives in Phosphene's repo+and only *uses* the engine: `lyra.mert.MERT2` for the frontend, `lyra.ar.+_source_sdpa` for attention opmath, `lyra.pipeline.YuE2Pipeline` for synthesis,+and `yue2_lora.py` (ours) to attach `nar_lora_joint_v9`.+"""+from __future__ import annotations++import argparse+from dataclasses import dataclass+import json+import math+import os+from pathlib import Path+import shutil+import subprocess+import sys+import time++import mlx.core as mx+import mlx.nn as nn+import numpy as np++sys.path.insert(0, str(Path(__file__).resolve().parents[2]))+from scripts.pinokio.music_lora_fetch import ( # noqa: E402+ HEAD_SUBDIR, TOKENIZER_HEAD, head_path, sha256_of,+)++__all__ = [+ "HEAD_VERSION", "WINDOW", "HOP", "FRAME_RATE", "VOCAB", "MERT_LAYER",+ "TokenizerHead", "Features", "convert_head_weights", "encode_codes",+ "instance_norm", "load_head", "mert_features", "predict_codes",+ "resample_time", "tile_starts", "code_statistics", "continue_from_codes",+ "log_mel", "spectral_distance", "chroma_correlation", "reference_mono_48k",+]++#: The pinned head this port was written and verified against.+HEAD_VERSION = "tokenizer_head_joint_v9"+HEAD_SHA256 = "cffb673cd663517c8978ba73d186a87517958025f7e409371ea56df3bb364db2"++#: Architecture, from the safetensors header (103 tensors, all BF16).+WINDOW = 512+HOP = WINDOW // 2+TRIM = WINDOW // 4+FEATURE_DIM = 1024+MODEL_DIM = 512+FFN_DIM = 2048+NUM_LAYERS = 8+NUM_HEADS = 8+VOCAB = 32768+LAYER_NORM_EPS = 1e-5++#: Feature extraction, from `prep_real.py`.+MERT_RATE = 24000+MERT_CHUNK = MERT_RATE * 30+MERT_MIN_CHUNK = MERT_RATE+MERT_LAYER = 20 #: the transformers `hidden_states` index+FRAME_RATE = 25 #: MERT-v2-FullSong's native frame rate+INSTNORM_EPS = 1e-5+#: The head was trained on features stored as float16; keep the rounding.+FEATURE_STORAGE_DTYPE = np.float16+++# --------------------------------------------------------------- the encoder++def _sdpa(query, key, value, *, scale):+ """The engine's own attention opmath where it is importable, MLX's otherwise.++ `lyra.ar._source_sdpa` promotes BF16 operands to FP32 under Lyra's verified+ process policy. In FP32 the promotion is a no-op, so the fallback used by+ the repo-root test suite (which has MLX but not the music engine) computes+ the same values.+ """+ try:+ from lyra.ar import _source_sdpa+ except Exception: # noqa: BLE001+ return mx.fast.scaled_dot_product_attention(query, key, value, scale=scale)+ return _source_sdpa(query, key, value, scale=scale)+++class SelfAttention(nn.Module):+ """`torch.nn.MultiheadAttention` with the fused q,k,v projection kept fused.++ PyTorch stores one `in_proj_weight` of `[3*d, d]` whose row blocks are q,+ then k, then v. That order is the thing a port gets silently wrong — the+ shapes are identical under any permutation — so `test_yue2_tokenizer.py`+ pins it against a written-out reference and the release proof reports the+ max-abs-diff against a torch `TransformerEncoderLayer` built from these+ exact tensors.+ """++ def __init__(self, dim=MODEL_DIM, heads=NUM_HEADS):+ super().__init__()+ self.heads = heads+ self.in_proj_weight = mx.zeros((3 * dim, dim))+ self.in_proj_bias = mx.zeros((3 * dim,))+ self.out_proj = nn.Linear(dim, dim)++ def __call__(self, x):+ batch, length, dim = x.shape+ head_dim = dim // self.heads+ fused = x @ self.in_proj_weight.T + self.in_proj_bias+ query, key, value = mx.split(fused, 3, axis=-1)+ shape = (batch, length, self.heads, head_dim)+ query, key, value = (part.reshape(shape).transpose(0, 2, 1, 3)+ for part in (query, key, value))+ out = _sdpa(query, key, value, scale=head_dim ** -0.5)+ return self.out_proj(out.transpose(0, 2, 1, 3).reshape(batch, length, dim))+++class EncoderLayer(nn.Module):+ """`TransformerEncoderLayer(512, 8, 2048, norm_first=True, activation='gelu')`.++ Pre-norm: the residual carries the unnormalised stream, each block reads a+ normalised copy. Dropout was 0.1 in training and is absent at inference.+ """++ def __init__(self):+ super().__init__()+ self.self_attn = SelfAttention()+ self.linear1 = nn.Linear(MODEL_DIM, FFN_DIM)+ self.linear2 = nn.Linear(FFN_DIM, MODEL_DIM)+ self.norm1 = nn.LayerNorm(MODEL_DIM, eps=LAYER_NORM_EPS)+ self.norm2 = nn.LayerNorm(MODEL_DIM, eps=LAYER_NORM_EPS)++ def __call__(self, x):+ x = x + self.self_attn(self.norm1(x))+ return x + self.linear2(nn.gelu(self.linear1(self.norm2(x))))+++class Encoder(nn.Module):+ """`nn.TransformerEncoder(layer, 8)` — no final norm of its own."""++ def __init__(self, layers=NUM_LAYERS):+ super().__init__()+ self.layers = [EncoderLayer() for _ in range(layers)]++ def __call__(self, x):+ for layer in self.layers:+ x = layer(x)+ return x+++class TokenizerHead(nn.Module):+ """`Tok` from `joint_v6.py`, parameter for parameter.++ `head(norm(enc(inp(x) + pos[:, :T])))`. The learned `pos` is `[1, 512, 512]`+ and is sliced, never interpolated, so a short tail window sees exactly the+ positions it saw in training.+ """++ def __init__(self):+ super().__init__()+ self.inp = nn.Linear(FEATURE_DIM, MODEL_DIM)+ self.pos = mx.zeros((1, WINDOW, MODEL_DIM))+ self.enc = Encoder()+ self.norm = nn.LayerNorm(MODEL_DIM, eps=LAYER_NORM_EPS)+ self.head = nn.Linear(MODEL_DIM, VOCAB)++ def __call__(self, features):+ if features.ndim != 3 or features.shape[-1] != FEATURE_DIM:+ raise ValueError(f"Expected [batch, frames, {FEATURE_DIM}] MERT features")+ if features.shape[1] > WINDOW:+ raise ValueError(f"A window is at most {WINDOW} frames; tile longer inputs")+ x = self.inp(features) + self.pos[:, :features.shape[1]]+ return self.head(self.norm(self.enc(x)))+++#: Every tensor the checkpoint carries, mapped to this module's parameter tree.+#: The names already line up (they are PyTorch's), so the map is the identity —+#: which is the point of naming the modules after theirs. Kept explicit so a+#: renamed or reordered release fails loudly instead of loading half a head.+EXPECTED_KEYS = tuple(sorted(+ ["inp.weight", "inp.bias", "pos", "norm.weight", "norm.bias",+ "head.weight", "head.bias"]+ + [f"enc.layers.{i}.{name}"+ for i in range(NUM_LAYERS)+ for name in ("self_attn.in_proj_weight", "self_attn.in_proj_bias",+ "self_attn.out_proj.weight", "self_attn.out_proj.bias",+ "linear1.weight", "linear1.bias", "linear2.weight", "linear2.bias",+ "norm1.weight", "norm1.bias", "norm2.weight", "norm2.bias")]))+++def convert_head_weights(weights, dtype=mx.float32):+ """Checkpoint tensors → `(name, array)` pairs, refusing an unexpected tree."""+ names = set(weights)+ missing = sorted(set(EXPECTED_KEYS) - names)+ extra = sorted(names - set(EXPECTED_KEYS))+ if missing or extra:+ raise ValueError(+ f"This is not {HEAD_VERSION}: "+ + (f"missing {len(missing)} tensors ({missing[:3]}…) " if missing else "")+ + (f"unexpected {len(extra)} tensors ({extra[:3]}…)" if extra else ""))+ return [(name, mx.array(weights[name]).astype(dtype)) for name in EXPECTED_KEYS]+++def load_head(path, *, dtype=mx.float32, verify_sha=False):+ """Build the MLX head from a safetensors file and evaluate its parameters."""+ path = Path(path).expanduser()+ if not path.is_file():+ raise FileNotFoundError(+ f"No tokenizer head at {path}. Fetch it with "+ f"`python scripts/pinokio/music_lora_fetch.py --root <lora dir>`.")+ digest = sha256_of(path) if verify_sha else None+ if verify_sha and digest != HEAD_SHA256:+ raise ValueError(f"{path.name} is not the pinned {HEAD_VERSION} "+ f"({digest} != {HEAD_SHA256})")+ # `mx.load` reads BF16 natively; numpy-framework safetensors cannot.+ weights, metadata = mx.load(str(path), return_metadata=True)+ if not isinstance(weights, dict) or not weights:+ raise ValueError(f"{path.name}: no named tensors")+ model = TokenizerHead()+ model.load_weights(convert_head_weights(weights, dtype), strict=True)+ mx.eval(model.parameters())+ object.__setattr__(model, "identity", {+ "head": path.name, "version": HEAD_VERSION, "path": str(path),+ "sha256": digest, "dtype": str(dtype).rsplit(".", 1)[-1],+ "metadata": metadata,+ })+ return model+++# ------------------------------------------------------------------- features++@dataclass+class Features:+ """One recording's MERT features, already instance-normalised."""++ values: np.ndarray #: [frames, 1024] float32, instance-normed+ seconds: float+ source: str+ mert_layer: int+ resampler: str+ chunks: int++ def summary(self) -> dict:+ return {"frames": int(len(self.values)), "seconds": round(self.seconds, 3),+ "mert_layer": self.mert_layer, "frame_rate": FRAME_RATE,+ "resampler": self.resampler, "chunks": self.chunks}+++def resample_time(values: np.ndarray, frames: int) -> np.ndarray:+ """`F.interpolate(mode='linear', align_corners=False)` over the time axis.++ Written out because the whole feature pipeline hangs off it: MERT's native+ rate is already 25 Hz, so this is the identity for any recording whose+ length is a whole number of 960-sample frames, and a one-frame stretch+ otherwise. Getting the half-pixel convention wrong would shift every code.+ """+ source = int(values.shape[0])+ if frames < 1:+ raise ValueError("Need at least one output frame")+ if source == frames:+ return values+ scale = source / frames+ position = np.clip((np.arange(frames, dtype=np.float64) + 0.5) * scale - 0.5, 0.0, None)+ low = np.floor(position).astype(np.int64)+ high = np.minimum(low + 1, source - 1)+ weight = (position - low)[:, None]+ return (values[low] * (1.0 - weight) + values[high] * weight).astype(values.dtype)+++def instance_norm(values: np.ndarray) -> np.ndarray:+ """`joint_v6.instnorm`: per-track, per-channel, population standard deviation.++ Per TRACK, not per window — the statistics are taken over the whole+ recording once, before it is cut up. numpy's `std` is ddof=0; torch's+ default is ddof=1, and the original reads the array as numpy.+ """+ values = np.asarray(values, dtype=np.float32)+ if values.ndim != 2:+ raise ValueError("Instance norm expects [frames, channels]")+ return (values - values.mean(0)) / (values.std(0) + INSTNORM_EPS)+++def _ffmpeg() -> str:+ for name in ("ffmpeg",):+ found = shutil.which(name)+ if found:+ return found+ raise FileNotFoundError("ffmpeg is not on PATH; it decodes the recording")+++def _run_ffmpeg(command, timeout=900) -> bytes:+ done = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,+ timeout=timeout)+ if done.returncode:+ message = done.stderr.decode("utf-8", "replace").strip().splitlines()+ raise RuntimeError(f"ffmpeg failed: {message[-1] if message else done.returncode}")+ return done.stdout+++def _probe_rate(path: Path):+ probe = shutil.which("ffprobe")+ if not probe:+ return None+ try:+ done = subprocess.run(+ [probe, "-v", "error", "-select_streams", "a:0", "-show_entries",+ "stream=sample_rate", "-of", "csv=p=0", str(path)],+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=60)+ return int(done.stdout.decode().strip()) if not done.returncode else None+ except (ValueError, OSError, subprocess.SubprocessError):+ return None+++def load_mono_24k(path, *, start=0.0, seconds=None, resampler="polyphase"):+ """The recording as mono float32 at 24 kHz, plus the resampler actually used.++ `prep_real.py` resampled with `scipy.signal.resample_poly`. That is the+ default here when scipy is importable (it always is in the music engine's+ venv); `ffmpeg` is the fallback and the explicit alternative, and which one+ ran is recorded in the metadata rather than assumed.+ """+ if resampler not in {"polyphase", "ffmpeg"}:+ raise ValueError("resampler must be 'polyphase' or 'ffmpeg'")+ path = Path(path).expanduser()+ if not path.is_file():+ raise FileNotFoundError(path)+ trim = ["-ss", f"{float(start):.6f}"] if start else []+ if seconds is not None:+ trim += ["-t", f"{float(seconds):.6f}"]+ native = _probe_rate(path) if resampler == "polyphase" else None+ if resampler == "polyphase" and native:+ try:+ from scipy.signal import resample_poly+ except ImportError:+ native = None+ if resampler == "polyphase" and native:+ raw = _run_ffmpeg([_ffmpeg(), "-v", "error", "-nostdin", *trim, "-i", str(path),+ "-vn", "-ac", "1", "-ar", str(native), "-f", "f32le", "pipe:1"])+ audio = np.frombuffer(raw, dtype="<f4").astype(np.float32)+ if native != MERT_RATE:+ divisor = math.gcd(native, MERT_RATE)+ audio = resample_poly(audio, MERT_RATE // divisor, native // divisor).astype(np.float32)+ used = f"scipy.resample_poly({native}->{MERT_RATE})"+ else:+ raw = _run_ffmpeg([_ffmpeg(), "-v", "error", "-nostdin", *trim, "-i", str(path),+ "-vn", "-ac", "1", "-ar", str(MERT_RATE), "-f", "f32le", "pipe:1"])+ audio = np.frombuffer(raw, dtype="<f4").astype(np.float32)+ used = f"ffmpeg(->{MERT_RATE})"+ if len(audio) < MERT_MIN_CHUNK:+ raise ValueError(f"Need at least one second of audio at {MERT_RATE} Hz, "+ f"got {len(audio) / MERT_RATE:.2f} s")+ if not np.isfinite(audio).all():+ raise ValueError("The decoded recording is not finite")+ return audio, used+++def resolve_mert(directory=None, *, offline=False, cache_dir=None) -> Path:+ """The plain MERT-v2-FullSong checkpoint — not SheetSage2's merged copy.++ Phosphene's cover pack already puts the parent on disk at+ `mlx_models/yue2-cover/mert2/`; that is the default. A directory is taken as+ given, the pinned repo is downloaded when nothing is there.+ """+ from lyra.transcription.model import MERT_REPO, MERT_REVISION++ if directory is not None:+ directory = Path(directory).expanduser()+ if not directory.is_dir():+ raise FileNotFoundError(f"No MERT-v2-FullSong checkpoint at {directory}")+ return directory+ root = os.environ.get("LTX_MUSIC_MODELS") or (Path(__file__).resolve().parents[2] / "mlx_models")+ candidate = Path(root).expanduser() / "yue2-cover" / "mert2"+ if (candidate / "model.safetensors").is_file():+ return candidate+ from huggingface_hub import snapshot_download+ return Path(snapshot_download(MERT_REPO, revision=MERT_REVISION, local_files_only=offline,+ cache_dir=cache_dir,+ allow_patterns=["config.json", "model.safetensors"]))+++def load_mert(directory=None, **kwargs):+ """`lyra.mert.MERT2` with the official parent weights, in FP32."""+ from safetensors.numpy import load_file++ from lyra.mert import MERT2, convert_mert_weights++ directory = resolve_mert(directory, **kwargs)+ config = json.loads((directory / "config.json").read_text())+ model = MERT2(config)+ model.load_weights(convert_mert_weights(load_file(directory / "model.safetensors")), strict=True)+ mx.eval(model.parameters())+ object.__setattr__(model, "mert_config", config)+ object.__setattr__(model, "mert_dir", str(directory))+ return model+++def _mixer_weights(layers: int, layer: int) -> mx.array:+ """One-hot for `lyra.mert`'s weighted mixer.++ Index 0 of that vector is the pre-layer subsampled embedding; transformers'+ `hidden_states[k]` is the output of block `k`. Hence the +1.+ """+ if not 0 <= layer < layers:+ raise ValueError(f"MERT layer must be in [0, {layers})")+ weights = np.zeros((layers + 1,), dtype=np.float32)+ weights[layer + 1] = 1.0+ return mx.array(weights)+++def mert_features(audio, model, *, layer=MERT_LAYER, cancelled=None,+ progress=None) -> np.ndarray:+ """`prep_real.mert_l20`: 30-second chunks, layer 20, resampled to 25 Hz.++ The chunks are encoded one at a time rather than as one padded batch. Every+ operation in MERT2 is per-sample (global response norm reduces over time+ within a sample, attention never crosses the batch), so this is the same+ arithmetic with bounded memory.+ """+ audio = np.asarray(audio, dtype=np.float32)+ layers = model.mert_config["num_hidden_layers"] if hasattr(model, "mert_config") else len(model.layers)+ mixer = _mixer_weights(layers, layer)+ chunks = [audio[start:start + MERT_CHUNK] for start in range(0, len(audio), MERT_CHUNK)]+ chunks = [chunk for chunk in chunks if len(chunk) >= MERT_MIN_CHUNK]+ if not chunks:+ raise ValueError("Nothing to encode: the recording is shorter than one second")+ parts = []+ for index, chunk in enumerate(chunks):+ if cancelled is not None and cancelled():+ raise InterruptedError("Cancelled during MERT encoding")+ hidden = model(mx.array(chunk[None]), mixer, cancelled)+ mx.eval(hidden)+ parts.append(np.asarray(hidden, dtype=np.float32).reshape(-1, FEATURE_DIM))+ del hidden+ mx.clear_cache()+ if progress is not None:+ progress(index + 1, len(chunks))+ stacked = np.concatenate(parts, axis=0)+ frames = int(round(len(audio) / MERT_RATE * FRAME_RATE))+ return resample_time(stacked, frames).astype(FEATURE_STORAGE_DTYPE), len(chunks)+++def extract(path, *, mert=None, mert_dir=None, layer=MERT_LAYER, start=0.0,+ seconds=None, resampler="polyphase", cancelled=None, progress=None) -> Features:+ """A path on disk → instance-normalised features ready for the head."""+ audio, used = load_mono_24k(path, start=start, seconds=seconds, resampler=resampler)+ model = mert if mert is not None else load_mert(mert_dir)+ raw, chunks = mert_features(audio, model, layer=layer, cancelled=cancelled, progress=progress)+ return Features(instance_norm(raw), len(audio) / MERT_RATE, str(Path(path).expanduser()),+ layer, used, chunks)+++# --------------------------------------------------------------- the decoding++def tile_starts(frames: int, window: int = WINDOW, hop: int = HOP) -> list[int]:+ """`joint_v6.predict`'s window starts, including its pull-back final window."""+ if frames < 1:+ raise ValueError("Need at least one frame")+ starts = list(range(0, max(1, frames - window + 1), hop))+ if starts[-1] + window < frames:+ starts.append(max(0, frames - window))+ return starts+++def predict_codes(head, features: np.ndarray, *, batch_dtype=mx.float32,+ cancelled=None, progress=None) -> np.ndarray:+ """Tile, run the head, keep each window's centre — `joint_v6.predict`.++ Interior windows contribute frames `[start+128, start+384)`; the first+ window keeps its head and the last keeps its tail, so every frame is+ written exactly once and no frame is decided by a window edge.+ """+ features = np.asarray(features, dtype=np.float32)+ if features.ndim != 2 or features.shape[1] != FEATURE_DIM:+ raise ValueError(f"Expected [frames, {FEATURE_DIM}] features")+ frames = len(features)+ out = np.zeros(frames, dtype=np.int64)+ starts = tile_starts(frames)+ for index, start in enumerate(starts):+ if cancelled is not None and cancelled():+ raise InterruptedError("Cancelled during tokenisation")+ window = features[start:start + WINDOW]+ length = len(window)+ if length < WINDOW:+ window = np.pad(window, ((0, WINDOW - length), (0, 0)))+ logits = head(mx.array(window[None]).astype(batch_dtype))+ codes = np.asarray(mx.argmax(logits.astype(mx.float32), axis=-1)[0, :length])+ low = start + (0 if start == 0 else TRIM)+ high = start + length - (0 if start + length >= frames else TRIM)+ out[low:high] = codes[low - start:high - start]+ mx.clear_cache()+ if progress is not None:+ progress(index + 1, len(starts))+ if out.min() < 0 or out.max() >= VOCAB:+ raise ValueError("The head produced a code outside YuE2's semantic vocabulary")+ return out+++def code_statistics(codes) -> dict:+ """What a token stream looks like, in the numbers `joint_v6` reports itself.++ `repeat` is the share of frames equal to their predecessor and `run_mean`+ the average run length: a head that has collapsed prints repeat near 1.+ """+ codes = np.asarray(codes).astype(np.int64).reshape(-1)+ if not len(codes):+ raise ValueError("No codes")+ values, counts = np.unique(codes, return_counts=True)+ runs = 1 + int((codes[1:] != codes[:-1]).sum()) if len(codes) > 1 else 1+ return {+ "frames": int(len(codes)),+ "seconds": round(len(codes) / FRAME_RATE, 3),+ "unique": int(len(values)),+ "unique_share": round(float(len(values)) / len(codes), 4),+ "top_code": int(values[int(np.argmax(counts))]),+ "top_share": round(float(counts.max()) / len(codes), 4),+ "repeat": round(float((codes[1:] == codes[:-1]).mean()), 4) if len(codes) > 1 else 0.0,+ "runs": runs,+ "run_mean": round(float(len(codes)) / runs, 3),+ "run_max": int(max((len(list(group)) for group in _runs(codes)), default=1)),+ }+++def _runs(codes):+ start = 0+ for index in range(1, len(codes) + 1):+ if index == len(codes) or codes[index] != codes[start]:+ yield codes[start:index]+ start = index+++def encode_codes(path, *, head=None, head_file=None, mert=None, mert_dir=None,+ layer=MERT_LAYER, start=0.0, seconds=None, resampler="polyphase",+ dtype=mx.float32, cancelled=None, on_stage=None):+ """A recording → `(codes, metadata)`. The one call everything else goes through."""+ if on_stage:+ on_stage("features")+ features = extract(path, mert=mert, mert_dir=mert_dir, layer=layer, start=start,+ seconds=seconds, resampler=resampler, cancelled=cancelled,+ progress=(lambda k, n: on_stage(f"mert {k}/{n}")) if on_stage else None)+ if mert is None:+ mx.clear_cache()+ if on_stage:+ on_stage("tokenising")+ model = head if head is not None else load_head(head_file, dtype=dtype)+ codes = predict_codes(model, features.values, batch_dtype=dtype, cancelled=cancelled,+ progress=(lambda k, n: on_stage(f"codes {k}/{n}")) if on_stage else None)+ metadata = {+ "head": getattr(model, "identity", {"version": HEAD_VERSION}),+ "features": features.summary(),+ "source": features.source,+ "start_seconds": float(start),+ "requested_seconds": None if seconds is None else float(seconds),+ "window": WINDOW, "hop": HOP, "trim": TRIM,+ "statistics": code_statistics(codes),+ }+ return codes, metadata+++# ------------------------------------------------ synthesis and continuation++def semantic_result(pipe, codes, *, style="", lyrics="", seed=0, cot="off"):+ """Wrap codes as something `pipe.synthesize()` will accept.++ The acoustic stage is conditioned on the request prefix, so a round trip+ still needs one. `cot="off"` is what `prep_real.py` used when it prepared+ real recordings for training, and it is the only mode whose prefix is+ independent of a score: `[EOD] + text + [ABC_START, ABC_END, MUSIC_START]`.+ """+ from yue2.pipeline import SemanticResult, SymbolicPlan+ from yue2.protocol import SongRequest, token_prefixes++ request = SongRequest(style=style, lyrics=lyrics, cot=cot, seed=int(seed), id="realaudio")+ plan = SymbolicPlan(request, None, [], token_prefixes(request, pipe.tokenizer), {}, False)+ return SemanticResult(plan, [int(code) for code in codes], {}, False)+++def continue_from_codes(pipe, plan, codes, *, sampling=None, cancelled=None, on_token=None):+ """Generate a song that CONTINUES a real recording.++ The prompt's codes are appended to the request prefix as ordinary codec+ tokens, so the AR model prefills on them exactly as it would on its own+ output, and generation carries on from there. The returned tokens are the+ prompt followed by what the model wrote; the plan keeps its canonical+ prefix, which is what `synthesize()` validates against the request.++ Two honest edges: the repetition-penalty window and the minimum-length+ counter both start empty at the boundary, because `generate_tokens()` takes+ no prior history — the model sees the prompt, the sampler does not.+ """+ from yue2.pipeline import SemanticResult+ from yue2.protocol import CODEC_OFFSET, negative_prefix, resolve_sampling++ codes = [int(code) for code in codes]+ if not codes:+ raise ValueError("An audio prompt needs at least one code")+ if min(codes) < 0 or max(codes) >= VOCAB:+ raise ValueError("Audio-prompt codes are outside YuE2's semantic vocabulary")+ request = plan.request+ sampling = resolve_sampling(sampling, pipe.generation_config.semantic)+ codec = [CODEC_OFFSET + code for code in codes]+ negative = None+ if request.guidance != 1:+ negative = negative_prefix(request, pipe.tokenizer, plan.abc_ids) + codec+ ids, timing, truncated = pipe._generate(+ list(plan.prefix) + codec, sampling, request.seed, "semantic",+ negative=negative, cfg_scale=request.guidance, legacy_off=request.cot == "off",+ cancelled=cancelled, on_token=on_token)+ tokens = codes + [int(token) - CODEC_OFFSET for token in ids]+ return SemanticResult(plan, tokens, {**timing, "audio_prompt_frames": len(codes)}, truncated)+++def build_pipeline(model_dir, vae_dir, *, precision="bf16", steps=32,+ memory_budget_gib=None, lora=(), lora_mode="joint"):+ """The engine pipeline plus any adapters, ready for `synthesize`/`decode`."""+ from yue2.protocol import GenerationConfig++ from lyra.pipeline import YuE2Pipeline++ sys.path.insert(0, str(Path(__file__).resolve().parent))+ import yue2_lora++ adapters = yue2_lora.load_stack([(Path(path), 1.0) for path in lora], mode=lora_mode) if lora else []+ config = GenerationConfig(ode_steps=int(steps))+ kwargs = {} if memory_budget_gib is None else {"memory_budget_gib": float(memory_budget_gib)}+ pipe = YuE2Pipeline(Path(model_dir), Path(vae_dir), precision=precision,+ generation_config=config, progress=False, **kwargs)+ runtime = yue2_lora.LoRARuntime(adapters)+ runtime.attach(pipe)+ return pipe, runtime, adapters+++def synthesize_codes(pipe, codes, *, style="", lyrics="", seed=0, cancelled=None):+ """Codes → 48 kHz stereo float32, through the NAR and the VAE decoder."""+ from lyra.pipeline import initial_noise++ semantic = semantic_result(pipe, codes, style=style, lyrics=lyrics, seed=seed)+ noise = initial_noise(len(semantic.tokens), int(seed))+ latents = pipe.synthesize(semantic, noise=noise, cancelled=cancelled)+ return pipe.decode(latents, cancelled=cancelled), semantic+++# -------------------------------------------------------------- measurements++def log_mel(audio, rate=48000, n_fft=2048, hop=480, mels=128):+ """A small log-mel magnitude spectrogram — numpy only, no torchaudio.++ Slaney-style mel scale on a Hann-windowed magnitude STFT, the shape+ `joint_v6.spec_loss` measures with. It exists so the round-trip proof can+ be reported in numbers rather than adjectives.+ """+ audio = np.ascontiguousarray(np.asarray(audio, dtype=np.float64).reshape(-1))+ if not np.isfinite(audio).all():+ raise ValueError("Cannot measure a recording that is not finite")+ window = np.hanning(n_fft + 1)[:-1]+ frames = 1 + max(0, (len(audio) - n_fft) // hop)+ if frames < 1:+ raise ValueError("Recording is shorter than one STFT frame")+ strided = np.lib.stride_tricks.as_strided(+ audio, (frames, n_fft), (audio.strides[0] * hop, audio.strides[0]))+ spectrum = np.abs(np.fft.rfft(strided * window, axis=-1))+ hz = np.fft.rfftfreq(n_fft, 1.0 / rate)+ mel = lambda f: 2595.0 * np.log10(1.0 + f / 700.0) # noqa: E731+ edges = np.linspace(mel(0.0), mel(rate / 2), mels + 2)+ centres = 700.0 * (10.0 ** (edges / 2595.0) - 1.0)+ bank = np.zeros((len(hz), mels))+ for index in range(mels):+ left, centre, right = centres[index:index + 3]+ rising = (hz - left) / max(centre - left, 1e-9)+ falling = (right - hz) / max(right - centre, 1e-9)+ bank[:, index] = np.clip(np.minimum(rising, falling), 0.0, None)+ # Accelerate leaves FP status flags set after a large GEMM, so numpy raises+ # divide/overflow/invalid warnings for a product that is finite and correct+ # (the reference measured against itself returns exactly 0.0 dB).+ with np.errstate(divide="ignore", over="ignore", invalid="ignore"):+ energy = spectrum @ bank+ return np.log(energy + 1e-5)+++def spectral_distance(reference, estimate, rate=48000) -> float:+ """Mean |Δ log-mel| in dB between two recordings, on their common length."""+ length = min(len(reference), len(estimate))+ a, b = log_mel(reference[:length], rate), log_mel(estimate[:length], rate)+ frames = min(len(a), len(b))+ return float((20.0 / math.log(10)) * np.abs(a[:frames] - b[:frames]).mean())+++def chroma(audio, rate=48000, n_fft=4096, hop=2048) -> np.ndarray:+ """A 12-bin chroma sequence: which pitch classes are sounding, over time."""+ audio = np.ascontiguousarray(np.asarray(audio, dtype=np.float64).reshape(-1))+ window = np.hanning(n_fft + 1)[:-1]+ frames = 1 + max(0, (len(audio) - n_fft) // hop)+ strided = np.lib.stride_tricks.as_strided(+ audio, (frames, n_fft), (audio.strides[0] * hop, audio.strides[0]))+ spectrum = np.abs(np.fft.rfft(strided * window, axis=-1))+ hz = np.fft.rfftfreq(n_fft, 1.0 / rate)+ usable = (hz >= 55.0) & (hz <= 4186.0)+ pitch = np.zeros(len(hz), dtype=np.int64)+ pitch[usable] = np.round(12 * np.log2(hz[usable] / 440.0) + 69).astype(np.int64) % 12+ bins = np.zeros((frames, 12))+ with np.errstate(divide="ignore", over="ignore", invalid="ignore"):+ for index in range(12):+ mask = usable & (pitch == index)+ if mask.any():+ bins[:, index] = spectrum[:, mask].sum(axis=1)+ return bins / (bins.sum(axis=1, keepdims=True) + 1e-9)+++def chroma_correlation(reference, estimate, rate=48000) -> float:+ """Pearson correlation of the two mean chroma profiles: same notes or not."""+ a, b = chroma(reference, rate).mean(0), chroma(estimate, rate).mean(0)+ a, b = a - a.mean(), b - b.mean()+ return float((a @ b) / (np.linalg.norm(a) * np.linalg.norm(b) + 1e-12))+++# ---------------------------------------------------------------------- CLI++def say(*parts):+ print("[tokenizer]", *parts, flush=True)+++def _default_head() -> Path:+ root = os.environ.get("LTX_MUSIC_LORAS")+ if not root:+ root = Path(__file__).resolve().parents[2] / "mlx_models" / "yue2-loras"+ return head_path(root)+++def reference_mono_48k(path, *, start=0.0, seconds=None) -> np.ndarray:+ """The measured excerpt of the ORIGINAL recording, mono, 48 kHz.++ It must be the same excerpt the codes came from: measuring a round trip of+ seconds 60–90 against the record from its first second is the kind of+ mistake that reads as a quiet, plausible number instead of an error.+ """+ trim = ["-ss", f"{float(start):.6f}"] if start else []+ if seconds is not None:+ trim += ["-t", f"{float(seconds):.6f}"]+ raw = _run_ffmpeg([_ffmpeg(), "-v", "error", "-nostdin", *trim, "-i", str(Path(path).expanduser()),+ "-vn", "-ac", "1", "-ar", "48000", "-f", "f32le", "pipe:1"])+ return np.frombuffer(raw, dtype="<f4").astype(np.float32)+++def main(argv=None) -> int:+ parser = argparse.ArgumentParser(+ description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ sub = parser.add_subparsers(dest="command", required=True)++ encode = sub.add_parser("encode", help="a recording → YuE2 semantic codes")+ encode.add_argument("audio", type=Path)+ encode.add_argument("--out", type=Path, required=True, help="codes .npy (int32)")+ encode.add_argument("--head", type=Path, default=None,+ help=f"default: <lora pack>/{HEAD_SUBDIR}/{TOKENIZER_HEAD}")+ encode.add_argument("--mert-dir", type=Path, default=None,+ help="MERT-v2-FullSong checkpoint (default: the cover pack's)")+ encode.add_argument("--mert-layer", type=int, default=MERT_LAYER,+ help="transformers hidden_states index (default 20)")+ encode.add_argument("--start", type=float, default=0.0)+ encode.add_argument("--seconds", type=float, default=None)+ encode.add_argument("--resampler", choices=("polyphase", "ffmpeg"), default="polyphase")+ encode.add_argument("--dtype", choices=("float32", "bfloat16"), default="float32")+ encode.add_argument("--verify-sha", action="store_true")+ encode.add_argument("--meta", type=Path, default=None, help="default: <out>.json")+ encode.add_argument("--features-out", type=Path, default=None,+ help="also save the instance-normed MERT features")+ # --- the round trip ---+ encode.add_argument("--roundtrip", type=Path, default=None,+ help="also synthesise the codes back to audio (.wav/.flac)")+ encode.add_argument("--model-dir", type=Path, default=None)+ encode.add_argument("--vae-dir", type=Path, default=None)+ encode.add_argument("--lora", action="append", default=[],+ help="an adapter for the acoustic branch, e.g. nar_lora_joint_v9")+ encode.add_argument("--lora-mode", choices=("joint", "separate"), default="joint")+ encode.add_argument("--steps", type=int, default=32)+ encode.add_argument("--seed", type=int, default=0)+ encode.add_argument("--precision", choices=("bf16", "8bit", "4bit"), default="bf16")+ encode.add_argument("--style", default="")+ encode.add_argument("--lyrics", default="")+ encode.add_argument("--memory-budget-gib", type=float, default=None)++ args = parser.parse_args(argv)+ os.environ.setdefault("MLX_ENABLE_TF32", "0")+ os.environ.pop("PYTORCH_ENABLE_MPS_FALLBACK", None)+ os.environ.pop("PYTORCH_MPS_FAST_MATH", None)++ if args.roundtrip is not None and (args.model_dir is None or args.vae_dir is None):+ say("error", "--roundtrip needs --model-dir and --vae-dir")+ return 2+ started = time.perf_counter()+ dtype = mx.float32 if args.dtype == "float32" else mx.bfloat16+ head_file = args.head or _default_head()+ try:+ head = load_head(head_file, dtype=dtype, verify_sha=args.verify_sha)+ say("stage", f"head {Path(head_file).name} · {args.dtype}")+ features = extract(args.audio, mert_dir=args.mert_dir, layer=args.mert_layer,+ start=args.start, seconds=args.seconds, resampler=args.resampler,+ progress=lambda k, n: say("mert", f"{k}/{n}"))+ mx.clear_cache()+ say("stage", f"features {len(features.values)} frames · {features.resampler}")+ codes = predict_codes(head, features.values, batch_dtype=dtype,+ progress=lambda k, n: say("codes", f"{k}/{n}"))+ except (FileNotFoundError, ValueError, RuntimeError) as error:+ say("error", f"{type(error).__name__}: {error}")+ return 2+ args.out.parent.mkdir(parents=True, exist_ok=True)+ np.save(args.out, codes.astype(np.int32), allow_pickle=False)+ statistics = code_statistics(codes)+ metadata = {+ "head": head.identity, "features": features.summary(), "source": features.source,+ "start_seconds": args.start, "requested_seconds": args.seconds,+ "window": WINDOW, "hop": HOP, "trim": TRIM, "statistics": statistics,+ "codes": str(args.out), "encode_seconds": round(time.perf_counter() - started, 2),+ }+ say("codes", f"{statistics['frames']} frames · {statistics['seconds']:.2f} s · "+ f"{statistics['unique']} unique · top {statistics['top_share'] * 100:.1f}% · "+ f"repeat {statistics['repeat']:.3f} · run mean {statistics['run_mean']:.2f}")+ if args.features_out is not None:+ np.save(args.features_out, features.values.astype(np.float32), allow_pickle=False)++ if args.roundtrip is not None:+ del head+ mx.clear_cache()+ say("stage", "synthesising")+ pipe, runtime, adapters = build_pipeline(+ args.model_dir, args.vae_dir, precision=args.precision, steps=args.steps,+ memory_budget_gib=args.memory_budget_gib, lora=args.lora, lora_mode=args.lora_mode)+ for adapter in adapters:+ say("stage", f"lora {adapter.name} · {adapter.branch} · {args.lora_mode}")+ synth_started = time.perf_counter()+ with pipe:+ audio, semantic = synthesize_codes(pipe, codes, style=args.style,+ lyrics=args.lyrics, seed=args.seed)+ import soundfile as sf++ args.roundtrip.parent.mkdir(parents=True, exist_ok=True)+ sf.write(str(args.roundtrip), audio, 48000, subtype="PCM_24",+ format="WAV" if args.roundtrip.suffix.lower() == ".wav" else "FLAC")+ metadata["roundtrip"] = {+ "audio": str(args.roundtrip), "seconds": round(len(audio) / 48000, 3),+ "lora": [adapter.summary() for adapter in adapters], "lora_mode": args.lora_mode,+ "steps": args.steps, "seed": args.seed, "precision": args.precision,+ "style": args.style, "lyrics": args.lyrics,+ "synthesis_seconds": round(time.perf_counter() - synth_started, 2),+ "mlx_peak_gib": round(mx.get_peak_memory() / 2 ** 30, 2),+ }+ runtime.detach()+ try:+ reference = reference_mono_48k(args.audio, start=args.start, seconds=args.seconds)+ estimate = audio.mean(axis=1) if audio.ndim == 2 else audio+ metadata["roundtrip"]["log_mel_db"] = round(spectral_distance(reference, estimate), 3)+ metadata["roundtrip"]["chroma_correlation"] = round(+ chroma_correlation(reference, estimate), 4)+ metadata["roundtrip"]["reference_seconds"] = round(len(reference) / 48000, 3)+ except Exception as error: # noqa: BLE001+ metadata["roundtrip"]["measurement_error"] = f"{type(error).__name__}: {error}"+ say("roundtrip", f"{metadata['roundtrip']['seconds']:.2f} s → {args.roundtrip}")++ meta_path = args.meta or args.out.with_name(args.out.name + ".json")+ meta_path.write_text(json.dumps(metadata, indent=2, default=str), encoding="utf-8")+ say("done", f"{time.perf_counter() - started:.2f}", str(args.out))+ return 0+++if __name__ == "__main__": # pragma: no cover+ sys.exit(main())diff --git a/scripts/music/yue2_train_voice.py b/scripts/music/yue2_train_voice.pynew file mode 100644index 0000000..b68af1c--- /dev/null+++ b/scripts/music/yue2_train_voice.py@@ -0,0 +1,1011 @@+#!/usr/bin/env python3+"""Train a voice from recordings, so YuE2 can sing new songs with it.++WHAT THIS IS+------------+An AR-branch LoRA trainer for the YuE2 MLX engine. It takes somebody's+recordings, turns them into YuE2's own semantic codes with our real-audio+tokenizer head (`yue2_tokenizer.py`), and teaches the AR model to WRITE that+code stream from style + lyrics alone. Generation then runs with+`--lora <file> --lora-trigger <word>` and no conversion step anywhere: the+singer is never resynthesised from a stranger's performance, which is what+makes a converted "clone" sound robotic (`notes/yue2/MAESTRO_VOICE_STUDY.md` §4).++The objective is Mothersuperior's `ar_lora.py` and Maestro's+`artist_training.py`, which agree to the character:++ sequence = token_prefixes(SongRequest(style, lyrics, ...)) + [code + CODEC_OFFSET ...]+ loss = cross-entropy on the CODE TAIL ONLY++The prefix is built by the engine's own `token_prefixes`, so what the model+sees while training is the byte-identical thing it will see at inference.+Nothing else in this file is allowed to invent a prompt layout.++TWO DIALECTS+------------+`--dialect direct` `cot="off"` — the prefix ends `[ABC_START, ABC_END,+ MUSIC_START]` and the model writes codes with no score.+ Generate with `--mode off`.+`--dialect score` `cot="melody"` (or `full`) with a real ABC score of the+ SAME window inside the prefix. Generate with+ `--mode melody --abc-file <score>`. This exists because a+ direct-dialect voice cannot follow a supplied score: the+ engine refuses `abc` with `cot="off"`+ (`protocol.SongRequest.__post_init__`) and a voice that has+ never seen a score in its prefix has no reason to obey one.++WINDOWS, AND WHY THE LYRICS ARE SLICED+--------------------------------------+Training pairs ONE prefix with ONE stretch of codes. If the lyrics in the+prefix are the whole song while the codes are a random slice of it, the pair+is a lie: the model learns "this style → this singer's codes" and never learns+"these words → these sounds". It then reproduces trained fragments instead of+pronouncing new lyrics. So a recording is cut into `--window-seconds` windows+(Maestro's 512 frames = 20.48 s) at `--hop-seconds`, and each window gets the+lyric lines that were actually sung inside it — from a `<stem>.lines.json`+timing sidecar when there is one, otherwise sliced by time in proportion.++The trainer stays pure: it does not run demucs, whisper or SheetSage2. Line+timings and window scores come in as sidecars; `--emit-windows` writes the+window audio so those tools can be pointed at it outside this process.++OUTPUT+------+`<out>/<name>.safetensors` in the Mothersuperior key layout that+`scripts/music/yue2_lora.py` already loads, plus `<name>.json` recording the+trigger, the dialect, the base model, the steps, a hash of the training data+and the loss curve. Drop both in `mlx_models/yue2-loras/user/` (or pass+`--install`) and the studio picker offers it.+"""+from __future__ import annotations++import argparse+import hashlib+import json+import math+import os+import random+import re+import shutil+import subprocess+import sys+import time+from dataclasses import dataclass+from pathlib import Path++import numpy as np++ROOT = Path(__file__).resolve().parents[2]+sys.path.insert(0, str(ROOT / "yue2-mlx" / "vendor" / "yue" / "src"))++from yue2.protocol import CODEC_OFFSET, CODEC_SIZE, MUSIC_END, SongRequest, token_prefixes # noqa: E402++__all__ = [+ "AUDIO_SUFFIXES", "ATTN_PROJECTIONS", "MLP_PROJECTIONS", "FRAME_RATE",+ "Window", "adapter_key", "build_dataset", "data_fingerprint", "emit_windows",+ "codes_cache_key", "file_digest", "lyrics_for_window", "match_sidecar",+ "plan_windows", "read_regularizer_cache", "read_timed_lines", "resolve_head",+ "resolve_recordings", "sidecar_metadata", "supervised_span", "training_sequence",+ "window_request", "write_regularizer_cache",+]++#: 25 semantic codes a second, like everything else in this pipeline.+FRAME_RATE = 25+#: Maestro's excerpt length: 512 frames. Kept as the default window.+DEFAULT_WINDOW_SECONDS = 512 / FRAME_RATE+DEFAULT_HOP_SECONDS = DEFAULT_WINDOW_SECONDS / 2+#: Every projection an AR LoRA targets, 28 layers × 7 = 196.+ATTN_PROJECTIONS = ("q_proj", "k_proj", "v_proj", "o_proj")+MLP_PROJECTIONS = ("gate_proj", "up_proj", "down_proj")+AUDIO_SUFFIXES = (".wav", ".flac", ".mp3", ".m4a", ".aac", ".ogg", ".opus")+DIALECTS = ("direct", "score")+#: A window with fewer codes than this is a scrap, not an excerpt.+MIN_WINDOW_FRAMES = 64+++# --------------------------------------------------------------- the inputs --++def resolve_recordings(paths) -> list[Path]:+ """`--recordings` is a directory or a list of files; either way, sorted files."""+ found: list[Path] = []+ for item in paths:+ path = Path(item).expanduser()+ if path.is_dir():+ found += sorted(p for p in path.iterdir()+ if p.is_file() and p.suffix.lower() in AUDIO_SUFFIXES)+ elif path.is_file():+ found.append(path)+ else:+ raise FileNotFoundError(f"No recording at {path}")+ if not found:+ raise ValueError("No recordings found — give a folder of audio or the files")+ return found+++def match_sidecar(audio: Path, sources, suffixes, *, allow_single=False) -> Path | None:+ """The file that belongs to this recording: same stem, one of `suffixes`.++ `sources` is whatever the caller passed (folders and/or files). With+ `allow_single`, one file given for one recording wins outright, so the+ one-song case does not have to rename anything to match.+ """+ candidates: list[Path] = []+ for item in sources or []:+ path = Path(item).expanduser()+ if path.is_dir():+ candidates += [p for p in path.iterdir() if p.is_file()]+ elif path.is_file():+ candidates.append(path)+ for path in candidates:+ if path.stem == audio.stem and path.suffix.lower() in suffixes:+ return path+ for path in candidates:+ if path.stem == audio.stem:+ return path+ if allow_single and len(candidates) == 1:+ return candidates[0]+ return None+++_SECTION = re.compile(r"^\s*\[[^\]]*\]\s*$")+++def read_timed_lines(path: Path | None) -> list[dict] | None:+ """A `<stem>.lines.json` timing sidecar → [{text, onset, end, section}].++ Shape accepted: a bare list, or `{"lines": [...]}`. Each entry carries+ `text` and `onset` (seconds); `end` and `section` are optional. Lines+ without an onset are dropped — an unlocated line cannot be attributed to a+ window, and guessing would put the wrong words in the prefix.+ """+ if path is None or not path.is_file():+ return None+ data = json.loads(path.read_text(encoding="utf-8"))+ rows = data["lines"] if isinstance(data, dict) else data+ lines: list[dict] = []+ for row in rows:+ text = str(row.get("text", "")).strip()+ onset = row.get("onset", row.get("s"))+ if not text or onset is None:+ continue+ end = row.get("end", row.get("e"))+ lines.append({"text": text, "onset": float(onset),+ "end": None if end is None else float(end),+ "section": (str(row.get("section")).strip()+ if row.get("section") else None)})+ lines.sort(key=lambda row: row["onset"])+ return lines or None+++def lyrics_for_window(lyrics_text: str, lines: list[dict] | None,+ start: float, end: float, duration: float) -> str:+ """The words sung inside [start, end) — timed when we know, proportional when not.++ Timed: every line whose onset falls in the window (plus a line still+ running into it). Untimed: the song's sung lines cut by the window's share+ of the recording, which is crude but keeps each prefix roughly honest about+ its own codes. Section tags ride along so the prefix looks like the one+ inference builds.+ """+ if lines:+ chosen = [row for row in lines+ if start <= row["onset"] < end+ or (row["end"] is not None and row["onset"] < start < row["end"])]+ if not chosen:+ return ""+ out: list[str] = []+ section = chosen[0].get("section")+ if section:+ out.append(section)+ for row in chosen:+ if row.get("section") and row["section"] != section:+ section = row["section"]+ out.append(section)+ out.append(row["text"])+ return "\n".join(out)++ body = [line.strip() for line in lyrics_text.splitlines() if line.strip()]+ sung = [line for line in body if not _SECTION.match(line)]+ if not sung or duration <= 0:+ return ""+ first = min(int(len(sung) * start / duration), len(sung) - 1)+ last = max(first + 1, min(int(math.ceil(len(sung) * end / duration)), len(sung)))+ head = [line for line in body[:body.index(sung[first]) + 1] if _SECTION.match(line)]+ return "\n".join(head[-1:] + sung[first:last])+++# ------------------------------------------------------------- the sequences --++@dataclass(frozen=True)+class Window:+ """One training excerpt: where it came from and what its prefix says."""+ source: str+ index: int+ start: float+ seconds: float+ lyrics: str+ abc: str | None+ frames: int+++def plan_windows(frames: int, window_frames: int, hop_frames: int) -> list[tuple[int, int]]:+ """[start, end) code spans covering the track, the last one flush with the end."""+ if frames < MIN_WINDOW_FRAMES:+ return []+ if window_frames < MIN_WINDOW_FRAMES or hop_frames < 1:+ raise ValueError("A window needs at least 64 frames and a positive hop")+ if frames <= window_frames:+ return [(0, frames)]+ spans = [(start, start + window_frames)+ for start in range(0, frames - window_frames + 1, hop_frames)]+ if spans[-1][1] < frames:+ spans.append((frames - window_frames, frames))+ return spans+++def window_request(style: str, trigger: str, lyrics: str, *, dialect: str,+ abc: str | None, cot: str, identifier: str) -> SongRequest:+ """The request whose prefix this window trains on — the engine's own dataclass."""+ if dialect not in DIALECTS:+ raise ValueError(f"dialect must be one of {DIALECTS}")+ text = style.strip()+ trigger = trigger.strip()+ if trigger and trigger.lower() not in text.lower():+ text = f"{trigger}, {text}" if text else trigger+ if dialect == "direct":+ return SongRequest(style=text, lyrics=lyrics, cot="off", seed=1, id=identifier)+ if not (abc or "").strip():+ raise ValueError("The score dialect needs an ABC score for the window")+ return SongRequest(style=text, lyrics=lyrics, cot=cot, abc=abc, seed=1, id=identifier)+++def training_sequence(prefix, codes, max_len: int, rng=None):+ """`prefix + codes` as ids, with the index the loss is allowed to start at.++ Mothersuperior truncates a long track to its head. With windowed data the+ codes already fit; the random window here only matters when a caller hands+ in a whole track, and it is a window over the performance rather than a+ permanent bias towards its first minute.+ """+ prefix = [int(token) for token in prefix]+ codes = np.asarray(codes).reshape(-1)+ if codes.size and (codes.min() < 0 or codes.max() >= CODEC_SIZE):+ raise ValueError("Codes outside the 32768-symbol semantic vocabulary")+ room = max_len - len(prefix) - 1+ if room < MIN_WINDOW_FRAMES:+ raise ValueError(f"The prefix leaves room for {room} codes; raise --max-len")+ if codes.size <= room:+ body = [int(code) + CODEC_OFFSET for code in codes] + [MUSIC_END]+ else:+ start = 0 if rng is None else rng.randrange(0, int(codes.size) - room + 1)+ body = [int(code) + CODEC_OFFSET for code in codes[start:start + room]]+ return prefix + body, len(prefix)+++def supervised_span(prefix_len: int, total: int):+ """Which hidden states are scored, and against which ids — the code tail only.++ Position `i`'s hidden state predicts token `i+1`, so the first state that+ may be scored is the last PREFIX position and the first target is the first+ CODE token. Score one position earlier and the model is being taught to+ write the prompt; one later and the first code is never supervised. This is+ the loss mask, and it is the whole difference between teaching a voice and+ teaching a prompt.+ """+ if not 1 <= prefix_len < total:+ raise ValueError("The prefix has to be shorter than the sequence")+ return slice(prefix_len - 1, total - 1), slice(prefix_len, total)+++# ------------------------------------------------------------ the dataset --++def file_digest(path: Path) -> str:+ """sha256 of a file's bytes, streamed. Identity, not name."""+ digest = hashlib.sha256()+ with Path(path).open("rb") as handle:+ for block in iter(lambda: handle.read(1 << 20), b""):+ digest.update(block)+ return digest.hexdigest()+++def resolve_head(head: Path | None, lora_dir: Path | None) -> Path:+ """The tokenizer head to encode with, checked BEFORE anything expensive.++ `--head` defaults to the pinned one in the music LoRA pack. Leaving it+ unresolved used to hand `None` all the way down to `load_head()`, where+ `Path(None)` raised a bare TypeError halfway through a training run — and+ only on a cold codes cache, so it hid until somebody trained a fresh voice.+ """+ if head is not None:+ head = Path(head).expanduser()+ if not head.is_file():+ raise FileNotFoundError(f"No tokenizer head at {head}")+ return head+ root = Path(lora_dir).expanduser() if lora_dir else (+ Path(os.environ.get("LTX_MUSIC_LORAS") or ROOT / "mlx_models" / "yue2-loras"))+ sys.path.insert(0, str(ROOT))+ from scripts.pinokio.music_lora_fetch import head_path # noqa: PLC0415++ candidate = head_path(root)+ if not candidate.is_file():+ raise FileNotFoundError(+ f"The tokenizer head is not installed ({candidate}). Install the music "+ f"LoRA pack, or pass --head. It is what turns a recording into codes.")+ return candidate+++def codes_cache_key(audio: Path, head: Path, mert_layer=None) -> str:+ """What a cached encode is allowed to be reused for.++ Keyed by the recording's CONTENTS and the head that read them, never by+ file name: two albums both holding a `take.wav` used to share one cache+ entry, so the second voice trained on the first one's codes — paired with+ its own lyrics. Replacing a recording in place had the same effect.+ """+ parts = [file_digest(audio), Path(head).name, file_digest(head)[:16],+ str(mert_layer if mert_layer is not None else "default")]+ return hashlib.sha256("|".join(parts).encode()).hexdigest()[:16]+++def _codes_for(audio: Path, cache: Path | None, head_file: Path,+ mert_dir: Path | None, say, *, mert_layer=None) -> np.ndarray:+ """Semantic codes for a recording, tokenised once and cached by identity."""+ target = None+ if cache is not None:+ key = codes_cache_key(audio, head_file, mert_layer)+ target = Path(cache) / f"{audio.stem}.{key}.codes.npy"+ sidecar = target.with_suffix(".json")+ if target.is_file() and sidecar.is_file():+ try:+ stored = json.loads(sidecar.read_text()).get("cache_key")+ except (json.JSONDecodeError, OSError):+ stored = None+ if stored == key:+ say(f"codes cached {audio.name} ({key})")+ return np.load(target, allow_pickle=False).reshape(-1).astype(np.int64)+ say(f"codes cache MISS for {audio.name}: the entry is for other bytes")+ sys.path.insert(0, str(Path(__file__).resolve().parent))+ import yue2_tokenizer as T # noqa: PLC0415++ codes, metadata = T.encode_codes(audio, head_file=head_file, mert_dir=mert_dir,+ on_stage=lambda stage: say(f" {audio.name}: {stage}"))+ codes = np.asarray(codes).reshape(-1).astype(np.int64)+ if target is not None:+ target.parent.mkdir(parents=True, exist_ok=True)+ np.save(target, codes.astype(np.int32))+ target.with_suffix(".json").write_text(json.dumps(+ {"cache_key": codes_cache_key(audio, head_file, mert_layer),+ "source": str(audio), "source_sha256": file_digest(audio),+ "head": str(head_file), "frames": int(codes.size),+ "metadata": metadata}, indent=2, default=str))+ return codes+++def build_dataset(recordings, *, style: str, trigger: str, dialect: str, cot: str,+ lyrics_sources=None, scores_dir: Path | None = None,+ window_frames: int, hop_frames: int, tokenizer,+ codes_of, say=print):+ """Every window of every recording, as (Window, prefix ids, codes).++ `codes_of(audio)` hands back the semantic codes — injected so the caller+ decides whether that means the tokenizer head or a cache, and so this is+ testable without a GPU.+ """+ items, windows, skipped = [], [], {"no_score": 0, "short": 0, "no_lyrics": 0}+ recordings = list(recordings)+ for audio in recordings:+ codes = np.asarray(codes_of(audio)).reshape(-1)+ duration = len(codes) / FRAME_RATE+ lyrics_file = match_sidecar(audio, lyrics_sources, (".txt", ".md"),+ allow_single=len(recordings) == 1)+ lyrics_text = lyrics_file.read_text(encoding="utf-8") if lyrics_file else ""+ lines = read_timed_lines(audio.with_suffix(".lines.json"))+ if lines is None and lyrics_file is not None:+ lines = read_timed_lines(lyrics_file.with_suffix(".lines.json"))+ spans = plan_windows(len(codes), window_frames, hop_frames)+ say(f"{audio.name}: {len(codes)} frames ({duration:.1f}s) → {len(spans)} windows"+ f"{' (timed lyrics)' if lines else ''}")+ for index, (first, last) in enumerate(spans):+ if last - first < MIN_WINDOW_FRAMES:+ skipped["short"] += 1+ continue+ start, end = first / FRAME_RATE, last / FRAME_RATE+ words = lyrics_for_window(lyrics_text, lines, start, end, duration)+ abc = None+ if dialect == "score":+ score_file = None+ if scores_dir is not None:+ score_file = Path(scores_dir) / f"{audio.stem}.w{index:03d}.abc"+ if score_file is None or not score_file.is_file():+ skipped["no_score"] += 1+ continue+ abc = score_file.read_text(encoding="utf-8")+ if not words.strip():+ skipped["no_lyrics"] += 1+ request = window_request(style, trigger, words, dialect=dialect, abc=abc,+ cot=cot, identifier=f"w{len(items):04d}")+ prefix = token_prefixes(request, tokenizer)+ window = Window(source=audio.name, index=index, start=round(start, 3),+ seconds=round(end - start, 3), lyrics=words, abc=abc,+ frames=int(last - first))+ windows.append(window)+ items.append({"src": "artist", "name": f"{audio.stem}.w{index:03d}",+ "prefix": np.asarray(prefix, dtype=np.int64),+ "codec": codes[first:last].astype(np.int64)})+ if not items:+ raise ValueError(f"No trainable windows (skipped {skipped})")+ say(f"dataset: {len(items)} windows, skipped {skipped}")+ return items, windows, skipped+++#: Bumped when the on-disk shape of a regulariser cache changes.+REG_CACHE_VERSION = 2+++def write_regularizer_cache(path: Path, items) -> Path:+ """Ragged int sequences as flat arrays + offsets, and names as JSON.++ Deliberately NOT an object array. The first version wrote+ `np.savez(items=np.asarray(items, dtype=object))` and read it back with+ `allow_pickle=True`, which executes whatever `__reduce__` the file asks+ for — so a shared or downloaded `--reg-cache` was arbitrary code execution,+ reached even by `--plan-only`.+ """+ path = Path(path)+ path.parent.mkdir(parents=True, exist_ok=True)+ prefix_offsets, codec_offsets = [0], [0]+ prefixes, codecs = [], []+ for item in items:+ prefixes.append(np.asarray(item["prefix"], dtype=np.int64).reshape(-1))+ codecs.append(np.asarray(item["codec"], dtype=np.int64).reshape(-1))+ prefix_offsets.append(prefix_offsets[-1] + prefixes[-1].size)+ codec_offsets.append(codec_offsets[-1] + codecs[-1].size)+ empty = np.zeros(0, dtype=np.int64)+ np.savez(path,+ version=np.asarray(REG_CACHE_VERSION, dtype=np.int64),+ prefix_data=np.concatenate(prefixes) if prefixes else empty,+ prefix_offsets=np.asarray(prefix_offsets, dtype=np.int64),+ codec_data=np.concatenate(codecs) if codecs else empty,+ codec_offsets=np.asarray(codec_offsets, dtype=np.int64),+ meta=np.asarray(json.dumps(+ [{"src": str(item["src"]), "name": str(item["name"])} for item in items])))+ return path+++def read_regularizer_cache(path: Path) -> list[dict]:+ """The inverse, with `allow_pickle=False`. A legacy cache is refused, loudly."""+ with np.load(Path(path), allow_pickle=False) as blob:+ missing = {"version", "prefix_data", "prefix_offsets", "codec_data",+ "codec_offsets", "meta"} - set(blob.files)+ if missing:+ raise ValueError(+ f"{Path(path).name} is not a v{REG_CACHE_VERSION} regulariser cache "+ f"(missing {sorted(missing)}). Delete it and let --reg-pack rebuild "+ f"it; the old format was a pickle and is no longer read.")+ version = int(blob["version"])+ if version != REG_CACHE_VERSION:+ raise ValueError(f"{Path(path).name} is version {version}, not "+ f"{REG_CACHE_VERSION}; delete it and rebuild")+ prefix_data, prefix_offsets = blob["prefix_data"], blob["prefix_offsets"]+ codec_data, codec_offsets = blob["codec_data"], blob["codec_offsets"]+ meta = json.loads(str(blob["meta"]))+ items = []+ for index, row in enumerate(meta):+ items.append({+ "src": row["src"], "name": row["name"],+ "prefix": prefix_data[prefix_offsets[index]:prefix_offsets[index + 1]],+ "codec": codec_data[codec_offsets[index]:codec_offsets[index + 1]]})+ return items+++def load_regularizer(path: Path, tokenizer, *, cap: int, validation: int,+ cache: Path | None = None, say=print):+ """Minted base-dialect songs, so the AR stays inside YuE2's own dialect.++ Maestro mixes these against the artist at `artist_fraction`; without them+ an AR LoRA drifts out of the dialect and the decoder stops understanding+ it. The pack is a torch file; a converted copy is cached as .npz so a+ machine without torch can still train.+ """+ if cache is not None and Path(cache).is_file():+ items = read_regularizer_cache(cache)[: cap + validation]+ say(f"regularizer cached: {len(items)} songs")+ return items+ import torch # noqa: PLC0415++ with torch.serialization.safe_globals([np._core.multiarray._reconstruct, np.ndarray,+ np.dtype, np.dtypes.Int32DType,+ np.dtypes.Int64DType]):+ data = torch.load(path, map_location="cpu", weights_only=True)+ if isinstance(data, dict):+ data = data.get("records", data.get("items", data.get("data")))+ items, kept = [], {"minted": 0, "minted_val": 0}+ for index, record in enumerate(data):+ source = record.get("src")+ if source not in {"minted", "minted_val"}:+ source = "minted_val" if index % 20 == 0 else "minted"+ limit = validation if source == "minted_val" else cap+ if kept[source] >= limit:+ continue+ codes = np.asarray(record["codec"], dtype=np.int64).reshape(-1)+ if not codes.size or codes.min() < 0 or codes.max() >= CODEC_SIZE:+ raise ValueError("The regulariser pack carries invalid semantic codes")+ request = SongRequest(style=str(record["style"]), lyrics=str(record["lyrics"]),+ cot="off", seed=1, id=f"m{index}")+ items.append({"src": source, "name": f"m{index}",+ "prefix": np.asarray(token_prefixes(request, tokenizer), dtype=np.int64),+ "codec": codes})+ kept[source] += 1+ say(f"regularizer: {kept['minted']} minted, {kept['minted_val']} held out")+ if cache is not None:+ write_regularizer_cache(cache, items)+ return items+++def data_fingerprint(recordings, lyrics_sources, scores_dir) -> str:+ """One hash over everything that decided the dataset, for the sidecar."""+ digest = hashlib.sha256()+ for audio in recordings:+ digest.update(audio.name.encode())+ digest.update(str(audio.stat().st_size).encode())+ with audio.open("rb") as handle:+ digest.update(handle.read(1 << 20))+ for item in sorted(str(Path(p)) for p in (lyrics_sources or [])):+ digest.update(item.encode())+ if scores_dir is not None:+ for score in sorted(Path(scores_dir).glob("*.abc")):+ digest.update(score.read_bytes())+ return digest.hexdigest()+++# ---------------------------------------------------------- window audio out --++def emit_windows(recordings, out: Path, *, window_seconds: float, hop_seconds: float,+ codes_of, say=print) -> list[dict]:+ """Write each window as its own wav, so a transcriber can be pointed at it.++ The score dialect needs an ABC score PER WINDOW, and the thing that makes+ one is the engine's cover transcription (`yue2_run.py --source-audio+ --cover-task melody-vocal --transcribe-only`). Rather than pull SheetSage2+ into this trainer, hand that tool the exact audio each window trains on.+ """+ out.mkdir(parents=True, exist_ok=True)+ ffmpeg = shutil.which("ffmpeg")+ if not ffmpeg:+ raise FileNotFoundError("ffmpeg is not on PATH; it cuts the window audio")+ window_frames = int(round(window_seconds * FRAME_RATE))+ hop_frames = max(1, int(round(hop_seconds * FRAME_RATE)))+ # Window files are named by basename, because the per-window ABC scores are+ # looked up by that name. So the manifest carries the source's sha256 and a+ # window cut from DIFFERENT bytes is re-cut rather than silently reused.+ previous = {}+ if (out / "windows.json").is_file():+ try:+ for row in json.loads((out / "windows.json").read_text()):+ previous[row.get("file")] = row.get("source_sha256")+ except (json.JSONDecodeError, OSError):+ previous = {}+ manifest: list[dict] = []+ for audio in recordings:+ source_sha = file_digest(audio)+ codes = np.asarray(codes_of(audio)).reshape(-1)+ for index, (first, last) in enumerate(plan_windows(len(codes), window_frames,+ hop_frames)):+ start, seconds = first / FRAME_RATE, (last - first) / FRAME_RATE+ target = out / f"{audio.stem}.w{index:03d}.wav"+ stale = target.is_file() and previous.get(target.name) != source_sha+ if stale:+ say(f"re-cutting {target.name}: it was cut from other bytes")+ if not target.is_file() or stale:+ done = subprocess.run(+ [ffmpeg, "-nostdin", "-v", "error", "-y", "-ss", f"{start:.3f}",+ "-t", f"{seconds:.3f}", "-i", str(audio), "-ac", "2",+ str(target)], stdout=subprocess.PIPE, stderr=subprocess.PIPE)+ if done.returncode:+ raise RuntimeError(f"ffmpeg failed on {target.name}: "+ f"{done.stderr.decode('utf-8', 'replace')[-200:]}")+ manifest.append({"source": audio.name, "index": index, "file": target.name,+ "source_sha256": source_sha,+ "start": round(start, 3), "seconds": round(seconds, 3),+ "frames": int(last - first)})+ (out / "windows.json").write_text(json.dumps(manifest, indent=2))+ say(f"windows: {len(manifest)} files in {out}")+ return manifest+++# ------------------------------------------------------------------ training --++def adapter_key(layer: int, group: str, projection: str) -> str:+ """The one spelling `yue2_lora.read_adapter` normalises everything else to."""+ return f"layers.{layer}.{group}.{projection}"+++def _targets(model):+ out = {}+ for index, layer in enumerate(model.model.layers):+ for group, names in (("self_attn", ATTN_PROJECTIONS), ("mlp", MLP_PROJECTIONS)):+ container = getattr(layer, group)+ for name in names:+ out[adapter_key(index, group, name)] = (container, name)+ return out+++class _Slot:+ """Where a wrapped projection finds its current A and B."""+ __slots__ = ("a", "b")++ def __init__(self):+ self.a = self.b = None+++_SLOT_ATTR = "_train_lora_slot"+_wrapped: dict[type, type] = {}+++def _lora_class(base: type) -> type:+ if base in _wrapped:+ return _wrapped[base]++ class _LoRA(base): # type: ignore[misc]+ def __call__(self, x, *args, **kwargs):+ out = super().__call__(x, *args, **kwargs)+ slot = object.__getattribute__(self, _SLOT_ATTR)+ delta = (x.astype(slot.a.dtype) @ slot.a.T) @ slot.b.T+ return out + delta.astype(out.dtype)++ _LoRA.__name__ = f"TrainLoRA{base.__name__}"+ _wrapped[base] = _LoRA+ return _LoRA+++def _linear_shape(module):+ weight = module.weight+ scales = module.get("scales") if hasattr(module, "get") else None+ if scales is not None:+ return int(weight.shape[0]), int(scales.shape[1]) * int(module.group_size)+ return int(weight.shape[0]), int(weight.shape[1])+++def install_adapters(model, rank: int, seed: int):+ """Wrap every AR target in place; return the slots and the parameter tree.++ Same trick as `yue2_lora.apply_adapters`: swap the projection's class+ rather than nest it in a wrapper, so not one parameter is renamed.+ """+ import mlx.core as mx # noqa: PLC0415++ rng = np.random.default_rng(seed)+ slots, params = {}, {}+ for name, (container, attribute) in _targets(model).items():+ module = getattr(container, attribute)+ out_features, in_features = _linear_shape(module)+ slot = _Slot()+ object.__setattr__(module, _SLOT_ATTR, slot)+ module.__class__ = _lora_class(type(module))+ slots[name] = slot+ params[name] = {+ "A": mx.array((rng.standard_normal((rank, in_features))+ / math.sqrt(in_features)).astype(np.float32)),+ "B": mx.zeros((out_features, rank), dtype=mx.float32),+ }+ return slots, params+++def bind(slots, params):+ for name, slot in slots.items():+ slot.a, slot.b = params[name]["A"], params[name]["B"]+++def save_adapter(params, path: Path, *, rank: int, dialect: str, trigger: str):+ """BF16 `lora_A`/`lora_B` pairs, the layout the runtime already reads."""+ import mlx.core as mx # noqa: PLC0415++ flat = {}+ for name, pair in params.items():+ flat[f"{name}.lora_A"] = pair["A"].astype(mx.bfloat16)+ flat[f"{name}.lora_B"] = pair["B"].astype(mx.bfloat16)+ path.parent.mkdir(parents=True, exist_ok=True)+ mx.save_safetensors(str(path), flat, metadata={+ "format": "mlx", "branch": "ar", "rank": str(rank), "dialect": dialect,+ "trigger": trigger, "targets": "self_attn q,k,v,o + mlp gate,up,down"})+++def sidecar_metadata(*, name: str, trigger: str, dialect: str, cot: str, style: str,+ model_dir: Path, steps: int, rank: int, lr: float,+ window_seconds: float, hop_seconds: float, windows, skipped,+ fingerprint: str, metrics: dict, seed: int,+ artist_fraction: float) -> dict:+ """What a listener has to know to use this file, and to trust its numbers."""+ revision = {}+ conversion = Path(model_dir) / "conversion.json"+ if conversion.is_file():+ try:+ raw = json.loads(conversion.read_text())+ revision = {key: raw[key] for key in ("format", "schema", "upstream")+ if key in raw}+ identity = (raw.get("source") or {}).get("identity") or {}+ for key in ("repo", "repository", "revision", "commit"):+ if key in identity:+ revision[key] = identity[key]+ except (json.JSONDecodeError, OSError):+ revision = {}+ return {+ "name": name, "kind": "yue2-ar-voice", "branch": "ar", "trigger": trigger,+ "dialect": dialect, "cot": cot, "style": style,+ "generate_with": ("--mode off" if dialect == "direct"+ else f"--mode {cot} --abc-file <score.abc>"),+ "base": {"model_dir": str(model_dir), **revision},+ "training": {"steps": steps, "rank": rank, "lr": lr, "seed": seed,+ "artist_fraction": artist_fraction,+ "window_seconds": window_seconds, "hop_seconds": hop_seconds,+ "windows": len(windows), "skipped": skipped},+ "data": {"fingerprint": fingerprint,+ "recordings": sorted({window.source for window in windows}),+ "windows_with_lyrics": sum(1 for w in windows if w.lyrics.strip()),+ "windows_with_score": sum(1 for w in windows if w.abc)},+ "metrics": metrics,+ "created": time.strftime("%Y-%m-%dT%H:%M:%S"),+ }+++# ----------------------------------------------------------------- the CLI --++def build_parser() -> argparse.ArgumentParser:+ p = argparse.ArgumentParser(+ prog="yue2_train_voice.py",+ description="Train a YuE2 voice (AR LoRA) from recordings.")+ p.add_argument("--recordings", nargs="+", required=True,+ help="a folder of audio, or the files themselves")+ p.add_argument("--lyrics", nargs="*", default=None,+ help="a folder or files matching the recordings by stem; "+ "'none' trains timbre only")+ p.add_argument("--trigger", default="", help="the word that turns the voice on")+ p.add_argument("--out", type=Path, required=True)+ p.add_argument("--name", default=None, help="output basename (default: the trigger)")+ p.add_argument("--style", default="", help="style tags every window trains with")+ p.add_argument("--style-file", type=Path, default=None)+ p.add_argument("--dialect", choices=DIALECTS, default="direct")+ p.add_argument("--cot", choices=("melody", "full"), default="melody",+ help="score dialect only: which planning instruction")+ p.add_argument("--scores", type=Path, default=None,+ help="score dialect only: folder of <stem>.wNNN.abc")+ p.add_argument("--reg-pack", type=Path, default=None,+ help="minted_regularizer_pack.pt — keeps the AR in YuE2's dialect")+ p.add_argument("--reg-cache", type=Path, default=None,+ help="converted copy of the pack (.npz), written on first use")+ p.add_argument("--reg-cap", type=int, default=400)+ p.add_argument("--reg-validation", type=int, default=6)+ p.add_argument("--artist-fraction", type=float, default=0.5)+ p.add_argument("--steps", type=int, default=400)+ p.add_argument("--rank", type=int, default=32)+ p.add_argument("--lr", type=float, default=1e-4)+ p.add_argument("--sched-steps", type=int, default=3000)+ p.add_argument("--accumulation", type=int, default=2)+ p.add_argument("--max-len", type=int, default=2048)+ p.add_argument("--chunk", type=int, default=256)+ p.add_argument("--window-seconds", type=float, default=DEFAULT_WINDOW_SECONDS)+ p.add_argument("--hop-seconds", type=float, default=DEFAULT_HOP_SECONDS)+ p.add_argument("--eval-every", type=int, default=50)+ p.add_argument("--save-every", type=int, default=100)+ p.add_argument("--seed", type=int, default=4242)+ p.add_argument("--minutes", type=float, default=None, help="wall-clock budget")+ p.add_argument("--model-dir", type=Path,+ default=ROOT / "mlx_models" / "yue2" / "generator")+ p.add_argument("--head", type=Path, default=None, help="tokenizer head (default: the pack's)")+ p.add_argument("--mert-dir", type=Path, default=None)+ p.add_argument("--codes-cache", type=Path, default=None,+ help="where tokenised codes are kept (default: <out>/codes)")+ p.add_argument("--emit-windows", type=Path, default=None,+ help="write the window audio here and stop")+ p.add_argument("--plan-only", action="store_true",+ help="build the dataset, write the plan, train nothing")+ p.add_argument("--install", action="store_true",+ help="also copy the result into the music LoRA folder's user/ dir")+ p.add_argument("--lora-dir", type=Path,+ default=ROOT / "mlx_models" / "yue2-loras")+ return p+++def main(argv=None) -> int:+ args = build_parser().parse_args(argv)+ out = Path(args.out).expanduser()+ out.mkdir(parents=True, exist_ok=True)+ log = (out / "train.log").open("a")++ def say(*parts):+ message = " ".join(str(part) for part in parts)+ print(message, flush=True)+ log.write(f"{time.strftime('%H:%M:%S')} {message}\n")+ log.flush()++ name = args.name or (args.trigger or "voice")+ style = args.style+ if args.style_file:+ style = Path(args.style_file).read_text(encoding="utf-8")+ style = " ".join(style.split())+ lyrics_sources = None if (args.lyrics in (None, ["none"], ["None"])) else args.lyrics++ recordings = resolve_recordings(args.recordings)+ say(f"recordings: {len(recordings)}")+ codes_cache = args.codes_cache or (out / "codes")+ head = resolve_head(args.head, args.lora_dir)+ say(f"tokenizer head: {head.name}")+ codes_of = (lambda audio: _codes_for(audio, codes_cache, head, args.mert_dir, say))++ if args.emit_windows:+ emit_windows(recordings, Path(args.emit_windows),+ window_seconds=args.window_seconds, hop_seconds=args.hop_seconds,+ codes_of=codes_of, say=say)+ return 0++ sys.path.insert(0, str(ROOT / "mlx_models" / "yue2" / "generator"))+ from yue2.tokenization_yue2 import YuE2TextTokenizer # noqa: PLC0415+ tokenizer = YuE2TextTokenizer(str(Path(args.model_dir) / "qwen.tiktoken"))++ window_frames = int(round(args.window_seconds * FRAME_RATE))+ hop_frames = max(1, int(round(args.hop_seconds * FRAME_RATE)))+ items, windows, skipped = build_dataset(+ recordings, style=style, trigger=args.trigger, dialect=args.dialect,+ cot=args.cot, lyrics_sources=lyrics_sources, scores_dir=args.scores,+ window_frames=window_frames, hop_frames=hop_frames, tokenizer=tokenizer,+ codes_of=codes_of, say=say)++ if args.reg_pack or args.reg_cache:+ items += load_regularizer(args.reg_pack, tokenizer, cap=args.reg_cap,+ validation=args.reg_validation,+ cache=args.reg_cache, say=say)+ else:+ say("WARNING no regulariser: the AR can drift out of YuE2's dialect")++ fingerprint = data_fingerprint(recordings, lyrics_sources, args.scores)+ plan = {"windows": [vars(window) | {"lyrics": len(window.lyrics.split()),+ "abc": bool(window.abc)} for window in windows],+ "skipped": skipped, "fingerprint": fingerprint,+ "prefix_tokens": [len(item["prefix"]) for item in items if item["src"] == "artist"]}+ (out / "plan.json").write_text(json.dumps(plan, indent=2))+ longest = max(plan["prefix_tokens"])+ say(f"prefix tokens: min {min(plan['prefix_tokens'])} max {longest}")+ if longest + MIN_WINDOW_FRAMES >= args.max_len:+ raise SystemExit(f"--max-len {args.max_len} is too small for a {longest}-token prefix")+ if args.plan_only:+ say("PLAN ONLY — nothing trained")+ return 0++ return _train(args, items, windows, out, name, style, fingerprint, skipped, say)+++def _train(args, items, windows, out: Path, name: str, style: str,+ fingerprint: str, skipped, say) -> int:+ import mlx.core as mx # noqa: PLC0415+ import mlx.nn as nn # noqa: PLC0415+ import mlx.optimizers as optim # noqa: PLC0415++ sys.path.insert(0, str(ROOT / "yue2-mlx" / "src"))+ from lyra.ar import load_ar # noqa: PLC0415++ groups = {"artist": [], "minted": [], "minted_val": []}+ for item in items:+ groups[item["src"]].append(item)+ rng = random.Random(args.seed)+ mx.random.seed(args.seed)++ model = load_ar(args.model_dir, precision="bf16", verify=False)+ model.freeze()+ mx.eval(model.parameters())+ slots, params = install_adapters(model, args.rank, args.seed)+ mx.eval(params)+ count = sum(value.size for pair in params.values() for value in pair.values())+ say(f"AR LoRA {count / 1e6:.1f}M params, rank {args.rank}, lr {args.lr}, "+ f"{len(groups['artist'])} artist windows, {len(groups['minted'])} minted")++ def loss_fn(parameters, ids, prefix_len):+ bind(slots, parameters)+ states, labels = supervised_span(prefix_len, int(ids.shape[0]))+ hidden = model.model(ids[None])[0][states]+ targets = ids[labels]+ total = mx.zeros((), dtype=mx.float32)+ for start in range(0, hidden.shape[0], args.chunk):+ logits = model.lm_head(hidden[start:start + args.chunk]).astype(mx.float32)+ total = total + nn.losses.cross_entropy(+ logits, targets[start:start + args.chunk], reduction="sum")+ return total / targets.shape[0]++ value_and_grad = mx.value_and_grad(loss_fn)+ optimizer = optim.AdamW(learning_rate=args.lr, betas=[0.9, 0.95], weight_decay=0.0)++ def ids_of(item, jitter):+ sequence, prefix_len = training_sequence(item["prefix"], item["codec"],+ args.max_len, jitter)+ return mx.array(sequence, dtype=mx.int32), prefix_len++ def evaluate():+ scores = {}+ for tag, pool in (("minted_val", groups["minted_val"][:4]),+ ("artist", groups["artist"][:8])):+ if not pool:+ continue+ values = []+ for item in pool:+ ids, prefix_len = ids_of(item, None)+ values.append(float(loss_fn(params, ids, prefix_len)))+ scores[tag] = round(sum(values) / len(values), 4)+ return scores++ history, started = [], time.time()+ baseline = evaluate()+ history.append({"step": 0, **baseline})+ say("EVAL step 0 " + " ".join(f"{k} {v:.3f}" for k, v in baseline.items()))+ deadline = started + args.minutes * 60 if args.minutes else None+ step = 0++ def checkpoint(step_number):+ save_adapter(params, out / f"{name}.step-{step_number}.safetensors",+ rank=args.rank, dialect=args.dialect, trigger=args.trigger)+ (out / "progress.json").write_text(json.dumps(+ {"step": step_number, "history": history, "name": name}, indent=2))++ for step in range(1, args.steps + 1):+ factor = min(1, step / 50) * (0.2 + 0.8 * 0.5 * (+ 1 + math.cos(math.pi * min(step, args.sched_steps) / args.sched_steps)))+ optimizer.learning_rate = args.lr * factor+ total, accumulated = 0.0, None+ for _ in range(args.accumulation):+ pool = groups["artist"] if (rng.random() < args.artist_fraction+ or not groups["minted"]) else groups["minted"]+ ids, prefix_len = ids_of(rng.choice(pool), rng)+ loss, grads = value_and_grad(params, ids, prefix_len)+ total += float(loss) / args.accumulation+ scaled = {k: {n: v / args.accumulation for n, v in pair.items()}+ for k, pair in grads.items()}+ accumulated = scaled if accumulated is None else {+ k: {n: accumulated[k][n] + v for n, v in pair.items()}+ for k, pair in scaled.items()}+ mx.eval(accumulated)+ flat = [v for pair in accumulated.values() for v in pair.values()]+ norm = mx.sqrt(sum(mx.sum(g.astype(mx.float32) ** 2) for g in flat))+ scale = mx.minimum(mx.array(1.0), 1.0 / (norm + 1e-6))+ accumulated = {k: {n: v * scale for n, v in pair.items()}+ for k, pair in accumulated.items()}+ params = optimizer.apply_gradients(accumulated, params)+ mx.eval(params, optimizer.state)+ if step <= 3 or step % 10 == 0:+ say(f"step {step} loss {total:.3f} len {ids.shape[0]} "+ f"{time.time() - started:.0f}s peak {mx.get_peak_memory() / 2 ** 30:.2f}G")+ if step % args.eval_every == 0 or step == args.steps:+ scores = evaluate()+ history.append({"step": step, **scores})+ say(f"EVAL step {step} " + " ".join(f"{k} {v:.3f}" for k, v in scores.items())+ + f" {time.time() - started:.0f}s")+ if step % args.save_every == 0 or step == args.steps:+ checkpoint(step)+ if deadline and time.time() > deadline:+ say(f"BUDGET reached at step {step}")+ history.append({"step": step, **evaluate()})+ checkpoint(step)+ break++ final = out / f"{name}.safetensors"+ save_adapter(params, final, rank=args.rank, dialect=args.dialect, trigger=args.trigger)+ metrics = {"history": history, "final": history[-1] if history else {},+ "minutes": round((time.time() - started) / 60, 1)}+ meta = sidecar_metadata(+ name=name, trigger=args.trigger, dialect=args.dialect, cot=args.cot, style=style,+ model_dir=args.model_dir, steps=step, rank=args.rank, lr=args.lr,+ window_seconds=args.window_seconds, hop_seconds=args.hop_seconds,+ windows=windows, skipped=skipped, fingerprint=fingerprint, metrics=metrics,+ seed=args.seed, artist_fraction=args.artist_fraction)+ final.with_suffix(".json").write_text(json.dumps(meta, indent=2))+ say(f"SAVED {final} ({final.stat().st_size / 1e6:.1f} MB)")++ if args.install:+ user = Path(args.lora_dir) / "user"+ user.mkdir(parents=True, exist_ok=True)+ shutil.copy2(final, user / final.name)+ shutil.copy2(final.with_suffix(".json"), user / f"{name}.json")+ say(f"INSTALLED {user / final.name}")+ say("TRAIN DONE")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/pinokio/README.md b/scripts/pinokio/README.mdindex d7b1e80..f3b9f6e 100644--- a/scripts/pinokio/README.md+++ b/scripts/pinokio/README.md@@ -82,3 +82,4 @@ Anything bigger belongs here, behind one short `bash …` line.| `mflux_pack.sh` | `install_qwen.js` | the image-engine pack (Ideogram 4 + Qwen-Edit) || `h3_preflight.sh` | `install_h3.js` | Hailuo H3 disk/RAM preflight || `h3_build_q8.sh` | `install_h3.js` | the H3 q8 DiT build |+| `a2v_stems_deps.sh` | nothing yet — run by hand with the `ltx-2-mlx` path | the OPTIONAL stems extra (demucs, torch-based) for the engine venv. A2V conditions the mouth on a separated vocal and the panel muxes the original song back; without it the panel degrades to the full mix and says so, so a queued job never fails on a missing download |diff --git a/scripts/pinokio/a2v_stems_deps.sh b/scripts/pinokio/a2v_stems_deps.shnew file mode 100755index 0000000..53e3af5--- /dev/null+++ b/scripts/pinokio/a2v_stems_deps.sh@@ -0,0 +1,80 @@+#!/usr/bin/env bash+# The STEMS extra for the engine venv — what a vocal-stem-conditioned A2V+# render needs and an ordinary render does not.+#+# WHY IT IS OPTIONAL. A2V drives a mouth from a waveform, and the waveform it+# is given is normally the whole record. Drums, bass and guitar reach the audio+# encoder as energy that can be read as syllables, so the model hedges: the+# mouth moves a little, all the time, on everything. Conditioning on a+# SEPARATED VOCAL removes that noise (the panel muxes the original song back+# over the finished clip, so nothing the audience hears changes). Measured on+# one shot at one seed, that swap was the difference between a mouth whose+# movement tracked the voice and one that did not — and it doubled how much+# the mouth moved at all.+#+# It is an extra rather than a dependency because it drags torch and+# torchaudio in (~2.5 GB) for a lane most renders never take, and because a+# queued job must never fail on a missing optional download — the panel+# degrades to the full mix and says so.+#+# WHERE IT GOES: the engine venv's own bin, which is the FIRST place+# `mlx_ltx_panel._resolve_demucs()` looks. Nothing else on the Mac counts — a+# demucs living in some other project's virtualenv is not a dependency of+# Phosphene and must never become one by accident.+#+# Usage: a2v_stems_deps.sh <path to the ltx-2-mlx checkout>+set -euo pipefail++MLX_CHECKOUT="$(cd "${1:?ltx-2-mlx checkout required}" && pwd)"++# The venv the panel spawns its helper from, in the two layouts that exist.+VENV=""+for cand in "$MLX_CHECKOUT/.venv" "$MLX_CHECKOUT/env"; do+ if [ -x "$cand/bin/python3.11" ] || [ -x "$cand/bin/python" ]; then+ VENV="$cand"+ break+ fi+done+if [ -z "$VENV" ]; then+ echo "no engine venv under $MLX_CHECKOUT (looked for .venv/ and env/)" >&2+ echo "run the engine install first, then this script" >&2+ exit 1+fi++PY="$VENV/bin/python3.11"+[ -x "$PY" ] || PY="$VENV/bin/python"++# Already there? Say so and stop — this script is run from a sidebar button+# and a second click must not spend ten minutes re-resolving torch.+if [ -x "$VENV/bin/demucs" ]; then+ echo "demucs is already installed at $VENV/bin/demucs"+ "$VENV/bin/demucs" --help >/dev/null 2>&1 \+ && echo "it runs" \+ || echo "WARNING: it does not run — reinstall with --force-reinstall" >&2+ exit 0+fi++# demucs pulls torch + torchaudio. Installed BY NAME, not pinned here: the+# engine's own constraints file is the version authority on this machine, the+# same rule music_cover_deps.sh follows for the transcription extra.+CONSTRAINTS=""+for cand in "$MLX_CHECKOUT/../pip-build-constraints.txt" \+ "$MLX_CHECKOUT/pip-build-constraints.txt"; do+ [ -f "$cand" ] && { CONSTRAINTS="$cand"; break; }+done++if [ -n "$CONSTRAINTS" ]; then+ "$PY" -m pip install --upgrade --constraint "$CONSTRAINTS" demucs+else+ "$PY" -m pip install --upgrade demucs+fi++# Prove it, rather than trusting pip's exit code: the panel resolves an+# executable, so an install that produced a library and no console script is+# an install that has not happened as far as A2V is concerned.+if [ ! -x "$VENV/bin/demucs" ]; then+ echo "pip finished but $VENV/bin/demucs is not there" >&2+ exit 1+fi+"$VENV/bin/demucs" --help >/dev/null+echo "demucs installed at $VENV/bin/demucs"diff --git a/scripts/pinokio/h3_build_q8.sh b/scripts/pinokio/h3_build_q8.shindex c053ff5..2dc6799 100644--- a/scripts/pinokio/h3_build_q8.sh+++ b/scripts/pinokio/h3_build_q8.sh@@ -140,17 +140,39 @@ except Exception:sys.exit(1)PY}+# THE HOLD, AND WHY WAITING WAS NOT ENOUGH (Codex H3-02, 2026-09-24). Waiting+# for the current job did nothing about the NEXT one: the panel kept taking+# jobs, so a render queued after the idle check ran beside the ~20 GB load it+# was supposed to avoid. So before anything waits or loads, this build writes+# $STATE_DIR/h3_build.lock (pid + start time); the panel's worker starts no+# new job while it is live (_external_build_hold() in mlx_ltx_panel.py), and+# the trap removes it however the build ends. Order matters: hold first, then+# wait for the job already running. A lock whose pid is gone, or which is+# older than four hours, is ignored by the panel.+HOLD="$STATE_DIR/h3_build.lock"+hold_panel() {+ mkdir -p "$STATE_DIR" 2>/dev/null+ printf '{"pid": %d, "ts": %d, "what": "the Hailuo H3 compact-engine build"}\n' \+ "$$" "$(date +%s)" > "$HOLD" 2>/dev/null \+ || echo 'WARN: could not tell the panel to hold new renders during the build.'+}+trap 'rm -f "$HOLD"' EXITwait_for_idle_panel() {+ hold_panelWAITED=0while panel_rendering; doif [ "$WAITED" -eq 0 ]; thenecho 'A Phosphene render is running. Waiting for it to finish before'echo 'loading the compact engine (it needs ~20 GB of memory briefly).'+ echo 'The panel starts no new render until the build is done.'fiWAITED=$((WAITED + 1))if [ "$WAITED" -ge 120 ]; then- echo 'Still rendering after 60 minutes - continuing anyway.'- break+ # Not "continuing anyway": loading ~20 GB beside a render is exactly+ # what this wait exists to prevent. Nothing built is lost.+ echo 'Still rendering after 60 minutes - not loading the compact engine'+ echo 'on top of it. Run this again when the render has finished.'+ exit 1fisleep 30donediff --git a/scripts/pinokio/h3_roots.sh b/scripts/pinokio/h3_roots.shnew file mode 100644index 0000000..02ab815--- /dev/null+++ b/scripts/pinokio/h3_roots.sh@@ -0,0 +1,72 @@+# shellcheck shell=bash+# Resolve the Hailuo H3 checkout and weights roots EXACTLY as the panel does.+# SOURCE it (`. scripts/pinokio/h3_roots.sh`) from the app root; every+# install_h3.js step does, because Pinokio runs each message element in its own+# shell and nothing exported in one survives to the next.+#+# WHY IT EXISTS (Codex INST-09, 2026-09-24). The panel honours LTX_H3_ROOT and+# LTX_H3_MODELS (mlx_ltx_panel.py H3_ROOT / H3_MODELS) and so does the sidebar+# (pinokio.js h3Path) — docs/H3_ENGINE.md recommends them for sharing one 75 GB+# tree between installs. install_h3.js did not: it cloned, installed and+# downloaded into the literal default paths, so "Repair Hailuo H3" repaired a+# second checkout the panel never uses and could pull ~75 GB of duplicate+# weights, while the engine the menu had diagnosed stayed broken.+#+# Semantics match the panel: unset = the default under the app root; a+# relative value is relative to the app root (the panel's cwd); an absolute+# one is used as-is. Spaces are fine — every consumer quotes these.+#+# Exports: APP_ROOT H3_CHECKOUT H3_MODELS_ROOT H3_LAYOUT H3_FLAT LTX_H3_MODELS+# H3_LAYOUT where the component dirs live: <root>/models (what upstream's+# download_selected.py --root writes) or <root> itself for the+# flat tree the panel also accepts (_h3_model_roots()).+# H3_FLAT 1 when an existing flat tree was found — the downloader cannot+# write that layout, so the install leaves it alone rather than+# duplicating it under models/.+APP_ROOT="$(pwd)"+_h3_abs() { case "$1" in /*) printf '%s' "$1" ;; *) printf '%s/%s' "$APP_ROOT" "$1" ;; esac; }+H3_CHECKOUT="$(_h3_abs "${LTX_H3_ROOT:-minimax-h3-mlx}")"+H3_MODELS_ROOT="$(_h3_abs "${LTX_H3_MODELS:-mlx_models/hailuo-h3}")"+H3_DIT_REL='deepbeep-pruned-bf16/MiniMax-H3-FL2VA-pruned_bf16.safetensors'+if [ -f "$H3_MODELS_ROOT/$H3_DIT_REL" ] && [ ! -d "$H3_MODELS_ROOT/models" ]; then+ H3_LAYOUT="$H3_MODELS_ROOT"; H3_FLAT=1+else+ H3_LAYOUT="$H3_MODELS_ROOT/models"; H3_FLAT=0+fi+# Absolute from here on, so h3_build_q8.sh (which runs with cwd = the+# checkout) reads the same tree rather than resolving a relative value again.+LTX_H3_MODELS="$H3_MODELS_ROOT"+export APP_ROOT H3_CHECKOUT H3_MODELS_ROOT H3_LAYOUT H3_FLAT LTX_H3_MODELS+echo "H3 checkout: $H3_CHECKOUT"+echo "H3 weights: $H3_MODELS_ROOT"++# What a FLAT tree still lacks, one relative path per line ("" = complete).+# Same three things the panel's h3_paths() requires. The downloader cannot+# write a flat tree, so an incomplete one has to be SAID, not skipped: before+# this, Install/Repair printed "not downloading" over a tree missing its VAE+# and H3 stayed unavailable no matter how often it was clicked (Codex, 4.16.0).+h3_flat_missing() {+ local c="${LTX_H3_COMPACT_DIR:-ddalcu-q8}" f+ [ -f "$H3_MODELS_ROOT/$H3_DIT_REL" ] || echo "$H3_DIT_REL"+ for f in text_encoder.safetensors video_vae.safetensors audio_vae.safetensors; do+ [ -f "$H3_MODELS_ROOT/$c/$f" ] || [ -f "$H3_MODELS_ROOT/ddalcu-q8/$f" ] || echo "$c/$f"+ done+ [ -f "$H3_MODELS_ROOT/upstream-meta/FL2VA/text_encoder/config.json" ] \+ || echo "upstream-meta/FL2VA/text_encoder/config.json"+}++# The install's weights step. Run from the H3 checkout (RH3 cds there).+h3_fetch_weights() {+ local m+ if [ "$H3_FLAT" != 1 ]; then+ .venv/bin/python scripts/download_selected.py --root "$H3_MODELS_ROOT"+ return $?+ fi+ m="$(h3_flat_missing)"+ if [ -n "$m" ]; then+ echo "error: the flat H3 weights tree at $H3_MODELS_ROOT is missing:" $m \+ "- complete it, or unset LTX_H3_MODELS so Install can download into its own folder."+ return 1+ fi+ echo 'Flat H3 weights tree complete - nothing to download.'+}diff --git a/scripts/pinokio/h3_venv.sh b/scripts/pinokio/h3_venv.shnew file mode 100755index 0000000..e9c40d1--- /dev/null+++ b/scripts/pinokio/h3_venv.sh@@ -0,0 +1,16 @@+#!/usr/bin/env bash+# The H3 engine's own Python 3.11 venv — self-healing. cwd: the H3 checkout.+# Lifted out of install_h3.js (a 372-char dispatch, above the ~350 Pinokio 8 is+# proven to survive) when that step had to learn the relocated checkout; the+# reasoning for probing the interpreter instead of a path lives above the step+# in install_h3.js.+echo '=== H3 venv check ==='+if .venv/bin/python -c 'import sys' >/dev/null 2>&1; then+ echo 'H3 venv healthy - reusing it'+else+ echo 'H3 venv missing or broken (dangling interpreter) - rebuilding, no weights are re-downloaded'+ which uv && uv --version || echo 'uv NOT FOUND'+ rm -rf .venv+ uv venv --python 3.11 --seed .venv+ .venv/bin/python --version || echo 'venv python NOT executable'+fidiff --git a/scripts/pinokio/music_cover_deps.sh b/scripts/pinokio/music_cover_deps.shnew file mode 100755index 0000000..bc68a92--- /dev/null+++ b/scripts/pinokio/music_cover_deps.sh@@ -0,0 +1,16 @@+#!/usr/bin/env bash+# The transcription extra for the music engine venv — what a COVER needs and a+# prompt-written song does not.+#+# `lyra.transcription` imports mir_eval, mido, pretty_midi and scipy at module+# import time, and `uv sync --frozen --no-dev` (music_sync.sh) installs the base+# dependency set without extras. So a venv built for writing songs raises+# ModuleNotFoundError the moment a cover starts — which is exactly what it did+# the first time this ran end to end. The extra is declared upstream in+# pyproject.toml as [project.optional-dependencies].transcription; install it by+# NAME rather than pinning here, so the engine pin stays the only version+# authority.+set -euo pipefail+MUSIC_CHECKOUT="$(cd "${1:?music checkout required}" && pwd)"+UV_PROJECT_ENVIRONMENT="$MUSIC_CHECKOUT/.venv" \+ uv sync --frozen --no-dev --extra transcription --project "$MUSIC_CHECKOUT"diff --git a/scripts/pinokio/music_cover_fetch.py b/scripts/pinokio/music_cover_fetch.pynew file mode 100644index 0000000..1e1837a--- /dev/null+++ b/scripts/pinokio/music_cover_fetch.py@@ -0,0 +1,157 @@+#!/usr/bin/env python3+"""Fetch the two models that let YuE2 cover a real recording.++Cover is the engine's most interesting mode and the cheapest to add: the+generator and decoder are already here (~10 GB), and listening to a record+costs **2.8 GB more**. SheetSage2 transcribes a mix into an ABC score;+MERT-v2-FullSong is the audio encoder it is a LoRA adapter over, merged on+load. Neither is needed to write a song from a prompt, so neither ships with+the music pack — this is an opt-in second download.++Pinned to the revisions the ENGINE pins (lyra/transcription/model.py), not to+whatever is newest: SheetSage2's config carries the sha256 of the MERT+checkpoint it was trained against and refuses to load beside any other one.+Bump both together with engine_pin.txt or not at all.++Layout, deliberately plain directories rather than an HF cache:++ mlx_models/yue2-cover/sheetsage2/{config.json,model.safetensors}+ mlx_models/yue2-cover/mert2/{config.json,model.safetensors}++`resolve_models()` takes a directory as readily as a repo id, so a plain tree+is offline by construction, checkable with `ls`, and deletable with `rm -rf`.++Both models are CC BY-NC 4.0, the same terms as YuE2 itself.+"""+from __future__ import annotations++import argparse+import json+import os+import shutil+import sys+from pathlib import Path++SOURCES = {+ "sheetsage2": {"repo": "m-a-p/SheetSage2",+ "revision": "eab522a8168e8b8b8c4856bf8609cd86198f01fe"},+ "mert2": {"repo": "m-a-p/MERT-v2-FullSong",+ "revision": "d8ba1c745e733b3908ce6ad16ebeb17ac7600a42"},+}+FILES = ("config.json", "model.safetensors")+EXTRA = ("LICENSE", "THIRD_PARTY_NOTICES.md", "README.md")+COVER_BYTES = 2_800_000_000+++RECEIPT = "pack_source.json"+++def _receipt(root: Path) -> dict | None:+ try:+ return json.loads((root / RECEIPT).read_text(encoding="utf-8"))+ except (OSError, ValueError):+ return None+++def _file_ok(root: Path, rel: str, receipt: dict | None) -> bool:+ """A weight file counts only when the receipt vouches for it.++ "Nonzero size" was the whole check, so a copy cut short by a crash, a full+ disk or an unplugged drive left a truncated checkpoint that readiness+ accepted, a retry skipped and the in-panel installer reported "ready"+ (Codex INST-10). The receipt is written only after every file landed, and+ records each one's size. A receipt from before sizes were recorded still+ vouches for files that are present — those installs finished."""+ f = root / rel+ if receipt is None or not f.is_file() or f.stat().st_size == 0:+ return False+ want = (receipt.get("bytes") or {}).get(rel)+ return want is None or f.stat().st_size == int(want)+++def part_problems(root: Path, part: str) -> list[str]:+ receipt = _receipt(root)+ return [f"{part}/{name}" for name in FILES+ if not _file_ok(root, f"{part}/{name}", receipt)]+++def cover_problems(root: Path) -> list[str]:+ """Empty when a cover is possible. The panel's install card reads this."""+ out: list[str] = []+ for part in SOURCES:+ out += part_problems(root, part)+ return out+++def fetch(root: Path, *, min_free_gb: float = 6.0) -> None:+ from huggingface_hub import hf_hub_download++ root.mkdir(parents=True, exist_ok=True)+ free = shutil.disk_usage(root).free / 1e9+ if free < min_free_gb:+ raise SystemExit(f"[cover] only {free:.1f} GB free; need about {min_free_gb:g} GB")+ receipt = _receipt(root)+ sizes: dict[str, int] = {}+ for part, src in SOURCES.items():+ target = root / part+ target.mkdir(parents=True, exist_ok=True)+ # The two weight files are what the loader reads. The licence and+ # notices ride along because we are keeping a copy of someone else's+ # model on a user's disk, and the terms belong next to it.+ for name in FILES + EXTRA:+ dest = target / name+ rel = f"{part}/{name}"+ if _file_ok(root, rel, receipt):+ print(f"[cover] have {rel}", flush=True)+ if name in FILES:+ sizes[rel] = dest.stat().st_size+ continue+ try:+ staged = hf_hub_download(repo_id=src["repo"], revision=src["revision"],+ filename=name)+ except Exception as exc: # noqa: BLE001+ if name in EXTRA:+ continue # a missing notice is not a failed install+ raise SystemExit(f"[cover] could not fetch {part}/{name}: {exc}") from exc+ dest.parent.mkdir(parents=True, exist_ok=True)+ # Sibling temp file, size-checked, then an atomic rename: the final+ # name only ever holds a complete copy (INST-10).+ part_file = dest.with_name(dest.name + ".part")+ shutil.copyfile(staged, part_file)+ if part_file.stat().st_size != Path(staged).stat().st_size:+ part_file.unlink(missing_ok=True)+ raise SystemExit(f"[cover] short copy of {rel}; run it again")+ os.replace(part_file, dest)+ if name in FILES:+ sizes[rel] = dest.stat().st_size+ print(f"[cover] wrote {rel} "+ f"({dest.stat().st_size / 1e6:.1f} MB)", flush=True)+ tmp = root / (RECEIPT + ".tmp")+ tmp.write_text(json.dumps(+ {"sources": SOURCES, "files": list(FILES), "bytes": sizes,+ "license": "CC BY-NC 4.0",+ "purpose": "YuE2 cover: transcribe a recording into an ABC score"},+ indent=2), encoding="utf-8")+ os.replace(tmp, root / RECEIPT)+ missing = cover_problems(root)+ if missing:+ raise SystemExit(f"[cover] incomplete after fetch: {', '.join(missing)}")+ print("[cover] ready", flush=True)+++def main(argv=None) -> int:+ ap = argparse.ArgumentParser(description=__doc__)+ ap.add_argument("--root", type=Path, required=True)+ ap.add_argument("--min-free-gb", type=float, default=6.0)+ ap.add_argument("--check", action="store_true", help="report readiness and exit")+ args = ap.parse_args(argv)+ if args.check:+ missing = cover_problems(args.root)+ print(json.dumps({"ready": not missing, "missing": missing}))+ return 0 if not missing else 1+ fetch(args.root, min_free_gb=args.min_free_gb)+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/pinokio/music_lora_fetch.py b/scripts/pinokio/music_lora_fetch.pynew file mode 100644index 0000000..4b33cdf--- /dev/null+++ b/scripts/pinokio/music_lora_fetch.py@@ -0,0 +1,491 @@+#!/usr/bin/env python3+"""Fetch the YuE2 LoRA pack — and own what "a LoRA the studio can pick" means.++Two adapters, ~210 MB together, pinned by revision and checked by SHA-256:++ mlx_models/yue2-loras/ar_lora_inst_v3abc.bf16.safetensors 139.5 MB+ mlx_models/yue2-loras/nar_lora_joint_v9.bf16.safetensors 70.3 MB+ mlx_models/yue2-loras/user/*.safetensors whatever you drop in++The first is Mothersuperior's instrumental AR adapter: the one thing that+turns Phosphene's Instrumental toggle from a prompt trick into the same+mechanism Maestro uses. The second is the acoustic-branch adapter from the+real-audio tokenizer pack, kept because it is the one published NAR LoRA we+can verify against — it is trained beside a tokenizer head we have not ported+yet (phase 2), so it is offered as an experiment, not as a recommendation.++Plus, in its own subdirectory so the LoRA picker never offers it as an+adapter, the real-audio TOKENIZER HEAD:++ mlx_models/yue2-loras/tokenizer/tokenizer_head_joint_v9.bf16.safetensors 85.6 MB+ mlx_models/yue2-loras/tokenizer/sem_nbr_cos.npy 2.1 MB+ mlx_models/yue2-loras/tokenizer/sem_nbr_idx.npy 2.1 MB++The head turns a REAL recording into YuE2 semantic codes (MERT-v2-FullSong+layer-20 features at 25 Hz in, 32768-way codes out) — the thing that makes+`nar_lora_joint_v9` worth having, and the thing that makes an audio prompt+possible. `scripts/music/yue2_tokenizer.py` is the MLX port that runs it. The+two `sem_nbr_*` tables are the TRAINING-side semantic-neighbour lookups (8+neighbours per code); inference never reads them, they are pinned here so a+future training port does not have to re-derive their provenance, and they are+not required for readiness.++Deliberately plain directories, like the cover pack: readable with `ls`,+deletable with `rm -rf`, offline by construction. `user/` is scanned for any+`*.safetensors`, so a community or AI-Toolkit adapter is usable the moment it+is copied in — no registry, no install step. The head lives under `tokenizer/`+precisely because `pack_adapters()` globs only the root and `user/`.++This module is STDLIB ONLY apart from `huggingface_hub` inside `fetch()`: the+panel imports it at boot to list what the picker offers, and the panel must+not pull MLX or numpy onto that path.++Both adapters are CC BY-NC 4.0, the same terms as YuE2 itself.+"""+from __future__ import annotations++import argparse+import hashlib+import json+import os+from pathlib import Path+import shutil+import sys++SOURCES = {+ "ar_lora_inst_v3abc.bf16.safetensors": {+ "repo": "Mothersuperior/YuE2-instrumental-cot-full-loras",+ "revision": "947f2f4b28978b2b6c3e316e6a87925c76bf3c4b",+ "sha256": "e408fd3148b75b1165f7ddbf63db575d83bb6402a0b5f876fcb767dbcb2c5414",+ "bytes": 139_502_088,+ },+ "nar_lora_joint_v9.bf16.safetensors": {+ "repo": "Mothersuperior/yue2-mothersuperior-realaudio-tokenizer-v4",+ "revision": "e2e63d859f3af879baf1b4d4e9f22d1eeda6fde5",+ "sha256": "ce57f98e9e0e65c724c2a00aa23dea2568952590504a428c588d82f00bc61c55",+ "bytes": 70_301_896,+ },+}+#: The real-audio tokenizer head and its training-side lookup tables. Same repo+#: and revision as the acoustic adapter it was trained beside. `remote` is the+#: path inside the repository; the key is the name on disk.+HEAD_SOURCES = {+ "tokenizer_head_joint_v9.bf16.safetensors": {+ "repo": "Mothersuperior/yue2-mothersuperior-realaudio-tokenizer-v4",+ "revision": "e2e63d859f3af879baf1b4d4e9f22d1eeda6fde5",+ "remote": "tokenizer_head_joint_v9.bf16.safetensors",+ "sha256": "cffb673cd663517c8978ba73d186a87517958025f7e409371ea56df3bb364db2",+ "bytes": 85_644_856,+ "required": True,+ },+ "sem_nbr_cos.npy": {+ "repo": "Mothersuperior/yue2-mothersuperior-realaudio-tokenizer-v4",+ "revision": "e2e63d859f3af879baf1b4d4e9f22d1eeda6fde5",+ "remote": "assets/sem_nbr_cos.npy",+ "sha256": "cf544760a9ef2f66b0bba4fa6ac3d055c628fc109cea47ba9bc6de59c767ad12",+ "bytes": 2_097_280,+ "required": False,+ },+ "sem_nbr_idx.npy": {+ "repo": "Mothersuperior/yue2-mothersuperior-realaudio-tokenizer-v4",+ "revision": "e2e63d859f3af879baf1b4d4e9f22d1eeda6fde5",+ "remote": "assets/sem_nbr_idx.npy",+ "sha256": "081d5f3d41ac2b604ee95db53f5c2069b33d871c317b611d7df8e02b42eda141",+ "bytes": 2_097_280,+ "required": False,+ },+}+INSTRUMENTAL_ADAPTER = "ar_lora_inst_v3abc.bf16.safetensors"+JOINT_NAR_ADAPTER = "nar_lora_joint_v9.bf16.safetensors"+TOKENIZER_HEAD = "tokenizer_head_joint_v9.bf16.safetensors"+USER_SUBDIR = "user"+HEAD_SUBDIR = "tokenizer"+LORA_BYTES = sum(entry["bytes"] for entry in SOURCES.values())+HEAD_BYTES = sum(entry["bytes"] for entry in HEAD_SOURCES.values())+MAX_STRENGTH = 1.5++NOTICE = """YuE2 LoRA pack — third-party weights+====================================++ar_lora_inst_v3abc.bf16.safetensors+ Mothersuperior/YuE2-instrumental-cot-full-loras+ revision 947f2f4b28978b2b6c3e316e6a87925c76bf3c4b+ An AR-branch LoRA (rank 64) for instrumental generation with full score+ planning. Applied at strength 1.0 by Phosphene's Instrumental toggle.++nar_lora_joint_v9.bf16.safetensors+ Mothersuperior/yue2-mothersuperior-realaudio-tokenizer-v4+ revision e2e63d859f3af879baf1b4d4e9f22d1eeda6fde5+ An acoustic-branch LoRA (rank 32) trained jointly with the real-audio+ tokenizer head `tokenizer_head_joint_v9`, which Phosphene has NOT ported.+ The file also carries complete vae2llm / llm2vae decoder projections;+ Phosphene's `joint` mode ignores them, as Maestro's does.++Both files are licensed CC BY-NC 4.0 (Creative Commons Attribution-+NonCommercial 4.0 International), the same terms as YuE2 itself+(m-a-p/YuE2-3B). Non-commercial use only. Neither file is redistributed by+Phosphene: this script downloads them from Hugging Face on request.++tokenizer/tokenizer_head_joint_v9.bf16.safetensors+tokenizer/sem_nbr_cos.npy+tokenizer/sem_nbr_idx.npy+ Mothersuperior/yue2-mothersuperior-realaudio-tokenizer-v4+ revision e2e63d859f3af879baf1b4d4e9f22d1eeda6fde5+ The real-audio tokenizer head trained jointly with nar_lora_joint_v9: an+ 8-layer transformer encoder that turns MERT-v2-FullSong layer-20 features+ at 25 Hz into YuE2 semantic codes. The two sem_nbr_*.npy tables are the+ training-side semantic-neighbour lookups (assets/ in the repository);+ inference does not read them.++Anything under user/ is yours and is never touched by an update or a repair.+"""+++# ------------------------------------------------------------------ the pack++def part_problems(root: Path, name: str, source: dict | None = None,+ *, deep: bool = False) -> list[str]:+ """Empty when the file on disk is the file that was pinned.++ A NAME IS NOT A FILE (Codex review, 2026-09-22). Any non-empty file used+ to count, so a download that dropped halfway through left a truncated+ adapter that read as ready forever: the card said so, the Download button+ did nothing, and the first song that picked it failed to load it.++ Cheap by default - presence and exact size - because the panel asks this+ on every status poll and hashing 300 MB every few seconds is not a thing a+ UI may do. The hash is not skipped, it is moved: `_download` verifies it+ before a file is ever given its pinned name, so on-disk size is a+ sufficient gate afterwards. `deep=True` hashes anyway, which is what+ `--check --deep` is for.+ """+ path = Path(root) / name+ try:+ size = path.stat().st_size+ except OSError:+ return [name]+ if not path.is_file() or size == 0:+ return [name]+ if source is not None:+ if size != int(source["bytes"]):+ return [name]+ if deep and sha256_of(path) != source["sha256"]:+ return [name]+ return []+++def lora_problems(root: Path, *, deep: bool = False) -> list[str]:+ """Empty when the two pinned ADAPTERS are usable — which is what the+ studio's picker needs and all it needs. Not the same question as "is the+ whole pack here": see `pack_problems`."""+ out: list[str] = []+ for name, source in SOURCES.items():+ out += part_problems(Path(root), name, source, deep=deep)+ return out+++def head_root(root) -> Path:+ """Where the tokenizer head lives — never the adapter root itself."""+ return Path(root).expanduser() / HEAD_SUBDIR+++def head_path(root) -> Path:+ return head_root(root) / TOKENIZER_HEAD+++def head_problems(root, *, deep: bool = False) -> list[str]:+ """Empty when the tokenizer head is usable. Optional assets are not gates."""+ out: list[str] = []+ for name, source in HEAD_SOURCES.items():+ if source["required"]:+ out += part_problems(head_root(root), name, source, deep=deep)+ return out+++def pack_problems(root, *, deep: bool = False) -> list[str]:+ """Empty when there is NOTHING LEFT TO DOWNLOAD — adapters and head.++ The second of the two readiness questions, and the one the fetch endpoint+ has to ask. It used to ask the first: both adapter names present meant+ "ready", so a pack whose tokenizer-head download was interrupted could+ never be completed from the UI (Codex review, 2026-09-22).+ """+ return lora_problems(root, deep=deep) + [+ f"{HEAD_SUBDIR}/{name}" for name in head_problems(root, deep=deep)]+++_LABELS = {+ INSTRUMENTAL_ADAPTER: ("Instrumental", "ar",+ "Mothersuperior's instrumental AR adapter — the one the "+ "Instrumental toggle uses"),+ JOINT_NAR_ADAPTER: ("Real-audio sound v9", "nar",+ "Experimental: an acoustic adapter trained beside a tokenizer "+ "head Phosphene has not ported yet"),+}+++def adapter_meta(path) -> dict:+ """What a trained adapter's own sidecar says about how to USE it.++ `yue2_train_voice.py --install` puts `<name>.json` beside+ `<name>.safetensors`; it names the training `trigger` and the `dialect`+ (`direct`: generate with no score; `score`: generate with one). The picker+ used to derive everything from the filename, so a trained voice was+ offered as usable and then rendered without its trigger and under the+ wrong conditioning (M6-04). An adapter with no sidecar says nothing."""+ p = Path(path)+ side = p.with_name(p.name[: -len(".safetensors")] + ".json") \+ if p.name.lower().endswith(".safetensors") else p.with_suffix(".json")+ try:+ data = json.loads(side.read_text(encoding="utf-8"))+ except (OSError, ValueError):+ return {}+ if not isinstance(data, dict):+ return {}+ out = {}+ trigger = str(data.get("trigger") or "").strip()+ if trigger:+ out["trigger"] = trigger+ dialect = str(data.get("dialect") or "").strip()+ if dialect in ("direct", "score"):+ out["dialect"] = dialect+ return out+++def _entry(path: Path, root: Path, *, builtin: bool) -> dict:+ label, branch, note = _LABELS.get(+ path.name,+ (path.stem.replace("_", " ").strip(),+ "nar" if "nar" in path.name.lower() else "ar", ""))+ meta = {} if builtin else adapter_meta(path)+ if meta:+ bits = []+ if meta.get("trigger"):+ bits.append(f"trigger “{meta['trigger']}” is added for you")+ if meta.get("dialect") == "direct":+ bits.append("trained without a score — use Score: No score")+ elif meta.get("dialect") == "score":+ bits.append("trained with a score — use Melody or Melody + chords")+ note = " · ".join(filter(None, [note] + bits))+ return {"id": str(path.relative_to(root)), "file": path.name, "name": label,+ "note": note, "builtin": builtin, "branch": branch,+ "bytes": path.stat().st_size,+ "instrumental": path.name == INSTRUMENTAL_ADAPTER, **meta}+++def pack_adapters(root) -> list[dict]:+ """Every adapter the picker offers: the pinned pack, then the user folder."""+ root = Path(root).expanduser()+ if not root.is_dir():+ return []+ # A pinned adapter is offered only when it is the pinned FILE; a truncated+ # download must not sit in the picker waiting to fail a render. Nothing is+ # pinned about `user/`, so anything non-empty there is the owner's to try.+ found = [_entry(path, root, builtin=True)+ for path in sorted(root.glob("*.safetensors"))+ if not part_problems(root, path.name, SOURCES.get(path.name))]+ user = root / USER_SUBDIR+ if user.is_dir():+ found += [_entry(path, root, builtin=False)+ for path in sorted(user.rglob("*.safetensors"))]+ return found+++def resolve_in_pack(root, identifier: str) -> Path:+ """A picker id → a real file, refusing anything outside the LoRA folder."""+ root = Path(root).expanduser().resolve()+ candidate = (root / str(identifier)).resolve()+ if not candidate.is_relative_to(root):+ raise ValueError("A LoRA has to come from the music LoRA folder")+ if not candidate.is_file() or candidate.suffix.lower() != ".safetensors":+ raise FileNotFoundError(f"No LoRA named {identifier!r} in {root}")+ return candidate+++def validate_strength(value) -> float:+ try:+ strength = float(value)+ except (TypeError, ValueError) as error:+ raise ValueError("A LoRA strength must be a number") from error+ if not 0.0 <= strength <= MAX_STRENGTH:+ raise ValueError(f"A LoRA strength must be between 0 and {MAX_STRENGTH:g}, "+ f"not {strength}")+ return strength+++def parse_spec(spec: str) -> tuple[str, float]:+ """`path[:strength]` — split only when the tail really is a number, so a+ path that happens to contain a colon still resolves."""+ text = str(spec).strip()+ head, sep, tail = text.rpartition(":")+ if sep and head:+ try:+ return head, validate_strength(tail)+ except ValueError:+ pass+ return text, 1.0+++def _items_from_text(raw) -> list:+ """One piece of TEXT -> the specs inside it. `a:0.8,b:1.2` or a JSON list."""+ text = str(raw or "").strip()+ if not text:+ return []+ if text.startswith("["):+ try:+ loaded = json.loads(text)+ except ValueError:+ return []+ return loaded if isinstance(loaded, list) else []+ return [part for part in text.split(",") if part.strip()]+++def _picks_from_items(items) -> list[tuple[str, float]]:+ picks: list[tuple[str, float]] = []+ for item in items:+ if isinstance(item, dict):+ identifier = str(item.get("id") or "").strip()+ strength = item.get("strength", 1.0)+ elif isinstance(item, (list, tuple)):+ picks += _picks_from_items(item)+ continue+ else:+ identifier, strength = parse_spec(item)+ if not identifier:+ continue+ try:+ picks.append((identifier, validate_strength(strength)))+ except ValueError:+ continue+ return picks+++def parse_picks(raw) -> list[tuple[str, float]]:+ """A NORMALISED selection: one `id:strength,id:strength` string, a JSON+ list, or a list whose every element is ONE spec (a string or a dict).++ This is the shape a job's saved params carry, because `music_params` has+ already resolved them once. It is NOT the shape a browser posts — see+ `parse_field`."""+ if isinstance(raw, dict):+ return _picks_from_items([raw])+ if isinstance(raw, (list, tuple)):+ return _picks_from_items(raw)+ return _picks_from_items(_items_from_text(raw))+++def parse_field(raw) -> list[tuple[str, float]]:+ """A FORM FIELD, as `parse_qs` hands it over.++ THE DIFFERENCE IS THE BUG (Codex review, 2026-09-22). `parse_qs` returns a+ list with one element PER REPEAT of the field, and the studio repeats+ nothing: it joins the whole selection into a single value, so two picked+ adapters arrive as `["a.safetensors:0.8,b.safetensors:1.2"]`. Read as a+ normalised list, that one element is one spec — a filename with a comma in+ it, which resolves to nothing, so picking two voices silently turned both+ of them off and picking one worked. Every value of the field is therefore+ split here, and only an element that is already normalised (a dict, or a+ nested list) is passed through untouched."""+ values = list(raw) if isinstance(raw, (list, tuple)) else [raw]+ picks: list[tuple[str, float]] = []+ for value in values:+ if isinstance(value, (dict, list, tuple)):+ picks += parse_picks(value)+ else:+ picks += _picks_from_items(_items_from_text(value))+ return picks+++# --------------------------------------------------------------- downloading++def sha256_of(path: Path) -> str:+ digest = hashlib.sha256()+ with Path(path).open("rb") as handle:+ for block in iter(lambda: handle.read(1 << 20), b""):+ digest.update(block)+ return digest.hexdigest()+++def _download(sources: dict, destination: Path, label: str) -> None:+ from huggingface_hub import hf_hub_download++ destination.mkdir(parents=True, exist_ok=True)+ for name, source in sources.items():+ dest = destination / name+ if not part_problems(destination, name, source, deep=True):+ print(f"[{label}] have {name}", flush=True)+ continue+ if dest.exists():+ print(f"[{label}] {name} is damaged or unfinished — fetching it again",+ flush=True)+ try:+ staged = hf_hub_download(repo_id=source["repo"], revision=source["revision"],+ filename=source.get("remote", name))+ except Exception as exc: # noqa: BLE001+ raise SystemExit(f"[{label}] could not fetch {name}: {exc}") from exc+ # ATOMIC. The pinned name is given to a file only after that file has+ # passed its checksum, so an interrupted copy leaves a `.partial` to+ # throw away and never a plausible-looking adapter (Codex review,+ # 2026-09-22). `os.replace` is atomic within a filesystem, and the+ # temp file is a sibling so it always is one.+ tmp = dest.with_name(f"{dest.name}.{os.getpid()}.partial")+ try:+ shutil.copyfile(staged, tmp)+ digest = sha256_of(tmp)+ if digest != source["sha256"]:+ raise SystemExit(f"[{label}] {name} failed its checksum "+ f"({digest} != {source['sha256']})")+ os.replace(tmp, dest)+ finally:+ Path(tmp).unlink(missing_ok=True)+ print(f"[{label}] wrote {name} ({dest.stat().st_size / 1e6:.1f} MB)", flush=True)+++def fetch(root: Path, *, min_free_gb: float = 1.0, include_head: bool = True) -> None:+ root = Path(root)+ root.mkdir(parents=True, exist_ok=True)+ (root / USER_SUBDIR).mkdir(exist_ok=True)+ free = shutil.disk_usage(root).free / 1e9+ if free < min_free_gb:+ raise SystemExit(f"[music-lora] only {free:.1f} GB free; need about {min_free_gb:g} GB")+ _download(SOURCES, root, "music-lora")+ if include_head:+ _download(HEAD_SOURCES, head_root(root), "music-head")+ (root / "NOTICE").write_text(NOTICE, encoding="utf-8")+ (root / "pack_source.json").write_text(json.dumps(+ {"sources": SOURCES, "tokenizer_head": HEAD_SOURCES, "license": "CC BY-NC 4.0",+ "purpose": "YuE2 LoRA inference: instrumental generation, acoustic adapters "+ "and the real-audio tokenizer head"},+ indent=2), encoding="utf-8")+ missing = lora_problems(root) if not include_head else pack_problems(root)+ if missing:+ raise SystemExit(f"[music-lora] incomplete after fetch: {', '.join(missing)}")+ print("[music-lora] ready", flush=True)+++def main(argv=None) -> int:+ ap = argparse.ArgumentParser(description=__doc__)+ ap.add_argument("--root", type=Path, required=True)+ ap.add_argument("--min-free-gb", type=float, default=1.0)+ ap.add_argument("--check", action="store_true", help="report readiness and exit")+ ap.add_argument("--deep", action="store_true",+ help="with --check: hash every pinned file, not just size it")+ ap.add_argument("--no-head", action="store_true",+ help="adapters only; skip the real-audio tokenizer head")+ args = ap.parse_args(argv)+ if args.check:+ deep = bool(args.deep)+ missing = lora_problems(args.root, deep=deep)+ head_missing = head_problems(args.root, deep=deep)+ print(json.dumps({"ready": not missing, "missing": missing,+ "head_ready": not head_missing, "head_missing": head_missing,+ "complete": not (missing or head_missing),+ "head": str(head_path(args.root)),+ "adapters": pack_adapters(args.root)}, indent=2))+ return 0 if not missing else 1+ fetch(args.root, min_free_gb=args.min_free_gb, include_head=not args.no_head)+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/pinokio/music_sync.sh b/scripts/pinokio/music_sync.shindex 6162bf4..42d4af0 100755--- a/scripts/pinokio/music_sync.sh+++ b/scripts/pinokio/music_sync.sh@@ -5,4 +5,7 @@# engines/yue2/engines/yue2/.venv while everything else uses engines/yue2/.venv.set -euo pipefailMUSIC_CHECKOUT="$(cd "${1:?music checkout required}" && pwd)"-UV_PROJECT_ENVIRONMENT="$MUSIC_CHECKOUT/.venv" uv sync --frozen --no-dev --project "$MUSIC_CHECKOUT"+UV_PROJECT_ENVIRONMENT="$MUSIC_CHECKOUT/.venv" uv sync --frozen --no-dev --extra transcription --project "$MUSIC_CHECKOUT"+# `--extra transcription` on EVERY sync: an exact sync without it removes the+# cover's libraries (mir_eval, mido, pretty_midi) on the next Update while the+# cover models stay on disk and the readiness check keeps saying ready.diff --git a/scripts/pinokio/q8_weights.sh b/scripts/pinokio/q8_weights.shindex 6e7659b..8f0af1b 100644--- a/scripts/pinokio/q8_weights.sh+++ b/scripts/pinokio/q8_weights.sh@@ -42,7 +42,34 @@ esacecho "Fetching $LABEL (pack key: $REPO_KEY)…"PY=./ltx-2-mlx/env/bin/python3.11-if $PY scripts/fetch_pack_release.py --repo-key "$REPO_KEY"; then++# THE TRANSPORT COMES FROM THE REGISTRY, NOT FROM THE KEY. Only the 2.5 packs+# are mirrored as GitHub release assets; LTX-2.3's q8 lives on Hugging Face+# only, and handing its key to the release fetcher failed before a single+# byte moved ("repo 'q8' is not mirrored through a GitHub release") — under a+# banner blaming the network (Codex INST-06, 2026-09-24). An unmirrored pack+# goes through `hf download` with the registry's own --include allowlist, the+# same lane the in-panel Models page uses for it.+fetch_pack() {+ if $PY -c 'import json,sys+r = next(x for x in json.load(open("required_files.json"))["repos"] if x["key"] == sys.argv[1])+sys.exit(0 if (r.get("mirror") or {}).get("kind") == "github-release" else 1)' "$REPO_KEY"+ then+ $PY scripts/fetch_pack_release.py --repo-key "$REPO_KEY"+ return+ fi+ ARGS=()+ while IFS= read -r -d '' a; do ARGS+=("$a"); done < <($PY -c 'import json,sys+r = next(x for x in json.load(open("required_files.json"))["repos"] if x["key"] == sys.argv[1])+out = [r["repo_id"], "--local-dir", r["local_dir"]]+for pat in r.get("download_include") or []:+ out += ["--include", pat]+sys.stdout.write("\0".join(out) + "\0")' "$REPO_KEY")+ [ "${#ARGS[@]}" -gt 0 ] || return 1+ HF_HUB_ENABLE_HF_TRANSFER=1 ./ltx-2-mlx/env/bin/hf download "${ARGS[@]}"+}++if fetch_pack; thenecho "$LABEL ready (verified against the published manifest)."elseecho '=================================================================='@@ -50,7 +77,7 @@ elseecho 'Nothing is broken - this pack is optional. The panel keeps rendering'echo 'on the base weights; trained characters and voices are what need Q8.'echo 'This is almost always a network problem (no connection, a VPN or'- echo "proxy, or GitHub blocked) or a full disk: the pack needs about $SIZE_GB GB."+ echo "proxy, GitHub or Hugging Face blocked) or a full disk: the pack needs about $SIZE_GB GB."echo 'Fix that and click again - nothing already downloaded is fetched'echo 'twice, and a part-finished pack resumes where it stopped.'echo '=================================================================='diff --git a/scripts/pinokio/update_converge.sh b/scripts/pinokio/update_converge.shindex 0a4a3f1..0436a9f 100644--- a/scripts/pinokio/update_converge.sh+++ b/scripts/pinokio/update_converge.sh@@ -14,11 +14,11 @@# branch, and the `exec` on the happy path is what makes the fast-forward# exit with the rev-parse's own status and output.#-# ORDER IS THE GUARANTEE. This runs after scripts/pinokio/update_obstruction_-# guard.sh, which has already proven nothing untracked is in the way. Reaching+# ORDER IS NOT THE GUARANTEE — this script re-runs+# scripts/pinokio/update_obstruction_guard.sh itself (see below). Reaching# `reset --hard` requires BOTH of these to have passed:#-# 1. the obstruction guard (its step, before this one), and+# 1. the obstruction guard (run again here, in this shell), and# 2. `git rev-list --count $U..HEAD` > 0 — the number of commits this clone# has that upstream does not.#@@ -32,16 +32,27 @@# print git's own error — which names the obstructing paths. Nothing is# deleted on that path, ever.+# THE GUARD AGAIN, IN THIS SHELL, before anything moves the tree. "Its step,+# before this one" was not a guarantee: Pinokio 8.2.0 runs the next step after+# one that exits 1 unless the output says "error:", and the guard's refusal did+# not — so a diverged clone with an untracked obstruction was reset over it+# anyway, and on a clone with no divergence `merge --ff-only` silently+# overwrote an IGNORED obstruction, which git treats as expendable (Codex+# INST-02, 2026-09-24). A missing guard is a refusal too.+G="$(dirname "$0")/update_obstruction_guard.sh"+[ -f "$G" ] || { echo 'FATAL error: update_obstruction_guard.sh missing - not updating. Nothing deleted.'; exit 1; }+bash "$G" || exit 1+U=$(git rev-parse --abbrev-ref --symbolic-full-name @{u})M=$(git merge --ff-only "$U" 2>&1) && exec git rev-parse --short HEADA=$(git rev-list --count "$U"..HEAD)[ "$A" -gt 0 ] || {echo "$M"- echo 'FATAL: blocked above; history has NOT diverged. Nothing deleted.'+ echo 'FATAL error: blocked above; history has NOT diverged. Nothing deleted.'exit 1}git diff --quiet && git diff --cached --quiet || {- echo 'FATAL: local edits to tracked files'+ echo 'FATAL error: local edits to tracked files - not resetting. Nothing deleted.'exit 1}echo "diverged: $A commit(s) - resetting"diff --git a/scripts/pinokio/update_obstruction_guard.sh b/scripts/pinokio/update_obstruction_guard.shindex dab4648..5bf9a30 100644--- a/scripts/pinokio/update_obstruction_guard.sh+++ b/scripts/pinokio/update_obstruction_guard.sh@@ -7,6 +7,9 @@# survive). See scripts/pinokio/README.md.## cwd : the app root, i.e. the panel repo+# $1 : the ref being updated TO, optional; defaults to @{u}. The in-panel+# Update (panel/routes_meta.py) passes origin/main — it runs the same+# guard rather than a second implementation of these rules.## SEMANTICS: unchanged — one shell, NO `set -e`. Almost every command in here# exits non-zero as ordinary control flow (`git cat-file -e ... || continue`,@@ -74,9 +77,17 @@# scripts/check_ltx_pin.js, which drives these real dispatches against real# throwaway clones.-O=$(git diff --name-only --diff-filter=ADRT HEAD '@{u}' | while IFS= read -r f; do+REF=${1:-'@{u}'}+# An unresolvable ref would make the diff below print nothing and the guard+# pass — fail closed instead.+git rev-parse --verify -q "$REF^{commit}" >/dev/null || {+ echo "FATAL error: cannot resolve $REF - not updating. Nothing deleted."+ exit 1+}++O=$(git diff --name-only --diff-filter=ADRT HEAD "$REF" | while IFS= read -r f; do# Only paths the fetched tree actually writes, and only ones we don't track.- git cat-file -e "@{u}:$f" 2>/dev/null || continue+ git cat-file -e "$REF:$f" 2>/dev/null || continuegit cat-file -e "HEAD:$f" 2>/dev/null && continue# 1. The exact path. An empty directory holds no user data and git removes@@ -104,8 +115,12 @@ O=$(git diff --name-only --diff-filter=ADRT HEAD '@{u}' | while IFS= read -r f;donedone)+# "error:" IN THE REFUSAL IS LOAD-BEARING. Pinokio 8.2.0 ignores a step's exit+# status; it stops a run only when the output matches /error:/i (or /errno /i).+# "FATAL: ..." alone let the run continue into update_converge.sh (INST-02).+# That script now repeats this guard before its reset as well — two defences.[ -z "$O" ] || {echo "$O"- echo 'FATAL: untracked/ignored paths obstruct Update. Move them; nothing deleted.'+ echo 'FATAL error: untracked/ignored paths obstruct Update. Move them; nothing deleted.'exit 1}diff --git a/scripts/post_update.sh b/scripts/post_update.shindex fe6ea73..116afae 100644--- a/scripts/post_update.sh+++ b/scripts/post_update.sh@@ -71,6 +71,9 @@ require() {echo ""echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"echo "!! PHOSPHENE UPDATE FAILED: $what"+ # "error:" is what Pinokio 8.2.0 reads as a failed step — it ignores the+ # exit status below. Without it the run ended looking successful (INST-02).+ echo "!! error: the Update did not complete"echo "!! This step is not optional — stopping here rather than reporting a"echo "!! successful update that did not happen. Nothing has been deleted."echo "!! Re-run Update; if it fails the same way, the message above it is"@@ -165,6 +168,21 @@ require "the transformers <5.13.0 cap (5.13.0 breaks every generation)" -- \# pip drops inherited constraints inside the isolated build env on purpose# (`_PIP_IN_BUILD_IGNORE_CONSTRAINTS=1`), and its `--build-constraint` flag# does not exist on the older pips this fleet was seeded with.+#+# FIRST, THEIR DEPENDENCIES — the pass install.js has always run and Update+# never did. The reinstall below is --no-deps, so on a venv step 0 has just+# REBUILT (or one whose first install died half-way) nothing ever installs what+# the three packages declare. `mlx-arsenal` is the one nothing else pulls in:+# core and pipelines both import `mlx_arsenal.diffusion`, so such a venv had+# Python, mlx and our packages and still could not render — and every further+# Update repeated the same dependency-free install (Codex INST-03, 2026-09-24;+# part of the fleet's "venv has a Python but no packages" signal). Resolved on+# the SAME invocation as the mlx trio and the transformers cap so the solver+# cannot move either; on a healthy venv everything is already satisfied and+# this is a no-op. It links the workspace members editable — the --reinstall+# --no-deps pass right after replaces those links with real copies, exactly+# as install.js does.+require "installing the vendored packages' dependencies (mlx-arsenal and the rest)" -- bash -c 'cd "$1/ltx-2-mlx" && shift && uv pip install --python env/bin/python --build-constraints ../pip-build-constraints.txt "$@" ./packages/ltx-core-mlx ./packages/ltx-pipelines-mlx ./packages/ltx-trainer' _ "$ROOT" 'mlx==0.31.1' 'mlx-lm==0.31.1' 'mlx-metal==0.31.1' 'transformers>=5.0.0,<5.13.0'require "re-installing the three vendored packages" -- bash -c 'cd "$1/ltx-2-mlx" && uv pip install --python env/bin/python --reinstall --no-deps --build-constraints ../pip-build-constraints.txt ./packages/ltx-core-mlx ./packages/ltx-pipelines-mlx ./packages/ltx-trainer' _ "$ROOT"# ---- 4. The codec patch — IMMEDIATELY after the reinstall -------------------@@ -346,15 +364,24 @@ echo 'Trim done.'# so `check_post_update.js` can still tell them apart: the gate is the# comma-form line it must find wrapped in `require`. (A one-package probe let# a torn ltx_core_mlx skip the repair and fail the gate — review 2026-09-02.)+# The repair resolves dependencies first, like step 3: a --no-deps-only repair+# could never install a missing `mlx_arsenal`, so it failed the same way every+# time (INST-03). mlx_arsenal is imported explicitly because the package roots+# import without it — the failure used to surface only at Generate.echo 'Verifying the render engine actually imports…'-if ! "$PY" -c "import ltx_core_mlx; import ltx_pipelines_mlx; import mlx" 2>/dev/null; then+if ! "$PY" -c "import ltx_core_mlx; import ltx_pipelines_mlx; import mlx; import mlx_arsenal" 2>/dev/null; thenecho 'Render engine did not import — repairing the vendored packages once…'- ( cd "$ROOT/ltx-2-mlx" && uv pip install --python env/bin/python --reinstall \+ ( cd "$ROOT/ltx-2-mlx" && uv pip install --python env/bin/python \+ --build-constraints ../pip-build-constraints.txt \+ 'mlx==0.31.1' 'mlx-lm==0.31.1' 'mlx-metal==0.31.1' 'transformers>=5.0.0,<5.13.0' \+ ./packages/ltx-core-mlx ./packages/ltx-pipelines-mlx ./packages/ltx-trainer \+ && uv pip install --python env/bin/python --reinstall \--no-deps --build-constraints ../pip-build-constraints.txt \- ./packages/ltx-core-mlx ./packages/ltx-pipelines-mlx ./packages/ltx-trainer ) \+ ./packages/ltx-core-mlx ./packages/ltx-pipelines-mlx ./packages/ltx-trainer \+ && "$PY" "$ROOT/patch_ltx_codec.py" ) \|| truefi-require "the render engine import gate" -- "$PY" -c "import ltx_core_mlx, ltx_pipelines_mlx, mlx"+require "the render engine import gate" -- "$PY" -c "import ltx_core_mlx, ltx_pipelines_mlx, mlx, mlx_arsenal"# Music is independent of LTX. Update only an installed checkout; never pull# an 11 GB pack as a side effect of an ordinary panel update.diff --git a/scripts/test_analytics_dryrun.py b/scripts/test_analytics_dryrun.pyindex c619ab8..f6b8685 100644--- a/scripts/test_analytics_dryrun.py+++ b/scripts/test_analytics_dryrun.py@@ -549,6 +549,42 @@ class TestEventSchemas(AnalyticsTestCase):self.assertNotIn("error_fingerprint", p)self.assertEqual(p["audio_mode"], "h3_native")+ def test_image_ref_paths_with_spaces_never_reach_the_signature(self):+ """Codex UI-02: the image job's `refs` array was not in the secret+ list and the path regex stops at whitespace, so a failed image job+ sent "<path> Client Portrait.png"."""+ from unittest import mock+ self.configure(analytics_first_render_reported=True)+ ref = "/Volumes/Photos/Private Client Portrait.png"+ uni = "/Volumes/写真/秘密 の 顧客.png"+ cases = [+ (f"ref image not found: {ref}", {"refs": [ref]}),+ (f"ref image not found: {uni}", {"refs": [{"path": uni}]}),+ ("ref image not found: Private Client Portrait.png", {"refs": [ref]}),+ ]+ for err, extra in cases:+ self.spy.bodies.clear()+ P._analytics_render_event({+ "status": "failed", "error": err, "elapsed_sec": 5.0,+ "params": dict({"mode": "image", "engine": "mflux",+ "prompt": "x"}, **extra)})+ drain()+ sig = self.props_of("render_failed")["error_signature"]+ for frag in ("Private", "Client", "Portrait", "秘密", "顧客", "写真"):+ self.assertNotIn(frag, sig, (err, sig))+ # an install root with a space in it+ root = Path("/Users/someone/My Apps/phosphene.git")+ with mock.patch.object(P, "ROOT", root), mock.patch.object(P, "UPLOADS", root / "panel_uploads"):+ self.spy.bodies.clear()+ P._analytics_render_event({+ "status": "failed", "elapsed_sec": 5.0,+ "error": f"ref image not found: {root}/panel_uploads/1700_face.png",+ "params": {"mode": "image", "engine": "mflux", "prompt": "x"}})+ drain()+ sig = self.props_of("render_failed")["error_signature"]+ self.assertNotIn("Apps", sig, sig)+ self.assertNotIn("someone", sig, sig)+def test_unknown_error_ships_class_other_plus_fingerprint(self):self.configure(analytics_first_render_reported=True)P._analytics_render_event({diff --git a/scripts/test_pack_release.py b/scripts/test_pack_release.pyindex def5fc0..676a791 100644--- a/scripts/test_pack_release.py+++ b/scripts/test_pack_release.py@@ -233,6 +233,28 @@ def test_a_truncated_shard_resumes_instead_of_restarting(served):assert (dest / "big.safetensors").read_bytes() == (pack / "big.safetensors").read_bytes()+def test_a_corrupted_partial_is_discarded_so_the_retry_can_recover(served):+ """Codex INST-08: bytes already appended to a .partial went bad without+ changing length. Resume trusted the progress sidecar, skipped those shards,+ failed the whole-file hash — and kept both files, so every retry skipped+ the same bytes and failed identically. The first attempt may fail; the+ next one must refetch and finish."""+ root, pack, _, dest, hits, manifest = served+ spec = manifest["files"]["big.safetensors"]+ dest.mkdir(parents=True, exist_ok=True)+ first = spec["shards"][0]+ good = bytearray((pack / "big.safetensors").read_bytes()[:first["bytes"]])+ good[5] ^= 0xFF # same length, one bad byte+ partial = dest / "big.safetensors.partial"+ partial.write_bytes(bytes(good))+ fetcher._write_progress(partial, 1)++ assert _fetch(root, dest, attempts=1) == 1+ assert not partial.exists(), "a partial that failed its whole-file hash was kept"+ assert _fetch(root, dest, attempts=1) == 0+ assert (dest / "big.safetensors").read_bytes() == (pack / "big.safetensors").read_bytes()++def test_a_complete_pack_is_not_downloaded_again(served):root, _, _, dest, hits, _ = servedassert _fetch(root, dest) == 0diff --git a/storyboard.py b/storyboard.pyindex 2d69878..b7f3e9a 100644--- a/storyboard.py+++ b/storyboard.py@@ -568,7 +568,28 @@ def validate_storyboard_detail(# warning, on the same principle as everything else here: the failure# it prevents is a finished clip of somebody babbling, and you only# find out after the render.- verb = shot_speech_problem(prompt)+ #+ # AN A2V SHOT IS EXEMPT, and that is not a loosening. The law asks+ # "are there words for this mouth to say" and reads the prompt because+ # on every other mode the prompt is the only place words can be. On+ # a2v the words are a WAVEFORM — the pipeline drives the mouth from+ # `audio` at `audio_start_time`, which is the whole mode — so a music+ # video's "close-up, singing to camera" was refused for having no+ # lyrics written in it while the lyrics were in the file next to it.+ # Same reasoning for the pacing check below: a line's length is set by+ # the recording, not by a word count in a sentence nobody will read.+ # AN A2V SHOT IS NOT EXEMPT ANY MORE — it is judged by its own law.+ # The stillness words are the documented cause of a freeze frame with+ # no lip-sync, and our own planners used to write them mechanically.+ if mode == "a2v":+ for phrase in a2v_stillness_problems(prompt):+ add("a2v_stillness",+ f"{where}: {phrase!r} tells the model that nothing moves — "+ f"and that includes the singer's lips. An audio-driven "+ f"shot renders as a freeze frame with a closed mouth. "+ f"Say what the performer DOES instead.",+ n=n_for_ui, field="prompt", phrase=phrase)+ verb = shot_speech_problem(prompt) if mode != "a2v" else Noneif verb:add("speech_without_words",f"{where}: {verb!r} implies someone is speaking, but no spoken "@@ -580,7 +601,8 @@ def validate_storyboard_detail(# clock. Blocks the render for the same reason everything here does —# the defect (a sentence cut off mid-word) is only visible AFTER the# render time is spent.- pacing = shot_pacing_problem(prompt, s.get("duration_s") or 0)+ pacing = (shot_pacing_problem(prompt, s.get("duration_s") or 0)+ if mode != "a2v" else None)if pacing:add("dialogue_does_not_fit",f"{where}: {pacing}.",@@ -1024,6 +1046,198 @@ _SUNG_READ_RE = re.compile(SPEECH_SETTLE_S = 1.0+# --- THE A2V PROMPT LAW: A SINGING SHOT IS NOT A STILL ----------------------+# An a2v shot is driven by a WAVEFORM. The one thing it must not be told is+# that nothing moves - LTX reads a stillness word as "nothing in the scene+# moves, INCLUDING the singer's lips", and the shot comes back as a freeze+# frame with a closed mouth. Our own planners were writing exactly that:+# `storyboard_planner._CAMERA_SENTENCES["static"]` is "The camera holds a+# static shot, the frame never moves..." and the settle law adds "with no new+# movement of any kind" - two documented lip-sync killers, as canonical+# sentences PYTHON wrote, on every planned shot.+#+# Three rules, and they live HERE rather than in either planner because both+# planners and the validator have to agree about them:+#+# 1. no stillness words, ever, on an a2v shot (an ERROR, not advice);+# 2. a literal sync contract, appended AFTER all polish so a re-roll, an+# enhance pass or a hand edit cannot paraphrase it away;+# 3. a SHORT prompt - the more set-dressing there is, the more static the+# clip becomes and the further the vocal verb sinks behind it.+#+# The contract's wording is deliberate: "lip-syncs" rather than "sings",+# because a generic "sings" is read as unconstrained performance while the+# written word binds the mouth to the file the shot was given.+A2V_SYNC_CONTRACT = (+ "The singer lip-syncs every vocal syllable to the supplied soundtrack, "+ "with exact timing, natural mouth shapes and matching breaths.")++#: A window with no vocal in it. Saying nothing is not neutral - the model+#: keeps the mouth working through an instrumental bar - so a silent window+#: gets its own contract instead of the singing one.+A2V_SILENT_CONTRACT = (+ "Nobody is singing in this moment: the mouth stays at rest with relaxed "+ "closed lips.")++#: The words that BIND the contract. A re-roll or a hand edit may rewrite the+#: sentence; these are what `a2v_prompt` looks for before adding another.+_A2V_CONTRACT_KEYS = ("lip-sync", "relaxed closed lips")++#: How many words of creative direction an a2v shot gets. The contract rides+#: ON TOP of this, because it is the one sentence that must survive.+A2V_MAX_WORDS = 40++#: Every stillness phrase, and what it becomes when it is rewritten in place.+#: The order matters: the specific forms rewrite before the general ones.+#:+#: `still` on its own is deliberately absent. "the coffee is still hot" is an+#: adverb, not a freeze frame, and this list drives a BLOCKING error - so the+#: phrases are matched with their verbs, and the bare `is still` form only+#: when nothing follows it inside the clause.+_A2V_STILLNESS_FIXES = (+ (r"\bholds? a static (?:shot|hold|frame)\b", "is locked in place"),+ (r"\bstatic (?:shot|hold|camera|frame|framing)\b", "locked-off camera"),+ (r"\bthe (?:frame|camera) never moves\b", "the camera is locked in place"),+ (r"\bbarely mov(?:es|ing)\b", "moves clearly"),+ (r"\bno new movement(?: of any kind)?\b", "the performance carries on"),+ (r"\b(holds?|held|stays?|staying|remains?|sits?|sitting|stands?|standing"+ r"|keeps?|keeping) (?:perfectly |completely |very |utterly |absolutely )?"+ r"(?:still|motionless)\b", r"\1 steady"),+ (r"\b(?:is|are|was|were) (?:perfectly |completely |very |utterly "+ r"|absolutely )?still\b(?!\s+\w)", "is steady"),+ (r"\b(?:perfectly|completely|utterly|absolutely) (?:still|motionless)\b",+ "steady"),+ (r"\bmotionless\b", "steady"),+ (r"\bfreeze frame\b", "held frame"),+ (r"\bnothing (?:in the (?:scene|frame) )?moves\b",+ "the camera is locked in place"),+ (r"\bwithout moving\b", "steadily"),+ (r"\b(?:does not|doesn't|never) move\b", "stays steady"),+)++#: The union of the above - what `a2v_stillness_problems` reports and the+#: validator refuses. Built from the same tuple so a phrase can never be+#: refusable and unfixable at the same time.+_A2V_STILLNESS_RE = re.compile(+ "|".join(pat for pat, _ in _A2V_STILLNESS_FIXES), re.IGNORECASE)++#: A clause that is NOTHING BUT a refusal of camera movement. Cleaned out of+#: an a2v prompt but never an error on its own: one of these is a tripod+#: instruction, and it is only STACKING them that compounds into no motion.+_A2V_DEAD_CLAUSE_RE = re.compile(+ r"^(?:and\s+|with\s+)?no\s+(?:new\s+)?"+ r"(?:pan|push[- ]?in|pull[- ]?back|re-?fram\w+|zoom|drift"+ r"|camera\s+\w+|movement|motion)\b",+ re.IGNORECASE)++#: A clause whose subject is the camera or the frame. On an a2v shot a clause+#: like this is DELETED rather than rewritten: the shot does not need a camera+#: restraint sentence at all, and rewriting "the camera holds a static shot"+#: only produces a more polite way of saying the same fatal thing.+_A2V_CAMERA_SUBJECT_RE = re.compile(r"\b(?:camera|frame|framing|shot)\b",+ re.IGNORECASE)++_A2V_SENTENCE_SPLIT = re.compile(r"(?<=[.!?])\s+")+++def a2v_stillness_problems(prompt: str) -> list[str]:+ """Every stillness phrase in `prompt`, in the order they appear.++ Empty means the prompt is safe to hand to an audio-driven render.+ """+ return [m.group(0) for m in _A2V_STILLNESS_RE.finditer(prompt or "")]+++def _a2v_clean_clause(clause: str) -> str:+ """One clause, made safe. Empty string when it should disappear."""+ c = clause.strip()+ if not c:+ return ""+ if _A2V_DEAD_CLAUSE_RE.match(c):+ return ""+ if not _A2V_STILLNESS_RE.search(c):+ return c+ if _A2V_CAMERA_SUBJECT_RE.search(c):+ return ""+ for pattern, replacement in _A2V_STILLNESS_FIXES:+ c = re.sub(pattern, replacement, c, flags=re.IGNORECASE)+ return c.strip()+++def a2v_clean_prompt(text: str) -> str:+ """`text` with every stillness cue removed, clause by clause.++ CLAUSE-LEVEL, not sentence-level, and the two treatments are different on+ purpose: a clause about the CAMERA is deleted (an audio-driven shot does+ not want a restraint sentence at all), a clause about a PERSON is rewritten+ in place so it keeps its subject - "she stands still at the microphone,+ singing" has to come out as a woman at a microphone, singing.+ """+ out = []+ for sentence in _A2V_SENTENCE_SPLIT.split(str(text or "").strip()):+ if not sentence.strip():+ continue+ tail = "." if sentence.rstrip()[-1:] in ".!?" else ""+ kept = [k for k in (_a2v_clean_clause(c)+ for c in re.split(r"[,;]", sentence.rstrip(".!?")))+ if k]+ if kept:+ out.append(", ".join(kept) + tail)+ return " ".join(out).strip()+++def a2v_direction(line: str, max_words=A2V_MAX_WORDS) -> str:+ """The CREATIVE DIRECTION of an a2v shot: stillness out, cap on, no+ contract yet.++ Split from `a2v_prompt` because the cap must fall on the direction and+ never on the laws: the face law alone is sixty words, and a cap applied to+ a finished prompt would delete it - along with the style suffix and the+ sync contract, which are the two things that must survive.+ """+ return _a2v_cap_words(a2v_clean_prompt(line), max_words)+++def _a2v_cap_words(text: str, max_words) -> str:+ """`text` cut to `max_words`, on a clause boundary when there is one.++ Cutting mid-clause leaves a dangling "in the warm light of" that the model+ finishes by inventing; a clause boundary always closes an idea.+ """+ raw = str(text or "").strip()+ if max_words is None:+ return raw+ words = raw.split()+ if len(words) <= max_words:+ return raw+ clipped = " ".join(words[:max_words])+ cut = max(clipped.rfind(","), clipped.rfind(";"), clipped.rfind("."))+ if cut > 0:+ clipped = clipped[:cut]+ return clipped.rstrip(" ,;.") + "."+++def a2v_prompt(line: str, *, silent: bool = False,+ max_words=A2V_MAX_WORDS) -> str:+ """One direction, made safe for an audio-driven render.++ Stillness out, capped to `max_words` of creative direction, then the+ contract LAST - after the cap, so a long prompt loses set-dressing and+ never the one sentence that makes the mouth move. Idempotent: a prompt+ that already carries a contract does not collect a second one.+ `max_words=None` skips the cap, for a prompt whose direction was already+ capped when it was written (see `a2v_direction`).+ """+ body = a2v_direction(line, max_words).strip()+ contract = A2V_SILENT_CONTRACT if silent else A2V_SYNC_CONTRACT+ low = body.lower()+ if any(key in low for key in _A2V_CONTRACT_KEYS):+ return body+ if body and body[-1] not in ".!?":+ body += "."+ return (body + " " + contract).strip() if body else contract++def is_slow_read(prompt: str) -> bool:"""True when the voice descriptor asks for slow delivery."""return bool(_SLOW_READ_RE.search(prompt or ""))@@ -1319,6 +1533,17 @@ def compose_shot_prompt(shot: dict, locations: dict[str, dict] | None = None,flipping an eyeline to fix the 180-degree line — re-flows every shot thatuses it without rewriting anybody's text."""+ # THE LAST PLACE A PROMPT CAN BE MADE SAFE. Every shot passes through here+ # on its way to a render, so an a2v shot gets its sync contract here even+ # if it was planned before this law existed, hand-edited since, or written+ # by a caller who never heard of it. `a2v_prompt` is idempotent, so a+ # planner that already appended the contract does not produce two.+ if shot.get("mode") == "a2v":+ # NO CAP HERE. The direction was capped when the shot was written; a+ # cap applied to a finished prompt would delete the face law and the+ # style along with the set-dressing, which is not this seam's job.+ shot = dict(shot, prompt=a2v_prompt(shot.get("prompt") or "",+ max_words=None))trigger = (shot.get("trigger") or shot.get("character_id") or "").strip()# H3's three-field prompt. The additions below describe the PICTURE, so# they belong in `integrated_multimodal_description` and nowhere after it:@@ -1658,6 +1883,28 @@ def shot_to_job(shot: dict, policy_pass: dict, *,# made from the character's own frames (2026-09-10, the sitcom's jungle# shots lost the lead's face on every text-only render and kept it on# every render that started from a still).+ # AUDIO -> VIDEO. The three fields `run_job_inner`'s a2v branch reads are+ # `audio`, `audio_start_time` and `image`, and all three are in make_job's+ # allowlist — but nothing here ever wrote them, so an a2v shot enqueued as+ # a SILENT t2v from its prompt and the reference PNG make_job defaults to.+ # (The refs note at the bottom is about `shot["refs"]`, which still is not+ # mapped: a2v does not want a ref list, it wants one still and one file.)+ if shot.get("mode") == "a2v" and shot.get("audio"):+ job["audio"] = str(shot["audio"])+ # Where in the song this shot is looking. The whole of the music-video+ # lane rides on this number: the clip is rendered against the seconds+ # of the track it will be playing under once the film is assembled.+ job["audio_start_time"] = str(+ max(0.0, float(shot.get("audio_start_time") or 0.0)))+ # WHAT THE MODEL LISTENS TO, when that is not what the clip plays. A+ # separated vocal stem conditions the mouth and the panel muxes the+ # original song back, so the shot still carries `audio` as the file it+ # is cut against — `audio_stem` only ever changes the conditioning.+ # Same offset applies to both: the stem is the whole song, separated.+ if shot.get("audio_stem"):+ job["audio_stem"] = str(shot["audio_stem"])+ if shot.get("still"):+ job["image"] = str(shot["still"])if shot.get("still") and job["mode"] == "t2v" and (engine != "h3" or h3_first_frame):job["mode"] = "i2v"job["image"] = str(shot["still"])diff --git a/storyboard_editor.py b/storyboard_editor.pyindex b18ed20..d836853 100644--- a/storyboard_editor.py+++ b/storyboard_editor.py@@ -188,9 +188,13 @@ class EditConflict(EditError):is what is actually on disk right now."""- def __init__(self, message: str, *, revision: int = 0) -> None:+ def __init__(self, message: str, *, revision: int = 0,+ draft: str = "") -> None:super().__init__(message)self.revision = int(revision)+ # Set when the conflict is about WHICH DRAFT edit.json is, not about+ # its revision: the active draft's slug, right now.+ self.draft = str(draft or "")def _f(x, default: float = 0.0) -> float:@@ -3415,7 +3419,8 @@ def on_disk_revision(board_dir) -> int:def save_edit(board_dir, edit: dict, *, bump: bool = True,- origin: str = "manual", expect: int | None = None) -> Path:+ origin: str = "manual", expect: int | None = None,+ expect_draft: str | None = None) -> Path:"""Validate, then write atomically. A bad edit NEVER lands on a good one.This is the whole reason `validate_edit` returns structured errors instead@@ -3433,6 +3438,14 @@ def save_edit(board_dir, edit: dict, *, bump: bool = True,THE LOCK IS TAKEN WHETHER OR NOT `expect` IS. Two unguarded writers stillmust not interleave a history copy with a replace.++ `expect_draft` is the other half of "the document the caller believes is+ on disk": WHICH draft `edit.json` is. A revision alone cannot tell drafts+ apart — a new or duplicated draft restarts at revision 1 — so a stale tab+ holding draft A at revision 1 used to save straight into a just-created+ draft B at revision 1 with no conflict at all (SB5-04). Checked in the+ same critical section as the revision, and the draft verbs below take the+ same lock, so a switch cannot land between the check and the write."""errs = blocking_errors(validate_edit(edit))if errs:@@ -3441,12 +3454,20 @@ def save_edit(board_dir, edit: dict, *, bump: bool = True,doc = normalise_edit(edit)with board_write_lock(board_dir):return _save_edit_locked(board_dir, doc, bump=bump, origin=origin,- expect=expect)+ expect=expect, expect_draft=expect_draft)def _save_edit_locked(board_dir, doc: dict, *, bump: bool, origin: str,- expect: int | None) -> Path:+ expect: int | None,+ expect_draft: str | None = None) -> Path:"""The critical section: compare, stamp, archive, replace. Lock held."""+ if expect_draft:+ active = load_draft_index(board_dir)["active"]+ if str(expect_draft) != active:+ raise EditConflict(+ f"this film is on the draft {active!r} now, not "+ f"{str(expect_draft)!r} — your arrangement was not written "+ f"over it", revision=on_disk_revision(board_dir), draft=active)if expect is not None:current = on_disk_revision(board_dir)try:@@ -5250,6 +5271,25 @@ def _stash_active(board_dir, idx: dict) -> None:_atomic_json(_draft_file(board_dir, idx["active"]), doc, prefix=".draft-")+def _under_board_lock(fn):+ """Run a draft verb inside the board's write lock.++ Switching drafts is two writes — `edit.json` becomes the other draft, then+ the index points at it — and a save checks `expect_draft` against that+ index. Without the lock a save could pass its check, a switch could land,+ and the save would then write the old draft's arrangement over the new+ one. The lock is an RLock, so the `save_edit` calls inside nest.+ """+ import functools # noqa: PLC0415++ @functools.wraps(fn)+ def inner(board_dir, *a, **kw):+ with board_write_lock(board_dir):+ return fn(board_dir, *a, **kw)+ return inner+++@_under_board_lockdef create_draft(board_dir, name: str, *, from_current: bool = False) -> dict:"""A new draft, empty or copied from what is on screen. Becomes active.@@ -5281,6 +5321,7 @@ def create_draft(board_dir, name: str, *, from_current: bool = False) -> dict:return _land_draft(board_dir, idx, slug, text, doc)+@_under_board_lockdef duplicate_draft(board_dir, slug: str, name: str = "") -> dict:"""Copy a draft under a new name. The copy becomes active."""idx = load_draft_index(board_dir)@@ -5327,6 +5368,7 @@ def _land_draft(board_dir, idx: dict, slug: str, text: str, doc: dict) -> dict:return {"slug": slug, "name": text}+@_under_board_lockdef rename_draft(board_dir, slug: str, name: str) -> dict:"""A NAME CHANGE IS NOT A FILE MOVE. The slug is the identity and it staysput, so renaming can never orphan a draft's file or its backup."""@@ -5342,6 +5384,7 @@ def rename_draft(board_dir, slug: str, name: str) -> dict:raise EditError("there is no draft by that name")+@_under_board_lockdef delete_draft(board_dir, slug: str) -> dict:"""Remove a draft. The LAST one cannot go, and neither can the active onewithout something to land on — an editor with no document is not a state@@ -5379,6 +5422,7 @@ def delete_draft(board_dir, slug: str) -> dict:return {"active": idx["active"], "deleted": target}+@_under_board_lockdef activate_draft(board_dir, slug: str) -> dict:"""Switch which draft `edit.json` is. The outgoing one is stashed first."""idx = load_draft_index(board_dir)diff --git a/storyboard_planner.py b/storyboard_planner.pyindex e4f6ccc..7f3dea6 100644--- a/storyboard_planner.py+++ b/storyboard_planner.py@@ -213,6 +213,37 @@ def _storyboard_module():return None+_SB_CACHE: Dict[str, Any] = {}+++def _sb():+ """storyboard.py, cached, or None. The a2v prompt law lives there because+ both planners AND the validator have to agree about it — this module must+ not carry a second copy that can drift."""+ if "mod" not in _SB_CACHE:+ _SB_CACHE["mod"] = _storyboard_module()+ return _SB_CACHE["mod"]+++# --------------------------------------------------------------------------------------+# A2V — a shot whose mouth is driven by a waveform+# --------------------------------------------------------------------------------------+# The planner does not EMIT a2v shots (see `_PLANNABLE_MODES`), but it is the+# module that assembles prompts, and an a2v shot reaches the assembler two+# ways: a caller hands in a spec that names the mode, and the repair loop+# re-assembles a shot that is already on a board. Both have to obey the a2v+# law — because the stillness sentence this module writes mechanically is the+# single documented cause of a singing shot rendering as a freeze frame.+A2V_MODE = "a2v"++#: What a locked camera is ALLOWED to say on an a2v shot. "Locked in place"+#: is a fact about the tripod; "the frame never moves" is a claim about the+#: whole scene, and the model applies it to the singer's lips.+A2V_CAMERA_SENTENCE = (+ "The camera is locked in place while the performer keeps moving - lips "+ "and jaw work clearly with every word.")++def _load_validator():"""Return (validate_fn, storyboard_module).@@ -2143,22 +2174,38 @@ def _stable_seed(concept: str) -> int:return int(h, 16) % 2147483647-def _compose_body(desc: str, camera: Any, settle: str, face: str = "") -> str:+def _compose_body(desc: str, camera: Any, settle: str, face: str = "",+ mode: str = "text") -> str:"""description + the camera law + the face law + the settle law, in exemplar order.If the model already wrote a camera sentence or an end-state clause of its own, that ishonoured rather than duplicated — a prompt with two camera instructions is worse than aprompt with the wrong one.++ ON AN A2V SHOT TWO OF THOSE LAWS ARE INVERTED. `_CAMERA_SENTENCES["static"]`+ says "the frame never moves - no pan, no push-in, no reframing" and the+ settle law says "with no new movement of any kind"; the model reads both as+ "nothing in this scene moves" and stops the singer's lips with everything+ else. So a2v gets a camera sentence that locks the TRIPOD and explicitly+ keeps the performer moving, no settle clause at all, and the stillness+ scrubber on whatever the model wrote for itself."""+ a2v = str(mode or "").strip().lower() == A2V_MODEbody = _plain_punctuation(_SHOT_MARKER_RE.sub("", (desc or "").strip())).rstrip()+ if a2v:+ sb = _sb()+ if sb is not None:+ # Cleaned AND capped, here and not at the end: the cap belongs+ # on the creative direction, never on the laws that follow it.+ body = sb.a2v_direction(body)if body and body[-1] not in ".!?":body += "."if "the camera" not in body.lower():- body += " " + _camera_sentence(camera)+ body += " " + (A2V_CAMERA_SENTENCE if a2v else _camera_sentence(camera))law = _FACE_LAWS.get(face or "", "")if law and "holds the exact angle" not in body:body += " " + law- if "completely finished before the shot ends" not in body.lower():+ if not a2v and "completely finished before the shot ends" not in body.lower():s = _settle_sentence(_plain_punctuation(settle or ""))if s:body += " " + s@@ -2168,10 +2215,11 @@ def _compose_body(desc: str, camera: Any, settle: str, face: str = "") -> str:def _assemble_h3_prompt(desc: str, sound: str, music: str,- camera: Any = "static", settle: str = "", face: str = "") -> str:+ camera: Any = "static", settle: str = "", face: str = "",+ mode: str = "text") -> str:"""The official three-field form. `[Shot 1]` carries no timestamp — every storyboardshot is one continuous take, so there is never a `[Shot 2]` inside a single prompt."""- body = _fix_unbalanced_d(_compose_body(desc, camera, settle, face))+ body = _fix_unbalanced_d(_compose_body(desc, camera, settle, face, mode))sound = _plain_punctuation((sound or "").strip()) or "N/A"music = _plain_punctuation((music or "").strip()) or "N/A"return (@@ -2182,10 +2230,12 @@ def _assemble_h3_prompt(desc: str, sound: str, music: str,def _assemble_ltx_prompt(desc: str, sound: str, style: str,- camera: Any = "static", settle: str = "", face: str = "") -> str:+ camera: Any = "static", settle: str = "", face: str = "",+ mode: str = "text") -> str:"""LTX 2.3 prose: one paragraph, master style suffix verbatim, one trailing `Audio:`line (the shape mlx_warm_helper's enhance addendum says LTX was trained on)."""- body = _strip_h3_markup(_compose_body(desc, camera, settle, face)).rstrip()+ a2v = str(mode or "").strip().lower() == A2V_MODE+ body = _strip_h3_markup(_compose_body(desc, camera, settle, face, mode)).rstrip()if body and body[-1] not in ".!?":body += "."st = _plain_punctuation((style or "").strip().rstrip("."))@@ -2194,7 +2244,18 @@ def _assemble_ltx_prompt(desc: str, sound: str, style: str,snd = _plain_punctuation((sound or "").strip().rstrip("."))if snd and snd.upper() != "N/A":body += " Audio: %s." % snd- return body.strip()+ body = body.strip()+ if a2v:+ # LAST, AFTER EVERY POLISH PASS. The style suffix and the Audio line+ # are appended above; anything that ran before them could be softened+ # or re-ordered by what came after. The sync contract is the one+ # sentence that must survive verbatim, so it goes on at the end — and+ # the same call caps the creative direction, because a long prompt+ # renders a more static clip and buries the vocal verb.+ sb = _sb()+ if sb is not None:+ body = sb.a2v_prompt(body, max_words=None)+ return bodydef default_policy(max_dim: Optional[int] = None) -> Dict[str, Any]:@@ -3413,7 +3474,12 @@ def _reassemble_prompt(shot: Dict[str, Any], style: str,"%s The on-screen subject is %s." % (desc, char["trigger"]),sound, music, camera, settle, face)return _assemble_h3_prompt(desc, sound, music, camera, settle, face)- prompt = _assemble_ltx_prompt(desc, sound, style, camera, settle, face)+ # THE SHOT'S OWN MODE. A re-assembly is the planner's a2v seam: the+ # planner never EMITS an a2v shot, but the repair loop re-composes shots+ # that are already on a board — including a music video's singing shots,+ # which must not collect the stillness sentence on the way back out.+ prompt = _assemble_ltx_prompt(desc, sound, style, camera, settle, face,+ shot.get("mode") or "text")if char:if sb is not None and hasattr(sb, "ensure_trigger"):prompt = sb.ensure_trigger(prompt, char["trigger"])diff --git a/test_a2v_sync_fixes.py b/test_a2v_sync_fixes.pyindex 2a63322..cd74424 100644--- a/test_a2v_sync_fixes.py+++ b/test_a2v_sync_fixes.py@@ -1,11 +1,12 @@-"""The a2v lip-sync fix — audio guidance defaults to the lane's own value.+"""The a2v lip-sync fixes — the lane default, the vocal stem, the prompt rules.Measured on one shot, at one seed, with the image, the audio window and the-prompt held fixed: the per-second correlation between the mouth's aperture and-the vocal-band energy of the soundtrack went **-0.065 -> +0.128** by changing-the audio-guidance default alone. -0.065 is worse than the same clip scored-against deliberately WRONG audio, i.e. the old default was not lip-syncing at-all on the Q8 lane.+prompt held fixed: the+per-second correlation between the mouth's aperture and the vocal-band energy+of the soundtrack went **-0.065 -> +0.128** by changing the audio-guidance+default alone, and **-> +0.156** with a demucs vocal stem as the conditioning+waveform. -0.065 is worse than the same clip scored against deliberately WRONG+audio, i.e. the shipped default was not lip-syncing at all.Structural assertions (reading a source file rather than running a render) areused where the alternative is a GPU: the a2v branch of `run_job_inner` needs a@@ -13,10 +14,19 @@ weights pack, a helper subprocess and twenty minutes. They are written againstthe exact line that decides the behaviour, never against prose."""+import json+import os+import subprocessimport unittestfrom pathlib import Path+from tempfile import TemporaryDirectory+from unittest import mockimport mlx_ltx_panel as P+import music_video as mv+import storyboard+import storyboard_planner+from panel import routes_musicPANEL_SRC = Path(__file__).with_name("mlx_ltx_panel.py").read_text()HELPER_SRC = Path(__file__).with_name("mlx_warm_helper.py").read_text()@@ -132,6 +142,676 @@ class LaneAwareAudioScale(unittest.TestCase):self.assertIn("(acsEl && !acsEl.dataset.auto)", js)+# ---------------------------------------------------------------------------+# 2. THE VOCAL-STEM CONDITIONING SEAM+# ---------------------------------------------------------------------------+class ConditioningAudioIsNotAlwaysTheSoundtrack(unittest.TestCase):+ """What the model listens to vs. what the finished clip plays."""++ def setUp(self):+ self.tmp = TemporaryDirectory()+ self.root = Path(self.tmp.name)+ self.song = self.root / "song.wav"+ self.song.write_bytes(b"RIFF....WAVE")+ self.stem = self.root / "vocals.wav"+ self.stem.write_bytes(b"RIFF....WAVE")+ self.addCleanup(self.tmp.cleanup)++ def test_no_stem_asked_for_means_the_song_itself(self):+ got, note = P.a2v_conditioning_audio({}, str(self.song))+ self.assertEqual(got, str(self.song))+ self.assertEqual(note, "")++ def test_an_explicit_stem_is_what_the_model_hears(self):+ got, note = P.a2v_conditioning_audio(+ {"audio_stem": str(self.stem)}, str(self.song))+ self.assertEqual(got, str(self.stem))+ self.assertEqual(note, "")++ def test_an_explicit_stem_that_is_not_there_is_a_refusal(self):+ # A typo in something the caller wrote. Rendering the full mix quietly+ # would hide it for the whole film.+ with self.assertRaises(RuntimeError) as cm:+ P.a2v_conditioning_audio(+ {"audio_stem": str(self.root / "nope.wav")}, str(self.song))+ self.assertIn("nope.wav", str(cm.exception))++ def test_auto_without_demucs_degrades_with_a_visible_note(self):+ with mock.patch.object(P, "_resolve_demucs", return_value=None):+ got, note = P.a2v_conditioning_audio(+ {"audio_stem_auto": "on"}, str(self.song))+ self.assertEqual(got, str(self.song))+ self.assertIn("stems extra", note)++ def test_auto_that_fails_mid_separation_never_fails_the_job(self):+ with mock.patch.object(P, "_resolve_demucs",+ return_value=Path("/bin/true")), \+ mock.patch.object(P, "_a2v_separate_vocals",+ side_effect=RuntimeError("demucs failed: boom")):+ got, note = P.a2v_conditioning_audio(+ {"audio_stem_auto": "1"}, str(self.song))+ self.assertEqual(got, str(self.song))+ self.assertIn("full mix", note)++ def test_auto_that_works_hands_back_the_stem(self):+ with mock.patch.object(P, "_resolve_demucs",+ return_value=Path("/bin/true")), \+ mock.patch.object(P, "_a2v_separate_vocals",+ return_value=self.stem):+ got, note = P.a2v_conditioning_audio(+ {"audio_stem_auto": "true"}, str(self.song))+ self.assertEqual(got, str(self.stem))+ self.assertEqual(note, "")++ def test_auto_is_off_unless_it_is_asked_for(self):+ for raw in ("", "0", "off", "no", None):+ with self.subTest(raw=raw):+ with mock.patch.object(P, "_resolve_demucs") as res:+ got, note = P.a2v_conditioning_audio(+ {"audio_stem_auto": raw}, str(self.song))+ res.assert_not_called()+ self.assertEqual(got, str(self.song))++ def test_the_stem_cache_is_keyed_to_the_file_not_the_name(self):+ first = P._a2v_stem_cache_path(str(self.song))+ self.assertEqual(first, P._a2v_stem_cache_path(str(self.song)))+ self.song.write_bytes(b"RIFF....WAVE-edited-and-longer")+ self.assertNotEqual(first, P._a2v_stem_cache_path(str(self.song)))+++class StopCanEndASeparation(unittest.TestCase):+ """Demucs is a child of this panel, so Stop has to reach it.++ It ran through a bare, untracked `subprocess.run` (Codex review,+ 2026-09-22): pressing Stop during separation killed the helper and left+ demucs grinding, with the queue held by a job the user had already+ cancelled, for up to the 900-second timeout. Worse, Stop DURING the final+ remux was caught as an ordinary mux failure, and the panel published the+ clip anyway — playing the a-cappella, because the original song is muxed+ back only at that step.+ """++ def setUp(self):+ self.tmp = TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ self.root = Path(self.tmp.name)+ self.song = self.root / "song.wav"+ self.song.write_bytes(b"RIFF....WAVE")+ # A stand-in separator: writes what demucs writes, exits 0.+ self.demucs = self.root / "demucs"+ self.demucs.write_text(+ "#!/bin/sh\n"+ 'out=""\n'+ 'while [ $# -gt 0 ]; do [ "$1" = "-o" ] && out="$2"; shift; done\n'+ 'mkdir -p "$out/htdemucs/song" && printf RIFF > "$out/htdemucs/song/vocals.wav"\n'+ "exit 0\n")+ self.demucs.chmod(0o755)+ self.job = {"id": "job-stem-1", "cancel_requested": False}++ def _separate(self):+ with mock.patch.object(P, "_thread_job", return_value=self.job):+ return P._a2v_separate_vocals(str(self.song), self.demucs)++ def test_a_real_separation_still_produces_the_stem(self):+ # The gate is a real exit code from a real child, not a mock.+ stem = self._separate()+ self.assertTrue(stem.is_file())+ self.assertEqual(stem.name, "vocals.wav")+ self.assertFalse((stem.parent / "work").exists(), "the work dir leaked")+ # Cached: the second call must not run the separator again.+ self.demucs.write_text("#!/bin/sh\nexit 9\n")+ self.assertEqual(self._separate(), stem)++ def test_the_child_is_registered_where_stop_looks_for_it(self):+ seen = []+ real = P._register_job_pgid+ with mock.patch.object(P, "_register_job_pgid",+ side_effect=lambda key, pgid, job=None: (+ seen.append(key), real(key, pgid, job))[1]):+ self._separate()+ self.assertIn("mux_pgid", seen)+ # And that is a key /stop actually kills.+ stop = PANEL_SRC.split("def stop_current_job")[1].split("\ndef ")[0]+ self.assertIn('STATE.get("mux_pgid")', stop)+ self.assertIn("os.killpg(mux_pgid", stop)++ def test_stop_before_the_separator_starts_is_a_cancellation(self):+ self.job["cancel_requested"] = True+ with mock.patch.object(P, "_thread_job", return_value=self.job):+ with self.assertRaises(P.JobCancelled):+ P._a2v_separate_vocals(str(self.song), self.demucs)++ def test_a_separation_that_fails_is_still_only_a_note(self):+ self.demucs.write_text("#!/bin/sh\necho 'no such model' >&2\nexit 1\n")+ self.demucs.chmod(0o755)+ with mock.patch.object(P, "_thread_job", return_value=self.job), \+ mock.patch.object(P, "_resolve_demucs", return_value=self.demucs):+ got, note = P.a2v_conditioning_audio(+ {"audio_stem_auto": "on"}, str(self.song))+ self.assertEqual(got, str(self.song))+ self.assertIn("full mix", note)++ def test_stop_during_the_separation_is_never_downgraded_to_a_note(self):+ # A cancelled job must not quietly become a full-mix render that the+ # user then waits twenty minutes for.+ with mock.patch.object(P, "_resolve_demucs", return_value=self.demucs), \+ mock.patch.object(P, "_a2v_separate_vocals",+ side_effect=P.JobCancelled("Stopped during it.")):+ with self.assertRaises(P.JobCancelled):+ P.a2v_conditioning_audio({"audio_stem_auto": "on"}, str(self.song))++ def test_the_separator_runs_through_the_tracked_runner(self):+ body = PANEL_SRC.split("def _a2v_separate_vocals")[1].split("\ndef ")[0]+ self.assertIn("run_tracked_subprocess(", body)+ self.assertNotIn("subprocess.run(", body)+ self.assertIn("A2V_STEM_TIMEOUT_S", body)++ def test_stop_during_the_remux_does_not_publish_the_a_cappella(self):+ # The clip on disk is still the one the model sang against; the song+ # goes back over it in the remux, so a remux that was STOPPED may not+ # be filed as a finished take.+ block = PANEL_SRC.split("if cond_audio != audio_src:")[1].split("sidecar = {")[0]+ self.assertIn("a2v_mux_original_audio(", block)+ self.assertLess(block.index("except JobCancelled:"),+ block.index("except Exception as exc:"),+ "Stop is still caught as an ordinary mux failure")+++class OnlyToolsTheInstallScriptsProvide(unittest.TestCase):++ def test_a_resolved_demucs_is_a_file_that_exists_or_nothing(self):+ # `_resolve_tool` ends on a LAST-RESORT path that need not exist. A+ # separator that is not there has to read as "not installed" now, not+ # as a command that dies twenty minutes into a render.+ got = P._resolve_demucs()+ self.assertTrue(got is None or got.is_file())++ def test_no_foreign_virtualenv_is_a_dependency(self):+ # Some other project's venv on this Mac is not a dependency of+ # Phosphene, and an install script cannot provide one.+ self.assertNotIn("voice-lab", PANEL_SRC)+ # The resolver looks at exactly two places: the engine venv's own bin+ # (what the installer script fills) and the ordinary tool resolver+ # (env override, PATH, Pinokio's folders, Homebrew). Anything else+ # would be a path this project cannot install into.+ body = PANEL_SRC.split("def _resolve_demucs")[1].split("\ndef ")[0]+ self.assertIn('HELPER_PYTHON.parent / "demucs"', body)+ self.assertIn('_resolve_tool("demucs", "PHOSPHENE_DEMUCS")', body)+ self.assertNotIn("/Users/", body)++ def test_the_installer_script_exists_and_parses(self):+ script = Path(__file__).with_name("scripts") / "pinokio" / "a2v_stems_deps.sh"+ self.assertTrue(script.is_file())+ self.assertTrue(os.access(script, os.X_OK), "not executable")+ self.assertEqual(+ subprocess.run(["bash", "-n", str(script)]).returncode, 0)++ def test_the_note_points_at_the_installer(self):+ self.assertIn("a2v_stems_deps.sh", P.A2V_STEM_MISSING_NOTE)+++class TheStemNeverReachesTheAudience(unittest.TestCase):++ def test_make_job_carries_both_stem_fields(self):+ job = P.make_job({"mode": "a2v", "prompt": "a face", "audio": "/x.wav",+ "audio_stem": "/y.wav", "audio_stem_auto": "on"})+ self.assertEqual(job["params"]["audio_stem"], "/y.wav")+ self.assertEqual(job["params"]["audio_stem_auto"], "on")++ def test_the_stem_goes_through_the_paste_cleaner(self):+ self.assertIn("audio_stem", P.PASTED_PATH_FIELDS)++ def test_the_helper_is_handed_the_conditioning_file(self):+ self.assertIn('"audio_path": cond_audio,', PANEL_SRC)++ def test_the_original_is_muxed_back_when_they_differ(self):+ self.assertIn("if cond_audio != audio_src:", PANEL_SRC)+ self.assertIn("a2v_mux_original_audio(", PANEL_SRC)++ def test_the_mux_copies_the_video_stream(self):+ # A container edit, not a second render.+ src = PANEL_SRC.split("def a2v_mux_original_audio")[1].split("\ndef ")[0]+ self.assertIn('"-c:v", "copy"', src)+++class TheBoardCarriesTheStem(unittest.TestCase):++ def _board(self, **kw):+ sections = [{"start": 0.0, "end": 24.0, "kind": "vocal", "name": "v"}]+ images = [{"path": "/u/face.png", "role": "singer"},+ {"path": "/u/room.png", "role": "room"}]+ return mv.plan_music_video(sections, images, style="warm 16mm",+ bpm_grid={}, song="/o/song.wav", **kw)++ def test_a_singing_shot_carries_the_stem_and_b_roll_does_not(self):+ out = self._board(vocal_stem="/o/vocals.wav")+ sing = [s for s in out["shots"] if s["music_video"]["kind"] == "singing"]+ broll = [s for s in out["shots"] if s["music_video"]["kind"] == "broll"]+ self.assertTrue(sing)+ for s in sing:+ self.assertEqual(s["audio_stem"], "/o/vocals.wav")+ for s in broll:+ self.assertNotIn("audio_stem", s)+ self.assertEqual(out["board"]["music_video"]["vocal_stem"],+ "/o/vocals.wav")++ def test_no_stem_means_no_key_at_all(self):+ out = self._board()+ for s in out["shots"]:+ self.assertNotIn("audio_stem", s)+ self.assertEqual(out["board"]["music_video"]["vocal_stem"], "")++ def test_the_stem_moves_nothing_about_the_clock(self):+ # The stem is the whole song, separated: a shot's audio_start_time+ # means the same second in both files, so the tiling must be identical.+ plain = self._board()+ stemmed = self._board(vocal_stem="/o/vocals.wav")+ self.assertEqual(+ [(s["n"], s["duration_s"], s.get("audio_start_time"))+ for s in plain["shots"]],+ [(s["n"], s["duration_s"], s.get("audio_start_time"))+ for s in stemmed["shots"]])++ def test_shot_to_job_maps_the_stem_on_a2v_and_nowhere_else(self):+ pol = storyboard.default_policy()["final"]+ shot = {"n": 1, "mode": "a2v", "prompt": "she sings",+ "duration_s": 5.0, "audio": "/o/song.wav",+ "audio_start_time": 12.0, "audio_stem": "/o/vocals.wav",+ "still": "/u/face.png", "engine": "ltx"}+ job = storyboard.shot_to_job(shot, pol)+ self.assertEqual(job["audio_stem"], "/o/vocals.wav")+ self.assertEqual(job["audio"], "/o/song.wav")+ self.assertEqual(job["audio_start_time"], "12.0")+ text = storyboard.shot_to_job(+ {"n": 2, "mode": "text", "prompt": "a room", "duration_s": 5.0,+ "engine": "ltx", "audio_stem": "/o/vocals.wav"}, pol)+ self.assertNotIn("audio_stem", text)+++# ---------------------------------------------------------------------------+# 3. THE PROMPT RULES FOR A SINGING SHOT+# ---------------------------------------------------------------------------+class StillnessIsTheLipSyncKiller(unittest.TestCase):+ """LTX reads a stillness word as "nothing moves" - lips included."""++ BANNED = (+ "The camera holds a static shot, the frame never moves.",+ "a static hold on the stage",+ "she holds perfectly still at the microphone",+ "he stands still, singing",+ "the singer barely moves",+ "with no new movement of any kind",+ "she is motionless",+ "a freeze frame of the band",+ "nothing in the scene moves",+ "she does not move",+ )++ def test_every_banned_phrase_is_reported(self):+ for line in self.BANNED:+ with self.subTest(line=line):+ self.assertTrue(storyboard.a2v_stillness_problems(line), line)++ def test_a_cleaned_prompt_reports_nothing(self):+ for line in self.BANNED:+ with self.subTest(line=line):+ cleaned = storyboard.a2v_prompt(line)+ self.assertEqual(storyboard.a2v_stillness_problems(cleaned), [],+ cleaned)++ def test_still_as_an_adverb_is_not_a_freeze_frame(self):+ # This list BLOCKS a render, so a false positive is expensive.+ for line in ("the coffee is still hot, she sings",+ "a still life of flowers on the piano",+ "she is still singing when the lights come up"):+ with self.subTest(line=line):+ self.assertEqual(storyboard.a2v_stillness_problems(line), [])++ def test_a_camera_clause_is_deleted_and_a_person_clause_is_rewritten(self):+ # Two different treatments, on purpose: an audio-driven shot does not+ # want a camera restraint sentence at all, but a clause about a person+ # has to keep its subject.+ got = storyboard.a2v_clean_prompt(+ "The camera holds a static shot, the frame never moves - no pan, "+ "no push-in, no reframing. She stands still at the microphone, singing.")+ self.assertNotIn("camera", got.lower())+ self.assertIn("She stands steady at the microphone", got)+ self.assertIn("singing", got)++ def test_the_planners_canonical_sentences_are_the_ones_it_kills(self):+ # Not a hypothetical list: these are the strings storyboard_planner+ # writes mechanically onto every shot.+ self.assertTrue(storyboard.a2v_stillness_problems(+ storyboard_planner._CAMERA_SENTENCES["static"]))+ self.assertTrue(storyboard.a2v_stillness_problems(+ "for the last two seconds she is still, with no new movement of any kind"))+++class TheSyncContractSurvivesEverything(unittest.TestCase):++ def test_the_contract_is_literal_and_says_lip_sync(self):+ self.assertIn("lip-syncs every vocal syllable to the supplied "+ "soundtrack", storyboard.A2V_SYNC_CONTRACT)++ def test_it_is_appended_last(self):+ got = storyboard.a2v_prompt("close-up, singing to camera, warm 16mm")+ self.assertTrue(got.endswith(storyboard.A2V_SYNC_CONTRACT), got)++ def test_it_is_not_collected_twice(self):+ once = storyboard.a2v_prompt("close-up, singing to camera")+ self.assertEqual(storyboard.a2v_prompt(once), once)+ self.assertEqual(once.count("lip-syncs"), 1)++ def test_a_silent_window_gets_relaxed_closed_lips_instead(self):+ got = storyboard.a2v_prompt("wide, the band plays", silent=True)+ self.assertIn("relaxed closed lips", got)+ self.assertNotIn("lip-syncs", got)++ def test_an_empty_direction_is_still_a_contract(self):+ self.assertEqual(storyboard.a2v_prompt(""),+ storyboard.A2V_SYNC_CONTRACT)++ def test_compose_shot_prompt_is_the_last_line_of_defence(self):+ # A board planned before this law existed, or hand-edited since, still+ # reaches the model with the contract on it.+ shot = {"n": 1, "mode": "a2v", "audio": "/o/s.wav",+ "prompt": "she holds perfectly still and sings"}+ got = storyboard.compose_shot_prompt(shot)+ self.assertIn("lip-syncs", got)+ self.assertEqual(storyboard.a2v_stillness_problems(got), [])+ # And it does not touch a shot that is not audio-driven.+ plain = storyboard.compose_shot_prompt(+ {"n": 2, "mode": "text", "prompt": "she holds perfectly still"})+ self.assertNotIn("lip-syncs", plain)++ def test_the_last_line_of_defence_does_not_cap(self):+ # Capping a FINISHED prompt would delete the face law and the style.+ long_prompt = ("a woman at a microphone, " * 20).rstrip(", ")+ shot = {"n": 1, "mode": "a2v", "audio": "/o/s.wav",+ "prompt": long_prompt + ". " + storyboard.A2V_SYNC_CONTRACT}+ got = storyboard.compose_shot_prompt(shot)+ self.assertGreater(len(got.split()), storyboard.A2V_MAX_WORDS)+++class TheDirectionIsShort(unittest.TestCase):++ def test_the_creative_direction_is_capped(self):+ long_line = ", ".join(f"detail number {i}" for i in range(40))+ got = storyboard.a2v_direction(long_line)+ self.assertLessEqual(len(got.split()), storyboard.A2V_MAX_WORDS)++ def test_the_cap_falls_on_a_clause_boundary(self):+ long_line = ", ".join(f"detail number {i}" for i in range(40))+ got = storyboard.a2v_direction(long_line)+ # No half-clause left hanging for the model to finish by inventing.+ self.assertTrue(got.endswith("."), got)+ self.assertNotIn(",,", got)++ def test_a_short_line_is_left_exactly_alone(self):+ self.assertEqual(storyboard.a2v_direction("close-up, singing to camera"),+ "close-up, singing to camera")++ def test_no_cap_means_no_cap(self):+ long_line = ", ".join(f"detail number {i}" for i in range(40))+ self.assertEqual(storyboard.a2v_direction(long_line, None), long_line)+++class ValidationNoLongerSkipsA2V(unittest.TestCase):++ def _board(self, prompt):+ board = storyboard.new_storyboard("sb_test", "T", shots=[{+ "n": 1, "title": "S01", "mode": "a2v", "engine": "ltx",+ "prompt": prompt, "duration_s": 10.0, "seed": -1, "refs": [],+ "audio": "/o/s.wav", "audio_start_time": 0.0, "status": "pending"}])+ return storyboard.validate_storyboard_detail(board)++ def test_a_stillness_word_is_an_error_now(self):+ errs = self._board("she holds perfectly still, singing to camera. "+ + storyboard.A2V_SYNC_CONTRACT)+ codes = [e["code"] for e in errs]+ self.assertIn("a2v_stillness", codes)+ hit = next(e for e in errs if e["code"] == "a2v_stillness")+ self.assertEqual(hit["n"], 1)+ self.assertEqual(hit["field"], "prompt")+ self.assertIn("holds perfectly still", hit["message"])++ def test_a_clean_singing_shot_passes(self):+ self.assertEqual(+ self._board(storyboard.a2v_prompt("close-up, singing to camera")),+ [])++ def test_the_old_exemptions_are_still_exemptions(self):+ # The words an a2v mouth says are a WAVEFORM, so the speech and pacing+ # laws still do not apply - only the stillness law was added.+ codes = [e["code"] for e in+ self._board(storyboard.a2v_prompt("close-up, singing to camera"))]+ self.assertNotIn("speech_without_words", codes)+ self.assertNotIn("dialogue_does_not_fit", codes)++ def test_a_planned_music_video_validates(self):+ sections = [{"start": 0.0, "end": 40.0, "kind": "vocal", "name": "v"}]+ images = [{"path": "/u/face.png", "role": "singer"},+ {"path": "/u/room.png", "role": "room"}]+ out = mv.plan_music_video(sections, images, style="warm 16mm",+ bpm_grid={}, song="/o/s.wav",+ board_id="sb_mv")+ self.assertEqual(storyboard.validate_storyboard(out["board"]), [])+++class ThePlannerStopsWritingTheKiller(unittest.TestCase):++ def test_an_a2v_body_gets_a_locked_tripod_not_a_frozen_scene(self):+ got = storyboard_planner._compose_body(+ "A woman at a microphone", "static", "she is still", "close",+ "a2v")+ self.assertEqual(storyboard.a2v_stillness_problems(got), [], got)+ self.assertIn("locked in place", got)+ self.assertIn("lips and jaw work clearly", got)++ def test_the_settle_clause_is_not_written_on_an_a2v_shot(self):+ got = storyboard_planner._compose_body(+ "A woman at a microphone", "static",+ "she is quiet with her hands on the stand", "close", "a2v")+ self.assertNotIn("completely finished before the shot ends", got)++ def test_an_ordinary_shot_is_untouched(self):+ got = storyboard_planner._compose_body(+ "A woman at a microphone", "static",+ "she is quiet with her hands on the stand", "close")+ self.assertIn(storyboard_planner._CAMERA_SENTENCES["static"], got)+ self.assertIn("completely finished before the shot ends", got)++ def test_the_contract_lands_after_the_style_and_the_audio_line(self):+ got = storyboard_planner._assemble_ltx_prompt(+ "A woman at a microphone, singing", "room tone",+ "1990s broadcast video", "static", "she is still", "close", "a2v")+ self.assertTrue(got.endswith(storyboard.A2V_SYNC_CONTRACT), got)+ self.assertIn("1990s broadcast video", got)+ self.assertIn("Audio: room tone", got)+ self.assertEqual(storyboard.a2v_stillness_problems(got), [])++ def test_the_face_law_survives_the_cap(self):+ got = storyboard_planner._assemble_ltx_prompt(+ ", ".join(f"detail number {i}" for i in range(40)), "room tone",+ "warm 16mm", "static", "", "close", "a2v")+ self.assertIn("holds the exact angle", got)++ def test_a_reassembly_keeps_the_shot_s_own_mode(self):+ shot = {"mode": "a2v", "engine": "ltx",+ "description": "A woman at a microphone, singing",+ "soundscape": "room tone", "camera": "static",+ "settle": "she is still", "face": "close"}+ got = storyboard_planner._reassemble_prompt(shot, "warm 16mm", (), None)+ self.assertTrue(got.endswith(storyboard.A2V_SYNC_CONTRACT), got)+ self.assertEqual(storyboard.a2v_stillness_problems(got), [])+++class TheMusicVideoWritesSafeSingingShots(unittest.TestCase):++ def _plan(self, sections=None, **kw):+ sections = sections or [{"start": 0.0, "end": 40.0, "kind": "vocal",+ "name": "v"}]+ images = [{"path": "/u/face.png", "role": "singer"},+ {"path": "/u/room.png", "role": "room"}]+ return mv.plan_music_video(sections, images, style="warm 16mm",+ bpm_grid={}, song="/o/s.wav", **kw)++ def test_every_singing_shot_carries_the_contract_and_no_stillness(self):+ out = self._plan()+ sang = 0+ for shot in out["shots"]:+ if shot["music_video"]["kind"] == "singing":+ self.assertIn("lip-syncs", shot["prompt"])+ self.assertEqual(+ storyboard.a2v_stillness_problems(shot["prompt"]), [])+ sang += 1+ self.assertTrue(sang)++ def test_b_roll_gets_no_contract_because_it_has_no_waveform(self):+ out = self._plan()+ for shot in out["shots"]:+ if shot["music_video"]["kind"] == "broll":+ self.assertNotIn("lip-syncs", shot["prompt"])++ def test_a_per_shot_line_is_made_safe_too(self):+ # The override replaces the direction; it must not be a way around the+ # law, or the one shot somebody cared enough to write by hand is the+ # one that freezes.+ out = self._plan(shot_prompts={1: "she holds perfectly still and sings"})+ first = out["shots"][0]+ self.assertEqual(first["music_video"]["kind"], "singing")+ self.assertIn("lip-syncs", first["prompt"])+ self.assertEqual(storyboard.a2v_stillness_problems(first["prompt"]), [])++ def test_a_silent_window_is_told_to_close_the_mouth(self):+ self.assertIn("relaxed closed lips",+ mv._prompt_for({"path": "/u/f.png", "role": "singer"},+ "singing", "warm 16mm", silent=True))++ def test_vocal_activity_is_read_off_the_sections(self):+ sections = [{"start": 0.0, "end": 30.0, "kind": "vocal"},+ {"start": 30.0, "end": 60.0, "kind": "instrumental"}]+ self.assertFalse(mv.slice_is_silent(sections, 5.0, 15.0))+ self.assertTrue(mv.slice_is_silent(sections, 40.0, 50.0))+ # A window that straddles counts as singing: a mouth that sings+ # slightly too long reads far better than one that stops mid-line.+ self.assertFalse(mv.slice_is_silent(sections, 25.0, 35.0))+ self.assertTrue(mv.slice_is_silent(sections, 29.0, 60.0))+++# ---------------------------------------------------------------------------+# 4. THE FACE-TIGHT PICTURE SINGS THE CLOSE SHOTS+# ---------------------------------------------------------------------------+class TheBiggestFaceLeadsTheSinging(unittest.TestCase):+ """A mouth at a quarter of the frame is mush; at half of it, legible."""++ WIDE = {"path": "/u/wide.png", "role": "singer", "face_frac": 0.23}+ TIGHT = {"path": "/u/tight.png", "role": "singer", "face_frac": 0.46}+ ROOM = {"path": "/u/room.png", "role": "room"}++ def _plan(self, images, **kw):+ sections = [{"start": 0.0, "end": 60.0, "kind": "vocal", "name": "v"}]+ return mv.plan_music_video(sections, images, style="warm 16mm",+ bpm_grid={}, song="/o/s.wav", **kw)++ def _singing(self, out):+ return [s["music_video"]["image"] for s in out["shots"]+ if s["music_video"]["kind"] == "singing"]++ def test_the_biggest_measured_face_opens_the_rotation(self):+ out = self._plan([self.WIDE, self.TIGHT, self.ROOM])+ self.assertEqual(self._singing(out)[0], "/u/tight.png")+ self.assertTrue(any("biggest face" in n for n in out["notes"]))++ def test_the_rotation_still_alternates(self):+ # Biggest first is about WHO LEADS, not about shooting one picture for+ # the whole song - the angle still has to change.+ got = self._singing(self._plan([self.WIDE, self.TIGHT, self.ROOM]))+ self.assertGreater(len(set(got)), 1)+ self.assertEqual(got[0], "/u/tight.png")+ self.assertEqual(got[1], "/u/wide.png")++ def test_a_use_pin_means_the_caller_decided_and_nothing_is_reordered(self):+ images = [dict(self.WIDE, use="open"), self.TIGHT, self.ROOM]+ got = self._singing(self._plan(images))+ self.assertEqual(got[0], "/u/wide.png")+ self.assertFalse(any("biggest face" in n for n in self._plan(images)["notes"]))++ def test_a_per_shot_image_pin_wins_outright(self):+ out = self._plan([self.WIDE, self.TIGHT, self.ROOM],+ shot_images={1: "/u/wide.png"})+ self.assertEqual(self._singing(out)[0], "/u/wide.png")+ self.assertFalse(any("biggest face" in n for n in out["notes"]))++ def test_unmeasured_pictures_keep_the_order_they_were_given(self):+ a = {"path": "/u/a.png", "role": "singer"}+ b = {"path": "/u/b.png", "role": "singer"}+ got = self._singing(self._plan([a, b, self.ROOM]))+ self.assertEqual(got[0], "/u/a.png")++ def test_a_measured_face_leads_the_unmeasured_ones(self):+ a = {"path": "/u/a.png", "role": "singer"}+ got = self._singing(self._plan([a, self.TIGHT, self.ROOM]))+ self.assertEqual(got[0], "/u/tight.png")++ def test_a_pin_moves_who_is_in_frame_and_never_the_clock(self):+ plain = self._plan([self.WIDE, self.TIGHT, self.ROOM])+ pinned = self._plan([self.WIDE, self.TIGHT, self.ROOM],+ shot_images={2: "/u/tight.png"})+ self.assertEqual(+ [(s["n"], s["duration_s"], s.get("audio_start_time"))+ for s in plain["shots"]],+ [(s["n"], s["duration_s"], s.get("audio_start_time"))+ for s in pinned["shots"]])++ def test_a_pin_to_a_picture_outside_the_cast_is_a_note_not_a_refusal(self):+ out = self._plan([self.WIDE, self.TIGHT, self.ROOM],+ shot_images={1: "/u/stranger.png"})+ self.assertTrue(any("stranger.png" in n for n in out["notes"]))+ self.assertEqual(self._singing(out)[0], "/u/tight.png")++ def test_face_frac_is_never_invented_from_the_picture(self):+ # The cheap proxies (aspect, short side) cannot tell a 1:1 crop of a+ # face from a 1:1 crop of a room, so a picture nobody measured has no+ # number at all rather than a made-up one.+ for raw in (None, "", "banana", 0, -1, [], float("nan")):+ with self.subTest(raw=raw):+ self.assertIsNone(mv._face_frac(raw))+ self.assertEqual(mv._face_frac("0.46"), 0.46)+ self.assertEqual(mv._face_frac(2.0), 1.0)++ def test_the_cast_carries_the_measurement_through(self):+ cast = mv._cast([self.TIGHT, self.ROOM])+ self.assertEqual(cast[0]["face_frac"], 0.46)+ self.assertIsNone(cast[1]["face_frac"])+++class TheRouteTakesTheMeasurementAndThePin(unittest.TestCase):++ def test_a_face_frac_outside_zero_to_one_is_refused_by_name(self):+ rows, err = routes_music._music_video_images(json.dumps(+ [{"path": "/etc/passwd", "role": "singer", "face_frac": 4}]))+ self.assertEqual(rows, [])+ self.assertTrue(err)++ def test_a_row_that_pins_only_a_picture_is_not_an_empty_prompt(self):+ prompts, err = routes_music._music_video_shot_prompts(+ json.dumps([{"n": 3, "image": "/u/face.png"}]))+ self.assertEqual((prompts, err), ({}, ""))++ def test_a_row_that_says_nothing_at_all_is_still_refused(self):+ prompts, err = routes_music._music_video_shot_prompts(+ json.dumps([{"n": 3, "prompt": " "}]))+ self.assertEqual(prompts, {})+ self.assertIn("empty", err)++ def test_a_pinned_picture_obeys_the_containment_rule(self):+ pins, err = routes_music._music_video_shot_images(+ json.dumps([{"n": 3, "image": "/etc/passwd"}]))+ self.assertEqual(pins, {})+ self.assertIn("/etc/passwd", err)+ self.assertIn("uploads", err)+class JobsSavedBeforeTheFix(unittest.TestCase):"""A job queued or finished under 4.15.1 carries the old make_job's floatdiff --git a/test_control_discoverability.py b/test_control_discoverability.pyindex 714036d..6489225 100644--- a/test_control_discoverability.py+++ b/test_control_discoverability.py@@ -259,10 +259,11 @@ class TestSourceDerivedCanvasRidesTheEngineGrid(unittest.TestCase):def test_make_job_shares_the_same_helper(self):"""One rule, one function — or the day the grid changes, two of thethree lanes learn about it."""- # one def + six call sites: make_job, Control, Colorize, Upscale &- # Face Fix (the worker and the one-click admission check), and the H3- # form's after-the-draft export note (same rule, same helper).- self.assertEqual(PANEL_SRC.count("ltx_floor_canvas("), 7)+ # one def + seven call sites: make_job, Control, Colorize, Upscale &+ # Face Fix (the worker and the one-click admission check), the H3+ # form's after-the-draft export note (same rule, same helper), and+ # ltx_fit_canvas, which every hardware clamp goes through.+ self.assertEqual(PANEL_SRC.count("ltx_floor_canvas("), 8)class TestTheDocumentation(unittest.TestCase):diff --git a/test_download_cancel.py b/test_download_cancel.pynew file mode 100644index 0000000..c918f94--- /dev/null+++ b/test_download_cancel.py@@ -0,0 +1,197 @@+"""Cancel stops a model download — it does not restart it (Codex INST-07 / JOB-05),+and Repair deletes nothing it cannot re-download (INST-11).++/models/cancel killed the downloader but never told the worker, which read the+killed attempt as a FAILED one and started the next attempt 5-10 s later; a+cancel during that backoff signalled a process that had already exited and did+nothing. Every process here is a fake; nothing is spawned or downloaded.+"""+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 P # noqa: E402++routes_models = sys.modules["panel.routes_models"]+++class _H:+ def __init__(self):+ self.status = self.payload = None++ def _json(self, payload, status=200):+ self.payload, self.status = payload, status+++def _cancel():+ h = _H()+ routes_models.post_models_cancel(h, "/models/cancel", {}, "")+ return h+++class _Out:+ def __init__(self, on_read=None):+ self.on_read, self.done = on_read, False++ def read(self, n):+ if not self.done:+ self.done = True+ if self.on_read:+ self.on_read()+ return "progress 10%\n"+ return ""+++class _Proc:+ def __init__(self, rc, on_read=None):+ self.pid, self.rc, self.stdout = 4242, rc, _Out(on_read)++ def wait(self, timeout=None):+ return self.rc+++class CancelStopsTheDownload(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.killed = []+ self.sleep_hook = None++ def _sleep(_s):+ if self.sleep_hook:+ hook, self.sleep_hook = self.sleep_hook, None+ hook()+ self._patches = [+ mock.patch.object(P, "ROOT", Path(self.tmp.name)),+ mock.patch.object(P, "HF_BIN", Path("/nonexistent/hf")),+ mock.patch.object(P, "push", lambda *a, **k: None),+ mock.patch.object(P, "_active_hf_token", lambda: None),+ mock.patch.object(P.time, "sleep", _sleep),+ mock.patch.object(P.os, "getpgid", lambda pid: 777),+ mock.patch.object(P.os, "killpg", lambda pg, sig: self.killed.append(pg)),+ ]+ for p in self._patches:+ p.start()+ with P.DOWNLOAD_LOCK:+ P.DOWNLOAD.update(active=True, key="q4", repo_id="x/y", cancelled=False)+ self.repo = {"key": "q4", "repo_id": "x/y", "local_dir": "models/q4"}++ def tearDown(self):+ for p in reversed(self._patches):+ p.stop()+ with P.DOWNLOAD_LOCK:+ P.DOWNLOAD.update(active=False, key=None, repo_id=None, proc=None,+ pgid=None, cancelled=False)+ self.tmp.cleanup()++ def _run(self, procs):+ it = iter(procs)+ with mock.patch.object(P.subprocess, "Popen", side_effect=lambda *a, **k: next(it)()) as pop:+ P._download_thread(self.repo)+ return pop.call_count++ def test_cancel_during_an_attempt_does_not_retry(self):+ calls = self._run([lambda: _Proc(-15, on_read=_cancel)] + [lambda: _Proc(0)] * 2)+ self.assertEqual(calls, 1)+ self.assertEqual(self.killed, [777])++ def test_cancel_during_backoff_does_not_retry(self):+ self.sleep_hook = _cancel+ calls = self._run([lambda: _Proc(1)] + [lambda: _Proc(0)] * 2)+ self.assertEqual(calls, 1)++ def test_cancel_between_spawn_and_registration_kills_the_new_group(self):+ def spawn_after_cancel():+ _cancel() # lands while no process is registered+ return _Proc(-15)+ calls = self._run([spawn_after_cancel, lambda: _Proc(0), lambda: _Proc(0)])+ self.assertEqual(calls, 1)+ self.assertIn(777, self.killed)++ def test_the_slot_is_released_clean_for_the_next_download(self):+ self._run([lambda: _Proc(-15, on_read=_cancel)])+ with P.DOWNLOAD_LOCK:+ self.assertFalse(P.DOWNLOAD["active"])+ self.assertFalse(P.DOWNLOAD["cancelled"])+ # and an uncancelled download that fails once still retries+ with P.DOWNLOAD_LOCK:+ P.DOWNLOAD.update(active=True, key="q4", repo_id="x/y")+ self.assertEqual(self._run([lambda: _Proc(1), lambda: _Proc(0)]), 2)+++class RepairDeletesNothingUntilItCanDownload(unittest.TestCase):+ """Codex INST-11: Repair unlinked the corrupt files and only THEN found the+ download slot busy, answering 409 with nothing started to replace them."""++ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ root = Path(self.tmp.name)+ self.f = root / "models" / "q4" / "model.safetensors"+ self.f.parent.mkdir(parents=True)+ self.f.write_bytes(b"x" * 10)+ self.started = []+ repo = {"key": "q4", "repo_id": "x/y", "local_dir": "models/q4"}+ self._patches = [+ mock.patch.object(P, "ROOT", root),+ mock.patch.object(P, "HF_BIN", Path("/nonexistent/hf")),+ mock.patch.object(P, "push", lambda *a, **k: None),+ mock.patch.object(P, "h3_status_invalidate", lambda: None),+ mock.patch.object(P, "_repos", lambda: [repo]),+ mock.patch.object(P, "_model_integrity", lambda force=False: {"bad": []}),+ mock.patch.object(P.threading, "Thread",+ lambda target=None, args=(), daemon=None: mock.Mock(+ start=lambda: self.started.append(args))),+ ]+ for p in self._patches:+ p.start()+ self._dv = P._DEEP_VERIFY.get("result")+ P._DEEP_VERIFY["result"] = {"bad": [{"repo": "q4", "file": "model.safetensors"},+ {"repo": "gemma", "file": "g.safetensors"}]}++ def tearDown(self):+ for p in reversed(self._patches):+ p.stop()+ P._DEEP_VERIFY["result"] = self._dv+ with P.DOWNLOAD_LOCK:+ P.DOWNLOAD.update(active=False, key=None, repo_id=None, started_ts=None,+ last_line="", cancelled=False)+ self.tmp.cleanup()++ def _repair(self):+ h = _H()+ h._read_form_body = lambda: ("repo_key=q4", {"repo_key": ["q4"]})+ routes_models.post_models_repair(h, "/models/repair", {}, "")+ return h++ def test_busy_slot_deletes_nothing(self):+ with P.DOWNLOAD_LOCK:+ P.DOWNLOAD.update(active=True, repo_id="other/pack")+ h = self._repair()+ self.assertEqual(h.status, 409)+ self.assertTrue(self.f.exists(), "Repair deleted a file it could not re-download")+ self.assertEqual(self.started, [])++ def test_a_repeat_repair_does_not_reuse_the_consumed_deep_check(self):+ h = self._repair()+ self.assertEqual(h.status, 202, h.payload)+ self.assertFalse(self.f.exists())+ self.assertEqual(len(self.started), 1)+ # the re-download landed a good copy; the old deep-check verdict must+ # not delete it again+ self.f.write_bytes(b"good" * 3)+ with P.DOWNLOAD_LOCK:+ P.DOWNLOAD.update(active=False)+ h = self._repair()+ self.assertTrue(h.payload.get("nothing_to_repair"), h.payload)+ self.assertTrue(self.f.exists())+ self.assertEqual([b["repo"] for b in P._DEEP_VERIFY["result"]["bad"]], ["gemma"])+++if __name__ == "__main__":+ unittest.main()diff --git a/test_editor_film_switcher.py b/test_editor_film_switcher.pynew file mode 100644index 0000000..535bed8--- /dev/null+++ b/test_editor_film_switcher.py@@ -0,0 +1,131 @@+#!/usr/bin/env python3+"""The Editor's name is the way to another film.++Observed alongside the 2026-09-24 review: the title in the Editor's header+looked like a control and did nothing, and the list of films sat behind the+full-screen Editor with ⋯ → Close as the only way back to it. The title now+drops the films that have clips; picking one goes through the ordinary door+(`edOpenBoard`), which backs up unsaved work the way Close does.++The switcher's functions run for real in node; the markup and the global+publication are checked in the served sources, because an onclick naming a+function the module did not publish is a silent no-op in the browser.+"""+from __future__ import annotations++import re+import sys+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT / "scripts"))++from extract_panel_js import extract_function, panel_source # noqa: E402++from test_editor_save_integrity import run # noqa: E402+++class TheTitleSwitchesFilms(unittest.TestCase):++ @classmethod+ def setUpClass(cls) -> None:+ cls.src = panel_source()+ cls.r = run(r"""+SBE.open = true; SBE.id = 'sb_a';+els.sbeFilmsMenu = stubEl('sbeFilmsMenu', true);+FETCHES = [];+NEXT = { status: 200, body: { boards: [+ { id: 'sb_a', title: 'Night Drive', clips: 3 },+ { id: 'sb_b', title: 'Divorce <v2>', clips: 1 },+ { id: 'sb_c', title: 'Not rendered yet', clips: 0 } ] } };+await sbeFilmsToggle();+out.asked = FETCHES.map(f => f.url);+out.open = !els.sbeFilmsMenu.hidden;+out.html = els.sbeFilmsList.innerHTML;+out.noteHidden = els.sbeFilmsNote.hidden;+sbeFilmsPick('sb_a');+sbeFilmsPick('sb_b');+out.opened = opened.slice();+out.closedAfterPick = els.sbeFilmsMenu.hidden;+// A second press closes it without asking the panel again.+FETCHES = [];+await sbeFilmsToggle();+await sbeFilmsToggle();+out.toggledShut = els.sbeFilmsMenu.hidden;+out.askedOnClose = FETCHES.length;+sbeFilmsAll();+out.allClosed = closes;+// Alone: says so instead of offering an empty list.+NEXT = { status: 200, body: { boards: [{ id: 'sb_a', title: 'Night Drive', clips: 3 }] } };+els.sbeFilmsMenu.hidden = true;+await sbeFilmsToggle();+out.aloneNote = [els.sbeFilmsNote.hidden, els.sbeFilmsNote.textContent];+""", extra=("sbeFilmsToggle", "sbeFilmsPick", "sbeFilmsAll"), shim=r"""+const opened = [];+let closes = 0;+function edOpenBoard(id) { opened.push(id); }+function sbeClose() { closes++; }+function sbePopToggle(id) { const el = sbeEl(id); el.hidden = !el.hidden; }+function sbePopCloseAll() { sbeEl('sbeFilmsMenu').hidden = true; }+function escapeHtml(s) {+ return String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&',+ '<': '<', '>': '>', '"': '"', "'": ''' })[c]);+}+""")++ def test_the_title_is_a_button_that_opens_the_film_list(self):+ btn = re.search(r'<button[^>]*id="sbeFilmsBtn"[^>]*>(.*?)</button>',+ self.src, re.S)+ self.assertIsNotNone(btn)+ self.assertIn('onclick="sbeFilmsToggle()"', btn.group(0))+ self.assertIn('aria-haspopup="menu"', btn.group(0))+ # The name the client writes into is still there, inside it.+ self.assertIn('id="sbeTitle">Editor<', btn.group(1))+ self.assertIn('id="sbeFilmsMenu"', self.src)++ def test_it_lists_the_films_with_clips_and_marks_the_open_one(self):+ self.assertEqual(self.r["asked"], ["/storyboard/list"])+ self.assertTrue(self.r["open"])+ html = self.r["html"]+ self.assertIn("Night Drive", html)+ self.assertIn("Divorce <v2>", html) # escaped+ self.assertNotIn("Not rendered yet", html)+ self.assertEqual(html.count('aria-current="true"'), 1)+ self.assertIn("sbeFilmsPick('sb_b')", html)+ self.assertTrue(self.r["noteHidden"])++ def test_picking_another_film_opens_it_and_the_open_one_is_a_no_op(self):+ self.assertEqual(self.r["opened"], ["sb_b"])+ self.assertTrue(self.r["closedAfterPick"])++ def test_it_toggles_and_has_a_way_to_every_film(self):+ self.assertTrue(self.r["toggledShut"])+ self.assertEqual(self.r["askedOnClose"], 1)+ self.assertEqual(self.r["allClosed"], 1)+ self.assertIn('onclick="sbeFilmsAll()"', self.src)++ def test_alone_it_says_so(self):+ hidden, text = self.r["aloneNote"]+ self.assertFalse(hidden)+ self.assertIn("No other", text)++ def test_the_menu_is_one_of_the_popovers_and_its_verbs_are_global(self):+ pops = self.src[self.src.index("const SBE_POPS = ["):]+ self.assertIn("'sbeFilmsMenu'", pops[:pops.index("];")])+ publish = self.src[self.src.index("Object.assign(globalThis, {\n sbeStripY"):]+ publish = publish[:publish.index("});")]+ for name in ("sbeFilmsToggle", "sbeFilmsPick", "sbeFilmsAll"):+ self.assertRegex(publish, r"\b%s\b" % name)++ def test_leaving_through_it_backs_up_like_close(self):+ # The one door: edOpenBoard -> sbeOpen -> sbeCloseDoc, which backs up+ # a dirty document before it lets go of it.+ self.assertIn("edOpenBoard(id)", extract_function("sbeFilmsPick", self.src))+ self.assertIn("sbeCloseDoc({ quiet: true })",+ extract_function("sbeOpen", self.src))+ self.assertIn("sbeBackup(true)", extract_function("sbeCloseDoc", self.src))+++if __name__ == "__main__":+ unittest.main()diff --git a/test_editor_save_integrity.py b/test_editor_save_integrity.pynew file mode 100644index 0000000..c78a9e6--- /dev/null+++ b/test_editor_save_integrity.py@@ -0,0 +1,435 @@+#!/usr/bin/env python3+"""What the Editor sends, and WHEN it believes it: the save lane, driven.++`test_storyboard_editor_ui.py` locks the arrangement maths and each guard of+the save lane on its own. This file locks the SEAMS between them — the places+the 2026-09-24 review found work going missing while every guard passed:++ * SB5-01 the save and the backup both built their payload without the+ transitions, so every dissolve was discarded on Save.+ * SB5-02 a Save answered late marked edits made DURING it as saved, and+ dropped the second Save the user pressed.+ * SB5-14 a dependent action (Render, NLE export) read `'busy'` as "saved"+ and ran against the previous cut.+ * SB5-04 the save named no draft, so the server could not refuse one+ that landed on a draft another tab had switched to.+ * SB5-03 a load was adopted whenever it answered — another film's, or a+ quiet re-read of the SAVED file over unsaved work.+ * SB5-11 the soundtrack field kept the previous film's song, and Render+ posted it as an override for the next film.++Same method as the UI gate: the REAL functions, extracted and run in node, with+only the paint and the network stubbed.+"""+from __future__ import annotations++import json+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT / "scripts"))++from extract_panel_js import extract_function, panel_source # noqa: E402++import test_storyboard_editor_ui as ui # noqa: E402+++# A fetch that can be HELD: a request parks until the test releases it, which+# is the only way to put an edit, or a second Save, inside the window a slow+# save leaves open.+HELD_FETCH = r"""+const HELD = [];+let HOLD = false;+global.fetch = (url, opts) => {+ FETCHES.push({ url, body: opts && opts.body });+ const r = NEXT;+ const answer = { ok: r.status < 400, status: r.status, json: async () => r.body };+ if (!HOLD) return Promise.resolve(answer);+ return new Promise(res => HELD.push(() => res(answer)));+};+const tick = () => new Promise(r => setImmediate(r));+async function release() { const f = HELD.shift(); if (f) f(); for (let i = 0; i < 8; i++) await tick(); }+async function releaseAt(i) { const f = HELD.splice(i, 1)[0]; if (f) f(); for (let k = 0; k < 8; k++) await tick(); }+"""+++def run(body: str, extra: tuple = (), shim: str = "") -> dict:+ if ui.NODE is None:+ raise unittest.SkipTest("node not on PATH")+ source = panel_source()+ names = list(ui.FUNCTIONS) + [n for n in extra if n not in ui.FUNCTIONS]+ script = (ui.SHIM + HELD_FETCH + shim+ + "\n".join(extract_function(n, source) for n in names)+ + "\n(async () => {\nconst out = {};\n" + body+ + "\nprocess.stdout.write(JSON.stringify(out));\n})();\n")+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ path = Path(fh.name)+ try:+ res = subprocess.run([ui.NODE, str(path)], capture_output=True,+ text=True, timeout=60)+ if res.returncode:+ raise AssertionError(res.stdout + "\n" + res.stderr)+ if not res.stdout.strip():+ raise AssertionError("the contract never finished (a promise "+ "nobody resolved?)\n" + res.stderr)+ return json.loads(res.stdout)+ finally:+ path.unlink(missing_ok=True)+++# Two clips and a dissolve on the cut between them — the smallest timeline a+# transition can exist on.+TWO_CLIPS = r"""+function twoClips() {+ SBE.clips = lay([clip({ id: 'a', end: 2 }), clip({ id: 'b', end: 3 })]);+ SBE.edit = { clips: SBE.clips };+ SBE.transitions = sbeTxSet([], 'a', 'dissolve', 0.5).transitions;+ SBE.overlays = []; SBE.tracks = [];+ SBE.dirty = true; SBE.dirtyAt = 1; SBE.conflict = 0; SBE.saving = false;+ SBE.savePending = false; SBE.saveFailed = ''; SBE.revision = 1;+ els.sbeAlarm = { hidden: true }; els.sbeAlarmWhy = { textContent: '' };+}+"""+++class TransitionsTravel(unittest.TestCase):+ """SB5-01 — a dissolve on screen is a dissolve on disk."""++ @classmethod+ def setUpClass(cls) -> None:+ cls.r = run(TWO_CLIPS + r"""+twoClips();+FETCHES = [];+NEXT = { status: 200, body: { ok: true, edit: { revision: 2, clips: [] } } };+await sbeSave(false);+out.save = JSON.parse(FETCHES[0].body);+twoClips();+FETCHES = [];+NEXT = { status: 200, body: { ok: true } };+await sbeBackup(true);+out.backup = JSON.parse(FETCHES[0].body);+out.live = SBE.transitions;+""")++ def test_the_save_carries_the_transition(self):+ tx = self.r["save"]["edit"]["transitions"]+ self.assertEqual(len(tx), 1)+ self.assertEqual((tx[0]["after_clip"], tx[0]["kind"], tx[0]["duration"]),+ ("a", "dissolve", 0.5))++ def test_the_crash_backup_carries_the_transition(self):+ tx = self.r["backup"]["edit"]["transitions"]+ self.assertEqual([t["after_clip"] for t in tx], ["a"])++ def test_the_saved_document_keeps_it_through_the_server_model(self):+ # The payload, as the server's own model reads it back: the boundary+ # must still resolve between the two clips it was put on.+ import storyboard_editor as sedit # noqa: PLC0415+ doc = sedit.normalise_edit(self.r["save"]["edit"])+ self.assertEqual([t["after_clip"] for t in sedit.transition_items(doc)],+ ["a"])+++class SaveThatLandsLate(unittest.TestCase):+ """SB5-02 — a response describes the arrangement it was SENT with."""++ @classmethod+ def setUpClass(cls) -> None:+ cls.r = run(TWO_CLIPS + r"""+twoClips();+FETCHES = []; HOLD = true;+NEXT = { status: 200, body: { ok: true, edit: { revision: 2, clips: [] } } };+const first = sbeSave(false);+await tick();+// The user trims while the first Save is on the wire...+sbeMutate(cs => sbeTrim(cs, 'b', 'r', 4.5));+const liveEnd = sbeById(SBE.clips, 'b').film_end;+// ...and presses Save again.+const second = sbeSave(false);+await tick();+out.requestsBeforeRelease = FETCHES.length;+NEXT = { status: 200, body: { ok: true, edit: { revision: 3, clips: [] } } };+await release(); // the first answer lands+out.dirtyAfterFirst = SBE.dirty;+out.stateAfterFirst = (states[states.length - 1] || [])[0];+out.requestsAfterFirst = FETCHES.length;+while (HELD.length) await release();+const results = [await first, await second];+out.results = results;+const sent = FETCHES.map(f => JSON.parse(f.body));+out.sentEnds = sent.map(b => (b.edit.clips.find(c => c.id === 'b') || {}).film_end);+out.sentExpect = sent.map(b => b.expect_revision);+out.liveEnd = liveEnd;+out.dirtyAtEnd = SBE.dirty;+out.revisionAtEnd = SBE.revision;+""")++ def test_the_late_answer_does_not_mark_newer_work_saved(self):+ self.assertEqual(self.r["requestsBeforeRelease"], 1)+ self.assertTrue(self.r["dirtyAfterFirst"])+ self.assertNotRegex(self.r["stateAfterFirst"] or "", r"^saved")++ def test_the_second_save_is_sent_with_the_trim(self):+ self.assertEqual(len(self.r["sentEnds"]), 2)+ self.assertNotEqual(self.r["sentEnds"][0], self.r["liveEnd"])+ self.assertEqual(self.r["sentEnds"][1], self.r["liveEnd"])+ # ...against the revision the first one produced, not the stale one.+ self.assertEqual(self.r["sentExpect"], [1, 2])++ def test_both_presses_are_answered_by_the_save_that_carried_them(self):+ self.assertEqual(self.r["results"], [True, True])+ self.assertFalse(self.r["dirtyAtEnd"])+ self.assertEqual(self.r["revisionAtEnd"], 3)+++class DependentActionsWaitForTheSave(unittest.TestCase):+ """SB5-14 — `'busy'` is not `true`: Render must not outrun its Save."""++ @classmethod+ def setUpClass(cls) -> None:+ cls.r = run(TWO_CLIPS + r"""+// ---- a save in flight, then Render ----------------------------------------+twoClips();+SBE.rendering = false;+els.sbeRenderBtn = Object.assign(stubEl('sbeRenderBtn'), { textContent: 'Render' });+els.sbeMusic = Object.assign(stubEl('sbeMusic'), { value: '' });+FETCHES = []; HOLD = true;+NEXT = { status: 200, body: { ok: true, edit: { revision: 2, clips: [] } } };+const saving = sbeSave(false);+await tick();+const rendering = sbeRenderFilm();+for (let i = 0; i < 6; i++) await tick();+out.urlsWhileSaving = FETCHES.map(f => f.url);+NEXT = { status: 200, body: { ok: false, error: 'stop here' } };+while (HELD.length) await release();+await saving; await rendering;+out.urlsAfter = FETCHES.map(f => f.url);++// ---- a save in flight that FAILS: no render at all ------------------------+twoClips();+FETCHES = []; HOLD = true;+NEXT = { status: 409, body: { ok: false, conflict: true, revision: 7 } };+const s2 = sbeSave(false);+await tick();+const r2 = sbeRenderFilm();+while (HELD.length) await release();+await s2; await r2;+for (let i = 0; i < 6; i++) await tick();+while (HELD.length) await release();+out.urlsAfterConflict = FETCHES.map(f => f.url);+""", extra=("sbeRenderFilm",),+ shim=r"""+function sbeDeliverGet() { return { format: 'h264', size: 'native', finish: 'none' }; }+function sbeMusicMode() { return 'under'; }+global.confirm = () => true;+const SB = { id: '' };+function workflowSwitch() {}+function sbFilmOpen() {}+""")++ def test_render_waits_for_the_save_in_flight(self):+ self.assertEqual(self.r["urlsWhileSaving"], ["/storyboard/edit/save"])+ self.assertEqual(self.r["urlsAfter"],+ ["/storyboard/edit/save", "/storyboard/edit/render"])++ def test_a_save_that_does_not_land_stops_the_render(self):+ self.assertNotIn("/storyboard/edit/render", self.r["urlsAfterConflict"])++++class SaveNamesItsDraft(unittest.TestCase):+ """SB5-04 — the client half: the save says which draft it was cut in."""++ @classmethod+ def setUpClass(cls) -> None:+ cls.r = run(TWO_CLIPS + r"""+twoClips();+SBE.activeDraft = 'draft-1';+FETCHES = [];+NEXT = { status: 409, body: { ok: false, conflict: true, draft_conflict: true,+ active_draft: 'take-two', revision: 1 } };+out.ok = await sbeSave(false);+out.draft = JSON.parse(FETCHES[0].body).draft;+out.text = els.sbeConflictText.textContent;+out.conflict = SBE.conflict;+out.dirty = SBE.dirty;+""")++ def test_the_body_names_the_draft(self):+ self.assertEqual(self.r["draft"], "draft-1")++ def test_a_draft_conflict_says_which_draft_won_and_keeps_the_work(self):+ self.assertFalse(self.r["ok"])+ self.assertIn("take-two", self.r["text"])+ self.assertIn("draft-1", self.r["text"])+ self.assertTrue(self.r["conflict"])+ self.assertTrue(self.r["dirty"])++++class LoadsBelongToTheirFilm(unittest.TestCase):+ """SB5-03 — a response is adopted only by the film and load that asked."""++ @classmethod+ def setUpClass(cls) -> None:+ cls.r = run(TWO_CLIPS + r"""+// ---- open A, switch to B, B answers first --------------------------------+SBE.open = true; SBE.id = 'A'; SBE.dirty = false; SBE.saving = false;+SBE.conflict = 0; SBE.session = 's1';+FETCHES = []; HOLD = true; adopted.length = 0;+NEXT = { status: 200, body: { ok: true, title: 'film A', edit: { revision: 4, clips: [] } } };+const la = sbeLoad();+await tick();+SBE.id = 'B';+NEXT = { status: 200, body: { ok: true, title: 'film B', edit: { revision: 1, clips: [] } } };+const lb = sbeLoad();+await tick();+out.asked = FETCHES.map(f => f.url);+await releaseAt(1);+await releaseAt(0);+await la; await lb;+out.adopted = adopted.map(r => r.title);++// ---- Prepare finishes while there is unsaved work ------------------------+HOLD = false; adopted.length = 0;+SBE.id = 'B';+twoClips();+sbeMutate(cs => sbeTrim(cs, 'b', 'r', 4.5));+const shapeBefore = JSON.stringify(shape(SBE.clips));+const undoBefore = SBE.undo.length;+NEXT = { status: 200, body: { ok: true, title: 'film B',+ edit: { revision: 1, clips: [clip({ id: 'a', proxy: '/p/a.mp4' })] },+ clips: [], unplaced: [{ path: '/o/new.mp4' }], relink: [],+ prepare: { state: 'done' } } };+await sbeLoad(true);+out.prepAdopted = adopted.length;+out.prepShapeKept = JSON.stringify(shape(SBE.clips)) === shapeBefore;+out.prepUndoKept = SBE.undo.length === undoBefore && undoBefore > 0;+out.prepDirty = SBE.dirty;+out.prepProxy = sbeById(SBE.clips, 'a').proxy;+out.prepUnplaced = (SBE.unplaced || []).length;+out.prepState = (SBE.prepare || {}).state;+out.prepTransitions = (SBE.transitions || []).length;++// ---- ...and with nothing unsaved, the same re-read IS adopted -------------+SBE.dirty = false;+await sbeLoad(true);+out.cleanAdopted = adopted.length;+""", extra=("sbeLoad", "sbeAdoptMeta"), shim=r"""+const ED = { src: 'gallery' };+function sbePaintRelink() {}+function edPoolRefresh() {}+async function sbeFetchPeaks() {}+function sbeShowDocError() {}+""")++ def test_a_late_answer_for_the_film_you_left_is_dropped(self):+ self.assertEqual(len(self.r["asked"]), 2)+ self.assertIn("id=A", self.r["asked"][0])+ self.assertIn("id=B", self.r["asked"][1])+ self.assertEqual(self.r["adopted"], ["film B"])++ def test_prepare_finishing_does_not_replace_unsaved_work(self):+ self.assertEqual(self.r["prepAdopted"], 0)+ self.assertTrue(self.r["prepShapeKept"])+ self.assertTrue(self.r["prepUndoKept"])+ self.assertTrue(self.r["prepDirty"])+ self.assertEqual(self.r["prepTransitions"], 1)++ def test_prepare_finishing_still_brings_its_proxies_and_shots(self):+ self.assertEqual(self.r["prepProxy"], "/p/a.mp4")+ self.assertEqual(self.r["prepUnplaced"], 1)+ self.assertEqual(self.r["prepState"], "done")++ def test_a_clean_timeline_still_takes_the_re_read(self):+ self.assertEqual(self.r["cleanAdopted"], 1)++++class TheSoundtrackFieldFollowsTheFilm(unittest.TestCase):+ """SB5-11 — film B renders with film B's song, or with none."""++ @classmethod+ def setUpClass(cls) -> None:+ cls.r = run(TWO_CLIPS + r"""+els.sbeMusic = Object.assign(stubEl('sbeMusic'), { value: '' });+els.sbeRenderBtn = Object.assign(stubEl('sbeRenderBtn'), { textContent: 'Render' });+SBE.session = 's1';+const payload = (title, song) => ({ ok: true, title: title, edit: {+ revision: 1, audio: song ? { path: song, offset: 0 } : null,+ clips: [clip({ id: 'a' })] } });+async function renderMusic() {+ FETCHES = []; SBE.dirty = false; SBE.rendering = false;+ NEXT = { status: 200, body: { ok: false, error: 'stop here' } };+ await sbeRenderFilm();+ const f = FETCHES.find(x => x.url === '/storyboard/edit/render');+ return f ? (f.body.get('music') || '') : null;+}+// Film A, with song A.+SBE.open = true; SBE.id = 'A'; SBE.activeDraft = 'draft-1';+sbeAdopt(payload('A', '/songs/song-A.wav'), true);+out.fieldA = els.sbeMusic.value;+out.renderA = await renderMusic();+// Close it, open film B with song B.+sbeCloseDoc({ quiet: true });+out.fieldClosed = els.sbeMusic.value;+SBE.open = true; SBE.id = 'B';+sbeAdopt(payload('B', '/songs/song-B.wav'), true);+out.fieldB = els.sbeMusic.value;+out.renderB = await renderMusic();+// ...and a silent film C straight after B, without closing first.+SBE.id = 'C';+sbeAdopt(payload('C', null), true);+out.fieldC = els.sbeMusic.value;+out.renderC = await renderMusic();+// A re-read of the SAME film keeps what the user typed into the field.+els.sbeMusic.value = '/songs/typed.wav';+sbeAdopt(payload('C', null), true);+out.typedKept = els.sbeMusic.value;+""", extra=("sbeAdopt", "sbeCloseDoc", "sbeRenderFilm", "sbeTsCopy",+ "sbePaintMusicName"), shim=r"""+const ED = { src: 'gallery' };+function sbeDeliverGet() { return { format: 'h264', size: 'native', finish: 'none' }; }+function sbeMusicMode() { return 'under'; }+global.confirm = () => true;+const SB = { id: '' };+function workflowSwitch() {}+function sbFilmOpen() {}+function sbeSetMusicMode() {}+function sbeSyncMusic() {}+function sbePaintRelink() {}+function sbeDeliverPaint() {}+function edPoolRefresh() {}+async function sbeFetchPeaks() {}+function sbeShowFrameAt() {}+function sbeStop() {}+function sbeVersionsClose() {}+function edRemember() {}+function edShowPicker() {}+global.window = { addEventListener() {}, removeEventListener() {} };+""")++ def test_each_film_opens_with_its_own_song(self):+ self.assertEqual(self.r["fieldA"], "/songs/song-A.wav")+ self.assertEqual(self.r["fieldB"], "/songs/song-B.wav")++ def test_render_posts_the_open_films_song_never_the_last_ones(self):+ self.assertEqual(self.r["renderA"], "/songs/song-A.wav")+ self.assertEqual(self.r["renderB"], "/songs/song-B.wav")++ def test_a_silent_film_renders_with_no_soundtrack_override(self):+ self.assertEqual(self.r["fieldClosed"], "")+ self.assertEqual(self.r["fieldC"], "")+ self.assertEqual(self.r["renderC"], "")++ def test_a_re_read_of_the_same_film_keeps_a_typed_path(self):+ self.assertEqual(self.r["typedKept"], "/songs/typed.wav")+++if __name__ == "__main__":+ unittest.main()diff --git a/test_editor_server_races.py b/test_editor_server_races.pynew file mode 100644index 0000000..eea9125--- /dev/null+++ b/test_editor_server_races.py@@ -0,0 +1,145 @@+#!/usr/bin/env python3+"""The Editor's server under two writers: who is allowed to land last.++`test_storyboard_editor_api.py` locks each route on its own. These are the+interleavings the 2026-09-24 review found, each driven for real against a+scratch board (the `EditorCase` sandbox — never the live state dir):++ * SB5-07 the first GET's auto-edit wrote over a timeline saved by hand+ while it was still analysing the clips.+ * SB5-04 revisions restart per draft, so a stale tab on draft A saved+ into a draft B another tab had just duplicated, with no conflict.+"""+from __future__ import annotations++import json+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_editor as sedit # noqa: E402+from test_storyboard_editor_api import (EditorCase, FakeHandler, # noqa: E402+ _clip, _edit)+++class FirstGetLosesToAManualSave(EditorCase):+ """SB5-07 — the machine's cut is a first draft, never a last word."""++ def _auto(self):+ return sedit.edit_from_plan(+ [{"path": str(self.clips[1]), "start": 0.0, "end": 2.0,+ "film_start": 0.0}], board_id="sb_t")++ def test_a_save_made_during_the_first_auto_edit_survives_it(self):+ manual = _edit([_clip(str(self.clips[0]), 0.0, 1.0, 0.0)],+ source="human")++ def slow_auto(board, **kw):+ # Another tab finished its own first load, cut by hand and saved+ # while this GET was still decoding clips.+ sedit.save_edit(self.bdir, manual, expect=0)+ return self._auto()++ with mock.patch.object(panel, "_sbe_auto_edit", slow_auto):+ h = FakeHandler().get("/storyboard/edit?id=sb_t")+ self.assertEqual(h.status, 200)+ on_disk = sedit.load_edit(self.bdir)+ self.assertEqual([c["path"] for c in on_disk["clips"]],+ [str(self.clips[0])])+ self.assertEqual(on_disk["revision"], 1)+ # ...and the late GET answers with the document that won, not with+ # the cut it failed to write.+ self.assertEqual([c["path"] for c in h.payload["edit"]["clips"]],+ [str(self.clips[0])])+ self.assertFalse(h.payload["generated"])++ def test_an_uncontested_first_get_still_writes_the_auto_edit(self):+ with mock.patch.object(panel, "_sbe_auto_edit",+ lambda board, **kw: self._auto()):+ h = FakeHandler().get("/storyboard/edit?id=sb_t")+ self.assertTrue(h.payload["generated"])+ self.assertEqual(sedit.load_edit(self.bdir)["revision"], 1)+ self.assertEqual(sedit.load_edit(self.bdir)["origin"], "auto")++++class SaveNamesItsDraft(EditorCase):+ """SB5-04 — a revision number is not a document identity."""++ def _two_tabs(self):+ a = _edit([_clip(str(self.clips[0]), 0.0, 1.0, 0.0)], source="human")+ sedit.save_edit(self.bdir, a) # draft-1 @ r1+ # Tab 2 duplicates A; the copy becomes active, also at revision 1.+ out = sedit.duplicate_draft(self.bdir, "draft-1", "B")+ self.assertEqual(sedit.load_edit(self.bdir)["revision"], 1)+ return out["slug"], sedit.load_edit(self.bdir)++ def test_a_stale_tab_gets_a_draft_conflict_not_a_write(self):+ b_slug, before = self._two_tabs()+ # Tab 1 still believes it is on draft-1 at revision 1.+ body = json.dumps({"id": "sb_t", "expect_revision": 1,+ "draft": "draft-1",+ "edit": _edit([_clip(str(self.clips[1]),+ 0.0, 2.0, 0.0)],+ source="human")})+ h = FakeHandler().post("edit/save", {}, body)+ self.assertEqual(h.status, 409)+ self.assertTrue(h.payload["conflict"])+ self.assertTrue(h.payload["draft_conflict"])+ self.assertEqual(h.payload["active_draft"], b_slug)+ self.assertEqual(sedit.load_edit(self.bdir)["clips"], before["clips"])++ def test_the_guard_holds_at_the_write_too(self):+ # The early answer can be raced; the check inside the lock cannot.+ b_slug, before = self._two_tabs()+ with self.assertRaises(sedit.EditConflict) as cm:+ sedit.save_edit(self.bdir,+ _edit([_clip(str(self.clips[1]), 0.0, 2.0, 0.0)]),+ expect=1, expect_draft="draft-1")+ self.assertEqual(cm.exception.draft, b_slug)+ self.assertEqual(sedit.load_edit(self.bdir)["clips"], before["clips"])++ def test_the_right_draft_still_saves(self):+ b_slug, _ = self._two_tabs()+ body = json.dumps({"id": "sb_t", "expect_revision": 1, "draft": b_slug,+ "edit": _edit([_clip(str(self.clips[1]),+ 0.0, 2.0, 0.0)])})+ h = FakeHandler().post("edit/save", {}, body)+ self.assertTrue(h.payload["ok"])+ self.assertEqual(sedit.load_edit(self.bdir)["revision"], 2)++ def test_a_client_without_the_field_is_unchecked_as_before(self):+ self._two_tabs()+ body = json.dumps({"id": "sb_t", "expect_revision": 1,+ "edit": _edit([_clip(str(self.clips[1]),+ 0.0, 2.0, 0.0)])})+ self.assertTrue(FakeHandler().post("edit/save", {}, body).payload["ok"])++ def test_every_draft_verb_runs_inside_the_board_lock(self):+ # A switch between a save's check and its write is the whole race;+ # the verbs take the same lock the save holds.+ self._two_tabs()+ seen = []+ real = sedit._save_draft_index++ def spy(board_dir, idx):+ seen.append(sedit.board_write_lock(board_dir)._is_owned())+ return real(board_dir, idx)++ with mock.patch.object(sedit, "_save_draft_index", spy):+ c = sedit.create_draft(self.bdir, "C")+ sedit.rename_draft(self.bdir, c["slug"], "C2")+ sedit.activate_draft(self.bdir, "draft-1")+ sedit.duplicate_draft(self.bdir, "draft-1", "D")+ sedit.delete_draft(self.bdir, c["slug"])+ self.assertTrue(seen)+ self.assertTrue(all(seen), seen)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_engine_env_fault.py b/test_engine_env_fault.pyindex d4b5ff9..4cca648 100644--- a/test_engine_env_fault.py+++ b/test_engine_env_fault.py@@ -109,5 +109,82 @@ class ItIsFiledUnderTheRightHeading(unittest.TestCase):self.assertNotIn("missing (", msg.lower())+def _menu(root: Path, running: bool) -> list:+ """Run the REAL pinokio.js menu against a fake install root."""+ import json, subprocess+ probe = (+ "const path=require('path'),fs=require('fs');const root=process.argv[1];"+ "const running=process.argv[2]==='1';"+ "const mod=require(path.join(root,'pinokio.js'));"+ "const info={path:(...a)=>path.join(root,...a),exists:p=>fs.existsSync(path.join(root,p)),"+ "running:s=>running&&s==='start.js',local:s=>s==='start.js'?{url:'http://127.0.0.1:1'}:{}};"+ "mod.menu({},info).then(m=>console.log(JSON.stringify(m.map(i=>({text:i.text,default:!!i.default})))))"+ )+ out = subprocess.run(["node", "-e", probe, str(root), "1" if running else "0"],+ capture_output=True, text=True, errors="replace", timeout=30)+ if out.returncode != 0:+ raise AssertionError(out.stderr[-800:])+ return json.loads(out.stdout)++[email protected](__import__("shutil").which("node"), "node not on PATH")+class TheSidebarOffersTheRepairItsErrorNames(unittest.TestCase):+ """Codex INST-05 (2026-09-24): complete weights, venv with a Python and no+ ltx_pipelines_mlx. Start stayed `default: true` (auto-runs a panel that+ cannot render), and once it ran both running menus hid the Repair entry+ the render error tells the user to click."""++ def setUp(self):+ import json, shutil+ self.tmp = TemporaryDirectory()+ root = self.root = Path(self.tmp.name)+ src = Path(__file__).resolve().parent+ shutil.copy(src / "pinokio.js", root / "pinokio.js")+ shutil.copy(src / "required_files.json", root / "required_files.json")+ req = json.loads((src / "required_files.json").read_text())+ minb = req.get("min_size_bytes", 1024)++ def touch(rel, size=minb):+ f = root / rel+ f.parent.mkdir(parents=True, exist_ok=True)+ with open(f, "wb") as fh:+ fh.truncate(size)+ touch("ltx-2-mlx/env/pyvenv.cfg", 10)+ touch("ltx-2-mlx/env/bin/python3.11", 10)+ (root / "ltx-2-mlx/env/lib/python3.11/site-packages").mkdir(parents=True)+ render = req["capabilities"]["render"]+ for key in render["repos_by_version"][render["default_version"]]:+ repo = next(r for r in req["repos"] if r["key"] == key)+ for f in repo.get("files", []):+ touch(f"{repo['local_dir']}/{f}")++ def tearDown(self):+ self.tmp.cleanup()++ def _heal(self):+ (self.root / "ltx-2-mlx/env/lib/python3.11/site-packages/ltx_pipelines_mlx").mkdir()++ def test_stopped_broken_engine_does_not_auto_start(self):+ m = _menu(self.root, running=False)+ self.assertEqual(m[0]["text"], "Repair Phosphene engine (models kept)", m)+ self.assertFalse([i for i in m if i["default"]], m)+ self.assertIn("Start", [i["text"] for i in m])++ def test_running_broken_engine_says_how_to_reach_the_repair(self):+ texts = [i["text"] for i in _menu(self.root, running=True)]+ hint = [t for t in texts if "Repair Phosphene engine" in t]+ self.assertTrue(hint, texts)+ self.assertIn("Stop the panel", hint[0])+ self.assertIn("Stop Phosphene", P.ENGINE_ENV_REPAIR)++ def test_healthy_engine_is_unchanged(self):+ self._heal()+ stopped = _menu(self.root, running=False)+ self.assertEqual(stopped[0], {"text": "Start", "default": True})+ self.assertFalse([i for i in stopped if "Repair Phosphene" in i["text"]])+ running = [i["text"] for i in _menu(self.root, running=True)]+ self.assertFalse([t for t in running if "Repair Phosphene" in t], running)++if __name__ == "__main__":unittest.main(verbosity=2)diff --git a/test_h3_48gb_install_path.py b/test_h3_48gb_install_path.pyindex 6a68eb6..c68b527 100644--- a/test_h3_48gb_install_path.py+++ b/test_h3_48gb_install_path.py@@ -30,6 +30,7 @@ import subprocessimport sysimport tempfileimport unittest+import unittest.mockfrom pathlib import PathROOT = Path(__file__).resolve().parent@@ -210,12 +211,77 @@ class TestSidebarOffersH3WhereTheCardSaysItIs(unittest.TestCase):self.assertNotIn(P.H3_BUILD_MENU_TEXT, items)self.assertIn("Update Hailuo H3 runner (weights kept — no re-download)", items)+ def test_relocated_roots_with_spaces_are_read_from_environment(self):+ """Codex INST-13: the sidebar's ENVIRONMENT parser took `(\\S+)`, so a+ relocated root with a space — quoted or not — was dropped and the menu+ probed the default location: an installed engine was offered as a+ fresh 75 GB install. Pinokio itself parses the file with dotenv."""+ shared = self.root / "Shared Drive" / "日本語"+ ck, models = shared / "h3 engine", shared / "h3 weights"+ rel = lambda p, pre: Path(p).relative_to(pre) # noqa: E731+ for f in [self.h3["paths"][0], self.h3["venv_any"][0]]:+ t = ck / rel(f, "minimax-h3-mlx")+ t.parent.mkdir(parents=True, exist_ok=True)+ t.write_bytes(b"x" * 10)+ for f in self.h3["models"]:+ t = models / f+ t.parent.mkdir(parents=True, exist_ok=True)+ t.write_bytes(b"x" * 10)+ (self.root / "ENVIRONMENT").write_text(+ f'LTX_H3_ROOT="{ck}"\nLTX_H3_MODELS={models}\n', encoding="utf-8")+ items = _menu(self.root, GIB64, running=False)+ self.assertNotIn(P.H3_INSTALL_MENU_TEXT, items)+ self.assertIn("Update Hailuo H3 runner (weights kept — no re-download)", items)++ def test_a_q8_pack_missing_indexed_shards_still_offers_the_build(self):+ """Codex H3-04: 'config + quant_config + ANY shard' read a pack missing+ four of five shards as built — H3 unlocked on it and Build vanished."""+ self._install_h3(q8=False)+ pack = self.root / "mlx_models/hailuo-h3/h3-dit-q8"+ names = [f"model-0000{i}-of-00005.safetensors" for i in range(1, 6)]+ for n in ("config.json", "quant_config.json", names[0]):+ self.touch(f"mlx_models/hailuo-h3/h3-dit-q8/{n}", 10)+ (pack / "model.safetensors.index.json").write_text(+ json.dumps({"weight_map": {f"w{i}": n for i, n in enumerate(names)}}))+ for running in (True, False):+ self.assertIn(P.H3_BUILD_MENU_TEXT, _menu(self.root, GIB48, running=running))+ for n in names[1:]:+ self.touch(f"mlx_models/hailuo-h3/h3-dit-q8/{n}", 10)+ self.assertNotIn(P.H3_BUILD_MENU_TEXT, _menu(self.root, GIB48, running=False))+ self.touch(f"mlx_models/hailuo-h3/h3-dit-q8/{names[3]}", 0) # truncated+ self.assertIn(P.H3_BUILD_MENU_TEXT, _menu(self.root, GIB48, running=False))+def test_32gb_is_never_offered_h3(self):for running in (True, False):items = _menu(self.root, GIB32, running=running)self.assertFalse([t for t in items if "Hailuo" in t], items)+class TestPanelQ8PackIsComplete(unittest.TestCase):+ """The panel half of H3-04: the resolver behind auto/explicit Q8 dispatch."""++ def test_every_indexed_shard_must_be_present_and_non_empty(self):+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp)+ d = root / P.H3_DIT_Q8_DIRNAME+ d.mkdir()+ names = [f"model-0000{i}-of-00005.safetensors" for i in range(1, 6)]+ for n in ("config.json", "quant_config.json", names[0]):+ (d / n).write_bytes(b"x")+ (d / "model.safetensors.index.json").write_text(+ json.dumps({"weight_map": {f"w{i}": n for i, n in enumerate(names)}}))+ with unittest.mock.patch.object(P, "_h3_model_roots", lambda: [root]):+ self.assertIsNone(P._h3_q8_dit_dir())+ for n in names[1:]:+ (d / n).write_bytes(b"x")+ self.assertEqual(P._h3_q8_dit_dir(), d)+ (d / names[2]).write_bytes(b"")+ self.assertIsNone(P._h3_q8_dit_dir())+ (d / names[2]).write_bytes(b"x")+ (d / "model.safetensors.index.json").unlink() # a pre-index pack+ self.assertEqual(P._h3_q8_dit_dir(), d)++class TestPublicIdentity(unittest.TestCase):"""v4.8.2 committed the beta checkout's local title into public main."""diff --git a/test_h3_build_hold.py b/test_h3_build_hold.pynew file mode 100644index 0000000..eec8fe4--- /dev/null+++ b/test_h3_build_hold.py@@ -0,0 +1,139 @@+"""The compact-engine build holds new renders while it loads ~20 GB (Codex H3-02).++h3_build_q8.sh (offered by the sidebar while the panel runs) waited for the job+already running, but the panel kept taking new ones — so a render queued after+the idle check ran beside the build's full-model load on a 36-59 GB Mac. The+build now writes STATE_DIR/h3_build.lock for its whole duration and the worker+starts no job while it is live. Everything here is a stub in a temp dir: no+model, no quantizer, no GPU.+"""+from __future__ import annotations++import json+import os+import subprocess+import sys+import tempfile+import threading+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 P # noqa: E402++PY_STUB = r"""#!/bin/bash+code=""+[ "$1" = "-" ] && code=$(cat)+if [ -f "$STATE/h3_build.lock" ]; then h=HELD; else h=FREE; fi+case "$code$*" in+ *quantize_stream.py*)+ out="${@: -1}"; mkdir -p "$out"; echo x > "$out/model-00001.safetensors"+ echo '{"weight_map": {"a": "model-00001.safetensors"}}' > "$out/model.safetensors.index.json"+ echo "$h quantize" >> "$CALLS" ;;+ *load_dit*) echo "$h validate" >> "$CALLS"; echo "LOAD OK" ;;+ *weight_map*) [ -f "$2/model.safetensors.index.json" ] ;;+ *) exit 1 ;;+esac+"""+++class TheBuildHoldsThePanel(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ base = Path(self.tmp.name)+ self.app, self.ck, self.state = base / "app", base / "ck", base / "state"+ dit = (self.app / "mlx_models/hailuo-h3/models/deepbeep-pruned-bf16"+ / "MiniMax-H3-FL2VA-pruned_bf16.safetensors")+ dit.parent.mkdir(parents=True)+ dit.write_bytes(b"x")+ (self.ck / ".venv/bin").mkdir(parents=True)+ py = self.ck / ".venv/bin/python"+ py.write_text(PY_STUB)+ py.chmod(0o755)+ self.state.mkdir()+ self.calls = base / "calls.log"++ def tearDown(self):+ self.tmp.cleanup()++ def test_both_model_loads_run_under_the_hold_and_it_is_released(self):+ env = {k: v for k, v in os.environ.items() if k != "LTX_H3_MODELS"}+ env.update(LTX_STATE_DIR=str(self.state), STATE=str(self.state), CALLS=str(self.calls))+ r = subprocess.run(["bash", str(ROOT / "scripts/pinokio/h3_build_q8.sh"), str(self.app)],+ cwd=self.ck, env=env, capture_output=True, text=True,+ errors="replace", timeout=60)+ self.assertEqual(r.returncode, 0, r.stdout + r.stderr)+ self.assertEqual(self.calls.read_text().split(), ["HELD", "quantize", "HELD", "validate"])+ self.assertFalse((self.state / "h3_build.lock").exists(), "the hold outlived the build")+++class TheWorkerRespectsTheHold(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.state = Path(self.tmp.name)+ self.lock = self.state / "h3_build.lock"++ def tearDown(self):+ self.tmp.cleanup()++ def _hold(self, pid=None, age=0.0):+ self.lock.write_text(json.dumps({"pid": pid or os.getpid(), "ts": int(time.time()),+ "what": "the Hailuo H3 compact-engine build"}))+ if age:+ t = time.time() - age+ os.utime(self.lock, (t, t))++ def test_a_live_hold_is_reported_and_a_stale_one_is_not(self):+ with mock.patch.object(P, "STATE_DIR", self.state):+ self.assertEqual(P._external_build_hold(), "")+ self._hold()+ self.assertIn("compact-engine build", P._external_build_hold())+ dead = subprocess.Popen(["true"])+ dead.wait()+ self._hold(pid=dead.pid)+ self.assertEqual(P._external_build_hold(), "", "a dead builder wedged the queue")+ self._hold(age=5 * 3600)+ self.assertEqual(P._external_build_hold(), "", "an ancient lock wedged the queue")++ def test_no_job_starts_while_held_and_the_queue_resumes_after(self):+ class _StopWorker(BaseException):+ pass+ ran = threading.Event()++ def fake_run(job):+ ran.set()+ raise _StopWorker()+ job = {"id": "hold-test", "params": {}, "status": "queued"}+ saved = {k: P.STATE.get(k) for k in ("queue", "paused", "current", "history")}+ self._hold()+ try:+ P.STATE.update(queue=[job], paused=False, current=None, history=[])+ with mock.patch.object(P, "STATE_DIR", self.state), \+ mock.patch.object(P, "run_job_inner", fake_run), \+ mock.patch.object(P, "persist_queue", lambda: None), \+ mock.patch.object(P, "caffeinate_on", lambda: None), \+ mock.patch.object(P, "caffeinate_off", lambda: None), \+ mock.patch.object(P, "_analytics_install_step", lambda *a, **k: None), \+ mock.patch.object(P, "_analytics_render_event", lambda *a, **k: None), \+ mock.patch.object(P, "push", lambda *a, **k: None):+ def _worker():+ try:+ P.worker_loop()+ except _StopWorker:+ pass+ t = threading.Thread(target=_worker, daemon=True)+ t.start()+ self.assertFalse(ran.wait(3), "a render started during the build's hold")+ self.lock.unlink()+ self.assertTrue(ran.wait(6), "the queue never resumed after the hold")+ t.join(5)+ finally:+ P.STATE.update(saved)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_h3_install_roots.py b/test_h3_install_roots.pynew file mode 100644index 0000000..aeb58d2--- /dev/null+++ b/test_h3_install_roots.py@@ -0,0 +1,160 @@+"""Install / Repair Hailuo H3 works on the roots the panel uses (Codex INST-09).++The panel and the sidebar honour LTX_H3_ROOT / LTX_H3_MODELS; install_h3.js+cloned, installed and downloaded into the literal defaults, so Repair fixed a+checkout the panel never uses and could fetch ~75 GB of duplicate weights.++Drives the REAL install_h3.js dispatches, one shell per message element as+Pinokio 8.2.0 runs them, in a throwaway app root whose git, uv, venv python+and heavy scripts are recording stubs. Nothing is cloned or downloaded.+"""+from __future__ import annotations++import json+import os+import shutil+import subprocess+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent++DISPATCHES_JS = r"""+const mod = require(process.argv[1]);+const out = [];+for (const st of mod.run) {+ if (st.method !== "shell.run") continue;+ const m = st.params.message;+ for (const d of (Array.isArray(m) ? m : [m])) out.push({d: String(d), env: st.params.env || {}});+}+console.log(JSON.stringify(out));+"""++STUB = """#!/bin/bash+printf '%s|%s|%s' "$(basename "$0")" "$PWD" "${LTX_H3_MODELS:-}" >> "$CALLS"+for a in "$@"; do printf '|%s' "$a" >> "$CALLS"; done+echo >> "$CALLS"+"""++[email protected](shutil.which("node"), "node not on PATH")+class H3InstallRoots(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ base = self.base = Path(self.tmp.name).resolve()+ self.app = base / "app"+ (self.app / "scripts" / "pinokio").mkdir(parents=True)+ for f in ("h3_roots.sh", "h3_venv.sh"):+ shutil.copy(ROOT / "scripts/pinokio" / f, self.app / "scripts/pinokio" / f)+ self.calls = base / "calls.log"+ self.bin = base / "bin"+ self.bin.mkdir()+ for name in ("git", "uv"):+ (self.bin / name).write_text(STUB + {+ # git clone <url> <dest>: make the checkout exist+ "git": 'if [ "$1" = clone ]; then mkdir -p "${@: -1}/.git"; fi\n',+ # uv venv ... <dir>: give it a python that records its calls+ "uv": 'if [ "$1" = venv ]; then d="${@: -1}"; mkdir -p "$d/bin"; '+ f'cp "{self.bin}/pystub" "$d/bin/python"; fi\n',+ }[name])+ (self.bin / "pystub").write_text(STUB)+ for f in ("h3_preflight.sh", "h3_checkout.sh", "h3_build_q8.sh"):+ (self.app / "scripts/pinokio" / f).write_text(STUB.replace('"$(basename "$0")"', f'"{f}"'))+ for f in self.bin.iterdir():+ f.chmod(0o755)+ out = subprocess.run(["node", "-e", DISPATCHES_JS, str(ROOT / "install_h3.js")],+ capture_output=True, text=True, errors="replace", check=True)+ self.dispatches = json.loads(out.stdout)++ def tearDown(self):+ self.tmp.cleanup()++ def _install(self, h3_root: str, h3_models: str) -> list[list[str]]:+ for d in self.dispatches:+ cmd = d["d"].replace("{{cwd}}", str(self.app))+ env = dict(os.environ, PATH=f"{self.bin}:{os.environ['PATH']}", CALLS=str(self.calls),+ LTX_H3_ROOT=h3_root, LTX_H3_MODELS=h3_models)+ for k, v in d["env"].items():+ env[k] = v.replace("{{cwd}}", str(self.app))+ subprocess.run(["bash", "-c", cmd], cwd=self.app, env=env,+ capture_output=True, text=True, errors="replace", timeout=30)+ return [line.split("|") for line in self.calls.read_text().splitlines()]++ def test_relocated_roots_with_spaces_and_japanese_are_used_everywhere(self):+ ckout = self.base / "Shared Drive" / "日本語 H3"+ models = self.base / "Shared Drive" / "重み h3"+ calls = self._install(str(ckout), str(models))+ clone = [c for c in calls if c[0] == "git" and c[3] == "clone"]+ self.assertEqual(len(clone), 1, calls)+ self.assertEqual(clone[0][-1], str(ckout))+ in_checkout = [c for c in calls if c[0] in ("python", "uv", "h3_checkout.sh", "h3_build_q8.sh")]+ self.assertTrue(in_checkout)+ for c in in_checkout:+ self.assertEqual(c[1], str(ckout), c)+ dl = [c for c in calls if "scripts/download_selected.py" in c]+ self.assertEqual(dl[0][-2:], ["--root", str(models)])+ turbo = [c for c in calls if any(a.endswith("fetch_h3_turbo.py") for a in c)]+ self.assertEqual(turbo[0][-1], str(models / "models" / "turbo-lora"))+ tae = [c for c in calls if any(a.endswith("h3_fetch_tae.py") for a in c)]+ self.assertEqual(tae[0][-1], str(models / "models" / "tae" / "taeh3.safetensors"))+ build = [c for c in calls if c[0] == "h3_build_q8.sh"]+ self.assertEqual(build[0][2], str(models), "the Q8 build must read the relocated weights")+ self.assertFalse((self.app / "minimax-h3-mlx").exists(), "cloned into the default root")+ self.assertFalse((self.app / "mlx_models").exists(), "wrote into the default weights root")++ def test_relative_overrides_resolve_against_the_app_root(self):+ calls = self._install("engines/h3", "weights/h3")+ clone = [c for c in calls if c[0] == "git" and c[3] == "clone"]+ self.assertEqual(clone[0][-1], str(self.app / "engines/h3"))+ dl = [c for c in calls if "scripts/download_selected.py" in c]+ self.assertEqual(dl[0][-1], str(self.app / "weights/h3"))++ def test_defaults_are_unchanged(self):+ calls = self._install("", "")+ clone = [c for c in calls if c[0] == "git" and c[3] == "clone"]+ self.assertEqual(clone[0][-1], str(self.app / "minimax-h3-mlx"))+ dl = [c for c in calls if "scripts/download_selected.py" in c]+ self.assertEqual(dl[0][-1], str(self.app / "mlx_models/hailuo-h3"))++ FLAT_FILES = ("deepbeep-pruned-bf16/MiniMax-H3-FL2VA-pruned_bf16.safetensors",+ "ddalcu-q8/text_encoder.safetensors", "ddalcu-q8/video_vae.safetensors",+ "ddalcu-q8/audio_vae.safetensors",+ "upstream-meta/FL2VA/text_encoder/config.json")++ def _flat(self, skip=()):+ models = self.base / "flat"+ for rel in self.FLAT_FILES:+ if rel in skip:+ continue+ f = models / rel+ f.parent.mkdir(parents=True, exist_ok=True)+ f.write_bytes(b"x")+ return models++ def test_an_incomplete_flat_tree_stops_the_install_and_names_what_is_missing(self):+ # Codex 4.16.0: the flat branch checked only the DiT, printed "not+ # downloading", and Install/Repair could never supply the rest.+ models = self._flat(skip=("ddalcu-q8/video_vae.safetensors",))+ step = [d for d in self.dispatches if "h3_fetch_weights" in d["d"]]+ self.assertEqual(len(step), 1)+ self.assertLessEqual(len(step[0]["d"]), 350)+ env = dict(os.environ, LTX_H3_ROOT=str(self.base / "ck"), LTX_H3_MODELS=str(models))+ (self.base / "ck").mkdir()+ r = subprocess.run(["bash", "-c", step[0]["d"]], cwd=self.app, env=env,+ capture_output=True, text=True, errors="replace", timeout=30)+ self.assertNotEqual(r.returncode, 0)+ self.assertIn("error:", r.stdout)+ self.assertIn("ddalcu-q8/video_vae.safetensors", r.stdout)+ self.assertNotIn("text_encoder.safetensors", r.stdout.split("missing:")[1].split(" - ")[0])++ def test_an_existing_flat_tree_is_not_duplicated_under_models(self):+ models = self._flat()+ calls = self._install(str(self.base / "ck"), str(models))+ self.assertFalse([c for c in calls if "scripts/download_selected.py" in c])+ turbo = [c for c in calls if any(a.endswith("fetch_h3_turbo.py") for a in c)]+ self.assertEqual(turbo[0][-1], str(models / "turbo-lora"))+++if __name__ == "__main__":+ unittest.main()diff --git a/test_h3_lora_browser_scale.py b/test_h3_lora_browser_scale.pynew file mode 100644index 0000000..1b0791d--- /dev/null+++ b/test_h3_lora_browser_scale.py@@ -0,0 +1,111 @@+"""Browser-installed H3 LoRAs get the same strength as uploaded ones (Codex H3-01).++The upload importer writes the adapter's alpha/rank into recommended_strength;+the Hugging Face and CivitAI installers wrote the listing's number or 1.0, and+`_h3_lora_prepare` only folds MIXED ratios — so a uniform-alpha adapter from a+browser was applied rank/alpha times too strong. Network is faked; every file+lives in a temp dir.+"""+from __future__ import annotations++import io+import json+import struct+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 P # noqa: E402++RANK, ALPHA = 4, 2.0 # uniform alpha/rank = 0.5 on every module+++def _uniform_alpha_lora() -> bytes:+ values, header = [], {}+ for module in ("blocks.0.attn.qkv_proj", "blocks.1.attn.qkv_proj"):+ values.append((module + ".lora_A.weight", b"\0" * (4 * RANK), [RANK, 1]))+ values.append((module + ".lora_B.weight", b"\0" * (4 * RANK), [1, RANK]))+ values.append((module + ".alpha", struct.pack("<f", ALPHA), [1]))+ offset = 0+ for key, raw, shape in values:+ header[key] = {"dtype": "F32", "shape": shape, "data_offsets": [offset, offset + len(raw)]}+ offset += len(raw)+ enc = json.dumps(header).encode()+ return len(enc).to_bytes(8, "little") + enc + b"".join(r for _, r, _ in values)+++class BrowserInstallsCarryTheTrainingScale(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ base = Path(self.tmp.name)+ self.h3dir = base / "h3loras"+ self.h3dir.mkdir()+ self.payload = _uniform_alpha_lora()+ self._patches = [+ mock.patch.object(P, "_safe_h3_loras_dir", lambda: self.h3dir),+ mock.patch.object(P, "STATE_DIR", base / "state"),+ mock.patch.object(P, "push", lambda *a, **k: None),+ mock.patch.object(P, "_active_hf_token", lambda: None),+ mock.patch.object(P, "_active_civitai_key", lambda: None),+ ]+ for p in self._patches:+ p.start()++ def tearDown(self):+ for p in reversed(self._patches):+ p.stop()+ self.tmp.cleanup()++ def _upload_strength(self) -> float:+ return P.import_h3_lora_file("uploaded.safetensors", self.payload)["recommended_strength"]++ def _hf(self, meta: dict) -> dict:+ import huggingface_hub++ def fake_dl(repo_id, filename, token=None, local_dir=None):+ d = Path(local_dir)+ d.mkdir(parents=True, exist_ok=True)+ (d / filename).write_bytes(self.payload)+ return str(d / filename)+ with mock.patch.object(huggingface_hub, "hf_hub_download", fake_dl):+ r = P._hf_lora_download("someone/h3-uniform", "uniform.safetensors",+ dict(meta, lane="h3", base_model="MiniMax H3"))+ return json.loads(Path(r["sidecar_path"]).read_text())++ def _civitai(self, meta: dict) -> dict:+ payload = self.payload++ class Resp(io.BytesIO):+ headers = {"Content-Length": str(len(payload))}++ opener = mock.Mock()+ opener.open = lambda req, timeout=60: Resp(payload)+ with mock.patch.object(P, "_civitai_opener", lambda: opener):+ r = P._civitai_download("https://civitai.com/api/download/models/1",+ dict(meta, base_model="MiniMax H3",+ filename="civ_uniform.safetensors"))+ return json.loads(Path(r["sidecar_path"]).read_text())++ def test_all_three_install_paths_recommend_the_same_scale(self):+ with mock.patch.object(P, "_validate_h3_lora_payload", lambda *a, **k: None):+ upload = self._upload_strength()+ self.assertAlmostEqual(upload, ALPHA / RANK)+ self.assertAlmostEqual(self._hf({})["recommended_strength"], upload)+ self.assertAlmostEqual(self._civitai({})["recommended_strength"], upload)++ def test_a_listing_strength_multiplies_the_training_scale(self):+ self.assertAlmostEqual(self._hf({"recommended_strength": 0.8})["recommended_strength"],+ 0.8 * ALPHA / RANK)++ def test_an_unreadable_file_keeps_the_listing_number(self):+ self.payload = b"0" * 4096+ self.assertEqual(self._hf({"recommended_strength": 0.7})["recommended_strength"], 0.7)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_h3_lora_file_import.py b/test_h3_lora_file_import.pyindex 4dd2942..bbed90a 100644--- a/test_h3_lora_file_import.py+++ b/test_h3_lora_file_import.py@@ -140,6 +140,21 @@ class TestH3LoraFileImport(unittest.TestCase):self.assertEqual(names, ["raw-kohya.json", "raw-kohya.safetensors"])self.assertEqual(P._h3_lora_layout(self.dir / "raw-kohya.safetensors")["layout"], "bare")+ def test_non_ascii_filenames_import(self):+ """Codex H3-05: `日本語.safetensors` was refused as the wrong extension —+ sanitising the whole name ate the stem and the dot with it."""+ a = P.import_h3_lora_file("日本語.safetensors", _safetensors_lora())+ self.assertTrue(a["filename"].endswith(".safetensors"), a)+ self.assertTrue((self.dir / a["filename"]).is_file())+ b = P.import_h3_lora_file("人物 LoRA.safetensors", _safetensors_lora())+ self.assertEqual(b["filename"], "LoRA.safetensors")+ c = P.import_h3_lora_file("別の人.safetensors", _safetensors_lora())+ self.assertNotEqual(c["filename"], a["filename"], "two Japanese names collided")+ for bad in ("日本語.bin", ".safetensors", "../x.ckpt"):+ with self.assertRaises(ValueError):+ P._h3_lora_import_name(bad)+ self.assertEqual(P._h3_lora_import_name("../../etc/x.safetensors"), "x.safetensors")+def test_refuses_non_safetensors_uploads(self):with self.assertRaisesRegex(ValueError, "\.safetensors"):P.import_h3_lora_file("adapter.zip", b"not an adapter")diff --git a/test_h3_lora_strength_migration.py b/test_h3_lora_strength_migration.pyindex c70712a..47a429a 100644--- a/test_h3_lora_strength_migration.py+++ b/test_h3_lora_strength_migration.py@@ -309,6 +309,30 @@ class TheRenderPathUsesIt(_LoraDir):replay["id"] = "lora-rt2"self.assertEqual(self._dispatch_argv(replay), 1.0)+ def test_an_untouched_old_sidecar_replayed_is_migrated_not_stamped_current(self):+ # Codex H3-03: Load Params / Finish of a clip made BEFORE the stamp+ # existed restore its automatic 0.5 verbatim; make_job then stamped the+ # current version on the job and the dispatch read 0.5 as deliberate —+ # the scale applied twice. queue.js now sends each replayed entry with+ # its recipe's scale version (0 = unstamped).+ f = self.mixed()+ replay = P.make_job({k: [v] for k, v in {+ "mode": "t2v", "engine": "h3", "prompt": "a dancer", "h3_turbo": "0",+ "loras": json.dumps([{"path": str(f), "strength": 0.5, "scale_v": 0}])}.items()})+ self.assertEqual(replay["params"]["h3_lora_scale_v"], P.H3_LORA_SCALE_VERSION)+ replay["id"] = "lora-old"+ self.assertEqual(self._dispatch_argv(replay), 1.0)+ entry = replay["params"]["loras"][0]+ self.assertEqual(entry["strength"], 1.0)+ self.assertNotIn("scale_v", entry, "the recipe is current after dispatch")+ # control: the same 0.5 from a CURRENT recipe is someone's choice+ cur = P.make_job({k: [v] for k, v in {+ "mode": "t2v", "engine": "h3", "prompt": "a dancer", "h3_turbo": "0",+ "loras": json.dumps([{"path": str(f), "strength": 0.5,+ "scale_v": P.H3_LORA_SCALE_VERSION}])}.items()})+ cur["id"] = "lora-cur"+ self.assertEqual(self._dispatch_argv(cur), 0.5)+def test_a_deliberate_strength_is_not_rewritten_in_the_recipe(self):f = self.mixed()job = {"id": "lora-keep", "params": {@@ -327,5 +351,57 @@ class TheRenderPathUsesIt(_LoraDir):self.assertNotIn("h3_lora_scale_v", ltx["params"])+_RESTORE_JS = r"""+const fs = require('fs'), vm = require('vm');+function extract(file, name) {+ const s = fs.readFileSync(file, 'utf8');+ const start = s.indexOf('function ' + name + '(');+ if (start < 0) throw new Error('missing ' + name);+ return s.slice(start, s.indexOf('\n}', start) + 2);+}+const Q = process.argv[1] + '/webapp/js/queue.js', L = process.argv[1] + '/webapp/js/loras.js';+const json = {value: ''};+const ctx = {document: {getElementById: id => (id === 'lorasJson' ? json : null)},+ _knownUserLoras: [{path: '/a.safetensors', lane: 'h3', name: 'A'}],+ _currentLoraModeFilter: () => 'video:h3', _activeLoras: [], out: {}};+vm.createContext(ctx);+for (const [f, n] of [[Q, '_restoreLoraPicker'], [Q, 'h3FinishFieldsFromSidecar'],+ [L, '_serializeLoras'], [L, 'setLoraStrength']]) {+ vm.runInContext(extract(f, n), ctx);+}+vm.runInContext(`+ h3TierByKeyExact = key => ({key, quality: 'high', length: '5s'});+ _h3FinishSteps = () => 'auto';+ const old = {engine: 'h3', mode: 't2v', prompt: 'p', seed_used: 3,+ loras: [{path: '/a.safetensors', strength: 0.5}]};+ const f = h3FinishFieldsFromSidecar(old, 'high_5s');+ _restoreLoraPicker(f.loras, f.h3_lora_scale_v);+ _serializeLoras();+ out.replayed = JSON.parse(document.getElementById('lorasJson').value);+ setLoraStrength('/a.safetensors', 0.5);+ out.edited = JSON.parse(document.getElementById('lorasJson').value);+ _restoreLoraPicker([{path: '/a.safetensors', strength: 0.8}]);+ _serializeLoras();+ out.ltx = JSON.parse(document.getElementById('lorasJson').value);+`, ctx);+process.stdout.write(JSON.stringify(ctx.out));+"""++[email protected](__import__("shutil").which("node"), "node missing")+class TheBrowserSendsTheRecipesMeaning(unittest.TestCase):+ """The browser half of H3-03, executed rather than grepped."""++ def test_replay_carries_scale_v_until_the_user_edits_it(self):+ import subprocess+ r = subprocess.run(["node", "-e", _RESTORE_JS, str(ROOT)], capture_output=True,+ text=True, errors="replace", timeout=60)+ self.assertEqual(r.returncode, 0, r.stderr)+ out = json.loads(r.stdout)+ self.assertEqual(out["replayed"], [{"path": "/a.safetensors", "strength": 0.5, "scale_v": 0}])+ self.assertEqual(out["edited"], [{"path": "/a.safetensors", "strength": 0.5}])+ self.assertEqual(out["ltx"], [{"path": "/a.safetensors", "strength": 0.8}])++if __name__ == "__main__":unittest.main()diff --git a/test_h3_reference_image_error.py b/test_h3_reference_image_error.pynew file mode 100644index 0000000..5d6a1a1--- /dev/null+++ b/test_h3_reference_image_error.py@@ -0,0 +1,72 @@+"""H3 Image mode: a broken engine venv is not a bad picture (fleet 4.15.2).++One 128 GB Mac on 4.15.2 failed six H3 Image renders with "The reference image+can't be read (ModuleNotFoundError). Export it as a JPEG or PNG" — the panel+could not import PIL because its engine venv was half installed, and the same+install also reported "the engine venv has a Python but no packages". The+sentence sent the user to re-export a good image instead of to Repair.+"""+from __future__ import annotations++import builtins+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+++class H3ReferenceImageError(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.dir = Path(self.tmp.name)++ def tearDown(self):+ self.tmp.cleanup()++ def test_a_readable_image_passes(self):+ from PIL import Image+ f = self.dir / "ok.png"+ Image.new("RGB", (8, 8)).save(f)+ self.assertEqual(panel.h3_reference_image_error(f), "")++ def test_a_broken_file_asks_for_a_jpeg_or_png(self):+ f = self.dir / "bad.png"+ f.write_bytes(b"not an image")+ msg = panel.h3_reference_image_error(f)+ self.assertIn("can't be read", msg)+ self.assertIn("JPEG or PNG", msg)++ def test_a_venv_without_pillow_sends_the_user_to_repair(self):+ f = self.dir / "ok.png"+ f.write_bytes(b"\\x89PNG")+ real_import = builtins.__import__++ def no_pil(name, *a, **k):+ if name == "PIL" or name.startswith("PIL."):+ raise ModuleNotFoundError("No module named 'PIL'")+ return real_import(name, *a, **k)++ with mock.patch.dict(sys.modules, {k: None for k in list(sys.modules)+ if k == "PIL" or k.startswith("PIL.")}), \+ mock.patch.object(builtins, "__import__", no_pil):+ msg = panel.h3_reference_image_error(f)+ self.assertNotIn("JPEG or PNG", msg)+ self.assertIn("venv", msg) # venv_broken in the taxonomy+ self.assertIn(panel.ENGINE_ENV_REPAIR, msg)+ self.assertEqual(panel._analytics_error_class(msg), "venv_broken")++ def test_the_render_path_uses_the_helper(self):+ import inspect+ src = inspect.getsource(panel.run_h3_job_inner)+ self.assertIn("h3_reference_image_error(", src)+ self.assertNotIn("from PIL import Image as _PilImg", src)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_h3_review_r2.py b/test_h3_review_r2.pyindex df8d6a1..d431d41 100644--- a/test_h3_review_r2.py+++ b/test_h3_review_r2.py@@ -410,7 +410,7 @@ class TestBrowserReplay(unittest.TestCase):def test_finish_restores_before_the_shape(self):js = (ROOT / "webapp" / "js" / "queue.js").read_text(encoding="utf-8")body = js.split("async function h3FinishActive()", 1)[1]- self.assertLess(body.index("_restoreLoraPicker(fields.loras)"),+ self.assertLess(body.index("_restoreLoraPicker(fields.loras"),body.index("setH3Tier(fields.h3_tier)"))self.assertLess(body.index("setH3Orientation(fields.h3_orientation)"),body.index("setH3Tier(fields.h3_tier)"))diff --git a/test_h3_vae_fp16.py b/test_h3_vae_fp16.pynew file mode 100644index 0000000..41f7297--- /dev/null+++ b/test_h3_vae_fp16.py@@ -0,0 +1,113 @@+"""H3 FP16 VAE decode is the default (4.16.0), and can be turned off.++perf/vae-2026-09-23 measured the runner's FP16 ViT decode on a real+1152x640/124f latent: 105.1 s -> 90.2 s, 11.1 -> 8.0 GiB, PSNR 72.8 dB. The+runner has carried it since minimax-h3-mlx 6bbed80 as `--vae-dtype float16`;+the panel passes it unless the `h3_vae_fp16` setting (default on since 4.16.0)+or PHOSPHENE_H3_VAE_FP16=0 turns it off. Popen is intercepted: nothing renders.+"""+from __future__ import annotations++import os+import sys+import tempfile+import unittest+import unittest.mock+from contextlib import ExitStack+from pathlib import Path++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT))+os.environ.setdefault("LTX_H3_FORCE_CAPABLE", "1")++import mlx_ltx_panel as P # noqa: E402++_TMP = Path(tempfile.mkdtemp(prefix="phos-h3-vae16-"))+++class _Intercept(Exception):+ pass+++def _argv(settings: dict, env: dict, runner_has_flag: bool = True):+ seen = {}++ def popen(cmd, **kw):+ seen["cmd"] = cmd+ raise _Intercept()+ job = {"id": "vae16", "params": {"engine": "h3", "mode": "t2v", "h3_tier": "standard_5s",+ "prompt": "a dancer", "seed": "7", "h3_turbo": False}}+ paths = dict(missing=[], repairable=False, dit=_TMP / "dit", python=sys.executable,+ runner=_TMP / "gen.py", compact_root=_TMP / "c", text_config=_TMP / "t")+ ff = _TMP / "ffmpeg"+ ff.write_text("")+ logs = []+ with ExitStack() as st:+ for name, val in {+ "h3_paths": lambda: paths, "h3_capable": lambda: True,+ "h3_supports_lora": lambda: True, "h3_supports_lora_stack": lambda: False,+ "h3_lora_max_stack": lambda: 1, "h3_dit_choice": lambda: ("bf16", None),+ "output_codec_settings": lambda: {"crf": "18", "pix_fmt": "yuv420p"},+ "_h3_runner_has_flag": lambda flag: runner_has_flag and flag == "--vae-dtype",+ "get_settings": lambda: dict(settings), "push": logs.append,+ "FFMPEG": ff}.items():+ st.enter_context(unittest.mock.patch.object(P, name, val))+ for name in ("h3_supports_memory_limits", "h3_supports_prompt_cache",+ "h3_live_preview_ready", "h3_supports_stage_a", "h3_supports_tae_draft"):+ st.enter_context(unittest.mock.patch.object(P, name, lambda: False))+ st.enter_context(unittest.mock.patch.object(P.HELPER, "is_alive", lambda: False))+ st.enter_context(unittest.mock.patch.object(P.subprocess, "Popen", popen))+ st.enter_context(unittest.mock.patch.dict(os.environ, env))+ if "PHOSPHENE_H3_VAE_FP16" not in env:+ os.environ.pop("PHOSPHENE_H3_VAE_FP16", None)+ try:+ P.run_h3_job_inner(job)+ except _Intercept:+ pass+ return seen["cmd"], job["params"], logs+++def _fp16(cmd) -> bool:+ return "--vae-dtype" in cmd and cmd[cmd.index("--vae-dtype") + 1] == "float16"+++class FP16DecodeIsTheDefault(unittest.TestCase):+ def test_on_by_default(self):+ # Flipped for 4.16.0 after the release A/B: 90.1 s -> 77.4 s decode,+ # no visible difference.+ self.assertTrue(P._settings_defaults()["h3_vae_fp16"])+ cmd, params, _ = _argv({}, {})+ self.assertTrue(_fp16(cmd), cmd)+ self.assertEqual(params["h3_vae_dtype"], "float16")++ def test_the_setting_turns_it_off(self):+ cmd, params, _ = _argv({"h3_vae_fp16": False}, {})+ self.assertNotIn("--vae-dtype", cmd)+ self.assertNotIn("h3_vae_dtype", params)++ def test_the_setting_turns_it_on_and_the_recipe_records_it(self):+ cmd, params, _ = _argv({"h3_vae_fp16": True}, {})+ self.assertTrue(_fp16(cmd), cmd)+ self.assertEqual(params["h3_vae_dtype"], "float16")++ def test_the_env_overrides_the_setting_both_ways(self):+ self.assertTrue(_fp16(_argv({}, {"PHOSPHENE_H3_VAE_FP16": "1"})[0]))+ self.assertNotIn("--vae-dtype", _argv({"h3_vae_fp16": True},+ {"PHOSPHENE_H3_VAE_FP16": "0"})[0])++ def test_an_old_runner_is_told_about_not_handed_an_unknown_flag(self):+ cmd, params, logs = _argv({"h3_vae_fp16": True}, {}, runner_has_flag=False)+ self.assertNotIn("--vae-dtype", cmd)+ self.assertNotIn("h3_vae_dtype", params)+ self.assertTrue(any("predates the faster FP16" in l for l in logs), logs)++ def test_the_setting_validates_and_is_readable(self):+ for raw, want in (("1", True), ("on", True), ("0", False), (False, False)):+ out, err = P._validate_settings_patch({"h3_vae_fp16": raw})+ self.assertIsNone(err)+ self.assertIs(out["h3_vae_fp16"], want)+ self.assertIn("h3_vae_fp16", P.get_settings_public())+++if __name__ == "__main__":+ unittest.main()diff --git a/test_image_engine_presets.py b/test_image_engine_presets.pyindex eec9fb5..326a86d 100644--- a/test_image_engine_presets.py+++ b/test_image_engine_presets.py@@ -26,6 +26,64 @@ def _cfg(override: str):return panel._build_image_engine_config(override, {})+class _Spawned(Exception):+ pass+++def _argv(cfg) -> list:+ """The mflux argv _generate_mflux would spawn — nothing is spawned."""+ import tempfile+ from pathlib import Path+ seen = {}++ def popen(cmd, *a, **k):+ seen["cmd"] = list(cmd)+ raise _Spawned()+ with tempfile.TemporaryDirectory() as tmp:+ ref = Path(tmp) / "ref.png"+ ref.write_bytes(b"x")+ with mock.patch.object(image_engine, "_resolve_mflux_bin", lambda c: "/nonexistent/mflux-generate-qwen-edit"), \+ mock.patch.object(image_engine, "repair_partial_hf_download", lambda *a, **k: None), \+ mock.patch("subprocess.Popen", popen):+ try:+ image_engine._generate_mflux("a test", 1, 512, 512, Path(tmp), 1, cfg, refs=[str(ref)])+ except _Spawned:+ pass+ return seen["cmd"]+++def _guidance(cfg) -> float:+ cmd = _argv(cfg)+ return float(cmd[cmd.index("--guidance") + 1])+++class LightningRunsWithoutCfg(unittest.TestCase):+ """Codex UI-03: Reference Edit Fast paired the 4-step Lightning adapter with+ `--guidance 4.0` (the qwen_edit family default, i.e. Quality's true-CFG)."""++ def test_fast_sends_guidance_one(self):+ cmd = _argv(_cfg("qwen_edit_lightning_inline"))+ self.assertEqual(float(cmd[cmd.index("--guidance") + 1]), 1.0)+ self.assertEqual(cmd[cmd.index("--steps") + 1], "4")+ self.assertIn("--lora-paths", cmd)++ def test_the_default_and_promoted_lightning_configs_send_guidance_one(self):+ self.assertEqual(_guidance(image_engine.ImageEngineConfig(+ kind="mflux", mflux_model="Qwen/Qwen-Image-Edit-2511", mflux_family="qwen_edit")), 1.0)+ with mock.patch.object(image_engine, "_resolve_mflux_bin", lambda c: "/x"):+ # a v2.x config: 8 steps, no LoRA — the branch that writes the recipe+ promoted = panel._auto_promote_image_engine_kind(image_engine.ImageEngineConfig(+ kind="mflux", mflux_family="qwen_edit", mflux_steps=8, mflux_lora_paths=[]))+ self.assertEqual(promoted.mflux_guidance, 1.0)+ self.assertEqual(_guidance(promoted), 1.0)++ def test_quality_keeps_its_cfg_and_an_explicit_value_wins(self):+ self.assertEqual(_guidance(_cfg("qwen_edit_high_inline")), 4.0)+ cfg = _cfg("qwen_edit_lightning_inline")+ cfg.mflux_guidance = 2.5+ self.assertEqual(_guidance(cfg), 2.5)++class PresetLoraContracts(unittest.TestCase):def test_quality_carries_no_lora(self):cfg = _cfg("qwen_edit_high_inline")diff --git a/test_modal_scaffold.py b/test_modal_scaffold.pynew file mode 100644index 0000000..4724ac5--- /dev/null+++ b/test_modal_scaffold.py@@ -0,0 +1,124 @@+"""Escape, the Tab trap and the scroll lock cover dialogs opened with `.show` (Codex UI-08).++health.js's scaffold matched `.modal-bg.show` at startup only (no dialog is+open then) and its isVisible() did not know the `show` class, so Storyboard's+re-plan dialog and the Editor's Generate-shot dialog — both opened with+classList.add('show') — ignored Escape, let Tab walk out, and never locked the+page scroll. Runs the REAL scaffold in node against a small DOM shim.+"""+from __future__ import annotations++import json+import shutil+import subprocess+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent++_JS = r"""+const fs = require('fs'), vm = require('vm');+const src = fs.readFileSync(process.argv[1] + '/webapp/js/health.js', 'utf8');+const a = src.indexOf('(function _phosModalScaffold');+const scaffold = src.slice(a, src.indexOf('})();', a) + 5);++const observers = [];+class CL {+ constructor(el, names) { this.el = el; this.s = new Set(names); }+ contains(c) { return this.s.has(c); }+ add(...c) { c.forEach(x => this.s.add(x)); this.el._mut('class'); }+ remove(...c) { c.forEach(x => this.s.delete(x)); this.el._mut('class'); }+ toggle(c, on) { on ? this.s.add(c) : this.s.delete(c); }+}+class El {+ constructor(tag, classes = [], attrs = {}) {+ this.tagName = tag.toUpperCase(); this.classList = new CL(this, classes);+ this.attrs = attrs; this.children = []; this.nodeType = 1; this.offsetWidth = 10;+ const self = this;+ this.style = new Proxy({}, {set(t, k, v) { t[k] = v; self._mut('style'); return true; }});+ }+ _mut(attr) { observers.filter(o => o.el === this).forEach(o => o.cb([{attributeName: attr}])); }+ add(c) { c.parent = this; this.children.push(c); return c; }+ getAttribute(k) { return this.attrs[k] ?? null; }+ all() { return this.children.flatMap(c => [c, ...c.all()]); }+ _one(sel) {+ sel = sel.trim();+ if (/^button/.test(sel)) {+ if (this.tagName !== 'BUTTON') return false;+ const m = sel.match(/\[onclick\*="(\w+)"\]/);+ if (m) return (this.attrs.onclick || '').includes(m[1]);+ if (/\[onclick\]/.test(sel)) return 'onclick' in this.attrs;+ return true;+ }+ if (sel.startsWith('.')) return sel.slice(1).split('.').every(c => this.classList.contains(c));+ return false;+ }+ matches(sel) { return sel.split(',').some(s => this._one(s)); }+ querySelectorAll(sel) { return this.all().filter(e => e.matches(sel)); }+ querySelector(sel) { return this.querySelectorAll(sel)[0] || null; }+ contains(e) { return e === this || this.all().includes(e); }+ focus() { doc.activeElement = this; }+ click() { if (this.onclick) this.onclick(); }+}+const body = new El('body');+const listeners = {};+const doc = {+ body, activeElement: body,+ querySelectorAll: sel => body.querySelectorAll(sel),+ querySelector: sel => body.querySelector(sel),+ addEventListener: (t, f) => (listeners[t] = listeners[t] || []).push(f),+};+const outside = body.add(new El('button', [], {}));+const replan = body.add(new El('div', ['modal-bg']));+const cancel = replan.add(new El('button', [], {onclick: 'sbCloseReplan()'}));+cancel.onclick = () => replan.classList.remove('show');+const go = replan.add(new El('button', [], {onclick: 'sbReplan()'}));+const raw = body.add(new El('div', ['modal-bg']));+// sbRawModal's Close button names no close function: the fallback must close it+raw.add(new El('button', [], {onclick: "document.getElementById('sbRawModal').classList.remove('show')"}));++const ctx = {document: doc, console, Array, Set, WeakSet,+ MutationObserver: class { constructor(cb) { this.cb = cb; } observe(el) { this.el = el; observers.push(this); } }};+vm.createContext(ctx);+vm.runInContext(scaffold, ctx);+const key = (k, shift) => { const e = {key: k, shiftKey: !!shift, preventDefault() {}, stopPropagation() {}};+ (listeners.keydown || []).forEach(f => f(e)); };+const out = {};+replan.classList.add('show'); // opened AFTER startup+out.lockedOnOpen = body.classList.contains('modal-open');+doc.activeElement = outside;+key('Tab');+out.tabLandsInside = replan.contains(doc.activeElement);+key('Escape');+out.closedByEscape = !replan.classList.contains('show');+out.unlockedOnClose = !body.classList.contains('modal-open');+replan.classList.add('show');+out.reopens = replan.classList.contains('show') && replan.style.display !== 'none';+key('Escape');+raw.classList.add('show');+key('Escape');+out.rawClosed = !raw.classList.contains('show');+raw.classList.add('show');+out.rawReopens = raw.classList.contains('show') && raw.style.display !== 'none';+process.stdout.write(JSON.stringify(out));+"""++[email protected](shutil.which("node"), "node not on PATH")+class ClassOpenedDialogs(unittest.TestCase):+ def test_escape_tab_and_scroll_lock_follow_a_show_dialog(self):+ r = subprocess.run(["node", "-e", _JS, str(ROOT)], capture_output=True, text=True,+ errors="replace", timeout=60)+ self.assertEqual(r.returncode, 0, r.stderr)+ out = json.loads(r.stdout)+ self.assertTrue(out["lockedOnOpen"], out)+ self.assertTrue(out["tabLandsInside"], out)+ self.assertTrue(out["closedByEscape"], out)+ self.assertTrue(out["unlockedOnClose"], out)+ self.assertTrue(out["reopens"], out)+ self.assertTrue(out["rawClosed"], out)+ self.assertTrue(out["rawReopens"], out)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_music_compose_contract.py b/test_music_compose_contract.pynew file mode 100644index 0000000..3bb2d2c--- /dev/null+++ b/test_music_compose_contract.py@@ -0,0 +1,249 @@+#!/usr/bin/env python3+"""What Compose sends, and what the panel refuses rather than render wrong.++ * M6-05 LoRA picks went out as `id:strength` joined by commas; a filename+ with a comma split into two ids nobody has, both were dropped, and+ the song came back without the ticked voice.+ * M6-07 Cover with no recording was indistinguishable from Write and+ composed a new song instead of refusing.+ * M6-09 The LoRA / cover-model downloads reported only their start; the+ next status tick painted the Download offer back and a failure+ never reached the screen.++Browser halves run in node against a DOM stub; server halves run the real+make_job / music_params / music_argv / music_status against scratch folders.+"""+from __future__ import annotations++import json+import shutil+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path+from unittest import mock+from urllib.parse import parse_qs, urlencode++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as P # noqa: E402+from scripts.extract_panel_js import extract_function # noqa: E402++NODE = shutil.which("node")+CHARS = (ROOT / "webapp/js/characters.js").read_text()++NAMES = ["user/Voice, warm.safetensors", "user/日本 語:take 2.safetensors",+ "user/plain.safetensors"]+++def _node(script: str):+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ try:+ out = subprocess.run([NODE, fh.name], capture_output=True, text=True, timeout=30)+ finally:+ Path(fh.name).unlink(missing_ok=True)+ if out.returncode:+ raise AssertionError(out.stderr)+ return json.loads(out.stdout)+++DOM = r"""+const mk = (extra) => Object.assign({ hidden: false, innerHTML: '', value: '', textContent: '',+ checked: false, open: false, dataset: {}, querySelectorAll: () => [] }, extra || {});+const els = {};+const document = { getElementById: id => els[id] || (els[id] = mk()),+ querySelectorAll: () => [] };+function row(id, on, strength) {+ const cb = { checked: on }, rg = { value: String(strength) };+ return { dataset: { id }, querySelector: sel => sel.includes('checkbox') ? cb : rg };+}+const charactersEscapeHtml = s => String(s == null ? '' : s).replace(/[&<>"']/g, c =>+ ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);+"""+++class Sandbox(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ self.root = Path(self.tmp.name)+ self.loras = self.root / "loras"+ (self.loras / "user").mkdir(parents=True)+ for n in NAMES:+ (self.loras / n).write_bytes(b"x" * 64)+ p = mock.patch.object(P, "MUSIC_LORAS", self.loras)+ p.start()+ self.addCleanup(p.stop)++[email protected](NODE is None, "node not on PATH")+class PicksSurviveTheirFilenames(Sandbox):+ """M6-05."""++ def _browser_field(self):+ funcs = extract_function("musicLoraPicks", CHARS)+ rows = json.dumps([[n, True, s] for n, s in zip(NAMES, (0.8, 1.2, 0.5))])+ return _node(DOM + funcs + r"""+els.musicLoraList = mk({ querySelectorAll: () =>+ """ + rows + r""".map(([id, on, s]) => row(id, on, s)).concat([row('user/off.safetensors', false, 1)]) });+process.stdout.write(JSON.stringify(musicLoraPicks()));+""")++ def test_the_exact_files_and_strengths_reach_the_runner(self):+ field = self._browser_field()+ form = parse_qs(urlencode({"mode": "music", "music_style": "dub",+ "music_loras": field}))+ picks = P.music_params(form)["music_loras"]+ self.assertEqual([(p["id"], p["strength"]) for p in picks],+ list(zip(NAMES, (0.8, 1.2, 0.5))))+ job = P.make_job(form)+ paths = {"python": Path("/x/py"), "runner": Path("/x/run.py"),+ "generator": Path("/x/gen"), "vae": Path("/x/vae")}+ argv = P.music_argv(job, paths, self.root / "o.wav")+ loras = [argv[i + 1] for i, a in enumerate(argv) if a == "--lora"]+ self.assertEqual(loras, [f"{(self.loras / n).resolve()}:{s:g}"+ for n, s in zip(NAMES, (0.8, 1.2, 0.5))])++ def test_a_pick_that_does_not_resolve_is_refused_not_dropped(self):+ form = parse_qs(urlencode({"mode": "music", "music_style": "dub",+ "music_loras": json.dumps(+ [{"id": "user/gone.safetensors", "strength": 1}])}))+ with self.assertRaises(P.MusicRequestError) as cm:+ P.make_job(form)+ self.assertIn("user/gone.safetensors", str(cm.exception))++ def test_queue_add_answers_the_refusal_with_a_400(self):+ from panel import routes_queue+ routes_queue.P = P++ class H:+ def _read_form_body(self):+ return b"", {"mode": ["music"], "music_style": ["dub"],+ "music_loras": ['[{"id": "user/gone.safetensors"}]']}++ def _json(self, payload, status=200):+ self.payload, self.status = payload, status++ h = H()+ with mock.patch.object(P, "STATE", {"queue": []}), \+ mock.patch.object(P, "persist_queue", lambda: None):+ routes_queue.post_run(h, "/queue/add", {}, "")+ self.assertEqual(h.status, 400)+ self.assertIn("not in the music LoRA folder", h.payload["error"])++ def test_the_summary_reads_the_json(self):+ funcs = "\n".join(extract_function(n, CHARS) for n in+ ("musicLoraPicks", "musicLoraSummaryText"))+ out = _node(DOM + funcs + r"""+els.musicInstrumental = mk({ checked: false });+els.musicLoraList = mk({ querySelectorAll: () => [row('user/Voice, warm.safetensors', true, 0.8)] });+process.stdout.write(JSON.stringify((musicLoraSummaryText(), els.musicLoraSummary.textContent)));+""")+ self.assertTrue(out.endswith("@ 0.80"), out)++[email protected](NODE is None, "node not on PATH")+class CoverNeedsARecording(Sandbox):+ """M6-07."""++ def test_the_composer_queues_nothing_without_a_recording(self):+ funcs = "\n".join(extract_function(n, CHARS) for n in+ ("musicGenerate", "musicFormParams", "musicCfgValue",+ "musicLoraPicks"))+ out = _node(DOM + r"""+const window = { _ENGINE_PROBES: { music: { available: true, cover: { ready: false } } } };+let musicBusy = false;+function musicSimpleActive() { return false; }+function musicFormChanged() {}+const posted = [];+global.fetch = async (url) => { posted.push(url); return { ok: true, json: async () => ({}) }; };+els.musicTask = mk({ value: 'cover' });+els.musicInstrumental = mk({ checked: false });+els.musicLyrics = mk({ value: 'la la' }); els.musicStyle = mk({ value: 'folk' });+els.musicMode = mk({ value: 'full' }); els.musicMaxSeconds = mk({ value: '120' });+els.musicSeed = mk({ value: '-1' }); els.musicQuality = mk({ value: 'final' });+els.musicSourceAudio = mk({ value: ' ' });+""" + funcs + r"""+(async () => {+ await musicGenerate();+ process.stdout.write(JSON.stringify({ posted, status: els.musicStatus.textContent,+ opened: els.musicCoverDetails.open,+ task: musicFormParams().get('music_task') }));+})();+""")+ self.assertEqual(out["posted"], [])+ self.assertIn("recording", out["status"])+ self.assertTrue(out["opened"])+ self.assertEqual(out["task"], "cover")++ def _job(self, **form):+ base = {"mode": "music", "music_style": "folk"}+ base.update(form)+ return P.make_job(parse_qs(urlencode(base)))++ def test_the_server_refuses_an_empty_or_missing_recording(self):+ for src in ("", " ", str(self.root / "nope.wav")):+ with self.assertRaises(P.MusicRequestError, msg=repr(src)):+ self._job(music_task="cover", music_source_audio=src)++ def test_a_real_recording_is_a_cover_and_write_needs_none(self):+ rec = self.root / "take.wav"+ rec.write_bytes(b"RIFF")+ job = self._job(music_task="cover", music_source_audio=str(rec))+ self.assertEqual(job["params"]["music_source_audio"], str(rec))+ self.assertEqual(job["params"]["music_task"], "cover")+ self.assertEqual(self._job(music_task="write")["params"]["music_source_audio"], "")+ # A caller that predates the field is judged as before.+ self.assertEqual(self._job()["params"]["music_task"], "")+++class DownloadsSayWhatTheyAreDoing(unittest.TestCase):+ """M6-09."""++ def test_status_carries_both_fetch_states(self):+ with mock.patch.dict(P._MUSIC_LORA_FETCH, running=True, line="adapter 1/2", error=""), \+ mock.patch.dict(P._MUSIC_COVER_FETCH, running=False, line="",+ error="the transcription models failed (exit 1)"):+ st = P.music_status()+ self.assertEqual(st["loras"]["fetch"]["line"], "adapter 1/2")+ self.assertTrue(st["loras"]["fetch"]["running"])+ self.assertIn("exit 1", st["cover"]["fetch"]["error"])++ @unittest.skipIf(NODE is None, "node not on PATH")+ def test_the_cards_show_progress_failure_and_retry(self):+ funcs = "\n".join(extract_function(n, CHARS) for n in+ ("musicFetchCard", "musicLoraInstallCard",+ "musicCoverInstallCard"))+ out = _node(DOM + funcs + r"""+els.musicInstrumental = mk({ checked: true });+els.musicSourceAudio = mk({ value: '/rec.wav' });+const html = [];+for (const fetch of [{ running: true, line: 'adapter 1/2' },+ { running: false, error: 'disk <full>' }, {}]) {+ musicLoraInstallCard({ loras: { instrumental_ready: false, bytes: 2.1e8, fetch } });+ musicCoverInstallCard({ cover: { ready: false, bytes: 2.8e9, fetch } });+ html.push([els.musicLoraInstall.innerHTML, els.musicCoverInstall.innerHTML]);+}+process.stdout.write(JSON.stringify(html));+""")+ running, failed, idle = out+ for card in running:+ self.assertIn("Downloading", card)+ self.assertNotIn("Download it", card)+ self.assertNotIn("Download them", card)+ self.assertIn("adapter 1/2", running[0])+ for card in failed:+ self.assertIn("failed", card)+ self.assertIn("disk <full>", card)+ self.assertIn("Try again", card)+ self.assertIn('onclick="musicLoraInstall()"', failed[0])+ self.assertIn('onclick="musicCoverInstall()"', failed[1])+ self.assertIn("Download it", idle[0])+ self.assertIn("Download them", idle[1])+++if __name__ == "__main__":+ unittest.main()diff --git a/test_music_cover.py b/test_music_cover.pynew file mode 100644index 0000000..cfedc61--- /dev/null+++ b/test_music_cover.py@@ -0,0 +1,223 @@+"""Cover: a real recording in, a new song out.++The engine has been able to do this since the pin — `lyra cover` transcribes a+mix into an ABC score with SheetSage2 and hands that score to the generator as+the plan. Phosphene exposed none of it. This is the wiring, and these are the+rules that keep it honest:++ * the two transcription models are an OPT-IN ~2.8 GB, so a cover asked for+ without them must fail at the form, not ten minutes into a job;+ * the transcription task decides the planning mode, because a full+ transcription can only be realised by full planning;+ * a supplied ABC file and a source recording are the same input arriving two+ ways, so asking for both is a refusal rather than a silent winner;+ * transcription shells out to ffmpeg, which on a Pinokio-started panel is not+ on PATH — the same trap that cost five installs their exports in 4.15.1.+"""+import subprocess+import sys+import unittest+from unittest import mock+from pathlib import Path++import mlx_ltx_panel as P++RUNNER = Path(__file__).with_name("scripts") / "music" / "yue2_run.py"+++class TheFormCarriesIt(unittest.TestCase):++ def test_a_source_song_survives_the_allowlist(self):+ p = P.music_params({"music_style": "dream pop",+ "music_source_audio": "/tmp/a song.wav"})+ self.assertEqual(p["music_source_audio"], "/tmp/a song.wav")++ def test_a_pasted_finder_path_is_cleaned(self):+ """Same treatment as every other path field: the field is in+ PASTED_PATH_FIELDS, so a dragged path with a tilde and stray spaces+ is a path by the time a gate looks at it."""+ self.assertIn("music_source_audio", P.PASTED_PATH_FIELDS)+ p = P.music_params({"music_source_audio": " ~/Music/x.wav "})+ self.assertTrue(p["music_source_audio"].startswith("/"))+ self.assertTrue(p["music_source_audio"].endswith("Music/x.wav"))++ def test_no_source_song_is_the_ordinary_job(self):+ p = P.music_params({"music_style": "dream pop"})+ self.assertEqual(p["music_source_audio"], "")++ def test_the_task_is_a_closed_vocabulary(self):+ for bad in ("", "everything", "../../etc"):+ p = P.music_params({"music_cover_task": bad})+ self.assertEqual(p["music_cover_task"], "melody-full")+ for good in ("full", "melody-full", "melody-vocal"):+ p = P.music_params({"music_cover_task": good})+ self.assertEqual(p["music_cover_task"], good)+++class TheArgvSaysIt(unittest.TestCase):++ def argv(self, form):+ job = {"id": "j-1", "params": form}+ paths = {"python": Path("/x/python"), "runner": RUNNER,+ "generator": Path("/x/gen"), "vae": Path("/x/vae")}+ return P.music_argv(job, paths, Path("/tmp/out.wav"))++ def test_a_prompt_job_passes_no_cover_flags(self):+ argv = self.argv({"music_style": "dream pop"})+ self.assertNotIn("--source-audio", argv)++ def test_a_cover_job_passes_the_source_the_task_and_both_models(self):+ argv = self.argv({"music_style": "dream pop",+ "music_source_audio": "/tmp/song.mp3",+ "music_cover_task": "melody-vocal"})+ self.assertEqual(argv[argv.index("--source-audio") + 1], "/tmp/song.mp3")+ self.assertEqual(argv[argv.index("--cover-task") + 1], "melody-vocal")+ self.assertTrue(argv[argv.index("--transcription-model") + 1].endswith("sheetsage2"))+ self.assertTrue(argv[argv.index("--transcription-base-model") + 1].endswith("mert2"))+++class TheRunnerRefusesTheImpossible(unittest.TestCase):+ """Driven as a subprocess against the real script: these are argument+ rules, so they answer before any model is loaded."""++ def run_runner(self, *extra):+ out = subprocess.run(+ [sys.executable, str(RUNNER), "--model-dir", "/x", "--vae-dir", "/x",+ "--output", "/tmp/never-written.wav", "--style", "pop", *extra],+ capture_output=True, text=True, timeout=120)+ return out.returncode, out.stdout + out.stderr++ def test_a_missing_source_song_is_named(self):+ rc, out = self.run_runner("--source-audio", "/tmp/definitely-not-here.mp3")+ self.assertEqual(rc, 2)+ self.assertIn("source song not found", out)++ def test_a_score_and_a_recording_together_are_refused(self):+ with open("/tmp/cover_test_score.abc", "w") as fh:+ fh.write("X:1\n")+ rc, out = self.run_runner("--source-audio", "/tmp/cover_test_score.abc",+ "--abc-file", "/tmp/cover_test_score.abc")+ self.assertEqual(rc, 2)+ self.assertIn("drop the ABC file", out)++ def test_the_task_choices_are_the_engines_own(self):+ rc, out = self.run_runner("--cover-task", "melody")+ self.assertNotEqual(rc, 0)+ self.assertIn("invalid choice", out.lower())+++class TheModelsAreOptional(unittest.TestCase):++ def test_status_reports_what_is_missing_rather_than_a_boolean(self):+ st = P.music_cover_status()+ self.assertIn("ready", st)+ self.assertIn("missing", st)+ self.assertIn("bytes", st)+ if not st["ready"]:+ self.assertTrue(all("/" in m for m in st["missing"]))++ def test_cover_readiness_rides_on_music_status(self):+ """The Compose card reads one payload."""+ self.assertIn("cover", P.music_status())++ def test_the_fetcher_pins_the_revisions_the_engine_pins(self):+ """SheetSage2's config carries the sha256 of the MERT checkpoint it was+ trained against and refuses to load beside any other one."""+ from scripts.pinokio.music_cover_fetch import SOURCES+ model = (Path(__file__).with_name("yue2-mlx") / "src" / "lyra" /+ "transcription" / "model.py").read_text()+ self.assertIn(SOURCES["sheetsage2"]["revision"], model)+ self.assertIn(SOURCES["mert2"]["revision"], model)+++class AnInterruptedCopyIsNeverReady(unittest.TestCase):+ """Codex INST-10: the cover models were copied straight onto their final+ names and "ready" meant "nonzero size", so a copy cut short left a+ truncated checkpoint that readiness accepted and every retry skipped.+ Fake HF: nothing is downloaded, everything lives in a temp dir."""++ def setUp(self):+ import sys as _sys+ import tempfile+ import types+ from scripts.pinokio import music_cover_fetch as mcf+ self.mcf = mcf+ self.tmp = tempfile.TemporaryDirectory()+ base = Path(self.tmp.name)+ self.root = base / "yue2-cover"+ self.cache = base / "hf"+ self.cache.mkdir()+ self.payload = {n: (n * 50).encode() for n in mcf.FILES + mcf.EXTRA}++ def fake_download(repo_id, revision, filename):+ f = self.cache / repo_id.replace("/", "_") / filename+ f.parent.mkdir(parents=True, exist_ok=True)+ f.write_bytes(self.payload[filename])+ return str(f)+ self._hub = _sys.modules.get("huggingface_hub")+ _sys.modules["huggingface_hub"] = types.SimpleNamespace(hf_hub_download=fake_download)++ def tearDown(self):+ import sys as _sys+ if self._hub is not None:+ _sys.modules["huggingface_hub"] = self._hub+ else:+ _sys.modules.pop("huggingface_hub", None)+ self.tmp.cleanup()++ def test_a_copy_cut_short_stays_not_ready_and_the_retry_repairs_it(self):+ mcf = self.mcf+ real = mcf.shutil.copyfile++ def dies_half_way(src, dst):+ Path(dst).write_bytes(Path(src).read_bytes()[:7])+ raise OSError(28, "No space left on device")+ with mock.patch.object(mcf.shutil, "copyfile", dies_half_way):+ with self.assertRaises(OSError):+ mcf.fetch(self.root, min_free_gb=0)+ self.assertTrue(mcf.cover_problems(self.root), "a truncated copy read as ready")+ self.assertEqual(real, mcf.shutil.copyfile)+ mcf.fetch(self.root, min_free_gb=0)+ self.assertEqual(mcf.cover_problems(self.root), [])+ for part in mcf.SOURCES:+ for n in mcf.FILES:+ self.assertEqual((self.root / part / n).read_bytes(), self.payload[n])++ def test_a_truncated_file_from_the_old_copier_is_replaced(self):+ mcf = self.mcf+ for part in mcf.SOURCES:+ for n in mcf.FILES:+ f = self.root / part / n+ f.parent.mkdir(parents=True, exist_ok=True)+ f.write_bytes(b"trunc") # nonzero, and no receipt+ self.assertTrue(mcf.cover_problems(self.root))+ mcf.fetch(self.root, min_free_gb=0)+ self.assertEqual((self.root / "mert2" / "model.safetensors").read_bytes(),+ self.payload["model.safetensors"])++ def test_a_finished_install_from_before_the_size_receipt_stays_ready(self):+ mcf = self.mcf+ for part in mcf.SOURCES:+ for n in mcf.FILES:+ f = self.root / part / n+ f.parent.mkdir(parents=True, exist_ok=True)+ f.write_bytes(self.payload[n])+ (self.root / "pack_source.json").write_text('{"sources": {}, "files": []}')+ self.assertEqual(mcf.cover_problems(self.root), [])+++class FfmpegReachesTheChild(unittest.TestCase):++ def test_the_music_child_gets_the_resolved_ffmpeg_on_path(self):+ """Transcription builds an ffmpeg argv and reads f32le off its stdout.+ Pinokio's bundled binary is not on the default PATH."""+ env = P.music_child_env({"PATH": "/usr/bin"})+ self.assertTrue(env["PATH"].startswith(str(P.FFMPEG_BIN)))++ def test_the_mps_strip_still_happens(self):+ env = P.music_child_env({"PYTORCH_ENABLE_MPS_FALLBACK": "1", "PATH": "/usr/bin"})+ self.assertNotIn("PYTORCH_ENABLE_MPS_FALLBACK", env)+++if __name__ == "__main__":+ unittest.main(verbosity=2)diff --git a/test_music_engine.py b/test_music_engine.pyindex e72b198..932a2af 100644--- a/test_music_engine.py+++ b/test_music_engine.py@@ -398,7 +398,7 @@ const document={getElementById:id=>els[id]}; const AUDIO_STUDIO={};const findOutputByPath=()=>({clip_sec:120}); const audioModeSet=m=>{mode=m};const workflowSwitch=w=>{workflow=w};const audioStudioRenderSlots=()=>{}; const phosToast=()=>{};const fetch=()=>{submits++};-''' + extract_function("musicFormParams", src) + extract_function("useTrackInA2V", src) + '''+''' + extract_function("musicFormParams", src) + extract_function("musicCfgValue", src) + extract_function("useTrackInA2V", src) + '''const payload=Object.fromEntries(musicFormParams());useTrackInA2V('/tmp/song.wav');console.log(JSON.stringify({payload,lyrics:els.musicLyrics.value,AUDIO_STUDIO,submits,mode,workflow}));''')assert result["payload"]["music_instrumental"] == "on" and result["payload"]["music_lyrics"] == ""@@ -407,22 +407,175 @@ console.log(JSON.stringify({payload,lyrics:els.musicLyrics.value,AUDIO_STUDIO,suassert result["AUDIO_STUDIO"]["audioPath"] == "/tmp/song.wav"+def test_the_lyrics_editor_is_sections_and_the_brackets_stay_the_truth():+ """The editor shows sections; #musicLyrics is still the only field the+ rest of the form reads, so every structural edit has to land there."""+ src = (ROOT / "webapp/js/music.js").read_text()+ funcs = "\n".join(extract_function(n, src) for n in (+ "_el", "_lyricsParse", "_lyricsText", "_lyricsLineCount", "_lyricsCountLabel",+ "_lyricsSync", "_lyricsGrow", "musicLyricsRender", "musicLyricsType",+ "musicLyricsRetag", "musicLyricsMove", "musicLyricsRemove", "musicLyricsAdd",+ "musicLyricsSet", "musicLyricsView", "musicLyricsRawSync", "musicLyricsLock"))+ ids = ["musicLyrics", "musicLyricsRaw", "musicLyricsEditor", "musicLyricsSections",+ "musicLyricsAdd", "musicStatus", "musicConcept", "musicStyle", "musicMaxSeconds"]+ result = node_eval("""+const LYRIC_LABELS=['Intro','Verse','Pre-Chorus','Chorus','Bridge','Instrumental','Outro'];+let LYRICS=[],lyricsView='sections',lyricsBusy=-1;+const _esc=s=>String(s==null?'':s).replace(/&/g,'&').replace(/</g,'<').replace(/"/g,'"');+const mk=()=>{const cls=[];return {cls,value:'',hidden:false,innerHTML:'',disabled:false,style:{},+ classList:{toggle:(c,on)=>{const i=cls.indexOf(c);if(on&&i<0)cls.push(c);if(!on&&i>=0)cls.splice(i,1);}},+ querySelectorAll:()=>[],querySelector:()=>null,setAttribute(){},focus(){}};};+const els=Object.fromEntries(""" + json.dumps(ids) + """.map(id=>[id,mk()]));+const document={getElementById:id=>els[id]||null,querySelectorAll:()=>[]};+const musicFormChanged=()=>{};+""" + funcs + """+const SONG='[Intro]\\n\\n[Verse]\\none line\\ntwo line\\n\\n[Chorus]\\nthe hook';+musicLyricsSet(SONG);+const afterSet=els.musicLyrics.value, html=els.musicLyricsSections.innerHTML;+musicLyricsMove(1,-1); const afterMove=els.musicLyrics.value;+musicLyricsMove(0,1); musicLyricsRetag(2,'Bridge'); const afterRetag=els.musicLyrics.value;+musicLyricsRemove(0); musicLyricsAdd('Outro'); const afterAdd=els.musicLyrics.value;+musicLyricsType(0,{value:'new words\\nhere',closest:()=>null,style:{},scrollHeight:0});+const afterType=els.musicLyrics.value;+musicLyricsView('text');+const text={raw:els.musicLyricsRaw.value,editor:els.musicLyricsEditor.hidden,box:els.musicLyricsRaw.hidden};+els.musicLyricsRaw.value='[Verse]\\ntyped by hand\\n\\n[Chorus]\\n';+musicLyricsView('sections');+const afterText=els.musicLyrics.value, backToSections=els.musicLyricsEditor.hidden;+els.musicLyrics.disabled=true; musicLyricsRender();+const locked=els.musicLyricsEditor.cls.includes('lyr-off');+console.log(JSON.stringify({afterSet,html,afterMove,afterRetag,afterAdd,afterType,text,afterText,backToSections,locked}));+""")+ # Round trip: what the editor writes back is the same bracket text, tags+ # unnumbered, an empty section still an instrumental passage.+ assert result["afterSet"] == "[Intro]\n\n[Verse]\none line\ntwo line\n\n[Chorus]\nthe hook"+ # Every section says what it costs, and a wordless one says so in place.+ assert "2 lines" in result["html"] and "1 line" in result["html"]+ assert "no words" in result["html"] and "wordless" in result["html"]+ assert "instrumental passage" in result["html"]+ # Structure is editable: reorder, retag, delete, add — all through the+ # hidden field, because that is what musicFormParams sends.+ assert result["afterMove"].startswith("[Verse]\none line")+ assert "[Bridge]\nthe hook" in result["afterRetag"] and "[Chorus]" not in result["afterRetag"]+ assert result["afterAdd"] == "[Verse]\none line\ntwo line\n\n[Bridge]\nthe hook\n\n[Outro]"+ assert result["afterType"] == "[Verse]\nnew words\nhere\n\n[Bridge]\nthe hook\n\n[Outro]"+ # Text mode is the same truth typed by hand, and it re-parses on the way back.+ assert result["text"]["raw"] == result["afterType"]+ assert result["text"]["editor"] is True and result["text"]["box"] is False+ assert result["afterText"] == "[Verse]\ntyped by hand\n\n[Chorus]"+ assert result["backToSections"] is False+ # Instrumental: the words stay, the editor goes quiet — including the+ # controls a re-render has just rebuilt.+ assert result["locked"] is True+++def test_simple_mode_writes_the_brief_and_renders_nothing():+ """Simple is one box. Compose in Simple asks Gemma for the style and the+ words, fills the Custom fields with them and STOPS — the song itself is+ minutes of GPU, so the second press is the user's."""+ music = (ROOT / "webapp/js/music.js").read_text()+ chars = (ROOT / "webapp/js/characters.js").read_text()+ funcs = "\n".join(extract_function(n, music) for n in (+ "_el", "_mmss", "_lyricsParse", "_lyricsText", "_lyricsLineCount", "_lyricsCountLabel",+ "_lyricsSync", "_lyricsGrow", "musicLyricsRender", "musicLyricsLock", "musicLyricsSet",+ "musicTaskSet", "musicSimpleActive", "musicSimpleMirror", "musicSimpleChanged",+ "musicModeApply", "musicModeSet", "musicModeInit", "musicSimpleCompose",+ )) + "\n" + extract_function("musicGenerate", chars)+ ids = ["musicSimplePane", "musicCustomPane", "musicSimpleSeconds", "musicSimpleSecondsVal",+ "musicSimpleInstrumental", "musicMaxSeconds", "musicInstrumental", "musicSimpleDescription",+ "musicSimpleNotice", "musicGenBtn", "musicStatus", "musicTitle", "musicStyle", "musicConcept",+ "musicTask", "musicCoverDetails", "musicLyrics", "musicLyricsRaw", "musicLyricsEditor",+ "musicLyricsSections", "musicLyricsAdd", "musicSourceAudio", "musicCoverTask"]+ result = node_eval("""+const LYRIC_LABELS=['Intro','Verse','Pre-Chorus','Chorus','Bridge','Instrumental','Outro'];+let LYRICS=[],lyricsView='sections',lyricsBusy=-1,musicMode='custom',musicBusy=false;+const _esc=s=>String(s==null?'':s).replace(/&/g,'&').replace(/</g,'<').replace(/"/g,'"');+const cl=cls=>({toggle:(c,on)=>{const i=cls.indexOf(c);if(on&&i<0)cls.push(c);if(!on&&i>=0)cls.splice(i,1);}});+const mk=()=>{const cls=[];return {cls,value:'',hidden:false,innerHTML:'',textContent:'',disabled:false,+ checked:false,open:false,style:{},classList:cl(cls),querySelectorAll:()=>[],querySelector:()=>null,+ setAttribute(){},focus(){focused=this;}};};+let focused=null;+const els=Object.fromEntries(""" + json.dumps(ids) + """.map(id=>[id,mk()]));+const seg=v=>{const cls=[];return {cls,dataset:{value:v},classList:cl(cls),setAttribute(){}};};+const groups={'#musicModeSeg .seg-btn':['simple','custom'].map(seg),+ '#musicTaskPills .seg-btn':['write','cover','score'].map(seg)};+const document={getElementById:id=>els[id]||null,querySelectorAll:s=>groups[s]||[]};+const store={};+const localStorage={getItem:k=>(k in store?store[k]:null),setItem:(k,v)=>{store[k]=v;}};+const window={_ENGINE_PROBES:{music:{available:true,capable:true,estimates:{},cover:{ready:true}}}};+let posts=[],queued=0;+const fetch=(url,opt)=>{posts.push(url); if(url==='/queue/add')queued++;+ return Promise.resolve({ok:true,json:async()=>({ok:true,title:'Leaving Town',+ style:'English, slow piano ballad, low warm female voice, brushed drums, 72 BPM',+ lyrics:'[Verse]\\nthe boxes by the door\\n\\n[Chorus]\\nyou are going',elapsed_sec:8})});};+const musicFormChanged=()=>{};const poll=async()=>{};const setMainOutputsFilter=()=>{};+const openMusicInstallCard=()=>{};const musicTranscribe=()=>{};+""" + funcs + """+(async()=>{+els.musicMaxSeconds.value='240';+musicModeInit();+const start={active:musicSimpleActive(),simple:els.musicSimplePane.hidden,custom:els.musicCustomPane.hidden};+musicModeSet('simple');+const inSimple={active:musicSimpleActive(),simple:els.musicSimplePane.hidden,custom:els.musicCustomPane.hidden,+ saved:store.phos_music_mode,secs:els.musicSimpleSeconds.value,label:els.musicSimpleSecondsVal.textContent,+ on:groups['#musicModeSeg .seg-btn'].filter(b=>b.cls.includes('active')).map(b=>b.dataset.value)};+els.musicSimpleSeconds.value='90';els.musicSimpleInstrumental.checked=true;musicSimpleChanged();+const mirrored={max:els.musicMaxSeconds.value,inst:els.musicInstrumental.checked,label:els.musicSimpleSecondsVal.textContent};+els.musicSimpleInstrumental.checked=false;musicSimpleChanged();+els.musicSimpleDescription.value='a slow piano ballad for a friend moving away';+await musicGenerate();+const after={title:els.musicTitle.value,style:els.musicStyle.value,lyrics:els.musicLyrics.value,+ concept:els.musicConcept.value,active:musicSimpleActive(),custom:els.musicCustomPane.hidden,+ notice:els.musicSimpleNotice.hidden,noticeText:els.musicSimpleNotice.textContent,+ posts,queued,btn:els.musicGenBtn.textContent,focusedGen:focused===els.musicGenBtn,saved:store.phos_music_mode};+console.log(JSON.stringify({start,inSimple,mirrored,after}));+})();""")+ # Custom is the default, and the choice is remembered once it is made.+ assert result["start"] == {"active": False, "simple": True, "custom": False}+ assert result["inSimple"]["active"] is True+ assert result["inSimple"]["simple"] is False and result["inSimple"]["custom"] is True+ assert result["inSimple"]["saved"] == "simple" and result["inSimple"]["on"] == ["simple"]+ # Simple's two knobs ARE Custom's two fields — one value, shown twice.+ assert result["inSimple"]["secs"] == "240" and result["inSimple"]["label"] == "4:00"+ assert result["mirrored"] == {"max": "90", "inst": True, "label": "1:30"}+ # Compose in Simple writes the brief into the Custom fields and queues+ # nothing: one POST, to /music/simple, and no job.+ a = result["after"]+ assert a["posts"] == ["/music/simple"] and a["queued"] == 0+ assert a["title"] == "Leaving Town" and a["style"].startswith("English, slow piano ballad")+ assert a["lyrics"] == "[Verse]\nthe boxes by the door\n\n[Chorus]\nyou are going"+ assert a["concept"] == "a slow piano ballad for a friend moving away"+ # …and hands over to Custom, with the reason said once and the button ready.+ assert a["active"] is False and a["custom"] is False and a["saved"] == "custom"+ assert a["notice"] is False and "edit anything, then Compose" in a["noticeText"]+ assert a["btn"] == "Compose" and a["focusedGen"] is True++def test_compose_visibility_tracks_install_state():"""v4.14.1: Compose is always offered. Not installed, the form is greyed,the install panel carries one primary button, and Compose opens the card."""src = (ROOT / "webapp/js/characters.js").read_text()ids = ['audioModeGroup', 'musicComposePane', 'audioDrivePane', 'musicInstrumental', 'musicLyrics','musicInstrumentalPill', 'musicMaxSeconds', 'musicMaxSecondsVal', 'musicQuality', 'musicEstimate',- 'musicGenBtn', 'musicInstallPanel', 'musicInstallModal', 'musicInstallBody', 'musicStyle', 'musicStatus']+ 'musicGenBtn', 'musicInstallPanel', 'musicInstallModal', 'musicInstallBody', 'musicStyle', 'musicStatus',+ 'musicLoraList', 'musicLoraSummary', 'musicLoraInstall']funcs = "\n".join(extract_function(n, src) for n in (- "updateMusicAvailability", "musicFormChanged", "musicInstallRender", "openMusicInstallCard", "musicGenerate"))+ "updateMusicAvailability", "musicFormChanged", "musicInstallRender",+ "openMusicInstallCard", "musicGenerate",+ # Compose's cover and LoRA sections keep their own summaries and+ # install cards in step from inside musicFormChanged, so all of them+ # have to be in scope here.+ "musicCoverSummary", "musicCoverInstallCard",+ "musicLoraPicks", "musicLoraRender", "musicLoraSummaryText", "musicLoraInstallCard"))result = node_eval("""let audioModeChoice=null,musicBusy=false,musicInstall={state:'idle',active:false},musicInstallSeenActive=false;const window={_ENGINE_PROBES:{music:{available:false,capable:true,min_ram_gb:24}}};-const mk=()=>{const cl=new Set();return {hidden:false,innerHTML:'',value:'',classList:{toggle:(c,on)=>on?cl.add(c):cl.delete(c),has:c=>cl.has(c)}}};+const mk=()=>{const cl=new Set();return {hidden:false,innerHTML:'',value:'',textContent:'',dataset:{},+ classList:{toggle:(c,on)=>on?cl.add(c):cl.delete(c),has:c=>cl.has(c)},querySelectorAll:()=>[]}};const els=Object.fromEntries(""" + json.dumps(ids) + """.map(id=>[id,mk()]));els.musicInstallModal.hidden=true;els.musicInstrumental.checked=false;els.musicMaxSeconds.value='240';els.musicQuality.value='final';const document={body:{dataset:{workflow:'audio'}},getElementById:id=>els[id],querySelectorAll:()=>[]};+const charactersEscapeHtml=s=>String(s==null?'':s);const charactersEscapeAttr=charactersEscapeHtml;const renderEngineSwitch=()=>{};const escapeHtml=s=>String(s);let fetched=0;const fetch=()=>{fetched++;};let toasts=0;const phosToast=()=>{toasts++;};""" + funcs + """@@ -472,8 +625,12 @@ console.log(JSON.stringify({states,card,toasts}));def test_progress_eta_is_total_and_remaining_is_separate():src = Path(P.__file__).read_text()body = src[src.index("def run_music_job_inner"):src.index("ENGINE_DEFAULT = ")]- assert 'eta_sec=music_estimate(p["music_quality"], p["music_max_seconds"])["eta_sec"],' in body- assert "remaining_sec=max(0," in body+ # The total is the song estimate (scaled for a variation: a re-recording+ # is the NAR + decoder only) and the remaining is that total minus the+ # clock — two fields, never one derived from the other on the client.+ assert '_eta = music_estimate(p["music_quality"], p["music_max_seconds"])["eta_sec"] * _eta_scale' in body+ assert "eta_sec=_eta," in body+ assert "remaining_sec=max(0, _eta - elapsed)" in bodydef test_runner_reports_decode_and_never_publishes_after_stop():@@ -529,25 +686,99 @@ def test_music_estimate_is_calibrated_and_scaled(monkeypatch):def test_external_gpu_lock_is_read_never_written(pack, monkeypatch, tmp_path):+ """By default the panel only READS the shared locks: it waits (capped) and+ refuses past the cap, and never creates or removes a lock."""stub = tmp_path / "never_runs.py"stub.write_text("raise SystemExit('the runner must not start while a lock exists')\n")monkeypatch.setattr(P, "MUSIC_RUNNER", stub)monkeypatch.setattr(P.HELPER, "kill", lambda: None)+ monkeypatch.setattr(P, "MUSIC_GPU_WAIT_MAX_S", 0.3)+ monkeypatch.setattr(P, "MUSIC_GPU_POLL_S", 0.05)+ monkeypatch.setattr(P, "MUSIC_TAKES_GPU_LOCK", False)for lock, make in ((P.MUSIC_GPU_FILE_LOCK, lambda p: p.write_text("lab job")),(P.MUSIC_GPU_DIR_LOCK, lambda p: p.mkdir())):make(lock)job = P.make_job({"mode": "music", "music_style": "test"})with pytest.raises(P.RenderRefused, match=lock.name):P.run_job_inner(job)+ assert job["progress"]["phase"] == "waiting" # it showed the wait before refusingassert lock.exists() # left exactly as foundif lock.is_dir():lock.rmdir()else:lock.unlink()- src = Path(P.__file__).read_text()- body = src[src.index("def run_music_job_inner"):src.index("ENGINE_DEFAULT = ")]- assert "MUSIC_GPU_DIR_LOCK.mkdir" not in src and "MUSIC_GPU_FILE_LOCK.open" not in src- assert "_music_take_gpu_locks" not in src and "_music_release_gpu_locks" not in src+++def test_music_waits_for_the_gpu_then_runs(pack, monkeypatch, tmp_path):+ """A lock held by a command-line job delays the song; it does not fail it."""+ import threading+ stub = tmp_path / "stub_runner.py"+ stub.write_text("""import sys,pathlib+args=sys.argv[1:]; out=pathlib.Path(args[args.index('--output')+1])+out.write_bytes(b'RIFF'); pathlib.Path(str(out)+'.json').write_text(args[args.index('--extra-json')+1])+print('[music] done 5 '+str(out),flush=True)+""")+ monkeypatch.setattr(P, "MUSIC_RUNNER", stub)+ monkeypatch.setattr(P.HELPER, "kill", lambda: None)+ monkeypatch.setattr(P, "MUSIC_GPU_POLL_S", 0.05)+ monkeypatch.setattr(P, "MUSIC_TAKES_GPU_LOCK", False)+ P.MUSIC_GPU_FILE_LOCK.write_text("12345 lab job")+ seen = []+ def release():+ time.sleep(0.3)+ seen.append(dict(job.get("progress") or {}))+ P.MUSIC_GPU_FILE_LOCK.unlink()+ job = P.make_job({"mode": "music", "music_style": "test"})+ P.STATE["current"] = job+ t = threading.Thread(target=release); t.start()+ P.run_job_inner(job)+ t.join()+ assert seen and seen[0]["phase"] == "waiting" and "gpu" in seen[0]["phase_label"].lower()+ assert Path(job["output_path"]).is_file()+ assert not P.MUSIC_GPU_FILE_LOCK.exists()+++def test_stop_ends_the_gpu_wait(pack, monkeypatch, tmp_path):+ import threading+ stub = tmp_path / "never_runs.py"+ stub.write_text("raise SystemExit('must not start')\n")+ monkeypatch.setattr(P, "MUSIC_RUNNER", stub)+ monkeypatch.setattr(P.HELPER, "kill", lambda: None)+ monkeypatch.setattr(P, "MUSIC_GPU_POLL_S", 0.05)+ P.MUSIC_GPU_FILE_LOCK.write_text("12345 lab job")+ job = P.make_job({"mode": "music", "music_style": "test"})+ threading.Timer(0.2, lambda: job.__setitem__("cancel_requested", True)).start()+ with pytest.raises(P.JobStopped):+ P.run_job_inner(job)+ assert P.MUSIC_GPU_FILE_LOCK.read_text() == "12345 lab job" # a foreign lock is never touched+++def test_opt_in_panel_holds_the_lock_while_it_renders(pack, monkeypatch, tmp_path):+ """PHOSPHENE_MUSIC_TAKES_GPU_LOCK=1: the panel creates the file lock atomically+ while the runner works, so command-line jobs queue behind it, and removes only+ the lock it wrote."""+ probe = tmp_path / "lock_seen_by_runner"+ stub = tmp_path / "stub_runner.py"+ stub.write_text(f"""import sys,pathlib+lock=pathlib.Path({str(P.MUSIC_GPU_FILE_LOCK)!r})+pathlib.Path({str(probe)!r}).write_text(lock.read_text() if lock.exists() else 'NO LOCK')+args=sys.argv[1:]; out=pathlib.Path(args[args.index('--output')+1])+out.write_bytes(b'RIFF'); pathlib.Path(str(out)+'.json').write_text(args[args.index('--extra-json')+1])+print('[music] done 5 '+str(out),flush=True)+""")+ monkeypatch.setattr(P, "MUSIC_RUNNER", stub)+ monkeypatch.setattr(P.HELPER, "kill", lambda: None)+ monkeypatch.setattr(P, "MUSIC_TAKES_GPU_LOCK", True)+ job = P.make_job({"mode": "music", "music_style": "test"})+ P.STATE["current"] = job+ P.run_job_inner(job)+ assert "phosphene-panel-music" in probe.read_text() # held while the runner ran+ assert not P.MUSIC_GPU_FILE_LOCK.exists() # and released after+ # A lock that is not ours is never removed, even if it appeared mid-run.+ assert P._music_release_gpu("999 phosphene-panel-music other\n") is None+ P.MUSIC_GPU_FILE_LOCK.write_text("someone else")+ P._music_release_gpu("999 phosphene-panel-music other\n")+ assert P.MUSIC_GPU_FILE_LOCK.read_text() == "someone else"def test_late_stop_leaves_nothing_behind(pack, monkeypatch, tmp_path):@@ -898,7 +1129,13 @@ def test_music_child_env_drops_the_pinokio_torch_vars():"PYTORCH_MPS_FAST_MATH": "1"})assert "PYTORCH_ENABLE_MPS_FALLBACK" not in envassert "PYTORCH_MPS_FAST_MATH" not in env- assert env["HF_HOME"] == "/hf" and env["PATH"] == "/bin"+ assert env["HF_HOME"] == "/hf"+ # PATH is no longer passed through untouched: a COVER decodes its source+ # recording by shelling out to ffmpeg, and Pinokio's bundled binary is not+ # on the default PATH (the 4.15.1 export bug, one engine over). The+ # resolved one goes in front; everything the caller had is kept behind it.+ assert env["PATH"].startswith(str(P.FFMPEG_BIN))+ assert env["PATH"].endswith("/bin")assert env["MLX_ENABLE_TF32"] == "0" and env["PYTHONUNBUFFERED"] == "1"diff --git a/test_music_song_actions.py b/test_music_song_actions.pynew file mode 100644index 0000000..d848a67--- /dev/null+++ b/test_music_song_actions.py@@ -0,0 +1,326 @@+#!/usr/bin/env python3+"""The Music Studio's verbs on an existing song: what they send, and what the+queued job keeps of the song it came from.++ * M6-01 Restyle and an edited score queued the PARENT's Max length, not+ the slider on screen.+ * M6-03 An edited score dropped the song's adapters, Instrumental, LoRA+ mode, guidance and precision.+ * M6-06 Two edits of one song in the same second shared one .abc file,+ so the first job rendered the second one's notes.+ * M6-02 A ⋯-menu action fired 400 ms after opening the card and used+ whatever song the card held by then — the previous one.+ * M6-10 Every parent-song link was an inline handler with a syntax error.++Routes run for real against a scratch outputs/state tree and an in-memory+queue; the browser half runs in node. No model, no GPU, no audio.+"""+from __future__ import annotations++import json+import shutil+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 P # noqa: E402+from panel import routes_music as R # noqa: E402+from scripts.extract_panel_js import extract_function # noqa: E402++R.P = P+NODE = shutil.which("node")+++class _Handler:+ def __init__(self, form):+ self.form = {k: [v] for k, v in form.items()}+ self.payload, self.status = None, None++ def _read_form_body(self):+ return b"", self.form++ def _json(self, payload, status=200):+ self.payload, self.status = payload, status+++class Studio(unittest.TestCase):+ """A scratch outputs tree, LoRA folder and queue."""++ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ root = Path(self.tmp.name)+ self.out, self.loras, self.art = root / "out", root / "loras", root / "art"+ for d in (self.out, self.loras / "user", self.art):+ d.mkdir(parents=True)+ (self.loras / "user" / "voice.safetensors").write_bytes(b"x" * 64)+ self.queue = {"queue": [], "current": None, "history": []}+ for p in (mock.patch.object(P, "OUTPUT", self.out),+ mock.patch.object(P, "MUSIC_LORAS", self.loras),+ mock.patch.object(P, "MUSIC_ARTIFACTS", self.art),+ mock.patch.object(P, "STATE", self.queue),+ mock.patch.object(P, "persist_queue", lambda: None),+ mock.patch.object(P, "push", lambda *a, **k: None)):+ p.start()+ self.addCleanup(p.stop)++ def song(self, name="music_song.wav", *, instrumental=False, **params):+ wav = self.out / name+ wav.write_bytes(b"RIFF")+ base = {"music_max_seconds": 180, "music_quality": "final",+ "music_lora_mode": "separate", "music_cfg_scale": 1.3,+ "music_precision": "bf16",+ "music_loras": [] if instrumental else+ [{"id": "user/voice.safetensors", "strength": 0.8,+ "path": str(self.loras / "user" / "voice.safetensors")}]}+ base.update(params)+ side = {"engine": "music", "style": "dream pop", "lyrics": "[verse]\nla",+ "mode": "full", "instrumental": instrumental,+ "score_abc": "X:1\nK:C\nCDEF|\n", "params": base}+ Path(str(wav) + ".json").write_text(json.dumps(side))+ return wav++ def queued(self):+ return P.music_params(self.queue["queue"][-1]["params"])+++class TheSliderOnScreenWins(Studio):+ """M6-01, server half."""++ def test_an_edited_score_takes_the_form_limit(self):+ wav = self.song()+ h = _Handler({"path": str(wav), "abc": "X:1\nK:C\nG|\n", "max_seconds": "60"})+ R.post_music_score_render(h, "/music/score/render", {}, "")+ self.assertTrue(h.payload.get("ok"), h.payload)+ self.assertEqual(self.queued()["music_max_seconds"], 60)++ def test_a_restyle_takes_the_form_limit(self):+ wav = self.song()+ h = _Handler({"path": str(wav), "kind": "restyle", "style": "punk",+ "max_seconds": "60"})+ R.post_music_variation(h, "/music/variation", {}, "")+ self.assertTrue(h.payload.get("ok"), h.payload)+ self.assertEqual(self.queued()["music_max_seconds"], 60)++ def test_no_slider_value_still_inherits_the_parents(self):+ wav = self.song()+ R.post_music_score_render(_Handler({"path": str(wav), "abc": "X:1\nK:C\nG|\n"}),+ "/music/score/render", {}, "")+ self.assertEqual(self.queued()["music_max_seconds"], 180)+++class AnEditedScoreKeepsTheSongsRecipe(Studio):+ """M6-03."""++ def _render(self, wav):+ h = _Handler({"path": str(wav), "abc": "X:1\nK:C\nG|\n"})+ R.post_music_score_render(h, "/music/score/render", {}, "")+ self.assertTrue(h.payload.get("ok"), h.payload)+ return self.queued()++ def test_the_singer_and_the_sound_survive_a_note_change(self):+ p = self._render(self.song())+ self.assertEqual([(x["id"], x["strength"]) for x in p["music_loras"]],+ [("user/voice.safetensors", 0.8)])+ self.assertEqual(p["music_lora_mode"], "separate")+ self.assertEqual(p["music_cfg_scale"], 1.3)+ self.assertEqual(p["music_precision"], "bf16")+ self.assertFalse(p["music_instrumental"])++ def test_an_instrumental_stays_instrumental(self):+ p = self._render(self.song("music_inst.wav", instrumental=True))+ self.assertTrue(p["music_instrumental"])++ def test_the_recipe_reaches_the_runner(self):+ p = self._render(self.song())+ paths = {"python": Path("/x/py"), "runner": Path("/x/run.py"),+ "generator": Path("/x/gen"), "vae": Path("/x/vae")}+ argv = P.music_argv({"id": "j", "params": p}, paths, self.out / "o.wav")+ self.assertIn("--lora", argv)+ self.assertEqual(argv[argv.index("--lora-mode") + 1], "separate")+ self.assertIn(":0.8", argv[argv.index("--lora") + 1])+++class EveryEditGetsItsOwnScore(Studio):+ """M6-06."""++ def test_two_edits_in_one_second_do_not_share_a_file(self):+ wav = self.song()+ paths = []+ with mock.patch.object(R.time, "strftime", return_value="_20260924_120000"):+ for abc in ("X:1\nK:C\nA|\n", "X:1\nK:C\nB|\n"):+ h = _Handler({"path": str(wav), "abc": abc})+ R.post_music_score_render(h, "/music/score/render", {}, "")+ paths.append(h.payload["abc_path"])+ self.assertNotEqual(paths[0], paths[1])+ jobs = [j["params"]["music_abc_path"] for j in self.queue["queue"]]+ self.assertEqual(jobs, paths)+ self.assertEqual(Path(paths[0]).read_text(), "X:1\nK:C\nA|\n")+ self.assertEqual(Path(paths[1]).read_text(), "X:1\nK:C\nB|\n")++[email protected](NODE is None, "node not on PATH")+class TheBrowserSendsTheSlider(unittest.TestCase):+ """M6-01, browser half: both requests carry Max length."""++ def test_restyle_and_score_edit_post_the_slider(self):+ src = (ROOT / "webapp/js/music.js").read_text()+ funcs = "\n".join(extract_function(n, src) for n in (+ "musicRestyleFromSong", "musicRenderEditedScore"))+ script = r"""+const EL = { musicStyle: {value: 'punk'}, musicLyrics: {value: ''},+ musicSeed: {value: '-1'}, musicQuality: {value: 'final'},+ musicTitle: {value: ''}, musicMaxSeconds: {value: '60'},+ songScoreText: {value: 'X:1\nK:C\nG|\n'} };+function _el(id) { return EL[id]; }+function _say() {}+function musicScoreEditToggle() {}+let SONG = { path: '/out/music_song.wav' };+const bodies = [];+global.fetch = async (url, o) => { bodies.push([url, String(o.body)]);+ return { ok: true, json: async () => ({ ok: true }) }; };+""" + funcs + r"""+(async () => {+ await musicRestyleFromSong();+ await musicRenderEditedScore();+ process.stdout.write(JSON.stringify(bodies.map(([u, b]) =>+ [u, new URLSearchParams(b).get('max_seconds')])));+})();+"""+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ try:+ out = subprocess.run([NODE, fh.name], capture_output=True, text=True,+ timeout=30)+ finally:+ Path(fh.name).unlink(missing_ok=True)+ self.assertEqual(out.returncode, 0, out.stderr)+ self.assertEqual(json.loads(out.stdout),+ [["/music/variation", "60"], ["/music/score/render", "60"]])++++def _node(script: str):+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ try:+ out = subprocess.run([NODE, fh.name], capture_output=True, text=True, timeout=30)+ finally:+ Path(fh.name).unlink(missing_ok=True)+ if out.returncode:+ raise AssertionError(out.stderr)+ return json.loads(out.stdout)++[email protected](NODE is None, "node not on PATH")+class AnActionUsesItsOwnSong(unittest.TestCase):+ """M6-02."""++ SHIM = r"""+const EL = {};+function _el(id) { return EL[id] || (EL[id] = { value: '', textContent: '', innerHTML: '',+ hidden: false, querySelectorAll: () => [] }); }+EL.musicStyle = { value: 'punk' }; EL.musicLyrics = { value: '' };+EL.musicMaxSeconds = { value: '60' };+const said = [];+function _say(m) { said.push(m); }+function _esc(s) { return String(s); }+let _barSong = 1;+function musicBarShow() {}+function _songNameFromFile(n) { return n; }+function _badges() { return ''; }+function musicScoreEditToggle() {}+function _renderLineage() {} function _renderScore() {} function _renderLyrics() {}+function selectOutput(path) { songCardRender({ kind: 'audio', engine: 'music', path, name: path, music: {} }); }+const posted = [];+const held = [];+let failScore = false;+global.fetch = (url, o) => {+ if (url.startsWith('/music/score?')) {+ const path = decodeURIComponent(url.split('path=')[1]);+ return new Promise(res => held.push(() => res(failScore+ ? { ok: false, json: async () => ({ error: 'gone' }) }+ : { ok: true, json: async () => ({ path, abc: 'X:1', has_artifacts: true }) })));+ }+ posted.push([url, new URLSearchParams(String(o.body)).get('path')]);+ return Promise.resolve({ ok: true, json: async () => ({ ok: true }) });+};+const tick = () => new Promise(r => setImmediate(r));+async function releaseAll() { while (held.length) { held.shift()(); for (let i = 0; i < 6; i++) await tick(); } }+"""++ def _run(self, body):+ src = (ROOT / "webapp/js/music.js").read_text()+ funcs = "\n".join(extract_function(n, src) for n in (+ "songCardRender", "_songFor", "musicSongAction",+ "musicRestyleFromSong", "musicCoverFromSong"))+ return _node(self.SHIM + "let SONG = null; let songReq = 0; let songShown = '';\n"+ + funcs + "\n(async () => { const out = {};\n" + body+ + "\nprocess.stdout.write(JSON.stringify(out)); })();")++ def test_the_action_waits_for_its_song_and_uses_it(self):+ r = self._run(r"""+SONG = { path: '/out/A.wav', abc: 'X:1' }; songShown = '/out/A.wav';+const act = musicSongAction('/out/B.wav', 'restyle');+await tick();+out.whileLoading = posted.slice();+out.songWhileLoading = SONG;+await releaseAll(); await act;+out.after = posted.slice();+""")+ self.assertEqual(r["whileLoading"], [])+ self.assertIsNone(r["songWhileLoading"])+ self.assertEqual(r["after"], [["/music/variation", "/out/B.wav"]])++ def test_a_song_that_cannot_be_read_queues_nothing(self):+ r = self._run(r"""+SONG = { path: '/out/A.wav', abc: 'X:1' }; songShown = '/out/A.wav';+failScore = true;+const act = musicSongAction('/out/B.wav', 'restyle');+await releaseAll(); await act;+out.posted = posted; out.src = (EL.musicSourceAudio || {}).value || '';+const cover = musicSongAction('/out/B.wav', 'cover');+await releaseAll(); await cover;+out.coverSrc = (EL.musicSourceAudio || {}).value || '';+out.cardButton = (musicRestyleFromSong(), posted.length);+""")+ self.assertEqual(r["posted"], [])+ self.assertEqual(r["coverSrc"], "")+ self.assertEqual(r["cardButton"], 0)++[email protected](NODE is None, "node not on PATH")+class TheParentLinkWorks(unittest.TestCase):+ """M6-10."""++ def test_the_link_hands_back_the_exact_path(self):+ src = (ROOT / "webapp/js/music.js").read_text()+ paths = ["/out/music_a.wav", "/out/日本語 song.wav",+ "/out/a \"quoted\" & <odd> 'name'.wav"]+ r = _node(r"""+const EL = { songLineage: { innerHTML: '' } };+function _el(id) { return EL[id]; }+""" + next(ln for ln in src.splitlines() if ln.startswith("function _esc("))+ + "\n" + extract_function("_renderLineage", src) + r"""+const got = [];+function musicOpenSong(p) { got.push(p); }+const unesc = s => s.replace(/"/g, '"').replace(/'/g, "'").replace(/</g, '<')+ .replace(/>/g, '>').replace(/&/g, '&');+for (const p of """ + json.dumps(paths) + r""") {+ _renderLineage({ parent: p, variation: 'take' });+ const m = EL.songLineage.innerHTML.match(/onclick="([^"]*)"/);+ new Function('musicOpenSong', unesc(m[1]))(musicOpenSong);+}+process.stdout.write(JSON.stringify(got));+""")+ self.assertEqual(r, paths)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_music_studio.py b/test_music_studio.pynew file mode 100644index 0000000..aaec534--- /dev/null+++ b/test_music_studio.py@@ -0,0 +1,415 @@+"""Music Studio: the song as a thing you come back to.++A song keeps its artifacts (plan, tokens, latents, noise), and that is what+every variation restarts from. These are the rules the studio's verbs obey:++ * a variation names its parent by OUTPUT PATH; the worker turns that into an+ artifact folder from the parent's own sidecar — a form never names a+ state directory, and a song that kept nothing is refused with the reason;+ * an edited score is rendered only from inside the studio's own tree;+ * the lineage lands in the sidecar and the gallery reads it back;+ * the runner refuses the impossible combinations before loading a model.+"""+import json+import subprocess+import sys+import unittest+from pathlib import Path+from tempfile import TemporaryDirectory++import mlx_ltx_panel as P++RUNNER = Path(__file__).with_name("scripts") / "music" / "yue2_run.py"+++class TheParams(unittest.TestCase):++ def test_variation_is_a_closed_vocabulary(self):+ for bad in ("", "remix", "../x"):+ self.assertEqual(P.music_params({"music_variation": bad})["music_variation"], "")+ for good in ("take", "sound", "restyle", "score"):+ self.assertEqual(P.music_params({"music_variation": good})["music_variation"], good)++ def test_precision_defaults_to_what_every_song_was_made_with(self):+ self.assertEqual(P.music_params({})["music_precision"], "8bit")+ self.assertEqual(P.music_params({"music_precision": "bf16"})["music_precision"], "bf16")+ self.assertEqual(P.music_params({"music_precision": "fp8"})["music_precision"], "8bit")++ def test_guidance_is_none_unless_chosen_and_sane(self):+ self.assertIsNone(P.music_params({})["music_cfg_scale"])+ self.assertEqual(P.music_params({"music_cfg_scale": "1.4"})["music_cfg_scale"], 1.4)+ self.assertIsNone(P.music_params({"music_cfg_scale": "40"})["music_cfg_scale"])+ self.assertIsNone(P.music_params({"music_cfg_scale": "loud"})["music_cfg_scale"])++ def test_title_and_parent_travel(self):+ p = P.music_params({"music_title": "Lights On", "music_parent": "/tmp/a song.wav"})+ self.assertEqual(p["music_title"], "Lights On")+ self.assertEqual(p["music_parent"], "/tmp/a song.wav")+++class _Song:+ """A finished song with a complete artifact folder, or without one."""++ def __init__(self, artifacts=True, score=True):+ self.artifacts, self.score = artifacts, score++ def __enter__(self):+ self.tmp = TemporaryDirectory()+ root = Path(self.tmp.name)+ self.wav = root / "music_x.wav"+ self.wav.write_bytes(b"RIFF")+ side = {"engine": "music", "style": "dream pop", "lyrics": "[Verse]\nla", "mode": "full"}+ if self.artifacts:+ art = root / "art"+ art.mkdir()+ (art / "result.json").write_text("{}")+ if self.score:+ (art / "score.abc").write_text("X:1\nK:C\n")+ side["artifacts"] = str(art)+ self.art = art+ Path(str(self.wav) + ".json").write_text(json.dumps(side))+ return self++ def __exit__(self, *a):+ self.tmp.cleanup()+++class TheArgv(unittest.TestCase):++ def argv(self, form, job_id="j-test"):+ paths = {"python": Path("/x/py"), "runner": RUNNER,+ "generator": Path("/x/gen"), "vae": Path("/x/vae")}+ return P.music_argv({"id": job_id, "params": form}, paths, Path("/tmp/out.wav"))++ def test_every_song_keeps_its_artifacts(self):+ argv = self.argv({"music_style": "dream pop"})+ d = Path(argv[argv.index("--artifacts") + 1])+ self.assertTrue(d.is_relative_to(P.MUSIC_ARTIFACTS))++ def test_a_take_restarts_from_the_parents_artifacts(self):+ with _Song() as song:+ argv = self.argv({"music_parent": str(song.wav), "music_variation": "take"})+ self.assertEqual(Path(argv[argv.index("--from-artifacts") + 1]), song.art)+ self.assertEqual(argv[argv.index("--variation") + 1], "take")++ def test_a_song_that_kept_nothing_is_refused_with_the_reason(self):+ with _Song(artifacts=False) as song:+ with self.assertRaises(RuntimeError) as cm:+ self.argv({"music_parent": str(song.wav), "music_variation": "sound"})+ self.assertIn("no saved artifacts", str(cm.exception))++ def test_a_restyle_points_at_the_saved_score(self):+ with _Song() as song:+ argv = self.argv({"music_parent": str(song.wav), "music_variation": "restyle",+ "music_style": "bossa nova"})+ self.assertEqual(Path(argv[argv.index("--abc-file") + 1]), song.art / "score.abc")+ self.assertNotIn("--from-artifacts", argv)++ def test_a_restyle_of_a_scoreless_song_is_refused(self):+ with _Song(score=False) as song:+ with self.assertRaises(RuntimeError):+ self.argv({"music_parent": str(song.wav), "music_variation": "restyle"})++ def test_a_score_job_transcribes_only(self):+ argv = self.argv({"music_variation": "score", "music_source_audio": "/tmp/x.mp3"})+ self.assertIn("--transcribe-only", argv)+ self.assertIn("--source-audio", argv)++ def test_an_edited_score_must_come_from_the_studio_tree(self):+ with TemporaryDirectory() as tmp:+ stray = Path(tmp) / "evil.abc"+ stray.write_text("X:1\nK:C\n")+ with self.assertRaises(RuntimeError):+ self.argv({"music_style": "x", "music_abc_path": str(stray)})+ edits = P.MUSIC_ARTIFACTS / "edits"+ edits.mkdir(parents=True, exist_ok=True)+ ok = edits / "test_edit.abc"+ ok.write_text("X:1\nK:C\n")+ try:+ argv = self.argv({"music_style": "x", "music_abc_path": str(ok)})+ self.assertEqual(Path(argv[argv.index("--abc-file") + 1]), ok.resolve())+ finally:+ ok.unlink()++ def test_guidance_precision_and_title_reach_the_runner(self):+ argv = self.argv({"music_style": "x", "music_cfg_scale": "1.3",+ "music_precision": "bf16", "music_title": "Lights On"})+ self.assertEqual(argv[argv.index("--cfg-scale") + 1], "1.3")+ self.assertEqual(argv[argv.index("--precision") + 1], "bf16")+ self.assertEqual(argv[argv.index("--title") + 1], "Lights On")+++class TheRunnerRefusesTheImpossible(unittest.TestCase):++ def run_runner(self, *extra):+ out = subprocess.run(+ [sys.executable, str(RUNNER), "--model-dir", "/x", "--vae-dir", "/x",+ "--output", "/tmp/never.wav", *extra],+ capture_output=True, text=True, timeout=120)+ return out.returncode, out.stdout + out.stderr++ def test_a_variation_needs_its_artifacts(self):+ rc, out = self.run_runner("--variation", "take")+ self.assertEqual(rc, 2); self.assertIn("go together", out)++ def test_a_missing_artifact_folder_is_named(self):+ rc, out = self.run_runner("--variation", "sound", "--from-artifacts", "/tmp/not-a-song")+ self.assertEqual(rc, 2); self.assertIn("no saved song", out)++ def test_transcribe_only_writes_a_score_not_a_wav(self):+ rc, out = self.run_runner("--transcribe-only", "--source-audio", "/tmp/x.mp3")+ self.assertEqual(rc, 2); self.assertIn(".abc", out)++ def test_a_variation_needs_no_prompt(self):+ """The words and the style come off the saved plan."""+ with TemporaryDirectory() as tmp:+ (Path(tmp) / "result.json").write_text("{}")+ rc, out = self.run_runner("--variation", "take", "--from-artifacts", tmp)+ self.assertNotIn("Give it something to work with", out)+++class TheGalleryReadsItBack(unittest.TestCase):++ def test_music_artifacts_for_reads_the_sidecar_not_the_filename(self):+ with _Song() as song:+ self.assertEqual(P.music_artifacts_for(song.wav), song.art)+ with _Song(artifacts=False) as song:+ self.assertIsNone(P.music_artifacts_for(song.wav))+ self.assertIsNone(P.music_artifacts_for(""))+ self.assertIsNone(P.music_artifacts_for("/tmp/nope.wav"))++ def test_the_song_card_facts_ride_on_the_output_row(self):+ """One poll payload, no second request for what the card shows first."""+ src = Path(__file__).with_name("mlx_ltx_panel.py").read_text()+ i = src.index("def list_outputs")+ block = src[i:i + 40000]+ for key in ('"has_score"', '"has_artifacts"', '"parent"', '"variation"', '"title"'):+ self.assertIn(key, block)+++if __name__ == "__main__":+ unittest.main(verbosity=2)+++class TheRoutesTrustNothing(unittest.TestCase):+ """A form field naming a file is a form field naming a file."""++ def setUp(self):+ from panel import routes_music+ routes_music.P = P+ self.R = routes_music++ def test_only_a_song_inside_the_outputs_folder_is_a_song(self):+ self.assertIsNone(self.R._song_output("/etc/passwd"))+ self.assertIsNone(self.R._song_output(""))+ self.assertIsNone(self.R._song_output(str(P.OUTPUT / "nope.wav")))++ def test_a_clip_that_is_not_music_is_not_a_song(self):+ P.OUTPUT.mkdir(parents=True, exist_ok=True)+ clip = P.OUTPUT / "_studio_test_clip.wav"+ clip.write_bytes(b"RIFF")+ Path(str(clip) + ".json").write_text(json.dumps({"engine": "h3"}))+ try:+ self.assertIsNone(self.R._song_output(str(clip)))+ Path(str(clip) + ".json").write_text(json.dumps({"engine": "music"}))+ self.assertEqual(self.R._song_output(str(clip)), clip.resolve())+ finally:+ clip.unlink(missing_ok=True)+ Path(str(clip) + ".json").unlink(missing_ok=True)++ def test_the_variation_vocabulary_matches_the_params(self):+ for kind in self.R.VARIATIONS:+ self.assertEqual(P.music_params({"music_variation": kind})["music_variation"], kind)+++class _Handler:+ """Just enough of the panel's request handler to run a route body: the+ form it read, and where the JSON answer lands."""++ def __init__(self, form):+ self.form = {k: [v] for k, v in form.items()}+ self.payload, self.status = None, None++ def _read_form_body(self):+ return b"", self.form++ def _json(self, payload, status=200):+ self.payload, self.status = payload, status+++class _Helper:+ """The warm helper, stubbed: it records what it was asked and answers."""++ def __init__(self, reply):+ self.reply, self.asked = reply, []++ def run(self, msg, timeout=None):+ self.asked.append(msg)+ if isinstance(self.reply, Exception):+ raise self.reply+ return self.reply+++class TheSectionRewrite(unittest.TestCase):+ """Rewrite asks Gemma for ONE section, and the tag never travels: the+ editor owns it, and a tag in the answer lands doubled in the box."""++ def setUp(self):+ from panel import routes_music+ routes_music.P = P+ self.R = routes_music+ self._helper = getattr(P, "HELPER", None)++ def tearDown(self):+ if self._helper is not None:+ P.HELPER = self._helper++ def call(self, form, reply):+ P.HELPER = _Helper(reply)+ h = _Handler(form)+ self.R.post_music_lyrics_section(h, "/music/lyrics/section", "", "")+ return h, P.HELPER++ def test_with_neither_a_concept_nor_lines_the_model_is_never_loaded(self):+ h, helper = self.call({"section": "Chorus", "lines": " ", "concept": ""},+ {"lyrics": "never asked"})+ self.assertEqual(h.status, 400)+ self.assertEqual(helper.asked, [])++ def test_the_label_and_the_lines_reach_the_lyricist(self):+ h, helper = self.call({"section": "[Chorus]", "lines": "old hook",+ "concept": "leaving a town", "style": "dream pop"},+ {"lyrics": "a new hook", "elapsed_sec": 3.2})+ self.assertEqual(h.status, 200)+ params = helper.asked[0]["params"]+ self.assertEqual(helper.asked[0]["action"], "write_lyrics")+ # The brackets are the editor's, not the model's.+ self.assertEqual(params["section"], "Chorus")+ self.assertEqual(params["lines"], "old hook")+ self.assertEqual(params["concept"], "leaving a town")+ self.assertEqual(params["style"], "dream pop")+ self.assertEqual(h.payload["lines"], "a new hook")+ self.assertEqual(h.payload["section"], "Chorus")++ def test_a_rewrite_can_stand_on_the_lines_alone(self):+ h, helper = self.call({"section": "Verse", "lines": "a line that needs work"},+ {"lyrics": "a better line"})+ self.assertEqual(h.status, 200)+ self.assertEqual(helper.asked[0]["params"]["concept"], "")++ def test_nothing_back_is_an_error_not_an_emptied_section(self):+ h, _ = self.call({"section": "Verse", "lines": "words"}, {"lyrics": " "})+ self.assertEqual(h.status, 500)++ def test_a_helper_that_blows_up_says_so_instead_of_hanging(self):+ h, _ = self.call({"section": "Verse", "lines": "words"},+ RuntimeError("helper failed to start"))+ self.assertEqual(h.status, 500)+ self.assertIn("helper failed", h.payload["error"])+++class TheLyricistPrompt(unittest.TestCase):+ """The helper action the route leans on. The contract is narrow and the+ route cannot hold it up on its own: with `section` set, Gemma is asked+ for that section's lines and any tag it adds anyway is dropped."""++ def setUp(self):+ src = Path(__file__).with_name("mlx_warm_helper.py").read_text()+ i = src.index('if action == "write_lyrics":')+ self.block = src[i:src.index('if action == "enhance_prompt":', i)]++ def test_the_section_is_read_off_the_params_and_the_lines_with_it(self):+ self.assertIn('section = (p.get("section") or "").strip().strip("[]")', self.block)+ self.assertIn('lines_in = (p.get("lines") or "").strip()', self.block)++ def test_a_section_rewrite_does_not_need_a_concept(self):+ self.assertIn("if not concept and not (section and lines_in):", self.block)++ def test_the_answer_comes_back_without_its_tag(self):+ self.assertIn('ln.strip().startswith("[") and ln.strip().endswith("]")', self.block)+ # The whole-song branch keeps its own rule: everything before the+ # first tag is a title or an apology and gets dropped.+ self.assertIn('while lines and not lines[0].strip().startswith("["):', self.block)+++class TheSimpleBrief(unittest.TestCase):+ """Simple mode: one description in, a brief out, nothing rendered."""++ def setUp(self):+ from panel import routes_music+ routes_music.P = P+ self.R = routes_music+ self._helper = getattr(P, "HELPER", None)+ self._queue = len(P.STATE.get("queue") or [])++ def tearDown(self):+ if self._helper is not None:+ P.HELPER = self._helper++ def call(self, form, reply):+ P.HELPER = _Helper(reply)+ h = _Handler(form)+ self.R.post_music_simple(h, "/music/simple", "", "")+ return h, P.HELPER++ BRIEF = {"title": "Leaving Town", "style": "English, slow piano ballad, 72 BPM",+ "lyrics": "[Verse]\nthe boxes by the door", "elapsed_sec": 8.1}++ def test_an_empty_description_never_loads_the_model(self):+ h, helper = self.call({"description": " "}, self.BRIEF)+ self.assertEqual(h.status, 400)+ self.assertEqual(helper.asked, [])++ def test_the_brief_comes_back_whole_and_nothing_is_queued(self):+ h, helper = self.call({"description": "a ballad for a friend moving away",+ "seconds": "180"}, self.BRIEF)+ self.assertEqual(h.status, 200)+ self.assertEqual(helper.asked[0]["action"], "write_song")+ self.assertEqual(helper.asked[0]["params"]["seconds"], 180)+ self.assertEqual(helper.asked[0]["params"]["instrumental"], False)+ self.assertEqual(h.payload["title"], "Leaving Town")+ self.assertIn("72 BPM", h.payload["style"])+ self.assertIn("[Verse]", h.payload["lyrics"])+ # A brief is not a job: Compose is still the user's press.+ self.assertEqual(len(P.STATE.get("queue") or []), self._queue)++ def test_instrumental_is_the_forms_decision_not_the_models(self):+ h, helper = self.call({"description": "a rainy night loop", "instrumental": "on"},+ self.BRIEF)+ self.assertTrue(helper.asked[0]["params"]["instrumental"])+ self.assertEqual(h.payload["lyrics"], "")+ self.assertTrue(h.payload["instrumental"])++ def test_a_brief_with_no_style_is_nothing_to_show(self):+ h, _ = self.call({"description": "something nice"}, {"title": "x", "lyrics": "[Verse]\na"})+ self.assertEqual(h.status, 500)++ def test_a_nonsense_length_falls_back_instead_of_blowing_up(self):+ h, helper = self.call({"description": "x", "seconds": "forever"}, self.BRIEF)+ self.assertEqual(h.status, 200)+ self.assertEqual(helper.asked[0]["params"]["seconds"], 150)+++class TheSongBrief(unittest.TestCase):+ """The helper action behind Simple mode. One Gemma call has to answer with+ the two fields YuE2 reads, and the parse has to survive the wrapping."""++ def setUp(self):+ src = Path(__file__).with_name("mlx_warm_helper.py").read_text()+ i = src.index('if action == "write_song":')+ self.block = src[i:src.index('if action == "enhance_prompt":', i)]++ def test_it_asks_for_one_json_object_with_the_three_fields(self):+ self.assertIn('{"title": "...", "style": "...", "lyrics": "..."}', self.block)+ self.assertIn("Answer with ONE JSON object and nothing else", self.block)++ def test_the_object_is_read_out_of_whatever_wraps_it(self):+ self.assertIn('i, j = text.find("{"), text.rfind("}")', self.block)++ def test_an_instrumental_brief_asks_for_no_words_at_all(self):+ self.assertIn("This one has no singing at all", self.block)+ self.assertIn('lyrics = "" if instrumental else', self.block)++ def test_a_brief_with_no_style_is_a_failure_not_a_blank_field(self):+ self.assertIn("raise ValueError(\"the model returned no style\")", self.block)+diff --git a/test_music_tags.py b/test_music_tags.pynew file mode 100644index 0000000..88367f7--- /dev/null+++ b/test_music_tags.py@@ -0,0 +1,28 @@+"""Section tags come back bare, whatever Gemma wrote."""+import unittest++from music_tags import canonical_tag, normalize_section_tags+++class BareTags(unittest.TestCase):+ def test_numbers_are_dropped(self):+ self.assertEqual(normalize_section_tags("[Verse 1]\nla\n[Chorus 2]\nlo"), "[Verse]\nla\n[Chorus]\nlo")++ def test_aliases_fold_into_the_closed_list(self):+ self.assertEqual(normalize_section_tags("[Hook]\n[Solo]\n[Pre Chorus 3]\n[Refrain]"),+ "[Chorus]\n[Instrumental]\n[Pre-Chorus]\n[Chorus]")++ def test_lines_are_never_touched(self):+ text = "[Verse]\n[bracketed words] inside a line stay\nso does [this 1]"+ self.assertEqual(normalize_section_tags(text), text)++ def test_unknown_tags_are_left_for_a_human(self):+ self.assertEqual(normalize_section_tags("[Spoken Word 1]"), "[Spoken Word 1]")+ self.assertIsNone(canonical_tag("Spoken Word"))++ def test_whitespace_and_case(self):+ self.assertEqual(normalize_section_tags(" [ verse 12 ] "), "[Verse]")+++if __name__ == "__main__":+ unittest.main()diff --git a/test_music_trained_voice.py b/test_music_trained_voice.pynew file mode 100644index 0000000..e4c4639--- /dev/null+++ b/test_music_trained_voice.py@@ -0,0 +1,115 @@+#!/usr/bin/env python3+"""A voice trained by `yue2_train_voice.py --install` is used the way it was+trained (M6-04).++The trainer writes `<name>.json` beside the adapter: the training `trigger`+and the `dialect` (`direct` = generate with no score, `score` = with one).+The Studio derived its picker from the filename alone, so the trigger never+reached inference and the default Score setting ("Melody + chords") put a+direct-dialect voice under conditioning it had never seen.++Scratch LoRA folder; the runner's own argument parser reads the argv the+panel builds. No model is loaded.+"""+from __future__ import annotations++import importlib.util+import json+import sys+import tempfile+import unittest+from pathlib import Path+from unittest import mock+from urllib.parse import parse_qs, urlencode++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as P # noqa: E402+from scripts.pinokio import music_lora_fetch as F # noqa: E402+++def _runner():+ spec = importlib.util.spec_from_file_location(+ "yue2_run_under_test", ROOT / "scripts" / "music" / "yue2_run.py")+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ return mod+++class TrainedVoice(unittest.TestCase):++ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ self.root = Path(self.tmp.name) / "loras"+ user = self.root / "user"+ user.mkdir(parents=True)+ (user / "myvoice.safetensors").write_bytes(b"x" * 64)+ (user / "myvoice.json").write_text(json.dumps({+ "name": "myvoice", "kind": "yue2-ar-voice", "branch": "ar",+ "trigger": "myvoice", "dialect": "direct",+ "generate_with": "--mode off"}))+ (user / "scorevoice.safetensors").write_bytes(b"x" * 64)+ (user / "scorevoice.json").write_text(json.dumps({+ "trigger": "scv", "dialect": "score"}))+ (user / "plain.safetensors").write_bytes(b"x" * 64)+ p = mock.patch.object(P, "MUSIC_LORAS", self.root)+ p.start()+ self.addCleanup(p.stop)++ def _form(self, picks, mode):+ return parse_qs(urlencode({"mode": "music", "music_style": "soul",+ "music_mode": mode,+ "music_loras": json.dumps(picks)}))++ def test_the_picker_shows_what_the_training_said(self):+ rows = {a["id"]: a for a in F.pack_adapters(self.root)}+ mine = rows["user/myvoice.safetensors"]+ self.assertEqual((mine["trigger"], mine["dialect"]), ("myvoice", "direct"))+ self.assertIn("No score", mine["note"])+ self.assertIn("myvoice", mine["note"])+ self.assertNotIn("trigger", rows["user/plain.safetensors"])++ def test_a_direct_voice_under_a_score_is_refused_before_queueing(self):+ with self.assertRaises(P.MusicRequestError) as cm:+ P.make_job(self._form([{"id": "user/myvoice.safetensors"}], "full"))+ self.assertIn("No score", str(cm.exception))+ with self.assertRaises(P.MusicRequestError):+ P.make_job(self._form([{"id": "user/scorevoice.safetensors"}], "off"))++ def test_the_trigger_reaches_the_runner_paired_with_its_adapter(self):+ job = P.make_job(self._form([{"id": "user/plain.safetensors", "strength": 0.5},+ {"id": "user/myvoice.safetensors", "strength": 1}],+ "off"))+ paths = {"python": Path("/x/py"), "runner": Path("/x/run.py"),+ "generator": Path("/x/gen"), "vae": Path("/x/vae")}+ argv = P.music_argv(job, paths, Path(self.tmp.name) / "o.wav")+ runner_args = argv[argv.index("/x/run.py") + 1:] if "/x/run.py" in argv else argv[2:]+ args = _runner().parse_args(runner_args)+ self.assertEqual(args.mode, "off")+ self.assertEqual([Path(s.rsplit(":", 1)[0]).name for s in args.lora],+ ["plain.safetensors", "myvoice.safetensors"])+ self.assertEqual(args.lora_trigger, ["", "myvoice"])++ def test_the_runner_adds_it_to_the_style_once(self):+ sys.path.insert(0, str(ROOT / "scripts" / "music"))+ import yue2_lora # noqa: PLC0415++ class A:+ def __init__(self, t):+ self.trigger = t++ self.assertEqual(yue2_lora.style_with_triggers("soul", [A(""), A("myvoice")]),+ "myvoice, soul")++ def test_no_trained_voice_no_trigger_flags(self):+ job = P.make_job(self._form([{"id": "user/plain.safetensors"}], "full"))+ paths = {"python": Path("/x/py"), "runner": Path("/x/run.py"),+ "generator": Path("/x/gen"), "vae": Path("/x/vae")}+ self.assertNotIn("--lora-trigger",+ P.music_argv(job, paths, Path(self.tmp.name) / "o.wav"))+++if __name__ == "__main__":+ unittest.main()diff --git a/test_music_video.py b/test_music_video.pynew file mode 100644index 0000000..f2f2b74--- /dev/null+++ b/test_music_video.py@@ -0,0 +1,771 @@+"""The music-video planner: the song is the clock and the shots tile it.++Everything here runs with no weights and no GPU. The song is a click track+this file writes with numpy — a real file, decoded by the real ffmpeg, read by+the real `beat_map`, because the whole planner hangs off that grid and a+stubbed one would test the stub.++The rules being pinned:++ * a singing shot is a REAL LTX cell, never a length the sampler cannot+ render, and never longer than the singing window;+ * the shots tile the song — shot n+1 starts where shot n ended — and a+ singing shot's `audio_start_time` IS its place in that tiling, which is+ the one thing lip-sync depends on;+ * Singer pictures alternate, so two adjacent windows are not the same angle;+ * a song nobody sings in, and a cast with no face in it, both come back as+ B-roll with the reason written down rather than a silent half-plan.+"""+from __future__ import annotations++import json+import math+import unittest+import wave+from pathlib import Path+from tempfile import TemporaryDirectory++import numpy as np++import music_video as mv+import storyboard+import storyboard_edit as sedit++SR = 44100+BPM = 120.0+++def click_track(path: Path, *, bars: int = 24, bpm: float = BPM,+ vocal_bars=()) -> None:+ """A 4/4 click track at `bpm`, with a voice-band tone over `vocal_bars`.++ The accent is an 80 Hz decaying kick and the bed a 220 Hz sine, so a bar+ with no tone has almost nothing in the 1–4 kHz band the classifier reads;+ a "vocal" bar adds 2.2 kHz on top. That separation is the point — it lets+ the band heuristic be tested for what it decides, not for how well it+ copes with pink noise.+ """+ beat = 60.0 / bpm+ total = bars * 4 * beat+ n = int(total * SR)+ t = np.arange(n, dtype=np.float64) / SR+ x = 0.15 * np.sin(2 * math.pi * 220.0 * t)+ for b in range(bars * 4):+ i0 = int(b * beat * SR)+ i1 = min(n, i0 + int(0.06 * SR))+ env = np.exp(-np.linspace(0.0, 8.0, i1 - i0))+ amp = 0.9 if b % 4 == 0 else 0.6+ x[i0:i1] += amp * env * np.sin(+ 2 * math.pi * 80.0 * np.arange(i1 - i0) / SR)+ for bar in vocal_bars:+ i0 = int(bar * 4 * beat * SR)+ i1 = min(n, int((bar + 1) * 4 * beat * SR))+ x[i0:i1] += 0.45 * np.sin(2 * math.pi * 2200.0 * t[i0:i1])+ x = np.clip(x, -1.0, 1.0)+ with wave.open(str(path), "wb") as fh:+ fh.setnchannels(1)+ fh.setsampwidth(2)+ fh.setframerate(SR)+ fh.writeframes((x * 32000).astype("<i2").tobytes())+++IMAGES = [+ {"path": "/tmp/mv/singer_a.png", "role": "singer"},+ {"path": "/tmp/mv/singer_b.png", "role": "singer"},+ {"path": "/tmp/mv/piano.png", "role": "instrument"},+ {"path": "/tmp/mv/room.png", "role": "room"},+]+STYLE = "handheld 16mm documentary, warm tungsten light"++# A 4/4 score at 120 BPM: one bar is exactly 2 seconds, so the arithmetic in+# the assertions below is readable rather than derived.+SCORE = """X:1+T:+M:4/4+L:1/8+Q:1/4=120+V: Vocal clef=treble+V: Ins clef=treble+K:C+% intro+V: Vocal+z8|z8|z8|z8|+V: Ins+Z4|+% verse+V: Vocal+C8|D8|E8|F8|G8|A8|B8|c8|+V: Ins+Z8|+% outro+V: Vocal+z8|z8|z8|z8|+V: Ins+Z2|Z2|+"""+LYRICS = "[Verse]\nsomething about the rain\nand the lights\n"+++class TheScoreIsRead(unittest.TestCase):++ def test_bars_and_tempo_come_off_the_headers(self):+ rows, spb = mv.score_sections(SCORE)+ self.assertEqual([(r["name"], r["bars"]) for r in rows],+ [("intro", 4), ("verse", 8), ("outro", 4)])+ self.assertAlmostEqual(spb, 2.0, places=6)++ def test_a_multi_measure_rest_is_as_many_bars_as_it_says(self):+ self.assertEqual(mv._count_bars("Z4|"), 4)+ self.assertEqual(mv._count_bars("Z|"), 1)+ self.assertEqual(mv._count_bars("Z2|z16e6g2a6e2|g16z6G2A4c4|"), 4)++ def test_a_bare_tag_is_an_instrumental_section(self):+ rows = mv.lyric_sections("[Intro]\n[Verse]\nwords here\n[Verse 2]\nmore\n")+ self.assertEqual([(r["name"], r["vocal"]) for r in rows],+ [("intro", False), ("verse", True), ("verse", True)])++ def test_a_score_with_no_tempo_says_so_rather_than_guessing(self):+ rows, spb = mv.score_sections("X:1\nK:C\n% a\nV: V\nC8|D8|\n")+ self.assertEqual([r["bars"] for r in rows], [2])+ self.assertIsNone(spb)+++class TheSongIsSectioned(unittest.TestCase):+ """The two paths: the score's arithmetic, and the band heuristic."""++ @classmethod+ def setUpClass(cls):+ cls.tmp = TemporaryDirectory()+ root = Path(cls.tmp.name)+ # 24 bars = 48 s at 120 BPM. Bars 8..15 carry the voice band.+ cls.song = root / "click.wav"+ click_track(cls.song, bars=24, vocal_bars=range(8, 16))+ cls.instrumental = root / "instrumental.wav"+ click_track(cls.instrumental, bars=24, vocal_bars=())+ cls.beats = sedit.beat_map(cls.song)++ @classmethod+ def tearDownClass(cls):+ cls.tmp.cleanup()++ def test_the_click_track_reads_as_the_tempo_it_was_written_at(self):+ # An octave error is the classic tempo failure and it would move every+ # downbeat, so the assertion is on the bar, not on a loose ratio.+ self.assertAlmostEqual(self.beats["bpm"], BPM, delta=2.0)++ def test_the_score_places_the_sections_to_the_second(self):+ rows = mv.song_sections(self.song, lyrics=LYRICS, score_abc=SCORE,+ beats=self.beats)+ self.assertEqual([r["name"] for r in rows], ["intro", "verse", "outro"])+ self.assertEqual([r["kind"] for r in rows],+ ["instrumental", "vocal", "instrumental"])+ self.assertAlmostEqual(rows[0]["start"], 0.0, places=6)+ # intro 4 bars = 8 s, verse 8 bars = 16 s; snapping to the measured+ # downbeat grid can move a boundary by less than half a bar.+ self.assertAlmostEqual(rows[0]["end"], 8.0, delta=1.0)+ self.assertAlmostEqual(rows[1]["end"], 24.0, delta=1.0)++ def test_the_sections_cover_the_song_with_no_gaps(self):+ for kwargs in ({"lyrics": LYRICS, "score_abc": SCORE}, {}):+ rows = mv.song_sections(self.song, beats=self.beats, **kwargs)+ for a, b in zip(rows, rows[1:]):+ self.assertEqual(a["end"], b["start"])+ self.assertEqual(rows[0]["start"], 0.0)+ self.assertAlmostEqual(rows[-1]["end"],+ self.beats["duration"], delta=0.05)++ def test_without_a_score_the_band_heuristic_finds_the_sung_phrase(self):+ rows = mv.song_sections(self.song, beats=self.beats)+ self.assertTrue(all(r["source"] == "phrase" for r in rows))+ sung = [r for r in rows if r["kind"] == "vocal"]+ self.assertTrue(sung, "the 2.2 kHz phrase should read as vocal")+ # Bars 8..15 = 16 s .. 32 s. Every phrase called vocal has to overlap+ # it; a classifier that said "all vocal" would fail here.+ for r in sung:+ self.assertLess(r["start"], 32.0)+ self.assertGreater(r["end"], 16.0)++ def test_a_track_with_no_voice_band_comes_back_instrumental(self):+ beats = sedit.beat_map(self.instrumental)+ rows = mv.song_sections(self.instrumental, beats=beats)+ self.assertEqual({r["kind"] for r in rows}, {"instrumental"})++ def test_a_score_longer_than_the_recording_is_clamped_not_believed(self):+ # 40 bars at 2 s = 80 s of score against a 48 s file.+ long_score = SCORE.replace("% outro\nV: Vocal\nz8|z8|z8|z8|\nV: Ins\nZ2|Z2|\n",+ "% outro\nV: Vocal\n" + "z8|" * 28 + "\n")+ rows = mv.song_sections(self.song, lyrics=LYRICS,+ score_abc=long_score, beats=self.beats)+ self.assertLessEqual(rows[-1]["end"], self.beats["duration"] + 0.05)+ self.assertLessEqual(len(rows), 3)++ def test_the_tempo_disagreement_is_a_sentence_not_a_refusal(self):+ self.assertIsNone(mv.tempo_disagreement(self.beats, SCORE))+ # 120 written against 120 measured is silent; 60 written is not.+ half = SCORE.replace("Q:1/4=120", "Q:1/4=75")+ note = mv.tempo_disagreement(self.beats, half)+ self.assertIsNotNone(note)+ self.assertIn("75", note)+++class TheDurationAxis(unittest.TestCase):++ def test_the_module_default_is_the_panel_table(self):+ # The planner may not import the panel, so it carries the seconds and+ # derives the frames. This is the assertion that keeps the two honest.+ import mlx_ltx_panel as P+ self.assertEqual(mv.LTX_CELLS, mv.cells_from_lengths(P.LTX_LENGTHS))++ def test_every_cell_is_a_frame_count_the_sampler_accepts(self):+ for secs, frames in mv.LTX_CELLS:+ self.assertEqual((frames - 1) % 8, 0)+ self.assertEqual(frames, storyboard.ltx_frames_for(secs))++ def test_the_largest_cell_that_fits_is_the_one_chosen(self):+ self.assertEqual(mv._cell_for(20.0, mv.LTX_CELLS), (20, 481))+ self.assertEqual(mv._cell_for(19.9, mv.LTX_CELLS), (10, 241))+ self.assertEqual(mv._cell_for(2.9, mv.LTX_CELLS), None)++ def test_the_restriction_table_is_the_panel_s_own(self):+ # The module mirrors the `qualities` column the same way it mirrors+ # the seconds, and for the same reason (no panel import). This is the+ # assertion that keeps the mirror honest.+ import mlx_ltx_panel as P+ panel = {int(l["seconds"]): tuple(l["qualities"])+ for l in P.LTX_LENGTHS.values() if l.get("qualities")}+ self.assertEqual(panel, mv.LTX_CELL_QUALITIES)++ def test_a_cell_this_canvas_cannot_render_is_not_on_the_axis(self):+ # 481 frames holds at 640×480 and dies around frame 454 at 1024×576,+ # so the panel offers the 20 s cell at Quick only — and the planner+ # has to read that column, not just the seconds.+ import mlx_ltx_panel as P+ std = mv.cells_from_lengths(P.LTX_LENGTHS, quality="standard")+ quick = mv.cells_from_lengths(P.LTX_LENGTHS, quality="quick")+ self.assertNotIn((20, 481), std)+ self.assertIn((20, 481), quick)+ self.assertEqual(max(f for _, f in std), 241)+ # Every other cell survives both.+ self.assertEqual(set(std), set(quick) - {(20, 481)})++ def test_an_axis_handed_in_by_hand_is_cut_down_too(self):+ kept, dropped = mv._cells_for_quality(mv.LTX_CELLS, "standard")+ self.assertEqual(dropped, ((20, 481),))+ self.assertNotIn((20, 481), kept)+ self.assertEqual(mv._cells_for_quality(mv.LTX_CELLS, "quick"),+ (mv.LTX_CELLS, ()))+ # No quality stated is no opinion — the axis comes back untouched.+ self.assertEqual(mv._cells_for_quality(mv.LTX_CELLS, ""),+ (mv.LTX_CELLS, ()))+++class TheBrollSplit(unittest.TestCase):++ def test_the_cuts_land_on_the_downbeats(self):+ grid = [2.0 * i for i in range(12)]+ spans = mv._broll_spans(0.0, 20.0, window=(3.0, 7.0), grid=grid,+ bar=2.0)+ self.assertAlmostEqual(sum(spans), 20.0, places=6)+ for s in spans:+ self.assertGreaterEqual(s, 3.0 - 1e-6)+ self.assertLessEqual(s, 7.0 + 1e-6)+ edge = 0.0+ for s in spans[:-1]:+ edge += s+ self.assertTrue(any(abs(edge - g) < 1e-6 for g in grid),+ f"cut at {edge} is not on the bar grid")++ def test_a_scrap_shorter_than_the_window_is_one_short_shot_not_a_hole(self):+ self.assertEqual(mv._broll_spans(0.0, 1.4, window=(3.0, 7.0),+ grid=[], bar=0.0), [1.4])++ def test_nothing_left_makes_nothing(self):+ self.assertEqual(mv._broll_spans(5.0, 5.0, window=(3.0, 7.0),+ grid=[], bar=0.0), [])+++class _Planned:+ """One click track and one set of sections, shared by every plan test.++ A mixin rather than a base TestCase on purpose: subclassing a TestCase to+ reuse its fixture re-runs all of its tests in every child.+ """++ @classmethod+ def setUpClass(cls):+ cls.tmp = TemporaryDirectory()+ cls.song = Path(cls.tmp.name) / "click.wav"+ click_track(cls.song, bars=24, vocal_bars=range(8, 16))+ cls.beats = sedit.beat_map(cls.song)+ cls.sections = [+ {"start": 0.0, "end": 16.0, "kind": "instrumental",+ "name": "intro", "source": "score"},+ {"start": 16.0, "end": 72.0, "kind": "vocal",+ "name": "verse", "source": "score"},+ {"start": 72.0, "end": 88.0, "kind": "instrumental",+ "name": "outro", "source": "score"},+ ]++ @classmethod+ def tearDownClass(cls):+ cls.tmp.cleanup()++ def plan(self, sections=None, images=None, **kw):+ return mv.plan_music_video(+ sections if sections is not None else self.sections,+ IMAGES if images is None else images,+ style=STYLE, bpm_grid=self.beats, song=str(self.song),+ title="Test video", board_id="sb_test", **kw)+++class ThePlan(_Planned, unittest.TestCase):++ def test_the_shots_tile_the_song(self):+ out = self.plan()+ shots = out["shots"]+ self.assertTrue(shots)+ cursor = 0.0+ for s in shots:+ block = s["music_video"]+ self.assertAlmostEqual(block["film_start"], cursor, places=3)+ cursor = block["film_end"]+ self.assertAlmostEqual(+ block["film_end"] - block["film_start"],+ s["duration_s"], places=3)+ self.assertAlmostEqual(cursor, out["film_seconds"], places=3)++ def test_a_singing_shot_is_rendered_against_its_own_second_of_the_song(self):+ for s in self.plan()["shots"]:+ if s["music_video"]["kind"] != "singing":+ continue+ self.assertEqual(s["mode"], "a2v")+ self.assertEqual(s["audio"], str(self.song))+ self.assertAlmostEqual(s["audio_start_time"],+ s["music_video"]["film_start"], places=3)++ def test_a_singing_window_never_exceeds_a_cell(self):+ cells = dict((f, s) for s, f in mv.LTX_CELLS)+ lo, hi = mv.SINGING_WINDOW+ for s in self.plan()["shots"]:+ if s["music_video"]["kind"] != "singing":+ continue+ frames = s["music_video"]["frames"]+ self.assertIn(frames, cells, "a singing shot off the cell table")+ self.assertLessEqual(frames / mv.FPS, hi + 1.0)+ self.assertGreaterEqual(frames / mv.FPS, lo - 1e-6)++ def test_broll_stays_inside_its_window(self):+ lo, hi = mv.BROLL_WINDOW+ spans = [s["duration_s"] for s in self.plan()["shots"]+ if s["music_video"]["kind"] == "broll"]+ self.assertTrue(spans)+ # The floor is the one a scrap at the end of a section may break, and+ # it is allowed to: a hole in the tiling is worse than a 1 s shot.+ self.assertTrue(all(s <= hi + 1.0 for s in spans), spans)++ def test_the_singers_alternate(self):+ faces = [s["still"] for s in self.plan()["shots"]+ if s["music_video"]["kind"] == "singing"]+ self.assertGreaterEqual(len(faces), 2)+ for a, b in zip(faces, faces[1:]):+ self.assertNotEqual(a, b, "two singing shots in a row, same angle")++ def test_the_plan_is_the_same_plan_twice(self):+ self.assertEqual(json.dumps(self.plan()["board"], sort_keys=True),+ json.dumps(self.plan()["board"], sort_keys=True))++ def test_an_all_instrumental_song_is_all_broll(self):+ rows = [dict(r, kind="instrumental") for r in self.sections]+ out = self.plan(sections=rows)+ kinds = {s["music_video"]["kind"] for s in out["shots"]}+ self.assertEqual(kinds, {"broll"})+ self.assertIn("0 singing", out["summary"])++ def test_a_cast_with_no_face_is_all_broll_and_says_why(self):+ out = self.plan(images=[{"path": "/tmp/mv/piano.png",+ "role": "instrument"}])+ self.assertEqual({s["music_video"]["kind"] for s in out["shots"]},+ {"broll"})+ self.assertTrue(any("Singer" in n for n in out["notes"]), out["notes"])++ def test_only_faces_still_makes_a_film_and_says_what_it_did(self):+ out = self.plan(images=[{"path": "/tmp/mv/singer_a.png",+ "role": "singer"}])+ kinds = {s["music_video"]["kind"] for s in out["shots"]}+ self.assertEqual(kinds, {"singing", "broll"})+ self.assertTrue(any("B-roll" in n for n in out["notes"]), out["notes"])+ # And a Singer picture used as B-roll must not be told to sing.+ for s in out["shots"]:+ if s["music_video"]["kind"] == "broll":+ self.assertNotIn("singing", s["prompt"])++ def test_the_summary_reads_like_a_sentence(self):+ out = self.plan()+ n_sing = sum(1 for s in out["shots"]+ if s["music_video"]["kind"] == "singing")+ self.assertIn(f"{len(out['shots'])} shots", out["summary"])+ self.assertIn(f"{n_sing} singing", out["summary"])+ self.assertRegex(out["summary"], r"\d+:\d\d$")++ def test_every_prompt_carries_the_look_and_the_picture_s_own_line(self):+ for s in self.plan()["shots"]:+ self.assertIn(STYLE, s["prompt"])+ override = self.plan(images=[+ {"path": "/tmp/mv/singer_a.png", "role": "singer",+ "prompt": "he leans back and laughs"}])+ self.assertIn("he leans back and laughs",+ override["shots"][0]["prompt"])++ def test_a_picture_with_no_role_is_broll_never_a_singer(self):+ out = self.plan(images=[{"path": "/tmp/mv/x.png"},+ {"path": "/tmp/mv/singer_a.png",+ "role": "singer"}])+ cast = out["board"]["music_video"]["images"]+ self.assertEqual(cast[0]["role"], "room")++ def test_a_song_with_no_pictures_is_refused_with_a_sentence(self):+ with self.assertRaises(mv.MusicVideoError):+ self.plan(images=[])+++class TheQualityDecidesTheDurationAxis(_Planned, unittest.TestCase):+ """The bug the first real film found: a 481-frame a2v shot planned onto a+ 1024×576 board, where LTX dies around frame 454. The planner now knows+ which canvas it is planning for."""++ def test_at_standard_nothing_longer_than_the_canvas_allows_is_planned(self):+ # Default quality, stated nowhere — the conservative half of the+ # choice, because a missing cell costs a cut and a dead cell costs+ # the shot.+ for s in self.plan()["shots"]:+ self.assertLessEqual(s["music_video"]["frames"], 241,+ f"{s['title']} is a Quick-only cell")++ def test_at_quick_the_twenty_second_cell_is_available_again(self):+ frames = [s["music_video"]["frames"]+ for s in self.plan(quality="quick")["shots"]]+ self.assertIn(481, frames)++ def test_a_hand_written_axis_is_still_cut_to_the_canvas_and_said_so(self):+ out = self.plan(cells=mv.LTX_CELLS, quality="standard")+ self.assertTrue(all(s["music_video"]["frames"] <= 241+ for s in out["shots"]))+ self.assertTrue(any("20 s" in n for n in out["notes"]), out["notes"])++ def test_naming_no_quality_at_all_leaves_the_axis_alone(self):+ frames = [s["music_video"]["frames"]+ for s in self.plan(quality="")["shots"]]+ self.assertIn(481, frames)+++class TheCastingCanBePinned(_Planned, unittest.TestCase):+ """B-roll was a blind round-robin: whatever came next in the list took the+ next slot, so the picture the film opens and closes on was cast by+ accident. `use` and `weight` are the two opinions a person actually has."""++ STAGE = "/tmp/mv/stage.png"+ WIDE = "/tmp/mv/wide.png"+ PINNED = [+ {"path": "/tmp/mv/singer_a.png", "role": "singer"},+ {"path": STAGE, "role": "room", "use": "open",+ "prompt": "the empty stage, the lights easing up"},+ {"path": "/tmp/mv/piano.png", "role": "instrument"},+ {"path": WIDE, "role": "room", "use": "close",+ "prompt": "wide of the whole band"},+ ]++ def broll(self, out):+ return [s for s in out["shots"]+ if s["music_video"]["kind"] == "broll"]++ def test_open_and_close_land_in_the_first_and_last_broll_shots(self):+ out = self.plan(images=self.PINNED)+ shots = self.broll(out)+ self.assertGreater(len(shots), 2)+ self.assertEqual(shots[0]["still"], self.STAGE)+ self.assertEqual(shots[-1]["still"], self.WIDE)+ # And the pinned picture's own line came with it.+ self.assertIn("the empty stage", shots[0]["prompt"])+ self.assertIn("wide of the whole band", shots[-1]["prompt"])++ def test_a_pin_moves_who_is_in_frame_and_nothing_about_the_clock(self):+ loose = [dict(im, use="any") for im in self.PINNED]+ a, b = self.plan(images=loose), self.plan(images=self.PINNED)+ self.assertEqual([s["duration_s"] for s in a["shots"]],+ [s["duration_s"] for s in b["shots"]])+ self.assertEqual([s.get("audio_start_time") for s in a["shots"]],+ [s.get("audio_start_time") for s in b["shots"]])+ self.assertEqual(a["film_seconds"], b["film_seconds"])++ def test_a_weight_buys_a_picture_more_of_the_rotation(self):+ plain = [{"path": "/tmp/mv/singer_a.png", "role": "singer"},+ {"path": "/tmp/mv/piano.png", "role": "instrument"},+ {"path": "/tmp/mv/room.png", "role": "room"}]+ heavy = [dict(im, weight=3) if im["path"].endswith("piano.png") else im+ for im in plain]+ def times(images, path):+ return sum(1 for s in self.broll(self.plan(images=images))+ if s["still"] == path)+ self.assertGreater(times(heavy, "/tmp/mv/piano.png"),+ times(plain, "/tmp/mv/piano.png"))++ def test_a_per_shot_pin_is_not_overwritten_by_the_opening_pin(self):+ """Two kinds of casting decision, and the later pass ate the earlier.++ `emit()` honours `shots[i].image`, but `_pin_broll()` then recast the+ same shot for `use: open` (Codex review, 2026-09-22). The caller who+ pinned a picture to shot 1 by hand got the opening picture there+ instead, and the pin they wrote was silently worth nothing.+ """+ A, B = "/tmp/mv/roomA.png", "/tmp/mv/roomB.png"+ images = [{"path": A, "role": "room", "use": "open"},+ {"path": B, "role": "room"}]+ out = self.plan(+ sections=[{"start": 0.0, "end": 15.0, "kind": "instrumental",+ "name": "intro", "source": "score"}],+ images=images, shot_images={1: B})+ shots = out["shots"]+ self.assertEqual(shots[0]["still"], B, "the explicit pin lost")+ # …and the opening picture still gets into the film, in the first+ # B-roll slot nobody claimed.+ self.assertIn(A, [s["still"] for s in shots[1:]])++ def test_a_per_shot_pin_is_not_overwritten_by_the_closing_pin(self):+ A, B = "/tmp/mv/roomA.png", "/tmp/mv/roomB.png"+ images = [{"path": A, "role": "room", "use": "close"},+ {"path": B, "role": "room"}]+ out = self.plan(images=images)+ last = len(out["shots"])+ self.assertEqual(out["shots"][-1]["still"], A) # unpinned: A closes+ out = self.plan(images=images, shot_images={last: B})+ self.assertEqual(out["shots"][-1]["still"], B)+ self.assertIn(A, [s["still"] for s in out["shots"][:-1]])++ def test_a_film_whose_every_broll_shot_is_pinned_says_the_truth(self):+ # Not "every shot is a singing shot" — there were slots, the caller+ # had already cast all of them.+ A, B = "/tmp/mv/roomA.png", "/tmp/mv/roomB.png"+ out = self.plan(+ sections=[{"start": 0.0, "end": 6.0, "kind": "instrumental",+ "name": "intro", "source": "score"}],+ images=[{"path": A, "role": "room", "use": "open"},+ {"path": B, "role": "room"}],+ shot_images={1: B})+ self.assertEqual([s["still"] for s in out["shots"]], [B])+ self.assertTrue(any("pinned to a picture by hand" in n+ for n in out["notes"]), out["notes"])+ self.assertFalse(any("singing shot" in n for n in out["notes"]),+ out["notes"])++ def test_the_reserved_shot_is_said_out_loud(self):+ A, B = "/tmp/mv/roomA.png", "/tmp/mv/roomB.png"+ out = self.plan(images=[{"path": A, "role": "room", "use": "open"},+ {"path": B, "role": "room"}],+ shot_images={1: B})+ self.assertTrue(any("pinned" in n and "open" in n for n in out["notes"]),+ out["notes"])++ def test_without_a_per_shot_pin_open_and_close_are_unchanged(self):+ out = self.plan(images=self.PINNED)+ shots = self.broll(out)+ self.assertEqual(shots[0]["still"], self.STAGE)+ self.assertEqual(shots[-1]["still"], self.WIDE)++ def test_a_singer_pinned_to_open_is_ignored_and_said_so(self):+ images = [dict(self.PINNED[0], use="open")] + self.PINNED[1:]+ out = self.plan(images=images)+ self.assertEqual(self.broll(out)[0]["still"], self.STAGE)+ self.assertTrue(any("Singer" in n for n in out["notes"]), out["notes"])+++class TheLineForOneShot(_Planned, unittest.TestCase):+ """A per-image prompt follows the picture into every shot it is cast in;+ the last shot of a film needs a line no other shot may have."""++ def repeated(self, out):+ """(picture, [shot numbers]) for a picture cast more than once."""+ by_image: dict[str, list[int]] = {}+ for s in out["shots"]:+ by_image.setdefault(s["still"], []).append(int(s["n"]))+ return next((k, v) for k, v in by_image.items() if len(v) >= 2)++ def test_a_shot_level_line_does_not_leak_to_other_uses_of_the_picture(self):+ base = self.plan()+ _image, ns = self.repeated(base)+ line = "the stage lights slowly fading down to black"+ out = self.plan(shot_prompts={ns[0]: line})+ before = {int(s["n"]): s for s in base["shots"]}+ after = {int(s["n"]): s for s in out["shots"]}+ self.assertIn(line, after[ns[0]]["prompt"])+ self.assertTrue(after[ns[0]]["music_video"]["prompt_override"])+ for n in ns[1:]:+ self.assertNotIn(line, after[n]["prompt"])+ self.assertEqual(after[n]["prompt"], before[n]["prompt"])+ self.assertNotIn("prompt_override", after[n]["music_video"])++ def test_the_overridden_line_still_carries_the_film_s_look(self):+ out = self.plan(shot_prompts={1: "the door opens"})+ self.assertIn(STYLE, out["shots"][0]["prompt"])++ def test_a_line_and_a_pin_on_the_same_shot_both_survive(self):+ images = [{"path": "/tmp/mv/singer_a.png", "role": "singer"},+ {"path": "/tmp/mv/piano.png", "role": "instrument"},+ {"path": "/tmp/mv/wide.png", "role": "room", "use": "close"}]+ out = self.plan(images=images)+ last = out["shots"][-1]+ self.assertEqual(last["music_video"]["kind"], "broll")+ pinned = self.plan(images=images,+ shot_prompts={int(last["n"]): "lights to black"})+ end = pinned["shots"][-1]+ self.assertEqual(end["still"], "/tmp/mv/wide.png")+ self.assertIn("lights to black", end["prompt"])++ def test_a_line_for_a_shot_that_does_not_exist_is_a_note_not_a_crash(self):+ out = self.plan(shot_prompts={9999: "nobody's shot"})+ self.assertTrue(any("9999" in n for n in out["notes"]), out["notes"])++ def test_nonsense_keys_are_ignored_rather_than_refused(self):+ self.assertEqual(mv._shot_prompts({"3": "a", "x": "b", 4: "", 0: "c"}),+ {3: "a"})+++class TheCallerCanWriteTheStructure(unittest.TestCase):+ """`given_sections`: the person with the song knows where the lines are.+ The first real film was planned against measured vocal onsets typed in by+ hand, because no analyser could have known them."""++ ROWS = [{"start": 0.0, "end": 8.5, "kind": "instrumental", "label": "open"},+ {"start": 8.5, "end": 51.6, "kind": "vocal", "label": "intro"},+ {"start": 51.6, "end": 60.0, "kind": "instrumental"}]++ def test_the_rows_are_taken_as_written(self):+ rows, notes = mv.given_sections(self.ROWS, duration=60.0)+ self.assertEqual([r["kind"] for r in rows],+ ["instrumental", "vocal", "instrumental"])+ self.assertEqual([r["name"] for r in rows],+ ["open", "intro", "instrumental"])+ self.assertTrue(all(r["source"] == "given" for r in rows))+ self.assertEqual(notes, [])++ def test_they_are_sorted_and_the_gaps_are_closed(self):+ rows, _ = mv.given_sections(+ [{"start": 20.0, "end": 30.0, "kind": "vocal"},+ {"start": 0.0, "end": 10.0, "kind": "instrumental"}],+ duration=30.0)+ self.assertEqual([r["start"] for r in rows], [0.0, 10.0])+ for a, b in zip(rows, rows[1:]):+ self.assertEqual(a["end"], b["start"])++ def test_the_first_section_is_pulled_to_the_start_of_the_song(self):+ # The film plays from 0:00 with the song under it from 0:00. A cursor+ # that began at 8.5 s would render every mouth 8.5 s off its words.+ rows, notes = mv.given_sections(+ [{"start": 8.5, "end": 40.0, "kind": "vocal"}], duration=40.0)+ self.assertEqual(rows[0]["start"], 0.0)+ self.assertTrue(any("0:00" in n for n in notes), notes)++ def test_a_section_past_the_end_of_the_song_is_clamped(self):+ rows, _ = mv.given_sections(+ [{"start": 0.0, "end": 30.0, "kind": "vocal"},+ {"start": 30.0, "end": 900.0, "kind": "instrumental"}],+ duration=40.0)+ self.assertEqual(rows[-1]["end"], 40.0)++ def test_sections_that_stop_early_are_honoured_and_noted(self):+ rows, notes = mv.given_sections(+ [{"start": 0.0, "end": 30.0, "kind": "vocal"}], duration=90.0)+ self.assertEqual(rows[-1]["end"], 30.0)+ self.assertTrue(any("no shots" in n for n in notes), notes)++ def test_overlapping_sections_are_refused_by_name(self):+ with self.assertRaises(mv.MusicVideoError) as cm:+ mv.given_sections([{"start": 0.0, "end": 30.0, "kind": "vocal"},+ {"start": 20.0, "end": 40.0, "kind": "vocal"}],+ duration=40.0)+ self.assertIn("overlap", str(cm.exception))++ def test_every_other_way_of_getting_it_wrong_is_a_sentence(self):+ for rows, word in (+ ([], "list"),+ ("not a list", "list"),+ ([{"start": 0.0, "end": 5.0}], "kind"),+ ([{"start": 0.0, "end": 5.0, "kind": "chorus"}], "kind"),+ ([{"start": 5.0, "end": 5.0, "kind": "vocal"}], "after"),+ ([{"end": 5.0, "kind": "vocal"}], "start"),+ ([["nope"]], "object"),+ ([{"start": 200.0, "end": 300.0, "kind": "vocal"}], "inside")):+ with self.assertRaises(mv.MusicVideoError, msg=rows) as cm:+ mv.given_sections(rows, duration=60.0)+ self.assertIn(word, str(cm.exception))+++class TheBoardTheStoryboardGets(unittest.TestCase):+ """The plan has to be a board the existing machinery can shoot."""++ @classmethod+ def setUpClass(cls):+ cls.tmp = TemporaryDirectory()+ root = Path(cls.tmp.name)+ cls.song = root / "click.wav"+ click_track(cls.song, bars=24, vocal_bars=range(8, 16))+ cls.beats = sedit.beat_map(cls.song)+ # Real files, because the validator checks refs and the panel checks+ # stills; a fake path would pass the planner and fail the render.+ cls.images = []+ for name, role in (("singer_a.png", "singer"), ("singer_b.png", "singer"),+ ("piano.png", "instrument"), ("room.png", "room")):+ p = root / name+ p.write_bytes(b"\x89PNG\r\n\x1a\n")+ cls.images.append({"path": str(p), "role": role})+ cls.out = mv.plan_music_video(+ [{"start": 0.0, "end": 10.0, "kind": "instrumental",+ "name": "intro", "source": "score"},+ {"start": 10.0, "end": 60.0, "kind": "vocal",+ "name": "verse", "source": "score"}],+ cls.images, style=STYLE, bpm_grid=cls.beats,+ song=str(cls.song), title="Test video", board_id="sb_test")++ @classmethod+ def tearDownClass(cls):+ cls.tmp.cleanup()++ def test_it_validates(self):+ errs = storyboard.validate_storyboard(self.out["board"])+ self.assertEqual(errs, [], errs)++ def test_every_shot_is_ltx_because_a2v_only_exists_there(self):+ self.assertEqual(self.out["board"]["engine_mode"], "ltx")+ self.assertEqual({s["engine"] for s in self.out["shots"]}, {"ltx"})++ def test_a_singing_shot_becomes_an_a2v_job_carrying_its_audio(self):+ shot = next(s for s in self.out["shots"]+ if s["music_video"]["kind"] == "singing")+ job = storyboard.shot_to_job(shot, storyboard.default_policy()["final"],+ board_id="sb_test", engine_mode="ltx")+ self.assertEqual(job["mode"], "a2v")+ self.assertEqual(job["audio"], str(self.song))+ self.assertAlmostEqual(float(job["audio_start_time"]),+ shot["audio_start_time"], places=3)+ self.assertEqual(job["image"], shot["still"])+ self.assertEqual(int(job["frames"]), shot["music_video"]["frames"])++ def test_a_broll_shot_becomes_an_anchored_i2v_job(self):+ shot = next(s for s in self.out["shots"]+ if s["music_video"]["kind"] == "broll")+ job = storyboard.shot_to_job(shot, storyboard.default_policy()["final"],+ board_id="sb_test", engine_mode="ltx")+ self.assertEqual(job["mode"], "i2v")+ self.assertEqual(job["image"], shot["still"])+ self.assertEqual(job["i2v_reference_mode"], "anchor")+ self.assertNotIn("audio", job)++ def test_the_board_remembers_the_song_and_the_cast(self):+ block = self.out["board"]["music_video"]+ self.assertEqual(block["song"], str(self.song))+ self.assertEqual([i["role"] for i in block["images"]],+ [i["role"] for i in self.images])+ self.assertEqual(block["summary"], self.out["summary"])+++if __name__ == "__main__":+ unittest.main()diff --git a/test_music_video_editor.py b/test_music_video_editor.pynew file mode 100644index 0000000..1e99ebe--- /dev/null+++ b/test_music_video_editor.py@@ -0,0 +1,106 @@+#!/usr/bin/env python3+"""A music video opened in the Editor keeps its plan and its song (SB5-12).++The planner stores the master track at `board["music_video"]["song"]` and+places every shot at a planned film second; each singing (a2v) shot was+rendered against exactly that stretch of the song. The Editor's first GET+used to run the ordinary auto-editor over it — no song, every shot re-cut —+and the edit it wrote is also what `/music/video/film` renders afterwards.++Driven through the real Editor GET on a scratch board; ffprobe is mocked and+the auto-editor is made to fail loudly if it is reached at all.+"""+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 # noqa: E402+import storyboard_edit # noqa: E402+import storyboard_editor as sedit # noqa: E402+from test_storyboard_editor_api import EditorCase, FakeHandler # noqa: E402++# Singing / B-roll / singing, at the seconds the planner laid them out.+PLAN = [(1, "singing", 0.0, 4.25), (2, "broll", 4.25, 9.5),+ (3, "singing", 9.5, 13.0)]+++class MusicVideoOpensOnItsPlan(EditorCase):++ def setUp(self):+ super().setUp()+ self.song = self.root / "song.wav"+ self.song.write_bytes(b"RIFF")+ shots = []+ for (n, kind, fs, fe), clip in zip(PLAN, self.clips):+ shots.append({+ "n": n, "mode": "image", "engine": "ltx", "prompt": f"shot {n}",+ "duration_s": fe - fs, "seed": n, "refs": [], "status": "done",+ "draft_output": str(clip),+ "music_video": {"kind": kind, "film_start": fs, "film_end": fe,+ "panel_mode": "a2v" if kind == "singing" else "i2v"}})+ board = dict(self.board, shots=shots,+ music_video={"song": str(self.song), "film_seconds": 13.0})+ storyboard.save_storyboard(self.state, board)+ # File durations: shot 2 came out one frame short, as renders do.+ self.durations = {str(self.clips[0]): 4.25, str(self.clips[1]): 5.25 - 1 / 24,+ str(self.clips[2]): 3.5, str(self.song): 13.0}++ def _get(self):+ def probe(path):+ d = self.durations.get(str(path))+ return {"duration": d, "w": 768, "h": 416, "has_audio": True} if d else None++ def no_recut(*a, **k):+ raise AssertionError("the auto-editor re-cut a music video")++ with mock.patch.object(storyboard_edit, "probe_media", side_effect=probe), \+ mock.patch.object(storyboard_edit, "plan_cut", side_effect=no_recut):+ return FakeHandler().get("/storyboard/edit?id=sb_t")++ def test_every_shot_sits_where_the_plan_put_it_whole(self):+ h = self._get()+ self.assertEqual(h.status, 200, h.payload)+ clips = sorted(h.payload["edit"]["clips"], key=lambda c: c["film_start"])+ self.assertEqual([round(c["film_start"], 4) for c in clips], [0.0, 4.25, 9.5])+ self.assertEqual([c["start"] for c in clips], [0.0, 0.0, 0.0])+ # Whole shots — trimmed only where the file is shorter than planned.+ self.assertEqual([round(c["end"], 4) for c in clips],+ [4.25, round(5.25 - 1 / 24, 4), 3.5])++ def test_the_song_is_the_bed_replacing_the_clips_at_unity(self):+ audio = self._get().payload["edit"]["audio"]+ self.assertEqual(audio["path"], str(self.song))+ self.assertEqual(audio["mode"], "replace")+ self.assertEqual(float(audio.get("offset") or 0.0), 0.0)+ mix = sedit.audio_mix(audio)+ self.assertEqual((mix["bed_gain"], mix["duck"]), (1.0, False))++ def test_the_render_plan_carries_the_song_for_the_whole_film(self):+ self._get()+ edit = sedit.load_edit(self.bdir)+ win = sedit.music_window(edit["audio"])+ self.assertEqual((win["start"], win["film_start"]), (0.0, 0.0))+ self.assertIsNone(win["end"])+ cuts = sedit.edit_to_cuts(edit)+ self.assertEqual([round(c["film_start"], 4) for c in cuts], [0.0, 4.25, 9.5])++ def test_an_ordinary_board_still_gets_the_auto_editor(self):+ board = dict(self.board)+ board.pop("music_video", None)+ storyboard.save_storyboard(self.state, board)+ with mock.patch.object(storyboard_edit, "plan_cut",+ return_value=[]) as pc, \+ mock.patch.object(storyboard_edit, "probe_media", return_value=None):+ FakeHandler().get("/storyboard/edit?id=sb_t")+ pc.assert_called_once()+++if __name__ == "__main__":+ unittest.main()diff --git a/test_music_video_minshot.py b/test_music_video_minshot.pynew file mode 100644index 0000000..9777c21--- /dev/null+++ b/test_music_video_minshot.py@@ -0,0 +1,95 @@+"""No planned shot is shorter than a second — the board writer would stretch it.++Codex review, 2026-09-20: the planner allowed a 9-frame scrap (0.375 s) at the+end of a section; `_sb_normalize` then raised it to 1 s while every singing+shot after it kept its planned `audio_start_time`, so the singer appeared at+11.08 s singing the words from 10.42 s. A scrap now folds into the B-roll shot+before it, and nothing the planner writes is ever below MIN_SHOT_S.+"""+import math+import unittest+import wave+from pathlib import Path+from tempfile import TemporaryDirectory++import numpy as np++import music_video as mv+import storyboard_edit as sedit++IMAGES = [+ {"path": "/tmp/mv/singer_a.png", "role": "singer"},+ {"path": "/tmp/mv/piano.png", "role": "instrument"},+ {"path": "/tmp/mv/room.png", "role": "room"},+]+++def click_track(path: Path, seconds: float, bpm: float = 120.0, sr: int = 44100):+ """A metronome: a short decaying click on every beat, louder on the one."""+ n = int(seconds * sr)+ y = np.zeros(n, dtype=np.float32)+ per = 60.0 / bpm+ t = 0.0+ k = 0+ while t < seconds:+ i = int(t * sr)+ length = min(n - i, int(0.03 * sr))+ if length <= 0:+ break+ env = np.exp(-np.arange(length) / (0.004 * sr))+ y[i:i + length] += (0.9 if k % 4 == 0 else 0.5) * env * np.sin(2 * np.pi * 1000 * np.arange(length) / sr)+ t += per+ k += 1+ with wave.open(str(path), "wb") as fh:+ fh.setnchannels(1); fh.setsampwidth(2); fh.setframerate(sr)+ fh.writeframes((np.clip(y, -1, 1) * 32767).astype(np.int16).tobytes())+++class NothingUnderASecond(unittest.TestCase):++ @classmethod+ def setUpClass(cls):+ cls.tmp = TemporaryDirectory()+ cls.song = Path(cls.tmp.name) / "click.wav"+ click_track(cls.song, 40.0)+ cls.beats = sedit.beat_map(cls.song)++ @classmethod+ def tearDownClass(cls):+ cls.tmp.cleanup()++ def plan(self, sections):+ return mv.plan_music_video(sections, IMAGES, style="x", bpm_grid=self.beats,+ song=str(self.song), title="t", board_id="sb_test")++ def shots(self, board):+ return board["shots"] if isinstance(board, dict) and "shots" in board else board["board"]["shots"]++ def test_a_scrap_at_a_section_end_folds_into_the_shot_before_it(self):+ # 5.375 s of B-roll cell + a 0.375 s scrap used to be two shots.+ board = self.plan([{"start": 0.0, "end": 5.75, "kind": "instrumental", "name": "intro"},+ {"start": 5.75, "end": 30.0, "kind": "vocal", "name": "verse"}])+ for s in self.shots(board):+ self.assertGreaterEqual(float(s["duration_s"]), mv.MIN_SHOT_S - 1e-6, s)+ self.assertGreaterEqual(int(s["music_video"]["frames"]), 25, s)++ def test_the_singer_still_starts_where_the_film_has_reached(self):+ """The whole point of the cursor: a singing shot's audio offset is the+ film time at which it begins, after every fold before it."""+ board = self.plan([{"start": 0.0, "end": 5.75, "kind": "instrumental", "name": "intro"},+ {"start": 5.75, "end": 30.0, "kind": "vocal", "name": "verse"}])+ cursor = 0.0+ for s in self.shots(board):+ if s["music_video"]["kind"] == "singing":+ self.assertAlmostEqual(float(s["audio_start_time"]), cursor, places=3)+ cursor += s["music_video"]["frames"] / float(mv.FPS)++ def test_a_song_of_only_scraps_still_gets_a_whole_second(self):+ board = self.plan([{"start": 0.0, "end": 0.4, "kind": "instrumental", "name": "blip"}])+ shots = self.shots(board)+ self.assertEqual(len(shots), 1)+ self.assertGreaterEqual(float(shots[0]["duration_s"]), mv.MIN_SHOT_S - 1e-6)+++if __name__ == "__main__":+ unittest.main(verbosity=2)diff --git a/test_music_video_routes.py b/test_music_video_routes.pynew file mode 100644index 0000000..39c1f5b--- /dev/null+++ b/test_music_video_routes.py@@ -0,0 +1,469 @@+"""The two music-video routes: what they refuse, and what they write.++Same shape as `test_music_studio.py` — the route functions are called+directly with a stand-in handler, because the thing worth testing is the+door policy, not HTTP. The policy is the one every other route in this file's+neighbour obeys: **a form field naming a file is a form field naming a file**.+It resolves inside the outputs folder or the uploads folder, or it is not+used — and a role is one of three words or the request is refused.++The song is a real click track and the beat map that reads it is the real+one, so `/music/video/plan` is exercised end to end: form -> sections ->+plan -> a board on disk that `load_storyboard` can read back.+"""+from __future__ import annotations++import json+import unittest+from pathlib import Path+from tempfile import TemporaryDirectory+from urllib.parse import urlencode++import mlx_ltx_panel as P+import music_video as mv+import storyboard+from panel import routes_music as R+from panel.routes import POST_ROUTES+from test_music_video import LYRICS, SCORE, click_track++R.P = P+++class _Handler:+ """Enough of the panel's handler for a route to answer into."""++ def __init__(self, form: dict):+ self._form = {k: [v] for k, v in form.items()}+ self.status = 200+ self.body = None++ def _read_form_body(self):+ return urlencode(self._form, doseq=True), self._form++ def _json(self, payload, status=200):+ self.body, self.status = payload, status+++class _Fixture:+ """A song in the outputs and three pictures in the uploads."""++ def __enter__(self):+ self.tmp = TemporaryDirectory()+ root = Path(self.tmp.name)+ P.OUTPUT.mkdir(parents=True, exist_ok=True)+ P.UPLOADS.mkdir(parents=True, exist_ok=True)+ # Resolved, because the routes resolve: on macOS the sandbox lives+ # under /var, which is a symlink to /private/var, and an unresolved+ # fixture path would compare unequal to a correct answer.+ self.song = (P.OUTPUT / "_mvtest_song.wav").resolve()+ click_track(self.song, bars=24, vocal_bars=range(8, 16))+ self.sidecar = Path(str(self.song) + ".json")+ self.sidecar.write_text(json.dumps({"engine": "music",+ "title": "Click Track",+ "lyrics": "", "score_abc": ""}))+ self.images = []+ for name, role in (("_mvtest_face.png", "singer"),+ ("_mvtest_piano.png", "instrument"),+ ("_mvtest_room.png", "room")):+ p = (P.UPLOADS / name).resolve()+ p.write_bytes(b"\x89PNG\r\n\x1a\n")+ self.images.append({"path": str(p), "role": role})+ # A pre-separated vocal of the same song, in the outputs where a+ # panel-made file lives.+ self.stem = (P.OUTPUT / "_mvtest_song_vocals.wav").resolve()+ click_track(self.stem, bars=24, vocal_bars=range(8, 16))+ self.outsider = root / "outside.png"+ self.outsider.write_bytes(b"\x89PNG\r\n\x1a\n")+ return self++ def __exit__(self, *a):+ self.song.unlink(missing_ok=True)+ self.stem.unlink(missing_ok=True)+ self.sidecar.unlink(missing_ok=True)+ for im in self.images:+ Path(im["path"]).unlink(missing_ok=True)+ self.tmp.cleanup()++ def form(self, **over):+ base = {"song": str(self.song), "images": json.dumps(self.images),+ "style": "handheld 16mm documentary", "title": "Click Track"}+ base.update(over)+ return base+++class TheDoorTrustsNothing(unittest.TestCase):++ def test_a_file_outside_the_panel_is_not_a_panel_file(self):+ with _Fixture() as fx:+ self.assertIsNone(R._panel_file("/etc/passwd"))+ self.assertIsNone(R._panel_file(""))+ self.assertIsNone(R._panel_file(str(fx.outsider)))+ self.assertIsNone(R._panel_file(str(P.OUTPUT / "nope.wav")))+ self.assertEqual(R._panel_file(str(fx.song)), fx.song.resolve())+ self.assertEqual(R._panel_file(fx.images[0]["path"]),+ Path(fx.images[0]["path"]).resolve())++ def test_an_upload_counts_even_though_it_has_no_sidecar(self):+ # `_song_output` needs a music sidecar; a song somebody dropped in has+ # none and never will, which is why the music-video door is wider.+ with _Fixture() as fx:+ self.assertIsNotNone(R._panel_file(fx.images[0]["path"]))+ self.assertIsNone(R._song_output(fx.images[0]["path"]))++ def test_the_roles_are_a_closed_vocabulary(self):+ with _Fixture() as fx:+ self.assertEqual(R.ROLES, mv.ROLES)+ bad = [dict(fx.images[0], role="guitarist")]+ rows, err = R._music_video_images(json.dumps(bad))+ self.assertEqual(rows, [])+ self.assertIn("guitarist", err)++ def test_a_picture_from_outside_is_named_and_refused(self):+ with _Fixture() as fx:+ rows, err = R._music_video_images(json.dumps(+ [{"path": str(fx.outsider), "role": "room"}]))+ self.assertEqual(rows, [])+ self.assertIn("outside.png", err)++ def test_broken_or_empty_json_is_a_sentence_not_a_traceback(self):+ for raw in ("", "[]", "{", "not json", '["a string"]'):+ rows, err = R._music_video_images(raw)+ self.assertEqual(rows, [])+ self.assertTrue(err)++ def test_a_plan_with_no_song_is_refused(self):+ with _Fixture() as fx:+ h = _Handler(fx.form(song="/etc/passwd"))+ R.post_music_video_plan(h, "/music/video/plan", {}, "")+ self.assertEqual(h.status, 400)+ self.assertIn("song", h.body["error"])++ def test_a_plan_with_a_bad_role_is_refused_before_any_decode(self):+ with _Fixture() as fx:+ bad = [dict(fx.images[0], role="")]+ h = _Handler(fx.form(images=json.dumps(bad)))+ R.post_music_video_plan(h, "/music/video/plan", {}, "")+ self.assertEqual(h.status, 400)++ def test_a_pin_and_a_weight_are_a_closed_vocabulary_too(self):+ with _Fixture() as fx:+ for bad, word in (({"use": "middle"}, "use"),+ ({"weight": "lots"}, "weight"),+ ({"weight": 0}, "weight"),+ ({"weight": 99}, "weight")):+ rows, err = R._music_video_images(+ json.dumps([dict(fx.images[0], **bad)]))+ self.assertEqual(rows, [])+ self.assertIn(word, err)++ def test_a_good_pin_and_weight_reach_the_planner(self):+ with _Fixture() as fx:+ rows, err = R._music_video_images(json.dumps(+ [dict(fx.images[1], use="close", weight=3)]))+ self.assertEqual(err, "")+ self.assertEqual(rows[0]["use"], "close")+ self.assertEqual(rows[0]["weight"], 3)+ # Absent is the old shape, and it still means "no opinion".+ rows, _ = R._music_video_images(json.dumps([fx.images[1]]))+ self.assertEqual((rows[0]["use"], rows[0]["weight"]), ("any", 1))+++class TheRefusalSaysWhereFilesGo(unittest.TestCase):+ """The containment rule stays; the dead end goes. A refusal that does not+ say where a file BECOMES a panel file leaves the person guessing at a+ folder name, which is what the first real film's operator had to do."""++ def test_a_picture_from_outside_is_told_the_uploads_folder_and_the_route(self):+ with _Fixture() as fx:+ _rows, err = R._music_video_images(json.dumps(+ [{"path": str(fx.outsider), "role": "room"}]))+ self.assertIn(str(P.UPLOADS), err)+ self.assertIn(str(P.OUTPUT), err)+ self.assertIn("/upload", err)++ def test_a_song_from_outside_gets_the_same_sentence(self):+ with _Fixture() as fx:+ h = _Handler(fx.form(song=str(fx.outsider)))+ R.post_music_video_plan(h, "/music/video/plan", {}, "")+ self.assertEqual(h.status, 400)+ self.assertIn(str(P.UPLOADS), h.body["error"])+ self.assertIn("/upload", h.body["error"])++ def test_the_route_the_error_names_is_a_route_this_panel_has(self):+ # An error that points at an endpoint which does not exist is worse+ # than the bare one it replaced.+ self.assertIn("/upload", POST_ROUTES)+++class TheStructureCanBeGiven(unittest.TestCase):+ """Precedence, strongest first: `sections` > form lyrics/score > the+ song's sidecar > the band classifier."""++ def test_sections_beat_the_classifier_on_a_song_with_no_sidecar(self):+ with _Fixture() as fx:+ # A song somebody dropped in: in the uploads, no sidecar, and with+ # NO voice band at all — the classifier would call every second of+ # it instrumental and the film would have no singing shot.+ song = (P.UPLOADS / "_mvtest_dropped.wav").resolve()+ click_track(song, bars=24, vocal_bars=())+ try:+ rows = [{"start": 0.0, "end": 12.0, "kind": "instrumental",+ "label": "open"},+ {"start": 12.0, "end": 48.0, "kind": "vocal",+ "label": "verse"}]+ h = _Handler(fx.form(song=str(song),+ sections=json.dumps(rows)))+ R.post_music_video_plan(h, "/music/video/plan", {}, "")+ self.assertEqual(h.status, 200, h.body)+ self.assertEqual([s["source"] for s in h.body["sections"]],+ ["given", "given"])+ sung = [r for r in h.body["shots"] if r["kind"] == "singing"]+ self.assertTrue(sung, "the vocal span produced no singing shot")+ for r in sung:+ self.assertGreaterEqual(r["film_start"], 12.0 - 1e-6)+ self.assertEqual(r["section"], "verse")+ finally:+ song.unlink(missing_ok=True)++ def test_a_score_in_the_form_is_read_when_the_sidecar_has_none(self):+ with _Fixture() as fx:+ h = _Handler(fx.form(lyrics=LYRICS, score_abc=SCORE))+ R.post_music_video_plan(h, "/music/video/plan", {}, "")+ self.assertEqual(h.status, 200, h.body)+ self.assertEqual([s["name"] for s in h.body["sections"]],+ ["intro", "verse", "outro"])+ self.assertTrue(all(s["source"] == "score"+ for s in h.body["sections"]))++ def test_a_score_in_the_form_outranks_the_one_in_the_sidecar(self):+ # A song re-cut, or one whose sidecar belongs to an earlier take: the+ # score in the request is the one the caller is looking at.+ with _Fixture() as fx:+ stale = SCORE.replace("% intro", "% nobody").replace(+ "% verse", "% wrong").replace("% outro", "% stale")+ fx.sidecar.write_text(json.dumps(+ {"engine": "music", "title": "Click Track",+ "lyrics": LYRICS, "score_abc": stale}))+ h = _Handler(fx.form(score_abc=SCORE, lyrics=LYRICS))+ R.post_music_video_plan(h, "/music/video/plan", {}, "")+ self.assertEqual(h.status, 200, h.body)+ self.assertEqual([s["name"] for s in h.body["sections"]],+ ["intro", "verse", "outro"])++ def test_unreadable_sections_are_a_sentence_not_a_traceback(self):+ with _Fixture() as fx:+ for raw, word in (("{", "JSON"),+ ("[]", "list"),+ ('[{"start": 0, "end": 5}]', "kind"),+ ('[{"start": 0, "end": 5, "kind": "vocal"},'+ ' {"start": 2, "end": 9, "kind": "vocal"}]',+ "overlap")):+ h = _Handler(fx.form(sections=raw))+ R.post_music_video_plan(h, "/music/video/plan", {}, "")+ self.assertEqual(h.status, 400, raw)+ self.assertIn(word, h.body["error"])+++class TheShotPromptsAreParsed(unittest.TestCase):++ def test_both_spellings_mean_the_same_thing(self):+ listed, err = R._music_video_shot_prompts(+ json.dumps([{"n": 3, "prompt": "the lights fade"}]))+ self.assertEqual((listed, err), ({3: "the lights fade"}, ""))+ mapped, err = R._music_video_shot_prompts(+ json.dumps({"3": "the lights fade"}))+ self.assertEqual((mapped, err), ({3: "the lights fade"}, ""))+ self.assertEqual(R._music_video_shot_prompts(""), ({}, ""))++ def test_nonsense_is_named_rather_than_swallowed(self):+ for raw, word in (("{", "JSON"),+ ('"a string"', "list"),+ ('[{"prompt": "x"}]', "shot number"),+ ('[{"n": 0, "prompt": "x"}]', "start at 1"),+ ('[{"n": 2, "prompt": " "}]', "empty")):+ rows, err = R._music_video_shot_prompts(raw)+ self.assertEqual(rows, {})+ self.assertIn(word, err, raw)++ def test_a_line_written_for_one_shot_reaches_that_shot_alone(self):+ with _Fixture() as fx:+ base = _Handler(fx.form())+ R.post_music_video_plan(base, "/music/video/plan", {}, "")+ self.assertEqual(base.status, 200, base.body)+ rows = base.body["shots"]+ self.assertTrue(all(r["prompt_override"] is False for r in rows))+ n = rows[-1]["n"]+ h = _Handler(fx.form(shots=json.dumps(+ [{"n": n, "prompt": "the lights fade down to black"}])))+ R.post_music_video_plan(h, "/music/video/plan", {}, "")+ self.assertEqual(h.status, 200, h.body)+ after = {r["n"]: r for r in h.body["shots"]}+ self.assertIn("the lights fade down to black", after[n]["prompt"])+ self.assertTrue(after[n]["prompt_override"])+ for r in rows[:-1]:+ self.assertEqual(after[r["n"]]["prompt"], r["prompt"])+++class TheAxisFollowsTheDeliveryQuality(unittest.TestCase):++ def test_no_shot_uses_a_cell_the_final_pass_cannot_render(self):+ with _Fixture() as fx:+ h = _Handler(fx.form())+ R.post_music_video_plan(h, "/music/video/plan", {}, "")+ self.assertEqual(h.status, 200, h.body)+ quality = str(P.get_settings().get(+ "storyboard_final_quality", "standard") or "standard")+ self.assertEqual(h.body["quality"], quality)+ allowed = {f for _s, f in+ mv.cells_from_lengths(P.LTX_LENGTHS, quality=quality)}+ for row in h.body["shots"]:+ if row["mode"] == "a2v":+ self.assertIn(row["frames"], allowed, row)+ board = storyboard.load_storyboard(P.STATE_DIR, h.body["board_id"])+ self.assertEqual(board["music_video"]["quality"], quality)+++class ThePlanRouteWritesABoard(unittest.TestCase):++ @classmethod+ def setUpClass(cls):+ cls.fx = _Fixture().__enter__()+ cls.h = _Handler(cls.fx.form())+ R.post_music_video_plan(cls.h, "/music/video/plan", {}, "")++ @classmethod+ def tearDownClass(cls):+ cls.fx.__exit__(None, None, None)++ def test_it_answers_with_the_board_the_summary_and_the_shots(self):+ self.assertEqual(self.h.status, 200, self.h.body)+ body = self.h.body+ self.assertTrue(body["board_id"].startswith("sb_"))+ self.assertRegex(body["summary"], r"^\d+ shots · \d+ singing · ")+ self.assertEqual(len(body["shots"]), len(self.saved()["shots"]))++ def saved(self):+ return storyboard.load_storyboard(P.STATE_DIR, self.h.body["board_id"])++ def test_the_board_is_on_disk_and_valid(self):+ board = self.saved()+ self.assertEqual(storyboard.validate_storyboard(board), [])+ self.assertEqual(board["engine_mode"], "ltx")+ self.assertEqual(board["music_video"]["song"], str(self.fx.song))++ def test_the_policy_is_this_machine_s_saved_quality_not_the_module_default(self):+ # `new_storyboard` hands back storyboard.DEFAULT_POLICY, which ignores+ # this Mac's canvas cap — the same trap the planner route already fell+ # into once (the `setdefault("policy", …)` no-op).+ self.assertEqual(+ self.saved()["policy"],+ P._sb_policy_for(+ P.get_settings().get("storyboard_draft_quality", "quick"),+ P.get_settings().get("storyboard_final_quality", "standard")))++ def test_the_shot_rows_say_which_panel_mode_will_run(self):+ modes = {r["mode"] for r in self.h.body["shots"]}+ self.assertTrue(modes <= {"a2v", "i2v"}, modes)+ for row in self.h.body["shots"]:+ if row["mode"] == "a2v":+ self.assertIsNotNone(row["audio_start_time"])+ self.assertAlmostEqual(row["audio_start_time"],+ row["film_start"], places=3)++ def test_the_cells_come_from_the_panel_s_own_table(self):+ frames = {int(l["frames"]) for l in P.LTX_LENGTHS.values()}+ for row in self.h.body["shots"]:+ if row["mode"] == "a2v":+ self.assertIn(row["frames"], frames)+++class TheVocalStemRidesOnTheSingingShots(unittest.TestCase):+ """A stem conditions the mouth; the film still plays the record."""++ def test_a_stem_from_outside_the_panel_is_refused_by_name(self):+ with _Fixture() as fx:+ h = _Handler(fx.form(vocal_stem=str(fx.outsider)))+ R.post_music_video_plan(h, "/music/video/plan", {}, "")+ self.assertEqual(h.status, 400)+ self.assertIn("outside.png", h.body["error"])+ self.assertIn("uploads", h.body["error"])++ def test_the_stem_reaches_every_singing_shot_and_nothing_else(self):+ with _Fixture() as fx:+ h = _Handler(fx.form(vocal_stem=str(fx.stem)))+ R.post_music_video_plan(h, "/music/video/plan", {}, "")+ self.assertEqual(h.status, 200, h.body)+ self.assertEqual(h.body["vocal_stem"], str(fx.stem))+ board = storyboard.load_storyboard(P.STATE_DIR, h.body["board_id"])+ self.assertEqual(board["music_video"]["vocal_stem"], str(fx.stem))+ sang = 0+ for shot in board["shots"]:+ if shot["mode"] == "a2v":+ self.assertEqual(shot["audio_stem"], str(fx.stem))+ self.assertEqual(shot["audio"], str(fx.song))+ sang += 1+ else:+ self.assertNotIn("audio_stem", shot)+ self.assertTrue(sang)++ def test_no_stem_named_means_no_stem_anywhere(self):+ with _Fixture() as fx:+ h = _Handler(fx.form())+ R.post_music_video_plan(h, "/music/video/plan", {}, "")+ self.assertEqual(h.status, 200, h.body)+ self.assertEqual(h.body["vocal_stem"], "")+ board = storyboard.load_storyboard(P.STATE_DIR, h.body["board_id"])+ for shot in board["shots"]:+ self.assertNotIn("audio_stem", shot)+++class TheFilmRoute(unittest.TestCase):++ def call(self, board_id, **over):+ h = _Handler({"board_id": board_id, **over})+ R.post_music_video_film(h, "/music/video/film", {}, "")+ return h++ def test_an_unknown_board_is_a_404(self):+ self.assertEqual(self.call("sb_nope").status, 404)++ def test_a_board_that_is_not_a_music_video_is_refused_with_the_reason(self):+ board = storyboard.new_storyboard("sb_mvtest_plain", "Plain film")+ storyboard.save_storyboard(P.STATE_DIR, board)+ h = self.call("sb_mvtest_plain")+ self.assertEqual(h.status, 409)+ self.assertIn("song", h.body["error"])++ def test_a_song_that_moved_is_a_404_not_a_silent_film(self):+ board = storyboard.new_storyboard("sb_mvtest_gone", "Gone")+ board["music_video"] = {"song": "/tmp/not-here.wav", "images": []}+ storyboard.save_storyboard(P.STATE_DIR, board)+ h = self.call("sb_mvtest_gone")+ self.assertEqual(h.status, 404)++ def test_the_song_replaces_every_clip_s_audio_and_the_cut_is_left_alone(self):+ # THE TWO THINGS THIS ROUTE EXISTS FOR. `replace` throws the a2v+ # clips' own audio away so the master is one continuous song; the+ # auto-editor stays OFF because the board is already cut to the grid+ # and `plan_cut` would walk every later shot off its own words.+ from unittest import mock+ with _Fixture() as fx:+ board = storyboard.new_storyboard("sb_mvtest_film", "A film")+ board["music_video"] = {"song": str(fx.song), "images": []}+ storyboard.save_storyboard(P.STATE_DIR, board)+ with mock.patch.object(P, "_sb_export",+ return_value={"ok": True}) as exp:+ self.call("sb_mvtest_film")+ kw = exp.call_args.kwargs+ self.assertEqual(kw["music"], str(fx.song))+ self.assertEqual(kw["music_mode"], "replace")+ self.assertFalse(kw["auto_edit"])++ with mock.patch.object(P, "_sb_export",+ return_value={"ok": True}) as exp:+ self.call("sb_mvtest_film", auto_edit="on")+ self.assertTrue(exp.call_args.kwargs["auto_edit"])+++if __name__ == "__main__":+ unittest.main()diff --git a/test_outputs_cache_invalidation.py b/test_outputs_cache_invalidation.pynew file mode 100644index 0000000..304c1dc--- /dev/null+++ b/test_outputs_cache_invalidation.py@@ -0,0 +1,81 @@+"""Deleted and hidden outputs do not come back from the Show-all cache (Codex UI-06).++After "Show all" (or typing a search, which loads the same list),+filteredMainOutputs() re-adds every cached path missing from the poll. Delete+and hide only cleared `currentOutputs` and polled, so a deleted clip came back+as a 404 card and a hidden one stayed visible. Runs the REAL boot.js / queue.js+functions in node against stubbed fetch, poll and DOM.+"""+from __future__ import annotations++import json+import shutil+import subprocess+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent++_JS = r"""+const fs = require('fs'), vm = require('vm');+function extract(file, name) {+ const s = fs.readFileSync(file, 'utf8');+ const start = s.search(new RegExp('(async )?function ' + name + '\\('));+ if (start < 0) throw new Error('missing ' + name);+ return s.slice(start, s.indexOf('\n}', start) + 2);+}+const B = process.argv[1] + '/webapp/js/boot.js', Q = process.argv[1] + '/webapp/js/queue.js';+let server = ['/o/new.mp4', '/o/old1.mp4', '/o/old2.png', '/o/hideme.mp4'];+const ctx = {+ window: {}, console, out: {}, Set, Promise, URLSearchParams, JSON, String, Array,+ currentOutputs: [], mainOutputsFilter: 'all', activePath: null,+ confirm: () => true, phosToast: () => {}, renderCarousel: () => {}, paintOutputsCount: () => {},+ outputKind: () => 'video',+ document: {getElementById: () => null},+ poll: () => { ctx.currentOutputs = [{path: server[0]}]; }, // the newest only, like /status+ fetch: async (url, opts) => {+ if (url.startsWith('/outputs')) return {ok: true, json: async () => ({outputs: server.map(p => ({path: p}))})};+ const m = url.match(/path=([^&]+)/);+ const p = m ? decodeURIComponent(m[1]) : (opts && opts.body && opts.body.get('path'));+ if (url.startsWith('/output/delete') || url.startsWith('/output/hide')) server = server.filter(x => x !== p);+ return {ok: true, json: async () => ({ok: true})};+ },+};+ctx.window = ctx;+vm.createContext(ctx);+for (const [f, n] of [[B, 'filteredMainOutputs'], [B, 'applyOutputsQuery'], [B, 'outputsLoadAll'],+ [B, 'outputsCacheMutated'], [Q, 'deleteOutput'], [Q, 'hide']]) {+ try { vm.runInContext(extract(f, n), ctx); }+ catch (e) { if (n !== 'outputsCacheMutated') throw e; } // absent before the fix+}+vm.runInContext(`var _outputsQuery = '';`, ctx);+(async () => {+ await vm.runInContext('outputsLoadAll()', ctx);+ ctx.poll();+ ctx.out.before = vm.runInContext('filteredMainOutputs().map(o => o.path)', ctx);+ await vm.runInContext("deleteOutput('/o/old1.mp4')", ctx);+ await new Promise(r => setTimeout(r, 20));+ ctx.out.afterDelete = vm.runInContext('filteredMainOutputs().map(o => o.path)', ctx);+ await vm.runInContext("hide('/o/hideme.mp4')", ctx);+ await new Promise(r => setTimeout(r, 20));+ ctx.out.afterHide = vm.runInContext('filteredMainOutputs().map(o => o.path)', ctx);+ process.stdout.write(JSON.stringify(ctx.out));+})().catch(e => { console.error(e); process.exit(1); });+"""++[email protected](shutil.which("node"), "node not on PATH")+class ShowAllCacheFollowsMutations(unittest.TestCase):+ def test_deleted_and_hidden_outputs_stay_gone(self):+ r = subprocess.run(["node", "-e", _JS, str(ROOT)], capture_output=True, text=True,+ errors="replace", timeout=60)+ self.assertEqual(r.returncode, 0, r.stderr)+ out = json.loads(r.stdout)+ self.assertIn("/o/old1.mp4", out["before"])+ self.assertNotIn("/o/old1.mp4", out["afterDelete"])+ self.assertIn("/o/old2.png", out["afterDelete"])+ self.assertNotIn("/o/hideme.mp4", out["afterHide"])+++if __name__ == "__main__":+ unittest.main()diff --git a/test_outputs_search.py b/test_outputs_search.pyindex cf69bdc..20b8ed5 100644--- a/test_outputs_search.py+++ b/test_outputs_search.py@@ -31,6 +31,18 @@ class TheWords(unittest.TestCase):self.assertEqual(panel._output_search_text({}, {}), "")self.assertEqual(panel._output_search_text({"bad": object()}, {"prompt": None}), "")+ def test_image_studio_sidecars_are_searchable_by_prompt_seed_and_size(self):+ """Codex UI-07: image sidecars keep these at the top level."""+ q = panel._output_search_text(+ {"prompt": "a zebra on Mars", "seed": 42, "width": 1024, "height": 1024,+ "engine": "mflux", "model": "qwen-image-edit-2511"}, {})+ for w in ("a zebra on mars", "42", "1024x1024", "mflux"):+ self.assertIn(w, q, w)+ # params still wins where both exist+ q2 = panel._output_search_text({"prompt": "top"}, {"prompt": "nested"})+ self.assertIn("nested", q2)+ self.assertNotIn("top", q2)+def test_list_outputs_carries_q(self):with tempfile.TemporaryDirectory() as d:out = Path(d)diff --git a/test_q8_sidebar_download.py b/test_q8_sidebar_download.pynew file mode 100644index 0000000..4bd4051--- /dev/null+++ b/test_q8_sidebar_download.py@@ -0,0 +1,69 @@+"""The sidebar's Q8 download picks its transport from the registry (Codex INST-06).++With LTX_MODEL_VERSION=ltx23 the script correctly chose the 2.3 pack (`q8`) and+then handed it to the GitHub-release fetcher, which only knows the mirrored 2.5+packs — so the download failed before a byte moved, under a banner blaming the+network. Runs the REAL q8_weights.sh in a throwaway app root whose python,+fetcher and `hf` are recording stubs: nothing is downloaded.+"""+from __future__ import annotations++import json+import os+import shutil+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+++class Q8SidebarTransport(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ app = self.app = Path(self.tmp.name)+ (app / "scripts" / "pinokio").mkdir(parents=True)+ shutil.copy(ROOT / "required_files.json", app / "required_files.json")+ shutil.copy(ROOT / "scripts/pinokio/q8_weights.sh", app / "scripts/pinokio/q8_weights.sh")+ bindir = app / "ltx-2-mlx" / "env" / "bin"+ bindir.mkdir(parents=True)+ self.log = app / "calls.log"+ (bindir / "python3.11").write_text(f'#!/bin/sh\nexec "{sys.executable}" "$@"\n')+ (bindir / "hf").write_text(+ '#!/bin/sh\nprintf "hf" >> calls.log\n'+ 'for a in "$@"; do printf " [%s]" "$a" >> calls.log; done\necho >> calls.log\n')+ (app / "scripts" / "fetch_pack_release.py").write_text(+ "import sys\nopen('calls.log','a').write('release ' + ' '.join(sys.argv[1:]) + '\\n')\n")+ for f in bindir.iterdir():+ f.chmod(0o755)++ def tearDown(self):+ self.tmp.cleanup()++ def _run(self, version: str) -> str:+ env = {k: v for k, v in os.environ.items() if k != "LTX_MODEL_VERSION"}+ env["LTX_MODEL_VERSION"] = version+ r = subprocess.run(["bash", "scripts/pinokio/q8_weights.sh"], cwd=self.app, env=env,+ capture_output=True, text=True, errors="replace", timeout=60)+ self.assertEqual(r.returncode, 0, r.stdout + r.stderr)+ return self.log.read_text()++ def test_ltx23_q8_goes_through_hf_with_the_registry_allowlist(self):+ calls = self._run("ltx23")+ repo = next(r for r in json.loads((ROOT / "required_files.json").read_text())["repos"]+ if r["key"] == "q8")+ self.assertNotIn("release", calls)+ self.assertTrue(calls.startswith(f"hf [download] [{repo['repo_id']}] "+ f"[--local-dir] [{repo['local_dir']}]"), calls)+ for pat in repo["download_include"]:+ self.assertIn(f"[--include] [{pat}]", calls)++ def test_ltx25_q8_still_uses_the_release_mirror(self):+ calls = self._run("ltx25")+ self.assertEqual(calls.strip(), "release --repo-key q8_25")+++if __name__ == "__main__":+ unittest.main()diff --git a/test_release_coherence.py b/test_release_coherence.pyindex 2c83b0a..de1d3fb 100644--- a/test_release_coherence.py+++ b/test_release_coherence.py@@ -73,6 +73,41 @@ class ReadmeVersionBanner(unittest.TestCase):)+class ReadmeManualInstall(unittest.TestCase):+ """The README's Manual install runs on a fresh machine (Codex INST-04).++ It created the venv with `uv venv --seed` and then called `./env/bin/uv`,+ which `--seed` never installs (pip, setuptools, wheel only) — so every+ package step failed and the reader was left with a venv holding a Python+ and nothing else. It also named a stale engine tag and skipped the+ transformers cap and the dependency pass install.js runs.+ """++ def _section(self):+ readme = _read("README.md")+ start = readme.index("### Manual install")+ end = readme.index("\n## ", start) if "\n## " in readme[start:] else len(readme)+ return readme[start:end]++ def test_no_venv_local_uv_or_pip(self):+ sec = self._section()+ self.assertNotRegex(sec, r"(?m)^\s*\S*env/bin/uv\b",+ "Manual install calls env/bin/uv — `uv venv --seed` does not put uv in the venv")+ self.assertNotRegex(sec, r"(?m)^\s*\S*env/bin/pip\b",+ "Manual install mixes plain pip into a uv-managed install")++ def test_pins_match_the_installer(self):+ sec = self._section()+ pin = re.search(r'LTX_PIN="([^"]+)"', _read("scripts/pinokio/ltx_checkout.sh")).group(1)+ self.assertIn(f"git checkout {pin}", sec)+ self.assertIn("'transformers>=5.0.0,<5.13.0'", sec)+ # The dependency pass (no --no-deps) must precede the --reinstall pass.+ dep = re.search(r"uv pip install --python env/bin/python \\\n\s*--build-constraints", sec)+ rei = re.search(r"--reinstall --no-deps \\\n\s*--build-constraints", sec)+ self.assertTrue(dep and rei and dep.start() < rei.start(),+ "vendored packages need a dependency pass, then the --reinstall --no-deps pass")++class AgentRulesAreSymlinks(unittest.TestCase):"""No agent reads a frozen copy of the manual."""diff --git a/test_review_416_jobs.py b/test_review_416_jobs.pynew file mode 100644index 0000000..77642eb--- /dev/null+++ b/test_review_416_jobs.py@@ -0,0 +1,518 @@+"""Contract gate for the 4.16.0 review round — job lifecycle core (JOB-*).++Findings: PM hub review-2026-09-24/findings_2-jobs.md. Each class below names+the finding it pins and drives the REAL function with the GPU-facing edges+(helper, pack preflight, engines, ffmpeg) replaced — no model, no subprocess,+no panel. Everything a test writes lands in a temp dir (conftest's sandbox or+its own mkdtemp).+"""+from __future__ import annotations++import json+import os+import shutil+import subprocess+import sys+import tempfile+import threading+import time+import unittest+from pathlib import Path+from unittest import mock++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT))+sys.path.insert(0, str(ROOT / "scripts"))++import mlx_ltx_panel as P # noqa: E402++NODE = shutil.which("node")+++class _Helper:+ """Stands in for the warm helper: records every spec, writes the output."""++ ready_info: dict = {}++ def __init__(self):+ self.sent: list[dict] = []++ def is_alive(self):+ return True++ def kill(self, *a, **k):+ pass++ def run(self, spec, *a, **k):+ self.sent.append(spec)+ out = (spec.get("params") or {}).get("output_path")+ if out:+ Path(out).write_bytes(b"x")+ return {"seed_used": 1, "elapsed_sec": 0.1}+++# ---------------------------------------------------------------------------+# JOB-02 — a 30 s a2v on an 8 GB Mac reached the engine instead of a refusal+# ---------------------------------------------------------------------------++class CompactMacsRefuseOversizedA2V(unittest.TestCase):+ """The Audio tab's own form (characters.js audioStudioGenerate), 30 s on a+ simulated 8 GB Mac, through make_job and the real a2v branch."""++ def _form(self, seconds: int) -> dict:+ frames = ((max(1, round(seconds * 24)) - 1 + 7) >> 3 << 3) + 1+ return {"mode": "a2v", "prompt": "a singer at a microphone",+ "audio": str(self.wav), "width": "768", "height": "416",+ "frames": str(frames), "seed": "-1", "quality": "high",+ "accel": "off", "enhance": "off", "audio_start_time": "0"}++ def setUp(self):+ self.tmp = Path(tempfile.mkdtemp(prefix="job02-"))+ self.wav = self.tmp / "song.wav"+ self.wav.write_bytes(b"RIFF0000WAVE")++ def _run(self, seconds: int, *, ram: float, tier: str, env: dict | None = None,+ helper: _Helper | None = None):+ helper = helper or _Helper()+ with mock.patch.dict(os.environ, env or {}):+ profile = P._select_generation_profile(ram, tier)+ job = P.make_job(self._form(seconds))+ job["started_ts"] = time.time()+ with mock.patch.object(P, "HELPER", helper), \+ mock.patch.object(P, "OUTPUT", self.tmp), \+ mock.patch.object(P, "SYSTEM_RAM_GB", ram), \+ mock.patch.object(P, "SYSTEM_TIER", tier), \+ mock.patch.object(P, "SYSTEM_CAPS", P.CAPABILITIES[tier]), \+ mock.patch.object(P, "GENERATION_PROFILE", profile), \+ mock.patch.object(P, "ltx_pack_preflight", lambda *a, **k: None), \+ mock.patch.object(P, "hq_surface_missing", lambda *a, **k: []), \+ mock.patch.object(P, "write_sidecar", lambda *a, **k: True):+ P.run_job_inner(job)+ return helper++ def test_thirty_seconds_on_8gb_is_refused_before_the_helper(self):+ helper = _Helper()+ with self.assertRaises(P.RenderRefused) as cm:+ self._run(30, ram=8.0, tier="base", helper=helper)+ self.assertEqual(cm.exception.reason, "hardware_tier")+ self.assertEqual(helper.sent, [])+ msg = str(cm.exception)+ self.assertIn("10 s", msg)+ self.assertIn("Start at", msg)+ self.assertEqual(P._analytics_refusal_reason(msg), "hardware_tier")++ def test_the_cap_is_the_compact_profiles_own_number(self):+ with mock.patch.object(P, "SYSTEM_TIER", "base"), \+ mock.patch.object(P, "GENERATION_PROFILE",+ P._select_generation_profile(8.0, "base")):+ self.assertEqual(P.a2v_max_frames(),+ P.GENERATION_PROFILE["auto_temporal_after_frames"])+ self.assertEqual(P.a2v_max_frames(),+ P.LTX_LENGTHS["10s"]["frames"])++ def test_a_ten_second_clip_on_8gb_still_renders_on_the_q4_lane(self):+ helper = self._run(10, ram=8.0, tier="base")+ self.assertEqual([s["action"] for s in helper.sent],+ ["generate_a2v_distilled"])++ def test_bigger_macs_are_not_capped(self):+ helper = self._run(30, ram=64.0, tier="standard")+ self.assertEqual(len(helper.sent), 1)+ self.assertEqual(helper.sent[0]["params"]["frames"], 721)++ def test_the_profile_escape_hatch_lifts_it(self):+ helper = self._run(30, ram=8.0, tier="base",+ env={"LTX_GENERATION_PROFILE": "full"})+ self.assertEqual(len(helper.sent), 1)++ def test_the_q4_a2v_constructor_streams_like_the_others(self):+ src = (ROOT / "mlx_warm_helper.py").read_text(encoding="utf-8")+ body = src.split("def get_a2v_distilled_pipe")[1].split("\ndef ")[0]+ self.assertIn("_construct_pipeline(\n A2VidDistilledPipeline", body)+ self.assertIn("low_ram_streaming=_stream_for(loras)", body)++ @unittest.skipUnless(NODE, "node not on PATH")+ def test_the_audio_tab_warns_with_the_same_number(self):+ from extract_panel_js import extract_function, panel_source # noqa: PLC0415+ src = panel_source()+ js = """+var A2V_AREA_KNEE = 0.45e6, A2V_KNEE_FRAMES = 450, BOOT;+const els = {};+function el(id, v) { return els[id] = {id, value: v, style: {}, innerHTML: '', textContent: ''}; }+const document = { getElementById: id => els[id] || null };+el('audioStudioDuration', '30'); el('audioStudioDurationVal');+el('audioStudioDurationWarn'); el('audioStudioWidth', '768'); el('audioStudioHeight', '416');+""" + "\n".join(extract_function(n, src) for n in (+ "_a2vFramesForSeconds", "audioStudioDurationChanged")) + """+const out = {};+for (const [cap, sec] of [[241, 30], [241, 10], [0, 30]]) {+ BOOT = {a2v_max_frames: cap};+ audioStudioDurationChanged(String(sec));+ out[cap + '_' + sec] = els.audioStudioDurationWarn.style.display === 'none'+ ? '' : els.audioStudioDurationWarn.innerHTML;+}+console.log(JSON.stringify(out));+"""+ r = subprocess.run([NODE, "-e", js], capture_output=True, text=True, timeout=30)+ self.assertEqual(r.returncode, 0, r.stderr)+ out = json.loads(r.stdout)+ self.assertIn("10 s", out["241_30"])+ self.assertEqual(out["241_10"], "")+ self.assertNotIn("refused", out["0_30"])+++# ---------------------------------------------------------------------------+# JOB-03 — an older queue snapshot could overwrite a newer one on disk+# ---------------------------------------------------------------------------++class QueueFileIsNeverRolledBack(unittest.TestCase):+ """Force the exact interleaving: writer 1 snapshots, is held at the write,+ writer 2 snapshots AND writes, then writer 1 is released."""++ def setUp(self):+ self.tmp = Path(tempfile.mkdtemp(prefix="job03-"))+ self.saved = {k: P.STATE[k] for k in ("queue", "current", "history", "paused")}++ def tearDown(self):+ with P.LOCK:+ P.STATE.update(self.saved)++ def _race(self, first: list, second: list) -> list:+ real_write = P.atomic_write_text+ second_done = threading.Event()+ calls = {"n": 0}++ def write(path, text, *a, **k):+ calls["n"] += 1+ if calls["n"] == 1: # the older writer, held here+ second_done.wait(0.5)+ real_write(path, text, *a, **k)++ def older():+ P.persist_queue()++ qfile = self.tmp / "panel_queue.json"+ with mock.patch.object(P, "QUEUE_FILE", qfile), \+ mock.patch.object(P, "atomic_write_text", write):+ with P.LOCK:+ P.STATE.update(queue=list(first), current=None, history=[], paused=False)+ t = threading.Thread(target=older)+ t.start()+ while calls["n"] == 0: # older has snapshotted+ time.sleep(0.005)+ with P.LOCK:+ P.STATE["queue"] = list(second)+ P.persist_queue()+ second_done.set()+ t.join(5)+ return [j["id"] for j in json.loads(qfile.read_text())["queue"]]++ def test_an_acknowledged_add_survives_the_race(self):+ a, b = {"id": "A", "params": {}}, {"id": "B", "params": {}}+ self.assertEqual(self._race([a], [a, b]), ["A", "B"])++ def test_a_removed_job_does_not_come_back(self):+ a, b = {"id": "A", "params": {}}, {"id": "B", "params": {}}+ self.assertEqual(self._race([a, b], [a]), ["A"])+++# ---------------------------------------------------------------------------+# JOB-07 — a full disk at the sidecar write was reported as a clean success+# ---------------------------------------------------------------------------++class ASidecarTheDiskRefusedIsNotASilentSuccess(unittest.TestCase):++ def setUp(self):+ self.tmp = Path(tempfile.mkdtemp(prefix="job07-"))+ self.wav = self.tmp / "song.wav"+ self.wav.write_bytes(b"RIFF0000WAVE")+ self.saved_history = P.STATE["history"]++ def tearDown(self):+ with P.LOCK:+ P.STATE["history"] = self.saved_history+ P._JOB_CTX.job = None++ def test_enospc_lands_on_the_job_and_a_retry_restores_it_without_a_render(self):+ import errno+ real_write = P.atomic_write_text++ def full_disk(path, text, *a, **k):+ if str(path).endswith(".json"):+ raise OSError(errno.ENOSPC, "No space left on device")+ return real_write(path, text, *a, **k)++ helper = _Helper()+ job = P.make_job({"mode": "a2v", "prompt": "a singer", "audio": str(self.wav),+ "width": "512", "height": "288", "frames": "49"})+ job["started_ts"] = time.time()+ P._JOB_CTX.job = job # what worker_loop does+ with mock.patch.object(P, "HELPER", helper), \+ mock.patch.object(P, "OUTPUT", self.tmp), \+ mock.patch.object(P, "ltx_pack_preflight", lambda *a, **k: None), \+ mock.patch.object(P, "hq_surface_missing", lambda *a, **k: []), \+ mock.patch.object(P, "atomic_write_text", full_disk):+ P.run_job_inner(job)+ video = Path(job["output_path"])+ sidecar = video.with_suffix(video.suffix + ".json")+ self.assertTrue(video.exists(), "the finished video is kept")+ self.assertFalse(sidecar.exists())+ self.assertIn("could not be written", job.get("warning", ""))+ self.assertIn("No space left", job["warning"])+ self.assertEqual(len(job["sidecar_pending"]), 1)+ json.dumps(job) # still persistable++ # Space is back: the record is written from the kept payload.+ with P.LOCK:+ P.STATE["history"] = [job]+ self.assertEqual(P.retry_pending_sidecars(), 1)+ self.assertTrue(sidecar.exists())+ self.assertEqual(json.loads(sidecar.read_text())["params"]["mode"], "a2v")+ self.assertNotIn("sidecar_pending", job)+ self.assertNotIn("warning", job)+ self.assertEqual(len(helper.sent), 1, "no second render")++ def test_the_writer_reports_its_own_outcome(self):+ ok = P.write_sidecar(self.tmp / "ok.mp4.json", {"a": 1})+ self.assertIs(ok, True)+ with mock.patch.object(P, "atomic_write_text",+ mock.Mock(side_effect=OSError(28, "No space left"))):+ self.assertIs(P.write_sidecar(self.tmp / "x.mp4.json", {"a": 1}), False)++ def test_the_worker_retries_before_each_render(self):+ src = (ROOT / "mlx_ltx_panel.py").read_text(encoding="utf-8")+ body = src.split("def worker_loop")[1].split("\ndef ")[0]+ self.assertLess(body.index("retry_pending_sidecars()"), body.index("run_job_inner(job)"))+++# ---------------------------------------------------------------------------+# JOB-01 — the upscaled export overwrote an existing video and its sidecar+# ---------------------------------------------------------------------------++def _fake_ffmpeg(cmd, *a, **k):+ """Encoder stand-in: the output (last argument) gets the input's bytes."""+ src = Path(cmd[cmd.index("-i") + 1])+ Path(cmd[-1]).write_bytes(src.read_bytes() + b"+enc")+ return "", ""+++class ExportsNeverReplaceAnotherClip(unittest.TestCase):++ def setUp(self):+ self.tmp = Path(tempfile.mkdtemp(prefix="job01-"))++ def test_scene_fit_720p_does_not_overwrite_scene_720p(self):+ victim = self.tmp / "scene_720p.mp4"+ victim.write_bytes(b"THE EARLIER RENDER")+ victim_json = self.tmp / "scene_720p.mp4.json"+ victim_json.write_text('{"output": "earlier"}')+ helper = _Helper()+ job = P.make_job({"mode": "t2v", "prompt": "a lighthouse at dusk",+ "preset_label": "scene", "quality": "balanced",+ "width": "1024", "height": "576", "frames": "49",+ "upscale": "fit_720p", "upscale_method": "lanczos"})+ job["started_ts"] = time.time()+ with mock.patch.object(P, "HELPER", helper), \+ mock.patch.object(P, "OUTPUT", self.tmp), \+ mock.patch.object(P, "ltx_pack_preflight", lambda *a, **k: None), \+ mock.patch.object(P, "run_ffmpeg_tracked", _fake_ffmpeg), \+ mock.patch.object(P, "set_hidden", lambda *a, **k: None):+ P.run_job_inner(job)+ self.assertEqual(victim.read_bytes(), b"THE EARLIER RENDER")+ self.assertEqual(victim_json.read_text(), '{"output": "earlier"}')+ out = Path(job["output_path"])+ self.assertNotEqual(out, victim)+ self.assertTrue(out.exists())+ side = json.loads(out.with_suffix(".mp4.json").read_text())+ self.assertEqual(side["output"], str(out))+++# ---------------------------------------------------------------------------+# JOB-04 — Enhance Prompt started a second GPU consumer beside H3 / music+# ---------------------------------------------------------------------------++class _Req:+ def __init__(self, prompt):+ self.form = {"prompt": [prompt], "mode": ["t2v"]}+ self.replies = []++ def _read_form_body(self):+ return b"", self.form++ def _json(self, body, status=200):+ self.replies.append((status, body))+++class EnhanceWaitsForTheGpu(unittest.TestCase):++ def setUp(self):+ from panel import routes_queue # noqa: PLC0415+ self.rq = routes_queue+ # Whichever panel module the routes are wired to in this process (a+ # suite-mate may have booted a second copy) is the one to patch.+ self.PM = routes_queue.P or P++ def test_busy_gpu_answers_busy_and_spawns_nothing(self):+ helper = _Helper()+ busy = threading.Lock()+ busy.acquire() # an H3 / music job holds the gate+ req = _Req("a lighthouse")+ with mock.patch.object(self.PM, "HELPER", helper), \+ mock.patch.object(self.PM, "_GPU_LOCK", mock.Mock(wraps=busy)) as gate:+ gate.acquire.side_effect = lambda *a, **k: busy.acquire(blocking=False)+ self.rq.post_prompt_enhance(req, "/prompt/enhance", {}, "")+ self.assertEqual(helper.sent, [])+ self.assertEqual(req.replies[0][0], 409)+ self.assertIn("GPU", req.replies[0][1]["error"])++ def test_free_gpu_enhances_and_releases_the_gate(self):+ class _Enh(_Helper):+ def run(self, spec, *a, **k):+ self.sent.append(spec)+ return {"enhanced": "a lighthouse at dusk, waves", "elapsed_sec": 0.1}+ helper = _Enh()+ gate = threading.Lock()+ req = _Req("a lighthouse")+ with mock.patch.object(self.PM, "HELPER", helper), \+ mock.patch.object(self.PM, "_GPU_LOCK", gate):+ self.rq.post_prompt_enhance(req, "/prompt/enhance", {}, "")+ self.assertFalse(gate.locked(), "released after the request")+ self.assertEqual(len(helper.sent), 1)+ self.assertEqual(req.replies[0][0], 200)+ self.assertTrue(req.replies[0][1]["ok"])+++# ---------------------------------------------------------------------------+# JOB-06 — Stop before the image process registered was ignored+# ---------------------------------------------------------------------------++class StopReachesAnImageJobInPreflight(unittest.TestCase):++ def setUp(self):+ self.job = P.make_job({"mode": "image", "prompt": "a brass lamp on a desk",+ "n": "1"})+ P._JOB_CTX.job = self.job # what worker_loop does+ self.calls = []++ def tearDown(self):+ P._JOB_CTX.job = None++ def _generate(self, **kw):+ self.calls.append(kw)+ out = Path(kw["output_dir"]) / "c0.png"+ out.write_bytes(b"png")+ return [{"path": str(out), "seed": 1}]++ def _run(self, preflight):+ with mock.patch.object(P, "_preflight_image_job", preflight), \+ mock.patch.object(P, "_sync_hf_token_to_env", lambda: None), \+ mock.patch.object(P, "_video_render_active", lambda: False), \+ mock.patch.object(P.agent_image_engine, "generate", self._generate):+ P.run_image_job_inner(self.job)++ def test_stop_pressed_during_preflight_starts_no_engine(self):+ def preflight(*a, **k):+ self.job["cancel_requested"] = True # Stop, while memory settles+ with self.assertRaises(P.JobCancelled):+ self._run(preflight)+ self.assertEqual(self.calls, [])+ self.assertIsNone(self.job.get("output_path"))++ def test_stop_that_lands_as_the_engine_exits_is_not_filed_done(self):+ def generate(**kw):+ r = self._generate(**kw)+ self.job["cancel_requested"] = True+ return r+ with mock.patch.object(P, "_preflight_image_job", lambda *a, **k: None), \+ mock.patch.object(P, "_sync_hf_token_to_env", lambda: None), \+ mock.patch.object(P, "_video_render_active", lambda: False), \+ mock.patch.object(P.agent_image_engine, "generate", generate):+ with self.assertRaises(P.JobCancelled):+ P.run_image_job_inner(self.job)+ self.assertIsNone(self.job.get("output_path"))++ def test_stop_between_popen_and_registration_kills_the_new_group(self):+ ie = P.agent_image_engine+ # The panel installs the hook at import (a suite-mate that boots a+ # second panel copy re-installs its own, hence by name).+ self.assertEqual(getattr(ie._CANCEL_CHECK, "__name__", ""), "_image_job_cancelled")+ self.job["cancel_requested"] = True+ proc = subprocess.Popen(["sleep", "30"], start_new_session=True)+ try:+ with mock.patch.object(ie, "_CANCEL_CHECK", P._image_job_cancelled), \+ self.assertRaises(ie.ImageJobCancelled):+ ie._register_active_proc(proc)+ self.assertIsNotNone(proc.poll(), "the process group was killed")+ self.assertNotIn(proc, ie._ACTIVE_PROCS)+ finally:+ if proc.poll() is None:+ proc.kill()+ proc.wait()++ def test_registration_outside_a_cancelled_job_is_untouched(self):+ ie = P.agent_image_engine+ P._JOB_CTX.job = None # inline /image/generate+ proc = subprocess.Popen(["sleep", "30"], start_new_session=True)+ try:+ with mock.patch.object(ie, "_CANCEL_CHECK", P._image_job_cancelled):+ ie._register_active_proc(proc)+ self.assertIsNone(proc.poll())+ self.assertIn(proc, ie._ACTIVE_PROCS)+ finally:+ ie._unregister_active_proc(proc)+ proc.kill()+ proc.wait()+++# ---------------------------------------------------------------------------+# JOB-08 — Stop waited out the helper's startup handshake+# ---------------------------------------------------------------------------++class StopInterruptsAHelperThatIsStillStarting(unittest.TestCase):++ def test_kill_lands_while_the_handshake_is_waiting(self):+ import signal+ tmp = Path(tempfile.mkdtemp(prefix="job08-"))+ script = tmp / "silent_helper.py"+ script.write_text("import time\ntime.sleep(60)\n") # never says ready+ h = P.WarmHelper()+ errors: list = []++ def start():+ try:+ with h.run_lock:+ h._ensure()+ except Exception as exc: # noqa: BLE001+ errors.append(exc)++ with mock.patch.object(P, "HELPER_PYTHON", Path(sys.executable)), \+ mock.patch.object(P, "HELPER_SCRIPT", script), \+ mock.patch.object(P, "MLX", tmp), \+ mock.patch.object(P, "engine_env_fault", lambda: None):+ starter = threading.Thread(target=start, daemon=True)+ starter.start()+ deadline = time.time() + 10+ while h.proc is None and time.time() < deadline:+ time.sleep(0.01)+ proc = h.proc+ self.assertIsNotNone(proc)+ try:+ killer = threading.Thread(target=h.kill, daemon=True)+ t0 = time.time()+ killer.start()+ killer.join(8)+ self.assertFalse(killer.is_alive(), "kill() waited on the handshake")+ self.assertLess(time.time() - t0, 8)+ self.assertIsNotNone(proc.poll(), "the starting helper was signalled")+ starter.join(5)+ self.assertFalse(starter.is_alive())+ self.assertTrue(errors and isinstance(errors[0], RuntimeError))+ self.assertIn("stopped while it was starting", str(errors[0]))+ finally:+ if proc.poll() is None:+ os.killpg(proc.pid, signal.SIGKILL)+ proc.wait()+++if __name__ == "__main__":+ unittest.main()diff --git a/test_review_416_ltx.py b/test_review_416_ltx.pynew file mode 100644index 0000000..e35f9c8--- /dev/null+++ b/test_review_416_ltx.py@@ -0,0 +1,774 @@+"""Contract gate for the 4.16.0 review round — the LTX lanes (LTX-*).++Findings: PM hub review-2026-09-24/findings_3-ltx.md. The render path is+driven for real with the helper replaced by a recorder and the engine-facing+edges stubbed; the One Shot joins run the real ffmpeg on tiny synthetic clips.+Nothing loads a model or touches the GPU; everything lands in a temp dir.+"""+from __future__ import annotations++import json+import os+import shutil+import subprocess+import sys+import tempfile+import threading+import time+import unittest+from pathlib import Path+from unittest import mock++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT))+sys.path.insert(0, str(ROOT / "scripts"))++import mlx_ltx_panel as P # noqa: E402++NODE = shutil.which("node")+++class _Helper:+ """Stands in for the warm helper: records every spec, writes the output."""++ ready_info: dict = {}++ def __init__(self):+ self.sent: list[dict] = []++ def is_alive(self):+ return True++ def kill(self, *a, **k):+ pass++ def run(self, spec, *a, **k):+ self.sent.append(spec)+ out = (spec.get("params") or {}).get("output_path")+ if out:+ Path(out).write_bytes(b"x")+ return {"seed_used": 1, "elapsed_sec": 0.1}+++def _tiny_clip(path: Path, colour: str = "red", secs: float = 0.5) -> None:+ subprocess.run([str(P.FFMPEG), "-loglevel", "error", "-y", "-f", "lavfi", "-i",+ f"color=c={colour}:s=64x64:d={secs}:r=24", "-f", "lavfi", "-i",+ "anullsrc=r=48000:cl=stereo", "-t", str(secs), "-c:v", "libx264", "-pix_fmt",+ "yuv420p", "-c:a", "aac", "-shortest", str(path)], check=True)+++class _TakeHarness(unittest.TestCase):+ """An LTX One Shot whose parts are tiny real clips with real-shaped+ (nested) LTX sidecars, as run_job_inner writes them."""++ def setUp(self):+ self.tmp = Path(tempfile.mkdtemp(prefix="ltx-take-"))+ self.out_dir = self.tmp / "out"+ self.out_dir.mkdir()+ self.parts: list[dict] = []+ self.clip_secs = 0.5+ self.patches = [+ mock.patch.object(P, "OUTPUT", self.out_dir),+ mock.patch.object(P, "STATE_DIR", self.tmp / "state"),+ mock.patch.object(P, "set_hidden", lambda *a, **k: None),+ mock.patch.object(P, "take_drift",+ lambda *a, **k: {"ok": True, "delta": 0.0, "drifted": False}),+ mock.patch.object(P, "run_job_inner", self._fake_part),+ ]+ for pt in self.patches:+ pt.start()++ def tearDown(self):+ for pt in reversed(self.patches):+ pt.stop()++ def _fake_part(self, child):+ cp = child["params"]+ self.parts.append(dict(cp))+ out = self.out_dir / f"{child['id']}.mp4"+ _tiny_clip(out, "red" if len(self.parts) % 2 else "blue", self.clip_secs)+ # What run_job_inner really writes: the part's intent under `params`.+ (self.out_dir / f"{child['id']}.mp4.json").write_text(json.dumps({+ "output": str(out), "raw_output": str(out), "native_output": str(out),+ "params": {**cp}, "command": "helper", "fps": 24, "queue_id": child["id"],+ }))+ child["output_path"] = str(out)+++# ---------------------------------------------------------------------------+# LTX-01 — Stop could not interrupt the One Shot final join+# ---------------------------------------------------------------------------++class StopEndsTheOneShotJoin(_TakeHarness):++ def test_stop_during_the_join_kills_it_and_nothing_is_published(self):+ real_ff = str(P.FFMPEG)+ slow = self.tmp / "ffmpeg"+ # The join (and only the join) takes "forever".+ slow.write_text("#!/bin/sh\ncase \"$*\" in *concat=n=*) exec sleep 30;; esac\n"+ f"exec '{real_ff}' \"$@\"\n")+ slow.chmod(0o755)+ job = P.make_job({"mode": "t2v", "engine": "ltx", "prompt": "a hen skates",+ "take_seconds": "30"})+ self.assertEqual(len(job["params"]["take"]["parts"]), 3)+ errors: list = []++ def run():+ try:+ P.run_take_job_inner(job)+ except Exception as exc: # noqa: BLE001+ errors.append(exc)++ saved_current = P.STATE["current"]+ with mock.patch.object(P, "FFMPEG", slow), \+ mock.patch.object(P, "HELPER", _Helper()):+ with P.LOCK:+ P.STATE["current"] = job+ try:+ t = threading.Thread(target=run, daemon=True)+ t.start()+ deadline = time.time() + 30+ # Only the join is left once the runner says so; then wait+ # for its process group to be registered where Stop looks.+ while not (any("[take] joining" in str(l) for l in P.STATE.get("log", []))+ and P.STATE.get("mux_pgid")):+ self.assertLess(time.time(), deadline, "join never started")+ time.sleep(0.02)+ t0 = time.time()+ P.stop_current_job()+ t.join(10)+ self.assertFalse(t.is_alive(), "the join ran on after Stop")+ self.assertLess(time.time() - t0, 10)+ finally:+ with P.LOCK:+ P.STATE["current"] = saved_current+ self.assertTrue(errors)+ self.assertIsInstance(errors[0], P.JobCancelled)+ self.assertIsNone(job.get("output_path"))+ self.assertEqual(list(self.out_dir.glob("*_take30s.mp4.json")), [])++ def test_a_stop_as_the_join_finishes_is_not_published(self):+ job = P.make_job({"mode": "t2v", "engine": "ltx", "prompt": "a hen skates",+ "take_seconds": "30"})+ real_join = P._join_take_parts++ def join(*a, **k):+ real_join(*a, **k)+ job["cancel_requested"] = True # Stop lands as the encode ends+ with mock.patch.object(P, "_join_take_parts", join):+ with self.assertRaises(P.JobCancelled):+ P.run_take_job_inner(job)+ self.assertIsNone(job.get("output_path"))+ self.assertEqual(list(self.out_dir.glob("*_take30s.mp4.json")), [])+++# ---------------------------------------------------------------------------+# LTX-02 — the One Shot sidecar carried the last part's parameters+# ---------------------------------------------------------------------------++class TheTakesSidecarIsTheTakes(_TakeHarness):++ def _take(self, **form):+ job = P.make_job({"mode": "t2v", "engine": "ltx", "prompt": "a hen skates on a pond",+ "take_seconds": "30", "preset_label": "ride",+ "beats": json.dumps(["b1", "b2", "b3", "b4", "b5", "b6"]), **form})+ P.run_take_job_inner(job)+ final = Path(job["output_path"])+ return job, final, json.loads(final.with_suffix(final.suffix + ".json").read_text())++ def test_params_hold_the_parent_intent_and_outputs_name_the_take(self):+ job, final, side = self._take()+ q = side["params"]+ self.assertEqual(q["take"]["seconds"], 30)+ self.assertTrue(q["take"]["beats"][0].startswith("b1"))+ self.assertTrue(q["take"]["beats"][1].startswith("b2"))+ self.assertEqual(q["mode"], "t2v")+ self.assertEqual(q["prompt"], "a hen skates on a pond")+ self.assertIsNone(q["image"], "never a handoff frame")+ self.assertEqual(q["frames"], job["params"]["frames"])+ for k in ("output", "raw_output", "native_output"):+ self.assertEqual(side[k], str(final), k)++ def test_a_speech_handoff_take_still_has_params(self):+ # The last part is a remux in the state dir with no sidecar of its own.+ self.clip_secs = 2.0+ with mock.patch.object(P, "take_handoff_points", lambda *a, **k: (1.0, 1.5)), \+ mock.patch.object(P, "take_lipsync_score", lambda *a, **k: None):+ job, final, side = self._take(take_handoff="speech")+ self.assertEqual(side["take"]["handoff"], "speech")+ self.assertTrue(side["take"]["parts"][-1].endswith("_lead.mp4"))+ self.assertEqual(side["params"]["take"]["seconds"], 30)+ self.assertEqual(side["params"]["prompt"], "a hen skates on a pond")++ @unittest.skipUnless(NODE, "node not on PATH")+ def test_load_params_reopens_new_and_legacy_takes_as_one_shot(self):+ from extract_panel_js import extract_function, panel_source # noqa: PLC0415+ src = panel_source()+ _, _, new_side = self._take()+ legacy = {"take": {"seconds": 30, "beats": ["b1"], "engine": "ltx"},+ "prompt": "a hen skates on a pond", "engine": "ltx", "mode": "t2v",+ # the last part's params (malformed legacy shape)+ "params": {"mode": "i2v", "prompt": "b5 b6", "take": None,+ "image": "/state/take/x/part2_last.png"}}+ speech_legacy = {"take": {"seconds": 30, "beats": ["b1"], "engine": "ltx"},+ "prompt": "a hen skates on a pond", "engine": "ltx"}+ js = """+var activePath = '/x.mp4', opened = [], modes = [];+function _parseIdeoCaption() { return null; }+async function charactersLoadParams() { opened.push('characters'); }+function oneshotOpenFromParams(p) { opened.push(p); }+function setMode(m) { modes.push(m); }+""" + extract_function("loadParams", src) + """+const cases = %s;+(async () => {+ const out = [];+ for (const c of cases) {+ opened = []; modes = [];+ globalThis.fetch = async () => ({ok: true, json: async () => c});+ let err = null;+ try { await loadParams(); } catch (e) { err = String(e); }+ const o = opened[0] || {};+ out.push({err, seconds: o.take && o.take.seconds, prompt: o.prompt,+ image: o.image || '', modes});+ }+ console.log(JSON.stringify(out));+})();+""" % json.dumps([new_side, legacy, speech_legacy])+ r = subprocess.run([NODE, "-e", js], capture_output=True, text=True, timeout=30)+ self.assertEqual(r.returncode, 0, r.stderr)+ for got in json.loads(r.stdout):+ self.assertIsNone(got["err"])+ self.assertEqual(got["seconds"], 30)+ self.assertEqual(got["prompt"], "a hen skates on a pond")+ self.assertEqual(got["image"], "")+ self.assertEqual(got["modes"], [], "never the single-clip form")+++# ---------------------------------------------------------------------------+# LTX-03 — Extend, FFLF and Q4 Audio→Video dropped the selected LoRAs+# ---------------------------------------------------------------------------++STYLE = [{"path": "/loras/crisp.safetensors", "strength": 0.8}]+++class EveryLaneSendsTheLoraStack(unittest.TestCase):+ """The real dispatch branches, the helper intercepted: the stack the job+ carries is the stack the helper is asked to attach."""++ def setUp(self):+ self.tmp = Path(tempfile.mkdtemp(prefix="ltx03-"))+ self.clip = self.tmp / "src.mp4"+ _tiny_clip(self.clip)+ self.png = self.tmp / "a.png"+ subprocess.run([str(P.FFMPEG), "-loglevel", "error", "-y", "-f", "lavfi", "-i",+ "color=c=green:s=64x64:d=1", "-frames:v", "1", "-update", "1",+ str(self.png)], check=True)+ self.wav = self.tmp / "song.wav"+ self.wav.write_bytes(b"RIFF0000WAVE")++ def _dispatch(self, form: dict, *, q8: bool = True) -> dict:+ helper = _Helper()+ job = P.make_job(form)+ job["params"]["loras"] = [dict(l) for l in STYLE]+ job["started_ts"] = time.time()+ caps = dict(P.CAPABILITIES["pro"], allows_q8=q8)+ with mock.patch.object(P, "HELPER", helper), \+ mock.patch.object(P, "OUTPUT", self.tmp), \+ mock.patch.object(P, "SYSTEM_CAPS", caps), \+ mock.patch.object(P, "ltx_pack_preflight", lambda *a, **k: None), \+ mock.patch.object(P, "hq_surface_missing", lambda *a, **k: []), \+ mock.patch.object(P, "_native_render_for", lambda x: x), \+ mock.patch.object(P, "run_ffmpeg_tracked", lambda *a, **k: ("", "")), \+ mock.patch.object(P, "write_sidecar", lambda *a, **k: True):+ try:+ P.run_job_inner(job)+ except Exception: # noqa: BLE001+ # Anything after the helper call (muxing a fake clip) is not+ # this test's business; the request is.+ pass+ self.assertTrue(helper.sent, "the lane never reached the helper")+ return helper.sent[0]++ def test_extend(self):+ spec = self._dispatch({"mode": "extend", "prompt": "the hen keeps skating",+ "video_path": str(self.clip), "extend_frames": "2"})+ self.assertEqual(spec["action"], "extend")+ self.assertEqual(spec["params"]["loras"], STYLE)++ def test_fflf(self):+ spec = self._dispatch({"mode": "keyframe", "prompt": "the hen crosses the pond",+ "start_image": str(self.png), "end_image": str(self.png),+ "width": "512", "height": "288", "frames": "49"})+ self.assertEqual(spec["action"], "generate_keyframe")+ self.assertEqual(spec["params"]["loras"], STYLE)++ def test_a2v_on_both_lanes(self):+ form = {"mode": "a2v", "prompt": "a singer", "audio": str(self.wav),+ "width": "512", "height": "288", "frames": "49"}+ for q8, action in ((True, "generate_a2v"), (False, "generate_a2v_distilled")):+ with self.subTest(q8=q8):+ spec = self._dispatch(form, q8=q8)+ self.assertEqual(spec["action"], action)+ self.assertEqual(spec["params"]["loras"], STYLE)+++class TheHelperAttachesThem(unittest.TestCase):+ """get_kf_pipe / get_a2v_distilled_pipe executed from the helper source+ (the helper is a script — never imported) against stand-in pipelines."""++ def _ns(self, fake_modules: dict):+ import ast+ import types+ src = (ROOT / "mlx_warm_helper.py").read_text(encoding="utf-8")+ names = {"get_kf_pipe", "get_a2v_distilled_pipe", "_lora_fingerprint",+ "_lora_fingerprint_base", "_stream_for", "_construct_pipeline",+ "_filter_unsupported_kwargs", "_attach_loras"}+ tree = ast.parse(src)+ picked = [n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name in names]+ self.assertEqual({n.name for n in picked}, names)+ ns = {"os": os, "threading": threading, "emit": lambda *a, **k: None,+ "_pipe_lock": threading.RLock(), "release_pipelines": lambda **k: None,+ "_install_lora_fusion_patches": lambda: None,+ "_install_video_decoder_patch": lambda: None,+ "_install_a2v_frame_rate_patch": lambda: None,+ "_resolve_lora_path": lambda path: path,+ "GEMMA_PATH": "/g", "LOW_MEMORY": True, "LOW_RAM_STREAM": True,+ "_kf_pipe": None, "_kf_model_dir": None, "_kf_weight_key": None,+ "_kf_lora_key": None, "_a2v_distilled_pipe": None,+ "_a2v_distilled_model_dir": None, "_a2v_distilled_lora_key": None}+ exec(compile(ast.Module(body=picked, type_ignores=[]), "mlx_warm_helper.py", "exec"), ns)+ for name, attrs in fake_modules.items():+ mod = types.ModuleType(name)+ mod.__dict__.update(attrs)+ sys.modules[name] = mod+ self.addCleanup(sys.modules.pop, name, None)+ return ns++ def test_fflf_attaches_and_rebuilds_on_a_new_set(self):+ built = []++ class KeyframeInterpolationPipeline:+ def __init__(self, **kw):+ built.append(self)+ ns = self._ns({"ltx_pipelines_mlx": {},+ "ltx_pipelines_mlx.keyframe_interpolation":+ {"KeyframeInterpolationPipeline": KeyframeInterpolationPipeline}})+ a = ns["get_kf_pipe"]("/q8", loras=STYLE)+ self.assertEqual(a._pending_loras, [("/loras/crisp.safetensors", 0.8)])+ self.assertIs(ns["get_kf_pipe"]("/q8", loras=STYLE), a)+ b = ns["get_kf_pipe"]("/q8", loras=[])+ self.assertIsNot(b, a)+ self.assertFalse(getattr(b, "_pending_loras", None))++ def test_q4_a2v_attaches_and_does_not_stream_with_adapters(self):+ built = []++ class A2VidDistilledPipeline:+ def __init__(self, model_dir=None, gemma_model_id=None, low_memory=None,+ low_ram_streaming=False):+ self.stream = low_ram_streaming+ built.append(self)+ ns = self._ns({"a2vid_distilled": {"A2VidDistilledPipeline": A2VidDistilledPipeline},+ "ltx_core_mlx": {}, "ltx_core_mlx.utils": {},+ "ltx_core_mlx.utils.memory": {"aggressive_cleanup": lambda: None}})+ plain = ns["get_a2v_distilled_pipe"]("/q4")+ self.assertTrue(plain.stream)+ styled = ns["get_a2v_distilled_pipe"]("/q4", loras=STYLE)+ self.assertIsNot(styled, plain)+ self.assertFalse(styled.stream, "adapters keep the unfused branch")+ self.assertEqual(styled._pending_loras, [("/loras/crisp.safetensors", 0.8)])+++# ---------------------------------------------------------------------------+# LTX-04 — Load Params turned an Audio → Video clip into a Text render+# ---------------------------------------------------------------------------++A2V_DOM = r"""+var BOOT = {a2v_max_frames: 0}, A2V_AREA_KNEE = 0.45e6, A2V_KNEE_FRAMES = 450;+var activePath = '/x.mp4', calls = [], posted = null, _activeLoras = [];+var AUDIO_STUDIO = {busy: false, audioPath: null, audioName: null, audioDuration: null};+window = globalThis; window.PHOSPHENE_CAP_TIER = 'q8';+const els = {};+function el(id, v) { return els[id] = {id, value: v === undefined ? '' : v, style: {}, dataset: {},+ innerHTML: '', textContent: '', disabled: false, open: false}; }+['audioStudioPrompt', 'audioStudioStatus', 'audioStudioGenBtn', 'audioStudioDurationVal',+ 'audioStudioDurationWarn', 'audioConditioningScaleVal', 'audioConditioningScaleHint',+ 'mvOneShotDetails', 'a2v_image'].forEach(i => el(i));+el('audioStudioWidth', '1024'); el('audioStudioHeight', '576'); el('audioStudioSeed', '-1');+el('audioStudioStart', '0'); el('audioStudioDuration', '7'); el('audioConditioningScale', '3.0');+const document = { getElementById: id => els[id] || null };+function audioModeSet(m) { calls.push('audioMode:' + m); }+function workflowSwitch(w) { calls.push('workflow:' + w); }+function audioStudioRenderSlots() {}+function pickerSetImage(k, v) { if (k === 'a2v_image') els.a2v_image.value = v; calls.push('picker:' + k + '=' + v); }+function _restoreLoraPicker(l) { calls.push('loras:' + l.length); _activeLoras = l; }+function setMode(m) { calls.push('setMode:' + m); }+function _parseIdeoCaption() { return null; }+function phosToast() {}+"""++[email protected](NODE, "node not on PATH")+class AnA2VClipReopensAsAudioToVideo(unittest.TestCase):++ def _run(self, params: dict) -> dict:+ from extract_panel_js import extract_function, panel_source # noqa: PLC0415+ src = panel_source()+ fns = ("_a2vFramesForSeconds", "audioStudioDurationChanged", "a2vLaneAudioScale",+ "audioConditioningScaleChanged", "audioConditioningScaleReset",+ "a2vLoadParams", "loadParams", "audioStudioGenerate")+ js = A2V_DOM + "\n".join(extract_function(n, src) for n in fns) + """+const sidecar = %s;+(async () => {+ globalThis.fetch = async () => ({ok: true, json: async () => sidecar});+ await loadParams();+ globalThis.fetch = async (url, opts) => { posted = Object.fromEntries(opts.body); return {ok: true}; };+ await audioStudioGenerate();+ console.log(JSON.stringify({calls, posted, open: els.mvOneShotDetails.open}));+})();+""" % json.dumps({"output": "/x.mp4", "params": params})+ r = subprocess.run([NODE, "-e", js], capture_output=True, text=True, timeout=30)+ self.assertEqual(r.returncode, 0, r.stderr)+ return json.loads(r.stdout)++ def _params(self, **over):+ base = {"mode": "a2v", "prompt": "a singer at a microphone", "audio": "/songs/take.wav",+ "image": "/uploads/singer.png", "width": 832, "height": 480, "frames": 241,+ "seed": "-1", "seed_used": 4242, "audio_start_time": 30.0,+ "audio_conditioning_scale": "4", "loras": [{"path": "/l.safetensors", "strength": 1}]}+ base.update(over)+ return base++ def test_the_round_trip_keeps_mode_track_and_conditioning(self):+ out = self._run(self._params())+ self.assertNotIn("setMode:t2v", out["calls"])+ self.assertIn("workflow:audio", out["calls"])+ self.assertIn("loras:1", out["calls"])+ self.assertTrue(out["open"])+ got = out["posted"]+ self.assertEqual(got["mode"], "a2v")+ self.assertEqual(got["audio"], "/songs/take.wav")+ self.assertEqual(got["image"], "/uploads/singer.png")+ self.assertEqual((got["width"], got["height"], got["frames"]), ("832", "480", "241"))+ self.assertEqual(got["seed"], "4242")+ self.assertEqual(got["audio_start_time"], "30")+ self.assertEqual(got["audio_conditioning_scale"], "4")++ def test_auto_stays_auto(self):+ out = self._run(self._params(audio_conditioning_scale=""))+ self.assertNotIn("audio_conditioning_scale", out["posted"])++ def test_the_pre_4152_float_default_reopens_as_auto(self):+ # Old jobs stored a FLOAT 1.0 on every a2v render; on Q8 that is audio+ # guidance off. The server reads it as Auto; so must Load Params+ # (Codex integration review, 2026-09-24).+ out = self._run(self._params(audio_conditioning_scale=1.0))+ self.assertNotIn("audio_conditioning_scale", out["posted"])++ def test_a_chosen_one_is_kept(self):+ out = self._run(self._params(audio_conditioning_scale="1"))+ self.assertEqual(out["posted"]["audio_conditioning_scale"], "1")+++# ---------------------------------------------------------------------------+# LTX-05 — Load Params lost Sliding windows and the per-window prompts+# ---------------------------------------------------------------------------++# Everything loadParams touches that is not under test resolves to a no-op+# (or an auto-created element); the functions under test are the real ones.+LOOSE_SHIM = r"""+var _els = {};+function _mk(id, v) {+ return _els[id] = {id, value: v === undefined ? '' : String(v), textContent: '', dataset: {},+ hidden: false, style: {}, innerHTML: '', checked: false, open: false,+ classList: {toggle(){}, add(){}, remove(){}, contains(){ return false; }},+ querySelector(){ return null; }, querySelectorAll(){ return []; },+ setAttribute(){}, getAttribute(){ return null; }, dispatchEvent(){ return true; },+ addEventListener(){}, focus(){}};+}+var document = {getElementById: id => _els[id] || _mk(id), querySelector: () => null,+ querySelectorAll: () => [], body: {dataset: {}, classList: {toggle(){}}}};+var BOOT = {ltx: {qualities: [{key: 'balanced', pipeline: 'distilled'}]}}, currentMode = 't2v',+ activePath = '/x.mp4', FPS = 24;+_mk('mode', 't2v'); _mk('quality', 'balanced'); _mk('frames', '481');+_mk('window_prompts_text', 'STALE LINE'); _mk('window_invariants', 'stale');+var _noop = function () {};+var SHIM = new Proxy({}, {+ has: (_, k) => k !== Symbol.unscopables && !(k in globalThis) && typeof k === 'string',+ get: (_, k) => _noop,+});+"""++[email protected](NODE, "node not on PATH")+class WindowedClipsReloadAsWindowed(unittest.TestCase):++ def _load(self, params: dict) -> dict:+ from extract_panel_js import extract_function, panel_source # noqa: PLC0415+ src = panel_source()+ fns = ("_qualityUsesHq", "temporalModeAllowed", "setTemporalMode",+ "windowPromptsInput", "loadParams")+ js = LOOSE_SHIM + "with (SHIM) {\n" + "\n".join(+ extract_function(n, src) for n in fns) + """+globalThis.fetch = async () => ({ok: true, json: async () => (%s)});+loadParams().then(() => console.log(JSON.stringify({+ temporal: document.getElementById('temporal_mode').value,+ prompts: document.getElementById('window_prompts').value,+ invariants: document.getElementById('window_invariants').value})),+ e => { console.error(e); process.exit(1); });+}""" % json.dumps({"output": "/x.mp4", "params": params})+ r = subprocess.run([NODE, "-e", js], capture_output=True, text=True, timeout=30)+ self.assertEqual(r.returncode, 0, r.stderr[-2000:])+ return json.loads(r.stdout.strip().splitlines()[-1])++ def test_a_windowed_sidecar_round_trips_through_make_job(self):+ form = {"mode": "t2v", "prompt": "a hen skates", "frames": "481",+ "quality": "balanced", "temporal_mode": "windows",+ "window_prompts": json.dumps(["opening", "", "the hen jumps", "landing"]),+ "window_invariants": "same pond, same dusk light"}+ saved = P.make_job(form)["params"]+ self.assertEqual(saved["long_mode"], "windows")+ got = self._load(saved)+ self.assertEqual(got["temporal"], "windows")+ again = P.make_job({**form, "temporal_mode": got["temporal"],+ "window_prompts": got["prompts"],+ "window_invariants": got["invariants"]})["params"]+ self.assertEqual(again["long_mode"], "windows")+ self.assertEqual(again["window_prompts"], saved["window_prompts"])+ self.assertEqual(again["window_invariants"], saved["window_invariants"])++ def test_a_native_clip_clears_stale_window_text(self):+ saved = P.make_job({"mode": "t2v", "prompt": "x", "frames": "121"})["params"]+ got = self._load(saved)+ self.assertEqual(got["temporal"], "native")+ self.assertEqual(got["prompts"], "")+ self.assertEqual(got["invariants"], "")+++# ---------------------------------------------------------------------------+# LTX-06 / LTX-10 — hardware clamps squashed the aspect and left the /64 grid+# ---------------------------------------------------------------------------++def _fake_ffmpeg(cmd, *a, **k):+ Path(cmd[-1]).write_bytes(b"enc")+ return "", ""+++class HardwareClampsKeepShapeAndGrid(unittest.TestCase):++ def setUp(self):+ self.tmp = Path(tempfile.mkdtemp(prefix="ltx06-"))+ self.wav = self.tmp / "song.wav"+ self.wav.write_bytes(b"RIFF0000WAVE")+ self.png = self.tmp / "a.png"+ subprocess.run([str(P.FFMPEG), "-loglevel", "error", "-y", "-f", "lavfi", "-i",+ "color=c=green:s=64x64:d=1", "-frames:v", "1", "-update", "1",+ str(self.png)], check=True)++ def _dispatch(self, form: dict, tier: str, *, profile=None) -> tuple[dict, dict]:+ helper, sidecars = _Helper(), []+ job = P.make_job(form)+ job["started_ts"] = time.time()+ with mock.patch.object(P, "HELPER", helper), \+ mock.patch.object(P, "OUTPUT", self.tmp), \+ mock.patch.object(P, "SYSTEM_TIER", tier), \+ mock.patch.object(P, "SYSTEM_CAPS", P.CAPABILITIES[tier]), \+ mock.patch.object(P, "GENERATION_PROFILE",+ profile or P._select_generation_profile(128.0, "pro")), \+ mock.patch.object(P, "ltx_pack_preflight", lambda *a, **k: None), \+ mock.patch.object(P, "hq_surface_missing", lambda *a, **k: []), \+ mock.patch.object(P, "run_ffmpeg_tracked", _fake_ffmpeg), \+ mock.patch.object(P, "set_hidden", lambda *a, **k: None), \+ mock.patch.object(P, "write_sidecar",+ lambda _p, data: sidecars.append(data) or True):+ P.run_job_inner(job)+ spec = helper.sent[0]["params"]+ return spec, (sidecars[-1]["params"] if sidecars else job["params"])++ def _check(self, got, want_long, req):+ w, h = got+ self.assertEqual((w % 64, h % 64), (0, 0), got)+ self.assertLessEqual(max(w, h), want_long)+ scale = want_long / max(req)+ for have, asked in zip(got, req):+ self.assertLess(abs(have - asked * scale), 64, (got, req))++ def test_a2v_scales_both_sides_and_records_what_rendered(self):+ for req in ((1280, 704), (704, 1280), (1024, 1024)):+ with self.subTest(req=req):+ spec, side = self._dispatch(+ {"mode": "a2v", "prompt": "a singer", "audio": str(self.wav),+ "width": str(req[0]), "height": str(req[1]), "frames": "49",+ "quality": "high"}, "base")+ got = (spec["width"], spec["height"])+ self._check(got, 768, req)+ self.assertEqual((side["width"], side["height"]), got)++ def test_the_base_tier_t2v_clamp_stays_on_the_grid(self):+ spec, side = self._dispatch({"mode": "t2v", "prompt": "a lighthouse", "quality": "standard",+ "width": "1280", "height": "704", "frames": "49"}, "base")+ got = (spec["width"], spec["height"])+ self._check(got, 768, (1280, 704))+ self.assertEqual((side["width"], side["height"]), got)++ def test_the_fflf_clamp_stays_on_the_grid(self):+ spec, side = self._dispatch({"mode": "keyframe", "prompt": "across the pond",+ "start_image": str(self.png), "end_image": str(self.png),+ "width": "1280", "height": "704", "frames": "49"}, "standard")+ got = (spec["width"], spec["height"])+ self._check(got, 768, (1280, 704))+ self.assertEqual((side["width"], side["height"]), got)++ def test_the_compact_profile_clamp_stays_on_the_grid(self):+ job = P.make_job({"mode": "t2v", "prompt": "x", "quality": "balanced",+ "width": "1536", "height": "832", "frames": "49"})+ with mock.patch.object(P, "GENERATION_PROFILE", P._select_generation_profile(48.0, "standard")):+ P._apply_generation_profile_to_job(job)+ got = (job["params"]["width"], job["params"]["height"])+ self._check(got, 1024, (1536, 832))+++# ---------------------------------------------------------------------------+# LTX-07 — an apostrophe in the output folder broke the windows join+# ---------------------------------------------------------------------------++def _frames_clip(path: Path, frames: int) -> None:+ subprocess.run([str(P.FFMPEG), "-loglevel", "error", "-y", "-f", "lavfi", "-i",+ f"testsrc=s=64x64:r=24:d={frames / 24:.4f}", "-f", "lavfi", "-i",+ "anullsrc=r=48000:cl=stereo", "-frames:v", str(frames),+ "-t", f"{frames / 24:.4f}", "-c:v", "libx264", "-pix_fmt", "yuv420p",+ "-c:a", "aac", str(path)], check=True)+++def _probe_frames(path: Path) -> int:+ out = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-count_packets",+ "-show_entries", "stream=nb_read_packets", "-of", "csv=p=0", str(path)],+ capture_output=True, text=True).stdout.strip()+ return int(out or 0)+++class TheWindowsJoinSurvivesAnyFolderName(unittest.TestCase):++ def test_the_real_join_under_awkward_output_roots(self):+ import ltx_windows as lw+ if not shutil.which("ffprobe"):+ self.skipTest("ffprobe not on PATH")+ for name in ("Artist's Drive", "with space", "出力 フォルダ"):+ with self.subTest(root=name):+ root = Path(tempfile.mkdtemp(prefix="ltx07-")) / name / "outputs"+ root.mkdir(parents=True)+ first = root / "clip_w0.mp4"+ _frames_clip(first, 121)+ raw = root / "clip.mp4"++ def fake_run(spec):+ # an extend: context + the new window, as one clip+ _frames_clip(Path(spec["params"]["output_path"]), 121 + 112)+ return {"elapsed_sec": 1}+ with mock.patch.object(P, "OUTPUT", root), \+ mock.patch.object(P.HELPER, "run", side_effect=fake_run), \+ mock.patch.object(P, "set_hidden", lambda *a, **k: None), \+ mock.patch.object(P, "pack_path", return_value=Path("/q8")), \+ mock.patch.object(P, "hq_weights",+ return_value={"dev_transformer": "dev.safetensors"}):+ out = P._run_windows_chain({"id": "j7"}, {"prompt": "a walk", "seed": 7},+ lw.plan_windows(241), first, raw, 241)+ self.assertTrue(raw.is_file())+ self.assertEqual(out["output_frames"], 241)+ self.assertGreaterEqual(_probe_frames(raw), 230)++ def test_the_manifest_line_quotes_an_apostrophe(self):+ self.assertEqual(P.ffconcat_line("/V/Artist's Drive/a.mp4"),+ "file '/V/Artist'\\''s Drive/a.mp4'\n")+++# ---------------------------------------------------------------------------+# LTX-08 — the first sliding-window line was saved but never rendered+# ---------------------------------------------------------------------------++class EveryWindowRendersItsOwnLine(unittest.TestCase):++ def test_three_windows_render_the_three_saved_prompts(self):+ tmp = Path(tempfile.mkdtemp(prefix="ltx08-"))+ helper, sidecars = _Helper(), []+ job = P.make_job({"mode": "t2v", "prompt": "BASE PROMPT", "quality": "balanced",+ "width": "512", "height": "320", "frames": "241",+ "temporal_mode": "windows",+ "window_prompts": json.dumps(["OPENING OVERRIDE", "SECOND", "THIRD"])})+ job["started_ts"] = time.time()+ with mock.patch.object(P, "HELPER", helper), \+ mock.patch.object(P, "OUTPUT", tmp), \+ mock.patch.object(P, "SYSTEM_CAPS", P.CAPABILITIES["pro"]), \+ mock.patch.object(P, "GENERATION_PROFILE", P._select_generation_profile(128.0, "pro")), \+ mock.patch.object(P, "ltx_pack_preflight", lambda *a, **k: None), \+ mock.patch.object(P, "hq_surface_missing", lambda *a, **k: []), \+ mock.patch.object(P, "run_ffmpeg_tracked", _fake_ffmpeg), \+ mock.patch.object(P, "set_hidden", lambda *a, **k: None), \+ mock.patch.object(P, "write_sidecar",+ lambda _p, data: sidecars.append(data) or True):+ P.run_job_inner(job)+ sent = [s["params"]["prompt"] for s in helper.sent]+ saved = sidecars[-1]["windows"]["prompts"]+ self.assertEqual(len(sent), 3)+ self.assertEqual(sent[0], "OPENING OVERRIDE")+ self.assertEqual(sent, saved)+++# ---------------------------------------------------------------------------+# LTX-09 — One Shot previews were written where the status reader never looked+# ---------------------------------------------------------------------------++class TheTakesPreviewFollowsThePartRendering(_TakeHarness):++ def _publish(self, job_id: str) -> Path:+ d = P.live_preview_dir(job_id)+ d.mkdir(parents=True, exist_ok=True)+ (d / "status.json").write_text(json.dumps({"forward": 8, "total_forwards": 10}))+ (d / "preview_latest.png").write_bytes(b"png")+ return d++ def test_status_and_stop_early_resolve_the_active_part(self):+ from panel import routes_queue # noqa: PLC0415+ PM = routes_queue.P or P+ job = P.make_job({"mode": "t2v", "engine": "ltx", "prompt": "a hen skates",+ "take_seconds": "30"})+ seen = []++ def part(child):+ seen.append(job.get("preview_id"))+ d = self._publish(child["id"])+ got = P._preview_progress(job, 12.0, "denoise")+ self.assertIn("preview", got, "status sees the part's preview")+ self.assertIn(child["id"], got["preview"]["url"])+ # Stop early, through the real route, lands in the part's folder.+ saved = PM.STATE["current"]+ replies = []++ class _Req:+ def _json(self, body, status=200):+ replies.append((status, body))+ with PM.LOCK:+ PM.STATE["current"] = job+ try:+ with mock.patch.object(PM, "live_preview_dir", P.live_preview_dir):+ routes_queue.post_stop(_Req(), "/stop", {"mode": ["early"]}, "")+ finally:+ with PM.LOCK:+ PM.STATE["current"] = saved+ self.assertEqual(replies[0][0], 200, replies)+ self.assertTrue((d / "ABORT").is_file())+ (d / "ABORT").unlink()+ self._fake_part(child)++ with mock.patch.object(P, "run_job_inner", part), \+ mock.patch.object(P, "STATE_DIR", self.tmp / "state"):+ P.run_take_job_inner(job)+ self.assertEqual(seen, [f"{job['id']}-p1", f"{job['id']}-p2", f"{job['id']}-p3"])+ self.assertNotIn("preview_id", job, "cleared for the join")++ def test_an_ordinary_job_is_unchanged(self):+ self.assertEqual(P.live_preview_job_id({"id": "j-1"}), "j-1")+++if __name__ == "__main__":+ unittest.main()diff --git a/test_room_tone_decoder.py b/test_room_tone_decoder.pynew file mode 100644index 0000000..e6adf62--- /dev/null+++ b/test_room_tone_decoder.py@@ -0,0 +1,100 @@+#!/usr/bin/env python3+"""Room tone "From this film" decodes with the panel's own ffmpeg (M6-08).++The panel resolves ffmpeg at boot, including Pinokio's bundled tool folders+that need not be on the process PATH. `room_tone` searched only PATH and two+Homebrew paths, so on such a Mac it could not start a decoder, read that as+"no clip with usable quiet sound", and bedded the film with a preset (or, on+the automatic cut, with nothing) while blaming the clips.++Scratch OUTPUT only; the decoder process is mocked, nothing is decoded.+"""+from __future__ import annotations++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 room_tone as rt # noqa: E402+++class RoomToneUsesThePanelsFfmpeg(unittest.TestCase):++ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ root = Path(self.tmp.name)+ self.out = root / "outputs"+ self.out.mkdir()+ # The only ffmpeg on this "Mac": a bundled one the panel found.+ self.bundled = root / "pinokio-bin" / "ffmpeg"+ self.bundled.parent.mkdir()+ self.bundled.write_text("#!/bin/sh\nexit 0\n")+ self.bundled.chmod(0o755)+ self.clip = root / "S01.mp4"+ self.clip.write_bytes(b"x")+ self.board = {"id": "sb_20231115_aaaaaa", "title": "Room",+ "created_at": 1_700_050_000, "shots": []}+ for p in (mock.patch.object(panel, "OUTPUT", self.out),+ mock.patch.object(panel, "FFMPEG", self.bundled),+ mock.patch.object(panel, "push", lambda *a, **k: None),+ mock.patch.object(rt, "FFMPEG", None),+ mock.patch.dict("os.environ", {"PHOSPHENE_FFMPEG": ""}),+ mock.patch.object(rt.shutil, "which", return_value=None)):+ p.start()+ self.addCleanup(p.stop)++ def _bed(self, run, strict=True):+ with mock.patch.object(rt.subprocess, "run", side_effect=run):+ return panel._sbe_room_tone(+ self.board, variant="film", seed=1, film_len=10.0, strict=strict,+ clips=[{"path": str(self.clip), "start": 0.0, "end": 5.0}])++ def test_the_decoder_is_the_one_the_panel_resolved(self):+ seen = []++ def run(cmd, **kw):+ seen.append(cmd[0])+ return subprocess.CompletedProcess(cmd, 0, stdout=b"", stderr=b"")++ self._bed(run)+ self.assertEqual(seen, [str(self.bundled)])++ def test_a_decoder_that_cannot_start_is_said_as_that(self):+ def run(cmd, **kw):+ raise FileNotFoundError(2, "No such file or directory", cmd[0])++ facts = self._bed(run)+ self.assertFalse(facts["ok"])+ self.assertIn("ffmpeg could not be started", facts["error"])+ self.assertNotIn("no clip with usable quiet sound", facts["error"])++ def test_by_hand_it_falls_back_but_does_not_cache_the_fallback(self):+ def run(cmd, **kw):+ raise PermissionError(13, "Permission denied", cmd[0])++ facts = self._bed(run, strict=False)+ self.assertTrue(facts["ok"])+ self.assertIn("could not be read", facts["fallback"])+ # The next pick — with a decoder that works — must not be answered+ # by a cached preset that was only ever a symptom.+ self.assertEqual(list(Path(facts["path"]).parent.glob("*.json")), [])++ def test_a_silent_clip_is_still_called_silent(self):+ def run(cmd, **kw):+ return subprocess.CompletedProcess(cmd, 0, stdout=b"\0\0" * 48000 * 5,+ stderr=b"")++ facts = self._bed(run)+ self.assertIn("no clip with usable quiet sound", facts["error"])+++if __name__ == "__main__":+ unittest.main()diff --git a/test_settings_merge.py b/test_settings_merge.pyindex f3b17ed..44b871e 100644--- a/test_settings_merge.py+++ b/test_settings_merge.py@@ -61,5 +61,53 @@ class AWriteKeepsWhatOthersSaved(unittest.TestCase):self.assertEqual(json.loads(P.SETTINGS_FILE.read_text())["hf_token"], "")++_WRITER = r"""+import os, sys, time+sys.path.insert(0, sys.argv[1])+import mlx_ltx_panel as P+P.get_settings() # this process's copy, before either write+real_save = P._save_settings+def slow_save(settings, **kw): # widen the read-merge-replace window+ time.sleep(0.6)+ real_save(settings, **kw)+P._save_settings = slow_save+go = float(sys.argv[2])+while time.time() < go:+ time.sleep(0.005)+if sys.argv[3] == "token":+ cur, err = P.update_settings({"hf_token": "hf_saved_in_panel_a_0123456789"})+ assert err is None, err+else:+ P._settings_set_internal(analytics_last_version="9.9.9")+"""+++class TwoPanelsWritingAtOnce(unittest.TestCase):+ """Codex UI-04: the merge above is only as good as its lock, and the lock+ was a THREAD lock. Two processes that both read before either replaced the+ file lost the first one's key. Two real processes, one temp state dir."""++ def test_both_keys_survive_a_simultaneous_save(self):+ import subprocess+ import sys+ root = str(Path(__file__).resolve().parent)+ state = Path(tempfile.mkdtemp(prefix="phos-settings-2p-"))+ env = dict(os.environ, LTX_STATE_DIR=str(state),+ LTX_OUTPUT_DIR=str(state / "out"), LTX_UPLOADS_DIR=str(state / "up"),+ PHOSPHENE_ANALYTICS_DISABLED="1", PHOSPHENE_DISABLE_VERSION_CHECK="1")+ env.pop("PYTEST_CURRENT_TEST", None)+ go = str(time.time() + 6.0)+ procs = [subprocess.Popen([sys.executable, "-c", _WRITER, root, go, role], env=env,+ stdout=subprocess.PIPE, stderr=subprocess.PIPE)+ for role in ("token", "bookkeeping")]+ for pr in procs:+ _, err = pr.communicate(timeout=120)+ self.assertEqual(pr.returncode, 0, err.decode(errors="replace")[-800:])+ on_disk = json.loads((state / "panel_settings.json").read_text())+ self.assertEqual(on_disk.get("hf_token"), "hf_saved_in_panel_a_0123456789",+ "a concurrent bookkeeping write reverted a saved token")+ self.assertEqual(on_disk.get("analytics_last_version"), "9.9.9")+if __name__ == "__main__":unittest.main()diff --git a/test_storyboard_assembly.py b/test_storyboard_assembly.pyindex 80bbaac..13081e1 100644--- a/test_storyboard_assembly.py+++ b/test_storyboard_assembly.py@@ -877,13 +877,17 @@ class ExportSelection(unittest.TestCase):def clip(self, name: str) -> Path:return _write_fake_clip(self.src / name, name.encode() * 64)- def export(self, board, film=None):+ def export(self, board, film=None, **export_kw):"""Run the real _sb_export with the assembler mocked. -> (res, clips)."""seen = {}- def fake_assemble(clips, out):+ def fake_assemble(clips, out, **kw):seen["clips"] = [Path(c) for c in clips]seen["out"] = Path(out)+ # The soundtrack arguments are part of the call now (a music video+ # exports whole clips WITH the song as the bed), so the fake has+ # to see them or the thing under test cannot be asserted.+ seen["kw"] = kwif film is None:Path(out).write_bytes(b"film")return {"ok": True, "path": str(out), "clips": len(clips),@@ -892,7 +896,7 @@ class ExportSelection(unittest.TestCase):return filmwith mock.patch.object(panel, "_sb_assemble_film", side_effect=fake_assemble):- res = panel._sb_export(board)+ res = panel._sb_export(board, **export_kw)return res, seendef test_shots_reach_the_film_in_n_order_however_the_board_stores_them(self):@@ -904,6 +908,24 @@ class ExportSelection(unittest.TestCase):"S03_shot-3-happens.mp4"])self.assertEqual(res["files"], [p.name for p in seen["clips"]])+ def test_a_soundtrack_reaches_the_assembler_on_the_whole_clip_path(self):+ # THE BUG THIS PINS: the whole-clip branch called the assembler with+ # the clip list and nothing else, so `_sb_export(music=...)` without+ # auto_edit accepted a soundtrack at the door and wrote a film with no+ # soundtrack in it. That is the path a music video wants — its shots+ # are already cut to the beat, and re-cutting them would slide every+ # a2v clip off the seconds of the song it was rendered against.+ song = _write_fake_clip(self.src / "song.wav", b"RIFF" * 64)+ _res, seen = self.export(_board([_clip(1, self.clip("a.mp4"))]),+ music=str(song), music_mode="replace")+ self.assertEqual(seen["kw"].get("music"), str(song))+ self.assertEqual(seen["kw"].get("music_mode"), "replace")+ self.assertIsNone(seen["kw"].get("plan"))++ def test_an_export_with_no_soundtrack_asks_for_none(self):+ _res, seen = self.export(_board([_clip(1, self.clip("a.mp4"))]))+ self.assertIsNone(seen["kw"].get("music"))+def test_skipped_shots_are_excluded_from_the_film_and_the_folder(self):a, b = self.clip("a.mp4"), self.clip("b.mp4")board = _board([_clip(1, a), _clip(2, b, status="skipped")])@@ -1026,10 +1048,16 @@ class ExportSelection(unittest.TestCase):"unreadable": []}res = panel._sb_export(_board([_clip(1, a)]))planner.assert_not_called()- # and the assembler is called EXACTLY as it was before the auto-editor- # existed — two positional arguments, no keywords.+ # and the assembler is asked for EXACTLY what it was asked for before+ # the auto-editor existed: the clips, where to write them, no plan and+ # no soundtrack. (It used to be two positional arguments and no+ # keywords at all; the soundtrack keywords are always passed now, and+ # `music=None` builds the identical filtergraph — see the comment at+ # the call site. The assertion is on the ASK, not on the argv shape,+ # because the argv shape was never the promise.)self.assertEqual(len(asm.call_args.args), 2)- self.assertEqual(asm.call_args.kwargs, {})+ self.assertIsNone(asm.call_args.kwargs.get("music"))+ self.assertIsNone(asm.call_args.kwargs.get("plan"))self.assertFalse(res["auto_edit"])self.assertNotIn("Auto-edited",(Path(res["dir"]) / "storyboard.md")@@ -1073,7 +1101,11 @@ class ExportSelection(unittest.TestCase):"sample_rate": 48000, "duration": 5.0,"unreadable": []}res = panel._sb_export(_board([_clip(1, a)]), auto_edit=True)- self.assertEqual(asm.call_args.kwargs, {}) # the old call, exactly+ # No plan reached the assembler — the whole-clip call. (The soundtrack+ # keywords ride along on every call now; this export named no song, so+ # they are empty and the filtergraph is the one that always ran.)+ self.assertIsNone(asm.call_args.kwargs.get("plan"))+ self.assertIsNone(asm.call_args.kwargs.get("music"))self.assertTrue(res["ok"])self.assertFalse(res["auto_edit"])md = (Path(res["dir"]) / "storyboard.md").read_text(encoding="utf-8")diff --git a/test_storyboard_dispatch_integrity.py b/test_storyboard_dispatch_integrity.pynew file mode 100644index 0000000..f3aea7b--- /dev/null+++ b/test_storyboard_dispatch_integrity.py@@ -0,0 +1,249 @@+#!/usr/bin/env python3+"""The storyboard render dispatcher: what it retries, what Stop stops, and what+a poll is allowed to change.++ * SB5-08 a shot whose job could not be queued (or failed) was picked again+ on the very next round, forever: a tight loop rewriting the board+ and spamming the log, or the same render re-spent indefinitely.+ * SB5-09 Stop Film collected draft/final job ids only, so anchor-still+ image jobs stayed queued (and a running one kept the GPU).+ * SB5-10 the reconciler turned a shot the user had CUT back into "done"+ because its old draft job was still in the queue history, which+ put it back into the delivery pass and the export.++Everything runs against a scratch STATE_DIR and an in-memory queue; nothing+is enqueued to a real panel and no engine runs.+"""+from __future__ import annotations++import sys+import tempfile+import threading+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+import storyboard # noqa: E402+from test_storyboard_editor_api import FakeHandler # noqa: E402+++def _shot(n, **kw):+ s = {"n": n, "mode": "text", "engine": "ltx", "prompt": f"shot {n} happens",+ "duration_s": 5.0, "seed": 100 + n, "refs": [], "status": "pending"}+ s.update(kw)+ return s+++def _board(shots, bid="sb_20231115_d15bad", **kw):+ b = {"schema": 1, "id": bid, "title": "Dispatch", "created_at": 1_700_050_000,+ "policy": storyboard.default_policy(), "cast": [], "engine_mode": "ltx",+ "shots": shots}+ b.update(kw)+ return b+++class Sandbox(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ self.state = Path(self.tmp.name) / "state"+ self.state.mkdir()+ self.queue_state = {"queue": [], "current": None, "history": []}+ for p in (mock.patch.object(panel, "STATE_DIR", self.state),+ mock.patch.object(panel, "STATE", self.queue_state),+ mock.patch.object(panel, "persist_queue", lambda: None),+ mock.patch.object(panel, "push", lambda *a, **k: None)):+ p.start()+ self.addCleanup(p.stop)+ panel._SB_RENDERS.clear()+ self.addCleanup(panel._SB_RENDERS.clear)++ def save(self, board):+ storyboard.save_storyboard(self.state, board)+ return board++ def load(self, bid):+ return storyboard.load_storyboard(self.state, bid)+++class FailedShotsAreNotRetriedForever(Sandbox):+ """SB5-08."""++ def _dispatch(self, board, *, enqueue, index):+ self.save(board)+ bid = board["id"]+ panel._SB_RENDERS[bid] = {"stop": False, "queued": 0}+ th = threading.Thread(target=panel._sb_render_thread,+ args=(bid, "draft", None), daemon=True)+ with mock.patch.object(panel, "_sb_enqueue", side_effect=enqueue), \+ mock.patch.object(panel, "_sb_job_index", side_effect=index), \+ mock.patch.object(panel, "_sb_h3_available", return_value=False), \+ mock.patch.object(panel, "h3_supports_chain_prompts", return_value=False), \+ mock.patch.object(panel, "h3_supports_first_frame", return_value=False), \+ mock.patch.object(panel, "_sb_lipsync_gate", lambda *a, **k: None), \+ mock.patch.object(panel, "_sb_sweep_stage_a", lambda *a, **k: None), \+ mock.patch.object(storyboard, "shot_to_job",+ lambda shot, *a, **k: {"mode": "t2v",+ "prompt": shot["prompt"]}):+ th.start()+ th.join(timeout=10)+ finished = not th.is_alive()+ if not finished: # never leave a spinning thread behind+ panel._SB_RENDERS.setdefault(bid, {})["stop"] = True+ th.join(timeout=10)+ return finished++ def test_a_shot_that_cannot_be_queued_is_tried_once_per_render(self):+ calls = []++ def refuse(form):+ calls.append(form["prompt"])+ raise RuntimeError("the character sheet is missing")++ board = _board([_shot(1), _shot(2)])+ finished = self._dispatch(board, enqueue=refuse, index=lambda: {})+ self.assertTrue(finished, "the dispatcher kept retrying a refused shot")+ self.assertEqual(sorted(calls), ["shot 1 happens", "shot 2 happens"])+ after = self.load(board["id"])+ self.assertEqual({s["status"] for s in after["shots"]}, {"failed"})+ self.assertIn("character sheet", after["shots"][0]["error"])+ # ...and the film's render slot is released, so Render can be pressed+ # again once the cause is fixed.+ self.assertNotIn(board["id"], panel._SB_RENDERS)++ def test_a_shot_whose_job_fails_is_not_re_rendered_by_the_same_run(self):+ calls = []++ def ok(form):+ calls.append(form["prompt"])+ return f"job-{len(calls)}"++ def index():+ return {f"job-{i + 1}": {"status": "failed", "error": "engine died"}+ for i in range(len(calls))}++ board = _board([_shot(1)])+ finished = self._dispatch(board, enqueue=ok, index=index)+ self.assertTrue(finished, "the dispatcher kept re-rendering a failing shot")+ self.assertEqual(calls, ["shot 1 happens"])+ self.assertEqual(self.load(board["id"])["shots"][0]["status"], "failed")+++class StopFilmStopsItsStills(Sandbox):+ """SB5-09."""++ def test_stop_withdraws_queued_stills_and_cancels_the_running_one(self):+ board = self.save(_board([+ _shot(1, still_job_id="img-running", status="pending"),+ _shot(2, still_job_id="img-queued-1", status="pending"),+ _shot(3, still_job_id="img-queued-2", status="pending"),+ _shot(4, still_job_id="skipped", still_error="no sheet"),+ ]))+ self.queue_state["queue"] = [{"id": "img-queued-1"}, {"id": "other-job"},+ {"id": "img-queued-2"}]+ self.queue_state["current"] = {"id": "img-running"}+ panel._SB_RENDERS[board["id"]] = {"stop": False}+ with mock.patch.object(panel, "stop_current_job",+ return_value=True) as stop:+ h = FakeHandler().post("stop", {"id": [board["id"]]})+ self.assertTrue(h.payload["ok"])+ self.assertEqual([j["id"] for j in self.queue_state["queue"]], ["other-job"])+ self.assertEqual(h.payload["removed"], 2)+ self.assertEqual(h.payload["cancelled"], "img-running")+ stop.assert_called_once()+ # A still that was withdrawn is owed again: the next Render makes it+ # instead of rendering the shot unanchored.+ after = {s["n"]: s for s in self.load(board["id"])["shots"]}+ for n in (1, 2, 3):+ self.assertFalse(after[n].get("still_job_id"), n)+ # A still that was never going to exist is left as it was said.+ self.assertEqual(after[4]["still_job_id"], "skipped")++ def test_an_unrelated_running_job_is_not_this_films_to_kill(self):+ board = self.save(_board([_shot(1, still_job_id="img-queued")]))+ self.queue_state["queue"] = [{"id": "img-queued"}]+ self.queue_state["current"] = {"id": "somebody-elses-render"}+ with mock.patch.object(panel, "stop_current_job") as stop:+ h = FakeHandler().post("stop", {"id": [board["id"]]})+ stop.assert_not_called()+ self.assertIsNone(h.payload["cancelled"])+ self.assertEqual(self.queue_state["queue"], [])++ def test_the_dispatcher_queues_no_still_after_stop(self):+ # Stop can land while the still loop is running: it must not go on+ # queueing the rest of the batch.+ board = self.save(_board([_shot(n, still_prompt="x") for n in (1, 2, 3)],+ anchor_stills=True))+ bid = board["id"]+ panel._SB_RENDERS[bid] = {"stop": False}+ queued = []++ def enqueue(form):+ queued.append(form)+ panel._SB_RENDERS[bid]["stop"] = True # Stop pressed now+ return f"img-{len(queued)}"++ with mock.patch.object(panel, "_sb_enqueue", side_effect=enqueue), \+ mock.patch.object(panel, "_sb_still_job_form",+ lambda shot, b, p: {"mode": "image"}), \+ mock.patch.object(storyboard, "shot_wants_still", return_value=True), \+ mock.patch.object(panel, "_sb_job_index", return_value={}), \+ mock.patch.object(panel, "_sb_h3_available", return_value=False), \+ mock.patch.object(panel, "_sb_sweep_stage_a", lambda *a, **k: None):+ panel._sb_render_thread(bid, "draft", None)+ self.assertEqual(len(queued), 1)+++class ACutShotStaysCut(Sandbox):+ """SB5-10."""++ def _reconcile(self, board, index):+ with mock.patch.object(panel, "_sb_job_index", return_value=index):+ return panel._sb_reconcile(board)++ def test_a_poll_does_not_revive_a_cut_shot(self):+ board = _board([_shot(1, status="skipped", grade="cut",+ draft_job_id="j1", draft_output="/o/s1.mp4"),+ _shot(2, status="done", draft_job_id="j2",+ draft_output="/o/s2.mp4")])+ index = {"j1": {"status": "done", "output_path": "/o/s1.mp4"},+ "j2": {"status": "done", "output_path": "/o/s2.mp4"}}+ for _ in range(3):+ self._reconcile(board, index)+ self.assertEqual(board["shots"][0]["status"], "skipped")+ self.assertEqual([s["n"] for s in+ storyboard.shots_pending(board["shots"], "final")], [2])++ def test_a_job_that_is_still_running_does_not_uncut_it_either(self):+ board = _board([_shot(1, status="skipped", grade="cut",+ final_job_id="j9", draft_output="/o/s1.mp4")])+ self._reconcile(board, {"j9": {"status": "running"}})+ self.assertEqual(board["shots"][0]["status"], "skipped")++ def test_a_board_already_revived_by_the_old_poll_is_put_right(self):+ board = _board([_shot(1, status="done", grade="cut",+ draft_job_id="j1", draft_output="/o/s1.mp4")])+ self.assertTrue(self._reconcile(+ board, {"j1": {"status": "done", "output_path": "/o/s1.mp4"}}))+ self.assertEqual(board["shots"][0]["status"], "skipped")++ def test_uncut_is_still_one_click(self):+ board = self.save(_board([_shot(1, status="skipped", grade="cut",+ draft_output="/o/s1.mp4")]))+ with mock.patch.object(panel, "_sb_sweep_stage_a", lambda *a, **k: None):+ FakeHandler().post("grade", {"id": [board["id"]], "n": ["1"],+ "grade": [""]})+ after = self.load(board["id"])["shots"][0]+ self.assertEqual(after["status"], "done")+ with mock.patch.object(panel, "_sb_job_index", return_value={}):+ panel._sb_reconcile(after and self.load(board["id"]))+ self.assertEqual(self.load(board["id"])["shots"][0]["status"], "done")+++if __name__ == "__main__":+ unittest.main()diff --git a/test_storyboard_editor_ui.py b/test_storyboard_editor_ui.pyindex 94779fa..7dee8d5 100644--- a/test_storyboard_editor_ui.py+++ b/test_storyboard_editor_ui.py@@ -2991,11 +2991,15 @@ class SavingCannotFailQuietly(unittest.TestCase):# `true` and re-queuing through that lane turned the second of two# rapid Save presses into a backup write, with edit.json left at the# older revision and the alarm reading clear.- self.assertEqual(self.r["midFlightRemembered"], "backup")+ # 2026-09-24 (SB5-14): a QUIET request is a save too now. Every+ # `sbeSave(true)` left is Render / export / relink waiting on edit.json,+ # and downgrading it to a backup let them run against the previous+ # cut. `test_editor_save_integrity.py` drives the interleaving itself.+ self.assertEqual(self.r["midFlightRemembered"], "save")self.assertEqual(self.r["midFlightRemembersASave"], "save")fn = extract_function("sbeSave", self.src)self.assertIn("finally", fn)- self.assertIn("if (again === 'save') sbeSave(quiet, force);", fn)+ self.assertIn("if (again && SBE.dirty && !SBE.conflict && SBE.open) return sbeSave(quiet, false);", fn)def test_the_in_flight_flag_cannot_stick_after_a_throw(self):self.assertFalse(self.r["flagClearedAfterThrow"])diff --git a/test_storyboard_film.py b/test_storyboard_film.pyindex eb5a4c9..e939729 100644--- a/test_storyboard_film.py+++ b/test_storyboard_film.py@@ -62,12 +62,17 @@ class FilmDir(unittest.TestCase):def test_the_folder_is_date_and_slug_under_the_outputs_root(self):d = panel._sb_film_dir(_board())self.assertEqual(d.parent, panel.OUTPUT / "storyboards")- self.assertTrue(d.name.endswith("_the-last-dawn"), d.name)+ # ...and the board: date + title alone was shared by every board made+ # the same day under the same name (SB5-05). A board whose old+ # date+title folder is already on disk keeps it — see+ # test_storyboard_film_integrity.py.+ self.assertTrue(d.name.endswith("_the-last-dawn_sb-film-test"), d.name)day = time.strftime("%Y-%m-%d", time.localtime(1_700_000_000))self.assertTrue(d.name.startswith(day), d.name)def test_an_untitled_board_still_gets_a_folder(self):- self.assertTrue(str(panel._sb_film_dir(_board(title=""))).endswith("_storyboard"))+ self.assertTrue(str(panel._sb_film_dir(_board(title=""))).endswith(+ "_storyboard_sb-film-test"))def test_the_export_writes_into_exactly_that_folder(self):# The whole point of the helper: the writer and the reader agree by@@ -216,7 +221,9 @@ class Sidecar(unittest.TestCase):out = Path(tmp) / "x_film.mp4"def fake_ffmpeg(cmd, *a, **kw):- out.write_bytes(b"\0" * 4096)+ # The encoder writes its OWN last argument — a hidden sibling+ # that replaces the film only once it is whole (SB5-06).+ Path(cmd[-1]).write_bytes(b"\0" * 4096)probe = {"w": 1024, "h": 576, "duration": 5.0,"has_audio": True, "sample_rate": 48000}diff --git a/test_storyboard_film_integrity.py b/test_storyboard_film_integrity.pynew file mode 100644index 0000000..dbc3037--- /dev/null+++ b/test_storyboard_film_integrity.py@@ -0,0 +1,249 @@+#!/usr/bin/env python3+"""A finished film is a thing the panel must not lose, and must not share.++ * SB5-05 the film folder was `<day>_<title slug>`: two boards made the same+ day with the same title — or any two with non-Latin titles, which+ slug to "shot" — wrote into one folder and overwrote each other's+ film, shot copies and manifests.+ * SB5-06 the encoder wrote straight over the last good film and deleted it+ on failure, so a failed or cancelled re-render lost the film that+ had already worked.+ * SB5-13 a still (or a black slug) with a fade previewed the fade and+ rendered a hard cut: the segment builder dropped its `fx`.++Everything runs against a scratch OUTPUT/STATE_DIR; ffmpeg and ffprobe are+mocked. Nothing here reaches the live state or output tree.+"""+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++DAY = 1_700_050_000 # 2023-11-15 midday UTC: one date in every zone ±11h+++def _board(bid, title, created=DAY):+ return {"schema": 1, "id": bid, "title": title, "created_at": created,+ "policy": storyboard.default_policy(), "cast": [],+ "engine_mode": "ltx", "shots": []}+++class Sandbox(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ root = Path(self.tmp.name)+ self.state, self.out = root / "state", root / "outputs"+ self.state.mkdir()+ self.out.mkdir()+ for p in (mock.patch.object(panel, "STATE_DIR", self.state),+ mock.patch.object(panel, "OUTPUT", self.out),+ mock.patch.object(panel, "push", lambda *a, **k: None)):+ p.start()+ self.addCleanup(p.stop)++ def save(self, board):+ storyboard.save_storyboard(self.state, board)+ return board+++class FilmFolderBelongsToOneBoard(Sandbox):+ """SB5-05."""++ def test_same_day_same_title_is_two_folders_and_two_films(self):+ a = self.save(_board("sb_20231115_aaaaaa", "Night Drive"))+ b = self.save(_board("sb_20231115_bbbbbb", "Night Drive"))+ da, db = panel._sb_film_dir(a), panel._sb_film_dir(b)+ self.assertNotEqual(da, db)+ self.assertNotEqual(da / panel._sb_film_name(a),+ db / panel._sb_film_name(b))++ def test_japanese_titles_do_not_collapse_into_one_folder(self):+ a = self.save(_board("sb_20231115_111111", "京都の夜"))+ b = self.save(_board("sb_20231115_222222", "東京の朝"))+ self.assertNotEqual(panel._sb_film_dir(a), panel._sb_film_dir(b))++ def test_the_first_six_words_matching_is_not_identity(self):+ t = "one two three four five six"+ a = self.save(_board("sb_20231115_333333", t + " seven"))+ b = self.save(_board("sb_20231115_444444", t + " eight"))+ self.assertNotEqual(panel._sb_film_dir(a), panel._sb_film_dir(b))++ def test_a_board_that_already_exported_keeps_its_folder(self):+ # MIGRATION: an Export wrote storyboard.json (with the board's id)+ # into the old-style folder. That board keeps it, so its films stay+ # listed; a newcomer with the same day and title does not get it.+ a = self.save(_board("sb_20231115_aaaaaa", "Night Drive"))+ legacy = self.out / "storyboards" / panel._sb_film_dir(a).name+ legacy = legacy.parent / legacy.name.rsplit("_", 1)[0]+ legacy.mkdir(parents=True)+ (legacy / "storyboard.json").write_text(json.dumps(a))+ (legacy / "night-drive_film.mp4").write_bytes(b"A's film")+ b = self.save(_board("sb_20231115_bbbbbb", "Night Drive", DAY - 3600))+ self.assertEqual(panel._sb_film_dir(a), legacy)+ self.assertNotEqual(panel._sb_film_dir(b), legacy)+ self.assertEqual([f["name"] for f in panel._sb_films(a, probe=False)],+ ["night-drive_film.mp4"])+ self.assertEqual(panel._sb_films(b, probe=False), [])++ def test_an_unmarked_old_folder_goes_to_the_oldest_board_with_that_name(self):+ # Timeline renders wrote no manifest, so the folder says nothing about+ # whose it is. The board made first made it.+ a = self.save(_board("sb_20231115_aaaaaa", "Night Drive", DAY))+ b = self.save(_board("sb_20231115_bbbbbb", "Night Drive", DAY + 60))+ legacy = self.out / "storyboards" / (+ panel._sb_film_dir(b).name.rsplit("_", 1)[0])+ legacy.mkdir(parents=True)+ (legacy / "night-drive_film.mp4").write_bytes(b"somebody's film")+ self.assertEqual(panel._sb_film_dir(a), legacy)+ self.assertNotEqual(panel._sb_film_dir(b), legacy)++ def test_writing_a_film_marks_the_folder_as_this_boards(self):+ a = self.save(_board("sb_20231115_aaaaaa", "Night Drive", DAY))+ d = panel._sb_film_dir_for_write(a)+ self.assertTrue(d.is_dir())+ self.assertEqual(panel._sb_film_owner(d), a["id"])++ def test_a_board_alone_with_its_old_folder_keeps_it(self):+ a = self.save(_board("sb_divorce_v2", "Divorce"))+ legacy = self.out / "storyboards" / (+ panel._sb_film_dir(a).name.rsplit("_", 1)[0])+ # (The scoped name for a non-minted id still starts with the legacy+ # one; that is what rsplit relies on.)+ self.assertTrue(panel._sb_film_dir(a).name.startswith(legacy.name))+ legacy.mkdir(parents=True)+ self.assertEqual(panel._sb_film_dir(a), legacy)+++def _probe(w, h, duration, *, audio=True, rate=48000):+ return {"w": w, "h": h, "duration": duration,+ "has_audio": audio, "sample_rate": rate if audio else 0}+++class AFailedRenderKeepsTheLastFilm(unittest.TestCase):+ """SB5-06."""++ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ self.dir = Path(self.tmp.name)+ self.clip = self.dir / "a.mp4"+ self.clip.write_bytes(b"clip")+ self.film = self.dir / "night-drive_film.mp4"+ self.film.write_bytes(b"THE GOOD FILM")+ panel._sb_film_sidecar(self.film).write_text('{"film": "good"}')++ def _assemble(self, ffmpeg):+ with mock.patch.object(panel, "_sb_probe_clip",+ return_value=_probe(640, 448, 3.0)), \+ mock.patch.object(panel, "run_ffmpeg_tracked", side_effect=ffmpeg), \+ mock.patch.object(panel, "output_codec_settings",+ return_value={"pix_fmt": "yuv420p", "crf": "18"}):+ return panel._sb_assemble_film([self.clip], self.film)++ def _leftovers(self):+ return sorted(p.name for p in self.dir.iterdir()+ if p.name not in {"a.mp4", self.film.name,+ self.film.name + ".json"})++ def test_a_crash_after_partial_bytes_keeps_the_old_film_and_sidecar(self):+ def half(cmd, label):+ Path(cmd[-1]).write_bytes(b"half a film")+ raise RuntimeError("exited with code 1")+ res = self._assemble(half)+ self.assertFalse(res["ok"])+ self.assertEqual(self.film.read_bytes(), b"THE GOOD FILM")+ self.assertEqual(panel._sb_film_sidecar(self.film).read_text(),+ '{"film": "good"}')+ self.assertEqual(self._leftovers(), [])++ def test_a_failure_before_any_bytes_keeps_the_old_film(self):+ def dead(cmd, label):+ raise RuntimeError("cancelled")+ self.assertFalse(self._assemble(dead)["ok"])+ self.assertEqual(self.film.read_bytes(), b"THE GOOD FILM")+ self.assertEqual(self._leftovers(), [])++ def test_an_encoder_that_writes_nothing_keeps_the_old_film(self):+ self.assertFalse(self._assemble(lambda c, l: ("", ""))["ok"])+ self.assertEqual(self.film.read_bytes(), b"THE GOOD FILM")+ self.assertEqual(self._leftovers(), [])++ def test_a_good_render_replaces_it(self):+ def ok(cmd, label):+ # Never the finished name while it is being written.+ self.assertNotEqual(Path(cmd[-1]), self.film)+ self.assertEqual(Path(cmd[-1]).suffix, ".mp4")+ Path(cmd[-1]).write_bytes(b"THE NEW FILM")+ return "", ""+ res = self._assemble(ok)+ self.assertTrue(res["ok"])+ self.assertEqual(res["path"], str(self.film))+ self.assertEqual(self.film.read_bytes(), b"THE NEW FILM")+ self.assertEqual(self._leftovers(), [])++ def test_the_film_list_never_shows_a_film_still_being_written(self):+ board = _board("sb_20231115_aaaaaa", "Night Drive")+ with mock.patch.object(panel, "_sb_film_dir", return_value=self.dir):+ (self.dir / ".night-drive_film.part-1234abcd.mp4").write_bytes(b"x")+ names = [f["name"] for f in panel._sb_films(board, probe=False)]+ self.assertIn(self.film.name, names)+ self.assertFalse([n for n in names if n.startswith(".")], names)++++class StillFadesReachTheEncoder(unittest.TestCase):+ """SB5-13 — the same fade on a still, a slug and a video, end to end."""++ def _segments(self):+ fx = {"fade_in": 1.0, "fade_out": 0.5}+ edit = {"version": sedit.EDIT_VERSION, "board_id": "sb_t", "revision": 1,+ "source": "human", "audio": None, "beats": None, "settings": {},+ "clips": [+ dict(sedit.new_clip("/x/card.png", 0.0, 3.0, 0.0,+ source="human"), kind="still", fx=fx),+ dict(sedit.new_clip("", 0.0, 2.0, 3.0, source="human"),+ kind="slug", path=None, fx=fx),+ dict(sedit.new_clip("/x/a.mp4", 0.0, 4.0, 5.0,+ source="human", duration=10.0), fx=fx),+ ]}+ cuts = sedit.edit_to_cuts(sedit.normalise_edit(edit))+ self.assertEqual([c.get("fx") for c in cuts], [fx] * 3)+ info = {"w": 768, "h": 416, "duration": 10.0, "has_audio": False,+ "sample_rate": 0}+ with mock.patch.object(panel, "_sb_probe_still", return_value=dict(info)), \+ mock.patch.object(panel, "_sb_probe_clip", return_value=dict(info)):+ segs, unreadable, _ = panel._sb_timeline_segments(cuts)+ self.assertEqual(unreadable, [])+ return segs++ def test_every_kind_of_segment_keeps_its_fade(self):+ segs = self._segments()+ self.assertEqual([s["kind"] for s in segs], ["still", "slug", "video"])+ for s in segs:+ self.assertEqual(s.get("fx"), {"fade_in": 1.0, "fade_out": 0.5},+ s["kind"])++ def test_the_graph_fades_the_still(self):+ segs = self._segments()+ with mock.patch.object(panel, "bt709_vf", return_value=""):+ g, _ = panel._sb_film_filtergraph([], 768, 416, 48000, "yuv420p",+ segments=segs)+ still_chain = next(c for c in g.split(";") if c.startswith("[0:v]"))+ self.assertIn("fade=t=in", still_chain)+ self.assertIn("fade=t=out", still_chain)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_take.py b/test_take.pyindex 3651689..6d8bc41 100644--- a/test_take.py+++ b/test_take.py@@ -186,7 +186,7 @@ def test_take_runner_stops_between_parts(tmp_path, monkeypatch):job["cancel_requested"] = True # Stop pressed during part 1monkeypatch.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"):+ with pytest.raises(RuntimeError, match="(?i)stopped"):p.run_take_job_inner(job)diff --git a/test_trash_collisions.py b/test_trash_collisions.pynew file mode 100644index 0000000..598b407--- /dev/null+++ b/test_trash_collisions.py@@ -0,0 +1,86 @@+"""Delete to Trash never overwrites something already in the Trash (Codex UI-05).++Same-seed image batches share basenames (`cand_42_mflux.png`). The delete route+checked only the plain name, then fell back to ONE timestamp-suffixed name it+never checked: two deletions in the same second overwrote the first trashed+image. HOME is a temp dir here — nothing reaches the real ~/.Trash.+"""+from __future__ import annotations++import sys+import tempfile+import threading+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 P # noqa: E402++routes_files = sys.modules["panel.routes_files"]+++class _H:+ def __init__(self, target):+ self.target, self.status, self.payload = target, None, None++ def _read_form_body(self):+ return ("", {"path": [str(self.target)]})++ def _json(self, payload, status=200):+ self.payload, self.status = payload, status+++class TrashNeverOverwrites(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ base = Path(self.tmp.name).resolve()+ self.home, self.out = base / "home", base / "out"+ (self.home / ".Trash").mkdir(parents=True)+ self.out.mkdir()+ self._patches = [+ mock.patch("pathlib.Path.home", lambda *a: self.home),+ mock.patch.object(P, "OUTPUT", self.out),+ mock.patch.object(P, "UPLOADS", base / "up"),+ mock.patch.object(P.time, "strftime", lambda *a, **k: "20260924-120000"),+ mock.patch.object(P, "set_hidden", lambda *a, **k: None),+ ]+ for p in self._patches:+ p.start()++ def tearDown(self):+ for p in reversed(self._patches):+ p.stop()+ self.tmp.cleanup()++ def _batch(self, n: int) -> Path:+ d = self.out / f"batch{n}"+ d.mkdir()+ f = d / "cand_42_mflux.png"+ f.write_bytes(f"image {n}".encode())+ Path(str(f) + ".json").write_text(f'{{"batch": {n}}}')+ return f++ def test_three_same_named_deletes_in_one_second_all_survive(self):+ files = [self._batch(i) for i in range(3)]+ routes_files.post_output_delete(_H(files[0]), "/output/delete", {}, "")+ hs = [_H(f) for f in files[1:]]+ ts = [threading.Thread(target=routes_files.post_output_delete,+ args=(h, "/output/delete", {}, "")) for h in hs]+ for t in ts:+ t.start()+ for t in ts:+ t.join(10)+ for h in hs:+ self.assertEqual(h.status, 200, h.payload)+ trash = self.home / ".Trash"+ pngs = sorted(p.read_bytes() for p in trash.glob("cand_42_mflux*.png"))+ self.assertEqual(pngs, [b"image 0", b"image 1", b"image 2"])+ sidecars = sorted(p.read_text() for p in trash.glob("*.json"))+ self.assertEqual(len(sidecars), 3, sidecars)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_uploads_listing.py b/test_uploads_listing.pynew file mode 100644index 0000000..eb84808--- /dev/null+++ b/test_uploads_listing.py@@ -0,0 +1,40 @@+"""Recent uploads lists the user's images, not the panel's own crops (Codex H3-06).++H3 writes a fitted first frame per job into the uploads folder as a dot-file.+list_uploads() filtered only by type and extension, so after 24 H3 renders the+Recent-uploads strip held nothing but crops and the original was gone from it.+"""+from __future__ import annotations++import os+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 P # noqa: E402+++class RecentUploads(unittest.TestCase):+ def test_internal_h3_crops_never_displace_the_original(self):+ with tempfile.TemporaryDirectory() as tmp:+ up = Path(tmp)+ orig = up / "1727000000000_portrait.png"+ orig.write_bytes(b"x")+ old = time.time() - 3600+ os.utime(orig, (old, old))+ for i in range(40):+ (up / f".h3_job{i}_firstframe_1280x704.png").write_bytes(b"x")+ with mock.patch.object(P, "UPLOADS", up):+ got = P.list_uploads(limit=24)+ self.assertEqual([u["path"] for u in got], [str(orig)])+ self.assertEqual(got[0]["name"], "portrait.png")+++if __name__ == "__main__":+ unittest.main()diff --git a/test_version_pull_route.py b/test_version_pull_route.pynew file mode 100644index 0000000..f308aa0--- /dev/null+++ b/test_version_pull_route.py@@ -0,0 +1,157 @@+"""The in-panel Update (POST /version/pull) against REAL throwaway git repos.++Codex INST-01 (2026-09-24): any `pull --ff-only` failure was read as history+divergence and answered with `reset --hard origin/main` — including git's own+"untracked working tree files would be overwritten", so the reset destroyed the+file git had just refused to touch. And `pull --ff-only` itself silently+overwrites an IGNORED file where upstream now tracks one. The route now runs the+sidebar's obstruction guard first and resets only on divergence proven against+the fetched origin/main.++Codex INST-12: a pull that changes only the music-engine pin must ask for the+full Pinokio Update, since only that runs music_checkout.sh.++Nothing here touches the real checkout: P.ROOT and _git_capture are pointed at+a temp clone for the duration of each test.+"""+from __future__ import annotations++import os+import shutil+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 P # noqa: E402++routes_meta = sys.modules["panel.routes_meta"]+GIT_ENV = dict(os.environ, GIT_CONFIG_GLOBAL="/dev/null", GIT_CONFIG_SYSTEM="/dev/null",+ GIT_AUTHOR_NAME="t", GIT_AUTHOR_EMAIL="t@t", GIT_COMMITTER_NAME="t",+ GIT_COMMITTER_EMAIL="t@t")+++def git(cwd: Path, *args: str) -> str:+ return subprocess.run(["git", *args], cwd=str(cwd), env=GIT_ENV, check=True,+ capture_output=True, text=True, errors="replace").stdout.strip()+++class _H:+ def __init__(self):+ self.status, self.payload = None, None++ def _json(self, payload, status=200):+ self.payload, self.status = payload, status++[email protected](shutil.which("git"), "git not on PATH")+class VersionPull(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ base = Path(self.tmp.name)+ self.up, self.clone = base / "up", base / "clone"+ self.up.mkdir()+ git(self.up, "init", "-q", "-b", "main", ".")+ (self.up / "f.txt").write_text("v1\n")+ guard = ROOT / "scripts" / "pinokio" / "update_obstruction_guard.sh"+ (self.up / "scripts" / "pinokio").mkdir(parents=True)+ shutil.copy(guard, self.up / "scripts" / "pinokio" / guard.name)+ git(self.up, "add", ".")+ git(self.up, "commit", "-qm", "v1")+ git(base, "clone", "-q", str(self.up), str(self.clone))+ real_capture = P._git_capture+ self._patches = [+ mock.patch.object(P, "ROOT", self.clone),+ mock.patch.object(P, "_git_capture",+ lambda args, cwd=None: real_capture(args, cwd=self.clone)),+ mock.patch.object(P, "_detect_local_install_state", lambda: None),+ mock.patch.object(P, "_check_remote_once", lambda: None),+ mock.patch.object(P, "get_version_state", lambda: {}),+ mock.patch.dict(P._VERSION_STATE, {}, clear=False),+ mock.patch.dict(os.environ, {"GIT_CONFIG_GLOBAL": "/dev/null",+ "GIT_CONFIG_SYSTEM": "/dev/null"}),+ ]+ for p in self._patches:+ p.start()++ def tearDown(self):+ for p in reversed(self._patches):+ p.stop()+ self.tmp.cleanup()++ def _upstream_adds(self, rel: str, text: str = "upstream\n"):+ f = self.up / rel+ f.parent.mkdir(parents=True, exist_ok=True)+ f.write_text(text)+ git(self.up, "add", rel)+ git(self.up, "commit", "-qm", f"add {rel}")++ def _pull(self) -> _H:+ h = _H()+ routes_meta.post_version_pull(h, "/version/pull", {}, "")+ return h++ def test_untracked_obstruction_is_refused_not_reset(self):+ self._upstream_adds("notes.txt")+ (self.clone / "notes.txt").write_text("MINE\n")+ head = git(self.clone, "rev-parse", "HEAD")+ h = self._pull()+ self.assertFalse(h.payload["ok"], h.payload)+ self.assertEqual((self.clone / "notes.txt").read_text(), "MINE\n")+ self.assertEqual(git(self.clone, "rev-parse", "HEAD"), head)++ def test_ignored_obstruction_is_not_overwritten_by_the_fast_forward(self):+ self._upstream_adds("ignored.txt")+ with open(self.clone / ".git" / "info" / "exclude", "a") as fh:+ fh.write("\nignored.txt\n")+ (self.clone / "ignored.txt").write_text("MINE\n")+ h = self._pull()+ self.assertFalse(h.payload["ok"], h.payload)+ self.assertEqual((self.clone / "ignored.txt").read_text(), "MINE\n")++ def test_diverged_history_with_an_obstruction_is_not_reset(self):+ # upstream rewrote v1 (force-push) AND now tracks notes.txt+ git(self.up, "commit", "-q", "--amend", "-m", "v1 rewritten")+ self._upstream_adds("notes.txt")+ (self.clone / "notes.txt").write_text("MINE\n")+ h = self._pull()+ self.assertFalse(h.payload["ok"], h.payload)+ self.assertEqual((self.clone / "notes.txt").read_text(), "MINE\n")++ def test_proven_divergence_on_a_clean_tree_still_converges(self):+ git(self.up, "commit", "-q", "--amend", "-m", "v1 rewritten")+ h = self._pull()+ self.assertTrue(h.payload["ok"], h.payload)+ self.assertEqual(git(self.clone, "rev-parse", "HEAD"),+ git(self.up, "rev-parse", "HEAD"))++ def test_plain_fast_forward(self):+ (self.up / "f.txt").write_text("v2\n")+ git(self.up, "commit", "-qam", "v2")+ h = self._pull()+ self.assertTrue(h.payload["ok"], h.payload)+ self.assertEqual((self.clone / "f.txt").read_text(), "v2\n")+ self.assertFalse(P._VERSION_STATE["pull_requires_full_update"])++ def test_music_pin_only_pull_requires_the_full_update(self):+ self._upstream_adds("scripts/music/engine_pin.txt", "a" * 40 + "\n")+ h = self._pull()+ self.assertTrue(h.payload["ok"], h.payload)+ self.assertTrue(P._VERSION_STATE["pull_requires_full_update"])++ def test_build_constraints_and_engine_installers_require_the_full_update(self):+ for rel in ("pip-build-constraints.txt", "install_music.js"):+ with self.subTest(rel=rel):+ self._upstream_adds(rel, f"{rel}\n")+ h = self._pull()+ self.assertTrue(h.payload["ok"], h.payload)+ self.assertTrue(P._VERSION_STATE["pull_requires_full_update"])+++if __name__ == "__main__":+ unittest.main()diff --git a/test_yue2_lora.py b/test_yue2_lora.pynew file mode 100644index 0000000..15fc2bd--- /dev/null+++ b/test_yue2_lora.py@@ -0,0 +1,997 @@+"""YuE2 LoRA inference: the rules an adapter has to obey before it runs.++CPU only, tiny fake models, no YuE2 weights. What is pinned here:++ * one canonical spelling for the half-dozen key layouts an adapter arrives in;+ * a delta is refused unless its shapes match the model that will run it;+ * the wrapped projection computes exactly `W x + strength · B (A x)` — checked+ against the arithmetic written out by hand, on a plain AND a quantised base;+ * wrapping does not rename one parameter, because `lyra.nar.load_nar()`+ validates the shared AR model by exact tensor name;+ * `joint` never touches the decoder's I/O projections, `separate` replaces+ them with a strength-weighted blend;+ * the instrumental recipe is Maestro's: AR adapter at 1.0, `cot=full`,+ `[instrumental]` in place of sung prose;+ * the panel's form → argv round trip carries the picks and refuses paths+ from outside the LoRA folder.+"""+from __future__ import annotations++import hashlib+import json+import os+from pathlib import Path+import sys+import tempfile+import types+import unittest+from unittest import mock+from urllib.parse import parse_qs, urlencode++import mlx.core as mx+import mlx.nn as nn+import numpy as np++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT / "scripts" / "music"))+os.environ.setdefault("LTX_STATE_DIR", tempfile.mkdtemp(prefix="yue2-lora-state-"))+os.environ["PHOSPHENE_ANALYTICS_DISABLED"] = "1"+os.environ["PHOSPHENE_DISABLE_VERSION_CHECK"] = "1"++import yue2_lora as L # noqa: E402+from scripts.pinokio import music_lora_fetch as F # noqa: E402++HIDDEN, KV, INTERMEDIATE, LAYERS, RANK = 32, 16, 64, 2, 4+LATENT = 8+++class _Attention(nn.Module):+ def __init__(self):+ super().__init__()+ self.q_proj = nn.Linear(HIDDEN, HIDDEN, bias=False)+ self.k_proj = nn.Linear(HIDDEN, KV, bias=False)+ self.v_proj = nn.Linear(HIDDEN, KV, bias=False)+ self.o_proj = nn.Linear(HIDDEN, HIDDEN, bias=False)+++class _MLP(nn.Module):+ def __init__(self):+ super().__init__()+ self.gate_proj = nn.Linear(HIDDEN, INTERMEDIATE, bias=False)+ self.up_proj = nn.Linear(HIDDEN, INTERMEDIATE, bias=False)+ self.down_proj = nn.Linear(INTERMEDIATE, HIDDEN, bias=False)+++class _Layer(nn.Module):+ def __init__(self, branch):+ super().__init__()+ attn, mlp = L.BRANCH_GROUPS[branch]+ setattr(self, attn, _Attention())+ setattr(self, mlp, _MLP())+++class _Backbone(nn.Module):+ def __init__(self, branch):+ super().__init__()+ self.layers = [_Layer(branch) for _ in range(LAYERS)]+++class _Model(nn.Module):+ """Small stand-in with lyra's attribute names (`model.layers[i]....`)."""++ def __init__(self, branch="ar", *, io=False):+ super().__init__()+ self.model = _Backbone(branch)+ if io:+ self.llm2vae = nn.Linear(HIDDEN, LATENT)+ self.vae2llm = nn.Linear(LATENT, HIDDEN)+ self.set_dtype(mx.bfloat16)+++def _pair(out_features, in_features, rank=RANK, seed=0):+ rng = np.random.default_rng(seed)+ a = mx.array(rng.standard_normal((rank, in_features)) * 0.05, dtype=mx.bfloat16)+ b = mx.array(rng.standard_normal((out_features, rank)) * 0.05, dtype=mx.bfloat16)+ return a, b+++def _write(path, tensors):+ mx.save_safetensors(str(path), tensors)+ return Path(str(path) + ("" if str(path).endswith(".safetensors") else ".safetensors"))+++def _full_file(path, branch, *, rank=RANK, io=False, spelling="lora_A", prefix=""):+ attn, mlp = L.BRANCH_GROUPS[branch]+ tensors = {}+ widths = {"q_proj": (HIDDEN, HIDDEN), "k_proj": (KV, HIDDEN), "v_proj": (KV, HIDDEN),+ "o_proj": (HIDDEN, HIDDEN)}+ mlp_widths = {"gate_proj": (INTERMEDIATE, HIDDEN), "up_proj": (INTERMEDIATE, HIDDEN),+ "down_proj": (HIDDEN, INTERMEDIATE)}+ lo, hi = ("lora_A", "lora_B") if spelling == "lora_A" else ("A", "B")+ for index in range(LAYERS):+ for group, table in ((attn, widths), (mlp, mlp_widths)):+ for name, (out_features, in_features) in table.items():+ a, b = _pair(out_features, in_features, rank, seed=index * 17 + len(tensors))+ stem = f"{prefix}layers.{index}.{group}.{name}"+ tensors[f"{stem}.{lo}"] = a+ tensors[f"{stem}.{hi}"] = b+ if io:+ tensors["vae2llm.weight"] = mx.zeros((HIDDEN, LATENT), dtype=mx.bfloat16) + 0.25+ tensors["vae2llm.bias"] = mx.zeros((HIDDEN,), dtype=mx.bfloat16) + 0.5+ tensors["llm2vae.weight"] = mx.zeros((LATENT, HIDDEN), dtype=mx.bfloat16) + 0.125+ tensors["llm2vae.bias"] = mx.zeros((LATENT,), dtype=mx.bfloat16) + 0.75+ mx.save_safetensors(str(path), tensors)+ return Path(path)+++class KeyMapping(unittest.TestCase):++ def test_every_published_spelling_lands_on_one_name(self):+ for spelling in (+ "layers.3.mlp.up_proj.lora_A",+ "model.layers.3.mlp.up_proj.lora_A",+ "base_model.model.model.layers.3.mlp.up_proj.lora_A.default.weight",+ "base_model.model.layers.3.mlp.up_proj.lora_A.weight",+ "transformer.layers.3.mlp.up_proj.lora_down.weight",+ "model.layers.3.mlp.up_proj.A",+ ):+ self.assertEqual(L.normalize_key(spelling), "layers.3.mlp.up_proj.lora_A",+ f"{spelling} mapped wrong")+ self.assertEqual(L.normalize_key("layers.0.nar_mlp.down_proj.lora_up.weight"),+ "layers.0.nar_mlp.down_proj.lora_B")++ def test_the_branch_is_read_off_the_keys(self):+ self.assertEqual(L.branch_of(["layers.0.mlp.up_proj.lora_A"]), "ar")+ self.assertEqual(L.branch_of(["layers.0.nar_self_attn.q_proj.lora_A"]), "nar")++ def test_a_strength_outside_the_dial_is_refused(self):+ for bad in (-0.1, 1.6, "loud", None):+ with self.assertRaises(ValueError):+ L.validate_strength(bad)+ self.assertEqual(L.validate_strength("0.75"), 0.75)++ def test_a_spec_splits_only_on_a_real_number(self):+ self.assertEqual(L.parse_spec("/x/y.safetensors:0.4"), ("/x/y.safetensors", 0.4))+ self.assertEqual(L.parse_spec("/x/a:b.safetensors"), ("/x/a:b.safetensors", 1.0))+++class Reading(unittest.TestCase):++ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.dir = Path(self.tmp.name)+ self.addCleanup(self.tmp.cleanup)++ def test_a_full_ar_file_reads_with_one_rank_and_every_target(self):+ path = _full_file(self.dir / "ar.safetensors", "ar")+ adapter = L.read_adapter(path, strength=0.5)+ self.assertEqual(adapter.branch, "ar")+ self.assertEqual(adapter.rank, RANK)+ self.assertEqual(len(adapter.deltas), LAYERS * 7)+ self.assertEqual(adapter.strength, 0.5)+ self.assertEqual(adapter.summary()["file"], "ar.safetensors")++ def test_maestros_own_spelling_and_a_model_prefix_read_the_same(self):+ plain = L.read_adapter(_full_file(self.dir / "a.safetensors", "ar"))+ other = L.read_adapter(_full_file(self.dir / "b.safetensors", "ar",+ spelling="A", prefix="model."))+ self.assertEqual(sorted(plain.deltas), sorted(other.deltas))++ def test_a_half_pair_and_a_mixed_rank_are_refused(self):+ tensors = {"layers.0.mlp.up_proj.lora_A": _pair(INTERMEDIATE, HIDDEN)[0]}+ mx.save_safetensors(str(self.dir / "half.safetensors"), tensors)+ with self.assertRaisesRegex(ValueError, "missing its lora_B"):+ L.read_adapter(self.dir / "half.safetensors")+ a1, b1 = _pair(INTERMEDIATE, HIDDEN, rank=4)+ a2, b2 = _pair(INTERMEDIATE, HIDDEN, rank=8)+ mx.save_safetensors(str(self.dir / "ranks.safetensors"), {+ "layers.0.mlp.up_proj.lora_A": a1, "layers.0.mlp.up_proj.lora_B": b1,+ "layers.0.mlp.gate_proj.lora_A": a2, "layers.0.mlp.gate_proj.lora_B": b2})+ with self.assertRaisesRegex(ValueError, "one rank per adapter"):+ L.read_adapter(self.dir / "ranks.safetensors")++ def test_a_tensor_we_do_not_understand_stops_the_song(self):+ a, b = _pair(INTERMEDIATE, HIDDEN)+ mx.save_safetensors(str(self.dir / "odd.safetensors"), {+ "layers.0.mlp.up_proj.lora_A": a, "layers.0.mlp.up_proj.lora_B": b,+ "some.other.tensor": mx.zeros((2, 2))})+ with self.assertRaisesRegex(ValueError, "unsupported tensor targets"):+ L.read_adapter(self.dir / "odd.safetensors")++ def test_a_peft_alpha_is_folded_into_b(self):+ a, b = _pair(INTERMEDIATE, HIDDEN, rank=4, seed=3)+ base = {"layers.0.mlp.up_proj.lora_A": a, "layers.0.mlp.up_proj.lora_B": b}+ mx.save_safetensors(str(self.dir / "plain.safetensors"), base)+ mx.save_safetensors(str(self.dir / "alpha.safetensors"),+ {**base, "layers.0.mlp.up_proj.alpha": mx.array([8.0])})+ without = L.read_adapter(self.dir / "plain.safetensors").deltas["layers.0.mlp.up_proj"][1]+ with_alpha = L.read_adapter(self.dir / "alpha.safetensors").deltas["layers.0.mlp.up_proj"][1]+ self.assertLess(float(mx.abs(with_alpha.astype(mx.float32)+ - without.astype(mx.float32) * 2.0).max()), 0.02)++ def test_a_decoder_companion_has_to_be_complete_and_acoustic(self):+ path = _full_file(self.dir / "nar.safetensors", "nar", io=True)+ adapter = L.read_adapter(path, mode="separate")+ self.assertEqual(adapter.branch, "nar")+ self.assertEqual(len(adapter.io), 4)+ joint = L.read_adapter(path, mode="joint")+ self.assertEqual(joint.io, {})+ self.assertTrue(joint.ignored_io)+++class WrapperMath(unittest.TestCase):++ def _manual(self, weight, x, stack):+ out = x.astype(mx.float32) @ weight.astype(mx.float32).T+ for a, b, scale in stack:+ delta = (x.astype(mx.bfloat16) @ a.T) @ b.T+ out = out + delta.astype(mx.float32) * scale+ return out++ def test_a_wrapped_projection_is_w_x_plus_scale_b_a_x(self):+ tmp = tempfile.TemporaryDirectory()+ self.addCleanup(tmp.cleanup)+ path = _full_file(Path(tmp.name) / "ar.safetensors", "ar")+ model = _Model("ar")+ adapter = L.read_adapter(path, strength=0.7)+ weight = model.model.layers[0].mlp.up_proj.weight+ L.apply_adapters(model, "ar", [adapter])+ rng = np.random.default_rng(11)+ x = mx.array(rng.standard_normal((1, 3, HIDDEN)), dtype=mx.bfloat16)+ got = model.model.layers[0].mlp.up_proj(x)+ a, b = adapter.deltas["layers.0.mlp.up_proj"]+ want = self._manual(weight, x, [(a, b, 0.7)])+ self.assertLess(float(mx.abs(got.astype(mx.float32) - want).max()), 0.05)++ def test_two_adapters_add_their_deltas(self):+ tmp = tempfile.TemporaryDirectory()+ self.addCleanup(tmp.cleanup)+ first = L.read_adapter(_full_file(Path(tmp.name) / "1.safetensors", "ar"), strength=0.3)+ second = L.read_adapter(_full_file(Path(tmp.name) / "2.safetensors", "ar"), strength=0.9)+ model = _Model("ar")+ weight = model.model.layers[1].self_attn.k_proj.weight+ L.apply_adapters(model, "ar", [first, second])+ rng = np.random.default_rng(5)+ x = mx.array(rng.standard_normal((1, 2, HIDDEN)), dtype=mx.bfloat16)+ got = model.model.layers[1].self_attn.k_proj(x)+ stack = [(*first.deltas["layers.1.self_attn.k_proj"], 0.3),+ (*second.deltas["layers.1.self_attn.k_proj"], 0.9)]+ self.assertLess(float(mx.abs(got.astype(mx.float32) - self._manual(weight, x, stack)).max()), 0.05)++ def test_it_works_on_a_quantised_base_too(self):+ """The AR model runs 8-bit by default — a merge would not be possible."""+ tmp = tempfile.TemporaryDirectory()+ self.addCleanup(tmp.cleanup)+ adapter = L.read_adapter(_full_file(Path(tmp.name) / "q.safetensors", "ar"), strength=1.0)+ model = _Model("ar")+ nn.quantize(model, group_size=32, bits=8, mode="affine",+ class_predicate=lambda _p, m: isinstance(m, nn.Linear))+ module = model.model.layers[0].mlp.up_proj+ self.assertIsInstance(module, nn.QuantizedLinear)+ self.assertEqual(L.linear_shape(module), (INTERMEDIATE, HIDDEN))+ rng = np.random.default_rng(7)+ x = mx.array(rng.standard_normal((1, 2, HIDDEN)), dtype=mx.bfloat16)+ before = module(x)+ L.apply_adapters(model, "ar", [adapter])+ after = model.model.layers[0].mlp.up_proj(x)+ a, b = adapter.deltas["layers.0.mlp.up_proj"]+ delta = ((x @ a.T) @ b.T).astype(mx.float32)+ self.assertLess(float(mx.abs((after - before).astype(mx.float32) - delta).max()), 0.05)++ def test_applying_twice_replaces_the_stack_rather_than_doubling_it(self):+ tmp = tempfile.TemporaryDirectory()+ self.addCleanup(tmp.cleanup)+ adapter = L.read_adapter(_full_file(Path(tmp.name) / "a.safetensors", "ar"))+ model = _Model("ar")+ rng = np.random.default_rng(2)+ x = mx.array(rng.standard_normal((1, 2, HIDDEN)), dtype=mx.bfloat16)+ L.apply_adapters(model, "ar", [adapter])+ once = model.model.layers[0].mlp.up_proj(x)+ L.apply_adapters(model, "ar", [adapter])+ twice = model.model.layers[0].mlp.up_proj(x)+ self.assertLess(float(mx.abs((once - twice).astype(mx.float32)).max()), 1e-6)+++class Attachment(unittest.TestCase):++ def test_wrapping_renames_nothing_and_unwraps_clean(self):+ """`lyra.nar.load_nar()` validates the AR model by exact tensor name."""+ from mlx.utils import tree_flatten+ tmp = tempfile.TemporaryDirectory()+ self.addCleanup(tmp.cleanup)+ adapter = L.read_adapter(_full_file(Path(tmp.name) / "a.safetensors", "ar"))+ model = _Model("ar")+ before = sorted(k for k, _ in tree_flatten(model.parameters()))+ L.apply_adapters(model, "ar", [adapter])+ self.assertTrue(L.is_adapted(model))+ self.assertEqual(sorted(k for k, _ in tree_flatten(model.parameters())), before)+ self.assertEqual(L.remove_adapters(model), LAYERS * 7)+ self.assertFalse(L.is_adapted(model))+ self.assertEqual(sorted(k for k, _ in tree_flatten(model.parameters())), before)++ def test_a_shape_that_does_not_fit_the_model_is_named(self):+ tmp = tempfile.TemporaryDirectory()+ self.addCleanup(tmp.cleanup)+ a, b = _pair(INTERMEDIATE + 8, HIDDEN)+ mx.save_safetensors(str(Path(tmp.name) / "bad.safetensors"),+ {"layers.0.mlp.up_proj.lora_A": a, "layers.0.mlp.up_proj.lora_B": b})+ adapter = L.read_adapter(Path(tmp.name) / "bad.safetensors")+ with self.assertRaisesRegex(ValueError, "layers.0.mlp.up_proj expects"):+ L.apply_adapters(_Model("ar"), "ar", [adapter])++ def test_joint_leaves_the_decoder_projections_alone(self):+ tmp = tempfile.TemporaryDirectory()+ self.addCleanup(tmp.cleanup)+ path = _full_file(Path(tmp.name) / "nar.safetensors", "nar", io=True)+ model = _Model("nar", io=True)+ original = mx.array(model.vae2llm.weight)+ L.apply_adapters(model, "nar", [L.read_adapter(path, mode="joint")])+ self.assertLess(float(mx.abs((model.vae2llm.weight - original).astype(mx.float32)).max()), 1e-6)++ def test_separate_replaces_them_with_a_strength_weighted_blend(self):+ tmp = tempfile.TemporaryDirectory()+ self.addCleanup(tmp.cleanup)+ one = _full_file(Path(tmp.name) / "one.safetensors", "nar", io=True)+ model = _Model("nar", io=True)+ original = mx.array(model.vae2llm.weight)+ first = L.read_adapter(one, strength=0.25, mode="separate")+ second = L.read_adapter(one, strength=0.75, mode="separate")+ L.apply_adapters(model, "nar", [first, second])+ # Both companions carry the same 0.25 weight; a convex blend is 0.25,+ # and summing them (the bug this rule exists to prevent) would be 0.5.+ self.assertLess(abs(float(model.vae2llm.weight[0, 0]) - 0.25), 0.01)+ L.remove_adapters(model)+ self.assertLess(float(mx.abs((model.vae2llm.weight - original).astype(mx.float32)).max()), 1e-6)++ def test_the_runtime_adapts_every_model_the_pipeline_loads(self):+ """The acoustic model is built lazily, halfway through the song."""+ tmp = tempfile.TemporaryDirectory()+ self.addCleanup(tmp.cleanup)+ ar = L.read_adapter(_full_file(Path(tmp.name) / "ar.safetensors", "ar"))+ nar = L.read_adapter(_full_file(Path(tmp.name) / "nar.safetensors", "nar"))++ class FakePipeline:+ def __init__(self):+ self._ar = self._bf16_ar = self._nar = None++ def _load_model(self, for_nar=False):+ if for_nar:+ self._bf16_ar = self._bf16_ar or _Model("ar")+ self._nar = self._nar or _Model("nar")+ return self._nar+ self._ar = self._ar or _Model("ar")+ return self._ar++ pipeline = FakePipeline()+ runtime = L.LoRARuntime([ar, nar]).attach(pipeline)+ pipeline._load_model()+ self.assertTrue(L.is_adapted(pipeline._ar))+ self.assertIsNone(pipeline._nar)+ pipeline._load_model(for_nar=True)+ self.assertTrue(L.is_adapted(pipeline._nar))+ self.assertTrue(L.is_adapted(pipeline._bf16_ar))+ runtime.detach()+ for model in (pipeline._ar, pipeline._bf16_ar, pipeline._nar):+ self.assertFalse(L.is_adapted(model))+++class InstrumentalRecipe(unittest.TestCase):++ def test_sung_prose_never_reaches_the_instrumental_adapter(self):+ self.assertEqual(L.instrumental_lyrics("I was born in a small town"), "[instrumental]")+ self.assertEqual(L.instrumental_lyrics(""), "[instrumental]")+ self.assertEqual(L.instrumental_lyrics("[Verse]\nsomething sung"), "[instrumental]")++ def test_bare_and_timed_section_tags_pass_through_lowercased(self):+ self.assertEqual(L.instrumental_lyrics("[Intro]\n[Chorus]"), "[intro]\n[chorus]")+ self.assertEqual(L.instrumental_lyrics("[intro 0:00-0:15]\n[chorus 0:15-0:40]"),+ "[intro 0:00-0:15]\n[chorus 0:15-0:40]")++ def test_overlapping_or_backwards_times_fall_back(self):+ self.assertEqual(L.instrumental_lyrics("[intro 0:10-0:05]"), "[instrumental]")+ self.assertEqual(L.instrumental_lyrics("[intro 0:00-0:20]\n[verse 0:10-0:30]"),+ "[instrumental]")++ def test_the_recipe_is_the_adapter_at_one_full_planning_and_a_stock_decoder(self):+ tmp = tempfile.TemporaryDirectory()+ self.addCleanup(tmp.cleanup)+ root = Path(tmp.name)+ empty = L.instrumental_recipe(root, "whatever")+ self.assertIsNone(empty["adapter"])+ self.assertIsNone(empty["lyrics"]) # fall back to the v4.16 skeleton+ (root / L.INSTRUMENTAL_ADAPTER).write_bytes(b"")+ recipe = L.instrumental_recipe(root, "a song about rain")+ self.assertEqual(recipe["adapter"], root / L.INSTRUMENTAL_ADAPTER)+ self.assertEqual(recipe["strength"], 1.0)+ self.assertEqual(recipe["cot"], "full")+ self.assertEqual(recipe["lyrics"], "[instrumental]")+ self.assertEqual(recipe["decoder"], "stock")+ self.assertTrue(recipe["pauses_other_loras"])++ def test_a_trigger_joins_the_style_once(self):+ class Stub:+ def __init__(self, trigger):+ self.trigger = trigger+ self.assertEqual(L.style_with_triggers("warm soul", [Stub("mtrsprr")]),+ "mtrsprr, warm soul")+ self.assertEqual(L.style_with_triggers("MTRSPRR ballad", [Stub("mtrsprr")]),+ "MTRSPRR ballad")+ self.assertEqual(L.style_with_triggers("", [Stub("a"), Stub("a"), Stub("b")]), "a, b")+++class ThePack(unittest.TestCase):++ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.root = Path(self.tmp.name)+ self.addCleanup(self.tmp.cleanup)++ def test_the_pinned_pack_and_the_user_folder_both_list(self):+ pinned_stand_in(self.root / L.INSTRUMENTAL_ADAPTER,+ F.SOURCES[L.INSTRUMENTAL_ADAPTER])+ pinned_stand_in(self.root / L.JOINT_NAR_ADAPTER,+ F.SOURCES[L.JOINT_NAR_ADAPTER])+ (self.root / L.USER_SUBDIR).mkdir()+ (self.root / L.USER_SUBDIR / "my_voice.safetensors").write_bytes(b"xxx")+ listed = L.pack_adapters(self.root)+ self.assertEqual([a["id"] for a in listed],+ [L.INSTRUMENTAL_ADAPTER, L.JOINT_NAR_ADAPTER,+ f"{L.USER_SUBDIR}/my_voice.safetensors"])+ self.assertTrue(listed[0]["instrumental"])+ self.assertEqual(listed[1]["branch"], "nar")+ self.assertFalse(listed[2]["builtin"])++ def test_a_pick_from_outside_the_folder_is_refused(self):+ (self.root / L.INSTRUMENTAL_ADAPTER).write_bytes(b"x")+ self.assertEqual(L.resolve_in_pack(self.root, L.INSTRUMENTAL_ADAPTER).name,+ L.INSTRUMENTAL_ADAPTER)+ with self.assertRaises(ValueError):+ L.resolve_in_pack(self.root, "../../etc/passwd")+ with self.assertRaises(FileNotFoundError):+ L.resolve_in_pack(self.root, "nothing.safetensors")+++class _FormHandler:+ """Enough of the panel's handler for a route to answer into."""++ def __init__(self, form: dict):+ self._form = {k: [v] for k, v in form.items()}+ self.status, self.body = 200, None++ def _read_form_body(self):+ return urlencode(self._form, doseq=True), self._form++ def _json(self, payload, status=200):+ self.body, self.status = payload, status+++def pinned_stand_in(path: Path, source: dict) -> None:+ """A file of the PINNED size, for a test that needs a pinned name to read+ as present. Readiness is size-checked now (Codex review, 2026-09-22), so a+ one-byte placeholder IS a truncated download. Sparse — instant, no disk.+ """+ path.parent.mkdir(parents=True, exist_ok=True)+ with path.open("wb") as handle:+ handle.truncate(int(source["bytes"]))+++class ThePackIsEitherWholeOrNot(unittest.TestCase):+ """A file with the pinned name is not the pinned file.++ Readiness accepted ANY non-empty adapter and the fetch endpoint returned+ early the moment both adapter names existed (Codex review, 2026-09-22), so+ a download that dropped halfway through left a truncated adapter that+ nothing would ever repair: the card said ready, Download did nothing, and+ the first song with that adapter failed to load it. The same early return+ stranded a pack whose tokenizer head never arrived.+ """++ BODY = b"the pinned bytes, all of them"+ DIGEST = hashlib.sha256(BODY).hexdigest()++ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ self.root = Path(self.tmp.name) / "pack"+ self.root.mkdir()+ self.pins = self.enterContext(mock.patch.multiple(+ F,+ SOURCES={n: {**src, "bytes": len(self.BODY), "sha256": self.DIGEST}+ for n, src in F.SOURCES.items()},+ HEAD_SOURCES={n: {**src, "bytes": len(self.BODY), "sha256": self.DIGEST}+ for n, src in F.HEAD_SOURCES.items()}))++ def _write(self, path: Path, body=None):+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_bytes(self.BODY if body is None else body)++ def _whole_adapters(self):+ for name in F.SOURCES:+ self._write(self.root / name)++ def _whole_head(self):+ for name, src in F.HEAD_SOURCES.items():+ if src["required"]:+ self._write(F.head_root(self.root) / name)++ def test_a_truncated_adapter_is_not_a_ready_pack(self):+ self._whole_adapters()+ self.assertEqual(F.lora_problems(self.root), [])+ self._write(self.root / L.INSTRUMENTAL_ADAPTER, b"x")+ self.assertEqual(F.lora_problems(self.root), [L.INSTRUMENTAL_ADAPTER])++ def test_a_truncated_adapter_is_not_offered_in_the_picker(self):+ self._whole_adapters()+ self._write(self.root / L.INSTRUMENTAL_ADAPTER, b"x")+ listed = [a["id"] for a in F.pack_adapters(self.root)]+ self.assertNotIn(L.INSTRUMENTAL_ADAPTER, listed)+ self.assertIn(L.JOINT_NAR_ADAPTER, listed)++ def test_a_users_own_adapter_is_never_size_checked(self):+ # Nothing is pinned about it; any non-empty file is theirs to try.+ (self.root / L.USER_SUBDIR).mkdir()+ self._write(self.root / L.USER_SUBDIR / "mine.safetensors", b"x")+ self.assertEqual([a["id"] for a in F.pack_adapters(self.root)],+ [f"{L.USER_SUBDIR}/mine.safetensors"])++ def test_usable_adapters_and_a_whole_pack_are_two_questions(self):+ self._whole_adapters()+ self.assertEqual(F.lora_problems(self.root), []) # pickable+ self.assertEqual(F.pack_problems(self.root), # not whole+ [f"{F.HEAD_SUBDIR}/{F.TOKENIZER_HEAD}"])+ self._whole_head()+ self.assertEqual(F.pack_problems(self.root), [])++ def test_a_deep_check_catches_bytes_the_size_cannot(self):+ self._write(self.root / L.INSTRUMENTAL_ADAPTER, b"x" * len(self.BODY))+ self._write(self.root / L.JOINT_NAR_ADAPTER)+ self.assertEqual(F.lora_problems(self.root), [])+ self.assertEqual(F.lora_problems(self.root, deep=True),+ [L.INSTRUMENTAL_ADAPTER])++ # ---- the download itself ------------------------------------------+ def _fetch(self, staged: dict, **kw):+ """Run `fetch()` with a stand-in hub that serves `staged` bodies."""+ store = Path(self.tmp.name) / "hub"+ store.mkdir(exist_ok=True)+ served = []++ def hf_hub_download(repo_id, revision, filename, **_):+ served.append(filename)+ out = store / f"{len(served)}-{Path(filename).name}"+ body = staged.get(Path(filename).name)+ if body is None:+ raise RuntimeError("not in this fake repo")+ out.write_bytes(body)+ return str(out)++ with mock.patch.dict(sys.modules, {"huggingface_hub": types.SimpleNamespace(+ hf_hub_download=hf_hub_download)}):+ F.fetch(self.root, **kw)+ return served++ def test_an_interrupted_head_is_resumed_not_declared_done(self):+ self._whole_adapters()+ served = self._fetch({n: self.BODY for n in+ {**F.SOURCES, **F.HEAD_SOURCES}})+ # The adapters were already whole, so only the head was fetched.+ self.assertNotIn(L.INSTRUMENTAL_ADAPTER, served)+ self.assertIn(F.TOKENIZER_HEAD, served)+ self.assertEqual(F.pack_problems(self.root), [])++ def test_a_truncated_adapter_is_fetched_again(self):+ self._whole_adapters()+ self._write(self.root / L.JOINT_NAR_ADAPTER, b"x")+ served = self._fetch({n: self.BODY for n in+ {**F.SOURCES, **F.HEAD_SOURCES}})+ self.assertIn(L.JOINT_NAR_ADAPTER, served)+ self.assertNotIn(L.INSTRUMENTAL_ADAPTER, served)+ self.assertEqual(F.pack_problems(self.root), [])++ def test_a_file_that_fails_its_checksum_never_wears_the_pinned_name(self):+ bad = {n: b"corrupted-on-the-wire!!!!!!!!" for n in F.SOURCES}+ self.assertEqual(len(bad[L.INSTRUMENTAL_ADAPTER]), len(self.BODY))+ with self.assertRaises(SystemExit):+ self._fetch(bad)+ self.assertFalse((self.root / L.INSTRUMENTAL_ADAPTER).exists())+ self.assertEqual(list(self.root.glob("*.partial")), [])++ def test_a_good_file_survives_a_failed_re_download_beside_it(self):+ # Atomic: the verified adapter on disk is not destroyed by a second+ # file arriving corrupted.+ self._whole_adapters()+ self._write(self.root / L.JOINT_NAR_ADAPTER, b"x")+ with self.assertRaises(SystemExit):+ self._fetch({L.JOINT_NAR_ADAPTER: b"corrupted-on-the-wire!!!!!!!!"})+ self.assertEqual(+ (self.root / L.INSTRUMENTAL_ADAPTER).read_bytes(), self.BODY)+ self.assertEqual(list(self.root.glob("*.partial")), [])++ # ---- what the panel does with all that -----------------------------+ def test_the_panel_reports_usable_and_whole_separately(self):+ import mlx_ltx_panel as panel+ with mock.patch.object(panel, "MUSIC_LORAS", self.root):+ self._whole_adapters()+ status = panel.music_lora_status()+ self.assertTrue(status["ready"])+ self.assertFalse(status["complete"])+ self.assertTrue(status["incomplete"])+ self._whole_head()+ self.assertTrue(panel.music_lora_status()["complete"])++ def test_the_download_button_still_works_on_a_half_a_pack(self):+ import mlx_ltx_panel as panel+ self._whole_adapters() # head still missing+ started = []+ with mock.patch.object(panel, "MUSIC_LORAS", self.root), \+ mock.patch.object(panel.threading, "Thread",+ side_effect=lambda **kw: started.append(kw)+ or mock.MagicMock()):+ code, payload = panel.music_lora_fetch_start()+ self.assertEqual(code, 202, payload)+ self.assertTrue(started, "the endpoint returned ready and downloaded nothing")++ def test_a_whole_pack_asks_for_no_download(self):+ import mlx_ltx_panel as panel+ self._whole_adapters()+ self._whole_head()+ with mock.patch.object(panel, "MUSIC_LORAS", self.root):+ code, payload = panel.music_lora_fetch_start()+ self.assertEqual((code, payload), (200, {"ok": True, "ready": True}))+++class ThePanelRoundTrip(unittest.TestCase):+ """The form the studio posts, through `music_params` and into argv."""++ @classmethod+ def setUpClass(cls):+ import mlx_ltx_panel+ cls.P = mlx_ltx_panel++ def _argv(self, form, tmp):+ job = {"id": "job-lora-1", "params": form}+ paths = {"python": Path("/bin/true"), "runner": Path("/dev/null"),+ "generator": Path(tmp) / "gen", "vae": Path(tmp) / "vae"}+ return self.P.music_argv(job, paths, Path(tmp) / "song.wav")++ def test_picks_become_lora_flags_with_their_strengths(self):+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp) / "loras"+ (root / L.USER_SUBDIR).mkdir(parents=True)+ (root / L.JOINT_NAR_ADAPTER).write_bytes(b"x")+ (root / L.USER_SUBDIR / "mine.safetensors").write_bytes(b"x")+ self.P.MUSIC_LORAS = root+ argv = self._argv({"music_style": "dub", "music_loras":+ f"{L.JOINT_NAR_ADAPTER}:0.8,{L.USER_SUBDIR}/mine.safetensors:1.2"}, tmp)+ specs = [argv[i + 1] for i, a in enumerate(argv) if a == "--lora"]+ real = root.resolve()+ self.assertEqual(specs, [f"{real / L.JOINT_NAR_ADAPTER}:0.8",+ f"{real / L.USER_SUBDIR}/mine.safetensors:1.2"])+ self.assertIn("--lora-dir", argv)++ def test_a_pick_that_is_not_in_the_folder_never_reaches_the_runner(self):+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp) / "loras"+ root.mkdir(parents=True)+ self.P.MUSIC_LORAS = root+ params = self.P.music_params({"music_loras": "../../../etc/passwd:1.0"})+ self.assertEqual(params["music_loras"], [])+ argv = self._argv({"music_style": "dub",+ "music_loras": "../../../etc/passwd:1.0"}, tmp)+ self.assertNotIn("--lora", argv)++ def test_instrumental_still_sends_its_own_flag(self):+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp) / "loras"+ root.mkdir(parents=True)+ self.P.MUSIC_LORAS = root+ argv = self._argv({"music_style": "dub", "music_instrumental": "on"}, tmp)+ self.assertIn("--instrumental", argv)+ self.assertIn("--lora-dir", argv)++ def test_the_status_block_says_what_is_missing(self):+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp) / "loras"+ root.mkdir(parents=True)+ self.P.MUSIC_LORAS = root+ status = self.P.music_lora_status()+ self.assertFalse(status["ready"])+ self.assertTrue(status["missing"])+ self.assertEqual(status["adapters"], [])+ self.assertGreater(status["bytes"], 0)++ def test_the_runner_advertises_the_flags_the_panel_sends(self):+ runner = (ROOT / "scripts/music/yue2_run.py").read_text()+ for flag in ("--lora", "--lora-mode", "--lora-dir", "--lora-trigger", "--instrumental"):+ self.assertIn(f'"{flag}"', runner, f"{flag} is not a runner flag")++ def test_the_browser_sends_ONE_field_and_both_picks_survive_it(self):+ """The bug a plain string could never show (Codex review, 2026-09-22).++ The studio joins its picks into one comma-separated field, and+ `parse_qs` hands the panel `{"music_loras": ["a:0.8,b:1.2"]}` — a LIST+ with the whole selection inside its single element. Read as a list of+ specs, those two adapters became one filename nobody has, and every+ pick was silently dropped: choosing two voices turned them both off.+ """+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp) / "loras"+ (root / L.USER_SUBDIR).mkdir(parents=True)+ (root / L.JOINT_NAR_ADAPTER).write_bytes(b"x")+ (root / L.USER_SUBDIR / "mine.safetensors").write_bytes(b"x")+ self.P.MUSIC_LORAS = root+ field = f"{L.JOINT_NAR_ADAPTER}:0.8,{L.USER_SUBDIR}/mine.safetensors:1.2"+ form = parse_qs(urlencode({"music_style": "dub", "music_loras": field}))+ self.assertEqual(form["music_loras"], [field]) # one field, one list+ picks = self.P.music_params(form)["music_loras"]+ self.assertEqual([(p["id"], p["strength"]) for p in picks],+ [(L.JOINT_NAR_ADAPTER, 0.8),+ (f"{L.USER_SUBDIR}/mine.safetensors", 1.2)])+ argv = self._argv(form, tmp)+ real = root.resolve()+ self.assertEqual([argv[i + 1] for i, a in enumerate(argv) if a == "--lora"],+ [f"{real / L.JOINT_NAR_ADAPTER}:0.8",+ f"{real / L.USER_SUBDIR}/mine.safetensors:1.2"])++ def test_one_pick_through_parse_qs_still_works(self):+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp) / "loras"+ root.mkdir(parents=True)+ (root / L.JOINT_NAR_ADAPTER).write_bytes(b"x")+ self.P.MUSIC_LORAS = root+ form = parse_qs(urlencode({"music_loras": f"{L.JOINT_NAR_ADAPTER}:0.5"}))+ picks = self.P.music_params(form)["music_loras"]+ self.assertEqual([(p["id"], p["strength"]) for p in picks],+ [(L.JOINT_NAR_ADAPTER, 0.5)])++ def test_a_job_reparsed_from_its_own_params_keeps_its_picks(self):+ """`music_argv` runs `music_params` over `job["params"]`, where the+ picks are ALREADY a list of dicts. A normalised list and one HTTP+ field are two different shapes and both have to survive."""+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp) / "loras"+ root.mkdir(parents=True)+ (root / L.JOINT_NAR_ADAPTER).write_bytes(b"x")+ self.P.MUSIC_LORAS = root+ once = self.P.music_params(+ parse_qs(urlencode({"music_loras": f"{L.JOINT_NAR_ADAPTER}:0.8"})))+ twice = self.P.music_params(once)+ self.assertEqual(once["music_loras"], twice["music_loras"])+++class TheFormFieldIsNotOneSpec(unittest.TestCase):+ """`parse_field` (what a browser posted) vs `parse_picks` (a normalised+ list). Keeping them apart is the whole fix: an HTTP field's list is one+ element PER REPEAT of the field, and each element carries a whole+ comma-separated selection."""++ def test_a_single_field_value_splits_on_the_commas(self):+ self.assertEqual(L.parse_field(["a.safetensors:0.8,b.safetensors:1.2"]),+ [("a.safetensors", 0.8), ("b.safetensors", 1.2)])++ def test_a_repeated_field_is_every_value_together(self):+ self.assertEqual(L.parse_field(["a.safetensors:0.8", "b.safetensors:1.2"]),+ [("a.safetensors", 0.8), ("b.safetensors", 1.2)])++ def test_a_bare_string_is_the_same_answer(self):+ self.assertEqual(L.parse_field("a.safetensors:0.8,b.safetensors:1.2"),+ L.parse_picks("a.safetensors:0.8,b.safetensors:1.2"))++ def test_json_in_the_field_is_still_json(self):+ self.assertEqual(+ L.parse_field(['[{"id": "a.safetensors", "strength": 0.4}]']),+ [("a.safetensors", 0.4)])++ def test_a_normalised_list_is_taken_element_by_element(self):+ # This is what `parse_picks` is FOR, and why the field needs its own+ # door: here each element really is one spec.+ self.assertEqual(L.parse_picks(["a.safetensors:0.8", "b.safetensors"]),+ [("a.safetensors", 0.8), ("b.safetensors", 1.0)])+ self.assertEqual(L.parse_field([{"id": "a.safetensors", "strength": 0.3}]),+ [("a.safetensors", 0.3)])++ def test_nothing_at_all_is_no_picks(self):+ for raw in (None, "", [], ["", " "], " "):+ self.assertEqual(L.parse_field(raw), [])+++class TheRunnerArgvRoundTrip(unittest.TestCase):+ """`--lora-trigger` from argv to the style prompt and the sidecar.++ The study measured the trigger as load-bearing (0.846 with, 0.772 without,+ same checkpoint and seed), so what is pinned here is the wiring that makes+ it reachable: the flag repeats, the Nth trigger belongs to the Nth+ `--lora`, a trigger with no adapter is dropped rather than misapplied, and+ the word reaches the style prompt exactly once in pick order.+ """++ @classmethod+ def setUpClass(cls):+ sys.path.insert(0, str(ROOT / "scripts" / "music"))+ import yue2_run+ cls.R = yue2_run++ def _args(self, *extra):+ return self.R.parse_args(["--model-dir", "m", "--vae-dir", "v",+ "--output", "song.wav", *extra])++ def test_the_flag_repeats_and_keeps_its_order(self):+ args = self._args("--lora", "a.safetensors:0.8", "--lora-trigger", "frddtrn",+ "--lora", "b.safetensors", "--lora-trigger", "mtrsprr")+ self.assertEqual(args.lora_trigger, ["frddtrn", "mtrsprr"])+ self.assertEqual(args.lora, ["a.safetensors:0.8", "b.safetensors"])+ self.assertEqual(self._args().lora_trigger, [])++ def test_the_nth_trigger_belongs_to_the_nth_adapter(self):+ tmp = tempfile.TemporaryDirectory()+ self.addCleanup(tmp.cleanup)+ root = Path(tmp.name)+ first = _full_file(root / "a.safetensors", "ar")+ second = _full_file(root / "b.safetensors", "ar")+ args = self._args("--lora", f"{first}", "--lora-trigger", "frddtrn",+ "--lora", f"{second}")+ specs = [L.parse_spec(one) for one in args.lora]+ adapters = L.load_stack(specs, mode=args.lora_mode,+ triggers=args.lora_trigger, with_sha=False)+ self.assertEqual([a.trigger for a in adapters], ["frddtrn", ""])+ # A trigger with no adapter of its own is dropped, never slid onto+ # the wrong file.+ args = self._args("--lora", f"{first}",+ "--lora-trigger", "frddtrn", "--lora-trigger", "spare")+ adapters = L.load_stack([L.parse_spec(one) for one in args.lora],+ mode=args.lora_mode, triggers=args.lora_trigger,+ with_sha=False)+ self.assertEqual([a.trigger for a in adapters], ["frddtrn"])++ def test_the_trigger_reaches_the_style_and_the_sidecar(self):+ tmp = tempfile.TemporaryDirectory()+ self.addCleanup(tmp.cleanup)+ root = Path(tmp.name)+ first = _full_file(root / "a.safetensors", "ar")+ second = _full_file(root / "b.safetensors", "ar")+ args = self._args("--style", "MTV Unplugged, acoustic",+ "--lora", f"{first}", "--lora-trigger", "frddtrn",+ "--lora", f"{second}", "--lora-trigger", "mtrsprr")+ adapters = L.load_stack([L.parse_spec(one) for one in args.lora],+ mode=args.lora_mode, triggers=args.lora_trigger,+ with_sha=False)+ # The prototype's shape: "<trigger>, <style>", in pick order, once.+ self.assertEqual(L.style_with_triggers(args.style, adapters),+ "frddtrn, mtrsprr, MTV Unplugged, acoustic")+ block = L.describe_stack(adapters)+ self.assertEqual(block["triggers"], ["frddtrn", "mtrsprr"])+ self.assertEqual([a["trigger"] for a in block["adapters"]],+ ["frddtrn", "mtrsprr"])+ json.dumps(block)+++class TheVariationKeepsTheVoice(unittest.TestCase):+ """`/music/variation` — a new take of a song is the SAME singer.++ A take keeps the parent's words and style, and a re-roll keeps its+ performance, so the parent's adapters are part of what is being repeated.+ They were not carried (Codex review, 2026-09-22): the new runner applies+ adapters only when they are named, so New take handed back a song in a+ voice the user had never picked, and Re-roll the sound dropped the+ acoustic adapter that made the recording sound the way it did.+ """++ def setUp(self):+ import mlx_ltx_panel+ from panel import routes_music+ self.P, self.R = mlx_ltx_panel, routes_music+ routes_music.P = mlx_ltx_panel+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ root = Path(self.tmp.name)+ self.loras = root / "loras"+ (self.loras / L.USER_SUBDIR).mkdir(parents=True)+ (self.loras / L.USER_SUBDIR / "freddie.safetensors").write_bytes(b"x")+ self._saved_loras = self.P.MUSIC_LORAS+ self.P.MUSIC_LORAS = self.loras+ self.addCleanup(lambda: setattr(self.P, "MUSIC_LORAS", self._saved_loras))+ # A finished song in the outputs, with the artifacts a variation+ # restarts from and the params the runner recorded.+ self.P.OUTPUT.mkdir(parents=True, exist_ok=True)+ self.song = (self.P.OUTPUT / "_loratest_song.wav").resolve()+ self.song.write_bytes(b"RIFF....WAVE")+ self.addCleanup(self.song.unlink, True)+ self.artifacts = root / "artifacts"+ self.artifacts.mkdir()+ (self.artifacts / "result.json").write_text("{}")+ self.side = Path(str(self.song) + ".json")+ self.addCleanup(self.side.unlink, True)+ self.pick = f"{L.USER_SUBDIR}/freddie.safetensors"+ self.side.write_text(json.dumps({+ "engine": "music", "title": "Unplugged", "style": "warm soul",+ "lyrics": "[verse]\nooh", "mode": "full", "instrumental": False,+ "artifacts": str(self.artifacts),+ "params": {"music_quality": "final", "music_max_seconds": "120",+ "music_precision": "8bit", "music_lora_mode": "separate",+ "music_loras": [{"id": self.pick, "strength": 0.9,+ "path": str(self.loras / self.pick)}]},+ }))++ def _vary(self, kind):+ queued = []+ with mock.patch.object(self.R, "_queue",+ side_effect=lambda form: queued.append(form)+ or self.P.make_job(form)), \+ mock.patch.object(self.P, "push"):+ h = _FormHandler({"kind": kind, "path": str(self.song)})+ self.R.post_music_variation(h, "/music/variation", {}, "")+ self.assertEqual(h.status, 200, h.body)+ return queued[0], self.P.make_job(queued[0])["params"]++ def test_a_new_take_carries_the_parents_adapter_and_its_strength(self):+ _form, params = self._vary("take")+ self.assertEqual([(p["id"], p["strength"]) for p in params["music_loras"]],+ [(self.pick, 0.9)])++ def test_a_re_roll_of_the_sound_carries_the_mode_too(self):+ _form, params = self._vary("sound")+ self.assertEqual(params["music_lora_mode"], "separate")+ self.assertTrue(params["music_loras"])++ def test_the_carried_picks_are_resolved_inside_the_lora_folder_again(self):+ # A sidecar is a file on disk; it names an adapter, never a path.+ # It is not resolved, and since 2026-09-24 (M6-05) it is not silently+ # DROPPED either: a take without the parent's singer is refused with+ # the id named, instead of queued with a different voice.+ self.side.write_text(self.side.read_text().replace(+ json.dumps(self.pick), json.dumps("../../../etc/passwd")))+ queued = []+ with mock.patch.object(self.R, "_queue",+ side_effect=lambda form: queued.append(form)+ or self.P.make_job(form)), \+ mock.patch.object(self.P, "push"):+ h = _FormHandler({"kind": "take", "path": str(self.song)})+ self.R.post_music_variation(h, "/music/variation", {}, "")+ self.assertEqual(h.status, 409, h.body)+ self.assertIn("../../../etc/passwd", h.body["error"])+ self.assertEqual(self.P.music_params(queued[0])["music_loras"], [])++ def test_a_song_written_with_no_adapter_queues_none(self):+ self.side.write_text(self.side.read_text().replace(+ json.dumps([{"id": self.pick, "strength": 0.9,+ "path": str(self.loras / self.pick)}]), "[]"))+ _form, params = self._vary("take")+ self.assertEqual(params["music_loras"], [])++ def test_a_restyle_keeps_them_as_well(self):+ # The words and the style are new; who is singing them is not.+ meta = json.loads(self.side.read_text())+ meta["score_abc"] = "X:1"+ self.side.write_text(json.dumps(meta))+ queued = []+ with mock.patch.object(self.R, "_queue",+ side_effect=lambda form: queued.append(form)+ or self.P.make_job(form)), \+ mock.patch.object(self.P, "push"):+ h = _FormHandler({"kind": "restyle", "path": str(self.song),+ "style": "bossa nova"})+ self.R.post_music_variation(h, "/music/variation", {}, "")+ self.assertEqual(h.status, 200, h.body)+ params = self.P.make_job(queued[0])["params"]+ self.assertEqual(params["music_style"], "bossa nova")+ self.assertTrue(params["music_loras"])+++class TheSidecarBlock(unittest.TestCase):++ def test_it_records_every_adapter_and_the_instrumental_recipe(self):+ tmp = tempfile.TemporaryDirectory()+ self.addCleanup(tmp.cleanup)+ adapter = L.read_adapter(_full_file(Path(tmp.name) / "a.safetensors", "ar"),+ strength=0.6, trigger="mtrsprr", with_sha=True)+ block = L.describe_stack([adapter], instrumental={"adapter": "ar_lora_inst", "strength": 1.0})+ self.assertEqual(block["adapters"][0]["strength"], 0.6)+ self.assertEqual(block["adapters"][0]["rank"], RANK)+ self.assertEqual(len(block["adapters"][0]["sha256"]), 64)+ self.assertEqual(block["triggers"], ["mtrsprr"])+ self.assertEqual(block["branches"], ["ar"])+ json.dumps(block) # the sidecar has to serialise+++if __name__ == "__main__":+ unittest.main()diff --git a/test_yue2_tokenizer.py b/test_yue2_tokenizer.pynew file mode 100644index 0000000..957f6b4--- /dev/null+++ b/test_yue2_tokenizer.py@@ -0,0 +1,625 @@+"""The real-audio tokenizer head: the rules a recording has to pass through.++CPU only, no YuE2 weights, no 2.5 GB MERT checkpoint, no audio decoding. What+is pinned here is everything that can be wrong in silence — every item below+has identical shapes whether it is right or wrong, which is exactly why it gets+a test rather than a comment:++ * the checkpoint's tensor names map onto this module's parameter tree with+ nothing missing and nothing extra, and a renamed or truncated file is+ refused by name rather than loaded half-way;+ * the encoder computes what torch's `TransformerEncoderLayer(norm_first=True,+ activation="gelu")` computes — checked against a numpy reference written+ out longhand on random weights, including the fused q,k,v row order, which+ every permutation would load without complaint;+ * `pos` is sliced for a short window, never interpolated;+ * instance norm is per TRACK and uses the population standard deviation+ (numpy's default, not torch's) — the original reads the array as numpy;+ * the time resampler is `align_corners=False` half-pixel, the convention that+ decides which frame every code lands on;+ * the tiling is `joint_v6.predict`'s: hop 256, a pulled-back final window,+ 128 frames trimmed off every interior edge, and no frame left unwritten;+ * the MERT mixer one-hot sits at `layer + 1`, because transformers collects+ hidden states only after each block while `lyra.mert`'s vector begins with+ the pre-layer embedding;+ * the pack keeps the head out of the LoRA picker's reach;+ * the runner's argv round trip carries the prompt and refuses nonsense.++The numbers in `docs/MUSIC_ENGINE.md` come from the real head against a real+torch reference; this file is the part that runs on every release.+"""+from __future__ import annotations++import json+import os+from pathlib import Path+import subprocess+import sys+import tempfile+import unittest++import mlx.core as mx+import numpy as np++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT))+sys.path.insert(0, str(ROOT / "scripts" / "music"))+os.environ.setdefault("LTX_STATE_DIR", tempfile.mkdtemp(prefix="yue2-tok-state-"))+os.environ["PHOSPHENE_ANALYTICS_DISABLED"] = "1"+os.environ["PHOSPHENE_DISABLE_VERSION_CHECK"] = "1"++import yue2_tokenizer as T # noqa: E402+from scripts.pinokio import music_lora_fetch as P # noqa: E402+++# ------------------------------------------------------------ numpy reference++def _layer_norm(x, weight, bias, eps=1e-5):+ mean = x.mean(-1, keepdims=True)+ variance = ((x - mean) ** 2).mean(-1, keepdims=True)+ return (x - mean) / np.sqrt(variance + eps) * weight + bias+++def _gelu(x):+ from math import erf++ return 0.5 * x * (1.0 + np.vectorize(erf)(x / np.sqrt(2.0)))+++def _attention(x, in_weight, in_bias, out_weight, out_bias, heads):+ """torch's `MultiheadAttention` written out: q,k,v are the row blocks of+ `in_proj_weight`, in that order, and q is scaled by 1/sqrt(head_dim)."""+ length, dim = x.shape+ head_dim = dim // heads+ fused = x @ in_weight.T + in_bias+ query, key, value = fused[:, :dim], fused[:, dim:2 * dim], fused[:, 2 * dim:]+ out = np.zeros_like(x)+ for head in range(heads):+ span = slice(head * head_dim, (head + 1) * head_dim)+ scores = (query[:, span] @ key[:, span].T) / np.sqrt(head_dim)+ scores = scores - scores.max(-1, keepdims=True)+ weights = np.exp(scores)+ weights /= weights.sum(-1, keepdims=True)+ out[:, span] = weights @ value[:, span]+ return out @ out_weight.T + out_bias+++def _reference_head(weights, features, layers=2, heads=T.NUM_HEADS):+ """`Tok.forward` from `joint_v6.py`, in numpy, on the given weights."""+ frames = len(features)+ x = features @ weights["inp.weight"].T + weights["inp.bias"]+ x = x + weights["pos"][0, :frames]+ for index in range(layers):+ prefix = f"enc.layers.{index}."+ normed = _layer_norm(x, weights[prefix + "norm1.weight"], weights[prefix + "norm1.bias"])+ x = x + _attention(normed, weights[prefix + "self_attn.in_proj_weight"],+ weights[prefix + "self_attn.in_proj_bias"],+ weights[prefix + "self_attn.out_proj.weight"],+ weights[prefix + "self_attn.out_proj.bias"], heads)+ normed = _layer_norm(x, weights[prefix + "norm2.weight"], weights[prefix + "norm2.bias"])+ hidden = _gelu(normed @ weights[prefix + "linear1.weight"].T + weights[prefix + "linear1.bias"])+ x = x + hidden @ weights[prefix + "linear2.weight"].T + weights[prefix + "linear2.bias"]+ x = _layer_norm(x, weights["norm.weight"], weights["norm.bias"])+ return x @ weights["head.weight"].T + weights["head.bias"]+++def _random_weights(rng, *, layers=2, dim=T.MODEL_DIM, vocab=64, window=T.WINDOW,+ feature_dim=T.FEATURE_DIM, ffn=T.FFN_DIM):+ def draw(*shape, scale=0.05):+ return rng.standard_normal(shape).astype(np.float32) * scale++ weights = {+ "inp.weight": draw(dim, feature_dim), "inp.bias": draw(dim),+ "pos": draw(1, window, dim),+ "norm.weight": 1.0 + draw(dim), "norm.bias": draw(dim),+ "head.weight": draw(vocab, dim), "head.bias": draw(vocab),+ }+ for index in range(layers):+ prefix = f"enc.layers.{index}."+ weights.update({+ prefix + "self_attn.in_proj_weight": draw(3 * dim, dim),+ prefix + "self_attn.in_proj_bias": draw(3 * dim),+ prefix + "self_attn.out_proj.weight": draw(dim, dim),+ prefix + "self_attn.out_proj.bias": draw(dim),+ prefix + "linear1.weight": draw(ffn, dim), prefix + "linear1.bias": draw(ffn),+ prefix + "linear2.weight": draw(dim, ffn), prefix + "linear2.bias": draw(dim),+ prefix + "norm1.weight": 1.0 + draw(dim), prefix + "norm1.bias": draw(dim),+ prefix + "norm2.weight": 1.0 + draw(dim), prefix + "norm2.bias": draw(dim),+ })+ return weights+++def _small_head(weights, *, layers=2, vocab=64):+ head = T.TokenizerHead()+ head.enc = T.Encoder(layers)+ head.head = type(head.head)(T.MODEL_DIM, vocab)+ head.update(_tree(weights))+ mx.eval(head.parameters())+ return head+++def _tree(weights):+ from mlx.utils import tree_unflatten++ return tree_unflatten([(key, mx.array(value)) for key, value in weights.items()])+++# ------------------------------------------------------------------- the tests++class KeyMapping(unittest.TestCase):+ def test_expected_keys_match_a_fresh_module(self):+ from mlx.utils import tree_flatten++ head = T.TokenizerHead()+ names = sorted(key for key, _ in tree_flatten(head.parameters()))+ self.assertEqual(names, list(T.EXPECTED_KEYS))+ self.assertEqual(len(names), 103, "the checkpoint carries 103 tensors")++ def test_shapes_are_the_published_architecture(self):+ from mlx.utils import tree_flatten++ shapes = {key: tuple(value.shape) for key, value in tree_flatten(T.TokenizerHead().parameters())}+ self.assertEqual(shapes["inp.weight"], (512, 1024))+ self.assertEqual(shapes["pos"], (1, 512, 512))+ self.assertEqual(shapes["head.weight"], (32768, 512))+ self.assertEqual(shapes["enc.layers.7.self_attn.in_proj_weight"], (1536, 512))+ self.assertEqual(shapes["enc.layers.0.linear1.weight"], (2048, 512))++ def test_a_missing_tensor_is_refused_by_name(self):+ weights = {key: np.zeros((1,), np.float32) for key in T.EXPECTED_KEYS}+ weights.pop("head.bias")+ with self.assertRaises(ValueError) as caught:+ T.convert_head_weights(weights)+ self.assertIn("missing", str(caught.exception))+ self.assertIn("tokenizer_head_joint_v9", str(caught.exception))++ def test_an_extra_tensor_is_refused(self):+ weights = {key: np.zeros((1,), np.float32) for key in T.EXPECTED_KEYS}+ weights["enc.layers.8.norm1.weight"] = np.zeros((1,), np.float32)+ with self.assertRaises(ValueError) as caught:+ T.convert_head_weights(weights)+ self.assertIn("unexpected", str(caught.exception))++ def test_a_missing_file_names_the_fetch_command(self):+ with self.assertRaises(FileNotFoundError) as caught:+ T.load_head(Path(tempfile.mkdtemp()) / "nothing.safetensors")+ self.assertIn("music_lora_fetch", str(caught.exception))+++class EncoderMath(unittest.TestCase):+ """The encoder against a numpy reference on random weights."""++ def setUp(self):+ self.rng = np.random.default_rng(20260921)+ self.weights = _random_weights(self.rng)+ self.head = _small_head(self.weights)++ def _run(self, frames):+ features = self.rng.standard_normal((frames, T.FEATURE_DIM)).astype(np.float32)+ want = _reference_head(self.weights, features)+ got = np.array(self.head(mx.array(features[None])).astype(mx.float32))[0]+ return want, got++ def test_full_window_matches_the_reference(self):+ want, got = self._run(T.WINDOW)+ self.assertLess(np.abs(want - got).max(), 2e-4)+ self.assertTrue((want.argmax(-1) == got.argmax(-1)).all())++ def test_short_window_slices_pos_rather_than_interpolating(self):+ want, got = self._run(97)+ self.assertLess(np.abs(want - got).max(), 2e-4)++ def test_qkv_row_order_is_q_then_k_then_v(self):+ """Every permutation has identical shapes and loads without complaint.+ Only one of them is what the checkpoint means."""+ features = self.rng.standard_normal((64, T.FEATURE_DIM)).astype(np.float32)+ want = _reference_head(self.weights, features)+ import itertools++ wrong = 0+ for order in itertools.permutations(range(3)):+ weights = dict(self.weights)+ for index in range(2):+ prefix = f"enc.layers.{index}.self_attn."+ blocks = self.weights[prefix + "in_proj_weight"].reshape(3, T.MODEL_DIM, T.MODEL_DIM)+ biases = self.weights[prefix + "in_proj_bias"].reshape(3, T.MODEL_DIM)+ weights[prefix + "in_proj_weight"] = np.concatenate(+ [blocks[i] for i in order], axis=0)+ weights[prefix + "in_proj_bias"] = np.concatenate([biases[i] for i in order])+ got = np.array(_small_head(weights)(mx.array(features[None])).astype(mx.float32))[0]+ difference = np.abs(want - got).max()+ if order == (0, 1, 2):+ self.assertLess(difference, 2e-4, "q,k,v must be the identity")+ else:+ self.assertGreater(difference, 1e-3, f"permutation {order} looked identical")+ wrong += 1+ self.assertEqual(wrong, 5)++ def test_more_frames_than_a_window_is_refused(self):+ features = np.zeros((T.WINDOW + 1, T.FEATURE_DIM), np.float32)+ with self.assertRaises(ValueError):+ self.head(mx.array(features[None]))++ def test_the_wrong_feature_width_is_refused(self):+ with self.assertRaises(ValueError):+ self.head(mx.array(np.zeros((1, 8, 512), np.float32)))+++class InstanceNorm(unittest.TestCase):+ def test_per_channel_over_the_whole_track(self):+ rng = np.random.default_rng(3)+ values = rng.standard_normal((400, 16)).astype(np.float32) * 7.0 + 3.0+ normed = T.instance_norm(values)+ self.assertTrue(np.allclose(normed.mean(0), 0.0, atol=1e-5))+ self.assertTrue(np.allclose(normed.std(0), 1.0, atol=1e-3))++ def test_population_std_not_bessel_corrected(self):+ """numpy's default is ddof=0 and torch's is ddof=1. The original reads+ the array as numpy, so a Bessel-corrected port is quietly wrong."""+ values = np.arange(8, dtype=np.float32)[:, None]+ expected = (values - values.mean(0)) / (values.std(0) + T.INSTNORM_EPS)+ self.assertTrue(np.allclose(T.instance_norm(values), expected))+ bessel = (values - values.mean(0)) / (values.std(0, ddof=1) + T.INSTNORM_EPS)+ self.assertFalse(np.allclose(T.instance_norm(values), bessel))++ def test_a_constant_channel_survives_the_epsilon(self):+ values = np.ones((32, 4), np.float32)+ self.assertTrue(np.isfinite(T.instance_norm(values)).all())++ def test_a_window_is_not_normalised_on_its_own(self):+ """Normalising per window instead of per track would make the same+ second of music decode differently depending on where it was cut."""+ rng = np.random.default_rng(5)+ track = rng.standard_normal((1000, 8)).astype(np.float32)+ track[:500] *= 10.0+ whole = T.instance_norm(track)[500:]+ piece = T.instance_norm(track[500:])+ self.assertFalse(np.allclose(whole, piece, atol=1e-3))++ def test_rank_is_checked(self):+ with self.assertRaises(ValueError):+ T.instance_norm(np.zeros((4, 4, 4), np.float32))+++class TimeResampling(unittest.TestCase):+ def test_identity_when_the_length_already_matches(self):+ values = np.arange(20, dtype=np.float32).reshape(10, 2)+ self.assertIs(T.resample_time(values, 10), values)++ def test_half_pixel_convention(self):+ """`align_corners=False`: output i reads source (i + 0.5) * scale - 0.5,+ clamped at 0. Getting this wrong shifts every code by a frame."""+ values = np.arange(10, dtype=np.float32)[:, None]+ self.assertTrue(np.allclose(T.resample_time(values, 5).ravel(),+ [0.5, 2.5, 4.5, 6.5, 8.5]))++ def test_upsampling_clamps_at_both_edges(self):+ values = np.arange(4, dtype=np.float32)[:, None]+ out = T.resample_time(values, 8).ravel()+ self.assertAlmostEqual(float(out[0]), 0.0, places=5)+ self.assertAlmostEqual(float(out[-1]), 3.0, places=5)+ self.assertTrue(np.all(np.diff(out) >= -1e-6))++ def test_zero_frames_is_refused(self):+ with self.assertRaises(ValueError):+ T.resample_time(np.zeros((4, 1), np.float32), 0)++ def test_twenty_five_hertz_is_a_whole_number_of_frames(self):+ """MERT-v2-FullSong runs at 25 Hz natively, so a track whose length is a+ multiple of 960 samples resamples by the identity."""+ self.assertEqual(T.MERT_RATE // T.FRAME_RATE, 960)+ for seconds in (1, 7, 30):+ samples = seconds * T.MERT_RATE+ self.assertEqual(int(round(samples / T.MERT_RATE * T.FRAME_RATE)),+ samples // 960)+++class Tiling(unittest.TestCase):+ def test_short_track_is_one_window(self):+ self.assertEqual(T.tile_starts(300), [0])++ def test_hop_is_half_a_window_with_a_pulled_back_tail(self):+ self.assertEqual(T.tile_starts(1200), [0, 256, 512, 688])+ self.assertEqual(T.tile_starts(750), [0, 238])++ def test_exact_multiple_needs_no_pull_back(self):+ self.assertEqual(T.tile_starts(T.WINDOW), [0])+ self.assertEqual(T.tile_starts(T.WINDOW + T.HOP), [0, 256])++ def test_zero_frames_is_refused(self):+ with self.assertRaises(ValueError):+ T.tile_starts(0)++ def test_no_frame_is_left_unwritten(self):+ """A gap would leave a frame at code 0 — silence spliced into the middle+ of a recording. Only the pulled-back final window may overlap what came+ before it, and it wins, which is `joint_v6.predict`'s own behaviour."""+ for frames in (1, 100, 512, 513, 750, 1200, 2049, 9000):+ starts = T.tile_starts(frames)+ written = np.zeros(frames, np.int64)+ for start in starts:+ length = min(T.WINDOW, frames - start)+ low = start + (0 if start == 0 else T.TRIM)+ high = start + length - (0 if start + length >= frames else T.TRIM)+ written[low:high] += 1+ self.assertTrue((written >= 1).all(), f"{frames} frames: a gap at "+ f"{int(np.argmin(written))}")+ overlap = np.flatnonzero(written > 1)+ if overlap.size:+ self.assertGreaterEqual(int(overlap.min()), starts[-1],+ f"{frames} frames: an overlap before the final window")+ self.assertNotIn(starts[-1], starts[:-1])+++class Windowing(unittest.TestCase):+ """`predict_codes` end to end on a tiny head with known weights."""++ def setUp(self):+ self.rng = np.random.default_rng(11)+ self.weights = _random_weights(self.rng)+ self.head = _small_head(self.weights)++ def test_every_code_comes_from_a_windows_centre(self):+ """Two properties at once: the code is the argmax of the window that+ claimed the frame, and no frame is decided within 128 frames of an+ interior window edge — the reason for the trim in the first place."""+ frames = 1200+ features = self.rng.standard_normal((frames, T.FEATURE_DIM)).astype(np.float32)+ codes = T.predict_codes(self.head, features)+ self.assertEqual(codes.shape, (frames,))+ owner = np.full(frames, -1, np.int64)+ argmax = {}+ for start in T.tile_starts(frames):+ length = min(T.WINDOW, frames - start)+ window = features[start:start + length]+ if length < T.WINDOW:+ window = np.pad(window, ((0, T.WINDOW - length), (0, 0)))+ argmax[start] = np.array(+ mx.argmax(self.head(mx.array(window[None])), axis=-1))[0, :length]+ low = start + (0 if start == 0 else T.TRIM)+ high = start + length - (0 if start + length >= frames else T.TRIM)+ owner[low:high] = start # a later window wins+ self.assertTrue((owner >= 0).all())+ for frame in range(frames):+ start = int(owner[frame])+ length = len(argmax[start])+ self.assertEqual(int(codes[frame]), int(argmax[start][frame - start]))+ if start:+ self.assertGreaterEqual(frame - start, T.TRIM)+ if start + length < frames:+ self.assertGreaterEqual(start + length - frame, T.TRIM)++ def test_a_short_track_is_padded_not_stretched(self):+ features = self.rng.standard_normal((90, T.FEATURE_DIM)).astype(np.float32)+ codes = T.predict_codes(self.head, features)+ self.assertEqual(len(codes), 90)++ def test_progress_reports_every_window(self):+ seen = []+ features = np.zeros((1200, T.FEATURE_DIM), np.float32)+ T.predict_codes(self.head, features, progress=lambda k, n: seen.append((k, n)))+ self.assertEqual(seen, [(index + 1, 4) for index in range(4)])++ def test_cancellation_is_honoured(self):+ features = np.zeros((1200, T.FEATURE_DIM), np.float32)+ with self.assertRaises(InterruptedError):+ T.predict_codes(self.head, features, cancelled=lambda: True)++ def test_the_wrong_feature_width_is_refused(self):+ with self.assertRaises(ValueError):+ T.predict_codes(self.head, np.zeros((100, 64), np.float32))+++class MertMixer(unittest.TestCase):+ def test_the_one_hot_sits_one_past_the_transformers_index(self):+ """transformers collects a hidden state only AFTER each conformer block,+ so hidden_states[k] is the output of layers[k]; lyra.mert's vector is one+ longer because index 0 is the pre-layer subsampled embedding. Verified+ against the real HF model: index 21 reproduces hidden_states[20] to+ 1.135e-04, while 19, 20 and 22 are off by 7.3, 12.2 and 19.8."""+ weights = np.array(T._mixer_weights(24, 20))+ self.assertEqual(weights.shape, (25,))+ self.assertEqual(float(weights[21]), 1.0)+ self.assertEqual(float(weights.sum()), 1.0)++ def test_the_default_layer_is_the_head_metadata_layer(self):+ self.assertEqual(T.MERT_LAYER, 20)++ def test_a_layer_outside_the_stack_is_refused(self):+ for layer in (-1, 24, 99):+ with self.assertRaises(ValueError):+ T._mixer_weights(24, layer)+++class CodeStatistics(unittest.TestCase):+ def test_a_collapsed_stream_reads_as_collapsed(self):+ stats = T.code_statistics(np.zeros(500, np.int64))+ self.assertEqual(stats["unique"], 1)+ self.assertEqual(stats["repeat"], 1.0)+ self.assertEqual(stats["run_max"], 500)+ self.assertEqual(stats["seconds"], 20.0)++ def test_a_healthy_stream_reads_as_healthy(self):+ codes = np.arange(750, dtype=np.int64) % 600+ stats = T.code_statistics(codes)+ self.assertEqual(stats["unique"], 600)+ self.assertEqual(stats["repeat"], 0.0)+ self.assertEqual(stats["run_mean"], 1.0)++ def test_frames_convert_at_twenty_five_per_second(self):+ self.assertEqual(T.code_statistics(np.zeros(250, np.int64))["seconds"], 10.0)++ def test_empty_is_refused(self):+ with self.assertRaises(ValueError):+ T.code_statistics(np.zeros(0, np.int64))+++class Measurements(unittest.TestCase):+ def test_a_recording_measured_against_itself_is_zero(self):+ rng = np.random.default_rng(1)+ audio = rng.standard_normal(48000).astype(np.float32) * 0.1+ self.assertEqual(T.spectral_distance(audio, audio), 0.0)+ self.assertAlmostEqual(T.chroma_correlation(audio, audio), 1.0, places=5)++ def test_a_different_note_is_further_away_than_the_same_note(self):+ """Both measures have to rank a re-performance of the same note above a+ different note. Everything is mixed with the same noise floor: a log-mel+ distance between a bare tone and anything else is dominated by the empty+ bins, where the log of 1e-5 is not a musical fact."""+ rng = np.random.default_rng(2)+ time = np.arange(96000, dtype=np.float64) / 48000+ floor = lambda seed: 0.05 * np.random.default_rng(seed).standard_normal(len(time)) # noqa: E731+ tone = lambda hz, seed: (np.sin(2 * np.pi * hz * time) + floor(seed)).astype(np.float32) # noqa: E731+ reference = tone(440, 1)+ same = tone(440, 2) # a second take+ other = tone(880, 2) # an octave up+ self.assertLess(T.spectral_distance(reference, same),+ T.spectral_distance(reference, other))+ self.assertGreater(T.chroma_correlation(reference, same),+ T.chroma_correlation(reference, other))+ del rng++ def test_a_non_finite_recording_is_refused(self):+ audio = np.zeros(48000, np.float32)+ audio[10] = np.nan+ with self.assertRaises(ValueError):+ T.log_mel(audio)+++def pinned_stand_in(path: Path, source: dict) -> None:+ """A file of the PINNED size. Readiness is size-checked (Codex review,+ 2026-09-22), so a one-byte placeholder IS a truncated download now.+ Sparse — instant, and it costs no disk."""+ path.parent.mkdir(parents=True, exist_ok=True)+ with path.open("wb") as handle:+ handle.truncate(int(source["bytes"]))+++class ThePack(unittest.TestCase):+ def test_the_head_is_not_offered_as_a_lora(self):+ """`pack_adapters()` globs the root and `user/`. A head in the root+ would appear in the studio's picker as if it were an adapter."""+ root = Path(tempfile.mkdtemp(prefix="yue2-pack-"))+ pinned_stand_in(root / P.HEAD_SUBDIR / P.TOKENIZER_HEAD,+ P.HEAD_SOURCES[P.TOKENIZER_HEAD])+ pinned_stand_in(root / P.JOINT_NAR_ADAPTER, P.SOURCES[P.JOINT_NAR_ADAPTER])+ names = [entry["file"] for entry in P.pack_adapters(root)]+ self.assertIn(P.JOINT_NAR_ADAPTER, names)+ self.assertNotIn(P.TOKENIZER_HEAD, names)++ def test_adapter_readiness_does_not_depend_on_the_head(self):+ """An installed pack must not be declared broken by a new download."""+ root = Path(tempfile.mkdtemp(prefix="yue2-pack-"))+ for name, source in P.SOURCES.items():+ pinned_stand_in(root / name, source)+ self.assertEqual(P.lora_problems(root), [])+ self.assertEqual(P.head_problems(root), [P.TOKENIZER_HEAD])+ # …but the PACK is not whole until the head lands, which is the+ # question the Download button asks (Codex review, 2026-09-22).+ self.assertEqual(P.pack_problems(root),+ [f"{P.HEAD_SUBDIR}/{P.TOKENIZER_HEAD}"])++ def test_the_optional_assets_are_not_a_gate(self):+ root = Path(tempfile.mkdtemp(prefix="yue2-pack-"))+ pinned_stand_in(root / P.HEAD_SUBDIR / P.TOKENIZER_HEAD,+ P.HEAD_SOURCES[P.TOKENIZER_HEAD])+ self.assertEqual(P.head_problems(root), [])++ def test_the_head_and_the_adapter_come_from_one_revision(self):+ head = P.HEAD_SOURCES[P.TOKENIZER_HEAD]+ adapter = P.SOURCES[P.JOINT_NAR_ADAPTER]+ self.assertEqual(head["repo"], adapter["repo"])+ self.assertEqual(head["revision"], adapter["revision"])++ def test_every_pinned_part_carries_a_sha256_and_a_size(self):+ for name, source in {**P.SOURCES, **P.HEAD_SOURCES}.items():+ self.assertRegex(source["sha256"], r"^[0-9a-f]{64}$", name)+ self.assertGreater(source["bytes"], 0, name)++ def test_the_module_agrees_with_the_pack_on_the_pinned_head(self):+ self.assertEqual(T.HEAD_SHA256, P.HEAD_SOURCES[P.TOKENIZER_HEAD]["sha256"])+ self.assertIn(T.HEAD_VERSION, P.TOKENIZER_HEAD)++ def test_head_path_lives_under_the_subdirectory(self):+ self.assertEqual(P.head_path("/tmp/pack"),+ Path("/tmp/pack") / P.HEAD_SUBDIR / P.TOKENIZER_HEAD)+++class RunnerArguments(unittest.TestCase):+ """The argv contract the panel will build."""++ def setUp(self):+ import yue2_run++ self.run = yue2_run++ def _args(self, *extra):+ return self.run.parse_args([+ "--model-dir", "/tmp/generator", "--vae-dir", "/tmp/vae",+ "--output", "/tmp/song.wav", *extra])++ def test_the_prompt_round_trips_through_argv(self):+ args = self._args("--audio-prompt", "/tmp/take.wav",+ "--audio-prompt-seconds", "12.5",+ "--audio-prompt-start", "30")+ self.assertEqual(args.audio_prompt, Path("/tmp/take.wav"))+ self.assertEqual(args.audio_prompt_seconds, 12.5)+ self.assertEqual(args.audio_prompt_start, 30.0)++ def test_the_default_listen_is_ten_seconds(self):+ self.assertEqual(self._args().audio_prompt_seconds, 10.0)+ self.assertIsNone(self._args().audio_prompt)++ def test_a_missing_recording_is_refused_before_anything_loads(self):+ missing = Path(tempfile.mkdtemp()) / "nope.wav"+ self.assertEqual(self.run.main([+ "--model-dir", "/tmp/generator", "--vae-dir", "/tmp/vae",+ "--output", "/tmp/song.wav", "--style", "a test",+ "--audio-prompt", str(missing)]), 2)++ def test_an_absurd_duration_is_refused(self):+ real = Path(tempfile.mkdtemp()) / "take.wav"+ real.write_bytes(b"not really a wav")+ for seconds in ("0", "600"):+ self.assertEqual(self.run.main([+ "--model-dir", "/tmp/generator", "--vae-dir", "/tmp/vae",+ "--output", "/tmp/song.wav", "--style", "a test",+ "--audio-prompt", str(real), "--audio-prompt-seconds", seconds]), 2)++ def test_a_prompt_and_a_variation_do_not_mix(self):+ real = Path(tempfile.mkdtemp()) / "take.wav"+ real.write_bytes(b"not really a wav")+ artifacts = Path(tempfile.mkdtemp())+ (artifacts / "result.json").write_text("{}")+ self.assertEqual(self.run.main([+ "--model-dir", "/tmp/generator", "--vae-dir", "/tmp/vae",+ "--output", "/tmp/song.wav", "--audio-prompt", str(real),+ "--from-artifacts", str(artifacts), "--variation", "take"]), 2)+++class TheCommandLine(unittest.TestCase):+ def test_encode_refuses_a_round_trip_without_the_models(self):+ code = subprocess.run(+ [sys.executable, str(ROOT / "scripts" / "music" / "yue2_tokenizer.py"), "encode",+ "/tmp/nothing.wav", "--out", "/tmp/codes.npy", "--roundtrip", "/tmp/out.wav"],+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=180)+ self.assertEqual(code.returncode, 2)+ self.assertIn(b"--model-dir", code.stdout)++ def test_check_reports_the_head_separately(self):+ root = Path(tempfile.mkdtemp(prefix="yue2-pack-"))+ for name, source in P.SOURCES.items():+ pinned_stand_in(root / name, source)+ done = subprocess.run(+ [sys.executable, str(ROOT / "scripts" / "pinokio" / "music_lora_fetch.py"),+ "--root", str(root), "--check"],+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=180)+ payload = json.loads(done.stdout.decode())+ self.assertTrue(payload["ready"])+ self.assertFalse(payload["head_ready"])+ self.assertFalse(payload["complete"])+ self.assertEqual(payload["head_missing"], [P.TOKENIZER_HEAD])+++if __name__ == "__main__":+ unittest.main(verbosity=2)diff --git a/test_yue2_train_voice.py b/test_yue2_train_voice.pynew file mode 100644index 0000000..ecbe466--- /dev/null+++ b/test_yue2_train_voice.py@@ -0,0 +1,551 @@+"""Training a voice: the rules the trainer has to obey before it burns an hour of GPU.++CPU only, no YuE2 weights, no MERT, no audio. What is pinned here:++ * a training sequence is EXACTLY `token_prefixes(request) + codes`, checked+ against the engine's own function, in both dialects;+ * the loss mask supervises the code tail and nothing else — the bug that+ teaches a model to write prompts instead of to sing;+ * a window's lyrics are the words sung inside that window, not the whole+ song, because a prefix that lies about its codes is what stopped new+ lyrics being pronounced at all;+ * the score dialect carries a real ABC score, and the engine still refuses+ the combination the score dialect exists to avoid (`abc` with `cot=off`);+ * a saved checkpoint reads back through the production loader with one rank+ and every target, and its sidecar says what the file is;+ * the CLI plans a real dataset and exits 0, and refuses a bad flag with 2.+"""+from __future__ import annotations++import json+import os+from pathlib import Path+import subprocess+import sys+import tempfile+import unittest++import mlx.core as mx+import mlx.nn as nn+import numpy as np++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT / "scripts" / "music"))+sys.path.insert(0, str(ROOT / "yue2-mlx" / "vendor" / "yue" / "src"))+os.environ.setdefault("LTX_STATE_DIR", tempfile.mkdtemp(prefix="yue2-voice-state-"))+os.environ["PHOSPHENE_ANALYTICS_DISABLED"] = "1"+os.environ["PHOSPHENE_DISABLE_VERSION_CHECK"] = "1"++import yue2_lora as L # noqa: E402+import yue2_train_voice as V # noqa: E402+from yue2.protocol import (CODEC_OFFSET, MUSIC_END, MUSIC_START, # noqa: E402+ SongRequest, token_prefixes)++HIDDEN, KV, INTERMEDIATE, LAYERS, RANK = 16, 8, 32, 2, 4+++class FakeTokenizer:+ """Deterministic text → ids, inside the ordinary text vocabulary."""++ def encode(self, text):+ return [(ord(ch) % 4000) + 7 for ch in text]+++def codes(n, seed=0):+ return np.random.default_rng(seed).integers(0, 32768, size=n, dtype=np.int64)+++# --------------------------------------------------------------- sequences --++class SequenceLayout(unittest.TestCase):+ def setUp(self):+ self.tok = FakeTokenizer()++ def test_a_direct_sequence_is_the_engines_prefix_then_the_codes(self):+ request = V.window_request("piano ballad", "frddtrn", "a line",+ dialect="direct", abc=None, cot="melody", identifier="w0")+ want = token_prefixes(request, self.tok)+ body = codes(120)+ ids, prefix_len = V.training_sequence(want, body, 4096)+ self.assertEqual(ids[:prefix_len], list(want))+ self.assertEqual(prefix_len, len(want))+ self.assertEqual(ids[prefix_len:-1], [int(c) + CODEC_OFFSET for c in body])+ self.assertEqual(ids[-1], MUSIC_END)+ self.assertEqual(want[-1], MUSIC_START)++ def test_a_score_sequence_carries_the_abc_inside_the_prefix(self):+ score = "X:1\nL:1/8\nK:Bb\nV:Vocal\nB c d2 |\n"+ request = V.window_request("piano ballad", "frddtrn", "a line",+ dialect="score", abc=score, cot="melody",+ identifier="w0")+ prefix = token_prefixes(request, self.tok)+ self.assertEqual(request.cot, "melody")+ # the ABC ids really are in there, between ABC_START and ABC_END+ abc_ids = self.tok.encode(score)+ joined = ",".join(map(str, prefix))+ self.assertIn(",".join(map(str, abc_ids)), joined)+ ids, prefix_len = V.training_sequence(prefix, codes(120), 4096)+ self.assertEqual(ids[:prefix_len], list(prefix))+ self.assertGreater(prefix_len, len(token_prefixes(+ SongRequest(style="piano ballad", lyrics="a line", cot="off"), self.tok)))++ def test_the_score_dialect_needs_a_score(self):+ with self.assertRaises(ValueError):+ V.window_request("s", "t", "l", dialect="score", abc=None,+ cot="melody", identifier="w0")+ with self.assertRaises(ValueError):+ V.window_request("s", "t", "l", dialect="score", abc=" ",+ cot="melody", identifier="w0")++ def test_the_engine_still_refuses_a_score_with_direct_planning(self):+ # The reason the score dialect exists at all.+ with self.assertRaises(ValueError):+ SongRequest(style="s", lyrics="l", cot="off", abc="X:1\n")++ def test_the_trigger_joins_the_style_once(self):+ first = V.window_request("piano ballad", "frddtrn", "l", dialect="direct",+ abc=None, cot="melody", identifier="w0")+ self.assertTrue(first.style.startswith("frddtrn,"))+ again = V.window_request(first.style, "frddtrn", "l", dialect="direct",+ abc=None, cot="melody", identifier="w0")+ self.assertEqual(again.style.lower().count("frddtrn"), 1)++ def test_codes_outside_the_vocabulary_never_reach_the_model(self):+ with self.assertRaises(ValueError):+ V.training_sequence([1, 2, 3], np.array([32768]), 4096)+ with self.assertRaises(ValueError):+ V.training_sequence([1, 2, 3], np.array([-1]), 4096)++ def test_a_prefix_that_leaves_no_room_is_refused_not_truncated(self):+ with self.assertRaises(ValueError):+ V.training_sequence(list(range(1000)), codes(600), 1024)++ def test_a_long_track_is_windowed_rather_than_truncated(self):+ prefix, body = [5] * 10, codes(5000)+ ids, prefix_len = V.training_sequence(prefix, body, 1024, rng=None)+ self.assertEqual(len(ids), 1024 - 1)+ self.assertEqual(ids[prefix_len], int(body[0]) + CODEC_OFFSET)+ import random+ picked = {V.training_sequence(prefix, body, 1024, rng=random.Random(s))[0][10]+ for s in range(8)}+ self.assertGreater(len(picked), 1, "a random window should move")+++# -------------------------------------------------------------- loss mask --++class LossMask(unittest.TestCase):+ def test_only_the_code_tail_is_supervised(self):+ prefix = token_prefixes(SongRequest(style="s", lyrics="l", cot="off"),+ FakeTokenizer())+ body = codes(64)+ ids, prefix_len = V.training_sequence(prefix, body, 4096)+ states, labels = V.supervised_span(prefix_len, len(ids))+ targets = ids[labels]+ self.assertEqual(len(targets), len(body) + 1) # codes + MUSIC_END+ self.assertTrue(all(t >= CODEC_OFFSET or t == MUSIC_END for t in targets))+ self.assertEqual(states.stop - states.start, labels.stop - labels.start)+ # the first scored hidden state is the LAST prefix position+ self.assertEqual(states.start, prefix_len - 1)+ self.assertEqual(labels.start, prefix_len)++ def test_no_prefix_token_is_ever_a_target(self):+ prefix = list(range(1, 40))+ ids, prefix_len = V.training_sequence(prefix, codes(80), 4096)+ _, labels = V.supervised_span(prefix_len, len(ids))+ self.assertEqual(set(ids[labels]) & set(prefix), set())++ def test_an_empty_tail_is_refused(self):+ with self.assertRaises(ValueError):+ V.supervised_span(10, 10)+++# ----------------------------------------------------------------- windows --++class Windows(unittest.TestCase):+ def test_windows_cover_the_track_and_the_last_one_is_flush_with_the_end(self):+ spans = V.plan_windows(8988, 512, 256)+ self.assertEqual(spans[0], (0, 512))+ self.assertEqual(spans[-1][1], 8988)+ self.assertTrue(all(b - a == 512 for a, b in spans))+ covered = set()+ for a, b in spans:+ covered |= set(range(a, b))+ self.assertEqual(len(covered), 8988)++ def test_a_short_track_is_one_window_and_a_scrap_is_none(self):+ self.assertEqual(V.plan_windows(300, 512, 256), [(0, 300)])+ self.assertEqual(V.plan_windows(10, 512, 256), [])++ def test_timed_lyrics_put_the_sung_words_in_their_own_window(self):+ lines = [{"text": "one", "onset": 1.0, "end": 3.0, "section": "[Verse]"},+ {"text": "two", "onset": 12.0, "end": 14.0},+ {"text": "three", "onset": 25.0, "end": 27.0, "section": "[Chorus]"}]+ first = V.lyrics_for_window("", lines, 0.0, 20.48, 40.0)+ self.assertEqual(first.splitlines(), ["[Verse]", "one", "two"])+ second = V.lyrics_for_window("", lines, 20.48, 40.0, 40.0)+ self.assertEqual(second.splitlines(), ["[Chorus]", "three"])+ self.assertNotIn("one", second)++ def test_a_line_still_running_into_the_window_is_kept(self):+ lines = [{"text": "held", "onset": 18.0, "end": 24.0}]+ self.assertIn("held", V.lyrics_for_window("", lines, 20.48, 40.0, 40.0))++ def test_without_timings_the_window_gets_its_share_not_the_whole_song(self):+ sheet = "[Verse]\n" + "\n".join(f"line {i}" for i in range(20))+ early = V.lyrics_for_window(sheet, None, 0.0, 10.0, 100.0)+ late = V.lyrics_for_window(sheet, None, 90.0, 100.0, 100.0)+ self.assertIn("line 0", early)+ self.assertNotIn("line 19", early)+ self.assertIn("line 19", late)+ self.assertNotIn("line 0", late)+ self.assertLess(len(early.splitlines()), 20)++ def test_a_reader_drops_a_line_it_could_not_locate(self):+ with tempfile.TemporaryDirectory() as tmp:+ path = Path(tmp) / "x.lines.json"+ path.write_text(json.dumps([{"text": "a", "onset": 1.0},+ {"text": "b"},+ {"text": "", "onset": 2.0}]))+ rows = V.read_timed_lines(path)+ self.assertEqual([row["text"] for row in rows], ["a"])++ def test_the_dataset_pairs_each_window_with_its_own_codes(self):+ with tempfile.TemporaryDirectory() as tmp:+ audio = Path(tmp) / "song.wav"+ audio.write_bytes(b"RIFF")+ (Path(tmp) / "song.txt").write_text("[Verse]\nalpha\nbeta\ngamma\ndelta")+ body = codes(1024, seed=3)+ items, windows, skipped = V.build_dataset(+ [audio], style="ballad", trigger="frddtrn", dialect="direct",+ cot="melody", lyrics_sources=[tmp], window_frames=512, hop_frames=256,+ tokenizer=FakeTokenizer(), codes_of=lambda _: body, say=lambda *a: None)+ self.assertEqual(len(items), len(windows))+ self.assertEqual([w.frames for w in windows], [512] * len(windows))+ self.assertEqual(len(items[0]["codec"]), 512)+ np.testing.assert_array_equal(items[0]["codec"], body[:512])+ np.testing.assert_array_equal(items[1]["codec"], body[256:768])+ self.assertEqual(skipped["no_score"], 0)+ self.assertTrue(all(item["src"] == "artist" for item in items))++ def test_one_lyric_sheet_for_one_recording_does_not_need_a_matching_name(self):+ with tempfile.TemporaryDirectory() as tmp:+ audio = Path(tmp) / "frddtrn.wav"+ audio.write_bytes(b"RIFF")+ sheet = Path(tmp) / "whatever_the_sheet_is_called.txt"+ sheet.write_text("[Verse]\nalpha\nbeta\ngamma\ndelta")+ _, windows, skipped = V.build_dataset(+ [audio], style="ballad", trigger="t", dialect="direct", cot="melody",+ lyrics_sources=[str(sheet)], window_frames=512, hop_frames=256,+ tokenizer=FakeTokenizer(), codes_of=lambda _: codes(1024, seed=9),+ say=lambda *a: None)+ self.assertEqual(skipped["no_lyrics"], 0)+ self.assertTrue(all(w.lyrics.strip() for w in windows))+ # ...but two recordings and one unnamed sheet stay unmatched+ self.assertIsNone(V.match_sidecar(Path("a.wav"), ["b.txt"], (".txt",)))++ def test_a_score_dialect_window_without_a_score_is_skipped_not_faked(self):+ with tempfile.TemporaryDirectory() as tmp:+ audio = Path(tmp) / "song.wav"+ audio.write_bytes(b"RIFF")+ scores = Path(tmp) / "scores"+ scores.mkdir()+ (scores / "song.w000.abc").write_text("X:1\nL:1/8\nK:C\nV:Vocal\nC D E2 |\n")+ items, windows, skipped = V.build_dataset(+ [audio], style="ballad", trigger="t", dialect="score", cot="melody",+ lyrics_sources=None, scores_dir=scores, window_frames=512,+ hop_frames=256, tokenizer=FakeTokenizer(),+ codes_of=lambda _: codes(1024, seed=4), say=lambda *a: None)+ self.assertEqual(len(items), 1)+ self.assertEqual(windows[0].index, 0)+ self.assertGreater(skipped["no_score"], 0)+ self.assertTrue(windows[0].abc)+++# ------------------------------------------------------------- checkpoints --++class _Attention(nn.Module):+ def __init__(self):+ super().__init__()+ self.q_proj = nn.Linear(HIDDEN, HIDDEN, bias=False)+ self.k_proj = nn.Linear(HIDDEN, KV, bias=False)+ self.v_proj = nn.Linear(HIDDEN, KV, bias=False)+ self.o_proj = nn.Linear(HIDDEN, HIDDEN, bias=False)+++class _MLP(nn.Module):+ def __init__(self):+ super().__init__()+ self.gate_proj = nn.Linear(HIDDEN, INTERMEDIATE, bias=False)+ self.up_proj = nn.Linear(HIDDEN, INTERMEDIATE, bias=False)+ self.down_proj = nn.Linear(INTERMEDIATE, HIDDEN, bias=False)+++class _Layer(nn.Module):+ def __init__(self):+ super().__init__()+ self.self_attn = _Attention()+ self.mlp = _MLP()+++class _Backbone(nn.Module):+ def __init__(self):+ super().__init__()+ self.layers = [_Layer() for _ in range(LAYERS)]++ def __call__(self, ids):+ return mx.zeros((ids.shape[0], ids.shape[1], HIDDEN))+++class _Model(nn.Module):+ def __init__(self):+ super().__init__()+ self.model = _Backbone()+ self.lm_head = nn.Linear(HIDDEN, 64, bias=False)+++class Checkpoints(unittest.TestCase):+ def test_a_saved_file_reads_back_through_the_production_loader(self):+ model = _Model()+ slots, params = V.install_adapters(model, RANK, seed=7)+ self.assertEqual(len(params), LAYERS * 7)+ with tempfile.TemporaryDirectory() as tmp:+ path = Path(tmp) / "frddtrn.safetensors"+ V.save_adapter(params, path, rank=RANK, dialect="direct", trigger="frddtrn")+ adapter = L.read_adapter(path)+ self.assertEqual(adapter.rank, RANK)+ self.assertEqual(adapter.branch, "ar")+ self.assertEqual(len(adapter.deltas), LAYERS * 7)+ for layer in range(LAYERS):+ for group, names in (("self_attn", V.ATTN_PROJECTIONS),+ ("mlp", V.MLP_PROJECTIONS)):+ for projection in names:+ self.assertIn(V.adapter_key(layer, group, projection), adapter.deltas)++ def test_a_fresh_adapter_is_the_identity_so_step_zero_is_the_base_model(self):+ model = _Model()+ slots, params = V.install_adapters(model, RANK, seed=7)+ V.bind(slots, params)+ x = mx.random.normal((3, HIDDEN))+ base = nn.Linear(HIDDEN, HIDDEN, bias=False)+ base.weight = model.model.layers[0].self_attn.q_proj.weight+ self.assertTrue(mx.allclose(model.model.layers[0].self_attn.q_proj(x), base(x)))++ def test_wrapping_renames_not_one_parameter(self):+ from mlx.utils import tree_flatten+ before = {k for k, _ in tree_flatten(_Model().parameters())}+ model = _Model()+ V.install_adapters(model, RANK, seed=7)+ self.assertEqual({k for k, _ in tree_flatten(model.parameters())}, before)++ def test_the_sidecar_says_what_the_file_is_and_what_made_it(self):+ windows = [V.Window("song.wav", 0, 0.0, 20.48, "a line", None, 512),+ V.Window("song.wav", 1, 10.24, 20.48, "", None, 512)]+ meta = V.sidecar_metadata(+ name="frddtrn", trigger="frddtrn", dialect="direct", cot="melody",+ style="piano ballad", model_dir=ROOT / "mlx_models" / "yue2" / "generator",+ steps=400, rank=32, lr=1e-4, window_seconds=20.48, hop_seconds=10.24,+ windows=windows, skipped={"no_score": 0}, fingerprint="abc123",+ metrics={"history": [{"step": 0, "artist": 5.3}]}, seed=4242,+ artist_fraction=0.5)+ self.assertEqual(meta["trigger"], "frddtrn")+ self.assertEqual(meta["dialect"], "direct")+ self.assertEqual(meta["branch"], "ar")+ self.assertEqual(meta["generate_with"], "--mode off")+ self.assertEqual(meta["training"]["steps"], 400)+ self.assertEqual(meta["data"]["fingerprint"], "abc123")+ self.assertEqual(meta["data"]["windows_with_lyrics"], 1)+ self.assertEqual(meta["data"]["recordings"], ["song.wav"])+ self.assertTrue(meta["metrics"]["history"])+ json.dumps(meta) # has to serialise++ def test_the_score_dialect_sidecar_tells_the_caller_it_needs_a_score(self):+ meta = V.sidecar_metadata(+ name="v", trigger="t", dialect="score", cot="melody", style="s",+ model_dir=Path("/nowhere"), steps=1, rank=8, lr=1e-4, window_seconds=20.48,+ hop_seconds=10.24, windows=[], skipped={}, fingerprint="f", metrics={},+ seed=1, artist_fraction=0.5)+ self.assertIn("--abc-file", meta["generate_with"])+ self.assertIn("--mode melody", meta["generate_with"])+++# ------------------------------------------------- caches and identity --++class RegulariserCache(unittest.TestCase):+ """The cache is data. It was a pickle, and a pickle is code."""++ def test_a_cache_round_trips_without_pickles(self):+ items = [{"src": "minted", "name": "m0", "prefix": np.array([1, 2, 3]),+ "codec": codes(40, seed=1)},+ {"src": "minted_val", "name": "m1", "prefix": np.array([4, 5]),+ "codec": codes(7, seed=2)}]+ with tempfile.TemporaryDirectory() as tmp:+ path = Path(tmp) / "reg.npz"+ V.write_regularizer_cache(path, items)+ # the file itself must be loadable with pickles DISABLED+ with np.load(path, allow_pickle=False) as blob:+ self.assertIn("prefix_data", blob.files)+ self.assertNotIn("items", blob.files)+ back = V.read_regularizer_cache(path)+ self.assertEqual([row["src"] for row in back], ["minted", "minted_val"])+ self.assertEqual([row["name"] for row in back], ["m0", "m1"])+ for want, got in zip(items, back):+ np.testing.assert_array_equal(want["prefix"], got["prefix"])+ np.testing.assert_array_equal(want["codec"], got["codec"])++ def test_an_object_array_cache_is_refused_rather_than_unpickled(self):+ with tempfile.TemporaryDirectory() as tmp:+ path = Path(tmp) / "legacy.npz"+ np.savez(path, items=np.asarray([{"src": "minted", "name": "m0",+ "prefix": np.array([1]),+ "codec": np.array([2])}], dtype=object))+ with self.assertRaises(ValueError) as caught:+ V.read_regularizer_cache(path)+ self.assertIn("regulariser cache", str(caught.exception))++ def test_a_cache_claiming_another_version_is_refused(self):+ with tempfile.TemporaryDirectory() as tmp:+ path = Path(tmp) / "future.npz"+ empty = np.zeros(0, dtype=np.int64)+ np.savez(path, version=np.asarray(99, dtype=np.int64),+ prefix_data=empty, prefix_offsets=np.zeros(1, dtype=np.int64),+ codec_data=empty, codec_offsets=np.zeros(1, dtype=np.int64),+ meta=np.asarray("[]"))+ with self.assertRaises(ValueError):+ V.read_regularizer_cache(path)+++class CodesCacheIdentity(unittest.TestCase):+ """Two albums both holding a take.wav must not share one cache entry."""++ def test_the_key_follows_the_bytes_not_the_name(self):+ with tempfile.TemporaryDirectory() as tmp:+ tmp = Path(tmp)+ head = tmp / "head.safetensors"+ head.write_bytes(b"HEAD")+ (tmp / "a").mkdir()+ (tmp / "b").mkdir()+ first, second = tmp / "a" / "take.wav", tmp / "b" / "take.wav"+ first.write_bytes(b"RIFF" + b"\x01" * 512)+ second.write_bytes(b"RIFF" + b"\x02" * 512)+ same = tmp / "c.wav"+ same.write_bytes(first.read_bytes())+ key_first = V.codes_cache_key(first, head)+ key_second = V.codes_cache_key(second, head)+ key_same = V.codes_cache_key(same, head)+ other_head = tmp / "other.safetensors"+ other_head.write_bytes(b"OTHER")+ key_other_head = V.codes_cache_key(first, other_head)+ self.assertEqual(first.name, second.name) # the collision that bit+ self.assertNotEqual(key_first, key_second)+ self.assertEqual(key_first, key_same) # same bytes, same key+ self.assertNotEqual(key_first, key_other_head) # the head is part of it++ def test_a_cache_entry_for_other_bytes_is_not_reused(self):+ calls = []++ with tempfile.TemporaryDirectory() as tmp:+ tmp = Path(tmp)+ head = tmp / "head.safetensors"+ head.write_bytes(b"HEAD")+ audio = tmp / "take.wav"+ audio.write_bytes(b"RIFF" + b"\x01" * 256)+ cache = tmp / "codes"+ cache.mkdir()+ key = V.codes_cache_key(audio, head)+ np.save(cache / f"take.{key}.codes.npy", codes(64, seed=8).astype(np.int32))+ (cache / f"take.{key}.codes.json").write_text(json.dumps({"cache_key": key}))+ got = V._codes_for(audio, cache, head, None, lambda *a: calls.append(a))+ self.assertEqual(len(got), 64) # the hit, no encoding+ audio.write_bytes(b"RIFF" + b"\x09" * 256) # the recording is replaced+ stale_key = V.codes_cache_key(audio, head)+ self.assertNotEqual(stale_key, key)+ self.assertFalse((cache / f"take.{stale_key}.codes.npy").is_file())+++class HeadResolution(unittest.TestCase):+ def test_an_explicit_head_that_is_not_there_is_named(self):+ with self.assertRaises(FileNotFoundError):+ V.resolve_head(Path("/nowhere/head.safetensors"), None)++ def test_a_missing_pack_says_what_to_install_instead_of_TypeError(self):+ with tempfile.TemporaryDirectory() as tmp:+ with self.assertRaises(FileNotFoundError) as caught:+ V.resolve_head(None, Path(tmp))+ message = str(caught.exception)+ self.assertIn("tokenizer head", message)+ self.assertNotIn("NoneType", message)++ def test_an_explicit_head_is_returned_as_given(self):+ with tempfile.TemporaryDirectory() as tmp:+ head = Path(tmp) / "head.safetensors"+ head.write_bytes(b"HEAD")+ self.assertEqual(V.resolve_head(head, None), head)+++# --------------------------------------------------------------- the CLI --++class CommandLine(unittest.TestCase):+ SCRIPT = ROOT / "scripts" / "music" / "yue2_train_voice.py"++ def run_cli(self, *argv):+ return subprocess.run([sys.executable, str(self.SCRIPT), *argv],+ capture_output=True, text=True, timeout=300)++ def test_help_exits_zero_and_advertises_the_flags_the_brief_asked_for(self):+ done = self.run_cli("--help")+ self.assertEqual(done.returncode, 0, done.stderr)+ for flag in ("--recordings", "--lyrics", "--trigger", "--out", "--steps",+ "--rank", "--lr", "--dialect", "--reg-pack"):+ self.assertIn(flag, done.stdout)++ def test_a_flag_that_is_not_ours_exits_two(self):+ self.assertEqual(self.run_cli("--recordings", "x", "--out", "y",+ "--dialect", "karaoke").returncode, 2)+ self.assertEqual(self.run_cli("--out", "y").returncode, 2)++ def test_a_plan_only_run_builds_a_real_dataset_and_exits_zero(self):+ with tempfile.TemporaryDirectory() as tmp:+ tmp = Path(tmp)+ audio = tmp / "song.wav"+ audio.write_bytes(b"RIFF" + b"\0" * 64)+ (tmp / "song.txt").write_text("[Verse]\nalpha\nbeta\ngamma\ndelta\n")+ cache = tmp / "codes"+ cache.mkdir()+ head = tmp / "head.safetensors"+ head.write_bytes(b"HEAD")+ key = V.codes_cache_key(audio, head)+ np.save(cache / f"song.{key}.codes.npy", codes(1024, seed=5).astype(np.int32))+ (cache / f"song.{key}.codes.json").write_text(json.dumps({"cache_key": key}))+ out = tmp / "out"+ done = self.run_cli("--recordings", str(audio), "--lyrics", str(tmp / "song.txt"),+ "--trigger", "frddtrn", "--out", str(out),+ "--style", "piano ballad", "--codes-cache", str(cache),+ "--head", str(head), "--plan-only")+ self.assertEqual(done.returncode, 0, done.stdout + done.stderr)+ plan = json.loads((out / "plan.json").read_text())+ self.assertEqual(len(plan["windows"]), len(V.plan_windows(1024, 512, 256)))+ self.assertTrue(all(w["abc"] is False for w in plan["windows"]))+ self.assertTrue(all(t > 0 for t in plan["prefix_tokens"]))+ self.assertIn("fingerprint", plan)++ def test_a_score_run_with_no_scores_folder_fails_loudly(self):+ with tempfile.TemporaryDirectory() as tmp:+ tmp = Path(tmp)+ audio = tmp / "song.wav"+ audio.write_bytes(b"RIFF" + b"\0" * 64)+ cache = tmp / "codes"+ cache.mkdir()+ head = tmp / "head.safetensors"+ head.write_bytes(b"HEAD")+ key = V.codes_cache_key(audio, head)+ np.save(cache / f"song.{key}.codes.npy", codes(1024, seed=6).astype(np.int32))+ (cache / f"song.{key}.codes.json").write_text(json.dumps({"cache_key": key}))+ done = self.run_cli("--recordings", str(audio), "--out", str(tmp / "out"),+ "--dialect", "score", "--codes-cache", str(cache),+ "--head", str(head), "--plan-only")+ self.assertNotEqual(done.returncode, 0)+ self.assertIn("No trainable windows", done.stdout + done.stderr)+++if __name__ == "__main__":+ unittest.main()diff --git a/update.js b/update.jsindex 0f0b142..4f2eb18 100644--- a/update.js+++ b/update.js@@ -100,9 +100,9 @@ module.exports = {params: {message: ["U=$(git rev-parse --abbrev-ref --symbolic-full-name @{u} 2>/dev/null)",- "[ -n \"$U\" ] || { echo 'FATAL: no upstream configured'; exit 1; }",+ "[ -n \"$U\" ] || { echo 'FATAL error: no upstream configured'; exit 1; }","echo \"updating $(git rev-parse --abbrev-ref HEAD) from $U\"",- "git fetch \"${U%%/*}\" || { echo 'FATAL: fetch failed (offline?) - nothing changed, re-run Update'; exit 1; }"+ "git fetch \"${U%%/*}\" || { echo 'FATAL error: fetch failed (offline?) - nothing changed, re-run Update'; exit 1; }"].join("\n")}},@@ -175,13 +175,13 @@ module.exports = {{method: "shell.run",params: {- message: "if [ -f scripts/pinokio/update_obstruction_guard.sh ]; then bash scripts/pinokio/update_obstruction_guard.sh; else echo 'FATAL: scripts/pinokio/update_obstruction_guard.sh missing - repair with: git checkout -- scripts/pinokio'; exit 1; fi"+ message: "if [ -f scripts/pinokio/update_obstruction_guard.sh ]; then bash scripts/pinokio/update_obstruction_guard.sh; else echo 'FATAL error: scripts/pinokio/update_obstruction_guard.sh missing - repair with: git checkout -- scripts/pinokio'; exit 1; fi"}},{method: "shell.run",params: {- message: "if [ -f scripts/pinokio/update_converge.sh ]; then bash scripts/pinokio/update_converge.sh; else echo 'FATAL: scripts/pinokio/update_converge.sh missing - repair with: git checkout -- scripts/pinokio'; exit 1; fi"+ message: "if [ -f scripts/pinokio/update_converge.sh ]; then bash scripts/pinokio/update_converge.sh; else echo 'FATAL error: scripts/pinokio/update_converge.sh missing - repair with: git checkout -- scripts/pinokio'; exit 1; fi"}},// ---- 2. Everything else, from the tree we just pulled ------------------@@ -199,7 +199,7 @@ module.exports = {{method: "shell.run",params: {- message: "if [ -f scripts/post_update.sh ]; then bash scripts/post_update.sh; else echo 'FATAL: scripts/post_update.sh missing - the repo pull above did not land. Re-run Update.'; exit 1; fi"+ message: "if [ -f scripts/post_update.sh ]; then bash scripts/post_update.sh; else echo 'FATAL error: scripts/post_update.sh missing - the repo pull above did not land. Re-run Update.'; exit 1; fi"}}]diff --git a/webapp/index.html b/webapp/index.htmlindex 37586b0..5b1f802 100644--- a/webapp/index.html+++ b/webapp/index.html@@ -3185,13 +3185,128 @@ The same wizard walks out of frame. Audio: footsteps on leaves."></textarea><div id="audioSectionTab" style="display:none"><div class="mode-bar pill-group cols-2" id="audioModeGroup" hidden><button type="button" class="mode-chip pill-btn" data-audio-mode="compose" onclick="audioModeSet('compose')">Compose<span class="mc-sub sub">write a song</span></button>- <button type="button" class="mode-chip pill-btn" data-audio-mode="drive" onclick="audioModeSet('drive')">Drive video<span class="mc-sub sub">use a track you have</span></button>+ <button type="button" class="mode-chip pill-btn" data-audio-mode="drive" onclick="audioModeSet('drive')">Music video<span class="mc-sub sub">a song and your pictures</span></button></div><div id="musicComposePane" hidden>+ <div class="studio-head">+ <div class="studio-head-text">+ <div class="studio-title">Music Studio</div>+ <div class="studio-sub">Write a song, cover one, or read the score off a recording.</div>+ </div>+ <!-- SIMPLE or CUSTOM. Simple is one box: say what the song is and+ Gemma writes the style and the words for you to read. Custom is+ the studio — the same two fields, yours to type. The choice is+ remembered (phos_music_mode); Custom is the default because it+ is what the fields on this page already are. -->+ <div class="studio-seg" id="musicModeSeg" role="group" aria-label="How much you fill in">+ <button type="button" class="seg-btn" data-value="simple" onclick="musicModePick(this)">Simple</button>+ <button type="button" class="seg-btn active" data-value="custom" onclick="musicModePick(this)">Custom</button>+ </div>+ </div>+ <!-- The engine's install lives above both modes: it is about YuE2+ being here, not about which form you are filling in. --><div class="composer-card music-install-panel" id="musicInstallPanel" role="status" hidden></div>+ <div id="musicSimplePane" hidden>+ <div class="composer-card">+ <label for="musicSimpleDescription">Describe the song</label>+ <textarea id="musicSimpleDescription" class="composer-prompt" rows="4"+ placeholder="Who sings it, what it is about, how it sounds — e.g. a slow piano ballad for a friend moving away, a woman with a low warm voice, brushed drums, a little sad but not bitter"></textarea>+ <div class="hint">One breath is enough. Gemma turns it into a style and the words, and shows you both before anything renders.</div>+ <div class="composer-tools">+ <label class="toggle-pill" id="musicSimpleInstrumentalPill" title="When on, the model is asked for a track with no vocal line — Gemma writes the style only, no words.">+ <input type="checkbox" id="musicSimpleInstrumental" onchange="musicSimpleChanged()"><span class="dot"></span><span>Instrumental</span>+ </label>+ </div>+ </div>+ <div class="quick-settings">+ <div class="range-strip">+ <label for="musicSimpleSeconds">Max length</label>+ <input type="range" id="musicSimpleSeconds" min="30" max="360" step="15" value="240" oninput="musicSimpleChanged()">+ <span id="musicSimpleSecondsVal">4:00</span>+ </div>+ <div class="hint">How long the words are written for, and the ceiling on the song. It never stretches a short one.</div>+ </div>+ </div>+ <div id="musicCustomPane">+ <div class="music-notice" id="musicSimpleNotice" role="status" hidden></div>+ <!-- THREE TASKS, one form. Write is the composer as it was; Cover+ opens the cover section; Score is transcription only — listen+ to a recording and get its sheet music, no song rendered. -->+ <div class="studio-tasks studio-seg full" id="musicTaskPills" role="group" aria-label="What to make">+ <button type="button" class="seg-btn active" data-value="write" onclick="musicTaskPick(this)">Write a song</button>+ <button type="button" class="seg-btn" data-value="cover" onclick="musicTaskPick(this)">Cover a song</button>+ <button type="button" class="seg-btn" data-value="score" onclick="musicTaskPick(this)">Get the score</button>+ </div>+ <input type="hidden" id="musicTask" value="write">+ <!-- COVER. The engine can read a score off a record: SheetSage2+ transcribes the source into ABC, and that becomes the plan the+ generator realises under YOUR style and YOUR lyrics. Closed by+ default because most songs start from a prompt, and the two+ transcription models are an opt-in 2.8 GB on top of the pack. -->+ <details class="customize-section" id="musicCoverDetails">+ <summary class="cz-summary">+ <span class="cz-chevron" aria-hidden="true"><svg class="ph"><use href="#ph-caret-down-bold"/></svg></span>+ <span class="cz-title">Cover a song</span>+ <span class="cz-meta" id="musicCoverSummary">off</span>+ </summary>+ <div class="cz-body">+ <div class="music-cover-install" id="musicCoverInstall" role="status" hidden></div>+ <label class="mf-label" for="musicSourceAudio">Source song</label>+ <input id="musicSourceAudio" placeholder="/path/to/the/song.mp3 — drag a file in"+ oninput="musicFormChanged()">+ <div class="hint">The tune comes off this recording. Everything else — style,+ lyrics, voice — is still yours. Leave empty to write a song from your prompt.</div>+ <div class="mf-label">Take from it</div>+ <div class="pill-group cols-3" id="musicCoverTaskPills">+ <button type="button" class="pill-btn active" data-value="melody-full"+ onclick="musicPick('musicCoverTask',this)">Melody + chords</button>+ <button type="button" class="pill-btn" data-value="melody-vocal"+ onclick="musicPick('musicCoverTask',this)">The sung line</button>+ <button type="button" class="pill-btn" data-value="full"+ onclick="musicPick('musicCoverTask',this)">Everything</button>+ </div>+ <input type="hidden" id="musicCoverTask" value="melody-full">+ <div class="hint" id="musicCoverTaskHint">Melody and the chords under it, read from the+ whole mix. <b>The sung line</b> takes the vocal only, so the arrangement is new.+ <b>Everything</b> keeps the accompaniment too and needs the longest read.</div>+ </div>+ </details><div class="composer-card">- <label for="musicLyrics">Lyrics</label>- <textarea id="musicLyrics" class="composer-prompt" rows="8" placeholder="[Verse]+ <label for="musicTitle">Title <span class="sub">optional</span></label>+ <input id="musicTitle" placeholder="What the song is called" maxlength="120" oninput="musicFormChanged()">+ <label for="musicConcept">What is it about?</label>+ <div class="concept-row">+ <textarea id="musicConcept" class="composer-prompt" rows="2" placeholder="A concept, a story, a feeling — one or two sentences. Gemma writes the lyrics in the format YuE2 reads."></textarea>+ <button type="button" class="ghost-btn" id="musicWriteLyricsBtn" onclick="musicWriteLyrics()" title="Gemma (local) writes section-tagged lyrics from the concept, in the style you gave below. Runs on this Mac.">Write lyrics</button>+ </div>+ <!-- THE LYRICS EDITOR. A song is sections, not a wall of text, so+ the editor shows sections: a label you can change, the lines+ under it, how many lines that is, and a Rewrite that asks Gemma+ for THAT part only. The bracket text stays the truth underneath+ — #musicLyrics is still the one field every caller reads — and+ Text flips to it for anyone who would rather type brackets. -->+ <div class="lyr-head">+ <span class="lyr-title">Lyrics</span>+ <div class="studio-seg" id="musicLyricsViewSeg" role="group" aria-label="How to edit the lyrics">+ <button type="button" class="seg-btn active" data-value="sections" onclick="musicLyricsViewPick(this)">Sections</button>+ <button type="button" class="seg-btn" data-value="text" onclick="musicLyricsViewPick(this)">Text</button>+ </div>+ </div>+ <div class="lyr-editor" id="musicLyricsEditor">+ <div class="lyr-sections" id="musicLyricsSections"></div>+ <div class="lyr-add" id="musicLyricsAdd">+ <span class="lyr-add-label">Add</span>+ <button type="button" class="tag-chip" onclick="musicLyricsAdd('Intro')">Intro</button>+ <button type="button" class="tag-chip" onclick="musicLyricsAdd('Verse')">Verse</button>+ <button type="button" class="tag-chip" onclick="musicLyricsAdd('Pre-Chorus')">Pre-Chorus</button>+ <button type="button" class="tag-chip" onclick="musicLyricsAdd('Chorus')">Chorus</button>+ <button type="button" class="tag-chip" onclick="musicLyricsAdd('Bridge')">Bridge</button>+ <button type="button" class="tag-chip" onclick="musicLyricsAdd('Instrumental')">Instrumental</button>+ <button type="button" class="tag-chip" onclick="musicLyricsAdd('Outro')">Outro</button>+ </div>+ </div>+ <textarea id="musicLyricsRaw" class="composer-prompt" rows="10" hidden+ aria-label="Lyrics as text" onblur="musicLyricsRawSync()" placeholder="[Verse]Write the words here, one line at a time[Pre-Chorus]@@ -3205,7 +3320,11 @@ A different turn[Outro]The last line"></textarea>- <div class="hint">Tags in square brackets mark the sections. Everything else is sung. A tag with nothing under it is an instrumental passage.</div>+ <!-- The source of truth. Hidden, never typed into: the editor above+ writes it, musicFormParams reads it, and the restyle and score+ verbs on a song read it too. -->+ <textarea id="musicLyrics" hidden tabindex="-1" aria-hidden="true"></textarea>+ <div class="hint">Square brackets mark the sections; everything else is sung. A section with no words is an instrumental passage.</div><label for="musicStyle">Style</label><textarea id="musicStyle" class="composer-prompt" rows="2" placeholder="Genre, instruments, vocal, language and tempo in plain words — e.g. English, warm piano pop, expressive female voice, acoustic piano, light drums, 88 BPM"></textarea><div class="hint">Prose, not fields. Put the tempo, the language and the singer in the sentence.</div>@@ -3214,6 +3333,10 @@ The last line"></textarea><input type="checkbox" id="musicInstrumental" onchange="musicFormChanged()"><span class="dot"></span><span>Instrumental</span></label></div>+ <!-- Instrumental is two recipes, and which one runs depends on one+ 140 MB file. Said here, in place, rather than after a song comes+ back with a voice on it. -->+ <div class="music-pack-note" id="musicLoraInstall" role="status" hidden></div></div><div class="quick-settings"><div class="mf-label">Score</div>@@ -3240,166 +3363,286 @@ The last line"></textarea><div class="mini-fields"><div class="mf-cell"><label class="mf-label" for="musicSeed">Seed</label><input type="number" id="musicSeed" value="-1" min="-1" max="4294967295" step="1" placeholder="-1 = random" title="-1 = random">+ </div><div class="mf-cell">+ <label class="mf-label" for="musicTakes">Takes</label>+ <input type="number" id="musicTakes" value="1" min="1" max="8" step="1" title="How many songs to queue from this form, each with its own seed"></div></div>+ <details class="customize-section" id="musicLoraDetails">+ <summary class="cz-summary"><span class="cz-chevron" aria-hidden="true"><svg class="ph"><use href="#ph-caret-down-bold"/></svg></span><span class="cz-title">Voice & style LoRA</span><span class="cz-meta" id="musicLoraSummary">off</span></summary>+ <div class="cz-body">+ <div class="music-lora-list" id="musicLoraList"></div>+ <div class="hint">Adapters change how the model writes and how it sounds. Drop your own+ <code>.safetensors</code> into the LoRA folder's <code>user/</code> and it appears here.+ Instrumental uses its own adapter and pauses these.</div>+ </div>+ </details>+ <details class="customize-section" id="musicAdvancedDetails">+ <summary class="cz-summary"><span class="cz-chevron" aria-hidden="true"><svg class="ph"><use href="#ph-caret-down-bold"/></svg></span><span class="cz-title">Advanced</span><span class="cz-meta" id="musicAdvancedSummary">defaults</span></summary>+ <div class="cz-body">+ <div class="mf-label">Guidance</div>+ <div class="range-strip">+ <label for="musicCfg">Text guidance</label>+ <input type="range" id="musicCfg" min="0" max="3" step="0.1" value="1" oninput="musicFormChanged()">+ <span id="musicCfgVal">1.0</span>+ </div>+ <div class="hint">How hard the song follows the style and the words. 1.0 is the model's own default; higher is more literal and can get stiff, lower is looser.</div>+ <div class="mf-label">Precision</div>+ <div class="pill-group cols-2" id="musicPrecisionPills">+ <button type="button" class="pill-btn" data-value="bf16" onclick="musicPick('musicPrecision',this)">bf16<span class="sub">best, most memory</span></button>+ <button type="button" class="pill-btn active" data-value="8bit" onclick="musicPick('musicPrecision',this)">8-bit<span class="sub">default</span></button>+ </div>+ <input type="hidden" id="musicPrecision" value="8bit">+ <div class="hint">The composer model's weights. 8-bit is what every song so far was made with; bf16 needs roughly 8 GB more memory.</div>+ </div>+ </details></div>+ </div><!-- /musicCustomPane --><div class="form-action-footer">- <div class="queue-strip"><span class="qchip-spacer"></span><span class="qchip-derived" id="musicEstimate" title="Estimated for a song that runs to Max length, from M4 Max timings (a 3-minute song took about 3 minutes on Final) scaled for this chip. Most songs end sooner; the first song after install also loads the models."></span></div>+ <div class="queue-strip"><span class="qchip-derived" id="musicEstimate" title="Estimated for a song that runs to Max length, from M4 Max timings (a 3-minute song took about 3 minutes on Final) scaled for this chip. Most songs end sooner; the first song after install also loads the models."></span></div><div class="actions"><button type="button" class="primary" id="musicGenBtn" onclick="musicGenerate()">Compose</button><button type="button" class="danger" onclick="api('/stop', 'POST').then(poll)">Stop</button></div><div class="hint" id="musicStatus" role="status"></div>- <div class="hint" id="musicHint">Generated with YuE2 by Multimodal Art Projection · MLX port by vanch007</div>+ <div class="music-credit" id="musicHint">Generated with YuE2 by Multimodal Art Projection · MLX port by vanch007</div></div></div><div id="audioDrivePane">+ <!-- ============== MUSIC VIDEO ================================+ "I give it all the images, and then it creates a compelling video+ out of them." The pieces were all here and none of them knew about+ each other: a2v sings from one picture and one stretch of a+ waveform, i2v moves a still, the beat map knows where the bars are,+ and the Storyboard renders and assembles a list of shots. This pane+ is the brief that joins them — the song, the pictures, and one line+ about how it should look — and it ends by opening an ORDINARY+ storyboard, because the first thing anybody wants after seeing a+ shot list is to change shot 7.++ The single-clip Audio -> Video form is untouched at the bottom,+ inside "One shot": it is still the right tool for one talking head+ and it is still the only way to drive a clip from a spoken take. --><div class="composer-card"><div class="composer-refs"><div class="show">- <h2>Audio- <span class="h2-hint">drives the generation · WAV / MP3 / M4A / FLAC</span>+ <h2>The song+ <span class="h2-hint">drop a file, or pick one you have written</span></h2><div class="studio-ref-grid" style="grid-template-columns:1fr;">- <div class="studio-ref-slot" id="audioStudioAudioSlot" data-slot="audio" style="aspect-ratio:auto;min-height:96px;">- <span class="ref-tag">Audio</span>+ <div class="studio-ref-slot" id="mvSongSlot" data-slot="song" style="aspect-ratio:auto;min-height:96px;">+ <span class="ref-tag">Song</span><div class="hint" style="padding:24px 12px;text-align:center;color:var(--muted);font-size:12px;">Drop a WAV / MP3 / M4A / FLAC here, or click to pick a file.</div></div></div>- <input type="file" id="audioStudioAudioInput" accept=".wav,.mp3,.m4a,.flac,audio/*" style="display:none">+ <input type="file" id="mvSongInput" accept=".wav,.mp3,.m4a,.flac,audio/*" style="display:none">+ <div class="mf-cell" style="margin-top:10px">+ <label class="mf-label" for="mvSongLibrary">Use a song from the library</label>+ <select id="mvSongLibrary" onchange="mvPickFromLibrary(this.value)">+ <option value="">Nothing composed yet</option>+ </select>+ <div class="hint" style="margin-top:4px">A song this panel wrote brings its own words and its own score, so the verses land where they really are instead of where the beat map guesses.</div>+ </div></div></div><div class="composer-refs"><div class="show">- <h2>Reference image- <span class="h2-hint">optional · anchors frame 0 like I2V</span>+ <h2>The pictures+ <span class="h2-hint">Singer sings to camera · Instrument and Room are the B-roll</span></h2>- <!-- Y2.005 — use the shared .picker component (same as I2V /- FFLF) instead of the bespoke studio-ref-slot. Mr Bizarro- report: "image preview and managing kinda shit in audio- to video make it like the others." The picker brings the- drop tile, big centered preview, X-clear button, and- Recent-uploads strip, all consistent with the rest of- the panel. Wired via pickerWire('a2v_image'). -->- <div class="picker" data-key="a2v_image">- <div class="picker-drop" id="picker_drop_a2v_image">+ <div class="picker">+ <div class="picker-drop" id="mvImagesDrop"><div class="picker-empty"><div class="picker-icon"><svg class="ph"><use href="#ph-image"/></svg></div>- <div class="picker-cta">Drop an image here, or <strong>click to browse</strong></div>- <div class="hint">PNG / JPG / WEBP — anchors frame 0 of the audio-driven clip</div>+ <div class="picker-cta">Drop your pictures here, or <strong>click to browse</strong></div>+ <div class="hint">PNG / JPG / WEBP — as many as you like</div></div>- <img class="picker-preview" id="picker_preview_a2v_image" alt="" style="display:none">- <button type="button" class="picker-clear" id="picker_clear_a2v_image" title="Clear" style="display:none"><svg class="ph" aria-hidden="true"><use href="#ph-x-bold"/></svg></button>- </div>- <input type="file" id="picker_file_a2v_image" accept="image/*" style="display:none">- <input type="hidden" name="a2v_image" id="a2v_image" value="">- <div class="picker-recent" id="picker_recent_a2v_image_wrap" style="display:none">- <div class="picker-recent-label">Recent uploads · click to use</div>- <div class="picker-recent-strip" id="picker_recent_a2v_image"></div></div>+ <input type="file" id="mvImagesFile" accept="image/*" multiple style="display:none"></div>- <div class="hint" style="margin-top:6px">- Leave empty for pure Audio → Video. Add an image to open the clip on that frame (e.g. a portrait for a talking-head shot).- </div>+ <div class="mv-cast" id="mvCast"></div></div></div>- <textarea id="audioStudioPrompt" class="composer-prompt" rows="4"- placeholder="A photoreal medium close-up of a woman speaking to camera, soft daylight, shallow depth of field, natural skin pores"></textarea>- <div class="composer-tools">- <button type="button" class="ghost-btn" id="audioStudioEnhanceBtn" onclick="audioStudioEnhancePrompt()" title="Use Gemma to rewrite your prompt"><svg class="ph" aria-hidden="true" style="margin-right:6px"><use href="#ph-sparkle-fill"/></svg>Enhance</button>- <span class="ct-spacer"></span>+ <div class="mf-cell" style="margin-top:6px">+ <label class="mf-label" for="mvStyle">Look</label>+ <input type="text" id="mvStyle" value="handheld 16mm documentary, warm tungsten light, shallow depth of field, MTV Unplugged">+ <div class="hint" style="margin-top:4px">One line, on every shot. A picture with its own note below overrides only its own direction, never this.</div></div></div><div class="studio-status-row" style="margin: 6px 0 -4px;">- <span id="audioStudioStatus" class="hint"></span>+ <span id="mvStatus" class="hint" role="status"></span></div>- <!-- Quick settings: width / height / duration / seed.- Width/height are free-form; the panel snaps to 32 px multiple.- Duration slider covers 1–30 s; JS rounds frames to 8k+1. -->- <div class="quick-settings">- <div>- <div class="mini-fields">- <div class="mf-cell">- <span class="mf-label">Width</span>- <input type="number" id="audioStudioWidth" value="1024" min="256" max="1920" step="32"- oninput="audioStudioDurationChanged()">- </div>- <div class="mf-cell">- <span class="mf-label">Height</span>- <input type="number" id="audioStudioHeight" value="576" min="256" max="1920" step="32"- oninput="audioStudioDurationChanged()">- </div>- <div class="mf-cell">- <span class="mf-label">Seed</span>- <input type="number" id="audioStudioSeed" value="-1" placeholder="-1 = random">+ <div class="form-action-footer" id="mvFooter">+ <div class="queue-strip">+ <span class="qchip-spacer"></span>+ <span class="qchip-derived" id="mvSummary"></span>+ </div>+ <div class="actions">+ <button type="button" class="primary" id="mvPlanBtn" onclick="mvPlan()">Plan the video</button>+ </div>+ <div class="hint">Planning is instant and costs nothing — it reads the beat, writes the shot list, and opens it in Storyboard. Render all, then Film with the song.</div>+ </div>++ <details class="cz-section" id="mvOneShotDetails">+ <summary class="cz-summary">+ <span class="cz-title">One shot (audio → video)</span>+ <span class="cz-sum">one clip, driven by one stretch of audio</span>+ </summary>+ <div class="cz-body">+ <div class="composer-card">+ <div class="composer-refs">+ <div class="show">+ <h2>Audio+ <span class="h2-hint">drives the generation · WAV / MP3 / M4A / FLAC</span>+ </h2>+ <div class="studio-ref-grid" style="grid-template-columns:1fr;">+ <div class="studio-ref-slot" id="audioStudioAudioSlot" data-slot="audio" style="aspect-ratio:auto;min-height:96px;">+ <span class="ref-tag">Audio</span>+ <div class="hint" style="padding:24px 12px;text-align:center;color:var(--muted);font-size:12px;">+ Drop a WAV / MP3 / M4A / FLAC here, or click to pick a file.+ </div>+ </div>+ </div>+ <input type="file" id="audioStudioAudioInput" accept=".wav,.mp3,.m4a,.flac,audio/*" style="display:none"></div>- <!-- Start offset into the source file. The pipelines and the render- helper have always taken this; the panel had no control for it,- so every A2V render used the first N seconds of the file and the- only workaround was trimming the audio beforehand (#46). -->- <div class="mf-cell">- <span class="mf-label">Audio start</span>- <input type="number" id="audioStudioStart" value="0" min="0" step="0.5"- title="Seconds into the audio file where the clip starts reading. 0 = from the beginning.">+ </div>++ <div class="composer-refs">+ <div class="show">+ <h2>Reference image+ <span class="h2-hint">optional · anchors frame 0 like I2V</span>+ </h2>+ <!-- Y2.005 — use the shared .picker component (same as I2V /+ FFLF) instead of the bespoke studio-ref-slot. Mr Bizarro+ report: "image preview and managing kinda shit in audio+ to video make it like the others." The picker brings the+ drop tile, big centered preview, X-clear button, and+ Recent-uploads strip, all consistent with the rest of+ the panel. Wired via pickerWire('a2v_image'). -->+ <div class="picker" data-key="a2v_image">+ <div class="picker-drop" id="picker_drop_a2v_image">+ <div class="picker-empty">+ <div class="picker-icon"><svg class="ph"><use href="#ph-image"/></svg></div>+ <div class="picker-cta">Drop an image here, or <strong>click to browse</strong></div>+ <div class="hint">PNG / JPG / WEBP — anchors frame 0 of the audio-driven clip</div>+ </div>+ <img class="picker-preview" id="picker_preview_a2v_image" alt="" style="display:none">+ <button type="button" class="picker-clear" id="picker_clear_a2v_image" title="Clear" style="display:none"><svg class="ph" aria-hidden="true"><use href="#ph-x-bold"/></svg></button>+ </div>+ <input type="file" id="picker_file_a2v_image" accept="image/*" style="display:none">+ <input type="hidden" name="a2v_image" id="a2v_image" value="">+ <div class="picker-recent" id="picker_recent_a2v_image_wrap" style="display:none">+ <div class="picker-recent-label">Recent uploads · click to use</div>+ <div class="picker-recent-strip" id="picker_recent_a2v_image"></div>+ </div>+ </div>+ <div class="hint" style="margin-top:6px">+ Leave empty for pure Audio → Video. Add an image to open the clip on that frame (e.g. a portrait for a talking-head shot).+ </div></div></div>- <div class="hint" style="margin-top:4px">- Audio start is an offset into the file you loaded — set it to 30 to drive the clip from 0:30 onward.++ <textarea id="audioStudioPrompt" class="composer-prompt" rows="4"+ placeholder="A photoreal medium close-up of a woman speaking to camera, soft daylight, shallow depth of field, natural skin pores"></textarea>+ <div class="composer-tools">+ <button type="button" class="ghost-btn" id="audioStudioEnhanceBtn" onclick="audioStudioEnhancePrompt()" title="Use Gemma to rewrite your prompt"><svg class="ph" aria-hidden="true" style="margin-right:6px"><use href="#ph-sparkle-fill"/></svg>Enhance</button>+ <span class="ct-spacer"></span></div>- <div class="mf-cell" style="margin-top:8px">- <span class="mf-label">Duration</span>- <div class="range-strip">- <input type="range" id="audioStudioDuration" min="1" max="30" step="1" value="7"- oninput="audioStudioDurationChanged(this.value)">- <span id="audioStudioDurationVal" class="range-val">7 s</span>+ </div>++ <div class="studio-status-row" style="margin: 6px 0 -4px;">+ <span id="audioStudioStatus" class="hint"></span>+ </div>++ <!-- Quick settings: width / height / duration / seed.+ Width/height are free-form; the panel snaps to 32 px multiple.+ Duration slider covers 1–30 s; JS rounds frames to 8k+1. -->+ <div class="quick-settings">+ <div>+ <div class="mini-fields">+ <div class="mf-cell">+ <span class="mf-label">Width</span>+ <input type="number" id="audioStudioWidth" value="1024" min="256" max="1920" step="32"+ oninput="audioStudioDurationChanged()">+ </div>+ <div class="mf-cell">+ <span class="mf-label">Height</span>+ <input type="number" id="audioStudioHeight" value="576" min="256" max="1920" step="32"+ oninput="audioStudioDurationChanged()">+ </div>+ <div class="mf-cell">+ <span class="mf-label">Seed</span>+ <input type="number" id="audioStudioSeed" value="-1" placeholder="-1 = random">+ </div>+ <!-- Start offset into the source file. The pipelines and the render+ helper have always taken this; the panel had no control for it,+ so every A2V render used the first N seconds of the file and the+ only workaround was trimming the audio beforehand (#46). -->+ <div class="mf-cell">+ <span class="mf-label">Audio start</span>+ <input type="number" id="audioStudioStart" value="0" min="0" step="0.5"+ title="Seconds into the audio file where the clip starts reading. 0 = from the beginning.">+ </div></div>- <!-- Length warning. Deliberately a warning and NOT a hard cap: the- evidence for where A2V gives out is two independent field- reports converging on ~257 frames (#46 — @blackest hit it here- and on a separate MLX pipeline), not a measurement made here,- and the diagnostic that would tell us whether it is a length- ceiling at all is still outstanding. Silently deleting 11-30 s- from the slider would be asserting a number nobody has measured.- Showing the frame count and the reported wall lets the user- decide with the same information the maintainer has. -->- <div class="hint" id="audioStudioDurationWarn" style="margin-top:4px; display:none"></div>- </div>- <div class="mf-cell" style="margin-top:8px">- <span class="mf-label">Audio conditioning strength</span>- <!-- Starts on AUTO and stays there until the thumb is dragged:- the two A2V pipelines read this number differently and only- the panel knows which one this Mac will run, so an untouched- control must send NOTHING rather than a number that means- "audio off" on one lane and "audio on" on the other. -->- <div class="range-strip">- <input type="range" id="audioConditioningScale" min="0.5" max="5.0" step="0.1" value="3.0"- data-auto="1" oninput="audioConditioningScaleChanged(this)">- <span id="audioConditioningScaleVal" class="range-val">Auto</span>+ <div class="hint" style="margin-top:4px">+ Audio start is an offset into the file you loaded — set it to 30 to drive the clip from 0:30 onward.+ </div>+ <div class="mf-cell" style="margin-top:8px">+ <span class="mf-label">Duration</span>+ <div class="range-strip">+ <input type="range" id="audioStudioDuration" min="1" max="30" step="1" value="7"+ oninput="audioStudioDurationChanged(this.value)">+ <span id="audioStudioDurationVal" class="range-val">7 s</span>+ </div>+ <!-- Length warning. Deliberately a warning and NOT a hard cap: the+ evidence for where A2V gives out is two independent field+ reports converging on ~257 frames (#46 — @blackest hit it here+ and on a separate MLX pipeline), not a measurement made here,+ and the diagnostic that would tell us whether it is a length+ ceiling at all is still outstanding. Silently deleting 11-30 s+ from the slider would be asserting a number nobody has measured.+ Showing the frame count and the reported wall lets the user+ decide with the same information the maintainer has. -->+ <div class="hint" id="audioStudioDurationWarn" style="margin-top:4px; display:none"></div>+ </div>+ <div class="mf-cell" style="margin-top:8px">+ <span class="mf-label">Audio conditioning strength</span>+ <!-- Starts on AUTO and stays there until the thumb is dragged:+ the two A2V pipelines read this number differently and only+ the panel knows which one this Mac will run, so an untouched+ control must send NOTHING rather than a number that means+ "audio off" on one lane and "audio on" on the other. -->+ <div class="range-strip">+ <input type="range" id="audioConditioningScale" min="0.5" max="5.0" step="0.1" value="3.0"+ data-auto="1" oninput="audioConditioningScaleChanged(this)">+ <span id="audioConditioningScaleVal" class="range-val">Auto</span>+ </div>+ <div class="hint" style="margin-top:2px" id="audioConditioningScaleHint">Higher = stronger audio adhesion, lower visual flexibility</div></div>- <div class="hint" style="margin-top:2px" id="audioConditioningScaleHint">Higher = stronger audio adhesion, lower visual flexibility</div></div></div>- </div>- <div class="hint" style="margin-top:8px" id="audioStudioHint">- Audio → Video uses audio conditioning during generation (not post-hoc mux). Some seeds may not work properly — retry if the mouth doesn't move.- </div>+ <div class="hint" style="margin-top:8px" id="audioStudioHint">+ Audio → Video uses audio conditioning during generation (not post-hoc mux). Some seeds may not work properly — retry if the mouth doesn't move.+ </div>- <div class="form-action-footer" id="audioStudioFooter">- <div class="queue-strip">- <span class="qchip-spacer"></span>- <span class="qchip-derived" id="audioStudioEstimate"></span>+ <div class="form-action-footer" id="audioStudioFooter">+ <div class="queue-strip">+ <span class="qchip-spacer"></span>+ <span class="qchip-derived" id="audioStudioEstimate"></span>+ </div>+ <div class="actions">+ <button type="button" class="primary" id="audioStudioGenBtn" onclick="audioStudioGenerate()">Generate</button>+ <button type="button" class="danger" onclick="api('/stop', 'POST').then(poll)">Stop</button>+ </div></div>- <div class="actions">- <button type="button" class="primary" id="audioStudioGenBtn" onclick="audioStudioGenerate()">Generate</button>- <button type="button" class="danger" onclick="api('/stop', 'POST').then(poll)">Stop</button></div>- </div>+ </details></div></div>@@ -3759,6 +4002,50 @@ The last line"></textarea><div class="expand-stage" id="expandStage"></div><div class="expand-meta" id="expandMeta"></div></div>+ <!-- ============== MUSIC STUDIO — the Song card =====================+ Under the player, for songs only. The song is the unit: its words,+ its sheet music (drawn by abcjs from the score YuE2 wrote), where it+ came from, and the four ways to get another one from it. Filled by+ songCardRender() whenever a music output is selected; hidden for+ everything else. -->+ <div class="song-card" id="songCard" hidden>+ <div class="song-head">+ <div>+ <div class="song-title" id="songTitle"></div>+ <div class="song-style" id="songStyle"></div>+ </div>+ <div class="song-badges" id="songBadges"></div>+ </div>+ <div class="song-actions" id="songActions">+ <button type="button" class="ghost-btn" onclick="musicVariation('take')" title="Same score, same words, a new performance — the singing and the playing are done again from the plan.">New take<span class="sub">same song, performed again</span></button>+ <button type="button" class="ghost-btn" onclick="musicVariation('sound')" title="Same performance, recorded again: the notes and the words stay, the sound of it changes. A fraction of the time of a full song.">Re-roll the sound<span class="sub">same performance, new recording</span></button>+ <button type="button" class="ghost-btn" onclick="musicRestyleFromSong()" title="Keep this song's score and put the form's style and lyrics on it.">New style on this score<span class="sub">uses the composer's style + lyrics</span></button>+ <button type="button" class="ghost-btn" onclick="musicCoverFromSong()" title="Load this song as the source in Cover a song.">Cover it<span class="sub">read the tune, write it fresh</span></button>+ </div>+ <div class="song-lineage" id="songLineage"></div>+ <div class="song-status" id="songStatus" role="status"></div>+ <details class="song-section" id="songScoreSection" open>+ <summary>Sheet music <span class="sum" id="songScoreSum"></span></summary>+ <div class="song-score" id="songScore"></div>+ <div class="song-score-editor" id="songScoreEditor" hidden>+ <textarea id="songScoreText" spellcheck="false"></textarea>+ <div class="row">+ <button type="button" class="primary" onclick="musicRenderEditedScore()">Render this score</button>+ <button type="button" class="ghost-btn" onclick="musicScorePreview()">Preview</button>+ <button type="button" class="ghost-btn" onclick="musicScoreEditToggle(false)">Cancel</button>+ <div class="hint">ABC notation. Change notes, chords or bars; the words come from the composer's Lyrics box (or this song's if that is empty).</div>+ </div>+ </div>+ <div class="song-actions">+ <button type="button" class="ghost-btn" id="songScoreEditBtn" onclick="musicScoreEditToggle(true)">Edit the score<span class="sub">change it, render it again</span></button>+ <button type="button" class="ghost-btn" onclick="musicScoreCopy()">Copy ABC</button>+ </div>+ </details>+ <details class="song-section" id="songLyricsSection">+ <summary>Lyrics <span class="sum" id="songLyricsSum"></span></summary>+ <div class="song-lyrics" id="songLyrics"></div>+ </details>+ </div><!-- Hidden compatibility slot. selectOutput() writes #playerName hereand toggles display on #playerMeta — both kept so external codeand tests don't break. The visible name lives in playerOverlayName. -->@@ -3935,6 +4222,15 @@ The last line"></textarea><h3>The film</h3><span class="sb-plan-status" id="sbFilmStatus"></span><span class="ch-spacer"></span>+ <!-- Only a board planned in Music video has a song to lay under it,+ so this button appears only there. It is a second door onto the+ same assembler Export uses — the difference is the bed: the+ song replaces every clip's own audio and plays unbroken, which+ the lip-sync survives because each singing shot was rendered+ against its own seconds of this very file. -->+ <button type="button" class="ghost-btn" id="sbMusicFilmBtn"+ onclick="sbFilmWithTheSong()" hidden+ title="Join the shots and lay the song under them, unbroken">Film with the song</button></header><div id="sbFilmBody"></div></div>@@ -3984,7 +4280,15 @@ The last line"></textarea>the screen and the one that LEAVES looked alike. Navigation nestsunder the ⋯; the only filled control on the screen is Render. --><header class="carousel-head sbe-head">- <span class="sbe-title" id="sbeTitle">Editor</span>+ <!-- WHICH FILM, AND THE WAY TO ANOTHER ONE. The name looked like a+ control and did nothing, and the list of films sat behind the+ full-screen Editor with ⋯ → Close as the only way to it. The name+ IS the switcher: it drops the films that have clips, and opening+ one keeps the work here the way closing does (backed up, never+ discarded). -->+ <button type="button" class="ghost-btn sbe-titlebtn" id="sbeFilmsBtn"+ onclick="sbeFilmsToggle()" aria-haspopup="menu"+ title="Switch to another __SEQ__ — nothing here is lost"><span class="sbe-title" id="sbeTitle">Editor</span><span class="sbe-car">▾</span></button><!-- WHICH DOCUMENT AM I CUTTING, and which of its drafts. Identity, soit sits beside the name rather than among the verbs. --><button type="button" class="ghost-btn sbe-draftchip" id="sbeKeepBtn"@@ -4117,6 +4421,14 @@ The last line"></textarea><span class="sbe-pop-note" id="sbeRenderNote"></span></div>+ <div class="sbe-pop sbe-films" id="sbeFilmsMenu" role="menu" hidden>+ <span class="sbe-pop-note" id="sbeFilmsNote">reading your __SEQS__…</span>+ <div class="sbe-films-list" id="sbeFilmsList"></div>+ <span class="sbe-pop-sep"></span>+ <button type="button" class="ghost-btn" id="sbeFilmsAllBtn" onclick="sbeFilmsAll()"+ title="Close this timeline and show every __SEQ__. Nothing is deleted.">All __SEQS__…</button>+ </div>+<div class="sbe-pop" id="sbeMoreMenu" hidden><button type="button" class="ghost-btn" id="sbeVersBtn" onclick="sbeVersionsOpen(false)"title="Every draft this __SEQ__ has, and every past save of this one">Drafts and versions…</button>@@ -4791,6 +5103,27 @@ The last line"></textarea>other segs). --></div><div class="carousel" id="carousel"></div>+ <!-- MUSIC STUDIO — the player bar. Sticks to the bottom of the outputs+ column while you browse; one <audio> for every song, a real+ waveform (decoded once per song, cached), click to seek, prev/next+ through the list. Shown the first time a song is selected. -->+ <div class="music-bar" id="musicBar" hidden>+ <div class="music-bar-cover" id="musicBarCover" aria-hidden="true"></div>+ <div class="music-bar-text">+ <div class="music-bar-title" id="musicBarTitle"></div>+ <div class="music-bar-style" id="musicBarStyle"></div>+ </div>+ <div class="music-bar-controls">+ <button type="button" class="music-bar-btn" title="Previous" aria-label="Previous song" onclick="musicBarStep(-1)"><svg width="14" height="14" viewBox="0 0 16 16" aria-hidden="true"><path d="M3 2.5v11M13 2.5 5 8l8 5.5z" fill="currentColor"/></svg></button>+ <button type="button" class="music-bar-btn play" id="musicBarPlay" title="Play" aria-label="Play or pause" onclick="musicBarTogglePlay()"><svg width="14" height="14" viewBox="0 0 16 16" aria-hidden="true"><path d="M4 2.5 L13.5 8 L4 13.5 Z" fill="currentColor"/></svg></button>+ <button type="button" class="music-bar-btn" title="Next" aria-label="Next song" onclick="musicBarStep(1)"><svg width="14" height="14" viewBox="0 0 16 16" aria-hidden="true"><path d="M13 2.5v11M3 2.5 11 8l-8 5.5z" fill="currentColor"/></svg></button>+ </div>+ <canvas class="music-bar-wave" id="musicBarWave" onclick="musicBarSeek(event)" title="Click to seek"></canvas>+ <div class="music-bar-time" id="musicBarTime">0:00 / 0:00</div>+ <audio id="musicBarAudio" preload="metadata"></audio>+ </div>+ <!-- The ⋯ menu, one for every song row; positioned by musicMenuOpen(). -->+ <div class="song-menu" id="songMenu" hidden role="menu"></div></div></section>@@ -5582,7 +5915,12 @@ The last line"></textarea><script>const BOOT = __BOOTSTRAP__;</script>+<!-- abcjs draws the sheet music YuE2 writes for every song. Vendored (MIT,+ webapp/vendor/abcjs/) so a score renders with the network off. Classic+ script on purpose: it publishes `ABCJS` as a global for the studio module. -->+<script src="/webapp/vendor/abcjs/abcjs-basic-min.min.js"></script><script type="module" src="/webapp/js/boot.js"></script>+<script type="module" src="/webapp/js/music.js"></script><script type="module" src="/webapp/js/shortcuts.js"></script><script type="module" src="/webapp/js/tips.js"></script><script type="module" src="/webapp/js/docs.js"></script>diff --git a/webapp/js/boot.js b/webapp/js/boot.jsindex 074205e..5f18775 100644--- a/webapp/js/boot.js+++ b/webapp/js/boot.js@@ -399,6 +399,27 @@ async function outputsLoadAll() {window._outputsLoadAllInFlight = p;return p;}+// A delete / hide / unhide changed what /outputs would say. The poll+// refreshes `currentOutputs`, but filteredMainOutputs() re-adds any path the+// Show-all cache still holds — so a deleted clip came back as a 404 card and+// a hidden one stayed visible until a reload (Codex UI-06). Drop the paths we+// know about now, then refetch the full list (the server may have removed+// companions too: an upscale's hidden native, its sidecars).+function outputsCacheMutated(paths) {+ const gone = new Set((paths || []).filter(Boolean));+ if (gone.size) {+ window._olderOutputs = (window._olderOutputs || []).filter(o => !gone.has(o.path));+ }+ if (window._showingAllOutputs && typeof outputsLoadAll === 'function') {+ // A fetch already in flight began before this change and would put the+ // old list back — refetch after it, not instead of it.+ const inflight = window._outputsLoadAllInFlight;+ try {+ if (inflight) inflight.then(() => outputsLoadAll());+ else outputsLoadAll();+ } catch (_) {}+ }+}function _updateMainFilterChips() {const a = document.getElementById('mainOutputsFilterAll');const v = document.getElementById('mainOutputsFilterVideos');@@ -894,7 +915,7 @@ Object.assign(globalThis, {applyTierTimes, setKeyframeMode, keyframeTimingSlots, renderKeyframeDynamicSlots,maybeScaleTouchedKeyframeTiming, syncKeyframeTiming, outputKind, isPhotoOutputMain, filteredMainOutputs,applyOutputsQuery, setOutputsQuery, paintOutputsCount, outputsTitleText, outputsQueryText,- outputsLoadAll, _updateMainFilterChips, _maybeAutoLoadAllForEmptyFilter, setMainOutputsFilter,+ outputsLoadAll, outputsCacheMutated, _updateMainFilterChips, _maybeAutoLoadAllForEmptyFilter, setMainOutputsFilter,updateModelCredit, toggleAvoidRow, syncAvoidRowFromValue, ingredientsServed,_paintControlGenNote, defaultRemixMode, setMode, _portalLoraPicker,});diff --git a/webapp/js/characters.js b/webapp/js/characters.jsindex f50ede4..773de99 100644--- a/webapp/js/characters.js+++ b/webapp/js/characters.js@@ -92,14 +92,32 @@ function musicPick(id, button) {function musicFormChanged() {const instrumental = document.getElementById('musicInstrumental').checked;document.getElementById('musicLyrics').disabled = instrumental;+ // The lyrics editor (music.js) reads that same flag and goes quiet — the+ // words stay in the boxes, they are just not used while this is on.+ if (typeof musicLyricsLock === 'function') musicLyricsLock(instrumental);document.getElementById('musicInstrumentalPill').classList.toggle('on', instrumental);const seconds = Number(document.getElementById('musicMaxSeconds').value);document.getElementById('musicMaxSecondsVal').textContent = `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`;const quality = document.getElementById('musicQuality').value;+ const cfgEl = document.getElementById('musicCfg');+ if (cfgEl) {+ document.getElementById('musicCfgVal').textContent = Number(cfgEl.value).toFixed(1);+ const prec = (document.getElementById('musicPrecision') || {}).value || '8bit';+ const parts = [];+ if (Math.abs(Number(cfgEl.value) - 1) >= 0.001) parts.push(`guidance ${Number(cfgEl.value).toFixed(1)}`);+ if (prec !== '8bit') parts.push(prec);+ const sum = document.getElementById('musicAdvancedSummary');+ if (sum) sum.textContent = parts.length ? parts.join(' · ') : 'defaults';+ }const music = window._ENGINE_PROBES.music;const estimate = ((music.estimates || {})[quality] || {})[String(seconds)];document.getElementById('musicEstimate').textContent = estimate? `≈ ${estimate.eta} at full length · estimate` : '';+ musicCoverSummary();+ musicCoverInstallCard(music);+ musicLoraRender(music);+ musicLoraInstallCard(music);+ musicLoraSummaryText();const btn = document.getElementById('musicGenBtn');btn.disabled = musicBusy || !music.capable;btn.title = music.available ? '' : (music.capable@@ -110,6 +128,11 @@ function musicFormParams() {const instrumental = document.getElementById('musicInstrumental').checked;return new URLSearchParams({mode: 'music', engine: 'music',+ // WHICH TASK WAS CHOSEN, in words the server can check (M6-07): a cover+ // was represented only by a non-empty recording path, so Cover with the+ // path left empty was indistinguishable from Write and composed a new+ // song instead of refusing.+ music_task: (document.getElementById('musicTask') || {}).value || 'write',music_lyrics: instrumental ? '' : document.getElementById('musicLyrics').value,music_style: document.getElementById('musicStyle').value,music_mode: document.getElementById('musicMode').value,@@ -117,26 +140,261 @@ function musicFormParams() {music_max_seconds: document.getElementById('musicMaxSeconds').value,music_seed: document.getElementById('musicSeed').value,music_quality: document.getElementById('musicQuality').value,+ // Cover: a path here changes the job's shape. Sent even when empty so a+ // replay of a cover job and a replay of a prompt job differ in the field+ // rather than in which fields exist.+ // Only when Cover is the task. Switching back to Write closes the cover+ // section but leaves the path in its box — and a path in the form is a+ // cover, whatever the chips say (Codex review, 2026-09-20).+ music_source_audio: (((document.getElementById('musicTask') || {}).value || 'write') === 'cover')+ ? ((document.getElementById('musicSourceAudio') || {}).value || '') : '',+ music_cover_task: (document.getElementById('musicCoverTask') || {}).value || 'melody-full',+ music_title: (document.getElementById('musicTitle') || {}).value || '',+ music_cfg_scale: musicCfgValue(),+ music_precision: (document.getElementById('musicPrecision') || {}).value || '8bit',+ // Adapters, as `id:strength` pairs. Instrumental pauses them: its own AR+ // adapter is the recipe and a second AR delta would fight it. The picks+ // stay checked in the form so turning Instrumental off brings them back.+ music_loras: instrumental ? '' : musicLoraPicks(),+ });+}++// ---- Voice & style LoRA -----------------------------------------------------+// The picker is a directory listing, not a registry: whatever is in the LoRA+// folder (and in its user/ subfolder) is pickable. State lives in the DOM —+// the checkbox and the slider ARE the selection — so a re-render has to carry+// it across rather than reset it.+// AS JSON, `[{id, strength}]` (M6-05). The picks went out as `id:strength`+// joined with commas, and an id is a FILENAME: `Voice, warm.safetensors` was+// split into two ids nobody has, both were dropped, and the song came back+// without the voice the row showed ticked. The server's parser has always+// read this JSON form, and the variation route already sends it.+function musicLoraPicks() {+ const list = document.getElementById('musicLoraList');+ if (!list) return '';+ const picks = Array.from(list.querySelectorAll('.music-lora-item'))+ .filter(row => row.querySelector('input[type="checkbox"]').checked)+ .map(row => ({ id: row.dataset.id,+ strength: Number(Number(row.querySelector('input[type="range"]').value).toFixed(2)) }));+ return picks.length ? JSON.stringify(picks) : '';+}++function musicLoraRender(music) {+ const list = document.getElementById('musicLoraList');+ if (!list) return;+ const adapters = ((music || {}).loras || {}).adapters || [];+ // Carry the current selection across a re-render (/status polls every few+ // seconds; a slider that snapped back every poll would be unusable).+ const kept = {};+ list.querySelectorAll('.music-lora-item').forEach(row => {+ kept[row.dataset.id] = {+ on: row.querySelector('input[type="checkbox"]').checked,+ strength: row.querySelector('input[type="range"]').value,+ };});+ const signature = adapters.map(a => a.id).join('|');+ if (list.dataset.signature === signature && Object.keys(kept).length) {+ musicLoraSummaryText();+ return;+ }+ list.dataset.signature = signature;+ if (!adapters.length) {+ list.innerHTML = `<div class="music-lora-empty">No adapters yet. ` ++ `<button type="button" class="ghost-btn" onclick="musicLoraInstall()">Download the LoRA pack</button></div>`;+ musicLoraSummaryText();+ return;+ }+ list.innerHTML = adapters.map(a => {+ const state = kept[a.id] || {};+ const strength = state.strength != null ? state.strength : '1.00';+ const branch = a.branch === 'nar' ? 'sound' : 'writing';+ return `<div class="music-lora-item${state.on ? ' active' : ''}" data-id="${charactersEscapeAttr(a.id)}">+ <label class="music-lora-head">+ <input type="checkbox" ${state.on ? 'checked' : ''} onchange="musicLoraToggled(this)">+ <span class="music-lora-name">${charactersEscapeHtml(a.name)}</span>+ <span class="music-lora-branch">${branch}</span>+ </label>+ <div class="range-strip">+ <input type="range" min="0" max="1.5" step="0.05" value="${charactersEscapeAttr(String(strength))}"+ oninput="musicLoraToggled(this)" title="Adapter strength">+ <span class="range-val">${Number(strength).toFixed(2)}</span>+ </div>+ ${a.note ? `<div class="hint">${charactersEscapeHtml(a.note)}</div>` : ''}+ </div>`;+ }).join('');+ musicLoraSummaryText();+}++function musicLoraToggled(el) {+ const row = el.closest('.music-lora-item');+ if (row) {+ const on = row.querySelector('input[type="checkbox"]').checked;+ row.classList.toggle('active', on);+ const value = Number(row.querySelector('input[type="range"]').value);+ row.querySelector('.range-val').textContent = value.toFixed(2);+ }+ musicFormChanged();+}++function musicLoraSummaryText() {+ const el = document.getElementById('musicLoraSummary');+ if (!el) return;+ if (document.getElementById('musicInstrumental').checked) {+ el.textContent = 'paused by Instrumental';+ return;+ }+ const picks = musicLoraPicks();+ if (!picks) { el.textContent = 'off'; return; }+ const names = Array.from(document.querySelectorAll('.music-lora-item.active .music-lora-name'))+ .map(n => n.textContent);+ el.textContent = `${names.join(' · ')} @ ${JSON.parse(picks).map(p => p.strength.toFixed(2)).join(' / ')}`;+}++// Instrumental with no adapter still works — it falls back to the section-tag+// prompt that shipped in v4.16 — so this offers the upgrade, never blocks.+// A BACKGROUND DOWNLOAD SAYS WHAT IT IS DOING (M6-09). The two install cards+// used to read only the 202 that started the fetch; the next /status tick+// repainted the Download offer over it, and a fetch that then failed (a+// dropped connection, a full disk) never said so. /status now carries each+// fetch's `{running, line, error}` and this is the one painter both read.+function musicFetchCard(fetch, what, retry) {+ const f = fetch || {};+ if (f.running) {+ return `<b>Downloading ${what}…</b> <span class="hint">${charactersEscapeHtml(f.line || 'starting')}</span>`;+ }+ if (f.error) {+ return `<b>The ${what} download failed:</b> ${charactersEscapeHtml(f.error)} ` ++ `<button type="button" class="ghost-btn" onclick="${retry}()">Try again</button>`;+ }+ return '';+}++function musicLoraInstallCard(music) {+ const box = document.getElementById('musicLoraInstall');+ if (!box) return;+ const loras = (music || {}).loras || {};+ const wanted = document.getElementById('musicInstrumental').checked;+ if (loras.instrumental_ready || !wanted) { box.hidden = true; box.innerHTML = ''; return; }+ const mb = Math.round((loras.bytes || 0) / 1e6);+ box.hidden = false;+ box.innerHTML = musicFetchCard(loras.fetch, 'music LoRAs', 'musicLoraInstall') ||+ `<b>Instrumental gets better with the music LoRA pack (~${mb} MB, once).</b> ` ++ `Without it the model is only asked in words for a track with no vocal line. ` ++ `<button type="button" class="ghost-btn" onclick="musicLoraInstall()">Download it</button>`;+}++async function musicLoraInstall() {+ const box = document.getElementById('musicLoraInstall');+ if (box) { box.hidden = false; box.innerHTML = 'Downloading the music LoRAs…'; }+ try {+ const r = await fetch('/music/lora/fetch', { method: 'POST' });+ const result = await r.json();+ if (!r.ok || result.error) throw new Error(result.error || 'Could not start the download');+ if (box) box.innerHTML = 'Downloading the music LoRAs… this runs in the background.';+ } catch (e) {+ if (box) box.innerHTML = `Could not start the download: ${e.message || e}`;+ }+}++// 1.0 is the engine's own default; sending nothing for it keeps the sidecar+// honest ("cfg_scale": null = the default was used, not "1.0 was chosen").+function musicCfgValue() {+ const el = document.getElementById('musicCfg');+ if (!el) return '';+ const v = Number(el.value);+ return Math.abs(v - 1) < 0.001 ? '' : String(v);+}++// The cover section says what it is doing without being opened, the way every+// other closed section on this page does.+function musicCoverSummary() {+ const src = (document.getElementById('musicSourceAudio') || {}).value || '';+ const el = document.getElementById('musicCoverSummary');+ if (!el) return;+ if (!src.trim()) { el.textContent = 'off'; return; }+ const name = src.trim().split('/').pop();+ const task = (document.getElementById('musicCoverTask') || {}).value || 'melody-full';+ const words = {'melody-full': 'melody + chords', 'melody-vocal': 'the sung line',+ 'full': 'everything'};+ el.textContent = `${name} · ${words[task] || task}`;+}++// The two transcription models are an opt-in download, so the section says so+// in place rather than letting a cover fail ten minutes in.+function musicCoverInstallCard(music) {+ const box = document.getElementById('musicCoverInstall');+ if (!box) return;+ const cover = (music || {}).cover || {};+ const src = (document.getElementById('musicSourceAudio') || {}).value || '';+ if (cover.ready || !src.trim()) { box.hidden = true; box.innerHTML = ''; return; }+ const gb = ((cover.bytes || 0) / 1e9).toFixed(1);+ box.hidden = false;+ box.innerHTML = musicFetchCard(cover.fetch, 'cover models', 'musicCoverInstall') ||+ `<b>Covering needs two more models (~${gb} GB).</b> They read the tune off ` ++ `your recording; writing a song from a prompt never uses them. ` ++ `<button type="button" class="ghost-btn" onclick="musicCoverInstall()">Download them</button>`;+}++async function musicCoverInstall() {+ const box = document.getElementById('musicCoverInstall');+ if (box) box.innerHTML = 'Downloading the cover models…';+ try {+ const r = await fetch('/music/cover/install', { method: 'POST' });+ const result = await r.json();+ if (!r.ok || result.error) throw new Error(result.error || 'Could not start the download');+ if (box) box.innerHTML = 'Downloading the cover models… this runs in the background.';+ } catch (e) {+ if (box) box.innerHTML = `Could not start the download: ${e.message || e}`;+ }}async function musicGenerate() {if (musicBusy) return;// Pressing Compose before the engine exists IS the request to install it.if (!window._ENGINE_PROBES.music.available) { openMusicInstallCard(); return; }+ // Simple mode does not render: it asks Gemma for the style and the words+ // and shows them in the Custom fields, because a song is minutes of this+ // Mac's GPU and nobody should spend that on a brief they have not read.+ if (typeof musicSimpleActive === 'function' && musicSimpleActive()) {+ if (typeof musicSimpleCompose === 'function') await musicSimpleCompose();+ return;+ }+ // Get the score is transcription only — a different route, no song.+ const task = (document.getElementById('musicTask') || {}).value || 'write';+ if (task === 'score') { if (typeof musicTranscribe === 'function') musicTranscribe(); return; }const fd = musicFormParams();const status = document.getElementById('musicStatus');+ if (task === 'cover' && !fd.get('music_source_audio').trim()) {+ const det = document.getElementById('musicCoverDetails');+ if (det) det.open = true;+ status.textContent = 'Cover needs a recording — pick or paste the one to cover.';+ return;+ }if (!fd.get('music_style').trim() && !fd.get('music_lyrics').trim() && fd.get('music_instrumental') !== 'on') {status.textContent = 'Give it something to work with — lyrics, a style description, or both.';return;}+ // A cover with no transcription models is a ten-minute job that cannot+ // succeed. Say it here, where the fix is one click away.+ if (fd.get('music_source_audio').trim() &&+ !(((window._ENGINE_PROBES.music || {}).cover || {}).ready)) {+ document.getElementById('musicCoverDetails').open = true;+ status.textContent = 'Covering needs the two transcription models first.';+ return;+ }musicBusy = true;musicFormChanged();status.textContent = 'Queueing…';try {- const r = await fetch('/queue/add', { method: 'POST', body: fd });- const result = await r.json();- if (!r.ok || result.error) throw new Error(result.error || 'Could not queue music');- status.textContent = 'Song queued.';+ // Takes: N songs from one form, each with its own seed. A fixed seed+ // applies to the first only — identical seeds would be identical songs.+ const takes = Math.max(1, Math.min(8, Number((document.getElementById('musicTakes') || {}).value) || 1));+ for (let i = 0; i < takes; i++) {+ if (i > 0) fd.set('music_seed', '-1');+ const r = await fetch('/queue/add', { method: 'POST', body: fd });+ const result = await r.json();+ if (!r.ok || result.error) throw new Error(result.error || 'Could not queue music');+ }+ status.textContent = takes > 1 ? `${takes} takes queued.` : 'Song queued.';setMainOutputsFilter('audio');await poll();} catch (e) {@@ -154,7 +412,13 @@ function useTrackInA2V(path) {audioModeSet('drive');workflowSwitch('audio');audioStudioRenderSlots();- phosToast('Track loaded — add a prompt and generate.');+ // The pane this lands on is Music video now, so the track has to land in+ // ITS song slot as well as in the One-shot form underneath — a button that+ // opens a screen and fills nothing on it reads as broken. Both, because the+ // user may well have wanted the one clip.+ if (typeof mvInit === 'function') mvInit();+ if (typeof mvPickFromLibrary === 'function') mvPickFromLibrary(path);+ phosToast('Song loaded — drop your pictures, then Plan the video.');}// One renderer, two places: the panel on top of Compose and the modal card// (opened by Compose, the header engine picker and Settings → Models).@@ -223,6 +487,12 @@ function closeMusicInstallCard() {function audioStudioInit() {if (musicComposeActive()) setMainOutputsFilter('audio');+ // The Drive-video pane is the Music video pane now (music.js owns it; the+ // single-clip form this function wires is the "One shot" disclosure at the+ // bottom of it). `mvInit` is idempotent and re-reads the song library every+ // time, so it belongs BEFORE the wired guard — a song composed since the+ // last visit has to appear in the select.+ if (typeof mvInit === 'function') mvInit();// Re-read every visit, not once: the tier is known by the time the pane is// opened and the hint names a lane-specific number. A thumb the user has// already dragged is left exactly where they put it.@@ -388,6 +658,20 @@ function audioStudioDurationChanged(val) {const w = parseInt((document.getElementById('audioStudioWidth') || {}).value || '1024', 10);const h = parseInt((document.getElementById('audioStudioHeight') || {}).value || '576', 10);const area = (w > 0 && h > 0) ? w * h : 1024 * 576;+ // A MEMORY LIMIT COMES FIRST. On a Compact-tier Mac the panel refuses an+ // a2v render past BOOT.a2v_max_frames (see a2v_max_frames() server-side):+ // a 30 s clip on an 8 GB Mac died in the GPU watchdog instead. Say so here,+ // before Generate, with the same number the worker refuses on.+ const a2vCap = (BOOT && BOOT.a2v_max_frames) || 0;+ if (a2vCap && frames > a2vCap) {+ const capSec = Math.round((a2vCap - 1) / 24);+ warn.style.display = '';+ warn.innerHTML = 'This Mac renders Audio → Video up to <b>' + capSec+ + ' s</b> per clip — longer ones outgrow its memory and are refused. '+ + 'Render the song as ' + capSec + ' s clips (set <b>Start at</b> to 0, '+ + capSec + ', ' + (2 * capSec) + ' …) and join them in the Editor.';+ return;+ }// THE CANVAS IS THE LEVER, NOT THE LENGTH. Below the knee the reports run// clean to 721 frames, so there is nothing to say; above it they give out// around frame 450 whatever the length asked for.@@ -466,6 +750,64 @@ function audioConditioningScaleReset() {}}+// LOAD PARAMS ON AN AUDIO → VIDEO CLIP (LTX-04). The generic loader has no+// a2v branch: it fell through to Text mode, copied the track into the Manual+// form's #audio (which a2v never reads) and left the Audio tab untouched, so+// Generate queued a different kind of video with no audio conditioning. This+// puts the request back where it came from — the Audio tab's one-shot form,+// read by audioStudioGenerate(): the track, the reference image, the canvas,+// the length, the seed, the offset into the song and the conditioning+// strength, with Auto kept as Auto (a blank in the sidecar) rather than+// frozen at whichever lane default the clip happened to render on.+function a2vLoadParams(p) {+ p = p || {};+ const audio = String(p.audio || '');+ AUDIO_STUDIO.audioPath = audio || null;+ AUDIO_STUDIO.audioName = audio ? audio.split('/').pop() : null;+ AUDIO_STUDIO.audioDuration = null;+ audioModeSet('drive');+ if (typeof workflowSwitch === 'function') workflowSwitch('audio');+ const det = document.getElementById('mvOneShotDetails');+ if (det) det.open = true;+ audioStudioRenderSlots();+ const setVal = (id, v) => {+ const el = document.getElementById(id);+ if (el && v !== undefined && v !== null && v !== '') el.value = String(v);+ };+ setVal('audioStudioPrompt', p.prompt);+ setVal('audioStudioWidth', p.width);+ setVal('audioStudioHeight', p.height);+ const seed = (p.seed_used != null && p.seed_used !== '') ? p.seed_used : p.seed;+ setVal('audioStudioSeed', seed);+ const startEl = document.getElementById('audioStudioStart');+ if (startEl) startEl.value = String(Math.max(0, parseFloat(p.audio_start_time) || 0));+ const frames = parseInt(p.frames, 10);+ if (Number.isFinite(frames) && frames > 1) {+ const slider = document.getElementById('audioStudioDuration');+ const sec = Math.max(1, Math.round((frames - 1) / 24));+ if (slider) slider.value = String(sec);+ audioStudioDurationChanged(String(sec));+ }+ if (typeof pickerSetImage === 'function') {+ pickerSetImage('a2v_image', p.image ? String(p.image) : '', { snapAspect: false });+ }+ const acs = p.audio_conditioning_scale;+ const acsEl = document.getElementById('audioConditioningScale');+ // A NUMBER 1 is the pre-4.15.2 default, not a choice: the old make_job+ // stored a float 1.0 on every a2v job, and on Q8 1.0 switches audio+ // guidance off. The server reads that float as Auto (a2v_requested_scale);+ // restoring it here as an explicit "1" would undo that. Today's sidecars+ // carry strings ("" = Auto, "2.5" = dragged), which are kept as they are.+ const legacyDefault = (typeof acs === 'number' && acs === 1);+ if (acsEl && !legacyDefault && acs !== undefined && acs !== null && String(acs).trim() !== ''+ && Number.isFinite(parseFloat(acs))) {+ acsEl.value = String(parseFloat(acs));+ audioConditioningScaleChanged(acsEl);+ } else {+ audioConditioningScaleReset();+ }+}+async function audioStudioGenerate() {if (AUDIO_STUDIO.busy) return;const status = document.getElementById('audioStudioStatus');@@ -3181,9 +3523,14 @@ Object.assign(globalThis, {musicComposeActive, musicInit, updateMusicAvailability, audioModeSet, musicPick, musicFormChanged,musicFormParams, musicGenerate, useTrackInA2V, openMusicInstallCard, closeMusicInstallCard,musicInstallRender, musicInstallStart, musicInstallStop,+ // Music Studio (cover): the install card's button is generated markup.+ musicCoverInstall, musicCoverSummary, musicCoverInstallCard, musicCfgValue,+ // Music Studio (LoRA): the picker's rows and the install card are generated markup.+ musicLoraPicks, musicLoraRender, musicLoraToggled, musicLoraSummaryText,+ musicLoraInstallCard, musicLoraInstall, musicFetchCard,windowPromptsInput,audioStudioInit, audioStudioDurationChanged, audioStudioEnhancePrompt, audioStudioGenerate,- audioConditioningScaleChanged, audioConditioningScaleReset,+ audioConditioningScaleChanged, audioConditioningScaleReset, a2vLoadParams,trainRecommendedPreset, trainUpdatePresetButtons, trainUpdatePresetNote, downloadSampleCharacter,charactersInit, charactersRenderChips, charactersOpenCompose, charactersBackToGrid,charactersHandleAudioUpload, charactersClearAudio, charactersUpdateStrengthDisplay, charactersSyncStrengthControls,diff --git a/webapp/js/editor.js b/webapp/js/editor.jsindex 8999e1c..93f5ac7 100644--- a/webapp/js/editor.js+++ b/webapp/js/editor.js@@ -205,6 +205,9 @@ window.SBE = {// nothing has reached the disk for too long; `saveFailed` is the reason the// alarm is up, and it is a string precisely so it can be shown.savePending: false, dirtyAt: 0, saveFailed: '',+ // The promise of the save in flight, follow-up included: what a second+ // caller is handed instead of the old `'busy'` (see sbeSave).+ saveFlight: null,// The quiet lane's own two facts, and the drafts this film has.backingUp: false, backedUpAt: 0,drafts: [], activeDraft: '', backup: null,@@ -217,7 +220,7 @@ window.SBE = {// inspector, the preview and the strip player mean — and `selSet` is every// clip the verbs act on, always including `sel`. See sbeSelNormalise.selSet: [],- undo: [], redo: [], errors: {}, sentOrder: [],+ undo: [], redo: [], errors: {}, sentOrder: [], loadGen: 0, musicFor: '',// THE ONE NOTICE SURFACE. `noticeLead` is the chip the user clicked open,// `backupHidden` is "Later" on the recovery offer (this session, this// offer), `errsOpen` is the validation list unfolded past its first line.@@ -3809,6 +3812,10 @@ function sbeCloseDoc(opts) {SBE.id = '';SBE.clips = [];SBE.undo.length = 0; SBE.redo.length = 0;+ // The soundtrack field belongs to the document that just closed (SB5-11).+ SBE.musicFor = '';+ const musicBox = sbeEl('sbeMusic');+ if (musicBox) musicBox.value = '';window.removeEventListener('resize', sbePaint);if (!(opts && opts.quiet)) { edRemember(''); edShowPicker(); }}@@ -3827,15 +3834,75 @@ function sbeGoToBoard() {// The document is gone and nothing about it is worth keeping.function sbeTeardown() { sbeCloseDoc({ quiet: true }); }+// SWITCHING FILMS FROM INSIDE THE EDITOR. The document fills the stage, the+// name in the header looked like a control and did nothing, and the only way+// to another film was ⋯ → Close → the picker. The name drops the list now.+// Picking a film goes through the one door (edOpenBoard → sbeOpen), which+// closes this document the way Close does: unsaved work is backed up first.+async function sbeFilmsToggle() {+ const pop = sbeEl('sbeFilmsMenu');+ if (!pop) return;+ const opening = pop.hidden;+ sbePopToggle('sbeFilmsMenu', 'sbeFilmsBtn');+ if (!opening) return;+ const list = sbeEl('sbeFilmsList');+ const note = sbeEl('sbeFilmsNote');+ list.innerHTML = '';+ note.hidden = false;+ note.textContent = 'reading your __SEQS__…';+ let boards;+ try {+ const r = await (await fetch('/storyboard/list')).json();+ boards = ((r && r.boards) || []).filter(b => (b.clips || 0) > 0 || b.id === SBE.id);+ } catch (e) {+ note.textContent = 'The panel did not answer — try again.';+ return;+ }+ if (pop.hidden) return; // closed while the list was on its way+ note.hidden = boards.length > 1;+ if (boards.length <= 1) note.textContent = 'No other __SEQ__ has clips yet.';+ list.innerHTML = boards.map(b => {+ const cur = b.id === SBE.id;+ const n = b.clips || 0;+ return '<button type="button" role="menuitem" class="ghost-btn' ++ (cur ? ' is-current' : '') + '"' + (cur ? ' aria-current="true"' : '') ++ ' onclick="sbeFilmsPick(\'' + escapeHtml(b.id) + '\')"' ++ ' title="' + escapeHtml(b.title || b.id) + '">' ++ '<span class="name">' + escapeHtml(b.title || b.id) + '</span>' ++ '<span class="sub">' + (cur ? 'open · ' : '') + n + ' clip' + (n === 1 ? '' : 's') ++ '</span></button>';+ }).join('');+}++function sbeFilmsPick(id) {+ sbePopCloseAll('');+ if (!id || id === SBE.id) return;+ edOpenBoard(id);+}++// Every film, as the picker shows them: Close, said from where it is wanted.+function sbeFilmsAll() {+ sbePopCloseAll('');+ sbeClose();+}+async function sbeLoad(quiet) {+ // WHICH LOAD THIS IS, AND FOR WHICH FILM (SB5-03). A response used to be+ // adopted whenever it arrived: open A, switch to B before A answered, and+ // A's clips, revision and soundtrack landed under B's id — a Save then+ // wrote A's arrangement into B. Only the newest load of the film still on+ // screen may be adopted.+ const id = SBE.id;+ const gen = SBE.loadGen = (SBE.loadGen || 0) + 1;let r;try {- r = await (await fetch('/storyboard/edit?id=' + encodeURIComponent(SBE.id)+ r = await (await fetch('/storyboard/edit?id=' + encodeURIComponent(id)+ '&session=' + encodeURIComponent(SBE.session))).json();} catch (e) {- if (!quiet) sbeSetState('the panel did not answer', 'dirty');+ if (!quiet && SBE.id === id) sbeSetState('the panel did not answer', 'dirty');return;}+ if (!SBE.open || SBE.id !== id || gen !== SBE.loadGen) return;if (!r || !r.ok) {// THE DOCUMENT IS GONE, not broken. A remembered id whose film was// deleted has to land on the picker — the Editor's own empty state — and@@ -3855,9 +3922,40 @@ async function sbeLoad(quiet) {: ((r && r.error) || 'could not read this timeline'));return;}+ // A QUIET RE-READ NEVER REPLACES UNSAVED WORK. Prepare finishing, a tab+ // coming back into view and a clip landing all re-read the SAVED document+ // to pick up proxies and new shots — and adopting it threw away every edit+ // made since the last Save and marked the timeline clean. With work on+ // screen, take the facts around the arrangement and leave the arrangement.+ if (quiet && (SBE.dirty || SBE.saving || SBE.conflict)) { sbeAdoptMeta(r); return; }sbeAdopt(r, quiet);}+// THE FACTS AROUND AN ARRANGEMENT, WITHOUT THE ARRANGEMENT. Everything a+// re-read is FOR — proxies Prepare just built, shots rendered since, relink+// offers, the Prepare state — and nothing the user edits: clips, overlays,+// transitions, tracks, the soundtrack, the revision and the undo history all+// stay exactly as they are on screen.+function sbeAdoptMeta(r) {+ SBE.proxyUrl = r.proxy_url || SBE.proxyUrl;+ SBE.unplaced = r.unplaced || [];+ SBE.pool = r.clips || [];+ SBE.relink = r.relink || [];+ SBE.sections = r.sections || SBE.sections || [];+ SBE.prepare = r.prepare || {};+ const px = {};+ for (const c of (((r.edit || {}).clips) || []).concat(r.clips || [])) {+ if (c && c.path && c.proxy) px[c.path] = c.proxy;+ }+ for (const c of (SBE.clips || [])) {+ if (c && c.path && px[c.path]) c.proxy = px[c.path];+ }+ sbePaintRelink();+ if (ED.src === 'film') edPoolRefresh();+ sbeFetchPeaks();+ sbePaint();+}+function sbeAdopt(r, quiet) {SBE.onMissing = null;// The payload has always carried the title; the Editor now uses it, so the@@ -3901,8 +3999,20 @@ function sbeAdopt(r, quiet) {// overlay id that is no longer in the document.if (typeof sbeKeyedDismiss === 'function') sbeKeyedDismiss();sbePaintNotices();- if (SBE.audio && SBE.audio.path && !sbeEl('sbeMusic').value) {- sbeEl('sbeMusic').value = SBE.audio.path;+ // THE SOUNDTRACK FIELD FOLLOWS THE DOCUMENT (SB5-11). It used to be filled+ // only when empty and never cleared, so after film A (song A) the field+ // still held song A when film B opened: B previewed its own soundtrack and+ // Render, Prepare and Auto-edit posted A's as an explicit override — and+ // an explicit `music` outranks the document's own on the server. A new+ // document (or draft) resets it to that document's track, or to nothing;+ // a re-read of the same one keeps whatever the user typed.+ const musicBox = sbeEl('sbeMusic');+ const docKey = SBE.id + '\n' + (SBE.activeDraft || '');+ if (SBE.musicFor !== docKey) {+ SBE.musicFor = docKey;+ musicBox.value = (SBE.audio && SBE.audio.path) || '';+ } else if (SBE.audio && SBE.audio.path && !musicBox.value) {+ musicBox.value = SBE.audio.path;}sbePaintMusicName();// The saved mode wins over the control's default, or reopening a film would@@ -3928,10 +4038,15 @@ function sbeAdopt(r, quiet) {}async function sbeFetchPeaks() {+ const id = SBE.id;try {- const res = await fetch('/storyboard/edit/peaks?id=' + encodeURIComponent(SBE.id));+ const res = await fetch('/storyboard/edit/peaks?id=' + encodeURIComponent(id));+ // Another film is on screen now: these peaks, and the track path they+ // carry, are not its soundtrack.+ if (SBE.id !== id) return;if (!res.ok) { SBE.peaks = null; SBE.peaksFor = ''; sbePaint(); return; }const doc = await res.json();+ if (SBE.id !== id) return;SBE.peaks = sbeDecodePeaks(doc);SBE.peaksFor = String(doc.path || '');// THE WAVEFORM EXISTS BEFORE THE EDIT KNOWS ABOUT IT. `prepare` writes@@ -4500,6 +4615,7 @@ async function sbeBackup(quiet) {try {const body = sbeSaveBody({ id: SBE.id, edit: SBE.edit, clips: SBE.clips,overlays: SBE.overlays, tracks: SBE.tracks,+ transitions: SBE.transitions,expect: null });// WHICH DRAFT THIS WAS COMPOSED FROM. The server files the backup under// the draft that is active when the write LANDS, and this one is@@ -4561,33 +4677,47 @@ async function sbeBackup(quiet) {// session. `finally` is the whole fix, and it is the difference between an// error and a lost afternoon.async function sbeSave(quiet, force) {- if (!SBE.open) return;- // WHAT KIND OF WRITE IS PENDING, not just that one is. `sbeQueueSave` no- // longer saves — it schedules a crash BACKUP — so remembering a dropped- // save as a bare `true` and re-queuing through that lane turned the second- // of two rapid Save presses into a backup write, leaving edit.json at the- // older revision with the alarm reading clear.- if (SBE.saving) { SBE.savePending = quiet ? 'backup' : 'save'; return 'busy'; }+ if (!SBE.open) return false;+ // A SAVE ASKED FOR WHILE ANOTHER IS IN FLIGHT IS ANSWERED BY THE WRITE THAT+ // CARRIES IT. This used to return the string 'busy', and every action that+ // depends on the saved file reads its answer as `!(await sbeSave(true))` —+ // 'busy' is truthy, so Render and the NLE export went straight to the+ // server while the save was still on the wire and built the PREVIOUS cut,+ // including when that save then failed or conflicted (SB5-14). The caller+ // now gets the flight's own promise, which settles only once the follow-up+ // write below has landed or failed.+ //+ // AND THE FOLLOW-UP IS ALWAYS A SAVE. A quiet request used to be remembered+ // as a crash backup — a leftover from when the quiet save was the autosave.+ // It is not any more: every `sbeSave(true)` left is an action that needs+ // edit.json to hold what is on screen, and a backup does not do that.+ if (SBE.saving) {+ SBE.savePending = 'save';+ return SBE.saveFlight || false;+ }if (SBE.saveTimer) { clearTimeout(SBE.saveTimer); SBE.saveTimer = null; }SBE.saving = true;- let ok = false;- try {- ok = await sbeSaveInner(quiet, force);- } catch (e) {- // A throw here is the case that used to wedge the flag. It is also the- // one nothing on screen could have told you about.- sbeSaveAlarm('the editor could not build the save (' +- ((e && e.message) || String(e)) + ')');- } finally {- SBE.saving = false;+ const flight = (async () => {+ let ok = false;+ try {+ ok = await sbeSaveInner(quiet, force);+ } catch (e) {+ // A throw here is the case that used to wedge the flag. It is also the+ // one nothing on screen could have told you about.+ sbeSaveAlarm('the editor could not build the save (' ++ ((e && e.message) || String(e)) + ')');+ } finally {+ SBE.saving = false;+ }const again = SBE.savePending;SBE.savePending = false;- if (again && SBE.dirty && !SBE.conflict) {- if (again === 'save') sbeSave(quiet, force);- else sbeQueueSave();- }- }- return ok;+ // `force` does not carry: it answered one conflict, and the revision it+ // produced is the one the follow-up now expects.+ if (again && SBE.dirty && !SBE.conflict && SBE.open) return sbeSave(quiet, false);+ return ok;+ })();+ SBE.saveFlight = flight;+ return flight;}// THE ALARM. A save that is not happening is not a status, it is an@@ -4617,9 +4747,28 @@ function sbeSaveAlarmClear() {async function sbeSaveInner(quiet, force) {const order = SBE.clips.map(c => c.id);SBE.sentOrder = order;+ // EVERY LIVE COLLECTION, BY NAME. `transitions` was missing from both of+ // these calls while `sbeSaveBody` read `state.transitions`, so every Save+ // and every crash backup wrote an empty list: the dissolve previewed, the+ // render cut hard, and reopening lost it (2026-09-24 review, SB5-01).const body = sbeSaveBody({ id: SBE.id, edit: SBE.edit, clips: SBE.clips,overlays: SBE.overlays, tracks: SBE.tracks,+ transitions: SBE.transitions,expect: force ? null : SBE.revision });+ // WHAT THIS REQUEST CARRIES, AND FOR WHICH DOCUMENT. The answer comes back+ // later, and by then the user may have trimmed a clip or opened another+ // film: the response is a receipt for THIS arrangement of THIS draft, and+ // it used to be read as a receipt for whatever was on screen when it+ // arrived — `dirty = false` over a trim made while it was in flight, so+ // the trim was never written and closing did not even back it up (SB5-02).+ const sentId = SBE.id;+ const sentDraft = SBE.activeDraft || '';+ const sentDoc = JSON.stringify(body.edit);+ // ...AND THE SERVER CHECKS THE DRAFT TOO. A revision cannot tell drafts+ // apart (a new draft restarts at 1), so without the name a stale tab saved+ // draft A's arrangement into a draft another tab had just switched to, with+ // no conflict (SB5-04). The backup has always said which draft it is from.+ body.draft = sentDraft;let r;try {const res = await fetch('/storyboard/edit/save', {@@ -4630,21 +4779,35 @@ async function sbeSaveInner(quiet, force) {} catch (e) {r = { ok: false, error: String(e), _status: 0 };}+ // Another document is on screen now. Whatever this answer says is about a+ // film or draft the user has left; nothing here may be touched by it.+ if (SBE.id !== sentId || (SBE.activeDraft || '') !== sentDraft) return false;if (r.ok) {SBE.errors = {};sbeEl('sbeErrors').hidden = true;+ const rev = sbeNum((r.edit || {}).revision, SBE.revision + 1);+ // DID ANYTHING CHANGE WHILE THIS WAS ON THE WIRE? Asked of the same+ // serialisation the request was built from, so there is no list of+ // fields to fall out of date.+ const now = sbeSaveBody({ id: SBE.id, edit: SBE.edit, clips: SBE.clips,+ overlays: SBE.overlays, tracks: SBE.tracks,+ transitions: SBE.transitions, expect: null });+ const moved = JSON.stringify(now.edit) !== sentDoc;// Adopt the server's copy of the document, but NOT its clip array — the// user may have moved something in the milliseconds the save was in// flight, and throwing that away is the one thing an editor must never do.- SBE.edit = Object.assign({}, r.edit || {}, { clips: SBE.edit.clips || [] });- SBE.revision = sbeNum((r.edit || {}).revision, SBE.revision + 1);+ // If the document itself moved, keep ALL of it and take only the number.+ SBE.edit = moved ? Object.assign({}, SBE.edit, { revision: rev })+ : Object.assign({}, r.edit || {}, { clips: SBE.edit.clips || [] });+ SBE.revision = rev;SBE.unplaced = r.unplaced || [];SBE.prepare = r.prepare || SBE.prepare;- SBE.dirty = false;+ SBE.dirty = moved;SBE.conflict = 0;sbeEl('sbeConflict').hidden = true;- sbePaintNotices();- SBE.dirtyAt = 0;+ sbePaintNotices();+ if (!moved) SBE.dirtyAt = 0;+ else if (!SBE.dirtyAt) SBE.dirtyAt = Date.now();// A SAVE IS THE USER ANSWERING THE OFFER. The server deletes the backup// on a successful save, so this follows it rather than deciding on its// own — and clearing it is what brings the crash lane back to life:@@ -4658,19 +4821,29 @@ async function sbeSaveInner(quiet, force) {// thing a user checks after saving is the panel that reports on saving.if (r.drafts) { SBE.drafts = r.drafts; sbePaintDraft(); }sbeSaveAlarmClear();- sbeSetState('saved · revision ' + SBE.revision, 'saved');+ if (moved) {+ // The save that just landed deleted the crash backup, and what is on+ // screen is newer than it: put the net back under the newer work.+ sbeSetState('unsaved changes · revision ' + SBE.revision + ' is saved', 'dirty');+ sbeQueueSave();+ } else {+ sbeSetState('saved · revision ' + SBE.revision, 'saved');+ }sbePaint();return true;}if (r._status === 409 && r.conflict) {// Honest, and it does not choose for you: another tab is ahead, your// arrangement is still on this screen, and both ways out are one click.- SBE.conflict = sbeNum(r.revision, 0);+ SBE.conflict = Math.max(1, sbeNum(r.revision, 0));sbeEl('sbeConflict').hidden = false;sbePaintNotices();- sbeEl('sbeConflictText').textContent =- 'Another tab saved this timeline (it is at revision ' + SBE.conflict +- ', you started from ' + SBE.revision + '). Nothing here has been lost.';+ sbeEl('sbeConflictText').textContent = r.draft_conflict+ ? ('Another tab switched this __SEQ__ to the draft "' + (r.active_draft || '?') ++ '". This arrangement belongs to "' + (sentDraft || '?') + '" and was not ' ++ 'written over it — its crash backup keeps it. Load theirs to follow the switch.')+ : ('Another tab saved this timeline (it is at revision ' + SBE.conflict ++ ', you started from ' + SBE.revision + '). Nothing here has been lost.');sbeSaveAlarm('another tab is at revision ' + SBE.conflict +' and this one is not being stored — choose which arrangement wins');return false;@@ -4745,17 +4918,12 @@ async function sbeForceSave() {// notifications. The button is the opposite — it is pressed by somebody who// wants to be told it worked, so it says which revision they now have.async function sbeSaveNow() {+ if (!SBE.open) { phosToast('Nothing to save yet.', {}); return; }+ // A press while another save is on the wire no longer answers 'busy': it+ // waits for the write that carries it (sbeSave), so the revision named here+ // is the one that holds what was on screen when the button was pressed.const ok = await sbeSave(false);- if (ok) {- phosToast('Saved — revision ' + SBE.revision, { kind: 'success' });- } else if (ok === 'busy') {- // Two very different reasons used to arrive as the same `undefined`, and- // this is the one where telling somebody their work needed no saving is- // exactly wrong: it is unwritten and a save is on its way.- phosToast('A save is already on its way — this one will follow it.', {});- } else if (ok === undefined) {- phosToast('Nothing to save yet.', {});- }+ if (ok) phosToast('Saved — revision ' + SBE.revision, { kind: 'success' });}// "4 minutes ago", in the smallest unit that still reads as a duration. Pure,@@ -8499,7 +8667,7 @@ function sbePaintHead() {// close-all and any-open — so the clip bar's overflow and the track's context// menu would have been two more chances to add a panel that Escape and a// click elsewhere could not shut.-const SBE_POPS = ['sbeRenderMenu', 'sbeMoreMenu', 'sbeKeysPop', 'sbeMusicMenu',+const SBE_POPS = ['sbeFilmsMenu', 'sbeRenderMenu', 'sbeMoreMenu', 'sbeKeysPop', 'sbeMusicMenu','sbeCbarMenu', 'sbeCtxMenu', 'sbeSoundMenu'];function sbePopToggle(id, anchorId) {@@ -12892,6 +13060,8 @@ Object.assign(globalThis, {sbeCbarModel, sbePaintCbar, sbeCbarFit, sbeCbarStamp,sbeSplitWhy, sbeCbarPlayhead,sbeCtxOpen, sbeReorderSel, sbeSplitHere, sbeGenOpen,+ // The header's film switcher (index.html onclicks + generated rows).+ sbeFilmsToggle, sbeFilmsPick, sbeFilmsAll,// THE AUDIO TRACKS — the model (for the harnesses) and every name the// generated heads, strips, inspector and pool rows call back into.sbeTrackLabel, sbeUnitGain, sbeTrackGain, sbeTsGain, sbeTsWindow, sbeTsGainPoints,diff --git a/webapp/js/health.js b/webapp/js/health.jsindex 658c41a..427dbcd 100644--- a/webapp/js/health.js+++ b/webapp/js/health.js@@ -704,12 +704,19 @@ setInterval(refreshVersionPill, 5 * 60 * 1000);// .modal-bg.show covers the batch modal (and any future modal that// uses the same .modal-bg + .show idiom). Including it here so Esc /// Tab focus-trap / body.modal-open scroll-lock all work for it too.- const MODAL_SEL = '.models-modal, .model-browser-modal, .expand-lightbox, .modal-bg.show';+ //+ // EVERY .modal-bg, not only the ones showing at startup (Codex UI-08). The+ // selector said `.modal-bg.show`, so the observers below were registered+ // only on dialogs already open when the page loaded — none — and isVisible()+ // did not know the `show` class at all: Storyboard's re-plan dialog and the+ // Editor's Generate-shot dialog open with classList.add('show'), so Escape,+ // the Tab trap and the scroll lock all ignored them.+ const MODAL_SEL = '.models-modal, .model-browser-modal, .expand-lightbox, .modal-bg';const isVisible = el => {const d = el.style.display;- // Some modals open by adding an .open class (.model-browser-modal);- // others toggle the inline style. Cover both.- if (el.classList.contains('open')) return true;+ // Some modals open by adding an .open class (.model-browser-modal), the+ // .modal-bg family by adding .show; others toggle the inline style.+ if (el.classList.contains('open') || el.classList.contains('show')) return true;return d === 'flex' || d === 'block';};const visibleModals = () =>@@ -726,12 +733,25 @@ setInterval(refreshVersionPill, 5 * 60 * 1000);// global subtree observer and avoids the cost of body-wide attribute// tracking. Lazy — modals added later (none today, but defensive)// need to re-register.- document.querySelectorAll(MODAL_SEL).forEach(el => {+ const watched = new WeakSet();+ const watch = el => {+ if (watched.has(el)) return;+ watched.add(el);new MutationObserver(refreshScrollLock).observe(el, {attributes: true,attributeFilter: ['style', 'class'],});- });+ };+ document.querySelectorAll(MODAL_SEL).forEach(watch);+ // A modal appended to <body> later (the batch modal) registers itself.+ // Direct children only — not the body-wide subtree observer ruled out above.+ new MutationObserver(recs => {+ for (const r of recs) {+ for (const n of (r.addedNodes || [])) {+ if (n.nodeType === 1 && n.matches && n.matches(MODAL_SEL)) { watch(n); refreshScrollLock(); }+ }+ }+ }).observe(document.body, { childList: true });refreshScrollLock();// Esc closes the topmost modal. We find the close button inside it@@ -744,12 +764,20 @@ setInterval(refreshVersionPill, 5 * 60 * 1000);if (!top) return;e.preventDefault();e.stopPropagation();+ // Case-insensitive: sbCloseReplan() / sbeGenClose() are the class-based+ // dialogs' own close functions and never matched a lower-case "close".const closeBtn =top.querySelector('button[onclick*="close"]') ||+ Array.from(top.querySelectorAll('button[onclick]'))+ .find(b => /close/i.test(b.getAttribute('onclick') || '')) ||top.querySelector('.close-btn') ||top.querySelector('.expand-close');if (closeBtn) closeBtn.click();- else { top.style.display = 'none'; top.classList.remove('open'); }+ else if (top.classList.contains('show') || top.classList.contains('open')) {+ // Class-opened: drop the class. An inline display:none here would+ // outrank `.modal-bg.show` and the dialog could never open again.+ top.classList.remove('show', 'open');+ } else { top.style.display = 'none'; }});// Focus trap — when a modal is visible, Tab cycles inside it.diff --git a/webapp/js/loras.js b/webapp/js/loras.jsindex 9183306..8fb0e2b 100644--- a/webapp/js/loras.js+++ b/webapp/js/loras.js@@ -262,8 +262,13 @@ function _serializeLoras() {const _inLane = (l) => (_tag === 'video:h3')? _laneOf(l.path) === 'h3': _laneOf(l.path) !== 'h3';+ // `scale_v` rides along only on a strength replayed from an older recipe+ // (Load Params / Finish, _restoreLoraPicker): it tells the server which+ // meaning of "strength" that number was written in (Codex H3-03).const slim = _activeLoras.filter(_inLane)- .map(l => ({ path: l.path, strength: l.strength }));+ .map(l => (typeof l.scale_v === 'number')+ ? { path: l.path, strength: l.strength, scale_v: l.scale_v }+ : { path: l.path, strength: l.strength });document.getElementById('lorasJson').value = JSON.stringify(slim);// Train-Character LoRAs are trained against the dev transformer (HQ// path) — Quick/Standard run the distilled model at 8 steps, which is@@ -328,6 +333,7 @@ function setLoraStrength(path, strength) {const e = _activeLoras.find(l => l.path === path);if (!e) return;e.strength = Math.max(-2, Math.min(2, parseFloat(strength) || 0));+ delete e.scale_v; // chosen now, in this build's meaning — no longer a replay_serializeLoras();}diff --git a/webapp/js/music.js b/webapp/js/music.jsnew file mode 100644index 0000000..b71f1e3--- /dev/null+++ b/webapp/js/music.js@@ -0,0 +1,1282 @@+// webapp/js/music.js — Music Studio: the song as a thing you come back to.+//+// The composer (Write / Cover / Score) lives in characters.js with the rest+// of the Audio tab; this module owns what happens AFTER a song exists — the+// Song card under the player: its sheet music, its words, where it came from,+// and the four ways to get another song out of it. It also owns the two+// helpers the composer borrows: Gemma writing lyrics, and section-tag chips.+//+// Everything a handler in the markup calls is published at the bottom.++let SONG = null; // the /music/score payload for the selected song+let songReq = 0; // stale-response guard for the fetch below+let songShown = ''; // the path the card is showing (or loading)++function _el(id) { return document.getElementById(id); }+function _esc(s) { return String(s == null ? '' : s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); }+function _say(msg) { const el = _el('songStatus'); if (el) el.textContent = msg || ''; }++// ---- the Song card --------------------------------------------------------++// Called by selectOutput() for every selection; only a song fills it in.+async function songCardRender(o) {+ const card = _el('songCard');+ if (!card) return;+ const isSong = o && o.kind === 'audio' && o.engine === 'music';+ card.hidden = !isSong;+ // THE PREVIOUS SONG IS GONE THE MOMENT ANOTHER IS PICKED (M6-02). SONG+ // used to keep the last song until the new one's score arrived, so an+ // action pressed in that window — or after a failed read — used the OLD+ // song's score or recording under the NEW song's title. Leaving the card+ // also retires any read still on its way.+ SONG = null;+ if (!isSong) { songShown = ''; ++songReq; return; }+ songShown = o.path;+ const m = o.music || {};+ // The bar is the player, the card is the reader. Looking at a song never+ // interrupts the one that is playing; the bar only takes a song when it has+ // none yet (so the transport is there to press), and never starts it.+ if (!_barSong) musicBarShow(o);+ _el('songTitle').textContent = m.title || _songNameFromFile(o.name);+ _el('songStyle').textContent = m.style || '';+ _el('songBadges').innerHTML = _badges(m);+ _say('');+ musicScoreEditToggle(false);+ // Facts we already have from the gallery row; the score itself is fetched.+ const req = ++songReq;+ try {+ const r = await fetch(`/music/score?path=${encodeURIComponent(o.path)}`);+ const data = await r.json();+ if (req !== songReq) return; // the user moved on+ if (!r.ok || data.error) throw new Error(data.error || 'Could not read the song');+ SONG = data;+ _el('songTitle').textContent = data.title || _songNameFromFile(o.name);+ _el('songStyle').textContent = data.style || '';+ _renderLineage(data);+ _renderScore(data.abc);+ _renderLyrics(data.lyrics);+ // A song with nothing saved cannot be performed again: say so on the+ // buttons rather than after a click.+ const noArt = !data.has_artifacts;+ for (const b of _el('songActions').querySelectorAll('button')) {+ const kind = (b.getAttribute('onclick') || '').match(/musicVariation\('(\w+)'\)/);+ if (kind) { b.disabled = noArt; b.title = noArt ? 'This song kept no artifacts (made before v4.16). Compose it again to get takes.' : b.title; }+ }+ } catch (e) {+ if (req === songReq) _say(e.message || String(e));+ }+}++function _songNameFromFile(name) {+ return String(name || '').replace(/\.wav$/i, '').replace(/^music_\d{8}_\d{6}_/, '').replace(/_/g, ' ');+}++// The gallery block carries `loras: [{name, strength}]`; /music/score answers+// with the runner's full `lora` block. Read both shapes, show one badge.+function _loraList(m) {+ if (Array.isArray(m.loras)) return m.loras;+ const adapters = ((m.lora || {}).adapters) || [];+ return adapters.map(a => ({name: a.file, strength: a.strength}));+}+function _loraLabel(file) {+ return String(file || 'lora').replace(/\.bf16\.safetensors$|\.safetensors$/i, '')+ .replace(/_/g, ' ').slice(0, 28);+}++function _badges(m) {+ const out = [];+ if (m.variation) out.push(`<span class="song-badge">${_esc({take: 'new take', sound: 're-rolled', restyle: 'restyled'}[m.variation] || m.variation)}</span>`);+ if (m.cover) out.push('<span class="song-badge">cover</span>');+ if (m.instrumental) out.push(`<span class="song-badge muted"${+ m.instrumental_recipe === 'mothersuperior-ar-lora'+ ? ' title="Made with Mothersuperior\'s instrumental AR adapter at strength 1"' : ''+ }>instrumental${m.instrumental_recipe === 'mothersuperior-ar-lora' ? ' · lora' : ''}</span>`);+ // Which adapters made this song. The sidecar keeps their hashes; the badge+ // keeps the two things a listener compares by — which one, and how hard.+ for (const l of (_loraList(m))) {+ out.push(`<span class="song-badge" title="LoRA ${_esc(l.name || '')}">${+ _esc(_loraLabel(l.name))}${l.strength != null ? ` ${Number(l.strength).toFixed(2)}` : ''}</span>`);+ }+ if (m.mode && m.mode !== 'off') out.push(`<span class="song-badge muted">${_esc(m.mode === 'full' ? 'melody + chords' : 'melody')}</span>`);+ if (m.ended_naturally === false) out.push('<span class="song-badge muted" title="The song hit Max length before it ended on its own">cut at max length</span>');+ return out.join('');+}++function _renderLineage(d) {+ const el = _el('songLineage');+ if (!d.parent) { el.innerHTML = ''; return; }+ const parentName = String(d.parent).split('/').pop();+ const how = {take: 'a new take of', sound: 'a re-recording of', restyle: 'a restyle of'}[d.variation] || 'made from';+ // The handler's argument is JSON inside an HTML attribute, so it is+ // ESCAPED for the attribute: the bare JSON's opening quote used to close+ // `onclick="` and every parent link was a syntax error (M6-10).+ const arg = _esc(JSON.stringify(String(d.parent)));+ el.innerHTML = `${how} <a onclick="musicOpenSong(${arg})">${_esc(parentName)}</a>`;+}++function _renderScore(abc) {+ const host = _el('songScore');+ const sum = _el('songScoreSum');+ const editBtn = _el('songScoreEditBtn');+ host.innerHTML = '';+ if (!abc || !abc.trim()) {+ host.innerHTML = '<div class="song-score-empty">This song was written with No score — there is nothing to draw. Compose with Melody + chords or Melody only to get sheet music.</div>';+ sum.textContent = 'none';+ if (editBtn) editBtn.disabled = true;+ return;+ }+ if (editBtn) editBtn.disabled = false;+ const facts = _abcFacts(abc);+ sum.textContent = facts;+ _drawAbc(host, abc);+}++// abcjs renders into a host element; sizing is responsive to the card.+function _drawAbc(host, abc) {+ if (!window.ABCJS) { host.innerHTML = '<div class="song-score-empty">Score renderer not loaded.</div>'; return; }+ try {+ window.ABCJS.renderAbc(host, abc, {+ responsive: 'resize', add_classes: true, staffwidth: 640,+ paddingtop: 4, paddingbottom: 4, paddingleft: 4, paddingright: 4,+ });+ } catch (e) {+ host.innerHTML = `<div class="song-score-empty">Could not draw this score: ${_esc(e.message || e)}</div>`;+ }+}++// Key, meter and tempo read straight off the ABC header — the three facts a+// musician asks first.+function _abcFacts(abc) {+ const get = (k) => { const m = abc.match(new RegExp(`^${k}:\\s*(.+)$`, 'm')); return m ? m[1].trim() : ''; };+ const key = get('K'), meter = get('M'), q = get('Q');+ const bpm = q ? (q.match(/=(\d+)/) || [])[1] : '';+ return [key && `${key}`, meter && `${meter}`, bpm && `${bpm} BPM`].filter(Boolean).join(' · ');+}++function _renderLyrics(lyrics) {+ const el = _el('songLyrics');+ const sum = _el('songLyricsSum');+ if (!lyrics || !lyrics.trim()) { el.textContent = '(instrumental)'; sum.textContent = 'instrumental'; return; }+ el.innerHTML = _esc(lyrics).replace(/^(\[[^\]]+\])$/gm, '<span class="tag">$1</span>');+ const tags = (lyrics.match(/^\[[^\]]+\]$/gm) || []).length;+ sum.textContent = tags ? `${tags} sections` : '';+}++// ---- the four ways to get another song ------------------------------------++async function musicVariation(kind, path) {+ const target = path || (SONG && SONG.path);+ if (!target) return;+ const seed = _el('musicSeed') ? _el('musicSeed').value : '-1';+ _say(kind === 'sound' ? 'Queueing a re-recording…' : 'Queueing a new take…');+ if (typeof phosToast === 'function' && path) phosToast(kind === 'sound' ? 'Re-recording queued' : 'New take queued');+ try {+ const fd = new URLSearchParams({path: target, kind, seed});+ const r = await fetch('/music/variation', {method: 'POST', body: fd});+ const data = await r.json();+ if (!r.ok || data.error) throw new Error(data.error || 'Could not queue');+ _say(kind === 'sound' ? 'Re-recording queued — a fraction of a full song.' : 'New take queued.');+ if (typeof poll === 'function') poll();+ } catch (e) { _say(e.message || String(e)); }+}++// "New style on this score": the composer's current style + lyrics go on+// THIS song's score. The form is the instrument; the card is the source.+// THE SONG AN ACTION IS FOR, read for that path and no other. The card's+// SONG is whatever the card last finished reading; an action from a song's+// ⋯ menu names its song and must not borrow another one while the card+// catches up.+async function _songFor(path) {+ if (SONG && SONG.path === path) return SONG;+ try {+ const r = await fetch(`/music/score?path=${encodeURIComponent(path)}`);+ const data = await r.json();+ if (!r.ok || !data || data.error) return null;+ return data;+ } catch (e) { return null; }+}++// The ⋯ menu's verbs that act on a song's own score or recording. Opening+// the card is for the eye; the action waits for THIS song and uses it —+// it used to fire 400 ms later against whatever SONG was by then (M6-02).+async function musicSongAction(path, action) {+ if (typeof selectOutput === 'function') selectOutput(path);+ const song = await _songFor(path);+ if (!song) { _say('Could not read that song — nothing was done.'); return; }+ if (action === 'restyle') return musicRestyleFromSong(song);+ if (action === 'cover') return musicCoverFromSong(song);+ if (action === 'edit') {+ if (songShown !== path) return; // the user has moved on+ SONG = song;+ musicScoreEditToggle(true);+ }+}++async function musicRestyleFromSong(song) {+ song = (song && song.path) ? song : SONG;+ if (!song) { _say('Still reading this song — try again in a moment.'); return; }+ const style = (_el('musicStyle') || {}).value || '';+ const lyrics = (_el('musicLyrics') || {}).value || '';+ if (!style.trim() && !lyrics.trim()) {+ _say('Put the new style and/or lyrics in the composer first, then click again.');+ if (typeof audioModeSet === 'function') audioModeSet('compose');+ return;+ }+ _say('Queueing a restyle…');+ try {+ // Max length is the composer's like the style is: the slider on screen,+ // not the limit the parent happened to be made with (M6-01).+ const fd = new URLSearchParams({path: song.path, kind: 'restyle', style, lyrics,+ seed: (_el('musicSeed') || {}).value || '-1', quality: (_el('musicQuality') || {}).value || 'final',+ title: (_el('musicTitle') || {}).value || '',+ max_seconds: (_el('musicMaxSeconds') || {}).value || ''});+ const r = await fetch('/music/variation', {method: 'POST', body: fd});+ const data = await r.json();+ if (!r.ok || data.error) throw new Error(data.error || 'Could not queue');+ _say('Restyle queued: this score, your new words and style.');+ if (typeof poll === 'function') poll();+ } catch (e) { _say(e.message || String(e)); }+}++function musicCoverFromSong(song) {+ song = (song && song.path) ? song : SONG;+ if (!song) { _say('Still reading this song — try again in a moment.'); return; }+ const src = _el('musicSourceAudio');+ if (src) src.value = song.path;+ const task = _el('musicTask');+ if (task) musicTaskSet('cover');+ if (typeof audioModeSet === 'function') audioModeSet('compose');+ if (typeof musicFormChanged === 'function') musicFormChanged();+ _say('Loaded as the source in Cover a song.');+}++function musicOpenSong(path) {+ if (typeof selectOutput === 'function') selectOutput(path);+}++// ---- the score editor ------------------------------------------------------++function musicScoreEditToggle(on) {+ const ed = _el('songScoreEditor');+ if (!ed) return;+ ed.hidden = !on;+ if (on && SONG) {+ _el('songScoreText').value = SONG.abc || '';+ _el('songScoreText').focus();+ }+}++function musicScorePreview() {+ const abc = _el('songScoreText').value;+ _drawAbc(_el('songScore'), abc);+ _el('songScoreSum').textContent = _abcFacts(abc) + ' · edited';+}++async function musicRenderEditedScore() {+ if (!SONG) return;+ const abc = _el('songScoreText').value;+ if (!/^K:/m.test(abc)) { _say('That is not a complete ABC score (no K: key line).'); return; }+ _say('Queueing the edited score…');+ try {+ const fd = new URLSearchParams({path: SONG.path, abc,+ style: (_el('musicStyle') || {}).value || '', lyrics: (_el('musicLyrics') || {}).value || '',+ seed: (_el('musicSeed') || {}).value || '-1', quality: (_el('musicQuality') || {}).value || 'final',+ title: (_el('musicTitle') || {}).value || '',+ max_seconds: (_el('musicMaxSeconds') || {}).value || ''});+ const r = await fetch('/music/score/render', {method: 'POST', body: fd});+ const data = await r.json();+ if (!r.ok || data.error) throw new Error(data.error || 'Could not queue');+ _say('Edited score queued. The new song lands beside this one.');+ musicScoreEditToggle(false);+ if (typeof poll === 'function') poll();+ } catch (e) { _say(e.message || String(e)); }+}++async function musicScoreCopy() {+ if (!SONG || !SONG.abc) return;+ try { await navigator.clipboard.writeText(SONG.abc); _say('ABC copied.'); }+ catch (_) { _say('Could not copy — select the text in Edit the score instead.'); }+}++// ---- composer helpers borrowed by characters.js --------------------------++function musicTaskSet(task) {+ const hidden = _el('musicTask');+ if (hidden) hidden.value = task;+ document.querySelectorAll('#musicTaskPills .seg-btn').forEach(b => {+ const on = b.dataset.value === task;+ b.classList.toggle('active', on); b.setAttribute('aria-pressed', String(on));+ });+ const cover = _el('musicCoverDetails');+ if (cover) cover.open = task !== 'write';+ // Score only: the composer's words and style are not used, say so by+ // dimming them rather than hiding a form the user may be mid-way through.+ for (const id of ['musicLyrics', 'musicStyle', 'musicConcept', 'musicTitle']) {+ const el = _el(id); if (el) el.disabled = task === 'score';+ }+ const btn = _el('musicGenBtn');+ if (btn) btn.textContent = task === 'score' ? 'Get the score' : task === 'cover' ? 'Cover it' : 'Compose';+}+function musicTaskPick(button) { musicTaskSet(button.dataset.value); if (typeof musicFormChanged === 'function') musicFormChanged(); }++// ---- Simple mode -----------------------------------------------------------+//+// Suno's best idea is that the form is optional: one box, and the machine+// fills in the brief. Ours differs in one place on purpose — it does not+// render. A song is minutes of this Mac's GPU, so what Gemma writes lands in+// the Custom fields and the person reads it before pressing Compose.+//+// Custom stays the truth. Simple's two knobs (Instrumental, Max length) are+// the same two decisions Custom already owns, mirrored rather than duplicated,+// so there is never a second value to reconcile at queue time.++let musicMode = 'custom';++function musicSimpleActive() { return musicMode === 'simple'; }++function musicSimpleMirror(dir) {+ const secs = _el('musicMaxSeconds'), inst = _el('musicInstrumental');+ const mine = _el('musicSimpleSeconds'), myInst = _el('musicSimpleInstrumental');+ if (!secs || !mine) return;+ if (dir === 'out') { secs.value = mine.value; inst.checked = myInst.checked; }+ else { mine.value = secs.value; myInst.checked = inst.checked; }+ const val = _el('musicSimpleSecondsVal');+ if (val) val.textContent = _mmss(Number(mine.value));+}++function musicSimpleChanged() {+ musicSimpleMirror('out');+ if (typeof musicFormChanged === 'function') musicFormChanged();+ musicSimpleMirror('in');+}++// Panes and the segment only — no form callbacks, so this is safe at boot+// before the engine probes have landed.+function musicModeApply() {+ const simple = musicMode === 'simple';+ const sp = _el('musicSimplePane'), cp = _el('musicCustomPane');+ if (sp) sp.hidden = !simple;+ if (cp) cp.hidden = simple;+ document.querySelectorAll('#musicModeSeg .seg-btn').forEach(b => {+ const on = b.dataset.value === musicMode;+ b.classList.toggle('active', on); b.setAttribute('aria-pressed', String(on));+ });+ musicSimpleMirror('in');+}++function musicModeSet(mode) {+ musicMode = mode === 'simple' ? 'simple' : 'custom';+ try { localStorage.setItem('phos_music_mode', musicMode); } catch (_) {}+ musicModeApply();+ const notice = _el('musicSimpleNotice');+ if (notice && musicMode === 'simple') notice.hidden = true;+ const btn = _el('musicGenBtn');+ if (musicMode === 'simple') { if (btn) btn.textContent = 'Compose'; }+ else musicTaskSet((_el('musicTask') || {}).value || 'write');+ if (typeof musicFormChanged === 'function') musicFormChanged();+}+function musicModePick(button) { musicModeSet(button.dataset.value); }++function musicModeInit() {+ let saved = null;+ try { saved = localStorage.getItem('phos_music_mode'); } catch (_) {}+ musicMode = saved === 'simple' ? 'simple' : 'custom';+ musicModeApply();+}++// Compose in Simple mode: write the brief, show it, stop. The button ends up+// focused on the Custom form so the next press is the one that renders.+async function musicSimpleCompose() {+ const box = _el('musicSimpleDescription');+ const status = _el('musicStatus');+ const notice = _el('musicSimpleNotice');+ const desc = (box || {}).value || '';+ if (!desc.trim()) {+ if (status) status.textContent = 'Say what the song should be first.';+ if (box) box.focus();+ return;+ }+ const btn = _el('musicGenBtn');+ if (notice) notice.hidden = true;+ if (btn) { btn.disabled = true; btn.textContent = 'Writing…'; }+ if (status) status.textContent = 'Gemma is writing the style and the words (the first time loads the model, ~15 s)…';+ try {+ musicSimpleMirror('out');+ const fd = new URLSearchParams({+ description: desc,+ instrumental: (_el('musicInstrumental') || {}).checked ? 'on' : 'off',+ seconds: (_el('musicMaxSeconds') || {}).value || '150',+ });+ const r = await fetch('/music/simple', {method: 'POST', body: fd});+ const data = await r.json();+ if (!r.ok || data.error) throw new Error(data.error || 'Nothing came back');+ if (_el('musicTitle')) _el('musicTitle').value = data.title || '';+ if (_el('musicStyle')) _el('musicStyle').value = data.style || '';+ // The description is the concept the per-section Rewrite works from.+ if (_el('musicConcept') && !(_el('musicConcept').value || '').trim()) _el('musicConcept').value = desc;+ musicLyricsSet(data.lyrics || '');+ musicTaskSet('write');+ musicModeSet('custom');+ if (notice) {+ notice.textContent = 'Written from your description — edit anything, then Compose.';+ notice.hidden = false;+ }+ if (status) status.textContent = '';+ if (btn) btn.focus();+ } catch (e) {+ if (status) status.textContent = e.message || String(e);+ } finally {+ if (btn) { btn.disabled = false; btn.textContent = 'Compose'; }+ if (typeof musicFormChanged === 'function') musicFormChanged();+ }+}++// ---- the lyrics editor -----------------------------------------------------+//+// A song is sections. The old box was one textarea and seven chips that typed+// a tag at the caret, which meant the structure existed only in the user's+// head and in the brackets. Here the structure IS the interface: a stack of+// sections, each with its label, its lines, its line count and a Rewrite that+// asks Gemma for that part alone.+//+// The bracket text stays the truth: #musicLyrics is written on every edit and+// is still the only field musicFormParams, the restyle verb and the score+// editor read. Text mode is the same truth, typed by hand — it re-parses into+// sections on blur, so neither view can drift from the other.++const LYRIC_LABELS = ['Intro', 'Verse', 'Pre-Chorus', 'Chorus', 'Bridge', 'Instrumental', 'Outro'];+let LYRICS = []; // [{tag: 'Verse', body: 'a line\nanother line'}]+let lyricsView = 'sections'; // 'sections' | 'text'+let lyricsBusy = -1; // index of the section Gemma is rewriting++// Text → sections. A bracketed line on its own opens a section; everything+// else belongs to the one above it. Words before the first tag are a real+// thing a user can type, so they become a section with no tag rather than+// being thrown away.+function _lyricsParse(text) {+ const out = [];+ let cur = null;+ for (const raw of String(text || '').split('\n')) {+ const tag = raw.trim().match(/^\[([^\]]+)\]$/);+ if (tag) { cur = {tag: tag[1].trim(), body: []}; out.push(cur); continue; }+ if (!cur) { if (!raw.trim()) continue; cur = {tag: '', body: []}; out.push(cur); }+ cur.body.push(raw);+ }+ return out.map(s => ({tag: s.tag, body: s.body.join('\n').replace(/^\n+/, '').replace(/\s+$/, '')}));+}++// Sections → text, in YuE2's format: the tag on its own line, the lines under+// it, a blank line between sections. A tag with nothing under it survives —+// that is how an instrumental passage is written.+function _lyricsText(sections) {+ return sections+ .map(s => (s.tag ? `[${s.tag}]` : '') + (s.body ? (s.tag ? '\n' : '') + s.body : ''))+ .filter(Boolean).join('\n\n');+}++function _lyricsLineCount(body) {+ return String(body || '').split('\n').filter(l => l.trim()).length;+}++// What the section costs, in the unit a lyricist counts in. No words is not+// nothing: it is how an instrumental passage is written.+function _lyricsCountLabel(n) {+ return n ? n + (n === 1 ? ' line' : ' lines') : 'no words';+}++// Every path that changes the sections ends here: the hidden field is the+// contract with the rest of the form, so it is written before anything else+// is told that the lyrics changed.+function _lyricsSync() {+ const ta = _el('musicLyrics');+ if (ta) ta.value = _lyricsText(LYRICS);+ const raw = _el('musicLyricsRaw');+ if (raw && lyricsView !== 'text') raw.value = ta ? ta.value : '';+ if (typeof musicFormChanged === 'function') musicFormChanged();+}++// A textarea that grows with its content: a chorus is four lines and a verse+// is eight, and scrolling inside a four-line box to read eight is the thing+// the old single textarea already did badly.+function _lyricsGrow(ta) {+ if (!ta) return;+ ta.style.height = 'auto';+ // A box inside a hidden pane measures 0 — the editor is built at boot, long+ // before anyone opens the Audio tab — so fall back to counting its rows.+ const h = ta.scrollHeight || String(ta.value || '').split('\n').length * 19 + 14;+ ta.style.height = `${Math.max(h, 30)}px`;+}++function musicLyricsRender() {+ const host = _el('musicLyricsSections');+ if (!host) return;+ if (!LYRICS.length) {+ host.innerHTML = '<div class="lyr-blank">No words yet. Add a section below, or say what ' ++ 'the song is about and let Gemma write the whole thing.</div>';+ return;+ }+ host.innerHTML = LYRICS.map((s, i) => {+ const n = _lyricsLineCount(s.body);+ const count = _lyricsCountLabel(n);+ const labels = LYRIC_LABELS.includes(s.tag) || !s.tag ? LYRIC_LABELS : [s.tag, ...LYRIC_LABELS];+ const opts = labels.map(l => `<option value="${_esc(l)}"${l === s.tag ? ' selected' : ''}>${_esc(l)}</option>`).join('');+ const busy = lyricsBusy === i;+ return `<div class="lyr-sec${n ? '' : ' wordless'}">+ <div class="lyr-sec-head">+ <span class="lyr-tag-wrap"><select class="lyr-tag" aria-label="Section" onchange="musicLyricsRetag(${i}, this.value)">${opts}</select></span>+ <span class="lyr-count">${count}</span>+ <span class="lyr-acts">+ <button type="button" class="lyr-btn"${busy ? ' disabled' : ''} onclick="musicLyricsRewrite(${i})"+ title="Gemma rewrites this section only, in the style you gave">${busy ? 'Writing…' : 'Rewrite'}</button>+ <button type="button" class="lyr-ico"${i === 0 ? ' disabled' : ''} onclick="musicLyricsMove(${i}, -1)" title="Move up" aria-label="Move up">↑</button>+ <button type="button" class="lyr-ico"${i === LYRICS.length - 1 ? ' disabled' : ''} onclick="musicLyricsMove(${i}, 1)" title="Move down" aria-label="Move down">↓</button>+ <button type="button" class="lyr-ico lyr-del" onclick="musicLyricsRemove(${i})" title="Delete this section" aria-label="Delete this section">✕</button>+ </span>+ </div>+ <textarea class="lyr-lines" rows="1" aria-label="${_esc(s.tag || 'Lyrics')} lines"+ oninput="musicLyricsType(${i}, this)">${_esc(s.body)}</textarea>+ <div class="lyr-wordless">Nothing sung here — an instrumental passage. Type to give it words.</div>+ </div>`;+ }).join('');+ host.querySelectorAll('textarea.lyr-lines').forEach(_lyricsGrow);+ // Fresh controls arrive enabled; if the song is instrumental they must not.+ musicLyricsLock(!!(_el('musicLyrics') || {}).disabled);+}++// Typing must not re-render (the caret would jump), so the one thing that+// changes with the words — the line count and the wordless hint — is updated+// in place and everything else is left alone.+function musicLyricsType(i, ta) {+ if (!LYRICS[i]) return;+ LYRICS[i].body = ta.value;+ const sec = ta.closest('.lyr-sec');+ const n = _lyricsLineCount(ta.value);+ if (sec) {+ sec.classList.toggle('wordless', !n);+ const count = sec.querySelector('.lyr-count');+ if (count) count.textContent = _lyricsCountLabel(n);+ }+ _lyricsGrow(ta);+ _lyricsSync();+}++function musicLyricsRetag(i, tag) {+ if (!LYRICS[i]) return;+ LYRICS[i].tag = tag;+ _lyricsSync(); musicLyricsRender();+}++function musicLyricsMove(i, dir) {+ const j = i + dir;+ if (!LYRICS[i] || !LYRICS[j]) return;+ [LYRICS[i], LYRICS[j]] = [LYRICS[j], LYRICS[i]];+ _lyricsSync(); musicLyricsRender();+}++function musicLyricsRemove(i) {+ if (!LYRICS[i]) return;+ LYRICS.splice(i, 1);+ _lyricsSync(); musicLyricsRender();+}++function musicLyricsAdd(tag) {+ LYRICS.push({tag: tag || 'Verse', body: ''});+ _lyricsSync(); musicLyricsRender();+ const boxes = _el('musicLyricsSections').querySelectorAll('textarea.lyr-lines');+ const last = boxes[boxes.length - 1];+ if (last) last.focus();+}++// Whatever set the words — Gemma, Simple mode, a song being loaded — comes+// through here, so there is exactly one way the editor is filled.+function musicLyricsSet(text) {+ LYRICS = _lyricsParse(text);+ _lyricsSync();+ const raw = _el('musicLyricsRaw');+ if (raw) raw.value = _el('musicLyrics') ? _el('musicLyrics').value : String(text || '');+ musicLyricsRender();+}++function musicLyricsViewPick(button) { musicLyricsView(button.dataset.value); }++function musicLyricsView(mode) {+ const want = mode === 'text' ? 'text' : 'sections';+ const wasText = lyricsView === 'text';+ lyricsView = want;+ const ed = _el('musicLyricsEditor'), raw = _el('musicLyricsRaw');+ if (ed) ed.hidden = want === 'text';+ if (raw) {+ raw.hidden = want !== 'text';+ if (want === 'text') raw.value = _el('musicLyrics') ? _el('musicLyrics').value : '';+ }+ // Leaving Text takes the typed brackets with it, otherwise the sections+ // would quietly overwrite what the user just wrote — and it re-parses AFTER+ // the editor is visible again, so the boxes can measure their own height.+ if (wasText && want !== 'text') musicLyricsRawSync();+ document.querySelectorAll('#musicLyricsViewSeg .seg-btn').forEach(b => {+ const on = b.dataset.value === want;+ b.classList.toggle('active', on); b.setAttribute('aria-pressed', String(on));+ });+}++// Text mode's blur: the brackets the user typed become the sections again.+function musicLyricsRawSync() {+ const raw = _el('musicLyricsRaw');+ if (!raw) return;+ LYRICS = _lyricsParse(raw.value);+ _lyricsSync();+ musicLyricsRender();+}++// Instrumental: the words are not used, so the editor says so by going quiet+// rather than disappearing — they are still there when the toggle comes off.+function musicLyricsLock(on) {+ const ed = _el('musicLyricsEditor'), raw = _el('musicLyricsRaw'), add = _el('musicLyricsAdd');+ for (const el of [ed, raw, add]) if (el) el.classList.toggle('lyr-off', !!on);+ if (raw) raw.disabled = !!on;+ if (ed) for (const c of ed.querySelectorAll('textarea, select, button')) c.disabled = !!on;+}++async function musicLyricsRewrite(i) {+ const s = LYRICS[i];+ if (!s || lyricsBusy >= 0) return;+ const status = _el('musicStatus');+ lyricsBusy = i; musicLyricsRender();+ if (status) status.textContent = `Gemma is rewriting the ${s.tag || 'section'}…`;+ try {+ const fd = new URLSearchParams({+ section: s.tag || 'Verse', lines: s.body,+ concept: (_el('musicConcept') || {}).value || '',+ style: (_el('musicStyle') || {}).value || '',+ seconds: (_el('musicMaxSeconds') || {}).value || '150',+ seed: String(Math.floor(Math.random() * 1e6)), // a rewrite asked twice should differ+ });+ const r = await fetch('/music/lyrics/section', {method: 'POST', body: fd});+ const data = await r.json();+ if (!r.ok || data.error) throw new Error(data.error || 'No lines came back');+ // The answer belongs to the section object captured above, wherever it+ // has been moved to since — never to "whatever is at index i now".+ if (!LYRICS.includes(s)) throw new Error('That section was removed while Gemma was writing — nothing changed.');+ s.body = data.lines;+ if (status) status.textContent = `${s.tag || 'Section'} rewritten in ${Math.round(data.elapsed_sec || 0)} s.`;+ _lyricsSync();+ } catch (e) {+ if (status) status.textContent = e.message || String(e);+ } finally {+ lyricsBusy = -1;+ musicLyricsRender();+ }+}++function musicLyricsInit() {+ if (!_el('musicLyricsSections')) return;+ musicLyricsSet((_el('musicLyrics') || {}).value || '');+ musicLyricsView('sections');+}++async function musicWriteLyrics() {+ const concept = (_el('musicConcept') || {}).value || '';+ const btn = _el('musicWriteLyricsBtn');+ const status = _el('musicStatus');+ if (!concept.trim()) { if (status) status.textContent = 'Say what the song is about first.'; _el('musicConcept').focus(); return; }+ if (btn) { btn.disabled = true; btn.textContent = 'Writing…'; }+ if (status) status.textContent = 'Gemma is writing the lyrics (the first time loads the model, ~15 s)…';+ try {+ const fd = new URLSearchParams({concept, style: (_el('musicStyle') || {}).value || '',+ seconds: (_el('musicMaxSeconds') || {}).value || '150'});+ const r = await fetch('/music/lyrics', {method: 'POST', body: fd});+ const data = await r.json();+ if (!r.ok || data.error) throw new Error(data.error || 'No lyrics came back');+ musicLyricsSet(data.lyrics);+ if (status) status.textContent = `Lyrics written in ${Math.round(data.elapsed_sec || 0)} s — edit anything, then Compose.`;+ } catch (e) {+ if (status) status.textContent = e.message || String(e);+ } finally {+ if (btn) { btn.disabled = false; btn.textContent = 'Write lyrics'; }+ }+}++// "Get the score": transcription only, then show it on the card.+async function musicTranscribe() {+ const src = (_el('musicSourceAudio') || {}).value || '';+ const status = _el('musicStatus');+ if (!src.trim()) { if (status) status.textContent = 'Pick the recording to read.'; return; }+ if (status) status.textContent = 'Queueing the transcription…';+ try {+ const fd = new URLSearchParams({path: src, task: (_el('musicCoverTask') || {}).value || 'melody-full'});+ const r = await fetch('/music/transcribe', {method: 'POST', body: fd});+ const data = await r.json();+ if (!r.ok || data.error) throw new Error(data.error || 'Could not queue');+ if (status) status.textContent = 'Listening… the score appears here when it is done.';+ _watchScoreJob(data.id);+ if (typeof poll === 'function') poll();+ } catch (e) { if (status) status.textContent = e.message || String(e); }+}++function _watchScoreJob(id) {+ const status = _el('musicStatus');+ const tick = async () => {+ try {+ const r = await fetch(`/music/score?job=${encodeURIComponent(id)}`);+ const d = await r.json();+ if (d.abc) {+ const card = _el('songCard');+ SONG = {path: d.path, abc: d.abc, title: d.title, style: '', lyrics: '', has_artifacts: false};+ card.hidden = false;+ _el('songTitle').textContent = d.title || 'Score';+ _el('songStyle').textContent = d.cover ? `read from ${String(d.cover.artifacts || '').split('/').pop() ? 'the recording' : 'the recording'} · ${d.cover.task}` : '';+ _el('songBadges').innerHTML = '<span class="song-badge">score</span>';+ _el('songLineage').innerHTML = '';+ for (const b of _el('songActions').querySelectorAll('button')) b.disabled = true;+ _renderScore(d.abc);+ _renderLyrics('');+ if (status) status.textContent = 'Score ready — it is on the card. Edit it and render, or copy the ABC.';+ return;+ }+ if (d.status === 'failed' || d.status === 'cancelled') { if (status) status.textContent = d.error || 'The transcription did not finish.'; return; }+ } catch (_) {}+ setTimeout(tick, 2500);+ };+ setTimeout(tick, 2500);+}++Object.assign(globalThis, {+ songCardRender, musicVariation, musicRestyleFromSong, musicCoverFromSong, musicOpenSong,+ musicSongAction,+ musicScoreEditToggle, musicScorePreview, musicRenderEditedScore, musicScoreCopy,+ musicTaskSet, musicTaskPick, musicWriteLyrics, musicTranscribe,+ musicLyricsRender, musicLyricsType, musicLyricsRetag, musicLyricsMove, musicLyricsRemove,+ musicLyricsAdd, musicLyricsSet, musicLyricsView, musicLyricsViewPick, musicLyricsRawSync,+ musicLyricsLock, musicLyricsRewrite, musicLyricsInit,+ musicModeSet, musicModePick, musicModeInit, musicSimpleActive, musicSimpleChanged,+ musicSimpleCompose,+});++// ===========================================================================+// THE LIBRARY — songs listed like songs, and a player that stays put.+//+// Studied from Suno and kept: a list, not a grid (a song has no thumbnail+// worth a grid cell); cover art on every row; title / style / duration at a+// glance; a play button and a ⋯ menu carrying every verb; families nested one+// level under their parent the way Suno nests versions; a persistent player+// bar with a real waveform. Not kept: their two-clips-per-generation default+// (a full song is minutes of GPU here — Re-roll the sound is the cheap second+// opinion and it is one click on every row).+// ===========================================================================++const _peaks = new Map(); // path -> Float32Array of peaks+let _barSong = null; // the row the bar is showing+let _barList = []; // the songs the bar can step through++function _mmss(sec) {+ sec = Math.max(0, Math.round(Number(sec) || 0));+ return `${Math.floor(sec / 60)}:${String(sec % 60).padStart(2, '0')}`;+}++// Cover art, deterministic from the song: two hues off a hash of the title and+// style, so a family shares a look and every song has one before an image is+// ever generated for it. (The image engine can paint a real one later; this is+// the fallback that must always exist.)+function _hash(s) { let h = 2166136261; for (const c of String(s)) { h ^= c.charCodeAt(0); h = Math.imul(h, 16777619); } return h >>> 0; }+function songCoverStyle(o) {+ const m = o.music || {};+ const h = _hash((m.title || o.name) + '|' + (m.style || ''));+ const h1 = h % 360, h2 = (h1 + 40 + (h >> 8) % 60) % 360;+ return `background: linear-gradient(135deg, hsl(${h1} 70% 52%), hsl(${h2} 75% 30%));`;+}+function _songTitle(o) {+ const m = o.music || {};+ return m.title || String(o.name || '').replace(/\.wav$/i, '').replace(/^music_\d{8}_\d{6}_/, '').replace(/_/g, ' ');+}+function _styleChips(style, n = 3) {+ return String(style || '').split(/,|·/).map(s => s.trim()).filter(Boolean).slice(0, n)+ .map(s => `<span class="song-chip">${_esc(s)}</span>`).join('');+}+function _kindBadge(m) {+ if (!m) return '';+ const k = m.variation ? ({take: 'take', sound: 're-roll', restyle: 'restyle'}[m.variation] || m.variation)+ : m.cover ? 'cover' : '';+ return k ? `<span class="song-badge">${_esc(k)}</span>` : '';+}++// One level of family: a song's takes sit under it, indented, in order.+function _familyOrder(songs) {+ const byPath = new Map(songs.map(o => [o.path, o]));+ const children = new Map();+ const roots = [];+ for (const o of songs) {+ const parent = o.music && o.music.parent;+ if (parent && byPath.has(parent)) {+ if (!children.has(parent)) children.set(parent, []);+ children.get(parent).push(o);+ } else roots.push(o);+ }+ // Every descendant is listed — a re-roll of a take is a grandchild and+ // used to vanish from the library. Indentation stays capped at one level.+ const out = [], seen = new Set();+ const walk = (o, depth) => {+ if (seen.has(o.path)) return;+ seen.add(o.path);+ out.push({o, depth: Math.min(depth, 1)});+ for (const c of (children.get(o.path) || [])) walk(c, depth + 1);+ };+ for (const r of roots) walk(r, 0);+ for (const o of songs) if (!seen.has(o.path)) walk(o, 0); // a cycle, or an orphan whose parent is filtered out+ return out;+}++function renderSongList(el, songs) {+ _barList = songs.slice();+ const rows = _familyOrder(songs).map(({o, depth}) => {+ const m = o.music || {};+ const playing = _barSong && _barSong.path === o.path && !_barAudio().paused;+ const attr = JSON.stringify(o.path).replace(/"/g, '"');+ return `<div class="song-row${o.path === activePath ? ' active' : ''}${depth ? ' child' : ''}" data-path="${_esc(o.path)}"+ onclick="selectOutput(${attr})" role="button" tabindex="0" onkeydown="if(event.key==='Enter')selectOutput(${attr})">+ <div class="song-cover" style="${songCoverStyle(o)}" aria-hidden="true">${depth ? '' : `<span>${_esc(_songTitle(o).slice(0, 1).toUpperCase())}</span>`}</div>+ <div class="song-main">+ <div class="song-row-title">${_esc(_songTitle(o))} ${_kindBadge(m)}${m.instrumental ? '<span class="song-badge muted">instrumental</span>' : ''}</div>+ <div class="song-row-sub">${_styleChips(m.style)}${m.has_score ? '<span class="song-chip score" title="Has sheet music">♪ score</span>' : ''}</div>+ </div>+ <div class="song-dur">${o.clip_sec ? _mmss(o.clip_sec) : ''}</div>+ <button type="button" class="song-play${playing ? ' on' : ''}" title="${playing ? 'Pause' : 'Play'}" aria-label="${playing ? 'Pause' : 'Play'}"+ onclick="event.stopPropagation(); musicBarToggle(${attr})">${playing ? _svgPause() : _svgPlay()}</button>+ <button type="button" class="song-more" title="More" aria-label="More actions"+ onclick="event.stopPropagation(); musicMenuOpen(event, ${attr})">⋯</button>+ </div>`;+ });+ el.classList.add('song-list');+ el.innerHTML = rows.join('');+}+function _svgPlay() { return '<svg width="14" height="14" viewBox="0 0 16 16" aria-hidden="true"><path d="M4 2.5 L13.5 8 L4 13.5 Z" fill="currentColor"/></svg>'; }+function _svgPause() { return '<svg width="14" height="14" viewBox="0 0 16 16" aria-hidden="true"><rect x="3" y="2.5" width="3.5" height="11" fill="currentColor"/><rect x="9.5" y="2.5" width="3.5" height="11" fill="currentColor"/></svg>'; }++// The hero for the player surface: a song is not a black rectangle with a+// stock control in it. Cover, title, style — playback lives in the bar.+function songHero(o) {+ const m = o.music || {};+ return `<div class="song-hero">+ <div class="song-hero-cover" style="${songCoverStyle(o)}"><span>${_esc(_songTitle(o).slice(0, 1).toUpperCase())}</span></div>+ <div class="song-hero-text">+ <div class="song-hero-title">${_esc(_songTitle(o))}</div>+ <div class="song-hero-style">${_esc(m.style || '')}</div>+ <div class="song-hero-meta">${o.clip_sec ? _mmss(o.clip_sec) : ''}${m.mode && m.mode !== 'off' ? ' · sheet music' : ''}${m.cover ? ' · cover' : ''}</div>+ <button type="button" class="primary song-hero-play" onclick="musicBarToggle(${JSON.stringify(o.path).replace(/"/g, '"')})">${_svgPlay()} Play</button>+ </div>+ </div>`;+}++// ---- the ⋯ menu ----------------------------------------------------------++function musicMenuOpen(ev, path) {+ const menu = _el('songMenu');+ if (!menu) return;+ const o = (typeof findOutputByPath === 'function') ? findOutputByPath(path) : null;+ const m = (o && o.music) || {};+ const attr = JSON.stringify(path).replace(/"/g, '"');+ const item = (label, sub, fn, disabled, why) =>+ `<button type="button" class="song-menu-item" ${disabled ? `disabled title="${_esc(why || '')}"` : ''} onclick="musicMenuClose(); ${fn}">${label}${sub ? `<span class="sub">${sub}</span>` : ''}</button>`;+ const noArt = !m.has_artifacts, noScore = !m.has_score;+ menu.innerHTML = [+ item('Play', '', `musicBarToggle(${attr})`),+ item('Open', 'score, lyrics, family', `selectOutput(${attr})`),+ '<div class="song-menu-sep"></div>',+ item('New take', 'same song, performed again', `musicVariation('take', ${attr})`, noArt, 'This song kept no artifacts'),+ item('Re-roll the sound', 'same performance, new recording · fast', `musicVariation('sound', ${attr})`, noArt, 'This song kept no artifacts'),+ item('New style on this score', "the composer's style + lyrics", `musicSongAction(${attr}, 'restyle')`, noScore, 'No score on this song'),+ item('Cover it', 'read the tune, write it fresh', `musicSongAction(${attr}, 'cover')`),+ item('Edit the score', '', `musicSongAction(${attr}, 'edit')`, noScore, 'No score on this song'),+ '<div class="song-menu-sep"></div>',+ item('Show in Finder', 'the outputs folder', `if (typeof openOutputsFolder === 'function') openOutputsFolder()`),+ item('Delete', '', `if (typeof deleteOutput === 'function') deleteOutput(${attr})`),+ ].join('');+ menu.hidden = false;+ const r = ev.currentTarget.getBoundingClientRect();+ const w = 260;+ menu.style.left = `${Math.max(8, Math.min(window.innerWidth - w - 8, r.right - w))}px`;+ menu.style.top = `${Math.min(window.innerHeight - menu.offsetHeight - 8, r.bottom + 6)}px`;+ setTimeout(() => document.addEventListener('click', musicMenuClose, {once: true}), 0);+}+function musicMenuClose() { const menu = _el('songMenu'); if (menu) menu.hidden = true; }++// ---- the player bar ------------------------------------------------------++function _barAudio() { return _el('musicBarAudio'); }++function musicBarShow(o, {play = false} = {}) {+ const bar = _el('musicBar');+ if (!bar || !o) return;+ const a = _barAudio();+ const changed = !_barSong || _barSong.path !== o.path;+ _barSong = o;+ bar.hidden = false;+ document.body.classList.add('music-bar-on');+ _el('musicBarCover').setAttribute('style', songCoverStyle(o));+ _el('musicBarTitle').textContent = _songTitle(o);+ _el('musicBarStyle').textContent = (o.music || {}).style || '';+ if (changed) {+ a.src = o.url;+ a.load();+ _el('musicBarTime').textContent = `0:00 / ${o.clip_sec ? _mmss(o.clip_sec) : '–:––'}`;+ _drawWave(o, 0);+ _loadPeaks(o).then(() => { if (_barSong && _barSong.path === o.path) _drawWave(o, a.currentTime / (a.duration || 1)); });+ }+ if (play) a.play().catch(() => {});+ _barSyncButtons();+}+function musicBarToggle(path) {+ const o = (typeof findOutputByPath === 'function') ? findOutputByPath(path) : null;+ if (!o) return;+ const a = _barAudio();+ if (_barSong && _barSong.path === path) { if (a.paused) a.play().catch(() => {}); else a.pause(); }+ else musicBarShow(o, {play: true});+ _barSyncButtons();+}+// The bar's own play/pause. Module state is private to this file, so an+// inline handler cannot read `_barSong` — it has to be a published function.+// (That was the pause button that "did not work": the handler threw.)+function musicBarTogglePlay() {+ if (!_barSong) return;+ const a = _barAudio();+ if (a.paused) a.play().catch(() => {}); else a.pause();+ _barSyncButtons();+}+function musicBarStep(dir) {+ if (!_barSong || !_barList.length) return;+ const i = _barList.findIndex(o => o.path === _barSong.path);+ const next = _barList[(i + dir + _barList.length) % _barList.length];+ if (next) { musicBarShow(next, {play: true}); if (typeof selectOutput === 'function') selectOutput(next.path); }+}+function musicBarSeek(ev) {+ const a = _barAudio();+ if (!a.duration) return;+ const r = ev.currentTarget.getBoundingClientRect();+ a.currentTime = Math.max(0, Math.min(1, (ev.clientX - r.left) / r.width)) * a.duration;+}+function _barSyncButtons() {+ const a = _barAudio();+ const playing = a && !a.paused;+ const btn = _el('musicBarPlay');+ if (btn) { btn.innerHTML = playing ? _svgPause() : _svgPlay(); btn.title = playing ? 'Pause' : 'Play'; }+ document.querySelectorAll('.song-row .song-play').forEach(b => {+ const row = b.closest('.song-row');+ const on = playing && _barSong && row && row.dataset.path === _barSong.path;+ b.classList.toggle('on', on);+ b.innerHTML = on ? _svgPause() : _svgPlay();+ });+}++// Peaks: decode once per song, 480 buckets, cached. Drawn as mirrored bars —+// the played part in the accent, the rest muted. Click to seek.+async function _loadPeaks(o) {+ if (_peaks.has(o.path)) return _peaks.get(o.path);+ try {+ const buf = await (await fetch(o.url)).arrayBuffer();+ const ctx = new (window.AudioContext || window.webkitAudioContext)();+ const audio = await ctx.decodeAudioData(buf);+ const ch = audio.getChannelData(0);+ const n = 480, step = Math.max(1, Math.floor(ch.length / n));+ const peaks = new Float32Array(n);+ for (let i = 0; i < n; i++) {+ let m = 0; const s = i * step, e = Math.min(ch.length, s + step);+ for (let j = s; j < e; j += 4) { const v = Math.abs(ch[j]); if (v > m) m = v; }+ peaks[i] = m;+ }+ ctx.close && ctx.close();+ _peaks.set(o.path, peaks);+ return peaks;+ } catch (_) { return null; }+}+function _drawWave(o, frac) {+ const c = _el('musicBarWave');+ if (!c) return;+ const peaks = _peaks.get(o.path);+ const dpr = window.devicePixelRatio || 1;+ const W = c.clientWidth || 300, H = c.clientHeight || 36;+ if (c.width !== Math.round(W * dpr)) { c.width = Math.round(W * dpr); c.height = Math.round(H * dpr); }+ const g = c.getContext('2d');+ g.setTransform(dpr, 0, 0, dpr, 0, 0);+ g.clearRect(0, 0, W, H);+ const cs = getComputedStyle(document.documentElement);+ const accent = cs.getPropertyValue('--accent-bright').trim() || '#58a6ff';+ const muted = cs.getPropertyValue('--border-strong').trim() || '#3d477a';+ const n = 160, bw = W / n;+ for (let i = 0; i < n; i++) {+ let v = 0.15;+ if (peaks) { const s = Math.floor(i * peaks.length / n), e = Math.floor((i + 1) * peaks.length / n); for (let j = s; j < e; j++) v = Math.max(v, peaks[j]); }+ const h = Math.max(2, v * (H - 4));+ g.fillStyle = (i / n) <= frac ? accent : muted;+ g.fillRect(i * bw + bw * 0.2, (H - h) / 2, bw * 0.6, h);+ }+}+function musicBarInit() {+ const a = _barAudio();+ if (!a || a.dataset.wired) return;+ a.dataset.wired = '1';+ a.addEventListener('timeupdate', () => {+ if (!_barSong) return;+ _el('musicBarTime').textContent = `${_mmss(a.currentTime)} / ${_mmss(a.duration || _barSong.clip_sec || 0)}`;+ _drawWave(_barSong, a.duration ? a.currentTime / a.duration : 0);+ });+ a.addEventListener('play', _barSyncButtons);+ a.addEventListener('pause', _barSyncButtons);+ a.addEventListener('ended', () => { _barSyncButtons(); });+ window.addEventListener('resize', () => { if (_barSong) _drawWave(_barSong, a.duration ? a.currentTime / a.duration : 0); });+}+function musicStudioBoot() { musicBarInit(); musicLyricsInit(); musicModeInit(); }+document.addEventListener('DOMContentLoaded', musicStudioBoot);+if (document.readyState !== 'loading') musicStudioBoot();+++// ===========================================================================+// MUSIC VIDEO — the song, the pictures, and one line about the look+// ===========================================================================+// The pane is a brief, not a render form: nothing here queues anything. It+// posts to /music/video/plan, which writes an ORDINARY storyboard board, and+// then it opens that board. Every decision about what the shots are lives in+// music_video.py on the server; this file collects four fields and paints+// what came back.+//+// WHY THE CAST IS ITS OWN LITTLE LIST. The `.picker` component is one image+// per slot — it owns a hidden input, a preview and a clear button — and a+// music video wants five or ten pictures each carrying a ROLE and maybe a+// note. So the drop tile is the picker's (same class, same look, same+// `/upload` route and the same `image` field name), and the thumbnails below+// it are this module's own row list. Nothing about the upload path is new.++const MV = { song: null, songName: '', songSeconds: null, cast: [], busy: false, boardId: '' };++function mvSay(msg) { const el = _el('mvStatus'); if (el) el.textContent = msg || ''; }++function mvInit() {+ const drop = _el('mvImagesDrop');+ const file = _el('mvImagesFile');+ const slot = _el('mvSongSlot');+ const song = _el('mvSongInput');+ if (drop && file && !drop.dataset.wired) {+ drop.dataset.wired = '1';+ drop.addEventListener('click', () => file.click());+ drop.addEventListener('dragover', (e) => { e.preventDefault(); drop.classList.add('dragover'); });+ drop.addEventListener('dragleave', () => drop.classList.remove('dragover'));+ drop.addEventListener('drop', (e) => {+ e.preventDefault(); drop.classList.remove('dragover');+ mvAddPictures(e.dataTransfer && e.dataTransfer.files);+ });+ file.addEventListener('change', () => { mvAddPictures(file.files); file.value = ''; });+ }+ if (slot && song && !slot.dataset.wired) {+ slot.dataset.wired = '1';+ slot.addEventListener('click', () => song.click());+ slot.addEventListener('dragover', (e) => { e.preventDefault(); slot.classList.add('drop-active'); });+ slot.addEventListener('dragleave', () => slot.classList.remove('drop-active'));+ slot.addEventListener('drop', (e) => {+ e.preventDefault(); slot.classList.remove('drop-active');+ const f = e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files[0];+ if (f) mvUploadSong(f);+ });+ song.addEventListener('change', () => { if (song.files[0]) mvUploadSong(song.files[0]); });+ }+ mvRenderSong();+ mvRenderCast();+ mvFillLibrary();+}++// The library select is filled from the gallery the panel already polls, so+// it needs no endpoint of its own and it can never list a song the outputs+// column does not show.+function mvFillLibrary() {+ const sel = _el('mvSongLibrary');+ if (!sel) return;+ const songs = (typeof currentOutputs !== 'undefined' && currentOutputs || [])+ .filter(o => o && o.kind === 'audio' && o.engine === 'music');+ const keep = sel.value;+ sel.innerHTML = songs.length+ ? '<option value="">Pick one…</option>' + songs.map(o => {+ const m = o.music || {};+ const label = m.title || _songNameFromFile(o.name) || o.name;+ return `<option value="${_esc(o.path)}">${_esc(label)}</option>`;+ }).join('')+ : '<option value="">Nothing composed yet</option>';+ if (keep && songs.some(o => o.path === keep)) sel.value = keep;+}++function mvPickFromLibrary(path) {+ if (!path) return;+ const o = (typeof currentOutputs !== 'undefined' && currentOutputs || [])+ .find(x => x && x.path === path);+ MV.song = path;+ MV.songName = (o && ((o.music || {}).title || _songNameFromFile(o.name))) || path.split('/').pop();+ MV.songSeconds = (o && (o.clip_sec != null ? Number(o.clip_sec) : null));+ mvRenderSong();+ mvSay('');+}++async function mvUploadSong(file) {+ mvSay(`Uploading ${file.name}…`);+ try {+ const fd = new FormData();+ fd.append('audio', file); // /upload takes image or audio+ const r = await fetch('/upload', { method: 'POST', body: fd });+ const data = await r.json();+ if (!r.ok || data.error) throw new Error(data.error || ('HTTP ' + r.status));+ MV.song = data.path;+ MV.songName = file.name;+ MV.songSeconds = (data.duration_sec != null) ? Number(data.duration_sec) : null;+ const sel = _el('mvSongLibrary'); if (sel) sel.value = '';+ mvRenderSong();+ mvSay('');+ } catch (e) {+ mvSay('Could not read that song: ' + (e.message || e));+ }+}++function mvClearSong() {+ MV.song = null; MV.songName = ''; MV.songSeconds = null;+ const sel = _el('mvSongLibrary'); if (sel) sel.value = '';+ mvRenderSong();+}++function mvRenderSong() {+ const slot = _el('mvSongSlot');+ if (!slot) return;+ if (!MV.song) {+ slot.innerHTML = '<span class="ref-tag">Song</span>'+ + '<div class="hint" style="padding:24px 12px;text-align:center;color:var(--muted);font-size:12px;">'+ + 'Drop a WAV / MP3 / M4A / FLAC here, or click to pick a file.</div>';+ return;+ }+ const dur = (MV.songSeconds != null && isFinite(MV.songSeconds))+ ? ' · ' + _mmss(MV.songSeconds) : '';+ slot.innerHTML = '<span class="ref-tag">Song</span>'+ + '<div style="padding:18px 12px;text-align:center;font-size:12px;color:var(--text);overflow:hidden;text-overflow:ellipsis;">'+ + '<svg class="ph" aria-hidden="true" style="width:18px;height:18px;vertical-align:-3px;margin-right:6px;"><use href="#ph-music-notes"/></svg>'+ + _esc(MV.songName || 'song') + dur+ + '<div class="hint" style="margin-top:8px;">'+ + '<a href="#" onclick="event.stopPropagation();mvClearSong();return false;">Remove</a>'+ + '</div></div>';+}++async function mvAddPictures(files) {+ const list = Array.from(files || []);+ if (!list.length) return;+ mvSay(`Uploading ${list.length} picture${list.length > 1 ? 's' : ''}…`);+ for (const f of list) {+ try {+ const fd = new FormData();+ fd.append('image', f);+ const r = await fetch('/upload', { method: 'POST', body: fd });+ const data = await r.json();+ if (!r.ok || data.error) throw new Error(data.error || ('HTTP ' + r.status));+ // The FIRST picture is the singer unless the user says otherwise: a cast+ // with no face plans as B-roll only, and arriving at that by default+ // would read as the feature not working.+ MV.cast.push({ path: data.path, name: f.name,+ role: MV.cast.length === 0 ? 'singer' : 'room', prompt: '' });+ } catch (e) {+ mvSay(`Could not add ${f.name}: ` + (e.message || e));+ mvRenderCast();+ return;+ }+ }+ mvSay('');+ mvRenderCast();+}++function mvSetRole(i, role) {+ if (!MV.cast[i]) return;+ MV.cast[i].role = role;+ mvRenderCast();+}++function mvSetPrompt(i, text) {+ if (MV.cast[i]) MV.cast[i].prompt = String(text || '');+}++function mvRemovePicture(i) {+ MV.cast.splice(i, 1);+ mvRenderCast();+}++const MV_ROLES = [+ ['singer', 'Singer', 'Filmed singing, in sync with the song'],+ ['instrument', 'Instrument', 'B-roll — hands, keys, strings'],+ ['room', 'Room', 'B-roll — the wide, the lights, the audience'],+];++function mvRenderCast() {+ const box = _el('mvCast');+ if (!box) return;+ box.innerHTML = MV.cast.map((im, i) => `+ <div class="mv-pic">+ <img class="mv-pic-thumb" src="/image?path=${encodeURIComponent(im.path)}&w=160" alt="">+ <div class="mv-pic-body">+ <div class="mv-pic-name" title="${_esc(im.path)}">${_esc(im.name || im.path.split('/').pop())}</div>+ <div class="mv-roles" role="group" aria-label="What this picture is for">+ ${MV_ROLES.map(([key, label, tip]) => `+ <button type="button" class="pill-btn${im.role === key ? ' active' : ''}"+ data-i="${i}" data-role="${key}" title="${_esc(tip)}">${label}</button>`).join('')}+ </div>+ <input type="text" class="mv-pic-prompt" data-i="${i}"+ placeholder="Optional — what happens in this shot"+ value="${_esc(im.prompt || '')}">+ </div>+ <button type="button" class="mv-pic-x" data-i="${i}" title="Take this picture out">+ <svg class="ph" aria-hidden="true"><use href="#ph-x-bold"/></svg>+ </button>+ </div>`).join('');+ // Listeners, not inline onclick: generated markup resolves inline handlers+ // through the global scope, which is the v4.9.0 regression class the webapp+ // lint exists to catch.+ box.querySelectorAll('.mv-roles button').forEach(b =>+ b.addEventListener('click', () => mvSetRole(+b.dataset.i, b.dataset.role)));+ box.querySelectorAll('.mv-pic-prompt').forEach(inp =>+ inp.addEventListener('input', () => mvSetPrompt(+inp.dataset.i, inp.value)));+ box.querySelectorAll('.mv-pic-x').forEach(b =>+ b.addEventListener('click', () => mvRemovePicture(+b.dataset.i)));+ const chip = _el('mvSummary');+ if (chip) {+ const n = MV.cast.length;+ const faces = MV.cast.filter(c => c.role === 'singer').length;+ chip.textContent = n ? `${n} picture${n > 1 ? 's' : ''} · ${faces} singer${faces === 1 ? '' : 's'}` : '';+ }+}++async function mvPlan() {+ if (MV.busy) return;+ if (!MV.song) { mvSay('Pick a song first.'); return; }+ if (!MV.cast.length) { mvSay('Drop at least one picture.'); return; }+ const btn = _el('mvPlanBtn');+ MV.busy = true;+ if (btn) { btn.disabled = true; btn.textContent = 'Reading the song…'; }+ mvSay('Reading the beat and writing the shot list…');+ try {+ const fd = new URLSearchParams();+ fd.set('song', MV.song);+ fd.set('images', JSON.stringify(MV.cast.map(c => ({+ path: c.path, role: c.role, prompt: c.prompt || '' }))));+ fd.set('style', (_el('mvStyle') || {}).value || '');+ fd.set('title', MV.songName || 'Music video');+ const r = await fetch('/music/video/plan', { method: 'POST', body: fd });+ const data = await r.json();+ if (!r.ok || data.error) throw new Error(data.error || ('HTTP ' + r.status));+ MV.boardId = data.board_id;+ mvSay(data.summary + (data.notes && data.notes.length ? ' — ' + data.notes.join(' ') : ''));+ const chip = _el('mvSummary'); if (chip) chip.textContent = data.summary;+ if (typeof phosToast === 'function') phosToast(data.summary, { kind: 'success' });+ // AND SHOW IT. A shot list nobody can see is a toast that fades; the plan+ // ends where the work continues, which is the board.+ if (typeof workflowSwitch === 'function') workflowSwitch('storyboard');+ if (typeof sbOpen === 'function') await sbOpen(data.board_id);+ } catch (e) {+ mvSay('Could not plan that video: ' + (e.message || e));+ } finally {+ MV.busy = false;+ if (btn) { btn.disabled = false; btn.textContent = 'Plan the video'; }+ }+}++Object.assign(globalThis, {+ renderSongList, songHero, songCoverStyle, musicMenuOpen, musicMenuClose,+ musicBarShow, musicBarToggle, musicBarTogglePlay, musicBarStep, musicBarSeek, musicBarInit,+ mvInit, mvPlan, mvPickFromLibrary, mvClearSong, mvFillLibrary,+});diff --git a/webapp/js/queue.js b/webapp/js/queue.jsindex da8aefe..891e4a4 100644--- a/webapp/js/queue.js+++ b/webapp/js/queue.js@@ -149,6 +149,8 @@ function h3FinishFieldsFromSidecar(p, tierKey) {.map(l => ({ path: String(l.path),strength: (typeof l.strength === 'number') ? l.strength : 1.0 })): [],+ // Which meaning of "strength" the loras above were written in (H3-03).+ h3_lora_scale_v: Number(p.h3_lora_scale_v) || 0,h3_orientation: (p.h3_orientation === 'portrait') ? 'portrait' : 'landscape',h3_lora_slot: (p.h3_lora_slot === 'user') ? 'user' : 'turbo',// Turbo carries over: a draft judged with the 4-step sampler should be@@ -305,7 +307,7 @@ async function h3FinishActive() {if (fields.h3_upscale && typeof setH3Upscale === 'function') setH3Upscale(fields.h3_upscale);// The source's adapters, not whatever the picker holds now (an empty list// clears it), and its framing BEFORE the shape stamps geometry.- _restoreLoraPicker(fields.loras);+ _restoreLoraPicker(fields.loras, fields.h3_lora_scale_v);if (typeof setH3Orientation === 'function') setH3Orientation(fields.h3_orientation);if (typeof setH3Steps === 'function') setH3Steps(fields.h3_steps);// Turbo before the shape: setH3Turbo forces the Steps pills back to 'auto',@@ -2993,9 +2995,28 @@ function _fmtRenderTime(s) {return `rendered ${Math.floor(s / 3600)} h ${Math.round((s % 3600) / 60)} m`;}+// A song's card reads like a song, not a file: the title it was given (or the+// name minus the timestamp), and a chip for what it is — a new take, a+// re-recording, a restyle, a cover. Everything else keeps its filename.+function _songCardName(o) {+ const m = o && o.music;+ if (!m) return escapeHtml(o.name);+ const title = m.title || o.name.replace(/\.wav$/i, '').replace(/^music_\d{8}_\d{6}_/, '').replace(/_/g, ' ');+ const chip = m.variation ? ({take: 'take', sound: 're-roll', restyle: 'restyle'}[m.variation] || m.variation)+ : m.cover ? 'cover' : '';+ return `${escapeHtml(title)}${chip ? ` <span class="song-badge">${chip}</span>` : ''}`;+}function renderCarousel() {const el = document.getElementById('carousel');const visible = filteredMainOutputs();+ // Music Studio: songs are listed like songs — a list with cover art, a+ // play button and a ⋯ menu — not a grid of thumbnails there is nothing to+ // thumbnail. Any other filter gets the grid it always had.+ el.classList.toggle('song-list', mainOutputsFilter === 'audio');+ if (mainOutputsFilter === 'audio' && visible.length && typeof renderSongList === 'function') {+ renderSongList(el, visible);+ return;+ }if (!visible.length) {const q = (typeof outputsQueryText === 'function') ? outputsQueryText() : '';const msg = q ? ('No matches for \u201c' + escapeHtml(q) + '\u201d.')@@ -3100,13 +3121,13 @@ function renderCarousel() {<div class="card-chrome">${remakeChip}${animateChip}- ${isAudio ? `<button class="card-action card-action-photo" type="button" title="Load this track into Audio → Video (does not auto-submit)" onclick="event.stopPropagation();useTrackInA2V(${pathAttr})">Drive video</button>` : ''}+ ${isAudio ? `<button class="card-action card-action-photo" type="button" title="Load this track into Music video (does not auto-submit)" onclick="event.stopPropagation();useTrackInA2V(${pathAttr})">Music video</button>` : ''}<button class="card-action card-action-danger" type="button" title="Move this file to the Trash — asks first"onclick="event.stopPropagation(); deleteOutput(${pathAttr})"><svg class="ph" aria-hidden="true"><use href="#ph-trash-simple"/></svg></button></div></div><div class="info">- <div class="name" title="${escapeHtml(o.name)}">${escapeHtml(o.name)}</div>+ <div class="name" title="${escapeHtml(o.name)}">${_songCardName(o)}</div><div class="sub" title="Render time · file size">${o.sb ? `<span class="badge sb-badge" title="Shot ${o.sb.n} of a storyboard — click to open it"onclick="event.stopPropagation(); sbOpenFromClip('${escapeHtml(o.sb.id)}')">S${String(o.sb.n).padStart(2,'0')}</span> · ` : ''}${_outputDurationLabel(o)} · ${o.size_mb.toFixed(1)} MB@@ -3285,7 +3306,19 @@ function selectOutput(path, options) {// Photo viewer is a static <img> — no controls, no autoplay (would// be a no-op on an image element anyway). Video viewer keeps the// existing controls + autoplay behaviour.- if (isAudio) {+ // Music Studio: the Song card under the player fills for a song and+ // clears for anything else. Runs for every selection so a click from a+ // song to a clip never leaves the previous song's score on screen.+ if (typeof songCardRender === 'function') songCardRender(o);+ if (isAudio && o && o.engine === 'music' && typeof songHero === 'function') {+ // A song is not a black rectangle with a stock control in it: the+ // surface shows the cover, the title and the style; playback is the+ // bar's, which stays put while you browse.+ // NO AUTOPLAY FOR SONGS, ever. Selecting a song is looking at it — the+ // score, the words, the family. Sound starts on a play button and+ // nowhere else, and it keeps going while you browse other songs.+ wrap.innerHTML = songHero(o);+ } else if (isAudio) {wrap.innerHTML = `<audio class="train-voice-audio" controls preload="metadata"${autoplay ? ' autoplay' : ''} src="${escapeHtml(playerSrc)}"></audio>`;} else if (isPhoto) {wrap.innerHTML = `<img src="${escapeHtml(playerSrc)}" alt="${o ? escapeHtml(o.name) : ''}">`;@@ -3548,8 +3581,8 @@ async function animateActive() {}}-async function hide(path) { await fetch('/output/hide?path='+encodeURIComponent(path),{method:'POST'}); currentOutputs = []; poll(); }-async function unhide(path) { await fetch('/output/show?path='+encodeURIComponent(path),{method:'POST'}); currentOutputs = []; poll(); }+async function hide(path) { await fetch('/output/hide?path='+encodeURIComponent(path),{method:'POST'}); outputsCacheMutated([path]); currentOutputs = []; poll(); }+async function unhide(path) { await fetch('/output/show?path='+encodeURIComponent(path),{method:'POST'}); outputsCacheMutated([]); currentOutputs = []; poll(); }async function deleteOutput(path) {// Per-card × button. Moves the media (and any sibling sidecar JSON)@@ -3579,6 +3612,8 @@ async function deleteOutput(path) {closeExpandLightbox();}}+ // The Show-all cache too, or filteredMainOutputs() resurrects it (UI-06).+ outputsCacheMutated([path]);currentOutputs = [];poll();phosToast('Moved to Trash · ' + base, { kind: 'success' });@@ -3688,8 +3723,15 @@ function setUpscalePreset(btn) {// Put a saved {path, strength} list into the LoRA picker (Load Params and// Finish share this). Re-decorated with name + trigger words from// _knownUserLoras so the chips render nicely.-function _restoreLoraPicker(list) {+//+// `scaleV` is the SOURCE recipe's h3_lora_scale_v (absent on sidecars written+// before the stamp existed = 0). Each restored strength keeps it, so the+// server can migrate an old automatic strength instead of reading it as a+// deliberate modern pick (Codex H3-03); setLoraStrength drops it on an edit.+function _restoreLoraPicker(list, scaleV) {if (!Array.isArray(list)) return;+ const sv = (scaleV === undefined || scaleV === null) ? null+ : (Number.isFinite(Number(scaleV)) ? Number(scaleV) : 0);_activeLoras = list.map(l => {const path = l && l.path;const strength = (l && typeof l.strength === 'number') ? l.strength : 1.0;@@ -3699,6 +3741,7 @@ function _restoreLoraPicker(list) {return {path,strength,+ ...(sv === null ? {} : { scale_v: sv }),name: meta.name || (path ? path.split('/').pop() : 'LoRA'),trigger_words: meta.trigger_words || [],compatible_modes: meta.compatible_modes || ['unknown'],@@ -3741,6 +3784,32 @@ async function loadParams() {}return;}+ // A One Shot reopens as One Shot, before any other branch reads `p` (a+ // character One Shot must not land in the Characters tab as one clip).+ // Takes rendered before 4.16 wrote the LAST PART's sidecar with the take+ // block laid on top: `params` there is a short i2v of the final beats on a+ // handoff frame, and a speech-handoff take had no `params` at all. The+ // top-level take block and prompt are the take's own, so they win there.+ if (data && data.take && data.take.seconds && !(p && p.take && p.take.seconds)+ && typeof oneshotOpenFromParams === 'function') {+ oneshotOpenFromParams(Object.assign({}, p || {}, {+ take: data.take, engine: data.engine || (p && p.engine),+ prompt: data.prompt || '', image: data.image || '',+ }));+ return;+ }+ if (p && p.take && p.take.seconds && typeof oneshotOpenFromParams === 'function') {+ oneshotOpenFromParams(p);+ return;+ }+ if (!p) return;+ // An Audio → Video clip reopens in the Audio tab with its track (LTX-04);+ // the video form below has no field that a2v reads.+ if (p.mode === 'a2v' && typeof a2vLoadParams === 'function') {+ a2vLoadParams(p);+ if (Array.isArray(p.loras)) _restoreLoraPicker(p.loras);+ return;+ }// If this clip came from the Characters tab, restore the Characters// compose state instead of dumping the user into Manual. The sidecar// carries the source flag + the original compose chips verbatim@@ -3839,7 +3908,23 @@ async function loadParams() {if (typeof setI2vRefMode === 'function') {try { setI2vRefMode(p.i2v_reference_mode || 'anchor'); } catch (e) {}}- if (p.temporal_mode) setTemporalMode(p.temporal_mode);+ // SLIDING WINDOWS ARE STORED AS long_mode (LTX-05). make_job turns the+ // form's temporal_mode=windows into long_mode=windows + temporal_mode=native,+ // so restoring temporal_mode alone reopened a windowed clip as Native and+ // dropped its per-window prompts and invariants — the next Generate asked+ // for the whole length in one pass. The window text is always written, so+ // a native clip clears whatever an earlier windowed one left in the box.+ const _winText = document.getElementById('window_prompts_text');+ const _winInv = document.getElementById('window_invariants');+ const _windowed = p.long_mode === 'windows';+ if (_winText) {+ _winText.value = (_windowed && Array.isArray(p.window_prompts))+ ? p.window_prompts.map(x => String(x || '')).join('\n') : '';+ }+ if (_winInv) _winInv.value = _windowed ? String(p.window_invariants || '') : '';+ if (typeof windowPromptsInput === 'function') windowPromptsInput();+ if (_windowed) setTemporalMode('windows');+ else if (p.temporal_mode) setTemporalMode(p.temporal_mode);if (p.upscale) setUpscale(p.upscale);if (p.upscale_method) setUpscaleMethod(p.upscale_method);document.getElementById('prompt').value = p.prompt || '';@@ -4044,7 +4129,9 @@ async function loadParams() {// without fusion (no face/style transfer). Wire shape on the sidecar is// a list of {path, strength}; we re-decorate with `name` + `trigger_words`// from _knownUserLoras when available so the chip renders nicely.- if (lorasForPicker) _restoreLoraPicker(lorasForPicker);+ // An H3 recipe carries its strength meaning (H3-03); an LTX one has none.+ if (lorasForPicker) _restoreLoraPicker(lorasForPicker,+ (p.engine === 'h3') ? (Number(p.h3_lora_scale_v) || 0) : undefined);// ---- Engine + engine-specific settings ----------------------------------// Params restored geometry and prompt but NOT the engine, so loading an LTXdiff --git a/webapp/js/storyboard.js b/webapp/js/storyboard.jsindex 540f50d..5cf5904 100644--- a/webapp/js/storyboard.js+++ b/webapp/js/storyboard.js@@ -1948,9 +1948,47 @@ async function sbFilmLoad() {sbFilmPaint();sbRailPaint();}+// A board planned in Music video carries the song it was planned against, and+// that is the only thing that makes this button meaningful — so it is shown+// off the board itself rather than off anything this screen remembers.+function sbMusicVideoBlock() {+ const board = ((SB.payload || {}).board) || {};+ const mv = board.music_video;+ return (mv && typeof mv === 'object' && mv.song) ? mv : null;+}++// Join the shots and lay the song under them, unbroken. The lip-sync survives+// because each singing shot was rendered against its own `audio_start_time`+// segment of this very file — the route's own docstring has the rest, and the+// auto-editor is deliberately off there.+async function sbFilmWithTheSong() {+ const mv = sbMusicVideoBlock();+ if (!mv) return;+ const btn = sbEl('sbMusicFilmBtn');+ if (btn && btn.dataset.busy === '1') return;+ const prev = btn ? btn.textContent : '';+ if (btn) { btn.dataset.busy = '1'; btn.disabled = true; btn.textContent = 'Assembling…'; }+ const fd = new URLSearchParams(); fd.set('board_id', SB.id);+ let r;+ try { r = await (await fetch('/music/video/film', { method: 'POST', body: fd })).json(); }+ catch (e) { r = { ok: false, error: String(e) }; }+ finally { if (btn) { btn.dataset.busy = ''; btn.disabled = false; btn.textContent = prev; } }+ if (!r.ok) { phosToast(r.error || 'The film could not be assembled.', { kind: 'danger' }); return; }+ if (r.film_name) {+ phosToast(`${r.film_name} — ${Math.round(r.film_duration || 0)} s with the song under it`,+ { kind: 'success', duration: 8000 });+ sbFilmOpen({ focus: r.film_name });+ } else {+ phosToast(`The clips and the shot list are in ${r.dir}, but the film could `+ + `not be assembled: ${r.film_error || 'unknown reason'}`, { duration: 9000 });+ }+}+function sbFilmPaint() {const body = sbEl('sbFilmBody');const status = sbEl('sbFilmStatus');+ const songBtn = sbEl('sbMusicFilmBtn');+ if (songBtn) songBtn.hidden = !sbMusicVideoBlock();if (!body) return;const film = sbFilmPick(SB.films, SB.filmOpen);if (!film) {@@ -2335,6 +2373,7 @@ Object.assign(globalThis, {sbSetStage, sbRenderPlan, sbRenderRemaining, sbAddShot,sbTitleSave, sbRenderDrafts, sbFinish, sbRewrite,sbStopShot, sbStopFilm, sbExport, sbFilmOpen,+ sbMusicVideoBlock, sbFilmWithTheSong,sbFilmPaint, sbBoardChip, sbRowAction, sbAddActiveToBoard,sbOpenFromClip, sbPollHook,// inline-handler targets: generated markup resolves these through thediff --git a/webapp/style/panel.css b/webapp/style/panel.cssindex 1d7b95d..5698911 100644--- a/webapp/style/panel.css+++ b/webapp/style/panel.css@@ -1643,6 +1643,27 @@/* The draft's name yields with the title now that the View group sharesthe header: it ellipsises past 200px instead of taking the title's room. */.sbe-head .ghost-btn.sbe-draftchip { flex: 0 1 auto; min-width: 0; max-width: 220px; }+ /* THE FILM SWITCHER. The name is still prose — quiet until hovered, and+ the item in the row that yields first — but it is a control now. */+ .sbe-head .ghost-btn.sbe-titlebtn {+ flex: 0 1 auto; min-width: 0; max-width: 360px; gap: 6px;+ display: inline-flex; align-items: center;+ background: transparent; border-color: transparent; padding-inline: 6px;+ }+ .sbe-head .ghost-btn.sbe-titlebtn:hover {+ background: var(--panel-2); border-color: var(--border);+ }+ .sbe-films { min-width: 260px; }+ .sbe-films-list {+ display: flex; flex-direction: column; gap: 4px;+ max-height: min(60vh, 420px); overflow-y: auto;+ }+ .sbe-films-list .ghost-btn { justify-content: space-between; gap: 10px; }+ .sbe-films-list .ghost-btn .sub { color: var(--muted); flex: 0 0 auto; }+ .sbe-films-list .ghost-btn .name {+ min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;+ }+ .sbe-films-list .ghost-btn.is-current { border-color: var(--accent); }.sbe-head .sbe-draftchip #sbeDraftName { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }.sbe-car { color: var(--muted); font-size: var(--fs-2xs); }.sbe-split { display: inline-flex; }@@ -10826,13 +10847,7 @@ body[data-workflow="oneshot"] #audioSectionTab { display: none !important; }/* Audio's two panes use the existing composer/strip grammar. */#audioModeGroup[hidden], #musicComposePane[hidden], #audioDrivePane[hidden],#musicInstallModal[hidden] { display: none !important; }-#musicComposePane .composer-card > label { display: block; margin: 12px 14px 4px; }-#musicComposePane .composer-card > .hint { margin: 4px 14px 12px; }#musicLyrics:disabled { opacity: .45; }-#musicComposePane .quick-settings { display: block; }-#musicComposePane .quick-settings > .hint { margin: 6px 0 14px; }-#musicComposePane .range-strip { margin-top: 16px; }-#musicHint { margin-top: 10px; }.music-card-player { width: calc(100% - 34px); margin-left: 4px; min-width: 0; position: relative; z-index: 1; }/* The player sits at the TOP of the thumb: the card's hover chrome slides upover the bottom edge and would otherwise cover the play button. */@@ -10844,8 +10859,10 @@ body[data-workflow="oneshot"] #audioSectionTab { display: none !important; }pressing it opens the install card. */#musicInstallPanel[hidden] { display: none !important; }.music-install-panel { padding: 14px 16px; border-color: rgba(177,74,255,0.42); }-#musicComposePane.music-locked > .composer-card:not(.music-install-panel),-#musicComposePane.music-locked > .quick-settings,+#musicComposePane.music-locked .composer-card:not(.music-install-panel),+#musicComposePane.music-locked .quick-settings,+#musicComposePane.music-locked .customize-section,+#musicComposePane.music-locked .studio-tasks,#musicComposePane.music-locked .queue-strip { opacity: .45; pointer-events: none; user-select: none; }.music-install-body, .music-install-panel { line-height: 1.5; }.music-install-body .mi-lead, .music-install-panel .mi-lead { margin: 0 0 10px; }@@ -11221,3 +11238,345 @@ button .ph, label .ph, .qchip .ph { width: 14px; height: 14px; }button > .ph:first-child:not(:only-child),label > .ph:first-child:not(:only-child),.qchip > .ph:first-child:not(:only-child) { margin-right: 6px; vertical-align: -2px; }++/* ====== MUSIC STUDIO ======================================================+ The song is the unit, not the file. Everything below serves one idea: a+ song you can come back to — hear it, read its score, change one thing+ about it and get another. Tokens only; nothing declares its own colour. */+.studio-head { display: flex; flex-wrap: wrap; align-items: flex-start; justify-content: space-between;+ gap: 8px 16px; margin: 0 0 16px; }+.studio-head-text { flex: 1 1 200px; min-width: 0; }+.studio-head .studio-seg { flex: none; }+.studio-head .studio-title { font-size: var(--fs-lg); font-weight: 650; letter-spacing: -0.01em; }+.studio-head .studio-sub { display: block; margin-top: 2px; color: var(--muted); font-size: var(--fs-sm); }+.studio-tasks { margin-bottom: 16px; }+/* What Simple just wrote, said once, where the fields it wrote are. */+.music-notice { margin: 0 0 12px; padding: 8px 12px; border: 1px solid var(--accent-dim);+ border-left: 2px solid var(--accent); border-radius: var(--r-md); background: var(--accent-dim);+ color: var(--accent-bright); font-size: var(--fs-sm); }+.music-notice[hidden] { display: none; }+.tag-chips { display: flex; flex-wrap: wrap; gap: 6px; margin: 6px 0 2px; }+.tag-chip { height: var(--ctl-h-sm); padding: 0 10px; border-radius: var(--r-pill); border: 1px solid var(--border);+ background: var(--panel-2); color: var(--muted); font-size: var(--fs-xs); font-weight: 600; cursor: pointer;+ transition: background var(--t-fast), color var(--t-fast), border-color var(--t-fast); }+.tag-chip:hover { color: var(--text); border-color: var(--border-strong); }+.concept-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 8px; align-items: start; }+.concept-row textarea { min-height: 54px; }+.concept-row .ghost-btn { height: var(--ctl-h); white-space: nowrap; }+.concept-row .ghost-btn[disabled] { opacity: .55; cursor: progress; }++/* The studio's one switch idiom: two or three mutually exclusive views of the+ same surface. Anything that ACTS stays a button; this only ever chooses. */+.studio-seg { display: inline-grid; grid-auto-flow: column; grid-auto-columns: minmax(0, 1fr); gap: 2px;+ width: auto; padding: 3px; border: 1px solid var(--border); border-radius: var(--r-md); background: var(--bg-2); }+.studio-seg.full { display: grid; width: 100%; }+.studio-seg .seg-btn { width: auto; height: var(--ctl-h-sm); padding: 0 12px; border: 1px solid transparent;+ border-radius: var(--r-xs); background: transparent; color: var(--muted); font-size: var(--fs-sm); font-weight: 600;+ white-space: nowrap; cursor: pointer; transition: background var(--t-fast), color var(--t-fast), border-color var(--t-fast); }+.studio-seg .seg-btn .sub { display: block; font-size: var(--fs-2xs); font-weight: 400; color: var(--muted); }+.studio-seg .seg-btn:hover { color: var(--text); }+.studio-seg .seg-btn.active { background: var(--accent-dim); border-color: var(--accent); color: var(--accent-bright); }++/* ---- the lyrics editor ---------------------------------------------------+ A song is sections, so the editor is sections: a label, its lines, its line+ count, and the two verbs that belong to a part rather than to the song. */+.lyr-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin: 16px 0 8px; }+.lyr-title { font-size: var(--fs-md); font-weight: 600; color: var(--text); }+.lyr-editor { display: flex; flex-direction: column; gap: 8px; }+.lyr-editor[hidden] { display: none; }+.lyr-sections { display: flex; flex-direction: column; gap: 8px; }+.lyr-blank { padding: 16px 12px; border: 1px dashed var(--border); border-radius: var(--r-md);+ color: var(--muted); font-size: var(--fs-sm); line-height: 1.5; text-align: center; }+.lyr-sec { padding: 8px; border: 1px solid var(--border); border-radius: var(--r-md); background: var(--bg-2);+ transition: border-color var(--t-fast); }+.lyr-sec:focus-within { border-color: var(--accent); }+/* Two zones that wrap as units: what the section IS on the left, what you can+ do to it on the right. In a 215 px form pane the verbs drop to their own+ row instead of the last one falling off the edge. */+.lyr-sec-head { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 8px; }+.lyr-acts { display: flex; align-items: center; gap: 4px; margin-left: auto; }+/* The label is a pill, and the pill is the tag: what it reads is what sits in+ the brackets underneath. Native select chrome would break that reading, so+ the chevron is drawn in the wrapper's own colour. */+.lyr-tag-wrap { position: relative; display: inline-flex; align-items: center; color: var(--accent-bright); }+.lyr-tag-wrap::after { content: ""; position: absolute; right: 9px; top: 50%; margin-top: -1px; width: 0; height: 0;+ border-left: 3.5px solid transparent; border-right: 3.5px solid transparent; border-top: 4px solid currentColor;+ pointer-events: none; }+.lyr-tag { width: auto; height: var(--ctl-h-sm); padding: 0 24px 0 10px; appearance: none; -webkit-appearance: none;+ border: 1px solid var(--accent-dim); border-radius: var(--r-pill); background: var(--accent-dim); color: var(--accent-bright);+ font-size: var(--fs-xs); font-weight: 700; letter-spacing: .03em; cursor: pointer; }+.lyr-tag:focus { background: var(--accent-dim); border-color: var(--accent); }+.lyr-count { font-size: var(--fs-2xs); font-weight: 600; letter-spacing: .06em; text-transform: uppercase;+ color: var(--muted); white-space: nowrap; }+.lyr-btn { width: auto; height: var(--ctl-h-sm); padding: 0 10px; border-radius: var(--r-sm); border: 1px solid var(--border);+ background: var(--panel-2); color: var(--muted); font-size: var(--fs-xs); font-weight: 600; cursor: pointer;+ transition: color var(--t-fast), border-color var(--t-fast); }+.lyr-btn:hover:not([disabled]) { color: var(--text); border-color: var(--border-strong); }+.lyr-ico { width: var(--ctl-h-sm); height: var(--ctl-h-sm); padding: 0; display: grid; place-items: center;+ border: 1px solid transparent; border-radius: var(--r-sm); background: transparent; color: var(--muted);+ font-size: var(--fs-sm); line-height: 1; cursor: pointer; transition: background var(--t-fast), color var(--t-fast); }+.lyr-ico:hover:not([disabled]) { background: var(--panel-2); color: var(--text); }+.lyr-ico.lyr-del:hover:not([disabled]) { color: var(--danger); }+.lyr-btn[disabled], .lyr-ico[disabled] { opacity: .35; cursor: default; }+/* The lines themselves: the section IS the field, so the box has no chrome of+ its own and grows instead of scrolling. */+.lyr-lines { width: 100%; margin-top: 8px; padding: 0 2px; min-height: 30px; overflow: hidden; resize: none;+ border: 0; background: transparent; color: var(--text); font-family: inherit; font-size: var(--fs-md); line-height: 1.55; }+.lyr-lines:focus { background: transparent; border: 0; box-shadow: none; }+.lyr-wordless { display: none; margin-top: 6px; font-size: var(--fs-xs); color: var(--muted); }+.lyr-sec.wordless .lyr-wordless { display: block; }+.lyr-add { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }+.lyr-add-label { font-size: var(--fs-2xs); font-weight: 600; letter-spacing: .08em; text-transform: uppercase; color: var(--muted); }+/* Buttons are width:100% app-wide; a chip row has to say otherwise or every+ chip takes a line of its own. */+.lyr-add .tag-chip { width: auto; }+/* Instrumental: the words stay put, they are simply not used. */+.lyr-off { opacity: .45; }++/* ---- one rhythm, one rung ------------------------------------------------+ The composer grew a surface at a time and ended up with four label styles,+ five gaps and hints floating halfway between the control they explain and+ the next one. Everything below is scoped to this pane: the rest of the app+ keeps its own spacing, and nothing here declares a new value — 8 for "these+ belong together", 12 for "related", 16 for "a new thing starts".++ ONE LABEL RUNG. Every field label is the micro-caps the quick settings+ already used, so a label can never read as a heading or a heading as a+ label. .toggle-pill is a <label> wrapping a control and is not one of+ these, which is why the rule asks for [for]. */+#musicComposePane label[for],+#musicComposePane .mf-label,+#musicComposePane .lyr-title {+ display: block; margin: 16px 0 8px;+ font-size: var(--fs-2xs); font-weight: 600; letter-spacing: .08em;+ text-transform: uppercase; color: var(--muted);+}+#musicComposePane label[for] .sub { text-transform: none; letter-spacing: 0; font-weight: 500; }+#musicComposePane .composer-card > label[for]:first-child,+#musicComposePane .quick-settings > .mf-label:first-child { margin-top: 0; }+/* The range strip keeps its label on the row with the slider: no stacking+ margin, and it does not give ground to the track. */+#musicComposePane .range-strip label[for] { margin: 0; flex: none; }+#musicComposePane .lyr-head { margin: 16px 0 8px; }+#musicComposePane .lyr-head .lyr-title { margin: 0; }++/* ONE GAP LADDER. The stack is explicit rather than an inherited gap, so a+ hint sits ON the control it explains instead of midway to the next one. */+#musicComposePane .composer-card,+#musicComposePane .customize-section,+#musicComposePane .quick-settings { margin-bottom: 16px; }+#musicComposePane .customize-section { margin-top: 0; }+/* A plain block stack, so the ladder below is the only thing setting gaps. */+#musicComposePane .quick-settings { display: block; }+#musicComposePane .quick-settings > * + * { margin-top: 16px; }+#musicComposePane .quick-settings > .hint,+#musicComposePane .composer-card > .hint { margin-top: 6px; }+#musicComposePane .pill-group, #musicComposePane .studio-seg.full { margin-bottom: 0; }+#musicComposePane .composer-tools { margin-top: 12px; }++/* The footer: the estimate is about the button under it, so it starts where+ the button starts. The credit is about the engine, not about this press —+ a quieter rung, and last. */+#musicComposePane .form-action-footer .queue-strip { margin-bottom: 8px; }+#musicComposePane .form-action-footer #musicStatus { margin-top: 8px; min-height: 1.2em; }+.music-credit { margin-top: 12px; font-size: var(--fs-2xs); color: var(--muted); opacity: .75; }++/* The two optional packs say what they cost in place, in the section that+ needs them — the cover models and the LoRAs read the same way. */+.music-pack-note, .music-cover-install {+ margin-top: 10px; padding: 9px 11px; border-radius: var(--r-md);+ border: 1px solid var(--border-strong); background: var(--panel-2);+ color: var(--muted); font-size: var(--fs-xs); line-height: 1.5;+}+.music-pack-note[hidden], .music-cover-install[hidden] { display: none; }+.music-pack-note b, .music-cover-install b { color: var(--text); font-weight: 600; }+.music-pack-note .ghost-btn, .music-cover-install .ghost-btn { margin-left: 6px; }++/* The LoRA picker: the same row grammar as the video LoRA list, at the size+ the composer's quick settings use. */+.music-lora-list { display: flex; flex-direction: column; gap: 8px; }+.music-lora-empty { color: var(--muted); font-size: var(--fs-xs); }+.music-lora-item {+ padding: 8px 10px; border-radius: var(--r-sm);+ border: 1px solid var(--border-strong); background: var(--panel);+ transition: border-color var(--t-fast), background var(--t-fast);+}+.music-lora-item.active { border-color: var(--accent-bright); background: var(--accent-dim); }+.music-lora-head {+ display: flex; align-items: center; gap: 8px; cursor: pointer; user-select: none;+}+.music-lora-name { font-size: var(--fs-sm); font-weight: 600; color: var(--text); flex: 1 1 auto; }+.music-lora-branch {+ font-size: var(--fs-2xs); font-weight: 700; letter-spacing: .04em; text-transform: uppercase;+ padding: 2px 6px; border-radius: var(--r-pill); background: var(--panel-2); color: var(--muted);+}+.music-lora-item .range-strip { margin-top: 6px; }+.music-lora-item .hint { margin-top: 4px; }++/* The Song card: under the player, only for songs. */+.song-card { margin: 10px 0 0; padding: 12px 14px; border: 1px solid var(--border); border-radius: var(--r-lg);+ background: var(--panel); box-shadow: var(--shadow-1); }+.song-card[hidden] { display: none; }+.song-head { display: flex; align-items: baseline; justify-content: space-between; gap: 10px; flex-wrap: wrap; }+.song-title { font-size: var(--fs-lg); font-weight: 650; letter-spacing: -0.01em; }+.song-style { color: var(--muted); font-size: var(--fs-sm); max-width: 100%; }+.song-badges { display: flex; gap: 6px; flex-wrap: wrap; }+.song-badge { font-size: var(--fs-2xs); font-weight: 700; letter-spacing: .04em; text-transform: uppercase;+ padding: 3px 7px; border-radius: var(--r-pill); background: var(--accent-dim); color: var(--accent-bright); }+.song-badge.muted { background: var(--panel-2); color: var(--muted); }+.song-actions { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 10px; }+.song-actions .ghost-btn { height: var(--ctl-h); }+.song-actions .ghost-btn .sub { display: block; font-size: var(--fs-2xs); color: var(--muted); font-weight: 500; }+.song-lineage { margin-top: 8px; font-size: var(--fs-xs); color: var(--muted); }+.song-lineage a { color: var(--accent-bright); cursor: pointer; text-decoration: none; }+.song-lineage a:hover { text-decoration: underline; }+.song-section { margin-top: 12px; }+.song-section > summary { cursor: pointer; font-size: var(--fs-sm); font-weight: 600; color: var(--text); list-style: none; display: flex; align-items: center; gap: 8px; }+.song-section > summary::-webkit-details-marker { display: none; }+.song-section > summary::before { content: ""; width: 6px; height: 6px; border-right: 1.5px solid var(--muted); border-bottom: 1.5px solid var(--muted);+ transform: rotate(-45deg); transition: transform var(--t-fast); }+.song-section[open] > summary::before { transform: rotate(45deg); }+.song-section .sum { color: var(--muted); font-weight: 400; }+/* Sheet music. abcjs paints in black by default; the tokens win here so a+ score reads on the void and on paper alike. */+.song-score { margin-top: 8px; padding: 10px 6px; border-radius: var(--r-md); background: var(--panel-2); overflow: auto; max-height: 380px; }+.song-score svg { max-width: 100%; height: auto; }+.song-score svg path, .song-score svg text, .song-score svg rect, .song-score svg line, .song-score svg ellipse, .song-score svg polygon+ { fill: var(--text); stroke: var(--text); }+.song-score svg text { stroke: none; }+.song-score svg .abcjs-staff path, .song-score svg .abcjs-bar path { fill: none; }+.song-score svg .abcjs-staff-extra path { fill: var(--text); stroke: none; }+.song-score .abcjs-container { color: var(--text); }+.song-score-empty { color: var(--muted); font-size: var(--fs-sm); padding: 8px 4px; }+.song-score-editor { margin-top: 8px; }+.song-score-editor textarea { width: 100%; min-height: 180px; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: var(--fs-sm);+ background: var(--bg-2); color: var(--text); border: 1px solid var(--border); border-radius: var(--r-md); padding: 8px 10px; resize: vertical; }+.song-score-editor .row { display: flex; gap: 8px; align-items: center; margin-top: 8px; flex-wrap: wrap; }+.song-score-editor .row .hint { flex: 1 1 200px; margin: 0; }+.song-lyrics { margin-top: 8px; white-space: pre-wrap; font-size: var(--fs-sm); line-height: 1.5; color: var(--text); padding: 8px 10px;+ background: var(--panel-2); border-radius: var(--r-md); max-height: 260px; overflow: auto; }+.song-lyrics .tag { color: var(--accent-bright); font-weight: 700; font-size: var(--fs-2xs); letter-spacing: .06em; }+.song-status { margin-top: 8px; font-size: var(--fs-xs); color: var(--muted); min-height: 1.2em; }++/* ---- Music Studio: the library ------------------------------------------ */+.carousel.song-list { display: flex; flex-direction: column; gap: 4px; padding: 2px 0 8px; }+.song-row { display: grid; grid-template-columns: 44px minmax(0, 1fr) auto 32px 32px; align-items: center; gap: 12px;+ padding: 6px 8px 6px 6px; border-radius: var(--r-md); border: 1px solid transparent; cursor: pointer;+ transition: background var(--t-fast), border-color var(--t-fast); }+.song-row:hover { background: var(--panel-2); }+.song-row.active { background: var(--panel); border-color: var(--border-strong); }+.song-row.child { margin-left: 28px; position: relative; }+.song-row.child::before { content: ""; position: absolute; left: -16px; top: -6px; bottom: 50%; width: 10px;+ border-left: 1px solid var(--border-strong); border-bottom: 1px solid var(--border-strong); border-bottom-left-radius: 6px; }+.song-cover { width: 44px; height: 44px; border-radius: var(--r-sm); display: grid; place-items: center; color: rgba(255,255,255,.92);+ font-weight: 800; font-size: 18px; letter-spacing: -.02em; box-shadow: var(--shadow-1); flex: none; }+.song-row.child .song-cover { width: 36px; height: 36px; opacity: .85; }+.song-main { min-width: 0; }+.song-row-title { font-size: var(--fs-md); font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; display: flex; gap: 6px; align-items: center; }+.song-row-sub { display: flex; gap: 4px; flex-wrap: nowrap; overflow: hidden; margin-top: 3px; }+.song-chip { font-size: var(--fs-2xs); color: var(--muted); padding: 2px 7px; border-radius: var(--r-pill); background: var(--panel-2); border: 1px solid var(--border); white-space: nowrap; }+.song-row:hover .song-chip, .song-row.active .song-chip { background: var(--bg-2); }+.song-chip.score { color: var(--accent-bright); border-color: var(--accent-dim); }+.song-dur { font-size: var(--fs-xs); color: var(--muted); font-variant-numeric: tabular-nums; }+.song-play, .song-more { width: 32px; height: 32px; border-radius: var(--r-pill); border: 1px solid var(--border); background: var(--panel-2); color: var(--text);+ display: grid; place-items: center; cursor: pointer; transition: background var(--t-fast), border-color var(--t-fast), transform var(--t-fast); }+.song-play:hover, .song-more:hover { border-color: var(--border-strong); background: var(--panel); }+.song-play.on { background: var(--accent); border-color: var(--accent); color: #fff; }+.song-more { font-weight: 700; letter-spacing: .05em; }++/* the hero on the player surface */+.player-wrap .song-hero { position: absolute; inset: 0; display: flex; align-items: center; gap: 28px; padding: 32px;+ background: radial-gradient(120% 120% at 20% 0%, color-mix(in srgb, var(--accent) 12%, transparent), transparent 60%); }+.song-hero-cover { width: 180px; height: 180px; border-radius: var(--r-lg); display: grid; place-items: center; color: rgba(255,255,255,.92);+ font-weight: 800; font-size: 64px; letter-spacing: -.03em; box-shadow: var(--shadow-2); flex: none; }+.song-hero-text { min-width: 0; }+.song-hero-title { font-size: 26px; font-weight: 700; letter-spacing: -.02em; line-height: 1.15; }+.song-hero-style { color: var(--muted); margin-top: 8px; font-size: var(--fs-md); max-width: 60ch; }+.song-hero-meta { color: var(--muted); margin-top: 6px; font-size: var(--fs-sm); }+.song-hero-play { margin-top: 16px; display: inline-flex; align-items: center; gap: 8px; height: var(--ctl-h-lg); padding: 0 18px; border-radius: var(--r-pill); }++/* the player bar */+.music-bar { position: sticky; bottom: 0; z-index: 5; margin-top: 8px; display: grid; grid-template-columns: 40px minmax(120px, 220px) auto minmax(120px, 1fr) auto; align-items: center; gap: 12px;+ padding: 8px 12px; border: 1px solid var(--border); border-radius: var(--r-lg); background: color-mix(in srgb, var(--panel) 88%, transparent);+ backdrop-filter: blur(14px); -webkit-backdrop-filter: blur(14px); box-shadow: var(--shadow-2); }+.music-bar[hidden] { display: none; }+.music-bar-cover { width: 40px; height: 40px; border-radius: var(--r-sm); box-shadow: var(--shadow-1); }+.music-bar-text { min-width: 0; }+.music-bar-title { font-size: var(--fs-sm); font-weight: 650; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+.music-bar-style { font-size: var(--fs-2xs); color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; margin-top: 2px; }+.music-bar-controls { display: flex; gap: 4px; align-items: center; }+.music-bar-btn { width: 30px; height: 30px; border-radius: var(--r-pill); border: 1px solid transparent; background: transparent; color: var(--text); display: grid; place-items: center; cursor: pointer; }+.music-bar-btn:hover { background: var(--panel-2); }+.music-bar-btn.play { width: 36px; height: 36px; background: var(--accent); color: #fff; }+.music-bar-btn.play:hover { background: var(--accent-bright); }+.music-bar-wave { width: 100%; height: 36px; display: block; cursor: pointer; }+.music-bar-time { font-size: var(--fs-xs); color: var(--muted); font-variant-numeric: tabular-nums; white-space: nowrap; }++/* the ⋯ menu */+.song-menu { position: fixed; z-index: 60; width: 260px; padding: 6px; border-radius: var(--r-md); border: 1px solid var(--border-strong);+ background: var(--panel); box-shadow: var(--shadow-2); display: flex; flex-direction: column; }+.song-menu[hidden] { display: none; }+.song-menu-item { text-align: left; padding: 8px 10px; border: 0; border-radius: var(--r-sm); background: transparent; color: var(--text); font-size: var(--fs-sm); font-weight: 500; cursor: pointer; display: flex; flex-direction: column; gap: 1px; }+.song-menu-item .sub { font-size: var(--fs-2xs); color: var(--muted); font-weight: 400; }+.song-menu-item:hover:not([disabled]) { background: var(--panel-2); }+.song-menu-item[disabled] { opacity: .45; cursor: not-allowed; }+.song-menu-sep { height: 1px; background: var(--border); margin: 4px 6px; }++/* ===== MUSIC VIDEO — the cast of pictures =================================+ One row per picture: the thumbnail, what it is for, and an optional line+ about what happens in its shot. Deliberately a LIST and not the gallery's+ grid — a role is a decision per picture, and a decision needs a label+ beside it, not a hover state. Built from the same tokens as everything+ else, so it inherits both themes with no second palette. */+.mv-cast { display: grid; gap: 8px; margin-top: 10px; }+.mv-cast:empty { margin-top: 0; }+.mv-pic {+ display: grid;+ grid-template-columns: 72px minmax(0, 1fr) 28px;+ gap: 10px; align-items: center;+ padding: 8px; border: 1px solid var(--border);+ border-radius: var(--r-sm); background: var(--panel-2);+}+.mv-pic-thumb {+ width: 72px; height: 48px; object-fit: cover;+ border-radius: var(--r-xs); background: var(--bg-2);+ border: 1px solid var(--border);+}+.mv-pic-body { display: grid; gap: 6px; min-width: 0; }+.mv-pic-name {+ font-size: var(--fs-xs); color: var(--muted);+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;+}+/* auto-fit rather than three fixed columns: the Audio pane is draggable and+ at its narrowest the three role buttons wrap instead of clipping the last+ one — the same rule the render form's chip rows settled on. */+.mv-roles { display: grid; grid-template-columns: repeat(auto-fit, minmax(76px, 1fr)); gap: 4px; }+.mv-roles .pill-btn { min-height: var(--ctl-h-sm); font-size: var(--fs-xs); padding: 4px 6px; }+.mv-pic-prompt {+ width: 100%; min-height: var(--ctl-h-sm);+ font-size: var(--fs-sm); padding: 4px 8px;+ border-radius: var(--r-xs); border: 1px solid var(--border);+ background: var(--bg-2); color: var(--text);+}+.mv-pic-prompt:focus { outline: none; border-color: var(--accent); box-shadow: var(--ring); }+.mv-pic-x {+ width: 24px; height: 24px; display: grid; place-items: center;+ border: 1px solid var(--border); border-radius: var(--r-xs);+ background: transparent; color: var(--muted); cursor: pointer;+ transition: color var(--t-fast), border-color var(--t-fast);+}+.mv-pic-x:hover { color: var(--danger); border-color: var(--danger); }+.mv-pic-x .ph { width: 12px; height: 12px; }++/* A footer INSIDE a disclosure is not the pane's bottom bar. `.form-action-footer`+ is written to break out of the form-pane's own padding and stick to its+ bottom edge; One shot now lives inside a `<details>` halfway down the Music+ video pane, where sticking to the viewport and reaching past its parent's+ edge are both wrong. Same buttons, same order, laid out in place. */+#mvOneShotDetails .form-action-footer {+ position: static;+ margin: 12px 0 0;+ padding: 12px 0 0;+ background: none;+ backdrop-filter: none; -webkit-backdrop-filter: none;+}diff --git a/webapp/vendor/abcjs/LICENSE.md b/webapp/vendor/abcjs/LICENSE.mdnew file mode 100644index 0000000..ad4789d--- /dev/null+++ b/webapp/vendor/abcjs/LICENSE.md@@ -0,0 +1,21 @@+Copyright (c) 2009-2026 Paul Rosen and Gregory Dyke++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in+all copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN+THE SOFTWARE.++**This text is from: http://opensource.org/licenses/MIT**diff --git a/webapp/vendor/abcjs/NOTICE.md b/webapp/vendor/abcjs/NOTICE.mdnew file mode 100644index 0000000..7c9e7a6--- /dev/null+++ b/webapp/vendor/abcjs/NOTICE.md@@ -0,0 +1,10 @@+# abcjs 6.7.0 — vendored++Renderer for ABC music notation. Used by Phosphene's Music Studio to draw the+sheet music YuE2 writes for every song (the `score_abc` in a song's sidecar)+and to let it be edited and re-rendered.++- Source: https://github.com/paulrosen/abcjs (MIT — see LICENSE.md)+- File: `abcjs-basic-min.min.js`, byte-identical to the 6.7.0 npm/cdnjs build+- Vendored rather than loaded from a CDN because the panel is local-first:+ a song's score must render with the network off.diff --git a/webapp/vendor/abcjs/abcjs-basic-min.min.js b/webapp/vendor/abcjs/abcjs-basic-min.min.jsnew file mode 100644index 0000000..6b0c16f--- /dev/null+++ b/webapp/vendor/abcjs/abcjs-basic-min.min.js@@ -0,0 +1,3 @@+/*! abcjs_basic v6.7.0 Copyright © 2009-2026 Paul Rosen and Gregory Dyke (https://abcjs.net) */+/*! For license information please see abcjs_basic.LICENSE */+!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.abcjs=t():e.ABCJS=t()}(this,function(){return e={1045:function(e,t,r){var n=r(1185),a=r(6306),i=r(1592),s=r(1028),o=r(5633),c={};c.signature="abcjs-basic v"+n,Object.keys(a).forEach(function(e){c[e]=a[e]}),Object.keys(i).forEach(function(e){c[e]=i[e]}),c.renderAbc=r(6859),c.tuneMetrics=r(9989),c.TimingCallbacks=r(5681);var l=r(6020);c.setGlyph=l.setSymbol,c.strTranspose=o;var h=r(5594),u=r(8471),d=r(522),f=r(2029),p=r(6313),m=r(5281),g=r(8702),v=r(5049),b=r(4718),y=r(3450),x=r(562),k=r(9991);c.synth={CreateSynth:h,instrumentIndexToName:u,pitchToNoteName:d,SynthController:y,SynthSequence:f,CreateSynthControl:p,registerAudioContext:m,activeAudioContext:g,supportsAudio:v,playEvent:b,getMidiFile:x,sequence:s,midiRenderer:k},c.Editor=r(5294),c.EditArea=r(2945),c.test={Parse:r(8905),EngraverController:r(5253)},e.exports=c},6306:function(e,t,r){var n=r(5681),a={};!function(){"use strict";var e,t;a.startAnimation=function(r,a,i){function s(e){for(var t=0;t<e.length;t++){var r=e[t];r.classList.contains("abcjs-bar")||(r.style.display="none")}}var o;function c(e){i.hideCurrentMeasure?function(e){s(r.querySelectorAll(e))}(e):i.hideFinishedMeasures&&function(e){o&&s(r.querySelectorAll(o)),o=e}(e)}e&&(e.stop(),e=void 0),i.showCursor&&((t=r.querySelector(".abcjs-cursor"))||((t=document.createElement("DIV")).className="abcjs-cursor cursor",t.style.position="absolute",r.appendChild(t),r.style.position="relative")),(e=new n(a,{qpm:i.bpm,eventCallback:function(r){if(r){if(r.measureStart){var n=".abcjs-l"+(a=r).line+".abcjs-m"+a.measureNumber;n&&c(n)}t&&(t.style.left=r.left+"px",t.style.top=r.top+"px",t.style.width=r.width+"px",t.style.height=r.height+"px")}else e.stop(),e=void 0;var a}})).start()},a.pauseAnimation=function(t){e&&(t?e.pause():e.start())},a.stopAnimation=function(){e&&(e.stop(),e=void 0)}}(),e.exports=a},5681:function(e){e.exports=function(e,t){var r=this;t||(t={}),r.qpm=t.qpm?parseInt(t.qpm,10):null,r.extraMeasuresAtBeginning=t.extraMeasuresAtBeginning?parseInt(t.extraMeasuresAtBeginning,10):0,r.beatCallback=t.beatCallback,r.eventCallback=t.eventCallback,r.lineEndCallback=t.lineEndCallback,r.lineEndAnticipation=t.lineEndAnticipation?parseInt(t.lineEndAnticipation,10):0,r.beatSubdivisions=t.beatSubdivisions?parseInt(t.beatSubdivisions,10):1,r.beatSubdivisions||(r.beatSubdivisions=1),r.joggerTimer=null,r.replaceTarget=function(e){if(!t.qpm){var n=e.metaText?e.metaText.tempo:null;r.qpm=e.getBpm(n)}if(r.noteTimings=e.setTiming(r.qpm,r.extraMeasuresAtBeginning),0===e.noteTimings.length&&(r.noteTimings=e.setTiming(0,0)),r.lineEndCallback&&(r.lineEndTimings=function(e,t){for(var r=[],n=null,a=0;a<e.length;a++){var i=e[a];"end"!==i.type&&i.top!==n&&(r.push({measureNumber:i.measureNumber,milliseconds:i.milliseconds-t,top:i.top,bottom:i.top+i.height}),n=i.top)}return r}(e.noteTimings,r.lineEndAnticipation)),r.startTime=null,r.currentBeat=0,r.currentEvent=0,r.currentLine=0,r.currentTime=0,r.isPaused=!1,r.isRunning=!1,r.pausedPercent=null,r.justUnpaused=!1,r.newSeekPercent=0,r.lastTimestamp=0,0!==r.noteTimings.length){r.millisecondsPerBeat=1e3/(r.qpm/60)/r.beatSubdivisions,r.lastMoment=r.noteTimings[r.noteTimings.length-1].milliseconds;var a=e.getMeter(),i="";if(a&&"specified"===a.type&&a.value&&a.value.length>0&&a.value[0].num.indexOf("+")>0&&(i=a.value[0].num),r.beatStarts=[],i){for(var s=r.noteTimings[r.noteTimings.length-1].millisecondsPerMeasure,o=r.lastMoment/s,c=i.split("+"),l=0;l<c.length;l++)c[l]=parseInt(c[l],10)/2;for(var h=0,u=0,d=0;d<o;d++)for(var f=d*s,p=0,m=0;m<c.length;m++){var g=c[m];if(1===r.beatSubdivisions)1===r.beatSubdivisions&&h<r.lastMoment&&r.beatStarts.push({b:u,ts:h}),h+=g*r.millisecondsPerBeat;else for(var v=g*r.beatSubdivisions,b=0;b<Math.floor(v);b++){var y=b/v,x=Math.round(f+p*r.millisecondsPerBeat);x<r.lastMoment&&r.beatStarts.push({b:u+y,ts:x}),p++}u++}r.beatStarts.push({b:o*c.length,ts:r.lastMoment}),r.totalBeats=r.beatStarts.length}else{r.totalBeats=Math.round(r.lastMoment/r.millisecondsPerBeat);for(var k=0;k<r.totalBeats+1;k++)r.beatStarts.push({b:k/r.beatSubdivisions,ts:Math.round(k*r.millisecondsPerBeat)})}}},r.replaceTarget(e),r.doTiming=function(e){if(r.lastTimestamp!==e&&(r.lastTimestamp=e,!r.isPaused&&r.isRunning)){for(r.startTime||(r.startTime=e),r.currentTime=e-r.startTime,r.currentTime+=16;r.noteTimings.length>r.currentEvent&&r.noteTimings[r.currentEvent].milliseconds<r.currentTime;){if(r.eventCallback&&"event"===r.noteTimings[r.currentEvent].type){var t=r.startTime;r.eventCallback(r.noteTimings[r.currentEvent]),t!==r.startTime&&(r.currentTime=e-r.startTime)}r.currentEvent++}if(r.lineEndCallback&&r.lineEndTimings.length>r.currentLine&&r.lineEndTimings[r.currentLine].milliseconds<r.currentTime&&r.currentEvent<r.noteTimings.length){var n=r.noteTimings[r.currentEvent].milliseconds===r.currentTime?r.noteTimings[r.currentEvent]:r.noteTimings[r.currentEvent-1];r.lineEndCallback(r.lineEndTimings[r.currentLine],n,{line:r.currentLine,endTimings:r.lineEndTimings,currentTime:r.currentTime}),r.currentLine++}if(r.currentTime<r.lastMoment){if(requestAnimationFrame(r.doTiming),r.currentBeat<r.beatStarts.length&&r.beatStarts[r.currentBeat].ts<=r.currentTime){var a=r.doBeatCallback(e);r.currentBeat++,null!==a&&(r.currentTime=a)}}else if(r.currentBeat<=r.totalBeats&&r.beatCallback){var i=r.doBeatCallback(e);r.currentBeat++,null!==i&&(r.currentTime=i),requestAnimationFrame(r.doTiming)}if(r.currentTime>=r.lastMoment)if(r.eventCallback){var s=r.eventCallback(null);r.shouldStop(s).then(function(e){e&&r.stop()})}else r.stop()}},r.shouldStop=function(e){return new Promise(function(t){return e?"continue"===e?t(!1):void(e.then&&e.then(function(e){t("continue"!==e)})):t(!0)})},r.doBeatCallback=function(e){if(r.beatCallback){for(var t,n,a=r.currentEvent;a<r.noteTimings.length&&null===r.noteTimings[a].left;)a++;if(a<r.noteTimings.length){for(t=r.noteTimings[a].milliseconds,a=Math.max(0,r.currentEvent-1);a>=0&&null===r.noteTimings[a].left;)a--;n=r.noteTimings[a]}var i={},s={};if(n){i.top=n.top,i.height=n.height;var o=Math.max(0,e-r.startTime-n.milliseconds),c=t-n.milliseconds,l=n.endX-n.left,h=c?o*l/c:0;i.left=n.left+h,0===r.currentEvent&&n.milliseconds>e-r.startTime&&(i.left=void 0),s={timestamp:e,startTime:r.startTime,ev:n,endMs:t,offMs:o,offPx:h,gapMs:c,gapPx:l}}else s={timestamp:e,startTime:r.startTime};if(r.currentBeat<0||r.currentBeat>=r.beatStarts.length||!r.beatStarts[r.currentBeat]){var u={currentBeat:r.currentBeat,beatStartLength:r.beatStarts.length,totalBeats:r.totalBeats,startTime:r.startTime,currentTime:r.currentTime,lastMoment:r.lastMoment,lastTimestamp:r.lastTimestamp,qpm:r.qpm,millisecondsPerBeat:r.millisecondsPerBeat,beatSubdivisions:r.beatSubdivisions,currentEvent:r.currentEvent,currentLine:r.currentLine,isPaused:r.isPaused,isRunning:r.isRunning,pausedPercent:r.pausedPercent,justUnpaused:r.justUnpaused,newSeekPercent:r.newSeekPercent};setTimeout(function(){throw new Error("abcjs-timing-callback error: "+JSON.stringify(u))},1)}else{var d=r.startTime;if(r.beatCallback(r.beatStarts[r.currentBeat].b,r.totalBeats/r.beatSubdivisions,r.lastMoment,i,s),d!==r.startTime)return e-r.startTime}}return null},r.animationJogger=function(){r.isRunning&&(r.doTiming(performance.now()),r.joggerTimer=setTimeout(r.animationJogger,60))},r.start=function(e,t){if(r.isRunning=!0,r.isPaused&&(r.isPaused=!1,void 0===e&&(r.justUnpaused=!0)),e)r.setProgress(e,t);else if(0===e)r.reset();else if(null!==r.pausedPercent){var n=performance.now();r.currentTime=r.lastMoment*r.pausedPercent,r.startTime=n-r.currentTime,r.pausedPercent=null,r.reportNext=!0}requestAnimationFrame(r.doTiming),r.joggerTimer=setTimeout(r.animationJogger,60)},r.pause=function(){r.isPaused=!0;var e=performance.now();r.pausedPercent=(e-r.startTime)/r.lastMoment,r.isRunning=!1,r.joggerTimer&&(clearTimeout(r.joggerTimer),r.joggerTimer=null)},r.currentMillisecond=function(){return r.currentTime},r.reset=function(){r.currentBeat=0,r.currentEvent=0,r.currentLine=0,r.startTime=null,r.pausedPercent=null},r.stop=function(){r.pause(),r.reset()},r.setProgress=function(e,t){var n;switch(t){case"seconds":r.currentTime=1e3*e,r.currentTime<0&&(r.currentTime=0),r.currentTime>r.lastMoment&&(r.currentTime=r.lastMoment),n=r.currentTime/r.lastMoment;break;case"beats":r.currentTime=e*r.millisecondsPerBeat*r.beatSubdivisions,r.currentTime<0&&(r.currentTime=0),r.currentTime>r.lastMoment&&(r.currentTime=r.lastMoment),n=r.currentTime/r.lastMoment;break;default:(n=e)<0&&(n=0),n>1&&(n=1),r.currentTime=r.lastMoment*n}r.isRunning||(r.pausedPercent=n);var a=performance.now();for(r.startTime=a-r.currentTime,r.currentEvent=0;r.noteTimings.length>r.currentEvent&&r.noteTimings[r.currentEvent].milliseconds<r.currentTime;)r.currentEvent++;if(r.lineEndCallback)for(r.currentLine=0;r.lineEndTimings.length>r.currentLine&&r.lineEndTimings[r.currentLine].milliseconds+r.lineEndAnticipation<r.currentTime;)r.currentLine++;var i=r.currentBeat;for(r.currentBeat=0;r.currentBeat<r.beatStarts.length&&!(r.beatStarts[r.currentBeat].ts>r.currentTime);r.currentBeat++);r.currentBeat--,r.beatCallback&&i!==r.currentBeat&&(r.doBeatCallback(r.startTime+r.currentTime),r.currentBeat++),r.eventCallback&&r.currentEvent>=0&&"event"===r.noteTimings[r.currentEvent].type&&r.eventCallback(r.noteTimings[r.currentEvent]),r.lineEndCallback&&r.lineEndCallback(r.lineEndTimings[r.currentLine],r.noteTimings[r.currentEvent],{line:r.currentLine,endTimings:r.lineEndTimings}),r.joggerTimer=setTimeout(r.animationJogger,60)}}},1592:function(e,t,r){function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}var a=r(8905),i=r(9565),s=r(2426),o={};!function(){"use strict";o.numberOfTunes=function(e){var t=e.split("\nX:").length;return 0===t&&(t=1),t};var e=o.TuneBook=function(e){var t=i(e);this.header=t.header,this.tunes=t.tunes};e.prototype.getTuneById=function(e){for(var t=0;t<this.tunes.length;t++)if(this.tunes[t].id===""+e)return this.tunes[t];return null},e.prototype.getTuneByTitle=function(e){for(var t=0;t<this.tunes.length;t++)if(this.tunes[t].title===e)return this.tunes[t];return null},o.parseOnly=function(e,t){for(var r=o.numberOfTunes(e),n=[],a=0;a<r;a++)n.push(1);return o.renderEngine(function(){},n,e,t)},o.renderEngine=function(t,r,i,o){var c=[];if(void 0!==r&&void 0!==i){var l;(!(l=r)||l.propertyIsEnumerable("length")||"object"!==n(l)||"number"!=typeof l.length)&&(r=[r]),void 0===o&&(o={});for(var h=o.startingTune?parseInt(o.startingTune,10):0,u=new e(i),d=new a,f=0;f<r.length;f++){var p=r[f];if("*"===p||"string"==typeof p&&(p=document.getElementById(p)),p)if(h>=0&&h<u.tunes.length){d.parse(u.tunes[h].abc,o,u.tunes[h].startPos-u.header.length);var m=d.getTune();o.tablature&&(m.tablatures=s.preparePlugins(m,h,o));var g=d.getWarnings();g&&(m.warnings=g);var v=t(p,m,f,u.tunes[h].abc);c.push(v||m)}else p.innerHTML&&(p.innerHTML="");h++}return c}},o.extractMeasures=function(t){for(var r=[],n=new e(t),a=0;a<n.tunes.length;a++){for(var i=n.tunes[a],s=i.abc.split("K:"),c=s[1].split("\n"),l=s[0]+"K:"+c[0]+"\n",h=null,u=null,d=null,f=[],p=!1,m=o.parseOnly(i.abc)[0],g=m.getPickupLength()>0,v=0;v<m.lines.length;v++){var b=m.lines[v];if(b.staff)for(var y=0;y<1;y++)for(var x=b.staff[y],k=0;k<1;k++)for(var w=x.voices[k],C=0;C<w.length;C++){var T=w[C];if(null===d&&T.startChar>=0&&(d=T.startChar,u=void 0===T.chord?h:null),T.chord&&(h=T),"bar"===T.el_type){if(p){var S={abc:i.abc.substring(d,T.endChar)};(h=u&&u.chord&&u.chord.length>0?u.chord[0].name:null)&&(S.lastChord=h),T.startEnding&&(S.startEnding=T.startEnding),T.endEnding&&(S.endEnding=T.endEnding),f.push(S),d=null,p=!1}}else"note"===T.el_type&&(p=!0)}}r.push({header:l,measures:f,hasPickup:g})}return r}}(),e.exports=o},6859:function(e,t,r){var n=r(1592),a=(r(6780),r(5253)),i=r(8905),s=r(1756),o={};function c(){var e=window.innerWidth;for(var t in o)if(o.hasOwnProperty(t)){var r=o[t];e-=2*r.offsetLeft,r.style.width=e+"px"}}try{window.addEventListener("resize",c),window.addEventListener("orientationChange",c)}catch(e){}function l(e,t,r,n,i){r.viewportHorizontal?(e.innerHTML='<div class="abcjs-inner"></div>',r.scrollHorizontal?(e.style.overflowX="auto",e.style.overflowY="hidden"):e.style.overflow="hidden",o[e.id]=e,e=e.children[0]):r.viewportVertical?(e.innerHTML='<div class="abcjs-inner scroll-amount"></div>',e.style.overflowX="hidden",e.style.overflowY="auto",e=e.children[0]):e.innerHTML="";var s=new a(e,r);s.engraveABC(t,n,i),t.engraver=s,(r.viewportVertical||r.viewportHorizontal)&&(e.parentNode.style.width=e.style.width)}e.exports=function(e,t,r,o,c){var h,u={};if(r){for(h in r)r.hasOwnProperty(h)&&(u[h]=r[h]);u.warnings_id&&u.tablature&&(u.tablature.warning_id=u.warnings_id)}if(o)for(h in o)o.hasOwnProperty(h)&&("listener"===h?o[h].highlight&&(u.clickListener=o[h].highlight):u[h]=o[h]);if(c)for(h in c)c.hasOwnProperty(h)&&(u[h]=c[h]);return n.renderEngine(function(e,t,r,n){var o=!1;return"*"===e&&(o=!0,(e=document.createElement("div")).setAttribute("style","visibility: hidden;"),document.body.appendChild(e)),!o&&u.wrap&&u.staffwidth?(t=function(e,t,r,n,o){var c=new a(e,o).getMeasureWidths(t),h=s.calcLineWraps(t,c,o);if(h.reParse){var u=new i;u.parse(n,h.revisedParams),t=u.getTune();var d=u.getWarnings();d&&(t.warnings=d)}return o.afterParsing&&o.afterParsing(t,r,n),l(e,t,h.revisedParams,r,0),t.explanation=h.explanation,t}(e,t,r,n,u),t):(u.afterParsing&&u.afterParsing(t,r,n),l(e,t,u,r,0),o&&e.parentNode.removeChild(e),null)},e,t,u)}},9989:function(e,t,r){var n=r(1592),a=r(5253);e.exports=function(e,t){return n.renderEngine(function(e,r,n,i){(e=document.createElement("div")).setAttribute("style","visibility: hidden;"),document.body.appendChild(e);var s=new a(e,t).getMeasureWidths(r);return e.parentNode.removeChild(e),{sections:s}},"*",e,t)}},9447:function(e,t,r){var n=r(4914).relativeMajor,a={acc:"sharp",note:"f"},i={acc:"sharp",note:"c"},s={acc:"sharp",note:"g"},o={acc:"sharp",note:"d"},c={acc:"sharp",note:"A"},l={acc:"sharp",note:"e"},h={acc:"flat",note:"B"},u={acc:"flat",note:"e"},d={acc:"flat",note:"A"},f={acc:"flat",note:"d"},p={acc:"flat",note:"G"},m={acc:"flat",note:"c"},g={"C#":[a,i,s,o,c,l,{acc:"sharp",note:"B"}],"F#":[a,i,s,o,c,l],B:[a,i,s,o,c],E:[a,i,s,o],A:[a,i,s],D:[a,i],G:[a],C:[],F:[h],Bb:[h,u],Eb:[h,u,d],Cm:[h,u,d],Ab:[h,u,d,f],Db:[h,u,d,f,p],Gb:[h,u,d,f,p,m],Cb:[h,u,d,f,p,m,{acc:"flat",note:"F"}],"A#":[h,u],"B#":[],"D#":[h,u,d],"E#":[h],"G#":[h,u,d,f],none:[]};e.exports=function(e){var t=g[n(e)];return t?JSON.parse(JSON.stringify(t)):null}},4914:function(e){var t={C:{modes:["CMaj","CIon","Amin","AAeo","Am","GMix","DDor","EPhr","FLyd","BLoc"],stepsFromC:0},Db:{modes:["DbMaj","DbIon","Bbmin","BbAeo","Bbm","AbMix","EbDor","FPhr","GbLyd","CLoc"],stepsFromC:1},D:{modes:["DMaj","DIon","Bmin","BAeo","Bm","AMix","EDor","F#Phr","GLyd","C#Loc"],stepsFromC:2},Eb:{modes:["EbMaj","EbIon","Cmin","CAeo","Cm","BbMix","FDor","GPhr","AbLyd","DLoc"],stepsFromC:3},E:{modes:["EMaj","EIon","C#min","C#Aeo","C#m","BMix","F#Dor","G#Phr","ALyd","D#Loc"],stepsFromC:4},F:{modes:["FMaj","FIon","Dmin","DAeo","Dm","CMix","GDor","APhr","BbLyd","ELoc"],stepsFromC:5},Gb:{modes:["GbMaj","GbIon","Ebmin","EbAeo","Ebm","DbMix","AbDor","BbPhr","CbLyd","FLoc"],stepsFromC:6},G:{modes:["GMaj","GIon","Emin","EAeo","Em","DMix","ADor","BPhr","CLyd","F#Loc"],stepsFromC:7},Ab:{modes:["AbMaj","AbIon","Fmin","FAeo","Fm","EbMix","BbDor","CPhr","DbLyd","GLoc"],stepsFromC:8},A:{modes:["AMaj","AIon","F#min","F#Aeo","F#m","EMix","BDor","C#Phr","DLyd","G#Loc"],stepsFromC:9},Bb:{modes:["BbMaj","BbIon","Gmin","GAeo","Gm","FMix","CDor","DPhr","EbLyd","ALoc"],stepsFromC:10},B:{modes:["BMaj","BIon","G#min","G#Aeo","G#m","F#Mix","C#Dor","D#Phr","ELyd","A#Loc"],stepsFromC:11},"C#":{modes:["C#Maj","C#Ion","A#min","A#Aeo","A#m","G#Mix","D#Dor","E#Phr","F#Lyd","B#Loc"],stepsFromC:1},"F#":{modes:["F#Maj","F#Ion","D#min","D#Aeo","D#m","C#Mix","G#Dor","A#Phr","BLyd","E#Loc"],stepsFromC:6},Cb:{modes:["CbMaj","CbIon","Abmin","AbAeo","Abm","GbMix","DbDor","EbPhr","FbLyd","BbLoc"],stepsFromC:11}},r=["maj","ion","min","aeo","m","mix","dor","phr","lyd","loc"],n=null;e.exports={relativeMajor:function(e){n||function(){n={};for(var e=Object.keys(t),r=0;r<e.length;r++){var a=t[e[r]];n[e[r].toLowerCase()]=e[r];for(var i=0;i<a.modes.length;i++){var s=a.modes[i].toLowerCase();n[s]=e[r]}}}();var r=e.toLowerCase().match(/([a-g][b#]?)(maj|ion|min|aeo|mix|dor|phr|lyd|loc|m)?/);return r&&r[2]?(r=r[1]+r[2],n[r]||e):e},relativeMode:function(e,r){var n=t[e];if(!n)return e;if(""===r)return e;var a=r.toLowerCase().match(/^(maj|ion|min|aeo|mix|dor|phr|lyd|loc|m)/);if(!a)return e;for(var i=a[1],s=0;s<n.modes.length;s++){var o=n.modes[s],c=o.toLowerCase().indexOf(i);if(-1!==c&&c===o.length-i.length)return o.substring(0,o.length-i.length)}return e},transposeKey:function(e,r){var n=t[e];if(!n)return e;for(;r<0;)r+=12;for(var a=(n.stepsFromC+r)%12,i=0;i<Object.keys(t).length;i++){var s=Object.keys(t)[i];if(t[s].stepsFromC===a)return s}return e},isLegalMode:function(e){return r.indexOf(e.toLowerCase())>=0}}},6780:function(e,t,r){var n=r(5008),a=r(4331),i=r(1028),s=r(9716),o=r(351);e.exports=function(){function e(e,t,r,n){for(var a=0;a<n.length;a++)e[r][n[a]]=t[r][n[a]]}function t(e,t){for(;t<e.length&&null===e[t].left;)t++;return e[t]}this.reset=function(){this.version="1.1.0",this.media="screen",this.metaText={},this.metaTextInfo={},this.formatting={},this.lines=[],this.staffNum=0,this.voiceNum=0,this.lineNum=0,this.runningFonts={},delete this.visualTranspose},this.reset(),this.copyTopInfo=function(t){var r=["tempo","title","header","rhythm","origin","composer","author","partOrder"];e(this,t,"metaText",r),e(this,t,"metaTextInfo",r)},this.copyBottomInfo=function(t){var r=["unalignedWords","book","source","discography","notes","transcription","history","abc-copyright","abc-creator","abc-edited-by","footer"];e(this,t,"metaText",r),e(this,t,"metaTextInfo",r)},this.getBeatLength=function(){var e=this.getMeterFraction(),t=1;return 6===e.num||9===e.num||12===e.num||3===e.num&&8===e.den?t=3:8!==e.den||5!==e.num&&7!==e.num||(t=2),t/e.den},this.getPickupLength=function(){var e=this.getBarLength(),t=function(e,t){for(var r=0,n=0;n<e.length;n++)if(e[n].staff)for(var a=0;a<e[n].staff.length;a++)for(var i=0;i<e[n].staff[a].voices.length;i++)for(var s=e[n].staff[a].voices[i],o=1,c=0;c<s.length;c++){var l=s[c].rest&&"spacer"===s[c].rest.type;if(s[c].startTriplet&&(o=s[c].tripletMultiplier),s[c].duration&&!l&&"tempo"!==s[c].el_type&&(r+=s[c].duration*o),s[c].endTriplet&&(o=1),r>=t&&(r-=t),"bar"===s[c].el_type)return r}return r}(this.lines,e);return t<1e-8||e-t<1e-8?0:t},this.getBarLength=function(){var e=this.getMeterFraction();return e.num/e.den},this.getTotalTime=function(){return this.totalTime},this.getTotalBeats=function(){return this.totalBeats},this.millisecondsPerMeasure=function(e){var t;if(e)t=e;else{var r=this.metaText?this.metaText.tempo:null;t=this.getBpm(r)}return t<=0&&(t=1),this.getBeatsPerMeasure()/t*6e4},this.getBeatsPerMeasure=function(){var e=this.getBeatLength();return this.getBarLength()/e},this.getMeter=function(){for(var e=0;e<this.lines.length;e++){var t=this.lines[e];if(t.staff)for(var r=0;r<t.staff.length;r++){var n=t.staff[r].meter;if(n)return n}}return{type:"common_time"}},this.getMeterFraction=function(){var e=this.getMeter(),t=4,r=4;if(e)if("specified"===e.type){if(e.value&&e.value.length>0&&e.value[0].num.indexOf("+")>0){var n=e.value[0].num.split("+");t=0;for(var a=0;a<n.length;a++)t+=parseInt(n[a],10)}else t=parseInt(e.value[0].num,10);r=parseInt(e.value[0].den,10)}else"cut_time"===e.type?(t=2,r=2):"common_time"===e.type&&(t=4,r=4);return this.meter={num:t,den:r},this.meter},this.getKeySignature=function(){for(var e=0;e<this.lines.length;e++){var t=this.lines[e];if(t.staff)for(var r=0;r<t.staff.length;r++)if(t.staff[r].key)return t.staff[r].key}return{}},this.getElementFromChar=function(e){for(var t=0;t<this.lines.length;t++){var r=this.lines[t];if(r.staff)for(var n=0;n<r.staff.length;n++)for(var a=r.staff[n],i=0;i<a.voices.length;i++)for(var s=a.voices[i],o=0;o<s.length;o++){var c=s[o];if(c.startChar&&c.endChar&&c.startChar<=e&&c.endChar>e)return c}}return null},this.addElementToEvents=function(e,t,r,a,i,s,o,c,l,h){if(t.hint)return{isTiedState:void 0,duration:0};var u=t.durationClass?t.durationClass:t.duration;if(t.abcelem.rest&&"spacer"===t.abcelem.rest.type&&(u=0),u>0){for(var d=[],f=0;f<t.elemset.length;f++)null!==t.elemset[f]&&d.push(t.elemset[f]);var p=t.startTie;if(void 0!==l)e["event"+l].elements.push(d),h&&(e["event"+r]||(e["event"+r]={type:"event",milliseconds:r,line:s,measureNumber:o,top:a,height:i,left:null,width:0,elements:[],startChar:null,endChar:null,startCharArray:[],endCharArray:[]}),e["event"+r].measureStart=!0,h=!1),p||(l=void 0);else{if(e["event"+r]){if(e["event"+r].left?e["event"+r].left=Math.min(e["event"+r].left,t.x):e["event"+r].left=t.x,e["event"+r].elements.push(d),e["event"+r].startCharArray.push(t.abcelem.startChar),e["event"+r].endCharArray.push(t.abcelem.endChar),null===e["event"+r].startChar&&(e["event"+r].startChar=t.abcelem.startChar),null===e["event"+r].endChar&&(e["event"+r].endChar=t.abcelem.endChar),t.abcelem.midiPitches&&t.abcelem.midiPitches.length)for(e["event"+r].midiPitches||(e["event"+r].midiPitches=[]),f=0;f<t.abcelem.midiPitches.length;f++)e["event"+r].midiPitches.push(t.abcelem.midiPitches[f]);if(t.abcelem.midiGraceNotePitches&&t.abcelem.midiGraceNotePitches.length){e["event"+r].midiGraceNotePitches||(e["event"+r].midiGraceNotePitches=[]);for(var m=0;m<t.abcelem.midiGraceNotePitches.length;m++)e["event"+r].midiGraceNotePitches.push(t.abcelem.midiGraceNotePitches[m])}}else e["event"+r]={type:"event",milliseconds:r,line:s,measureNumber:o,top:a,height:i,left:t.x,width:t.w,elements:[d],startChar:t.abcelem.startChar,endChar:t.abcelem.endChar,startCharArray:[t.abcelem.startChar],endCharArray:[t.abcelem.endChar],midiPitches:t.abcelem.midiPitches?n.cloneArray(t.abcelem.midiPitches):[]},t.abcelem.midiGraceNotePitches&&(e["event"+r].midiGraceNotePitches=n.cloneArray(t.abcelem.midiGraceNotePitches));h&&(e["event"+r].measureStart=!0,h=!1)}}return{isTiedState:l,duration:u/c,nextIsBar:h||"bar"===t.type}},this.makeVoicesArray=function(){for(var e=[],t=[],r={},n=0;n<this.engraver.staffgroups.length;n++){var i=this.engraver.staffgroups[n];if(i&&i.staffs&&i.staffs.length>0)for(var s=i.staffs[0],o=s.absoluteY,c=o-s.top*a.STEP,l=i.staffs[i.staffs.length-1],h=(o=l.absoluteY)-l.bottom*a.STEP-c,u=i.voices,d=0;d<u.length;d++)if(!u[d].staff||!u[d].staff.isTabStaff){var f=!1;e[d]||(e[d]=[]),void 0===t[d]&&(t[d]=0);for(var p=u[d].children,m=0;m<p.length;m++)"tempo"===p[m].type&&(r[t[d]]=this.getBpm(p[m].abcelem)),e[d].push({top:c,height:h,line:i.line,measureNumber:t[d],elem:p[m]}),"bar"===p[m].type&&f&&t[d]++,"note"!==p[m].type&&"rest"!==p[m].type||(f=!0)}}return this.tempoLocations=r,e},this.setupEvents=function(e,r,n,a){a||(a=1);for(var i,s=[],o={},c=e,l=!0,h=this.makeVoicesArray(),u=0,d=0;d<h.length;d++){var f=c,p=Math.round(1e3*f),m=0,g=-1,v=h[d],b=n;r=this.getBeatLength()*b/60;for(var y=-1,x=0;x<v.length;x++){var k=v[x].measureNumber;y!==k&&this.tempoLocations[k]&&(b=this.tempoLocations[k],r=a*this.getBeatLength()*b/60,y=k);var w,C=v[x].elem,T=this.addElementToEvents(o,C,p,v[x].top,v[x].height,v[x].line,v[x].measureNumber,r,i,l);if(i=T.isTiedState,l=T.nextIsBar,f+=T.duration,C.duration>0&&o["event"+p]&&(w="event"+p),p=Math.round(1e3*f),"bar"===C.type){var S=C.abcelem.type,_="bar_right_repeat"===S||"bar_dbl_repeat"===S,E="1"===C.abcelem.startEnding,M="bar_left_repeat"===S||"bar_dbl_repeat"===S||"bar_right_repeat"===S;if(_){x>0&&(o[w].endX=C.x),-1===g&&(g=x);var A=0;y=-1;for(var N=m;N<g;N++){y!==(k=v[N].measureNumber)&&this.tempoLocations[k]&&(b=this.tempoLocations[k],r=a*this.getBeatLength()*b/60,y=k);var B=v[N].elem;i=(T=this.addElementToEvents(o,B,p,v[N].top,v[N].height,v[N].line,v[N].measureNumber,r,i,l)).isTiedState,l=T.nextIsBar,f+=T.duration,A=p,p=Math.round(1e3*f)}o["event"+A]&&(o["event"+A].endX=v[g].elem.x),l=!0,g=-1}E&&(g=x),M&&(m=x)}}u=Math.max(u,p)}return function(e){for(var t,r,n,a,i=e.length-1;i>=0;i--){var s=e[i];"bar"===s.type?(s.top=n,s.nextTop=t,t=n,s.bottom=a,s.nextBottom=r,r=a):"event"===s.type&&(n=s.top,a=s.top+s.height)}}(s=function(e){var t=[];for(var r in e)e.hasOwnProperty(r)&&t.push(e[r]);return t.sort(function(e,t){var r=e.milliseconds-t.milliseconds;return 0!==r?r:"bar"===e.type?-1:1})}(o)),function(e,r){if(!(r.length<1)){for(var n=0;n<r.length-1;n++){var a=r[n],i=t(r,n+1);if(null!==a.left){var s=i&&a.top===i.top?i.left:e[a.line].staffGroup.w;void 0!==a.endX?s>a.left&&(a.endX=Math.min(a.endX,s)):a.endX=s}}var o=r[r.length-1];o.endX=e[o.line].staffGroup.w}}(this.lines,s),s.push({type:"end",milliseconds:u}),this.addUsefulCallbackInfo(s,b*a),s},this.addUsefulCallbackInfo=function(e,t){for(var r=this.millisecondsPerMeasure(t),n=0;n<e.length;n++)e[n].millisecondsPerMeasure=r},this.getBpm=function(e){var t;if(e||(e=this.metaText?this.metaText.tempo:null),e){t=e.bpm;var r=this.getBeatLength();t=t*(e.duration&&e.duration.length>0?e.duration[0]:r)/r}if(!t){t=180;var n=this.getMeterFraction();n&&3!==n.num&&n.num%3==0&&(t=120)}return t},this.setTiming=function(e,t){if(t=t||0,!this.engraver||!this.engraver.staffgroups)return console.log("setTiming cannot be called before the tune is drawn."),this.noteTimings=[],this.noteTimings;var r=this.metaText?this.metaText.tempo:null,n=this.getBpm(r),a=1;e?r&&(a=e/n):e=n;var i=this.getBeatLength(),s=e/60,o=this.getBarLength()/i*t/s;o&&(o-=this.getPickupLength()/i/s);var c=i*s;return this.noteTimings=this.setupEvents(o,c,e,a),this.noteTimings.length>0?(this.totalTime=this.noteTimings[this.noteTimings.length-1].milliseconds/1e3,this.totalBeats=this.totalTime*s):(this.totalTime=void 0,this.totalBeats=void 0),this.noteTimings},this.setUpAudio=function(e){e||(e={});var t=i(this,e);return s(t,e,this.formatting.percmap,this.formatting.midi)},this.deline=function(e){return o(this.lines,e)},this.findSelectableElement=function(e){return this.engraver&&this.engraver.selectables?this.engraver.findSelectableElement(e):null},this.getSelectableArray=function(){return this.engraver&&this.engraver.selectables?this.engraver.selectables:[]}}},351:function(e){function t(e,t){return"abselem"===e?"abselem":t}function r(e,t){e.el_type="meter",e.startChar=-1,e.endChar=-1;for(var r=0;r<t.length;r++)t[r].unshift(e)}function n(e,t){e.el_type="key",e.startChar=-1,e.endChar=-1;for(var r=0;r<t.length;r++)t[r].unshift(e)}function a(e,t){e.el_type="clef",e.startChar=-1,e.endChar=-1;for(var r=0;r<t.length;r++)t[r].unshift(e)}function i(e,t,r){e.el_type="font",e.type=r,e.startChar=-1,e.endChar=-1;for(var n=0;n<t.length;n++)t[n].unshift(e)}function s(e,r){return!e||JSON.stringify(e,t)===JSON.stringify(r,t)}function o(e){for(var t={},r=Object.keys(e),n=0;n<r.length;n++)if("staff"!==r[n])t[r[n]]=e[r[n]];else{t.staff=[];for(var a=0;a<e.staff.length;a++){for(var i={},s=Object.keys(e.staff[a]),o=0;o<s.length;o++)if("voices"!==s[o])i[s[o]]=e.staff[a][s[o]];else{i.voices=[];for(var c=0;c<e.staff[a].voices.length;c++)i.voices.push([].concat(e.staff[a].voices[c]))}t.staff.push(i)}}return t}e.exports=function(e,t){t||(t={});for(var c=!!t.lineBreaks,l=[],h=!1,u=[],d=[],f=[],p=[],m=[],g=[],v=[],b=0;b<e.length;b++){var y=o(e[b]);if(y.staff){if(h&&!y.vskip)for(var x=l[l.length-1],k=0;k<x.staff.length;k++){var w=y.staff[k],C=x.staff[k];if(w&&(s(w.meter,u[k])||(r(w.meter,w.voices),u[k]=w.meter,delete w.meter),s(w.key,d[k])||(n(w.key,w.voices),d[k]=w.key,delete w.key),w.title&&(C.abbrevTitle=w.title),s(w.clef,f[k])||(a(w.clef,w.voices),f[k]=w.clef,delete w.clef),s(w.vocalfont,p[k])||(i(w.vocalfont,w.voices,"vocalfont"),p[k]=w.vocalfont,delete w.vocalfont),s(w.gchordfont,m[k])||(i(w.gchordfont,w.voices,"gchordfont"),m[k]=w.gchordfont,delete w.gchordfont),s(w.tripletfont,g[k])||(i(w.tripletfont,w.voices,"tripletfont"),g[k]=w.tripletfont,delete w.tripletfont),s(w.annotationfont,v[k])||(i(w.annotationfont,w.voices,"annotationfont"),v[k]=w.annotationfont,delete w.annotationfont)),w)for(var T=0;T<C.voices.length;T++){var S=C.voices[T],_=w.voices[T];c&&S.push({el_type:"break"}),_&&(C.voices[T]=S.concat(_))}}else{for(var E=0;E<y.staff.length;E++)d[E]=y.staff[E].key,u[E]=y.staff[E].meter,f[E]=y.staff[E].clef;l.push(o(y))}h=!0}else h=!1,l.push(y)}return l}},2945:function(e){try{if("function"!=typeof window.CustomEvent){var t=function(e,t){t=t||{bubbles:!1,cancelable:!1,detail:void 0};var r=document.createEvent("CustomEvent");return r.initCustomEvent(e,t.bubbles,t.cancelable,t.detail),r};t.prototype=window.Event.prototype,window.CustomEvent=t}}catch(e){}var r=function(e){this.isEditArea=!0,"string"==typeof e?(this.textarea=document.getElementById(e),this.textarea||(this.textarea=document.querySelector(e))):this.textarea=e,this.initialText=this.textarea.value,this.isDragging=!1};r.prototype.addSelectionListener=function(e){this.textarea.onmousemove=function(t){this.isDragging&&e.fireSelectionChanged()}},r.prototype.addChangeListener=function(e){this.changelistener=e,this.textarea.onkeyup=function(){e.fireChanged()},this.textarea.onmousedown=function(){this.isDragging=!0,e.fireSelectionChanged()},this.textarea.onmouseup=function(){this.isDragging=!1,e.fireChanged()},this.textarea.onchange=function(){e.fireChanged()}},r.prototype.getSelection=function(){return{start:this.textarea.selectionStart,end:this.textarea.selectionEnd}},r.prototype.setSelection=function(e,t){if(this.textarea.setSelectionRange)this.textarea.setSelectionRange(e,t);else if(this.textarea.createTextRange){var r=this.textarea.createTextRange();r.collapse(!0),r.moveEnd("character",t),r.moveStart("character",e),r.select()}this.textarea.focus()},r.prototype.getString=function(){return this.textarea.value},r.prototype.setString=function(e){this.textarea.value=e,this.initialText=this.getString(),this.changelistener&&this.changelistener.fireChanged()},r.prototype.getElem=function(){return this.textarea},e.exports=r},5294:function(e,t,r){var n=r(5008),a=r(3450),i=r(5049),s=r(6859),o=r(2945),c=function(e,t){this.abcjsParams=function(e){var t,r={};if(e.abcjsParams)for(t in e.abcjsParams)e.abcjsParams.hasOwnProperty(t)&&(r[t]=e.abcjsParams[t]);if(e.midi_options)for(t in e.midi_options)e.midi_options.hasOwnProperty(t)&&(r[t]=e.midi_options[t]);if(e.parser_options)for(t in e.parser_options)e.parser_options.hasOwnProperty(t)&&(r[t]=e.parser_options[t]);if(e.render_options)for(t in e.render_options)e.render_options.hasOwnProperty(t)&&(r[t]=e.render_options[t]);return r.tablature&&e.warnings_id&&(r.tablature.warnings_id=e.warnings_id),r}(t),t.indicate_changed&&(this.indicate_changed=!0),"string"==typeof e?this.editarea=new o(e):e.isEditArea?this.editarea=e:this.editarea=new o(e),this.editarea.addSelectionListener(this),this.editarea.addChangeListener(this),t.canvas_id?this.div=t.canvas_id:t.paper_id?this.div=t.paper_id:(this.div=document.createElement("DIV"),this.editarea.getElem().parentNode.insertBefore(this.div,this.editarea.getElem())),"string"==typeof this.div&&(this.div=document.getElementById(this.div)),t.selectionChangeCallback&&(this.selectionChangeCallback=t.selectionChangeCallback),this.clientClickListener=this.abcjsParams.clickListener,this.abcjsParams.clickListener=this.highlight.bind(this),t.synth&&i()&&(this.synth={el:t.synth.el,cursorControl:t.synth.cursorControl,options:t.synth.options}),t.generate_midi&&(this.generate_midi=t.generate_midi,this.abcjsParams.generateDownload&&("string"==typeof t.midi_download_id?this.downloadMidi=document.getElementById(t.midi_download_id):t.midi_download_id&&(this.downloadMidi=t.midi_download_id)),!1!==this.abcjsParams.generateInline&&("string"==typeof t.midi_id?this.inlineMidi=document.getElementById(t.midi_id):t.midi_id&&(this.inlineMidi=t.midi_id))),t.warnings_id?"string"==typeof t.warnings_id?this.warningsdiv=document.getElementById(t.warnings_id):this.warningsdiv=t.warnings_id:t.generate_warnings&&(this.warningsdiv=document.createElement("div"),this.div.parentNode.insertBefore(this.warningsdiv,this.div)),this.onchangeCallback=t.onchange,this.redrawCallback=t.redrawCallback,this.currentAbc="",this.tunes=[],this.bReentry=!1,this.parseABC(),this.modelChanged(),this.addClassName=function(e,t){return function(e,t){var r=e.className;return r.length>0&&(r===t||new RegExp("(^|\\s)"+t+"(\\s|$)").test(r))}(e,t)||(e.className+=(e.className?" ":"")+t),e},this.removeClassName=function(e,t){return e.className=n.strip(e.className.replace(new RegExp("(^|\\s+)"+t+"(\\s+|$)")," ")),e},this.setReadOnly=function(e){var t="abc_textarea_readonly",r=this.editarea.getElem();e?(r.setAttribute("readonly","yes"),this.addClassName(r,t)):(r.removeAttribute("readonly"),this.removeClassName(r,t))}};c.prototype.redrawMidi=function(){if(this.generate_midi&&!this.midiPause){var e=new window.CustomEvent("generateMidi",{detail:{tunes:this.tunes,abcjsParams:this.abcjsParams,downloadMidiEl:this.downloadMidi,inlineMidiEl:this.inlineMidi,engravingEl:this.div}});window.dispatchEvent(e)}if(this.synth){var t=this.synth.synthControl;this.synth.synthControl||(this.synth.synthControl=new a,this.synth.synthControl.load(this.synth.el,this.synth.cursorControl,this.synth.options)),this.synth.synthControl.setTune(this.tunes[0],t,this.synth.options)}},c.prototype.modelChanged=function(){if(!this.bReentry){this.bReentry=!0;try{this.timerId=null,this.redrawCallback&&this.redrawCallback(!0),this.synth&&this.synth.synthControl&&this.synth.synthControl.disable(!0),this.tunes=s(this.div,this.currentAbc,this.abcjsParams),this.tunes.length>0&&(this.warnings=this.tunes[0].warnings),this.redrawMidi(),this.redrawCallback&&this.redrawCallback(!1)}catch(e){console.error("ABCJS error: ",e),this.warnings||(this.warnings=[]),this.warnings.push(e.message)}this.warningsdiv&&(this.warningsdiv.innerHTML=this.warnings?this.warnings.join("<br />"):"No errors"),this.updateSelection(),this.bReentry=!1}},c.prototype.paramChanged=function(e){if(e)for(var t in e)e.hasOwnProperty(t)&&(this.abcjsParams[t]=e[t]);this.currentAbc="",this.fireChanged()},c.prototype.getTunes=function(){return this.tunes},c.prototype.synthParamChanged=function(e){if(this.synth){if(this.synth.options={},e)for(var t in e)e.hasOwnProperty(t)&&(this.synth.options[t]=e[t]);this.currentAbc="",this.fireChanged()}},c.prototype.parseABC=function(){var e=this.editarea.getString();return e===this.currentAbc?(this.updateSelection(),!1):(this.currentAbc=e,!0)},c.prototype.updateSelection=function(){var e=this.editarea.getSelection();try{this.tunes.length>0&&this.tunes[0].engraver&&this.tunes[0].engraver.rangeHighlight(e.start,e.end)}catch(e){}this.selectionChangeCallback&&this.selectionChangeCallback(e.start,e.end)},c.prototype.fireSelectionChanged=function(){this.updateSelection()},c.prototype.setDirtyStyle=function(e){if(void 0!==this.indicate_changed){var t,r,a="abc_textarea_dirty",i=this.editarea.getElem();e?function(e,t){var r=e.className;return r.length>0&&(r===t||new RegExp("(^|\\s)"+t+"(\\s|$)").test(r))}(t=i,r=a)||(t.className+=(t.className?" ":"")+r):function(e,t){e.className=n.strip(e.className.replace(new RegExp("(^|\\s+)"+t+"(\\s+|$)")," "))}(i,a)}},c.prototype.fireChanged=function(){if(!this.bIsPaused&&this.parseABC()){var e=this;this.timerId&&clearTimeout(this.timerId),this.timerId=setTimeout(function(){e.modelChanged()},300);var t=this.isDirty();this.wasDirty!==t&&(this.wasDirty=t,this.setDirtyStyle(t)),this.onchangeCallback&&this.onchangeCallback(this)}},c.prototype.setNotDirty=function(){this.editarea.initialText=this.editarea.getString(),this.wasDirty=!1,this.setDirtyStyle(!1)},c.prototype.isDirty=function(){return void 0!==this.indicate_changed&&this.editarea.initialText!==this.editarea.getString()},c.prototype.highlight=function(e,t,r,n,a,i){this.editarea.setSelection(e.startChar,e.endChar),this.selectionChangeCallback&&this.selectionChangeCallback(e.startChar,e.endChar),this.clientClickListener&&this.clientClickListener(e,t,r,n,a,i)},c.prototype.pause=function(e){this.bIsPaused=e,e||this.fireChanged()},c.prototype.millisecondsPerMeasure=function(){return this.synth&&this.synth.synthControl&&this.synth.synthControl.visualObj?this.synth.synthControl.visualObj.millisecondsPerMeasure():0},c.prototype.pauseMidi=function(e){this.midiPause=e,e||this.redrawMidi()},e.exports=c},3284:function(e,t,r){var n,a=r(9991);!function(){"use strict";function e(e,t,r){for(var n=Object.keys(t),a=0;a<n.length;a++)n[a]=parseFloat(n[a]);n.sort(function(e,t){return e-t});for(var i=0,s=0;s<n.length;s++){var o=t[n[s]];if(n[s]>i){var c=(n[s]-i)*r;e.addRest(c),i=n[s]}for(var l=0;l<o.length;l++){var h=o[l];h.volume?e.startNote(h.pitch,h.volume,h.cents):e.endNote(h.pitch)}}}n=function(t,r){void 0===r&&(r={});var n=t.setUpAudio(r),i=a(),s=t.metaText?t.metaText.title:void 0;s&&s.length>128&&(s=s.substring(0,124)+"...");var o=t.getKeySignature(),c=t.getMeterFraction(),l=n.tempo,h=l/60;8===c.den&&5!==c.num&&7!==c.num&&(h=(l=6e4/(t.millisecondsPerMeasure()/c.num)/2)/60),i.setGlobalInfo(l,s,o,c);for(var u=0;u<n.tracks.length;u++){i.startTrack();for(var d={},f=0;f<n.tracks[u].length;f++){var p=n.tracks[u][f];switch(p.cmd){case"text":i.setText(p.type,p.text);break;case"program":var m=0;r.pan&&r.pan.length>u&&(m=r.pan[u]),128===p.instrument?(i.setChannel(9,m),i.setInstrument(0)):(i.setChannel(p.channel,m),i.setInstrument(p.instrument));break;case"note":var g=p.gap*h,v=p.start,b=v+p.duration-g;d[v]||(d[v]=[]),d[v].push({pitch:p.pitch,volume:p.volume,cents:p.cents}),d[b]||(d[b]=[]),d[b].push({pitch:p.pitch,volume:0});break;default:console.log("MIDI create Unknown: "+p.cmd)}}e(i,d,1920),i.endTrack()}return i.getData()}}(),e.exports=n},5008:function(e){var t={cloneArray:function(e){for(var t=[],r=0;r<e.length;r++)t.push(Object.assign({},e[r]));return t},cloneHashOfHash:function(e){var t={};for(var r in e)e.hasOwnProperty(r)&&(t[r]=Object.assign({},e[r]));return t},cloneHashOfArrayOfHash:function(e){var r={};for(var n in e)e.hasOwnProperty(n)&&(r[n]=t.cloneArray(e[n]));return r},strip:function(e){return e.replace(/^\s+/,"").replace(/\s+$/,"")},startsWith:function(e,t){return 0===e.indexOf(t)},endsWith:function(e,t){var r=e.length-t.length;return r>=0&&e.lastIndexOf(t)===r},last:function(e){return 0===e.length?null:e[e.length-1]}};e.exports=t},8905:function(e,t,r){var n=r(5008),a=r(8360),i=r(9928),s=r(6476),o=r(1881),c=r(1756),l=r(6225),h=r(6780),u=r(575);e.exports=function(){"use strict";var e,t=new h,r=new u(t),d="",f="";function p(e,t,r){e.positioning||(e.positioning={}),e.positioning[t]=r}function m(e,t,r){e.fonts||(e.fonts={}),e.fonts[t]=r}this.getTune=function(){var e={formatting:t.formatting,lines:t.lines,media:t.media,metaText:t.metaText,metaTextInfo:t.metaTextInfo,version:t.version,addElementToEvents:t.addElementToEvents,addUsefulCallbackInfo:t.addUsefulCallbackInfo,getTotalTime:t.getTotalTime,getTotalBeats:t.getTotalBeats,getBarLength:t.getBarLength,getBeatLength:t.getBeatLength,getBeatsPerMeasure:t.getBeatsPerMeasure,getBpm:t.getBpm,getMeter:t.getMeter,getMeterFraction:t.getMeterFraction,getPickupLength:t.getPickupLength,getKeySignature:t.getKeySignature,getElementFromChar:t.getElementFromChar,makeVoicesArray:t.makeVoicesArray,millisecondsPerMeasure:t.millisecondsPerMeasure,setupEvents:t.setupEvents,setTiming:t.setTiming,setUpAudio:t.setUpAudio,deline:t.deline,findSelectableElement:t.findSelectableElement,getSelectableArray:t.getSelectableArray};return t.lineBreaks&&(e.lineBreaks=t.lineBreaks),t.visualTranspose&&(e.visualTranspose=t.visualTranspose),t.chordGrid&&(e.chordGrid=t.chordGrid),e};var g,v,b={reset:function(){for(var e in this)this.hasOwnProperty(e)&&"function"!=typeof this[e]&&delete this[e];this.iChar=0,this.key={accidentals:[],root:"none",acc:"",mode:""},this.meter=null,this.origMeter=null,this.hasMainTitle=!1,this.default_length=.125,this.clef={type:"treble",verticalPos:0},this.octave=0,this.next_note_duration=0,this.start_new_line=!0,this.is_in_header=!0,this.partForNextLine={},this.tempoForNextLine=[],this.havent_set_length=!0,this.voices={},this.staves=[],this.macros={},this.currBarNumber=1,this.barCounter={},this.ignoredDecorations=[],this.score_is_present=!1,this.inEnding=!1,this.inTie=[],this.inTieChord={},this.vocalPosition="auto",this.dynamicPosition="auto",this.chordPosition="auto",this.ornamentPosition="auto",this.volumePosition="auto",this.openSlurs=[],this.freegchord=!1,this.endingHoldOver={}},differentFont:function(e,t){return this[e].decoration!==t[e].decoration||this[e].face!==t[e].face||this[e].size!==t[e].size||this[e].style!==t[e].style||this[e].weight!==t[e].weight},addFormattingOptions:function(e,t,r){"note"===r?("auto"!==this.vocalPosition&&p(e,"vocalPosition",this.vocalPosition),"auto"!==this.dynamicPosition&&p(e,"dynamicPosition",this.dynamicPosition),"auto"!==this.chordPosition&&p(e,"chordPosition",this.chordPosition),"auto"!==this.ornamentPosition&&p(e,"ornamentPosition",this.ornamentPosition),"auto"!==this.volumePosition&&p(e,"volumePosition",this.volumePosition),this.differentFont("annotationfont",t)&&m(e,"annotationfont",this.annotationfont),this.differentFont("gchordfont",t)&&m(e,"gchordfont",this.gchordfont),this.differentFont("vocalfont",t)&&m(e,"vocalfont",this.vocalfont),this.differentFont("tripletfont",t)&&m(e,"tripletfont",this.tripletfont)):"bar"===r&&("auto"!==this.dynamicPosition&&p(e,"dynamicPosition",this.dynamicPosition),"auto"!==this.chordPosition&&p(e,"chordPosition",this.chordPosition),"auto"!==this.ornamentPosition&&p(e,"ornamentPosition",this.ornamentPosition),"auto"!==this.volumePosition&&p(e,"volumePosition",this.volumePosition),this.differentFont("measurefont",t)&&m(e,"measurefont",this.measurefont),this.differentFont("repeatfont",t)&&m(e,"repeatfont",this.repeatfont))},duplicateStartEndingHoldOvers:function(){this.endingHoldOver={inTie:[],inTieChord:{}};for(var e=0;e<this.inTie.length;e++)if(this.endingHoldOver.inTie.push([]),this.inTie[e])for(var t=0;t<this.inTie[e].length;t++)this.endingHoldOver.inTie[e].push(this.inTie[e][t]);for(var r in this.inTieChord)this.inTieChord.hasOwnProperty(r)&&(this.endingHoldOver.inTieChord[r]=this.inTieChord[r])},restoreStartEndingHoldOvers:function(){if(this.endingHoldOver.inTie){this.inTie=[],this.inTieChord={};for(var e=0;e<this.endingHoldOver.inTie.length;e++){this.inTie.push([]);for(var t=0;t<this.endingHoldOver.inTie[e].length;t++)this.inTie[e].push(this.endingHoldOver.inTie[e][t])}for(var r in this.endingHoldOver.inTieChord)this.endingHoldOver.inTieChord.hasOwnProperty(r)&&(this.inTieChord[r]=this.endingHoldOver.inTieChord[r])}}},y=function(e){var t=e.replace(/\x12/g," ");return(t=(t=t.replace(/&/g,"&")).replace(/</g,"<")).replace(/>/g,">")},x=function(t,r,n){r||(r=" ");var a=r[n];" "!==a&&a||(a="SPACE");var i,s=y(r.substring(n-64,n))+'<span style="text-decoration:underline;font-size:1.3em;font-weight:bold;">'+a+"</span>"+y(r.substring(n+1).substring(0,64));!function(e){b.warnings||(b.warnings=[]),b.warnings.push(e)}("Music Line:"+e.lineIndex+":"+(n+1)+": "+t+": "+s),i={message:t,line:r,startChar:b.iChar+n,column:n},b.warningObjects||(b.warningObjects=[]),b.warningObjects.push(i)};this.getWarnings=function(){return b.warnings},this.getWarningObjects=function(){return b.warningObjects};var k=function(t,r){if(r.indexOf("")>=0)d+=r;else if(r=d+r,d="",t){"-"!==(r=n.strip(r))[r.length-1]&&(r+=" ");for(var a=[],i=0,s=!1,o=function(t){var o=n.strip(r.substring(i,t));if(o=o.replace(/\\([-_*|~])/g,"$1"),i=t+1,o.length>0){s&&(o=o.replace(/~/g," "));var c=r[t];return"_"!==c&&"-"!==c&&(c=" "),a.push({syllable:e.translateString(o),divider:c}),s=!1,!0}return!1},c=!1,l=0;l<r.length;l++){switch(r[l]){case" ":case"":o(l);break;case"-":!c&&!o(l)&&a.length>0&&(n.last(a).divider="-",a.push({skip:!0,to:"next"}));break;case"_":c||(o(l),a.push({skip:!0,to:"slur"}));break;case"*":c||(o(l),a.push({skip:!0,to:"next"}));break;case"|":c||(o(l),a.push({skip:!0,to:"bar"}));break;case"~":c||(s=!0)}c="\\"===r[l]}t.forEach(function(e){if(0!==a.length)if(a[0].skip){switch(a[0].to){case"next":case"slur":"note"===e.el_type&&null!==e.pitches&&a.shift();break;case"bar":"bar"===e.el_type&&a.shift()}"bar"!==e.el_type&&(void 0===e.lyric?e.lyric=[{syllable:"",divider:" "}]:e.lyric.push({syllable:"",divider:" "}))}else if("note"===e.el_type&&void 0===e.rest){var t=a.shift();t.syllable&&(t.syllable=t.syllable.replace(/ +/g," ")),void 0===e.lyric?e.lyric=[t]:e.lyric.push(t)}})}else x("Can't add words before the first line of music",t,0)},w=function(t,r){if(r.indexOf("")>=0)f+=r;else if(r=f+r,f="",t){"-"!==(r=n.strip(r))[r.length-1]&&(r+=" ");for(var a=[],i=0,s=!1,o=function(t){var o=n.strip(r.substring(i,t));if(i=t+1,o.length>0){s&&(o=o.replace(/~/g," "));var c=r[t];return"_"!==c&&"-"!==c&&(c=" "),a.push({syllable:e.translateString(o),divider:c}),s=!1,!0}return!1},c=0;c<r.length;c++)switch(r[c]){case" ":case"":o(c);break;case"-":!o(c)&&a.length>0&&(n.last(a).divider="-",a.push({skip:!0,to:"next"}));break;case"_":o(c),a.push({skip:!0,to:"slur"});break;case"*":o(c),a.push({skip:!0,to:"next"});break;case"|":o(c),a.push({skip:!0,to:"bar"});break;case"~":s=!0}t.forEach(function(e){if(0!==a.length)if(a[0].skip)switch(a[0].to){case"next":case"slur":"note"===e.el_type&&null!==e.pitches&&a.shift();break;case"bar":"bar"===e.el_type&&a.shift()}else if("note"===e.el_type&&void 0===e.rest){var t=a.shift();void 0===e.lyric?e.lyric=[t]:e.lyric.push(t)}})}else x("Can't add symbols before the first line of music",t,0)},C=function(e){if(n.startsWith(e,"%%")){var t=a.addDirective(e.substring(2));t&&x(t,e,2)}else{var i=e.indexOf("%");if(i>=0&&(e=e.substring(0,i)),0!==(e=e.replace(/\s+$/,"")).length)if(d)k(r.getCurrentVoice(),e.substring(2));else if(f)w(r.getCurrentVoice(),e.substring(2));else if(e.length<2||":"!==e[1]||v.lineContinuation)v.parseMusic(e);else{var s=g.parseHeader(e);s.regular&&v.parseMusic(e),s.newline&&v.startNewLine(),s.words&&k(r.getCurrentVoice(),e.substring(2)),s.symbols&&w(r.getCurrentVoice(),e.substring(2))}}};function T(e,t){e.push({el_type:"hint"});for(var r=0;r<t.length;r++){var n=t[r],a=Object.assign({},n);if(e.push(a),"bar"===n.el_type)return}}function S(e,t){for(var r=0;r<e.length;r++){var n=e[r],a=t[r];if(a)for(var i=0;i<a.voices.length;i++){var s=a.voices[i],o=n.voices[i];o&&T(o,s)}}}this.parse=function(h,u,p){u||(u={}),p||(p=0),t.reset();var m=(h=h.replace(/\r\n?/g,"\n")+"\n").split("\n\\");if(m.length>1){for(var y=1;y<m.length;y++)for(;m[y].length>0&&"\n"!==m[y][0];)m[y]=m[y].substr(1),m[y-1]+=" ";h=m.join(" ")}var T=(h=(h=h.replace(/\\%/g,"%")).replace(/\\([ \t]*)(%.*)*\n/g,function(e,t,r){return t+""+(r?Array(r.length+1).join(" "):"")+"\n"})).split("\n");0===n.last(T).length&&T.pop(),e=new o(T,b),g=new i(e,x,b,t,r),v=new s(e,x,b,t,r,g),u.print&&(t.media="print"),b.reset(),b.iChar=p,u.visualTranspose?(b.globalTranspose=parseInt(u.visualTranspose),0===b.globalTranspose?b.globalTranspose=void 0:r.setVisualTranspose(u.visualTranspose)):b.globalTranspose=void 0,u.lineBreaks&&(b.lineBreaks=u.lineBreaks),g.reset(e,x,b,t);try{u.format&&a.globalFormatting(u.format);for(var _=e.nextLine();_;){if(u.header_only&&!1===b.is_in_header)throw"normal_abort";if(u.stop_on_warning&&b.warnings)throw"normal_abort";var E=b.is_in_header;C(_),E&&!b.is_in_header&&(r.setRunningFont("annotationfont",b.annotationfont),r.setRunningFont("gchordfont",b.gchordfont),r.setRunningFont("tripletfont",b.tripletfont),r.setRunningFont("vocalfont",b.vocalfont)),_=e.nextLine()}d&&k(r.getCurrentVoice(),""),f&&w(r.getCurrentVoice(),""),b.openSlurs=r.cleanUp(b.barsperstaff,b.staffnonote,b.openSlurs)}catch(e){if("normal_abort"!==e)throw e}var M=792,A=612;switch(b.papersize){case"legal":M=1008,A=612;break;case"A4":M=842.4,A=597.6}if(b.landscape){var N=M;M=A,A=N}if(t.formatting.pagewidth||(t.formatting.pagewidth=A),t.formatting.pageheight||(t.formatting.pageheight=M),u.hint_measures&&function(){for(var e=0;e<t.lines.length;e++){var r=t.lines[e].staff;if(r){for(var n=e+1;n<t.lines.length&&void 0===t.lines[n].staff;)n++;n<t.lines.length&&S(r,t.lines[n].staff)}}}(),c.wrapLines(t,b.lineBreaks,b.barNumbers),u.chordGrid)try{t.chordGrid=l(t)}catch(e){switch(e.message){case"notCommonTime":x("Chord grid only works for 2/2 and 4/4 time.",0,0);break;case"noChords":x("No chords are found in the tune.",0,0);break;default:x(e.message,0,0)}}}}},9565:function(e,t,r){var n=r(5008);e.exports=function(e){"use strict";for(var t="",r=e.match(/(\s*)/),a=(e=n.strip(e)).split("\nX:"),i=1;i<a.length;i++)a[i]="X:"+a[i];var s=r?r[0].length:0,o=[];a.forEach(function(e){o.push({abc:e,startPos:s}),s+=e.length+1}),o.length>1&&!n.startsWith(o[0].abc,"X:")&&o.shift().abc.split("\n").forEach(function(e){n.startsWith(e,"%%")&&(t+=e+"\n")});var c=t;return o.forEach(function(e){var r=e.abc.indexOf("\n\n");r>0&&(e.abc=e.abc.substring(0,r)),e.pure=e.abc,e.abc=t+e.abc,e.title="";var a=e.pure.split("T:");a.length>1&&(a=a[1].split("\n"),e.title=n.strip(a[0]));var i=e.pure.substring(2,e.pure.indexOf("\n"));e.id=n.strip(i)}),{header:c,tunes:o}}},8360:function(e,t,r){var n=r(5008),a={};!function(){"use strict";var e,t,r,i,s;a.initialize=function(n,a,o,c,l){e=n,t=a,i=c,s=l,(r=o).annotationfont={face:"Helvetica",size:12,weight:"normal",style:"normal",decoration:"none"},r.gchordfont={face:"Helvetica",size:12,weight:"normal",style:"normal",decoration:"none"},r.historyfont={face:'"Times New Roman"',size:16,weight:"normal",style:"normal",decoration:"none"},r.infofont={face:'"Times New Roman"',size:14,weight:"normal",style:"italic",decoration:"none"},r.measurefont={face:'"Times New Roman"',size:14,weight:"normal",style:"italic",decoration:"none"},r.partsfont={face:'"Times New Roman"',size:15,weight:"normal",style:"normal",decoration:"none"},r.repeatfont={face:'"Times New Roman"',size:13,weight:"normal",style:"normal",decoration:"none"},r.textfont={face:'"Times New Roman"',size:16,weight:"normal",style:"normal",decoration:"none"},r.tripletfont={face:"Times",size:11,weight:"normal",style:"italic",decoration:"none"},r.vocalfont={face:'"Times New Roman"',size:13,weight:"bold",style:"normal",decoration:"none"},r.wordsfont={face:'"Times New Roman"',size:16,weight:"normal",style:"normal",decoration:"none"},i.formatting.composerfont={face:'"Times New Roman"',size:14,weight:"normal",style:"italic",decoration:"none"},i.formatting.subtitlefont={face:'"Times New Roman"',size:16,weight:"normal",style:"normal",decoration:"none"},i.formatting.tempofont={face:'"Times New Roman"',size:15,weight:"bold",style:"normal",decoration:"none"},i.formatting.titlefont={face:'"Times New Roman"',size:20,weight:"normal",style:"normal",decoration:"none"},i.formatting.footerfont={face:'"Times New Roman"',size:12,weight:"normal",style:"normal",decoration:"none"},i.formatting.headerfont={face:'"Times New Roman"',size:12,weight:"normal",style:"normal",decoration:"none"},i.formatting.voicefont={face:'"Times New Roman"',size:13,weight:"bold",style:"normal",decoration:"none"},i.formatting.tablabelfont={face:'"Trebuchet MS"',size:16,weight:"normal",style:"normal",decoration:"none"},i.formatting.tabnumberfont={face:'"Arial"',size:11,weight:"normal",style:"normal",decoration:"none"},i.formatting.tabgracefont={face:'"Arial"',size:8,weight:"normal",style:"normal",decoration:"none"},i.formatting.annotationfont=r.annotationfont,i.formatting.gchordfont=r.gchordfont,i.formatting.historyfont=r.historyfont,i.formatting.infofont=r.infofont,i.formatting.measurefont=r.measurefont,i.formatting.partsfont=r.partsfont,i.formatting.repeatfont=r.repeatfont,i.formatting.textfont=r.textfont,i.formatting.tripletfont=r.tripletfont,i.formatting.vocalfont=r.vocalfont,i.formatting.wordsfont=r.wordsfont};var o={gchordfont:!0,measurefont:!0,partsfont:!0,annotationfont:!0,composerfont:!0,historyfont:!0,infofont:!0,subtitlefont:!0,textfont:!0,titlefont:!0,voicefont:!0},c=function(e,r,n,a,i){function s(){var s=parseInt(e[0].token);return e.shift(),r?0===e.length?{face:r.face,weight:r.weight,style:r.style,decoration:r.decoration,size:s}:1===e.length&&"box"===e[0].token&&o[i]?{face:r.face,weight:r.weight,style:r.style,decoration:r.decoration,size:s,box:!0}:(t("Extra parameters in font definition.",n,a),{face:r.face,weight:r.weight,style:r.style,decoration:r.decoration,size:s}):(t("Can't set just the size of the font since there is no default value.",n,a),{face:'"Times New Roman"',weight:"normal",style:"normal",decoration:"none",size:s})}if("*"===e[0].token){if(e.shift(),"number"===e[0].type)return s();t("Expected font size number after *.",n,a)}if("number"===e[0].type)return s();for(var c,l=[],h="normal",u="normal",d="none",f=!1,p="face",m=!1;e.length;){var g=e.shift(),v=g.token.toLowerCase();switch(p){case"face":m||"utf"!==v&&"number"!==g.type&&"bold"!==v&&"italic"!==v&&"underline"!==v&&"box"!==v?l.length>0&&"-"===g.token?(m=!0,l[l.length-1]=l[l.length-1]+g.token):m?(m=!1,l[l.length-1]=l[l.length-1]+g.token):l.push(g.token):"number"===g.type?(c?t("Font size specified twice in font definition.",n,a):c=g.token,p="modifier"):"bold"===v?h="bold":"italic"===v?u="italic":"underline"===v?d="underline":"box"===v?(o[i]?f=!0:t('This font style doesn\'t support "box"',n,a),p="finished"):"utf"===v?(g=e.shift(),p="size"):t("Unknown parameter "+g.token+" in font definition.",n,a);break;case"size":"number"===g.type?c?t("Font size specified twice in font definition.",n,a):c=g.token:t("Expected font size in font definition.",n,a),p="modifier";break;case"modifier":"bold"===v?h="bold":"italic"===v?u="italic":"underline"===v?d="underline":"box"===v?(o[i]?f=!0:t('This font style doesn\'t support "box"',n,a),p="finished"):t("Unknown parameter "+g.token+" in font definition.",n,a);break;case"finished":t('Extra characters found after "box" in font definition.',n,a)}}void 0===c?r?c=r.size:(t("Must specify the size of the font since there is no default value.",n,a),c=12):c=parseFloat(c),""===(l=l.join(" "))&&(r?l=r.face:(t("Must specify the name of the font since there is no default value.",n,a),l="sans-serif"));var b=function(e){switch(e){case"Arial-Italic":return{face:"Arial",weight:"normal",style:"italic",decoration:"none"};case"Arial-Bold":return{face:"Arial",weight:"bold",style:"normal",decoration:"none"};case"Bookman-Demi":return{face:"Bookman,serif",weight:"bold",style:"normal",decoration:"none"};case"Bookman-DemiItalic":return{face:"Bookman,serif",weight:"bold",style:"italic",decoration:"none"};case"Bookman-Light":return{face:"Bookman,serif",weight:"normal",style:"normal",decoration:"none"};case"Bookman-LightItalic":return{face:"Bookman,serif",weight:"normal",style:"italic",decoration:"none"};case"Courier":return{face:'"Courier New"',weight:"normal",style:"normal",decoration:"none"};case"Courier-Oblique":return{face:'"Courier New"',weight:"normal",style:"italic",decoration:"none"};case"Courier-Bold":return{face:'"Courier New"',weight:"bold",style:"normal",decoration:"none"};case"Courier-BoldOblique":return{face:'"Courier New"',weight:"bold",style:"italic",decoration:"none"};case"AvantGarde-Book":return{face:"AvantGarde,Arial",weight:"normal",style:"normal",decoration:"none"};case"AvantGarde-BookOblique":return{face:"AvantGarde,Arial",weight:"normal",style:"italic",decoration:"none"};case"AvantGarde-Demi":case"Avant-Garde-Demi":return{face:"AvantGarde,Arial",weight:"bold",style:"normal",decoration:"none"};case"AvantGarde-DemiOblique":return{face:"AvantGarde,Arial",weight:"bold",style:"italic",decoration:"none"};case"Helvetica-Oblique":return{face:"Helvetica",weight:"normal",style:"italic",decoration:"none"};case"Helvetica-Bold":return{face:"Helvetica",weight:"bold",style:"normal",decoration:"none"};case"Helvetica-BoldOblique":return{face:"Helvetica",weight:"bold",style:"italic",decoration:"none"};case"Helvetica-Narrow":return{face:'"Helvetica Narrow",Helvetica',weight:"normal",style:"normal",decoration:"none"};case"Helvetica-Narrow-Oblique":return{face:'"Helvetica Narrow",Helvetica',weight:"normal",style:"italic",decoration:"none"};case"Helvetica-Narrow-Bold":return{face:'"Helvetica Narrow",Helvetica',weight:"bold",style:"normal",decoration:"none"};case"Helvetica-Narrow-BoldOblique":return{face:'"Helvetica Narrow",Helvetica',weight:"bold",style:"italic",decoration:"none"};case"Palatino-Roman":return{face:"Palatino",weight:"normal",style:"normal",decoration:"none"};case"Palatino-Italic":return{face:"Palatino",weight:"normal",style:"italic",decoration:"none"};case"Palatino-Bold":return{face:"Palatino",weight:"bold",style:"normal",decoration:"none"};case"Palatino-BoldItalic":return{face:"Palatino",weight:"bold",style:"italic",decoration:"none"};case"NewCenturySchlbk-Roman":return{face:'"New Century",serif',weight:"normal",style:"normal",decoration:"none"};case"NewCenturySchlbk-Italic":return{face:'"New Century",serif',weight:"normal",style:"italic",decoration:"none"};case"NewCenturySchlbk-Bold":return{face:'"New Century",serif',weight:"bold",style:"normal",decoration:"none"};case"NewCenturySchlbk-BoldItalic":return{face:'"New Century",serif',weight:"bold",style:"italic",decoration:"none"};case"Times":case"Times-Roman":case"Times-Narrow":case"Times-Courier":case"Times-New-Roman":return{face:'"Times New Roman"',weight:"normal",style:"normal",decoration:"none"};case"Times-Italic":case"Times-Italics":return{face:'"Times New Roman"',weight:"normal",style:"italic",decoration:"none"};case"Times-Bold":return{face:'"Times New Roman"',weight:"bold",style:"normal",decoration:"none"};case"Times-BoldItalic":return{face:'"Times New Roman"',weight:"bold",style:"italic",decoration:"none"};case"ZapfChancery-MediumItalic":return{face:'"Zapf Chancery",cursive,serif',weight:"normal",style:"normal",decoration:"none"};default:return null}}(l),y={};return b?(y.face=b.face,y.weight=b.weight,y.style=b.style,y.decoration=b.decoration,y.size=c,f&&(y.box=!0),y):(y.face=l,y.weight=h,y.style=u,y.decoration=d,y.size=c,f&&(y.box=!0),y)},l=function(e,t,n){return 0===t.length?'Directive "'+e+'" requires a font as a parameter.':(r[e]=c(t,r[e],n,0,e),r.is_in_header&&(i.formatting[e]=r[e]),null)},h=function(e,t){var r="";t.forEach(function(e){r+=e.token});var n=parseFloat(r);if(isNaN(n)||0===n)return'Directive "'+e+'" requires a number as a parameter.';i.formatting.scale=n},u=["acoustic-bass-drum","bass-drum-1","side-stick","acoustic-snare","hand-clap","electric-snare","low-floor-tom","closed-hi-hat","high-floor-tom","pedal-hi-hat","low-tom","open-hi-hat","low-mid-tom","hi-mid-tom","crash-cymbal-1","high-tom","ride-cymbal-1","chinese-cymbal","ride-bell","tambourine","splash-cymbal","cowbell","crash-cymbal-2","vibraslap","ride-cymbal-2","hi-bongo","low-bongo","mute-hi-conga","open-hi-conga","low-conga","high-timbale","low-timbale","high-agogo","low-agogo","cabasa","maracas","short-whistle","long-whistle","short-guiro","long-guiro","claves","hi-wood-block","low-wood-block","mute-cuica","open-cuica","mute-triangle","open-triangle"],d=function(e,t,n,a,i){if(1!==n.length||"number"!==n[0].type)return'Directive "'+t+'" requires a number as a parameter.';var s=n[0].intt;return void 0!==a&&s<a?'Directive "'+t+'" requires a number greater than or equal to '+a+" as a parameter.":void 0!==i&&s>i?'Directive "'+t+'" requires a number less than or equal to '+i+" as a parameter.":(r[e]=s,null)},f=function(e,t,n){if(1===n.length&&("true"===n[0].token||"false"===n[0].token))return r[e]="true"===n[0].token,null;var a=d(e,t,n,0,1);return null!==a?a:(r[e]=1===r[e],null)},p=function(e,t,n,a){if(1!==n.length)return'Directive "'+t+'" requires one of [ '+a.join(", ")+" ] as a parameter.";for(var i=n[0].token,s=!1,o=0;!s&&o<a.length;o++)a[o]===i&&(s=!0);return s?(r[e]=i,null):'Directive "'+t+'" requires one of [ '+a.join(", ")+" ] as a parameter."},m=["nobarlines","barlines","beataccents","nobeataccents","droneon","droneoff","drumon","drumoff","fermatafixed","fermataproportional","gchordon","gchordoff","controlcombo","temperamentnormal","noportamento"],g=["gchord","ptstress","beatstring"],v=["bassvol","chordvol","c","channel","beatmod","deltaloudness","drumbars","gracedivider","makechordchannels","randomchordattack","chordattack","stressmodel","transpose","rtranspose","vol","volinc","gchordbars"],b=["program"],y=["ratio","snt","bendvelocity","pitchbend","control","temperamentlinear"],x=["beat"],k=["drone"],w=["portamento"],C=["expand","grace","trim"],T=["drum","chordname"],S=["bassprog","chordprog"];a.parseFontChangeLine=function(e){var t=(e=e.replace(/\$\$/g,"")).split("$");if(t.length>1&&r.setfont){var n=[];""!==t[0]&&n.push({text:t[0]});for(var a=1;a<t.length;a++)if("0"===t[a][0])n.push({text:t[a].substring(1).replace(/\x03/g,"$$")});else{var i=parseInt(t[a][0],10);r.setfont[i]?n.push({font:r.setfont[i],text:t[a].substring(1).replace(/\x03/g,"$$")}):n[n.length-1].text+="$"+t[a].replace(/\x03/g,"$$")}return n}return e.replace(/\x03/g,"$$")};var _=["auto","above","below","hidden"];function E(e){if(0===e.length)return{value:1};if(1===e.length)if("number"===e[0].type){if(e[0].floatt>=0||e[0].floatt<=1)return{value:e[0].floatt}}else{if("false"===e[0].token)return{value:0};if("true"===e[0].token)return{value:1}}return{error:"Directive stretchlast requires zero or one parameter: false, true, or number between 0 and 1 (received "+e[0].token+")"}}a.addDirective=function(o){var M=e.tokenize(o,0,o.length);if(0===M.length||"alpha"!==M[0].type)return null;var A=o.substring(o.indexOf(M[0].token)+M[0].token.length);A=e.stripComment(A);var N,B=M.shift().token.toLowerCase(),P="";switch(B){case"bagpipes":i.formatting.bagpipes=!0;break;case"flatbeams":i.formatting.flatbeams=!0;break;case"jazzchords":i.formatting.jazzchords=!0;break;case"accentAbove":i.formatting.accentAbove=!0;break;case"germanAlphabet":i.formatting.germanAlphabet=!0;break;case"landscape":r.landscape=!0;break;case"papersize":r.papersize=A;break;case"graceslurs":if(1!==M.length)return"Directive graceslurs requires one parameter: 0 or 1";if("0"===M[0].token||"false"===M[0].token)i.formatting.graceSlurs=!1;else{if("1"!==M[0].token&&"true"!==M[0].token)return"Directive graceslurs requires one parameter: 0 or 1 (received "+M[0].token+")";i.formatting.graceSlurs=!0}break;case"lineThickness":var L=E(M);if(void 0!==L.value&&(i.formatting.lineThickness=L.value),L.error)return L.error;break;case"stretchlast":var O=E(M);if(void 0!==O.value&&(i.formatting.stretchlast=O.value),O.error)return O.error;break;case"titlecaps":r.titlecaps=!0;break;case"titleleft":i.formatting.titleleft=!0;break;case"measurebox":i.formatting.measurebox=!0;break;case"vocal":return p("vocalPosition",B,M,_);case"dynamic":return p("dynamicPosition",B,M,_);case"gchord":return p("chordPosition",B,M,_);case"ornament":return p("ornamentPosition",B,M,_);case"volume":return p("volumePosition",B,M,_);case"botmargin":case"botspace":case"composerspace":case"indent":case"leftmargin":case"linesep":case"musicspace":case"partsspace":case"pageheight":case"pagewidth":case"rightmargin":case"stafftopmargin":case"staffsep":case"staffwidth":case"subtitlespace":case"sysstaffsep":case"systemsep":case"textspace":case"titlespace":case"topmargin":case"topspace":case"vocalspace":case"wordsspace":return function(t,r){var n=e.getMeasurement(r);return 0===n.used||0!==r.length?'Directive "'+t+'" requires a measurement as a parameter.':(i.formatting[t]=n.value,null)}(B,M);case"voicescale":if(1!==M.length||"number"!==M[0].type)return"voicescale requires one float as a parameter";var j=M.shift();return r.currentVoice&&(r.currentVoice.scale=j.floatt,s.changeVoiceScale(r.currentVoice.scale)),null;case"voicecolor":if(1!==M.length)return"voicecolor requires one string as a parameter";var H=M.shift();return r.currentVoice&&(r.currentVoice.color=H.token,s.changeVoiceColor(r.currentVoice.color)),null;case"vskip":var D=Math.round(function(t,r){var n=e.getMeasurement(r);return 0===n.used||0!==r.length?{error:'Directive "'+t+'" requires a measurement as a parameter.'}:n.value}(B,M));return D.error?D.error:(s.addSpacing(D),null);case"scale":h(B,M);break;case"sep":if(0===M.length)s.addSeparator(14,14,85,{startChar:r.iChar,endChar:r.iChar+5});else{var z=e.getMeasurement(M);if(0===z.used)return'Directive "'+B+'" requires 3 numbers: space above, space below, length of line';var I=z.value;if(0===(z=e.getMeasurement(M)).used)return'Directive "'+B+'" requires 3 numbers: space above, space below, length of line';var F=z.value;if(0===(z=e.getMeasurement(M)).used||0!==M.length)return'Directive "'+B+'" requires 3 numbers: space above, space below, length of line';var V=z.value;s.addSeparator(I,F,V,{startChar:r.iChar,endChar:r.iChar+A.length})}break;case"barsperstaff":if(null!==(P=d("barsperstaff",B,M)))return P;break;case"staffnonote":if(1!==M.length)return"Directive staffnonote requires one parameter: 0 or 1";if("0"===M[0].token)r.staffnonote=!0;else{if("1"!==M[0].token)return"Directive staffnonote requires one parameter: 0 or 1 (received "+M[0].token+")";r.staffnonote=!1}break;case"printtempo":if(null!==(P=f("printTempo",B,M)))return P;break;case"partsbox":if(null!==(P=f("partsBox",B,M)))return P;r.partsfont.box=r.partsBox;break;case"freegchord":if(null!==(P=f("freegchord",B,M)))return P;break;case"measurenb":case"barnumbers":if(null!==(P=d("barNumbers",B,M)))return P;break;case"setbarnb":if(1!==M.length||"number"!==M[0].type)return"Directive setbarnb requires a number as a parameter.";r.currBarNumber=s.setBarNumberImmediate(M[0].intt);break;case"keywarn":if(1!==M.length||"number"!==M[0].type||1!==M[0].intt&&0!==M[0].intt)return"Directive "+B+" requires 0 or 1 as a parameter.";r[B]=1===M[0].intt;break;case"begintext":var G="";for(N=e.nextLine();N&&0!==N.indexOf("%%endtext");){if(n.startsWith(N,"%%")){var Y=N.substring(2);G+=Y=Y.trim()+"\n"}else G+=N.trim()+"\n";N=e.nextLine()}s.addText(G,{startChar:r.iChar,endChar:r.iChar+G.length+7});break;case"continueall":r.continueall=!0;break;case"beginps":for(N=e.nextLine();N&&0!==N.indexOf("%%endps");)e.nextLine();t("Postscript ignored",o,0);break;case"deco":A.length>0&&r.ignoredDecorations.push(A.substring(0,A.indexOf(" "))),t("Decoration redefinition ignored",o,0);break;case"text":var q=e.translateString(A);s.addText(a.parseFontChangeLine(q),{startChar:r.iChar,endChar:r.iChar+A.length+7});break;case"center":var R=e.translateString(A);s.addCentered(a.parseFontChangeLine(R));break;case"font":break;case"setfont":var W=e.tokenize(A,0,A.length);if(W.length>=4&&"-"===W[0].token&&"number"===W[1].type){var X=parseInt(W[1].token);X>=1&&X<=9&&(r.setfont||(r.setfont=[]),W.shift(),W.shift(),r.setfont[X]=c(W,r.setfont[X],o,0,"setfont"))}break;case"gchordfont":case"partsfont":case"tripletfont":case"vocalfont":case"textfont":case"annotationfont":case"historyfont":case"infofont":case"measurefont":case"repeatfont":case"wordsfont":return l(B,M,o);case"composerfont":case"subtitlefont":case"tempofont":case"titlefont":case"voicefont":case"footerfont":case"headerfont":return function(e,t,r){return 0===t.length?'Directive "'+e+'" requires a font as a parameter.':(i.formatting[e]=c(t,i.formatting[e],r,0,e),null)}(B,M,o);case"barlabelfont":case"barnumberfont":case"barnumfont":return l("measurefont",M,o);case"staves":case"score":r.score_is_present=!0;for(var U,K=function(e,t,a,i,s){(t||0===r.staves.length)&&r.staves.push({index:r.staves.length,numVoices:0});var o=n.last(r.staves);void 0!==a&&void 0===o.bracket&&(o.bracket=a),void 0!==i&&void 0===o.brace&&(o.brace=i),s&&(o.connectBarLines="end"),void 0===r.voices[e]&&(r.voices[e]={staffNum:o.index,index:o.numVoices},o.numVoices++)},$=!1,Q=!1,J=!1,Z=!1,ee=!1,te=!1,re=!1,ne=function(){if(re=!0,U){var e="start";U.staffNum>0&&("start"!==r.staves[U.staffNum-1].connectBarLines&&"continue"!==r.staves[U.staffNum-1].connectBarLines||(e="continue")),r.staves[U.staffNum].connectBarLines=e}};M.length;){var ae=M.shift();switch(ae.token){case"(":$?t("Can't nest parenthesis in %%score",o,ae.start):($=!0,Z=!0);break;case")":!$||Z?t("Unexpected close parenthesis in %%score",o,ae.start):$=!1;break;case"[":Q?t("Can't nest brackets in %%score",o,ae.start):(Q=!0,ee=!0);break;case"]":!Q||ee?t("Unexpected close bracket in %%score",o,ae.start):(Q=!1,r.staves[U.staffNum].bracket="end");break;case"{":J?t("Can't nest braces in %%score",o,ae.start):(J=!0,te=!0);break;case"}":!J||te?t("Unexpected close brace in %%score",o,ae.start):(J=!1,r.staves[U.staffNum].brace="end");break;case"|":ne();break;default:for(var ie="";("alpha"===ae.type||"number"===ae.type)&&(ie+=ae.token,ae.continueId);)ae=M.shift();K(ie,!$||Z,ee?"start":Q?"continue":void 0,te?"start":J?"continue":void 0,re),Z=!1,ee=!1,te=!1,re=!1,U=r.voices[ie],"staves"===B&&ne()}}break;case"maxstaves":var se=e.getInt(A);0===se.digits?t("Expected number of staves in maxstaves"):se.value>0&&(i.formatting.maxStaves=se.value);break;case"newpage":var oe=e.getInt(A);s.addNewPage(0===oe.digits?-1:oe.value);break;case"abc":var ce=A.split(" ");switch(ce[0]){case"-copyright":case"-creator":case"-edited-by":case"-version":case"-charset":var le=ce.shift();s.addMetaText(B+le,ce.join(" "),{startChar:r.iChar,endChar:r.iChar+A.length+5});break;default:return"Unknown directive: "+B+ce[0]}break;case"header":case"footer":var he=e.getMeat(A,0,A.length);'"'===(he=A.substring(he.start,he.end))[0]&&'"'===he[he.length-1]&&(he=he.substring(1,he.length-1));var ue,de=he.split("\t");ue=1===de.length?{left:"",center:de[0],right:""}:2===de.length?{left:de[0],center:de[1],right:""}:{left:de[0],center:de[1],right:de[2]},de.length>3&&t("Too many tabs in "+B+": "+de.length+" found.",A,0),s.addMetaTextObj(B,ue,{startChar:r.iChar,endChar:r.iChar+o.length});break;case"midi":var fe=e.tokenize(A,0,A.length,!0);fe.length>0&&"="===fe[0].token&&fe.shift(),0===fe.length?t("Expected midi command",A,0):function(e,r,n){var a=e.shift().token,i=[];if(m.indexOf(a)>=0)0!==e.length&&t("Unexpected parameter in MIDI "+a,n,0);else if(g.indexOf(a)>=0)1!==e.length?t("Expected one parameter in MIDI "+a,n,0):i.push(e[0].token);else if(v.indexOf(a)>=0)1!==e.length?t("Expected one parameter in MIDI "+a,n,0):"number"!==e[0].type?t("Expected one integer parameter in MIDI "+a,n,0):i.push(e[0].intt);else if(b.indexOf(a)>=0)1!==e.length&&2!==e.length?t("Expected one or two parameters in MIDI "+a,n,0):"number"!==e[0].type||2===e.length&&"number"!==e[1].type?t("Expected integer parameter in MIDI "+a,n,0):(i.push(e[0].intt),2===e.length&&i.push(e[1].intt));else if(y.indexOf(a)>=0)2!==e.length?t("Expected two parameters in MIDI "+a,n,0):"number"!==e[0].type||"number"!==e[1].type?t("Expected two integer parameters in MIDI "+a,n,0):(i.push(e[0].intt),i.push(e[1].intt));else if(w.indexOf(a)>=0)2!==e.length?t("Expected two parameters in MIDI "+a,n,0):"alpha"!==e[0].type||"number"!==e[1].type?t("Expected one string and one integer parameters in MIDI "+a,n,0):(i.push(e[0].token),i.push(e[1].intt));else if("drummap"===a)2===e.length&&"alpha"===e[0].type&&"number"===e[1].type?(r.formatting||(r.formatting={}),r.formatting.midi||(r.formatting.midi={}),r.formatting.midi.drummap||(r.formatting.midi.drummap={}),r.formatting.midi.drummap[e[0].token]=e[1].intt,i=r.formatting.midi.drummap):3===e.length&&"punct"===e[0].type&&"alpha"===e[1].type&&"number"===e[2].type?(r.formatting||(r.formatting={}),r.formatting.midi||(r.formatting.midi={}),r.formatting.midi.drummap||(r.formatting.midi.drummap={}),r.formatting.midi.drummap[e[0].token+e[1].token]=e[2].intt,i=r.formatting.midi.drummap):t("Expected one note name and one integer parameter in MIDI "+a,n,0);else if(C.indexOf(a)>=0)3!==e.length||"number"!==e[0].type||"/"!==e[1].token||"number"!==e[2].type?t("Expected fraction parameter in MIDI "+a,n,0):(i.push(e[0].intt),i.push(e[2].intt));else if(x.indexOf(a)>=0)4!==e.length?t("Expected four parameters in MIDI "+a,n,0):"number"!==e[0].type||"number"!==e[1].type||"number"!==e[2].type||"number"!==e[3].type?t("Expected four integer parameters in MIDI "+a,n,0):(i.push(e[0].intt),i.push(e[1].intt),i.push(e[2].intt),i.push(e[3].intt));else if(k.indexOf(a)>=0)5!==e.length?t("Expected five parameters in MIDI "+a,n,0):"number"!==e[0].type||"number"!==e[1].type||"number"!==e[2].type||"number"!==e[3].type||"number"!==e[4].type?t("Expected five integer parameters in MIDI "+a,n,0):(i.push(e[0].intt),i.push(e[1].intt),i.push(e[2].intt),i.push(e[3].intt),i.push(e[4].intt));else if(b.indexOf(a)>=0)1!==e.length||4!==e.length?t("Expected one or two parameters in MIDI "+a,n,0):"number"!==e[0].type?t("Expected integer parameter in MIDI "+a,n,0):4===e.length?("octave"!==e[1].token&&t("Expected octave parameter in MIDI "+a,n,0),"="!==e[2].token&&t("Expected octave parameter in MIDI "+a,n,0),"number"!==e[3].type&&t("Expected integer parameter for octave in MIDI "+a,n,0)):(i.push(e[0].intt),4===e.length&&i.push(e[3].intt));else if(T.indexOf(a)>=0)if(e.length<2)t("Expected string parameter and at least one integer parameter in MIDI "+a,n,0);else if("alpha"!==e[0].type)t("Expected string parameter and at least one integer parameter in MIDI "+a,n,0);else{var o=e.shift();for(i.push(o.token);e.length>0;)"number"!==(o=e.shift()).type&&t("Expected integer parameter in MIDI "+a,n,0),i.push(o.intt)}else if(S.indexOf(a)>=0)if(1!==e.length&&2!==e.length)t("Expected one or two parameters in MIDI "+a,n,0);else if("number"!==e[0].type)t("Expected integer parameter in MIDI "+a,n,0);else if(2===e.length&&"alpha"!==e[1].type)t("Expected alpha parameter in MIDI "+a,n,0);else if(i.push(e[0].intt),2===e.length){var c=e[1].token;-1!=c.indexOf("octave=")?(c=c.replace("octave=",""),c=parseInt(c),isNaN(c)?t("Expected octave value in MIDI"+a):(c<-1&&(t("Expected octave= in MIDI "+a+" to be >= -1 (recv:"+c+")"),c=-1),c>3&&(t("Expected octave= in MIDI "+a+" to be <= 3 (recv:"+c+")"),c=3),i.push(c))):t("Expected octave= in MIDI"+a)}s.hasBeginMusic()?s.appendElement("midi",-1,-1,{cmd:a,params:i}):(void 0===r.formatting.midi&&(r.formatting.midi={}),r.formatting.midi[a]=i)}(fe,i,A);break;case"percmap":var pe=function(e){var t=e.split(/\s+/);if(2!==t.length&&3!==t.length)return{error:'Expected parameters "abc-note", "drum-sound", and optionally "note-head"'};var r=t[0],n=parseInt(t[1],10);if((isNaN(n)||n<35||n>81)&&t[1]&&(n=u.indexOf(t[1].toLowerCase())+35),isNaN(n)||n<35||n>81)return{error:'Expected drum name, received "'+t[1]+'"'};var a={sound:n};return 3===t.length&&(a.noteHead=t[2]),{key:r,value:a}}(A);pe.error?t(pe.error,o,8):(i.formatting.percmap||(i.formatting.percmap={}),i.formatting.percmap[pe.key]=pe.value);break;case"visualtranspose":var me=e.getInt(A);0===me.digits?t("Expected number of half steps in visualTranspose"):r.globalTranspose=me.value;break;case"map":case"playtempo":case"auquality":case"continuous":case"nobarcheck":i.formatting[B]=A;break;default:return"Unknown directive: "+B}return null},a.globalFormatting=function(n){for(var a in n)if(n.hasOwnProperty(a)){var s,o=""+n[a],c=e.tokenize(o,0,o.length);switch(a){case"titlefont":case"gchordfont":case"composerfont":case"footerfont":case"headerfont":case"historyfont":case"infofont":case"measurefont":case"partsfont":case"repeatfont":case"subtitlefont":case"tempofont":case"textfont":case"voicefont":case"tripletfont":case"vocalfont":case"wordsfont":case"annotationfont":case"tablabelfont":case"tabnumberfont":case"tabgracefont":l(a,c,o);break;case"scale":h(a,c);break;case"partsbox":null!==(s=f("partsBox",a,c))&&t(s),r.partsfont.box=r.partsBox;break;case"freegchord":null!==(s=f("freegchord",a,c))&&t(s);break;case"fontboxpadding":1===c.length&&"number"===c[0].type||t('Directive "'+a+'" requires a number as a parameter.'),i.formatting.fontboxpadding=c[0].floatt;break;case"stafftopmargin":1===c.length&&"number"===c[0].type||t('Directive "'+a+'" requires a number as a parameter.'),i.formatting.stafftopmargin=c[0].floatt;break;case"stretchlast":var u=E(c);if(void 0!==u.value&&(i.formatting.stretchlast=u.value),u.error)return u.error;break;default:t("Formatting directive unrecognized: ",a,0)}}}}(),e.exports=a},9928:function(e,t,r){var n=r(5008),a=r(8360),i=r(9708);e.exports=function(e,t,r,s,o){this.reset=function(e,t,r,n){i.initialize(e,t,r,n,o),a.initialize(e,t,r,n,o)},this.reset(e,t,r,s),this.setTitle=function(e,t){r.hasMainTitle?o.addSubtitle(e,{startChar:r.iChar,endChar:r.iChar+t+2}):(o.addMetaText("title",e,{startChar:r.iChar,endChar:r.iChar+t+2}),r.hasMainTitle=!0)},this.setMeter=function(n){if("C"===(n=e.stripComment(n)))return!0===r.havent_set_length&&(r.default_length=.125,r.havent_set_length=!1),{type:"common_time"};if("C|"===n)return!0===r.havent_set_length&&(r.default_length=.125,r.havent_set_length=!1),{type:"cut_time"};if("o"===n)return!0===r.havent_set_length&&(r.default_length=.125,r.havent_set_length=!1),{type:"tempus_perfectum"};if("c"===n)return!0===r.havent_set_length&&(r.default_length=.125,r.havent_set_length=!1),{type:"tempus_imperfectum"};if("o."===n)return!0===r.havent_set_length&&(r.default_length=.125,r.havent_set_length=!1),{type:"tempus_perfectum_prolatio"};if("c."===n)return!0===r.havent_set_length&&(r.default_length=.125,r.havent_set_length=!1),{type:"tempus_imperfectum_prolatio"};if(0===n.length||"none"===n.toLowerCase())return!0===r.havent_set_length&&(r.default_length=.125,r.havent_set_length=!1),null;var a=e.tokenize(n,0,n.length);try{var i=function(){var e=function(){var e={value:0,num:""},t=a.shift();for("("===t.token&&(t=a.shift());;){if("number"!==t.type)throw"Expected top number of meter";if(e.value+=parseInt(t.token),e.num+=t.token,0===a.length||"/"===a[0].token)return e;if(")"===(t=a.shift()).token){if(0===a.length||"/"===a[0].token)return e;throw"Unexpected paren in meter"}if("."!==t.token&&"+"!==t.token)throw"Expected top number of meter";if(e.num+=t.token,0===a.length)throw"Expected top number of meter";t=a.shift()}return e}();if(0===a.length)return e;var t=a.shift();if("/"!==t.token)throw"Expected slash in meter";if("number"!==(t=a.shift()).type)throw"Expected bottom number of meter";return e.den=t.token,e.value=e.value/parseInt(e.den),e};if(0===a.length)throw"Expected meter definition in M: line";for(var s={type:"specified",value:[]},o=0;;){var c=i();o+=c.value;var l={num:c.num};if(void 0!==c.den&&(l.den=c.den),s.value.push(l),0===a.length)break}return!0===r.havent_set_length&&(r.default_length=o<.75?.0625:.125,r.havent_set_length=!1),s}catch(e){t(e,n,0)}return null},this.calcTempo=function(e){var t=1/4;r.meter&&"specified"===r.meter.type?t=1/parseInt(r.meter.value[0].den):r.origMeter&&"specified"===r.origMeter.type&&(t=1/parseInt(r.origMeter.value[0].den));for(var n=0;n<e.duration;n++)e.duration[n]=t*e.duration[n];return e},this.resolveTempo=function(){r.tempo&&(this.calcTempo(r.tempo),s.metaText.tempo=r.tempo,delete r.tempo)},this.addUserDefinition=function(e,a,i){var s=e.indexOf("=",a);if(-1!==s){var o=n.strip(e.substring(a,s)),c=n.strip(e.substring(s+1));1===o.length?-1!=="HIJKLMNOPQRSTUVWXYhijklmnopqrstuvw~".indexOf(o)?0!==c.length?(void 0===r.macros&&(r.macros={}),r.macros[o]=c):t("Missing macro definition",e,a):t("Macro definitions must be H-Y, h-w, or tilde",e,a):t("Macro definitions can only be one character",e,a)}else t("Need an = in a macro definition",e,a)},this.setDefaultLength=function(e,t,n){var a=e.substring(t,n).replace(/ /g,"").split("/");if(2===a.length){var i=parseInt(a[0]),s=parseInt(a[1]);s>0&&(r.default_length=i/s,r.havent_set_length=!1)}else 1===a.length&&"1"===a[0]&&(r.default_length=1,r.havent_set_length=!1)};var c={larghissimo:20,adagissimo:24,sostenuto:28,grave:32,largo:40,lento:50,larghetto:60,adagio:68,adagietto:74,andante:80,andantino:88,"marcia moderato":84,"andante moderato":100,moderato:112,allegretto:116,"allegro moderato":120,allegro:126,animato:132,agitato:140,veloce:148,"mosso vivo":156,vivace:164,vivacissimo:172,allegrissimo:176,presto:184,prestissimo:210};this.setTempo=function(n,a,i,s){try{var o=e.tokenize(n,a,i);if(0===o.length)throw"Missing parameter in Q: field";var l={startChar:s+a-2,endChar:s+i},h=!0,u=o.shift();if("quote"===u.type&&(l.preString=u.token,u=o.shift(),0===o.length))return c[l.preString.toLowerCase()]&&(l.bpm=c[l.preString.toLowerCase()],l.suppressBpm=!0),{type:"immediate",tempo:l};if("alpha"===u.type&&"C"===u.token){if(0===o.length)throw"Missing tempo after C in Q: field";if("punct"===(u=o.shift()).type&&"="===u.token){if(0===o.length)throw"Missing tempo after = in Q: field";if("number"!==(u=o.shift()).type)throw"Expected number after = in Q: field";l.duration=[1],l.bpm=parseInt(u.token)}else{if("number"!==u.type)throw"Expected number or equal after C in Q: field";if(l.duration=[parseInt(u.token)],0===o.length)throw"Missing = after duration in Q: field";if("punct"!==(u=o.shift()).type||"="!==u.token)throw"Expected = after duration in Q: field";if(0===o.length)throw"Missing tempo after = in Q: field";if("number"!==(u=o.shift()).type)throw"Expected number after = in Q: field";l.bpm=parseInt(u.token)}}else{if("number"!==u.type)throw"Unknown value in Q: field";var d=parseInt(u.token);if(0===o.length||"quote"===o[0].type)l.duration=[1],l.bpm=d;else{if(h=!1,"punct"!==(u=o.shift()).type&&"/"!==u.token)throw"Expected fraction in Q: field";if("number"!==(u=o.shift()).type)throw"Expected fraction in Q: field";var f=parseInt(u.token);for(l.duration=[d/f];o.length>0&&"="!==o[0].token&&"quote"!==o[0].type;){if("number"!==(u=o.shift()).type)throw"Expected fraction in Q: field";if(d=parseInt(u.token),"punct"!==(u=o.shift()).type&&"/"!==u.token)throw"Expected fraction in Q: field";if("number"!==(u=o.shift()).type)throw"Expected fraction in Q: field";f=parseInt(u.token),l.duration.push(d/f)}if("punct"!==(u=o.shift()).type&&"="!==u.token)throw"Expected = in Q: field";if("number"!==(u=o.shift()).type)throw"Expected tempo in Q: field";l.bpm=parseInt(u.token)}}if(0!==o.length&&("quote"===(u=o.shift()).type&&(l.postString=u.token,u=o.shift()),0!==o.length))throw"Unexpected string at end of Q: field";return!1===r.printTempo&&(l.suppress=!0),{type:h?"delaySet":"immediate",tempo:l}}catch(e){return t(e,n,a),{type:"none"}}},this.letter_to_inline_header=function(n,c,l){var h=!1,u=e.eatWhiteSpace(n,c);if(c+=u,n.length>=c+5&&"["===n[c]&&":"===n[c+2]){var d=n.indexOf("]",c),f=r.iChar+c,p=r.iChar+d+1;switch(n.substring(c,c+3)){case"[I:":var m=a.addDirective(n.substring(c+3,d));return m&&t(m,n,c),[d-c+1+u];case"[M:":var g=this.setMeter(n.substring(c+3,d));return l&&r.currentVoice&&g?r.staves[r.currentVoice.staffNum].meter=g:o.hasBeginMusic()&&g?o.appendStartingElement("meter",f,p,g):r.meter=g,[d-c+1+u];case"[K:":var v=i.parseKey(n.substring(c+3,d),!0);return v.foundClef&&o.hasBeginMusic()&&o.appendStartingElement("clef",f,p,r.clef),v.foundKey&&o.hasBeginMusic()&&o.appendStartingElement("key",f,p,i.fixKey(r.clef,r.key)),[d-c+1+u];case"[P:":var b=a.parseFontChangeLine(n.substring(c+3,d));return l||s.lines.length<=s.lineNum?r.partForNextLine={title:b,startChar:f,endChar:p}:o.appendElement("part",f,p,{title:b}),[d-c+1+u];case"[L:":return this.setDefaultLength(n,c+3,d),[d-c+1+u];case"[Q:":if(d>0){var y=this.setTempo(n,c+3,d,r.iChar);return"delaySet"===y.type?o.hasBeginMusic()?o.appendElement("tempo",f,p,this.calcTempo(y.tempo)):r.tempoForNextLine=["tempo",f,p,this.calcTempo(y.tempo)]:"immediate"===y.type&&(!l&&o.hasBeginMusic()?o.appendElement("tempo",f,p,y.tempo):r.tempoForNextLine=["tempo",f,p,y.tempo]),[d-c+1+u,n[c+1],n.substring(c+3,d)]}break;case"[V:":if(d>0)return h=i.parseVoice(n,c+3,d),[d-c+1+u,n[c+1],n.substring(c+3,d),h];break;case"[r:":return[d-c+1+u]}}return[0]},this.letter_to_body_header=function(e,s){var c=!1;if(e.length>=s+3)switch(e.substring(s,s+2)){case"I:":var l=a.addDirective(e.substring(s+2));return l&&t(l,e,s),[e.length];case"M:":var h=this.setMeter(e.substring(s+2));return o.hasBeginMusic()&&h&&o.appendStartingElement("meter",r.iChar+s,r.iChar+e.length,h),[e.length];case"K:":var u=i.parseKey(e.substring(s+2),o.hasBeginMusic());return u.foundClef&&o.hasBeginMusic()&&!1!==r.keywarn&&o.appendStartingElement("clef",r.iChar+s,r.iChar+e.length,r.clef),u.foundKey&&o.hasBeginMusic()&&!1!==r.keywarn&&o.appendStartingElement("key",r.iChar+s,r.iChar+e.length,i.fixKey(r.clef,r.key)),[e.length];case"P:":return o.hasBeginMusic()&&o.appendElement("part",r.iChar+s,r.iChar+e.length,{title:e.substring(s+2)}),[e.length];case"L:":return this.setDefaultLength(e,s+2,e.length),[e.length];case"Q:":var d=e.indexOf("",s+2);-1===d&&(d=e.length);var f=this.setTempo(e,s+2,d,r.iChar);return"delaySet"===f.type?o.appendElement("tempo",r.iChar+s,r.iChar+e.length,this.calcTempo(f.tempo)):"immediate"===f.type&&o.appendElement("tempo",r.iChar+s,r.iChar+e.length,f.tempo),[d,e[s],n.strip(e.substring(s+2))];case"V:":return c=i.parseVoice(e,s+2,e.length),[e.length,e[s],n.strip(e.substring(s+2)),c]}return[0]};var l={A:"author",B:"book",C:"composer",D:"discography",F:"url",G:"group",I:"instruction",N:"notes",O:"origin",R:"rhythm",S:"source",W:"unalignedWords",Z:"transcription"};this.parseHeader=function(n){var c=l[n[0]],h=n.length-2,u=e.translateString(e.stripComment(n.substring(2)));if("unalignedWords"===c||"notes"===c)o.addMetaTextArray(c,a.parseFontChangeLine(u),{startChar:r.iChar,endChar:r.iChar+n.length});else if(void 0!==c)o.addMetaText(c,a.parseFontChangeLine(u),{startChar:r.iChar,endChar:r.iChar+n.length});else{var d=r.iChar,f=d+n.length;switch(n[0]){case"H":for(o.addMetaTextArray("history",a.parseFontChangeLine(u),{startChar:r.iChar,endChar:r.iChar+n.length}),n=e.peekLine();n&&":"!==n[1];)e.nextLine(),o.addMetaTextArray("history",a.parseFontChangeLine(e.translateString(e.stripComment(n))),{startChar:r.iChar,endChar:r.iChar+n.length}),n=e.peekLine();break;case"K":this.resolveTempo();var p=i.parseKey(n.substring(2),!1);!r.is_in_header&&o.hasBeginMusic()&&!1!==r.keywarn&&(p.foundClef&&o.appendStartingElement("clef",d,f,r.clef),p.foundKey&&o.appendStartingElement("key",d,f,i.fixKey(r.clef,r.key))),r.is_in_header=!1;break;case"L":this.setDefaultLength(n,2,n.length);break;case"M":r.origMeter=r.meter=this.setMeter(n.substring(2));break;case"P":r.is_in_header?o.addMetaText("partOrder",a.parseFontChangeLine(u),{startChar:r.iChar,endChar:r.iChar+n.length}):r.partForNextLine={title:u,startChar:d,endChar:f};break;case"Q":var m=this.setTempo(n,2,n.length,r.iChar);"delaySet"===m.type?r.tempo=m.tempo:"immediate"===m.type&&(s.metaText.tempo?r.tempoForNextLine=["tempo",d,f,m.tempo]:s.metaText.tempo=m.tempo);break;case"T":r.titlecaps&&(u=u.toUpperCase()),this.setTitle(a.parseFontChangeLine(e.theReverser(u)),h);break;case"U":this.addUserDefinition(n,2,n.length);break;case"V":if(i.parseVoice(n,2,n.length),!r.is_in_header)return{newline:!0};break;case"s":return{symbols:!0};case"w":return{words:!0};case"X":break;case"E":case"m":t("Ignored header",n,0);break;default:return{regular:!0}}}return{}}}},9708:function(e,t,r){var n=r(8360),a=r(2821),i={};!function(){var e,t,r,s;i.initialize=function(n,a,i,o,c){e=n,t=a,r=i,s=c},i.standardKey=function(e,t,n,i){return a.keySignature(r,e,t,n,i)};var o={treble:{clef:"treble",pitch:4,mid:0},"treble+8":{clef:"treble+8",pitch:4,mid:0},"treble-8":{clef:"treble-8",pitch:4,mid:0},"treble^8":{clef:"treble+8",pitch:4,mid:0},treble_8:{clef:"treble-8",pitch:4,mid:0},treble1:{clef:"treble",pitch:2,mid:2},treble2:{clef:"treble",pitch:4,mid:0},treble3:{clef:"treble",pitch:6,mid:-2},treble4:{clef:"treble",pitch:8,mid:-4},treble5:{clef:"treble",pitch:10,mid:-6},perc:{clef:"perc",pitch:6,mid:0},none:{clef:"none",mid:0},bass:{clef:"bass",pitch:8,mid:-12},"bass+8":{clef:"bass+8",pitch:8,mid:-12},"bass-8":{clef:"bass-8",pitch:8,mid:-12},"bass^8":{clef:"bass+8",pitch:8,mid:-12},bass_8:{clef:"bass-8",pitch:8,mid:-12},"bass+16":{clef:"bass",pitch:8,mid:-12},"bass-16":{clef:"bass",pitch:8,mid:-12},"bass^16":{clef:"bass",pitch:8,mid:-12},bass_16:{clef:"bass",pitch:8,mid:-12},bass1:{clef:"bass",pitch:2,mid:-6},bass2:{clef:"bass",pitch:4,mid:-8},bass3:{clef:"bass",pitch:6,mid:-10},bass4:{clef:"bass",pitch:8,mid:-12},bass5:{clef:"bass",pitch:10,mid:-14},tenor:{clef:"alto",pitch:8,mid:-8},tenor1:{clef:"alto",pitch:2,mid:-2},tenor2:{clef:"alto",pitch:4,mid:-4},tenor3:{clef:"alto",pitch:6,mid:-6},tenor4:{clef:"alto",pitch:8,mid:-8},tenor5:{clef:"alto",pitch:10,mid:-10},alto:{clef:"alto",pitch:6,mid:-6},alto1:{clef:"alto",pitch:2,mid:-2},alto2:{clef:"alto",pitch:4,mid:-4},alto3:{clef:"alto",pitch:6,mid:-6},alto4:{clef:"alto",pitch:8,mid:-8},alto5:{clef:"alto",pitch:10,mid:-10},"alto+8":{clef:"alto+8",pitch:6,mid:-6},"alto-8":{clef:"alto-8",pitch:6,mid:-6},"alto^8":{clef:"alto+8",pitch:6,mid:-6},alto_8:{clef:"alto-8",pitch:6,mid:-6}},c=function(e,t){var r=o[e];return(r?r.mid:0)+t};i.fixClef=function(e){var t=o[e.type];t&&(e.clefPos=t.pitch,e.type=t.clef)},i.deepCopyKey=function(e){var t={accidentals:[],root:e.root,acc:e.acc,mode:e.mode};return e.accidentals.forEach(function(e){t.accidentals.push(Object.assign({},e))}),e.explicitAccidentals&&(t.explicitAccidentals=[],e.explicitAccidentals.forEach(function(e){t.explicitAccidentals.push(Object.assign({},e))})),t};var l=function(){r.currentVoice&&(r.currentVoice.key=i.deepCopyKey(r.key))},h={A:5,B:6,C:0,D:1,E:2,F:3,G:4,a:12,b:13,c:7,d:8,e:9,f:10,g:11};i.addPosToKey=function(e,t){var r=e.verticalPos;t.accidentals.forEach(function(e){var t=h[e.note];t-=r,e.verticalPos=t}),t.impliedNaturals&&t.impliedNaturals.forEach(function(e){var t=h[e.note];t-=r,e.verticalPos=t}),r<-10?(t.accidentals.forEach(function(e){e.verticalPos-=7,(e.verticalPos>=11||10===e.verticalPos&&"flat"===e.acc)&&(e.verticalPos-=7),"A"===e.note&&"sharp"===e.acc&&(e.verticalPos-=7),"G"!==e.note&&"F"!==e.note||"flat"!==e.acc||(e.verticalPos-=7)}),t.impliedNaturals&&t.impliedNaturals.forEach(function(e){e.verticalPos-=7,(e.verticalPos>=11||10===e.verticalPos&&"flat"===e.acc)&&(e.verticalPos-=7),"A"===e.note&&"sharp"===e.acc&&(e.verticalPos-=7),"G"!==e.note&&"F"!==e.note||"flat"!==e.acc||(e.verticalPos-=7)})):r<-4?(t.accidentals.forEach(function(e){e.verticalPos-=7,-8!==r||"f"!==e.note&&"g"!==e.note||"sharp"!==e.acc||(e.verticalPos-=7)}),t.impliedNaturals&&t.impliedNaturals.forEach(function(e){e.verticalPos-=7,-8!==r||"f"!==e.note&&"g"!==e.note||"sharp"!==e.acc||(e.verticalPos-=7)})):r>=7&&(t.accidentals.forEach(function(e){e.verticalPos+=7}),t.impliedNaturals&&t.impliedNaturals.forEach(function(e){e.verticalPos+=7}))},i.fixKey=function(e,t){var r=Object.assign({},t);return i.addPosToKey(e,r),r};var u=function(e){var t=0,r=e[t++];"^"!==r&&"_"!==r||(r=e[t++]);var n=h[r];for(void 0===n&&(n=6);t<e.length;t++)if(","===e[t])n-=7;else{if("'"!==e[t])break;n+=7}return{mid:n-6,str:e.substring(t)}};i.parseKey=function(a,s){0===a.length&&(a="none");var o=e.tokenize(a,0,a.length),h={};if(0===o.length)return t("Must pass in key signature.",a,0),h;switch(o[0].token){case"HP":n.addDirective("bagpipes"),r.key={root:"HP",accidentals:[],acc:"",mode:""},h.foundKey=!0,o.shift(),s||(r.globalKey=i.deepCopyKey(r.key)),l();break;case"Hp":n.addDirective("bagpipes"),r.key={root:"Hp",accidentals:[{acc:"natural",note:"g"},{acc:"sharp",note:"f"},{acc:"sharp",note:"c"}],acc:"",mode:""},h.foundKey=!0,o.shift(),s||(r.globalKey=i.deepCopyKey(r.key)),l();break;case"none":r.key={root:"none",accidentals:[],acc:"",mode:""},h.foundKey=!0,o.shift(),s||(r.globalKey=i.deepCopyKey(r.key)),l();break;default:var u=e.getKeyPitch(o[0].token);if(u.len>0){h.foundKey=!0;var d="",f="";o[0].token.length>1?o[0].token=o[0].token.substring(1):o.shift();var p=u.token;if(o.length>0){var m=e.getSharpFlat(o[0].token);if(m.len>0&&(o[0].token.length>1?o[0].token=o[0].token.substring(1):o.shift(),p+=m.token,d=m.token),o.length>0){var g=e.getMode(o[0].token);g.len>0&&(o.shift(),p+=g.token,f=g.token)}if(void 0===i.standardKey(p,u.token,d,0))return t("Unsupported key signature: "+p,a,0),h}var v,b=i.deepCopyKey(r.key),y=!s&&r.globalTranspose?-r.globalTranspose:0;if(s&&(v=r.globalTransposeOrigKeySig),r.key=i.deepCopyKey(i.standardKey(p,u.token,d,y)),s&&(r.globalTransposeOrigKeySig=v),r.key.mode=f,b&&!1!==r.keywarn){for(var x,k=0;k<r.key.accidentals.length;k++)for(x=0;x<b.accidentals.length;x++)b.accidentals[x].note&&r.key.accidentals[k].note.toLowerCase()===b.accidentals[x].note.toLowerCase()&&(b.accidentals[x].note=null);for(x=0;x<b.accidentals.length;x++)b.accidentals[x].note&&(r.key.impliedNaturals||(r.key.impliedNaturals=[]),r.key.impliedNaturals.push({acc:"natural",note:b.accidentals[x].note}))}s||(r.globalKey=i.deepCopyKey(r.key)),l()}}if(0===o.length)return h;if("exp"===o[0].token&&o.shift(),0===o.length)return h;if("oct"===o[0].token&&o.shift(),0===o.length)return h;var w,C=e.getKeyAccidentals2(o);if(C.warn&&t(C.warn,a,0),C.accs){h.foundKey||(h.foundKey=!0,r.key={root:"none",acc:"",mode:"",accidentals:[]}),function(e){for(var t=0;t<e.length;t++)"b"===e[t].note?e[t].note="B":"a"===e[t].note?e[t].note="A":"F"===e[t].note?e[t].note="f":"E"===e[t].note?e[t].note="e":"D"===e[t].note?e[t].note="d":"C"===e[t].note?e[t].note="c":"G"===e[t].note&&"sharp"===e[t].acc?e[t].note="g":"g"===e[t].note&&"flat"===e[t].acc&&(e[t].note="G")}(C.accs);for(var T=0;T<C.accs.length;T++){for(var S=!1,_=0;_<r.key.accidentals.length&&!S;_++)r.key.accidentals[_].note===C.accs[T].note&&(S=!0,r.key.accidentals[_].acc!==C.accs[T].acc&&(r.key.accidentals[_].acc=C.accs[T].acc,r.key.explicitAccidentals||(r.key.explicitAccidentals=[]),r.key.explicitAccidentals.push(C.accs[T])));if(!S&&(r.key.explicitAccidentals||(r.key.explicitAccidentals=[]),r.key.explicitAccidentals.push(C.accs[T]),r.key.accidentals.push(C.accs[T]),r.key.impliedNaturals))for(var E=0;E<r.key.impliedNaturals.length;E++)r.key.impliedNaturals[E].note===C.accs[T].note&&r.key.impliedNaturals.splice(E,1)}s||(r.globalKey=i.deepCopyKey(r.key)),l()}for(;o.length>0;)switch(o[0].token){case"m":case"middle":if(o.shift(),0===o.length)return t("Expected = after middle",a,0),h;if("="!==(w=o.shift()).token){t("Expected = after middle",a,w.start);break}if(0===o.length)return t("Expected parameter after middle=",a,0),h;var M=e.getPitchFromTokens(o);M.warn&&t(M.warn,a,0),M.position&&(r.clef.verticalPos=M.position-6);break;case"transpose":if(o.shift(),0===o.length)return t("Expected = after transpose",a,0),h;if("="!==(w=o.shift()).token){t("Expected = after transpose",a,w.start);break}if(0===o.length)return t("Expected parameter after transpose=",a,0),h;if("number"!==o[0].type){t("Expected number after transpose",a,o[0].start);break}r.clef.transpose=o[0].intt,o.shift();break;case"stafflines":if(o.shift(),0===o.length)return t("Expected = after stafflines",a,0),h;if("="!==(w=o.shift()).token){t("Expected = after stafflines",a,w.start);break}if(0===o.length)return t("Expected parameter after stafflines=",a,0),h;if("number"!==o[0].type){t("Expected number after stafflines",a,o[0].start);break}r.clef.stafflines=o[0].intt,o.shift();break;case"staffscale":if(o.shift(),0===o.length)return t("Expected = after staffscale",a,0),h;if("="!==(w=o.shift()).token){t("Expected = after staffscale",a,w.start);break}if(0===o.length)return t("Expected parameter after staffscale=",a,0),h;if("number"!==o[0].type){t("Expected number after staffscale",a,o[0].start);break}r.clef.staffscale=o[0].floatt,o.shift();break;case"octave":if(o.shift(),0===o.length)return t("Expected = after octave",a,0),h;if("="!==(w=o.shift()).token){t("Expected = after octave",a,w.start);break}if(0===o.length)return t("Expected parameter after octave=",a,0),h;if("number"!==o[0].type){t("Expected number after octave",a,o[0].start);break}r.octave=o[0].intt,o.shift();break;case"style":if(o.shift(),0===o.length)return t("Expected = after style",a,0),h;if("="!==(w=o.shift()).token){t("Expected = after style",a,w.start);break}if(0===o.length)return t("Expected parameter after style=",a,0),h;switch(o[0].token){case"normal":case"harmonic":case"rhythm":case"x":case"triangle":r.style=o[0].token,o.shift();break;default:t("error parsing style element: "+o[0].token,a,o[0].start)}break;case"clef":if(o.shift(),0===o.length)return t("Expected = after clef",a,0),h;if("="!==(w=o.shift()).token){t("Expected = after clef",a,w.start);break}if(0===o.length)return t("Expected parameter after clef=",a,0),h;case"treble":case"bass":case"alto":case"tenor":case"perc":case"none":var A=o.shift();switch(A.token){case"treble":case"tenor":case"alto":case"bass":case"perc":case"none":break;case"C":case"c":A.token="alto";break;case"F":case"f":A.token="bass";break;case"G":case"g":A.token="treble";break;default:t("Expected clef name. Found "+A.token,a,A.start)}o.length>0&&"number"===o[0].type&&(A.token+=o[0].token,o.shift()),o.length>1&&("-"===o[0].token||"+"===o[0].token||"^"===o[0].token||"_"===o[0].token)&&"8"===o[1].token&&(A.token+=o[0].token+o[1].token,o.shift(),o.shift()),r.clef={type:A.token,verticalPos:c(A.token,0)},r.currentVoice&&void 0!==r.currentVoice.transpose&&(r.clef.transpose=r.currentVoice.transpose),h.foundClef=!0;break;default:t("Unknown parameter: "+o[0].token,a,o[0].start),o.shift()}return h},i.parseVoice=function(n,a,o){var l=e.getMeat(n,a,o),h=l.start,d=l.end,f=e.getToken(n,h,d);if(0!==f.length){var p=!1;void 0===r.voices[f]&&(r.voices[f]={},p=!0,r.score_is_present&&t("Can't have an unknown V: id when the %score directive is present",n,h)),h+=f.length,h+=e.eatWhiteSpace(n,h);for(var m={startStaff:p},g=function(r){var a=e.getVoiceToken(n,h,d);void 0!==a.warn?t("Expected value for "+r+" in voice: "+a.warn,n,h):void 0!==a.err?t("Expected value for "+r+" in voice: "+a.err,n,h):0===a.token.length&&'"'!==n[h]?t("Expected value for "+r+" in voice",n,h):m[r]=a.token,h+=a.len},v=function(a,i,s){var o=e.getVoiceToken(n,h,d);void 0!==o.warn?t("Expected value for "+i+" in voice: "+o.warn,n,h):void 0!==o.err?t("Expected value for "+i+" in voice: "+o.err,n,h):0===o.token.length&&'"'!==n[h]?t("Expected value for "+i+" in voice",n,h):("number"===s&&(o.token=parseFloat(o.token)),r.voices[a][i]=o.token),h+=o.len},b=function(r,a){var i=e.getVoiceToken(n,h,d);if(void 0!==i.warn)t("Expected value for "+r+" in voice: "+i.warn,n,h);else if(void 0!==i.err)t("Expected value for "+r+" in voice: "+i.err,n,h);else{if(0!==i.token.length||'"'===n[h])return"number"===a&&(i.token=parseFloat(i.token)),i.token;t("Expected value for "+r+" in voice",n,h)}h+=i.len},y=function(a,i){var s=e.getVoiceToken(n,h,d);if(void 0!==s.warn)t("Expected one of (_B, _E, _b, _e) for "+i+" in voice: "+s.warn,n,h);else if(0===s.token.length&&'"'!==n[h])t("Expected one of (_B, _E, _b, _e) for "+i+" in voice",n,h);else{var o={_B:2,_E:9,_b:-10,_e:-3}[s.token];o?r.voices[a][i]=o:t("Expected one of (_B, _E, _b, _e) for "+i+" in voice",n,h)}h+=s.len};h<d;){var x=e.getVoiceToken(n,h,d);if(h+=x.len,x.warn)t("Error parsing voice: "+x.warn,n,h);else{var k=null;switch(x.token){case"clef":case"cl":g("clef");var w=0;void 0!==m.clef&&(m.clef=m.clef.replace(/[',]/g,""),-1!==m.clef.indexOf("+16")&&(w+=14,m.clef=m.clef.replace("+16","")),m.verticalPos=c(m.clef,w));break;case"treble":case"bass":case"tenor":case"alto":case"perc":case"none":case"treble'":case"bass'":case"tenor'":case"alto'":case"none'":case"treble''":case"bass''":case"tenor''":case"alto''":case"none''":case"treble,":case"bass,":case"tenor,":case"alto,":case"none,":case"treble,,":case"bass,,":case"tenor,,":case"alto,,":case"none,,":case"treble+8":case"treble-8":case"treble^8":case"treble_8":case"treble1":case"treble2":case"treble3":case"treble4":case"treble5":case"bass+8":case"bass-8":case"bass^8":case"bass_8":case"bass+16":case"bass-16":case"bass^16":case"bass_16":case"bass1":case"bass2":case"bass3":case"bass4":case"bass5":case"tenor1":case"tenor2":case"tenor3":case"tenor4":case"tenor5":case"alto1":case"alto2":case"alto3":case"alto4":case"alto5":case"alto+8":case"alto-8":case"alto^8":case"alto_8":m.clef=x.token.replace(/[',]/g,""),m.verticalPos=c(m.clef,0),r.voices[f].clef=x.token;break;case"staves":case"stave":case"stv":g("staves");break;case"brace":case"brc":g("brace");break;case"bracket":case"brk":g("bracket");break;case"name":case"nm":g("name");break;case"subname":case"sname":case"snm":g("subname");break;case"merge":m.startStaff=!1;break;case"stem":case"stems":void 0!==(k=e.getVoiceToken(n,h,d)).warn?t("Expected value for stems in voice: "+k.warn,n,h):void 0!==k.err?t("Expected value for stems in voice: "+k.err,n,h):"up"===k.token||"down"===k.token?r.voices[f].stem=k.token:t("Expected up or down for voice stem",n,h),h+=k.len;break;case"up":case"down":r.voices[f].stem=x.token;break;case"middle":case"m":g("verticalPos"),m.verticalPos=u(m.verticalPos).mid;break;case"gchords":case"gch":r.voices[f].suppressChords=!0,"0"===(k=e.getVoiceToken(n,h,d)).token&&(h+=k.len);break;case"space":case"spc":g("spacing");break;case"scale":v(f,"scale","number");break;case"score":y(f,"scoreTranspose");break;case"transpose":v(f,"transpose","number");break;case"stafflines":v(f,"stafflines","number");break;case"staffscale":v(f,"staffscale","number");break;case"octave":v(f,"octave","number");break;case"volume":v(f,"volume","number");break;case"cue":var C=b("cue","string");r.voices[f].scale="on"===C?.6:1;break;case"style":void 0!==(k=e.getVoiceToken(n,h,d)).warn?t("Expected value for style in voice: "+k.warn,n,h):void 0!==k.err?t("Expected value for style in voice: "+k.err,n,h):"normal"===k.token||"harmonic"===k.token||"rhythm"===k.token||"x"===k.token||"triangle"===k.token?r.voices[f].style=k.token:t("Expected one of [normal, harmonic, rhythm, x, triangle] for voice style",n,h),h+=k.len}}h+=e.eatWhiteSpace(n,h)}if((m.startStaff||0===r.staves.length)&&(r.staves.push({index:r.staves.length,meter:r.origMeter}),r.score_is_present||(r.staves[r.staves.length-1].numVoices=0)),void 0===r.voices[f].staffNum){r.voices[f].staffNum=r.staves.length-1;var T=0;for(var S in r.voices)r.voices.hasOwnProperty(S)&&r.voices[S].staffNum===r.voices[f].staffNum&&T++;r.voices[f].index=T-1}var _=r.staves[r.voices[f].staffNum];return r.score_is_present||_.numVoices++,m.clef&&(_.clef={type:m.clef,verticalPos:m.verticalPos}),m.spacing&&(_.spacing_below_offset=m.spacing),m.verticalPos&&(_.verticalPos=m.verticalPos),m.name&&(_.name?_.name.push(m.name):_.name=[m.name]),m.subname&&(_.subname?_.subname.push(m.subname):_.subname=[m.subname]),function(e){var t=r.voices[e];if(!r.currentVoice||r.currentVoice.index!==t.index||r.currentVoice.staffNum!==t.staffNum)return r.currentVoice=t,t.key?r.key=i.deepCopyKey(t.key):r.globalKey&&(r.key=i.deepCopyKey(r.globalKey)),s.setCurrentVoice(t.staffNum,t.index,e)}(f)}t("Expected a voice id",n,h)}}(),e.exports=i},6476:function(e,t,r){var n,a,i,s,o,c,l=r(9708),h=r(2821),u=r(2539),d=u.legalAccents,f=u.volumeDecorations,p=u.dynamicDecorations,m=u.accentPseudonyms,g=u.accentDynamicPseudonyms,v=u.nonDecorations,b=u.durations,y=u.pitches,x=u.rests,k=u.accMap,w=u.tripletQ,C=function(e,t,r,l,h,u){n=e,a=t,i=r,s=l,o=h,c=u,this.lineContinuation=!1},T=function(e,t,r){if(void 0===e.inTie[t])return!1;var n=e.currentVoice?100*e.currentVoice.staffNum+e.currentVoice.index:0;return!(!e.inTie[t][n]||void 0===r.pitches&&"spacer"===r.rest.type)},S={};C.prototype.parseMusic=function(e){c.resolveTempo(),i.is_in_header=!1;for(var t=0,r=i.iChar;n.isWhiteSpace(e[t])&&t<e.length;)t++;if(t!==e.length&&"%"!==e[t]){var l=i.start_new_line;void 0===i.continueall?i.start_new_line=!0:i.start_new_line=!1;var h=0,u=c.letter_to_body_header(e,t);u[0]>0&&(t+=u[0],"V"===u[1]&&this.startNewLine());for(var d=0;t<e.length;){var f=t;if("%"===e[t])break;var p=c.letter_to_inline_header(e,t,l);if(p[0]>0)t+=p[0],"V"===p[1]&&(l=!0);else{var m;for((!o.hasBeginMusic()||l&&!this.lineContinuation)&&(this.startNewLine(),l=!1);;)if((m=n.eatWhiteSpace(e,t))>0&&(t+=m),t>0&&""===e[t-1]&&(m=c.letter_to_body_header(e,t))[0]>0&&("V"===m[1]&&this.startNewLine(),t=m[0],i.start_new_line=!1),(m=P(e,t))[0]>0&&(t+=m[0]),(m=E(e,t))[0]>0){S.chord||(S.chord=[]);var g=n.translateString(m[1]);g=g.replace(/;/g,"\n");for(var y=!1,x=0;x<S.chord.length;x++)S.chord[x].position===m[2]&&(y=!0,S.chord[x].name+="\n"+g);!1===y&&(null===m[2]&&m[3]?S.chord.push({name:g,rel_position:m[3]}):S.chord.push({name:g,position:m[2]})),t+=m[0];var k=n.skipWhiteSpace(e.substring(t));k>0&&(S.force_end_beam_last=!0),t+=k}else if((m=-1===v.indexOf(e[t])?B(e,t):[0])[0]>0)null===m[1]?t+1<e.length&&this.startNewLine():m[1].length>0&&(0===m[1].indexOf("style=")?S.style=m[1].substring(6):0===m[1].indexOf("class=")?S.extraClass=m[1].substring(6):(void 0===S.decoration&&(S.decoration=[]),"beambr1"===m[1]?S.beambr=1:"beambr2"===m[1]?S.beambr=2:S.decoration.push(m[1]))),t+=m[0];else{if(!((m=M(e,t))[0]>0))break;S.gracenotes=m[1],t+=m[0]}if((m=L(e,t))[0]>0){d=0,void 0!==S.gracenotes&&(S.rest={type:"spacer"},S.duration=.125,i.addFormattingOptions(S,s.formatting,"note"),o.appendElement("note",r+t,r+t+m[0],S),i.measureNotEmpty=!0,S={});var w={type:m[1]};0===w.type.length?a("Unknown bar type",e,t):(i.inEnding&&"bar_thin"!==w.type&&(w.endEnding=!0,i.inEnding=!1),m[2]&&(w.startEnding=m[2],i.inEnding&&(w.endEnding=!0),i.inEnding=!0,"bar_right_repeat"===m[1]?i.restoreStartEndingHoldOvers():i.duplicateStartEndingHoldOvers()),void 0!==S.decoration&&(w.decoration=S.decoration),void 0!==S.chord&&(w.chord=S.chord),w.startEnding&&void 0===i.barFirstEndingNum?i.barFirstEndingNum=i.currBarNumber:w.startEnding&&w.endEnding&&i.barFirstEndingNum?i.currBarNumber=i.barFirstEndingNum:w.endEnding&&(i.barFirstEndingNum=void 0),"bar_invisible"!==w.type&&i.measureNotEmpty&&z()&&(i.currBarNumber++,i.barNumbers&&i.currBarNumber%i.barNumbers==0&&(w.barNumber=i.currBarNumber)),i.addFormattingOptions(S,s.formatting,"bar"),o.appendElement("bar",r+f,r+t+m[0],w),i.measureNotEmpty=!1,S={}),t+=m[0]}else if("&"===e[t])(m=A(e,t))[0]>0&&(o.appendElement("overlay",r,r+1,{}),t+=1,d++);else{if((m=O(e,t)).consumed>0&&(void 0!==m.startSlur&&(S.startSlur=m.startSlur),m.dottedSlur&&(S.dottedSlur=!0),void 0!==m.triplet&&(h>0?a("Can't nest triplets",e,t):(S.startTriplet=m.triplet,S.tripletMultiplier=m.tripletQ/m.triplet,S.tripletR=m.num_notes,h=void 0===m.num_notes?m.triplet:m.num_notes)),t+=m.consumed),"["===e[t]){t++;for(var C=null,I=!1,F=!1;!F;){var V=B(e,t);V[0]>0&&(t+=V[0]);var G=H(e,t,{},!1);if(null!==G&&void 0!==G.pitch)V[0]>0&&0!==V[1].indexOf("style=")&&(void 0===S.decoration&&(S.decoration=[]),S.decoration.push(V[1])),G.end_beam&&(S.end_beam=!0,delete G.end_beam),void 0===S.pitches?(S.duration=G.duration,S.pitches=[G]):S.pitches.push(G),delete G.duration,V[0]>0&&0===V[1].indexOf("style=")&&(S.pitches[S.pitches.length-1].style=V[1].substr(6)),i.inTieChord[S.pitches.length]&&(G.endTie=!0,i.inTieChord[S.pitches.length]=void 0),G.startTie&&(i.inTieChord[S.pitches.length]=!0),t=G.endChar,delete G.endChar;else if(" "===e[t])a("Spaces are not allowed in chords",e,t),t++;else{if(t<e.length&&"]"===e[t]){t++,0!==i.next_note_duration&&(S.duration=S.duration*i.next_note_duration,i.next_note_duration=0),T(i,d,S)&&(S.pitches.forEach(function(e){e.endTie=!0}),_(i,d,!1)),h>0&&(!S.rest||"spacer"!==S.rest.type)&&0==--h&&(S.endTriplet=!0);for(var Y=!1;t<e.length&&!Y;){switch(e[t]){case" ":case"\t":j(S);break;case")":void 0===S.endSlur?S.endSlur=1:S.endSlur++;break;case"-":S.pitches.forEach(function(e){e.startTie={}}),_(i,d,!0);break;case">":case"<":var q=D(e,t);t+=q[0]-1,i.next_note_duration=q[2],C?C*=q[1]:C=q[1];break;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case"/":var R=n.getFraction(e,t);C=R.value;var W=e[t=R.index];" "===W&&(I=!0),"-"===W||")"===W||" "===W||"<"===W||">"===W?t--:Y=!0;break;case"0":C=0;break;default:Y=!0}Y||t++}}else a("Expected ']' to end the chords",e,t);void 0!==S.pitches&&(null!==C&&(S.duration=S.duration*C,I&&j(S)),i.addFormattingOptions(S,s.formatting,"note"),o.appendElement("note",r+f,r+t,S),i.measureNotEmpty=!0,S={}),F=!0}}}else{var X={},U=H(e,t,X,!0);void 0!==X.endTie&&_(i,d,!0),null!==U&&(void 0!==U.pitch?(S.pitches=[{}],void 0!==U.accidental&&(S.pitches[0].accidental=U.accidental),S.pitches[0].pitch=U.pitch,S.pitches[0].name=U.name,(U.midipitch||0===U.midipitch)&&(S.pitches[0].midipitch=U.midipitch),void 0!==U.endSlur&&(S.pitches[0].endSlur=U.endSlur),void 0!==U.endTie&&(S.pitches[0].endTie=U.endTie),void 0!==U.startSlur&&(S.pitches[0].startSlur=U.startSlur),void 0!==S.startSlur&&(S.pitches[0].startSlur=S.startSlur),void 0!==S.dottedSlur&&(S.pitches[0].dottedSlur=!0),void 0!==U.startTie&&(S.pitches[0].startTie=U.startTie),void 0!==S.startTie&&(S.pitches[0].startTie=S.startTie)):(S.rest=U.rest,"multimeasure"===U.rest.type&&z()&&(i.currBarNumber+=U.rest.text-1),void 0!==U.endSlur&&(S.endSlur=U.endSlur),void 0!==U.endTie&&(S.rest.endTie=U.endTie),void 0!==U.startSlur&&(S.startSlur=U.startSlur),void 0!==U.startTie&&(S.rest.startTie=U.startTie),void 0!==S.startTie&&(S.rest.startTie=S.startTie)),void 0!==U.chord&&(S.chord=U.chord),void 0!==U.duration&&(S.duration=U.duration),void 0!==U.decoration&&(S.decoration=U.decoration),void 0!==U.graceNotes&&(S.graceNotes=U.graceNotes),delete S.startSlur,delete S.dottedSlur,T(i,d,S)&&(void 0!==S.pitches?S.pitches[0].endTie=!0:"spacer"!==S.rest.type&&(S.rest.endTie=!0),_(i,d,!1)),(U.startTie||S.startTie)&&_(i,d,!0),t=U.endChar,h>0&&(!U.rest||"spacer"!==U.rest.type)&&0==--h&&(S.endTriplet=!0),U.end_beam&&j(S),S.rest&&"rest"===S.rest.type&&1===S.duration&&N(i)<=1&&(S.rest.type="whole",S.duration=N(i)),S.duration<1&&-1===b.indexOf(S.duration)&&0!==S.duration&&(S.rest&&"spacer"===S.rest.type||a("Duration not representable: "+e.substring(f,t),e,t)),i.addFormattingOptions(S,s.formatting,"note"),o.appendElement("note",r+f,r+t,S)||(this.startNewLine(),o.appendElement("note",r+f,r+t,S)),i.measureNotEmpty=!0,S={})}t===f&&(" "!==e[t]&&"`"!==e[t]&&a("Unknown character ignored",e,t),t++)}}}this.lineContinuation=e.indexOf("")>=0||u[0]>0,this.lineContinuation||(S={})}};var _=function(e,t,r){var n=e.currentVoice?100*e.currentVoice.staffNum+e.currentVoice.index:0;void 0===e.inTie[t]&&(e.inTie[t]=[]),e.inTie[t][n]=r},E=function(e,t){if('"'===e[t]){var r=n.getBrackettedSubstring(e,t,5);if(r[2]||a("Missing the closing quote while parsing the chord symbol",e,t),r[0]>0&&r[1].length>0&&"^"===r[1][0])r[1]=r[1].substring(1),r[2]="above";else if(r[0]>0&&r[1].length>0&&"_"===r[1][0])r[1]=r[1].substring(1),r[2]="below";else if(r[0]>0&&r[1].length>0&&"<"===r[1][0])r[1]=r[1].substring(1),r[2]="left";else if(r[0]>0&&r[1].length>0&&">"===r[1][0])r[1]=r[1].substring(1),r[2]="right";else if(r[0]>0&&r[1].length>0&&"@"===r[1][0]){r[1]=r[1].substring(1);var s=n.getFloat(r[1]);if(0===s.digits)return a("Missing first position in absolutely positioned annotation.",e,t),r[1]=r[1].replace("@",""),r[2]="above",r;if(r[1]=r[1].substring(s.digits),","!==r[1][0])return a("Missing comma absolutely positioned annotation.",e,t),r[1]=r[1].replace("@",""),r[2]="above",r;r[1]=r[1].substring(1);var o=n.getFloat(r[1]);if(0===o.digits)return a("Missing second position in absolutely positioned annotation.",e,t),r[1]=r[1].replace("@",""),r[2]="above",r;r[1]=r[1].substring(o.digits);var c=n.skipWhiteSpace(r[1]);r[1]=r[1].substring(c),r[2]=null,r[3]={x:s.value,y:o.value}}else!0!==i.freegchord&&(r[1]=r[1].replace(/([ABCDEFG0-9])b/g,"$1♭"),r[1]=r[1].replace(/([ABCDEFG0-9])#/g,"$1♯"),r[1]=r[1].replace(/^([ABCDEFG])([♯♭]?)o([^A-Za-z])/g,"$1$2°$3"),r[1]=r[1].replace(/^([ABCDEFG])([♯♭]?)o$/g,"$1$2°"),r[1]=r[1].replace(/^([ABCDEFG])([♯♭]?)0([^A-Za-z])/g,"$1$2ø$3"),r[1]=r[1].replace(/^([ABCDEFG])([♯♭]?)\^([^A-Za-z])/g,"$1$2∆$3")),r[2]="default",r[1]=h.chordName(i,r[1]);return r}return[0,""]},M=function(e,t){if("{"===e[t]){var r=n.getBrackettedSubstring(e,t,1,"}");r[2]||a("Missing the closing '}' while parsing grace note",e,t),")"===e[t+r[0]]&&(r[0]++,r[1]+=")");for(var s=[],o=0,c=!1;o<r[1].length;){var l=!1;"/"===r[1][o]&&(l=!0,o++);var h=H(r[1],o,{},!1);null!==h?(h.duration=h.duration/(8*i.default_length),l&&(h.acciaccatura=!0),h.rest?a("Rests not allowed as grace notes '"+r[1][o]+"' while parsing grace note",e,t):s.push(h),c&&(h.endTie=!0,c=!1),h.startTie&&(c=!0),o=h.endChar,delete h.endChar,h.end_beam&&(h.endBeam=!0,delete h.end_beam)):(" "===r[1][o]?s.length>0&&(s[s.length-1].endBeam=!0):a("Unknown character '"+r[1][o]+"' while parsing grace note",e,t),o++)}if(s.length)return[r[0],s]}return[0]};function A(e,t){if("&"===e[t]){for(var r=t;e[t]&&":"!==e[t]&&"|"!==e[t];)t++;return[t-r,e.substring(r+1,t)]}return[0]}function N(e){var t=e.origMeter;return t&&"specified"===t.type&&t.value&&0!==t.value.length?parseInt(t.value[0].num,10)/parseInt(t.value[0].den,10):1}var B=function(e,t){var r=i.macros[e[t]];if(void 0!==r)return"!"!==r[0]&&"+"!==r[0]||(r=r.substring(1)),"!"!==r[r.length-1]&&"+"!==r[r.length-1]||(r=r.substring(0,r.length-1)),d.includes(r)?[1,r]:f.includes(r)?("hidden"===i.volumePosition&&(r=""),[1,r]):p.includes(r)?("hidden"===i.dynamicPosition&&(r=""),[1,r]):(i.ignoredDecorations.includes(r)||a("Unknown macro: "+r,e,t),[1,""]);switch(e[t]){case".":if("("===e[t+1]||"-"===e[t+1])break;return[1,"staccato"];case"u":return[1,"upbow"];case"v":return[1,"downbow"];case"~":return[1,"irishroll"];case"!":case"+":var s=n.getBrackettedSubstring(e,t,5);if(s[1].length>1&&("^"===s[1][0]||"_"===s[1][0])&&(s[1]=s[1].substring(1)),d.includes(s[1])||0===s[1].indexOf("class="))return s;if(f.includes(s[1]))return"hidden"===i.volumePosition&&(s[1]=""),s;if(p.includes(s[1]))return"hidden"===i.dynamicPosition&&(s[1]=""),s;var o=m.findIndex(function(e){return s[1]===e[0]});return o>=0?(s[1]=m[o][1],s):(o=g.findIndex(function(e){return s[1]===e[0]}))>=0?(s[1]=g[o][1],"hidden"===i.dynamicPosition&&(s[1]=""),s):"!"!==e[t]||1!==s[0]&&"!"===e[t+s[0]-1]?(a("Unknown decoration: "+s[1],e,t),s[1]="",s):[1,null];case"H":return[1,"fermata"];case"J":return[1,"slide"];case"L":return[1,"accent"];case"M":return[1,"mordent"];case"O":return[1,"coda"];case"P":return[1,"pralltriller"];case"R":return[1,"roll"];case"S":return[1,"segno"];case"T":return[1,"trill"];case"t":return[1,"trillh"]}return[0,0]},P=function(e,t){for(var r=t;n.isWhiteSpace(e[t]);)t++;return[t-r]},L=function(e,t){var r=n.getBarLine(e,t);if(0===r.len)return[0,""];if(r.warn)return a(r.warn,e,t),[r.len,""];for(var i=0;i<e.length&&" "===e[t+r.len+i];i++);var s=r.len;if("["===e[t+r.len+i]&&(r.len+=i+1),'"'===e[t+r.len]&&"["===e[t+r.len-1]){var o=n.getBrackettedSubstring(e,t+r.len,5);return[r.len+o[0],r.token,o[1]]}var c=n.getTokenOf(e.substring(t+r.len),"1234567890-,");return 0===c.len||"-"===c.token[0]?[s,r.token]:[r.len+c.len,r.token,c.token]},O=function(e,t){var r={},i=t;for("."===e[t]&&"("===e[t+1]&&(r.dottedSlur=!0,t++);"("===e[t]||n.isWhiteSpace(e[t]);)"("===e[t]&&(t+1<e.length&&e[t+1]>="2"&&e[t+1]<="9"?(void 0!==r.triplet?a("Can't nest triplets",e,t):(r.triplet=e[t+1]-"0",r.tripletQ=w[r.triplet],r.num_notes=r.triplet,t+2<e.length&&":"===e[t+2]&&(t+3<e.length&&":"===e[t+3]?t+4<e.length&&e[t+4]>="1"&&e[t+4]<="9"?(r.num_notes=e[t+4]-"0",t+=3):a("expected number after the two colons after the triplet to mark the duration",e,t):t+3<e.length&&e[t+3]>="1"&&e[t+3]<="9"?(r.tripletQ=e[t+3]-"0",t+4<e.length&&":"===e[t+4]?t+5<e.length&&e[t+5]>="1"&&e[t+5]<="9"&&(r.num_notes=e[t+5]-"0",t+=4):t+=2):a("expected number after the triplet to mark the duration",e,t))),t++):void 0===r.startSlur?r.startSlur=1:r.startSlur++),t++;return r.consumed=t-i,r};C.prototype.startNewLine=function(){var e={startChar:-1,endChar:-1};i.partForNextLine.title&&(e.part=i.partForNextLine),e.clef=i.currentVoice&&void 0!==i.staves[i.currentVoice.staffNum].clef?Object.assign({},i.staves[i.currentVoice.staffNum].clef):Object.assign({},i.clef);var t=i.currentVoice?i.currentVoice.scoreTranspose:0;if(e.key=l.standardKey(i.key.root+i.key.acc+i.key.mode,i.key.root,i.key.acc,t),e.key.mode=i.key.mode,i.key.impliedNaturals&&(e.key.impliedNaturals=i.key.impliedNaturals),i.key.explicitAccidentals)for(var r=0;r<i.key.explicitAccidentals.length;r++){for(var n=!1,a=0;a<e.key.accidentals.length;a++)e.key.accidentals[a].note===i.key.explicitAccidentals[r].note&&(e.key.accidentals[a].acc=i.key.explicitAccidentals[r].acc,n=!0);n||e.key.accidentals.push(i.key.explicitAccidentals[r])}if(i.targetKey=e.key,e.key.explicitAccidentals&&delete e.key.explicitAccidentals,l.addPosToKey(e.clef,e.key),null!==i.meter?(i.currentVoice?(i.staves.forEach(function(e){e.meter=i.meter}),e.meter=i.staves[i.currentVoice.staffNum].meter,i.staves[i.currentVoice.staffNum].meter=null):e.meter=i.meter,i.meter=null):i.currentVoice&&i.staves[i.currentVoice.staffNum].meter&&(e.meter=i.staves[i.currentVoice.staffNum].meter,i.staves[i.currentVoice.staffNum].meter=null),i.currentVoice&&i.currentVoice.name&&(e.name=i.currentVoice.name),i.vocalfont&&(e.vocalfont=i.vocalfont),i.tripletfont&&(e.tripletfont=i.tripletfont),i.gchordfont&&(e.gchordfont=i.gchordfont),i.style&&(e.style=i.style),i.currentVoice){var s=i.staves[i.currentVoice.staffNum];s.brace&&(e.brace=s.brace),s.bracket&&(e.bracket=s.bracket),s.connectBarLines&&(e.connectBarLines=s.connectBarLines),s.name&&(e.name=s.name[i.currentVoice.index]),s.subname&&(e.subname=s.subname[i.currentVoice.index]),i.currentVoice.stem&&(e.stem=i.currentVoice.stem),i.currentVoice.stafflines&&(e.stafflines=i.currentVoice.stafflines),i.currentVoice.staffscale&&(e.staffscale=i.currentVoice.staffscale),i.currentVoice.scale&&(e.scale=i.currentVoice.scale),i.currentVoice.color&&(e.color=i.currentVoice.color),i.currentVoice.style&&(e.style=i.currentVoice.style),i.currentVoice.transpose&&(e.clef.transpose=i.currentVoice.transpose),e.currentVoice=i.currentVoice;for(var c=Object.keys(i.voices),h=0;h<c.length;h++)e.currentVoice.staffNum===i.voices[c[h]].staffNum&&e.currentVoice.index===i.voices[c[h]].index&&(e.currentVoiceName=c[h])}0===i.barNumbers&&z()&&1!==i.currBarNumber&&(e.barNumber=i.currBarNumber),o.startNewLine(e),i.key.impliedNaturals&&delete i.key.impliedNaturals,i.partForNextLine={},4===i.tempoForNextLine.length&&o.appendElement(i.tempoForNextLine[0],i.tempoForNextLine[1],i.tempoForNextLine[2],i.tempoForNextLine[3]),i.tempoForNextLine=[]};var j=function(e){return void 0!==e.duration&&e.duration<.25&&(e.end_beam=!0),e},H=function(e,t,r,a){var c,l=function(e){return"octave"===e||"duration"===e||"Zduration"===e||"broken_rhythm"===e||"end_slur"===e};"."===e[t]&&"-"===e[t+1]&&(c=!0,t++);for(var u="startSlur",d=!1;;){switch(e[t]){case"(":if("startSlur"!==u)return l(u)?(r.endChar=t,r):null;void 0===r.startSlur?r.startSlur=1:r.startSlur++;break;case")":if(!l(u))return null;void 0===r.endSlur?r.endSlur=1:r.endSlur++;break;case"^":if("startSlur"===u)r.accidental="sharp",u="sharp2";else{if("sharp2"!==u)return l(u)?(r.endChar=t,r):null;r.accidental="dblsharp",u="pitch"}break;case"_":if("startSlur"===u)r.accidental="flat",u="flat2";else{if("flat2"!==u)return l(u)?(r.endChar=t,r):null;r.accidental="dblflat",u="pitch"}break;case"=":if("startSlur"!==u)return l(u)?(r.endChar=t,r):null;r.accidental="natural",u="pitch";break;case"A":case"B":case"C":case"D":case"E":case"F":case"G":case"a":case"b":case"c":case"d":case"e":case"f":case"g":if("startSlur"!==u&&"sharp2"!==u&&"flat2"!==u&&"pitch"!==u)return l(u)?(r.endChar=t,r):null;if(r.pitch=y[e[t]],r.pitch+=7*(i.currentVoice&&void 0!==i.currentVoice.octave?i.currentVoice.octave:i.octave),r.name=e[t],r.accidental&&(r.name=k[r.accidental]+r.name),h.note(i,r),u="octave",a&&0!==i.next_note_duration?(r.duration=i.default_length*i.next_note_duration,i.next_note_duration=0,d=!0):r.duration=i.default_length,i.clef&&"perc"===i.clef.type||i.currentVoice&&"perc"===i.currentVoice.clef){var f=e[t];r.accidental&&(f=k[r.accidental]+f),s.formatting&&s.formatting.midi&&s.formatting.midi.drummap&&(r.midipitch=s.formatting.midi.drummap[f])}break;case",":if("octave"!==u)return l(u)?(r.endChar=t,r):null;r.pitch-=7,r.name+=",";break;case"'":if("octave"!==u)return l(u)?(r.endChar=t,r):null;r.pitch+=7,r.name+="'";break;case"x":case"X":case"y":case"z":case"Z":if("startSlur"!==u)return l(u)?(r.endChar=t,r):null;r.rest={type:x[e[t]]},delete r.accidental,delete r.startSlur,delete r.startTie,delete r.endSlur,delete r.endTie,delete r.end_beam,delete r.grace_notes,r.rest.type.indexOf("multimeasure")>=0?(r.duration=s.getBarLength(),r.rest.text=1,u="Zduration"):(a&&0!==i.next_note_duration?(r.duration=i.default_length*i.next_note_duration,i.next_note_duration=0,d=!0):r.duration=i.default_length,u="duration");break;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case"0":case"/":if("octave"===u||"duration"===u){var p=n.getFraction(e,t);for(r.duration=r.duration*p.value,r.endChar=p.index;p.index<e.length&&(n.isWhiteSpace(e[p.index])||"-"===e[p.index]);)"-"===e[p.index]?r.startTie={}:r=j(r),p.index++;t=p.index-1,u="broken_rhythm"}else if("sharp2"===u)r.accidental="quartersharp",u="pitch";else{if("flat2"!==u){if("Zduration"===u){var m=n.getNumber(e,t);return r.duration=m.num*s.getBarLength(),r.rest.text=m.num,r.endChar=m.index,r}return null}r.accidental="quarterflat",u="pitch"}break;case"-":if("startSlur"===u)o.addTieToLastNote(c),r.endTie=!0;else{if("octave"!==u&&"duration"!==u&&"end_slur"!==u)return"broken_rhythm"===u?(r.endChar=t,r):null;if(r.startTie={},d||!a)return n.isWhiteSpace(e[t+1])&&j(r),r.endChar=t+1,r;u="broken_rhythm"}break;case" ":case"\t":if(!l(u))return null;r.end_beam=!0,c=!1;do{"."===e[t]&&"-"===e[t+1]&&(c=!0,t++),"-"===e[t]&&(r.startTie={},c&&(r.startTie.style="dotted")),t++}while(t<e.length&&(n.isWhiteSpace(e[t])||"-"===e[t])||"."===e[t]&&"-"===e[t+1]);if(r.endChar=t,d||!a||"<"!==e[t]&&">"!==e[t])return r;t--,u="broken_rhythm";break;case">":case"<":if(!l(u))return null;if(!a)return r.endChar=t,r;var g=D(e,t);t+=g[0]-1,i.next_note_duration=g[2],r.duration=g[1]*r.duration,u="end_slur";break;default:return l(u)?(r.endChar=t,r):null}if(++t===e.length)return l(u)?(r.endChar=t,r):null}return null},D=function(e,t){switch(e[t]){case">":return t<e.length-2&&">"===e[t+1]&&">"===e[t+2]?[3,1.875,.125]:t<e.length-1&&">"===e[t+1]?[2,1.75,.25]:[1,1.5,.5];case"<":return t<e.length-2&&"<"===e[t+1]&&"<"===e[t+2]?[3,.125,1.875]:t<e.length-1&&"<"===e[t+1]?[2,.25,1.75]:[1,.5,1.5]}return null};function z(){return void 0===i.currentVoice||0===i.currentVoice.staffNum&&0===i.currentVoice.index}e.exports=C},2539:function(e){e.exports.legalAccents=["trill","trillh","lowermordent","uppermordent","mordent","pralltriller","accent","fermata","invertedfermata","tenuto","0","1","2","3","4","5","+","wedge","open","thumb","snap","turn","roll","breath","shortphrase","mediumphrase","longphrase","segno","coda","D.S.","D.C.","fine","beambr1","beambr2","slide","marcato","upbow","downbow","/","//","///","////","trem1","trem2","trem3","trem4","turnx","invertedturn","invertedturnx","trill(","trill)","arpeggio","xstem","mark","umarcato","style=normal","style=harmonic","style=rhythm","style=x","style=triangle","D.C.alcoda","D.C.alfine","D.S.alcoda","D.S.alfine","editorial","courtesy"],e.exports.volumeDecorations=["p","pp","f","ff","mf","mp","ppp","pppp","fff","ffff","sfz"],e.exports.dynamicDecorations=["crescendo(","crescendo)","diminuendo(","diminuendo)","glissando(","glissando)","~(","~)"],e.exports.accentPseudonyms=[["<","accent"],[">","accent"],["tr","trill"],["plus","+"],["emphasis","accent"],["^","umarcato"],["marcato","umarcato"]],e.exports.accentDynamicPseudonyms=[["<(","crescendo("],["<)","crescendo)"],[">(","diminuendo("],[">)","diminuendo)"]],e.exports.nonDecorations="ABCDEFGabcdefgxyzZ[]|^_{",e.exports.durations=[.5,.75,.875,.9375,.96875,.984375,.25,.375,.4375,.46875,.484375,.4921875,.125,.1875,.21875,.234375,.2421875,.24609375,.0625,.09375,.109375,.1171875,.12109375,.123046875,.03125,.046875,.0546875,.05859375,.060546875,.0615234375,.015625,.0234375,.02734375,.029296875,.0302734375,.03076171875],e.exports.pitches={A:5,B:6,C:0,D:1,E:2,F:3,G:4,a:12,b:13,c:7,d:8,e:9,f:10,g:11},e.exports.rests={x:"invisible",X:"invisible-multimeasure",y:"spacer",z:"rest",Z:"multimeasure"},e.exports.accMap={dblflat:"__",flat:"_",natural:"=",sharp:"^",dblsharp:"^^",quarterflat:"_/",quartersharp:"^/"},e.exports.tripletQ={2:3,3:2,4:3,5:2,6:2,7:2,8:3,9:2}},1881:function(e,t,r){var n=r(5008),a=function(e,t){this.lineIndex=0,this.lines=e,this.multilineVars=t,this.skipWhiteSpace=function(e){for(var t=0;t<e.length;t++)if(!this.isWhiteSpace(e[t]))return t;return e.length};var r=function(e,t){return t>=e.length};this.eatWhiteSpace=function(e,t){for(var r=t;r<e.length;r++)if(!this.isWhiteSpace(e[r]))return r-t;return r-t},this.getKeyPitch=function(e){var t=this.skipWhiteSpace(e);if(r(e,t))return{len:0};switch(e[t]){case"A":return{len:t+1,token:"A"};case"B":return{len:t+1,token:"B"};case"C":return{len:t+1,token:"C"};case"D":return{len:t+1,token:"D"};case"E":return{len:t+1,token:"E"};case"F":return{len:t+1,token:"F"};case"G":return{len:t+1,token:"G"}}return{len:0}},this.getSharpFlat=function(e){if("bass"===e)return{len:0};switch(e[0]){case"#":return{len:1,token:"#"};case"b":return{len:1,token:"b"}}return{len:0}},this.getMode=function(e){var t=function(e,t){for(;t<e.length&&(e[t]>="a"&&e[t]<="z"||e[t]>="A"&&e[t]<="Z");)t++;return t},n=this.skipWhiteSpace(e);if(r(e,n))return{len:0};var a=e.substring(n,n+3).toLowerCase();switch((a.length>1&&" "===a[1]||"^"===a[1]||"_"===a[1]||"="===a[1])&&(a=a[0]),a){case"mix":return{len:t(e,n),token:"Mix"};case"dor":return{len:t(e,n),token:"Dor"};case"phr":return{len:t(e,n),token:"Phr"};case"lyd":return{len:t(e,n),token:"Lyd"};case"loc":return{len:t(e,n),token:"Loc"};case"aeo":case"min":case"m":return{len:t(e,n),token:"m"};case"maj":case"ion":return{len:t(e,n),token:""}}return{len:0}},this.getClef=function(e,t){var a=e,i=this.skipWhiteSpace(e);if(r(e,i))return{len:0};var s=!1,o=e.substring(i);if(n.startsWith(o,"clef=")&&(s=!0,o=o.substring(5),i+=5),0===o.length&&s)return{len:i+5,warn:"No clef specified: "+a};var c=this.skipWhiteSpace(o);if(r(o,c))return{len:0};c>0&&(i+=c,o=o.substring(c));var l=null;if(n.startsWith(o,"treble"))l="treble";else if(n.startsWith(o,"bass3"))l="bass3";else if(n.startsWith(o,"bass"))l="bass";else if(n.startsWith(o,"tenor"))l="tenor";else if(n.startsWith(o,"alto2"))l="alto2";else if(n.startsWith(o,"alto1"))l="alto1";else if(n.startsWith(o,"alto"))l="alto";else if(!t&&s&&n.startsWith(o,"none"))l="none";else if(n.startsWith(o,"perc"))l="perc";else if(!t&&s&&n.startsWith(o,"C"))l="tenor";else if(!t&&s&&n.startsWith(o,"F"))l="bass";else{if(t||!s||!n.startsWith(o,"G"))return{len:i+5,warn:"Unknown clef specified: "+a};l="treble"}return o=o.substring(l.length),(c=this.isMatch(o,"+8"))>0?l+="+8":(c=this.isMatch(o,"-8"))>0&&(l+="-8"),{len:i+l.length,token:l,explicit:s}},this.getBarLine=function(e,t){switch(e[t]){case"]":switch(e[++t]){case"|":return{len:2,token:"bar_thick_thin"};case"[":return e[++t]>="1"&&e[t]<="9"||'"'===e[t]?{len:2,token:"bar_invisible"}:{len:1,warn:"Unknown bar symbol"};default:return{len:1,token:"bar_invisible"}}break;case":":switch(e[++t]){case":":return{len:2,token:"bar_dbl_repeat"};case"|":switch(e[++t]){case"]":return"|"===e[++t]&&":"===e[++t]?{len:5,token:"bar_dbl_repeat"}:{len:3,token:"bar_right_repeat"};case"|":return":"===e[++t]?{len:4,token:"bar_dbl_repeat"}:{len:3,token:"bar_right_repeat"};default:return{len:2,token:"bar_right_repeat"}}break;default:return{len:1,warn:"Unknown bar symbol"}}break;case"[":if("|"!==e[++t])return e[t]>="1"&&e[t]<="9"||'"'===e[t]?{len:1,token:"bar_invisible"}:{len:0};switch(e[++t]){case":":return{len:3,token:"bar_left_repeat"};case"]":return{len:3,token:"bar_invisible"};default:return{len:2,token:"bar_thick_thin"}}break;case"|":switch(e[++t]){case"]":return{len:2,token:"bar_thin_thick"};case"|":return":"===e[++t]?{len:3,token:"bar_left_repeat"}:{len:2,token:"bar_thin_thin"};case":":for(var r=0;":"===e[t+r];)r++;return{len:1+r,token:"bar_left_repeat"};default:return{len:1,token:"bar_thin"}}}return{len:0}},this.getTokenOf=function(e,t){for(var r=0;r<e.length;r++)if(t.indexOf(e[r])<0)return{len:r,token:e.substring(0,r)};return{len:r,token:e}},this.getToken=function(e,t,r){for(var n=t;n<r&&!this.isWhiteSpace(e[n]);)n++;return e.substring(t,n)},this.isMatch=function(e,t){var a=this.skipWhiteSpace(e);return r(e,a)?0:n.startsWith(e.substring(a),t)?a+t.length:0},this.getPitchFromTokens=function(e){var t={};if(t.position={A:5,B:6,C:0,D:1,E:2,F:3,G:4,a:12,b:13,c:7,d:8,e:9,f:10,g:11}[e[0].token],void 0===t.position)return{warn:"Pitch expected. Found: "+e[0].token};for(e.shift();e.length;)switch(e[0].token){case",":t.position-=7,e.shift();break;case"'":t.position+=7,e.shift();break;default:return t}return t},this.getKeyAccidentals2=function(e){for(var t;e.length>0;){var r;if("^"===e[0].token){if(r="sharp",e.shift(),0===e.length)return{accs:t,warn:"Expected note name after "+r};switch(e[0].token){case"^":r="dblsharp",e.shift();break;case"/":r="quartersharp",e.shift()}}else if("="===e[0].token)r="natural",e.shift();else{if("_"!==e[0].token)return{accs:t};if(r="flat",e.shift(),0===e.length)return{accs:t,warn:"Expected note name after "+r};switch(e[0].token){case"_":r="dblflat",e.shift();break;case"/":r="quarterflat",e.shift()}}if(0===e.length)return{accs:t,warn:"Expected note name after "+r};switch(e[0].token[0]){case"a":case"b":case"c":case"d":case"e":case"f":case"g":case"A":case"B":case"C":case"D":case"E":case"F":case"G":void 0===t&&(t=[]),t.push({acc:r,note:e[0].token[0]}),1===e[0].token.length?e.shift():e[0].token=e[0].token.substring(1);break;default:return{accs:t,warn:"Expected note name after "+r+" Found: "+e[0].token}}}return{accs:t}},this.getKeyAccidental=function(e){var t={"^":"sharp","^^":"dblsharp","=":"natural",_:"flat",__:"dblflat","_/":"quarterflat","^/":"quartersharp"},n=this.skipWhiteSpace(e);if(r(e,n))return{len:0};var a=null;switch(e[n]){case"^":case"_":case"=":a=e[n];break;default:return{len:0}}if(n++,r(e,n))return{len:1,warn:"Expected note name after accidental"};switch(e[n]){case"a":case"b":case"c":case"d":case"e":case"f":case"g":case"A":case"B":case"C":case"D":case"E":case"F":case"G":return{len:n+1,token:{acc:t[a],note:e[n]}};case"^":case"_":case"/":if(a+=e[n],n++,r(e,n))return{len:2,warn:"Expected note name after accidental"};switch(e[n]){case"a":case"b":case"c":case"d":case"e":case"f":case"g":case"A":case"B":case"C":case"D":case"E":case"F":case"G":return{len:n+1,token:{acc:t[a],note:e[n]}};default:return{len:2,warn:"Expected note name after accidental"}}break;default:return{len:1,warn:"Expected note name after accidental"}}},this.isWhiteSpace=function(e){return" "===e||"\t"===e||""===e},this.getMeat=function(e,t,r){var n=e.indexOf("%",t);for(n>=0&&n<r&&(r=n);t<r&&(" "===e[t]||"\t"===e[t]||""===e[t]);)t++;for(;t<r&&(" "===e[r-1]||"\t"===e[r-1]||""===e[r-1]);)r--;return{start:t,end:r}};var a=function(e){return e>="A"&&e<="Z"||e>="a"&&e<="z"},i=function(e){return e>="0"&&e<="9"};this.tokenize=function(e,t,r,n){var s=this.getMeat(e,t,r);t=s.start,r=s.end;for(var o,c=[];t<r;){if('"'===e[t]){for(o=t+1;o<r&&'"'!==e[o];)o++;c.push({type:"quote",token:e.substring(t+1,o),start:t+1,end:o}),o++}else if(a(e[t])){if(o=t+1,n)for(;o<r&&!this.isWhiteSpace(e[o]);)o++;else for(;o<r&&a(e[o]);)o++;c.push({type:"alpha",token:e.substring(t,o),continueId:i(e[o]),start:t,end:o}),t=o+1}else if("."===e[t]&&i(e[o+1])){o=t+1;for(var l;o<r&&i(e[o]);)o++;l=parseFloat(e.substring(t,o)),c.push({type:"number",token:e.substring(t,o),intt:null,floatt:l,continueId:a(e[o]),start:t,end:o}),t=o+1}else if(i(e[t])||"-"===e[t]&&i(e[o+1])){o=t+1;for(var h,u=null;o<r&&i(e[o]);)o++;if("."===e[o]&&i(e[o+1]))for(o++;o<r&&i(e[o]);)o++;else u=parseInt(e.substring(t,o));h=parseFloat(e.substring(t,o)),c.push({type:"number",token:e.substring(t,o),intt:u,floatt:h,continueId:a(e[o]),start:t,end:o}),t=o+1}else" "===e[t]||"\t"===e[t]||c.push({type:"punct",token:e[t],start:t,end:t+1}),o=t+1;t=o}return c},this.getVoiceToken=function(e,t,r){for(var n=t;n<r&&this.isWhiteSpace(e[n])||"="===e[n];)n++;if('"'===e[n]){var a=e.indexOf('"',n+1);return-1===a||a>=r?{len:1,err:"Missing close quote"}:{len:a-t+1,token:this.translateString(e.substring(n+1,a))}}for(var i=n;i<r&&!this.isWhiteSpace(e[i])&&"="!==e[i];)i++;return{len:i-t+1,token:e.substring(n,i)}};var s={"`a":"à","'a":"á","^a":"â","~a":"ã",'"a':"ä",oa:"å",aa:"å","=a":"ā",ua:"ă",";a":"ą","`e":"è","'e":"é","^e":"ê",'"e':"ë","=e":"ē",ue:"ĕ",";e":"ę",".e":"ė","`i":"ì","'i":"í","^i":"î",'"i':"ï","=i":"ī",ui:"ĭ",";i":"į","`o":"ò","'o":"ó","^o":"ô","~o":"õ",'"o':"ö","=o":"ō",uo:"ŏ","/o":"ø","`u":"ù","'u":"ú","^u":"û","~u":"ũ",'"u':"ü",ou:"ů","=u":"ū",uu:"ŭ",";u":"ų","`A":"À","'A":"Á","^A":"Â","~A":"Ã",'"A':"Ä",oA:"Å",AA:"Å","=A":"Ā",uA:"Ă",";A":"Ą","`E":"È","'E":"É","^E":"Ê",'"E':"Ë","=E":"Ē",uE:"Ĕ",";E":"Ę",".E":"Ė","`I":"Ì","'I":"Í","^I":"Î","~I":"Ĩ",'"I':"Ï","=I":"Ī",uI:"Ĭ",";I":"Į",".I":"İ","`O":"Ò","'O":"Ó","^O":"Ô","~O":"Õ",'"O':"Ö","=O":"Ō",uO:"Ŏ","/O":"Ø","`U":"Ù","'U":"Ú","^U":"Û","~U":"Ũ",'"U':"Ü",oU:"Ů","=U":"Ū",uU:"Ŭ",";U":"Ų",ae:"æ",AE:"Æ",oe:"œ",OE:"Œ",ss:"ß","'c":"ć","^c":"ĉ",uc:"č",cc:"ç",".c":"ċ",cC:"Ç","'C":"Ć","^C":"Ĉ",uC:"Č",".C":"Ċ","~N":"Ñ","~n":"ñ","=s":"š",vs:"š",DH:"Ð",dh:"ð",HO:"Ő",Ho:"ő",HU:"Ű",Hu:"ű","'Y":"Ý","'y":"ý","^Y":"Ŷ","^y":"ŷ",'"Y':"Ÿ",'"y':"ÿ",vS:"Š",vZ:"Ž",vz:"ž"},o={"#":"♯",b:"♭","=":"♮"},c={201:"♯",202:"♭",203:"♮",241:"¡",242:"¢",252:"a",262:"2",272:"o",302:"Â",312:"Ê",322:"Ò",332:"Ú",342:"â",352:"ê",362:"ò",372:"ú",243:"£",253:"«",263:"3",273:"»",303:"Ã",313:"Ë",323:"Ó",333:"Û",343:"ã",353:"ë",363:"ó",373:"û",244:"¤",254:"¬",264:" ́",274:"1⁄4",304:"Ä",314:"Ì",324:"Ô",334:"Ü",344:"ä",354:"ì",364:"ô",374:"ü",245:"¥",255:"-",265:"μ",275:"1⁄2",305:"Å",315:"Í",325:"Õ",335:"Ý",345:"å",355:"í",365:"õ",375:"ý",246:"¦",256:"®",266:"¶",276:"3⁄4",306:"Æ",316:"Î",326:"Ö",336:"Þ",346:"æ",356:"î",366:"ö",376:"þ",247:"§",257:" ̄",267:"·",277:"¿",307:"Ç",317:"Ï",327:"×",337:"ß",347:"ç",357:"ï",367:"÷",377:"ÿ",250:" ̈",260:"°",270:" ̧",300:"À",310:"È",320:"Ð",330:"Ø",340:"à",350:"è",360:"ð",370:"ø",251:"©",261:"±",271:"1",301:"Á",311:"É",321:"Ñ",331:"Ù",341:"á",351:"é",361:"ñ",371:"ù"};function l(e){var t=/^(\d+)\./.exec(e);return t?t[1]:null}this.translateString=function(e){var t=e.split("\\");if(1===t.length)return e;var r=null;return t.forEach(function(e){if(null===r)r=e;else{var t=s[e.substring(0,2)];void 0!==t?r+=t+e.substring(2):void 0!==(t=c[e.substring(0,3)])?r+=t+e.substring(3):(t=o[e.substring(0,1)],r+=void 0!==t?t+e.substring(1):"\\"+e)}}),r},this.getNumber=function(e,t){for(var r=0;t<e.length;)switch(e[t]){case"0":r*=10,t++;break;case"1":r=10*r+1,t++;break;case"2":r=10*r+2,t++;break;case"3":r=10*r+3,t++;break;case"4":r=10*r+4,t++;break;case"5":r=10*r+5,t++;break;case"6":r=10*r+6,t++;break;case"7":r=10*r+7,t++;break;case"8":r=10*r+8,t++;break;case"9":r=10*r+9,t++;break;default:return{num:r,index:t}}return{num:r,index:t}},this.getFraction=function(e,t){var r=1,n=1;if("/"!==e[t]){var a=this.getNumber(e,t);r=a.num,t=a.index}if("/"===e[t]){if("/"===e[++t]){for(var i=.5;"/"===e[t++];)i/=2;return{value:r*i,index:t-1}}var s=t,o=this.getNumber(e,t);0===o.num&&s===t&&(o.num=2),0!==o.num&&(n=o.num),t=o.index}return{value:r/n,index:t}};var h=[{match:/,\s*The$/,replace:"The "},{match:/,\s*the$/,replace:"the "},{match:/,\s*A$/,replace:"A "},{match:/,\s*a$/,replace:"a "},{match:/,\s*An$/,replace:"An "},{match:/,\s*an$/,replace:"an "},{match:/,\s*Da$/,replace:"Da "},{match:/,\s*La$/,replace:"La "},{match:/,\s*Le$/,replace:"Le "},{match:/,\s*Les$/,replace:"Les "},{match:/,\s*Ye$/,replace:"Ye "}];this.theReverser=function(e){for(var t=0;t<h.length;t++){var r=h[t],n=e.match(r.match);if(n){var a=l(e);a&&(e=(e=e.replace(a+".","")).trim());var i=n[0].length,s=r.replace+e.substring(0,e.length-i);return a&&(s=a+". "+s),s}}return e},this.stripComment=function(e){var t=e.indexOf("%");return t>=0?n.strip(e.substring(0,t)):n.strip(e)},this.getInt=function(e){var t=parseInt(e);if(isNaN(t))return{digits:0};var r=""+t;return{value:t,digits:e.indexOf(r)+r.length}},this.getFloat=function(e){var t=parseFloat(e);if(isNaN(t))return{digits:0};var r=""+t;return{value:t,digits:e.indexOf(r)+r.length}},this.getMeasurement=function(e){if(0===e.length)return{used:0};var t=1,r="";if("-"===e[0].token)e.shift(),r="-",t++;else if("number"!==e[0].type)return{used:0};if(r+=e.shift().token,0===e.length)return{used:1,value:parseInt(r)};var n=e.shift();if("."===n.token){if(t++,0===e.length)return{used:t,value:parseInt(r)};if("number"===e[0].type&&(r=r+"."+(n=e.shift()).token,t++,0===e.length))return{used:t,value:parseFloat(r)};n=e.shift()}switch(n.token){case"pt":case"px":return{used:t+1,value:parseFloat(r)};case"cm":return{used:t+1,value:parseFloat(r)/2.54*72};case"in":return{used:t+1,value:72*parseFloat(r)};default:return e.unshift(n),{used:t,value:parseFloat(r)}}};var u=function(e){return(e=e.replace(/\\n/g,"\n")).replace(/\\"/g,'"')};this.getBrackettedSubstring=function(e,t,r,n){for(var a=n||e[t],i=t+1,s=!1;i<e.length&&(s||e[i]!==a);)s="\\"===e[i],++i;return e[i]===a?[i-t+1,u(e.substring(t+1,i)),!0]:((i=t+r)>e.length-1&&(i=e.length-1),[i-t+1,u(e.substring(t+1,i)),!1])}};a.prototype.peekLine=function(){return this.lines[this.lineIndex]},a.prototype.nextLine=function(){if(this.lineIndex>0&&(this.multilineVars.iChar+=this.lines[this.lineIndex-1].length+1),this.lineIndex<this.lines.length){var e=this.lines[this.lineIndex];return this.lineIndex++,e}return null},e.exports=a},2821:function(e,t,r){var n=r(867),a=r(4208),i=r(9447),s={},o={C:0,"C#":1,Db:1,D:2,"D#":3,Eb:3,E:4,F:5,"F#":6,Gb:6,G:7,"G#":8,Ab:8,A:9,"A#":10,Bb:10,B:11},c=["C","Db","D","Eb","E","F","F#","G","Ab","A","Bb","B"],l=["C","C#","D","D#","E","F","F#","G","G#","A","Bb","B"];s.keySignature=function(e,t,r,n,a){if("perc"===e.clef.type||"none"===e.clef.type)return{accidentals:i(t),root:r,acc:n};a||(a=0),e.localTransposeVerticalMovement=0,e.localTransposePreferFlats=!1;var s=i(t);if(!s)return e.key;if(e.localTranspose=(e.globalTranspose?e.globalTranspose:0)+a,!e.localTranspose)return{accidentals:s,root:r,acc:n};if(e.globalTransposeOrigKeySig=s,e.localTranspose%12==0)return e.localTransposeVerticalMovement=e.localTranspose/12*7,{accidentals:s,root:r,acc:n};var h=t[0];"b"===t[1]||"#"===t[1]?(h+=t[1],t=t.substr(2)):t=t.substr(1);var u=o[h],d=void 0!==u;d||(u=0,h="C",t="");for(var f=u+e.localTranspose;f<0;)f+=12;f>11&&(f%=12);var p="m"===t[0]?l[f]:c[f],m=p+t,g=i(m);0!==g.length&&"flat"!==g[0].acc||(e.localTransposePreferFlats=!0);var v=m.charCodeAt(0)-h.charCodeAt(0);return e.localTranspose>0?v<0?v+=7:0===v&&("#"!==h[1]&&"b"!==m[1]||(v+=7)):e.localTranspose<0&&(v>0?v-=7:0===v&&("b"!==h[1]&&"#"!==m[1]||(v-=7))),e.localTranspose>0?e.localTransposeVerticalMovement=v+7*Math.floor(e.localTranspose/12):e.localTransposeVerticalMovement=v+7*Math.ceil(e.localTranspose/12),d?{accidentals:g,root:p[0],acc:p.length>1?p[1]:""}:{accidentals:[],root:r,acc:n}},s.chordName=function(e,t){return a(t,e.localTranspose,e.localTransposePreferFlats,e.freegchord)};var h=["c","d","e","f","g","a","b"],u={dblflat:-2,flat:-1,natural:0,sharp:1,dblsharp:2},d={"-2":"dblflat","-1":"flat",0:"natural",1:"sharp",2:"dblsharp"},f={"-2":"__","-1":"_",0:"=",1:"^",2:"^^"};s.note=function(e,t){if(e.localTranspose&&"perc"!==e.clef.type){var r=t.pitch;if(e.localTransposeVerticalMovement&&(t.pitch=t.pitch+e.localTransposeVerticalMovement,t.name)){var a=t.accidental?t.name.substring(1):t.name,i=t.accidental?t.name[0]:"",s=n.pitchIndex(a);t.name=i+n.noteName(s+e.localTransposeVerticalMovement)}if(t.accidental){var o=function(e,t,r,n,a){for(var i=h[(e+49)%7],s=0,o=0;o<n.length;o++)n[o].note.toLowerCase()===i&&(s=u[n[o].acc]);for(var c=u[r]-s,l=h[(t+49)%7],d=0,f=0;f<a.accidentals.length;f++)a.accidentals[f].note.toLowerCase()===l&&(d=u[a.accidentals[f].acc]);var p=c+d;return p<-2&&(t--,p+="c"===l||"f"===l?1:2),p>2&&(t++,p-="b"===l||"e"===l?1:2),[t,p]}(r,t.pitch,t.accidental,e.globalTransposeOrigKeySig,e.targetKey);t.pitch=o[0],t.accidental=d[o[1]],t.name&&(t.name=f[o[1]]+t.name.replace(/[_^=]/g,""))}}},e.exports=s},867:function(e){var t={},r=["C,,,","D,,,","E,,,","F,,,","G,,,","A,,,","B,,,","C,,","D,,","E,,","F,,","G,,","A,,","B,,","C,","D,","E,","F,","G,","A,","B,","C","D","E","F","G","A","B","c","d","e","f","g","a","b","c'","d'","e'","f'","g'","a'","b'","c''","d''","e''","f''","g''","a''","b''","c'''","d'''","e'''","f'''","g'''","a'''","b'''"];t.pitchIndex=function(e){return r.indexOf(e)},t.noteName=function(e){return r[e]},e.exports=t},6225:function(e){var t=["break","(break)","no chord","n.c.","tacet"];function r(e,t){if(e.decoration)for(var r=0;r<e.decoration.length;r++)switch(e.decoration[r]){case"fermata":case"segno":case"coda":case"D.C.":case"D.S.":case"D.C.alcoda":case"D.C.alfine":case"D.S.alcoda":case"D.S.alfine":case"fine":t.annotations||(t.annotations=[]),t.annotations.push(e.decoration[r])}}e.exports=function(e){var n=e.getMeterFraction(),a=4===n.num&&4===n.den;if((2!==n.num||2!==n.den)&&!a)throw new Error("notCommonTime");var i=e.deline(),s=[],o=!1;return i.forEach(function(e){if(e.subtitle)o&&s.push({type:"subtitle",subtitle:e.subtitle.text});else if(e.text)o=!0,s.push({type:"text",text:e.text.text});else if(e.staff){o=!0;var n=function(e){var n=[],a="",i=[],s={chord:["","","",""]},o="",c="";if(e.forEach(function(e,l){e.voices&&e.voices.forEach(function(e,h){var u=0,d=0;e.forEach(function(e){if("part"===e.el_type)i.length>0&&0===l&&0===h&&(n.push({type:"part",name:a,lines:[i]}),i=[]),a=e.title;else if("note"===e.el_type){r(e,s);var f=Math.floor(u);if(e.chord&&e.chord.length>0){var p=e.chord[0],m="default"===p.position||t.indexOf(p.name.toLowerCase())>=0?p.name:"";m&&(f>0&&!s.chord[0]&&(s.chord[0]=o),o=m,s.chord[f]?f<4&&!s.chord[f+1]&&(s.chord[f+1]=m):s.chord[f]=m),e.chord.forEach(function(e){"default"!==e.position&&t.indexOf(p.name.toLowerCase())<0&&(s.annotations||(s.annotations=[]),s.annotations.push(e.name))})}if(!e.rest||"spacer"!==e.rest.type){var g=0!==e.duration||e.rest?e.duration:.25,v=Math.floor(4*g);if(v>4)d+=Math.floor(v/4),u=0;else{var b=4*g;e.tripletMultiplier&&(b*=e.tripletMultiplier),u+=b}}}else if("bar"===e.el_type){if(c&&(s.ending=c,c=""),r(e,s),e.chord&&e.chord.forEach(function(e){"default"!==e.position&&(s.annotations||(s.annotations=[]),s.annotations.push(e.name))}),"bar_dbl_repeat"!==e.type&&"bar_left_repeat"!==e.type||(s.hasStartRepeat=!0),"bar_dbl_repeat"!==e.type&&"bar_right_repeat"!==e.type||(s.hasEndRepeat=!0),e.startEnding&&(c=e.startEnding),u>=4){if(""===s.chord[0]&&(s.chord[1]||s.chord[2]||s.chord[3])&&(s.chord[0]=function(e){for(var t=e.length-1;t>=0;t--)for(var r=e[t].chord.length-1;r>=0;r--)if(e[t].chord[r])return e[t].chord[r]}(i)),0===l&&0===h)i.push(s);else{for(var y=d,x=0;y>=n[x].lines[0].length&&x<n.length;)y-=n[x].lines[0].length,x++;if(x<n.length&&y<n[x].lines[0].length){var k=n[x].lines[0][y];!k.chord[0]&&s.chord[0]&&(k.chord[0]=s.chord[0]),!k.chord[1]&&s.chord[1]&&(k.chord[1]=s.chord[1]),!k.chord[2]&&s.chord[2]&&(k.chord[2]=s.chord[2]),!k.chord[3]&&s.chord[3]&&(k.chord[3]=s.chord[3]),s.annotations&&(k.annotations?k.annotations=k.annotations.concat(s.annotations):k.annotations=s.annotations)}d++}s={chord:["","","",""]}}else s.chord=["","","",""];u=0}else e.el_type}),0===l&&0===h&&n.push({type:"part",name:a,lines:[i]})})}),!o)throw new Error("noChords");return n}(e.staff);s=s.concat(n)}}),function(e){e.forEach(function(e){if("part"===e.type){var t=e.lines[0],r=t.findIndex(function(e){return!!e.ending}),n=t.findIndex(function(e,t){return t>r&&!!e.ending});if(r>=0&&n>=0&&n-r==t.length-n){for(var a=!0,i=0;i<n-r&&a;i++){var s=t[r+i],o=t[n+i];if(s.chord[0]!==o.chord[0]&&(a=!1),s.chord[1]!==o.chord[1]&&(a=!1),s.chord[2]!==o.chord[2]&&(a=!1),s.chord[3]!==o.chord[3]&&(a=!1),s.annotations&&!o.annotations&&(a=!1),!s.annotations&&o.annotations&&(a=!1),s.annotations&&o.annotations)if(s.annotations.length!==o.annotations.length)a=!1;else for(var c=0;c<s.annotations.length;c++)s.annotations[c]!==o.annotations[c]&&(a=!1)}a&&(delete t[r].ending,t.splice(n,t.length-n))}}})}(s),function(e){e.forEach(function(e){if("part"===e.type){var t=[],r=e.lines[0],n=!1,a=r.findIndex(function(e){return!!e.hasEndRepeat});12===(a>=0?Math.min(a+1,r.length):r.length)&&(n=!0);for(var i=n?4:8,s=0;s<r.length;s+=i){var o=r.slice(s,s+i),c=o.findIndex(function(e){return!!e.hasEndRepeat});c>=0&&c<o.length-1?(t.push(o.slice(0,c+1)),t.push(o.slice(c+1))):t.push(o)}for(var l=0;l<t.length;l++)if(t[l][0].ending){for(var h=t[Math.max(0,l-1)].length-t[l].length,u=[],d=0;d<h;d++)u.push({noBorder:!0,chord:["","","",""]});t[l]=u.concat(t[l])}e.lines=t}})}(s),function(e){e.forEach(function(e){if(e.lines){var t=!1,r="";e.lines.forEach(function(e){e.forEach(function(e){if(!e.noBorder){var n=e.chord;n[0]||n[1]||n[2]||n[3]?n[1]||n[2]||n[3]?(t=!1,r=n[3]||n[2]||n[1]):(t=!0,r=n[0]):(t?r&&(n[0]="%"):n[0]=r,t=!0)}})})}})}(s),s}},4208:function(e){var t=["C","C♯","D","D♯","E","F","F♯","G","G♯","A","A♯","B"],r=["C","D♭","D","E♭","E","F","G♭","G","A♭","A","B♭","B"],n=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"],a=["C","Db","D","Eb","E","F","Gb","G","Ab","A","Bb","B"];e.exports=function(e,i,s,o){if(!i||i%12==0)return e;for(;i<0;)i+=12;i>11&&(i%=12);var c=e.match(/^([A-G][b#♭♯]?)([^\/]+)?\/?([A-G][b#♭♯]?)?(.+)?/);if(!c)return e;var l=c[1],h=c[2],u=c[3],d=c[4];if((f=t.indexOf(l))<0&&(f=r.indexOf(l)),f<0&&(f=n.indexOf(l)),f<0&&(f=a.indexOf(l)),f<0)return e;f+=i,f%=12,e=s?o?a[f]:r[f]:o?n[f]:t[f];var f,p=h&&(h.indexOf("dim")>=0||h.indexOf("°")>=0);return p&&"A#"===e&&(e="Bb"),p&&"D#"===e&&(e="Eb"),p&&"A♯"===e&&(e="B♭"),p&&"D♯"===e&&(e="E♭"),h&&(e+=h),u&&((f=t.indexOf(u))<0&&(f=r.indexOf(u)),f<0&&(f=n.indexOf(u)),f<0&&(f=a.indexOf(u)),e+="/",f>=0?(f+=i,f%=12,e+=s?o?a[f]:r[f]:o?n[f]:t[f]):e+=u),d&&(e+=d),e}},575:function(e,t,r){var n=r(9708);function a(e){if(!e)return!1;if("string"==typeof e)return!1;for(var t=0;t<e.length;t++)if("string"!=typeof e[t])return!1;return!0}function i(e){for(var t=!1,r=0;r<e.lines.length;r++){var n=e.lines[r];if(n.staff)for(var a=0;a<n.staff.length;a++){for(var i=n.staff[a],o=[],c=0;c<i.voices.length;c++){var l=i.voices[c];o.push({hasOverlay:!1,voice:[],snip:[]});for(var h=0,u=!1,d=-1,f=0;f<l.length;f++){var p=l[f];if("overlay"!==p.el_type||u)"bar"===p.el_type?(u?(u=!1,o[c].snip.push({start:d,len:f-d}),o[c].voice.push(p)):(h>0&&o[c].voice.push({el_type:"note",duration:h,rest:{type:"invisible"},startChar:p.startChar,endChar:p.endChar}),o[c].voice.push(p)),h=0):"note"===p.el_type?u?o[c].voice.push(p):p.rest&&"spacer"===p.rest.type||(h+=p.duration):"scale"!==p.el_type&&"stem"!==p.el_type&&"overlay"!==p.el_type&&"style"!==p.el_type&&"transpose"!==p.el_type&&"color"!==p.el_type||o[c].voice.push(p);else{t=!0,u=!0,d=f,o[c].hasOverlay=!0;for(var m=0;m<r;m++)e.lines[m].staff&&e.lines[m].staff.forEach(function(e){i.voices.length>=e.voices.length&&e.voices.forEach(function(t){var r=[];t.forEach(function(e){"bar"===e.el_type?r.push(e):"note"===e.el_type&&r.push({el_type:"note",duration:e.duration,rest:{type:"invisible"},startChar:e.startChar,endChar:e.endChar})}),e.voices.push(r)})})}}o[c].hasOverlay&&0===o[c].snip.length&&o[c].snip.push({start:d,len:l.length-d})}for(c=0;c<o.length;c++){var g=o[c];if(g.hasOverlay){g.voice.splice(0,0,{el_type:"stem",direction:"down"}),i.voices.push(g.voice);for(var v=g.snip.length-1;v>=0;v--){var b=g.snip[v];i.voices[c].splice(b.start,b.len),i.voices[c].splice(b.start+1,0,{el_type:"stem",direction:"auto"});var y=s(i.voices[c],b.start);i.voices[c].splice(y,0,{el_type:"stem",direction:"up"})}for(v=0;v<i.voices[i.voices.length-1].length;v++){i.voices[i.voices.length-1][v]=Object.assign({},i.voices[i.voices.length-1][v]);var x=i.voices[i.voices.length-1][v];"bar"===x.el_type&&x.startEnding&&delete x.startEnding,"bar"===x.el_type&&x.endEnding&&delete x.endEnding}}}}}return t}function s(e,t){for(var r=t-1;r>0&&"bar"!==e[r].el_type;r--);return r}function o(e,t,r,n){var a;n[t]||(n[t]=[]),n[t][r]||(n[t][r]=[]);for(var i=function(e,i,s){if(void 0===n[t][r][s]){for(a=0;a<n[t][r].length;a++)if(void 0!==n[t][r][a]){s=a;break}if(void 0===n[t][r][s]){var o=100*s+1;e.endSlur.forEach(function(e){o===e&&--o}),n[t][r][s]=[o]}}for(var c,l=0;l<i;l++)c=n[t][r][s].pop(),e.endSlur.push(c);return 0===n[t][r][s].length&&delete n[t][r][s],c},s=function(e,a,i,s){e.startSlur=[],void 0===n[t][r][i]&&(n[t][r][i]=[]);for(var o=100*i+1,c=0;c<a;c++)s&&(s.forEach(function(e){o===e&&++o}),s.forEach(function(e){o===e&&++o}),s.forEach(function(e){o===e&&++o})),n[t][r][i].forEach(function(e){o===e&&++o}),n[t][r][i].forEach(function(e){o===e&&++o}),n[t][r][i].push(o),e.startSlur.push({label:o}),e.dottedSlur&&(e.startSlur[e.startSlur.length-1].style="dotted",delete e.dottedSlur),o++},o=0;o<e.length;o++){var c=e[o];if("note"===c.el_type){if(c.gracenotes)for(var l=0;l<c.gracenotes.length;l++){if(c.gracenotes[l].endSlur){var h=c.gracenotes[l].endSlur;c.gracenotes[l].endSlur=[];for(var u=0;u<h;u++)i(c.gracenotes[l],1,20)}c.gracenotes[l].startSlur&&(a=c.gracenotes[l].startSlur,s(c.gracenotes[l],a,20))}if(c.endSlur&&(a=c.endSlur,c.endSlur=[],i(c,a,0)),c.startSlur&&s(c,a=c.startSlur,0),c.pitches){for(var d=[],f=0;f<c.pitches.length;f++)if(c.pitches[f].endSlur){var p=c.pitches[f].endSlur;c.pitches[f].endSlur=[];for(var m=0;m<p;m++){var g=i(c.pitches[f],1,f+1);d.push(g)}}for(f=0;f<c.pitches.length;f++)c.pitches[f].startSlur&&(a=c.pitches[f].startSlur,s(c.pitches[f],a,f+1,d));c.gracenotes&&c.pitches[0].endSlur&&100===c.pitches[0].endSlur[0]&&c.pitches[0].startSlur&&(c.gracenotes[0].endSlur?c.gracenotes[0].endSlur.push(c.pitches[0].startSlur[0].label):c.gracenotes[0].endSlur=[c.pitches[0].startSlur[0].label],1===c.pitches[0].endSlur.length?delete c.pitches[0].endSlur:100===c.pitches[0].endSlur[0]?c.pitches[0].endSlur.shift():100===c.pitches[0].endSlur[c.pitches[0].endSlur.length-1]&&c.pitches[0].endSlur.pop(),1===n[t][r][1].length?delete n[t][r][1]:n[t][r][1].pop())}}}}function c(e,t){for(var r=0;r<e.length;r++)if(void 0!==e[r].staff)for(var n=0;n<e[r].staff.length;n++)for(var a=[],i=0;i<e[r].staff[n].voices.length;i++)for(var s=e[r].staff[n].voices[i],o=0,c=0;c<s.length;c++)if("bar"===s[c].el_type){if(++o>=t&&c<s.length-1){var h=l(e,r);if(!h){var u=JSON.parse(JSON.stringify(e[r]));e.push(Object.assign({},u)),h=e[e.length-1];for(var d=0;d<h.staff.length;d++)for(var f=0;f<h.staff[d].voices.length;f++)h.staff[d].voices[f]=[]}var p=c+1,m=e[r].staff[n].voices[i].slice(p);return e[r].staff[n].voices[i]=e[r].staff[n].voices[i].slice(0,p),h.staff[n].voices[i]=a.concat(m.concat(h.staff[n].voices[i])),!0}}else s[c].duration||a.push(s[c]);return!1}function l(e,t){for(t++;e.length>t;){if(e[t].staff)return e[t];t++}return null}function h(e){e.potentialStartBeam&&e.potentialEndBeam&&(e.potentialStartBeam.startBeam=!0,e.potentialEndBeam.endBeam=!0),delete e.potentialStartBeam,delete e.potentialEndBeam}function u(e){for(var t=0;t<e.length;t++)if("note"===e[t].el_type||"bar"===e[t].el_type)return!0;return!1}function d(e){for(var t=0;t<e.length;t++)if("note"===e[t].el_type&&(void 0===e[t].rest||void 0!==e[t].chord))return!0;return!1}function f(e,t){e.vskipPending&&(t.vskip=e.vskipPending,delete e.vskipPending),e.lines.push(t)}function p(e){void 0!==e.potentialStartBeam&&void 0!==e.potentialEndBeam&&(e.potentialStartBeam.startBeam=!0,e.potentialEndBeam.endBeam=!0),delete e.potentialStartBeam,delete e.potentialEndBeam}function m(e,t,r){if(e.runningFonts[t]){for(var n=!1,a=Object.keys(r),i=0;i<a.length;i++)e.runningFonts[t][a[i]]!==r[a[i]]&&(n=!0);n&&(e.lines[e.lineNum].staff[e.staffNum][t]=r)}e.runningFonts[t]=r}function g(e,t,r){var n=t.lines[t.lineNum].staff[t.staffNum];if(n.voices[t.voiceNum]=[],n.title||(n.title=[]),n.title[t.voiceNum]={name:r.name,subname:r.subname},r.style&&e.appendElement("style",null,null,{head:r.style}),r.stem)e.appendElement("stem",null,null,{direction:r.stem});else if(t.voiceNum>0){if(void 0!==n.voices[0]){for(var a=!1,i=0;i<n.voices[0].length;i++)"stem"===n.voices[0].el_type&&(a=!0);a||n.voices[0].splice(0,0,{el_type:"stem",direction:"up"})}e.appendElement("stem",null,null,{direction:"down"})}r.scale&&e.appendElement("scale",null,null,{size:r.scale}),r.color&&e.appendElement("color",null,null,{color:r.color})}function v(e,t,r){r.key&&r.key.impliedNaturals&&(r.key.accidentals=r.key.accidentals.concat(r.key.impliedNaturals),delete r.key.impliedNaturals),t.lines[t.lineNum].staff[t.staffNum]={voices:[],clef:r.clef,key:r.key,workingClef:r.clef};var n=t.lines[t.lineNum].staff[t.staffNum];void 0!==r.stafflines&&(n.clef.stafflines=r.stafflines,n.workingClef.stafflines=r.stafflines),r.staffscale&&(n.staffscale=r.staffscale),r.annotationfont&&m(t,"annotationfont",r.annotationfont),r.gchordfont&&m(t,"gchordfont",r.gchordfont),r.tripletfont&&m(t,"tripletfont",r.tripletfont),r.vocalfont&&m(t,"vocalfont",r.vocalfont),r.bracket&&(n.bracket=r.bracket),r.brace&&(n.brace=r.brace),r.connectBarLines&&(n.connectBarLines=r.connectBarLines),r.barNumber&&(n.barNumber=r.barNumber),g(e,t,r),r.part&&e.appendElement("part",r.part.startChar,r.part.endChar,{title:r.part.title}),void 0!==r.meter&&(n.meter=r.meter),t.vskipPending&&(t.lines[t.lineNum].vskip=t.vskipPending,delete t.vskipPending)}function b(e,t){for(var r=!1,n=!1,a=0;a<e.length;a++){var i=e[a].staff;if(i)for(var s=0;s<i.length;s++){var o=i[s];if(t<o.voices.length){n=!0;for(var c=o.voices[t],l=0;l<c.length;l++){var h=c[l];"note"!==h.el_type||h.rest&&!h.chord||(r=!0)}}}}return n?r:"not-found"}function y(e,t){for(var r=0;r<e.length;r++){var n=e[r].staff;if(n)for(var a=0;a<n.length;a++){var i=n[a];t<i.voices.length&&i.voices.splice(t,1)}}}e.exports=function(e){var t=this,r={},s="";e.reset(),this.setVisualTranspose=function(t){void 0!==t&&(e.visualTranspose=t)},this.cleanUp=function(t,r,s){h(e),delete e.runningFonts,function(e){a(e.metaText.notes)&&(e.metaText.notes=e.metaText.notes.join("\n")),a(e.metaText.history)&&(e.metaText.history=e.metaText.history.join("\n"))}(e),e.metaText.tempo&&e.metaText.tempo.bpm&&!e.metaText.tempo.duration&&(e.metaText.tempo.duration=[e.getBeatLength()]),function(e){for(var t=1;t<e.lines.length;t++)if(e.lines[t].subtitle){var r=e.lines[t-1];if(r.staff)for(var n=0;n<r.staff.length;n++)for(var a=0;a<r.staff[n].voices.length;a++){var i=r.staff[n].voices[a];if("key"===i[i.length-1].el_type){i.pop();for(var s=e.lines[t];t<e.lines.length&&!s.staff;)t++,s=e.lines[t];if(s)for(var o=0;o<s.staff.length;o++){for(var c=s.staff[o].key.accidentals,l=[],h=0;h<c.length;h++)"natural"!==c[h].acc&&l.push(c[h]);s.staff[o].key.accidentals=l}}}}}(e);var f,p,m=!1;for(C=0;C<e.lines.length;C++)if(void 0!==e.lines[C].staff){var g=!1;for(f=0;f<e.lines[C].staff.length;f++)if(void 0===e.lines[C].staff[f])m=!0,e.lines[C].staff[f]=null;else for(p=0;p<e.lines[C].staff[f].voices.length;p++)void 0===e.lines[C].staff[f].voices[p]?e.lines[C].staff[f].voices[p]=[]:u(e.lines[C].staff[f].voices[p])&&(g=!0);g||(e.lines[C]=null,m=!0)}if(m&&(e.lines=e.lines.filter(function(e){return!!e}),e.lines.forEach(function(e){e.staff&&(e.staff=e.staff.filter(function(e){return!!e}))})),t)for(;c(e.lines,t););if(r){for(m=!1,C=0;C<e.lines.length;C++)if(void 0!==e.lines[C].staff)for(f=0;f<e.lines[C].staff.length;f++){var v=!1;for(p=0;p<e.lines[C].staff[f].voices.length;p++)d(e.lines[C].staff[f].voices[p])&&(v=!0);v||(m=!0,e.lines[C].staff[f]=null)}m&&e.lines.forEach(function(e){e.staff&&(e.staff=e.staff.filter(function(e){return!!e}))})}for(function(e){for(var t=!0,r=0;r<e.length;r++){var n=e[r];if(n.staff){for(var a=0;a<n.staff.length;a++){var i=n.staff[a];if(i.title){for(var s=!1,o=0;o<i.title.length;o++)i.title[o]?(i.title[o]=t?i.title[o].name:i.title[o].subname,i.title[o]?s=!0:i.title[o]=""):i.title[o]="";s||delete i.title}}t=!1}}}(e.lines),C=0;C<e.lines.length;C++)if(e.lines[C].staff)for(f=0;f<e.lines[C].staff.length;f++)delete e.lines[C].staff[f].workingClef;for(var x=!1;i(e);)x=!0;if(x)for(var k=0,w=b(e.lines,k);"not-found"!==w;)(w=b(e.lines,k))?k++:y(e.lines,k);for(var C=0;C<e.lines.length;C++){var T=e.lines[C].staff;if(T)for(e.staffNum=0;e.staffNum<T.length;e.staffNum++)for(T[e.staffNum].clef&&n.fixClef(T[e.staffNum].clef),e.voiceNum=0;e.voiceNum<T[e.staffNum].voices.length;e.voiceNum++){var S=T[e.staffNum].voices[e.voiceNum];o(S,e.staffNum,e.voiceNum,s);for(var _=0;_<S.length;_++)"clef"===S[_].el_type&&n.fixClef(S[_]);if(S.length>0&&S[S.length-1].barNumber){var E=l(e.lines,C);E&&(E.staff[0].barNumber=S[S.length-1].barNumber),delete S[S.length-1].barNumber}}}return delete e.staffNum,delete e.voiceNum,delete e.lineNum,delete e.potentialStartBeam,delete e.potentialEndBeam,delete e.vskipPending,s},this.addTieToLastNote=function(t){var r=function(e){if(!e.lines[e.lineNum])return null;if(!e.lines[e.lineNum].staff)return null;if(!e.lines[e.lineNum].staff[e.staffNum])return null;var t=e.lines[e.lineNum].staff[e.staffNum].voices[e.voiceNum];if(!t)return null;for(var r=t.length-1;r>=0;r--){var n=t[r];if("note"===n.el_type)return n}return null}(e);return!!(r&&r.pitches&&r.pitches.length>0)&&(r.pitches[0].startTie={},t&&(r.pitches[0].startTie.style="dotted"),!0)},this.appendElement=function(n,a,i,o){var c;return o.el_type=n,null!==a&&(o.startChar=a),null!==i&&(o.endChar=i),"note"===n?((c=o).duration?c.duration:0)>=.25||o.force_end_beam_last&&void 0!==e.potentialStartBeam?p(e):o.end_beam&&void 0!==e.potentialStartBeam?void 0===o.rest?function(e,t){t.potentialStartBeam.startBeam=!0,e.endBeam=!0,delete t.potentialStartBeam,delete t.potentialEndBeam}(o,e):p(e):void 0===o.rest&&(void 0===e.potentialStartBeam?o.end_beam||(e.potentialStartBeam=o,delete e.potentialEndBeam):e.potentialEndBeam=o):p(e),delete o.end_beam,delete o.force_end_beam_last,o.rest&&"invisible"===o.rest.type&&delete o.decoration,!(e.lines.length<=e.lineNum||e.lines[e.lineNum].staff.length<=e.staffNum||(function(e,t,r,n,a){var i=t.lines[t.lineNum].staff[t.staffNum];if(void 0!==r.pitches){var s=i.workingClef.verticalPos;r.pitches.forEach(function(e){e.verticalPos=e.pitch-s})}if(void 0!==r.gracenotes){var o=i.workingClef.verticalPos;r.gracenotes.forEach(function(e){e.verticalPos=e.pitch-o})}i.voices.length<=t.voiceNum&&(n[a]||(n[a]={}),g(e,t,n[a])),i.voices[t.voiceNum].push(r)}(t,e,o,r,s),0))},this.appendStartingElement=function(t,r,n,a){var i;h(e),"key"===t&&(i=a.impliedNaturals,delete a.impliedNaturals,delete a.explicitAccidentals);var s=Object.assign({},a);if(e.lines[e.lineNum]){var o=e.lines[e.lineNum].staff;if(o){o.length<=e.staffNum&&(o[e.staffNum]={},o[e.staffNum].clef=Object.assign({},o[0].clef),o[e.staffNum].key=Object.assign({},o[0].key),o[0].meter&&(o[e.staffNum].meter=Object.assign({},o[0].meter)),o[e.staffNum].workingClef=Object.assign({},o[0].workingClef),o[e.staffNum].voices=[[]]),"clef"===t&&(o[e.staffNum].workingClef=s);for(var c=o[e.staffNum].voices[e.voiceNum],l=0;l<c.length;l++){if("note"===c[l].el_type||"bar"===c[l].el_type)return s.el_type=t,s.startChar=r,s.endChar=n,i&&(s.accidentals=i.concat(s.accidentals)),void c.push(s);if(c[l].el_type===t)return s.el_type=t,s.startChar=r,s.endChar=n,i&&(s.accidentals=i.concat(s.accidentals)),void(c[l]=s)}o[e.staffNum][t]=a}}},this.addSubtitle=function(t,r){f(e,{subtitle:{text:t,startChar:r.startChar,endChar:r.endChar}})},this.addSpacing=function(t){e.vskipPending=t},this.addNewPage=function(t){f(e,{newpage:t})},this.addSeparator=function(t,r,n,a){f(e,{separator:{spaceAbove:Math.round(t),spaceBelow:Math.round(r),lineLength:Math.round(n),startChar:a.startChar,endChar:a.endChar}})},this.addText=function(t,r){f(e,{text:{text:t,startChar:r.startChar,endChar:r.endChar}})},this.addCentered=function(t){f(e,{text:[{text:t,center:!0}]})},this.changeVoiceScale=function(e){t.appendElement("scale",null,null,{size:e})},this.changeVoiceColor=function(e){t.appendElement("color",null,null,{color:e})},this.startNewLine=function(n){h(e),n.currentVoiceName&&(s=n.currentVoiceName,r[n.currentVoiceName]=n),void 0===e.lines[e.lineNum]?function(e,t,r){t.lines[t.lineNum]={staff:[]},v(e,t,r)}(t,e,n):void 0===e.lines[e.lineNum].staff?(e.lineNum++,this.startNewLine(n)):void 0===e.lines[e.lineNum].staff[e.staffNum]?v(t,e,n):void 0===e.lines[e.lineNum].staff[e.staffNum].voices[e.voiceNum]?g(t,e,n):u(e.lines[e.lineNum].staff[e.staffNum].voices[e.voiceNum])?(e.lineNum++,this.startNewLine(n)):n.part&&t.appendElement("part",n.part.startChar,n.part.endChar,{title:n.part.title})},this.setRunningFont=function(t,r){e.runningFonts[t]=r},this.setBarNumberImmediate=function(e){var t=this.getCurrentVoice();if(t&&t.length>0){var r=t[t.length-1];if("bar"!==r.el_type)return e-1;void 0!==r.barNumber&&(r.barNumber=e)}return e},this.hasBeginMusic=function(){for(var t=0;t<e.lines.length;t++)if(e.lines[t].staff)return!0;return!1},this.isFirstLine=function(t){for(var r=t-1;r>=0;r--)if(void 0!==e.lines[r].staff)return!1;return!0},this.getCurrentVoice=function(){var t=function(e,t){if(e.length<=t)return null;for(;t>=0;){if(e[t].staff)return e[t];t--}return null}(e.lines,e.lineNum);if(!t)return null;var r=t.staff[e.staffNum];return r&&void 0!==r.voices[e.voiceNum]?r.voices[e.voiceNum]:null},this.setCurrentVoice=function(t,r,n){e.staffNum=t,e.voiceNum=r,s=n;for(var a=0;a<e.lines.length;a++)if(e.lines[a].staff&&(void 0===e.lines[a].staff[t]||void 0===e.lines[a].staff[t].voices[r]||!u(e.lines[a].staff[t].voices[r])))return e.lineNum=a,!(e.lines[a].staff[t]&&!e.lines[a].staff[t].voices[r]);return e.lineNum=a,!1},this.addMetaText=function(t,r,n){void 0===e.metaText[t]?(e.metaText[t]=r,e.metaTextInfo[t]=n):("string"==typeof e.metaText[t]&&"string"==typeof r?e.metaText[t]+="\n"+r:("string"===e.metaText[t]&&(e.metaText[t]=[{text:e.metaText[t]}]),"string"==typeof r&&(r=[{text:r}]),e.metaText[t]=e.metaText[t].concat(r)),e.metaTextInfo[t].endChar=n.endChar)},this.addMetaTextArray=function(t,r,n){void 0===e.metaText[t]?(e.metaText[t]=[r],e.metaTextInfo[t]=n):(e.metaText[t].push(r),e.metaTextInfo[t].endChar=n.endChar)},this.addMetaTextObj=function(t,r,n){e.metaText[t]=r,e.metaTextInfo[t]=n}}},1756:function(e){function t(e,t){for(var r=[],n=[],a=0,i=0;i<e.length;i++){var s=e[i],o=a+s;o<t?a=o:t-a<o-t&&a>0?(r.push(i-1),n.push(Math.round(a-s)),a=s):i<e.length-1&&(r.push(i),n.push(Math.round(a)),a=0)}return n.push(Math.round(a)),{lineBreaks:r,totals:n}}function r(e){for(var t=[],r=0;r<e.length;r++)t.push(e[r]);return t}function n(e,t,n,a,i,s,o,c,l,h,u){for(var d=h;d<e.length;d++){var f=e[d];n+=f,a+=f;var p=Math.abs(n-t[c]);if(Math.abs(p-s)<t[0]/10)if(p<s){var m=r(i),g=r(l);g.push(d-1),m.push(a-f),u.push({accumulator:n,lineAccumulator:f,lineWidths:m,lastVariance:Math.abs(n-t[c+1]),highestVariance:Math.max(o,s),currLine:c+1,lineBreaks:g,startIndex:d+1})}else p>s&&d<e.length-1&&(m=r(i),g=r(l),u.push({accumulator:n,lineAccumulator:a,lineWidths:m,lastVariance:p,highestVariance:Math.max(o,p),currLine:c,lineBreaks:g,startIndex:d+1}));p>s?(l.push(d-1),c++,o=Math.max(o,s),s=Math.abs(n-t[c]),i.push(a-f),a=f):s=p}i.push(a)}function a(e,t,r,a){for(var i=Math.ceil(e.total/t),s=Math.floor(e.total/i),o=[],c=0;c<i;c++)o.push(s*(c+1));var l=[];l.push({accumulator:0,lineAccumulator:0,lineWidths:[],lastVariance:999999,highestVariance:0,currLine:0,lineBreaks:[],startIndex:0});for(var h=0;h<l.length;)n(e.measureWidths,o,l[h].accumulator,l[h].lineAccumulator,l[h].lineWidths,l[h].lastVariance,l[h].highestVariance,l[h].currLine,l[h].lineBreaks,l[h].startIndex,l),h++;for(c=0;c<l.length;c++){var u=l[c];u.variances=[],u.aveVariance=0;for(var d=0;d<u.lineWidths.length;d++){var f=u.lineWidths[d];u.variances.push(f-o[0]),u.aveVariance+=Math.abs(f-o[0])}u.aveVariance=u.aveVariance/u.lineWidths.length,a.attempts.push({type:"optimizeLineWidths",lineBreaks:u.lineBreaks,variances:u.variances,aveVariance:u.aveVariance,widths:e.measureWidths})}var p=9999999,m=-1;for(c=0;c<l.length;c++)(u=l[c]).aveVariance<p&&(p=u.aveVariance,m=c);return{failed:!1,lineBreaks:l[m].lineBreaks,variance:l[m].highestVariance}}function i(e,t,r){for(var n=[],a=[],i=0,s=!1,o=0;o<e.length;o++)(i+=e[o])>t&&(s=!0),o%r==r-1&&(o!==e.length-1&&n.push(o),a.push(Math.round(i)),i=0);return{failed:s,totals:a,lineBreaks:n}}e.exports={wrapLines:function(e,t,r){if(t&&0!==e.lines.length){var n=e.deline({lineBreaks:!1}),a=function(e,t){for(var r=[],n=0,a=0,i=0,s=0;s<e.length;s++){var o=e[s];if(o.staff){var c=a,l=t[n];n++;for(var h=0;h<o.staff.length;h++)for(var u=o.staff[h],d=0;d<u.voices.length;d++){i=c;for(var f=0,p=0,m=u.voices[d],g=0,v=0;v<m.length;v++)"bar"===m[v].el_type&&(l[p]===f&&(r.push({ogLine:s,line:i,staff:h,voice:d,start:g,end:v}),g=v+1,i++,a=Math.max(a,i),p++),f++);r.push({ogLine:s,line:i,staff:h,voice:d,start:g,end:m.length}),i++,a=Math.max(a,i)}}else r.push({ogLine:s,line:i}),i++,a=Math.max(a,i)}return r}(n,t);e.lines=function(e,t,r){for(var n=[],a=[],i=[],s=1,o=0;o<t.length;o++){var c=t[o];if(e[c.ogLine].staff){var l=e[c.ogLine].staff[c.staff];if(n[c.line]||(n[c.line]={staff:[]}),!n[c.line].staff[c.staff]){n[c.line].staff[c.staff]={voices:[]},void 0!==r&&0===c.staff&&c.line>0&&(n[c.line].staff[c.staff].barNumber=s);for(var h=Object.keys(l),u=0;u<h.length;u++){var d="voices"===h[u];"meter"===h[u]&&0!==c.line&&(d=!0),d||(n[c.line].staff[c.staff][h[u]]=l[h[u]])}a[c.staff]&&(n[c.line].staff[c.staff].key=a[c.staff])}n[c.line].staff[c.staff].voices[c.voice]||(n[c.line].staff[c.staff].voices[c.voice]=[]),n[c.line].staff[c.staff].voices[c.voice]=e[c.ogLine].staff[c.staff].voices[c.voice].slice(c.start,c.end+1),i[10*c.staff+c.voice]&&n[c.line].staff[c.staff].voices[c.voice].unshift({el_type:"stem",direction:i[10*c.staff+c.voice].direction});for(var f=n[c.line].staff[c.staff].voices[c.voice],p=f.length-1;p>=0;p--)if("key"===f[p].el_type){a[c.staff]={root:f[p].root,acc:f[p].acc,mode:f[p].mode,accidentals:f[p].accidentals.filter(function(e){return"natural"!==e.acc})};break}for(p=f.length-1;p>=0;p--)if("stem"===f[p].el_type){i[10*c.staff+c.voice]={direction:f[p].direction};break}if(void 0!==r&&0===c.staff&&0===c.voice)for(p=0;p<f.length;p++)"bar"===f[p].el_type&&(s++,p===f.length-1?delete f[p].barNumber:f[p].barNumber=s)}else n[c.line]=e[c.ogLine]}for(var m=0;m<n.length;m++)n[m].staff&&(n[m].staff=n[m].staff.filter(function(e){return null!=e}));return n}(n,a,r),e.lineBreaks=a}},calcLineWraps:function(e,r,n){if(0===r.length||n.staffwidth<r[0].left)return{reParse:!1,explanation:"Staff width is narrower than the margin",revisedParams:n};var s=n.scale?Math.max(n.scale,.1):1,o=n.wrap.minSpacing?Math.max(parseFloat(n.wrap.minSpacing),1):1,c=n.wrap.minSpacingLimit?Math.max(parseFloat(n.wrap.minSpacingLimit),1):o-.1,l=n.wrap.maxSpacing?Math.max(parseFloat(n.wrap.maxSpacing),1):void 0;n.wrap.lastLineLimit&&!l&&(l=Math.max(parseFloat(n.wrap.lastLineLimit),1));for(var h=n.wrap.preferredMeasuresPerLine?Math.max(parseInt(n.wrap.preferredMeasuresPerLine,10),0):void 0,u=[],d=[],f=0;f<r.length;f++){var p=r[f],m=n.staffwidth-p.left,g=m/o/s,v=m/c/s,b={widths:p,lineBreakPoint:g,minLineSize:m/l/s,attempts:[],staffWidth:n.staffwidth,minWidth:Math.round(v)},y=null;if(h){var x=i(p.measureWidths,g,h);b.attempts.push({type:"Fixed Measures Per Line",preferredMeasuresPerLine:h,lineBreaks:x.lineBreaks,failed:x.failed,totals:x.totals}),x.failed||(y=x.lineBreaks)}if(!y){var k=t(p.measureWidths,g);b.attempts.push({type:"Free Form",lineBreaks:k.lineBreaks,totals:k.totals}),(y=k.lineBreaks).length>0&&p.measureWidths.length<25&&(k=a(p,g,0,b),b.attempts.push({type:"Optimize",failed:k.failed,reason:k.reason,lineBreaks:k.lineBreaks,totals:k.totals}),k.failed||(y=k.lineBreaks))}u.push(y),d.push(b)}var w=function(e,t,r){var n={lineBreaks:e,staffwidth:t};for(var a in r)r.hasOwnProperty(a)&&"wrap"!==a&&"staffwidth"!==a&&(n[a]=r[a]);return{revisedParams:n}}(u,n.staffwidth,n);return w.explanation=d,w.reParse=!0,w}}},5633:function(e,t,r){var n,a=r(9447),i=r(4914),s=i.relativeMajor,o=i.transposeKey,c=i.relativeMode,l=i.isLegalMode,h=r(4208);!function(){"use strict";function e(e,r,n){var a=[],i=r.getKeySignature();if("Hp"===i.root||"HP"===i.root)return a;a=a.concat(function(e,t){for(var r=[],n=e.split("K:"),a=n[0].length,i=1;i<n.length;i++){var s=n[i],o=s.match(/^( *)([A-G])([#b]?)( ?)(\w*)/);if(o){var c=a+2+o[1].length,h=l(o[5])?o[5]:"",u=o[2]+o[3]+o[4]+h,d=p({root:o[2],acc:o[3],mode:h},t),f=d.root+d.acc+o[4]+d.mode;r.push({start:c,end:c+u.length,note:f})}a+=s.length+2}return r}(e,n));for(var s=0;s<r.lines.length;s++){var o=r.lines[s].staff;if(o)for(var c=0;c<o.length;c++){var h=o[c];"perc"!==h.clef.type&&(a=a.concat(t(e,h.voices,h.key,n)))}}return a}function t(e,t,n,a){for(var i=[],s=p(n,a),o=0;o<t.length;o++)i=i.concat(u(e,t[o],n.root,r(n),s,a));return i}function r(e){for(var t={},r=0;r<e.accidentals.length;r++){var n=e.accidentals[r];"flat"===n.acc?t[n.note.toUpperCase()]="_":"sharp"===n.acc&&(t[n.note.toUpperCase()]="^")}return t}function i(e,t,r){var n=d.indexOf(e.root)-d.indexOf(t);return"none"===t&&(n=d.indexOf(e.root)),0===n?r>2?n+=7:-12===r&&(n-=7):r>0&&n<0?n+=7:r<0&&n>0&&(n-=7),r>12?n+=7:r<-12&&(n-=7),n}function u(e,t,n,a,s,o){for(var c=[],l=i(s,n,o),u={},d={},f=0;f<t.length;f++){var g=t[f];if(g.chord)for(var v=0;v<g.chord.length;v++){var w=g.chord[v];if("default"===w.position){var C=s.accidentals.length&&"flat"===s.accidentals[0].acc,T=h(w.name,o,C,!0);(T=T.replace(/♭/g,"b").replace(/♯/g,"#"))!==w.name&&c.push(k(e,g.startChar,g.endChar,T))}}if("note"===g.el_type&&g.pitches){for(var S=y(e,g.startChar,g.endChar),_=0;_<S.length;_++){var E=b(S[_].note,n,a,u);E.acc&&(u[E.name.toUpperCase()]=E.acc);var M=m(E,s,l,d);M.acc&&(d[M.upper]=M.acc),c.push({note:M.acc+M.name,start:S[_].index,end:S[_].index+S[_].note.length})}if(g.gracenotes)for(var A=0;A<g.gracenotes.length;A++){var N=b(g.gracenotes[A].name,n,a,u);N.acc&&(u[N.name.toUpperCase()]=N.acc);var B=m(N,s,l,u);B.acc&&(d[B.upper]=B.acc),c.push(x(e,g.startChar,g.endChar,B.acc+B.name,A))}}else"bar"===g.el_type?(u={},d={}):"keySignature"===g.el_type&&(n=g.root,a=r(g),l=i(s=p(g,o),n,o))}return c}n=function(t,r,n){if("TEST"===r)return{keyAccidentals:a,relativeMajor:s,transposeKey:o,relativeMode:c,transposeChordName:h};n=parseInt(n,10);var i,l=[];for(i=0;i<r.length;i++)l=l.concat(e(t,r[i],n));l=l.sort(function(e,t){return t.start-e.start});var u=t.split("");for(i=0;i<l.length;i++){var d=l[i];u.splice(d.start,d.end-d.start,d.note)}return u.join("")};var d="CDEFGAB",f=[",,,,",",,,",",,",",","","'","''","'''","''''"];function p(e,t){if("none"===e.root)return{root:o("C",t),mode:"",acc:"",accidentals:[]};var r=s(e.root+e.acc+e.mode),n=o(r,t),i=c(n,e.mode),l=a(n);return{root:i[0],mode:e.mode,acc:i.length>1?i[1]:"",accidentals:l}}function m(e,t,r,n){for(var a=e.pitch,i=d.indexOf(e.name),s=(d.indexOf(t.root)+a)%7,o=i+r,c=e.oct;o>6;)c++,o-=7;for(;o<0;)c--,o+=7;for(var l,h=d[s],u="",f=e.adj,p="=",g=0;g<t.accidentals.length;g++)if(t.accidentals[g].note.toLowerCase()===h.toLowerCase()){f+="flat"===t.accidentals[g].acc?-1:1,p="flat"===t.accidentals[g].acc?"_":"^";break}switch(f){case-2:u="__";break;case-1:u="_";break;case 0:u="=";break;case 1:u="^";break;case 2:u="^^";break;case-3:return(l={}).pitch=e.pitch-1,l.oct=e.oct,l.name=d[d.indexOf(e.name)-1],l.name||(l.name="B",l.oct--),"B"===l.name||"E"===l.name?l.adj=e.adj+1:l.adj=e.adj+2,m(l,t,r+1,n);case 3:return(l={}).pitch=e.pitch+1,l.oct=e.oct,l.name=d[d.indexOf(e.name)+1],l.name||(l.name="C",l.oct++),"C"===l.name||"F"===l.name?l.adj=e.adj-1:l.adj=e.adj-2,m(l,t,r+1,n)}switch(n[h]!==u&&(n[h]||u!==p)||e.courtesy||(u=""),c){case 0:h+=",,,";break;case 1:h+=",,";break;case 2:h+=",";break;case 4:h=h.toLowerCase();break;case 5:h=h.toLowerCase()+"'";break;case 6:h=h.toLowerCase()+"''";break;case 7:h=h.toLowerCase()+"'''";break;case 8:h=h.toLowerCase()+"''''"}return c>4&&(h=h.toLowerCase()),{acc:u,name:h,upper:h.toUpperCase()}}var g=/([_^=]*)([A-Ga-g])([,']*)/,v=/([_^=]*[A-Ga-g][,']*)?(\d*\/*\d*)?([\>\<\-\)]*)?/;function b(e,t,r,n){var a="none"===t?0:d.indexOf(t),i=e.match(g),s=i[2].toUpperCase(),o=d.indexOf(s)-a;o<0&&(o+=7);var c=f.indexOf(i[3]);s===i[2]&&c--;var l=n[s]||r[s]||"=";return{acc:i[1],name:s,pitch:o,oct:c,adj:w(i[1],r[s],n[s]),courtesy:i[1]===l}}function y(e,t,r){for(var n,a=e.substring(t,r),i=[],s=/("[^"]+")+/g;null!==(n=s.exec(a));)i.push({start:s.lastIndex-n[0].length,end:s.lastIndex});for(var o=/(![^!]+!)+/g;null!==(n=o.exec(a));)i.push({start:o.lastIndex-n[0].length,end:o.lastIndex});for(var c=[],l=/([_^=]*)([A-Ga-g])([,']*)/g;null!==(n=l.exec(a));){for(var h=!1,u=0;u<i.length;u++)l.lastIndex>=i[u].start&&l.lastIndex<=i[u].end&&(h=!0);h||c.push({note:n[0],index:t+l.lastIndex-n[0].length})}return c}function x(e,t,r,n,a){var i=/(\/*)/,s=e.substring(t,r).match(new RegExp(/([^\{]*)/.source+/\{/.source+i.source+v.source+i.source+v.source+i.source+v.source+i.source+v.source+i.source+v.source+i.source+v.source+i.source+v.source+i.source+v.source+/\}/.source));if(s){for(var o=1+s[1].length,c=0;c<a;c++)s[3*c+2]&&(o+=s[3*c+2].length),s[3*c+3]&&(o+=s[3*c+3].length),s[3*c+4]&&(o+=s[3*c+4].length),s[3*c+5]&&(o+=s[3*c+5].length);s[3*a+2]&&(o+=s[3*c+2].length),t+=o;var l=s[3*a+3]?s[3*a+3].length:0;l+=s[3*a+4]?s[3*a+4].length:0,r=t+(l+=s[3*a+5]?s[3*a+5].length:0)}return{start:t,end:r,note:n}}function k(e,t,r,n){var a=e.substring(t,r).match(/([^"]+)?(".+")+/);return a[1]&&(t+=a[1].length),{start:t+1,end:(r=t+a[2].length)-1,note:n}}function w(e,t,r){if(!e&&r&&(e=r),!e)return 0;switch(t){case void 0:switch(e){case"__":return-2;case"_":return-1;case"=":default:return 0;case"^":return 1;case"^^":return 2}case"_":switch(e){case"__":return-1;case"_":default:return 0;case"=":return 1;case"^":return 2;case"^^":return 3}case"^":switch(e){case"__":return-3;case"_":return-2;case"=":return-1;case"^":default:return 0;case"^^":return 1}}return 0}}(),e.exports=n},9716:function(e,t,r){var n,a=r(7207),i=r(5058);!function(){"use strict";var e,t,r,s,o,c,l,h,u,d,f,p,m,g,v,b,y,x,k=1,w={num:4,den:4},C=128,T=!0,S=105,_=95,E=85,M=[[S,_,E]],A=.25,N=0,B={},P=0;function L(e){for(var t=u.length-1;t>=0;t--)if("program"===u[t].cmd)return void(u[t].channel=e)}function O(e){return e/1e6}function j(e){return Math.round(e*k*1e6)/1e6}function H(e){switch(parseInt(e.den,10)){case 2:return.5;case 4:return.25;case 8:return e.num%3==0?.375:.125;case 16:return.125}return.25}function D(e,t,r){if(t)return 0;var n,a=S,i=_,s=E;if(void 0!==r&&M.length>=r+1&&(a=M[r][0],i=M[r][1],s=M[r][2]),void 0!==g)n=g,g=void 0;else if(T)if(P>e)n=s;else{var o=(e-m)/H(w);n=0===o?a:parseInt(o,10)===o?i:s}else n=i;return v&&(n+=v,v=void 0),n<0&&(n=0),n>127&&(n=127),t?0:n}function z(e,t){var r=t.start,n=t.duration,a=j(1/32);switch(e){case"trill":for(var i=2;n>0;)u.push({cmd:"note",pitch:t.pitch+i,volume:t.volume,start:r,duration:a,gap:0,instrument:h,style:"decoration"}),i=2===i?0:2,n-=a,r+=a;break;case"trillh":for(i=1;n>0;)u.push({cmd:"note",pitch:t.pitch+i,volume:t.volume,start:r,duration:a,gap:0,instrument:h,style:"decoration"}),i=1===i?0:1,n-=a,r+=a;break;case"pralltriller":u.push({cmd:"note",pitch:t.pitch,volume:t.volume,start:r,duration:a,gap:0,instrument:h,style:"decoration"}),n-=a,r+=a,u.push({cmd:"note",pitch:t.pitch+2,volume:t.volume,start:r,duration:a,gap:0,instrument:h,style:"decoration"}),n-=a,r+=a,u.push({cmd:"note",pitch:t.pitch,volume:t.volume,start:r,duration:n,gap:0,instrument:h});break;case"mordent":case"lowermordent":u.push({cmd:"note",pitch:t.pitch,volume:t.volume,start:r,duration:a,gap:0,instrument:h,style:"decoration"}),n-=a,r+=a,u.push({cmd:"note",pitch:t.pitch-2,volume:t.volume,start:r,duration:a,gap:0,instrument:h,style:"decoration"}),n-=a,r+=a,u.push({cmd:"note",pitch:t.pitch,volume:t.volume,start:r,duration:n,gap:0,instrument:h});break;case"turn":a=t.duration/4,u.push({cmd:"note",pitch:t.pitch+2,volume:t.volume,start:r,duration:a,gap:0,instrument:h,style:"decoration"}),u.push({cmd:"note",pitch:t.pitch,volume:t.volume,start:r+a,duration:a,gap:0,instrument:h,style:"decoration"}),u.push({cmd:"note",pitch:t.pitch-1,volume:t.volume,start:r+2*a,duration:a,gap:0,instrument:h,style:"decoration"}),u.push({cmd:"note",pitch:t.pitch,volume:t.volume,start:r+3*a,duration:a,gap:0,instrument:h,style:"decoration"});break;case"roll":for(;n>0;)u.push({cmd:"note",pitch:t.pitch,volume:t.volume,start:r,duration:a,gap:0,instrument:h,style:"decoration"}),n-=2*a,r+=2*a}}function I(e,t){var r,n=D(O(e.time),t);if(p.processChord(e),e.gracenotes&&e.pitches&&e.pitches.length>0&&e.pitches[0]&&(r=function(e,t){for(var r,n=0,a=[],s=0;s<e.length;s++)n+=(r=e[s]).duration;var o=t/2/n;for(s=0;s<e.length;s++){var c=V(r=e[s]);if(h===C&&x){var l=i(r);l&&x[l]&&(c=x[l].sound)}var u={pitch:c,duration:r.duration*o};u=Y(u),a.push(u)}return a}(e.gracenotes,e.pitches[0].duration),e.elem&&(e.elem.midiGraceNotePitches=function(e,t,r,n){var a=[];r=Math.round(r);for(var i=0;i<e.length;i++){var s=e[i];u.push({cmd:"note",pitch:s.pitch,volume:r,start:t,duration:s.duration,gap:0,instrument:n,style:"grace"}),a.push({pitch:s.pitch,durationInMeasures:s.duration,volume:r,instrument:n}),t+=s.duration}return a}(r,O(e.time),2*n/3,h))),e.elem){var a=O(e.time),s=a/A/o*60*1e3;if(void 0===e.elem.currentTrackMilliseconds)e.elem.currentTrackMilliseconds=s,e.elem.currentTrackWholeNotes=a;else if(void 0===e.elem.currentTrackMilliseconds.length)e.elem.currentTrackMilliseconds!==s&&(e.elem.currentTrackMilliseconds=[e.elem.currentTrackMilliseconds,s],e.elem.currentTrackWholeNotes=[e.elem.currentTrackWholeNotes,a]);else{for(var c=!1,l=0;l<e.elem.currentTrackMilliseconds.length;l++)e.elem.currentTrackMilliseconds[l]===s&&(c=!0);c||(e.elem.currentTrackMilliseconds.push(s),e.elem.currentTrackWholeNotes.push(a))}}if(e.pitches){var d="",m=function(e,t){var r={};if(e.decoration)for(var n=0;n<e.decoration.length;n++)"staccato"===e.decoration[n]?r.thisBreakBetweenNotes="staccato":"tenuto"===e.decoration[n]?r.thisBreakBetweenNotes="tenuto":"accent"===e.decoration[n]?r.velocity=Math.min(127,1.5*t):"trill"===e.decoration[n]?r.noteModification="trill":"lowermordent"===e.decoration[n]?r.noteModification="lowermordent":"uppermordent"===e.decoration[n]?r.noteModification="pralltriller":"mordent"===e.decoration[n]?r.noteModification="mordent":"turn"===e.decoration[n]?r.noteModification="turn":"roll"===e.decoration[n]?r.noteModification="roll":"pralltriller"===e.decoration[n]?r.noteModification="pralltriller":"trillh"===e.decoration[n]&&(r.noteModification="trillh");return r}(e,n);m.thisBreakBetweenNotes&&(d=m.thisBreakBetweenNotes),m.velocity&&(n=m.velocity);var g=e.pitches;"rhythm"===e.style&&(g=p.setRhythmHead(!0,e)),e.elem&&(e.elem.midiPitches=[]);for(var v=0;v<g.length;v++){var b=n;!m.velocity&&Array.isArray(e.decoration)&&e.decoration.length>v&&(b=D(O(e.time),t,v));var y=g[v];if(y){y.startSlur&&(N+=y.startSlur.length),y.endSlur&&(N-=y.endSlur.length);var k=y.actualPitch?y.actualPitch:V(y);if(h===C&&x){var w=i(y);w&&x[w]&&(k=x[w].sound)}var T={cmd:"note",pitch:k,volume:b,start:O(e.time),duration:j(y.duration),instrument:h,startChar:e.elem.startChar,endChar:e.elem.endChar};if(T=Y(T),e.gracenotes&&(T.duration=T.duration/2,T.start=T.start+T.duration),e.elem&&e.elem.midiPitches.push(T),m.noteModification)z(m.noteModification,T);else{switch(N>0?T.endType="tenuto":d&&(T.endType=d),T.endType){case"tenuto":T.gap=-.001;break;case"staccato":var S=.4*T.duration;T.gap=o/60*S;break;default:T.gap=0}u.push(T)}}}u.length}var _=function(e){return e.pitches&&e.pitches.length>0&&e.pitches[0]?e.pitches[0].duration:e.elem?e.elem.duration:e.duration}(e);f=Math.max(f,O(e.time)+j(_))}n=function(n,i,C,j){i||(i={}),j||(j={}),e=[],t=[0,0,0,0,0,0,0],s=[],o=i.qpm,c=void 0,k=1,l=void 0,h=void 0,u=void 0,d=void 0,f=0,x=C,w={num:4,den:4},T=!0,S=105,_=95,E=85,M=[],A=.25,g=void 0,v=void 0,N=0,b=[],B={},y=1,n.length>0&&n[0].length>0&&(P=n[0][0].pickupLength),void 0===i.bassprog||j.bassprog||(j.bassprog=[i.bassprog]),void 0===i.bassvol||j.bassvol||(j.bassvol=[i.bassvol]),void 0===i.chordprog||j.chordprog||(j.chordprog=[i.chordprog]),void 0===i.chordvol||j.chordvol||(j.chordvol=[i.chordvol]),void 0===i.gchord||j.gchord||(j.gchord=[i.gchord]),p=new a(n.length,i.chordsOff,j,w),function(e,t){for(var r=0;r<e.length;r++){for(var n=e[r],a={},i=t.qpm,s=0,o=1,c=0;c<n.length;c++){var l=n[c];if("tempo"!==l.el_type){l.time=s;var h=l.duration?l.duration:0;if(s+=Math.round(h*o*1e6),l.pitches){for(var u=0;u<l.pitches.length;u++){var d=l.pitches[u];if(d)if(d.duration=l.duration,d.startTie)void 0===a[d.pitch]?a[d.pitch]={el:c,pitch:u}:(n[a[d.pitch].el].pitches[a[d.pitch].pitch].duration+=d.duration,l.pitches[u]=null);else if(d.endTie){var f=a[d.pitch];if(f){var p=d.duration;delete n[f.el].pitches[f.pitch].startTie,n[f.el].pitches[f.pitch].duration+=p,l.pitches[u]=null,delete a[d.pitch]}else delete d.endTie}}delete l.duration}}else i?o=l.qpm?i/l.qpm:1:i=l.qpm}for(var m in a)if(a.hasOwnProperty(m)){var g=a[m];delete n[g.el].pitches[g.pitch].startTie}}}(n,i);for(var D=0;D<n.length;D++){r=0,p.setTranspose(r);var z=n[D];u=[{cmd:"program",channel:D,instrument:l}],d=void 0,m=0,p.setLastBarTime(0);var F=!1;(!0===i.voicesOff||i.voicesOff&&i.voicesOff.length&&i.voicesOff.indexOf(D)>=0)&&(F=!0);for(var V=0;V<z.length;V++){var Y=z[V];switch(Y.el_type){case"name":d={cmd:"text",type:"name",text:Y.trackName};break;case"note":I(Y,F);break;case"key":t=G(Y);break;case"meter":c||(c=Y),w=Y,p.setMeter(w),A=H(w),W();break;case"tempo":o?k=Y.qpm?o/Y.qpm:1:o=Y.qpm,p.setTempoChangeFactor(k);break;case"transpose":r=Y.transpose,p.setTranspose(r);break;case"bar":p.barEnd(Y),e=[],0===D&&X(n.length+1),p.setRhythmHead(!1),m=O(Y.time),p.setLastBarTime(m);break;case"bagpipes":break;case"instrument":if(void 0===l&&(l=Y.program),h=Y.program,u.length>0&&"program"===u[u.length-1].cmd)u[u.length-1].instrument=Y.program;else{var q;for(q=u.length-1;q>=0&&"program"!==u[q].cmd;q--);(q<0||u[q].instrument!==Y.program)&&u.push({cmd:"program",channel:0,instrument:Y.program})}break;case"channel":L(Y.channel);break;case"drum":B=R(Y.params),W();break;case"gchordOn":p.gChordOn(Y);break;case"beat":S=Y.beats[0],_=Y.beats[1],E=Y.beats[2],M=Y.volumesPerNotePitch?Y.volumesPerNotePitch:[];break;case"vol":g=Y.volume;break;case"volinc":v=Y.volume;break;case"beataccents":T=Y.value;break;case"gchord":case"bassprog":case"chordprog":case"bassvol":case"chordvol":case"gchordbars":p.paramChange(Y);break;default:console.log("MIDI creation. Unknown el_type: "+Y.el_type+"\n")}}void 0===u[0].instrument&&(u[0].instrument=l||0),d&&u.unshift(d),s.push(u),p.finish(),b.length}return i.detuneOctave&&function(e,t){for(var r={},n=0;n<e.length;n++)for(var a=0;a<e[n].length;a++){var i=e[n][a];"note"===i.cmd&&(void 0===r[i.start]&&(r[i.start]=[]),r[i.start].push({track:n,event:a,pitch:i.pitch}))}var s=Object.keys(r);for(n=0;n<s.length;n++){var o=r[s[n]];if(o.length>1){var c=(o=o.sort(function(e,t){return e.pitch-t.pitch}))[o.length-1],l=c.pitch%12,h=!1;for(a=0;!h&&a<o.length-1;a++)o[a].pitch%12===l&&(h=!0);if(h){var u=e[c.track][c.event];u.cents||(u.cents=0),u.cents+=t}}}}(s,parseInt(i.detuneOctave,10)),p.addTrack(s),b.length>0&&s.push(b),{tempo:o,instrument:l,tracks:s,totalDuration:f}};var F=[0,2,4,5,7,9,11];function V(n){if(void 0!==n.midipitch)return n.midipitch;var a=n.pitch;if(n.accidental)switch(n.accidental){case"sharp":e[a]=1;break;case"flat":e[a]=-1;break;case"natural":e[a]=0;break;case"dblsharp":e[a]=2;break;case"dblflat":e[a]=-2;break;case"quartersharp":e[a]=.25;break;case"quarterflat":e[a]=-.25}var i=12*function(e){return Math.floor(e/7)}(a)+F[q(a)]+60;return void 0!==e[a]?i+=e[a]:i+=t[q(a)],i+r}function G(e){var t=[0,0,0,0,0,0,0];if(!e.accidentals)return t;for(var r=0;r<e.accidentals.length;r++){var n,a=e.accidentals[r];switch(a.acc){case"flat":n=-1;break;case"quarterflat":n=-.25;break;case"sharp":n=1;break;case"quartersharp":n=.25;break;default:n=0}t[q(a.note.toLowerCase().charCodeAt(0)-"c".charCodeAt(0))]+=n}return t}function Y(e){var t=""+e.pitch;return t.indexOf(".75")>=0?(e.pitch=Math.round(e.pitch),e.cents=-50):t.indexOf(".25")>=0&&(e.pitch=Math.round(e.pitch),e.cents=50),e}function q(e){return(e%=7)<0&&(e+=7),e}function R(e){if(0===e.pattern.length||!1===e.on)return{on:!1};for(var t=e.pattern[0],r=[],n="",a=0,i=0;i<t.length;i++)if("d"===t[i]&&a++,"d"===t[i]||"z"===t[i])0!==n.length?(r.push(n),n=t[i]):n+=t[i];else{if(0===n.length)return{on:!1};n+=t[i]}if(0!==n.length&&r.push(n),e.pattern.length!==2*a+1)return{on:!1};for(var s={on:!0,bars:e.bars,pattern:[]},o=H(w),c=0,l=0;l<r.length;l++){n=r[l];for(var h=1,u=!1,d=0,f=1;f<n.length;f++)switch(n[f]){case"/":0!==d&&(h*=d),d=0,u=!0;break;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":d=10*d+n[f];break;default:return{on:!1}}u?(0===d&&(d=2),h/=d):d&&(h*=d),"d"===n[0]?(s.pattern.push({len:h*o,pitch:e.pattern[1+c],velocity:e.pattern[1+c+a]}),c++):s.pattern.push({len:h*o,pitch:null})}return y=e.bars?e.bars:1,s}function W(){if(B&&B.pattern){for(var e=B,t=0,r=w.num/w.den,n=0;n<e.pattern.length;n++)t+=e.pattern[n].len;var a=t/y/r;for(n=0;n<e.pattern.length;n++)e.pattern[n].len=e.pattern[n].len/a;B=e}}function X(e){if(0!==b.length||B.on){var t=w.num/w.den;if(0===b.length){if(f<t)return;b.push({cmd:"program",channel:e,instrument:C})}if(B.on)for(var r=m,n=0;n<B.pattern.length;n++){var a=j(B.pattern[n].len);B.pattern[n].pitch&&b.push({cmd:"note",pitch:B.pattern[n].pitch,volume:B.pattern[n].velocity,start:r,duration:a,gap:0,instrument:C}),r+=a}}}}(),e.exports=n},9991:function(e,t,r){var n,a=r(2710);!function(){"use strict";function e(e,t){for(var r in t)t.hasOwnProperty(r)&&e.setAttribute(r,t[r]);return e}function t(){this.trackstrings="",this.trackcount=0,this.noteOnAndChannel="%90",this.noteOffAndChannel="%80"}function r(e,t){for(var r="",n=0;n<e.length;n++)r+=i(e.charCodeAt(n),2);return"%00%FF"+t+i(r.length/3,2)+r}function i(e,t){var r=e.toString(16);for(r=r.split(".")[0];r.length<t;)r="0"+r;return r.length>t&&(r=r.substring(0,t)),function(e){for(var t="",r=0;r<e.length;r+=2)t+="%",t+=e.substr(r,2);return t}(r)}function s(e){var t=(e=Math.round(e))%128;return i(2*(e-t)+t,4)}function o(e){var t=0,r=[];for(e=Math.round(e);0!==e;)r.push(127&e),e>>=7;for(var n=r.length-1;n>=0;n--){t<<=8;var a=r[n];0!==n&&(a|=128),t|=a}var s=t.toString(16).length;return i(t,s+=s%2)}t.prototype.setTempo=function(e){0===this.trackcount&&(this.startTrack(),this.track+="%00%FF%51%03"+i(Math.round(6e7/e),6),this.endTrack())},t.prototype.setGlobalInfo=function(e,t,n,a){if(0===this.trackcount){this.startTrack();var s=Math.round(6e7/e);this.track+="%00%FF%51%03"+i(s,6),n&&(this.track+=function(e){if(!e||!e.accidentals)return"";for(var t=0,r=256,n=0;n<e.accidentals.length;n++)"sharp"===e.accidentals[n].acc?t++:"flat"===e.accidentals[n].acc&&r--;return"%00%FF%59%02"+i(256!==r?r:t,2)+("m"===e.mode?"%01":"%00")}(n)),a&&(this.track+=function(e){var t,r="%00%FF%58%04"+i(e.num,2),n={1:0,2:1,4:2,8:3,16:4,32:5}[e.den];if(!n)return"";switch(r+=i(n,2),e.num+"/"+e.den){case"2/4":case"3/4":case"4/4":case"5/4":t=24;break;case"6/4":t=72;break;case"2/2":case"3/2":case"4/2":t=48;break;case"3/8":case"6/8":case"9/8":case"12/8":t=36}return t?(r+=i(t,2))+"%08":""}(a)),t&&(this.track+=r(t,"%01")),this.endTrack()}},t.prototype.startTrack=function(){this.noteWarped={},this.track="",this.trackName="",this.trackInstrument="",this.silencelength=0,this.trackcount++,this.instrument&&this.setInstrument(this.instrument)},t.prototype.endTrack=function(){this.track=this.trackName+this.trackInstrument+this.track;var e=i(this.track.length/3+4,8);this.track="MTrk"+e+this.track+"%00%FF%2F%00",this.trackstrings+=this.track},t.prototype.setText=function(e,t){"name"===e&&(this.trackName=r(t,"%03"))},t.prototype.setInstrument=function(e){this.trackInstrument="%00%C0"+i(e,2),this.instrument=e},t.prototype.setChannel=function(e,t){this.channel=e;var r="%00%B"+this.channel.toString(16);this.track+=r+"%79%00",this.track+=r+"%40%00",this.track+=r+"%5B%30",t||(t=0),t=Math.round(64*(t+1)),this.track+=r+"%0A"+i(t,2),this.track+=r+"%07%64",this.noteOnAndChannel="%9"+this.channel.toString(16),this.noteOffAndChannel="%8"+this.channel.toString(16)},t.prototype.startNote=function(e,t,r){if(this.track+=o(this.silencelength),this.silencelength=0,r){this.track+="%e"+this.channel.toString(16);var n=Math.round(4096*a(r));this.track+=s(8192+n),this.track+=o(0),this.noteWarped[e]=!0}this.track+=this.noteOnAndChannel,this.track+="%"+e.toString(16)+i(t,2)},t.prototype.endNote=function(e){this.track+=o(this.silencelength),this.silencelength=0,this.noteWarped[e]&&(this.track+="%e"+this.channel.toString(16),this.track+=s(8192),this.track+=o(0),this.noteWarped[e]=!1),this.track+=this.noteOffAndChannel,this.track+="%"+e.toString(16)+"%00"},t.prototype.addRest=function(e){this.silencelength+=e,this.silencelength<0&&(this.silencelength=0)},t.prototype.getData=function(){return"data:audio/midi,MThd%00%00%00%06%00%01"+i(this.trackcount,4)+"%01%e0"+this.trackstrings},t.prototype.embed=function(t,r){var n=this.getData(),a=e(document.createElement("a"),{href:n});if(a.innerHTML="download midi",t.insertBefore(a,t.firstChild),!r){var i=e(document.createElement("embed"),{src:n,type:"video/quicktime",controller:"true",autoplay:"false",loop:"false",enablejavascript:"true",style:"display:block; height: 20px;"});t.insertBefore(i,t.firstChild)}},n=function(){return new t}}(),e.exports=n},1028:function(e,t,r){var n,a=r(5008),i=r(7021);!function(){"use strict";var e=1,t=128;function r(e,t,r){for(var n=0,a=t+1;a<e.length;a++)if("note"===e[a].el_type&&n++,e[a].decoration&&e[a].decoration.indexOf(r)>=0)return n;return n}function s(e,t,r){for(var n=Math.min(e.length,t+3),a=t;a<n;a++)if("note"===e[a].el_type&&e[a].decoration)for(var i=0;i<e[a].decoration.length;i++)if(r.indexOf(e[a].decoration[i])>=0)return e[a].decoration[i];return null}function o(e){for(var t=0;t<e.length;t++)for(var r=e[t],n=r.length-1;n>=0&&"bar"!==r[n].el_type;)r[n].noChordVoice=!0,n--}function c(e,t){if(e&&!(e.length<=t)&&e[t].title)return e[t].title.join(" ")}function l(e,t){var r=1/4;e.duration&&(r=e.duration[0]);var n=60;return e.bpm&&(n=e.bpm),r*n/t}function h(t){var r;switch(t.type){case"common_time":r={el_type:"meter",num:4,den:4},e=1;break;case"cut_time":r={el_type:"meter",num:2,den:2},e=1;break;case"specified":var n=0;if(t.value&&t.value.length>0&&t.value[0].num.indexOf("+")>0)for(var a=t.value[0].num.split("+"),i=0;i<a.length;i++)n+=parseInt(a[i],10);else n=parseInt(t.value[0].num,10);r={el_type:"meter",num:n,den:t.value[0].den},e=n/parseInt(t.value[0].den,10);break;default:r={el_type:"meter"},e=1}return r}function u(e){for(var t=[],r=0;r<e.length;r++)"natural"!==e[r].acc&&t.push(e[r]);return t}function d(e,t){p(e,"HP"===t.root?{el_type:"key",accidentals:[{acc:"natural",note:"g"},{acc:"sharp",note:"f"},{acc:"sharp",note:"c"}]}:{el_type:"key",accidentals:u(t.accidentals)})}function f(e,t){p(e,h(t))}function p(e,t){for(var r=e.length-1;r>=0;r--)if(e[r].el_type===t.el_type)return void(JSON.stringify(e[r])!==JSON.stringify(t)&&e.push(t));e.push(t)}n=function(n,u){var m,g=(u=u||{}).program||0,v=u.midiTranspose||0;n.visualTranspose&&(v-=n.visualTranspose);var b=u.channel||0,y=!1,x=u.drum||"",k=u.drumBars||1,w=u.drumIntro||0,C=""!==x,T=!!u.drumOff,S=[];g=parseInt(g,10),v=parseInt(v,10),10===(b=parseInt(b,10))&&(g=t),x=x.split(" "),k=parseInt(k,10),w=parseInt(w,10);var _=n.formatting.bagpipes;_&&(g=71);var E=[];if(n.formatting.midi){var M=n.formatting.midi;M.program&&M.program.length>0&&(g=M.program[0],M.program.length>1&&(g=M.program[1],b=M.program[0]),y=!0),M.transpose&&(v=M.transpose[0]),M.channel&&(b=M.channel[0],y=!0),M.drum&&(x=M.drum),M.drumbars&&(k=M.drumbars[0]),M.drumon&&(C=!0),10===b&&(g=t),M.beat&&E.push({el_type:"beat",beats:M.beat}),M.nobeataccents&&E.push({el_type:"beataccents",value:!1})}m=u.qpm?parseInt(u.qpm,10):n.metaText.tempo?l(n.metaText.tempo,n.getBeatLength()):u.defaultQpm?u.defaultQpm:180;var A=[];_&&A.push({el_type:"bagpipes"}),A.push({el_type:"instrument",program:g}),b&&A.push({el_type:"channel",channel:b}),v&&A.push({el_type:"transpose",transpose:v}),A.push({el_type:"tempo",qpm:m});for(var N=0;N<E.length;N++)A.push(E[N]);var B,P=[],L=[],O=[],j=[],H=[0],D={};D[0]={el_type:"tempo",qpm:m,timing:0};for(var z=[],I=!1,F=n.lines,V=0;V<F.length;V++){var G=F[V];if(G.staff)for(var Y=function(e){var t,n={pppp:[15,10,5,1],ppp:[30,20,10,1],pp:[45,35,20,1],p:[60,50,35,1],mp:[75,65,50,1],mf:[90,80,65,1],f:[105,95,80,1],ff:[120,110,95,1],fff:[127,125,110,1],ffff:[127,125,110,1]};if(e.decoration){if(e.decoration.indexOf("pppp")>=0?t="pppp":e.decoration.indexOf("ppp")>=0?t="ppp":e.decoration.indexOf("pp")>=0?t="pp":e.decoration.indexOf("p")>=0?t="p":e.decoration.indexOf("mp")>=0?t="mp":e.decoration.indexOf("mf")>=0?t="mf":e.decoration.indexOf("f")>=0?t="f":e.decoration.indexOf("ff")>=0?t="ff":e.decoration.indexOf("fff")>=0?t="fff":e.decoration.indexOf("ffff")>=0&&(t="ffff"),t){var a=[B=n[t].slice(0)];Array.isArray(e.decoration)&&(a=[],e.decoration.forEach(function(e){e in n&&a.push(n[e].slice(0))})),P[R].push({el_type:"beat",beats:B.slice(0),volumesPerNotePitch:a}),O[U]=!1,j[U]=!1}if(e.decoration.indexOf("crescendo(")>=0){var i=r(K,re,"crescendo)"),o=Math.min(127,B[0]+50),c=s(K,re+i+1,Object.keys(n));c&&(o=n[c][0]),O[U]=i>0&&Math.floor((o-B[0])/i),j[U]=!1}else if(e.decoration.indexOf("crescendo)")>=0)O[U]=!1;else if(e.decoration.indexOf("diminuendo(")>=0){var l=r(K,re,"diminuendo)"),h=Math.max(15,B[0]-50),u=s(K,re+l+1,Object.keys(n));u&&(h=n[u][0]),O[U]=!1,j[U]=l>0&&Math.floor((h-B[0])/l)}else e.decoration.indexOf("diminuendo)")>=0&&(j[U]=!1)}},q=G.staff,R=0,W=0;W<q.length;W++){var X=q[W];if(!X.clef||"TAB"!==X.clef.type)for(var U=0;U<X.voices.length;U++){var K=X.voices[U];if(!P[R]){P[R]=[].concat(JSON.parse(JSON.stringify(A)));var $=c(G.staff,R);$&&P[R].unshift({el_type:"name",trackName:$}),z[R]=new i(P[R])}if(v&&"perc"===X.clef.type&&P[R].push({el_type:"transpose",transpose:0}),X.clef&&"perc"===X.clef.type&&!y)for(var Q=0;Q<P[R].length;Q++)"instrument"===P[R][Q].el_type&&(P[R][Q].program=t);else X.key&&d(P[R],X.key);X.meter&&f(P[R],X.meter),!I&&C&&(P[R].push({el_type:"drum",params:{pattern:x,bars:k,on:C,intro:w}}),I=!0),X.clef&&"perc"!==X.clef.type&&X.clef.transpose&&(X.clef.el_type="clef",P[R].push({el_type:"transpose",transpose:X.clef.transpose}),L[R]=!1),X.clef&&X.clef.type&&(X.clef.type.indexOf("-8")>=0?(P[R].push({el_type:"transpose",transpose:-12}),L[R]=!0):X.clef.type.indexOf("+8")>=0?(P[R].push({el_type:"transpose",transpose:12}),L[R]=!0):L[R]&&(P[R].push({el_type:"transpose",transpose:0}),L[R]=!1)),n.formatting.midi&&n.formatting.midi.drumoff&&(P[R].push({el_type:"bar"}),P[R].push({el_type:"drum",params:{pattern:"",on:!1}}));var J=0,Z=0,ee=0,te=0;B=[105,95,85,1];for(var re=0;re<K.length;re++){var ne=K[re];switch(ne.el_type){case"note":if(O[U]&&(B[0]+=O[U],B[1]+=O[U],B[2]+=O[U],P[R].push({el_type:"beat",beats:B.slice(0)})),j[U]&&(B[0]+=j[U],B[1]+=j[U],B[2]+=j[U],P[R].push({el_type:"beat",beats:B.slice(0)})),Y(ne),!ne.rest||"spacer"!==ne.rest.type){var ae={elem:ne,el_type:"note",timing:H[R]};if(ne.style?ae.style=ne.style:S[R]&&(ae.style=S[R]),ae.duration=0===ne.duration?.25:ne.duration,ne.startTriplet){if(Z=ne.tripletMultiplier,ee=ne.startTriplet*Z*ne.duration,ne.startTriplet!==ne.tripletR&&re+ne.tripletR<=K.length){for(var ie=0,se=re;se<re+ne.tripletR;se++)ie+=K[se].duration;ee=Z*ie}ae.duration=ae.duration*Z,ae.duration=Math.round(1e6*ae.duration)/1e6,te=ae.duration}else Z&&(ne.endTriplet?(Z=0,ae.duration=Math.round(1e6*(ee-te))/1e6):(ae.duration=ae.duration*Z,ae.duration=Math.round(1e6*ae.duration)/1e6,te+=ae.duration));ne.rest&&(ae.rest=ne.rest),ne.decoration&&(ae.decoration=ne.decoration.slice(0)),ne.pitches&&(ae.pitches=a.cloneArray(ne.pitches)),ne.gracenotes&&(ae.gracenotes=a.cloneArray(ne.gracenotes)),ne.chord&&(ae.chord=a.cloneArray(ne.chord)),P[R].push(ae),"rhythm"===ne.style&&o(P),J++,H[R]+=ae.duration}break;case"key":case"keySignature":d(P[R],ne);break;case"meter":f(P[R],ne);break;case"clef":ne.transpose&&P[R].push({el_type:"transpose",transpose:ne.transpose}),ne.type&&(ne.type.indexOf("-8")>=0?P[R].push({el_type:"transpose",transpose:-12}):ne.type.indexOf("+8")>=0&&P[R].push({el_type:"transpose",transpose:12}));break;case"tempo":m=l(ne,n.getBeatLength()),P[R].push({el_type:"tempo",qpm:m,timing:H[R]}),D[""+H[R]]={el_type:"tempo",qpm:m,timing:H[R]};break;case"bar":J>0&&P[R].push({el_type:"bar"}),Y(ne),J=0,z[R].addBar(ne,R);break;case"style":S[R]=ne.head;break;case"timeSignature":P[R].push(h(ne));break;case"part":case"stem":case"scale":case"break":case"font":break;case"midi":var oe=!1;switch(ne.cmd){case"drumon":C=!0,oe=!0;break;case"drumoff":C=!1,oe=!0;break;case"drum":x=ne.params,oe=!0;break;case"drumbars":k=ne.params[0],oe=!0;break;case"drummap":break;case"channel":10===ne.params[0]&&P[R].push({el_type:"instrument",program:t});break;case"program":p(P[R],{el_type:"instrument",program:ne.params[0]}),y=!0;break;case"transpose":P[R].push({el_type:"transpose",transpose:ne.params[0]});break;case"gchordoff":P[R].push({el_type:"gchordOn",tacet:!0});break;case"gchordon":P[R].push({el_type:"gchordOn",tacet:!1});break;case"beat":P[R].push({el_type:"beat",beats:ne.params});break;case"nobeataccents":P[R].push({el_type:"beataccents",value:!1});break;case"beataccents":P[R].push({el_type:"beataccents",value:!0});break;case"vol":case"volinc":P[R].push({el_type:ne.cmd,volume:ne.params[0]});break;case"swing":case"gchord":case"bassvol":case"chordvol":case"gchordbars":P[R].push({el_type:ne.cmd,param:ne.params[0]});break;case"bassprog":case"chordprog":P[R].push({el_type:ne.cmd,value:ne.params[0],octaveShift:ne.params[1]});break;default:console.log("MIDI seq: midi cmd not handled: ",ne.cmd,ne)}oe&&(P[0].push({el_type:"drum",params:{pattern:x,bars:k,intro:w,on:C}}),I=!0);break;default:console.log("MIDI: element type "+ne.el_type+" not handled.")}}H[++R]||(H[R]=0)}}}for(var ce=0;ce<z.length;ce++)P[ce]=z[ce].resolveRepeats();if(function(e,t){if(t&&0!==t.length)for(var r=Object.keys(t),n=0;n<e.length;n++)for(var a=e[n],i=t[0]?t[0].qpm:0,s=0;s<a.length;s++){var o=a[s];"tempo"===o.el_type&&(i=o.qpm),r.indexOf(""+o.timing)>=0&&i!==t[""+o.timing].qpm&&(i=t[""+o.timing].qpm,"tempo"===o.el_type?(o.qpm=t[""+o.timing].qpm,s++):(e[n].splice(s,0,{el_type:"tempo",qpm:t[""+o.timing].qpm,timing:o.timing}),s+=2))}}(P,D),w)for(var le=n.getPickupLength(),he=0;he<P.length;he++){for(var ue=0;"note"!==P[he][ue].el_type&&P[he].length>ue;)ue++;if(P[he].length>ue){for(se=0;se<w;se++)0===le||se<w-1?(P[he].splice(ue,0,{el_type:"note",rest:{type:"rest"},duration:e},{el_type:"bar"}),ue+=2):P[he].splice(ue++,0,{el_type:"note",rest:{type:"rest"},duration:e-le});T&&(C=!1,P[he].splice(ue++,0,{el_type:"drum",params:{pattern:x,bars:k,intro:w,on:C}}),T=!1)}}return P.length>0&&P[0].length>0&&(P[0][0].pickupLength=n.getPickupLength()),P}}(),e.exports=n},8702:function(e,t,r){var n=r(5281);e.exports=function(){return window.abcjsAudioContext||n(),window.abcjsAudioContext}},2710:function(e){e.exports=function(e){return Math.pow(2,e/1200)}},7207:function(e){var t=function(e,t,r,n){this.chordTrack=[],this.chordTrackFinished=!1,this.chordChannel=e,this.currentChords=[],this.lastChord,this.chordLastBar,this.chordsOff=!!t,this.gChordTacet=this.chordsOff,this.hasRhythmHead=!1,this.transpose=0,this.lastBarTime=0,this.meter=n,this.tempoChangeFactor=1,this.bassInstrument=r.bassprog&&r.bassprog.length>=1?r.bassprog[0]:0,this.chordInstrument=r.chordprog&&r.chordprog.length>=1?r.chordprog[0]:0,this.bassOctaveShift=r.bassprog&&2===r.bassprog.length?r.bassprog[1]:0,this.chordOctaveShift=r.chordprog&&2===r.chordprog.length?r.chordprog[1]:0,this.boomVolume=r.bassvol&&1===r.bassvol.length?r.bassvol[0]:64,this.chickVolume=r.chordvol&&1===r.chordvol.length?r.chordvol[0]:48,r.gchord&&r.gchord.length>0?this.overridePattern=a(r.gchord[0]):this.overridePattern=void 0};function r(e,t,r,a){var i=[];if(!e)return i;t.indexOf("boom")>=0?i.push(r?e.boom:e.boom2):a&&i.push(e.boom);var s=e.chick.length;if(t.indexOf("chick")>=0)for(var o=0;o<s;o++)i.push(e.chick[o]);switch(t){case"DO":i.push(e.chick[0]);break;case"MI":i.push(e.chick[1]);break;case"SOL":i.push(n(e,2));break;case"TI":i.push(n(e,3));break;case"TOP":i.push(n(e,4));break;case"do":i.push(e.chick[0]+12);break;case"mi":i.push(e.chick[1]+12);break;case"sol":i.push(n(e,2)+12);break;case"ti":i.push(n(e,3)+12);break;case"top":i.push(n(e,4)+12)}return i}function n(e,t){var r=Math.floor(t/e.chick.length);return e.chick[t%e.chick.length]+12*r}function a(e){for(var t=[],r=0;r<e.length;r++)switch(e[r]){case"z":case"2":t.push("");break;case"c":t.push("chick");break;case"b":t.push("boom&chick");break;case"f":t.push("boom");break;case"G":t.push("DO");break;case"H":t.push("MI");break;case"I":t.push("SOL");break;case"J":t.push("TI");break;case"K":t.push("TOP");break;case"g":t.push("do");break;case"h":t.push("mi");break;case"i":t.push("sol");break;case"j":t.push("ti");break;case"k":t.push("top")}return t}t.prototype.setMeter=function(e){this.meter=e},t.prototype.setTempoChangeFactor=function(e){this.tempoChangeFactor=e},t.prototype.setLastBarTime=function(e){this.lastBarTime=e},t.prototype.setTranspose=function(e){this.transpose=e},t.prototype.setRhythmHead=function(e,t){this.hasRhythmHead=e;var r=[];if(e&&this.lastChord&&this.lastChord.chick)for(var n=0;n<this.lastChord.chick.length;n++){var a=Object.assign({},t.pitches[0]);a.actualPitch=this.lastChord.chick[n],r.push(a)}return r},t.prototype.barEnd=function(e){this.chordTrack.length>0&&!this.chordTrackFinished&&(this.resolveChords(this.lastBarTime,s(e.time)),this.currentChords=[]),this.chordLastBar=this.lastChord},t.prototype.gChordOn=function(e){this.chordsOff||(this.gChordTacet=e.tacet)},t.prototype.paramChange=function(e){switch(e.el_type){case"gchord":e.param&&e.param.length>0?this.overridePattern=a(e.param):this.overridePattern=void 0;break;case"bassprog":this.bassInstrument=e.value,null!=e.octaveShift&&null!=e.octaveShift?this.bassOctaveShift=e.octaveShift:this.bassOctaveShift=0;break;case"chordprog":this.chordInstrument=e.value,null!=e.octaveShift&&null!=e.octaveShift?this.chordOctaveShift=e.octaveShift:this.chordOctaveShift=0;break;case"bassvol":this.boomVolume=e.param;break;case"chordvol":this.chickVolume=e.param;break;default:console.log("unhandled midi param",e)}},t.prototype.finish=function(){this.chordTrackEmpty()||(this.chordTrackFinished=!0)},t.prototype.addTrack=function(e){this.chordTrackEmpty()||e.push(this.chordTrack)},t.prototype.findChord=function(e){if(this.gChordTacet)return"break";if(this.chordTrackFinished||!e.chord||0===e.chord.length)return null;for(var t=0;t<e.chord.length;t++){var r=e.chord[t];if("default"===r.position)return r.name;if(this.breakSynonyms.indexOf(r.name.toLowerCase())>=0)return"break"}return null},t.prototype.interpretChord=function(e){if(0!==e.length){if("break"===e)return{chick:[]};var t=e.substring(0,1);if("("===t){if(0===(e=e.substring(1,e.length-1)).length)return;t=e.substring(0,1)}var r=this.basses[t];if(r){for(var n=this.transpose;n<-8;)n+=12;for(;n>8;)n-=12;(r+=n)<33?r+=12:r>44&&(r-=12);var a,i=r,s=(r+=12*this.bassOctaveShift)-5;1===e.length&&(a=this.chordNotes(r,""));var o=e.substring(1),c=o.substring(0,1);"b"===c||"♭"===c?(i--,r--,s--,o=o.substring(1)):"#"!==c&&"♯"!==c||(i++,r++,s++,o=o.substring(1));var l=o.split("/");if((a=this.chordNotes(i,l[0])).length>=3&&(s=s+(a[2]-a[0])-7),2===l.length&&this.basses[l[1].substring(0,1)]){var h={"#":1,"♯":1,b:-1,"♭":-1}[l[1].substring(1)]||0;r=this.basses[l[1].substring(0,1)]+h+n,s=r+=12*this.bassOctaveShift}return{boom:r,boom2:s,chick:a}}}},t.prototype.chordNotes=function(e,t){t=t.replace(/♭/g,"b").replace(/♯/g,"#");var r=i[t];r||(r="ma"===t.slice(0,2).toLowerCase()||"M"===t[0]?i.M:"m"===t[0]||"-"===t[0]?i.m:i.M),e+=12,e+=12*this.chordOctaveShift;for(var n=[],a=0;a<r.length;a++)n.push(e+r[a]);return n},t.prototype.writeNote=function(e,t,r,n,a,i){void 0!==e&&this.chordTrack.push({cmd:"note",pitch:e,volume:r,start:this.lastBarTime+n*o(t,this.tempoChangeFactor),duration:o(a,this.tempoChangeFactor),gap:0,instrument:i})},t.prototype.chordTrackEmpty=function(){for(var e=!0,t=0;t<this.chordTrack.length&&e;t++)"note"===this.chordTrack[t].cmd&&(e=!1);return e},t.prototype.resolveChords=function(e,t){if(!this.hasRhythmHead){var n=this.meter.num,a=this.meter.den,i=1/a/2,s=parseInt(n,10)/parseInt(a,10)-(t-e)/this.tempoChangeFactor;Math.abs(s)<1e-5&&(s=0),0!==this.currentChords.length&&0===this.currentChords[0].beat||this.currentChords.unshift({beat:0,chord:this.chordLastBar});var o=function(e,t){var r=[];if(0===e.length)return r;for(var n=e[0].chord,a=1;a<e.length;a++){for(var i=e[a];r.length<i.beat;)r.push(n);n=i.chord}for(;r.length<t;)r.push(n);return r}(this.currentChords,8*n/a),c=this.overridePattern?this.overridePattern:this.rhythmPatterns[n+"/"+a];if(s){c=[];for(var l=(t-e)/this.tempoChangeFactor*8,h=0;h<l/2;h+=2)c.push("chick"),c.push("")}if(!c)for(c=[],h=0;h<8*n/a/2;h++)c.push("chick"),c.push("");var u=!0,d=Math.min(c.length,o.length);for(h=0;h<d;h++){h>0&&o[h-1]&&o[h]&&o[h-1].boom!==o[h].boom&&(u=!0);var f=c[h],p=f.indexOf("boom")>=0,m=!p&&0!==h&&c[0].indexOf("boom")>=0&&(!o[h-1]||o[h-1].boom!==o[h].boom),g=r(o[h],f,u,m);p&&(u=!1);for(var v=0;v<g.length;v++)this.writeNote(g[v],.125,p||m?this.boomVolume:this.chickVolume,h,i,p||m?this.bassInstrument:this.chordInstrument),m?m=!1:p=!1}}},t.prototype.processChord=function(e){if(!this.chordTrackFinished){var t,r=this.findChord(e);if(r){var n=this.interpretChord(r);if(n){0===this.chordTrack.length&&this.chordTrack.push({cmd:"program",channel:this.chordChannel,instrument:this.chordInstrument}),this.lastChord=n;var a=(t=this.lastBarTime,8*(s(e.time)-t));this.currentChords.push({chord:this.lastChord,beat:a,start:s(e.time)})}}}},t.prototype.breakSynonyms=["break","(break)","no chord","n.c.","tacet"],t.prototype.basses={A:33,B:35,C:36,D:38,E:40,F:41,G:43};var i={"-addb2":[0,1,3,7],maddb2:[0,1,3,7],addb2:[0,1,4,7],susb2:[0,1,7],"-add2":[0,2,3,7],madd2:[0,2,3,7],add2:[0,2,4,7],sus2:[0,2,7],"-7sus2":[0,2,7,10],"7sus2":[0,2,7,10],m7sus2:[0,2,7,10],min7sus2:[0,2,7,10],"7sus2/9":[0,2,7,10,14],"add#2":[0,3,4,7],"-add4":[0,3,5,7],madd4:[0,3,5,7],dim:[0,3,6],"m(b5)":[0,3,6],"°":[0,3,6],"˚":[0,3,6],"-add#4":[0,3,6,7],"madd#4":[0,3,6,7],dim7:[0,3,6,9],"°7":[0,3,6,9],"˚7":[0,3,6,9],"-7(b5)":[0,3,6,10],"-7b5":[0,3,6,10],"m7(b5)":[0,3,6,10],m7b5:[0,3,6,10],"ø":[0,3,6,10],"ø7":[0,3,6,10],"-":[0,3,7],m:[0,3,7],"-(b6)":[0,3,7,8],"-b6":[0,3,7,8],"m(b6)":[0,3,7,8],mb6:[0,3,7,8],"-6":[0,3,7,9],m6:[0,3,7,9],"-6(9)":[0,3,7,9,14],"-6/9":[0,3,7,9,14],"-69":[0,3,7,9,14],"m6(9)":[0,3,7,9,14],"m6/9":[0,3,7,9,14],m69:[0,3,7,9,14],"-7":[0,3,7,10],m7:[0,3,7,10],"-7(b9)":[0,3,7,10,13],"-7b9":[0,3,7,10,13],"-7(9)":[0,3,7,10,14],"-7/9":[0,3,7,10,14],"-9":[0,3,7,10,14],"m7(9)":[0,3,7,10,14],"m7/9":[0,3,7,10,14],m9:[0,3,7,10,14],"-7(9,11)":[0,3,7,10,14,17],"-7/9/11":[0,3,7,10,14,17],"m7(9,11)":[0,3,7,10,14,17],"m7/9/11":[0,3,7,10,14,17],"-13":[0,3,7,10,14,17,21],"-7(9,11,13)":[0,3,7,10,14,17,21],"-7/9/11/13":[0,3,7,10,14,17,21],m13:[0,3,7,10,14,17,21],"m7(9,11,13)":[0,3,7,10,14,17,21],"m7/9/11/13":[0,3,7,10,14,17,21],"-7(9,13)":[0,3,7,10,14,21],"-7/9/13":[0,3,7,10,14,21],"m7(9,13)":[0,3,7,10,14,21],"m7/9/13":[0,3,7,10,14,21],"-7(11)":[0,3,7,10,17],"-7/11":[0,3,7,10,17],"m7(11)":[0,3,7,10,17],"m7/11":[0,3,7,10,17],"-7(11,13)":[0,3,7,10,17,21],"-7/11/13":[0,3,7,10,17,21],"m7(11,13)":[0,3,7,10,17,21],"m7/11/13":[0,3,7,10,17,21],"-(maj7)":[0,3,7,11],"-7M":[0,3,7,11],"-maj7":[0,3,7,11],"-∆7":[0,3,7,11],"m(maj7)":[0,3,7,11],mM7:[0,3,7,11],"min(maj7)":[0,3,7,11],"-9+7":[0,3,7,11,13],"-(maj9)":[0,3,7,11,14],"-7M(9)":[0,3,7,11,14],"-maj9":[0,3,7,11,14],"-∆9":[0,3,7,11,14],"m(maj9)":[0,3,7,11,14],mM9:[0,3,7,11,14],"min(maj9)":[0,3,7,11,14],"-11":[0,3,7,11,14,17],m11:[0,3,7,11,14,17],"-addb9":[0,3,7,13],maddb9:[0,3,7,13],"-add9":[0,3,7,14],madd9:[0,3,7,14],"-add11":[0,3,7,17],madd11:[0,3,7,17],"-add#11":[0,3,7,18],"madd#11":[0,3,7,18],"-#5":[0,3,8],"-(#5)":[0,3,8],"m#5":[0,3,8],"m(#5)":[0,3,8],"-7#5":[0,3,8,10],"-7(#5)":[0,3,8,10],"dim7(b13)":[0,3,9,20],"°7(b13)":[0,3,9,20],"˚7(b13)":[0,3,9,20],add4:[0,4,5,7],"maj(b5)":[0,4,6],majb5:[0,4,6],"add#4":[0,4,6,7],"7(b5)":[0,4,6,10],"7b5":[0,4,6,10],"7(b5,b9)":[0,4,6,10,13],"7(b9,b5)":[0,4,6,10,13],"7b5(b9)":[0,4,6,10,13],"7b9,b5":[0,4,6,10,13],"7b9b5":[0,4,6,10,13],"7(b5,b9,b13)":[0,4,6,10,13,20],"7/b5/b9/b13":[0,4,6,10,13,20],"7b5/b9/b13":[0,4,6,10,13,20],"7(b5,b9,13)":[0,4,6,10,13,21],"7/b5/b9/13":[0,4,6,10,13,21],"7b5/b9/13":[0,4,6,10,13,21],"7(9,b5)":[0,4,6,10,14],"7(b5,9)":[0,4,6,10,14],"7b5(9)":[0,4,6,10,14],"9b5":[0,4,6,10,14],"13(b5)":[0,4,6,10,14,21],"13b5":[0,4,6,10,14,21],"7(b5,9,13)":[0,4,6,10,14,21],"7/b5/9/13":[0,4,6,10,14,21],"7b5/9/13":[0,4,6,10,14,21],"7#9b5":[0,4,6,10,15],"7(#9,b5)":[0,4,6,10,15],"7(b5,#9)":[0,4,6,10,15],"7b5(#9)":[0,4,6,10,15],"7(b5,#9,b13)":[0,4,6,10,15,20],"7/b5/#9/b13":[0,4,6,10,15,20],"7b5/#9/b13":[0,4,6,10,15,20],"7(b5,#9,13)":[0,4,6,10,15,21],"7/b5/#9/13":[0,4,6,10,15,21],"7b5/#9/13":[0,4,6,10,15,21],"7(b5,b13)":[0,4,6,10,20],"7/b5/b13":[0,4,6,10,20],"7b5/b13":[0,4,6,10,20],"7(b5,13)":[0,4,6,10,21],"7/b5/13":[0,4,6,10,21],"7b5(13)":[0,4,6,10,21],"7b5/13":[0,4,6,10,21],"7M(b5)":[0,4,6,11],"maj7(b5)":[0,4,6,11],maj7b5:[0,4,6,11],"7M(b5,9)":[0,4,6,11,14],"maj7(b5,9)":[0,4,6,11,14],"maj7b5/9":[0,4,6,11,14],"7M(b5,9,13)":[0,4,6,11,14,21],"maj7(b5,9,13)":[0,4,6,11,14,21],"maj7b5/9/13":[0,4,6,11,14,21],"7M(b5,13)":[0,4,6,11,21],"maj7(b5,13)":[0,4,6,11,21],"maj7b5/13":[0,4,6,11,21],M:[0,4,7],"Δ":[0,4,7],"∆":[0,4,7],6:[0,4,7,9],"6(9)":[0,4,7,9,14],"6/9":[0,4,7,9,14],69:[0,4,7,9,14],"6add9":[0,4,7,9,14],"6(9,11)":[0,4,7,9,14,17],"6/9/11":[0,4,7,9,14,17],6911:[0,4,7,9,14,17],"6(9,#11)":[0,4,7,9,14,18],"6/9/#11":[0,4,7,9,14,18],"69#11":[0,4,7,9,14,18],"6(11)":[0,4,7,9,17],"6/11":[0,4,7,9,17],611:[0,4,7,9,17],"6#11":[0,4,7,9,18],"6(#11)":[0,4,7,9,18],"6/#11":[0,4,7,9,18],7:[0,4,7,10],"7(b9)":[0,4,7,10,13],"7b9":[0,4,7,10,13],"7(9)":[0,4,7,10,14],"7/9":[0,4,7,10,14],9:[0,4,7,10,14],"7(9,11)":[0,4,7,10,14,17],"7/9/11":[0,4,7,10,14,17],"7(9,11,13)":[0,4,7,10,14,17,21],"7/9/11/13":[0,4,7,10,14,17,21],"7#11":[0,4,7,10,14,18],"7(#11)":[0,4,7,10,14,18],"9#11":[0,4,7,10,14,18],"9(#11)":[0,4,7,10,14,18],"(13)":[0,4,7,10,14,21],13:[0,4,7,10,14,21],"7(9,13)":[0,4,7,10,14,21],"7/9/13":[0,4,7,10,14,21],"9/13":[0,4,7,10,14,21],"7#9":[0,4,7,10,15],"7(#9)":[0,4,7,10,15],"7(#9,b13)":[0,4,7,10,15,20],"7(11)":[0,4,7,10,17],"7/11":[0,4,7,10,17],"7(11,13)":[0,4,7,10,17,21],"7/11/13":[0,4,7,10,17,21],"13#11":[0,4,7,10,18,21],"13(#11)":[0,4,7,10,18,21],"7(b13)":[0,4,7,10,20],"7b13":[0,4,7,10,20],"7(13)":[0,4,7,10,21],"7/13":[0,4,7,10,21],"7M":[0,4,7,11],maj7:[0,4,7,11],"Δ7":[0,4,7,11],"∆7":[0,4,7,11],"7M(9)":[0,4,7,11,14],"7M/9":[0,4,7,11,14],"maj7(9)":[0,4,7,11,14],"maj7/9":[0,4,7,11,14],maj9:[0,4,7,11,14],"Δ9":[0,4,7,11,14],"∆9":[0,4,7,11,14],"7M(9,11)":[0,4,7,11,14,17],"7M/9/11":[0,4,7,11,14,17],maj11:[0,4,7,11,14,17],"maj7(9,11)":[0,4,7,11,14,17],"maj7/9/11":[0,4,7,11,14,17],"Δ11":[0,4,7,11,14,17],"∆11":[0,4,7,11,14,17],"7M(9,11,13)":[0,4,7,11,14,17,21],"7M/9/11/13":[0,4,7,11,14,17,21],maj13:[0,4,7,11,14,17,21],"maj7(9,11,13)":[0,4,7,11,14,17,21],"maj7/9/11/13":[0,4,7,11,14,17,21],"Δ11(13)":[0,4,7,11,14,17,21],"Δ13":[0,4,7,11,14,17,21],"∆11(13)":[0,4,7,11,14,17,21],"7M(9,#11)":[0,4,7,11,14,18],"7M/9/#11":[0,4,7,11,14,18],"maj7(9,#11)":[0,4,7,11,14,18],"maj7/9/#11":[0,4,7,11,14,18],"maj9#11":[0,4,7,11,14,18],"maj9(#11)":[0,4,7,11,14,18],"maj9/#11":[0,4,7,11,14,18],"Δ9(#11)":[0,4,7,11,14,18],"7M(9,#11,13)":[0,4,7,11,14,18,21],"7M/9/#11/13":[0,4,7,11,14,18,21],"maj13#11":[0,4,7,11,14,18,21],"maj13(#11)":[0,4,7,11,14,18,21],"maj13/#11":[0,4,7,11,14,18,21],"Δ13(#11)":[0,4,7,11,14,18,21],"∆13(#11)":[0,4,7,11,14,18,21],"7M(9,13)":[0,4,7,11,14,21],"7M/9/13":[0,4,7,11,14,21],"maj7(9,13)":[0,4,7,11,14,21],"maj7/9/13":[0,4,7,11,14,21],"maj9(13)":[0,4,7,11,14,21],"Δ9(13)":[0,4,7,11,14,21],"∆9(13)":[0,4,7,11,14,21],"7M(11)":[0,4,7,11,17],"7M/11":[0,4,7,11,17],"maj7(11)":[0,4,7,11,17],"maj7/11":[0,4,7,11,17],"Δ7(11)":[0,4,7,11,17],"∆7(11)":[0,4,7,11,17],"7M(#11)":[0,4,7,11,18],"7M/#11":[0,4,7,11,18],"maj7(#11)":[0,4,7,11,18],"maj7/#11":[0,4,7,11,18],"Δ7(#11)":[0,4,7,11,18],"∆7(#11)":[0,4,7,11,18],"7M(13)":[0,4,7,11,21],"7M/13":[0,4,7,11,21],"maj7(13)":[0,4,7,11,21],"maj7/13":[0,4,7,11,21],"Δ7(13)":[0,4,7,11,21],"∆7(13)":[0,4,7,11,21],addb9:[0,4,7,13],add9:[0,4,7,14],"add#9":[0,4,7,15],add11:[0,4,7,17],"add#11":[0,4,7,18],"+":[0,4,8],aug:[0,4,8],"+7":[0,4,8,10],"7#5":[0,4,8,10],"7(#5)":[0,4,8,10],"7+5":[0,4,8,10],aug7:[0,4,8,10],"7(b9,#5)":[0,4,8,10,13],"7b9#5":[0,4,8,10,13],"9#5":[0,4,8,10,14],"9(#5)":[0,4,8,10,14],"9+5":[0,4,8,10,14],"13#5":[0,4,8,10,14,21],"13(#5)":[0,4,8,10,14,21],"7M(#5)":[0,4,8,11],"maj7#5":[0,4,8,11],"maj7(#5)":[0,4,8,11],"7M(#5,9)":[0,4,8,11,14],"maj7#5/9":[0,4,8,11,14],"maj7(#5,9)":[0,4,8,11,14],"maj7#5#11":[0,4,8,11,18],"maj7(#5,#11)":[0,4,8,11,18],sus:[0,5,7],sus4:[0,5,7],"-7sus4":[0,5,7,10],"7sus":[0,5,7,10],"7sus4":[0,5,7,10],m7sus4:[0,5,7,10],min7sus4:[0,5,7,10],"7sus(b9)":[0,5,7,10,13],"7sus4(b9)":[0,5,7,10,13],"-9sus4":[0,5,7,10,14],"7sus4(9)":[0,5,7,10,14],"7sus4/9":[0,5,7,10,14],"9sus":[0,5,7,10,14],"9sus4":[0,5,7,10,14],m9sus4:[0,5,7,10,14],min9sus4:[0,5,7,10,14],"11sus4":[0,5,7,10,14,17],"13sus4":[0,5,7,10,14,21],"7sus(#9)":[0,5,7,10,15],"7sus4(#9)":[0,5,7,10,15],"7sus4(11)":[0,5,7,10,17],"7sus4(13)":[0,5,7,10,21],"7Msus":[0,5,7,11],"7Msus4":[0,5,7,11],maj7sus:[0,5,7,11],maj7sus4:[0,5,7,11],"#4":[0,6],b5:[0,6],"sus#4":[0,6,7],"7Msus#4":[0,6,11],"maj7sus#4":[0,6,11],5:[0,7],11:[0,7,10,14,17],"5(8)":[0,7,12],"5add8":[0,7,12],"5(9)":[0,7,14],"5add9":[0,7,14],"#5":[0,8],b6:[0,8]};function s(e){return e/1e6}function o(e,t){return Math.round(e*t*1e6)/1e6}t.prototype.rhythmPatterns={"2/2":["boom","","","","chick","","",""],"3/2":["boom","","","","chick","","","","chick","","",""],"4/2":["boom","","","","chick","","","","boom","","","","chick","","",""],"2/4":["boom","","chick",""],"3/4":["boom","","chick","","chick",""],"4/4":["boom","","chick","","boom","","chick",""],"5/4":["boom","","chick","","chick","","boom","","chick",""],"6/4":["boom","","chick","","boom","","chick","","boom","","chick",""],"3/8":["boom","","chick"],"5/8":["boom","chick","chick","boom","chick"],"6/8":["boom","","chick","boom","","chick"],"7/8":["boom","chick","chick","boom","chick","boom","chick"],"9/8":["boom","","chick","boom","","chick","boom","","chick"],"10/8":["boom","chick","chick","boom","chick","chick","boom","chick","boom","chick"],"11/8":["boom","chick","chick","boom","chick","chick","boom","chick","boom","chick","chick"],"12/8":["boom","","chick","boom","","chick","boom","","chick","boom","","chick"]},e.exports=t},9143:function(e,t,r){var n=r(8471);e.exports=function(e){for(var t=[],r=0;r<e.tracks.length;r++)t.push([]);var a=n[0];return e.tracks.forEach(function(e,r){e.forEach(function(e){switch(e.cmd){case"note":var i=void 0!==e.instrument?n[e.instrument]:a;if(e.duration>0){var s=e.gap?e.gap:0,o=e.duration;s=Math.min(s,2*o/3);var c={pitch:e.pitch,instrument:i,start:Math.round(1e6*e.start)/1e6,end:Math.round(1e6*(e.start+o-s))/1e6,volume:e.volume};e.startChar&&(c.startChar=e.startChar),e.endChar&&(c.endChar=e.endChar),e.style&&(c.style=e.style),e.cents&&(c.cents=e.cents),t[r].push(c)}break;case"program":a=n[e.instrument];break;case"text":break;default:console.log("Unhandled midi event",e)}})}),t}},6313:function(e,t,r){var n=r(5049),a=r(5281),i=r(8702),s=r(1225),o=r(9733),c=r(5075),l=r(5343),h=r(6987);function u(e,t,r,s,o){var c=!0;if(i()?c="suspended"===i().state:a(),!n())throw{status:"NotSupported",message:"This browser does not support audio."};(c||o)&&r&&r.classList.add("abcjs-loading"),c?i().resume().then(function(){s?s().then(function(n){d(e,t,r,o)}):d(e,t,r,o)}):d(e,t,r,o)}function d(e,t,r,n){n?e(t).then(function(){r&&r.classList.remove("abcjs-loading")}):(e(t),r&&r.classList.remove("abcjs-loading"))}e.exports=function(e,t){var r=this;if("string"==typeof e){var n=e;if(!(e=document.querySelector(n)))throw new Error('Cannot find element "'+n+'" in the DOM.')}else if(!(e instanceof HTMLElement))throw new Error("The first parameter must be a valid element or selector in the DOM.");if(r.parent=e,r.options={},t&&(r.options=Object.assign({},t)),r.options.ac&&a(r.options.ac),function(e,t){var r=!!t.loopHandler,n=!!t.restartHandler,a=!!t.playHandler||!!t.playPromiseHandler,i=!!t.progressHandler,u=!!t.warpHandler,d=!1!==t.hasClock,f='<div class="abcjs-inline-audio">\n';if(r){var p=t.repeatTitle?t.repeatTitle:"Click to toggle play once/repeat.";f+='<button type="button" class="abcjs-midi-loop abcjs-btn" title="'+p+'" aria-label="'+(t.repeatAria?t.repeatAria:p)+'">'+s+"</button>\n"}if(n){var m=t.restartTitle?t.restartTitle:"Click to go to beginning.";f+='<button type="button" class="abcjs-midi-reset abcjs-btn" title="'+m+'" aria-label="'+(t.restartAria?t.restartAria:m)+'">'+h+"</button>\n"}if(a){var g=t.playTitle?t.playTitle:"Click to play/pause.";f+='<button type="button" class="abcjs-midi-start abcjs-btn" title="'+g+'" aria-label="'+(t.playAria?t.playAria:g)+'">'+o+c+l+"</button>\n"}if(i){var v=t.randomTitle?t.randomTitle:"Click to change the playback position.";f+='<button type="button" class="abcjs-midi-progress-background" title="'+v+'" aria-label="'+(t.randomAria?t.randomAria:v)+'"><span class="abcjs-midi-progress-indicator"></span></button>\n'}if(d&&(f+='<span class="abcjs-midi-clock"></span>\n'),u){var b=t.warpTitle?t.warpTitle:"Change the playback speed.";f+='<span class="abcjs-tempo-wrapper"><label><input class="abcjs-midi-tempo" type="number" min="1" max="300" value="100" title="'+b+'" aria-label="'+(t.warpAria?t.warpAria:b)+'">%</label><span> (<span class="abcjs-midi-current-tempo"></span> '+(t.bpm?t.bpm:"BPM")+")</span></span>\n"}f+='<div class="abcjs-css-warning" style="font-size: 12px;color:red;border: 1px solid red;text-align: center;width: 300px;margin-top: 4px;font-weight: bold;border-radius: 4px;">CSS required: load abcjs-audio.css</div>',f+="</div>\n",e.innerHTML=f}(r.parent,r.options),function(e){var t=!!e.options.loopHandler,r=!!e.options.restartHandler,n=!!e.options.playHandler||!!e.options.playPromiseHandler,a=!!e.options.progressHandler,i=!!e.options.warpHandler,s=e.parent.querySelector(".abcjs-midi-start");t&&e.parent.querySelector(".abcjs-midi-loop").addEventListener("click",function(t){u(e.options.loopHandler,t,s,e.options.afterResume)}),r&&e.parent.querySelector(".abcjs-midi-reset").addEventListener("click",function(t){u(e.options.restartHandler,t,s,e.options.afterResume)}),n&&s.addEventListener("click",function(t){u(e.options.playPromiseHandler||e.options.playHandler,t,s,e.options.afterResume,!!e.options.playPromiseHandler)}),a&&e.parent.querySelector(".abcjs-midi-progress-background").addEventListener("click",function(t){u(e.options.progressHandler,t,s,e.options.afterResume)}),i&&e.parent.querySelector(".abcjs-midi-tempo").addEventListener("change",function(t){u(e.options.warpHandler,t,s,e.options.afterResume)})}(r),r.disable=function(e){var t=r.parent.querySelector(".abcjs-inline-audio");e?t.classList.add("abcjs-disabled"):t.classList.remove("abcjs-disabled")},r.setWarp=function(e,t){r.parent.querySelector(".abcjs-midi-tempo").value=Math.round(t),r.setTempo(e)},r.setTempo=function(e){var t=r.parent.querySelector(".abcjs-midi-current-tempo");t&&(t.innerHTML=Math.round(e))},r.resetAll=function(){for(var e=r.parent.querySelectorAll(".abcjs-pushed"),t=0;t<e.length;t++)e[t].classList.remove("abcjs-pushed")},r.pushPlay=function(e){var t=r.parent.querySelector(".abcjs-midi-start");t&&(e?t.classList.add("abcjs-pushed"):t.classList.remove("abcjs-pushed"))},r.pushLoop=function(e){var t=r.parent.querySelector(".abcjs-midi-loop");t&&(e?t.classList.add("abcjs-pushed"):t.classList.remove("abcjs-pushed"))},r.setProgress=function(e,t){var n=r.parent.querySelector(".abcjs-midi-progress-background"),a=r.parent.querySelector(".abcjs-midi-progress-indicator");if(n&&a){var i=n.clientWidth*e;a.style.left=i+"px";var s=r.parent.querySelector(".abcjs-midi-clock");if(s){var o=t*e/1e3,c=Math.floor(o/60),l=Math.floor(o%60),h=l<10?"0"+l:l;s.innerHTML=c+":"+h}}},r.options.afterResume){var d=!1;r.options.ac?d="suspended"!==r.options.ac.state:i()&&(d="suspended"!==i().state),d&&r.options.afterResume()}}},5594:function(e,t,r){var n=r(2228),a=r(9143),i=r(5281),s=r(8702),o=r(5049),c=r(522),l=r(8471),h=r(873),u=r(4586),d=r(4771),f="MIDI is not supported in this browser.",p="https://paulrosen.github.io/midi-js-soundfonts/abcjs/",m="https://paulrosen.github.io/midi-js-soundfonts/FluidR3_GM/";e.exports=function(){var e=this;e.audioBufferPossible=void 0,e.directSource=[],e.startTimeSec=void 0,e.pausedTimeSec=void 0,e.audioBuffers=[],e.duration=void 0,e.isRunning=!1,e.options={},e.pickupLength=0,e.init=function(t){t||(t={}),t.options&&(e.options=t.options),i(t.audioContext);var r=s().currentTime;if(e.debugCallback=t.debugCallback,e.debugCallback&&e.debugCallback("init called"),e.audioBufferPossible=e._deviceCapable(),!e.audioBufferPossible)return Promise.reject({status:"NotSupported",message:f});var n=t.options?t.options:{};e.soundFontUrl=n.soundFontUrl?n.soundFontUrl:m,"/"!==e.soundFontUrl[e.soundFontUrl.length-1]&&(e.soundFontUrl+="/"),n.soundFontVolumeMultiplier||0===n.soundFontVolumeMultiplier?e.soundFontVolumeMultiplier=n.soundFontVolumeMultiplier:e.soundFontUrl===m||"https://paulrosen.github.io/midi-js-soundfonts/MusyngKite/"===e.soundFontUrl?e.soundFontVolumeMultiplier=3:e.soundFontUrl===p?e.soundFontVolumeMultiplier=.4:e.soundFontVolumeMultiplier=1,n.programOffsets?e.programOffsets=n.programOffsets:e.soundFontUrl===p?e.programOffsets={bright_acoustic_piano:20,honkytonk_piano:20,electric_piano_1:30,electric_piano_2:30,harpsichord:40,clavinet:20,celesta:20,glockenspiel:40,vibraphone:30,marimba:35,xylophone:30,tubular_bells:35,dulcimer:30,drawbar_organ:20,percussive_organ:25,rock_organ:20,church_organ:40,reed_organ:40,accordion:40,harmonica:40,acoustic_guitar_nylon:20,acoustic_guitar_steel:30,electric_guitar_jazz:25,electric_guitar_clean:15,electric_guitar_muted:35,overdriven_guitar:25,distortion_guitar:20,guitar_harmonics:30,electric_bass_finger:15,electric_bass_pick:30,fretless_bass:40,violin:105,viola:50,cello:40,contrabass:60,trumpet:10,trombone:90,alto_sax:20,tenor_sax:20,clarinet:20,flute:50,banjo:50,woodblock:20}:e.programOffsets={};var a=void 0!==n.fadeLength?parseInt(n.fadeLength,10):NaN;if(e.fadeLength=isNaN(a)?200:a,a=void 0!==n.noteEnd?parseInt(n.noteEnd,10):NaN,e.noteEnd=isNaN(a)?0:a,e.pan=n.pan,e.meterSize=1,t.visualObj){e.flattened=t.visualObj.setUpAudio(n);var o=t.visualObj.getMeterFraction();o.den&&(e.meterSize=o.num/o.den),e.pickupLength=t.visualObj.getPickupLength()}else{if(!t.sequence)return Promise.reject(new Error("Must pass in either a visualObj or a sequence"));e.flattened=t.sequence}e.millisecondsPerMeasure=t.millisecondsPerMeasure?t.millisecondsPerMeasure:t.visualObj?t.visualObj.millisecondsPerMeasure(e.flattened.tempo):1e3,e.beatsPerMeasure=t.visualObj?t.visualObj.getBeatsPerMeasure():4,e.sequenceCallback=n.sequenceCallback,e.callbackContext=n.callbackContext,e.onEnded=n.onEnded,e.meterFraction=t.visualObj?t.visualObj.getMeterFraction():{den:1};var h={},u=[],g=[],v=l[0];e.flattened.tracks.forEach(function(e){e.forEach(function(e){if("program"===e.cmd&&l[e.instrument]&&(v=l[e.instrument]),void 0!==e.pitch){var t=e.pitch,r=c[t],n=void 0!==e.instrument?l[e.instrument]:v;if(r)if(h[n]||(h[n]={}),d[n]&&d[n][r]){var a=n+":"+r;u.indexOf(a)<0&&u.push(a)}else h[n][r]=!0;else{var i=n+":"+r;console.log("Can't find note: ",t,i),g.indexOf(i)<0&&g.push(i)}}})}),e.debugCallback&&e.debugCallback("note gathering time = "+Math.floor(1e3*(s().currentTime-r))+"ms"),r=s().currentTime;var b=[];Object.keys(h).forEach(function(e){Object.keys(h[e]).forEach(function(t){b.push({instrument:e,note:t})})}),e.debugCallback&&e.debugCallback("notes "+JSON.stringify(b));for(var y=[],x=0;x<b.length;x+=256)y.push(b.slice(x,x+256));return new Promise(function(t,n){var a={cached:u,error:g,loaded:[]},i=0;!function o(){e.debugCallback&&e.debugCallback("loadBatch idx="+i+" len="+y.length),i<y.length?e._loadBatch(y[i],e.soundFontUrl,r).then(function(t){e.debugCallback&&e.debugCallback("loadBatch then"),r=s().currentTime,t&&(t.error&&(a.error=a.error.concat(t.error)),t.loaded&&(a.loaded=a.loaded.concat(t.loaded))),i++,o()},n):(e.debugCallback&&e.debugCallback("resolve init"),t(a))}()})},e._loadBatch=function(t,r,a,i){var o=[];return t.forEach(function(t){e.debugCallback&&e.debugCallback("getNote "+t.instrument+":"+t.note),o.push(n(r,t.instrument,t.note,s()))}),Promise.all(o).then(function(n){e.debugCallback&&e.debugCallback("mp3 load time = "+Math.floor(1e3*(s().currentTime-a))+"ms");for(var o=[],c=[],l=[],h=[],u=0;u<n.length;u++){var d=n[u],f=d.instrument+":"+d.name;"loaded"===d.status?o.push(f):"pending"===d.status?l.push(f):"cached"===d.status?c.push(f):h.push(f+" "+d.message)}if(l.length>0){if(e.debugCallback&&e.debugCallback("pending "+JSON.stringify(l)),i?i*=2:i=50,i<9e4)return new Promise(function(t,n){setTimeout(function(){var s=[];for(u=0;u<l.length;u++)f=l[u].split(":"),s.push({instrument:f[0],note:f[1]});e.debugCallback&&e.debugCallback("retry "+JSON.stringify(s)),e._loadBatch(s,r,a,i).then(function(e){t(e)}).catch(function(e){n(e)})},i)});for(var p=[],m=0;m<t.length;m++)p.push(t[m].instrument+"/"+t[m].note);return e.debugCallback&&e.debugCallback("loadBatch timeout"),Promise.reject(new Error("timeout attempting to load: "+p.join(", ")))}return e.debugCallback&&e.debugCallback("loadBatch resolve"),Promise.resolve({loaded:o,cached:c,error:h})}).catch(function(t){e.debugCallback&&e.debugCallback("loadBatch catch "+t.message)})},e.prime=function(){var t=e.fadeLength/1e3;return e.isRunning=!1,e.audioBufferPossible?(e.debugCallback&&e.debugCallback("prime called"),new Promise(function(r,n){try{var i=function(e){var t=e&&e.audioBuffers&&e.audioBuffers.length>0?e.audioBuffers[0].duration:0;return{status:s().state,duration:t}},o=s().currentTime,c=e.millisecondsPerMeasure/1e3/e.meterSize;if(e.duration=e.flattened.totalDuration*c,e.duration<=0)return e.audioBuffers=[],r({status:"empty",seconds:0});e.duration+=t;var l=Math.floor(s().sampleRate*e.duration);e.stop();var h=a(e.flattened);if(e.options.swing){var d=e.options.drumIntro?0:e.pickupLength;!function(e,t,r,n){if(!(4!==r.den&&8!==r.den||(t=parseFloat(t),isNaN(t)||t<=50))){t>75&&(t=75),t=t/50-1;var a=.25;8===r.den&&(a/=2);for(var i=a/2,s=i*t,o=0;o<e.length;o++)for(var c=e[o],l=0;l<c.length;l++){var h=c[l];if((h.start-n)%i==0&&(h.start-n)%a!=0&&(0===l||c[l-1].start<=c[l].start-i)&&(l===c.length-1||c[l+1].start>=c[l].start+i)){var u=h.start;h.start+=s,h.volume*=1,l>0&&c[l-1].end===u&&(c[l-1].end=h.start,c[l-1].volume*=1)}}}}(h,e.options.swing,e.meterFraction,d)}e.sequenceCallback&&e.sequenceCallback(h,e.callbackContext);var f=function(e,t){if(null==t)return null;var r=[];if(t.length){for(var n=0;n<e;n++)if(n<t.length){var a=parseFloat(t[n]);a<-1?a=-1:a>1&&(a=1),r.push(a)}else r.push(0);return r}var i=parseFloat(t);if(i*(e-1)>2)return null;for(var s=e%2==0,o=s?0-i/2:0,c=o+i,l=0;l<e;l++)(s=l%2==0)?(r.push(o),o-=i):(r.push(c),c+=i);return r}(h.length,e.pan),p={};h.forEach(function(t,r){var n=f&&f.length>r?f[r]:0;t.forEach(function(t){var r=t.instrument+":"+t.pitch+":"+t.volume+":"+Math.round(1e3*(t.end-t.start))/1e3+":"+n+":"+c+":"+(t.cents?t.cents:0);e.debugCallback&&e.debugCallback("noteMapTrack "+r),p[r]||(p[r]=[]),p[r].push(t.start)})});for(var m=[],g=s().createBuffer(2,l,s().sampleRate),v=0;v<Object.keys(p).length;v++){var b=Object.keys(p)[v],y=b.split(":"),x=void 0!==y[6]?parseFloat(y[6]):0;y={instrument:y[0],pitch:parseInt(y[1],10),volume:parseInt(y[2],10),len:parseFloat(y[3]),pan:parseFloat(y[4]),tempoMultiplier:parseFloat(y[5]),cents:x},m.push(u(g,s().sampleRate,y,p[b],e.soundFontVolumeMultiplier,e.programOffsets[y.instrument],t,e.noteEnd/1e3,e.debugCallback))}e.audioBuffers=[g],e.debugCallback&&(e.debugCallback("sampleRate = "+s().sampleRate),e.debugCallback("totalSamples = "+l),e.debugCallback("creationTime = "+Math.floor(1e3*(s().currentTime-o))+"ms")),Promise.all(m).then(function(){"suspended"===s().state?s().resume().then(function(){r(i(e))}):"interrupted"===s().state?s().suspend().then(function(){s().resume().then(function(){r(i(e))})}):r(i(e))}).catch(function(e){n(e)})}catch(e){n(e)}})):Promise.reject(new Error(f))},e.start=function(){if(!e.audioBufferPossible)throw new Error(f);e.debugCallback&&e.debugCallback("start called");var t=e.pausedTimeSec?e.pausedTimeSec:0;e._kickOffSound(t),e.startTimeSec=s().currentTime-t,e.pausedTimeSec=void 0,e.debugCallback&&e.debugCallback("MIDI STARTED",e.startTimeSec)},e.pause=function(){if(!e.audioBufferPossible)throw new Error(f);return e.debugCallback&&e.debugCallback("pause called"),e.pausedTimeSec=e.stop(),e.pausedTimeSec},e.resume=function(){e.start()},e.seek=function(t,r){var n;switch(r){case"seconds":n=t;break;case"beats":n=t*e.millisecondsPerMeasure/e.beatsPerMeasure/1e3;break;default:n=(e.duration-e.fadeLength/1e3)*t}if(!e.audioBufferPossible)throw new Error(f);e.debugCallback&&e.debugCallback("seek called sec="+n),e.isRunning?(e.stop(),e._kickOffSound(n)):e.pausedTimeSec=n,e.pausedTimeSec=n},e.stop=function(){return e.isRunning=!1,e.pausedTimeSec=void 0,e.directSource.forEach(function(e){try{e.stop()}catch(e){console.log("direct source didn't stop:",e)}}),e.directSource=[],s().currentTime-e.startTimeSec},e.finished=function(){e.startTimeSec=void 0,e.pausedTimeSec=void 0,e.isRunning=!1},e.download=function(){return h(e)},e.getAudioBuffer=function(){return e.audioBuffers[0]},e.getIsRunning=function(){return e.isRunning},e._deviceCapable=function(){return!!o()||(console.warn(f),e.debugCallback&&e.debugCallback(f),!1)},e._kickOffSound=function(t){e.isRunning=!0,e.directSource=[],e.audioBuffers.forEach(function(t,r){e.directSource[r]=s().createBufferSource(),e.directSource[r].buffer=t,e.directSource[r].connect(s().destination)}),e.directSource.forEach(function(e){e.start(0,t)}),e.onEnded&&(e.directSource[0].onended=function(){e.onEnded(e.callbackContext)})}}},873:function(e){e.exports=function(e){return window.URL.createObjectURL(function(e){var t,r,n=e[0],a=n.numberOfChannels,i=n.length*a*2+44,s=new ArrayBuffer(i),o=new DataView(s),c=[],l=0,h=0;for(d(1179011410),d(i-8),d(1163280727),d(544501094),d(16),u(1),u(a),d(n.sampleRate),d(2*n.sampleRate*a),u(2*a),u(16),d(1635017060),d(i-h-4),t=0;t<a;t++)c.push(n.getChannelData(t));for(;h<i;){for(t=0;t<c.length;t++)r=0|(.5+(r=Math.max(-1,Math.min(1,c[t][l])))<0?32768*r:32767*r),o.setInt16(h,r,!0),h+=2;l++}return new Blob([s],{type:"audio/wav"});function u(e){o.setUint16(h,e,!0),h+=2}function d(e){o.setUint32(h,e,!0),h+=4}}(e.audioBuffers))}},562:function(e,t,r){var n=r(1592),a=r(3284);e.exports=function(e,t){var r={};if(t)for(var i in t)t.hasOwnProperty(i)&&(r[i]=t[i]);function s(e,t,n){var i=a(t,r);switch(r.midiOutputType){case"encoded":return i;case"binary":var s=i.replace("data:audio/midi,","");s=(s=s.replace(/MThd/g,"%4d%54%68%64")).replace(/MTrk/g,"%4d%54%72%6b");for(var o=new ArrayBuffer(s.length/3),c=new Uint8Array(o),l=0;l<s.length/3;l++){var h=3*l+1,u=parseInt(s.substring(h,h+2),16);c[l]=u}return c;default:return function(e,t,r,n){var a=["abcjs-download-midi","abcjs-midi-"+n];t.downloadClass&&a.push(t.downloadClass);var i='<div class="'+a.join(" ")+'">';t.preTextDownload&&(i+=t.preTextDownload);var s,o,c=e.metaText&&e.metaText.title?e.metaText.title:"Untitled";return s=t.downloadLabel&&(o=t.downloadLabel)&&"[object Function]"==={}.toString.call(o)?t.downloadLabel(e,n):t.downloadLabel?t.downloadLabel.replace(/%T/,c):'Download MIDI for "'+c+'"',c=c.toLowerCase().replace(/'/g,"").replace(/\W/g,"_").replace(/__/g,"_"),i+='<a download="'+(t.fileName?t.fileName:c+".midi")+'" href="'+r+'">'+s+"</a>",t.postTextDownload&&(i+=t.postTextDownload),i+"</div>"}(t,r,i,n)}}return r.generateInline=!1,"string"==typeof e?n.renderEngine(s,"*",e,r):s(0,e,0)}},5343:function(e){e.exports='\n<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" class="abcjs-loading-svg">\n <circle cx="50" cy="50" fill="none" stroke-width="20" r="35" stroke-dasharray="160 55"></circle>\n</svg>\n'},1225:function(e){e.exports='\n<svg version="1.0" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 700 700" preserveAspectRatio="xMidYMid meet">\n\t<g transform="translate(0,700) scale(0.1,-0.1)" >\n\t<path d="M3111 6981 c-20 -37 -90 -55 -364 -96 -120 -18 -190 -33 -244 -55\n\t-42 -17 -124 -42 -182 -56 -78 -18 -119 -34 -157 -60 -28 -19 -86 -46 -128\n\t-60 -43 -13 -107 -42 -144 -64 -37 -23 -84 -46 -106 -52 -21 -7 -56 -29 -79\n\t-50 -22 -22 -61 -50 -86 -63 -26 -13 -67 -40 -91 -60 -24 -20 -65 -47 -90 -60\n\t-25 -13 -53 -31 -61 -41 -8 -9 -32 -30 -54 -46 -75 -54 -486 -460 -512 -507\n\t-15 -25 -48 -69 -75 -98 -26 -28 -48 -57 -48 -63 0 -6 -18 -29 -39 -53 -21\n\t-23 -56 -71 -77 -107 -20 -36 -50 -80 -65 -97 -16 -18 -33 -52 -40 -75 -12\n\t-47 -47 -115 -84 -166 -13 -18 -30 -56 -38 -83 -8 -27 -34 -80 -56 -118 -33\n\t-53 -46 -91 -62 -167 -12 -63 -34 -127 -59 -179 -42 -84 -60 -166 -60 -270 0\n\t-90 26 -122 125 -154 54 -17 96 -19 430 -20 305 -1 381 2 430 14 82 22 140 51\n\t153 78 6 12 22 47 37 77 14 30 38 77 54 103 15 27 34 73 40 103 7 30 28 78 48\n\t107 19 28 44 74 55 101 10 28 34 67 53 87 18 20 49 61 68 90 19 30 44 63 57\n\t74 13 11 36 40 52 65 59 94 232 270 306 313 20 11 57 37 82 58 25 20 70 52\n\t100 72 30 19 66 47 79 61 13 14 49 35 80 46 30 12 80 37 111 56 31 19 95 45\n\t143 58 48 12 110 37 139 55 63 40 127 55 323 76 83 9 208 28 279 41 156 29\n\t165 29 330 4 453 -71 514 -84 606 -130 31 -16 83 -36 116 -45 32 -9 84 -34\n\t115 -56 31 -21 82 -48 113 -60 32 -11 72 -33 89 -48 18 -16 59 -45 92 -65 33\n\t-21 74 -51 90 -66 17 -15 49 -40 73 -54 52 -32 65 -61 50 -113 -8 -31 -61 -90\n\t-277 -308 -300 -303 -361 -382 -369 -481 -2 -29 0 -66 6 -81 13 -40 88 -138\n\t115 -151 12 -6 54 -26 92 -44 l70 -33 945 -2 c520 -1 975 2 1012 7 64 8 191\n\t50 231 76 11 7 33 34 50 60 22 34 42 51 65 58 l32 9 0 1101 0 1102 -32 9 c-21\n\t7 -44 26 -64 55 -60 84 -77 97 -140 110 -44 9 -76 10 -127 2 -59 -9 -77 -17\n\t-134 -62 -37 -28 -172 -155 -301 -281 -129 -127 -249 -237 -267 -245 -25 -10\n\t-41 -11 -71 -2 -58 15 -112 45 -124 69 -6 11 -35 35 -64 54 -28 18 -58 41 -66\n\t50 -8 9 -41 35 -75 58 -33 22 -77 56 -99 75 -21 18 -64 46 -95 61 -31 14 -73\n\t39 -93 55 -20 15 -70 40 -110 55 -40 15 -97 44 -127 64 -29 21 -78 44 -107 53\n\t-30 8 -77 31 -105 51 -42 28 -73 39 -173 60 -68 14 -154 39 -196 58 -95 43\n\t-131 51 -343 76 -209 24 -242 32 -279 70 l-30 29 -328 0 c-312 0 -330 -1 -339\n\t-19z"></path>\n\t<path d="M254 2875 c-89 -16 -107 -26 -145 -78 -32 -44 -62 -66 -91 -67 -17 0\n\t-18 -61 -18 -1140 l0 -1140 24 0 c16 0 41 -17 72 -50 40 -42 61 -55 117 -72\n\tl69 -21 82 23 c44 12 96 30 114 39 18 9 148 132 290 272 141 141 267 261 279\n\t268 51 26 86 14 176 -61 32 -26 62 -48 66 -48 5 0 36 -25 70 -55 34 -30 74\n\t-61 89 -69 15 -8 37 -28 50 -45 12 -17 50 -45 84 -62 34 -17 78 -44 98 -60 19\n\t-16 61 -37 93 -48 32 -11 81 -37 107 -56 27 -20 76 -45 109 -56 33 -12 75 -31\n\t93 -44 62 -45 93 -58 191 -82 54 -12 130 -37 168 -54 68 -29 180 -58 226 -59\n\t62 0 183 -64 183 -96 0 -12 88 -14 639 -14 l639 0 12 30 c18 44 76 66 233 89\n\t89 14 160 30 200 47 34 15 106 42 159 60 54 18 112 44 130 57 47 35 85 52 146\n\t67 29 7 76 28 105 48 29 20 77 48 107 63 30 15 66 39 80 54 14 15 50 40 81 56\n\t31 15 78 46 104 69 26 22 61 46 79 54 17 7 43 26 56 42 14 16 41 41 60 56 64\n\t48 380 362 408 405 15 23 40 51 55 63 15 12 36 38 46 58 11 21 37 57 58 82 22\n\t25 49 62 62 83 13 20 38 56 57 78 19 23 50 74 69 113 19 39 46 86 59 104 14\n\t18 34 62 46 98 12 36 32 77 45 92 31 38 60 97 80 167 9 33 26 76 37 95 29 50\n\t47 103 68 206 10 52 32 117 51 155 29 56 33 74 34 140 0 94 -10 108 -101 138\n\t-61 20 -83 21 -463 21 -226 0 -421 -4 -451 -10 -63 -12 -86 -30 -110 -85 -10\n\t-22 -33 -63 -52 -92 -21 -31 -42 -80 -53 -123 -11 -44 -32 -93 -56 -128 -20\n\t-32 -47 -83 -59 -115 -12 -32 -37 -77 -56 -100 -19 -23 -50 -65 -69 -94 -19\n\t-29 -44 -57 -54 -63 -11 -5 -29 -27 -42 -47 -52 -85 -234 -277 -300 -315 -25\n\t-15 -53 -38 -62 -51 -9 -14 -42 -39 -74 -57 -32 -18 -75 -48 -95 -66 -21 -18\n\t-59 -44 -85 -58 -26 -13 -72 -40 -100 -59 -35 -24 -78 -41 -128 -52 -47 -11\n\t-99 -31 -139 -56 -69 -42 -94 -49 -391 -110 -245 -51 -425 -66 -595 -50 -168\n\t16 -230 27 -330 61 -47 16 -123 35 -170 44 -98 17 -123 25 -172 58 -20 14 -71\n\t37 -114 53 -44 15 -95 40 -115 56 -20 16 -70 42 -110 59 -40 16 -88 45 -108\n\t63 -20 19 -55 46 -78 61 -24 14 -49 35 -55 47 -7 11 -34 33 -60 49 -50 31 -65\n\t61 -53 102 4 13 130 147 281 298 236 238 277 283 299 335 15 32 35 71 46 86\n\t12 18 19 44 19 76 0 42 -8 63 -53 138 -92 151 11 139 -1207 141 -798 2 -1030\n\t0 -1086 -11z"></path>\n\t</g>\n</svg>\n'},5075:function(e){e.exports='\n<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 25 25" class="abcjs-pause-svg">\n <g>\n <rect width="8.23" height="25"/>\n <rect width="8.23" height="25" x="17"/>\n </g>\n</svg>\n'},9733:function(e){e.exports='\n<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 25 25" class="abcjs-play-svg">\n <g>\n <polygon points="4 0 23 12.5 4 25"/>\n </g>\n</svg>\n'},6987:function(e){e.exports='\n<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 25 25">\n <g>\n <polygon points="5 12.5 24 0 24 25"/>\n <rect width="3" height="25" x="0" y="0"/>\n </g>\n</svg>\n'},8471:function(e){e.exports=["acoustic_grand_piano","bright_acoustic_piano","electric_grand_piano","honkytonk_piano","electric_piano_1","electric_piano_2","harpsichord","clavinet","celesta","glockenspiel","music_box","vibraphone","marimba","xylophone","tubular_bells","dulcimer","drawbar_organ","percussive_organ","rock_organ","church_organ","reed_organ","accordion","harmonica","tango_accordion","acoustic_guitar_nylon","acoustic_guitar_steel","electric_guitar_jazz","electric_guitar_clean","electric_guitar_muted","overdriven_guitar","distortion_guitar","guitar_harmonics","acoustic_bass","electric_bass_finger","electric_bass_pick","fretless_bass","slap_bass_1","slap_bass_2","synth_bass_1","synth_bass_2","violin","viola","cello","contrabass","tremolo_strings","pizzicato_strings","orchestral_harp","timpani","string_ensemble_1","string_ensemble_2","synth_strings_1","synth_strings_2","choir_aahs","voice_oohs","synth_choir","orchestra_hit","trumpet","trombone","tuba","muted_trumpet","french_horn","brass_section","synth_brass_1","synth_brass_2","soprano_sax","alto_sax","tenor_sax","baritone_sax","oboe","english_horn","bassoon","clarinet","piccolo","flute","recorder","pan_flute","blown_bottle","shakuhachi","whistle","ocarina","lead_1_square","lead_2_sawtooth","lead_3_calliope","lead_4_chiff","lead_5_charang","lead_6_voice","lead_7_fifths","lead_8_bass_lead","pad_1_new_age","pad_2_warm","pad_3_polysynth","pad_4_choir","pad_5_bowed","pad_6_metallic","pad_7_halo","pad_8_sweep","fx_1_rain","fx_2_soundtrack","fx_3_crystal","fx_4_atmosphere","fx_5_brightness","fx_6_goblins","fx_7_echoes","fx_8_scifi","sitar","banjo","shamisen","koto","kalimba","bagpipe","fiddle","shanai","tinkle_bell","agogo","steel_drums","woodblock","taiko_drum","melodic_tom","synth_drum","reverse_cymbal","guitar_fret_noise","breath_noise","seashore","bird_tweet","telephone_ring","helicopter","applause","gunshot","percussion"]},2228:function(e,t,r){var n=r(4771);e.exports=function(e,t,r,a){n[t]||(n[t]={});var i=n[t];return i[r]||(i[r]=new Promise(function(n,i){var s=new XMLHttpRequest,o=e+t+"-mp3/"+r+".mp3";s.open("GET",o,!0),s.responseType="arraybuffer",s.onload=function(){if(200===s.status){var e=a.decodeAudioData(s.response,function(e){n({instrument:t,name:r,status:"loaded",audioBuffer:e})},function(){i(Error("Can't decode sound at "+o))});e&&"function"==typeof e.catch&&e.catch(i)}else i(Error("Can't load sound at "+o+" status="+s.status))},s.onerror=function(){i(Error("Can't load sound at "+o))},s.send()}).catch(function(e){throw console.error("Didn't load note",t,r,":",e.message),e})),i[r]}},2842:function(e){var t={__:-2,_:-1,"_/":-.5,"=":0,"":0,"^/":.5,"^":1,"^^":2},r=["C","-","D","-","E","F","-","G","-","A","-","B","c","-","d","-","e","f","-","g","-","a","-","b"];e.exports={noteToMidi:function(e){var n=e.match(/([_^\/]*)([ABCDEFGabcdefg])(,*)('*)/);if(n&&5===n.length){var a=t[n[1]];return 48+r.indexOf(n[2])+a+12*(n[4].length-n[3].length)}return 0},midiToNote:function(e){e=parseInt(e,10);var t=Math.floor(e/12),n=e%12,a=r[n];if("-"===a&&(a="^"+r[n-1]),t>4)for(a=a.toLowerCase(),t-=5;t>0;)a+="'",t--;else for(;t<4;)a+=",",t++;return a}}},522:function(e){e.exports={21:"A0",22:"Bb0",23:"B0",24:"C1",25:"Db1",26:"D1",27:"Eb1",28:"E1",29:"F1",30:"Gb1",31:"G1",32:"Ab1",33:"A1",34:"Bb1",35:"B1",36:"C2",37:"Db2",38:"D2",39:"Eb2",40:"E2",41:"F2",42:"Gb2",43:"G2",44:"Ab2",45:"A2",46:"Bb2",47:"B2",48:"C3",49:"Db3",50:"D3",51:"Eb3",52:"E3",53:"F3",54:"Gb3",55:"G3",56:"Ab3",57:"A3",58:"Bb3",59:"B3",60:"C4",61:"Db4",62:"D4",63:"Eb4",64:"E4",65:"F4",66:"Gb4",67:"G4",68:"Ab4",69:"A4",70:"Bb4",71:"B4",72:"C5",73:"Db5",74:"D5",75:"Eb5",76:"E5",77:"F5",78:"Gb5",79:"G5",80:"Ab5",81:"A5",82:"Bb5",83:"B5",84:"C6",85:"Db6",86:"D6",87:"Eb6",88:"E6",89:"F6",90:"Gb6",91:"G6",92:"Ab6",93:"A6",94:"Bb6",95:"B6",96:"C7",97:"Db7",98:"D7",99:"Eb7",100:"E7",101:"F7",102:"Gb7",103:"G7",104:"Ab7",105:"A7",106:"Bb7",107:"B7",108:"C8",109:"Db8",110:"D8",111:"Eb8",112:"E8",113:"F8",114:"Gb8",115:"G8",116:"Ab8",117:"A8",118:"Bb8",119:"B8",120:"C9",121:"Db9"}},5058:function(e){var t={f0:"_C",n0:"=C",s0:"^C",x0:"C",f1:"_D",n1:"=D",s1:"^D",x1:"D",f2:"_E",n2:"=E",s2:"^E",x2:"E",f3:"_F",n3:"=F",s3:"^F",x3:"F",f4:"_G",n4:"=G",s4:"^G",x4:"G",f5:"_A",n5:"=A",s5:"^A",x5:"A",f6:"_B",n6:"=B",s6:"^B",x6:"B",f7:"_c",n7:"=c",s7:"^c",x7:"c",f8:"_d",n8:"=d",s8:"^d",x8:"d",f9:"_e",n9:"=e",s9:"^e",x9:"e",f10:"_f",n10:"=f",s10:"^f",x10:"f",f11:"_g",n11:"=g",s11:"^g",x11:"g",f12:"_a",n12:"=a",s12:"^a",x12:"a",f13:"_b",n13:"=b",s13:"^b",x13:"b",f14:"_c'",n14:"=c'",s14:"^c'",x14:"c'",f15:"_d'",n15:"=d'",s15:"^d'",x15:"d'",f16:"_e'",n16:"=e'",s16:"^e'",x16:"e'"};e.exports=function(e){var r=(e.accidental?e.accidental[0]:"x")+e.verticalPos;return t[r]}},4586:function(e,t,r){var n=r(4771),a=r(522),i=r(2710),s=function(e,t,r){for(var n=0;n<2;n++)for(var a=t.getChannelData(n),i=e.getChannelData(n),s=0;s<a.length;s++)i[s+r]+=a[s]};e.exports=function(e,t,r,o,c,l,h,u,d){var f=window.OfflineAudioContext||window.webkitOfflineAudioContext,p=r.len*r.tempoMultiplier;l&&(p+=l/1e3),(p-=u)<0&&(p=.005);var m=new f(2,Math.floor((p+h)*t),t),g=a[r.pitch];if(!n[r.instrument])return d&&d("placeNote skipped (instrument empty): "+r.instrument+":"+g),Promise.resolve();var v=n[r.instrument][g];return v?v.then(function(n){var a=m.createBufferSource();a.buffer=n.audioBuffer;var u,f=r.volume/96*c;return a.gainNode=m.createGain(),r.pan&&m.createStereoPanner&&(a.panNode=m.createStereoPanner(),a.panNode.pan.setValueAtTime(r.pan,0)),a.gainNode.gain.value=f,a.gainNode.gain.linearRampToValueAtTime(a.gainNode.gain.value,p),a.gainNode.gain.linearRampToValueAtTime(0,p+h),r.cents&&(a.playbackRate.value=i(r.cents)),a.panNode?(a.panNode.connect(m.destination),a.gainNode.connect(a.panNode)):a.gainNode.connect(m.destination),a.connect(a.gainNode),a.start(0),a.noteOff?a.noteOff(p+h):a.stop(p+h),m.oncomplete=function(n){if(n.renderedBuffer&&n.renderedBuffer.getChannelData)for(var a=0;a<o.length;a++){var i=o[a]*r.tempoMultiplier;l&&(i-=l/1e3),i<0&&(i=0),i=Math.floor(i*t),s(e,n.renderedBuffer,i)}d&&d("placeNote: "+r.instrument+":"+g),u()},m.startRendering(),new Promise(function(e){u=e})}).catch(function(e){return d&&d("placeNote catch: "+e.message),Promise.reject(e)}):(d&&d("placeNote skipped: "+r.instrument+":"+g),Promise.resolve())}},4718:function(e,t,r){var n=r(2029),a=r(5594),i=r(8702);function s(e,t,r,n){var i=new a;return i.init({sequence:e,millisecondsPerMeasure:t,options:{soundFontUrl:r},debugCallback:n}).then(function(){return i.prime()}).then(function(){return i.start(),Promise.resolve()})}e.exports=function(e,t,r,a,o){for(var c=new n,l=0;l<e.length;l++){var h=e[l],u=c.addTrack();if(c.setInstrument(u,h.instrument),0===l&&t)for(var d=0;d<t.length;d++){var f=t[d];c.appendNote(u,f.pitch,1/64,f.volume,f.cents)}c.appendNote(u,h.pitch,h.duration,h.volume,h.cents)}var p=i();return"suspended"===p.state?p.resume().then(function(){return s(c,r,a,o)}):s(c,r,a,o)}},5281:function(e){e.exports=function(e){if(e)window.abcjsAudioContext=e;else if(!window.abcjsAudioContext){var t=window.AudioContext||window.webkitAudioContext;if(!t)return!1;window.abcjsAudioContext=new t}return"suspended"!==window.abcjsAudioContext.state}},7021:function(e,t,r){var n=r(5008);function a(e,t,r,a){r<0&&(r=0),t.length>0&&"bar"===e[r].el_type&&"bar"===t[t.length-1].el_type&&r++;for(var i=r;i<=a;i++){var s,o=!1;if("key"===e[i].el_type||"meter"===e[i].el_type||"tempo"===e[i].el_type||"instrument"===e[i].el_type){for(s=t.length-1;s>=0&&t[s].el_type!==e[i].el_type;)s--;s>=0&&("key"===e[i].el_type&&(h=e[i],u=t[s],h.accidentals&&u.accidentals&&JSON.stringify(h.accidentals)===JSON.stringify(u.accidentals))||"meter"===e[i].el_type&&e[i].num===t[s].num&&e[i].den===t[s].den||"instrument"===e[i].el_type&&e[i].program===t[s].program||"tempo"===e[i].el_type&&e[i].qpm===t[s].qpm)&&(o=!0)}o||t.push((c=e[i],l=void 0,(l=Object.assign({},c)).pitches&&(l.pitches=n.cloneArray(l.pitches)),l))}var c,l,h,u}e.exports=function(e){this.sections=[{type:"startRepeat",index:-1}],this.addBar=function(t){var r=e.length-1,n="bar_left_repeat"===t.type||"bar_dbl_repeat"===t.type,a="bar_right_repeat"===t.type||"bar_dbl_repeat"===t.type,i=t.startEnding?function(e){var t,r,n,a=[];if(e.indexOf(",")>0)for(r=e.split(","),n=0;n<r.length;n++)(t=parseInt(r[n],10))>0&&a.push(t);else if(e.indexOf("-")>0){r=e.split("-");var i=parseInt(r[0],10),s=parseInt(r[1],10);for(n=i;n<=s;n++)a.push(n)}else(t=parseInt(e,10))>0&&a.push(t);return a}(t.startEnding):void 0;a&&(this.sections.length>0&&"endRepeat"===this.sections[this.sections.length-1].type&&this.sections.push({type:"startRepeat",index:this.sections[this.sections.length-1].index}),this.sections.push({type:"endRepeat",index:r})),i&&this.sections.push({type:"startEnding",index:r,endings:i}),n&&this.sections.push({type:"startRepeat",index:r})},this.resolveRepeats=function(){var t,r=this.sections[this.sections.length-1],n=e.length-1;if("startRepeat"===r.type?r.end=n:r.index+1<n&&this.sections.push({type:"startRepeat",index:r.index+1}),this.sections.length<2)return e;for(var i=[],s=null,o=0;o<this.sections.length;o++){var c=this.sections[o];switch(c.type){case"startRepeat":if(s){if(s.common.end||(s.common.end=c.index),s.endings)for(t=0;t<s.endings.length;t++)s.endings[t]&&!s.endings[t].end&&s.endings[t].start!==c.index&&(s.endings[t].end=c.index);"endRepeat"===this.sections[o-1].type&&s.endings&&s.endings.length&&(s.endings[s.endings.length]={start:-1,end:-1}),i.push(s)}if(s){var l=s.common.end;if(s.endings)for(t=0;t<s.endings.length;t++)s.endings[t]&&(l=Math.max(l,s.endings[t].end));l<c.index-1&&i.push({common:{start:l+1,end:c.index}})}s={common:{start:c.index}};break;case"startEnding":if(s)for(s.common.end||(s.common.end=c.index),s.endings||(s.endings=[]),t=0;t<c.endings.length;t++)s.endings[c.endings[t]]={start:c.index+1};break;case"endRepeat":if(s){if(s.endings||(s.endings=[]),s.endings.length>0)for(t=0;t<s.endings.length;t++)s.endings[t]&&!s.endings[t].end&&(s.endings[t].end=c.index);s.common.end||(s.common.end=c.index)}}}if(s){if(s.common.end||(s.common.end=n),s.endings)for(t=0;t<s.endings.length;t++)s.endings[t]&&!s.endings[t].end&&(s.endings[t].end=n);i.push(s)}for(var h=[],u=-1,d=0;d<i.length;d++){var f=i[d];if(f.endings)if(0===f.endings.length)a(e,h,f.common.start,f.common.end),a(e,h,f.common.start,f.common.end);else for(t=0;t<f.endings.length;t++){var p=f.endings[t];p&&(a(e,h,f.common.start,f.common.end),p.start>0&&a(e,h,p.start,p.end),u=Math.max(u,p.end))}else a(e,h,f.common.start,f.common.end)}return h}}},4771:function(e){e.exports={}},5049:function(e,t,r){var n=r(8702);e.exports=function(){if(!window.Promise)return!1;if(!(window.AudioContext||window.webkitAudioContext||navigator.mozAudioContext||navigator.msAudioContext))return!1;var e=n();return e?void 0!==e.resume:void 0}},3450:function(e,t,r){var n=r(6313),a=r(5594),i=r(5681),s=r(8702);e.exports=function(){var e=this;e.warp=100,e.cursorControl=null,e.visualObj=null,e.timer=null,e.midiBuffer=null,e.options=null,e.currentTempo=null,e.control=null,e.isLooping=!1,e.isStarted=!1,e.isLoaded=!1,e.isLoading=!1,e.load=function(t,r,a){a||(a={}),void 0===a.displayPlay&&(a.displayPlay=!0),void 0===a.displayProgress&&(a.displayProgress=!0),e.control=new n(t,{loopHandler:a.displayLoop?e.toggleLoop:void 0,restartHandler:a.displayRestart?e.restart:void 0,playPromiseHandler:a.displayPlay?e.play:void 0,progressHandler:a.displayProgress?e.randomAccess:void 0,warpHandler:a.displayWarp?e.onWarp:void 0,afterResume:e.init}),e.cursorControl=r,e.disable(!0)},e.disable=function(t){e.control&&e.control.disable(t)},e.setTune=function(t,r,n){return e.visualObj=t,e.disable(!1),e.options=n||{},e.control&&(e.pause(),e.setProgress(0,1),e.control.resetAll(),e.restart(),e.isStarted=!1),e.isLooping=!1,r?e.go():Promise.resolve({status:"no-audio-context"})},e.go=function(){e.isLoading=!0;var t,r=100*e.visualObj.millisecondsPerMeasure()/e.warp;return e.currentTempo=Math.round(e.visualObj.getBeatsPerMeasure()/r*6e4),e.control&&e.control.setTempo(e.currentTempo),e.percent=0,e.midiBuffer||(e.midiBuffer=new a),s().resume().then(function(t){return e.midiBuffer.init({visualObj:e.visualObj,options:e.options,millisecondsPerMeasure:r})}).then(function(r){return t=r,e.midiBuffer.prime()}).then(function(){var r=16;return e.cursorControl&&void 0!==e.cursorControl.beatSubdivisions&&parseInt(e.cursorControl.beatSubdivisions,10)>=1&&parseInt(e.cursorControl.beatSubdivisions,10)<=64&&(r=parseInt(e.cursorControl.beatSubdivisions,10)),e.timer=new i(e.visualObj,{beatCallback:e.beatCallback,eventCallback:e.eventCallback,lineEndCallback:e.lineEndCallback,qpm:e.currentTempo,extraMeasuresAtBeginning:e.cursorControl?e.cursorControl.extraMeasuresAtBeginning:void 0,lineEndAnticipation:e.cursorControl?e.cursorControl.lineEndAnticipation:0,beatSubdivisions:r}),e.cursorControl&&e.cursorControl.onReady&&"function"==typeof e.cursorControl.onReady&&e.cursorControl.onReady(e),e.isLoaded=!0,e.isLoading=!1,Promise.resolve({status:"created",notesStatus:t})})},e.destroy=function(){e.timer&&(e.timer.reset(),e.timer.stop(),e.timer=null),e.midiBuffer&&(e.midiBuffer.stop(),e.midiBuffer=null),e.setProgress(0,1),e.control&&e.control.resetAll()},e.play=function(){return e.runWhenReady(e._play,void 0)},e.runWhenReady=function(t,r){return e.visualObj?e.isLoading?new Promise(function(e){setTimeout(e,500)}).then(function(){return e.isLoading?e.runWhenReady(t,r):t(r)}):e.isLoaded?t(r):e.go().then(function(){return t(r)}):Promise.resolve({status:"loading"})},e._play=function(){return s().resume().then(function(){return e.isStarted=!e.isStarted,e.isStarted?(e.cursorControl&&e.cursorControl.onStart&&"function"==typeof e.cursorControl.onStart&&e.cursorControl.onStart(),e.midiBuffer.start(),e.timer.start(e.percent),e.control&&e.control.pushPlay(!0)):e.pause(),Promise.resolve({status:"ok"})})},e.pause=function(){e.timer&&(e.timer.pause(),e.midiBuffer.pause(),e.control&&e.control.pushPlay(!1))},e.toggleLoop=function(){e.isLooping=!e.isLooping,e.control&&e.control.pushLoop(e.isLooping)},e.restart=function(){e.timer&&(e.timer.setProgress(0),e.midiBuffer.seek(0))},e.randomAccess=function(t){return e.runWhenReady(e._randomAccess,t)},e._randomAccess=function(t){var r=t.target.classList.contains("abcjs-midi-progress-indicator")?t.target.parentNode:t.target,n=(t.x-r.getBoundingClientRect().left)/r.offsetWidth;return n<0&&(n=0),n>1&&(n=1),e.seek(n),Promise.resolve({status:"ok"})},e.seek=function(t,r){e.timer&&e.midiBuffer&&(e.timer.setProgress(t,r),e.midiBuffer.seek(t,r))},e.setWarp=function(t){if(parseInt(t,10)>0){e.warp=parseInt(t,10);var r=e.isStarted,n=e.percent;return e.destroy(),e.isStarted=!1,e.go().then(function(){return e.setProgress(n,1e3*e.midiBuffer.duration),e.control&&e.control.setWarp(e.currentTempo,e.warp),r?e.play().then(function(){return e.seek(n),Promise.resolve()}):(e.seek(n),Promise.resolve())})}return Promise.resolve()},e.onWarp=function(t){var r=t.target.value;return e.setWarp(r)},e.setProgress=function(t,r){e.percent=t,e.control&&e.control.setProgress(t,r)},e.finished=function(){if(e.timer.reset(),e.isLooping)return e.timer.start(0),e.midiBuffer.finished(),e.midiBuffer.start(),"continue";e.timer.stop(),e.isStarted&&(e.control&&e.control.pushPlay(!1),e.isStarted=!1,e.midiBuffer.finished(),e.cursorControl&&e.cursorControl.onFinished&&"function"==typeof e.cursorControl.onFinished&&e.cursorControl.onFinished(),e.setProgress(0,1))},e.beatCallback=function(t,r,n,a){var i=t/r;e.setProgress(i,n),e.cursorControl&&e.cursorControl.onBeat&&"function"==typeof e.cursorControl.onBeat&&e.cursorControl.onBeat(t,r,n,a)},e.eventCallback=function(t){if(!t)return e.finished();e.cursorControl&&e.cursorControl.onEvent&&"function"==typeof e.cursorControl.onEvent&&e.cursorControl.onEvent(t)},e.lineEndCallback=function(t,r){e.cursorControl&&e.cursorControl.onLineEnd&&"function"==typeof e.cursorControl.onLineEnd&&e.cursorControl.onLineEnd(t,r)},e.getUrl=function(){return e.midiBuffer.download()},e.download=function(t){var r=e.getUrl(),n=document.createElement("a");document.body.appendChild(n),n.setAttribute("style","display: none;"),n.href=r,n.download=t||"output.wav",n.click(),window.URL.revokeObjectURL(r),document.body.removeChild(n)}}},2029:function(e){e.exports=function(){var e=this;e.tracks=[],e.totalDuration=0,e.currentInstrument=[],e.starts=[],e.addTrack=function(){return e.tracks.push([]),e.currentInstrument.push(0),e.starts.push(0),e.tracks.length-1},e.setInstrument=function(t,r){e.tracks[t].push({channel:0,cmd:"program",instrument:r}),e.currentInstrument[t]=r},e.appendNote=function(t,r,n,a,i){var s={cmd:"note",duration:n,gap:0,instrument:e.currentInstrument[t],pitch:r,start:e.starts[t],volume:a};i&&(s.cents=i),e.tracks[t].push(s),e.starts[t]+=n,e.totalDuration=Math.max(e.totalDuration,e.starts[t])}}},2426:function(e,t,r){var n=r(6074),a={violin:{name:"StringTab",defaultTuning:["G,","D","A","e"],isTabBig:!1,tabSymbolOffset:0},fiddle:{name:"StringTab",defaultTuning:["G,","D","A","e"],isTabBig:!1,tabSymbolOffset:0},mandolin:{name:"StringTab",defaultTuning:["G,","D","A","e"],isTabBig:!1,tabSymbolOffset:0},guitar:{name:"StringTab",defaultTuning:["E,","A,","D","G","B","e"],isTabBig:!0,tabSymbolOffset:0},fiveString:{name:"StringTab",defaultTuning:["C,","G,","D","A","e"],isTabBig:!1,tabSymbolOffset:-.95}},i={inited:!1,plugins:{},register:function(e){var t=e.name,r=e.tablature;this.plugins[t]=r},setError:function(e,t){e.warnings?e.warning.push(t):e.warnings=[t]},preparePlugins:function(e,t,r){this.inited||(this.register(new n),this.inited=!0);var i=null;if(r.tablature){var s=r.tablature;i=[];for(var o=0;o<s.length;o++){var c=s[o],l=c.instrument;if(null==l)return this.setError(e,"tablature 'instrument' is missing"),i;var h=a[l],u=null;if(h&&(u=this.plugins[h.name]),u){0!=r.visualTranspose&&(c.visualTranspose=r.visualTranspose),c.abcSrc=r.tablature.abcSrc;var d={classz:u,tuneNumber:t,params:c,instance:null,tabType:h};i.push(d)}else{if(""!==l)return this.setError(e,"Undefined tablature plugin: "+l),i;i.push(null)}}}return i},layoutTablatures:function(e,t){var r=t.tablatures,n=0;if(r&&r.length>0)for(var a=r.length,i=0;i<a;++i)r[i]&&r[i].params.firstStaffOnly&&(r[i].params.suppress=!1);for(var s=0;s<t.lines.length;s++){var o=t.lines[s];if(o.staff&&n++,n>1&&r&&r.length>0)for(a=r.length,i=0;i<a;++i)r[i].params.firstStaffOnly&&(r[i].params.suppress=!0);var c=o.staff;if(c)for(var l=c.length,h=0;h<c.length;h++)if(r[h]&&h<l){var u=r[h];null==u.instance&&(u.instance=new u.classz,u.instance.init(t,u.tuneNumber,u.params,u.tabType)),u.instance.render(e,o,h)}}}};e.exports=i},1921:function(e,t,r){var n=r(2842).noteToMidi,a=r(6776),i=r(6629);function s(e,t){for(var r=[],n=0;n<t.length;n++)if(!t[n].endTie){var i=new a(t[n].name,e.clefTranspose);i.checkKeyAccidentals(e.accidentals,e.measureAccidentals);var s=c(e,i);r.push(s)}return function(e,t){for(var r=0;r<t.length-1;r++){var n=t[r],a=t[r+1];if(n.str==a.str){if(n.str==e.strings.length-1)return n.num="?",void(a.num="?");a.num<n.num?(a.str++,a=o(e,a.note,a.str,e.secondPos,e.strings[a.str].length)):(n.str++,n=o(e,n.note,n.str,e.secondPos,e.strings[n.str].length)),t[r]=n,t[r+1]=a}}}(e,r),r}function o(e,t,r,n,a){var i=e.strings;t.checkKeyAccidentals(e.accidentals,e.measureAccidentals),n&&(i=n);var s=t.emitNoAccidentals(),o=i[r].indexOf(s),c=t.acc;if(-1!=o){if(n&&(o+=a),(t.isFlat||-1==t.acc)&&0==o){var l=t.getAccidentalEquiv();o=i[++r].indexOf(l.emit()),c=0}return{num:o+c,str:r,note:t}}return null}function c(e,t){var r;(t.isAltered||t.natural)&&(t.isFlat?r=t.isDouble?"__":"_":t.isSharp?r=t.isDouble?"^^":"^":t.natural&&(r="="),e.measureAccidentals[t.name.toUpperCase()]=r);for(var n=e.stringPitches.length-1;n>=0;n--)if(t.pitch+t.pitchAltered>=e.stringPitches[n]){var a=t.pitch+t.pitchAltered-e.stringPitches[n];return"^"===t.quarter?a-=.5:"v"===t.quarter&&(a+=.5),{num:Math.round(a),str:e.stringPitches.length-1-n,note:t}}return{num:"?",str:e.stringPitches.length-1,note:t}}function l(e,t){var r={num:"?",str:0,note:t};e.push(r),e.error=t.emit()+": unexpected note for instrument"}function h(e){var t=e.tuning,r=e.capo,s=e.params.highestNote;this.linePitch=e.linePitch,this.highestNote="a'",s&&(this.highestNote=s),this.measureAccidentals={},this.capo=0,r&&(this.capo=parseInt(r,10)),this.transpose=e.transpose?e.transpose:0,this.tuning=t,this.stringPitches=[];for(var o=0;o<this.tuning.length;o++){var c=n(this.tuning[o])+this.capo;this.stringPitches.push(c)}if(this.capo>0&&(this.capoTuning=function(e){var t=null,r=e.tuning;if(e.capo>0){t=[];for(var n=0;n<r.length;n++){for(var i=new a(r[n]),s=0;s<e.capo;s++)i=i.nextNote();t[n]=i.emit()}}return t}(this)),this.strings=function(e){var t=[],r=e.tuning;e.capo>0&&(r=e.capoTuning);for(var n=r.length-1,a=0;a<r.length;a++){var s=e.highestNote;a!=r.length-1&&(s=r[a+1]);var o=i(r[a],s);if(o.error)return o;t[n--]=o}return t}(this),this.strings.error)return e.setError(this.strings.error),void(e.inError=!0);this.secondPos=function(e){var t=[];t[0]=[];for(var r=e.strings,n=1;n<r.length;n++)t[n]=r[n-1];return t}(this)}h.prototype.stringToPitch=function(e){return 5.3+(this.strings.length-1-e)*this.linePitch},h.prototype.notesToNumber=function(e,t){var r,n,i=null,o=null;if(e&&(o=[],e.length>1?(o=s(this,e)).error&&(i=o.error):e[0].endTie||((r=new a(e[0].name,this.clefTranspose)).checkKeyAccidentals(this.accidentals,this.measureAccidentals),(n=c(this,r))?o.push(n):(l(o,r),i=o.error))),i)return o;var h=null;if(t){h=[];for(var u=0;u<t.length;u++)(r=new a(t[u].name,this.clefTranspose)).checkKeyAccidentals(this.accidentals,this.measureAccidentals),(n=c(this,r))?h.push(n):(l(h,r),i=o.error)}return{notes:o,graces:h,error:i}},h.prototype.toString=function(){for(var e=[],t=0;t<this.tuning.length;t++){var r=this.tuning[t].replaceAll(",","").replaceAll("'","").toUpperCase();"_"===r[0]?r=r[1]+"b ":"^"===r[0]&&(r=r[1]+"# "),e.push(r)}return e.join("")},h.prototype.tabInfos=function(e){var t=e.params.label;if(t){var r="";return-1!=t.indexOf("%T")&&(r=this.toString(),e.capo>0&&(r+=" capo:"+e.capo),t=t.replace("%T",r)),t}return""},h.prototype.suppress=function(e){return!!e.params.suppress},e.exports=h},8918:function(e){function t(e,t){this.numLines=e,this.lineSpace=t,this.verticalSize=this.numLines*this.lineSpace,this.bar={pitch:3,pitch2:t*e,height:5}}t.prototype.bypass=function(e){var t=e.staffGroup.voices;return!!(t.length>0&&t[0].isPercussion)},t.prototype.setRelative=function(e,t,r){switch(e.type){case"bar":t.pitch=this.bar.pitch,t.pitch2=this.bar.pitch2,t.height=this.height;break;case"symbol":var n=this.bar.pitch2/2;if("dots.dot"==e.name)return r?(t.pitch=n,!1):(t.pitch=n+this.lineSpace,!0)}return r},e.exports=t},6776:function(e,t,r){var n=r(2842),a=n.noteToMidi,i=n.midiToNote;function s(e,t){var r=a(e);t&&(r+=t);var n,s=i(r),o=!1,c=!1,l=null,h=null,u=!1,d=0;e.startsWith("_")?(o=!0,d=-1,"/"==e[1]?(o=!1,h="v",d=0):"_"==e[1]&&(u=!0,d-=1)):e.startsWith("^")?(c=!0,d=1,"/"==e[1]?(c=!1,h="^",d=0):"^"==e[1]&&(u=!0,d+=1)):e.startsWith("=")&&(l=!0,d=0),((n=o||c||null!=h)||l)&&(s=null!=h||u?e.slice(2):e.slice(1));var f=(s.match(/,/g)||[]).length,p=(s.match(/'/g)||[]).length;this.pitch=r,this.pitchAltered=0,this.name=s,this.acc=d,this.isSharp=c,this.isKeySharp=!1,this.isDouble=u,this.isAltered=n,this.isFlat=o,this.isKeyFlat=!1,this.natural=l,this.quarter=h,this.isLower=this.name==this.name.toLowerCase(),this.name=this.name[0].toUpperCase(),this.hasComma=f,this.isQuoted=p}s.prototype.sameNoteAs=function(e){return e.pitch===this.pitch},s.prototype.isLowerThan=function(e){return e.pitch>this.pitch},s.prototype.checkKeyAccidentals=function(e,t){if(!this.isAltered&&!this.natural)if(t[this.name.toUpperCase()])switch(t[this.name.toUpperCase()]){case"__":return this.acc=-2,void(this.pitchAltered=-2);case"_":return this.acc=-1,void(this.pitchAltered=-1);case"=":return this.acc=0,void(this.pitchAltered=0);case"^":return this.acc=1,void(this.pitchAltered=1);case"^^":return this.acc=2,void(this.pitchAltered=2)}else if(e)for(var r=this.name,n=0;n<e.length;n++){var a=e[n];r==a.note.toUpperCase()&&("flat"==a.acc&&(this.acc=-1,this.isKeyFlat=!0,this.pitchAltered=-1),"sharp"==a.acc&&(this.acc=1,this.isKeySharp=!0,this.pitchAltered=1))}},s.prototype.getAccidentalEquiv=function(){var e,t,r=((t=new s((e=this).name)).pitch=e.pitch,t.hasComma=e.hasComma,t.isLower=e.isLower,t.isQuoted=e.isQuoted,t.isSharp=e.isSharp,t.isKeySharp=e.isKeySharp,t.isFlat=e.isFlat,t.isKeyFlat=e.isKeyFlat,t);return r.isSharp||r.isKeySharp?((r=r.nextNote()).isFlat=!0,r.isSharp=!1,r.isKeySharp=!1):(r.isFlat||r.isKeyFlat)&&((r=r.prevNote()).isSharp=!0,r.isFlat=!1,r.isKeyFlat=!1),r},s.prototype.nextNote=function(){return new s(i(this.pitch+1+this.pitchAltered))},s.prototype.prevNote=function(){return new s(i(this.pitch-1+this.pitchAltered))},s.prototype.emitNoAccidentals=function(){var e=this.name;this.isLower&&(e=e.toLowerCase());for(var t=0;t<this.isQuoted;t++)e+="'";for(var r=0;r<this.hasComma;r++)e+=",";return e},s.prototype.emit=function(){var e=this.name;(this.isSharp||this.isKeySharp)&&(e="^"+e,this.isDouble&&(e="^"+e)),(this.isFlat||this.isKeyFlat)&&(e="_"+e,this.isDouble&&(e="_"+e)),this.quarter&&(e="^"==this.quarter?"^/"+e:"_/"+e),this.natural&&(e="="+e);for(var t=1;t<=this.hasComma;t++)e+=",";if(this.isLower){e=e.toLowerCase();for(var r=1;r<=this.isQuoted;r++)e+="'"}return e},e.exports=s},6629:function(e,t,r){var n=r(6776),a=["A","B","C","D","E","F","G"];e.exports=function(e,t){var r=new n(e),i=new n(t);if(i.isLowerThan(r)){var s=r.emit();return{error:"Invalid string Instrument tuning : "+i.emit()+" string lower than "+s+" string"}}var o=[],c=a.indexOf(r.name),l=a.indexOf(i.name);if(-1==c||-1==l)return o;for(var h=!1;!h;)o.push(r.emit()),(r=r.nextNote()).sameNoteAs(i)&&(h=!0);return o}},6074:function(e,t,r){var n=r(8918),a=r(4785),i=r(1921);function s(){}s.prototype.init=function(e,t,r,a){this.tune=e,this.params=r,this.tuneNumber=t,this.inError=!1,this.abcTune=e,this.linePitch=3,this.nbLines=a.defaultTuning.length,this.isTabBig=a.isTabBig,this.tabSymbolOffset=a.tabSymbolOffset,this.capo=r.capo,this.transpose=r.visualTranspose,this.hideTabSymbol=r.hideTabSymbol,this.tablature=new n(this.nbLines,this.linePitch);var s=r.tuning;s||(s=a.defaultTuning),this.tuning=s,this.semantics=new i(this)},s.prototype.setError=function(e){e&&(this.error=e,this.inError=!0,this.tune.warnings?this.tune.warnings.push(e):this.tune.warnings=[e])},s.prototype.render=function(e,t,r){this.inError||this.tablature.bypass(t)||a(this,e,t,r)},e.exports=function(){return{name:"StringTab",tablature:s}}},4240:function(e,t,r){var n=r(1409),a=r(6658);function i(e,t){for(var r in t)t.hasOwnProperty(r)&&(Array.isArray(t[r])||null!=(n=t[r])&&n.constructor===Object||(e[r]=t[r]));var n}function s(e){var t=new n("",0,0,"",0);return i(t,e),t.top=0,t.bottom=-1,e.abcelem&&(t.abcelem={},i(t.abcelem,e.abcelem),"note"===t.abcelem.el_type&&(t.abcelem.el_type="tabNumber")),e.cloned=t,t}function o(e,t){var r=s(e);if(t)for(var n=e.children,o=!0,c=0;c<n.length;c++){var l=n[c],h=new a("",0,0,0,"");i(h,l),o=t.tablature.setRelative(l,h,o),r.children.push(h)}return r}function c(e,t,r){var i="tab.tiny",s=7.5;e.isTabBig&&(i="tab.big",s=10);var o={el_type:"tab",icon:i,Ypos:s};if(s+=e.tabSymbolOffset,!e.hideTabSymbol){var c=new n(o,0,0,"symbol",0);c.x=t;var l=new a(i,0,0,7.5,"tab");l.x=r,c.children.push(l),"tab"==c.abcelem.el_type&&(l.pitch=s)}return c}function l(e){if(e.extra)for(var t=0;t<e.extra.length;t++){var r=e.extra[t];if("lyric"==r.type)return{bottom:r.bottom,height:r.height}}return null}function h(){this.accidentals=null}function u(e,t,r,n,i){var s=n.num;null!=n.note.quarter&&(s=s.toString(),s+=n.note.quarter);var o=e.semantics.stringToPitch(n.str);r.notes.push({num:s,str:n.str,pitch:n.note.emit()});var c=new a(s,0,0,o+.3,{type:"tabNumber"});return c.x=t,c.isGrace=i,c.isAltered=n.note.isAltered,c}function d(e,t){var r=0;if(e.extra)for(var n=0;n<e.extra.length;n++)if(e.extra[n].c.indexOf("noteheads")>=0){if(r===t)return e.extra[n].x+e.extra[n].w/2;r++}return-1}function f(e){if(e.abcelem){var t=e.abcelem;if(t.rest)return t.gracenotes}return null}function p(e,t,r){var n=e.semantics.notesToNumber(t,r);if(n.error)return e.setError(n.error),n;if(n.graces&&n.notes){var a=n.notes.length-1;n.notes[a].graces=n.graces}return n}function m(e,t,r,n,a){for(var i=0;i<n.length;i++){var s={el_type:"note",startChar:r.abcelem.startChar,endChar:r.abcelem.endChar,notes:[],grace:!0},o=u(e,d(r,i),s,n[i],!0);t.children.push(o),a.push(s)}}h.prototype.build=function(e,t,r,n,a,i,h){!function(e){for(var t=0;t<e.length;t++)e[t].tabNameInfos}(t);var g=t[a+n],v=t[h],b=null,y=null;"clef"!=g.children[0].abcelem.el_type&&"none"!=i&&g.children.splice(0,0,i);for(var x=0;x<g.children.length;x++){var k=g.children[x],w=k.x,C=w;switch(k.isClef&&(v.children.push(c(e,w,C)),k.abcelem.type.indexOf("-8")>=0&&(e.semantics.clefTranspose=-12),k.abcelem.type.indexOf("+8")>=0&&(e.semantics.clefTranspose=12)),k.type){case"staff-extra key-signature":this.accidentals=k.abcelem.accidentals,e.semantics.accidentals=this.accidentals;break;case"bar":e.semantics.measureAccidentals={};var T=!1;x===g.children.length-1&&(T=!0);var S=o(k,e);if(S.abcelem.barNumber){delete S.abcelem.barNumber;for(var _=0;_<S.children.length;_++)if("barNumber"===S.children[_].type){S.children.splice(_,1);break}}S.abcelem.lastBar=T,v.children.push(S),r.push({el_type:k.abcelem.el_type,type:k.abcelem.type,endChar:k.abcelem.endChar,startChar:k.abcelem.startChar,abselem:S});break;case"rest":var E=f(k);if(E){if((b=p(e,null,E)).error)return;j={el_type:"note",startChar:k.abcelem.startChar,endChar:k.abcelem.endChar,notes:[],grace:!0},m(e,M,k,b.graces,r)}break;case"note":var M=s(k);M.x=k.heads[0].x+k.heads[0].w/2,M.lyricDim=l(k);var A=k.abcelem.pitches,N=k.abcelem.gracenotes;if(M.type="tabNumber",(b=p(e,A,N)).error)return;if(b.graces){var B=b.notes.length-1;b.notes[B].graces=b.graces}y={el_type:"note",startChar:k.abcelem.startChar,endChar:k.abcelem.endChar,notes:[]};for(var P=0;P<b.notes.length;P++){var L=b.notes[P];if(L.graces)for(var O=0;O<L.graces.length;O++){var j={el_type:"note",startChar:k.abcelem.startChar,endChar:k.abcelem.endChar,notes:[],grace:!0},H=u(e,d(k,O),j,L.graces[O],!0);M.children.push(H),r.push(j)}var D=u(e,M.x+k.heads[P].dx,y,L,!1);M.children.push(D)}y.notes.length>0&&(y.abselem=M,r.push(y),v.children.push(M))}}},e.exports=h},4785:function(e,t,r){var n=r(3197),a=r(4240),i=r(4331);function s(e,t,r){var n=e.semantics,a=t.controller.getTextSize,i=n.tabInfos(e),s=!0;if(n.suppress(e)&&(s=!1),s){var o=a.calc(i,"tablabelfont","text instrumentname");return r.tabNameInfos={textSize:{height:o.height,width:o.width},name:i},o.height}return 0}function o(e,t){return!(!t[e].isTabStaff||e!==t.length-1&&t[e+1].isTabStaff)}function c(e,t){for(var r=t;r>=0;r--)if(!e[r].isTabStaff)return r;return-1}function l(e,t){return"clef"===e[t].children[0].abcelem.el_type?null:0==t?"none":e[t-1].children[0]}e.exports=function(e,t,r,h){var u=new a,d={clef:{type:"TAB"}},f=e.linePitch*e.nbLines,p=r.staff;if(p){var m=p[0];if(m&&m.clef&&0==m.clef.stafflines)return void e.setError("No tablatures when stafflines=0");p.splice(p.length,0,d)}var g=r.staffGroup,v=g.voices,b=function(e){for(var t=0,r=0;r<e.children.length;r++){var n=e.children[r];n.specialY&&n.specialY.lyricHeightBelow>t&&(t=n.specialY.lyricHeightBelow)}return t}(v[0]),y=h,x=g.staffs[y],k=f+3-x.bottom-b;x.isTabStaff&&(k=x.top);var w={bottom:-1,isTabStaff:!0,specialY:{tempoHeightAbove:0,partHeightAbove:0,volumeHeightAbove:0,dynamicHeightAbove:0,endingHeightAbove:0,chordHeightAbove:0,lyricHeightAbove:0,lyricHeightBelow:0,chordHeightBelow:0,volumeHeightBelow:0,dynamicHeightBelow:0},lines:e.nbLines,linePitch:e.linePitch,dy:.15,top:k},C=function(e,t){for(var r=0,n=0,a=0;;){if(!t[r])return-1;if(t[r].isTabStaff||(a=t[r].voices.length),t[r].isTabStaff){if(n++,o(r,t)&&n<a)return r+1}else if(n=0,r>=e){if(r+1==t.length)return r+1;if(!t[r+1].isTabStaff)return r+1}if(++r>t.length)return-1}}(h,g.staffs);if(-1!==C){w.parentIndex=C-1,g.staffs.splice(C,0,w),g.height+=f+3;var T=function(e,t){for(var r=t;r>=0;r--)if(!e[r].isTabStaff)return e[r];return null}(g.staffs,C),S=1;(function(e,t){return 1===function(e){for(var t=0,r=0;r<e.length;r++)e[r].isTabStaff||t++;return t}(e)&&t.voices.length>1})(g.staffs,T)&&(S=T.voices.length),d.voices=[];for(var _=0;_<S;_++){var E=new n(0,0);_>0&&(E.duplicate=!0);var M=s(e,t,E)/i.STEP;M=Math.max(M,1),g.staffs[h].top+=1,g.height+=M,E.staff=w;var A=v.length;v.splice(v.length,0,E);var N=l(v,_+h);d.voices[_]=[],u.build(e,v,d.voices[_],_,h,N,A)}!function(e){for(var t=0;t<e.length;t++)if(e[t].isTabStaff){var r=c(e,t);e[t].hasStaff=e[r],e[r].hasTab||(e[r].hasTab=[]),e[r].hasTab.push(e[t])}}(g.staffs)}}},1897:function(e,t,r){var n=r(1409),a=r(8491),i=r(5224),s=r(9600),o=r(3923),c=r(2143),l=r(2525),h=r(8677),u=r(8256),d=r(6020),f=r(6658),p=r(4331),m=r(7398),g=r(1106),v=r(6183),b=r(2096),y=r(3197),x=r(2652),k=r(5058),w=r(5008),C=function(e){var t=0;return e.duration&&(t=e.duration),t},T=!1,S={rest:{0:"rests.whole",1:"rests.half",2:"rests.quarter",3:"rests.8th",4:"rests.16th",5:"rests.32nd",6:"rests.64th",7:"rests.128th",multi:"rests.multimeasure"},note:{"-1":"noteheads.dbl",0:"noteheads.whole",1:"noteheads.half",2:"noteheads.quarter",3:"noteheads.quarter",4:"noteheads.quarter",5:"noteheads.quarter",6:"noteheads.quarter",7:"noteheads.quarter",nostem:"noteheads.quarter"},rhythm:{"-1":"noteheads.slash.whole",0:"noteheads.slash.whole",1:"noteheads.slash.whole",2:"noteheads.slash.quarter",3:"noteheads.slash.quarter",4:"noteheads.slash.quarter",5:"noteheads.slash.quarter",6:"noteheads.slash.quarter",7:"noteheads.slash.quarter",nostem:"noteheads.slash.nostem"},x:{"-1":"noteheads.indeterminate",0:"noteheads.indeterminate",1:"noteheads.indeterminate",2:"noteheads.indeterminate",3:"noteheads.indeterminate",4:"noteheads.indeterminate",5:"noteheads.indeterminate",6:"noteheads.indeterminate",7:"noteheads.indeterminate",nostem:"noteheads.indeterminate"},harmonic:{"-1":"noteheads.harmonic.quarter",0:"noteheads.harmonic.quarter",1:"noteheads.harmonic.quarter",2:"noteheads.harmonic.quarter",3:"noteheads.harmonic.quarter",4:"noteheads.harmonic.quarter",5:"noteheads.harmonic.quarter",6:"noteheads.harmonic.quarter",7:"noteheads.harmonic.quarter",nostem:"noteheads.harmonic.quarter"},triangle:{"-1":"noteheads.triangle.quarter",0:"noteheads.triangle.quarter",1:"noteheads.triangle.quarter",2:"noteheads.triangle.quarter",3:"noteheads.triangle.quarter",4:"noteheads.triangle.quarter",5:"noteheads.triangle.quarter",6:"noteheads.triangle.quarter",7:"noteheads.triangle.quarter",nostem:"noteheads.triangle.quarter"},uflags:{3:"flags.u8th",4:"flags.u16th",5:"flags.u32nd",6:"flags.u64th"},dflags:{3:"flags.d8th",4:"flags.d16th",5:"flags.d32nd",6:"flags.d64th"}},_=function(e,t,r){this.decoration=new h,this.getTextSize=e,this.tuneNumber=t,this.isBagpipes=r.bagpipes,this.flatBeams=r.flatbeams,this.graceSlurs=r.graceSlurs,this.percmap=r.percmap,this.initialClef=r.initialClef,this.jazzchords=!!r.jazzchords,this.accentAbove=!!r.accentAbove,this.germanAlphabet=!!r.germanAlphabet,this.reset()};function E(e,t){var r=e[t];if("note"!==r.el_type||!r.startBeam||r.endBeam)return{count:1,elem:r};for(var n=[];t<e.length&&"note"===e[t].el_type&&(n.push(e[t]),!e[t].endBeam);)t++;return{count:n.length,elem:n}}function M(e){if(e.pitches){A(e);for(var t=0,r=0;r<e.pitches.length;r++)t+=e.pitches[r].verticalPos;e.averagepitch=t/e.pitches.length,e.minpitch=e.pitches[0].verticalPos,e.maxpitch=e.pitches[e.pitches.length-1].verticalPos}}_.prototype.reset=function(){this.slurs={},this.ties=[],this.voiceScale=1,this.voiceColor=void 0,this.slursbyvoice={},this.tiesbyvoice={},this.endingsbyvoice={},this.scaleByVoice={},this.colorByVoice={},this.tripletmultiplier=1,this.abcline=void 0,this.accidentalSlot=void 0,this.accidentalshiftx=void 0,this.dotshiftx=void 0,this.hasVocals=!1,this.minY=void 0,this.partstartelem=void 0,this.startlimitelem=void 0,this.stemdir=void 0},_.prototype.setStemHeight=function(e){this.stemHeight=Math.round(10*e/p.STEP)/10},_.prototype.getCurrentVoiceId=function(e,t){return"s"+e+"v"+t},_.prototype.pushCrossLineElems=function(e,t){this.slursbyvoice[this.getCurrentVoiceId(e,t)]=this.slurs,this.tiesbyvoice[this.getCurrentVoiceId(e,t)]=this.ties,this.endingsbyvoice[this.getCurrentVoiceId(e,t)]=this.partstartelem,this.scaleByVoice[this.getCurrentVoiceId(e,t)]=this.voiceScale,this.voiceColor&&(this.colorByVoice[this.getCurrentVoiceId(e,t)]=this.voiceColor)},_.prototype.popCrossLineElems=function(e,t){this.slurs=this.slursbyvoice[this.getCurrentVoiceId(e,t)]||{},this.ties=this.tiesbyvoice[this.getCurrentVoiceId(e,t)]||[],this.partstartelem=this.endingsbyvoice[this.getCurrentVoiceId(e,t)],this.voiceScale=this.scaleByVoice[this.getCurrentVoiceId(e,t)],void 0===this.voiceScale&&(this.voiceScale=1),this.voiceColor=this.colorByVoice[this.getCurrentVoiceId(e,t)]},_.prototype.containsLyrics=function(e){for(var t=0;t<e.length;t++)for(var r=0;r<e[t].voices.length;r++)for(var n=0;n<e[t].voices[r].length;n++){var a=e[t].voices[r][n];if(a.lyric)return void(a.positioning&&"below"!==a.positioning.vocalPosition||(this.hasVocals=!0))}},_.prototype.createABCLine=function(e,t,r){this.minY=2,this.containsLyrics(e);var n=new m(this.getTextSize);this.tempoSet=!1;for(var a=0;a<e.length;a++)T&&this.restoreState(),T=!1,this.createABCStaff(n,e[a],t,a,r);return n},_.prototype.createABCStaff=function(e,t,r,n,a){e.getTextSize.updateFonts(t);for(var c=0;c<t.voices.length;c++){var h=new y(c,t.voices.length);0===c?(h.barfrom="start"===t.connectBarLines||"continue"===t.connectBarLines,h.barto="continue"===t.connectBarLines||"end"===t.connectBarLines):h.duplicate=!0,t.title&&t.title[c]&&(h.header=t.title[c].replace(/\\n/g,"\n"),h.headerPosition=6+e.getTextSize.baselineToCenter(h.header,"voicefont","staff-extra voice-name",c,t.voices.length)/p.STEP),t.clef&&"perc"===t.clef.type&&(h.isPercussion=!0);var u=(!this.initialClef||0===a)&&s(t.clef,this.tuneNumber);u&&(0===c&&t.barNumber&&this.addMeasureNumber(t.barNumber,u),h.addChild(u),this.startlimitelem=u);var d=o(t.key,this.tuneNumber);if(d&&(h.addChild(d),this.startlimitelem=d),t.meter){"specified"===t.meter.type?this.measureLength=t.meter.value[0].num/t.meter.value[0].den:this.measureLength=1;var f=l(t.meter,this.tuneNumber);h.addChild(f),this.startlimitelem=f}h.duplicate&&(h.children=[]);var m=t.clef.stafflines||0===t.clef.stafflines?t.clef.stafflines:5;e.addVoice(h,n,m);var g=1===m;this.createABCVoice(t.voices[c],r,n,c,g,h),e.setStaffLimits(h),0===c&&("start"===t.brace||!e.brace&&t.brace?(e.brace||(e.brace=[]),e.brace.push(new i(h,"brace"))):"end"===t.brace&&e.brace?e.brace[e.brace.length-1].setBottomStaff(h):"continue"===t.brace&&e.brace&&e.brace[e.brace.length-1].continuing(h),"start"===t.bracket||!e.bracket&&t.bracket?(e.bracket||(e.bracket=[]),e.bracket.push(new i(h,"bracket"))):"end"===t.bracket&&e.bracket?e.bracket[e.bracket.length-1].setBottomStaff(h):"continue"===t.bracket&&e.bracket&&e.bracket[e.bracket.length-1].continuing(h))}},_.prototype.createABCVoice=function(e,t,r,a,i,s){this.popCrossLineElems(r,a),this.stemdir=this.isBagpipes?"down":null,this.abcline=e,this.partstartelem&&(this.partstartelem=new u("",null,null),s.addOther(this.partstartelem));var o=s.voicetotal<2?-1:s.voicenumber;for(var l in this.slurs)this.slurs.hasOwnProperty(l)&&(this.slurs[l]=new v({force:this.slurs[l].force,voiceNumber:o,stemDir:this.slurs[l].stemDir,style:this.slurs[l].dotted}),T&&this.slurs[l].setHint(),s.addOther(this.slurs[l]));for(var h=0;h<this.ties.length;h++)this.ties[h]=new v({force:this.ties[h].force,stemDir:this.ties[h].stemDir,voiceNumber:o,style:this.ties[h].dotted}),T&&this.ties[h].setHint(),s.addOther(this.ties[h]);for(var d=0;d<this.abcline.length;d++)M(this.abcline[d]),this.minY=Math.min(this.abcline[d].minpitch,this.minY);for(var f=0===r,p=0;p<this.abcline.length;){var m=E(this.abcline,p),b=this.createABCElement(f,i,s,m.elem);if(b)for(h=0;h<b.length;h++){if(!this.tempoSet&&t&&!t.suppress){this.tempoSet=!0;var y=new n(t,0,0,"tempo",this.tuneNumber,{});y.addFixedX(new g(t,this.tuneNumber,c)),s.addChild(y)}s.addChild(b[h])}p+=m.count}this.decoration.endLine(s),this.pushCrossLineElems(r,a)},_.prototype.saveState=function(){this.tiesSave=w.cloneArray(this.ties),this.slursSave=w.cloneHashOfHash(this.slurs),this.slursbyvoiceSave=w.cloneHashOfHash(this.slursbyvoice),this.tiesbyvoiceSave=w.cloneHashOfArrayOfHash(this.tiesbyvoice)},_.prototype.restoreState=function(){this.ties=w.cloneArray(this.tiesSave),this.slurs=w.cloneHashOfHash(this.slursSave),this.slursbyvoice=w.cloneHashOfHash(this.slursbyvoiceSave),this.tiesbyvoice=w.cloneHashOfArrayOfHash(this.tiesbyvoiceSave)},_.prototype.createABCElement=function(e,t,r,a){var i=[];switch(a.el_type){case void 0:i=this.createBeam(t,r,a);break;case"note":i[0]=this.createNote(a,!1,t,r),this.triplet&&this.triplet.isClosed()&&(r.addOther(this.triplet),this.triplet=null,this.tripletmultiplier=1);break;case"bar":i[0]=this.createBarLine(r,a,e),r.duplicate&&i.length>0&&(i[0].invisible=!0);break;case"meter":i[0]=l(a,this.tuneNumber),this.startlimitelem=i[0],r.duplicate&&i.length>0&&(i[0].invisible=!0);break;case"clef":if(i[0]=s(a,this.tuneNumber),!i[0])return null;r.duplicate&&i.length>0&&(i[0].invisible=!0);break;case"key":var h=o(a,this.tuneNumber);h&&(i[0]=h,this.startlimitelem=i[0]),r.duplicate&&i.length>0&&(i[0].invisible=!0);break;case"stem":this.stemdir="auto"===a.direction?void 0:a.direction;break;case"part":var u=new n(a,0,0,"part",this.tuneNumber),d=this.getTextSize.calc(a.title,"partsfont","part");u.addFixedX(new f(a.title,0,0,void 0,{type:"part",height:d.height/p.STEP})),i[0]=u;break;case"tempo":var m=new n(a,0,0,"tempo",this.tuneNumber);a.suppress||m.addFixedX(new g(a,this.tuneNumber,c)),i[0]=m;break;case"style":"normal"===a.head?delete this.style:this.style=a.head;break;case"hint":T=!0,this.saveState();break;case"midi":break;case"scale":this.voiceScale=a.size;break;case"color":this.voiceColor=a.color,r.color=this.voiceColor;break;default:var v=new n(a,0,0,"unsupported",this.tuneNumber);v.addFixed(new f("element type "+a.el_type,0,0,void 0,{type:"debug"})),i[0]=v}return i},_.prototype.createBeam=function(e,t,r){var n=[],i=new a(this.stemHeight*this.voiceScale,this.stemdir,this.flatBeams,r[0]);T&&i.setHint();for(var s=0;s<r.length;s++)i.runningDirection(r[s]);i.setStemDirection();var o=this.stemdir;for(this.stemdir=i.stemsUp?"up":"down",s=0;s<r.length;s++){var c=r[s],l=this.createNote(c,!0,e,t);n.push(l),i.add(l),this.triplet&&this.triplet.isClosed()&&(t.addOther(this.triplet),this.triplet=null,this.tripletmultiplier=1)}return i.calcDir(),t.addBeam(i),this.stemdir=o,n};var A=function(e){var t;do{t=!0;for(var r=0;r<e.pitches.length-1;r++)if(e.pitches[r].pitch>e.pitches[r+1].pitch){t=!1;var n=e.pitches[r];e.pitches[r]=e.pitches[r+1],e.pitches[r+1]=n}}while(!t)},N=function(e,t,r,n,a,i,s,o,c){for(var l=r;l>11;l--)l%2!=0||n||e.addFixed(new f(null,o,(a+4)*c,l,{type:"ledger"}));for(l=t;l<1;l++)l%2!=0||n||e.addFixed(new f(null,o,(a+4)*c,l,{type:"ledger"}));for(l=0;l<i.length;l++){var h=a;"down"===s&&(h=-h),e.addFixed(new f(null,h+o,(a+4)*c,i[l],{type:"ledger"}))}};function B(e,t){for(var r=0;r<e.length;r++)if(JSON.stringify(e[r])===JSON.stringify(t))return;e.push(t)}_.prototype.addGraceNotes=function(e,t,r,n,i,s,o){var l=.6;i=Math.round(.7*i);var h,u,p=null;e.gracenotes.length>1&&(p=new a(i,"grace",s),T&&p.setHint(),p.mainNote=r);var m=[];for(u=e.gracenotes.length-1;u>=0;u--)o+=10,m[u]=o,e.gracenotes[u].accidental&&(o+=7);for(u=0;u<e.gracenotes.length;u++){var g=e.gracenotes[u].verticalPos;h=p?null:S.uflags[s?5:3];var b=c(r,"noteheads.quarter",e.gracenotes[u],{dir:"up",headx:-m[u],extrax:-m[u],flag:h,scale:l*this.voiceScale,accidentalSlot:[]});b.notehead.highestVert=b.notehead.pitch+i;var y=b.notehead;if(this.addSlursAndTies(r,e.gracenotes[u],y,t,"up",!0),r.addExtra(y),e.gracenotes[u].acciaccatura){var x=e.gracenotes[u].verticalPos+4.2,k=p?5:6;r.addRight(new f("flags.ugrace",-m[u]+k,0,x,{scalex:l,scaley:l}))}if(p){var w=e.gracenotes[u].duration/2;s&&(w/=2);var C={heads:[y],abcelem:{averagepitch:g,minpitch:g,maxpitch:g,duration:w}};p.add(C)}else{var _=g+1/3*l,E=g+4.2,M=y.dx+y.w;r.addExtra(new f(null,M,0,_,{type:"stem",pitch2:E,linewidth:-.6}))}N(r,g,g,!1,d.getSymbolWidth("noteheads.quarter"),[],!0,y.dx-1,.6);var A=e.rest&&("spacer"===e.rest.type||"invisible"===e.rest.type);0!==u||s||!this.graceSlurs||A||t.addOther(new v({anchor1:y,anchor2:n,isGrace:!0}))}return p&&(p.calcDir(),t.addBeam(p)),o},_.prototype.addNoteToAbcElement=function(e,t,r,n,a,i,s,o,l){var h,u,p,m,g,v=0,b=0,y=0,x=[],w=[],T=0,_=t.averagepitch>=6?"down":"up";for(n&&(_=n),(a=t.style?t.style:a)&&"normal"!==a||(a="note"),(m=i?S[a].nostem:S[a][-s])||console.log("noteSymbol:",a,s,i),g="down"===_?t.pitches.length-2:1;"down"===_?g>=0:g<t.pitches.length;g="down"===_?g-1:g+1){var E=t.pitches["down"===_?g+1:g-1],M=t.pitches[g],A="down"===_?E.pitch-M.pitch:M.pitch-E.pitch;A<=1&&!E.printer_shift&&(M.printer_shift=A?"different":"same",(M.verticalPos>11||M.verticalPos<1)&&x.push(M.verticalPos-M.verticalPos%2),"down"===_?b=d.getSymbolWidth(m)+2:v=d.getSymbolWidth(m)+2)}var N=t.pitches.length;for(g=0;g<t.pitches.length;g++){var P,L;if(o||(P="down"===_&&0!==g||"up"===_&&g!==N-1?null:S["down"===_?"dflags":"uflags"][-s]),t.pitches[g].style)L=S[t.pitches[g].style][-s];else if(l.isPercussion&&this.percmap){L=m;var O=this.percmap[k(t.pitches[g])];O&&O.noteHead&&S[O.noteHead]&&(L=S[O.noteHead][-s])}else L=m;if(t.pitches[g].highestVert=t.pitches[g].verticalPos,("up"===n||"up"===_)&&0===g||("down"===n||"down"===_)&&g===N-1){if((t.startSlur||1===N)&&(t.pitches[g].highestVert=t.pitches[N-1].verticalPos,C(t)<1&&("up"===n||"up"===_)&&(t.pitches[g].highestVert+=6)),t.startSlur)for(t.pitches[g].startSlur||(t.pitches[g].startSlur=[]),p=0;p<t.startSlur.length;p++)B(t.pitches[g].startSlur,t.startSlur[p]);if(t.endSlur)for(t.pitches[g].highestVert=t.pitches[N-1].verticalPos,C(t)<1&&("up"===n||"up"===_)&&(t.pitches[g].highestVert+=6),t.pitches[g].endSlur||(t.pitches[g].endSlur=[]),p=0;p<t.endSlur.length;p++)B(t.pitches[g].endSlur,t.endSlur[p])}var j=!o&&s<=-1,H=N>1?g+1:null,D=c(e,L,t.pitches[g],{dir:_,extrax:-b,flag:P,dot:r,dotshiftx:v,scale:this.voiceScale,accidentalSlot:w,shouldExtendStem:!n,printAccidentals:!l.isPercussion,chordPos:H});T=Math.max(d.getSymbolWidth(L),T),e.extraw-=D.extraLeft,(h=D.notehead)&&(this.addSlursAndTies(e,t.pitches[g],h,l,j?_:null,!1),t.gracenotes&&t.gracenotes.length>0&&(h.bottom=h.bottom-1),e.addHead(h)),b+=D.accidentalshiftx,y=Math.max(y,D.dotshiftx)}if(j){var z=Math.round(70*this.voiceScale)/10,I="down"===_?t.minpitch-z:t.minpitch+1/3;I>6&&!n&&(I=6);var F="down"===_?t.maxpitch-1/3:t.maxpitch+z;F<6&&!n&&(F=6);var V="down"===_||0===e.heads.length?0:e.heads[0].w,G="down"===_?1:-1;h&&"noteheads.slash.quarter"===h.c&&("down"===_?F-=1:I+=1),h&&"noteheads.triangle.quarter"===h.c&&("down"===_?F-=.7:I-=1.2),e.addRight(new f(null,V,0,I,{type:"stem",pitch2:F,linewidth:G,bottom:I-1})),u=Math.min(I,F)}return{noteHead:h,roomTaken:b,roomTakenRight:y,min:u,additionalLedgers:x,dir:_,symbolWidth:T}},_.prototype.addLyric=function(e,t,r){var n="";t.lyric.forEach(function(e){var t=" "===e.divider?"":e.divider;n+=e.syllable+t+"\n"});var a=this.getTextSize.calc(n,"vocalfont","lyric"),i=t.positioning?t.positioning.vocalPosition:"below";e.addCentered(new f(n,0,a.width,void 0,{type:"lyric",position:i,height:a.height/p.STEP,dim:this.getTextSize.attr("vocalfont","lyric"),voiceNumber:r}))},_.prototype.createNote=function(e,t,r,a){var i,s=null,o=0,l=0,h=0,u=[],p=C(e),m=!1;0===p&&(m=!0,p=.25,t=!0);for(var g=Math.floor(Math.log(p)/Math.log(2)),v=0,y=Math.pow(2,g),k=y/2;y<p;v++,y+=k,k/=2);e.startTriplet&&(this.tripletmultiplier=e.tripletMultiplier);var w=p*this.tripletmultiplier;e.rest&&"multimeasure"===e.rest.type&&(w=1),e.rest&&"invisible-multimeasure"===e.rest.type&&(w=this.measureLength*e.rest.text);var _=e.rest?"rest":"note",E=new n(e,w,1,_,this.tuneNumber,{durationClassOveride:e.duration*this.tripletmultiplier});if(T&&E.setHint(),e.rest){this.measureLength===p&&"invisible"!==e.rest.type&&"spacer"!==e.rest.type&&e.rest.type.indexOf("multimeasure")<0&&(e.rest.type="whole");var M=function(e,t,r,n,a,i,s,o,l){var h,u,p,m,g=7;switch(a&&("down"===i&&(g=3),"up"===i&&(g=11)),s&&(g=r<.5||r<1?7:5),t.rest.type){case"whole":h=S.rest[0],t.averagepitch=g,t.minpitch=g,t.maxpitch=g,n=0;break;case"rest":h="rhythm"===t.style?S.rhythm[-o]:S.rest[-o],t.averagepitch=g,t.minpitch=g,t.maxpitch=g;break;case"invisible":case"invisible-multimeasure":case"spacer":h="",t.averagepitch=g,t.minpitch=g,t.maxpitch=g;break;case"multimeasure":h=S.rest.multi,t.averagepitch=g,t.minpitch=g,t.maxpitch=g,n=0;var v=d.getSymbolWidth(h);e.addHead(new f(h,v,2*v,7));var b=new f(""+t.rest.text,v,v,16,{type:"multimeasure-text"});e.addExtra(b)}if(t.rest.type.indexOf("multimeasure")<0&&"invisible"!==t.rest.type){var y=c(e,h,{verticalPos:g},{dot:n,scale:l});(u=y.notehead)&&(e.addHead(u),p=y.accidentalshiftx,m=y.dotshiftx)}return{noteHead:u,roomTaken:p,roomTakenRight:m}}(E,e,p,v,a.voicetotal>1,this.stemdir,r,g,this.voiceScale);s=M.noteHead,o=M.roomTaken,l=M.roomTakenRight}else{var A=this.addNoteToAbcElement(E,e,v,this.stemdir,this.style,m,g,t,a);void 0!==A.min&&(this.minY=Math.min(A.min,this.minY)),s=A.noteHead,o=A.roomTaken,l=A.roomTakenRight,u=A.additionalLedgers,i=A.dir,h=A.symbolWidth}if(void 0!==e.lyric&&this.addLyric(E,e,a.voicenumber),void 0!==e.gracenotes&&(o+=this.addGraceNotes(e,a,E,s,this.stemHeight*this.voiceScale,this.isBagpipes,o)),e.decoration){var B=t&&"up"!==i?Math.min(-3,E.bottom-6):E.bottom;this.decoration.createDecoration(a,e.decoration,E.top,s?s.w:0,E,o,i,B,e.positioning,this.hasVocals,this.accentAbove)}if(e.barNumber&&E.addFixed(new f(e.barNumber,-10,0,0,{type:"barNumber"})),N(E,e.minpitch,e.maxpitch,e.rest,h,u,i,-2,1),void 0!==e.chord){var P=x(this.getTextSize,E,e,o,l,h,this.jazzchords,this.germanAlphabet);o=P.roomTaken,l=P.roomTakenRight}return e.startTriplet&&(this.triplet=new b(e.startTriplet,s,{flatBeams:this.flatBeams})),e.endTriplet&&this.triplet&&this.triplet.setCloseAnchor(s),!this.triplet||e.startTriplet||e.endTriplet||e.rest&&"spacer"===e.rest.type||this.triplet.middleNote(s),E},_.prototype.addSlursAndTies=function(e,t,r,n,a,i){if(t.endTie&&this.ties.length>0){for(var s=!1,o=0;o<this.ties.length;o++)if(this.ties[o].anchor1&&this.ties[o].anchor1.pitch===r.pitch){this.ties[o].setEndAnchor(r),n.setRange(this.ties[o]),this.ties.splice(o,1),s=!0;break}s||(this.ties[0].setEndAnchor(r),n.setRange(this.ties[0]),this.ties.splice(0,1))}var c,l,h=n.voicetotal<2?-1:n.voicenumber;if(t.startTie){var u=new v({anchor1:r,force:"down"===this.stemdir||"up"===this.stemdir,stemDir:this.stemdir,isGrace:i,voiceNumber:h,style:t.startTie.style});T&&u.setHint(),this.ties[this.ties.length]=u,n.addOther(u),e.startTie=!0}if(t.endSlur)for(var d=0;d<t.endSlur.length;d++)l=t.endSlur[d],this.slurs[l]?((c=this.slurs[l]).setEndAnchor(r),n.setRange(c),delete this.slurs[l]):(c=new v({anchor2:r,stemDir:this.stemdir,voiceNumber:h}),T&&c.setHint(),n.addOther(c)),this.startlimitelem&&c.setStartX(this.startlimitelem);else if(!i)for(var f in this.slurs)this.slurs.hasOwnProperty(f)&&this.slurs[f].addInternalNote(r);if(t.startSlur)for(d=0;d<t.startSlur.length;d++)l=t.startSlur[d].label,c=new v({anchor1:r,stemDir:this.stemdir,voiceNumber:h,style:t.startSlur[d].style}),T&&c.setHint(),this.slurs[l]=c,n.addOther(c)},_.prototype.addMeasureNumber=function(e,t){var r=this.getTextSize.calc(e,"measurefont","bar-number"),n=0;t.isClef&&(n+=r.width/2);var a=r.width>10&&"treble"===t.abcelem.type?13.5:11;t.addFixed(new f(e,n,r.width,a+r.height/p.STEP,{type:"barNumber",dim:this.getTextSize.attr("measurefont","bar-number")}))},_.prototype.createBarLine=function(e,t,r){var a=new n(t,0,10,"bar",this.tuneNumber),i=null,s=0;t.barNumber&&this.addMeasureNumber(t.barNumber,a);var o="bar_right_repeat"===t.type||"bar_dbl_repeat"===t.type,c="bar_left_repeat"!==t.type&&"bar_thick_thin"!==t.type&&"bar_invisible"!==t.type,l="bar_right_repeat"===t.type||"bar_dbl_repeat"===t.type||"bar_left_repeat"===t.type||"bar_thin_thick"===t.type||"bar_thick_thin"===t.type,h="bar_left_repeat"===t.type||"bar_thick_thin"===t.type||"bar_thin_thin"===t.type||"bar_dbl_repeat"===t.type,d="bar_left_repeat"===t.type||"bar_dbl_repeat"===t.type;if(o||d){for(var p in this.slurs)this.slurs.hasOwnProperty(p)&&this.slurs[p].setEndX(a);this.startlimitelem=a}if(o&&(a.addRight(new f("dots.dot",s,1,7)),a.addRight(new f("dots.dot",s,1,5)),s+=6),c&&(i=new f(null,s,1,2,{type:"bar",pitch2:10,linewidth:.6}),a.addRight(i)),"bar_invisible"===t.type&&(i=new f(null,s,1,2,{type:"none",pitch2:10,linewidth:.6}),a.addRight(i)),t.decoration&&this.decoration.createDecoration(e,t.decoration,12,l?3:1,a,0,"down",2,t.positioning,this.hasVocals,this.accentAbove),l&&(i=new f(null,s+=4,4,2,{type:"bar",pitch2:10,linewidth:4}),a.addRight(i),s+=5),this.partstartelem&&t.endEnding&&(this.partstartelem.anchor2=i,this.partstartelem=null),h&&(i=new f(null,s+=3,1,2,{type:"bar",pitch2:10,linewidth:.6}),a.addRight(i)),d&&(s+=3,a.addRight(new f("dots.dot",s,1,7)),a.addRight(new f("dots.dot",s,1,5))),t.startEnding&&r&&0===e.voicenumber){var m=this.getTextSize.calc(t.startEnding,"repeatfont","").width;a.minspacing+=m+10,this.partstartelem=new u(t.startEnding,i,null),e.addOther(this.partstartelem)}return a.extraw-=5,void 0!==t.chord&&x(this.getTextSize,a,t,0,0,0,!1,this.germanAlphabet),a},e.exports=_},2652:function(e,t,r){var n=r(6658),a=r(4331),i=r(5810);function s(e,t,r,s,o,c,l,h,u,d,f,p,m,g,v){for(var b=e.split("\n"),y=b.length-1;y>=0;y--){var x,k=b[y],w=0;s||(k=i(k,g,v));var C=h.calc(k,o,c),T=C.width,S=C.height/a.STEP;switch(t){case"left":w=-(f+=T+7),x=d.averagepitch,u.addExtra(new n(k,w,T+4,x,{type:"text",height:S,dim:l,position:"left"}));break;case"right":w=p+=4,x=d.averagepitch,u.addRight(new n(k,w,T+4,x,{type:"text",height:S,dim:l,position:"right"}));break;case"below":u.addRight(new n(k,0,0,void 0,{type:"text",position:"below",height:S,dim:l,realWidth:T}));break;case"above":u.addRight(new n(k,0,0,void 0,{type:"text",position:"above",height:S,dim:l,realWidth:T}));break;default:if(r){var _=r.y+3*a.STEP;u.addRight(new n(k,w+r.x,0,d.minpitch+_/a.STEP,{position:"relative",type:"text",height:S,dim:l}))}else{var E="above";d.positioning&&d.positioning.chordPosition&&(E=d.positioning.chordPosition),"hidden"!==E&&u.addCentered(new n(k,m/2,T,void 0,{type:"chord",position:E,height:S,dim:l,realWidth:T}))}}}return{roomTaken:f,roomTakenRight:p}}e.exports=function(e,t,r,n,a,i,o,c){for(var l=0;l<r.chord.length;l++){var h,u,d=r.chord[l].position,f=r.chord[l].rel_position,p="left"===d||"right"===d||"below"===d||"above"===d||!!f;p?(h="annotationfont",u="abcjs-annotation"):(h="gchordfont",u="abcjs-chord");var m,g=e.attr(h,u),v=r.chord[l].name;if("string"==typeof v)n=(m=s(v,d,f,p,h,u,g,e,t,r,n,a,i,o,c)).roomTaken,a=m.roomTakenRight;else for(var b=0;b<v.length;b++)n=(m=s(v[b].text,d,f,p,h,u,g,e,t,r,n,a,i,o,c)).roomTaken,a=m.roomTakenRight}return{roomTaken:n,roomTakenRight:a}}},1716:function(e){e.exports=function(e,t,r){if(t.text){t.marginLeft||(t.marginLeft=0),t.klass||(t.klass=""),t.anchor||(t.anchor="start"),t.info||(t.info={startChar:-2,endChar:-2}),t.marginTop&&e.push({move:t.marginTop});var n={left:t.marginLeft,text:t.text,font:t.font,anchor:t.anchor,startChar:t.info.startChar,endChar:t.info.endChar,"dominant-baseline":t["dominant-baseline"]};t.absElemType&&(n.absElemType=t.absElemType),!t.inGroup&&t.klass&&(n.klass=t.klass),t.name&&(n.name=t.name),e.push(n);var a=r.calc("A",t.font,t.klass),i=t.text.split("\n").length;if("\n"===t.text[t.text.length-1]&&i--,!t.noMove){var s=1.1*a.height*i;e.push({move:Math.round(s)}),t.marginBottom&&e.push({move:t.marginBottom})}}}},3661:function(e){e.exports=function(e){for(var t=0,r=0;r<e.voices.length;r++){var n=e.voices[r].staff;e.voices[r].duplicate||(t+=n.top,t+=-n.bottom)}return t}},9600:function(e,t,r){var n=r(1409),a=r(6020),i=r(6658);e.exports=function(e,t){var r,s=0;e.el_type="clef";var o=new n(e,0,10,"staff-extra clef",t);switch(o.isClef=!0,e.type){case"treble":r="clefs.G";break;case"tenor":case"alto":r="clefs.C";break;case"bass":r="clefs.F";break;case"treble+8":r="clefs.G",s=1;break;case"tenor+8":case"alto+8":r="clefs.C",s=1;break;case"bass+8":r="clefs.F",s=1;break;case"treble-8":r="clefs.G",s=-1;break;case"tenor-8":case"alto-8":r="clefs.C",s=-1;break;case"bass-8":r="clefs.F",s=-1;break;case"none":return null;case"perc":r="clefs.perc";break;default:o.addFixed(new i("clef="+e.type,0,0,void 0,{type:"debug"}))}if(r){var c=a.symbolHeightInPitches(r),l=function(e){switch(e){case"clefs.G":return-5;case"clefs.C":case"clefs.F":return-4;case"clefs.perc":return-2;default:return 0}}(r);if(o.addRight(new i(r,5,a.getSymbolWidth(r),e.clefPos,{top:c+e.clefPos+l,bottom:e.clefPos+l})),0!==s){var h=2/3,u=(a.getSymbolWidth(r)-a.getSymbolWidth("8")*h)/2,d=s>0?o.top+3:o.bottom-1,f=s>0?o.top+3:o.bottom-3,p=f-2;"bass-8"===e.type&&(d=3,u=0),o.addRight(new i("8",5+u,a.getSymbolWidth("8")*h,d,{scalex:h,scaley:h,top:f,bottom:p}))}}return o}},3923:function(e,t,r){var n=r(1409),a=r(6020),i=r(6658);e.exports=function(e,t){if(e.el_type="keySignature",!e.accidentals||0===e.accidentals.length)return null;var r=new n(e,0,10,"staff-extra key-signature",t);r.isKeySig=!0;var s=0;return e.accidentals.forEach(function(e){var t,n=0;switch(e.acc){case"sharp":t="accidentals.sharp",n=-3;break;case"natural":t="accidentals.nat";break;case"flat":t="accidentals.flat",n=-1.2;break;case"quartersharp":t="accidentals.halfsharp",n=-2.5;break;case"quarterflat":t="accidentals.halfflat",n=-1.2;break;default:t="accidentals.flat"}r.addRight(new i(t,s,a.getSymbolWidth(t),e.verticalPos,{thickness:a.symbolHeightInPitches(t),top:e.verticalPos+a.symbolHeightInPitches(t)+n,bottom:e.verticalPos+n})),s+=a.getSymbolWidth(t)+2},this),r}},2143:function(e,t,r){var n=r(6020),a=r(6658);e.exports=function(e,t,r,i){i||(i={});var s,o=void 0!==i.dir?i.dir:null,c=void 0!==i.headx?i.headx:0,l=void 0!==i.extrax?i.extrax:0,h=void 0!==i.flag?i.flag:null,u=void 0!==i.dot?i.dot:0,d=void 0!==i.dotshiftx?i.dotshiftx:0,f=void 0!==i.scale?i.scale:1,p=void 0!==i.accidentalSlot?i.accidentalSlot:[],m=void 0!==i.shouldExtendStem&&i.shouldExtendStem,g=void 0===i.printAccidentals||i.printAccidentals,v=i.chordPos,b=r.verticalPos,y=0,x=0,k=0;if(void 0===t)e.addFixed(new a("pitch is undefined",0,0,0,{type:"debug"}));else if(""===t)s=new a(null,0,0,b,{chordPos:v});else{var w=c;if(r.printer_shift){var C="same"===r.printer_shift?1:0;w="down"===o?-n.getSymbolWidth(t)*f+C:n.getSymbolWidth(t)*f-C}var T={scalex:f,scaley:f,thickness:n.symbolHeightInPitches(t)*f,name:r.name,chordPos:v};if((s=new a(t,w,n.getSymbolWidth(t)*f,b,T)).stemDir=o,h){var S=b+("down"===o?-7:7)*f;m&&("down"===o&&S>6&&(S=6),"up"===o&&S<6&&(S=6));var _="down"===o?c:c+s.w-.6;e.addRight(new a(h,_,n.getSymbolWidth(h)*f,S,{scalex:f,scaley:f,chordPos:v}))}for(x=s.w+d-2+5*u;u>0;u--){var E=1-Math.abs(b)%2;e.addRight(new a("dots.dot",s.w+d-2+5*u,n.getSymbolWidth("dots.dot"),b+E,{chordPos:v}))}}if(s&&(s.highestVert=r.highestVert),g&&r.accidental){var M;switch(r.accidental){case"quartersharp":M="accidentals.halfsharp";break;case"dblsharp":M="accidentals.dblsharp";break;case"sharp":M="accidentals.sharp";break;case"quarterflat":M="accidentals.halfflat";break;case"flat":M="accidentals.flat";break;case"dblflat":M="accidentals.dblflat";break;case"natural":M="accidentals.nat"}for(var A=!1,N=l,B=0;B<p.length;B++)if(b-p[B][0]>=6){p[B][0]=b,N=p[B][1],A=!0;break}!1===A&&(N-=n.getSymbolWidth(M)*f+2,p.push([b,N]),y=n.getSymbolWidth(M)*f+2);var P=n.symbolHeightInPitches(M);e.addExtra(new a(M,N,n.getSymbolWidth(M),b,{scalex:f,scaley:f,top:b+P/2,bottom:b-P/2,chordPos:v})),k=n.getSymbolWidth(M)/2}return{notehead:s,accidentalshiftx:y,dotshiftx:x,extraLeft:k}}},2525:function(e,t,r){var n=r(1409),a=r(6020),i=r(6658);e.exports=function(e,t){e.el_type="timeSignature";var r=new n(e,0,10,"staff-extra time-signature",t);if("specified"===e.type)for(var s=0,o=0;o<e.value.length;o++)if(0!==o&&(r.addRight(new i("+",s+1,a.getSymbolWidth("+"),6,{thickness:a.symbolHeightInPitches("+")})),s+=a.getSymbolWidth("+")+2),e.value[o].den){for(var c=0,l=0;l<e.value[o].num.length;l++)c+=a.getSymbolWidth(e.value[o].num[l]);var h=0;for(l=0;l<e.value[o].num.length;l++)h+=a.getSymbolWidth(e.value[o].den[l]);var u=Math.max(c,h);r.addRight(new i(e.value[o].num,s+(u-c)/2,c,8,{thickness:a.symbolHeightInPitches(e.value[o].num[0])})),r.addRight(new i(e.value[o].den,s+(u-h)/2,h,4,{thickness:a.symbolHeightInPitches(e.value[o].den[0])})),s+=u}else{for(var d=0,f=0;f<e.value[o].num.length;f++)d+=a.getSymbolWidth(e.value[o].num[f]);r.addRight(new i(e.value[o].num,s,d,6,{thickness:a.symbolHeightInPitches(e.value[o].num[0])})),s+=d}else"common_time"===e.type?r.addRight(new i("timesig.common",0,a.getSymbolWidth("timesig.common"),6,{thickness:a.symbolHeightInPitches("timesig.common")})):"cut_time"===e.type?r.addRight(new i("timesig.cut",0,a.getSymbolWidth("timesig.cut"),6,{thickness:a.symbolHeightInPitches("timesig.cut")})):"tempus_imperfectum"===e.type?r.addRight(new i("timesig.imperfectum",0,a.getSymbolWidth("timesig.imperfectum"),6,{thickness:a.symbolHeightInPitches("timesig.imperfectum")})):"tempus_imperfectum_prolatio"===e.type?r.addRight(new i("timesig.imperfectum2",0,a.getSymbolWidth("timesig.imperfectum2"),6,{thickness:a.symbolHeightInPitches("timesig.imperfectum2")})):"tempus_perfectum"===e.type?r.addRight(new i("timesig.perfectum",0,a.getSymbolWidth("timesig.perfectum"),6,{thickness:a.symbolHeightInPitches("timesig.perfectum")})):"tempus_perfectum_prolatio"===e.type?r.addRight(new i("timesig.perfectum2",0,a.getSymbolWidth("timesig.perfectum2"),6,{thickness:a.symbolHeightInPitches("timesig.perfectum2")})):console.log("time signature:",e);return r}},8677:function(e,t,r){var n=r(3185),a=r(6891),i=r(8844),s=r(6020),o=r(6658),c=r(6183),l=function(){this.startDiminuendoX=void 0,this.startCrescendoX=void 0,this.minTop=12,this.minBottom=0};function h(e){for(var t=0;t<e.length;t++)if(e[t].abcelem.pitches)return e[t];return null}function u(e){return e[e.length-1]}l.prototype.endLine=function(e){this.startDiminuendoX&&(e.addOther(new a(this.startDiminuendoX,u(e.children),">",this.dynamicPositioning)),this.startDiminuendoX=void 0),this.startCrescendoX&&(e.addOther(new a(this.startCrescendoX,u(e.children),"<",this.dynamicPositioning)),this.startCrescendoX=void 0)},l.prototype.dynamicDecoration=function(e,t,r,n){for(var s,o,c,l=0;l<t.length;l++)switch(t[l]){case"diminuendo(":this.startDiminuendoX=r,this.dynamicPositioning=n,s=void 0;break;case"diminuendo)":this.startDiminuendoX||(this.startDiminuendoX=h(e.children)),s={start:this.startDiminuendoX,stop:r},this.startDiminuendoX=void 0;break;case"crescendo(":this.startCrescendoX=r,this.dynamicPositioning=n,o=void 0;break;case"crescendo)":this.startCrescendoX||(this.startCrescendoX=h(e.children)),o={start:this.startCrescendoX,stop:r},this.startCrescendoX=void 0;break;case"~(":case"glissando(":this.startGlissandoX=r,c=void 0;break;case"~)":case"glissando)":c={start:this.startGlissandoX,stop:r},this.startGlissandoX=void 0}s&&e.addOther(new a(s.start,s.stop,">",n)),o&&e.addOther(new a(o.start,o.stop,"<",n)),c&&e.addOther(new i(c.start,c.stop))},l.prototype.createDecoration=function(e,t,r,a,i,l,h,u,d,f,p){d||(d={ornamentPosition:"above",volumePosition:f?"above":"below",dynamicPosition:f?"above":"below"}),function(e,t,r,a){for(var i=0;i<t.length;i++)switch(t[i]){case"p":case"mp":case"pp":case"ppp":case"pppp":case"f":case"ff":case"fff":case"ffff":case"sfz":case"mf":var s=new n(r,t[i],a);e.addOther(s)}}(e,t,i,d.volumePosition),this.dynamicDecoration(e,t,i,d.dynamicPosition),function(e,t,r,n,a){function i(e,t){var i="down"===a?function(){if(0===n.heads.length)return 2;for(var e=n.heads[0].pitch,t=1;t<n.heads.length;t++)e=Math.min(e,n.heads[t].pitch);return e}()+1:function(){if(0===n.heads.length)return 10;for(var e=n.heads[0].pitch,t=1;t<n.heads.length;t++)e=Math.max(e,n.heads[t].pitch);return e}()+9;"down"!==a&&1===t&&i--;var c=r/2;c+="down"===a?-5:3;for(var l=0;l<t;l++)i-=1,n.addFixedX(new o(e,c,s.getSymbolWidth(e),i))}for(var c=0;c<e.length;c++)switch(e[c]){case"/":i("flags.ugrace",1);break;case"//":i("flags.ugrace",2);break;case"///":i("flags.ugrace",3);break;case"////":i("flags.ugrace",4)}}(t,0,a,i,h);var m=function(e,t,r,n,a,i,l,h,u){for(var d,f=0;f<t.length;f++){if("staccato"===t[f]||"tenuto"===t[f]||"accent"===t[f]&&!u){var p="scripts."+t[f];if("accent"===t[f]&&(p="scripts.sforzato"),d=void 0===d?"down"===l?r+2:h-2:"down"===l?d+2:d-2,"accent"===t[f])"up"===l?d--:d++;else switch(d){case 2:case 4:case 6:case 8:case 10:"up"===l?d--:d++}r>9&&d++;var m=n/2;"center"!==s.getSymbolAlign(p)&&(m-=s.getSymbolWidth(p)/2),a.addFixedX(new o(p,m,s.getSymbolWidth(p),d))}if("slide"===t[f]&&a.heads[0]){var g=a.heads[0].pitch,v=new o("",-i-15,0,(g-=2)-1),b=new o("",-i-5,0,g+1);a.addFixedX(v),a.addFixedX(b),e.addOther(new c({anchor1:v,anchor2:b,fixedY:!0}))}}return void 0===d&&(d=r),{above:d,below:a.bottom}}(e,t,r,a,i,l,h,u,p);m.above=Math.max(m.above,this.minTop),m.below=Math.min(m.below,u),function(e,t,r,n,a,i,c,l){function h(e,t){"above"===e?n.above+=t:n.below-=t}function u(e){var t;return"above"===e?(t=n.above)<i&&(t=i):(t=n.below)>c&&(t=c),t}function d(e,n,a){var i=u(n);r.addFixedX(new o(e,t/2,0,i+2,{type:"decoration",klass:"ornament",thickness:3,anchor:a})),h(n,5)}function f(e,n){var a=t/2;"center"!==s.getSymbolAlign(e)&&(a-=s.getSymbolWidth(e)/2);var i=s.symbolHeightInPitches(e)+1,c=u(n);c="above"===n?c+i/2:c-i/2,r.addFixedX(new o(e,a,s.getSymbolWidth(e),c,{klass:"ornament",thickness:s.symbolHeightInPitches(e),position:n})),h(n,i)}for(var p={"+":"scripts.stopped",open:"scripts.open",snap:"scripts.snap",wedge:"scripts.wedge",thumb:"scripts.thumb",shortphrase:"scripts.shortphrase",mediumphrase:"scripts.mediumphrase",longphrase:"scripts.longphrase",trill:"scripts.trill",trillh:"scripts.trill",roll:"scripts.roll",irishroll:"scripts.roll",marcato:"scripts.umarcato",dmarcato:"scripts.dmarcato",umarcato:"scripts.umarcato",turn:"scripts.turn",uppermordent:"scripts.prall",pralltriller:"scripts.prall",mordent:"scripts.mordent",lowermordent:"scripts.mordent",downbow:"scripts.downbow",upbow:"scripts.upbow",fermata:"scripts.ufermata",invertedfermata:"scripts.dfermata",breath:",",coda:"scripts.coda",segno:"scripts.segno"},m=0;m<e.length;m++)switch(e[m]){case"0":case"1":case"2":case"3":case"4":case"5":case"D.C.":case"D.S.":d(e[m],a,"middle");break;case"D.C.alcoda":d("D.C. al coda",a,"end");break;case"D.C.alfine":d("D.C. al fine",a,"end");break;case"D.S.alcoda":d("D.S. al coda",a,"end");break;case"D.S.alfine":d("D.S. al fine",a,"end");break;case"fine":d("FINE",a,"middle");break;case"+":case"open":case"snap":case"wedge":case"thumb":case"shortphrase":case"mediumphrase":case"longphrase":case"trill":case"trillh":case"roll":case"irishroll":case"marcato":case"dmarcato":case"turn":case"uppermordent":case"pralltriller":case"mordent":case"lowermordent":case"downbow":case"upbow":case"fermata":case"breath":case"umarcato":case"coda":case"segno":f(p[e[m]],a);break;case"invertedfermata":f(p[e[m]],"below");break;case"mark":r.klass="mark";break;case"accent":l&&f("scripts.sforzato",a)}}(t,a,i,m,d.ornamentPosition,this.minTop,u,p),function(e,t,r){for(var n=0;n<e.length;n++)if("arpeggio"===e[n])for(var a=t.abcelem.minpitch-1;a<=t.abcelem.maxpitch;a+=2)t.addExtra(new o("scripts.arpeggio",2*-s.getSymbolWidth("scripts.arpeggio")-r,0,a+2,{klass:"ornament",thickness:s.symbolHeightInPitches("scripts.arpeggio")}))}(t,i,l)},e.exports=l},1409:function(e,t,r){var n=r(5741),a=r(5829),i=function(e,t,r,n,a,i){i||(i={}),this.tuneNumber=a,this.abcelem=e,this.duration=t,this.durationClass=i.durationClassOveride?i.durationClassOveride:this.duration,this.minspacing=r||0,this.x=0,this.children=[],this.heads=[],this.extra=[],this.extraw=0,this.w=0,this.right=[],this.invisible=!1,this.bottom=void 0,this.top=void 0,this.type=n,e.extraClass&&(this.extraClass=e.extraClass),this.fixed={w:0,t:void 0,b:void 0},this.specialY={tempoHeightAbove:0,partHeightAbove:0,volumeHeightAbove:0,dynamicHeightAbove:0,endingHeightAbove:0,chordHeightAbove:0,lyricHeightAbove:0,lyricHeightBelow:0,chordHeightBelow:0,volumeHeightBelow:0,dynamicHeightBelow:0}};i.prototype.getFixedCoords=function(){return{x:this.x,w:this.fixed.w,t:this.fixed.t,b:this.fixed.b}},i.prototype.addExtra=function(e){this.fixed.w=Math.max(this.fixed.w,e.dx+e.w),void 0===this.fixed.t?this.fixed.t=e.top:this.fixed.t=Math.max(this.fixed.t,e.top),void 0===this.fixed.b?this.fixed.b=e.bottom:this.fixed.b=Math.min(this.fixed.b,e.bottom),e.dx<this.extraw&&(this.extraw=e.dx),this.extra[this.extra.length]=e,this._addChild(e)},i.prototype.addHead=function(e){e.dx<this.extraw&&(this.extraw=e.dx),this.heads[this.heads.length]=e,this.addRight(e)},i.prototype.addRight=function(e){this.fixed.w=Math.max(this.fixed.w,e.dx+e.w),void 0!==e.top&&(void 0===this.fixed.t?this.fixed.t=e.top:this.fixed.t=Math.max(this.fixed.t,e.top)),void 0!==e.bottom&&(void 0===this.fixed.b?this.fixed.b=e.bottom:this.fixed.b=Math.min(this.fixed.b,e.bottom)),e.dx+e.w>this.w&&(this.w=e.dx+e.w),this.right[this.right.length]=e,this._addChild(e)},i.prototype.addFixed=function(e){this._addChild(e)},i.prototype.addFixedX=function(e){this._addChild(e)},i.prototype.addCentered=function(e){var t=e.w/2;-t<this.extraw&&(this.extraw=-t),this.extra[this.extra.length]=e,e.dx+t>this.w&&(this.w=e.dx+t),this.right[this.right.length]=e,this._addChild(e)},i.prototype.setLimit=function(e,t){t[e]&&(this.specialY[e]?this.specialY[e]=Math.max(this.specialY[e],t[e]):this.specialY[e]=t[e])},i.prototype._addChild=function(e){var t=!0;"clef"==this.abcelem.el_type&&"barNumber"==e.type&&(t=!1),e.parent=this,this.children[this.children.length]=e,t&&this.pushTop(e.top),this.pushBottom(e.bottom),this.setLimit("tempoHeightAbove",e),this.setLimit("partHeightAbove",e),this.setLimit("volumeHeightAbove",e),this.setLimit("dynamicHeightAbove",e),this.setLimit("endingHeightAbove",e),this.setLimit("chordHeightAbove",e),this.setLimit("lyricHeightAbove",e),this.setLimit("lyricHeightBelow",e),this.setLimit("chordHeightBelow",e),this.setLimit("volumeHeightBelow",e),this.setLimit("dynamicHeightBelow",e)},i.prototype.pushTop=function(e){void 0!==e&&(void 0===this.top?this.top=e:this.top=Math.max(e,this.top))},i.prototype.pushBottom=function(e){void 0!==e&&(void 0===this.bottom?this.bottom=e:this.bottom=Math.min(e,this.bottom))},i.prototype.setX=function(e){this.x=e;for(var t=0;t<this.children.length;t++)this.children[t].setX(e)},i.prototype.center=function(e,t){var r=(t.x-e.x)/2+e.x;this.x=r-this.w/2;for(var n=0;n<this.children.length;n++)this.children[n].setX(this.x)},i.prototype.setHint=function(){this.hint=!0},i.prototype.highlight=function(e,t){n.bind(this)(e,t)},i.prototype.unhighlight=function(e,t){a.bind(this)(e,t)},e.exports=i},8491:function(e){var t=function(e,t,r,n){this.type="BeamElem",this.isflat=!!r,this.isgrace=!(!t||"grace"!==t),this.forceup=!!(this.isgrace||t&&"up"===t),this.forcedown=!(!t||"down"!==t),this.elems=[],this.total=0,this.average=6,this.allrests=!0,this.stemHeight=e,this.beams=[],n&&n.duration?(this.duration=n.duration,n.startTriplet&&(this.duration*=n.tripletMultiplier),this.duration=Math.round(1e3*this.duration)/1e3):this.duration=0};function r(e,t){return t?e/t:0}t.prototype.setHint=function(){this.hint=!0},t.prototype.runningDirection=function(e){var t=e.averagepitch;void 0!==t&&(this.total=Math.round(this.total+t),this.count||(this.count=0),this.count++)},t.prototype.add=function(e){var t=e.abcelem.averagepitch;void 0!==t&&(e.abcelem.rest||(this.allrests=!1),e.beam=this,this.elems.push(e),this.total=Math.round(this.total+t),(void 0===this.min||e.abcelem.minpitch<this.min)&&(this.min=e.abcelem.minpitch),(void 0===this.max||e.abcelem.maxpitch>this.max)&&(this.max=e.abcelem.maxpitch))},t.prototype.addBeam=function(e){this.beams.push(e)},t.prototype.setStemDirection=function(){this.average=r(this.total,this.count),this.forceup?this.stemsUp=!0:this.forcedown?this.stemsUp=!1:this.stemsUp=this.average<6,delete this.count,this.total=0},t.prototype.calcDir=function(){this.average=r(this.total,this.elems.length),this.forceup?this.stemsUp=!0:this.forcedown?this.stemsUp=!1:this.stemsUp=this.average<6;for(var e=this.stemsUp?"up":"down",t=0;t<this.elems.length;t++)for(var n=0;n<this.elems[t].heads.length;n++)this.elems[t].heads[n].stemDir=e},e.exports=t},9316:function(e,t,r){var n=r(1716),a=r(6994);function i(e,t,r,n,a,i,s){this.rows=[],e.unalignedWords&&e.unalignedWords.length>0&&this.unalignedWords(e.unalignedWords,n,a,i,s),this.extraText(e,n,a,i,s),e.footer&&r&&this.footer(e.footer,t,n,s)}function s(e,t,r,n,i,s,o){r&&(t&&(r="string"==typeof r?t+r:[{text:t}].concat(r)),a(e,r,"historyfont",i=s?"abcjs-extra-text "+i:"","description",n,{absElemType:"extraText",anchor:"start"},o))}function o(e,t,r,i,s,o,c,l,h,u,d,f){if(r){l=d?"abcjs-extra-text "+l:"";var p=f.calc("A",s,l);if("string"==typeof r)t&&(r=t+"\n"+r),n(e,{marginLeft:i,text:r,font:s,absElemType:"extraText",name:h,"dominant-baseline":"middle",klass:l},f);else{e.push({startGroup:c,klass:l,name:h}),e.push({move:u.info}),t&&(n(e,{marginLeft:i,text:t,font:s,absElemType:"extraText",name:h,"dominant-baseline":"middle"},f),e.push({move:3*p.height/4}));for(var m=0;m<r.length;m++)a(e,r[m],s,"",h,i,{anchor:"start"},f),m<r.length-1&&"string"==typeof r[m]&&"string"!=typeof r[m+1]&&e.push({move:3*p.height/4});e.push({endGroup:c,absElemType:o,startChar:-1,endChar:-1,name:h}),e.push({move:p.height})}}}i.prototype.unalignedWords=function(e,t,r,n,a){var i=n?"abcjs-unaligned-words":"",s="wordsfont",c=a.calc("i",s,i);this.rows.push({move:r.words}),o(this.rows,"",e,t,s,"unalignedWords","unalignedWords",i,"unalignedWords",r,n,a),this.rows.push({move:c.height})},i.prototype.extraText=function(e,t,r,n,a){s(this.rows,"Book: ",e.book,t,"abcjs-book",n,a),s(this.rows,"Source: ",e.source,t,"abcjs-source",n,a),s(this.rows,"Discography: ",e.discography,t,"abcjs-discography",n,a),o(this.rows,"Notes:",e.notes,t,"historyfont","extraText","notes","abcjs-notes","description",r,n,a),s(this.rows,"Transcription: ",e.transcription,t,"abcjs-transcription",n,a),o(this.rows,"History:",e.history,t,"historyfont","extraText","history","abcjs-history","description",r,n,a),s(this.rows,"Copyright: ",e["abc-copyright"],t,"abcjs-copyright",n,a),s(this.rows,"Creator: ",e["abc-creator"],t,"abcjs-creator",n,a),s(this.rows,"Edited By: ",e["abc-edited-by"],t,"abcjs-edited-by",n,a)},i.prototype.footer=function(e,t,r,a){var i="header meta-bottom",s="footerfont";this.rows.push({startGroup:"footer",klass:i}),n(this.rows,{marginLeft:r,text:e.left,font:s,klass:i,name:"footer"},a),n(this.rows,{marginLeft:r+t/2,text:e.center,font:s,klass:i,anchor:"middle",name:"footer"},a),n(this.rows,{marginLeft:r+t,text:e.right,font:s,klass:i,anchor:"end",name:"footer"},a)},e.exports=i},5224:function(e){var t=function(e,t){this.startVoice=e,this.type=t};t.prototype.setBottomStaff=function(e){this.endVoice=e,this.startVoice.header&&!this.endVoice.header&&(this.header=this.startVoice.header,delete this.startVoice.header)},t.prototype.continuing=function(e){this.lastContinuedVoice=e},t.prototype.getWidth=function(){return 10},t.prototype.isStartVoice=function(e){return!!(this.startVoice&&this.startVoice.staff&&this.startVoice.staff.voices.length>0&&this.startVoice.staff.voices[0]===e)},e.exports=t},6891:function(e){e.exports=function(e,t,r,n){this.type="CrescendoElem",this.anchor1=e,this.anchor2=t,this.dir=r,"above"===n?this.dynamicHeightAbove=6:this.dynamicHeightBelow=6,this.pitch=void 0}},3185:function(e){e.exports=function(e,t,r){this.type="DynamicDecoration",this.anchor=e,this.dec=t,"below"===r?this.volumeHeightBelow=6:this.volumeHeightAbove=6,this.pitch=void 0}},8256:function(e){e.exports=function(e,t,r){this.type="EndingElem",this.text=e,this.anchor1=t,this.anchor2=r,this.endingHeightAbove=5,this.pitch=void 0}},3736:function(e){e.exports=function(e,t,r,n,a,i){var s,o=e.text;this.rows=[],t&&this.rows.push({move:t});var c=r.calc("textfont","defined-text");if(""===o)this.rows.push({move:2*c.attr["font-size"]});else if("string"==typeof o){this.rows.push({move:c.attr["font-size"]/2}),this.rows.push({left:n,text:o,font:"textfont",klass:"defined-text",anchor:"start",startChar:e.startChar,endChar:e.endChar,absElemType:"freeText",name:"free-text"});var l=o.replace(/^[ \t]*\n/gm,"X\n");s=i.calc(l,"textfont","defined-text"),this.rows.push({move:s.height})}else if(o){for(var h=0,u=n,d="textfont",f=0;f<o.length;f++)d=o[f].font?o[f].font:"textfont",this.rows.push({left:u,text:o[f].text,font:d,klass:"defined-text",anchor:"start",startChar:e.startChar,endChar:e.endChar,absElemType:"freeText",name:"free-text"}),u+=(s=i.calc(o[f].text,r.calc(d,"defined-text").font,"defined-text")).width+s.height/2,h=Math.max(h,s.height);this.rows.push({move:h})}else if(1===e.length){var p=a/2;this.rows.push({left:p,text:e[0].text,font:"textfont",klass:"defined-text",anchor:"middle",startChar:e.startChar,endChar:e.endChar,absElemType:"freeText",name:"free-text"}),s=i.calc(e[0].text,"textfont","defined-text"),this.rows.push({move:s.height})}}},8844:function(e){e.exports=function(e,t){this.type="GlissandoElem",this.anchor1=e,this.anchor2=t}},6658:function(e){var t=function(e,t,r,n,a){switch(a=a||{},this.x=0,this.c=e,this.dx=t,this.w=r,this.pitch=n,this.scalex=a.scalex||1,this.scaley=a.scaley||1,this.type=a.type||"symbol",this.pitch2=a.pitch2,this.linewidth=a.linewidth,this.klass=a.klass,this.chordPos=a.chordPos,this.anchor=a.anchor?a.anchor:"middle",this.top=n,void 0!==this.pitch2&&this.pitch2>this.top&&(this.top=this.pitch2),this.bottom=n,void 0!==this.pitch2&&this.pitch2<this.bottom&&(this.bottom=this.pitch2),a.thickness&&(this.top+=a.thickness/2,this.bottom-=a.thickness/2),a.stemHeight&&(a.stemHeight>0?this.top+=a.stemHeight:this.bottom+=a.stemHeight),a.dim&&(this.dim=a.dim),a.position&&(this.position=a.position),void 0!==a.voiceNumber&&(this.voiceNumber=a.voiceNumber),this.height=a.height?a.height:4,a.top&&(this.top=a.top),a.bottom&&(this.bottom=a.bottom),a.name?this.name=a.name:this.c?this.name=this.c:this.name=this.type,a.realWidth?this.realWidth=a.realWidth:this.realWidth=this.w,this.centerVertically=!1,this.type){case"debug":this.chordHeightAbove=this.height;break;case"lyric":a.position&&"below"===a.position?this.lyricHeightBelow=this.height:this.lyricHeightAbove=this.height;break;case"chord":a.position&&"below"===a.position?this.chordHeightBelow=this.height:this.chordHeightAbove=this.height;break;case"text":void 0===this.pitch?a.position&&"below"===a.position?this.chordHeightBelow=this.height:this.chordHeightAbove=this.height:this.centerVertically=!0;break;case"part":this.partHeightAbove=this.height}};t.prototype.getChordDim=function(){if("debug"===this.type)return null;if(!this.chordHeightAbove&&!this.chordHeightBelow)return null;var e="chord"===this.type?this.realWidth/2:0,t=this.x-e-0;return{left:t,right:t+this.realWidth+0}},t.prototype.invertLane=function(e){void 0===this.lane&&(this.lane=0),this.lane=e-this.lane-1},t.prototype.putChordInLane=function(e){this.lane=e,this.chordHeightAbove?this.chordHeightAbove=1.25*this.height*this.lane:this.chordHeightBelow=1.25*this.height*this.lane},t.prototype.getLane=function(){return void 0===this.lane?0:this.lane},t.prototype.setX=function(e){this.x=e+this.dx},e.exports=t},6994:function(e,t,r){var n=r(1716);e.exports=function(e,t,r,a,i,s,o,c){var l=c.calc("i",r,a);if(""===t)e.push({move:l.height});else{if("string"==typeof t)return void n(e,{marginLeft:s,text:t,font:r,klass:a,marginTop:o.marginTop,anchor:o.anchor,absElemType:o.absElemType,info:o.info,name:i},c);o.marginTop&&e.push({move:o.marginTop});var h=0,u={left:s,anchor:o.anchor,phrases:[]};a&&(u.klass=a),e.push(u);for(var d=0;d<t.length;d++){var f=t[d],p=f.font?f.font:c.attr(r,a).font,m={content:f.text};p&&(m.attrs={"font-family":c.getFamily(p.face),"font-size":p.size,"font-weight":p.weight,"font-style":p.style,"font-decoration":p.decoration}),u.phrases.push(m);var g=c.calc(f.text,p,a);h=Math.max(h,g.height)," "===f.text[f.text.length-1]&&l.width}e.push({move:h})}}},5588:function(e){e.exports=function(e,t,r){this.rows=[],e&&this.rows.push({move:e}),this.rows.push({separator:t,absElemType:"separator"}),r&&this.rows.push({move:r})}},7398:function(e,t,r){var n=r(3661),a=function(e){this.getTextSize=e,this.voices=[],this.staffs=[],this.brace=void 0,this.bracket=void 0};a.prototype.setLimit=function(e,t){t.specialY[e]&&(t.staff.specialY[e]?t.staff.specialY[e]=Math.max(t.staff.specialY[e],t.specialY[e]):t.staff.specialY[e]=t.specialY[e])},a.prototype.addVoice=function(e,t,r){var n=this.voices.length;this.voices[n]=e,this.staffs[t]?this.staffs[t].voices.push(n):this.staffs[this.staffs.length]={top:10,bottom:2,lines:r,voices:[n],specialY:{tempoHeightAbove:0,partHeightAbove:0,volumeHeightAbove:0,dynamicHeightAbove:0,endingHeightAbove:0,chordHeightAbove:0,lyricHeightAbove:0,lyricHeightBelow:0,chordHeightBelow:0,volumeHeightBelow:0,dynamicHeightBelow:0}},e.staff=this.staffs[t]},a.prototype.setHeight=function(){this.height=n(this)},a.prototype.setWidth=function(e){this.w=e;for(var t=0;t<this.voices.length;t++)this.voices[t].setWidth(e)},a.prototype.setStaffLimits=function(e){e.staff.top=Math.max(e.staff.top,e.top),e.staff.bottom=Math.min(e.staff.bottom,e.bottom),this.setLimit("tempoHeightAbove",e),this.setLimit("partHeightAbove",e),this.setLimit("volumeHeightAbove",e),this.setLimit("dynamicHeightAbove",e),this.setLimit("endingHeightAbove",e),this.setLimit("chordHeightAbove",e),this.setLimit("lyricHeightAbove",e),this.setLimit("lyricHeightBelow",e),this.setLimit("chordHeightBelow",e),this.setLimit("volumeHeightBelow",e),this.setLimit("dynamicHeightBelow",e)},e.exports=a},4726:function(e){e.exports=function(e,t,r,n,a,i){this.rows=[],e&&this.rows.push({move:e});var s=t.titleleft?"start":"middle",o=t.titleleft?a:n;this.rows.push({left:o,text:r.text,font:"subtitlefont",klass:"text subtitle",anchor:s,startChar:r.startChar,endChar:r.endChar,absElemType:"subtitle",name:"subtitle"});var c=i.calc(r.text,"subtitlefont","text subtitle");this.rows.push({move:c.height})}},1106:function(e,t,r){var n=r(1409),a=r(6658),i=function(e,t,r){this.type="TempoElement",this.tempo=e,this.tempo.type="tempo",this.tuneNumber=t,this.totalHeightInPitches=6,this.tempoHeightAbove=this.totalHeightInPitches,this.pitch=void 0,this.tempo.duration&&!this.tempo.suppressBpm&&(this.note=this.createNote(r,e,t))};i.prototype.setX=function(e){this.x=e},i.prototype.createNote=function(e,t,r){var i,s,o,c=t.duration[0],l=new n(t,c,1,"tempo",r);c<=1/32?(o="noteheads.quarter",s="flags.u32nd",i=0):c<=1/16?(o="noteheads.quarter",s="flags.u16th",i=0):c<=3/32?(o="noteheads.quarter",s="flags.u16nd",i=1):c<=1/8?(o="noteheads.quarter",s="flags.u8th",i=0):c<=3/16?(o="noteheads.quarter",s="flags.u8th",i=1):c<=1/4?(o="noteheads.quarter",i=0):c<=3/8?(o="noteheads.quarter",i=1):c<=.5?(o="noteheads.half",i=0):c<=3/4?(o="noteheads.half",i=1):c<=1?(o="noteheads.whole",i=0):c<=1.5?(o="noteheads.whole",i=1):c<=2?(o="noteheads.dbl",i=0):(o="noteheads.dbl",i=1);var h,u=e(l,o,{verticalPos:0},{dir:"up",flag:s,dot:i,scale:.75}).notehead;if(l.addHead(u),"noteheads.whole"!==o&&"noteheads.dbl"!==o){var d=u.dx+u.w;h=new a(null,d,0,.25,{type:"stem",pitch2:3.75,linewidth:-.6}),l.addRight(h)}return l},e.exports=i},6183:function(e){var t=function(e){this.type="TieElem",this.anchor1=e.anchor1,this.anchor2=e.anchor2,e.isGrace&&(this.isGrace=!0),e.fixedY&&(this.fixedY=!0),e.stemDir&&(this.stemDir=e.stemDir),void 0!==e.voiceNumber&&(this.voiceNumber=e.voiceNumber),void 0!==e.style&&(this.dotted=!0),this.internalNotes=[]};t.prototype.addInternalNote=function(e){this.internalNotes.push(e)},t.prototype.setEndAnchor=function(e){this.anchor2=e,this.anchor1?(this.top=Math.max(this.anchor1.pitch,this.anchor2.pitch)+4,this.bottom=Math.min(this.anchor1.pitch,this.anchor2.pitch)-4):(this.top=this.anchor2.pitch+4,this.bottom=this.anchor2.pitch-4)},t.prototype.setStartX=function(e){this.startLimitX=e},t.prototype.setEndX=function(e){this.endLimitX=e},t.prototype.setHint=function(){this.hint=!0},t.prototype.calcTieDirection=function(){if(this.isGrace)this.above=!1;else if(0===this.voiceNumber)this.above=!0;else if(this.voiceNumber>0)this.above=!1;else{var e;e=this.anchor1?this.anchor1.pitch:this.anchor2?this.anchor2.pitch:14,this.anchor1&&"down"===this.anchor1.stemDir&&this.anchor2&&"down"===this.anchor2.stemDir?this.above=!0:this.anchor1&&"up"===this.anchor1.stemDir&&this.anchor2&&"up"===this.anchor2.stemDir?this.above=!1:this.anchor1&&this.anchor2?this.above=e>=6:this.anchor1?this.above="down"===this.anchor1.stemDir:this.anchor2?this.above="down"===this.anchor2.stemDir:this.above=e>=6}},t.prototype.calcSlurDirection=function(){if(this.isGrace)this.above=!1;else if(0===this.voiceNumber)this.above=!0;else if(this.voiceNumber>0)this.above=!1;else{var e=!1;this.anchor1&&"down"===this.anchor1.stemDir&&(e=!0),this.anchor2&&"down"===this.anchor2.stemDir&&(e=!0);for(var t=0;t<this.internalNotes.length;t++)"down"===this.internalNotes[t].stemDir&&(e=!0);this.above=e}},t.prototype.calcX=function(e,t){this.anchor1?(this.startX=this.anchor1.x,this.anchor1.scalex<1&&(this.startX-=3)):this.startLimitX?this.startX=this.startLimitX.x+this.startLimitX.w:this.anchor2?this.startX=this.anchor2.x-20:this.startX=e,!this.anchor1&&this.dotted&&(this.startX-=3),this.anchor2?this.endX=this.anchor2.x:this.endLimitX?this.endX=this.endLimitX.x:this.endX=t},t.prototype.calcTieY=function(){this.anchor1?this.startY=this.anchor1.pitch:this.anchor2?this.startY=this.anchor2.pitch:this.startY=this.above?14:0,this.anchor2?this.endY=this.anchor2.pitch:this.anchor1?this.endY=this.anchor1.pitch:this.endY=this.above?14:0},t.prototype.calcSlurY=function(){if(this.anchor1&&this.anchor2){this.above&&"up"===this.anchor1.stemDir&&!this.fixedY?(this.startY=(this.anchor1.highestVert+this.anchor1.pitch)/2,this.startX+=this.anchor1.w/2):this.startY=this.anchor1.pitch;var e=this.anchor2.parent.beam&&this.anchor2.parent.beam.stemsUp&&this.anchor2.parent.beam.elems[0]!==this.anchor2.parent,t=(this.anchor2.highestVert+this.anchor2.pitch)/2;if(this.above&&"up"===this.anchor2.stemDir&&!this.fixedY&&!e&&t<this.startY?(this.endY=t,this.endX+=Math.round(this.anchor2.w/2)):this.endY=this.above&&e?this.anchor2.highestVert:this.anchor2.pitch,1===this.anchor1.scalex){var r=!!this.anchor1.parent.beam,n=!!this.anchor2.parent.beam;r&&(this.anchor1.parent===this.anchor1.parent.beam.elems[this.anchor1.parent.beam.elems.length-1]||(this.above?this.startY=this.anchor1.parent.fixed.t:this.startY=this.anchor1.parent.fixed.b)),n&&(this.anchor2.parent===this.anchor2.parent.beam.elems[0]||(this.above?this.endY=this.anchor2.parent.fixed.t:this.endY=this.anchor2.parent.fixed.b))}}else this.anchor1?this.startY=this.endY=this.anchor1.pitch:this.anchor2?this.startY=this.endY=this.anchor2.pitch:(this.startY=this.above?14:0,this.endY=this.above?14:0)},t.prototype.avoidCollisionAbove=function(){if(this.above){for(var e=-50,t=0;t<this.internalNotes.length;t++)this.internalNotes[t].highestVert>e&&(e=this.internalNotes[t].highestVert);e>this.startY&&e>this.endY&&(this.startY=this.endY=e-1)}},t.prototype.getYBounds=function(){var e,t;return this.isTie?(this.calcTieDirection(),this.calcX(10,1e3),this.calcTieY()):(this.calcSlurDirection(),this.calcX(10,1e3),this.calcSlurY()),this.above?e=(t=Math.min(this.startY,this.endY))+3:t=(e=Math.min(this.startY,this.endY))-3,[e,t]},e.exports=t},1134:function(e,t,r){var n=r(1716),a=r(6994);e.exports=function(e,t,r,i,s,o,c,l,h,u){if(this.rows=[],e.header&&o){var d=u.calc("X","headerfont","abcjs-header abcjs-meta-top").height;n(this.rows,{marginLeft:c,text:e.header.left,font:"headerfont",klass:"header meta-top",marginTop:-d,info:t.header,name:"header"},u),n(this.rows,{marginLeft:c+s/2,text:e.header.center,font:"headerfont",klass:"header meta-top",marginTop:-d,anchor:"middle",info:t.header,name:"header"},u),n(this.rows,{marginLeft:c+s,text:e.header.right,font:"headerfont",klass:"header meta-top",marginTop:-d,anchor:"end",info:t.header,name:"header"},u)}o&&this.rows.push({move:l.top});var f=r.titleleft?"start":"middle",p=r.titleleft?c:c+s/2;if(e.title){var m=h?"abcjs-title":"";a(this.rows,e.title,"titlefont",m,"title",p,{marginTop:l.title,anchor:f,absElemType:"title",info:t.title},u)}if(i.length)for(var g=0;g<i.length&&i[g].subtitle;)m=h?"abcjs-text abcjs-subtitle":"",a(this.rows,i[g].subtitle.text,"subtitlefont",m,"subtitle",p,{marginTop:l.subtitle,anchor:f,absElemType:"subtitle",info:i[g].subtitle},u),g++;if(e.rhythm||e.origin||e.composer){if(this.rows.push({move:l.composer}),e.rhythm&&e.rhythm.length>0){var v=!(!e.composer&&!e.origin);m=h?"abcjs-rhythm":"",n(this.rows,{marginLeft:c,text:e.rhythm,font:"infofont",klass:m,absElemType:"rhythm",noMove:v,info:t.rhythm,name:"rhythm"},u)}e.composer&&e.composer,e.origin&&e.origin;var b=e.composer?e.composer:"";e.origin&&("string"==typeof b&&"string"==typeof e.origin?b+=" ("+e.origin+")":"string"==typeof b&&"string"!=typeof e.origin?((b=[{text:b}]).push({text:" ("}),(b=b.concat(e.origin)).push({text:")"})):(b.push({text:" ("}),(b=b.concat(e.origin)).push({text:")"}))),b&&(m=h?"abcjs-composer":"",a(this.rows,b,"composerfont",m,"composer",c+s,{anchor:"end",absElemType:"composer",info:t.composer,ingroup:!0},u))}e.author&&e.author.length>0&&(m=h?"abcjs-author":"",a(this.rows,e.author,"composerfont",m,"author",c+s,{anchor:"end",absElemType:"author",info:t.author},u)),e.partOrder&&e.partOrder.length>0&&(m=h?"abcjs-part-order":"",a(this.rows,e.partOrder,"partsfont",m,"part-order",c,{absElemType:"partOrder",info:t.partOrder,anchor:"start"},u))}},2096:function(e){var t=function(e,t,r){this.type="TripletElem",this.anchor1=t,this.number=e,this.durationClass=("d"+Math.round(1e3*t.parent.durationClass)/1e3).replace(/\./,"-"),this.middleElems=[],this.flatBeams=r.flatBeams};t.prototype.isClosed=function(){return!!this.anchor2},t.prototype.middleNote=function(e){this.middleElems.push(e)},t.prototype.setCloseAnchor=function(e){this.anchor2=e,this.anchor1.parent.beam&&"up"!==this.anchor1.stemDir||(this.endingHeightAbove=4)},e.exports=t},3197:function(e){var t=function(e,t){this.children=[],this.beams=[],this.otherchildren=[],this.w=0,this.duplicate=!1,this.voicenumber=e,this.voicetotal=t,this.bottom=7,this.top=7,this.specialY={tempoHeightAbove:0,partHeightAbove:0,volumeHeightAbove:0,dynamicHeightAbove:0,endingHeightAbove:0,chordHeightAbove:0,lyricHeightAbove:0,lyricHeightBelow:0,chordHeightBelow:0,volumeHeightBelow:0,dynamicHeightBelow:0}};t.prototype.addChild=function(e){if("bar"===e.type){for(var t=!0,r=0;t&&r<this.children.length;r++)this.children[r].type.indexOf("staff-extra")<0&&"tempo"!==this.children[r].type&&(t=!1);t||(this.beams.push("bar"),this.otherchildren.push("bar"))}this.children[this.children.length]=e,this.setRange(e)},t.prototype.setLimit=function(e,t){var r=t.specialY;r||(r=t),r[e]&&(this.specialY[e]?this.specialY[e]=Math.max(this.specialY[e],r[e]):this.specialY[e]=r[e])},t.prototype.adjustRange=function(e){void 0!==e.bottom&&(this.bottom=Math.min(this.bottom,e.bottom)),void 0!==e.top&&(this.top=Math.max(this.top,e.top))},t.prototype.setRange=function(e){this.adjustRange(e),this.setLimit("tempoHeightAbove",e),this.setLimit("partHeightAbove",e),this.setLimit("volumeHeightAbove",e),this.setLimit("dynamicHeightAbove",e),this.setLimit("endingHeightAbove",e),this.setLimit("chordHeightAbove",e),this.setLimit("lyricHeightAbove",e),this.setLimit("lyricHeightBelow",e),this.setLimit("chordHeightBelow",e),this.setLimit("volumeHeightBelow",e),this.setLimit("dynamicHeightBelow",e)},t.prototype.addOther=function(e){this.otherchildren.push(e),this.setRange(e)},t.prototype.addBeam=function(e){this.beams.push(e)},t.prototype.setWidth=function(e){this.w=e},e.exports=t},6020:function(e,t,r){var n=r(4331),a={0:{d:[["M",4.83,-14.97],["c",.33,-.03,1.11,0,1.47,.06],["c",1.68,.36,2.97,1.59,3.78,3.6],["c",1.2,2.97,.81,6.96,-.9,9.27],["c",-.78,1.08,-1.71,1.71,-2.91,1.95],["c",-.45,.09,-1.32,.09,-1.77,0],["c",-.81,-.18,-1.47,-.51,-2.07,-1.02],["c",-2.34,-2.07,-3.15,-6.72,-1.74,-10.2],["c",.87,-2.16,2.28,-3.42,4.14,-3.66],["z"],["m",1.11,.87],["c",-.21,-.06,-.69,-.09,-.87,-.06],["c",-.54,.12,-.87,.42,-1.17,.99],["c",-.36,.66,-.51,1.56,-.6,3],["c",-.03,.75,-.03,4.59,0,5.31],["c",.09,1.5,.27,2.4,.6,3.06],["c",.24,.48,.57,.78,.96,.9],["c",.27,.09,.78,.09,1.05,0],["c",.39,-.12,.72,-.42,.96,-.9],["c",.33,-.66,.51,-1.56,.6,-3.06],["c",.03,-.72,.03,-4.56,0,-5.31],["c",-.09,-1.47,-.27,-2.37,-.6,-3.03],["c",-.24,-.48,-.54,-.78,-.93,-.9],["z"]],w:10.78,h:14.959},1:{d:[["M",3.3,-15.06],["c",.06,-.06,.21,-.03,.66,.15],["c",.81,.39,1.08,.39,1.83,.03],["c",.21,-.09,.39,-.15,.42,-.15],["c",.12,0,.21,.09,.27,.21],["c",.06,.12,.06,.33,.06,5.94],["c",0,3.93,0,5.85,.03,6.03],["c",.06,.36,.15,.69,.27,.96],["c",.36,.75,.93,1.17,1.68,1.26],["c",.3,.03,.39,.09,.39,.3],["c",0,.15,-.03,.18,-.09,.24],["c",-.06,.06,-.09,.06,-.48,.06],["c",-.42,0,-.69,-.03,-2.1,-.24],["c",-.9,-.15,-1.77,-.15,-2.67,0],["c",-1.41,.21,-1.68,.24,-2.1,.24],["c",-.39,0,-.42,0,-.48,-.06],["c",-.06,-.06,-.06,-.09,-.06,-.24],["c",0,-.21,.06,-.27,.36,-.3],["c",.75,-.09,1.32,-.51,1.68,-1.26],["c",.12,-.27,.21,-.6,.27,-.96],["c",.03,-.18,.03,-1.59,.03,-4.29],["c",0,-3.87,0,-4.05,-.06,-4.14],["c",-.09,-.15,-.18,-.24,-.39,-.24],["c",-.12,0,-.15,.03,-.21,.06],["c",-.03,.06,-.45,.99,-.96,2.13],["c",-.48,1.14,-.9,2.1,-.93,2.16],["c",-.06,.15,-.21,.24,-.33,.24],["c",-.24,0,-.42,-.18,-.42,-.39],["c",0,-.06,3.27,-7.62,3.33,-7.74],["z"]],w:8.94,h:15.058},2:{d:[["M",4.23,-14.97],["c",.57,-.06,1.68,0,2.34,.18],["c",.69,.18,1.5,.54,2.01,.9],["c",1.35,.96,1.95,2.25,1.77,3.81],["c",-.15,1.35,-.66,2.34,-1.68,3.15],["c",-.6,.48,-1.44,.93,-3.12,1.65],["c",-1.32,.57,-1.8,.81,-2.37,1.14],["c",-.57,.33,-.57,.33,-.24,.27],["c",.39,-.09,1.26,-.09,1.68,0],["c",.72,.15,1.41,.45,2.1,.9],["c",.99,.63,1.86,.87,2.55,.75],["c",.24,-.06,.42,-.15,.57,-.3],["c",.12,-.09,.3,-.42,.3,-.51],["c",0,-.09,.12,-.21,.24,-.24],["c",.18,-.03,.39,.12,.39,.3],["c",0,.12,-.15,.57,-.3,.87],["c",-.54,1.02,-1.56,1.74,-2.79,2.01],["c",-.42,.09,-1.23,.09,-1.62,.03],["c",-.81,-.18,-1.32,-.45,-2.01,-1.11],["c",-.45,-.45,-.63,-.57,-.96,-.69],["c",-.84,-.27,-1.89,.12,-2.25,.9],["c",-.12,.21,-.21,.54,-.21,.72],["c",0,.12,-.12,.21,-.27,.24],["c",-.15,0,-.27,-.03,-.33,-.15],["c",-.09,-.21,.09,-1.08,.33,-1.71],["c",.24,-.66,.66,-1.26,1.29,-1.89],["c",.45,-.45,.9,-.81,1.92,-1.56],["c",1.29,-.93,1.89,-1.44,2.34,-1.98],["c",.87,-1.05,1.26,-2.19,1.2,-3.63],["c",-.06,-1.29,-.39,-2.31,-.96,-2.91],["c",-.36,-.33,-.72,-.51,-1.17,-.54],["c",-.84,-.03,-1.53,.42,-1.59,1.05],["c",-.03,.33,.12,.6,.57,1.14],["c",.45,.54,.54,.87,.42,1.41],["c",-.15,.63,-.54,1.11,-1.08,1.38],["c",-.63,.33,-1.2,.33,-1.83,0],["c",-.24,-.12,-.33,-.18,-.54,-.39],["c",-.18,-.18,-.27,-.3,-.36,-.51],["c",-.24,-.45,-.27,-.84,-.21,-1.38],["c",.12,-.75,.45,-1.41,1.02,-1.98],["c",.72,-.72,1.74,-1.17,2.85,-1.32],["z"]],w:10.764,h:14.97},3:{d:[["M",3.78,-14.97],["c",.3,-.03,1.41,0,1.83,.06],["c",2.22,.3,3.51,1.32,3.72,2.91],["c",.03,.33,.03,1.26,-.03,1.65],["c",-.12,.84,-.48,1.47,-1.05,1.77],["c",-.27,.15,-.36,.24,-.45,.39],["c",-.09,.21,-.09,.36,0,.57],["c",.09,.15,.18,.24,.51,.39],["c",.75,.42,1.23,1.14,1.41,2.13],["c",.06,.42,.06,1.35,0,1.71],["c",-.18,.81,-.48,1.38,-1.02,1.95],["c",-.75,.72,-1.8,1.2,-3.18,1.38],["c",-.42,.06,-1.56,.06,-1.95,0],["c",-1.89,-.33,-3.18,-1.29,-3.51,-2.64],["c",-.03,-.12,-.03,-.33,-.03,-.6],["c",0,-.36,0,-.42,.06,-.63],["c",.12,-.3,.27,-.51,.51,-.75],["c",.24,-.24,.45,-.39,.75,-.51],["c",.21,-.06,.27,-.06,.6,-.06],["c",.33,0,.39,0,.6,.06],["c",.3,.12,.51,.27,.75,.51],["c",.36,.33,.57,.75,.6,1.2],["c",0,.21,0,.27,-.06,.42],["c",-.09,.18,-.12,.24,-.54,.54],["c",-.51,.36,-.63,.54,-.6,.87],["c",.06,.54,.54,.9,1.38,.99],["c",.36,.06,.72,.03,.96,-.06],["c",.81,-.27,1.29,-1.23,1.44,-2.79],["c",.03,-.45,.03,-1.95,-.03,-2.37],["c",-.09,-.75,-.33,-1.23,-.75,-1.44],["c",-.33,-.18,-.45,-.18,-1.98,-.18],["c",-1.35,0,-1.41,0,-1.5,-.06],["c",-.18,-.12,-.24,-.39,-.12,-.6],["c",.12,-.15,.15,-.15,1.68,-.15],["c",1.5,0,1.62,0,1.89,-.15],["c",.18,-.09,.42,-.36,.54,-.57],["c",.18,-.42,.27,-.9,.3,-1.95],["c",.03,-1.2,-.06,-1.8,-.36,-2.37],["c",-.24,-.48,-.63,-.81,-1.14,-.96],["c",-.3,-.06,-1.08,-.06,-1.38,.03],["c",-.6,.15,-.9,.42,-.96,.84],["c",-.03,.3,.06,.45,.63,.84],["c",.33,.24,.42,.39,.45,.63],["c",.03,.72,-.57,1.5,-1.32,1.65],["c",-1.05,.27,-2.1,-.57,-2.1,-1.65],["c",0,-.45,.15,-.96,.39,-1.38],["c",.12,-.21,.54,-.63,.81,-.81],["c",.57,-.42,1.38,-.69,2.25,-.81],["z"]],w:9.735,h:14.967},4:{d:[["M",8.64,-14.94],["c",.27,-.09,.42,-.12,.54,-.03],["c",.09,.06,.15,.21,.15,.3],["c",-.03,.06,-1.92,2.31,-4.23,5.04],["c",-2.31,2.73,-4.23,4.98,-4.26,5.01],["c",-.03,.06,.12,.06,2.55,.06],["l",2.61,0],["l",0,-2.37],["c",0,-2.19,.03,-2.37,.06,-2.46],["c",.03,-.06,.21,-.18,.57,-.42],["c",1.08,-.72,1.38,-1.08,1.86,-2.16],["c",.12,-.3,.24,-.54,.27,-.57],["c",.12,-.12,.39,-.06,.45,.12],["c",.06,.09,.06,.57,.06,3.96],["l",0,3.9],["l",1.08,0],["c",1.05,0,1.11,0,1.2,.06],["c",.24,.15,.24,.54,0,.69],["c",-.09,.06,-.15,.06,-1.2,.06],["l",-1.08,0],["l",0,.33],["c",0,.57,.09,1.11,.3,1.53],["c",.36,.75,.93,1.17,1.68,1.26],["c",.3,.03,.39,.09,.39,.3],["c",0,.15,-.03,.18,-.09,.24],["c",-.06,.06,-.09,.06,-.48,.06],["c",-.42,0,-.69,-.03,-2.1,-.24],["c",-.9,-.15,-1.77,-.15,-2.67,0],["c",-1.41,.21,-1.68,.24,-2.1,.24],["c",-.39,0,-.42,0,-.48,-.06],["c",-.06,-.06,-.06,-.09,-.06,-.24],["c",0,-.21,.06,-.27,.36,-.3],["c",.75,-.09,1.32,-.51,1.68,-1.26],["c",.21,-.42,.3,-.96,.3,-1.53],["l",0,-.33],["l",-2.7,0],["c",-2.91,0,-2.85,0,-3.09,-.15],["c",-.18,-.12,-.3,-.39,-.27,-.54],["c",.03,-.06,.18,-.24,.33,-.45],["c",.75,-.9,1.59,-2.07,2.13,-3.03],["c",.33,-.54,.84,-1.62,1.05,-2.16],["c",.57,-1.41,.84,-2.64,.9,-4.05],["c",.03,-.63,.06,-.72,.24,-.81],["l",.12,-.06],["l",.45,.12],["c",.66,.18,1.02,.24,1.47,.27],["c",.6,.03,1.23,-.09,2.01,-.33],["z"]],w:11.795,h:14.994},5:{d:[["M",1.02,-14.94],["c",.12,-.09,.03,-.09,1.08,.06],["c",2.49,.36,4.35,.36,6.96,-.06],["c",.57,-.09,.66,-.06,.81,.06],["c",.15,.18,.12,.24,-.15,.51],["c",-1.29,1.26,-3.24,2.04,-5.58,2.31],["c",-.6,.09,-1.2,.12,-1.71,.12],["c",-.39,0,-.45,0,-.57,.06],["c",-.09,.06,-.15,.12,-.21,.21],["l",-.06,.12],["l",0,1.65],["l",0,1.65],["l",.21,-.21],["c",.66,-.57,1.41,-.96,2.19,-1.14],["c",.33,-.06,1.41,-.06,1.95,0],["c",2.61,.36,4.02,1.74,4.26,4.14],["c",.03,.45,.03,1.08,-.03,1.44],["c",-.18,1.02,-.78,2.01,-1.59,2.7],["c",-.72,.57,-1.62,1.02,-2.49,1.2],["c",-1.38,.27,-3.03,.06,-4.2,-.54],["c",-1.08,-.54,-1.71,-1.32,-1.86,-2.28],["c",-.09,-.69,.09,-1.29,.57,-1.74],["c",.24,-.24,.45,-.39,.75,-.51],["c",.21,-.06,.27,-.06,.6,-.06],["c",.33,0,.39,0,.6,.06],["c",.3,.12,.51,.27,.75,.51],["c",.36,.33,.57,.75,.6,1.2],["c",0,.21,0,.27,-.06,.42],["c",-.09,.18,-.12,.24,-.54,.54],["c",-.18,.12,-.36,.3,-.42,.33],["c",-.36,.42,-.18,.99,.36,1.26],["c",.51,.27,1.47,.36,2.01,.27],["c",.93,-.21,1.47,-1.17,1.65,-2.91],["c",.06,-.45,.06,-1.89,0,-2.31],["c",-.15,-1.2,-.51,-2.1,-1.05,-2.55],["c",-.21,-.18,-.54,-.36,-.81,-.39],["c",-.3,-.06,-.84,-.03,-1.26,.06],["c",-.93,.18,-1.65,.6,-2.16,1.2],["c",-.15,.21,-.27,.3,-.39,.3],["c",-.15,0,-.3,-.09,-.36,-.18],["c",-.06,-.09,-.06,-.15,-.06,-3.66],["c",0,-3.39,0,-3.57,.06,-3.66],["c",.03,-.06,.09,-.15,.15,-.18],["z"]],w:10.212,h:14.997},6:{d:[["M",4.98,-14.97],["c",.36,-.03,1.2,0,1.59,.06],["c",.9,.15,1.68,.51,2.25,1.05],["c",.57,.51,.87,1.23,.84,1.98],["c",-.03,.51,-.21,.9,-.6,1.26],["c",-.24,.24,-.45,.39,-.75,.51],["c",-.21,.06,-.27,.06,-.6,.06],["c",-.33,0,-.39,0,-.6,-.06],["c",-.3,-.12,-.51,-.27,-.75,-.51],["c",-.39,-.36,-.57,-.78,-.57,-1.26],["c",0,-.27,0,-.3,.09,-.42],["c",.03,-.09,.18,-.21,.3,-.3],["c",.12,-.09,.3,-.21,.39,-.27],["c",.09,-.06,.21,-.18,.27,-.24],["c",.06,-.12,.09,-.15,.09,-.33],["c",0,-.18,-.03,-.24,-.09,-.36],["c",-.24,-.39,-.75,-.6,-1.38,-.57],["c",-.54,.03,-.9,.18,-1.23,.48],["c",-.81,.72,-1.08,2.16,-.96,5.37],["l",0,.63],["l",.3,-.12],["c",.78,-.27,1.29,-.33,2.1,-.27],["c",1.47,.12,2.49,.54,3.27,1.29],["c",.48,.51,.81,1.11,.96,1.89],["c",.06,.27,.06,.42,.06,.93],["c",0,.54,0,.69,-.06,.96],["c",-.15,.78,-.48,1.38,-.96,1.89],["c",-.54,.51,-1.17,.87,-1.98,1.08],["c",-1.14,.3,-2.4,.33,-3.24,.03],["c",-1.5,-.48,-2.64,-1.89,-3.27,-4.02],["c",-.36,-1.23,-.51,-2.82,-.42,-4.08],["c",.3,-3.66,2.28,-6.3,4.95,-6.66],["z"],["m",.66,7.41],["c",-.27,-.09,-.81,-.12,-1.08,-.06],["c",-.72,.18,-1.08,.69,-1.23,1.71],["c",-.06,.54,-.06,3,0,3.54],["c",.18,1.26,.72,1.77,1.8,1.74],["c",.39,-.03,.63,-.09,.9,-.27],["c",.66,-.42,.9,-1.32,.9,-3.24],["c",0,-2.22,-.36,-3.12,-1.29,-3.42],["z"]],w:9.956,h:14.982},7:{d:[["M",.21,-14.97],["c",.21,-.06,.45,0,.54,.15],["c",.06,.09,.06,.15,.06,.39],["c",0,.24,0,.33,.06,.42],["c",.06,.12,.21,.24,.27,.24],["c",.03,0,.12,-.12,.24,-.21],["c",.96,-1.2,2.58,-1.35,3.99,-.42],["c",.15,.12,.42,.3,.54,.45],["c",.48,.39,.81,.57,1.29,.6],["c",.69,.03,1.5,-.3,2.13,-.87],["c",.09,-.09,.27,-.3,.39,-.45],["c",.12,-.15,.24,-.27,.3,-.3],["c",.18,-.06,.39,.03,.51,.21],["c",.06,.18,.06,.24,-.27,.72],["c",-.18,.24,-.54,.78,-.78,1.17],["c",-2.37,3.54,-3.54,6.27,-3.87,9],["c",-.03,.33,-.03,.66,-.03,1.26],["c",0,.9,0,1.08,.15,1.89],["c",.06,.45,.06,.48,.03,.6],["c",-.06,.09,-.21,.21,-.3,.21],["c",-.03,0,-.27,-.06,-.54,-.15],["c",-.84,-.27,-1.11,-.3,-1.65,-.3],["c",-.57,0,-.84,.03,-1.56,.27],["c",-.6,.18,-.69,.21,-.81,.15],["c",-.12,-.06,-.21,-.18,-.21,-.3],["c",0,-.15,.6,-1.44,1.2,-2.61],["c",1.14,-2.22,2.73,-4.68,5.1,-8.01],["c",.21,-.27,.36,-.48,.33,-.48],["c",0,0,-.12,.06,-.27,.12],["c",-.54,.3,-.99,.39,-1.56,.39],["c",-.75,.03,-1.2,-.18,-1.83,-.75],["c",-.99,-.9,-1.83,-1.17,-2.31,-.72],["c",-.18,.15,-.36,.51,-.45,.84],["c",-.06,.24,-.06,.33,-.09,1.98],["c",0,1.62,-.03,1.74,-.06,1.8],["c",-.15,.24,-.54,.24,-.69,0],["c",-.06,-.09,-.06,-.15,-.06,-3.57],["c",0,-3.42,0,-3.48,.06,-3.57],["c",.03,-.06,.09,-.12,.15,-.15],["z"]],w:10.561,h:15.093},8:{d:[["M",4.98,-14.97],["c",.33,-.03,1.02,-.03,1.32,0],["c",1.32,.12,2.49,.6,3.21,1.32],["c",.39,.39,.66,.81,.78,1.29],["c",.09,.36,.09,1.08,0,1.44],["c",-.21,.84,-.66,1.59,-1.59,2.55],["l",-.3,.3],["l",.27,.18],["c",1.47,.93,2.31,2.31,2.25,3.75],["c",-.03,.75,-.24,1.35,-.63,1.95],["c",-.45,.66,-1.02,1.14,-1.83,1.53],["c",-1.8,.87,-4.2,.87,-6,.03],["c",-1.62,-.78,-2.52,-2.16,-2.46,-3.66],["c",.06,-.99,.54,-1.77,1.8,-2.97],["c",.54,-.51,.54,-.54,.48,-.57],["c",-.39,-.27,-.96,-.78,-1.2,-1.14],["c",-.75,-1.11,-.87,-2.4,-.3,-3.6],["c",.69,-1.35,2.25,-2.25,4.2,-2.4],["z"],["m",1.53,.69],["c",-.42,-.09,-1.11,-.12,-1.38,-.06],["c",-.3,.06,-.6,.18,-.81,.3],["c",-.21,.12,-.6,.51,-.72,.72],["c",-.51,.87,-.42,1.89,.21,2.52],["c",.21,.21,.36,.3,1.95,1.23],["c",.96,.54,1.74,.99,1.77,1.02],["c",.09,0,.63,-.6,.99,-1.11],["c",.21,-.36,.48,-.87,.57,-1.23],["c",.06,-.24,.06,-.36,.06,-.72],["c",0,-.45,-.03,-.66,-.15,-.99],["c",-.39,-.81,-1.29,-1.44,-2.49,-1.68],["z"],["m",-1.44,8.07],["l",-1.89,-1.08],["c",-.03,0,-.18,.15,-.39,.33],["c",-1.2,1.08,-1.65,1.95,-1.59,3],["c",.09,1.59,1.35,2.85,3.21,3.24],["c",.33,.06,.45,.06,.93,.06],["c",.63,0,.81,-.03,1.29,-.27],["c",.9,-.42,1.47,-1.41,1.41,-2.4],["c",-.06,-.66,-.39,-1.29,-.9,-1.65],["c",-.12,-.09,-1.05,-.63,-2.07,-1.23],["z"]],w:10.926,h:14.989},9:{d:[["M",4.23,-14.97],["c",.42,-.03,1.29,0,1.62,.06],["c",.51,.12,.93,.3,1.38,.57],["c",1.53,1.02,2.52,3.24,2.73,5.94],["c",.18,2.55,-.48,4.98,-1.83,6.57],["c",-1.05,1.26,-2.4,1.89,-3.93,1.83],["c",-1.23,-.06,-2.31,-.45,-3.03,-1.14],["c",-.57,-.51,-.87,-1.23,-.84,-1.98],["c",.03,-.51,.21,-.9,.6,-1.26],["c",.24,-.24,.45,-.39,.75,-.51],["c",.21,-.06,.27,-.06,.6,-.06],["c",.33,0,.39,0,.6,.06],["c",.3,.12,.51,.27,.75,.51],["c",.39,.36,.57,.78,.57,1.26],["c",0,.27,0,.3,-.09,.42],["c",-.03,.09,-.18,.21,-.3,.3],["c",-.12,.09,-.3,.21,-.39,.27],["c",-.09,.06,-.21,.18,-.27,.24],["c",-.06,.12,-.06,.15,-.06,.33],["c",0,.18,0,.24,.06,.36],["c",.24,.39,.75,.6,1.38,.57],["c",.54,-.03,.9,-.18,1.23,-.48],["c",.81,-.72,1.08,-2.16,.96,-5.37],["l",0,-.63],["l",-.3,.12],["c",-.78,.27,-1.29,.33,-2.1,.27],["c",-1.47,-.12,-2.49,-.54,-3.27,-1.29],["c",-.48,-.51,-.81,-1.11,-.96,-1.89],["c",-.06,-.27,-.06,-.42,-.06,-.96],["c",0,-.51,0,-.66,.06,-.93],["c",.15,-.78,.48,-1.38,.96,-1.89],["c",.15,-.12,.33,-.27,.42,-.36],["c",.69,-.51,1.62,-.81,2.76,-.93],["z"],["m",1.17,.66],["c",-.21,-.06,-.57,-.06,-.81,-.03],["c",-.78,.12,-1.26,.69,-1.41,1.74],["c",-.12,.63,-.15,1.95,-.09,2.79],["c",.12,1.71,.63,2.4,1.77,2.46],["c",1.08,.03,1.62,-.48,1.8,-1.74],["c",.06,-.54,.06,-3,0,-3.54],["c",-.15,-1.05,-.51,-1.53,-1.26,-1.68],["z"]],w:9.959,h:14.986},"rests.multimeasure":{d:[["M",0,-4],["l",0,16],["l",1,0],["l",0,-5],["l",40,0],["l",0,5],["l",1,0],["l",0,-16],["l",-1,0],["l",0,5],["l",-40,0],["l",0,-5],["z"]],w:42,h:18},"rests.whole":{d:[["M",.06,.03],["l",.09,-.06],["l",5.46,0],["l",5.49,0],["l",.09,.06],["l",.06,.09],["l",0,2.19],["l",0,2.19],["l",-.06,.09],["l",-.09,.06],["l",-5.49,0],["l",-5.46,0],["l",-.09,-.06],["l",-.06,-.09],["l",0,-2.19],["l",0,-2.19],["z"]],w:11.25,h:4.68},"rests.half":{d:[["M",.06,-4.62],["l",.09,-.06],["l",5.46,0],["l",5.49,0],["l",.09,.06],["l",.06,.09],["l",0,2.19],["l",0,2.19],["l",-.06,.09],["l",-.09,.06],["l",-5.49,0],["l",-5.46,0],["l",-.09,-.06],["l",-.06,-.09],["l",0,-2.19],["l",0,-2.19],["z"]],w:11.25,h:4.68},"rests.quarter":{d:[["M",1.89,-11.82],["c",.12,-.06,.24,-.06,.36,-.03],["c",.09,.06,4.74,5.58,4.86,5.82],["c",.21,.39,.15,.78,-.15,1.26],["c",-.24,.33,-.72,.81,-1.62,1.56],["c",-.45,.36,-.87,.75,-.96,.84],["c",-.93,.99,-1.14,2.49,-.6,3.63],["c",.18,.39,.27,.48,1.32,1.68],["c",1.92,2.25,1.83,2.16,1.83,2.34],["c",0,.18,-.18,.36,-.36,.39],["c",-.15,0,-.27,-.06,-.48,-.27],["c",-.75,-.75,-2.46,-1.29,-3.39,-1.08],["c",-.45,.09,-.69,.27,-.9,.69],["c",-.12,.3,-.21,.66,-.24,1.14],["c",-.03,.66,.09,1.35,.3,2.01],["c",.15,.42,.24,.66,.45,.96],["c",.18,.24,.18,.33,.03,.42],["c",-.12,.06,-.18,.03,-.45,-.3],["c",-1.08,-1.38,-2.07,-3.36,-2.4,-4.83],["c",-.27,-1.05,-.15,-1.77,.27,-2.07],["c",.21,-.12,.42,-.15,.87,-.15],["c",.87,.06,2.1,.39,3.3,.9],["l",.39,.18],["l",-1.65,-1.95],["c",-2.52,-2.97,-2.61,-3.09,-2.7,-3.27],["c",-.09,-.24,-.12,-.48,-.03,-.75],["c",.15,-.48,.57,-.96,1.83,-2.01],["c",.45,-.36,.84,-.72,.93,-.78],["c",.69,-.75,1.02,-1.8,.9,-2.79],["c",-.06,-.33,-.21,-.84,-.39,-1.11],["c",-.09,-.15,-.45,-.6,-.81,-1.05],["c",-.36,-.42,-.69,-.81,-.72,-.87],["c",-.09,-.18,0,-.42,.21,-.51],["z"]],w:7.888,h:21.435},"rests.8th":{d:[["M",1.68,-6.12],["c",.66,-.09,1.23,.09,1.68,.51],["c",.27,.3,.39,.54,.57,1.26],["c",.09,.33,.18,.66,.21,.72],["c",.12,.27,.33,.45,.6,.48],["c",.12,0,.18,0,.33,-.09],["c",.39,-.18,1.32,-1.29,1.68,-1.98],["c",.09,-.21,.24,-.3,.39,-.3],["c",.12,0,.27,.09,.33,.18],["c",.03,.06,-.27,1.11,-1.86,6.42],["c",-1.02,3.48,-1.89,6.39,-1.92,6.42],["c",0,.03,-.12,.12,-.24,.15],["c",-.18,.09,-.21,.09,-.45,.09],["c",-.24,0,-.3,0,-.48,-.06],["c",-.09,-.06,-.21,-.12,-.21,-.15],["c",-.06,-.03,.15,-.57,1.68,-4.92],["c",.96,-2.67,1.74,-4.89,1.71,-4.89],["l",-.51,.15],["c",-1.08,.36,-1.74,.48,-2.55,.48],["c",-.66,0,-.84,-.03,-1.32,-.27],["c",-1.32,-.63,-1.77,-2.16,-1.02,-3.3],["c",.33,-.45,.84,-.81,1.38,-.9],["z"]],w:7.534,h:13.883},"rests.16th":{d:[["M",3.33,-6.12],["c",.66,-.09,1.23,.09,1.68,.51],["c",.27,.3,.39,.54,.57,1.26],["c",.09,.33,.18,.66,.21,.72],["c",.15,.39,.57,.57,.87,.42],["c",.39,-.18,1.2,-1.23,1.62,-2.07],["c",.06,-.15,.24,-.24,.36,-.24],["c",.12,0,.27,.09,.33,.18],["c",.03,.06,-.45,1.86,-2.67,10.17],["c",-1.5,5.55,-2.73,10.14,-2.76,10.17],["c",-.03,.03,-.12,.12,-.24,.15],["c",-.18,.09,-.21,.09,-.45,.09],["c",-.24,0,-.3,0,-.48,-.06],["c",-.09,-.06,-.21,-.12,-.21,-.15],["c",-.06,-.03,.12,-.57,1.44,-4.92],["c",.81,-2.67,1.47,-4.86,1.47,-4.89],["c",-.03,0,-.27,.06,-.54,.15],["c",-1.08,.36,-1.77,.48,-2.58,.48],["c",-.66,0,-.84,-.03,-1.32,-.27],["c",-1.32,-.63,-1.77,-2.16,-1.02,-3.3],["c",.72,-1.05,2.22,-1.23,3.06,-.42],["c",.3,.33,.42,.6,.6,1.38],["c",.09,.45,.21,.78,.33,.9],["c",.09,.09,.27,.18,.45,.21],["c",.12,0,.18,0,.33,-.09],["c",.33,-.15,1.02,-.93,1.41,-1.59],["c",.12,-.21,.18,-.39,.39,-1.08],["c",.66,-2.1,1.17,-3.84,1.17,-3.87],["c",0,0,-.21,.06,-.42,.15],["c",-.51,.15,-1.2,.33,-1.68,.42],["c",-.33,.06,-.51,.06,-.96,.06],["c",-.66,0,-.84,-.03,-1.32,-.27],["c",-1.32,-.63,-1.77,-2.16,-1.02,-3.3],["c",.33,-.45,.84,-.81,1.38,-.9],["z"]],w:9.724,h:21.383},"rests.32nd":{d:[["M",4.23,-13.62],["c",.66,-.09,1.23,.09,1.68,.51],["c",.27,.3,.39,.54,.57,1.26],["c",.09,.33,.18,.66,.21,.72],["c",.12,.27,.33,.45,.6,.48],["c",.12,0,.18,0,.27,-.06],["c",.33,-.21,.99,-1.11,1.44,-1.98],["c",.09,-.24,.21,-.33,.39,-.33],["c",.12,0,.27,.09,.33,.18],["c",.03,.06,-.57,2.67,-3.21,13.89],["c",-1.8,7.62,-3.3,13.89,-3.3,13.92],["c",-.03,.06,-.12,.12,-.24,.18],["c",-.21,.09,-.24,.09,-.48,.09],["c",-.24,0,-.3,0,-.48,-.06],["c",-.09,-.06,-.21,-.12,-.21,-.15],["c",-.06,-.03,.09,-.57,1.23,-4.92],["c",.69,-2.67,1.26,-4.86,1.29,-4.89],["c",0,-.03,-.12,-.03,-.48,.12],["c",-1.17,.39,-2.22,.57,-3,.54],["c",-.42,-.03,-.75,-.12,-1.11,-.3],["c",-1.32,-.63,-1.77,-2.16,-1.02,-3.3],["c",.72,-1.05,2.22,-1.23,3.06,-.42],["c",.3,.33,.42,.6,.6,1.38],["c",.09,.45,.21,.78,.33,.9],["c",.12,.09,.3,.18,.48,.21],["c",.12,0,.18,0,.3,-.09],["c",.42,-.21,1.29,-1.29,1.56,-1.89],["c",.03,-.12,1.23,-4.59,1.23,-4.65],["c",0,-.03,-.18,.03,-.39,.12],["c",-.63,.18,-1.2,.36,-1.74,.45],["c",-.39,.06,-.54,.06,-1.02,.06],["c",-.66,0,-.84,-.03,-1.32,-.27],["c",-1.32,-.63,-1.77,-2.16,-1.02,-3.3],["c",.72,-1.05,2.22,-1.23,3.06,-.42],["c",.3,.33,.42,.6,.6,1.38],["c",.09,.45,.21,.78,.33,.9],["c",.18,.18,.51,.27,.72,.15],["c",.3,-.12,.69,-.57,1.08,-1.17],["c",.42,-.6,.39,-.51,1.05,-3.03],["c",.33,-1.26,.6,-2.31,.6,-2.34],["c",0,0,-.21,.03,-.45,.12],["c",-.57,.18,-1.14,.33,-1.62,.42],["c",-.33,.06,-.51,.06,-.96,.06],["c",-.66,0,-.84,-.03,-1.32,-.27],["c",-1.32,-.63,-1.77,-2.16,-1.02,-3.3],["c",.33,-.45,.84,-.81,1.38,-.9],["z"]],w:11.373,h:28.883},"rests.64th":{d:[["M",5.13,-13.62],["c",.66,-.09,1.23,.09,1.68,.51],["c",.27,.3,.39,.54,.57,1.26],["c",.15,.63,.21,.81,.33,.96],["c",.18,.21,.54,.3,.75,.18],["c",.24,-.12,.63,-.66,1.08,-1.56],["c",.33,-.66,.39,-.72,.6,-.72],["c",.12,0,.27,.09,.33,.18],["c",.03,.06,-.69,3.66,-3.54,17.64],["c",-1.95,9.66,-3.57,17.61,-3.57,17.64],["c",-.03,.06,-.12,.12,-.24,.18],["c",-.21,.09,-.24,.09,-.48,.09],["c",-.24,0,-.3,0,-.48,-.06],["c",-.09,-.06,-.21,-.12,-.21,-.15],["c",-.06,-.03,.06,-.57,1.05,-4.95],["c",.6,-2.7,1.08,-4.89,1.08,-4.92],["c",0,0,-.24,.06,-.51,.15],["c",-.66,.24,-1.2,.36,-1.77,.48],["c",-.42,.06,-.57,.06,-1.05,.06],["c",-.69,0,-.87,-.03,-1.35,-.27],["c",-1.32,-.63,-1.77,-2.16,-1.02,-3.3],["c",.72,-1.05,2.22,-1.23,3.06,-.42],["c",.3,.33,.42,.6,.6,1.38],["c",.09,.45,.21,.78,.33,.9],["c",.09,.09,.27,.18,.45,.21],["c",.21,.03,.39,-.09,.72,-.42],["c",.45,-.45,1.02,-1.26,1.17,-1.65],["c",.03,-.09,.27,-1.14,.54,-2.34],["c",.27,-1.2,.48,-2.19,.51,-2.22],["c",0,-.03,-.09,-.03,-.48,.12],["c",-1.17,.39,-2.22,.57,-3,.54],["c",-.42,-.03,-.75,-.12,-1.11,-.3],["c",-1.32,-.63,-1.77,-2.16,-1.02,-3.3],["c",.36,-.54,.96,-.87,1.65,-.93],["c",.54,-.03,1.02,.15,1.41,.54],["c",.27,.3,.39,.54,.57,1.26],["c",.09,.33,.18,.66,.21,.72],["c",.15,.39,.57,.57,.9,.42],["c",.36,-.18,1.2,-1.26,1.47,-1.89],["c",.03,-.09,.3,-1.2,.57,-2.43],["l",.51,-2.28],["l",-.54,.18],["c",-1.11,.36,-1.8,.48,-2.61,.48],["c",-.66,0,-.84,-.03,-1.32,-.27],["c",-1.32,-.63,-1.77,-2.16,-1.02,-3.3],["c",.36,-.54,.96,-.87,1.65,-.93],["c",.54,-.03,1.02,.15,1.41,.54],["c",.27,.3,.39,.54,.57,1.26],["c",.15,.63,.21,.81,.33,.96],["c",.21,.21,.54,.3,.75,.18],["c",.36,-.18,.93,-.93,1.29,-1.68],["c",.12,-.24,.18,-.48,.63,-2.55],["l",.51,-2.31],["c",0,-.03,-.18,.03,-.39,.12],["c",-1.14,.36,-2.1,.54,-2.82,.51],["c",-.42,-.03,-.75,-.12,-1.11,-.3],["c",-1.32,-.63,-1.77,-2.16,-1.02,-3.3],["c",.33,-.45,.84,-.81,1.38,-.9],["z"]],w:12.453,h:36.383},"rests.128th":{d:[["M",6.03,-21.12],["c",.66,-.09,1.23,.09,1.68,.51],["c",.27,.3,.39,.54,.57,1.26],["c",.09,.33,.18,.66,.21,.72],["c",.12,.27,.33,.45,.6,.48],["c",.21,0,.33,-.06,.54,-.36],["c",.15,-.21,.54,-.93,.78,-1.47],["c",.15,-.33,.18,-.39,.3,-.48],["c",.18,-.09,.45,0,.51,.15],["c",.03,.09,-7.11,42.75,-7.17,42.84],["c",-.03,.03,-.15,.09,-.24,.15],["c",-.18,.06,-.24,.06,-.45,.06],["c",-.24,0,-.3,0,-.48,-.06],["c",-.09,-.06,-.21,-.12,-.21,-.15],["c",-.06,-.03,.03,-.57,.84,-4.98],["c",.51,-2.7,.93,-4.92,.9,-4.92],["c",0,0,-.15,.06,-.36,.12],["c",-.78,.27,-1.62,.48,-2.31,.57],["c",-.15,.03,-.54,.03,-.81,.03],["c",-.66,0,-.84,-.03,-1.32,-.27],["c",-1.32,-.63,-1.77,-2.16,-1.02,-3.3],["c",.36,-.54,.96,-.87,1.65,-.93],["c",.54,-.03,1.02,.15,1.41,.54],["c",.27,.3,.39,.54,.57,1.26],["c",.09,.33,.18,.66,.21,.72],["c",.12,.27,.33,.45,.63,.48],["c",.12,0,.18,0,.3,-.09],["c",.42,-.21,1.14,-1.11,1.5,-1.83],["c",.12,-.27,.12,-.27,.54,-2.52],["c",.24,-1.23,.42,-2.25,.39,-2.25],["c",0,0,-.24,.06,-.51,.18],["c",-1.26,.39,-2.25,.57,-3.06,.54],["c",-.42,-.03,-.75,-.12,-1.11,-.3],["c",-1.32,-.63,-1.77,-2.16,-1.02,-3.3],["c",.36,-.54,.96,-.87,1.65,-.93],["c",.54,-.03,1.02,.15,1.41,.54],["c",.27,.3,.39,.54,.57,1.26],["c",.15,.63,.21,.81,.33,.96],["c",.18,.21,.51,.3,.75,.18],["c",.36,-.15,1.05,-.99,1.41,-1.77],["l",.15,-.3],["l",.42,-2.25],["c",.21,-1.26,.42,-2.28,.39,-2.28],["l",-.51,.15],["c",-1.11,.39,-1.89,.51,-2.7,.51],["c",-.66,0,-.84,-.03,-1.32,-.27],["c",-1.32,-.63,-1.77,-2.16,-1.02,-3.3],["c",.36,-.54,.96,-.87,1.65,-.93],["c",.54,-.03,1.02,.15,1.41,.54],["c",.27,.3,.39,.54,.57,1.26],["c",.15,.63,.21,.81,.33,.96],["c",.18,.18,.48,.27,.72,.21],["c",.33,-.12,1.14,-1.26,1.41,-1.95],["c",0,-.09,.21,-1.11,.45,-2.34],["c",.21,-1.2,.39,-2.22,.39,-2.28],["c",.03,-.03,0,-.03,-.45,.12],["c",-.57,.18,-1.2,.33,-1.71,.42],["c",-.3,.06,-.51,.06,-.93,.06],["c",-.66,0,-.84,-.03,-1.32,-.27],["c",-1.32,-.63,-1.77,-2.16,-1.02,-3.3],["c",.36,-.54,.96,-.87,1.65,-.93],["c",.54,-.03,1.02,.15,1.41,.54],["c",.27,.3,.39,.54,.57,1.26],["c",.09,.33,.18,.66,.21,.72],["c",.12,.27,.33,.45,.6,.48],["c",.18,0,.36,-.09,.57,-.33],["c",.33,-.36,.78,-1.14,.93,-1.56],["c",.03,-.12,.24,-1.2,.45,-2.4],["c",.24,-1.2,.42,-2.22,.42,-2.28],["c",.03,-.03,0,-.03,-.39,.09],["c",-1.05,.36,-1.8,.48,-2.58,.48],["c",-.63,0,-.84,-.03,-1.29,-.27],["c",-1.32,-.63,-1.77,-2.16,-1.02,-3.3],["c",.33,-.45,.84,-.81,1.38,-.9],["z"]],w:12.992,h:43.883},"accidentals.sharp":{d:[["M",5.73,-11.19],["c",.21,-.12,.54,-.03,.66,.24],["c",.06,.12,.06,.21,.06,2.31],["c",0,1.23,0,2.22,.03,2.22],["c",0,0,.27,-.12,.6,-.24],["c",.69,-.27,.78,-.3,.96,-.15],["c",.21,.15,.21,.18,.21,1.38],["c",0,1.02,0,1.11,-.06,1.2],["c",-.03,.06,-.09,.12,-.12,.15],["c",-.06,.03,-.42,.21,-.84,.36],["l",-.75,.33],["l",-.03,2.43],["c",0,1.32,0,2.43,.03,2.43],["c",0,0,.27,-.12,.6,-.24],["c",.69,-.27,.78,-.3,.96,-.15],["c",.21,.15,.21,.18,.21,1.38],["c",0,1.02,0,1.11,-.06,1.2],["c",-.03,.06,-.09,.12,-.12,.15],["c",-.06,.03,-.42,.21,-.84,.36],["l",-.75,.33],["l",-.03,2.52],["c",0,2.28,-.03,2.55,-.06,2.64],["c",-.21,.36,-.72,.36,-.93,0],["c",-.03,-.09,-.06,-.33,-.06,-2.43],["l",0,-2.31],["l",-1.29,.51],["l",-1.26,.51],["l",0,2.43],["c",0,2.58,0,2.52,-.15,2.67],["c",-.06,.09,-.27,.18,-.36,.18],["c",-.12,0,-.33,-.09,-.39,-.18],["c",-.15,-.15,-.15,-.09,-.15,-2.43],["c",0,-1.23,0,-2.22,-.03,-2.22],["c",0,0,-.27,.12,-.6,.24],["c",-.69,.27,-.78,.3,-.96,.15],["c",-.21,-.15,-.21,-.18,-.21,-1.38],["c",0,-1.02,0,-1.11,.06,-1.2],["c",.03,-.06,.09,-.12,.12,-.15],["c",.06,-.03,.42,-.21,.84,-.36],["l",.78,-.33],["l",0,-2.43],["c",0,-1.32,0,-2.43,-.03,-2.43],["c",0,0,-.27,.12,-.6,.24],["c",-.69,.27,-.78,.3,-.96,.15],["c",-.21,-.15,-.21,-.18,-.21,-1.38],["c",0,-1.02,0,-1.11,.06,-1.2],["c",.03,-.06,.09,-.12,.12,-.15],["c",.06,-.03,.42,-.21,.84,-.36],["l",.78,-.33],["l",0,-2.52],["c",0,-2.28,.03,-2.55,.06,-2.64],["c",.21,-.36,.72,-.36,.93,0],["c",.03,.09,.06,.33,.06,2.43],["l",.03,2.31],["l",1.26,-.51],["l",1.26,-.51],["l",0,-2.43],["c",0,-2.28,0,-2.43,.06,-2.55],["c",.06,-.12,.12,-.18,.27,-.24],["z"],["m",-.33,10.65],["l",0,-2.43],["l",-1.29,.51],["l",-1.26,.51],["l",0,2.46],["l",0,2.43],["l",.09,-.03],["c",.06,-.03,.63,-.27,1.29,-.51],["l",1.17,-.48],["l",0,-2.46],["z"]],w:8.25,h:22.462},"accidentals.halfsharp":{d:[["M",2.43,-10.05],["c",.21,-.12,.54,-.03,.66,.24],["c",.06,.12,.06,.21,.06,2.01],["c",0,1.05,0,1.89,.03,1.89],["l",.72,-.48],["c",.69,-.48,.69,-.51,.87,-.51],["c",.15,0,.18,.03,.27,.09],["c",.21,.15,.21,.18,.21,1.41],["c",0,1.11,-.03,1.14,-.09,1.23],["c",-.03,.03,-.48,.39,-1.02,.75],["l",-.99,.66],["l",0,2.37],["c",0,1.32,0,2.37,.03,2.37],["l",.72,-.48],["c",.69,-.48,.69,-.51,.87,-.51],["c",.15,0,.18,.03,.27,.09],["c",.21,.15,.21,.18,.21,1.41],["c",0,1.11,-.03,1.14,-.09,1.23],["c",-.03,.03,-.48,.39,-1.02,.75],["l",-.99,.66],["l",0,2.25],["c",0,1.95,0,2.28,-.06,2.37],["c",-.06,.12,-.12,.21,-.24,.27],["c",-.27,.12,-.54,.03,-.69,-.24],["c",-.06,-.12,-.06,-.21,-.06,-2.01],["c",0,-1.05,0,-1.89,-.03,-1.89],["l",-.72,.48],["c",-.69,.48,-.69,.48,-.87,.48],["c",-.15,0,-.18,0,-.27,-.06],["c",-.21,-.15,-.21,-.18,-.21,-1.41],["c",0,-1.11,.03,-1.14,.09,-1.23],["c",.03,-.03,.48,-.39,1.02,-.75],["l",.99,-.66],["l",0,-2.37],["c",0,-1.32,0,-2.37,-.03,-2.37],["l",-.72,.48],["c",-.69,.48,-.69,.48,-.87,.48],["c",-.15,0,-.18,0,-.27,-.06],["c",-.21,-.15,-.21,-.18,-.21,-1.41],["c",0,-1.11,.03,-1.14,.09,-1.23],["c",.03,-.03,.48,-.39,1.02,-.75],["l",.99,-.66],["l",0,-2.25],["c",0,-2.13,0,-2.28,.06,-2.4],["c",.06,-.12,.12,-.18,.27,-.24],["z"]],w:5.25,h:20.174},"accidentals.nat":{d:[["M",.21,-11.4],["c",.24,-.06,.78,0,.99,.15],["c",.03,.03,.03,.48,0,2.61],["c",-.03,1.44,-.03,2.61,-.03,2.61],["c",0,.03,.75,-.09,1.68,-.24],["c",.96,-.18,1.71,-.27,1.74,-.27],["c",.15,.03,.27,.15,.36,.3],["l",.06,.12],["l",.09,8.67],["c",.09,6.96,.12,8.67,.09,8.67],["c",-.03,.03,-.12,.06,-.21,.09],["c",-.24,.09,-.72,.09,-.96,0],["c",-.09,-.03,-.18,-.06,-.21,-.09],["c",-.03,-.03,-.03,-.48,0,-2.61],["c",.03,-1.44,.03,-2.61,.03,-2.61],["c",0,-.03,-.75,.09,-1.68,.24],["c",-.96,.18,-1.71,.27,-1.74,.27],["c",-.15,-.03,-.27,-.15,-.36,-.3],["l",-.06,-.15],["l",-.09,-7.53],["c",-.06,-4.14,-.09,-8.04,-.12,-8.67],["l",0,-1.11],["l",.15,-.06],["c",.09,-.03,.21,-.06,.27,-.09],["z"],["m",3.75,8.4],["c",0,-.33,0,-.42,-.03,-.42],["c",-.12,0,-2.79,.45,-2.79,.48],["c",-.03,0,-.09,6.3,-.09,6.33],["c",.03,0,2.79,-.45,2.82,-.48],["c",0,0,.09,-4.53,.09,-5.91],["z"]],w:5.4,h:22.8},"accidentals.flat":{d:[["M",-.36,-14.07],["c",.33,-.06,.87,0,1.08,.15],["c",.06,.03,.06,.36,-.03,5.25],["c",-.06,2.85,-.09,5.19,-.09,5.19],["c",0,.03,.12,-.03,.24,-.12],["c",.63,-.42,1.41,-.66,2.19,-.72],["c",.81,-.03,1.47,.21,2.04,.78],["c",.57,.54,.87,1.26,.93,2.04],["c",.03,.57,-.09,1.08,-.36,1.62],["c",-.42,.81,-1.02,1.38,-2.82,2.61],["c",-1.14,.78,-1.44,1.02,-1.8,1.44],["c",-.18,.18,-.39,.39,-.45,.42],["c",-.27,.18,-.57,.15,-.81,-.06],["c",-.06,-.09,-.12,-.18,-.15,-.27],["c",-.03,-.06,-.09,-3.27,-.18,-8.34],["c",-.09,-4.53,-.15,-8.58,-.18,-9.03],["l",0,-.78],["l",.12,-.06],["c",.06,-.03,.18,-.09,.27,-.12],["z"],["m",3.18,11.01],["c",-.21,-.12,-.54,-.15,-.81,-.06],["c",-.54,.15,-.99,.63,-1.17,1.26],["c",-.06,.3,-.12,2.88,-.06,3.87],["c",.03,.42,.03,.81,.06,.9],["l",.03,.12],["l",.45,-.39],["c",.63,-.54,1.26,-1.17,1.56,-1.59],["c",.3,-.42,.6,-.99,.72,-1.41],["c",.18,-.69,.09,-1.47,-.18,-2.07],["c",-.15,-.3,-.33,-.51,-.6,-.63],["z"]],w:6.75,h:18.801},"accidentals.halfflat":{d:[["M",4.83,-14.07],["c",.33,-.06,.87,0,1.08,.15],["c",.06,.03,.06,.6,-.12,9.06],["c",-.09,5.55,-.15,9.06,-.18,9.12],["c",-.03,.09,-.09,.18,-.15,.27],["c",-.24,.21,-.54,.24,-.81,.06],["c",-.06,-.03,-.27,-.24,-.45,-.42],["c",-.36,-.42,-.66,-.66,-1.8,-1.44],["c",-1.23,-.84,-1.83,-1.32,-2.25,-1.77],["c",-.66,-.78,-.96,-1.56,-.93,-2.46],["c",.09,-1.41,1.11,-2.58,2.4,-2.79],["c",.3,-.06,.84,-.03,1.23,.06],["c",.54,.12,1.08,.33,1.53,.63],["c",.12,.09,.24,.15,.24,.12],["c",0,0,-.12,-8.37,-.18,-9.75],["l",0,-.66],["l",.12,-.06],["c",.06,-.03,.18,-.09,.27,-.12],["z"],["m",-1.65,10.95],["c",-.6,-.18,-1.08,.09,-1.38,.69],["c",-.27,.6,-.36,1.38,-.18,2.07],["c",.12,.42,.42,.99,.72,1.41],["c",.3,.42,.93,1.05,1.56,1.59],["l",.48,.39],["l",0,-.12],["c",.03,-.09,.03,-.48,.06,-.9],["c",.03,-.57,.03,-1.08,0,-2.22],["c",-.03,-1.62,-.03,-1.62,-.24,-2.07],["c",-.21,-.42,-.6,-.75,-1.02,-.84],["z"]],w:6.728,h:18.801},"accidentals.dblflat":{d:[["M",-.36,-14.07],["c",.33,-.06,.87,0,1.08,.15],["c",.06,.03,.06,.36,-.03,5.25],["c",-.06,2.85,-.09,5.19,-.09,5.19],["c",0,.03,.12,-.03,.24,-.12],["c",.63,-.42,1.41,-.66,2.19,-.72],["c",.81,-.03,1.47,.21,2.04,.78],["c",.57,.54,.87,1.26,.93,2.04],["c",.03,.57,-.09,1.08,-.36,1.62],["c",-.42,.81,-1.02,1.38,-2.82,2.61],["c",-1.14,.78,-1.44,1.02,-1.8,1.44],["c",-.18,.18,-.39,.39,-.45,.42],["c",-.27,.18,-.57,.15,-.81,-.06],["c",-.06,-.09,-.12,-.18,-.15,-.27],["c",-.03,-.06,-.09,-3.27,-.18,-8.34],["c",-.09,-4.53,-.15,-8.58,-.18,-9.03],["l",0,-.78],["l",.12,-.06],["c",.06,-.03,.18,-.09,.27,-.12],["z"],["m",3.18,11.01],["c",-.21,-.12,-.54,-.15,-.81,-.06],["c",-.54,.15,-.99,.63,-1.17,1.26],["c",-.06,.3,-.12,2.88,-.06,3.87],["c",.03,.42,.03,.81,.06,.9],["l",.03,.12],["l",.45,-.39],["c",.63,-.54,1.26,-1.17,1.56,-1.59],["c",.3,-.42,.6,-.99,.72,-1.41],["c",.18,-.69,.09,-1.47,-.18,-2.07],["c",-.15,-.3,-.33,-.51,-.6,-.63],["z"],["m",3,-11],["c",.33,-.06,.87,0,1.08,.15],["c",.06,.03,.06,.36,-.03,5.25],["c",-.06,2.85,-.09,5.19,-.09,5.19],["c",0,.03,.12,-.03,.24,-.12],["c",.63,-.42,1.41,-.66,2.19,-.72],["c",.81,-.03,1.47,.21,2.04,.78],["c",.57,.54,.87,1.26,.93,2.04],["c",.03,.57,-.09,1.08,-.36,1.62],["c",-.42,.81,-1.02,1.38,-2.82,2.61],["c",-1.14,.78,-1.44,1.02,-1.8,1.44],["c",-.18,.18,-.39,.39,-.45,.42],["c",-.27,.18,-.57,.15,-.81,-.06],["c",-.06,-.09,-.12,-.18,-.15,-.27],["c",-.03,-.06,-.09,-3.27,-.18,-8.34],["c",-.09,-4.53,-.15,-8.58,-.18,-9.03],["l",0,-.78],["l",.12,-.06],["c",.06,-.03,.18,-.09,.27,-.12],["z"],["m",3.18,11.01],["c",-.21,-.12,-.54,-.15,-.81,-.06],["c",-.54,.15,-.99,.63,-1.17,1.26],["c",-.06,.3,-.12,2.88,-.06,3.87],["c",.03,.42,.03,.81,.06,.9],["l",.03,.12],["l",.45,-.39],["c",.63,-.54,1.26,-1.17,1.56,-1.59],["c",.3,-.42,.6,-.99,.72,-1.41],["c",.18,-.69,.09,-1.47,-.18,-2.07],["c",-.15,-.3,-.33,-.51,-.6,-.63],["z"]],w:12.1,h:18.804},"accidentals.dblsharp":{d:[["M",-.18,-3.96],["c",.06,-.03,.12,-.06,.15,-.06],["c",.09,0,2.76,.27,2.79,.3],["c",.12,.03,.15,.12,.15,.51],["c",.06,.96,.24,1.59,.57,2.1],["c",.06,.09,.15,.21,.18,.24],["l",.09,.06],["l",.09,-.06],["c",.03,-.03,.12,-.15,.18,-.24],["c",.33,-.51,.51,-1.14,.57,-2.1],["c",0,-.39,.03,-.45,.12,-.51],["c",.03,0,.66,-.09,1.44,-.15],["c",1.47,-.15,1.5,-.15,1.56,-.03],["c",.03,.06,0,.42,-.09,1.44],["c",-.09,.72,-.15,1.35,-.15,1.38],["c",0,.03,-.03,.09,-.06,.12],["c",-.06,.06,-.12,.09,-.51,.09],["c",-1.08,.06,-1.8,.3,-2.28,.75],["l",-.12,.09],["l",.09,.09],["c",.12,.15,.39,.33,.63,.45],["c",.42,.18,.96,.27,1.68,.33],["c",.39,0,.45,.03,.51,.09],["c",.03,.03,.06,.09,.06,.12],["c",0,.03,.06,.66,.15,1.38],["c",.09,1.02,.12,1.38,.09,1.44],["c",-.06,.12,-.09,.12,-1.56,-.03],["c",-.78,-.06,-1.41,-.15,-1.44,-.15],["c",-.09,-.06,-.12,-.12,-.12,-.54],["c",-.06,-.93,-.24,-1.56,-.57,-2.07],["c",-.06,-.09,-.15,-.21,-.18,-.24],["l",-.09,-.06],["l",-.09,.06],["c",-.03,.03,-.12,.15,-.18,.24],["c",-.33,.51,-.51,1.14,-.57,2.07],["c",0,.42,-.03,.48,-.12,.54],["c",-.03,0,-.66,.09,-1.44,.15],["c",-1.47,.15,-1.5,.15,-1.56,.03],["c",-.03,-.06,0,-.42,.09,-1.44],["c",.09,-.72,.15,-1.35,.15,-1.38],["c",0,-.03,.03,-.09,.06,-.12],["c",.06,-.06,.12,-.09,.51,-.09],["c",.72,-.06,1.26,-.15,1.68,-.33],["c",.24,-.12,.51,-.3,.63,-.45],["l",.09,-.09],["l",-.12,-.09],["c",-.48,-.45,-1.2,-.69,-2.28,-.75],["c",-.39,0,-.45,-.03,-.51,-.09],["c",-.03,-.03,-.06,-.09,-.06,-.12],["c",0,-.03,-.06,-.63,-.12,-1.38],["c",-.09,-.72,-.15,-1.35,-.15,-1.38],["z"]],w:7.95,h:7.977},"dots.dot":{d:[["M",1.32,-1.68],["c",.09,-.03,.27,-.06,.39,-.06],["c",.96,0,1.74,.78,1.74,1.71],["c",0,.96,-.78,1.74,-1.71,1.74],["c",-.96,0,-1.74,-.78,-1.74,-1.71],["c",0,-.78,.54,-1.5,1.32,-1.68],["z"]],w:3.45,h:3.45},"noteheads.dbl":{d:[["M",-.69,-4.02],["c",.18,-.09,.36,-.09,.54,0],["c",.18,.09,.24,.15,.33,.3],["c",.06,.15,.06,.18,.06,1.41],["l",0,1.23],["l",.12,-.18],["c",.72,-1.26,2.64,-2.31,4.86,-2.64],["c",.81,-.15,1.11,-.15,2.13,-.15],["c",.99,0,1.29,0,2.1,.15],["c",.75,.12,1.38,.27,2.04,.54],["c",1.35,.51,2.34,1.26,2.82,2.1],["l",.12,.18],["l",0,-1.23],["c",0,-1.2,0,-1.26,.06,-1.38],["c",.09,-.18,.15,-.24,.33,-.33],["c",.18,-.09,.36,-.09,.54,0],["c",.18,.09,.24,.15,.33,.3],["l",.06,.15],["l",0,3.54],["l",0,3.54],["l",-.06,.15],["c",-.09,.18,-.15,.24,-.33,.33],["c",-.18,.09,-.36,.09,-.54,0],["c",-.18,-.09,-.24,-.15,-.33,-.33],["c",-.06,-.12,-.06,-.18,-.06,-1.38],["l",0,-1.23],["l",-.12,.18],["c",-.48,.84,-1.47,1.59,-2.82,2.1],["c",-.84,.33,-1.71,.54,-2.85,.66],["c",-.45,.06,-2.16,.06,-2.61,0],["c",-1.14,-.12,-2.01,-.33,-2.85,-.66],["c",-1.35,-.51,-2.34,-1.26,-2.82,-2.1],["l",-.12,-.18],["l",0,1.23],["c",0,1.23,0,1.26,-.06,1.38],["c",-.09,.18,-.15,.24,-.33,.33],["c",-.18,.09,-.36,.09,-.54,0],["c",-.18,-.09,-.24,-.15,-.33,-.33],["l",-.06,-.15],["l",0,-3.54],["c",0,-3.48,0,-3.54,.06,-3.66],["c",.09,-.18,.15,-.24,.33,-.33],["z"],["m",7.71,.63],["c",-.36,-.06,-.9,-.06,-1.14,0],["c",-.3,.03,-.66,.24,-.87,.42],["c",-.6,.54,-.9,1.62,-.75,2.82],["c",.12,.93,.51,1.68,1.11,2.31],["c",.75,.72,1.83,1.2,2.85,1.26],["c",1.05,.06,1.83,-.54,2.1,-1.65],["c",.21,-.9,.12,-1.95,-.24,-2.82],["c",-.36,-.81,-1.08,-1.53,-1.95,-1.95],["c",-.3,-.15,-.78,-.3,-1.11,-.39],["z"]],w:16.83,h:8.145},"noteheads.whole":{d:[["M",6.51,-4.05],["c",.51,-.03,2.01,0,2.52,.03],["c",1.41,.18,2.64,.51,3.72,1.08],["c",1.2,.63,1.95,1.41,2.19,2.31],["c",.09,.33,.09,.9,0,1.23],["c",-.24,.9,-.99,1.68,-2.19,2.31],["c",-1.08,.57,-2.28,.9,-3.75,1.08],["c",-.66,.06,-2.31,.06,-2.97,0],["c",-1.47,-.18,-2.67,-.51,-3.75,-1.08],["c",-1.2,-.63,-1.95,-1.41,-2.19,-2.31],["c",-.09,-.33,-.09,-.9,0,-1.23],["c",.24,-.9,.99,-1.68,2.19,-2.31],["c",1.2,-.63,2.61,-.99,4.23,-1.11],["z"],["m",.57,.66],["c",-.87,-.15,-1.53,0,-2.04,.51],["c",-.15,.15,-.24,.27,-.33,.48],["c",-.24,.51,-.36,1.08,-.33,1.77],["c",.03,.69,.18,1.26,.42,1.77],["c",.6,1.17,1.74,1.98,3.18,2.22],["c",1.11,.21,1.95,-.15,2.34,-.99],["c",.24,-.51,.36,-1.08,.33,-1.8],["c",-.06,-1.11,-.45,-2.04,-1.17,-2.76],["c",-.63,-.63,-1.47,-1.05,-2.4,-1.2],["z"]],w:14.985,h:8.097},"noteheads.half":{d:[["M",7.44,-4.05],["c",.06,-.03,.27,-.03,.48,-.03],["c",1.05,0,1.71,.24,2.1,.81],["c",.42,.6,.45,1.35,.18,2.4],["c",-.42,1.59,-1.14,2.73,-2.16,3.39],["c",-1.41,.93,-3.18,1.44,-5.4,1.53],["c",-1.17,.03,-1.89,-.21,-2.28,-.81],["c",-.42,-.6,-.45,-1.35,-.18,-2.4],["c",.42,-1.59,1.14,-2.73,2.16,-3.39],["c",.63,-.42,1.23,-.72,1.98,-.96],["c",.9,-.3,1.65,-.42,3.12,-.54],["z"],["m",1.29,.87],["c",-.27,-.09,-.63,-.12,-.9,-.03],["c",-.72,.24,-1.53,.69,-3.27,1.8],["c",-2.34,1.5,-3.3,2.25,-3.57,2.79],["c",-.36,.72,-.06,1.5,.66,1.77],["c",.24,.12,.69,.09,.99,0],["c",.84,-.3,1.92,-.93,4.14,-2.37],["c",1.62,-1.08,2.37,-1.71,2.61,-2.19],["c",.36,-.72,.06,-1.5,-.66,-1.77],["z"]],w:10.37,h:8.132},"noteheads.quarter":{d:[["M",6.09,-4.05],["c",.36,-.03,1.2,0,1.53,.06],["c",1.17,.24,1.89,.84,2.16,1.83],["c",.06,.18,.06,.3,.06,.66],["c",0,.45,0,.63,-.15,1.08],["c",-.66,2.04,-3.06,3.93,-5.52,4.38],["c",-.54,.09,-1.44,.09,-1.83,.03],["c",-1.23,-.27,-1.98,-.87,-2.25,-1.86],["c",-.06,-.18,-.06,-.3,-.06,-.66],["c",0,-.45,0,-.63,.15,-1.08],["c",.24,-.78,.75,-1.53,1.44,-2.22],["c",1.2,-1.2,2.85,-2.01,4.47,-2.22],["z"]],w:9.81,h:8.094},"noteheads.slash.nostem":{d:[["M",9.3,-7.77],["c",.06,-.06,.18,-.06,1.71,-.06],["l",1.65,0],["l",.09,.09],["c",.06,.06,.06,.09,.06,.15],["c",-.03,.12,-9.21,15.24,-9.3,15.33],["c",-.06,.06,-.18,.06,-1.71,.06],["l",-1.65,0],["l",-.09,-.09],["c",-.06,-.06,-.06,-.09,-.06,-.15],["c",.03,-.12,9.21,-15.24,9.3,-15.33],["z"]],w:12.81,h:15.63},"noteheads.indeterminate":{d:[["M",.78,-4.05],["c",.12,-.03,.24,-.03,.36,.03],["c",.03,.03,.93,.72,1.95,1.56],["l",1.86,1.5],["l",1.86,-1.5],["c",1.02,-.84,1.92,-1.53,1.95,-1.56],["c",.21,-.12,.33,-.09,.75,.24],["c",.3,.27,.36,.36,.36,.54],["c",0,.03,-.03,.12,-.06,.18],["c",-.03,.06,-.9,.75,-1.89,1.56],["l",-1.8,1.47],["c",0,.03,.81,.69,1.8,1.5],["c",.99,.81,1.86,1.5,1.89,1.56],["c",.03,.06,.06,.15,.06,.18],["c",0,.18,-.06,.27,-.36,.54],["c",-.42,.33,-.54,.36,-.75,.24],["c",-.03,-.03,-.93,-.72,-1.95,-1.56],["l",-1.86,-1.5],["l",-1.86,1.5],["c",-1.02,.84,-1.92,1.53,-1.95,1.56],["c",-.21,.12,-.33,.09,-.75,-.24],["c",-.3,-.27,-.36,-.36,-.36,-.54],["c",0,-.03,.03,-.12,.06,-.18],["c",.03,-.06,.9,-.75,1.89,-1.56],["l",1.8,-1.47],["c",0,-.03,-.81,-.69,-1.8,-1.5],["c",-.99,-.81,-1.86,-1.5,-1.89,-1.56],["c",-.06,-.12,-.09,-.21,-.03,-.36],["c",.03,-.09,.57,-.57,.72,-.63],["z"]],w:9.843,h:8.139},"scripts.ufermata":{d:[["M",-.75,-10.77],["c",.12,0,.45,-.03,.69,-.03],["c",2.91,-.03,5.55,1.53,7.41,4.35],["c",1.17,1.71,1.95,3.72,2.43,6.03],["c",.12,.51,.12,.57,.03,.69],["c",-.12,.21,-.48,.27,-.69,.12],["c",-.12,-.09,-.18,-.24,-.27,-.69],["c",-.78,-3.63,-3.42,-6.54,-6.78,-7.38],["c",-.78,-.21,-1.2,-.24,-2.07,-.24],["c",-.63,0,-.84,0,-1.2,.06],["c",-1.83,.27,-3.42,1.08,-4.8,2.37],["c",-1.41,1.35,-2.4,3.21,-2.85,5.19],["c",-.09,.45,-.15,.6,-.27,.69],["c",-.21,.15,-.57,.09,-.69,-.12],["c",-.09,-.12,-.09,-.18,.03,-.69],["c",.33,-1.62,.78,-3,1.47,-4.38],["c",1.77,-3.54,4.44,-5.67,7.56,-5.97],["z"],["m",.33,7.47],["c",1.38,-.3,2.58,.9,2.31,2.25],["c",-.15,.72,-.78,1.35,-1.47,1.5],["c",-1.38,.27,-2.58,-.93,-2.31,-2.31],["c",.15,-.69,.78,-1.29,1.47,-1.44],["z"]],w:19.748,h:11.289},"scripts.dfermata":{d:[["M",-9.63,-.42],["c",.15,-.09,.36,-.06,.51,.03],["c",.12,.09,.18,.24,.27,.66],["c",.78,3.66,3.42,6.57,6.78,7.41],["c",.78,.21,1.2,.24,2.07,.24],["c",.63,0,.84,0,1.2,-.06],["c",1.83,-.27,3.42,-1.08,4.8,-2.37],["c",1.41,-1.35,2.4,-3.21,2.85,-5.22],["c",.09,-.42,.15,-.57,.27,-.66],["c",.21,-.15,.57,-.09,.69,.12],["c",.09,.12,.09,.18,-.03,.69],["c",-.33,1.62,-.78,3,-1.47,4.38],["c",-1.92,3.84,-4.89,6,-8.31,6],["c",-3.42,0,-6.39,-2.16,-8.31,-6],["c",-.48,-.96,-.84,-1.92,-1.14,-2.97],["c",-.18,-.69,-.42,-1.74,-.42,-1.92],["c",0,-.12,.09,-.27,.24,-.33],["z"],["m",9.21,0],["c",1.2,-.27,2.34,.63,2.34,1.86],["c",0,.9,-.66,1.68,-1.5,1.89],["c",-1.38,.27,-2.58,-.93,-2.31,-2.31],["c",.15,-.69,.78,-1.29,1.47,-1.44],["z"]],w:19.744,h:11.274},"scripts.sforzato":{d:[["M",-6.45,-3.69],["c",.06,-.03,.15,-.06,.18,-.06],["c",.06,0,2.85,.72,6.24,1.59],["l",6.33,1.65],["c",.33,.06,.45,.21,.45,.51],["c",0,.3,-.12,.45,-.45,.51],["l",-6.33,1.65],["c",-3.39,.87,-6.18,1.59,-6.21,1.59],["c",-.21,0,-.48,-.24,-.51,-.45],["c",0,-.15,.06,-.36,.18,-.45],["c",.09,-.06,.87,-.27,3.84,-1.05],["c",2.04,-.54,3.84,-.99,4.02,-1.02],["c",.15,-.06,1.14,-.24,2.22,-.42],["c",1.05,-.18,1.92,-.36,1.92,-.36],["c",0,0,-.87,-.18,-1.92,-.36],["c",-1.08,-.18,-2.07,-.36,-2.22,-.42],["c",-.18,-.03,-1.98,-.48,-4.02,-1.02],["c",-2.97,-.78,-3.75,-.99,-3.84,-1.05],["c",-.12,-.09,-.18,-.3,-.18,-.45],["c",.03,-.15,.15,-.3,.3,-.39],["z"]],w:13.5,h:7.5},"scripts.staccato":{d:[["M",-.36,-1.47],["c",.93,-.21,1.86,.51,1.86,1.47],["c",0,.93,-.87,1.65,-1.8,1.47],["c",-.54,-.12,-1.02,-.57,-1.14,-1.08],["c",-.21,-.81,.27,-1.65,1.08,-1.86],["z"]],w:2.989,h:3.004},"scripts.tenuto":{d:[["M",-4.2,-.48],["l",.12,-.06],["l",4.08,0],["l",4.08,0],["l",.12,.06],["c",.39,.21,.39,.75,0,.96],["l",-.12,.06],["l",-4.08,0],["l",-4.08,0],["l",-.12,-.06],["c",-.39,-.21,-.39,-.75,0,-.96],["z"]],w:8.985,h:1.08},"scripts.umarcato":{d:[["M",-.15,-8.19],["c",.15,-.12,.36,-.03,.45,.15],["c",.21,.42,3.45,7.65,3.45,7.71],["c",0,.12,-.12,.27,-.21,.3],["c",-.03,.03,-.51,.03,-1.14,.03],["c",-1.05,0,-1.08,0,-1.17,-.06],["c",-.09,-.06,-.24,-.36,-1.17,-2.4],["c",-.57,-1.29,-1.05,-2.34,-1.08,-2.34],["c",0,-.03,-.51,1.02,-1.08,2.34],["c",-.93,2.07,-1.08,2.34,-1.14,2.4],["c",-.06,.03,-.15,.06,-.18,.06],["c",-.15,0,-.33,-.18,-.33,-.33],["c",0,-.06,3.24,-7.32,3.45,-7.71],["c",.03,-.06,.09,-.15,.15,-.15],["z"]],w:7.5,h:8.245},"scripts.dmarcato":{d:[["M",-3.57,.03],["c",.03,0,.57,-.03,1.17,-.03],["c",1.05,0,1.08,0,1.17,.06],["c",.09,.06,.24,.36,1.17,2.4],["c",.57,1.29,1.05,2.34,1.08,2.34],["c",0,.03,.51,-1.02,1.08,-2.34],["c",.93,-2.07,1.08,-2.34,1.14,-2.4],["c",.06,-.03,.15,-.06,.18,-.06],["c",.15,0,.33,.18,.33,.33],["c",0,.09,-3.45,7.74,-3.54,7.83],["c",-.12,.12,-.3,.12,-.42,0],["c",-.09,-.09,-3.54,-7.74,-3.54,-7.83],["c",0,-.09,.12,-.27,.18,-.3],["z"]],w:7.5,h:8.25},"scripts.stopped":{d:[["M",-.27,-4.08],["c",.18,-.09,.36,-.09,.54,0],["c",.18,.09,.24,.15,.33,.3],["l",.06,.15],["l",0,1.5],["l",0,1.47],["l",1.47,0],["l",1.5,0],["l",.15,.06],["c",.15,.09,.21,.15,.3,.33],["c",.09,.18,.09,.36,0,.54],["c",-.09,.18,-.15,.24,-.33,.33],["c",-.12,.06,-.18,.06,-1.62,.06],["l",-1.47,0],["l",0,1.47],["l",0,1.47],["l",-.06,.15],["c",-.09,.18,-.15,.24,-.33,.33],["c",-.18,.09,-.36,.09,-.54,0],["c",-.18,-.09,-.24,-.15,-.33,-.33],["l",-.06,-.15],["l",0,-1.47],["l",0,-1.47],["l",-1.47,0],["c",-1.44,0,-1.5,0,-1.62,-.06],["c",-.18,-.09,-.24,-.15,-.33,-.33],["c",-.09,-.18,-.09,-.36,0,-.54],["c",.09,-.18,.15,-.24,.33,-.33],["l",.15,-.06],["l",1.47,0],["l",1.47,0],["l",0,-1.47],["c",0,-1.44,0,-1.5,.06,-1.62],["c",.09,-.18,.15,-.24,.33,-.33],["z"]],w:8.295,h:8.295},"scripts.upbow":{d:[["M",-4.65,-15.54],["c",.12,-.09,.36,-.06,.48,.03],["c",.03,.03,.09,.09,.12,.15],["c",.03,.06,.66,2.13,1.41,4.62],["c",1.35,4.41,1.38,4.56,2.01,6.96],["l",.63,2.46],["l",.63,-2.46],["c",.63,-2.4,.66,-2.55,2.01,-6.96],["c",.75,-2.49,1.38,-4.56,1.41,-4.62],["c",.06,-.15,.18,-.21,.36,-.24],["c",.15,0,.3,.06,.39,.18],["c",.15,.21,.24,-.18,-2.1,7.56],["c",-1.2,3.96,-2.22,7.32,-2.25,7.41],["c",0,.12,-.06,.27,-.09,.3],["c",-.12,.21,-.6,.21,-.72,0],["c",-.03,-.03,-.09,-.18,-.09,-.3],["c",-.03,-.09,-1.05,-3.45,-2.25,-7.41],["c",-2.34,-7.74,-2.25,-7.35,-2.1,-7.56],["c",.03,-.03,.09,-.09,.15,-.12],["z"]],w:9.73,h:15.608},"scripts.downbow":{d:[["M",-5.55,-9.93],["l",.09,-.06],["l",5.46,0],["l",5.46,0],["l",.09,.06],["l",.06,.09],["l",0,4.77],["c",0,5.28,0,4.89,-.18,5.01],["c",-.18,.12,-.42,.06,-.54,-.12],["c",-.06,-.09,-.06,-.18,-.06,-2.97],["l",0,-2.85],["l",-4.83,0],["l",-4.83,0],["l",0,2.85],["c",0,2.79,0,2.88,-.06,2.97],["c",-.15,.24,-.51,.24,-.66,0],["c",-.06,-.09,-.06,-.21,-.06,-4.89],["l",0,-4.77],["z"]],w:11.22,h:9.992},"scripts.turn":{d:[["M",-4.77,-3.9],["c",.36,-.06,1.05,-.06,1.44,.03],["c",.78,.15,1.5,.51,2.34,1.14],["c",.6,.45,1.05,.87,2.22,2.01],["c",1.11,1.08,1.62,1.5,2.22,1.86],["c",.6,.36,1.32,.57,1.92,.57],["c",.9,0,1.71,-.57,1.89,-1.35],["c",.24,-.93,-.39,-1.89,-1.35,-2.1],["l",-.15,-.06],["l",-.09,.15],["c",-.03,.09,-.15,.24,-.24,.33],["c",-.72,.72,-2.04,.54,-2.49,-.36],["c",-.48,-.93,.03,-1.86,1.17,-2.19],["c",.3,-.09,1.02,-.09,1.35,0],["c",.99,.27,1.74,.87,2.25,1.83],["c",.69,1.41,.63,3,-.21,4.26],["c",-.21,.3,-.69,.81,-.99,1.02],["c",-.3,.21,-.84,.45,-1.17,.54],["c",-1.23,.36,-2.49,.15,-3.72,-.6],["c",-.75,-.48,-1.41,-1.02,-2.85,-2.46],["c",-1.11,-1.08,-1.62,-1.5,-2.22,-1.86],["c",-.6,-.36,-1.32,-.57,-1.92,-.57],["c",-.9,0,-1.71,.57,-1.89,1.35],["c",-.24,.93,.39,1.89,1.35,2.1],["l",.15,.06],["l",.09,-.15],["c",.03,-.09,.15,-.24,.24,-.33],["c",.72,-.72,2.04,-.54,2.49,.36],["c",.48,.93,-.03,1.86,-1.17,2.19],["c",-.3,.09,-1.02,.09,-1.35,0],["c",-.99,-.27,-1.74,-.87,-2.25,-1.83],["c",-.69,-1.41,-.63,-3,.21,-4.26],["c",.21,-.3,.69,-.81,.99,-1.02],["c",.48,-.33,1.11,-.57,1.74,-.66],["z"]],w:16.366,h:7.893},"scripts.trill":{d:[["M",-.51,-16.02],["c",.12,-.09,.21,-.18,.21,-.18],["l",-.81,4.02],["l",-.81,4.02],["c",.03,0,.51,-.27,1.08,-.6],["c",.6,-.3,1.14,-.63,1.26,-.66],["c",1.14,-.54,2.31,-.6,3.09,-.18],["c",.27,.15,.54,.36,.6,.51],["l",.06,.12],["l",.21,-.21],["c",.9,-.81,2.22,-.99,3.12,-.42],["c",.6,.42,.9,1.14,.78,2.07],["c",-.15,1.29,-1.05,2.31,-1.95,2.25],["c",-.48,-.03,-.78,-.3,-.96,-.81],["c",-.09,-.27,-.09,-.9,-.03,-1.2],["c",.21,-.75,.81,-1.23,1.59,-1.32],["l",.24,-.03],["l",-.09,-.12],["c",-.51,-.66,-1.62,-.63,-2.31,.03],["c",-.39,.42,-.3,.09,-1.23,4.77],["l",-.81,4.14],["c",-.03,0,-.12,-.03,-.21,-.09],["c",-.33,-.15,-.54,-.18,-.99,-.18],["c",-.42,0,-.66,.03,-1.05,.18],["c",-.12,.06,-.21,.09,-.21,.09],["c",0,-.03,.36,-1.86,.81,-4.11],["c",.9,-4.47,.87,-4.26,.69,-4.53],["c",-.21,-.36,-.66,-.51,-1.17,-.36],["c",-.15,.06,-2.22,1.14,-2.58,1.38],["c",-.12,.09,-.12,.09,-.21,.6],["l",-.09,.51],["l",.21,.24],["c",.63,.75,1.02,1.47,1.2,2.19],["c",.06,.27,.06,.36,.06,.81],["c",0,.42,0,.54,-.06,.78],["c",-.15,.54,-.33,.93,-.63,1.35],["c",-.18,.24,-.57,.63,-.81,.78],["c",-.24,.15,-.63,.36,-.84,.42],["c",-.27,.06,-.66,.06,-.87,.03],["c",-.81,-.18,-1.32,-1.05,-1.38,-2.46],["c",-.03,-.6,.03,-.99,.33,-2.46],["c",.21,-1.08,.24,-1.32,.21,-1.29],["c",-1.2,.48,-2.4,.75,-3.21,.72],["c",-.69,-.06,-1.17,-.3,-1.41,-.72],["c",-.39,-.75,-.12,-1.8,.66,-2.46],["c",.24,-.18,.69,-.42,1.02,-.51],["c",.69,-.18,1.53,-.15,2.31,.09],["c",.3,.09,.75,.3,.99,.45],["c",.12,.09,.15,.09,.15,.03],["c",.03,-.03,.33,-1.59,.72,-3.45],["c",.36,-1.86,.66,-3.42,.69,-3.45],["c",0,-.03,.03,-.03,.21,.03],["c",.21,.06,.27,.06,.48,.06],["c",.42,-.03,.78,-.18,1.26,-.48],["c",.15,-.12,.36,-.27,.48,-.39],["z"],["m",-5.73,7.68],["c",-.27,-.03,-.96,-.06,-1.2,-.03],["c",-.81,.12,-1.35,.57,-1.5,1.2],["c",-.18,.66,.12,1.14,.75,1.29],["c",.66,.12,1.92,-.12,3.18,-.66],["l",.33,-.15],["l",.09,-.39],["c",.06,-.21,.09,-.42,.09,-.45],["c",0,-.03,-.45,-.3,-.75,-.45],["c",-.27,-.15,-.66,-.27,-.99,-.36],["z"],["m",4.29,3.63],["c",-.24,-.39,-.51,-.75,-.51,-.69],["c",-.06,.12,-.39,1.92,-.45,2.28],["c",-.09,.54,-.12,1.14,-.06,1.38],["c",.06,.42,.21,.6,.51,.57],["c",.39,-.06,.75,-.48,.93,-1.14],["c",.09,-.33,.09,-1.05,0,-1.38],["c",-.09,-.39,-.24,-.69,-.42,-1.02],["z"]],w:17.963,h:16.49},"scripts.segno":{d:[["M",-3.72,-11.22],["c",.78,-.09,1.59,.03,2.31,.42],["c",1.2,.6,2.01,1.71,2.31,3.09],["c",.09,.42,.09,1.2,.03,1.5],["c",-.15,.45,-.39,.81,-.66,.93],["c",-.33,.18,-.84,.21,-1.23,.15],["c",-.81,-.18,-1.32,-.93,-1.26,-1.89],["c",.03,-.36,.09,-.57,.24,-.9],["c",.15,-.33,.45,-.6,.72,-.75],["c",.12,-.06,.18,-.09,.18,-.12],["c",0,-.03,-.03,-.15,-.09,-.24],["c",-.18,-.45,-.54,-.87,-.96,-1.08],["c",-1.11,-.57,-2.34,-.18,-2.88,.9],["c",-.24,.51,-.33,1.11,-.24,1.83],["c",.27,1.92,1.5,3.54,3.93,5.13],["c",.48,.33,1.26,.78,1.29,.78],["c",.03,0,1.35,-2.19,2.94,-4.89],["l",2.88,-4.89],["l",.84,0],["l",.87,0],["l",-.03,.06],["c",-.15,.21,-6.15,10.41,-6.15,10.44],["c",0,0,.21,.15,.48,.27],["c",2.61,1.47,4.35,3.03,5.13,4.65],["c",1.14,2.34,.51,5.07,-1.44,6.39],["c",-.66,.42,-1.32,.63,-2.13,.69],["c",-2.01,.09,-3.81,-1.41,-4.26,-3.54],["c",-.09,-.42,-.09,-1.2,-.03,-1.5],["c",.15,-.45,.39,-.81,.66,-.93],["c",.33,-.18,.84,-.21,1.23,-.15],["c",.81,.18,1.32,.93,1.26,1.89],["c",-.03,.36,-.09,.57,-.24,.9],["c",-.15,.33,-.45,.6,-.72,.75],["c",-.12,.06,-.18,.09,-.18,.12],["c",0,.03,.03,.15,.09,.24],["c",.18,.45,.54,.87,.96,1.08],["c",1.11,.57,2.34,.18,2.88,-.9],["c",.24,-.51,.33,-1.11,.24,-1.83],["c",-.27,-1.92,-1.5,-3.54,-3.93,-5.13],["c",-.48,-.33,-1.26,-.78,-1.29,-.78],["c",-.03,0,-1.35,2.19,-2.91,4.89],["l",-2.88,4.89],["l",-.87,0],["l",-.87,0],["l",.03,-.06],["c",.15,-.21,6.15,-10.41,6.15,-10.44],["c",0,0,-.21,-.15,-.48,-.3],["c",-2.61,-1.44,-4.35,-3,-5.13,-4.62],["c",-.9,-1.89,-.72,-4.02,.48,-5.52],["c",.69,-.84,1.68,-1.41,2.73,-1.53],["z"],["m",8.76,9.09],["c",.03,-.03,.15,-.03,.27,-.03],["c",.33,.03,.57,.18,.72,.48],["c",.09,.18,.09,.57,0,.75],["c",-.09,.18,-.21,.3,-.36,.39],["c",-.15,.06,-.21,.06,-.39,.06],["c",-.21,0,-.27,0,-.39,-.06],["c",-.3,-.15,-.48,-.45,-.48,-.75],["c",0,-.39,.24,-.72,.63,-.84],["z"],["m",-10.53,2.61],["c",.03,-.03,.15,-.03,.27,-.03],["c",.33,.03,.57,.18,.72,.48],["c",.09,.18,.09,.57,0,.75],["c",-.09,.18,-.21,.3,-.36,.39],["c",-.15,.06,-.21,.06,-.39,.06],["c",-.21,0,-.27,0,-.39,-.06],["c",-.3,-.15,-.48,-.45,-.48,-.75],["c",0,-.39,.24,-.72,.63,-.84],["z"]],w:15,h:22.504},"scripts.coda":{d:[["M",-.21,-10.47],["c",.18,-.12,.42,-.06,.54,.12],["c",.06,.09,.06,.18,.06,1.5],["l",0,1.38],["l",.18,0],["c",.39,.06,.96,.24,1.38,.48],["c",1.68,.93,2.82,3.24,3.03,6.12],["c",.03,.24,.03,.45,.03,.45],["c",0,.03,.6,.03,1.35,.03],["c",1.5,0,1.47,0,1.59,.18],["c",.09,.12,.09,.3,0,.42],["c",-.12,.18,-.09,.18,-1.59,.18],["c",-.75,0,-1.35,0,-1.35,.03],["c",0,0,0,.21,-.03,.42],["c",-.24,3.15,-1.53,5.58,-3.45,6.36],["c",-.27,.12,-.72,.24,-.96,.27],["l",-.18,0],["l",0,1.38],["c",0,1.32,0,1.41,-.06,1.5],["c",-.15,.24,-.51,.24,-.66,0],["c",-.06,-.09,-.06,-.18,-.06,-1.5],["l",0,-1.38],["l",-.18,0],["c",-.39,-.06,-.96,-.24,-1.38,-.48],["c",-1.68,-.93,-2.82,-3.24,-3.03,-6.15],["c",-.03,-.21,-.03,-.42,-.03,-.42],["c",0,-.03,-.6,-.03,-1.35,-.03],["c",-1.5,0,-1.47,0,-1.59,-.18],["c",-.09,-.12,-.09,-.3,0,-.42],["c",.12,-.18,.09,-.18,1.59,-.18],["c",.75,0,1.35,0,1.35,-.03],["c",0,0,0,-.21,.03,-.45],["c",.24,-3.12,1.53,-5.55,3.45,-6.33],["c",.27,-.12,.72,-.24,.96,-.27],["l",.18,0],["l",0,-1.38],["c",0,-1.53,0,-1.5,.18,-1.62],["z"],["m",-.18,6.93],["c",0,-2.97,0,-3.15,-.06,-3.15],["c",-.09,0,-.51,.15,-.66,.21],["c",-.87,.51,-1.38,1.62,-1.56,3.51],["c",-.06,.54,-.12,1.59,-.12,2.16],["l",0,.42],["l",1.2,0],["l",1.2,0],["l",0,-3.15],["z"],["m",1.17,-3.06],["c",-.09,-.03,-.21,-.06,-.27,-.09],["l",-.12,0],["l",0,3.15],["l",0,3.15],["l",1.2,0],["l",1.2,0],["l",0,-.81],["c",-.06,-2.4,-.33,-3.69,-.93,-4.59],["c",-.27,-.39,-.66,-.69,-1.08,-.81],["z"],["m",-1.17,10.14],["l",0,-3.15],["l",-1.2,0],["l",-1.2,0],["l",0,.81],["c",.03,.96,.06,1.47,.15,2.13],["c",.24,2.04,.96,3.12,2.13,3.36],["l",.12,0],["l",0,-3.15],["z"],["m",3.18,-2.34],["l",0,-.81],["l",-1.2,0],["l",-1.2,0],["l",0,3.15],["l",0,3.15],["l",.12,0],["c",1.17,-.24,1.89,-1.32,2.13,-3.36],["c",.09,-.66,.12,-1.17,.15,-2.13],["z"]],w:16.035,h:21.062},"scripts.comma":{d:[["M",1.14,-4.62],["c",.3,-.12,.69,-.03,.93,.15],["c",.12,.12,.36,.45,.51,.78],["c",.9,1.77,.54,4.05,-1.08,6.75],["c",-.36,.63,-.87,1.38,-.96,1.44],["c",-.18,.12,-.42,.06,-.54,-.12],["c",-.09,-.18,-.09,-.3,.12,-.6],["c",.96,-1.44,1.44,-2.97,1.38,-4.35],["c",-.06,-.93,-.3,-1.68,-.78,-2.46],["c",-.27,-.39,-.33,-.63,-.24,-.96],["c",.09,-.27,.36,-.54,.66,-.63],["z"]],w:3.042,h:9.237},"scripts.roll":{d:[["M",1.95,-6],["c",.21,-.09,.36,-.09,.57,0],["c",.39,.15,.63,.39,1.47,1.35],["c",.66,.75,.78,.87,1.08,1.05],["c",.75,.45,1.65,.42,2.4,-.06],["c",.12,-.09,.27,-.27,.54,-.6],["c",.42,-.54,.51,-.63,.69,-.63],["c",.09,0,.3,.12,.36,.21],["c",.09,.12,.12,.3,.03,.42],["c",-.06,.12,-3.15,3.9,-3.3,4.08],["c",-.06,.06,-.18,.12,-.27,.18],["c",-.27,.12,-.6,.06,-.99,-.27],["c",-.27,-.21,-.42,-.39,-1.08,-1.14],["c",-.63,-.72,-.81,-.9,-1.17,-1.08],["c",-.36,-.18,-.57,-.21,-.99,-.21],["c",-.39,0,-.63,.03,-.93,.18],["c",-.36,.15,-.51,.27,-.9,.81],["c",-.24,.27,-.45,.51,-.48,.54],["c",-.12,.09,-.27,.06,-.39,0],["c",-.24,-.15,-.33,-.39,-.21,-.6],["c",.09,-.12,3.18,-3.87,3.33,-4.02],["c",.06,-.06,.18,-.15,.24,-.21],["z"]],w:10.817,h:6.125},"scripts.prall":{d:[["M",-4.38,-3.69],["c",.06,-.03,.18,-.06,.24,-.06],["c",.3,0,.27,-.03,1.89,1.95],["l",1.53,1.83],["c",.03,0,.57,-.84,1.23,-1.83],["c",1.14,-1.68,1.23,-1.83,1.35,-1.89],["c",.06,-.03,.18,-.06,.24,-.06],["c",.3,0,.27,-.03,1.89,1.95],["l",1.53,1.83],["l",.48,-.69],["c",.51,-.78,.54,-.84,.69,-.9],["c",.42,-.18,.87,.15,.81,.6],["c",-.03,.12,-.3,.51,-1.5,2.37],["c",-1.38,2.07,-1.5,2.22,-1.62,2.28],["c",-.06,.03,-.18,.06,-.24,.06],["c",-.3,0,-.27,.03,-1.89,-1.95],["l",-1.53,-1.83],["c",-.03,0,-.57,.84,-1.23,1.83],["c",-1.14,1.68,-1.23,1.83,-1.35,1.89],["c",-.06,.03,-.18,.06,-.24,.06],["c",-.3,0,-.27,.03,-1.89,-1.95],["l",-1.53,-1.83],["l",-.48,.69],["c",-.51,.78,-.54,.84,-.69,.9],["c",-.42,.18,-.87,-.15,-.81,-.6],["c",.03,-.12,.3,-.51,1.5,-2.37],["c",1.38,-2.07,1.5,-2.22,1.62,-2.28],["z"]],w:15.011,h:7.5},"scripts.arpeggio":{d:[["M",1.5,0],["c",1.5,2,1.5,3,1.5,3],["s",0,1,-2,1.5],["s",-.5,3,1,5.5],["l",1.5,0],["s",-1.75,-2,-1.9,-3.25],["s",2.15,-.6,2.95,-1.6],["s",.45,-1,.5,-1.25],["s",0,-1,-2,-3.9],["l",-1.5,0],["z"]],w:5,h:10},"scripts.mordent":{d:[["M",-.21,-4.95],["c",.27,-.15,.63,0,.75,.27],["c",.06,.12,.06,.24,.06,1.44],["l",0,1.29],["l",.57,-.84],["c",.51,-.75,.57,-.84,.69,-.9],["c",.06,-.03,.18,-.06,.24,-.06],["c",.3,0,.27,-.03,1.89,1.95],["l",1.53,1.83],["l",.48,-.69],["c",.51,-.78,.54,-.84,.69,-.9],["c",.42,-.18,.87,.15,.81,.6],["c",-.03,.12,-.3,.51,-1.5,2.37],["c",-1.38,2.07,-1.5,2.22,-1.62,2.28],["c",-.06,.03,-.18,.06,-.24,.06],["c",-.3,0,-.27,.03,-1.83,-1.89],["c",-.81,-.99,-1.5,-1.8,-1.53,-1.86],["c",-.06,-.03,-.06,-.03,-.12,.03],["c",-.06,.06,-.06,.15,-.06,2.28],["c",0,1.95,0,2.25,-.06,2.34],["c",-.18,.45,-.81,.48,-1.05,.03],["c",-.03,-.06,-.06,-.24,-.06,-1.41],["l",0,-1.35],["l",-.57,.84],["c",-.54,.78,-.6,.87,-.72,.93],["c",-.06,.03,-.18,.06,-.24,.06],["c",-.3,0,-.27,.03,-1.89,-1.95],["l",-1.53,-1.83],["l",-.48,.69],["c",-.51,.78,-.54,.84,-.69,.9],["c",-.42,.18,-.87,-.15,-.81,-.6],["c",.03,-.12,.3,-.51,1.5,-2.37],["c",1.38,-2.07,1.5,-2.22,1.62,-2.28],["c",.06,-.03,.18,-.06,.24,-.06],["c",.3,0,.27,-.03,1.89,1.95],["l",1.53,1.83],["c",.03,0,.06,-.06,.09,-.09],["c",.06,-.12,.06,-.15,.06,-2.28],["c",0,-1.92,0,-2.22,.06,-2.31],["c",.06,-.15,.15,-.24,.3,-.3],["z"]],w:15.011,h:10.012},"flags.u8th":{d:[["M",-.42,3.75],["l",0,-3.75],["l",.21,0],["l",.21,0],["l",0,.18],["c",0,.3,.06,.84,.12,1.23],["c",.24,1.53,.9,3.12,2.13,5.16],["l",.99,1.59],["c",.87,1.44,1.38,2.34,1.77,3.09],["c",.81,1.68,1.2,3.06,1.26,4.53],["c",.03,1.53,-.21,3.27,-.75,5.01],["c",-.21,.69,-.51,1.5,-.6,1.59],["c",-.09,.12,-.27,.21,-.42,.21],["c",-.15,0,-.42,-.12,-.51,-.21],["c",-.15,-.18,-.18,-.42,-.09,-.66],["c",.15,-.33,.45,-1.2,.57,-1.62],["c",.42,-1.38,.6,-2.58,.6,-3.9],["c",0,-.66,0,-.81,-.06,-1.11],["c",-.39,-2.07,-1.8,-4.26,-4.59,-7.14],["l",-.42,-.45],["l",-.21,0],["l",-.21,0],["l",0,-3.75],["z"]],w:6.692,h:22.59},"flags.u16th":{d:[["M",-.42,7.5],["l",0,-7.5],["l",.21,0],["l",.21,0],["l",0,.39],["c",.06,1.08,.39,2.19,.99,3.39],["c",.45,.9,.87,1.59,1.95,3.12],["c",1.29,1.86,1.77,2.64,2.22,3.57],["c",.45,.93,.72,1.8,.87,2.64],["c",.06,.51,.06,1.5,0,1.92],["c",-.12,.6,-.3,1.2,-.54,1.71],["l",-.09,.24],["l",.18,.45],["c",.51,1.2,.72,2.22,.69,3.42],["c",-.06,1.53,-.39,3.03,-.99,4.53],["c",-.3,.75,-.36,.81,-.57,.9],["c",-.15,.09,-.33,.06,-.48,0],["c",-.18,-.09,-.27,-.18,-.33,-.33],["c",-.09,-.18,-.06,-.3,.12,-.75],["c",.66,-1.41,1.02,-2.88,1.08,-4.32],["c",0,-.6,-.03,-1.05,-.18,-1.59],["c",-.3,-1.2,-.99,-2.4,-2.25,-3.87],["c",-.42,-.48,-1.53,-1.62,-2.19,-2.22],["l",-.45,-.42],["l",-.03,1.11],["l",0,1.11],["l",-.21,0],["l",-.21,0],["l",0,-7.5],["z"],["m",1.65,.09],["c",-.3,-.3,-.69,-.72,-.9,-.87],["l",-.33,-.33],["l",0,.15],["c",0,.3,.06,.81,.15,1.26],["c",.27,1.29,.87,2.61,2.04,4.29],["c",.15,.24,.6,.87,.96,1.38],["l",1.08,1.53],["l",.42,.63],["c",.03,0,.12,-.36,.21,-.72],["c",.06,-.33,.06,-1.2,0,-1.62],["c",-.33,-1.71,-1.44,-3.48,-3.63,-5.7],["z"]],w:6.693,h:26.337},"flags.u32nd":{d:[["M",-.42,11.25],["l",0,-11.25],["l",.21,0],["l",.21,0],["l",0,.36],["c",.09,1.68,.69,3.27,2.07,5.46],["l",.87,1.35],["c",1.02,1.62,1.47,2.37,1.86,3.18],["c",.48,1.02,.78,1.92,.93,2.88],["c",.06,.48,.06,1.5,0,1.89],["c",-.09,.42,-.21,.87,-.36,1.26],["l",-.12,.3],["l",.15,.39],["c",.69,1.56,.84,2.88,.54,4.38],["c",-.09,.45,-.27,1.08,-.45,1.47],["l",-.12,.24],["l",.18,.36],["c",.33,.72,.57,1.56,.69,2.34],["c",.12,1.02,-.06,2.52,-.42,3.84],["c",-.27,.93,-.75,2.13,-.93,2.31],["c",-.18,.15,-.45,.18,-.66,.09],["c",-.18,-.09,-.27,-.18,-.33,-.33],["c",-.09,-.18,-.06,-.3,.06,-.6],["c",.21,-.36,.42,-.9,.57,-1.38],["c",.51,-1.41,.69,-3.06,.48,-4.08],["c",-.15,-.81,-.57,-1.68,-1.2,-2.55],["c",-.72,-.99,-1.83,-2.13,-3.3,-3.33],["l",-.48,-.42],["l",-.03,1.53],["l",0,1.56],["l",-.21,0],["l",-.21,0],["l",0,-11.25],["z"],["m",1.26,-3.96],["c",-.27,-.3,-.54,-.6,-.66,-.72],["l",-.18,-.21],["l",0,.42],["c",.06,.87,.24,1.74,.66,2.67],["c",.36,.87,.96,1.86,1.92,3.18],["c",.21,.33,.63,.87,.87,1.23],["c",.27,.39,.6,.84,.75,1.08],["l",.27,.39],["l",.03,-.12],["c",.12,-.45,.15,-1.05,.09,-1.59],["c",-.27,-1.86,-1.38,-3.78,-3.75,-6.33],["z"],["m",-.27,6.09],["c",-.27,-.21,-.48,-.42,-.51,-.45],["c",-.06,-.03,-.06,-.03,-.06,.21],["c",0,.9,.3,2.04,.81,3.09],["c",.48,1.02,.96,1.77,2.37,3.63],["c",.6,.78,1.05,1.44,1.29,1.77],["c",.06,.12,.15,.21,.15,.18],["c",.03,-.03,.18,-.57,.24,-.87],["c",.06,-.45,.06,-1.32,-.03,-1.74],["c",-.09,-.48,-.24,-.9,-.51,-1.44],["c",-.66,-1.35,-1.83,-2.7,-3.75,-4.38],["z"]],w:6.697,h:32.145},"flags.u64th":{d:[["M",-.42,15],["l",0,-15],["l",.21,0],["l",.21,0],["l",0,.36],["c",.06,1.2,.39,2.37,1.02,3.66],["c",.39,.81,.84,1.56,1.8,3.09],["c",.81,1.26,1.05,1.68,1.35,2.22],["c",.87,1.5,1.35,2.79,1.56,4.08],["c",.06,.54,.06,1.56,-.03,2.04],["c",-.09,.48,-.21,.99,-.36,1.35],["l",-.12,.27],["l",.12,.27],["c",.09,.15,.21,.45,.27,.66],["c",.69,1.89,.63,3.66,-.18,5.46],["l",-.18,.39],["l",.15,.33],["c",.3,.66,.51,1.44,.63,2.1],["c",.06,.48,.06,1.35,0,1.71],["c",-.15,.57,-.42,1.2,-.78,1.68],["l",-.21,.27],["l",.18,.33],["c",.57,1.05,.93,2.13,1.02,3.18],["c",.06,.72,0,1.83,-.21,2.79],["c",-.18,1.02,-.63,2.34,-1.02,3.09],["c",-.15,.33,-.48,.45,-.78,.3],["c",-.18,-.09,-.27,-.18,-.33,-.33],["c",-.09,-.18,-.06,-.3,.03,-.54],["c",.75,-1.5,1.23,-3.45,1.17,-4.89],["c",-.06,-1.02,-.42,-2.01,-1.17,-3.15],["c",-.48,-.72,-1.02,-1.35,-1.89,-2.22],["c",-.57,-.57,-1.56,-1.5,-1.92,-1.77],["l",-.12,-.09],["l",0,1.68],["l",0,1.68],["l",-.21,0],["l",-.21,0],["l",0,-15],["z"],["m",.93,-8.07],["c",-.27,-.3,-.48,-.54,-.51,-.54],["c",0,0,0,.69,.03,1.02],["c",.15,1.47,.75,2.94,2.04,4.83],["l",1.08,1.53],["c",.39,.57,.84,1.2,.99,1.44],["c",.15,.24,.3,.45,.3,.45],["c",0,0,.03,-.09,.06,-.21],["c",.36,-1.59,-.15,-3.33,-1.47,-5.4],["c",-.63,-.93,-1.35,-1.83,-2.52,-3.12],["z"],["m",.06,6.72],["c",-.24,-.21,-.48,-.42,-.51,-.45],["l",-.06,-.06],["l",0,.33],["c",0,1.2,.3,2.34,.93,3.6],["c",.45,.9,.96,1.68,2.25,3.51],["c",.39,.54,.84,1.17,1.02,1.44],["c",.21,.33,.33,.51,.33,.48],["c",.06,-.09,.21,-.63,.3,-.99],["c",.06,-.33,.06,-.45,.06,-.96],["c",0,-.6,-.03,-.84,-.18,-1.35],["c",-.3,-1.08,-1.02,-2.28,-2.13,-3.57],["c",-.39,-.45,-1.44,-1.47,-2.01,-1.98],["z"],["m",0,6.72],["c",-.24,-.21,-.48,-.39,-.51,-.42],["l",-.06,-.06],["l",0,.33],["c",0,1.41,.45,2.82,1.38,4.35],["c",.42,.72,.72,1.14,1.86,2.73],["c",.36,.45,.75,.99,.87,1.2],["c",.15,.21,.3,.36,.3,.36],["c",.06,0,.3,-.48,.39,-.75],["c",.09,-.36,.12,-.63,.12,-1.05],["c",-.06,-1.05,-.45,-2.04,-1.2,-3.18],["c",-.57,-.87,-1.11,-1.53,-2.07,-2.49],["c",-.36,-.33,-.84,-.78,-1.08,-1.02],["z"]],w:6.682,h:39.694},"flags.d8th":{d:[["M",5.67,-21.63],["c",.24,-.12,.54,-.06,.69,.15],["c",.06,.06,.21,.36,.39,.66],["c",.84,1.77,1.26,3.36,1.32,5.1],["c",.03,1.29,-.21,2.37,-.81,3.63],["c",-.6,1.23,-1.26,2.13,-3.21,4.38],["c",-1.35,1.53,-1.86,2.19,-2.4,2.97],["c",-.63,.93,-1.11,1.92,-1.38,2.79],["c",-.15,.54,-.27,1.35,-.27,1.8],["l",0,.15],["l",-.21,0],["l",-.21,0],["l",0,-3.75],["l",0,-3.75],["l",.21,0],["l",.21,0],["l",.48,-.3],["c",1.83,-1.11,3.12,-2.1,4.17,-3.12],["c",.78,-.81,1.32,-1.53,1.71,-2.31],["c",.45,-.93,.6,-1.74,.51,-2.88],["c",-.12,-1.56,-.63,-3.18,-1.47,-4.68],["c",-.12,-.21,-.15,-.33,-.06,-.51],["c",.06,-.15,.15,-.24,.33,-.33],["z"]],w:8.492,h:21.691},"flags.ugrace":{d:[["M",6.03,6.93],["c",.15,-.09,.33,-.06,.51,0],["c",.15,.09,.21,.15,.3,.33],["c",.09,.18,.06,.39,-.03,.54],["c",-.06,.15,-10.89,8.88,-11.07,8.97],["c",-.15,.09,-.33,.06,-.48,0],["c",-.18,-.09,-.24,-.15,-.33,-.33],["c",-.09,-.18,-.06,-.39,.03,-.54],["c",.06,-.15,10.89,-8.88,11.07,-8.97],["z"]],w:12.019,h:9.954},"flags.dgrace":{d:[["M",-6.06,-15.93],["c",.18,-.09,.33,-.12,.48,-.06],["c",.18,.09,14.01,8.04,14.1,8.1],["c",.12,.12,.18,.33,.18,.51],["c",-.03,.21,-.15,.39,-.36,.48],["c",-.18,.09,-.33,.12,-.48,.06],["c",-.18,-.09,-14.01,-8.04,-14.1,-8.1],["c",-.12,-.12,-.18,-.33,-.18,-.51],["c",.03,-.21,.15,-.39,.36,-.48],["z"]],w:15.12,h:9.212},"flags.d16th":{d:[["M",6.84,-22.53],["c",.27,-.12,.57,-.06,.72,.15],["c",.15,.15,.33,.87,.45,1.56],["c",.06,.33,.06,1.35,0,1.65],["c",-.06,.33,-.15,.78,-.27,1.11],["c",-.12,.33,-.45,.96,-.66,1.32],["l",-.18,.27],["l",.09,.18],["c",.48,1.02,.72,2.25,.69,3.3],["c",-.06,1.23,-.42,2.28,-1.26,3.45],["c",-.57,.87,-.99,1.32,-3,3.39],["c",-1.56,1.56,-2.22,2.4,-2.76,3.45],["c",-.42,.84,-.66,1.8,-.66,2.55],["l",0,.15],["l",-.21,0],["l",-.21,0],["l",0,-7.5],["l",0,-7.5],["l",.21,0],["l",.21,0],["l",0,1.14],["l",0,1.11],["l",.27,-.15],["c",1.11,-.57,1.77,-.99,2.52,-1.47],["c",2.37,-1.56,3.69,-3.15,4.05,-4.83],["c",.03,-.18,.03,-.39,.03,-.78],["c",0,-.6,-.03,-.93,-.24,-1.5],["c",-.06,-.18,-.12,-.39,-.15,-.45],["c",-.03,-.24,.12,-.48,.36,-.6],["z"],["m",-.63,7.5],["c",-.06,-.18,-.15,-.36,-.15,-.36],["c",-.03,0,-.03,.03,-.06,.06],["c",-.06,.12,-.96,1.02,-1.95,1.98],["c",-.63,.57,-1.26,1.17,-1.44,1.35],["c",-1.53,1.62,-2.28,2.85,-2.55,4.32],["c",-.03,.18,-.03,.54,-.06,.99],["l",0,.69],["l",.18,-.09],["c",.93,-.54,2.1,-1.29,2.82,-1.83],["c",.69,-.51,1.02,-.81,1.53,-1.29],["c",1.86,-1.89,2.37,-3.66,1.68,-5.82],["z"]],w:8.475,h:22.591},"flags.d32nd":{d:[["M",6.84,-29.13],["c",.27,-.12,.57,-.06,.72,.15],["c",.12,.12,.27,.63,.36,1.11],["c",.33,1.59,.06,3.06,-.81,4.47],["l",-.18,.27],["l",.09,.15],["c",.12,.24,.33,.69,.45,1.05],["c",.63,1.83,.45,3.57,-.57,5.22],["l",-.18,.3],["l",.15,.27],["c",.42,.87,.6,1.71,.57,2.61],["c",-.06,1.29,-.48,2.46,-1.35,3.78],["c",-.54,.81,-.93,1.29,-2.46,3],["c",-.51,.54,-1.05,1.17,-1.26,1.41],["c",-1.56,1.86,-2.25,3.36,-2.37,5.01],["l",0,.33],["l",-.21,0],["l",-.21,0],["l",0,-11.25],["l",0,-11.25],["l",.21,0],["l",.21,0],["l",0,1.35],["l",.03,1.35],["l",.78,-.39],["c",1.38,-.69,2.34,-1.26,3.24,-1.92],["c",1.38,-1.02,2.28,-2.13,2.64,-3.21],["c",.15,-.48,.18,-.72,.18,-1.29],["c",0,-.57,-.06,-.9,-.24,-1.47],["c",-.06,-.18,-.12,-.39,-.15,-.45],["c",-.03,-.24,.12,-.48,.36,-.6],["z"],["m",-.63,7.2],["c",-.09,-.18,-.12,-.21,-.12,-.15],["c",-.03,.09,-1.02,1.08,-2.04,2.04],["c",-1.17,1.08,-1.65,1.56,-2.07,2.04],["c",-.84,.96,-1.38,1.86,-1.68,2.76],["c",-.21,.57,-.27,.99,-.3,1.65],["l",0,.54],["l",.66,-.33],["c",3.57,-1.86,5.49,-3.69,5.94,-5.7],["c",.06,-.39,.06,-1.2,-.03,-1.65],["c",-.06,-.39,-.24,-.9,-.36,-1.2],["z"],["m",-.06,7.2],["c",-.06,-.15,-.12,-.33,-.15,-.45],["l",-.06,-.18],["l",-.18,.21],["l",-1.83,1.83],["c",-.87,.9,-1.77,1.8,-1.95,2.01],["c",-1.08,1.29,-1.62,2.31,-1.89,3.51],["c",-.06,.3,-.06,.51,-.09,.93],["l",0,.57],["l",.09,-.06],["c",.75,-.45,1.89,-1.26,2.52,-1.74],["c",.81,-.66,1.74,-1.53,2.22,-2.16],["c",1.26,-1.53,1.68,-3.06,1.32,-4.47],["z"]],w:8.385,h:29.191},"flags.d64th":{d:[["M",7.08,-32.88],["c",.3,-.12,.66,-.03,.78,.24],["c",.18,.33,.27,2.1,.15,2.64],["c",-.09,.39,-.21,.78,-.39,1.08],["l",-.15,.3],["l",.09,.27],["c",.03,.12,.09,.45,.12,.69],["c",.27,1.44,.18,2.55,-.3,3.6],["l",-.12,.33],["l",.06,.42],["c",.27,1.35,.33,2.82,.21,3.63],["c",-.12,.6,-.3,1.23,-.57,1.8],["l",-.15,.27],["l",.03,.42],["c",.06,1.02,.06,2.7,.03,3.06],["c",-.15,1.47,-.66,2.76,-1.74,4.41],["c",-.45,.69,-.75,1.11,-1.74,2.37],["c",-1.05,1.38,-1.5,1.98,-1.95,2.73],["c",-.93,1.5,-1.38,2.82,-1.44,4.2],["l",0,.42],["l",-.21,0],["l",-.21,0],["l",0,-15],["l",0,-15],["l",.21,0],["l",.21,0],["l",0,1.86],["l",0,1.89],["c",0,0,.21,-.03,.45,-.09],["c",2.22,-.39,4.08,-1.11,5.19,-2.01],["c",.63,-.54,1.02,-1.14,1.2,-1.8],["c",.06,-.3,.06,-1.14,-.03,-1.65],["c",-.03,-.18,-.06,-.39,-.09,-.48],["c",-.03,-.24,.12,-.48,.36,-.6],["z"],["m",-.45,6.15],["c",-.03,-.18,-.06,-.42,-.06,-.54],["l",-.03,-.18],["l",-.33,.3],["c",-.42,.36,-.87,.72,-1.68,1.29],["c",-1.98,1.38,-2.25,1.59,-2.85,2.16],["c",-.75,.69,-1.23,1.44,-1.47,2.19],["c",-.15,.45,-.18,.63,-.21,1.35],["l",0,.66],["l",.39,-.18],["c",1.83,-.9,3.45,-1.95,4.47,-2.91],["c",.93,-.9,1.53,-1.83,1.74,-2.82],["c",.06,-.33,.06,-.87,.03,-1.32],["z"],["m",-.27,4.86],["c",-.03,-.21,-.06,-.36,-.06,-.36],["c",0,-.03,-.12,.09,-.24,.24],["c",-.39,.48,-.99,1.08,-2.16,2.19],["c",-1.47,1.38,-1.92,1.83,-2.46,2.49],["c",-.66,.87,-1.08,1.74,-1.29,2.58],["c",-.09,.42,-.15,.87,-.15,1.44],["l",0,.54],["l",.48,-.33],["c",1.5,-1.02,2.58,-1.89,3.51,-2.82],["c",1.47,-1.47,2.25,-2.85,2.4,-4.26],["c",.03,-.39,.03,-1.17,-.03,-1.71],["z"],["m",-.66,7.68],["c",.03,-.15,.03,-.6,.03,-.99],["l",0,-.72],["l",-.27,.33],["l",-1.74,1.98],["c",-1.77,1.92,-2.43,2.76,-2.97,3.9],["c",-.51,1.02,-.72,1.77,-.75,2.91],["c",0,.63,0,.63,.06,.6],["c",.03,-.03,.3,-.27,.63,-.54],["c",.66,-.6,1.86,-1.8,2.31,-2.31],["c",1.65,-1.89,2.52,-3.54,2.7,-5.16],["z"]],w:8.485,h:32.932},"clefs.C":{d:[["M",.06,-14.94],["l",.09,-.06],["l",1.92,0],["l",1.92,0],["l",.09,.06],["l",.06,.09],["l",0,14.85],["l",0,14.82],["l",-.06,.09],["l",-.09,.06],["l",-1.92,0],["l",-1.92,0],["l",-.09,-.06],["l",-.06,-.09],["l",0,-14.82],["l",0,-14.85],["z"],["m",5.37,0],["c",.09,-.06,.09,-.06,.57,-.06],["c",.45,0,.45,0,.54,.06],["l",.06,.09],["l",0,7.14],["l",0,7.11],["l",.09,-.06],["c",.18,-.18,.72,-.84,.96,-1.2],["c",.3,-.45,.66,-1.17,.84,-1.65],["c",.36,-.9,.57,-1.83,.6,-2.79],["c",.03,-.48,.03,-.54,.09,-.63],["c",.12,-.18,.36,-.21,.54,-.12],["c",.18,.09,.21,.15,.24,.66],["c",.06,.87,.21,1.56,.57,2.22],["c",.51,1.02,1.26,1.68,2.22,1.92],["c",.21,.06,.33,.06,.78,.06],["c",.45,0,.57,0,.84,-.06],["c",.45,-.12,.81,-.33,1.08,-.6],["c",.57,-.57,.87,-1.41,.99,-2.88],["c",.06,-.54,.06,-3,0,-3.57],["c",-.21,-2.58,-.84,-3.87,-2.16,-4.5],["c",-.48,-.21,-1.17,-.36,-1.77,-.36],["c",-.69,0,-1.29,.27,-1.5,.72],["c",-.06,.15,-.06,.21,-.06,.42],["c",0,.24,0,.3,.06,.45],["c",.12,.24,.24,.39,.63,.66],["c",.42,.3,.57,.48,.69,.72],["c",.06,.15,.06,.21,.06,.48],["c",0,.39,-.03,.63,-.21,.96],["c",-.3,.6,-.87,1.08,-1.5,1.26],["c",-.27,.06,-.87,.06,-1.14,0],["c",-.78,-.24,-1.44,-.87,-1.65,-1.68],["c",-.12,-.42,-.09,-1.17,.09,-1.71],["c",.51,-1.65,1.98,-2.82,3.81,-3.09],["c",.84,-.09,2.46,.03,3.51,.27],["c",2.22,.57,3.69,1.8,4.44,3.75],["c",.36,.93,.57,2.13,.57,3.36],["c",0,1.44,-.48,2.73,-1.38,3.81],["c",-1.26,1.5,-3.27,2.43,-5.28,2.43],["c",-.48,0,-.51,0,-.75,-.09],["c",-.15,-.03,-.48,-.21,-.78,-.36],["c",-.69,-.36,-.87,-.42,-1.26,-.42],["c",-.27,0,-.3,0,-.51,.09],["c",-.57,.3,-.81,.9,-.81,2.1],["c",0,1.23,.24,1.83,.81,2.13],["c",.21,.09,.24,.09,.51,.09],["c",.39,0,.57,-.06,1.26,-.42],["c",.3,-.15,.63,-.33,.78,-.36],["c",.24,-.09,.27,-.09,.75,-.09],["c",2.01,0,4.02,.93,5.28,2.4],["c",.9,1.11,1.38,2.4,1.38,3.84],["c",0,1.5,-.3,2.88,-.84,3.96],["c",-.78,1.59,-2.19,2.64,-4.17,3.15],["c",-1.05,.24,-2.67,.36,-3.51,.27],["c",-1.83,-.27,-3.3,-1.44,-3.81,-3.09],["c",-.18,-.54,-.21,-1.29,-.09,-1.74],["c",.15,-.6,.63,-1.2,1.23,-1.47],["c",.36,-.18,.57,-.21,.99,-.21],["c",.42,0,.63,.03,1.02,.21],["c",.42,.21,.84,.63,1.05,1.05],["c",.18,.36,.21,.6,.21,.96],["c",0,.3,0,.36,-.06,.51],["c",-.12,.24,-.27,.42,-.69,.72],["c",-.57,.42,-.69,.63,-.69,1.08],["c",0,.24,0,.3,.06,.45],["c",.12,.21,.3,.39,.57,.54],["c",.42,.18,.87,.21,1.53,.15],["c",1.08,-.15,1.8,-.57,2.34,-1.32],["c",.54,-.75,.84,-1.83,.99,-3.51],["c",.06,-.57,.06,-3.03,0,-3.57],["c",-.12,-1.47,-.42,-2.31,-.99,-2.88],["c",-.27,-.27,-.63,-.48,-1.08,-.6],["c",-.27,-.06,-.39,-.06,-.84,-.06],["c",-.45,0,-.57,0,-.78,.06],["c",-1.14,.27,-2.01,1.17,-2.46,2.49],["c",-.21,.57,-.3,.99,-.33,1.65],["c",-.03,.51,-.06,.57,-.24,.66],["c",-.12,.06,-.27,.06,-.39,0],["c",-.21,-.09,-.21,-.15,-.24,-.75],["c",-.09,-1.92,-.78,-3.72,-2.01,-5.19],["c",-.18,-.21,-.36,-.42,-.39,-.45],["l",-.09,-.06],["l",0,7.11],["l",0,7.14],["l",-.06,.09],["c",-.09,.06,-.09,.06,-.54,.06],["c",-.48,0,-.48,0,-.57,-.06],["l",-.06,-.09],["l",0,-14.82],["l",0,-14.85],["z"]],w:20.31,h:29.97},"clefs.F":{d:[["M",6.3,-7.8],["c",.36,-.03,1.65,0,2.13,.03],["c",3.6,.42,6.03,2.1,6.93,4.86],["c",.27,.84,.36,1.5,.36,2.58],["c",0,.9,-.03,1.35,-.18,2.16],["c",-.78,3.78,-3.54,7.08,-8.37,9.96],["c",-1.74,1.05,-3.87,2.13,-6.18,3.12],["c",-.39,.18,-.75,.33,-.81,.36],["c",-.06,.03,-.15,.06,-.18,.06],["c",-.15,0,-.33,-.18,-.33,-.33],["c",0,-.15,.06,-.21,.51,-.48],["c",3,-1.77,5.13,-3.21,6.84,-4.74],["c",.51,-.45,1.59,-1.5,1.95,-1.95],["c",1.89,-2.19,2.88,-4.32,3.15,-6.78],["c",.06,-.42,.06,-1.77,0,-2.19],["c",-.24,-2.01,-.93,-3.63,-2.04,-4.71],["c",-.63,-.63,-1.29,-1.02,-2.07,-1.2],["c",-1.62,-.39,-3.36,.15,-4.56,1.44],["c",-.54,.6,-1.05,1.47,-1.32,2.22],["l",-.09,.21],["l",.24,-.12],["c",.39,-.21,.63,-.24,1.11,-.24],["c",.3,0,.45,0,.66,.06],["c",1.92,.48,2.85,2.55,1.95,4.38],["c",-.45,.99,-1.41,1.62,-2.46,1.71],["c",-1.47,.09,-2.91,-.87,-3.39,-2.25],["c",-.18,-.57,-.21,-1.32,-.03,-2.28],["c",.39,-2.25,1.83,-4.2,3.81,-5.19],["c",.69,-.36,1.59,-.6,2.37,-.69],["z"],["m",11.58,2.52],["c",.84,-.21,1.71,.3,1.89,1.14],["c",.3,1.17,-.72,2.19,-1.89,1.89],["c",-.99,-.21,-1.5,-1.32,-1.02,-2.25],["c",.18,-.39,.6,-.69,1.02,-.78],["z"],["m",0,7.5],["c",.84,-.21,1.71,.3,1.89,1.14],["c",.21,.87,-.3,1.71,-1.14,1.89],["c",-.87,.21,-1.71,-.3,-1.89,-1.14],["c",-.21,-.84,.3,-1.71,1.14,-1.89],["z"]],w:20.153,h:23.142},"clefs.G":{d:[["M",9.69,-37.41],["c",.09,-.09,.24,-.06,.36,0],["c",.12,.09,.57,.6,.96,1.11],["c",1.77,2.34,3.21,5.85,3.57,8.73],["c",.21,1.56,.03,3.27,-.45,4.86],["c",-.69,2.31,-1.92,4.47,-4.23,7.44],["c",-.3,.39,-.57,.72,-.6,.75],["c",-.03,.06,0,.15,.18,.78],["c",.54,1.68,1.38,4.44,1.68,5.49],["l",.09,.42],["l",.39,0],["c",1.47,.09,2.76,.51,3.96,1.29],["c",1.83,1.23,3.06,3.21,3.39,5.52],["c",.09,.45,.12,1.29,.06,1.74],["c",-.09,1.02,-.33,1.83,-.75,2.73],["c",-.84,1.71,-2.28,3.06,-4.02,3.72],["l",-.33,.12],["l",.03,1.26],["c",0,1.74,-.06,3.63,-.21,4.62],["c",-.45,3.06,-2.19,5.49,-4.47,6.21],["c",-.57,.18,-.9,.21,-1.59,.21],["c",-.69,0,-1.02,-.03,-1.65,-.21],["c",-1.14,-.27,-2.13,-.84,-2.94,-1.65],["c",-.99,-.99,-1.56,-2.16,-1.71,-3.54],["c",-.09,-.81,.06,-1.53,.45,-2.13],["c",.63,-.99,1.83,-1.56,3,-1.53],["c",1.5,.09,2.64,1.32,2.73,2.94],["c",.06,1.47,-.93,2.7,-2.37,2.97],["c",-.45,.06,-.84,.03,-1.29,-.09],["l",-.21,-.09],["l",.09,.12],["c",.39,.54,.78,.93,1.32,1.26],["c",1.35,.87,3.06,1.02,4.35,.36],["c",1.44,-.72,2.52,-2.28,2.97,-4.35],["c",.15,-.66,.24,-1.5,.3,-3.03],["c",.03,-.84,.03,-2.94,0,-3],["c",-.03,0,-.18,0,-.36,.03],["c",-.66,.12,-.99,.12,-1.83,.12],["c",-1.05,0,-1.71,-.06,-2.61,-.3],["c",-4.02,-.99,-7.11,-4.35,-7.8,-8.46],["c",-.12,-.66,-.12,-.99,-.12,-1.83],["c",0,-.84,0,-1.14,.15,-1.92],["c",.36,-2.28,1.41,-4.62,3.3,-7.29],["l",2.79,-3.6],["c",.54,-.66,.96,-1.2,.96,-1.23],["c",0,-.03,-.09,-.33,-.18,-.69],["c",-.96,-3.21,-1.41,-5.28,-1.59,-7.68],["c",-.12,-1.38,-.15,-3.09,-.06,-3.96],["c",.33,-2.67,1.38,-5.07,3.12,-7.08],["c",.36,-.42,.99,-1.05,1.17,-1.14],["z"],["m",2.01,4.71],["c",-.15,-.3,-.3,-.54,-.3,-.54],["c",-.03,0,-.18,.09,-.3,.21],["c",-2.4,1.74,-3.87,4.2,-4.26,7.11],["c",-.06,.54,-.06,1.41,-.03,1.89],["c",.09,1.29,.48,3.12,1.08,5.22],["c",.15,.42,.24,.78,.24,.81],["c",0,.03,.84,-1.11,1.23,-1.68],["c",1.89,-2.73,2.88,-5.07,3.15,-7.53],["c",.09,-.57,.12,-1.74,.06,-2.37],["c",-.09,-1.23,-.27,-1.92,-.87,-3.12],["z"],["m",-2.94,20.7],["c",-.21,-.72,-.39,-1.32,-.42,-1.32],["c",0,0,-1.2,1.47,-1.86,2.37],["c",-2.79,3.63,-4.02,6.3,-4.35,9.3],["c",-.03,.21,-.03,.69,-.03,1.08],["c",0,.69,0,.75,.06,1.11],["c",.12,.54,.27,.99,.51,1.47],["c",.69,1.38,1.83,2.55,3.42,3.42],["c",.96,.54,2.07,.9,3.21,1.08],["c",.78,.12,2.04,.12,2.94,-.03],["c",.51,-.06,.45,-.03,.42,-.3],["c",-.24,-3.33,-.72,-6.33,-1.62,-10.08],["c",-.09,-.39,-.18,-.75,-.18,-.78],["c",-.03,-.03,-.42,0,-.81,.09],["c",-.9,.18,-1.65,.57,-2.22,1.14],["c",-.72,.72,-1.08,1.65,-1.05,2.64],["c",.06,.96,.48,1.83,1.23,2.58],["c",.36,.36,.72,.63,1.17,.9],["c",.33,.18,.36,.21,.42,.33],["c",.18,.42,-.18,.9,-.6,.87],["c",-.18,-.03,-.84,-.36,-1.26,-.63],["c",-.78,-.51,-1.38,-1.11,-1.86,-1.83],["c",-1.77,-2.7,-.99,-6.42,1.71,-8.19],["c",.3,-.21,.81,-.48,1.17,-.63],["c",.3,-.09,1.02,-.3,1.14,-.3],["c",.06,0,.09,0,.09,-.03],["c",.03,-.03,-.51,-1.92,-1.23,-4.26],["z"],["m",3.78,7.41],["c",-.18,-.03,-.36,-.06,-.39,-.06],["c",-.03,0,0,.21,.18,1.02],["c",.75,3.18,1.26,6.3,1.5,9.09],["c",.06,.72,0,.69,.51,.42],["c",.78,-.36,1.44,-.96,1.98,-1.77],["c",1.08,-1.62,1.2,-3.69,.3,-5.55],["c",-.81,-1.62,-2.31,-2.79,-4.08,-3.15],["z"]],w:19.051,h:57.057},"clefs.perc":{d:[["M",5.07,-7.44],["l",.09,-.06],["l",1.53,0],["l",1.53,0],["l",.09,.06],["l",.06,.09],["l",0,7.35],["l",0,7.32],["l",-.06,.09],["l",-.09,.06],["l",-1.53,0],["l",-1.53,0],["l",-.09,-.06],["l",-.06,-.09],["l",0,-7.32],["l",0,-7.35],["z"],["m",6.63,0],["l",.09,-.06],["l",1.53,0],["l",1.53,0],["l",.09,.06],["l",.06,.09],["l",0,7.35],["l",0,7.32],["l",-.06,.09],["l",-.09,.06],["l",-1.53,0],["l",-1.53,0],["l",-.09,-.06],["l",-.06,-.09],["l",0,-7.32],["l",0,-7.35],["z"]],w:21,h:14.97},"tab.big":{d:[["M",20.16,-21.66],["c",.24,-.09,.66,.09,.78,.36],["c",.09,.21,.09,.24,-.18,.54],["c",-.78,.81,-1.86,1.44,-2.94,1.71],["c",-.87,.24,-1.71,.24,-2.55,.03],["l",-.06,-.03],["l",-.18,.99],["c",-.33,1.98,-.75,4.26,-.96,5.04],["c",-.42,1.65,-1.26,3.18,-2.28,4.14],["c",-.57,.57,-1.17,.9,-1.86,1.08],["c",-.18,.06,-.33,.06,-.66,.06],["c",-.54,0,-.78,-.03,-1.23,-.27],["c",-.39,-.18,-.66,-.39,-1.38,-.99],["c",-.3,-.24,-.66,-.51,-.75,-.57],["c",-.21,-.15,-.27,-.24,-.24,-.45],["c",.06,-.27,.36,-.6,.6,-.66],["c",.18,-.03,.33,.06,.9,.57],["c",.48,.42,.72,.57,.93,.69],["c",.66,.33,1.38,.21,1.95,-.36],["c",.63,-.6,1.05,-1.62,1.23,-3],["c",.03,-.18,.09,-.66,.09,-1.11],["c",.09,-1.56,.33,-3.81,.57,-5.49],["c",.06,-.33,.09,-.63,.09,-.63],["c",-.03,-.03,-.81,-.12,-1.02,-.12],["c",-.57,0,-1.32,.12,-1.8,.33],["c",-.87,.3,-1.35,.78,-1.5,1.41],["c",-.18,.63,.09,1.26,.66,1.65],["c",.12,.06,.15,.12,.18,.24],["c",.09,.27,.06,.57,-.09,.75],["c",-.03,.06,-.12,.09,-.27,.15],["c",-.72,.21,-1.44,.15,-2.1,-.18],["c",-.54,-.27,-.96,-.66,-1.2,-1.14],["c",-.39,-.75,-.33,-1.74,.15,-2.52],["c",.27,-.42,.84,-.93,1.41,-1.23],["c",1.17,-.57,2.88,-.9,4.8,-.9],["c",.69,0,.78,0,1.08,.06],["c",.45,.09,1.11,.3,2.07,.6],["c",1.47,.48,1.83,.57,2.55,.54],["c",1.02,-.06,2.04,-.45,2.94,-1.11],["c",.12,-.09,.24,-.18,.27,-.18],["z"],["m",-5.88,13.05],["c",.21,-.03,.81,0,1.08,.06],["c",.48,.12,.9,.42,.99,.69],["c",.03,.09,.03,.15,0,.27],["c",0,.09,-.03,.57,-.06,1.08],["c",-.09,2.19,-.24,5.76,-.39,8.28],["c",-.06,1.53,-.06,1.77,.03,2.01],["c",.09,.18,.15,.24,.3,.3],["c",.24,.12,.54,.06,1.23,-.27],["c",.57,-.27,.66,-.3,.75,-.24],["c",.09,.06,.18,.3,.18,.45],["c",0,.33,-.15,.51,-.45,.63],["c",-.12,.03,-.39,.15,-.6,.27],["c",-1.17,.6,-1.38,.69,-1.8,.72],["c",-.45,.03,-.78,-.09,-1.08,-.39],["c",-.39,-.42,-.66,-1.2,-1.02,-3.12],["c",-.24,-1.23,-.36,-2.07,-.54,-3.75],["l",0,-.18],["l",-.36,.45],["c",-.6,.75,-1.32,1.59,-1.95,2.25],["c",-.15,.18,-.27,.3,-.27,.33],["c",0,0,.06,.09,.15,.18],["c",.24,.33,.6,.57,1.05,.69],["c",.18,.06,.3,.06,.69,.06],["l",.48,.03],["l",.06,.12],["c",.15,.27,.03,.72,-.21,.9],["c",-.18,.12,-.93,.27,-1.41,.27],["c",-.84,0,-1.59,-.3,-1.98,-.84],["l",-.12,-.15],["l",-.45,.42],["c",-.99,.87,-1.53,1.32,-2.16,1.74],["c",-.78,.51,-1.5,.84,-2.1,.93],["c",-.69,.12,-1.2,.03,-1.95,-.42],["c",-.21,-.12,-.51,-.27,-.66,-.36],["c",-.24,-.12,-.3,-.18,-.33,-.24],["c",-.12,-.27,.15,-.78,.45,-.93],["c",.24,-.12,.33,-.09,.9,.18],["c",.6,.3,.84,.39,1.2,.36],["c",.87,-.09,1.77,-.69,3.24,-2.31],["c",2.67,-2.85,4.59,-5.94,5.7,-9.15],["c",.15,-.45,.24,-.63,.42,-.81],["c",.21,-.24,.6,-.45,.99,-.51],["z"],["m",-3.99,16.05],["c",.18,0,.69,-.03,1.17,0],["c",3.27,.03,5.37,.75,6,2.07],["c",.45,.99,.12,2.4,-.81,3.42],["c",-.24,.27,-.57,.57,-.84,.75],["c",-.09,.06,-.18,.09,-.18,.12],["c",0,0,.18,.03,.42,.09],["c",1.23,.3,2.01,.81,2.37,1.59],["c",.27,.54,.3,1.32,.09,2.1],["c",-.12,.36,-.45,1.05,-.69,1.35],["c",-.87,1.17,-2.1,1.92,-3.54,2.25],["c",-.36,.06,-.48,.06,-.96,.06],["c",-.45,0,-.66,0,-.84,-.03],["c",-.84,-.18,-1.47,-.51,-2.07,-1.11],["c",-.33,-.33,-.45,-.51,-.45,-.63],["c",0,-.06,.03,-.15,.06,-.24],["c",.18,-.33,.69,-.6,.93,-.48],["c",.03,.03,.15,.12,.27,.24],["c",.39,.42,.99,.57,1.62,.45],["c",1.05,-.21,1.98,-1.02,2.31,-2.01],["c",.48,-1.53,-.48,-2.55,-2.58,-2.67],["c",-.21,0,-.36,-.03,-.42,-.06],["c",-.15,-.09,-.21,-.51,-.06,-.78],["c",.12,-.27,.24,-.33,.6,-.36],["c",.57,-.06,1.11,-.42,1.5,-.99],["c",.48,-.72,.54,-1.59,.18,-2.31],["c",-.12,-.21,-.45,-.54,-.69,-.69],["c",-.33,-.21,-.93,-.45,-1.35,-.51],["l",-.12,-.03],["l",-.06,.48],["c",-.54,2.94,-1.14,6.24,-1.29,6.75],["c",-.33,1.35,-.93,2.61,-1.65,3.6],["c",-.3,.36,-.81,.9,-1.14,1.14],["c",-.3,.24,-.84,.48,-1.14,.57],["c",-.33,.09,-.96,.09,-1.26,.03],["c",-.45,-.12,-.87,-.39,-1.53,-.96],["c",-.24,-.15,-.51,-.39,-.63,-.48],["c",-.3,-.21,-.33,-.33,-.21,-.63],["c",.12,-.18,.27,-.36,.42,-.45],["c",.27,-.12,.36,-.09,.87,.33],["c",.78,.6,1.08,.75,1.65,.72],["c",.45,-.03,.81,-.21,1.17,-.54],["c",.87,-.9,1.38,-2.85,1.38,-5.37],["c",0,-.6,.03,-1.11,.12,-2.04],["c",.06,-.69,.24,-2.01,.33,-2.58],["c",.06,-.24,.06,-.42,.06,-.42],["c",0,0,-.12,.03,-.21,.09],["c",-1.44,.57,-2.16,1.65,-1.74,2.55],["c",.09,.15,.18,.24,.27,.33],["c",.24,.21,.3,.27,.33,.39],["c",.06,.24,0,.63,-.15,.78],["c",-.09,.12,-.54,.21,-.96,.24],["c",-1.02,.03,-2.01,-.48,-2.43,-1.32],["c",-.21,-.45,-.27,-.9,-.15,-1.44],["c",.06,-.27,.21,-.66,.39,-.93],["c",.87,-1.29,3,-2.22,5.64,-2.43],["z"]],w:19.643,h:43.325},"tab.tiny":{d:[["M",16.02,-17.25],["c",.12,-.09,.15,-.09,.27,-.09],["c",.21,.03,.51,.3,.51,.45],["c",0,.06,-.12,.18,-.3,.36],["c",-1.11,1.08,-2.55,1.59,-3.84,1.41],["c",-.15,-.03,-.33,-.06,-.39,-.09],["c",-.06,-.03,-.09,-.03,-.12,-.03],["c",0,0,-.06,.42,-.15,.93],["c",-.33,2.01,-.66,3.69,-.84,4.26],["c",-.42,1.41,-1.23,2.67,-2.16,3.33],["c",-.27,.18,-.75,.42,-.99,.48],["c",-.3,.09,-.72,.09,-1.02,.06],["c",-.45,-.09,-.84,-.33,-1.53,-.9],["c",-.21,-.18,-.51,-.39,-.63,-.48],["c",-.27,-.21,-.3,-.24,-.3,-.36],["c",0,-.12,.09,-.36,.18,-.45],["c",.09,-.09,.27,-.18,.36,-.18],["c",.12,0,.3,.12,.66,.45],["c",.57,.51,.87,.69,1.23,.72],["c",.93,.06,1.68,-.78,1.98,-2.37],["c",.09,-.39,.15,-.75,.18,-1.53],["c",.06,-.99,.24,-2.79,.42,-4.05],["c",.03,-.3,.06,-.57,.06,-.6],["c",0,-.06,-.03,-.09,-.15,-.12],["c",-.9,-.18,-2.13,.06,-2.76,.57],["c",-.36,.3,-.51,.6,-.51,1.02],["c",0,.45,.15,.75,.48,.99],["c",.06,.06,.15,.18,.18,.24],["c",.12,.24,.03,.63,-.15,.69],["c",-.24,.12,-.6,.15,-.9,.15],["c",-.36,-.03,-.57,-.09,-.87,-.24],["c",-.78,-.36,-1.23,-1.11,-1.2,-1.92],["c",.12,-1.53,1.74,-2.49,4.62,-2.7],["c",1.2,-.09,1.47,-.03,3.33,.57],["c",.9,.3,1.14,.36,1.56,.39],["c",.45,0,.93,-.06,1.38,-.21],["c",.51,-.18,.81,-.33,1.41,-.75],["z"],["m",-4.68,10.38],["c",.39,-.06,.84,0,1.2,.15],["c",.24,.12,.36,.21,.45,.36],["l",.09,.09],["l",-.06,1.41],["c",-.09,2.19,-.18,3.96,-.27,5.49],["c",-.03,.78,-.06,1.59,-.06,1.86],["c",0,.42,0,.48,.06,.57],["c",.06,.18,.18,.24,.36,.27],["c",.18,0,.39,-.06,.84,-.27],["c",.45,-.21,.54,-.24,.63,-.18],["c",.12,.12,.15,.54,.03,.69],["c",-.03,.03,-.15,.12,-.27,.18],["c",-.15,.03,-.3,.12,-.36,.15],["c",-.87,.45,-1.02,.51,-1.26,.57],["c",-.33,.09,-.6,.06,-.84,-.06],["c",-.42,-.18,-.63,-.6,-.87,-1.44],["c",-.3,-1.23,-.57,-2.97,-.66,-4.08],["c",0,-.18,-.03,-.3,-.03,-.33],["l",-.06,.06],["c",-.18,.27,-1.11,1.38,-1.68,2.01],["l",-.33,.33],["l",.06,.09],["c",.06,.15,.27,.33,.48,.42],["c",.27,.18,.51,.24,.96,.27],["l",.39,0],["l",.03,.12],["c",.12,.21,.03,.57,-.15,.69],["c",-.03,.03,-.21,.09,-.36,.15],["c",-.27,.06,-.39,.06,-.75,.06],["c",-.48,0,-.75,-.03,-1.08,-.21],["c",-.21,-.12,-.51,-.36,-.57,-.48],["l",-.03,-.09],["l",-.39,.36],["c",-1.47,1.35,-2.49,1.98,-3.42,2.13],["c",-.54,.09,-.96,-.03,-1.62,-.39],["c",-.21,-.15,-.45,-.27,-.54,-.3],["c",-.18,-.09,-.21,-.21,-.12,-.45],["c",.06,-.27,.33,-.48,.54,-.48],["c",.03,0,.27,.09,.48,.21],["c",.48,.24,.69,.27,.99,.27],["c",.6,-.06,1.17,-.42,2.1,-1.35],["c",2.22,-2.22,4.02,-4.98,4.95,-7.59],["c",.21,-.57,.3,-.78,.48,-.93],["c",.15,-.15,.42,-.27,.66,-.33],["z"],["m",-3.06,12.84],["c",.27,-.03,1.68,0,2.01,.03],["c",1.92,.18,3.15,.69,3.63,1.5],["c",.18,.33,.24,.51,.21,.93],["c",0,.45,-.06,.72,-.24,1.11],["c",-.24,.51,-.69,1.02,-1.17,1.35],["c",-.21,.15,-.21,.15,-.12,.18],["c",.72,.15,1.11,.3,1.5,.57],["c",.39,.24,.63,.57,.75,.96],["c",.09,.3,.09,.96,0,1.29],["c",-.15,.57,-.39,1.05,-.78,1.5],["c",-.66,.75,-1.62,1.32,-2.61,1.53],["c",-.27,.06,-.42,.06,-.84,.06],["c",-.48,0,-.57,0,-.81,-.06],["c",-.6,-.18,-1.05,-.42,-1.47,-.81],["c",-.36,-.39,-.42,-.51,-.3,-.75],["c",.12,-.21,.39,-.39,.6,-.39],["c",.09,0,.15,.03,.33,.18],["c",.12,.12,.27,.24,.36,.27],["c",.96,.48,2.46,-.33,2.82,-1.5],["c",.24,-.81,-.03,-1.44,-.69,-1.77],["c",-.39,-.21,-1.02,-.33,-1.53,-.33],["c",-.18,0,-.21,0,-.27,-.09],["c",-.06,-.09,-.06,-.3,-.03,-.48],["c",.06,-.18,.18,-.36,.33,-.36],["c",.39,-.06,.51,-.09,.72,-.18],["c",.69,-.36,1.11,-1.23,.99,-2.01],["c",-.09,-.51,-.42,-.9,-.93,-1.17],["c",-.24,-.12,-.6,-.27,-.87,-.3],["c",-.09,-.03,-.09,-.03,-.12,.12],["c",0,.09,-.21,1.11,-.42,2.25],["c",-.66,3.75,-.72,3.99,-1.26,5.07],["c",-.9,1.89,-2.25,2.85,-3.48,2.61],["c",-.39,-.09,-.69,-.27,-1.38,-.84],["c",-.63,-.51,-.63,-.48,-.63,-.6],["c",0,-.18,.18,-.48,.39,-.57],["c",.21,-.12,.3,-.09,.81,.33],["c",.15,.15,.39,.3,.54,.36],["c",.18,.12,.27,.12,.48,.15],["c",.99,.06,1.71,-.78,2.04,-2.46],["c",.12,-.66,.18,-1.14,.21,-2.22],["c",.03,-1.23,.12,-2.25,.36,-3.63],["c",.03,-.24,.06,-.45,.06,-.48],["c",-.06,-.03,-.66,.27,-.9,.42],["c",-.06,.06,-.21,.18,-.33,.3],["c",-.57,.57,-.6,1.35,-.06,1.74],["c",.18,.12,.24,.24,.21,.51],["c",-.03,.3,-.15,.42,-.57,.48],["c",-1.11,.24,-2.22,-.42,-2.43,-1.38],["c",-.09,-.45,.03,-1.02,.3,-1.47],["c",.18,-.24,.6,-.63,.9,-.84],["c",.9,-.6,2.28,-1.02,3.69,-1.11],["z"]],w:15.709,h:34.656},"timesig.common":{d:[["M",6.66,-7.83],["c",.72,-.06,1.41,-.03,1.98,.09],["c",1.2,.27,2.34,.96,3.09,1.92],["c",.63,.81,1.08,1.86,1.14,2.73],["c",.06,1.02,-.51,1.92,-1.44,2.22],["c",-.24,.09,-.3,.09,-.63,.09],["c",-.33,0,-.42,0,-.63,-.06],["c",-.66,-.24,-1.14,-.63,-1.41,-1.2],["c",-.15,-.3,-.21,-.51,-.24,-.9],["c",-.06,-1.08,.57,-2.04,1.56,-2.37],["c",.18,-.06,.27,-.06,.63,-.06],["l",.45,0],["c",.06,.03,.09,.03,.09,0],["c",0,0,-.09,-.12,-.24,-.27],["c",-1.02,-1.11,-2.55,-1.68,-4.08,-1.5],["c",-1.29,.15,-2.04,.69,-2.4,1.74],["c",-.36,.93,-.42,1.89,-.42,5.37],["c",0,2.97,.06,3.96,.24,4.77],["c",.24,1.08,.63,1.68,1.41,2.07],["c",.81,.39,2.16,.45,3.18,.09],["c",1.29,-.45,2.37,-1.53,3.03,-2.97],["c",.15,-.33,.33,-.87,.39,-1.17],["c",.09,-.24,.15,-.36,.3,-.39],["c",.21,-.03,.42,.15,.39,.36],["c",-.06,.39,-.42,1.38,-.69,1.89],["c",-.96,1.8,-2.49,2.94,-4.23,3.18],["c",-.99,.12,-2.58,-.06,-3.63,-.45],["c",-.96,-.36,-1.71,-.84,-2.4,-1.5],["c",-1.11,-1.11,-1.8,-2.61,-2.04,-4.56],["c",-.06,-.6,-.06,-2.01,0,-2.61],["c",.24,-1.95,.9,-3.45,2.01,-4.56],["c",.69,-.66,1.44,-1.11,2.37,-1.47],["c",.63,-.24,1.47,-.42,2.22,-.48],["z"]],w:13.038,h:15.689},"timesig.cut":{d:[["M",6.24,-10.44],["c",.09,-.06,.09,-.06,.48,-.06],["c",.36,0,.36,0,.45,.06],["l",.06,.09],["l",0,1.23],["l",0,1.26],["l",.27,0],["c",1.26,0,2.49,.45,3.48,1.29],["c",1.05,.87,1.8,2.28,1.89,3.48],["c",.06,1.02,-.51,1.92,-1.44,2.22],["c",-.24,.09,-.3,.09,-.63,.09],["c",-.33,0,-.42,0,-.63,-.06],["c",-.66,-.24,-1.14,-.63,-1.41,-1.2],["c",-.15,-.3,-.21,-.51,-.24,-.9],["c",-.06,-1.08,.57,-2.04,1.56,-2.37],["c",.18,-.06,.27,-.06,.63,-.06],["l",.45,0],["c",.06,.03,.09,.03,.09,0],["c",0,-.03,-.45,-.51,-.66,-.69],["c",-.87,-.69,-1.83,-1.05,-2.94,-1.11],["l",-.42,0],["l",0,7.17],["l",0,7.14],["l",.42,0],["c",.69,-.03,1.23,-.18,1.86,-.51],["c",1.05,-.51,1.89,-1.47,2.46,-2.7],["c",.15,-.33,.33,-.87,.39,-1.17],["c",.09,-.24,.15,-.36,.3,-.39],["c",.21,-.03,.42,.15,.39,.36],["c",-.03,.24,-.21,.78,-.39,1.2],["c",-.96,2.37,-2.94,3.9,-5.13,3.9],["l",-.3,0],["l",0,1.26],["l",0,1.23],["l",-.06,.09],["c",-.09,.06,-.09,.06,-.45,.06],["c",-.39,0,-.39,0,-.48,-.06],["l",-.06,-.09],["l",0,-1.29],["l",0,-1.29],["l",-.21,-.03],["c",-1.23,-.21,-2.31,-.63,-3.21,-1.29],["c",-.15,-.09,-.45,-.36,-.66,-.57],["c",-1.11,-1.11,-1.8,-2.61,-2.04,-4.56],["c",-.06,-.6,-.06,-2.01,0,-2.61],["c",.24,-1.95,.93,-3.45,2.04,-4.59],["c",.42,-.39,.78,-.66,1.26,-.93],["c",.75,-.45,1.65,-.75,2.61,-.9],["l",.21,-.03],["l",0,-1.29],["l",0,-1.29],["z"],["m",-.06,10.44],["c",0,-5.58,0,-6.99,-.03,-6.99],["c",-.15,0,-.63,.27,-.87,.45],["c",-.45,.36,-.75,.93,-.93,1.77],["c",-.18,.81,-.24,1.8,-.24,4.74],["c",0,2.97,.06,3.96,.24,4.77],["c",.24,1.08,.66,1.68,1.41,2.07],["c",.12,.06,.3,.12,.33,.15],["l",.09,0],["l",0,-6.96],["z"]],w:13.038,h:20.97},"timesig.imperfectum":{d:[["M",13,-5],["a",8,8,0,1,0,0,10]],w:13.038,h:20.97},"timesig.imperfectum2":{d:[["M",13,-5],["a",8,8,0,1,0,0,10]],w:13.038,h:20.97},"timesig.perfectum":{d:[["M",13,-5],["a",8,8,0,1,0,0,10]],w:13.038,h:20.97},"timesig.perfectum2":{d:[["M",13,-5],["a",8,8,0,1,0,0,10]],w:13.038,h:20.97},f:{d:[["M",9.93,-14.28],["c",1.53,-.18,2.88,.45,3.12,1.5],["c",.12,.51,0,1.32,-.27,1.86],["c",-.15,.3,-.42,.57,-.63,.69],["c",-.69,.36,-1.56,.03,-1.83,-.69],["c",-.09,-.24,-.09,-.69,0,-.87],["c",.06,-.12,.21,-.24,.45,-.42],["c",.42,-.24,.57,-.45,.6,-.72],["c",.03,-.33,-.09,-.39,-.63,-.42],["c",-.3,0,-.45,0,-.6,.03],["c",-.81,.21,-1.35,.93,-1.74,2.46],["c",-.06,.27,-.48,2.25,-.48,2.31],["c",0,.03,.39,.03,.9,.03],["c",.72,0,.9,0,.99,.06],["c",.42,.15,.45,.72,.03,.9],["c",-.12,.06,-.24,.06,-1.17,.06],["l",-1.05,0],["l",-.78,2.55],["c",-.45,1.41,-.87,2.79,-.96,3.06],["c",-.87,2.37,-2.37,4.74,-3.78,5.91],["c",-1.05,.9,-2.04,1.23,-3.09,1.08],["c",-1.11,-.18,-1.89,-.78,-2.04,-1.59],["c",-.12,-.66,.15,-1.71,.54,-2.19],["c",.69,-.75,1.86,-.54,2.22,.39],["c",.06,.15,.09,.27,.09,.48],["c",0,.24,-.03,.27,-.12,.42],["c",-.03,.09,-.15,.18,-.27,.27],["c",-.09,.06,-.27,.21,-.36,.27],["c",-.24,.18,-.36,.36,-.39,.6],["c",-.03,.33,.09,.39,.63,.42],["c",.42,0,.63,-.03,.9,-.15],["c",.6,-.3,.96,-.96,1.38,-2.64],["c",.09,-.42,.63,-2.55,1.17,-4.77],["l",1.02,-4.08],["c",0,-.03,-.36,-.03,-.81,-.03],["c",-.72,0,-.81,0,-.93,-.06],["c",-.42,-.18,-.39,-.75,.03,-.9],["c",.09,-.06,.27,-.06,1.05,-.06],["l",.96,0],["l",0,-.09],["c",.06,-.18,.3,-.72,.51,-1.17],["c",1.2,-2.46,3.3,-4.23,5.34,-4.5],["z"]],w:16.155,h:19.445},m:{d:[["M",2.79,-8.91],["c",.09,0,.3,-.03,.45,-.03],["c",.24,.03,.3,.03,.45,.12],["c",.36,.15,.63,.54,.75,1.02],["l",.03,.21],["l",.33,-.3],["c",.69,-.69,1.38,-1.02,2.07,-1.02],["c",.27,0,.33,0,.48,.06],["c",.21,.09,.48,.36,.63,.6],["c",.03,.09,.12,.27,.18,.42],["c",.03,.15,.09,.27,.12,.27],["c",0,0,.09,-.09,.18,-.21],["c",.33,-.39,.87,-.81,1.29,-.99],["c",.78,-.33,1.47,-.21,2.01,.33],["c",.3,.33,.48,.69,.6,1.14],["c",.09,.42,.06,.54,-.54,3.06],["c",-.33,1.29,-.57,2.4,-.57,2.43],["c",0,.12,.09,.21,.21,.21],["c",.24,0,.75,-.3,1.2,-.72],["c",.45,-.39,.6,-.45,.78,-.27],["c",.18,.18,.09,.36,-.45,.87],["c",-1.05,.96,-1.83,1.47,-2.58,1.71],["c",-.93,.33,-1.53,.21,-1.8,-.33],["c",-.06,-.15,-.06,-.21,-.06,-.45],["c",0,-.24,.03,-.48,.6,-2.82],["c",.42,-1.71,.6,-2.64,.63,-2.79],["c",.03,-.57,-.3,-.75,-.84,-.48],["c",-.24,.12,-.54,.39,-.66,.63],["c",-.03,.09,-.42,1.38,-.9,3],["c",-.9,3.15,-.84,3,-1.14,3.15],["l",-.15,.09],["l",-.78,0],["c",-.6,0,-.78,0,-.84,-.06],["c",-.09,-.03,-.18,-.18,-.18,-.27],["c",0,-.03,.36,-1.38,.84,-2.97],["c",.57,-2.04,.81,-2.97,.84,-3.12],["c",.03,-.54,-.3,-.72,-.84,-.45],["c",-.24,.12,-.57,.42,-.66,.63],["c",-.06,.09,-.51,1.44,-1.05,2.97],["c",-.51,1.56,-.99,2.85,-.99,2.91],["c",-.06,.12,-.21,.24,-.36,.3],["c",-.12,.06,-.21,.06,-.9,.06],["c",-.6,0,-.78,0,-.84,-.06],["c",-.09,-.03,-.18,-.18,-.18,-.27],["c",0,-.03,.45,-1.38,.99,-2.97],["c",1.05,-3.18,1.05,-3.18,.93,-3.45],["c",-.12,-.27,-.39,-.3,-.72,-.15],["c",-.54,.27,-1.14,1.17,-1.56,2.4],["c",-.06,.15,-.15,.3,-.18,.36],["c",-.21,.21,-.57,.27,-.72,.09],["c",-.09,-.09,-.06,-.21,.06,-.63],["c",.48,-1.26,1.26,-2.46,2.01,-3.21],["c",.57,-.54,1.2,-.87,1.83,-1.02],["z"]],w:14.687,h:9.126},p:{d:[["M",1.92,-8.7],["c",.27,-.09,.81,-.06,1.11,.03],["c",.54,.18,.93,.51,1.17,.99],["c",.09,.15,.15,.33,.18,.36],["l",0,.12],["l",.3,-.27],["c",.66,-.6,1.35,-1.02,2.13,-1.2],["c",.21,-.06,.33,-.06,.78,-.06],["c",.45,0,.51,0,.84,.09],["c",1.29,.33,2.07,1.32,2.25,2.79],["c",.09,.81,-.09,2.01,-.45,2.79],["c",-.54,1.26,-1.86,2.55,-3.18,3.03],["c",-.45,.18,-.81,.24,-1.29,.24],["c",-.69,-.03,-1.35,-.18,-1.86,-.45],["c",-.3,-.15,-.51,-.18,-.69,-.09],["c",-.09,.03,-.18,.09,-.18,.12],["c",-.09,.12,-1.05,2.94,-1.05,3.06],["c",0,.24,.18,.48,.51,.63],["c",.18,.06,.54,.15,.75,.15],["c",.21,0,.36,.06,.42,.18],["c",.12,.18,.06,.42,-.12,.54],["c",-.09,.03,-.15,.03,-.78,0],["c",-1.98,-.15,-3.81,-.15,-5.79,0],["c",-.63,.03,-.69,.03,-.78,0],["c",-.24,-.15,-.24,-.57,.03,-.66],["c",.06,-.03,.48,-.09,.99,-.12],["c",.87,-.06,1.11,-.09,1.35,-.21],["c",.18,-.06,.33,-.18,.39,-.3],["c",.06,-.12,3.24,-9.42,3.27,-9.6],["c",.06,-.33,.03,-.57,-.15,-.69],["c",-.09,-.06,-.12,-.06,-.3,-.06],["c",-.69,.06,-1.53,1.02,-2.28,2.61],["c",-.09,.21,-.21,.45,-.27,.51],["c",-.09,.12,-.33,.24,-.48,.24],["c",-.18,0,-.36,-.15,-.36,-.3],["c",0,-.24,.78,-1.83,1.26,-2.55],["c",.72,-1.11,1.47,-1.74,2.28,-1.92],["z"],["m",5.37,1.47],["c",-.27,-.12,-.75,-.03,-1.14,.21],["c",-.75,.48,-1.47,1.68,-1.89,3.15],["c",-.45,1.47,-.42,2.34,0,2.7],["c",.45,.39,1.26,.21,1.83,-.36],["c",.51,-.51,.99,-1.68,1.38,-3.27],["c",.3,-1.17,.33,-1.74,.15,-2.13],["c",-.09,-.15,-.15,-.21,-.33,-.3],["z"]],w:14.689,h:13.127},r:{d:[["M",6.33,-9.12],["c",.27,-.03,.93,0,1.2,.06],["c",.84,.21,1.23,.81,1.02,1.53],["c",-.24,.75,-.9,1.17,-1.56,.96],["c",-.33,-.09,-.51,-.3,-.66,-.75],["c",-.03,-.12,-.09,-.24,-.12,-.3],["c",-.09,-.15,-.3,-.24,-.48,-.24],["c",-.57,0,-1.38,.54,-1.65,1.08],["c",-.06,.15,-.33,1.17,-.9,3.27],["c",-.57,2.31,-.81,3.12,-.87,3.21],["c",-.03,.06,-.12,.15,-.18,.21],["l",-.12,.06],["l",-.81,.03],["c",-.69,0,-.81,0,-.9,-.03],["c",-.09,-.06,-.18,-.21,-.18,-.3],["c",0,-.06,.39,-1.62,.9,-3.51],["c",.84,-3.24,.87,-3.45,.87,-3.72],["c",0,-.21,0,-.27,-.03,-.36],["c",-.12,-.15,-.21,-.24,-.42,-.24],["c",-.24,0,-.45,.15,-.78,.42],["c",-.33,.36,-.45,.54,-.72,1.14],["c",-.03,.12,-.21,.24,-.36,.27],["c",-.12,0,-.15,0,-.24,-.06],["c",-.18,-.12,-.18,-.21,-.06,-.54],["c",.21,-.57,.42,-.93,.78,-1.32],["c",.54,-.51,1.2,-.81,1.95,-.87],["c",.81,-.03,1.53,.3,1.92,.87],["l",.12,.18],["l",.09,-.09],["c",.57,-.45,1.41,-.84,2.19,-.96],["z"]],w:9.41,h:9.132},s:{d:[["M",4.47,-8.73],["c",.09,0,.36,-.03,.57,-.03],["c",.75,.03,1.29,.24,1.71,.63],["c",.51,.54,.66,1.26,.36,1.83],["c",-.24,.42,-.63,.57,-1.11,.42],["c",-.33,-.09,-.6,-.36,-.6,-.57],["c",0,-.03,.06,-.21,.15,-.39],["c",.12,-.21,.15,-.33,.18,-.48],["c",0,-.24,-.06,-.48,-.15,-.6],["c",-.15,-.21,-.42,-.24,-.75,-.15],["c",-.27,.06,-.48,.18,-.69,.36],["c",-.39,.39,-.51,.96,-.33,1.38],["c",.09,.21,.42,.51,.78,.72],["c",1.11,.69,1.59,1.11,1.89,1.68],["c",.21,.39,.24,.78,.15,1.29],["c",-.18,1.2,-1.17,2.16,-2.52,2.52],["c",-1.02,.24,-1.95,.12,-2.7,-.42],["c",-.72,-.51,-.99,-1.47,-.6,-2.19],["c",.24,-.48,.72,-.63,1.17,-.42],["c",.33,.18,.54,.45,.57,.81],["c",0,.21,-.03,.3,-.33,.51],["c",-.33,.24,-.39,.42,-.27,.69],["c",.06,.15,.21,.27,.45,.33],["c",.3,.09,.87,.09,1.2,0],["c",.75,-.21,1.23,-.72,1.29,-1.35],["c",.03,-.42,-.15,-.81,-.54,-1.2],["c",-.24,-.24,-.48,-.42,-1.41,-1.02],["c",-.69,-.42,-1.05,-.93,-1.05,-1.47],["c",0,-.39,.12,-.87,.3,-1.23],["c",.27,-.57,.78,-1.05,1.38,-1.35],["c",.24,-.12,.63,-.27,.9,-.3],["z"]],w:6.632,h:8.758},z:{d:[["M",2.64,-7.95],["c",.36,-.09,.81,-.03,1.71,.27],["c",.78,.21,.96,.27,1.74,.3],["c",.87,.06,1.02,.03,1.38,-.21],["c",.21,-.15,.33,-.15,.48,-.06],["c",.15,.09,.21,.3,.15,.45],["c",-.03,.06,-1.26,1.26,-2.76,2.67],["l",-2.73,2.55],["l",.54,.03],["c",.54,.03,.72,.03,2.01,.15],["c",.36,.03,.9,.06,1.2,.09],["c",.66,0,.81,-.03,1.02,-.24],["c",.3,-.3,.39,-.72,.27,-1.23],["c",-.06,-.27,-.06,-.27,-.03,-.39],["c",.15,-.3,.54,-.27,.69,.03],["c",.15,.33,.27,1.02,.27,1.5],["c",0,1.47,-1.11,2.7,-2.52,2.79],["c",-.57,.03,-1.02,-.09,-2.01,-.51],["c",-1.02,-.42,-1.23,-.48,-2.13,-.54],["c",-.81,-.06,-.96,-.03,-1.26,.18],["c",-.12,.06,-.24,.12,-.27,.12],["c",-.27,0,-.45,-.3,-.36,-.51],["c",.03,-.06,1.32,-1.32,2.91,-2.79],["l",2.88,-2.73],["c",-.03,0,-.21,.03,-.42,.06],["c",-.21,.03,-.78,.09,-1.23,.12],["c",-1.11,.12,-1.23,.15,-1.95,.27],["c",-.72,.15,-1.17,.18,-1.29,.09],["c",-.27,-.18,-.21,-.75,.12,-1.26],["c",.39,-.6,.93,-1.02,1.59,-1.2],["z"]],w:8.573,h:8.743},"+":{d:[["M",3.48,-9.3],["c",.18,-.09,.36,-.09,.54,0],["c",.18,.09,.24,.15,.33,.3],["l",.06,.15],["l",0,1.29],["l",0,1.29],["l",1.29,0],["c",1.23,0,1.29,0,1.41,.06],["c",.06,.03,.15,.09,.18,.12],["c",.12,.09,.21,.33,.21,.48],["c",0,.15,-.09,.39,-.21,.48],["c",-.03,.03,-.12,.09,-.18,.12],["c",-.12,.06,-.18,.06,-1.41,.06],["l",-1.29,0],["l",0,1.29],["c",0,1.23,0,1.29,-.06,1.41],["c",-.09,.18,-.15,.24,-.3,.33],["c",-.21,.09,-.39,.09,-.57,0],["c",-.18,-.09,-.24,-.15,-.33,-.33],["c",-.06,-.12,-.06,-.18,-.06,-1.41],["l",0,-1.29],["l",-1.29,0],["c",-1.23,0,-1.29,0,-1.41,-.06],["c",-.18,-.09,-.24,-.15,-.33,-.33],["c",-.09,-.18,-.09,-.36,0,-.54],["c",.09,-.18,.15,-.24,.33,-.33],["l",.15,-.06],["l",1.26,0],["l",1.29,0],["l",0,-1.29],["c",0,-1.23,0,-1.29,.06,-1.41],["c",.09,-.18,.15,-.24,.33,-.33],["z"]],w:7.507,h:7.515},",":{d:[["M",1.85,-3.36],["c",.57,-.15,1.17,.03,1.59,.45],["c",.45,.45,.6,.96,.51,1.89],["c",-.09,1.23,-.42,2.46,-.99,3.93],["c",-.3,.72,-.72,1.62,-.78,1.68],["c",-.18,.21,-.51,.18,-.66,-.06],["c",-.03,-.06,-.06,-.15,-.06,-.18],["c",0,-.06,.12,-.33,.24,-.63],["c",.84,-1.8,1.02,-2.61,.69,-3.24],["c",-.12,-.24,-.27,-.36,-.75,-.6],["c",-.36,-.15,-.42,-.21,-.6,-.39],["c",-.69,-.69,-.69,-1.71,0,-2.4],["c",.21,-.21,.51,-.39,.81,-.45],["z"]],w:3.452,h:8.143},"-":{d:[["M",.18,-5.34],["c",.09,-.06,.15,-.06,2.31,-.06],["c",2.46,0,2.37,0,2.46,.21],["c",.12,.21,.03,.42,-.15,.54],["c",-.09,.06,-.15,.06,-2.28,.06],["c",-2.16,0,-2.22,0,-2.31,-.06],["c",-.27,-.15,-.27,-.54,-.03,-.69],["z"]],w:5.001,h:.81},".":{d:[["M",1.32,-3.36],["c",1.05,-.27,2.1,.57,2.1,1.65],["c",0,1.08,-1.05,1.92,-2.1,1.65],["c",-.9,-.21,-1.5,-1.14,-1.26,-2.04],["c",.12,-.63,.63,-1.11,1.26,-1.26],["z"]],w:3.413,h:3.402},"scripts.wedge":{d:[["M",-3.66,-7.44],["c",.06,-.09,0,-.09,.81,.03],["c",1.86,.3,3.84,.3,5.73,0],["c",.78,-.12,.72,-.12,.78,-.03],["c",.15,.15,.12,.24,-.24,.6],["c",-.93,.93,-1.98,2.76,-2.67,4.62],["c",-.3,.78,-.51,1.71,-.51,2.13],["c",0,.15,0,.18,-.06,.27],["c",-.12,.09,-.24,.09,-.36,0],["c",-.06,-.09,-.06,-.12,-.06,-.27],["c",0,-.42,-.21,-1.35,-.51,-2.13],["c",-.69,-1.86,-1.74,-3.69,-2.67,-4.62],["c",-.36,-.36,-.39,-.45,-.24,-.6],["z"]],w:7.49,h:7.752},"scripts.thumb":{d:[["M",-.54,-3.69],["c",.15,-.03,.36,-.06,.51,-.06],["c",1.44,0,2.58,1.11,2.94,2.85],["c",.09,.48,.09,1.32,0,1.8],["c",-.27,1.41,-1.08,2.43,-2.16,2.73],["l",-.18,.06],["l",0,.12],["c",.03,.06,.06,.45,.09,.87],["c",.03,.57,.03,.78,0,.84],["c",-.09,.27,-.39,.48,-.66,.48],["c",-.27,0,-.57,-.21,-.66,-.48],["c",-.03,-.06,-.03,-.27,0,-.84],["c",.03,-.42,.06,-.81,.09,-.87],["l",0,-.12],["l",-.18,-.06],["c",-1.08,-.3,-1.89,-1.32,-2.16,-2.73],["c",-.09,-.48,-.09,-1.32,0,-1.8],["c",.15,-.84,.51,-1.53,1.02,-2.04],["c",.39,-.39,.84,-.63,1.35,-.75],["z"],["m",1.05,.9],["c",-.15,-.09,-.21,-.09,-.45,-.12],["c",-.15,0,-.3,.03,-.39,.03],["c",-.57,.18,-.9,.72,-1.08,1.74],["c",-.06,.48,-.06,1.8,0,2.28],["c",.15,.9,.42,1.44,.9,1.65],["c",.18,.09,.21,.09,.51,.09],["c",.3,0,.33,0,.51,-.09],["c",.48,-.21,.75,-.75,.9,-1.65],["c",.03,-.27,.03,-.54,.03,-1.14],["c",0,-.6,0,-.87,-.03,-1.14],["c",-.15,-.9,-.45,-1.44,-.9,-1.65],["z"]],w:5.955,h:9.75},"scripts.open":{d:[["M",-.54,-3.69],["c",.15,-.03,.36,-.06,.51,-.06],["c",1.44,0,2.58,1.11,2.94,2.85],["c",.09,.48,.09,1.32,0,1.8],["c",-.33,1.74,-1.47,2.85,-2.91,2.85],["c",-1.44,0,-2.58,-1.11,-2.91,-2.85],["c",-.09,-.48,-.09,-1.32,0,-1.8],["c",.15,-.84,.51,-1.53,1.02,-2.04],["c",.39,-.39,.84,-.63,1.35,-.75],["z"],["m",1.11,.9],["c",-.21,-.09,-.27,-.09,-.51,-.12],["c",-.3,0,-.42,.03,-.66,.15],["c",-.24,.12,-.51,.39,-.66,.63],["c",-.54,.93,-.63,2.64,-.21,3.81],["c",.21,.54,.51,.9,.93,1.11],["c",.21,.09,.24,.09,.54,.09],["c",.3,0,.33,0,.54,-.09],["c",.42,-.21,.72,-.57,.93,-1.11],["c",.36,-.99,.36,-2.37,0,-3.36],["c",-.21,-.54,-.51,-.9,-.9,-1.11],["z"]],w:5.955,h:7.5},"scripts.longphrase":{d:[["M",1.47,-15.09],["c",.36,-.09,.66,-.18,.69,-.18],["c",.06,0,.06,.54,.06,11.25],["l",0,11.25],["l",-.63,.15],["c",-.66,.18,-1.44,.39,-1.5,.39],["c",-.03,0,-.03,-3.39,-.03,-11.25],["l",0,-11.25],["l",.36,-.09],["c",.21,-.06,.66,-.18,1.05,-.27],["z"]],w:2.16,h:23.04},"scripts.mediumphrase":{d:[["M",1.47,-7.59],["c",.36,-.09,.66,-.18,.69,-.18],["c",.06,0,.06,.39,.06,7.5],["l",0,7.5],["l",-.63,.15],["c",-.66,.18,-1.44,.39,-1.5,.39],["c",-.03,0,-.03,-2.28,-.03,-7.5],["l",0,-7.5],["l",.36,-.09],["c",.21,-.06,.66,-.18,1.05,-.27],["z"]],w:2.16,h:15.54},"scripts.shortphrase":{d:[["M",1.47,-7.59],["c",.36,-.09,.66,-.18,.69,-.18],["c",.06,0,.06,.21,.06,3.75],["l",0,3.75],["l",-.42,.09],["c",-.57,.18,-1.65,.45,-1.71,.45],["c",-.03,0,-.03,-.72,-.03,-3.75],["l",0,-3.75],["l",.36,-.09],["c",.21,-.06,.66,-.18,1.05,-.27],["z"]],w:2.16,h:8.04},"scripts.snap":{d:[["M",4.5,-3.39],["c",.36,-.03,.96,-.03,1.35,0],["c",1.56,.15,3.15,.9,4.2,2.01],["c",.24,.27,.33,.42,.33,.6],["c",0,.27,.03,.24,-2.46,2.22],["c",-1.29,1.02,-2.4,1.86,-2.49,1.92],["c",-.18,.09,-.3,.09,-.48,0],["c",-.09,-.06,-1.2,-.9,-2.49,-1.92],["c",-2.49,-1.98,-2.46,-1.95,-2.46,-2.22],["c",0,-.18,.09,-.33,.33,-.6],["c",1.05,-1.08,2.64,-1.86,4.17,-2.01],["z"],["m",1.29,1.17],["c",-1.47,-.15,-2.97,.3,-4.14,1.2],["l",-.18,.15],["l",.06,.09],["c",.15,.12,3.63,2.85,3.66,2.85],["c",.03,0,3.51,-2.73,3.66,-2.85],["l",.06,-.09],["l",-.18,-.15],["c",-.84,-.66,-1.89,-1.08,-2.94,-1.2],["z"]],w:10.38,h:6.84},"noteheads.slash.whole":{d:[["M",5,-5],["l",1,1],["l",-5,5],["l",-1,-1],["z"],["m",4,6],["l",-5,-5],["l",2,-2],["l",5,5],["z"],["m",0,-2],["l",1,1],["l",-5,5],["l",-1,-1],["z"],["m",-4,6],["l",-5,-5],["l",2,-2],["l",5,5],["z"]],w:10.81,h:15.63},"noteheads.slash.quarter":{d:[["M",9,-6],["l",0,4],["l",-9,9],["l",0,-4],["z"]],w:9,h:9},"noteheads.harmonic.quarter":{d:[["M",3.63,-4.02],["c",.09,-.06,.18,-.09,.24,-.03],["c",.03,.03,.87,.93,1.83,2.01],["c",1.5,1.65,1.8,1.98,1.8,2.04],["c",0,.06,-.3,.39,-1.8,2.04],["c",-.96,1.08,-1.8,1.98,-1.83,2.01],["c",-.06,.06,-.15,.03,-.24,-.03],["c",-.12,-.09,-3.54,-3.84,-3.6,-3.93],["c",-.03,-.03,-.03,-.09,-.03,-.15],["c",.03,-.06,3.45,-3.84,3.63,-3.96],["z"]],w:7.5,h:8.165},"noteheads.triangle.quarter":{d:[["M",0,4],["l",9,0],["l",-4.5,-9],["z"]],w:9,h:9}},i=function(e){for(var t=[],r=0,n=e.length;r<n;r++){t[r]=[];for(var a=0,i=e[r].length;a<i;a++)t[r][a]=e[r][a]}return t},s={printSymbol:function(e,t,r,n,s){if(!a[r])return null;var o=i(a[r].d);o[0][1]+=e,o[0][2]+=t;for(var c="",l=0;l<o.length;l++)c+=o[l].join(" ");return s.path=c,n.path(s)},getPathForSymbol:function(e,t,r,n,s){if(n=n||1,s=s||1,!a[r])return null;var o=i(a[r].d);return 1===n&&1===s||function(e,t,r){for(var n=0,a=e.length;n<a;n++){var i,s,o=e[n];for(i=1,s=o.length;i<s;i++)o[i]*=i%2?t:r}}(o,n,s),o[0][1]+=e,o[0][2]+=t,o},getSymbolWidth:function(e){return a[e]?a[e].w:0},symbolHeightInPitches:function(e){return(a[e]?a[e].h:0)/n.STEP},getSymbolAlign:function(e){return"scripts"===e.substring(0,7)&&"scripts.roll"!==e?"center":"left"},getYCorr:function(e){switch(e){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case"+":case"flags.d64th":case"scripts.trill":case"scripts.upbow":case"scripts.downbow":return-2;case"timesig.common":case"timesig.cut":default:return 0;case"flags.d32nd":case"rests.half":case"rests.8th":case"rests.quarter":case"rests.16th":case"rests.32nd":case"rests.64th":case"scripts.ufermata":case"scripts.wedge":case"scripts.roll":case"scripts.shortphrase":case"scripts.longphrase":return-1;case"flags.u32nd":case"rests.whole":case"scripts.dfermata":return 1;case"flags.u64th":return 3;case"f":case"m":case"p":case"s":case"z":return-4}},setSymbol:function(e,t){a[e]=t}};e.exports=s},5810:function(e){function t(e){switch(e){case"B#":return"H#";case"B♯":return"H♯";case"B":return"H";case"Bb":case"B♭":return"B"}return e}e.exports=function(e,r,n){for(var a=e.split("\n"),i=0;i<a.length;i++){var s=a[i].match(/^([ABCDEFG][♯♭]?)?([^\/]+)?(\/([ABCDEFG][#b♯♭]?))?/);if(s){var o=s[1]||"",c=s[2]||"",l=s[4]||"";n&&(o=t(o),l=t(l));var h=r?"":"",u=l?"/"+l:"";a[i]=[o,c,u].join(h)}}return a.join("\n")}},4750:function(e,t,r){var n=r(3987),a=r(2435),i=r(4331),s=r(2187),o=r(8832);e.exports=function(e,t,r,c,l){if(!t.invisible){var h=t.children.length>0&&"TempoElement"===t.children[0].type;t.elemset=[],o.beginGroup(e.paper,e.controller);for(var u=0;u<t.children.length;u++){var d=t.children[u];if("TempoElement"===d.type)n(e,d);else{var f=a(e,d,r);"symbol"===d.type&&d.c&&d.c.indexOf("notehead")>=0&&f.setAttribute("class","abcjs-notehead"),f&&d.chordPos&&0!==d.name.indexOf("flags.")&&(p=(p=f.getAttribute("class"))?p+" abcjs-chord-pos-"+d.chordPos:"abcjs-chord-pos-"+d.chordPos,f.setAttribute("class",p))}}var p=t.type;if(("note"===t.type||"rest"===t.type)&&(t.counters=e.controller.classes.getCurrent(),p=(p+=" d"+Math.round(1e3*t.durationClass)/1e3).replace(/\./g,"-"),t.abcelem.pitches))for(var m=0;m<t.abcelem.pitches.length;m++)p+=" p"+t.abcelem.pitches[m].pitch;var g=o.endGroup(p,t.type,t.extraClass);if(g){if(t.cloned&&(t.cloned.overrideClasses=g.className.baseVal),t.overrideClasses){var v=g.classList&&g.classList.length>0?g.classList[0]+" ":"";g.setAttribute("class",v+t.overrideClasses)}if(h)t.startChar=t.abcelem.startChar,t.endChar=t.abcelem.endChar,c.add(t,g,!1,l);else{t.elemset.push(g);var b=!1;"note"!==t.type&&"tabNumber"!==t.type||(b=!0),c.add(t,g,b,l)}}else t.elemset.length>0&&c.add(t,t.elemset[0],"note"===t.type,l);if(t.klass&&s(t.elemset,"mark","","#00ff00"),t.hint&&s(t.elemset,"abcjs-hint","",null),t.abcelem.abselem=t,t.heads&&t.heads.length>0){t.notePositions=[];for(var y=0;y<t.heads.length;y++)t.notePositions.push({x:t.heads[y].x+t.heads[y].w/2,y:l.zero-t.heads[y].pitch*i.STEP})}}}},7489:function(e,t,r){var n=r(6454),a=r(7199);function i(e,t,r,n,i,s){r=a(e.calcY(r)),i=a(e.calcY(i)),t=a(t),n=a(n);var o=a(r+s);return"M"+t+" "+r+" L"+n+" "+i+"L"+n+" "+a(i+s)+" L"+t+" "+o+"z"}function s(e,t,r,n){return t+(n-e)*r}e.exports=function(e,t){if(0!==t.beams.length){for(var r="",a=0;a<t.beams.length;a++){var o=t.beams[a];if(o.split){for(var c=(m=o.startX,g=o.startY,v=o.endX,(o.endY-g)/(v-m)),l=[],h=0;h<o.split.length;h+=2)l.push([o.split[h],o.split[h+1]]);for(h=0;h<l.length;h++){var u=s(o.startX,o.startY,c,l[h][0]),d=s(o.startX,o.startY,c,l[h][1]);r+=i(e,l[h][0],u,l[h][1],d,o.dy)}}else r+=i(e,o.startX,o.startY,o.endX,o.endY,o.dy)}var f=("abcjs-d"+t.duration).replace(/\./g,"-"),p=e.controller.classes.generate("beam-elem "+f);return[n(e,{path:r,stroke:"none",fill:e.foregroundColor,class:p})]}var m,g,v}},129:function(e,t,r){var n=r(6764),a=r(4331),i=r(5759);function s(e,t,r,a){return n("M %f %f C %f %f %f %f %f %f C %f %f %f %f %f %f z",e+r[0],t+a[0],e+r[1],t+a[1],e+r[2],t+a[2],e+r[3],t+a[3],e+r[4],t+a[4],e+r[5],t+a[5],e+r[6],t+a[6])}var o=function(e,t,r,o,c,l,h){var u;if(l){e.paper.openGroup({klass:e.controller.classes.generate("staff-extra voice-name"),"data-name":c});var d=r+(o-r)/2;d-=e.controller.getTextSize.baselineToCenter(l,"voicefont","staff-extra voice-name",0,1),i(e,{x:e.padding.left,y:d,text:l,type:"voicefont",klass:"staff-extra voice-name",anchor:"start",centerVertically:!0})}return"brace"===c?u=function(e,t,r,n,a){var i=n-r,o=s(t,r,[7.5,-8,21,0,18.5,-10.5,7.5],[0,i/5.5,i/3.14,i/2,i/2.93,i/4.88,0]);return o+=s(t,r,[0,17.5,-7.5,6.6,-5,20,0],[i/2,i/1.46,i/1.22,i,i/1.19,i/1.42,i/2]),e.paper.path({path:o,stroke:e.foregroundColor,fill:e.foregroundColor,class:e.controller.classes.generate(a),"data-name":a})}(e,t,r,o,c):"bracket"===c&&(u=function(e,t,r,i,s){t+=a.STEP;var o=.75*a.STEP,c=.75*a.STEP,l=i-r,h=n("M %f %f l %f %f l %f %f l %f %f z",t,r-c,0,l+2*c,o,0,0,-(l+2*c)),u=2*a.STEP,d=a.STEP;return h+=n("M %f %f q %f %f %f %f q %f %f %f %f z",t+o,r-c,.6*u,.2*d,u,-d,.1*-u,.3*d,-u,d+a.STEP),h+=n("M %f %f q %f %f %f %f q %f %f %f %f z",t+o,r+c+l,.6*u,.2*-d,u,d,.1*-u,.3*-d,-u,-d-a.STEP),e.paper.path({path:h,stroke:e.foregroundColor,fill:e.foregroundColor,class:e.controller.classes.generate(s),"data-name":s})}(e,t,r,o,c)),l&&(u=e.paper.closeGroup()),h.wrapSvgEl({el_type:c,startChar:-1,endChar:-1},u),u};e.exports=function(e,t,r){var n=t.startVoice.staff.absoluteY-10*a.STEP;return t.endVoice&&t.endVoice.staff?t.endY=t.endVoice.staff.absoluteY-2*a.STEP:t.lastContinuedVoice&&t.lastContinuedVoice.staff?t.endY=t.lastContinuedVoice.staff.absoluteY-2*a.STEP:t.endY=t.startVoice.staff.absoluteY-2*a.STEP,o(e,t.x,n,t.endY,t.type,t.header,r)}},7333:function(e,t,r){var n=r(4777),a=r(3624);function i(e,t,r,i,s,o){var c=s?t+2:t-4,l=s?t+9:t-11;e.paper.openGroup({klass:"abcjs-repeat"}),a(e,c,3+e.lineThickness,r,i,null,"bar"),n(e,l,-e.yToPitch(o)-4,"dots.dot",{scalex:1,scaley:1,klass:"",name:"dot"}),n(e,l,-e.yToPitch(o)-8,"dots.dot",{scalex:1,scaley:1,klass:"",name:"dot"}),e.paper.closeGroup()}var s={segno:"scripts.segno",coda:"scripts.coda",fermata:"scripts.ufermata"};function o(e,t,r,n,a,i,s){for(var o=h(e,a,t,r,n,i,null,"abcjs-chord",!0),c=o.getBBox(),l=n;c.width>s&&l>=14;)l-=2,o.setAttribute("font-size",l),c=o.getBBox()}var c=-3;function l(e){return"No Chord"===e?"N.C.":e}function h(e,t,r,n,a,i,s,o,c){var l={x:r,y:n,stroke:"none","font-size":a,"font-style":i.style,"font-family":i.face,"font-weight":i.weight,"text-decoration":i.decoration};return s&&(l["data-name"]=s),o&&(l.class=o),l["text-anchor"]=c?"middle":"start",e.paper.text(t,l,null,{"alignment-baseline":"middle"})}e.exports=function(e,t,r,a,u){var d=u.gchordfont,f=(u.partsfont,u.annotationfont),p=u.repeatfont,m=u.textfont,g=u.subtitlefont,v=50;e.paper.openGroup({klass:"abcjs-chord-grid"}),t.forEach(function(t){switch(t.type){case"text":h(e,t.text,r,e.y,16,m,null,null,!1),e.moveY(16);break;case"subtitle":h(e,t.subtitle,r,e.y+10,20,g,null,"abcjs-subtitle",!1),e.moveY(20);break;case"part":if(t.lines.length>0){h(e,t.name,r,e.y+10,20,g,t.name,"abcjs-part",!1),e.moveY(20);var u=t.lines[0].length,b=a/u;t.lines.forEach(function(t,a){var u=!1,m=!1;t.forEach(function(e){e.ending&&(u=!0),e.annotations&&e.annotations.length>0&&(m=!0)});var g=m?14:u?10:0;t.forEach(function(t,a){if(!t.noBorder){e.paper.rect({x:r+a*b,y:e.y,width:b,height:g+v}),e.paper.rect({x:r+a*b+1,y:e.y+1,width:b-2,height:g+v-2});var u=0,m=0,y=e.y,x=r+b*a;t.hasStartRepeat&&(i(e,x,y,y+v+g,!0,g),u=12),t.hasEndRepeat&&(i(e,x+b,y,y+v+g,!1,g),m=12);var k=0;t.ending&&(k=h(e,t.ending,r+a*b+4,y+10,12,p,null,null,!1).getBBox().width+4),function(e,t,r,a,i,s,h,u,d,f,p){var m=r+a*s;h[1]||h[2]||h[3]?h[1]||h[3]?function(e,t,r,n,a,i,s,h){e.paper.lineToBack({x1:t+3,x2:t+n-3,y1:r+25+h,y2:r+25+h}),e.paper.lineToBack({x1:t+n/2,x2:t+n/2,y1:r+3+h,y2:r+a-3+h}),i[0]&&o(e,t+n/4,r+a/4+2+h+c,20,l(i[0]),s,n/2),i[1]&&o(e,t+3*n/4,r+a/4+2+h+c,20,l(i[1]),s,n/2),i[2]&&o(e,t+n/4,r+37.5+h+c,20,l(i[2]),s,n/2),i[3]&&o(e,t+3*n/4,r+37.5+h+c,20,l(i[3]),s,n/2)}(e,m,t,a-d,50,h,u,p):function(e,t,r,n,a,i,s,l,h){e.paper.lineToBack({x1:t,x2:t+n,y1:r+50+h,y2:r+2}),o(e,t+n/4,r+12.5+5+h+c,26,i,l,n/2),o(e,t+3*n/4,r+37.5+h+c,26,s,l,n/2)}(e,m,t,a-d,0,h[0],h[2],u,p):function(e,t,r,a,i,s,l,h){"%"===s?function(e,t,r,a){var i=t-10,s=t+10,o=r+10,c=r-10,l=t-10,h=2-e.yToPitch(a),u=t+6.5,d=-e.yToPitch(a)-2.3;e.paper.lineToBack({x1:i,x2:s,y1:o,y2:c,"stroke-width":"3px","stroke-linecap":"round"}),n(e,l,h,"dots.dot",{scalex:1,scaley:1,klass:"",name:"dot"}),n(e,u,d,"dots.dot",{scalex:1,scaley:1,klass:"",name:"dot"})}(e,t+a/2,r+25,h+25):o(e,t+a/2,r+25+c,34,s,l,a)}(e,m,t+p,a-d,0,h[0],u,p)}(e,y,r+u,b,0,a,t.chord,d,u+m,0,g),t.annotations&&t.annotations.length>0&&function(e,t,r,a,i){r+=3;for(var o=0;o<a.length;o++)switch(a[o]){case"segno":case"coda":case"fermata":r+=12,r+=n(e,r,-3,s[a[o]],{scalex:1,scaley:1,name:s[a[o]]}).getBBox().width;break;default:h(e,a[o],r,t+12,12,i,null,null,!1)}}(e,y,r+a*b+k,t.annotations,f),g&&e.paper.rectBeneath({x:r+a*b,y:e.y,width:b,height:g,fill:"#e8e8e8",stroke:"none"})}}),e.moveY(g+v)}),e.moveY(20)}}}),e.paper.closeGroup()}},3245:function(e,t,r){var n=r(6764),a=r(6454),i=r(7199),s=function(e,t,r,s,o,c,l){t=i(t),r=i(r),s=i(s),o=i(o),c=i(c),l=i(l);var h=n("M %f %f L %f %f M %f %f L %f %f",c,t,l,r,c,s,l,o);return a(e,{path:h,highlight:"stroke",stroke:e.foregroundColor,class:e.controller.classes.generate("dynamics decoration"),"data-name":"dynamics"})};e.exports=function(e,t,r){void 0===t.pitch&&window.console.error("Crescendo Element y-coordinate not set.");var n,a=e.calcY(t.pitch)+4,i=t.anchor1?t.anchor1.x:0,o=t.anchor2?t.anchor2.x:800;return n="<"===t.dir?s(e,a+4,a,a+4,a+8,i,o):s(e,a,a+4,a+8,a+4,i,o),r.wrapSvgEl({el_type:"dynamicDecoration",startChar:-1,endChar:-1},n),[n]}},1547:function(e){e.exports=function(e,t,r){var n=e.paper.rectBeneath(t);return r&&e.paper.text(r,{x:0,y:t.y+7,"text-anchor":"start","font-size":"14px",fill:"rgba(0,0,255,.4)",stroke:"rgba(0,0,255,.4)"}),n}},5012:function(e,t,r){var n=r(5537),a=r(7611),i=r(5668),s=r(4331),o=r(3524),c=r(7333);function l(e,t,r,a){n(e,t,r,a);var i=t.height*s.STEP;return e.moveY(i),t}function h(e,t,r,n){var a=-(r.staffs[r.staffs.length-1].bottom-2),i=(n.staffs[0].top-10+a)*s.STEP;i<t&&e.moveY(t-i)}e.exports=function(e,t,r,n,s,u,d,f,p,m,g){var v=new o(e.paper,f,p),b={};t.shouldAddClasses&&(b.klass="abcjs-meta-top"),e.paper.openGroup(b),e.moveY(e.padding.top),i(e,r.topText,v),e.paper.closeGroup(),e.moveY(e.spacing.music);var y=!1;g&&r.chordGrid&&(c(e,r.chordGrid,e.padding.left,n,r.formatting),"noMusic"===g&&(y=!0));var x=[],k=0;if(!y)for(var w=0;w<r.lines.length;w++){t.incrLine();var C=r.lines[w];if(C.staff){if(k++,r.formatting.maxStaves&&k>r.formatting.maxStaves)break;t.shouldAddClasses&&(b.klass="abcjs-staff-wrapper abcjs-l"+t.lineNumber),e.paper.openGroup(b),C.vskip&&e.moveY(C.vskip),x.length>=1?h(e,e.spacing.staffSeparation,x[x.length-1],C.staffGroup):w>0&&e.moveY(e.spacing.staffSeparation);var T=l(e,C.staffGroup,v,w);T.line=m+w,x.push(T),e.paper.closeGroup()}else C.nonMusic&&(t.shouldAddClasses&&(b.klass="abcjs-non-music"),e.paper.openGroup(b),i(e,C.nonMusic,v),e.paper.closeGroup())}return t.reset(),y||r.bottomText&&r.bottomText.rows&&r.bottomText.rows.length>0&&(t.shouldAddClasses&&(b.klass="abcjs-meta-bottom"),e.paper.openGroup(b),e.moveY(24),i(e,r.bottomText,v),e.paper.closeGroup()),a(e,s,d,u),{staffgroups:x,selectables:v.getElements()}}},9879:function(e,t,r){var n=r(4777);e.exports=function(e,t,r){void 0===t.pitch&&window.console.error("Dynamic Element y-coordinate not set.");var a=n(e,t.anchor.x,t.pitch,t.dec,{scalex:1,scaley:1,klass:e.controller.classes.generate("decoration dynamics"),fill:e.foregroundColor,stroke:"none",name:"dynamics"});return r.wrapSvgEl({el_type:"dynamicDecoration",startChar:-1,endChar:-1,decoration:t.dec},a),[a]}},5947:function(e,t,r){var n=r(6764),a=r(5759),i=r(6454),s=r(7199);e.exports=function(e,t,r,o,c){void 0===t.pitch&&window.console.error("Ending Element y-coordinate not set.");var l=s(e.calcY(t.pitch)),h="";t.anchor1&&(r=s(t.anchor1.x+t.anchor1.w),h+=n("M %f %f L %f %f ",r,l,r,s(l+20))),t.anchor2&&(o=s(t.anchor2.x),h+=n("M %f %f L %f %f ",o,l,o,s(l+20))),h+=n("M %f %f L %f %f ",r,l,o,l),e.paper.openGroup({klass:e.controller.classes.generate("ending"),fill:e.foregroundColor,"data-name":"ending"}),i(e,{path:h,stroke:e.foregroundColor,fill:e.foregroundColor,"data-name":"line"}),t.anchor1&&a(e,{x:s(r+5),y:s(e.calcY(t.pitch-.5)),text:t.text,type:"repeatfont",klass:"ending",anchor:"start",noClass:!0,name:t.text});var u=e.paper.closeGroup();return c.wrapSvgEl({el_type:"ending",startChar:-1,endChar:-1},u),[u]}},9045:function(e,t,r){var n=r(6764),a=r(6454),i=r(7199);function s(e,t,r){return i(e+r*t)}var o=[[3.5,-4.8]],c=[[1.5,-1],[.3,-.3],[-3.5,3.8]],l=[[-1.5,2]],h=[[3,4],[3,-4]],u=[[-3,4],[-3,-4]];function d(e,t){for(var r="",n=0;n<e.length;n++)r+="l"+e[n][0]+" "+s(e[n][1],t,e[n][0]);return r}var f=function(e,t,r,i,s){var f,p=n("M %f %f",t,r);for(p+=d(o,s),f=0;f<i;f++)p+=d(h,s);for(p+=d(c,s),f=0;f<i;f++)p+=d(u,s);return p+=d(l,s)+"z",a(e,{path:p,highlight:"stroke",stroke:e.foregroundColor,class:e.controller.classes.generate("decoration"),"data-name":"glissando"})};e.exports=function(e,t,r){t.anchor1&&t.anchor2&&t.anchor1.heads&&t.anchor2.heads&&0!==t.anchor1.heads.length&&0!==t.anchor2.heads.length||window.console.error("Glissando Element not set.");var n,a=e.calcY(t.anchor1.heads[0].pitch),i=e.calcY(t.anchor2.heads[0].pitch),o=t.anchor1.x+t.anchor1.w/2,c=t.anchor2.x+t.anchor2.w/2,l=function(e,t,r,n){var a=r-e,i=n-t;return Math.sqrt(a*a+i*i)}(o,a,c,i),h=t.anchor1.w/2+4,u=t.anchor2.w/2+4,d=function(e,t,r,n){return(n-t)/(r-e)}(o,a,c,i),p=s(a,d,h),m=(s(i,d,-u),n=l-h-u,Math.max(2,Math.floor((n-10)/6))),g=f(e,o+h,p,m,d);return r.wrapSvgEl({el_type:"glissando",startChar:-1,endChar:-1},g),[g]}},8832:function(e,t,r){var n=r(7199);function a(){this.ingroup=!1}a.prototype.beginGroup=function(e,t){this.paper=e,this.controller=t,this.path=[],this.lastM=[0,0],this.ingroup=!0,this.paper.openGroup()},a.prototype.isInGroup=function(){return this.ingroup},a.prototype.addPath=function(e){if(0!==(e=e||[]).length){e[0][0]="m",e[0][1]=n(e[0][1]-this.lastM[0]),e[0][2]=n(e[0][2]-this.lastM[1]),this.lastM[0]+=e[0][1],this.lastM[1]+=e[0][2],this.path.push(e[0]);for(var t=1,r=e.length;t<r;t++)"m"===e[t][0]&&(this.lastM[0]+=e[t][1],this.lastM[1]+=e[t][2]),this.path.push(e[t])}},a.prototype.endGroup=function(e,t,r){this.ingroup=!1;for(var n=0;n<this.path.length;n++)this.path[n].join(" ");this.path=[];var a=this.paper.closeGroup();if(a){var i=this.controller.classes.generate(e);i&&(r&&(i+=" "+r),a.setAttribute("class",i)),a.setAttribute("fill",this.controller.renderer.foregroundColor),a.setAttribute("stroke","none"),a.setAttribute("data-name",t)}return a};var i=new a;e.exports=i},5668:function(e,t,r){var n=r(4169),a=r(5759);e.exports=function(e,t,r){for(var i=0;i<t.rows.length;i++){var s=t.rows[i];if(s.absmove)e.absolutemoveY(s.absmove);else if(s.move)e.moveY(s.move);else if(s.text||s.phrases){var o=s.left?s.left:0,c=a(e,{x:o,y:e.y,text:s.text,phrases:s.phrases,"dominant-baseline":s["dominant-baseline"],type:s.font,klass:s.klass,name:s.name,anchor:s.anchor});s.absElemType&&r.wrapSvgEl({el_type:s.absElemType,name:s.name,startChar:s.startChar,endChar:s.endChar,text:s.text},c)}else if(s.separator)n(e,s.separator);else if(s.startGroup)e.paper.openGroup({klass:s.klass,"data-name":s.name});else if(s.endGroup){var l=e.paper.closeGroup();s.absElemType&&r.wrapSvgEl({el_type:s.absElemType,name:s.name,startChar:s.startChar,endChar:s.endChar,text:""},l)}}}},6637:function(e,t,r){var n=r(6764),a=r(7199);e.exports=function(e,t,r,i,s,o,c){var l=e.foregroundColor;t=a(t),r=a(r);var h=a(i-c),u=a(i+c);if(e.firefox){var d={x1:t,x2:r,y1:i+=c/2,y2:i,stroke:e.foregroundColor,"stroke-width":Math.abs(2*c)};return s&&(d.class=s),o&&(d["data-name"]=o),e.paper.lineToBack(d)}var f={path:n("M %f %f L %f %f L %f %f L %f %f z",t,h,r,h,r,u,t,u),stroke:"none",fill:l};return o&&(f["data-name"]=o),s&&(f.class=s),e.paper.pathToBack(f)}},6454:function(e){e.exports=function(e,t,r){return e.paper.path(t)}},3624:function(e,t,r){var n=r(8832),a=r(7199);e.exports=function(e,t,r,i,s,o,c){if(r<0||i<s){var l=a(s);s=a(i),i=l}else i=a(i),s=a(s);t=a(t);var h=a(t+r);if(e.firefox){var u={x1:t+=r/2,x2:t,y1:i,y2:s,stroke:e.foregroundColor,"stroke-width":Math.abs(r)};return o&&(u.class=o),c&&(u["data-name"]=c),e.paper.lineToBack(u)}for(var d=[["M",t,i],["L",t,s],["L",h,s],["L",h,i],["z"]],f=(u={path:""},0);f<d.length;f++)u.path+=d[f].join(" ");return o&&(u.class=o),c&&(u["data-name"]=c),n.isInGroup()||(u.stroke="none",u.fill=e.foregroundColor),e.paper.pathToBack(u)}},4777:function(e,t,r){var n=r(5759),a=r(6020),i=r(8832);e.exports=function(e,t,r,s,o){var c,l,h,u,d;if(!s)return null;if(s.length>1&&s.indexOf(".")<0){var f=i.isInGroup()?"":o.klass;e.paper.openGroup({"data-name":o.name,klass:f});for(var p=0,m=0;m<s.length;m++){var g=s[m];l=a.getYCorr(g),(c=a.printSymbol(t+p,e.calcY(r+l),g,e.paper,{stroke:o.stroke,fill:o.fill}))?m<s.length-1&&(p+=(h=g,u=s[m+1],d=void 0,d=a.getSymbolWidth(g),"f"===h&&"f"===u&&(d=2*d/3),"p"===h&&"p"===u&&(d=5*d/6),"f"===h&&"z"===u&&(d=5*d/8),d)):n(e,{x:t,y:e.y,text:"no symbol:"+s,type:"debugfont",klass:"debug-msg",anchor:"start"},!1)}return e.paper.closeGroup()}return l=a.getYCorr(s),(c=i.isInGroup()?a.printSymbol(t,e.calcY(r+l),s,e.paper,{"data-name":o.name}):a.printSymbol(t,e.calcY(r+l),s,e.paper,{klass:o.klass,stroke:o.stroke,fill:o.fill,"data-name":o.name}))?c:(n(e,{x:t,y:e.y,text:"no symbol:"+s,type:"debugfont",klass:"debug-msg",anchor:"start"},!1),null)}},2435:function(e,t,r){var n=r(5759),a=r(3624),i=r(7865),s=r(4777);e.exports=function(e,t,r){void 0===t.pitch&&window.console.error(t.type+" Relative Element y-coordinate not set.");var o=e.calcY(t.pitch);switch(t.type){case"symbol":if(null===t.c)return null;var c="symbol";t.klass&&(c+=" "+t.klass),t.graphelem=s(e,t.x,t.pitch,t.c,{scalex:t.scalex,scaley:t.scaley,klass:e.controller.classes.generate(c),name:t.name});break;case"debug":t.graphelem=n(e,{x:t.x,y:e.calcY(15),text:""+t.c,type:"debugfont",klass:e.controller.classes.generate("debug-msg"),anchor:"start",centerVertically:!1,dim:t.dim},!1);break;case"tabNumber":var l="tabnumberfont",h="abcjs-tab-number";t.isGrace&&(l="tabgracefont",o+=2.5,h="tab-grace"),t.graphelem=n(e,{x:t.x,y:o,text:""+t.c,type:l,klass:e.controller.classes.generate(h),anchor:"middle",centerVertically:!1,dim:t.dim,cursor:"default"},!1);break;case"barNumber":t.graphelem=n(e,{x:t.x,y:o,text:""+t.c,type:"measurefont",klass:e.controller.classes.generate("bar-number"),anchor:"middle",dim:t.dim,name:"bar-number"},!0);break;case"lyric":t.graphelem=n(e,{x:t.x,y:o,text:t.c,type:"vocalfont",klass:e.controller.classes.generate("lyric"),anchor:"middle",dim:t.dim,name:"lyric"},!1);break;case"chord":t.graphelem=n(e,{x:t.x,y:o,text:t.c,type:"gchordfont",klass:e.controller.classes.generate("chord"),anchor:"middle",dim:t.dim,lane:t.getLane(),name:"chord"},!1);break;case"decoration":t.graphelem=n(e,{x:t.x,y:o+6,text:t.c,type:"annotationfont",klass:e.controller.classes.generate("annotation"),anchor:t.anchor,centerVertically:!0,dim:t.dim},!1);break;case"text":t.graphelem=n(e,{x:t.x,y:o,text:t.c,type:"annotationfont",klass:e.controller.classes.generate("annotation"),anchor:"start",centerVertically:t.centerVertically,dim:t.dim,lane:t.getLane(),name:"annotation"},!1);break;case"multimeasure-text":t.graphelem=n(e,{x:t.x+t.w/2,y:o,text:t.c,type:"tempofont",klass:e.controller.classes.generate("rest"),anchor:"middle",centerVertically:!1,dim:t.dim},!1);break;case"part":t.graphelem=n(e,{x:t.x,y:o,text:t.c,type:"partsfont",klass:e.controller.classes.generate("part"),anchor:"start",dim:t.dim,name:t.c},!0);break;case"bar":t.graphelem=a(e,t.x,t.linewidth+e.lineThickness,o,r||e.calcY(t.pitch2),null,"bar");break;case"stem":var u=t.linewidth>0?t.linewidth+e.lineThickness:t.linewidth-e.lineThickness;t.graphelem=a(e,t.x,u,o,e.calcY(t.pitch2),"abcjs-stem","stem");break;case"ledger":t.graphelem=i(e,t.x,t.x+t.w,t.pitch,"abcjs-ledger","ledger",.35+e.lineThickness)}return 1!==t.scalex&&t.graphelem&&function(e,t,r,n,a,i){e.setAttributeOnElement(t,{style:"transform:scale("+r+","+n+");transform-origin:"+a+"px "+i+"px;"})}(e.paper,t.graphelem,t.scalex,t.scaley,t.x,o),t.graphelem}},7199:function(e){e.exports=function(e){return parseFloat(e.toFixed(2))}},3524:function(e,t,r){var n=r(5741),a=r(5829);function i(e,t,r){this.elements=[],this.paper=e,this.tuneNumber=r,this.selectTypes=t}i.prototype.getElements=function(){return this.elements},i.prototype.add=function(e,t,r,n){if(this.canSelect(e)){var a;a=void 0===this.selectTypes?{selectable:!1,"data-index":this.elements.length}:{selectable:!0,tabindex:0,"data-index":this.elements.length},this.paper.setAttributeOnElement(t,a);var i={absEl:e,svgEl:t,isDraggable:r};void 0!==n&&(i.staffPos=n),this.elements.push(i)}},i.prototype.canSelect=function(e){return!(!1===this.selectTypes||!e||!e.abcelem||!0!==this.selectTypes&&!(void 0===this.selectTypes?"note"===e.abcelem.el_type||"tabNumber"===e.abcelem.el_type:this.selectTypes.indexOf(e.abcelem.el_type)>=0))},i.prototype.wrapSvgEl=function(e,t){var r={tuneNumber:this.tuneNumber,abcelem:e,elemset:[t],highlight:n,unhighlight:a};this.add(r,t,!1)},e.exports=i},4169:function(e){e.exports=function(e,t){var r=Math.round(e.y),n=(e.controller.width-t)/2,a=n+t,i="M "+n+" "+r+" L "+a+" "+r+" L "+a+" "+(r+1)+" L "+n+" "+(r+1)+" L "+n+" "+r+" z";e.paper.pathToBack({path:i,stroke:"rgba(0,0,0,0)",fill:"rgba(0,0,0,255)",class:e.controller.classes.generate("defined-text")})}},7611:function(e){e.exports=function(e,t,r,n){var a=(t+e.padding.left+e.padding.right)*r,i=(e.y+e.padding.bottom)*r;if(e.isPrint&&(i=Math.max(i,1056)),""!==e.ariaLabel){var s="Sheet Music";e.abctune&&e.abctune.metaText&&e.abctune.metaText.title&&(s+=' for "'+e.abctune.metaText.title+'"'),e.paper.setTitle(s);var o=e.ariaLabel?e.ariaLabel:s;e.paper.setAttribute("aria-label",o)}e.paper.insertStyles(".abcjs-dragging-in-progress text, .abcjs-dragging-in-progress tspan {"+["-webkit-touch-callout: none;","-webkit-user-select: none;","-khtml-user-select: none;","-moz-user-select: none;","-ms-user-select: none;","user-select: none;"].join(" ")+"}");var c={overflow:"hidden"};"resize"===n?e.paper.setResponsiveWidth(a,i):(c.width="",c.height=i+"px",r<1?(c.width=a+"px",e.paper.setSize(a/r,i/r)):e.paper.setSize(a,i)),e.paper.setScale(r),e.paper.setParentStyles(c)}},6764:function(e){function t(e){return t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},t(e)}e.exports=function(){for(var e,r,n,a,i,s=0,o=arguments[s++],c=[];o;){if(r=/^[^\x25]+/.exec(o))c.push(r[0]);else if(r=/^\x25{2}/.exec(o))c.push("%");else{if(!(r=/^\x25(?:(\d+)\$)?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(o)))throw"Huh ?!";if(null==(e=arguments[r[1]||s++])||null==e)throw"Too few arguments.";if(/[^s]/.test(r[7])&&"number"!=typeof e)throw"Expecting number but found "+t(e);switch(r[7]){case"b":e=e.toString(2);break;case"c":e=String.fromCharCode(e);break;case"d":e=parseInt(e);break;case"e":e=r[6]?e.toExponential(r[6]):e.toExponential();break;case"f":e=r[6]?parseFloat(e).toFixed(r[6]):parseFloat(e);break;case"o":e=e.toString(8);break;case"s":e=(e=String(e))&&r[6]?e.substring(0,r[6]):e;break;case"u":e=Math.abs(e);break;case"x":e=e.toString(16);break;case"X":e=e.toString(16).toUpperCase()}e=/[def]/.test(r[7])&&r[2]&&e>0?"+"+e:e,a=r[3]?"0"==r[3]?"0":r[3][1]:" ",i=r[5]-String(e).length,n=r[5]?str_repeat(a,i):"",c.push(r[4]?e+n:n+e)}o=o.substring(r[0].length)}return c.join("")}},5537:function(e,t,r){var n=r(4331),a=r(129),i=r(3145),s=r(7641),o=r(1547),c=r(3624),l=r(5668);function h(e,t,r,i,s){if(r)for(var o=0;o<r.length;o++)r[o].isStartVoice(i)&&(r[o].startY=t-10*n.STEP,r[o].elemset=a(e,r[o],s))}function u(e,t,r){for(var a=0;a<r.length;a++)for(var i=t[r[a]].children,s=0;s<i.length;s++){var c=i[s],l=c.getFixedCoords();if(!c.invisible&&void 0!==l.t&&void 0!==l.b){var h=(l.t-l.b)*n.STEP;o(e,{x:l.x,y:e.calcY(l.t),width:l.w,height:h,fill:"#88e888","fill-opacity":.4,stroke:"#4aa93d","stroke-opacity":.8});for(var u=0;u<c.children.length;u++){var d=c.children[u],f=d.getChordDim();if(f){var p=e.calcY(d.pitch);p+=d.dim.font.size*d.getLane(),o(e,{x:f.left,y:p,width:f.right-f.left,height:d.dim.font.size,fill:"none",stroke:"#4aa93d","stroke-opacity":.8})}}}}}e.exports=function(e,t,r,a){for(var d,f,p,m=e.y,g=0;g<t.staffs.length;g++){var v=t.staffs[g];e.moveY(n.STEP,v.top),v.absoluteY=e.y,e.showDebug&&(e.showDebug.indexOf("box")>=0&&v.voices&&u(e,t.voices,v.voices),e.showDebug.indexOf("grid")>=0&&(e.paper.dottedLine({x1:e.padding.left,x2:e.padding.left+e.controller.width,y1:m,y2:m,stroke:"#0000ff"}),o(e,{x:e.padding.left,y:e.calcY(v.originalTop),width:e.controller.width,height:e.calcY(v.originalBottom)-e.calcY(v.originalTop),fill:e.foregroundColor,stroke:e.foregroundColor,"fill-opacity":.1,"stroke-opacity":.1}),d=0,E(v,"chordHeightAbove"),E(v,"chordHeightBelow"),E(v,"dynamicHeightAbove"),E(v,"dynamicHeightBelow"),E(v,"endingHeightAbove"),E(v,"lyricHeightAbove"),E(v,"lyricHeightBelow"),E(v,"partHeightAbove"),E(v,"tempoHeightAbove"),E(v,"volumeHeightAbove"),E(v,"volumeHeightBelow"))),e.moveY(n.STEP,-v.bottom),e.showDebug&&e.showDebug.indexOf("grid")>=0&&e.paper.dottedLine({x1:e.padding.left,x2:e.padding.left+e.controller.width,y1:e.y,y2:e.y,stroke:"#0000aa"})}for(var b=2,y=0,x=0;x<t.voices.length;x++){var k=t.voices[x].staff,w=t.voices[x].tabNameInfos;if(e.y=k.absoluteY,e.controller.classes.incrVoice(),!t.voices[x].duplicate){if(f||(f=e.calcY(10)),p=e.calcY(b),0!==k.lines){k.linePitch&&(b=k.linePitch),e.controller.classes.newMeasure();var C=s(e,t.startx,t.w,k.lines,k.linePitch,.35);p=C[1],k.bottomLine=p,k.topLine=C[0],k.hasTab&&(y=k.topLine),k.hasStaff&&(y=k.hasStaff.topLine,t.voices[x].barto=!0,t.voices[x].topLine=f)}h(e,k.absoluteY,t.brace,x,r),h(e,k.absoluteY,t.bracket,x,r)}i(e,t.voices[x],y,r,{top:m,zero:e.y,height:t.height*n.STEP});var T=0;if(w){var S={rows:[]};S.rows.push({absmove:p+2}),S.rows.push({left:t.startx+8,text:w.name,font:"tablabelfont",klass:"text instrument-name",anchor:"start"}),S.rows.push({move:w.textSize.height}),l(e,S),T=w.textSize.height}e.controller.classes.newMeasure(),t.voices[x].duplicate||(y=e.calcY(2+T))}e.controller.classes.newMeasure();var _=t.staffs.length;function E(t,r){var a=["rgb(207,27,36)","rgb(168,214,80)","rgb(110,161,224)","rgb(191,119,218)","rgb(195,30,151)","rgb(31,170,177)","rgb(220,166,142)"];if(t.positionY&&t.positionY[r]){var i=t.specialY[r]*n.STEP;"chordHeightAbove"===r&&t.specialY.chordLines&&t.specialY.chordLines.above&&(i*=t.specialY.chordLines.above),"chordHeightBelow"===r&&t.specialY.chordLines&&t.specialY.chordLines.below&&(i*=t.specialY.chordLines.below),o(e,{x:e.padding.left,y:e.calcY(t.positionY[r]),width:e.controller.width,height:i,fill:a[d],stroke:a[d],"fill-opacity":.4,"stroke-opacity":.4},r.substr(0,4)),(d+=1)>6&&(d=0)}}_>1&&(f=t.staffs[0].topLine,p=t.staffs[_-1].bottomLine,c(e,t.startx,.6,f,p,null)),e.y=m}},7865:function(e,t,r){var n=r(6637);e.exports=function(e,t,r,a,i,s,o){var c=e.calcY(a);return n(e,t,r,c,i,s,o)}},7641:function(e,t,r){var n=r(7865);e.exports=function(e,t,r,a,i,s){var o="abcjs-top-line",c=2;i&&(c=i),e.paper.openGroup({prepend:!0,klass:e.controller.classes.generate("abcjs-staff")});var l=0,h=0;if(1===a)n(e,t,r,6,o,null,s+e.lineThickness),l=e.calcY(10),h=e.calcY(2);else for(var u=a-1;u>=0;u--){var d=(u+1)*c;h=e.calcY(d),0===l&&(l=h),n(e,t,r,d,o,null,s+e.lineThickness),o=void 0}return e.paper.closeGroup(),[l,h]}},3987:function(e,t,r){var n=r(2435),a=r(5759);e.exports=function(e,t){var r=t.x;void 0===t.pitch&&window.console.error("Tempo Element y-coordinate not set."),t.tempo.el_type="tempo";var i,s=e.calcY(t.pitch)+2;if(t.tempo.preString){i=a(e,{x:r,y:s,text:t.tempo.preString,type:"tempofont",klass:"abcjs-tempo",anchor:"start",noClass:!0,name:"pre"},!0);var o=e.controller.getTextSize.calc(t.tempo.preString,"tempofont","tempo",i).width;r+=o+o/t.tempo.preString.length}if(t.note){t.note.setX(r);for(var c=0;c<t.note.children.length;c++)n(e,t.note.children[c],r);r+=t.note.w+5;var l="= "+t.tempo.bpm;i=a(e,{x:r,y:s,text:l,type:"tempofont",klass:"abcjs-tempo",anchor:"start",noClass:!0,name:"beats"});var h=e.controller.getTextSize.calc(l,"tempofont","tempo",i).width;r+=h+h/l.length}t.tempo.postString&&a(e,{x:r,y:s,text:t.tempo.postString,type:"tempofont",klass:"abcjs-tempo",anchor:"start",noClass:!0,name:"post"},!0)}},5759:function(e,t,r){var n=r(7199);e.exports=function(e,t,r){var a,i,s=t.y;if(t.phrases)return e.paper.richTextLine(t.phrases,t.x,t.y,t.klass,t.anchor);if(t.lane){var o=.25*t.dim.font.size;s+=(t.dim.font.size+o)*t.lane}t.dim?(a=t.dim).attr.class=t.klass:a=e.controller.getFontAndAttr.calc(t.type,t.klass),t.anchor&&(a.attr["text-anchor"]=t.anchor),t["dominant-baseline"]&&(a.attr["dominant-baseline"]=t["dominant-baseline"]),a.attr.x=t.x,a.attr.y=s,t.centerVertically||(a.attr.y+=a.font.size),"debugfont"===t.type&&(console.log("Debug msg: "+t.text),a.attr.stroke="#ff0000"),t.cursor&&(a.attr.cursor=t.cursor),i=(i="free-text"===t.name?t.text.replace(/^[ \t]*\n/gm," \n"):t.text.replace(/\n\n/g,"\n \n")).replace(/^\n/," \n"),a.font.box&&(r||e.paper.openGroup({klass:a.attr.class,fill:e.foregroundColor,"data-name":t.name}),"end"===a.attr["text-anchor"]?a.attr.x-=a.font.padding:"start"===a.attr["text-anchor"]&&(a.attr.x+=a.font.padding),a.attr.y+=a.font.padding,delete a.attr.class),t.noClass&&delete a.attr.class,a.attr.x=n(a.attr.x),a.attr.y=n(a.attr.y),t.name&&(a.attr["data-name"]=t.name);var c=e.paper.text(i,a.attr);if(a.font.box){var l=c.getBBox(),h=0;"middle"===a.attr["text-anchor"]?h=l.width/2+a.font.padding:"end"===a.attr["text-anchor"]&&(h=l.width+2*a.font.padding);var u=0;t.centerVertically&&(u=l.height-a.font.padding),e.paper.rect({"data-name":"box",x:Math.round(t.x-h),y:Math.round(s-u),width:Math.round(l.width+2*a.font.padding),height:Math.round(l.height+2*a.font.padding)}),r||(c=e.paper.closeGroup())}return c}},3272:function(e,t,r){var n=r(6764),a=r(7199),i=function(e,t,r,i,s,o,c,l,h){var u=l?1.2:1.5;t=a(t+6),r=a(r+4),i+=o?u:-u,s+=o?u:-u;var d,f=a(e.calcY(i)),p=a(e.calcY(s)),m=r-t,g=p-f,v=Math.sqrt(m*m+g*g),b=m/v,y=g/v,x=v/3.5,k=l?10:25,w=(o?-1:1)*Math.min(k,Math.max(4,x)),C=a(t+x*b-w*y),T=a(f+x*y+w*b),S=a(r-x*b-w*y),_=a(p-x*y+w*b);if(c?c+=" slur":c="slur",c+=l?" tie":" legato",h){c+=" dotted";var E=n("M %f %f C %f %f %f %f %f %f",t,f,C,T,S,_,r,p);d=e.paper.path({path:E,stroke:e.foregroundColor,fill:"none","stroke-dasharray":"5 5",class:e.controller.classes.generate(c),"data-name":l?"tie":"slur"})}else{var M=n("M %f %f C %f %f %f %f %f %f C %f %f %f %f %f %f z",t,f,C,T,S,_,r,p,a(S-2*y),a(_+2*b),a(C-2*y),a(T+2*b),t,f);d=e.paper.path({path:M,stroke:"none",fill:e.foregroundColor,class:e.controller.classes.generate(c),"data-name":l?"tie":"slur"})}return d};e.exports=function(e,t,r,n,a){!function(e,t,r){e.anchor1&&e.anchor2?e.anchor1.pitch===e.anchor2.pitch&&0===e.internalNotes.length?e.isTie=!0:e.isTie=!1:e.isTie=!0,e.isTie?(e.calcTieDirection(),e.calcX(t,r),e.calcTieY()):(e.calcSlurDirection(),e.calcX(t,r),e.calcSlurY()),e.avoidCollisionAbove()}(t,r,n);var s="";t.anchor1?s+="abcjs-start-m"+t.anchor1.parent.counters.measure+"-n"+t.anchor1.parent.counters.note:s+="abcjs-start-edge",t.anchor2?s+=" abcjs-end-m"+t.anchor2.parent.counters.measure+"-n"+t.anchor2.parent.counters.note:s+=" abcjs-end-edge",t.hint&&(s="abcjs-hint");var o=t.fixedY?1.5:0,c=i(e,t.startX,t.endX,t.startY+o,t.endY+o,t.above,s,t.isTie,t.dotted),l=-1;t.anchor1&&!t.isTie&&(l=t.anchor1.parent.abcelem.startChar-1);var h=-1;return t.anchor2&&!t.isTie&&(h=t.anchor2.parent.abcelem.endChar+1),a.wrapSvgEl({el_type:"slur",startChar:l,endChar:h},c),[c]}},4322:function(e,t,r){var n=r(6764),a=r(5759),i=r(6454),s=r(7199);function o(e,t,r,a){return n("M %f %f L %f %f",s(e),s(t),s(r),s(a))}e.exports=function(e,t,r){e.paper.openGroup({klass:e.controller.classes.generate("triplet "+t.durationClass),"data-name":"triplet"}),t.hasBeam||function(e,t,r,n,a,s){r=e.calcY(r),a=e.calcY(a);var c=s?5:-5,l="";l+=o(t,r,t,r+c),l+=o(n,a,n,a+c);var h=t+(n-t)/2,u=(a-r)/(n-t),d=h-8;l+=o(t,r,d,r+(d-t)*u);var f=h+8;l+=o(f,r+(f-t)*u,n,a),i(e,{path:l,stroke:e.foregroundColor,"data-name":"triplet-bracket"})}(e,t.anchor1.x,t.startNote,t.anchor2.x+t.anchor2.w,t.endNote,t.up),a(e,{x:t.xTextPos,y:e.calcY(t.yTextPos-1),text:""+t.number,type:"tripletfont",anchor:"middle",centerVertically:!0,noClass:!0,name:""+t.number},!0);var n=e.paper.closeGroup();return r.wrapSvgEl({el_type:"triplet",startChar:-1,endChar:-1},n),n}},3145:function(e,t,r){var n=r(9045),a=r(3245),i=r(9879),s=r(4322),o=r(5947),c=r(3272),l=r(7489),h=r(5759),u=r(4750);e.exports=function(e,t,r,d,f){var p=t.w-1;e.staffbottom=t.staff.bottom;var m,g,v=e.foregroundColor;if(t.color&&(e.foregroundColor=t.color),t.header){var b=h(e,{x:e.padding.left,y:e.calcY(t.headerPosition),text:t.header,type:"voicefont",klass:"staff-extra voice-name",anchor:"start",centerVertically:!0,name:"voice-name"},!0);d.wrapSvgEl({el_type:"voiceName",startChar:-1,endChar:-1,text:t.header},b)}var y,x=!1;for(m=0;m<t.children.length;m++){"note"!==(g=t.children[m]).type&&"rest"!==g.type||(x=!0);var k=!1;"staff-extra"===g.type||e.controller.classes.isInMeasure()||(e.controller.classes.startMeasure(),k=!0),t.staff.isTabStaff&&(g.invisible=!1,"bar"==g.type&&g.abcelem.lastBar&&(r=t.topLine)),u(e,g,t.barto||m===t.children.length-1?r:0,d,f),("note"===g.type||"rest"===(y=g).type&&!(!y.abcelem||!y.abcelem.rest||"spacer"===y.abcelem.rest.type))&&e.controller.classes.incrNote(),"bar"===g.type&&!k&&x&&e.controller.classes.incrMeasure()}for(e.controller.classes.startMeasure(),m=0;m<t.beams.length;m++){var w=t.beams[m];"bar"===w?e.controller.classes.incrMeasure():l(e,w,d)}for(e.controller.classes.startMeasure(),m=0;m<t.otherchildren.length;m++)if("bar"===(g=t.otherchildren[m]))e.controller.classes.incrMeasure();else switch(g.type){case"GlissandoElem":g.elemset=n(e,g,d);break;case"CrescendoElem":g.elemset=a(e,g,d);break;case"DynamicDecoration":g.elemset=i(e,g,d);break;case"TripletElem":s(e,g,d);break;case"EndingElem":g.elemset=o(e,g,t.startx+10,p,d);break;case"TieElem":g.elemset=c(e,g,t.startx+10,p,d);break;default:console.log(g),u(e,g,t.startx+10,p,d,f)}e.foregroundColor=v}},5253:function(e,t,r){var n=r(4331),a=r(1897),i=r(8510),s=r(3736),o=r(5588),c=r(4726),l=r(1134),h=r(9316),u=r(8068),d=r(1564),f=r(1954),p=r(1328),m=r(9799),g=r(5012),v=r(2426),b=r(3051),y=function(e,t){t=t||{},this.findSelectableElement=b,this.oneSvgPerLine=t.oneSvgPerLine,this.selectionColor=t.selectionColor,this.dragColor=t.dragColor?t.dragColor:t.selectionColor,this.dragging=!!t.dragging,this.selectTypes=t.selectTypes,this.responsive=t.responsive,this.space=3*n.SPACE,this.initialClef=t.initialClef,this.timeBasedLayout=t.timeBasedLayout,this.expandToWidest=!!t.expandToWidest,this.scale=t.scale?parseFloat(t.scale):0,this.classes=new f({shouldAddClasses:t.add_classes}),this.scale>.1||(this.scale=void 0),t.staffwidth?(this.staffwidthScreen=t.staffwidth,this.staffwidthPrint=t.staffwidth):(this.staffwidthScreen=740,this.staffwidthPrint=680),this.listeners=[],t.clickListener&&this.addSelectListener(t.clickListener),this.renderer=new i(e),this.renderer.setPaddingOverride(t),t.showDebug&&(this.renderer.showDebug=t.showDebug),t.jazzchords&&(this.jazzchords=t.jazzchords),t.accentAbove&&(this.accentAbove=t.accentAbove),t.germanAlphabet&&(this.germanAlphabet=t.germanAlphabet),t.lineThickness&&(this.lineThickness=t.lineThickness),t.chordGrid&&(this.chordGrid=t.chordGrid),this.renderer.controller=this,this.renderer.foregroundColor=t.foregroundColor?t.foregroundColor:"currentColor",void 0!==t.ariaLabel&&(this.renderer.ariaLabel=t.ariaLabel),this.renderer.minPadding=t.minPadding?t.minPadding:0,this.reset()};function x(e){for(var t=document.createElementNS("http://www.w3.org/2000/svg","svg"),r=0;r<e.attributes.length;r++){var n=e.attributes[r];"height"!==n.name&&"aria-label"!=n.name&&t.setAttribute(n.name,n.value)}return t}y.prototype.reset=function(){this.selected=[],this.staffgroups=[],this.engraver&&this.engraver.reset(),this.engraver=null,this.renderer.reset(),this.dragTarget=null,this.dragIndex=-1,this.dragMouseStart={x:-1,y:-1},this.dragYStep=0,this.lineThickness&&this.renderer.setLineThickness(this.lineThickness)},y.prototype.engraveABC=function(e,t,r){void 0===e[0]&&(e=[e]),this.reset();for(var n=0;n<e.length;n++)void 0===t&&(t=n),this.getFontAndAttr=new p(e[n].formatting,this.classes),this.getTextSize=new m(this.getFontAndAttr,this.renderer.paper),this.engraveTune(e[n],t,r)},y.prototype.adjustNonScaledItems=function(e){this.width/=e,this.renderer.adjustNonScaledItems(e)},y.prototype.getMeasureWidths=function(e){this.reset(),this.getFontAndAttr=new p(e.formatting,this.classes),this.getTextSize=new m(this.getFontAndAttr,this.renderer.paper);var t=this.jazzchords;this.setupTune(e,0),this.constructTuneElements(e),d(this.renderer,e,0,this.space,this.timeBasedLayout);for(var r,n=[],a=!0,i=0;i<e.lines.length;i++){var s=e.lines[i];if(s.staff){if(a&&(r={left:0,measureWidths:[],total:0},n.push(r),a=!1),s.staffGroup.voices.length>0)for(var o=s.staffGroup.voices[0],c=!1,l=0,h=0;h<o.children.length;h++){var u=o.children[h];c||u.isClef||u.isKeySig||(c=!0,r.left=u.x,l=u.x),"bar"===u.type&&(r.measureWidths.push(u.x-l),r.total+=u.x-l,l=u.x)}}else a=!0}return this.jazzchords=t,n},y.prototype.setupTune=function(e,t){this.classes.reset(),void 0!==e.formatting.jazzchords&&(this.jazzchords=e.formatting.jazzchords),void 0!==e.formatting.accentAbove&&(this.accentAbove=e.formatting.accentAbove),this.renderer.newTune(e),this.engraver=new a(this.getTextSize,t,{bagpipes:e.formatting.bagpipes,flatbeams:e.formatting.flatbeams,graceSlurs:!1!==e.formatting.graceSlurs,percmap:e.formatting.percmap,initialClef:this.initialClef,jazzchords:this.jazzchords,timeBasedLayout:this.timeBasedLayout,accentAbove:this.accentAbove,germanAlphabet:this.germanAlphabet}),this.engraver.setStemHeight(this.renderer.spacing.stemHeight),this.engraver.measureLength=e.getMeterFraction().num/e.getMeterFraction().den,e.formatting.staffwidth?this.width=1.33*e.formatting.staffwidth:this.width=this.renderer.isPrint?this.staffwidthPrint:this.staffwidthScreen;var r=e.formatting.scale?e.formatting.scale:this.scale;return"resize"===this.responsive&&(r=void 0),void 0===r&&(r=this.renderer.isPrint?.75:1),this.adjustNonScaledItems(r),r},y.prototype.constructTuneElements=function(e){var t,r;e.topText=new l(e.metaText,e.metaTextInfo,e.formatting,e.lines,this.width,this.renderer.isPrint,this.renderer.padding.left,this.renderer.spacing,this.classes.shouldAddClasses,this.getTextSize);var n=!1,a=!1;for(t=0;t<e.lines.length;t++)if((r=e.lines[t]).staff)a=!0,r.staffGroup=this.engraver.createABCLine(r.staff,n?null:e.metaText.tempo,t),n=!0;else if(r.subtitle){if(a){var i=this.width/2+this.renderer.padding.left;r.nonMusic=new c(this.renderer.spacing.subtitle,e.formatting,r.subtitle,i,this.renderer.padding.left,this.getTextSize)}}else void 0!==r.text?(a=!0,r.nonMusic=new s(r.text,r.vskip,this.getFontAndAttr,this.renderer.padding.left,this.width,this.getTextSize)):void 0!==r.separator&&r.separator.lineLength&&(a=!0,r.nonMusic=new o(r.separator.spaceAbove,r.separator.lineLength,r.separator.spaceBelow));e.bottomText=new h(e.metaText,this.width,this.renderer.isPrint,this.renderer.padding.left,this.renderer.spacing,this.classes.shouldAddClasses,this.getTextSize)},y.prototype.engraveTune=function(e,t,r){var n=this.jazzchords,a=this.setupTune(e,t);this.constructTuneElements(e);var i=d(this.renderer,e,this.width,this.space,this.expandToWidest,this.timeBasedLayout);if(this.expandToWidest&&i>this.width+1&&(e.topText=new l(e.metaText,e.metaTextInfo,e.formatting,e.lines,i,this.renderer.isPrint,this.renderer.padding.left,this.renderer.spacing,this.classes.shouldAddClasses,this.getTextSize),e.lines&&e.lines.length>0))for(var s=e.lines.length,o=0;o<s;++o){var c=e.lines[o];if(c.nonMusic&&c.nonMusic.rows&&c.nonMusic.rows.length>0)for(var h=c.nonMusic.rows.length,f=0;f<h;++f){var p=c.nonMusic.rows[f];p.left&&(c.subtitle||c.text&&c.text.length>0&&c.text[0].center)&&(p.left=i/2+this.renderer.padding.left)}}e.tablatures&&v.layoutTablatures(this.renderer,e);var m=g(this.renderer,this.classes,e,this.width,i,this.responsive,a,this.selectTypes,t,r,this.chordGrid);if(this.staffgroups=m.staffgroups,this.selectables=m.selectables,this.oneSvgPerLine){var b=this.renderer.paper.svg.parentNode;this.svgs=function(e,t,r,n,a){r||(r="Untitled");var i=t.querySelector("svg");"resize"===n&&(t.style.paddingBottom="");for(var s=i.querySelector("style"),o="resize"===n?i.viewBox.baseVal.width:i.getAttribute("width"),c=t.querySelectorAll("svg > g"),l=0,h=[],u=0;u<c.length;u++){var d=c[u],f=d.getBBox(),p=f.y-l,m=f.height+p,g=document.createElement("div"),v="overflow: hidden;";"resize"!==n&&(v+="height:"+m*a+"px;"),g.setAttribute("style",v);var b=x(i),y='Sheet Music for "'+r+'" section '+(u+1);b.setAttribute("aria-label",y),"resize"!==n&&b.setAttribute("height",m),"resize"===n&&(b.style.position="");var k=e.firefox?m+1:m;b.setAttribute("viewBox","0 "+l+" "+o+" "+k),b.appendChild(s.cloneNode(!0));var w=document.createElement("title");w.innerText=y,b.appendChild(w),b.appendChild(d),g.appendChild(b),h.push(b),t.appendChild(g),l=f.y+f.height}return t.removeChild(i),h}(this.renderer,b,e.metaText.title,this.responsive,a)}else this.svgs=[this.renderer.paper.svg];u(this,this.svgs),this.jazzchords=n},y.prototype.getDim=function(e){if(!e.dim){var t=e.svgEl.getBBox();e.dim={left:Math.round(t.x),top:Math.round(t.y),right:Math.round(t.x+t.width),bottom:Math.round(t.y+t.height)}}return e.dim},y.prototype.addSelectListener=function(e){this.listeners[this.listeners.length]=e},e.exports=y},1954:function(e){var t=function(e){this.shouldAddClasses=e.shouldAddClasses,this.reset()};t.prototype.reset=function(){this.lineNumber=null,this.voiceNumber=null,this.measureNumber=null,this.measureTotalPerLine=[],this.noteNumber=null},t.prototype.incrLine=function(){null===this.lineNumber?this.lineNumber=0:this.lineNumber++,this.voiceNumber=null,this.measureNumber=null,this.noteNumber=null},t.prototype.incrVoice=function(){null===this.voiceNumber?this.voiceNumber=0:this.voiceNumber++,this.measureNumber=null,this.noteNumber=null},t.prototype.isInMeasure=function(){return null!==this.measureNumber},t.prototype.newMeasure=function(){this.measureNumber&&(this.measureTotalPerLine[this.lineNumber]=this.measureNumber),this.measureNumber=null,this.noteNumber=null},t.prototype.startMeasure=function(){this.measureNumber=0,this.noteNumber=0},t.prototype.incrMeasure=function(){this.measureNumber++,this.noteNumber=0},t.prototype.incrNote=function(){this.noteNumber++},t.prototype.measureTotal=function(){for(var e=0,t=0;t<this.lineNumber;t++)e+=this.measureTotalPerLine[t]?this.measureTotalPerLine[t]:0;return this.measureNumber&&(e+=this.measureNumber),e},t.prototype.getCurrent=function(e){return{line:this.lineNumber,measure:this.measureNumber,measureTotal:this.measureTotal(),voice:this.voiceNumber,note:this.noteNumber}},t.prototype.generate=function(e){if(!this.shouldAddClasses)return"";var t=[];if(e&&e.length>0&&t.push(e),"abcjs-tab-number"===e)return t.join(" ");if("text instrument-name"===e)return"abcjs-text abcjs-instrument-name";if(null!==this.lineNumber&&t.push("l"+this.lineNumber),null!==this.measureNumber&&t.push("m"+this.measureNumber),null!==this.measureNumber&&t.push("mm"+this.measureTotal()),null!==this.voiceNumber&&t.push("v"+this.voiceNumber),e&&(e.indexOf("note")>=0||e.indexOf("rest")>=0||e.indexOf("lyric")>=0)&&null!==this.noteNumber&&t.push("n"+this.noteNumber),t.length>0){t=(t=t.join(" ")).split(" ");for(var r=0;r<t.length;r++)0!==t[r].indexOf("abcjs-")&&t[r].length>0&&(t[r]="abcjs-"+t[r])}return t.join(" ")},e.exports=t},1328:function(e){var t=function(e,t){this.formatting=e,this.classes=t};t.prototype.updateFonts=function(e){e.gchordfont&&(this.formatting.gchordfont=e.gchordfont),e.tripletfont&&(this.formatting.tripletfont=e.tripletfont),e.annotationfont&&(this.formatting.annotationfont=e.annotationfont),e.vocalfont&&(this.formatting.vocalfont=e.vocalfont)},t.prototype.getFamily=function(e){return'"'===e[0]&&'"'===e[e.length-1]?e.substring(1,e.length-1):e},t.prototype.calc=function(e,t){var r;r="string"==typeof e?(r=this.formatting[e])?{face:r.face,size:Math.round(4*r.size/3),decoration:r.decoration,style:r.style,weight:r.weight,box:r.box}:{face:"Arial",size:Math.round(16),decoration:"underline",style:"normal",weight:"normal"}:{face:e.face,size:Math.round(4*e.size/3),decoration:e.decoration,style:e.style,weight:e.weight,box:e.box};var n=this.formatting.fontboxpadding?this.formatting.fontboxpadding:.1;return r.padding=r.size*n,{font:r,attr:{"font-size":r.size,"font-style":r.style,"font-family":this.getFamily(r.face),"font-weight":r.weight,"text-decoration":r.decoration,class:this.classes.generate(t)}}},e.exports=t},9799:function(e){var t=function(e,t){this.getFontAndAttr=e,this.svg=t};t.prototype.updateFonts=function(e){this.getFontAndAttr.updateFonts(e)},t.prototype.attr=function(e,t){return this.getFontAndAttr.calc(e,t)},t.prototype.getFamily=function(e){return'"'===e[0]&&'"'===e[e.length-1]?e.substring(1,e.length-1):e},t.prototype.calc=function(e,t,r,n){var a;a="string"==typeof t?this.attr(t,r):{font:{face:t.face,size:t.size,decoration:t.decoration,style:t.style,weight:t.weight},attr:{"font-size":t.size,"font-style":t.style,"font-family":this.getFamily(t.face),"font-weight":t.weight,"text-decoration":t.decoration,class:this.getFontAndAttr.classes.generate(r)}};var i=this.svg.getTextSize(e,a.attr,n);return a.font.box?{height:i.height+4*a.font.padding,width:i.width+4*a.font.padding}:i},t.prototype.baselineToCenter=function(e,t,r,n,a){return.5*this.calc(e,t,r).height+(a-n-2)*this.attr(t,r).font.size},e.exports=t},2187:function(e){e.exports=function(e,t,r,n){if(e)for(var a=0;a<e.length;a++){var i=e[a],s=i.getAttribute("highlight");s||(s="fill"),i.setAttribute(s,n);var o=i.getAttribute("class");o||(o=""),o=(o=o.replace(r,"")).replace(t,""),t.length>0&&(o.length>0&&" "!==o[o.length-1]&&(o+=" "),o+=t),i.setAttribute("class",o)}}},4331:function(e){var t={FONTEM:360,FONTSIZE:30};t.STEP=93*t.FONTSIZE/720,t.SPACE=10,t.TOPNOTE=15,t.STAVEHEIGHT=100,t.INDENT=50,e.exports=t},8123:function(e){function t(e,t,r,n){if(0===e.indexOf(t)){var a=e.replace(t,""),i=parseInt(a,10);""+i===a&&(r[n]=i)}}e.exports=function(e,r){var n=[];if(e.absEl.elemset){for(var a={},i=0;i<e.absEl.elemset.length;i++){var s=e.absEl.elemset[i];if(s)for(var o=s.getAttribute("class").split(" "),c=0;c<o.length;c++)a[o[c]]=!0}for(var l=0;l<Object.keys(a).length;l++)n.push(Object.keys(a)[l])}for(var h={},u=0;u<n.length;u++)t(n[u],"abcjs-v",h,"voice"),t(n[u],"abcjs-l",h,"line"),t(n[u],"abcjs-m",h,"measure");e.staffPos&&(h.staffPos=e.staffPos);for(var d=r.target;d&&d.dataset&&!d.dataset.name&&"svg"!==d.tagName.toLowerCase();)d=d.parentNode;for(var f=r.target;f&&f.dataset&&!f.dataset.index&&"svg"!==f.tagName.toLowerCase();)f=f.parentNode;return f&&f.dataset&&(h.name=f.dataset.name,h.clickedName=d.dataset.name,h.parentClasses=f.classList),d&&d.classList&&(h.clickedClasses=d.classList),h.selectableElement=e.svgEl,{classes:n,analysis:h}}},3051:function(e,t,r){var n=r(8123);e.exports=function(e){for(var t=e;t&&t.attributes&&"svg"!==t.tagName.toLowerCase()&&!t.attributes.selectable;)t=t.parentNode;if(t&&t.attributes&&t.attributes.selectable){var r=t.attributes["data-index"].nodeValue;if(r&&(r=parseInt(r,10))>=0&&r<this.selectables.length){var a=this.selectables[r],i=n(a,e);return i.index=r,i.element=a,i}}return null}},5741:function(e,t,r){var n=r(2187);e.exports=function(e,t){void 0===e&&(e="abcjs-note_selected"),void 0===t&&(t="#ff0000"),n(this.elemset,e,"",t)}},8068:function(e,t,r){var n=r(4331),a=r(8123);function i(e){"keyboard"===this.dragMechanism&&0!==this.dragYStep&&this.dragTarget&&p.bind(this)(this.dragTarget,this.dragYStep,this.selectables.length,this.dragIndex,e),this.dragYStep=0}function s(e){switch(e.keyCode){case 38:case 40:e.preventDefault()}}function o(e){var t=!1,r=e.target.dataset.index;switch(e.keyCode){case 13:case 32:t=!0,this.dragTarget=this.selectables[r],this.dragIndex=r,this.dragMechanism="keyboard",d.bind(this)(e);break;case 38:t=!0,this.dragTarget=this.selectables[r],this.dragIndex=r,this.dragTarget&&this.dragTarget.isDraggable&&(this.dragging&&this.dragTarget.isDraggable&&this.dragTarget.absEl.highlight(void 0,this.dragColor),this.dragYStep--,this.dragTarget.svgEl.setAttribute("transform","translate(0,"+this.dragYStep*n.STEP+")"));break;case 40:t=!0,this.dragTarget=this.selectables[r],this.dragIndex=r,this.dragMechanism="keyboard",this.dragTarget&&this.dragTarget.isDraggable&&(this.dragging&&this.dragTarget.isDraggable&&this.dragTarget.absEl.highlight(void 0,this.dragColor),this.dragYStep++,this.dragTarget.svgEl.setAttribute("transform","translate(0,"+this.dragYStep*n.STEP+")"));break;case 9:0!==this.dragYStep&&d.bind(this)(e)}t&&e.preventDefault()}function c(e,t){var r,n,a,i=function(e,t){if(!t)return-1;var r=t.dataset;if(!r)return-1;for(var n=r.index,a=0;a<e.length;a++){var i=e[a].svgEl.dataset;if(i&&n===i.index)return a}return-1}(e.selectables,function(e){if(!e)return null;if("svg"===e.tagName)return e;if(!e.getAttribute)return null;for(var t=e.getAttribute("selectable");!t;)t=!e.parentElement||"svg"===(e=e.parentElement).tagName||e.getAttribute("selectable");return e}(t.target));return i>=0?(a=function(e,t,r){return e.x<=t.offsetX&&e.x+e.width>=t.offsetX&&e.y<=t.offsetY&&e.y+e.height>=t.offsetY||Math.abs(t.layerY/r-t.offsetY)<3?[t.offsetX,t.offsetY]:[t.layerX,t.layerY]}(e.selectables[i].svgEl.getBBox(),t,e.scale),r=a[0],n=a[1]):(a=function(e){var t,r,n=1,a=1,i=e.target.closest("svg"),s=0;return i&&i.viewBox&&i.viewBox.baseVal&&(0!==i.viewBox.baseVal.width&&(n=i.viewBox.baseVal.width/i.clientWidth),0!==i.viewBox.baseVal.height&&(a=i.viewBox.baseVal.height/i.clientHeight),s=i.viewBox.baseVal.y),e.target&&"svg"===e.target.tagName?(t=e.offsetX,r=e.offsetY):(t=e.layerX,r=e.layerY),[t*=n,(r*=a)+s]}(t),i=function(e,t,r){for(var n=9999999,a=-1,i=0;i<e.selectables.length&&n>0;i++){var s=e.selectables[i];if(e.getDim(s),s.dim.left<t&&s.dim.right>t&&s.dim.top<r&&s.dim.bottom>r)a=i,n=0;else if(s.dim.top<r&&s.dim.bottom>r){var o=Math.min(Math.abs(s.dim.left-t),Math.abs(s.dim.right-t));o<n&&(n=o,a=i)}else if(s.dim.left<t&&s.dim.right>t){var c=Math.min(Math.abs(s.dim.top-r),Math.abs(s.dim.bottom-r));c<n&&(n=c,a=i)}else{var l=Math.abs(t-s.dim.left)>Math.abs(t-s.dim.right)?Math.abs(t-s.dim.right):Math.abs(t-s.dim.left),h=Math.abs(r-s.dim.top)>Math.abs(r-s.dim.bottom)?Math.abs(r-s.dim.bottom):Math.abs(r-s.dim.top),u=Math.sqrt(l*l+h*h);u<n&&(n=u,a=i)}}return a>=0&&n<=12?a:-1}(e,r=a[0],n=a[1])),{x:r,y:n,clickedOn:i}}function l(e){if(e&&e.target&&e.touches&&!(e.touches.length<1)){var t=e.target.getBoundingClientRect(),r=e.touches[0].pageX-t.left,n=e.touches[0].pageY-t.top;e.touches[0].offsetX=r,e.touches[0].offsetY=n,e.touches[0].layerX=e.touches[0].pageX,e.touches[0].layerY=e.touches[0].pageY}}function h(e){var t=e;"touchstart"===e.type&&(l(e),e.touches.length>0&&(t=e.touches[0]));var r=c(this,t);r.clickedOn>=0&&("touchstart"===e.type||0===e.button)&&this.selectables[r.clickedOn]&&(this.dragTarget=this.selectables[r.clickedOn],this.dragIndex=r.clickedOn,this.dragMechanism="mouse",this.dragMouseStart={x:r.x,y:r.y},this.dragging&&this.dragTarget.isDraggable&&(function(e){if(e){var t=v(e.svg);t["abcjs-dragging-in-progress"]=!0,b(e.svg,t)}}(this.renderer.paper),this.dragTarget.absEl.highlight(void 0,this.dragColor)))}function u(e){var t=e;if("touchmove"===e.type&&(l(e),e.touches.length>0&&(t=e.touches[0])),this.lastTouchMove=e,this.dragTarget&&this.dragging&&this.dragTarget.isDraggable&&"mouse"===this.dragMechanism&&this.dragMouseStart){var r=c(this,t),a=Math.round((r.y-this.dragMouseStart.y)/n.STEP);a!==this.dragYStep&&(this.dragYStep=a,this.dragTarget.svgEl.setAttribute("transform","translate(0,"+a*n.STEP+")"))}}function d(e){var t=e;"touchend"===e.type&&this.lastTouchMove&&(l(this.lastTouchMove),this.lastTouchMove&&this.lastTouchMove.touches&&this.lastTouchMove.touches.length>0&&(t=this.lastTouchMove.touches[0])),this.dragTarget&&(m.bind(this)(),this.dragTarget.absEl&&this.dragTarget.absEl.highlight&&(this.selected=[this.dragTarget.absEl],this.dragTarget.absEl.highlight(void 0,this.selectionColor)),p.bind(this)(this.dragTarget,this.dragYStep,this.selectables.length,this.dragIndex,t),this.dragTarget.svgEl&&this.dragTarget.svgEl.focus&&(this.dragTarget.svgEl.focus(),this.dragTarget=null,this.dragIndex=-1),function(e){if(e){var t=v(e.svg);delete t["abcjs-dragging-in-progress"],b(e.svg,t)}}(this.renderer.svg))}function f(e){e>=0&&e<this.selectables.length&&(this.dragTarget=this.selectables[e],this.dragIndex=e,this.dragMechanism="keyboard",d.bind(this)({target:this.dragTarget.svgEl}))}function p(e,t,r,n,i){for(var s=a(e,i),o=s.classes,c=s.analysis,l=0;l<this.listeners.length;l++)this.listeners[l](e.absEl.abcelem,e.absEl.tuneNumber,o.join(" "),c,{step:t,max:r,index:n,setSelection:f.bind(this)},i)}function m(){for(var e=0;e<this.selected.length;e++)this.selected[e].unhighlight(void 0,this.renderer.foregroundColor);this.selected=[]}function g(e,t){m.bind(this)();for(var r=0;r<this.staffgroups.length;r++)for(var n=this.staffgroups[r].voices,a=0;a<n.length;a++)for(var i=n[a].children,s=0;s<i.length;s++){var o=i[s].abcelem.startChar,c=i[s].abcelem.endChar;(t>o&&e<c||t===e&&t===c)&&(this.selected[this.selected.length]=i[s],i[s].highlight(void 0,this.selectionColor))}}function v(e){var t=e.getAttribute("class");t||(t="");for(var r=t.split(" "),n={},a=0;a<r.length;a++)n[r[a]]=!0;return n}function b(e,t){var r=[];for(var n in t)t.hasOwnProperty(n)&&r.push(n);e.setAttribute("class",r.join(" "))}e.exports=function(e,t){if(e.rangeHighlight=g,e.dragging)for(var r=0;r<e.selectables.length;r++){var n=e.selectables[r];"true"===n.svgEl.getAttribute("selectable")&&(n.svgEl.setAttribute("tabindex",0),n.svgEl.setAttribute("data-index",r),n.svgEl.addEventListener("keydown",s.bind(e)),n.svgEl.addEventListener("keyup",o.bind(e)),n.svgEl.addEventListener("focus",i.bind(e)))}for(var a=0;a<t.length;a++)t[a].addEventListener("touchstart",h.bind(e),{passive:!0}),t[a].addEventListener("touchmove",u.bind(e),{passive:!0}),t[a].addEventListener("touchend",d.bind(e),{passive:!0}),t[a].addEventListener("mousedown",h.bind(e)),t[a].addEventListener("mousemove",u.bind(e)),t[a].addEventListener("mouseup",d.bind(e))}},5829:function(e,t,r){var n=r(2187);e.exports=function(e,t){void 0===e&&(e="abcjs-note_selected"),void 0===t&&(t="#000000"),n(this.elemset,"",e,t)}},6251:function(e,t,r){var n=r(6658),a=r(4331),i=r(3721),s=function(e){return void 0===e?0:Math.floor(Math.log(e)/Math.log(2))};function o(e,t,r,n){if(!e.children)return n;for(var a=0;a<e.children.length;a++){var i=e.children[a];t&&void 0!==i.top&&"flags.ugrace"===i.c?n=Math.max(n,i.top-r):t||void 0===i.bottom||"flags.ugrace"!==i.c||(n=Math.max(n,r-i.bottom+7))}return n}function c(e,t,r){var n=t.heads[e?0:t.heads.length-1],a=r.heads[e?0:r.heads.length-1],i=n.x;e&&(i+=n.w-.6);var s=a.x;return[i,s+=e?a.w:.6]}function l(e,t){for(var r=t+1;r<e.length;r++)if(!e[r].abcelem.rest)return r;return-1}function h(e,t){for(var r=t-1;r>=0;r--)if(!e[r].abcelem.rest)return r;return-1}e.exports=function(e){if(0!==e.elems.length&&!e.allrests){var t=function(e,t){var r=e?a.STEP:-a.STEP;return t&&(r*=.4),r}(e.stemsUp,e.isgrace),r=e.elems[0],u=e.elems[e.elems.length-1],d=0,f=e.stemsUp?r.abcelem.maxpitch:r.abcelem.minpitch;d=o(r,e.stemsUp,f,d),d=o(u,e.stemsUp,f,d),d=Math.max(e.stemHeight,d+3);var p=(b=e.average,y=e.elems.length,x=d,k=e.stemsUp,w=r.abcelem.averagepitch,C=u.abcelem.averagepitch,T=e.isflat,S=e.min,_=e.max,E=e.isgrace,M=x-2,A=x-2,N=Math.round(k?Math.max(b+M,_+A):Math.min(b-M,S-A)),B=function(e,t,r,n){if(n)return 0;var a=e-t,i=r/2;return a>i&&(a=i),a<-i&&(a=-i),a}(w,C,y,T),P=N+Math.floor(B/2),L=N+Math.floor(-B/2),E||(k&&N<6||!k&&N>6)&&(P=6,L=6),[P,L]),m=c(e.stemsUp,r,u);e.addBeam({startX:m[0],endX:m[1],startY:p[0],endY:p[1],dy:t});for(var g=function(e,t,r,n,a){for(var o=[],u=[],d=0;d<e.length;d++){var f=e[d];if(!f.abcelem.rest){var p=f.heads[t?0:f.heads.length-1],m=p.x+(t?p.w:0),g=i(r.startX,r.startY,r.endX,r.endY,m),v=t?-1.5:1.5;n&&(v=2*v/3);var b=f.abcelem.duration;0===b&&(b=.25);for(var y=s(b);y<-3;y++){var x=-4-y;if(u[x]?u[x].single=!1:u[x]={x:m+(t?-.6:0),y:g+v*(x+1),durlog:y,single:!0},d>0&&f.abcelem.beambr&&f.abcelem.beambr<=x+1){u[x].split||(u[x].split=[u[x].x]);var k=c(t,e[d-1],f);u[x].split[u[x].split.length-1]>=k[0]&&(k[0]+=f.w),u[x].split.push(k[0]),u[x].split.push(k[1])}}for(var w=u.length-1;w>=0;w--){var C=l(e,d);if(-1===C||C<e.length&&s(e[C].abcelem.duration)>-w-4){var T=m,S=g+v*(w+1);if(u[w].single){var _=h(e,d);if(-1===_)T=m+5;else if(-1===C)T=m-5;else{var E=e[_].abcelem.duration,M=e[C].abcelem.duration;T=E===M?d%2==0?m+5:m-5:E<M?m+5:m-5}S=i(r.startX,r.startY,r.endX,r.endY,T)+v*(w+1)}var A={startX:u[w].x,endX:T,startY:u[w].y,endY:S,dy:a};if(void 0!==u[w].split){var N=u[w].split;A.endX<=N[N.length-1]&&(N[N.length-1]-=f.w),N.push(A.endX),A.split=u[w].split}o.push(A),u=u.slice(0,w)}}}}return o}(e.elems,e.stemsUp,e.beams[0],e.isgrace,t),v=0;v<g.length;v++)e.addBeam(g[v]);!function(e,t,r,s,o){for(var c=0;c<e.length;c++){var l=e[c];if(!l.abcelem.rest){var h=!l.addExtra,u=h?o:l,d=l.heads[t?0:l.heads.length-1],f=d.pitch+(t?.2:-.2),p=t?d.w:0;h||(p+=d.dx);var m=d.x+p,g=i(r.startX,r.startY,r.endX,r.endY,m),v=t?-.6:.6;t||(g-=s/2/a.STEP),h&&(p+=l.heads[0].dx),"noteheads.slash.quarter"===d.c&&(t?f+=1:f-=1);var b=new n(null,p,0,f,{type:"stem",pitch2:g,linewidth:v});b.setX(u.x),u.addRight(b)}}}(e.elems,e.stemsUp,e.beams[0],t,e.mainNote)}var b,y,x,k,w,C,T,S,_,E,M,A,N,B,P,L}},3721:function(e){e.exports=function(e,t,r,n,a){return t+(n-t)/(r-e)*(a-e)}},4760:function(e){function t(e,t,r){if(t)for(var n=0;n<t.length;n++)if(t[n].header){var a=r.calc(t[n].header,"voicefont","");e=Math.max(e,a.width)}return e}function r(e,t,r){if(e)for(var a=0;a<e.length;a++)n(t,e[a]),r=Math.max(r,e[a].getWidth());return r}function n(e,t){t.x=e}e.exports=function(e,n,a,i,s){var o,c,l=e.padding.left,h=0;for(o=0;o<a.length;o++)a[o].header&&(c=n.calc(a[o].header,"voicefont",""),h=Math.max(h,c.width));h=t(h,i,n),(h=t(h,s,n))&&(h+=n.calc("A","voicefont","").width);var u=0;return u=r(i,l+=h,u),l+r(s,l,u)}},5687:function(e,t,r){var n=r(4760);e.exports=function(e,t,r){var a=n(e,t.getTextSize,t.voices,t.brace,t.bracket),i=function(e,t){for(var r=0,n=0,a=0;a<e.voices.length;a++){for(var i=0,s=e.voices[a],o=0;o<s.children.length;o++){var c=s.children[o];if(i+=c.duration,c.duration){var l=(c.w+t)/c.duration;r=Math.max(r,l)}}n=Math.max(n,i)}return{totalDuration:n,minSpacing:r}}(t,r.minPadding),s=i.totalDuration,o=i.minSpacing*s;r.minWidth&&(o=Math.max(o,r.minWidth));var c=r.minPadding?r.minPadding/2:2;t.startx=a,t.w=o+a;for(var l=0;l<t.voices.length;l++){var h=t.voices[l];h.startx=a,h.w=o+a;for(var u=a,d=!1,f=0,p=0;p<h.children.length;p++){var m=h.children[p];d||(0!==m.duration?(d=!0,f=(o+a-u)/s,t.gridStart=u):(m.x=u,u+=m.w+m.minspacing)),d&&("center"===r.align?m.x=u+m.duration*f/2-m.w/2:0===m.duration?m.x=u+1-m.w:m.x=u+c-m.extraw,u+=m.duration*f);for(var g=0;g<m.children.length;g++){var v=m.children[g],b=v.dx?v.dx:0;v.x=m.x+b}}t.gridEnd=u}return o}},1564:function(e,t,r){var n=r(6759),a=r(6934),i=r(735),s=r(4760),o=r(5687),c=r(1277),l=function(e,t,r,n,a,o,c){for(var l=s(e,n.getTextSize,n.voices,n.brace,n.bracket),u=r,d=0;d<8;d++){var f=i(u,e.minPadding,c,n,l);if(u=h(o,a.stretchlast,t+e.padding.left,n.w,u,f.spacingUnits,f.minSpace,e.padding.left+e.padding.right),c&&console.log("setXSpace",d,n.w,u,n.minspace),null===u)break}return function(e){for(var t=0;t<e.length;t++)for(var r=e[t],n=1;n<r.children.length-1;n++){var a=r.children[n];if(a.abcelem.rest&&("whole"===a.abcelem.rest.type||"multimeasure"===a.abcelem.rest.type)){var i=r.children[n-1],s=r.children[n+1];a.center(i,s)}}}(n.voices),n.w-l};function h(e,t,r,n,a,i,s,o){if(e)if(void 0===t){if(n/r<.66)return null}else if(!(1-(n+o)/r<t))return null;return Math.abs(r-n)<2?null:i>0?((a=(r-(n-i*a))/i)*s>50&&(a=50/s),a):null}function u(e){for(var t=0;t<e.length;t++)for(var r=e[t],n=Object.keys(r),a=0;a<n.length;a++){var i=r[n[a]],s=i.length-1;if(i.length>1){var o=i[0].abcelem.rest&&"rest"===i[0].abcelem.rest.type,c=i[s].abcelem.rest&&"rest"===i[s].abcelem.rest.type;if(o&&!i[s].abcelem.rest){var l=i[0].children.find(function(e){return e.name.includes("rest")}),h=d(i[s]);if(l){var u=l.bottom-h;(u-=2)<0&&i[0].children.length>0&&(i[0].bottom-=u,i[0].top-=u,i[0].children[0].bottom-=u,i[0].children[0].top-=u,i[0].children[0].pitch-=u)}}else if(c&&!i[0].abcelem.rest){var p=i[s].children.find(function(e){return e.name.includes("rest")});if(p){var m=p.top-f(i[0]);(m+=2)>0&&i[s].children.length>0&&(i[s].bottom-=m,i[s].top-=m,i[s].children[0].bottom-=m,i[s].children[0].top-=m,i[s].children[0].pitch-=m)}}}}}function d(e){if(e.children){for(var t=-90,r=0;r<e.children.length;r++){var n=e.children[r];"chord"!==n.type&&(t=Math.max(t,n.top))}if(t>-90)return t}return e.top}function f(e){if(e.children){for(var t=90,r=0;r<e.children.length;r++){var n=e.children[r];"lyric"!==n.type&&(t=Math.min(t,n.bottom))}if(t<90)return t}return e.bottom}e.exports=function(e,t,r,i,s,h){var d,f,p=r;for(d=0;d<t.lines.length;d++){var m;(f=t.lines[d]).staff&&(m=void 0!==h?o(e,f.staffGroup,h):l(e,p,i,f.staffGroup,t.formatting,d===t.lines.length-1,!1),Math.round(m)>Math.round(p)&&(p=m,s&&(d=-1)))}for(d=0;d<t.lines.length;d++)if((f=t.lines[d]).staffGroup&&f.staffGroup.voices){for(var g=0;g<f.staffGroup.voices.length;g++)n(f.staffGroup.voices[g]);a(e,f.staffGroup)}var v=c(t.lines);for(d=0;d<t.lines.length;d++)(f=t.lines[d]).staffGroup&&u(v[d]);for(d=0;d<t.lines.length;d++)(f=t.lines[d]).staffGroup&&f.staffGroup.setHeight();return p}},6934:function(e,t,r){var n=r(4331);function a(e,t,r,n){if(e.specialY[r]){var a=e.specialY[r];n&&(a*=n),e.top+=a+1,t[r]=e.top}}function i(e,t,r){var n,a,i=0;for(n=0;n<t.children.length;n++){var h=s(e,a=t.children[n],r);h<a.bottom&&(i=a.bottom-h,a.bottom=h,t.bottom=h)}for(n=0;n<t.otherchildren.length;n++)switch((a=t.otherchildren[n]).type){case"CrescendoElem":o(e,a);break;case"DynamicDecoration":c(e,a);break;case"EndingElem":l(e,a);break;case"TieElem":var u=a.getYBounds();t.staff.top=Math.max(t.staff.top,u[0]),t.staff.top=Math.max(t.staff.top,u[1]),t.staff.bottom=Math.min(t.staff.bottom,u[0]),t.staff.bottom=Math.min(t.staff.bottom,u[1])}return i}function s(e,t,r){for(var n=t.bottom,a=0;a<t.children.length;a++){var i=t.children[a];for(var s in t.specialY)t.specialY.hasOwnProperty(s)&&i[s]&&(i.pitch=e[s],"lyricHeightBelow"===s&&"lyric"===i.type&&i.voiceNumber&&(i.pitch-=i.voiceNumber*i[s],n=Math.min(t.bottom,i.pitch)),void 0===i.top&&("TempoElement"===i.type?h(e,i):u(e,i,r),t.pushTop(i.top),t.pushBottom(i.bottom)))}return n}function o(e,t){t.dynamicHeightAbove?t.pitch=e.dynamicHeightAbove:t.pitch=e.dynamicHeightBelow}function c(e,t){t.volumeHeightAbove?t.pitch=e.volumeHeightAbove:t.pitch=e.volumeHeightBelow}function l(e,t){t.pitch=e.endingHeightAbove-2}function h(e,t){if(t.pitch=e.tempoHeightAbove,t.top=e.tempoHeightAbove,t.bottom=e.tempoHeightAbove,t.note){var r=t.pitch-t.totalHeightInPitches+1;t.note.top=r,t.note.bottom=r;for(var n=0;n<t.note.children.length;n++){var a=t.note.children[n];a.top+=r,a.bottom+=r,a.pitch+=r,void 0!==a.pitch2&&(a.pitch2+=r)}}}function u(e,t,r){switch(t.type){case"part":t.top=e.partHeightAbove+t.height,t.bottom=e.partHeightAbove;break;case"text":case"chord":t.chordHeightAbove?(t.top=e.chordHeightAbove,t.bottom=e.chordHeightAbove):(t.top=e.chordHeightBelow,t.bottom=e.chordHeightBelow);break;case"lyric":t.lyricHeightAbove?(t.top=e.lyricHeightAbove,t.bottom=e.lyricHeightAbove):(t.top=e.lyricHeightBelow+r.vocal/n.STEP,t.bottom=e.lyricHeightBelow+r.vocal/n.STEP,t.pitch-=r.vocal/n.STEP);break;case"debug":t.top=e.chordHeightAbove,t.bottom=e.chordHeightAbove}void 0!==t.pitch&&void 0!==t.top||console.error("RelativeElement position not set.",t.type,t.pitch,t.top,e)}e.exports=function(e,t){for(var r,s=0;s<t.staffs.length;s++){var o=t.staffs[s],c={tempoHeightAbove:0,partHeightAbove:0,volumeHeightAbove:0,dynamicHeightAbove:0,endingHeightAbove:0,chordHeightAbove:0,lyricHeightAbove:0,lyricHeightBelow:0,chordHeightBelow:0,volumeHeightBelow:0,dynamicHeightBelow:0};if(e.showDebug&&e.showDebug.indexOf("box")>=0&&(o.originalTop=o.top,o.originalBottom=o.bottom),a(o,c,"lyricHeightAbove"),a(o,c,"chordHeightAbove",o.specialY.chordLines.above),o.specialY.endingHeightAbove&&(o.specialY.chordHeightAbove?o.top+=2:o.top+=o.specialY.endingHeightAbove+1,c.endingHeightAbove=o.top),o.specialY.dynamicHeightAbove&&o.specialY.volumeHeightAbove?(o.top+=Math.max(o.specialY.dynamicHeightAbove,o.specialY.volumeHeightAbove)+1,c.dynamicHeightAbove=o.top,c.volumeHeightAbove=o.top):(a(o,c,"dynamicHeightAbove"),a(o,c,"volumeHeightAbove")),a(o,c,"partHeightAbove"),a(o,c,"tempoHeightAbove"),o.specialY.lyricHeightBelow&&(o.specialY.lyricHeightBelow+=e.spacing.vocal/n.STEP,c.lyricHeightBelow=o.bottom,o.bottom-=o.specialY.lyricHeightBelow+1),o.specialY.chordHeightBelow){c.chordHeightBelow=o.bottom;var l=o.specialY.chordHeightBelow;o.specialY.chordLines.below&&(l*=o.specialY.chordLines.below),o.bottom-=l+1}o.specialY.volumeHeightBelow&&o.specialY.dynamicHeightBelow?(c.volumeHeightBelow=o.bottom,c.dynamicHeightBelow=o.bottom,o.bottom-=Math.max(o.specialY.volumeHeightBelow,o.specialY.dynamicHeightBelow)+1):o.specialY.volumeHeightBelow?(c.volumeHeightBelow=o.bottom,o.bottom-=o.specialY.volumeHeightBelow+1):o.specialY.dynamicHeightBelow&&(c.dynamicHeightBelow=o.bottom,o.bottom-=o.specialY.dynamicHeightBelow+1),e.showDebug&&e.showDebug.indexOf("box")>=0&&(o.positionY=c);for(var h=0;h<o.voices.length;h++){var u=i(c,t.voices[o.voices[h]],e.spacing);o.bottom-=u}if(void 0!==r){var d=r+(o.top-10),f=e.spacing.systemStaffSeparation/n.STEP-d;f>0&&(o.top+=f)}o.top+=e.spacing.staffTopMargin/n.STEP,r=2-o.bottom}}},735:function(e,t,r){var n=r(937);function a(e){for(var t=0;t<e.length;t++)if(!n.layoutEnded(e[t]))return!1;return!0}function i(e){return e.durationindex-(e.children[e.i]&&e.children[e.i].duration>0?0:5e-7)}e.exports=function(e,t,r,s,o){var c,l=0,h=1e3,u=o;s.startx=u;var d,f,p=0;for(r&&console.log("init layout",e),c=0;c<s.voices.length;c++)n.beginLayout(u,s.voices[c]);for(var m=0;!a(s.voices);){for(p=null,c=0;c<s.voices.length;c++)n.layoutEnded(s.voices[c])||p&&!(i(s.voices[c])<p)||(p=i(s.voices[c]));var g=[],v=[];for(c=0;c<s.voices.length;c++)i(s.voices[c])-p>1e-7?v.push(s.voices[c]):g.push(s.voices[c]);m=0;var b=0;for(c=0;c<g.length;c++)n.getNextX(g[c])>u&&(u=n.getNextX(g[c]),m=n.getSpacingUnits(g[c]),b=g[c].spacingduration);l+=m,h=Math.min(h,m),r&&console.log("currentduration: ",p,l,h);var y=void 0;for(c=0;c<g.length;c++){var x=g[c];0===x.voicenumber&&(y=c);var k=void 0!==y&&g[y].voicenumber!==x.voicenumber?g[y]:void 0;f=k,(d=x)&&d.staff&&d.staff.voices&&0!==d.staff.voices.length&&f&&f.staff&&f.staff.voices&&0!==f.staff.voices.length&&d.staff.voices[0]===f.staff.voices[0]||(k=void 0);var w=n.layoutOneItem(u,e,x,t,k),C=w-u;if(C>0){u=w;for(var T=0;T<c;T++)n.shiftRight(C,g[T])}}for(c=0;c<v.length;c++)v[c].spacingduration-=b,n.updateNextX(u,e,v[c]);for(c=0;c<g.length;c++){var S=g[c];n.updateIndices(S)}}for(c=0;c<s.voices.length;c++)n.getNextX(s.voices[c])>u&&(u=n.getNextX(s.voices[c]),m=n.getSpacingUnits(s.voices[c]));return function(e){for(var t=0,r=0;r<e.length;r++){var n=e[r];if(n.children.length>0){var a=n.children.length-1,i=n.children[a];if("bar"===i.abcelem.el_type){var s=i.children[0].x;s>t?t=s:i.children[0].x=t}}}}(s.voices),l+=m,s.setWidth(u),{spacingUnits:l,minSpace:h}}},1277:function(e){e.exports=function(e){for(var t=[],r=0;r<e.length;r++){var n=e[r].staffGroup,a=[];if(n&&n&&n.staffs)for(var i=0;i<n.staffs.length;i++){for(var s=n.staffs[i],o={},c=0;c<s.voices.length;c++)for(var l=n.voices[s.voices[c]],h=0,u=0;u<l.children.length;u++){var d="T"+Math.round(1e3*h);o[d]||(o[d]=[]),"note"===l.children[u].abcelem.el_type&&(o[d].push(l.children[u]),h+=l.children[u].duration)}a.push(o)}t.push(a)}return t}},3294:function(e,t,r){var n=r(3721);function a(e){return e.stemsUp}e.exports=function(e){if(e.anchor1&&e.anchor2){e.hasBeam=!!e.anchor1.parent.beam&&e.anchor1.parent.beam===e.anchor2.parent.beam;var t=e.anchor1.parent.beam;if(!e.hasBeam||t.elems[0]===e.anchor1.parent&&t.elems[t.elems.length-1]===e.anchor2.parent||(e.hasBeam=!1),e.hasBeam){var r=a(t)?e.anchor1.x+e.anchor1.w:e.anchor1.x;e.yTextPos=function(e,t,r){if(0===r.beams.length)return 0;r=r.beams[0];var a=e+(t-e)/2;return n(r.startX,r.startY,r.endX,r.endY,a)}(r,e.anchor2.x,t),e.yTextPos+=a(t)?3:-2,e.xTextPos=(l=r)+(e.anchor2.x-l)/2,e.top=e.yTextPos+1,e.bottom=e.yTextPos-2,a(t)&&(e.endingHeightAbove=4)}else{var i=function(e){var t=0,r=0;if(e.anchor1&&("up"===e.anchor1.stemDir&&t++,"down"===e.anchor1.stemDir&&r++),e.anchor2&&("up"===e.anchor2.stemDir&&t++,"down"===e.anchor2.stemDir&&r++),e.middleElems)for(var n=0;n<e.middleElems.length;n++){var a=e.middleElems[n];"up"===a.stemDir&&t++,"down"===a.stemDir&&r++}return t>=r}(e);if(e.up=i,e.startNote=i?Math.max(e.anchor1.parent.top,9)+4:Math.min(e.anchor1.parent.bottom,0)-2,e.endNote=i?Math.max(e.anchor2.parent.top,9)+4:Math.min(e.anchor2.parent.bottom,0)-2,"rest"===e.anchor1.parent.type&&"rest"!==e.anchor2.parent.type?e.startNote=e.endNote:"rest"===e.anchor2.parent.type&&"rest"!==e.anchor1.parent.type&&(e.endNote=e.startNote),i){for(var s=0,o=0;o<e.middleElems.length;o++)s=Math.max(s,e.middleElems[o].top);((s+=4)>e.startNote||s>e.endNote)&&(e.startNote=s+3,e.endNote=s+3)}else{var c=0;for(o=0;o<e.middleElems.length;o++)c=Math.min(c,e.middleElems[o].bottom-e.middleElems[o].height);(c-=3)<e.startNote&&c<e.endNote&&(e.startNote=Math.min(c,e.startNote)-2,e.endNote=Math.min(c,e.endNote)-2)}e.flatBeams&&(i?(e.startNote=Math.max(e.startNote,e.endNote),e.endNote=Math.max(e.startNote,e.endNote)):(e.startNote=Math.min(e.startNote,e.endNote),e.endNote=Math.min(e.startNote,e.endNote))),e.yTextPos=e.startNote+(e.endNote-e.startNote)/2,e.xTextPos=e.anchor1.x+(e.anchor2.x+e.anchor2.w-e.anchor1.x)/2,e.top=e.yTextPos+1,e.bottom=e.yTextPos-2}}var l;delete e.middleElems,delete e.flatBeams}},937:function(e){var t=function(){};t.beginLayout=function(e,t){t.i=0,t.durationindex=0,t.startx=e,t.minx=e,t.nextx=e,t.spacingduration=0},t.layoutEnded=function(e){return e.i>=e.children.length},t.getNextX=function(e){return Math.max(e.minx,e.nextx)},t.getSpacingUnits=function(e){return Math.sqrt(8*e.spacingduration)},t.layoutOneItem=function(e,t,r,n,a){var i=r.children[r.i];if(!i)return 0;var s=e-r.minx,o=r.durationindex+i.duration>0?n:0;if("note"===i.abcelem.el_type&&!i.abcelem.rest&&0!==r.voicenumber&&a){var c=a.children[a.i],l=c&&(i.abcelem.maxpitch<=c.abcelem.maxpitch+1&&i.abcelem.maxpitch>=c.abcelem.minpitch-1||i.abcelem.minpitch<=c.abcelem.maxpitch+1&&i.abcelem.minpitch>=c.abcelem.minpitch-1);if(l&&i.abcelem.minpitch===c.abcelem.minpitch&&i.abcelem.maxpitch===c.abcelem.maxpitch&&c.heads&&c.heads.length>0&&i.heads&&i.heads.length>0&&c.heads[0].c===i.heads[0].c&&(l=!1),l){var h=c.heads&&c.heads.length>0?c.heads[0].realWidth:c.fixed.w;i.adjustedWidth||(i.adjustedWidth=h+i.w),i.w=i.adjustedWidth;for(var u=0;u<i.children.length;u++){var d=i.children[u];d.name.indexOf("accidental")<0&&(d.adjustedWidth||(d.adjustedWidth=d.dx+h),d.dx=d.adjustedWidth)}}}var f=function(e,t){var r=0;return"note"!==e.type&&"bar"!==e.type||(r=t),-e.extraw+r}(i,o);return s<f&&(0===r.i||"bar"!==i.type||"part"!==r.children[r.i-1].type&&"tempo"!==r.children[r.i-1].type)&&(e+=f-s),i.setX(e),r.spacingduration=i.duration,r.minx=e+function(e){return e.w}(i),r.i!==r.children.length-1&&(r.minx+=i.minspacing),this.updateNextX(e,t,r),e},t.shiftRight=function(e,t){var r=t.children[t.i];r&&(r.setX(r.x+e),t.minx+=e,t.nextx+=e)},t.updateNextX=function(e,t,r){r.nextx=e+t*this.getSpacingUnits(r)},t.updateIndices=function(e){this.layoutEnded(e)||(e.durationindex+=e.children[e.i].duration,"bar"===e.children[e.i].type&&(e.durationindex=Math.round(64*e.durationindex)/64),e.i++)},e.exports=t},6759:function(e,t,r){var n=r(6251),a=r(3721),i=r(3294);function s(e){for(var t=0;t<e.elems.length;t++){var r=e.elems[t];if(r.top)for(var n=l(r,e),a=0;a<r.children.length;a++){var i=r.children[a];if("ornament"===i.klass&&"below"!==i.position&&i.bottom-1.5<n){var s=n-i.bottom+1.5;i.bottom+=s,i.top+=s,i.pitch+=s,n=r.top=i.top}}}}function o(e,t){var r=t.getChordDim();if(r){for(var n=0;n<e.length;n++)if(e[n]<r.left)return n>0&&t.putChordInLane(n),void(e[n]=r.right);e.push(r.right),t.putChordInLane(e.length-1)}}function c(e){for(var t=0,r=0;r<e.children.length;r++)e.children[r].chordHeightBelow&&t++;return t}function l(e,t){return t=t.beams[0],a(t.startX,t.startY,t.endX,t.endY,e.x)}e.exports=function(e){for(var t=0;t<e.beams.length;t++)if("BeamElem"===e.beams[t].type){n(e.beams[t]),s(e.beams[t]);for(var r=0;r<e.beams[t].elems.length;r++)e.adjustRange(e.beams[t].elems[r])}for(e.staff.specialY.chordLines=function(e){var t,r,n,a=[0],i=[0];for(t=0;t<e.length;t++){for(r=0;r<e[t].children.length;r++)(n=e[t].children[r]).chordHeightAbove&&o(a,n);for(r=e[t].children.length-1;r>=0;r--)(n=e[t].children[r]).chordHeightBelow&&o(i,n)}return(a.length>1||i.length>1)&&function(e,t){for(var r=0;r<e.length;r++){c(e[r]);for(var n=0;n<e[r].children.length;n++){var a=e[r].children[n];a.chordHeightAbove&&a.invertLane(t)}}}(e,a.length),{above:a.length,below:i.length}}(e.children),t=0;t<e.otherchildren.length;t++){var a=e.otherchildren[t];"TripletElem"===a.type&&(i(a),e.adjustRange(a))}e.staff.top=Math.max(e.staff.top,e.top),e.staff.bottom=Math.min(e.staff.bottom,e.bottom)}},8510:function(e,t,r){var n=r(4331),a=r(4101),i=function(e){this.paper=new a(e),this.controller=null,this.space=3*n.SPACE,this.padding={},this.reset(),this.firefox=navigator.userAgent.indexOf("Firefox/")>=0};i.prototype.reset=function(){this.paper.clear(),this.y=0,this.abctune=null,this.path=null,this.isPrint=!1,this.lineThickness=0,this.initVerticalSpace()},i.prototype.newTune=function(e){this.abctune=e,this.setVerticalSpace(e.formatting),this.isPrint="print"===e.media,this.setPadding(e)},i.prototype.setLineThickness=function(e){this.lineThickness=e},i.prototype.setPaddingOverride=function(e){this.paddingOverride={top:e.paddingtop,bottom:e.paddingbottom,right:e.paddingright,left:e.paddingleft}},i.prototype.setPadding=function(e){function t(t,r,n,a,i){void 0!==e.formatting[n]?t.padding[r]=e.formatting[n]:void 0!==t.paddingOverride[r]?t.padding[r]=t.paddingOverride[r]:t.isPrint?t.padding[r]=a:t.padding[r]=i}t(this,"top","topmargin",38,15),t(this,"bottom","botmargin",38,15),t(this,"left","leftmargin",68,15),t(this,"right","rightmargin",68,15)},i.prototype.adjustNonScaledItems=function(e){this.padding.top/=e,this.padding.bottom/=e,this.padding.left/=e,this.padding.right/=e,this.abctune.formatting.headerfont.size/=e,this.abctune.formatting.footerfont.size/=e},i.prototype.initVerticalSpace=function(){this.spacing={composer:7.56,graceBefore:8.67,graceInside:10.67,graceAfter:16,info:0,lineSkipFactor:1.1,music:7.56,paragraphSkipFactor:.4,parts:11.33,slurHeight:1,staffSeparation:61.33,staffTopMargin:0,stemHeight:36.67,subtitle:3.78,systemStaffSeparation:48,text:18.9,title:7.56,top:30.24,vocal:0,words:0}},i.prototype.setVerticalSpace=function(e){void 0!==e.staffsep&&(this.spacing.staffSeparation=4*e.staffsep/3),void 0!==e.composerspace&&(this.spacing.composer=4*e.composerspace/3),void 0!==e.partsspace&&(this.spacing.parts=4*e.partsspace/3),void 0!==e.textspace&&(this.spacing.text=4*e.textspace/3),void 0!==e.musicspace&&(this.spacing.music=4*e.musicspace/3),void 0!==e.titlespace&&(this.spacing.title=4*e.titlespace/3),void 0!==e.sysstaffsep&&(this.spacing.systemStaffSeparation=4*e.sysstaffsep/3),void 0!==e.stafftopmargin&&(this.spacing.staffTopMargin=4*e.stafftopmargin/3),void 0!==e.subtitlespace&&(this.spacing.subtitle=4*e.subtitlespace/3),void 0!==e.topspace&&(this.spacing.top=4*e.topspace/3),void 0!==e.vocalspace&&(this.spacing.vocal=4*e.vocalspace/3),void 0!==e.wordsspace&&(this.spacing.words=4*e.wordsspace/3)},i.prototype.calcY=function(e){return this.y-e*n.STEP},i.prototype.yToPitch=function(e){return e/n.STEP},i.prototype.moveY=function(e,t){void 0===t&&(t=1),this.y+=e*t},i.prototype.absolutemoveY=function(e){this.y=e},e.exports=i},4101:function(e){var t="http://www.w3.org/2000/svg";function r(e){this.svg=s(),this.currentGroup=[],e.appendChild(this.svg)}function n(e,t,r){var n=r-e;return"M "+e+" "+t+" l "+n+" 0 l 0 1 l "+-n+" 0 z "}function a(e,t,r){var n=r-t;return"M "+e+" "+t+" l 0 "+n+" l 1 0 l 0 "+-n+" z "}r.prototype.clear=function(){if(this.svg){var e=this.svg.parentNode;this.svg=s(),this.currentGroup=[],e&&(e.innerHTML="",e.appendChild(this.svg))}},r.prototype.setTitle=function(e){var t=document.createElement("title"),r=document.createTextNode(e);t.appendChild(r),this.svg.insertBefore(t,this.svg.firstChild)},r.prototype.setResponsiveWidth=function(e,t){if(this.svg.setAttribute("viewBox","0 0 "+e+" "+t),this.svg.setAttribute("preserveAspectRatio","xMinYMin meet"),this.svg.removeAttribute("height"),this.svg.removeAttribute("width"),this.svg.style.display="inline-block",this.svg.style.position="absolute",this.svg.style.top="0",this.svg.style.left="0",this.svg.parentNode){var r=this.svg.parentNode.getAttribute("class");r?r.indexOf("abcjs-container")<0&&this.svg.parentNode.setAttribute("class",r+" abcjs-container"):this.svg.parentNode.setAttribute("class","abcjs-container"),this.svg.parentNode.style.display="inline-block",this.svg.parentNode.style.position="relative",this.svg.parentNode.style.width="100%";var n=t/e*100;this.svg.parentNode.style["padding-bottom"]=n+"%",this.svg.parentNode.style["vertical-align"]="middle",this.svg.parentNode.style.overflow="hidden"}},r.prototype.setSize=function(e,t){this.svg.setAttribute("width",e),this.svg.setAttribute("height",t)},r.prototype.setAttribute=function(e,t){this.svg.setAttribute(e,t)},r.prototype.setScale=function(e){1!==e?(this.svg.style.transform="scale("+e+","+e+")",this.svg.style["-ms-transform"]="scale("+e+","+e+")",this.svg.style["-webkit-transform"]="scale("+e+","+e+")",this.svg.style["transform-origin"]="0 0",this.svg.style["-ms-transform-origin-x"]="0",this.svg.style["-ms-transform-origin-y"]="0",this.svg.style["-webkit-transform-origin-x"]="0",this.svg.style["-webkit-transform-origin-y"]="0"):(this.svg.style.transform="",this.svg.style["-ms-transform"]="",this.svg.style["-webkit-transform"]="")},r.prototype.insertStyles=function(e){var r=document.createElementNS(t,"style");r.textContent=e,this.svg.insertBefore(r,this.svg.firstChild)},r.prototype.setParentStyles=function(e){for(var t in e)e.hasOwnProperty(t)&&this.svg.parentNode&&(this.svg.parentNode.style[t]=e[t]);this.dummySvg&&(document.querySelector("body").removeChild(this.dummySvg),this.dummySvg=null)},r.prototype.rect=function(e){var t=[],r=e.x,i=e.y,s=e.x+e.width,o=e.y+e.height;return t.push(n(r,i,s)),t.push(n(r,o,s)),t.push(a(s,i,o)),t.push(a(r,o,i)),this.path({path:t.join(" "),stroke:"none","data-name":e["data-name"]})},r.prototype.dottedLine=function(e){var r=document.createElementNS(t,"line");r.setAttribute("x1",e.x1),r.setAttribute("x2",e.x2),r.setAttribute("y1",e.y1),r.setAttribute("y2",e.y2),r.setAttribute("stroke",e.stroke),r.setAttribute("stroke-dasharray","5,5"),this.svg.insertBefore(r,this.svg.firstChild)},r.prototype.rectBeneath=function(e){var r=document.createElementNS(t,"rect");r.setAttribute("x",e.x),r.setAttribute("width",e.width),r.setAttribute("y",e.y),r.setAttribute("height",e.height),e.stroke&&r.setAttribute("stroke",e.stroke),e["stroke-opacity"]&&r.setAttribute("stroke-opacity",e["stroke-opacity"]),e.fill&&r.setAttribute("fill",e.fill),e["fill-opacity"]&&r.setAttribute("fill-opacity",e["fill-opacity"]),this.svg.insertBefore(r,this.svg.firstChild)},r.prototype.text=function(e,r,n,a){var i=document.createElementNS(t,"text");for(var s in i.setAttribute("stroke","none"),r)r.hasOwnProperty(s)&&i.setAttribute(s,r[s]);for(var o="free-text"==r["data-name"],c=(""+e).split("\n"),l=0;l<c.length;l++)if(!o||""!=c[l]){var h=document.createElementNS(t,"tspan");if(a)for(var u in a)a.hasOwnProperty(u)&&h.setAttribute(u,a[u]);if(h.setAttribute("x",r.x?r.x:0),0!==l&&h.setAttribute("dy","1.2em"),-1!==c[l].indexOf("")){var d=c[l].split("");if(h.textContent=d[0],d[1]){var f=document.createElementNS(t,"tspan");f.setAttribute("dy","-0.3em"),f.setAttribute("style","font-size:0.7em"),f.textContent=d[1],h.appendChild(f)}if(d[2]){var p=d[1]?"0.4em":"0.1em",m=document.createElementNS(t,"tspan");m.setAttribute("dy",p),m.setAttribute("style","font-size:0.7em"),m.textContent=d[2],h.appendChild(m)}}else o&&""==c[l].trim()?h.innerHTML=" ":h.textContent=c[l];i.appendChild(h)}return n?n.appendChild(i):this.append(i),i},r.prototype.richTextLine=function(e,r,n,a,i,s){var o=document.createElementNS(t,"text");o.setAttribute("stroke","none"),o.setAttribute("class",a),o.setAttribute("x",r),o.setAttribute("y",n),o.setAttribute("text-anchor",i),o.setAttribute("dominant-baseline","middle");for(var c=0;c<e.length;c++){for(var l=e[c],h=document.createElementNS(t,"tspan"),u=Object.keys(l.attrs),d=0;d<u.length;d++){var f=l.attrs[u[d]];""!==f&&h.setAttribute(u[d],f)}h.textContent=l.content,o.appendChild(h)}return s?s.appendChild(o):this.append(o),o},r.prototype.guessWidth=function(e,t){var r,n=this.createDummySvg(),a=this.text(e,t,n);try{r=a.getBBox(),r=isNaN(r.height)||!r.height?{width:t["font-size"]/2,height:t["font-size"]+2}:{width:r.width,height:r.height}}catch(e){r={width:t["font-size"]/2,height:t["font-size"]+2}}return n.removeChild(a),r},r.prototype.createDummySvg=function(){return this.dummySvg||(this.dummySvg=s(),this.dummySvg.setAttribute("style",["display: block !important;","height: 1px;","width: 1px;","position: absolute;"].join("")),document.querySelector("body").appendChild(this.dummySvg)),this.dummySvg};var i={};function s(){var e=document.createElementNS(t,"svg");return e.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns:xlink","http://www.w3.org/1999/xlink"),e.setAttribute("role","img"),e.setAttribute("fill","currentColor"),e.setAttribute("stroke","currentColor"),e}r.prototype.getTextSize=function(e,t,r){if("number"==typeof e&&(e=""+e),!e||e.match(/^\s+$/))return{width:0,height:0};var n;if(e.length<20&&(n=e+JSON.stringify(t),i[n]))return i[n];var a,s=!r;r||(r=this.text(e,t));try{a=r.getBBox(),a=isNaN(a.height)||!a.height?this.guessWidth(e,t):{width:a.width,height:a.height}}catch(r){a=this.guessWidth(e,t)}return s&&(this.currentGroup.length>0?this.currentGroup[0].removeChild(r):this.svg.removeChild(r)),n&&(i[n]=a),a},r.prototype.openGroup=function(e){e=e||{};var r=document.createElementNS(t,"g");return e.klass&&r.setAttribute("class",e.klass),e.fill&&r.setAttribute("fill",e.fill),e.stroke&&r.setAttribute("stroke",e.stroke),e["data-name"]&&r.setAttribute("data-name",e["data-name"]),e.prepend?this.prepend(r):this.append(r),this.currentGroup.unshift(r),r},r.prototype.closeGroup=function(){var e=this.currentGroup.shift();return e&&0===e.children.length?(e.parentElement.removeChild(e),null):e},r.prototype.path=function(e){var r=document.createElementNS(t,"path");for(var n in e)e.hasOwnProperty(n)&&("path"===n?r.setAttributeNS(null,"d",e.path):"klass"===n?r.setAttributeNS(null,"class",e[n]):void 0!==e[n]&&r.setAttributeNS(null,n,e[n]));return this.append(r),r},r.prototype.pathToBack=function(e){var r=document.createElementNS(t,"path");for(var n in e)e.hasOwnProperty(n)&&("path"===n?r.setAttributeNS(null,"d",e.path):"klass"===n?r.setAttributeNS(null,"class",e[n]):r.setAttributeNS(null,n,e[n]));return this.prepend(r),r},r.prototype.lineToBack=function(e){for(var r=document.createElementNS(t,"line"),n=Object.keys(e),a=0;a<n.length;a++)r.setAttribute(n[a],e[n[a]]);return this.prepend(r),r},r.prototype.append=function(e){this.currentGroup.length>0?this.currentGroup[0].appendChild(e):this.svg.appendChild(e)},r.prototype.prepend=function(e){this.currentGroup.length>0?this.currentGroup[0].appendChild(e):this.svg.insertBefore(e,this.svg.firstChild)},r.prototype.setAttributeOnElement=function(e,t){for(var r in t)t.hasOwnProperty(r)&&e.setAttributeNS(null,r,t[r])},r.prototype.moveElementToChild=function(e,t){e.appendChild(t)},e.exports=r},1185:function(e){e.exports="6.7.0"}},t={},function r(n){var a=t[n];if(void 0!==a)return a.exports;var i=t[n]={exports:{}};return e[n](i,i.exports,r),i.exports}(1045);var e,t});\ No newline at end of file