diff --git a/composer-lab/README.md b/composer-lab/README.md index e1cab9b..d5bb3a5 100644 --- a/composer-lab/README.md +++ b/composer-lab/README.md @@ -87,10 +87,12 @@ python -m studio.summary out_studio только нужный слой в этой секции (ритм-гитару, фактуру, вариант середины, вступление, концовку) или весь риф / темп целиком — всё остальное останется нетронутым; удачные слои закрепите кнопкой «Откр./Закр.», после чего можно -нажать «Перегенерировать всё незакреплённое». Снизу настраиваются скорость соло в -середине B, пауза в конце риф-такта и дозы v8 для следующих перегенераций ритма; -кнопка «Отменить» возвращает предыдущее состояние, а «Скачать MIDI» и «Скачать -табы (MusicXML)» сохраняют готовый трек для DAW и Guitar Pro. +нажать «Перегенерировать всё незакреплённое». Снизу настраиваются глухие ноты +ритм-гитары, доля октавных тактов, длина вступления, повтор квадрата в куплетах, +скорость соло в середине B и пауза в конце риф-такта (все применяются сразу, +а дозы перегенерации ритма вынесены в раздел «Дополнительно»); кнопка «Отменить» +возвращает предыдущее состояние, а «Скачать MIDI» и «Скачать табы (MusicXML)» +сохраняют готовый трек для DAW и Guitar Pro. ## Studio Web @@ -122,6 +124,6 @@ nix shell nixpkgs#fluidsynth nixpkgs#sox nixpkgs#ffmpeg -c bash build_samples.sh ### Как пользоваться в браузере (для владельца) -Откройте страницу на компьютере или телефоне: при первом запуске браузер загрузит Pyodide и сэмплы гитары (далее они берутся из кеша браузера). Нажмите «Новая пьеса» (при желании задайте `seed`), запускайте воспроизведение кнопкой «Играть» или кликом по блокам секций на таймлайне. Перегенерируйте отдельные слои, закрепляйте удачные кнопкой «Откр./Закр.», меняйте параметры снизу и скачивайте готовый результат в MIDI, MusicXML или ASCII-табах. Все пьесы и журнал действий сохраняются локально в браузере; в боковой панели доступны «Скачать журнал» (`history.jsonl`), «Экспорт пьес» и «Импорт пьес» для переноса между устройствами. +Откройте страницу на компьютере или телефоне: при первом запуске браузер загрузит Pyodide и сэмплы гитары (далее они берутся из кеша браузера). Нажмите «Новая пьеса» (при желании задайте `seed`), запускайте воспроизведение кнопкой «Играть» или кликом по блокам секций на таймлайне. Перегенерируйте отдельные слои, закрепляйте удачные кнопкой «Откр./Закр.», сразу меняйте глухие ноты ритм-гитары, долю октавных тактов, длину вступления, повтор квадрата в куплетах и прочие параметры снизу (дозы перегенерации скрыты в «Дополнительно») и скачивайте готовый результат в MIDI, MusicXML или ASCII-табах. Все пьесы и журнал действий сохраняются локально в браузере; в боковой панели доступны «Скачать журнал» (`history.jsonl`), «Экспорт пьес» и «Импорт пьес» для переноса между устройствами. diff --git a/composer-lab/STUDIO-CONTROLS-SPEC.md b/composer-lab/STUDIO-CONTROLS-SPEC.md new file mode 100644 index 0000000..2912b3d --- /dev/null +++ b/composer-lab/STUDIO-CONTROLS-SPEC.md @@ -0,0 +1,87 @@ +# Studio controls that do what their labels say (specification) + +Base: `main` (Studio and Studio Web as published). Applies to both front ends: +the server page (`studio/index.html`) and Studio Web (`web/index.html`, +`web/app.js`), which share `studio/engine.py`, `studio/web_api.py` and +`composer.py`. + +## Problem (from the owner) + +- He set "Глухие ноты (dead notes)" to 1 and expected the rhythm guitar to be + muted; nothing changed without a re-roll and little changed with one. + Today the value is the probability that a section whose rhythm guitar plays + octave chords gets a dead stroke before each accent, applied only at the next + re-roll of `comp` in A/A2, only if octave chords were drawn, and never in the + sixteenth-note octave grid. At 1 a piece has 0-8 % dead notes. +- "Доля октавных секций" has the same indirect behaviour. +- The intro is often 1.5 s (one bar of 7/8 at a fast tempo); its length changes + only when the intro layer is re-rolled. Verses are one 4-bar square. + +## Required behaviour + +All four controls act immediately on the current piece (recompose and render +on change, no re-roll needed), are stored in `studio.options`, are undoable, +and are logged like other options. Their defaults reproduce today's output +byte for byte (existing recipes and tests unchanged). + +1. **Глухие ноты (доля ударов ритм-гитары)**, option `mute_share`, 0-1, + default 0. After composition, each onset of the accompanying (non-lead) + guitar in sections A, A2, A3 and B is muted with probability `mute_share`, + chosen deterministically from the recipe seed and the onset time (so the + same value gives the same result and undo restores it). A muted onset keeps + its string and fret, gets technique `dead`, duration one sixteenth and + velocity 40; all notes struck together at that onset are muted together. + At 1 every accompaniment onset in those sections is dead; the lead is never + touched. The existing octave dead strokes stay as they are. +2. **Октавные аккорды (доля тактов)**, option `octave_share`, 0-1 or unset. + Unset (default) keeps today's behaviour. When set, each comping bar of A and + A2 plays octave chords if a deterministic draw from the seed and the bar + index is below the value, otherwise its current role. 1 = every comping bar + of A and A2 in octave chords. +3. **Длина вступления (тактов)**, option `intro_bars`: "auto" (default, today's + behaviour including the intro layer) or 1, 2, 4, 8. Extra bars cycle the A + chords as the existing intro does. +4. **Повтор квадрата в куплетах**, option `square_repeat`: 1 (default) or 2. + With 2, sections A and A2 are played twice in a row (the same four bars + again), so a verse lasts eight bars. + +Keep the old dose options working for existing saved pieces but hide them in +the UI behind "Дополнительно" with labels that state what they really do: +"Вероятность октав при перегенерации ритма", "Октавы шестнадцатыми (при +перегенерации)", "Глухие перед акцентами в октавах (при перегенерации)". + +Each new control shows a one-line hint under it in Russian saying what it does +and that it applies at once. + +## Constraints + +- Python standard library; existing tests stay green; `test_composer.py` not + edited; all existing version flags stay byte-identical (the version-hash + script in the reviewer's notes). +- Section isolation rules of STUDIO-SPEC stay true: the four options are + whole-piece settings, not layers; locks are unaffected by them. +- English code and comments, Russian UI text, minimal comments. Work only in + `composer-lab/`. Do not commit or push. + +## Tests (write first) + +- Defaults: a piece with none of the new options set composes byte-identical + MIDI to before for seeds 801, 802, 805, 807, 809, 810 and 20 random seeds. +- `mute_share=1`: every accompaniment onset in A, A2, A3, B is dead and the lead + is unchanged; `mute_share=0.3`: share of muted onsets within 0.2-0.4 over 20 + pieces; same value twice gives identical MIDI; undo restores the previous MIDI. +- `octave_share=1`: every comping bar of A and A2 is an octave-chord bar; + `octave_share=0`: none. +- `intro_bars=8`: the intro has 8 bars; `auto` equals today. +- `square_repeat=2`: A and A2 each have twice as many bars and the second half + repeats the first note for note; total length grows accordingly. +- Studio Web: the same option sequence gives the same MIDI through `web_api` + as through the engine; the Node harness covers that the controls send the + option and the page refreshes without a re-roll. +- All `ComposerInvariants` hold for 20 seeds with random combinations of the + four options. + +## Deliverables + +Code, tests, updated README sections, and a short report: what was built, test +commands and results, anything not done. diff --git a/composer-lab/composer.py b/composer-lab/composer.py index 41fa7d9..0a0c845 100644 --- a/composer-lab/composer.py +++ b/composer-lab/composer.py @@ -7,6 +7,7 @@ import argparse import copy import functools +import hashlib import itertools import json import math @@ -503,9 +504,12 @@ def octave_bar(th, root, bar_start, L, accents, grid, dead, state, slide_max=Non nxt = ons[k + 1] if k + 1 < len(ons) else L tech = ["slide"] if slide and k == 0 else [] for s, f in ((1, x), (3, x + 2)): - notes.append({"start": bar_start + o, "dur": max(1, nxt - o), "pitch": fretboard.OPEN[s] + f, - "fixed": (s, f), "preset_tech": tech, "dyad": True, "ring": False, - "vel": 86 if o in accents else 72}) + note = {"start": bar_start + o, "dur": max(1, nxt - o), "pitch": fretboard.OPEN[s] + f, + "fixed": (s, f), "preset_tech": tech, "dyad": True, "ring": False, + "vel": 86 if o in accents else 72} + if tech: + note["_slide_max"] = smax + notes.append(note) if dead: for a in sorted(accents): if a > 0 and a - 1 not in ons: @@ -810,6 +814,276 @@ def _studio_rng(seed, layer, section, salt): return random.Random(f"{seed}:{layer}:{section}:{salt}") +def _det_unit(key): + h = hashlib.sha256(key.encode("utf-8")).digest() + return (int.from_bytes(h[:7], "big") >> 3) / (1 << 53) + + +def _oct_art_key(spec, has_dead_slot=True): + grid = spec["grid"] + dead = False if (grid == 16 or not has_dead_slot) else bool(spec["dead"]) + return (grid, dead) + + +def _oct_alternatives(grid_p, dead_p, smax, base_key, has_dead_slot=True): + cands = [] + if grid_p > 0.0: + cands.append({"grid": 16, "dead": False, "slide_max": smax}) + if grid_p < 1.0 and (not has_dead_slot or dead_p < 1.0): + cands.append({"grid": 8, "dead": False, "slide_max": smax}) + if has_dead_slot and grid_p < 1.0 and dead_p > 0.0: + cands.append({"grid": 8, "dead": True, "slide_max": smax}) + return [c for c in cands if _oct_art_key(c, has_dead_slot) != base_key] + + +def _studio_octave_spec(seed, sec, comp_doses_map, opts=None, comp_salt=0, base_oct=None, has_dead_slot=True): + if sec in comp_doses_map: + doses = comp_doses_map[sec] + elif comp_salt > 0 and opts: + doses = opts + else: + doses = V8 + grid_p = float(doses.get("octave_sixteenths", V8["octave_sixteenths"])) + dead_p = float(doses.get("dead_notes", V8["dead_notes"])) + smax = int(doses.get("slide_max", V8["slide_max"])) + + def draw(rng, gp=grid_p, dp=dead_p, sm=smax): + return { + "grid": 16 if rng.random() < gp else 8, + "dead": rng.random() < dp, + "slide_max": sm, + } + + base_spec = ( + dict(base_oct) + if base_oct is not None + else draw( + random.Random(f"{seed}:octave_spec:{sec}"), + float(V8["octave_sixteenths"]), + float(V8["dead_notes"]), + int(V8["slide_max"]), + ) + ) + if comp_salt <= 0: + return base_spec + base_key = _oct_art_key(base_spec, has_dead_slot) + rng = random.Random(f"{seed}:octave_spec:{sec}:{comp_salt}") + spec = draw(rng) + if comp_salt == 1: + for _ in range(8): + if _oct_art_key(spec, has_dead_slot) != base_key: + break + spec = draw(rng) + if _oct_art_key(spec, has_dead_slot) == base_key: + alts = _oct_alternatives(grid_p, dead_p, smax, base_key, has_dead_slot) + if alts: + spec = rng.choice(alts) + return spec + + +def _is_line_note(n): + return ( + not n.get("chordtone") + and not n.get("dyad") + and not (n.get("fixed") and "preset_tech" not in n) + ) + + +def _pred_sig(p): + return None if p is None else (p["string"], p["fret"], "dead" in p.get("tech", [])) + + +def _strip_leading_legato(notes, s0, s1): + ordered = sorted(notes, key=lambda n: (n["start"], n["string"], n["pitch"])) + prev_str_before = {} + last_str_in = {} + prev_line_before = None + last_line_in = None + in_sec = [] + for n in ordered: + if n["start"] < s0: + prev_str_before[n["string"]] = n + if _is_line_note(n): + prev_line_before = n + elif n["start"] < s1: + in_sec.append(n) + last_str_in[n["string"]] = n + if _is_line_note(n): + last_line_in = n + seen_str = set() + seen_line = False + for n in in_sec: + tech = n.get("tech", []) + leg = {"hammer", "pull", "slide"} & set(tech) + if leg and n["string"] not in seen_str: + pb = prev_str_before.get(n["string"]) + pr = last_str_in.get(n["string"]) + valid = ( + pr is not None + and _pred_sig(pb) == _pred_sig(pr) + and "dead" not in pr.get("tech", []) + and pr["fret"] != n["fret"] + and ("hammer" not in leg or n["fret"] > pr["fret"]) + and ("pull" not in leg or n["fret"] < pr["fret"]) + and (not n.get("dyad") or "slide" not in leg or abs(n["fret"] - pr["fret"]) <= n.get("_slide_max", V8["slide_max"])) + ) + if not valid: + n["tech"] = [x for x in tech if x not in ("hammer", "pull", "slide")] + if _is_line_note(n) and not seen_line: + tech = n.get("tech", []) + leg = {"hammer", "pull", "slide"} & set(tech) + if leg: + valid_line = ( + last_line_in is not None + and _pred_sig(prev_line_before) == _pred_sig(last_line_in) + and "dead" not in last_line_in.get("tech", []) + and last_line_in["string"] == n["string"] + and last_line_in["fret"] != n["fret"] + and ("hammer" not in leg or n["fret"] > last_line_in["fret"]) + and ("pull" not in leg or n["fret"] < last_line_in["fret"]) + ) + if not valid_line: + n["tech"] = [x for x in tech if x not in ("hammer", "pull", "slide")] + seen_str.add(n["string"]) + if _is_line_note(n): + seen_line = True + + +def _validate_octave_slides(parts): + for g in ("g1", "g2"): + by_string = {} + for n in sorted(parts[g], key=lambda x: (x["start"], x["string"], x["pitch"])): + if n.get("dyad") and "slide" in n.get("tech", []): + p = by_string.get(n["string"]) + smax = n.get("_slide_max", V8["slide_max"]) + if ( + p is None + or p["fret"] == n["fret"] + or "dead" in p.get("tech", []) + or abs(n["fret"] - p["fret"]) > smax + ): + n["tech"] = [x for x in n["tech"] if x != "slide"] + by_string[n["string"]] = n + + +def _section_runs(chords, total16): + runs = [] + seen = {} + i = 0 + while i < len(chords): + sec = chords[i]["sec"] + j = i + 1 + while j < len(chords) and chords[j]["sec"] == sec: + j += 1 + occ = seen.get(sec, 0) + seen[sec] = occ + 1 + s0 = chords[i]["start"] + s1 = chords[j]["start"] if j < len(chords) else total16 + runs.append((sec, occ, s0, s1)) + i = j + return runs + + +def _strip_legato_from_dead(notes): + by_string = {} + prev_line = None + for n in sorted(notes, key=lambda x: (x["start"], x["string"], x["pitch"])): + is_line = _is_line_note(n) + p_str = by_string.get(n["string"]) + bad_str = p_str is not None and "dead" in p_str.get("tech", []) + bad_line = is_line and prev_line is not None and "dead" in prev_line.get("tech", []) + if bad_str or bad_line: + n["tech"] = [x for x in n.get("tech", []) if x not in ("hammer", "pull", "slide")] + by_string[n["string"]] = n + if is_line: + prev_line = n + + +def _apply_square_repeat(parts, chords, meters, total16, repeat, form=None): + if repeat <= 1: + return total16 + runs = [] + i = 0 + while i < len(chords): + sec = chords[i]["sec"] + if sec in ("A", "A2"): + j = i + 1 + while j < len(chords) and chords[j]["sec"] == sec: + j += 1 + runs.append((i, j - 1)) + i = j + else: + i += 1 + for first_i, last_i in reversed(runs): + s0 = chords[first_i]["start"] + s1 = chords[last_i + 1]["start"] if last_i + 1 < len(chords) else total16 + sec_len = s1 - s0 + extra_len = sec_len * (repeat - 1) + for g in ("g1", "g2"): + _strip_leading_legato(parts[g], s0, s1) + sec_notes = [] + for n in parts[g]: + if s0 <= n["start"] < s1: + n["dur"] = min(n["dur"], max(1, s1 - n["start"])) + sec_notes.append(n) + elif n["start"] >= s1: + n["start"] += extra_len + for r in range(1, repeat): + shift = sec_len * r + parts[g].extend(dict(copy.deepcopy(n), start=n["start"] + shift) for n in sec_notes) + parts[g].sort(key=lambda n: (n["start"], n["pitch"])) + for c in chords[last_i + 1:]: + c["start"] += extra_len + block = [dict(c) for c in chords[first_i:last_i + 1]] + inserted_chords = [] + for r in range(1, repeat): + shift = sec_len * r + inserted_chords.extend(dict(c, start=c["start"] + shift) for c in block) + chords[last_i + 1:last_i + 1] = inserted_chords + if form is not None: + fblock = [copy.deepcopy(b) for b in form[first_i:last_i + 1]] + inserted_form = [] + for r in range(1, repeat): + inserted_form.extend(copy.deepcopy(b) for b in fblock) + form[last_i + 1:last_i + 1] = inserted_form + for k, (tick, num, den) in enumerate(meters): + if tick >= s1 * 120: + meters[k] = (tick + extra_len * 120, num, den) + total16 += extra_len + for i, c in enumerate(chords): + c["bar"] = i + return total16 + + +def _apply_mute_share(parts, other, chords, total16, seed, mute_share): + if mute_share <= 0.0: + return + runs = [r for r in _section_runs(chords, total16) if r[0] in ("A", "A2", "A3", "B")] + if not runs: + return + by_key = {} + for n in parts[other]: + st = n["start"] + for sec, occ, s0, s1 in runs: + if s0 <= st < s1: + by_key.setdefault((sec, occ, st - s0, st), []).append(n) + break + for (sec, occ, rel, _onset), group in sorted(by_key.items()): + if all("dead" in n.get("tech", []) for n in group): + continue + key = f"{seed}:mute:{sec}:{rel}" if occ == 0 else f"{seed}:mute:{sec}:{occ}:{rel}" + if _det_unit(key) < mute_share: + for n in group: + if "dead" in n.get("tech", []): + continue + n["tech"] = ["dead"] + n["dur"] = 1 + n["vel"] = 40 + n["ring"] = False + n["_muted"] = True + _strip_legato_from_dead(parts[other]) + + def _studio_cycle(rng, v8): cycle = rng.choice([3, 4, 5, 5, 6, 7]) ladder_pick = list(range(cycle)) @@ -881,18 +1155,21 @@ def _studio_lead_rhythm(seed, intent, salt, tail_rest): return m["hook"], lp -def _studio_intro(seed, base_bars, base_dens, salt): +def _studio_intro(seed, base_bars, base_dens, salt, fixed_bars=False, base_tex="arp"): rng = _studio_rng(seed, "intro", "intro", salt) for _ in range(8): n_bars = rng.choice([1, 2, 4]) dens = rng.choice([1, 2, 3]) tex = rng.choice(["arp", "tap"]) if dens == 3 else "arp" - if salt != 1 or n_bars != base_bars or dens != base_dens: + if fixed_bars: + if salt != 1 or (dens, tex) != (base_dens, base_tex): + return n_bars, dens, tex + elif salt != 1 or n_bars != base_bars or dens != base_dens: return n_bars, dens, tex return n_bars, dens, tex -def _studio_comp(seed, sec, salt, grouping, L, doses, base_sec_bars): +def _studio_comp(seed, sec, salt, grouping, L, doses, base_sec_bars, base_oct=None, has_dead_slot=True): rng = _studio_rng(seed, "comp", sec, salt) pool = [ ["chords", "chords", "chatter"], @@ -901,8 +1178,8 @@ def _studio_comp(seed, sec, salt, grouping, L, doses, base_sec_bars): ["chords", "chords", "chords"], ["chatter", "chatter", "chords"], ] - base_roles = [b.get("role") for b in base_sec_bars if b.get("role")] - base_oct = base_sec_bars[0].get("oct") if base_roles and base_roles[0] == "octave" else None + if base_oct is None: + base_oct = next((b.get("oct") for b in base_sec_bars if b.get("oct")), None) base_acc_pat = [(a, "hit") for a in sorted(accents_of(grouping))] def draw(): @@ -922,14 +1199,24 @@ def draw(): if salt != 1: break if plan["kind"] == "octave": - same = base_oct is not None and ( - plan["oct"]["grid"] == base_oct.get("grid") and plan["oct"]["dead"] == base_oct.get("dead") - ) + same = base_oct is not None and _oct_art_key(plan["oct"], has_dead_slot) == _oct_art_key(base_oct, has_dead_slot) else: same = plan["comp"] == base_acc_pat if not same: break plan = draw() + if salt == 1 and plan["kind"] == "octave" and base_oct is not None: + base_key = _oct_art_key(base_oct, has_dead_slot) + if _oct_art_key(plan["oct"], has_dead_slot) == base_key: + alts = _oct_alternatives( + doses["octave_sixteenths"], + doses["dead_notes"], + int(doses["slide_max"]), + base_key, + has_dead_slot, + ) + if alts: + plan = {"kind": "octave", "oct": rng.choice(alts)} return plan @@ -1044,12 +1331,17 @@ def _prepare_studio(recipe, arp, v8): form = [dict(b, _orig_bar_i=idx) for idx, b in enumerate(recipe["form"])] + intro_bars_opt = opts.get("intro_bars", "auto") intro_salt = int(salts.get("intro@intro", 0)) if intro_salt > 0: orig_intro = [b for b in form if b["sec"] == "intro"] base_bars = len(orig_intro) base_dens = orig_intro[0].get("dens", 3) if orig_intro else 3 - n_bars, dens, intro_tex = _studio_intro(seed, base_bars, base_dens, intro_salt) + base_tex = "tap" if (base_dens == 3 and arp.get("texture") == "tap") else "arp" + n_bars, dens, intro_tex = _studio_intro( + seed, base_bars, base_dens, intro_salt, + fixed_bars=(intro_bars_opt != "auto"), base_tex=base_tex, + ) non_intro = [b for b in form if b["sec"] != "intro"] harmony_a = recipe["harmony"]["A"] new_intro = [ @@ -1065,7 +1357,52 @@ def _prepare_studio(recipe, arp, v8): ] form = new_intro + non_intro + if intro_bars_opt != "auto": + n_bars = int(intro_bars_opt) + orig_intro = [b for b in form if b["sec"] == "intro"] + non_intro = [b for b in form if b["sec"] != "intro"] + harmony_a = recipe["harmony"]["A"] + template = {k: v for k, v in orig_intro[0].items() if k != "handover"} if orig_intro else { + "sec": "intro", + "prog": "intro", + "dens": 2, + } + last_handover = orig_intro[-1].get("handover") if orig_intro else None + new_intro = [] + for i in range(n_bars): + bar = dict(template, sec="intro", chord=harmony_a[i % len(harmony_a)], prog="intro", _orig_bar_i=i) + if last_handover and i == n_bars - 1: + bar["handover"] = last_handover + new_intro.append(bar) + form = new_intro + non_intro + L = METERS[it["meter"]][0] + raw_oct_share = opts.get("octave_share", None) + octave_share = None if raw_oct_share is None else max(0.0, min(1.0, float(raw_oct_share))) + skel = recipe["motifs"].get("skeleton") + sec_acc = set(skel["A"]) if skel else accents_of(it["grouping"]) + ons8 = eighths(sec_acc, L) + has_dead_slot = any(a > 0 and (a - 1) not in ons8 for a in sec_acc) + + salt0_oct_map = {} + for sec in ("A", "A2"): + orig_comping = [ + b for b in form + if b["sec"] == sec + and not b.get("tex") + and (b.get("role") in ("chords", "chatter", "octave") or b.get("prog") == "cad_open") + ] + orig_oct = next((b.get("oct") for b in orig_comping if b.get("oct")), None) + any_forced_oct = octave_share is not None and any( + _det_unit(f"{seed}:octave:{b['_orig_bar_i']}") < octave_share for b in orig_comping + ) + if orig_oct is not None: + salt0_oct_map[sec] = dict(orig_oct) + elif any_forced_oct: + salt0_oct_map[sec] = _studio_octave_spec(seed, sec, {}, opts=None, comp_salt=0) + else: + salt0_oct_map[sec] = None + for sec in ("A", "A2"): csalt = int(salts.get(f"comp@{sec}", 0)) if csalt > 0: @@ -1077,7 +1414,10 @@ def _prepare_studio(recipe, arp, v8): "dead_notes": float(comp_doses_map.get(sec, {}).get("dead_notes", opts.get("dead_notes", V8["dead_notes"]))), "slide_max": int(comp_doses_map.get(sec, {}).get("slide_max", opts.get("slide_max", V8["slide_max"]))), } - cplan = _studio_comp(seed, sec, csalt, it["grouping"], L, doses, sec_bars) + cplan = _studio_comp( + seed, sec, csalt, it["grouping"], L, doses, sec_bars, + base_oct=salt0_oct_map.get(sec), has_dead_slot=has_dead_slot, + ) ri = 0 for b in form: if b["sec"] == sec and b.get("role") in ("chords", "chatter", "octave"): @@ -1093,6 +1433,41 @@ def _prepare_studio(recipe, arp, v8): b["_fallback_comp"] = list(cplan["comp"]) ri += 1 + if octave_share is not None: + for sec in ("A", "A2"): + comping_bars = [ + b for b in form + if b["sec"] == sec + and not b.get("tex") + and (b.get("role") in ("chords", "chatter", "octave") or b.get("prog") == "cad_open") + ] + if not comping_bars: + continue + if "texture" in recipe and sec in recipe["texture"].get("role", {}): + fallback_roles = [recipe["texture"]["role"][sec]] + elif "repeat" in recipe and recipe["repeat"].get("roles"): + fallback_roles = list(recipe["repeat"]["roles"]) + else: + fallback_roles = ["chords"] + base_oct = next((b.get("oct") for b in comping_bars if b.get("oct")), None) + csalt = int(salts.get(f"comp@{sec}", 0)) + oct_spec = dict(base_oct) if base_oct is not None else _studio_octave_spec( + seed, sec, comp_doses_map, opts=opts, comp_salt=csalt, + base_oct=salt0_oct_map.get(sec), has_dead_slot=has_dead_slot, + ) + for ri, b in enumerate(comping_bars): + if _det_unit(f"{seed}:octave:{b['_orig_bar_i']}") < octave_share: + b["role"] = "octave" + b["oct"] = dict(b.get("oct") or oct_spec) + b.pop("comp", None) + b.pop("_fallback_comp", None) + elif b.get("role") == "octave": + b.pop("oct", None) + if b.get("prog") == "cad_open": + b.pop("role", None) + else: + b["role"] = fallback_roles[ri % len(fallback_roles)] + sec_arp = {} for sec in ("A", "A2"): tsalt = int(salts.get(f"texture@{sec}", 0)) @@ -1135,6 +1510,9 @@ def _prepare_studio(recipe, arp, v8): tempo_salt = int(salts.get("tempo@all", 0)) tempo = _studio_tempo(seed, base_tempo, tempo_salt) if tempo_salt > 0 else base_tempo + mute_share = max(0.0, min(1.0, float(opts.get("mute_share", 0.0)))) + square_repeat = int(opts.get("square_repeat", 1)) + return { "hook": hook, "lead_plan": lead_plan, @@ -1146,6 +1524,8 @@ def _prepare_studio(recipe, arp, v8): "tempo": tempo, "base": base, "end_riff": end_riff, + "mute_share": mute_share, + "square_repeat": square_repeat, } @@ -1345,6 +1725,9 @@ def phrase_anchor(sec, root, lift, tone=None): resp = [dict(e, on=e["on"] + L // 2) for e in resp if e["on"] + L // 2 < L] fn2 = phrase_anchor("call", root, -5, rec_hook["anchor"]) parts[other] += place_line(th, resp, root, fn2, t, acc, *rng_lead[other], 86) + elif bar.get("role") == "octave": + parts[other] += octave_bar(th, root, t, L, acc, bar["oct"]["grid"], bar["oct"]["dead"], oct_state, + slide_max=bar["oct"].get("slide_max")) elif comp is not None and (pr == "cad_open" or bar.get("role") == "chords"): parts[other] += comp_strike(th, root, t, L, other, comp, 84 if pr == "cad_open" else 74, v8) elif pr == "cad_open": @@ -1355,9 +1738,6 @@ def phrase_anchor(sec, root, lift, tone=None): for s, f, p in v or []: parts[other].append({"start": t + a, "dur": 2, "pitch": p, "vel": 92 if a == 0 else 84, "fixed": (s, f)}) - elif bar.get("role") == "octave": - parts[other] += octave_bar(th, root, t, L, acc, bar["oct"]["grid"], bar["oct"]["dead"], oct_state, - slide_max=bar["oct"].get("slide_max")) elif bar.get("role") == "chords" or (bar.get("role") and dense): if bar.get("_fallback_comp") is not None: parts[other] += comp_strike(th, root, t, L, other, bar["_fallback_comp"], 74, v8) @@ -1542,6 +1922,16 @@ def phrase_anchor(sec, root, lift, tone=None): parts = out_parts if fix: report["m9_resolved"] = resolve_minor_ninths(parts, lead, other) + _validate_octave_slides(parts) + if st_cfg["mute_share"] > 0.0: + _apply_mute_share(parts, other, chords, t, recipe["seed"], st_cfg["mute_share"]) + if st_cfg["square_repeat"] > 1: + t = _apply_square_repeat( + parts, chords, meters, t, st_cfg["square_repeat"], + form=form if _trace is not None else None, + ) + if _trace is not None: + _trace["form"] = form else: for g in ("g1", "g2"): ns = sorted(parts[g], key=lambda n: (n["start"], n["pitch"])) diff --git a/composer-lab/musicxml.py b/composer-lab/musicxml.py index 70cbf5f..bf29e29 100644 --- a/composer-lab/musicxml.py +++ b/composer-lab/musicxml.py @@ -85,7 +85,10 @@ def part_xml(piece, g, pid): nxt = onsets[k + 1] if k + 1 < len(onsets) else b1 group = [n for n in inbar if int(n["start"]) == on] longest = max(n["dur"] for n in group) - written = max(1, min(nxt - on, int(round(longest)) if nxt == b1 else nxt - on)) + if all("dead" in n.get("tech", []) for n in group): + written = 1 + else: + written = max(1, min(nxt - on, int(round(longest)) if nxt == b1 else nxt - on)) pieces = split_dur(written) is_pm = any("pm" in n.get("tech", []) for n in group) if is_pm and not pm_on: diff --git a/composer-lab/studio/engine.py b/composer-lab/studio/engine.py index 77b35e2..b942325 100644 --- a/composer-lab/studio/engine.py +++ b/composer-lab/studio/engine.py @@ -40,6 +40,8 @@ VALID_B_LEAD = ("augmented", "same_speed", "rest") VALID_DOSE_FLOATS = ("octave_piece", "octave_sixteenths", "dead_notes") +VALID_INTRO_BARS = ("auto", 1, 2, 4, 8) +VALID_SQUARE_REPEAT = (1, 2) PIECE_ID_RE = re.compile(r"^[A-Za-z0-9_-]+$") @@ -47,6 +49,10 @@ def default_options(): return { "b_lead": "augmented", "trailing_rest": True, + "mute_share": 0.0, + "octave_share": None, + "intro_bars": "auto", + "square_repeat": 1, "octave_piece": float(composer.V8["octave_piece"]), "octave_sixteenths": float(composer.V8["octave_sixteenths"]), "dead_notes": float(composer.V8["dead_notes"]), @@ -193,16 +199,40 @@ def set_option(recipe, name, value): if not isinstance(value, bool): raise ValueError("trailing_rest must be a boolean") opts["trailing_rest"] = value + elif name == "mute_share": + num = _number(value, name) + opts["mute_share"] = max(0.0, min(1.0, float(num))) + elif name == "octave_share": + if value is None: + opts["octave_share"] = None + else: + num = _number(value, name) + opts["octave_share"] = max(0.0, min(1.0, float(num))) + elif name == "intro_bars": + if value == "auto": + opts["intro_bars"] = "auto" + elif isinstance(value, bool) or not isinstance(value, int) or value not in (1, 2, 4, 8): + raise ValueError(f"invalid intro_bars: {value}") + else: + opts["intro_bars"] = value + elif name == "square_repeat": + if isinstance(value, bool) or not isinstance(value, int) or value not in (1, 2): + raise ValueError(f"invalid square_repeat: {value}") + opts["square_repeat"] = value elif name in VALID_DOSE_FLOATS: num = _number(value, name) - _backfill_comp_doses(st) - opts[name] = max(0.0, min(1.0, float(num))) + clamped = max(0.0, min(1.0, float(num))) + if opts[name] != clamped: + _backfill_comp_doses(st) + opts[name] = clamped elif name == "slide_max": num = _number(value, name) if num != int(num): raise ValueError("slide_max must be an integer") - _backfill_comp_doses(st) - opts["slide_max"] = max(0, min(12, int(num))) + clamped = max(0, min(12, int(num))) + if opts[name] != clamped: + _backfill_comp_doses(st) + opts[name] = clamped else: raise ValueError(f"unknown option: {name}") return rec @@ -451,7 +481,11 @@ def _change(self, piece_id, change, log): pdir = self._piece_dir(piece_id) with self._write_lock(piece_id): old_rec = self._read_recipe(pdir) + base_rec = _ensure_studio(old_rec) new_rec = change(old_rec) + if new_rec == base_rec: + piece = composer.compose(old_rec) + return piece_detail(piece_id, old_rec, piece, can_undo=bool(self._read_undo(pdir))) stack = self._read_undo(pdir) + [old_rec] piece, stage, reuse = self._build(pdir, new_rec) self._publish(pdir, stage, reuse, stack) diff --git a/composer-lab/studio/index.html b/composer-lab/studio/index.html index 3c2ea47..f6ff0ec 100644 --- a/composer-lab/studio/index.html +++ b/composer-lab/studio/index.html @@ -186,6 +186,10 @@ font-size: 0.88rem; } .slider-head { display: flex; justify-content: space-between; color: var(--muted); } + .option-hint { font-size: 0.78rem; color: var(--muted); margin-top: 2px; } + .slider-dim { opacity: 0.55; } + .advanced-options { margin-top: 14px; border-top: 1px solid var(--border); padding-top: 10px; } + .advanced-options summary { cursor: pointer; color: var(--muted); font-size: 0.9rem; font-weight: 600; margin-bottom: 10px; } input[type="range"] { width: 100%; } .empty { color: var(--muted); padding: 24px 0; text-align: center; } @media (max-width: 780px) { @@ -293,8 +297,12 @@

