AllowParentPaths is off by default, so WriteFiles still refuses a path with .. in it. Absolute paths are refused either way. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
sfz
A Go library that reads, validates, edits and writes SFZ 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.
go get code.aneur.in/zampler/sfz
It needs Go 1.25 or later and has no dependencies.
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
#defineand#includeunexpanded. Each#includethat was read holds its file, so a document is a tree of files.Stringreturns the main file's text, and a document that hasn't been edited gives the text it was read from. - Flat.
Document.Flattenreads each#includewhere it stands, replaces variables with their values as of where they are used, and gives each region the opcodes of the<control>settings,<global>,<master>and<group>above it. Comments and layout are gone. - Instrument.
Flat.Instrumentreads the regions into a typed model, with settings taken at the controllers' starting values. Opcodes the model has no field for are counted inUnread, and regions it has no region for, such as generated sounds, inSkipped.
Opcodes
The library knows every opcode and header in the format, from the data behind sfzformat.com: 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 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.Headersreturns the headers of every file.Header.Get,SetandDeletechange 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.AddHeaderadds a header.Header.Set,Document.SetDefineandDocument.AddHeaderreturn an error wrappingErrInvalid, 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.Seton an opcode that uses a variable writes the value in its place.Document.SetDefinechanges 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.Patchesreturns the changes without making them.- It returns
ErrNoSourceif 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 outsidedefault_path.
- It returns
Nodepositions are worked out when asked for, withFile.Position, so edits stay cheap.
Writing and building
Document.Writewrites one file, andWriteFileswrites the main file and each file it includes, through aFileWriter. They takeWriteOptions:InlineIncludesputs included files into the main file,ExpandVariablesreplaces variables with their values, andLineEndingsets the line break. The zero value writes each file as it was read.WriteandWriteToreturn an error for a document with includes unlessInlineIncludesis set, as the files they hold would be lost.WriteFilesalso returns an error for an include whose path is absolute or leaves the folder (AllowParentPathsopts in to..paths, not absolute ones), and for a file included more than once that would be written differently each time.Buildmakes a new document from anInstrument, withBuildOptions:SplitFilesputs regions in included files,Variableshoists repeated values into#defines and the samples' folder intodefault_path, andIndentsets 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.
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 Problems 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, withIncludesFail.ErrNoSourceandErrUnpatchable:Applycan'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.
Parsestops at the limits inLimits: includes nest at most 16 deep, and the files and what their variables expand to may hold 16 MB.WithLimitschanges both. It reads no more than the limit from a reader. - Paths. The paths in
#includeandsamplecome from the text and can be absolute or hold... AResolverthat reads from a disk, and aFileWriterthat writes to one, need to keep to the instrument's folder.ParseFiledoes, throughfs.FS, andWriteFilesrefuses a path that leaves the folder unlessAllowParentPathsis set.Region.Sampleis 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 withgo test -run xxx -fuzz '^FuzzEdit$' -fuzztime 30s ., withFuzzRoundTrip,FuzzWriteandFuzzBuildas the other names.- The opcode registry is generated. To change it, replace
internal/gen/syntax.yml, rungo generate ./..., thengo test -update, which rewritesdocs/opcodes.md. See internal/gen. - 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.