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.line("#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) } return &Document{Root: b.file("")}, nil } // The main file includes a file for each run of regions. 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) } name := path.Clean(o.FileNamer(i)) 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.reposition() return &Document{Root: main}, nil } // builder writes text and lexes it into files. type builder struct { indent string text strings.Builder } 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 { b.line(b.indent + op.name + "=" + op.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 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 } // 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 { d := defaultRegion() ops := []opcodeLine{{"sample", r.Sample}} add := func(name, value string) { ops = append(ops, opcodeLine{name, value}) } if r.LowKey != d.LowKey { add("lokey", strconv.Itoa(r.LowKey)) } if r.HighKey != d.HighKey { add("hikey", strconv.Itoa(r.HighKey)) } if r.RootFromSample { add("pitch_keycenter", "sample") } else if r.RootKey != d.RootKey { add("pitch_keycenter", strconv.Itoa(r.RootKey)) } if r.LowVelocity != d.LowVelocity { add("lovel", strconv.Itoa(r.LowVelocity)) } if r.HighVelocity != d.HighVelocity { add("hivel", strconv.Itoa(r.HighVelocity)) } if r.KeyTrack != d.KeyTrack { add("pitch_keytrack", num(r.KeyTrack)) } if r.Tune != 0 { add("tune", num(r.Tune)) } if r.Volume != 0 { add("volume", num(r.Volume)) } if r.Pan != 0 { add("pan", num(r.Pan)) } if r.Width != nil { add("width", num(*r.Width)) } if r.Offset != 0 { add("offset", strconv.FormatInt(r.Offset, 10)) } if r.VelocityTracking != d.VelocityTracking { add("amp_veltrack", num(r.VelocityTracking)) } for _, p := range r.VelocityCurve { add(fmt.Sprintf("amp_velcurve_%d", p.Velocity), num(p.Gain)) } crossfade := func(c *Crossfade, which string) { if c == nil { return } add("xfin_lo"+which, strconv.Itoa(c.FadeInLow)) add("xfin_hi"+which, strconv.Itoa(c.FadeInHigh)) add("xfout_lo"+which, strconv.Itoa(c.FadeOutLow)) add("xfout_hi"+which, strconv.Itoa(c.FadeOutHigh)) if c.Curve == CrossfadeGain { add("xf_"+which+"curve", "gain") } } crossfade(r.KeyCrossfade, "key") crossfade(r.VelocityCrossfade, "vel") e, de := r.Envelope, d.Envelope for _, s := range []struct { name string v, d float64 }{ {"ampeg_delay", e.Delay, de.Delay}, {"ampeg_attack", e.Attack, de.Attack}, {"ampeg_hold", e.Hold, de.Hold}, {"ampeg_decay", e.Decay, de.Decay}, {"ampeg_sustain", e.Sustain, de.Sustain}, {"ampeg_release", e.Release, de.Release}, } { if s.v != s.d { add(s.name, num(s.v)) } } if r.Trigger != d.Trigger { add("trigger", r.Trigger) } if r.LoopMode != "" { add("loop_mode", r.LoopMode) } if r.LoopStart != nil { add("loop_start", strconv.FormatInt(*r.LoopStart, 10)) } if r.LoopEnd != nil { add("loop_end", strconv.FormatInt(*r.LoopEnd, 10)) } if r.ReleaseDecay != 0 { add("rt_decay", num(r.ReleaseDecay)) } if r.SequenceLength != d.SequenceLength { add("seq_length", strconv.Itoa(r.SequenceLength)) } if r.SequencePosition != d.SequencePosition { add("seq_position", strconv.Itoa(r.SequencePosition)) } if r.LowRandom != 0 { add("lorand", num(r.LowRandom)) } if r.HighRandom != d.HighRandom { add("hirand", num(r.HighRandom)) } if r.Group != 0 { add("group", strconv.Itoa(r.Group)) } if r.OffBy != nil { add("off_by", strconv.Itoa(*r.OffBy)) } if r.Polyphony != nil { add("polyphony", strconv.Itoa(*r.Polyphony)) } if r.NotePolyphony != nil { add("note_polyphony", strconv.Itoa(*r.NotePolyphony)) } if r.OffMode != d.OffMode { add("off_mode", r.OffMode) } if r.OffTime != d.OffTime { add("off_time", num(r.OffTime)) } for _, p := range []struct { name string v *float64 }{{"bend_up", r.BendUp}, {"bend_down", r.BendDown}, {"bend_step", r.BendStep}} { if p.v != nil { add(p.name, num(*p.v)) } } for _, c := range r.Conditions { scale, lo, hi := conditionOpcodes(c) if lo == "" { add(fmt.Sprintf("lohdcc%d", c.Controller), num(c.Low)) add(fmt.Sprintf("hihdcc%d", c.Controller), num(c.High)) continue } add(lo, scaled(c.Low, scale)) add(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(s.name, strconv.Itoa(*s.v)) } } } for _, m := range r.Modulations { add(fmt.Sprintf("%s_oncc%d", m.Target, m.Controller), num(m.Depth)) if m.Curve != 0 { add(fmt.Sprintf("%s_curvecc%d", m.Target, m.Controller), strconv.Itoa(m.Curve)) } } return ops } // 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, "", "" }