uvi-script
Musical event scripting with Lua
MultiSample (SampleMappingOscillator)

Overview

The MultiSample oscillator — named "MultiSample" in the host's element browser, MultiSample in the script API (element class and uvi.SampleMappingOscillator.* parameter constants) — is the same element under two names. A Sample oscillator plays one sample. A MultiSample plays a whole sample set: it holds a list of zones and picks one per note, along four axes — key, velocity, and two extra dimensions the script controls directly. That makes it the oscillator to use for multi-articulation instruments, multi-microphone sets, and round-robin variations, where the alternative would be one keygroup per articulation and a script juggling layers.

The zone list comes from a mapping file on disk (.dmap, .xml or .sfz). The program normally carries it — the oscillator's MappingPath is saved with the preset and loaded with it — and a script can load another one at run time. This guide covers the file format, the script API that loads mappings and dispatches notes into them, and what happens when a program loads, which decides where the loading belongs.

Note
A script cannot create a MultiSample oscillator — no scripting call inserts an element. It drives one the program already carries: load a mapping, purge zones, route notes. Inserting one is a user action, from the element browser, where the oscillator is listed as "MultiSample" (searching the browser for keymap, zones, layers or velocity finds it).

The dispatch model

The four axes

Every zone in a mapping declares a key range, a velocity range, and a position on two further axes:

axis meaning
key the zone's MIDI key range, lowKey … highKey
velocity the zone's velocity range, lowVel … highVel
dim1 the logical layer — articulation, microphone, dynamic level
dim2 the round-robin variant inside that layer

A note-on carries key and velocity as usual, and may carry dim1 and dim2 as extra fields — see Dispatching notes. Exactly one zone is selected, and the voice plays that zone's sample.

When a note-on carries no dimensions at all, dim1 is 0 and dim2 is chosen by the round-robin policy. A single-layer mapping therefore plays from plain MIDI notes with no dispatch code at all, leaving the script nothing to do but load it. The dimensions come in once one oscillator has to cover several articulations or several takes.

Note
The MIDI channel is deliberately not used as a fallback for dim1. Dimensions are only ever what the script puts in the event.

Which zones can sound

A zone is a candidate only when it is loaded and not purged. Both conditions matter in practice:

  • while a mapping loads, a note whose zone has not arrived yet is silent. Zones become playable one by one as their samples finish, so a mapping half-way through loading is partly audible, not mute — and until the new mapping is published at all, notes still play the previous one;
  • notes routed to a purged layer are silent until the layer is unpurged.

Neither case is an error and nothing is reported. The note still allocates a voice, which finds no zone to play and is dropped silently on its first block — so it produces no sound but was counted against the polyphony first. The same goes for a note whose zones all lie outside the dim1 / dim2 the script pins on it.

A key the mapping does not cover at all is a different case. When no zone, on any layer and in any variant, spans the note's key and velocity, the keygroup does not trigger: no voice is allocated, so the note does not count against the polyphony, steal a voice or cut an exclusive group. In the two morphing dynamics modes, Continuous and Velocity XFade, the velocity is not part of that test — any zone on the key keeps the note. A keygroup holding several oscillators triggers as soon as one of them, not bypassed, can play the note. An oscillator with no mapping at all produces no voice. When a mapping seems mute, check the load state first.

Note
This applies to real-time playing. An offline render is allowed to block, so a note triggered there waits for its zone instead of dropping it. A mapping that sounds full in a bounce but has a silent attack live is showing you the difference, not a bug in either — see Live playing and offline renders.

Round robin

When several zones match (key, velocity, dim1) — that is, when the layer holds several dim2 variants — the SampleMappingOscillator::RoundRobinMode parameter decides which one plays:

value mode behaviour
0 First always the lowest dim2
1 Cycle successive notes walk the variants in order (default)
2 Random a variant is drawn at random

Passing an explicit dim2 bypasses the policy entirely: the script has already named the variant it wants.

The Cycle counter belongs to the matching zones, not to the key: the first zone of the set holds it, so a zone spanning several keys walks one sequence across all of them, and purging that zone hands the walk to the next zone's own counter — usually a fresh one, unless that zone was already the head for other keys.

Mapping files

The extension selects the parser: .dmap and .xml are read as the UVI mapping format described below, .sfz as the SFZ subset. Any other extension is rejected.

The .dmap format

A mapping file is a layers root holding layer elements, each holding zone elements. The common shape is a single layer of key-split zones — a multisampled instrument, no dimensions involved:

<?xml version="1.0" encoding="utf-8"?>
<layers channelMax="2">
<layer name="default">
<zone path="../../Samples/Strings/Strings-C2.wav" baseNote="48"
lowKey="0" highKey="51" lowVel="1" highVel="127"/>
<zone path="../../Samples/Strings/Strings-C3.wav" baseNote="60"
lowKey="52" highKey="63" lowVel="1" highVel="127"/>
<zone path="../../Samples/Strings/Strings-C4.wav" baseNote="72"
lowKey="64" highKey="127" lowVel="1" highVel="127"/>
</layer>
</layers>

Layers and round-robin variants are what the extra dimensions address. Adding a second layer and a second take per zone:

<layers>
<layer name="sustain">
<zone path="Samples/vln_sus_C4_p.wav" baseNote="60"
lowKey="58" highKey="62" lowVel="1" highVel="63"/>
<zone path="Samples/vln_sus_C4_f.wav" baseNote="60"
lowKey="58" highKey="62" lowVel="64" highVel="127"/>
</layer>
<layer name="staccato">
<zone path="Samples/vln_stac_C4_a.wav" baseNote="60"
lowKey="58" highKey="62" rr="1"/>
<zone path="Samples/vln_stac_C4_b.wav" baseNote="60"
lowKey="58" highKey="62" rr="2"/>
</layer>
</layers>

dim1 0 is now the sustain layer, split into two velocity zones; dim1 1 is the staccato layer, with two round-robin variants (dim2 0 and 1) over the full velocity range.

