Files
sfz/instrument.go
T

459 lines
15 KiB
Go
Raw Normal View History

package sfz
import (
"cmp"
"maps"
"math"
"path"
"regexp"
"slices"
"strconv"
"strings"
)
// 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 {
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] = withOwnNames(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 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 that the opcodes describe, or the reason, one of
// the Skipped constants, that there is none.
func (e evaluator) region(ops Opcodes) (Region, string) {
ops = withOwnNames(ops)
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]
}
// 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
}
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 = toInt64(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(ops["loop_mode"])
r.LoopStart = frames(ops["loop_start"])
r.LoopEnd = frames(ops["loop_end"])
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, toInt(n))
}
if n, ok := parseNumber(ops["seq_position"]); ok {
r.SequencePosition = max(1, toInt(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)
}
if n, ok := parseNumber(ops["group"]); ok {
r.Group = toInt(n)
}
if n, ok := parseNumber(ops["off_by"]); ok {
g := toInt(n)
r.OffBy = &g
}
r.Polyphony = polyphonyLimit(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 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, 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{}
// The opcodes are read in the order of their names, so that two spellings of
// one velocity, as amp_velcurve_064 and amp_velcurve_64, give the same result
// each time.
for _, name := range slices.Sorted(maps.Keys(ops)) {
v := ops[name]
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 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]
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 = toInt(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
}
// polyphonyLimit reads the value of polyphony, which is a number of voices, or
// legato_high, legato_last or legato_low, which each limit the region to one
// voice and choose which note sounds. It returns nil if v is neither.
func polyphonyLimit(v string) *int {
switch strings.TrimSpace(v) {
case "legato_high", "legato_last", "legato_low":
return ptr(1)
}
return voiceLimit(v)
}
// 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 {
return nil
}
limit := toInt(n)
return &limit
}
// minVolume is the quietest a region plays, in dB, which stands for silence.
const minVolume = -144
// 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
}
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 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), "./")
}
// 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 {
return nil
}
f := toInt64(n)
return &f
}
// toInt returns a number as a whole number, cut to the range of 32 bits, which
// is as far as the format goes. A number that doesn't fit would otherwise
// change sign.
func toInt(f float64) int { return int(clamp(math.Trunc(f), math.MinInt32, math.MaxInt32)) }
// toInt64 returns a number as a whole number, cut to the range that a float64
// holds exactly.
func toInt64(f float64) int64 { return int64(clamp(math.Trunc(f), -1<<53, 1<<53)) }
// 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 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,
"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 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 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)$`)
// withOwnNames returns the opcodes with each name that is another name of an
// opcode replaced by the opcode's own, such as loopmode by loop_mode. An opcode
// that is set under its own name keeps that value, and one that is set under
// several other names takes the value of the name that sorts last, so that the
// result is the same each time.
func withOwnNames(ops Opcodes) Opcodes {
var others []string
for name := range ops {
if ownName(name) != name {
others = append(others, name)
}
}
if others == nil {
return ops
}
slices.Sort(others)
out := maps.Clone(ops)
for _, name := range others {
delete(out, name)
}
for _, name := range others {
if _, set := ops[ownName(name)]; !set {
out[ownName(name)] = ops[name]
}
}
return out
}
// handled reports whether the typed model reads an opcode.
func handled(name string) bool {
name = ownName(name)
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
}