A standalone Go library that reads, validates and writes SFZ instruments. It is extracted from Zampler (code.aneur.in/zampler/zampler), whose sampler is built on internal/sfz and stores its configuration in project.json. The goal is to keep SFZ handling in one small, stable package, so the sampler's persistence can later move onto it.
The library handles SFZ as data: it reads, edits and writes the whole format (SFZ v1, v2 and the ARIA extensions), whether or not a sampler can play a feature. Which features Zampler plays is documented in Zampler, not here.
Why
The sampler and its SFZ support are a large part of Zampler and a heavy demand on agent context. The SFZ code is the cleanest part to separate: internal/sfz imports nothing else from Zampler.
Zampler only reads SFZ today. Storing samplers as instrument/<name>.sfz in the project needs a writer that loses nothing.
SFZ's document layer is stable. Once the library keeps what it doesn't understand, it should need changes only for a new typed feature or a bug.
Design
Lossless document. Headers, opcodes in order, comments, unknown opcodes, and #include and #define unexpanded. Writing a document it didn't change gives the same text back.
Flattening. A resolved view with includes and macros expanded, which the typed layer reads.
Opcode registry. One table of every opcode in the spec, with its type, range, default, dialect and aliases, including numbered forms such as _onccN. It drives validation, typed access to any opcode, and the README table.
Typed model (regions, envelope, loops, velocity curves, crossfades, triggers, polyphony and choke groups, conditions, keyswitches, modulations, controls). It lives in this library, with json and doc struct tags, so Zampler can use it as its API type.
Edits go through the typed layer as opcode patches. The library never rebuilds a file from the typed model alone.
Unknown opcodes pass through untouched and can be read and set generically. Zampler uses this for its own zampler_* opcodes. The library knows nothing about disks, projects or Zampler.
Writing.WriteOptions has a zero value that writes one file with literal values and keeps an existing document's structure. Options: SplitFiles, InlineIncludes, Variables, ExpandVariables, Indent, LineEnding. A document is a tree of files, so includes are tracked and written.
I/O. A package-level Parse with options, taking an io.Reader and an include resolver (an fs.FS or a callback). Document implements io.WriterTo and fmt.Stringer.
Validation reports problems with line positions, and doesn't fail on things it doesn't support.
Feature table
The README has a table with one row per feature: its name and whether the library knows it, types it, or treats it as a vendor extension. It is generated from the opcode registry, so it can't drift. Playback limits stay in Zampler's docs:
Spike. Round-trip a few real SFZ files (parse, write, parse, compare) to settle the document model.
Library. Port the parser, with its tests and the Splendid Grand Piano fixture, from internal/sfz in Zampler. Add the lossless document, the flattening, the typed model, the writer and validation. Add the opcode registry and the spec's remaining opcodes, headers and directives. Write the README feature table.
Zampler adopts it for reading. Import and the SFZ summary use this library, and internal/sfz goes. Samplers are still saved in project.json, with no format change.
Later, in Zampler: store samplers as instrument/<name>.sfz. That needs a new formatVersion and a migration, and it is a one-way upgrade. Kits stay in project.json.
Steps 1 and 2 happen here. The rest happens in Zampler and is tracked there.
Out of scope
Playback, audio and MIDI. The sampler engine and editor stay in Zampler.
Resolving sample= paths to disks or URLs. The library gives paths, and the host resolves them.
Anything Zampler-specific, such as playback settings and the import record.
Open questions
The module path and the minimum Go version.
The licence. Zampler is AGPL-3.0-or-later.
Whether the typed model's validation and limits (the minimum and maximum tags) live here or stay with Zampler's API.
How the library handles a file whose includes can't be resolved: fail, or parse what it has and report what's missing.
## Summary
A standalone Go library that reads, validates and writes [SFZ](https://sfzformat.com/) instruments. It is extracted from Zampler ([code.aneur.in/zampler/zampler](https://code.aneur.in/zampler/zampler)), whose sampler is built on `internal/sfz` and stores its configuration in `project.json`. The goal is to keep SFZ handling in one small, stable package, so the sampler's persistence can later move onto it.
The library handles SFZ as data: it reads, edits and writes the whole format (SFZ v1, v2 and the ARIA extensions), whether or not a sampler can play a feature. Which features Zampler plays is documented in Zampler, not here.
## Why
- The sampler and its SFZ support are a large part of Zampler and a heavy demand on agent context. The SFZ code is the cleanest part to separate: `internal/sfz` imports nothing else from Zampler.
- Zampler only reads SFZ today. Storing samplers as `instrument/<name>.sfz` in the project needs a writer that loses nothing.
- SFZ's document layer is stable. Once the library keeps what it doesn't understand, it should need changes only for a new typed feature or a bug.
## Design
- **Lossless document.** Headers, opcodes in order, comments, unknown opcodes, and `#include` and `#define` unexpanded. Writing a document it didn't change gives the same text back.
- **Flattening.** A resolved view with includes and macros expanded, which the typed layer reads.
- **Opcode registry.** One table of every opcode in the spec, with its type, range, default, dialect and aliases, including numbered forms such as `_onccN`. It drives validation, typed access to any opcode, and the README table.
- **Typed model** (regions, envelope, loops, velocity curves, crossfades, triggers, polyphony and choke groups, conditions, keyswitches, modulations, controls). It lives in this library, with `json` and `doc` struct tags, so Zampler can use it as its API type.
- **Edits** go through the typed layer as opcode patches. The library never rebuilds a file from the typed model alone.
- **Unknown opcodes** pass through untouched and can be read and set generically. Zampler uses this for its own `zampler_*` opcodes. The library knows nothing about disks, projects or Zampler.
- **Writing.** `WriteOptions` has a zero value that writes one file with literal values and keeps an existing document's structure. Options: `SplitFiles`, `InlineIncludes`, `Variables`, `ExpandVariables`, `Indent`, `LineEnding`. A document is a tree of files, so includes are tracked and written.
- **I/O.** A package-level `Parse` with options, taking an `io.Reader` and an include resolver (an `fs.FS` or a callback). `Document` implements `io.WriterTo` and `fmt.Stringer`.
- **Validation** reports problems with line positions, and doesn't fail on things it doesn't support.
## Feature table
The README has a table with one row per feature: its name and whether the library knows it, types it, or treats it as a vendor extension. It is generated from the opcode registry, so it can't drift. Playback limits stay in Zampler's docs:
- Zampler's [SFZ support reference](https://code.aneur.in/zampler/zampler/src/branch/main/docs/reference.sfz-support.md)
- zampler/zampler#105, which lists what Zampler deliberately doesn't play
## Plan
1. **Spike.** Round-trip a few real SFZ files (parse, write, parse, compare) to settle the document model.
2. **Library.** Port the parser, with its tests and the Splendid Grand Piano fixture, from `internal/sfz` in Zampler. Add the lossless document, the flattening, the typed model, the writer and validation. Add the opcode registry and the spec's remaining opcodes, headers and directives. Write the README feature table.
3. **Zampler adopts it for reading.** Import and the SFZ summary use this library, and `internal/sfz` goes. Samplers are still saved in `project.json`, with no format change.
4. **Later, in Zampler:** store samplers as `instrument/<name>.sfz`. That needs a new `formatVersion` and a migration, and it is a one-way upgrade. Kits stay in `project.json`.
Steps 1 and 2 happen here. The rest happens in Zampler and is tracked there.
## Out of scope
- Playback, audio and MIDI. The sampler engine and editor stay in Zampler.
- Resolving `sample=` paths to disks or URLs. The library gives paths, and the host resolves them.
- Anything Zampler-specific, such as playback settings and the import record.
## Open questions
- The module path and the minimum Go version.
- The licence. Zampler is AGPL-3.0-or-later.
- Whether the typed model's validation and limits (the `minimum` and `maximum` tags) live here or stay with Zampler's API.
- How the library handles a file whose includes can't be resolved: fail, or parse what it has and report what's missing.
aneurin
was assigned by claude2026-11-30 00:09:33 +00:00
The library reads, edits, validates and writes SFZ. It is not wired into Zampler yet (steps 3 and 4 below).
What is in
Lossless document.Parse and ParseFile keep a file exactly as written, with #define and #include unexpanded, and each include that was read is its own file in a tree. Writing an unchanged document gives the same text back, byte for byte (golden tests on the Splendid Grand Piano, and a fuzz test).
Flattening and typed model.Document.Flatten resolves includes, variables and header inheritance. Flat.Instrument reads regions into the model ported from internal/sfz, with its tests and the Splendid fixture. Ignored and LeftOut are now Unread and Skipped.
Opcode registry. 734 opcodes and 9 headers, generated from the data behind sfzformat.com (CC0, commit recorded in internal/gen/README.md). Lookup finds families such as loccN and aliases such as loopmode. GetAs[T] reads any opcode as an int, float or string. docs/opcodes.md lists every opcode and marks the 112 the typed model reads; a test keeps it current.
Validation.Validate reports unknown headers and opcodes, wrong types, out-of-range values, values outside an option list, lo above hi, undefined variables and unresolved includes, all with file, line and column. It never fails on an opcode it doesn't know.
Editing.Header.Get, Set and Delete keep the comments and spacing around an opcode. Set on an opcode that uses a variable writes the value in its place; Document.SetDefine changes the variable.
Writing.Write and WriteFiles take WriteOptions (InlineIncludes, ExpandVariables, LineEnding); the zero value writes each file as it was read.
Building.Build(inst, BuildOptions) makes a document from an Instrument, with SplitFiles, Variables and Indent. Reading the result gives the instrument back, except for opcodes the model doesn't hold.
Decisions
Scope. The library handles the whole format (SFZ v1, v2 and ARIA) as data, whether or not a sampler plays it. What Zampler plays stays documented in Zampler. This replaces "accurately, not completely".
Feature table.docs/opcodes.md is generated from the registry, with a "typed" column, rather than a hand-kept tick/cross table in the README.
Licence. MIT. Module code.aneur.in/zampler/sfz; go 1.25.0 is the minimum (Zampler is on 1.26).
Validation ranges live here, driven by the registry. The minimum/maximum tags stay Zampler's concern.
Unresolved includes.Parse reports them as problems and carries on. WithIncludes(IncludesFail) makes it an error. Include loops and depth or size overruns (16 deep, 16 MB, both adjustable) are always errors.
Fixtures. Zampler's Splendid Grand Piano plus small hand-made files; no other third-party libraries.
Multi-file and variables. Both are supported from the first release. The default writes one file with values as they were; options turn the rest on.
Build options (Indent, SplitFiles, Variables) are separate from write options, since they only apply to a new document. SplitFiles splits by region count, because the typed model has no groups.
Edits are opcode patches. The library never rebuilds an existing file from the typed model; Build is for new documents only.
Known gaps
Registry data: 289 opcodes have no type in the spec data, so their values aren't checked. The Splendid fixture's amplitude_oncc70=200 is flagged because the spec's maximum is 100.
No check that an opcode is in a header where it belongs; the spec data doesn't say.
The typed model holds what Zampler reads. Everything else is reachable with GetAs and the opcode maps.
No json/doc struct tags on the typed model yet, and no CI config.
Next (in Zampler)
Zampler adopts the library for reading: import and the SFZ summary use it, and internal/sfz goes. No format change.
Store samplers as instrument/<name>.sfz, with a new formatVersion and a one-way migration.
## Status: steps 1 and 2 are on `main`
The library reads, edits, validates and writes SFZ. It is not wired into Zampler yet (steps 3 and 4 below).
### What is in
- **Lossless document.** `Parse` and `ParseFile` keep a file exactly as written, with `#define` and `#include` unexpanded, and each include that was read is its own file in a tree. Writing an unchanged document gives the same text back, byte for byte (golden tests on the Splendid Grand Piano, and a fuzz test).
- **Flattening and typed model.** `Document.Flatten` resolves includes, variables and header inheritance. `Flat.Instrument` reads regions into the model ported from `internal/sfz`, with its tests and the Splendid fixture. `Ignored` and `LeftOut` are now `Unread` and `Skipped`.
- **Opcode registry.** 734 opcodes and 9 headers, generated from the data behind sfzformat.com (CC0, commit recorded in `internal/gen/README.md`). `Lookup` finds families such as `loccN` and aliases such as `loopmode`. `GetAs[T]` reads any opcode as an int, float or string. `docs/opcodes.md` lists every opcode and marks the 112 the typed model reads; a test keeps it current.
- **Validation.** `Validate` reports unknown headers and opcodes, wrong types, out-of-range values, values outside an option list, `lo` above `hi`, undefined variables and unresolved includes, all with file, line and column. It never fails on an opcode it doesn't know.
- **Editing.** `Header.Get`, `Set` and `Delete` keep the comments and spacing around an opcode. `Set` on an opcode that uses a variable writes the value in its place; `Document.SetDefine` changes the variable.
- **Writing.** `Write` and `WriteFiles` take `WriteOptions` (`InlineIncludes`, `ExpandVariables`, `LineEnding`); the zero value writes each file as it was read.
- **Building.** `Build(inst, BuildOptions)` makes a document from an `Instrument`, with `SplitFiles`, `Variables` and `Indent`. Reading the result gives the instrument back, except for opcodes the model doesn't hold.
### Decisions
- **Scope.** The library handles the whole format (SFZ v1, v2 and ARIA) as data, whether or not a sampler plays it. What Zampler plays stays documented in Zampler. This replaces "accurately, not completely".
- **Feature table.** `docs/opcodes.md` is generated from the registry, with a "typed" column, rather than a hand-kept tick/cross table in the README.
- **Licence.** MIT. Module `code.aneur.in/zampler/sfz`; `go 1.25.0` is the minimum (Zampler is on 1.26).
- **Validation ranges** live here, driven by the registry. The `minimum`/`maximum` tags stay Zampler's concern.
- **Unresolved includes.** `Parse` reports them as problems and carries on. `WithIncludes(IncludesFail)` makes it an error. Include loops and depth or size overruns (16 deep, 16 MB, both adjustable) are always errors.
- **Fixtures.** Zampler's Splendid Grand Piano plus small hand-made files; no other third-party libraries.
- **Multi-file and variables.** Both are supported from the first release. The default writes one file with values as they were; options turn the rest on.
- **Build options** (`Indent`, `SplitFiles`, `Variables`) are separate from write options, since they only apply to a new document. `SplitFiles` splits by region count, because the typed model has no groups.
- **Edits are opcode patches.** The library never rebuilds an existing file from the typed model; `Build` is for new documents only.
### Known gaps
- Registry data: 289 opcodes have no type in the spec data, so their values aren't checked. The Splendid fixture's `amplitude_oncc70=200` is flagged because the spec's maximum is 100.
- No check that an opcode is in a header where it belongs; the spec data doesn't say.
- The typed model holds what Zampler reads. Everything else is reachable with `GetAs` and the opcode maps.
- No `json`/`doc` struct tags on the typed model yet, and no CI config.
### Next (in Zampler)
3. Zampler adopts the library for reading: import and the SFZ summary use it, and `internal/sfz` goes. No format change.
4. Store samplers as `instrument/<name>.sfz`, with a new `formatVersion` and a one-way migration.
Found while checking whether Zampler can store instruments as SFZ, with its own data in project.json and in zampler_* opcodes.
Instrument.Regions[i] has no accessor for its FlatRegion or Header. Typed and flat indices differ as soon as a region is skipped: parsing four <region>s, one with no sample and one generated, gives 2 typed regions and 4 flat ones.
Zampler needs this to keep per-region data in the file, such as a zone ID or a sample reference. Header.Set and GetAs work on unknown opcodes (zampler_zone=abc123 survived a re-flatten), but the only way to reach the header of typed region i is to assume Flat.Regions[i] is Instrument.Regions[i]. That holds only while Skipped is empty.
Ask: an accessor such as Instrument.Source(i int) (*FlatRegion, bool).
## Gap 1: no link from a typed region to its header
Found while checking whether Zampler can store instruments as SFZ, with its own data in `project.json` and in `zampler_*` opcodes.
`Instrument.Regions[i]` has no accessor for its `FlatRegion` or `Header`. Typed and flat indices differ as soon as a region is skipped: parsing four `<region>`s, one with no sample and one generated, gives 2 typed regions and 4 flat ones.
Zampler needs this to keep per-region data in the file, such as a zone ID or a sample reference. `Header.Set` and `GetAs` work on unknown opcodes (`zampler_zone=abc123` survived a re-flatten), but the only way to reach the header of typed region `i` is to assume `Flat.Regions[i]` is `Instrument.Regions[i]`. That holds only while `Skipped` is empty.
**Ask:** an accessor such as `Instrument.Source(i int) (*FlatRegion, bool)`.
Gap 2: no structural edits on an existing document
There is no way to remove or move a region. Header.Delete removes opcodes, not headers. Zampler's zone delete and zone reorder (slot order) have nothing to call.
Adding a region means AddHeader followed by one Set per opcode by hand. That works (the region is read back), but there is no typed "append this Region", so a caller would have to rewrite Patches itself.
Without these, Zampler has to rebuild the file with Build on every structural change. That loses comments, unknown opcodes and includes, which defeats the lossless design.
A document edit also leaves the Instrument stale. After AddHeader and Set, a fresh Flatten().Instrument() has 4 regions and the old instrument still has 3.
Ask:AddRegion(Region), RemoveRegion(i) and MoveRegion(from, to) on Instrument, which edit the document and update the instrument as Apply does.
## Gap 2: no structural edits on an existing document
There is no way to remove or move a region. `Header.Delete` removes opcodes, not headers. Zampler's zone delete and zone reorder (slot order) have nothing to call.
Adding a region means `AddHeader` followed by one `Set` per opcode by hand. That works (the region is read back), but there is no typed "append this `Region`", so a caller would have to rewrite `Patches` itself.
Without these, Zampler has to rebuild the file with `Build` on every structural change. That loses comments, unknown opcodes and includes, which defeats the lossless design.
A document edit also leaves the `Instrument` stale. After `AddHeader` and `Set`, a fresh `Flatten().Instrument()` has 4 regions and the old instrument still has 3.
**Ask:** `AddRegion(Region)`, `RemoveRegion(i)` and `MoveRegion(from, to)` on `Instrument`, which edit the document and update the instrument as `Apply` does.
trigger= and off_mode= have empty values, and seq_length=0, seq_position=0 and hirand=0 are not meaningful. The caller has to know to set Trigger: "attack", OffMode: "fast", SequenceLength: 1, SequencePosition: 1, HighRandom: 1, HighKey: 127 and the others.
Ask:Build either fills these defaults or returns ErrInvalid. Either is fine, but not silent output.
Related, smaller
Region.Sample is rejected by Build ("can't be written as one opcode") if it contains //, <, */, or a space followed by = (for example a b=c.wav), and backslashes come back as /. Real filenames on remote disks can hit these, so Zampler can't use raw disk paths as sample=. This may only need documenting.
Apply returns ErrUnpatchable for a sample outside default_path, and for removing a modulation inherited from a <group>. It returns ErrNoSource for a region made by #define. That is documented, and it only affects hand-written or imported files.
## Gap 3: `Build` doesn't normalise or reject a zero `Region`
`Build` writes a `Region` with zero values as empty or invalid SFZ. For `Region{Sample: "a.wav"}` it writes:
```
<region>
sample=a.wav
hikey=0
pitch_keycenter=0
hivel=0
pitch_keytrack=0
amp_veltrack=0
ampeg_sustain=0
ampeg_release=0
trigger=
seq_length=0
seq_position=0
hirand=0
off_mode=
off_time=0
```
`trigger=` and `off_mode=` have empty values, and `seq_length=0`, `seq_position=0` and `hirand=0` are not meaningful. The caller has to know to set `Trigger: "attack"`, `OffMode: "fast"`, `SequenceLength: 1`, `SequencePosition: 1`, `HighRandom: 1`, `HighKey: 127` and the others.
**Ask:** `Build` either fills these defaults or returns `ErrInvalid`. Either is fine, but not silent output.
## Related, smaller
- `Region.Sample` is rejected by `Build` ("can't be written as one opcode") if it contains `//`, `<`, `*/`, or a space followed by `=` (for example `a b=c.wav`), and backslashes come back as `/`. Real filenames on remote disks can hit these, so Zampler can't use raw disk paths as `sample=`. This may only need documenting.
- `Apply` returns `ErrUnpatchable` for a sample outside `default_path`, and for removing a modulation inherited from a `<group>`. It returns `ErrNoSource` for a region made by `#define`. That is documented, and it only affects hand-written or imported files.
Gap 1:Instrument.Source(i) returns the FlatRegion and Header behind typed region i. The Header is nil when a variable made it.
Gap 2:Instrument.AddRegion, RemoveRegion and MoveRegion edit the document and read the instrument again, so it matches the document, including Skipped, Unread and Controls. An edit that would read differently, or whose text would not read back as the edited nodes, changes nothing and returns ErrUnpatchable. ErrNoSource is returned for a region with no header of its own, and for an instrument that was not read from a document, or that was changed other than with Apply, or whose document was edited since it was read.
Gap 3:Build returns ErrInvalid for a region that cannot be read back as it is: an empty sample, an empty or unknown Trigger, an OffMode that is not fast, time or normal, a sequence length or position below 1, an empty random range, or inverted key or velocity ranges. NewRegion(sample) returns a region with the format's defaults.
zampler_* opcodes: treated like any unknown opcode. They are kept through every edit and a write, and reachable with Source(i).Header and Get and Set. Validate reports them as information only.
Sample paths: the Build and Apply restrictions are documented in the README.
Behaviour to know about:
A comment on the lines above a <region> stays with the header before it, so it is not removed or moved with the region it is above.
Each structural edit flattens the whole document, so many edits in a row cost more than one.
Build now fails for an instrument read from a file with, for example, trigger=bogus or hirand=0.
## Gaps 1, 2 and 3 are closed
Committed to `main` in 49fd867 and 8db34cc.
- **Gap 1:** `Instrument.Source(i)` returns the `FlatRegion` and `Header` behind typed region `i`. The `Header` is nil when a variable made it.
- **Gap 2:** `Instrument.AddRegion`, `RemoveRegion` and `MoveRegion` edit the document and read the instrument again, so it matches the document, including `Skipped`, `Unread` and `Controls`. An edit that would read differently, or whose text would not read back as the edited nodes, changes nothing and returns `ErrUnpatchable`. `ErrNoSource` is returned for a region with no header of its own, and for an instrument that was not read from a document, or that was changed other than with `Apply`, or whose document was edited since it was read.
- **Gap 3:** `Build` returns `ErrInvalid` for a region that cannot be read back as it is: an empty sample, an empty or unknown `Trigger`, an `OffMode` that is not fast, time or normal, a sequence length or position below 1, an empty random range, or inverted key or velocity ranges. `NewRegion(sample)` returns a region with the format's defaults.
- **`zampler_*` opcodes:** treated like any unknown opcode. They are kept through every edit and a write, and reachable with `Source(i).Header` and `Get` and `Set`. `Validate` reports them as information only.
- **Sample paths:** the `Build` and `Apply` restrictions are documented in the README.
Behaviour to know about:
- A comment on the lines above a `<region>` stays with the header before it, so it is not removed or moved with the region it is above.
- Each structural edit flattens the whole document, so many edits in a row cost more than one.
- `Build` now fails for an instrument read from a file with, for example, `trigger=bogus` or `hirand=0`.
On the Splendid Grand Piano fixture, AddRegion returns ErrUnpatchable:
doc,_:=sfz.ParseFile(os.DirFS("testdata/splendid"),"Splendid Grand Piano.sfz")inst:=doc.Flatten().Instrument()err:=inst.AddRegion(sfz.NewRegion("x.wav"))// the region can't be written to its own header: region 359 would read// differently: Sample, Envelope.Release, Modulations, NotePolyphony
The new region goes at the end of the document, so it inherits the opcodes of the <global>, <master> and <group> above it. Some of them (modulations, note_polyphony, a release time) can't be cancelled by an opcode in the region's own header, so AddRegion refuses.
The same file reads and edits fine otherwise: Apply, RemoveRegion and MoveRegion work. Instruments that Build makes have nothing to inherit, so they are not affected. Adding a region to an instrument read from a file with such headers is.
Ask: make AddRegion work when the headers above the end of the document change the region. A header clears the opcodes of the levels below it, so an empty <global> before the new region should stop the inheritance. AddRegion could write one when the headers above it would otherwise change the region.
If that is not wanted, document the limit on AddRegion, so a host knows to rebuild an instrument with Build when it returns ErrUnpatchable.
Not about this issue, but noted while measuring: each structural edit flattens the whole document. On synthetic flat instruments, add, remove and move take about 0.5 s at 5,000 regions and 0.9 s at 10,000, growing linearly. On Splendid (360 regions) they took 130–280 ms. Apply stays at about 0.1 ms.
## `AddRegion` fails on a real-world file
Checked against `main` after gaps 1–3 closed.
On the Splendid Grand Piano fixture, `AddRegion` returns `ErrUnpatchable`:
```go
doc, _ := sfz.ParseFile(os.DirFS("testdata/splendid"), "Splendid Grand Piano.sfz")
inst := doc.Flatten().Instrument()
err := inst.AddRegion(sfz.NewRegion("x.wav"))
// the region can't be written to its own header: region 359 would read
// differently: Sample, Envelope.Release, Modulations, NotePolyphony
```
The new region goes at the end of the document, so it inherits the opcodes of the `<global>`, `<master>` and `<group>` above it. Some of them (modulations, `note_polyphony`, a release time) can't be cancelled by an opcode in the region's own header, so `AddRegion` refuses.
The same file reads and edits fine otherwise: `Apply`, `RemoveRegion` and `MoveRegion` work. Instruments that `Build` makes have nothing to inherit, so they are not affected. Adding a region to an instrument read from a file with such headers is.
**Ask:** make `AddRegion` work when the headers above the end of the document change the region. A header clears the opcodes of the levels below it, so an empty `<global>` before the new region should stop the inheritance. `AddRegion` could write one when the headers above it would otherwise change the region.
If that is not wanted, document the limit on `AddRegion`, so a host knows to rebuild an instrument with `Build` when it returns `ErrUnpatchable`.
Not about this issue, but noted while measuring: each structural edit flattens the whole document. On synthetic flat instruments, add, remove and move take about 0.5 s at 5,000 regions and 0.9 s at 10,000, growing linearly. On Splendid (360 regions) they took 130–280 ms. `Apply` stays at about 0.1 ms.
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.
Summary
A standalone Go library that reads, validates and writes SFZ instruments. It is extracted from Zampler (code.aneur.in/zampler/zampler), whose sampler is built on
internal/sfzand stores its configuration inproject.json. The goal is to keep SFZ handling in one small, stable package, so the sampler's persistence can later move onto it.The library handles SFZ as data: it reads, edits and writes the whole format (SFZ v1, v2 and the ARIA extensions), whether or not a sampler can play a feature. Which features Zampler plays is documented in Zampler, not here.
Why
internal/sfzimports nothing else from Zampler.instrument/<name>.sfzin the project needs a writer that loses nothing.Design
#includeand#defineunexpanded. Writing a document it didn't change gives the same text back._onccN. It drives validation, typed access to any opcode, and the README table.jsonanddocstruct tags, so Zampler can use it as its API type.zampler_*opcodes. The library knows nothing about disks, projects or Zampler.WriteOptionshas a zero value that writes one file with literal values and keeps an existing document's structure. Options:SplitFiles,InlineIncludes,Variables,ExpandVariables,Indent,LineEnding. A document is a tree of files, so includes are tracked and written.Parsewith options, taking anio.Readerand an include resolver (anfs.FSor a callback).Documentimplementsio.WriterToandfmt.Stringer.Feature table
The README has a table with one row per feature: its name and whether the library knows it, types it, or treats it as a vendor extension. It is generated from the opcode registry, so it can't drift. Playback limits stay in Zampler's docs:
Plan
internal/sfzin Zampler. Add the lossless document, the flattening, the typed model, the writer and validation. Add the opcode registry and the spec's remaining opcodes, headers and directives. Write the README feature table.internal/sfzgoes. Samplers are still saved inproject.json, with no format change.instrument/<name>.sfz. That needs a newformatVersionand a migration, and it is a one-way upgrade. Kits stay inproject.json.Steps 1 and 2 happen here. The rest happens in Zampler and is tracked there.
Out of scope
sample=paths to disks or URLs. The library gives paths, and the host resolves them.Open questions
minimumandmaximumtags) live here or stay with Zampler's API.Status: steps 1 and 2 are on
mainThe library reads, edits, validates and writes SFZ. It is not wired into Zampler yet (steps 3 and 4 below).
What is in
ParseandParseFilekeep a file exactly as written, with#defineand#includeunexpanded, and each include that was read is its own file in a tree. Writing an unchanged document gives the same text back, byte for byte (golden tests on the Splendid Grand Piano, and a fuzz test).Document.Flattenresolves includes, variables and header inheritance.Flat.Instrumentreads regions into the model ported frominternal/sfz, with its tests and the Splendid fixture.IgnoredandLeftOutare nowUnreadandSkipped.internal/gen/README.md).Lookupfinds families such asloccNand aliases such asloopmode.GetAs[T]reads any opcode as an int, float or string.docs/opcodes.mdlists every opcode and marks the 112 the typed model reads; a test keeps it current.Validatereports unknown headers and opcodes, wrong types, out-of-range values, values outside an option list,loabovehi, undefined variables and unresolved includes, all with file, line and column. It never fails on an opcode it doesn't know.Header.Get,SetandDeletekeep the comments and spacing around an opcode.Seton an opcode that uses a variable writes the value in its place;Document.SetDefinechanges the variable.WriteandWriteFilestakeWriteOptions(InlineIncludes,ExpandVariables,LineEnding); the zero value writes each file as it was read.Build(inst, BuildOptions)makes a document from anInstrument, withSplitFiles,VariablesandIndent. Reading the result gives the instrument back, except for opcodes the model doesn't hold.Decisions
docs/opcodes.mdis generated from the registry, with a "typed" column, rather than a hand-kept tick/cross table in the README.code.aneur.in/zampler/sfz;go 1.25.0is the minimum (Zampler is on 1.26).minimum/maximumtags stay Zampler's concern.Parsereports them as problems and carries on.WithIncludes(IncludesFail)makes it an error. Include loops and depth or size overruns (16 deep, 16 MB, both adjustable) are always errors.Indent,SplitFiles,Variables) are separate from write options, since they only apply to a new document.SplitFilessplits by region count, because the typed model has no groups.Buildis for new documents only.Known gaps
amplitude_oncc70=200is flagged because the spec's maximum is 100.GetAsand the opcode maps.json/docstruct tags on the typed model yet, and no CI config.Next (in Zampler)
internal/sfzgoes. No format change.instrument/<name>.sfz, with a newformatVersionand a one-way migration.Gap 1: no link from a typed region to its header
Found while checking whether Zampler can store instruments as SFZ, with its own data in
project.jsonand inzampler_*opcodes.Instrument.Regions[i]has no accessor for itsFlatRegionorHeader. Typed and flat indices differ as soon as a region is skipped: parsing four<region>s, one with no sample and one generated, gives 2 typed regions and 4 flat ones.Zampler needs this to keep per-region data in the file, such as a zone ID or a sample reference.
Header.SetandGetAswork on unknown opcodes (zampler_zone=abc123survived a re-flatten), but the only way to reach the header of typed regioniis to assumeFlat.Regions[i]isInstrument.Regions[i]. That holds only whileSkippedis empty.Ask: an accessor such as
Instrument.Source(i int) (*FlatRegion, bool).Gap 2: no structural edits on an existing document
There is no way to remove or move a region.
Header.Deleteremoves opcodes, not headers. Zampler's zone delete and zone reorder (slot order) have nothing to call.Adding a region means
AddHeaderfollowed by oneSetper opcode by hand. That works (the region is read back), but there is no typed "append thisRegion", so a caller would have to rewritePatchesitself.Without these, Zampler has to rebuild the file with
Buildon every structural change. That loses comments, unknown opcodes and includes, which defeats the lossless design.A document edit also leaves the
Instrumentstale. AfterAddHeaderandSet, a freshFlatten().Instrument()has 4 regions and the old instrument still has 3.Ask:
AddRegion(Region),RemoveRegion(i)andMoveRegion(from, to)onInstrument, which edit the document and update the instrument asApplydoes.Gap 3:
Builddoesn't normalise or reject a zeroRegionBuildwrites aRegionwith zero values as empty or invalid SFZ. ForRegion{Sample: "a.wav"}it writes:trigger=andoff_mode=have empty values, andseq_length=0,seq_position=0andhirand=0are not meaningful. The caller has to know to setTrigger: "attack",OffMode: "fast",SequenceLength: 1,SequencePosition: 1,HighRandom: 1,HighKey: 127and the others.Ask:
Buildeither fills these defaults or returnsErrInvalid. Either is fine, but not silent output.Related, smaller
Region.Sampleis rejected byBuild("can't be written as one opcode") if it contains//,<,*/, or a space followed by=(for examplea b=c.wav), and backslashes come back as/. Real filenames on remote disks can hit these, so Zampler can't use raw disk paths assample=. This may only need documenting.ApplyreturnsErrUnpatchablefor a sample outsidedefault_path, and for removing a modulation inherited from a<group>. It returnsErrNoSourcefor a region made by#define. That is documented, and it only affects hand-written or imported files.Gaps 1, 2 and 3 are closed
Committed to
mainin49fd867and8db34cc.Instrument.Source(i)returns theFlatRegionandHeaderbehind typed regioni. TheHeaderis nil when a variable made it.Instrument.AddRegion,RemoveRegionandMoveRegionedit the document and read the instrument again, so it matches the document, includingSkipped,UnreadandControls. An edit that would read differently, or whose text would not read back as the edited nodes, changes nothing and returnsErrUnpatchable.ErrNoSourceis returned for a region with no header of its own, and for an instrument that was not read from a document, or that was changed other than withApply, or whose document was edited since it was read.BuildreturnsErrInvalidfor a region that cannot be read back as it is: an empty sample, an empty or unknownTrigger, anOffModethat is not fast, time or normal, a sequence length or position below 1, an empty random range, or inverted key or velocity ranges.NewRegion(sample)returns a region with the format's defaults.zampler_*opcodes: treated like any unknown opcode. They are kept through every edit and a write, and reachable withSource(i).HeaderandGetandSet.Validatereports them as information only.BuildandApplyrestrictions are documented in the README.Behaviour to know about:
<region>stays with the header before it, so it is not removed or moved with the region it is above.Buildnow fails for an instrument read from a file with, for example,trigger=bogusorhirand=0.AddRegionfails on a real-world fileChecked against
mainafter gaps 1–3 closed.On the Splendid Grand Piano fixture,
AddRegionreturnsErrUnpatchable:The new region goes at the end of the document, so it inherits the opcodes of the
<global>,<master>and<group>above it. Some of them (modulations,note_polyphony, a release time) can't be cancelled by an opcode in the region's own header, soAddRegionrefuses.The same file reads and edits fine otherwise:
Apply,RemoveRegionandMoveRegionwork. Instruments thatBuildmakes have nothing to inherit, so they are not affected. Adding a region to an instrument read from a file with such headers is.Ask: make
AddRegionwork when the headers above the end of the document change the region. A header clears the opcodes of the levels below it, so an empty<global>before the new region should stop the inheritance.AddRegioncould write one when the headers above it would otherwise change the region.If that is not wanted, document the limit on
AddRegion, so a host knows to rebuild an instrument withBuildwhen it returnsErrUnpatchable.Not about this issue, but noted while measuring: each structural edit flattens the whole document. On synthetic flat instruments, add, remove and move take about 0.5 s at 5,000 regions and 0.9 s at 10,000, growing linearly. On Splendid (360 regions) they took 130–280 ms.
Applystays at about 0.1 ms.