/[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 3277 by schoenebeck, Mon Jun 5 18:40:18 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 74  namespace LinuxSampler { Line 117  namespace LinuxSampler {
117                  else                  else
118                      return 1;                      return 1;
119              }              }
120    
121                case STMT_SYNC: {
122                    #if DEBUG_SCRIPTVM_CORE
123                    _printIndents(depth);
124                    printf("-> STMT_SYNC\n");
125                    #endif
126                    SyncBlock* syncStmt = (SyncBlock*) statement;
127                    if (syncStmt->statements())
128                        return _requiredMaxStackSizeFor( syncStmt->statements() ) + 1;
129                    else
130                        return 1;
131                }
132          }          }
133    
134          return 1; // actually just to avoid compiler warning          return 1; // actually just to avoid compiler warning
# Line 88  namespace LinuxSampler { Line 143  namespace LinuxSampler {
143          return max;          return max;
144      }      }
145    
146      ScriptVM::ScriptVM() : m_parserContext(NULL), fnWait(this) {      ScriptVM::ScriptVM() : m_eventHandler(NULL), m_parserContext(NULL), m_autoSuspend(true) {
147            m_fnMessage = new CoreVMFunction_message;
148            m_fnExit = new CoreVMFunction_exit;
149            m_fnWait = new CoreVMFunction_wait(this);
150            m_fnAbs = new CoreVMFunction_abs;
151            m_fnRandom = new CoreVMFunction_random;
152            m_fnNumElements = new CoreVMFunction_num_elements;
153            m_fnInc = new CoreVMFunction_inc;
154            m_fnDec = new CoreVMFunction_dec;
155            m_fnInRange = new CoreVMFunction_in_range;
156            m_varRealTimer = new CoreVMDynVar_NKSP_REAL_TIMER;
157            m_varPerfTimer = new CoreVMDynVar_NKSP_PERF_TIMER;
158            m_fnShLeft = new CoreVMFunction_sh_left;
159            m_fnShRight = new CoreVMFunction_sh_right;
160            m_fnMin = new CoreVMFunction_min;
161            m_fnMax = new CoreVMFunction_max;
162            m_fnArrayEqual = new CoreVMFunction_array_equal;
163            m_fnSearch = new CoreVMFunction_search;
164            m_fnSort = new CoreVMFunction_sort;
165      }      }
166    
167      ScriptVM::~ScriptVM() {      ScriptVM::~ScriptVM() {
168            delete m_fnMessage;
169            delete m_fnExit;
170            delete m_fnWait;
171            delete m_fnAbs;
172            delete m_fnRandom;
173            delete m_fnNumElements;
174            delete m_fnInc;
175            delete m_fnDec;
176            delete m_fnInRange;
177            delete m_fnShLeft;
178            delete m_fnShRight;
179            delete m_fnMin;
180            delete m_fnMax;
181            delete m_fnArrayEqual;
182            delete m_fnSearch;
183            delete m_fnSort;
184            delete m_varRealTimer;
185            delete m_varPerfTimer;
186      }      }
187    
188      VMParserContext* ScriptVM::loadScript(const String& s) {      VMParserContext* ScriptVM::loadScript(const String& s) {
# Line 106  namespace LinuxSampler { Line 197  namespace LinuxSampler {
197          context->registerBuiltInConstIntVariables( builtInConstIntVariables() );          context->registerBuiltInConstIntVariables( builtInConstIntVariables() );
198          context->registerBuiltInIntVariables( builtInIntVariables() );          context->registerBuiltInIntVariables( builtInIntVariables() );
199          context->registerBuiltInIntArrayVariables( builtInIntArrayVariables() );          context->registerBuiltInIntArrayVariables( builtInIntArrayVariables() );
200            context->registerBuiltInDynVariables( builtInDynamicVariables() );
201    
202          context->createScanner(is);          context->createScanner(is);
203    
204          InstrScript_parse(context);          InstrScript_parse(context);
205          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))));
206          std::cout << "Allocating " << context->globalStrVarCount << " of global VM string variables.\n";          dmsg(2,("Allocating %d of global VM string variables.\n", context->globalStrVarCount));
207          if (!context->globalIntMemory)          if (!context->globalIntMemory)
208              context->globalIntMemory = new ArrayList<int>();              context->globalIntMemory = new ArrayList<int>();
209          if (!context->globalStrMemory)          if (!context->globalStrMemory)
# Line 152  namespace LinuxSampler { Line 244  namespace LinuxSampler {
244                  _requiredMaxStackSizeFor(&*parserCtx->handlers);                  _requiredMaxStackSizeFor(&*parserCtx->handlers);
245          }          }
246          execCtx->stack.resize(parserCtx->requiredMaxStackSize);          execCtx->stack.resize(parserCtx->requiredMaxStackSize);
247          std::cout << "Created VM exec context with "          dmsg(2,("Created VM exec context with %ld bytes VM stack size.\n",
248                    << parserCtx->requiredMaxStackSize * sizeof(ExecContext::StackFrame)                  long(parserCtx->requiredMaxStackSize * sizeof(ExecContext::StackFrame))));
                   << " bytes VM stack size.\n";  
