/[svn]/linuxsampler/trunk/src/engines/common/InstrumentScriptVM.cpp
ViewVC logotype

Contents of /linuxsampler/trunk/src/engines/common/InstrumentScriptVM.cpp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 3733 - (show annotations) (download)
Sat Feb 1 18:11:20 2020 UTC (4 years, 1 month ago) by schoenebeck
File size: 20535 byte(s)
NKSP: Added support for 'patch' variables.

* NKSP language: Added support for 'patch' variable qualifier
  (as new dedicated keyword 'patch').

* NKSP parser: capture locations of 'patch' variable declarations
  in script's source code.

* ScriptVM: Allow patching 'patch' script variables by replacing
  their default assignment expression with a supplied replacement
  variable initialization expression by optional 2nd argument when
  calling loadScript().

* ScriptVM: Allow retrieval of default initialization expressions
  of all 'patch' variables by optional 3rd argument when calling
  loadScript() (i.e. for instrument editors).

* gig engine: Implemented support for loading real-time instrument
  scripts with 'patch' variables bundled with gig instruments.

* Bumped version (2.1.1.svn46).


1 /*
2 * Copyright (c) 2014 - 2020 Christian Schoenebeck
3 *
4 * http://www.linuxsampler.org
5 *
6 * This file is part of LinuxSampler and released under the same terms.
7 * See README file for details.
8 */
9
10 #include "../../common/global_private.h"
11 #include "InstrumentScriptVM.h"
12 #include "../AbstractEngineChannel.h"
13 #include "../../common/global_private.h"
14 #include "AbstractInstrumentManager.h"
15 #include "MidiKeyboardManager.h"
16 #include "Fade.h"
17
18 namespace LinuxSampler {
19
20 ///////////////////////////////////////////////////////////////////////
21 // class 'EventGroup'
22
23 void EventGroup::insert(vmint eventID) {
24 if (contains(eventID)) return;
25
26 AbstractEngine* pEngine = m_script->pEngineChannel->pEngine;
27
28 // before adding the new event ID, check if there are any dead events
29 // and remove them in that case, before otherwise we might run in danger
30 // to run out of free space on this group for event IDs if a lot of
31 // events die before being removed explicitly from the group by script
32 //
33 // NOTE: or should we do this "dead ones" check only once in a while?
34 ssize_t firstDead = -1;
35 for (size_t i = 0; i < size(); ++i) {
36 if (firstDead >= 0) {
37 if (pEngine->EventByID(eventID)) {
38 remove(firstDead, i - firstDead);
39 firstDead = -1;
40 }
41 } else {
42 if (!pEngine->EventByID(eventID)) firstDead = i;
43 }
44 }
45
46 append(eventID);
47 }
48
49 void EventGroup::erase(vmint eventID) {
50 size_t index = find(eventID);
51 remove(index);
52 }
53
54 ///////////////////////////////////////////////////////////////////////
55 // class 'InstrumentScript'
56
57 InstrumentScript::InstrumentScript(AbstractEngineChannel* pEngineChannel) {
58 parserContext = NULL;
59 bHasValidScript = false;
60 handlerInit = NULL;
61 handlerNote = NULL;
62 handlerRelease = NULL;
63 handlerController = NULL;
64 handlerRpn = NULL;
65 handlerNrpn = NULL;
66 pEvents = NULL;
67 for (int i = 0; i < 128; ++i)
68 pKeyEvents[i] = NULL;
69 this->pEngineChannel = pEngineChannel;
70 for (int i = 0; i < INSTR_SCRIPT_EVENT_GROUPS; ++i)
71 eventGroups[i].setScript(this);
72 }
73
74 InstrumentScript::~InstrumentScript() {
75 resetAll();
76 if (pEvents) {
77 for (int i = 0; i < 128; ++i) delete pKeyEvents[i];
78 delete pEvents;
79 }
80 }
81
82 /** @brief Load real-time instrument script.
83 *
84 * Loads the real-time instrument script given by @a text on the engine
85 * channel this InstrumentScript object belongs to (defined by
86 * pEngineChannel member variable). The sampler engine's resource manager is
87 * used to allocate and share equivalent scripts on multiple engine
88 * channels.
89 *
90 * @param text - source code of script
91 * @param patchVars - 'patch' variables being overridden by instrument
92 */
93 void InstrumentScript::load(const String& text,
94 const std::map<String,String>& patchVars)
95 {
96 dmsg(1,("Loading real-time instrument script ... "));
97
98 // hand back old script reference and VM execution contexts
99 // (if not done already)
100 unload();
101
102 code = text;
103
104 AbstractInstrumentManager* pManager =
105 dynamic_cast<AbstractInstrumentManager*>(pEngineChannel->pEngine->GetInstrumentManager());
106
107 // get new script reference
108 parserContext = pManager->scripts.Borrow(
109 { .code = text, .patchVars = patchVars }, pEngineChannel
110 );
111 if (!parserContext->errors().empty()) {
112 std::vector<ParserIssue> errors = parserContext->errors();
113 std::cerr << "[ScriptVM] Could not load instrument script, there were "
114 << errors.size() << " parser errors:\n";
115 for (int i = 0; i < errors.size(); ++i)
116 errors[i].dump();
117 return; // stop here if there were any parser errors
118 }
119
120 handlerInit = parserContext->eventHandlerByName("init");
121 handlerNote = parserContext->eventHandlerByName("note");
122 handlerRelease = parserContext->eventHandlerByName("release");
123 handlerController = parserContext->eventHandlerByName("controller");
124 handlerRpn = parserContext->eventHandlerByName("rpn");
125 handlerNrpn = parserContext->eventHandlerByName("nrpn");
126 bHasValidScript =
127 handlerInit || handlerNote || handlerRelease || handlerController ||
128 handlerRpn || handlerNrpn;
129
130 // amount of script handlers each script event has to execute
131 int handlerExecCount = 0;
132 if (handlerNote || handlerRelease || handlerController || handlerRpn ||
133 handlerNrpn) // only one of these are executed after "init" handler
134 handlerExecCount++;
135
136 // create script event pool (if it doesn't exist already)
137 if (!pEvents) {
138 pEvents = new Pool<ScriptEvent>(CONFIG_MAX_EVENTS_PER_FRAGMENT);
139 for (int i = 0; i < 128; ++i)
140 pKeyEvents[i] = new RTList<ScriptEvent>(pEvents);
141 // reset RTAVLNode's tree node member variables after nodes are allocated
142 // (since we can't use a constructor right now, we do that initialization here)
143 while (!pEvents->poolIsEmpty()) {
144 RTList<ScriptEvent>::Iterator it = pEvents->allocAppend();
145 it->reset();
146 }
147 pEvents->clear();
148 }
149
150 // create new VM execution contexts for new script
151 while (!pEvents->poolIsEmpty()) {
152 RTList<ScriptEvent>::Iterator it = pEvents->allocAppend();
153 it->execCtx = pEngineChannel->pEngine->pScriptVM->createExecContext(
154 parserContext
155 );
156 it->handlers = new VMEventHandler*[handlerExecCount+1];
157 }
158 pEvents->clear();
159
160 dmsg(1,("Done\n"));
161 }
162
163 /** @brief Unload real-time instrument script.
164 *
165 * Unloads the currently used real-time instrument script and frees all
166 * resources allocated for that script. The sampler engine's resource manager
167 * is used to share equivalent scripts among multiple sampler channels, and
168 * to deallocate the parsed script once not used on any engine channel
169 * anymore.
170 *
171 * Calling this method will however not clear the @c code member variable.
172 * Thus, the script can be parsed again afterwards.
173 */
174 void InstrumentScript::unload() {
175 //dmsg(1,("InstrumentScript::unload(this=0x%llx)\n", this));
176
177 if (parserContext)
178 dmsg(1,("Unloading current instrument script.\n"));
179
180 resetEvents();
181
182 // free allocated VM execution contexts
183 if (pEvents) {
184 pEvents->clear();
185 while (!pEvents->poolIsEmpty()) {
186 RTList<ScriptEvent>::Iterator it = pEvents->allocAppend();
187 if (it->execCtx) {
188 // free VM execution context object
189 delete it->execCtx;
190 it->execCtx = NULL;
191 // free C array of handler pointers
192 delete [] it->handlers;
193 }
194 }
195 pEvents->clear();
196 }
197 // hand back VM representation of script
198 if (parserContext) {
199 AbstractInstrumentManager* pManager =
200 dynamic_cast<AbstractInstrumentManager*>(pEngineChannel->pEngine->GetInstrumentManager());
201
202 pManager->scripts.HandBack(parserContext, pEngineChannel);
203 parserContext = NULL;
204 handlerInit = NULL;
205 handlerNote = NULL;
206 handlerRelease = NULL;
207 handlerController = NULL;
208 handlerRpn = NULL;
209 handlerNrpn = NULL;
210 }
211 bHasValidScript = false;
212 }
213
214 /**
215 * Same as unload(), but this one also empties the @c code member variable
216 * to an empty string.
217 */
218 void InstrumentScript::resetAll() {
219 unload();
220 code.clear();
221 }
222
223 /**
224 * Clears all currently active script events. This should be called
225 * whenever the engine or engine channel was reset for some reason.
226 */
227 void InstrumentScript::resetEvents() {
228 for (int i = 0; i < INSTR_SCRIPT_EVENT_GROUPS; ++i)
229 eventGroups[i].clear();
230
231 for (int i = 0; i < 128; ++i)
232 if (pKeyEvents[i])
233 pKeyEvents[i]->clear();
234
235 suspendedEvents.clear();
236
237 if (pEvents) pEvents->clear();
238 }
239
240 ///////////////////////////////////////////////////////////////////////
241 // class 'InstrumentScriptVM'
242
243 InstrumentScriptVM::InstrumentScriptVM() :
244 m_event(NULL), m_fnPlayNote(this), m_fnSetController(this),
245 m_fnSetRpn(this), m_fnSetNrpn(this),
246 m_fnIgnoreEvent(this), m_fnIgnoreController(this), m_fnNoteOff(this),
247 m_fnSetEventMark(this), m_fnDeleteEventMark(this), m_fnByMarks(this),
248 m_fnChangeVol(this), m_fnChangeVolTime(this),
249 m_fnChangeTune(this), m_fnChangeTuneTime(this), m_fnChangePan(this),
250 m_fnChangePanTime(this), m_fnChangePanCurve(this),
251 m_fnChangeCutoff(this), m_fnChangeReso(this), m_fnChangeAttack(this),
252 m_fnChangeDecay(this), m_fnChangeSustain(this), m_fnChangeRelease(this),
253 m_fnChangeCutoffAttack(this), m_fnChangeCutoffDecay(this),
254 m_fnChangeCutoffSustain(this), m_fnChangeCutoffRelease(this),
255 m_fnChangeAmpLFODepth(this), m_fnChangeAmpLFOFreq(this),
256 m_fnChangeCutoffLFODepth(this), m_fnChangeCutoffLFOFreq(this),
257 m_fnChangePitchLFODepth(this), m_fnChangePitchLFOFreq(this),
258 m_fnChangeNote(this), m_fnChangeVelo(this), m_fnFork(this),
259 m_fnEventStatus(this), m_fnWait2(this), m_fnStopWait(this),
260 m_fnAbort(this), m_fnFadeIn(this), m_fnFadeOut(this),
261 m_fnChangeVolCurve(this), m_fnChangeTuneCurve(this),
262 m_fnGetEventPar(this), m_fnSetEventPar(this), m_fnChangePlayPos(this),
263 m_fnCallbackStatus(this),
264 m_varEngineUptime(this), m_varCallbackID(this), m_varAllEvents(this),
265 m_varCallbackChildID(this)
266 {
267 m_CC.size = _MEMBER_SIZEOF(AbstractEngineChannel, ControllerTable);
268 m_CC_NUM = DECLARE_VMINT(m_event, class ScriptEvent, cause.Param.CC.Controller);
269 m_EVENT_ID = DECLARE_VMINT_READONLY(m_event, class ScriptEvent, id);
270 m_EVENT_NOTE = DECLARE_VMINT_READONLY(m_event, class ScriptEvent, cause.Param.Note.Key);
271 m_EVENT_VELOCITY = DECLARE_VMINT_READONLY(m_event, class ScriptEvent, cause.Param.Note.Velocity);
272 m_RPN_ADDRESS = DECLARE_VMINT_READONLY(m_event, class ScriptEvent, cause.Param.RPN.Parameter);
273 m_RPN_VALUE = DECLARE_VMINT_READONLY(m_event, class ScriptEvent, cause.Param.RPN.Value);
274 m_KEY_DOWN.size = 128;
275 m_KEY_DOWN.readonly = true;
276 m_NI_CALLBACK_TYPE = DECLARE_VMINT_READONLY(m_event, class ScriptEvent, handlerType);
277 m_NKSP_IGNORE_WAIT = DECLARE_VMINT(m_event, class ScriptEvent, ignoreAllWaitCalls);
278 m_NKSP_CALLBACK_PARENT_ID = DECLARE_VMINT_READONLY(m_event, class ScriptEvent, parentHandlerID);
279 }
280
281 VMExecStatus_t InstrumentScriptVM::exec(VMParserContext* parserCtx, ScriptEvent* event) {
282 AbstractEngineChannel* pEngineChannel =
283 static_cast<AbstractEngineChannel*>(event->cause.pEngineChannel);
284
285 // prepare built-in script variables for script execution
286 m_event = event;
287 m_CC.data = (int8_t*) &pEngineChannel->ControllerTable[0];
288 m_KEY_DOWN.data = &pEngineChannel->GetMidiKeyboardManager()->KeyDown[0];
289
290 // if script is in start condition, then do mandatory MIDI event
291 // preprocessing tasks, which essentially means updating i.e. controller
292 // table with new CC value in case of a controller event, because the
293 // script might access the new CC value
294 if (!event->executionSlices) {
295 switch (event->cause.Type) {
296 case Event::type_control_change:
297 pEngineChannel->ControllerTable[event->cause.Param.CC.Controller] =
298 event->cause.Param.CC.Value;
299 break;
300 case Event::type_channel_pressure:
301 pEngineChannel->ControllerTable[CTRL_TABLE_IDX_AFTERTOUCH] =
302 event->cause.Param.ChannelPressure.Value;
303 break;
304 case Event::type_pitchbend:
305 pEngineChannel->ControllerTable[CTRL_TABLE_IDX_PITCHBEND] =
306 event->cause.Param.Pitch.Pitch;
307 break;
308 default:
309 ; // noop
310 }
311 }
312
313 // run the script handler(s)
314 VMExecStatus_t res = VM_EXEC_NOT_RUNNING;
315 for ( ; event->handlers[event->currentHandler]; event->currentHandler++) {
316 res = ScriptVM::exec(
317 parserCtx, event->execCtx, event->handlers[event->currentHandler]
318 );
319 event->executionSlices++;
320 if (!(res & VM_EXEC_SUSPENDED)) { // if script terminated ...
321 // check if this script handler instance has any forked children
322 // to be auto aborted
323 for (int iChild = 0; iChild < MAX_FORK_PER_SCRIPT_HANDLER &&
324 event->childHandlerID[iChild]; ++iChild)
325 {
326 RTList<ScriptEvent>::Iterator itChild =
327 pEngineChannel->ScriptCallbackByID(event->childHandlerID[iChild]);
328 if (itChild && itChild->autoAbortByParent)
329 itChild->execCtx->signalAbort();
330 }
331 }
332 if (res & VM_EXEC_SUSPENDED || res & VM_EXEC_ERROR) return res;
333 }
334
335 return res;
336 }
337
338 std::map<String,VMIntPtr*> InstrumentScriptVM::builtInIntVariables() {
339 // first get built-in integer variables of derived VM class
340 std::map<String,VMIntPtr*> m = ScriptVM::builtInIntVariables();
341
342 // now add own built-in variables
343 m["$CC_NUM"] = &m_CC_NUM;
344 m["$EVENT_ID"] = &m_EVENT_ID;
345 m["$EVENT_NOTE"] = &m_EVENT_NOTE;
346 m["$EVENT_VELOCITY"] = &m_EVENT_VELOCITY;
347 // m["$POLY_AT_NUM"] = &m_POLY_AT_NUM;
348 m["$RPN_ADDRESS"] = &m_RPN_ADDRESS; // used for both RPN and NRPN events
349 m["$RPN_VALUE"] = &m_RPN_VALUE; // used for both RPN and NRPN events
350 m["$NI_CALLBACK_TYPE"] = &m_NI_CALLBACK_TYPE;
351 m["$NKSP_IGNORE_WAIT"] = &m_NKSP_IGNORE_WAIT;
352 m["$NKSP_CALLBACK_PARENT_ID"] = &m_NKSP_CALLBACK_PARENT_ID;
353
354 return m;
355 }
356
357 std::map<String,VMInt8Array*> InstrumentScriptVM::builtInIntArrayVariables() {
358 // first get built-in integer array variables of derived VM class
359 std::map<String,VMInt8Array*> m = ScriptVM::builtInIntArrayVariables();
360
361 // now add own built-in variables
362 m["%CC"] = &m_CC;
363 m["%KEY_DOWN"] = &m_KEY_DOWN;
364 //m["%POLY_AT"] = &m_POLY_AT;
365
366 return m;
367 }
368
369 std::map<String,vmint> InstrumentScriptVM::builtInConstIntVariables() {
370 // first get built-in integer variables of derived VM class
371 std::map<String,vmint> m = ScriptVM::builtInConstIntVariables();
372
373 m["$EVENT_STATUS_INACTIVE"] = EVENT_STATUS_INACTIVE;
374 m["$EVENT_STATUS_NOTE_QUEUE"] = EVENT_STATUS_NOTE_QUEUE;
375 m["$VCC_MONO_AT"] = CTRL_TABLE_IDX_AFTERTOUCH;
376 m["$VCC_PITCH_BEND"] = CTRL_TABLE_IDX_PITCHBEND;
377 for (int i = 0; i < INSTR_SCRIPT_EVENT_GROUPS; ++i) {
378 m["$MARK_" + ToString(i+1)] = i;
379 }
380 m["$EVENT_PAR_NOTE"] = EVENT_PAR_NOTE;
381 m["$EVENT_PAR_VELOCITY"] = EVENT_PAR_VELOCITY;
382 m["$EVENT_PAR_VOLUME"] = EVENT_PAR_VOLUME;
383 m["$EVENT_PAR_TUNE"] = EVENT_PAR_TUNE;
384 m["$EVENT_PAR_0"] = EVENT_PAR_0;
385 m["$EVENT_PAR_1"] = EVENT_PAR_1;
386 m["$EVENT_PAR_2"] = EVENT_PAR_2;
387 m["$EVENT_PAR_3"] = EVENT_PAR_3;
388 m["$NKSP_LINEAR"] = FADE_CURVE_LINEAR;
389 m["$NKSP_EASE_IN_EASE_OUT"] = FADE_CURVE_EASE_IN_EASE_OUT;
390 m["$CALLBACK_STATUS_TERMINATED"] = CALLBACK_STATUS_TERMINATED;
391 m["$CALLBACK_STATUS_QUEUE"] = CALLBACK_STATUS_QUEUE;
392 m["$CALLBACK_STATUS_RUNNING"] = CALLBACK_STATUS_RUNNING;
393
394 return m;
395 }
396
397 std::map<String,VMDynVar*> InstrumentScriptVM::builtInDynamicVariables() {
398 // first get built-in dynamic variables of derived VM class
399 std::map<String,VMDynVar*> m = ScriptVM::builtInDynamicVariables();
400
401 m["%ALL_EVENTS"] = &m_varAllEvents;
402 m["$ENGINE_UPTIME"] = &m_varEngineUptime;
403 m["$NI_CALLBACK_ID"] = &m_varCallbackID;
404 m["%NKSP_CALLBACK_CHILD_ID"] = &m_varCallbackChildID;
405
406 return m;
407 }
408
409 VMFunction* InstrumentScriptVM::functionByName(const String& name) {
410 // built-in script functions of this class
411 if (name == "play_note") return &m_fnPlayNote;
412 else if (name == "set_controller") return &m_fnSetController;
413 else if (name == "set_rpn") return &m_fnSetRpn;
414 else if (name == "set_nrpn") return &m_fnSetNrpn;
415 else if (name == "ignore_event") return &m_fnIgnoreEvent;
416 else if (name == "ignore_controller") return &m_fnIgnoreController;
417 else if (name == "note_off") return &m_fnNoteOff;
418 else if (name == "set_event_mark") return &m_fnSetEventMark;
419 else if (name == "delete_event_mark") return &m_fnDeleteEventMark;
420 else if (name == "by_marks") return &m_fnByMarks;
421 else if (name == "change_vol") return &m_fnChangeVol;
422 else if (name == "change_vol_time") return &m_fnChangeVolTime;
423 else if (name == "change_tune") return &m_fnChangeTune;
424 else if (name == "change_tune_time") return &m_fnChangeTuneTime;
425 else if (name == "change_note") return &m_fnChangeNote;
426 else if (name == "change_velo") return &m_fnChangeVelo;
427 else if (name == "change_pan") return &m_fnChangePan;
428 else if (name == "change_pan_time") return &m_fnChangePanTime;
429 else if (name == "change_pan_curve") return &m_fnChangePanCurve;
430 else if (name == "change_cutoff") return &m_fnChangeCutoff;
431 else if (name == "change_reso") return &m_fnChangeReso;
432 else if (name == "change_attack") return &m_fnChangeAttack;
433 else if (name == "change_decay") return &m_fnChangeDecay;
434 else if (name == "change_sustain") return &m_fnChangeSustain;
435 else if (name == "change_release") return &m_fnChangeRelease;
436 else if (name == "change_cutoff_attack") return &m_fnChangeCutoffAttack;
437 else if (name == "change_cutoff_decay") return &m_fnChangeCutoffDecay;
438 else if (name == "change_cutoff_sustain") return &m_fnChangeCutoffSustain;
439 else if (name == "change_cutoff_release") return &m_fnChangeCutoffRelease;
440 else if (name == "change_amp_lfo_depth") return &m_fnChangeAmpLFODepth;
441 else if (name == "change_amp_lfo_freq") return &m_fnChangeAmpLFOFreq;
442 else if (name == "change_cutoff_lfo_depth") return &m_fnChangeCutoffLFODepth;
443 else if (name == "change_cutoff_lfo_freq") return &m_fnChangeCutoffLFOFreq;
444 else if (name == "change_pitch_lfo_depth") return &m_fnChangePitchLFODepth;
445 else if (name == "change_pitch_lfo_freq") return &m_fnChangePitchLFOFreq;
446 else if (name == "fade_in") return &m_fnFadeIn;
447 else if (name == "fade_out") return &m_fnFadeOut;
448 else if (name == "change_vol_curve") return &m_fnChangeVolCurve;
449 else if (name == "change_tune_curve") return &m_fnChangeTuneCurve;
450 else if (name == "change_play_pos") return &m_fnChangePlayPos;
451 else if (name == "get_event_par") return &m_fnGetEventPar;
452 else if (name == "set_event_par") return &m_fnSetEventPar;
453 else if (name == "event_status") return &m_fnEventStatus;
454 else if (name == "wait") return &m_fnWait2; // override wait() core implementation
455 else if (name == "stop_wait") return &m_fnStopWait;
456 else if (name == "abort") return &m_fnAbort;
457 else if (name == "fork") return &m_fnFork;
458 else if (name == "callback_status") return &m_fnCallbackStatus;
459
460 // built-in script functions of derived VM class
461 return ScriptVM::functionByName(name);
462 }
463
464 } // namespace LinuxSampler

  ViewVC Help
Powered by ViewVC