A layer's dim1 is its position in the file**, counted from 0 in order of appearance. The name attribute is for people: the editor shows it next to the layer's zones, but nothing dispatches on it and no script call reads it.

zone attributes:

attribute type default notes
path string — required; relative to the mapping file's own folder, or absolute
lowKey / highKey 0…127 0 / 127 key range
lowVel / highVel 1…127 1 / 127 velocity range
baseNote 0…127 60 the sample's root note
rr ≥ 1 1 round-robin index; dim2 is rr - 1
tune number 0 fine tune in cents, on top of baseNote
gain number 0 zone gain in dB
purged 0 / 1 0 when 1, the zone is not loaded with the mapping
streaming 0 / 1 1 stream the sample from disk rather than hold it in memory
maxSampleStart number 0 ms; how far into the sample a voice may start, see Starting a note inside the sample
start / end frames sample play region; end is inclusive (the last frame played)
reverse 0 / 1 sample play the region backwards
loopMode name sample no_loop, one_shot, loop_continuous or loop_sustain, as SFZ loop_mode
loopType name sample forward or alternate (ping-pong)
loopStart / loopEnd frames sample loop points; loopEnd is inclusive
loopXfade frames sample loop crossfade length; 0 turns the sample's crossfade off
loopXfadeCenterX / loopXfadeCenterY 0…1 sample the crossfade curve's control point

Key, velocity and baseNote values outside their ranges are clamped; tune, gain and maxSampleStart are taken as written (maxSampleStart floors at 0). A zone whose key or velocity range is inverted (lowKey above highKey) or whose path is missing is skipped silently, so a typo costs you one zone rather than the whole file. Backslashes in a path are read as folder separators, so a mapping written on Windows loads unchanged elsewhere.

A zone may also carry a <velFilter> child, the per-zone timbre correction described in Velocity dynamics.

tune is where a tuning table belongs: per-zone cents are applied once when the zone is picked, which is cheaper than correcting pitch on every note the script plays.

The mapping and the sample file each own half of a zone. Root note, tune, gain and the key and velocity ranges come from the mapping alone: whatever root key, fine tune or ranges the sample file stores are ignored, and a zone without baseNote plays with root 60 whatever the file says. The playback points go the other way: the loop, its mode and crossfade, and the start and end points are read from the sample file every time the zone loads, unless the zone overrides them. Sample file metadata lists which chunks count, format by format.

Playback overrides

The attributes from start down in the table above override the sample file's playback options for one zone. Each is independent: whatever a zone leaves out still comes from the file, and a zone with none of them plays the file's options untouched, as every mapping did before they existed. Positions are in frames of the sample file, counted from 0, and both ends — end and loopEnd — are inclusive**, the last frame played, as in SFZ.

<zone path="Samples/pad_C3.wav" baseNote="48" lowKey="36" highKey="59"
start="512" end="176399"
loopMode="loop_continuous" loopType="forward"
loopStart="44100" loopEnd="132299" loopXfade="4410"/>

The loop rules are those of the SFZ subset below: without loopMode the zone loops only when the file carries a loop; a missing loopStart or loopEnd comes from the file's markers, or from the start or end of the play region when it has none; loop_sustain leaves the loop at note-off where loop_continuous keeps looping; and a loop shorter than three frames is dropped, the file's own loop playing instead. When only the points move, the file's loop keeps its direction and crossfade unless loopType or loopXfade say otherwise. The crossfade is counted in frames here, where SFZ counts seconds, so a zone reproduces a loop to the frame whatever the sample rate.

A region that would play nothing (end before start) is ignored and the file's points are kept. A loop never reaches outside the play region: a loop point past start or end is moved to it, the file's own loop included, and a file loop left shorter than three frames by the move is dropped. A zone with a loopXfade above 0 is loaded into memory whatever its streaming attribute says, unless its loopMode is no_loop or one_shot: a crossfaded loop cannot be streamed.

The optional channelMax attribute on layers declares the widest channel count in the set, so the oscillator can size its output bus before the first sample arrives. It is a floor, not an assertion: a wider sample still widens the bus. It can be left out, but see Purging zones for why a stereo set is better off declaring it. layers may also carry two children, <velGain> and <velXFade>, which belong to Velocity dynamics and are described there.

maxSampleStart can be written at any of the three levels and each inherits the one above: on layers it sets the default for every layer, on a layer for every zone in it, and on a zone for that zone alone. Declaring it once at the top is usually enough.

Loading fails outright — no zones, previous mapping kept — when the file cannot be parsed, when there is no layers root, or when not a single valid zone survives.

The SFZ subset

.sfz files are read with a deliberately small opcode set, enough to consume mappings exported by common sampler tools:

opcode maps to
sample the zone's sample path
lokey / hikey key range
key shorthand: sets lokey, hikey and pitch_keycenter at once
lovel / hivel velocity range (0 is clamped to 1)
pitch_keycenter baseNote
tune fine tune in cents
volume zone gain in dB
seq_position round-robin index; dim2 is seq_position - 1
group_label on a <group>: the layer's display name (ARIA extension)
loop_mode no_loop, one_shot, loop_continuous or loop_sustain
loop_start loop start, in frames
loop_end loop end, in frames, inclusive (the last frame played)
loop_crossfade loop crossfade length, in seconds

The SFZ v1 spellings loopmode, loopstart and loopend are accepted too.

Headers behave as SFZ implementations expect: <global> opcodes are inherited by every group, <group> opcodes by every region below it, and <region> produces one zone. <control> is read for default_path, which prefixes every relative sample path. Both // line comments and C-style block comments are stripped. Unrecognised opcodes are ignored rather than treated as errors.

