Instrument.Patches works out the opcode changes that make region i read as an updated Region, checking them against the reader, and Instrument.Apply makes them in the document. Only the changed settings are touched, always in the region's own header, so unknown opcodes and what other regions inherit stay as they are. A change the header can't hold is an error and changes nothing. FlatRegion gains Own, Inherited and Header to trace a region to its source, and regionLines lists a region's opcodes with the field each sets. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
437 lines
14 KiB
Go
437 lines
14 KiB
Go
package sfz
|
|
|
|
import (
|
|
"fmt"
|
|
"math"
|
|
"path"
|
|
"sort"
|
|
"strconv"
|
|
"strings"
|
|
)
|
|
|
|
// BuildOptions change how [Build] lays out a document. The zero value makes one
|
|
// file, with the values written literally and two spaces of indent.
|
|
type BuildOptions struct {
|
|
// Indent is what an opcode's line starts with. The default is two spaces.
|
|
Indent string
|
|
// SplitFiles puts the regions into included files, RegionsPerFile at a
|
|
// time, and leaves the controls and variables in the main file.
|
|
SplitFiles bool
|
|
// RegionsPerFile is how many regions each included file holds. 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. The default is regions/001.sfz,
|
|
// regions/002.sfz and so on.
|
|
FileNamer func(index int) string
|
|
// Variables writes a #define for each value that more than MinRepeat
|
|
// regions share, and uses default_path for the folder that all samples are
|
|
// in.
|
|
Variables bool
|
|
// MinRepeat is how many regions must share an opcode's value to make it a
|
|
// variable. The default is 8.
|
|
MinRepeat int
|
|
}
|
|
|
|
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 is a region that sets nothing: 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,
|
|
}
|
|
}
|
|
|
|
// opcodeLine is an opcode to write.
|
|
type opcodeLine struct{ name, value string }
|
|
|
|
// num writes a number with the digits it needs to read back as it was.
|
|
func num(v float64) string { return strconv.FormatFloat(v, 'f', -1, 64) }
|
|
|
|
// scaled writes a condition's limit in the unit of its opcode, which is the
|
|
// limit times scale, rounded so that a limit that was a whole number stays
|
|
// one.
|
|
func scaled(v, scale float64) string { return num(math.Round(v*scale*1e9) / 1e9) }
|
|
|
|
// Build makes a 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: unread opcodes, and which headers regions
|
|
// were under.
|
|
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 {
|
|
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
|
|
}
|
|
|
|
// The main file includes a file for each run of regions.
|
|
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 text and lexes it into files.
|
|
type builder struct {
|
|
indent string
|
|
text strings.Builder
|
|
// err is the first thing that couldn't be written.
|
|
err error
|
|
}
|
|
|
|
func (b *builder) line(s string) {
|
|
b.text.WriteString(s)
|
|
b.text.WriteString("\n")
|
|
}
|
|
|
|
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)
|
|
}
|
|
}
|
|
|
|
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 as a file with the path.
|
|
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 none.
|
|
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 values that at least min regions share with variables, and
|
|
// returns their definitions. The sample is the first opcode of a region and is
|
|
// 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] that it sets.
|
|
// The field of an envelope's setting is Envelope.Delay and so on.
|
|
type fieldLine struct {
|
|
field string
|
|
opcodeLine
|
|
}
|
|
|
|
// regionOpcodes returns the opcodes that make a region, starting with its
|
|
// sample, with those that are the format's defaults left out.
|
|
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.
|
|
// Those that are the format's defaults are left out unless all is set.
|
|
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 their values are the range's times. A
|
|
// controller has none, and 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, "", ""
|
|
}
|