Files
sfz/patch.go
T
aneurinandClaude Sonnet 5.5 158661eefe Rewrite the code comments for consistent tone and accuracy
Comments only: the tokens of every Go file are unchanged.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-01 19:08:00 +00:00

384 lines
14 KiB
Go

package sfz
import (
"errors"
"fmt"
"maps"
"math"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
)
var (
// ErrNoSource is returned for a region that has no header to edit: 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 change that the region's own header can't
// hold: it would need an opcode that the region inherits to be removed, or a
// setting that the typed model doesn't read from the header, such as a
// sample outside default_path.
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 is the opcode's name.
Name string
// Value is what the opcode is set to, unless Delete is set.
Value string
// Delete is whether the opcode is removed from the header.
Delete bool
}
// Patches returns the changes to the opcodes of the header of region i that
// make it read as updated. It only touches the settings that updated changes,
// and leaves the header's other opcodes, known or not, as they are. Changes are
// made in the region's own header, over what the region inherits, so other
// regions are not affected. It returns [ErrNoSource] or [ErrUnpatchable] if the
// header can't hold the change.
func (inst *Instrument) Patches(i int, updated Region) ([]Patch, error) {
patches, _, err := inst.plan(i, updated)
return patches, err
}
// Apply changes the document that 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. Afterwards the
// instrument holds updated as region i, and its other regions are as they were.
// The [Flat] it was read from isn't changed.
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 that the header of region i has once it reads as
// updated, and the patches that take it there from the opcodes it has. It
// checks each plan by reading a region from the opcodes, so a plan that is
// returned reads back as updated.
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)
// RootFromSample and RootKey are both set by pitch_keycenter.
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)
// Each changed field has the opcodes it owns replaced by those of the updated
// region, with the defaults written out so that they override what the
// region inherits.
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" {
// The sample is read as relative to default_path.
value = strings.TrimPrefix(value, defaultPath)
}
own[l.name] = value
}
}
// A setting that other opcodes move, such as a key that an offset shifts or
// a volume that an amplitude adds to, is read as other than what was
// written. Each opcode is moved by the difference that is left, until the
// setting reads as it should, or no opcode can move it further.
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, ", "))
}
// The patches are the differences between the opcodes the header has and
// those it should have.
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
}
// slicesContains reports whether list has s.
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, or an
// error wrapping [ErrNoSource].
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, each with the opcode that
// sets it. A path such as Envelope.Attack names a field of the envelope.
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 the field of the
// region got is from that of the region want, and reports whether that changed
// the opcode.
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,
// following pointers, and whether there is one.
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, and false if there is
// none, as for 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 names of the fields of two regions that differ, naming
// a setting of the envelope as Envelope.Attack is named.
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 reports whether two values of a region are equal. Numbers are
// equal to within a rounding error, and an empty list is 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 one field of a region is read from and no
// other field, by the name of the 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 name of an opcode that limits a controller, and
// the controller's 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 is
// read into. The opcodes that a field owns are removed when the field is
// written again, so that none is left to set it otherwise.
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)
}