Loops follow the SFZ rules, on top of the sample file. Unlike a .dmap, an SFZ region can set its own loop, and every loop opcode it leaves out falls back to the sample file:

  • without loop_mode, the zone loops only when the sample file carries loop markers — the file's loop plays as it is, unless loop_start, loop_end or loop_crossfade move it;
  • without loop_start or loop_end, the point comes from the file's markers and, when the file has none, from the start or end of the sample, so loop_mode=loop_continuous alone loops a marker-less sample over its whole length;
  • loop_continuous keeps looping through the release; loop_sustain leaves the loop at note-off and plays on to the end of the sample;
  • one_shot ignores the loop and the note-off alike: the sample always plays to its end, and the amplitude envelope is not released — as long as the MultiSample is the first oscillator of its keygroup, the one whose answer the keygroup asks at note-off;
  • no_loop plays straight through, even when the file carries a loop.

The crossfade is shortened to fit: it never runs longer than the loop itself, nor further back than the start of the sample, so a loop starting at frame 0 cannot crossfade. A loop shorter than three frames is dropped and the zone keeps the sample file's own loop settings. When only the points move, the file's loop keeps its direction (forward or alternating) and its crossfade.

Three limits of the subset are worth knowing before pointing it at a file you did not write. Values must be numbers: a note name such as lokey=c1 does not parse and silently leaves the inherited value in place — except on key, where an unparseable value collapses the region to note 60. Opcodes written before the first header are discarded, <master> is ignored altogether, and a second <global> replaces the first rather than adding to it.

Each <group> becomes a dim1 layer**, in order of appearance, so a single-group file — the common case — stays at dim1 0 and a multi-group file becomes a multi-layer mapping with no extra markup. Zones from an SFZ file are streamed, except those with a loop_crossfade, which are loaded whole (a crossfaded loop cannot be streamed), and they never start purged.

Path resolution

Two resolutions happen, and it is worth keeping them apart.

The zone paths inside a mapping file resolve against the folder holding that mapping file. A mapping in Mappings/violin.dmap with a zone path of Samples/vln_C4.wav reads Mappings/Samples/vln_C4.wav. Absolute paths are used as they are.

The mapping path passed to the script is tried against several bases, and the first one that exists wins:

  1. the path exactly as written;
  2. the folder holding the script;
  3. the folder holding the program;
  4. the folder holding the performance;
  5. the program's original folder;
  6. the samples folder declared by the program's volume, when it lives in one.

When none of them exists the string is passed on as written, and the load fails on it.

So a script shipped next to its mappings, and a script shipped next to the program that loads them, can both just say "Mappings/violin.dmap".

A path saved in a program is a third case, and the one that applies when a patch carries its mapping instead of loading it from script. It resolves against the program's root — but a plain-XML .uvip does not set that root, so a relative path saved in one is tried against the working directory and will normally miss. Store an absolute path, or a $Volume-prefixed one, which resolves on every load route. A program that cannot find its saved mapping still loads: silently, with no zones, and with MappingPath still reporting the stored string. An oscillator that is mute on a freshly opened patch is worth checking against that.

Velocity dynamics

Falcon 27 adds a second way for velocity to reach the sound. A multisampled instrument is recorded at a few dynamic levels, and the dispatch model above picks one of them per note: velocity selects the zone, and whatever the recording did not capture between two levels is left to the amp envelope's velocity amount. The oscillator can instead treat the recorded levels as a ladder and crossfade between two neighbouring rungs, continuously, from a position the performer moves while the note sounds. That is what a real crescendo on a held note needs, and what a shelf EQ can only imitate.

Three things cooperate, and each is declared where it belongs: the mode is an oscillator parameter; the crossfade shape and the level law are declared once in the mapping file, because they follow from how the set was recorded; and an optional per-zone timbre correction smooths the seam between layers in the plain mode.

Note
Velocity dynamics are a Falcon 27 feature. On a host without it the seven parameters below do not exist — hasParameter("DynamicsMode") returns false and setParameter on their names does nothing, silently — and a mapping's <velGain>, <velXFade> and <velFilter> elements are read past and ignored.

The three modes

The DynamicsMode parameter selects how velocity reaches the ladder:

value mode behaviour
0 Velocity one zone per note, selected by velocity (default)
1 Continuous velocity selects nothing; Morph is the position on the ladder, 0 lowest rung to 1 highest
2 Velocity XFade the played velocity sets the position at trigger; VelMorph is a bipolar offset on top, −1 … 1

Velocity** is the model described so far. Continuous hands the whole dynamic to a control: the note velocity is ignored for layer selection and Morph alone says where on the ladder the voice sits; the ladder can be any set ordered by velocity range, e.g. a hi-hat from closed to open. Velocity XFade keeps the played velocity as the base position and lets VelMorph push it either way, scaled so that +1 always reaches the loudest rung and −1 the softest whatever the base — 0 means "as played", which is the right rest position for a wheel or a pressure control.

In both morphing modes the voice sits between two rungs and plays both, with weights that follow the position; every other rung of the ladder advances in step, silently, so that moving the control later lands on a layer exactly in time with the ones sounding. A moving Morph or VelMorph is smoothed by the engine and rendered in short slices of 32 samples: the position is re-read on every slice, ramped across it, and a step between two slices is capped at one rung, so a layer never jumps from silent to full at once.

Two more parameters shape the position. DynamicRange (0 … 1, default 1) restricts it to the top of the ladder, so 0.5 leaves the softest half out of reach. Curve (0.25 … 4, default 1) bends it: above 1 the soft rungs get more of the travel, below 1 the loud ones. In Continuous mode they act on Morph. In Velocity XFade they act on the velocity base only — the VelMorph offset is added afterwards, unshaped, so a wheel pushed to −1 still reaches the softest rung whatever DynamicRange says. Both are exact passthroughs at their defaults, and neither has any effect in Velocity mode.

What makes a ladder

Nothing in the file declares a ladder. At trigger, the oscillator gathers every zone of the dim1 layer that covers the played key, across the whole velocity axis, and sorts them by velocity range. The morph engages when that set is a clean ladder, and silently falls back to the single-zone Velocity path for that voice when it is not:

  • at least two zones, all loaded and not purged — so purging rungs shrinks the ladder, and purging down to one rung turns the morph off for those keys;
  • velocity ranges that do not overlap. Zones sharing an identical range are round-robin variants and collapse to the lowest rr; a range that partially overlaps its neighbour is not a ladder;
  • rungs recorded alike: same channel count and sample rate, same loop (presence, points, crossfade length), same direction, release behaviour and start position, same baseNote and tune. Lengths may differ, except in reverse play: a rung that ends plays silence until the longest one ends;
  • at most 32 rungs, and at most 64 zones stacked on the key before variants are collapsed.

