/[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 3848 - (show annotations) (download)
Thu Jan 7 13:52:46 2021 UTC (8 weeks, 4 days ago) by schoenebeck
File size: 20760 byte(s)
* NKSP VM: Fixed dead note events not been removed from user's event groups
  (i.e. causing incorrect behaviour of built-in NKSP functions by_marks()
  and set_event_mark() after max. size of event group list was exhausted).

* Bumped version (2.1.1.svn70).

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

  ViewVC Help
Powered by ViewVC