From 83c905633c69420a6656ee1ce01c42655c4caff9 Mon Sep 17 00:00:00 2001 From: Aneurin Barker Snook Date: Tue, 1 Dec 2026 18:42:17 +0000 Subject: [PATCH] Apply changes to a typed region as patches to its own header 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 --- build.go | 175 +++++++++++------------- flatten.go | 26 +++- instrument.go | 2 + model.go | 5 + model_test.go | 3 + patch.go | 366 ++++++++++++++++++++++++++++++++++++++++++++++++++ patch_test.go | 229 +++++++++++++++++++++++++++++++ 7 files changed, 704 insertions(+), 102 deletions(-) create mode 100644 patch.go create mode 100644 patch_test.go diff --git a/build.go b/build.go index 46c7cfe..c7dfa7e 100644 --- a/build.go +++ b/build.go @@ -285,141 +285,124 @@ func hoist(regions [][]opcodeLine, min int) []opcodeLine { 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() - 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)) + 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("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)) + 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", 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)) + 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(fmt.Sprintf("amp_velcurve_%d", p.Velocity), num(p.Gain)) + add("VelocityCurve", true, fmt.Sprintf("amp_velcurve_%d", p.Velocity), num(p.Gain)) } - crossfade := func(c *Crossfade, which string) { + crossfade := func(field string, 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)) + 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("xf_"+which+"curve", "gain") + add(field, true, "xf_"+which+"curve", "gain") } } - crossfade(r.KeyCrossfade, "key") - crossfade(r.VelocityCrossfade, "vel") + crossfade("KeyCrossfade", r.KeyCrossfade, "key") + crossfade("VelocityCrossfade", r.VelocityCrossfade, "vel") e, de := r.Envelope, d.Envelope for _, s := range []struct { - name string - v, d float64 + field, 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}, + {"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}, } { - if s.v != s.d { - add(s.name, num(s.v)) - } - } - if r.Trigger != d.Trigger { - add("trigger", r.Trigger) + 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("loop_mode", r.LoopMode) + add("LoopMode", true, "loop_mode", r.LoopMode) } if r.LoopStart != nil { - add("loop_start", strconv.FormatInt(*r.LoopStart, 10)) + add("LoopStart", true, "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)) + 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("off_by", strconv.Itoa(*r.OffBy)) + add("OffBy", true, "off_by", strconv.Itoa(*r.OffBy)) } if r.Polyphony != nil { - add("polyphony", strconv.Itoa(*r.Polyphony)) + add("Polyphony", true, "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)) + 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 { - name string - v *float64 - }{{"bend_up", r.BendUp}, {"bend_down", r.BendDown}, {"bend_step", r.BendStep}} { + 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.name, num(*p.v)) + add(p.field, true, 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)) + 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(lo, scaled(c.Low, scale)) - add(hi, scaled(c.High, scale)) + 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 { @@ -427,17 +410,17 @@ func regionOpcodes(r Region) []opcodeLine { 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)) + add("Keyswitch", true, s.name, strconv.Itoa(*s.v)) } } } for _, m := range r.Modulations { - add(fmt.Sprintf("%s_oncc%d", m.Target, m.Controller), num(m.Depth)) + add("Modulations", true, 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)) + add("Modulations", true, fmt.Sprintf("%s_curvecc%d", m.Target, m.Controller), strconv.Itoa(m.Curve)) } } - return ops + return out } // conditionOpcodes returns the opcodes that limit a source that isn't a diff --git a/flatten.go b/flatten.go index 1227252..5d81a71 100644 --- a/flatten.go +++ b/flatten.go @@ -25,6 +25,12 @@ type FlatRegion struct { // File and Line are where the header is. File string Line int + // Own holds the opcodes of the region's own header, and Inherited those that + // it inherits, which Opcodes is the two of together. + Own, Inherited Opcodes + // Header is the header, or nil if a variable made it, so that it + // has no node of its own. + Header *Header } // Flat is an instrument with its directives expanded and its headers resolved. @@ -70,6 +76,7 @@ type target struct { region bool line int file string + header *Header } // flattener reads a document's nodes in order. @@ -104,7 +111,11 @@ func (f *flattener) header(file *File, n *Node, name string, variable bool) { // A header that a variable made has no node of its own, so it takes the line // of the node that made it. line, _ := file.Position(n) - f.startHeader(name, line, file.Path) + var own *Header + if !variable { + own = &Header{File: file, Node: n} + } + f.startHeader(name, line, file, own) } func (f *flattener) opcode(_ *File, _ *Node, name, value string, _ bool) { f.setOpcode(name, value) } @@ -121,11 +132,14 @@ func (f *flattener) closeRegion() { control[name] = v } } - ops := control.with(f.levels[levelGlobal]).with(f.levels[levelMaster]).with(f.levels[levelGroup]).with(f.into.ops) - f.flat.Regions = append(f.flat.Regions, FlatRegion{Opcodes: ops, File: f.into.file, Line: f.into.line}) + inherited := control.with(f.levels[levelGlobal]).with(f.levels[levelMaster]).with(f.levels[levelGroup]) + f.flat.Regions = append(f.flat.Regions, FlatRegion{ + Opcodes: inherited.with(f.into.ops), File: f.into.file, Line: f.into.line, + Own: f.into.ops, Inherited: inherited, Header: f.into.header, + }) } -func (f *flattener) startHeader(header string, line int, file string) { +func (f *flattener) startHeader(header string, line int, file *File, own *Header) { f.closeRegion() name := strings.ToLower(header) switch name { @@ -148,9 +162,9 @@ func (f *flattener) startHeader(header string, line int, file string) { for l := lvl; l <= levelRegion; l++ { f.levels[l] = Opcodes{} } - f.into = &target{ops: f.levels[lvl], file: file} + f.into = &target{ops: f.levels[lvl], file: file.Path} if lvl == levelRegion { - f.into.region, f.into.line = true, line + f.into.region, f.into.line, f.into.header = true, line, own } } } diff --git a/instrument.go b/instrument.go index 0a05941..ea5c74d 100644 --- a/instrument.go +++ b/instrument.go @@ -18,6 +18,7 @@ func (f *Flat) Instrument() *Instrument { } curves, stops := readCurves(f.Curves) e := evaluator{cc: controllerValues(f.Control), curves: curves, stops: stops} + inst.eval = e regions := make([]Opcodes, len(f.Regions)) for i, fr := range f.Regions { ops := fr.Opcodes @@ -33,6 +34,7 @@ func (f *Flat) Instrument() *Instrument { } } inst.Regions = append(inst.Regions, r) + inst.sources = append(inst.sources, fr) } inst.Controls = e.controls(f.Control, inst.Regions) inst.Keyswitches = keyswitchRange(regions) diff --git a/model.go b/model.go index 4a4f2ca..ae94d85 100644 --- a/model.go +++ b/model.go @@ -221,6 +221,11 @@ type Instrument struct { Controls []Control `json:"controls,omitempty" doc:"The controllers that the instrument names, sets or uses."` // Keyswitches are its keyswitch keys, or nil if it has none. Keyswitches *KeyswitchRange `json:"keyswitches,omitempty" doc:"The keys that are keyswitches, or nil if the instrument has none."` + + // sources are the flattened regions that the typed ones were read from, in + // the same order, and eval reads a region from opcodes as they were. + sources []FlatRegion + eval evaluator } // Reasons a region is skipped: the typed model has no region for it. diff --git a/model_test.go b/model_test.go index f888f21..74c3770 100644 --- a/model_test.go +++ b/model_test.go @@ -23,6 +23,9 @@ func TestModelTags(t *testing.T) { names := map[string]bool{} for i := 0; i < typ.NumField(); i++ { f := typ.Field(i) + if !f.IsExported() { + continue + } tag := f.Tag name, _, _ := strings.Cut(tag.Get("json"), ",") if name == "" || name == "-" || names[name] || name != strings.ToLower(name[:1])+name[1:] { diff --git a/patch.go b/patch.go new file mode 100644 index 0000000..2a56aeb --- /dev/null +++ b/patch.go @@ -0,0 +1,366 @@ +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) +} diff --git a/patch_test.go b/patch_test.go new file mode 100644 index 0000000..c71c894 --- /dev/null +++ b/patch_test.go @@ -0,0 +1,229 @@ +package sfz + +import ( + "errors" + "os" + "path/filepath" + "strings" + "testing" +) + +// readInstrument reads the instrument of a document, which keeps its sources. +func readInstrument(t *testing.T, doc *Document) *Instrument { + t.Helper() + return doc.Flatten().Instrument() +} + +func TestApplyEditsOwnHeader(t *testing.T) { + text := " default_path=S/ note_offset=12\n volume=-6 ampeg_release=0.5 group_volume=-2\n" + + " sample=a.wav lokey=c3 hikey=e3 // keys\n zampler_x=1\n sample=b.wav\n" + doc := mustParse(t, text, nil) + inst := readInstrument(t, doc) + r := inst.Regions[0] + r.Sample = "S/new.wav" + r.LowKey = 40 + r.Volume = -10 + r.Envelope.Release = 2 + r.Tune = 25 + r.Trigger = "release" + if err := inst.Apply(0, r); err != nil { + t.Fatal(err) + } + got := readInstrument(t, doc) + if d := differing(got.Regions[0], r); len(d) != 0 { + t.Errorf("differs in %v: %+v", d, got.Regions[0]) + } + // The other region, the unknown opcode and the comment are as they were. + if d := differing(got.Regions[1], inst.Regions[1]); len(d) != 0 { + t.Errorf("second region changed in %v", d) + } + for _, want := range []string{"zampler_x=1", "// keys", " sample=b.wav\n", " volume=-6 ampeg_release=0.5 group_volume=-2\n"} { + if !strings.Contains(doc.String(), want) { + t.Errorf("lost %q:\n%s", want, doc.String()) + } + } + // A second change to the same region reads from what the first made. + r.Pan = 30 + if err := inst.Apply(0, r); err != nil { + t.Fatal(err) + } + if d := differing(readInstrument(t, doc).Regions[0], r); len(d) != 0 { + t.Errorf("second apply differs in %v", d) + } +} + +func TestApplyNothingToDo(t *testing.T) { + doc := mustParse(t, " sample=a.wav\n", nil) + inst := readInstrument(t, doc) + patches, err := inst.Patches(0, inst.Regions[0]) + if err != nil || len(patches) != 0 { + t.Errorf("patches %v, err %v", patches, err) + } +} + +// TestApplyRefusals checks the changes a region's own header can't hold, and +// that none of them changes the document. +func TestApplyRefusals(t *testing.T) { + for name, tc := range map[string]struct { + text string + change func(r *Region) + want error + }{ + "an inherited loop mode can't be removed": { + " loop_mode=one_shot\n sample=a.wav\n", func(r *Region) { r.LoopMode = "" }, ErrUnpatchable}, + "an inherited limit can't be removed": { + " locc7=10\n sample=a.wav\n", func(r *Region) { r.Conditions = nil }, ErrUnpatchable}, + "a root note from the sample has no key": { + " sample=a.wav pitch_keycenter=62\n", func(r *Region) { r.RootFromSample = true }, ErrUnpatchable}, + "a path outside default_path": { + " default_path=S/\n sample=a.wav\n", func(r *Region) { r.Sample = "Other/a.wav" }, ErrUnpatchable}, + "a path that can't be written": { + " sample=a.wav\n", func(r *Region) { r.Sample = "a\nb.wav" }, ErrInvalid}, + "a region that wouldn't play": { + " sample=a.wav\n", func(r *Region) { r.Sample = "" }, ErrUnpatchable}, + "a header from a variable": { + "#define $R \n$R sample=a.wav\n", func(r *Region) { r.Tune = 1 }, ErrNoSource}, + "opcodes from an include": { + " sample=a.wav #include \"x.sfz\"\n", func(r *Region) { r.Tune = 1 }, ErrNoSource}, + "opcodes from a variable": { + "#define $T tune=3\n sample=a.wav\n$T\n", func(r *Region) { r.Pan = 1 }, ErrNoSource}, + } { + doc := mustParse(t, tc.text, map[string]string{"x.sfz": "lokey=3"}) + inst := readInstrument(t, doc) + if len(inst.Regions) == 0 { + t.Fatalf("%s: no region", name) + } + r := inst.Regions[0] + tc.change(&r) + before := doc.String() + err := inst.Apply(0, r) + if !errors.Is(err, tc.want) { + t.Errorf("%s: err %v", name, err) + } + if doc.String() != before { + t.Errorf("%s: changed the text to %q", name, doc.String()) + } + } + if err := (&Instrument{}).Apply(0, Region{}); !errors.Is(err, ErrNoSource) { + t.Errorf("an instrument not read from a document: %v", err) + } +} + +// edits are changes a region can take, by what they change. +var edits = map[string]func(r *Region){ + "sample": func(r *Region) { r.Sample = "other/x y.wav" }, + "keys": func(r *Region) { r.LowKey, r.HighKey = 10, 20 }, + "root": func(r *Region) { r.RootFromSample, r.RootKey = false, 45 }, + "velocity": func(r *Region) { r.LowVelocity, r.HighVelocity = 5, 99 }, + "volume": func(r *Region) { r.Volume += 3.5 }, + "tune": func(r *Region) { r.Tune += 17 }, + "pan": func(r *Region) { r.Pan = 12 }, + "width": func(r *Region) { w := 40.0; r.Width = &w }, + "offset": func(r *Region) { r.Offset += 1000 }, + "veltrack": func(r *Region) { r.VelocityTracking = 40 }, + "envelope": func(r *Region) { r.Envelope.Attack += 0.25; r.Envelope.Release += 1; r.Envelope.Sustain = 80 }, + "trigger": func(r *Region) { r.Trigger = "release" }, + "loop": func(r *Region) { + r.LoopMode = "loop_continuous" + s, e := int64(10), int64(500) + r.LoopStart, r.LoopEnd = &s, &e + }, + "sequence": func(r *Region) { r.SequenceLength, r.SequencePosition = 3, 2 }, + "random": func(r *Region) { r.LowRandom, r.HighRandom = 0.25, 0.75 }, + "group": func(r *Region) { g := 4; r.Group, r.OffBy = 3, &g }, + "polyphony": func(r *Region) { p := 2; r.Polyphony, r.NotePolyphony = &p, &p }, + "off": func(r *Region) { r.OffMode, r.OffTime = "time", 0.3 }, + "bend": func(r *Region) { u := 300.0; r.BendUp, r.BendDown, r.BendStep = &u, &u, &u }, + "velcurve": func(r *Region) { r.VelocityCurve = []CurvePoint{{0, 0}, {50, 0.4}, {127, 1}} }, + "keyxfade": func(r *Region) { r.KeyCrossfade = &Crossfade{1, 5, 100, 120, CrossfadeGain} }, + "velxfade": func(r *Region) { r.VelocityCrossfade = &Crossfade{1, 5, 100, 120, CrossfadePower} }, + "condition": func(r *Region) { + r.Conditions = []Condition{{Source: SourceController, Controller: 21, Low: 0.25, High: 0.5}} + }, + "channel": func(r *Region) { r.Conditions = []Condition{{Source: SourceChannel, Low: 2, High: 4}} }, + "keyswitch": func(r *Region) { k := 38; r.Keyswitch = &Keyswitch{Last: &k} }, + "modulation": func(r *Region) { r.Modulations = []Modulation{{Target: TargetVolume, Controller: 12, Depth: -4}} }, + "release": func(r *Region) { r.ReleaseDecay = 4 }, + "remove loops": func(r *Region) { r.LoopMode, r.LoopStart, r.LoopEnd = "", nil, nil }, +} + +// TestApplyProperty applies each edit to each region of each fixture. An edit +// either reads back exactly, with the rest of the document as it was, or is +// refused with the document as it was. +func TestApplyProperty(t *testing.T) { + dir := filepath.Join("testdata", "splendid") + sources := map[string]func() *Document{ + "splendid": func() *Document { + doc, err := ParseFile(os.DirFS(dir), "Splendid Grand Piano.sfz") + if err != nil { + t.Fatal(err) + } + return doc + }, + "plain": func() *Document { + return mustParse(t, " default_path=S/\n loop_mode=no_loop\n volume=-3 group=2\n sample=a.wav lokey=30 hikey=40 zampler_a=1\n"+ + " sample=b.wav key=50 pitch_keycenter=sample volume=2\n ampeg_attack=0.1\n sample=c.wav lovel=20 hivel=90 locc7=5 volume_oncc7=-5\n", nil) + }, + } + refused := map[string]int{} + applied := 0 + for name, open := range sources { + if name == "splendid" && slowdown > 1 { + // The fixture takes long to read again and again under the race detector. + continue + } + regions := len(readInstrument(t, open()).Regions) + for edit, change := range edits { + for i := 0; i < regions; i += max(1, regions/3) { + doc := open() + inst := readInstrument(t, doc) + before := doc.String() + others := make([]Region, len(inst.Regions)) + copy(others, inst.Regions) + updated := inst.Regions[i] + change(&updated) + err := inst.Apply(i, updated) + if err != nil { + if !errors.Is(err, ErrUnpatchable) && !errors.Is(err, ErrNoSource) { + t.Errorf("%s/%s/%d: %v", name, edit, i, err) + } + if doc.String() != before { + t.Errorf("%s/%s/%d: refused, but changed the text", name, edit, i) + } + refused[edit+": "+strings.SplitN(err.Error(), ": ", 3)[len(strings.SplitN(err.Error(), ": ", 3))-1]]++ + continue + } + applied++ + got := readInstrument(t, doc) + if len(got.Regions) != len(others) { + t.Fatalf("%s/%s/%d: %d regions, want %d", name, edit, i, len(got.Regions), len(others)) + } + if d := differing(got.Regions[i], updated); len(d) != 0 { + t.Errorf("%s/%s/%d: reads back differing in %v:\n got %+v\nwant %+v", name, edit, i, d, got.Regions[i], updated) + } + for j := range others { + if j == i { + continue + } + if d := differing(got.Regions[j], others[j]); len(d) != 0 { + t.Errorf("%s/%s/%d: region %d changed in %v", name, edit, i, j, d) + } + } + if name == "plain" { + // What was written reads back from its text. + again := readInstrument(t, mustParse(t, doc.String(), nil)) + if d := differing(again.Regions[i], updated); len(d) != 0 { + t.Errorf("%s/%s/%d: the text reads back differing in %v:\n%s", name, edit, i, d, doc.String()) + } + } + if !strings.Contains(doc.String(), "zampler_a=1") && strings.Contains(before, "zampler_a=1") { + t.Errorf("%s/%s/%d: lost an unknown opcode", name, edit, i) + } + } + } + } + t.Logf("%d edits applied; refused: %v", applied, refused) + if applied < 50 { + t.Errorf("only %d edits applied", applied) + } +}