Round robin and morphing are therefore exclusive unless the note names its variant: with an explicit dim2 the ladder is built from that variant alone; otherwise RoundRobinMode is not consulted and the first variant plays.

Note
Switching DynamicsMode only affects the notes to come. Loading a mapping whose ladder is deeper or shallower than the previous one while a morphing mode is active cuts every voice of the keygroup — at publish when the file declares channelMax, otherwise once its last zone has loaded.

The crossfade shape

The default fade is a linear tent: the two weights sum to one, which is the law phase-aligned layers need, since their sum is what must stay constant. Layers recorded as independent takes need constant power instead, or the middle of the fade dips. The mapping declares which, once, on layers:

<layers channelMax="2">
<velXFade type="power" center="0.7071"/>
...
</layers>

center is the gain each layer carries at the middle of the fade: 0.5 is the linear tent, and the default when the element is absent; 0.7071 is constant power; values up to 0.9 make a pair sum hot. It is clamped to 0.5 … 0.9. This is deliberately not a parameter — the right shape follows from how the set was recorded, and no performance decision rides on it.

The velocity level law

Loudness across the ladder is a separate matter from which rungs play. The mapping can carry a velocity-to-gain law, calibrated against the set, so the data is self-contained and the preset's amp envelope can keep its velocity amount at 0:

<layers>
<velGain type="db" range="42.6" curve="1.13" rangeKeyTrack="0"/>
...
</layers>
attribute default meaning
range 0 dB dropped from the loudest velocity down to the softest; 0 disables the law
curve 1 exponent shaping that drop, 1 being dB-linear; floored at 0.01
rangeKeyTrack 0 dB added to range per octave above middle C, taken away below it

The law is gain_dB = -range × (1 - velocity/127)^curve, with range extended by the key tracking. It applies in every mode: in Velocity mode to the picked zone, in the morphing modes as a function of the morph position rather than the played velocity — the rungs are expected to be loudness-normalised, so the law owns the level and the crossfade does not count it twice.

The file's values are calibrated defaults. Every mapping load seeds the oscillator's VelGainRange, VelGainCurve and VelGainKeyTrack parameters from them, and those parameters own the law until the next load seeds them again. A value saved in the program is re-applied on top when the program opens; a script that wants its own law must set it after loadMapping has reported, not before.

Per-zone timbre correction

In Velocity mode the seam between two rungs is audible as a timbre step: the loudest note of the softer zone sits next to the softest note of the louder one. A zone can carry a correction that tilts it toward its softer neighbour as velocity falls through it:

<zone path="Samples/pno_C4_mf.wav" baseNote="60" lowKey="60" highKey="60"
lowVel="64" highVel="95">
<velFilter type="shelf" fc="1411" depth="-15.9" gain="0.7"/>
</zone>
attribute default meaning
fc 0 corner of the high-shelf cut in Hz, above which the zone is lowered by depth; 0 means no correction
depth 0 dB reached at the bottom of the zone (≤ 0); transparent at its top
gain 0 dB of make-up at the bottom of the zone, scaled the same way
static 0 dB applied at every velocity of the zone (≤ 0), for note-to-note uniformity
staticGain 0 make-up for static, constant across the zone

type defaults to shelf, so the attribute may be left out. The other type, lp, darkens the zone with a one-pole lowpass whose corner follows velocity across it — the filter a keygroup instrument builds from a OnePole and a velocity mapper, carried by the zone instead:

<zone path="Samples/pno_C4_p.wav" baseNote="60" lowKey="60" highKey="60"
lowVel="1" highVel="40">
<velFilter type="lp" fcLow="202" fcHigh="16828" curve="1"/>
</zone>
attribute default meaning
fcHigh 0 corner in Hz at the top of the zone (highVel); 0 means no filter
fcLow fcHigh corner in Hz at the bottom of the zone (lowVel); 0 disables the filter as well
curve 1 exponent on the position in the zone, floored at 0.01

The corner is interpolated in log-frequency, the way a Freq modulation moves: with u running from 0 at lowVel to 1 at highVel (1 when the zone spans a single velocity), fc = fcLow × (fcHigh / fcLow)^(u^curve), clamped to half the sample rate. Leaving out fcLow gives a fixed lowpass. Unlike the shelf, the lowpass has no make-up gain; compensate with the zone's gain where needed. A zone carries one <velFilter>, either a shelf or a lowpass: a second one is ignored, and so is an unknown type.

Either filter is fixed for the life of the voice — velocity only exists at trigger — so there is nothing to ramp. The shelf's figures are solved offline against the sample set rather than tuned by ear, and both filters are off in the morphing modes, where the crossfade replaces them.

Driving it from script

These parameters have no uvi.SampleMappingOscillator.* constant; address them by name, which setParameter accepts:

parameter range / values default scope
DynamicsMode 0 Velocity, 1 Continuous, 2 Velocity XFade 0 element; new notes only
Morph 0 … 1 0 per voice, Continuous only
VelMorph −1 … 1 0 per voice, Velocity XFade only
DynamicRange 0 … 1 1 element, morphing modes only
Curve 0.25 … 4 1 element, morphing modes only
VelGainRange 0 … 90 dB 0 element, seeded by <velGain range>
VelGainCurve 0.25 … 4 1 element, seeded by <velGain curve>
VelGainKeyTrack −6 … 6 dB per octave 0 element, seeded by <velGain rangeKeyTrack>

The ranges are the declared ones, which the UI and automation respect. DynamicsMode, Morph, VelMorph and DynamicRange clamp a script value to them; Curve and the three VelGain parameters store what they are given and only floor the curves at 0.01 and the range at 0 when they use them.

