AddRegion, RemoveRegion and MoveRegion now refuse an edit whose written text would read differently from the nodes, as when a comment that never ends takes in the text after it, and an instrument whose regions were changed other than by Apply. Build refuses an unknown trigger and an empty random range. Add tests for edits across files, defines, skipped regions and edge cases, a random-sequence test and FuzzRegionEdits. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
500 lines
17 KiB
Go
500 lines
17 KiB
Go
package sfz
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"math"
|
|
"path"
|
|
"slices"
|
|
"sort"
|
|
"strconv"
|
|
"strings"
|
|
)
|
|
|
|
// BuildOptions change how [Build] lays out a document. The zero value makes one
|
|
// file, with each value written out where it is used and an indent of two
|
|
// spaces.
|
|
type BuildOptions struct {
|
|
// Indent is what the line of an opcode starts with. The default is two
|
|
// spaces.
|
|
Indent string
|
|
// SplitFiles puts the regions into included files, RegionsPerFile at a time,
|
|
// and leaves the controls, curves and variables in the main file.
|
|
SplitFiles bool
|
|
// RegionsPerFile is how many regions each included file holds, when
|
|
// SplitFiles is set. The default is 64.
|
|
RegionsPerFile int
|
|
// FileNamer returns the path of an included file, given its number from 0,
|
|
// relative to the main file's folder, when SplitFiles is set. The default
|
|
// gives regions/001.sfz, regions/002.sfz and so on.
|
|
FileNamer func(index int) string
|
|
// Variables writes a #define for each value that at least MinRepeat regions
|
|
// share, and sets default_path to the folder that all the samples are in.
|
|
Variables bool
|
|
// MinRepeat is how many regions must share an opcode's value for the value
|
|
// to become a variable, when Variables is set. The default is 8.
|
|
MinRepeat int
|
|
}
|
|
|
|
// defaults sets each option that has its zero value to its default.
|
|
func (o *BuildOptions) defaults() {
|
|
if o.Indent == "" {
|
|
o.Indent = " "
|
|
}
|
|
if o.RegionsPerFile <= 0 {
|
|
o.RegionsPerFile = 64
|
|
}
|
|
if o.FileNamer == nil {
|
|
o.FileNamer = func(i int) string { return fmt.Sprintf("regions/%03d.sfz", i+1) }
|
|
}
|
|
if o.MinRepeat <= 0 {
|
|
o.MinRepeat = 8
|
|
}
|
|
}
|
|
|
|
// defaultRegion returns a region that sets nothing, which has the format's
|
|
// defaults.
|
|
func defaultRegion() Region {
|
|
return Region{
|
|
HighKey: 127, RootKey: defaultRootKey, LowVelocity: defaultLowVelocity, HighVelocity: 127,
|
|
KeyTrack: 100, VelocityTracking: 100, Envelope: DefaultEnvelope, Trigger: defaultTrigger,
|
|
SequenceLength: 1, SequencePosition: 1, HighRandom: 1, OffMode: defaultOffMode, OffTime: defaultOffTime,
|
|
}
|
|
}
|
|
|
|
// NewRegion returns a region of the sample that has the format's defaults for
|
|
// everything else: it plays from key 0 to 127 at any velocity, on attack, as
|
|
// the only note of its round robin. A [Region] made any other way has to set
|
|
// each of these itself, as [Build] and [Instrument.AddRegion] refuse a region
|
|
// that can't be read back as it is, such as one with an empty Trigger.
|
|
func NewRegion(sample string) Region {
|
|
r := defaultRegion()
|
|
r.Sample = sample
|
|
return r
|
|
}
|
|
|
|
// triggers returns the values that trigger can have.
|
|
func triggers() []string {
|
|
info, _ := Lookup("trigger")
|
|
return info.Options
|
|
}
|
|
|
|
// checkRegion returns an error saying why a region can't be written as it is:
|
|
// the opcodes for it would be empty, or would be read as something else, or
|
|
// would never match a note.
|
|
func checkRegion(r Region) error {
|
|
switch {
|
|
case r.Sample == "":
|
|
return errors.New("the sample is empty")
|
|
case r.Trigger == "":
|
|
return errors.New("the trigger is empty")
|
|
case !slices.Contains(triggers(), r.Trigger):
|
|
return fmt.Errorf("the trigger %q isn't one of %s", r.Trigger, strings.Join(triggers(), ", "))
|
|
case r.OffMode != "fast" && r.OffMode != "time" && r.OffMode != "normal":
|
|
return fmt.Errorf("the off mode %q isn't fast, time or normal", r.OffMode)
|
|
case r.SequenceLength < 1 || r.SequencePosition < 1:
|
|
return errors.New("the sequence length and position start at 1")
|
|
case r.HighRandom <= r.LowRandom:
|
|
return errors.New("the random range is empty, so the region never plays")
|
|
case r.HighKey < r.LowKey:
|
|
return errors.New("the highest key is below the lowest")
|
|
case r.HighVelocity < r.LowVelocity:
|
|
return errors.New("the highest velocity is below the lowest")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// opcodeLine is an opcode to write, with its value as text.
|
|
type opcodeLine struct{ name, value string }
|
|
|
|
// num returns a number as text, with the fewest digits that read back as the
|
|
// same number.
|
|
func num(v float64) string { return strconv.FormatFloat(v, 'f', -1, 64) }
|
|
|
|
// scaled returns a condition's limit as text in the unit of its opcode, which
|
|
// is the limit times scale. It is rounded so that a limit that was a whole
|
|
// number in that unit is written as one.
|
|
func scaled(v, scale float64) string { return num(math.Round(v*scale*1e9) / 1e9) }
|
|
|
|
// Build makes a new document that describes the instrument. Reading it with
|
|
// [Document.Flatten] and [Flat.Instrument] gives the instrument back, except
|
|
// for what the model doesn't hold: the opcodes it doesn't read, and which
|
|
// headers the regions were under. It returns an error wrapping [ErrInvalid] if
|
|
// something in the instrument, such as a sample path or a label, can't be
|
|
// written as the value of an opcode, or if a region can't be read back as it is
|
|
// (see [NewRegion]).
|
|
func Build(inst *Instrument, opts ...BuildOptions) (*Document, error) {
|
|
var o BuildOptions
|
|
if len(opts) > 0 {
|
|
o = opts[0]
|
|
}
|
|
o.defaults()
|
|
|
|
regions := make([][]opcodeLine, len(inst.Regions))
|
|
for i := range inst.Regions {
|
|
if err := checkRegion(inst.Regions[i]); err != nil {
|
|
return nil, fmt.Errorf("%w: region %d: %w", ErrInvalid, i, err)
|
|
}
|
|
regions[i] = regionOpcodes(inst.Regions[i])
|
|
}
|
|
|
|
var control []opcodeLine
|
|
var defines []opcodeLine
|
|
if o.Variables {
|
|
prefix := samplePrefix(inst.Regions)
|
|
if prefix != "" {
|
|
control = append(control, opcodeLine{"default_path", prefix})
|
|
for i := range regions {
|
|
regions[i][0].value = strings.TrimPrefix(regions[i][0].value, prefix)
|
|
}
|
|
}
|
|
defines = hoist(regions, o.MinRepeat)
|
|
}
|
|
for _, c := range inst.Controls {
|
|
if c.Label != "" {
|
|
control = append(control, opcodeLine{fmt.Sprintf("label_cc%d", c.Controller), c.Label})
|
|
}
|
|
control = append(control, opcodeLine{fmt.Sprintf("set_hdcc%d", c.Controller), num(c.Value)})
|
|
}
|
|
|
|
var global []opcodeLine
|
|
if k := inst.Keyswitches; k != nil {
|
|
global = append(global, opcodeLine{"sw_lokey", strconv.Itoa(k.Low)}, opcodeLine{"sw_hikey", strconv.Itoa(k.High)})
|
|
if k.Default != nil {
|
|
global = append(global, opcodeLine{"sw_default", strconv.Itoa(*k.Default)})
|
|
}
|
|
}
|
|
|
|
b := &builder{indent: o.Indent}
|
|
for _, d := range defines {
|
|
b.define(d.name, d.value)
|
|
}
|
|
if len(control) > 0 {
|
|
b.header("control", control)
|
|
}
|
|
b.curves(inst)
|
|
if len(global) > 0 {
|
|
b.header("global", global)
|
|
}
|
|
if !o.SplitFiles {
|
|
for _, ops := range regions {
|
|
b.header("region", ops)
|
|
}
|
|
if b.err != nil {
|
|
return nil, b.err
|
|
}
|
|
return &Document{Root: b.file("")}, nil
|
|
}
|
|
|
|
// Each run of regions goes in a file that the main file includes.
|
|
if b.err != nil {
|
|
return nil, b.err
|
|
}
|
|
main := b.file("")
|
|
for i := 0; i*o.RegionsPerFile < len(regions); i++ {
|
|
chunk := regions[i*o.RegionsPerFile : min(len(regions), (i+1)*o.RegionsPerFile)]
|
|
cb := &builder{indent: o.Indent}
|
|
for _, ops := range chunk {
|
|
cb.header("region", ops)
|
|
}
|
|
if cb.err != nil {
|
|
return nil, cb.err
|
|
}
|
|
name := path.Clean(o.FileNamer(i))
|
|
if nodes := lex(`#include "` + name + `"`); len(nodes) != 1 || nodes[0].Kind != KindInclude || nodes[0].Value != name {
|
|
return nil, fmt.Errorf("%w: %q can't be the path of an included file", ErrInvalid, name)
|
|
}
|
|
child := cb.file(name)
|
|
main.Nodes = append(main.Nodes,
|
|
&Node{Kind: KindInclude, Raw: `#include "` + name + `"`, Value: name, Resolved: name, File: child},
|
|
&Node{Kind: KindSpace, Raw: "\n"})
|
|
}
|
|
main.dirty = true
|
|
return &Document{Root: main}, nil
|
|
}
|
|
|
|
// builder writes the text of a file and lexes it into a [File].
|
|
type builder struct {
|
|
// indent is what the line of an opcode starts with.
|
|
indent string
|
|
// text is what has been written.
|
|
text strings.Builder
|
|
// err is the first thing that couldn't be written.
|
|
err error
|
|
}
|
|
|
|
// line writes a line of text.
|
|
func (b *builder) line(s string) {
|
|
b.text.WriteString(s)
|
|
b.text.WriteString("\n")
|
|
}
|
|
|
|
// header writes a header, and a line for each of its opcodes. It sets err for
|
|
// an opcode that can't be read back as it is written.
|
|
func (b *builder) header(name string, ops []opcodeLine) {
|
|
b.line("<" + name + ">")
|
|
for _, op := range ops {
|
|
if err := checkOpcode(op.name, op.value); err != nil && b.err == nil {
|
|
b.err = err
|
|
}
|
|
b.line(b.indent + op.name + "=" + op.value)
|
|
}
|
|
}
|
|
|
|
// define writes a #define, or sets err if it can't be read back as written.
|
|
func (b *builder) define(name, value string) {
|
|
if err := checkDefine(name, value); err != nil && b.err == nil {
|
|
b.err = err
|
|
}
|
|
b.line("#define " + name + " " + value)
|
|
}
|
|
|
|
// file returns what the builder has written, lexed, as a file with the path p.
|
|
func (b *builder) file(p string) *File {
|
|
f := &File{Path: p, Nodes: lex(b.text.String())}
|
|
return f
|
|
}
|
|
|
|
// curves writes a <curve> header for each custom curve that a region's
|
|
// modulation uses.
|
|
func (b *builder) curves(inst *Instrument) {
|
|
seen := map[int]bool{}
|
|
var indexes []int
|
|
points := map[int][]CurveStop{}
|
|
for _, r := range inst.Regions {
|
|
for _, m := range r.Modulations {
|
|
if len(m.Points) > 0 && !seen[m.Curve] {
|
|
seen[m.Curve] = true
|
|
indexes = append(indexes, m.Curve)
|
|
points[m.Curve] = m.Points
|
|
}
|
|
}
|
|
}
|
|
sort.Ints(indexes)
|
|
for _, i := range indexes {
|
|
ops := []opcodeLine{{"curve_index", strconv.Itoa(i)}}
|
|
for _, p := range points[i] {
|
|
ops = append(ops, opcodeLine{fmt.Sprintf("v%03d", p.At), num(p.Value)})
|
|
}
|
|
b.header("curve", ops)
|
|
}
|
|
}
|
|
|
|
// samplePrefix returns the folder, with its slash, that every sample is in, or
|
|
// "" if there is no folder that they all are.
|
|
func samplePrefix(regions []Region) string {
|
|
if len(regions) == 0 {
|
|
return ""
|
|
}
|
|
prefix := path.Dir(regions[0].Sample)
|
|
for _, r := range regions {
|
|
for prefix != "." && prefix != "/" && !strings.HasPrefix(r.Sample, prefix+"/") {
|
|
prefix = path.Dir(prefix)
|
|
}
|
|
}
|
|
if prefix == "." || prefix == "/" {
|
|
return ""
|
|
}
|
|
return prefix + "/"
|
|
}
|
|
|
|
// hoist replaces the values that at least min regions share with variables, and
|
|
// returns the definitions of the variables. The sample, the first opcode of a
|
|
// region, and values with spaces or variables are left alone. The names end in
|
|
// a run of three letters, so that none is the start of another.
|
|
func hoist(regions [][]opcodeLine, min int) []opcodeLine {
|
|
type key struct{ name, value string }
|
|
counts := map[key]int{}
|
|
for _, ops := range regions {
|
|
seen := map[key]bool{}
|
|
for _, op := range ops[1:] {
|
|
k := key{op.name, op.value}
|
|
if !seen[k] && !strings.Contains(op.value, "$") && !strings.ContainsAny(op.value, " \t") {
|
|
seen[k] = true
|
|
counts[k]++
|
|
}
|
|
}
|
|
}
|
|
var shared []key
|
|
for k, n := range counts {
|
|
if n >= min {
|
|
shared = append(shared, k)
|
|
}
|
|
}
|
|
sort.Slice(shared, func(i, j int) bool {
|
|
if shared[i].name != shared[j].name {
|
|
return shared[i].name < shared[j].name
|
|
}
|
|
return shared[i].value < shared[j].value
|
|
})
|
|
names := map[key]string{}
|
|
var defines []opcodeLine
|
|
for i, k := range shared {
|
|
suffix := string([]byte{byte('A' + i/676%26), byte('A' + i/26%26), byte('A' + i%26)})
|
|
name := "$" + strings.ToUpper(k.name) + "_" + suffix
|
|
names[k] = name
|
|
defines = append(defines, opcodeLine{name, k.value})
|
|
}
|
|
for _, ops := range regions {
|
|
for i := 1; i < len(ops); i++ {
|
|
if name, ok := names[key{ops[i].name, ops[i].value}]; ok {
|
|
ops[i].value = name
|
|
}
|
|
}
|
|
}
|
|
return defines
|
|
}
|
|
|
|
// fieldLine is an opcode to write, with the field of [Region] it is read into.
|
|
// The field for a setting of the envelope is named as Envelope.Delay is.
|
|
type fieldLine struct {
|
|
field string
|
|
opcodeLine
|
|
}
|
|
|
|
// regionOpcodes returns the opcodes that make a region, starting with its
|
|
// sample, leaving out those that would only set the format's defaults.
|
|
func regionOpcodes(r Region) []opcodeLine {
|
|
lines := regionLines(r, false)
|
|
out := make([]opcodeLine, len(lines))
|
|
for i, l := range lines {
|
|
out[i] = l.opcodeLine
|
|
}
|
|
return out
|
|
}
|
|
|
|
// regionLines returns the opcodes that make a region, starting with its sample,
|
|
// each with the field it is read into. The opcodes that would only set the
|
|
// format's defaults are left out unless all is set. An optional setting that
|
|
// the region doesn't have, such as a loop mode, has no opcode either way.
|
|
func regionLines(r Region, all bool) []fieldLine {
|
|
d := defaultRegion()
|
|
out := []fieldLine{{"Sample", opcodeLine{"sample", r.Sample}}}
|
|
add := func(field string, nonDefault bool, name, value string) {
|
|
if all || nonDefault {
|
|
out = append(out, fieldLine{field, opcodeLine{name, value}})
|
|
}
|
|
}
|
|
add("LowKey", r.LowKey != d.LowKey, "lokey", strconv.Itoa(r.LowKey))
|
|
add("HighKey", r.HighKey != d.HighKey, "hikey", strconv.Itoa(r.HighKey))
|
|
if r.RootFromSample {
|
|
add("RootKey", true, "pitch_keycenter", "sample")
|
|
} else {
|
|
add("RootKey", r.RootKey != d.RootKey, "pitch_keycenter", strconv.Itoa(r.RootKey))
|
|
}
|
|
add("LowVelocity", r.LowVelocity != d.LowVelocity, "lovel", strconv.Itoa(r.LowVelocity))
|
|
add("HighVelocity", r.HighVelocity != d.HighVelocity, "hivel", strconv.Itoa(r.HighVelocity))
|
|
add("KeyTrack", r.KeyTrack != d.KeyTrack, "pitch_keytrack", num(r.KeyTrack))
|
|
add("Tune", r.Tune != 0, "tune", num(r.Tune))
|
|
add("Volume", r.Volume != 0, "volume", num(r.Volume))
|
|
add("Pan", r.Pan != 0, "pan", num(r.Pan))
|
|
if r.Width != nil {
|
|
add("Width", true, "width", num(*r.Width))
|
|
}
|
|
add("Offset", r.Offset != 0, "offset", strconv.FormatInt(r.Offset, 10))
|
|
add("VelocityTracking", r.VelocityTracking != d.VelocityTracking, "amp_veltrack", num(r.VelocityTracking))
|
|
for _, p := range r.VelocityCurve {
|
|
add("VelocityCurve", true, fmt.Sprintf("amp_velcurve_%d", p.Velocity), num(p.Gain))
|
|
}
|
|
crossfade := func(field string, c *Crossfade, which string) {
|
|
if c == nil {
|
|
return
|
|
}
|
|
add(field, true, "xfin_lo"+which, strconv.Itoa(c.FadeInLow))
|
|
add(field, true, "xfin_hi"+which, strconv.Itoa(c.FadeInHigh))
|
|
add(field, true, "xfout_lo"+which, strconv.Itoa(c.FadeOutLow))
|
|
add(field, true, "xfout_hi"+which, strconv.Itoa(c.FadeOutHigh))
|
|
if c.Curve == CrossfadeGain {
|
|
add(field, true, "xf_"+which+"curve", "gain")
|
|
}
|
|
}
|
|
crossfade("KeyCrossfade", r.KeyCrossfade, "key")
|
|
crossfade("VelocityCrossfade", r.VelocityCrossfade, "vel")
|
|
e, de := r.Envelope, d.Envelope
|
|
for _, s := range []struct {
|
|
field, name string
|
|
v, d float64
|
|
}{
|
|
{"Envelope.Delay", "ampeg_delay", e.Delay, de.Delay}, {"Envelope.Attack", "ampeg_attack", e.Attack, de.Attack},
|
|
{"Envelope.Hold", "ampeg_hold", e.Hold, de.Hold}, {"Envelope.Decay", "ampeg_decay", e.Decay, de.Decay},
|
|
{"Envelope.Sustain", "ampeg_sustain", e.Sustain, de.Sustain}, {"Envelope.Release", "ampeg_release", e.Release, de.Release},
|
|
} {
|
|
add(s.field, s.v != s.d, s.name, num(s.v))
|
|
}
|
|
add("Trigger", r.Trigger != d.Trigger, "trigger", r.Trigger)
|
|
if r.LoopMode != "" {
|
|
add("LoopMode", true, "loop_mode", r.LoopMode)
|
|
}
|
|
if r.LoopStart != nil {
|
|
add("LoopStart", true, "loop_start", strconv.FormatInt(*r.LoopStart, 10))
|
|
}
|
|
if r.LoopEnd != nil {
|
|
add("LoopEnd", true, "loop_end", strconv.FormatInt(*r.LoopEnd, 10))
|
|
}
|
|
add("ReleaseDecay", r.ReleaseDecay != 0, "rt_decay", num(r.ReleaseDecay))
|
|
add("SequenceLength", r.SequenceLength != d.SequenceLength, "seq_length", strconv.Itoa(r.SequenceLength))
|
|
add("SequencePosition", r.SequencePosition != d.SequencePosition, "seq_position", strconv.Itoa(r.SequencePosition))
|
|
add("LowRandom", r.LowRandom != 0, "lorand", num(r.LowRandom))
|
|
add("HighRandom", r.HighRandom != d.HighRandom, "hirand", num(r.HighRandom))
|
|
add("Group", r.Group != 0, "group", strconv.Itoa(r.Group))
|
|
if r.OffBy != nil {
|
|
add("OffBy", true, "off_by", strconv.Itoa(*r.OffBy))
|
|
}
|
|
if r.Polyphony != nil {
|
|
add("Polyphony", true, "polyphony", strconv.Itoa(*r.Polyphony))
|
|
}
|
|
if r.NotePolyphony != nil {
|
|
add("NotePolyphony", true, "note_polyphony", strconv.Itoa(*r.NotePolyphony))
|
|
}
|
|
add("OffMode", r.OffMode != d.OffMode, "off_mode", r.OffMode)
|
|
add("OffTime", r.OffTime != d.OffTime, "off_time", num(r.OffTime))
|
|
for _, p := range []struct {
|
|
field, name string
|
|
v *float64
|
|
}{{"BendUp", "bend_up", r.BendUp}, {"BendDown", "bend_down", r.BendDown}, {"BendStep", "bend_step", r.BendStep}} {
|
|
if p.v != nil {
|
|
add(p.field, true, p.name, num(*p.v))
|
|
}
|
|
}
|
|
for _, c := range r.Conditions {
|
|
scale, lo, hi := conditionOpcodes(c)
|
|
if lo == "" {
|
|
add("Conditions", true, fmt.Sprintf("lohdcc%d", c.Controller), num(c.Low))
|
|
add("Conditions", true, fmt.Sprintf("hihdcc%d", c.Controller), num(c.High))
|
|
continue
|
|
}
|
|
add("Conditions", true, lo, scaled(c.Low, scale))
|
|
add("Conditions", true, hi, scaled(c.High, scale))
|
|
}
|
|
if k := r.Keyswitch; k != nil {
|
|
for _, s := range []struct {
|
|
name string
|
|
v *int
|
|
}{{"sw_last", k.Last}, {"sw_previous", k.Previous}, {"sw_down", k.Down}, {"sw_up", k.Up}} {
|
|
if s.v != nil {
|
|
add("Keyswitch", true, s.name, strconv.Itoa(*s.v))
|
|
}
|
|
}
|
|
}
|
|
for _, m := range r.Modulations {
|
|
add("Modulations", true, fmt.Sprintf("%s_oncc%d", m.Target, m.Controller), num(m.Depth))
|
|
if m.Curve != 0 {
|
|
add("Modulations", true, fmt.Sprintf("%s_curvecc%d", m.Target, m.Controller), strconv.Itoa(m.Curve))
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
// conditionOpcodes returns the opcodes that limit a source that isn't a
|
|
// numbered controller, and the number that their values are the range's limits
|
|
// times. A controller has no such opcodes, so lo and hi are empty for it, and
|
|
// it is written as lohdcc and hihdcc.
|
|
func conditionOpcodes(c Condition) (scale float64, lo, hi string) {
|
|
for _, b := range controllerBounds {
|
|
if b.source == c.Source {
|
|
return b.scale, b.low, b.high
|
|
}
|
|
}
|
|
return 0, "", ""
|
|
}
|