Rewrite the code comments for consistent tone and accuracy

Comments only: the tokens of every Go file are unchanged.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-01 19:08:00 +00:00
co-authored by Claude Sonnet 5.5
parent 41f752e1c1
commit 158661eefe
27 changed files with 716 additions and 437 deletions
+6 -6
View File
@@ -2,16 +2,16 @@ package sfz
import "strings"
// Value is the Go types that an opcode's value can be read as.
// Value is the Go types that the value of an opcode can be read as.
type Value interface {
int | int64 | float64 | string
}
// GetAs returns the value of an opcode, read as a T, or false if it isn't
// set or can't be read as one. A name the format gives an alias is also looked
// up by its aliases, so GetAs(o, "loop_mode") finds loopmode. An integer opcode
// that takes notes, such as lokey, reads a note name as its MIDI number, with
// middle C as c4. A string is returned without surrounding whitespace.
// GetAs returns the value of an opcode, read as a T, and whether the opcode is
// set and can be read as one. An opcode that the format gives aliases is found
// by any of its names, so GetAs(o, "loop_mode") finds loopmode. An integer
// opcode that takes notes, such as lokey, reads a note name as its MIDI number,
// with middle C as c4. A string is returned without surrounding whitespace.
func GetAs[T Value](o Opcodes, name string) (T, bool) {
var zero T
raw, ok := o[name]
+52 -37
View File
@@ -10,29 +10,31 @@ import (
)
// BuildOptions change how [Build] lays out a document. The zero value makes one
// file, with the values written literally and two spaces of indent.
// file, with each value written out where it is used and an indent of two
// spaces.
type BuildOptions struct {
// Indent is what an opcode's line starts with. The default is two spaces.
// Indent is what the line of an opcode starts with. The default is two
// spaces.
Indent string
// SplitFiles puts the regions into included files, RegionsPerFile at a
// time, and leaves the controls and variables in the main file.
// SplitFiles puts the regions into included files, RegionsPerFile at a time,
// and leaves the controls, curves and variables in the main file.
SplitFiles bool
// RegionsPerFile is how many regions each included file holds. The default
// is 64.
// RegionsPerFile is how many regions each included file holds, when
// SplitFiles is set. The default is 64.
RegionsPerFile int
// FileNamer returns the path of an included file, given its number from 0,
// relative to the main file's folder. The default is regions/001.sfz,
// regions/002.sfz and so on.
// relative to the main file's folder, when SplitFiles is set. The default
// gives regions/001.sfz, regions/002.sfz and so on.
FileNamer func(index int) string
// Variables writes a #define for each value that more than MinRepeat
// regions share, and uses default_path for the folder that all samples are
// in.
// Variables writes a #define for each value that at least MinRepeat regions
// share, and sets default_path to the folder that all the samples are in.
Variables bool
// MinRepeat is how many regions must share an opcode's value to make it a
// variable. The default is 8.
// MinRepeat is how many regions must share an opcode's value for the value
// to become a variable, when Variables is set. The default is 8.
MinRepeat int
}
// defaults sets each option that has its zero value to its default.
func (o *BuildOptions) defaults() {
if o.Indent == "" {
o.Indent = " "
@@ -48,7 +50,8 @@ func (o *BuildOptions) defaults() {
}
}
// defaultRegion is a region that sets nothing: the format's defaults.
// defaultRegion returns a region that sets nothing, which has the format's
// defaults.
func defaultRegion() Region {
return Region{
HighKey: 127, RootKey: defaultRootKey, LowVelocity: defaultLowVelocity, HighVelocity: 127,
@@ -57,21 +60,24 @@ func defaultRegion() Region {
}
}
// opcodeLine is an opcode to write.
// opcodeLine is an opcode to write, with its value as text.
type opcodeLine struct{ name, value string }
// num writes a number with the digits it needs to read back as it was.
// num returns a number as text, with the fewest digits that read back as the
// same number.
func num(v float64) string { return strconv.FormatFloat(v, 'f', -1, 64) }
// scaled writes a condition's limit in the unit of its opcode, which is the
// limit times scale, rounded so that a limit that was a whole number stays
// one.
// scaled returns a condition's limit as text in the unit of its opcode, which
// is the limit times scale. It is rounded so that a limit that was a whole
// number in that unit is written as one.
func scaled(v, scale float64) string { return num(math.Round(v*scale*1e9) / 1e9) }
// Build makes a document that describes the instrument. Reading it with
// Build makes a new document that describes the instrument. Reading it with
// [Document.Flatten] and [Flat.Instrument] gives the instrument back, except
// for what the model doesn't hold: unread opcodes, and which headers regions
// were under.
// 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.
func Build(inst *Instrument, opts ...BuildOptions) (*Document, error) {
var o BuildOptions
if len(opts) > 0 {
@@ -132,7 +138,7 @@ func Build(inst *Instrument, opts ...BuildOptions) (*Document, error) {
return &Document{Root: b.file("")}, nil
}
// The main file includes a file for each run of regions.
// Each run of regions goes in a file that the main file includes.
if b.err != nil {
return nil, b.err
}
@@ -159,19 +165,24 @@ func Build(inst *Instrument, opts ...BuildOptions) (*Document, error) {
return &Document{Root: main}, nil
}
// builder writes text and lexes it into files.
// builder writes the text of a file and lexes it into a [File].
type builder struct {
// indent is what the line of an opcode starts with.
indent string
// text is what has been written.
text strings.Builder
// err is the first thing that couldn't be written.
err error
}
// line writes a line of text.
func (b *builder) line(s string) {
b.text.WriteString(s)
b.text.WriteString("\n")
}
// header writes a header, and a line for each of its opcodes. It sets err for
// an opcode that can't be read back as it is written.
func (b *builder) header(name string, ops []opcodeLine) {
b.line("<" + name + ">")
for _, op := range ops {
@@ -182,6 +193,7 @@ func (b *builder) header(name string, ops []opcodeLine) {
}
}
// define writes a #define, or sets err if it can't be read back as written.
func (b *builder) define(name, value string) {
if err := checkDefine(name, value); err != nil && b.err == nil {
b.err = err
@@ -189,7 +201,7 @@ func (b *builder) define(name, value string) {
b.line("#define " + name + " " + value)
}
// file returns what the builder has written as a file with the path.
// file returns what the builder has written, lexed, as a file with the path p.
func (b *builder) file(p string) *File {
f := &File{Path: p, Nodes: lex(b.text.String())}
return f
@@ -221,7 +233,7 @@ func (b *builder) curves(inst *Instrument) {
}
// samplePrefix returns the folder, with its slash, that every sample is in, or
// "" if there is none.
// "" if there is no folder that they all are.
func samplePrefix(regions []Region) string {
if len(regions) == 0 {
return ""
@@ -238,10 +250,10 @@ func samplePrefix(regions []Region) string {
return prefix + "/"
}
// hoist replaces values that at least min regions share with variables, and
// returns their definitions. The sample is the first opcode of a region and is
// left alone. The names end in a run of three letters, so that none is the
// start of another.
// hoist replaces the values that at least min regions share with variables, and
// returns the definitions of the variables. The sample, the first opcode of a
// region, and values with spaces or variables are left alone. The names end in
// a run of three letters, so that none is the start of another.
func hoist(regions [][]opcodeLine, min int) []opcodeLine {
type key struct{ name, value string }
counts := map[key]int{}
@@ -285,15 +297,15 @@ func hoist(regions [][]opcodeLine, min int) []opcodeLine {
return defines
}
// fieldLine is an opcode to write, with the field of [Region] that it sets.
// The field of an envelope's setting is Envelope.Delay and so on.
// fieldLine is an opcode to write, with the field of [Region] it is read into.
// The field for a setting of the envelope is named as Envelope.Delay is.
type fieldLine struct {
field string
opcodeLine
}
// regionOpcodes returns the opcodes that make a region, starting with its
// sample, with those that are the format's defaults left out.
// sample, leaving out those that would only set the format's defaults.
func regionOpcodes(r Region) []opcodeLine {
lines := regionLines(r, false)
out := make([]opcodeLine, len(lines))
@@ -303,8 +315,10 @@ func regionOpcodes(r Region) []opcodeLine {
return out
}
// regionLines returns the opcodes that make a region, starting with its sample.
// Those that are the format's defaults are left out unless all is set.
// regionLines returns the opcodes that make a region, starting with its sample,
// each with the field it is read into. The opcodes that would only set the
// format's defaults are left out unless all is set. An optional setting that
// the region doesn't have, such as a loop mode, has no opcode either way.
func regionLines(r Region, all bool) []fieldLine {
d := defaultRegion()
out := []fieldLine{{"Sample", opcodeLine{"sample", r.Sample}}}
@@ -424,8 +438,9 @@ func regionLines(r Region, all bool) []fieldLine {
}
// conditionOpcodes returns the opcodes that limit a source that isn't a
// numbered controller, and the number their values are the range's times. A
// controller has none, and is written as lohdcc and hihdcc.
// numbered controller, and the number that their values are the range's limits
// times. A controller has no such opcodes, so lo and hi are empty for it, and
// it is written as lohdcc and hihdcc.
func conditionOpcodes(c Condition) (scale float64, lo, hi string) {
for _, b := range controllerBounds {
if b.source == c.Source {
+7
View File
@@ -39,6 +39,9 @@ func instruments(t *testing.T) map[string]*Instrument {
}
}
// TestBuildRoundTrip checks that an instrument built into a document, written
// to files and read again, is the same instrument, for each way of laying the
// document out.
func TestBuildRoundTrip(t *testing.T) {
for name, inst := range instruments(t) {
for label, opts := range map[string]BuildOptions{
@@ -91,6 +94,8 @@ func rebuilt(t *testing.T, doc *Document) *Instrument {
return back.Flatten().Instrument()
}
// TestBuildLayout checks the text that Build writes for the plain, variable
// and split layouts.
func TestBuildLayout(t *testing.T) {
inst := parseText(t, "<region> sample=Dir/a.wav lokey=40\n<region> sample=Dir/b.wav lokey=40\n<region> sample=Dir/c.wav lokey=41\n")
doc, err := Build(inst)
@@ -120,6 +125,8 @@ func TestBuildLayout(t *testing.T) {
}
}
// TestWriteFilesPaths checks that WriteFiles writes the included files in the
// folder of the main file.
func TestWriteFilesPaths(t *testing.T) {
doc, err := Build(parseText(t, "<region> sample=a.wav\n"), BuildOptions{SplitFiles: true})
if err != nil {
+34 -30
View File
@@ -6,7 +6,7 @@ import (
"strings"
)
// Controllers above 127 that ARIA defines, which depend on the note: its
// The controllers above 127 that ARIA defines, which depend on the note: its
// velocity, its key, and whether it is held.
const (
extendedVelocityCC = 131
@@ -14,12 +14,12 @@ const (
extendedGateCC = 134
)
// maxControls is the most controllers an instrument has, one for each.
// maxControls is how many numbered controllers an instrument has, 0 to 127.
const maxControls = 128
// controls returns the controllers the instrument names with label_ccN, sets
// with set_ccN or set_hdccN, or has regions that use, by number, each with its
// starting value.
// controls returns the controllers that the instrument names with label_ccN,
// sets with set_ccN or set_hdccN, or has regions that use, in order of number,
// each with its starting value.
func (e evaluator) controls(control Opcodes, regions []Region) []Control {
labels := map[int]string{}
used := map[int]bool{}
@@ -57,8 +57,8 @@ func (e evaluator) controls(control Opcodes, regions []Region) []Control {
}
// keyswitchRange returns the keys that are keyswitches and the one that is down
// at the start, or nil if no region uses a keyswitch. Without sw_lokey and
// sw_hikey, they are the keys that the regions name.
// at the start, or nil if no region uses a keyswitch. The keys are those that
// sw_lokey and sw_hikey give, and the keys that the regions name.
func keyswitchRange(regions []Opcodes) *KeyswitchRange {
var r *KeyswitchRange
for _, ops := range regions {
@@ -96,17 +96,18 @@ func keyswitchRange(regions []Opcodes) *KeyswitchRange {
return r
}
// ccRE reads a controller number from the end of an opcode, such as the 64 of
// locc64.
// ccRE reads the name of an opcode that ends in a controller number, such as
// locc64, as the name without the number and then the number.
var ccRE = regexp.MustCompile(`^(.*?)(\d+)$`)
// defaultControllers are the controllers that start somewhere other than 0
// unless set_cc or set_hdcc say otherwise, as sfizz starts them: volume at
// 100, pan in the middle, and expression at full.
// defaultControllers are the controllers that start somewhere other than 0,
// unless set_cc or set_hdcc say otherwise, as sfizz starts them: volume at 100,
// pan in the middle, and expression at full.
var defaultControllers = map[int]float64{7: 100.0 / 127, 10: 0.5, 11: 1}
// controllerValues returns the starting values of the controllers, from 0 to
// 1: those that set_cc and set_hdcc give, then defaultControllers, then 0.
// controllerValues returns the starting values of the controllers, from 0 to 1.
// A controller takes the value that set_cc or set_hdcc gives it, or else its
// value in defaultControllers, or else 0.
func controllerValues(control Opcodes) map[int]float64 {
values := map[int]float64{}
for n, v := range defaultControllers {
@@ -132,11 +133,11 @@ func controllerValues(control Opcodes) map[int]float64 {
return values
}
// defaultKeyswitch returns the keyswitch that is active before any is
// pressed: the first sw_default, or failing that the first sw_last, or -1
// if the instrument has no keyswitches. Without an sw_default, SFZ players
// play no keyswitched region until a keyswitch is pressed; a host that can't
// press one can use the first articulation instead.
// defaultKeyswitch returns the keyswitch that is active before any is pressed:
// the first sw_default, or failing that the first sw_last, or -1 if the
// instrument has no keyswitches. Without an sw_default, SFZ players play no
// keyswitched region until a keyswitch is pressed. A host that can't press one
// can use the first articulation instead.
func defaultKeyswitch(regions []Opcodes) int {
for _, ops := range regions {
if n, ok := parseNote(ops["sw_default"]); ok {
@@ -151,7 +152,7 @@ func defaultKeyswitch(regions []Opcodes) int {
return -1
}
// keyShift is how far the <control> header's note_offset and octave_offset
// keyShift returns how far the <control> header's note_offset and octave_offset
// move a region's key numbers.
func keyShift(ops Opcodes) int {
shift := 0
@@ -164,14 +165,16 @@ func keyShift(ops Opcodes) int {
return shift
}
// hicc's high end includes the whole of value N, as a controller at 0.5 is
// 63.5 out of 127 and so within hicc63, as sfizz compares them. So the range
// is made to end just below value N + 1, unless N is the top.
// topEpsilon is how far below the next whole value the end of a hiccN range is
// put. The range includes the whole of value N, as a controller at 0.5 is 63.5
// out of 127 and so is within hicc63, as sfizz compares them. The range ends
// just below value N + 1, unless N is the top.
const topEpsilon = 1e-9
// controllerBounds are the Opcodes that limit a source that isn't a numbered
// controller to a range: the lowest and highest, the range they run over, and
// what they default to.
// controllerBounds are the opcodes that limit a source that isn't a numbered
// controller to a range. Each has the name of the source, the opcodes for its
// lowest and highest limits, the scale that their values are the range's limits
// times, and the range of the source, which the limits default to.
var controllerBounds = []struct {
source, low, high string
scale float64
@@ -183,9 +186,9 @@ var controllerBounds = []struct {
{SourcePolyAftertouch, "lopolyaft", "hipolyaft", 127, 0, 1},
}
// conditions returns the ranges a region's locc, hicc, lohdcc and hihdcc, and
// its channel, pitch bend and aftertouch Opcodes limit it to. Controllers
// above 127, which belong to the note, are left out.
// conditions returns the ranges that a region's locc, hicc, lohdcc and hihdcc
// opcodes, and its channel, pitch bend and aftertouch opcodes, limit it to.
// Controllers above 127, which belong to the note, are left out.
func conditions(ops Opcodes) []Condition {
ranges := map[int]*Condition{}
for name, v := range ops {
@@ -243,7 +246,8 @@ func conditions(ops Opcodes) []Condition {
return out
}
// keyswitch returns the keyswitches a region needs, or nil if it has none.
// keyswitch returns the keyswitches that a region needs, with shift added to
// their keys, or nil if it has none.
func keyswitch(ops Opcodes, shift int) *Keyswitch {
var k Keyswitch
found := false
+37 -25
View File
@@ -1,12 +1,15 @@
// Package sfz reads, validates and writes SFZ instruments: text files that
// map samples to keys, velocities and playback settings. It handles SFZ v1 and
// v2 with the ARIA extensions as data. It doesn't play or load samples.
// Package sfz reads, validates, edits and writes SFZ instruments: text files
// that map samples to keys, velocities and playback settings. It handles SFZ v1
// and v2 with the ARIA extensions as data. It doesn't play instruments or load
// samples.
//
// A [Document] keeps a file exactly as written, including comments, spacing,
// unknown opcodes, and #define and #include directives, so that writing an
// unchanged document gives the same text back. [Document.Flatten] resolves
// directives and header inheritance into regions, and [Flat.Instrument] reads
// those into a typed model.
// unknown opcodes, and #define and #include directives, so that a document
// that hasn't been edited is written as the text it was read from.
// [Document.Flatten] resolves directives and header inheritance into regions,
// and [Flat.Instrument] reads those into a typed model. [Instrument.Apply]
// writes a change to a typed region back to the document as changes to the
// region's own opcodes.
package sfz
import (
@@ -16,14 +19,16 @@ import (
"strings"
)
// Errors that Parse and Flatten wrap.
// The errors that the package returns, directly or wrapped.
var (
// ErrInvalid is returned for text that can't be read as an instrument.
// ErrInvalid is returned for text that can't be read as an instrument, and
// for an edit or an output that can't be written as SFZ.
ErrInvalid = errors.New("invalid SFZ")
// ErrIncludeLoop is returned when a file includes itself, directly or not.
// ErrIncludeLoop is returned when a file includes itself, directly or
// through the files it includes.
ErrIncludeLoop = errors.New("include loop")
// ErrUnresolved is returned, with [IncludesFail], for an include that
// can't be read.
// ErrUnresolved is returned, with [IncludesFail], for an include that can't
// be read.
ErrUnresolved = errors.New("unresolved include")
)
@@ -68,17 +73,18 @@ func (k NodeKind) String() string {
return "text"
}
// Node is one piece of a file. The raw text of a file's nodes, in order, is
// the file's text.
// Node is one piece of a file. The raw text of a file's nodes, in order, is the
// file's text.
type Node struct {
// Kind is what the node holds, and so which of the other fields are set.
Kind NodeKind
// Raw is the node's text as written.
Raw string
// Name is a header's name without its brackets, as written, an opcode's
// name, or a define's variable name with its $.
// name, or a define's variable name with its $. Other nodes have none.
Name string
// Value is an opcode's or a define's value without surrounding
// whitespace, or an include's path as written.
// Value is an opcode's or a define's value without surrounding whitespace,
// or an include's path as written.
Value string
// Resolved is an include's path with its variables substituted, with
// forward slashes, relative to the folder of the main file.
@@ -86,20 +92,23 @@ type Node struct {
// File is the file an include reads, or nil if it wasn't read.
File *File
// line and col are where the node starts, from 1, with col in bytes, as of
// the last time the file's positions were worked out (see [File.Position]).
// the last time its file's positions were worked out (see [File.Position]).
line, col int
// idx is where the node was in its file's nodes the last time it was
// looked for, which stays close to where it is.
// idx is where the node was in its file's nodes the last time it was looked
// for. Edits move a node only a short way from there.
idx int
}
// File is one file of a document: the main file or an included one.
type File struct {
// Path is the file's path relative to the folder of the main file, with
// forward slashes. For a file read with [Parse] and no name, it is empty.
// forward slashes. For the main file of a document read with [Parse], which
// has no name, it is empty.
Path string
// Nodes are the file's nodes, in order.
Nodes []*Node
// dirty is whether edits have left the nodes' lines and columns out of date.
// dirty is whether edits have moved nodes since their lines and columns were
// last worked out.
dirty bool
}
@@ -117,7 +126,7 @@ func (f *File) String() string {
type Document struct {
// Root is the main file.
Root *File
// problems are those found while parsing.
// problems are the problems found while parsing.
problems []Problem
}
@@ -136,7 +145,8 @@ func (d *Document) WriteTo(w io.Writer) (int64, error) {
func (d *Document) String() string { return d.Root.String() }
// Files returns the main file and the files it includes, in the order they are
// read, each time they are included.
// read. A file that is included more than once is returned once for each time,
// as each is read with the variables defined at that point.
func (d *Document) Files() []*File {
var out []*File
var walk func(f *File)
@@ -176,15 +186,17 @@ func (s Severity) String() string {
return "error"
}
// Problem is something found in a document.
// Problem is something found in a document that its writer may want to fix.
type Problem struct {
// File is the path of the file, as in [File.Path].
File string
// Line and Col are where the problem is, from 1.
Line, Col int
// Severity is how serious the problem is.
Severity Severity
// Code is a short stable name for the kind of problem, such as
// "include.unresolved".
Code string
// Msg describes the problem for a person to read.
Msg string
}
+55 -50
View File
@@ -6,9 +6,9 @@ import (
"strings"
)
// Header is a header of a file, with the opcodes that follow it up to the
// next header in the same file. Opcodes that an #include after it brings in
// belong to the included file's own headers.
// Header is a header of a file, with the opcodes that follow it in the same
// file up to the next header. The nodes of a file that an #include in that
// range reads are the nodes of that file, and not of the header.
type Header struct {
// File is the file the header is in.
File *File
@@ -16,12 +16,12 @@ type Header struct {
Node *Node
}
// Name returns the header's name without brackets, as written.
// Name returns the header's name without its brackets, as written.
func (h *Header) Name() string { return h.Node.Name }
// indexOf returns where a node is in the file, or -1. A node remembers where it
// was, which stays close to where it is after edits, so the search starts
// there.
// indexOf returns where a node is in the file's nodes, or -1 if it isn't. A
// node remembers where it was, and edits move it only a short way from there,
// so the search starts there and goes outwards.
func (f *File) indexOf(n *Node) int {
at := func(i int) bool { return i >= 0 && i < len(f.Nodes) && f.Nodes[i] == n }
for d := 0; ; d++ {
@@ -39,8 +39,8 @@ func (f *File) indexOf(n *Node) int {
}
}
// span returns the range of the file's nodes after the header's own, up to the
// next header.
// span returns the range of the file's nodes that follow the header's own, up
// to the next header or the end of the file.
func (h *Header) span() (start, end int) {
start = h.File.indexOf(h.Node) + 1
end = start
@@ -62,8 +62,8 @@ func (h *Header) Opcodes() []*Node {
return out
}
// Get returns the header's last node for an opcode, which is the one that
// takes effect.
// Get returns the header's last node for an opcode, which is the one that takes
// effect, and whether it has one.
func (h *Header) Get(name string) (*Node, bool) {
start, end := h.span()
for i := end - 1; i >= start; i-- {
@@ -74,9 +74,9 @@ func (h *Header) Get(name string) (*Node, bool) {
return nil, false
}
// checkOpcode returns an error if name=value wouldn't be read back as one
// opcode with that value, as when the value holds a line break, a comment, or
// another opcode.
// checkOpcode returns an error wrapping [ErrInvalid] if name=value wouldn't be
// read back as one opcode with that value, as when the value holds a line
// break, a comment or another opcode.
func checkOpcode(name, value string) error {
text := name + "=" + value
nodes := lex(text)
@@ -87,8 +87,8 @@ func checkOpcode(name, value string) error {
return fmt.Errorf("%w: %s=%q can't be written as one opcode", ErrInvalid, name, value)
}
// checkDefine returns an error if the text of a #define of name with value
// wouldn't be read back as that directive.
// checkDefine returns an error wrapping [ErrInvalid] if a #define of the
// variable name with the value wouldn't be read back as that directive.
func checkDefine(name, value string) error {
nodes := lex("#define " + name + " " + value)
if len(nodes) > 0 && nodes[0].Kind == KindDefine && nodes[0].Name == name && nodes[0].Value == strings.TrimSpace(value) && onlySpace(nodes[1:]) {
@@ -107,11 +107,12 @@ func onlySpace(nodes []*Node) bool {
return true
}
// Set gives the opcode a value, or returns an error wrapping [ErrInvalid], and
// changes nothing, if the value can't be written as the value of one opcode. An
// opcode the header already has keeps its place and the text around it, and
// takes the value as written even if it was a variable. A new one goes after the
// header's last opcode, and its comment, laid out as that opcode is.
// Set gives the opcode a value. It returns an error wrapping [ErrInvalid], and
// changes nothing, if the name and value can't be written as one opcode. An
// opcode that the header has keeps its place and the text around it, and takes
// the value as written, even if the value was a variable. A new opcode goes
// after the header's last, and after any comment on that opcode's line, laid
// out as that opcode is.
func (h *Header) Set(name, value string) error {
value = strings.TrimSpace(value)
if err := checkOpcode(name, value); err != nil {
@@ -134,8 +135,8 @@ func (h *Header) Set(name, value string) error {
at := start
var sep string
if last < 0 {
// With no opcode to follow, the new one goes after the header, on its own
// line if the header is.
// With no opcode to follow, the new one goes after the header, on a line
// of its own if the header has one.
sep = " "
if start < len(h.File.Nodes) && h.File.Nodes[start].Kind == KindSpace && strings.Contains(h.File.Nodes[start].Raw, "\n") {
sep = h.File.Nodes[start].Raw
@@ -150,8 +151,9 @@ func (h *Header) Set(name, value string) error {
} else if h.File.hasLineBreak() {
sep = "\n"
}
// The new opcode goes after what ends the last one's line. A line comment
// runs to the end of the line, so the opcode then needs a line of its own.
// The new opcode goes after the comments that end the last one's line. A
// line comment runs to the end of its line, so the opcode then goes on a
// line of its own. A block comment that never ends can't be passed.
for {
k := at
for k < end && h.File.Nodes[k].Kind == KindSpace && !strings.Contains(h.File.Nodes[k].Raw, "\n") {
@@ -169,7 +171,7 @@ func (h *Header) Set(name, value string) error {
inserted := append([]*Node{{Kind: KindSpace, Raw: sep}}, nodes...)
// A value runs to the end of its line unless a header, opcode, comment or
// directive ends it, so text after the new opcode on its line would become
// part of the value. It goes on a line of its own.
// part of the value. A line break after the opcode keeps it out.
k := at
for k < len(h.File.Nodes) && h.File.Nodes[k].Kind == KindSpace && !strings.Contains(h.File.Nodes[k].Raw, "\n") {
k++
@@ -181,13 +183,13 @@ func (h *Header) Set(name, value string) error {
return nil
}
// unterminated reports whether a node is a block comment that never ends, which
// unterminated reports whether n is a block comment that never ends, and so
// takes in all that follows it.
func unterminated(n *Node) bool {
return n.Kind == KindComment && strings.HasPrefix(n.Raw, "/*") && (len(n.Raw) < 4 || !strings.HasSuffix(n.Raw, "*/"))
}
// hasLineBreak reports whether the file has a line break.
// hasLineBreak reports whether the file has a line break anywhere.
func (f *File) hasLineBreak() bool {
for _, n := range f.Nodes {
if n.Kind == KindSpace && strings.Contains(n.Raw, "\n") {
@@ -197,8 +199,9 @@ func (f *File) hasLineBreak() bool {
return false
}
// Delete removes the opcode, every time the header has it, with the space
// before it.
// Delete removes the opcode, each time the header has it, with the space that
// separated it from what came before, and leaves the line breaks around other
// text as they are.
func (h *Header) Delete(name string) {
for {
n, ok := h.Get(name)
@@ -214,9 +217,9 @@ func (h *Header) Delete(name string) {
case isSpace(i-1, false):
from = i - 1
case isSpace(i-1, true):
// The line break before the opcode goes with it only if what follows
// ends the line, as the opcode's own line then goes. Otherwise the
// text after it stays on the line, without the space that separated it.
// The line break before the opcode goes with it only if the opcode ends
// its line, so that its whole line goes. Otherwise the text after it
// keeps its line, and the space that separated it from the opcode goes.
if i+1 >= len(h.File.Nodes) || isSpace(i+1, true) || h.File.Nodes[i+1].Kind == KindHeader {
from = i - 1
} else if isSpace(i+1, false) {
@@ -228,7 +231,7 @@ func (h *Header) Delete(name string) {
}
}
// insert adds nodes at an index.
// insert adds nodes to the file at the index.
func (f *File) insert(at int, nodes ...*Node) {
f.Nodes = slices.Insert(f.Nodes, at, nodes...)
for i, n := range nodes {
@@ -237,9 +240,9 @@ func (f *File) insert(at int, nodes ...*Node) {
f.dirty = true
}
// Position returns where a node of the file starts, with the line and the
// column, in bytes, from 1. Edits move what follows them, which is worked out
// when this is next called.
// Position returns the line and the column, both from 1, where a node of the
// file starts. The column is in bytes. Edits move the nodes after them, which
// Position works out when it is next called, and not at each edit.
func (f *File) Position(n *Node) (line, col int) {
if f.dirty {
f.reposition()
@@ -247,8 +250,8 @@ func (f *File) Position(n *Node) (line, col int) {
return n.line, n.col
}
// reposition sets the line, column and index of each node from the text
// before it.
// reposition sets the line, column and index of each node from the text before
// it.
func (f *File) reposition() {
line, col := 1, 1
for i, n := range f.Nodes {
@@ -266,7 +269,7 @@ func (f *File) reposition() {
}
// Headers returns the headers of every file of the document, in the order the
// files are read.
// files are read, as [Document.Files] returns them.
func (d *Document) Headers() []*Header {
var out []*Header
for _, f := range d.Files() {
@@ -279,10 +282,10 @@ func (d *Document) Headers() []*Header {
return out
}
// AddHeader adds an empty header on a line of its own after another header and
// its opcodes, or at the end of the main file if after is nil, and returns it.
// It returns an error wrapping [ErrInvalid] if the name isn't one a header can
// have.
// AddHeader adds an empty header, on a line of its own, after the header after
// and its opcodes, or at the end of the main file if after is nil, and returns
// it. It returns an error wrapping [ErrInvalid] if name isn't one that a header
// can have, or if the header would fall inside a block comment that never ends.
func (d *Document) AddHeader(name string, after *Header) (*Header, error) {
if m := headerRE.FindString("<" + name + ">"); m != "<"+name+">" {
return nil, fmt.Errorf("%w: <%s> isn't a header", ErrInvalid, name)
@@ -294,7 +297,8 @@ func (d *Document) AddHeader(name string, after *Header) (*Header, error) {
_, at = after.span()
}
if at > 0 {
// A header after a block comment that never ends would be inside it.
// A header after a block comment that never ends would be inside the
// comment.
if c := f.Nodes[at-1]; unterminated(c) {
return nil, fmt.Errorf("%w: a comment that doesn't end is where <%s> would go", ErrInvalid, name)
}
@@ -315,6 +319,7 @@ func (d *Document) Defines() []*Node { return d.nodes(KindDefine) }
// Includes returns the #include nodes of every file, in order.
func (d *Document) Includes() []*Node { return d.nodes(KindInclude) }
// nodes returns the nodes of a kind in every file, in order.
func (d *Document) nodes(kind NodeKind) []*Node {
var out []*Node
for _, f := range d.Files() {
@@ -327,12 +332,12 @@ func (d *Document) nodes(kind NodeKind) []*Node {
return out
}
// SetDefine gives a variable a new value, by changing its first #define, so
// that each opcode that uses it changes with it. Setting an opcode that uses
// the variable with [Header.Set] replaces the variable there instead. A
// SetDefine gives a variable a new value by changing its first #define, so
// that each opcode that uses the variable changes with it. [Header.Set] on an
// opcode that uses the variable replaces the variable in that opcode instead. A
// variable with no #define gets one at the start of the main file. The name
// includes its $. It returns an error wrapping [ErrInvalid], and changes
// nothing, if the name or value can't be written as a #define.
// includes its $. SetDefine returns an error wrapping [ErrInvalid], and changes
// nothing, if the name and value can't be written as a #define.
func (d *Document) SetDefine(name, value string) error {
value = strings.TrimSpace(value)
if err := checkDefine(name, value); err != nil {
+14
View File
@@ -8,6 +8,8 @@ import (
"testing"
)
// mustParse parses text, reading its includes from the map m of paths to
// contents, and fails the test if it can't.
func mustParse(t *testing.T, text string, m map[string]string) *Document {
t.Helper()
if m == nil {
@@ -28,6 +30,8 @@ func set(t *testing.T, h *Header, name, value string) {
}
}
// TestSetKeepsLayout checks that Set changes an opcode in place, adds a new
// one laid out like the last, and that what is written reads back.
func TestSetKeepsLayout(t *testing.T) {
doc := mustParse(t, "// piano\n<group>\n\tvolume=-1 // quiet\n\tpan=5\n<region> sample=a.wav\n", nil)
hs := doc.Headers()
@@ -54,6 +58,8 @@ func TestSetKeepsLayout(t *testing.T) {
}
}
// TestDelete checks that Delete removes every copy of an opcode, and does
// nothing for one that isn't there.
func TestDelete(t *testing.T) {
doc := mustParse(t, "<region>\n sample=a.wav\n lokey=1\n hikey=2\n lokey=3\n", nil)
h := doc.Headers()[0]
@@ -64,6 +70,8 @@ func TestDelete(t *testing.T) {
}
}
// TestAddHeader checks that AddHeader puts a header after another header's
// opcodes or at the end of the file, and that Set fills it.
func TestAddHeader(t *testing.T) {
doc := mustParse(t, "<group> volume=1\n<region> sample=a.wav", nil)
hs := doc.Headers()
@@ -127,6 +135,8 @@ func TestEditIncluded(t *testing.T) {
}
}
// TestSetKeepsComments checks where Set puts a new opcode among the comments,
// directives and text that follow the last one.
func TestSetKeepsComments(t *testing.T) {
for _, tc := range []struct{ text, want string }{
{"<region>\n sample=a.wav // the sample\n", "<region>\n sample=a.wav // the sample\n lokey=1\n"},
@@ -144,6 +154,8 @@ func TestSetKeepsComments(t *testing.T) {
}
}
// TestSetRefusesBadValues checks that Set, SetDefine and AddHeader refuse
// what can't be written, and change nothing.
func TestSetRefusesBadValues(t *testing.T) {
text := "<region> sample=a.wav\n"
for _, value := range []string{"1\n<region>", "1 // c", "1 /* c", "1 hikey=2", "<group>", "1\r\n2"} {
@@ -177,6 +189,8 @@ func TestSetRefusesBadValues(t *testing.T) {
}
}
// TestDeleteKeepsLines checks that Delete keeps the line breaks and comments
// that aren't the opcode's.
func TestDeleteKeepsLines(t *testing.T) {
for _, tc := range []struct{ text, want string }{
{"<region>\n a=1\n b=2\n a=3 // x\n", "<region>\n b=2\n // x\n"},
+49 -25
View File
@@ -2,10 +2,11 @@ package sfz
import "strings"
// Opcodes are the opcodes set at one point of an instrument, by name.
// Opcodes are the opcodes set at one point of an instrument, by name, with
// their values as written and any variables in them replaced.
type Opcodes map[string]string
// with returns the opcodes of o with those of more on top.
// with returns a copy of the opcodes of o, with those of more set over them.
func (o Opcodes) with(more Opcodes) Opcodes {
out := make(Opcodes, len(o)+len(more))
for k, v := range o {
@@ -19,14 +20,16 @@ func (o Opcodes) with(more Opcodes) Opcodes {
// FlatRegion is a <region> with the opcodes it inherits.
type FlatRegion struct {
// Opcodes are the region's own and those of the headers above it, and the
// <control> settings that apply to it.
// Opcodes are the region's own opcodes, those of the headers above it, and
// the <control> settings that apply to it. They are Inherited with Own set
// over them.
Opcodes Opcodes
// File and Line are where the <region> header is.
// File is the path of the file that has the <region> header, as in
// [File.Path], and Line is the line the header is on.
File string
Line int
// Own holds the opcodes of the region's own header, and Inherited those that
// it inherits, which Opcodes is the two of together.
// Own are the opcodes that follow the region's header, and Inherited are
// those that the region takes from the headers above it.
Own, Inherited Opcodes
// Header is the <region> header, or nil if a variable made it, so that it
// has no node of its own.
@@ -34,21 +37,25 @@ type FlatRegion struct {
}
// Flat is an instrument with its directives expanded and its headers resolved.
// It has no comments and no layout.
type Flat struct {
// Control holds the opcodes of the <control> headers.
// Control holds the opcodes of the <control> headers, the later setting of
// an opcode replacing the earlier.
Control Opcodes
// Curves holds the opcodes of each <curve> header.
// Curves holds the opcodes of each <curve> header, in order.
Curves []Opcodes
// Regions are the regions, in order.
// Regions are the <region> headers, with what they inherit, in order.
Regions []FlatRegion
// Headers counts the headers that aren't <control>, <curve>, <global>,
// <master>, <group> or <region>, by name.
// Headers counts, by lowercase name, the headers that aren't <control>,
// <curve>, <global>, <master>, <group> or <region>.
Headers map[string]int
}
// level is how far down the header hierarchy a header is.
// level is how far down the header hierarchy a header is, where the opcodes of
// each level are set over those of the levels before it.
type level int
// The levels of the headers that regions inherit from.
const (
levelGlobal level = iota
levelMaster
@@ -65,33 +72,38 @@ var headerLevels = map[string]level{
}
// controlSettings are the <control> opcodes that apply to the regions after
// them.
// them, as opposed to those that name controllers or set their values.
var controlSettings = []string{"default_path", "note_offset", "octave_offset"}
// target is where the opcodes after a header go.
type target struct {
// ops are the opcodes set so far.
ops Opcodes
// region is whether the header is a <region>, which becomes a region when
// the next header starts or the text ends, and line is where it is.
// the next header starts or the text ends.
region bool
// line, file and header are where the <region> header is, and its node, if a
// variable didn't make it.
line int
file string
header *Header
}
// flattener reads a document's nodes in order.
// flattener is the [visitor] that builds a [Flat] from a document's nodes.
type flattener struct {
flat *Flat
// levels are the opcodes set at each level.
// levels are the opcodes set at each level by the headers read so far.
levels [levelRegion + 1]Opcodes
// into is where the opcodes that come next go, or nil before any header.
into *target
}
// Flatten returns the instrument with each #include read where it stands,
// each variable replaced by its value as of where it is used, and each
// region given the opcodes of the <global>, <master> and <group> above it. A
// new header clears the ones below it, so a <group> starts with no group
// opcodes. Comments are dropped. An include that wasn't read is skipped.
// Flatten returns the instrument with each #include read where it stands, each
// variable replaced by its value as of where it is used, and each region given
// the opcodes of the <global>, <master> and <group> above it. A header clears
// the opcodes of the levels below it, so a <group> starts with no group
// 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{}}}
for i := range f.levels {
@@ -102,14 +114,22 @@ func (d *Document) Flatten() *Flat {
return f.flat
}
// define does nothing, as [walk] sets variables itself.
func (f *flattener) define(*File, *Node) {}
// include does nothing, as [walk] reads included files itself.
func (f *flattener) include(*File, *Node) {}
// variables does nothing, as [walk] replaces variables itself.
func (f *flattener) variables(*File, *Node) {}
// text does nothing, as a flattened instrument leaves out text that isn't SFZ.
func (f *flattener) text(*File, *Node, string) {}
// header starts the header, which is on the line of n even if a variable made
// it.
func (f *flattener) header(file *File, n *Node, name string, variable bool) {
// A header that a variable made has no node of its own, so it takes the line
// of the node that made it.
// A header that a variable made has no node of its own to edit.
line, _ := file.Position(n)
var own *Header
if !variable {
@@ -118,10 +138,11 @@ func (f *flattener) header(file *File, n *Node, name string, variable bool) {
f.startHeader(name, line, file, own)
}
// opcode sets the opcode in the header being read.
func (f *flattener) opcode(_ *File, _ *Node, name, value string, _ bool) { f.setOpcode(name, value) }
// closeRegion adds the region being read, if any. A region takes the <control>
// settings made before it, which later <control> headers don't change.
// settings made before it, and later <control> headers don't change them.
func (f *flattener) closeRegion() {
if f.into == nil || !f.into.region {
return
@@ -139,6 +160,8 @@ func (f *flattener) closeRegion() {
})
}
// startHeader ends the header being read and starts the one called header,
// which is on a line of file, and is own if it has a node of its own.
func (f *flattener) startHeader(header string, line int, file *File, own *Header) {
f.closeRegion()
name := strings.ToLower(header)
@@ -169,6 +192,7 @@ func (f *flattener) startHeader(header string, line int, file *File, own *Header
}
}
// setOpcode sets an opcode in the header being read.
func (f *flattener) setOpcode(name, value string) {
if f.into == nil {
// Opcodes before any header apply to every region.
+39 -28
View File
@@ -10,7 +10,10 @@ import (
"strings"
)
// Instrument reads the flattened instrument into the typed model.
// Instrument reads the flattened instrument into the typed model, with each
// setting that a controller moves taken at the controller's starting value.
// 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{}}
for h, n := range f.Headers {
@@ -41,15 +44,18 @@ func (f *Flat) Instrument() *Instrument {
return inst
}
// evaluator turns regions' Opcodes into regions.
// evaluator turns the opcodes of regions into typed regions.
type evaluator struct {
// cc are the starting values of the controllers, from 0 to 1.
cc map[int]float64
// curves are the curves that modulations can use, by index.
curves map[int]curve
// stops are the points of the custom curves, by index.
stops map[int][]CurveStop
}
// region returns the region the opcodes describe, or why it is skipped.
// region returns the region that the opcodes describe, or the reason, one of
// the Skipped constants, that there is none.
func (e evaluator) region(ops Opcodes) (Region, string) {
sample := strings.TrimSpace(ops["sample"])
switch {
@@ -122,16 +128,18 @@ func (e evaluator) region(ops Opcodes) (Region, string) {
}
return e.cc[n]
}
// A setting that the controllers move while a note plays has only what the
// note itself moves it by here, which is the controllers above 127, and the
// others are left to its modulations. The rest are taken at the starting
// controller values.
// own is the value of a setting that the controllers move while a note
// plays, with only what the note itself moves it by, which is the
// controllers above 127. The other controllers are left to the region's
// modulations.
own := func(target string, base float64) float64 {
if v, ok := parseNumber(ops[target]); ok {
base = v
}
return base + e.modulation(ops, target, cc, extendedOnly)
}
// value is the value of a setting that the controllers don't move while a
// note plays, with every controller taken at its starting value.
value := func(target string, base float64) float64 {
if v, ok := parseNumber(ops[target]); ok {
base = v
@@ -225,12 +233,12 @@ func (e evaluator) region(ops Opcodes) (Region, string) {
return r, ""
}
// velocityCurveRE reads the velocity of an amp_velcurve_N opcode.
// velocityCurveRE reads the velocity from the name of an amp_velcurve_N opcode.
var velocityCurveRE = regexp.MustCompile(`^amp_velcurve_(\d{1,3})$`)
// velocityCurve returns the points of a region's amp_velcurve_N Opcodes, with
// the ends the curve doesn't set at no level for velocity 0 and the full
// level for 127, or nil if the region sets none.
// velocityCurve returns the points of a region's amp_velcurve_N opcodes, in
// order. A curve that doesn't set the ends starts at no level for velocity 0
// and ends at the full level for 127. It returns nil if the region sets none.
func velocityCurve(ops Opcodes) []CurvePoint {
points := map[int]float64{}
for name, v := range ops {
@@ -260,10 +268,10 @@ func velocityCurve(ops Opcodes) []CurvePoint {
return out
}
// crossfade returns the crossfade of a region's xfin_ and xfout_ Opcodes over
// keys, or over velocities for which is "vel", or nil if it sets none. A
// fade in that isn't given starts and ends at 0, and a fade out at 127.
// shift moves keys, as the <control> header's offsets do.
// crossfade returns the crossfade of a region's xfin_ and xfout_ opcodes over
// keys, or over velocities if which is "vel". It returns nil if the region sets
// none. A fade in that isn't given starts and ends at 0, and a fade out starts
// and ends at 127. The shift moves keys, as the <control> header's offsets do.
func crossfade(ops Opcodes, which string, shift int) *Crossfade {
read := func(name string, fallback int) (int, bool) {
v, ok := ops[name]
@@ -298,8 +306,8 @@ func crossfade(ops Opcodes, which string, shift int) *Crossfade {
return c
}
// voiceLimit reads a number of voices, which is at least 1, or nil if v isn't
// one.
// voiceLimit reads a number of voices, which is at least 1. It returns nil if
// v isn't one.
func voiceLimit(v string) *int {
n, ok := parseNumber(v)
if !ok || n < 1 {
@@ -312,7 +320,7 @@ func voiceLimit(v string) *int {
// minVolume is the quietest a region plays, in dB, which stands for silence.
const minVolume = -144
// number returns the number an opcode sets, or nil if it doesn't set one.
// number returns the number that an opcode sets, or nil if it doesn't set one.
func number(ops Opcodes, name string) *float64 {
if v, ok := parseNumber(ops[name]); ok {
return &v
@@ -320,16 +328,18 @@ func number(ops Opcodes, name string) *float64 {
return nil
}
// ptr returns a pointer to a copy of v.
func ptr[T any](v T) *T { return &v }
// samplePath joins a region's default_path and sample into a clean relative
// path with forward slashes.
// samplePath joins a region's default_path and sample into a clean path with
// forward slashes. The path is relative unless the text makes it absolute.
func samplePath(defaultPath, sample string) string {
p := strings.ReplaceAll(strings.TrimSpace(defaultPath)+sample, `\`, "/")
return strings.TrimPrefix(path.Clean(p), "./")
}
// firstOf returns the value of the first of the Opcodes that is set.
// firstOf returns the value of the first of the named opcodes that is set, or
// an empty string if none is.
func firstOf(ops Opcodes, names ...string) string {
for _, n := range names {
if v, ok := ops[n]; ok {
@@ -339,7 +349,7 @@ func firstOf(ops Opcodes, names ...string) string {
return ""
}
// frames reads a sample position in frames, or returns nil if v isn't one.
// frames reads a sample position in frames. It returns nil if v isn't one.
func frames(v string) *int64 {
n, ok := parseNumber(v)
if !ok || n < 0 {
@@ -349,12 +359,13 @@ func frames(v string) *int64 {
return &f
}
// clamp returns v, or the nearest of lo and hi if v is outside them.
func clamp(v, lo, hi float64) float64 {
return math.Min(hi, math.Max(lo, v))
}
// handledNames are the opcodes the typed model reads, or uses to choose
// regions.
// handledNames are the opcodes that the typed model reads, or uses to choose
// regions, and so doesn't count as unread.
var handledNames = map[string]bool{
"sample": true, "default_path": true, "note_offset": true, "octave_offset": true,
"key": true, "lokey": true, "hikey": true, "pitch_keycenter": true, "lovel": true, "hivel": true,
@@ -374,15 +385,15 @@ var handledNames = map[string]bool{
"lochan": true, "hichan": true, "lobend": true, "hibend": true, "lochanaft": true, "hichanaft": true, "lopolyaft": true, "hipolyaft": true,
}
// modulatedTargets are the opcodes whose controller modulation the typed model
// reads.
// modulatedTargets are the opcodes whose modulation by controllers the typed
// model reads.
var modulatedTargets = []string{
"pitch_keytrack", "tune", "pitch", "volume", "gain", "amplitude", "pan", "width", "offset", "amp_veltrack",
"ampeg_delay", "ampeg_attack", "ampeg_hold", "ampeg_decay", "ampeg_sustain", "ampeg_release", "rt_decay",
}
// handledRE matches the opcodes the typed model reads that carry a controller
// number or only name things.
// handledRE matches the opcodes that the typed model reads and that carry a
// controller number, or only name something.
var handledRE = regexp.MustCompile(`^(?:(?:lo|hi)(?:hd)?cc\d+|set_(?:hd)?cc\d+|label_cc\d+|amp_velcurve_\d+|[a-z_]*_label)$`)
// handled reports whether the typed model reads an opcode.
+22 -4
View File
@@ -20,7 +20,8 @@ import (
"gopkg.in/yaml.v3"
)
// entry is an opcode as it goes into the registry.
// entry is an opcode as it goes into the registry, with the fields of
// OpcodeInfo that the data gives it.
type entry struct {
name string
aliases []string
@@ -35,18 +36,21 @@ type entry struct {
description string
}
// notes are the integer opcodes that also take a note name.
// notes matches the names of the integer opcodes that also take a note name.
var notes = regexp.MustCompile(`^(?:key|(?:lo|hi)key|pitch_keycenter|sw_(?:lokey|hikey|last|previous|down|up|default)|xf(?:in|out)_(?:lo|hi)key|(?:lo|hi)_?key)$`)
// tags matches an HTML tag.
var tags = regexp.MustCompile(`<[^>]*>`)
// text turns the data's HTML snippets into plain text.
// text turns one of the data's HTML snippets into plain text on one line. It
// returns an empty string for a value that isn't text.
func text(v any) string {
s, _ := v.(string)
s = html.UnescapeString(tags.ReplaceAllString(s, ""))
return strings.Join(strings.Fields(s), " ")
}
// str returns a value of the data as text, or an empty string if there is none.
func str(v any) string {
if v == nil {
return ""
@@ -54,6 +58,7 @@ func str(v any) string {
return fmt.Sprint(v)
}
// number returns a number of the data, or nil if the value isn't one.
func number(v any) *float64 {
switch n := v.(type) {
case int:
@@ -65,23 +70,28 @@ func number(v any) *float64 {
return nil
}
// asMap returns v as a map, or nil if it isn't one.
func asMap(v any) map[string]any {
m, _ := v.(map[string]any)
return m
}
// asList returns v as a list, or nil if it isn't one.
func asList(v any) []any {
l, _ := v.([]any)
return l
}
// generator collects the opcodes of the data.
type generator struct {
// entries are the opcodes read so far, in the order they are listed.
entries []*entry
byName map[string]*entry
}
// add reads an opcode of the data, and its aliases and modulations, into
// entries. inherit is the opcode whose value an opcode without one takes.
// entries, and returns it, or nil if the data's entry isn't an opcode. inherit
// is the opcode whose value an opcode without one takes, or nil.
func (g *generator) add(x map[string]any, category string, inherit *entry) *entry {
name := str(x["name"])
if name == "" || x["macro"] == true {
@@ -173,6 +183,9 @@ func (g *generator) modulations(x map[string]any, e *entry, category string, par
}
}
// walk reads the opcodes under a part of the data's tree of categories into
// entries. The category of an opcode is the names of the categories it is under,
// joined with a slash; category is those of the parts above o.
func (g *generator) walk(o any, category string) {
switch v := o.(type) {
case map[string]any:
@@ -206,8 +219,11 @@ func (g *generator) walk(o any, category string) {
}
}
// quote returns s as a Go string literal.
func quote(s string) string { return strconv.Quote(s) }
// fl returns the Go expression for an optional number: nil, or a pointer made
// with ptr.
func fl(p *float64) string {
if p == nil {
return "nil"
@@ -215,6 +231,7 @@ func fl(p *float64) string {
return "ptr(float64(" + strconv.FormatFloat(*p, 'g', -1, 64) + "))"
}
// main reads the syntax data and writes the registry's Go source.
func main() {
in := flag.String("in", "syntax.yml", "the syntax data")
out := flag.String("out", "registry_data.go", "the Go file to write")
@@ -272,6 +289,7 @@ func main() {
log.Printf("wrote %d opcodes", count)
}
// strs returns the Go expression for a list of strings.
func strs(s []string) string {
if len(s) == 0 {
return "nil"
+20 -9
View File
@@ -22,25 +22,30 @@ var (
breakRE = regexp.MustCompile(`<[A-Za-z_]+>|\s[A-Za-z0-9_$]+=|//|/\*|\s#(?:define|include)\b|\n`)
)
// byteOrderMark is the UTF-8 mark some editors put at the start of a file. It
// is read as space.
// byteOrderMark is the UTF-8 mark that some editors put at the start of a file.
// The lexer reads it as space.
const byteOrderMark = "\ufeff"
// atLineStart reports whether a directive may start at offset i: at the start
// of the text, after the byte order mark, or after whitespace.
// atLineStart reports whether a directive may start at offset i of src, which
// is so at the start of the text, after the byte order mark, and after
// whitespace.
func atLineStart(src string, i int) bool {
return i == 0 || isSpace(src[i-1]) || i == len(byteOrderMark) && strings.HasPrefix(src, byteOrderMark)
}
// isSpace reports whether c is whitespace.
func isSpace(c byte) bool { return c == ' ' || c == '\t' || c == '\r' || c == '\n' }
// isNameChar reports whether c may be in the name of an opcode or a variable.
func isNameChar(c byte) bool {
return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '_' || c == '$'
}
// lexer cuts text into nodes and keeps count of the position.
type lexer struct {
// nodes are the nodes cut so far.
nodes []*Node
// line is the line the next node starts on, from 1.
line int
// lineStart is the offset where the current line starts.
lineStart int
@@ -48,7 +53,8 @@ type lexer struct {
pos int
}
// add appends a node for the text from the current position to end.
// add gives n the text from the current position to end, and appends it, or
// extends the node before it if both are text.
func (l *lexer) add(src string, end int, n *Node) {
n.Raw = src[l.pos:end]
n.line, n.col = l.line, l.pos-l.lineStart+1
@@ -75,7 +81,9 @@ func (l *lexer) advance(src string, end int) {
l.pos = end
}
// lex cuts text into nodes whose raw text, joined, is the text.
// lex cuts text into nodes whose raw text, joined, is the text. Text that
// isn't a space, comment, header, opcode or directive is kept as text nodes,
// so that any text can be lexed.
func lex(src string) []*Node {
l := &lexer{line: 1}
for l.pos < len(src) {
@@ -83,6 +91,7 @@ func lex(src string) []*Node {
rest := src[i:]
switch {
case isSpace(src[i]) || i == 0 && strings.HasPrefix(src, byteOrderMark):
// A byte order mark and the whitespace after it make one space node.
j := i
if i == 0 && strings.HasPrefix(src, byteOrderMark) {
j = len(byteOrderMark)
@@ -107,7 +116,9 @@ func lex(src string) []*Node {
m := headerRE.FindStringSubmatch(rest)
l.add(src, i+len(m[0]), &Node{Kind: KindHeader, Name: m[1]})
case src[i] == '#' && atLineStart(src, i) && l.directive(src):
// The directive is added by the call that tests for it.
case opcodeRE.MatchString(rest):
// A value runs to the next break, or to the end of the text.
m := opcodeRE.FindStringSubmatch(rest)
valueStart := i + len(m[0])
end := len(src)
@@ -135,8 +146,8 @@ func lex(src string) []*Node {
return l.nodes
}
// directive adds a #define or #include at the current position, and reports
// whether it was one that can be read.
// directive adds the #define or #include at the current position, and reports
// whether there was one that can be read. Otherwise it adds nothing.
func (l *lexer) directive(src string) bool {
rest := src[l.pos:]
if m := defineRE.FindStringSubmatch(rest); m != nil {
@@ -159,5 +170,5 @@ func (l *lexer) directive(src string) bool {
return false
}
// commentRE finds the start of a comment.
// commentRE finds the start of a comment, which ends the value of a #define.
var commentRE = regexp.MustCompile(`//|/\*`)
+19 -15
View File
@@ -17,7 +17,7 @@ type CurvePoint struct {
Gain float64 `json:"gain" doc:"How much of its level the velocity plays." minimum:"0" maximum:"1"`
}
// The curves of a crossfade.
// The values of [Crossfade.Curve].
const (
CrossfadePower = "power"
CrossfadeGain = "gain"
@@ -36,7 +36,7 @@ type Crossfade struct {
Curve string `json:"curve" doc:"How the level changes through the fade: power, which keeps the loudness steady through a crossfade between regions, or gain, which fades the level in a straight line."`
}
// Where a condition's value comes from.
// The values of [Condition.Source].
const (
SourceController = "cc"
SourceBend = "bend"
@@ -65,7 +65,7 @@ type Keyswitch struct {
Up *int `json:"up,omitempty" doc:"A keyswitch key that must not be held, or nil if the region doesn't depend on it."`
}
// The settings a controller moves, as a modulation names them.
// The values of [Modulation.Target], the settings that a controller moves.
const (
TargetAmplitude = "amplitude"
TargetVolume = "volume"
@@ -74,8 +74,8 @@ const (
TargetTune = "tune"
)
// CurveStop is a point of a custom curve: the controller at one of the values
// 0 to 127, and the result there.
// CurveStop is a point of a custom curve: the result of the curve at one of
// the controller values 0 to 127.
type CurveStop struct {
At int `json:"at" doc:"The controller value the point is at." minimum:"0" maximum:"127"`
Value float64 `json:"value" doc:"The result of the curve at that value."`
@@ -96,8 +96,8 @@ type Modulation struct {
Points []CurveStop `json:"points,omitempty" doc:"The points of a custom curve, which pass through straight lines, or none for a built-in curve."`
}
// Control is a controller an instrument uses, with the name its SFZ gives it,
// and its starting value from 0 to 1.
// Control is a controller that an instrument uses, with the name its SFZ gives
// it and its starting value, from 0 to 1.
type Control struct {
Controller int `json:"controller" doc:"The controller number." minimum:"0" maximum:"127"`
Label string `json:"label,omitempty" doc:"The name the instrument gives the controller."`
@@ -112,7 +112,7 @@ type KeyswitchRange struct {
Default *int `json:"default,omitempty" doc:"The keyswitch that is active before any is pressed, or nil if there is none."`
}
// DefaultEnvelope is the envelope of a region that sets none: it plays at full
// DefaultEnvelope is the envelope of a region that sets none. It plays at full
// level at once, and stops almost at once when its note ends.
var DefaultEnvelope = Envelope{Sustain: 100, Release: defaultRelease}
@@ -209,7 +209,8 @@ type Region struct {
}
// Instrument is an SFZ instrument as typed regions, with its settings taken at
// the starting controller values.
// the starting controller values. One read from a document remembers where each
// region came from, so that [Instrument.Apply] can change the document.
type Instrument struct {
Regions []Region `json:"regions" doc:"The regions that the typed model has, in the order of the file."`
// Unread counts, for each opcode or header the typed model has no field
@@ -222,13 +223,15 @@ type Instrument struct {
// Keyswitches are its keyswitch keys, or nil if it has none.
Keyswitches *KeyswitchRange `json:"keyswitches,omitempty" doc:"The keys that are keyswitches, or nil if the instrument has none."`
// sources are the flattened regions that the typed ones were read from, in
// the same order, and eval reads a region from opcodes as they were.
// sources are the flattened regions that Regions were read from, in the same
// order.
sources []FlatRegion
// eval reads a region from opcodes, as when the regions were read.
eval evaluator
}
// Reasons a region is skipped: the typed model has no region for it.
// The keys of [Instrument.Skipped], the reasons that a region has no typed
// region.
const (
SkippedNoSample = "no sample file"
SkippedGenerated = "a generated sound"
@@ -236,7 +239,8 @@ const (
SkippedNotKeys = "not played by keys"
)
// Region defaults that SFZ gives.
// The defaults that SFZ gives a region, for the settings that the typed model
// has no zero value for.
const (
defaultRootKey = 60
// defaultLowVelocity is 1, as velocity 0 is a note-off.
@@ -245,8 +249,8 @@ const (
defaultRelease = 0.001
defaultTrigger = "attack"
// defaultOffMode is how a region stops when its group's voice limit or
// another group stops it, and defaultOffTime how long that takes when the
// mode is time, in seconds.
// another group stops it, and defaultOffTime is how long that takes, in
// seconds, when the mode is time.
defaultOffMode = "fast"
defaultOffTime = 0.006
)
+2
View File
@@ -121,6 +121,8 @@ func TestModelBounds(t *testing.T) {
walk(reflect.ValueOf(inst.Regions[0]), "Region")
}
// checkBounds reports a value that is outside the minimum and maximum in the
// tag of the field it was read from.
func checkBounds(t *testing.T, name string, tag reflect.StructTag, v float64) {
t.Helper()
if s, ok := tag.Lookup("minimum"); ok {
+29 -27
View File
@@ -8,8 +8,8 @@ import (
"strings"
)
// modulatedBy are the settings controllers move while a note plays, with the
// Opcodes that set each.
// modulatedBy are the settings that controllers move while a note plays, each
// with the opcodes that set it.
var modulatedBy = []struct {
target string
Opcodes []string
@@ -21,14 +21,14 @@ var modulatedBy = []struct {
{TargetTune, []string{"tune", "pitch"}},
}
// hasModulation reports whether a controller moves a target.
// hasModulation reports whether a numbered controller moves the target.
func (e evaluator) hasModulation(ops Opcodes, target string) bool {
return len(e.modulations(ops, target)) > 0
}
// modulations returns the controller modulations of a region's settings, which
// are the controllers 0 to 127, or only those of the targets named. They are in
// the order of the settings, then of the controllers.
// modulations returns the modulations of a region's settings by the numbered
// controllers, 0 to 127, or only those of the targets named. They are in the
// order of the settings, then of the controllers.
func (e evaluator) modulations(ops Opcodes, only ...string) []Modulation {
var out []Modulation
for _, set := range modulatedBy {
@@ -64,9 +64,10 @@ func (e evaluator) modulations(ops Opcodes, only ...string) []Modulation {
return out
}
// modulation returns how much the controllers from the number given up move an
// opcode from its own value: the sum of each target_onccN depth, or its SFZ v1
// form targetccN, shaped by target_curveccN at the controller's value.
// modulation returns how far the controllers from the number from up move a
// target from its own value. It is the sum of the depths of its target_onccN
// opcodes, or targetccN in SFZ v1, each shaped by target_curveccN at the
// controller's value.
func (e evaluator) modulation(ops Opcodes, target string, cc func(int) float64, from int) float64 {
total := 0.0
for _, m := range modulators(ops, target, from) {
@@ -75,18 +76,18 @@ func (e evaluator) modulation(ops Opcodes, target string, cc func(int) float64,
return total
}
// modulatorOpcode is a controller modulation of a target in a region's
// opcodes.
// modulatorOpcode is an opcode of a region that sets the depth of a controller's
// modulation of a target.
type modulatorOpcode struct {
name string
controller int
depth float64
}
// modulators returns the controller modulations of a target from the
// controller given up, whose depths are numbers, ordered by controller and then
// by name. The order makes sums of them, which floating-point addition makes
// depend on it, the same each time.
// modulators returns the opcodes that modulate the target by the controllers
// from the number from up, and whose depths are numbers, ordered by controller
// and then by name. Floating-point sums depend on the order of their terms, so
// summing in this order gives the same result each time.
func modulators(ops Opcodes, target string, from int) []modulatorOpcode {
var out []modulatorOpcode
for name, v := range ops {
@@ -104,8 +105,8 @@ func modulators(ops Opcodes, target string, from int) []modulatorOpcode {
return out
}
// amplitude returns the region's amplitude as a factor: amplitude and the
// global, master and group amplitudes are percentages that multiply, and so
// amplitude returns the region's amplitude as a factor. The amplitude, and the
// global, master and group amplitudes, are percentages that multiply, and so
// does each amplitude_oncc of the controllers above 127.
func (e evaluator) amplitude(ops Opcodes, cc func(int) float64) float64 {
a := 1.0
@@ -122,13 +123,13 @@ func (e evaluator) amplitude(ops Opcodes, cc func(int) float64) float64 {
// extendedOnly is the lowest of the controllers above 127, which belong to the
// note: its velocity, its key and whether it is held. A region takes the
// modulation of these at its root note and the middle of its velocities, as it
// can't follow them, and leaves the numbered controllers to be applied when a
// note plays.
// modulation by these at its root note and the middle of its velocities, as it
// can't follow them. It leaves the modulation by the numbered controllers to
// be applied when a note plays.
const extendedOnly = 128
// shape returns a controller's value through the curve the region gives it
// for the target, or straight through if it gives none.
// shape returns the value x of controller n through the curve that the region
// gives it for the target, or straight through if it gives none.
func (e evaluator) shape(ops Opcodes, target string, n int, x float64) float64 {
c, ok := e.curves[e.curveIndex(ops, target, n)]
if !ok {
@@ -137,8 +138,9 @@ func (e evaluator) shape(ops Opcodes, target string, n int, x float64) float64 {
return c(x)
}
// curveIndex returns the curve a region gives a controller's modulation of a
// target, or 0, the straight one, if it gives none or the curve doesn't exist.
// curveIndex returns the curve that a region gives a controller's modulation of
// a target, or 0, the straight one, if it gives none or the curve doesn't
// exist.
func (e evaluator) curveIndex(ops Opcodes, target string, n int) int {
if v, ok := parseNumber(ops[fmt.Sprintf("%s_curvecc%d", target, n)]); ok {
if _, exists := e.curves[int(v)]; exists {
@@ -148,9 +150,9 @@ func (e evaluator) curveIndex(ops Opcodes, target string, n int) int {
return 0
}
// modulator reports whether an opcode is a controller modulation of the
// target, and of which controller: target_onccN, or targetccN or target_ccN
// in SFZ v1.
// modulator reports whether an opcode sets a controller's modulation of the
// target, and the controller's number. The opcode is target_onccN, or targetccN
// or target_ccN in SFZ v1.
func modulator(name, target string) (int, bool) {
rest, ok := strings.CutPrefix(name, target)
if !ok {
+53 -34
View File
@@ -9,36 +9,40 @@ import (
"strings"
)
// Resolver returns the contents of an included file. The path is relative to
// the folder of the main file, with forward slashes.
// Resolver returns the contents of an included file. The path it is given is
// relative to the folder of the main file, with forward slashes. It may hold ..
// elements or be absolute, as the text of an instrument decides, so a Resolver
// that reads from a disk needs to keep to the instrument's folder.
type Resolver func(path string) ([]byte, error)
// IncludeMode is what [Parse] does with an #include.
// IncludeMode is what [Parse] does with each #include.
type IncludeMode int
// The include modes.
const (
// IncludesResolve reads each include. One that can't be read is reported
// as a [Problem] and left unresolved.
// IncludesResolve reads each include. An include that can't be read is
// reported as a [Problem] and left unresolved.
IncludesResolve IncludeMode = iota
// IncludesKeep reads no includes, and works out their paths only.
// IncludesKeep reads no includes, and only works out their paths.
IncludesKeep
// IncludesFail reads each include, and returns [ErrUnresolved] for one
// that can't be read.
// IncludesFail reads each include, and makes [Parse] return
// [ErrUnresolved] for one that can't be read.
IncludesFail
)
// Limits bound what an instrument may make Parse do.
// Limits bound the work that the text of an instrument can make [Parse] do.
type Limits struct {
// MaxDepth is how deeply #include may nest. The main file is at depth 0.
MaxDepth int
// MaxBytes is how many bytes all the files together may hold.
// MaxBytes is how many bytes all the files together may hold, counting
// what their variables expand to as well.
MaxBytes int
}
// DefaultLimits are the limits [Parse] uses unless [WithLimits] says otherwise.
// DefaultLimits are the limits [Parse] uses unless [WithLimits] sets others.
var DefaultLimits = Limits{MaxDepth: 16, MaxBytes: 16 << 20}
// parseConfig is what the [ParseOption]s set.
type parseConfig struct {
resolver Resolver
includes IncludeMode
@@ -48,7 +52,8 @@ type parseConfig struct {
// ParseOption changes how [Parse] works.
type ParseOption func(*parseConfig)
// WithResolver sets how includes are read. Without one, includes aren't read.
// WithResolver sets how includes are read. Without a resolver, includes aren't
// read.
func WithResolver(r Resolver) ParseOption {
return func(c *parseConfig) { c.resolver = r }
}
@@ -59,7 +64,7 @@ func WithIncludes(m IncludeMode) ParseOption {
return func(c *parseConfig) { c.includes = m }
}
// WithLimits sets the limits. A field that is 0 uses its default.
// WithLimits sets the limits. A field that is 0 keeps its default.
func WithLimits(l Limits) ParseOption {
return func(c *parseConfig) {
if l.MaxDepth > 0 {
@@ -71,7 +76,11 @@ func WithLimits(l Limits) ParseOption {
}
}
// Parse reads an instrument from r, and its includes with the resolver.
// Parse reads an instrument from r, and its includes with the resolver. It
// returns an error wrapping [ErrInvalid] for an instrument that is past the
// limits or that includes itself, and one wrapping [ErrUnresolved] for an
// include that can't be read if [IncludesFail] is set. Any other text can be
// read, and what in it isn't SFZ is for [Document.Validate] to report.
func Parse(r io.Reader, opts ...ParseOption) (*Document, error) {
p := newParser(opts)
data, err := p.read(r)
@@ -82,8 +91,8 @@ func Parse(r io.Reader, opts ...ParseOption) (*Document, error) {
}
// ParseFile reads the instrument whose main file is name in fsys, and its
// includes from the folder of the main file. [WithResolver] overrides how
// includes are read.
// includes from the folder of the main file, which fsys keeps them to.
// [WithResolver] overrides how includes are read.
func ParseFile(fsys fs.FS, name string, opts ...ParseOption) (*Document, error) {
dir := path.Dir(name)
read := func(p string) ([]byte, error) { return fs.ReadFile(fsys, path.Join(dir, p)) }
@@ -100,10 +109,11 @@ func ParseFile(fsys fs.FS, name string, opts ...ParseOption) (*Document, error)
return p.document(path.Base(name), data)
}
// Includes returns the files that an SFZ file includes directly, with the
// variables it defines itself substituted, in the order they first appear. The
// paths are relative to the folder of the main file. Includes that an
// included file makes aren't followed.
// Includes returns the files that an SFZ file includes directly, in the order
// they first appear, each once. A variable that the file defines itself is
// replaced by its value. The paths are relative to the folder of the main file.
// Includes that an included file makes aren't followed. It returns nil if text
// is past the limits.
func Includes(text []byte) []string {
doc, err := newParser([]ParseOption{WithIncludes(IncludesKeep)}).document("", text)
if err != nil {
@@ -126,10 +136,14 @@ type parser struct {
defines defines
// including holds the files being read, to refuse an include loop.
including []string
// bytes is how many bytes the files read so far, and what their variables
// expand to, come to.
bytes int
// problems are the problems found so far.
problems []Problem
}
// newParser returns a parser with the options set.
func newParser(opts []ParseOption) *parser {
p := &parser{parseConfig: parseConfig{limits: DefaultLimits}, defines: defines{}}
for _, o := range opts {
@@ -138,8 +152,8 @@ func newParser(opts []ParseOption) *parser {
return p
}
// read returns the text of the main file, and refuses one that is longer than
// the limit without reading the rest of it.
// read returns the text of the main file. It refuses one that is longer than the
// limit without reading the rest of it.
func (p *parser) read(r io.Reader) ([]byte, error) {
data, err := io.ReadAll(io.LimitReader(r, int64(p.limits.MaxBytes)+1))
if err != nil {
@@ -151,13 +165,14 @@ func (p *parser) read(r io.Reader) ([]byte, error) {
return data, nil
}
// tooLong returns the error for an instrument that is past the limit on bytes.
func (p *parser) tooLong() error {
return fmt.Errorf("%w: the instrument, with what its variables expand to, is longer than %d bytes", ErrInvalid, p.limits.MaxBytes)
}
// expand replaces the variables in text, counting the result against the
// limit on bytes, so that variables that hold variables can't make text
// that grows faster than the text that makes it.
// expand replaces the variables in text and counts the result against the
// limit on bytes. The count stops variables that hold variables from making
// text that grows much faster than the text that makes it.
func (p *parser) expand(text string) (string, error) {
out, ok := expand(p.defines, text, p.limits.MaxBytes-p.bytes)
if !ok {
@@ -176,7 +191,9 @@ func (p *parser) document(name string, data []byte) (*Document, error) {
return &Document{Root: root, problems: p.problems}, nil
}
// file lexes a file and reads the directives in it, in order.
// file lexes a file, and reads the directives in it in order: each #define sets
// a variable and each #include reads the file it names, at depth levels of
// include below the main file.
func (p *parser) file(name string, data []byte, depth int) (*File, error) {
if depth > p.limits.MaxDepth {
return nil, fmt.Errorf("%w: includes nest more than %d deep at %s", ErrInvalid, p.limits.MaxDepth, name)
@@ -203,7 +220,8 @@ func (p *parser) file(name string, data []byte, depth int) (*File, error) {
}
p.defines.set(n.Name, value)
case KindOpcode, KindText:
// Flattening and writing expand these again, so what they make counts.
// Flattening and writing expand these again, so what they make counts
// against the limit now.
if strings.Contains(n.Raw, "$") {
if _, err := p.expand(n.Raw); err != nil {
return nil, err
@@ -238,25 +256,26 @@ func (p *parser) file(name string, data []byte, depth int) (*File, error) {
return f, nil
}
// variableRE finds a $ and the run of name characters after it. Only the start
// of the run may be the name of a variable (see substitute).
// variableRE finds a $ and the run of name characters after it. The name of a
// variable is the start of the run (see substitute).
var variableRE = regexp.MustCompile(`\$[A-Za-z0-9_]+`)
// maxVariableName is the most bytes a variable's name may have, with its $.
// maxVariableName is the most bytes that the name of a variable may have, with
// its $. It keeps the search for the end of a name short.
const maxVariableName = 129
// substitute replaces the variables defined so far in text. A variable's name
// ends at the shortest run of characters that is a defined name, so in
// $MIC_$ART the underscore is text between $MIC and $ART, as in ARIA. A
// variable that isn't defined is left as it is.
// variable that isn't defined stays as it is.
func substitute(defines map[string]string, text string) string {
out, _ := expand(defines, text, -1)
return out
}
// expand is substitute with a limit on the length of the result, which it
// reports as false if text would make more than that. A negative limit is
// none.
// expand is substitute with a limit on the length of the result. It reports
// false, and returns nothing, if text would make more than that. A negative
// limit is no limit.
func expand(defines map[string]string, text string, limit int) (string, bool) {
if !strings.Contains(text, "$") {
return text, limit < 0 || len(text) <= limit
+57 -40
View File
@@ -13,40 +13,43 @@ import (
)
var (
// ErrNoSource is returned for a region that can't be edited because its
// opcodes aren't all in its own header: the instrument wasn't read from a
// document, a variable made the header, or an include or a variable
// brings in opcodes after it.
// ErrNoSource is returned for a region that has no header to edit: the
// instrument wasn't read from a document, a variable made the header, or an
// include or a variable brings in opcodes after it.
ErrNoSource = errors.New("no header to edit for the region")
// ErrUnpatchable is returned for a region that its own header can't hold:
// the changes would need to alter a header that other regions inherit, or a
// setting that the typed model reads from more than one place.
// ErrUnpatchable is returned for a change that the region's own header can't
// hold: it would need an opcode that the region inherits to be removed, or a
// setting that the typed model doesn't read from the header, such as a
// sample outside default_path.
ErrUnpatchable = errors.New("the region can't be written to its own header")
)
// Patch is a change to one opcode of a region's own header.
type Patch struct {
// Name is the opcode's name.
Name string
// Value is what the opcode is set to, unless Delete is set.
Value string
// Delete is whether the opcode is removed from the header.
Delete bool
}
// Patches returns the changes to the opcodes of the header of region i that
// make it read as updated. Only the settings that updated changes are touched,
// and the header's other opcodes, known or not, are left as they are. A change
// is always made in the region's own header, over what it inherits. It returns
// [ErrNoSource] or [ErrUnpatchable] if there is no way to make the change there,
// and then nothing has changed.
// make it read as updated. It only touches the settings that updated changes,
// and leaves the header's other opcodes, known or not, as they are. Changes are
// made in the region's own header, over what the region inherits, so other
// regions are not affected. It returns [ErrNoSource] or [ErrUnpatchable] if the
// header can't hold the change.
func (inst *Instrument) Patches(i int, updated Region) ([]Patch, error) {
patches, _, err := inst.plan(i, updated)
return patches, err
}
// Apply changes the document the instrument was read from so that region i
// reads as updated, with the changes that [Instrument.Patches] returns. It
// changes nothing and returns an error if they can't be made. The instrument
// now holds updated, and what it was read from isn't read again.
// Apply changes the document that the instrument was read from so that region
// i reads as updated, with the changes that [Instrument.Patches] returns. It
// changes nothing, and returns an error, if they can't be made. Afterwards the
// instrument holds updated as region i, and its other regions are as they were.
// The [Flat] it was read from isn't changed.
func (inst *Instrument) Apply(i int, updated Region) error {
patches, own, err := inst.plan(i, updated)
if err != nil {
@@ -73,20 +76,26 @@ func (inst *Instrument) Apply(i int, updated Region) error {
return nil
}
// plan works out the opcodes the region's own header ends with, and the patches
// that get it there.
// plan works out the opcodes that the header of region i has once it reads as
// updated, and the patches that take it there from the opcodes it has. It
// checks each plan by reading a region from the opcodes, so a plan that is
// returned reads back as updated.
func (inst *Instrument) plan(i int, updated Region) ([]Patch, Opcodes, error) {
src, err := inst.source(i)
if err != nil {
return nil, nil, err
}
changed := differing(inst.Regions[i], updated)
// RootFromSample and RootKey are both set by pitch_keycenter.
if slicesContains(changed, "RootFromSample") && !slicesContains(changed, "RootKey") {
changed = append(changed, "RootKey")
}
own := maps.Clone(src.Own)
defaultPath := strings.ReplaceAll(strings.TrimSpace(src.Opcodes["default_path"]), `\`, "/")
lines := regionLines(updated, true)
// Each changed field has the opcodes it owns replaced by those of the updated
// region, with the defaults written out so that they override what the
// region inherits.
for _, field := range changed {
for name := range own {
if owns(field, name) {
@@ -99,15 +108,17 @@ func (inst *Instrument) plan(i int, updated Region) ([]Patch, Opcodes, error) {
}
value := l.value
if field == "Sample" {
// The sample is read as relative to default_path.
value = strings.TrimPrefix(value, defaultPath)
}
own[l.name] = value
}
}
// Settings that other opcodes move, such as a key shifted by an offset, a
// volume that amplitude adds to, or a level that a clamp holds, are brought
// to the value by the difference that is left.
// A setting that other opcodes move, such as a key that an offset shifts or
// a volume that an amplitude adds to, is read as other than what was
// written. Each opcode is moved by the difference that is left, until the
// setting reads as it should, or no opcode can move it further.
var wrong []string
for try := 0; ; try++ {
got, reason := inst.eval.region(src.Inherited.with(own))
@@ -132,6 +143,8 @@ func (inst *Instrument) plan(i int, updated Region) ([]Patch, Opcodes, error) {
return nil, nil, fmt.Errorf("%w: %s", ErrUnpatchable, strings.Join(wrong, ", "))
}
// The patches are the differences between the opcodes the header has and
// those it should have.
var patches []Patch
for name, value := range own {
if old, ok := src.Own[name]; !ok || old != value {
@@ -147,6 +160,7 @@ func (inst *Instrument) plan(i int, updated Region) ([]Patch, Opcodes, error) {
return patches, own, nil
}
// slicesContains reports whether list has s.
func slicesContains(list []string, s string) bool {
for _, v := range list {
if v == s {
@@ -156,7 +170,8 @@ func slicesContains(list []string, s string) bool {
return false
}
// source returns the flattened region i, if its header can be edited.
// source returns the flattened region i if its header can be edited, or an
// error wrapping [ErrNoSource].
func (inst *Instrument) source(i int) (FlatRegion, error) {
if i < 0 || i >= len(inst.Regions) || i >= len(inst.sources) {
return FlatRegion{}, fmt.Errorf("%w: there is no region %d", ErrNoSource, i)
@@ -178,8 +193,8 @@ func (inst *Instrument) source(i int) (FlatRegion, error) {
return src, nil
}
// scalarOpcodes are the numeric fields of a region, by the opcode that sets
// each.
// scalarOpcodes are the numeric fields of a region, each with the opcode that
// sets it. A path such as Envelope.Attack names a field of the envelope.
var scalarOpcodes = map[string]string{
"LowKey": "lokey", "HighKey": "hikey", "RootKey": "pitch_keycenter", "LowVelocity": "lovel", "HighVelocity": "hivel",
"KeyTrack": "pitch_keytrack", "Tune": "tune", "Volume": "volume", "Pan": "pan", "Width": "width", "Offset": "offset",
@@ -189,8 +204,9 @@ var scalarOpcodes = map[string]string{
"Envelope.Decay": "ampeg_decay", "Envelope.Sustain": "ampeg_sustain", "Envelope.Release": "ampeg_release",
}
// adjust moves an opcode of the region's own header by how far a region read
// from it is from the one wanted, and reports whether that changed it.
// adjust moves an opcode of the region's own header by how far the field of the
// region got is from that of the region want, and reports whether that changed
// the opcode.
func adjust(own Opcodes, opcode, field string, got, want Region) bool {
g, ok := numberAt(reflect.ValueOf(got), field)
w, ok2 := numberAt(reflect.ValueOf(want), field)
@@ -212,8 +228,8 @@ func adjust(own Opcodes, opcode, field string, got, want Region) bool {
return next != base
}
// fieldAt returns the field of a struct at a path such as Envelope.Attack, with
// a pointer followed.
// fieldAt returns the field of a struct at a path such as Envelope.Attack,
// following pointers, and whether there is one.
func fieldAt(v reflect.Value, path string) (reflect.Value, bool) {
for _, name := range strings.Split(path, ".") {
for v.Kind() == reflect.Pointer && !v.IsNil() {
@@ -227,8 +243,8 @@ func fieldAt(v reflect.Value, path string) (reflect.Value, bool) {
return v, v.IsValid()
}
// numberAt returns the number at a path in a region, or false if there is none,
// as in a width that isn't set.
// numberAt returns the number at a path in a region, and false if there is
// none, as for a width that isn't set.
func numberAt(v reflect.Value, path string) (float64, bool) {
f, ok := fieldAt(v, path)
if !ok {
@@ -249,8 +265,8 @@ func numberAt(v reflect.Value, path string) (float64, bool) {
return 0, false
}
// differing returns the fields of two regions that differ, naming a setting of
// the envelope as Envelope.Attack.
// differing returns the names of the fields of two regions that differ, naming
// a setting of the envelope as Envelope.Attack is named.
func differing(a, b Region) []string {
var out []string
va, vb := reflect.ValueOf(a), reflect.ValueOf(b)
@@ -270,8 +286,8 @@ func differing(a, b Region) []string {
return out
}
// equalValues compares two values of a region, with numbers equal to within a
// rounding error, and an empty list the same as none.
// equalValues reports whether two values of a region are equal. Numbers are
// equal to within a rounding error, and an empty list is the same as none.
func equalValues(a, b reflect.Value) bool {
switch a.Kind() {
case reflect.Float64:
@@ -302,8 +318,8 @@ func equalValues(a, b reflect.Value) bool {
return a.Interface() == b.Interface()
}
// ownedNames are the opcodes that only one field of a region is read from,
// by field.
// ownedNames are the opcodes that one field of a region is read from and no
// other field, by the name of the field.
var ownedNames = map[string]*regexp.Regexp{
"Sample": regexp.MustCompile(`^sample$`), "LowKey": regexp.MustCompile(`^lokey$`), "HighKey": regexp.MustCompile(`^hikey$`),
"RootKey": regexp.MustCompile(`^pitch_keycenter$`), "LowVelocity": regexp.MustCompile(`^lovel$`), "HighVelocity": regexp.MustCompile(`^hivel$`),
@@ -327,12 +343,13 @@ var ownedNames = map[string]*regexp.Regexp{
"Keyswitch": regexp.MustCompile(`^sw_(last|previous|down|up)$`),
}
// controllerLimitRE reads the opcodes that limit a controller, and its number.
// controllerLimitRE reads the name of an opcode that limits a controller, and
// the controller's number.
var controllerLimitRE = regexp.MustCompile(`^(?:lo|hi)(?:hd)?cc(\d+)$`)
// owns reports whether a field of a region is the only one that an opcode of
// the region's header is read into, so that the opcode goes when the field is
// written again.
// owns reports whether a field of a region is the only one that an opcode is
// read into. The opcodes that a field owns are removed when the field is
// written again, so that none is left to set it otherwise.
func owns(field, name string) bool {
switch field {
case "Conditions":
+5 -1
View File
@@ -14,6 +14,8 @@ func readInstrument(t *testing.T, doc *Document) *Instrument {
return doc.Flatten().Instrument()
}
// TestApplyEditsOwnHeader checks that Apply changes the region's own header
// and nothing else, and that a second Apply starts from what the first wrote.
func TestApplyEditsOwnHeader(t *testing.T) {
text := "<control> default_path=S/ note_offset=12\n<group> volume=-6 ampeg_release=0.5 group_volume=-2\n" +
"<region> sample=a.wav lokey=c3 hikey=e3 // keys\n zampler_x=1\n<region> sample=b.wav\n"
@@ -52,6 +54,8 @@ func TestApplyEditsOwnHeader(t *testing.T) {
}
}
// TestApplyNothingToDo checks that a region that hasn't changed has no
// patches.
func TestApplyNothingToDo(t *testing.T) {
doc := mustParse(t, "<region> sample=a.wav\n", nil)
inst := readInstrument(t, doc)
@@ -109,7 +113,7 @@ func TestApplyRefusals(t *testing.T) {
}
}
// edits are changes a region can take, by what they change.
// edits are the changes that TestApplyProperty makes to a region, by name.
var edits = map[string]func(r *Region){
"sample": func(r *Region) { r.Sample = "other/x y.wav" },
"keys": func(r *Region) { r.LowKey, r.HighKey = 10, 20 },
+27 -8
View File
@@ -16,8 +16,12 @@ type ValueType int
const (
// TypeUnspecified is for an opcode whose value the format doesn't describe.
TypeUnspecified ValueType = iota
// TypeString is for a value that is text, which may have a fixed set of
// options.
TypeString
// TypeInteger is for a whole number, which may also be a note name.
TypeInteger
// TypeFloat is for a number that may have a fraction.
TypeFloat
)
@@ -41,7 +45,9 @@ type HeaderInfo struct {
// Version is the first SFZ version or player that has it: "SFZ v1", "SFZ v2",
// "ARIA", and so on.
Version string
// Deprecated is whether the format has dropped the header.
Deprecated bool
// Description is what the format says about the header.
Description string
}
@@ -56,10 +62,12 @@ type OpcodeInfo struct {
// Version is the first SFZ version or player that has it: "SFZ v1", "SFZ
// v2", "ARIA", "sfizz", "Calfbox" or "LinuxSampler".
Version string
// Deprecated is whether the format has dropped the opcode.
Deprecated bool
// Category is where the format lists it, such as "Performance Parameters /
// Amplifier".
Category string
// Type is the kind of value the opcode takes.
Type ValueType
// Min and Max bound a numeric value, or are nil where the format gives no
// bound it can state as a number.
@@ -73,19 +81,26 @@ type OpcodeInfo struct {
Options []string
// Note is whether an integer opcode also takes a note name, such as c4.
Note bool
// Description is what the format says about the opcode.
Description string
}
// matcher finds the registry entry for an opcode name.
// matcher finds the registry entry for the names of an opcode family.
type matcher struct {
// re matches the names that the family's name stands for.
re *regexp.Regexp
info *OpcodeInfo
}
var (
// registryOnce makes the lookup tables below on the first lookup.
registryOnce sync.Once
// byName holds the opcodes that aren't families, by each of their names.
byName map[string]*OpcodeInfo
// patterns holds the opcode families, with those whose names have a * last
// so that a more exact family is found first.
patterns []matcher
// headerByName holds the headers, by lowercase name.
headerByName map[string]*HeaderInfo
)
@@ -116,6 +131,7 @@ func pattern(name string) *regexp.Regexp {
return regexp.MustCompile(b.String())
}
// loadRegistry makes the lookup tables from the generated data, once.
func loadRegistry() {
registryOnce.Do(func() {
byName = map[string]*OpcodeInfo{}
@@ -142,9 +158,10 @@ func loadRegistry() {
})
}
// Lookup returns what the format says about an opcode, found by its name or
// one of its aliases. The info is the same for each name of the opcode, and
// its Name is the opcode's own.
// Lookup returns what the format says about an opcode, and whether it knows
// the opcode. The opcode is found by its name or one of its aliases, and by the
// name of a family it is in, such as locc64 in loccN. The info is the same for
// each name of the opcode, and its Name is the opcode's own.
func Lookup(name string) (OpcodeInfo, bool) {
loadRegistry()
if info, ok := byName[name]; ok {
@@ -158,7 +175,8 @@ func Lookup(name string) (OpcodeInfo, bool) {
return OpcodeInfo{}, false
}
// KnownOpcodes returns every opcode of the format, in the order of its listing.
// KnownOpcodes returns every opcode of the format, in the order the format
// lists them.
func KnownOpcodes() iter.Seq[OpcodeInfo] {
return func(yield func(OpcodeInfo) bool) {
for _, info := range opcodeData {
@@ -169,7 +187,8 @@ func KnownOpcodes() iter.Seq[OpcodeInfo] {
}
}
// KnownHeaders returns every header of the format.
// KnownHeaders returns every header of the format, in the order the format
// lists them.
func KnownHeaders() iter.Seq[HeaderInfo] {
return func(yield func(HeaderInfo) bool) {
for _, h := range headerData {
@@ -180,8 +199,8 @@ func KnownHeaders() iter.Seq[HeaderInfo] {
}
}
// LookupHeader returns what the format says about a header, given its name
// without brackets, in any case.
// LookupHeader returns what the format says about a header, and whether it
// knows the header. The name is given without brackets, in any case.
func LookupHeader(name string) (HeaderInfo, bool) {
loadRegistry()
h, ok := headerByName[strings.ToLower(name)]
+6
View File
@@ -12,6 +12,8 @@ import (
var update = flag.Bool("update", false, "rewrite docs/opcodes.md")
// TestLookup checks that Lookup finds an opcode by its name, its aliases and
// the name of its family, and doesn't find a name that isn't the format's.
func TestLookup(t *testing.T) {
for _, tc := range []struct {
name, canonical string
@@ -74,6 +76,8 @@ func TestRegistryComplete(t *testing.T) {
}
}
// TestGetAs checks the types that GetAs reads an opcode as, and that it reads
// note names and finds aliases.
func TestGetAs(t *testing.T) {
ops := Opcodes{"lokey": "c4", "hikey": " 72 ", "loopmode": "one_shot", "volume": "-3.5", "offset": "12", "bad": "x"}
if n, ok := GetAs[int](ops, "lokey"); !ok || n != 60 {
@@ -99,6 +103,8 @@ func TestGetAs(t *testing.T) {
}
}
// TestValidateValues checks the problems that Validate reports for the values
// of opcodes, and that it leaves alone what it can't check.
func TestValidateValues(t *testing.T) {
text := "<region> sample=a.wav lokey=c4 hikey=60 lovel=100 hivel=20 volume=loud pan=300 loop_mode=sideways\n" +
"<region> zampler_gain=3 locc7=1 pitch_keycenter=sample key=$K <wrong>\n" +
+17 -4
View File
@@ -10,8 +10,8 @@ import (
"time"
)
// TestDefinesCannotOutgrowLimit checks that variables that hold variables
// stop at the byte limit, as a few lines of them would otherwise make gigabytes.
// TestDefinesCannotOutgrowLimit checks that variables that hold variables stop
// at the byte limit, as a few lines of them would otherwise make gigabytes.
func TestDefinesCannotOutgrowLimit(t *testing.T) {
var b strings.Builder
// The names are as long as each other, so none is the start of another.
@@ -53,6 +53,9 @@ func (r *countingReader) Read(p []byte) (int, error) {
return len(p), nil
}
// TestParseReadsNoMoreThanLimit checks that Parse refuses a reader that is
// past the limit without reading all of it, and accepts text that is at the
// limit.
func TestParseReadsNoMoreThanLimit(t *testing.T) {
var r countingReader
_, err := Parse(&r, WithLimits(Limits{MaxBytes: 1000}))
@@ -67,6 +70,7 @@ func TestParseReadsNoMoreThanLimit(t *testing.T) {
}
}
// TestLimitsDepth checks that WithLimits sets how deeply includes may nest.
func TestLimitsDepth(t *testing.T) {
m := map[string]string{"a": "#include \"b\"", "b": "#include \"c\"", "c": "<region>"}
_, err := Parse(strings.NewReader("#include \"a\""), WithResolver(files(m)), WithLimits(Limits{MaxDepth: 2}))
@@ -75,8 +79,9 @@ func TestLimitsDepth(t *testing.T) {
}
}
// TestLexScales checks that text a few megabytes long takes a moment to
// read in each shape that was once quadratic.
// TestLexScales checks that text a few megabytes long is read in a moment, in
// each shape of text whose reading time could grow with the square of its
// length.
func TestLexScales(t *testing.T) {
for name, text := range map[string]string{
"opcodes on one line": strings.Repeat("a=1 ", 1<<19),
@@ -100,6 +105,8 @@ func TestLexScales(t *testing.T) {
}
}
// TestByteOrderMark checks that a byte order mark is read as space, so that a
// directive after it is still one.
func TestByteOrderMark(t *testing.T) {
text := "\ufeff#define $A 1\n<region> sample=$A.wav\n"
doc := mustParse(t, text, nil)
@@ -118,6 +125,8 @@ func TestByteOrderMark(t *testing.T) {
}
}
// TestWriteFilesStaysInFolder checks that WriteFiles refuses an include that
// leaves the folder, and writes nothing.
func TestWriteFilesStaysInFolder(t *testing.T) {
anyFile := func(string) ([]byte, error) { return []byte("<region> sample=a.wav\n"), nil }
for _, include := range []string{"../evil.sfz", "a/../../evil.sfz", "/evil.sfz", "..\\evil.sfz"} {
@@ -133,6 +142,8 @@ func TestWriteFilesStaysInFolder(t *testing.T) {
}
}
// TestValidateOutsideFolder checks that Validate reports includes and samples
// that leave the folder.
func TestValidateOutsideFolder(t *testing.T) {
doc := mustParse(t, "#include \"../x.sfz\"\n<region> sample=../a.wav\n<region> sample=/a.wav\n<region> sample=C:\\a.wav\n<region> sample=ok/../b.wav\n", map[string]string{"../x.sfz": ""})
var codes []string
@@ -145,6 +156,8 @@ func TestValidateOutsideFolder(t *testing.T) {
}
}
// TestKeyswitchRangeOneEnd checks that a keyswitch range with only one end
// set is that one key.
func TestKeyswitchRangeOneEnd(t *testing.T) {
for text, want := range map[string]KeyswitchRange{
"<region> sample=a.wav sw_lokey=36": {Low: 36, High: 36},
+3
View File
@@ -23,6 +23,7 @@ var roundTripTexts = map[string]string{
"variable": "#define $A 1\n$A $B=2 label_cc$A=x\n",
}
// TestRoundTrip checks that awkward text is written back as it was read.
func TestRoundTrip(t *testing.T) {
for name, text := range roundTripTexts {
doc, err := Parse(strings.NewReader(text))
@@ -86,6 +87,8 @@ func TestIncludedTwice(t *testing.T) {
}
}
// TestValidate checks the problems that Validate reports for the text, as
// opposed to the values, of a document.
func TestValidate(t *testing.T) {
doc, err := Parse(strings.NewReader("lokey=1\n<region> sample=$GONE.wav\n#define $A 1\n<region> %%% sample=$A.wav\n"))
if err != nil {
+19 -16
View File
@@ -2,14 +2,16 @@ package sfz
import "strings"
// defines are the variables defined so far, by name with their $.
// defines are the variables defined so far, by name with their $, with their
// values as they stand after the variables in them are replaced.
type defines map[string]string
// set gives a variable the value, which has its own variables replaced
// set gives a variable a value, which has had its own variables replaced
// already.
func (d defines) set(name, value string) { d[name] = strings.TrimSpace(value) }
// define reads a #define node, replacing the variables in its value.
// define sets the variable of a #define node, replacing the variables in its
// value.
func (d defines) define(n *Node) { d.set(n.Name, substitute(d, n.Value)) }
// undefined returns the variables in text that haven't been defined.
@@ -23,29 +25,30 @@ func (d defines) undefined(text string) []string {
return out
}
// visitor reads a document's nodes as [walk] meets them.
// visitor is what [walk] tells about the nodes of a document, in order.
type visitor interface {
// define is called for a #define before its variable is set.
// define is called for a #define, before its variable is set.
define(f *File, n *Node)
// include is called for an #include before the file it read is walked.
// include is called for an #include, before the file it read is walked.
include(f *File, n *Node)
// variables is called for an opcode or text node that uses variables,
// before what it makes is read.
// before the headers, opcodes and text that it makes are told of.
variables(f *File, n *Node)
// header is called for a header. Variable is whether a variable's value
// made it, in which case n is the node that uses the variable.
// header is called for a header. Variable is whether the value of a
// variable made it, in which case n is the node that uses the variable.
header(f *File, n *Node, name string, variable bool)
// opcode is called for an opcode. Variable is as for header.
// opcode is called for an opcode. Variable is as for header, and n is
// likewise the node that uses the variable.
opcode(f *File, n *Node, name, value string, variable bool)
// text is called for text that isn't an opcode or header, which n is or
// holds.
// text is called for text that isn't an opcode or a header, which is n or
// is made by n.
text(f *File, n *Node, raw string)
}
// walk reads the nodes of a file in order, and of the files it includes where
// they stand, with the variables as they are at each node. Text that uses a
// variable is read again with the variable replaced, as the value can hold
// opcodes and headers.
// walk tells v of the nodes of a file in order, and of the files it includes
// where the includes stand, with defs holding the variables as they are at each
// node. A node that uses a variable is lexed again with its variables replaced,
// because a value can hold opcodes and headers.
func walk(f *File, defs defines, v visitor) {
for _, n := range f.Nodes {
switch n.Kind {
+26
View File
@@ -42,6 +42,7 @@ func parseText(t *testing.T, text string) *Instrument {
return parseFiles(t, map[string]string{"main.sfz": text}).Flatten().Instrument()
}
// near reports whether two numbers are equal to within a rounding error.
func near(a, b float64) bool { return math.Abs(a-b) < 1e-9 }
// TestVariableNames checks that a variable's name ends at the shortest
@@ -59,6 +60,8 @@ func TestVariableNames(t *testing.T) {
}
}
// TestFlatten checks that Flatten reads includes, variables and comments as
// the format says.
func TestFlatten(t *testing.T) {
doc := parseFiles(t, map[string]string{
"main.sfz": "#define $DIR Data // the folder\n" +
@@ -101,6 +104,8 @@ func TestVariableOpcodes(t *testing.T) {
}
}
// TestParseErrors checks the errors that Parse returns for includes that
// loop, nest too deeply or can't be read.
func TestParseErrors(t *testing.T) {
// An include loop and an include nested too deeply are refused (spec:
// "recursion must be avoided"; sfizz limits the depth).
@@ -140,6 +145,8 @@ func TestParseErrors(t *testing.T) {
}
}
// TestIncludes checks that Includes lists the files that a file includes
// itself.
func TestIncludes(t *testing.T) {
// A file's includes are listed once each, in order, with its own
// variables substituted, backslashes read as slashes and paths cleaned.
@@ -161,6 +168,8 @@ func TestIncludes(t *testing.T) {
}
}
// TestInheritance checks which opcodes a region takes from the headers above
// it.
func TestInheritance(t *testing.T) {
inst := parseText(t, `
<control> default_path=One/
@@ -220,6 +229,7 @@ func TestInheritance(t *testing.T) {
}
}
// TestDefaults checks the values of a region that sets nothing.
func TestDefaults(t *testing.T) {
r := parseText(t, "<region> sample=a.wav").Regions[0]
// Spec: lovel 1, hivel 127, pitch_keycenter 60, pitch_keytrack 100,
@@ -237,6 +247,8 @@ func TestDefaults(t *testing.T) {
}
}
// TestKeysAndNotes checks how keys, note names and the offsets of the control
// header set a region's keys.
func TestKeysAndNotes(t *testing.T) {
inst := parseText(t, `
<control> note_offset=1 octave_offset=-1
@@ -279,6 +291,8 @@ func TestKeysAndNotes(t *testing.T) {
}
}
// TestControllers checks how modulation by controllers, and the conditions on
// them, are read.
func TestControllers(t *testing.T) {
inst := parseText(t, `
<control> set_cc7=127 set_hdcc20=0.25 set_cc64=0 label_cc20=Mic mix
@@ -373,6 +387,8 @@ func TestControllers(t *testing.T) {
}
}
// TestVariantsAndChokes checks how round robins, random variants and choke
// groups are read.
func TestVariantsAndChokes(t *testing.T) {
inst := parseText(t, `
<region> sample=plain.wav
@@ -411,6 +427,7 @@ func TestVariantsAndChokes(t *testing.T) {
}
}
// TestStartingControllers checks the starting values of the controllers.
func TestStartingControllers(t *testing.T) {
// Without set_cc, volume starts at 100, pan in the middle and expression
// at full (sfizz); other controllers start at 0 (sfizz). The controllers
@@ -428,6 +445,7 @@ func TestStartingControllers(t *testing.T) {
}
}
// TestControllerConditions checks how the ranges of locc and hicc are read.
func TestControllerConditions(t *testing.T) {
// locc and hicc include both ends, and hiccN includes all of value N
// (sfizz), so a controller at 0.5, which is 63.5 of 127, is within hicc63
@@ -472,6 +490,8 @@ func TestControllerConditions(t *testing.T) {
}
}
// TestKeyswitches checks the keyswitches that regions need, and the range of
// keys that they make.
func TestKeyswitches(t *testing.T) {
// Every region is kept with the keyswitches it needs, and the first
// articulation is the one down at the start unless sw_default says
@@ -515,6 +535,8 @@ func TestKeyswitches(t *testing.T) {
}
}
// TestModulationsAndBend checks how a region's stereo width, pitch bend and
// modulation of its settings are read.
func TestModulationsAndBend(t *testing.T) {
inst := parseText(t, `
<region> sample=a.wav width=50 width_oncc3=-25 gain_oncc4=3 pitch_oncc5=100 bend_up=1200 bend_down=-100 bend_step=100
@@ -543,6 +565,8 @@ func TestModulationsAndBend(t *testing.T) {
}
}
// TestOtherOpcodes checks how the other opcodes the typed model reads are
// read, and that those it doesn't are counted.
func TestOtherOpcodes(t *testing.T) {
inst := parseText(t, `
<region> sample=a.wav tune=-20 transpose=1 pitch_keytrack=0 offset=100 amp_veltrack=40 group_volume=-3
@@ -562,6 +586,8 @@ trigger=release rt_decay=6 loop_mode=loop_continuous loopstart=10 loop_end=20 am
}
}
// TestSplendid checks the typed instrument that the Splendid Grand Piano
// fixture makes.
func TestSplendid(t *testing.T) {
doc, err := ParseFile(os.DirFS(filepath.Join("testdata", "splendid")), "Splendid Grand Piano.sfz")
if err != nil {
+31 -13
View File
@@ -9,9 +9,11 @@ import (
"strings"
)
// Validate returns the problems in the document, in the order the files are
// read. It reports what is wrong with the text and with values the format
// describes, and never fails on an opcode it doesn't know.
// Validate returns the problems in the document: those found while it was
// read, then those in each file, in the order the files are read. It reports
// what is wrong with the text, and with the values of opcodes that the format
// describes. An opcode or header that it doesn't know is only information, and
// is never an error.
func (d *Document) Validate() []Problem {
defs := defines{}
v := &validator{defs: defs, known: map[string]known{}}
@@ -21,25 +23,27 @@ func (d *Document) Validate() []Problem {
return v.problems
}
// opcodeAt is an opcode read in a header.
// opcodeAt is the numeric value of an opcode of a header, with where it is.
type opcodeAt struct {
value float64
at *Node
file *File
}
// known is the result of a [Lookup].
// known is the result of a [Lookup], kept so it needn't be made again.
type known struct {
info OpcodeInfo
ok bool
}
// validator is the [visitor] that finds the problems in a document's nodes.
type validator struct {
// defs are the variables defined so far, which [walk] sets.
defs defines
// known holds the lookups made, as a document names the same few opcodes
// many times.
known map[string]known
// problems are those found so far.
problems []Problem
// inHeader is whether a header has been read.
inHeader bool
@@ -48,13 +52,17 @@ type validator struct {
numbers map[string]opcodeAt
}
// add records a problem at the node n of the file f.
func (v *validator) add(f *File, n *Node, sev Severity, code, msg string) {
line, col := f.Position(n)
v.problems = append(v.problems, Problem{File: f.Path, Line: line, Col: col, Severity: sev, Code: code, Msg: msg})
}
// define reports the undefined variables that a #define's value uses.
func (v *validator) define(f *File, n *Node) { v.undefined(f, n, n.Value) }
// include reports the undefined variables that an #include's path uses, and a
// path that leaves the folder of the main file.
func (v *validator) include(f *File, n *Node) {
v.undefined(f, n, n.Value)
if n.Resolved != "" && !fs.ValidPath(n.Resolved) {
@@ -62,8 +70,11 @@ func (v *validator) include(f *File, n *Node) {
}
}
// variables reports the undefined variables that a node uses.
func (v *validator) variables(f *File, n *Node) { v.undefined(f, n, n.Raw) }
// text reports text that isn't SFZ. Text that holds a variable is left, as the
// variable may be undefined.
func (v *validator) text(f *File, n *Node, raw string) {
if strings.Contains(raw, "$") {
return
@@ -71,6 +82,7 @@ func (v *validator) text(f *File, n *Node, raw string) {
v.add(f, n, SeverityWarning, "text.unreadable", fmt.Sprintf("can't read %q", strings.TrimSpace(raw)))
}
// header ends the header before it, and checks that the format has the header.
func (v *validator) header(f *File, n *Node, name string, _ bool) {
v.endHeader()
v.inHeader = true
@@ -80,8 +92,8 @@ func (v *validator) header(f *File, n *Node, name string, _ bool) {
}
}
// endHeader checks the ranges of the header that has just ended: a lo opcode
// above its hi opcode.
// endHeader checks the header that has just ended, for an opcode that starts
// with lo and is above the one that is its hi.
func (v *validator) endHeader() {
names := make([]string, 0, len(v.numbers))
for name := range v.numbers {
@@ -101,6 +113,10 @@ func (v *validator) endHeader() {
v.numbers = nil
}
// opcode checks that the format has the opcode, and that its value is one it
// allows. An opcode before any header is reported once. A name or value that
// uses a variable is only checked for the name, as the variable may hold
// anything.
func (v *validator) opcode(f *File, n *Node, name, value string, _ bool) {
if !v.inHeader {
v.add(f, n, SeverityInfo, "opcode.no-header", fmt.Sprintf("%s is before any header", name))
@@ -132,7 +148,8 @@ func (v *validator) opcode(f *File, n *Node, name, value string, _ bool) {
v.value(f, n, name, value, info)
}
// value checks a value against what the format says about its opcode.
// value checks the value of an opcode against its type, range and options, and
// notes it, if it is a number, to check the header's ranges at its end.
func (v *validator) value(f *File, n *Node, name, value string, info OpcodeInfo) {
switch info.Type {
case TypeInteger, TypeFloat:
@@ -172,7 +189,7 @@ func (v *validator) value(f *File, n *Node, name, value string, info OpcodeInfo)
}
}
// bounds describes the range an opcode's value may take.
// bounds describes the range an opcode's value may take, as text.
func bounds(info OpcodeInfo) string {
lo, hi := "-∞", "∞"
if info.Min != nil {
@@ -184,18 +201,19 @@ func bounds(info OpcodeInfo) string {
return lo + " to " + hi
}
// undefined reports the variables in text that haven't been defined.
// undefined reports the variables in text of the node n that haven't been
// defined.
func (v *validator) undefined(f *File, n *Node, text string) {
for _, run := range v.defs.undefined(text) {
v.add(f, n, SeverityWarning, "define.undefined", fmt.Sprintf("%s isn't defined", run))
}
}
// driveRE reads the drive of a Windows path.
// driveRE reads the drive at the start of a Windows path.
var driveRE = regexp.MustCompile(`^[A-Za-z]:`)
// outsideFolder reports whether a sample path is absolute or leaves the
// folder it is relative to.
// outsideFolder reports whether a path is absolute, or leaves the folder that
// it is relative to by going up.
func outsideFolder(p string) bool {
p = strings.ReplaceAll(strings.TrimSpace(p), `\`, "/")
if strings.HasPrefix(p, "/") || driveRE.MatchString(p) {
+15 -14
View File
@@ -8,15 +8,16 @@ import (
"strings"
)
// noteRE reads a note name such as c4, C#0 or eb-1. Middle C is c4, MIDI
// note 60.
// noteRE reads a note name such as c4, C#0 or eb-1, as the letter, the sharp
// or flat if any, and the octave. Middle C is c4, MIDI note 60.
var noteRE = regexp.MustCompile(`^([A-Ga-g])([#b]?)(-?[0-9]+)$`)
// semitones are the notes' places in the octave from C.
// semitones are how many semitones each natural note is above C, by the
// note's lowercase letter.
var semitones = map[byte]int{'c': 0, 'd': 2, 'e': 4, 'f': 5, 'g': 7, 'a': 9, 'b': 11}
// parseNote reads a MIDI note number or a note name. It reports false if the
// value is neither.
// parseNote reads a MIDI note number or a note name, and reports whether v was
// one.
func parseNote(v string) (int, bool) {
v = strings.TrimSpace(v)
if n, err := strconv.Atoi(v); err == nil {
@@ -37,7 +38,7 @@ func parseNote(v string) (int, bool) {
return n, true
}
// parseNumber reads a number, and reports false if the value isn't one.
// parseNumber reads a finite number, and reports whether v was one.
func parseNumber(v string) (float64, bool) {
f, err := strconv.ParseFloat(strings.TrimSpace(v), 64)
if err != nil || math.IsNaN(f) || math.IsInf(f, 0) {
@@ -46,11 +47,11 @@ func parseNumber(v string) (float64, bool) {
return f, true
}
// curve maps a controller's value, from 0 to 1, to how much of a
// modulation's depth applies.
// curve maps a controller's value, from 0 to 1, to how much of a modulation's
// depth applies.
type curve func(x float64) float64
// builtinCurves are the curves SFZ players define, by index.
// builtinCurves are the curves that SFZ players define, by index.
var builtinCurves = map[int]curve{
0: func(x float64) float64 { return x },
1: func(x float64) float64 { return 2*x - 1 },
@@ -61,14 +62,14 @@ var builtinCurves = map[int]curve{
6: func(x float64) float64 { return math.Sqrt(1 - x) },
}
// pointRE reads a <curve> point, such as v064, whose number is the
// pointRE reads the name of a <curve> point, such as v064, whose number is the
// controller value from 0 to 127.
var pointRE = regexp.MustCompile(`^v([0-9]{1,3})$`)
// readCurves returns the instrument's curves: the built-in ones, and those of
// its <curve> headers, which pass through their points in straight lines, and
// the points of the custom ones.
// A curve that doesn't set v000 or v127 starts at 0 or ends at 1.
// readCurves returns the instrument's curves by index, and the points of its
// custom curves. The curves are the built-in ones and those of its <curve>
// headers, which pass through their points in straight lines. A curve that
// doesn't set v000 starts at 0, and one that doesn't set v127 ends at 1.
func readCurves(defs []Opcodes) (map[int]curve, map[int][]CurveStop) {
curves := make(map[int]curve, len(builtinCurves)+len(defs))
stops := map[int][]CurveStop{}
+35 -27
View File
@@ -9,7 +9,7 @@ import (
"strings"
)
// LineEnding is the line break a written document uses.
// LineEnding is the line break that a written document uses.
type LineEnding string
// The line endings.
@@ -23,30 +23,32 @@ const (
)
// WriteOptions change how a document is written. The zero value writes each
// file as it was read.
// file as it was read, with the line breaks it had.
type WriteOptions struct {
// InlineIncludes replaces each #include that was read with the text of its
// file, so the main file stands alone.
InlineIncludes bool
// ExpandVariables replaces each variable with its value, as of where it is
// used, and leaves out the #define directives. Written to several files,
// a file that is included more than once, and so would be expanded
// differently each time, is an error.
// used, and leaves out the #define directives. A file that is included more
// than once, with its variables set differently each time, can't be written
// as a file of its own, as it would need to be written differently each
// time, and [Document.WriteFiles] returns an error for it.
ExpandVariables bool
// LineEnding sets the line break of the text written.
// LineEnding is the line break of the text written. The zero value is
// [KeepLineEndings].
LineEnding LineEnding
}
// FileWriter writes a file of a document. The path is that of the file, with
// forward slashes, in the folder of the main file.
// FileWriter writes the data of a file of a document. The path is that of the
// file, with forward slashes, in the folder of the path given to
// [Document.WriteFiles].
type FileWriter func(path string, data []byte) error
// Write writes the document as one file to w. A document that has includes
// that were read can be written as one file only with InlineIncludes, or else
// the files they hold would be dropped; Write returns [ErrInvalid] then. With
// ExpandVariables, the included files would also need variables that the main
// file no longer defines, so it needs InlineIncludes as well. Use
// [Document.WriteFiles] to write the files separately.
// Write writes the document as one file to w. A document with includes that
// were read can be written as one file only with InlineIncludes, as the files
// they hold would be lost otherwise, and Write returns an error wrapping
// [ErrInvalid] for it. Use [Document.WriteFiles] to write the files
// separately, with ExpandVariables or not.
func (d *Document) Write(w io.Writer, opts WriteOptions) error {
if d.hasIncludes() && !opts.InlineIncludes {
return fmt.Errorf("%w: the document has includes, which need InlineIncludes, or WriteFiles", ErrInvalid)
@@ -56,7 +58,7 @@ func (d *Document) Write(w io.Writer, opts WriteOptions) error {
return err
}
// hasIncludes reports whether the document read any include.
// hasIncludes reports whether the main file has an include that was read.
func (d *Document) hasIncludes() bool {
for _, n := range d.Root.Nodes {
if n.Kind == KindInclude && n.File != nil {
@@ -66,10 +68,11 @@ func (d *Document) hasIncludes() bool {
return false
}
// WriteFiles writes the main file with the path root, and each file it
// includes at its own path, in the folder of root, using fw. It writes nothing
// and returns [ErrInvalid] if an include's path is absolute or leaves the
// folder.
// WriteFiles writes the main file with the path root, and each file it includes
// at its own path in the folder of root, using fw. It writes nothing, and
// returns an error wrapping [ErrInvalid], for an include whose path is absolute
// or leaves the folder, and for a file that is included more than once and
// would be written differently each time.
func (d *Document) WriteFiles(root string, fw FileWriter, opts WriteOptions) error {
r := &renderer{opts: opts, defines: defines{}, outputs: map[string]string{}, collect: true}
text := r.file(d.Root)
@@ -98,18 +101,21 @@ func (d *Document) WriteFiles(root string, fw FileWriter, opts WriteOptions) err
return nil
}
// renderer writes files as the options say.
// renderer writes the files of a document as the options say.
type renderer struct {
opts WriteOptions
// defines are the variables defined so far, when variables are expanded.
defines defines
// collect is whether the included files that stand apart are kept in
// outputs, as WriteFiles writes them.
collect bool
// outputs are the included files that stand apart, by path.
outputs map[string]string
// err is the first error found.
err error
}
// lineEndings returns text with the line breaks that the options give it.
func (r *renderer) lineEndings(text string) string {
if r.opts.LineEnding == KeepLineEndings {
return text
@@ -118,14 +124,15 @@ func (r *renderer) lineEndings(text string) string {
return strings.ReplaceAll(text, "\n", string(r.opts.LineEnding))
}
// file returns the text of a file as it is written.
// file returns the text of a file as it is written, with the files it includes
// written into it or kept for [Document.WriteFiles], as the options say.
func (r *renderer) file(f *File) string {
var b strings.Builder
// dropBreak is whether the next line break is cut, as the directive it
// followed is.
// dropBreak is whether the next line break is cut, as the directive that it
// ends is cut, or its text has been written in its place.
dropBreak := false
// gap is whether an inlined file ended without whitespace, so that what
// follows needs some.
// follows needs some to stay apart from it.
gap := false
for _, n := range f.Nodes {
raw := n.Raw
@@ -148,7 +155,8 @@ func (r *renderer) file(f *File) string {
b.WriteByte(' ')
}
b.WriteString(inner)
// The include's own line break would leave an empty line.
// The include's own line break would leave an empty line after a file
// that ends with one.
dropBreak = strings.HasSuffix(inner, "\n")
gap = inner != "" && !isSpace(inner[len(inner)-1])
continue
@@ -177,8 +185,8 @@ func (r *renderer) file(f *File) string {
return b.String()
}
// output keeps the text of an included file, and reports a file that comes out
// differently each time it is included.
// output keeps the text of an included file, and sets err if the file has
// already been kept with other text.
func (r *renderer) output(n *Node, text string) {
if prev, ok := r.outputs[n.Resolved]; ok && prev != text && r.err == nil {
r.err = fmt.Errorf("%w: %s is included more than once and is written differently each time", ErrInvalid, n.Resolved)
+13
View File
@@ -6,6 +6,7 @@ import (
"testing"
)
// write writes a document with the options, and fails the test if it can't.
func write(t *testing.T, doc *Document, opts WriteOptions) string {
t.Helper()
var b strings.Builder
@@ -21,6 +22,9 @@ var writeFiles = map[string]string{
const writeMain = "#define $S kick\n#include \"x.sfz\"\n#define $S snare\n<region> sample=$S.wav\n"
// TestWriteZeroValue checks that the zero value of WriteOptions writes each
// file as it was read, and that Write refuses to lose the files a document
// includes.
func TestWriteZeroValue(t *testing.T) {
doc := mustParse(t, writeMain, writeFiles)
// Written to files, each file is as it was read.
@@ -75,6 +79,8 @@ func TestIncludedTwiceEdited(t *testing.T) {
}
}
// TestExpandVariablesKeepsComments checks that ExpandVariables leaves the
// text of comments as it is.
func TestExpandVariablesKeepsComments(t *testing.T) {
doc := mustParse(t, "#define $A 1\n// uses $A\n/* $A */<region> sample=$A.wav // $A\n", nil)
want := "// uses $A\n/* $A */<region> sample=1.wav // $A\n"
@@ -83,6 +89,8 @@ func TestExpandVariablesKeepsComments(t *testing.T) {
}
}
// TestInlineIncludes checks that InlineIncludes writes one file that reads as
// the document did.
func TestInlineIncludes(t *testing.T) {
doc := mustParse(t, writeMain, writeFiles)
got := write(t, doc, WriteOptions{InlineIncludes: true})
@@ -97,6 +105,9 @@ func TestInlineIncludes(t *testing.T) {
}
}
// TestExpandVariables checks that ExpandVariables writes each variable's value
// as of where it is used, and returns an error where the files can't be written
// with them expanded.
func TestExpandVariables(t *testing.T) {
doc := mustParse(t, writeMain, writeFiles)
got := write(t, doc, WriteOptions{InlineIncludes: true, ExpandVariables: true})
@@ -127,6 +138,8 @@ func TestExpandVariables(t *testing.T) {
}
}
// TestLineEndings checks that LineEnding sets the line breaks that are
// written, and that the zero value keeps them.
func TestLineEndings(t *testing.T) {
doc := mustParse(t, "<region>\r\nsample=a.wav\n", nil)
if got := write(t, doc, WriteOptions{LineEnding: LF}); got != "<region>\nsample=a.wav\n" {