From 49fd8672833ead0e4fdf57e90fe1da755b9f6dcc Mon Sep 17 00:00:00 2001 From: Aneurin Barker Snook Date: Wed, 2 Dec 2026 01:19:40 +0000 Subject: [PATCH] Add region lookup and structural edits, and reject regions Build can't write Instrument.Source returns the flattened region and header behind a typed region. AddRegion, RemoveRegion and MoveRegion edit the document and read the instrument again, restoring the document if a region would read differently. NewRegion returns a region with the format's defaults, and Build refuses a region that can't be read back as it is. Co-Authored-By: Claude Sonnet 5.5 --- README.md | 8 +- build.go | 39 ++++++- example_test.go | 23 ++++ flatten.go | 5 +- instrument.go | 2 +- model.go | 3 + structure.go | 206 ++++++++++++++++++++++++++++++++ structure_test.go | 290 ++++++++++++++++++++++++++++++++++++++++++++++ 8 files changed, 571 insertions(+), 5 deletions(-) create mode 100644 structure.go create mode 100644 structure_test.go diff --git a/README.md b/README.md index 3a4f651..687c2ba 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ The package documentation has runnable examples of reading, editing and building ## Opcodes -The library knows every opcode and header in the format, from the data behind [sfzformat.com](https://sfzformat.com/): [docs/opcodes.md](docs/opcodes.md) lists them. `Lookup` returns an opcode's type, range, unit, options and version, finding numbered families such as `loccN` and aliases such as `loopmode`. `Validate` checks values against it. `GetAs` reads any opcode's value as an int, float or string. An opcode the registry doesn't know is kept, read and written as text like any other, and `Validate` reports it only as information. +The library knows every opcode and header in the format, from the data behind [sfzformat.com](https://sfzformat.com/): [docs/opcodes.md](docs/opcodes.md) lists them. `Lookup` returns an opcode's type, range, unit, options and version, finding numbered families such as `loccN` and aliases such as `loopmode`. `Validate` checks values against it. `GetAs` reads any opcode's value as an int, float or string. An opcode the registry doesn't know is kept, read and written as text like any other, and `Validate` reports it only as information. That includes opcodes that a host adds for its own data, such as `zampler_zone`: samplers ignore them, and the library keeps them through every edit. `Instrument.Source(i)` returns the flattened region behind typed region `i`, with its `Header`, so that a host can `Get` and `Set` them. ## The typed model @@ -45,13 +45,17 @@ The model is read with each setting that a controller moves taken at the control - `Instrument.Apply(i, region)` writes a change to a typed region back to the document that the instrument was read from, as changes to the region's own opcodes. It touches only the settings that changed, leaves unknown opcodes, comments and the other regions as they were, and puts every change in the region's own header, over what the region inherits. `Instrument.Patches` returns the changes without making them. - It returns `ErrNoSource` if the region has no header to edit: a variable made the header, or an include or a variable brings in opcodes after it. - It returns `ErrUnpatchable`, and changes nothing, for a change the header can't hold: removing an opcode the region inherits, or a sample outside `default_path`. +- `Instrument.AddRegion(region)`, `RemoveRegion(i)` and `MoveRegion(from, to)` change the document's structure and read the instrument again, so it is as the document reads. A removed or moved region takes the comments and spacing that follow its header. A new region goes at the end of the main file. Each changes nothing, and returns an error, if the result wouldn't read as intended. + - `ErrNoSource` is for a region that has no header to move or remove, or an instrument that wasn't read from a document. + - `ErrUnpatchable` is for a region that would read differently where it ends up: a new region that a `default_path` changes, or a region moved under another ``. - `Node` positions are worked out when asked for, with `File.Position`, so edits stay cheap. ## Writing and building - `Document.Write` writes one file, and `WriteFiles` writes the main file and each file it includes, through a `FileWriter`. They take `WriteOptions`: `InlineIncludes` puts included files into the main file, `ExpandVariables` replaces variables with their values, and `LineEnding` sets the line break. The zero value writes each file as it was read. - `Write` and `WriteTo` return an error for a document with includes unless `InlineIncludes` is set, as the files they hold would be lost. `WriteFiles` also returns an error for an include whose path is absolute or leaves the folder (`AllowParentPaths` opts in to `..` paths, not absolute ones), and for a file included more than once that would be written differently each time. -- `Build` makes a new document from an `Instrument`, with `BuildOptions`: `SplitFiles` puts regions in included files, `Variables` hoists repeated values into `#define`s and the samples' folder into `default_path`, and `Indent` sets the indent. Reading the result gives the instrument back, except for the opcodes and headers the typed model doesn't hold. It returns an error for a value that can't be written, such as a sample path with a line break in it. +- `Build` makes a new document from an `Instrument`, with `BuildOptions`: `SplitFiles` puts regions in included files, `Variables` hoists repeated values into `#define`s and the samples' folder into `default_path`, and `Indent` sets the indent. Reading the result gives the instrument back, except for the opcodes and headers the typed model doesn't hold. It returns an error wrapping `ErrInvalid` for a value that can't be written, and for a region that wouldn't read back as it is, such as a zero `Region` with an empty `Trigger`. `NewRegion(sample)` makes a region with the format's defaults. + - A `Region.Sample` is written as one opcode, so `Build` and `Apply` refuse one with a line break, `//`, `/*`, `<`, or a space followed by `=` (as in `a b=c.wav`). A backslash reads back as `/`. A host that has such file names needs to map them to safe ones. ## Includes diff --git a/build.go b/build.go index 265c09e..9b7bc72 100644 --- a/build.go +++ b/build.go @@ -1,6 +1,7 @@ package sfz import ( + "errors" "fmt" "math" "path" @@ -60,6 +61,38 @@ func defaultRegion() Region { } } +// NewRegion returns a region of the sample that has the format's defaults for +// everything else: it plays from key 0 to 127 at any velocity, on attack, as +// the only note of its round robin. A [Region] made any other way has to set +// each of these itself, as [Build] and [Instrument.AddRegion] refuse a region +// that can't be read back as it is, such as one with an empty Trigger. +func NewRegion(sample string) Region { + r := defaultRegion() + r.Sample = sample + return r +} + +// checkRegion returns an error saying why a region can't be written as it is: +// the opcodes for it would be empty, or would be read as something else, or +// would never match a note. +func checkRegion(r Region) error { + switch { + case r.Sample == "": + return errors.New("the sample is empty") + case r.Trigger == "": + return errors.New("the trigger is empty") + case r.OffMode != "fast" && r.OffMode != "time" && r.OffMode != "normal": + return fmt.Errorf("the off mode %q isn't fast, time or normal", r.OffMode) + case r.SequenceLength < 1 || r.SequencePosition < 1: + return errors.New("the sequence length and position start at 1") + case r.HighKey < r.LowKey: + return errors.New("the highest key is below the lowest") + case r.HighVelocity < r.LowVelocity: + return errors.New("the highest velocity is below the lowest") + } + return nil +} + // opcodeLine is an opcode to write, with its value as text. type opcodeLine struct{ name, value string } @@ -77,7 +110,8 @@ func scaled(v, scale float64) string { return num(math.Round(v*scale*1e9) / 1e9) // for what the model doesn't hold: the opcodes it doesn't read, and which // headers the regions were under. It returns an error wrapping [ErrInvalid] if // something in the instrument, such as a sample path or a label, can't be -// written as the value of an opcode. +// written as the value of an opcode, or if a region can't be read back as it is +// (see [NewRegion]). func Build(inst *Instrument, opts ...BuildOptions) (*Document, error) { var o BuildOptions if len(opts) > 0 { @@ -87,6 +121,9 @@ func Build(inst *Instrument, opts ...BuildOptions) (*Document, error) { regions := make([][]opcodeLine, len(inst.Regions)) for i := range inst.Regions { + if err := checkRegion(inst.Regions[i]); err != nil { + return nil, fmt.Errorf("%w: region %d: %w", ErrInvalid, i, err) + } regions[i] = regionOpcodes(inst.Regions[i]) } diff --git a/example_test.go b/example_test.go index 4ef9b36..36bcced 100644 --- a/example_test.go +++ b/example_test.go @@ -67,6 +67,29 @@ func ExampleInstrument_Apply() { // volume=-6 } +// This example adds a region, then moves it first, keeping what the document +// has around the other regions. +func ExampleInstrument_AddRegion() { + doc, err := sfz.Parse(strings.NewReader(" sample=a.wav // the first\n sample=b.wav\n")) + if err != nil { + log.Fatal(err) + } + inst := doc.Flatten().Instrument() + + if err := inst.AddRegion(sfz.NewRegion("c.wav")); err != nil { + log.Fatal(err) + } + if err := inst.MoveRegion(2, 0); err != nil { + log.Fatal(err) + } + fmt.Print(doc) + // Output: + // + // sample=c.wav + // sample=a.wav // the first + // sample=b.wav +} + // This example changes an opcode of a header directly, with the text around it // as it was. func ExampleHeader_Set() { diff --git a/flatten.go b/flatten.go index 0de1c30..2a12101 100644 --- a/flatten.go +++ b/flatten.go @@ -49,6 +49,9 @@ type Flat struct { // Headers counts, by lowercase name, the headers that aren't , // , , , or . Headers map[string]int + + // doc is the document that was flattened. + doc *Document } // level is how far down the header hierarchy a header is, where the opcodes of @@ -105,7 +108,7 @@ type flattener struct { // opcodes of its own. Comments are dropped, and an include that wasn't read is // skipped. func (d *Document) Flatten() *Flat { - f := &flattener{flat: &Flat{Control: Opcodes{}, Headers: map[string]int{}}} + f := &flattener{flat: &Flat{Control: Opcodes{}, Headers: map[string]int{}, doc: d}} for i := range f.levels { f.levels[i] = Opcodes{} } diff --git a/instrument.go b/instrument.go index cbc36fd..51eb9b4 100644 --- a/instrument.go +++ b/instrument.go @@ -16,7 +16,7 @@ import ( // Regions that the typed model has no region for are counted in Skipped, and // the opcodes and headers it doesn't read in Unread. func (f *Flat) Instrument() *Instrument { - inst := &Instrument{Unread: map[string]int{}, Skipped: map[string]int{}} + inst := &Instrument{Unread: map[string]int{}, Skipped: map[string]int{}, doc: f.doc} for h, n := range f.Headers { inst.Unread["<"+h+">"] += n } diff --git a/model.go b/model.go index c4e6fa6..f6aeabd 100644 --- a/model.go +++ b/model.go @@ -228,6 +228,9 @@ type Instrument struct { sources []FlatRegion // eval reads a region from opcodes, as when the regions were read. eval evaluator + // doc is the document the instrument was read from, or nil if it wasn't read + // from one. + doc *Document } // The keys of [Instrument.Skipped], the reasons that a region has no typed diff --git a/structure.go b/structure.go new file mode 100644 index 0000000..371ae68 --- /dev/null +++ b/structure.go @@ -0,0 +1,206 @@ +package sfz + +import ( + "errors" + "fmt" + "slices" + "strings" +) + +// Source returns the flattened region that typed region i was read from, with +// its header, or false if there is no region i. The header is nil if a variable +// made it. The result is only good until the next [Instrument.AddRegion], +// [Instrument.RemoveRegion] or [Instrument.MoveRegion], which read the +// instrument again. +func (inst *Instrument) Source(i int) (*FlatRegion, bool) { + if i < 0 || i >= len(inst.sources) { + return nil, false + } + return &inst.sources[i], true +} + +// AddRegion adds a for r at the end of the document that the +// instrument was read from, and makes it the last of the instrument's regions. +// It writes only the opcodes that differ from the format's defaults if they +// read back as r, and every opcode if the headers above it need to be +// overridden. It changes nothing, and returns an error, if r can't be written +// so that it reads back as r: [ErrInvalid] if r or its sample can't be written +// as it is, [ErrUnpatchable] if the headers above the new region or a +// default_path change it, and [ErrNoSource] if the instrument wasn't read from +// a document. +// +// Afterwards the instrument is as the document reads, with Skipped, Unread and +// Controls too. Use [Instrument.Source] to set opcodes the typed model doesn't +// hold on the new region's header. +func (inst *Instrument) AddRegion(r Region) error { + if err := checkRegion(r); err != nil { + return fmt.Errorf("%w: %w", ErrInvalid, err) + } + var err error + for _, all := range []bool{false, true} { + err = inst.restructure( + func() error { return inst.writeRegion(r, all) }, + func(old []Region) []Region { return append(slices.Clone(old), r) }) + if !errors.Is(err, ErrUnpatchable) { + return err + } + } + return err +} + +// writeRegion adds a for r at the end of the main file. It writes the +// opcodes that the format's defaults would give too if all is set. +func (inst *Instrument) writeRegion(r Region, all bool) error { + defaultPath := strings.ReplaceAll(strings.TrimSpace(inst.doc.Flatten().Control["default_path"]), `\`, "/") + h, err := inst.doc.AddHeader("region", nil) + if err != nil { + return err + } + for _, l := range regionLines(r, all) { + value := l.value + if l.field == "Sample" { + // The sample is read as relative to default_path. + value = strings.TrimPrefix(value, defaultPath) + } + if err := checkOpcode(l.name, value); err != nil { + return err + } + if err := h.Set(l.name, value); err != nil { + return err + } + } + return nil +} + +// RemoveRegion removes region i from the document that the instrument was read +// from, with the comments and spacing that follow its header. It changes +// nothing, and returns an error, if the document can't be edited there: an +// error wrapping [ErrNoSource] if there is no region i or it has no header of +// its own to remove. Afterwards the instrument is as the document reads. +func (inst *Instrument) RemoveRegion(i int) error { + src, err := inst.source(i) + if err != nil { + return err + } + return inst.restructure( + func() error { + f := src.Header.File + start, end := src.Header.span() + f.Nodes = slices.Delete(f.Nodes, start-1, end) + f.dirty = true + return nil + }, + func(old []Region) []Region { return slices.Delete(slices.Clone(old), i, i+1) }) +} + +// MoveRegion moves region from in the document that the instrument was read +// from so that it is region to, with the comments and spacing that follow its +// header. The regions between keep their order, and so do the regions the typed +// model has no region for. It changes nothing, and returns an error, if the +// document can't be edited there: an error wrapping [ErrNoSource] if either +// region has no header of its own to move, and [ErrUnpatchable] if the headers +// above the new place would change the region, as when it moves into another +// . Afterwards the instrument is as the document reads. +func (inst *Instrument) MoveRegion(from, to int) error { + src, err := inst.source(from) + if err != nil { + return err + } + dst, err := inst.source(to) + if err != nil { + return err + } + if from == to { + return nil + } + return inst.restructure( + func() error { + f := src.Header.File + start, end := src.Header.span() + moved := slices.Clone(f.Nodes[start-1 : end]) + f.Nodes = slices.Delete(f.Nodes, start-1, end) + f.dirty = true + g := dst.Header.File + at := g.indexOf(dst.Header.Node) + if from < to { + _, at = dst.Header.span() + } + insertNodes(g, at, moved) + return nil + }, + func(old []Region) []Region { + out := slices.Delete(slices.Clone(old), from, from+1) + return slices.Insert(out, to, old[from]) + }) +} + +// insertNodes inserts the nodes of whole lines into a file at a node index, +// with a line break before or after them if the text around them lacks one. +func insertNodes(f *File, at int, nodes []*Node) { + if at > 0 && !strings.HasSuffix(f.Nodes[at-1].Raw, "\n") { + nodes = append([]*Node{{Kind: KindSpace, Raw: "\n"}}, nodes...) + } + if at < len(f.Nodes) && !strings.HasSuffix(nodes[len(nodes)-1].Raw, "\n") { + nodes = append(nodes, &Node{Kind: KindSpace, Raw: "\n"}) + } + f.insert(at, nodes...) +} + +// restructure edits the instrument's document with change, and then reads the +// document again. The edit stands if the regions read from it are those that +// want makes from the regions the document had before, and the instrument then +// becomes what the document reads as. Otherwise the document is as it was, and +// the error wraps [ErrUnpatchable] if the edit changed what the regions are. +func (inst *Instrument) restructure(change func() error, want func(old []Region) []Region) error { + if inst.doc == nil { + return fmt.Errorf("%w: the instrument wasn't read from a document", ErrNoSource) + } + before := inst.doc.Flatten().Instrument() + if !inst.matches(before) { + return fmt.Errorf("%w: the document has changed since the instrument was read", ErrNoSource) + } + saved := map[*File][]*Node{} + for _, f := range inst.doc.Files() { + saved[f] = slices.Clone(f.Nodes) + } + undo := func() { + for f, nodes := range saved { + f.Nodes = nodes + f.dirty = true + } + } + if err := change(); err != nil { + undo() + return err + } + after := inst.doc.Flatten().Instrument() + expected := want(before.Regions) + if len(after.Regions) != len(expected) { + undo() + return fmt.Errorf("%w: the document would read as %d regions, not %d", ErrUnpatchable, len(after.Regions), len(expected)) + } + for i := range expected { + if wrong := differing(after.Regions[i], expected[i]); len(wrong) > 0 { + undo() + return fmt.Errorf("%w: region %d would read differently: %s", ErrUnpatchable, i, strings.Join(wrong, ", ")) + } + } + inst.Regions, inst.sources, inst.eval = after.Regions, after.sources, after.eval + inst.Unread, inst.Skipped, inst.Controls, inst.Keyswitches = after.Unread, after.Skipped, after.Controls, after.Keyswitches + return nil +} + +// matches reports whether other, read from the instrument's document, has the +// regions that the instrument was read with, from the same headers. +func (inst *Instrument) matches(other *Instrument) bool { + if len(inst.sources) != len(other.sources) { + return false + } + for i, s := range inst.sources { + o := other.sources[i] + if (s.Header == nil) != (o.Header == nil) || s.Header != nil && s.Header.Node != o.Header.Node { + return false + } + } + return true +} diff --git a/structure_test.go b/structure_test.go new file mode 100644 index 0000000..9a7a2ac --- /dev/null +++ b/structure_test.go @@ -0,0 +1,290 @@ +package sfz + +import ( + "errors" + "os" + "path/filepath" + "reflect" + "strings" + "testing" +) + +// regionSamples returns the samples of an instrument's regions, in order. +func regionSamples(inst *Instrument) string { + var out []string + for _, r := range inst.Regions { + out = append(out, r.Sample) + } + return strings.Join(out, " ") +} + +// TestSource checks that a typed region finds its own header when other regions +// are skipped, which makes the typed and flat indexes differ. +func TestSource(t *testing.T) { + doc := mustParse(t, " sample=a.wav\n lokey=1\n sample=b.wav\n sample=c.wav hikey=3 hikey=2 lokey=9\n", nil) + inst := readInstrument(t, doc) + if regionSamples(inst) != "a.wav b.wav" || inst.Skipped[SkippedNoSample] != 1 || inst.Skipped[SkippedNotKeys] != 1 { + t.Fatalf("regions %q, skipped %v", regionSamples(inst), inst.Skipped) + } + src, ok := inst.Source(1) + if !ok || src.Own["sample"] != "b.wav" || src.Line != 3 { + t.Fatalf("source %+v %v", src, ok) + } + if err := src.Header.Set("zampler_zone", "abc123"); err != nil { + t.Fatal(err) + } + if got := doc.Flatten().Regions[2].Own["zampler_zone"]; got != "abc123" { + t.Errorf("zampler_zone is %q on the flat region", got) + } + for _, i := range []int{-1, 2} { + if _, ok := inst.Source(i); ok { + t.Errorf("Source(%d) found a region", i) + } + } +} + +// TestRegionEdits checks the text and the instrument after each structural +// edit, and that comments and opcodes the model doesn't read stay. +func TestRegionEdits(t *testing.T) { + text := " volume=-3\n sample=a.wav // first\n zampler_zone=1\n sample=b.wav\n sample=c.wav zampler_zone=3\n" + tests := map[string]struct { + edit func(*Instrument) error + want string + next string + }{ + "remove the first": { + func(i *Instrument) error { return i.RemoveRegion(0) }, + " volume=-3\n sample=b.wav\n sample=c.wav zampler_zone=3\n", "b.wav c.wav", + }, + "remove the last": { + func(i *Instrument) error { return i.RemoveRegion(2) }, + " volume=-3\n sample=a.wav // first\n zampler_zone=1\n sample=b.wav\n", "a.wav b.wav", + }, + "move up": { + func(i *Instrument) error { return i.MoveRegion(2, 0) }, + " volume=-3\n sample=c.wav zampler_zone=3\n sample=a.wav // first\n zampler_zone=1\n sample=b.wav\n", "c.wav a.wav b.wav", + }, + "move down": { + func(i *Instrument) error { return i.MoveRegion(0, 2) }, + " volume=-3\n sample=b.wav\n sample=c.wav zampler_zone=3\n sample=a.wav // first\n zampler_zone=1\n", "b.wav c.wav a.wav", + }, + "add": { + func(i *Instrument) error { + r := i.Regions[0] + r.Sample, r.Volume = "d.wav", -3 + return i.AddRegion(r) + }, + text + "\nsample=d.wav\nvolume=-3\n", "a.wav b.wav c.wav d.wav", + }, + } + for name, tc := range tests { + t.Run(name, func(t *testing.T) { + doc := mustParse(t, text, nil) + inst := readInstrument(t, doc) + if err := tc.edit(inst); err != nil { + t.Fatal(err) + } + if got := doc.String(); got != tc.want { + t.Errorf("document\n%q\nwant\n%q", got, tc.want) + } + if regionSamples(inst) != tc.next { + t.Errorf("instrument has %q", regionSamples(inst)) + } + fresh := readInstrument(t, mustParse(t, doc.String(), nil)) + if len(fresh.Regions) != len(inst.Regions) { + t.Fatalf("the document reads as %d regions, not %d", len(fresh.Regions), len(inst.Regions)) + } + for i := range fresh.Regions { + if wrong := differing(fresh.Regions[i], inst.Regions[i]); len(wrong) > 0 { + t.Errorf("region %d differs from a fresh read in %v", i, wrong) + } + } + // The instrument's sources still lead to the headers. + for i := range inst.Regions { + src, ok := inst.Source(i) + if !ok || src.Header == nil || src.Own["sample"] != inst.Regions[i].Sample { + t.Errorf("source %d is %+v", i, src) + } + } + }) + } +} + +// TestAddRegionOverridesInherited checks that a new region overrides what the +// header above it sets, and that a default_path is taken off its sample. +func TestAddRegionOverridesInherited(t *testing.T) { + doc := mustParse(t, " default_path=S/\n hikey=60 volume=-6\n sample=a.wav\n", nil) + inst := readInstrument(t, doc) + r := NewRegion("S/b.wav") + if err := inst.AddRegion(r); err != nil { + t.Fatal(err) + } + if got := inst.Regions[1]; got.HighKey != 127 || got.Volume != 0 || got.Sample != "S/b.wav" { + t.Errorf("region %+v", got) + } + if !strings.Contains(doc.String(), "sample=b.wav") || strings.Contains(doc.String(), "S/b.wav") { + t.Errorf("document %q", doc.String()) + } +} + +// TestRegionEditRefusals checks that an edit that can't be made says why and +// leaves the document as it was. +func TestRegionEditRefusals(t *testing.T) { + text := " hikey=50\n sample=a.wav\n hikey=70\n sample=b.wav\n sample=c.wav\n" + files := map[string]string{"r.sfz": " sample=x.wav\n"} + tests := map[string]struct { + text string + edit func(*Instrument) error + want error + }{ + "remove out of range": {text, func(i *Instrument) error { return i.RemoveRegion(3) }, ErrNoSource}, + "move out of range": {text, func(i *Instrument) error { return i.MoveRegion(0, -1) }, ErrNoSource}, + "move across a group": {text, func(i *Instrument) error { return i.MoveRegion(0, 2) }, ErrUnpatchable}, + "add under a group": {text, func(i *Instrument) error { + r := NewRegion("d.wav") + r.HighKey = 127 + r.Pan = 3 + r.Width = nil + return i.AddRegion(r) + }, nil}, + "add a zero region": {text, func(i *Instrument) error { return i.AddRegion(Region{Sample: "d.wav"}) }, ErrInvalid}, + "add a bad sample": {text, func(i *Instrument) error { return i.AddRegion(NewRegion("a b=c.wav")) }, ErrInvalid}, + "remove an include": {"#include \"r.sfz\"\n sample=y.wav\n", func(i *Instrument) error { return i.RemoveRegion(1) }, nil}, + "remove before include": {" sample=y.wav\n#include \"r.sfz\"\n", func(i *Instrument) error { return i.RemoveRegion(0) }, ErrNoSource}, + } + for name, tc := range tests { + t.Run(name, func(t *testing.T) { + doc := mustParse(t, tc.text, files) + inst := readInstrument(t, doc) + before := doc.String() + err := tc.edit(inst) + if tc.want == nil { + if err != nil { + t.Fatal(err) + } + return + } + if !errors.Is(err, tc.want) { + t.Fatalf("error %v, want %v", err, tc.want) + } + if doc.String() != before { + t.Errorf("document changed to %q", doc.String()) + } + if len(inst.Regions) != len(readInstrument(t, doc).Regions) { + t.Errorf("instrument changed") + } + }) + } +} + +// TestRegionEditsKeepUnknownOpcodes checks that opcodes the format doesn't +// define, set through a region's header, survive every kind of edit and a +// write. +func TestRegionEditsKeepUnknownOpcodes(t *testing.T) { + doc := mustParse(t, " sample=a.wav\n sample=b.wav\n", nil) + inst := readInstrument(t, doc) + for i, id := range []string{"za", "zb"} { + src, _ := inst.Source(i) + if err := src.Header.Set("zampler_zone", id); err != nil { + t.Fatal(err) + } + } + if err := inst.AddRegion(NewRegion("c.wav")); err != nil { + t.Fatal(err) + } + if err := inst.MoveRegion(2, 0); err != nil { + t.Fatal(err) + } + if err := inst.RemoveRegion(1); err != nil { + t.Fatal(err) + } + var got []string + for i := range inst.Regions { + src, _ := inst.Source(i) + got = append(got, inst.Regions[i].Sample+":"+src.Own["zampler_zone"]) + } + if strings.Join(got, " ") != "c.wav: b.wav:zb" { + t.Errorf("regions %v\n%s", got, doc.String()) + } + out := readInstrument(t, mustParse(t, doc.String(), nil)) + if src, _ := out.Source(1); src.Own["zampler_zone"] != "zb" { + t.Errorf("zampler_zone didn't survive writing: %q", doc.String()) + } + if problems := doc.Validate(); len(problems) == 0 { + t.Log("zampler_zone isn't reported") + } else { + for _, p := range problems { + if p.Severity != SeverityInfo { + t.Errorf("problem %+v", p) + } + } + } +} + +// TestBuildRefusesZeroRegion checks that Build says what is wrong with a zero +// region, and that a region from NewRegion builds and reads back. +func TestBuildRefusesZeroRegion(t *testing.T) { + _, err := Build(&Instrument{Regions: []Region{{Sample: "a.wav"}}}) + if !errors.Is(err, ErrInvalid) || !strings.Contains(err.Error(), "trigger") { + t.Errorf("error %v", err) + } + inst := &Instrument{Regions: []Region{NewRegion("a.wav")}} + doc, err := Build(inst) + if err != nil { + t.Fatal(err) + } + if got := readInstrument(t, doc); len(got.Regions) != 1 || len(differing(got.Regions[0], inst.Regions[0])) > 0 { + t.Errorf("read back %+v", got.Regions) + } +} + +// TestRegionEditsOnFixtures checks, on a real instrument, that removing and +// moving regions leaves the instrument as a fresh read of the +// document, and that a move to another group is refused. +func TestRegionEditsOnFixtures(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() + n := len(inst.Regions) + before := doc.String() + if err := inst.MoveRegion(n-1, 0); !errors.Is(err, ErrUnpatchable) || doc.String() != before { + t.Fatalf("a move to another group returned %v", err) + } + // Two neighbours that inherit the same opcodes can swap. + pair := -1 + for i := 0; i+1 < n && pair < 0; i++ { + if reflect.DeepEqual(inst.sources[i].Inherited, inst.sources[i+1].Inherited) { + pair = i + } + } + if pair < 0 { + t.Fatal("no neighbours share a group") + } + first, second := inst.Regions[pair].Sample, inst.Regions[pair+1].Sample + steps := []struct { + name string + do func() error + n int + at int + want string + }{ + {"swap neighbours", func() error { return inst.MoveRegion(pair+1, pair) }, n, pair, second}, + {"remove one", func() error { return inst.RemoveRegion(pair) }, n - 1, pair, first}, + } + for _, s := range steps { + if err := s.do(); err != nil { + t.Fatalf("%s: %v", s.name, err) + } + if len(inst.Regions) != s.n || inst.Regions[s.at].Sample != s.want { + t.Fatalf("%s: %d regions, region %d is %q", s.name, len(inst.Regions), s.at, inst.Regions[s.at].Sample) + } + fresh := doc.Flatten().Instrument() + for i := range fresh.Regions { + if wrong := differing(fresh.Regions[i], inst.Regions[i]); len(wrong) > 0 { + t.Fatalf("%s: region %d differs from a fresh read in %v", s.name, i, wrong) + } + } + } +}