BeatScript Editor

#BeatScript, the bitwrap language

Beyond Swift. BeatScript is the bitwrap language: one small language of our own (no embedded Lua, Rhai
or JS) that is a full front end to djapp. A program is a few lines of text, or a whole track. Pattern
lines become Petri nets on the decks; every other line is a call on the control-language registry, so
anything djapp does a program can do. You evaluate the text (Cmd+Enter, btw eval), and the change lands
on the next bar: no restart, no gap, no glitch. A program with an error is refused whole, and the last
good one keeps playing.

The language is called BeatScript, and beatscript is its name wherever a name is syntax: the command line beatscript,
files and snippets .beatscript, the MIME type text/beatscript, the editors' language id. It was called btw until
BeatScript 2 ("Versions"). The desktop booth (djrust) still spells its command noun btw: it names a registry noun,
not the language, and these are real commands: the registry noun btw (live and livecode still work), do btw,
btw test, djctl btw eval, the MCP tool djapp_btw, the window btw.

This page is the whole reference. The language grew in two steps: the base (mini-notation, control lines, let def
repeat section arrange, evolve, saved and shared programs, and sets: programs of programs), and fourteen extensions written in one run
(arithmetic, time finer than a bar, degrees and Roman numerals, Euclidean rhythms and polymeter, seeded chance,
stack and then, typed ports, tempo curves, shapes and lfos, duck and mix, sing, assertions, the performed
tier, links to the ontology). Each extension has one short section below ("The language extensions") and a long note,
docs/beatscript/ext-<feature>.md, with its grammar, semantics, decisions and what is not done. docs/BEATSCRIPT-EXTENSIONS.md is
the contract of that run, kept as history.

Code: crates/djlive (lexer, parser, mini-notation, expansion, IR, compile, diff, the hot-reload runtime, share links;
pure, no I/O; one module for each extension: expr dur scale meter chance algebra ports mixmoves sing
tempo shape assertion perform linked, and set for sets), djhost::beatscript_env (the registry, the engine's instruments, the voices,
the controllers' bank and the cached ontology, handed to the checker), djhost::live_store (saved .beatscript objects, their
JSON-LD and performances), djhost::beatscript_render (a song as an arrangement for the offline renderer),
djhost::beatscript_test (btw test), djhost::beatscript_inputs (the controllers behind knob(3) and its kin),
djhost::ontology (the vocabulary), djapp/src/live_panel.rs (the window, the booth's side) and
djapp/src/control/live.rs (the btw verbs).

BeatScript
#! beatscript 2
tempo 126
key am

deck A: kick e(5,8) | snare ~ x ~ x | bass markov(am, 0.7) | hihat x*8 vel=60..90
deck B: harmony chord(am7) | arp arp(am7, up, 8)

every 16 bars: swap pairs with echo_out
on phrase: deck A: filter lp 12k -> 400 over 4 bars   # a build, every 8 bars
master: filter lp 2k -> 8k over 8 bars

Read it aloud: "deck A: kick, euclid five in eight; snare, rest hit rest hit; bass, markov in A minor,
density point seven. Every sixteen bars, swap pairs with an echo out. Master: filter low-pass two
kilohertz to eight kilohertz over eight bars."

#The rules in one screen

#Versions

A program starts with its version line:

BeatScript
#! beatscript 2
tempo 126
deck A: kick x ~ x ~ | hihat x*8

BeatScript 2 is the language that was called btw, renamed. Its meaning is the same line for line: every statement
of a BeatScript 2 program means what it meant before, and plays the same.

#Two halves: structure and engine

A program has two halves: its structure is the track's own source, and its engine calls ask the engine for what the text does not spell out.

structure: the track's own source engine: calls into the engine
tempo 126, key am, swing 0.1 seed(techno, 42).bass[17..24]: the beats generator, seeds v1, written out as text before lowering
deck A: kick x ~ x ~ | bass c2 ~ c2 ~ inst=fm-bass: parts, patterns, params master: filter lp 400 -> 8k over 8 bars, deck A: level 0.8, crossfader 0.5: the mixer and the FX
let, def, repeat, stack, then, evolve move echo_out on B, swap pairs with filter_exit: the booth's moves
section drop 16 bars { }, arrange, arrange { } with ~ and @ do <noun> <verb> ... and its sugar (freeze, vocoder, the wheel): the control registry
doc comments: the # lines above a section, let, def or arrange sing "words" on melody, duck, mix: the voice and the mix
arrange from template(rondo, @hands_up): a template is BeatScript with slots load, queue, play, stop, sync, mute: the decks' transport
section hook from <cid>.drop, <cid>.drop.bass, import: another program's source, by its hash gen@2 techno seed=42 section=drop part=bass: the seeded generator called with its own parameters, the result pinned by its CID ("Call the generator")
a form's roles, template(rondo, @hands_up, episodes=template(passacaglia, ground=ode_to_joy)): themes, notes, other programs' parts and sections, other forms, written in as text (a seed in a role stays an engine call) coming: macro riser over 8 bars on A, the DJ macro catalogue by name (designed: docs/beatscript/ext-control.md)
use theme ode_to_joy as tune, use <cid>.drop as hook, use template(passacaglia).ground as ground: a name for a source, on a line of its own, written out where the name is used ("Name a source: use") use gen@2 house seed=7 section=drop part=bass as walk: a name for an engine call, still pinned and resolved as one
control: move echo_out on B, at bar 12: control: swap pairs with filter_exit: the control deck, beside deck A:, deck B: and master:, holds only engine calls, sequenced by sections like any deck ("The control deck")

One program that uses both:

BeatScript
#! beatscript 2
tempo 126
key am

let groove = x ~ x ~ x ~ x [x x]                          # structure: a let
section build 8 bars {                                     # structure: a section
  deck A: kick groove | bass seed(techno, 42).bass[17..24] inst=fm-bass   # parts; seed(): the generator, pinned
  deck B: arp arp(am7, up, 8)
  master: filter lp 400 -> 8k over 8 bars                 # engine: the master's filter, a ramp
}
section drop 8 bars {
  deck A: kick x x x x | bass seed(techno, 42).bass[17..24] inst=fm-bass
  deck B: arp arp(am7, up, 8)
}
on phrase: move echo_out on B                              # engine: a move of the booth
arrange build drop

#What a reference resolves to

A program's CID is of its text as written: the recipe, with its references in it. check (and listen, and the MCP tools
generate and genre_template) also says what the recipe makes:

