Files
sfz/patch_test.go
aneurinandClaude Sonnet 5.5 8134660721 Fix the differences from the spec and sfizz that a conformance review found
Read opcodes under their other names. The registry lists the other names an
opcode has, and the typed model now reads each under its own name: amp_release
for ampeg_release, offby, bendup, tune_keytrack and the rest. Apply treats an
old name as belonging to the same field, so it doesn't leave one behind.

Cut a #define's value at the first space, as ARIA and sfizz do, so that two
defines can share a line. Before, the first define took the rest of the line,
and a kit that writes "#define $lo 1  #define $hi 25" lost its velocity layers.

Ignore opcodes before any header when flattening, as sfizz does, and report
them as a warning. Included files that hold only opcodes are not affected.

Read the limits of a controller the same way each time. A region that sets
lohdccN and inherits loccN took whichever the map gave first, so Apply's change
could read back as the old limits. The hdcc opcodes now win.

Accept -1 for lokey, hikey and key, which SFZ v2 allows, and don't report a
region with a hikey of -1 as an inverted range.

Cut numbers that don't fit to what a setting can hold, so offset=1e30 doesn't
turn negative, and ignore a controller number or octave that overflows.

Read polyphony=legato_high, legato_last and legato_low as a limit of 1.

Put a new #define after a byte order mark.

Mark in the tests where each expected value comes from, correct the tags that
the spec doesn't support, and add tests for each of these.

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

259 lines
10 KiB
Go

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()
}
// TestApplyEditsOwnHeader checks that Apply changes the region's own header
// and nothing else, and that a second Apply starts from what the first wrote.
func TestApplyEditsOwnHeader(t *testing.T) {
text := "<control> default_path=S/ note_offset=12\n<group> volume=-6 ampeg_release=0.5 group_volume=-2\n" +
"<region> sample=a.wav lokey=c3 hikey=e3 // keys\n zampler_x=1\n<region> 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", "<region> sample=b.wav\n", "<group> 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)
}
}
// TestApplyNothingToDo checks that a region that hasn't changed has no
// patches.
func TestApplyNothingToDo(t *testing.T) {
doc := mustParse(t, "<region> 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": {
"<group> loop_mode=one_shot\n<region> sample=a.wav\n", func(r *Region) { r.LoopMode = "" }, ErrUnpatchable},
"an inherited limit can't be removed": {
"<group> locc7=10\n<region> sample=a.wav\n", func(r *Region) { r.Conditions = nil }, ErrUnpatchable},
"a root note from the sample has no key": {
"<region> sample=a.wav pitch_keycenter=62\n", func(r *Region) { r.RootFromSample = true }, ErrUnpatchable},
"a path outside default_path": {
"<control> default_path=S/\n<region> sample=a.wav\n", func(r *Region) { r.Sample = "Other/a.wav" }, ErrUnpatchable},
"a path that can't be written": {
"<region> sample=a.wav\n", func(r *Region) { r.Sample = "a\nb.wav" }, ErrInvalid},
"a region that wouldn't play": {
"<region> sample=a.wav\n", func(r *Region) { r.Sample = "" }, ErrUnpatchable},
"a header from a variable": {
"#define $R <region>\n$R sample=a.wav\n", func(r *Region) { r.Tune = 1 }, ErrNoSource},
"opcodes from an include": {
"<region> sample=a.wav #include \"x.sfz\"\n", func(r *Region) { r.Tune = 1 }, ErrNoSource},
"opcodes from a variable": {
"#define $T tune=3\n<region> 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 the changes that TestApplyProperty makes to a region, by name.
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, "<control> default_path=S/\n<global> loop_mode=no_loop\n<group> volume=-3 group=2\n<region> sample=a.wav lokey=30 hikey=40 zampler_a=1\n"+
"<region> sample=b.wav key=50 pitch_keycenter=sample volume=2\n<group> ampeg_attack=0.1\n<region> 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)
}
}
// TestApplyReplacesOtherNames checks that a change to a setting that the
// region's header sets under another name of its opcode leaves only the opcode's
// own name behind, so that no player reads the old one instead.
func TestApplyReplacesOtherNames(t *testing.T) {
doc := mustParse(t, "<region> sample=a.wav amp_release=2 offby=3 bendup=100\n", nil)
inst := readInstrument(t, doc)
r := inst.Regions[0]
r.Envelope.Release = 5
g := 4
r.OffBy = &g
u := 200.0
r.BendUp = &u
if err := inst.Apply(0, r); err != nil {
t.Fatal(err)
}
for _, old := range []string{"amp_release", "offby", "bendup"} {
if strings.Contains(doc.String(), old) {
t.Errorf("%s is still there: %q", old, doc.String())
}
}
if d := differing(readInstrument(t, doc).Regions[0], r); len(d) != 0 {
t.Errorf("reads back differing in %v: %q", d, doc.String())
}
}