/[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 2588 by schoenebeck, Sun Jun 1 14:44:38 2014 UTC revision 3076 by schoenebeck, Thu Jan 5 18:00:52 2017 UTC
# Line 1  Line 1 
1  /*  /*
2   * Copyright (c) 2014 Christian Schoenebeck   * Copyright (c) 2014 - 2017 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 {
62    
63        #if DEBUG_SCRIPTVM_CORE
64      static void _printIndents(int n) {      static void _printIndents(int n) {
65          for (int i = 0; i < n; ++i) printf("  ");          for (int i = 0; i < n; ++i) printf("  ");
66          fflush(stdout);          fflush(stdout);
67      }      }
68        #endif
69    
70      static int _requiredMaxStackSizeFor(Statement* statement, int depth = 0) {      static int _requiredMaxStackSizeFor(Statement* statement, int depth = 0) {
71          if (!statement) return 1;          if (!statement) return 1;
# Line 88  namespace LinuxSampler { Line 131  namespace LinuxSampler {
131          return max;          return max;
132      }      }
133    
134      ScriptVM::ScriptVM() : m_parserContext(NULL), fnWait(this) {      ScriptVM::ScriptVM() : m_eventHandler(NULL), m_parserContext(NULL), m_autoSuspend(true) {
135            m_fnMessage = new CoreVMFunction_message;
136            m_fnExit = new CoreVMFunction_exit;
137            m_fnWait = new CoreVMFunction_wait(this);
138            m_fnAbs = new CoreVMFunction_abs;
139            m_fnRandom = new CoreVMFunction_random;
140            m_fnNumElements = new CoreVMFunction_num_elements;
141            m_fnInc = new CoreVMFunction_inc;
142            m_fnDec = new CoreVMFunction_dec;
143            m_fnInRange = new CoreVMFunction_in_range;
144            m_varRealTimer = new CoreVMDynVar_NKSP_REAL_TIMER;
145            m_varPerfTimer = new CoreVMDynVar_NKSP_PERF_TIMER;
146            m_fnShLeft = new CoreVMFunction_sh_left;
147            m_fnShRight = new CoreVMFunction_sh_right;
148            m_fnMin = new CoreVMFunction_min;
149            m_fnMax = new CoreVMFunction_max;
150      }      }
151    
152      ScriptVM::~ScriptVM() {      ScriptVM::~ScriptVM() {
153            delete m_fnMessage;
154            delete m_fnExit;
155            delete m_fnWait;
156            delete m_fnAbs;
157            delete m_fnRandom;
158            delete m_fnNumElements;
159            delete m_fnInc;
160            delete m_fnDec;
161            delete m_fnInRange;
162            delete m_fnShLeft;
163            delete m_fnShRight;
164            delete m_fnMin;
165            delete m_fnMax;
166            delete m_varRealTimer;
167            delete m_varPerfTimer;
168      }      }
169    
170      VMParserContext* ScriptVM::loadScript(const String& s) {      VMParserContext* ScriptVM::loadScript(const String& s) {
# Line 102  namespace LinuxSampler { Line 175  namespace LinuxSampler {
175      VMParserContext* ScriptVM::loadScript(std::istream* is) {      VMParserContext* ScriptVM::loadScript(std::istream* is) {
176          ParserContext* context = new ParserContext(this);          ParserContext* context = new ParserContext(this);
177          //printf("parserCtx=0x%lx\n", (uint64_t)context);          //printf("parserCtx=0x%lx\n", (uint64_t)context);
178            
179            context->registerBuiltInConstIntVariables( builtInConstIntVariables() );
180            context->registerBuiltInIntVariables( builtInIntVariables() );
181            context->registerBuiltInIntArrayVariables( builtInIntArrayVariables() );
182            context->registerBuiltInDynVariables( builtInDynamicVariables() );
183    
184          context->createScanner(is);          context->createScanner(is);
185    
186          InstrScript_parse(context);          InstrScript_parse(context);
187          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))));
188          std::cout << "Allocating " << context->globalStrVarCount << " of global VM string variables.\n";          dmsg(2,("Allocating %d of global VM string variables.\n", context->globalStrVarCount));
189          if (!context->globalIntMemory)          if (!context->globalIntMemory)
190              context->globalIntMemory = new ArrayList<int>();              context->globalIntMemory = new ArrayList<int>();
191          if (!context->globalStrMemory)          if (!context->globalStrMemory)
# Line 148  namespace LinuxSampler { Line 226  namespace LinuxSampler {
226                  _requiredMaxStackSizeFor(&*parserCtx->handlers);                  _requiredMaxStackSizeFor(&*parserCtx->handlers);
227          }          }
228          execCtx->stack.resize(parserCtx->requiredMaxStackSize);          execCtx->stack.resize(parserCtx->requiredMaxStackSize);
229          std::cout << "Created VM exec context with "          dmsg(2,("Created VM exec context with %ld bytes VM stack size.\n",
230                    << parserCtx->requiredMaxStackSize * sizeof(ExecContext::StackFrame)                  long(parserCtx->requiredMaxStackSize * sizeof(ExecContext::StackFrame))));
                   << " bytes VM stack size.\n";  
231          //printf("execCtx=0x%lx\n", (uint64_t)execCtx);          //printf("execCtx=0x%lx\n", (uint64_t)execCtx);
232          const int polySize = parserCtx->polyphonicIntVarCount;          const int polySize = parserCtx->polyphonicIntVarCount;
233          execCtx->polyphonicIntMemory.resize(polySize);          execCtx->polyphonicIntMemory.resize(polySize);
234          memset(&execCtx->polyphonicIntMemory[0], 0, polySize * sizeof(int));          memset(&execCtx->polyphonicIntMemory[0], 0, polySize * sizeof(int));
235    
236          std::cout << "Allocated " << polySize * sizeof(int)          dmsg(2,("Allocated %ld bytes polyphonic memory.\n", long(polySize * sizeof(int))));
                   << " bytes polyphonic memory.\n";  
237          return execCtx;          return execCtx;
238      }      }
239    
240        std::vector<VMSourceToken> ScriptVM::syntaxHighlighting(const String& s) {
241            std::istringstream iss(s);
242            return syntaxHighlighting(&iss);
243        }
244    
245        std::vector<VMSourceToken> ScriptVM::syntaxHighlighting(std::istream* is) {
246            NkspScanner scanner(is);
247            std::vector<SourceToken> tokens = scanner.tokens();
248            std::vector<VMSourceToken> result;
249            result.resize(tokens.size());
250            for (int i = 0; i < tokens.size(); ++i) {
251                SourceToken* st = new SourceToken;
252                *st = tokens[i];
253                result[i] = VMSourceToken(st);
254            }
255            return result;
256        }
257    
258      VMFunction* ScriptVM::functionByName(const String& name) {      VMFunction* ScriptVM::functionByName(const String& name) {
259          if (name == "message") return &fnMessage;          if (name == "message") return m_fnMessage;
260          else if (name == "exit") return &fnExit;          else if (name == "exit") return m_fnExit;
261          else if (name == "wait") return &fnWait;          else if (name == "wait") return m_fnWait;
262            else if (name == "abs") return m_fnAbs;
263            else if (name == "random") return m_fnRandom;
264            else if (name == "num_elements") return m_fnNumElements;
265            else if (name == "inc") return m_fnInc;
266            else if (name == "dec") return m_fnDec;
267            else if (name == "in_range") return m_fnInRange;
268            else if (name == "sh_left") return m_fnShLeft;
269            else if (name == "sh_right") return m_fnShRight;
270            else if (name == "min") return m_fnMin;
271            else if (name == "max") return m_fnMax;
272          return NULL;          return NULL;
273      }      }
274    
275        std::map<String,VMIntRelPtr*> ScriptVM::builtInIntVariables() {
276            return std::map<String,VMIntRelPtr*>();
277        }
278    
279        std::map<String,VMInt8Array*> ScriptVM::builtInIntArrayVariables() {
280            return std::map<String,VMInt8Array*>();
281        }
282    
283        std::map<String,VMDynVar*> ScriptVM::builtInDynamicVariables() {
284            std::map<String,VMDynVar*> m;
285    
286            m["$NKSP_PERF_TIMER"] = m_varPerfTimer;
287            m["$NKSP_REAL_TIMER"] = m_varRealTimer;
288            m["$KSP_TIMER"] = m_varRealTimer;
289    
290            return m;
291        }
292    
293        std::map<String,int> ScriptVM::builtInConstIntVariables() {
294            std::map<String,int> m;
295    
296            m["$NI_CB_TYPE_INIT"] = VM_EVENT_HANDLER_INIT;
297            m["$NI_CB_TYPE_NOTE"] = VM_EVENT_HANDLER_NOTE;
298            m["$NI_CB_TYPE_RELEASE"] = VM_EVENT_HANDLER_RELEASE;
299            m["$NI_CB_TYPE_CONTROLLER"] = VM_EVENT_HANDLER_CONTROLLER;
300    
301            return m;
302        }
303    
304        VMEventHandler* ScriptVM::currentVMEventHandler() {
305            return m_eventHandler;
306        }
307    
308      VMParserContext* ScriptVM::currentVMParserContext() {      VMParserContext* ScriptVM::currentVMParserContext() {
309          return m_parserContext;          return m_parserContext;
310      }      }
# Line 177  namespace LinuxSampler { Line 314  namespace LinuxSampler {
314          return m_parserContext->execContext;          return m_parserContext->execContext;
315      }      }
316    
317        void ScriptVM::setAutoSuspendEnabled(bool b) {
318            m_autoSuspend = b;
319        }
320    
321        bool ScriptVM::isAutoSuspendEnabled() const {
322            return m_autoSuspend;
323        }
324    
325      VMExecStatus_t ScriptVM::exec(VMParserContext* parserContext, VMExecContext* execContex, VMEventHandler* handler) {      VMExecStatus_t ScriptVM::exec(VMParserContext* parserContext, VMExecContext* execContex, VMEventHandler* handler) {
326          m_parserContext = dynamic_cast<ParserContext*>(parserContext);          m_parserContext = dynamic_cast<ParserContext*>(parserContext);
327          if (!m_parserContext) {          if (!m_parserContext) {
# Line 184  namespace LinuxSampler { Line 329  namespace LinuxSampler {
329              return VMExecStatus_t(VM_EXEC_NOT_RUNNING | VM_EXEC_ERROR);              return VMExecStatus_t(VM_EXEC_NOT_RUNNING | VM_EXEC_ERROR);
330          }          }
331    
332            // a ParserContext object is always tied to exactly one ScriptVM object
333            assert(m_parserContext->functionProvider == this);
334    
335          ExecContext* ctx = dynamic_cast<ExecContext*>(execContex);          ExecContext* ctx = dynamic_cast<ExecContext*>(execContex);
336          if (!ctx) {          if (!ctx) {
337              std::cerr << "Invalid VM exec context.\n";              std::cerr << "Invalid VM exec context.\n";
# Line 191  namespace LinuxSampler { Line 339  namespace LinuxSampler {
339          }          }
340          EventHandler* h = dynamic_cast<EventHandler*>(handler);          EventHandler* h = dynamic_cast<EventHandler*>(handler);
341          if (!h) return VM_EXEC_NOT_RUNNING;          if (!h) return VM_EXEC_NOT_RUNNING;
342            m_eventHandler = handler;
343    
344          m_parserContext->execContext = ctx;          m_parserContext->execContext = ctx;
345    
346          ctx->status = VM_EXEC_RUNNING;          ctx->status = VM_EXEC_RUNNING;
347          StmtFlags_t flags = STMT_SUCCESS;          StmtFlags_t flags = STMT_SUCCESS;
348            int instructionsCounter = 0;
349    
350          int& frameIdx = ctx->stackFrame;          int& frameIdx = ctx->stackFrame;
351          if (frameIdx < 0) { // start condition ...          if (frameIdx < 0) { // start condition ...
# Line 272  namespace LinuxSampler { Line 422  namespace LinuxSampler {
422                          ctx->pushStack(                          ctx->pushStack(
423                              whileStmt->statements()                              whileStmt->statements()
424                          );                          );
425                            if (flags == STMT_SUCCESS && m_autoSuspend &&
426                                instructionsCounter > SCRIPTVM_MAX_INSTR_PER_CYCLE_SOFT)
427                            {
428                                flags = StmtFlags_t(STMT_SUSPEND_SIGNALLED);
429                                ctx->suspendMicroseconds = SCRIPT_VM_FORCE_SUSPENSION_MICROSECONDS;
430                            }
431                      } else ctx->popStack();                      } else ctx->popStack();
432                        break;
433                  }                  }
434              }              }
435    
436                if (flags == STMT_SUCCESS && m_autoSuspend &&
437                    instructionsCounter > SCRIPTVM_MAX_INSTR_PER_CYCLE_HARD)
438                {
439                    flags = StmtFlags_t(STMT_SUSPEND_SIGNALLED);
440                    ctx->suspendMicroseconds = SCRIPT_VM_FORCE_SUSPENSION_MICROSECONDS;
441                }
442    
443                ++instructionsCounter;
444          }          }
445    
446          if (flags & STMT_SUSPEND_SIGNALLED) {          if (flags & STMT_SUSPEND_SIGNALLED) {
# Line 286  namespace LinuxSampler { Line 452  namespace LinuxSampler {
452              ctx->reset();              ctx->reset();
453          }          }
454    
455            m_eventHandler = NULL;
456          m_parserContext->execContext = NULL;          m_parserContext->execContext = NULL;
457          m_parserContext = NULL;          m_parserContext = NULL;
458          return ctx->status;          return ctx->status;

Legend:
Removed from v.2588  
changed lines
  Added in v.3076

  ViewVC Help
Powered by ViewVC