Секции

-

Параметры (для следующих перегенераций)

+

Параметры пьесы

+
+ Дополнительно +
+
`; @@ -357,8 +365,146 @@

Параметры (для следующих перегенераций) { valText.textContent = inp.value; }; + inp.onchange = () => mutate(`/api/piece/${encodeURIComponent(d.id)}/option`, { + name, + value: step === 1 ? parseInt(inp.value, 10) : parseFloat(inp.value), + }, d.id); + wrap.appendChild(head); + wrap.appendChild(inp); + if (hint) addHint(wrap, hint); + grid.appendChild(wrap); + } + + addSlider( + oGrid, + "mute_share", + "Глухие ноты (доля ударов ритм-гитары)", + 0, 1, 0.05, + "Глушит долю ударов ритм-гитары в секциях A, A2, A3 и B; применяется сразу." + ); + + { + const wrap = document.createElement("div"); + wrap.className = "slider-row"; + const isAuto = opts.octave_share === null || opts.octave_share === undefined; + const valText = document.createElement("span"); + valText.textContent = isAuto ? "авто" : String(opts.octave_share); + const head = document.createElement("div"); + head.className = "slider-head"; + const lbl = document.createElement("span"); + lbl.textContent = "Октавные аккорды (доля тактов)"; + head.appendChild(lbl); + head.appendChild(valText); + const row = document.createElement("div"); + row.className = "row"; + const autoBtn = document.createElement("button"); + autoBtn.className = isAuto ? "active" : ""; + autoBtn.dataset.option = "octave_share"; + autoBtn.dataset.value = "auto"; + autoBtn.textContent = "Авто"; + const inp = document.createElement("input"); + inp.type = "range"; + inp.dataset.option = "octave_share"; + inp.min = "0"; + inp.max = "1"; + inp.step = "0.05"; + inp.value = isAuto ? "0.5" : String(opts.octave_share); + inp.className = isAuto ? "slider-dim" : ""; + inp.style.flex = "1"; + autoBtn.onclick = () => mutate(`/api/piece/${encodeURIComponent(d.id)}/option`, { name: "octave_share", value: isAuto ? parseFloat(inp.value) : null }, d.id); + inp.oninput = () => { + inp.classList.remove("slider-dim"); + valText.textContent = inp.value; + }; + inp.onchange = () => mutate(`/api/piece/${encodeURIComponent(d.id)}/option`, { + name: "octave_share", + value: parseFloat(inp.value), + }, d.id); + row.appendChild(autoBtn); + row.appendChild(inp); + wrap.appendChild(head); + wrap.appendChild(row); + addHint(wrap, "Доля тактов A и A2 с октавами («Авто» — как в пьесе); применяется сразу."); + oGrid.appendChild(wrap); + } + + { + const box = document.createElement("div"); + const title = document.createElement("div"); + title.className = "piece-meta"; + title.style.marginBottom = "6px"; + title.textContent = "Длина вступления (тактов)"; + const row = document.createElement("div"); + row.className = "row"; + const cur = opts.intro_bars ?? "auto"; + for (const [val, txt] of [["auto", "Авто"], [1, "1"], [2, "2"], [4, "4"], [8, "8"]]) { + const b = document.createElement("button"); + b.className = cur === val ? "active" : ""; + b.dataset.option = "intro_bars"; + b.dataset.value = String(val); + b.textContent = txt; + b.onclick = () => mutate(`/api/piece/${encodeURIComponent(d.id)}/option`, { name: "intro_bars", value: val }, d.id); + row.appendChild(b); + } + box.appendChild(title); + box.appendChild(row); + addHint(box, "Меняет число тактов вступления по аккордам A; применяется сразу."); + oGrid.appendChild(box); + } + + { + const box = document.createElement("div"); + const title = document.createElement("div"); + title.className = "piece-meta"; + title.style.marginBottom = "6px"; + title.textContent = "Повтор квадрата в куплетах"; + const row = document.createElement("div"); + row.className = "row"; + const cur = opts.square_repeat ?? 1; + for (const [val, txt] of [[1, "1× (4 такта)"], [2, "2× (8 тактов)"]]) { + const b = document.createElement("button"); + b.className = cur === val ? "active" : ""; + b.dataset.option = "square_repeat"; + b.dataset.value = String(val); + b.textContent = txt; + b.onclick = () => mutate(`/api/piece/${encodeURIComponent(d.id)}/option`, { name: "square_repeat", value: val }, d.id); + row.appendChild(b); + } + box.appendChild(title); + box.appendChild(row); + addHint(box, "Повторяет 4-тактовый квадрат куплетов A и A2 дважды подряд; применяется сразу."); + oGrid.appendChild(box); + } + const bBox = document.createElement("div"); bBox.innerHTML = `
Соло в середине B (b_lead)
`; const bRow = document.createElement("div"); @@ -383,33 +529,12 @@

Параметры (для следующих перегенераций)${label}`; - head.appendChild(valText); - const inp = document.createElement("input"); - inp.type = "range"; - inp.min = String(min); - inp.max = String(max); - inp.step = String(step); - inp.value = String(opts[name]); - inp.oninput = () => { valText.textContent = inp.value; }; - inp.onchange = () => mutate(`/api/piece/${encodeURIComponent(d.id)}/option`, { - name, - value: step === 1 ? parseInt(inp.value, 10) : parseFloat(inp.value), - }, d.id); - wrap.appendChild(head); - wrap.appendChild(inp); - oGrid.appendChild(wrap); + addSlider(advGrid, name, label, min, max, step, null); } } diff --git a/composer-lab/studio/web_api.py b/composer-lab/studio/web_api.py index c3b2a5e..a462696 100644 --- a/composer-lab/studio/web_api.py +++ b/composer-lab/studio/web_api.py @@ -64,6 +64,22 @@ def _validate_recipe(rec): raise ValueError("invalid studio.options.b_lead") if "trailing_rest" in opts and not isinstance(opts["trailing_rest"], bool): raise ValueError("invalid studio.options.trailing_rest") + if "mute_share" in opts: + v = opts["mute_share"] + if isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v) or not 0.0 <= float(v) <= 1.0: + raise ValueError("invalid studio.options.mute_share") + if "octave_share" in opts and opts["octave_share"] is not None: + v = opts["octave_share"] + if isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v) or not 0.0 <= float(v) <= 1.0: + raise ValueError("invalid studio.options.octave_share") + if "intro_bars" in opts: + ib = opts["intro_bars"] + if ib != "auto" and (not _is_int(ib) or ib not in (1, 2, 4, 8)): + raise ValueError("invalid studio.options.intro_bars") + if "square_repeat" in opts: + sr = opts["square_repeat"] + if not _is_int(sr) or sr not in (1, 2): + raise ValueError("invalid studio.options.square_repeat") for k in engine.VALID_DOSE_FLOATS: if k in opts: v = opts[k] @@ -93,7 +109,10 @@ def _validate_state(state): def _apply_change(state, fn): pid, old_rec, undo_stack = _validate_state(state) + base_rec = engine._ensure_studio(old_rec) new_rec = fn(old_rec) + if new_rec == base_rec: + return {"id": pid, "recipe": old_rec, "undo": undo_stack} next_undo = (undo_stack + [old_rec])[-UNDO_LIMIT:] return {"id": pid, "recipe": new_rec, "undo": next_undo} diff --git a/composer-lab/test_studio.py b/composer-lab/test_studio.py index 82f7e70..7f35d81 100644 --- a/composer-lab/test_studio.py +++ b/composer-lab/test_studio.py @@ -30,6 +30,29 @@ 810: "f11bfbfac1e772e5842bf6503ece98880f531d6ab3f9f388190cc5b40807fc1a", } +GOLDEN_RANDOM_V8_MID_SHA256 = { + 792514: "68568ea2f532c2377145638a5098f8565dd59762ad848ea9310d0337c65a6f02", + 604693: "5ba6f42307c238e562b1fc9d37a310efedaba20981e936dc18ff554423fc9065", + 942077: "8b9efc818c39024fed3aec7ea95767a0a1dde06ae0eeec74686ea531dde63fe7", + 687798: "f04058211c9bdbf9d0e184af0028d2e1136a5b8ce8988e17485aab9c829fee1a", + 518853: "b408b453c90b152fc8d20e0e2422426df917817695b3a73babb8bf0b2382d563", + 168680: "2b598c5de891d22d39ff367468b550f9f79792127c18882aef551af4f24643a7", + 182816: "5d7da49efbc42f3dc981a3ec4807fa980395d043d166412e82d8cf9a7c0024f2", + 853315: "cc02ebfcfb6bf43e116aecedc2e03d48ed2e0fbdd2cbdf595438bc67e0c27948", + 588703: "a7306ea0e532eecefbf5984470407d8bf32ee665ee1c97fd7f39dcfc6a2ab7cc", + 94121: "5eaefd8f0915afa7f24d0b2835f56d7901e2589d942b266b734516f8ce1d7d58", + 566529: "1691ca14087454c4a4f064b450ed2dccf072623ef797474c482ce4d60cfaf5be", + 895585: "c2bec3c67c4145aaab02077ae9dda096f5bcfd65b999f71ff7bcb1db781c7b6a", + 396748: "05e8f92535d010eb96bc182b560f8becb773a5f49c59d144c650853e8305ed45", + 408510: "5470d575caa3378c13645e0f9a2851a34102c86ed8990dd4f6a93c27bf4fe180", + 772707: "76348c206a38d407591207757e6e7ac6382cd06a36e1ff7ee86ae08a28c34dc4", + 195912: "bebd09762fed5d4d538747d3d81179b3e797faf503f1cfce4858a91dbe5199a9", + 31844: "246f5ba3694b9801165bea57cb2f3390936b24ebcf5f2a6674d7029462714f1c", + 687270: "3721223487a74c4b984404c51f5af83f0f2a784f14262941bc1f1a8a53138a6e", + 78428: "93db201d4a85b73fecadaedb777f6ce35427db5b944e6e4f5b9e67667931b482", + 106810: "75578be9fe917d342b8ee19d10678b6d0aea8e3873b54f14321fb02c7bc7e77e", +} + def midi_sha256(piece): with tempfile.TemporaryDirectory() as d: @@ -490,10 +513,13 @@ def test_composer_invariants_after_random_rerolls(self): # 3. Octave slides from same string for g, notes in p["parts"].items(): last = {} - for n in sorted((x for x in notes if x.get("dyad")), key=lambda x: x["start"]): - if "slide" in n["tech"]: + for n in sorted(notes, key=lambda x: (x["start"], x["string"], x["pitch"])): + if n.get("dyad") and "slide" in n["tech"]: prev = last.get(n["string"]) - self.assertTrue(prev is not None and prev["fret"] != n["fret"], (s, g, n)) + self.assertTrue( + prev is not None and prev["fret"] != n["fret"] and "dead" not in prev.get("tech", []), + (s, g, prev, n), + ) last[n["string"]] = n # 4. Taps above fretting hand @@ -1301,6 +1327,764 @@ def test_stale_responses_do_not_change_the_selection(self): self.assertEqual(out["afterMutate"], "b") self.assertEqual(out["latestSeed"], 2) + def test_active_auto_button_switches_to_manual_and_mute_hint_lists_sections(self): + import subprocess + + html = studio_server.INDEX_HTML.read_text(encoding="utf-8") + self.assertIn("в секциях A, A2, A3 и B; применяется сразу.", html) + + node = shutil.which("node") + if node is None: + self.skipTest("node is not available") + script = r""" +const fs = require("fs"), vm = require("vm"); +const html = fs.readFileSync(process.argv[2], "utf8"); +const script = html.split("")[0]; +const calls = []; +const ids = new Map(); +function makeEl(tag) { + const el = { + tagName: tag, id: "", className: "", value: "", textContent: "", title: "", type: "", + min: "", max: "", step: "", disabled: false, href: "", download: "", + style: {}, dataset: {}, children: [], + classList: { + set: new Set(), + toggle(k, f) { if (f === undefined) { if (this.set.has(k)) this.set.delete(k); else this.set.add(k); } else if (f) this.set.add(k); else this.set.delete(k); }, + add(...ks) { ks.forEach((k) => this.set.add(k)); }, + remove(...ks) { ks.forEach((k) => this.set.delete(k)); }, + }, + appendChild(c) { this.children.push(c); return c; }, + addEventListener() {}, + set innerHTML(v) { this.children = []; if (this.id === "workspace") { for (const k of Array.from(ids.keys())) { if (!["workspace", "pieceList", "busy", "newBtn", "seedInput"].includes(k)) ids.delete(k); } } }, + get innerHTML() { return ""; }, + }; + return el; +} +for (const id of ["workspace", "pieceList", "busy", "newBtn", "seedInput"]) { + const e = makeEl("div"); + e.id = id; + ids.set(id, e); +} +const ctx = { + document: { + getElementById: (id) => { + if (!ids.has(id)) { + const e = makeEl("div"); + e.id = id; + ids.set(id, e); + ids.get("workspace").appendChild(e); + } + return ids.get(id); + }, + createElement: (tag) => makeEl(tag), + }, + fetch: async (url, opts) => { + calls.push({ url, body: opts && opts.body ? JSON.parse(opts.body) : null }); + return { ok: true, json: async () => ({ pieces: [], id: "p1", seed: 1, meter: "4/4", mode: "lydian", key: "E", tempo: 140, length: 10, sections: [], whole_layers: [], options: { octave_share: 0.5 }, can_undo: true }) }; + }, + alert() {}, console, Date, Math, Number, String, Promise, encodeURIComponent, parseInt, parseFloat, +}; +vm.createContext(ctx); +vm.runInContext(script, ctx); +function findAutoBtn(node) { + if (node.dataset && node.dataset.option === "octave_share" && node.dataset.value === "auto") return node; + for (const c of node.children || []) { const f = findAutoBtn(c); if (f) return f; } + return null; +} +(async () => { + vm.runInContext('state.current = { id: "p1", seed: 1, meter: "4/4", mode: "lydian", key: "E", tempo: 140, length: 10, sections: [], whole_layers: [], options: { octave_share: null }, can_undo: false }; renderWorkspace();', ctx); + const auto1 = findAutoBtn(ids.get("workspace")); + auto1.onclick(); + await new Promise((r) => setTimeout(r, 10)); + vm.runInContext('state.current.options.octave_share = 0.5; renderWorkspace();', ctx); + const auto2 = findAutoBtn(ids.get("workspace")); + auto2.onclick(); + await new Promise((r) => setTimeout(r, 10)); + console.log(JSON.stringify(calls.filter((c) => c.url.endsWith("/option")).map((c) => c.body))); +})(); +""" + script = "const vm = require('vm');\n" + script.replace("const fs = require(\"fs\"), vm = require(\"vm\");", "const fs = require(\"fs\");") + with tempfile.TemporaryDirectory() as d: + harness = Path(d) / "opt_harness.js" + harness.write_text(script, encoding="utf-8") + res = subprocess.run( + [node, str(harness), str(studio_server.INDEX_HTML)], capture_output=True, text=True, timeout=60 + ) + self.assertEqual(res.returncode, 0, res.stderr) + sent = json.loads(res.stdout.strip().splitlines()[-1]) + self.assertEqual(sent, [{"name": "octave_share", "value": 0.5}, {"name": "octave_share", "value": None}]) + + +class TestStudioControls(unittest.TestCase): + def _v8_plain(self, seed): + args = argparse.Namespace(meter=None, mode=None, key=None, tempo=None, v8=True) + return composer.make_recipe(seed, args) + + def test_defaults_byte_identical(self): + rng = random.Random(20261123) + rand_seeds = rng.sample(range(1000, 999999), 20) + self.assertEqual(set(rand_seeds), set(GOLDEN_RANDOM_V8_MID_SHA256)) + seeds = [s * 1000 for s in (801, 802, 805, 807, 809, 810)] + rand_seeds + for seed in seeds: + plain = self._v8_plain(seed) + rec = studio_engine.new_recipe(seed) + rec_omitted = copy.deepcopy(rec) + for k in ("mute_share", "octave_share", "intro_bars", "square_repeat"): + rec_omitted["studio"]["options"].pop(k, None) + h_plain = midi_sha256(composer.compose(plain)) + h_rec = midi_sha256(composer.compose(rec)) + h_omitted = midi_sha256(composer.compose(rec_omitted)) + self.assertEqual(h_rec, h_plain, seed) + self.assertEqual(h_omitted, h_plain, seed) + if seed in GOLDEN_RANDOM_V8_MID_SHA256: + self.assertEqual(h_plain, GOLDEN_RANDOM_V8_MID_SHA256[seed], seed) + self.assertEqual(h_rec, GOLDEN_RANDOM_V8_MID_SHA256[seed], seed) + self.assertEqual(h_omitted, GOLDEN_RANDOM_V8_MID_SHA256[seed], seed) + for s, expected in GOLDEN_V8_MID_SHA256.items(): + self.assertEqual(midi_sha256(composer.compose(studio_engine.new_recipe(s * 1000))), expected, s) + + def test_mute_share(self): + seeds_20 = [s * 1000 for s in range(801, 821)] + target_secs = {"A", "A2", "A3", "B"} + + for seed in seeds_20: + rec0 = studio_engine.new_recipe(seed) + p0 = composer.compose(rec0) + rec1 = studio_engine.set_option(rec0, "mute_share", 1.0) + p1 = composer.compose(rec1) + lead = rec0["intent"]["lead"] + other = other_of(rec0) + + self.assertEqual(p0["parts"][lead], p1["parts"][lead], ("lead changed", seed)) + + spans = section_spans(p0) + self.assertEqual(spans, section_spans(p1), seed) + for sn, s0, e0 in spans: + ns0 = sorted((n for n in p0["parts"][other] if s0 <= n["start"] < e0), key=lambda n: (n["start"], n["pitch"])) + ns1 = sorted((n for n in p1["parts"][other] if s0 <= n["start"] < e0), key=lambda n: (n["start"], n["pitch"])) + if sn in target_secs: + self.assertEqual(len(ns0), len(ns1), (seed, sn)) + for a, b in zip(ns0, ns1): + self.assertEqual( + (a["start"], a["pitch"], a["string"], a["fret"]), + (b["start"], b["pitch"], b["string"], b["fret"]), + (seed, sn), + ) + self.assertIn("dead", b.get("tech", []), (seed, sn, b)) + self.assertEqual(b["dur"], 1, (seed, sn, b)) + if "dead" in a.get("tech", []): + self.assertEqual(b["vel"], a["vel"], (seed, sn, b)) + else: + self.assertEqual(b["vel"], 40, (seed, sn, b)) + else: + self.assertEqual(ns0, ns1, ("non-target section changed", seed, sn)) + + # mute_share=0.3 share, onset grouping, determinism, and undo + muted_onsets = 0 + total_onsets = 0 + for seed in seeds_20: + rec0 = studio_engine.new_recipe(seed) + p0 = composer.compose(rec0) + rec_m1 = studio_engine.set_option(rec0, "mute_share", 0.3) + rec_m2 = studio_engine.set_option(rec0, "mute_share", 0.3) + p_m1 = composer.compose(rec_m1) + self.assertEqual(midi_sha256(p_m1), midi_sha256(composer.compose(rec_m2)), seed) + other = other_of(rec0) + + pre_dead_onsets = set() + for n in p0["parts"][other]: + if "dead" in n.get("tech", []): + pre_dead_onsets.add(n["start"]) + + for sn, s0, e0 in section_spans(p_m1): + if sn not in target_secs: + continue + by_onset = {} + for n in p_m1["parts"][other]: + if s0 <= n["start"] < e0: + by_onset.setdefault(n["start"], []).append(n) + for on, grp in by_onset.items(): + if on in pre_dead_onsets: + continue + total_onsets += 1 + deads = ["dead" in n.get("tech", []) for n in grp] + self.assertTrue(all(deads) or not any(deads), ("partial onset mute", seed, on, grp)) + if all(deads): + muted_onsets += 1 + + share = muted_onsets / max(1, total_onsets) + self.assertTrue(0.2 <= share <= 0.4, (muted_onsets, total_onsets, share)) + + with tempfile.TemporaryDirectory() as d: + store = studio_engine.StudioStore(d, render_fn=studio_render.fake_render) + det0 = store.create_piece(801000) + pid = det0["id"] + pdir = Path(d) / pid + mid0 = (pdir / "piece.mid").read_bytes() + store.set_option(pid, "mute_share", 0.5) + mid1 = (pdir / "piece.mid").read_bytes() + self.assertNotEqual(mid0, mid1) + store.undo(pid) + self.assertEqual((pdir / "piece.mid").read_bytes(), mid0) + + def test_octave_share(self): + seeds_20 = [s * 1000 for s in range(801, 821)] + for seed in seeds_20: + rec0 = studio_engine.new_recipe(seed) + p0 = composer.compose(rec0) + rec_auto = studio_engine.set_option(rec0, "octave_share", None) + self.assertEqual(midi_sha256(p0), midi_sha256(composer.compose(rec_auto)), seed) + + other = other_of(rec0) + rec1 = studio_engine.set_option(rec0, "octave_share", 1.0) + p1, t1 = traced(rec1) + for i, b in enumerate(t1["form"]): + if b["sec"] in ("A", "A2") and (b.get("role") or b.get("prog") == "cad_open") and not b.get("tex"): + self.assertEqual(b["role"], "octave", (seed, i, b)) + s0 = p1["chords"][i]["start"] + s1 = p1["chords"][i + 1]["start"] if i + 1 < len(p1["chords"]) else p1["total16"] + in_bar = [n for n in p1["parts"][other] if s0 <= n["start"] < s1] + dyads = [n for n in in_bar if n.get("dyad")] + self.assertTrue(dyads, (seed, i)) + self.assertEqual(len(dyads), len(in_bar), (seed, i, in_bar)) + by_on = {} + for n in dyads: + by_on.setdefault(n["start"], []).append(n) + for pair in by_on.values(): + self.assertEqual(sorted(n["string"] for n in pair), [1, 3], (seed, pair)) + lo, hi = sorted(n["pitch"] for n in pair) + self.assertEqual(hi - lo, 12, (seed, pair)) + + rec_zero = studio_engine.set_option(rec0, "octave_share", 0.0) + p_zero, t_zero = traced(rec_zero) + for i, b in enumerate(t_zero["form"]): + if b["sec"] in ("A", "A2"): + self.assertNotEqual(b.get("role"), "octave", (seed, i, b)) + s0 = p_zero["chords"][i]["start"] + s1 = p_zero["chords"][i + 1]["start"] if i + 1 < len(p_zero["chords"]) else p_zero["total16"] + dyads = [n for n in p_zero["parts"][other] if s0 <= n["start"] < s1 and n.get("dyad")] + self.assertEqual(dyads, [], (seed, i)) + + # Regression check on seed 801000: 4th bar of A (cad_open) and A2 cadence must play octaves, not [62, 65, 69, 74] + rec_801 = studio_engine.set_option(studio_engine.new_recipe(801000), "octave_share", 1.0) + p_801, t_801 = traced(rec_801) + other_801 = other_of(rec_801) + cad_bars = [i for i, b in enumerate(t_801["form"]) if b["sec"] in ("A", "A2") and b["prog"] == "cad_open"] + self.assertTrue(cad_bars) + for bi in cad_bars: + s0 = p_801["chords"][bi]["start"] + s1 = p_801["chords"][bi + 1]["start"] if bi + 1 < len(p_801["chords"]) else p_801["total16"] + bar_notes = [n for n in p_801["parts"][other_801] if s0 <= n["start"] < s1] + self.assertTrue(bar_notes and all(n.get("dyad") for n in bar_notes), (bi, bar_notes)) + self.assertNotIn([62, 65, 69, 74], [sorted(n["pitch"] for n in bar_notes if n["start"] == s0)]) + + def test_mute_share_preserves_repeat_and_locks(self): + rec0 = studio_engine.new_recipe(801000) + rec_rep = studio_engine.set_option(rec0, "mute_share", 0.3) + rec_rep = studio_engine.set_option(rec_rep, "square_repeat", 2) + p_rep = composer.compose(rec_rep) + for sec in ("A", "A2"): + s0, e0 = span_of(p_rep, sec) + half = (e0 - s0) // 2 + for g in ("g1", "g2"): + self.assertEqual( + section_notes(p_rep, g, s0, s0 + half), + section_notes(p_rep, g, s0 + half, e0), + (sec, g), + ) + + rec_lock = studio_engine.set_option(rec0, "mute_share", 0.3) + rec_lock = studio_engine.set_lock(rec_lock, "comp", "A", True) + p_a0 = composer.compose(rec_lock) + other = other_of(rec_lock) + p_a1 = composer.compose(studio_engine.reroll(rec_lock, "intro", "intro")) + self.assertEqual( + section_notes(p_a0, other, *span_of(p_a0, "A")), + section_notes(p_a1, other, *span_of(p_a1, "A")), + ) + p_a2 = composer.compose(studio_engine.set_option(rec_lock, "intro_bars", 8)) + self.assertEqual( + section_notes(p_a0, other, *span_of(p_a0, "A")), + section_notes(p_a2, other, *span_of(p_a2, "A")), + ) + + def test_mute_share_clears_incoming_legato_from_dead_notes(self): + stripped_cases = 0 + for seed in [s * 1000 for s in range(801, 821)]: + rec0 = studio_engine.new_recipe(seed) + p0 = composer.compose(rec0) + other = other_of(rec0) + orig_legato = { + (n["start"], n["string"]) + for n in p0["parts"][other] + if {"hammer", "pull", "slide"} & set(n.get("tech", [])) + } + for share in (0.3, 1.0): + rec = studio_engine.set_option(rec0, "mute_share", share) + p = composer.compose(rec) + last_str = {} + prev_line = None + for n in sorted(p["parts"][other], key=lambda x: (x["start"], x["string"], x["pitch"])): + p_str = last_str.get(n["string"]) + is_line = ( + not n.get("chordtone") + and not n.get("dyad") + and not (n.get("fixed") and "preset_tech" not in n) + ) + if (n["start"], n["string"]) in orig_legato and not ({"hammer", "pull", "slide"} & set(n.get("tech", []))): + stripped_cases += 1 + if {"hammer", "pull", "slide"} & set(n.get("tech", [])): + self.assertFalse(p_str is not None and "dead" in p_str.get("tech", []), (seed, share, p_str, n)) + if is_line: + self.assertFalse( + prev_line is not None and "dead" in prev_line.get("tech", []), + (seed, share, prev_line, n), + ) + last_str[n["string"]] = n + if is_line: + prev_line = n + + if seed <= 805000: + with tempfile.TemporaryDirectory() as d: + composer.export(p, Path(d) / "x") + root = ET.parse(Path(d) / "x.musicxml").getroot() + pid = "P2" if other == "g2" else "P1" + part = next(pt for pt in root.iter("part") if pt.get("id") == pid) + for note in part.iter("note"): + if note.find("notehead") is not None and note.findtext("notehead") == "x": + for tag in ("hammer-on", "pull-off", "slide"): + for el in note.iter(tag): + self.assertNotEqual(el.get("type"), "start", (seed, share, tag)) + self.assertGreater(stripped_cases, 0) + + def test_musicxml_writes_muted_strokes_as_one_division(self): + rec = studio_engine.set_option(studio_engine.new_recipe(801000), "mute_share", 1.0) + p = composer.compose(rec) + other = other_of(rec) + pid = "P2" if other == "g2" else "P1" + with tempfile.TemporaryDirectory() as d: + composer.export(p, Path(d) / "x") + root = ET.parse(Path(d) / "x.musicxml").getroot() + part = next(pt for pt in root.iter("part") if pt.get("id") == pid) + m3 = next(m for m in part.iter("measure") if m.get("number") == "3") + m3_notes = list(m3.iter("note")) + self.assertTrue(m3_notes) + self.assertIsNotNone(m3_notes[0].find("notehead")) + self.assertEqual(m3_notes[0].findtext("notehead"), "x") + self.assertEqual(int(m3_notes[0].findtext("duration")), 1) + rest_after = next((n for n in m3_notes[1:] if n.find("chord") is None), None) + self.assertIsNotNone(rest_after) + self.assertIsNotNone(rest_after.find("rest")) + + rec_03 = studio_engine.set_option(studio_engine.new_recipe(801000), "mute_share", 0.3) + p_03 = composer.compose(rec_03) + with tempfile.TemporaryDirectory() as d: + composer.export(p_03, Path(d) / "x") + root_03 = ET.parse(Path(d) / "x.musicxml").getroot() + part_03 = next(pt for pt in root_03.iter("part") if pt.get("id") == pid) + num = den = None + for m in part_03.iter("measure"): + t = m.find("attributes/time") + if t is not None: + num, den = int(t.findtext("beats")), int(t.findtext("beat-type")) + total = sum(int(n.findtext("duration")) for n in m.iter("note") if n.find("chord") is None) + self.assertEqual(total, num * 16 // den) + for n in m.iter("note"): + if n.find("notehead") is not None and n.findtext("notehead") == "x": + self.assertEqual(int(n.findtext("duration")), 1) + + def test_octave_slides_validated_against_all_preceding_notes_and_repeat_boundary(self): + rec = studio_engine.set_option(studio_engine.new_recipe(4), "octave_share", 0.5) + p = composer.compose(rec) + other = other_of(rec) + smax = rec["studio"]["options"]["slide_max"] + last = {} + for n in sorted(p["parts"][other], key=lambda x: (x["start"], x["string"], x["pitch"])): + if n.get("dyad") and "slide" in n.get("tech", []): + prev = last.get(n["string"]) + self.assertIsNotNone(prev, n) + self.assertNotEqual(prev["fret"], n["fret"], (prev, n)) + self.assertNotIn("dead", prev.get("tech", []), (prev, n)) + self.assertLessEqual(abs(n["fret"] - prev["fret"]), smax, (prev, n)) + last[n["string"]] = n + + rec_rep = studio_engine.set_option(rec, "square_repeat", 2) + p_rep = composer.compose(rec_rep) + s0, e0 = span_of(p_rep, "A2") + half = (e0 - s0) // 2 + self.assertEqual(section_notes(p_rep, other, s0, s0 + half), section_notes(p_rep, other, s0 + half, e0)) + slides_a2 = [ + n for n in p_rep["parts"][other] + if s0 <= n["start"] < s0 + half and n.get("dyad") and n["string"] == 1 and "slide" in n.get("tech", []) + ] + self.assertTrue(slides_a2, "valid fret 3->5 slide on string 1 in A2 bar 2 must be kept with square_repeat=2") + + def test_legacy_dose_edit_preserves_saved_arrangement_with_octave_share(self): + rec = studio_engine.new_recipe(801000) + rec["studio"]["salts"]["comp@A"] = 1 + rec["studio"]["options"]["octave_piece"] = 0.0 + rec["studio"]["options"]["octave_sixteenths"] = 1.0 + rec["studio"].pop("comp_doses", None) + rec = studio_engine.set_option(rec, "octave_share", 1.0) + p0 = composer.compose(rec) + rec2 = studio_engine.set_option(rec, "slide_max", 4) + p1 = composer.compose(rec2) + other = other_of(rec) + self.assertEqual( + section_notes(p0, other, *span_of(p0, "A")), + section_notes(p1, other, *span_of(p1, "A")), + ) + self.assertEqual(midi_sha256(p0), midi_sha256(p1)) + + def test_rerolls_vary_under_fixed_octave_share_and_intro_bars(self): + rec = studio_engine.set_option(studio_engine.new_recipe(801000), "octave_share", 1.0) + rec = studio_engine.set_option(rec, "octave_piece", 0.0) + other = other_of(rec) + a_notes = [] + cur = rec + a_notes.append(section_notes(composer.compose(cur), other, *span_of(composer.compose(cur), "A"))) + for _ in range(5): + cur = studio_engine.reroll(cur, "comp", "A") + p = composer.compose(cur) + a_notes.append(section_notes(p, other, *span_of(p, "A"))) + self.assertNotEqual(a_notes[0], a_notes[1]) + self.assertGreater(len({tuple(x) for x in a_notes[1:]}), 1) + + rec_in = studio_engine.set_option(studio_engine.new_recipe(0), "intro_bars", 8) + p_in0 = composer.compose(rec_in) + p_in1 = composer.compose(studio_engine.reroll(rec_in, "intro", "intro")) + other_0 = other_of(rec_in) + self.assertNotEqual( + section_notes(p_in0, other_0, *span_of(p_in0, "intro")), + section_notes(p_in1, other_0, *span_of(p_in1, "intro")), + ) + + def test_comp_first_reroll_always_changes_forced_octaves_over_60_seeds(self): + seeds = [s * 1000 for s in range(801, 821)] + list(range(40)) + for seed in seeds: + for oct_piece in (0.0, 0.5, 1.0): + rec0 = studio_engine.new_recipe(seed) + rec0 = studio_engine.set_option(rec0, "octave_share", 1.0) + rec0 = studio_engine.set_option(rec0, "octave_piece", oct_piece) + other = other_of(rec0) + p0 = composer.compose(rec0) + rec1 = studio_engine.reroll(rec0, "comp", "A") + p1 = composer.compose(rec1) + self.assertNotEqual( + section_notes(p0, other, *span_of(p0, "A")), + section_notes(p1, other, *span_of(p1, "A")), + (seed, "A", oct_piece), + ) + rec0 = studio_engine.new_recipe(seed) + rec0 = studio_engine.set_option(rec0, "octave_share", 1.0) + rec0 = studio_engine.set_option(rec0, "octave_piece", 0.0) + other = other_of(rec0) + p0 = composer.compose(rec0) + if "A2" in [sn for sn, _, _ in section_spans(p0)]: + rec1_a2 = studio_engine.reroll(rec0, "comp", "A2") + p1_a2 = composer.compose(rec1_a2) + self.assertNotEqual( + section_notes(p0, other, *span_of(p0, "A2")), + section_notes(p1_a2, other, *span_of(p1_a2, "A2")), + (seed, "A2"), + ) + + def test_noop_option_does_not_push_undo_or_log(self): + with tempfile.TemporaryDirectory() as d: + render = RecordingRender() + store = studio_engine.StudioStore(d, render_fn=render) + det0 = store.create_piece(801000) + pid = det0["id"] + pdir = store._piece_dir(pid) + calls0 = render.calls + + for name, val in ( + ("intro_bars", "auto"), + ("square_repeat", 1), + ("mute_share", 0.0), + ("octave_share", None), + ("b_lead", "augmented"), + ("trailing_rest", det0["options"]["trailing_rest"]), + ("octave_piece", composer.V8["octave_piece"]), + ("slide_max", composer.V8["slide_max"]), + ("mute_share", -0.1), + ): + det = store.set_option(pid, name, val) + self.assertFalse(det["can_undo"], (name, val)) + self.assertEqual(store._read_undo(pdir), [], (name, val)) + self.assertEqual(render.calls, calls0, (name, val)) + + actions = [json.loads(line)["action"] for line in (pdir / "history.jsonl").read_text(encoding="utf-8").splitlines() if line] + self.assertEqual(actions, ["new"]) + + det1 = store.set_option(pid, "intro_bars", 8) + self.assertTrue(det1["can_undo"]) + self.assertEqual(len(store._read_undo(pdir)), 1) + actions = [json.loads(line)["action"] for line in (pdir / "history.jsonl").read_text(encoding="utf-8").splitlines() if line] + self.assertEqual(actions, ["new", "option"]) + + det2 = store.set_option(pid, "intro_bars", 8) + self.assertTrue(det2["can_undo"]) + self.assertEqual(len(store._read_undo(pdir)), 1) + actions = [json.loads(line)["action"] for line in (pdir / "history.jsonl").read_text(encoding="utf-8").splitlines() if line] + self.assertEqual(actions, ["new", "option"]) + + det_undo = store.undo(pid) + self.assertEqual(det_undo["options"]["intro_bars"], "auto") + self.assertFalse(det_undo["can_undo"]) + + with tempfile.TemporaryDirectory() as d: + srv = studio_server.create_server(d, host="127.0.0.1", port=0, render_fn=studio_render.fake_render) + threading.Thread(target=srv.serve_forever, daemon=True).start() + base = f"http://127.0.0.1:{srv.server_address[1]}" + try: + def post(path, body): + req = urllib.request.Request( + base + path, + data=json.dumps(body).encode("utf-8"), + method="POST", + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(req, timeout=10) as r: + return r.status, json.loads(r.read()) + + st, det = post("/api/new", {"seed": 801000}) + self.assertEqual(st, 200) + pid = det["id"] + st, out = post(f"/api/piece/{pid}/option", {"name": "intro_bars", "value": "auto"}) + self.assertEqual(st, 200) + self.assertFalse(out["can_undo"]) + lines = [json.loads(line) for line in (Path(d) / pid / "history.jsonl").read_text(encoding="utf-8").splitlines() if line] + self.assertEqual([x["action"] for x in lines], ["new"]) + finally: + srv.shutdown() + srv.server_close() + + with tempfile.TemporaryDirectory() as d: + store = studio_engine.StudioStore(d, render_fn=studio_render.fake_render) + pid = store.create_piece(801000)["id"] + pdir = store._piece_dir(pid) + rec = store._read_recipe(pdir) + rec["studio"]["salts"]["comp@A"] = 1 + rec["studio"].pop("comp_doses", None) + raw_before = json.dumps(rec, indent=1) + (pdir / "recipe.json").write_text(raw_before, encoding="utf-8") + + det = store.set_option(pid, "slide_max", composer.V8["slide_max"]) + self.assertFalse(det["can_undo"]) + self.assertEqual((pdir / "recipe.json").read_text(encoding="utf-8"), raw_before) + lines = [json.loads(line) for line in (pdir / "history.jsonl").read_text(encoding="utf-8").splitlines() if line] + self.assertEqual([x["action"] for x in lines], ["new"]) + + def test_intro_bars(self): + for seed in [s * 1000 for s in range(801, 811)]: + rec0 = studio_engine.new_recipe(seed) + p0 = composer.compose(rec0) + rec_auto = studio_engine.set_option(rec0, "intro_bars", "auto") + self.assertEqual(midi_sha256(p0), midi_sha256(composer.compose(rec_auto)), seed) + + for count in (1, 2, 4, 8): + rec_n = studio_engine.set_option(rec0, "intro_bars", count) + p_n = composer.compose(rec_n) + intro_chords = [c for c in p_n["chords"] if c["sec"] == "intro"] + self.assertEqual(len(intro_chords), count, (seed, count)) + harm_a = rec0["harmony"]["A"] + self.assertEqual( + [c["root_deg"] for c in intro_chords], + [harm_a[i % len(harm_a)] for i in range(count)], + (seed, count), + ) + p8 = composer.compose(studio_engine.set_option(rec0, "intro_bars", 8)) + s0 = section_spans(p0) + s8 = section_spans(p8) + for (sn0, a0, b0), (sn8, a8, b8) in zip(s0[1:], s8[1:]): + self.assertEqual(sn0, sn8) + for g in ("g1", "g2"): + self.assertTrue( + boundary_equal(section_notes(p0, g, a0, b0), section_notes(p8, g, a8, b8), b0 - a0), + (seed, sn0, g), + ) + + def test_square_repeat(self): + seeds_20 = [s * 1000 for s in range(801, 821)] + saw_a2 = False + for seed in seeds_20: + rec0 = studio_engine.new_recipe(seed) + p0 = composer.compose(rec0) + rec1 = studio_engine.set_option(rec0, "square_repeat", 1) + self.assertEqual(midi_sha256(p0), midi_sha256(composer.compose(rec1)), seed) + + rec2 = studio_engine.set_option(rec0, "square_repeat", 2) + p2 = composer.compose(rec2) + sp0 = section_spans(p0) + sp2 = section_spans(p2) + self.assertEqual([x[0] for x in sp0], [x[0] for x in sp2], seed) + + grow = sum(e - s for sn, s, e in sp0 if sn in ("A", "A2")) + self.assertEqual(p2["total16"], p0["total16"] + grow, seed) + + for sec in ("A", "A2"): + if not any(sn == sec for sn, _, _ in sp0): + continue + if sec == "A2": + saw_a2 = True + bars0 = sum(1 for c in p0["chords"] if c["sec"] == sec) + bars2 = sum(1 for c in p2["chords"] if c["sec"] == sec) + self.assertEqual(bars2, bars0 * 2, (seed, sec)) + s0, e0 = span_of(p2, sec) + half = (e0 - s0) // 2 + for g in ("g1", "g2"): + first_half = section_notes(p2, g, s0, s0 + half) + second_half = section_notes(p2, g, s0 + half, e0) + self.assertEqual(first_half, second_half, (seed, sec, g)) + self.assertTrue(saw_a2) + + def test_server_options_validation_and_ui_labels(self): + with tempfile.TemporaryDirectory() as d: + srv = studio_server.create_server(d, host="127.0.0.1", port=0, render_fn=studio_render.fake_render) + threading.Thread(target=srv.serve_forever, daemon=True).start() + base = f"http://127.0.0.1:{srv.server_address[1]}" + try: + with urllib.request.urlopen(base + "/", timeout=10) as resp: + html = resp.read().decode("utf-8") + for label in ( + "Глухие ноты (доля ударов ритм-гитары)", + "Глушит долю ударов ритм-гитары в секциях A, A2, A3 и B; применяется сразу.", + "Октавные аккорды (доля тактов)", + "Длина вступления (тактов)", + "Повтор квадрата в куплетах", + "Дополнительно", + "Вероятность октав при перегенерации ритма", + "Октавы шестнадцатыми (при перегенерации)", + "Глухие перед акцентами в октавах (при перегенерации)", + ): + self.assertIn(label, html) + + def post(path, body): + req = urllib.request.Request( + base + path, + data=json.dumps(body).encode("utf-8"), + method="POST", + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(req, timeout=10) as r: + return r.status, json.loads(r.read()) + except urllib.error.HTTPError as exc: + return exc.code, json.loads(exc.read()) + + st, det = post("/api/new", {"seed": 801000}) + self.assertEqual(st, 200) + pid = det["id"] + for name, val in ( + ("mute_share", 0.35), + ("octave_share", 0.5), + ("octave_share", None), + ("intro_bars", 8), + ("intro_bars", "auto"), + ("square_repeat", 2), + ): + st, out = post(f"/api/piece/{pid}/option", {"name": name, "value": val}) + self.assertEqual(st, 200, (name, val, out)) + self.assertEqual(out["options"][name], val) + + for name, bad_val in ( + ("mute_share", True), + ("mute_share", "0.5"), + ("octave_share", True), + ("intro_bars", 3), + ("intro_bars", True), + ("intro_bars", "8"), + ("square_repeat", 3), + ("square_repeat", True), + ): + st, out = post(f"/api/piece/{pid}/option", {"name": name, "value": bad_val}) + self.assertEqual(st, 400, (name, bad_val, out)) + finally: + srv.shutdown() + srv.server_close() + + def test_composer_invariants_with_random_control_combinations(self): + bad_clash = shared_clash = 0 + for s in range(801, 821): + rng = random.Random(s + 9191) + rec = studio_engine.new_recipe(s * 1000) + rec = studio_engine.set_option(rec, "mute_share", rng.choice([0.0, 0.3, 0.6, 1.0])) + rec = studio_engine.set_option(rec, "octave_share", rng.choice([None, 0.0, 0.5, 1.0])) + rec = studio_engine.set_option(rec, "intro_bars", rng.choice(["auto", 1, 2, 4, 8])) + rec = studio_engine.set_option(rec, "square_repeat", rng.choice([1, 2])) + + p = composer.compose(rec) + + for g, notes in p["parts"].items(): + for n in notes: + self.assertTrue(0 <= n["fret"] <= fretboard.MAX_FRET, (s, g, n)) + self.assertEqual(fretboard.OPEN[n["string"]] + n["fret"], n["pitch"], (s, g, n)) + + for g, notes in p["parts"].items(): + line = [ + n for n in notes + if not n.get("chordtone") and not n.get("dyad") and not (n.get("fixed") and "preset_tech" not in n) + ] + for prev, n in zip(line, line[1:]): + if {"hammer", "pull", "slide"} & set(n["tech"]): + self.assertEqual(prev["string"], n["string"], (s, g, n)) + if "hammer" in n["tech"]: + self.assertGreater(n["fret"], prev["fret"], (s, g, n)) + + for g, notes in p["parts"].items(): + last = {} + for n in sorted(notes, key=lambda x: (x["start"], x["string"], x["pitch"])): + if n.get("dyad") and "slide" in n["tech"]: + prev = last.get(n["string"]) + self.assertTrue( + prev is not None and prev["fret"] != n["fret"] and "dead" not in prev.get("tech", []), + (s, g, prev, n), + ) + last[n["string"]] = n + + for g, notes in p["parts"].items(): + for _, n in zip(notes, notes[1:]): + if "tap" in n.get("tech", []) and n.get("fixed"): + nxt = [ + m for m in notes + if n["start"] < m["start"] <= n["start"] + 2 + and m["string"] == n["string"] + and "pull" in m.get("tech", []) + ][:1] + for m in nxt: + self.assertGreater(n["fret"], m["fret"], (s, g, n)) + + g2 = {} + for n in p["parts"]["g2"]: + g2.setdefault(n["start"], []).append(n["pitch"]) + for n in p["parts"]["g1"]: + for q in g2.get(n["start"], []): + shared_clash += 1 + bad_clash += abs(n["pitch"] - q) % 12 in (1, 11) + + a = [(n["start"], n["start"] + n["dur"], n["pitch"]) for n in p["parts"]["g1"]] + b = [(n["start"], n["start"] + n["dur"], n["pitch"]) for n in p["parts"]["g2"]] + for x, y in ((a, b), (b, a)): + for s0, _, pa in x: + for s2, e2, q in y: + if s2 <= s0 < e2 and pa != q: + self.assertNotEqual(abs(pa - q) % 12, 1, (s, s0, pa, q)) + + with tempfile.TemporaryDirectory() as d: + composer.export(p, Path(d) / "x") + root = ET.parse(Path(d) / "x.musicxml").getroot() + for part in root.iter("part"): + num = den = None + for m in part.iter("measure"): + t = m.find("attributes/time") + if t is not None: + num, den = int(t.findtext("beats")), int(t.findtext("beat-type")) + total = sum(int(n.findtext("duration")) for n in m.iter("note") if n.find("chord") is None) + self.assertEqual(total, num * 16 // den, (s, part.get("id"), m.get("number"))) + + self.assertLess(bad_clash / max(1, shared_clash), 0.03, (bad_clash, shared_clash)) + if __name__ == "__main__": unittest.main() diff --git a/composer-lab/test_web_api.py b/composer-lab/test_web_api.py index aef90ee..8675f8a 100644 --- a/composer-lab/test_web_api.py +++ b/composer-lab/test_web_api.py @@ -167,6 +167,141 @@ def test_engine_importable_without_studio_render(self): ) self.assertEqual(res.returncode, 0, res.stderr) + def test_new_controls_sequence_matches_studio_store(self): + with tempfile.TemporaryDirectory() as d: + store = studio_engine.StudioStore(d, render_fn=studio_render.fake_render) + det = store.create_piece(801000) + pid = det["id"] + st = web_api.new_piece(801000) + + steps = [ + ("mute_share", 0.4), + ("octave_share", 1.0), + ("intro_bars", 8), + ("square_repeat", 2), + ("octave_share", 0.0), + ("octave_share", None), + ] + pdir = Path(d) / pid + for name, val in steps: + s_det = store.set_option(pid, name, val) + st = json.loads(json.dumps(web_api.option(st, name, val))) + w_det = web_api.detail(st) + self.assertEqual(w_det, s_det, (name, val)) + self.assertEqual( + st["recipe"], + json.loads((pdir / "recipe.json").read_text(encoding="utf-8")), + (name, val), + ) + self.assertEqual( + base64.b64decode(web_api.export_midi(st)), + (pdir / "piece.mid").read_bytes(), + (name, val), + ) + + s_det = store.undo(pid) + st = json.loads(json.dumps(web_api.undo(st))) + self.assertEqual(web_api.detail(st), s_det) + self.assertEqual(base64.b64decode(web_api.export_midi(st)), (pdir / "piece.mid").read_bytes()) + + def test_new_controls_validation(self): + st = web_api.new_piece(801000) + for name, bad in ( + ("mute_share", True), + ("mute_share", "0.5"), + ("octave_share", False), + ("intro_bars", 3), + ("intro_bars", True), + ("intro_bars", "8"), + ("square_repeat", 3), + ("square_repeat", True), + ): + with self.assertRaises(ValueError, msg=(name, bad)): + web_api.option(st, name, bad) + bad_st = copy.deepcopy(st) + bad_st["recipe"]["studio"]["options"][name] = bad + with self.assertRaises(ValueError, msg=("validate", name, bad)): + web_api.detail(bad_st) + + for name, out_of_range in (("mute_share", -0.1), ("mute_share", 1.5), ("octave_share", 2.0)): + bad_st = copy.deepcopy(st) + bad_st["recipe"]["studio"]["options"][name] = out_of_range + with self.assertRaises(ValueError, msg=("validate", name, out_of_range)): + web_api.detail(bad_st) + self.assertEqual(web_api.option(st, "mute_share", -0.1)["recipe"]["studio"]["options"]["mute_share"], 0.0) + self.assertEqual(web_api.option(st, "octave_share", 2.0)["recipe"]["studio"]["options"]["octave_share"], 1.0) + + def test_square_repeat_repeats_disjoint_a_runs_independently(self): + import xml.etree.ElementTree as ET + + st = web_api.new_piece(802000) + form = st["recipe"]["form"] + a_bars = [copy.deepcopy(b) for b in form if b["sec"] == "A"] + b_end = max(i for i, b in enumerate(form) if b["sec"] == "B") + st["recipe"]["form"] = form[:b_end + 1] + a_bars + form[b_end + 1:] + + snap1 = web_api.snapshot(st) + b_secs_1 = [s for s in snap1["detail"]["sections"] if s["section"] == "B"] + self.assertEqual(len(b_secs_1), 1) + b_dur_1 = b_secs_1[0]["end16"] - b_secs_1[0]["start16"] + + st2 = web_api.option(st, "square_repeat", 2) + snap2 = web_api.snapshot(st2) + b_secs_2 = [s for s in snap2["detail"]["sections"] if s["section"] == "B"] + self.assertEqual(len(b_secs_2), 1) + self.assertEqual(b_secs_2[0]["end16"] - b_secs_2[0]["start16"], b_dur_1) + + a_secs_1 = [s for s in snap1["detail"]["sections"] if s["section"] == "A"] + a_secs_2 = [s for s in snap2["detail"]["sections"] if s["section"] == "A"] + self.assertEqual(len(a_secs_2), 2) + for s1, s2 in zip(a_secs_1, a_secs_2): + self.assertEqual(s2["end16"] - s2["start16"], 2 * (s1["end16"] - s1["start16"])) + + root = ET.fromstring(web_api.export_musicxml(st2)) + for part in root.iter("part"): + num = den = None + for m in part.iter("measure"): + t = m.find("attributes/time") + if t is not None: + num, den = int(t.findtext("beats")), int(t.findtext("beat-type")) + total = sum(int(n.findtext("duration")) for n in m.iter("note") if n.find("chord") is None) + self.assertEqual(total, num * 16 // den, (part.get("id"), m.get("number"))) + + def test_noop_option_does_not_push_undo(self): + st0 = web_api.new_piece(801000) + for name, val in ( + ("intro_bars", "auto"), + ("square_repeat", 1), + ("mute_share", 0.0), + ("octave_share", None), + ("b_lead", "augmented"), + ("trailing_rest", st0["recipe"]["studio"]["options"]["trailing_rest"]), + ("octave_piece", composer.V8["octave_piece"]), + ("slide_max", composer.V8["slide_max"]), + ("mute_share", -0.1), + ): + st1 = web_api.option(st0, name, val) + self.assertEqual(st1["undo"], [], (name, val)) + self.assertEqual(st1["recipe"], st0["recipe"], (name, val)) + self.assertFalse(web_api.detail(st1)["can_undo"], (name, val)) + + st_changed = web_api.option(st0, "intro_bars", 8) + self.assertEqual(len(st_changed["undo"]), 1) + + st_same = web_api.option(st_changed, "intro_bars", 8) + self.assertEqual(len(st_same["undo"]), 1) + self.assertEqual(st_same["recipe"], st_changed["recipe"]) + + st_undone = web_api.undo(st_same) + self.assertEqual(st_undone["recipe"]["studio"]["options"]["intro_bars"], "auto") + self.assertEqual(st_undone["undo"], []) + + legacy_st = copy.deepcopy(st0) + for key in ("mute_share", "intro_bars", "square_repeat", "octave_share"): + legacy_st["recipe"]["studio"]["options"].pop(key, None) + legacy_after = web_api.option(legacy_st, "intro_bars", "auto") + self.assertEqual(legacy_after["undo"], []) + class TestReviewFixesPython(unittest.TestCase): def _load_check_site(self): diff --git a/composer-lab/web/app.js b/composer-lab/web/app.js index 31b5f33..c706308 100644 --- a/composer-lab/web/app.js +++ b/composer-lab/web/app.js @@ -1526,12 +1526,168 @@ const optCard = document.createElement("div"); optCard.className = "card"; const optH2 = document.createElement("h2"); - optH2.textContent = "Параметры (для следующих перегенераций)"; + optH2.textContent = "Параметры пьесы"; const oGrid = document.createElement("div"); oGrid.id = "optionsGrid"; oGrid.className = "options-grid"; + const advDetails = document.createElement("details"); + advDetails.className = "advanced-options"; + const advSummary = document.createElement("summary"); + advSummary.textContent = "Дополнительно"; + const advGrid = document.createElement("div"); + advGrid.id = "advancedGrid"; + advGrid.className = "options-grid"; + advDetails.appendChild(advSummary); + advDetails.appendChild(advGrid); const opts = d.options; + function addOptionHint(parent, text) { + const h = document.createElement("div"); + h.className = "option-hint"; + h.textContent = text; + parent.appendChild(h); + } + + function sendOption(name, value) { + return runMutation( + "option", + { name, value }, + d.id, + (snap) => ({ action: "option", value: { [name]: snap.detail.options[name] } }) + ); + } + + function addSliderControl(grid, name, label, min, max, step, hint) { + const wrap = document.createElement("div"); + wrap.className = "slider-row"; + const valText = document.createElement("span"); + valText.textContent = String(opts[name] ?? 0); + const head = document.createElement("div"); + head.className = "slider-head"; + const labelSpan = document.createElement("span"); + labelSpan.textContent = label; + head.appendChild(labelSpan); + head.appendChild(valText); + const inp = document.createElement("input"); + inp.type = "range"; + inp.dataset.option = name; + inp.min = String(min); + inp.max = String(max); + inp.step = String(step); + inp.value = String(opts[name] ?? 0); + inp.oninput = () => { + valText.textContent = inp.value; + }; + inp.onchange = () => { + const num = step === 1 ? parseInt(inp.value, 10) : parseFloat(inp.value); + sendOption(name, num); + }; + wrap.appendChild(head); + wrap.appendChild(inp); + if (hint) addOptionHint(wrap, hint); + grid.appendChild(wrap); + } + + addSliderControl( + oGrid, + "mute_share", + "Глухие ноты (доля ударов ритм-гитары)", + 0, + 1, + 0.05, + "Глушит долю ударов ритм-гитары в секциях A, A2, A3 и B; применяется сразу." + ); + + { + const wrap = document.createElement("div"); + wrap.className = "slider-row"; + const isAuto = opts.octave_share === null || opts.octave_share === undefined; + const valText = document.createElement("span"); + valText.textContent = isAuto ? "авто" : String(opts.octave_share); + const head = document.createElement("div"); + head.className = "slider-head"; + const lbl = document.createElement("span"); + lbl.textContent = "Октавные аккорды (доля тактов)"; + head.appendChild(lbl); + head.appendChild(valText); + const row = document.createElement("div"); + row.className = "row"; + const autoBtn = document.createElement("button"); + autoBtn.className = isAuto ? "active" : ""; + autoBtn.dataset.option = "octave_share"; + autoBtn.dataset.value = "auto"; + autoBtn.textContent = "Авто"; + const inp = document.createElement("input"); + inp.type = "range"; + inp.dataset.option = "octave_share"; + inp.min = "0"; + inp.max = "1"; + inp.step = "0.05"; + inp.value = isAuto ? "0.5" : String(opts.octave_share); + inp.className = isAuto ? "slider-dim" : ""; + inp.style.flex = "1 1 120px"; + autoBtn.onclick = () => sendOption("octave_share", isAuto ? parseFloat(inp.value) : null); + inp.oninput = () => { + inp.classList.remove("slider-dim"); + valText.textContent = inp.value; + }; + inp.onchange = () => sendOption("octave_share", parseFloat(inp.value)); + row.appendChild(autoBtn); + row.appendChild(inp); + wrap.appendChild(head); + wrap.appendChild(row); + addOptionHint(wrap, "Доля тактов A и A2 с октавами («Авто» — как в пьесе); применяется сразу."); + oGrid.appendChild(wrap); + } + + { + const box = document.createElement("div"); + const title = document.createElement("div"); + title.className = "piece-meta"; + title.style.marginBottom = "6px"; + title.textContent = "Длина вступления (тактов)"; + const row = document.createElement("div"); + row.className = "row"; + const cur = opts.intro_bars ?? "auto"; + for (const [val, txt] of [["auto", "Авто"], [1, "1"], [2, "2"], [4, "4"], [8, "8"]]) { + const b = document.createElement("button"); + b.className = cur === val ? "active" : ""; + b.dataset.option = "intro_bars"; + b.dataset.value = String(val); + b.textContent = txt; + b.onclick = () => sendOption("intro_bars", val); + row.appendChild(b); + } + box.appendChild(title); + box.appendChild(row); + addOptionHint(box, "Меняет число тактов вступления по аккордам A; применяется сразу."); + oGrid.appendChild(box); + } + + { + const box = document.createElement("div"); + const title = document.createElement("div"); + title.className = "piece-meta"; + title.style.marginBottom = "6px"; + title.textContent = "Повтор квадрата в куплетах"; + const row = document.createElement("div"); + row.className = "row"; + const cur = opts.square_repeat ?? 1; + for (const [val, txt] of [[1, "1× (4 такта)"], [2, "2× (8 тактов)"]]) { + const b = document.createElement("button"); + b.className = cur === val ? "active" : ""; + b.dataset.option = "square_repeat"; + b.dataset.value = String(val); + b.textContent = txt; + b.onclick = () => sendOption("square_repeat", val); + row.appendChild(b); + } + box.appendChild(title); + box.appendChild(row); + addOptionHint(box, "Повторяет 4-тактовый квадрат куплетов A и A2 дважды подряд; применяется сразу."); + oGrid.appendChild(box); + } + const bBox = document.createElement("div"); const bTitle = document.createElement("div"); bTitle.className = "piece-meta"; @@ -1547,13 +1703,7 @@ const b = document.createElement("button"); b.className = opts.b_lead === val ? "active" : ""; b.textContent = txt; - b.onclick = () => - runMutation( - "option", - { name: "b_lead", value: val }, - d.id, - (snap) => ({ action: "option", value: { b_lead: snap.detail.options.b_lead } }) - ); + b.onclick = () => sendOption("b_lead", val); bRow.appendChild(b); } bBox.appendChild(bTitle); @@ -1568,58 +1718,23 @@ const tBtn = document.createElement("button"); tBtn.className = opts.trailing_rest ? "active" : ""; tBtn.textContent = opts.trailing_rest ? "Вкл (есть пауза)" : "Выкл (--notail)"; - tBtn.onclick = () => - runMutation( - "option", - { name: "trailing_rest", value: !opts.trailing_rest }, - d.id, - (snap) => ({ action: "option", value: { trailing_rest: snap.detail.options.trailing_rest } }) - ); + tBtn.onclick = () => sendOption("trailing_rest", !opts.trailing_rest); tBox.appendChild(tTitle); tBox.appendChild(tBtn); oGrid.appendChild(tBox); for (const [name, label, min, max, step] of [ - ["octave_piece", "Доля октавных секций", 0, 1, 0.05], - ["octave_sixteenths", "Октавы шестнадцатыми", 0, 1, 0.05], - ["dead_notes", "Глухие ноты (dead notes)", 0, 1, 0.05], - ["slide_max", "Макс. слайд октав (лады)", 0, 12, 1], + ["octave_piece", "Вероятность октав при перегенерации ритма", 0, 1, 0.05], + ["octave_sixteenths", "Октавы шестнадцатыми (при перегенерации)", 0, 1, 0.05], + ["dead_notes", "Глухие перед акцентами в октавах (при перегенерации)", 0, 1, 0.05], + ["slide_max", "Макс. слайд октав в ладах (при перегенерации)", 0, 12, 1], ]) { - const wrap = document.createElement("div"); - wrap.className = "slider-row"; - const valText = document.createElement("span"); - valText.textContent = String(opts[name]); - const head = document.createElement("div"); - head.className = "slider-head"; - const labelSpan = document.createElement("span"); - labelSpan.textContent = label; - head.appendChild(labelSpan); - head.appendChild(valText); - const inp = document.createElement("input"); - inp.type = "range"; - inp.min = String(min); - inp.max = String(max); - inp.step = String(step); - inp.value = String(opts[name]); - inp.oninput = () => { - valText.textContent = inp.value; - }; - inp.onchange = () => { - const num = step === 1 ? parseInt(inp.value, 10) : parseFloat(inp.value); - runMutation( - "option", - { name, value: num }, - d.id, - (snap) => ({ action: "option", value: { [name]: snap.detail.options[name] } }) - ); - }; - wrap.appendChild(head); - wrap.appendChild(inp); - oGrid.appendChild(wrap); + addSliderControl(advGrid, name, label, min, max, step, null); } optCard.appendChild(optH2); optCard.appendChild(oGrid); + optCard.appendChild(advDetails); main.appendChild(optCard); } @@ -1682,6 +1797,12 @@ return; } const { result: snap, elapsedMs } = resp; + if (samePieceState(latestState, snap.state)) { + if (appState.currentId === pieceId && !appState.navPending) { + renderWorkspace(); + } + return; + } if (cmd === "reroll") { debugInfo.lastRerollMs = elapsedMs; } diff --git a/composer-lab/web/index.html b/composer-lab/web/index.html index 7619210..22ca8f9 100644 --- a/composer-lab/web/index.html +++ b/composer-lab/web/index.html @@ -289,6 +289,18 @@ min-width: 0; } .slider-head { display: flex; justify-content: space-between; color: var(--muted); gap: 8px; } + .option-hint { font-size: 0.78rem; color: var(--muted); margin-top: 2px; } + .slider-dim { opacity: 0.55; } + .advanced-options { margin-top: 14px; border-top: 1px solid var(--border); padding-top: 10px; } + .advanced-options summary { + cursor: pointer; + color: var(--muted); + font-size: 0.9rem; + font-weight: 600; + min-height: 44px; + display: flex; + align-items: center; + } input[type="range"] { width: 100%; min-height: 44px; cursor: pointer; } .empty { color: var(--muted); padding: 24px 0; text-align: center; } @media (max-width: 780px) { diff --git a/composer-lab/web/tests/harness.js b/composer-lab/web/tests/harness.js index 5965017..10124f4 100644 --- a/composer-lab/web/tests/harness.js +++ b/composer-lab/web/tests/harness.js @@ -36,6 +36,10 @@ function makeFakeState(seed = 801000, overrides = {}) { options: { b_lead: "augmented", trailing_rest: true, + mute_share: 0, + octave_share: null, + intro_bars: "auto", + square_repeat: 1, octave_piece: 0.25, octave_sixteenths: 0.3, dead_notes: 0.2, @@ -69,7 +73,8 @@ function buildDetailFromState(st, sectionLabels = {}) { for (const bar of rec.form || []) { if (!secsSeen.includes(bar.sec)) secsSeen.push(bar.sec); } - const sections = secsSeen.map((sec, idx) => { + let cursor = 0; + const sections = secsSeen.map((sec) => { const layers = []; if (sec === "A" || sec === "A2") { const k = `comp@${sec}`; @@ -90,10 +95,18 @@ function buildDetailFromState(st, sectionLabels = {}) { locked: locks.has(k), }); } + let dur = 2; + if (sec === "intro" && typeof opts.intro_bars === "number") { + dur = opts.intro_bars * 2; + } else if ((sec === "A" || sec === "A2") && opts.square_repeat === 2) { + dur = 4; + } + const start_sec = cursor; + cursor += dur; return { section: sec, - start_sec: idx * 2, - end_sec: idx * 2 + 2, + start_sec, + end_sec: cursor, label: sectionLabels[sec] || defaultLabels[sec] || sec, layers, }; @@ -105,7 +118,7 @@ function buildDetailFromState(st, sectionLabels = {}) { mode: rec.intent.mode, key: rec.intent.tonic, tempo: rec.intent.tempo, - length: Math.max(2, sections.length * 2), + length: Math.max(2, cursor), sections, whole_layers: [ { @@ -126,6 +139,10 @@ function buildDetailFromState(st, sectionLabels = {}) { options: { b_lead: opts.b_lead || "augmented", trailing_rest: opts.trailing_rest !== undefined ? opts.trailing_rest : true, + mute_share: opts.mute_share ?? 0, + octave_share: opts.octave_share !== undefined ? opts.octave_share : null, + intro_bars: opts.intro_bars ?? "auto", + square_repeat: opts.square_repeat ?? 1, octave_piece: opts.octave_piece ?? 0.25, octave_sixteenths: opts.octave_sixteenths ?? 0.3, dead_notes: opts.dead_notes ?? 0.2, @@ -596,6 +613,14 @@ function createAppHarness(options = {}) { const oldSt = deepClone(payload.state); const nextRec = deepClone(oldSt.recipe); nextRec.studio.options[payload.name] = payload.value; + if (JSON.stringify(nextRec) === JSON.stringify(oldSt.recipe)) { + const sameSt = { id: oldSt.id, recipe: oldSt.recipe, undo: [...(oldSt.undo || [])] }; + return { + state: sameSt, + detail: buildDetailFromState(sameSt, env.sectionLabels), + events: eventsForState ? eventsForState(sameSt) : defaultFakeEvents(sameSt), + }; + } const nextUndo = [...(oldSt.undo || []), deepClone(oldSt.recipe)].slice(-50); const nextSt = { id: oldSt.id, recipe: nextRec, undo: nextUndo }; return { diff --git a/composer-lab/web/tests/test_app.mjs b/composer-lab/web/tests/test_app.mjs index 7c6a03b..4ba80ba 100644 --- a/composer-lab/web/tests/test_app.mjs +++ b/composer-lab/web/tests/test_app.mjs @@ -357,3 +357,187 @@ test("Finding 11: worker.onerror rejects pending calls, clears pending map, and await env.flushAll(10); assert.equal(env.window.__studioDebug.ready, true, "retry worker ready must mark studio ready"); }); + +test("Studio controls send option immediately without reroll, refresh UI, and hide old doses under Дополнительно", async () => { + const env = await bootWithPiece(); + env.workerMessages.length = 0; + + const ws = env.document.getElementById("workspace"); + const adv = ws.querySelectorAll("details"); + assert.equal(adv.length, 1, "advanced doses must be inside a
element"); + const summary = adv[0].querySelectorAll("summary"); + assert.equal(summary.length, 1); + assert.equal(summary[0].textContent, "Дополнительно"); + for (const lbl of [ + "Вероятность октав при перегенерации ритма", + "Октавы шестнадцатыми (при перегенерации)", + "Глухие перед акцентами в октавах (при перегенерации)", + ]) { + assert.ok(adv[0].textContent.includes(lbl), `missing renamed advanced dose label: ${lbl}`); + } + + const hints = ws.querySelectorAll(".option-hint"); + assert.equal(hints.length, 4, "each of the 4 new controls must have a one-line Russian hint"); + for (const h of hints) { + assert.match(h.textContent, /применяется сразу/i); + } + + // 1. mute_share slider + const muteSlider = ws + .querySelectorAll("input") + .find((el) => el.dataset.option === "mute_share"); + assert.ok(muteSlider, "mute_share slider must exist"); + muteSlider.value = "0.6"; + muteSlider.onchange(); + await env.flushAll(15); + + // 2. octave_share slider then Авто button + const octSlider = env.document + .getElementById("workspace") + .querySelectorAll("input") + .find((el) => el.dataset.option === "octave_share"); + assert.ok(octSlider, "octave_share slider must exist"); + octSlider.value = "0.8"; + octSlider.onchange(); + await env.flushAll(15); + + const octAutoBtn = env.document + .getElementById("workspace") + .querySelectorAll("button") + .find((el) => el.dataset.option === "octave_share" && el.dataset.value === "auto"); + assert.ok(octAutoBtn, "octave_share auto button must exist"); + octAutoBtn.click(); + await env.flushAll(15); + + // 3. intro_bars = 8 + const intro8Btn = env.document + .getElementById("workspace") + .querySelectorAll("button") + .find((el) => el.dataset.option === "intro_bars" && el.dataset.value === "8"); + assert.ok(intro8Btn, "intro_bars=8 button must exist"); + intro8Btn.click(); + await env.flushAll(15); + + // 4. square_repeat = 2 + const rep2Btn = env.document + .getElementById("workspace") + .querySelectorAll("button") + .find((el) => el.dataset.option === "square_repeat" && el.dataset.value === "2"); + assert.ok(rep2Btn, "square_repeat=2 button must exist"); + rep2Btn.click(); + await env.flushAll(15); + + const calls = env.workerMessages.filter((m) => m.type === "call"); + assert.equal( + calls.filter((m) => m.cmd === "reroll").length, + 0, + "changing the four controls must not trigger reroll", + ); + const optCalls = calls.filter((m) => m.cmd === "option").map((m) => [m.payload.name, m.payload.value]); + assert.deepEqual(optCalls, [ + ["mute_share", 0.6], + ["octave_share", 0.8], + ["octave_share", null], + ["intro_bars", 8], + ["square_repeat", 2], + ]); + + const saved = env.indexedDB._pieces.get("piece_801000"); + assert.equal(saved.state.recipe.studio.options.mute_share, 0.6); + assert.equal(saved.state.recipe.studio.options.octave_share, null); + assert.equal(saved.state.recipe.studio.options.intro_bars, 8); + assert.equal(saved.state.recipe.studio.options.square_repeat, 2); + assert.match(env.document.getElementById("workspace").textContent, /24 с/); +}); + +test("Active Auto button switches to displayed manual value without wasting undo, and mute hint names A, A2, A3, B", async () => { + const env = await bootWithPiece(); + env.workerMessages.length = 0; + + const ws = env.document.getElementById("workspace"); + const hints = ws.querySelectorAll(".option-hint"); + assert.match(hints[0].textContent, /A,\s*A2,\s*A3\s+и\s+B/); + + const octAutoBtn1 = ws + .querySelectorAll("button") + .find((el) => el.dataset.option === "octave_share" && el.dataset.value === "auto"); + assert.ok(octAutoBtn1); + assert.equal(octAutoBtn1.classList.contains("active"), true); + octAutoBtn1.click(); + await env.flushAll(15); + + let saved = env.indexedDB._pieces.get("piece_801000"); + assert.equal(saved.state.recipe.studio.options.octave_share, 0.5); + assert.equal(saved.state.undo.length, 1); + + const octSlider2 = env.document + .getElementById("workspace") + .querySelectorAll("input") + .find((el) => el.dataset.option === "octave_share"); + assert.equal(octSlider2.classList.contains("slider-dim"), false); + + const octAutoBtn2 = env.document + .getElementById("workspace") + .querySelectorAll("button") + .find((el) => el.dataset.option === "octave_share" && el.dataset.value === "auto"); + assert.equal(octAutoBtn2.classList.contains("active"), false); + octAutoBtn2.click(); + await env.flushAll(15); + + saved = env.indexedDB._pieces.get("piece_801000"); + assert.equal(saved.state.recipe.studio.options.octave_share, null); + assert.equal(saved.state.undo.length, 2); + + const optCalls = env.workerMessages + .filter((m) => m.type === "call" && m.cmd === "option") + .map((m) => [m.payload.name, m.payload.value]); + assert.deepEqual(optCalls, [ + ["octave_share", 0.5], + ["octave_share", null], + ]); +}); + +test("Re-clicking already active options does not push undo or append option logs", async () => { + const env = await bootWithPiece(); + + const ws = env.document.getElementById("workspace"); + const introAuto = ws.querySelectorAll("button").find((el) => el.dataset.option === "intro_bars" && el.dataset.value === "auto"); + const sq1 = ws.querySelectorAll("button").find((el) => el.dataset.option === "square_repeat" && el.dataset.value === "1"); + const bLeadAug = ws.querySelectorAll("button").find((el) => el.textContent === "Удвоенно (как сейчас)"); + const muteSlider = ws.querySelectorAll("input").find((el) => el.dataset.option === "mute_share"); + assert.ok(introAuto && sq1 && bLeadAug && muteSlider); + + introAuto.click(); + sq1.click(); + bLeadAug.click(); + muteSlider.value = "0"; + muteSlider.onchange(); + await env.flushAll(20); + + let saved = env.indexedDB._pieces.get("piece_801000"); + assert.equal(saved.state.undo.length, 0); + assert.equal(env.document.getElementById("undoBtn").disabled, true); + assert.equal(env.indexedDB._logs.filter((l) => l.action === "option").length, 0); + + const intro8 = env.document + .getElementById("workspace") + .querySelectorAll("button") + .find((el) => el.dataset.option === "intro_bars" && el.dataset.value === "8"); + intro8.click(); + await env.flushAll(15); + + saved = env.indexedDB._pieces.get("piece_801000"); + assert.equal(saved.state.undo.length, 1); + assert.equal(env.indexedDB._logs.filter((l) => l.action === "option").length, 1); + + const intro8Again = env.document + .getElementById("workspace") + .querySelectorAll("button") + .find((el) => el.dataset.option === "intro_bars" && el.dataset.value === "8"); + intro8Again.click(); + await env.flushAll(15); + + saved = env.indexedDB._pieces.get("piece_801000"); + assert.equal(saved.state.undo.length, 1); + assert.equal(env.indexedDB._logs.filter((l) => l.action === "option").length, 1); +});