# sfz A Go library that reads, validates, edits and writes [SFZ](https://sfzformat.com/) instruments. It handles the format as data, covering SFZ v1, v2 and the ARIA extensions, whether or not a sampler can play a feature. It doesn't play instruments or load samples. ```sh go get code.aneur.in/zampler/sfz ``` It needs Go 1.25 or later and has no dependencies. ```go doc, err := sfz.ParseFile(os.DirFS("Piano"), "Piano.sfz") if err != nil { return err } for _, p := range doc.Validate() { log.Printf("%s:%d: %s", p.File, p.Line, p.Msg) } inst := doc.Flatten().Instrument() ``` The package documentation has runnable examples of reading, editing and building instruments. ## Layers - **Document.** A file exactly as written: headers, opcodes in order, comments, unknown opcodes, and `#define` and `#include` unexpanded. Each `#include` that was read holds its file, so a document is a tree of files. `String` returns the main file's text, and a document that hasn't been edited gives the text it was read from. - **Flat.** `Document.Flatten` reads each `#include` where it stands, replaces variables with their values as of where they are used, and gives each region the opcodes of the `` settings, ``, `` and `` above it. Comments and layout are gone. - **Instrument.** `Flat.Instrument` reads the regions into a typed model, with settings taken at the controllers' starting values. Opcodes the model has no field for are counted in `Unread`, and regions it has no region for, such as generated sounds, in `Skipped`. ## 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. 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 `Instrument`, `Region` and the types in them are plain structs. Each field has a `json` name and a `doc` description, and a numeric field has `minimum` and `maximum` tags where the format gives bounds. The library reads and writes values outside those bounds, and leaves it to the host to enforce them. The model is read with each setting that a controller moves taken at the controller's starting value. The controllers' modulation of the settings is kept in `Region.Modulations`, for the host to apply as notes play. ## Editing - `Document.Headers` returns the headers of every file. `Header.Get`, `Set` and `Delete` change an opcode and keep the comments and spacing around it. A new opcode goes after the header's last, and after the comment on its line, laid out like it. `Document.AddHeader` adds a header. - `Header.Set`, `Document.SetDefine` and `Document.AddHeader` return an error wrapping `ErrInvalid`, and change nothing, for a name or value that wouldn't read back as one opcode, define or header, such as a value with a line break or a comment in it. - `Header.Set` on an opcode that uses a variable writes the value in its place. `Document.SetDefine` changes the variable, and so each opcode that uses it. - `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 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 `Parse` reads includes with the resolver from `WithResolver`; `ParseFile` reads them from the folder of the main file. An include that can't be read is a `Problem` from `Validate`, and `WithIncludes(sfz.IncludesFail)` makes it an error. `WithIncludes(sfz.IncludesKeep)` reads none. `Includes` lists the files an SFZ text includes. ## Validation `Document.Validate` returns `Problem`s with a file, a line and column, a severity and a stable code. It never fails on what it doesn't know. | Code | Severity | Means | |---|---|---| | `define.undefined` | warning | A variable is used that isn't defined. | | `header.unknown` | info | The format has no such header. | | `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. | | `opcode.deprecated` | info | The format has dropped the opcode. | | `opcode.no-header` | warning | An opcode comes before any header, so no region has it. | | `opcode.unknown` | info | The format has no such opcode. | | `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. | | `text.unreadable` | warning | Text that isn't SFZ. | | `value.option` | warning | A value isn't one of the opcode's options. | | `value.range` | warning | A number is outside the opcode's range. | | `value.type` | warning or info | A value isn't a number, or isn't a whole number. | ## Errors Errors wrap one of these, for `errors.Is`: - `ErrInvalid`: text that can't be read as an instrument, past the limits, or an edit or output that can't be written as SFZ. - `ErrIncludeLoop`: a file includes itself, directly or through the files it includes. - `ErrUnresolved`: an include can't be read, with `IncludesFail`. - `ErrNoSource` and `ErrUnpatchable`: `Apply` can't make a change. ## Untrusted input An instrument's text decides what the library does, so a file from elsewhere can't be trusted to be small or to stay in its folder. - **Limits.** `Parse` stops at the limits in `Limits`: includes nest at most 16 deep, and the files and what their variables expand to may hold 16 MB. `WithLimits` changes both. It reads no more than the limit from a reader. - **Paths.** The paths in `#include` and `sample` come from the text and can be absolute or hold `..`. A `Resolver` that reads from a disk, and a `FileWriter` that writes to one, need to keep to the instrument's folder. `ParseFile` does, through `fs.FS`, and `WriteFiles` refuses a path that leaves the folder unless `AllowParentPaths` is set. `Region.Sample` is as the text gives it, and the host resolves it. ## Concurrency A `Document` that hasn't been edited can be read from several goroutines at once. Edits aren't synchronised, so don't edit a document while another goroutine is using it. `Lookup` and the registry functions are safe to call from any goroutine. ## Development - `go test ./...` runs the tests. The fuzz targets run with `go test -run xxx -fuzz '^FuzzEdit$' -fuzztime 30s .`, with `FuzzRoundTrip`, `FuzzWrite` and `FuzzBuild` as the other names. - The opcode registry is generated. To change it, replace `internal/gen/syntax.yml`, run `go generate ./...`, then `go test -update`, which rewrites `docs/opcodes.md`. See [internal/gen](internal/gen/README.md). - Many tests mark where an expected value comes from: the format's documentation, the sfizz player's source, or a choice this library makes where neither says. ## Licence MIT. The SFZ files in `testdata/splendid` are another project's, kept as a test fixture, and have their own terms; see [testdata/splendid/README.md](testdata/splendid/README.md).