Files
sfz/README.md
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

8.8 KiB

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 #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 <control> settings, <global>, <master> and <group> 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: 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.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.
  • 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, 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 #defines 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.

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, 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. 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.
  • 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.