/[svn]/linuxsampler/trunk/src/scriptvm/ScriptVM.cpp
ViewVC logotype

Diff of /linuxsampler/trunk/src/scriptvm/ScriptVM.cpp

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 2594 by schoenebeck, Thu Jun 5 00:16:25 2014 UTC revision 2974 by schoenebeck, Fri Jul 22 15:51:40 2016 UTC
# Line 1  Line 1 
1  /*  /*
2   * Copyright (c) 2014 Christian Schoenebeck   * Copyright (c) 2014 - 2016 Christian Schoenebeck
3   *   *
4   * http://www.linuxsampler.org   * http://www.linuxsampler.org
5   *   *
# Line 10  Line 10 
10  #include "ScriptVM.h"  #include "ScriptVM.h"
11    
12  #include <string.h>  #include <string.h>
13    #include <assert.h>
14  #include "../common/global_private.h"  #include "../common/global_private.h"
15  #include "tree.h"  #include "tree.h"
16    #include "CoreVMFunctions.h"
17    #include "CoreVMDynVars.h"
18    #include "editor/NkspScanner.h"
19    
20  #define DEBUG_SCRIPTVM_CORE 0  #define DEBUG_SCRIPTVM_CORE 0
21    
22    /**
23     * Maximum amount of VM instructions to be executed per ScriptVM::exec() call
24     * in case loops are involved, before the script got automatically suspended
25     * for a certain amount of time to avoid any RT instability issues.
26     *
27     * The following value takes a max. execution time of 300 microseconds as aimed
28     * target, assuming an execution time of approximately 5 microseconds per
29     * instruction this leads to the very approximate value set below.
30     */
31    #define SCRIPTVM_MAX_INSTR_PER_CYCLE_SOFT 70
32    
33    /**
34     * Absolute maximum amount of VM instructions to be executed per
35     * ScriptVM::exec() call (even if no loops are involved), before the script got
36     * automatically suspended for a certain amount of time to avoid any RT
37     * instability issues.
38     *
39     * A distinction between "soft" and "hard" limit is done here ATM because a
40     * script author typically expects that his script might be interrupted
41     * automatically if he is using while() loops, however he might not be
42     * prepared that his script might also be interrupted if no loop is involved
43     * (i.e. on very large scripts).
44     *
45     * The following value takes a max. execution time of 1000 microseconds as
46     * aimed target, assuming an execution time of approximately 5 microseconds per
47     * instruction this leads to the very approximate value set below.
48     */
49    #define SCRIPTVM_MAX_INSTR_PER_CYCLE_HARD 210
50    
51    /**
52     * In case either SCRIPTVM_MAX_INSTR_PER_CYCLE_SOFT or
53     * SCRIPTVM_MAX_INSTR_PER_CYCLE_HARD was exceeded when calling
54     * ScriptVM::exec() : the amount of microseconds the respective script
55     * execution instance should be automatically suspended by the VM.
56     */
57    #define SCRIPT_VM_FORCE_SUSPENSION_MICROSECONDS 1000
58    
59  int InstrScript_parse(LinuxSampler::ParserContext*);  int InstrScript_parse(LinuxSampler::ParserContext*);
60    
61  namespace LinuxSampler {  namespace LinuxSampler {
# Line 88  namespace LinuxSampler { Line 129  namespace LinuxSampler {
129          return max;          return max;
130      }      }
131    
132      ScriptVM::ScriptVM() : m_parserContext(NULL), fnWait(this) {      ScriptVM::ScriptVM() : m_eventHandler(NULL), m_parserContext(NULL), m_autoSuspend(true) {
133            m_fnMessage = new CoreVMFunction_message;
134            m_fnExit = new CoreVMFunction_exit;
135            m_fnWait = new CoreVMFunction_wait(this);
136            m_fnAbs = new CoreVMFunction_abs;
137            m_fnRandom = new CoreVMFunction_random;
138            m_fnNumElements = new CoreVMFunction_num_elements;
139            m_fnInc = new CoreVMFunction_inc;
140            m_fnDec = new CoreVMFunction_dec;
141            m_varRealTimer = new CoreVMDynVar_NKSP_REAL_TIMER;
142            m_varPerfTimer = new CoreVMDynVar_NKSP_PERF_TIMER;
143            m_fnShLeft = new CoreVMFunction_sh_left;
144            m_fnShRight = new CoreVMFunction_sh_right;
145            m_fnMin = new CoreVMFunction_min;
146            m_fnMax = new CoreVMFunction_max;
147      }      }
148    
149      ScriptVM::~ScriptVM() {      ScriptVM::~ScriptVM() {
150            delete m_fnMessage;
151            delete m_fnExit;
152            delete m_fnWait;
153            delete m_fnAbs;
154            delete m_fnRandom;
155            delete m_fnNumElements;
156            delete m_fnInc;
157            delete m_fnDec;
158            delete m_fnShLeft;
159            delete m_fnShRight;
160            delete m_fnMin;
161            delete m_fnMax;
162            delete m_varRealTimer;
163            delete m_varPerfTimer;
164      }      }
165    
166      VMParserContext* ScriptVM::loadScript(const String& s) {      VMParserContext* ScriptVM::loadScript(const String& s) {
# Line 106  namespace LinuxSampler { Line 175  namespace LinuxSampler {
175          context->registerBuiltInConstIntVariables( builtInConstIntVariables() );          context->registerBuiltInConstIntVariables( builtInConstIntVariables() );
176          context->registerBuiltInIntVariables( builtInIntVariables() );          context->registerBuiltInIntVariables( builtInIntVariables() );
177          context->registerBuiltInIntArrayVariables( builtInIntArrayVariables() );          context->registerBuiltInIntArrayVariables( builtInIntArrayVariables() );
178            context->registerBuiltInDynVariables( builtInDynamicVariables() );
179    
180          context->createScanner(is);          context->createScanner(is);
181    
182          InstrScript_parse(context);          InstrScript_parse(context);
183          std::cout << "Allocating " << context->globalIntVarCount * sizeof(int) << " bytes of global int VM memory.\n";          dmsg(2,("Allocating %ld bytes of global int VM memory.\n", long(context->globalIntVarCount * sizeof(int))));
184          std::cout << "Allocating " << context->globalStrVarCount << " of global VM string variables.\n";          dmsg(2,("Allocating %d of global VM string variables.\n", context->globalStrVarCount));
185          if (!context->globalIntMemory)          if (!context->globalIntMemory)
186              context->globalIntMemory = new ArrayList<int>();              context->globalIntMemory = new ArrayList<int>();
187          if (!context->globalStrMemory)          if (!context->globalStrMemory)
# Line 152  namespace LinuxSampler { Line 222  namespace LinuxSampler {
222                  _requiredMaxStackSizeFor(&*parserCtx->handlers);                  _requiredMaxStackSizeFor(&*parserCtx->handlers);
223          }          }
224          execCtx->stack.resize(parserCtx->requiredMaxStackSize);          execCtx->stack.resize(parserCtx->requiredMaxStackSize);
225          std::cout << "Created VM exec context with "          dmsg(2,("Created VM exec context with %ld bytes VM stack size.\n",
226                    << parserCtx->requiredMaxStackSize * sizeof(ExecContext::StackFrame)                  long(parserCtx->requiredMaxStackSize * sizeof(ExecContext::StackFrame))));
                   << " bytes VM stack size.\n";  