Morph and VelMorph are the ones to move while notes sound, each in its own mode. They are held per voice, so a modulation assigned to them in the program — a CC, aftertouch, MPE pressure — reaches each voice on its own; and they behave like a filter cutoff, not like a sample start: setting one from a script moves the voices already playing, from their next block on, rather than only the notes to come. At ratio 1, a CC sweeps Morph 0 … 1 and a bipolar source sweeps VelMorph −1 … 1. The other six are element-wide.

-- Sustained articulations morph under the mod wheel; one-shots stay in
-- Velocity mode, where a voice costs one stream.
local SUSTAINED = { true, false, false } -- one flag per dim1 layer
local function selectArticulation(index)
currentDim1 = index - 1
-- 2 = Velocity XFade, 0 = Velocity. Sounding voices keep their mode.
osc:setParameter("DynamicsMode", SUSTAINED[index] and 2 or 0)
end
function onController(e)
if e.controller == 1 then
-- centre = as played; either end reaches the softest / loudest rung
osc:setParameter("VelMorph", (e.value - 64) / 64)
end
end
void onController(table e)
event callback that will receive all incoming control-change events when defined.

setSampleOffset still works in the morphing modes, with one offset for the whole voice: the rungs must stay time-aligned, so the smallest maxSampleStart budget among the streamed rungs bounds all of them.

What it costs

In the morphing modes every rung of the ladder streams for every voice. Only the two around the position produce output; the others advance so that they are in time when the position reaches them, and each is a disk stream of its own. An eight-layer violin voice runs eight streams, not two. Every voice reserves its stream set as soon as the mode is not Velocity and the mapping holds a ladder at all, sized to the deepest ladder in the mapping whatever key the voice plays — unused slots are never triggered, so they cost memory, not disk. Keep the morphing modes for the articulations where a swell means something — sustains, rolls, loops — whose polyphony is low, and leave one-shots in Velocity mode.

Scripting the oscillator

Reaching the oscillator

The oscillator is reached by walking the engine hierarchy, like any other (see Engine):

