Files
sfz/controls.go
aneurinandClaude Sonnet 5.5 8134660721 Fix the differences from the spec and sfizz that a conformance review found
Read opcodes under their other names. The registry lists the other names an
opcode has, and the typed model now reads each under its own name: amp_release
for ampeg_release, offby, bendup, tune_keytrack and the rest. Apply treats an
old name as belonging to the same field, so it doesn't leave one behind.

Cut a #define's value at the first space, as ARIA and sfizz do, so that two
defines can share a line. Before, the first define took the rest of the line,
and a kit that writes "#define $lo 1  #define $hi 25" lost its velocity layers.

Ignore opcodes before any header when flattening, as sfizz does, and report
them as a warning. Included files that hold only opcodes are not affected.

Read the limits of a controller the same way each time. A region that sets
lohdccN and inherits loccN took whichever the map gave first, so Apply's change
could read back as the old limits. The hdcc opcodes now win.

Accept -1 for lokey, hikey and key, which SFZ v2 allows, and don't report a
region with a hikey of -1 as an inverted range.

Cut numbers that don't fit to what a setting can hold, so offset=1e30 doesn't
turn negative, and ignore a controller number or octave that overflows.

Read polyphony=legato_high, legato_last and legato_low as a limit of 1.

Put a new #define after a byte order mark.

Mark in the tests where each expected value comes from, correct the tags that
the spec doesn't support, and add tests for each of these.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-01 20:38:57 +00:00

283 lines
7.7 KiB
Go

package sfz
import (
"regexp"
"strconv"
"strings"
)
// The controllers above 127 that ARIA defines, which depend on the note: its
// velocity, its key, and whether it is held.
const (
extendedVelocityCC = 131
extendedKeyCC = 133
extendedGateCC = 134
)
// maxControls is how many numbered controllers an instrument has, 0 to 127.
const maxControls = 128
// 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{}
for name, v := range control {
m := ccRE.FindStringSubmatch(name)
if m == nil {
continue
}
n, err := strconv.Atoi(m[2])
if err != nil {
continue
}
switch m[1] {
case "label_cc":
labels[n] = strings.TrimSpace(v)
used[n] = true
case "set_cc", "set_hdcc":
used[n] = true
}
}
for _, r := range regions {
for _, c := range r.Conditions {
if c.Source == SourceController {
used[c.Controller] = true
}
}
for _, m := range r.Modulations {
used[m.Controller] = true
}
}
var out []Control
for n := 0; n < maxControls; n++ {
if used[n] {
out = append(out, Control{Controller: n, Label: labels[n], Value: e.cc[n]})
}
}
return out
}
// keyswitchRange returns the keys that are keyswitches and the one that is down
// 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 {
shift := keyShift(ops)
low, lowOK := parseNote(ops["sw_lokey"])
high, highOK := parseNote(ops["sw_hikey"])
var keys []int
for _, name := range []string{"sw_last", "sw_previous", "sw_down", "sw_up"} {
if n, ok := parseNote(ops[name]); ok {
keys = append(keys, n+shift)
}
}
if !lowOK && !highOK && len(keys) == 0 {
continue
}
if r == nil {
r = &KeyswitchRange{Low: 127, High: 0}
}
if lowOK {
keys = append(keys, low+shift)
}
if highOK {
keys = append(keys, high+shift)
}
for _, k := range keys {
r.Low, r.High = min(r.Low, k), max(r.High, k)
}
}
if r != nil {
r.Low, r.High = max(0, r.Low), min(127, r.High)
if d := defaultKeyswitch(regions); d >= 0 {
r.Default = &d
}
}
return r
}
// 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.
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.
// 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 {
values[n] = v
}
for name, v := range control {
m := ccRE.FindStringSubmatch(name)
if m == nil {
continue
}
n, err := strconv.Atoi(m[2])
if err != nil {
continue
}
f, ok := parseNumber(v)
if !ok {
continue
}
switch m[1] {
case "set_cc":
values[n] = clamp(f/127, 0, 1)
case "set_hdcc":
values[n] = clamp(f, 0, 1)
}
}
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.
func defaultKeyswitch(regions []Opcodes) int {
for _, ops := range regions {
if n, ok := parseNote(ops["sw_default"]); ok {
return n + keyShift(ops)
}
}
for _, ops := range regions {
if n, ok := parseNote(ops["sw_last"]); ok {
return n + keyShift(ops)
}
}
return -1
}
// 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
if n, ok := parseNumber(ops["note_offset"]); ok {
shift += toInt(n)
}
if n, ok := parseNumber(ops["octave_offset"]); ok {
shift += 12 * toInt(n)
}
return shift
}
// 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. 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
min, max float64
}{
{SourceChannel, "lochan", "hichan", 1, 1, 16},
{SourceBend, "lobend", "hibend", 8192, -1, 1},
{SourceAftertouch, "lochanaft", "hichanaft", 127, 0, 1},
{SourcePolyAftertouch, "lopolyaft", "hipolyaft", 127, 0, 1},
}
// 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{}
// A limit set as both lo/hicc and lo/hihdcc, as when a region sets one and
// inherits the other, takes the value of the hdcc one. The opcodes have no
// order of their own, so reading the hdcc ones last is what makes the result
// the same each time.
read := func(hd bool) {
for name, v := range ops {
m := ccRE.FindStringSubmatch(name)
if m == nil || strings.Contains(m[1], "hd") != hd {
continue
}
n, err := strconv.Atoi(m[2])
if err != nil {
continue
}
limit, ok := parseNumber(v)
if !ok || n >= extendedVelocityCC {
continue
}
c := ranges[n]
if c == nil {
c = &Condition{Source: SourceController, Controller: n, Low: 0, High: 1}
}
switch m[1] {
case "locc":
c.Low = clamp(limit/127, 0, 1)
case "hicc":
c.High = 1
if limit < 127 {
c.High = clamp((limit+1)/127-topEpsilon, 0, 1)
}
case "lohdcc":
c.Low = clamp(limit, 0, 1)
case "hihdcc":
c.High = clamp(limit, 0, 1)
default:
continue
}
ranges[n] = c
}
}
read(false)
read(true)
var out []Condition
for _, b := range controllerBounds {
lo, loOK := parseNumber(ops[b.low])
hi, hiOK := parseNumber(ops[b.high])
if !loOK && !hiOK {
continue
}
c := Condition{Source: b.source, Low: b.min, High: b.max}
if loOK {
c.Low = clamp(lo/b.scale, b.min, b.max)
}
if hiOK {
c.High = clamp(hi/b.scale, b.min, b.max)
}
out = append(out, c)
}
for n := 0; n < extendedVelocityCC; n++ {
if c := ranges[n]; c != nil {
out = append(out, *c)
}
}
return out
}
// 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
for name, into := range map[string]**int{"sw_last": &k.Last, "sw_previous": &k.Previous, "sw_down": &k.Down, "sw_up": &k.Up} {
if n, ok := parseNote(ops[name]); ok {
key := n + shift
*into = &key
found = true
}
}
if !found {
return nil
}
return &k
}