Files
sfz/sfz_test.go
T
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

741 lines
29 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package sfz
import (
"errors"
"io/fs"
"math"
"os"
"path/filepath"
"reflect"
"slices"
"strings"
"testing"
)
// The tests mark where their expected values come from: "spec" is
// sfzformat.com, "sfizz" is the sfizz player's source, which the spec leaves
// open points to, and "choice" is Zampler's own where neither settles it.
// files returns a Resolver that reads from a map of paths to contents.
func files(m map[string]string) Resolver {
return func(p string) ([]byte, error) {
if s, ok := m[p]; ok {
return []byte(s), nil
}
return nil, fs.ErrNotExist
}
}
// parseFiles parses the main file of a map of files.
func parseFiles(t *testing.T, m map[string]string, opts ...ParseOption) *Document {
t.Helper()
doc, err := Parse(strings.NewReader(m["main.sfz"]), append([]ParseOption{WithResolver(files(m))}, opts...)...)
if err != nil {
t.Fatal(err)
}
return doc
}
// parseText parses a one-file instrument.
func parseText(t *testing.T, text string) *Instrument {
t.Helper()
return parseFiles(t, map[string]string{"main.sfz": text}).Flatten().Instrument()
}
// near reports whether two numbers are equal to within a rounding error.
func near(a, b float64) bool { return math.Abs(a-b) < 1e-9 }
// TestVariableNames checks that a variable's name ends at the shortest
// defined name, so an underscore after it is text (ARIA), and that a name with
// an underscore is found when no shorter name is defined.
func TestVariableNames(t *testing.T) {
doc := parseFiles(t, map[string]string{
"main.sfz": "#define $MIC Far\n#define $VEL1 10\n#define $CODE_01 AB\n" +
"<region> sample=$MIC_$VEL1_one-$CODE_01.flac $NOPE_x\n",
})
ops := doc.Flatten().Regions[0].Opcodes
// An undefined variable is left as it is.
if ops["sample"] != "Far_10_one-AB.flac $NOPE_x" {
t.Errorf("sample %q", ops["sample"])
}
}
// TestFlatten checks that Flatten reads includes, variables and comments as
// the format says.
func TestFlatten(t *testing.T) {
doc := parseFiles(t, map[string]string{
"main.sfz": "#define $DIR Data // the folder\n" +
"#define $V soft\n" +
"<group> #include \"$DIR/a.txt\" lovel=1 #include \"Data/b.txt\"\n" +
"#define $V loud\n" +
"/* a\nblock */<region> sample=$V C#4.wav $UNDEFINED=1\n",
"Data/a.txt": "#define $X 7\nhivel=$X",
"Data/b.txt": "<region> sample=$V.wav",
})
flat := doc.Flatten()
if len(flat.Regions) != 2 {
t.Fatalf("regions %v", flat.Regions)
}
// Variables take the value they had where they are used (sfizz), an
// include is read where it was written (spec), comments are dropped, and a
// # in a note name isn't a directive.
first, second := flat.Regions[0].Opcodes, flat.Regions[1].Opcodes
if first["sample"] != "soft.wav" || first["hivel"] != "7" || first["lovel"] != "1" {
t.Errorf("first region %v", first)
}
if second["sample"] != "loud C#4.wav" || second["$UNDEFINED"] != "1" || second["hivel"] != "7" {
t.Errorf("second region %v", second)
}
if flat.Regions[0].File != "Data/b.txt" || flat.Regions[1].Line != 6 {
t.Errorf("positions %+v %+v", flat.Regions[0], flat.Regions[1])
}
}
// TestVariableOpcodes checks that a variable can stand for opcodes and
// headers, and for part of an opcode's name.
func TestVariableOpcodes(t *testing.T) {
doc := parseFiles(t, map[string]string{
"main.sfz": "#define $RANGE lokey=36\n#define $CC 70\n#define $HEAD <region>\n" +
"$HEAD sample=a.wav $RANGE locc$CC=5\n",
})
ops := doc.Flatten().Regions[0].Opcodes
if ops["lokey"] != "36" || ops["locc70"] != "5" || ops["sample"] != "a.wav" {
t.Errorf("%v", ops)
}
}
// TestParseErrors checks the errors that Parse returns for includes that
// loop, nest too deeply or can't be read.
func TestParseErrors(t *testing.T) {
// An include loop and an include nested too deeply are refused (spec:
// "recursion must be avoided"; sfizz limits the depth).
loop := map[string]string{"a": `#include "b"`, "b": `#include "a"`}
if _, err := Parse(strings.NewReader(loop["a"]), WithResolver(files(loop))); err != nil {
// The main file has no name, so b includes a, which includes b.
if !errors.Is(err, ErrIncludeLoop) || !errors.Is(err, ErrInvalid) {
t.Errorf("loop: %v", err)
}
} else {
t.Errorf("loop: no error")
}
deep := map[string]string{}
for i := 0; i <= DefaultLimits.MaxDepth+1; i++ {
deep[string(rune('a'+i))] = `#include "` + string(rune('b'+i)) + `"`
}
if _, err := Parse(strings.NewReader(deep["a"]), WithResolver(files(deep))); !errors.Is(err, ErrInvalid) {
t.Errorf("deep includes: %v", err)
}
// A missing include is reported and left unresolved, unless asked to fail.
missing := `<region> sample=a.wav #include "missing.sfz"`
doc, err := Parse(strings.NewReader(missing), WithResolver(files(nil)))
if err != nil {
t.Fatal(err)
}
problems := doc.Validate()
if len(problems) != 1 || problems[0].Code != "include.unresolved" || problems[0].Col != 23 {
t.Errorf("problems %+v", problems)
}
if len(doc.Flatten().Regions) != 1 {
t.Errorf("regions %v", doc.Flatten().Regions)
}
_, err = Parse(strings.NewReader(missing), WithResolver(files(nil)), WithIncludes(IncludesFail))
if !errors.Is(err, ErrUnresolved) || !errors.Is(err, fs.ErrNotExist) {
t.Errorf("fail mode: %v", err)
}
}
// TestIncludes checks that Includes lists the files that a file includes
// itself.
func TestIncludes(t *testing.T) {
// A file's includes are listed once each, in order, with its own
// variables substituted, backslashes read as slashes and paths cleaned.
// An include in a comment isn't one, and an undefined variable is kept.
text := "#define $KIT kick\n" +
"#include \"mappings/$KIT/a.sfz\"\n" +
"// #include \"commented.sfz\"\n" +
"<group> #include \"mappings\\$KIT\\.\\b.sfz\"\n" +
"#include \"mappings/$KIT/a.sfz\"\n" +
"#include \"$UNSET/c.sfz\"\n"
want := []string{"mappings/kick/a.sfz", "mappings/kick/b.sfz", "$UNSET/c.sfz"}
if got := Includes([]byte(text)); !reflect.DeepEqual(got, want) {
t.Errorf("got %q, want %q", got, want)
}
// A file with no includes has none.
if got := Includes([]byte("<region> sample=a.wav")); len(got) != 0 {
t.Errorf("got %q, want none", got)
}
}
// TestInheritance checks which opcodes a region takes from the headers above
// it.
func TestInheritance(t *testing.T) {
inst := parseText(t, `
<control> default_path=One/
<global> pan=10
<group> lovel=64 tune=5
<region> sample=a b.wav tune=7
<region> sample=c.wav
<control> default_path=Two/
<group> hivel=90
<region> sample=d.wav
<effect> type=reverb
<master> pan=-20
<region> sample=e.wav
<global>
<region> sample=f.wav
`)
got := map[string]Region{}
for _, r := range inst.Regions {
got[r.Sample] = r
}
// A region has the opcodes of the headers above it, its own winning
// (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
// region.
if r := got["One/a b.wav"]; r.Tune != 7 || r.LowVelocity != 64 || r.Pan != 10 {
t.Errorf("first region %+v", r)
}
if r := got["One/c.wav"]; r.Tune != 5 || r.LowVelocity != 64 {
t.Errorf("second region %+v", r)
}
if r := got["Two/d.wav"]; r.Tune != 0 || r.LowVelocity != 1 || r.HighVelocity != 90 || r.Pan != 10 {
t.Errorf("third region %+v", r)
}
// A <master> clears the group, and a <global> clears the master and the
// group (sfizz; the spec says a global applies until the next one).
if r := got["Two/e.wav"]; r.HighVelocity != 127 || r.Pan != -20 {
t.Errorf("fourth region %+v", r)
}
if r := got["Two/f.wav"]; r.Pan != 0 || r.Volume != 0 {
t.Errorf("fifth region %+v", r)
}
if inst.Unread["<effect>"] != 1 || inst.Unread["type"] != 0 {
t.Errorf("unread %v", inst.Unread)
}
// Opcodes before any header belong to no region (sfizz; the spec doesn't
// say). The document keeps them, and Validate reports them.
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)
}
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
// settings (spec, describing ARIA; Cakewalk keeps it).
reset := parseText(t, "<control> default_path=A/ note_offset=12\n<control>\n<region> sample=x.wav key=60")
if r := reset.Regions[0]; r.Sample != "x.wav" || r.LowKey != 72 {
t.Errorf("after a second <control> %+v", r)
}
}
// TestDefaults checks the values of a region that sets nothing.
func TestDefaults(t *testing.T) {
r := parseText(t, "<region> sample=a.wav").Regions[0]
// Spec: lovel 1, hivel 127, pitch_keycenter 60, pitch_keytrack 100,
// amp_veltrack 100, ampeg_release 0.001, ampeg_sustain 100, every other
// envelope stage 0, seq_length and seq_position 1, lorand 0 and hirand 1,
// group 0 and no off_by, and no voice limits. (sfizz starts lovel at 0; velocity 0 is a
// note-off, so it makes no difference.)
want := Region{
Sample: "a.wav", LowKey: 0, HighKey: 127, RootKey: 60, LowVelocity: 1, HighVelocity: 127,
KeyTrack: 100, VelocityTracking: 100, Envelope: Envelope{Sustain: 100, Release: 0.001}, Trigger: "attack",
SequenceLength: 1, SequencePosition: 1, HighRandom: 1, OffMode: "fast", OffTime: 0.006,
}
if !reflect.DeepEqual(r, want) {
t.Errorf("defaults\n got %+v\nwant %+v", r, want)
}
}
// TestKeysAndNotes checks how keys, note names and the offsets of the control
// header set a region's keys.
func TestKeysAndNotes(t *testing.T) {
inst := parseText(t, `
<control> note_offset=1 octave_offset=-1
<region> sample=a.wav key=c4
<region> sample=b.wav lokey=21 hikey=c#2 pitch_keycenter=eb2
<region> sample=c.wav lokey=-1 hikey=-1
<region> sample=d.wav pitch_keycenter=sample
<region> sample=*sine
<region> lokey=1
`)
if len(inst.Regions) != 3 {
t.Fatalf("regions %+v", inst.Regions)
}
// Note names count from c-1, so c4 is 60 (spec), and the control's
// offsets move every key (spec).
if r := inst.Regions[0]; r.LowKey != 49 || r.HighKey != 49 || r.RootKey != 49 {
t.Errorf("key=c4 %+v", r)
}
if r := inst.Regions[1]; r.LowKey != 10 || r.HighKey != 26 || r.RootKey != 28 {
t.Errorf("ranges %+v", r)
}
// A root note that is the sample file's (spec: allowed in v2) is the
// importer's to read, so the region says so, and not the file's note
// before it is read; sfizz keeps the file's root over key, which only sets
// the keys (sfztest).
if r := inst.Regions[2]; !r.RootFromSample || r.Sample != "d.wav" {
t.Errorf("pitch_keycenter=sample %+v", r)
}
if inst.Regions[0].RootFromSample || inst.Regions[1].RootFromSample {
t.Errorf("a root note was taken from the sample: %+v", inst.Regions)
}
if r := parseText(t, "<region> sample=e.wav key=c4 pitch_keycenter=sample").Regions[0]; !r.RootFromSample || r.LowKey != 60 || r.HighKey != 60 {
t.Errorf("key with a root note from the sample %+v", r)
}
want := map[string]int{SkippedNotKeys: 1, SkippedGenerated: 1, SkippedNoSample: 1}
for reason, n := range want {
if inst.Skipped[reason] != n {
t.Errorf("skipped %v", inst.Skipped)
}
}
}
// TestControllers checks how modulation by controllers, and the conditions on
// them, are read.
func TestControllers(t *testing.T) {
inst := parseText(t, `
<control> set_cc7=127 set_hdcc20=0.25 set_cc64=0 label_cc20=Mic mix
<curve> curve_index=9 v000=0 v064=1 v127=1
<global> sw_default=c0 sw_lokey=c0 sw_hikey=d0
<region> sample=natural.wav sw_last=c0 amplitude_oncc7=50 volume_oncc20=-8 pan_oncc20=100 pan_curvecc20=1
<region> sample=retuned.wav sw_last=c#0
<region> sample=pedal.wav locc64=64
<region> sample=no-pedal.wav hicc64=63 ampeg_releasecc20=4 ampeg_release_curvecc20=9
<region> sample=switched.wav on_locc64=127
<region> sample=first.wav lorand=0 hirand=0.5
<region> sample=second.wav lorand=0.5 hirand=1
<region> sample=rr2.wav seq_position=2 seq_length=2
<region> sample=hold.wav ampeg_hold=8 ampeg_hold_oncc133=-6 key=127
<region> sample=vel.wav tune_oncc20=50 tune_oncc134=7
`)
got := map[string]Region{}
for _, r := range inst.Regions {
got[r.Sample] = r
}
// A region that a controller or a keyswitch only sometimes plays is kept,
// with what it needs, and only one that a controller starts is skipped.
if len(got) != 9 || !reflect.DeepEqual(inst.Skipped, map[string]int{SkippedByCC: 1}) {
t.Fatalf("regions %v, skipped %v", got, inst.Skipped)
}
// Modulation by a controller is kept as it is, to be applied as notes
// 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
// units, and the depth of an amplitude as a percentage.
r := got["natural.wav"]
want := []Modulation{
{Target: TargetAmplitude, Controller: 7, Depth: 50},
{Target: TargetVolume, Controller: 20, Depth: -8},
{Target: TargetPan, Controller: 20, Depth: 100, Curve: 1},
}
if !reflect.DeepEqual(r.Modulations, want) || r.Volume != 0 || r.Pan != 0 {
t.Errorf("natural %+v", r)
}
if !reflect.DeepEqual(r.Keyswitch, &Keyswitch{Last: ptr(12)}) {
t.Errorf("natural's keyswitch %+v", r.Keyswitch)
}
// A custom curve is kept with its points, and is applied when the note
// plays; the opcodes that aren't among the settings that controllers move
// as notes play are taken at the starting values: a quarter of the way
// is about half of the way to v064, and the release adds to its 0.001 s
// default (spec).
if r := got["no-pedal.wav"]; !near(r.Envelope.Release, 0.001+4*(0.25*127/64)) {
t.Errorf("custom curve %+v", r)
}
// Controller 133 is the note number (spec), taken at the region's root
// note (choice), so the hold shortens towards the top key.
if r := got["hold.wav"]; !near(r.Envelope.Hold, 2) {
t.Errorf("key-dependent hold %+v", r)
}
// A controller above 127 belongs to the note, so a modulation by it is
// taken at once: tune_oncc134 is the gate, 1 while a note is held.
if r := got["vel.wav"]; !near(r.Tune, 7) || len(r.Modulations) != 1 || r.Modulations[0].Controller != 20 {
t.Errorf("a note's controller %+v", r)
}
// The conditions are kept, and the switch for a keyswitch that none sets.
if r := got["pedal.wav"]; !reflect.DeepEqual(r.Conditions, []Condition{{Source: SourceController, Controller: 64, Low: 64.0 / 127, High: 1}}) {
t.Errorf("pedal %+v", r.Conditions)
}
if r := got["no-pedal.wav"]; len(r.Conditions) != 1 || r.Conditions[0].High >= 64.0/127 || r.Conditions[0].High < 63.0/127 {
t.Errorf("no-pedal %+v", r.Conditions)
}
if got["retuned.wav"].Keyswitch == nil || *got["retuned.wav"].Keyswitch.Last != 13 {
t.Errorf("retuned %+v", got["retuned.wav"].Keyswitch)
}
// Random and round-robin variants are all kept, to be chosen as they play.
for _, name := range []string{"first.wav", "second.wav", "rr2.wav"} {
if _, ok := got[name]; !ok {
t.Errorf("the variant %s isn't kept", name)
}
}
// The instrument names the controllers it uses, with the starting values
// that set_cc and set_hdcc give.
wantControls := []Control{
{Controller: 7, Value: 1},
{Controller: 20, Label: "Mic mix", Value: 0.25},
{Controller: 64, Value: 0},
}
if !reflect.DeepEqual(inst.Controls, wantControls) {
t.Errorf("controls %+v, want %+v", inst.Controls, wantControls)
}
if k := inst.Keyswitches; k == nil || k.Low != 12 || k.High != 14 || k.Default == nil || *k.Default != 12 {
t.Errorf("keyswitches %+v", k)
}
}
// TestVariantsAndChokes checks how round robins, random variants and choke
// groups are read.
func TestVariantsAndChokes(t *testing.T) {
inst := parseText(t, `
<region> sample=plain.wav
<region> sample=v2.wav polyphony_group=7 off_by=0
<group> seq_length=3 group=2 off_by=2
<region> sample=rr1.wav seq_position=1
<region> sample=rr2.wav seq_position=2 lorand=0.25 hirand=0.75
<region> sample=zero.wav seq_position=0 seq_length=0 lorand=-1 hirand=2
`)
got := map[string]Region{}
for _, r := range inst.Regions {
got[r.Sample] = r
}
// A region is in a round robin of 1 at position 1, takes every random
// value, is in group 0 and is stopped by no group (spec).
if r := got["plain.wav"]; r.SequenceLength != 1 || r.SequencePosition != 1 || r.LowRandom != 0 || r.HighRandom != 1 || r.Group != 0 || r.OffBy != nil {
t.Errorf("defaults %+v", r)
}
// The group's settings reach its regions (spec).
if r := got["rr2.wav"]; r.SequenceLength != 3 || r.SequencePosition != 2 || r.LowRandom != 0.25 || r.HighRandom != 0.75 || r.Group != 2 || r.OffBy == nil || *r.OffBy != 2 {
t.Errorf("round robin, random and choke %+v", r)
}
// A length or position below 1 plays as 1 (sfizz), and random values are
// from 0 to 1 (spec).
if r := got["zero.wav"]; r.SequenceLength != 1 || r.SequencePosition != 1 || r.LowRandom != 0 || r.HighRandom != 1 {
t.Errorf("out of range %+v", r)
}
// polyphony_group is ARIA's alias of group (spec), and an off_by of group
// 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 {
t.Errorf("polyphony_group %+v", r)
}
// None of these opcodes is counted as unread.
if len(inst.Unread) != 0 {
t.Errorf("unread %v", inst.Unread)
}
}
// TestStartingControllers checks the starting values of the controllers.
func TestStartingControllers(t *testing.T) {
// Without set_cc, volume starts at 100, pan in the middle and expression
// at full (sfizz); other controllers start at 0 (sfizz). The controllers
// are named with their starting values, and the modulation by them is kept.
inst := parseText(t, `
<region> sample=a.wav amplitude_oncc7=100 pan_oncc10=100 pan_curvecc10=1 volume_oncc11=-10 volume_oncc1=-10
`)
r := inst.Regions[0]
if len(r.Modulations) != 4 || r.Volume != 0 || r.Pan != 0 {
t.Errorf("a region %+v", r)
}
want := []Control{{Controller: 1, Value: 0}, {Controller: 7, Value: 100.0 / 127}, {Controller: 10, Value: 0.5}, {Controller: 11, Value: 1}}
if !reflect.DeepEqual(inst.Controls, want) {
t.Errorf("controls %+v, want %+v", inst.Controls, want)
}
}
// TestControllerConditions checks how the ranges of locc and hicc are read.
func TestControllerConditions(t *testing.T) {
// locc and hicc include both ends, and hiccN includes all of value N
// (sfizz), so a controller at 0.5, which is 63.5 of 127, is within hicc63
// but not locc64. A region keeps the ranges it needs.
inst := parseText(t, `
<region> sample=hicc63.wav hicc20=63
<region> sample=locc64.wav locc20=64
<region> sample=hd.wav lohdcc20=0.25 hihdcc20=0.75
<region> sample=top.wav locc21=10 hicc21=127
<region> sample=other.wav lochan=2 hichan=3 lobend=0 hibend=8192 lochanaft=127 lopolyaft=64 locc200=1
<region> sample=none.wav
`)
got := map[string][]Condition{}
for _, r := range inst.Regions {
got[r.Sample] = r.Conditions
}
within := func(c Condition, v float64) bool { return v >= c.Low && v <= c.High }
hicc63, locc64 := got["hicc63.wav"][0], got["locc64.wav"][0]
if !within(hicc63, 0.5) || within(locc64, 0.5) || !within(locc64, 64.0/127) || within(hicc63, 64.0/127) {
t.Errorf("hicc63 %+v, locc64 %+v", hicc63, locc64)
}
if hd := got["hd.wav"]; len(hd) != 1 || hd[0].Low != 0.25 || hd[0].High != 0.75 {
t.Errorf("hd %+v", hd)
}
if top := got["top.wav"]; len(top) != 1 || top[0].Low != 10.0/127 || top[0].High != 1 {
t.Errorf("top %+v", top)
}
want := []Condition{
{Source: SourceChannel, Low: 2, High: 3},
{Source: SourceBend, Low: 0, High: 1},
{Source: SourceAftertouch, Low: 1, High: 1},
{Source: SourcePolyAftertouch, Low: 64.0 / 127, High: 1},
}
if !reflect.DeepEqual(got["other.wav"], want) {
t.Errorf("channel, bend and aftertouch %+v, want %+v", got["other.wav"], want)
}
if got["none.wav"] != nil {
t.Errorf("a region with none %+v", got["none.wav"])
}
if len(inst.Unread) != 1 || inst.Unread["locc200"] != 0 {
t.Logf("unread %v", inst.Unread)
}
}
// TestKeyswitches checks the keyswitches that regions need, and the range of
// keys that they make.
func TestKeyswitches(t *testing.T) {
// Every region is kept with the keyswitches it needs, and the first
// articulation is the one down at the start unless sw_default says
// otherwise, as an SFZ player has none until a keyswitch is pressed
// (spec, sfizz) and Zampler starts with one (choice).
inst := parseText(t, `
<region> sample=first.wav sw_last=24
<region> sample=second.wav sw_last=25 sw_previous=24
<region> sample=held.wav sw_down=26 sw_up=27
<region> sample=always.wav
`)
got := map[string]*Keyswitch{}
for _, r := range inst.Regions {
got[r.Sample] = r.Keyswitch
}
if len(inst.Regions) != 4 || len(inst.Skipped) != 0 {
t.Fatalf("regions %v, skipped %v", got, inst.Skipped)
}
if k := got["first.wav"]; k == nil || *k.Last != 24 || k.Previous != nil {
t.Errorf("first %+v", k)
}
if k := got["second.wav"]; k == nil || *k.Last != 25 || *k.Previous != 24 {
t.Errorf("second %+v", k)
}
if k := got["held.wav"]; k == nil || *k.Down != 26 || *k.Up != 27 || k.Last != nil {
t.Errorf("held %+v", k)
}
if got["always.wav"] != nil {
t.Errorf("always %+v", got["always.wav"])
}
// With no sw_lokey and sw_hikey, the keys are those that regions name.
if k := inst.Keyswitches; k == nil || k.Low != 24 || k.High != 27 || k.Default == nil || *k.Default != 24 {
t.Errorf("keyswitch range %+v", k)
}
if parseText(t, "<region> sample=a.wav").Keyswitches != nil {
t.Error("an instrument with no keyswitches has some")
}
// A seq_position of 0 plays as 1 (sfizz).
if r := parseText(t, "<region> sample=a.wav seq_position=0"); len(r.Regions) != 1 {
t.Errorf("seq_position=0 skipped: %v", r.Skipped)
}
}
// TestModulationsAndBend checks how a region's stereo width, pitch bend and
// modulation of its settings are read.
func TestModulationsAndBend(t *testing.T) {
inst := parseText(t, `
<region> sample=a.wav width=50 width_oncc3=-25 gain_oncc4=3 pitch_oncc5=100 bend_up=1200 bend_down=-100 bend_step=100
<region> sample=b.wav
`)
a, b := inst.Regions[0], inst.Regions[1]
if a.Width == nil || *a.Width != 50 {
t.Errorf("width %v", a.Width)
}
want := []Modulation{
{Target: TargetVolume, Controller: 4, Depth: 3},
{Target: TargetWidth, Controller: 3, Depth: -25},
{Target: TargetTune, Controller: 5, Depth: 100},
}
if !reflect.DeepEqual(a.Modulations, want) {
t.Errorf("modulations %+v, want %+v", a.Modulations, want)
}
if a.BendUp == nil || *a.BendUp != 1200 || *a.BendDown != -100 || *a.BendStep != 100 {
t.Errorf("bend %v %v %v", a.BendUp, a.BendDown, a.BendStep)
}
if b.Width != nil || b.BendUp != nil || b.Modulations != nil || b.Conditions != nil {
t.Errorf("a region with none %+v", b)
}
if len(inst.Unread) != 0 {
t.Errorf("unread %v", inst.Unread)
}
}
// TestOtherOpcodes checks how the other opcodes the typed model reads are
// read, and that those it doesn't are counted.
func TestOtherOpcodes(t *testing.T) {
inst := parseText(t, `
<region> sample=a.wav tune=-20 transpose=1 pitch_keytrack=0 offset=100 amp_veltrack=40 group_volume=-3
trigger=release rt_decay=6 loop_mode=loop_continuous loopstart=10 loop_end=20 ampeg_sustain=150 cutoff=500
`)
r := inst.Regions[0]
if r.Tune != 80 || r.KeyTrack != 0 || r.Offset != 100 || r.VelocityTracking != 40 || r.Volume != -3 {
t.Errorf("settings %+v", r)
}
if r.Trigger != "release" || r.ReleaseDecay != 6 || r.LoopMode != "loop_continuous" || *r.LoopStart != 10 || *r.LoopEnd != 20 || r.Envelope.Sustain != 100 {
t.Errorf("trigger, loop and envelope %+v", r)
}
// An opcode that isn't read is counted, and the region still plays
// (choice). ampeg_sustain is at most 100 (spec).
if inst.Unread["cutoff"] != 1 || len(inst.Unread) != 1 {
t.Errorf("unread %v", inst.Unread)
}
}
// TestSplendid checks the typed instrument that the Splendid Grand Piano
// fixture makes.
func TestSplendid(t *testing.T) {
doc, err := ParseFile(os.DirFS(filepath.Join("testdata", "splendid")), "Splendid Grand Piano.sfz")
if err != nil {
t.Fatal(err)
}
inst := doc.Flatten().Instrument()
// Five velocity layers of about 60 regions each, and the string resonance,
// which needs the sustain pedal down, is kept with its conditions.
if len(inst.Regions) != 360 || len(inst.Skipped) != 0 {
t.Errorf("%d regions, skipped %v", len(inst.Regions), inst.Skipped)
}
layers := map[[2]int]int{}
resonance := 0
for _, r := range inst.Regions {
if len(r.Conditions) > 0 {
resonance++
continue
}
layers[[2]int{r.LowVelocity, r.HighVelocity}]++
}
if resonance != 57 {
t.Errorf("%d regions have conditions", resonance)
}
if len(layers) != 5 || layers[[2]int{1, 40}] != 61 || layers[[2]int{101, 127}] == 0 {
t.Errorf("velocity layers %v", layers)
}
// The lowest region that always plays: its own release plus 0.7 s from the
// 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
// through curve 4, x² (sfizz), multiplied (sfizz), which is kept to be
// applied as notes play.
var r Region
for _, candidate := range inst.Regions {
if len(candidate.Conditions) == 0 {
r = candidate
break
}
}
if r.Sample != "Samples/PP B-1.flac" || r.LowKey != 21 || r.HighKey != 24 || r.RootKey != 23 {
t.Errorf("first region %+v", r)
}
if !near(r.Envelope.Release, 1.3) || !near(r.Envelope.Hold, 8-6*23.0/127) || !near(r.Envelope.Decay, 80-60*23.0/127) || r.Envelope.Sustain != 0 {
t.Errorf("first region's envelope %+v", r.Envelope)
}
volume := Modulation{Target: TargetAmplitude, Controller: 7, Depth: 100, Curve: 4}
if !slices.ContainsFunc(r.Modulations, func(m Modulation) bool {
return m.Target == volume.Target && m.Controller == 7 && m.Depth == 100 && m.Curve == 4
}) || r.VelocityTracking != 100 {
t.Errorf("first region's level %+v", r)
}
// What isn't read is listed: the filter on the softest layer, and the
// pedal settings.
for _, name := range []string{"cutoff", "sustain_cc", "ampeg_dynamic", "ampeg_release_shape"} {
if inst.Unread[name] == 0 {
t.Errorf("%s isn't listed as unread: %v", name, inst.Unread)
}
}
if inst.Unread["cutoff"] != 61 {
t.Errorf("cutoff on %d regions", inst.Unread["cutoff"])
}
}
// A region's velocity curve passes through its amp_velcurve_N points, and
// starts at 0 and ends at 1 unless it says otherwise (sfizz).
func TestVelocityCurve(t *testing.T) {
inst := parseText(t, `<region> sample=a.wav amp_velcurve_127=0.8 amp_velcurve_32=0.1 amp_velcurve_64=0.5
<region> sample=b.wav amp_velcurve_0=0.2
<region> sample=c.wav`)
want := []CurvePoint{{0, 0}, {32, 0.1}, {64, 0.5}, {127, 0.8}}
if !reflect.DeepEqual(inst.Regions[0].VelocityCurve, want) {
t.Errorf("curve %v, want %v", inst.Regions[0].VelocityCurve, want)
}
if got := inst.Regions[1].VelocityCurve; !reflect.DeepEqual(got, []CurvePoint{{0, 0.2}, {127, 1}}) {
t.Errorf("curve ends %v", got)
}
if inst.Regions[2].VelocityCurve != nil {
t.Errorf("a region with no points has the curve %v", inst.Regions[2].VelocityCurve)
}
if len(inst.Unread) != 0 {
t.Errorf("unread %v", inst.Unread)
}
}
// Crossfades are over keys, which note names and the control header's
// offsets move, or velocities, and are power curves unless gain is asked for
// (spec).
func TestCrossfades(t *testing.T) {
inst := parseText(t, `<control> note_offset=2
<region> sample=a.wav xfin_lokey=c4 xfin_hikey=64 xfout_lokey=70 xfout_hikey=80 xfin_lovel=10 xfin_hivel=40 xf_velcurve=gain
<region> sample=b.wav xfout_lovel=100 xfout_hivel=127
<region> sample=c.wav`)
a := inst.Regions[0]
wantKeys := &Crossfade{FadeInLow: 62, FadeInHigh: 66, FadeOutLow: 72, FadeOutHigh: 82, Curve: "power"}
if !reflect.DeepEqual(a.KeyCrossfade, wantKeys) {
t.Errorf("key crossfade %+v, want %+v", a.KeyCrossfade, wantKeys)
}
wantVel := &Crossfade{FadeInLow: 10, FadeInHigh: 40, FadeOutLow: 127, FadeOutHigh: 127, Curve: "gain"}
if !reflect.DeepEqual(a.VelocityCrossfade, wantVel) {
t.Errorf("velocity crossfade %+v, want %+v", a.VelocityCrossfade, wantVel)
}
b := inst.Regions[1]
if b.KeyCrossfade != nil || b.VelocityCrossfade == nil || b.VelocityCrossfade.FadeInHigh != 0 || b.VelocityCrossfade.FadeOutLow != 100 {
t.Errorf("b: %+v, %+v", b.KeyCrossfade, b.VelocityCrossfade)
}
if c := inst.Regions[2]; c.KeyCrossfade != nil || c.VelocityCrossfade != nil {
t.Errorf("c: %+v, %+v", c.KeyCrossfade, c.VelocityCrossfade)
}
if len(inst.Unread) != 0 {
t.Errorf("unread %v", inst.Unread)
}
}
// polyphony limits the voices of a region's group, note_polyphony those of one
// key, and off_mode and off_time say how a stopped region fades (spec). A
// limit below 1 isn't one, and the mode is fast, taking 6 ms, unless said
// (sfizz).
func TestVoiceLimits(t *testing.T) {
inst := parseText(t, `<group> polyphony=4 note_polyphony=2 off_mode=normal
<region> sample=a.wav
<region> sample=b.wav off_mode=time off_time=0.25 polyphony=1
<region> sample=c.wav polyphony=0 note_polyphony=-3 off_mode=bogus off_time=-1
<region> sample=d.wav`)
a, b, c, d := inst.Regions[0], inst.Regions[1], inst.Regions[2], inst.Regions[3]
if a.Polyphony == nil || *a.Polyphony != 4 || a.NotePolyphony == nil || *a.NotePolyphony != 2 || a.OffMode != "normal" || a.OffTime != 0.006 {
t.Errorf("a %+v", a)
}
if b.Polyphony == nil || *b.Polyphony != 1 || b.OffMode != "time" || b.OffTime != 0.25 {
t.Errorf("b %+v", b)
}
if c.Polyphony != nil || c.NotePolyphony != nil || c.OffMode != "fast" || c.OffTime != 0.006 {
t.Errorf("c %+v", c)
}
if d.Polyphony == nil || *d.Polyphony != 4 {
t.Errorf("d %+v", d)
}
plain := parseText(t, `<region> sample=a.wav`).Regions[0]
if plain.Polyphony != nil || plain.NotePolyphony != nil || plain.OffMode != "fast" || plain.OffTime != 0.006 {
t.Errorf("a region with none %+v", plain)
}
if len(inst.Unread) != 0 {
t.Errorf("unread %v", inst.Unread)
}
}