Files
sfz/instrument.go
T

1036 lines
32 KiB
Go
Raw Normal View History

package sfz
import (
"cmp"
"fmt"
"math"
"path"
"regexp"
"slices"
"strconv"
"strings"
)
// Envelope is a region's amplitude envelope. Times are in seconds.
type Envelope struct {
Delay float64
Attack float64
Hold float64
Decay float64
// Sustain is the level held after the decay, as a percentage.
Sustain float64
Release float64
}
// CurvePoint is how much of its level a velocity plays, from 0 to 1.
type CurvePoint struct {
Velocity int
Gain float64
}
// The curves of a crossfade.
const (
CrossfadePower = "power"
CrossfadeGain = "gain"
)
// Crossfade fades a region in over one range of keys or velocities and out
// over another. It plays at no level below the start of its fade in and above
// the end of its fade out. A range whose ends are equal doesn't fade.
type Crossfade struct {
FadeInLow, FadeInHigh int
FadeOutLow, FadeOutHigh int
// Curve is power, which keeps the loudness steady through a crossfade
// between regions, or gain, which fades the level in a straight line.
Curve string
}
// Where a condition's value comes from.
const (
SourceController = "cc"
SourceBend = "bend"
SourceAftertouch = "aftertouch"
SourcePolyAftertouch = "polyAftertouch"
SourceChannel = "channel"
)
// Condition limits when a region plays to a source being within a range, which
// includes both ends. A controller, aftertouch and polyphonic aftertouch are
// from 0 to 1, pitch bend from -1 to 1 and a MIDI channel from 1 to 16.
type Condition struct {
Source string
Controller int
Low, High float64
}
// Keyswitch limits when a region plays to the keyswitches that have been
// pressed: the last one, the one before it, and keys that are held or aren't.
// A field that isn't set is nil.
type Keyswitch struct {
Last, Previous, Down, Up *int
}
// The settings a controller moves, as a modulation names them.
const (
TargetAmplitude = "amplitude"
TargetVolume = "volume"
TargetPan = "pan"
TargetWidth = "width"
TargetTune = "tune"
)
// CurveStop is a point of a custom curve: the controller at one of the values
// 0 to 127, and the result there.
type CurveStop struct {
At int
Value float64
}
// Modulation moves a region's setting as a controller does. The controller
// goes through the curve, and its result, from 0 to 1 or beyond, times Depth
// is added to the setting, or multiplies it for amplitude. Depth is in the
// setting's own units: percent for amplitude, pan and width, dB for volume,
// and cents for tune.
type Modulation struct {
Target string
Controller int
Depth float64
// Curve is the index of one of SFZ's built-in curves, 0 to 6, when Points
// is empty.
Curve int
Points []CurveStop
}
// Control is a controller an instrument uses, with the name its SFZ gives it,
// and its starting value from 0 to 1.
type Control struct {
Controller int
Label string
Value float64
}
// KeyswitchRange is the keys that are keyswitches, and the one that is down at
// the start, or nil if the instrument has no keyswitch.
type KeyswitchRange struct {
Low, High int
Default *int
}
// 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}
// Region is a sample and the notes and velocities that play it, with its
// settings at the instrument's starting controller values.
type Region struct {
// Sample is the sample's path, relative to the folder of the instrument's
// main file, with forward slashes.
Sample string
LowKey int
HighKey int
RootKey int
// RootFromSample says the root note is the one the sample file holds
// (pitch_keycenter=sample), which RootKey doesn't know.
RootFromSample bool
LowVelocity int
HighVelocity int
// KeyTrack is how far each key repitches the sample, in cents: 100 plays
// the keys' pitches, and 0 plays every key at the sample's own.
KeyTrack float64
// Tune is in cents.
Tune float64
// Volume is in dB.
Volume float64
// Pan is from -100, left, to 100, right.
Pan float64
// Offset is where the sample starts playing, in frames.
Offset int64
// VelocityTracking is how much velocity sets the level, as a percentage:
// 100 follows it fully, and 0 plays every velocity at full level.
VelocityTracking float64
// VelocityCurve is how much of its level each velocity plays, through
// straight lines between its points, or nil if the region sets none. Its
// points ascend by velocity, from 0 to 127.
VelocityCurve []CurvePoint
// KeyCrossfade and VelocityCrossfade are nil if the region sets none.
KeyCrossfade *Crossfade
VelocityCrossfade *Crossfade
Envelope Envelope
// Trigger is what starts the region: attack, when a note starts; release,
// when it ends; first; or legato.
Trigger string
// LoopMode is no_loop, one_shot, loop_continuous or loop_sustain, or
// empty to follow the sample file.
LoopMode string
// LoopStart and LoopEnd are frames, or nil to follow the sample file.
LoopStart *int64
LoopEnd *int64
// ReleaseDecay is how much quieter a release region plays for each second
// its note was held, in dB.
ReleaseDecay float64
// SequenceLength and SequencePosition make the region one of a round
// robin: of each SequenceLength notes it matches, it plays the one at
// SequencePosition, counting from 1.
SequenceLength int
SequencePosition int
// LowRandom and HighRandom make the region a random variant: it plays when
// a number drawn for the note, from 0 to 1, is at least LowRandom and less
// than HighRandom.
LowRandom float64
HighRandom float64
// Group is the region's choke group, which other regions' OffBy names.
Group int
// OffBy is the group whose notes stop this region while it plays, or nil
// if none does.
OffBy *int
// Polyphony is how many voices the region's group may have playing at
// once, or nil if it sets none. A note past it stops the oldest voice.
Polyphony *int
// Conditions and Keyswitch decide, from the controllers and keyswitches
// when a note starts, whether the region plays. The region plays if every
// condition holds and its keyswitch does.
Conditions []Condition
Keyswitch *Keyswitch
// Modulations are the controllers that move the region's settings, which
// hold their values with no controller.
Modulations []Modulation
// Width is the stereo width in percent, or nil for the sample's own. BendUp
// and BendDown are how far pitch bend moves the pitch at its ends in cents,
// and BendStep the size of its steps, or nil for the SFZ defaults.
Width *float64
BendUp *float64
BendDown *float64
BendStep *float64
// NotePolyphony is how many voices of the region's group may play the
// same key at once, or nil if it sets none.
NotePolyphony *int
// OffMode is how the region stops when it is stopped by a group or past a
// voice limit: fast, time or normal.
OffMode string
// OffTime is how long a region whose OffMode is time takes to stop, in
// seconds.
OffTime float64
}
// Instrument is an SFZ instrument as typed regions, with its settings taken at
// the starting controller values.
type Instrument struct {
Regions []Region
// Unread counts, for each opcode or header the typed model has no field
// for, the regions that have it, or how often a header appears.
Unread map[string]int
// Skipped counts the regions that have no typed region, by why.
Skipped map[string]int
// Controls are the controllers that the instrument names, sets or uses.
Controls []Control
// Keyswitches are its keyswitch keys, or nil if it has none.
Keyswitches *KeyswitchRange
}
// Reasons a region is skipped: the typed model has no region for it.
const (
SkippedNoSample = "no sample file"
SkippedGenerated = "a generated sound"
SkippedByCC = "started by a controller"
SkippedNotKeys = "not played by keys"
)
// Region defaults that SFZ gives.
const (
defaultRootKey = 60
// defaultLowVelocity is 1, as velocity 0 is a note-off.
defaultLowVelocity = 1
// defaultRelease is in seconds.
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.
defaultOffMode = "fast"
defaultOffTime = 0.006
)
// 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
)
// 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}
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.Controls = e.controls(f.Control, inst.Regions)
inst.Keyswitches = keyswitchRange(regions)
return inst
}
// maxControls is the most controllers an instrument has, one for each.
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.
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, _ := strconv.Atoi(m[2])
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. Without sw_lokey and
// sw_hikey, they are 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 && highOK {
keys = append(keys, low+shift, 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 a controller number from the end of an opcode, such as the 64 of
// locc64.
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: those that set_cc and set_hdcc give, then defaultControllers, then 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, _ := strconv.Atoi(m[2])
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 is 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 += int(n)
}
if n, ok := parseNumber(ops["octave_offset"]); ok {
shift += 12 * int(n)
}
return shift
}
// 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
// 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.
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.
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 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.
func conditions(ops Opcodes) []Condition {
ranges := map[int]*Condition{}
for name, v := range ops {
m := ccRE.FindStringSubmatch(name)
if m == nil {
continue
}
n, _ := strconv.Atoi(m[2])
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
}
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 a region needs, 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
}
// 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 }
// modulatedBy are the settings controllers move while a note plays, with the
// Opcodes that set each.
var modulatedBy = []struct {
target string
Opcodes []string
}{
{TargetAmplitude, []string{"amplitude"}},
{TargetVolume, []string{"volume", "gain"}},
{TargetPan, []string{"pan"}},
{TargetWidth, []string{"width"}},
{TargetTune, []string{"tune", "pitch"}},
}
// hasModulation reports whether a controller moves a 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.
func (e evaluator) modulations(ops Opcodes, only ...string) []Modulation {
var out []Modulation
for _, set := range modulatedBy {
if len(only) > 0 && !slices.Contains(only, set.target) {
continue
}
for _, opcode := range set.Opcodes {
for name, v := range ops {
n, ok := modulator(name, opcode)
depth, isNumber := parseNumber(v)
if !ok || !isNumber || n >= extendedOnly {
continue
}
m := Modulation{Target: set.target, Controller: n, Depth: depth, Curve: e.curveIndex(ops, opcode, n)}
if stops, ok := e.stops[m.Curve]; ok {
m.Points = stops
}
out = append(out, m)
}
}
}
order := func(t string) int {
for i, set := range modulatedBy {
if set.target == t {
return i
}
}
return len(modulatedBy)
}
slices.SortFunc(out, func(a, b Modulation) int {
return cmp.Or(order(a.Target)-order(b.Target), a.Controller-b.Controller, cmp.Compare(a.Depth, b.Depth))
})
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.
func (e evaluator) modulation(ops Opcodes, target string, cc func(int) float64, from int) float64 {
total := 0.0
for name, v := range ops {
n, ok := modulator(name, target)
if !ok || n < from {
continue
}
depth, ok := parseNumber(v)
if !ok {
continue
}
total += depth * e.shape(ops, target, n, cc(n))
}
return total
}
// amplitude returns the region's amplitude as a factor: 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
for _, name := range []string{"amplitude", "global_amplitude", "master_amplitude", "group_amplitude"} {
if v, ok := parseNumber(ops[name]); ok {
a *= v / 100
}
}
for name, v := range ops {
n, ok := modulator(name, "amplitude")
if !ok || n < extendedOnly {
continue
}
if depth, ok := parseNumber(v); ok {
a *= depth / 100 * e.shape(ops, "amplitude", n, cc(n))
}
}
return a
}
// 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.
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.
func (e evaluator) shape(ops Opcodes, target string, n int, x float64) float64 {
c, ok := e.curves[e.curveIndex(ops, target, n)]
if !ok {
c = builtinCurves[0]
}
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.
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 {
return int(v)
}
}
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.
func modulator(name, target string) (int, bool) {
rest, ok := strings.CutPrefix(name, target)
if !ok {
return 0, false
}
for _, prefix := range []string{"_oncc", "cc", "_cc"} {
if digits, ok := strings.CutPrefix(rest, prefix); ok {
n, err := strconv.Atoi(digits)
return n, err == nil
}
}
return 0, false
}
// 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
}