id
int64
0
755k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
65
repo_stars
int64
100
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
9 values
repo_extraction_date
stringclasses
92 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
34,057
SC_TerminalClient.h
supercollider_supercollider/lang/LangSource/SC_TerminalClient.h
/* -*- c++ -*- Commandline interpreter interface. Copyright (c) 2003 2004 stefan kersten. Copyright (c) 2013 tim blechmann. ==================================================================== SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "SC_LanguageClient.h" #include "SC_StringBuffer.h" #include "SC_Lock.h" #include <boost/array.hpp> #include <boost/asio.hpp> #include <boost/sync/semaphore.hpp> // ===================================================================== // SC_TerminalClient - command line sclang client. // ===================================================================== // TODO: move locks & thread out of the header, possibly using pimpl class SCLANG_DLLEXPORT SC_TerminalClient : public SC_LanguageClient { public: enum { kInterpretCmdLine = 0x1b, kInterpretPrintCmdLine = 0x0c, kRecompileLibrary = 0x18 // ctrl+x }; enum Signal { sig_input = 0x01, // there is new input sig_sched = 0x02, // something has been scheduled sig_recompile = 0x04, // class lib recompilation requested sig_stop = 0x08 // call Main:-stop }; struct Options : public SC_LanguageClient::Options { Options(): mLibraryConfigFile(0), mDaemon(false), mCallRun(false), mCallStop(false), mStandalone(false), mArgc(0), mArgv(0) {} const char* mLibraryConfigFile; bool mDaemon; bool mCallRun; bool mCallStop; bool mStandalone; int mArgc; char** mArgv; }; SC_TerminalClient(const char* name); virtual ~SC_TerminalClient(); const Options& options() const { return mOptions; } int run(int argc, char** argv); void quit(int code); void recompileLibrary(); virtual void postText(const char* str, size_t len); virtual void postFlush(const char* str, size_t len); virtual void postError(const char* str, size_t len); virtual void flush(); // Requests an action to be taken on the main thread. // NOTE: It may be called from any thread, and with interpreter locked. virtual void sendSignal(Signal code); void stop() { mIoService.stop(); } protected: bool parseOptions(int& argc, char**& argv, Options& opt); void printUsage(); void interpretCmdLine(const char* cmdLine, bool silent); void interpretCmdLine(const char* buf, size_t size, bool silent); // -------------------------------------------------------------- // NOTE: Subclasses should call from main thread // after receiving sig_input void interpretInput(); // -------------------------------------------------------------- // Language requested the application to quit // NOTE: It may be called from any thread, and with interpreter locked. virtual void onQuit(int exitCode); // See super class virtual void onLibraryStartup(); // -------------------------------------------------------------- // NOTE: Subclasses should override: virtual void commandLoop(); virtual void daemonLoop(); // -------------------------------------------------------------- static int prArgv(struct VMGlobals* g, int); static int prExit(struct VMGlobals* g, int); static int prScheduleChanged(struct VMGlobals*, int); static int prRecompile(struct VMGlobals*, int); void tick(const boost::system::error_code& error); private: // NOTE: called from input thread: #ifdef HAVE_READLINE static void readlineInit(); static void readlineFunc(SC_TerminalClient*); static int readlineRecompile(int, int); static void readlineCmdLine(char* cmdLine); #endif static void* pipeFunc(void*); void pushCmdLine(const char* newData, size_t size); void initInput(); void startInput(); void endInput(); void cleanupInput(); int mReturnCode; Options mOptions; // app-clock io service protected: boost::asio::io_service mIoService; private: boost::asio::io_service::work mWork; boost::asio::basic_waitable_timer<std::chrono::system_clock> mTimer; // input io service boost::asio::io_service mInputService; SC_Thread mInputThread; void inputThreadFn(); static const size_t inputBufferSize = 256; boost::array<char, inputBufferSize> inputBuffer; SC_StringBuffer mInputThrdBuf; SC_StringBuffer mInputBuf; #ifndef _WIN32 boost::asio::posix::stream_descriptor mStdIn; #else boost::asio::windows::object_handle mStdIn; #endif void startInputRead(); void onInputRead(const boost::system::error_code& error, std::size_t bytes_transferred); // command input bool mUseReadline; boost::sync::semaphore mReadlineSem; };
5,618
C++
.h
141
34.453901
92
0.638838
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,058
PyrParseNode.h
supercollider_supercollider/lang/LangSource/PyrParseNode.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "PyrSlot.h" #include "PyrKernel.h" #include "ByteCodeArray.h" #include "Opcodes.h" #include "AdvancingAllocPool.h" enum { rwPrivate = 0, rwReadOnly = 1, rwWriteOnly = 2, rwReadWrite = 3 }; enum { varInst, varClass, varTemp, varConst, varPseudo, varLocal }; enum { /* structural units */ pn_ClassNode, pn_ClassExtNode, pn_MethodNode, pn_BlockNode, pn_SlotNode, /* variable declarations */ pn_VarListNode, pn_VarDefNode, pn_DynDictNode, pn_DynListNode, pn_LitListNode, pn_LitDictNode, pn_StaticVarListNode, pn_InstVarListNode, pn_PoolVarListNode, pn_ArgListNode, pn_SlotDefNode, /* selectors */ pn_LiteralNode, /* code */ pn_PushLitNode, pn_PushNameNode, pn_PushKeyArgNode, pn_CallNode, pn_BinopCallNode, pn_DropNode, pn_AssignNode, pn_MultiAssignNode, pn_MultiAssignVarListNode, pn_SetterNode, pn_CurryArgNode, pn_ReturnNode, pn_BlockReturnNode, pn_NumTypes }; extern AdvancingAllocPool gParseNodePool; #define ALLOCNODE(type) (new (gParseNodePool.Alloc(sizeof(type))) type()) #define ALLOCSLOTNODE(type, classno) (new (gParseNodePool.Alloc(sizeof(type))) type(classno)) #define COMPILENODE(node, result, onTailBranch) (compileNode((node), (result), (onTailBranch))) #define DUMPNODE(node, level) \ do { \ if (node) \ (node)->dump(level); \ } while (false); struct PyrParseNode { PyrParseNode(int classno); virtual ~PyrParseNode() {} virtual void compile(PyrSlot* result) = 0; virtual void dump(int level) = 0; struct PyrParseNode* mNext; struct PyrParseNode* mTail; int mLineno; int mCharno; unsigned char mClassno; unsigned char mParens; }; struct PyrSlotNode : public PyrParseNode { PyrSlotNode(): PyrParseNode(pn_SlotNode) {} PyrSlotNode(int classno): PyrParseNode(classno) {} virtual ~PyrSlotNode() {} virtual void compile(PyrSlot* result); virtual void compileLiteral(PyrSlot* result); virtual void compilePushLit(PyrSlot* result); virtual void dump(int level); virtual void dumpLiteral(int level); virtual void dumpPushLit(int level); PyrSlot mSlot; }; typedef PyrSlotNode PyrLiteralNode; typedef PyrSlotNode PyrPushLitNode; typedef PyrSlotNode PyrPushNameNode; struct PyrCurryArgNode : public PyrParseNode { PyrCurryArgNode(): PyrParseNode(pn_CurryArgNode), mArgNum(-1) {} virtual ~PyrCurryArgNode() {} virtual void compile(PyrSlot* result); virtual void dump(int level); int mArgNum; }; struct PyrClassExtNode : public PyrParseNode { PyrClassExtNode(): PyrParseNode(pn_ClassExtNode) {} virtual ~PyrClassExtNode() {} virtual void compile(PyrSlot* result); virtual void dump(int level); struct PyrSlotNode* mClassName; struct PyrMethodNode* mMethods; }; struct PyrClassNode : public PyrParseNode { PyrClassNode(): PyrParseNode(pn_ClassNode) {} virtual ~PyrClassNode() {} virtual void compile(PyrSlot* result); virtual void dump(int level); struct PyrSlotNode* mClassName; struct PyrSlotNode* mSuperClassName; struct PyrSlotNode* mIndexType; struct PyrVarListNode* mVarlists; struct PyrMethodNode* mMethods; int mVarTally[4]; int mNumSuperInstVars; }; struct PyrMethodNode : public PyrParseNode { PyrMethodNode(): PyrParseNode(pn_MethodNode) {} virtual ~PyrMethodNode() {} virtual void compile(PyrSlot* result); virtual void dump(int level); struct PyrSlotNode* mMethodName; struct PyrSlotNode* mPrimitiveName; struct PyrArgListNode* mArglist; struct PyrVarListNode* mVarlist; struct PyrParseNode* mBody; int mIsClassMethod; // is class method? bool mExtension; }; struct PyrVarListNode : public PyrParseNode { PyrVarListNode(): PyrParseNode(pn_VarListNode) {} virtual ~PyrVarListNode() {} virtual void compile(PyrSlot* result); virtual void dump(int level); struct PyrVarDefNode* mVarDefs; int mFlags; }; struct PyrVarDefNode : public PyrParseNode { PyrVarDefNode(): PyrParseNode(pn_VarDefNode) {} virtual ~PyrVarDefNode() {} virtual void compile(PyrSlot* result); virtual void compileArg(PyrSlot* result); virtual void dump(int level); bool hasExpr(PyrSlot* result); struct PyrSlotNode* mVarName; PyrParseNode* mDefVal; int mFlags; bool mDrop; }; struct PyrCallNodeBase : public PyrParseNode { PyrCallNodeBase(int classno): PyrParseNode(classno) {} virtual ~PyrCallNodeBase() {} virtual void compile(PyrSlot* result); virtual void compilePartialApplication(int numCurryArgs, PyrSlot* result); virtual void compileCall(PyrSlot* result) = 0; virtual int isPartialApplication() = 0; }; struct PyrCallNodeBase2 : public PyrCallNodeBase { PyrCallNodeBase2(int classno): PyrCallNodeBase(classno) {} virtual ~PyrCallNodeBase2() {} struct PyrSlotNode* mSelector; struct PyrParseNode* mArglist; struct PyrParseNode* mKeyarglist; bool mTailCall; }; struct PyrCallNode : public PyrCallNodeBase2 { PyrCallNode(): PyrCallNodeBase2(pn_CallNode) {} virtual ~PyrCallNode() {} virtual void compileCall(PyrSlot* result); virtual void dump(int level); virtual int isPartialApplication(); }; struct PyrBinopCallNode : public PyrCallNodeBase2 { PyrBinopCallNode(): PyrCallNodeBase2(pn_BinopCallNode) {} virtual ~PyrBinopCallNode() {} virtual void compileCall(PyrSlot* result); virtual void dump(int level); virtual int isPartialApplication(); }; struct PyrSetterNode : public PyrCallNodeBase { PyrSetterNode(): PyrCallNodeBase(pn_SetterNode) {} virtual ~PyrSetterNode() {} virtual void compileCall(PyrSlot* result); virtual void dump(int level); virtual int isPartialApplication(); struct PyrSlotNode* mSelector; struct PyrParseNode* mExpr1; struct PyrParseNode* mExpr2; int mFlags; // is a var def ? }; struct PyrDynListNode : public PyrCallNodeBase { PyrDynListNode(): PyrCallNodeBase(pn_DynListNode) {} virtual ~PyrDynListNode() {} virtual void compileCall(PyrSlot* result); virtual void dump(int level); virtual int isPartialApplication(); struct PyrParseNode* mClassname; struct PyrParseNode* mElems; }; struct PyrDynDictNode : public PyrCallNodeBase { PyrDynDictNode(): PyrCallNodeBase(pn_DynDictNode) {} virtual ~PyrDynDictNode() {} virtual void compileCall(PyrSlot* result); virtual void dump(int level); virtual int isPartialApplication(); struct PyrParseNode* mElems; }; struct PyrDropNode : public PyrParseNode { PyrDropNode(): PyrParseNode(pn_DropNode) {} virtual ~PyrDropNode() {} virtual void compile(PyrSlot* result); virtual void dump(int level); struct PyrParseNode* mExpr1; struct PyrParseNode* mExpr2; }; struct PyrPushKeyArgNode : public PyrParseNode { PyrPushKeyArgNode(): PyrParseNode(pn_PushKeyArgNode) {} virtual ~PyrPushKeyArgNode() {} virtual void compile(PyrSlot* result); virtual void dump(int level); struct PyrSlotNode* mSelector; struct PyrParseNode* mExpr; }; struct PyrReturnNode : public PyrParseNode { PyrReturnNode(): PyrParseNode(pn_ReturnNode) {} virtual ~PyrReturnNode() {} virtual void compile(PyrSlot* result); virtual void dump(int level); struct PyrParseNode* mExpr; // if null, return self }; struct PyrBlockReturnNode : public PyrParseNode { PyrBlockReturnNode(): PyrParseNode(pn_BlockReturnNode) {} virtual ~PyrBlockReturnNode() {} virtual void compile(PyrSlot* result); virtual void dump(int level); struct PyrParseNode* mExpr; // if null, return self }; struct PyrAssignNode : public PyrParseNode { PyrAssignNode(): PyrParseNode(pn_AssignNode) {} virtual ~PyrAssignNode() {} virtual void compile(PyrSlot* result); virtual void dump(int level); struct PyrSlotNode* mVarName; struct PyrParseNode* mExpr; bool mDrop; // allow drop }; struct PyrMultiAssignNode : public PyrParseNode { PyrMultiAssignNode(): PyrParseNode(pn_MultiAssignNode) {} virtual ~PyrMultiAssignNode() {} virtual void compile(PyrSlot* result); virtual void dump(int level); struct PyrMultiAssignVarListNode* mVarList; struct PyrParseNode* mExpr; bool mDrop; // allow drop }; struct PyrMultiAssignVarListNode : public PyrParseNode { PyrMultiAssignVarListNode(): PyrParseNode(pn_MultiAssignVarListNode) {} virtual ~PyrMultiAssignVarListNode() {} virtual void compile(PyrSlot* result); virtual void dump(int level); struct PyrSlotNode* mVarNames; struct PyrSlotNode* mRest; }; struct PyrBlockNode : public PyrParseNode { PyrBlockNode(): PyrParseNode(pn_BlockNode) {} virtual ~PyrBlockNode() {} virtual void compile(PyrSlot* result); virtual void dump(int level); struct PyrArgListNode* mArglist; struct PyrVarListNode* mVarlist; struct PyrParseNode* mBody; bool mIsTopLevel; int mBeginCharNo; }; struct PyrArgListNode : public PyrParseNode { PyrArgListNode(): PyrParseNode(pn_ArgListNode) {} virtual ~PyrArgListNode() {} virtual void compile(PyrSlot* result); virtual void dump(int level); struct PyrVarDefNode* mVarDefs; struct PyrSlotNode* mRest; struct PyrSlotNode* mKeywordArgs = nullptr; }; struct PyrLitListNode : public PyrParseNode { PyrLitListNode(): PyrParseNode(pn_LitListNode) {} virtual ~PyrLitListNode() {} virtual void compile(PyrSlot* result); virtual void dump(int level); struct PyrParseNode* mClassname; struct PyrParseNode* mElems; }; struct PyrLitDictNode : public PyrParseNode { PyrLitDictNode(): PyrParseNode(pn_LitDictNode) {} virtual ~PyrLitDictNode() {} virtual void compile(PyrSlot* result); virtual void dump(int level); struct PyrParseNode* mElems; }; extern PyrParseNode* gRootParseNode; extern intptr_t gParserResult; extern bool gIsTailCodeBranch; extern bool gTailIsMethodReturn; extern bool compilingCmdLine; extern const char* nodename[]; void compileNode(PyrParseNode* node, PyrSlot* result, bool onTailBranch); class SetTailBranch { bool mSave; public: SetTailBranch(bool inValue) { mSave = gIsTailCodeBranch; gIsTailCodeBranch = inValue; } ~SetTailBranch() { gIsTailCodeBranch = mSave; } }; class SetTailIsMethodReturn { bool mSave; public: SetTailIsMethodReturn(bool inValue) { mSave = gTailIsMethodReturn; gTailIsMethodReturn = inValue; } ~SetTailIsMethodReturn() { gTailIsMethodReturn = mSave; } }; inline void compileNode(PyrParseNode* node, PyrSlot* result, bool onTailBranch) { SetTailBranch branch(gIsTailCodeBranch && onTailBranch); /*if (compilingCmdLine) { printf("stb %14s %d %d\n", nodename[node->mClassno], onTailBranch, gIsTailCodeBranch); }*/ node->compile(result); } void initParseNodes(); PyrSlotNode* newPyrSlotNode(PyrSlot* slot); PyrCurryArgNode* newPyrCurryArgNode(); PyrClassNode* newPyrClassNode(PyrSlotNode* className, PyrSlotNode* superClassName, PyrVarListNode* varlists, PyrMethodNode* methods, PyrSlotNode* indexType); PyrClassExtNode* newPyrClassExtNode(PyrSlotNode* className, PyrMethodNode* methods); PyrMethodNode* newPyrMethodNode(PyrSlotNode* methodName, PyrSlotNode* primitiveName, PyrArgListNode* arglist, PyrVarListNode* varlist, PyrParseNode* body, int isClassMethod); PyrArgListNode* newPyrArgListNode(PyrVarDefNode* varDefs, PyrSlotNode* rest, PyrSlotNode* kwArgs); PyrVarListNode* newPyrVarListNode(PyrVarDefNode* vardefs, int flags); PyrVarDefNode* newPyrVarDefNode(PyrSlotNode* varName, PyrParseNode* defVal, int flags); PyrCallNode* newPyrCallNode(PyrSlotNode* selector, PyrParseNode* arglist, PyrParseNode* keyarglist, PyrParseNode* blocklist); PyrBinopCallNode* newPyrBinopCallNode(PyrSlotNode* selector, PyrParseNode* arg1, PyrParseNode* arg2, PyrParseNode* arg3); PyrDropNode* newPyrDropNode(PyrParseNode* expr1, PyrParseNode* expr2); PyrPushKeyArgNode* newPyrPushKeyArgNode(PyrSlotNode* selector, PyrParseNode* expr); PyrPushLitNode* newPyrPushLitNode(PyrSlotNode* literalSlot, PyrParseNode* literalObj); PyrLiteralNode* newPyrLiteralNode(PyrSlotNode* literalSlot, PyrParseNode* literalObj); PyrReturnNode* newPyrReturnNode(PyrParseNode* expr); PyrBlockReturnNode* newPyrBlockReturnNode(); PyrAssignNode* newPyrAssignNode(PyrSlotNode* varName, PyrParseNode* expr, int flags); PyrSetterNode* newPyrSetterNode(PyrSlotNode* varName, PyrParseNode* expr1, PyrParseNode* expr2); PyrMultiAssignNode* newPyrMultiAssignNode(PyrMultiAssignVarListNode* varList, PyrParseNode* expr, int flags); PyrPushNameNode* newPyrPushNameNode(PyrSlotNode* slotNode); PyrDynDictNode* newPyrDynDictNode(PyrParseNode* elems); PyrDynListNode* newPyrDynListNode(PyrParseNode* classname, PyrParseNode* elems); PyrLitListNode* newPyrLitListNode(PyrParseNode* classname, PyrParseNode* elems); PyrLitDictNode* newPyrLitDictNode(PyrParseNode* elems); PyrMultiAssignVarListNode* newPyrMultiAssignVarListNode(PyrSlotNode* varNames, PyrSlotNode* rest); PyrBlockNode* newPyrBlockNode(PyrArgListNode* arglist, PyrVarListNode* varlist, PyrParseNode* body, bool isTopLevel); void compilePyrMethodNode(PyrMethodNode* node, PyrSlot* result); void compilePyrLiteralNode(PyrLiteralNode* node, PyrSlot* result); PyrClass* getNodeSuperclass(PyrClassNode* node); void countNodeMethods(PyrClassNode* node, int* numClassMethods, int* numInstMethods); void compileExtNodeMethods(PyrClassExtNode* node); void countVarDefs(PyrClassNode* node); bool compareVarDefs(PyrClassNode* node, PyrClass* classobj); void recompileSubclasses(PyrClass* classobj); void compileNodeMethods(PyrClassNode* node); void fillClassPrototypes(PyrClassNode* node, PyrClass* classobj, PyrClass* superclassobj); int nodeListLength(PyrParseNode* node); bool isSuperObjNode(PyrParseNode* node); bool isThisObjNode(PyrParseNode* node); int conjureSelectorIndex(PyrParseNode* node, PyrBlock* func, bool isSuper, PyrSymbol* selector, int* selType); int conjureLiteralSlotIndex(PyrParseNode* node, PyrBlock* func, PyrSlot* slot); bool findVarName(PyrBlock* func, PyrClass** classobj, PyrSymbol* name, int* varType, int* level, int* index, PyrBlock** tempfunc); void countClassVarDefs(PyrClassNode* node, int* numClassMethods, int* numInstMethods); void compileNodeList(PyrParseNode* node, bool onTailBranch); void dumpNodeList(PyrParseNode* node); int compareCallArgs(PyrMethodNode* node, PyrCallNode* cnode, int* varIndex, PyrClass* specialClass); bool findSpecialClassName(PyrSymbol* className, int* index); int getIndexType(PyrClassNode* classnode); void compileAnyIfMsg(PyrCallNodeBase2* node); void compileIfMsg(PyrCallNodeBase2* node); void compileIfNilMsg(PyrCallNodeBase2* node, bool flag); void compileCaseMsg(PyrCallNodeBase2* node); void compileWhileMsg(PyrCallNodeBase2* node); void compileLoopMsg(PyrCallNodeBase2* node); void compileAndMsg(PyrParseNode* arg1, PyrParseNode* arg2); void compileOrMsg(PyrParseNode* arg1, PyrParseNode* arg2); void compileQMsg(PyrParseNode* arg1, PyrParseNode* arg2); void compileQQMsg(PyrParseNode* arg1, PyrParseNode* arg2); void compileXQMsg(PyrParseNode* arg1, PyrParseNode* arg2); void compileSwitchMsg(PyrCallNode* node); void compilePushInt(int value); void compileAssignVar(PyrParseNode* node, PyrSymbol* varName, bool drop); void compilePushVar(PyrParseNode* node, PyrSymbol* varName); bool isAnInlineableBlock(PyrParseNode* node); bool isAnInlineableAtomicLiteralBlock(PyrParseNode* node); bool isAtomicLiteral(PyrParseNode* node); bool isWhileTrue(PyrParseNode* node); void installByteCodes(PyrBlock* block); ByteCodes compileSubExpression(PyrPushLitNode* litnode, bool onTailBranch); ByteCodes compileSubExpressionWithGoto(PyrPushLitNode* litnode, int branchLen, bool onTailBranch); ByteCodes compileBodyWithGoto(PyrParseNode* body, int branchLen, bool onTailBranch); // ByteCodes compileDefaultValue(int litIndex, int realExprLen); void initParser(); void finiParser(); void initParserPool(); void freeParserPool(); void initSpecialSelectors(); void initSpecialClasses(); void nodePostErrorLine(PyrParseNode* node); PyrParseNode* linkNextNode(PyrParseNode* a, PyrParseNode* b); PyrParseNode* linkAfterHead(PyrParseNode* a, PyrParseNode* b); extern int compileErrors; extern int numOverwrites; extern std::string overwriteMsg; extern intptr_t zzval; extern PyrSymbol* ps_newlist; extern PyrSymbol* gSpecialUnarySelectors[opNumUnarySelectors]; extern PyrSymbol* gSpecialBinarySelectors[opNumBinarySelectors]; extern PyrSymbol* gSpecialSelectors[opmNumSpecialSelectors]; extern PyrSymbol* gSpecialClasses[op_NumSpecialClasses]; extern PyrClass* gCurrentClass; extern PyrClass* gCurrentMetaClass; extern PyrClass* gCompilingClass; extern PyrMethod* gCompilingMethod; extern PyrBlock* gCompilingBlock; /* compiling "inlining" of special arithmetic opcodes. inlining of IF, WHILE, AND, OR */ #define YYSTYPE intptr_t
18,495
C++
.h
446
37.547085
120
0.753274
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,059
PyrObject.h
supercollider_supercollider/lang/LangSource/PyrObject.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* PyrObject represents the structure of all SC Objects. */ #pragma once #include "PyrSlot.h" #include <vector> /* special gc colors */ enum { obj_permanent = 1, // sent to gc->New as a flag obj_gcmarker = 2 // gc treadmill marker }; /* obj flag fields */ enum { obj_inaccessible = 4, obj_immutable = 16, obj_marked = 128 }; /* format types : */ enum { obj_notindexed, obj_slot, obj_double, obj_float, obj_int32, obj_int16, obj_int8, obj_char, obj_symbol, NUMOBJFORMATS }; /* PyrObjectHdr : object header fields prev, next : pointers in the GC treadmill classptr : pointer to the object's class size : number of slots or indexable elements. obj_format : what kind of data this object holds obj_sizeclass : power of two size class of the object obj_flags : immutable : set if object may not be updated. finalize : set if object requires finalization. marked : used by garbage collector debug sanity check. may be used by primitives but must be cleared before exiting primitive. gc_color : GC color : black, grey, white, free, permanent scratch1 : undefined value. may be used within primitives as a temporary scratch value. */ struct PyrObjectHdr { struct PyrObjectHdr *prev, *next; struct PyrClass* classptr; int size; unsigned char obj_format; unsigned char obj_sizeclass; unsigned char obj_flags; unsigned char gc_color; int scratch1; int SizeClass() { return obj_sizeclass; } void SetMark() { obj_flags |= obj_marked; } void ClearMark() { obj_flags &= ~obj_marked; } bool IsMarked() const { return obj_flags & obj_marked; } bool IsPermanent() const { return gc_color == obj_permanent; } bool IsImmutable() const { return obj_flags & obj_immutable; } bool IsMutable() const { return !IsImmutable(); } }; struct PyrObject : public PyrObjectHdr { PyrSlot slots[1]; }; struct PyrList : public PyrObjectHdr { PyrSlot array; }; struct PyrDoubleArray : public PyrObjectHdr { double d[1]; }; struct PyrFloatArray : public PyrObjectHdr { float f[1]; }; struct PyrInt32Array : public PyrObjectHdr { uint32 i[1]; }; struct PyrInt16Array : public PyrObjectHdr { uint16 i[1]; }; struct PyrInt8Array : public PyrObjectHdr { uint8 b[1]; }; struct PyrString : public PyrObjectHdr { char s[1]; }; struct PyrSymbolArray : public PyrObjectHdr { PyrSymbol* symbols[1]; }; extern struct PyrClass* class_object; extern struct PyrClass* class_array; extern struct PyrClass *class_list, *class_method, *class_fundef, *class_frame, *class_class; extern struct PyrClass *class_symbol, *class_nil; extern struct PyrClass *class_boolean, *class_true, *class_false; extern struct PyrClass *class_int, *class_char, *class_float, *class_complex; extern struct PyrClass* class_rawptr; extern struct PyrClass* class_string; extern struct PyrClass *class_magnitude, *class_number, *class_collection; extern struct PyrClass* class_sequenceable_collection; extern struct PyrClass* class_arrayed_collection; extern struct PyrClass* class_simple_number; extern struct PyrClass* class_signal; extern struct PyrClass* class_wavetable; extern struct PyrClass* class_rawarray; extern struct PyrClass* class_int8array; extern struct PyrClass* class_int16array; extern struct PyrClass* class_int32array; extern struct PyrClass* class_symbolarray; extern struct PyrClass* class_floatarray; extern struct PyrClass* class_doublearray; extern struct PyrClass *class_func, *class_absfunc; extern struct PyrClass* class_stream; extern struct PyrClass* class_process; extern struct PyrClass* class_interpreter; extern struct PyrClass* class_thread; extern struct PyrClass* class_routine; extern struct PyrClass* class_finalizer; extern struct PyrClass* class_server_shm_interface; extern PyrSymbol* s_none; extern PyrSymbol* s_object; extern PyrSymbol* s_bag; extern PyrSymbol* s_set; extern PyrSymbol* s_identityset; extern PyrSymbol* s_dictionary; extern PyrSymbol* s_identitydictionary; extern PyrSymbol* s_linkedlist; extern PyrSymbol* s_sortedlist; extern PyrSymbol* s_array; extern PyrSymbol *s_list, *s_method, *s_fundef, *s_frame, *s_class; extern PyrSymbol *s_symbol, *s_nil; extern PyrSymbol *s_boolean, *s_true, *s_false; extern PyrSymbol *s_int, *s_char, *s_color, *s_float, *s_complex; extern PyrSymbol* s_rawptr; extern PyrSymbol* s_string; extern PyrSymbol *s_magnitude, *s_number, *s_collection; extern PyrSymbol* s_ordered_collection; extern PyrSymbol* s_sequenceable_collection; extern PyrSymbol* s_arrayed_collection; extern PyrSymbol* s_simple_number; extern PyrSymbol* s_signal; extern PyrSymbol* s_wavetable; extern PyrSymbol* s_int8array; extern PyrSymbol* s_int16array; extern PyrSymbol* s_int32array; extern PyrSymbol* s_symbolarray; extern PyrSymbol* s_floatarray; extern PyrSymbol* s_doublearray; extern PyrSymbol* s_rect; extern PyrSymbol* s_stream; extern PyrSymbol* s_process; extern PyrSymbol* s_main; extern PyrSymbol* s_thread; extern PyrSymbol* s_routine; extern PyrSymbol* s_env; extern PyrSymbol *s_run, *s_stop, *s_tick; extern PyrSymbol* s_next; extern PyrSymbol* s_at; extern PyrSymbol* s_put; extern PyrSymbol *s_series, *s_copyseries, *s_putseries; extern PyrSymbol* s_value; extern PyrSymbol* s_performList; extern PyrSymbol* s_superPerformList; extern PyrSymbol* s_performArgs; extern PyrSymbol *s_new, *s_ref; extern PyrSymbol *s_synth, *s_environment, *s_event; extern PyrSymbol* s_interpreter; extern PyrSymbol* s_finalizer; extern PyrSymbol* s_awake; extern PyrSymbol* s_systemclock; extern PyrSymbol* s_server_shm_interface; extern PyrSymbol *s_interpretCmdLine, *s_interpretPrintCmdLine; extern int gFormatElemSize[NUMOBJFORMATS]; extern int gFormatElemCapc[NUMOBJFORMATS]; extern int gFormatElemTag[NUMOBJFORMATS]; void dumpObject(PyrObject* obj); void dumpObjectSlot(PyrSlot* slot); bool respondsTo(PyrSlot* slot, PyrSymbol* selector); bool isSubclassOf(struct PyrClass* classobj, struct PyrClass* testclass); extern struct PyrClass* gTagClassTable[16]; inline struct PyrClass* classOfSlot(PyrSlot* slot) { PyrClass* classobj; int tag; if (IsFloat(slot)) classobj = class_float; else if ((tag = GetTag(slot) & 0xF) == 1) classobj = slotRawObject(slot)->classptr; else classobj = gTagClassTable[tag]; return classobj; } typedef int (*ObjFuncPtr)(struct VMGlobals*, struct PyrObject*); void stringFromPyrString(PyrString* obj, char* str, int maxlength); void pstringFromPyrString(PyrString* obj, unsigned char* str, int maxlength); int instVarOffset(const char* classname, const char* instvarname); int classVarOffset(const char* classname, const char* classvarname, PyrClass** classobj); void fillSlots(PyrSlot* slot, int size, PyrSlot* fillslot); void nilSlots(PyrSlot* slot, int size); void zeroSlots(PyrSlot* slot, int size); int calcHash(PyrSlot* a); int getIndexedFloat(struct PyrObject* obj, int index, float* value); int getIndexedDouble(struct PyrObject* obj, int index, double* value); inline int getIndexedVal(struct PyrObject* obj, int index, float* value) { return getIndexedFloat(obj, index, value); } inline int getIndexedVal(struct PyrObject* obj, int index, double* value) { return getIndexedDouble(obj, index, value); } void getIndexedSlot(struct PyrObject* obj, PyrSlot* a, int index); int putIndexedSlot(struct VMGlobals* g, struct PyrObject* obj, PyrSlot* c, int index); int putIndexedFloat(PyrObject* obj, double val, int index); inline long ARRAYMAXINDEXSIZE(PyrObjectHdr* obj) { return (1L << obj->obj_sizeclass); } inline long MAXINDEXSIZE(PyrObjectHdr* obj) { return ((1L << obj->obj_sizeclass) * gFormatElemCapc[obj->obj_format]); } std::tuple<int, std::vector<std::string>> PyrCollToVectorStdString(PyrObject* coll); void InstallFinalizer(VMGlobals* g, PyrObject* inObj, int slotIndex, ObjFuncPtr inFunc);
8,810
C++
.h
223
36.887892
119
0.766635
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,060
ByteCodeArray.h
supercollider_supercollider/lang/LangSource/ByteCodeArray.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once typedef unsigned char Byte; #define BYTE_CODE_CHUNK_SIZE 64 typedef struct { Byte* bytes; Byte* ptr; size_t size; } ByteCodeArray, *ByteCodes; extern ByteCodes gCompilingByteCodes; extern long totalByteCodes; void initByteCodes(); void compileByte(long byte); void compileAndFreeByteCodes(ByteCodes byteCodes); void copyByteCodes(Byte* dest, ByteCodes byteCodes); ByteCodes getByteCodes(); ByteCodes saveByteCodeArray(); void restoreByteCodeArray(ByteCodes byteCodes); size_t byteCodeLength(ByteCodes byteCodes); void compileByteCodes(ByteCodes byteCodes); ByteCodes allocByteCodes(); void reallocByteCodes(ByteCodes byteCodes); void freeByteCodes(ByteCodes byteCodes); int compileOpcode(long opcode, long operand1); void compileJump(long opcode, long jumplen); int compileNumber(unsigned long value); int compileNumber24(unsigned long value);
1,749
C++
.h
42
38.785714
81
0.798468
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,061
PyrObjectProto.h
supercollider_supercollider/lang/LangSource/PyrObjectProto.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "PyrObject.h" void initSymbols(); void initClasses(); void buildClassTree(); void freePyrSlot(PyrSlot* slot); void freePyrObject(PyrObject* obj); bool objAddIndexedSlot(PyrObject* obj, PyrSlot* slot); bool objAddIndexedSymbol(PyrSymbolArray* obj, PyrSymbol* symbol); bool objAddIndexedObject(PyrObject* obj, PyrObject* obj2); void CallStackSanity(struct VMGlobals* g, const char* tagstr); bool FrameSanity(struct PyrFrame* frame, const char* tagstr); void dumpBadObject(PyrObject* obj); void initRawRegistry();
1,413
C++
.h
30
43.9
81
0.7815
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,062
PyrSlot32.h
supercollider_supercollider/lang/LangSource/PyrSlot32.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* PyrSlot is a value holder for SC variables. A PyrSlot is an 8-byte value which is either a double precision float or a 32-bit tag plus a 32-bit value. */ #pragma once #include "SC_Endian.h" #include "SC_Types.h" #include "PyrErrors.h" #include <cassert> #include <cstddef> struct PyrSymbol; /* Pyrite slots are the size of an 8 byte double. If the upper bits indicate that the double is a 'Not-A-Number' then the upper 32 bits are used as a tag to indicate one of a number of other types whose data is in the lower 32 bits. */ /* some DSPs like the TIC32 do not support 8 byte doubles */ /* on such CPUs, set DOUBLESLOTS to zero */ #define DOUBLESLOTS 1 /* use the high order bits of an IEEE double NaN as a tag */ enum { tagObj = 0x7FF90001, tagInt = 0x7FF90002, tagSym = 0x7FF90003, tagChar = 0x7FF90004, tagNil = 0x7FF90005, // nil, false, and true are indicated by the tag alone. tagFalse = 0x7FF90006, // the lower 32 bits are zero. tagTrue = 0x7FF90007, tagPtr = 0x7FF90008, /* anything else is a double */ tagUnused = 0x7FF9000D #if !DOUBLESLOTS , tagFloat = 0x7FF9000F /* used only to initialized 4 byte float tags, never compared with */ #endif }; typedef union pyrslot { double f; struct { #if BYTE_ORDER == BIG_ENDIAN int tag; #endif // BIG_ENDIAN union { int c; /* char */ int i; float f; void* ptr; struct PyrObject* o; PyrSymbol* s; struct PyrMethod* om; struct PyrBlock* oblk; struct PyrClass* oc; struct PyrFrame* of; struct PyrList* ol; struct PyrString* os; struct PyrInt8Array* ob; struct PyrDoubleArray* od; struct PyrSymbolArray* osym; struct PyrProcess* op; struct PyrThread* ot; struct PyrInterpreter* oi; } u; #if BYTE_ORDER == LITTLE_ENDIAN // need to swap on intel <sk> int tag; #endif // LITTLE_ENDIAN } s; } PyrSlot; /* these are some defines to make accessing the structure less verbose. obviously it polutes the namespace of identifiers beginning with 'u'. */ #define utag s.tag // int #define ui s.u.i // PyrObject #define uo s.u.o // PyrSymbol #define us s.u.s #define uc s.u.c #define uoc s.u.oc #define uof s.u.of #define uol s.u.ol #define uod s.u.od #define uob s.u.ob #define uop s.u.op #define uoi s.u.oi #define uod s.u.od // string #define uos s.u.os #define uot s.u.ot // method #define uom s.u.om // symbol array #define uosym s.u.osym #define uoblk s.u.oblk #define uptr s.u.ptr #if DOUBLESLOTS # define uf f #else # define uf s.u.f #endif /* Note that on the PowerPC, the fastest way to copy a slot is to copy the double field, not the struct. */ inline int GetTag(const PyrSlot* slot) { return slot->utag; } /* some macros for setting values of slots */ inline void SetInt(PyrSlot* slot, int val) { (slot)->utag = tagInt; (slot)->ui = (val); } inline void SetObject(PyrSlot* slot, struct PyrObjectHdr* val) { (slot)->utag = tagObj; (slot)->uo = (PyrObject*)(val); } inline void SetSymbol(PyrSlot* slot, PyrSymbol* val) { (slot)->utag = tagSym; (slot)->us = (val); } inline void SetChar(PyrSlot* slot, char val) { (slot)->utag = tagChar; (slot)->uc = (val); } inline void SetPtr(PyrSlot* slot, void* val) { (slot)->utag = tagPtr; (slot)->uptr = (void*)(val); } inline void SetObjectOrNil(PyrSlot* slot, PyrObject* val) { if (val) { (slot)->utag = tagObj; (slot)->uo = (val); } else { (slot)->utag = tagNil; (slot)->ui = 0; } } inline void SetTrue(PyrSlot* slot) { (slot)->utag = tagTrue; (slot)->ui = 0; } inline void SetFalse(PyrSlot* slot) { (slot)->utag = tagFalse; (slot)->ui = 0; } inline void SetBool(PyrSlot* slot, bool test) { (slot)->utag = ((test) ? tagTrue : tagFalse); (slot)->ui = 0; } inline void SetNil(PyrSlot* slot) { (slot)->utag = tagNil; (slot)->ui = 0; } #if DOUBLESLOTS inline void SetFloat(PyrSlot* slot, double val) { (slot)->uf = (val); } #else inline void SetFloat(PyrSlot* slot, double val) { (slot)->utag = s_float; (slot)->uf = (val); } #endif inline bool IsObj(const PyrSlot* slot) { return ((slot)->utag == tagObj); } inline bool NotObj(const PyrSlot* slot) { return ((slot)->utag != tagObj); } inline bool IsNil(const PyrSlot* slot) { return ((slot)->utag == tagNil); } inline bool NotNil(const PyrSlot* slot) { return ((slot)->utag != tagNil); } inline bool IsFalse(const PyrSlot* slot) { return ((slot)->utag == tagFalse); } inline bool IsTrue(const PyrSlot* slot) { return ((slot)->utag == tagTrue); } inline bool SlotEq(const PyrSlot* a, const PyrSlot* b) { return ((a)->ui == (b)->ui && (a)->utag == (b)->utag); } inline bool IsSym(const PyrSlot* slot) { return ((slot)->utag == tagSym); } inline bool NotSym(const PyrSlot* slot) { return ((slot)->utag != tagSym); } inline bool IsChar(const PyrSlot* slot) { return ((slot)->utag == tagChar); } inline bool NotChar(const PyrSlot* slot) { return ((slot)->utag != tagChar); } inline bool IsInt(const PyrSlot* slot) { return ((slot)->utag == tagInt); } inline bool NotInt(const PyrSlot* slot) { return ((slot)->utag != tagInt); } inline bool IsFloatTag(int tag) { return ((tag & 0xFFFFFFF0) != 0x7FF90000); } inline bool IsFloat(const PyrSlot* slot) { return (((slot)->utag & 0xFFFFFFF0) != 0x7FF90000); } inline bool NotFloat(const PyrSlot* slot) { return (((slot)->utag & 0xFFFFFFF0) == 0x7FF90000); } inline bool IsPtr(const PyrSlot* slot) { return ((slot)->utag == tagPtr); } inline bool NotPtr(const PyrSlot* slot) { return ((slot)->utag != tagPtr); } inline void SetRawChar(PyrSlot* slot, int val) { assert(IsChar(slot)); slot->uc = val; } inline void SetRaw(PyrSlot* slot, int val) { assert(IsInt(slot)); slot->ui = val; } inline void SetRaw(PyrSlot* slot, long val) { assert(IsInt(slot)); slot->ui = val; } inline void SetRaw(PyrSlot* slot, PyrObject* val) { assert(IsObj(slot)); slot->uo = val; } inline void SetRaw(PyrSlot* slot, PyrSymbol* val) { assert(IsSym(slot)); slot->us = val; } inline void SetRaw(PyrSlot* slot, void* val) { assert(IsPtr(slot)); slot->uptr = val; } inline void SetRaw(PyrSlot* slot, double val) { assert(IsFloat(slot)); SetFloat(slot, val); } inline void SetTagRaw(PyrSlot* slot, int tag) { slot->utag = tag; } template <typename numeric_type> inline int slotVal(PyrSlot* slot, numeric_type* value) { if (IsFloat(slot)) { *value = static_cast<numeric_type>(slot->uf); return errNone; } else if (IsInt(slot)) { *value = static_cast<numeric_type>(slot->ui); return errNone; } return errWrongType; } inline int slotFloatVal(PyrSlot* slot, float* value) { return slotVal<float>(slot, value); } inline int slotIntVal(PyrSlot* slot, int* value) { return slotVal<int>(slot, value); } inline int slotDoubleVal(PyrSlot* slot, double* value) { return slotVal<double>(slot, value); } inline int slotSymbolVal(PyrSlot* slot, PyrSymbol** symbol) { if (!IsSym(slot)) return errWrongType; *symbol = slot->us; return errNone; } inline void* slotRawPtr(PyrSlot* slot) { assert(IsPtr(slot) || (slot->s.u.ptr == NULL && IsNil(slot))); return slot->s.u.ptr; } inline PyrBlock* slotRawBlock(PyrSlot* slot) { return slot->s.u.oblk; } inline PyrSymbolArray* slotRawSymbolArray(PyrSlot* slot) { return slot->s.u.osym; } inline PyrDoubleArray* slotRawDoubleArray(PyrSlot* slot) { return slot->s.u.od; } inline PyrInt8Array* slotRawInt8Array(PyrSlot* slot) { return slot->s.u.ob; } inline PyrMethod* slotRawMethod(PyrSlot* slot) { return slot->s.u.om; } inline const PyrMethod* slotRawMethod(const PyrSlot* slot) { return slot->s.u.om; } inline PyrThread* slotRawThread(PyrSlot* slot) { return slot->s.u.ot; } inline PyrString* slotRawString(PyrSlot* slot) { return slot->s.u.os; } inline PyrList* slotRawList(PyrSlot* slot) { return slot->s.u.ol; } inline PyrFrame* slotRawFrame(PyrSlot* slot) { return slot->s.u.of; } inline PyrClass* slotRawClass(PyrSlot* slot) { return slot->s.u.oc; } inline const PyrClass* slotRawClass(const PyrSlot* slot) { return slot->s.u.oc; } inline PyrInterpreter* slotRawInterpreter(PyrSlot* slot) { return slot->s.u.oi; } inline PyrSymbol* slotRawSymbol(PyrSlot* slot) { assert(IsSym(slot)); return slot->s.u.s; } inline const PyrSymbol* slotRawSymbol(const PyrSlot* slot) { return slot->s.u.s; } inline int slotRawChar(const PyrSlot* slot) { assert(IsChar(slot)); return slot->s.u.c; } inline int slotRawInt(const PyrSlot* slot) { assert(IsInt(slot)); return slot->s.u.i; } inline double slotRawFloat(const PyrSlot* slot) { assert(IsFloat(slot)); return slot->uf; } inline PyrObject* slotRawObject(PyrSlot* slot) { assert(IsObj(slot)); return slot->s.u.o; } inline const PyrObject* slotRawObject(const PyrSlot* slot) { assert(IsObj(slot)); return slot->s.u.o; } inline void slotCopy(PyrSlot* dst, const PyrSlot* src) { double* dstp = (double*)dst; double* srcp = (double*)src; *dstp = *srcp; } inline void slotCopy(PyrSlot* dst, const PyrSlot* src, int num) { double* dstp = (double*)dst - 1; double* srcp = (double*)src - 1; for (int i = 0; i < num; ++i) { *++dstp = *++srcp; } } #undef uptr #undef uoblk #undef uosym #undef uom #undef uot #undef uos #undef uod #undef uob #undef uol #undef uof #undef uoc #undef utag #undef us #undef uc #undef uo #undef uoi #undef ui #undef uf #undef uop
10,595
C++
.h
318
29.77044
113
0.678092
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,063
PredefinedSymbols.h
supercollider_supercollider/lang/LangSource/PredefinedSymbols.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ extern PyrSymbol *s_func, *s_absfunc; extern PyrSymbol* s_doesNotUnderstand; extern PyrSymbol *s_curProcess, *s_curMethod, *s_curBlock, *s_curClosure, *s_curThread; extern PyrSymbol* s_startup; extern PyrSymbol* s_shutdown; extern PyrSymbol *s_envirGet, *s_envirPut;
1,142
C++
.h
22
48.136364
87
0.767713
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,064
InitAlloc.h
supercollider_supercollider/lang/LangSource/InitAlloc.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "SCBase.h" #include "SC_AllocPool.h" #include <stdexcept> #define MEMFAIL(ptr) \ if (!(ptr)) { \ throw std::runtime_error("Out of memory!\n"); \ } #define MEMFAILED throw std::runtime_error("Out of memory!\n");
1,389
C++
.h
25
51.44
120
0.594993
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,065
AdvancingAllocPool.h
supercollider_supercollider/lang/LangSource/AdvancingAllocPool.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* AdvancingAllocPool implements a simple advancing pointer allocation scheme. There is no Free(). All objects in the pool are freed at once with FreeAll(). Thus it is very fast. */ #pragma once #include <stdexcept> #include <stdlib.h> class AllocPool; struct AdvancingAllocPoolChunk; typedef int int32; inline void FailNil(void* ptr) { if (!ptr) throw std::runtime_error("alloc failed"); } struct AdvancingAllocPoolChunkHdr { AdvancingAllocPoolChunk* mNext; size_t mSize; int32 mPad1, mPad2; }; struct AdvancingAllocPoolChunk { AdvancingAllocPoolChunk* mNext; size_t mSize; int32 mPad1, mPad2; char mSpace[16]; }; class AdvancingAllocPool { public: AdvancingAllocPool(); ~AdvancingAllocPool() { FreeAll(); } void Init(AllocPool* inAllocPool, size_t initSize, size_t growSize, size_t tooBigSize); void* Alloc(size_t inBytes); void FreeAll(); bool SanityCheck(); private: void AddChunk(size_t inSize); AllocPool* mAllocPool; size_t mInitSize; size_t mGrowSize; size_t mCurSize; size_t mTooBig; AdvancingAllocPoolChunk* mChunks; AdvancingAllocPoolChunk* mFatties; };
2,050
C++
.h
60
30.316667
91
0.749366
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,066
PyrPrimitiveProto.h
supercollider_supercollider/lang/LangSource/PyrPrimitiveProto.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "PyrPrimitive.h" int basicNew(VMGlobals* g, int numArgsPushed); int basicNewClear(VMGlobals* g, int numArgsPushed); int basicSwap(VMGlobals* g, int numArgsPushed); int instVarAt(VMGlobals* g, int numArgsPushed); int instVarPut(VMGlobals* g, int numArgsPushed); int instVarSize(VMGlobals* g, int numArgsPushed); int objectHash(VMGlobals* g, int numArgsPushed); int objectClass(VMGlobals* g, int numArgsPushed); int blockValueWithKeys(VMGlobals* g, int allArgsPushed, int numKeyArgsPushed); inline int blockValue(VMGlobals* g, int numArgsPushed) { return blockValueWithKeys(g, numArgsPushed, 0); } int blockValueArray(VMGlobals* g, int numArgsPushed); int objectIsKindOf(VMGlobals* g, int numArgsPushed); int objectIsMemberOf(VMGlobals* g, int numArgsPushed); int objectDump(VMGlobals* g, int numArgsPushed); int haltInterpreter(VMGlobals* g, int numArgsPushed); int objectIdentical(VMGlobals* g, int numArgsPushed); int objectNotIdentical(VMGlobals* g, int numArgsPushed); int objectPerform(VMGlobals* g, int numArgsPushed); int objectPerformList(VMGlobals* g, int numArgsPushed); int objectPerformSelList(VMGlobals* g, int numArgsPushed); int undefinedPrimitive(VMGlobals* g, int numArgsPushed); int prObjectString(VMGlobals* g, int numArgsPushed); int prClassString(VMGlobals* g, int numArgsPushed); int prSymbolString(VMGlobals* g, int numArgsPushed); int prSymbolClass(VMGlobals* g, int numArgsPushed); int prPostString(VMGlobals* g, int numArgsPushed); int prPostLine(VMGlobals* g, int numArgsPushed); int prFlushPostBuf(VMGlobals* g, int numArgsPushed); int prPrimitiveError(VMGlobals* g, int numArgsPushed); int prPrimitiveErrorString(VMGlobals* g, int numArgsPushed); int prDumpStack(VMGlobals* g, int numArgsPushed); int prDebugger(VMGlobals* g, int numArgsPushed); int prPrimName(VMGlobals* g, int numArgsPushed); int prObjectShallowCopy(VMGlobals* g, int numArgsPushed); int prObjectCopyRange(VMGlobals* g, int numArgsPushed); int prObjectPointsTo(VMGlobals* g, int numArgsPushed); int prObjectRespondsTo(VMGlobals* g, int numArgsPushed); int prCompileString(VMGlobals* g, int numArgsPushed); int prDumpBackTrace(VMGlobals* g, int numArgsPushed); int prDumpByteCodes(VMGlobals* g, int numArgsPushed); int prAllClasses(VMGlobals* g, int numArgsPushed); int prPostClassTree(VMGlobals* g, int numArgsPushed); void initPrimitiveTable(); void growPrimitiveTable(int newsize); void initPrimitives(); void deinitPrimitives(); void doPrimitive(VMGlobals* g, struct PyrMethod* meth, int numArgsPushed); void doPrimitiveWithKeys(VMGlobals* g, struct PyrMethod* meth, int allArgsPushed, int numKeysPushed);
3,511
C++
.h
66
51.151515
106
0.809441
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,067
MiscInlineMath.h
supercollider_supercollider/lang/LangSource/MiscInlineMath.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #define NUMPRIMES 6542 long nthPrime(int n); long findPrime(int n); long prevPrime(int n); long nextPrime(int n); inline double linlin(double x, double a, double b, double c, double d) { if (x <= a) return c; if (x >= b) return d; return (x - a) / (b - a) * (d - c) + c; } inline double explin(double x, double a, double b, double c, double d) { if (x <= a) return c; if (x >= b) return d; return (log(x / a)) / (log(b / a)) * (d - c) + c; } inline double expexp(double x, double a, double b, double c, double d) { if (x <= a) return c; if (x >= b) return d; return pow(d / c, log(x / a) / log(b / a)) * c; } inline double linexp(double x, double a, double b, double c, double d) { if (x <= a) return c; if (x >= b) return d; return pow(d / c, (x - a) / (b - a)) * c; }
1,775
C++
.h
50
30.94
81
0.650146
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,068
PowerOfTwoAllocPool.h
supercollider_supercollider/lang/LangSource/PowerOfTwoAllocPool.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ // Implements a power of two size class allocator. // There is no consolidation of free space. Once a chunk is allocated it // remains at that size from then on whether free or allocated. // It uses AdvancingAllocPool as its parent allocator. // It is very fast. This is used to allocate Unit output buffers. #pragma once #include <stdexcept> #include <stdlib.h> #include "clz.h" #include "AdvancingAllocPool.h" #include "SC_AllocPool.h" void post(const char* fmt, ...); void postbuf(const char* fmt, ...); template <class Hdr, class Obj, class Elem, int LargeObjSizeClass, int Align> class PowerOfTwoAllocPool { public: PowerOfTwoAllocPool(::AllocPool* inPool, size_t initSize = 64 * 1024, size_t growSize = 64 * 1024) { mLargeObjPool = inPool; mNumLargeObjects = 0; mNumAlloc = 0; mNumFree = 0; size_t tooBigSize = (sizeof(Hdr) + (sizeof(Elem) << (LargeObjSizeClass - 1))) + 1; mSmallObjPool.Init(inPool, initSize, growSize, tooBigSize); Init(); // assert(SanityCheck()); } ~PowerOfTwoAllocPool() { // assert(SanityCheck()); // assert(mNumLargeObjects == 0); // you have to free the big ones yourself mSmallObjPool.FreeAll(); } Obj* Alloc(int32 inNumElems) { // mNumAlloc++; // assert(SanityCheck()); int sizeclass = LOG2CEIL(inNumElems); if (sizeclass >= LargeObjSizeClass) { mNumLargeObjects++; size_t size = sizeof(Hdr) + (sizeof(Elem) * inNumElems); return (Obj*)mLargeObjPool->Alloc(size); } // get from free list Obj* obj = mFreeLists[sizeclass]; if (obj != NULL) { // set free list to next element. mFreeLists[sizeclass] = *(Obj**)obj; } else { // have to allocate it size_t size = mSizes[sizeclass]; obj = (Obj*)mSmallObjPool.Alloc(size); if (!obj) throw runtime_error("PowerOfTwoAllocPool out of memory"); } // obj->mMagic = 'magk'; // assert(SanityCheck()); return obj; } void Free(Obj* inObjPtr) { // mNumFree++; // assert(SanityCheck()); if (inObjPtr == 0) return; /* free(0) has no effect */ /*if (inObjPtr->mMagic != 'magk') { postbuf("bad object\n"); throw runtime_error("bad object"); }*/ int sizeclass = inObjPtr->SizeClass(); if (sizeclass >= LargeObjSizeClass) { mLargeObjPool->Free(inObjPtr); mNumLargeObjects--; } else { Obj* nextfree = mFreeLists[sizeclass]; mFreeLists[sizeclass] = inObjPtr; *(Obj**)inObjPtr = nextfree; } // assert(SanityCheck()); } void FreeAll() { // assert(mNumLargeObjects == 0); // you have to free the big ones yourself mSmallObjPool.FreeAll(); Init(); } bool SanityCheck() { // postbuf("PowerOfTwoAllocPool::SanityCheck %d %d\n", mNumAlloc, mNumFree); mLargeObjPool->DoCheckPool(); mSmallObjPool.SanityCheck(); for (int i = 0; i < LargeObjSizeClass; ++i) { Obj* obj = mFreeLists[i]; for (int j = 0; obj; ++j) { if (j >= 1000) { post("linked loop??\n"); throw runtime_error("linked loop??\n"); return false; } obj = *(Obj**)obj; } } return true; } private: void Init() { for (int i = 0; i < LargeObjSizeClass; ++i) { mFreeLists[i] = NULL; size_t size = sizeof(Hdr) + (sizeof(Elem) << i); mSizes[i] = (size + (Align - 1)) & ~(Align - 1); // alignment } } Obj* mFreeLists[LargeObjSizeClass]; size_t mSizes[LargeObjSizeClass]; AllocPool* mLargeObjPool; AdvancingAllocPool mSmallObjPool; int mNumLargeObjects; int mNumAlloc, mNumFree; };
4,905
C++
.h
128
30.226563
105
0.603778
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,069
PyrPrimitive.h
supercollider_supercollider/lang/LangSource/PyrPrimitive.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* Functions for defining language primitives. */ #pragma once #include "PyrSlot.h" typedef int (*PrimitiveHandler)(struct VMGlobals* g, int numArgsPushed); typedef int (*PrimitiveWithKeysHandler)(struct VMGlobals* g, int numArgsPushed, int numKeyArgsPushed); int nextPrimitiveIndex(); int definePrimitive(int base, int index, const char* name, PrimitiveHandler handler, int numArgs, int varArgs); int definePrimitiveWithKeys(int base, int index, const char* name, PrimitiveHandler handler, PrimitiveWithKeysHandler keyhandler, int numArgs, int varArgs); int getPrimitiveNumArgs(int index); PyrSymbol* getPrimitiveName(int index);
1,538
C++
.h
29
48.827586
111
0.772667
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,070
AllocPools.h
supercollider_supercollider/lang/LangSource/AllocPools.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* Pools for memory allocation. */ #pragma once class AllocPool; extern AllocPool* pyr_pool_compile; extern AllocPool* pyr_pool_runtime;
1,014
C++
.h
23
40.347826
81
0.767276
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,071
VMGlobals.h
supercollider_supercollider/lang/LangSource/VMGlobals.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* Each virtual machine has a copy of VMGlobals, which contains the state of the virtual machine. */ #pragma once #include "PyrSlot.h" #include "SC_AllocPool.h" #include "SC_RGen.h" #include <setjmp.h> #include <map> #define TAILCALLOPTIMIZE 1 typedef void (*FifoMsgFunc)(struct VMGlobals*, struct FifoMsg*); struct FifoMsg { FifoMsg(): func(0), dataPtr(0) { dataWord[0] = dataWord[1] = 0; } void Perform(struct VMGlobals* g); void Free(struct VMGlobals* g); FifoMsgFunc func; void* dataPtr; long dataWord[2]; }; struct VMGlobals { VMGlobals(); // global context class AllocPool* allocPool; struct PyrProcess* process; class SymbolTable* symbolTable; class PyrGC* gc; // garbage collector for this process PyrObject* classvars; #if TAILCALLOPTIMIZE int tailCall; // next byte code is a tail call. #endif bool canCallOS; // thread context struct PyrThread* thread; struct PyrMethod* method; struct PyrBlock* block; struct PyrFrame* frame; struct PyrMethod* primitiveMethod; unsigned char* ip; // current instruction pointer PyrSlot* sp; // current stack ptr PyrSlot* args; PyrSlot receiver; // the receiver PyrSlot result; int numpop; // number of args to pop for primitive long primitiveIndex; RGen* rgen; jmp_buf escapeInterpreter; // scratch context long execMethod; // primitive exceptions std::map<PyrThread*, std::pair<std::exception_ptr, PyrMethod*>> lastExceptions; }; inline void FifoMsg::Perform(struct VMGlobals* g) { (func)(g, this); } inline void FifoMsg::Free(struct VMGlobals* g) { g->allocPool->Free(dataPtr); } extern VMGlobals gVMGlobals; extern VMGlobals* gMainVMGlobals; extern VMGlobals* gCompilingVMGlobals;
2,654
C++
.h
72
32.930556
94
0.736637
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,072
PyrSymbol.h
supercollider_supercollider/lang/LangSource/PyrSymbol.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* A PyrSymbol is a unique string that resides in a global hash table. */ #pragma once #include "SC_Types.h" #include "PyrSlot.h" struct PyrSymbol { char* name; long hash; short specialIndex; uint8 flags; uint8 length; union { intptr_t index; // index in row table or primitive table struct PyrClass* classobj; // pointer to class with this name. char* source; // source code for sym_Filename; used only during compilation. } u; struct classdep* classdep; }; enum { sym_Selector = 1, sym_Class = 2, sym_Compiled = 4, sym_Called = 8, sym_Primitive = 16, sym_Setter = 32, sym_MetaClass = 64, sym_Filename = 128 };
1,579
C++
.h
45
30.688889
84
0.714754
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,073
PyrLexer.h
supercollider_supercollider/lang/LangSource/PyrLexer.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "PyrSlot.h" #include "PyrSymbol.h" #include "SC_Export.h" #include "SCBase.h" #include <filesystem> extern int charno, lineno, linepos; extern int* linestarts; struct ClassExtFile { struct ClassExtFile* next; PyrSymbol* fileSym; int startPos, endPos, lineOffset; }; typedef struct classdep { struct classdep* next; struct classdep* superClassDep; struct classdep* subclasses; PyrSymbol* className; PyrSymbol* superClassName; PyrSymbol* fileSym; int startPos, endPos, lineOffset; } ClassDependancy; extern PyrSymbol* gCompilingFileSym; ClassDependancy* newClassDependancy(PyrSymbol* className, PyrSymbol* superClassName, PyrSymbol* fileSym, int startPos, int endPos, int lineOffset); bool parseOneClass(PyrSymbol* fileSym); void initPassOne(); void finiPassOne(); bool passOne(); void buildDepTree(); void traverseFullDepTree(); void traverseDepTree(ClassDependancy* classdep, int level); void traverseFullDepTree2(); void traverseDepTree2(ClassDependancy* classdep, int level); void compileClassExtensions(); void compileClass(PyrSymbol* fileSym, int startPos, int endPos, int lineOffset); SCLANG_DLLEXPORT_C void runLibrary(PyrSymbol* selector); void interpretCmdLine(const char* textbuf, int textlen, char* methodname); int input(); int input0(); void unput(int c); void unput0(int c); void finiLexer(); bool startLexer(char* filename); void startLexerCmdLine(char* textbuf, int textbuflen); int yylex(); void yyerror(const char* s); void fatal(); bool isValidSourceFileName(const std::filesystem::path& path); bool passOne_ProcessOneFile(const std::filesystem::path& path); std::filesystem::path relativeToCompileDir(const std::filesystem::path&); void initLexer(); int processbinop(char* token); int processident(char* token); int processfloat(char* token, int sawpi); int processint(char* token); int processchar(int c); int processintradix(char* s, int n, int radix); int processfloatradix(char* s, int n, int radix); int processhex(char* s); int processsymbol(char* token); int processstring(char* token); int processkeywordbinop(char* token); void postErrorLine(int linenum, int start, int charpos); bool scanForClosingBracket(); void parseClasses(); extern int parseFailed; extern bool compilingCmdLine; extern bool compilingCmdLineErrorWindow; extern bool compiledOK; #define MAXYYLEN 8192 extern int gNumCompiledFiles; extern int gClassCompileOrderNum; extern ClassDependancy** gClassCompileOrder; extern char curfilename[PATH_MAX]; extern int runcount; extern const char* binopchars; extern char yytext[MAXYYLEN]; extern char curfilename[PATH_MAX]; extern int yylen; extern int lexCmdLine; extern bool compilingCmdLine; extern bool compilingCmdLineErrorWindow; extern intptr_t zzval; extern intptr_t gParserResult; extern int lineno, charno, linepos; extern int* linestarts; extern int maxlinestarts; extern char* text; extern int textlen; extern int textpos; extern int parseFailed; extern bool compiledOK; extern int radixcharpos, decptpos; int rtf2txt(char* txt); int html2txt(char* txt);
4,001
C++
.h
112
33.285714
118
0.793264
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,074
PyrSlot.h
supercollider_supercollider/lang/LangSource/PyrSlot.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* PyrSlot is a value holder for SC variables. A PyrSlot is an 8-byte value which is either a double precision float or a 32-bit tag plus a 32-bit value. */ #pragma once #if (__SIZEOF_POINTER__ == 8) || defined(__x86_64__) || defined(_M_X64) || defined(__LP64__) || defined(_WIN64) # include "PyrSlot64.h" #elif (__SIZEOF_POINTER__ == 4) || defined(__i386__) || defined(_M_IX86) || defined(__ILP32__) || defined(_WIN32) \ || defined(__ppc__) || defined(__arm__) # include "PyrSlot32.h" #else # error "no PyrSlot imlementation for this platform" #endif #include <string> extern PyrSlot o_nil, o_true, o_false, o_inf; extern PyrSlot o_fhalf, o_fnegone, o_fzero, o_fone, o_ftwo; extern PyrSlot o_negone, o_zero, o_one, o_two; extern PyrSlot o_emptyarray, o_onenilarray, o_argnamethis; extern PyrSymbol* s_object; // "Object" extern PyrSymbol* s_this; // "this" extern PyrSymbol* s_super; // "super" void dumpPyrSlot(PyrSlot* slot); void slotString(PyrSlot* slot, char* str); void slotOneWord(PyrSlot* slot, char* str); bool postString(PyrSlot* slot, char* str); const char* slotSymString(PyrSlot* slot); int asCompileString(PyrSlot* slot, char* str); int slotIntVal(PyrSlot* slot, int* value); int slotFloatVal(PyrSlot* slot, float* value); int slotDoubleVal(PyrSlot* slot, double* value); int slotStrVal(PyrSlot* slot, char* str, size_t maxSize); std::tuple<int, std::string> slotStdStrVal(PyrSlot* slot); std::tuple<int, std::string> slotStrStdStrVal(PyrSlot* slot); int slotStrLen(PyrSlot* slot); int slotPStrVal(PyrSlot* slot, unsigned char* str); int slotSymbolVal(PyrSlot* slot, PyrSymbol** symbol); template <typename numeric_type> inline void setSlotVal(PyrSlot* slot, numeric_type value); template <> inline void setSlotVal<int>(PyrSlot* slot, int value) { SetInt(slot, value); } template <> inline void setSlotVal<double>(PyrSlot* slot, double value) { SetFloat(slot, value); }
2,788
C++
.h
56
47.446429
120
0.737946
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,075
PyrSched.h
supercollider_supercollider/lang/LangSource/PyrSched.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "VMGlobals.h" #include "SC_Export.h" #include "SC_Lock.h" #include <cerrno> #include <atomic> #include <chrono> extern timed_mutex gLangMutex; double elapsedTime(); double monotonicClockTime(); int64 OSCTime(); int64 ElapsedTimeToOSC(double elapsed); double OSCToElapsedTime(int64 oscTime); bool addheap(VMGlobals* g, PyrObject* heap, double schedtime, PyrSlot* task); bool lookheap(PyrObject* heap, double* schedtime, PyrSlot* task); bool getheap(VMGlobals* g, PyrObject* heap, double* schedtime, PyrSlot* task); void offsetheap(VMGlobals* g, PyrObject* heap, double offset); void dumpheap(PyrObject* heap); const double kSecondsToOSC = 4294967296.; // pow(2,32)/1 const double kMicrosToOSC = 4294.967296; // pow(2,32)/1e6 const double kNanosToOSC = 4.294967296; // pow(2,32)/1e9 const double kOSCtoSecs = 2.328306436538696e-10; // 1/pow(2,32) const double kOSCtoNanos = 0.2328306436538696; // 1e9/pow(2,32) // lock language, // if shouldBeRunning == false, return EINTR // if language has been locked, return 0 inline int lockLanguageOrQuit(std::atomic<bool> const& shouldBeRunning) { bool locked = gLangMutex.try_lock(); if (locked) { if (!shouldBeRunning.load()) { gLangMutex.unlock(); return EINTR; } } else { for (;;) { using namespace std::chrono_literals; locked = gLangMutex.try_lock_for(1s); if (!shouldBeRunning.load()) { if (locked) gLangMutex.unlock(); return EINTR; } if (locked) return 0; } } return 0; }
2,527
C++
.h
64
34.25
81
0.700653
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,076
PyrSymbolTable.h
supercollider_supercollider/lang/LangSource/PyrSymbolTable.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "PyrSymbol.h" #include "AdvancingAllocPool.h" #include "SC_Export.h" #define STRINGCHUNK 32000 #define SYMBOLCHUNK 32000 SCLANG_DLLEXPORT_C PyrSymbol* getsym(const char* name); SCLANG_DLLEXPORT_C PyrSymbol* findsym(const char* name); class SymbolSpace { public: SymbolSpace(AllocPool* inPool); PyrSymbol* NewSymbol(const char* inName, int inHash, int inLength); private: AllocPool* mPool; AdvancingAllocPool mStringPool; AdvancingAllocPool mSymbolPool; }; class SymbolTable { public: SymbolTable(AllocPool* inPool, int inSize); void CopyFrom(SymbolTable& inTable); int NumItems() { return mNumItems; } int TableSize() { return mMaxItems; } PyrSymbol* Get(int inIndex) { return mTable[inIndex]; } void CheckSymbols(); private: friend PyrSymbol* getsym(const char* name); friend PyrSymbol* findsym(const char* name); PyrSymbol* Find(const char* inName); PyrSymbol* Make(const char* inName); PyrSymbol* MakeNew(const char* inName, int inHash, int inLength); int StrHash(const char* inName, size_t* outLength); void AllocTable(); void Grow(); PyrSymbol* Find(const char* inName, int inHash); void Add(PyrSymbol* inSymbol); void Rehash(PyrSymbol** inTable, int inSize); void MakeEmpty(); AllocPool* mPool; SymbolSpace mSpace; PyrSymbol** mTable; int mNumItems, mMaxItems, mMask; };
2,294
C++
.h
59
34.813559
81
0.745266
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,077
SimpleStack.h
supercollider_supercollider/lang/LangSource/SimpleStack.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once typedef struct { intptr_t* stak; short num, maxsize; } LongStack; void initLongStack(LongStack* self); void freeLongStack(LongStack* self); void growLongStack(LongStack* self); void pushls(LongStack* self, intptr_t value); intptr_t popls(LongStack* self); int emptyls(LongStack* self);
1,183
C++
.h
27
40.222222
81
0.765217
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,078
PyrInterpreter.h
supercollider_supercollider/lang/LangSource/PyrInterpreter.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "PyrSlot.h" #include "VMGlobals.h" #include "SC_Export.h" extern bool gRunningInterpreterThread; extern int gNumClasses; extern int gNumClassVars; bool initInterpreter(VMGlobals* g, PyrSymbol* selector, int numArgsPushed); bool initRuntime(VMGlobals* g, int poolSize, AllocPool* inPool); void Interpret(VMGlobals* g); int doSpecialUnaryArithMsg(VMGlobals* g, int numArgsPushed); int prSpecialBinaryArithMsg(VMGlobals* g, int numArgsPushed); int doSpecialBinaryArithMsg(VMGlobals* g, int numArgsPushed, bool isPrimitive); void DumpBackTrace(VMGlobals* g); void DumpStack(VMGlobals* g, PyrSlot* sp); void DumpFrame(struct PyrFrame* frame); bool FrameSanity(PyrFrame* frame, const char* tagstr); struct PyrProcess* newPyrProcess(VMGlobals* g, struct PyrClass* classobj); void startProcess(VMGlobals* g, PyrSymbol* selector); SCLANG_DLLEXPORT_C void runInterpreter(VMGlobals* g, PyrSymbol* selector, int numArgsPushed);
1,817
C++
.h
36
47.666667
93
0.792889
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,079
Opcodes.h
supercollider_supercollider/lang/LangSource/Opcodes.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once /* opcodes */ enum { opExtended, // 0 opPushInstVar, opPushTempVar, opPushTempZeroVar, opPushLiteral, opPushClassVar, // 5 opPushSpecialValue, opStoreInstVar, opStoreTempVar, opStoreClassVar, opSendMsg, // 10 opSendSuper, opSendSpecialMsg, opSendSpecialUnaryArithMsg, opSendSpecialBinaryArithMsg, opSpecialOpcode, // 15 opNumOpcodes }; /* special opcodes */ enum { opcDrop, // 0 opcDup, opcFunctionReturn, opcReturn, opcReturnSelf, opcReturnTrue, // 5 opcReturnFalse, opcReturnNil, opcJumpIfFalse, // IF 3 args opcJumpIfFalsePushNil, // IF 2 args opcJumpIfFalsePushFalse, // AND: (10) opcJumpIfTruePushTrue, // OR: opcJumpFwd, opcJumpBak, opcSpecialBinaryOpWithAdverb, opcSuperSpecial, // 15 opcNewList, opcNumSpecialOpcodes /* opcSlotAt, opcByteAt, // 15 opcShortAt, opcInt32At, opcColorAt, opcFloatAt, opcDoubleAt */ }; /* special unary math operators */ enum { opNeg, opNot, opIsNil, opNotNil, opBitNot, opAbs, opAsFloat, opAsInteger, opCeil, // 5 opFloor, opFrac, opSign, opSquared, opCubed, // 10 opSqrt, opExp, opRecip, opMIDICPS, opCPSMIDI, // 15 opMIDIRatio, opRatioMIDI, opDbAmp, opAmpDb, opOctCPS, // 20 opCPSOct, opLog, opLog2, opLog10, opSin, // 25 opCos, opTan, opArcSin, opArcCos, opArcTan, opSinH, opCosH, // 30 opTanH, opRand, opRand2, opLinRand, opBiLinRand, // opExpRand, // opBiExpRand, opSum3Rand, // opGammaRand, // opGaussRand, // opPoiRand, opDistort, opSoftClip, opCoin, opDigitValue, opSilence, opThru, opRectWindow, opHanWindow, opWelchWindow, opTriWindow, opRamp, opSCurve, opNumUnarySelectors }; #define IS_UNARY_BOOL_OP(op) ((op) >= opCoin && (op) <= opOdd) #define IS_BINARY_BOOL_OP(op) ((op) >= opEQ && (op) <= opGE) /* special binary math operators */ enum { opAdd, opSub, opMul, opIDiv, opFDiv, opMod, opEQ, opNE, opLT, opGT, opLE, opGE, // opIdentical, // opNotIdentical, opMin, opMax, opBitAnd, opBitOr, opBitXor, opLCM, opGCD, opRound, opRoundUp, opTrunc, opAtan2, opHypot, opHypotx, opPow, opShiftLeft, opShiftRight, opUnsignedShift, opFill, opRing1, // a * (b + 1) == a * b + a opRing2, // a * b + a + b opRing3, // a*a*b opRing4, // a*a*b - a*b*b opDifSqr, // a*a - b*b opSumSqr, // a*a + b*b opSqrSum, // (a + b)^2 opSqrDif, // (a - b)^2 opAbsDif, // |a - b| opThresh, opAMClip, opScaleNeg, opClip2, opExcess, opFold2, opWrap2, opFirstArg, opRandRange, opExpRandRange, opNumBinarySelectors }; /* other special math operators */ enum { /* 3 operands */ opDivz, opClip, opWrap, opFold, opRampMult, opMix, /* 4 operands */ opPoly3, /* 5 operands */ opMapRange }; enum { opmNew, opmInit, opmAt, opmPut, opmNext, opmReset, opmValue, opmCopyToEnd, // used by multi assign opmAdd, // used by dynamic list // opmIsNil, // opmNotNil, opmSize, opmClass, opmIf, opmWhile, opmFor, opmAnd, opmOr, opmCase, opmSwitch, opmIdentical, opmNotIdentical, opmPrint, opmRemove, opmIndexOf, opmWrapAt, opmClipAt, opmFoldAt, opmWrapPut, opmClipPut, opmFoldPut, opmDo, opmCollect, opmSelect, opmReject, opmAny, opmEvery, opmFind, opmChoose, opmValueList, opmAddFirst, opmPrimitiveFailed, opmSubclassResponsibility, opmShouldNotImplement, opmNotYetImplemented, opmDoesNotUnderstand, opmAtSign, opmWrapAtSign, opmClipAtSign, opmFoldAtSign, opmNewClear, opmNewCopyArgs, opmMultiNew, opmMultiNewList, opmAR, opmKR, opmIR, opmCopy, opmPerformList, opmIsKindOf, opmPostln, opmAsString, opmEnvirGet, opmEnvirPut, opmHalt, opmForBy, opmForSeries, opmReverseDo, opmLoop, opmNonBooleanError, opmPlusPlus, opmLTLT, opmQuestionMark, opmDoubleQuestionMark, opmExclamationQuestionMark, opmYield, opmName, opmMulAdd, opmSeries, opmNumSpecialSelectors }; enum { opsvSelf, // 0 opsvMinusOne, opsvNegOne, opsvZero, opsvOne, opsvTwo, // 5 opsvFHalf, opsvFNegOne, opsvFZero, opsvFOne, opsvFTwo, // 10 opsvPlusOne, opsvTrue, opsvFalse, opsvNil, opsvInf, // 15 opsvNumSpecialValues }; enum { opgProcess, opgMethod, opgFunctionDef, opgFunction, opgThread, // opgSampleRate, // opgAudioClock, // opgLogicalClock, opgNumPseudoVars }; /* selector types */ enum { selNormal, selSpecial, selUnary, selBinary, selIf, selWhile, selAnd, selOr, selCase, selSwitch, selLoop, selSuperNew, selQuestionMark, selDoubleQuestionMark, selExclamationQuestionMark, selNumSelectorTypes }; /* special classes: Object, List, Number, Int, Float, Signal, Complex, Point */ enum { op_class_object, op_class_symbol, op_class_nil, op_class_boolean, op_class_true, op_class_false, op_class_magnitude, op_class_char, op_class_number, op_class_complex, op_class_simple_number, op_class_int, op_class_float, op_class_method, op_class_fundef, op_class_stream, op_class_func, op_class_frame, op_class_process, op_class_main, op_class_class, op_class_string, op_class_collection, op_class_sequenceable_collection, op_class_arrayed_collection, op_class_array, op_class_int8array, op_class_int16array, op_class_int32array, op_class_floatarray, op_class_signal, op_class_doublearray, op_class_symbolarray, op_class_list, op_class_linkedlist, op_class_bag, op_class_set, op_class_identityset, op_class_dictionary, op_class_identitydictionary, op_class_sortedlist, op_class_synth, op_class_ref, op_class_environment, op_class_event, op_class_wavetable, op_class_env, op_class_routine, op_class_color, op_class_rect, op_NumSpecialClasses };
7,521
C++
.h
389
14.491003
81
0.651996
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,080
SCBase.h
supercollider_supercollider/lang/LangSource/SCBase.h
// SuperCollider real time audio synthesis system // Copyright (c) 2002 James McCartney. All rights reserved. // http://www.audiosynth.com // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // Contains the most common definitions. #pragma once #include <limits.h> #include <stdio.h> #ifdef _WIN32 # include <stdlib.h> # ifndef PATH_MAX # define PATH_MAX _MAX_PATH # endif #endif #include "SC_BoundsMacros.h" #include "SC_Types.h" #include "PyrErrors.h" #include "AllocPools.h" #include "SC_Export.h" void postfl(const char* fmt, ...); void post(const char* fmt, ...); void error(const char* fmt, ...); void postText(const char* text, long length); void postChar(char c); void flushPostBuf(); void setPostFile(FILE* file); // If file is not NULL, causes all posted text to also be written to the file. void debugf(char* fmt, ...); void pprintf(unsigned char* str, char* fmt, ...); SCLANG_DLLEXPORT_C void schedInit(); SCLANG_DLLEXPORT_C void schedCleanup(); SCLANG_DLLEXPORT_C void init_OSC(int port); SCLANG_DLLEXPORT_C void cleanup_OSC(); SCLANG_DLLEXPORT_C bool pyr_init_mem_pools(int runtime_space, int runtime_grow); SCLANG_DLLEXPORT_C void schedRun(); SCLANG_DLLEXPORT_C void schedStop(); SCLANG_DLLEXPORT_C void schedClear(); SCLANG_DLLEXPORT_C bool compileLibrary(bool standalone); SCLANG_DLLEXPORT_C void runLibrary(struct PyrSymbol* selector); SCLANG_DLLEXPORT_C void runInterpreter(struct VMGlobals* g, struct PyrSymbol* selector, int numArgsPushed); SCLANG_DLLEXPORT_C struct VMGlobals* scGlobals(); SCLANG_DLLEXPORT_C struct PyrSymbol* getsym(const char* inName); SCLANG_DLLEXPORT_C struct PyrSymbol* getmetasym(const char* name); SCLANG_DLLEXPORT_C struct PyrSymbol* findsym(const char* name);
2,427
C++
.h
53
44.528302
108
0.761864
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,081
HashTable.h
supercollider_supercollider/lang/LangSource/HashTable.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "SC_Types.h" #include "SC_BoundsMacros.h" #include "Hash.h" #include <stddef.h> template <class T, class Allocator, class KeyType> class HashTable { Allocator* mPool; int32 mNumItems, mMaxItems, mTableSize, mHashMask; T** mItems; bool mCanResize; public: HashTable(Allocator* inPool, int32 inMaxItems, bool inCanResize = true): mPool(inPool) { mNumItems = 0; mMaxItems = inMaxItems; mTableSize = mMaxItems << 1; mItems = AllocTable(mTableSize); mHashMask = mTableSize - 1; mCanResize = inCanResize; } ~HashTable() { mPool->Free(mItems); } int32 TableSize() const { return mTableSize; } int32 MaxItems() const { return mMaxItems; } int32 NumItems() const { return mNumItems; } T** AllocTable(int inTableSize) { size_t size = inTableSize * sizeof(T*); T** items = static_cast<T**>(mPool->Alloc(size)); for (int i = 0; i < inTableSize; ++i) { items[i] = 0; } return items; } void Resize() { int32 newSize = sc_max(mTableSize << 1, 32); T** oldItems = mItems; mItems = AllocTable(newSize); for (int i = 0; i < mTableSize; ++i) { T* item = oldItems[i]; if (item) Add(item); } mTableSize = newSize; mMaxItems = mTableSize >> 1; mHashMask = mTableSize - 1; mPool->Free(oldItems); // printf("mMaxItems %d mTableSize %d newSize %d\n", mMaxItems, mTableSize, newSize); } bool Add(T* inItem) { // printf("mNumItems %d\n", mNumItems); // printf("mMaxItems %d\n", mMaxItems); // printf("mCanResize %d\n", mCanResize); if (mNumItems >= mMaxItems) { if (!mCanResize) return false; Resize(); } // printf("GetHash(inItem) %d\n", GetHash(inItem)); // printf("GetKey(inItem) %s\n", GetKey(inItem)); int32 index = IndexFor(GetHash(inItem), GetKey(inItem)); // printf("index %d\n", index); T* item = mItems[index]; if (item) return item == inItem; mItems[index] = inItem; mNumItems++; return true; } bool Remove(T* inItem) { int32 index = IndexFor(GetHash(inItem), GetKey(inItem)); if (mItems[index] != inItem) return false; mItems[index] = 0; FixCollisionsFrom(index); mNumItems--; return true; } int32 IndexFor(int32 inHashID, KeyType inKey) const { int index = inHashID & mHashMask; for (;;) { T* item = mItems[index]; if (!item) return index; if (GetHash(item) == inHashID && strcmp(inKey, GetKey(item)) == 0) return index; index = (index + 1) & mHashMask; } } T* Get(KeyType inKey) const { return Get(Hash(inKey), inKey); } T* Get(int32 inHashID, KeyType inKey) const { int32 index = IndexFor(inHashID, inKey); return mItems[index]; } bool Includes(T* inItem) const { return Get(GetHash(inItem), GetKey(inItem)) == inItem; } T* AtIndex(int32 inIndex) const { return mItems[inIndex]; } private: void FixCollisionsFrom(int32 inIndex) { int oldIndex = inIndex; for (;;) { oldIndex = (oldIndex + 1) & mHashMask; T* oldItem = mItems[oldIndex]; if (!oldItem) break; int newIndex = IndexFor(GetHash(oldItem), GetKey(oldItem)); if (oldIndex != newIndex) { mItems[oldIndex] = mItems[newIndex]; mItems[newIndex] = oldItem; } } } }; template <class T, int kMaxItems, class KeyType> class StaticHashTable { int32 mNumItems, mTableSize, mHashMask; T* mItems[kMaxItems * 2]; public: StaticHashTable() { mNumItems = 0; mTableSize = kMaxItems << 1; ClearTable(); mHashMask = mTableSize - 1; } ~StaticHashTable() {} int32 TableSize() const { return mTableSize; } int32 MaxItems() const { return kMaxItems; } int32 NumItems() const { return mNumItems; } void ClearTable() { for (int i = 0; i < mTableSize; ++i) { mItems[i] = 0; } } bool Add(T* inItem) { if (mNumItems >= kMaxItems) return false; int32 index = IndexFor(GetHash(inItem), GetKey(inItem)); T* item = mItems[index]; if (item) return item == inItem; mItems[index] = inItem; mNumItems++; return true; } bool Remove(T* inItem) { int32 index = IndexFor(GetHash(inItem), GetKey(inItem)); if (mItems[index] != inItem) return false; mItems[index] = 0; FixCollisionsFrom(index); mNumItems--; return true; } int32 IndexFor(int32 inHashID, KeyType inKey) const { int index = inHashID & mHashMask; for (;;) { T* item = mItems[index]; if (!item) return index; if (GetHash(item) == inHashID && strcmp(inKey, GetKey(item)) == 0) return index; index = (index + 1) & mHashMask; } } T* Get(KeyType inKey) const { return Get(Hash(inKey), inKey); } T* Get(int32 inHashID, KeyType inKey) const { int32 index = IndexFor(inHashID, inKey); return mItems[index]; } bool Includes(T* inItem) const { return Get(GetHash(inItem), GetKey(inItem)) == inItem; } T* AtIndex(int32 inIndex) const { return mItems[inIndex]; } private: void FixCollisionsFrom(int32 inIndex) { int oldIndex = inIndex; for (;;) { oldIndex = (oldIndex + 1) & mHashMask; T* oldItem = mItems[oldIndex]; if (!oldItem) break; int newIndex = IndexFor(GetHash(oldItem), GetKey(oldItem)); if (oldIndex != newIndex) { mItems[oldIndex] = mItems[newIndex]; mItems[newIndex] = oldItem; } } } };
7,064
C++
.h
198
27.262626
97
0.58409
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,082
PyrMessage.h
supercollider_supercollider/lang/LangSource/PyrMessage.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "PyrKernel.h" static constexpr size_t temporaryKeywordStackCapacity = 128; extern PyrSlot temporaryKeywordStack[temporaryKeywordStackCapacity]; extern bool gKeywordError; extern PyrMethod** gRowTable; void initUniqueMethods(); void prepareArgsForExecute(VMGlobals* g, PyrBlock* block, PyrFrame* callFrame, long totalSuppliedArgs, long numKwArgsSupplied, bool isMethod, PyrObject* optionalEnvirLookup = nullptr); void executeMethod(VMGlobals* g, PyrBlock* meth, long totalNumArgsPushed, long numKwArgsPushed); void sendMessage(VMGlobals* g, PyrSymbol* selector, long numArgsPushed, long numKeyArgsPushed); void sendSuperMessage(VMGlobals* g, PyrSymbol* selector, long numArgsPushed, long numKeyArgsPushed); void doesNotUnderstand(VMGlobals* g, PyrSymbol* selector, long numArgsPushed, long numKeyArgsPushed); void returnFromBlock(VMGlobals* g); void returnFromMethod(VMGlobals* g); int keywordFixStack(VMGlobals* g, PyrMethod* meth, PyrMethodRaw* methraw, long allArgsPushed, long numKeyArgsPushed);
1,932
C++
.h
32
56.34375
117
0.793743
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,083
PyrKernel.h
supercollider_supercollider/lang/LangSource/PyrKernel.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* This file contains the definitions of the core objects that implement the class system. */ #pragma once #include "PyrObject.h" #include "VMGlobals.h" #define classClassNumInstVars 19 enum { classIsIntrinsic = 1, classHasIndexableInstances = 2 }; struct PyrClass : public PyrObjectHdr { PyrSlot name; PyrSlot nextclass; PyrSlot superclass; PyrSlot subclasses; PyrSlot methods; PyrSlot instVarNames; PyrSlot classVarNames; PyrSlot iprototype; // instance prototype PyrSlot cprototype; // class var prototype PyrSlot constNames; PyrSlot constValues; // const values PyrSlot instanceFormat; PyrSlot instanceFlags; PyrSlot classIndex; PyrSlot classFlags; PyrSlot maxSubclassIndex; // used by isKindOf PyrSlot filenameSym; PyrSlot charPos; PyrSlot classVarIndex; }; inline bool isKindOf(const PyrObjectHdr* obj, const struct PyrClass* testclass) { int objClassIndex = slotRawInt(&obj->classptr->classIndex); return objClassIndex >= slotRawInt(&testclass->classIndex) && objClassIndex <= slotRawInt(&testclass->maxSubclassIndex); } inline bool isKindOfSlot(const PyrSlot* slot, const struct PyrClass* testclass) { return IsObj(slot) && isKindOf(slotRawObject(slot), testclass); } /* operations on class: numInstVars() numClassVars() */ struct PyrFrame : public PyrObjectHdr { PyrSlot method; PyrSlot caller; PyrSlot context; PyrSlot homeContext; PyrSlot ip; PyrSlot vars[1]; }; #define FRAMESIZE 5 struct PyrProcess : public PyrObjectHdr { PyrSlot classVars; PyrSlot interpreter; PyrSlot curThread, mainThread; PyrSlot sysSchedulerQueue; PyrSlot nowExecutingPath; }; enum { tInit, tStart, tReady, tRunning, tSleeping, tSuspended, tDone }; struct PyrThread : public PyrObjectHdr { PyrSlot state, func, stack, method, block, frame, ip, sp; PyrSlot numpop, receiver, numArgsPushed; PyrSlot parent, terminalValue; PyrSlot primitiveError; PyrSlot primitiveIndex; PyrSlot randData; PyrSlot beats, seconds, clock, nextBeat, endBeat, endValue; PyrSlot environment; PyrSlot exceptionHandler; PyrSlot threadPlayer; PyrSlot executingPath; PyrSlot oldExecutingPath; PyrSlot rescheduledTime; PyrSlot stackSize; }; #define EVALSTACKDEPTH 512 struct PyrMethodRaw { #ifdef PYR_SLOTS_GENERIC long padding; // used for the tag in the generic pyrslot implementation #endif unsigned short unused1; unsigned short specialIndex; unsigned short methType; unsigned short frameSize; #ifdef PYR_SLOTS_GENERIC long padding2; // used for the tag in generic pyrslot implementation, second slot #endif unsigned char unused2; unsigned char numargs; unsigned char varargs; unsigned char numvars; unsigned char numtemps; unsigned char needsHeapContext; unsigned char popSize; unsigned char posargs; }; #define METHRAW(obj) ((PyrMethodRaw*)&(((PyrBlock*)obj)->rawData1)) struct PyrBlock : public PyrObjectHdr { PyrSlot rawData1; PyrSlot rawData2; PyrSlot code; // byte codes, nil if inlined PyrSlot selectors; // method selectors, class names, closures table, stores literals in methReturnLiteral methods. PyrSlot constants; // floating point constants table (to alleviate the literal table problem) PyrSlot prototypeFrame; // prototype of an activation frame PyrSlot contextDef; // ***defining block context PyrSlot argNames; // ***arguments to block PyrSlot varNames; // ***variables in block PyrSlot sourceCode; // source code if it is a closed function. }; struct PyrMethod : public PyrBlock { PyrSlot ownerclass; PyrSlot name; PyrSlot primitiveName; PyrSlot filenameSym; PyrSlot charPos; // PyrSlot byteMeter; // PyrSlot callMeter; }; enum { methNormal = 0, methReturnSelf, methReturnLiteral, methReturnArg, methReturnInstVar, methAssignInstVar, methReturnClassVar, methAssignClassVar, methRedirect, methRedirectSuper, methForwardInstVar, methForwardClassVar, methPrimitive, methBlock }; struct PyrClosure : public PyrObjectHdr { PyrSlot block; PyrSlot context; }; struct PyrInterpreter : public PyrObjectHdr { PyrSlot cmdLine, context; PyrSlot a, b, c, d, e, f, g, h, i, j; PyrSlot k, l, m, n, o, p, q, r, s, t; PyrSlot u, v, w, x, y, z; PyrSlot codeDump, preProcessor; }; /* special values */ enum { svNil, svFalse, svTrue, svNegOne, svZero, svOne, svTwo, svFHalf, svFNegOne, svFZero, svFOne, svFTwo, svInf, svNumSpecialValues }; extern PyrSlot gSpecialValues[svNumSpecialValues]; extern PyrMethod* gNullMethod; // used to fill row table PyrObject* instantiateObject(class PyrGC* gc, PyrClass* classobj, int size, bool fill, bool collect); PyrObject* newPyrObject(class PyrGC* gc, size_t inNumBytes, int inFlags, int inFormat, bool inCollect); PyrString* newPyrString(class PyrGC* gc, const char* s, int flags, bool collect); PyrString* newPyrStringN(class PyrGC* gc, int size, int flags, bool collect); PyrObject* newPyrArray(class PyrGC* gc, int size, int flags, bool collect); PyrSymbolArray* newPyrSymbolArray(class PyrGC* gc, int size, int flags, bool collect); PyrInt8Array* newPyrInt8Array(class PyrGC* gc, int size, int flags, bool collect); PyrInt32Array* newPyrInt32Array(class PyrGC* gc, int size, int flags, bool collect); PyrDoubleArray* newPyrDoubleArray(class PyrGC* gc, int size, int flags, bool collect); PyrObject* copyObject(class PyrGC* gc, PyrObject* inobj, bool collect); PyrObject* copyObjectRange(class PyrGC* gc, PyrObject* inobj, int start, int end, bool collect);
6,645
C++
.h
191
30.801047
118
0.748869
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,084
GC.h
supercollider_supercollider/lang/LangSource/GC.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* The garbage collector for SuperCollider. Based on Wilson and Johnstone's real time collector and the Baker treadmill. */ #pragma once #include "PyrObject.h" #include "VMGlobals.h" #include "AdvancingAllocPool.h" #include "function_attributes.h" void DumpSimpleBackTrace(VMGlobals* g); const int kMaxPoolSet = 7; const int kNumGCSizeClasses = 28; const int kFinalizerSet = kNumGCSizeClasses; const int kNumGCSets = kNumGCSizeClasses + 1; const int kScanThreshold = 256; class GCSet { public: GCSet() {} void Init(int inSizeClass); bool HasFree() { return mFree != &mBlack; } private: friend class PyrGC; void MajorFlip(); void MinorFlip(); PyrObjectHdr mBlack; PyrObjectHdr mWhite; PyrObjectHdr* mFree; }; struct SlotRef { SlotRef(PyrObject* inObj, int32 inIndex): obj(inObj), slotIndex(inIndex) {} PyrObject* obj; int32 slotIndex; }; class PyrGC { static const int kLazyCollectThreshold = 1024; public: PyrGC(VMGlobals* g, AllocPool* inPool, PyrClass* mainProcessClass, long poolSize); MALLOC PyrObject* New(size_t inNumBytes, long inFlags, long inFormat, bool inCollect); MALLOC PyrObject* NewFrame(size_t inNumBytes, long inFlags, long inFormat, bool inAccount); MALLOC static PyrObject* NewPermanent(size_t inNumBytes, long inFlags, long inFormat); MALLOC PyrObject* NewFinalizer(ObjFuncPtr finalizeFunc, PyrObject* inObject, bool inCollect); bool IsBlack(PyrObjectHdr* inObj) { return inObj->gc_color == mBlackColor; } bool IsWhite(PyrObjectHdr* inObj) { return inObj->gc_color == mWhiteColor; } bool IsGrey(PyrObjectHdr* inObj) { return inObj->gc_color == mGreyColor; } static bool IsMarker(PyrObjectHdr* inObj) { return inObj->gc_color == obj_gcmarker; } bool IsFree(PyrObjectHdr* inObj) { return (!(IsMarker(inObj) || inObj->IsPermanent() || IsBlack(inObj) || IsWhite(inObj) || IsGrey(inObj))); } bool ObjIsBlack(PyrObjectHdr* inObj) { return IsBlack(inObj); } bool ObjIsGrey(PyrObjectHdr* inObj) { return IsGrey(inObj); } bool ObjIsFree(PyrObjectHdr* inObj) { return IsFree(inObj); } // general purpose write barriers: void GCWrite(PyrObjectHdr* inParent, PyrSlot* inSlot) { if (IsBlack(inParent) && IsObj(inSlot) && IsWhite(slotRawObject(inSlot))) { ToGrey(slotRawObject(inSlot)); } } void GCWrite(PyrObjectHdr* inParent, PyrObjectHdr* inChild) { if (IsBlack(inParent) && IsWhite(inChild)) { ToGrey(inChild); } } // when you know the parent is black: void GCWriteBlack(PyrSlot* inSlot) { if (IsObj(inSlot)) { if (IsWhite(slotRawObject(inSlot))) { ToGrey(slotRawObject(inSlot)); } } } void GCWriteBlack(PyrObjectHdr* inChild) { if (IsWhite(inChild)) { ToGrey(inChild); } } // when you know the child is white void GCWriteNew(PyrObjectHdr* inParent, PyrObjectHdr* inChild) { assert(IsWhite(inChild)); if (IsBlack(inParent)) { ToGrey(inChild); } } // users should not call anything below. void Collect(); void Collect(int32 inNumToScan); void LazyCollect() { if (mUncollectedAllocations > kLazyCollectThreshold) Collect(); } void FullCollection(); void ScanFinalizers(); void RunAllFinalizers(); GCSet* GetGCSet(PyrObjectHdr* inObj); void CompletePartialScan(PyrObject* obj); inline void ToGrey(PyrObjectHdr* inObj); inline void ToGrey2(PyrObjectHdr* inObj); void ToBlack(PyrObjectHdr* inObj); void ToWhite(PyrObjectHdr* inObj); void Free(PyrObjectHdr* inObj); long StackDepth() { return mVMGlobals->sp - mStack->slots + 1; } PyrObject* Stack() { return mStack; } void SetStack(PyrObject* inStack) { mStack = inStack; } bool SanityCheck(); bool SanityCheck2(); bool LinkSanity(); bool ListSanity(); bool BlackToWhiteCheck(PyrObject* objA); bool SanityMarkObj(PyrObject* objA, PyrObject* fromObj, int level); bool SanityClearObj(PyrObject* objA, int level); void DumpInfo(); void DumpGrey(); void DumpSet(int set); void BecomePermanent(PyrObject* inObject); void BecomeImmutable(PyrObject* inObject); bool IsPartialScanObject(PyrObject* inObject) const { return inObject == mPartialScanObj; } int32 GetPartialScanIndex() const { return mPartialScanSlot; } private: inline PyrObject* Allocate(size_t inNumBytes, int32 sizeclass, bool inCollect); static void throwMemfailed(size_t inNumBytes); void ScanSlots(PyrSlot* inSlots, long inNumToScan); void SweepBigObjects(); void DoPartialScan(int32 inObjSize); bool ScanOneObj(); void Flip(); void ScanStack(); void ScanFrames(); void DLRemove(PyrObjectHdr* obj); void DLInsertAfter(PyrObjectHdr* after, PyrObjectHdr* obj); void DLInsertBefore(PyrObjectHdr* before, PyrObjectHdr* obj); void ClearMarks(); void Finalize(PyrObject* obj); void beginPause(); void endPause(); void reportPause(); VMGlobals* mVMGlobals; AllocPool* mPool; AdvancingAllocPool mNewPool; GCSet mSets[kNumGCSets]; PyrProcess* mProcess; // the root is the pyrprocess which contains this struct PyrObject* mStack; PyrObject* mPartialScanObj; PyrObjectHdr mGrey; int32 mPartialScanSlot; int32 mNumToScan; int32 mNumGrey; int32 mFlips, mCollects, mAllocTotal, mScans, mNumAllocs, mStackScans, mNumPartialScans, mSlotsScanned, mUncollectedAllocations; unsigned char mBlackColor, mGreyColor, mWhiteColor, mFreeColor; bool mCanSweep; bool mRunning; }; inline void PyrGC::DLRemove(PyrObjectHdr* obj) { obj->next->prev = obj->prev; obj->prev->next = obj->next; } inline void PyrGC::DLInsertAfter(PyrObjectHdr* after, PyrObjectHdr* obj) { obj->next = after->next; obj->prev = after; after->next->prev = obj; after->next = obj; } inline void PyrGC::DLInsertBefore(PyrObjectHdr* before, PyrObjectHdr* obj) { obj->prev = before->prev; obj->next = before; before->prev->next = obj; before->prev = obj; } inline GCSet* PyrGC::GetGCSet(PyrObjectHdr* inObj) { return mSets + (inObj->classptr == class_finalizer ? kFinalizerSet : inObj->obj_sizeclass); } inline void PyrGC::ToBlack(PyrObjectHdr* obj) { if (IsGrey(obj)) { mNumGrey--; // post("ToBlack %d\n", mNumGrey); } DLRemove(obj); GCSet* gcs = GetGCSet(obj); DLInsertAfter(&gcs->mBlack, obj); obj->gc_color = mBlackColor; } inline void PyrGC::ToWhite(PyrObjectHdr* obj) { if (IsGrey(obj)) { mNumGrey--; // post("ToWhite %d\n", mNumGrey); } DLRemove(obj); GCSet* gcs = GetGCSet(obj); DLInsertAfter(&gcs->mWhite, obj); obj->gc_color = mWhiteColor; } inline void PyrGC::Free(PyrObjectHdr* obj) { if (IsGrey(obj)) { mNumGrey--; // post("ToWhite %d\n", mNumGrey); } DLRemove(obj); GCSet* gcs = GetGCSet(obj); DLInsertBefore(gcs->mFree, obj); gcs->mFree = obj; obj->gc_color = mFreeColor; obj->size = 0; } inline void PyrGC::ToGrey(PyrObjectHdr* obj) { /* move obj from white to grey */ /* link around object */ DLRemove(obj); /* link in new place */ DLInsertAfter(&mGrey, obj); /* set grey list pointer to obj */ obj->gc_color = mGreyColor; mNumGrey++; mNumToScan += 1L << obj->obj_sizeclass; } inline void PyrGC::ToGrey2(PyrObjectHdr* obj) { /* move obj from white to grey */ /* link around object */ DLRemove(obj); /* link in new place */ DLInsertAfter(&mGrey, obj); /* set grey list pointer to obj */ obj->gc_color = mGreyColor; mNumGrey++; } inline PyrObject* PyrGC::Allocate(size_t inNumBytes, int32 sizeclass, bool inRunCollection) { if (inRunCollection && mNumToScan >= kScanThreshold) Collect(); else { if (inRunCollection) mUncollectedAllocations = 0; else ++mUncollectedAllocations; } GCSet* gcs = mSets + sizeclass; PyrObject* obj = (PyrObject*)gcs->mFree; if (!IsMarker(obj)) { // from free list gcs->mFree = obj->next; assert(obj->obj_sizeclass == sizeclass); } else { if (sizeclass > kMaxPoolSet) { SweepBigObjects(); size_t allocSize = sizeof(PyrObjectHdr) + (sizeof(PyrSlot) << sizeclass); obj = (PyrObject*)mPool->Alloc(allocSize); } else { size_t allocSize = sizeof(PyrObjectHdr) + (sizeof(PyrSlot) << sizeclass); obj = (PyrObject*)mNewPool.Alloc(allocSize); } if (!obj) throwMemfailed(inNumBytes); DLInsertAfter(&gcs->mWhite, obj); obj->obj_sizeclass = sizeclass; } return obj; }
9,789
C++
.h
270
30.740741
113
0.683347
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,085
PyrSlot64.h
supercollider_supercollider/lang/LangSource/PyrSlot64.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. Copyright (c) 2009 Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once // generic pyrslot implementation #define PYR_SLOTS_GENERIC #include "SC_Endian.h" #include "SC_Types.h" #include "PyrErrors.h" #include <cstddef> #include <cassert> #include <vector> struct PyrSymbol; enum { tagNotInitialized, // uninitialized slots have a tag of 0 tagObj, tagInt, tagSym, tagChar, tagNil, // nil, false, and true are indicated by the tag alone. tagFalse, tagTrue, tagPtr, /* anything else is a double */ tagFloat, tagUnused, }; typedef struct pyrslot { long tag; union { int64 c; /* char */ int64 i; double f; void* ptr; struct PyrObject* o; PyrSymbol* s; struct PyrMethod* om; struct PyrBlock* oblk; struct PyrClass* oc; struct PyrFrame* of; struct PyrList* ol; struct PyrString* os; struct PyrInt8Array* ob; struct PyrDoubleArray* od; struct PyrSymbolArray* osym; struct PyrProcess* op; struct PyrThread* ot; struct PyrInterpreter* oi; } u; } PyrSlot; /* tag setter function */ inline int GetTag(const PyrSlot* slot) { return slot->tag; } /* tag checking functions */ inline bool IsObj(const PyrSlot* slot) { return slot->tag == tagObj; } inline bool NotObj(const PyrSlot* slot) { return slot->tag != tagObj; } inline bool IsNil(const PyrSlot* slot) { return slot->tag == tagNil; } inline bool NotNil(const PyrSlot* slot) { return slot->tag != tagNil; } inline bool IsFalse(const PyrSlot* slot) { return slot->tag == tagFalse; } inline bool IsTrue(const PyrSlot* slot) { return slot->tag == tagTrue; } inline bool IsSym(const PyrSlot* slot) { return slot->tag == tagSym; } inline bool NotSym(const PyrSlot* slot) { return slot->tag != tagSym; } inline bool IsChar(const PyrSlot* slot) { return slot->tag == tagChar; } inline bool NotChar(const PyrSlot* slot) { return slot->tag != tagChar; } inline bool IsInt(const PyrSlot* slot) { return slot->tag == tagInt; } inline bool NotInt(const PyrSlot* slot) { return slot->tag != tagInt; } inline bool IsFloat(const PyrSlot* slot) { return slot->tag == tagFloat; } inline bool NotFloat(const PyrSlot* slot) { return slot->tag != tagFloat; } inline bool IsPtr(const PyrSlot* slot) { return slot->tag == tagPtr; } inline bool NotPtr(const PyrSlot* slot) { return slot->tag != tagPtr; } /* setter functions */ inline void SetInt(PyrSlot* slot, int val) { slot->tag = tagInt; slot->u.i = val; } inline void SetObject(PyrSlot* slot, struct PyrObjectHdr* val) { slot->tag = tagObj; slot->u.o = (struct PyrObject*)(val); } inline void SetSymbol(PyrSlot* slot, PyrSymbol* val) { slot->tag = tagSym; slot->u.s = val; } inline void SetChar(PyrSlot* slot, char val) { slot->tag = tagChar; slot->u.c = val; } inline void SetPtr(PyrSlot* slot, void* val) { slot->tag = tagPtr; slot->u.ptr = (void*)val; } inline void SetObjectOrNil(PyrSlot* slot, struct PyrObject* val) { if (val) { slot->tag = tagObj; slot->u.o = val; } else { slot->tag = tagNil; slot->u.i = 0; } } inline void SetTrue(PyrSlot* slot) { slot->tag = tagTrue; slot->u.i = 0; } inline void SetFalse(PyrSlot* slot) { slot->tag = tagFalse; slot->u.i = 0; } inline void SetBool(PyrSlot* slot, bool test) { slot->tag = (test ? tagTrue : tagFalse); slot->u.i = 0; } inline void SetNil(PyrSlot* slot) { slot->tag = tagNil; slot->u.i = 0; } inline void SetFloat(PyrSlot* slot, double val) { slot->tag = tagFloat; slot->u.f = val; } /* raw setter functions, no typecheck */ inline void SetRawChar(PyrSlot* slot, int val) { assert(IsChar(slot)); slot->u.c = val; } inline void SetRaw(PyrSlot* slot, int val) { assert(IsInt(slot)); slot->u.i = val; } inline void SetRaw(PyrSlot* slot, long val) { assert(IsInt(slot)); slot->u.i = val; } inline void SetRaw(PyrSlot* slot, PyrObject* val) { assert(IsObj(slot)); slot->u.o = val; } inline void SetRaw(PyrSlot* slot, PyrSymbol* val) { assert(IsSym(slot)); slot->u.s = val; } inline void SetRaw(PyrSlot* slot, void* val) { assert(IsPtr(slot)); slot->u.ptr = val; } inline void SetRaw(PyrSlot* slot, double val) { assert(IsFloat(slot)); slot->u.f = val; } inline void SetTagRaw(PyrSlot* slot, int tag) { slot->tag = tag; } /* slot comparison */ inline bool SlotEq(const PyrSlot* a, const PyrSlot* b) { return (a->tag == b->tag) && (a->u.i == b->u.i); } /* extract numeric value */ template <typename numeric_type> inline int slotVal(PyrSlot* slot, numeric_type* value) { if (IsFloat(slot)) { *value = static_cast<numeric_type>(slot->u.f); return errNone; } else if (IsInt(slot)) { *value = static_cast<numeric_type>(slot->u.i); return errNone; } return errWrongType; } inline int slotFloatVal(PyrSlot* slot, float* value) { return slotVal<float>(slot, value); } inline int slotIntVal(PyrSlot* slot, int* value) { return slotVal<int>(slot, value); } inline int slotDoubleVal(PyrSlot* slot, double* value) { return slotVal<double>(slot, value); } /* get symbol */ inline int slotSymbolVal(PyrSlot* slot, PyrSymbol** symbol) { if (!IsSym(slot)) return errWrongType; *symbol = slot->u.s; return errNone; } /* raw access functions */ inline void* slotRawPtr(PyrSlot* slot) { assert(IsPtr(slot) || (slot->u.ptr == NULL && IsNil(slot))); return slot->u.ptr; } inline PyrBlock* slotRawBlock(PyrSlot* slot) { return slot->u.oblk; } inline PyrSymbolArray* slotRawSymbolArray(PyrSlot* slot) { return slot->u.osym; } inline PyrDoubleArray* slotRawDoubleArray(PyrSlot* slot) { return slot->u.od; } inline PyrInt8Array* slotRawInt8Array(PyrSlot* slot) { return slot->u.ob; } inline PyrMethod* slotRawMethod(PyrSlot* slot) { return slot->u.om; } inline const PyrMethod* slotRawMethod(const PyrSlot* slot) { return slot->u.om; } inline PyrThread* slotRawThread(PyrSlot* slot) { return slot->u.ot; } inline PyrString* slotRawString(PyrSlot* slot) { return slot->u.os; } inline PyrList* slotRawList(PyrSlot* slot) { return slot->u.ol; } inline PyrFrame* slotRawFrame(PyrSlot* slot) { return slot->u.of; } inline PyrClass* slotRawClass(PyrSlot* slot) { return slot->u.oc; } inline const PyrClass* slotRawClass(const PyrSlot* slot) { return slot->u.oc; } inline PyrInterpreter* slotRawInterpreter(PyrSlot* slot) { return slot->u.oi; } inline PyrSymbol* slotRawSymbol(PyrSlot* slot) { return slot->u.s; } inline const PyrSymbol* slotRawSymbol(const PyrSlot* slot) { return slot->u.s; } inline int slotRawChar(const PyrSlot* slot) { return slot->u.c; } inline int slotRawInt(const PyrSlot* slot) { assert(IsInt(slot)); return slot->u.i; } inline double slotRawFloat(const PyrSlot* slot) { assert(IsFloat(slot)); return slot->u.f; } inline PyrObject* slotRawObject(PyrSlot* slot) { assert(IsObj(slot)); return slot->u.o; } inline const PyrObject* slotRawObject(const PyrSlot* slot) { assert(IsObj(slot)); return slot->u.o; } /* slot copy functions */ inline void slotCopy(PyrSlot* dst, const PyrSlot* src) { *dst = *src; } inline void slotCopy(PyrSlot* dst, const PyrSlot* src, int num) { for (int i = 0; i < num; ++i) slotCopy(dst + i, src + i); }
8,257
C++
.h
229
32.353712
107
0.687571
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,086
PyrErrors.h
supercollider_supercollider/lang/LangSource/PyrErrors.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* virtual machine error codes. */ #pragma once enum { // primitive errors errReturn = -1, // not really an error.. primitive executed a non-local return errNone, errFailed = 5000, errBadPrimitive, errWrongType, errIndexNotAnInteger, errIndexOutOfRange, errImmutableObject, errNotAnIndexableObject, errStackOverflow, errOutOfMemory, errCantCallOS, errException, errPropertyNotFound = 6000, errLastError };
1,345
C++
.h
37
31.972973
82
0.751347
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,087
PyrSignal.h
supercollider_supercollider/lang/LangSource/PyrSignal.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "PyrObject.h" #include "GC.h" #define UNROLL 1 enum { kSignalRate = 0, // index of rate slot kSignalNextNode }; PyrObject* newPyrSignal(VMGlobals* g, long size); #define UNROLL8_CODE(size, var, stmt) \ { \ int tempi, tempend; \ tempend = size >> 3; \ for (tempi = 0; tempi < tempend; ++tempi) { \ stmt; \ stmt; \ stmt; \ stmt; \ stmt; \ stmt; \ stmt; \ stmt; \ } \ tempend = size & 7; \ for (tempi = 0; tempi < tempend; ++tempi) { \ stmt; \ } \ } #define UNROLL4_CODE(size, var, stmt) \ { \ int tempi, tempend; \ tempend = size >> 2; \ for (tempi = 0; tempi < tempend; ++tempi) { \ stmt; \ stmt; \ stmt; \ stmt; \ } \ tempend = size & 3; \ for (tempi = 0; tempi < tempend; ++tempi) { \ stmt; \ } \ } #define FILTER_LOOP(size, var, stmt, stmt2) \ { \ int tempi, tempend; \ tempend = size >> 2; \ for (tempi = 0; tempi < tempend; ++tempi) { \ stmt; \ stmt; \ stmt; \ stmt; \ stmt2; \ } \ tempend = size & 3; \ for (tempi = 0; tempi < tempend; ++tempi) { \ stmt; \ } \ } #define UNROLL1_CODE(size, var, stmt) \ { \ int tempi, tempend; \ tempend = size; \ for (tempi = 0; tempi < tempend; ++tempi) { \ stmt; \ } \ } #if UNROLL == 8 # define UNROLL_CODE UNROLL8_CODE #elif UNROLL == 4 # define UNROLL_CODE UNROLL4_CODE #else # define UNROLL_CODE UNROLL1_CODE #endif #if 0 # define BINOP_LOOP1(OP) # define BINOP_LOOP2(STMT1, STMT2, STMT3) #else # define BINOP_LOOP1(OP) \ float *a, *b, *c, *endptr; \ PyrObject* outc; \ long size; \ a = (float*)(ina->slots) - 1; \ b = (float*)(inb->slots) - 1; \ size = sc_min(ina->size, inb->size); \ outc = newPyrSignal(g, size); \ c = (float*)(outc->slots) - 1; \ endptr = c + size; \ switch (size & 3) { \ while (c < endptr) { \ *++c = *++a OP * ++b; \ case 3: \ *++c = *++a OP * ++b; \ case 2: \ *++c = *++a OP * ++b; \ case 1: \ *++c = *++a OP * ++b; \ case 0:; \ } \ } \ return outc; # define BINOP_LOOP2(STMT1) \ float *a, *b, *c, *endptr; \ PyrObject* outc; \ long size; \ a = (float*)(ina->slots) - 1; \ b = (float*)(inb->slots) - 1; \ size = sc_min(ina->size, inb->size); \ outc = newPyrSignal(g, size); \ c = (float*)(outc->slots) - 1; \ endptr = c + size; \ switch (size & 3) { \ while (c < endptr) { \ STMT1; \ case 3: \ STMT1; \ case 2: \ STMT1; \ case 1: \ STMT1; \ case 0:; \ } \ } \ return outc; #endif /* compound formulas : amclip out = B<=0 ? 0 : A*B; // two quadrant amplitude modulation ring1 out = A*(B+1) = A*B + A; // amplitude modulation of a by b. ring2 out = A*B + A + B; // ring modulation plus both original signals ring3 out = A*A*B; // ring modulation variant ring4 out = A*A*B - A*B*B; // ring modulation variant difsqr out = A*A - B*B; // difference of squares sumsqr out = A*A + B*B; // sum of squares sqrdif out = (A - B)^2 // square of the difference = a^2 + b^2 - 2ab sqrsum out = (A + B)^2 // square of the sum = a^2 + b^2 + 2ab */ void signal_init_globs(); PyrObject* signal_fill(PyrObject* outSignal, float inValue); PyrObject* signal_scale(PyrObject* outSignal, float inValue); PyrObject* signal_offset(PyrObject* outSignal, float inValue); PyrObject* signal_scale_offset(PyrObject* outSignal, float mul, float add); PyrObject* signal_mix(PyrObject* ina, PyrObject* inb, float start, float end, float slopeFactor); PyrObject* signal_add_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb); PyrObject* signal_sub_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb); PyrObject* signal_mul_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb); PyrObject* signal_mul_ds_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb); PyrObject* signal_add_ds_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb); PyrObject* signal_sub_ds_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb); PyrObject* signal_ring1_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb); PyrObject* signal_ring2_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb); PyrObject* signal_ring3_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb); PyrObject* signal_ring4_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb); PyrObject* signal_thresh_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb); PyrObject* signal_amclip_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb); PyrObject* signal_div_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb); PyrObject* signal_difsqr_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb); PyrObject* signal_sumsqr_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb); PyrObject* signal_sqrsum_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb); PyrObject* signal_sqrdif_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb); PyrObject* signal_add_xf(VMGlobals* g, PyrObject* ina, float inb); PyrObject* signal_sub_xf(VMGlobals* g, PyrObject* ina, float inb); PyrObject* signal_mul_xf(VMGlobals* g, PyrObject* ina, float inb); PyrObject* signal_ring1_xf(VMGlobals* g, PyrObject* ina, float inb); PyrObject* signal_ring2_xf(VMGlobals* g, PyrObject* ina, float inb); PyrObject* signal_ring3_xf(VMGlobals* g, PyrObject* ina, float inb); PyrObject* signal_ring4_xf(VMGlobals* g, PyrObject* ina, float inb); PyrObject* signal_thresh_xf(VMGlobals* g, PyrObject* ina, float inb); PyrObject* signal_amclip_xf(VMGlobals* g, PyrObject* ina, float inb); PyrObject* signal_div_xf(VMGlobals* g, PyrObject* ina, float inb); PyrObject* signal_difsqr_xf(VMGlobals* g, PyrObject* ina, float inb); PyrObject* signal_sumsqr_xf(VMGlobals* g, PyrObject* ina, float inb); PyrObject* signal_sqrsum_xf(VMGlobals* g, PyrObject* ina, float inb); PyrObject* signal_sqrdif_xf(VMGlobals* g, PyrObject* ina, float inb); PyrObject* signal_ring1_fx(VMGlobals* g, float ina, PyrObject* inb); PyrObject* signal_ring2_fx(VMGlobals* g, float ina, PyrObject* inb); PyrObject* signal_ring3_fx(VMGlobals* g, float ina, PyrObject* inb); PyrObject* signal_ring4_fx(VMGlobals* g, float ina, PyrObject* inb); PyrObject* signal_thresh_fx(VMGlobals* g, float ina, PyrObject* inb); PyrObject* signal_amclip_fx(VMGlobals* g, float ina, PyrObject* inb); PyrObject* signal_sub_fx(VMGlobals* g, float ina, PyrObject* inb); PyrObject* signal_div_fx(VMGlobals* g, float ina, PyrObject* inb); PyrObject* signal_difsqr_fx(VMGlobals* g, float ina, PyrObject* inb); PyrObject* signal_sumsqr_fx(VMGlobals* g, float ina, PyrObject* inb); PyrObject* signal_sqrsum_fx(VMGlobals* g, float ina, PyrObject* inb); PyrObject* signal_sqrdif_fx(VMGlobals* g, float ina, PyrObject* inb); PyrObject* signal_min_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb); PyrObject* signal_max_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb); PyrObject* signal_min_xf(VMGlobals* g, PyrObject* ina, float inb); PyrObject* signal_max_xf(VMGlobals* g, PyrObject* ina, float inb); PyrObject* signal_invert(VMGlobals* g, PyrObject* inPyrSignal); PyrObject* signal_recip(VMGlobals* g, PyrObject* inPyrSignal); PyrObject* signal_squared(VMGlobals* g, PyrObject* inPyrSignal); PyrObject* signal_cubed(VMGlobals* g, PyrObject* inPyrSignal); PyrObject* signal_abs(VMGlobals* g, PyrObject* inPyrSignal); PyrObject* signal_sign(VMGlobals* g, PyrObject* inPyrSignal); PyrObject* signal_negative(VMGlobals* g, PyrObject* inPyrSignal); PyrObject* signal_positive(VMGlobals* g, PyrObject* inPyrSignal); PyrObject* signal_strictly_positive(VMGlobals* g, PyrObject* inPyrSignal); PyrObject* signal_nyqring(VMGlobals* g, PyrObject* inPyrSignal); PyrObject* signal_clip_f(VMGlobals* g, PyrObject* inPyrSignal, float lo, float hi); PyrObject* signal_clip_f_ds(PyrObject* inPyrSignal, float lo, float hi); PyrObject* signal_clip_x(VMGlobals* g, PyrObject* ina, PyrObject* inb, PyrObject* inc); PyrObject* signal_wrap_f(VMGlobals* g, PyrObject* inPyrSignal, float lo, float hi); PyrObject* signal_wrap_x(VMGlobals* g, PyrObject* ina, PyrObject* inb, PyrObject* inc); PyrObject* signal_fold_f(VMGlobals* g, PyrObject* inPyrSignal, float lo, float hi); PyrObject* signal_fold_x(VMGlobals* g, PyrObject* ina, PyrObject* inb, PyrObject* inc); PyrObject* signal_log(VMGlobals* g, PyrObject* inPyrSignal); PyrObject* signal_log2(VMGlobals* g, PyrObject* inPyrSignal); PyrObject* signal_log10(VMGlobals* g, PyrObject* inPyrSignal); PyrObject* signal_sin(VMGlobals* g, PyrObject* inPyrSignal); PyrObject* signal_cos(VMGlobals* g, PyrObject* inPyrSignal); PyrObject* signal_tan(VMGlobals* g, PyrObject* inPyrSignal); PyrObject* signal_sinh(VMGlobals* g, PyrObject* inPyrSignal); PyrObject* signal_cosh(VMGlobals* g, PyrObject* inPyrSignal); PyrObject* signal_tanh(VMGlobals* g, PyrObject* inPyrSignal); PyrObject* signal_asin(VMGlobals* g, PyrObject* inPyrSignal); PyrObject* signal_acos(VMGlobals* g, PyrObject* inPyrSignal); PyrObject* signal_atan(VMGlobals* g, PyrObject* inPyrSignal); PyrObject* signal_exp(VMGlobals* g, PyrObject* inPyrSignal); PyrObject* signal_sqrt(VMGlobals* g, PyrObject* inPyrSignal); PyrObject* signal_distort(VMGlobals* g, PyrObject* inPyrSignal); PyrObject* signal_distortneg(VMGlobals* g, PyrObject* inPyrSignal); PyrObject* signal_softclip(VMGlobals* g, PyrObject* inPyrSignal); PyrObject* signal_softclipneg(VMGlobals* g, PyrObject* inPyrSignal); PyrObject* signal_fsin(VMGlobals* g, PyrObject* inPyrSignal); PyrObject* signal_poly3(VMGlobals* g, PyrObject* inPyrSignal, float a, float b, float c); PyrObject* signal_poly3r(VMGlobals* g, PyrObject* inPyrSignal, float a1, float a2, float b1, float b2, float c1, float c2, float slopeFactor); PyrObject* signal_integrate(VMGlobals* g, PyrObject* inPyrSignal, float* ioSum); PyrObject* signal_leakdc(VMGlobals* g, PyrObject* inPyrSignal, float* ioDC, float leakFactor); PyrObject* signal_ampflw1(VMGlobals* g, PyrObject* inPyrSignal, float* ioAmp, float leak1); PyrObject* signal_ampflw2(VMGlobals* g, PyrObject* inPyrSignal, float* ioAmp, float leak1); PyrObject* signal_differentiate(VMGlobals* g, PyrObject* inPyrSignal, float* ioPrev); PyrObject* signal_rotate(VMGlobals* g, PyrObject* ina, int rot); PyrObject* signal_reverse_ds(PyrObject* ina); PyrObject* signal_cat(VMGlobals* g, PyrObject* ina, PyrObject* inb); PyrObject* signal_insert(VMGlobals* g, PyrObject* ina, PyrObject* inb, long index); PyrObject* signal_overdub(VMGlobals* g, PyrObject* ina, PyrObject* inb, long index); PyrObject* signal_overwrite(VMGlobals* g, PyrObject* ina, PyrObject* inb, long index); PyrObject* signal_cat3(VMGlobals* g, PyrObject* ina, PyrObject* inb, PyrObject* inc); PyrObject* signal_linen(VMGlobals* g, PyrObject* ina, long atk, long dcy, float amp); PyrObject* signal_linen2(VMGlobals* g, PyrObject* ina, long atk, long dcy, float amp, float midamp); PyrObject* signal_writesplice(VMGlobals* g, PyrObject* outc, PyrObject* ina, PyrObject* inb, long indexc, long indexa, long indexb, long fadelen, float midamp); PyrObject* signal_splice(VMGlobals* g, PyrObject* ina, PyrObject* inb, long indexa, long indexb, long fadelen, float midamp); PyrObject* signal_invert_ds(PyrObject* inPyrSignal); PyrObject* signal_recip_ds(PyrObject* inPyrSignal); PyrObject* signal_squared_ds(PyrObject* inPyrSignal); PyrObject* signal_cubed_ds(PyrObject* inPyrSignal); PyrObject* signal_abs_ds(PyrObject* inPyrSignal); PyrObject* signal_sign_ds(PyrObject* inPyrSignal); PyrObject* signal_negative_ds(PyrObject* inPyrSignal); PyrObject* signal_positive_ds(PyrObject* inPyrSignal); PyrObject* signal_strictly_positive_ds(PyrObject* inPyrSignal); PyrObject* signal_nyqring_ds(PyrObject* inPyrSignal); PyrObject* signal_clipneg_ds(PyrObject* inPyrSignal); PyrObject* signal_distort_ds(PyrObject* inPyrSignal); PyrObject* signal_distortneg_ds(PyrObject* inPyrSignal); PyrObject* signal_softclip_ds(PyrObject* inPyrSignal); PyrObject* signal_softclipneg_ds(PyrObject* inPyrSignal); PyrObject* signal_fsin_ds(PyrObject* inPyrSignal); PyrObject* signal_log_ds(PyrObject* inPyrSignal); PyrObject* signal_log2_ds(PyrObject* inPyrSignal); PyrObject* signal_log10_ds(PyrObject* inPyrSignal); PyrObject* signal_sin_ds(PyrObject* inPyrSignal); PyrObject* signal_cos_ds(PyrObject* inPyrSignal); PyrObject* signal_tan_ds(PyrObject* inPyrSignal); PyrObject* signal_sinh_ds(PyrObject* inPyrSignal); PyrObject* signal_cosh_ds(PyrObject* inPyrSignal); PyrObject* signal_tanh_ds(PyrObject* inPyrSignal); PyrObject* signal_asin_ds(PyrObject* inPyrSignal); PyrObject* signal_acos_ds(PyrObject* inPyrSignal); PyrObject* signal_atan_ds(PyrObject* inPyrSignal); PyrObject* signal_exp_ds(PyrObject* inPyrSignal); PyrObject* signal_sqrt_ds(PyrObject* inPyrSignal); float signal_findpeak(PyrObject* inPyrSignal); PyrObject* signal_normalize(PyrObject* inPyrSignal); PyrObject* signal_normalize_transfer_fn(PyrObject* inPyrSignal); float signal_integral(PyrObject* inPyrSignal); PyrObject* signal_combself(VMGlobals* g, PyrObject* ina, long rot); PyrObject* signal_bilinen(VMGlobals* g, PyrObject* ina, long atk, long dcy, float amp, float midamp); PyrObject* signal_lace2(VMGlobals* g, PyrObject* ina, PyrObject* inb); void signal_unlace2(VMGlobals* g, PyrObject* ina, PyrObject** outb, PyrObject** outc); void signal_convolve(VMGlobals* g, PyrObject* ina, PyrObject* ir, PyrObject* previn, long* ppos); PyrObject* signal_thumbnail(VMGlobals* g, PyrObject* ina, long startpos, long length, int binsize); PyrObject* signal_scaleneg_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb); PyrObject* signal_scaleneg_xf(VMGlobals* g, PyrObject* ina, float inb); PyrObject* signal_scaleneg_fx(VMGlobals* g, float ina, PyrObject* inb); PyrObject* signal_clip2_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb); PyrObject* signal_clip2_xf(VMGlobals* g, PyrObject* ina, float inb); PyrObject* signal_clip2_fx(VMGlobals* g, float ina, PyrObject* inb); PyrObject* signal_fold2_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb); PyrObject* signal_fold2_xf(VMGlobals* g, PyrObject* ina, float inb); PyrObject* signal_fold2_fx(VMGlobals* g, float ina, PyrObject* inb); PyrObject* signal_wrap2_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb); PyrObject* signal_wrap2_xf(VMGlobals* g, PyrObject* ina, float inb); PyrObject* signal_wrap2_fx(VMGlobals* g, float ina, PyrObject* inb); PyrObject* signal_excess_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb); PyrObject* signal_excess_xf(VMGlobals* g, PyrObject* ina, float inb); PyrObject* signal_excess_fx(VMGlobals* g, float ina, PyrObject* inb); PyrObject* signal_absdif_fx(VMGlobals* g, float ina, PyrObject* inb); PyrObject* signal_absdif_xf(VMGlobals* g, PyrObject* ina, float inb); PyrObject* signal_absdif_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb); bool signal_equal_xf(VMGlobals* g, PyrObject* ina, float inb); bool signal_equal_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb); void signal_get_bounds(PyrObject* ina, float* ominval, float* omaxval); void signal_smooth_ds(PyrObject* inPyrSignal); void signal_hanning_ds(PyrObject* inPyrSignal); void signal_welch_ds(PyrObject* inPyrSignal); void signal_parzen_ds(PyrObject* inPyrSignal); PyrObject* signal_normalize_range(PyrObject* ina, long start, long end); PyrObject* signal_zero_range(PyrObject* ina, long start, long end); PyrObject* signal_invert_range(PyrObject* ina, long start, long end); PyrObject* signal_reverse_range(PyrObject* ina, long start, long end); PyrObject* signal_fade_in(PyrObject* ina, long start, long end); PyrObject* signal_fade_out(PyrObject* ina, long start, long end); PyrObject* signal_abs_range(PyrObject* ina, long start, long end); PyrObject* signal_squared_range(PyrObject* ina, long start, long end); PyrObject* signal_cubed_range(PyrObject* ina, long start, long end); PyrObject* signal_distort_range(PyrObject* ina, long start, long end); PyrObject* signal_fade_range(PyrObject* ina, long start, long end, float lvl0, float lvl1);
26,572
C++
.h
339
73.932153
120
0.459401
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,089
ReadWriteMacros.h
supercollider_supercollider/lang/LangPrimSource/ReadWriteMacros.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "SC_Types.h" #include "SC_Endian.h" #include <stdio.h> #include <string.h> #include <stdexcept> template <class T> class SC_IOStream { protected: T s; public: SC_IOStream(): s(0) {} SC_IOStream(T inStream): s(inStream) {} void SetStream(T inStream) { s = inStream; } T GetStream() { return s; } // core routines void readData(char* data, size_t size); uint8 readUInt8(); void writeData(char* data, size_t size); void writeUInt8(uint8 inInt); // built using core routines void writeInt8(int8 inInt) { writeUInt8((uint8)inInt); } void writeInt16_be(int16 inInt) { writeUInt8((uint8)(inInt >> 8)); writeUInt8(inInt); } void writeInt16_le(int16 inInt) { writeUInt8((uint8)inInt); writeUInt8((uint8)(inInt >> 8)); } void writeInt32_be(int32 inInt) { writeUInt8((uint8)(inInt >> 24)); writeUInt8((uint8)(inInt >> 16)); writeUInt8((uint8)(inInt >> 8)); writeUInt8((uint8)inInt); } void writeInt32_le(int32 inInt) { writeUInt8((uint8)inInt); writeUInt8((uint8)(inInt >> 8)); writeUInt8((uint8)(inInt >> 16)); writeUInt8((uint8)(inInt >> 24)); } #if BYTE_ORDER == BIG_ENDIAN void writeFloat_be(float inFloat) #else void writeFloat_le(float inFloat) #endif { union { float f; uint8 c[4]; } u; u.f = inFloat; writeUInt8(u.c[0]); writeUInt8(u.c[1]); writeUInt8(u.c[2]); writeUInt8(u.c[3]); } #if BYTE_ORDER == BIG_ENDIAN void writeFloat_le(float inFloat) #else void writeFloat_be(float inFloat) #endif { union { float f; uint8 c[4]; } u; u.f = inFloat; writeUInt8(u.c[3]); writeUInt8(u.c[2]); writeUInt8(u.c[1]); writeUInt8(u.c[0]); } #if BYTE_ORDER == BIG_ENDIAN void writeDouble_be(double inDouble) #else void writeDouble_le(double inDouble) #endif { union { double f; uint8 c[8]; } u; u.f = inDouble; writeUInt8(u.c[0]); writeUInt8(u.c[1]); writeUInt8(u.c[2]); writeUInt8(u.c[3]); writeUInt8(u.c[4]); writeUInt8(u.c[5]); writeUInt8(u.c[6]); writeUInt8(u.c[7]); } #if BYTE_ORDER == BIG_ENDIAN void writeDouble_le(double inDouble) #else void writeDouble_be(double inDouble) #endif { union { double f; uint8 c[8]; } u; u.f = inDouble; writeUInt8(u.c[7]); writeUInt8(u.c[6]); writeUInt8(u.c[5]); writeUInt8(u.c[4]); writeUInt8(u.c[3]); writeUInt8(u.c[2]); writeUInt8(u.c[1]); writeUInt8(u.c[0]); } int8 readInt8() { return (int8)readUInt8(); } int16 readInt16_be() { uint8 a = readUInt8(); uint8 b = readUInt8(); return (int16)((a << 8) | b); } int16 readInt16_le() { uint8 a = readUInt8(); uint8 b = readUInt8(); return (int16)((b << 8) | a); } int32 readInt32_be() { uint8 a = readUInt8(); uint8 b = readUInt8(); uint8 c = readUInt8(); uint8 d = readUInt8(); return (int32)((a << 24) | (b << 16) | (c << 8) | d); } int32 readInt32_le() { uint8 a = readUInt8(); uint8 b = readUInt8(); uint8 c = readUInt8(); uint8 d = readUInt8(); return (int32)((d << 24) | (c << 16) | (b << 8) | a); } #if BYTE_ORDER == BIG_ENDIAN float readFloat_be() #else float readFloat_le() #endif { union { float f; uint8 c[4]; } u; u.c[0] = readUInt8(); u.c[1] = readUInt8(); u.c[2] = readUInt8(); u.c[3] = readUInt8(); return u.f; } #if BYTE_ORDER == BIG_ENDIAN float readFloat_le() #else float readFloat_be() #endif { union { float f; uint8 c[4]; } u; u.c[3] = readUInt8(); u.c[2] = readUInt8(); u.c[1] = readUInt8(); u.c[0] = readUInt8(); return u.f; } #if BYTE_ORDER == BIG_ENDIAN double readDouble_be() #else double readDouble_le() #endif { union { double f; uint8 c[8]; } u; u.c[0] = readUInt8(); u.c[1] = readUInt8(); u.c[2] = readUInt8(); u.c[3] = readUInt8(); u.c[4] = readUInt8(); u.c[5] = readUInt8(); u.c[6] = readUInt8(); u.c[7] = readUInt8(); return u.f; } #if BYTE_ORDER == BIG_ENDIAN double readDouble_le() #else double readDouble_be() #endif { union { double f; uint8 c[8]; } u; u.c[7] = readUInt8(); u.c[6] = readUInt8(); u.c[5] = readUInt8(); u.c[4] = readUInt8(); u.c[3] = readUInt8(); u.c[2] = readUInt8(); u.c[1] = readUInt8(); u.c[0] = readUInt8(); return u.f; } void readSymbol(char* outString) { int length = readUInt8(); readData(outString, length); outString[length] = 0; } void writeSymbol(char* inString) { size_t length = strlen(inString); writeUInt8((uint8)length); writeData(inString, length); } }; // core routines template <> inline void SC_IOStream<FILE*>::readData(char* data, size_t size) { size_t read = fread(data, 1, size, s); if (read != size) throw std::runtime_error("SC_IOStream<FILE*>::readData: read != size"); } template <> inline uint8 SC_IOStream<FILE*>::readUInt8() { return (uint8)fgetc(s); } template <> inline void SC_IOStream<FILE*>::writeData(char* data, size_t size) { fwrite(data, 1, size, s); } template <> inline void SC_IOStream<FILE*>::writeUInt8(uint8 inInt) { fputc(inInt, s); } // core routines template <> inline void SC_IOStream<char*>::readData(char* data, size_t size) { memcpy(data, s, size); s += size; } template <> inline uint8 SC_IOStream<char*>::readUInt8() { return (uint8)*s++; } template <> inline void SC_IOStream<char*>::writeData(char* data, size_t size) { memcpy(s, data, size); s += size; } template <> inline void SC_IOStream<char*>::writeUInt8(uint8 inInt) { *s++ = (inInt & 255); }
7,297
C++
.h
257
21.824903
108
0.568101
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,090
SC_Levenshtein.h
supercollider_supercollider/lang/LangPrimSource/SC_Levenshtein.h
/* SC_Levenshtein.h Copyright (c) 2019 James Surgenor This is a header-only, templated functor to compute the Levenshtein distance between two arrays. It uses the reduced memory footprint version, based on Martin Ettl's implementation, and is written as a functor to facilitate even greater memory savings if a single instance is used (although only one comparison can be made at a time). It is self-contained, so could easily be multithreaded. Thanks to Brian Heim ==================================================================== SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include <vector> #include <functional> #include <numeric> template <typename T> struct levenshteinDistance { size_t operator()( const T* dataA, size_t sizeA, const T* dataB, size_t sizeB, std::function<bool(const T&, const T&)> compareFunc = [](const T& a, const T& b) { return a == b; }) { // reduce memory by comparing against the smallest array if (sizeA < sizeB) { std::swap(dataA, dataB); std::swap(sizeA, sizeB); } // empty array optimisation if (sizeA == 0 || sizeB == 0) { return sizeA; } matrix.resize(sizeB + 1); // initialise matrix std::iota(matrix.begin(), matrix.end(), 0); // calculate the distances for (size_t indX = 0; indX < sizeA; ++indX) { matrix[0] = indX + 1; size_t corner = indX; for (size_t indY = 0; indY < sizeB; ++indY) { size_t upper = matrix[indY + 1]; if (compareFunc(dataA[indX], dataB[indY])) matrix[indY + 1] = corner; else matrix[indY + 1] = std::min({ upper, corner, matrix[indY] }) + 1; corner = upper; } } return matrix[sizeB]; } private: std::vector<size_t> matrix; };
2,797
C++
.h
62
37.209677
116
0.627256
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,091
PyrListPrim.h
supercollider_supercollider/lang/LangPrimSource/PyrListPrim.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once void initArrayPrimitives(); int prArrayMultiChanExpand(VMGlobals* g, int numArgsPushed); bool identDict_lookupNonNil(PyrObject* dict, PyrSlot* key, int hash, PyrSlot* result); int arrayAtIdentityHash(PyrObject* array, PyrSlot* key); int arrayAtIdentityHashInPairs(PyrObject* array, PyrSlot* key); int arrayAtIdentityHashInPairsWithHash(PyrObject* array, PyrSlot* key, int hash);
1,270
C++
.h
23
51.434783
86
0.781275
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,092
SC_Clock.hpp
supercollider_supercollider/lang/LangPrimSource/SC_Clock.hpp
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef SC_CLOCK_INCLUDED #define SC_CLOCK_INCLUDED #include "PyrKernel.h" #include "PyrSched.h" #include "GC.h" #include "PyrPrimitive.h" #include "PyrSymbol.h" // heaps use an integer timestamp to ensure stable heap order struct PyrHeap : PyrObjectHdr { PyrSlot count; // stability count PyrSlot slots[0]; // slots }; class TempoClock { public: TempoClock(VMGlobals* inVMGlobals, PyrObject* inTempoClockObj, double inTempo, double inBaseBeats, double inBaseSeconds); virtual ~TempoClock() {} void StopReq(); void Stop(); void StopAndDelete() { Stop(); delete this; } void* Run(); void Add(double inBeats, PyrSlot* inTask); void SetTempoAtBeat(double inTempo, double inBeats); void SetTempoAtTime(double inTempo, double inSeconds); void SetAll(double inTempo, double inBeats, double inSeconds); double ElapsedBeats(); void Clear(); // void Flush(); double GetTempo() const { return mTempo; } double GetBeatDur() const { return mBeatDur; } virtual double BeatsToSecs(double beats) const { return (beats - mBaseBeats) * mBeatDur + mBaseSeconds; } virtual double SecsToBeats(double secs) const { return (secs - mBaseSeconds) * mTempo + mBaseBeats; } void Dump(); static TempoClock* GetAll() { return sAll; } TempoClock* GetNext() const { return mNext; } static void InitAll() { sAll = 0; } protected: VMGlobals* g; PyrObject* mTempoClockObj; PyrHeap* mQueue; double mTempo; // beats per second double mBeatDur; // 1/tempo double mBeats; // beats double mBaseSeconds; double mBaseBeats; bool mRun; SC_Thread mThread; condition_variable_any mCondition; private: TempoClock *mPrev, *mNext; static TempoClock* sAll; }; // Clock primitives template <typename Clock> int prClock_New(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp - 3; PyrSlot* b = g->sp - 2; PyrSlot* c = g->sp - 1; PyrSlot* d = g->sp; double tempo; int err = slotDoubleVal(b, &tempo); if (err) tempo = 1.; if (tempo <= 0.) { error("negative tempo %g is invalid\n", tempo); SetPtr(slotRawObject(a)->slots + 1, NULL); return errFailed; } double beats; err = slotDoubleVal(c, &beats); if (err) beats = 0.; double seconds; err = slotDoubleVal(d, &seconds); if (err) { err = slotDoubleVal(&g->thread->seconds, &seconds); if (err) return err; } try { Clock* clock = new Clock(g, slotRawObject(a), tempo, beats, seconds); SetPtr(slotRawObject(a)->slots + 1, clock); } catch (int err) { return err; } return errNone; } template <typename Clock> int prClock_SetBeats(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp - 1; PyrSlot* b = g->sp; Clock* clock = (Clock*)slotRawPtr(&slotRawObject(a)->slots[1]); if (!clock) { error("clock is not running.\n"); return errFailed; } double beats, seconds; int err; err = slotDoubleVal(b, &beats); if (err) return errWrongType; err = slotDoubleVal(&g->thread->seconds, &seconds); if (err) return errWrongType; clock->SetAll(clock->GetTempo(), beats, seconds); return errNone; } template <typename Clock> int prClock_SetTempoAtBeat(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp - 2; PyrSlot* b = g->sp - 1; PyrSlot* c = g->sp; Clock* clock = (Clock*)slotRawPtr(&slotRawObject(a)->slots[1]); if (!clock) { error("clock is not running.\n"); return errFailed; } if (clock->GetTempo() <= 0.f) { error("cannot set negative tempo from this method. Use 'etempo_' instead.\n"); // prTempoClock_SetTempoAtTime can be used. return errFailed; } double tempo, beat; int err = slotDoubleVal(b, &tempo); if (err) return errWrongType; if (tempo <= 0.) { error("negative tempo %g is invalid. Use 'etempo_' instead.\n", tempo); // prTempoClock_SetTempoAtTime can be used. return errFailed; } err = slotDoubleVal(c, &beat); if (err) return errWrongType; clock->SetTempoAtBeat(tempo, beat); return errNone; } template <typename Clock> int prClock_SetAll(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp - 3; PyrSlot* b = g->sp - 2; PyrSlot* c = g->sp - 1; PyrSlot* d = g->sp; Clock* clock = (Clock*)slotRawPtr(&slotRawObject(a)->slots[1]); if (!clock) { error("clock is not running.\n"); return errFailed; } double tempo, beat, secs; int err = slotDoubleVal(b, &tempo); if (err) return errWrongType; err = slotDoubleVal(c, &beat); if (err) return errWrongType; err = slotDoubleVal(d, &secs); if (err) return errWrongType; clock->SetAll(tempo, beat, secs); return errNone; } template <typename Clock> int prClock_SetTempoAtTime(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp - 2; PyrSlot* b = g->sp - 1; PyrSlot* c = g->sp; Clock* clock = (Clock*)slotRawPtr(&slotRawObject(a)->slots[1]); if (!clock) { error("clock is not running.\n"); return errFailed; } double tempo, sec; int err = slotDoubleVal(b, &tempo); if (err) return errWrongType; err = slotDoubleVal(c, &sec); if (err) return errWrongType; clock->SetTempoAtTime(tempo, sec); return errNone; } template <typename DurationType> inline double DurToFloat(DurationType dur) { using namespace std::chrono; seconds secs = duration_cast<seconds>(dur); return duration_cast<duration<double, std::ratio<1>>>(dur).count(); } #endif
6,708
C++
.h
199
28.306533
109
0.65774
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,093
SC_FIFO.h
supercollider_supercollider/lang/LangPrimSource/SC_FIFO.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #ifdef __APPLE__ # include <libkern/OSAtomic.h> #endif #ifdef _WIN32 # include <winsock2.h> # include <windows.h> #endif template <class T, int N> class SC_FIFO { public: SC_FIFO(): mMask(N - 1), mReadHead(0), mWriteHead(0) {} void MakeEmpty() { mReadHead = mWriteHead; } bool IsEmpty() { return mReadHead == mWriteHead; } bool HasData() { return mReadHead != mWriteHead; } bool Put(T data) { long next = NextPos(mWriteHead); if (next == mReadHead) return false; // fifo is full mItems[next] = data; #ifdef __APPLE__ // we don't really need a compare and swap, but this happens to call // the PowerPC memory barrier instruction lwsync. OSAtomicCompareAndSwap32Barrier(mWriteHead, next, &mWriteHead); #elif defined(_WIN32) InterlockedExchange(reinterpret_cast<volatile LONG*>(&mWriteHead), next); #else mWriteHead = next; #endif return true; } T Get() { // assert(HasData()); long next = NextPos(mReadHead); T out = mItems[next]; #ifdef __APPLE__ // we don't really need a compare and swap, but this happens to call // the PowerPC memory barrier instruction lwsync. OSAtomicCompareAndSwap32Barrier(mReadHead, next, &mReadHead); #elif defined(_WIN32) InterlockedExchange(reinterpret_cast<volatile LONG*>(&mReadHead), next); #else mReadHead = next; #endif return out; } int Capacity() const { return N; } private: int NextPos(int inPos) { return (inPos + 1) & mMask; } long mMask; #ifdef __APPLE__ int32_t mReadHead, mWriteHead; #else volatile int mReadHead, mWriteHead; #endif T mItems[N]; };
2,609
C++
.h
72
31.319444
81
0.689259
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,094
PyrDeepFreezer.h
supercollider_supercollider/lang/LangPrimSource/PyrDeepFreezer.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* An object archiving system for SuperCollider. */ #pragma once #include <stdexcept> #include <cstring> #include "PyrObject.h" #include "SC_AllocPool.h" #include "InitAlloc.h" #include "PyrKernel.h" #include "PyrPrimitive.h" #include "VMGlobals.h" #include "GC.h" const int32 kDeepFreezerObjectArrayInitialCapacity = 32; class PyrDeepFreezer { public: PyrDeepFreezer(VMGlobals* inG): g(inG), objectArray(initialObjectArray), numObjects(0), objectArrayCapacity(kDeepFreezerObjectArrayInitialCapacity) {} ~PyrDeepFreezer() { if (objectArrayCapacity > kDeepFreezerObjectArrayInitialCapacity) g->allocPool->Free(objectArray); } long doDeepFreeze(PyrSlot* objectSlot) { long err = errNone; try { if (IsObj(objectSlot)) { constructObjectArray(slotRawObject(objectSlot)); for (int i = 0; i < numObjects; ++i) { g->gc->BecomePermanent(objectArray[i]); objectArray[i]->ClearMark(); } } } catch (std::exception& ex) { error(ex.what()); err = errFailed; for (int i = 0; i < numObjects; ++i) objectArray[i]->ClearMark(); } return err; } private: void recurse(PyrObject* obj, int n) { PyrSlot* slot = obj->slots; for (int i = 0; i < n; ++i, ++slot) if (IsObj(slot)) constructObjectArray(slotRawObject(slot)); } void growObjectArray() { int32 newObjectArrayCapacity = objectArrayCapacity << 1; int32 newSize = newObjectArrayCapacity * sizeof(PyrObject*); PyrObject** newArray = (PyrObject**)g->allocPool->Alloc(newSize); MEMFAIL(newArray); memcpy(newArray, objectArray, numObjects * sizeof(PyrObject*)); if (objectArrayCapacity > kDeepFreezerObjectArrayInitialCapacity) g->allocPool->Free(objectArray); objectArrayCapacity = newObjectArrayCapacity; objectArray = newArray; } void putObject(PyrObject* obj) { obj->SetMark(); // expand array if needed if (numObjects >= objectArrayCapacity) growObjectArray(); // add to array objectArray[numObjects++] = obj; } void constructObjectArray(PyrObject* obj) { if (obj->IsPermanent()) return; if (!obj->IsMarked()) { if (isKindOf(obj, class_process)) { throw std::runtime_error("cannot freeze Process.\n"); } else if (isKindOf(obj, s_interpreter->u.classobj)) { throw std::runtime_error("cannot freeze Interpreter.\n"); } else if (isKindOf(obj, class_rawarray)) { putObject(obj); } else if (isKindOf(obj, class_array)) { putObject(obj); recurse(obj, obj->size); } else if (isKindOf(obj, class_func)) { if (NotNil(&slotRawBlock(&((PyrClosure*)obj)->block)->contextDef)) { throw std::runtime_error("open Function can not be frozen.\n"); } putObject(obj); recurse(obj, obj->size); } else if (isKindOf(obj, class_method)) { throw std::runtime_error("cannot freeze Methods.\n"); } else if (isKindOf(obj, class_thread)) { throw std::runtime_error("cannot freeze Threads.\n"); } else if (isKindOf(obj, class_frame)) { throw std::runtime_error("cannot freeze Frames.\n"); } else { putObject(obj); recurse(obj, obj->size); } } } VMGlobals* g; PyrObject** objectArray; int32 numObjects; int32 objectArrayCapacity; PyrObject* initialObjectArray[kDeepFreezerObjectArrayInitialCapacity]; };
4,802
C++
.h
122
30.319672
84
0.617615
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,095
PyrArchiverT.h
supercollider_supercollider/lang/LangPrimSource/PyrArchiverT.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* An object archiving system for SuperCollider. */ #pragma once #include "PyrObject.h" #include "SC_AllocPool.h" #include "InitAlloc.h" #include "PyrKernel.h" #include "PyrPrimitive.h" #include "PyrSymbol.h" #include "VMGlobals.h" #include "GC.h" #include "ReadWriteMacros.h" #include "SCBase.h" const int32 kArchHdrSize = 12; const int32 kObjectArrayInitialCapacity = 32; template <class S> class PyrArchiver { public: PyrArchiver(VMGlobals* inG): g(inG), mObjectArray(mInitialObjectArray), mNumObjects(0), mObjectArrayCapacity(kObjectArrayInitialCapacity), mReadArchiveVersion(0) {} ~PyrArchiver() { if (mObjectArray != mInitialObjectArray) { g->allocPool->Free(mObjectArray); } } void setStream(S s) { mStream.SetStream(s); } int32 calcArchiveSize() { PyrSlot* slot; int32 size = kArchHdrSize; if (mNumObjects == 0) { size += sizeOfElem(&mTopSlot) + 1; } else { // object table size for (int i = 0; i < mNumObjects; ++i) { PyrObject* obj = mObjectArray[i]; size += slotRawSymbol(&obj->classptr->name)->length + 1; // class name symbol size += sizeof(int32); // size if (obj->obj_format <= obj_slot) { size += obj->size; // tags slot = obj->slots; for (int j = 0; j < obj->size; ++j, ++slot) { size += sizeOfElem(slot); } } else if (obj->obj_format == obj_symbol) { PyrSymbol** symbol = ((PyrSymbolArray*)obj)->symbols; for (int j = 0; j < obj->size; ++j, ++symbol) { size += (**symbol).length + 1; } } else { size += obj->size * gFormatElemSize[obj->obj_format]; } } } return size; } long prepareToWriteArchive(PyrSlot* objectSlot) { long err = errNone; try { slotCopy(&mTopSlot, objectSlot); if (IsObj(objectSlot)) constructObjectArray(slotRawObject(objectSlot)); } catch (std::exception& ex) { error(ex.what()); err = errFailed; } return err; } long writeArchive() { long err = errNone; try { writeArchiveHeader(); if (mNumObjects == 0) { writeSlot(&mTopSlot); } else { for (int i = 0; i < mNumObjects; ++i) { writeObjectHeader(mObjectArray[i]); } for (int i = 0; i < mNumObjects; ++i) { writeSlots(mObjectArray[i]); } } } catch (std::exception& ex) { error(ex.what()); err = errFailed; } return err; } long readArchive(PyrSlot* objectSlot) { // postfl("->readArchive\n"); long err = errNone; SetNil(objectSlot); try { readArchiveHeader(); // postfl("readObjectHeaders %d\n", mNumObjects); if (mNumObjects == 0) { readSlot(objectSlot); } else { for (int i = 0; i < mNumObjects; ++i) { mObjectArray[i] = readObjectHeader(); } // postfl("readSlots\n"); for (int i = 0; i < mNumObjects; ++i) { readSlots(mObjectArray[i]); } // postfl("done reading\n"); // postfl("SetObject\n"); SetObject(objectSlot, mObjectArray[0]); } } catch (std::exception& ex) { error(ex.what()); err = errFailed; } catch (...) { err = errFailed; } // postfl("<-readArchive\n"); return err; } private: void writeArchiveHeader() { mStream.writeInt32_be(('!' << 24) | ('S' << 16) | ('C' << 8) | 'a' /*'!SCa'*/); mStream.writeInt32_be(2); // file version mStream.writeInt32_be(mNumObjects); } void readArchiveHeader() { int32 magicNumber = mStream.readInt32_be(); if (magicNumber != (('!' << 24) | ('S' << 16) | ('C' << 8) | 'a' /*'!SCa'*/)) { throw std::runtime_error("not an SC archive.\n"); } mReadArchiveVersion = mStream.readInt32_be(); // file version mNumObjects = mStream.readInt32_be(); // post("readArchiveHeader %d %d\n", mReadArchiveVersion, mNumObjects); if (mNumObjects > kObjectArrayInitialCapacity) { mObjectArray = (PyrObject**)g->allocPool->Alloc(mNumObjects * sizeof(PyrObject*)); mObjectArrayCapacity = mNumObjects; } } void recurse(PyrObject* obj, int n) { PyrSlot* slot = obj->slots; for (int i = 0; i < n; ++i, ++slot) { if (IsObj(slot)) constructObjectArray(slotRawObject(slot)); } } void growObjectArray() { int32 newObjectArrayCapacity = mObjectArrayCapacity << 1; int32 newSize = newObjectArrayCapacity * sizeof(PyrObject*); PyrObject** newArray = (PyrObject**)g->allocPool->Alloc(newSize); MEMFAIL(newArray); memcpy(newArray, mObjectArray, mNumObjects * sizeof(PyrObject*)); if (mObjectArray != mInitialObjectArray) { g->allocPool->Free(mObjectArray); } mObjectArrayCapacity = newObjectArrayCapacity; mObjectArray = newArray; } void putObject(PyrObject* obj) { obj->SetMark(); obj->scratch1 = mNumObjects; // expand array if needed if (mNumObjects >= mObjectArrayCapacity) growObjectArray(); // add to array mObjectArray[mNumObjects++] = obj; } void constructObjectArray(PyrObject* obj) { if (!obj->IsMarked()) { if (isKindOf(obj, class_class)) { } else if (isKindOf(obj, class_process)) { } else if (isKindOf(obj, s_interpreter->u.classobj)) { } else if (isKindOf(obj, class_method)) { throw std::runtime_error("cannot archive Methods.\n"); } else if (isKindOf(obj, class_thread)) { throw std::runtime_error("cannot archive Threads.\n"); } else if (isKindOf(obj, class_frame)) { throw std::runtime_error("cannot archive Frames.\n"); } else if (isKindOf(obj, class_func)) { // if (NotNil(&((PyrClosure*)obj)->block.uoblk->context)) { // throw std::runtime_error("open Function can not be archived.\n"); //} putObject(obj); recurse(obj, obj->size); } else { if (isKindOf(obj, class_rawarray)) { putObject(obj); } else if (isKindOf(obj, class_array)) { putObject(obj); recurse(obj, obj->size); } else { putObject(obj); recurse(obj, obj->size); } } } } int32 sizeOfElem(PyrSlot* slot) { // postfl("writeSlot %08X\n", GetTag(slot)); switch (GetTag(slot)) { case tagObj: if (isKindOf(slotRawObject(slot), class_class)) { return slotRawSymbol(&slotRawClass(slot)->name)->length + 1; } else if (isKindOf(slotRawObject(slot), class_process)) { return 0; } else if (isKindOf(slotRawObject(slot), class_frame)) { return 0; } else if (isKindOf(slotRawObject(slot), s_interpreter->u.classobj)) { return 0; } else { return sizeof(int32); } break; case tagInt: return sizeof(int32); case tagSym: return slotRawSymbol(slot)->length + 1; case tagChar: return sizeof(int32); case tagNil: return 0; case tagFalse: return 0; case tagTrue: return 0; case tagPtr: throw std::runtime_error("cannot archive RawPointers."); return 0; default: return sizeof(double); } } PyrSymbol* readSymbolID() { char str[256]; mStream.readSymbol(str); return getsym(str); } PyrObject* readObjectID() { int32 objID = mStream.readInt32_be(); // postfl("readObjectID %d\n", objID); return mObjectArray[objID]; } void writeObjectHeader(PyrObject* obj) { obj->ClearMark(); // postfl("writeObjectHeader %s\n", slotRawSymbol(&obj->classptr->name)->name); mStream.writeSymbol(slotRawSymbol(&obj->classptr->name)->name); mStream.writeInt32_be(obj->size); } PyrObject* readObjectHeader() { PyrSymbol* classname = readSymbolID(); // post("readObjectHeader %s\n", classname->name); PyrObject* obj; int32 size = mStream.readInt32_be(); if (slotRawInt(&classname->u.classobj->classFlags) & classHasIndexableInstances) { obj = instantiateObject(g->gc, classname->u.classobj, size, false, false); obj->size = size; } else { obj = instantiateObject(g->gc, classname->u.classobj, 0, false, false); } return obj; } void writeSlots(PyrObject* obj) { // postfl(" writeSlots %s\n", slotRawSymbol(&obj->classptr->name)->name); if (isKindOf(obj, class_rawarray)) { writeRawArray(obj); } else if (isKindOf(obj, class_func)) { PyrClosure* closure = (PyrClosure*)obj; if (NotNil(&slotRawBlock(&closure->block)->contextDef)) { writeSlot(&closure->block); writeSlot(&closure->context); } else { writeSlot(&closure->block); writeSlot(&o_nil); } } else { for (int i = 0; i < obj->size; ++i) { writeSlot(obj->slots + i); } } } void readSlots(PyrObject* obj) { // postfl("readSlots\n"); if (isKindOf(obj, class_rawarray)) { readRawArray(obj); } else if (isKindOf(obj, class_func)) { PyrClosure* closure = (PyrClosure*)obj; readSlot(&closure->block); readSlot(&closure->context); if (IsNil(&closure->context)) { slotCopy(&closure->context, &slotRawInterpreter(&g->process->interpreter)->context); } } else { for (int i = 0; i < obj->size; ++i) { readSlot(obj->slots + i); } } } void writeSlot(PyrSlot* slot) { PyrObject* obj; // postfl(" writeSlot %08X\n", GetTag(slot)); switch (GetTag(slot)) { case tagObj: obj = slotRawObject(slot); if (isKindOf(obj, class_class)) { mStream.writeInt8('C'); mStream.writeSymbol(slotRawSymbol(&slotRawClass(slot)->name)->name); } else if (isKindOf(obj, class_process)) { mStream.writeInt8('P'); } else if (isKindOf(obj, s_interpreter->u.classobj)) { mStream.writeInt8('R'); } else { mStream.writeInt8('o'); mStream.writeInt32_be(obj->scratch1); } break; case tagInt: mStream.writeInt8('i'); mStream.writeInt32_be(slotRawInt(slot)); break; case tagSym: mStream.writeInt8('s'); mStream.writeSymbol(slotRawSymbol(slot)->name); break; case tagChar: mStream.writeInt8('c'); mStream.writeInt32_be(slotRawInt(slot)); break; case tagNil: mStream.writeInt8('N'); break; case tagFalse: mStream.writeInt8('F'); break; case tagTrue: mStream.writeInt8('T'); break; case tagPtr: mStream.writeInt8('N'); break; default: mStream.writeInt8('f'); mStream.writeDouble_be(slotRawFloat(slot)); break; } } void readSlot(PyrSlot* slot) { char tag = mStream.readInt8(); switch (tag) { case 'o': SetObject(slot, readObjectID()); break; case 'z': SetObject(slot, (PyrObject*)(size_t)mStream.readInt32_be()); // FIXME: fix 64bit safety break; case 'C': SetObject(slot, (PyrObject*)readSymbolID()->u.classobj); break; case 'P': SetObject(slot, (PyrObject*)g->process); break; case 'R': SetObject(slot, slotRawObject(&g->process->interpreter)); break; case 'i': SetInt(slot, mStream.readInt32_be()); break; case 's': SetSymbol(slot, readSymbolID()); break; case 'c': SetChar(slot, mStream.readInt32_be()); break; case 'f': SetFloat(slot, mStream.readDouble_be()); break; case 'T': SetTrue(slot); break; case 'F': SetFalse(slot); break; case 'N': default: SetNil(slot); break; } } void writeRawArray(PyrObject* obj) { int32 size = obj->size; // postfl("writeRawArray %d\n", size); switch (obj->obj_format) { case obj_char: case obj_int8: { char* data = (char*)obj->slots; mStream.writeData(data, size); } break; case obj_int16: { int16* data = (int16*)obj->slots; for (int i = 0; i < size; ++i) { mStream.writeInt16_be(data[i]); } } break; case obj_int32: case obj_float: { int32* data = (int32*)obj->slots; for (int i = 0; i < size; ++i) { mStream.writeInt32_be(data[i]); } } break; case obj_double: { double* data = (double*)obj->slots; for (int i = 0; i < size; ++i) { mStream.writeDouble_be(data[i]); } } break; case obj_symbol: { PyrSymbol** data = (PyrSymbol**)obj->slots; for (int i = 0; i < size; ++i) { mStream.writeSymbol(data[i]->name); } } break; } } void readRawArray(PyrObject* obj) { // postfl("readRawArray\n"); int32 size = obj->size; switch (obj->obj_format) { case obj_char: case obj_int8: { int8* data = (int8*)obj->slots; for (int i = 0; i < size; ++i) { data[i] = mStream.readInt8(); } } break; case obj_int16: { int16* data = (int16*)obj->slots; for (int i = 0; i < size; ++i) { data[i] = mStream.readInt16_be(); } } break; case obj_int32: case obj_float: { int32* data = (int32*)obj->slots; for (int i = 0; i < size; ++i) { data[i] = mStream.readInt32_be(); } } break; case obj_double: { double* data = (double*)obj->slots; for (int i = 0; i < size; ++i) { data[i] = mStream.readDouble_be(); } } break; case obj_symbol: { PyrSymbol** data = (PyrSymbol**)obj->slots; for (int i = 0; i < size; ++i) { data[i] = readSymbolID(); } } break; } } VMGlobals* g; PyrObject** mObjectArray; int32 mNumObjects; int32 mObjectArrayCapacity; PyrSlot mTopSlot; SC_IOStream<S> mStream; int32 mReadArchiveVersion; PyrObject* mInitialObjectArray[kObjectArrayInitialCapacity]; };
17,156
C++
.h
485
24.435052
100
0.519044
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,096
PyrSignalPrim.h
supercollider_supercollider/lang/LangPrimSource/PyrSignalPrim.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once extern PyrSymbol* s_wavetable; extern struct PyrClass* class_wavetable; void initSignalPrimitives(); int prSignalCat(VMGlobals* g, int numArgsPushed); int prSignalFill(VMGlobals* g, int numArgsPushed); int prSignalRamp(VMGlobals* g, int numArgsPushed); int prSignalScale(VMGlobals* g, int numArgsPushed); int prSignalOffset(VMGlobals* g, int numArgsPushed); int prSignalString(VMGlobals* g, int numArgsPushed); int prSignalPeak(VMGlobals* g, int numArgsPushed); int prSignalNormalize(VMGlobals* g, int numArgsPushed); int prSignalNormalizeTransferFn(VMGlobals* g, int numArgsPushed); int prSignalIntegral(VMGlobals* g, int numArgsPushed); int prSignalOverDub(VMGlobals* g, int numArgsPushed); int prSignalOverWrite(VMGlobals* g, int numArgsPushed); int prSignalFade(VMGlobals* g, int numArgsPushed); int prSignalAddHarmonic(VMGlobals* g, int numArgsPushed); int prSignalAsWavetable(VMGlobals* g, int numArgsPushed); int prWavetableAsSignal(VMGlobals* g, int numArgsPushed); int prSignalInvert(VMGlobals* g, int numArgsPushed); int prSignalReverse(VMGlobals* g, int numArgsPushed); int prSignalRotate(VMGlobals* g, int numArgsPushed); void signalAsWavetable(float* signal, float* wavetable, int size); void wavetableAsSignal(float* wavetable, float* signal, int size);
2,163
C++
.h
41
50.097561
81
0.801422
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,097
SC_LinkClock.hpp
supercollider_supercollider/lang/LangPrimSource/SC_LinkClock.hpp
#pragma once #ifdef SC_ABLETON_LINK # include "PyrKernel.h" # include "PyrSched.h" # include "GC.h" # include "PyrPrimitive.h" # include "PyrSymbol.h" # include "SCBase.h" # include "SC_Clock.hpp" # include <ableton/Link.hpp> /** TempoClock for use with Ableton Link. * * Represented in sclang as class LinkClock. */ class LinkClock : public TempoClock { public: /// Called during PyrSched init. static void Init(); static std::chrono::microseconds GetInitTime() { return LinkClock::InitTime; } private: static std::chrono::microseconds InitTime; public: LinkClock(VMGlobals* vmGlobals, PyrObject* tempoClockObj, double tempo, double baseBeats, double baseSeconds); ~LinkClock() noexcept = default; void SetTempoAtBeat(double tempo, double inBeats); void SetTempoAtTime(double tempo, double inSeconds); void SetAll(double tempo, double inBeats, double inSeconds); double BeatsToSecs(double beats) const override; double SecsToBeats(double secs) const override; double GetQuantum() const { return mQuantum; } void SetQuantum(double quantum) { mQuantum = quantum; mCondition.notify_one(); } double GetLatency() const { return mLatency; } void SetLatency(double latency) { mLatency = latency; } void OnTempoChanged(double bpm); void OnStartStop(bool isPlaying) { gLangMutex.lock(); g->canCallOS = false; ++g->sp; SetObject(g->sp, mTempoClockObj); ++g->sp; SetBool(g->sp, isPlaying); runInterpreter(g, getsym("prStartStopSync"), 2); g->canCallOS = false; gLangMutex.unlock(); } void OnNumPeersChanged(std::size_t numPeers) { gLangMutex.lock(); g->canCallOS = false; ++g->sp; SetObject(g->sp, mTempoClockObj); ++g->sp; SetInt(g->sp, numPeers); runInterpreter(g, getsym("prNumPeersChanged"), 2); g->canCallOS = false; gLangMutex.unlock(); } std::size_t NumPeers() const { return mLink.numPeers(); } private: void CommitTempo(ableton::Link::SessionState sessionState, double tempo) { mTempo = tempo; mBeatDur = 1. / tempo; mLink.commitAppSessionState(sessionState); mCondition.notify_one(); } ableton::Link mLink; double mQuantum; double mLatency; }; #endif // SC_ABLETON_LINK
2,416
C++
.h
72
28.083333
114
0.668387
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,098
PyrMathPrim.h
supercollider_supercollider/lang/LangPrimSource/PyrMathPrim.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once void initMathPrimitives(); int prAddNum(VMGlobals* g, int numArgsPushed); int prSubNum(VMGlobals* g, int numArgsPushed); int prMulNum(VMGlobals* g, int numArgsPushed); int prAddInt(VMGlobals* g, int numArgsPushed); int prSubInt(VMGlobals* g, int numArgsPushed); int prMulInt(VMGlobals* g, int numArgsPushed); int prAddFloat(VMGlobals* g, int numArgsPushed); int prSubFloat(VMGlobals* g, int numArgsPushed); int prMulFloat(VMGlobals* g, int numArgsPushed); int mathClip(VMGlobals* g, int numArgsPushed); int mathWrap(VMGlobals* g, int numArgsPushed); int mathFold(VMGlobals* g, int numArgsPushed); int mathClipInt(VMGlobals* g, int numArgsPushed); int mathWrapInt(VMGlobals* g, int numArgsPushed); int mathFoldInt(VMGlobals* g, int numArgsPushed); int mathClipFloat(VMGlobals* g, int numArgsPushed); int mathWrapFloat(VMGlobals* g, int numArgsPushed); int mathFoldFloat(VMGlobals* g, int numArgsPushed); int mathClipSignal(VMGlobals* g, int numArgsPushed); int mathWrapSignal(VMGlobals* g, int numArgsPushed); int mathFoldSignal(VMGlobals* g, int numArgsPushed);
1,954
C++
.h
39
47.435897
81
0.790136
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,099
SC_ComPort.h
supercollider_supercollider/lang/LangPrimSource/SC_ComPort.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "SC_ReplyImpl.hpp" #include "SC_Types.h" #include <boost/array.hpp> #include <boost/asio.hpp> #include <boost/enable_shared_from_this.hpp> #include <boost/core/noncopyable.hpp> ////////////////////////////////////////////////////////////////////////////////////////////////////////// const int kTextBufSize = 65536; enum class HandlerType { OSC, Raw }; using HandleDataFunc = std::function<void(std::unique_ptr<char[]>, size_t)>; ////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace Detail { class TCPConnection : public std::enable_shared_from_this<TCPConnection>, private boost::noncopyable { public: using pointer = std::shared_ptr<TCPConnection>; TCPConnection(boost::asio::io_service& ioService, int portNum, HandlerType); void start(); auto& getSocket() { return mSocket; } private: void handleLengthReceived(const boost::system::error_code& error, size_t bytes_transferred); void handleMsgReceived(const boost::system::error_code& error, size_t bytes_transferred); void initHandler(HandlerType); HandleDataFunc mHandleFunc; boost::asio::ip::tcp::socket mSocket; int32 mOSCMsgLength; std::unique_ptr<char[]> mData; const int mPortNum; }; } ////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace InPort { class UDP : private boost::noncopyable { public: UDP(int inPortNum, HandlerType, int portsToCheck = 10); ~UDP() = default; auto RealPortNum() const { return mPortNum; } auto& getSocket() { return mUdpSocket; } private: void initHandler(HandlerType type); void handleReceivedUDP(const boost::system::error_code& error, std::size_t bytes_transferred); void startReceiveUDP(); int mPortNum; HandleDataFunc mHandleFunc; std::array<char, kTextBufSize> mRecvBuffer; boost::asio::ip::udp::endpoint mRemoteEndpoint; boost::asio::ip::udp::socket mUdpSocket; }; class UDPCustom : public UDP { public: UDPCustom(int inPortNum, HandlerType); ~UDPCustom() = default; }; class TCP : private boost::noncopyable { public: TCP(int inPortNum, int inMaxConnections, int inBacklog, HandlerType); private: void startAccept(); void handleAccept(Detail::TCPConnection::pointer new_connection, const boost::system::error_code& error); HandleDataFunc mHandleFunc; const HandlerType mHandlerType; const int mPortNum; boost::asio::ip::tcp::acceptor mAcceptor; }; } // namespace InPort ////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace OutPort { class TCP : private boost::noncopyable { public: typedef void (*ClientNotifyFunc)(void* clientData); public: TCP(unsigned long inAddress, int inPort, HandlerType, ClientNotifyFunc notifyFunc = 0, void* clientData = 0); int Close(); boost::asio::ip::tcp::socket& Socket() { return mSocket; } private: void startReceive(); void handleLengthReceived(const boost::system::error_code& error, size_t bytes_transferred); void handleMsgReceived(const boost::system::error_code& error, size_t bytes_transferred); void initHandler(HandlerType); HandleDataFunc mHandleFunc; int32 mOSCMsgLength; std::unique_ptr<char[]> mData; boost::asio::ip::tcp::socket mSocket; boost::asio::ip::tcp::endpoint mEndpoint; ClientNotifyFunc mClientNotifyFunc; void* mClientData; }; } // namespace OutPort
4,418
C++
.h
104
38.740385
113
0.671966
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,100
PyrDeepCopier.h
supercollider_supercollider/lang/LangPrimSource/PyrDeepCopier.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* An object archiving system for SuperCollider. */ #pragma once #include "PyrObject.h" #include "SC_AllocPool.h" #include "InitAlloc.h" #include "PyrKernel.h" #include "PyrPrimitive.h" #include "VMGlobals.h" #include "GC.h" const int32 kDeepCopierObjectArrayInitialCapacity = 32; class PyrDeepCopier { public: PyrDeepCopier(VMGlobals* inG): g(inG), objectArray(initialObjectArray), numObjects(0), objectArrayCapacity(kDeepCopierObjectArrayInitialCapacity) {} ~PyrDeepCopier() { if (objectArrayCapacity > kDeepCopierObjectArrayInitialCapacity) { g->allocPool->Free(objectArray); } } long doDeepCopy(PyrSlot* objectSlot) { long err = errNone; try { if (IsObj(objectSlot)) { constructObjectArray(slotRawObject(objectSlot)); for (int i = 0; i < numObjects; ++i) { fixSlots(objectArray[i]); } fixObjSlot(objectSlot); for (int i = 0; i < numObjects; ++i) { objectArray[i]->ClearMark(); } } } catch (std::exception& ex) { error(ex.what()); err = errFailed; } return err; } private: void recurse(PyrObject* obj, size_t n) { // post("->recurse %s %08X\n", obj->classptr->name.us->name, obj); PyrSlot* slot = obj->slots; for (size_t i = 0; i < n; ++i, ++slot) { if (IsObj(slot)) constructObjectArray(slotRawObject(slot)); } // post("<-recurse %s %08X\n", obj->classptr->name.us->name, obj); } void growObjectArray() { int32 newObjectArrayCapacity = objectArrayCapacity << 1; int32 newSize = newObjectArrayCapacity * sizeof(PyrObject*); PyrObject** newArray = (PyrObject**)g->allocPool->Alloc(newSize); MEMFAIL(newArray); memcpy(newArray, objectArray, numObjects * sizeof(PyrObject*)); if (objectArrayCapacity > kDeepCopierObjectArrayInitialCapacity) { g->allocPool->Free(objectArray); } objectArrayCapacity = newObjectArrayCapacity; objectArray = newArray; } void putSelf(PyrObject* obj) { obj->SetMark(); obj->scratch1 = numObjects; // expand array if needed if (numObjects >= objectArrayCapacity) growObjectArray(); // post("putSelf %d %08X\n", numObjects, obj); // add to array objectArray[numObjects++] = obj; } void putCopy(PyrObject* obj) { obj->SetMark(); obj->scratch1 = numObjects; // expand array if needed if (numObjects + 2 >= objectArrayCapacity) growObjectArray(); // add a shallow copy to object array PyrObject* copy = copyObject(g->gc, obj, false); copy->ClearMark(); // post("putCopy %d %08X\n", numObjects, copy); // add to array objectArray[numObjects++] = copy; objectArray[numObjects++] = obj; } void constructObjectArray(PyrObject* obj) { // post("->constructObjectArray %s %08X\n", obj->classptr->name.us->name, obj); if (!obj->IsMarked()) { if (obj->obj_flags & (obj_immutable) && obj->obj_flags & (obj_permanent)) { putSelf(obj); } else if (isKindOf(obj, class_class)) { putSelf(obj); } else if (isKindOf(obj, class_process)) { putSelf(obj); } else if (isKindOf(obj, s_interpreter->u.classobj)) { putSelf(obj); } else if (isKindOf(obj, class_rawarray)) { putCopy(obj); } else if (isKindOf(obj, class_array)) { putCopy(obj); recurse(obj, obj->size); } else if (isKindOf(obj, class_func)) { putSelf(obj); } else if (isKindOf(obj, class_method)) { putSelf(obj); } else if (isKindOf(obj, class_thread)) { putSelf(obj); } else if (isKindOf(obj, class_server_shm_interface)) { putSelf(obj); } else { putCopy(obj); recurse(obj, obj->size); } } // post("<-constructObjectArray %s %08X\n", obj->classptr->name.us->name, obj); } void fixObjSlot(PyrSlot* slot) { // post("fixObjSlot %s %08X %d %08X\n", slotRawObject(slot)->classptr->name.us->name, slotRawObject(slot), // slot->uo->scratch1, objectArray[slot->uo->scratch1]); SetRaw(slot, objectArray[slotRawObject(slot)->scratch1]); } void fixSlots(PyrObject* obj) { // post("fixSlots %s %08X %d\n", obj->classptr->name.us->name, obj, obj->IsMarked()); if (!obj->IsMarked() && obj->obj_format <= obj_slot) { // it is a copy PyrSlot* slot = obj->slots; for (int i = 0; i < obj->size; ++i, ++slot) { if (IsObj(slot)) fixObjSlot(slot); } } } VMGlobals* g; PyrObject** objectArray; int32 numObjects; int32 objectArrayCapacity; PyrObject* initialObjectArray[kDeepCopierObjectArrayInitialCapacity]; };
6,159
C++
.h
157
30.006369
114
0.591358
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,101
PyrFilePrim.h
supercollider_supercollider/lang/LangPrimSource/PyrFilePrim.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "PyrObject.h" struct PyrFile : public PyrObjectHdr { PyrSlot fileptr; }; void initFilePrimitives(); long prFileDelete(VMGlobals* g, long numArgsPushed); long prFileDeleteAll(VMGlobals* g, long numArgsPushed); long prFileOpen(VMGlobals* g, long numArgsPushed); long prFileClose(VMGlobals* g, long numArgsPushed); long prFileSeek(VMGlobals* g, long numArgsPushed); long prFilePos(VMGlobals* g, long numArgsPushed); long prFileLength(VMGlobals* g, long numArgsPushed); long prFileWrite(VMGlobals* g, long numArgsPushed); long prFileReadLine(VMGlobals* g, long numArgsPushed); long prFilePutRGB(VMGlobals* g, long numArgsPushed); long prFilePutInt32(VMGlobals* g, long numArgsPushed); long prFilePutInt16(VMGlobals* g, long numArgsPushed); long prFilePutInt8(VMGlobals* g, long numArgsPushed); long prFilePutChar(VMGlobals* g, long numArgsPushed); long prFilePutFloat(VMGlobals* g, long numArgsPushed); long prFilePutDouble(VMGlobals* g, long numArgsPushed); long prFileGetRGB(VMGlobals* g, long numArgsPushed); long prFileGetInt32(VMGlobals* g, long numArgsPushed); long prFileGetInt16(VMGlobals* g, long numArgsPushed); long prFileGetInt8(VMGlobals* g, long numArgsPushed); long prFileGetChar(VMGlobals* g, long numArgsPushed); long prFileGetFloat(VMGlobals* g, long numArgsPushed); long prFileGetDouble(VMGlobals* g, long numArgsPushed); long prFilePutString(VMGlobals* g, long numArgsPushed); long prFileRead(VMGlobals* g, long numArgsPushed);
2,350
C++
.h
47
47.510638
81
0.801134
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,102
SC_Msg.h
supercollider_supercollider/lang/LangPrimSource/SC_Msg.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include <stdio.h> #include <stdlib.h> #include "SC_ReplyImpl.hpp" #include "sc_msg_iter.h" class SC_Msg; enum { // Handler IDs kUnknownAction = 0, kRealTimeAction = 1, kNonRealTimeAction = 2, kEitherTimeAction = 3 }; int32 Hash(ReplyAddress* inReplyAddress); struct OSC_Packet { std::unique_ptr<char[]> mData; size_t mSize; ReplyAddress mReplyAddr; };
1,275
C++
.h
34
33.705882
81
0.747154
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,104
XenomaiLock.h
supercollider_supercollider/common/XenomaiLock.h
#pragma once #include <mutex> //unique_lock // Xenomai enforces the requirement to hold the lock so that optimizing // the wake up process is possible - under the assumption that the caller // owns the lock. There is no hack around this. // See: https://www.xenomai.org/pipermail/xenomai/2017-October/037759.html #define SC_CONDITION_VARIABLE_ANY_SHOULD_LOCK_BEFORE_NOTIFY // to make sure Xenomai gets initialised on time, create one object of this // class before any XenomaiMutex or XenomaiConditionVariable constructors class XenomaiInitializer { public: XenomaiInitializer(); }; class XenomaiMutex { friend class XenomaiConditionVariable; public: XenomaiMutex(); ~XenomaiMutex(); bool try_lock(); void lock(); void unlock(); private: pthread_mutex_t m_mutex; bool m_enabled = false; }; class XenomaiConditionVariable { public: XenomaiConditionVariable(); ~XenomaiConditionVariable(); void wait(std::unique_lock<XenomaiMutex>& lck); void notify_one() noexcept; void notify_all() noexcept; private: pthread_cond_t m_cond; bool m_enabled = false; };
1,123
C++
.h
36
28.194444
75
0.755329
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,106
SC_PaUtils.hpp
supercollider_supercollider/common/SC_PaUtils.hpp
// helper functions for SuperCollider server's PortAudio backend #pragma once #include "portaudio.h" #include <string> // get device name from PaDeviceIndex or PaDeviceInfo std::string GetPaDeviceName(PaDeviceIndex index); std::string GetPaDeviceName(const PaDeviceInfo* pdi); // get PaDeviceIndex from device name PaDeviceIndex GetPaDeviceFromName(const char* device, bool isInput); // select default PA devices if they are not defined // it will also try to check for some configuration problems // numIns, numOuts and sampleRate are only the requested values, may change later // PaError will be reported if the devices don't support a requested or a common sample rate PaError TryGetDefaultPaDevices(PaDeviceIndex* inDevice, PaDeviceIndex* outDevice, int numIns, int numOuts, double sampleRate); // create PaStreamParameters with requested values PaStreamParameters MakePaStreamParameters(int device, int channelCount, double suggestedLatency);
986
C++
.h
17
54.823529
106
0.804777
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,107
scsynthsend.h
supercollider_supercollider/common/scsynthsend.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "SC_Endian.h" #include "SC_Types.h" #include <stdexcept> #include <cstring> #include <string> template <int MaxPacketSize = 8192> struct scpacket { static const int kBufSize = MaxPacketSize / sizeof(int32); // round down int32 *wrpos, *endpos, *msgsizepos; char* tagwrpos; int inbundle; int32 buf[kBufSize]; void throw_overflow_exception() { throw std::runtime_error(std::string("buffer overflow")); } scpacket() { reset(); } void reset() { wrpos = buf; endpos = buf + kBufSize; inbundle = 0; } void addi(int i) { if (wrpos >= endpos) throw_overflow_exception(); *wrpos++ = sc_htonl(i); } void addii(int64 ii) { int i; i = (int)(ii >> 32); addi(i); i = (int)ii; addi(i); } void addf(float f) { if (wrpos >= endpos) throw_overflow_exception(); elem32 slot; slot.f = f; *wrpos++ = sc_htonl(slot.i); } void addd(double f) { if (wrpos >= endpos) throw_overflow_exception(); elem64 slot; slot.f = f; *wrpos++ = sc_htonl(slot.i >> 32); *wrpos++ = sc_htonl(slot.i & 0x00000000FFFFFFFF); } void adds(const char* src) { size_t len = strlen(src); size_t len4 = (len + 4) >> 2; if (wrpos + len4 > endpos) throw_overflow_exception(); wrpos[len4 - 1] = 0; memcpy(wrpos, src, len); wrpos += len4; } void adds_slpre(const char* src) // prepends a slash { size_t len = strlen(src); size_t len4 = (len + 5) >> 2; if (wrpos + len4 > endpos) throw_overflow_exception(); wrpos[len4 - 1] = 0; char* wrpos_c = (char*)wrpos; *wrpos_c = '/'; memcpy(wrpos_c + 1, src, len); wrpos += len4; } void adds(const char* src, size_t len) { size_t len4 = (len + 4) >> 2; if (wrpos + len4 > endpos) throw_overflow_exception(); wrpos[len4 - 1] = 0; memcpy(wrpos, src, len); wrpos += len4; } void addb(uint8* src, size_t len) { size_t len4 = (len + 3) >> 2; if (wrpos + (len4 + 1) > endpos) throw_overflow_exception(); wrpos[len4 - 1] = 0; int32 swaplen = len; *wrpos++ = sc_htonl(swaplen); memcpy(wrpos, src, len); wrpos += len4; } void addtag(char c) { *tagwrpos++ = c; } void skip(int n) { if (wrpos + n > endpos) throw_overflow_exception(); wrpos += n; } void maketags(int n) { int size4 = (n + 4) >> 2; tagwrpos = (char*)wrpos; skip(size4); wrpos[-1] = 0; } size_t size() { return (char*)wrpos - (char*)buf; } char* data() { return (char*)buf; } void OpenBundle(int64 time) { inbundle++; adds("#bundle"); addii(time); } void CloseBundle() { if (inbundle) inbundle--; } void BeginMsg() { if (inbundle) { msgsizepos = wrpos; addi(0); } } void EndMsg() { if (inbundle) { *msgsizepos = sc_htonl(((wrpos - msgsizepos) - 1) * sizeof(int32)); } } }; typedef scpacket<> small_scpacket; typedef scpacket<65516> big_scpacket;
4,267
C++
.h
138
23.782609
97
0.566051
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,108
malloc_aligned.hpp
supercollider_supercollider/common/malloc_aligned.hpp
// functions for aligned memory allocation // Copyright (C) 2009 Tim Blechmann // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once #include <cstdlib> #include <cstring> #include <new> // for std::bad_alloc #include <utility> // for std::forward #include <boost/align/aligned_alloc.hpp> #include "function_attributes.h" namespace nova { const int malloc_memory_alignment = 64; inline void* MALLOC ASSUME_ALIGNED(64) malloc_aligned(std::size_t bytes) { return boost::alignment::aligned_alloc(malloc_memory_alignment, bytes); } inline void free_aligned(void* ptr) { return boost::alignment::aligned_free(ptr); } inline void* MALLOC ASSUME_ALIGNED(64) calloc_aligned(std::size_t bytes) { void* ret = malloc_aligned(bytes); if (ret) std::memset(ret, 0, bytes); return ret; } template <typename T> T* MALLOC ASSUME_ALIGNED(64) malloc_aligned(std::size_t n) { return static_cast<T*>(malloc_aligned(n * sizeof(T))); } template <typename T> T* MALLOC ASSUME_ALIGNED(64) calloc_aligned(std::size_t n) { return static_cast<T*>(calloc_aligned(n * sizeof(T))); } /** smart-pointer, freeing the managed pointer via free_aligned */ template <class T, bool managed = true> class aligned_storage_ptr { public: explicit aligned_storage_ptr(T* p = 0): ptr(p) {} explicit aligned_storage_ptr(size_t count): ptr(malloc_aligned<T>(count)) {} ~aligned_storage_ptr(void) { if (managed && ptr) free_aligned(ptr); } void reset(T* p = 0) { if (managed && ptr) free_aligned(ptr); ptr = p; } T& operator*() const { return *ptr; } T* operator->() const { return ptr; } T* get() const { return ptr; } aligned_storage_ptr& operator=(T* p) { reset(p); return *this; } operator bool() const { return bool(ptr); } void swap(aligned_storage_ptr& b) { T* p = ptr; ptr = b.ptr; b.ptr = p; } private: T* ptr; }; } /* namespace nova */
2,719
C++
.h
73
33.438356
83
0.681038
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,109
SC_TextUtils.hpp
supercollider_supercollider/common/SC_TextUtils.hpp
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com Copyright (c) 2012 Tim Blechmann. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once // strips out all the RichTextFile crap int rtf2txt(char* txt); int html2txt(char* txt);
1,036
C++
.h
21
45.238095
81
0.760396
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,110
Samp.hpp
supercollider_supercollider/common/Samp.hpp
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "SC_Types.h" const long kSineSize = 8192; const long kSineMask = kSineSize - 1; const double kSinePhaseScale = kSineSize / (2.0 * 3.1415926535897932384626433832795); extern float32 gSine[kSineSize + 1]; extern float32 gPMSine[kSineSize + 1]; extern float32 gInvSine[kSineSize + 1]; extern float32 gSineWavetable[2 * kSineSize]; void SignalAsWavetable(float32* signal, float32* wavetable, long inSize); void WavetableAsSignal(float32* wavetable, float32* signal, long inSize);
1,376
C++
.h
27
47.592593
85
0.774795
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,111
SC_List.h
supercollider_supercollider/common/SC_List.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* A doubly linked list template. */ #pragma once #include <stdexcept> #include <assert.h> // A Link can be a node in a list or a list itself. template <class T> class Link { public: Link(): mNext(this), mPrev(this) {} T* Prev() { return static_cast<T*>(mPrev); } T* Next() { return static_cast<T*>(mNext); } void RemoveLeaveDangling() { mPrev->mNext = mNext; mNext->mPrev = mPrev; } void Remove() { RemoveLeaveDangling(); mNext = mPrev = this; } void InsertAfter(T* inLink) { mPrev = inLink; mNext = inLink->mNext; mNext->mPrev = this; mPrev->mNext = this; } void InsertBefore(T* inLink) { mNext = inLink; mPrev = inLink->mPrev; mNext->mPrev = this; mPrev->mNext = this; } T* Head() { return static_cast<T*>(mNext); } T* Tail() { return static_cast<T*>(mPrev); } T* PopHead(); T* PopTail(); void PushHead(T* inBuf); void PushTail(T* inBuf); bool ContainsBuf(T* inBuf); bool IsEmpty() { return mNext == this; } void BeEmpty() { mNext = mPrev = this; } void Cat(T* inLink); bool SanityCheck(); void DebugDump(); // private: // Codewarrior refuses to inline Next() in some places.. Link<T>*mNext, *mPrev; }; template <class T, class Alloc> void MakeListEmpty(Link<T>* inLink, Alloc* inAlloc) { Link<T>* link = inLink->mNext; while (link != inLink) { Link<T>* nextlink = link->mNext; // SC uses placement new extensively, so here we do a 'placement delete'. // Using DestructSelf allows me to have either virtual // or non virtual destructors in subclasses at the discretion of the subclass. ((T*)(link))->DestructSelf(); inAlloc->Free(static_cast<T*>(link)); link = nextlink; } inLink->mNext = inLink->mPrev = inLink; } template <class T> void Link<T>::PushHead(T* inLink) { assert(SanityCheck()); Link<T>* link = static_cast<Link<T>*>(inLink); link->InsertAfter(static_cast<T*>(this)); assert(SanityCheck()); } template <class T> T* Link<T>::PopHead() { assert(SanityCheck()); if (IsEmpty()) return 0; Link<T>* link = mNext; link->Remove(); assert(SanityCheck()); return static_cast<T*>(link); } template <class T> void Link<T>::PushTail(T* inLink) { assert(SanityCheck()); Link<T>* link = static_cast<Link<T>*>(inLink); link->InsertBefore(static_cast<T*>(this)); assert(SanityCheck()); } template <class T> T* Link<T>::PopTail() { assert(SanityCheck()); if (IsEmpty()) return 0; Link<T>* link = mPrev; link->Remove(); assert(SanityCheck()); return static_cast<T*>(link); } template <class T> void Link<T>::Cat(T* inLink) { assert(SanityCheck()); Link<T>* link = static_cast<Link<T>*>(inLink); if (link->IsEmpty()) return; if (IsEmpty()) { mNext = link->mNext; mPrev = link->mPrev; link->mNext->mPrev = this; link->mPrev->mNext = this; } else { link->mNext->mPrev = mPrev; link->mPrev->mNext = this; mPrev->mNext = link->mNext; mPrev = link->mPrev; } link->mPrev = link; link->mNext = link; assert(SanityCheck()); } template <class T> bool Link<T>::ContainsBuf(T* inLink) { Link<T>* link = static_cast<Link<T>*>(inLink); Link<T>* curLink = mNext; while (curLink != this) { if (curLink == link) return true; curLink = curLink->mNext; } return false; } template <class T> void Link<T>::DebugDump() { Link<T>* link = mNext; while (link != this) { // post("Link-> %08X next %08X prev %08X\n", // link, link->mNext, link->mPrev); link = link->mNext; } } template <class T> bool Link<T>::SanityCheck() { Link<T>* link = mNext; while (link != this) { if (link->mPrev->mNext != link) { throw std::runtime_error("Link: bad link <-,->"); } if (link->mNext->mPrev != link) { throw std::runtime_error("Link: bad link ->,<-"); } link = link->mNext; } return true; }
5,109
C++
.h
158
26.658228
86
0.614507
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,112
SC_Codecvt.hpp
supercollider_supercollider/common/SC_Codecvt.hpp
/** * \file SC_Codecvt.hpp * * \brief Codepage conversion utilities. * * This header provides convenience functions to convert strings and paths between UTF-8 and the OS's * filesystem API encoding. On POSIX systems, this does nothing. On Windows, this converts between * UTF-8 and UTF-16. On Windows, additional functions are provided to convert between UTF-8 std::string * and UTF-16 std::wstring. * * $Author: Brian Heim $ * * \version 1.1 * * $Date: 2017-05-14 $ * * $Contact: brianlheim@gmail.com $ * * Created on: 2017-05-14 */ /* * Copyright (C) Brian Heim, 2017. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA */ #pragma once #include <string> // string #include <filesystem> #ifdef _WIN32 # include <codecvt> // std::codecvt_utf8_utf16, utf16 # include <locale> // std::wstring_convert #endif /** \namespace SC_Codecvt * \brief Namespace for codepage conversion functions. */ namespace SC_Codecvt { // Windows helper functions. Only defined on Windows to avoid having // to unnecessarily include <codecvt> and <locale> #ifdef _WIN32 /** \brief Converts a UTF-8 char str to UTF-16 std::wstring * * This function is only defined on Windows, to avoid unnecessary header includes. */ inline std::wstring utf8_cstr_to_utf16_wstring(const char* s) { return std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>>().from_bytes(s); } /** \brief Converts a UTF-16 wchar_t str to UTF-8 std::string * * This function is only defined on Windows, to avoid unnecessary header includes. */ inline std::string utf16_wcstr_to_utf8_string(const wchar_t* s) { return std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>>().to_bytes(s); } #endif // _WIN32 /** \brief Converts a path to a UTF-8 encoded string. * * On POSIX platforms, this just converts using .string(). On Windows, uses * conversion between UTF-16 and UTF-8. */ inline std::string path_to_utf8_str(const std::filesystem::path& p) { #ifdef _WIN32 return std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>>().to_bytes(p.native()); #else return p.string(); #endif // _WIN32 } /** \brief Converts a UTF-8 encoded string to a path. * * On POSIX platforms, this converts using the default constructor. On Windows, * uses conversion between UTF-16 and UTF-8. */ inline std::filesystem::path utf8_str_to_path(const std::string& s) { #ifdef _WIN32 std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter; std::wstring wideString = converter.from_bytes(s); return std::filesystem::path(std::move(wideString)); #else return std::filesystem::path(s); #endif // _WIN32 } /** \brief Converts a native filesystem-encoded string to a UTF-8 string. * * On Windows, converts between UTF-16 and UTF-8. On POSIX systems, no-op. */ inline std::string utf8_to_native_str(const std::string& s) { #ifdef _WIN32 // first to wide string (native format) std::wstring ws = utf8_cstr_to_utf16_wstring(s.c_str()); // then to string (still native) std::wstring_convert<std::codecvt_utf16<wchar_t>> conv_16to16; std::string ret = conv_16to16.to_bytes(ws); return ret; #else return s; #endif // _WIN32 } /** \brief Converts a UTF-8 string to a native filesystem-encoded string. * * On Windows, converts between UTF-16 and UTF-8. On POSIX systems, no-op. */ inline std::string native_to_utf8_str(const std::string& s) { #ifdef _WIN32 // first to wide string (still native format) std::wstring_convert<std::codecvt_utf16<wchar_t>> conv_16to16; std::wstring ws = conv_16to16.from_bytes(s); // then to string (utf8) std::string ret = utf16_wcstr_to_utf8_string(ws.c_str()); return ret; #else return s; #endif // _WIN32 } } // SC_Codecvt
4,433
C++
.h
119
34.966387
104
0.71907
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
34,113
SC_ServerBootDelayWarning.h
supercollider_supercollider/common/SC_ServerBootDelayWarning.h
// Add a warning when Windows Defender delays scsynth boot by 60+ seconds // cf. github issue #4368 #pragma once // On Windows, starts a timer that will display a warning message // after 10 seconds if the server has not booted, // which may be due to Windows Defender. // On other platforms, it does not do anything. // Must be called at the start of the server boot sequence. void startServerBootDelayWarningTimer(); // Must be called at the end of the server boot sequence. void stopServerBootDelayWarningTimer();
520
C++
.h
11
46
73
0.784585
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,114
SC_AppleEventLoop.hpp
supercollider_supercollider/common/SC_AppleEventLoop.hpp
/************************************************************************ * * Copyright 2019 Christof Ressi <info@christofressi.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #pragma once namespace SC { namespace Apple { namespace EventLoop { // Setup the main application. This function must be called in the // main thread and before any other calls to Cocoa methods. void setup(); // Run the event loop. This function must be called in the main thread. // It blocks until the event loop finishes. void run(); // Ask the event loop to stop and terminate the program. // This function can be called from any thread. void quit(); }}} // namespace SC::Apple::EventLoop
1,359
C++
.h
30
43.6
74
0.677736
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,115
SC_EventLoop.hpp
supercollider_supercollider/common/SC_EventLoop.hpp
#pragma once #include <functional> #ifdef __APPLE__ # include "SC_AppleEventLoop.hpp" # include <thread> #endif // For now, the event loop is only implemented for macOS where // it is most needed (because the GUI event loop *must* run on the main thread). // Later a Windows and Linux implementation might follow, but this would // require a plugin API method to retrieve a handle to the GUI thread. // (Windows and Linux don't have any notion of a "main thread" and therefore // lack a method like "dispatch_get_main_queue".) class EventLoop { public: // This function must be called at the very beginning of the main thread! static void setup() { #ifdef __APPLE__ SC::Apple::EventLoop::setup(); #endif } // Run the event loop until 'waitFunction' returns. static void run(std::function<void()> waitFunction) { #ifdef __APPLE__ // this thread simply waits for 'waitFunction' to return, // after which it will ask the event loop to terminate. auto thread = std::thread([waitFunction]() { waitFunction(); SC::Apple::EventLoop::quit(); }); thread.detach(); SC::Apple::EventLoop::run(); #else waitFunction(); #endif } };
1,241
C++
.h
36
30.222222
80
0.674167
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,116
SC_OscUtils.hpp
supercollider_supercollider/common/SC_OscUtils.hpp
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. Copyright (c) 2013 Tim Blechmann This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "SC_ReplyImpl.hpp" #include <cinttypes> static bool dumpOSCmsg(int inSize, char* inData, bool skipStatus = false) { int size; const char* data; if (inData[0]) { const char* addr = inData; if (skipStatus) { if (strcmp(addr, "/status") == 0 || strcmp(addr, "status") == 0) // skip /status messages return false; // nothing has been printed } data = OSCstrskip(inData); size = inSize - (data - inData); scprintf("[ \"%s\",", addr); } else { scprintf("[ %d,", OSCint(inData)); data = inData + 4; size = inSize - 4; } sc_msg_iter msg(size, data); while (msg.remain()) { char c = msg.nextTag('i'); switch (c) { case 'i': scprintf(" %d", msg.geti()); break; case 'f': scprintf(" %g", msg.getf()); break; case 'd': scprintf(" %g", msg.getd()); break; case 's': scprintf(" \"%s\"", msg.gets()); break; case '[': scprintf(" ["); msg.count++; break; case ']': scprintf(" ]"); msg.count++; break; case 'b': scprintf(" DATA[%zu]", msg.getbsize()); msg.skipb(); break; case 'm': { char midi[4]; msg.getb(midi, 4); scprintf(" MIDI[0x%02x 0x%02x 0x%02x 0x%02x]", midi[0], midi[1], midi[2], midi[3]); break; } case 'c': scprintf(" %c", (char)msg.geti()); break; case 't': scprintf(" %" PRId64 "", msg.gett()); break; case 'T': scprintf(" true"); msg.count++; break; case 'F': scprintf(" false"); msg.count++; break; case 'I': scprintf(" infinitum"); msg.count++; break; case 'N': scprintf(" nil"); msg.count++; break; default: scprintf(" !unknown tag '%c' 0x%02x !", isprint(c) ? c : '?', (unsigned char)c & 255); goto leave; } if (msg.remain() && (c != '[')) scprintf(","); } leave: scprintf(" ]"); return true; // something has been printed } static void hexdump(int size, char* data) { char ascii[20]; int padsize = (size + 15) & -16; scprintf("size %d\n", size); for (int i = 0; i < padsize; ++i) { if ((i & 15) == 0) { scprintf("%4d ", i); } if (i >= size) { scprintf(" "); ascii[i & 15] = 0; } else { scprintf("%02x ", (unsigned char)data[i] & 255); if (isprint(data[i])) ascii[i & 15] = data[i]; else ascii[i & 15] = '.'; } if ((i & 15) == 15) { ascii[16] = 0; scprintf(" |%s|\n", ascii); } else if ((i & 3) == 3) { scprintf(" "); } } scprintf("\n"); } static bool dumpOSCbndl(int indent, int size, char* inData) { char* data = inData + 8; char* dataEnd = inData + size; scprintf("[ \"#bundle\", %" PRIu64 ", ", OSCtime(data)); data += 8; while (data < dataEnd) { int contentPrinted; int32 msgSize = OSCint(data); data += sizeof(int32); scprintf("\n"); for (int i = 0; i < indent + 1; i++) scprintf(" "); if (!strcmp(data, "#bundle")) contentPrinted = dumpOSCbndl(indent + 1, msgSize, data); else contentPrinted = dumpOSCmsg(msgSize, data, true); data += msgSize; if ((data < dataEnd) && contentPrinted) scprintf(","); } scprintf("\n"); for (int i = 0; i < indent; i++) scprintf(" "); scprintf("]"); return true; } static void dumpOSC(int mode, int size, char* inData) { if (mode & 1) { int indent = 0; bool contentPrinted; if (strcmp(inData, "#bundle") == 0) contentPrinted = dumpOSCbndl(indent, size, inData); else contentPrinted = dumpOSCmsg(size, inData, true); if (contentPrinted) scprintf("\n"); } if (mode & 2) hexdump(size, inData); } #if 0 // debugging code static void DumpReplyAddress(ReplyAddress *inReplyAddress) { scprintf("mAddress %s\n", inReplyAddress->mAddress.to_string().c_str()); if (inReplyAddress->mProtocol == kUDP) scprintf("mProtocol UDP\n"); else scprintf("mProtocol TCP\n"); scprintf("mPort %d\n", inReplyAddress->mPort); scprintf("mSocket %d\n", inReplyAddress->mSocket); scprintf("mReplyFunc %p\n", (void*)inReplyAddress->mReplyFunc); } #endif
5,779
C++
.h
183
23.131148
101
0.520553
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,117
SC_AllocPool.h
supercollider_supercollider/common/SC_AllocPool.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* This is based on Doug Lea's allocator but rewritten so I can read and understand it... also features of free all-at-once pools are added. Now uses 16 byte alignment, which does increase the minimum allocation size to 32 bytes including the overhead. Improved bit block scanning by using a count leading zeroes instruction. */ #pragma once #include "SC_List.h" #include "clz.h" #include "function_attributes.h" #include <stdlib.h> const int kNumAllocBins = 128; const int kNumSmallBins = 64; const int kMaxSmallBin = kNumSmallBins - 1; const int kBinWidth = 8; const int kMaxSmallBinSize = kNumSmallBins * kBinWidth; const int kBinBlockWidth = 4; const int kBinBlockMask = kBinBlockWidth - 1; const size_t kAlign = 64; const size_t kAlignMask = kAlign - 1; const size_t kChunkFree = 0; const size_t kChunkInUse = 1; const size_t kSizeBits = ~kChunkInUse; class AllocChunk; class AllocPool; typedef AllocChunk* AllocChunkPtr; typedef Link<AllocChunk> AllocBin; typedef AllocBin* AllocBinPtr; class AllocChunk : public Link<AllocChunk> { friend class AllocPool; size_t Size() { return mSize & kSizeBits; } size_t PrevSize() { return mPrevSize & kSizeBits; } AllocChunkPtr ChunkAtOffset(long inSize) { return AllocChunkPtr((char*)this + inSize); } AllocChunkPtr NextChunk() { return ChunkAtOffset(Size()); } AllocChunkPtr PrevChunk() { return ChunkAtOffset(-(long)PrevSize()); } bool InUse() { return (bool)(mSize & kChunkInUse); } bool PrevInUse() { return (bool)(mPrevSize & kChunkInUse); } void SetSizeFree(size_t inSize) { mSize = ChunkAtOffset(inSize)->mPrevSize = inSize; } void SetSizeInUse(size_t inSize) { mSize = ChunkAtOffset(inSize)->mPrevSize = inSize | kChunkInUse; } void SetNeighborsInUse(size_t inOffset) { mPrevSize = ChunkAtOffset(inOffset)->mSize = kChunkInUse; } bool IsArea() { return mPrevSize == kChunkInUse && NextChunk()->mSize == kChunkInUse; } void* ToPtr() { return (void*)((char*)this + sizeof(AllocChunk)); } size_t mPrevSize; size_t mSize; }; class AllocArea; typedef AllocArea* AllocAreaPtr; class AllocAreaHdr /* for size calculations */ { protected: friend class AllocPool; AllocAreaPtr mPrev, mNext; size_t mSize; void* mUnalignedPointerToThis; }; class AllocArea : public AllocAreaHdr { public: void SanityCheck(); private: friend class AllocPool; AllocChunk mChunk; }; const size_t kMinAllocSize = 2 * kAlign; const size_t kAreaOverhead = sizeof(AllocAreaHdr) + 2 * sizeof(AllocChunk) + kAlign; typedef void* (*NewAreaFunc)(size_t size); typedef void (*FreeAreaFunc)(void*); class AllocPool { public: AllocPool(NewAreaFunc allocArea, FreeAreaFunc freeArea, size_t areaInitSize, size_t areaMoreSize); ~AllocPool(); void Reinit(); MALLOC void* Alloc(size_t inBytes); MALLOC void* Realloc(void* inPtr, size_t inBytes); void Free(void* inPtr); void FreeAll(); void FreeAllInternal(); // debugging size_t TotalFree(); size_t LargestFreeChunk(); void DoCheckPool(); void DoCheckInUseChunk(AllocChunkPtr p); static AllocChunkPtr MemToChunk(void* inPtr) { return (AllocChunkPtr)((char*)(inPtr) - sizeof(AllocChunk)); } private: void InitAlloc(); void InitBins(); AllocAreaPtr NewArea(size_t inAreaSize); void FreeArea(AllocChunkPtr chunk); // debugging void DoCheckArea(AllocAreaPtr area); void DoCheckBin(AllocChunkPtr bin, long idx); void DoCheckChunk(AllocChunkPtr p); void DoCheckFreeChunk(AllocChunkPtr p); void DoCheckAllocedChunk(AllocChunkPtr p, size_t s); void DoGarbageFill(AllocChunkPtr p); void DoGarbageFill(AllocChunkPtr p, long size); // inlines static size_t RequestToSize(size_t inReqSize) { size_t sizePlusOverhead = inReqSize + sizeof(AllocChunk); if (sizePlusOverhead <= kMinAllocSize) return kMinAllocSize; else return (sizePlusOverhead + kAlignMask) & ~kAlignMask; } static size_t SmallBinIndex(size_t inSize) { return inSize >> 4; } static size_t BinIndex2(size_t inSize) { return ((inSize < 1024) ? (inSize >> 4) : (inSize < 2048) ? 56 + (inSize >> 7) : (inSize < 4096) ? 64 + (inSize >> 8) : (inSize < 8192) ? 72 + (inSize >> 9) : (inSize < 16384) ? 80 + (inSize >> 10) : (inSize < 32768) ? 88 + (inSize >> 11) : (inSize < 65536) ? 96 + (inSize >> 12) : (inSize < 131072) ? 104 + (inSize >> 13) : (inSize < 262144) ? 112 + (inSize >> 14) : 127); } static size_t BinIndex(size_t inSize) { if (inSize < 1024) return inSize >> 4; if (inSize >= 262144) return 127; int bits = 28 - CLZ(inSize); return (bits << 3) + (inSize >> bits); } void MarkBinBlock(size_t inIndex) { size_t word = inIndex >> 5; size_t bitPosition = inIndex & 31; size_t bitValue = 1L << bitPosition; mBinBlocks[word] |= bitValue; } void ClearBinBlock(size_t inIndex) { size_t word = inIndex >> 5; size_t bitPosition = inIndex & 31; size_t bitValue = 1L << bitPosition; mBinBlocks[word] &= ~bitValue; } int NextFullBin(int inStartingBinIndex) { if (inStartingBinIndex >= 128) return -1; int word = inStartingBinIndex >> 5; int bitPosition = inStartingBinIndex & 31; unsigned long bitValue = 1L << bitPosition; unsigned long binBits = mBinBlocks[word]; if (binBits >= bitValue) { binBits = (~(bitValue - 1) & binBits); } else { for (++word; word < 4 && !mBinBlocks[word]; ++word) {} if (word == 4) return -1; binBits = mBinBlocks[word]; } bitPosition = CTZ((int32)binBits); return (word << 5) + bitPosition; } void LinkFree(AllocChunkPtr inChunk); /* { size_t size = inChunk->Size(); int index = BinIndex(size); AllocChunkPtr bin = mBins + index; if (index < kNumSmallBins || bin->IsEmpty()) { inChunk->InsertAfter(bin); MarkBinBlock(index); } else { AllocChunkPtr link = bin->Next(); while (link != bin && size < link->Size()) link = link->Next(); inChunk->InsertBefore(link); } } */ void UnlinkFree(AllocChunkPtr inChunk) { inChunk->RemoveLeaveDangling(); size_t size = inChunk->Size(); size_t index = BinIndex(size); AllocChunkPtr bin = mBins + index; if (bin->IsEmpty()) ClearBinBlock(index); } AllocChunk mBins[kNumAllocBins]; AllocAreaPtr mAreas; NewAreaFunc mAllocArea; FreeAreaFunc mFreeArea; size_t mAreaInitSize, mAreaMoreSize; unsigned long mBinBlocks[4]; };
7,975
C++
.h
202
32.762376
113
0.650816
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,118
SC_Errors.h
supercollider_supercollider/common/SC_Errors.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once typedef int SCErr; void SC_ErrorString(SCErr err, char returnString[]); enum { kSCErr_None, kSCErr_Failed, kSCErr_NodeNotFound, kSCErr_TargetNodeNotFound, kSCErr_GroupNotFound, kSCErr_SynthDefNotFound, kSCErr_NoSuchCommand, kSCErr_WrongArgType, kSCErr_IndexOutOfRange, kSCErr_AccessDenied, kSCErr_NoReplyPort, kSCErr_InvalidControlIndex, kSCErr_AlreadyLoggedIn, kSCErr_NotLoggedIn, kSCErr_TooManyUsers, kSCErr_TooManyNodes, kSCErr_DuplicateNodeID, kSCErr_ReservedNodeID, kSCErr_ReplaceRootGroup, kSCErr_OutOfRealTimeMemory, kSCErr_UnsupportedHeaderFormat, kSCErr_UnsupportedSampleFormat, kSCErr_BufGenNotFound, kSCErr_NumErrors };
1,621
C++
.h
45
31.4
81
0.764856
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,119
SC_Apple.hpp
supercollider_supercollider/common/SC_Apple.hpp
/************************************************************************ * * Copyright 2013 Seth Nickell <snickell@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #pragma once namespace SC { namespace Apple { void disableAppNap(); } // namespace Apple } // namespace SC
967
C++
.h
23
40.130435
74
0.641489
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,120
SC_Filesystem.hpp
supercollider_supercollider/common/SC_Filesystem.hpp
/** * \file SC_Filesystem.hpp * * \brief Filesystem utilities for SuperCollider. * * This header provides a singleton class, SC_Filesystem, which handles many * important filesystem functions: * - Getting and setting application directories (such as config, resource, and extension) * - Expanding ~ to the home directory * - Alias resolution * - Globbing * - Conversion between Path and UTF-8 encoded string * * \note This header replaced an older implementation by Tim Walters, SC_DirUtils.hpp. Most of the globbing and * directory calculation code is his. * * $Authors: Brian Heim, Tim Walters $ * * \version Latest revision by Brian Heim, 2017 * * $Date: 2017-04-30 $ * * $Contact: brianlheim@gmail.com $ * * Created on: 2017-04-03 * * Original revision by Tim Walters, 2005-10-19. */ /* * Copyright (C) Tim Walters, 2005. All rights reserved. * Copyright (C) Brian Heim, 2017. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA */ #pragma once #ifndef PATH_MAX # define PATH_MAX MAX_PATH #endif #ifndef MAXPATHLEN # define MAXPATHLEN PATH_MAX #endif /// Name of the folder used for system and user extensions. #define SC_FOLDERNAME_EXTENSIONS "Extensions" /// Name of "SuperCollider" folder. Could probably pop this up another level of importance. #define SC_FOLDERNAME_APPLICATION_NAME "SuperCollider" /// Default IDE name. #define SC_DEFAULT_IDE_NAME "none" /// Name of the plugins subdirectory of the Resources dir #define SC_PLUGIN_DIR_NAME "plugins" /// Extension for server plugins. #ifndef SC_PLUGIN_EXT # define SC_PLUGIN_EXT ".scx" #endif #include <map> // map #include <algorithm> // std::transform #include <string> // std::string #include <filesystem> // std::filesystem #include "SC_Codecvt.hpp" // path_to_utf8_str /** \class SC_Filesystem * * \brief A singleton class providing SuperCollider filesystem utilities. * * - Getting and setting application directories (such as config, resource, and extension) * - Expanding ~ to the home directory * - Alias resolution * - Globbing * - Conversion between Path and UTF-8 encoded string */ class SC_Filesystem { public: //--------------------------------------------------------------------------------------// //------------------------------ PUBLIC CLASS MEMBERS ----------------------------------// //--------------------------------------------------------------------------------------// //---------------------------------- PUBLIC TYPES --------------------------------------// enum class DirName; struct Glob; typedef std::filesystem::path Path; ///< Path type. typedef std::map<DirName, Path> DirMap; ///< Type of directory name-to-path map. /// SuperCollider common directory names. enum class DirName { SystemAppSupport, SystemExtension, UserHome, UserAppSupport, UserExtension, UserConfig, Resource, MyDocuments // only on Windows, used for Platform.myDocumentsDir in sclang }; //------------------------------- SINGLETON INSTANCE -----------------------------------// /// Singleton instance. static SC_Filesystem& instance() { static SC_Filesystem instance; return instance; } //--------------------------- COMMON DIRECTORY MANAGEMENT ------------------------------// /// Get path associated with a common directory; the path is initialized if necessary. Path getDirectory(const DirName& dn) { const DirMap::const_iterator& it = mDirectoryMap.find(dn); if (it != mDirectoryMap.end()) { return it->second; } mDirectoryMap[dn] = defaultDirectory(dn); return mDirectoryMap[dn]; } /// Set path associated with a common directory. inline void setDirectory(const DirName& dn, const Path& p) { mDirectoryMap[dn] = p; } //-------------------------------- GENERAL UTILITIES -----------------------------------// /** \brief Checks whether a directory should be compiled. * \param p a directory path * \return True if the directory should not be traversed during compilation. * * Specifically, returns true if the directory name, ignoreing case, is equal to: * - one of ".svn", ".git", or "_darcs" * - one of "help" or "ignore" * - a string starting with "scide_" but not ending with the current IDE name * - one of "windows", "osx", "iphone", or "linux", but that is not the name of the current platform. */ bool shouldNotCompileDirectory(const Path& p) const { std::string dirname = SC_Codecvt::path_to_utf8_str(p.filename()); std::transform(dirname.begin(), dirname.end(), dirname.begin(), ::tolower); return dirname == "help" || dirname == "ignore" || dirname == ".svn" || dirname == ".git" || dirname == "_darcs" || isUnusedIdeDirectoryName(dirname) || isNonHostPlatformDirectoryName(dirname); } /// Expands a path starting with `~` to use the user's home directory. Path expandTilde(const Path& p) { static const Path tilde("~"); if (!p.empty() && *p.begin() == tilde) { // If the first element in the path is tilde, just concatenate the rest of the path onto it const Path homeDir = getDirectory(DirName::UserHome); const std::string homeDir_utf8 = SC_Codecvt::path_to_utf8_str(homeDir); const std::string inPath_utf8 = SC_Codecvt::path_to_utf8_str(p); const std::string result = homeDir_utf8 + inPath_utf8.substr(1); return SC_Codecvt::utf8_str_to_path(result); } else { return p; } } //---------------------------------- IDE UTILITIES -------------------------------------// /// Get the IDE name. "none" is the default. const std::string& getIdeName() const { return mIdeName; } /// Set the IDE name. const void setIdeName(const std::string& s) { mIdeName = s; } /// Returns true if the IDE name is "none" (the default) const bool usingIde() const { return mIdeName != SC_DEFAULT_IDE_NAME; } //--------------------------------------------------------------------------------------// //------------------------------ PUBLIC STATIC MEMBERS ---------------------------------// //--------------------------------------------------------------------------------------// //-------------------------------- GENERAL UTILITIES -----------------------------------// /** \brief Resolves an alias on macOS. * \param p a path to resolve * \param isAlias set to true if p is an alias * \return An empty path if resolution failed; otherwise, the resolved path. * * If the path was not an alias, a copy is returned. */ // Could possibly be split into `isAlias` and `resolveAlias` to avoid // unnecessary copying - bh static Path resolveIfAlias(const Path& p, bool& isAlias); //--------------------------------- GLOB UTILITIES -------------------------------------// /** \brief Makes a glob. * \param pattern a UTF-8 encoded string * * Constructs a Glob from a given pattern. Call globNext to get the next * Path in the glob. Client is responsible for calling freeGlob. */ static Glob* makeGlob(const char* pattern); /// Next available Path in the glob. Returns empty path to indicate end. static Path globNext(Glob* g); /// Frees a Glob. static void freeGlob(Glob* g); private: //--------------------------------------------------------------------------------------// //--------------------------------- PRIVATE MEMBERS ------------------------------------// //--------------------------------------------------------------------------------------// //---------------------------- CONSTRUCTORS & ASSIGNMENT -------------------------------// SC_Filesystem(SC_Filesystem const&) = delete; void operator=(SC_Filesystem const&) = delete; SC_Filesystem(): mDirectoryMap(), mIdeName(SC_DEFAULT_IDE_NAME) {} //----------------------------------- IDE UTILITIES ------------------------------------// bool isUnusedIdeDirectoryName(const std::string& s) const { return s.size() > 6 && s.substr(0, 6) == "scide_" && s.substr(6) != getIdeName(); } //------------------------------ PRIVATE STATIC MEMBERS --------------------------------// /** Of the four strings "windows", "osx", "linux", "iphone", returns true if `p` is one of the * three that doesn't correspond to this platform. */ static bool isNonHostPlatformDirectoryName(const std::string& p); static Path defaultDirectory(const DirName& dn) { switch (dn) { case DirName::SystemAppSupport: return defaultSystemAppSupportDirectory(); case DirName::SystemExtension: return defaultSystemExtensionDirectory(); case DirName::UserHome: return defaultUserHomeDirectory(); case DirName::UserAppSupport: return defaultUserAppSupportDirectory(); case DirName::UserExtension: return defaultUserExtensionDirectory(); case DirName::UserConfig: return defaultUserConfigDirectory(); case DirName::Resource: return defaultResourceDirectory(); #ifdef _WIN32 case DirName::MyDocuments: return defaultMyDocumentsDirectory(); #endif default: return Path(); } } static Path defaultSystemAppSupportDirectory(); static Path defaultUserHomeDirectory(); static Path defaultUserAppSupportDirectory(); static Path defaultUserConfigDirectory(); static Path defaultResourceDirectory(); #ifdef _WIN32 // this function has no analogue on other OSs, yet. static Path defaultMyDocumentsDirectory(); #endif static Path defaultSystemExtensionDirectory() { const Path& p = defaultSystemAppSupportDirectory(); return p.empty() ? p : p / SC_FOLDERNAME_EXTENSIONS; } static Path defaultUserExtensionDirectory() { const Path& p = defaultUserAppSupportDirectory(); return p.empty() ? p : p / SC_FOLDERNAME_EXTENSIONS; } //------------------------------- PRIVATE DATA MEMBERS ---------------------------------// DirMap mDirectoryMap; std::string mIdeName; };
11,085
C++
.h
243
40.36214
120
0.586213
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
34,121
SC_Win32Utils.h
supercollider_supercollider/common/SC_Win32Utils.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #ifdef _WIN32 # ifdef IN # define SC_IN IN # undef IN # endif # ifdef OUT # define SC_OUT OUT # undef OUT # endif # include <stdio.h> # include <winsock2.h> # undef IN # undef OUT # ifdef SC_IN # define IN SC_IN # endif # ifdef SC_OUT # define OUT SC_OUT # endif // wrappers for unix replacements # define basename win32_basename # define dirname win32_dirname # define pipe win32_pipe # if _MSC_VER typedef int pid_t; # endif void win32_ReplaceCharInString(char* string, int len, char src, char dst); // Finds the parent folder of a specified path pattern (including trailing slash) void win32_ExtractContainingFolder(char* folder, const char* pattern, int maxChars); void win32_synctimes(); char* win32_basename(char* path); char* win32_dirname(char* path); int win32_pipe(int handles[2]); int win32_piperead(int s, char* buf, int len); int win32_pipewrite(int s, char* buf, int len); // missing Windows implementations in nova_tt bool win32_thread_set_affinity(int i); int win32_name_thread(const char* name); // alloca # include <malloc.h> # ifndef alloca // MinGW has alloca defined in malloc.h, MSVC not # define alloca _alloca # endif #endif //_WIN32
2,165
C++
.h
61
33.327869
84
0.721876
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,122
SC_VFP11.h
supercollider_supercollider/common/SC_VFP11.h
#pragma once #include <TargetConditionals.h> #define IPHONE_VEC inline void initVFP() { #if !TARGET_IPHONE_SIMULATOR int tmp; __asm__ __volatile__("fmrx %[tmp], fpscr\n\t" "orr %[tmp], %[tmp], #(3 << 16)\n\t" /* set vector size to 4 */ "fmxr fpscr, %[tmp]\n\t" : [tmp] "=&r"(tmp) : : "cc", "memory"); #endif } inline void releaseVFP() { #if !TARGET_IPHONE_SIMULATOR int tmp; __asm__ __volatile__("fmrx %[tmp], fpscr\n\t" "bic %[tmp], %[tmp], #(7 << 16)\n\t" /* set vector size back to 1 */ "fmxr fpscr, %[tmp]\n\t" : [tmp] "=&r"(tmp) : : "cc", "memory"); #endif } inline void vfill(float* dest, float val, int len) { #if !TARGET_IPHONE_SIMULATOR float t[4] = { val, val, val, val }; float* v = (float*)t; int tmp; __asm__ __volatile__("fmrx %[tmp], fpscr\n\t" "orr %[tmp], %[tmp], #(3 << 16)\n\t" /* set vector size to 4 */ "fmxr fpscr, %[tmp]\n\t" "fldmias %[src1], {s8-s11}\n\t" "1:\n\t" "subs %[len], %[len], #16\n\t" "fstmias %[dst]!, {s8-s11}\n\t" "fstmias %[dst]!, {s8-s11}\n\t" "fstmiasge %[dst]!, {s8-s11}\n\t" "fstmiasge %[dst]!, {s8-s11}\n\t" "bgt 1b\n\t" "bic %[tmp], %[tmp], #(7 << 16)\n\t" /* set vector size back to 1 */ "fmxr fpscr, %[tmp]\n\t" : [dst] "+&r"(dest), [src1] "+&r"(v), [len] "+&r"(len), [tmp] "=&r"(tmp) : : "s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "s10", "s11", "s12", "s13", "s14", "s15", "s16", "s17", "s18", "s19", "s20", "s21", "s22", "s23", "s24", "s25", "s26", "s27", "s28", "s29", "s30", "s31", "cc", "memory"); #endif } // a + b*c inline void vmuladd(float* dest, float* a, float* b, float* c, int len) { #if !TARGET_IPHONE_SIMULATOR int tmp; __asm__ __volatile__( "fmrx %[tmp], fpscr\n\t" "orr %[tmp], %[tmp], #(3 << 16)\n\t" /* set vector size to 4 */ "fmxr fpscr, %[tmp]\n\t" "fldmias %[src2]!, {s0-s3}\n\t" "fldmias %[src1]!, {s8-s11}\n\t" "fldmias %[src3]!, {s24-s27}\n\t" "fldmias %[src2]!, {s4-s7}\n\t" "fldmias %[src1]!, {s12-s15}\n\t" "fldmias %[src3]!, {s28-s31}\n\t" "fmacs s8, s0, s24\n\t" "1:\n\t" "subs %[len], %[len], #16\n\t" "fmacs s12, s4, s28\n\t" "fldmiasge %[src2]!, {s0-s3}\n\t" "fldmiasge %[src1]!, {s16-s19}\n\t" "fldmiasge %[src3]!, {s24-s27}\n\t" "fldmiasge %[src2]!, {s4-s7}\n\t" "fldmiasge %[src1]!, {s20-s23}\n\t" "fldmiasge %[src3]!, {s28-s31}\n\t" "fmacsge s16, s0, s24\n\t" "fstmias %[dst]!, {s8-s11}\n\t" "fstmias %[dst]!, {s12-s15}\n\t" "fmacsge s20, s4, s28\n\t" "fldmiasgt %[src2]!, {s0-s3}\n\t" "fldmiasgt %[src1]!, {s8-s11}\n\t" "fldmiasgt %[src3]!, {s24-s27}\n\t" "fldmiasgt %[src2]!, {s4-s7}\n\t" "fldmiasgt %[src1]!, {s12-s15}\n\t" "fldmiasgt %[src3]!, {s28-s31}\n\t" "fmacsge s8, s0, s24\n\t" "fstmiasge %[dst]!, {s16-s19}\n\t" "fstmiasge %[dst]!, {s20-s23}\n\t" "bgt 1b\n\t" "bic %[tmp], %[tmp], #(7 << 16)\n\t" /* set vector size back to 1 */ "fmxr fpscr, %[tmp]\n\t" : [dst] "+&r"(dest), [src1] "+&r"(a), [src2] "+&r"(b), [src3] "+&r"(c), [len] "+&r"(len), [tmp] "=&r"(tmp) : : "s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "s10", "s11", "s12", "s13", "s14", "s15", "s16", "s17", "s18", "s19", "s20", "s21", "s22", "s23", "s24", "s25", "s26", "s27", "s28", "s29", "s30", "s31", "cc", "memory"); #endif } inline void vscalarmul(float* dest, float scalar, float* b, int len) { #if !TARGET_IPHONE_SIMULATOR float t[4] = { scalar, scalar, scalar, scalar }; float* s = t; int tmp; __asm__ __volatile__("fmrx %[tmp], fpscr\n\t" "orr %[tmp], %[tmp], #(3 << 16)\n\t" /* set vector size to 4 */ "fmxr fpscr, %[tmp]\n\t" "fldmias %[src1], {s0-s3}\n\t" "fldmias %[src2]!, {s8-s11}\n\t" "fldmias %[src2]!, {s12-s15}\n\t" "fmuls s8, s8, s0\n\t" "1:\n\t" "subs %[len], %[len], #16\n\t" "fmuls s12, s12, s0\n\t" "fldmiasge %[src2]!, {s24-s27}\n\t" "fldmiasge %[src2]!, {s28-s31}\n\t" "fmulsge s24, s24, s0\n\t" "fstmias %[dst]!, {s8-s11}\n\t" "fstmias %[dst]!, {s12-s15}\n\t" "fmulsge s28, s28, s0\n\t" "fldmiasgt %[src2]!, {s8-s11}\n\t" "fldmiasgt %[src2]!, {s12-s15}\n\t" "fmulsge s8, s8, s0\n\t" "fstmiasge %[dst]!, {s24-s27}\n\t" "fstmiasge %[dst]!, {s28-s31}\n\t" "bgt 1b\n\t" "bic %[tmp], %[tmp], #(7 << 16)\n\t" /* set vector size back to 1 */ "fmxr fpscr, %[tmp]\n\t" : [dst] "+&r"(dest), [src1] "+&r"(s), [src2] "+&r"(b), [len] "+&r"(len), [tmp] "=&r"(tmp) : : "s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "s10", "s11", "s12", "s13", "s14", "s15", "s16", "s17", "s18", "s19", "s20", "s21", "s22", "s23", "s24", "s25", "s26", "s27", "s28", "s29", "s30", "s31", "cc", "memory"); #endif } inline void vmul(float* dest, float* a, const float* b, int len) { #if !TARGET_IPHONE_SIMULATOR int tmp; __asm__ __volatile__("fmrx %[tmp], fpscr\n\t" "orr %[tmp], %[tmp], #(3 << 16)\n\t" /* set vector size to 4 */ "fmxr fpscr, %[tmp]\n\t" "fldmias %[src1]!, {s0-s3}\n\t" "fldmias %[src2]!, {s8-s11}\n\t" "fldmias %[src1]!, {s4-s7}\n\t" "fldmias %[src2]!, {s12-s15}\n\t" "fmuls s8, s0, s8\n\t" "1:\n\t" "subs %[len], %[len], #16\n\t" "fmuls s12, s4, s12\n\t" "fldmiasge %[src1]!, {s16-s19}\n\t" "fldmiasge %[src2]!, {s24-s27}\n\t" "fldmiasge %[src1]!, {s20-s23}\n\t" "fldmiasge %[src2]!, {s28-s31}\n\t" "fmulsge s24, s16, s24\n\t" "fstmias %[dst]!, {s8-s11}\n\t" "fstmias %[dst]!, {s12-s15}\n\t" "fmulsge s28, s20, s28\n\t" "fldmiasgt %[src1]!, {s0-s3}\n\t" "fldmiasgt %[src2]!, {s8-s11}\n\t" "fldmiasgt %[src1]!, {s4-s7}\n\t" "fldmiasgt %[src2]!, {s12-s15}\n\t" "fmulsge s8, s0, s8\n\t" "fstmiasge %[dst]!, {s24-s27}\n\t" "fstmiasge %[dst]!, {s28-s31}\n\t" "bgt 1b\n\t" "bic %[tmp], %[tmp], #(7 << 16)\n\t" /* set vector size back to 1 */ "fmxr fpscr, %[tmp]\n\t" : [dst] "+&r"(dest), [src1] "+&r"(a), [src2] "+&r"(b), [len] "+&r"(len), [tmp] "=&r"(tmp) : : "s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "s10", "s11", "s12", "s13", "s14", "s15", "s16", "s17", "s18", "s19", "s20", "s21", "s22", "s23", "s24", "s25", "s26", "s27", "s28", "s29", "s30", "s31", "cc", "memory"); #endif } inline void vadd(float* dest, float* a, const float* b, int len) { #if !TARGET_IPHONE_SIMULATOR int tmp; __asm__ __volatile__("fmrx %[tmp], fpscr\n\t" "orr %[tmp], %[tmp], #(3 << 16)\n\t" /* set vector size to 4 */ "fmxr fpscr, %[tmp]\n\t" "fldmias %[src1]!, {s0-s3}\n\t" "fldmias %[src2]!, {s8-s11}\n\t" "fldmias %[src1]!, {s4-s7}\n\t" "fldmias %[src2]!, {s12-s15}\n\t" "fadds s8, s0, s8\n\t" "1:\n\t" "subs %[len], %[len], #16\n\t" "fadds s12, s4, s12\n\t" "fldmiasge %[src1]!, {s16-s19}\n\t" "fldmiasge %[src2]!, {s24-s27}\n\t" "fldmiasge %[src1]!, {s20-s23}\n\t" "fldmiasge %[src2]!, {s28-s31}\n\t" "faddsge s24, s16, s24\n\t" "fstmias %[dst]!, {s8-s11}\n\t" "fstmias %[dst]!, {s12-s15}\n\t" "faddsge s28, s20, s28\n\t" "fldmiasgt %[src1]!, {s0-s3}\n\t" "fldmiasgt %[src2]!, {s8-s11}\n\t" "fldmiasgt %[src1]!, {s4-s7}\n\t" "fldmiasgt %[src2]!, {s12-s15}\n\t" "faddsge s8, s0, s8\n\t" "fstmiasge %[dst]!, {s24-s27}\n\t" "fstmiasge %[dst]!, {s28-s31}\n\t" "bgt 1b\n\t" "bic %[tmp], %[tmp], #(7 << 16)\n\t" /* set vector size back to 1 */ "fmxr fpscr, %[tmp]\n\t" : [dst] "+&r"(dest), [src1] "+&r"(a), [src2] "+&r"(b), [len] "+&r"(len), [tmp] "=&r"(tmp) : : "s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "s10", "s11", "s12", "s13", "s14", "s15", "s16", "s17", "s18", "s19", "s20", "s21", "s22", "s23", "s24", "s25", "s26", "s27", "s28", "s29", "s30", "s31", "cc", "memory"); #endif } inline void vcopy(float* dest, float* a, int len) { #if !TARGET_IPHONE_SIMULATOR int tmp; __asm__ __volatile__("fmrx %[tmp], fpscr\n\t" "orr %[tmp], %[tmp], #(3 << 16)\n\t" /* set vector size to 4 */ "fmxr fpscr, %[tmp]\n\t" "fldmias %[src1]!, {s8-s11}\n\t" "fldmias %[src1]!, {s12-s15}\n\t" "1:\n\t" "subs %[len], %[len], #16\n\t" "fldmiasge %[src1]!, {s24-s27}\n\t" "fldmiasge %[src1]!, {s28-s31}\n\t" "fstmias %[dst]!, {s8-s11}\n\t" "fstmias %[dst]!, {s12-s15}\n\t" "fldmiasgt %[src1]!, {s8-s11}\n\t" "fldmiasgt %[src1]!, {s12-s15}\n\t" "fstmiasge %[dst]!, {s24-s27}\n\t" "fstmiasge %[dst]!, {s28-s31}\n\t" "bgt 1b\n\t" "bic %[tmp], %[tmp], #(7 << 16)\n\t" /* set vector size back to 1 */ "fmxr fpscr, %[tmp]\n\t" : [dst] "+&r"(dest), [src1] "+&r"(a), [len] "+&r"(len), [tmp] "=&r"(tmp) : : "s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "s10", "s11", "s12", "s13", "s14", "s15", "s16", "s17", "s18", "s19", "s20", "s21", "s22", "s23", "s24", "s25", "s26", "s27", "s28", "s29", "s30", "s31", "cc", "memory"); #endif }
12,269
C++
.h
239
33.48954
120
0.361243
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,123
SC_SyncCondition.h
supercollider_supercollider/common/SC_SyncCondition.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "SC_Lock.h" class SC_SyncCondition { public: SC_SyncCondition(): read(0), write(0) {} ~SC_SyncCondition() {} void WaitEach() { // waits if it has caught up. // not very friendly, may be trying in vain to keep up. unique_lock<SC_Lock> lock(mutex); while (read == write) available.wait(lock); ++read; } void WaitOnce() { // waits if not signaled since last time. // if only a little late then can still go. unique_lock<SC_Lock> lock(mutex); int writeSnapshot = write; while (read == writeSnapshot) available.wait(lock); read = writeSnapshot; } void WaitNext() { // will wait for the next signal after the read = write statement // this is the friendliest to other tasks, because if it is // late upon entry, then it has to lose a turn. unique_lock<SC_Lock> lock(mutex); read = write; while (read == write) available.wait(lock); } void Signal() { ++write; #ifdef SC_CONDITION_VARIABLE_ANY_SHOULD_LOCK_BEFORE_NOTIFY if (mutex.try_lock()) { available.notify_one(); mutex.unlock(); } #else // CONDITION_VARIABLE_ANY_SHOULD_LOCK_BEFORE_NOTIFY available.notify_one(); #endif // CONDITION_VARIABLE_ANY_SHOULD_LOCK_BEFORE_NOTIFY } private: // the mutex is only for pthread_cond_wait, which requires it. // since there is only supposed to be one signaller and one waiter // there is nothing to mutually exclude. condition_variable_any available; SC_Lock mutex; int read, write; };
2,567
C++
.h
67
31.925373
81
0.667471
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,124
SC_StringParser.h
supercollider_supercollider/common/SC_StringParser.h
// emacs: -*- c++ -*- // file: SC_StringParser.h // copyright: 2003-2006 stefan kersten // cvs: $Id$ // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 // USA #pragma once #define SC_MAX_TOKEN_LENGTH 256 #ifdef _WIN32 # define SC_STRPARSE_PATHDELIMITER ';' #else # define SC_STRPARSE_PATHDELIMITER ':' #endif class SC_StringParser { const char *mSpec, *mStart, *mEnd; char mSep, mBuf[SC_MAX_TOKEN_LENGTH]; public: SC_StringParser(); SC_StringParser(const char* spec, char sep); bool AtEnd() const; const char* NextToken(); };
1,228
C++
.h
34
34.205882
75
0.734625
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,125
sc_popen.h
supercollider_supercollider/common/sc_popen.h
#include <stdio.h> #include <sys/types.h> #include <vector> #include <string> #ifndef _WIN32 # include <unistd.h> # include <sys/wait.h> #endif #ifdef _WIN32 # include "SC_Win32Utils.h" /* * Signal stuff * For WIN32, there is no wait() call so there are no wait() macros * to interpret the return value of system(). Instead, system() * return values < 0x100 are used for exit() termination, and higher * values are used to indicated non-exit() termination, which is * similar to a unix-style signal exit (think SIGSEGV == * STATUS_ACCESS_VIOLATION). See this URL for a list of WIN32 * STATUS_* values from Wine: * * http://source.winehq.org/source/include/ntstatus.h */ # define WIFEXITED(w) (((w)&0xffffff00) == 0) # define WIFSIGNALED(w) (!WIFEXITED(w)) # define WEXITSTATUS(w) (w) # define WTERMSIG(w) (w) std::tuple<pid_t, FILE*> sc_popen_c(const char* utf8_cmd, const char* mode); #else std::tuple<pid_t, FILE*> sc_popen_c_argv(const char* filename, char* const argv[], const char* type); #endif /** \brief Opens a pipe to a separate process. * * This function assumes a UTF-8 encoded, narrow-char string. */ std::tuple<pid_t, FILE*> sc_popen(std::string&& command, const std::string& type); std::tuple<pid_t, FILE*> sc_popen_argv(const std::vector<std::string>& strings, const std::string& type); int sc_pclose(FILE* iop, pid_t mPid);
1,384
C++
.h
37
35.891892
105
0.703428
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,126
fftlib.h
supercollider_supercollider/common/fftlib.h
long FFTInit(long* fftMptr, long fftN, float* Utbl); /* Compute cosine table and check size for complex ffts */ /* INPUTS */ /* fftN = size of fft */ /* OUTPUTS */ /* *fftMptr = log2 of fft size */ /* *Utbl = cosine table with fftN/4 + 1 entries (angles = 0 to pi/2 inclusive) */ /* RETURNS */ /* 1 if fftN is invalid, 0 otherwise */ long rFFTInit(long* fftMptr, long fftN, float* Utbl); /* Compute cosine table and check size for a real input fft */ /* INPUTS */ /* fftN = size of fft */ /* OUTPUTS */ /* *fftMptr = log2 of fft size */ /* *Utbl = cosine table with fftN/4 + 1 entries (angles = 0 to pi/2 inclusive) */ /* RETURNS */ /* 1 if fftN is invalid, 0 otherwise */ void ffts(float* ioptr, long M, long Rows, float* Utbl); /* Compute in-place complex fft on the rows of the input array */ /* INPUTS */ /* M = log2 of fft size */ /* *ioptr = input data array */ /* *Utbl = cosine table */ /* Rows = number of rows in ioptr array (use Rows of 1 if ioptr is a 1 dimensional array) */ /* OUTPUTS */ /* *ioptr = output data array */ void iffts(float* ioptr, long M, long Rows, float* Utbl); /* Compute in-place inverse complex fft on the rows of the input array */ /* INPUTS */ /* M = log2 of fft size */ /* *ioptr = input data array */ /* *Utbl = cosine table */ /* Rows = number of rows in ioptr array (use Rows of 1 if ioptr is a 1 dimensional array) */ /* OUTPUTS */ /* *ioptr = output data array */ void rffts(float* ioptr, long M, long Rows, float* Utbl); /* Compute in-place real fft on the rows of the input array */ /* INPUTS */ /* M = log2 of fft size */ /* *ioptr = real input data array */ /* *Utbl = cosine table */ /* Rows = number of rows in ioptr array (use Rows of 1 if ioptr is a 1 dimensional array) */ /* OUTPUTS */ /* *ioptr = output data array in the following order */ /* Re(x[0]), Re(x[N/2]), Re(x[1]), Im(x[1]), Re(x[2]), Im(x[2]), ... Re(x[N/2-1]), Im(x[N/2-1]). */ void riffts(float* ioptr, long M, long Rows, float* Utbl); /* Compute in-place real ifft on the rows of the input array */ /* INPUTS */ /* M = log2 of fft size */ /* *ioptr = input data array in the following order */ /* Re(x[0]), Re(x[N/2]), Re(x[1]), Im(x[1]), Re(x[2]), Im(x[2]), ... Re(x[N/2-1]), Im(x[N/2-1]). */ /* *Utbl = cosine table */ /* Rows = number of rows in ioptr array (use Rows of 1 if ioptr is a 1 dimensional array) */ /* OUTPUTS */ /* *ioptr = real output data array */
2,390
C++
.h
56
41.571429
99
0.642182
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,127
SC_ReplyImpl.hpp
supercollider_supercollider/common/SC_ReplyImpl.hpp
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. Copyright (c) 2013 Tim Blechmann. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "SC_Reply.h" #include <boost/asio.hpp> enum Protocol { kUDP, kTCP }; struct ReplyAddress { boost::asio::ip::address mAddress; enum Protocol mProtocol; int mPort; int mSocket; ReplyFunc mReplyFunc; void* mReplyData; }; void null_reply_func(struct ReplyAddress* addr, char* msg, int size); bool operator==(const ReplyAddress& a, const ReplyAddress& b); bool operator<(const ReplyAddress& a, const ReplyAddress& b); inline void SendReply(struct ReplyAddress* inReplyAddr, char* inBuf, int inSize) { (inReplyAddr->mReplyFunc)(inReplyAddr, inBuf, inSize); }
1,524
C++
.h
35
39.657143
82
0.754065
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,128
SC_Lock.h
supercollider_supercollider/common/SC_Lock.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include <chrono> #include <condition_variable> #include <mutex> #include <thread> #ifdef __COBALT__ # include <XenomaiLock.h> using SC_Lock = XenomaiMutex; using condition_variable_any = XenomaiConditionVariable; #else // __COBALT__ using SC_Lock = std::mutex; using condition_variable_any = std::condition_variable_any; #endif // __COBALT__ using SC_Thread = std::thread; using std::cv_status; using std::lock_guard; using std::timed_mutex; using std::unique_lock; using mutex = SC_Lock;
1,383
C++
.h
35
36.714286
81
0.759135
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,129
SC_SndFileHelpers.hpp
supercollider_supercollider/common/SC_SndFileHelpers.hpp
// sndfile helper functions // // Copyright (c) 2002 James McCartney. All rights reserved. // Copyright (C) 2012 Tim Blechmann // Copyright (C) 2017 Brian Heim // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once #include "SC_Errors.h" #ifndef NO_LIBSNDFILE // on Windows, enable Windows libsndfile prototypes in order to access sf_wchar_open. // See sndfile.h, lines 739-752. Note that order matters: this has to be the first include of sndfile.h # ifdef _WIN32 # include "SC_Codecvt.hpp" // utf8_cstr_to_utf16_wstring # include <windows.h> # define ENABLE_SNDFILE_WINDOWS_PROTOTYPES 1 # endif // _WIN32 # include <sndfile.h> # include <sndfile.hh> # include "string.h" # include <boost/algorithm/string/predicate.hpp> // iequals using boost::iequals; static inline int headerFormatFromString(const char* name) { if (!name) return SF_FORMAT_AIFF; if (iequals(name, "AIFF")) return SF_FORMAT_AIFF; if (iequals(name, "AIFC")) return SF_FORMAT_AIFF; if (iequals(name, "RIFF")) return SF_FORMAT_WAV; if (iequals(name, "WAVEX")) return SF_FORMAT_WAVEX; if (iequals(name, "WAVE")) return SF_FORMAT_WAV; if (iequals(name, "WAV")) return SF_FORMAT_WAV; if (iequals(name, "Sun")) return SF_FORMAT_AU; if (iequals(name, "IRCAM")) return SF_FORMAT_IRCAM; if (iequals(name, "NeXT")) return SF_FORMAT_AU; if (iequals(name, "raw")) return SF_FORMAT_RAW; if (iequals(name, "MAT4")) return SF_FORMAT_MAT4; if (iequals(name, "MAT5")) return SF_FORMAT_MAT5; if (iequals(name, "PAF")) return SF_FORMAT_PAF; if (iequals(name, "SVX")) return SF_FORMAT_SVX; if (iequals(name, "NIST")) return SF_FORMAT_NIST; if (iequals(name, "VOC")) return SF_FORMAT_VOC; if (iequals(name, "W64")) return SF_FORMAT_W64; if (iequals(name, "PVF")) return SF_FORMAT_PVF; if (iequals(name, "XI")) return SF_FORMAT_XI; if (iequals(name, "HTK")) return SF_FORMAT_HTK; if (iequals(name, "SDS")) return SF_FORMAT_SDS; if (iequals(name, "AVR")) return SF_FORMAT_AVR; if (iequals(name, "SD2")) return SF_FORMAT_SD2; if (iequals(name, "FLAC")) return SF_FORMAT_FLAC; # if defined(SNDFILE_HAS_VORBIS) || defined(SNDFILE_HAS_OPUS) if (iequals(name, "OGG")) return SF_FORMAT_OGG; # endif if (iequals(name, "CAF")) return SF_FORMAT_CAF; if (iequals(name, "RF64")) return SF_FORMAT_RF64; # ifdef SNDFILE_HAS_MPEG if (iequals(name, "MPEG")) return SF_FORMAT_MPEG; # endif return 0; } static inline int sampleFormatFromString(const char* name) { if (!name) return SF_FORMAT_PCM_16; size_t len = strlen(name); if (len < 1) return 0; if (iequals(name, "uint8")) { return SF_FORMAT_PCM_U8; // uint8 } else if (iequals(name, "int8")) { return SF_FORMAT_PCM_S8; // int8 } else if (iequals(name, "int16")) { return SF_FORMAT_PCM_16; // int16 } else if (iequals(name, "int24")) { return SF_FORMAT_PCM_24; // int24 } else if (iequals(name, "int32")) { return SF_FORMAT_PCM_32; // int32 } else if (iequals(name, "float")) { return SF_FORMAT_FLOAT; // float } else if (iequals(name, "double")) { return SF_FORMAT_DOUBLE; // double } else if (iequals(name, "mulaw") || iequals(name, "ulaw")) { return SF_FORMAT_ULAW; // mulaw ulaw } else if (iequals(name, "alaw")) { return SF_FORMAT_ALAW; // alaw } # ifdef SNDFILE_HAS_VORBIS if (iequals(name, "vorbis")) { return SF_FORMAT_VORBIS; // vorbis } # endif # ifdef SNDFILE_HAS_OPUS if (iequals(name, "opus")) { return SF_FORMAT_OPUS; // opus } # endif # ifdef SNDFILE_HAS_MPEG if (iequals(name, "mp1")) { return SF_FORMAT_MPEG_LAYER_I; // mpeg 1 layer 1 } else if (iequals(name, "mp2")) { return SF_FORMAT_MPEG_LAYER_II; // mpeg 1 layer 2 } else if (iequals(name, "mp3")) { return SF_FORMAT_MPEG_LAYER_III; // mpeg 2 layer 3 (mp3) } # endif return 0; } static inline int sndfileFormatInfoFromStrings(struct SF_INFO* info, const char* headerFormatString, const char* sampleFormatString) { int headerFormat = headerFormatFromString(headerFormatString); if (!headerFormat) return kSCErr_Failed; int sampleFormat = sampleFormatFromString(sampleFormatString); if (!sampleFormat) return kSCErr_Failed; info->format = (unsigned int)(headerFormat | sampleFormat); return kSCErr_None; } // ------------------------------ platform-specific functions ------------------------------ # ifdef _WIN32 inline SNDFILE* sndfileOpen(LPCWSTR wpath, int mode, SF_INFO* sfinfo) { return sf_wchar_open(wpath, mode, sfinfo); } // This safely opens a sound file using a raw cstring on any platform inline SNDFILE* sndfileOpenFromCStr(const char* path, int mode, SF_INFO* sfinfo) { // convert to wchar first const std::wstring path_w = SC_Codecvt::utf8_cstr_to_utf16_wstring(path); return sndfileOpen(path_w.c_str(), mode, sfinfo); } // Safely creates a handle using a raw cstring on any platform inline SndfileHandle makeSndfileHandle(const char* path, int mode = SFM_READ, int format = 0, int channels = 0, int samplerate = 0) { const std::wstring path_w = SC_Codecvt::utf8_cstr_to_utf16_wstring(path); return SndfileHandle(path_w.c_str(), mode, format, channels, samplerate); } # else // not _WIN32 inline SNDFILE* sndfileOpen(const char* path, int mode, SF_INFO* sfinfo) { return sf_open(path, mode, sfinfo); } // simple forward inline SNDFILE* sndfileOpenFromCStr(const char* path, int mode, SF_INFO* sfinfo) { return sndfileOpen(path, mode, sfinfo); } // simple forward inline SndfileHandle makeSndfileHandle(const char* path, int mode = SFM_READ, int format = 0, int channels = 0, int samplerate = 0) { return SndfileHandle(path, mode, format, channels, samplerate); } # endif // _WIN32 #else // not NO_LIBSNDFILE static inline int sndfileFormatInfoFromStrings(struct SF_INFO* info, const char* headerFormatString, const char* sampleFormatString) { return kSCErr_Failed; } #endif /* NO_LIBSNDFILE */
7,296
C++
.h
190
32.989474
116
0.642373
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
34,130
MsgFifo.h
supercollider_supercollider/common/MsgFifo.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com Copyright (c) 2013 Tim Blechmann This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include <atomic> ///////////////////////////////////////////////////////////////////// namespace SCMsgFifo { using std::memory_order_relaxed; using std::memory_order_release; template <class MsgType, int N> class MsgFifo { public: MsgFifo(): mReadHead(0), mWriteHead(0), mFreeHead(0) {} void MakeEmpty() { int writeHead = mWriteHead.load(); mReadHead.store(writeHead, memory_order_relaxed); mFreeHead.store(writeHead, memory_order_release); } bool IsEmpty() { return mReadHead.load(memory_order_relaxed) == mWriteHead.load(memory_order_relaxed); } bool HasData() { return mReadHead.load(memory_order_relaxed) != mWriteHead.load(memory_order_relaxed); } bool NeedsFree() { return mFreeHead.load(memory_order_relaxed) != mReadHead.load(memory_order_relaxed); } bool Write(MsgType& data) { unsigned int next = NextPos(mWriteHead.load(memory_order_relaxed)); if (next == mFreeHead.load(memory_order_relaxed)) return false; // fifo is full mItems[next] = data; mWriteHead.store(next, memory_order_release); return true; } void Perform() // get next and advance { while (HasData()) { unsigned int next = NextPos(mReadHead.load(memory_order_relaxed)); mItems[next].Perform(); mReadHead.store(next, memory_order_release); } } void Free() // reclaim messages { while (NeedsFree()) { unsigned int next = NextPos(mFreeHead.load(memory_order_relaxed)); mItems[next].Free(); mFreeHead.store(next, memory_order_release); } } private: int NextPos(int inPos) { return (inPos + 1) & (N - 1); } std::atomic<int> mReadHead, mWriteHead, mFreeHead; MsgType mItems[N]; }; ///////////////////////////////////////////////////////////////////// template <class MsgType, int N> class MsgFifoNoFree { public: MsgFifoNoFree(): mReadHead(0), mWriteHead(0) {} void MakeEmpty() { mReadHead.store(mWriteHead.load()); } bool IsEmpty() { return mReadHead.load(memory_order_relaxed) == mWriteHead.load(memory_order_relaxed); } bool HasData() { return mReadHead.load(memory_order_relaxed) != mWriteHead.load(memory_order_relaxed); } bool Write(MsgType& data) { unsigned int next = NextPos(mWriteHead.load(memory_order_relaxed)); if (next == mReadHead.load(memory_order_relaxed)) return false; // fifo is full mItems[next] = data; mWriteHead.store(next, memory_order_release); return true; } void Perform() // get next and advance { while (HasData()) { unsigned int next = NextPos(mReadHead.load(memory_order_relaxed)); mItems[next].Perform(); mReadHead.store(next, memory_order_release); } } private: int NextPos(int inPos) { return (inPos + 1) & (N - 1); } std::atomic<int> mReadHead, mWriteHead; MsgType mItems[N]; }; } using SCMsgFifo::MsgFifo; using SCMsgFifo::MsgFifoNoFree; /////////////////////////////////////////////////////////////////////
4,064
C++
.h
95
36.631579
109
0.643655
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,131
SC_SynthDef.h
supercollider_supercollider/server/scsynth/SC_SynthDef.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "SC_Types.h" #include "sc_msg_iter.h" typedef void (*NodeDtorFunc)(struct Node* inNode); // Node definition names can be 255 characters long. const unsigned int kSCNodeDefNameLen = 64; const unsigned int kSCNodeDefNameByteLen = 64 * sizeof(int32); struct NodeDef { int32 mName[kSCNodeDefNameLen]; int32 mHash; size_t mAllocSize; }; typedef struct NodeDef NodeDef; extern NodeDef gGroupNodeDef; void GroupNodeDef_Init(); void NodeDef_Dump(NodeDef* inNodeDef);
1,374
C++
.h
32
39.46875
81
0.770098
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,132
Rendezvous.h
supercollider_supercollider/server/scsynth/Rendezvous.h
/* * Rendezvous.h * SC3synth * * Created by C. Ramakrishnan on Wed Dec 18 2002. * Illposed Software * */ /* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once typedef enum { kSCRendezvous_UDP, kSCRendezvous_TCP } SCRendezvousProtocol; void PublishPortToRendezvous(SCRendezvousProtocol protocol, short portNum);
1,158
C++
.h
27
39.296296
81
0.765125
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,133
PriorityQueue.h
supercollider_supercollider/server/scsynth/PriorityQueue.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include <stdio.h> #include <math.h> #include <limits> #define SANITYCHECK 0 const int64 kMaxInt64 = std::numeric_limits<int64>::max(); template <class Event, int N> class PriorityQueueT { public: PriorityQueueT() { Empty(); } bool Add(Event& inEvent) { if (mSize >= N) return false; inEvent.mStabilityCount = mStabilityCounter++; long mom = mSize++; long me = mom; for (; mom > 0;) { /* percolate up heap */ mom = (mom - 1) >> 1; if (inEvent.key() < mEvents[mom].key()) { mEvents[me] = mEvents[mom]; me = mom; } else break; } mEvents[me] = inEvent; #if SANITYCHECK SanityCheck(); #endif return true; } void Perform(int64 inTime) { while (NextTime() <= inTime) { Event event = Remove(); event.Perform(); } } int64 NextTime() { return mEvents[0].mTime; } bool Ready(int64 inTime) { return NextTime() <= inTime; } void Flush() { Perform(kMaxInt64); } void Empty() { mSize = 0; SetEmptyTime(); } void SetEmptyTime() { mEvents[0].mTime = kMaxInt64; mStabilityCounter = 0; } int Size() { return mSize; } Event Remove() { Event event = mEvents[0]; if (--mSize == 0) SetEmptyTime(); else { Event temp = mEvents[mSize]; long mom = 0; long me = 1; for (; me < mSize;) { /* demote heap */ if (me + 1 < mSize && mEvents[me].key() > mEvents[me + 1].key()) { me++; } if (temp.key() > mEvents[me].key()) { mEvents[mom] = mEvents[me]; mom = me; me = (me << 1) + 1; } else break; } mEvents[mom] = temp; } #if SANITYCHECK SanityCheck(); #endif return event; } void SanityCheck() { for (int i = 0; i < mSize; ++i) { // int j = (i<<1)+1; // if (j<mSize && mEvents[i].mTime > mEvents[j].mTime) throw std::runtime_error("priority queue unsorted"); // if (k<mSize && mEvents[i].mTime > mEvents[k].mTime) throw std::runtime_error("priority queue unsorted"); } } void DebugDump() { for (int i = 0; i < mSize; ++i) { printf("%d %016llX\n", i, mEvents[i].mTime); } } private: int mSize; Event mEvents[N]; int64 mStabilityCounter; };
3,509
C++
.h
106
24.792453
119
0.556375
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,134
ReadWriteMacros.h
supercollider_supercollider/server/scsynth/ReadWriteMacros.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "SC_Types.h" #include <stdio.h> #include <string.h> #include <stdexcept> inline int32 readInt8(FILE* file) { int32 res = fgetc(file); return res; } inline uint32 readUInt8(FILE* file) { uint8 res = (uint8)fgetc(file); return (uint32)res; } inline int32 readInt16_be(FILE* file) { int32 c = fgetc(file); int32 d = fgetc(file); int32 res = ((c & 255) << 8) | (d & 255); return res; } inline int32 readInt32_be(FILE* file) { int32 a = fgetc(file); int32 b = fgetc(file); int32 c = fgetc(file); int32 d = fgetc(file); int32 res = ((a & 255) << 24) | ((b & 255) << 16) | ((c & 255) << 8) | (d & 255); return res; } inline float readFloat_be(FILE* file) { union { float f; int32 i; } u; u.i = readInt32_be(file); // post("readFloat %g\n", u.f); return u.f; } inline void readData(FILE* file, char* outData, size_t inLength) { size_t read = fread(outData, 1, inLength, file); if (read != inLength) throw std::runtime_error("readData: read != inLength"); } inline int32 readInt8(char*& buf) { int32 res = *buf++; return res; } inline uint32 readUInt8(char*& buf) { uint8 res = (uint8)*buf++; return (uint32)res; } inline int32 readInt16_be(char*& buf) { int32 c = readInt8(buf); int32 d = readInt8(buf); int32 res = ((c & 255) << 8) | (d & 255); return res; } inline int32 readInt32_be(char*& buf) { int32 a = readInt8(buf); int32 b = readInt8(buf); int32 c = readInt8(buf); int32 d = readInt8(buf); int32 res = ((a & 255) << 24) | ((b & 255) << 16) | ((c & 255) << 8) | (d & 255); return res; } inline float readFloat_be(char*& buf) { union { float f; int32 i; } u; u.i = readInt32_be(buf); // post("readFloat %g\n", u.f); return u.f; } inline void readData(char*& buf, char* outData, size_t inLength) { memcpy(outData, buf, inLength); buf += inLength; }
2,871
C++
.h
92
27.086957
85
0.645501
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,135
SC_Lib_Cintf.h
supercollider_supercollider/server/scsynth/SC_Lib_Cintf.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "SC_Lib.h" #include "SC_Reply.h" #include "SC_OSC_Commands.h" typedef SCErr (*SC_CommandFunc)(struct World* inWorld, int inSize, char* inData, ReplyAddress* inReply); class SC_LibCmd : public SC_NamedObj { public: SC_LibCmd(SC_CommandFunc inFunc); SCErr Perform(struct World* inWorld, int inSize, char* inData, ReplyAddress* inReply); private: SC_CommandFunc mFunc; }; extern Malloc gMalloc; extern HashTable<class SC_LibCmd, Malloc>* gCmdLib; void initialize_library(const char* mUGensPluginPath); void deinitialize_library(); SCErr NewCommand(const char* inPath, uint32 inCommandNumber, SC_CommandFunc inFunc); extern SC_LibCmd* gCmdArray[NUMBER_OF_COMMANDS];
1,579
C++
.h
34
43.058824
104
0.77154
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,136
SC_Prototypes.h
supercollider_supercollider/server/scsynth/SC_Prototypes.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include <ctype.h> // for size_t #include <cstdlib> #include <cstring> #include "SC_Types.h" #include "scsynthsend.h" //////////////////////////////////////////////////////////////////////// // replacement for calloc. // calloc lazily zeroes memory on first touch. This is good for most purposes, but bad for realtime audio. void* zalloc(size_t n, size_t size); void zfree(void* ptr); //////////////////////////////////////////////////////////////////////// void World_Run(struct World* inWorld); void World_Start(World* inWorld); void World_SetSampleRate(struct World* inWorld, double inSampleRate); extern "C" { void* World_Alloc(struct World* inWorld, size_t inByteSize); void* World_Realloc(struct World* inWorld, void* inPtr, size_t inByteSize); void World_Free(struct World* inWorld, void* inPtr); void World_NRTLock(World* world); void World_NRTUnlock(World* world); } size_t World_TotalFree(struct World* inWorld); size_t World_LargestFreeChunk(struct World* inWorld); int32 GetKey(struct Node* inNode); int32 GetHash(struct Node* inNode); bool World_AddNode(struct World* inWorld, struct Node* inNode); bool World_RemoveNode(struct World* inWorld, struct Node* inNode); extern "C" { struct Node* World_GetNode(struct World* inWorld, int32 inID); struct Graph* World_GetGraph(struct World* inWorld, int32 inID); } struct Group* World_GetGroup(struct World* inWorld, int32 inID); int32* GetKey(struct UnitDef* inUnitDef); int32 GetHash(struct UnitDef* inUnitDef); bool AddUnitDef(struct UnitDef* inUnitDef); bool RemoveUnitDef(struct UnitDef* inUnitDef); struct UnitDef* GetUnitDef(int32* inKey); int32* GetKey(struct BufGen* inBufGen); int32 GetHash(struct BufGen* inBufGen); bool AddBufGen(struct BufGen* inBufGen); bool RemoveBufGen(struct BufGen* inBufGen); struct BufGen* GetBufGen(int32* inKey); int32* GetKey(struct PlugInCmd* inPlugInCmd); int32 GetHash(struct PlugInCmd* inPlugInCmd); bool AddPlugInCmd(struct PlugInCmd* inPlugInCmd); bool RemovePlugInCmd(struct PlugInCmd* inPlugInCmd); struct PlugInCmd* GetPlugInCmd(int32* inKey); int PlugIn_DoCmd(struct World* inWorld, int inSize, char* inArgs, struct ReplyAddress* inReply); int32* GetKey(struct GraphDef* inGraphDef); int32 GetHash(struct GraphDef* inGraphDef); void World_AddGraphDef(struct World* inWorld, struct GraphDef* inGraphDef); void World_RemoveGraphDef(struct World* inWorld, struct GraphDef* inGraphDef); struct GraphDef* World_GetGraphDef(struct World* inWorld, int32* inKey); void World_FreeAllGraphDefs(World* inWorld); void GraphDef_Free(GraphDef* inGraphDef); void GraphDef_Define(World* inWorld, GraphDef* inList); void GraphDef_FreeOverwritten(World* inWorld); SCErr bufAlloc(struct SndBuf* buf, int numChannels, int numFrames, double sampleRate); //////////////////////////////////////////////////////////////////////// void Rate_Init(struct Rate* inRate, double inSampleRate, int inBufLength); //////////////////////////////////////////////////////////////////////// #define GRAPHDEF(inGraph) ((GraphDef*)((inGraph)->mNode.mDef)) #define GRAPH_PARAM_TABLE(inGraph) (GRAPHDEF(inGraph)->mParamSpecTable) int Graph_New(struct World* inWorld, struct GraphDef* def, int32 inID, struct sc_msg_iter* args, struct Graph** outGraph, bool argtype = true); void Graph_Ctor(struct World* inWorld, struct GraphDef* inGraphDef, struct Graph* graph, struct sc_msg_iter* msg, bool argtype); void Graph_Dtor(struct Graph* inGraph); int Graph_GetControl(struct Graph* inGraph, uint32 inIndex, float& outValue); int Graph_GetControl(struct Graph* inGraph, int32 inHash, int32* inName, uint32 inIndex, float& outValue); void Graph_SetControl(struct Graph* inGraph, uint32 inIndex, float inValue); void Graph_SetControl(struct Graph* inGraph, int32 inHash, int32* inName, uint32 inIndex, float inValue); void Graph_MapControl(Graph* inGraph, uint32 inIndex, uint32 inBus); void Graph_MapControl(Graph* inGraph, int32 inHash, int32* inName, uint32 inIndex, uint32 inBus); void Graph_MapAudioControl(Graph* inGraph, uint32 inIndex, uint32 inBus); void Graph_MapAudioControl(Graph* inGraph, int32 inHash, int32* inName, uint32 inIndex, uint32 inBus); void Graph_Trace(Graph* inGraph); //////////////////////////////////////////////////////////////////////// int Node_New(struct World* inWorld, struct NodeDef* def, int32 inID, struct Node** outNode); void Node_Dtor(struct Node* inNode); void Node_Remove(struct Node* s); void Node_RemoveID(Node* inNode); void Node_Delete(struct Node* inNode); void Node_AddAfter(struct Node* s, struct Node* afterThisOne); void Node_AddBefore(struct Node* s, struct Node* beforeThisOne); void Node_Replace(struct Node* s, struct Node* replaceThisOne); void Node_SetControl(Node* inNode, int inIndex, float inValue); void Node_SetControl(Node* inNode, int32 inHash, int32* inName, int inIndex, float inValue); void Node_MapControl(Node* inNode, int inIndex, int inBus); void Node_MapControl(Node* inNode, int32 inHash, int32* inName, int inIndex, int inBus); void Node_MapAudioControl(Node* inNode, int inIndex, int inBus); void Node_MapAudioControl(Node* inNode, int32 inHash, int32* inName, int inIndex, int inBus); void Node_StateMsg(Node* inNode, int inState); void Node_Trace(Node* inNode); void Node_SendReply(Node* inNode, int replyID, const char* cmdName, int numArgs, const float* values); void Node_SendReply(Node* inNode, int replyID, const char* cmdName, float value); extern "C" { void Node_SetRun(Node* inNode, int inRun); void Node_SendTrigger(Node* inNode, int triggerID, float value); void Node_End(struct Node* inNode); void Node_NullCalc(struct Node* inNode); void Unit_DoneAction(int doneAction, struct Unit* unit); } //////////////////////////////////////////////////////////////////////// extern "C" { void Group_Calc(Group* inGroup); void Graph_Calc(struct Graph* inGraph); } int Group_New(World* inWorld, int32 inID, Group** outGroup); void Group_Dtor(Group* inGroup); void Group_DeleteAll(Group* inGroup); void Group_DeepFreeGraphs(Group* inGroup); void Group_AddHead(Group* s, Node* child); void Group_AddTail(Group* s, Node* child); void Group_Insert(Group* s, Node* child, int inIndex); void Group_SetControl(struct Group* inGroup, uint32 inIndex, float inValue); void Group_SetControl(struct Group* inGroup, int32 inHash, int32* inName, uint32 inIndex, float inValue); void Group_MapControl(Group* inGroup, uint32 inIndex, uint32 inBus); void Group_MapControl(Group* inGroup, int32 inHash, int32* inName, uint32 inIndex, uint32 inBus); void Group_MapAudioControl(Group* inGroup, uint32 inIndex, uint32 inBus); void Group_MapAudioControl(Group* inGroup, int32 inHash, int32* inName, uint32 inIndex, uint32 inBus); void Group_Trace(Group* inGroup); void Group_DumpTree(Group* inGroup); void Group_DumpTreeAndControls(Group* inGroup); void Group_CountNodeTags(Group* inGroup, int* count); void Group_CountNodeAndControlTags(Group* inGroup, int* count, int* controlAndDefCount); void Group_QueryTree(Group* inGroup, big_scpacket* packet); void Group_QueryTreeAndControls(Group* inGroup, big_scpacket* packet); //////////////////////////////////////////////////////////////////////// struct Unit* Unit_New(struct World* inWorld, struct UnitSpec* inUnitSpec, char*& memory); void Unit_EndCalc(struct Unit* inUnit, int inNumSamples); void Unit_End(struct Unit* inUnit); void Unit_Dtor(struct Unit* inUnit); extern "C" { void Unit_ZeroOutputs(struct Unit* inUnit, int inNumSamples); } //////////////////////////////////////////////////////////////////////// void SendDone(struct ReplyAddress* inReply, const char* inCommandName); void SendDoneWithIntValue(struct ReplyAddress* inReply, const char* inCommandName, int value); void SendDoneWithVarArgs(struct ReplyAddress* inReply, const char* inCommandName, const char* oscFormat, ...); void SendFailure(struct ReplyAddress* inReply, const char* inCommandName, const char* errString); void SendFailureWithIntValue(struct ReplyAddress* inReply, const char* inCommandName, const char* errString, uint32 index); void SendFailureWithVarArgs(struct ReplyAddress* inReply, const char* inCommandName, const char* errString, const char* oscFormat, ...); void ReportLateness(struct ReplyAddress* inReply, float32 seconds); int32 Hash(struct ReplyAddress* inReplyAddress); //////////////////////////////////////////////////////////////////////// extern "C" { int32 server_timeseed(); } //////////////////////////////////////////////////////////////////////// typedef bool (*AsyncStageFn)(World* inWorld, void* cmdData); typedef void (*AsyncFreeFn)(World* inWorld, void* cmdData); int PerformAsynchronousCommand( World* inWorld, void* replyAddr, const char* cmdName, void* cmdData, AsyncStageFn stage2, // stage2 is non real time AsyncStageFn stage3, // stage3 is real time - completion msg performed if stage3 returns true AsyncStageFn stage4, // stage4 is non real time - sends done if stage4 returns true AsyncFreeFn cleanup, int completionMsgSize, void* completionMsgData); ////////////////////////////////////////////////////////////////////////
10,049
C++
.h
178
54.286517
113
0.721148
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,137
SC_GraphDef.h
supercollider_supercollider/server/scsynth/SC_GraphDef.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "SC_SynthDef.h" #include "HashTable.h" #include <filesystem> struct ParamSpec { int32 mName[kSCNameLen]; int32 mIndex; int32 mHash; int32 mNumChannels; }; typedef HashTable<ParamSpec, Malloc> ParamSpecTable; /** \note Relevant scsynth code: `GraphDef_Read(World *, char*&, GraphDef*, int32)` * \note Relevant supernova code: `sc_synthdef::prepare(void)` */ struct GraphDef { NodeDef mNodeDef; uint32 mNumControls; uint32 mNumAudioControls; uint32 mNumWires; uint32 mNumConstants; uint32 mNumUnitSpecs; uint32 mNumWireBufs; uint32 mNumCalcUnits; float32* mInitialControlValues; float32* mConstants; struct UnitSpec* mUnitSpecs; size_t mWiresAllocSize, mUnitsAllocSize, mCalcUnitsAllocSize; size_t mControlAllocSize, mMapControlsAllocSize, mMapControlRatesAllocSize, mAudioMapBusOffsetSize; uint32 mNumParamSpecs; ParamSpec* mParamSpecs; ParamSpecTable* mParamSpecTable; int mRefCount; struct GraphDef* mNext; struct GraphDef* mOriginal; uint32 mNumVariants; struct GraphDef* mVariants; }; typedef struct GraphDef GraphDef; GraphDef* GraphDef_Recv(World* inWorld, char* buffer, GraphDef* inList); GraphDef* GraphDef_Load(struct World* inWorld, const std::filesystem::path& path, GraphDef* inList); GraphDef* GraphDef_LoadDir(struct World* inWorld, const std::filesystem::path& path, GraphDef* inList); GraphDef* GraphDef_LoadGlob(World* inWorld, const char* pattern, GraphDef* inList); SCErr GraphDef_Remove(World* inWorld, int32* inName); SCErr GraphDef_DeleteMsg(struct World* inWorld, GraphDef* inDef); void GraphDef_Dump(GraphDef* inGraphDef); int32 GetHash(ParamSpec* inParamSpec); int32* GetKey(ParamSpec* inParamSpec);
2,637
C++
.h
63
38.063492
103
0.771127
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,138
SC_TimeDLL.hpp
supercollider_supercollider/server/scsynth/SC_TimeDLL.hpp
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* #include "SC_CoreAudio.h" #include <stdarg.h> #include "SC_Prototypes.h" #include "SC_HiddenWorld.h" #include "SC_WorldOptions.h" #include <stdlib.h> #ifdef _WIN32 #include "SC_Win32Utils.h" #else #include <sys/time.h> #endif */ // ===================================================================== // SC_TimeDLL // // Delay-Locked-Loop after // Fons Adriaensen, "Using a DLL to filter time" #ifndef M_PI # define M_PI 3.14159265358979323846 #endif #define SC_TIME_DLL_BW 0.012 class SC_TimeDLL { public: SC_TimeDLL(): m_b(0.), m_c(0.), m_t0(0.), m_t1(0.), m_e2(0.), m_np(0), m_ei(0.), m_ec(0) {} void Reset(double sampleRate, uint32_t periodFrames, double bandWidth, double t) { // compute coefficients m_np = periodFrames; m_b = 2 * M_PI * bandWidth * m_np / sampleRate; m_c = m_b * m_b / 2.; // initialize filter double tp = m_np / sampleRate; m_e2 = tp; m_t0 = t; m_t1 = t + tp; // initialize statistics m_ei = 0.; m_ec = 0; } void Update(double t) { // compute error double e = m_e = t - m_t1; // update filter m_t0 = m_t1; m_t1 += m_b * e + m_e2; m_e2 += m_c * e; // collect statistics m_ei += e; m_ec++; } double PeriodTime() const { return m_t0; } double NextPeriodTime() const { return m_t1; } double Period() const { return m_t1 - m_t0; } double SampleRate() const { return m_np / Period(); } double Error() const { return m_e; } double AvgError() const { return m_ec > 0 ? m_ei / m_ec : 0; } private: double m_b, m_c; double m_t0, m_t1, m_e, m_e2; int m_np; double m_ei; int m_ec; };
2,620
C++
.h
79
28.392405
95
0.615962
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,139
OSC_Packet.h
supercollider_supercollider/server/scsynth/OSC_Packet.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* * OSC_Packet.h * SC3synth * * Created by James McCartney on Sat Aug 24 2002. * Copyright (c) 2001 __MyCompanyName__. All rights reserved. * */ #pragma once #include "SC_ReplyImpl.hpp" #include "SC_Types.h" struct OSC_Packet { char* mData; int32 mSize; bool mIsBundle; ReplyAddress mReplyAddr; };
1,203
C++
.h
33
32.848485
81
0.742046
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,140
SC_Str4.h
supercollider_supercollider/server/scsynth/SC_Str4.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* a 4 byte aligned and zero padded string allows faster string operations. */ #pragma once #include "Hash.h" #include <stdio.h> #include <limits.h> void str4cpy(int32* dst, const char* src); void mem4cpy(int32* dst, const char* src, int charlen); // returns the number of pad bytes to add to a string of a given length inline int str4padbytes(int charlen) { return 4 - (charlen & 3); } // converts length in bytes to length in words inline int str4len(int charlen) { return (charlen + 4) >> 2; } // returns length in words of a char * inline int str4len(const char* src) { const char* src0 = src; while (*src) { src++; } return str4len(src - src0); } // returns length in words of a int32 * inline int str4len(const int32* src) { const int32* src0 = src; while (*src++ & kLASTCHAR) {} int wordlen = src - src0; return wordlen; } // returns length in words of a int32 * inline bool str4eq(const int32* a, const int32* b) { while (true) { if (*a != *b) return false; if ((*a & kLASTCHAR) == 0) return true; a++; b++; } } // copy an int32 * inline void str4cpy(int32* dst, const int32* src) { int32 c; do { *dst++ = c = *src++; } while (c & kLASTCHAR); } inline int sc_atoi(const char* string) { int value = 0; if (*string == 0) return -1; uint32 c; while ((c = *string++ - '0') <= 9) { value = value * 10 + c; } return value; }
2,376
C++
.h
70
29.6
81
0.664921
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,142
SC_CoreAudio.h
supercollider_supercollider/server/scsynth/SC_CoreAudio.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "MsgFifo.h" #include "SC_FifoMsg.h" #include "OSC_Packet.h" #include "SC_SyncCondition.h" #include "PriorityQueue.h" #include <boost/optional.hpp> #include <SC_Lock.h> #define SC_AUDIO_API_COREAUDIO 1 #define SC_AUDIO_API_JACK 2 #define SC_AUDIO_API_PORTAUDIO 3 #define SC_AUDIO_API_AUDIOUNITS 4 #define SC_AUDIO_API_COREAUDIOIPHONE 5 #define SC_AUDIO_API_BELA 6 #ifdef SC_IPHONE # define SC_AUDIO_API SC_AUDIO_API_COREAUDIOIPHONE #endif #ifndef SC_AUDIO_API # if defined(_WIN32) # define SC_AUDIO_API SC_AUDIO_API_PORTAUDIO # elif defined(__APPLE__) # define SC_AUDIO_API SC_AUDIO_API_COREAUDIO # else # error SC_AUDIO_API undefined, cannot determine audio backend # endif #endif // SC_AUDIO_API #if SC_AUDIO_API == SC_AUDIO_API_COREAUDIO || SC_AUDIO_API == SC_AUDIO_API_AUDIOUNITS # include <CoreAudio/AudioHardware.h> # include <CoreAudio/HostTime.h> #endif #if SC_AUDIO_API == SC_AUDIO_API_COREAUDIOIPHONE # include <AudioUnit/AudioUnit.h> # include <AudioToolbox/AudioToolbox.h> # include <AudioToolbox/AudioConverter.h> # include <AudioToolbox/AUGraph.h> #endif struct SC_ScheduledEvent { /// Callback function responsible for freeing the OSC packet in the correct thread. typedef void (*PacketFreeFunc)(struct World* world, OSC_Packet* packet); /// Frees an OSC packet in the realtime thread (to be used as a PacketFreeFunc). static void FreeInRT(struct World* world, OSC_Packet* packet); /// Frees an OSC packet in the non-realtime thread (to be used as a PacketFreeFunc). static void FreeInNRT(struct World* world, OSC_Packet* packet); SC_ScheduledEvent(): mTime(0), mPacket(0) {} SC_ScheduledEvent(struct World* inWorld, int64 inTime, OSC_Packet* inPacket, PacketFreeFunc freeFunc): mTime(inTime), mPacket(inPacket), mPacketFreeFunc(freeFunc), mWorld(inWorld) {} int64 Time() { return mTime; } void Perform(); struct key_t { int64 time, stabilityCount; bool operator<(key_t const& rhs) const { if (time < rhs.time) return true; if (time > rhs.time) return false; return stabilityCount < rhs.stabilityCount; } bool operator>(key_t const& rhs) const { if (time > rhs.time) return true; if (time < rhs.time) return false; return stabilityCount > rhs.stabilityCount; } bool operator==(key_t const& rhs) const { return (time == rhs.time) && (stabilityCount == rhs.stabilityCount); } }; key_t key() const { key_t ret; ret.time = mTime; ret.stabilityCount = mStabilityCount; return ret; } int64 mTime; int64 mStabilityCount; OSC_Packet* mPacket; PacketFreeFunc mPacketFreeFunc; struct World* mWorld; }; typedef MsgFifo<FifoMsg, 65536> EngineFifo; // Functions to be implemented by the driver backend extern "C" { int32 server_timeseed(); int64 oscTimeNow(); }; void initializeScheduler(); /** Denotes whether an OSC packet has been performed immediately or has been scheduled for later execution. If the package has been scheduled, memory ownership is transferred from the caller to the scheduler. */ enum PacketStatus { PacketPerformed, PacketScheduled }; /** Perform a completion message in the realtime thread. The return value denotes whether ownership is transferred to the scheduler or not. */ PacketStatus PerformCompletionMsg(World* world, const OSC_Packet& packet); class SC_AudioDriver { protected: int64 mOSCincrement; struct World* mWorld; double mOSCtoSamples; int mSampleTime; float mSafetyClipThreshold; // Common members uint32 mHardwareBufferSize; // bufferSize returned by kAudioDevicePropertyBufferSize EngineFifo mFromEngine, mToEngine; EngineFifo mOscPacketsToEngine; SC_SyncCondition mAudioSync; SC_Thread mThread; bool mRunThreadFlag; uint32 mSafetyOffset; PriorityQueueT<SC_ScheduledEvent, 2048> mScheduler; int mNumSamplesPerCallback; uint32 mPreferredHardwareBufferFrameSize; uint32 mPreferredSampleRate; boost::optional<uint32> mExplicitSampleRate; double mBuffersPerSecond; double mAvgCPU, mPeakCPU; int mPeakCounter, mMaxPeakCounter; double mOSCincrementNumerator; double mStartHostSecs; double mPrevHostSecs; double mStartSampleTime; double mPrevSampleTime; double mSmoothSampleRate; double mSampleRate; // Driver interface methods, implemented by subclasses /** * DriverSetup() should init the driver and write the num of samples per callback * and the sample rate into the two addresses supplied as arguments. * The driver will have access to the "preferred" values of these two args * (mPreferredHardwareBufferFrameSize, mPreferredSampleRate) and ideally should follow them. * This method should open the resources (and return true if successful), but shouldn't * really start the streaming (this is the responsibility of DriverStart()). */ virtual bool DriverSetup(int* outNumSamplesPerCallback, double* outSampleRate) = 0; /** * Start the audio streaming. Return true iff successful. */ virtual bool DriverStart() = 0; /** * Stop the audio streaming. Return true iff successful. */ virtual bool DriverStop() = 0; public: // Common methods SC_AudioDriver(struct World* inWorld); virtual ~SC_AudioDriver(); int64 mOSCbuftime; bool Setup(); bool Start(); bool Stop(); void ClearSched() { mScheduler.Empty(); } void RunNonRealTime(float* in, float* out, int numSamples, int64 oscTime); void RunThread(); int SafetyOffset() const { return mSafetyOffset; } int NumSamplesPerCallback() const { return mNumSamplesPerCallback; } void SetPreferredHardwareBufferFrameSize(int inSize) { mPreferredHardwareBufferFrameSize = inSize; } void SetPreferredSampleRate(int inRate) { mPreferredSampleRate = inRate; } void SetSafetyClipThreshold(float thr) { mSafetyClipThreshold = thr; } bool SendMsgToEngine(FifoMsg& inMsg); // called by NRT thread bool SendMsgFromEngine(FifoMsg& inMsg); bool SendOscPacketMsgToEngine(FifoMsg& inMsg); // called by OSC socket listener threads, protected by mWorld->mDriverLock void AddEvent(SC_ScheduledEvent& event) { mScheduler.Add(event); } double GetAvgCPU() const { return mAvgCPU; } double GetPeakCPU() const { return mPeakCPU; } double GetSampleRate() const { return mSampleRate; } double GetActualSampleRate() const { return mSmoothSampleRate; } }; extern SC_AudioDriver* SC_NewAudioDriver(struct World* inWorld); // the following classes should be split out into separate source files. #if SC_AUDIO_API == SC_AUDIO_API_COREAUDIO || SC_AUDIO_API == SC_AUDIO_API_AUDIOUNITS class SC_CoreAudioDriver : public SC_AudioDriver { AudioBufferList* mInputBufList; AudioDeviceID mInputDevice; AudioDeviceID mOutputDevice; AudioStreamBasicDescription inputStreamDesc; // info about the default device AudioStreamBasicDescription outputStreamDesc; // info about the default device template <bool IsClipping> friend OSStatus appIOProc(AudioDeviceID inDevice, const AudioTimeStamp* inNow, const AudioBufferList* inInputData, const AudioTimeStamp* inInputTime, AudioBufferList* outOutputData, const AudioTimeStamp* inOutputTime, void* defptr); friend OSStatus appIOProcSeparateIn(AudioDeviceID device, const AudioTimeStamp* inNow, const AudioBufferList* inInputData, const AudioTimeStamp* inInputTime, AudioBufferList* outOutputData, const AudioTimeStamp* inOutputTime, void* defptr); bool isClippingEnabled() const { return mSafetyClipThreshold > 0 && mSafetyClipThreshold < INFINITY; } protected: // Driver interface methods virtual bool DriverSetup(int* outNumSamplesPerCallback, double* outSampleRate); virtual bool DriverStart(); virtual bool DriverStop(); AudioDeviceIOProcID mOutputID; AudioDeviceIOProcID mInputID; public: int builtinoutputflag_; SC_CoreAudioDriver(struct World* inWorld); virtual ~SC_CoreAudioDriver(); bool StopStart(); template <bool IsClipping> void Run(const AudioBufferList* inInputData, AudioBufferList* outOutputData, int64 oscTime); bool UseInput() { return mInputDevice != kAudioDeviceUnknown; } bool UseSeparateIO() { return UseInput() && mInputDevice != mOutputDevice; } AudioDeviceID InputDevice() { return mInputDevice; } AudioDeviceID OutputDevice() { return mOutputDevice; } void SetInputBufferList(AudioBufferList* inBufList) { mInputBufList = inBufList; } AudioBufferList* GetInputBufferList() const { return mInputBufList; } }; #endif #if SC_AUDIO_API == SC_AUDIO_API_COREAUDIOIPHONE class SC_iCoreAudioDriver : public SC_AudioDriver { AUGraph graph; AudioStreamBasicDescription inputStreamDesc; // info about the default device AudioStreamBasicDescription outputStreamDesc; // info about the default device protected: // Driver interface methods virtual bool DriverSetup(int* outNumSamplesPerCallback, double* outSampleRate); virtual bool DriverStart(); virtual bool DriverStop(); public: SC_iCoreAudioDriver(struct World* inWorld); virtual ~SC_iCoreAudioDriver(); void Run(const AudioBufferList* inInputData, AudioBufferList* outOutputData, int64 oscTime); AudioBufferList* buflist; AudioBufferList* floatInputList; AudioBufferList* floatOutputList; AudioConverterRef converter_in_to_F32; AudioConverterRef converter_F32_to_out; AudioConverterRef converter_in_to_out; int* converter_buffer; int receivedIn; AudioUnit inputUnit; }; inline SC_AudioDriver* SC_NewAudioDriver(struct World* inWorld) { return new SC_iCoreAudioDriver(inWorld); } #endif // SC_AUDIO_API_COREAUDIOIPHONE
11,071
C++
.h
252
38.527778
120
0.73161
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,143
SC_UnitDef.h
supercollider_supercollider/server/scsynth/SC_UnitDef.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "SC_Types.h" #include "SC_Unit.h" #include "HashTable.h" struct PlugInCmd { int32 mCmdName[kSCNameLen]; int32 mHash; PlugInCmdFunc mFunc; void* mUserData; }; struct UnitCmd { int32 mCmdName[kSCNameLen]; int32 mHash; UnitCmdFunc mFunc; }; struct UnitDef { int32 mUnitDefName[kSCNameLen]; int32 mHash; size_t mAllocSize; UnitCtorFunc mUnitCtorFunc; UnitDtorFunc mUnitDtorFunc; HashTable<UnitCmd, Malloc>* mCmds; uint32 mFlags; }; extern "C" { bool UnitDef_Create(const char* inName, size_t inAllocSize, UnitCtorFunc inCtor, UnitDtorFunc inDtor, uint32 inFlags); bool UnitDef_AddCmd(const char* inUnitDefName, const char* inCmdName, UnitCmdFunc inFunc); bool PlugIn_DefineCmd(const char* inCmdName, PlugInCmdFunc inFunc, void* inUserData); } int Unit_DoCmd(World* inWorld, int inSize, char* inData); inline int32* GetKey(UnitCmd* inCmd) { return inCmd->mCmdName; } inline int32 GetHash(UnitCmd* inCmd) { return inCmd->mHash; }
1,885
C++
.h
48
35.666667
118
0.75932
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,144
SC_Group.h
supercollider_supercollider/server/scsynth/SC_Group.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "SC_Graph.h" struct Group { Node mNode; Node *mHead, *mTail; }; typedef struct Group Group;
1,000
C++
.h
23
39.347826
81
0.754386
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,146
SC_AU.h
supercollider_supercollider/server/scsynth/SC_AU.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #if SC_AUDIO_API == SC_AUDIO_API_AUDIOUNITS # include "SC_CoreAudio.h" # include "SC_Prototypes.h" # include "SC_HiddenWorld.h" # include <CoreAudio/HostTime.h> class SC_AUAudioDriver : public SC_CoreAudioDriver { protected: virtual bool DriverSetup(int* outNumSamplesPerCallback, double* outSampleRate); virtual bool DriverStart(); virtual bool DriverStop(); public: SC_AUAudioDriver(struct World* inWorld); virtual ~SC_AUAudioDriver(); void Callback(const AudioBufferList* in, AudioBufferList* out, AudioTimeStamp* inTimeStamp, UInt32 inFramesToProcess, Float64 sampleRate, int64 oscTime); }; extern "C" { void AUCallback(SC_AUAudioDriver* driver, AudioBufferList* in, AudioBufferList* out, AudioTimeStamp* inTimeStamp, UInt32 inFramesToProcess, Float64 sampleRate, int64 oscTime); } #endif
1,743
C++
.h
37
42.756757
113
0.753538
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,147
SC_WireSpec.h
supercollider_supercollider/server/scsynth/SC_WireSpec.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "SC_Types.h" struct InputSpec { // read from file: int32 mFromUnitIndex; // changed from int16, ver 2 int32 mFromOutputIndex; // changed from int16, ver 2 // computed: int32 mWireIndex; // changed from int16, ver 2 }; typedef struct InputSpec InputSpec; struct OutputSpec { // read from file: int16 mCalcRate; // computed: int32 mWireIndex; // changed from uint16, ver 2 int64 mBufferIndex; uint32 mNumConsumers; }; typedef struct OutputSpec OutputSpec;
1,397
C++
.h
35
35.857143
81
0.745387
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,148
SC_UnitSpec.h
supercollider_supercollider/server/scsynth/SC_UnitSpec.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include <ctype.h> // for size_t #include "SC_Unit.h" struct UnitSpec { struct UnitDef* mUnitDef; int16 mCalcRate; uint32 mNumInputs, mNumOutputs; // changed from uint16, ver 2 int16 mSpecialIndex; struct InputSpec* mInputSpec; struct OutputSpec* mOutputSpec; struct Rate* mRateInfo; size_t mAllocSize; }; typedef struct UnitSpec UnitSpec;
1,262
C++
.h
30
37.9
81
0.754286
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,149
HashTable.h
supercollider_supercollider/server/scsynth/HashTable.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "SC_Types.h" #include "SC_BoundsMacros.h" #include "SC_Str4.h" #include "Hash.h" #include <stddef.h> #include <stdlib.h> #include <string.h> #include <stdexcept> template <class T, class Allocator> class HashTable { Allocator* mPool; int32 mNumItems, mMaxItems, mTableSize, mHashMask; T** mItems; bool mCanResize; public: HashTable(Allocator* inPool, int32 inMaxItems, bool inCanResize = true): mPool(inPool) { mNumItems = 0; mMaxItems = inMaxItems; mTableSize = mMaxItems << 1; mItems = AllocTable(mTableSize); mHashMask = mTableSize - 1; mCanResize = inCanResize; } ~HashTable() { mPool->Free(mItems); } int32 TableSize() const { return mTableSize; } int32 MaxItems() const { return mMaxItems; } int32 NumItems() const { return mNumItems; } T** AllocTable(int inTableSize) { size_t size = inTableSize * sizeof(T*); T** items = static_cast<T**>(mPool->Alloc(size)); if (items == NULL) throw std::runtime_error("FAILURE IN SERVER: HashTable allocation failed: out of memory!\n"); for (int i = 0; i < inTableSize; ++i) { items[i] = 0; } return items; } void MakeEmpty() { for (int i = 0; i < mTableSize; ++i) { mItems[i] = 0; } mNumItems = 0; } void Resize() { int32 newSize = sc_max(mTableSize << 1, 32); int32 oldSize = mTableSize; T** oldItems = mItems; mItems = AllocTable(newSize); mTableSize = newSize; mMaxItems = mTableSize >> 1; mHashMask = mTableSize - 1; mNumItems = 0; for (int i = 0; i < oldSize; ++i) { T* item = oldItems[i]; if (item) Add(item); } mPool->Free(oldItems); // printf("mMaxItems %d mTableSize %d newSize %d\n", mMaxItems, mTableSize, newSize); } bool Add(T* inItem) { // printf("mNumItems %d\n", mNumItems); // printf("mMaxItems %d\n", mMaxItems); // printf("mCanResize %d\n", mCanResize); if (mNumItems >= mMaxItems) { if (!mCanResize) return false; Resize(); } // printf("GetHash(inItem) %d\n", GetHash(inItem)); // printf("GetKey(inItem) %s\n", GetKey(inItem)); int32 index = IndexFor(GetHash(inItem), (int32*)GetKey(inItem)); // printf("index %d\n", index); T* item = mItems[index]; if (item) return item == inItem; mItems[index] = inItem; mNumItems++; return true; } bool Remove(T* inItem) { int32 index = IndexFor(GetHash(inItem), (int32*)GetKey(inItem)); if (mItems[index] != inItem) return false; mItems[index] = 0; FixCollisionsFrom(index); mNumItems--; return true; } bool RemoveKey(int32* inKey) { T* item = Get(inKey); if (!item) return false; return Remove(item); } int32 IndexFor(int32 inHashID, int32* inKey) const { int index = inHashID & mHashMask; for (;;) { T* item = mItems[index]; if (!item) return index; if (GetHash(item) == inHashID && str4eq(inKey, GetKey(item))) return index; index = (index + 1) & mHashMask; } } T* Get(int32* inKey) const { return Get(Hash(inKey), inKey); } T* Get(int32 inHashID, int32* inKey) const { // printf("Get hash %d %s\n", inHashID, inKey); int32 index = IndexFor(inHashID, inKey); // printf("index %d\n", index); return mItems[index]; } bool Includes(T* inItem) const { return Get(GetHash(inItem), GetKey(inItem)) == inItem; } T* AtIndex(int32 inIndex) const { return mItems[inIndex]; } private: void FixCollisionsFrom(int32 inIndex) { int oldIndex = inIndex; for (;;) { oldIndex = (oldIndex + 1) & mHashMask; T* oldItem = mItems[oldIndex]; if (!oldItem) break; int newIndex = IndexFor(GetHash(oldItem), (int32*)GetKey(oldItem)); if (oldIndex != newIndex) { mItems[oldIndex] = mItems[newIndex]; mItems[newIndex] = oldItem; } } } }; template <class T, class Allocator> class IntHashTable { Allocator* mPool; int32 mNumItems, mMaxItems, mTableSize, mHashMask; T** mItems; bool mCanResize; public: IntHashTable(Allocator* inPool, int32 inMaxItems, bool inCanResize = true): mPool(inPool) { mNumItems = 0; mMaxItems = inMaxItems; mTableSize = mMaxItems << 1; mItems = AllocTable(mTableSize); mHashMask = mTableSize - 1; mCanResize = inCanResize; } ~IntHashTable() { mPool->Free(mItems); } int32 TableSize() const { return mTableSize; } int32 MaxItems() const { return mMaxItems; } int32 NumItems() const { return mNumItems; } T** AllocTable(int inTableSize) { size_t size = inTableSize * sizeof(T*); T** items = static_cast<T**>(mPool->Alloc(size)); if (items == NULL) throw std::runtime_error("FAILURE IN SERVER: HashTable allocation failed: out of memory!\n"); for (int i = 0; i < inTableSize; ++i) { items[i] = 0; } return items; } void Resize() { int32 newSize = sc_max(mTableSize << 1, 32); T** oldItems = mItems; mItems = AllocTable(newSize); for (int i = 0; i < mTableSize; ++i) { T* item = oldItems[i]; if (item) Add(item); } mTableSize = newSize; mMaxItems = mTableSize >> 1; mHashMask = mTableSize - 1; mPool->Free(oldItems); // printf("mMaxItems %d mTableSize %d newSize %d\n", mMaxItems, mTableSize, newSize); } bool Add(T* inItem) { // printf("mNumItems %d\n", mNumItems); // printf("mMaxItems %d\n", mMaxItems); // printf("mCanResize %d\n", mCanResize); if (mNumItems >= mMaxItems) { if (!mCanResize) return false; Resize(); } // printf("GetHash(inItem) %d\n", GetHash(inItem)); // printf("GetKey(inItem) %d\n", GetKey(inItem)); int32 index = IndexFor(GetHash(inItem), GetKey(inItem)); // printf("index %d\n", index); T* item = mItems[index]; if (item) return item == inItem; mItems[index] = inItem; mNumItems++; return true; } bool Remove(T* inItem) { int32 index = IndexFor(GetHash(inItem), GetKey(inItem)); // printf("rmv index %d hash %d key %d\n", index, GetHash(inItem), GetKey(inItem)); if (mItems[index] != inItem) return false; mItems[index] = 0; FixCollisionsFrom(index); mNumItems--; return true; } bool RemoveKey(int32 inKey) { T* item = Get(inKey); if (!item) return false; return Remove(item); } int32 IndexFor(int32 inHashID, int32 inKey) const { int index = inHashID & mHashMask; for (;;) { T* item = mItems[index]; if (!item) return index; if (GetHash(item) == inHashID && inKey == GetKey(item)) return index; index = (index + 1) & mHashMask; } } T* Get(int32 inKey) const { // printf("Get key %d\n", inKey); return Get(Hash(inKey), inKey); } T* Get(int32 inHashID, int32 inKey) const { int32 index = IndexFor(inHashID, inKey); // printf("Get index %d hash %d key %d\n", index, inHashID, inKey); return mItems[index]; } bool Includes(T* inItem) const { return Get(GetHash(inItem), GetKey(inItem)) == inItem; } T* AtIndex(int32 inIndex) const { return mItems[inIndex]; } void Dump() { for (int i = 0; i < mTableSize; ++i) { T* item = mItems[i]; if (item) { printf("%4d %4d %08X %08X\n", i, GetKey(item), GetHash(item), item); } } } private: void FixCollisionsFrom(int32 inIndex) { // printf("FixCollisionsFrom %d\n", inIndex); int oldIndex = inIndex; for (;;) { oldIndex = (oldIndex + 1) & mHashMask; T* oldItem = mItems[oldIndex]; if (!oldItem) break; int newIndex = IndexFor(GetHash(oldItem), GetKey(oldItem)); if (oldIndex != newIndex) { // printf("swap %d %d\n", oldIndex, newIndex); mItems[oldIndex] = mItems[newIndex]; mItems[newIndex] = oldItem; } } } }; struct Malloc { void Free(void* ptr) { free(ptr); } void* Alloc(size_t size) { return malloc(size); } };
9,905
C++
.h
278
27.136691
105
0.56952
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,150
SC_Lib.h
supercollider_supercollider/server/scsynth/SC_Lib.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "SC_Errors.h" #include "SC_Types.h" #include "Hash.h" #include "HashTable.h" #include <stdlib.h> #include <string.h> class SC_NamedObj { public: SC_NamedObj(); virtual ~SC_NamedObj(); const int32* Name() const { return mName; } void SetName(const char* inName); void SetName(const int32* inName); private: friend int32 GetHash(const SC_NamedObj* inObj); friend const int32* GetKey(const SC_NamedObj* inObj); int32 mName[kSCNameLen]; int32 mHash; }; inline int32 GetHash(const SC_NamedObj* inObj) { return inObj->mHash; } inline const int32* GetKey(const SC_NamedObj* inObj) { return inObj->mName; }
1,539
C++
.h
38
36.763158
81
0.743452
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,151
SC_SequencedCommand.h
supercollider_supercollider/server/scsynth/SC_SequencedCommand.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* * Having SequencedCommands allows performing actions that might otherwise require * taking a mutex, which is undesirable in a real time thread. * Some commands require several stages of processing at both the real time * and non real time levels. This class does the messaging between levels for you * so that you only need to write the functions. */ #pragma once #include "OSC_Packet.h" #include "SC_World.h" #include "SC_BufGen.h" #include "sc_msg_iter.h" #include "SC_SndFileHelpers.hpp" #include <new> #define CallSequencedCommand(T, inWorld, inSize, inData, inReply) \ void* space = World_Alloc(inWorld, sizeof(T)); \ if (!space) \ return kSCErr_OutOfRealTimeMemory; \ T* cmd = new (space) T(inWorld, inReply); \ if (!cmd) \ return kSCErr_Failed; \ int err = cmd->Init(inData, inSize); \ if (err) { \ cmd->~T(); \ World_Free(inWorld, space); \ return err; \ } \ if (inWorld->mRealTime) \ cmd->CallNextStage(); \ else \ cmd->CallEveryStage(); class SC_SequencedCommand { public: SC_SequencedCommand(World* inWorld, ReplyAddress* inReplyAddress); virtual ~SC_SequencedCommand(); void Delete(); void CallEveryStage(); void CallNextStage(); virtual int Init(char* inData, int inSize); virtual bool Stage1(); // real time virtual bool Stage2(); // non real time virtual bool Stage3(); // real time virtual void Stage4(); // non real time void SendDone(const char* inCommandName); void SendDoneWithIntValue(const char* inCommandName, int value); protected: int mNextStage; ReplyAddress mReplyAddress; World* mWorld; int mMsgSize; char* mMsgData; virtual void CallDestructor() = 0; }; /////////////////////////////////////////////////////////////////////////// class SyncCmd : public SC_SequencedCommand { public: SyncCmd(World* inWorld, ReplyAddress* inReplyAddress); virtual int Init(char* inData, int inSize); virtual bool Stage2(); // non real time virtual bool Stage3(); // real time virtual void Stage4(); // non real time protected: virtual void CallDestructor(); int mID; }; /////////////////////////////////////////////////////////////////////////// class BufGenCmd : public SC_SequencedCommand { public: BufGenCmd(World* inWorld, ReplyAddress* inReplyAddress); virtual ~BufGenCmd(); virtual int Init(char* inData, int inSize); virtual bool Stage2(); // non real time virtual bool Stage3(); // real time virtual void Stage4(); // non real time protected: int mBufIndex; BufGen* mBufGen; sc_msg_iter mMsg; char* mData; int mSize; SndBuf mSndBuf; float* mFreeData; virtual void CallDestructor(); }; /////////////////////////////////////////////////////////////////////////// class BufAllocCmd : public SC_SequencedCommand { public: BufAllocCmd(World* inWorld, ReplyAddress* inReplyAddress); virtual int Init(char* inData, int inSize); virtual bool Stage2(); // non real time virtual bool Stage3(); // real time virtual void Stage4(); // non real time protected: int mBufIndex; SndBuf mSndBuf; int mNumChannels, mNumFrames; float* mFreeData; virtual void CallDestructor(); }; /////////////////////////////////////////////////////////////////////////// class BufFreeCmd : public SC_SequencedCommand { public: BufFreeCmd(World* inWorld, ReplyAddress* inReplyAddress); virtual int Init(char* inData, int inSize); virtual bool Stage2(); // non real time virtual bool Stage3(); // real time virtual void Stage4(); // non real time protected: int mBufIndex; float* mFreeData; virtual void CallDestructor(); }; /////////////////////////////////////////////////////////////////////////// class BufCloseCmd : public SC_SequencedCommand { public: BufCloseCmd(World* inWorld, ReplyAddress* inReplyAddress); virtual int Init(char* inData, int inSize); virtual bool Stage2(); // non real time virtual bool Stage3(); // real time virtual void Stage4(); // non real time protected: int mBufIndex; virtual void CallDestructor(); }; /////////////////////////////////////////////////////////////////////////// class BufZeroCmd : public SC_SequencedCommand { public: BufZeroCmd(World* inWorld, ReplyAddress* inReplyAddress); virtual int Init(char* inData, int inSize); virtual bool Stage2(); // non real time virtual bool Stage3(); // real time virtual void Stage4(); // non real time protected: int mBufIndex; virtual void CallDestructor(); }; /////////////////////////////////////////////////////////////////////////// class BufAllocReadCmd : public SC_SequencedCommand { public: BufAllocReadCmd(World* inWorld, ReplyAddress* inReplyAddress); virtual ~BufAllocReadCmd(); virtual int Init(char* inData, int inSize); virtual bool Stage2(); // non real time virtual bool Stage3(); // real time virtual void Stage4(); // non real time protected: int mBufIndex; float* mFreeData; SndBuf mSndBuf; char* mFilename; int mFileOffset, mNumFrames; virtual void CallDestructor(); }; /////////////////////////////////////////////////////////////////////////// class BufReadCmd : public SC_SequencedCommand { public: BufReadCmd(World* inWorld, ReplyAddress* inReplyAddress); virtual ~BufReadCmd(); virtual int Init(char* inData, int inSize); virtual bool Stage2(); // non real time virtual bool Stage3(); // real time virtual void Stage4(); // non real time protected: int mBufIndex; char* mFilename; int mFileOffset, mNumFrames, mBufOffset; bool mLeaveFileOpen; double mSampleRate; virtual void CallDestructor(); }; /////////////////////////////////////////////////////////////////////////// class SC_BufReadCommand : public SC_SequencedCommand { public: enum { kMaxNumChannels = 32 }; SC_BufReadCommand(World* inWorld, ReplyAddress* inReplyAddress); virtual ~SC_BufReadCommand(); protected: void InitChannels(sc_msg_iter& msg); bool CheckChannels(int inNumChannels); void CopyChannels(float* dst, float* src, size_t srcChannels, size_t numFrames); protected: int mNumChannels; int mChannels[kMaxNumChannels]; }; /////////////////////////////////////////////////////////////////////////// class BufAllocReadChannelCmd : public SC_BufReadCommand { public: BufAllocReadChannelCmd(World* inWorld, ReplyAddress* inReplyAddress); virtual ~BufAllocReadChannelCmd(); virtual int Init(char* inData, int inSize); virtual bool Stage2(); // non real time virtual bool Stage3(); // real time virtual void Stage4(); // non real time protected: int mBufIndex; float* mFreeData; SndBuf mSndBuf; char* mFilename; int mFileOffset, mNumFrames; virtual void CallDestructor(); }; /////////////////////////////////////////////////////////////////////////// class BufReadChannelCmd : public SC_BufReadCommand { public: BufReadChannelCmd(World* inWorld, ReplyAddress* inReplyAddress); virtual ~BufReadChannelCmd(); virtual int Init(char* inData, int inSize); virtual bool Stage2(); // non real time virtual bool Stage3(); // real time virtual void Stage4(); // non real time protected: int mBufIndex; char* mFilename; int mFileOffset, mNumFrames, mBufOffset; bool mLeaveFileOpen; double mSampleRate; virtual void CallDestructor(); }; /////////////////////////////////////////////////////////////////////////// class BufWriteCmd : public SC_SequencedCommand { public: BufWriteCmd(World* inWorld, ReplyAddress* inReplyAddress); virtual ~BufWriteCmd(); virtual int Init(char* inData, int inSize); virtual bool Stage2(); // non real time virtual bool Stage3(); // real time virtual void Stage4(); // non real time protected: int mBufIndex; char* mFilename; #ifndef NO_LIBSNDFILE SF_INFO mFileInfo; #endif int mNumFrames, mBufOffset; bool mLeaveFileOpen; virtual void CallDestructor(); }; /////////////////////////////////////////////////////////////////////////// class AudioQuitCmd : public SC_SequencedCommand { public: AudioQuitCmd(World* inWorld, ReplyAddress* inReplyAddress); virtual bool Stage2(); // non real time virtual bool Stage3(); // real time virtual void Stage4(); // non real time protected: virtual void CallDestructor(); }; /////////////////////////////////////////////////////////////////////////// class AudioStatusCmd : public SC_SequencedCommand { public: AudioStatusCmd(World* inWorld, ReplyAddress* inReplyAddress); virtual bool Stage2(); // non real time protected: virtual void CallDestructor(); }; /////////////////////////////////////////////////////////////////////////// class RTMemStatusCmd : public SC_SequencedCommand { public: RTMemStatusCmd(World* inWorld, ReplyAddress* inReplyAddress); virtual bool Stage2(); // non real time protected: virtual void CallDestructor(); }; /////////////////////////////////////////////////////////////////////////// class NotifyCmd : public SC_SequencedCommand { public: NotifyCmd(World* inWorld, ReplyAddress* inReplyAddress); virtual int Init(char* inData, int inSize); virtual bool Stage2(); // non real time protected: virtual void CallDestructor(); int mOnOff; int mID; }; /////////////////////////////////////////////////////////////////////////// #define CallSendFailureCommand(inWorld, inCmdName, inErrString, inReply) \ void* space = World_Alloc(inWorld, sizeof(SendFailureCmd)); \ if (!space) \ return kSCErr_OutOfRealTimeMemory; \ SendFailureCmd* cmd = new (space) SendFailureCmd(inWorld, inReply); \ if (!cmd) \ return kSCErr_Failed; \ cmd->InitSendFailureCmd(inCmdName, inErrString); \ if (inWorld->mRealTime) \ cmd->CallNextStage(); \ else \ cmd->CallEveryStage(); class SendFailureCmd : public SC_SequencedCommand { public: SendFailureCmd(World* inWorld, ReplyAddress* inReplyAddress); virtual ~SendFailureCmd(); virtual void InitSendFailureCmd(const char* inCmdName, const char* inErrString); virtual bool Stage2(); // non real time protected: char *mCmdName, *mErrString; virtual void CallDestructor(); }; /////////////////////////////////////////////////////////////////////////// #include "SC_GraphDef.h" class LoadSynthDefCmd : public SC_SequencedCommand { public: LoadSynthDefCmd(World* inWorld, ReplyAddress* inReplyAddress); virtual ~LoadSynthDefCmd(); virtual int Init(char* inData, int inSize); virtual bool Stage2(); // non real time virtual bool Stage3(); // real time virtual void Stage4(); // non real time protected: char* mFilename; GraphDef* mDefs; virtual void CallDestructor(); }; /////////////////////////////////////////////////////////////////////////// #include "SC_GraphDef.h" class RecvSynthDefCmd : public SC_SequencedCommand { public: RecvSynthDefCmd(World* inWorld, ReplyAddress* inReplyAddress); virtual ~RecvSynthDefCmd(); virtual int Init(char* inData, int inSize); virtual bool Stage2(); // non real time virtual bool Stage3(); // real time virtual void Stage4(); // non real time protected: char* mBuffer; GraphDef* mDefs; virtual void CallDestructor(); }; /////////////////////////////////////////////////////////////////////////// class LoadSynthDefDirCmd : public SC_SequencedCommand { public: LoadSynthDefDirCmd(World* inWorld, ReplyAddress* inReplyAddress); virtual ~LoadSynthDefDirCmd(); virtual int Init(char* inData, int inSize); virtual bool Stage2(); // non real time virtual bool Stage3(); // real time virtual void Stage4(); // non real time protected: char* mFilename; GraphDef* mDefs; virtual void CallDestructor(); }; /////////////////////////////////////////////////////////////////////////// class SendReplyCmd : public SC_SequencedCommand { public: SendReplyCmd(World* inWorld, ReplyAddress* inReplyAddress); virtual int Init(char* inData, int inSize); virtual bool Stage2(); // non real time protected: virtual void CallDestructor(); }; /////////////////////////////////////////////////////////////////////////// typedef bool (*AsyncStageFn)(World* inWorld, void* cmdData); typedef void (*AsyncFreeFn)(World* inWorld, void* cmdData); class AsyncPlugInCmd : public SC_SequencedCommand { public: AsyncPlugInCmd(World* inWorld, ReplyAddress* inReplyAddress, const char* cmdName, void* cmdData, AsyncStageFn stage2, // stage2 is non real time AsyncStageFn stage3, // stage3 is real time - completion msg performed if stage3 returns true AsyncStageFn stage4, // stage4 is non real time - sends done if stage4 returns true AsyncFreeFn cleanup, int completionMsgSize, void* completionMsgData); virtual ~AsyncPlugInCmd(); virtual bool Stage2(); // non real time virtual bool Stage3(); // real time virtual void Stage4(); // non real time protected: const char* mCmdName; void* mCmdData; AsyncStageFn mStage2, mStage3, mStage4; AsyncFreeFn mCleanup; virtual void CallDestructor(); };
16,708
C++
.h
387
38.943152
120
0.541149
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,152
iscsynthAppDelegate.h
supercollider_supercollider/server/scsynth/iPhone/iscsynthAppDelegate.h
// // iscsynthAppDelegate.h // iscsynth // // Created by Axel Balley on 20/10/08. // Copyright __MyCompanyName__ 2008. All rights reserved. // #import <UIKit/UIKit.h> @interface iscsynthAppDelegate : NSObject <UIApplicationDelegate> { UIWindow* window; IBOutlet UITabBarController* tabBarController; IBOutlet UITableViewController* tableViewController; } @property (nonatomic, retain) IBOutlet UIWindow* window; @end
437
C++
.h
15
27.066667
67
0.77512
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
34,153
iSCSynthController.h
supercollider_supercollider/server/scsynth/iPhone/iSCSynthController.h
// // iSCSynthController.h // iscsynth // // Created by Axel Balley on 21/10/08. // Copyright 2008 __MyCompanyName__. All rights reserved. // #import <UIKit/UIKit.h> #import "FileBrowserViewController.h" #include "SC_World.h" #include "SC_HiddenWorld.h" #include "SC_CoreAudio.h" #include "SC_WorldOptions.h" @interface iSCSynthController : NSObject <UITabBarControllerDelegate> { WorldOptions options; struct World* world; NSTimer* timer; int lastNodeID; IBOutlet UILabel* avgCPULabel; IBOutlet UILabel* peakCPULabel; IBOutlet UILabel* synthsLabel; IBOutlet UILabel* ugensLabel; IBOutlet UISwitch* speakerSwitch; IBOutlet UIButton* freeAllButton; IBOutlet UITextView* logView; IBOutlet UIViewController* logViewController; IBOutlet FileBrowserViewController* synthdefsViewController; } - (IBAction)toggleState:(id)sender; - (IBAction)toggleSpeaker:(id)sender; - (IBAction)triggerFreeAll:(id)sender; - (void)start; - (void)stop; - (void)freeAllNodes; - (void)update:(NSTimer*)timer; - (void)log:(NSString*)string; - (void)selectSynthdef:(NSString*)string; @end
1,126
C++
.h
38
27.026316
71
0.764597
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,154
dsp_thread.hpp
supercollider_supercollider/server/supernova/dsp_thread_queue/dsp_thread.hpp
// dsp thread // Copyright (C) 2007-2015 Tim Blechmann // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once #include <cstdint> #include <iostream> #include <memory> #include <thread> #include <vector> #include <boost/sync/semaphore.hpp> #include "dsp_thread_queue.hpp" #include "malloc_aligned.hpp" #include "nova-tt/mlock.hpp" namespace nova { using std::uint16_t; struct nop_thread_init { nop_thread_init(void) {} template <typename... Args> nop_thread_init(Args const&...) {} void operator()(int thread_index) {} }; #if _POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600 # define SUPERNOVA_USE_PTHREAD #endif /** dsp helper thread * * the dsp helper threads are running with a high real-time priority and are * pinned to a specific cpu */ template <typename runnable, typename thread_init_functor = nop_thread_init, typename Alloc = std::allocator<void*>> class dsp_thread : public thread_init_functor { typedef nova::dsp_queue_interpreter<runnable, Alloc> dsp_queue_interpreter; public: dsp_thread(dsp_queue_interpreter& interpreter, uint16_t index, thread_init_functor const& thread_init = thread_init_functor()): thread_init_functor(thread_init), interpreter(interpreter), index(index) { #ifdef SUPERNOVA_USE_PTHREAD if (stack_size) { stack_ = malloc_aligned<char>(stack_size); if (stack_ == nullptr) throw std::bad_alloc(); // touch stack to avoid page faults for (size_t i = 0; i != stack_size; ++i) stack_[i] = 0; mlock(stack_, stack_size); } #endif } dsp_thread(dsp_thread const&) = delete; dsp_thread& operator=(dsp_thread const&) = delete; ~dsp_thread(void) { #ifdef SUPERNOVA_USE_PTHREAD if (stack_) free_aligned(stack_); #endif } void start() { stop = false; #ifdef SUPERNOVA_USE_PTHREAD pthread_attr_t attr; pthread_attr_init(&attr); int err = pthread_attr_setstack(&attr, stack_, stack_size); if (err) throw std::logic_error("Cannot set stack of DSP helper thread"); err = pthread_create(&thread_id, &attr, run_static, this); if (err) throw std::runtime_error("Cannot create DSP helper thread"); pthread_attr_destroy(&attr); #else thread = std::thread([this] { this->run(); }); #endif } void join() { stop.store(true, std::memory_order_relaxed); wake_thread(); #ifdef SUPERNOVA_USE_PTHREAD void* ret; int err = pthread_join(thread_id, &ret); if (err) printf("Error when joining helper thread\n"); #else thread.join(); #endif } void wake_thread(void) { cycle_sem.post(); } private: /** thread function * */ void run(void) { thread_init_functor::operator()(index); for (;;) { cycle_sem.wait(); if (unlikely(stop.load(std::memory_order_relaxed))) return; interpreter.tick(index); } } static void* run_static(void* arg) { dsp_thread* self = static_cast<dsp_thread*>(arg); self->run(); return nullptr; } private: boost::sync::semaphore cycle_sem; dsp_queue_interpreter& interpreter; std::atomic<bool> stop = { false }; uint16_t index; #ifdef SUPERNOVA_USE_PTHREAD pthread_t thread_id; static const size_t stack_size = 524288; char* stack_ = nullptr; #else std::thread thread; #endif }; /** \brief container for all dsp threads * * - no care is taken, that dsp_thread_pool::run is executed on a valid instance * * */ template <typename runnable, typename thread_init_functor = nop_thread_init, typename Alloc = std::allocator<void*>> class dsp_thread_pool { typedef nova::dsp_queue_interpreter<runnable, Alloc> dsp_queue_interpreter; typedef nova::dsp_thread<runnable, thread_init_functor, Alloc> dsp_thread; public: typedef typename dsp_queue_interpreter::node_count_t node_count_t; typedef typename dsp_queue_interpreter::thread_count_t thread_count_t; typedef std::unique_ptr<dsp_thread_queue<runnable, Alloc>> dsp_thread_queue_ptr; dsp_thread_pool(thread_count_t count, bool yield_if_busy = false, thread_init_functor const& init_functor = thread_init_functor()): interpreter(std::min(count, (thread_count_t)std::thread::hardware_concurrency()), yield_if_busy) { set_dsp_thread_count(interpreter.get_thread_count(), init_functor); } void run(void) { const bool run_tick = interpreter.init_tick(); if (likely(run_tick)) { wake_threads(); interpreter.tick_main(); } } /** reset queue * * don't call, if threads are currently accessing the queue * */ dsp_thread_queue_ptr reset_queue(dsp_thread_queue_ptr&& new_queue) { dsp_thread_queue_ptr ret = interpreter.reset_queue(std::move(new_queue)); return std::move(ret); } dsp_thread_queue_ptr release_queue(void) { return interpreter.release_queue(); } public: /** thread handling */ /* @{ */ void start_threads(void) { for (auto& thread : threads) thread->start(); } void terminate_threads(void) { for (auto& thread : threads) thread->join(); } /* @} */ private: void set_dsp_thread_count(thread_count_t count, thread_init_functor const& init_functor) { for (thread_count_t i = 1; i != count; ++i) threads.emplace_back(new dsp_thread(interpreter, i, init_functor)); } /** wake dsp threads */ void wake_threads(void) { for (thread_count_t i = 0; i != interpreter.get_used_helper_threads(); ++i) threads[i]->wake_thread(); } dsp_queue_interpreter interpreter; std::vector<std::unique_ptr<dsp_thread>> threads; }; } /* namespace nova */
6,711
C++
.h
190
29.615789
116
0.647731
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
34,155
dsp_thread_queue.hpp
supercollider_supercollider/server/supernova/dsp_thread_queue/dsp_thread_queue.hpp
// dsp thread queue // Copyright (C) 2007-2015 Tim Blechmann // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once #include <algorithm> #include <atomic> #include <chrono> #include <cstdint> #include <iostream> #include <memory> #include <thread> #include <vector> #include <cstdio> #include <boost/lockfree/stack.hpp> #include <boost/mpl/if.hpp> #include "nova-tt/pause.hpp" #include "utilities/branch_hints.hpp" #include "utilities/utils.hpp" namespace nova { template <typename runnable, typename Alloc> class dsp_queue_interpreter; /* concept runnable { runnable(const & runnable); operator()(uint threadindex); }; */ /** item of a dsp thread queue * * \tparam Alloc allocator for successor list * */ template <typename runnable, typename Alloc = std::allocator<void*>> class dsp_thread_queue_item : private Alloc { typedef nova::dsp_queue_interpreter<runnable, Alloc> dsp_queue_interpreter; typedef typename Alloc::template rebind<dsp_thread_queue_item>::other new_allocator; public: typedef std::uint_fast16_t activation_limit_t; struct successor_list { struct data_t { uint32_t count; uint32_t size; dsp_thread_queue_item* content[0]; }; typedef typename Alloc::template rebind<data_t>::other array_allocator; /* create instance */ explicit successor_list(uint32_t size = 0) { data = array_allocator().allocate(2 * sizeof(uint32_t) + size * sizeof(dsp_thread_queue_item*)); data->count = 1; data->size = size; } successor_list(successor_list const& rhs): data(rhs.data) { data->count++; } successor_list& operator=(successor_list const& rhs) { if (--data->count == 0) array_allocator().deallocate(data, 2 * sizeof(uint32_t) + data->size * sizeof(dsp_thread_queue_item*)); data = rhs.data; data->count++; return *this; } std::size_t size(void) const { return data->size; } bool empty(void) const { return size() == 0; } dsp_thread_queue_item*& operator[](std::size_t index) { assert(index < size()); return data->content[index]; } dsp_thread_queue_item* const& operator[](std::size_t index) const { assert(index < size()); return data->content[index]; } ~successor_list(void) { if (--data->count == 0) array_allocator().deallocate(data, 2 * sizeof(uint32_t) + data->size * sizeof(dsp_thread_queue_item*)); } data_t* data; }; dsp_thread_queue_item(runnable const& job, successor_list const& successors, activation_limit_t activation_limit): activation_count(0), job(job), successors(successors), activation_limit(activation_limit) {} dsp_thread_queue_item* run(dsp_queue_interpreter& interpreter, std::uint8_t thread_index) { assert(activation_count == 0); job(thread_index); dsp_thread_queue_item* next = update_dependencies(interpreter); reset_activation_count(); return next; } /** called from the run method or once, when dsp queue is initialized */ void reset_activation_count(void) { assert(activation_count == 0); activation_count.store(activation_limit, std::memory_order_release); } runnable const& get_job(void) const { return job; } runnable& get_job(void) { return job; } #ifdef DEBUG_DSP_THREADS void dump_item(void) { using namespace std; printf("\titem %p\n", this); printf("\tactivation limit %d\n", int(activation_limit)); if (!successors.empty()) { printf("\tsuccessors:\n"); for (size_t i = 0; i != successors.size(); ++i) { printf("\t\t%p\n", successors[i]); } } printf("\n"); } #endif private: /** \brief update all successors and possibly mark them as runnable */ dsp_thread_queue_item* update_dependencies(dsp_queue_interpreter& interpreter) { dsp_thread_queue_item* next_item_to_run; std::size_t i = 0; for (;;) { if (i == successors.size()) return nullptr; next_item_to_run = successors[i++]->decrement_activation_count(); if (next_item_to_run) break; // no need to update the next item to run } // push remaining items to scheduler queue while (i != successors.size()) { dsp_thread_queue_item* next = successors[i++]->decrement_activation_count(); if (next) interpreter.mark_as_runnable(next); } return next_item_to_run; } /** \brief decrement activation count and return this, if it drops to zero */ inline dsp_thread_queue_item* decrement_activation_count() { activation_limit_t current = activation_count--; assert(current > 0); if (current == 1) return this; else return nullptr; } std::atomic<activation_limit_t> activation_count; /**< current activation count */ runnable job; const successor_list successors; /**< list of successing nodes */ const activation_limit_t activation_limit; /**< number of precedessors */ }; template <typename T, typename Alloc> class raw_vector : Alloc { public: explicit raw_vector(size_t elements, Alloc const& alloc = Alloc()): Alloc(alloc), capacity_(elements) { data = elements ? Alloc::allocate(capacity_ * sizeof(T)) : nullptr; } template <class... Args> T* emplace_back(Args&&... args) { assert(size() != capacity_); T* element = data + size_; Alloc::construct(element, std::forward<Args>(args)...); size_ += 1; return element; } T& operator[](std::size_t index) { assert(index < size_); return data[index]; } T* begin() { return data; } T* end() { return data + size_; } bool empty() const { return size_ == 0; } size_t size() const { return size_; } size_t capacity() const { return capacity_; } ~raw_vector() { for (std::size_t i = 0; i != size_; ++i) Alloc::destroy(data + i); if (data) Alloc::deallocate(data, capacity_ * sizeof(Alloc)); } private: T* data = nullptr; const size_t capacity_ = 0; size_t size_ = 0; }; template <typename runnable, typename Alloc = std::allocator<void*>> class dsp_thread_queue { typedef std::uint_fast16_t node_count_t; typedef nova::dsp_thread_queue_item<runnable, Alloc> dsp_thread_queue_item; typedef std::vector<dsp_thread_queue_item*, typename Alloc::template rebind<dsp_thread_queue_item*>::other> item_vector_t; typedef typename Alloc::template rebind<dsp_thread_queue_item>::other item_allocator; public: #ifdef DEBUG_DSP_THREADS void dump_queue(void) { using namespace std; printf("queue %p\n items:\n", this); for (std::size_t i = 0; i != total_node_count; ++i) queue_items[i].dump_item(); printf("\ninitial items:\n", this); for (dsp_thread_queue_item* item : initially_runnable_items) item->dump_item(); printf("\n"); std::cout << std::endl; } #endif /** preallocate node_count nodes */ dsp_thread_queue(std::size_t node_count, bool has_parallelism = true): has_parallelism_(has_parallelism), items(node_count) { initially_runnable_items.reserve(node_count); } ~dsp_thread_queue(void) = default; void add_initially_runnable(dsp_thread_queue_item* item) { initially_runnable_items.push_back(item); } /** return initialized queue item */ dsp_thread_queue_item* allocate_queue_item(runnable const& job, typename dsp_thread_queue_item::successor_list const& successors, typename dsp_thread_queue_item::activation_limit_t activation_limit) { return items.emplace_back(job, successors, activation_limit); } void reset_activation_counts(void) { for (dsp_thread_queue_item& item : items) item.reset_activation_count(); } bool empty() const { return items.empty(); } node_count_t total_node_count(void) const { return node_count_t(items.size()); } bool has_parallelism(void) const { return has_parallelism_; } private: item_vector_t initially_runnable_items; /* nodes without precedessor */ const bool has_parallelism_; friend class dsp_queue_interpreter<runnable, Alloc>; raw_vector<dsp_thread_queue_item, item_allocator> items; }; template <typename runnable, typename Alloc = std::allocator<void*>> class dsp_queue_interpreter { protected: typedef nova::dsp_thread_queue<runnable, Alloc> dsp_thread_queue; typedef nova::dsp_thread_queue_item<runnable, Alloc> dsp_thread_queue_item; typedef typename dsp_thread_queue_item::successor_list successor_list; typedef std::size_t size_t; public: typedef boost::uint_fast8_t thread_count_t; typedef boost::uint_fast16_t node_count_t; typedef std::unique_ptr<dsp_thread_queue> dsp_thread_queue_ptr; dsp_queue_interpreter(thread_count_t tc, bool yield_if_busy = false): yield_if_busy(yield_if_busy) { if (!runnable_items.is_lock_free()) std::cout << "Warning: scheduler queue is not lockfree!" << std::endl; calibrate_backoff(10); set_thread_count(tc); } /** prepares queue and queue interpreter for dsp tick * * \return true, if dsp queue is valid * false, if no dsp queue is available or queue is empty */ bool init_tick(void) { if (unlikely(!queue || queue->empty())) return false; /* reset node count */ assert(node_count == 0); assert(runnable_items.empty()); node_count.store(queue->total_node_count(), std::memory_order_release); for (auto* item : queue->initially_runnable_items) mark_as_runnable(item); return true; } dsp_thread_queue_ptr release_queue(void) { dsp_thread_queue_ptr ret(queue.release()); return ret; } dsp_thread_queue_ptr reset_queue(dsp_thread_queue_ptr&& new_queue) { dsp_thread_queue_ptr ret(std::move(queue)); queue = std::move(new_queue); if (queue.get() == nullptr) return ret; queue->reset_activation_counts(); #ifdef DEBUG_DSP_THREADS queue->dump_queue(); #endif if (queue->has_parallelism()) { thread_count_t thread_number = std::min( thread_count_t(std::min(total_node_count(), node_count_t(std::numeric_limits<thread_count_t>::max()))), thread_count); used_helper_threads = thread_number - 1; /* this thread is not waked up */ } else used_helper_threads = 0; return ret; } node_count_t total_node_count(void) const { return queue->total_node_count(); } void set_thread_count(thread_count_t i) { assert(i < std::numeric_limits<thread_count_t>::max()); i = std::max(thread_count_t(1u), i); thread_count = i; } thread_count_t get_thread_count(void) const { return thread_count; } thread_count_t get_used_helper_threads(void) const { return used_helper_threads; } void tick(thread_count_t thread_index) { if (yield_if_busy) run_item<true>(thread_index); else run_item<false>(thread_index); } private: static const int max_backup_loops = 16384; struct backoff { backoff(int min, int max): min(min), max(max), loops(min) {} void run() { for (int i = 0; i != loops; ++i) nova::detail::pause(); loops = std::min(loops * 2, max); } void reset() { loops = min; } const int min, max; int loops; }; struct yield_backoff { yield_backoff(int dummy_min, int dummy_max) {} void run() { std::this_thread::yield(); } void reset() {} }; template <bool YieldBackoff> struct select_backoff { typedef typename boost::mpl::if_c<YieldBackoff, yield_backoff, backoff>::type type; }; void calibrate_backoff(int timeout_in_seconds) { using namespace std; using namespace std::chrono; const int backoff_iterations = 100; vector<nanoseconds> measured_values; generate_n(back_inserter(measured_values), 16, [backoff_iterations] { backoff b(max_backup_loops, max_backup_loops); auto start = high_resolution_clock::now(); for (int i = 0; i != backoff_iterations; ++i) b.run(); auto end = high_resolution_clock::now(); auto diff = duration_cast<nanoseconds>(end - start); return diff; }); std::sort(measured_values.begin(), measured_values.end()); auto median = measured_values[measured_values.size() / 2]; if (median.count() > 0) { watchdog_iterations = (seconds(timeout_in_seconds) / median) * backoff_iterations; } else { std::cout << "WARNING: could not calibrate back off, watchdog disabled." << std::endl; watchdog_iterations = std::numeric_limits<int>::max(); } } template <bool YieldBackoff> void run_item(thread_count_t index) { // note: in future we can avoid the watchdog on osx and linux, as they provide proper // deadline scheduling policies typedef typename select_backoff<YieldBackoff>::type backoff_t; backoff_t b(8, max_backup_loops); int poll_counts = 0; for (;;) { if (!node_count.load(std::memory_order_acquire)) return; /* we still have some nodes to process */ int state = run_next_item(index); switch (state) { case no_remaining_items: return; case fifo_empty: b.run(); ++poll_counts; break; case remaining_items: b.reset(); poll_counts = 0; } if (YieldBackoff) continue; if (poll_counts == watchdog_iterations) { if (index == 0) { std::printf( "nova::dsp_queue_interpreter::run_item: possible lookup detected in main audio thread\n"); abort(); } else { std::printf( "nova::dsp_queue_interpreter::run_item: possible lookup detected in dsp helper thread\n"); return; } } } } public: void tick_main(void) { if (yield_if_busy) run_item_main<true>(); else run_item_main<false>(); } private: template <bool YieldBackoff> void run_item_main(void) { run_item<YieldBackoff>(0); wait_for_end<YieldBackoff>(); assert(runnable_items.empty()); } template <bool YieldBackoff> void wait_for_end(void) { typedef typename select_backoff<YieldBackoff>::type backoff_t; backoff_t b(8, max_backup_loops); const int iterations = watchdog_iterations * 2; int count = 0; while (node_count.load(std::memory_order_acquire) != 0) { b.run(); ++count; if (!YieldBackoff && (count == iterations)) { std::printf("nova::dsp_queue_interpreter::wait_for_end: possible lookup detected\n"); } } // busy-wait for helper threads to finish } HOT int run_next_item(thread_count_t index) { dsp_thread_queue_item* item; bool success = runnable_items.pop(item); if (!success) return fifo_empty; node_count_t consumed = 0; do { item = item->run(*this, index); consumed += 1; } while (item != nullptr); node_count_t remaining = node_count.fetch_sub(consumed, std::memory_order_release); assert(remaining >= consumed); if (remaining == consumed) return no_remaining_items; else return remaining_items; } void mark_as_runnable(dsp_thread_queue_item* item) { runnable_items.push(item); } friend class nova::dsp_thread_queue_item<runnable, Alloc>; private: enum { no_remaining_items, fifo_empty, remaining_items }; dsp_thread_queue_ptr queue; thread_count_t thread_count; /* number of dsp threads to be used by this queue */ thread_count_t used_helper_threads; /* number of helper threads, which are actually used */ boost::lockfree::stack<dsp_thread_queue_item*, boost::lockfree::capacity<32768>> runnable_items; std::atomic<node_count_t> node_count = { 0 }; /* number of nodes, that need to be processed during this tick */ int watchdog_iterations; bool yield_if_busy; }; } /* namespace nova */
17,988
C++
.h
440
32.563636
119
0.611229
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
34,156
sc_synth_definition.hpp
supercollider_supercollider/server/supernova/sc/sc_synth_definition.hpp
// prototype of a supercollider-synthdef-based synth prototype // Copyright (C) 2009 Tim Blechmann // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once #include <filesystem> #include "sc_synthdef.hpp" #include "server/synth_definition.hpp" #include "utilities/sized_array.hpp" namespace nova { using std::filesystem::path; /* read synthdefs from path pattern */ std::vector<sc_synthdef> sc_read_synthdefs_file(path const& filename); std::vector<sc_synthdef> sc_read_synthdefs_dir(path const& dir); class sc_synth_definition : public synth_definition, public sc_synthdef { public: sc_synth_definition(sc_synthdef&& sd); private: friend class sc_synth; virtual abstract_synth* create_instance(int) override; }; typedef boost::intrusive_ptr<sc_synth_definition> sc_synth_definition_ptr; void register_synthdefs(class synth_factory& factory, std::vector<sc_synthdef>&&); } /* namespace nova */
1,632
C++
.h
37
42.432432
82
0.764223
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
34,157
sc_synthdef.hpp
supercollider_supercollider/server/supernova/sc/sc_synthdef.hpp
// supercollider-style synthdef // Copyright (C) 2008-2012 Tim Blechmann // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once #include <cstdint> #include <map> #include <string> #include <vector> #include <filesystem> #include <boost/align/aligned_allocator.hpp> #include "utilities/named_hash_entry.hpp" #include "SC_Types.h" #include "SC_Wire.h" namespace nova { class sc_synthdef { typedef std::vector<float, boost::alignment::aligned_allocator<float, 64>> float_vector; typedef std::vector<char, boost::alignment::aligned_allocator<char, 64>> char_vector; typedef std::map<symbol, int32_t, std::less<symbol>> parameter_index_map_t; public: struct input_spec { input_spec(int32_t source, int32_t index): source(source), index(index) {} bool operator<(input_spec const& rhs) const { if (source < rhs.source) return true; if (source > rhs.source) return false; return index < rhs.index; } int32_t source; /* index of ugen or -1 for constant */ int32_t index; /* number of output or constant index */ }; typedef std::vector<input_spec, boost::alignment::aligned_allocator<input_spec, 64>> input_spec_vector; struct unit_spec_t { explicit unit_spec_t(const char*& buffer, const char* buffer_end, int version); unit_spec_t(symbol const& name, int16_t rate, int16_t special_index, input_spec_vector const& in_specs, char_vector const& out_specs): name(name), rate(rate), special_index(special_index), input_specs(in_specs), output_specs(out_specs) {} unit_spec_t(unit_spec_t&& rhs) = default; unit_spec_t(unit_spec_t const& rhs) = default; unit_spec_t& operator=(unit_spec_t const& rhs) = default; symbol name; int16_t rate; /* 0: scalar rate, 1: buffer rate, 2: full rate, 3: demand rate */ int16_t special_index; input_spec_vector input_specs; char_vector output_specs; /* calculation rates */ std::vector<int32_t, boost::alignment::aligned_allocator<int32_t, 64>> buffer_mapping; std::size_t memory_requirement(void) const { return input_specs.size() * (sizeof(Wire*) + sizeof(float*)) + output_specs.size() * (sizeof(Wire*) + sizeof(float*)) + output_specs.size() * sizeof(Wire); } class sc_ugen_def* prototype; }; friend class sc_synth_definition; friend class sc_synth; friend class sc_ugen_factory; friend class sc_ugen_def; typedef std::vector<unit_spec_t, boost::alignment::aligned_allocator<unit_spec_t, 64>> graph_t; typedef std::vector<int32_t, boost::alignment::aligned_allocator<int32_t, 64>> calc_units_t; sc_synthdef(const char*& buffer, const char* buffer_end, int version); sc_synthdef(sc_synthdef&& rhs) = default; sc_synthdef(sc_synthdef const& rhs) = default; sc_synthdef& operator=(sc_synthdef const& rhs) = default; std::string dump(void) const; symbol const& name(void) const { return name_; } std::size_t parameter_count(void) const { return parameters.size(); } std::size_t unit_count(void) const { return graph.size(); } std::size_t calc_unit_count(void) const { return calc_unit_indices.size(); } std::size_t memory_requirement(void) const { assert(memory_requirement_); return memory_requirement_; } private: void read_synthdef(const char*& data, const char* end, int version); /** assign buffers, collect memory requirement & cache ugen prototype */ void prepare(void); symbol name_; float_vector constants; float_vector parameters; parameter_index_map_t parameter_map; graph_t graph; unsigned int buffer_count; calc_units_t calc_unit_indices; /**< indices of the units, that need to be calculated */ std::size_t memory_requirement_; }; std::vector<sc_synthdef> read_synthdefs(const char* buffer, const char* buffer_end); std::vector<sc_synthdef> read_synthdef_file(std::filesystem::path const& filename); } /* namespace nova */
4,895
C++
.h
105
40.647619
111
0.676619
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
34,158
sc_synth.hpp
supercollider_supercollider/server/supernova/sc/sc_synth.hpp
// synth based on supercollider-style synthdef // Copyright (C) 2009, 2010 Tim Blechmann // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once #include "SC_Unit.h" #include "SC_Graph.h" #include "SC_Rate.h" #include "SC_RGen.h" #include "SC_Wire.h" #include "sc_synth_definition.hpp" #include "../server/synth.hpp" #include "../server/memory_pool.hpp" namespace nova { struct sc_unit_cmd { sc_unit_cmd* next; int size; char data[1]; }; class sc_synth : public abstract_synth, public Graph { typedef std::vector<struct Unit*, rt_pool_allocator<void*>> unit_vector; typedef sc_synthdef::graph_t graph_t; friend class sc_synth_definition; public: sc_synth(int node_id, sc_synth_definition_ptr const& prototype); ~sc_synth(void); /** run ugen constructors and initialize first sample * * to be executed after preparing the synth and setting the controls */ void prepare(void); void finalize(void); HOT inline void perform(void) { if (unlikely(!initialized)) prepare(); if (likely(trace == 0)) { const size_t count = calc_unit_count; Unit** units = calc_units; const size_t preroll = count & 7; for (size_t i = 0; i != preroll; ++i) { Unit* unit = units[i]; prefetch(units[i + 1]); (unit->mCalcFunc)(unit, unit->mBufLength); } units += preroll; const size_t unroll = count / 8; if (unroll == 0) return; for (size_t i = 0; i != unroll; ++i) { Unit* unit = units[0]; prefetch(units[1]); (unit->mCalcFunc)(unit, unit->mBufLength); unit = units[1]; prefetch(units[2]); (unit->mCalcFunc)(unit, unit->mBufLength); unit = units[2]; prefetch(units[3]); (unit->mCalcFunc)(unit, unit->mBufLength); unit = units[3]; prefetch(units[4]); (unit->mCalcFunc)(unit, unit->mBufLength); unit = units[4]; prefetch(units[5]); (unit->mCalcFunc)(unit, unit->mBufLength); unit = units[5]; prefetch(units[6]); (unit->mCalcFunc)(unit, unit->mBufLength); unit = units[6]; prefetch(units[7]); (unit->mCalcFunc)(unit, unit->mBufLength); unit = units[7]; prefetch(units[8]); (unit->mCalcFunc)(unit, unit->mBufLength); units += 8; } } else run_traced(); } void prefetch(Unit* unit) { char* ptr = (char*)unit; char* end = (char*)unit + sizeof(Unit) + 2 * sizeof(Wire) /* + 4 * sizeof(void*)*/; static const size_t cacheline_size = 64; for (; ptr < end; ptr += cacheline_size) { #ifdef __GNUC__ __builtin_prefetch(ptr, 0, 0); #elif defined(_MSC_VER) _mm_prefetch(ptr, 0); #endif } } void run(void) override; void set(slot_index_t slot_index, sample val) override; float get(slot_index_t slot_index) const override; bool getMappedSymbol(slot_index_t slot_index, char* str) const override; void set_control_array(slot_index_t slot_index, size_t count, sample* val) override; sample get(slot_index_t slot_index) { return mControls[slot_index]; } /* @{ */ /** control mapping */ private: void map_control_bus_control(unsigned int slot_index, int control_bus_index); void map_control_buses_control(unsigned int slot_index, int control_bus_index, int count); void map_control_bus_audio(unsigned int slot_index, int audio_bus_index); void map_control_buses_audio(unsigned int slot_index, int audio_bus_index, int count); public: template <bool ControlBusIsAudio> void map_control_bus(unsigned int slot_index, int bus_index) { if (ControlBusIsAudio) map_control_bus_audio(slot_index, bus_index); else map_control_bus_control(slot_index, bus_index); } template <bool ControlBusIsAudio> void map_control_buses(unsigned int slot_index, int bus_index, int count) { if (ControlBusIsAudio) map_control_buses_audio(slot_index, bus_index, count); else map_control_buses_control(slot_index, bus_index, count); } template <bool ControlBusIsAudio> void map_control_bus(const char* slot_name, int bus_index) { int slot_index = resolve_slot(slot_name); if (slot_index == -1) return; map_control_bus<ControlBusIsAudio>(slot_index, bus_index); } template <bool ControlBusIsAudio> void map_control_buses(const char* slot_name, int bus_index, int count) { int controls_per_slot; int slot_index = resolve_slot_with_size(slot_name, controls_per_slot); if (slot_index == -1) return; count = std::min(count, controls_per_slot); map_control_buses<ControlBusIsAudio>(slot_index, bus_index, count); } template <bool ControlBusIsAudio> void map_control_bus(unsigned int slot_index, size_t arrayed_slot_index, int bus_index) { map_control_bus<ControlBusIsAudio>(slot_index + arrayed_slot_index, bus_index); } template <bool ControlBusIsAudio> void map_control_bus(const char* slot_name, size_t arrayed_slot_index, int bus_index) { int slot_base_index = resolve_slot(slot_name); if (slot_base_index == -1) return; size_t slot_index = slot_base_index + arrayed_slot_index; map_control_bus<ControlBusIsAudio>(slot_index, bus_index); } /* @} */ void enable_tracing(void) { trace = 1; } void apply_unit_cmd(const char* unit_cmd, unsigned int unit_index, struct sc_msg_iter* args); private: void run_traced(void); sample get_constant(size_t index) { return static_cast<sc_synth_definition*>(class_ptr.get())->constants[index]; } friend class sc_ugen_def; bool initialized = false; int_fast8_t trace = 0; Unit** calc_units; sample* unit_buffers = nullptr; int32_t calc_unit_count, unit_count; RGen rgen; Unit** units; }; } /* namespace nova */
7,078
C++
.h
171
33.397661
118
0.620152
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
34,159
sc_plugin_interface.hpp
supercollider_supercollider/server/supernova/sc/sc_plugin_interface.hpp
// interface for supercollider plugins // Copyright (C) 2009 Tim Blechmann // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once #include <mutex> #include <vector> #include "../server/audio_bus_manager.hpp" #include "../server/node_types.hpp" #include "../server/synth.hpp" #include "../server/memory_pool.hpp" #include "SC_InterfaceTable.h" #include "SC_World.h" #include <boost/scoped_array.hpp> namespace nova { class sc_done_action_handler { public: void add_pause_node(server_node* node) { spin_lock::scoped_lock lock(cmd_lock); pause_nodes.push_back(node); } void add_resume_node(server_node* node) { spin_lock::scoped_lock lock(cmd_lock); resume_nodes.push_back(node); } void add_done_node(server_node* node) { spin_lock::scoped_lock lock(cmd_lock); if (std::find(done_nodes.begin(), done_nodes.end(), node) != done_nodes.end()) return; done_nodes.push_back(node); } void add_freeDeep_node(abstract_group* node) { spin_lock::scoped_lock lock(cmd_lock); if (std::find(freeDeep_nodes.begin(), freeDeep_nodes.end(), node) != freeDeep_nodes.end()) return; freeDeep_nodes.push_back(node); } void add_freeAll_node(abstract_group* node) { spin_lock::scoped_lock lock(cmd_lock); if (std::find(freeAll_nodes.begin(), freeAll_nodes.end(), node) != freeAll_nodes.end()) return; freeAll_nodes.push_back(node); } void apply_done_actions(void); protected: typedef rt_pool_allocator<server_node*> server_node_alloc; typedef rt_pool_allocator<abstract_group*> abstract_group_alloc; std::vector<server_node*, server_node_alloc> done_nodes, pause_nodes, resume_nodes; std::vector<abstract_group*, abstract_group_alloc> freeAll_nodes, freeDeep_nodes; private: spin_lock cmd_lock; /* multiple synths can be scheduled for removal, so we need to guard this later we can try different approaches like a lockfree stack or bitmask */ }; class sc_plugin_interface : public sc_done_action_handler { public: void initialize(class server_arguments const& args, float* control_busses); void reset_sampling_rate(int sr); sc_plugin_interface(void) = default; ~sc_plugin_interface(void); InterfaceTable sc_interface; World world; audio_bus_manager audio_busses; int buf_counter(void) const { return world.mBufCounter; } /* @{ */ /* audio buffer handling */ SndBuf* allocate_buffer(uint32_t index, uint32_t frames, uint32_t channels); void allocate_buffer(SndBuf* buf, uint32_t frames, uint32_t channels, double samplerate); void buffer_read_alloc(uint32_t index, const char* filename, uint32_t start, uint32_t frames); void buffer_alloc_read_channels(uint32_t index, const char* filename, uint32_t start, uint32_t frames, uint32_t channel_count, const uint32_t* channel_data); void buffer_read(uint32_t index, const char* filename, uint32_t start_file, uint32_t frames, uint32_t start_buffer, bool leave_open); void buffer_read_channel(uint32_t index, const char* filename, uint32_t start_file, uint32_t frames, uint32_t start_buffer, bool leave_open, uint32_t channel_count, const uint32_t* channel_data); sample* get_nrt_mirror_buffer(uint32_t index) { return world.mSndBufsNonRealTimeMirror[index].data; } sample* get_buffer(uint32_t index) { return world.mSndBufs[index].data; } SndBuf* get_buffer_struct(uint32_t index) { return world.mSndBufs + index; } void buffer_write(uint32_t index, const char* filename, const char* header_format, const char* sample_format, uint32_t start, uint32_t frames, bool leave_open); void buffer_zero(uint32_t index); void buffer_close(uint32_t index); sample* buffer_generate(uint32_t index, const char* cmd_name, struct sc_msg_iter& msg); void increment_write_updates(uint32_t index) { world.mSndBufUpdates[index].writes++; } void free_buffer(uint32_t index); typedef std::lock_guard<std::mutex> buffer_lock_t; std::mutex& buffer_guard(size_t index) { return async_buffer_guards[index]; } bool is_realtime_synthesis() const { return world.mRealTime; } private: boost::scoped_array<std::mutex> async_buffer_guards; /* @} */ public: /* copies nrt mirror to rt buffers */ void buffer_sync(uint32_t index) noexcept; /* @{ */ /* control bus handling */ private: void controlbus_set_unchecked(uint32_t bus, float value) { world.mControlBus[bus] = value; world.mControlBusTouched[bus] = world.mBufCounter; } public: void controlbus_set(uint32_t bus, float value) { if (bus < world.mNumControlBusChannels) controlbus_set_unchecked(bus, value); } void controlbus_fill(uint32_t bus, size_t count, float value) { if (bus + count >= world.mNumControlBusChannels) count = world.mNumAudioBusChannels - bus; for (size_t i = 0; i != count; ++i) controlbus_set_unchecked(bus + i, value); } sample controlbus_get(uint32_t bus) { if (bus < world.mNumControlBusChannels) return world.mControlBus[bus]; else return 0.f; } void controlbus_getn(uint32_t bus, size_t count, size_t* r_count, float* r_values) { size_t remain = count; if (bus + count >= world.mNumControlBusChannels) remain = world.mNumAudioBusChannels - bus; *r_count = remain; for (size_t i = 0; i != remain; ++i) r_values[i] = world.mControlBus[i]; } /* @}*/ }; } /* namespace nova */
6,522
C++
.h
142
39.549296
119
0.674716
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,160
sc_ugen_factory.hpp
supercollider_supercollider/server/supernova/sc/sc_ugen_factory.hpp
// prototype of a supercollider-synthdef-based synth prototype // Copyright (C) 2009 Tim Blechmann // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once #include <boost/intrusive/set.hpp> #include <boost/intrusive/unordered_set.hpp> #include <boost/checked_delete.hpp> #include "sc_synthdef.hpp" #include "sc_synth.hpp" #include "sc_plugin_interface.hpp" #include "SC_InterfaceTable.h" #include "SC_Unit.h" #include "utilities/named_hash_entry.hpp" namespace nova { namespace bi = boost::intrusive; struct sc_unitcmd_def : public named_hash_entry { const UnitCmdFunc func; sc_unitcmd_def(const char* cmd_name, UnitCmdFunc func): named_hash_entry(cmd_name), func(func) {} void run(Unit* unit, struct sc_msg_iter* args) { (func)(unit, args); } }; class sc_ugen_def : public aligned_class, public named_hash_entry { private: const size_t alloc_size; const UnitCtorFunc ctor; const UnitDtorFunc dtor; const uint32_t flags; static const std::size_t unitcmd_set_bucket_count = 4; typedef bi::unordered_set<sc_unitcmd_def, bi::constant_time_size<false>, bi::power_2_buckets<true>, bi::store_hash<true>> unitcmd_set_type; unitcmd_set_type::bucket_type unitcmd_set_buckets[unitcmd_set_bucket_count]; unitcmd_set_type unitcmd_set; public: sc_ugen_def(const char* inUnitClassName, size_t inAllocSize, UnitCtorFunc inCtor, UnitDtorFunc inDtor, uint32 inFlags): named_hash_entry(inUnitClassName), alloc_size(inAllocSize), ctor(inCtor), dtor(inDtor), flags(inFlags), unitcmd_set(unitcmd_set_type::bucket_traits(unitcmd_set_buckets, unitcmd_set_bucket_count)) {} Unit* construct(sc_synthdef::unit_spec_t const& unit_spec, sc_synth* parent, int parentIndex, World* world, linear_allocator& allocator); void initialize(Unit* unit) { (*ctor)(unit); } void destruct(Unit* unit) { if (dtor) (*dtor)(unit); } bool cant_alias(void) const { return flags & kUnitDef_CantAliasInputsToOutputs; } std::size_t memory_requirement(void) const { return alloc_size + 64; // overallocate to allow alignment } bool add_command(const char* cmd_name, UnitCmdFunc func); void run_unit_command(const char* cmd_name, Unit* unit, struct sc_msg_iter* args); }; struct sc_bufgen_def : public named_hash_entry { const BufGenFunc func; sc_bufgen_def(const char* name, BufGenFunc func): named_hash_entry(name), func(func) {} sample* run(World* world, uint32_t buffer_index, struct sc_msg_iter* args); }; struct sc_cmdplugin_def : public named_hash_entry { const PlugInCmdFunc func; void* user_data; sc_cmdplugin_def(const char* name, PlugInCmdFunc func, void* user_data): named_hash_entry(name), func(func), user_data(user_data) {} void run(World* world, struct sc_msg_iter* args, void* replyAddr) { (func)(world, user_data, args, replyAddr); } }; class sc_plugin_container { static const std::size_t ugen_set_bucket_count = 512; typedef bi::unordered_set<sc_ugen_def, bi::constant_time_size<false>, bi::power_2_buckets<true>, bi::store_hash<true>> ugen_set_type; static const std::size_t bufgen_set_bucket_count = 64; typedef bi::unordered_set<sc_bufgen_def, bi::constant_time_size<false>, bi::power_2_buckets<true>, bi::store_hash<true>> bufgen_set_type; static const std::size_t cmdplugin_set_bucket_count = 8; typedef bi::unordered_set<sc_cmdplugin_def, bi::constant_time_size<false>, bi::power_2_buckets<true>, bi::store_hash<true>> cmdplugin_set_type; ugen_set_type::bucket_type ugen_set_buckets[ugen_set_bucket_count]; ugen_set_type ugen_set; bufgen_set_type::bucket_type bufgen_set_buckets[bufgen_set_bucket_count]; bufgen_set_type bufgen_set; cmdplugin_set_type::bucket_type cmdplugin_set_buckets[cmdplugin_set_bucket_count]; cmdplugin_set_type cmdplugin_set; protected: sc_plugin_container(void): ugen_set(ugen_set_type::bucket_traits(ugen_set_buckets, ugen_set_bucket_count)), bufgen_set(bufgen_set_type::bucket_traits(bufgen_set_buckets, bufgen_set_bucket_count)), cmdplugin_set(cmdplugin_set_type::bucket_traits(cmdplugin_set_buckets, cmdplugin_set_bucket_count)) {} ~sc_plugin_container(void) { ugen_set.clear_and_dispose(boost::checked_deleter<sc_ugen_def>()); bufgen_set.clear_and_dispose(boost::checked_deleter<sc_bufgen_def>()); cmdplugin_set.clear_and_dispose(boost::checked_deleter<sc_cmdplugin_def>()); } public: void register_ugen(const char* inUnitClassName, size_t inAllocSize, UnitCtorFunc inCtor, UnitDtorFunc inDtor, uint32 inFlags); void register_bufgen(const char* name, BufGenFunc func); sc_ugen_def* find_ugen(symbol const& name); bool register_ugen_command_function(const char* ugen_name, const char* cmd_name, UnitCmdFunc); bool register_cmd_plugin(const char* cmd_name, PlugInCmdFunc func, void* user_data); sample* run_bufgen(World* world, const char* name, uint32_t buffer_index, struct sc_msg_iter* args); bool run_cmd_plugin(World* world, const char* name, struct sc_msg_iter* args, void* replyAddr); }; /** factory class for supercollider ugens * * \todo do we need to take care of thread safety? */ class sc_ugen_factory : public sc_plugin_interface, public sc_plugin_container { public: sc_ugen_factory() = default; ~sc_ugen_factory(void) { close_handles(); } /* @{ */ /** ugen count handling */ void allocate_ugens(uint32_t count) { ugen_count_ += count; } void free_ugens(uint32_t count) { ugen_count_ -= count; } uint32_t ugen_count(void) const { return ugen_count_; } /* @} */ void load_plugin_folder(std::filesystem::path const& path); void load_plugin(std::filesystem::path const& path); private: void close_handles(void); uint32_t ugen_count_ = 0; std::vector<void*> open_handles; }; extern std::unique_ptr<sc_ugen_factory> sc_factory; } /* namespace nova */
6,940
C++
.h
144
42.604167
116
0.696058
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
34,161
sc_osc_handler.hpp
supercollider_supercollider/server/supernova/sc/sc_osc_handler.hpp
// osc handler for supercollider-style communication // Copyright (C) 2009, 2010 Tim Blechmann // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once #include <algorithm> #include <mutex> #include <vector> #ifndef BOOST_ASIO_HAS_STD_ARRAY # ifdef __clang__ // clang workaround # define BOOST_ASIO_HAS_STD_ARRAY # endif #endif // AppleClang workaround #if defined(__apple_build_version__) && __apple_build_version__ > 10000000 # define BOOST_ASIO_HAS_STD_STRING_VIEW 1 #endif // libc++ workaround #if defined(_LIBCPP_VERSION) && _LIBCPP_VERSION >= 7000 && _LIBCPP_VERSION < 9000 # define BOOST_ASIO_HAS_STD_STRING_VIEW 1 #endif #include <boost/asio/ip/tcp.hpp> #include <boost/enable_shared_from_this.hpp> #include <boost/date_time/microsec_time_clock.hpp> #include <boost/intrusive/treap_set.hpp> #include <boost/endian/arithmetic.hpp> #include "osc/OscReceivedElements.h" #include "../server/memory_pool.hpp" #include "../server/server_args.hpp" #include "../server/server_scheduler.hpp" #include "../utilities/osc_server.hpp" #include "../utilities/sized_array.hpp" #include "../utilities/static_pool.hpp" #include "../utilities/time_tag.hpp" struct FifoMsg; namespace nova { typedef bool (*AsyncStageFn)(World* inWorld, void* cmdData); typedef void (*AsyncFreeFn)(World* inWorld, void* cmdData); namespace detail { using namespace boost::asio; using namespace boost::asio::ip; struct nova_endpoint : public std::enable_shared_from_this<nova_endpoint> { virtual void send(const char* data, size_t length) = 0; }; class udp_endpoint : public nova_endpoint { public: udp_endpoint(udp::endpoint const& ep): endpoint_(ep) {} bool operator==(udp_endpoint const& rhs) const { return endpoint_ == rhs.endpoint_; } private: void send(const char* data, size_t length) override final; udp::endpoint endpoint_; }; typedef std::shared_ptr<nova_endpoint> endpoint_ptr; /** * observer to receive osc notifications * */ class sc_notify_observers { typedef std::vector<endpoint_ptr> observer_vector; public: typedef enum { no_error = 0, already_registered = -1, not_registered = -2 } error_code; sc_notify_observers(boost::asio::io_service& io_service): udp_socket(io_service) {} int add_observer(endpoint_ptr const& ep); int remove_observer(endpoint_ptr const& ep); /* @{ */ /** notifications, should be called from the real-time thread */ void notification_node_started(const server_node* node) { notify("/n_go", node); } void notification_node_ended(const server_node* node) { notify("/n_end", node); } void notification_node_turned_off(const server_node* node) { notify("/n_off", node); } void notification_node_turned_on(const server_node* node) { notify("/n_on", node); } void notification_node_moved(const server_node* node) { notify("/n_move", node); } void send_trigger(int32_t node_id, int32_t trigger_id, float value); void send_node_reply(int32_t node_id, int reply_id, const char* command_name, int argument_count, const float* values); /* @} */ /** send notifications, should not be called from the real-time thread */ void send_notification(const char* data, size_t length); void send_udp(const char* data, size_t size, udp::endpoint const& receiver); static const char* error_string(error_code); private: observer_vector::iterator find(endpoint_ptr const& ep); void notify(const char* address_pattern, const server_node* node) const; void send_notification(const char* data, size_t length, nova_endpoint* endpoint); observer_vector observers; protected: udp::socket udp_socket; std::mutex udp_mutex; }; class sc_scheduled_bundles { public: struct bundle_node : public boost::intrusive::bs_set_base_hook<> { bundle_node(time_tag const& timeout, const char* data, endpoint_ptr const& endpoint): timeout_(timeout), data_(data), endpoint_(endpoint) {} void run(void); const time_tag timeout_; const char* const data_; endpoint_ptr endpoint_; friend bool operator<(const bundle_node& lhs, const bundle_node& rhs) { return priority_order(lhs, rhs); } friend bool priority_order(const bundle_node& lhs, const bundle_node& rhs) { return lhs.timeout_ < rhs.timeout_; // lower value, higher priority } }; typedef boost::intrusive::treap_multiset<bundle_node> bundle_queue_t; void insert_bundle(time_tag const& timeout, const char* data, size_t length, endpoint_ptr const& endpoint); void execute_bundles(time_tag const& last, time_tag const& now); void clear_bundles(void) { bundle_q.clear_and_dispose(dispose_bundle); } static void dispose_bundle(bundle_node* node) { node->~bundle_node(); rt_pool.free(node); } private: bundle_queue_t bundle_q; }; class sc_osc_handler : private detail::network_thread, public sc_notify_observers { /* @{ */ /** constructor helpers */ void open_tcp_acceptor(ip::address address, unsigned int port); void open_udp_socket(ip::address address, unsigned int port); bool open_socket(int protocol, ip::address address, unsigned int port); /* @} */ public: sc_osc_handler(server_arguments const& args): sc_notify_observers(detail::network_thread::io_service_), tcp_acceptor_(detail::network_thread::io_service_), tcp_password_(args.server_password.size() ? args.server_password.c_str() : nullptr) { if (!args.non_rt) { if (args.tcp_port && !open_socket(IPPROTO_TCP, args.socket_address, args.tcp_port)) throw std::runtime_error("cannot open socket"); if (args.udp_port && !open_socket(IPPROTO_UDP, args.socket_address, args.udp_port)) throw std::runtime_error("cannot open socket"); } } void start_receive_thread(void) { detail::network_thread::start_receive(); } typedef osc::ReceivedPacket ReceivedPacket; typedef osc::ReceivedBundle ReceivedBundle; typedef osc::ReceivedMessage ReceivedMessage; class received_packet : public audio_sync_callback { received_packet(const char* dat, size_t length, endpoint_ptr const& endpoint): data(dat), length(length), endpoint_(endpoint) {} void* operator new(std::size_t size, void* ptr) { return ::operator new(size, ptr); } public: static received_packet* alloc_packet(const char* data, size_t length, endpoint_ptr const& remote_endpoint); void run(void) override final; const char* const data; const size_t length; endpoint_ptr endpoint_; }; private: /* @{ */ /** udp socket handling */ void start_receive_udp(); void handle_receive_udp(const boost::system::error_code& error, std::size_t bytes_transferred); /* @} */ /* @{ */ /** tcp connection handling */ public: class tcp_connection : public nova_endpoint { public: using pointer = std::shared_ptr<tcp_connection>; using executor = tcp::socket::executor_type; static pointer create(const executor& executor) { return pointer(new tcp_connection(executor)); } tcp::socket& socket() { return socket_; } void start(sc_osc_handler* self); bool operator==(tcp_connection const& rhs) const { return &rhs == this; } private: tcp_connection(const executor& executor): socket_(executor) {} void send(const char* data, size_t length) override final; void async_read_msg_size(); void handle_message_size(); void handle_message(); tcp::socket socket_; sc_osc_handler* osc_handler; boost::endian::big_int32_t msg_size_; std::vector<char> msg_buffer_; std::mutex socket_mutex_; }; private: void start_tcp_accept(void); void handle_tcp_accept(tcp_connection::pointer new_connection, const boost::system::error_code& error); /* @} */ public: void dumpOSC(int i) { dump_osc_packets = i; } private: int dump_osc_packets = 0; /* @{ */ public: /** \todo how to handle temporary message error suppression? */ void set_error_posting(int val) { error_posting = val; } int get_error_posting() { return error_posting; } private: int error_posting = 1; /* @} */ /* @{ */ /** packet handling */ public: void handle_packet_async(const char* data, size_t length, endpoint_ptr const& endpoint); void handle_packet(const char* data, size_t length, endpoint_ptr const& endpoint); time_tag handle_bundle_nrt(const char* data_, std::size_t length); private: template <bool realtime> void handle_bundle(ReceivedBundle const& bundle, endpoint_ptr const& endpoint); template <bool realtime> void handle_message(ReceivedMessage const& message, size_t msg_size, endpoint_ptr const& endpoint); template <bool realtime> void handle_message_int_address(ReceivedMessage const& message, size_t msg_size, endpoint_ptr const& endpoint); template <bool realtime> void handle_message_sym_address(ReceivedMessage const& message, size_t msg_size, endpoint_ptr const& endpoint); friend struct sc_scheduled_bundles::bundle_node; /* @} */ /* @{ */ /** bundle scheduling */ public: void clear_scheduled_bundles(void) { scheduled_bundles.clear_bundles(); } void execute_scheduled_bundles(void) { scheduled_bundles.execute_bundles(last, now); } void increment_logical_time(time_tag const& diff) { last = now; now += diff; } void set_last_now(time_tag const& lasts, time_tag const& nows) { now = nows; last = lasts; } void add_last_now(time_tag const& add) { now += add; last += add; } void update_time_from_system(void) { now = time_tag::from_ptime(boost::date_time::microsec_clock<boost::posix_time::ptime>::universal_time()); last = now - time_per_tick; } time_tag const& current_time(void) const { return now; } time_tag next_time(void) const { return now + time_per_tick; } sc_scheduled_bundles scheduled_bundles; time_tag now, last; time_tag time_per_tick; /* @} */ void do_asynchronous_command(World* world, void* replyAddr, const char* cmdName, void* cmdData, AsyncStageFn stage2, AsyncStageFn stage3, AsyncStageFn stage4, AsyncFreeFn cleanup, int completionMsgSize, void* completionMsgData) const; void send_message_from_RT(const World* world, FifoMsg& msg) const; void send_message_to_RT(const World* world, FifoMsg& msg) const; bool quit_received = false; private: /* @{ */ udp::endpoint udp_remote_endpoint_; tcp::acceptor tcp_acceptor_; const char* tcp_password_; /* we are not owning this! */ std::array<char, 1 << 15> recv_buffer_; /* @} */ }; } /* namespace detail */ using detail::sc_osc_handler; } /* namespace nova */
11,800
C++
.h
268
38.664179
120
0.681417
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false