227          //printf("execCtx=0x%lx\n", (uint64_t)execCtx);          //printf("execCtx=0x%lx\n", (uint64_t)execCtx);
228          const int polySize = parserCtx->polyphonicIntVarCount;          const int polySize = parserCtx->polyphonicIntVarCount;
229          execCtx->polyphonicIntMemory.resize(polySize);          execCtx->polyphonicIntMemory.resize(polySize);
230          memset(&execCtx->polyphonicIntMemory[0], 0, polySize * sizeof(int));          memset(&execCtx->polyphonicIntMemory[0], 0, polySize * sizeof(int));
231    
232          std::cout << "Allocated " << polySize * sizeof(int)          dmsg(2,("Allocated %ld bytes polyphonic memory.\n", long(polySize * sizeof(int))));
                   << " bytes polyphonic memory.\n";  
233          return execCtx;          return execCtx;
234      }      }
235    
236        std::vector<VMSourceToken> ScriptVM::syntaxHighlighting(const String& s) {
237            std::istringstream iss(s);
238            return syntaxHighlighting(&iss);
239        }
240    
241        std::vector<VMSourceToken> ScriptVM::syntaxHighlighting(std::istream* is) {
242            NkspScanner scanner(is);
243            std::vector<SourceToken> tokens = scanner.tokens();
244            std::vector<VMSourceToken> result;
245            result.resize(tokens.size());
246            for (int i = 0; i < tokens.size(); ++i) {
247                SourceToken* st = new SourceToken;
248                *st = tokens[i];
249                result[i] = VMSourceToken(st);
250            }
251            return result;
252        }
253    
254      VMFunction* ScriptVM::functionByName(const String& name) {      VMFunction* ScriptVM::functionByName(const String& name) {
255          if (name == "message") return &fnMessage;          if (name == "message") return m_fnMessage;
256          else if (name == "exit") return &fnExit;          else if (name == "exit") return m_fnExit;
257          else if (name == "wait") return &fnWait;          else if (name == "wait") return m_fnWait;
258            else if (name == "abs") return m_fnAbs;
259            else if (name == "random") return m_fnRandom;
260            else if (name == "num_elements") return m_fnNumElements;
261            else if (name == "inc") return m_fnInc;
262            else if (name == "dec") return m_fnDec;
263            else if (name == "sh_left") return m_fnShLeft;
264            else if (name == "sh_right") return m_fnShRight;
265            else if (name == "min") return m_fnMin;
266            else if (name == "max") return m_fnMax;
267          return NULL;          return NULL;
268      }      }
269    
# Line 180  namespace LinuxSampler { Line 275  namespace LinuxSampler {
275          return std::map<String,VMInt8Array*>();          return std::map<String,VMInt8Array*>();
276      }      }
277    
278        std::map<String,VMDynVar*> ScriptVM::builtInDynamicVariables() {
279            std::map<String,VMDynVar*> m;
280    
281            m["$NKSP_PERF_TIMER"] = m_varPerfTimer;
282            m["$NKSP_REAL_TIMER"] = m_varRealTimer;
283            m["$KSP_TIMER"] = m_varRealTimer;
284    
285            return m;
286        }
287    
288      std::map<String,int> ScriptVM::builtInConstIntVariables() {      std::map<String,int> ScriptVM::builtInConstIntVariables() {
289          return std::map<String,int>();          std::map<String,int> m;
290    
291            m["$NI_CB_TYPE_INIT"] = VM_EVENT_HANDLER_INIT;
292            m["$NI_CB_TYPE_NOTE"] = VM_EVENT_HANDLER_NOTE;
293            m["$NI_CB_TYPE_RELEASE"] = VM_EVENT_HANDLER_RELEASE;
294            m["$NI_CB_TYPE_CONTROLLER"] = VM_EVENT_HANDLER_CONTROLLER;
295    
296            return m;
297        }
298    
299        VMEventHandler* ScriptVM::currentVMEventHandler() {
300            return m_eventHandler;
301      }      }
302    
303      VMParserContext* ScriptVM::currentVMParserContext() {      VMParserContext* ScriptVM::currentVMParserContext() {
# Line 193  namespace LinuxSampler { Line 309  namespace LinuxSampler {
309          return m_parserContext->execContext;          return m_parserContext->execContext;
310      }      }
311    
312        void ScriptVM::setAutoSuspendEnabled(bool b) {
313            m_autoSuspend = b;
314        }
315    
316        bool ScriptVM::isAutoSuspendEnabled() const {
317            return m_autoSuspend;
318        }
319    
320      VMExecStatus_t ScriptVM::exec(VMParserContext* parserContext, VMExecContext* execContex, VMEventHandler* handler) {      VMExecStatus_t ScriptVM::exec(VMParserContext* parserContext, VMExecContext* execContex, VMEventHandler* handler) {
321          m_parserContext = dynamic_cast<ParserContext*>(parserContext);          m_parserContext = dynamic_cast<ParserContext*>(parserContext);
322          if (!m_parserContext) {          if (!m_parserContext) {
# Line 200  namespace LinuxSampler { Line 324  namespace LinuxSampler {
324              return VMExecStatus_t(VM_EXEC_NOT_RUNNING | VM_EXEC_ERROR);              return VMExecStatus_t(VM_EXEC_NOT_RUNNING | VM_EXEC_ERROR);
325          }          }
326    
327            // a ParserContext object is always tied to exactly one ScriptVM object
328            assert(m_parserContext->functionProvider == this);
329    
330          ExecContext* ctx = dynamic_cast<ExecContext*>(execContex);          ExecContext* ctx = dynamic_cast<ExecContext*>(execContex);
331          if (!ctx) {          if (!ctx) {
332              std::cerr << "Invalid VM exec context.\n";              std::cerr << "Invalid VM exec context.\n";
# Line 207  namespace LinuxSampler { Line 334  namespace LinuxSampler {
334          }          }
335          EventHandler* h = dynamic_cast<EventHandler*>(handler);          EventHandler* h = dynamic_cast<EventHandler*>(handler);
336          if (!h) return VM_EXEC_NOT_RUNNING;          if (!h) return VM_EXEC_NOT_RUNNING;
337            m_eventHandler = handler;
338    
339          m_parserContext->execContext = ctx;          m_parserContext->execContext = ctx;
340    
341          ctx->status = VM_EXEC_RUNNING;          ctx->status = VM_EXEC_RUNNING;
342          StmtFlags_t flags = STMT_SUCCESS;          StmtFlags_t flags = STMT_SUCCESS;
343            int instructionsCounter = 0;
344    
345          int& frameIdx = ctx->stackFrame;          int& frameIdx = ctx->stackFrame;
346          if (frameIdx < 0) { // start condition ...          if (frameIdx < 0) { // start condition ...
# Line 288  namespace LinuxSampler { Line 417  namespace LinuxSampler {
417                          ctx->pushStack(                          ctx->pushStack(
418                              whileStmt->statements()                              whileStmt->statements()
419                          );                          );
420                            if (flags == STMT_SUCCESS && m_autoSuspend &&
421                                instructionsCounter > SCRIPTVM_MAX_INSTR_PER_CYCLE_SOFT)
422                            {
423                                flags = StmtFlags_t(STMT_SUSPEND_SIGNALLED);
424                                ctx->suspendMicroseconds = SCRIPT_VM_FORCE_SUSPENSION_MICROSECONDS;
425                            }
426                      } else ctx->popStack();                      } else ctx->popStack();
427                        break;
428                  }                  }
429              }              }
430    
431                if (flags == STMT_SUCCESS && m_autoSuspend &&
432                    instructionsCounter > SCRIPTVM_MAX_INSTR_PER_CYCLE_HARD)
433                {
434                    flags = StmtFlags_t(STMT_SUSPEND_SIGNALLED);
435                    ctx->suspendMicroseconds = SCRIPT_VM_FORCE_SUSPENSION_MICROSECONDS;
436                }
437    
438                ++instructionsCounter;
439          }          }
440    
441          if (flags & STMT_SUSPEND_SIGNALLED) {          if (flags & STMT_SUSPEND_SIGNALLED) {
# Line 302  namespace LinuxSampler { Line 447  namespace LinuxSampler {
447              ctx->reset();              ctx->reset();
448          }          }
449    
450            m_eventHandler = NULL;
451          m_parserContext->execContext = NULL;          m_parserContext->execContext = NULL;
452          m_parserContext = NULL;          m_parserContext = NULL;
453          return ctx->status;          return ctx->status;

Legend:
Removed from v.2594  
changed lines
  Added in v.2974

  ViewVC Help
Powered by ViewVC