local osc = Program.layers[1].keygroups[1].oscillators[1]
if osc.type == "SampleMappingOscillator" then
print(osc:getNumZones(), "zones loaded")
end
A Patch that represents a monotimbral instrument.
Definition Engine.cpp:350
table layers
Layer list for this Program (1-indexed, use #Program.layers to get the count)
Definition Engine.cpp:359
Warning
Check type before calling anything. Every method below exists only on this class, so on any other oscillator the call is not a no-op — the member is nil, which raises an error and kills the script. The guard is mandatory whenever the oscillator's type is not certain, such as a keygroup a user could have edited.

Loading a mapping

osc:loadMapping(path) starts a load and returns immediately — the samples arrive on a background thread. What you wait on is getLoadingStatus: it drops to 0 the moment a load is requested and climbs back to 1 when every zone has finished, so the same value both paces the wait and feeds a progress bar.

osc:loadMapping("Mappings/violin.dmap")
spawn(function()
while osc:getLoadingStatus() < 1.0 do
progressBar:setValue(osc:getLoadingStatus(), false)
wait(30)
end
progressBar.visible = false
end)
function wait(ms)
suspend the current thread callback execution for the given number of milliseconds.
Definition wrapper.lua:39
function spawn(fun,...)
Launch a function in a separate parallel execution thread (deferred execution)
Definition api.lua:1338

Whether the mapping actually loaded is a separate question, and a second argument answers it. Pass a function and it is called with the task once the load finishes, the same shape loadSample takes:

osc:loadMapping("Mappings/violin.dmap", function(task)
if not task.success then print("mapping missing or unreadable") end
end)

Pass true instead of a function to get the AsyncTask without a callback, for a script that would rather poll task.success itself. So the status is how you wait, and the callback is how you learn whether it worked.

Before writing either, be clear about when a script loads a mapping. Not in onInit for the program's own content — the program carries that mapping in MappingPath, and the engine loads it with the preset, before any script code runs. A mapping loaded from onInit instead only exists some time after the first notes have been handled, which live means silent notes and in a preview render means a silent preview; Program load and warm-up explains the sequence. A script loads a mapping when it switches one at run time — the player picks another instrument, another layer, another sound — and that is where the progress readout earns its place, because the samples are arriving while the player waits.

Which makes the guard the first thing in the function. A persistent widget's changed callback also fires while a preset is being restored, and re-loading then would re-hit the disk for a mapping the program already holds — the same userReady flag IRLoader uses:

local userReady = false -- flipped in onInit, after preset state is restored
local function loadInstrument(name)
if not userReady then return end
-- The mapping is about to be replaced: silence the layer and stop
-- triggering, since notes played against a half-loaded mapping are silent.
postEvent{ type = Event.ControlChange, controller = 120, value = 0, layer = 1 }
loading = true
progressBar.visible = true
osc:loadMapping("Mappings/" .. name .. ".dmap", function(task)
if not task.success then print("could not load", name) end
end)
spawn(function()
while osc:getLoadingStatus() < 1.0 do
progressBar:setValue(osc:getLoadingStatus(), false)
wait(30)
end
progressBar.visible = false
loading = false
end)
end
instrumentMenu.changed = function(self)
loadInstrument(self.selectedText)
end
function onInit()
-- The program's mapping was loaded with the preset; its samples may still
-- be arriving, but that is the engine's business, not a reason to wait here.
userReady = true
end
Event types.
Definition Engine.cpp:905
void onInit()
initial callback, called once if the script was successfully analyzed.
function postEvent(e, delta)
send a script event back to the script engine event queue.
Definition api.lua:959

The poll has to live in a spawn or a run — a widget callback is not a script thread, so it cannot wait itself.

Note
loadMapping's return value is not a success indicator: it says the request was accepted and nothing more, so if osc:loadMapping(p) then only ever fails on an empty path. Pass a callback when you want the outcome.

Loading a mapping replaces whatever the oscillator held before. Notes already sounding keep playing on the old zones until they end, so a swap under the player's fingers will not glitch — which is why the example above still silences the layer explicitly: the aim is to stop new notes from landing on a mapping that is only half there. clearMapping drops everything instead, cutting every voice of the keygroup and clearing MappingPath.

Warning
Two swaps do cut sounding voices. One is a change of ladder depth while a morphing mode is active, covered in Velocity dynamics. The other is a change of channel width: when the new mapping settles on a different bus width than the old one — a mono set after a stereo one, or the first stereo mapping over an empty oscillator — every voice of the keygroup is dropped at that moment, because the per-voice effect state was sized for the old bus. That holds when this oscillator is what sets the keygroup's width; a sibling stereo oscillator in the same keygroup holds the bus open. Give every mapping the script switches between the same channelMax and the width never moves.

Parameters

Set like any other element parameter (see Element):

The full parameter list, with ranges and defaults, is in Elements & Parameters.

osc:setParameter(uvi.SampleMappingOscillator.RoundRobinMode, 2) -- Random
osc:setParameter(uvi.SampleMappingOscillator.InterpolationMode, 2) -- Best
print(osc:getParameter(uvi.SampleMappingOscillator.MappingPath))
  • MappingPath — the mapping file the oscillator holds, as a string. Note that this is the resolved absolute path, not whatever relative string you passed to the load call. Read-only in practice: see the warning below.
  • InterpolationMode — resampling quality: 0 Lo-fi, 1 Standard (default), 2 Best.
  • RoundRobinMode — the variant policy described in Round robin: 0 First, 1 Cycle (default), 2 Random.
  • SampleStartMillisecond — per-voice sample start, covered in Starting a note inside the sample below. Reach it with setSampleOffset rather than by name; it shares its identifier with Sample, so uvi.SamplePlayer.SampleStartMillisecond and uvi.SampleMappingOscillator.SampleStartMillisecond are the same parameter.

The velocity-dynamics parameters — DynamicsMode, Morph, VelMorph and the five around them — have no constant here and are set by name; they are covered in Velocity dynamics.

Warning
Writing MappingPath does not load a mapping. The parameter's setter only records the string — it exists so a saved program can restore its path before the load runs. Assigning it leaves the oscillator playing whatever it held before while reporting the new path, which is worse than doing nothing. Load with osc:loadMapping, which sets the parameter itself. Do not read it back as a completion signal either: the worker writes it when it starts the load, and only rolls it back if the file turns out to be unparseable.

Starting a note inside the sample

setSampleOffset works on this oscillator, addressing whichever zone the voice resolved to:

function onNote(e)
local id = postEvent(e)
setSampleOffset(id, 40) -- start 40 ms into the zone's sample
end
void onNote(table e)
event callback that will receive all incoming note-on events if defined.
function setSampleOffset(voiceId, value)
changes a sample starting point in milliseconds.
Definition api.lua:658

How far in you may start depends on how the zone is held in memory, and this is where a mapping has to opt in. A zone the engine streams from disk only has its opening resident, so a voice may start no further in than the zone's maxSampleStart — which is 0 unless the mapping says otherwise, meaning a streamed zone ignores the offset entirely until you declare one. A zone held whole in memory has no such limit and honours any offset inside the sample.

Note
The limit follows how the sample is actually held, not the streaming attribute you wrote: the loader downgrades some samples to memory on its own — a sample whose loop carries a crossfade cannot be streamed and is always loaded whole — and such a zone then accepts any offset regardless of what the mapping declared. Do not read a working offset as proof that maxSampleStart was set correctly.

Declaring maxSampleStart widens the preload to cover that window, so it costs RAM per zone — the preload is shared by every voice of the zone, so the figure to declare is the furthest in you ever intend to start, not a round number. An over-budget request is not an error: the voice starts as far in as the preload allows rather than dying. The offset is also bounded by the playable window, which ends at the loop end on a looping sample rather than at the sample end. On a sample that plays in reverse the offset is taken off the end it starts from, so it still skips the opening of what you hear.

The value is consumed once, when the voice renders its first slice, so it has to be set in the same block as the note-on — which is what setSampleOffset does, it writes without smoothing. Setting it later will not scrub a sounding voice. To move future notes rather than one voice, set the parameter element-wide with osc:setParameter(uvi.SamplePlayer.SampleStartMillisecond, ms): every new voice is seeded from it.

Purging zones

Zones are purged and reloaded a layer at a time, which is how you keep a large multi-articulation set out of memory until the player needs it. Pass a negative dim2 to mean "the whole `dim1` layer":

osc:purgeZones(1, -1) -- free every sample of layer 1
osc:unpurgeZones(1, -1) -- load them back
osc:purgeZones(1, 3) -- free just the dim2 = 3 variant of layer 1

Unpurging is asynchronous: the samples arrive on a background thread, so the layer becomes audible some time after the call returns. A third argument says when — a function called once every zone of that batch is in, or true for the AsyncTask without a callback, exactly like the reporting form of loadMapping:

osc:unpurgeZones(1, -1, function(task)
if task.success then
currentDim1 = 1 -- only now is it safe to route notes here
end
end)

Take that callback rather than polling. getLoadingStatus answers a different question — how far along the mapping's loading is overall — and it still reads 1 in the window between your call and the worker picking it up, so a note fired on the strength of it lands on zones that have not arrived and plays silence.

A mapping may legitimately ship with every zone purged="1": that is the shape to use for a large multi-articulation set, where the program carries the whole map and the script unpurges only what the current preset needs.

Purges are part of the program: saving it records every purged zone, and loading it replays them over the freshly loaded mapping, so a preset comes back as lean as it was left. How to combine that with an articulation switch at start-up and at run time is the subject of the recommended pattern.

Note
Purging can also move the bus width, with the same consequence as a mapping swap: when the last stereo zones of a set are purged and the mapping declares no channelMax, the bus narrows and every voice of the keygroup is cut — and unpurging them back widens it and cuts again. An SFZ mapping cannot declare one, so it is always exposed; a .dmap whose channelMax matches its widest sample is immune.
Warning
None of the generic sample calls reach this oscillator, and they fail in three different ways — which is the trap. purge and unpurge do nothing at all, yet their task still reports success == true, so a script that trusts it concludes a purge happened. purged always reads false, whatever you purged, and sampleInfo reads nil. loadSample and setPlaybackOptions do not silently fail: they raise and kill the script, because this oscillator is not a SampleBasedOscillator. Use purgeZones / unpurgeZones, and load through the mapping.

Dispatching notes

dim1 and dim2 are extra fields on a note-on event table handed to postEvent —

function onNote(e)
e.dim1 = currentArticulation
local id = postEvent(e)
end

Adding the field to the incoming event and forwarding it is usually all it takes. Building the event from scratch works the same way:

local id = postEvent{ type = Event.NoteOn, note = 60, velocity = 100, dim1 = 2 }

Either field may be given on its own. dim1 alone selects a layer and leaves the variant to the round-robin policy — the common case. dim2 alone stays on layer 0 and names the variant. Negative values are treated as 0.

The usual note-on fields still apply: vol, pan, tune, oscIndex and id behave exactly as they do for a plain note-on.

playNote takes them too, as its two last parameters or as table fields:

playNote{note = 60, velocity = 100, duration = 500, dim1 = 2}
function playNote(note, vel, duration, layer, channel, input, vol, pan, tune, slice, oscIndex, dim1, dim2)
helper function to generate a note event.
Definition api.lua:1089

The note-off it schedules carries no dimensions — they address a note-on only. A slice trigger takes its own path through the engine and ignores both fields.

Incoming events can also carry dimensions: when the engine generates a note-on that targets specific zones, onNote sees e.dim1 and e.dim2. Both are absent on ordinary MIDI notes, so test before reading them.

Release triggers

Release samples can be played two ways, and the choice decides where they sit in the mapping.

From the patch.** A keygroup whose TriggerMode is one of the note-off modes (Off, Off+E, Off+V, Off+VE) starts its voice when the key is released. The note-on it builds from the note-off carries no dimensions, so its MultiSample plays dim1 0 with the round-robin policy choosing the variant. Release samples played this way therefore go in a keygroup of their own, with a mapping of their own that holds them on layer 0 — a release layer placed next to the sustain layers of one mapping is never reached by it. The velocity is the original note-on's, except in the two +V modes, which use the release velocity. TriggerMode is an ordinary keygroup parameter, so a script can set it too:

local rel = Program.layers[1].keygroups[2] -- the release keygroup
rel:setParameter("TriggerMode", 1) -- Off: start at note-off

From a script.** When the release samples share a mapping with the sustained ones, on a layer of their own, the script plays them itself from onRelease with playNote, naming the layer through dim1. The note-off velocity is not what release samples usually follow, so the note-on velocity is kept from onNote when the key goes down:

local releaseLayer = 1 -- dim1 of the release samples in the mapping
local velocities = {}
function onNote(e)
velocities[e.note] = e.velocity
end
function onRelease(e)
postEvent(e) -- release the sustained voice
playNote{note = e.note, velocity = velocities[e.note] or 64,
duration = 2000, dim1 = releaseLayer}
end
void onRelease(table e)
event callback executed whenever a note off message is received.

Defining onRelease means the script forwards the note-off itself, hence the postEvent(e). The duration is how long the release voice is held before its own note-off, which carries no dimensions either.

Either way, a key with nothing to release costs nothing when its mapping has no zone on that key at all: the keygroup is skipped and no voice is allocated (see Which zones can sound). With the script pattern the mapping covers the key on its sustain layer, so a release note on a key the release layer lacks still allocates a voice, which is then dropped silently.

Pitfalls

These all come from the same place — loading is asynchronous, and the calls that look synchronous are weaker than they appear.

Warning
getNumZones describes the mapping that is currently live, not the one you just asked for. A requested mapping only becomes live once the worker thread has parsed it, so a getNumZones read taken right after a load call still counts the previous mapping's zones, or returns 0 when none was loaded. Read it after the wait, not before. getLoadingStatus is the exception and is safe to wait on for a mapping load: it reports 0 from the moment loadMapping is called. That guarantee is specific to loadMapping — it does not extend to unpurgeZones, which reports through its completion argument instead (see Purging zones).
A failed load is invisible without a callback. A missing file, a malformed mapping, or a mapping with no usable zone raises a "Sample Not Found" error in the host and restores the previous mapping path. Nothing about that reaches a script that did not ask: getLoadingStatus simply returns to 1 with getNumZones unchanged, and notes go on playing the previous mapping. task.success is the only way to see it — and it also reports the softer failure, a mapping that parsed but lost some of its samples. That mapping is published, with the zones that did load, MappingPath keeps the new path, and one error is raised per missing sample — the first 32, then a single summary. So success == false does not mean the old mapping is still there; read getNumZones to know what you have.
Note
waitForLoading blocks its calling thread, and script code runs on the audio thread — calling it from a script interrupts audio. It also returns immediately when the load it was meant to wait for has not been picked up yet. Take the completion callback, or poll getLoadingStatus after a loadMapping; there is no good reason to call it from a script.

Program load and warm-up

A MultiSample instrument that is silent on its first notes, or renders a silent preview, is almost always doing its loading in the wrong phase. The phases are fixed, and they decide what a script can rely on and when.

The load sequence

When a program is opened, things happen in this order:

  1. Every MultiSample oscillator with a MappingPath loads its mapping, before any script code runs. The mapping structure is complete when this step ends: the zones and the lookup that picks them are in place, and the purge state saved with the program has been replayed. The samples are not: their loads are only submitted, so they may still be arriving while the script initialises and while the first notes come in. Zones marked purged="1", or saved purged, are part of the lookup but are not loaded at all. A mapping file that cannot be found leaves the oscillator with no zones and reports nothing (see Path resolution).
  2. The script's main chunk runs — the only place widgets can be created.
  3. Saved widget and parameter values are restored, and each restored widget's changed handler fires.
  4. onLoad is called with the state onSave returned, synchronously.
  5. onInit starts on the first audio block, as a thread of its own. It runs up to its first wait before the first note of that block is handled.

Nothing in this sequence holds notes back until the samples are in.

Script callbacks and threads run on the audio thread, and wait counts audio time — samples rendered, not seconds on the clock. In an offline render running faster than real time, wait(30) is 30 ms of rendered audio and a small fraction of that in wall time. So a wait is never a loading delay: it is too long on a fast disk, too short on a slow one, and next to nothing in a bounce.

Live playing and offline renders

The two situations treat an unfinished load differently.

  • Live, a note on a zone that is purged or not loaded yet allocates a voice that is dropped silently — no sound, but one voice counted against the polyphony. An oscillator with no mapping at all produces no voice. Loading is asynchronous, and a completion only tells you the zones were loaded: the first blocks of a streamed sample can still be on their way from disk. A note played in the first moments after an unpurgeZones or a loadMapping can therefore still be dropped. That is the time the load takes, not an error.
  • Offline — a DAW in offline rendering (bounce, export), a preset preview, a command-line render — the engine blocks at note trigger until the oscillator's queued mapping work (loadMapping, purgeZones, unpurgeZones, clearMapping), the zone loads it started and the sample data the note needs are in, so the note renders with its sample. The engine handles the asynchronous load itself; the script has nothing to add.

What offline rendering does not make deterministic is the script's view of the load. A loadMapping or unpurgeZones completion, and a getLoadingStatus poll, land at a position in the rendered audio that depends on how fast the machine loaded the files. A script that drops or holds notes until such a callback has fired therefore renders differently from one run to the next, and can lose the opening notes of a preview entirely. The pattern below never gates notes: it keeps routing to a layer that is known to be there.

The recommended pattern

  1. Let the program own the mapping. Load it on the oscillator in the program and save the program, so MappingPath is restored with the preset and step 1 above does the loading. In a plain-XML .uvip, store the path in a form that resolves on every load route — absolute or $Volume-prefixed, see Path resolution.
  2. Mark what is not needed at start-up purged="1" in the .dmap, or save the program with those layers purged. The mapping stays complete; only the samples are left on disk.
  3. **In onInit, unpurge the active articulation with no completion and no wait.** Live, that is the earliest the request can be made; offline, the notes that follow block until it is done.
  4. At run time, switch in the completion. Unpurge the new layer with a completion, route notes to it from inside that completion, and purge the layer you left only after that. Until the completion fires, notes keep playing the layer that is loaded.
local osc = Program.layers[1].keygroups[1].oscillators[1]
local ARTICULATIONS = { "Sustain", "Staccato", "Pizzicato" }
local userReady = false -- lifted in onInit, once the preset is restored
local currentDim1 = 0 -- the layer notes are routed to: always a loaded one
local wantedDim1 = 0 -- the layer last asked for
local function purgeAllBut(keep)
for i = 1, #ARTICULATIONS do
if i - 1 ~= keep then osc:purgeZones(i - 1, -1) end
end
end
artMenu = Menu{"Articulation", ARTICULATIONS}
artMenu.changed = function(self)
local dim1 = self.selected - 1
wantedDim1 = dim1
if not userReady then return end -- preset restore: onInit takes it from here
osc:unpurgeZones(dim1, -1, function(task)
-- A later choice overtook this one: its own completion will settle it.
if not task.success or wantedDim1 ~= dim1 then return end
currentDim1 = dim1
purgeAllBut(dim1)
end)
end
function onNote(e)
e.dim1 = currentDim1
end
function onInit()
wantedDim1 = artMenu.selected - 1
currentDim1 = wantedDim1
-- The mapping came with the program. Ask for the active layer and move on.
osc:unpurgeZones(currentDim1, -1)
userReady = true
end
Menu widget.
Definition ui.cpp:1359
function changed
callback function used by child widgets to be notified of changes.
Definition ui.cpp:1001

Purging every other layer, rather than just the previous one, keeps the result right when the player switches again before a completion has arrived. Leaving the previous layer resident is a valid choice too — it makes switching back instant, at the cost of its memory.

Gotchas

  • **Do not loadMapping the program's main content in onInit.** The mapping then only exists after the first notes have been handled: silent notes live, and in an offline render a completion whose position in the audio depends on the machine.
  • Do not wait for an unpurgeZones on getLoadingStatus. It can still read 1 until the worker picks the request up; take the completion instead. getLoadingStatus is only safe to wait on right after loadMapping.
  • **Do not use wait as a loading delay**, and do not call waitForLoading from a script: it blocks the audio thread.
  • Do not gate notes on a completion flag if the instrument has to render the same way twice. Route to a loaded layer instead of dropping notes, as the pattern above does.
  • Guard disk work in persistent widgets' handlers. They fire while the preset is restored (step 3), before onInit; a flag lifted in onInit keeps them from reloading what the program already carries.
  • The first stereo mapping over an empty oscillator cuts the keygroup's voices, and so does any change of bus width; declare channelMax (see Loading a mapping).
  • Writing MappingPath does not load anything, and the generic purge / unpurge / loadSample do not apply to this oscillator (see Parameters and Purging zones).

What stays in memory

Zones stream by default (streaming="1"). A streamed zone keeps only a preload — the opening of the sample — in memory, and the rest is read from disk while a voice plays. The preload length is the user's streaming preference, in the range of about 0.05 to 0.6 s; the default for an SSD is 0.2 s, 0.1 s for compressed samples. maxSampleStart widens it (see Starting a note inside the sample). A zone with streaming="0" is loaded whole, and so is any sample whose loop carries a crossfade, which cannot be streamed.

Purging frees what a zone holds; unpurging a streamed zone loads its preload back, and the rest streams again when a voice plays it. The memory a layer costs while resident is therefore its preloads plus its unstreamed samples, not the size of its files on disk.

A complete example

MappingArticulations in the example gallery puts the whole guide together: it loads a mapping asynchronously with a progress readout, selects the articulation with a menu, routes notes to it through dim1, and purges the layers that are not in use.

See also
MultiSample, Oscillator, Asynchronous Operations, postEvent