367 lines
12 KiB
Go
367 lines
12 KiB
Go
package sfz
|
|||
|
|
|
||
|
|
import (
|
||
|
|
"errors"
|
||
|
|
"fmt"
|
||
|
|
"maps"
|
||
|
|
"math"
|
||
|
|
"reflect"
|
||
|
|
"regexp"
|
||
|
|
"sort"
|
||
|
|
"strconv"
|
||
|
|
"strings"
|
||
|
|
)
|
||
|
|
|
||
|
|
var (
|
||
|
|
// ErrNoSource is returned for a region that can't be edited because its
|
||
|
|
// opcodes aren't all in its own header: the instrument wasn't read from a
|
||
|
|
// document, a variable made the header, or an include or a variable
|
||
|
|
// brings in opcodes after it.
|
||
|
|
ErrNoSource = errors.New("no header to edit for the region")
|
||
|
|
// ErrUnpatchable is returned for a region that its own header can't hold:
|
||
|
|
// the changes would need to alter a header that other regions inherit, or a
|
||
|
|
// setting that the typed model reads from more than one place.
|
||
|
|
ErrUnpatchable = errors.New("the region can't be written to its own header")
|
||
|
|
)
|
||
|
|
|
||
|
|
// Patch is a change to one opcode of a region's own header.
|
||
|
|
type Patch struct {
|
||
|
|
Name string
|
||
|
|
// Value is what the opcode is set to, unless Delete is set.
|
||
|
|
Value string
|
||
|
|
Delete bool
|
||
|
|
}
|
||
|
|
|
||
|
|
// Patches returns the changes to the opcodes of the header of region i that
|
||
|
|
// make it read as updated. Only the settings that updated changes are touched,
|
||
|
|
// and the header's other opcodes, known or not, are left as they are. A change
|
||
|
|
// is always made in the region's own header, over what it inherits. It returns
|
||
|
|
// [ErrNoSource] or [ErrUnpatchable] if there is no way to make the change there,
|
||
|
|
// and then nothing has changed.
|
||
|
|
func (inst *Instrument) Patches(i int, updated Region) ([]Patch, error) {
|
||
|
|
patches, _, err := inst.plan(i, updated)
|
||
|
|
return patches, err
|
||
|
|
}
|
||
|
|
|
||
|
|
// Apply changes the document the instrument was read from so that region i
|
||
|
|
// reads as updated, with the changes that [Instrument.Patches] returns. It
|
||
|
|
// changes nothing and returns an error if they can't be made. The instrument
|
||
|
|
// now holds updated, and what it was read from isn't read again.
|
||
|
|
func (inst *Instrument) Apply(i int, updated Region) error {
|
||
|
|
patches, own, err := inst.plan(i, updated)
|
||
|
|
if err != nil {
|
||
|
|
return err
|
||
|
|
}
|
||
|
|
for _, p := range patches {
|
||
|
|
if !p.Delete {
|
||
|
|
if err := checkOpcode(p.Name, p.Value); err != nil {
|
||
|
|
return err
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
src := inst.sources[i]
|
||
|
|
for _, p := range patches {
|
||
|
|
if p.Delete {
|
||
|
|
src.Header.Delete(p.Name)
|
||
|
|
} else if err := src.Header.Set(p.Name, p.Value); err != nil {
|
||
|
|
return err
|
||
|
|
}
|
||
|
|
}
|
||
|
|
inst.Regions[i] = updated
|
||
|
|
inst.sources[i].Own = own
|
||
|
|
inst.sources[i].Opcodes = src.Inherited.with(own)
|
||
|
|
return nil
|
||
|
|
}
|
||
|
|
|
||
|
|
// plan works out the opcodes the region's own header ends with, and the patches
|
||
|
|
// that get it there.
|
||
|
|
func (inst *Instrument) plan(i int, updated Region) ([]Patch, Opcodes, error) {
|
||
|
|
src, err := inst.source(i)
|
||
|
|
if err != nil {
|
||
|
|
return nil, nil, err
|
||
|
|
}
|
||
|
|
changed := differing(inst.Regions[i], updated)
|
||
|
|
if slicesContains(changed, "RootFromSample") && !slicesContains(changed, "RootKey") {
|
||
|
|
changed = append(changed, "RootKey")
|
||
|
|
}
|
||
|
|
own := maps.Clone(src.Own)
|
||
|
|
defaultPath := strings.ReplaceAll(strings.TrimSpace(src.Opcodes["default_path"]), `\`, "/")
|
||
|
|
lines := regionLines(updated, true)
|
||
|
|
for _, field := range changed {
|
||
|
|
for name := range own {
|
||
|
|
if owns(field, name) {
|
||
|
|
delete(own, name)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
for _, l := range lines {
|
||
|
|
if l.field != field {
|
||
|
|
continue
|
||
|
|
}
|
||
|
|
value := l.value
|
||
|
|
if field == "Sample" {
|
||
|
|
value = strings.TrimPrefix(value, defaultPath)
|
||
|
|
}
|
||
|
|
own[l.name] = value
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// Settings that other opcodes move, such as a key shifted by an offset, a
|
||
|
|
// volume that amplitude adds to, or a level that a clamp holds, are brought
|
||
|
|
// to the value by the difference that is left.
|
||
|
|
var wrong []string
|
||
|
|
for try := 0; ; try++ {
|
||
|
|
got, reason := inst.eval.region(src.Inherited.with(own))
|
||
|
|
if reason != "" {
|
||
|
|
return nil, nil, fmt.Errorf("%w: it would be skipped as %s", ErrUnpatchable, reason)
|
||
|
|
}
|
||
|
|
wrong = differing(got, updated)
|
||
|
|
if len(wrong) == 0 || try == 4 {
|
||
|
|
break
|
||
|
|
}
|
||
|
|
moved := false
|
||
|
|
for _, field := range wrong {
|
||
|
|
if opcode, ok := scalarOpcodes[field]; ok && adjust(own, opcode, field, got, updated) {
|
||
|
|
moved = true
|
||
|
|
}
|
||
|
|
}
|
||
|
|
if !moved {
|
||
|
|
break
|
||
|
|
}
|
||
|
|
}
|
||
|
|
if len(wrong) > 0 {
|
||
|
|
return nil, nil, fmt.Errorf("%w: %s", ErrUnpatchable, strings.Join(wrong, ", "))
|
||
|
|
}
|
||
|
|
|
||
|
|
var patches []Patch
|
||
|
|
for name, value := range own {
|
||
|
|
if old, ok := src.Own[name]; !ok || old != value {
|
||
|
|
patches = append(patches, Patch{Name: name, Value: value})
|
||
|
|
}
|
||
|
|
}
|
||
|
|
for name := range src.Own {
|
||
|
|
if _, ok := own[name]; !ok {
|
||
|
|
patches = append(patches, Patch{Name: name, Delete: true})
|
||
|
|
}
|
||
|
|
}
|
||
|
|
sort.Slice(patches, func(a, b int) bool { return patches[a].Name < patches[b].Name })
|
||
|
|
return patches, own, nil
|
||
|
|
}
|
||
|
|
|
||
|
|
func slicesContains(list []string, s string) bool {
|
||
|
|
for _, v := range list {
|
||
|
|
if v == s {
|
||
|
|
return true
|
||
|
|
}
|
||
|
|
}
|
||
|
|
return false
|
||
|
|
}
|
||
|
|
|
||
|
|
// source returns the flattened region i, if its header can be edited.
|
||
|
|
func (inst *Instrument) source(i int) (FlatRegion, error) {
|
||
|
|
if i < 0 || i >= len(inst.Regions) || i >= len(inst.sources) {
|
||
|
|
return FlatRegion{}, fmt.Errorf("%w: there is no region %d", ErrNoSource, i)
|
||
|
|
}
|
||
|
|
src := inst.sources[i]
|
||
|
|
h := src.Header
|
||
|
|
if h == nil {
|
||
|
|
return FlatRegion{}, fmt.Errorf("%w: a variable made the header", ErrNoSource)
|
||
|
|
}
|
||
|
|
if h.File.indexOf(h.Node) < 0 {
|
||
|
|
return FlatRegion{}, fmt.Errorf("%w: the header isn't in its file now", ErrNoSource)
|
||
|
|
}
|
||
|
|
start, end := h.span()
|
||
|
|
for _, n := range h.File.Nodes[start:end] {
|
||
|
|
if n.Kind == KindInclude && n.File != nil || n.Kind == KindText && strings.Contains(n.Raw, "$") {
|
||
|
|
return FlatRegion{}, fmt.Errorf("%w: an include or a variable brings in opcodes", ErrNoSource)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
return src, nil
|
||
|
|
}
|
||
|
|
|
||
|
|
// scalarOpcodes are the numeric fields of a region, by the opcode that sets
|
||
|
|
// each.
|
||
|
|
var scalarOpcodes = map[string]string{
|
||
|
|
"LowKey": "lokey", "HighKey": "hikey", "RootKey": "pitch_keycenter", "LowVelocity": "lovel", "HighVelocity": "hivel",
|
||
|
|
"KeyTrack": "pitch_keytrack", "Tune": "tune", "Volume": "volume", "Pan": "pan", "Width": "width", "Offset": "offset",
|
||
|
|
"VelocityTracking": "amp_veltrack", "ReleaseDecay": "rt_decay", "SequenceLength": "seq_length", "SequencePosition": "seq_position",
|
||
|
|
"LowRandom": "lorand", "HighRandom": "hirand", "Group": "group", "OffTime": "off_time",
|
||
|
|
"Envelope.Delay": "ampeg_delay", "Envelope.Attack": "ampeg_attack", "Envelope.Hold": "ampeg_hold",
|
||
|
|
"Envelope.Decay": "ampeg_decay", "Envelope.Sustain": "ampeg_sustain", "Envelope.Release": "ampeg_release",
|
||
|
|
}
|
||
|
|
|
||
|
|
// adjust moves an opcode of the region's own header by how far a region read
|
||
|
|
// from it is from the one wanted, and reports whether that changed it.
|
||
|
|
func adjust(own Opcodes, opcode, field string, got, want Region) bool {
|
||
|
|
g, ok := numberAt(reflect.ValueOf(got), field)
|
||
|
|
w, ok2 := numberAt(reflect.ValueOf(want), field)
|
||
|
|
if !ok || !ok2 {
|
||
|
|
return false
|
||
|
|
}
|
||
|
|
base, err := strconv.ParseFloat(strings.TrimSpace(own[opcode]), 64)
|
||
|
|
if err != nil {
|
||
|
|
d, _ := numberAt(reflect.ValueOf(defaultRegion()), field)
|
||
|
|
base = d
|
||
|
|
}
|
||
|
|
next := base + (w - g)
|
||
|
|
if v, _ := fieldAt(reflect.ValueOf(want), field); v.Kind() != reflect.Float64 && v.Kind() != reflect.Pointer {
|
||
|
|
next = math.Round(next)
|
||
|
|
own[opcode] = strconv.FormatInt(int64(next), 10)
|
||
|
|
} else {
|
||
|
|
own[opcode] = num(next)
|
||
|
|
}
|
||
|
|
return next != base
|
||
|
|
}
|
||
|
|
|
||
|
|
// fieldAt returns the field of a struct at a path such as Envelope.Attack, with
|
||
|
|
// a pointer followed.
|
||
|
|
func fieldAt(v reflect.Value, path string) (reflect.Value, bool) {
|
||
|
|
for _, name := range strings.Split(path, ".") {
|
||
|
|
for v.Kind() == reflect.Pointer && !v.IsNil() {
|
||
|
|
v = v.Elem()
|
||
|
|
}
|
||
|
|
if v.Kind() != reflect.Struct {
|
||
|
|
return reflect.Value{}, false
|
||
|
|
}
|
||
|
|
v = v.FieldByName(name)
|
||
|
|
}
|
||
|
|
return v, v.IsValid()
|
||
|
|
}
|
||
|
|
|
||
|
|
// numberAt returns the number at a path in a region, or false if there is none,
|
||
|
|
// as in a width that isn't set.
|
||
|
|
func numberAt(v reflect.Value, path string) (float64, bool) {
|
||
|
|
f, ok := fieldAt(v, path)
|
||
|
|
if !ok {
|
||
|
|
return 0, false
|
||
|
|
}
|
||
|
|
if f.Kind() == reflect.Pointer {
|
||
|
|
if f.IsNil() {
|
||
|
|
return 0, false
|
||
|
|
}
|
||
|
|
f = f.Elem()
|
||
|
|
}
|
||
|
|
switch f.Kind() {
|
||
|
|
case reflect.Int, reflect.Int64:
|
||
|
|
return float64(f.Int()), true
|
||
|
|
case reflect.Float64:
|
||
|
|
return f.Float(), true
|
||
|
|
}
|
||
|
|
return 0, false
|
||
|
|
}
|
||
|
|
|
||
|
|
// differing returns the fields of two regions that differ, naming a setting of
|
||
|
|
// the envelope as Envelope.Attack.
|
||
|
|
func differing(a, b Region) []string {
|
||
|
|
var out []string
|
||
|
|
va, vb := reflect.ValueOf(a), reflect.ValueOf(b)
|
||
|
|
for i := 0; i < va.NumField(); i++ {
|
||
|
|
name := va.Type().Field(i).Name
|
||
|
|
if name == "Envelope" {
|
||
|
|
for j := 0; j < va.Field(i).NumField(); j++ {
|
||
|
|
sub := va.Field(i).Type().Field(j).Name
|
||
|
|
if !equalValues(va.Field(i).Field(j), vb.Field(i).Field(j)) {
|
||
|
|
out = append(out, "Envelope."+sub)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
} else if !equalValues(va.Field(i), vb.Field(i)) {
|
||
|
|
out = append(out, name)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
return out
|
||
|
|
}
|
||
|
|
|
||
|
|
// equalValues compares two values of a region, with numbers equal to within a
|
||
|
|
// rounding error, and an empty list the same as none.
|
||
|
|
func equalValues(a, b reflect.Value) bool {
|
||
|
|
switch a.Kind() {
|
||
|
|
case reflect.Float64:
|
||
|
|
return math.Abs(a.Float()-b.Float()) <= 1e-9
|
||
|
|
case reflect.Pointer:
|
||
|
|
if a.IsNil() || b.IsNil() {
|
||
|
|
return a.IsNil() == b.IsNil()
|
||
|
|
}
|
||
|
|
return equalValues(a.Elem(), b.Elem())
|
||
|
|
case reflect.Slice:
|
||
|
|
if a.Len() != b.Len() {
|
||
|
|
return false
|
||
|
|
}
|
||
|
|
for i := 0; i < a.Len(); i++ {
|
||
|
|
if !equalValues(a.Index(i), b.Index(i)) {
|
||
|
|
return false
|
||
|
|
}
|
||
|
|
}
|
||
|
|
return true
|
||
|
|
case reflect.Struct:
|
||
|
|
for i := 0; i < a.NumField(); i++ {
|
||
|
|
if !equalValues(a.Field(i), b.Field(i)) {
|
||
|
|
return false
|
||
|
|
}
|
||
|
|
}
|
||
|
|
return true
|
||
|
|
}
|
||
|
|
return a.Interface() == b.Interface()
|
||
|
|
}
|
||
|
|
|
||
|
|
// ownedNames are the opcodes that only one field of a region is read from,
|
||
|
|
// by field.
|
||
|
|
var ownedNames = map[string]*regexp.Regexp{
|
||
|
|
"Sample": regexp.MustCompile(`^sample$`), "LowKey": regexp.MustCompile(`^lokey$`), "HighKey": regexp.MustCompile(`^hikey$`),
|
||
|
|
"RootKey": regexp.MustCompile(`^pitch_keycenter$`), "LowVelocity": regexp.MustCompile(`^lovel$`), "HighVelocity": regexp.MustCompile(`^hivel$`),
|
||
|
|
"KeyTrack": regexp.MustCompile(`^pitch_keytrack$`), "Tune": regexp.MustCompile(`^tune$`), "Volume": regexp.MustCompile(`^volume$`),
|
||
|
|
"Pan": regexp.MustCompile(`^pan$`), "Width": regexp.MustCompile(`^width$`), "Offset": regexp.MustCompile(`^offset$`),
|
||
|
|
"VelocityTracking": regexp.MustCompile(`^amp_veltrack$`), "ReleaseDecay": regexp.MustCompile(`^rt_decay$`),
|
||
|
|
"Envelope.Delay": regexp.MustCompile(`^ampeg_delay$`), "Envelope.Attack": regexp.MustCompile(`^ampeg_attack$`),
|
||
|
|
"Envelope.Hold": regexp.MustCompile(`^ampeg_hold$`), "Envelope.Decay": regexp.MustCompile(`^ampeg_decay$`),
|
||
|
|
"Envelope.Sustain": regexp.MustCompile(`^ampeg_sustain$`), "Envelope.Release": regexp.MustCompile(`^ampeg_release$`),
|
||
|
|
"Trigger": regexp.MustCompile(`^trigger$`), "LoopMode": regexp.MustCompile(`^(loop_mode|loopmode)$`),
|
||
|
|
"LoopStart": regexp.MustCompile(`^(loop_start|loopstart)$`), "LoopEnd": regexp.MustCompile(`^(loop_end|loopend)$`),
|
||
|
|
"SequenceLength": regexp.MustCompile(`^seq_length$`), "SequencePosition": regexp.MustCompile(`^seq_position$`),
|
||
|
|
"LowRandom": regexp.MustCompile(`^lorand$`), "HighRandom": regexp.MustCompile(`^hirand$`),
|
||
|
|
"Group": regexp.MustCompile(`^(group|polyphony_group)$`), "OffBy": regexp.MustCompile(`^off_by$`),
|
||
|
|
"Polyphony": regexp.MustCompile(`^polyphony$`), "NotePolyphony": regexp.MustCompile(`^note_polyphony$`),
|
||
|
|
"OffMode": regexp.MustCompile(`^off_mode$`), "OffTime": regexp.MustCompile(`^off_time$`),
|
||
|
|
"BendUp": regexp.MustCompile(`^bend_up$`), "BendDown": regexp.MustCompile(`^bend_down$`), "BendStep": regexp.MustCompile(`^bend_step$`),
|
||
|
|
"VelocityCurve": regexp.MustCompile(`^amp_velcurve_\d+$`),
|
||
|
|
"KeyCrossfade": regexp.MustCompile(`^(xfin_lokey|xfin_hikey|xfout_lokey|xfout_hikey|xf_keycurve)$`),
|
||
|
|
"VelocityCrossfade": regexp.MustCompile(`^(xfin_lovel|xfin_hivel|xfout_lovel|xfout_hivel|xf_velcurve)$`),
|
||
|
|
"Keyswitch": regexp.MustCompile(`^sw_(last|previous|down|up)$`),
|
||
|
|
}
|
||
|
|
|
||
|
|
// controllerLimitRE reads the opcodes that limit a controller, and its number.
|
||
|
|
var controllerLimitRE = regexp.MustCompile(`^(?:lo|hi)(?:hd)?cc(\d+)$`)
|
||
|
|
|
||
|
|
// owns reports whether a field of a region is the only one that an opcode of
|
||
|
|
// the region's header is read into, so that the opcode goes when the field is
|
||
|
|
// written again.
|
||
|
|
func owns(field, name string) bool {
|
||
|
|
switch field {
|
||
|
|
case "Conditions":
|
||
|
|
if m := controllerLimitRE.FindStringSubmatch(name); m != nil {
|
||
|
|
n, _ := strconv.Atoi(m[1])
|
||
|
|
return n < extendedVelocityCC
|
||
|
|
}
|
||
|
|
for _, b := range controllerBounds {
|
||
|
|
if name == b.low || name == b.high {
|
||
|
|
return true
|
||
|
|
}
|
||
|
|
}
|
||
|
|
return false
|
||
|
|
case "Modulations":
|
||
|
|
for _, set := range modulatedBy {
|
||
|
|
for _, opcode := range set.Opcodes {
|
||
|
|
if n, ok := modulator(name, opcode); ok && n < extendedOnly {
|
||
|
|
return true
|
||
|
|
}
|
||
|
|
if rest, ok := strings.CutPrefix(name, opcode+"_curvecc"); ok {
|
||
|
|
if n, err := strconv.Atoi(rest); err == nil && n < extendedOnly {
|
||
|
|
return true
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
return false
|
||
|
|
}
|
||
|
|
re, ok := ownedNames[field]
|
||
|
|
return ok && re.MatchString(name)
|
||
|
|
}
|