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>
This commit is contained in:
2026-12-01 20:38:57 +00:00
co-authored by Claude Sonnet 5.5
parent 04419062f3
commit 8134660721
15 changed files with 384 additions and 85 deletions
+1 -1
View File
@@ -68,7 +68,7 @@ The model is read with each setting that a controller moves taken at the control
| `include.outside` | warning | An include's path is absolute or leaves the main file's folder. | | `include.outside` | warning | An include's path is absolute or leaves the main file's folder. |
| `include.unresolved` | warning | An include can't be read. | | `include.unresolved` | warning | An include can't be read. |
| `opcode.deprecated` | info | The format has dropped the opcode. | | `opcode.deprecated` | info | The format has dropped the opcode. |
| `opcode.no-header` | info | An opcode comes before any header. | | `opcode.no-header` | warning | An opcode comes before any header, so no region has it. |
| `opcode.unknown` | info | The format has no such opcode. | | `opcode.unknown` | info | The format has no such opcode. |
| `range.inverted` | warning | A `lo` opcode is above its `hi` opcode in the same header. | | `range.inverted` | warning | A `lo` opcode is above its `hi` opcode in the same header. |
| `sample.outside` | info | A sample or `default_path` is absolute or goes up out of the folder. | | `sample.outside` | info | A sample or `default_path` is absolute or goes up out of the folder. |
+1 -1
View File
@@ -46,7 +46,7 @@ func GetAs[T Value](o Opcodes, name string) (T, bool) {
} else { } else {
var f float64 var f float64
if f, ok = parseNumber(raw); ok { if f, ok = parseNumber(raw); ok {
n = int(f) n = toInt(f)
} }
} }
if !ok { if !ok {
+174
View File
@@ -0,0 +1,174 @@
package sfz
import (
"errors"
"strings"
"testing"
)
// The expected values of these tests are marked as in sfz_test.go: "spec" is
// sfzformat.com, "sfizz" is the sfizz player's source, and "choice" is
// Zampler's own.
// TestOtherNames checks that an opcode set under another name that the format
// gives it is read as the opcode (spec: each opcode's page lists its aliases),
// and that the opcode's own name wins if both are set.
func TestOtherNames(t *testing.T) {
r := parseText(t, "<region> sample=a.wav amp_attack=0.5 amp_release=2 offby=3 bendup=100 benddown=-50 tune_keytrack=0 loopmode=one_shot loopstart=10 loopend=20 polyphony_group=4").Regions[0]
if r.Envelope.Attack != 0.5 || r.Envelope.Release != 2 || r.OffBy == nil || *r.OffBy != 3 || r.KeyTrack != 0 ||
r.BendUp == nil || *r.BendUp != 100 || r.BendDown == nil || *r.BendDown != -50 ||
r.LoopMode != "one_shot" || r.LoopStart == nil || *r.LoopStart != 10 || r.LoopEnd == nil || *r.LoopEnd != 20 || r.Group != 4 {
t.Errorf("other names %+v", r)
}
inst := parseText(t, "<region> sample=a.wav amp_release=2 ampeg_release=7")
if got := inst.Regions[0].Envelope.Release; got != 7 {
t.Errorf("release %v with both names", got)
}
if len(inst.Unread) != 0 {
t.Errorf("unread %v", inst.Unread)
}
}
// TestKeyMinusOne checks that SFZ v2's -1 for lokey, hikey and key, which keeps
// a region from playing, isn't a problem (spec).
func TestKeyMinusOne(t *testing.T) {
doc := mustParse(t, "<region> sample=a.wav lokey=-1 hikey=-1\n<region> sample=b.wav lokey=60 hikey=-1\n<region> sample=c.wav key=-1\n", nil)
if p := doc.Validate(); len(p) != 0 {
t.Errorf("problems %v", p)
}
if inst := readInstrument(t, doc); len(inst.Regions) != 0 || inst.Skipped[SkippedNotKeys] != 3 {
t.Errorf("regions %v, skipped %v", inst.Regions, inst.Skipped)
}
if p := mustParse(t, "<region> sample=a.wav lokey=-2\n", nil).Validate(); len(p) != 1 || p[0].Code != "value.range" {
t.Errorf("-2: %v", p)
}
}
// TestHugeNumbers checks that a number beyond what a setting can hold is cut to
// the nearest it can, and doesn't change sign.
func TestHugeNumbers(t *testing.T) {
r := parseText(t, "<region> sample=a.wav offset=1e30 loop_start=1e30 loop_end=1e30 group=1e30 off_by=-1e30 seq_length=1e30 polyphony=1e30 note_polyphony=1e30").Regions[0]
if r.Offset <= 0 || *r.LoopStart <= 0 || *r.LoopEnd <= 0 || r.Group <= 0 || *r.OffBy >= 0 ||
r.SequenceLength <= 0 || *r.Polyphony <= 0 || *r.NotePolyphony <= 0 {
t.Errorf("huge numbers %+v", r)
}
if n, ok := GetAs[int](Opcodes{"group": "1e30"}, "group"); !ok || n <= 0 {
t.Errorf("GetAs %d %v", n, ok)
}
// A controller number or an octave that doesn't fit isn't read as 0.
inst := parseText(t, "<region> sample=a.wav locc99999999999999999999=5 lokey=c99999999999999999999")
if len(inst.Regions[0].Conditions) != 0 || inst.Regions[0].LowKey != 0 {
t.Errorf("huge names %+v", inst.Regions[0])
}
}
// TestSetDefineKeepsByteOrderMark checks that a new #define goes after a byte
// order mark, which has to stay at the start of the file.
func TestSetDefineKeepsByteOrderMark(t *testing.T) {
for _, text := range []string{"\xef\xbb\xbf<region> sample=a.wav\n", "\xef\xbb\xbf\n<region> sample=a.wav\n"} {
doc := mustParse(t, text, nil)
if err := doc.SetDefine("$X", "1"); err != nil {
t.Fatal(err)
}
got := doc.String()
if !strings.HasPrefix(got, "\xef\xbb\xbf") || strings.Count(got, "\xef\xbb\xbf") != 1 {
t.Errorf("byte order mark moved: %q", got)
}
again := mustParse(t, got, nil)
if p := again.Validate(); len(p) != 0 {
t.Errorf("%q: problems %v", got, p)
}
if ds := again.Defines(); len(ds) != 1 || ds[0].Name != "$X" {
t.Errorf("%q: defines %v", got, ds)
}
}
}
// TestPolyphonyLegato checks that polyphony's text values, which limit the
// region to one voice, read as a limit of 1 (spec).
func TestPolyphonyLegato(t *testing.T) {
for _, v := range []string{"legato_high", "legato_last", "legato_low"} {
if r := parseText(t, "<region> sample=a.wav polyphony="+v).Regions[0]; r.Polyphony == nil || *r.Polyphony != 1 {
t.Errorf("%s: %v", v, r.Polyphony)
}
}
if r := parseText(t, "<region> sample=a.wav polyphony=legato_sideways").Regions[0]; r.Polyphony != nil {
t.Errorf("an unknown word: %v", *r.Polyphony)
}
}
// TestBuiltinCurves checks the curves that SFZ players define (spec, sfizz):
// 0 straight, 1 bipolar, 2 inverted, 3 bipolar inverted, 4 x², 5 √x and 6 √(1-x).
func TestBuiltinCurves(t *testing.T) {
curves, _ := readCurves(nil)
for index, want := range map[int][3]float64{
0: {0, 0.25, 1}, 1: {-1, -0.5, 1}, 2: {1, 0.75, 0}, 3: {1, 0.5, -1},
4: {0, 0.0625, 1}, 5: {0, 0.5, 1}, 6: {1, 0.8660254037844386, 0},
} {
c := curves[index]
for i, x := range []float64{0, 0.25, 1} {
if !near(c(x), want[i]) {
t.Errorf("curve %d at %v is %v, want %v", index, x, c(x), want[i])
}
}
}
}
// TestDefaultPathNeedsItsSlash checks that default_path and the sample are
// joined as they are, so a default_path with no slash at its end runs into the
// sample's name (sfizz; the spec says either it ends in a slash or the sample
// starts with one).
func TestDefaultPathNeedsItsSlash(t *testing.T) {
if got := parseText(t, "<control> default_path=Samples\n<region> sample=a.wav").Regions[0].Sample; got != "Samplesa.wav" {
t.Errorf("sample %q", got)
}
if got := parseText(t, "<control> default_path=Samples\n<region> sample=/a.wav").Regions[0].Sample; got != "Samples/a.wav" {
t.Errorf("sample %q", got)
}
}
// TestConditionLimitsAreRead checks that a region that sets a limit as lohdcc,
// where it inherits one as locc, reads the lohdcc each time, and that Apply's
// change to such a region reads back (choice: the opcodes have no order, so the
// hdcc one wins).
func TestConditionLimitsAreRead(t *testing.T) {
doc := mustParse(t, "<group> locc7=14 hicc7=25\n<region> sample=a.wav\n", nil)
inst := readInstrument(t, doc)
r := inst.Regions[0]
r.Conditions = []Condition{{Source: SourceController, Controller: 7, Low: 0.5, High: 1}}
if err := inst.Apply(0, r); err != nil {
t.Fatal(err)
}
for i := 0; i < 50; i++ {
got := readInstrument(t, doc).Regions[0].Conditions
if len(got) != 1 || !near(got[0].Low, 0.5) || !near(got[0].High, 1) {
t.Fatalf("read %d: %+v", i, got)
}
}
}
// TestDefineValueIsOneWord checks that a #define's value ends at the first
// space, so that two can share a line, and that what follows is read as it
// would be anywhere else (sfizz, and ARIA, which sfizz follows here).
func TestDefineValueIsOneWord(t *testing.T) {
doc := mustParse(t, "#define $lo 1 #define $hi 25\n<region> sample=a.wav lovel=$lo hivel=$hi\n", nil)
r := readInstrument(t, doc).Regions[0]
if r.LowVelocity != 1 || r.HighVelocity != 25 {
t.Errorf("velocities %d to %d", r.LowVelocity, r.HighVelocity)
}
if p := doc.Validate(); len(p) != 0 {
t.Errorf("problems %v", p)
}
if ds := doc.Defines(); len(ds) != 2 || ds[0].Value != "1" || ds[1].Value != "25" {
t.Errorf("defines %v", ds)
}
// A value with a space in it is its first word, and the rest is text.
doc = mustParse(t, "#define $path some folder/name\n<region> sample=$path\n", nil)
if got := doc.Flatten().Regions[0].Opcodes["sample"]; got != "some" {
t.Errorf("sample %q", got)
}
// So SetDefine can't write one.
if err := doc.SetDefine("$path", "some folder"); !errors.Is(err, ErrInvalid) {
t.Errorf("SetDefine: %v", err)
}
}
+23 -6
View File
@@ -28,7 +28,10 @@ func (e evaluator) controls(control Opcodes, regions []Region) []Control {
if m == nil { if m == nil {
continue continue
} }
n, _ := strconv.Atoi(m[2]) n, err := strconv.Atoi(m[2])
if err != nil {
continue
}
switch m[1] { switch m[1] {
case "label_cc": case "label_cc":
labels[n] = strings.TrimSpace(v) labels[n] = strings.TrimSpace(v)
@@ -118,7 +121,10 @@ func controllerValues(control Opcodes) map[int]float64 {
if m == nil { if m == nil {
continue continue
} }
n, _ := strconv.Atoi(m[2]) n, err := strconv.Atoi(m[2])
if err != nil {
continue
}
f, ok := parseNumber(v) f, ok := parseNumber(v)
if !ok { if !ok {
continue continue
@@ -157,10 +163,10 @@ func defaultKeyswitch(regions []Opcodes) int {
func keyShift(ops Opcodes) int { func keyShift(ops Opcodes) int {
shift := 0 shift := 0
if n, ok := parseNumber(ops["note_offset"]); ok { if n, ok := parseNumber(ops["note_offset"]); ok {
shift += int(n) shift += toInt(n)
} }
if n, ok := parseNumber(ops["octave_offset"]); ok { if n, ok := parseNumber(ops["octave_offset"]); ok {
shift += 12 * int(n) shift += 12 * toInt(n)
} }
return shift return shift
} }
@@ -191,12 +197,20 @@ var controllerBounds = []struct {
// Controllers above 127, which belong to the note, are left out. // Controllers above 127, which belong to the note, are left out.
func conditions(ops Opcodes) []Condition { func conditions(ops Opcodes) []Condition {
ranges := map[int]*Condition{} ranges := map[int]*Condition{}
// A limit set as both lo/hicc and lo/hihdcc, as when a region sets one and
// inherits the other, takes the value of the hdcc one. The opcodes have no
// order of their own, so reading the hdcc ones last is what makes the result
// the same each time.
read := func(hd bool) {
for name, v := range ops { for name, v := range ops {
m := ccRE.FindStringSubmatch(name) m := ccRE.FindStringSubmatch(name)
if m == nil { if m == nil || strings.Contains(m[1], "hd") != hd {
continue
}
n, err := strconv.Atoi(m[2])
if err != nil {
continue continue
} }
n, _ := strconv.Atoi(m[2])
limit, ok := parseNumber(v) limit, ok := parseNumber(v)
if !ok || n >= extendedVelocityCC { if !ok || n >= extendedVelocityCC {
continue continue
@@ -222,6 +236,9 @@ func conditions(ops Opcodes) []Condition {
} }
ranges[n] = c ranges[n] = c
} }
}
read(false)
read(true)
var out []Condition var out []Condition
for _, b := range controllerBounds { for _, b := range controllerBounds {
lo, loOK := parseNumber(ops[b.low]) lo, loOK := parseNumber(ops[b.low])
+9 -2
View File
@@ -338,7 +338,8 @@ func (d *Document) nodes(kind NodeKind) []*Node {
// SetDefine gives a variable a new value by changing its first #define, so // SetDefine gives a variable a new value by changing its first #define, so
// that each opcode that uses the variable changes with it. [Header.Set] on an // that each opcode that uses the variable changes with it. [Header.Set] on an
// opcode that uses the variable replaces the variable in that opcode instead. A // opcode that uses the variable replaces the variable in that opcode instead. A
// variable with no #define gets one at the start of the main file. The name // variable with no #define gets one at the start of the main file, after its
// byte order mark. The name
// includes its $. SetDefine returns an error wrapping [ErrInvalid], and changes // includes its $. SetDefine returns an error wrapping [ErrInvalid], and changes
// nothing, if the name and value can't be written as a #define. // nothing, if the name and value can't be written as a #define.
func (d *Document) SetDefine(name, value string) error { func (d *Document) SetDefine(name, value string) error {
@@ -356,7 +357,13 @@ func (d *Document) SetDefine(name, value string) error {
} }
} }
} }
d.Root.insert(0, // A byte order mark has to stay the first thing in the file, so the new
// directive goes after it.
at := 0
if first := d.Root.Nodes; len(first) > 0 && first[0].Kind == KindSpace && strings.HasPrefix(first[0].Raw, byteOrderMark) {
at = 1
}
d.Root.insert(at,
&Node{Kind: KindDefine, Raw: "#define " + name + " " + value, Name: name, Value: value}, &Node{Kind: KindDefine, Raw: "#define " + name + " " + value, Name: name, Value: value},
&Node{Kind: KindSpace, Raw: "\n"}) &Node{Kind: KindSpace, Raw: "\n"})
return nil return nil
+3 -2
View File
@@ -194,9 +194,10 @@ func (f *flattener) startHeader(header string, line int, file *File, own *Header
// setOpcode sets an opcode in the header being read. // setOpcode sets an opcode in the header being read.
func (f *flattener) setOpcode(name, value string) { func (f *flattener) setOpcode(name, value string) {
// Opcodes before any header belong to no header, so no region has them, as in
// sfizz.
if f.into == nil { if f.into == nil {
// Opcodes before any header apply to every region. return
f.into = &target{ops: f.levels[levelGlobal]}
} }
f.into.ops[name] = value f.into.ops[name] = value
} }
+65 -26
View File
@@ -2,6 +2,7 @@ package sfz
import ( import (
"cmp" "cmp"
"maps"
"math" "math"
"path" "path"
"regexp" "regexp"
@@ -25,7 +26,7 @@ func (f *Flat) Instrument() *Instrument {
regions := make([]Opcodes, len(f.Regions)) regions := make([]Opcodes, len(f.Regions))
for i, fr := range f.Regions { for i, fr := range f.Regions {
ops := fr.Opcodes ops := fr.Opcodes
regions[i] = ops regions[i] = withOwnNames(ops)
r, reason := e.region(ops) r, reason := e.region(ops)
if reason != "" { if reason != "" {
inst.Skipped[reason]++ inst.Skipped[reason]++
@@ -57,6 +58,7 @@ type evaluator struct {
// region returns the region that the opcodes describe, or the reason, one of // region returns the region that the opcodes describe, or the reason, one of
// the Skipped constants, that there is none. // the Skipped constants, that there is none.
func (e evaluator) region(ops Opcodes) (Region, string) { func (e evaluator) region(ops Opcodes) (Region, string) {
ops = withOwnNames(ops)
sample := strings.TrimSpace(ops["sample"]) sample := strings.TrimSpace(ops["sample"])
switch { switch {
case sample == "": case sample == "":
@@ -177,7 +179,7 @@ func (e evaluator) region(ops Opcodes) (Region, string) {
r.Conditions = conditions(ops) r.Conditions = conditions(ops)
r.Keyswitch = keyswitch(ops, shift) r.Keyswitch = keyswitch(ops, shift)
r.Modulations = e.modulations(ops) r.Modulations = e.modulations(ops)
r.Offset = int64(max(0, value("offset", 0))) r.Offset = toInt64(max(0, value("offset", 0)))
r.VelocityTracking = clamp(value("amp_veltrack", 100), -100, 100) r.VelocityTracking = clamp(value("amp_veltrack", 100), -100, 100)
r.VelocityCurve = velocityCurve(ops) r.VelocityCurve = velocityCurve(ops)
r.KeyCrossfade = crossfade(ops, "key", shift) r.KeyCrossfade = crossfade(ops, "key", shift)
@@ -193,17 +195,17 @@ func (e evaluator) region(ops Opcodes) (Region, string) {
if t := strings.TrimSpace(ops["trigger"]); t != "" { if t := strings.TrimSpace(ops["trigger"]); t != "" {
r.Trigger = t r.Trigger = t
} }
r.LoopMode = strings.TrimSpace(firstOf(ops, "loop_mode", "loopmode")) r.LoopMode = strings.TrimSpace(ops["loop_mode"])
r.LoopStart = frames(firstOf(ops, "loop_start", "loopstart")) r.LoopStart = frames(ops["loop_start"])
r.LoopEnd = frames(firstOf(ops, "loop_end", "loopend")) r.LoopEnd = frames(ops["loop_end"])
r.ReleaseDecay = max(0, value("rt_decay", 0)) r.ReleaseDecay = max(0, value("rt_decay", 0))
// A seq_length or seq_position below 1 plays as 1, as sfizz plays it. // A seq_length or seq_position below 1 plays as 1, as sfizz plays it.
if n, ok := parseNumber(ops["seq_length"]); ok { if n, ok := parseNumber(ops["seq_length"]); ok {
r.SequenceLength = max(1, int(n)) r.SequenceLength = max(1, toInt(n))
} }
if n, ok := parseNumber(ops["seq_position"]); ok { if n, ok := parseNumber(ops["seq_position"]); ok {
r.SequencePosition = max(1, int(n)) r.SequencePosition = max(1, toInt(n))
} }
if n, ok := parseNumber(ops["lorand"]); ok { if n, ok := parseNumber(ops["lorand"]); ok {
r.LowRandom = clamp(n, 0, 1) r.LowRandom = clamp(n, 0, 1)
@@ -211,15 +213,14 @@ func (e evaluator) region(ops Opcodes) (Region, string) {
if n, ok := parseNumber(ops["hirand"]); ok { if n, ok := parseNumber(ops["hirand"]); ok {
r.HighRandom = clamp(n, 0, 1) r.HighRandom = clamp(n, 0, 1)
} }
// polyphony_group is SFZ v2's name for group. if n, ok := parseNumber(ops["group"]); ok {
if n, ok := parseNumber(firstOf(ops, "group", "polyphony_group")); ok { r.Group = toInt(n)
r.Group = int(n)
} }
if n, ok := parseNumber(ops["off_by"]); ok { if n, ok := parseNumber(ops["off_by"]); ok {
g := int(n) g := toInt(n)
r.OffBy = &g r.OffBy = &g
} }
r.Polyphony = voiceLimit(ops["polyphony"]) r.Polyphony = polyphonyLimit(ops["polyphony"])
r.NotePolyphony = voiceLimit(ops["note_polyphony"]) r.NotePolyphony = voiceLimit(ops["note_polyphony"])
r.OffMode = defaultOffMode r.OffMode = defaultOffMode
switch mode := strings.ToLower(strings.TrimSpace(ops["off_mode"])); mode { switch mode := strings.ToLower(strings.TrimSpace(ops["off_mode"])); mode {
@@ -284,7 +285,7 @@ func crossfade(ops Opcodes, which string, shift int) *Crossfade {
n += shift n += shift
} }
} else if f, isNumber := parseNumber(v); isNumber { } else if f, isNumber := parseNumber(v); isNumber {
n, ok = int(f), true n, ok = toInt(f), true
} }
if !ok { if !ok {
return fallback, false return fallback, false
@@ -306,6 +307,17 @@ func crossfade(ops Opcodes, which string, shift int) *Crossfade {
return c return c
} }
// polyphonyLimit reads the value of polyphony, which is a number of voices, or
// legato_high, legato_last or legato_low, which each limit the region to one
// voice and choose which note sounds. It returns nil if v is neither.
func polyphonyLimit(v string) *int {
switch strings.TrimSpace(v) {
case "legato_high", "legato_last", "legato_low":
return ptr(1)
}
return voiceLimit(v)
}
// voiceLimit reads a number of voices, which is at least 1. It returns nil if // voiceLimit reads a number of voices, which is at least 1. It returns nil if
// v isn't one. // v isn't one.
func voiceLimit(v string) *int { func voiceLimit(v string) *int {
@@ -313,7 +325,7 @@ func voiceLimit(v string) *int {
if !ok || n < 1 { if !ok || n < 1 {
return nil return nil
} }
limit := int(n) limit := toInt(n)
return &limit return &limit
} }
@@ -338,27 +350,25 @@ func samplePath(defaultPath, sample string) string {
return strings.TrimPrefix(path.Clean(p), "./") return strings.TrimPrefix(path.Clean(p), "./")
} }
// firstOf returns the value of the first of the named opcodes that is set, or
// an empty string if none is.
func firstOf(ops Opcodes, names ...string) string {
for _, n := range names {
if v, ok := ops[n]; ok {
return v
}
}
return ""
}
// frames reads a sample position in frames. It returns nil if v isn't one. // frames reads a sample position in frames. It returns nil if v isn't one.
func frames(v string) *int64 { func frames(v string) *int64 {
n, ok := parseNumber(v) n, ok := parseNumber(v)
if !ok || n < 0 { if !ok || n < 0 {
return nil return nil
} }
f := int64(n) f := toInt64(n)
return &f return &f
} }
// toInt returns a number as a whole number, cut to the range of 32 bits, which
// is as far as the format goes. A number that doesn't fit would otherwise
// change sign.
func toInt(f float64) int { return int(clamp(math.Trunc(f), math.MinInt32, math.MaxInt32)) }
// toInt64 returns a number as a whole number, cut to the range that a float64
// holds exactly.
func toInt64(f float64) int64 { return int64(clamp(math.Trunc(f), -1<<53, 1<<53)) }
// clamp returns v, or the nearest of lo and hi if v is outside them. // clamp returns v, or the nearest of lo and hi if v is outside them.
func clamp(v, lo, hi float64) float64 { func clamp(v, lo, hi float64) float64 {
return math.Min(hi, math.Max(lo, v)) return math.Min(hi, math.Max(lo, v))
@@ -396,8 +406,37 @@ var modulatedTargets = []string{
// controller number, or only name something. // controller number, or only name something.
var handledRE = regexp.MustCompile(`^(?:(?:lo|hi)(?:hd)?cc\d+|set_(?:hd)?cc\d+|label_cc\d+|amp_velcurve_\d+|[a-z_]*_label)$`) var handledRE = regexp.MustCompile(`^(?:(?:lo|hi)(?:hd)?cc\d+|set_(?:hd)?cc\d+|label_cc\d+|amp_velcurve_\d+|[a-z_]*_label)$`)
// withOwnNames returns the opcodes with each name that is another name of an
// opcode replaced by the opcode's own, such as loopmode by loop_mode. An opcode
// that is set under its own name keeps that value, and one that is set under
// several other names takes the value of the name that sorts last, so that the
// result is the same each time.
func withOwnNames(ops Opcodes) Opcodes {
var others []string
for name := range ops {
if ownName(name) != name {
others = append(others, name)
}
}
if others == nil {
return ops
}
slices.Sort(others)
out := maps.Clone(ops)
for _, name := range others {
delete(out, name)
}
for _, name := range others {
if _, set := ops[ownName(name)]; !set {
out[ownName(name)] = ops[name]
}
}
return out
}
// handled reports whether the typed model reads an opcode. // handled reports whether the typed model reads an opcode.
func handled(name string) bool { func handled(name string) bool {
name = ownName(name)
if handledNames[name] || handledRE.MatchString(name) { if handledNames[name] || handledRE.MatchString(name) {
return true return true
} }
+7 -1
View File
@@ -11,7 +11,8 @@ var (
headerRE = regexp.MustCompile(`^<([A-Za-z_]+)>`) headerRE = regexp.MustCompile(`^<([A-Za-z_]+)>`)
// opcodeRE reads an opcode's name and = at the start of the text. // opcodeRE reads an opcode's name and = at the start of the text.
opcodeRE = regexp.MustCompile(`^([A-Za-z0-9_$]+)=`) opcodeRE = regexp.MustCompile(`^([A-Za-z0-9_$]+)=`)
// defineRE reads a #define's variable and value, up to the end of its line. // defineRE reads a #define's variable and the rest of its line, whose first
// word is the value.
defineRE = regexp.MustCompile(`^#define[ \t]+(\$[A-Za-z0-9_]{1,128})[ \t]+([^\r\n]*)`) defineRE = regexp.MustCompile(`^#define[ \t]+(\$[A-Za-z0-9_]{1,128})[ \t]+([^\r\n]*)`)
// includeRE reads an #include's quoted path. // includeRE reads an #include's quoted path.
includeRE = regexp.MustCompile(`^#include[ \t]+"([^"\r\n]*)"`) includeRE = regexp.MustCompile(`^#include[ \t]+"([^"\r\n]*)"`)
@@ -160,6 +161,11 @@ func (l *lexer) directive(src string) bool {
for length > valueStart && isSpace(rest[length-1]) { for length > valueStart && isSpace(rest[length-1]) {
length-- length--
} }
// The value is the first word, as ARIA and sfizz read it, so that two
// directives can share a line. What follows it is read as the text it is.
if k := strings.IndexAny(rest[valueStart:length], " \t"); k >= 0 {
length = valueStart + k
}
l.add(src, l.pos+length, &Node{Kind: KindDefine, Name: m[1], Value: strings.TrimSpace(rest[valueStart:length])}) l.add(src, l.pos+length, &Node{Kind: KindDefine, Name: m[1], Value: strings.TrimSpace(rest[valueStart:length])})
return true return true
} }
+2 -2
View File
@@ -143,8 +143,8 @@ func (e evaluator) shape(ops Opcodes, target string, n int, x float64) float64 {
// exist. // exist.
func (e evaluator) curveIndex(ops Opcodes, target string, n int) int { func (e evaluator) curveIndex(ops Opcodes, target string, n int) int {
if v, ok := parseNumber(ops[fmt.Sprintf("%s_curvecc%d", target, n)]); ok { if v, ok := parseNumber(ops[fmt.Sprintf("%s_curvecc%d", target, n)]); ok {
if _, exists := e.curves[int(v)]; exists { if _, exists := e.curves[toInt(v)]; exists {
return int(v) return toInt(v)
} }
} }
return 0 return 0
+2 -2
View File
@@ -221,7 +221,7 @@ func adjust(own Opcodes, opcode, field string, got, want Region) bool {
next := base + (w - g) next := base + (w - g)
if v, _ := fieldAt(reflect.ValueOf(want), field); v.Kind() != reflect.Float64 && v.Kind() != reflect.Pointer { if v, _ := fieldAt(reflect.ValueOf(want), field); v.Kind() != reflect.Float64 && v.Kind() != reflect.Pointer {
next = math.Round(next) next = math.Round(next)
own[opcode] = strconv.FormatInt(int64(next), 10) own[opcode] = strconv.FormatInt(toInt64(next), 10)
} else { } else {
own[opcode] = num(next) own[opcode] = num(next)
} }
@@ -379,5 +379,5 @@ func owns(field, name string) bool {
return false return false
} }
re, ok := ownedNames[field] re, ok := ownedNames[field]
return ok && re.MatchString(name) return ok && re.MatchString(ownName(name))
} }
+25
View File
@@ -231,3 +231,28 @@ func TestApplyProperty(t *testing.T) {
t.Errorf("only %d edits applied", applied) 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())
}
}
+18
View File
@@ -102,6 +102,10 @@ var (
patterns []matcher patterns []matcher
// headerByName holds the headers, by lowercase name. // headerByName holds the headers, by lowercase name.
headerByName map[string]*HeaderInfo headerByName map[string]*HeaderInfo
// ownNames holds the own name of each opcode that has other names, by each
// other name. Families such as loccN are left out, and so is pitch, which
// the typed model adds to tune and doesn't take as another name for it.
ownNames map[string]string
) )
// patternRE reads a name's placeholders: a run of N, X and Y letters, or a *. // patternRE reads a name's placeholders: a run of N, X and Y letters, or a *.
@@ -135,6 +139,7 @@ func pattern(name string) *regexp.Regexp {
func loadRegistry() { func loadRegistry() {
registryOnce.Do(func() { registryOnce.Do(func() {
byName = map[string]*OpcodeInfo{} byName = map[string]*OpcodeInfo{}
ownNames = map[string]string{}
headerByName = map[string]*HeaderInfo{} headerByName = map[string]*HeaderInfo{}
for i := range headerData { for i := range headerData {
headerByName[headerData[i].Name] = &headerData[i] headerByName[headerData[i].Name] = &headerData[i]
@@ -147,6 +152,9 @@ func loadRegistry() {
switch { switch {
case re == nil: case re == nil:
byName[name] = info byName[name] = info
if name != info.Name && pattern(info.Name) == nil && name != "pitch" {
ownNames[name] = info.Name
}
case strings.Contains(name, "*"): case strings.Contains(name, "*"):
wild = append(wild, matcher{re, info}) wild = append(wild, matcher{re, info})
default: default:
@@ -175,6 +183,16 @@ func Lookup(name string) (OpcodeInfo, bool) {
return OpcodeInfo{}, false return OpcodeInfo{}, false
} }
// ownName returns the name that the format gives an opcode, for any other name
// it is known by. It returns name for an opcode that has no other name.
func ownName(name string) string {
loadRegistry()
if own, ok := ownNames[name]; ok {
return own
}
return name
}
// KnownOpcodes returns every opcode of the format, in the order the format // KnownOpcodes returns every opcode of the format, in the order the format
// lists them. // lists them.
func KnownOpcodes() iter.Seq[OpcodeInfo] { func KnownOpcodes() iter.Seq[OpcodeInfo] {
+17 -12
View File
@@ -95,11 +95,11 @@ func TestFlatten(t *testing.T) {
// headers, and for part of an opcode's name. // headers, and for part of an opcode's name.
func TestVariableOpcodes(t *testing.T) { func TestVariableOpcodes(t *testing.T) {
doc := parseFiles(t, map[string]string{ doc := parseFiles(t, map[string]string{
"main.sfz": "#define $RANGE lokey=36 hikey=40\n#define $CC 70\n#define $HEAD <region>\n" + "main.sfz": "#define $RANGE lokey=36\n#define $CC 70\n#define $HEAD <region>\n" +
"$HEAD sample=a.wav $RANGE locc$CC=5\n", "$HEAD sample=a.wav $RANGE locc$CC=5\n",
}) })
ops := doc.Flatten().Regions[0].Opcodes ops := doc.Flatten().Regions[0].Opcodes
if ops["lokey"] != "36" || ops["hikey"] != "40" || ops["locc70"] != "5" || ops["sample"] != "a.wav" { if ops["lokey"] != "36" || ops["locc70"] != "5" || ops["sample"] != "a.wav" {
t.Errorf("%v", ops) t.Errorf("%v", ops)
} }
} }
@@ -191,7 +191,7 @@ func TestInheritance(t *testing.T) {
got[r.Sample] = r got[r.Sample] = r
} }
// A region has the opcodes of the headers above it, its own winning // A region has the opcodes of the headers above it, its own winning
// (spec); a new <group> starts without the last group's opcodes (choice: // (spec); a new <group> starts without the last group's opcodes (sfizz;
// the spec doesn't say); and default_path is the one set before the // the spec doesn't say); and default_path is the one set before the
// region. // region.
if r := got["One/a b.wav"]; r.Tune != 7 || r.LowVelocity != 64 || r.Pan != 10 { if r := got["One/a b.wav"]; r.Tune != 7 || r.LowVelocity != 64 || r.Pan != 10 {
@@ -203,8 +203,8 @@ func TestInheritance(t *testing.T) {
if r := got["Two/d.wav"]; r.Tune != 0 || r.LowVelocity != 1 || r.HighVelocity != 90 || r.Pan != 10 { if r := got["Two/d.wav"]; r.Tune != 0 || r.LowVelocity != 1 || r.HighVelocity != 90 || r.Pan != 10 {
t.Errorf("third region %+v", r) t.Errorf("third region %+v", r)
} }
// A <master> clears the group, and a <global> clears everything (choice: // A <master> clears the group, and a <global> clears the master and the
// the spec says a global applies until the next one). // group (sfizz; the spec says a global applies until the next one).
if r := got["Two/e.wav"]; r.HighVelocity != 127 || r.Pan != -20 { if r := got["Two/e.wav"]; r.HighVelocity != 127 || r.Pan != -20 {
t.Errorf("fourth region %+v", r) t.Errorf("fourth region %+v", r)
} }
@@ -215,11 +215,15 @@ func TestInheritance(t *testing.T) {
t.Errorf("unread %v", inst.Unread) t.Errorf("unread %v", inst.Unread)
} }
// Opcodes before any header apply to every region (choice: the spec // Opcodes before any header belong to no region (sfizz; the spec doesn't
// doesn't say). // say). The document keeps them, and Validate reports them.
if r := parseText(t, "volume=-1\n<region> sample=a.wav").Regions[0]; r.Volume != -1 { if r := parseText(t, "volume=-1\ndefault_path=X/\n<region> sample=a.wav").Regions[0]; r.Volume != 0 || r.Sample != "a.wav" {
t.Errorf("opcode before any header %+v", r) t.Errorf("opcode before any header %+v", r)
} }
doc := parseFiles(t, map[string]string{"main.sfz": "volume=-1\n<region> sample=a.wav"})
if p := doc.Validate(); len(p) != 1 || p[0].Code != "opcode.no-header" || p[0].Severity != SeverityWarning || doc.String() != "volume=-1\n<region> sample=a.wav" {
t.Errorf("problems %v, text %q", p, doc.String())
}
// A new <control> resets default_path but keeps the other control // A new <control> resets default_path but keeps the other control
// settings (spec, describing ARIA; Cakewalk keeps it). // settings (spec, describing ARIA; Cakewalk keeps it).
@@ -320,7 +324,8 @@ func TestControllers(t *testing.T) {
} }
// Modulation by a controller is kept as it is, to be applied as notes // Modulation by a controller is kept as it is, to be applied as notes
// play: the setting has only its own value (spec: _onccN adds), with // play: the setting has only its own value (choice: the spec doesn't say how _onccN
// combines with it, and its tune_onccN example reads as adding), with
// pan's curve 1 and the others' straight one, in the settings' own // pan's curve 1 and the others' straight one, in the settings' own
// units, and the depth of an amplitude as a percentage. // units, and the depth of an amplitude as a percentage.
r := got["natural.wav"] r := got["natural.wav"]
@@ -416,8 +421,8 @@ func TestVariantsAndChokes(t *testing.T) {
if r := got["zero.wav"]; r.SequenceLength != 1 || r.SequencePosition != 1 || r.LowRandom != 0 || r.HighRandom != 1 { if r := got["zero.wav"]; r.SequenceLength != 1 || r.SequencePosition != 1 || r.LowRandom != 0 || r.HighRandom != 1 {
t.Errorf("out of range %+v", r) t.Errorf("out of range %+v", r)
} }
// polyphony_group is v2's name for group (spec), and off_by may name group // polyphony_group is ARIA's alias of group (spec), and an off_by of group
// 0 (spec). // 0 is kept for the host to read, as the spec says some players ignore it.
if r := got["v2.wav"]; r.Group != 7 || r.OffBy == nil || *r.OffBy != 0 { if r := got["v2.wav"]; r.Group != 7 || r.OffBy == nil || *r.OffBy != 0 {
t.Errorf("polyphony_group %+v", r) t.Errorf("polyphony_group %+v", r)
} }
@@ -616,7 +621,7 @@ func TestSplendid(t *testing.T) {
} }
// The lowest region that always plays: its own release plus 0.7 s from the // The lowest region that always plays: its own release plus 0.7 s from the
// Release control at 0.35 × 2 (spec: _onccN adds), and a hold and decay // Release control at 0.35 × 2 (choice: _onccN adds), and a hold and decay
// shortened by its key. Its level comes from the volume control at 100 // shortened by its key. Its level comes from the volume control at 100
// through curve 4, x² (sfizz), multiplied (sfizz), which is kept to be // through curve 4, x² (sfizz), multiplied (sfizz), which is kept to be
// applied as notes play. // applied as notes play.
+7 -3
View File
@@ -106,7 +106,8 @@ func (v *validator) endHeader() {
continue continue
} }
hi, ok := v.numbers["hi"+rest] hi, ok := v.numbers["hi"+rest]
if lo := v.numbers[name]; ok && lo.value > hi.value { // A hikey of -1 keeps the region from playing, whatever its lokey.
if lo := v.numbers[name]; ok && lo.value > hi.value && hi.value != -1 {
v.add(lo.file, lo.at, SeverityWarning, "range.inverted", fmt.Sprintf("%s is above hi%s", name, rest)) v.add(lo.file, lo.at, SeverityWarning, "range.inverted", fmt.Sprintf("%s is above hi%s", name, rest))
} }
} }
@@ -119,7 +120,7 @@ func (v *validator) endHeader() {
// anything. // anything.
func (v *validator) opcode(f *File, n *Node, name, value string, _ bool) { func (v *validator) opcode(f *File, n *Node, name, value string, _ bool) {
if !v.inHeader { if !v.inHeader {
v.add(f, n, SeverityInfo, "opcode.no-header", fmt.Sprintf("%s is before any header", name)) v.add(f, n, SeverityWarning, "opcode.no-header", fmt.Sprintf("%s is before any header, so no region has it", name))
v.inHeader = true v.inHeader = true
v.numbers = map[string]opcodeAt{} v.numbers = map[string]opcodeAt{}
} }
@@ -172,7 +173,10 @@ func (v *validator) value(f *File, n *Node, name, value string, info OpcodeInfo)
if info.Type == TypeInteger && !info.Note && x != float64(int64(x)) { if info.Type == TypeInteger && !info.Note && x != float64(int64(x)) {
v.add(f, n, SeverityInfo, "value.type", fmt.Sprintf("%s=%s isn't a whole number", name, value)) v.add(f, n, SeverityInfo, "value.type", fmt.Sprintf("%s=%s isn't a whole number", name, value))
} }
if info.Min != nil && x < *info.Min || info.Max != nil && x > *info.Max { // SFZ v2 allows -1 for lokey, hikey and key, to keep a region from
// playing on any key, though the table of ranges starts at 0.
disables := x == -1 && (name == "lokey" || name == "hikey" || name == "key")
if !disables && (info.Min != nil && x < *info.Min || info.Max != nil && x > *info.Max) {
v.add(f, n, SeverityWarning, "value.range", fmt.Sprintf("%s=%s is outside %s", name, value, bounds(info))) v.add(f, n, SeverityWarning, "value.range", fmt.Sprintf("%s=%s is outside %s", name, value, bounds(info)))
} }
v.numbers[name] = opcodeAt{value: x, at: n, file: f} v.numbers[name] = opcodeAt{value: x, at: n, file: f}
+4 -1
View File
@@ -27,7 +27,10 @@ func parseNote(v string) (int, bool) {
if m == nil { if m == nil {
return 0, false return 0, false
} }
octave, _ := strconv.Atoi(m[3]) octave, err := strconv.Atoi(m[3])
if err != nil {
return 0, false
}
n := (octave+1)*12 + semitones[strings.ToLower(m[1])[0]] n := (octave+1)*12 + semitones[strings.ToLower(m[1])[0]]
switch m[2] { switch m[2] {
case "#": case "#":