Files
sfz/instrument.go
T
aneurinandClaude Sonnet 5.5 83c905633c Apply changes to a typed region as patches to its own header
Instrument.Patches works out the opcode changes that make region i read as an
updated Region, checking them against the reader, and Instrument.Apply makes
them in the document. Only the changed settings are touched, always in the
region's own header, so unknown opcodes and what other regions inherit stay as
they are. A change the header can't hold is an error and changes nothing.

FlatRegion gains Own, Inherited and Header to trace a region to its source, and
regionLines lists a region's opcodes with the field each sets.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-01 18:42:17 +00:00

405 lines
13 KiB
Go

package sfz
import (
"cmp"
"math"
"path"
"regexp"
"slices"
"strconv"
"strings"
)
// Instrument reads the flattened instrument into the typed model.
func (f *Flat) Instrument() *Instrument {
inst := &Instrument{Unread: map[string]int{}, Skipped: map[string]int{}}
for h, n := range f.Headers {
inst.Unread["<"+h+">"] += n
}
curves, stops := readCurves(f.Curves)
e := evaluator{cc: controllerValues(f.Control), curves: curves, stops: stops}
inst.eval = e
regions := make([]Opcodes, len(f.Regions))
for i, fr := range f.Regions {
ops := fr.Opcodes
regions[i] = ops
r, reason := e.region(ops)
if reason != "" {
inst.Skipped[reason]++
continue
}
for name := range ops {
if !handled(name) {
inst.Unread[name]++
}
}
inst.Regions = append(inst.Regions, r)
inst.sources = append(inst.sources, fr)
}
inst.Controls = e.controls(f.Control, inst.Regions)
inst.Keyswitches = keyswitchRange(regions)
return inst
}
// evaluator turns regions' Opcodes into regions.
type evaluator struct {
cc map[int]float64
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.
func (e evaluator) region(ops Opcodes) (Region, string) {
sample := strings.TrimSpace(ops["sample"])
switch {
case sample == "":
return Region{}, SkippedNoSample
case strings.HasPrefix(sample, "*"):
return Region{}, SkippedGenerated
}
for name := range ops {
if strings.HasPrefix(name, "on_lo") || strings.HasPrefix(name, "on_hi") {
return Region{}, SkippedByCC
}
}
shift := keyShift(ops)
r := Region{
Sample: samplePath(ops["default_path"], sample),
LowKey: 0,
HighKey: 127,
RootKey: defaultRootKey,
LowVelocity: defaultLowVelocity,
HighVelocity: 127,
KeyTrack: 100,
VelocityTracking: 100,
Envelope: DefaultEnvelope,
Trigger: defaultTrigger,
SequenceLength: 1,
SequencePosition: 1,
HighRandom: 1,
}
note := func(name string, into *int) {
if n, ok := parseNote(ops[name]); ok {
*into = n + shift
}
}
note("key", &r.LowKey)
note("key", &r.HighKey)
note("key", &r.RootKey)
note("lokey", &r.LowKey)
note("hikey", &r.HighKey)
// A root note of sample is the file's, which only the host can read, and
// which sfizz keeps over key.
if strings.EqualFold(strings.TrimSpace(ops["pitch_keycenter"]), "sample") {
r.RootFromSample = true
} else {
note("pitch_keycenter", &r.RootKey)
}
if r.HighKey < 0 || r.LowKey > 127 || r.LowKey > r.HighKey {
return Region{}, SkippedNotKeys
}
r.LowKey, r.HighKey = max(r.LowKey, 0), min(r.HighKey, 127)
r.RootKey = int(clamp(float64(r.RootKey), 0, 127))
if n, ok := parseNumber(ops["lovel"]); ok {
r.LowVelocity = int(clamp(n, 0, 127))
}
if n, ok := parseNumber(ops["hivel"]); ok {
r.HighVelocity = int(clamp(n, 0, 127))
}
// Controllers that depend on the note are taken at the region's root note
// and the middle of its velocities.
cc := func(n int) float64 {
switch n {
case extendedVelocityCC:
return float64(r.LowVelocity+r.HighVelocity) / 2 / 127
case extendedKeyCC:
return float64(r.RootKey) / 127
case extendedGateCC:
return 1
}
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 := func(target string, base float64) float64 {
if v, ok := parseNumber(ops[target]); ok {
base = v
}
return base + e.modulation(ops, target, cc, extendedOnly)
}
value := func(target string, base float64) float64 {
if v, ok := parseNumber(ops[target]); ok {
base = v
}
return base + e.modulation(ops, target, cc, 0)
}
r.KeyTrack = value("pitch_keytrack", 100)
r.Tune = own("tune", 0) + e.modulation(ops, "pitch", cc, extendedOnly)
if v, ok := parseNumber(ops["pitch"]); ok {
r.Tune += v
}
if v, ok := parseNumber(ops["transpose"]); ok {
r.Tune += 100 * v
}
r.Volume = own("volume", 0) + e.modulation(ops, "gain", cc, extendedOnly)
for _, name := range []string{"group_volume", "master_volume", "global_volume"} {
if v, ok := parseNumber(ops[name]); ok {
r.Volume += v
}
}
amplitude := e.amplitude(ops, cc)
if amplitude <= 0 {
r.Volume = minVolume
} else {
r.Volume = max(minVolume, r.Volume+20*math.Log10(amplitude))
}
r.Pan = clamp(own("pan", 0), -100, 100)
if _, ok := parseNumber(ops["width"]); ok || e.hasModulation(ops, "width") {
r.Width = ptr(clamp(own("width", 100), -100, 100))
}
r.BendUp = number(ops, "bend_up")
r.BendDown = number(ops, "bend_down")
r.BendStep = number(ops, "bend_step")
r.Conditions = conditions(ops)
r.Keyswitch = keyswitch(ops, shift)
r.Modulations = e.modulations(ops)
r.Offset = int64(max(0, value("offset", 0)))
r.VelocityTracking = clamp(value("amp_veltrack", 100), -100, 100)
r.VelocityCurve = velocityCurve(ops)
r.KeyCrossfade = crossfade(ops, "key", shift)
r.VelocityCrossfade = crossfade(ops, "vel", 0)
r.Envelope = Envelope{
Delay: max(0, value("ampeg_delay", 0)),
Attack: max(0, value("ampeg_attack", 0)),
Hold: max(0, value("ampeg_hold", 0)),
Decay: max(0, value("ampeg_decay", 0)),
Sustain: clamp(value("ampeg_sustain", 100), 0, 100),
Release: max(0, value("ampeg_release", defaultRelease)),
}
if t := strings.TrimSpace(ops["trigger"]); t != "" {
r.Trigger = t
}
r.LoopMode = strings.TrimSpace(firstOf(ops, "loop_mode", "loopmode"))
r.LoopStart = frames(firstOf(ops, "loop_start", "loopstart"))
r.LoopEnd = frames(firstOf(ops, "loop_end", "loopend"))
r.ReleaseDecay = max(0, value("rt_decay", 0))
// A seq_length or seq_position below 1 plays as 1, as sfizz plays it.
if n, ok := parseNumber(ops["seq_length"]); ok {
r.SequenceLength = max(1, int(n))
}
if n, ok := parseNumber(ops["seq_position"]); ok {
r.SequencePosition = max(1, int(n))
}
if n, ok := parseNumber(ops["lorand"]); ok {
r.LowRandom = clamp(n, 0, 1)
}
if n, ok := parseNumber(ops["hirand"]); ok {
r.HighRandom = clamp(n, 0, 1)
}
// polyphony_group is SFZ v2's name for group.
if n, ok := parseNumber(firstOf(ops, "group", "polyphony_group")); ok {
r.Group = int(n)
}
if n, ok := parseNumber(ops["off_by"]); ok {
g := int(n)
r.OffBy = &g
}
r.Polyphony = voiceLimit(ops["polyphony"])
r.NotePolyphony = voiceLimit(ops["note_polyphony"])
r.OffMode = defaultOffMode
switch mode := strings.ToLower(strings.TrimSpace(ops["off_mode"])); mode {
case "fast", "time", "normal":
r.OffMode = mode
}
r.OffTime = defaultOffTime
if n, ok := parseNumber(ops["off_time"]); ok && n >= 0 {
r.OffTime = n
}
return r, ""
}
// velocityCurveRE reads the velocity 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.
func velocityCurve(ops Opcodes) []CurvePoint {
points := map[int]float64{}
for name, v := range ops {
m := velocityCurveRE.FindStringSubmatch(name)
if m == nil {
continue
}
at, _ := strconv.Atoi(m[1])
if gain, ok := parseNumber(v); ok && at <= 127 {
points[at] = clamp(gain, 0, 1)
}
}
if len(points) == 0 {
return nil
}
if _, ok := points[0]; !ok {
points[0] = 0
}
if _, ok := points[127]; !ok {
points[127] = 1
}
out := make([]CurvePoint, 0, len(points))
for at, gain := range points {
out = append(out, CurvePoint{Velocity: at, Gain: gain})
}
slices.SortFunc(out, func(a, b CurvePoint) int { return cmp.Compare(a.Velocity, b.Velocity) })
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.
func crossfade(ops Opcodes, which string, shift int) *Crossfade {
read := func(name string, fallback int) (int, bool) {
v, ok := ops[name]
if !ok {
return fallback, false
}
var n int
if which == "key" {
if n, ok = parseNote(v); ok {
n += shift
}
} else if f, isNumber := parseNumber(v); isNumber {
n, ok = int(f), true
}
if !ok {
return fallback, false
}
return int(clamp(float64(n), 0, 127)), true
}
c := &Crossfade{Curve: CrossfadePower}
var set [4]bool
c.FadeInLow, set[0] = read("xfin_lo"+which, 0)
c.FadeInHigh, set[1] = read("xfin_hi"+which, 0)
c.FadeOutLow, set[2] = read("xfout_lo"+which, 127)
c.FadeOutHigh, set[3] = read("xfout_hi"+which, 127)
if !set[0] && !set[1] && !set[2] && !set[3] {
return nil
}
if strings.EqualFold(strings.TrimSpace(ops["xf_"+which+"curve"]), "gain") {
c.Curve = CrossfadeGain
}
return c
}
// voiceLimit reads a number of voices, which is at least 1, or nil if v isn't
// one.
func voiceLimit(v string) *int {
n, ok := parseNumber(v)
if !ok || n < 1 {
return nil
}
limit := int(n)
return &limit
}
// 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.
func number(ops Opcodes, name string) *float64 {
if v, ok := parseNumber(ops[name]); ok {
return &v
}
return nil
}
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.
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.
func firstOf(ops Opcodes, names ...string) string {
for _, n := range names {
if v, ok := ops[n]; ok {
return v
}
}
return ""
}
// frames reads a sample position in frames, or returns nil if v isn't one.
func frames(v string) *int64 {
n, ok := parseNumber(v)
if !ok || n < 0 {
return nil
}
f := int64(n)
return &f
}
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.
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,
"pitch_keytrack": true, "tune": true, "pitch": true, "transpose": true,
"volume": true, "group_volume": true, "master_volume": true, "global_volume": true,
"amplitude": true, "global_amplitude": true, "master_amplitude": true, "group_amplitude": true,
"pan": true, "offset": true, "amp_veltrack": true,
"ampeg_delay": true, "ampeg_attack": true, "ampeg_hold": true, "ampeg_decay": true, "ampeg_sustain": true, "ampeg_release": true,
"trigger": true, "loop_mode": true, "loopmode": true, "loop_start": true, "loopstart": true, "loop_end": true, "loopend": true,
"rt_decay": true, "sw_lokey": true, "sw_hikey": true, "sw_last": true, "sw_default": true,
"lorand": true, "hirand": true, "seq_position": true, "seq_length": true,
"xfin_lokey": true, "xfin_hikey": true, "xfout_lokey": true, "xfout_hikey": true, "xf_keycurve": true,
"xfin_lovel": true, "xfin_hivel": true, "xfout_lovel": true, "xfout_hivel": true, "xf_velcurve": true,
"group": true, "polyphony_group": true, "off_by": true,
"polyphony": true, "note_polyphony": true, "off_mode": true, "off_time": true,
"sw_previous": true, "sw_down": true, "sw_up": true, "width": true, "bend_up": true, "bend_down": true, "bend_step": true,
"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.
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.
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.
func handled(name string) bool {
if handledNames[name] || handledRE.MatchString(name) {
return true
}
for _, target := range modulatedTargets {
if _, ok := modulator(name, target); ok {
return true
}
if rest, ok := strings.CutPrefix(name, target+"_curvecc"); ok {
if _, err := strconv.Atoi(rest); err == nil {
return true
}
}
}
return false
}