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" + " 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" + " #include \"$DIR/a.txt\" lovel=1 #include \"Data/b.txt\"\n" + "#define $V loud\n" + "/* a\nblock */ sample=$V C#4.wav $UNDEFINED=1\n", "Data/a.txt": "#define $X 7\nhivel=$X", "Data/b.txt": " 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 hikey=40\n#define $CC 70\n#define $HEAD \n" + "$HEAD sample=a.wav $RANGE locc$CC=5\n", }) ops := doc.Flatten().Regions[0].Opcodes if ops["lokey"] != "36" || ops["hikey"] != "40" || 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 := ` 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" + " #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(" 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, ` default_path=One/ pan=10 lovel=64 tune=5 sample=a b.wav tune=7 sample=c.wav default_path=Two/ hivel=90 sample=d.wav type=reverb pan=-20 sample=e.wav 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 starts without the last group's opcodes (choice: // 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 clears the group, and a clears everything (choice: // 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[""] != 1 || inst.Unread["type"] != 0 { t.Errorf("unread %v", inst.Unread) } // Opcodes before any header apply to every region (choice: the spec // doesn't say). if r := parseText(t, "volume=-1\n sample=a.wav").Regions[0]; r.Volume != -1 { t.Errorf("opcode before any header %+v", r) } // A new resets default_path but keeps the other control // settings (spec, describing ARIA; Cakewalk keeps it). reset := parseText(t, " default_path=A/ note_offset=12\n\n sample=x.wav key=60") if r := reset.Regions[0]; r.Sample != "x.wav" || r.LowKey != 72 { t.Errorf("after a second %+v", r) } } // TestDefaults checks the values of a region that sets nothing. func TestDefaults(t *testing.T) { r := parseText(t, " 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, ` note_offset=1 octave_offset=-1 sample=a.wav key=c4 sample=b.wav lokey=21 hikey=c#2 pitch_keycenter=eb2 sample=c.wav lokey=-1 hikey=-1 sample=d.wav pitch_keycenter=sample sample=*sine 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, " 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, ` set_cc7=127 set_hdcc20=0.25 set_cc64=0 label_cc20=Mic mix curve_index=9 v000=0 v064=1 v127=1 sw_default=c0 sw_lokey=c0 sw_hikey=d0 sample=natural.wav sw_last=c0 amplitude_oncc7=50 volume_oncc20=-8 pan_oncc20=100 pan_curvecc20=1 sample=retuned.wav sw_last=c#0 sample=pedal.wav locc64=64 sample=no-pedal.wav hicc64=63 ampeg_releasecc20=4 ampeg_release_curvecc20=9 sample=switched.wav on_locc64=127 sample=first.wav lorand=0 hirand=0.5 sample=second.wav lorand=0.5 hirand=1 sample=rr2.wav seq_position=2 seq_length=2 sample=hold.wav ampeg_hold=8 ampeg_hold_oncc133=-6 key=127 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 (spec: _onccN adds), 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, ` sample=plain.wav sample=v2.wav polyphony_group=7 off_by=0 seq_length=3 group=2 off_by=2 sample=rr1.wav seq_position=1 sample=rr2.wav seq_position=2 lorand=0.25 hirand=0.75 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 v2's name for group (spec), and off_by may name group // 0 (spec). 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, ` 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, ` sample=hicc63.wav hicc20=63 sample=locc64.wav locc20=64 sample=hd.wav lohdcc20=0.25 hihdcc20=0.75 sample=top.wav locc21=10 hicc21=127 sample=other.wav lochan=2 hichan=3 lobend=0 hibend=8192 lochanaft=127 lopolyaft=64 locc200=1 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, ` sample=first.wav sw_last=24 sample=second.wav sw_last=25 sw_previous=24 sample=held.wav sw_down=26 sw_up=27 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, " 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, " 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, ` sample=a.wav width=50 width_oncc3=-25 gain_oncc4=3 pitch_oncc5=100 bend_up=1200 bend_down=-100 bend_step=100 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, ` 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 (spec: _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, ` sample=a.wav amp_velcurve_127=0.8 amp_velcurve_32=0.1 amp_velcurve_64=0.5 sample=b.wav amp_velcurve_0=0.2 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, ` note_offset=2 sample=a.wav xfin_lokey=c4 xfin_hikey=64 xfout_lokey=70 xfout_hikey=80 xfin_lovel=10 xfin_hivel=40 xf_velcurve=gain sample=b.wav xfout_lovel=100 xfout_hivel=127 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, ` polyphony=4 note_polyphony=2 off_mode=normal sample=a.wav sample=b.wav off_mode=time off_time=0.25 polyphony=1 sample=c.wav polyphony=0 note_polyphony=-3 off_mode=bogus off_time=-1 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, ` 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) } }