diff --git a/model.go b/model.go index 3b70f82..4a4f2ca 100644 --- a/model.go +++ b/model.go @@ -2,19 +2,19 @@ package sfz // Envelope is a region's amplitude envelope. Times are in seconds. type Envelope struct { - Delay float64 - Attack float64 - Hold float64 - Decay float64 + Delay float64 `json:"delay" doc:"How long the region waits before its attack starts, in seconds." minimum:"0"` + Attack float64 `json:"attack" doc:"How long the level takes to rise to full, in seconds." minimum:"0"` + Hold float64 `json:"hold" doc:"How long the level stays at full before it decays, in seconds." minimum:"0"` + Decay float64 `json:"decay" doc:"How long the level takes to fall to the sustain level, in seconds." minimum:"0"` // Sustain is the level held after the decay, as a percentage. - Sustain float64 - Release float64 + Sustain float64 `json:"sustain" doc:"The level held after the decay while the note is held, as a percentage." minimum:"0" maximum:"100"` + Release float64 `json:"release" doc:"How long the level takes to fall to silence once the note ends, in seconds." minimum:"0"` } // CurvePoint is how much of its level a velocity plays, from 0 to 1. type CurvePoint struct { - Velocity int - Gain float64 + Velocity int `json:"velocity" doc:"The MIDI velocity the point is at." minimum:"0" maximum:"127"` + Gain float64 `json:"gain" doc:"How much of its level the velocity plays." minimum:"0" maximum:"1"` } // The curves of a crossfade. @@ -27,11 +27,13 @@ const ( // 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 + FadeInLow int `json:"fadeInLow" doc:"The key or velocity below which the region doesn't play." minimum:"0" maximum:"127"` + FadeInHigh int `json:"fadeInHigh" doc:"The key or velocity at which the region reaches full level." minimum:"0" maximum:"127"` + FadeOutLow int `json:"fadeOutLow" doc:"The key or velocity at which the region starts to fade out." minimum:"0" maximum:"127"` + FadeOutHigh int `json:"fadeOutHigh" doc:"The key or velocity above which the region doesn't play." minimum:"0" maximum:"127"` // 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 + 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. @@ -47,16 +49,20 @@ const ( // 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 + Source string `json:"source" doc:"Where the value comes from: cc, bend, aftertouch, polyAftertouch or channel."` + Controller int `json:"controller" doc:"The controller number, when the source is cc." minimum:"0" maximum:"127"` + Low float64 `json:"low" doc:"The lowest value the region plays at, in the source's range: 0 to 1 for a controller, aftertouch and polyphonic aftertouch, -1 to 1 for pitch bend and 1 to 16 for a channel."` + High float64 `json:"high" doc:"The highest value the region plays at, in the source's range."` } // 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 + Last *int `json:"last,omitempty" doc:"The key of the keyswitch pressed last, or nil if the region doesn't depend on it."` + Previous *int `json:"previous,omitempty" doc:"The key of the keyswitch pressed before the last, or nil if the region doesn't depend on it."` + Down *int `json:"down,omitempty" doc:"A keyswitch key that must be held, or nil if the region doesn't depend on it."` + 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. @@ -71,8 +77,8 @@ const ( // 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 + 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."` } // Modulation moves a region's setting as a controller does. The controller @@ -81,28 +87,29 @@ type CurveStop struct { // 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 + Target string `json:"target" doc:"The setting the controller moves: amplitude, volume, pan, width or tune."` + Controller int `json:"controller" doc:"The controller number." minimum:"0" maximum:"127"` + Depth float64 `json:"depth" doc:"How far the controller at 1 moves the setting, in the setting's own units: percent for amplitude, pan and width, dB for volume and cents for tune."` // Curve is the index of one of SFZ's built-in curves, 0 to 6, when Points // is empty. - Curve int - Points []CurveStop + Curve int `json:"curve,omitempty" doc:"The index of the curve the controller goes through: one of SFZ's built-in curves, 0 to 6, or that of a custom curve whose points are given." minimum:"0"` + 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. type Control struct { - Controller int - Label string - Value float64 + 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."` + Value float64 `json:"value" doc:"The controller's starting value." minimum:"0" maximum:"1"` } // 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 + Low int `json:"low" doc:"The lowest key that is a keyswitch." minimum:"0" maximum:"127"` + High int `json:"high" doc:"The highest key that is a keyswitch." minimum:"0" maximum:"127"` + 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 @@ -114,106 +121,106 @@ var DefaultEnvelope = Envelope{Sustain: 100, Release: defaultRelease} 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 + Sample string `json:"sample" doc:"The sample's path, relative to the folder of the instrument's main file, with forward slashes."` + LowKey int `json:"lowKey" doc:"The lowest key that plays the region." minimum:"0" maximum:"127"` + HighKey int `json:"highKey" doc:"The highest key that plays the region." minimum:"0" maximum:"127"` + RootKey int `json:"rootKey" doc:"The key at which the sample plays at its own pitch." minimum:"0" maximum:"127"` // 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 + RootFromSample bool `json:"rootFromSample,omitempty" doc:"Whether the root note is the one the sample file holds, which RootKey doesn't know."` + LowVelocity int `json:"lowVelocity" doc:"The lowest velocity that plays the region." minimum:"0" maximum:"127"` + HighVelocity int `json:"highVelocity" doc:"The highest velocity that plays the region." minimum:"0" maximum:"127"` // 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 + KeyTrack float64 `json:"keyTrack" doc:"How far each key repitches the sample, in cents: 100 plays the keys' pitches, and 0 plays every key at the sample's own."` // Tune is in cents. - Tune float64 + Tune float64 `json:"tune" doc:"How far the sample is repitched, in cents."` // Volume is in dB. - Volume float64 + Volume float64 `json:"volume" doc:"The region's level, in dB." minimum:"-144"` // Pan is from -100, left, to 100, right. - Pan float64 + Pan float64 `json:"pan" doc:"Where the region sits in the stereo field, from -100, left, to 100, right." minimum:"-100" maximum:"100"` // Offset is where the sample starts playing, in frames. - Offset int64 + Offset int64 `json:"offset,omitempty" doc:"Where the sample starts playing, in frames." minimum:"0"` // 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 + VelocityTracking float64 `json:"velocityTracking" doc:"How much velocity sets the level, as a percentage: 100 follows it fully, and 0 plays every velocity at full level." minimum:"-100" maximum:"100"` // 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 + VelocityCurve []CurvePoint `json:"velocityCurve,omitempty" doc:"How much of its level each velocity plays, through straight lines between its points, which ascend by velocity from 0 to 127, or none if the region sets none."` // KeyCrossfade and VelocityCrossfade are nil if the region sets none. - KeyCrossfade *Crossfade - VelocityCrossfade *Crossfade - Envelope Envelope + KeyCrossfade *Crossfade `json:"keyCrossfade,omitempty" doc:"The crossfade over keys, or nil if the region sets none."` + VelocityCrossfade *Crossfade `json:"velocityCrossfade,omitempty" doc:"The crossfade over velocities, or nil if the region sets none."` + Envelope Envelope `json:"envelope" doc:"The region's amplitude envelope."` // Trigger is what starts the region: attack, when a note starts; release, // when it ends; first; or legato. - Trigger string + Trigger string `json:"trigger" doc:"What starts the region: attack, when a note starts; release, when it ends; first; or legato."` // LoopMode is no_loop, one_shot, loop_continuous or loop_sustain, or // empty to follow the sample file. - LoopMode string + LoopMode string `json:"loopMode,omitempty" doc:"How the sample loops: no_loop, one_shot, loop_continuous or loop_sustain, or empty to follow the sample file."` // LoopStart and LoopEnd are frames, or nil to follow the sample file. - LoopStart *int64 - LoopEnd *int64 + LoopStart *int64 `json:"loopStart,omitempty" doc:"The frame the loop starts at, or nil to follow the sample file." minimum:"0"` + LoopEnd *int64 `json:"loopEnd,omitempty" doc:"The frame the loop ends at, or nil to follow the sample file." minimum:"0"` // ReleaseDecay is how much quieter a release region plays for each second // its note was held, in dB. - ReleaseDecay float64 + ReleaseDecay float64 `json:"releaseDecay,omitempty" doc:"How much quieter a release region plays for each second its note was held, in dB." minimum:"0"` // 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 + SequenceLength int `json:"sequenceLength" doc:"How many notes make a round robin: of each SequenceLength notes the region matches, it plays the one at SequencePosition." minimum:"1"` + SequencePosition int `json:"sequencePosition" doc:"Which of the notes of a round robin plays the region, counting from 1." minimum:"1"` // 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 + LowRandom float64 `json:"lowRandom,omitempty" doc:"The lowest number, from 0 to 1, drawn for a note that plays the region." minimum:"0" maximum:"1"` + HighRandom float64 `json:"highRandom" doc:"The number, from 0 to 1, that the one drawn for a note must be below for the region to play." minimum:"0" maximum:"1"` // Group is the region's choke group, which other regions' OffBy names. - Group int + Group int `json:"group,omitempty" doc:"The region's choke group, which other regions' OffBy names."` // OffBy is the group whose notes stop this region while it plays, or nil // if none does. - OffBy *int + OffBy *int `json:"offBy,omitempty" doc:"The group whose notes stop this region while it plays, or nil if none does."` // 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 + Polyphony *int `json:"polyphony,omitempty" doc:"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." minimum:"1"` // 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 + Conditions []Condition `json:"conditions,omitempty" doc:"The ranges of controllers, pitch bend, aftertouch and channel that the region plays within, all of which must hold when a note starts."` + Keyswitch *Keyswitch `json:"keyswitch,omitempty" doc:"The keyswitches the region needs, or nil if it needs none."` // Modulations are the controllers that move the region's settings, which // hold their values with no controller. - Modulations []Modulation + Modulations []Modulation `json:"modulations,omitempty" doc:"The controllers that move the region's settings while a note plays. The settings hold their values with no controller."` // 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 + Width *float64 `json:"width,omitempty" doc:"The stereo width, in percent, or nil for the sample's own." minimum:"-100" maximum:"100"` + BendUp *float64 `json:"bendUp,omitempty" doc:"How far pitch bend moves the pitch up at its end, in cents, or nil for the SFZ default."` + BendDown *float64 `json:"bendDown,omitempty" doc:"How far pitch bend moves the pitch down at its end, in cents, or nil for the SFZ default."` + BendStep *float64 `json:"bendStep,omitempty" doc:"The size of the steps of pitch bend, in cents, or nil for the SFZ default."` // 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 + NotePolyphony *int `json:"notePolyphony,omitempty" doc:"How many voices of the region's group may play the same key at once, or nil if it sets none." minimum:"1"` // OffMode is how the region stops when it is stopped by a group or past a // voice limit: fast, time or normal. - OffMode string + OffMode string `json:"offMode" doc:"How the region stops when it is stopped by a group or past a voice limit: fast, time or normal."` // OffTime is how long a region whose OffMode is time takes to stop, in // seconds. - OffTime float64 + OffTime float64 `json:"offTime" doc:"How long a region whose OffMode is time takes to stop, in seconds." minimum:"0"` } // Instrument is an SFZ instrument as typed regions, with its settings taken at // the starting controller values. type Instrument struct { - Regions []Region + 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 // for, the regions that have it, or how often a header appears. - Unread map[string]int + Unread map[string]int `json:"unread,omitempty" doc:"For each opcode or header the typed model has no field for, how many regions have it, or how often a header appears."` // Skipped counts the regions that have no typed region, by why. - Skipped map[string]int + Skipped map[string]int `json:"skipped,omitempty" doc:"How many regions have no typed region, by the reason."` // Controls are the controllers that the instrument names, sets or uses. - Controls []Control + Controls []Control `json:"controls,omitempty" doc:"The controllers that the instrument names, sets or uses."` // Keyswitches are its keyswitch keys, or nil if it has none. - Keyswitches *KeyswitchRange + Keyswitches *KeyswitchRange `json:"keyswitches,omitempty" doc:"The keys that are keyswitches, or nil if the instrument has none."` } // Reasons a region is skipped: the typed model has no region for it. diff --git a/model_test.go b/model_test.go new file mode 100644 index 0000000..f888f21 --- /dev/null +++ b/model_test.go @@ -0,0 +1,133 @@ +package sfz + +import ( + "encoding/json" + "reflect" + "strconv" + "strings" + "testing" +) + +// modelTypes are the types of the typed model. +var modelTypes = []reflect.Type{ + reflect.TypeFor[Instrument](), reflect.TypeFor[Region](), reflect.TypeFor[Envelope](), reflect.TypeFor[CurvePoint](), + reflect.TypeFor[Crossfade](), reflect.TypeFor[Condition](), reflect.TypeFor[Keyswitch](), reflect.TypeFor[CurveStop](), + reflect.TypeFor[Modulation](), reflect.TypeFor[Control](), reflect.TypeFor[KeyswitchRange](), +} + +// TestModelTags checks that each field of the typed model has a unique json +// name and a description, and that its bounds are numbers, in order, on a +// field that is a number. +func TestModelTags(t *testing.T) { + for _, typ := range modelTypes { + names := map[string]bool{} + for i := 0; i < typ.NumField(); i++ { + f := typ.Field(i) + tag := f.Tag + name, _, _ := strings.Cut(tag.Get("json"), ",") + if name == "" || name == "-" || names[name] || name != strings.ToLower(name[:1])+name[1:] { + t.Errorf("%s.%s: json name %q", typ.Name(), f.Name, name) + } + names[name] = true + if doc := tag.Get("doc"); !strings.HasSuffix(doc, ".") || len(doc) < 10 { + t.Errorf("%s.%s: doc %q", typ.Name(), f.Name, doc) + } + var bounds []float64 + for _, key := range []string{"minimum", "maximum"} { + v, ok := tag.Lookup(key) + if !ok { + continue + } + n, err := strconv.ParseFloat(v, 64) + if err != nil { + t.Errorf("%s.%s: %s %q", typ.Name(), f.Name, key, v) + } + bounds = append(bounds, n) + kind := f.Type.Kind() + if kind == reflect.Pointer { + kind = f.Type.Elem().Kind() + } + if kind != reflect.Int && kind != reflect.Int64 && kind != reflect.Float64 { + t.Errorf("%s.%s: %s on a %s", typ.Name(), f.Name, key, f.Type) + } + } + if len(bounds) == 2 && bounds[0] > bounds[1] { + t.Errorf("%s.%s: bounds %v", typ.Name(), f.Name, bounds) + } + } + } +} + +// TestModelJSON checks that an instrument is the same after it goes through +// JSON, so that no field is lost to its tags. +func TestModelJSON(t *testing.T) { + for name, inst := range instruments(t) { + data, err := json.Marshal(inst) + if err != nil { + t.Fatal(err) + } + var back Instrument + if err := json.Unmarshal(data, &back); err != nil { + t.Fatal(err) + } + // An empty list and none are the same in JSON, so the comparison is of the + // text. + again, err := json.Marshal(&back) + if err != nil || string(again) != string(data) { + t.Errorf("%s: wrote %s, then %s (%v)", name, data[:min(len(data), 300)], again[:min(len(again), 300)], err) + } + if len(back.Regions) != len(inst.Regions) || back.Regions[0].Sample != inst.Regions[0].Sample { + t.Errorf("%s: regions changed", name) + } + } +} + +// TestModelBounds checks that regions read from text stay within the bounds +// their fields name. +func TestModelBounds(t *testing.T) { + inst := parseText(t, " sample=a.wav lokey=-5 hikey=300 pitch_keycenter=500 lovel=-3 hivel=999 pan=500 amp_veltrack=900 ampeg_sustain=400 ampeg_attack=-1 lorand=-1 hirand=7 seq_length=-4 seq_position=0 polyphony=0 off_time=-1") + if len(inst.Regions) != 1 { + t.Fatalf("%d regions", len(inst.Regions)) + } + var walk func(v reflect.Value, path string) + walk = func(v reflect.Value, path string) { + switch v.Kind() { + case reflect.Pointer: + if !v.IsNil() { + walk(v.Elem(), path) + } + case reflect.Slice: + for i := 0; i < v.Len(); i++ { + walk(v.Index(i), path) + } + case reflect.Struct: + for i := 0; i < v.NumField(); i++ { + f := v.Type().Field(i) + fv := v.Field(i) + switch fv.Kind() { + case reflect.Int, reflect.Int64: + checkBounds(t, path+"."+f.Name, f.Tag, float64(fv.Int())) + case reflect.Float64: + checkBounds(t, path+"."+f.Name, f.Tag, fv.Float()) + default: + walk(fv, path+"."+f.Name) + } + } + } + } + walk(reflect.ValueOf(inst.Regions[0]), "Region") +} + +func checkBounds(t *testing.T, name string, tag reflect.StructTag, v float64) { + t.Helper() + if s, ok := tag.Lookup("minimum"); ok { + if lo, _ := strconv.ParseFloat(s, 64); v < lo { + t.Errorf("%s is %v, below %v", name, v, lo) + } + } + if s, ok := tag.Lookup("maximum"); ok { + if hi, _ := strconv.ParseFloat(s, 64); v > hi { + t.Errorf("%s is %v, above %v", name, v, hi) + } + } +}