listen marks each part a reference made with from (its call, kind, resolved CID, place and the sections it made it in; a
use line's also its name), and a gen call that was fitted to the program's key or tempo says so in its notes, in check's
words.

A program with references that is stored on beatscript.app is stored with its expansion beside it: the program written out
(its expanded_cid), canonical, as a program of its own under the same storage gate, with the recipe's licence, credits and name.
/p/<expanded_cid> loads it and it plays as the recipe does. The two name each other (the recipe's meta expands_to, written once
the expansion is stored; the expansion's expanded_from, and its based_on: each reference the recipe wrote out into it, with its
pin, never the expansion itself), and so do their JSON-LD (expandsTo; expandedFrom and isBasedOn) and lineage. First write
wins: an expansion someone stored first is the one, with the rights they gave it. An expansion is a copy, so it is stored only
when every program it copies is CC0 or the recipe author's own under the recipe's licence, and when it is within a program's size
and the store's room; else the answer says why. The answers say expanded_cid, and expanded_url and expansion_license, or
expansion_note (docs/beatscript/ext-template.md, "The stored expansion").

#Grammar (EBNF)

The grammar is crates/djlive/grammar.ebnf, the language's one source of
truth. The block below is generated from it (do not edit it here), and so is the Grammar page,
which draws every production as a railroad diagram. crates/djlive/tests/grammar.rs holds it to the parser both ways:
every example program is a sentence of it, and every sentence it writes is a program the parser reads.

{ x } zero or more, [ x ] optional, ( a | b ) choice, "x" a literal word or mark, (* ... *) a comment; an
UPPER-CASE name that is no production is a kind of token (below). Whitespace separates tokens and is otherwise free; a
line end ends a statement (except before |).

ebnf
(* == Programs and lines == *)
program     = { line } ;
line        = [ statement ] NEWLINE ;                         (* a comment is "#" to the end of the line; it is not a token *)
statement   = setting | headed | let | def | repeat | section | arrange | arrange_block | start | launch | import | end | loop
            | evolve | wire | assert | sample | cue | use | set | station ;

(* == Settings == *)
setting     = "tempo" tempo
            | "swing" arith
            | "key" KEY ;                                     (* a setting reads no input: it is the program's own *)
tempo       = arith [ "->" arith "over" dur [ shape ] ] ;     (* tempo 126   tempo 100 -> 130 over 8 bars exp *)

(* == Lines: when, where, what == *)
headed      = "deck" deck ":" parts [ guard ]
            | "at" pos [ "for" dur ] ":" "deck" deck ":" parts [ guard ]   (* a placed part, in a section *)
            | [ timing ":" ] "row" ":" "clip" NAME { cparam } [ cguard ]   (* an audio placement on the loop row *)
            | [ timing ":" ] [ target ":" ] control [ cguard ]
            | [ timing ":" ] "control" ":" ( engine | do | duck | mix ) [ cguard ]   (* the control deck *)
            | [ timing ":" ] ( invoke | duck | mix ) [ cguard ] ;   (* a def's call, a duck and a mix name their decks themselves *)
timing      = when [ "for" dur ] | "for" dur ;
cparam      = "crop" "=" arith ".." arith                     (* source beats: crop=32..64 *)
            | "gain" "=" arith
            | "fade" "=" ( "off" | "beat" | "bar" | time )
            | "route" "=" "vocoder" [ ":" INT ] ;             (* the vocoder's modulator; vocoder:2 .. 4 *)
when        = "every" dur [ "from" ( arith | pos ) ]          (* every 16 bars   every 2 beats   every 4 bars from 8 *)
            | "on" "phrase"                                   (* every 8 bars: a phrase *)
            | "on" "next" "bar"
            | "on" "next" "phrase" [ "8" | "16" | "32" ]
            | "at" pos                                        (* once, on that place of the program *)
            | "after" NAME                                    (* once, where that section ends *)
            | "before" NAME dur ;                             (* once, that long ahead of that section *)
dur         = arith ( "bar" | "bars" | "beat" | "beats" ) ;   (* 4 bars   1/2 bar   2 beats *)
pos         = "bar" arith [ "beat" arith ] ;                  (* bar 16   bar 16 beat 3   a beat is 0 to 3 *)
guard       = "when" expr ;                                   (* kept where it holds *)
cguard      = "when" cexpr ;                                  (* a control line's guard may read an input *)
target      = "deck" deck | "master" ;
deck        = "A" | "B" | PARAM ;                              (* PARAM: in a def body, filled in when it is called *)
control     = action | engine | do | sing ;

(* == Parts == *)
parts       = pitem { "|" pitem } ;                           (* only after "deck X:" and with no time word *)
pitem       = part                                            (* each item between `|` has a part in it *)
            | "stack" "(" pargs ")"                           (* over parts: `stack` is `|` *)
            | "then" "(" pargs ")" ;                          (* over parts: the per-bar alternation <p q> *)
pargs       = { pexpr "," } pitem { "," pexpr } ;
pexpr       = pitem | "silence" ;                             (* silence: the unit of both *)
part        = role [ "/" INT ] pattern { param }              (* hihat/12 x x ~ x : a cycle of 12 sixteenths *)
            | role ref { param } ;                            (* bass seed(techno, 42)[17..24]: a generated part's bars; bass <cid>.drop: a stored program's *)
role        = "kick" | "snare" | "hihat" | "clap"             (* drum parts: a hit plays the drum's note *)
            | "bass" | "melody" | "harmony" | "arp" ;         (* tonal parts: a hit plays the key's root *)
param       = pname "=" pvalue                                (* vel=70..100  oct=2  len=3  inst=sub-bass  glide=60 *)
            | "voice-lead" [ "=" ( "on" | "off" ) ] ;         (* a switch, on when it is bare *)
pname       = "vel" | "oct" | "len" | "inst" | "seed" | "kit" | "sound" | "route"   (* velocity, octave, length, voice, its generators' seed, a drum kit, a sound, where it plays *)
            | "glide" | "decay" | "pitch-drop"                (* tonal, an 808: glide= decay= ms, pitch-drop= 1 to 24 semitones *)
            | "cutoff" | "res" | "env" | "accent" | "drive" ; (* the acid voice's knobs: cutoff= Hz 20 to 12000, the rest 0 to 100; not reserved words *)
pvalue      = arith [ ".." arith ] | WORD | PARAM ;           (* a number, a range drawn per hit, a name; a $name in a body *)

(* == Mini-notation: the rhythm of a part == *)
pattern     = term { term } ;
term        = atom [ mark ] [ "*" ( INT | "(" arith ")" ) ] { "?" [ prob ] } [ "~" INT ] ;   (* x*4  c2!  e2^  x:3  x*8?0.7 *)
                                                              (* sugar: x? is x?0.5, c2~3 is c2 ~ ~ *)
mark        = ( "!" | GHOST ) [ "^" ] [ "&" ] [ RATCHET ] | "^" [ "!" | GHOST ] [ "&" ] [ RATCHET ]
            | "&" [ RATCHET ] | RATCHET ;                     (* accent ghost slide flam ratchet, any order *)
atom        = "x"                                             (* a hit *)
            | "~"                                             (* a rest *)
            | NOTE                                            (* c3  f#2  bb4 *)
            | INT                                             (* a scale degree of the key: 1 3 5 *)
            | "(" arith ")"                                   (* a degree computed: ($i + 1) *)
            | degrees                                         (* deg(1 b3 5' ~) *)
            | ROMAN [ "/" INT ]                               (* i  VI  V7/7: a chord of the key; /3 /5 /7 an inversion *)
            | PARAM                                           (* a def's parameter: $chords *)
            | "[" pattern { "," pattern } "]"                 (* a group: squeezed into one slot; commas stack *)
            | "<" pattern ">"                                 (* alternation: one term per cycle *)
            | choose                                          (* choose [a b c] weights 3 1 1 *)
            | call
            | NAME ;                                          (* a let pattern's name *)
call        = NAME "(" [ arg { "," arg } ] ")" ;              (* e(5,8)  markov(0.6, shift=2)  arp(am7, up)  chord(am)  maybe(p, 0.5) *)
arg         = arith | KEY | CHORD | ROMAN [ "/" INT ] | NAME | NAME "=" ( arith | WORD ) | "[" pattern "]" | degrees | call | PARAM ;
                                                              (* a chord of chord() and arp(): a symbol (am7) or a numeral (V7  bVII  V7/7), the numeral read in the key in force *)

(* == Degrees, Roman numerals, chance == *)
degrees     = "deg" "(" dstack ")" ;                          (* one slot, its terms squeezed into it like [..] *)
dstack      = dseq { "," dseq } ;
dseq        = dterm { dterm } ;
dterm       = dleaf [ mark ] [ "*" INT ] | "~" | "x" | "[" dstack "]" | "<" dseq ">" | "(" ( dterm | arith ) ")" ;
dleaf       = ( INT | SDEG ) { "'" } { "," } ;                (* 5' an octave up, 1, down; b3 flat, #4 sharp *)
prob        = NUMBER | "(" arith ")" ;                        (* 0 to 1, or a percent: ?0.3  ?30%  ?(1 / 4) *)
choose      = "choose" "[" pattern "]" "weights" weight { weight } [ "seed=" INT ] ;   (* one weight for each option *)
weight      = NUMBER | "(" arith ")" ;

(* == Control: what the mix does == *)
action      = "filter" ( "lp" | "hp" ) change                 (* hertz: 20 .. 20k *)
            | "filter" ( "off" | "open" )
            | ( "delay" | "reverb" | "crush" | "drive" | "resonance" ) change   (* 0 .. 1: how much *)
            | ( "level" | "low" | "mid" | "high" ) change     (* deck X: / master: level *)
            | "load" SPEC                                     (* deck X: *)
            | "play" | "stop" | "sync" | "mute" | "unmute"
            | ( "mute" | "unmute" | "solo" ) ( STEM | role )     (* deck X: a stem (solo mutes the other three), or one part by its role [booth] *)
            | "loop" ( arith "beats" | "off" )                  (* deck X: a slip loop, `for` lets go [booth] *)
            | "jump" ( arith ( "beats" | "bars" ) | NAME "." NAME ) ;   (* deck X: a beat jump, back when negative; or to a cue point [booth] *)
STEM        = "drums" | "bass" | "vocals" | "other" ;          (* a net deck's: its drum roles, bass, the melody (the lead), the rest *)
engine      = "crossfader" change                             (* no target, or control: *)
            | "tempo" tempo                                   (* at bar 16: tempo 128 -> 140 over 4 bars *)
            | "swap" "pairs" [ "with" MOVE ]                  (* the booth's: the desktop app plays these *)
            | "move" MOVE "on" deck [ span ]
            | "load" "pair" SPEC [ "group" INT ]
            | "queue" ( "play" | "pause" | "stop" | "next" | "loop" | "jump" INT | "add" WORD )
            | MACRO NAME ( "on" deck [ span ] | span "on" deck ) ;   (* macro riser on A over 8 bars: the DJ macro catalogue, by id; MACRO is macro or macro@1 *)
change      = value                                           (* a plain value *)
            | value "->" value span [ shape ]                 (* a ramp: 2k -> 8k over 8 bars exp *)
            | lfo ;                                           (* a value that keeps moving *)
span        = "over" dur ;
value       = carith ;                                        (* a control's value may read inputs: 200 + knob(3) * 7800 *)
MOVE        = "filter_exit" | "echo_out" | "loop_roll" | "bass_swap" | "phrase_sync" | "vocoder_handoff" ;
SPEC        = NAME ":" INT | NAME ;                           (* dnb:2602  acid-bass *)
do          = ( "do" WORD | SUGAR ) [ WORD ] { STRING } { NAME "=" doval } [ span [ shape ] ] ;   (* the control registry: noun, verb; SUGAR: a noun said with no `do` (vocoder, freeze, wheel ...) *)
doval       = arith [ "->" arith ] | WORD | STRING | "[" [ doval { "," doval } ] "]" | lfo ;

(* == Shapes and lfo == *)
shape       = "linear" | "exp" | "log" | "s-curve" | "step" INT ;
lfo         = "lfo" wave dur { "depth=" value | "center=" value | "phase=" NUMBER } [ span ] ;   (* lfo sine 2 bars center=3k depth=1k *)
wave        = "sine" | "tri" | "square" | "saw" ;

(* == Arithmetic and guards == *)
arith       = sum ;                                           (* worked out once, when the program is read, over exact rationals *)
sum         = product { ( "+" | "-" ) product } ;
product     = unary { ( "*" | "/" | "%" ) unary } ;           (* "/" is exact; "%" is Euclidean *)
unary       = [ "-" ] primary ;
primary     = NUMBER | PARAM | "(" arith ")" | ( "min" | "max" ) "(" arith { "," arith } ")" ;
carith      = csum ;                                          (* arithmetic that may read inputs: only in a control *)
csum        = cproduct { ( "+" | "-" ) cproduct } ;
cproduct    = cunary { ( "*" | "/" | "%" ) cunary } ;
cunary      = [ "-" ] cprimary ;
cprimary    = NUMBER | PARAM | "(" carith ")" | ( "min" | "max" ) "(" carith { "," carith } ")" | input ;
expr        = or ;                                            (* a guard: kept when it is true *)
or          = and { "or" and } ;
and         = not { "and" not } ;
not         = [ "not" ] compare ;
compare     = operand [ cmp operand ] ;                       (* words compare with == and != only *)
operand     = sum | WORD ;
cexpr       = cor ;                                           (* a control line's guard *)
cor         = cand { "or" cand } ;
cand        = cnot { "and" cnot } ;
cnot        = [ "not" ] ccompare ;
ccompare    = coperand [ cmp coperand ] ;
coperand    = csum | WORD ;
cmp         = "==" | "!=" | "<" | "<=" | ">" | ">=" ;
input       = "knob" "(" INT ")" | "pad" "(" INT ")" | "fader" "(" deck ")"   (* performed: only in a control value or guard *)
            | "held" "(" "key" ")" | "held" "(" PITCH ")" ;    (* PITCH: a note with its octave, c4 *)

(* == Structure: lets, defs, sections, the arrangement == *)
let         = "let" NAME "=" ( sexpr | arith | ref | TOKEN { TOKEN } ) ;   (* one token is a value; more tokens are a pattern *)
def         = "def" NAME "(" [ NAME { "," NAME } ] ")"
              [ "in" ":" type { "," type } ] [ "out" ":" type { "," type } ]
              "{" { def_line } "}" ;                          (* $NAME inside, filled in when it is called *)
def_line    = [ statement | emit ] NEWLINE ;                  (* a def's body line; `emit` says what an out port carries *)
invoke      = NAME "(" [ tokens { "," tokens } ] ")" ;        (* a def's call *)
tokens      = TOKEN { TOKEN } ;
repeat      = "repeat" INT [ "every" INT "bars" ] "{" { body_line } "}" ;   (* the count is written out, 1 to 64 *)
body_line   = [ statement ] NEWLINE ;                         (* a repeat's body line: $i is the pass, 0 up *)
section     = "section" NAME INT "bars" "{" { line } "}"     (* 1 to 256 bars; a `key` may open the body *)
            | "section" NAME "from" ref ;                     (* section intro from seed(techno, 42)[1..8]   section hook from <cid>.drop *)
arrange     = "arrange" sexpr { sexpr }
            | "arrange" NAME ":" sexpr { sexpr } [ arr_end ]   (* with a NAME it is one of several arrangements *)
            | "arrange" "from" ( seed | template )            (* the whole of a generated track: arrange from seed(techno, 42), or of a phrase: arrange from template(deep-house, @tempest_such_stuff) *)
            | "arrange" "from" gen ;                          (* the whole program a generator call prints: arrange from gen@2 techno seed=42 *)
arr_end     = "then" NAME | "loop" [ INT ] | "end" ;           (* only after a NAME: see "Several arrangements" *)
start       = "start" NAME ;                                  (* the named arrangement that plays first; default the first written *)
launch      = "launch" NAME "on" "pad" "(" INT ")" [ "next" ( "bar" | "phrase" [ "8" | "16" | "32" ] ) ] ;   (* a hit of the pad brings the scene, a section or an arrangement, in on that bar line: 8 bars by default *)
sexpr       = NAME                                            (* a section, or a let that names a composition *)
            | "silence"                                       (* the empty section *)
            | "stack" "(" sexpr { "," sexpr } ")"             (* at the same time *)
            | "then" "(" sexpr { "," sexpr } ")" ;            (* one after another *)
end         = "end" [ "at" "bar" INT | "after" NAME ] ;       (* a song ends after its last section by default *)
loop        = "loop" ;                                        (* a song starts again at its end *)

(* == Arrange mutations == *)
arrange_block = "arrange" "{" { arr_gap } NAME { arr_gap | NAME } "}" [ block_end ]   (* at least one section; see "Arrange mutations" *)
            | "arrange" NAME ":" "{" { arr_gap } NAME { arr_gap | NAME } "}" [ arr_end ] ;   (* a named arrangement with mutations *)
arr_gap     = NEWLINE | "," | mutation NEWLINE ;               (* a mutation runs to the end of its line *)
mutation    = ( "~" | "@" ) [ INT ] ( switch | mut_target mut_op { "|" mut_op } { "," mut_target mut_op { "|" mut_op } } ) ;   (* ~ from here on, @ the next section only; ~3: every 3rd pass *)
switch      = "control" [ NAME ] ( "on" | "off" ) ;           (* the control deck's lines fire or not: all of them, or one call's (~ control freeze off); a line of its own *)
mut_target  = GLOB | NAME ;                                   (* a let pattern, or a glob: acid_* *)
mut_op      = NAME { NUMBER | "-" NUMBER | NAME } ;           (* rot 2  thin 0.1  oct -1  morph b 0.5  jux rev: the operators of "Arrange mutations" *)
block_end   = "end" | "loop" | "loop" INT [ "then" { NAME } "end" ] ;   (* default end; loop N: 1 to 256 passes, then a coda *)

(* == Start from a seed == *)
ref         = seed | gen | stored ;                           (* music from elsewhere, written out as BeatScript before the program is read *)
seed        = SEED "(" NAME "," INT [ "," structure ] ")" [ "." role ] [ "[" INT [ ".." INT ] "]" ] ;   (* a track of the beats generator: genre, seed; a part, bars from 1; SEED is seed (seeds v1) or seed@2 (v2: with its genre's swing) *)
stored      = CID [ "." NAME ] [ "." role ] ;                 (* a saved program's section or part, by its CID: <cid>.drop  <cid>.drop.bass; a bare <cid> is a program with no sections [host] *)
gen         = GEN NAME "seed" "=" ( INT | NAME ) { gen_param } ;   (* gen@2 techno seed=42 section=drop part=bass: the seeded generator, called; GEN is gen@2 or a bare gen [host] *)
gen_param   = "bpm" "=" NUMBER | "key" "=" KEY | "length" "=" ( "short" | "standard" | "long" ) | "section" "=" NAME | "part" "=" role ;
structure   = "standard" | "loop" | "minimal" | "extended" ;  (* the generator's song structures; standard is the default *)

(* == Phrase templates == *)
template    = "template" "(" NAME "," ( PHRASE | STRING | NAME ) { "," binding } ")" ;   (* a template's name and a phrase, a phrasebook id or words in quotes (NAME: one a `use phrase` line named): the phrase is the vocal line of a track; then a form's roles *)
binding     = NAME [ "." role ] "=" ( source | [ "-" ] INT ) ;   (* a role of the form and what fills it: ground=gen@1 dubstep seed=54876 part=bass; one part of a seed role: a.bass=[d2 ~ a1 ~]; a form's number: delay=6 interval=-12 *)
source      = gen | NAME | notes | form | stored | track ;    (* an engine call; a public-domain theme by id (ode_to_joy); notes; another template, or one section of it; a stored program's part or sections; a stored set's track *)
notes       = "[" pattern "]" | "<" "[" pattern "]" { "[" pattern "]" } ">" ;   (* a bar, or bars one after another *)
form        = "template" "(" NAME { "," binding } ")" [ "." NAME [ "." role ] ] ;   (* a form inside another takes no phrase: forms nest 3 deep; .both is one of its sections, .both.arp that section's part *)
track       = CID "." NAME [ "." NAME ] [ "." role ] ;        (* a stored set's track by number: <cid>.track2, its section <cid>.track2.drop, its part <cid>.track2.drop.bass [host] *)

(* == Evolving == *)
evolve      = "evolve" "every" INT "bars" "{" { NEWLINE } { rule NEWLINE { NEWLINE } } [ bound NEWLINE { NEWLINE } ] "}" ;   (* a rule a line; the bound last *)
rule        = ( role | "deck" deck ) ":" op { "|" op } [ "when" "gen" [ "%" INT ] cmp INT ] ;
op          = ( "rotate" | "transpose" | "octave" | "invert" | "reverse" | "thin" | "fill" | "slow" | "fast" ) { NUMBER | "<" NUMBER { NUMBER } ">" } [ "seed=" INT ] ;   (* seed= on thin and fill *)
bound       = "stop" "when" "gen" ( "==" | ">=" | ">" ) INT | "for" INT "gens" ;

(* == Typed ports == *)
type        = "chords" | "key" | "bass" | "melody" | "drums" | "rhythm" | "bars" | "tempo" | "pattern" ;
emit        = "emit" [ type | "out" ] tokens ;                (* a line of a def body: what an out port carries *)
wire        = "wire" NAME "." port "->" NAME "." port ;       (* at the top: wire changes.out -> walker.chords *)
port        = type | "in" | "out" ;

(* == Mix moves and sung lyrics == *)
duck        = "duck" deck "under" deck "." role db { "attack=" time | "release=" time } ;
mix         = "mix" "{" { NEWLINE } mixitem { ( "," | NEWLINE ) { NEWLINE } mixitem } { NEWLINE } "}" ;   (* in a section: put back where the section ends *)
mixitem     = deck "level" arith | deck "eq" band arith [ "db" ] | "master" "level" arith | deck "pan" arith ;
band        = "low" | "mid" | "high" ;
db          = DECIMAL "db" ;                                  (* glued: 6db *)
time        = DECIMAL ( "ms" | "s" ) ;                        (* glued: 5ms *)
sing        = "sing" ( lyric | PHRASE | NAME ) "on" role { "bars=" INT | "key=" KEY | "voice=" NAME } ;   (* a tonal role; PHRASE: a phrasebook id, @hands_up; NAME: a phrase a `use phrase` line named *)
lyric       = STRING ;   (* its text is lyric_text; docs/beatscript/phonemes.md *)
lyric_text  = { TEXT | "/" SPACE | escape } [ "/" { TEXT } ] ;   (* "/" and a space is a phrase break; "/" and a phoneme opens an escape, to the next "/" (with none, a break too); a word touching "=" before an escape is its label, kept and not sung: jingle=/j ii ng g uh l/ *)
escape      = "/" PHONES "/" ;   (* PHONES (beatscript-v1): aa ae uh aw eh er ii ee uu oo ay ie oy ow oh p b t d k g f v s z sh zh th dh h m n ng l r w y ch j, "_" a rest, "-" cuts a word, ":" holds a vowel one more note, "!" accents it *)

(* == Assertions == *)
assert      = "assert" ( "ends"
                       | "period" [ "(" NAME ")" ] cmp INT
                       | "length" ( ( "==" | "!=" ) clock [ "±" clock ] | ( "<" | "<=" | ">" | ">=" ) clock )
                       | "level" leveldeck cmp levelexpr [ "in" NAME ]
                       | "key" ( "==" | "!=" ) KEY [ "in" NAME ]
                       | "never" subject ( "beside" | "during" ) subject [ "in" NAME ]   (* assert never A.snare beside A.snare   assert never B during sing: refused where it is false *)
                       | subject "ends" "on" INT [ "in" NAME ] ) ;                        (* assert bass ends on 1: the lowest note of its last onset is that degree of the key *)
subject     = "sing" | ldeck | [ ldeck "." ] role ;                                  (* sing: the vocal; a deck; A.snare; bass on both decks *)
clock       = DECIMAL "m" [ DECIMAL "s" ] | DECIMAL "s" | DECIMAL "ms" ;   (* 3m30s  90s  500ms *)
leveldeck   = { lfactor lop } ldeck { lop lfactor } ;         (* a level read: it names a deck *)
lop         = "+" | "-" | "*" | "/" ;
ldeck       = "A" | "B" | "master" ;
levelexpr   = lterm { ( "+" | "-" ) lterm } ;                 (* arithmetic over the words A, B and master: their levels *)
lterm       = lfactor { ( "*" | "/" ) lfactor } ;
lfactor     = NUMBER | ldeck | "(" levelexpr ")" ;

(* == Sets, samples, imports == *)
set         = "set" "{" { NEWLINE } { ( set_play | set_mix | set_next ) NEWLINE { NEWLINE } } "}" ;   (* programs of programs: an item a line *)
set_play    = "play" ( NAME | STRING | gen ) [ "until" until_when ] ;   (* a saved program, its CID in the canonical text, or a generator call [host] *)
set_next    = "next" step [ "until" until_when ] ;            (* the track before it, a generator call, with its seed stepped [host] *)
until_when  = TIME | "bar" INT | NAME | "after" NAME ;        (* a time, a bar of the track, a section's start or end *)
set_mix     = "mix" INT ( "bar" | "bars" ) "with" TRANSITION [ "," "tempo" NUMBER "->" NUMBER ] ;
TIME        = DECIMAL UNIT { DECIMAL UNIT } ;                 (* units glued: 20m  90s  1h  3m30s *)
TRANSITION  = "crossfade" | "filter_exit" | "echo_out" | "cut" ;

(* == Radio: stations == *)
station     = "station" "{" { NEWLINE } { station_line NEWLINE { NEWLINE } } "}" ;   (* endless and deterministic: position N is always the same track [host] *)
station_line = "from" gen | "next" step | "forms" NAME { NAME } ;   (* the first track's call; the step from a track to the next; the forms in turn *)
step        = "seed" "=" ( "+" INT | "~" ) ;                 (* seed=+1 counts on; seed=~ draws from a hash of the track before's CID *)
import      = "import" ( NAME | STRING ) ;                    (* a snippet's name in quotes, or its CID [host] *)
sample      = "sample" NAME "from" STRING [ "license" license ] [ "else" NAME ]
            | "loop" STRING "as" NAME [ "else" NAME ] ;       (* restricted sounds: a local file, an Apple Loop by its hash *)
license     = "cc0" | "cc-by" | "all-rights-reserved" | "restricted-private" ;
cue         = "cue" NAME "." NAME "at" pos ;                   (* cue tune.drop at bar 32 beat 2: a named place in a sample [booth] *)
use         = "use" "restricted"                                (* the program is private: it may use restricted assets *)
            | "use" use_source "as" NAME ;                        (* a name for a source, written out where it is used (docs/beatscript/ext-roles.md) *)
use_source  = stored                                            (* <cid>.drop: a section; <cid>.drop.bass: a line; <cid>: a source for a role *)
            | gen                                               (* gen@2 techno seed=42 section=drop, part=bass: a section or a line; with neither, a source for a role *)
            | "template" "(" NAME { "," binding } ")" [ "." NAME ]   (* template(passacaglia, ground=...): a form, for a role; .ground: a canned section of it *)
            | template "." NAME                                 (* template(deep-house, @tempest_such_stuff).night: a canned section, sung with that phrase *)
            | "theme" NAME                                      (* a theme of the public-domain library: a line, in the program's key *)
            | "phrase" PHRASE                                   (* a phrasebook line: a phrase, for sing and template *)
            | GENRE NAME "." NAME ;                             (* genre@1 techno.drop: a section of a genre template, frozen *)

NAME is a lower-case word (letters, digits, _, and - between letters), WORD any word. INT is a whole number
(arithmetic that comes to one is fine: repeat 2 + 1); NUMBER also takes a fraction and the k / % marks, and
DECIMAL is a number with no mark, before a glued unit (UNIT: 6db, 5ms, 2s, 3m30s, 1h30m; hz after a
filter's cutoff, filter lp 300hz, is the number and nothing else; the hours of 1h are read only after a set's
until). NOTE, PITCH (a note with its octave), KEY, CHORD and ROMAN are pitch words read as one token
(f#2, c4, d:dorian, am7, ii°); SDEG a written degree in deg( ) (b3, #4); PARAM a def's or a
repeat's $name; SUGAR a control noun said without do; STRING a double-quoted string; TOKEN any token; GLOB a
name with * in it; CID a saved program's id; SEED seed or seed@2; GHOST a ghost's . and
RATCHET a ratchet's :N (x. x:3). ± may be written +- after
a unit (3m30s +- 5s). In a lyric, PHONES is an escape's text:
aa ae uh aw eh er ii ee uu oo ay ie oy ow oh p b t d k g f v s z sh zh th dh h m n ng l r w y ch j, - cuts a word, _ rests,
: holds a vowel, ! accents it; / and a space: a phrase break. A phrase's NAME is one use phrase @id as NAME gave;
use theme ode_to_joy as tune names a theme ("Name a source").

Some marks must touch the token before them, because a space would change what they mean: hihat/12, x?0.3,
A.kick, 6db 120ms 3m30s, e2! c2^ x. x& x:3, the octave marks of deg( ) (5' 1,), and the
two-mark comparisons == != <= >=. A space where they must touch is an error that says so. Everywhere else
whitespace is free.
% is the percent mark when it follows a digit with no space (50%) and the modulo operator otherwise: write
$i % 4 with spaces.

The header lines of a .beatscript file are comments to the language, all but the version line, and have a grammar of
their own (F14):

text
#! beatscript 2                               the version line ("Versions"): BeatScript 2; none, or #! btw 1, is BeatScript 1
#! genre: techno                              one genre of the BeatScript ontology: a name, genre:techno, bw:Techno or an IRI
#! tags: acid, four on floor, drop            terms of it, by local name, label or IRI

The productions were read against the parser (where a long note and the parser disagreed, the parser won), and the
examples of the feature sections below are lines of the programs in examples/beatscript/, every one of which
crates/djlive/tests/examples_beatscript.rs compiles.

#Which target takes which action

action no target deck A: / deck B: master: control:
a part line (kick x ~ x ~) — yes (a time word only as at bar N [for M bars]:, inside a section: a placed part) — —
swap pairs, move, load pair, queue, crossfader yes — — yes
load SPEC, play, stop, sync, mute, unmute — yes — —
mute STEM, unmute STEM, solo STEM, loop, jump (the DJ tier) — yes — —
filter, delay, reverb, crush, resonance — yes (that deck's insert) yes (the Master's) —
drive — yes (that deck's drive) yes (both decks' drive) —
level, low, mid, high — yes (the strip) level only (the master level) —
tempo yes (a place, not a repeat) — — yes (with a time word)
duck, mix yes (they name their decks) — — yes
sing "words" on melody yes (the only deck that has the role) yes — —
a def's call yes (the deck is an argument) — — —

A line that puts an action on a target that does not take it is an error that says which targets do. control: is the
control deck ("The control deck"): a head in the place of a target, for the engine calls only.

#Patterns: mini-notation

A pattern is one cycle, one bar. Its terms share the bar equally, so the step count sets the grid:

text
kick x ~ x ~            4 terms: quarter notes, hits on 1 and 3
kick x x x x x x x x    8 terms: eighths
snare ~ x ~ x           hits on 2 and 4
hihat x*8               eight hits, one an eighth
hihat [x x] x [x x] x   groups: two hits squeezed into one slot
bass c2 ~ [c2 eb2] g2   notes
bass 1 ~ 3 5            scale degrees of the key
bass 1 ($i + 1) 5       a degree computed (inside a repeat or a def)
melody <c4 e4 g4>       alternation: one a bar, then round
kick e(5,8)             euclid: five hits over eight steps
kick e(3,8,2)           the same, rotated by two
harmony [c3,e3,g3]      a comma inside [] stacks: three notes at once
hihat x*8?0.7           each of the eight hits kept with chance 0.7 (seeded)
bass choose [c2 e2 g2] weights 3 1 1    one of the three a bar, c2 three times as often
melody deg(1 b3 5' ~)   degrees with accidentals and octave marks, one slot
harmony <I V vi IV>     Roman numerals: a chord of the key a bar (bare, one a quarter); a section's own `key` re-reads them
hihat/12 x x ~ x        a cycle of twelve sixteenths: four terms of three steps, drifting against the bar
bass c2~3 e2            elongate: c2 ~ ~, the step takes three slots
hihat x*8?              a bare ? is ?0.5

#Generators

call does
e(k, n) / e(k, n, rot) / euclid(...) k hits over n steps (Bjorklund, as djrust::gen::euclidean), rotated by rot. As a term it takes one slot, so kick e(5,8) is a bar of eight steps and kick x e(3,8) puts the eight steps in the second half. 0 <= k <= n, 1 <= n <= 64 ("Euclidean rhythms and polymeter").
markov(key, density) / markov(density) / markov(key, density, seed) a Markov melody of one bar in the key's scale (djrust::gen::markov). The key is the program's key (or the section's) when left out. density 0..1. Same seed, same notes: the seed is, when left out, taken from the text of the part.
arp(chord, mode, n) the chord's notes one at a time over n steps (default 8) in up, down or updown. Either takes shift=n: its notes n key degrees up (-21..21; up n writes it).
chord(chord) / chord(chord, octave) the chord's notes together. A chord is a symbol (am7) or a numeral (V7).
choose [a b c] weights 3 1 1 [seed=4] one option a bar, picked by a hash, by weight (not a call: it has its own words, "Seeded chance").

#Parameters

name=value after the pattern, in any order:

param value does
vel=90 / vel=70..100 1..127 velocity. A range gives each hit its own, by a hash of its place: the same text, the same velocities.
oct=2 -1..8 the part's octave.
len=3 1..16 note length in steps (drums 1, tonal 2).
inst=sub-bass a name the instrument.
seed=7 a whole number the seed of the part's generators (and of its chance terms, unless they say their own).
glide=70 decay=900 pitch-drop=7 ms, ms, semitones tonal: ^ bends into the next note; each note's tail; starts 7 semitones high. On inst=acid-bass a ^ slides without glide= (60 ms) and decay= is its filter's sweep.
cutoff=400 res=80 env=60 accent=90 drive=20 Hz 20..12000, then 0..100 each tonal, the acid voice's knobs: the filter's floor, its resonance, how far each strike opens it (100 is 6 octaves), how much an accent ! does, how hard the oscillator drives the filter. Defaults 300, 72, 45, 80, 0. On any other voice they are ignored, with a warning.
voice-lead / voice-lead=off on or off a harmony (or arp) part of chords: each chord after the first is voiced for the least motion from the one before; bare, it is on.

Every number of a param may be arithmetic (vel=(60 + $i * 4)..100, oct=3 - 1).

A range a..b is any value from a to b, only ever for a parameter of a part. A ramp a -> b is
moving from a to b, only for a control change, with over N bars (or beats).

#Settings

tempo 126 (BPM, 40..300), swing 0.1 (0..1), key am. A setting applies to the whole program. key
is the default for notes with no octave, scale degrees, Roman numerals, markov, and the key tag the share carries.
No key: C major. No tempo: the decks keep theirs.

The tempo can move. tempo 100 -> 130 over 8 bars exp ramps it from the program's first bar and holds the end; a
tempo line may stand anywhere a place does (at bar 16: tempo 128 -> 140 over 4 bars) and a section may set its own
(tempo 140 as a statement of its body, from the section's first bar). The bar clock never moves: see "Tempo curves".
A section may also begin with a key of its own, which re-reads its degrees and numerals ("Degrees, numerals, a key a
section"). swing stays a setting of the whole program.

swing s is how late the off-step plays: every second sixteenth of every deck sounds s / 2 of a sixteenth after its
place. So swing 0.6 is 0.3 of a sixteenth (37.5 ms at 120 BPM), and swing 1, the most, is half a sixteenth, a dotted
3:1 (a triplet feel is about swing 0.67). The scale is the beats generator's own 0..100 read as 0..1: gen@N and
seed@2(...) write a genre's swing this way (jazz 0.6, house 0.2), and it reaches the engine as beats' 60 or 20. It moves when
the notes sound, never where they are: the steps, the bar lines, a pattern's text and its net stay as written. The arrange op
swing amt ("Arrange mutations") is another thing: it rewrites a pattern, moving every second step amt of a step later on the
sixteenth grid (a step of two sixteenths or more), so it changes the notes and the net, and only that pattern's.

#Control

Every control line compiles to calls on the control-language registry (docs/CONTROL.md), the same
calls djctl app and the djapp_* MCP tools make, so a line can be checked with describe:

line registry calls
swap pairs with echo_out autodj {action: set, style: echo}, then autodj {action: next}: the loop-set pair steps to the next group on the next bar line, with that move across the handover (filter_exit → style filter, echo_out → echo, loop_roll → roll; none: auto)
move bass_swap on B over 8 bars moves {action: arm, kind: bass_swap, deck: B, bars: 8}
load pair dnb:2602 group 2 loopsets {action: load_pair, spec: dnb:2602, group: 2}
deck A: mute kick deck {action: mute_part, deck: A, role: kick, on: true} (a part's role; unmute kick: on: false; solo kick: on: false, solo: true, only that role sounds)
row: clip vox_a crop=32..64 route=vocoder loops {action: library_load, asset: sha256:…}, clips {action: crop, asset, from: 32, to: 64}, clips {action: quantize, asset, beats: 4}, clips {action: gain …}, clips {action: fade …}, vocoder {action: set, instance: 0, modulator: clip:sha256:…, on: true}, then clips {action: play, asset}
deck B: load techno:42 deck {action: load, deck: B, spec: techno:42}
queue play / queue jump 3 queue {action: play} / queue {action: jump, n: 3}
deck A: play / stop / sync deck {action: play, deck: A} / stop / sync
deck A: mute mixer {deck: A, mute: true}
deck A: solo drums / mute vocals / unmute bass deck {action: role, deck: A, role: bass, on: false}, a call for each role of the stem (solo: of the other three; unmute: on: true)
deck A: loop 4 beats / loop off deck {action: loop, deck: A, op: beats, beats: 4} / {..., op: exit}
deck A: jump -8 beats / jump 16 bars deck {action: jump, deck: A, beats: -8} / beats: 64
master: filter lp 2k inserts {action: on, target: Master, effect: filter}, inserts {action: set, target: Master, param: filter.sweep, value: v} (v from the hertz: the knob's own curve, below 0.5 low-pass, above 0.5 high-pass)
deck A: filter hp 400 the same with target: A
master: filter off inserts {action: on, target: Master, effect: filter, on: false}
master: delay 0.4 inserts {action: on, ... effect: delay}, inserts {action: set, param: delay.mix, value: 0.4}
master: reverb 0.3 / crush 0.5 / drive 0.6 the same with reverb.mix / crush.mix; drive is fx {action: set, param: drive, value: 0.6} (the FX unit's drive: with deck A: it is deck: A, with master: no deck, which is both; 0 is the unit at neutral)
master: level 0.8 mixer {master: 0.8}
deck A: level 0.7 / low 0 / mid / high mixer {deck: A, volume: 0.7} / {deck: A, low: 0} ...
crossfader 1 mixer {crossfader: 1}
duck B under A.kick 6db trick {action: on, deck: B, kind: pump, source: A, amount: 0.499, div: 16} (put back with trick {action: off, ...})
mix { A level 0.7, A eq low -3 } mixer {deck: A, volume: 0.7}, mixer {deck: A, low: 0.4375}; in a section the mixer is read first with mixer {} and put back when the section ends
deck B: sing "words" on melody vocal {action: create, lyrics: ..., notes: [...], ...}, then vocal {action: to_row, play: true} (the browser: a sung part in deck B's net, docs/beatscript/phonemes.md)
at bar 16: tempo 128 -> 140 over 4 bars no call of its own: a tempo is an event of the program's tempo map; the runtime sets the decks' tempo (deck {action: tempo, deck: A, bpm: ...}) each service pass
macro riser on A over 8 bars effects {action: fire, target: A, id: riser, bars: 8}: an entry of the DJ macro catalogue by name ("Macros", below), made a beat ahead so it starts on the line's bar

A ramp filter lp 2k -> 8k over 8 bars sends the value afresh on every service pass, from the bar
it starts on to the end of the span, so it moves smoothly inside the bars, and it ends where it says. A
plain filter lp 2k sets it once. over with no -> is an error (nothing to move). A ramp goes straight unless it
names a shape (over 8 bars exp), and a value can also keep moving, as an lfo ("Shapes and lfo").

drive is the saturation of a deck's sound (deck A: drive 0.6) or of both decks' (master: drive 0.6), 0 to 1, said, ramped and
swung like reverb (master: drive 0.2 -> 0.8 over 8 bars exp, deck A: drive lfo sine 2 bars center=0.5 depth=0.3); for 4 bars
puts it back to 0. It is no new effect: it is the engine's FX unit's drive, the master chain's distortion that the Effects window's
Drive knob turns, the waveshaper y = (3 + k) x 20° / (π + k |x|) with k = 100 * drive, fully wet whenever drive is above 0 (the
switch fades over 50 ms). 0 is off: the unit at neutral, which changes no sample, so a program with drive 0 renders the samples
of the one without the line. Above 0 the curve takes a quiet signal up (a gain of (3 + k) / 9, 7 at drive 0.6) and bends a loud one
over: the output never goes past about 0.35 (-9 dBFS) however hard it is driven, so drive adds the odd harmonics (a kick that hums at
a set pitch, a squared acid line, a crunched guitar) and does not add loudness; there is no makeup gain, level is the other knob.
The value is held to 0 to 1: drive 2 is an error that says the nearest, 1. Parts share their deck's strip, as they share its
filter, so a kick that wants drive alone is a deck of its own (deck A: kick ... driven, deck B: the rest); master: drives each
deck's chain, not one on the sum. The browser, the booth and the phone run the same engine code: the same text, the same samples.

#Time words

Any line can have a time word, then the target, then what it does: at bar 16 for 4 bars: master: filter lp 800.

word fires
(none) once, on the first bar line after the statement is added or changed (in a section: on its first bar); a value that names an input (knob(1)) follows it on every bar
every 16 bars: on bars 16, 32, 48 ... (never on bar 0)
every 2 beats: every half bar, from the program's first bar: at 1/2, 1, 1 1/2 ... of a bar (never at 0). The finest is every 1/64 bar
every 4 bars from 8: on bars 8, 12, 16 ... (from takes a bar, a fraction of one, or a position: from bar 3 beat 2)
on phrase: on bars 8, 16, 24 ...: every phrase
on next phrase [8|16|32]: once, on the first bar that is a multiple of 8 (or 16, 32)
at bar 32: once, on bar 32 (in a section: bar 0 is its first bar, so at bar 4 is the fifth)
at bar 16 beat 3: once, on the last quarter of bar 16 (beats count from 0: beat 4 is an error, write at bar 17)
after drop: once, on the bar the section drop ends on
before drop 4 bars: once, four bars ahead of the section: the roll that leads into a drop (before drop 2 beats: is a half bar ahead)
for 4 bars / for 2 beats after any of the above: the effect is put back after that long (for 4 bars: alone is now)

on next bar: is the same as no word. A length is 4 bars, 1 bar, 1/2 bar or 2 beats; a beat is a quarter of a bar. A time between bar lines fires
when the deck's beat position crosses it, once. at bar 3/2 is at bar 1 beat 2. At the top of a program with no sections
at bar 0 is an error (the first bar after the start is at bar 1) but a time inside bar 0, at bar 1/2 or at bar 0 beat 2,
is legal and fires once before bar 1.

for N bars puts back what the line did where the verb has an off: a filter, a delay, a reverb, a crush
(inserts ... on: false), a drive (turned to 0), mute (mute: false), freeze on / trick on / moves arm (the verb's pair),
play (stop), a duck (trick off) and a mix (the mixer's own values). A line with no off (a level, an EQ, a
ramp of a plain value) says so as an error: ramp it back with a second line. every 16 bars for 4 bars: puts it back
each time.

A ramp a -> b over N bars works on any numeric param of any line (do vocoder set mix=0 -> 1 over 8 bars,
master: resonance 0.2 -> 0.8 over 4 bars), one ramp to a line. over with no ->, or a -> with no over,
is an error.

Program bar 0 is the bar the program first started on. It keeps counting through every
re-evaluation, so editing a line never moves the schedule of the others. btw stop ends the program,
and the next eval starts a new one at bar 0. In a song with sections (below), bars are counted from the
song's own first bar, the bar the first section lands on.

In a program with no sections, bar 0 is the bar the evaluation fell in, and that decides what the first bar you hear is called.
With nothing playing the music starts on it at once, so it is bar 0 and the first bar you hear. With a deck already playing nothing of
the program sounds on it (a net lands on the next bar line) and the music lands on bar 1: at bar 1 is the first bar you hear, at bar 2 the second. The offline render and btw test start the music on their bar 0 (nothing was playing there), so a timed line of a
program with no sections, evaluated while a deck plays, lands one bar later counted from the first bar you hear in the render than
it did live (at bar 2 is the second bar you hear live and the third in the render). A song with sections is not affected: both count
from its first section. Programs written before the extensions have always counted this way and it is kept. The one thing counted from
the first bar you hear in both is the tempo: a tempo curve and the tempo lines of a program with no sections (the tempo map, a
timeline of its own) start on the bar the music lands on, live and in the render, so the ramp is not a quarter spent before the music
lands (see "Tempo curves"). (The lands an evaluation answers, and the bar numbers in btw get's words, count the clock: the bar you
evaluated in is the clock's bar 0, so a program that lands on the next bar says lands: 1.)

#Guards

A line can end with when and a condition: deck A: kick x ~ x ~ when $i % 4 == 3, at bar $i: master: filter lp 300 when $i % 2 == 0, drop(A, 8) when $i != 0. The condition is read where the line is expanded (so inside a repeat
or a def it sees $i, $n and the def's $params; at the top it is a constant), and a line whose guard is false is
removed before it is checked or compiled: a guarded-off line may name things that do not exist in this repetition
(a section, a second kick). A guard is a comparison (== != < <= > >=) joined by and or not, over arithmetic
and words (when $deck == A). It belongs to lines (a part line, a control line, a do, a def's call), not to let,
def, section, tempo or key. On a control line it may name a performed input (when held(key)): then it is
decided while the program plays ("Performed inputs"). when does not start a pattern step, so kick x ~ when ... ends the
pattern there.

#Moves put their strip back

filter_exit and echo_out end by muting the deck's channel. A move from a program restores it: the
strip is unmuted at the first phrase line after the move has ended
, whatever else happens, so a recurring
every 16 bars: move filter_exit on B over 4 bars never leaves B silent past the next phrase. for N bars
on a move puts it back after N instead; btw stop and an edit that drops the line put it back at once. The
deck's panel says MUTED in red while a strip a program plays on is muted, and btw get has it in warnings.
A move takes whole bars (the registry's moves arm takes bars): over 2 beats on a move is an error that says so.

#The control deck

control: is a deck of engine calls, beside deck A:, deck B: and master:. It takes the lines that take no target
(move, swap pairs, load pair, queue, crossfader, a tempo at a place, duck, mix, macro, do and its sugar nouns), in
the place a target goes, and sections, repeats, defs, guards and time words sequence it like any line:

BeatScript
section drop 16 bars {
  deck A: kick x x x x | bass c2 ~ c2 ~
  deck B: arp arp(am7, up, 8)
  master: filter lp 400 -> 8k over 8 bars
  control: move echo_out on B
  at bar 12: control: swap pairs with filter_exit
}
every 16 bars: control: freeze phrase bars=2

A line on it compiles to exactly what the line with no head does: the same registry calls, the same key (so moving a line
onto it, or off it, fires nothing again), the same nets. The canonical text keeps the head, so control: move echo_out on B
and move echo_out on B are two spellings with two CIDs; both stay, and no program's CID moved. The control deck never holds
a part or a note (control: kick x ~ x ~ is an error that says to write it on deck A:), a strip's action (control: filter lp 400: on deck A:, deck B: or master:), a deck's transport, a sing, a def's call or a setting (control: tempo 140 with
no time word is tempo 140). control is no reserved word: it is the head only before its colon. The long note is
docs/beatscript/ext-control.md, with macro's.

#Macros: the DJ catalogue

text
control: macro riser on A over 8 bars
at bar 24: control: macro cathedral on B over 2 bars
macro@1 breakdown over 4 bars on A

macro ID on DECK [over N bars] fires one entry of the engine's DJ macro catalogue, the 39 pads of the apps' Effects window
(riser, tape_stop, breakdown, cathedral, ping-pong, feel-build ...: the macros MCP tool lists them), on a deck: the
registry's effects fire, so the booth, the window and the program fire the same thing. It is a line of the control deck, and a
line with no head. on DECK is required (the focused deck is the person's, not the text's); over N bars takes 1 to 64 whole bars,
and with none the entry runs the window's own length (1 bar, 2 for a sweep). A transition runs its own length: the riser rises over
its over (4 bars with none), a tape stop, a spin back or a reverb freeze is held over N bars and let go (1 with none), and a cut
or a double drop takes no over. The engine starts an engagement on the deck's next bar line, so the call goes a beat ahead of a
bar-line time and the macro starts on the bar its line names (at bar 24: is sent at bar 23 beat 3); at the song's very first bar
there is no beat before it, and it starts on the next.

Versioned. macro is macro@1: a frozen copy of the catalogue as of the engine this repo pins, each id with its category,
family and length, never edited, so a stored program's macro riser means what it meant. A later catalogue is macro@2, a table
beside it; the canonical text writes the version only when it is not 1 (macro@1 riser is macro riser). An unknown id is an error
with the nearest (macro rizer: did you mean riser?), and an id only a later version has says which. render and listen play
a macro line (listen names each in macros, with the bar it starts on and whether the engine played it); a browser tab does not,
and lists it as not played here. macro is no reserved word.

An arrange { } switches the control deck pass by pass: ~ control off (its lines do not fire in the sections from here on),
~ control on, @ control off (the next section only), ~ control freeze off (the lines of one call), ~3 control off (every
3rd pass). The head is what a switch reaches: move echo_out on B with no head keeps firing ("Arrange mutations").

#The DJ tier: Selecta

BeatScript
sample tune from "sha256:..." license restricted-private else bright-pluck
cue tune.drop at bar 32 beat 2
deck A: solo drums
at bar 24 for 4 bars: deck A: loop 4 beats
at bar 32: deck B: jump -8 beats
at bar 40 for 8 bars: deck B: mute bass

The DJ constructs are a tier of the one grammar, called Selecta (docs/dj-language.md, taste calls 1, 2 and 6 to 8): no version
line and no CID of their own, and the productions whose note says [booth]. check says needs: ["booth"] of a program that uses
one, and its linked data says the same, so a host that is no booth can say what it would not play; every other report is as it was.

#The whole surface: do

text
do <noun> [<verb>] [<positional text>] key=value ... [over N bars [shape]]

is any call of the control language (docs/CONTROL.md), checked against the registry the same describe,
the MCP tools and CONTROL.md come from. The noun and verb must exist (an alias works; do vocoer on says
did you mean vocoder?), every key must be a param of the noun, with the right type (bands=2.5 is "a whole
number"), one of the allowed words where the registry lists them (deck=C), and what the verb requires must
be there (do vocal create bars=2 needs lyrics). The errors give line and column, what would have been
accepted and the nearest name. The btw noun's verbs that act on the program that runs (eval, stop, load, open,
replay, perform) are errors in a program, at check (at bar 4: do btw stop did nothing: the runtime holds the program while its
lines run, so the call acted on an empty placeholder); the others (check, fmt, save, list, jsonld ...) work. A bare string after the verb fills the verb's first required text param:
vocal create "robots on the road" bars=4. Values are numbers (2k, 50%, arithmetic: bands=2 + $i), words
(on / off are booleans where the param is one; dnb:2602 specs; param=delay.mix), "strings", [lists],
a -> b ramps (with a shape after over: mix=0 -> 1 over 8 bars exp) and lfo values
(value=lfo tri 1 bar depth=0.2 center=0.3). A ratio such as ratio=1/4 is the registry's word 1/4; ratio=(1/4) or
1/4 * 2 is arithmetic.

The sugar is the same line with no do: vocoder, vocal, voice, trick, freeze, loops, clips,
wheel, td3, pd705 (the kits noun), effects, aux, automix, record, mashup, and key when a verb
of it follows (key detect deck=A; key am is the setting).

text
every 16 bars: freeze phrase bars=2
at bar 8 for 4 bars: trick on deck=A kind=stutter
vocal create "robots on the road" key=am bars=4
do vocoder set mix=0 -> 1 over 8 bars
do td3 write confirm=true

#The wheel

The wheel lines play windwheel's tonewheel instrument (the Wheel window, on the Windwheel input strip). Each is the
sugar for do wheel <verb>, checked against the registry like any other call:

text
wheel load preset=NAME          # an instrument, by its id from `do wheel presets`
wheel key root=C transpose=2    # the key every note is re-wound for: root C, F#3, Bb2 ..., transpose -24..24
wheel sequence notes="C E G B"  # the notes the path plays, in order; without notes, the preset's own
wheel motor on=true speed=2     # a cord instrument's motor: on / off, speed in m/s (0..25)
wheel level db=3                # the wheel's level, dB -20..40
wheel play
wheel pause

A wheel line takes a time head like any other (at bar 16: wheel play). The browser engine on beatscript.app plays the
wheel too, the same instrument as the booth: the wheel goes into the master after the decks, so master: filter, reverb
and level reach it.

#Functions and structure

Everything here is total: there is no recursion and no loop without a written-out count, so check
always proves a program ends, and the same text always gives the same CIDs. (Arithmetic is part of that: an expression
is a tree walk, evaluated once when the program is read.)

text
let kicks = x ~ ~ ~ ~ ~ ~ ~ ~ ~ x ~ ~ ~ ~ ~       # a pattern: used where a pattern goes, as a group
let late = 8                                       # a value: put in place of every later use
let root = c2

def groove(deck, bars) {                           # a macro, expanded at each call
  deck $deck: kick kicks | bass root ~ root ~
  repeat $bars every 1 bars {                      # a literal count; $i is the copy's index
    master: filter lp 300 -> 2800 over 1 bars
  }
}

section drop 16 bars {                             # lines in it count from its first bar
  master: filter off
  groove(A, 16)
}
arrange intro build drop breakdown drop2 outro

#Ending

A program with a timeline (arrange, or sections in order) ends: after its last section the decks stop on the
bar line, what the lines still hold changed is put back (a strip a move muted, a filter), the ramps end, and the
window and btw get say ended (ended, ended_at_bar). Nothing wraps round to bar 1. A section that wants an
echo or a fade says so in its own lines (move echo_out on A over 8 bars in an 8-bar outro ends where the song does).

line does
end the same as the default: after the song's last section
end after outro where the section outro ends (the song stops there, later sections never play)
end at bar 64 on bar 64 of the song (of the program, with no sections)
loop at the song's end it starts again from the first section, its at lines firing again each lap
arrange set: drop wubs then close a named arrangement that goes on to another one (below)
arrange set: drop wubs loop a named arrangement that repeats itself for ever: the song's lap starts at it, not at the first section
launch drop on pad(2) a hit of pad 2 brings in the section (or arrangement) drop on the next phrase line, where it loops; next bar or next phrase 16 set the line
arrange close: outro end a named arrangement that ends the song
start set the arrangement that plays first (default: the first written)

arrange set: drop wubs loop 4 plays four passes in all, then goes on to the next arrangement written (the song ends after the last one).

A program with no sections plays on by itself (its patterns loop) until it is stopped or end at bar N says where.
A song either ends or loops, not both, and end is said once. Evaluating another program after the end starts fresh.

btw stop and the end put back what the program took: a strip a line still holds changed, a tempo curve's tempo (the
tempo each deck had when the program was applied, read before its nets landed, goes back to it: the words say "tempo put
back", and a deck whose tempo the host could not say is left where it is), and a sing line's voice (the clip it put on
the loop row is stopped with loops stop; so it is when an edit removes the line, and where a lap of a looped song turns).

#Several arrangements

A song may have several named arrangements, each saying how it ends, so one program can have an intro that plays
once, a section that loops, and an outro. arrange a b c with no name stays the one plain arrangement (a program may
have either that or named ones, not both), and every program written that way keeps its CID.

text
arrange open: intro build then set
arrange set: drop wubs build2 peak loop
arrange close: outro end
start open

#Scenes and launch

text
section verse 8 bars { ... }
section drop 8 bars { ... }
section breakdown 8 bars { ... }
arrange verse drop breakdown verse
loop

launch verse on pad(1)
launch drop on pad(2)
launch breakdown on pad(3) next phrase 16

A scene is a section (it plays on its own and loops until the next launch) or a named arrangement (it plays as start NAME would, from
its first section, and ends as it says: then, loop, end). A section and an arrangement share a namespace, so launch drop is never
ambiguous. launch NAME on pad(N) says which pad of the controller brings which scene in, so the written song is the song you hear until
a hand comes to the pads.

Long note: docs/beatscript/ext-perform.md, "Launch".

#Evolving

evolve is a program that applies transforms to itself over time: the variation inside a section or a loop, where
arrange stays the authored structure.

BeatScript
section drop 32 bars {
  deck B: melody [a4 c5 e5 g5] | bass [a2 ~ e2 ~]
  deck A: kick x ~ x ~ | hihat x*8
  evolve every 8 bars {
    melody: rotate 1 | transpose <0 5 7 0>
    hihat: thin 0.1 seed=3
    bass: invert when gen % 2 == 1
    stop when gen == 3
  }
}

The model. The parts as written are generation 0. Every every bars the next generation is made from the
one before by the rules, so generation n is f_n(...f_1(gen 0)); with a rule that does not mention gen (no
when, no <a b c>) that is f^n, the composite iterated: transforms are endomorphisms (a part to a part of the same
shape; see "Categorical notes"). A rule is target: transform | transform ... [when guard], the
target a role (melody, on every deck that has one) or deck A (every part of the deck), and the transforms are applied
in the order written. They act on the realized hits of the generation before (a step in the bar and a note), not on
the text, so a thin takes away what the last generation still had.

transform does
rotate n every hit n steps (sixteenths) along its bar, wrapping
reverse the steps of a bar backwards
transpose n / octave n pitches up n semitones / octaves (tonal parts; a drum's note is the drum)
invert pitches turned over about the part's first note (tonal parts)
thin p [seed=s] drops the share p of the hits, picked by a hash of (seed, generation, bar, step, note): the same seed, the same hits
fill p [seed=s] each step of a bar with no hit on it takes, with chance p (a hash of seed, generation, bar and step), a copy of the hits of the step before it that has some; a bar with no hits stays empty
slow n the first 1/n of each bar played over the whole of it: a hit at step s moves to s*n (its length with it), what would fall past the bar's end is gone (n 1 to 16)
fast n each bar played n times in the time of one: a hit at s lands at s/n and again every 16/n steps (n 1, 2, 4, 8 or 16)

The transforms act on realized hits, so they are not the arrange mutations' operators (which rewrite a pattern's text): a
mutation operator an evolve does not take (drift, ratchet, morph ...) is an error that says it belongs to arrange { }.

An argument <0 5 7 0> takes one value per generation, round (generation 1 the first). A guard is gen == 3,
gen % 4 == 3, gen >= 8 (also !=, <, <=, >): the rule runs in the generations it is true for.

Total, and the bound. stop when gen == 12 (or >= 12) or for 12 gens says the last generation (at most 256): it plays on
to the end of its section. It is optional, because the evolution is finite anyway: a part is a finite set of hits, so the
sequence of its generations (with the rule's own clock, the lengths of its <a b c> and the moduli of its guards) must come
round to a state it has had. In a section with no stop the section's length is the bound (as many generations as fit). In a
program with no sections, no stop means the orbit: the generations up to where it comes round, played through and ended
(over 256 generations of orbit is an error that says so and asks for a stop). Generations that would start after the section
is over are a warning ("generations 4 to 12 never play"). A program with no sections has its own timeline of last + 1
generations of every bars and ends when it has played them (loop starts it again); at bar lines in it count from its
first bar. In a song, an evolve belongs inside the section it varies (one to a section).

Tail and period. Because a rule acts on each part alone, the program's orbit is the parts' together: the longest tail (the
generations before a part settles into its cycle) and the period (the least common multiple of the parts' periods). check,
eval (evolve) and djctl btw check print it when what plays comes round to it (the tail and one period fit before the
stop or the section's end, or a program of its own plays its orbit through):

text
evolve in drop: tail 34 generations (272 bars), then it cycles: period 4 generations = period 32 bars ≈ 1m02s at 124

(that is the example above with its stop taken out and its section long enough to play the orbit through: the melody climbs until its notes reach the top of the MIDI range, the
thinned hi-hat runs out of hits, and what is left comes round every four generations. A rule whose parts come round in 7, 11 and
13 generations of 8 bars has a period of 1,001 generations, 8,008 bars, 4h18m at 124.)

When the stop or the section's end comes first, they say what plays instead, and that it does not cycle:

text
evolve in drop: generations 0 to 5 in 24 bars, then it stops at gen 5 (its `stop`); no generation repeats, so it does not cycle
evolve in drop: generations 0 to 2 in 6 bars, then the section ends; no generation repeats, so it does not cycle

thin picks hits by a hash of the generation number, so a part it acts on is not a function of its state and the rule's
clock: its only provable fixed point is the empty part (which every transform leaves empty), and a thinned part's orbit is
found when it has no hits left (or not found, said so, if that is not within 20,000 generations). fill is random the same
way; with no thin against it, its fixed point is the part with a hit on every step of every bar that has one, found when a
generation leaves it as it was under rules with no clock of their own (no when, no <a b c>).

Any generation, from the rule. btw generation {gen: N} (and djctl btw gen FILE N) answers the CID of generation N
computed from generation 0 and the rule alone: no chain stored, and a part that has come round its cycle is brought back to where
it is in it, so generation 1,000,000 costs the length of the orbit, not a million steps (a test walks every step by hand and
demands the same CID).

CIDs and lineage. A generation is compiled as a segment of the timeline, so the runtime swaps its nets in on the bar
line like any section's. Each generation has a CID of its nets (content only: djrust.live.gen over the deck
to net-CID map) and records the CID of the generation it came from: the chain a fork's forkedFrom is made of. A
rule that changes nothing (transpose 0, a fixed point) gives the same CID every generation, each forking itself.
eval answers the whole chain (lineage: scope, gen, cid, forkedFrom, start bar, bars) and btw get and the window say
which generation is playing. The share link carries generation 0 and the rule (it is the program), so opening it
reproduces every generation, CID for CID. (The evolved generations are not saved as programs of their own: they are
a function of the one that is.)

Blocks are written with braces, like every other block, not with the colon and indent of the first sketch.

#Pattern transforms

Terms like generators; a pattern is given as [...], a let name, or another transform:

call does
transpose(p, n) / octave(p, n) n semitones / octaves up (a hit in a tonal part is its root first)
reverse(p) / rotate(p, n) the steps backwards / moved n steps along
every(n, p) / every(n, p, q) p on every nth bar (the 4th, 8th ...), q (or a rest) on the others
degrade(p, a) / degrade(p, a, seed) drops the share a of the hits: seeded, so the same text is the same hits
slow(p, n) / fast(p, n) p stretched over n bars / played n times a bar
humanize(p, seed) / humanize(p, seed, amount) velocities wander by up to amount (default 10), seeded
maybe(p, prob) / maybe(p, prob, seed) keeps each hit of p with chance prob (0 to 1): p with ?prob on every hit
rests(p) / rests(p, q) a hit on each step where p rests / q kept there
ply(p, n) each step of p n times in its slot (*n on each)
palindrome(p) p, then p backwards: <[p] reverse(p)>
iter(p, n) p a 1/n of its steps later each bar
off(p, n) / off(p, n, k) p and a copy n steps later (k semitones up)
poly(p, q ...) / poly(n, p, q ...) each walked n steps a bar (the first's count when left out), stacked

Marks touch their step: c2! an accent (velocity +27), x. a ghost (40%), e2^ a slide (held into the next
step; with glide= it bends), x& a flam, x:3 a ratchet (3 hits in the sixteenth, 2 to 8). Not ! with ..

#Expression marks

The marks say how a hit is played, the tonal params glide=, decay= and pitch-drop= shape an 808, and
cutoff= res= env= accent= drive= turn the acid voice's knobs. A
program that uses none of them is the program it was: same canonical text, same nets, same CIDs
(crates/beatscript-api/tests/cid_pins.rs pins every program in the repo).

The acid voice (inst=acid-bass, a saw, also called inst=acid; inst=acid-square, a square) is a 303-style voice
made in the engine (no samples): an oscillator into a resonant four-pole (24 dB) lowpass that an envelope sweeps on each
note, with a soft output stage. It plays the marks as a 303 does. An accent ! is louder, opens the filter further and sweeps it shorter, and accents in a row build on each
other (the engine reads the accent from the velocity: above 110 in proportion, all of it at 127, so a vel= up there is
accented too). A slide ^ carries the voice into the next note without striking it again, the last step's into the
first: in 60 ms, or in glide= ms (the note it leaves says slide on its binding, so its gate stays open). A note that does not slide lets the one
before go (one note at a time, as a 303; a chord's notes each sound). Its knobs are part params, each on every note's
binding only when set (cutoff, res, env, accent, drive), so a part without them is the net it always was:
cutoff= (Hz, 20 to 12000, default 300) the filter's floor; res= (0 to 100, default 72) its resonance; env= (0 to
100, default 45: 100 is 6 octaves) how far each strike opens it; accent= (0 to 100, default 80) how much an accent does;
drive= (0 to 100, default 0) how hard the oscillator drives the filter's saturation, grit and not loudness. decay= is
its decay knob and glide= its slide time. They are not reserved words (section drive is still a section); on a drum
part they are errors, and on a voice that is not the acid voice a warning (it plays as it would without them). Long note,
with its decisions: docs/beatscript/ext-acid.md. Example: examples/beatscript/acid-303.beatscript.

glide=, decay= and pitch-drop= on a drum part are errors. Marks work on drums and tonal parts alike, in groups
([x x]& flams both), alternations and deg( ). The net carries them on each note's binding (glide, decay,
pitchDrop, ratchet, flam; written only when set), and the engine plays them in the browser, the app and renders
alike. Glide and pitch drop bend wavetable voices; a pluck or a sung voice strikes the note as written. Example:
examples/beatscript/trap-expression.beatscript.

#Arrange mutations

arrange { } makes the arrangement a path through the program's state: a mutation between sections rewrites the
text of a let pattern, and every later section reads the new text. The whole page: Arrange mutations.

text
arrange {
  intro build drop
  ~ acid_a rot 2, hoov_a up 3        # from here on
  wubs build2
  ~3 acid_* drift 0.15               # a glob, on every 3rd pass only
  peak
  @ hoov_b rev                       # the next section only
  @ control off                      # the control deck: none of its lines fire in the next section
  outro
} loop 4 then outro end
op does (to the pattern's steps: see The steps below the table)
rot n / rev / swap / mirror / shuffle rotate n steps later / backwards / swap neighbours / the first half, then backwards / a seeded permutation
thin p / fill p / euclid k each sounding step rests with chance p / each rest takes the step before it with chance p / the hits re-spread as k Euclidean hits
half / double / stutter n the first half at half speed / the pattern twice in the bar / the first 1/n of it n times
ratchet p / swing amt a sounding step struck twice with chance p: doubled on the grid (*2) when its step is longer than a sixteenth, else ratcheted inside it (x:2, again x:4, at most x:8), so no hit snaps / every second step later by amt of a step (on the sixteenth grid)
up n / down n / oct n / invert / drift p scale degrees of the key up / down / octaves / turned over about the first note / a step up or down with chance p. A Roman numeral moves by degrees too (in A minor i up 2 is III, the key's own triad there; V7 up 1 is VI7)
vel n / accent p accents on the n strongest steps (vel -n takes n off) / an accent with chance p
morph b p / xfer b / mask b each step becomes b's with chance p / b's rhythm with these notes / rests where b rests
grow / decay one rest filled / one sounding step taken out (seeded; they pile up pass on pass)
voice n / spread each chord [a3,c4,e4] or chord(am7) inverted n times / its every second note an octave up
jux op the pattern stays the left copy, op of it plays hard right (jux rev)

The steps. A pattern written as one [...] (let acid = [1 1 ~ 1 3 ~ 1 5 ~ ...], a bar of sixteenths) is its steps, not
one step: rot, thin, half, decay, ratchet and the rest work inside the brackets, and the brackets stay. A <...>
cycle of bars (let riff = <[...] [...]>, let chords = <i i iv v>) is worked a bar at a time, each bar as its own steps,
the dice running on from bar to bar: rot 3 rotates every bar, accent 0.3 accents steps in them, never the cycle as a whole.
A cross operator (morph b p, xfer b, mask b) reads b the same way, bar for bar when both are cycles. A pattern a
mutation takes down to one step (~ p half on x ~) is still a pattern.

Try arrange-in-eight-lines.

It is one section played eight times. Each play changes a pattern with ~ (the hats, then the arp, and so on, pass on pass)
or, with @, for one play only (the kick doubles, then the arp halves, and each is back the next play). Three comments in the
file say it in words.

#Start from a seed

seed(genre, n) is a track of the beats generator (the beats sequencer's, the same notes), as BeatScript: a value, never
audio. Start a program from one line, write it out, and make it yours:

BeatScript
arrange from seed(techno, 42)                          the whole track
section intro from seed(techno, 42)[1..8]              bars 1 to 8 as a section
deck B: bass seed(techno, 42).bass[17..24] inst=fm-bass    a part's bars; your params win
let riff = seed(techno, 42).bass[17..20]               the same, named (say which part)
arrange from seed@2(jazz, 7)                           seeds v2: the track, swung
section hook from <cid>.drop                  a saved program's section (parts, key)
deck B: bass <cid>.drop inst=hoover           its part (the line's role; .melody another)
arrange from template(deep-house, @tempest_such_stuff)  a phrase as a track
arrange from template(rondo, @hands_up, refrain=ode_to_joy)  a form, a role bound: docs/forms.md

#Borrow from a stored program

<cid>.drop is a section of a program that is already saved, and <cid>.drop.bass one of its parts: the music itself, named by
its hash, not a copy that can drift. It stands where a seed does (ref in the grammar): keep the drop of a track you like, and put your
own around it.

BeatScript
section hook from z4EBG9j9....drop              a section of it, as a section of yours
deck B: bass z4EBG9j9....drop inst=hoover       its bass on this line; your params win
deck B: bass z4EBG9j9....drop.melody            another of its parts, on this line's role
let riff = z4EBG9j9....drop.bass                the same, named (a let says which part)
deck A: kick z4EBG9jF...                        a bare CID is a program with no sections: its kick

#Call the generator: gen@v

gen@2 techno seed=42 is the program the seeded generator prints for those inputs: the generator of the MCP generate tool,
POST /api/generate and beatscript.app's ✦generate button (no model, no sign-in; the G key opens it). It is an engine call
("Two halves"): opaque until it is resolved, then pinned by the CID of the program it resolves to. Its params are the
generator's own, so a call reads like a function's signature:

BeatScript
let bed = gen@2 techno seed=42 section=drop part=bass      the bass of its drop, a let a bar: bed_1 ... let bed = <bed_1 ...>
deck B: arp gen@2 house seed=7 section=drop inst=pluck      a part of it, on this line's role; your params win
section hook from gen@2 techno seed=42 section=drop         a section of it: its parts, never its control lines
arrange from gen@2 techno seed=42 bpm=128 key=am            the whole program

#Phrase templates

template(name, phrase) compiles a phrase, a phrasebook id or any words, to a whole track. Like a seed it is written
out as plain BeatScript before the program is lowered, so the track is text you can read, edit and re-check:

text
arrange from template(deep-house, @tempest_such_stuff)      a phrasebook line: its words, its stress, its feel
arrange from template(deep-house, "robots on the road")      any words: their stress is worked out

Forms: six templates are classical forms (quodlibet, passacaglia, canon, rondo, fugue, theme and variations) and a seventh,
cross, is a quodlibet of two sources; each is a section shape and a mutation plan built from public-domain themes (the theme
library, beatscript.app/themes, CC0), the phrase sung in one section: docs/beatscript/forms.md (https://beatscript.app/docs/forms.md).
The MCP genre_template takes a form or a theme, and list_examples with themes lists the library.

template is example
deep-house deep house at 122 (Am F Dm G, swing 0.12): a four-on-the-floor kick (kick4) and clap, drm_hat, drm_shk and drm_rim drums, a bass on the roots, a pad and a kalimba on the vocal line. night buries the voice (lower, darker, ducked under the kick), spot puts it up front. The arrangement: night, @ vox_* oct 1 spot (an octave up), ~ drm_* fill 0.15, night, @ vox_* xfer drm_shk spot (the voice crossed onto the shaker), ~ drm_* grow, four passes examples/beatscript/such-stuff-as-dreams-122.beatscript
quodlibet a form: Pachelbel's ground and violin, Beethoven's Ode to Joy and fate motif take turns by section and cross-morph toward each other and away (~ a_* morph b_1 p, then ~ b_* morph a_1 p), the phrase sung over the ground examples/beatscript/canon-of-fate.beatscript (the reference)
passacaglia a form: Holst's five-beat Mars ostinato as a ground never changed, cumulative variations above it (rot, thin, `rev drift, grow, up, down, decay`)
canon a form: Pachelbel's violin line chased by copies of itself a bar and a beat behind, made of its own bars
rondo a form: Joplin's Entertainer as a refrain returning mutated (A B A C A) between Bach's Prelude in C and the sung section examples/beatscript/rag-rondo.beatscript (the reference)
fugue a form: Grieg's Mountain King as the subject, answered a fifth up and re-entering transposed while Bach's Badinerie morphs toward it
theme-and-variations a form: Dvorak's New World Largo, a different one-shot transform each section (rev, invert, stutter 2, oct -1, half), no cross-morphs
cross a form: two sources take turns (a_leads, b_leads), overlap (both) and morph toward each other and back in cycles (~ a_melody_* morph b_melody_1 p, @ ... xfer); unbound, Ode to Joy over Pachelbel's ground and the Badinerie in B minor examples/beatscript/cross-two-seeds.beatscript

Roles: the form is the structure, sources fill it. After the phrase, a form takes role=source bindings; a role nobody
binds keeps the form's own material, so a reference with none is the text it always was:

text
arrange from template(passacaglia, @eccl3_season, ground=gen@1 dubstep seed=54876 part=bass, upper=ode_to_joy)
arrange from template(cross, @psalm42_deep_calleth, a=gen@1 dubstep seed=54876, b=gen@1 house seed=7)
arrange from template(rondo, @hands_up, refrain=gen@1 dubstep seed=54876, episodes=template(passacaglia, ground=[g1 ~ d2 ~]))
form roles: what each is (default)
quodlibet a, b: two tunes drawn toward each other (Pachelbel's violin, Ode to Joy); ground: the bass (Pachelbel's ground); third: the line both are pulled toward (the fate motif in B minor)
passacaglia ground: the bass under every section, never changed (Holst's Mars ostinato); upper: the line the variations change (the form's own)
canon subject: the line chased by copies of itself, a bar and a beat behind (Pachelbel's violin); ground: the bass (Pachelbel's ground); the numbers delay= (beats behind) and interval= (semitones) of the chase's copy
rondo refrain: the tune that comes back (Joplin's Entertainer); episodes: a line, the episodes' figure (Bach's Prelude in C), or sections
fugue subject: entered, answered a fifth up, re-entered (Grieg's Mountain King); counter: drawn toward it (Bach's Badinerie)
theme-and-variations theme: the one source each variation changes (Dvorak's Largo)
cross a, b: two sources, each a melody, bass and chords (a whole seed; a line is the melody); one part alone: a.bass=, b.harmony=

Three phrases, three tracks (examples/beatscript/): such-stuff-as-dreams-122.beatscript, Shakespeare's "we are such stuff as dreams are
made on", iambic, 20 syllables, a four-bar line in the bar; assyrian-122.beatscript, Byron's anapestic "The Assyrian came down like
the wolf on the fold", 12 syllables, the 12-step cycle; commit-message-122.beatscript, "make the drop deeper and move the
kick", a commit message whose stress is worked out. Long note: docs/beatscript/ext-template.md.

#Name a source: use

use SOURCE as NAME gives a source a name, on a line of its own at the top of the program, and the name is then used where a
section, a let or a phrase of the program's own would be. A long reference reads in lines, and a source used twice is named
once:

text
use z4EBG9j9....drop as hook                             a stored program's section: arrange intro hook
use z4EBG9j9....drop.bass as riff                        one of its parts, a line: deck A: bass riff inst=sub-bass
use gen@2 house seed=7 section=drop part=bass as walk    a seed's part, a let a bar: ~ walk_* rot 2
use template(passacaglia).ground as ground               a canned section: a section of a template, written out
use template(deep-house, @tempest_such_stuff).night as night    the same, sung with that phrase
use genre@1 techno.drop as drop                          a genre template's section (genre_template's starter, frozen)
use theme ode_to_joy as tune                             a theme, in the program's key: deck B: melody tune inst=piano
use phrase @tyger_burning_bright as tyger                a phrasebook line: deck B: sing tyger on melody
use template(passacaglia, ground=walk) as episode_form   a form, for a role: template(rondo, @hands_up, episodes=episode_form)
source the name is written out (first, before templates, seeds and calls)
<cid>.drop, gen@2 ... section=drop a section section NAME from <cid>.drop, which the stored stage writes out ("Borrow from a stored program")
<cid>.drop.bass, <cid>.bass, gen@2 ... part=bass a line let NAME = <cid>.drop.bass (its pattern), let NAME = gen@2 ... (a let a bar)
template(passacaglia).ground, template(deep-house, @id).night a section the template written out (with the form's own example phrase when it names none), then that section borrowed by its CID; a section whose parts read the form's own lets in a call (the canon's chase) is refused, and list_examples with imports lists the ones that can be borrowed
genre@1 techno.drop a section the genre's starting program as genre_template writes it, frozen in genre templates v1, then that section borrowed by its CID
theme ode_to_joy a line its bars as lets named for the name, NAME_1 ... NAME = <NAME_1 ...>, moved into the program's key (to its relative key when the theme's mode is the other one), as a role moves one
phrase @tyger_burning_bright a phrase nothing: sing NAME on ROLE and template(T, NAME) sing @id
<cid>, gen@2 ... (no section or part), template(passacaglia, ground=...) a source for a role nothing: ROLE=NAME in a template reads the source

#The timeline extensions

Three additions to the language, and one derived report, for a view that draws a program as lanes against bars (the booth's
Timeline, a phone's read-only view). The timeline is a view of the program, not a second format: every edit a view makes is a text
patch, and a program that uses none of this keeps its text, its CID and its audio. They are part of BeatScript 2: no version line
of their own.

#Placed parts: at bar N for M bars: deck A: parts

BeatScript
section drop 16 bars {
  deck A: kick x ~ ~ ~ | snare ~ ~ x ~
  at bar 0 for 8 bars: deck B: bass acid_b inst=acid
  at bar 8 for 8 bars: deck B: bass acid_a inst=acid
}

A part line may take at POS [for DUR]: before its deck, inside a section. The parts play over that span of the section: from
POS (a bar of the section, counted from 0, as a control line's at bar counts) for DUR (to the section's end with no
for).

#Audio placements: row: clip NAME

text
use restricted
sample vox_a from "sha256:9f2c…" license restricted-private else bright-pluck
section chant 8 bars {
  at bar 0 for 8 bars: row: clip vox_a crop=32..64 route=vocoder
}

row: clip NAME [crop=A..B] [gain=G] [fade=F] [route=vocoder[:N]] plays a sample or loop of the program on the booth's loop row.
row: is a head beside master: and control:; the line takes the time words of any control line (at bar N for M bars:; with
none it starts with its section and plays to its end, and a for puts the clip away at its end). NAME is declared: the program
names audio by its content address only, never by path (BTW-ASSETS.md), so the rights are the sample's: a row: clip of a
restricted-private sample needs use restricted and the program is private, and btw fork {substitute: true} drops the swapped
sample's row: clip lines with its sample line.

#Part mute: deck A: mute|unmute|solo ROLE

mute, unmute and solo on a deck take a part's role (kick, snare, hihat, clap, bass, melody, harmony,
arp) as well as a stem. The line lowers to one registry verb: deck {action: mute_part, deck, role, on, solo?}. mute is
on: true, unmute is on: false, and solo ROLE plays only that role and mutes the deck's other parts (on: false, solo: true).
for N bars puts it back (a mute is unmuted; a solo lets the other parts sound again). A stem's name keeps its lowering, so mute bass is the stem bass, which is the bass role as before.

#The timeline report

check gains a timeline beside arrange and sections: it is derived (no CID, net or audio moves for it) and says what a
view draws.

text
lanes   [{id, target, role, inst, route, kind}]    id "B.bass", "row.vox_a", "ctl.master"; kind part | audio | control
blocks  [{lane, section, play, start, bars, line, col, end_line, end_col, span{start,end,start16,end16},
          text | let, params, placed, sample?, crop?}]
chips   [{lane, section, play, start, bars?, every?, line, col, end_line, end_col, span, text, call}]

Bars are the song's, counted from 0. A block is a part of a deck (or a row: clip) over its bars, one block however many
stretches the lowering cut its section into; text is the text it was written as (let is the call of a let or def that
made it); line and col count from 1 and span is the byte range (and its UTF-16 range) of that text, so a view edits by
patching exactly that span. A chip is a control line (a filter ramp, a call, a mute, a vocoder state) with its start bar and its
length when it has a for. play is the index of the play of the arrangement a block belongs to (a section played twice is two).

#The language extensions

Fifteen features were added to the base language. Each section below says what the feature is, shows a few lines of a real
program from examples/beatscript/ (every file there is original, CC0, and is compiled, canonicalised and reformatted at random by
crates/djlive/tests/examples_beatscript.rs), gives the rules in a few bullets and the canonical form, and links the long note.
The long notes hold the full grammar, the semantics, every decision and the errors; they are not repeated here.

feature example long note
Arithmetic and guards examples/beatscript/arith.beatscript docs/beatscript/ext-arith.md
Time finer than a bar examples/beatscript/timing.beatscript docs/beatscript/ext-timing.md
Tempo curves examples/beatscript/tempo.beatscript docs/beatscript/ext-tempo.md
Shapes and lfo examples/beatscript/shapes.beatscript docs/beatscript/ext-shape.md
Degrees, numerals, a key a section examples/beatscript/scale.beatscript docs/beatscript/ext-scale.md
Euclidean rhythms and polymeter examples/beatscript/euclid.beatscript docs/beatscript/ext-meter.md
Seeded chance examples/beatscript/chance.beatscript docs/beatscript/ext-chance.md
Composition: stack and then examples/beatscript/algebra.beatscript docs/beatscript/ext-algebra.md
Typed ports examples/beatscript/ports.beatscript, ports-import.beatscript docs/beatscript/ext-ports.md
Mix moves: duck and mix examples/beatscript/mix.beatscript docs/beatscript/ext-mix.md
Sung lyrics examples/beatscript/sing.beatscript docs/beatscript/ext-sing.md
Phonemes, the phrasebook, the vocoder examples/beatscript/vocals.beatscript docs/beatscript/phonemes.md
Assertions and btw test examples/beatscript/assert.beatscript, examples/beatscript/constraints.beatscript docs/beatscript/ext-assert.md
Performed inputs examples/beatscript/perform.beatscript docs/beatscript/ext-perform.md
Links to the ontology examples/beatscript/linked.beatscript docs/beatscript/ext-linked.md
Pattern sugar examples/beatscript/sugar.beatscript docs/beatscript/ext-sugar.md
Call and response examples/beatscript/answer.beatscript docs/beatscript/ext-answer.md

#Arithmetic and guards

Every place the language takes a number takes arithmetic: + - * / %, parentheses, a unary minus, min(...) and
max(...). It is worked out once, when the program is read, over exact rationals, so a program stays total and
deterministic: there is no loop, no state and no clock in an expression. $i, $n and a def's $params are put in place
as tokens before an expression is read, so $i * 2 + 1 is 3 * 2 + 1.

BeatScript
#! beatscript 2
tempo 120 + 4 * 2            # 128
key am
swing 1 / 16 + 1 / 16        # 0.125

let total = 4 * 4            # a `let` of arithmetic is one number, put in place of every later `total`
let base = 60 + 12           # 72

def pulse(deck, step) {
  deck $deck: hihat x*(4 + $step % 2 * 4) vel=(base + $step * 6)..100 when $deck == A
}

section groove total bars {
  deck A: kick e(2 + 2, 16) | bass 1 ~ (1 + 2) 5 oct=3 - 1
  deck B: harmony chord(am7)
  pulse(A, 1 + 1)
  pulse(B, 3)                # dropped: its guard is false for deck B

  repeat 4 {
    at bar $i * 4 + 1: master: filter lp 300 * ($i + 1) -> 2k over 2 bars when $i % 2 == 0
    at bar $i * 4 + 3: master: reverb min(0.5, ($i + 1) / 8)
  }
}

Canonical form: a lone literal keeps today's spelling; arithmetic that holds nothing read while the program plays is the number
it comes to, wherever a number goes: tempo 60 + 6 is tempo 66, level 0.25 + 0.25 is level 0.5, e(1 + 2, 8) is e(3, 8),
x*(1 + 1) is x*2, section drop 4 * 4 bars is section drop 16 bars; one program each. A rational prints as its decimal when
it has one of at most six places (0.7) and otherwise as the exact division (1 / 3), so what the text says is exactly the
number. An expression with an input in it (knob(3), held(key)) stays an expression, with every constant piece folded
(level knob(1) * 0.7, when knob(1) > 0.5: one space round a binary operator, parentheses only where precedence needs them). A
scalar let prints as its value (let third = 1 / 3); a guard prints after its line. A mix item is exactly a decimal of at most
six places or an error. Long note: docs/beatscript/ext-arith.md.

#Time finer than a bar

over 1/2 bar, over 2 beats, for 2 beats, every 2 beats, every 1/2 bar from 3, at bar 16 beat 3,
before drop 2 beats. A beat is a quarter of a bar.

BeatScript
section intro 4 bars {
  deck A: kick x ~ x ~ | hihat x*8 vel=50..80
  deck B: harmony chord(dm7)
  at bar 1 beat 2: master: filter lp 400 -> 3k over 2 beats     # a ramp half a bar long: it ends two beats after it starts
  at bar 2 for 3 beats: deck B: mute                              # muted for three beats, then put back
  before drop 1/2 bar: master: reverb 0.1 -> 0.7 over 2 beats   # the swell into the drop, a half bar ahead of it
}

section drop 8 bars {
  deck A: kick x x x x | snare ~ x ~ x | hihat x*8 vel=60..100
  deck B: bass d2 ~ d2 ~
  every 1/2 bar from 1: deck B: level 0.8                        # a pulse every half bar from the drop's second bar
  at bar 7 beat 5/2: master: delay 0.3                           # beat 2 and a half of bar 7
}

Canonical form: a duration prints N bars when N is whole (as it always did, 1 bars), else N beats when the beats are
whole, else P/Q bars in lowest terms (over 1/2 bar, over 2 beats and over 4/8 bars are one program, over 2 beats); a
position prints bar W or bar W beat B (after from, a whole bar stays a bare number). Every whole-bar spelling prints
exactly as before, so no CID moved. Long note: docs/beatscript/ext-timing.md.

#Tempo curves

tempo 100 -> 130 over 8 bars exp ramps the tempo and holds the end; a tempo in a section sets it from the section's
first bar; at bar 16: tempo 128 -> 140 over 4 bars is a timed one.

BeatScript
#! beatscript 2
tempo 100 -> 128 over 8 bars s-curve   # from the first bar: it speeds up through the intro, then holds 128
# ...
section build 8 bars {
  tempo 128 -> 140 over 6 bars exp                    # a tempo in a section runs from the section's first bar
# ...
}

section drop 16 bars {
  tempo 140                                           # a plain tempo holds until another one says
# ...
  at bar 12: tempo 140 -> 132 over 4 bars             # a timed line: it eases back before the end of the drop
}

section breakdown 8 bars {
  tempo 132 -> 90 over 8 bars log                     # fast at first, then it settles: the slowdown
# ...
}

Canonical form: tempo 100 -> 130 over 8 bars exp (linear is the default and is not printed); a plain tempo N prints as it
did; a timed line prints as a line (at bar 16: tempo 128 -> 140 over 4 bars). Long note: docs/beatscript/ext-tempo.md.

#Shapes and lfo

A ramp can go another way than straight: master: filter lp 300 -> 8k over 8 bars exp. A value can keep moving:
master: filter lp lfo sine 2 bars center=3k depth=1k.

BeatScript
section intro 8 bars {
# ...
  master: filter lp 300 -> 8k over 8 bars exp         # the riser: it opens slowly and then fast
  master: reverb 0.1 -> 0.6 over 8 bars s-curve       # a swell that is gentle at both ends
  deck B: level 0 -> 1 over 4 bars step 4             # four leaps of a quarter of the ramp each
}

section drop 16 bars {
# ...
  master: filter lp lfo sine 2 bars center=3k depth=1k            # a wub that lasts as long as the drop: 2k to 4k
  master: delay lfo tri 1 bar center=0.3 depth=0.2 phase=0.25 over 8 bars   # a triangle, a quarter of the way round, for 8 bars
  deck A: level lfo saw 4 beats center=0.8 depth=0.1              # a sawtooth a bar: it rises, falls back and rises again
  do vocoder set mix=0 -> 1 over 8 bars log                       # shapes work in `do` lines too
}
shape shape(t), t in 0..1 at 1/4, 1/2, 3/4 feel
linear t 1/4, 1/2, 3/4 the default, never printed
exp (2^(4t) - 1) / 15 1/15, 1/5, 7/15 slow start, fast end: a riser
log 1 - (2^(4(1-t)) - 1) / 15 8/15, 4/5, 14/15 fast start, slow end
s-curve 3t^2 - 2t^3 5/32, 1/2, 27/32 gentle at both ends
step N floor(t N) / (N - 1), at most 1 N held values, N - 1 leaps 2 <= N <= 1024

Canonical form: lfo sine 2 bars center=3000 depth=1000 over 16 bars: the wave, the period as a duration, the params sorted by
name with defaults left out, then over; a ramp's shape comes after its length. Long note: docs/beatscript/ext-shape.md.

#Degrees, numerals, a key a section

deg(1 b3 5' ~) writes degrees with accidentals and octave marks; Roman numerals (i VI III VII, V7/7) are chords of the key, as a
step or as the chord of chord() and arp(); a section may open with its own key; voice-lead moves chords as little as it can.

BeatScript
#! beatscript 2
tempo 96
key am

let tune = deg(1 3 5 ~ #7 1' 5 1,)

deck A: kick x ~ x ~ | hihat x*8 vel=60..90
deck B: harmony i VI III VII voice-lead | bass i VI III VII | melody tune

section verse 8 bars {
  deck B: arp i ii° V7/7 i voice-lead
}

section lift 8 bars {
  key cm
  deck B: arp i bII V7 i
}

arrange verse lift verse

Canonical form: deg(1 b3 5' 1,) one space apart, marks glued; a numeral's quality in its canonical case (VII° is vii°,
Idim7 is i°7, iaug is Iaug); voice-lead prints voice-lead=on; a section's key is its first line. Long note:
docs/beatscript/ext-scale.md.

#Euclidean rhythms and polymeter

e(k, n, rot) is checked and named; role/N gives a part a cycle of its own.

BeatScript
#! beatscript 2
tempo 122
key dm

deck A: kick e(4,16) | snare e(2,16,4) | hihat/12 x x ~ x vel=55..85
deck B: bass/12 e(5,12) oct=2 | melody/10 d4 ~ f4 ~ a4 vel=70..95 | harmony/32 chord(dm) ~ ~ chord(bb) oct=3

Canonical form: hihat/12 x x ~ x; /16 is the bar and is not printed; euclid(...) prints e(...); a rotation prints as typed
(e(3, 8, 10) and e(3, 8, 2) play the same notes and are two programs). Long note: docs/beatscript/ext-meter.md.

#Seeded chance

Parts that differ from bar to bar and are still a function of the text and the bar: x?0.3, choose [a b c] weights 3 1 1 seed=4,
maybe(p, 0.3, 4).

BeatScript
#! beatscript 2
tempo 128
key fm

section groove 16 bars {
  deck A: kick x ~ x ~ | hihat x*16?0.45 vel=45..85 | clap maybe([~ x ~ x], 0.8, 4)
  deck B: bass choose [f1 ab1 c2] weights 4 2 1 seed=4 ~ f1 ~ oct=1 | melody [c4 eb4 g4 ab4]?60% ~ c5?0.25 ~ inst=pwm-lead
}
arrange groove

Canonical form: x*8?0.7, choose [a b c] weights 3 1 1 seed=4, maybe([x ~ x ~], 0.3, 4); ?30% prints ?0.3; a seed prints only
when the term has its own. Long note: docs/beatscript/ext-chance.md.

#Composition: stack and then

A song is a composition of sections, and the two ways of composing them are in the language: stack(a, b) plays them at the same time,
then(a, b) one after the other, silence is the empty section, and a let names a composition.

BeatScript
section groove 8 bars {
  deck A: kick x ~ x ~ | snare ~ x ~ x | hihat x*8 vel=60..90
}

section wash 8 bars {
  deck B: harmony <chord(am) chord(f) chord(c) chord(g)>
}

section riff 4 bars {
  deck B: melody <a4 c5 e5 g5> | bass <a1 ~ c2 ~>
}
# ...
let verse = stack(groove, wash)

arrange intro stack(then(riff, riff), verse) coda
end after coda

Canonical form: the normal form of the laws; a plain arrange a b c prints as it always did; let both = stack(verse, intro) prints
stack(intro, verse); names are opaque (let both = stack(a, b) is not the text stack(a, b)). Long note: docs/beatscript/ext-algebra.md;
the categorical reading is under "Categorical notes".

#Typed ports

A def may declare a boundary: the values it needs (in:) and the values it makes (out:), each a type. wire changes.out -> walker.chords glues an output to an input, and the glue is checked.

BeatScript
def changes() out: chords {
  emit <chord(am7) chord(fmaj7) chord(cmaj7) chord(g7)>
}

def home() out: key {
  emit am
}

def walker(oct) in: chords, key out: bass {
  deck B: harmony $chords | melody markov($key, 0.5) oct=$oct
  emit [a2 ~ a2 ~ f2 ~ g2 ~]
}

def thump() in: bass {
  deck A: kick x ~ x ~ | bass $in
}

wire changes.out -> walker.chords
wire home.out -> walker.key
wire walker.out -> thump.in

walker(4)
thump()

Canonical form: def walker(oct) in: chords, key out: bass { (ports sorted by type); wire changes.out -> walker.chords (a sole port is written in / out); emit lines print as body tokens. A def with no ports is the
macro it always was. Long note: docs/beatscript/ext-ports.md; the cospan reading is under "Categorical notes".

#Mix moves: duck and mix

BeatScript
section drop 16 bars {
  deck A: kick x ~ x ~ | snare ~ x ~ x | hihat x*8 vel=60..90
  deck B: harmony chord(am7) inst=warm-pad | bass <a1 ~ c2 ~>
  duck B under A.kick 6db attack=5ms release=120ms
  mix {
    A level 0.85
    B level 0.7
    B eq low -6
    master level 0.9
  }
}

section break 8 bars {
  deck B: harmony chord(am7) inst=warm-pad
  mix { B level 0.9, master level 0.8 }
}

Canonical form: a duck prints both times, defaults filled in, always in ms (release=0.12s is release=120ms),
params sorted; a mix prints one item a line with each number as the value it comes to. Long note:
docs/beatscript/ext-mix.md.

#Sung lyrics

BeatScript
#! beatscript 2
deck A: kick x ~ x ~ | snare ~ x ~ x | hihat x*8 vel=60..90
deck B: bass a2 ~ e2 ~ | harmony chord(am) | melody <[a4 c5 e5 c5] [g4 b4 d5 b4]>

section verse 8 bars {
  # eight syllables on the melody's eight notes (it takes two bars to come round), sung over the whole section
  deck B: sing "lamps in the harbor, glowing slow" on melody voice=alto
}

section answer 4 bars {
  # a shorter lyric wraps over the two bars it is told to cover
  deck B: sing "hush _ lan-tern" on melody bars=2 voice=robot-choir
}

Found phrases: pick a line for its meter: https://beatscript.app/docs/found-phrases.md

The technique in full is docs/beatscript/found-phrases.md (borrow a public-domain line for its shape, keep the vocal low, cycle it buried and spotlit): trochees chant on the kick, iambs lilt on the offbeat, anapests and dactyls want a triplet feel; keep the vocal about A3 to F4; cross it onto the drums with @ vox xfer drm_shk. The MCP list_examples lists the lines (phrasebook true, or meter, syllables) and genre_template takes a phrase.

Canonical form: sing "robots on the road" on melody bars=2 key=am voice=alto (params sorted by name). Long note:
docs/beatscript/ext-sing.md.

#Assertions and btw test

A program can say what must be true of it.

text
# the statics: proved by `check`
assert ends                              # a song ends after its last section
assert length == 1m4s ± 2s               # 32 bars at 120 BPM
assert length < 2m
assert key == am in intro                # a section with no `key` of its own has the program's
assert key == dm in drop                 # the `key dm` at the head of the drop
assert key != dm in outro
assert period == 1                       # nothing here comes round over more than a bar

# the measured ones: pending at `check`, judged by `btw test`
assert level A > 0.2 * B in drop         # the drums are not buried under the bass
assert level A < 0.01 in outro           # deck A stops with the drop (what is left is the tail of its last notes)
assert level master > 0.01

# the constraints: about the notes, decided by `check` (examples/beatscript/constraints.beatscript)
assert never A.snare beside A.snare      # no two snares on neighbouring steps
assert never B during sing in verse      # deck B rests while the vocal is sung
assert bass ends on 1                    # every section lands on its own tonic
text
$ djctl btw test examples/beatscript/assert.beatscript
assert ends: the program ends at bar 32: pass
assert length == 1m4s ± 2s: the program is 1m4s: pass
assert level A > 0.2 * B in drop: A 0.110, B 0.129: 0.110 > 0.026: pass
10 assertions pass

Canonical form: statements print in order; a clock prints as minutes and seconds (90s is 1m30s); a level
expression folds constants and prints with one space round a binary operator. Long note: docs/beatscript/ext-assert.md.

#Performed inputs

knob(3), pad(5), fader(A), held(key) and held(c4) read the controllers while the program plays.

BeatScript
#! beatscript 2
deck A: kick x ~ x ~ | snare ~ x ~ x | hihat x*8 vel=60..90
deck B: harmony chord(am7) | bass a1 ~ a1 ~

master: filter lp knob(1)                  # a knob opens the filter: 60 Hz at 0, 20 kHz at 1, and follows it from the first bar
every 1/16 bar: master: reverb knob(2) when held(key)    # read 16 times a bar, only while a key is down
every 1 bars: master: filter lp 200 + knob(3) * 7800

every 1 bars: deck B: level 1 - fader(A)
master: reverb 0.1 -> 0.2 + knob(2) * 0.6 over 4 bars

every 1 bars: master: delay held(key) * 0.5 when held(key)
every 2 bars: deck A: low 0 when pad(5)                  # pad 5 kills deck A's low end for the bar it is held on
at bar 8: master: reverb 0.9 when held(c4) and knob(1) >= 0.5     # middle C and the first knob past halfway

master: filter hp lfo sine 2 bars center=500 + knob(1) * 400 depth=100 + fader(B) * 100
master: resonance 0.1 -> knob(2) over 4 bars exp
every 8 bars: duck B under A.kick 6db when held(key)

Canonical form: one spelling, knob(3), fader(A), held(c#4) (lower case, sharps); the performance is not in the
program's text or CID. Long note: docs/beatscript/ext-perform.md.

Two more #! header lines say what a program is and link it to the BeatScript ontology (https://beatscript.app/ontology/ns#).

BeatScript
#! beatscript 2
#! genre: https://beatscript.app/ontology/genre/techno
#! tags: acid, supersaw, four on floor, drop

tempo 128
key am

section intro 8 bars {
  deck A: kick e(4,16) | hihat e(5,8)
}

section drop 16 bars {
  deck A: kick e(4,16) | snare e(2,16,4) | hihat e(5,8)
  deck B: bass <a1 ~ c2 ~> | harmony chord(am)
}

arrange intro drop

Canonical form: nothing in the program's canonical text changes; the stored form of the links is full IRIs, tags
sorted and unique, genre first. Long note: docs/beatscript/ext-linked.md.

#Pattern sugar

Short ways to write patterns the language already has. Each one is written out to its longhand before the pattern is
played
, so it compiles to exactly the nets of that longhand, and btw same-as says so (crates/beatscript-api/tests/sugar.rs
proves every row against the longhand given here). The ideas come from TidalCycles and Strudel; the names, the
semantics and the code are BeatScript's own.

BeatScript
#! beatscript 2
tempo 124
key am

deck A: kick x~3 x | hihat ply([x ~ x x], 2) | clap poly(8, [~ ~ x])
deck B: bass c2~3 e2 | melody iter(off([a4 ~ c5 ~ e5 ~ ~ ~], 1, 12), 4)
sugar longhand idea from
c2~3 c2 ~ ~: the step takes three slots, rests in the two after it mini-notation @ (elongate), spelt ~ here
x? x?0.5 (x?? is x?0.5?0.5) mini-notation ? with no number
poly([a b], [c d e]), poly(4, [a b c]) each pattern walked n steps a bar as an alternation of the bars it takes to come round, stacked: [[a b], <[c d] [e c] [d e]>] polymeter {a b, c d e} and {..}%n
ply(p, n) *n on every step of p, groups and alternations opened: ply([c2 <e2 g2>], 3) is [c2*3 <e2*3 g2*3>] ply
palindrome(p) <[p] reverse(p)> palindrome
iter(p, n) <[p] rotate(p, -s) ... rotate(p, -(n-1)s)>, s the steps of p over n iter
off(p, n), off(p, n, k) [p, rotate(p, n)], [p, transpose(rotate(p, n), k)] off / superimpose

Canonical form: the sugar as typed (c2~3, ply([x x], 2)): formatting never writes it out, so c2~3 and c2 ~ ~ are
two programs with one song. The bare ? is the exception: it prints ?0.5.

#Not sugar yet (design notes)

These need something the nets or the language do not have today, so they are notes, not syntax:

#Call and response

One deck plays a call, another plays what the call leaves. rests(p) is a hit on every step where p rests, and
rests(p, q) is q, kept only on those steps. Write the call once, as a let, and give it to both decks: a let is text,
so editing it moves both decks together, and so does an arrange mutation of it.

BeatScript
#! beatscript 2
tempo 122
key am

let call = x ~ ~ x ~ ~ x ~
deck A: kick call
deck B: clap rests(call, [~ x ~ x ~ x ~ x]) | hihat rests(call) vel=50..75

The kick is a tresillo (steps 1, 4 and 7 of eight). The hat plays every step the kick leaves (2 3 5 6 8). The clap plays 2, 6
and 8 of its own pattern: its fourth step falls on the kick, so it is lost. Change call and both answers move.

Canonical form: rests(call), rests(call, [~ x ~ x]), as typed. Long note: docs/beatscript/ext-answer.md.

#Categorical notes

Three pieces of the language have an algebra, and the language keeps to it where it can be kept: the transforms of an
evolve, the composition of sections with stack and then, and the typed ports of a def. What each promises is
written here, with what it does not.

Evolve's transforms are a monoid. A transform is an endomorphism of the realised hits of a part (a part to a part
of the same shape). Writing them in a rule, rotate 1 | transpose 5, is composition in order, which is associative
and has an identity (transpose 0, rotate 0, octave 0): the transforms of one part form a monoid, and a rule
whose transforms do not mention gen makes generation n the n-fold composite f^n, iteration in that monoid. It is not
commutative (rotate 1 | reverse is not reverse | rotate 1). A rule that does mention gen, or thin, which hashes
the generation, is a sequence of endomorphisms (f_1, f_2, ...) rather than one repeated, and generation n is
f_n(...f_1(gen 0)): still a composite, no longer a power. Nothing about evolve changed with stack and then.

#Composition: stack and then, as a structure

A song is a composition of sections, and the two ways of composing them are in the language (above): arrange intro stack(then(riff, riff), verse) coda.

The structure. Give every section expression a length in bars: a section's own, then(a, b) is |a| + |b|,
stack(a, b) is max(|a|, |b|), silence is 0. Sections form a symmetric monoidal structure in the sense of
Hudak's music algebra (:+: and :=: of Haskore / Euterpea): a section of n bars is an arrow from bar line k to bar
line k + n, then is composition of arrows (end to start) with the 0-bar silence as identity, and stack is the
tensor of two arrows from the same line, padded to end together, with silence as its unit and the swap of its
operands as the braiding. Objects are the bar counts (the lines of the song), then composes, stack tensors,
silence is the unit, the braiding is the sort in the canonical form.

What the laws promise. The canonical form normalises exactly the axioms of that structure: associativity of
then and of stack (nested ones flatten), the unit (silence is dropped; a one-operand stack or then is its
operand; then(silence) is silence), and the symmetry of stack (its operands are sorted by canonical text, which
is the braiding made canonical). Programs equal by those laws have the same canonical text, so the same CID and the
same compiled song, and btw fmt shows the normal form. The length is a homomorphism: to (N, +, 0) for then
and to (N, max, 0) for stack. then is not commutative and is never reordered, and stack is not idempotent
(stack(a, a) plays a twice: two sections, which clash if they define one deck's role).

What then of parts means. Over parts the associativity law is on the text, and the music follows the canonical text:
then is a sequence, so a nested then flattens into it (then(then(a, b), c) is then(a, b, c) is kick <a b c>: bar 0
plays a, bar 1 b, bar 2 c, bar 3 a at its own second cycle when a alternates). It is never the alternation of an
alternation the nesting suggests (<<a b> c>, whose inner part advances once per visit): that is a different program, written as
the alternation it is, with its own CID.

What they do not. Equal music is not equal text. The interchange law, stack(then(a, b), then(c, d)) equal to
then(stack(a, c), stack(b, d)) when |a| = |c|, holds for what is played (the same notes in the same bars, so the
same nets of the song written out longhand) but it is not normalised: the two are different programs with different
CIDs. A section cut in two halves is not the section, because every section has its own clock (at bar N, every
and its alternations count from its first bar). A let names a composition and a name is opaque to the laws:
let both = stack(a, b) and stack(a, b) are not the same text. And the laws are about the shape of the
composition, not about the sounds: they say nothing about whether two sections sound alike.

#Ports and cospans

A def with ports is an open system with an interface, and wire composes two along the interface they
share. The nine port types form a preorder (a rhythm fits a bass, a melody or drums; each of those fits a pattern),
and an interface is a finite set of typed ports, each named by its type. A def with in: X out: Y is a cospan X → N ← Y (its apex has one cell for each port), decorated with what its body says: its lines, with a hole for each input
and for each parameter, and its emit function from the values of the inputs to the values of the outputs ("put the
inputs into the emit statements"). A wiring from one def to another is a set of pairs (output, input) with the types
fitting, a function on the inputs (each fed once) and arbitrary on the outputs (an output may feed many inputs, or
none: copying and discarding, as in a cartesian structure, and never a merge). The composite is the cospan whose apex
is the pushout of the two apexes (the two cells of a wired pair become one), with the lines of both and the
composed emit function. Imports are pinned by CID, so what is composed is exact modules.

What the language adds to cospans: no feedback. In the full cospan category a wire from a def's output to its own
input is a trace, and fine. Here it is an error (the wires make a loop), because a value that feeds itself has no
meaning for a macro that expands in finitely many steps: the wirings are the acyclic ones, a (cartesian) symmetric
monoidal category of modules, not the compact closed one. That is the totality rule of a def that calls itself,
again. The laws the tests hold (in crates/djlive/tests/ext_ports.rs): wiring is associative (any bracketing of a
chain, any cut of it, a saved snippet being one bracket, expands to the same lines); the order of the wire
statements does not matter; the module in: t out: t { emit $in } is the identity; independent modules compose in
parallel and the order of their calls is the braiding (it changes the order of lines, not the lines or the nets); the
value at an out port of a composite is the composite of the emit functions; a loop is reported exactly when the wiring
has one; the canonical form is a fixed point; and a def with no ports is the macro it was, with the same text, CID and
expansion.

#How long a program can be

A net is at most 64 bars: the piano roll that makes a deck's net (djrust::roll, from the Swift app) rings one place
per sixteenth step per part and refuses more than MAX_STEPS = 1024 (64 bars). It is a size bound, not an index width
(a step is an i64 there, a hit's step in its bar a u8): a net is a place, a transition and two arcs per step per part,
and the raw-nets envelope that carries it is JSON. A program is not a net. A deck whose parts take longer than 64 bars to
come round (an 80-bar alternation written longhand) is chained: cut into stretches of 64 bars, each its own net, loaded a bar
ahead and landing on the bar line the one before ends on. A section longer than its net is not chained (a 4-bar pattern
loops for 200 bars as one net); a section whose alternation is longer than 64 bars is; a program with no sections is
given a timeline of the bars its decks take to come round together, and loops, its at bar and every lines counting
program bars as they always did. The most one alternation may take to come round, and the most a timeline may add up to,
is 16,384 bars (9 hours at 120 BPM). What a stretch costs is the same whatever the program's length; the cap is not
raised because a longer net costs more than linearly in what matters live:

one net of JSON (8 parts, 2 decks) check envelope CID deck load peak RSS render speed
64 bars 1.1 MB 2.9 ms 8.9 ms 16 ms 0.60 s 223 MB x34 real time
128 2.2 MB 4.4 ms 16 ms 34 ms 1.03 s 426 MB x32
256 4.6 MB 8.4 ms 34 ms 70 ms 1.89 s 784 MB x28
512 9.2 MB 16.5 ms 69 ms 140 ms 3.57 s 1.58 GB x22
1024 18.8 MB 31.7 ms 137 ms 285 ms (not loaded)

(Measured with cargo run --release -p djlive --example net_cost, and djctl btw render on a build of the roll with the
cap lifted, on an M4 Pro at 124 BPM; the deck load is the wall time of rendering the first four bars.) Compiling is
linear and cheap; the engine's load is about 7 ms and 3 MB a bar, so a 256-bar net takes about a bar of real time to
load at 124 BPM and a 512-bar one two, on the window's thread, and the audio loop gets slower per second of sound as the
net grows. Chained, the same 512 bars load in 0.61 s (the first stretch) and render at x33.5, so a long track costs what a
64-bar one does at any moment. (The renders hold every stretch at once, so their peak memory is higher than a live
run's, which holds one stretch a deck.) Raising MAX_STEPS itself would be a change in the public engine and in the Swift
parity it keeps, for no gain a chain does not give.

Two extensions lengthen a net without an alternation, and both stay under the same 64 bars. A part with a cycle of its own
(hihat/12) comes round after lcm(N, 16) / 16 bars (/12 three, /10 five, /63 sixty-three), and a deck whose parts with
cycles take more than 64 bars to come round together is an error that names the parts and the way out (a long alternation
with no cycle of its own is still chained, as above). A part with chance is unrolled over the bars it needs to differ: 16
bars in a program with no sections, the section's length (up to 64) in a section, rounded up to whole copies of its
alternations and cycles. check reports the period of the program (period: 30 bars = 480 steps (...)) and the bars each
chance is unrolled over.

#Bounds on the text

The language is total, and so is the reading of it: every recursion in the reader and every multiplication in the
expander has a bound, and a program that crosses one is an error with a span, never a stack overflow, a hang or a
gigabyte. (The text of a share link is read by the editor thread, the control socket and btw open.)

what bound where it is said
nesting of groups [ ], alternations < >, calls and their arguments, deg( ), sections 64 deep, counted together an error at the opener that is too deep (a section's is the last thing read)
operators in one expression (+ - * / %, comparisons, and, or, not) 128 at the operator past it
a pattern's terms, with the lets in it put in place 16,384 terms and 128 levels deep, worked out from the text before anything is built at the let (or the part) that crossed it
events one part plays in one bar 4,096 at the term that crossed it; the work stops there
terms one bar of a part reads (nested *N of rests make no events) 8,192 the same
repeats and calls: the text they write out, counting each copy and each call a little even when it plays nothing about 2 million tokens at the repeat or call; the first nest more than 8 deep stops the expansion
lines 4,096 at the line (at the arrange when a section placed again and again is the cause)
a chain of lets of compositions 128 at the name past it

[[[x*64]*64]*64]*64 is 16.7 million hits and let b = a a, let c = b b, ... is 2^n terms in n lines: both were
built before anything counted them, and one more level never ended. A bar holds 16 steps, so 4,096 events is far
more than a part can use.

#Sets: programs of programs (design note)

A set is a program whose body is other programs, played one after another with the mixes between them. It is sequential
composition (∘) at program level: a set is a program, so it has a CID, a canonical form, a share link, a timeline and an end
like any other, and a set can play a set.

text
set {
  play hand-dubstep-140-v4
  mix 8 bars with filter_exit
  play matrix-130
  mix 16 bars with crossfade, tempo 140 -> 130
  play deep-house-60 until 20m
  play gen@2 techno seed=42
  mix 16 bars with crossfade
  next seed=+1
  mix 16 bars with echo_out
  next seed=~
  play yellow-rose-174
}
end

What a mix does on two decks. The engine has two decks, and a track plays its parts on both, so two tracks cannot each have
a deck to themselves for the overlap. The mix therefore puts both tracks' parts on the same two decks, one bar at a time (N
one-bar stretches of the timeline), with each deck's net rebuilt every bar:

These are approximations by velocity and swap: the engine's real filter and echo moves act on a whole deck, and during a mix
both tracks are on it. They are what two tracks on two decks can honestly do, and what the compiler can prove (check knows
every bar's levels), not a recording of a hand mix.

What check proves or plans (per mix, in the answer and as warnings):

Seen and heard as one timeline. A set compiles to an ordinary arranged program: one segment list and one control clock, so
the runtime, end, loop, the ended state, hot reload and anything that seeks or reads an arranged program treat it as one
timeline. A track's control lines (filters, do calls, ramps) move to the track's place in the set and run only while the
track does (every N bars stops at the track's end). The playhead sits on the play line of the current track and on the
mix line during a mix, so the follow-scroll goes track to track and mix to mix. What is not lit are tokens inside a
track: their text is the track's, not the set's. (The window shows the set's text; the track opens with btw load.)

A recorded set as a set. beatscript set-program <recording> (and the booth's record program) writes a recorded set back
out as a set, in the syntax above. Each tracklist line that is a saved program becomes a play, cut with until bar N where
the next track came in. The moves into it become one mix: its bars run from the incoming track's mark to the last move, a
move with no set spelling (a bass swap, a loop roll, a phrase sync, a vocoder handoff) is written as a crossfade under a
# performed: line, and tempo A -> B is added when the master tempo moved. A generator track (techno:7 with nothing
changed) is played as arrange from seed(techno, 7), which plays the generator's notes. Anything else (a mashup, a loop
set, a sample) is a # not a program: line, and its bars are said: the track before plays on through them, or, before the
first program, they are a # gap:. A sample makes the set use restricted and private. Beside the program it writes the
take, <cid>.take.json: the tracklist, the replay and the controls it was played with, naming the program by CID as a
performance does. A program is in a tracklist only when the booth marks it (record mark, kind track, its program CID).

Share links. The canonical text pins saved tracks by CID, and a generator call or a next is its own text, so a link of a
set is the set. A link carries its saved tracks' canonical texts (* section, each one checked against its CID on opening),
however long the link is, so it opens where no track is saved ("Share links").

Sets and the extensions (what the two bodies of work decided together). A set is checked by the whole compiler: each track
is compiled as any program is, with its arithmetic, tempo curve, chance, stack and then, ports, asserts and #! genre:
lines, so a set of such tracks checks, has a CID of its own and pins each track by the CID of its canonical text (a comment,
spacing or a header line of a track moves nothing; a number of its arithmetic moves the track and with it the set). What the
meeting settled:

#Radio: stations

A station is an endless, deterministic program of programs: position N of a station is always the same track. A station is
itself a BeatScript program (CC0, with a CID) that says where the walk starts, how it steps from track to track, and the forms
the tracks take in turn. Listeners do not steer a station; they tune it and lock its knobs.

BeatScript
#! name: techno radio
#! license: CC0-1.0
tempo 128
key am
station {
  from gen@2 techno seed=42
  next seed=~
  forms seeded passacaglia rondo fugue
}

Radio: a station is an endless program, track N always the same: station { } holds from gen@2 techno seed=42
(track 0), next seed=~ (the step) and forms seeded rondo fugue (in turn); MCP station and POST /api/station
give track n, its segue and neighbours; MCP artifact with station makes a page: https://beatscript.app/docs/radio.md

#Restricted sounds: local samples (design note)

A private set may play sounds it has no right to give away (your own Minecraft note-block samples, a sample pack
you bought) without the program, a link, the repo or any public store ever holding the bytes. The rules, before the
code:

BeatScript
use restricted                                       # the program says it is private (or the file header does)
sample harp from "~/samples/harp.wav" license restricted-private else bright-pluck
sample kick2 from "sha256:9f2c..." license cc-by
deck A: bass riff inst=harp

#Sounds

btw instruments (and describe btw) lists every voice the engine voices by itself (wobble-lead,
hoover, detuned-saw, pwm-lead, acid-bass and acid-square (a 303's; acid is acid-bass), the voice-* singers,
the stingers), the family words (bass, reese, sub, pad ...: a name that contains one plays that family's generic
voice; acid-bass and acid are a voice of their own, acid-lead is the generic saw bass), the drum kits and the sound
palettes. In a part:

param takes does
inst=wobble-lead a voice the part's instrument. An unknown name is an error with the nearest names; a family word (inst=reese) is accepted with a warning that it plays the generic saw bass, and which voices have a sound of their own. inst=acid-bass (or inst=acid) is a 303: ! accents, ^ slides, cutoff= res= env= accent= drive= turn its knobs
kit=drums-808 a kit a drum part's kit (set once the net has landed)
sound=synth:wobble-lead own, synth, synth:NAME, inst:NAME the role's sound option on the deck, set once the net has landed (DeckAction::SetRoleVoice)
route=td3 td3 a tonal part also fills the TD-3 editor's sixteen steps (note, octave shift, accent, slide, rest) once its net lands; do td3 write confirm=true sends it (a dry run unless confirmed)

A sing line (see "Sung lyrics") takes voice= from the same host: the formant presets (robot, robot-choir,
android, choir-aah, choir-ooh, soprano, bass-choir, talkbox) and the neural names (alto, tenor,
baritone, bass); the neural engine is not built, so a neural name plays on robot and check says so.

master: resonance 0.7 / deck A: resonance 0.2 -> 0.8 over 4 bars set the filter insert's resonance
(filter.res); any other insert param is do inserts set target=Master param=filter.mix value=0.5.

#Example: a whole track

docs/beatscript/hand-dubstep-140-v2.beatscript (saved as hand-dubstep-140-v2; rendered offline to
<local path>: 109.7 s, 64 bars at 140): an intro, a build whose
riser opens over eight bars and ends on the phrase line where the drop starts (with a loop_roll four bars
ahead of it by before drop 4 bars), a drop whose bass is the engine's wobble-lead voice (a checked
name) under a filter that opens and shuts once a bar, a breakdown, a second drop and an outro, from lets, one
def, sections and an arrange. The file is BeatScript 1 and stays so, since the tests pin its CID; beatscript fmt gives
the same track in BeatScript 2, with #! beatscript 2 first:

BeatScript
# hand-dubstep-140 v2: a whole track in one program.
# intro 8 · build 8 (the riser lands on the phrase line) · drop 16 · breakdown 8 · drop 2 16 · outro 8
tempo 140
key fm

# the parts, named once
let kicks = x ~ ~ ~ ~ ~ ~ ~ ~ ~ x ~ ~ ~ ~ ~
let snares = ~ ~ ~ ~ ~ ~ ~ ~ x ~ ~ ~ ~ ~ ~ ~
let hats = ~ ~ x ~ ~ ~ x ~ ~ ~ x ~ ~ x x ~
let wob_a = f1 ~ ~ f1 ~ ~ ab1 ~ f1 ~ ~ ~ eb1 ~ c1 ~
let wob_b = f1 ~ f1 ~ ~ ~ db1 ~ ~ ~ c1 ~ eb1 ~ eb1 ~
let lead_a = ~ ~ c4 ~ ab3 ~ ~ ~ f3 ~ ~ g3 ~ ab3 ~ ~
let lead_b = ~ ~ c4 ~ eb4 ~ ~ ~ db4 ~ c4 ~ ab3 ~ ~ ~
let changes = <chord(fm) chord(fm) chord(db) chord(db) chord(ab) chord(ab) chord(eb) chord(eb)>

# the drop's groove: the drums and the wobble bass on one deck, and a filter that opens and
# shuts once a bar (the wub), for as many bars as it is told
def groove(deck, bars) {
  deck $deck: kick kicks | snare snares | hihat hats | bass <wob_a wob_b> inst=wobble-lead
  repeat $bars every 1 bars {
    master: filter lp 300 -> 2800 over 1 bars
  }
}

section intro 8 bars {
  deck A: kick kicks | hihat hats vel=50..80
  deck B: harmony changes inst=warm-pad
  master: filter lp 400 -> 6000 over 8 bars
}

section build 8 bars {
  deck A: kick kicks | snare snares | hihat x*8 vel=50..100
  deck B: harmony changes inst=warm-pad | melody <lead_a lead_b> inst=pwm-lead
  # the riser: it opens over all eight bars and ends on the phrase line, where the drop starts
  master: filter hp 100 -> 5000 over 8 bars
  master: reverb 0.1 -> 0.5 over 8 bars
  # and the roll leads into it
  before drop 4 bars: move loop_roll on A over 4 bars
}

section drop 16 bars {
  master: filter off
  master: reverb 0.15
  groove(A, 16)
  deck B: melody <lead_a lead_b> inst=pwm-lead | harmony changes inst=warm-pad
}

section breakdown 8 bars {
  deck A: hihat x ~ x ~ vel=40..60
  deck B: harmony changes inst=warm-pad | melody <lead_a lead_b> inst=pwm-lead
  master: filter lp 6000 -> 1200 over 8 bars
  master: reverb 0.45
}

section drop2 16 bars {
  master: filter off
  master: reverb 0.15
  groove(A, 16)
  deck B: melody <lead_b lead_a> inst=pwm-lead | harmony changes inst=warm-pad
}

section outro 8 bars {
  deck A: kick kicks | hihat hats vel=40..70
  deck B: harmony changes inst=warm-pad
  master: filter lp 8000 -> 500 over 8 bars
}

arrange intro build drop breakdown drop2 outro
end after outro

#One song, two texts

examples/trance-138.beatscript is a 64-bar trance track (intro 16, breakdown 16, drop 24, outro 8) said with
lets, two defs, four sections and an arrange. crates/djlive/tests/fixtures/trance-138.live is the same song
written longhand: every part one 64-term <...> alternation with a rest bar wherever the part is out. They are
very different texts, and the song written out (Compiled::song_nets: one net per deck for the whole
timeline, a rest bar wherever a section does not have a part, velocity hashes taken at the song's bar) has
the same net CIDs as the longhand's own nets (crates/djlive/tests/trance.rs; djctl btw nets FILE):

text
$ djctl btw nets examples/trance-138.beatscript
program z4EBG9j5MMozvDkT1gTck6ZKTsqXctuNA25bzD86dkhc6buYuuB
deck A  z4EBG9jG8nT2p449McscV7ZSCfmUJDiFxFU26JpZhJ9hfBFgeLD  (the song written out longhand)
deck B  z4EBG9j8hbXoGqrw8qMseuz7BhibdkMiee4USmUaSyPRgJjiiLJ  (the song written out longhand)

$ djctl btw nets trance-138.live          # the longhand, 17 577 bytes against the song's 3 184
program z4EBG9jGbdqJ73AvEDLrPE8g2LuigXEfsG4o9sAsXqgod7JX6CY
deck A  z4EBG9jG8nT2p449McscV7ZSCfmUJDiFxFU26JpZhJ9hfBFgeLD
deck B  z4EBG9j8hbXoGqrw8qMseuz7BhibdkMiee4USmUaSyPRgJjiiLJ

What plays live is the sections' own nets swapped on the bar lines (so a section edit reloads only that section),
which are four small nets a deck, not one 64-bar loop: same notes, different CIDs, because a net's CID is of the
whole loop. The longhand form is the normal form to compare in. Differences that would break the equality are
reported, not hidden: a part with another instrument in another section has no single longhand (song_nets
says which). The longhand as it was first written names inst=supersaw, which the engine has no voice for (it
played the default lead): the checker now refuses it, and the song uses detuned-saw, so the test compares
against the longhand with that one name changed (and asserts that name is the only difference).

#Seeing it play

The desktop app's btw window lights what is playing, in the style of Strudel and Sonic Pi, and fills the screen when asked.

Where it comes from: the engine publishes where each deck is (its beat) to the UI, not a stream of fired transitions, and
that is the clock the runtime already runs on. Each frame (about 60 a second while a program runs) the runtime takes the
bars the clock moved through and calls a hit fired when its step's time fell in them (Live::watch_fires), so nothing
touches the audio thread and a test can fire the same spans on a fake clock. (A true event ring out of the net runner would
be a change in djrust.) The markers are for the text that was evaluated: edit it and they wait for the next Cmd+Enter.

The windowed panel folds the change plan under one line, plan: N changes (collapsed, remembered), with a summary
(+12 added · 3 changed · 1 removed) and a scroll area when opened; btw eval / btw get keep the full plan (changes,
plan) and plan_summary.

btw get carries it as marks, for a reader that is not the window (an MCP client, the web /p page): active_lines,
header (the section header's span and the playhead's progress), fires (role, deck, age_beats, the token's spans and its
call_sites), controls (the line, its span and via, age_beats, progress of a ramp, held), generation,
generation_flash_beats, evolve_spans. Every span is {start, end, line, col, len} in the evaluated text.
Screenshots: docs/layout-audit/btw/ (cargo test -p djapp btw_markers_shots -- --ignored, which plays
examples/markers-demo.beatscript on a fake clock).

#Evaluating and hot reload

eval parses, checks and compiles the text. Any error (a parse error, an unknown part or move, a range
that cannot be) means nothing is applied: the last good program goes on, and the errors come back with
line, column and a caret. A good program is staged and applied as follows:

  1. It is diffed against what runs. A deck whose parts compile to the same net (same net CID) is not
    touched. A deck whose net changed is loaded with the new net. A control statement already running
    (same text) keeps its state: a ramp goes on, a now line is not run again, an every keeps its
    schedule. A new or changed statement is added. A removed deck line pauses that deck on the next bar;
    a removed control line stops (a ramp stays where it got to).
  2. The apply happens in the first three beats of a bar (so the net is compiled well before the next
    line) and the engine installs it on the next bar line (Engine::load_prepared: "at the next bar
    when playing, at once when stopped"). When nothing plays it starts at once: the decks start. An
    evaluation sent in a bar's last beat is not applied then (there is no time to prepare it): it is
    applied in the next bar's first three beats and lands a bar later than "the next bar". The answer says
    which program bar it lands on (lands) and the window shows it.
  3. A deck's new net starts at the same place in its alternation (<a b>) the old one was at, so a
    kick edit does not send a <c4 e4> melody back to c4.

live check runs 1 and 2's checks and answers what would change, without staging it.

Four extensions have a word in how an edit lands. A tempo line is not a control: when an edit gives the program
another tempo map (and one of the two is not a single number) the plan says "tempo curve changed", and the running map
is replaced as the edit lands, the runtime going on from the program's position. A mix or duck whose line
is dropped by an edit is put back at once (the old line is put back; the edited line waits for its section to come
round, as every at bar line does). A sing line's identity is the line and the notes it is sung on, so the same
text over an edited melody sings again and an edit of nothing does not. A performed line is a control like any
other (an edit keeps its state), and the take being logged follows the program: applying another program ends the take
(it is kept as the last one, and can still be saved). A line the edit keeps keeps its state, and what its section's end gave it
moves with the section: lengthen a section that has a running mix or duck (held to the section's end) or an lfo
(stopping there) and they go on to the new end, shorten it and they stop sooner.

#Canonical form

The program CID is the share CID (z..., sha-256, CIDv1, base58) of a document that names the version ("Versions"):

A canonical text says its version by its first line alone (djlive::version::of_canonical), so whatever holds one hashes it
right with nothing beside it. The canonical text is the parse, printed again, so formatting never forks a program. A text's line ends do not matter: \n, \r\n and a lone \r (an old Mac file) are the same
newline, and a UTF-8 byte-order mark at the start is white space; an error's line and column are the same whichever way
the lines end. These do not change the CID:

normalised rule
whitespace, tabs, blank lines, indentation one statement a line, one space between tokens, blocks indented two spaces
line wrapping a deck's | continuation lines are one line
number spelling shortest form: 18k = 18000, 0.50 = 0.5, 50% = 0.5, 2.0 = 2
note, key and chord spelling lower case, flats as sharps: Bb4 = a#4, Bbm = a#m, BBMAJ7 = a#maj7, D:Dorian = d:dorian
order of params sorted by name, in a part (oct=2 vel=100) and in a do line
comments dropped: not in the CID, and not in the canonical text (the #! header lines are comments too: a name, the rights, genre, tags; the version line alone is kept, first, in BeatScript 2)
a scalar let its value is put where it is used
an import its snippet's CID replaces the name
a borrowed section or part kept as written: <cid>.drop has the source's full CID in it
free numbers a lone literal keeps the shortest spelling; arithmetic with no input in it is the number it comes to (level 0.25 + 0.25 is level 0.5, tempo 60 + 6 is tempo 66, e(1 + 2, 8) is e(3, 8)), a short decimal as that decimal and any other ratio as n / d (1 / 3); with an input in it the expression, its constant pieces folded (level knob(1) * 0.7, when knob(1) > 0.5)
counts, bars, lengths, degrees arithmetic folds to the whole number it comes to: x*(1 + 1) is x*2, section drop 4 * 4 bars is section drop 16 bars, at bar 2 + 2 is at bar 4
durations N bars when whole (1 bars), else N beats when the beats are whole, else P/Q bars in lowest terms: over 1/2 bar, over 4/8 bars and over 0.5 bars are over 2 beats
positions bar W when whole, else bar W beat B: at bar 3/2 is at bar 1 beat 2, at bar 8 beat 0 is at bar 8; after from a whole bar stays a bare number
a cycle, a euclid hihat/16 x is hihat x (/16 is the bar); euclid(3, 8) is e(3, 8); a rotation prints as typed (e(3, 8, 10) is not e(3, 8, 2))
chance ?30% and ?0.30 are ?0.3; ?0 is a rest and ?100% the bare term (x?1 is x); a seed= prints only when the term has its own
degrees, numerals deg(1 b3 5' 1,) one space apart with the marks glued; the letters of a quality in their canonical case, and the case of a numeral where the quality fixes it: VII° is vii°, Idim7 is i°7, iaug is Iaug; a bare voice-lead is voice-lead=on
stack, then, silence the laws of the structure: nested ones flatten, silence is dropped, a one-operand call is its operand, the operands of a stack are sorted by canonical text, a then is never reordered; arrange then(a, then(b, c)) is arrange a b c; over parts stack(...) prints as the | list sorted by text and then(...) as <p q>; a let of a lone name is the scalar let
def ports in: key, chords is in: chords, key (sorted by type); a sole port is written in / out in a wire once the def is known
shapes, lfo a ramp's linear is not printed (over 8 bars linear is over 8 bars); an lfo's params are sorted by name and depth=1, center=0, phase=0 are left out
duck, mix a duck prints both times, defaults filled in, in ms (release=0.12s is release=120ms) and 6.0db is 6db; a mix is one item a line, each number the value it comes to (A level 0.5 + 0.2 is A level 0.7)
sing the params sorted by name, the key spelled as everywhere
assertions a clock as minutes and seconds (90s is 1m30s, 500ms is 0.5s), a level expression with its constants folded
inputs one spelling: knob(3), fader(A), held(c#4) (a note in lower case with sharps)
launch launch drop on pad(2); the default line (next phrase, next phrase 8) says nothing, next bar and next phrase 16 / 32 are said
a guard printed after its line: ... when $i % 4 == 3

Doc comments. The # lines written directly above a section, let, def or arrange line, with no blank line
between, are that item's doc comment (djlive::doc). The editor's hover shows it above what it says of the name, at the
definition and at every use in arrange; check gives each documented section's entry in sections a doc, and lists
them all in docs ([{kind, name, doc}]); a shared program's JSON-LD gives each documented section its description. A
leading <name>: that repeats the item's name is dropped (# drop: the kick and the bass above section drop is "the kick
and the bass"), several lines are one paragraph, the hover trims it to about 280 characters, and a #! header line is never
one. They are comments all the same: a program has one CID with them, without them, or with other ones.

What is not normalised, because it is meaning: the order of statements, the order of sections, a pattern's
steps (x ~ x is not x x ~), the tokens of a def or repeat body (a macro: printed as written, one statement a line, one spacing rule for all, so
at bar $i + 1: master: level 0.5 when $i % 4==3 is a fixed point that is not pretty, and a stack in it is not sorted). Arithmetic is the number it comes to
(tempo 60 + 6 and tempo 66 are one program), but e(3, 8, 10) and e(3, 8, 2), emit c2, emit bass c2 and emit out c2 play the
same and are different programs. Names are opaque to the laws of stack and then (let both = stack(a, b) is not the text
stack(a, b)).
btw fmt prints exactly this text and its CID; share encodes exactly this text. The editor's fmt, the MCP fmt (text) and
beatscript fmt print it with the #! header lines, comments and blank lines between blocks kept, and upgrade: a BeatScript 1
text comes back in BeatScript 2, its version line first, with the BeatScript 2 CID (djlive::format::format_upgrading; from_cid
is the CID of the text given, and formatting twice is formatting once). beatscript fmt --keep-version formats and keeps the
version. Programs sent by eval, load, queue, share, push_private arrive formatted with their version kept
(djlive::format::format: the same CID), so a text is never upgraded without being asked. The tests (canonical.rs,
format.rs) reformat the repo's programs at random (spacing, tabs, comments, \| line breaks, number and note spellings) and demand
the same CID, a changed note another. Every extension has such tests (reformatting keeps the CID, an edit changes it, the
canonical text is a fixed point), examples_beatscript.rs for examples/beatscript/.

#Saved programs

A saved program is a licensed object, like a track (docs/LICENSING.md): the canonical text and its rights
(CC0-1.0 public by default, CC-BY-4.0, all-rights-reserved; public or private; an author, $DJ_AUTHOR by
default), forkedFrom (the parent program's CID) and its credits. btw fork records the parent, names the
forker as the author, and carries the license and credits on; it adds the parent with its author as a credit
whatever its license (a #! credit: line marked forked from), so every author up the fork chain stays in the
lineage. A program that imports a CC BY snippet is credited to it, down the fork chain. Two CIDs: the
program CID (of the text) is what links, imports and forkedFrom name; the object CID (text and rights) names the file, so a new license is a new object of
the same program.

A .beatscript file in <support>/live ($DJ_LIVE_DIR) is the program with #! header lines (comments to the
language, all but the version line), so any .beatscript runs as it stands (and a .btw file is still read):

BeatScript
#! beatscript 2
#! name: night bus
#! license: CC-BY-4.0
#! visibility: public
#! author: did:key:z6Mk...
#! forked-from: z4EBG9...
#! credit: z4EBG9... | did:key:z6Mk... | CC-BY-4.0 | the riffs
#! genre: https://beatscript.app/ontology/genre/techno
#! tags: https://beatscript.app/ontology/groove/four-on-floor, https://beatscript.app/ontology/instrument/acid
tempo 140
...

btw export {id, path} writes one anywhere on disk; btw import {path | text} and btw load {path} take one in
(its header's rights kept, a private one stays private). Older <cid>.json snippets are still read, as CC0
public. track save of a deck that plays a BeatScript program saves the program, not nothing.

The genre and tags lines link the program to the BeatScript ontology ("Links to the ontology"). They are read in any
spelling (techno, genre:techno, bw:Techno, an IRI) and kept as full IRIs, tags sorted and unique, genre first;
btw save {genre, tags} sets them; an unknown term is an error when the program is saved or imported (and a warning
in check). A change of genre or tags is a new object of the same program, as a new licence is; an object that links
to nothing is, byte for byte, the object it was before. #! skip-test: <why> is a header line for the examples
harness (the file needs a host to be tested): the store ignores it.

Beside each object <object cid>.beatscript the store writes <object cid>.jsonld, the program as linked data (btw jsonld {id} makes the same text again); it is derived, so a failure to write it never fails a save. A performance (a
take of a program's performed inputs, "Performed inputs") is a third kind of object, <cid>.perf.json, with a CID of
its own: it names its program by the program CID, so changing a program's tags or licence does not detach it. perform {do: list} lists them and btw replay {id} plays one back.

text
https://beatscript.app/#<CID>.<base64url(deflate(formatted text))>[.<sig>][*<base64url(deflate(programs))>]
https://beatscript.app/#<CID>.<base64url(deflate(canonical text))>[.<sig>][~<base64url(deflate(notes))>][*<base64url(deflate(programs))>]

btw share makes one: the sealed part is the CID and the program's formatted text (what fmt prints: the
canonical text with the #! header lines, the comments and one blank line between blocks kept), so a program
opens as it was written. The CID is still the canonical text's: the header lines and comments are in neither the
CID nor the signature, and come along unsealed (open says so). sig is the author's wallet signature over the
CID, carried as given (the wallet makes and checks it). The site's links are on https://beatscript.app unless
another origin is named. BeatScript links are made on beatscript.app only: a link made on an older host
(btw.bitwrap.io, beats.bitwrap.io/p#) still opens, since only the part after # is read, and none is made there. The
engine's form (second line, what the apps and the booth make) packs the canonical text; there ~notes carries the
comments, shown as unverified. btw open <url or CID> decodes it, parses and canonicalises the text, recompiles it and
recomputes the CID, and refuses a link whose CID is not its text's (refused: the link says z... but its text is z...). It answers the canonical text (what is stored and hashed) and the text formatted, with what the link
carried beside the program, for the editor. A link made before links carried the formatted text packs the
canonical text and opens as it always did; a text that is neither canonical nor formatted is a warning (the CID is
still its canonical text's); a CID alone is looked up in storage, where there is any.
A program that draws on others carries them. For an import or a set's tracks, the part after the * holds the canonical text of
each program it draws on, and of each of those in turn, by CID (what a program needs first). Each is hashed against its CID before
it is used, and a text that is not the program its CID names is refused (the program z... in this link is not the program it names),
so a link opens on a machine that has none of them, and whether it checks never depends on the machine. The * part is not sealed (the
CID is of the program alone) and is not signed. A link is as long as that makes it (over 2000 characters it says so); the programs
together may be 512 KiB, and past that no link is made. A program that imports one that is saved private is not shared, since the
link would carry its text.
A private program is never shared. A link over 2000 characters says so. The link seals the canonical text only: the genre and tags
lines and a program's performances are not in it (a link is the program; its links to the ontology are its author's statement about
it, kept with the saved object, as the licence is). Tonight's programs:

program canonical text link
hand-dubstep-140 778 bytes 405 characters
hand-proghouse-124 1236 bytes 545 characters
acid-rave-138 1256 bytes 498 characters
hand-dubstep-140-v2 (64 bars, six sections) 1863 bytes 819 characters

#Errors

text
error: expected a part's pattern, found `|`
  --> 3:14
   |
 3 | deck A: kick | snare ~ x
   |              ^ a part is `role pattern`, and this one has no pattern
   = expected: `x`, `~`, a note like c3, a degree like 3, `[`, `<` or a generator like e(5,8)
   = help: kick x ~ x ~

An extension's errors are of the same kind. A wire that joins two ports whose types do not fit:

text
error: type error: `groove.out` is a drums pattern, `walker.chords` wants chords
  --> 7:6
   |
 7 | wire groove.out -> walker.chords
   |      ^^^^^^^^^^^^^^^^^^^^^^^^^^^
   = help: a `chords` port carries chord symbols like am7 and fmaj7, Roman numerals like V7, or chord(am7) calls, as a pattern

Every diagnostic has a severity (error; warning, for what may be wrong; info, for what the check found out and has
nothing wrong to say about: a chance's period, a polymeter's period, the ontology's name for a rhythm, a pending render
assertion), a byte span, a line and column, a message, the
list of what was expected, what was found, and an optional help line. The caret form above is
render; live eval and live check return the same as JSON (diagnostics) with line, col,
end_col, message, expected, found, help.

#The btw noun

verb does
eval {text, name?} parse, check, compile and stage: lands on the next bar. On an error nothing changes and diagnostics says why; ok false. Answers ok, cid, nets (deck, or section@bar:deck, to net CID), changes (what the diff will do), lands, warnings, and the status; where the program has them also length (through the tempo curve), mix (the registry calls of its duck and mix lines) and lineage (an evolve's chain)
check {text} the same without staging
get the running program (canonical text, CID, since which bar), the section and the bar in it, what is staged, the last errors, warnings (a muted strip a program plays on, a tempo the host cannot set, a performed input nothing answers for), the decks it plays on, the tempo now (tempo, tempo_curve) and performed (the inputs it reads, whether it logs, the take's CID)
fmt {text?} the canonical form, its CID and the comments
save {name?, text?, license?, visibility?, author?, genre?, tags?} keep the running program (or text) as a licensed .beatscript object, with its links to the ontology; answers the CIDs, rights and warnings
load {id | path, eval?} a saved program (CID, part of one, name) or a .beatscript file; eval: true (the default) stages it
list the saved programs, with their rights, genre and tags
fork {id, name?, author?} a fork: forkedFrom, license, credits and links carried
license / visibility {id, value?} read or change them (a new object of the same program)
export {id, path} / import {path | text} .beatscript files on disk
share {id | text, sig?, notes?} the link
open {url, eval?} decode, recompile, verify; into the window, staged with eval
generation {gen, scope?, text?} the CID of generation gen of an evolve, made from generation 0 and the rule alone (no chain kept), with the evolve's tail and period
instruments the voices, family words, kits and palettes
jsonld {id? , text?} the program as JSON-LD: its CID, genre, tags, key, tempo, sections, rights, forkedFrom, credits and Euclidean rhythms
terms {kind?} the vocabulary the #! genre: and #! tags: lines are checked against: kind, local name, IRI and label of each term, and where the cached copy is from
test {text? | id?, sample_rate?} judge the program's assert statements: the static ones re-checked, the level ones measured on an offline render; each reported pass or fail with the measured values, and ok false when one fails
perform {do?} the performed inputs of the running program and the performance it has logged: status (default), start (a new take), stop (stop logging), save (keep the take as a performance object), list
replay {id} play a saved performance back: its program is evaluated afresh and its inputs read the performance's values, by bar, instead of the controllers
stop stop the program (the decks play on; the controls and ramps end; a strip a move muted is put back; a duck, a mix and a performed line's holds are put back)

From a shell, with no app: djctl btw fmt | check | share | open | render | test | nets | gen | save | instruments | jsonld | terms | replay. check prints errors and warnings with line and column (exit 1 on an error), the length of
the song through its tempo, and the notes the extensions make (the period, the chances, the performed inputs, the
rhythms the ontology names); test FILE [--sr N] [--json] exits 1 when an assertion fails; gen FILE N is
generation; nets FILE [--sections] prints the nets as CIDs (a song longer than 64 bars is chained nets with no single
CID: it says so, and --sections lists each section's; a song with no longhand form, because a part differs between
sections, still lists its sections with --sections); replay FILE|CID [OUT.wav] [--program FILE] [--bars N] [--sr N] [--beats N] plays a performance offline and prints the calls its control lines make (a value past the program's end is
refused). djctl btw render FILE OUT.wav [--sr N] [--beats N] plays a song's sections, nets and sounds offline
(docs/HEADLESS.md). --sr is 8000 to 192000 and --beats is 0 to 16384 (one number is read the same by test, render
and replay, and a word that is no number is an error); --bars is 1 to 16384.

The window's title is btw: the editor, ▸ section n/m beside the bar and phrase, errors with carets, what
will change, the CID and a name field, the saved programs. A deck that plays a program shows btw: <name>
and its section, bar and phrase where a track shows its genre and seed.

#The offline render

djctl btw render and btw test play a program without the app: djhost::beatscript_render turns the compiled song into an
arrangement (djrust.arrangement/1, which djapp_render also takes) and the offline renderer, the engine djapp plays
on, plays it. In it: each section's nets, loaded a bar before the section so they land on its bar line, and a deck
a section does not use stopped; a tempo curve, as a staircase of tempo-fader moves whose seconds add up exactly to
the integral (the fader reaches ±50 % of a net's own tempo, the engine's limit: a curve in one net that goes further
is held at the edge and djctl btw render prints a note:; sections make each net at the tempo it begins at);
duck (a trick live op: the engine's pump, which hears deck A's kick) and mix (param and master
actions, a section's snapshot put back where the section ends; with no mixer to read, what it goes back to is the
engine's starting positions), each placed on the exact beat it falls on and tagged with the tempo of the step it falls
in, every lines expanded over the render's length (at most 4096 firings of one line); and, with djctl btw replay ... OUT.wav, the mixer calls of a performance (a strip's volume, EQ and mute, the master level, the crossfader).
Not in it: every other control line, because the arrangement format has an op for those and for nothing else of
the registry: a filter, an insert, a do call, a ramp or an lfo, a move, a load, a queue and sing. So a
render has the song's notes, sounds, sections, tempo and mix, not its riser sweeps, and a level assertion about a
filter sweep measures a render without it. A program that has no end renders 16 bars unless --beats says; a
performed program renders with every input at 1/2.

beatscript render and beatscript listen (the site's render, and the stems) play a program as the browser's engine plays
it
(crates/beatscript-cli/RENDER.md): every control line's registry calls are read by a port of the page's own mapping
(site/web/js/engine-calls.js mapCall, held to it op for op) and played on the same djrust engine calls the page's Dj
makes: the mixer and its ramps and lfos, the insert filter and resonance, reverb and the master crush as the page has
them, the FX unit's drive, the vocoder, the Wheel (the page's own voice), kit= / sound=, and every move on the
booth's move scheduler (docs/PERFORM.md, which the page's MoveScheduler ports), on the render's clock and never the wall
clock: each lands on the next bar or phrase line after its line (the song's lines, counted from its first bar), as on the
page, and a strip it muted is put back on the first phrase line after it. What the page does not play yet (a delay, a
crush on a deck, a macro line, a duck) the render plays the booth's way. A line neither plays is named in its notes
(a phrase_sync that steps a seed: a program's deck plays its own nets, not a seed). A tempo curve is not followed (the
render runs at the opening tempo).

#Tests

crates/djlive has 122 unit tests (in the modules: rat, expr, dur, lex, scale, meter, chance,
algebra, ports, mixmoves, sing, tempo, shape, assertion, perform, linked, music, highlight) and
763 integration tests in 32 files (counted at commit 192a4b4):

file tests what it holds
tests/beatscript.rs, language.rs 37, 42 the base language: parser goldens, lets, defs, repeat, sections and arrange, after/before, for N bars, do, sugar, ramps, instruments, transforms, imports, determinism, the expansion cap; errors with line, column and message
tests/beatscript_runtime.rs, hot_reload.rs, marks.rs 13, 16, 10 a song on a fake clock (nets land on bar lines, controls count from their section, a move puts its strip back, stop), hot reload and diff, the editor's marks
tests/canonical.rs, evolve.rs, trance.rs 8, 13, 4 random reformatting keeps the CID, links seal their text; evolve; the 64-bar song equal to its longhand
tests/examples_beatscript.rs 2 every examples/beatscript/*.beatscript: compiles, canonical text is a fixed point, 40 reformattings keep the CID
tests/ext_arith.rs, ext_timing.rs, ext_tempo.rs, ext_shape.rs 21, 31, 22, 27 arithmetic and guards; sub-bar times on a fake clock; the tempo map (a law: bar_at(seconds_at(b)) == b, the seconds add up) and the runtime; shapes against hand formulas and lfos
tests/ext_scale.rs, ext_meter.rs, ext_chance.rs 47, 31, 34 degrees, numerals, voice leading (checked against an exhaustive search on 400 random cases); e() and role/N (periods, the ontology names); chance (golden hash values, the empirical rate over 4096 bars)
tests/ext_algebra.rs, ext_ports.rs 50, 52 the laws of stack and then (160 random compositions: re-association, unit insertion, operand permutation keep the CID; the song equals an independent oracle's longhand); the wiring laws (bracketing, order, identity, loops against a peeling oracle, 300 random graphs)
tests/ext_mix.rs, ext_sing.rs, ext_assert.rs, ext_assert_cross.rs 27, 27, 31, 14 duck and mix (a snapshot is put back whatever the song: 80 random songs); sing on fake voices; assertions and the length through the tempo map
tests/ext_perform.rs, ext_perform_cross.rs, ext_linked.rs 45, 21, 32 performed inputs (a live run with scripted controllers against the replay of its log, call for call); links and JSON-LD
tests/ext_cross.rs ... ext_cross7.rs 13, 15, 18, 18, 13, 12, 17 features that were built apart, joined, each test naming what it joins: the first two files arithmetic, guards and sub-bar times with ports, polymeter, chance and imports; then degrees and numerals with the rest; stack with keys, chance, cycles and wires; mix with arithmetic, sub-bar times and stacks; sing with defs, imports, stacks and chance; tempo curves and shapes with stacks, mixes and ports

crates/djhost: unit tests in beatscript_env (every verb of every noun reachable through do, the family words pinned to
the engine's own, the voices), live_store (rights, forks, import credits, .beatscript round trip, legacy files, links,
the JSON-LD pair, performances), beatscript_render, beatscript_test, beatscript_inputs, ontology, vocals, and the integration
tests tests/ext_linked.rs (14), beatscript_tempo.rs (9: a kick on every beat lands within 12 ms of the second the map
gives its beat; a duck heard under a curve) and beatscript_test_tempo.rs (5). crates/djctl: tests/btw_test_cmd.rs (7),
btw_replay.rs (4), ext_linked.rs (4). crates/djapp app_tests: the registry round trip over every btw verb,
the window's buttons, and the verbs on the real engine (fmt, instruments, share, open refusing a forgery, fork,
export, the deck panel's line, track save of a program deck; a duck on the real pump; a for mix reading the real
mixer; btw test measuring levels; performed inputs through the bindings; a performance kept and replayed).

#Decisions

The readings of the points the contract left open, each with its reason. Where a long note holds more, it is named.
(The orchestrator's log of how the features met is the end of docs/BEATSCRIPT-EXTENSIONS.md, section 5; the workers' own
logs are the "Decisions" of each docs/beatscript/ext-*.md.)

Names and reserved words (the syntax review, SYN-01)

Marks and comments (the syntax review)

Arithmetic and guards

Time and tempo

Shapes, lfo, mix

Degrees, meter, chance

Composition and ports

Sung lyrics, assertions, performed tier, links

Sets (the merge of origin/feat/btw-language, 2026-11)

Form extensions (sets, sections, parts, numbers; docs/beatscript/forms.md "Extensions")

A recipe's nested parts and its stored expansion (roadmap 6680)

#Not done

What the language does not do, as honestly as the long notes say it. (Each feature's note has the full list.)

The syntax review (what was found and left)

Sets

The base language

The offline render of djctl btw render and btw test carries the nets, the tempo curve, duck, mix and a
performance's mixer calls, and nothing else of the control lines: no filter, insert, do call, ramp, lfo, move, load,
queue or sing (the arrangement format has no op for a registry call). beatscript render and beatscript listen play the moves
too, all but a vocoder_handoff and a seed step, and in two readings: the control net starts filter_exit and echo_out
on the bar line their line fires on, the booth's scheduler starts the other moves on the next line after it, as the
booth does. A render holds a tempo ramp inside one net at ±50 % of the net's own tempo, and a program that has no end
renders 16 bars unless told. A level assertion about a filter sweep therefore measures a
render without the sweep, and a performed level, filter or do line is not in it whatever the inputs read. A deck
that comes in at a section starts on the section's bar line (it was started a beat ahead, so its notes fell a beat early).
The mix snapshot has no mixer to read there and goes back to the engine's starting positions.

Controllers. held(key) is the lowest key held over 127, so the lowest MIDI note (0, below any keyboard of the supported
controllers) reads like no key; a note-off lost because the controller was unplugged leaves held(c4) true until the next
press and release. A deck's tempo restored on stop is the deck's effective BPM (the fader's included).

Arithmetic and guards. Arithmetic in an evolve's own arguments (transpose (1 + 1)) and its when gen: they
stay literals, because numbers stand side by side there. Arithmetic on pitches, keys and patterns (c2 + 5). Guards
on let, def, section, tempo, key, swing and an evolve rule's lines. No functions beyond min and max
(floor, abs, round), no strings or string building. A bare x?1/4 is not read (write x?(1/4) or give the def
0.25). let r = 3*2 is the number 6 while let pat = 1*4 3*2 is a pattern (two terms: a value of more than one
expression is a pattern); a let of arithmetic that is not wanted as a number says which let it was where it fails
(bass pat), but is not refused. The tokens of one statement are not capped: a call with ten thousand arguments is read
(linearly), and only what recurses is bounded.

Time and tempo. A program with no sections has its bar 0 on the bar it was evaluated in, so its timed lines fall one bar
later in the offline render and in btw test (which start the music on bar 0) than they fire live when a deck was already playing
(a song is the same in both; the tempo curve is counted from the first bar you hear in both; "Time words"). Sections, generations and repeat ... every are whole bars (no section drop 1/2 bar); a def's
call takes no time between bar lines; a move's over is whole bars. The editor draws no progress bar on a tempo
line and get does not list the tempo map's pieces, only the tempo now. No tempo inside an evolve rule, and no
tempo that follows a deck (a tap, a sync): the program's tempo is the master. No lfo of a tempo, a pattern or a part
param (vel=lfo ...), no shape on a move or swap pairs, no random wave (it would need a seed in the text). A finished
tempo ramp's last tempo is sent again every bar until the program stops, so a manual nudge of a deck's tempo is put back
within a bar (to move the tempo by hand, stop the program or give it a plain tempo N, which is in its nets and not
driven; R-22). stop and end put the tempo back only for a deck whose tempo the host could say when the program was
applied (a deck with nothing on it is left where the ramp left it).

Keys, spelled two ways (L-19). am and a:minor, a and a:major play the same and are four programs, each a CID of its own
(and sing key= and assert key == inherit it). Folding the aliases would move the CID of every existing program that uses
the a:minor spelling, so it is deferred: the fix is to print a key's mode in one canonical word (am for the natural minor, a
bare a for major: the short spellings every old program uses) and to reread the long ones as them; it needs the pinned fixtures
checked and a note in "Decisions" for the programs it moves.

Hot reload. An edit that changes only a line's context (a section's length under an lfo with no over, a held for N bars
that was computed from it) keeps the running line's state, because the line's key (its section and canonical text) did not change:
the lfo stops, and a put-back falls, where the old program put them (L-20, R-05: reproduced on the fake clock, an edit of
the section from 8 to 16 bars leaves the lfo ending at bar 8). The fix is in runtime::apply: when a kept item's effect, timing or
hold differs from the new control's, re-derive its undo_at and LfoRun stop (or drop the run and let the line fire again).
It is the runtime fixer's (R-05) and is not in this run.

Degrees and meter. A numeral in a drum part is an error, not a hit. Voice leading does not run across the loop
point or from one section into the next and does not look ahead. No /9 inversion or figured bass (I6 is the added
sixth), no secondary dominants (V/V: the slash is an inversion only), and numerals do not follow a chromatic
alteration of the scale (the melodic minor's raised sixth and seventh: write #vi°, bVII, or use a:harmonic). A
section's key is not in btw get yet. The runtime shows no marker for where a part's own cycle begins. The
traditional names of rhythms are not in the ontology, so none is shown.

Chance. No chance on a control line, a section or a whole deck line, only on pattern terms; no chance in a
choose weight; ? after a rest is allowed and does nothing (and is not printed); maybe(p, 0) and maybe(p, 1) are calls and are
not folded to a rest or to p as x?0 and x?1 are. The window does not mark a hit a chance dropped (it is
not there to mark).

Composition and ports. stack and then are over sections and parts only: no composition of control lines, and
stack(a, b) oct=2 is an error. The interchange law and the other equalities of music are not normalised. import
does not bring a composition let (or sections, or assertions). A section with an evolve cannot be stacked. A stack
of unequal sections reloads a deck's net at the boundary when the alternation's phase moves, and the playhead carries
one header (the one that ends last). after NAME of a section that plays more than once is still an error. Two ports
of one type on a side (they would need names), parameters in an emit or the producer's arguments in a wire, a
default for an unwired input, a wire inside a section or a def, and feedback (on purpose) are not in. Arithmetic in a
bars or tempo emit is not range-checked. No editor feature (a jump from a wire to its def); the wiring is not in
btw get.

Mix and sing. A duck keyed by a part that is not low (a snare, a hat, a melody) needs a detector or a hit-keyed
gain stage in the engine. An attack that is a parameter of the pump, and a release in milliseconds rather than a note.
A strip pan. mix inside evolve rules. No neural voice: the engine, its models and their pinned download do not
exist yet (vocals::NEURAL_ENGINE_BUILT is false); the fallback is what runs. A sung line is not stopped when its
section ends (it loops on the loop row until stopped), starts on the loop row's own boundary, does not follow an
evolve (it sings generation 0), and has no melisma, no word split over a rest, and only English with the
dictionary's own spelling-to-sound rules.

Assertions. The window draws no panel of assertion states and check's answer carries the pending notes as
diagnostics, not an assertions list. A level is measured per deck strip and the master, not per part or instrument
(A.kick). No assertion on tempo or on the number of parts, and no assert inside a section for its own bars (use in).
The constraints on notes are never beside, never during and ends on only (no distance in steps, no chord shapes); a
vocal timed every N bars or by a key cannot be judged and says so.

Launch. No latched pad: a tap shorter than a frame of the booth is missed. No per-device bank (launch drop on pad(2) is the first attached device's pads, as pad(2) is), no launch inside a block or a section, and no scene that carries a generation or a mutation over. The page and the phone have no pads: the song plays as written.

Performed inputs. No input in an evolve rule's number (deferred, with the reason in "Decisions"), in a let, in
a pattern, or in a guard on a def's call. A pad is not latched: a tap between two bar lines is missed. No knob and
pad banks for the Inpulse and the TD-3, and no per-device choice of bank (knob(3) of the second device). A take that
begins mid-program replays from bar 0, and a performance of a program that was edited while it played is a take of the
program running at the end of it. The window does not show the performance (the Map shows the controls glowing): the
verbs and btw get do.

Links to the ontology. No refresh from inside the app (the script refreshes the snapshot; a refresh that drops a
term leaves old programs readable but their next save asks for another). No folk rhythm names. A tempo that moves is
not in the JSON-LD (tempo is the program's own setting). No SHACL or OWL validation, and the djrust: namespace is not
published (the @context is: https://beatscript.app/context/v1.jsonld; btw jsonld --inline spells it out). No genre-aware checks (tempo against the genre's bw:bpm, key against
its scale). The window does not show the links.

View source (the raw markdown of this page, for models and scripts)