249          //printf("execCtx=0x%lx\n", (uint64_t)execCtx);          //printf("execCtx=0x%lx\n", (uint64_t)execCtx);
250          const int polySize = parserCtx->polyphonicIntVarCount;          const int polySize = parserCtx->polyphonicIntVarCount;
251          execCtx->polyphonicIntMemory.resize(polySize);          execCtx->polyphonicIntMemory.resize(polySize);
252          memset(&execCtx->polyphonicIntMemory[0], 0, polySize * sizeof(int));          memset(&execCtx->polyphonicIntMemory[0], 0, polySize * sizeof(int));
253    
254          std::cout << "Allocated " << polySize * sizeof(int)          dmsg(2,("Allocated %ld bytes polyphonic memory.\n", long(polySize * sizeof(int))));
                   << " bytes polyphonic memory.\n";  
255          return execCtx;          return execCtx;
256      }      }
257    
258        std::vector<VMSourceToken> ScriptVM::syntaxHighlighting(const String& s) {
259            std::istringstream iss(s);
260            return syntaxHighlighting(&iss);
261        }
262    
263        std::vector<VMSourceToken> ScriptVM::syntaxHighlighting(std::istream* is) {
264            NkspScanner scanner(is);
265            std::vector<SourceToken> tokens = scanner.tokens();
266            std::vector<VMSourceToken> result;
267            result.resize(tokens.size());
268            for (int i = 0; i < tokens.size(); ++i) {
269                SourceToken* st = new SourceToken;
270                *st = tokens[i];
271                result[i] = VMSourceToken(st);
272            }
273            return result;
274        }
275    
276      VMFunction* ScriptVM::functionByName(const String& name) {      VMFunction* ScriptVM::functionByName(const String& name) {
277          if (name == "message") return &fnMessage;          if (name == "message") return m_fnMessage;
278          else if (name == "exit") return &fnExit;          else if (name == "exit") return m_fnExit;
279          else if (name == "wait") return &fnWait;          else if (name == "wait") return m_fnWait;
280            else if (name == "abs") return m_fnAbs;
281            else if (name == "random") return m_fnRandom;
282            else if (name == "num_elements") return m_fnNumElements;
283            else if (name == "inc") return m_fnInc;
284            else if (name == "dec") return m_fnDec;
285            else if (name == "in_range") return m_fnInRange;
286            else if (name == "sh_left") return m_fnShLeft;
287            else if (name == "sh_right") return m_fnShRight;
288            else if (name == "min") return m_fnMin;
289            else if (name == "max") return m_fnMax;
290            else if (name == "array_equal") return m_fnArrayEqual;
291            else if (name == "search") return m_fnSearch;
292            else if (name == "sort") return m_fnSort;
293          return NULL;          return NULL;
294      }      }
295    
# Line 180  namespace LinuxSampler { Line 301  namespace LinuxSampler {
301          return std::map<String,VMInt8Array*>();          return std::map<String,VMInt8Array*>();
302      }      }
303    
304        std::map<String,VMDynVar*> ScriptVM::builtInDynamicVariables() {
305            std::map<String,VMDynVar*> m;
306    
307            m["$NKSP_PERF_TIMER"] = m_varPerfTimer;
308            m["$NKSP_REAL_TIMER"] = m_varRealTimer;
309            m["$KSP_TIMER"] = m_varRealTimer;
310    
311            return m;
312        }
313    
314      std::map<String,int> ScriptVM::builtInConstIntVariables() {      std::map<String,int> ScriptVM::builtInConstIntVariables() {
315          return std::map<String,int>();          std::map<String,int> m;
316    
317            m["$NI_CB_TYPE_INIT"] = VM_EVENT_HANDLER_INIT;
318            m["$NI_CB_TYPE_NOTE"] = VM_EVENT_HANDLER_NOTE;
319            m["$NI_CB_TYPE_RELEASE"] = VM_EVENT_HANDLER_RELEASE;
320            m["$NI_CB_TYPE_CONTROLLER"] = VM_EVENT_HANDLER_CONTROLLER;
321    
322            return m;
323        }
324    
325        VMEventHandler* ScriptVM::currentVMEventHandler() {
326            return m_eventHandler;
327      }      }
328    
329      VMParserContext* ScriptVM::currentVMParserContext() {      VMParserContext* ScriptVM::currentVMParserContext() {
# Line 193  namespace LinuxSampler { Line 335  namespace LinuxSampler {
335          return m_parserContext->execContext;          return m_parserContext->execContext;
336      }      }
337    
338        void ScriptVM::setAutoSuspendEnabled(bool b) {
339            m_autoSuspend = b;
340        }
341    
342        bool ScriptVM::isAutoSuspendEnabled() const {
343            return m_autoSuspend;
344        }
345    
346      VMExecStatus_t ScriptVM::exec(VMParserContext* parserContext, VMExecContext* execContex, VMEventHandler* handler) {      VMExecStatus_t ScriptVM::exec(VMParserContext* parserContext, VMExecContext* execContex, VMEventHandler* handler) {
347          m_parserContext = dynamic_cast<ParserContext*>(parserContext);          m_parserContext = dynamic_cast<ParserContext*>(parserContext);
348          if (!m_parserContext) {          if (!m_parserContext) {
# Line 200  namespace LinuxSampler { Line 350  namespace LinuxSampler {
350              return VMExecStatus_t(VM_EXEC_NOT_RUNNING | VM_EXEC_ERROR);              return VMExecStatus_t(VM_EXEC_NOT_RUNNING | VM_EXEC_ERROR);
351          }          }
352    
353            // a ParserContext object is always tied to exactly one ScriptVM object
354            assert(m_parserContext->functionProvider == this);
355    
356          ExecContext* ctx = dynamic_cast<ExecContext*>(execContex);          ExecContext* ctx = dynamic_cast<ExecContext*>(execContex);
357          if (!ctx) {          if (!ctx) {
358              std::cerr << "Invalid VM exec context.\n";              std::cerr << "Invalid VM exec context.\n";
# Line 207  namespace LinuxSampler { Line 360  namespace LinuxSampler {
360          }          }
361          EventHandler* h = dynamic_cast<EventHandler*>(handler);          EventHandler* h = dynamic_cast<EventHandler*>(handler);
362          if (!h) return VM_EXEC_NOT_RUNNING;          if (!h) return VM_EXEC_NOT_RUNNING;
363            m_eventHandler = handler;
364    
365          m_parserContext->execContext = ctx;          m_parserContext->execContext = ctx;
366    
367          ctx->status = VM_EXEC_RUNNING;          ctx->status = VM_EXEC_RUNNING;
368          StmtFlags_t flags = STMT_SUCCESS;          ctx->instructionsCount = 0;
369            StmtFlags_t& flags = ctx->flags;
370            int instructionsCounter = 0;
371            int synced = m_autoSuspend ? 0 : 1;
372    
373          int& frameIdx = ctx->stackFrame;          int& frameIdx = ctx->stackFrame;
374          if (frameIdx < 0) { // start condition ...          if (frameIdx < 0) { // start condition ...
# Line 288  namespace LinuxSampler { Line 445  namespace LinuxSampler {
445                          ctx->pushStack(                          ctx->pushStack(
446                              whileStmt->statements()                              whileStmt->statements()
447                          );                          );
448                            if (flags == STMT_SUCCESS && !synced &&
449                                instructionsCounter > SCRIPTVM_MAX_INSTR_PER_CYCLE_SOFT)
450                            {
451                                flags = StmtFlags_t(STMT_SUSPEND_SIGNALLED);
452                                ctx->suspendMicroseconds = SCRIPT_VM_FORCE_SUSPENSION_MICROSECONDS;
453                            }
454                      } else ctx->popStack();                      } else ctx->popStack();
455                        break;
456                  }                  }
457    
458                    case STMT_SYNC: {
459                        #if DEBUG_SCRIPTVM_CORE
460                        _printIndents(frameIdx);
461                        printf("-> STMT_SYNC\n");
462                        #endif
463                        SyncBlock* syncStmt = (SyncBlock*) frame.statement;
464                        if (!frame.subindex++ && syncStmt->statements()) {
465                            ++synced;
466                            ctx->pushStack(
467                                syncStmt->statements()
468                            );
469                        } else {
470                            ctx->popStack();
471                            --synced;
472                        }
473                        break;
474                    }
475                }
476    
477                if (flags == STMT_SUCCESS && !synced &&
478                    instructionsCounter > SCRIPTVM_MAX_INSTR_PER_CYCLE_HARD)
479                {
480                    flags = StmtFlags_t(STMT_SUSPEND_SIGNALLED);
481                    ctx->suspendMicroseconds = SCRIPT_VM_FORCE_SUSPENSION_MICROSECONDS;
482              }              }
483    
484                ++instructionsCounter;
485          }          }
486    
487          if (flags & STMT_SUSPEND_SIGNALLED) {          if ((flags & STMT_SUSPEND_SIGNALLED) && !(flags & STMT_ABORT_SIGNALLED)) {
488              ctx->status = VM_EXEC_SUSPENDED;              ctx->status = VM_EXEC_SUSPENDED;
489                ctx->flags  = STMT_SUCCESS;
490          } else {          } else {
491              ctx->status = VM_EXEC_NOT_RUNNING;              ctx->status = VM_EXEC_NOT_RUNNING;
492              if (flags & STMT_ERROR_OCCURRED)              if (flags & STMT_ERROR_OCCURRED)
# Line 302  namespace LinuxSampler { Line 494  namespace LinuxSampler {
494              ctx->reset();              ctx->reset();
495          }          }
496    
497            ctx->instructionsCount = instructionsCounter;
498    
499            m_eventHandler = NULL;
500          m_parserContext->execContext = NULL;          m_parserContext->execContext = NULL;
501          m_parserContext = NULL;          m_parserContext = NULL;
502          return ctx->status;          return ctx->status;

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

  ViewVC Help
Powered by ViewVC